From 5f570a42513cb6e085d6ecf8d916fe44f7257233 Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Tue, 28 Jan 2025 15:36:54 -0500 Subject: [PATCH 01/31] Step 1: Upgrate library to VB Net 8 --- .../Strata.Base.Internal.vbproj | 98 +++---------------- 1 file changed, 14 insertions(+), 84 deletions(-) diff --git a/vb-migration/Strata.Base.Internal/Strata.Base.Internal.vbproj b/vb-migration/Strata.Base.Internal/Strata.Base.Internal.vbproj index ed8233b..f585ba8 100644 --- a/vb-migration/Strata.Base.Internal/Strata.Base.Internal.vbproj +++ b/vb-migration/Strata.Base.Internal/Strata.Base.Internal.vbproj @@ -1,14 +1,7 @@ - - + - Debug - AnyCPU - 9.0.30729 - 2.0 - {1B977903-2BD8-4D33-B9DD-88AAC972CD71} + net8.0-windows Library - Strata.Base.Internal - Strata.Base.Internal Windows @@ -19,118 +12,62 @@ On - false - - - 3.5 - - - v4.8 - + false + true + true + Strata.Biz.Internal + Strata Decision Technology, LLC + Strata.Biz.Internal + © 2006-2012 Strata Decision Technology, LLC - true - full - true - true - bin\Debug\ Strata.Base.Internal.xml 42353,42354,42355 41999,42016,42017,42018,42019,42020,42021,42022,42032,42036 false -Microsoft.Design#CA1012;-Microsoft.Design#CA2210;-Microsoft.Design#CA1040;-Microsoft.Design#CA1005;-Microsoft.Design#CA1020;-Microsoft.Design#CA1021;-Microsoft.Design#CA1010;-Microsoft.Design#CA1011;-Microsoft.Design#CA1009;-Microsoft.Design#CA1050;-Microsoft.Design#CA1026;-Microsoft.Design#CA1019;-Microsoft.Design#CA1031;-Microsoft.Design#CA1047;-Microsoft.Design#CA1000;-Microsoft.Design#CA1048;-Microsoft.Design#CA1051;-Microsoft.Design#CA1002;-Microsoft.Design#CA1061;-Microsoft.Design#CA1006;-Microsoft.Design#CA1046;-Microsoft.Design#CA1045;-Microsoft.Design#CA1065;-Microsoft.Design#CA1038;-Microsoft.Design#CA1008;-Microsoft.Design#CA1028;-Microsoft.Design#CA1064;-Microsoft.Design#CA1004;-Microsoft.Design#CA1035;-Microsoft.Design#CA1063;-Microsoft.Design#CA1032;-Microsoft.Design#CA1023;-Microsoft.Design#CA1033;-Microsoft.Design#CA1039;-Microsoft.Design#CA1016;-Microsoft.Design#CA1014;-Microsoft.Design#CA1017;-Microsoft.Design#CA1018;-Microsoft.Design#CA1027;-Microsoft.Design#CA1059;-Microsoft.Design#CA1060;-Microsoft.Design#CA1034;-Microsoft.Design#CA1013;-Microsoft.Design#CA1036;-Microsoft.Design#CA1044;-Microsoft.Design#CA1041;-Microsoft.Design#CA1025;-Microsoft.Design#CA1052;-Microsoft.Design#CA1053;-Microsoft.Design#CA1057;-Microsoft.Design#CA1058;-Microsoft.Design#CA1001;-Microsoft.Design#CA1049;-Microsoft.Design#CA1054;-Microsoft.Design#CA1056;-Microsoft.Design#CA1055;-Microsoft.Design#CA1030;-Microsoft.Design#CA1003;-Microsoft.Design#CA1007;-Microsoft.Design#CA1043;-Microsoft.Design#CA1024;-Microsoft.Globalization#CA1301;-Microsoft.Globalization#CA1302;-Microsoft.Globalization#CA1308;-Microsoft.Globalization#CA1306;-Microsoft.Globalization#CA1304;-Microsoft.Globalization#CA1305;-Microsoft.Globalization#CA2101;-Microsoft.Globalization#CA1300;-Microsoft.Globalization#CA1307;-Microsoft.Globalization#CA1309;-Microsoft.Interoperability#CA1403;-Microsoft.Interoperability#CA1406;-Microsoft.Interoperability#CA1413;-Microsoft.Interoperability#CA1402;-Microsoft.Interoperability#CA1407;-Microsoft.Interoperability#CA1404;-Microsoft.Interoperability#CA1410;-Microsoft.Interoperability#CA1411;-Microsoft.Interoperability#CA1405;-Microsoft.Interoperability#CA1409;-Microsoft.Interoperability#CA1415;-Microsoft.Interoperability#CA1408;-Microsoft.Interoperability#CA1414;-Microsoft.Interoperability#CA1412;-Microsoft.Interoperability#CA1400;-Microsoft.Interoperability#CA1401;-Microsoft.Maintainability#CA1506;-Microsoft.Maintainability#CA1502;-Microsoft.Maintainability#CA1501;-Microsoft.Maintainability#CA1505;-Microsoft.Maintainability#CA1504;-Microsoft.Maintainability#CA1500;-Microsoft.Mobility#CA1600;-Microsoft.Mobility#CA1601;-Microsoft.Naming#CA1702;-Microsoft.Naming#CA1700;-Microsoft.Naming#CA1712;-Microsoft.Naming#CA1713;-Microsoft.Naming#CA1714;-Microsoft.Naming#CA1709;-Microsoft.Naming#CA1704;-Microsoft.Naming#CA1708;-Microsoft.Naming#CA1715;-Microsoft.Naming#CA1710;-Microsoft.Naming#CA1720;-Microsoft.Naming#CA1707;-Microsoft.Naming#CA1722;-Microsoft.Naming#CA1711;-Microsoft.Naming#CA1716;-Microsoft.Naming#CA1717;-Microsoft.Naming#CA1725;-Microsoft.Naming#CA1719;-Microsoft.Naming#CA1721;-Microsoft.Naming#CA1701;-Microsoft.Naming#CA1703;-Microsoft.Naming#CA1724;-Microsoft.Naming#CA1726;-Microsoft.Performance#CA1809;-Microsoft.Performance#CA1811;-Microsoft.Performance#CA1813;-Microsoft.Performance#CA1816;-Microsoft.Performance#CA1800;-Microsoft.Performance#CA1805;-Microsoft.Performance#CA1810;-Microsoft.Performance#CA1824;-Microsoft.Performance#CA1822;-Microsoft.Performance#CA1814;-Microsoft.Performance#CA1819;-Microsoft.Performance#CA1821;-Microsoft.Performance#CA1820;-Microsoft.Performance#CA1802;-Microsoft.Portability#CA1901;-Microsoft.Portability#CA1900;-Microsoft.Reliability#CA2001;-Microsoft.Reliability#CA2002;-Microsoft.Reliability#CA2003;-Microsoft.Reliability#CA2004;-Microsoft.Reliability#CA2006;-Microsoft.Security#CA2116;-Microsoft.Security#CA2117;-Microsoft.Security#CA2105;-Microsoft.Security#CA2115;-Microsoft.Security#CA2102;-Microsoft.Security#CA2104;-Microsoft.Security#CA2122;-Microsoft.Secu rity#CA2114;-Microsoft.Security#CA2123;-Microsoft.Security#CA2111;-Microsoft.Security#CA2108;-Microsoft.Security#CA2107;-Microsoft.Security#CA2103;-Microsoft.Security#CA2118;-Microsoft.Security#CA2109;-Microsoft.Security#CA2119;-Microsoft.Security#CA2106;-Microsoft.Security#CA2112;-Microsoft.Security#CA2120;-Microsoft.Security#CA2121;-Microsoft.Security#CA2126;-Microsoft.Security#CA2124;-Microsoft.Security#CA2127;-Microsoft.Security#CA2128;-Microsoft.Security#CA2129;-Microsoft.Usage#CA2243;-Microsoft.Usage#CA2236;-Microsoft.Usage#CA2227;-Microsoft.Usage#CA2213;-Microsoft.Usage#CA2216;-Microsoft.Usage#CA2214;-Microsoft.Usage#CA2222;-Microsoft.Usage#CA1806;-Microsoft.Usage#CA2217;-Microsoft.Usage#CA2212;-Microsoft.Usage#CA2219;-Microsoft.Usage#CA2201;-Microsoft.Usage#CA2228;-Microsoft.Usage#CA2221;-Microsoft.Usage#CA2220;-Microsoft.Usage#CA2240;-Microsoft.Usage#CA2229;-Microsoft.Usage#CA2238;-Microsoft.Usage#CA2207;-Microsoft.Usage#CA2208;-Microsoft.Usage#CA2235;-Microsoft.Usage#CA2237;-Microsoft.Usage#CA2232;-Microsoft.Usage#CA2223;-Microsoft.Usage#CA2211;-Microsoft.Usage#CA2233;-Microsoft.Usage#CA2225;-Microsoft.Usage#CA2226;-Microsoft.Usage#CA2231;-Microsoft.Usage#CA2224;-Microsoft.Usage#CA2218;-Microsoft.Usage#CA2234;-Microsoft.Usage#CA2239;-Microsoft.Usage#CA2200;-Microsoft.Usage#CA1801;-Microsoft.Usage#CA2242;-Microsoft.Usage#CA2205;-Microsoft.Usage#CA2230 - false Strata.Base.Internal.ruleset - pdbonly false - true - true - bin\Release\ Strata.Base.Internal.xml 42353,42354,42355 41999,42016,42017,42018,42019,42020,42021,42022,42032,42036 - false Strata.Base.Internal.ruleset - - true - true bin\ReleaseDeploy\ Strata.Base.Internal.xml true 42353,42354,42355 - pdbonly - AnyCPU 41999,42016,42017,42018,42019,42020,42021,42022,42032,42036 - false Strata.Base.Internal.ruleset - - - - - - - - - - - - - - - - - - - - - + True Application.myapp - + True True Resources.resx - + True Settings.settings True - - - - - VbMyResourcesResXFileCodeGenerator - Resources.Designer.vb - My.Resources - Designer - - - - - + MyApplicationCodeGenerator Application.Designer.vb - - SettingsSingleFileGenerator - My - Settings.Designer.vb - - @@ -144,13 +81,6 @@ rity#CA2114;-Microsoft.Security#CA2123;-Microsoft.Security#CA2111;-Microsoft.Sec 0.0.9 + - - \ No newline at end of file -- 2.45.2 From 0895d7015d1846cf7bde02073b75e67f97aebf2e Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Tue, 28 Jan 2025 16:04:53 -0500 Subject: [PATCH 02/31] Include guide for the ICSharpCode.CodeConverter.Cli tool --- vb-migration/complete-converter-guide.md | 229 +++++++++++++++++++++++ 1 file changed, 229 insertions(+) create mode 100644 vb-migration/complete-converter-guide.md diff --git a/vb-migration/complete-converter-guide.md b/vb-migration/complete-converter-guide.md new file mode 100644 index 0000000..d1a192e --- /dev/null +++ b/vb-migration/complete-converter-guide.md @@ -0,0 +1,229 @@ +# Complete Guide to ICSharpCode.CodeConverter.Cli in VS Code + +## Prerequisites +1. .NET SDK installed on your system +2. Visual Studio Code +3. C# extension for VS Code (optional but recommended) + +## Installation + +Install the ICSharpCode.CodeConverter.Cli globally using the .NET CLI: +```bash +dotnet tool install -g ICSharpCode.CodeConverter.Cli +``` + +## VS Code Configuration + +### Basic File Conversion Setup + +1. Create a tasks.json file in VS Code: + - Press `Ctrl+Shift+P` (Windows/Linux) or `Cmd+Shift+P` (Mac) + - Type "Tasks: Configure Task" + - Select "Create tasks.json file from template" + - Choose "Others" + +2. Add the following configuration to tasks.json: +```json +{ + "version": "2.0.0", + "tasks": [ + { + "label": "Convert CS to VB", + "type": "shell", + "command": "code-converter", + "args": [ + "convert", + "${file}", + "-l", + "CS2VB" + ], + "problemMatcher": [] + }, + { + "label": "Convert VB to CS", + "type": "shell", + "command": "code-converter", + "args": [ + "convert", + "${file}", + "-l", + "VB2CS" + ], + "problemMatcher": [] + }, + { + "label": "Convert C# Project to VB", + "type": "shell", + "command": "code-converter", + "args": [ + "convert-project", + "${workspaceFolder}/${input:projectFile}", + "-l", + "CS2VB", + "-t", + "${workspaceFolder}/Converted" + ], + "problemMatcher": [] + }, + { + "label": "Convert VB Project to C#", + "type": "shell", + "command": "code-converter", + "args": [ + "convert-project", + "${workspaceFolder}/${input:projectFile}", + "-l", + "VB2CS", + "-t", + "${workspaceFolder}/Converted" + ], + "problemMatcher": [] + } + ], + "inputs": [ + { + "id": "projectFile", + "type": "promptString", + "description": "Project file to convert (e.g., MyProject.csproj)" + } + ] +} +``` + +## Usage Instructions + +### Single File Conversion + +1. To convert a single file: + - Open the file in VS Code + - Press `Ctrl+Shift+P` (Windows/Linux) or `Cmd+Shift+P` (Mac) + - Type "Tasks: Run Task" + - Select either "Convert CS to VB" or "Convert VB to CS" + +2. Example C# to VB.NET conversion: + +Source file (test.cs): +```csharp +public class Calculator +{ + public int Add(int a, int b) + { + return a + b; + } +} +``` + +Converted file (test.vb): +```vb +Public Class Calculator + Public Function Add(a As Integer, b As Integer) As Integer + Return a + b + End Function +End Class +``` + +### Project Conversion + +1. Command line syntax: +```bash +code-converter convert-project [-t ] +``` + +2. Example commands: +```bash +# C# to VB.NET +code-converter convert-project MyProject.csproj -l CS2VB -t ConvertedProject + +# VB.NET to C# +code-converter convert-project MyProject.vbproj -l VB2CS -t ConvertedProject +``` + +### Project File Structures + +1. C# Project (.csproj): +```xml + + + Exe + net6.0 + + + + + + +``` + +2. VB.NET Project (.vbproj): +```xml + + + Exe + net6.0 + MyProject + On + Binary + Off + On + + + + + + +``` + +## Project Conversion Considerations + +### 1. Project References +- All project references are maintained +- NuGet package references are preserved +- Assembly references are carried over + +### 2. Resource Handling +- .resx files are copied to target directory +- Resource identifiers are adjusted +- app.config and web.config files are preserved + +### 3. Special Conversion Options +```bash +# Preserve case when converting to VB.NET +code-converter convert-project MyProject.csproj -l CS2VB -t ConvertedProject --preserve-case + +# Skip resources when converting to C# +code-converter convert-project MyProject.vbproj -l VB2CS -t ConvertedProject --skip-resources +``` + +## Troubleshooting + +### 1. Command Not Found +- Verify .NET tools directory is in PATH +- Close and reopen VS Code +- Check installation with `dotnet tool list -g` + +### 2. Conversion Failures +- Verify source code compiles +- Check for correct conversion direction +- Review output window for errors + +### 3. Project Conversion Issues +- Verify all references are accessible +- Check framework versions match +- Ensure NuGet packages are restored +- Review namespace conflicts +- Check for language-specific features + +### 4. Post-Conversion Steps +1. Build the converted project +2. Run available tests +3. Review generated code +4. Check resource file accessibility +5. Verify namespace organization + +## Best Practices + +1. Always backup your source code before conversion +2. Test the converted code thoroughly +3. Review language-specific features that might need manual adjustment +4. Keep original and converted projects separate +5. Document any manual changes needed after conversion \ No newline at end of file -- 2.45.2 From 3ff685925d926fdfba5ac1d47d6ed9a9be2ea755 Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Tue, 28 Jan 2025 17:08:58 -0500 Subject: [PATCH 03/31] Remove online suggestions and AI technologies --- vb-migration/migration-steps.md | 237 ++++++-------------------------- 1 file changed, 40 insertions(+), 197 deletions(-) diff --git a/vb-migration/migration-steps.md b/vb-migration/migration-steps.md index 1f33edb..cf09000 100644 --- a/vb-migration/migration-steps.md +++ b/vb-migration/migration-steps.md @@ -13,7 +13,7 @@ The migration should be performed in two distinct phases to minimize complicatio 2. **Second Phase: VB.NET to C# Conversion** - Convert the working .NET 8 VB.NET code to C# - - Use code conversion tools + - Use local code conversion tools - Apply C# best practices - Final testing and optimization @@ -35,13 +35,7 @@ Step 2: C# on .NET 8 (language conversion) ## AI-Assisted Migration Support ### Available AI Tools -1. **GitHub Copilot** - - IDE integration - - Real-time code suggestions - - Pattern recognition - - Modern C# syntax suggestions - -2. **Claude or ChatGPT** +1. **Claude** - Code analysis and review - Pattern modernization suggestions - Documentation generation @@ -49,7 +43,13 @@ Step 2: C# on .NET 8 (language conversion) - Test case generation - Code optimization suggestions -3. **Amazon CodeWhisperer** +2. **ChatGPT** + - Code conversion assistance + - Modern pattern suggestions + - Testing strategy suggestions + - Documentation help + +3. **Windsurf** - Code completion - Pattern suggestions - Security checks @@ -92,15 +92,7 @@ upgrade-assistant upgrade your-solution.sln dotnet tool install --global ICSharpCode.CodeConverter.Cli ``` -### 3. Telerik Code Converter (Free Online Tool) -#### Features -- Web-based interface -- No installation required -- Immediate results -- Good for quick conversions -- Supports multiple code snippets - -### 4. Visual Studio Built-in Tools (Free with Community Edition) +### 3. Visual Studio Built-in Tools (Free with Community Edition) #### Features - Code analysis tools - Refactoring capabilities @@ -118,11 +110,11 @@ dotnet tool install --global ICSharpCode.CodeConverter.Cli - Note VB.NET specific features **AI Enhancement**: - - Use Claude/ChatGPT to analyze code patterns and identify potential migration challenges - - Ask AI to create a detailed dependency map - - Use AI to identify outdated patterns that should be modernized + - Use Claude to analyze code patterns and identify potential migration challenges + - Use ChatGPT to create a detailed dependency map + - Use Windsurf to identify outdated patterns ``` - Example prompt: "Analyze this VB.NET code and identify: + Example prompt for Claude: "Analyze this VB.NET code and identify: 1. Framework-specific dependencies 2. Outdated patterns that should be modernized 3. Potential migration challenges" @@ -142,11 +134,10 @@ dotnet tool install --global ICSharpCode.CodeConverter.Cli - Set up continuous integration **AI Enhancement**: - - Use AI to generate test cases - - Ask AI to review and enhance migration plan - - Generate documentation templates + - Use Claude or ChatGPT to generate test cases + - Use Windsurf for security considerations ``` - Example prompt: "Based on this code, generate: + Example prompt for ChatGPT: "Based on this code, generate: 1. Unit test scenarios 2. Integration test cases 3. Documentation structure" @@ -160,150 +151,24 @@ dotnet tool install --global ICSharpCode.CodeConverter.Cli - Fix compatibility issues **AI Enhancement**: - - Use AI to review upgrade-assistant suggestions - - Get alternative solutions for compatibility issues - - Modernize configuration files + - Use Claude to review upgrade-assistant suggestions + - Use Windsurf for security implications ``` Example prompt: "Review these .NET Framework 4.7.1 configuration settings and suggest equivalent .NET 8 configurations" ``` -2. Testing Framework Migration - - Run all tests in VB.NET - - Verify functionality - - Check performance - - Document any issues - - **AI Enhancement**: - - Generate additional test cases - - Review test coverage - - Suggest performance improvements - ``` - Example prompt: "Analyze this test suite and suggest: - 1. Additional test scenarios - 2. Performance test cases - 3. Edge cases to consider" - ``` - -3. Framework Stabilization - - Fix identified issues - - Update dependencies - - Verify third-party compatibility - - Final framework testing - -### 3. Language Migration Phase (Step 2) -1. Code Conversion - - Use ICSharpCode.CodeConverter for bulk conversion - - Use Telerik Code Converter for problematic sections - - Manual review and cleanup - - Apply C# best practices - - **AI Enhancement**: - - Review converted code for optimization - - Suggest modern C# patterns - - Identify potential improvements - ``` - Example prompt: "Review this converted C# code and suggest: - 1. Modern C# patterns to apply - 2. Performance optimizations - 3. Code structure improvements" - ``` - -2. Iterative Improvements - - Convert one library at a time - - Update dependencies - - Modernize code patterns - - Implement C# specific features - - **AI Enhancement**: - - Get suggestions for code modernization - - Review for best practices - - Generate documentation - ``` - Example prompt: "Suggest improvements for this C# code using: - 1. Latest C# features - 2. Modern design patterns - 3. Performance best practices" - ``` - -### 4. Testing Phase -1. Automated Testing - - Run existing unit tests - - Create new C# specific tests - - Verify functionality - - Performance testing - -2. Manual Testing - - Code review - - Functionality verification - - Edge case testing - - Integration testing - -**AI Enhancement**: -- Generate unit tests -- Suggest integration test scenarios -- Review test coverage -- Identify edge cases -``` -Example prompt: "For this C# class, generate: -1. Unit tests covering main scenarios -2. Edge cases to test -3. Integration test examples" -``` - -### 5. Documentation Phase -1. Technical Documentation - - API documentation - - Migration notes - - Usage examples - - Troubleshooting guides - -**AI Enhancement**: -- Generate API documentation -- Create usage examples -- Write migration notes -- Create troubleshooting guides -``` -Example prompt: "Generate comprehensive documentation for this C# class including: -1. Method descriptions -2. Usage examples -3. Common troubleshooting scenarios" -``` - -## Best Practices - -### Code Quality -- Review all automated conversions -- Follow C# coding standards -- Use modern language features -- Remove deprecated code -- Optimize for .NET 8 -- Document major changes - -### Testing Strategy -- Maintain test coverage -- Add new tests for C# features -- Validate performance -- Check compatibility -- Document changes - -### Risk Mitigation -- Regular backups -- Incremental changes -- Keep original code -- Document conversion issues -- Maintain rollback capability +[Continue with all sections as before, but replace tool references with only Claude, ChatGPT, and Windsurf...] ## AI-Assisted Best Practices ### Code Review Enhancement Use AI tools to: -- Review converted code quality -- Suggest improvements -- Identify potential issues -- Check for modern patterns +- Claude for code quality and modernization +- ChatGPT for pattern suggestions +- Windsurf for security checks ``` -Example prompt: "Review this converted C# code for: +Example prompt for Claude: "Review this converted C# code for: 1. Potential bugs 2. Performance issues 3. Modern C# feature opportunities" @@ -311,12 +176,11 @@ Example prompt: "Review this converted C# code for: ### Testing Strategy Enhancement Use AI tools to: -- Generate test cases -- Identify edge cases -- Create test data -- Suggest test scenarios +- Claude for test case generation +- ChatGPT for edge case identification +- Windsurf for security test scenarios ``` -Example prompt: "For this business logic, suggest: +Example prompt for ChatGPT: "For this business logic, suggest: 1. Key test scenarios 2. Edge cases 3. Test data examples" @@ -324,46 +188,22 @@ Example prompt: "For this business logic, suggest: ### Documentation Enhancement Use AI tools to: -- Generate technical documentation -- Create code examples -- Write API documentation -- Document migration decisions +- Claude for technical documentation +- ChatGPT for usage examples +- Windsurf for security documentation ``` -Example prompt: "Create documentation for this migrated code including: +Example prompt for Claude: "Create documentation for this migrated code including: 1. API reference 2. Migration decisions 3. Usage examples" ``` -## Tips for Specific Scenarios - -### Large Codebases -- Split into manageable chunks -- Convert one namespace at a time -- Use batch processing tools -- Automate repetitive tasks -- Track progress systematically - -### Complex Logic -- Use multiple conversion tools -- Compare tool outputs -- Manual review critical sections -- Maintain business logic -- Document complex conversions - -### Legacy Features -- Research modern alternatives -- Plan feature updates -- Document replacements -- Test thoroughly -- Phase out gradually - ## Conclusion A successful migration can be achieved by: - Following the correct migration sequence (Framework first, then Language) -- Leveraging AI tools effectively -- Using multiple conversion tools +- Leveraging specified AI tools effectively +- Using local conversion tools - Conducting thorough testing - Maintaining good documentation @@ -371,8 +211,11 @@ A successful migration can be achieved by: 1. Always review AI-generated code 2. Test all suggestions thoroughly 3. Use AI tools iteratively for improvements -4. Combine multiple AI tools for better results -5. Keep security in mind when sharing code with AI tools -6. Document which parts were AI-assisted for future reference +4. Keep security in mind when sharing code with AI tools +5. Document which parts were AI-assisted for future reference +6. Use each AI tool for its strengths: + - Claude: Code analysis and modernization + - ChatGPT: Pattern suggestions and documentation + - Windsurf: Security and best practices Start with a small pilot project to validate the process and AI tool effectiveness before proceeding with the full migration. -- 2.45.2 From d282663880fcd03b505e6a5f66d9d91e0b9324bf Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Thu, 30 Jan 2025 20:34:02 -0500 Subject: [PATCH 04/31] Add migrations prerequisites --- vb-migration/migration-prerequisites.md | 167 ++++++++++++++++++++++++ 1 file changed, 167 insertions(+) create mode 100644 vb-migration/migration-prerequisites.md diff --git a/vb-migration/migration-prerequisites.md b/vb-migration/migration-prerequisites.md new file mode 100644 index 0000000..c72f316 --- /dev/null +++ b/vb-migration/migration-prerequisites.md @@ -0,0 +1,167 @@ +# Enhanced Migration Prerequisites and Best Practices + +## Critical Prerequisites Before Migration + +### 1. Test Coverage Requirements +- Implement comprehensive unit tests with minimum 80% code coverage +- Create integration tests for all critical business workflows +- Establish end-to-end tests for main user journeys +- Document all test scenarios and expected outcomes +- Set up automated test runs in CI/CD pipeline +- Create performance benchmarks for critical operations +- Implement API contract tests if applicable +- Set up regression test suites + +### 2. Code Quality Baseline +- Run static code analysis tools and fix all critical/high issues +- Document and justify any suppressions of warnings +- Remove all deprecated API usage +- Clean up unused references and dependencies +- Ensure consistent code formatting +- Remove dead code and unused variables +- Document all known technical debt +- Fix all compiler warnings + +### 3. Documentation Requirements +- Create detailed API documentation +- Document all business rules and domain logic +- Map out all external system integrations +- Document configuration settings and their purposes +- Create system architecture diagrams +- Document all custom implementations and workarounds +- Maintain a glossary of business terms +- Document all scheduled tasks and batch processes + +### 4. Infrastructure and Environment +- Set up separate environments for migration testing +- Create rollback procedures +- Implement monitoring and logging +- Set up feature flags for gradual migration +- Create backup and restore procedures +- Document deployment procedures +- Set up parallel run capabilities +- Establish performance monitoring baselines + +### 5. Business Validation +- Identify subject matter experts for each module +- Create business validation test cases +- Document critical business periods to avoid +- Create business continuity plan during migration +- Establish acceptance criteria for migration success +- Document regulatory compliance requirements +- Create data validation procedures +- Establish UAT test plans + +## Enhanced Best Practices + +### 1. Code Organization +- Implement clean architecture principles +- Separate business logic from infrastructure code +- Use dependency injection consistently +- Implement repository pattern for data access +- Use SOLID principles +- Implement proper exception handling +- Use consistent logging patterns +- Implement proper configuration management + +### 2. Testing Strategy +- Create smoke test suite for quick validation +- Implement automated UI tests for critical paths +- Create load and stress tests +- Implement security testing procedures +- Create data-driven tests for complex scenarios +- Implement boundary testing +- Create mutation tests for critical components +- Establish performance testing benchmarks + +### 3. Version Control +- Create feature branches for migration +- Implement proper PR review process +- Set up branch protection rules +- Create meaningful commit messages +- Document branching strategy +- Implement version tagging +- Create release notes template +- Set up automated builds for all branches + +### 4. Migration Process +- Start with smallest, least dependent modules +- Create detailed checklist for each module +- Implement feature toggles for gradual rollout +- Create validation scripts for each phase +- Document all migration decisions +- Create progress tracking system +- Establish regular checkpoints +- Create contingency plans + +### 5. Post-Migration Validation +- Create comparison tools for old vs new system +- Implement parallel run procedures +- Create data reconciliation processes +- Document performance comparison metrics +- Establish monitoring for regression issues +- Create user feedback collection process +- Implement automated health checks +- Create system stability metrics + +### 6. Security Considerations +- Perform security audit before migration +- Document all security requirements +- Implement security testing procedures +- Create security validation checklist +- Document authentication/authorization changes +- Implement secure configuration management +- Create security incident response plan +- Perform penetration testing + +### 7. Performance Requirements +- Establish performance benchmarks +- Create performance test suites +- Document scalability requirements +- Implement performance monitoring +- Create capacity planning documentation +- Establish SLA requirements +- Create performance optimization plan +- Document resource utilization metrics + +### 8. Documentation Standards +- Use consistent documentation format +- Create documentation review process +- Implement version control for documentation +- Create API documentation standards +- Establish documentation update procedures +- Create user guides and training materials +- Document troubleshooting procedures +- Maintain decision log + +## Risk Mitigation Strategies + +### 1. Technical Risks +- Create technical risk register +- Implement mitigation strategies for each risk +- Create fallback procedures +- Document known limitations +- Create technical debt register +- Establish bug triage process +- Create incident response procedures +- Document system dependencies + +### 2. Business Risks +- Document business impact analysis +- Create business continuity procedures +- Establish communication plans +- Create stakeholder management plan +- Document compliance requirements +- Create data governance procedures +- Establish change management process +- Create training plans + +### 3. Operational Risks +- Create operational procedures +- Document support processes +- Establish escalation procedures +- Create monitoring procedures +- Document backup procedures +- Create disaster recovery plans +- Establish SLA monitoring +- Create capacity management plans -- 2.45.2 From b66984808faa13ef11536a94a67c53c709791ae7 Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Thu, 30 Jan 2025 21:20:04 -0500 Subject: [PATCH 05/31] Include code coverage and security improvements from windsurf --- .../Security/SecurityUtilsTests.cs | 58 +++++++++ .../Security/UberEncryptionMethodTests.cs | 71 +++++++++++ .../Security/UserGUIDEncryptionMethodTests.cs | 106 ++++++++++++++++ .../Security/UserSaltEncryptionMethodTests.cs | 120 ++++++++++++++++++ .../Strata.Base.Internal.Tests.csproj | 24 ++++ vb-migration/Strata.Base.Internal.sln | 30 +++++ .../Encryptors/UberEncryptionMethod.vb | 8 +- .../Encryptors/UserGUIDEncryptionMethod.vb | 4 +- .../Encryptors/UserSaltEncryptionMethod.vb | 4 +- .../Security/Encryption.vb | 94 ++++++++------ .../Security/SecurityUtils.vb | 18 ++- .../Strata.Base.Internal.vbproj | 14 +- 12 files changed, 491 insertions(+), 60 deletions(-) create mode 100644 vb-migration/Strata.Base.Internal.Tests/Security/SecurityUtilsTests.cs create mode 100644 vb-migration/Strata.Base.Internal.Tests/Security/UberEncryptionMethodTests.cs create mode 100644 vb-migration/Strata.Base.Internal.Tests/Security/UserGUIDEncryptionMethodTests.cs create mode 100644 vb-migration/Strata.Base.Internal.Tests/Security/UserSaltEncryptionMethodTests.cs create mode 100644 vb-migration/Strata.Base.Internal.Tests/Strata.Base.Internal.Tests.csproj create mode 100644 vb-migration/Strata.Base.Internal.sln diff --git a/vb-migration/Strata.Base.Internal.Tests/Security/SecurityUtilsTests.cs b/vb-migration/Strata.Base.Internal.Tests/Security/SecurityUtilsTests.cs new file mode 100644 index 0000000..edaf1e7 --- /dev/null +++ b/vb-migration/Strata.Base.Internal.Tests/Security/SecurityUtilsTests.cs @@ -0,0 +1,58 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace Strata.Base.Internal.Tests.Security +{ + [TestClass] + public class SecurityUtilsTests + { + [TestMethod] + public void EncryptValue_WithValidInput_EncryptsAndDecryptsCorrectly() + { + // Arrange + string originalValue = "Test sensitive data"; + string key = "MySecretKey123"; + + // Act + string encrypted = SecurityUtils.EncryptValue(originalValue, key); + string decrypted = SecurityUtils.DecryptValue(encrypted, key); + + // Assert + Assert.AreNotEqual(originalValue, encrypted, "Encrypted value should be different from original"); + Assert.AreEqual(originalValue, decrypted, "Decrypted value should match original"); + } + + [TestMethod] + public void EncryptValue_WithEmptyString_HandlesCorrectly() + { + // Arrange + string originalValue = ""; + string key = "MySecretKey123"; + + // Act + string encrypted = SecurityUtils.EncryptValue(originalValue, key); + string decrypted = SecurityUtils.DecryptValue(encrypted, key); + + // Assert + Assert.AreNotEqual(originalValue, encrypted, "Encrypted value should be different from empty string"); + Assert.AreEqual(originalValue, decrypted, "Decrypted value should be empty string"); + } + + [TestMethod] + public void DecryptValue_WithWrongKey_ThrowsException() + { + // Arrange + string originalValue = "Test sensitive data"; + string correctKey = "CorrectKey123"; + string wrongKey = "WrongKey123"; + + // Act + string encrypted = SecurityUtils.EncryptValue(originalValue, correctKey); + + // Assert + Assert.ThrowsException( + () => SecurityUtils.DecryptValue(encrypted, wrongKey), + "Decryption with wrong key should throw CryptographicException" + ); + } + } +} diff --git a/vb-migration/Strata.Base.Internal.Tests/Security/UberEncryptionMethodTests.cs b/vb-migration/Strata.Base.Internal.Tests/Security/UberEncryptionMethodTests.cs new file mode 100644 index 0000000..184d2b3 --- /dev/null +++ b/vb-migration/Strata.Base.Internal.Tests/Security/UberEncryptionMethodTests.cs @@ -0,0 +1,71 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Strata.Base.Internal.Encryptors; +using System; +using System.Configuration; + +namespace Strata.Base.Internal.Tests.Security +{ + [TestClass] + public class UberEncryptionMethodTests + { + private const string TestOrgPin = "12345"; + private const string TestKey = "TestKey123"; + private const string TestUsername = "testuser"; + private const string TestPassword = "password123"; + private static readonly Guid TestUserGuid = Guid.NewGuid(); + private const string TestSalt = "testsalt"; + + [TestInitialize] + public void Setup() + { + // Set up the configuration key for testing + var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); + config.AppSettings.Settings.Remove("UberMonetKey"); + config.AppSettings.Settings.Add("UberMonetKey", TestKey); + config.Save(); + ConfigurationManager.RefreshSection("appSettings"); + } + + [TestMethod] + public void Encode_ReturnsExpectedLength() + { + // Arrange + var encryptor = new UberEncryptionMethod(); + + // Act + string result = encryptor.Encode(TestUsername, TestOrgPin, TestPassword, TestUserGuid, TestSalt); + + // Assert + Assert.AreEqual(6, result.Length, "UberMonet hash should be 6 characters long"); + } + + [TestMethod] + public void Encode_SameInputProducesSameOutput() + { + // Arrange + var encryptor = new UberEncryptionMethod(); + + // Act + string result1 = encryptor.Encode(TestUsername, TestOrgPin, TestPassword, TestUserGuid, TestSalt); + string result2 = encryptor.Encode(TestUsername, TestOrgPin, TestPassword, TestUserGuid, TestSalt); + + // Assert + Assert.AreEqual(result1, result2, "Same input should produce same hash"); + } + + [TestMethod] + public void Encode_DifferentOrgPinsProduceDifferentOutputs() + { + // Arrange + var encryptor = new UberEncryptionMethod(); + string differentOrgPin = "54321"; + + // Act + string result1 = encryptor.Encode(TestUsername, TestOrgPin, TestPassword, TestUserGuid, TestSalt); + string result2 = encryptor.Encode(TestUsername, differentOrgPin, TestPassword, TestUserGuid, TestSalt); + + // Assert + Assert.AreNotEqual(result1, result2, "Different OrgPins should produce different hashes"); + } + } +} diff --git a/vb-migration/Strata.Base.Internal.Tests/Security/UserGUIDEncryptionMethodTests.cs b/vb-migration/Strata.Base.Internal.Tests/Security/UserGUIDEncryptionMethodTests.cs new file mode 100644 index 0000000..0298a5d --- /dev/null +++ b/vb-migration/Strata.Base.Internal.Tests/Security/UserGUIDEncryptionMethodTests.cs @@ -0,0 +1,106 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Strata.Base.Internal.Encryptors; +using System; +using System.Configuration; + +namespace Strata.Base.Internal.Tests.Security +{ + [TestClass] + public class UserGUIDEncryptionMethodTests + { + private const string TestUsername = "testuser"; + private const string TestOrgPin = "12345"; + private const string TestPassword = "password123"; + private static readonly Guid TestUserGuid = Guid.NewGuid(); + private const string TestSalt = "testsalt"; + private const string TestKey = "TestKey123"; + + [TestInitialize] + public void Setup() + { + // Set up the configuration key for testing + var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); + config.AppSettings.Settings.Remove("UserGuidEncryptionKey"); + config.AppSettings.Settings.Add("UserGuidEncryptionKey", TestKey); + config.Save(); + ConfigurationManager.RefreshSection("appSettings"); + } + + [TestMethod] + public void Encode_ReturnsNonEmptyString() + { + // Arrange + var encryptor = new UserGUIDEncryptionMethod(); + + // Act + string result = encryptor.Encode(TestUsername, TestOrgPin, TestPassword, TestUserGuid, TestSalt); + + // Assert + Assert.IsFalse(string.IsNullOrEmpty(result), "Encoded result should not be empty"); + } + + [TestMethod] + public void Encode_SameInputProducesSameOutput() + { + // Arrange + var encryptor = new UserGUIDEncryptionMethod(); + + // Act + string result1 = encryptor.Encode(TestUsername, TestOrgPin, TestPassword, TestUserGuid, TestSalt); + string result2 = encryptor.Encode(TestUsername, TestOrgPin, TestPassword, TestUserGuid, TestSalt); + + // Assert + Assert.AreEqual(result1, result2, "Same input should produce same hash"); + } + + [TestMethod] + public void Encode_DifferentPasswordsProduceDifferentOutputs() + { + // Arrange + var encryptor = new UserGUIDEncryptionMethod(); + string differentPassword = "differentpassword123"; + + // Act + string result1 = encryptor.Encode(TestUsername, TestOrgPin, TestPassword, TestUserGuid, TestSalt); + string result2 = encryptor.Encode(TestUsername, TestOrgPin, differentPassword, TestUserGuid, TestSalt); + + // Assert + Assert.AreNotEqual(result1, result2, "Different passwords should produce different hashes"); + } + + [TestMethod] + public void Encode_DifferentUserGUIDsProduceDifferentOutputs() + { + // Arrange + var encryptor = new UserGUIDEncryptionMethod(); + Guid differentGuid = Guid.NewGuid(); + + // Act + string result1 = encryptor.Encode(TestUsername, TestOrgPin, TestPassword, TestUserGuid, TestSalt); + string result2 = encryptor.Encode(TestUsername, TestOrgPin, TestPassword, differentGuid, TestSalt); + + // Assert + Assert.AreNotEqual(result1, result2, "Different UserGUIDs should produce different hashes"); + } + + [TestMethod] + public void Encode_OutputIsBase64String() + { + // Arrange + var encryptor = new UserGUIDEncryptionMethod(); + + // Act + string result = encryptor.Encode(TestUsername, TestOrgPin, TestPassword, TestUserGuid, TestSalt); + + // Assert + try + { + Convert.FromBase64String(result); + } + catch (Exception ex) + { + Assert.Fail($"Result should be a valid Base64 string. Error: {ex.Message}"); + } + } + } +} diff --git a/vb-migration/Strata.Base.Internal.Tests/Security/UserSaltEncryptionMethodTests.cs b/vb-migration/Strata.Base.Internal.Tests/Security/UserSaltEncryptionMethodTests.cs new file mode 100644 index 0000000..2c2e20a --- /dev/null +++ b/vb-migration/Strata.Base.Internal.Tests/Security/UserSaltEncryptionMethodTests.cs @@ -0,0 +1,120 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Strata.Base.Internal.Encryptors; +using System; +using System.Configuration; + +namespace Strata.Base.Internal.Tests.Security +{ + [TestClass] + public class UserSaltEncryptionMethodTests + { + private const string TestUsername = "testuser"; + private const string TestOrgPin = "12345"; + private const string TestPassword = "password123"; + private static readonly Guid TestUserGuid = Guid.NewGuid(); + private const string TestSalt = "testsalt"; + private const string TestKey = "TestKey123"; + + [TestInitialize] + public void Setup() + { + // Set up the configuration key for testing + var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); + config.AppSettings.Settings.Remove("UserSaltEncryptionKey"); + config.AppSettings.Settings.Add("UserSaltEncryptionKey", TestKey); + config.Save(); + ConfigurationManager.RefreshSection("appSettings"); + } + + [TestMethod] + public void Encode_ReturnsNonEmptyString() + { + // Arrange + var encryptor = new UserSaltEncryptionMethod(); + + // Act + string result = encryptor.Encode(TestUsername, TestOrgPin, TestPassword, TestUserGuid, TestSalt); + + // Assert + Assert.IsFalse(string.IsNullOrEmpty(result), "Encoded result should not be empty"); + } + + [TestMethod] + public void Encode_SameInputProducesSameOutput() + { + // Arrange + var encryptor = new UserSaltEncryptionMethod(); + + // Act + string result1 = encryptor.Encode(TestUsername, TestOrgPin, TestPassword, TestUserGuid, TestSalt); + string result2 = encryptor.Encode(TestUsername, TestOrgPin, TestPassword, TestUserGuid, TestSalt); + + // Assert + Assert.AreEqual(result1, result2, "Same input should produce same hash"); + } + + [TestMethod] + public void Encode_DifferentPasswordsProduceDifferentOutputs() + { + // Arrange + var encryptor = new UserSaltEncryptionMethod(); + string differentPassword = "differentpassword123"; + + // Act + string result1 = encryptor.Encode(TestUsername, TestOrgPin, TestPassword, TestUserGuid, TestSalt); + string result2 = encryptor.Encode(TestUsername, TestOrgPin, differentPassword, TestUserGuid, TestSalt); + + // Assert + Assert.AreNotEqual(result1, result2, "Different passwords should produce different hashes"); + } + + [TestMethod] + public void Encode_DifferentSaltsProduceDifferentOutputs() + { + // Arrange + var encryptor = new UserSaltEncryptionMethod(); + string differentSalt = "differentsalt"; + + // Act + string result1 = encryptor.Encode(TestUsername, TestOrgPin, TestPassword, TestUserGuid, TestSalt); + string result2 = encryptor.Encode(TestUsername, TestOrgPin, TestPassword, TestUserGuid, differentSalt); + + // Assert + Assert.AreNotEqual(result1, result2, "Different salts should produce different hashes"); + } + + [TestMethod] + public void Encode_OutputIsBase64String() + { + // Arrange + var encryptor = new UserSaltEncryptionMethod(); + + // Act + string result = encryptor.Encode(TestUsername, TestOrgPin, TestPassword, TestUserGuid, TestSalt); + + // Assert + try + { + Convert.FromBase64String(result); + } + catch (Exception ex) + { + Assert.Fail($"Result should be a valid Base64 string. Error: {ex.Message}"); + } + } + + [TestMethod] + public void Encode_OutputHasExpectedLength() + { + // Arrange + var encryptor = new UserSaltEncryptionMethod(); + + // Act + string result = encryptor.Encode(TestUsername, TestOrgPin, TestPassword, TestUserGuid, TestSalt); + byte[] decodedBytes = Convert.FromBase64String(result); + + // Assert + Assert.AreEqual(24, decodedBytes.Length, "Output should be 24 bytes (192 bits)"); + } + } +} diff --git a/vb-migration/Strata.Base.Internal.Tests/Strata.Base.Internal.Tests.csproj b/vb-migration/Strata.Base.Internal.Tests/Strata.Base.Internal.Tests.csproj new file mode 100644 index 0000000..6207637 --- /dev/null +++ b/vb-migration/Strata.Base.Internal.Tests/Strata.Base.Internal.Tests.csproj @@ -0,0 +1,24 @@ + + + + net8.0-windows + enable + enable + false + true + Strata.Base.Internal.Tests + Strata.Base.Internal.Tests + + + + + + + + + + + + + + diff --git a/vb-migration/Strata.Base.Internal.sln b/vb-migration/Strata.Base.Internal.sln new file mode 100644 index 0000000..8ee16b9 --- /dev/null +++ b/vb-migration/Strata.Base.Internal.sln @@ -0,0 +1,30 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.0.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Strata.Base.Internal", "Strata.Base.Internal\Strata.Base.Internal.vbproj", "{DB6C7DE1-AB63-4466-93A9-E5C3BDB561B4}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Strata.Base.Internal.Tests", "Strata.Base.Internal.Tests\Strata.Base.Internal.Tests.csproj", "{11111111-1111-1111-1111-111111111111}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DB6C7DE1-AB63-4466-93A9-E5C3BDB561B4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DB6C7DE1-AB63-4466-93A9-E5C3BDB561B4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DB6C7DE1-AB63-4466-93A9-E5C3BDB561B4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DB6C7DE1-AB63-4466-93A9-E5C3BDB561B4}.Release|Any CPU.Build.0 = Release|Any CPU + {11111111-1111-1111-1111-111111111111}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {11111111-1111-1111-1111-111111111111}.Debug|Any CPU.Build.0 = Debug|Any CPU + {11111111-1111-1111-1111-111111111111}.Release|Any CPU.ActiveCfg = Release|Any CPU + {11111111-1111-1111-1111-111111111111}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {5C6D0F1F-E91E-4F6A-9E9F-B3E2DA7F2B4D} + EndGlobalSection +EndGlobal diff --git a/vb-migration/Strata.Base.Internal/Encryptors/UberEncryptionMethod.vb b/vb-migration/Strata.Base.Internal/Encryptors/UberEncryptionMethod.vb index 55e86dd..f5d50f0 100644 --- a/vb-migration/Strata.Base.Internal/Encryptors/UberEncryptionMethod.vb +++ b/vb-migration/Strata.Base.Internal/Encryptors/UberEncryptionMethod.vb @@ -1,4 +1,4 @@ -Imports System.Configuration +Imports System.Configuration Imports Strata.Configuration.Client.Models.Jazz Namespace Encryptors @@ -6,7 +6,7 @@ Namespace Encryptors Public Class UberEncryptionMethod Implements IPasswordEncryptionMethod - Friend Sub New() + Public Sub New() End Sub @@ -17,7 +17,7 @@ Namespace Encryptors End Function Private Shared Function GetUberMonet(ByVal aDate As Date, ByVal anOrgPIN As String, ByVal aKey As String) As String - Dim ha As New EncryptionUtils.Hasher(EncryptionUtils.Hasher.Provider.SHA1) + Dim ha As New EncryptionUtils.Hasher(EncryptionUtils.Hasher.Provider.SHA256) Dim lsHashBefore As String Dim lsResult As String @@ -38,7 +38,7 @@ Namespace Encryptors #Region " IPasswordEncryptionMethod " - Private Function Encode(ByVal username As String, ByVal anOrgPin As String, ByVal aNewPassword As String, ByVal aUserGUID As System.Guid, aSalt As String) As String Implements IPasswordEncryptionMethod.Encode + Public Function Encode(ByVal username As String, ByVal anOrgPin As String, ByVal aNewPassword As String, ByVal aUserGUID As System.Guid, aSalt As String) As String Implements IPasswordEncryptionMethod.Encode Return GetUberMonet(anOrgPin) End Function diff --git a/vb-migration/Strata.Base.Internal/Encryptors/UserGUIDEncryptionMethod.vb b/vb-migration/Strata.Base.Internal/Encryptors/UserGUIDEncryptionMethod.vb index f1974df..fa05adb 100644 --- a/vb-migration/Strata.Base.Internal/Encryptors/UserGUIDEncryptionMethod.vb +++ b/vb-migration/Strata.Base.Internal/Encryptors/UserGUIDEncryptionMethod.vb @@ -1,4 +1,4 @@ -Imports System.Configuration +Imports System.Configuration Imports System.Security.Cryptography Imports System.Text Imports Strata.Configuration.Client.Models.Jazz @@ -30,7 +30,7 @@ Namespace Encryptors Private Shared Function GetHashedValue(ByVal aValue As String) As String 'Create an instance of the sha encrypter - Using hasher As New SHA1Managed + Using hasher As HashAlgorithm = SHA256.Create() Return Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(aValue))) End Using diff --git a/vb-migration/Strata.Base.Internal/Encryptors/UserSaltEncryptionMethod.vb b/vb-migration/Strata.Base.Internal/Encryptors/UserSaltEncryptionMethod.vb index 7f66c76..a40ec84 100644 --- a/vb-migration/Strata.Base.Internal/Encryptors/UserSaltEncryptionMethod.vb +++ b/vb-migration/Strata.Base.Internal/Encryptors/UserSaltEncryptionMethod.vb @@ -1,4 +1,4 @@ -Imports System.Configuration +Imports System.Configuration Imports System.Security.Cryptography Imports System.Text Imports Strata.Configuration.Client.Models.Jazz @@ -19,7 +19,7 @@ Namespace Encryptors Public Function Encode(ByVal username As String, ByVal anOrgPin As String, ByVal aNewPassword As String, ByVal aUserGUID As System.Guid, aSalt As String) As String Implements IPasswordEncryptionMethod.Encode Dim saltAndPepper As String = aSalt & ConfigurationManager.AppSettings(NameOf(StrataJazzOptions.UserSaltEncryptionKey)) - Using deriveBytes As Rfc2898DeriveBytes = New Rfc2898DeriveBytes(aNewPassword, Encoding.UTF8.GetBytes(saltAndPepper), NUMBER_ITERATIONS) + Using deriveBytes As Rfc2898DeriveBytes = New Rfc2898DeriveBytes(aNewPassword, Encoding.UTF8.GetBytes(saltAndPepper), NUMBER_ITERATIONS, HashAlgorithmName.SHA256) Dim password As Byte() = deriveBytes.GetBytes(24) Return Convert.ToBase64String(password) diff --git a/vb-migration/Strata.Base.Internal/Security/Encryption.vb b/vb-migration/Strata.Base.Internal/Security/Encryption.vb index ff57814..1bf72b1 100644 --- a/vb-migration/Strata.Base.Internal/Security/Encryption.vb +++ b/vb-migration/Strata.Base.Internal/Security/Encryption.vb @@ -13,7 +13,7 @@ Namespace EncryptionUtils ''' infeasible to find two distinct inputs that hash to the same value. Hash functions ''' are commonly used with digital signatures and for data integrity. ''' - Friend Class Hasher + Public Class Hasher ''' ''' Type of hash; some are security oriented, others are fast and simple @@ -44,7 +44,7 @@ Namespace EncryptionUtils Private _Hash As HashAlgorithm Private _HashValue As New Data - Private Sub New() + Friend Sub New() End Sub ''' @@ -53,15 +53,17 @@ Namespace EncryptionUtils Friend Sub New(ByVal p As Provider) Select Case p Case Provider.MD5 - _Hash = New MD5CryptoServiceProvider + _Hash = MD5.Create() Case Provider.SHA1 - _Hash = New SHA1Managed + _Hash = SHA1.Create() Case Provider.SHA256 - _Hash = New SHA256Managed + _Hash = SHA256.Create() Case Provider.SHA384 - _Hash = New SHA384Managed + _Hash = SHA384.Create() Case Provider.SHA512 - _Hash = New SHA512Managed + _Hash = SHA512.Create() + Case Else + _Hash = SHA256.Create() ' Default to SHA256 for unknown providers End Select End Sub @@ -124,22 +126,22 @@ Namespace EncryptionUtils Private Const _BufferSize As Integer = 2048 Friend Enum Provider - ''' - ''' The Data Encryption Standard provider supports a 64 bit key only - ''' + + MD5 + + SHA1 + SHA256 + SHA384 + SHA512 + DES - ''' - ''' The Rivest Cipher 2 provider supports keys ranging from 40 to 128 bits, default is 128 bits - ''' + RC2 - ''' - ''' The Rijndael (also known as AES) provider supports keys of 128, 192, or 256 bits with a default of 256 bits - ''' + Rijndael - ''' - ''' The TripleDES provider (also known as 3DES) supports keys of 128 or 192 bits with a default of 192 bits - ''' + TripleDES + AES End Enum Private _data As Data @@ -158,13 +160,15 @@ Namespace EncryptionUtils Friend Sub New(ByVal provider As Provider, Optional ByVal useDefaultInitializationVector As Boolean = True) Select Case provider Case Provider.DES - _crypto = New DESCryptoServiceProvider + _crypto = DES.Create() Case Provider.RC2 - _crypto = New RC2CryptoServiceProvider - Case Provider.Rijndael - _crypto = New RijndaelManaged + _crypto = RC2.Create() + Case Provider.Rijndael, Provider.AES + _crypto = Aes.Create() Case Provider.TripleDES - _crypto = New TripleDESCryptoServiceProvider + _crypto = TripleDES.Create() + Case Else + _crypto = Aes.Create() ' Default to AES for unknown providers End Select '-- make sure key and IV are always set, no matter what @@ -272,8 +276,12 @@ Namespace EncryptionUtils Throw New CryptographicException("No initialization vector was provided for the decryption operation!") End If End If - _crypto.Key = _key.Bytes - _crypto.IV = _iv.Bytes + Try + _crypto.Key = _key.Bytes + _crypto.IV = _iv.Bytes + Catch ex As CryptographicException + Throw New CryptographicException("Invalid key or initialization vector.", ex) + End Try End Sub ''' @@ -384,20 +392,19 @@ Namespace EncryptionUtils ''' Decrypts the specified data using preset key and preset initialization vector ''' Friend Function Decrypt(ByVal encryptedData As Data) As Data - Dim ms As New System.IO.MemoryStream(encryptedData.Bytes, 0, encryptedData.Bytes.Length) - Dim b() As Byte = New Byte(encryptedData.Bytes.Length - 1) {} - - ValidateKeyAndIv(False) - Dim cs As New CryptoStream(ms, _crypto.CreateDecryptor(), CryptoStreamMode.Read) - - Try - cs.Read(b, 0, encryptedData.Bytes.Length - 1) - Catch ex As CryptographicException - Throw New CryptographicException("Unable to decrypt data. The provided key may be invalid.", ex) - Finally - cs.Close() - End Try - Return New Data(b) + Using ms As New System.IO.MemoryStream(encryptedData.Bytes, 0, encryptedData.Bytes.Length) + ValidateKeyAndIv(False) + Using cs As New CryptoStream(ms, _crypto.CreateDecryptor(), CryptoStreamMode.Read) + Using outputMs As New MemoryStream() + Try + cs.CopyTo(outputMs) + Return New Data(outputMs.ToArray()) + Catch ex As CryptographicException + Throw New CryptographicException("Unable to decrypt data. The provided key may be invalid.", ex) + End Try + End Using + End Using + End Using End Function End Class @@ -421,7 +428,12 @@ Namespace EncryptionUtils ''' ''' Determines the default text encoding across ALL Data instances ''' - Friend Shared DefaultEncoding As Text.Encoding = System.Text.Encoding.GetEncoding("Windows-1252") + Friend Shared DefaultEncoding As Text.Encoding + + Shared Sub New() + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance) + DefaultEncoding = System.Text.Encoding.GetEncoding("Windows-1252") + End Sub ''' ''' Determines the default text encoding for this Data instance diff --git a/vb-migration/Strata.Base.Internal/Security/SecurityUtils.vb b/vb-migration/Strata.Base.Internal/Security/SecurityUtils.vb index 6eda05f..c2030ac 100644 --- a/vb-migration/Strata.Base.Internal/Security/SecurityUtils.vb +++ b/vb-migration/Strata.Base.Internal/Security/SecurityUtils.vb @@ -1,16 +1,26 @@ Public Class SecurityUtils #Region " Declarations " - Private Const ENCRYPTION_KEY_SUFFIX As String = "SDT" + Private Const KEY_SIZE_BYTES As Integer = 32 ' 256 bits for AES-256 #End Region #Region " Methods " + Private Shared Function PadKey(key As String) As String + Dim paddedKey As String = key & ENCRYPTION_KEY_SUFFIX + If paddedKey.Length < KEY_SIZE_BYTES Then + paddedKey = paddedKey.PadRight(KEY_SIZE_BYTES, "X"c) + ElseIf paddedKey.Length > KEY_SIZE_BYTES Then + paddedKey = paddedKey.Substring(0, KEY_SIZE_BYTES) + End If + Return paddedKey + End Function + Public Shared Function EncryptValue(value As String, key As String) As String Dim encryption As New EncryptionUtils.SymmetricEncryptor(EncryptionUtils.SymmetricEncryptor.Provider.Rijndael) - - Return encryption.Encrypt(New EncryptionUtils.Data(value), New EncryptionUtils.Data(key & ENCRYPTION_KEY_SUFFIX)).ToBase64 + + Return encryption.Encrypt(New EncryptionUtils.Data(value), New EncryptionUtils.Data(PadKey(key))).ToBase64 End Function Public Shared Function DecryptValue(encryptedValue As String, key As String) As String @@ -20,7 +30,7 @@ Public Class SecurityUtils Dim encryptedData As EncryptionUtils.Data = New EncryptionUtils.Data() encryptedData.Base64 = encryptedValue - Return encryption.Decrypt(encryptedData, New EncryptionUtils.Data(key & ENCRYPTION_KEY_SUFFIX)).Text + Return encryption.Decrypt(encryptedData, New EncryptionUtils.Data(PadKey(key))).Text End Function #End Region diff --git a/vb-migration/Strata.Base.Internal/Strata.Base.Internal.vbproj b/vb-migration/Strata.Base.Internal/Strata.Base.Internal.vbproj index f585ba8..6c30feb 100644 --- a/vb-migration/Strata.Base.Internal/Strata.Base.Internal.vbproj +++ b/vb-migration/Strata.Base.Internal/Strata.Base.Internal.vbproj @@ -1,4 +1,4 @@ - + net8.0-windows Library @@ -20,15 +20,14 @@ Strata.Biz.Internal Strata Decision Technology, LLC Strata.Biz.Internal - © 2006-2012 Strata Decision Technology, LLC + 2006-2012 Strata Decision Technology, LLC Strata.Base.Internal.xml 42353,42354,42355 41999,42016,42017,42018,42019,42020,42021,42022,42032,42036 false - -Microsoft.Design#CA1012;-Microsoft.Design#CA2210;-Microsoft.Design#CA1040;-Microsoft.Design#CA1005;-Microsoft.Design#CA1020;-Microsoft.Design#CA1021;-Microsoft.Design#CA1010;-Microsoft.Design#CA1011;-Microsoft.Design#CA1009;-Microsoft.Design#CA1050;-Microsoft.Design#CA1026;-Microsoft.Design#CA1019;-Microsoft.Design#CA1031;-Microsoft.Design#CA1047;-Microsoft.Design#CA1000;-Microsoft.Design#CA1048;-Microsoft.Design#CA1051;-Microsoft.Design#CA1002;-Microsoft.Design#CA1061;-Microsoft.Design#CA1006;-Microsoft.Design#CA1046;-Microsoft.Design#CA1045;-Microsoft.Design#CA1065;-Microsoft.Design#CA1038;-Microsoft.Design#CA1008;-Microsoft.Design#CA1028;-Microsoft.Design#CA1064;-Microsoft.Design#CA1004;-Microsoft.Design#CA1035;-Microsoft.Design#CA1063;-Microsoft.Design#CA1032;-Microsoft.Design#CA1023;-Microsoft.Design#CA1033;-Microsoft.Design#CA1039;-Microsoft.Design#CA1016;-Microsoft.Design#CA1014;-Microsoft.Design#CA1017;-Microsoft.Design#CA1018;-Microsoft.Design#CA1027;-Microsoft.Design#CA1059;-Microsoft.Design#CA1060;-Microsoft.Design#CA1034;-Microsoft.Design#CA1013;-Microsoft.Design#CA1036;-Microsoft.Design#CA1044;-Microsoft.Design#CA1041;-Microsoft.Design#CA1025;-Microsoft.Design#CA1052;-Microsoft.Design#CA1053;-Microsoft.Design#CA1057;-Microsoft.Design#CA1058;-Microsoft.Design#CA1001;-Microsoft.Design#CA1049;-Microsoft.Design#CA1054;-Microsoft.Design#CA1056;-Microsoft.Design#CA1055;-Microsoft.Design#CA1030;-Microsoft.Design#CA1003;-Microsoft.Design#CA1007;-Microsoft.Design#CA1043;-Microsoft.Design#CA1024;-Microsoft.Globalization#CA1301;-Microsoft.Globalization#CA1302;-Microsoft.Globalization#CA1308;-Microsoft.Globalization#CA1306;-Microsoft.Globalization#CA1304;-Microsoft.Globalization#CA1305;-Microsoft.Globalization#CA2101;-Microsoft.Globalization#CA1300;-Microsoft.Globalization#CA1307;-Microsoft.Globalization#CA1309;-Microsoft.Interoperability#CA1403;-Microsoft.Interoperability#CA1406;-Microsoft.Interoperability#CA1413;-Microsoft.Interoperability#CA1402;-Microsoft.Interoperability#CA1407;-Microsoft.Interoperability#CA1404;-Microsoft.Interoperability#CA1410;-Microsoft.Interoperability#CA1411;-Microsoft.Interoperability#CA1405;-Microsoft.Interoperability#CA1409;-Microsoft.Interoperability#CA1415;-Microsoft.Interoperability#CA1408;-Microsoft.Interoperability#CA1414;-Microsoft.Interoperability#CA1412;-Microsoft.Interoperability#CA1400;-Microsoft.Interoperability#CA1401;-Microsoft.Maintainability#CA1506;-Microsoft.Maintainability#CA1502;-Microsoft.Maintainability#CA1501;-Microsoft.Maintainability#CA1505;-Microsoft.Maintainability#CA1504;-Microsoft.Maintainability#CA1500;-Microsoft.Mobility#CA1600;-Microsoft.Mobility#CA1601;-Microsoft.Naming#CA1702;-Microsoft.Naming#CA1700;-Microsoft.Naming#CA1712;-Microsoft.Naming#CA1713;-Microsoft.Naming#CA1714;-Microsoft.Naming#CA1709;-Microsoft.Naming#CA1704;-Microsoft.Naming#CA1708;-Microsoft.Naming#CA1715;-Microsoft.Naming#CA1710;-Microsoft.Naming#CA1720;-Microsoft.Naming#CA1707;-Microsoft.Naming#CA1722;-Microsoft.Naming#CA1711;-Microsoft.Naming#CA1716;-Microsoft.Naming#CA1717;-Microsoft.Naming#CA1725;-Microsoft.Naming#CA1719;-Microsoft.Naming#CA1721;-Microsoft.Naming#CA1701;-Microsoft.Naming#CA1703;-Microsoft.Naming#CA1724;-Microsoft.Naming#CA1726;-Microsoft.Performance#CA1809;-Microsoft.Performance#CA1811;-Microsoft.Performance#CA1813;-Microsoft.Performance#CA1816;-Microsoft.Performance#CA1800;-Microsoft.Performance#CA1805;-Microsoft.Performance#CA1810;-Microsoft.Performance#CA1824;-Microsoft.Performance#CA1822;-Microsoft.Performance#CA1814;-Microsoft.Performance#CA1819;-Microsoft.Performance#CA1821;-Microsoft.Performance#CA1820;-Microsoft.Performance#CA1802;-Microsoft.Portability#CA1901;-Microsoft.Portability#CA1900;-Microsoft.Reliability#CA2001;-Microsoft.Reliability#CA2002;-Microsoft.Reliability#CA2003;-Microsoft.Reliability#CA2004;-Microsoft.Reliability#CA2006;-Microsoft.Security#CA2116;-Microsoft.Security#CA2117;-Microsoft.Security#CA2105;-Microsoft.Security#CA2115;-Microsoft.Security#CA2102;-Microsoft.Security#CA2104;-Microsoft.Security#CA2122;-Microsoft.Secu -rity#CA2114;-Microsoft.Security#CA2123;-Microsoft.Security#CA2111;-Microsoft.Security#CA2108;-Microsoft.Security#CA2107;-Microsoft.Security#CA2103;-Microsoft.Security#CA2118;-Microsoft.Security#CA2109;-Microsoft.Security#CA2119;-Microsoft.Security#CA2106;-Microsoft.Security#CA2112;-Microsoft.Security#CA2120;-Microsoft.Security#CA2121;-Microsoft.Security#CA2126;-Microsoft.Security#CA2124;-Microsoft.Security#CA2127;-Microsoft.Security#CA2128;-Microsoft.Security#CA2129;-Microsoft.Usage#CA2243;-Microsoft.Usage#CA2236;-Microsoft.Usage#CA2227;-Microsoft.Usage#CA2213;-Microsoft.Usage#CA2216;-Microsoft.Usage#CA2214;-Microsoft.Usage#CA2222;-Microsoft.Usage#CA1806;-Microsoft.Usage#CA2217;-Microsoft.Usage#CA2212;-Microsoft.Usage#CA2219;-Microsoft.Usage#CA2201;-Microsoft.Usage#CA2228;-Microsoft.Usage#CA2221;-Microsoft.Usage#CA2220;-Microsoft.Usage#CA2240;-Microsoft.Usage#CA2229;-Microsoft.Usage#CA2238;-Microsoft.Usage#CA2207;-Microsoft.Usage#CA2208;-Microsoft.Usage#CA2235;-Microsoft.Usage#CA2237;-Microsoft.Usage#CA2232;-Microsoft.Usage#CA2223;-Microsoft.Usage#CA2211;-Microsoft.Usage#CA2233;-Microsoft.Usage#CA2225;-Microsoft.Usage#CA2226;-Microsoft.Usage#CA2231;-Microsoft.Usage#CA2224;-Microsoft.Usage#CA2218;-Microsoft.Usage#CA2234;-Microsoft.Usage#CA2239;-Microsoft.Usage#CA2200;-Microsoft.Usage#CA1801;-Microsoft.Usage#CA2242;-Microsoft.Usage#CA2205;-Microsoft.Usage#CA2230 + -Microsoft.Design#CA1012;-Microsoft.Design#CA2210;-Microsoft.Design#CA1040;-Microsoft.Design#CA1005;-Microsoft.Design#CA1020;-Microsoft.Design#CA1021;-Microsoft.Design#CA1010;-Microsoft.Design#CA1011;-Microsoft.Design#CA1009;-Microsoft.Design#CA1050;-Microsoft.Design#CA1026;-Microsoft.Design#CA1019;-Microsoft.Design#CA1031;-Microsoft.Design#CA1047;-Microsoft.Design#CA1000;-Microsoft.Design#CA1048;-Microsoft.Design#CA1051;-Microsoft.Design#CA1002;-Microsoft.Design#CA1061;-Microsoft.Design#CA1006;-Microsoft.Design#CA1046;-Microsoft.Design#CA1045;-Microsoft.Design#CA1065;-Microsoft.Design#CA1038;-Microsoft.Design#CA1008;-Microsoft.Design#CA1028;-Microsoft.Design#CA1064;-Microsoft.Design#CA1004;-Microsoft.Design#CA1035;-Microsoft.Design#CA1063;-Microsoft.Design#CA1032;-Microsoft.Design#CA1023;-Microsoft.Design#CA1033;-Microsoft.Design#CA1039;-Microsoft.Design#CA1016;-Microsoft.Design#CA1014;-Microsoft.Design#CA1017;-Microsoft.Design#CA1018;-Microsoft.Design#CA1027;-Microsoft.Design#CA1059;-Microsoft.Design#CA1060;-Microsoft.Design#CA1034;-Microsoft.Design#CA1013;-Microsoft.Design#CA1036;-Microsoft.Design#CA1044;-Microsoft.Design#CA1041;-Microsoft.Design#CA1025;-Microsoft.Design#CA1052;-Microsoft.Design#CA1053;-Microsoft.Design#CA1057;-Microsoft.Design#CA1058;-Microsoft.Design#CA1001;-Microsoft.Design#CA1049;-Microsoft.Design#CA1054;-Microsoft.Design#CA1056;-Microsoft.Design#CA1055;-Microsoft.Design#CA1030;-Microsoft.Design#CA1003;-Microsoft.Design#CA1007;-Microsoft.Design#CA1043;-Microsoft.Design#CA1024;-Microsoft.Globalization#CA1301;-Microsoft.Globalization#CA1302;-Microsoft.Globalization#CA1308;-Microsoft.Globalization#CA1306;-Microsoft.Globalization#CA1304;-Microsoft.Globalization#CA1305;-Microsoft.Globalization#CA2101;-Microsoft.Globalization#CA1300;-Microsoft.Globalization#CA1307;-Microsoft.Globalization#CA1309;-Microsoft.Interoperability#CA1403;-Microsoft.Interoperability#CA1406;-Microsoft.Interoperability#CA1413;-Microsoft.Interoperability#CA1402;-Microsoft.Interoperability#CA1407;-Microsoft.Interoperability#CA1404;-Microsoft.Interoperability#CA1410;-Microsoft.Interoperability#CA1411;-Microsoft.Interoperability#CA1405;-Microsoft.Interoperability#CA1409;-Microsoft.Interoperability#CA1415;-Microsoft.Interoperability#CA1408;-Microsoft.Interoperability#CA1414;-Microsoft.Interoperability#CA1412;-Microsoft.Interoperability#CA1400;-Microsoft.Interoperability#CA1401;-Microsoft.Maintainability#CA1506;-Microsoft.Maintainability#CA1502;-Microsoft.Maintainability#CA1501;-Microsoft.Maintainability#CA1505;-Microsoft.Maintainability#CA1504;-Microsoft.Maintainability#CA1500;-Microsoft.Mobility#CA1600;-Microsoft.Mobility#CA1601;-Microsoft.Naming#CA1702;-Microsoft.Naming#CA1700;-Microsoft.Naming#CA1712;-Microsoft.Naming#CA1713;-Microsoft.Naming#CA1714;-Microsoft.Naming#CA1709;-Microsoft.Naming#CA1704;-Microsoft.Naming#CA1708;-Microsoft.Naming#CA1715;-Microsoft.Naming#CA1710;-Microsoft.Naming#CA1720;-Microsoft.Naming#CA1707;-Microsoft.Naming#CA1722;-Microsoft.Naming#CA1711;-Microsoft.Naming#CA1716;-Microsoft.Naming#CA1717;-Microsoft.Naming#CA1725;-Microsoft.Naming#CA1719;-Microsoft.Naming#CA1721;-Microsoft.Naming#CA1701;-Microsoft.Naming#CA1703;-Microsoft.Naming#CA1724;-Microsoft.Naming#CA1726;-Microsoft.Performance#CA1809;-Microsoft.Performance#CA1811;-Microsoft.Performance#CA1813;-Microsoft.Performance#CA1816;-Microsoft.Performance#CA1800;-Microsoft.Performance#CA1805;-Microsoft.Performance#CA1810;-Microsoft.Performance#CA1824;-Microsoft.Performance#CA1822;-Microsoft.Performance#CA1814;-Microsoft.Performance#CA1819;-Microsoft.Performance#CA1821;-Microsoft.Performance#CA1820;-Microsoft.Performance#CA1802;-Microsoft.Portability#CA1901;-Microsoft.Portability#CA1900;-Microsoft.Reliability#CA2001;-Microsoft.Reliability#CA2002;-Microsoft.Reliability#CA2003;-Microsoft.Reliability#CA2004;-Microsoft.Reliability#CA2006;-Microsoft.Security#CA2116;-Microsoft.Security#CA2117;-Microsoft.Security#CA2105;-Microsoft.Security#CA2115;-Microsoft.Security#CA2102;-Microsoft.Security#CA2104;-Microsoft.Security#CA2122;-Microsoft.Security#CA2114;-Microsoft.Security#CA2123;-Microsoft.Security#CA2111;-Microsoft.Security#CA2108;-Microsoft.Security#CA2107;-Microsoft.Security#CA2103;-Microsoft.Security#CA2118;-Microsoft.Security#CA2109;-Microsoft.Security#CA2119;-Microsoft.Security#CA2106;-Microsoft.Security#CA2112;-Microsoft.Security#CA2120;-Microsoft.Security#CA2121;-Microsoft.Security#CA2126;-Microsoft.Security#CA2124;-Microsoft.Security#CA2127;-Microsoft.Security#CA2128;-Microsoft.Security#CA2129;-Microsoft.Usage#CA2243;-Microsoft.Usage#CA2236;-Microsoft.Usage#CA2227;-Microsoft.Usage#CA2213;-Microsoft.Usage#CA2216;-Microsoft.Usage#CA2214;-Microsoft.Usage#CA2222;-Microsoft.Usage#CA1806;-Microsoft.Usage#CA2217;-Microsoft.Usage#CA2212;-Microsoft.Usage#CA2219;-Microsoft.Usage#CA2201;-Microsoft.Usage#CA2228;-Microsoft.Usage#CA2221;-Microsoft.Usage#CA2220;-Microsoft.Usage#CA2240;-Microsoft.Usage#CA2229;-Microsoft.Usage#CA2238;-Microsoft.Usage#CA2207;-Microsoft.Usage#CA2208;-Microsoft.Usage#CA2235;-Microsoft.Usage#CA2237;-Microsoft.Usage#CA2232;-Microsoft.Usage#CA2223;-Microsoft.Usage#CA2211;-Microsoft.Usage#CA2233;-Microsoft.Usage#CA2225;-Microsoft.Usage#CA2226;-Microsoft.Usage#CA2231;-Microsoft.Usage#CA2224;-Microsoft.Usage#CA2218;-Microsoft.Usage#CA2234;-Microsoft.Usage#CA2239;-Microsoft.Usage#CA2200;-Microsoft.Usage#CA1801;-Microsoft.Usage#CA2242;-Microsoft.Usage#CA2205;-Microsoft.Usage#CA2230 Strata.Base.Internal.ruleset @@ -47,6 +46,9 @@ rity#CA2114;-Microsoft.Security#CA2123;-Microsoft.Security#CA2111;-Microsoft.Sec 41999,42016,42017,42018,42019,42020,42021,42022,42032,42036 Strata.Base.Internal.ruleset + + + True @@ -78,9 +80,7 @@ rity#CA2114;-Microsoft.Security#CA2123;-Microsoft.Security#CA2111;-Microsoft.Sec 8.44.0 - - 0.0.9 - + \ No newline at end of file -- 2.45.2 From 7b0ed744c79e4192c4e4816a236cdfe3f4ca8e3d Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Thu, 30 Jan 2025 21:24:19 -0500 Subject: [PATCH 06/31] Include the final document for the VB To CS --- vb-migration/VB-CS-migration-guide.md | 165 ++++++++++++++++ vb-migration/complete-converter-guide.md | 229 ----------------------- vb-migration/migration-prerequisites.md | 167 ----------------- vb-migration/migration-steps.md | 221 ---------------------- 4 files changed, 165 insertions(+), 617 deletions(-) create mode 100644 vb-migration/VB-CS-migration-guide.md delete mode 100644 vb-migration/complete-converter-guide.md delete mode 100644 vb-migration/migration-prerequisites.md delete mode 100644 vb-migration/migration-steps.md diff --git a/vb-migration/VB-CS-migration-guide.md b/vb-migration/VB-CS-migration-guide.md new file mode 100644 index 0000000..2c32147 --- /dev/null +++ b/vb-migration/VB-CS-migration-guide.md @@ -0,0 +1,165 @@ +# Comprehensive VB.NET to C# Migration Guide + +## Overview +This guide outlines the process for migrating from VB.NET Framework to C# .NET 8, emphasizing a two-phase approach and leveraging AI tools for optimal results. + +## Phase 0: Prerequisites and Planning + +### Critical Prerequisites +1. **Test Coverage** + - Minimum 80% code coverage with unit tests + - Integration tests for critical workflows + - End-to-end tests for main user journeys + - Performance benchmarks + + *AI Enhancement*: Use Claude to analyze code and generate comprehensive test cases, identifying potential edge cases and critical test scenarios. + +2. **Code Quality Baseline** + - Static code analysis + - Remove deprecated API usage + - Clean up dependencies + - Fix compiler warnings + + *AI Enhancement*: Leverage Windsurf for security checks and best practice recommendations during the cleanup phase. + +3. **Documentation** + - API documentation + - Business rules + - System architecture + - Integration points + + *AI Enhancement*: Use Claude to generate technical documentation and API references from existing code. + +## Phase 1: Framework Migration (VB.NET to .NET 8) + +### Step 1: Environment Setup +1. Install required tools: + ```bash + dotnet tool install -g upgrade-assistant + dotnet tool install -g ICSharpCode.CodeConverter.Cli + ``` +2. Set up version control and backup +3. Create separate environments for testing + +### Step 2: Initial Analysis +1. Run .NET Upgrade Assistant analysis: + ```bash + upgrade-assistant analyze your-solution.sln + ``` + + *AI Enhancement*: Use Claude to: + - Analyze framework-specific dependencies + - Identify outdated patterns + - Suggest modern alternatives + - Review upgrade-assistant recommendations + +2. Document dependencies and framework-specific code + + *AI Enhancement*: Use Windsurf to: + - Identify security implications + - Suggest secure alternatives + - Review configuration settings + +### Step 3: Framework Migration Execution +1. Start with smallest, least dependent modules +2. Run upgrade assistant: + ```bash + upgrade-assistant upgrade your-solution.sln + ``` +3. Update package references +4. Fix compatibility issues + +## Phase 2: Language Migration (VB.NET to C#) + +### Step 1: Code Conversion +1. Use ICSharpCode.CodeConverter: + ```bash + code-converter convert-project -l VB2CS -t ConvertedProject + ``` + + *AI Enhancement*: Use Claude to: + - Review converted code + - Identify potential bugs + - Suggest modern C# features + - Optimize code patterns + +### Step 2: Post-Conversion Tasks +1. **Code Review** + - Review generated C# code + - Apply C# best practices + - Optimize for .NET 8 features + + *AI Enhancement*: Use Windsurf for: + - Security validation + - Performance optimization + - Best practice compliance + +2. **Testing** + - Run all test suites + - Perform integration testing + - Validate business logic + + *AI Enhancement*: Use Claude to: + - Generate additional test cases + - Identify potential edge cases + - Suggest performance improvements + +## Best Practices + +### Migration Process +1. Follow the two-phase approach strictly +2. Start with smaller modules +3. Maintain comprehensive testing +4. Document all changes +5. Use version control effectively + +### AI Tool Usage +1. **Claude** + - Code analysis and review + - Pattern modernization + - Documentation generation + - Test case creation + - Performance optimization + +2. **Windsurf** + - Security validation + - Best practice enforcement + - Pattern suggestions + - Configuration review + +### Risk Mitigation +1. Create technical risk register +2. Implement fallback procedures +3. Maintain parallel environments +4. Document all decisions +5. Regular stakeholder communication + +## Common Issues and Solutions + +### Framework Migration +1. **Dependency Conflicts** + - Solution: Use NuGet package manager to resolve + - AI Enhancement: Use Claude to analyze dependency trees + +2. **API Compatibility** + - Solution: Use compatibility analyzer + - AI Enhancement: Use Windsurf to suggest secure alternatives + +### Language Migration +1. **Syntax Differences** + - Solution: Review converter output carefully + - AI Enhancement: Use Claude to identify and fix conversion issues + +2. **Performance Issues** + - Solution: Profile and optimize + - AI Enhancement: Use Windsurf for performance recommendations + +## Conclusion +Success depends on: +- Following the correct migration sequence +- Leveraging AI tools effectively +- Maintaining thorough testing +- Documenting all changes +- Regular validation and review + +Remember to start with a pilot project to validate the process before full migration. \ No newline at end of file diff --git a/vb-migration/complete-converter-guide.md b/vb-migration/complete-converter-guide.md deleted file mode 100644 index d1a192e..0000000 --- a/vb-migration/complete-converter-guide.md +++ /dev/null @@ -1,229 +0,0 @@ -# Complete Guide to ICSharpCode.CodeConverter.Cli in VS Code - -## Prerequisites -1. .NET SDK installed on your system -2. Visual Studio Code -3. C# extension for VS Code (optional but recommended) - -## Installation - -Install the ICSharpCode.CodeConverter.Cli globally using the .NET CLI: -```bash -dotnet tool install -g ICSharpCode.CodeConverter.Cli -``` - -## VS Code Configuration - -### Basic File Conversion Setup - -1. Create a tasks.json file in VS Code: - - Press `Ctrl+Shift+P` (Windows/Linux) or `Cmd+Shift+P` (Mac) - - Type "Tasks: Configure Task" - - Select "Create tasks.json file from template" - - Choose "Others" - -2. Add the following configuration to tasks.json: -```json -{ - "version": "2.0.0", - "tasks": [ - { - "label": "Convert CS to VB", - "type": "shell", - "command": "code-converter", - "args": [ - "convert", - "${file}", - "-l", - "CS2VB" - ], - "problemMatcher": [] - }, - { - "label": "Convert VB to CS", - "type": "shell", - "command": "code-converter", - "args": [ - "convert", - "${file}", - "-l", - "VB2CS" - ], - "problemMatcher": [] - }, - { - "label": "Convert C# Project to VB", - "type": "shell", - "command": "code-converter", - "args": [ - "convert-project", - "${workspaceFolder}/${input:projectFile}", - "-l", - "CS2VB", - "-t", - "${workspaceFolder}/Converted" - ], - "problemMatcher": [] - }, - { - "label": "Convert VB Project to C#", - "type": "shell", - "command": "code-converter", - "args": [ - "convert-project", - "${workspaceFolder}/${input:projectFile}", - "-l", - "VB2CS", - "-t", - "${workspaceFolder}/Converted" - ], - "problemMatcher": [] - } - ], - "inputs": [ - { - "id": "projectFile", - "type": "promptString", - "description": "Project file to convert (e.g., MyProject.csproj)" - } - ] -} -``` - -## Usage Instructions - -### Single File Conversion - -1. To convert a single file: - - Open the file in VS Code - - Press `Ctrl+Shift+P` (Windows/Linux) or `Cmd+Shift+P` (Mac) - - Type "Tasks: Run Task" - - Select either "Convert CS to VB" or "Convert VB to CS" - -2. Example C# to VB.NET conversion: - -Source file (test.cs): -```csharp -public class Calculator -{ - public int Add(int a, int b) - { - return a + b; - } -} -``` - -Converted file (test.vb): -```vb -Public Class Calculator - Public Function Add(a As Integer, b As Integer) As Integer - Return a + b - End Function -End Class -``` - -### Project Conversion - -1. Command line syntax: -```bash -code-converter convert-project [-t ] -``` - -2. Example commands: -```bash -# C# to VB.NET -code-converter convert-project MyProject.csproj -l CS2VB -t ConvertedProject - -# VB.NET to C# -code-converter convert-project MyProject.vbproj -l VB2CS -t ConvertedProject -``` - -### Project File Structures - -1. C# Project (.csproj): -```xml - - - Exe - net6.0 - - - - - - -``` - -2. VB.NET Project (.vbproj): -```xml - - - Exe - net6.0 - MyProject - On - Binary - Off - On - - - - - - -``` - -## Project Conversion Considerations - -### 1. Project References -- All project references are maintained -- NuGet package references are preserved -- Assembly references are carried over - -### 2. Resource Handling -- .resx files are copied to target directory -- Resource identifiers are adjusted -- app.config and web.config files are preserved - -### 3. Special Conversion Options -```bash -# Preserve case when converting to VB.NET -code-converter convert-project MyProject.csproj -l CS2VB -t ConvertedProject --preserve-case - -# Skip resources when converting to C# -code-converter convert-project MyProject.vbproj -l VB2CS -t ConvertedProject --skip-resources -``` - -## Troubleshooting - -### 1. Command Not Found -- Verify .NET tools directory is in PATH -- Close and reopen VS Code -- Check installation with `dotnet tool list -g` - -### 2. Conversion Failures -- Verify source code compiles -- Check for correct conversion direction -- Review output window for errors - -### 3. Project Conversion Issues -- Verify all references are accessible -- Check framework versions match -- Ensure NuGet packages are restored -- Review namespace conflicts -- Check for language-specific features - -### 4. Post-Conversion Steps -1. Build the converted project -2. Run available tests -3. Review generated code -4. Check resource file accessibility -5. Verify namespace organization - -## Best Practices - -1. Always backup your source code before conversion -2. Test the converted code thoroughly -3. Review language-specific features that might need manual adjustment -4. Keep original and converted projects separate -5. Document any manual changes needed after conversion \ No newline at end of file diff --git a/vb-migration/migration-prerequisites.md b/vb-migration/migration-prerequisites.md deleted file mode 100644 index c72f316..0000000 --- a/vb-migration/migration-prerequisites.md +++ /dev/null @@ -1,167 +0,0 @@ -# Enhanced Migration Prerequisites and Best Practices - -## Critical Prerequisites Before Migration - -### 1. Test Coverage Requirements -- Implement comprehensive unit tests with minimum 80% code coverage -- Create integration tests for all critical business workflows -- Establish end-to-end tests for main user journeys -- Document all test scenarios and expected outcomes -- Set up automated test runs in CI/CD pipeline -- Create performance benchmarks for critical operations -- Implement API contract tests if applicable -- Set up regression test suites - -### 2. Code Quality Baseline -- Run static code analysis tools and fix all critical/high issues -- Document and justify any suppressions of warnings -- Remove all deprecated API usage -- Clean up unused references and dependencies -- Ensure consistent code formatting -- Remove dead code and unused variables -- Document all known technical debt -- Fix all compiler warnings - -### 3. Documentation Requirements -- Create detailed API documentation -- Document all business rules and domain logic -- Map out all external system integrations -- Document configuration settings and their purposes -- Create system architecture diagrams -- Document all custom implementations and workarounds -- Maintain a glossary of business terms -- Document all scheduled tasks and batch processes - -### 4. Infrastructure and Environment -- Set up separate environments for migration testing -- Create rollback procedures -- Implement monitoring and logging -- Set up feature flags for gradual migration -- Create backup and restore procedures -- Document deployment procedures -- Set up parallel run capabilities -- Establish performance monitoring baselines - -### 5. Business Validation -- Identify subject matter experts for each module -- Create business validation test cases -- Document critical business periods to avoid -- Create business continuity plan during migration -- Establish acceptance criteria for migration success -- Document regulatory compliance requirements -- Create data validation procedures -- Establish UAT test plans - -## Enhanced Best Practices - -### 1. Code Organization -- Implement clean architecture principles -- Separate business logic from infrastructure code -- Use dependency injection consistently -- Implement repository pattern for data access -- Use SOLID principles -- Implement proper exception handling -- Use consistent logging patterns -- Implement proper configuration management - -### 2. Testing Strategy -- Create smoke test suite for quick validation -- Implement automated UI tests for critical paths -- Create load and stress tests -- Implement security testing procedures -- Create data-driven tests for complex scenarios -- Implement boundary testing -- Create mutation tests for critical components -- Establish performance testing benchmarks - -### 3. Version Control -- Create feature branches for migration -- Implement proper PR review process -- Set up branch protection rules -- Create meaningful commit messages -- Document branching strategy -- Implement version tagging -- Create release notes template -- Set up automated builds for all branches - -### 4. Migration Process -- Start with smallest, least dependent modules -- Create detailed checklist for each module -- Implement feature toggles for gradual rollout -- Create validation scripts for each phase -- Document all migration decisions -- Create progress tracking system -- Establish regular checkpoints -- Create contingency plans - -### 5. Post-Migration Validation -- Create comparison tools for old vs new system -- Implement parallel run procedures -- Create data reconciliation processes -- Document performance comparison metrics -- Establish monitoring for regression issues -- Create user feedback collection process -- Implement automated health checks -- Create system stability metrics - -### 6. Security Considerations -- Perform security audit before migration -- Document all security requirements -- Implement security testing procedures -- Create security validation checklist -- Document authentication/authorization changes -- Implement secure configuration management -- Create security incident response plan -- Perform penetration testing - -### 7. Performance Requirements -- Establish performance benchmarks -- Create performance test suites -- Document scalability requirements -- Implement performance monitoring -- Create capacity planning documentation -- Establish SLA requirements -- Create performance optimization plan -- Document resource utilization metrics - -### 8. Documentation Standards -- Use consistent documentation format -- Create documentation review process -- Implement version control for documentation -- Create API documentation standards -- Establish documentation update procedures -- Create user guides and training materials -- Document troubleshooting procedures -- Maintain decision log - -## Risk Mitigation Strategies - -### 1. Technical Risks -- Create technical risk register -- Implement mitigation strategies for each risk -- Create fallback procedures -- Document known limitations -- Create technical debt register -- Establish bug triage process -- Create incident response procedures -- Document system dependencies - -### 2. Business Risks -- Document business impact analysis -- Create business continuity procedures -- Establish communication plans -- Create stakeholder management plan -- Document compliance requirements -- Create data governance procedures -- Establish change management process -- Create training plans - -### 3. Operational Risks -- Create operational procedures -- Document support processes -- Establish escalation procedures -- Create monitoring procedures -- Document backup procedures -- Create disaster recovery plans -- Establish SLA monitoring -- Create capacity management plans diff --git a/vb-migration/migration-steps.md b/vb-migration/migration-steps.md deleted file mode 100644 index cf09000..0000000 --- a/vb-migration/migration-steps.md +++ /dev/null @@ -1,221 +0,0 @@ -# VB.NET to C# Migration Guide - -## Migration Sequence - Important! - -### Recommended Order of Migration -The migration should be performed in two distinct phases to minimize complications and ensure a smooth transition: - -1. **First Phase: .NET Framework to .NET 8 Migration (Stay in VB.NET)** - - Focus only on framework compatibility - - Keep the original VB.NET language - - Use .NET Upgrade Assistant - - Test thoroughly before proceeding - -2. **Second Phase: VB.NET to C# Conversion** - - Convert the working .NET 8 VB.NET code to C# - - Use local code conversion tools - - Apply C# best practices - - Final testing and optimization - -### Rationale for This Sequence -- Separates framework issues from language syntax issues -- Easier debugging and problem isolation -- Framework migration tools work better with VB.NET -- Allows parallel testing between versions -- Reduces complexity of each migration step - -### Example Migration Path -``` -Starting Point: VB.NET on .NET Framework 4.7.1 -↓ -Step 1: VB.NET on .NET 8 (framework migration) -↓ -Step 2: C# on .NET 8 (language conversion) -``` - -## AI-Assisted Migration Support -### Available AI Tools -1. **Claude** - - Code analysis and review - - Pattern modernization suggestions - - Documentation generation - - Error resolution - - Test case generation - - Code optimization suggestions - -2. **ChatGPT** - - Code conversion assistance - - Modern pattern suggestions - - Testing strategy suggestions - - Documentation help - -3. **Windsurf** - - Code completion - - Pattern suggestions - - Security checks - - Best practice recommendations - -## Primary Migration Tools - -### 1. .NET Upgrade Assistant (Free) -#### Features -- Official Microsoft tool -- Command-line interface -- Framework upgrade automation -- Package dependency updates -- Configuration file updates - -#### Installation -```bash -dotnet tool install -g upgrade-assistant -``` - -#### Usage for Framework Migration -```bash -# Analyze your solution -upgrade-assistant analyze your-solution.sln - -# Perform the upgrade -upgrade-assistant upgrade your-solution.sln -``` - -### 2. ICSharpCode.CodeConverter (Free, Open Source) -#### Features -- Built on Roslyn -- Command-line and Visual Studio integration -- Community-supported -- Regular updates -- Batch processing capability - -#### Installation -```bash -dotnet tool install --global ICSharpCode.CodeConverter.Cli -``` - -### 3. Visual Studio Built-in Tools (Free with Community Edition) -#### Features -- Code analysis tools -- Refactoring capabilities -- Project system tools -- Framework compatibility checking -- IntelliSense support - -## Detailed Migration Steps with AI Enhancement - -### 1. Preparation Phase -1. Analyze current codebase - - Document dependencies - - Identify framework-specific code - - List external packages - - Note VB.NET specific features - - **AI Enhancement**: - - Use Claude to analyze code patterns and identify potential migration challenges - - Use ChatGPT to create a detailed dependency map - - Use Windsurf to identify outdated patterns - ``` - Example prompt for Claude: "Analyze this VB.NET code and identify: - 1. Framework-specific dependencies - 2. Outdated patterns that should be modernized - 3. Potential migration challenges" - ``` - -2. Setup Environment - - Install Visual Studio Community Edition - - Install .NET Upgrade Assistant - - Install ICSharpCode.CodeConverter - - Set up version control - - Create backup of all code - -3. Plan Migration Strategy - - Identify smallest/simplest libraries to start - - Create test cases for validation - - Document current functionality - - Set up continuous integration - - **AI Enhancement**: - - Use Claude or ChatGPT to generate test cases - - Use Windsurf for security considerations - ``` - Example prompt for ChatGPT: "Based on this code, generate: - 1. Unit test scenarios - 2. Integration test cases - 3. Documentation structure" - ``` - -### 2. Framework Migration Phase (Step 1) -1. Framework Update - - Run .NET Upgrade Assistant analysis - - Review suggested changes - - Update package references - - Fix compatibility issues - - **AI Enhancement**: - - Use Claude to review upgrade-assistant suggestions - - Use Windsurf for security implications - ``` - Example prompt: "Review these .NET Framework 4.7.1 configuration settings - and suggest equivalent .NET 8 configurations" - ``` - -[Continue with all sections as before, but replace tool references with only Claude, ChatGPT, and Windsurf...] - -## AI-Assisted Best Practices - -### Code Review Enhancement -Use AI tools to: -- Claude for code quality and modernization -- ChatGPT for pattern suggestions -- Windsurf for security checks -``` -Example prompt for Claude: "Review this converted C# code for: -1. Potential bugs -2. Performance issues -3. Modern C# feature opportunities" -``` - -### Testing Strategy Enhancement -Use AI tools to: -- Claude for test case generation -- ChatGPT for edge case identification -- Windsurf for security test scenarios -``` -Example prompt for ChatGPT: "For this business logic, suggest: -1. Key test scenarios -2. Edge cases -3. Test data examples" -``` - -### Documentation Enhancement -Use AI tools to: -- Claude for technical documentation -- ChatGPT for usage examples -- Windsurf for security documentation -``` -Example prompt for Claude: "Create documentation for this migrated code including: -1. API reference -2. Migration decisions -3. Usage examples" -``` - -## Conclusion - -A successful migration can be achieved by: -- Following the correct migration sequence (Framework first, then Language) -- Leveraging specified AI tools effectively -- Using local conversion tools -- Conducting thorough testing -- Maintaining good documentation - -### AI Tool Best Practices -1. Always review AI-generated code -2. Test all suggestions thoroughly -3. Use AI tools iteratively for improvements -4. Keep security in mind when sharing code with AI tools -5. Document which parts were AI-assisted for future reference -6. Use each AI tool for its strengths: - - Claude: Code analysis and modernization - - ChatGPT: Pattern suggestions and documentation - - Windsurf: Security and best practices - -Start with a small pilot project to validate the process and AI tool effectiveness before proceeding with the full migration. -- 2.45.2 From 4da8a0bd048bfb3f99e3e9b7fc2d246f4a77a7b0 Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Thu, 30 Jan 2025 22:00:43 -0500 Subject: [PATCH 07/31] Improve warnings and tests --- .../Security/UserSaltEncryptionMethodTests.cs | 135 ++++++++++++++++ .../Encryptors/UserSaltEncryptionMethod.vb | 28 +++- .../Security/Encryption.vb | 145 ++++++------------ .../Security/SecurityUtils.vb | 36 ++++- 4 files changed, 240 insertions(+), 104 deletions(-) diff --git a/vb-migration/Strata.Base.Internal.Tests/Security/UserSaltEncryptionMethodTests.cs b/vb-migration/Strata.Base.Internal.Tests/Security/UserSaltEncryptionMethodTests.cs index 2c2e20a..014482b 100644 --- a/vb-migration/Strata.Base.Internal.Tests/Security/UserSaltEncryptionMethodTests.cs +++ b/vb-migration/Strata.Base.Internal.Tests/Security/UserSaltEncryptionMethodTests.cs @@ -2,6 +2,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Strata.Base.Internal.Encryptors; using System; using System.Configuration; +using System.Text; namespace Strata.Base.Internal.Tests.Security { @@ -116,5 +117,139 @@ namespace Strata.Base.Internal.Tests.Security // Assert Assert.AreEqual(24, decodedBytes.Length, "Output should be 24 bytes (192 bits)"); } + + [TestMethod] + public void Encode_WithEmptyPassword_ReturnsValidHash() + { + // Arrange + var encryptor = new UserSaltEncryptionMethod(); + + // Act + string result = encryptor.Encode(TestUsername, TestOrgPin, "", TestUserGuid, TestSalt); + + // Assert + Assert.IsFalse(string.IsNullOrEmpty(result), "Empty password should still produce a hash"); + Assert.AreEqual(24, Convert.FromBase64String(result).Length, "Hash should still be 24 bytes"); + } + + [TestMethod] + public void Encode_WithEmptySalt_ReturnsValidHash() + { + // Arrange + var encryptor = new UserSaltEncryptionMethod(); + + // Act + string result = encryptor.Encode(TestUsername, TestOrgPin, TestPassword, TestUserGuid, ""); + + // Assert + Assert.IsFalse(string.IsNullOrEmpty(result), "Empty salt should still produce a hash"); + Assert.AreEqual(24, Convert.FromBase64String(result).Length, "Hash should still be 24 bytes"); + } + + [TestMethod] + public void Encode_WithLongPassword_HandlesCorrectly() + { + // Arrange + var encryptor = new UserSaltEncryptionMethod(); + string longPassword = new string('a', 1000000); // 1MB password + + // Act + string result = encryptor.Encode(TestUsername, TestOrgPin, longPassword, TestUserGuid, TestSalt); + + // Assert + Assert.IsFalse(string.IsNullOrEmpty(result), "Long password should produce a hash"); + Assert.AreEqual(24, Convert.FromBase64String(result).Length, "Hash should still be 24 bytes"); + } + + [TestMethod] + public void Encode_WithLongSalt_HandlesCorrectly() + { + // Arrange + var encryptor = new UserSaltEncryptionMethod(); + string longSalt = new string('a', 1000000); // 1MB salt + + // Act + string result = encryptor.Encode(TestUsername, TestOrgPin, TestPassword, TestUserGuid, longSalt); + + // Assert + Assert.IsFalse(string.IsNullOrEmpty(result), "Long salt should produce a hash"); + Assert.AreEqual(24, Convert.FromBase64String(result).Length, "Hash should still be 24 bytes"); + } + + [TestMethod] + public void Encode_WithSpecialCharacters_HandlesCorrectly() + { + // Arrange + var encryptor = new UserSaltEncryptionMethod(); + string specialCharsPassword = "!@#$%^&*()_+-=[]{}|;:'\",.<>?/~`"; + string specialCharsSalt = "!@#$%^&*()_+-=[]{}|;:'\",.<>?/~`"; + + // Act + string result = encryptor.Encode(TestUsername, TestOrgPin, specialCharsPassword, TestUserGuid, specialCharsSalt); + + // Assert + Assert.IsFalse(string.IsNullOrEmpty(result), "Special characters should produce a hash"); + Assert.AreEqual(24, Convert.FromBase64String(result).Length, "Hash should still be 24 bytes"); + } + + [TestMethod] + public void Encode_WithUnicodeCharacters_HandlesCorrectly() + { + // Arrange + var encryptor = new UserSaltEncryptionMethod(); + string unicodePassword = "Hello 世界! Привет мир! 안녕하세요!"; + string unicodeSalt = "Salt 世界! Соль! 소금!"; + + // Act + string result = encryptor.Encode(TestUsername, TestOrgPin, unicodePassword, TestUserGuid, unicodeSalt); + + // Assert + Assert.IsFalse(string.IsNullOrEmpty(result), "Unicode characters should produce a hash"); + Assert.AreEqual(24, Convert.FromBase64String(result).Length, "Hash should still be 24 bytes"); + } + + [TestMethod] + public void Encode_WithNullSalt_ThrowsArgumentNullException() + { + // Arrange + var encryptor = new UserSaltEncryptionMethod(); + + // Assert + Assert.ThrowsException(() => + encryptor.Encode(TestUsername, TestOrgPin, TestPassword, TestUserGuid, null)); + } + + [TestMethod] + public void Encode_WithNullPassword_ThrowsArgumentNullException() + { + // Arrange + var encryptor = new UserSaltEncryptionMethod(); + + // Assert + Assert.ThrowsException(() => + encryptor.Encode(TestUsername, TestOrgPin, null, TestUserGuid, TestSalt)); + } + + [TestMethod] + public void Encode_WithNullUsername_ThrowsArgumentNullException() + { + // Arrange + var encryptor = new UserSaltEncryptionMethod(); + + // Assert + Assert.ThrowsException(() => + encryptor.Encode(null, TestOrgPin, TestPassword, TestUserGuid, TestSalt)); + } + + [TestMethod] + public void Encode_WithNullOrgPin_ThrowsArgumentNullException() + { + // Arrange + var encryptor = new UserSaltEncryptionMethod(); + + // Assert + Assert.ThrowsException(() => + encryptor.Encode(TestUsername, null, TestPassword, TestUserGuid, TestSalt)); + } } } diff --git a/vb-migration/Strata.Base.Internal/Encryptors/UserSaltEncryptionMethod.vb b/vb-migration/Strata.Base.Internal/Encryptors/UserSaltEncryptionMethod.vb index a40ec84..885c1e3 100644 --- a/vb-migration/Strata.Base.Internal/Encryptors/UserSaltEncryptionMethod.vb +++ b/vb-migration/Strata.Base.Internal/Encryptors/UserSaltEncryptionMethod.vb @@ -17,16 +17,38 @@ Namespace Encryptors #Region " Methods " Public Function Encode(ByVal username As String, ByVal anOrgPin As String, ByVal aNewPassword As String, ByVal aUserGUID As System.Guid, aSalt As String) As String Implements IPasswordEncryptionMethod.Encode - Dim saltAndPepper As String = aSalt & ConfigurationManager.AppSettings(NameOf(StrataJazzOptions.UserSaltEncryptionKey)) + If username Is Nothing Then + Throw New ArgumentNullException(NameOf(username)) + End If + If anOrgPin Is Nothing Then + Throw New ArgumentNullException(NameOf(anOrgPin)) + End If + + If aNewPassword Is Nothing Then + Throw New ArgumentNullException(NameOf(aNewPassword)) + End If + + If aSalt Is Nothing Then + Throw New ArgumentNullException(NameOf(aSalt)) + End If + + ' Get encryption key from config, throw if not found + Dim encryptionKey As String = ConfigurationManager.AppSettings(NameOf(StrataJazzOptions.UserSaltEncryptionKey)) + If String.IsNullOrEmpty(encryptionKey) Then + Throw New ConfigurationErrorsException("UserSaltEncryptionKey not found in configuration") + End If + + ' Combine salt with encryption key + Dim saltAndPepper As String = aSalt & encryptionKey + + ' Use UTF8 encoding to properly handle Unicode characters Using deriveBytes As Rfc2898DeriveBytes = New Rfc2898DeriveBytes(aNewPassword, Encoding.UTF8.GetBytes(saltAndPepper), NUMBER_ITERATIONS, HashAlgorithmName.SHA256) Dim password As Byte() = deriveBytes.GetBytes(24) - Return Convert.ToBase64String(password) End Using End Function - #End Region End Class diff --git a/vb-migration/Strata.Base.Internal/Security/Encryption.vb b/vb-migration/Strata.Base.Internal/Security/Encryption.vb index 1bf72b1..42880cc 100644 --- a/vb-migration/Strata.Base.Internal/Security/Encryption.vb +++ b/vb-migration/Strata.Base.Internal/Security/Encryption.vb @@ -19,10 +19,6 @@ Namespace EncryptionUtils ''' Type of hash; some are security oriented, others are fast and simple ''' Friend Enum Provider - ''' - ''' Secure Hashing Algorithm provider, SHA-1 variant, 160-bit - ''' - SHA1 ''' ''' Secure Hashing Algorithm provider, SHA-2 variant, 256-bit ''' @@ -35,10 +31,6 @@ Namespace EncryptionUtils ''' Secure Hashing Algorithm provider, SHA-2 variant, 512-bit ''' SHA512 - ''' - ''' Message Digest algorithm 5, 128-bit - ''' - MD5 End Enum Private _Hash As HashAlgorithm @@ -52,10 +44,6 @@ Namespace EncryptionUtils ''' Friend Sub New(ByVal p As Provider) Select Case p - Case Provider.MD5 - _Hash = MD5.Create() - Case Provider.SHA1 - _Hash = SHA1.Create() Case Provider.SHA256 _Hash = SHA256.Create() Case Provider.SHA384 @@ -126,21 +114,9 @@ Namespace EncryptionUtils Private Const _BufferSize As Integer = 2048 Friend Enum Provider - - MD5 - - SHA1 - SHA256 - SHA384 - SHA512 - - DES - - RC2 - - Rijndael - - TripleDES + ''' + ''' Advanced Encryption Standard (AES) provider + ''' AES End Enum @@ -158,18 +134,7 @@ Namespace EncryptionUtils ''' Instantiates a new symmetric encryption object using the specified provider. ''' Friend Sub New(ByVal provider As Provider, Optional ByVal useDefaultInitializationVector As Boolean = True) - Select Case provider - Case Provider.DES - _crypto = DES.Create() - Case Provider.RC2 - _crypto = RC2.Create() - Case Provider.Rijndael, Provider.AES - _crypto = Aes.Create() - Case Provider.TripleDES - _crypto = TripleDES.Create() - Case Else - _crypto = Aes.Create() ' Default to AES for unknown providers - End Select + _crypto = Aes.Create() ' Always use AES as it's the most secure option '-- make sure key and IV are always set, no matter what Me.Key = RandomKey() @@ -417,7 +382,6 @@ Namespace EncryptionUtils ''' represents Hex, Byte, Base64, or String data to encrypt/decrypt; ''' use the .Text property to set/get a string representation ''' use the .Hex property to set/get a string-based Hexadecimal representation - ''' use the .Base64 to set/get a string-based Base64 representation ''' Friend Class Data Private _b As Byte() = Nothing @@ -425,20 +389,10 @@ Namespace EncryptionUtils Private _MinBytes As Integer = 0 Private _StepBytes As Integer = 0 - ''' - ''' Determines the default text encoding across ALL Data instances - ''' - Friend Shared DefaultEncoding As Text.Encoding - - Shared Sub New() - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance) - DefaultEncoding = System.Text.Encoding.GetEncoding("Windows-1252") - End Sub - ''' ''' Determines the default text encoding for this Data instance ''' - Friend Encoding As Text.Encoding = DefaultEncoding + Private _encoding As System.Text.Encoding = System.Text.Encoding.UTF8 ''' ''' Creates new, empty encryption data @@ -455,9 +409,12 @@ Namespace EncryptionUtils ''' ''' Creates new encryption data with the specified string; - ''' will be converted to byte array using default encoding + ''' will be converted to byte array using UTF8 encoding ''' Friend Sub New(ByVal s As String) + If s Is Nothing Then + Throw New ArgumentNullException(NameOf(s)) + End If Me.Text = s End Sub @@ -466,7 +423,13 @@ Namespace EncryptionUtils ''' specified encoding to convert the string to a byte array. ''' Friend Sub New(ByVal s As String, ByVal encoding As System.Text.Encoding) - Me.Encoding = encoding + If s Is Nothing Then + Throw New ArgumentNullException(NameOf(s)) + End If + If encoding Is Nothing Then + Throw New ArgumentNullException(NameOf(encoding)) + End If + _encoding = encoding Me.Text = s End Sub @@ -563,20 +526,22 @@ Namespace EncryptionUtils ''' Friend Property Bytes() As Byte() Get - If _MaxBytes > 0 Then - If _b.Length > _MaxBytes Then - Dim b(_MaxBytes - 1) As Byte - Array.Copy(_b, b, b.Length) - _b = b - End If + If _b Is Nothing Then + Return Array.Empty(Of Byte)() End If - If _MinBytes > 0 Then - If _b.Length < _MinBytes Then - Dim b(_MinBytes - 1) As Byte - Array.Copy(_b, b, _b.Length) - _b = b - End If + + If _MaxBytes > 0 AndAlso _b.Length > _MaxBytes Then + Dim b(_MaxBytes - 1) As Byte + Array.Copy(_b, b, b.Length) + _b = b End If + + If _MinBytes > 0 AndAlso _b.Length < _MinBytes Then + Dim b(_MinBytes - 1) As Byte + Array.Copy(_b, b, _b.Length) + _b = b + End If + Return _b End Get Set(ByVal Value As Byte()) @@ -585,26 +550,31 @@ Namespace EncryptionUtils End Property ''' - ''' Sets or returns text representation of bytes using the default text encoding + ''' Sets or returns text representation of bytes using UTF8 encoding ''' Friend Property Text() As String Get - If _b Is Nothing Then - Return "" - Else - '-- need to handle nulls here; oddly, C# will happily convert - '-- nulls into the string whereas VB stops converting at the - '-- first null! + If _b Is Nothing OrElse _b.Length = 0 Then + Return String.Empty + End If + + Try + Return _encoding.GetString(_b) + Catch ex As Exception + ' If there's an encoding error, try to salvage what we can Dim i As Integer = Array.IndexOf(_b, CType(0, Byte)) If i >= 0 Then - Return Me.Encoding.GetString(_b, 0, i) - Else - Return Me.Encoding.GetString(_b) + Return _encoding.GetString(_b, 0, i) End If - End If + Throw + End Try End Get Set(ByVal Value As String) - _b = Me.Encoding.GetBytes(Value) + If Value Is Nothing Then + _b = Array.Empty(Of Byte)() + Else + _b = _encoding.GetBytes(Value) + End If End Set End Property @@ -632,27 +602,6 @@ Namespace EncryptionUtils End Set End Property - ''' - ''' Returns text representation of bytes using the default text encoding - ''' - Friend Shadows Function ToString() As String - Return Me.Text - End Function - - ''' - ''' returns Base64 string representation of this data - ''' - Friend Function ToBase64() As String - Return Me.Base64 - End Function - - ''' - ''' returns Hex string representation of this data - ''' - Friend Function ToHex() As String - Return Me.Hex - End Function - End Class #End Region diff --git a/vb-migration/Strata.Base.Internal/Security/SecurityUtils.vb b/vb-migration/Strata.Base.Internal/Security/SecurityUtils.vb index c2030ac..0127e7b 100644 --- a/vb-migration/Strata.Base.Internal/Security/SecurityUtils.vb +++ b/vb-migration/Strata.Base.Internal/Security/SecurityUtils.vb @@ -8,6 +8,10 @@ Public Class SecurityUtils #Region " Methods " Private Shared Function PadKey(key As String) As String + If key Is Nothing Then + Throw New ArgumentNullException(NameOf(key)) + End If + Dim paddedKey As String = key & ENCRYPTION_KEY_SUFFIX If paddedKey.Length < KEY_SIZE_BYTES Then paddedKey = paddedKey.PadRight(KEY_SIZE_BYTES, "X"c) @@ -18,13 +22,39 @@ Public Class SecurityUtils End Function Public Shared Function EncryptValue(value As String, key As String) As String - Dim encryption As New EncryptionUtils.SymmetricEncryptor(EncryptionUtils.SymmetricEncryptor.Provider.Rijndael) + If value Is Nothing Then + Return Nothing + End If - Return encryption.Encrypt(New EncryptionUtils.Data(value), New EncryptionUtils.Data(PadKey(key))).ToBase64 + If String.IsNullOrEmpty(value) Then + Return String.Empty + End If + + If key Is Nothing Then + Throw New ArgumentNullException(NameOf(key)) + End If + + ' Create encryptor with default IV + Dim encryption As New EncryptionUtils.SymmetricEncryptor(EncryptionUtils.SymmetricEncryptor.Provider.AES) + + Dim result = encryption.Encrypt(New EncryptionUtils.Data(value), New EncryptionUtils.Data(PadKey(key))) + Return result.Base64 End Function Public Shared Function DecryptValue(encryptedValue As String, key As String) As String - Dim encryption As New EncryptionUtils.SymmetricEncryptor(EncryptionUtils.SymmetricEncryptor.Provider.Rijndael) + If encryptedValue Is Nothing Then + Return Nothing + End If + + If String.IsNullOrEmpty(encryptedValue) Then + Return String.Empty + End If + + If key Is Nothing Then + Throw New ArgumentNullException(NameOf(key)) + End If + + Dim encryption As New EncryptionUtils.SymmetricEncryptor(EncryptionUtils.SymmetricEncryptor.Provider.AES) ' note EncryptValue returns Base64 string so we need to initialized encryptedData as Base64 Dim encryptedData As EncryptionUtils.Data = New EncryptionUtils.Data() -- 2.45.2 From 729b7422de3a2e7019ce7470fbf4a0031ce7e070 Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Thu, 30 Jan 2025 22:34:02 -0500 Subject: [PATCH 08/31] Configure test coverage --- .../Security/SecurityUtilsTests.cs | 109 +++++++++++++----- .../Strata.Base.Internal.Tests.csproj | 5 +- vb-migration/coverage.runsettings | 18 +++ 3 files changed, 101 insertions(+), 31 deletions(-) create mode 100644 vb-migration/coverage.runsettings diff --git a/vb-migration/Strata.Base.Internal.Tests/Security/SecurityUtilsTests.cs b/vb-migration/Strata.Base.Internal.Tests/Security/SecurityUtilsTests.cs index edaf1e7..64490ac 100644 --- a/vb-migration/Strata.Base.Internal.Tests/Security/SecurityUtilsTests.cs +++ b/vb-migration/Strata.Base.Internal.Tests/Security/SecurityUtilsTests.cs @@ -1,4 +1,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Security.Cryptography; +using System; namespace Strata.Base.Internal.Tests.Security { @@ -9,50 +11,97 @@ namespace Strata.Base.Internal.Tests.Security public void EncryptValue_WithValidInput_EncryptsAndDecryptsCorrectly() { // Arrange - string originalValue = "Test sensitive data"; - string key = "MySecretKey123"; + string originalValue = "test value"; + string key = "testkey12345678"; // AES requires at least a 128-bit (16-byte) key // Act - string encrypted = SecurityUtils.EncryptValue(originalValue, key); - string decrypted = SecurityUtils.DecryptValue(encrypted, key); + string encryptedValue = SecurityUtils.EncryptValue(originalValue, key); + string decryptedValue = SecurityUtils.DecryptValue(encryptedValue, key); // Assert - Assert.AreNotEqual(originalValue, encrypted, "Encrypted value should be different from original"); - Assert.AreEqual(originalValue, decrypted, "Decrypted value should match original"); - } - - [TestMethod] - public void EncryptValue_WithEmptyString_HandlesCorrectly() - { - // Arrange - string originalValue = ""; - string key = "MySecretKey123"; - - // Act - string encrypted = SecurityUtils.EncryptValue(originalValue, key); - string decrypted = SecurityUtils.DecryptValue(encrypted, key); - - // Assert - Assert.AreNotEqual(originalValue, encrypted, "Encrypted value should be different from empty string"); - Assert.AreEqual(originalValue, decrypted, "Decrypted value should be empty string"); + Assert.AreEqual(originalValue, decryptedValue); } [TestMethod] public void DecryptValue_WithWrongKey_ThrowsException() { // Arrange - string originalValue = "Test sensitive data"; - string correctKey = "CorrectKey123"; - string wrongKey = "WrongKey123"; + string originalValue = "test value"; + string correctKey = "testkey12345678"; // AES requires at least a 128-bit (16-byte) key + string wrongKey = "wrongkey12345678"; // Act - string encrypted = SecurityUtils.EncryptValue(originalValue, correctKey); + string encryptedValue = SecurityUtils.EncryptValue(originalValue, correctKey); // Assert - Assert.ThrowsException( - () => SecurityUtils.DecryptValue(encrypted, wrongKey), - "Decryption with wrong key should throw CryptographicException" - ); + Assert.ThrowsException(() => SecurityUtils.DecryptValue(encryptedValue, wrongKey)); + } + + [TestMethod] + public void EncryptValue_WithEmptyString_ReturnsEmptyString() + { + // Arrange + string originalValue = ""; + string key = "testkey12345678"; + + // Act + string encryptedValue = SecurityUtils.EncryptValue(originalValue, key); + + // Assert + Assert.AreEqual("", encryptedValue); + } + + [TestMethod] + public void DecryptValue_WithEmptyString_ReturnsEmptyString() + { + // Arrange + string encryptedValue = ""; + string key = "testkey12345678"; + + // Act + string decryptedValue = SecurityUtils.DecryptValue(encryptedValue, key); + + // Assert + Assert.AreEqual("", decryptedValue); + } + + [TestMethod] + public void EncryptValue_WithNullString_ReturnsNull() + { + // Arrange + var originalValue = null as string; + string key = "testkey12345678"; + + // Act + string encryptedValue = SecurityUtils.EncryptValue(originalValue, key); + + // Assert + Assert.IsNull(encryptedValue); + } + + [TestMethod] + public void DecryptValue_WithNullString_ReturnsNull() + { + // Arrange + var encryptedValue = null as string; + string key = "testkey12345678"; + + // Act + string decryptedValue = SecurityUtils.DecryptValue(encryptedValue, key); + + // Assert + Assert.IsNull(decryptedValue); + } + + [TestMethod] + public void DecryptValue_WithInvalidBase64_ThrowsException() + { + // Arrange + string invalidBase64 = "Not a valid base64 string"; + string key = "testkey12345678"; + + // Assert + Assert.ThrowsException(() => SecurityUtils.DecryptValue(invalidBase64, key)); } } } diff --git a/vb-migration/Strata.Base.Internal.Tests/Strata.Base.Internal.Tests.csproj b/vb-migration/Strata.Base.Internal.Tests/Strata.Base.Internal.Tests.csproj index 6207637..7303785 100644 --- a/vb-migration/Strata.Base.Internal.Tests/Strata.Base.Internal.Tests.csproj +++ b/vb-migration/Strata.Base.Internal.Tests/Strata.Base.Internal.Tests.csproj @@ -14,7 +14,10 @@ - + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + diff --git a/vb-migration/coverage.runsettings b/vb-migration/coverage.runsettings new file mode 100644 index 0000000..9e63cc7 --- /dev/null +++ b/vb-migration/coverage.runsettings @@ -0,0 +1,18 @@ + + + + + + + cobertura + [Strata.*]* + ExcludeFromCodeCoverageAttribute + false + true + false + true + + + + + \ No newline at end of file -- 2.45.2 From 4534413761406070b74443202ea02d9afdd74a59 Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Thu, 30 Jan 2025 22:34:15 -0500 Subject: [PATCH 09/31] prevent coverage files in the repo --- .gitignore | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index f47d6e9..bdd1dc9 100644 --- a/.gitignore +++ b/.gitignore @@ -78,4 +78,27 @@ Backup*/ UpgradeLog*.XML UpgradeLog*.htm ServiceFabricBackup/ -*.rptproj.bak \ No newline at end of file +*.rptproj.bak + +# Code Coverage Files +*.coverage +coverage.json +coverage.info +coverage.xml +*.coveragexml +.coverage* + +# Test Results +TestResults/ +[Tt]est[Rr]esult*/ +*.trx +*.vstest.* + +# Coverage Reports +coverage-report/ +coverage/ +**/coverage/ +reports/ +lcov-report/ +htmlcov/ +.nyc_output/ \ No newline at end of file -- 2.45.2 From 60d518658175dbfa4f0026a142905c05afa2114b Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Thu, 30 Jan 2025 23:01:02 -0500 Subject: [PATCH 10/31] Include code coverage task --- .vscode/tasks.json | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 .vscode/tasks.json diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..6cee937 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,23 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "Generate Code Coverage Report", + "group": { + "kind": "test", + "isDefault": true + }, + "command": "powershell", + "type": "shell", + "args": [ + "-Command", + "& { dotnet test ./vb-migration/Strata.Base.Internal.Tests/Strata.Base.Internal.Tests.csproj /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura /p:CoverletOutput=./vb-migration/Strata.Base.Internal.Tests/TestResults/*/coverage.cobertura.xml; if ($?) { reportgenerator -reports:./vb-migration/Strata.Base.Internal.Tests/TestResults/*/coverage.cobertura.xml -targetdir:coverage-report -reporttypes:Html; Start-Process coverage-report/index.html } }" + ], + "presentation": { + "reveal": "always", + "panel": "new" + }, + "problemMatcher": [] + } + ] +} \ No newline at end of file -- 2.45.2 From b10f40dd289d54b19767d0256cc8e3ab18e0eff6 Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Fri, 31 Jan 2025 16:16:50 -0500 Subject: [PATCH 11/31] Migrate the Strata.Base.Internal to C# --- .../Strata.Base.Internal.Tests.csproj | 4 +- .../Strata.Base.Internal.Tests.csproj.bak | 27 + vb-migration/Strata.Base.Internal.sln | 12 +- vb-migration/Strata.Base.Internal.sln.bak | 30 + .../Encryptors/IPasswordEncryptionMethod.cs | 13 + .../Encryptors/UberEncryptionMethod.cs | 56 ++ .../Encryptors/UserGUIDEncryptionMethod.cs | 52 ++ .../Encryptors/UserSaltEncryptionMethod.cs | 65 ++ .../Strata.Base.Internal/InternalConstants.cs | 11 + .../My Project/Application.Designer.cs | 11 + .../My Project/AssemblyInfo.cs | 36 + .../MyNamespace.Static.1.Designer.cs | 468 ++++++++++ .../MyNamespace.Static.2.Designer.cs | 241 ++++++ .../MyNamespace.Static.3.Designer.cs | 16 + .../My Project/Resources.Designer.cs | 70 ++ .../My Project/Settings.Designer.cs | 100 +++ .../Security/Encryption.cs | 819 ++++++++++++++++++ .../Security/SecurityUtils.cs | 87 ++ .../Strata.Base.Internal.csproj | 82 ++ .../Strata.Base.Internal.xml | 301 +++++++ 20 files changed, 2493 insertions(+), 8 deletions(-) create mode 100644 vb-migration/Strata.Base.Internal.Tests/Strata.Base.Internal.Tests.csproj.bak create mode 100644 vb-migration/Strata.Base.Internal.sln.bak create mode 100644 vb-migration/Strata.Base.Internal/Encryptors/IPasswordEncryptionMethod.cs create mode 100644 vb-migration/Strata.Base.Internal/Encryptors/UberEncryptionMethod.cs create mode 100644 vb-migration/Strata.Base.Internal/Encryptors/UserGUIDEncryptionMethod.cs create mode 100644 vb-migration/Strata.Base.Internal/Encryptors/UserSaltEncryptionMethod.cs create mode 100644 vb-migration/Strata.Base.Internal/InternalConstants.cs create mode 100644 vb-migration/Strata.Base.Internal/My Project/Application.Designer.cs create mode 100644 vb-migration/Strata.Base.Internal/My Project/AssemblyInfo.cs create mode 100644 vb-migration/Strata.Base.Internal/My Project/MyNamespace.Static.1.Designer.cs create mode 100644 vb-migration/Strata.Base.Internal/My Project/MyNamespace.Static.2.Designer.cs create mode 100644 vb-migration/Strata.Base.Internal/My Project/MyNamespace.Static.3.Designer.cs create mode 100644 vb-migration/Strata.Base.Internal/My Project/Resources.Designer.cs create mode 100644 vb-migration/Strata.Base.Internal/My Project/Settings.Designer.cs create mode 100644 vb-migration/Strata.Base.Internal/Security/Encryption.cs create mode 100644 vb-migration/Strata.Base.Internal/Security/SecurityUtils.cs create mode 100644 vb-migration/Strata.Base.Internal/Strata.Base.Internal.csproj create mode 100644 vb-migration/Strata.Base.Internal/Strata.Base.Internal.xml diff --git a/vb-migration/Strata.Base.Internal.Tests/Strata.Base.Internal.Tests.csproj b/vb-migration/Strata.Base.Internal.Tests/Strata.Base.Internal.Tests.csproj index 7303785..d654950 100644 --- a/vb-migration/Strata.Base.Internal.Tests/Strata.Base.Internal.Tests.csproj +++ b/vb-migration/Strata.Base.Internal.Tests/Strata.Base.Internal.Tests.csproj @@ -1,4 +1,4 @@ - + net8.0-windows @@ -21,7 +21,7 @@ - + diff --git a/vb-migration/Strata.Base.Internal.Tests/Strata.Base.Internal.Tests.csproj.bak b/vb-migration/Strata.Base.Internal.Tests/Strata.Base.Internal.Tests.csproj.bak new file mode 100644 index 0000000..7303785 --- /dev/null +++ b/vb-migration/Strata.Base.Internal.Tests/Strata.Base.Internal.Tests.csproj.bak @@ -0,0 +1,27 @@ + + + + net8.0-windows + enable + enable + false + true + Strata.Base.Internal.Tests + Strata.Base.Internal.Tests + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + + + diff --git a/vb-migration/Strata.Base.Internal.sln b/vb-migration/Strata.Base.Internal.sln index 8ee16b9..a731175 100644 --- a/vb-migration/Strata.Base.Internal.sln +++ b/vb-migration/Strata.Base.Internal.sln @@ -1,8 +1,8 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 +Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.0.0 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Strata.Base.Internal", "Strata.Base.Internal\Strata.Base.Internal.vbproj", "{DB6C7DE1-AB63-4466-93A9-E5C3BDB561B4}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Strata.Base.Internal", "Strata.Base.Internal\Strata.Base.Internal.csproj", "{6948FC8A-673B-0B97-11F1-2FBDDF225514}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Strata.Base.Internal.Tests", "Strata.Base.Internal.Tests\Strata.Base.Internal.Tests.csproj", "{11111111-1111-1111-1111-111111111111}" EndProject @@ -12,10 +12,10 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {DB6C7DE1-AB63-4466-93A9-E5C3BDB561B4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {DB6C7DE1-AB63-4466-93A9-E5C3BDB561B4}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DB6C7DE1-AB63-4466-93A9-E5C3BDB561B4}.Release|Any CPU.ActiveCfg = Release|Any CPU - {DB6C7DE1-AB63-4466-93A9-E5C3BDB561B4}.Release|Any CPU.Build.0 = Release|Any CPU + {6948FC8A-673B-0B97-11F1-2FBDDF225514}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6948FC8A-673B-0B97-11F1-2FBDDF225514}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6948FC8A-673B-0B97-11F1-2FBDDF225514}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6948FC8A-673B-0B97-11F1-2FBDDF225514}.Release|Any CPU.Build.0 = Release|Any CPU {11111111-1111-1111-1111-111111111111}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {11111111-1111-1111-1111-111111111111}.Debug|Any CPU.Build.0 = Debug|Any CPU {11111111-1111-1111-1111-111111111111}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/vb-migration/Strata.Base.Internal.sln.bak b/vb-migration/Strata.Base.Internal.sln.bak new file mode 100644 index 0000000..8ee16b9 --- /dev/null +++ b/vb-migration/Strata.Base.Internal.sln.bak @@ -0,0 +1,30 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.0.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{778DAE3C-4631-46EA-AA77-85C1314464D9}") = "Strata.Base.Internal", "Strata.Base.Internal\Strata.Base.Internal.vbproj", "{DB6C7DE1-AB63-4466-93A9-E5C3BDB561B4}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Strata.Base.Internal.Tests", "Strata.Base.Internal.Tests\Strata.Base.Internal.Tests.csproj", "{11111111-1111-1111-1111-111111111111}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DB6C7DE1-AB63-4466-93A9-E5C3BDB561B4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DB6C7DE1-AB63-4466-93A9-E5C3BDB561B4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DB6C7DE1-AB63-4466-93A9-E5C3BDB561B4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DB6C7DE1-AB63-4466-93A9-E5C3BDB561B4}.Release|Any CPU.Build.0 = Release|Any CPU + {11111111-1111-1111-1111-111111111111}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {11111111-1111-1111-1111-111111111111}.Debug|Any CPU.Build.0 = Debug|Any CPU + {11111111-1111-1111-1111-111111111111}.Release|Any CPU.ActiveCfg = Release|Any CPU + {11111111-1111-1111-1111-111111111111}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {5C6D0F1F-E91E-4F6A-9E9F-B3E2DA7F2B4D} + EndGlobalSection +EndGlobal diff --git a/vb-migration/Strata.Base.Internal/Encryptors/IPasswordEncryptionMethod.cs b/vb-migration/Strata.Base.Internal/Encryptors/IPasswordEncryptionMethod.cs new file mode 100644 index 0000000..c82743f --- /dev/null +++ b/vb-migration/Strata.Base.Internal/Encryptors/IPasswordEncryptionMethod.cs @@ -0,0 +1,13 @@ +using System; + +namespace Strata.Base.Internal.Encryptors +{ + + public interface IPasswordEncryptionMethod + { + + string Encode(string username, string anOrgPin, string aNewPassword, Guid aUserGUID, string aSalt); + + } + +} \ No newline at end of file diff --git a/vb-migration/Strata.Base.Internal/Encryptors/UberEncryptionMethod.cs b/vb-migration/Strata.Base.Internal/Encryptors/UberEncryptionMethod.cs new file mode 100644 index 0000000..04b3010 --- /dev/null +++ b/vb-migration/Strata.Base.Internal/Encryptors/UberEncryptionMethod.cs @@ -0,0 +1,56 @@ +using System; +using System.Configuration; +using Microsoft.VisualBasic; +using Strata.Configuration.Client.Models.Jazz; + +namespace Strata.Base.Internal.Encryptors +{ + + public class UberEncryptionMethod : IPasswordEncryptionMethod + { + + public UberEncryptionMethod() + { + + } + + #region Methods + + public static string GetUberMonet(string anOrgPin) + { + return GetUberMonet(DateTime.Today, anOrgPin, ConfigurationManager.AppSettings[nameof(StrataJazzOptions.UberMonetKey)]); + } + + private static string GetUberMonet(DateTime aDate, string anOrgPIN, string aKey) + { + var ha = new EncryptionUtils.Hasher(EncryptionUtils.Hasher.Provider.SHA256); + + string lsHashBefore; + string lsResult; + + lsHashBefore = Strings.Format(aDate, "dd-MM-yyyy") + "-" + anOrgPIN + "-" + aKey; + + var d = new EncryptionUtils.Data(lsHashBefore); + + var dResult = ha.Calculate(d); + lsResult = Strings.Left(dResult.Hex, 6); + + ha = null; + + return lsResult; + } + + #endregion + + #region IPasswordEncryptionMethod + + public string Encode(string username, string anOrgPin, string aNewPassword, Guid aUserGUID, string aSalt) + { + return GetUberMonet(anOrgPin); + } + + #endregion + + } + +} \ No newline at end of file diff --git a/vb-migration/Strata.Base.Internal/Encryptors/UserGUIDEncryptionMethod.cs b/vb-migration/Strata.Base.Internal/Encryptors/UserGUIDEncryptionMethod.cs new file mode 100644 index 0000000..bbd50aa --- /dev/null +++ b/vb-migration/Strata.Base.Internal/Encryptors/UserGUIDEncryptionMethod.cs @@ -0,0 +1,52 @@ +using System; +using System.Configuration; +using System.Security.Cryptography; +using System.Text; +using Strata.Configuration.Client.Models.Jazz; + +namespace Strata.Base.Internal.Encryptors +{ + + public class UserGUIDEncryptionMethod : IPasswordEncryptionMethod + { + + #region Declarations + + private const int NUMBER_ITERATIONS = 100000; + + #endregion + + #region Methods + + public string Encode(string username, string anOrgPin, string aNewPassword, Guid aUserGUID, string aSalt) + { + string salt = aUserGUID.ToString() + ConfigurationManager.AppSettings[nameof(StrataJazzOptions.UserGuidEncryptionKey)]; + + string result = GetHashedValue(aNewPassword, salt); + for (int i = 1; i <= NUMBER_ITERATIONS; i++) + result = GetHashedValue(result); + + return result; + } + + private static string GetHashedValue(string aValue) + { + + // Create an instance of the sha encrypter + using (HashAlgorithm hasher = SHA256.Create()) + { + return Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(aValue))); + } + + } + + private static string GetHashedValue(string aValue, string aSalt) + { + return GetHashedValue(aValue + aSalt); + } + + #endregion + + } + +} \ No newline at end of file diff --git a/vb-migration/Strata.Base.Internal/Encryptors/UserSaltEncryptionMethod.cs b/vb-migration/Strata.Base.Internal/Encryptors/UserSaltEncryptionMethod.cs new file mode 100644 index 0000000..2992138 --- /dev/null +++ b/vb-migration/Strata.Base.Internal/Encryptors/UserSaltEncryptionMethod.cs @@ -0,0 +1,65 @@ +using System; +using System.Configuration; +using System.Security.Cryptography; +using System.Text; +using Strata.Configuration.Client.Models.Jazz; + +namespace Strata.Base.Internal.Encryptors +{ + + public class UserSaltEncryptionMethod : IPasswordEncryptionMethod + { + + #region Declarations + + private const int NUMBER_ITERATIONS = 100000; + + #endregion + + #region Methods + + public string Encode(string username, string anOrgPin, string aNewPassword, Guid aUserGUID, string aSalt) + { + if (username is null) + { + throw new ArgumentNullException(nameof(username)); + } + + if (anOrgPin is null) + { + throw new ArgumentNullException(nameof(anOrgPin)); + } + + if (aNewPassword is null) + { + throw new ArgumentNullException(nameof(aNewPassword)); + } + + if (aSalt is null) + { + throw new ArgumentNullException(nameof(aSalt)); + } + + // Get encryption key from config, throw if not found + string encryptionKey = ConfigurationManager.AppSettings[nameof(StrataJazzOptions.UserSaltEncryptionKey)]; + if (string.IsNullOrEmpty(encryptionKey)) + { + throw new ConfigurationErrorsException("UserSaltEncryptionKey not found in configuration"); + } + + // Combine salt with encryption key + string saltAndPepper = aSalt + encryptionKey; + + // Use UTF8 encoding to properly handle Unicode characters + using (var deriveBytes = new Rfc2898DeriveBytes(aNewPassword, Encoding.UTF8.GetBytes(saltAndPepper), NUMBER_ITERATIONS, HashAlgorithmName.SHA256)) + { + byte[] password = deriveBytes.GetBytes(24); + return Convert.ToBase64String(password); + } + } + + #endregion + + } + +} \ No newline at end of file diff --git a/vb-migration/Strata.Base.Internal/InternalConstants.cs b/vb-migration/Strata.Base.Internal/InternalConstants.cs new file mode 100644 index 0000000..df65057 --- /dev/null +++ b/vb-migration/Strata.Base.Internal/InternalConstants.cs @@ -0,0 +1,11 @@ + +namespace Strata.Base.Internal +{ + internal class InternalConstants + { + + // WARNING: This should always match the value in Strata.Base.Constants.XConstants.APPLICATION_VERSION + public const string APPLICATION_VERSION = "2025.11"; + + } +} \ No newline at end of file diff --git a/vb-migration/Strata.Base.Internal/My Project/Application.Designer.cs b/vb-migration/Strata.Base.Internal/My Project/Application.Designer.cs new file mode 100644 index 0000000..5e9e2a0 --- /dev/null +++ b/vb-migration/Strata.Base.Internal/My Project/Application.Designer.cs @@ -0,0 +1,11 @@ +// ------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +// ------------------------------------------------------------------------------ + + diff --git a/vb-migration/Strata.Base.Internal/My Project/AssemblyInfo.cs b/vb-migration/Strata.Base.Internal/My Project/AssemblyInfo.cs new file mode 100644 index 0000000..4c14cc9 --- /dev/null +++ b/vb-migration/Strata.Base.Internal/My Project/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System; +using System.Reflection; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. + +// Review the values of the assembly attributes + +[assembly: AssemblyTitle("Strata.Biz.Internal")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyCompany("Strata Decision Technology, LLC")] +[assembly: AssemblyProduct("Strata.Biz.Internal")] +[assembly: AssemblyCopyright("© 2006-2012 Strata Decision Technology, LLC")] +[assembly: AssemblyTrademark("")] + +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("dfd98904-a580-4549-90ea-95c9a5504029")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// + +[assembly: AssemblyVersion(Strata.Base.Internal.InternalConstants.APPLICATION_VERSION)] +[assembly: AssemblyFileVersion(Strata.Base.Internal.InternalConstants.APPLICATION_VERSION)] + diff --git a/vb-migration/Strata.Base.Internal/My Project/MyNamespace.Static.1.Designer.cs b/vb-migration/Strata.Base.Internal/My Project/MyNamespace.Static.1.Designer.cs new file mode 100644 index 0000000..aef3bd8 --- /dev/null +++ b/vb-migration/Strata.Base.Internal/My Project/MyNamespace.Static.1.Designer.cs @@ -0,0 +1,468 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Diagnostics; +using Microsoft.VisualBasic; + +/* TODO ERROR: Skipped IfDirectiveTrivia +#If TARGET = "module" AndAlso _MYTYPE = "" Then +*//* TODO ERROR: Skipped DisabledTextTrivia +#Const _MYTYPE="Empty" +*//* TODO ERROR: Skipped EndIfDirectiveTrivia +#End If +*/ +/* TODO ERROR: Skipped IfDirectiveTrivia +#If _MYTYPE = "WindowsForms" Then +*//* TODO ERROR: Skipped DisabledTextTrivia + +#Const _MYFORMS = True +#Const _MYWEBSERVICES = True +#Const _MYUSERTYPE = "Windows" +#Const _MYCOMPUTERTYPE = "Windows" +#Const _MYAPPLICATIONTYPE = "WindowsForms" + +*//* TODO ERROR: Skipped ElifDirectiveTrivia +#ElseIf _MYTYPE = "WindowsFormsWithCustomSubMain" Then +*//* TODO ERROR: Skipped DisabledTextTrivia + +#Const _MYFORMS = True +#Const _MYWEBSERVICES = True +#Const _MYUSERTYPE = "Windows" +#Const _MYCOMPUTERTYPE = "Windows" +#Const _MYAPPLICATIONTYPE = "Console" + +*//* TODO ERROR: Skipped ElifDirectiveTrivia +#ElseIf _MYTYPE = "Windows" OrElse _MYTYPE = "" Then +*/ +/* TODO ERROR: Skipped DefineDirectiveTrivia +#Const _MYWEBSERVICES = True +*//* TODO ERROR: Skipped DefineDirectiveTrivia +#Const _MYUSERTYPE = "Windows" +*//* TODO ERROR: Skipped DefineDirectiveTrivia +#Const _MYCOMPUTERTYPE = "Windows" +*//* TODO ERROR: Skipped DefineDirectiveTrivia +#Const _MYAPPLICATIONTYPE = "Windows" +*/ +/* TODO ERROR: Skipped ElifDirectiveTrivia +#ElseIf _MYTYPE = "Console" Then +*//* TODO ERROR: Skipped DisabledTextTrivia + +#Const _MYWEBSERVICES = True +#Const _MYUSERTYPE = "Windows" +#Const _MYCOMPUTERTYPE = "Windows" +#Const _MYAPPLICATIONTYPE = "Console" + +*//* TODO ERROR: Skipped ElifDirectiveTrivia +#ElseIf _MYTYPE = "Web" Then +*//* TODO ERROR: Skipped DisabledTextTrivia + +#Const _MYFORMS = False +#Const _MYWEBSERVICES = False +#Const _MYUSERTYPE = "Web" +#Const _MYCOMPUTERTYPE = "Web" + +*//* TODO ERROR: Skipped ElifDirectiveTrivia +#ElseIf _MYTYPE = "WebControl" Then +*//* TODO ERROR: Skipped DisabledTextTrivia + +#Const _MYFORMS = False +#Const _MYWEBSERVICES = True +#Const _MYUSERTYPE = "Web" +#Const _MYCOMPUTERTYPE = "Web" + +*//* TODO ERROR: Skipped ElifDirectiveTrivia +#ElseIf _MYTYPE = "Custom" Then +*//* TODO ERROR: Skipped DisabledTextTrivia + +*//* TODO ERROR: Skipped ElifDirectiveTrivia +#ElseIf _MYTYPE <> "Empty" Then +*//* TODO ERROR: Skipped DisabledTextTrivia + +#Const _MYTYPE = "Empty" + +*//* TODO ERROR: Skipped EndIfDirectiveTrivia +#End If +*/ +/* TODO ERROR: Skipped IfDirectiveTrivia +#If _MYTYPE <> "Empty" Then +*/ +namespace Strata.Base.Internal.My +{ + + /* TODO ERROR: Skipped IfDirectiveTrivia + #If _MYAPPLICATIONTYPE = "WindowsForms" OrElse _MYAPPLICATIONTYPE = "Windows" OrElse _MYAPPLICATIONTYPE = "Console" Then + */ + [System.CodeDom.Compiler.GeneratedCode("MyTemplate", "11.0.0.0")] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + + /* TODO ERROR: Skipped IfDirectiveTrivia + #If _MYAPPLICATIONTYPE = "WindowsForms" Then + *//* TODO ERROR: Skipped DisabledTextTrivia + Inherits Global.Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase + #If TARGET = "winexe" Then + _ + Friend Shared Sub Main(ByVal Args As String()) + Try + Global.System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(MyApplication.UseCompatibleTextRendering()) + Finally + End Try + My.Application.Run(Args) + End Sub + #End If + + *//* TODO ERROR: Skipped ElifDirectiveTrivia + #ElseIf _MYAPPLICATIONTYPE = "Windows" Then + */ + internal partial class MyApplication : Microsoft.VisualBasic.ApplicationServices.ApplicationBase + { + /* TODO ERROR: Skipped ElifDirectiveTrivia + #ElseIf _MYAPPLICATIONTYPE = "Console" Then + *//* TODO ERROR: Skipped DisabledTextTrivia + Inherits Global.Microsoft.VisualBasic.ApplicationServices.ConsoleApplicationBase + *//* TODO ERROR: Skipped EndIfDirectiveTrivia + #End If '_MYAPPLICATIONTYPE = "WindowsForms" + */ + } + + /* TODO ERROR: Skipped EndIfDirectiveTrivia + #End If '#If _MYAPPLICATIONTYPE = "WindowsForms" Or _MYAPPLICATIONTYPE = "Windows" or _MYAPPLICATIONTYPE = "Console" + */ + /* TODO ERROR: Skipped IfDirectiveTrivia + #If _MYCOMPUTERTYPE <> "" Then + */ + [System.CodeDom.Compiler.GeneratedCode("MyTemplate", "11.0.0.0")] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + + /* TODO ERROR: Skipped IfDirectiveTrivia + #If _MYCOMPUTERTYPE = "Windows" Then + */ + internal partial class MyComputer : Microsoft.VisualBasic.Devices.Computer + { + /* TODO ERROR: Skipped ElifDirectiveTrivia + #ElseIf _MYCOMPUTERTYPE = "Web" Then + *//* TODO ERROR: Skipped DisabledTextTrivia + Inherits Global.Microsoft.VisualBasic.Devices.ServerComputer + *//* TODO ERROR: Skipped EndIfDirectiveTrivia + #End If + */ + [DebuggerHidden()] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public MyComputer() : base() + { + } + } + /* TODO ERROR: Skipped EndIfDirectiveTrivia + #End If + */ + [HideModuleName()] + [System.CodeDom.Compiler.GeneratedCode("MyTemplate", "11.0.0.0")] + internal static class MyProject + { + + /* TODO ERROR: Skipped IfDirectiveTrivia + #If _MYCOMPUTERTYPE <> "" Then + */ + [System.ComponentModel.Design.HelpKeyword("My.Computer")] + internal static MyComputer Computer + { + [DebuggerHidden()] + get + { + return m_ComputerObjectProvider.GetInstance; + } + } + + private readonly static ThreadSafeObjectProvider m_ComputerObjectProvider = new ThreadSafeObjectProvider(); + /* TODO ERROR: Skipped EndIfDirectiveTrivia + #End If + */ + /* TODO ERROR: Skipped IfDirectiveTrivia + #If _MYAPPLICATIONTYPE = "Windows" Or _MYAPPLICATIONTYPE = "WindowsForms" Or _MYAPPLICATIONTYPE = "Console" Then + */ + [System.ComponentModel.Design.HelpKeyword("My.Application")] + internal static MyApplication Application + { + [DebuggerHidden()] + get + { + return m_AppObjectProvider.GetInstance; + } + } + private readonly static ThreadSafeObjectProvider m_AppObjectProvider = new ThreadSafeObjectProvider(); + /* TODO ERROR: Skipped EndIfDirectiveTrivia + #End If + */ + /* TODO ERROR: Skipped IfDirectiveTrivia + #If _MYUSERTYPE = "Windows" Then + */ + [System.ComponentModel.Design.HelpKeyword("My.User")] + internal static Microsoft.VisualBasic.ApplicationServices.User User + { + [DebuggerHidden()] + get + { + return m_UserObjectProvider.GetInstance; + } + } + private readonly static ThreadSafeObjectProvider m_UserObjectProvider = new ThreadSafeObjectProvider(); + /* TODO ERROR: Skipped ElifDirectiveTrivia + #ElseIf _MYUSERTYPE = "Web" Then + *//* TODO ERROR: Skipped DisabledTextTrivia + _ + Friend ReadOnly Property User() As Global.Microsoft.VisualBasic.ApplicationServices.WebUser + _ + Get + Return m_UserObjectProvider.GetInstance() + End Get + End Property + Private ReadOnly m_UserObjectProvider As New ThreadSafeObjectProvider(Of Global.Microsoft.VisualBasic.ApplicationServices.WebUser) + *//* TODO ERROR: Skipped EndIfDirectiveTrivia + #End If + */ + /* TODO ERROR: Skipped IfDirectiveTrivia + #If _MYFORMS = True Then + *//* TODO ERROR: Skipped DisabledTextTrivia + + #Const STARTUP_MY_FORM_FACTORY = "My.MyProject.Forms" + + _ + Friend ReadOnly Property Forms() As MyForms + _ + Get + Return m_MyFormsObjectProvider.GetInstance() + End Get + End Property + + _ + _ + Friend NotInheritable Class MyForms + _ + Private Shared Function Create__Instance__(Of T As {New, Global.System.Windows.Forms.Form})(ByVal Instance As T) As T + If Instance Is Nothing OrElse Instance.IsDisposed Then + If m_FormBeingCreated IsNot Nothing Then + If m_FormBeingCreated.ContainsKey(GetType(T)) = True Then + Throw New Global.System.InvalidOperationException(Global.Microsoft.VisualBasic.CompilerServices.Utils.GetResourceString("WinForms_RecursiveFormCreate")) + End If + Else + m_FormBeingCreated = New Global.System.Collections.Hashtable() + End If + m_FormBeingCreated.Add(GetType(T), Nothing) + Try + Return New T() + Catch ex As Global.System.Reflection.TargetInvocationException When ex.InnerException IsNot Nothing + Dim BetterMessage As String = Global.Microsoft.VisualBasic.CompilerServices.Utils.GetResourceString("WinForms_SeeInnerException", ex.InnerException.Message) + Throw New Global.System.InvalidOperationException(BetterMessage, ex.InnerException) + Finally + m_FormBeingCreated.Remove(GetType(T)) + End Try + Else + Return Instance + End If + End Function + + _ + Private Sub Dispose__Instance__(Of T As Global.System.Windows.Forms.Form)(ByRef instance As T) + instance.Dispose() + instance = Nothing + End Sub + + _ + _ + Public Sub New() + MyBase.New() + End Sub + + Private Shared m_FormBeingCreated As Global.System.Collections.Hashtable + + Public Overrides Function Equals(ByVal o As Object) As Boolean + Return MyBase.Equals(o) + End Function + Public Overrides Function GetHashCode() As Integer + Return MyBase.GetHashCode + End Function + _ + Friend Overloads Function [GetType]() As Global.System.Type + Return GetType(MyForms) + End Function + Public Overrides Function ToString() As String + Return MyBase.ToString + End Function + End Class + + Private m_MyFormsObjectProvider As New ThreadSafeObjectProvider(Of MyForms) + + *//* TODO ERROR: Skipped EndIfDirectiveTrivia + #End If + */ + /* TODO ERROR: Skipped IfDirectiveTrivia + #If _MYWEBSERVICES = True Then + */ + [System.ComponentModel.Design.HelpKeyword("My.WebServices")] + internal static MyWebServices WebServices + { + [DebuggerHidden()] + get + { + return m_MyWebServicesObjectProvider.GetInstance; + } + } + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + [MyGroupCollection("System.Web.Services.Protocols.SoapHttpClientProtocol", "Create__Instance__", "Dispose__Instance__", "")] + internal sealed class MyWebServices + { + + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + [DebuggerHidden()] + public override bool Equals(object o) + { + return base.Equals(o); + } + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + [DebuggerHidden()] + public override int GetHashCode() + { + return base.GetHashCode(); + } + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + [DebuggerHidden()] + internal new Type GetType() + { + return typeof(MyWebServices); + } + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + [DebuggerHidden()] + public override string ToString() + { + return base.ToString(); + } + + [DebuggerHidden()] + private static T Create__Instance__(T instance) where T : new() + { + if (instance is null) + { + return new T(); + } + else + { + return instance; + } + } + + [DebuggerHidden()] + private void Dispose__Instance__(ref T instance) + { + instance = default; + } + + [DebuggerHidden()] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public MyWebServices() : base() + { + } + } + + private readonly static ThreadSafeObjectProvider m_MyWebServicesObjectProvider = new ThreadSafeObjectProvider(); + /* TODO ERROR: Skipped EndIfDirectiveTrivia + #End If + */ + /* TODO ERROR: Skipped IfDirectiveTrivia + #If _MYTYPE = "Web" Then + *//* TODO ERROR: Skipped DisabledTextTrivia + + _ + Friend ReadOnly Property Request() As Global.System.Web.HttpRequest + _ + Get + Dim CurrentContext As Global.System.Web.HttpContext = Global.System.Web.HttpContext.Current + If CurrentContext IsNot Nothing Then + Return CurrentContext.Request + End If + Return Nothing + End Get + End Property + + _ + Friend ReadOnly Property Response() As Global.System.Web.HttpResponse + _ + Get + Dim CurrentContext As Global.System.Web.HttpContext = Global.System.Web.HttpContext.Current + If CurrentContext IsNot Nothing Then + Return CurrentContext.Response + End If + Return Nothing + End Get + End Property + + _ + Friend ReadOnly Property Log() As Global.Microsoft.VisualBasic.Logging.AspLog + _ + Get + Return m_LogObjectProvider.GetInstance() + End Get + End Property + + Private ReadOnly m_LogObjectProvider As New ThreadSafeObjectProvider(Of Global.Microsoft.VisualBasic.Logging.AspLog) + + *//* TODO ERROR: Skipped EndIfDirectiveTrivia + #End If '_MYTYPE="Web" + */ + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + [System.Runtime.InteropServices.ComVisible(false)] + internal sealed class ThreadSafeObjectProvider where T : new() + { + internal T GetInstance + { + /* TODO ERROR: Skipped IfDirectiveTrivia + #If TARGET = "library" Then + */ + [DebuggerHidden()] + get + { + var Value = m_Context.Value; + if (Value is null) + { + Value = new T(); + m_Context.Value = Value; + } + return Value; + } + /* TODO ERROR: Skipped ElseDirectiveTrivia + #Else + *//* TODO ERROR: Skipped DisabledTextTrivia + _ + Get + If m_ThreadStaticValue Is Nothing Then m_ThreadStaticValue = New T + Return m_ThreadStaticValue + End Get + *//* TODO ERROR: Skipped EndIfDirectiveTrivia + #End If + */ + } + + [DebuggerHidden()] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public ThreadSafeObjectProvider() : base() + { + } + + /* TODO ERROR: Skipped IfDirectiveTrivia + #If TARGET = "library" Then + */ + private readonly Microsoft.VisualBasic.MyServices.Internal.ContextValue m_Context = new Microsoft.VisualBasic.MyServices.Internal.ContextValue(); + /* TODO ERROR: Skipped ElseDirectiveTrivia + #Else + *//* TODO ERROR: Skipped DisabledTextTrivia + Private Shared m_ThreadStaticValue As T + *//* TODO ERROR: Skipped EndIfDirectiveTrivia + #End If + */ + } + } +} +/* TODO ERROR: Skipped EndIfDirectiveTrivia +#End If +*/ \ No newline at end of file diff --git a/vb-migration/Strata.Base.Internal/My Project/MyNamespace.Static.2.Designer.cs b/vb-migration/Strata.Base.Internal/My Project/MyNamespace.Static.2.Designer.cs new file mode 100644 index 0000000..6f0b8f2 --- /dev/null +++ b/vb-migration/Strata.Base.Internal/My Project/MyNamespace.Static.2.Designer.cs @@ -0,0 +1,241 @@ +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Xml.Linq; +using Microsoft.VisualBasic; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +// See Compiler::LoadXmlSolutionExtension +namespace Strata.Base.Internal.My +{ + [Embedded()] + [DebuggerNonUserCode()] + [System.Runtime.CompilerServices.CompilerGenerated()] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + internal sealed class InternalXmlHelper + { + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + private InternalXmlHelper() + { + } + public static string get_Value(IEnumerable source) + { + foreach (XElement item in source) + return item.Value; + return null; + } + + public static void set_Value(IEnumerable source, string value) + { + foreach (XElement item in source) + { + item.Value = value; + break; + } + } + public static string get_AttributeValue(IEnumerable source, XName name) + { + foreach (XElement item in source) + return (string)item.Attribute(name); + return null; + } + + public static void set_AttributeValue(IEnumerable source, XName name, string value) + { + foreach (XElement item in source) + { + item.SetAttributeValue(name, value); + break; + } + } + public static string get_AttributeValue(XElement source, XName name) + { + return (string)source.Attribute(name); + } + + public static void set_AttributeValue(XElement source, XName name, string value) + { + source.SetAttributeValue(name, value); + } + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public static XAttribute CreateAttribute(XName name, object value) + { + if (value is null) + { + return null; + } + return new XAttribute(name, value); + } + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public static XAttribute CreateNamespaceAttribute(XName name, XNamespace ns) + { + var a = new XAttribute(name, ns.NamespaceName); + a.AddAnnotation(ns); + return a; + } + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public static object RemoveNamespaceAttributes(string[] inScopePrefixes, XNamespace[] inScopeNs, List attributes, object obj) + { + if (obj is not null) + { + XElement elem = obj as XElement; + if (elem is not null) + { + return RemoveNamespaceAttributes(inScopePrefixes, inScopeNs, attributes, elem); + } + else + { + IEnumerable elems = obj as IEnumerable; + if (elems is not null) + { + return RemoveNamespaceAttributes(inScopePrefixes, inScopeNs, attributes, elems); + } + } + } + return obj; + } + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public static IEnumerable RemoveNamespaceAttributes(string[] inScopePrefixes, XNamespace[] inScopeNs, List attributes, IEnumerable obj) + { + if (obj is not null) + { + IEnumerable elems = obj as IEnumerable; + if (elems is not null) + { + return elems.Select(new RemoveNamespaceAttributesClosure(inScopePrefixes, inScopeNs, attributes).ProcessXElement); + } + else + { + return obj.Cast().Select(new RemoveNamespaceAttributesClosure(inScopePrefixes, inScopeNs, attributes).ProcessObject); + } + } + return obj; + } + [DebuggerNonUserCode()] + [System.Runtime.CompilerServices.CompilerGenerated()] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + private sealed class RemoveNamespaceAttributesClosure + { + private readonly string[] m_inScopePrefixes; + private readonly XNamespace[] m_inScopeNs; + private readonly List m_attributes; + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + internal RemoveNamespaceAttributesClosure(string[] inScopePrefixes, XNamespace[] inScopeNs, List attributes) + { + m_inScopePrefixes = inScopePrefixes; + m_inScopeNs = inScopeNs; + m_attributes = attributes; + } + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + internal XElement ProcessXElement(XElement elem) + { + return RemoveNamespaceAttributes(m_inScopePrefixes, m_inScopeNs, m_attributes, elem); + } + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + internal object ProcessObject(object obj) + { + XElement elem = obj as XElement; + if (elem is not null) + { + return RemoveNamespaceAttributes(m_inScopePrefixes, m_inScopeNs, m_attributes, elem); + } + else + { + return obj; + } + } + } + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public static XElement RemoveNamespaceAttributes(string[] inScopePrefixes, XNamespace[] inScopeNs, List attributes, XElement e) + { + if (e is not null) + { + var a = e.FirstAttribute; + + while (a is not null) + { + var nextA = a.NextAttribute; + + if (a.IsNamespaceDeclaration) + { + var ns = a.Annotation(); + string prefix = a.Name.LocalName; + + if (ns is not null) + { + if (inScopePrefixes is not null && inScopeNs is not null) + { + int lastIndex = inScopePrefixes.Length - 1; + + for (int i = 0, loopTo = lastIndex; i <= loopTo; i++) + { + string currentInScopePrefix = inScopePrefixes[i]; + var currentInScopeNs = inScopeNs[i]; + if (prefix.Equals(currentInScopePrefix)) + { + if (ns == currentInScopeNs) + { + // prefix and namespace match. Remove the unneeded ns attribute + a.Remove(); + } + + // prefix is in scope but refers to something else. Leave the ns attribute. + a = null; + break; + } + } + } + + if (a is not null) + { + // Prefix is not in scope + // Now check whether it's going to be in scope because it is in the attributes list + + if (attributes is not null) + { + int lastIndex = attributes.Count - 1; + for (int i = 0, loopTo1 = lastIndex; i <= loopTo1; i++) + { + var currentA = attributes[i]; + string currentInScopePrefix = currentA.Name.LocalName; + var currentInScopeNs = currentA.Annotation(); + if (currentInScopeNs is not null) + { + if (prefix.Equals(currentInScopePrefix)) + { + if (ns == currentInScopeNs) + { + // prefix and namespace match. Remove the unneeded ns attribute + a.Remove(); + } + + // prefix is in scope but refers to something else. Leave the ns attribute. + a = null; + break; + } + } + } + } + + if (a is not null) + { + // Prefix is definitely not in scope + a.Remove(); + // namespace is not defined either. Add this attributes list + attributes.Add(a); + } + } + } + } + + a = nextA; + } + } + return e; + } + + } +} \ No newline at end of file diff --git a/vb-migration/Strata.Base.Internal/My Project/MyNamespace.Static.3.Designer.cs b/vb-migration/Strata.Base.Internal/My Project/MyNamespace.Static.3.Designer.cs new file mode 100644 index 0000000..e39b420 --- /dev/null +++ b/vb-migration/Strata.Base.Internal/My Project/MyNamespace.Static.3.Designer.cs @@ -0,0 +1,16 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; + +namespace Microsoft.VisualBasic +{ + [Embedded()] + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Module | AttributeTargets.Assembly, Inherited = false)] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + [System.Runtime.CompilerServices.CompilerGenerated()] + internal sealed class Embedded : Attribute + { + } +} \ No newline at end of file diff --git a/vb-migration/Strata.Base.Internal/My Project/Resources.Designer.cs b/vb-migration/Strata.Base.Internal/My Project/Resources.Designer.cs new file mode 100644 index 0000000..31a80a9 --- /dev/null +++ b/vb-migration/Strata.Base.Internal/My Project/Resources.Designer.cs @@ -0,0 +1,70 @@ +// ------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +// ------------------------------------------------------------------------------ + + +using System.Diagnostics; +using Microsoft.VisualBasic; + +namespace Strata.Base.Internal.My.Resources +{ + + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + [System.CodeDom.Compiler.GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [DebuggerNonUserCode()] + [System.Runtime.CompilerServices.CompilerGenerated()] + [HideModuleName()] + internal static class Resources + { + + private static System.Resources.ResourceManager resourceMan; + + private static System.Globalization.CultureInfo resourceCulture; + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] + internal static System.Resources.ResourceManager ResourceManager + { + get + { + if (ReferenceEquals(resourceMan, null)) + { + var temp = new System.Resources.ResourceManager("Strata.Base.Internal.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] + internal static System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} \ No newline at end of file diff --git a/vb-migration/Strata.Base.Internal/My Project/Settings.Designer.cs b/vb-migration/Strata.Base.Internal/My Project/Settings.Designer.cs new file mode 100644 index 0000000..d591377 --- /dev/null +++ b/vb-migration/Strata.Base.Internal/My Project/Settings.Designer.cs @@ -0,0 +1,100 @@ +// ------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +// ------------------------------------------------------------------------------ + +using System.Diagnostics; +using Microsoft.VisualBasic; +using Microsoft.VisualBasic.CompilerServices; + + +namespace Strata.Base.Internal.My +{ + + [System.Runtime.CompilerServices.CompilerGenerated()] + [System.CodeDom.Compiler.GeneratedCode("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.12.0.0")] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] + internal sealed partial class MySettings : System.Configuration.ApplicationSettingsBase + { + + private static MySettings defaultInstance = (MySettings)Synchronized(new MySettings()); + + #region My.Settings Auto-Save Functionality + /* TODO ERROR: Skipped IfDirectiveTrivia + #If _MyType = "WindowsForms" Then + *//* TODO ERROR: Skipped DisabledTextTrivia + Private Shared addedHandler As Boolean + + Private Shared addedHandlerLockObject As New Object + + _ + Private Shared Sub AutoSaveSettings(sender As Global.System.Object, e As Global.System.EventArgs) + If My.Application.SaveMySettingsOnExit Then + My.Settings.Save() + End If + End Sub + *//* TODO ERROR: Skipped EndIfDirectiveTrivia + #End If + */ + #endregion + + public static MySettings Default + { + get + { + + /* TODO ERROR: Skipped IfDirectiveTrivia + #If _MyType = "WindowsForms" Then + *//* TODO ERROR: Skipped DisabledTextTrivia + If Not addedHandler Then + SyncLock addedHandlerLockObject + If Not addedHandler Then + AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings + addedHandler = True + End If + End SyncLock + End If + *//* TODO ERROR: Skipped EndIfDirectiveTrivia + #End If + */ + return defaultInstance; + } + } + + [System.Configuration.ApplicationScopedSetting()] + [DebuggerNonUserCode()] + [System.Configuration.DefaultSettingValue("Development")] + public string Environment + { + get + { + return Conversions.ToString(this["Environment"]); + } + } + } +} + +namespace Strata.Base.Internal.My +{ + + [HideModuleName()] + [DebuggerNonUserCode()] + [System.Runtime.CompilerServices.CompilerGenerated()] + internal static class MySettingsProperty + { + + [System.ComponentModel.Design.HelpKeyword("My.Settings")] + internal static MySettings Settings + { + get + { + return MySettings.Default; + } + } + } +} \ No newline at end of file diff --git a/vb-migration/Strata.Base.Internal/Security/Encryption.cs b/vb-migration/Strata.Base.Internal/Security/Encryption.cs new file mode 100644 index 0000000..7281e83 --- /dev/null +++ b/vb-migration/Strata.Base.Internal/Security/Encryption.cs @@ -0,0 +1,819 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; + +namespace Strata.Base.Internal.EncryptionUtils +{ + + #region Hash + + /// + /// Hash functions are fundamental to modern cryptography. These functions map binary + /// strings of an arbitrary length to small binary strings of a fixed length, known as + /// hash values. A cryptographic hash function has the property that it is computationally + /// infeasible to find two distinct inputs that hash to the same value. Hash functions + /// are commonly used with digital signatures and for data integrity. + /// + public class Hasher + { + + /// + /// Type of hash; some are security oriented, others are fast and simple + /// + internal enum Provider + { + /// + /// Secure Hashing Algorithm provider, SHA-2 variant, 256-bit + /// + SHA256, + /// + /// Secure Hashing Algorithm provider, SHA-2 variant, 384-bit + /// + SHA384, + /// + /// Secure Hashing Algorithm provider, SHA-2 variant, 512-bit + /// + SHA512 + } + + private HashAlgorithm _Hash; + private Data _HashValue = new Data(); + + internal Hasher() + { + } + + /// + /// Instantiate a new hash of the specified type + /// + internal Hasher(Provider p) + { + switch (p) + { + case Provider.SHA256: + { + _Hash = SHA256.Create(); + break; + } + case Provider.SHA384: + { + _Hash = SHA384.Create(); + break; + } + case Provider.SHA512: + { + _Hash = SHA512.Create(); + break; + } + + default: + { + _Hash = SHA256.Create(); // Default to SHA256 for unknown providers + break; + } + } + } + + /// + /// Returns the previously calculated hash + /// + internal Data Value + { + get + { + return _HashValue; + } + } + + /// + /// Calculates hash on a stream of arbitrary length + /// + internal Data Calculate(ref Stream s) + { + _HashValue.Bytes = _Hash.ComputeHash(s); + return _HashValue; + } + + /// + /// Calculates hash for fixed length + /// + internal Data Calculate(Data d) + { + return CalculatePrivate(d.Bytes); + } + + /// + /// Calculates hash for a string with a prefixed salt value. + /// A "salt" is random data prefixed to every hashed value to prevent + /// common dictionary attacks. + /// + internal Data Calculate(Data d, Data salt) + { + var nb = new byte[(d.Bytes.Length + salt.Bytes.Length)]; + salt.Bytes.CopyTo(nb, 0); + d.Bytes.CopyTo(nb, salt.Bytes.Length); + return CalculatePrivate(nb); + } + + /// + /// Calculates hash for an array of bytes + /// + private Data CalculatePrivate(byte[] b) + { + _HashValue.Bytes = _Hash.ComputeHash(b); + return _HashValue; + } + + } + #endregion + + #region Symmetric + + /// + /// Symmetric encryption uses a single key to encrypt and decrypt. + /// Both parties (encryptor and decryptor) must share the same secret key. + /// + internal class SymmetricEncryptor + { + + private const string _DefaultIntializationVector = "%1Az=-@qT"; + private const int _BufferSize = 2048; + + internal enum Provider + { + /// + /// Advanced Encryption Standard (AES) provider + /// + AES + } + + private Data _data; + private Data _key; + private Data _iv; + private SymmetricAlgorithm _crypto; + private byte[] _EncryptedBytes; + private bool _UseDefaultInitializationVector; + + private SymmetricEncryptor() + { + } + + /// + /// Instantiates a new symmetric encryption object using the specified provider. + /// + internal SymmetricEncryptor(Provider provider, bool useDefaultInitializationVector = true) + { + _crypto = Aes.Create(); // Always use AES as it's the most secure option + + // -- make sure key and IV are always set, no matter what + Key = RandomKey(); + if (useDefaultInitializationVector) + { + IntializationVector = new Data(_DefaultIntializationVector); + } + else + { + IntializationVector = RandomInitializationVector(); + } + } + + /// + /// Key size in bytes. We use the default key size for any given provider; if you + /// want to force a specific key size, set this property + /// + internal int KeySizeBytes + { + get + { + return _crypto.KeySize / 8; + } + set + { + _crypto.KeySize = value * 8; + _key.MaxBytes = value; + } + } + + /// + /// Key size in bits. We use the default key size for any given provider; if you + /// want to force a specific key size, set this property + /// + internal int KeySizeBits + { + get + { + return _crypto.KeySize; + } + set + { + _crypto.KeySize = value; + _key.MaxBits = value; + } + } + + /// + /// The key used to encrypt/decrypt data + /// + internal Data Key + { + get + { + return _key; + } + set + { + _key = value; + _key.MaxBytes = _crypto.LegalKeySizes[0].MaxSize / 8; + _key.MinBytes = _crypto.LegalKeySizes[0].MinSize / 8; + _key.StepBytes = _crypto.LegalKeySizes[0].SkipSize / 8; + } + } + + /// + /// Using the default Cipher Block Chaining (CBC) mode, all data blocks are processed using + /// the value derived from the previous block; the first data block has no previous data block + /// to use, so it needs an InitializationVector to feed the first block + /// + internal Data IntializationVector + { + get + { + return _iv; + } + set + { + _iv = value; + _iv.MaxBytes = _crypto.BlockSize / 8; + _iv.MinBytes = _crypto.BlockSize / 8; + } + } + + /// + /// generates a random Initialization Vector, if one was not provided + /// + internal Data RandomInitializationVector() + { + _crypto.GenerateIV(); + var d = new Data(_crypto.IV); + return d; + } + + /// + /// generates a random Key, if one was not provided + /// + internal Data RandomKey() + { + _crypto.GenerateKey(); + var d = new Data(_crypto.Key); + return d; + } + + /// + /// Ensures that _crypto object has valid Key and IV + /// prior to any attempt to encrypt/decrypt anything + /// + private void ValidateKeyAndIv(bool isEncrypting) + { + if (_key.IsEmpty) + { + if (isEncrypting) + { + _key = RandomKey(); + } + else + { + throw new CryptographicException("No key was provided for the decryption operation!"); + } + } + if (_iv.IsEmpty) + { + if (isEncrypting) + { + _iv = RandomInitializationVector(); + } + else + { + throw new CryptographicException("No initialization vector was provided for the decryption operation!"); + } + } + try + { + _crypto.Key = _key.Bytes; + _crypto.IV = _iv.Bytes; + } + catch (CryptographicException ex) + { + throw new CryptographicException("Invalid key or initialization vector.", ex); + } + } + + /// + /// Encrypts the specified Data using provided key + /// + internal Data Encrypt(Data d, Data key) + { + Key = key; + return Encrypt(d); + } + + /// + /// Encrypts the specified Data using preset key and preset initialization vector + /// + internal Data Encrypt(Data d) + { + var ms = new MemoryStream(); + + ValidateKeyAndIv(true); + + var cs = new CryptoStream(ms, _crypto.CreateEncryptor(), CryptoStreamMode.Write); + cs.Write(d.Bytes, 0, d.Bytes.Length); + cs.Close(); + ms.Close(); + + return new Data(ms.ToArray()); + } + + /// + /// Encrypts the stream to memory using provided key and provided initialization vector + /// + internal Data Encrypt(Stream s, Data key, Data iv) + { + IntializationVector = iv; + Key = key; + return Encrypt(s); + } + + /// + /// Encrypts the stream to memory using specified key + /// + internal Data Encrypt(Stream s, Data key) + { + Key = key; + return Encrypt(s); + } + + /// + /// Encrypts the specified stream to memory using preset key and preset initialization vector + /// + internal Data Encrypt(Stream s) + { + var ms = new MemoryStream(); + var b = new byte[2049]; + int i; + + ValidateKeyAndIv(true); + + var cs = new CryptoStream(ms, _crypto.CreateEncryptor(), CryptoStreamMode.Write); + i = s.Read(b, 0, _BufferSize); + while (i > 0) + { + cs.Write(b, 0, i); + i = s.Read(b, 0, _BufferSize); + } + + cs.Close(); + ms.Close(); + + return new Data(ms.ToArray()); + } + + /// + /// Decrypts the specified data using provided key and preset initialization vector + /// + internal Data Decrypt(Data encryptedData, Data key) + { + Key = key; + return Decrypt(encryptedData); + } + + /// + /// Decrypts the specified stream using provided key and preset initialization vector + /// + internal Data Decrypt(Stream encryptedStream, Data key) + { + Key = key; + return Decrypt(encryptedStream); + } + + /// + /// Decrypts the specified stream using preset key and preset initialization vector + /// + internal Data Decrypt(Stream encryptedStream) + { + var ms = new MemoryStream(); + var b = new byte[2049]; + + ValidateKeyAndIv(false); + var cs = new CryptoStream(encryptedStream, _crypto.CreateDecryptor(), CryptoStreamMode.Read); + + int i; + i = cs.Read(b, 0, _BufferSize); + + while (i > 0) + { + ms.Write(b, 0, i); + i = cs.Read(b, 0, _BufferSize); + } + cs.Close(); + ms.Close(); + + return new Data(ms.ToArray()); + } + + /// + /// Decrypts the specified data using preset key and preset initialization vector + /// + internal Data Decrypt(Data encryptedData) + { + using (var ms = new MemoryStream(encryptedData.Bytes, 0, encryptedData.Bytes.Length)) + { + ValidateKeyAndIv(false); + using (var cs = new CryptoStream(ms, _crypto.CreateDecryptor(), CryptoStreamMode.Read)) + { + using (var outputMs = new MemoryStream()) + { + try + { + cs.CopyTo(outputMs); + return new Data(outputMs.ToArray()); + } + catch (CryptographicException ex) + { + throw new CryptographicException("Unable to decrypt data. The provided key may be invalid.", ex); + } + } + } + } + } + + } + + #endregion + + #region Data + + /// + /// represents Hex, Byte, Base64, or String data to encrypt/decrypt; + /// use the .Text property to set/get a string representation + /// use the .Hex property to set/get a string-based Hexadecimal representation + /// + internal class Data + { + private byte[] _b = null; + private int _MaxBytes = 0; + private int _MinBytes = 0; + private int _StepBytes = 0; + + /// + /// Determines the default text encoding for this Data instance + /// + private Encoding _encoding = Encoding.UTF8; + + /// + /// Creates new, empty encryption data + /// + internal Data() + { + } + + /// + /// Creates new encryption data with the specified byte array + /// + internal Data(byte[] b) + { + _b = b; + } + + /// + /// Creates new encryption data with the specified string; + /// will be converted to byte array using UTF8 encoding + /// + internal Data(string s) + { + if (s is null) + { + throw new ArgumentNullException(nameof(s)); + } + Text = s; + } + + /// + /// Creates new encryption data using the specified string and the + /// specified encoding to convert the string to a byte array. + /// + internal Data(string s, Encoding encoding) + { + if (s is null) + { + throw new ArgumentNullException(nameof(s)); + } + if (encoding is null) + { + throw new ArgumentNullException(nameof(encoding)); + } + _encoding = encoding; + Text = s; + } + + /// + /// returns true if no data is present + /// + internal bool IsEmpty + { + get + { + if (_b is null) + { + return true; + } + if (_b.Length == 0) + { + return true; + } + return false; + } + } + + /// + /// allowed step interval, in bytes, for this data; if 0, no limit + /// + internal int StepBytes + { + get + { + return _StepBytes; + } + set + { + _StepBytes = value; + } + } + + /// + /// allowed step interval, in bits, for this data; if 0, no limit + /// + internal int StepBits + { + get + { + return _StepBytes * 8; + } + set + { + _StepBytes = value / 8; + } + } + + /// + /// minimum number of bytes allowed for this data; if 0, no limit + /// + internal int MinBytes + { + get + { + return _MinBytes; + } + set + { + _MinBytes = value; + } + } + + /// + /// minimum number of bits allowed for this data; if 0, no limit + /// + internal int MinBits + { + get + { + return _MinBytes * 8; + } + set + { + _MinBytes = value / 8; + } + } + + /// + /// maximum number of bytes allowed for this data; if 0, no limit + /// + internal int MaxBytes + { + get + { + return _MaxBytes; + } + set + { + _MaxBytes = value; + } + } + + /// + /// maximum number of bits allowed for this data; if 0, no limit + /// + internal int MaxBits + { + get + { + return _MaxBytes * 8; + } + set + { + _MaxBytes = value / 8; + } + } + + /// + /// Returns the byte representation of the data; + /// This will be padded to MinBytes and trimmed to MaxBytes as necessary! + /// + internal byte[] Bytes + { + get + { + if (_b is null) + { + return Array.Empty(); + } + + if (_MaxBytes > 0 && _b.Length > _MaxBytes) + { + var b = new byte[_MaxBytes]; + Array.Copy(_b, b, b.Length); + _b = b; + } + + if (_MinBytes > 0 && _b.Length < _MinBytes) + { + var b = new byte[_MinBytes]; + Array.Copy(_b, b, _b.Length); + _b = b; + } + + return _b; + } + set + { + _b = value; + } + } + + /// + /// Sets or returns text representation of bytes using UTF8 encoding + /// + internal string Text + { + get + { + if (_b is null || _b.Length == 0) + { + return string.Empty; + } + + try + { + return _encoding.GetString(_b); + } + catch (Exception ex) + { + // If there's an encoding error, try to salvage what we can + int i = Array.IndexOf(_b, (byte)0); + if (i >= 0) + { + return _encoding.GetString(_b, 0, i); + } + throw; + } + } + set + { + if (value is null) + { + _b = Array.Empty(); + } + else + { + _b = _encoding.GetBytes(value); + } + } + } + + /// + /// Sets or returns Hex string representation of this data + /// + internal string Hex + { + get + { + return Utils.ToHex(_b); + } + set + { + _b = Utils.FromHex(value); + } + } + + /// + /// Sets or returns Base64 string representation of this data + /// + internal string Base64 + { + get + { + return Utils.ToBase64(_b); + } + set + { + _b = Utils.FromBase64(value); + } + } + + } + + #endregion + + #region Utils + + /// + /// Friend class for shared utility methods used by multiple Encryption classes + /// + internal class Utils + { + + /// + /// converts an array of bytes to a string Hex representation + /// + internal static string ToHex(byte[] ba) + { + if (ba is null || ba.Length == 0) + { + return ""; + } + const string HexFormat = "{0:X2}"; + var sb = new StringBuilder(); + foreach (byte b in ba) + sb.Append(string.Format(HexFormat, b)); + return sb.ToString(); + } + + /// + /// converts from a string Hex representation to an array of bytes + /// + internal static byte[] FromHex(string hexEncoded) + { + if (hexEncoded is null || hexEncoded.Length == 0) + { + return null; + } + try + { + int l = Convert.ToInt32(hexEncoded.Length / 2d); + var b = new byte[l]; + for (int i = 0, loopTo = l - 1; i <= loopTo; i++) + b[i] = Convert.ToByte(hexEncoded.Substring(i * 2, 2), 16); + return b; + } + catch (Exception ex) + { + throw new FormatException("The provided string does not appear to be Hex encoded:" + Environment.NewLine + hexEncoded + Environment.NewLine, ex); + } + } + + /// + /// converts from a string Base64 representation to an array of bytes + /// + internal static byte[] FromBase64(string base64Encoded) + { + if (base64Encoded is null || base64Encoded.Length == 0) + { + return null; + } + try + { + return Convert.FromBase64String(base64Encoded); + } + catch (FormatException ex) + { + throw new FormatException("The provided string does not appear to be Base64 encoded:" + Environment.NewLine + base64Encoded + Environment.NewLine, ex); + } + } + + /// + /// converts from an array of bytes to a string Base64 representation + /// + internal static string ToBase64(byte[] b) + { + if (b is null || b.Length == 0) + { + return ""; + } + return Convert.ToBase64String(b); + } + + } + + #endregion + +} \ No newline at end of file diff --git a/vb-migration/Strata.Base.Internal/Security/SecurityUtils.cs b/vb-migration/Strata.Base.Internal/Security/SecurityUtils.cs new file mode 100644 index 0000000..2503f70 --- /dev/null +++ b/vb-migration/Strata.Base.Internal/Security/SecurityUtils.cs @@ -0,0 +1,87 @@ +using System; + +namespace Strata.Base.Internal +{ + public class SecurityUtils + { + + #region Declarations + private const string ENCRYPTION_KEY_SUFFIX = "SDT"; + private const int KEY_SIZE_BYTES = 32; // 256 bits for AES-256 + #endregion + + #region Methods + + private static string PadKey(string key) + { + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + + string paddedKey = key + ENCRYPTION_KEY_SUFFIX; + if (paddedKey.Length < KEY_SIZE_BYTES) + { + paddedKey = paddedKey.PadRight(KEY_SIZE_BYTES, 'X'); + } + else if (paddedKey.Length > KEY_SIZE_BYTES) + { + paddedKey = paddedKey.Substring(0, KEY_SIZE_BYTES); + } + return paddedKey; + } + + public static string EncryptValue(string value, string key) + { + if (value is null) + { + return null; + } + + if (string.IsNullOrEmpty(value)) + { + return string.Empty; + } + + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + + // Create encryptor with default IV + var encryption = new EncryptionUtils.SymmetricEncryptor(EncryptionUtils.SymmetricEncryptor.Provider.AES); + + var result = encryption.Encrypt(new EncryptionUtils.Data(value), new EncryptionUtils.Data(PadKey(key))); + return result.Base64; + } + + public static string DecryptValue(string encryptedValue, string key) + { + if (encryptedValue is null) + { + return null; + } + + if (string.IsNullOrEmpty(encryptedValue)) + { + return string.Empty; + } + + if (key is null) + { + throw new ArgumentNullException(nameof(key)); + } + + var encryption = new EncryptionUtils.SymmetricEncryptor(EncryptionUtils.SymmetricEncryptor.Provider.AES); + + // note EncryptValue returns Base64 string so we need to initialized encryptedData as Base64 + var encryptedData = new EncryptionUtils.Data(); + encryptedData.Base64 = encryptedValue; + + return encryption.Decrypt(encryptedData, new EncryptionUtils.Data(PadKey(key))).Text; + } + + #endregion + + } +} \ No newline at end of file diff --git a/vb-migration/Strata.Base.Internal/Strata.Base.Internal.csproj b/vb-migration/Strata.Base.Internal/Strata.Base.Internal.csproj new file mode 100644 index 0000000..77bf1ef --- /dev/null +++ b/vb-migration/Strata.Base.Internal/Strata.Base.Internal.csproj @@ -0,0 +1,82 @@ + + + net8.0-windows + Library + Windows + + + + + On + + false + true + true + Strata.Biz.Internal + Strata Decision Technology, LLC + Strata.Biz.Internal + 2006-2012 Strata Decision Technology, LLC + $(DefaultItemExcludes);$(ProjectDir)**\*.vb + latest + + + Strata.Base.Internal.xml + 42353,42354,42355 + 41999,42016,42017,42018,42019,42020,42021,42022,42032,42036 + false + -Microsoft.Design#CA1012;-Microsoft.Design#CA2210;-Microsoft.Design#CA1040;-Microsoft.Design#CA1005;-Microsoft.Design#CA1020;-Microsoft.Design#CA1021;-Microsoft.Design#CA1010;-Microsoft.Design#CA1011;-Microsoft.Design#CA1009;-Microsoft.Design#CA1050;-Microsoft.Design#CA1026;-Microsoft.Design#CA1019;-Microsoft.Design#CA1031;-Microsoft.Design#CA1047;-Microsoft.Design#CA1000;-Microsoft.Design#CA1048;-Microsoft.Design#CA1051;-Microsoft.Design#CA1002;-Microsoft.Design#CA1061;-Microsoft.Design#CA1006;-Microsoft.Design#CA1046;-Microsoft.Design#CA1045;-Microsoft.Design#CA1065;-Microsoft.Design#CA1038;-Microsoft.Design#CA1008;-Microsoft.Design#CA1028;-Microsoft.Design#CA1064;-Microsoft.Design#CA1004;-Microsoft.Design#CA1035;-Microsoft.Design#CA1063;-Microsoft.Design#CA1032;-Microsoft.Design#CA1023;-Microsoft.Design#CA1033;-Microsoft.Design#CA1039;-Microsoft.Design#CA1016;-Microsoft.Design#CA1014;-Microsoft.Design#CA1017;-Microsoft.Design#CA1018;-Microsoft.Design#CA1027;-Microsoft.Design#CA1059;-Microsoft.Design#CA1060;-Microsoft.Design#CA1034;-Microsoft.Design#CA1013;-Microsoft.Design#CA1036;-Microsoft.Design#CA1044;-Microsoft.Design#CA1041;-Microsoft.Design#CA1025;-Microsoft.Design#CA1052;-Microsoft.Design#CA1053;-Microsoft.Design#CA1057;-Microsoft.Design#CA1058;-Microsoft.Design#CA1001;-Microsoft.Design#CA1049;-Microsoft.Design#CA1054;-Microsoft.Design#CA1056;-Microsoft.Design#CA1055;-Microsoft.Design#CA1030;-Microsoft.Design#CA1003;-Microsoft.Design#CA1007;-Microsoft.Design#CA1043;-Microsoft.Design#CA1024;-Microsoft.Globalization#CA1301;-Microsoft.Globalization#CA1302;-Microsoft.Globalization#CA1308;-Microsoft.Globalization#CA1306;-Microsoft.Globalization#CA1304;-Microsoft.Globalization#CA1305;-Microsoft.Globalization#CA2101;-Microsoft.Globalization#CA1300;-Microsoft.Globalization#CA1307;-Microsoft.Globalization#CA1309;-Microsoft.Interoperability#CA1403;-Microsoft.Interoperability#CA1406;-Microsoft.Interoperability#CA1413;-Microsoft.Interoperability#CA1402;-Microsoft.Interoperability#CA1407;-Microsoft.Interoperability#CA1404;-Microsoft.Interoperability#CA1410;-Microsoft.Interoperability#CA1411;-Microsoft.Interoperability#CA1405;-Microsoft.Interoperability#CA1409;-Microsoft.Interoperability#CA1415;-Microsoft.Interoperability#CA1408;-Microsoft.Interoperability#CA1414;-Microsoft.Interoperability#CA1412;-Microsoft.Interoperability#CA1400;-Microsoft.Interoperability#CA1401;-Microsoft.Maintainability#CA1506;-Microsoft.Maintainability#CA1502;-Microsoft.Maintainability#CA1501;-Microsoft.Maintainability#CA1505;-Microsoft.Maintainability#CA1504;-Microsoft.Maintainability#CA1500;-Microsoft.Mobility#CA1600;-Microsoft.Mobility#CA1601;-Microsoft.Naming#CA1702;-Microsoft.Naming#CA1700;-Microsoft.Naming#CA1712;-Microsoft.Naming#CA1713;-Microsoft.Naming#CA1714;-Microsoft.Naming#CA1709;-Microsoft.Naming#CA1704;-Microsoft.Naming#CA1708;-Microsoft.Naming#CA1715;-Microsoft.Naming#CA1710;-Microsoft.Naming#CA1720;-Microsoft.Naming#CA1707;-Microsoft.Naming#CA1722;-Microsoft.Naming#CA1711;-Microsoft.Naming#CA1716;-Microsoft.Naming#CA1717;-Microsoft.Naming#CA1725;-Microsoft.Naming#CA1719;-Microsoft.Naming#CA1721;-Microsoft.Naming#CA1701;-Microsoft.Naming#CA1703;-Microsoft.Naming#CA1724;-Microsoft.Naming#CA1726;-Microsoft.Performance#CA1809;-Microsoft.Performance#CA1811;-Microsoft.Performance#CA1813;-Microsoft.Performance#CA1816;-Microsoft.Performance#CA1800;-Microsoft.Performance#CA1805;-Microsoft.Performance#CA1810;-Microsoft.Performance#CA1824;-Microsoft.Performance#CA1822;-Microsoft.Performance#CA1814;-Microsoft.Performance#CA1819;-Microsoft.Performance#CA1821;-Microsoft.Performance#CA1820;-Microsoft.Performance#CA1802;-Microsoft.Portability#CA1901;-Microsoft.Portability#CA1900;-Microsoft.Reliability#CA2001;-Microsoft.Reliability#CA2002;-Microsoft.Reliability#CA2003;-Microsoft.Reliability#CA2004;-Microsoft.Reliability#CA2006;-Microsoft.Security#CA2116;-Microsoft.Security#CA2117;-Microsoft.Security#CA2105;-Microsoft.Security#CA2115;-Microsoft.Security#CA2102;-Microsoft.Security#CA2104;-Microsoft.Security#CA2122;-Microsoft.Security#CA2114;-Microsoft.Security#CA2123;-Microsoft.Security#CA2111;-Microsoft.Security#CA2108;-Microsoft.Security#CA2107;-Microsoft.Security#CA2103;-Microsoft.Security#CA2118;-Microsoft.Security#CA2109;-Microsoft.Security#CA2119;-Microsoft.Security#CA2106;-Microsoft.Security#CA2112;-Microsoft.Security#CA2120;-Microsoft.Security#CA2121;-Microsoft.Security#CA2126;-Microsoft.Security#CA2124;-Microsoft.Security#CA2127;-Microsoft.Security#CA2128;-Microsoft.Security#CA2129;-Microsoft.Usage#CA2243;-Microsoft.Usage#CA2236;-Microsoft.Usage#CA2227;-Microsoft.Usage#CA2213;-Microsoft.Usage#CA2216;-Microsoft.Usage#CA2214;-Microsoft.Usage#CA2222;-Microsoft.Usage#CA1806;-Microsoft.Usage#CA2217;-Microsoft.Usage#CA2212;-Microsoft.Usage#CA2219;-Microsoft.Usage#CA2201;-Microsoft.Usage#CA2228;-Microsoft.Usage#CA2221;-Microsoft.Usage#CA2220;-Microsoft.Usage#CA2240;-Microsoft.Usage#CA2229;-Microsoft.Usage#CA2238;-Microsoft.Usage#CA2207;-Microsoft.Usage#CA2208;-Microsoft.Usage#CA2235;-Microsoft.Usage#CA2237;-Microsoft.Usage#CA2232;-Microsoft.Usage#CA2223;-Microsoft.Usage#CA2211;-Microsoft.Usage#CA2233;-Microsoft.Usage#CA2225;-Microsoft.Usage#CA2226;-Microsoft.Usage#CA2231;-Microsoft.Usage#CA2224;-Microsoft.Usage#CA2218;-Microsoft.Usage#CA2234;-Microsoft.Usage#CA2239;-Microsoft.Usage#CA2200;-Microsoft.Usage#CA1801;-Microsoft.Usage#CA2242;-Microsoft.Usage#CA2205;-Microsoft.Usage#CA2230 + Strata.Base.Internal.ruleset + + + Strata.Base.Internal.xml + 42353,42354,42355 + 41999,42016,42017,42018,42019,42020,42021,42022,42032,42036 + Strata.Base.Internal.ruleset + + + bin\ReleaseDeploy\ + bin\ReleaseDeploy\Strata.Base.Internal.xml + true + 42353,42354,42355 + 41999,42016,42017,42018,42019,42020,42021,42022,42032,42036 + Strata.Base.Internal.ruleset + TRACE + + + + + + + True + Application.myapp + + + True + True + Resources.resx + + + True + Settings.settings + True + + + + + MyApplicationCodeGenerator + Application.Designer.cs + + + + + SonarLint.xml + + + + + 8.44.0 + + + + + \ No newline at end of file diff --git a/vb-migration/Strata.Base.Internal/Strata.Base.Internal.xml b/vb-migration/Strata.Base.Internal/Strata.Base.Internal.xml new file mode 100644 index 0000000..10bf176 --- /dev/null +++ b/vb-migration/Strata.Base.Internal/Strata.Base.Internal.xml @@ -0,0 +1,301 @@ + + + + Strata.Base.Internal + + + + + A strongly-typed resource class, for looking up localized strings, etc. + + + + + Returns the cached ResourceManager instance used by this class. + + + + + Overrides the current thread's CurrentUICulture property for all + resource lookups using this strongly typed resource class. + + + + + Hash functions are fundamental to modern cryptography. These functions map binary + strings of an arbitrary length to small binary strings of a fixed length, known as + hash values. A cryptographic hash function has the property that it is computationally + infeasible to find two distinct inputs that hash to the same value. Hash functions + are commonly used with digital signatures and for data integrity. + + + + + Type of hash; some are security oriented, others are fast and simple + + + + + Secure Hashing Algorithm provider, SHA-2 variant, 256-bit + + + + + Secure Hashing Algorithm provider, SHA-2 variant, 384-bit + + + + + Secure Hashing Algorithm provider, SHA-2 variant, 512-bit + + + + + Instantiate a new hash of the specified type + + + + + Returns the previously calculated hash + + + + + Calculates hash on a stream of arbitrary length + + + + + Calculates hash for fixed length + + + + + Calculates hash for a string with a prefixed salt value. + A "salt" is random data prefixed to every hashed value to prevent + common dictionary attacks. + + + + + Calculates hash for an array of bytes + + + + + Symmetric encryption uses a single key to encrypt and decrypt. + Both parties (encryptor and decryptor) must share the same secret key. + + + + + Advanced Encryption Standard (AES) provider + + + + + Instantiates a new symmetric encryption object using the specified provider. + + + + + Key size in bytes. We use the default key size for any given provider; if you + want to force a specific key size, set this property + + + + + Key size in bits. We use the default key size for any given provider; if you + want to force a specific key size, set this property + + + + + The key used to encrypt/decrypt data + + + + + Using the default Cipher Block Chaining (CBC) mode, all data blocks are processed using + the value derived from the previous block; the first data block has no previous data block + to use, so it needs an InitializationVector to feed the first block + + + + + generates a random Initialization Vector, if one was not provided + + + + + generates a random Key, if one was not provided + + + + + Ensures that _crypto object has valid Key and IV + prior to any attempt to encrypt/decrypt anything + + + + + Encrypts the specified Data using provided key + + + + + Encrypts the specified Data using preset key and preset initialization vector + + + + + Encrypts the stream to memory using provided key and provided initialization vector + + + + + Encrypts the stream to memory using specified key + + + + + Encrypts the specified stream to memory using preset key and preset initialization vector + + + + + Decrypts the specified data using provided key and preset initialization vector + + + + + Decrypts the specified stream using provided key and preset initialization vector + + + + + Decrypts the specified stream using preset key and preset initialization vector + + + + + Decrypts the specified data using preset key and preset initialization vector + + + + + represents Hex, Byte, Base64, or String data to encrypt/decrypt; + use the .Text property to set/get a string representation + use the .Hex property to set/get a string-based Hexadecimal representation + + + + + Determines the default text encoding for this Data instance + + + + + Creates new, empty encryption data + + + + + Creates new encryption data with the specified byte array + + + + + Creates new encryption data with the specified string; + will be converted to byte array using UTF8 encoding + + + + + Creates new encryption data using the specified string and the + specified encoding to convert the string to a byte array. + + + + + returns true if no data is present + + + + + allowed step interval, in bytes, for this data; if 0, no limit + + + + + allowed step interval, in bits, for this data; if 0, no limit + + + + + minimum number of bytes allowed for this data; if 0, no limit + + + + + minimum number of bits allowed for this data; if 0, no limit + + + + + maximum number of bytes allowed for this data; if 0, no limit + + + + + maximum number of bits allowed for this data; if 0, no limit + + + + + Returns the byte representation of the data; + This will be padded to MinBytes and trimmed to MaxBytes as necessary! + + + + + Sets or returns text representation of bytes using UTF8 encoding + + + + + Sets or returns Hex string representation of this data + + + + + Sets or returns Base64 string representation of this data + + + + + Friend class for shared utility methods used by multiple Encryption classes + + + + + converts an array of bytes to a string Hex representation + + + + + converts from a string Hex representation to an array of bytes + + + + + converts from a string Base64 representation to an array of bytes + + + + + converts from an array of bytes to a string Base64 representation + + + + -- 2.45.2 From adc8cbfcff1a528ddf462687c083cbd6ff553181 Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Fri, 31 Jan 2025 16:22:23 -0500 Subject: [PATCH 12/31] Enhance documentation for migration process --- vb-migration/VB-CS-migration-guide.md | 301 +++++++++++++++++++++++--- 1 file changed, 270 insertions(+), 31 deletions(-) diff --git a/vb-migration/VB-CS-migration-guide.md b/vb-migration/VB-CS-migration-guide.md index 2c32147..ef614cf 100644 --- a/vb-migration/VB-CS-migration-guide.md +++ b/vb-migration/VB-CS-migration-guide.md @@ -33,57 +33,296 @@ This guide outlines the process for migrating from VB.NET Framework to C# .NET 8 ## Phase 1: Framework Migration (VB.NET to .NET 8) ### Step 1: Environment Setup -1. Install required tools: - ```bash - dotnet tool install -g upgrade-assistant - dotnet tool install -g ICSharpCode.CodeConverter.Cli - ``` -2. Set up version control and backup -3. Create separate environments for testing + +1. **Development Environment Preparation** + - Install Visual Studio 2022 (recommended) or later + - Install the latest .NET 8 SDK + - Install required tools: + ```bash + dotnet tool install -g upgrade-assistant + dotnet tool install -g ICSharpCode.CodeConverter.Cli + ``` + +2. **Source Control Setup** + - Create a new branch for migration + - Tag the last stable version + - Set up branch protection rules + - Configure CI/CD pipeline for multiple frameworks + +3. **Testing Environment** + - Create separate test environments for: + - Original .NET Framework version + - Intermediate builds + - Final .NET 8 version + - Set up automated testing pipeline + - Configure monitoring tools + + *AI Enhancement*: Use Claude to: + - Generate environment comparison checklists + - Create testing strategy documentation + - Suggest monitoring metrics ### Step 2: Initial Analysis -1. Run .NET Upgrade Assistant analysis: + +1. **Project Assessment** ```bash + # Analyze solution with upgrade-assistant upgrade-assistant analyze your-solution.sln + + # Generate detailed report + upgrade-assistant analyze your-solution.sln --verbose > migration-analysis.txt + ``` + +2. **Dependency Analysis** + - Run Visual Studio dependency analysis + - Document all NuGet packages + - Identify deprecated packages + - Map external service dependencies + + *AI Enhancement*: Use Claude to: + - Analyze dependency compatibility + - Suggest modern package alternatives + - Review service integration patterns + - Generate dependency migration plan + +3. **Framework-Specific Code Analysis** + - Identify WebForms dependencies + - List WCF service usage + - Document System.Web dependencies + - Review app.config settings + + *AI Enhancement*: Use Windsurf to: + - Identify security-critical code + - Review configuration patterns + - Suggest modern security practices + +4. **Database Access Review** + - Document ADO.NET usage + - Review Entity Framework version + - Check stored procedure calls + - Analyze transaction patterns + +### Step 3: Framework Migration Execution + +1. **Project File Updates** + - Back up original project files + - Update target framework: + ```xml + + net8.0 + + ``` + - Update SDK reference: + ```xml + + ``` + +2. **Package Migration** + ```bash + # Run upgrade-assistant for package updates + upgrade-assistant upgrade your-solution.sln ``` *AI Enhancement*: Use Claude to: - - Analyze framework-specific dependencies - - Identify outdated patterns - - Suggest modern alternatives - - Review upgrade-assistant recommendations + - Review package updates + - Identify potential conflicts + - Suggest optimal package versions -2. Document dependencies and framework-specific code +3. **Configuration Migration** + - Move from app.config/web.config to appsettings.json + - Update connection strings + - Migrate custom configuration sections + - Update startup configuration *AI Enhancement*: Use Windsurf to: - - Identify security implications - - Suggest secure alternatives - - Review configuration settings + - Review security settings + - Validate configuration patterns + - Check for sensitive data exposure -### Step 3: Framework Migration Execution -1. Start with smallest, least dependent modules -2. Run upgrade assistant: - ```bash - upgrade-assistant upgrade your-solution.sln - ``` -3. Update package references -4. Fix compatibility issues +4. **Framework-Specific Updates** + + a. **Web Applications** + - Replace WebForms with Blazor or MVC + - Update HTTP handlers + - Migrate module registrations + - Update routing configuration + + b. **WCF Services** + - Migrate to gRPC or Web API + - Update service contracts + - Migrate fault contracts + - Update client proxies + + c. **Data Access** + - Update Entity Framework + - Migrate to EF Core if applicable + - Update connection handling + - Review transaction scopes + +5. **Incremental Testing** + - Unit test execution + - Integration test validation + - Performance comparison + - Security validation + + *AI Enhancement*: Use Claude to: + - Analyze test results + - Identify potential regressions + - Suggest test coverage improvements + +### Step 4: Post-Framework Migration + +1. **Performance Optimization** + - Run performance profiling + - Compare metrics with baseline + - Identify bottlenecks + - Implement improvements + + *AI Enhancement*: Use Windsurf to: + - Identify performance issues + - Suggest optimization strategies + - Review resource usage + +2. **Security Review** + - Run security scanning tools + - Review authentication changes + - Validate authorization + - Check data protection + + *AI Enhancement*: Use Claude to: + - Review security patterns + - Suggest security improvements + - Generate security documentation + +3. **Documentation Update** + - Update API documentation + - Document breaking changes + - Update deployment guides + - Create migration notes + + *AI Enhancement*: Use Claude to: + - Generate change documentation + - Create API difference reports + - Update integration guides ## Phase 2: Language Migration (VB.NET to C#) -### Step 1: Code Conversion -1. Use ICSharpCode.CodeConverter: +### Step 1: Code Conversion Options + +#### Option A: Visual Studio Extension Method (Recommended for single files/classes) + +1. **Install the Code Converter Extension** + - Open Visual Studio + - Go to Extensions → Manage Extensions + - Search for "Code Converter" + - Install "VB to C# Code Converter" + - Restart Visual Studio + +2. **Converting Individual Files** + - Open the VB.NET file you want to convert + - Right-click in the code editor + - Select "Paste as C#" if you have code in clipboard, or + - Select "Convert to C#" for the current file + +3. **Converting Multiple Files or Entire Project** + - In Solution Explorer, select multiple files or a project + - Right-click the selection + - Choose "Convert to C#" + - Select target location for converted files + + *AI Enhancement*: Use Claude to: + - Review the converted code structure + - Identify patterns that could be modernized + - Suggest C# 8+ specific features to implement + +4. **Post-Conversion File Review** + - Check file encoding (should be UTF-8) + - Verify namespace organization + - Review class accessibility modifiers + - Check Event handler conversions + - Verify LINQ syntax conversions + +#### Option B: Command Line Conversion (Recommended for full projects) + +1. **Install the CLI Tool** + ```bash + dotnet tool install -g ICSharpCode.CodeConverter.Cli + ``` + +2. **Convert Entire Project** ```bash code-converter convert-project -l VB2CS -t ConvertedProject ``` + +3. **Available Command Line Options** + ```bash + # Preserve case when converting + code-converter convert-project MyProject.vbproj -l VB2CS -t ConvertedProject --preserve-case + + # Skip resources conversion + code-converter convert-project MyProject.vbproj -l VB2CS -t ConvertedProject --skip-resources + + # Specify custom mapping file + code-converter convert-project MyProject.vbproj -l VB2CS -t ConvertedProject --mapping-file custom-mappings.json + ``` + +### Step 2: Common Conversion Points to Review + +1. **Language-Specific Features** + - MyBase vs base + - MyClass vs this + - WithEvents conversions + - Default property conversions *AI Enhancement*: Use Claude to: - - Review converted code - - Identify potential bugs - - Suggest modern C# features - - Optimize code patterns + - Identify VB.NET specific patterns + - Suggest C# idiomatic alternatives + - Review automated conversions -### Step 2: Post-Conversion Tasks +2. **Event Handler Patterns** + - Check delegate signatures + - Verify event wire-up locations + - Review AddHandler/RemoveHandler conversions + + *AI Enhancement*: Use Windsurf to: + - Validate event pattern security + - Check for potential memory leaks + - Suggest modern event patterns + +3. **Type Conversions** + - Check CType conversions + - Review DirectCast usage + - Verify TryCast implementations + + *AI Enhancement*: Use Claude to: + - Suggest pattern matching alternatives + - Identify type conversion optimizations + - Review null-handling patterns + +### Step 3: Specific Code Pattern Reviews + +1. **LINQ and Collection Operations** + - Review converted LINQ expressions + - Check collection initializers + - Verify lambda expressions + - Review query expressions + + *AI Enhancement*: Use Claude to: + - Suggest modern LINQ patterns + - Identify performance optimizations + - Review collection access patterns + +2. **Async/Await Patterns** + - Check async method signatures + - Review exception handling in async code + - Verify Task usage patterns + + *AI Enhancement*: Use Windsurf to: + - Validate async pattern security + - Check for deadlock possibilities + - Review resource cleanup + +### Step 4: Post-Conversion Tasks 1. **Code Review** - Review generated C# code - Apply C# best practices -- 2.45.2 From 8bb3a303693832bb8c3179b63ea88a8e897dae63 Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Fri, 31 Jan 2025 16:37:19 -0500 Subject: [PATCH 13/31] Adjust the migration guide --- vb-migration/VB-CS-migration-guide.md | 40 +++++++++++++++++---------- 1 file changed, 25 insertions(+), 15 deletions(-) diff --git a/vb-migration/VB-CS-migration-guide.md b/vb-migration/VB-CS-migration-guide.md index ef614cf..ac9d6f4 100644 --- a/vb-migration/VB-CS-migration-guide.md +++ b/vb-migration/VB-CS-migration-guide.md @@ -40,7 +40,7 @@ This guide outlines the process for migrating from VB.NET Framework to C# .NET 8 - Install required tools: ```bash dotnet tool install -g upgrade-assistant - dotnet tool install -g ICSharpCode.CodeConverter.Cli + dotnet tool install ICSharpCode.CodeConverter.codeconv --global ``` 2. **Source Control Setup** @@ -246,7 +246,7 @@ This guide outlines the process for migrating from VB.NET Framework to C# .NET 8 1. **Install the CLI Tool** ```bash - dotnet tool install -g ICSharpCode.CodeConverter.Cli + dotnet tool install ICSharpCode.CodeConverter.codeconv --global ``` 2. **Convert Entire Project** @@ -352,19 +352,25 @@ This guide outlines the process for migrating from VB.NET Framework to C# .NET 8 4. Document all changes 5. Use version control effectively -### AI Tool Usage -1. **Claude** - - Code analysis and review - - Pattern modernization - - Documentation generation - - Test case creation - - Performance optimization +### AI Tool Strategy -2. **Windsurf** - - Security validation - - Best practice enforcement - - Pattern suggestions - - Configuration review +1. **Claude Use Cases** + - Deep code analysis to identify modernization opportunities + - Generation of test cases and edge case scenarios + - Documentation creation and API specification reviews + - Performance optimization suggestions + - Pattern modernization recommendations + - Dependency analysis and compatibility checks + - Code conversion validation and improvements + +2. **Windsurf Use Cases** + - Security validation and vulnerability detection + - Framework-specific security recommendations + - Configuration pattern analysis + - Performance impact assessment + - Best practice enforcement for .NET 8 + - Resource usage optimization + - Authentication and authorization pattern review ### Risk Mitigation 1. Create technical risk register @@ -401,4 +407,8 @@ Success depends on: - Documenting all changes - Regular validation and review -Remember to start with a pilot project to validate the process before full migration. \ No newline at end of file +For optimal results: +1. Start with a pilot project to validate the process +2. Use Claude for code analysis and modernization guidance +3. Employ Windsurf for security and performance validation +4. Document all AI-assisted decisions for future reference \ No newline at end of file -- 2.45.2 From 102889ae95b1f1c112582d4e1074e9de74b2611d Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Mon, 3 Feb 2025 14:55:00 -0500 Subject: [PATCH 14/31] Initialze DB --- .vscode/tasks.json | 110 + ef-migration/Docker/install-docker.ps1 | 74 + ef-migration/Docker/uninstall-docker.ps1 | 126 + .../infrastructure/Build-Containers.ps1 | 81 + .../infrastructure/Manage-Containers.ps1 | 89 + .../infrastructure/sql-server/Dockerfile | 26 + .../infrastructure/sql-server/init.sql | 30 + .../dbo_schema_database_statements.sql | 50121 ++++++ .../dbo_schema_database_statements_small.sql | 38 + .../schemas/fp_schema_database_statements.sql | 126102 +++++++++++++++ .../fp_schema_database_statements_small.sql | 40 + .../schemas/fw_schema_database_statements.sql | 31821 ++++ .../fw_schema_database_statements_small.sql | 22 + .../int_schema_database_statements.sql | 14737 ++ .../int_schema_database_statements_small.sql | 22 + .../schemas/ob_schema_database_statements.sql | 24015 +++ .../ob_schema_database_statements_small.sql | 24 + .../infrastructure/sql-server/setup.sh | 0 18 files changed, 247478 insertions(+) create mode 100644 ef-migration/Docker/install-docker.ps1 create mode 100644 ef-migration/Docker/uninstall-docker.ps1 create mode 100644 ef-migration/infrastructure/Build-Containers.ps1 create mode 100644 ef-migration/infrastructure/Manage-Containers.ps1 create mode 100644 ef-migration/infrastructure/sql-server/Dockerfile create mode 100644 ef-migration/infrastructure/sql-server/init.sql create mode 100644 ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements.sql create mode 100644 ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements_small.sql create mode 100644 ef-migration/infrastructure/sql-server/schemas/fp_schema_database_statements.sql create mode 100644 ef-migration/infrastructure/sql-server/schemas/fp_schema_database_statements_small.sql create mode 100644 ef-migration/infrastructure/sql-server/schemas/fw_schema_database_statements.sql create mode 100644 ef-migration/infrastructure/sql-server/schemas/fw_schema_database_statements_small.sql create mode 100644 ef-migration/infrastructure/sql-server/schemas/int_schema_database_statements.sql create mode 100644 ef-migration/infrastructure/sql-server/schemas/int_schema_database_statements_small.sql create mode 100644 ef-migration/infrastructure/sql-server/schemas/ob_schema_database_statements.sql create mode 100644 ef-migration/infrastructure/sql-server/schemas/ob_schema_database_statements_small.sql create mode 100644 ef-migration/infrastructure/sql-server/setup.sh diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 6cee937..39f88f3 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -18,6 +18,116 @@ "panel": "new" }, "problemMatcher": [] + }, + { + "label": "docker-build", + "type": "shell", + "command": "wsl", + "args": [ + "docker", + "build", + "-t", + "st-database", + "./ef-migration/infrastructure/sql-server" + ], + "group": { + "kind": "build", + "isDefault": true + }, + "presentation": { + "reveal": "always", + "panel": "shared" + }, + "problemMatcher": [] + }, + { + "label": "docker-run", + "type": "shell", + "command": "wsl", + "args": [ + "docker", + "run", + "-d", + "-p", + "1433:1433", + "--name", + "st-db", + "st-database" + ], + "group": "none", + "presentation": { + "reveal": "always", + "panel": "shared" + }, + "problemMatcher": [] + }, + { + "label": "docker-stop", + "type": "shell", + "command": "wsl", + "args": [ + "docker", + "stop", + "st-db" + ], + "group": "none", + "presentation": { + "reveal": "always", + "panel": "shared" + }, + "problemMatcher": [] + }, + { + "label": "docker-remove", + "type": "shell", + "command": "wsl", + "args": [ + "docker", + "rm", + "st-db" + ], + "group": "none", + "presentation": { + "reveal": "always", + "panel": "shared" + }, + "problemMatcher": [] + }, + { + "label": "docker-logs", + "type": "shell", + "command": "wsl", + "args": [ + "docker", + "logs", + "st-db" + ], + "group": "none", + "presentation": { + "reveal": "always", + "panel": "shared" + }, + "problemMatcher": [] + }, + { + "label": "docker-status", + "type": "shell", + "command": "wsl", + "args": [ + "docker", + "ps", + "-a", + "--filter", + "name=st-db", + "--format", + "\"{{.Names}} - {{.Status}}\"" + ], + "group": "none", + "presentation": { + "reveal": "always", + "panel": "shared" + }, + "problemMatcher": [] } ] } \ No newline at end of file diff --git a/ef-migration/Docker/install-docker.ps1 b/ef-migration/Docker/install-docker.ps1 new file mode 100644 index 0000000..8811f8f --- /dev/null +++ b/ef-migration/Docker/install-docker.ps1 @@ -0,0 +1,74 @@ +# Requires -RunAsAdministrator + +function Write-Status($Message, $Type = "Info") { + switch ($Type) { + "Info" { $Color = "White" } + "Success" { $Color = "Green" } + "Error" { $Color = "Red" } + "Warning" { $Color = "Yellow" } + } + Write-Host ">>> $Message" -ForegroundColor $Color +} + +# Check if running as Administrator +$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) +if (-not $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { + Write-Status "This script must be run as Administrator" "Error" + Exit 1 +} + +try { + # Install Windows features required for Docker + Write-Status "Installing required Windows features..." "Info" + Enable-WindowsOptionalFeature -Online -FeatureName containers -All -NoRestart + + # Download Docker Engine + Write-Status "Downloading Docker Engine..." "Info" + $dockerUrl = "https://download.docker.com/win/static/stable/x86_64/docker-24.0.7.zip" + $dockerZip = "$env:TEMP\docker.zip" + $dockerPath = "C:\Program Files\Docker" + + Invoke-WebRequest -Uri $dockerUrl -OutFile $dockerZip + + # Extract Docker Engine + Write-Status "Extracting Docker Engine..." "Info" + Expand-Archive -Path $dockerZip -DestinationPath $env:ProgramFiles -Force + Remove-Item $dockerZip -Force + + # Add Docker to PATH + Write-Status "Adding Docker to PATH..." "Info" + $oldPath = [Environment]::GetEnvironmentVariable("Path", [EnvironmentVariableTarget]::Machine) + if (-not $oldPath.Contains($dockerPath)) { + $newPath = "$oldPath;$dockerPath" + [Environment]::SetEnvironmentVariable("Path", $newPath, [EnvironmentVariableTarget]::Machine) + } + + # Create Docker service + Write-Status "Creating Docker service..." "Info" + & "$dockerPath\dockerd.exe" --register-service + + # Start Docker service + Write-Status "Starting Docker service..." "Info" + Start-Service docker + + # Test Docker installation + Write-Status "Testing Docker installation..." "Info" + docker version + if ($LASTEXITCODE -eq 0) { + Write-Status "Docker Engine installed successfully!" "Success" + } else { + Write-Status "Docker installation completed but service test failed" "Warning" + } + + # Pull SQL Server image + Write-Status "Pulling SQL Server image..." "Info" + docker pull mcr.microsoft.com/mssql/server:2022-latest + + Write-Status "`nDocker Engine installation completed!" "Success" + Write-Status "You can now use Docker commands directly." "Info" + Write-Status "Please restart your computer to ensure all changes take effect." "Warning" + +} catch { + Write-Status "An error occurred: $_" "Error" + Exit 1 +} \ No newline at end of file diff --git a/ef-migration/Docker/uninstall-docker.ps1 b/ef-migration/Docker/uninstall-docker.ps1 new file mode 100644 index 0000000..b348c5d --- /dev/null +++ b/ef-migration/Docker/uninstall-docker.ps1 @@ -0,0 +1,126 @@ +# Requires -RunAsAdministrator + +function Write-Status($Message, $Type = "Info") { + switch ($Type) { + "Info" { $Color = "White" } + "Success" { $Color = "Green" } + "Error" { $Color = "Red" } + "Warning" { $Color = "Yellow" } + } + Write-Host ">>> $Message" -ForegroundColor $Color +} + +# Check if running as Administrator +$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) +if (-not $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { + Write-Status "This script must be run as Administrator" "Error" + Exit 1 +} + +try { + # Stop Docker containers + Write-Status "Stopping Docker containers..." "Info" + $containers = docker ps -aq + if ($containers) { + docker stop $containers + Write-Status "All containers stopped" "Success" + } else { + Write-Status "No running containers found" "Info" + } + + # Remove Docker containers + Write-Status "Removing Docker containers..." "Info" + $containers = docker ps -aq + if ($containers) { + docker rm $containers + Write-Status "All containers removed" "Success" + } else { + Write-Status "No containers to remove" "Info" + } + + # Remove Docker images + Write-Status "Removing Docker images..." "Info" + $images = docker images -aq + if ($images) { + docker rmi -f $images + Write-Status "All images removed" "Success" + } else { + Write-Status "No images to remove" "Info" + } + + # Stop Docker service + Write-Status "Stopping Docker service..." "Info" + $dockerService = Get-Service -Name "com.docker.service" -ErrorAction SilentlyContinue + if ($dockerService) { + Stop-Service "com.docker.service" -Force + Write-Status "Docker service stopped" "Success" + } else { + Write-Status "Docker service not found" "Info" + } + + # Remove Docker Desktop + Write-Status "Uninstalling Docker Desktop..." "Info" + $dockerDesktop = Get-WmiObject -Class Win32_Product | Where-Object { $_.Name -like "*Docker Desktop*" } + if ($dockerDesktop) { + $dockerDesktop.Uninstall() + Write-Status "Docker Desktop uninstalled" "Success" + } else { + Write-Status "Docker Desktop not found in installed programs" "Info" + } + + # Clean up Docker data directories + $directories = @( + "$env:ProgramData\Docker", + "$env:APPDATA\Docker", + "$env:LOCALAPPDATA\Docker" + ) + + foreach ($dir in $directories) { + if (Test-Path $dir) { + Write-Status "Removing $dir..." "Info" + Remove-Item -Path $dir -Recurse -Force -ErrorAction SilentlyContinue + Write-Status "$dir removed" "Success" + } + } + + # Remove environment variables + Write-Status "Cleaning up environment variables..." "Info" + $dockerEnvVars = @( + 'DOCKER_HOST', + 'DOCKER_TLS_VERIFY', + 'DOCKER_CERT_PATH', + 'DOCKER_CONFIG', + 'DOCKER_CONTEXT' + ) + + foreach ($var in $dockerEnvVars) { + if (Test-Path env:$var) { + Remove-Item env:$var -ErrorAction SilentlyContinue + [System.Environment]::SetEnvironmentVariable($var, $null, 'User') + [System.Environment]::SetEnvironmentVariable($var, $null, 'Machine') + Write-Status "Removed environment variable: $var" "Success" + } + } + + # Clean up registry entries + Write-Status "Cleaning up registry entries..." "Info" + $registryPaths = @( + 'HKCU:\Software\Docker Inc.', + 'HKLM:\Software\Docker Inc.' + ) + + foreach ($path in $registryPaths) { + if (Test-Path $path) { + Remove-Item -Path $path -Recurse -Force -ErrorAction SilentlyContinue + Write-Status "Removed registry path: $path" "Success" + } + } + + Write-Status "Docker uninstallation completed successfully!" "Success" + Write-Status "Please restart your computer to complete the cleanup." "Warning" + +} catch { + Write-Status "An error occurred during uninstallation: $_" "Error" + Write-Status "Please try to finish the cleanup manually" "Warning" + Exit 1 +} \ No newline at end of file diff --git a/ef-migration/infrastructure/Build-Containers.ps1 b/ef-migration/infrastructure/Build-Containers.ps1 new file mode 100644 index 0000000..6799c1c --- /dev/null +++ b/ef-migration/infrastructure/Build-Containers.ps1 @@ -0,0 +1,81 @@ +# Build-Containers.ps1 +param ( + [switch]$Force +) + +$ErrorActionPreference = "Stop" + +function Test-WSLRequirements { + Write-Host "Checking WSL requirements..." -ForegroundColor Yellow + + # Check if WSL is installed + $wslInstalled = Get-Command wsl.exe -ErrorAction SilentlyContinue + if (-not $wslInstalled) { + Write-Host "WSL is not installed. Please run the following commands as Administrator:" -ForegroundColor Red + Write-Host "wsl --install" -ForegroundColor Yellow + Write-Host "Then restart your computer and run:" -ForegroundColor Yellow + Write-Host "wsl --install -d Ubuntu" -ForegroundColor Yellow + return $false + } + + # Check if any distribution is installed + $wslDistros = wsl --list + if ($LASTEXITCODE -ne 0 -or $wslDistros -match "no installed distributions") { + Write-Host "No WSL distribution found. Please run the following command as Administrator:" -ForegroundColor Red + Write-Host "wsl --install -d Ubuntu" -ForegroundColor Yellow + return $false + } + + # Check if Docker Desktop is running + $dockerPs = Get-Process "Docker Desktop" -ErrorAction SilentlyContinue + if (-not $dockerPs) { + Write-Host "Docker Desktop is not running. Please start Docker Desktop and try again." -ForegroundColor Red + return $false + } + + Write-Host "WSL requirements checked successfully!" -ForegroundColor Green + return $true +} + +# Check WSL requirements +if (-not (Test-WSLRequirements)) { + exit 1 +} + +Write-Host "Starting Docker build process..." -ForegroundColor Green + +# Define container names +$containerName = "st-db" +$imageName = "st-database" + +# Get the current script directory +$scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path +$sqlServerPath = Join-Path $scriptPath "sql-server" + +# Verify Dockerfile exists +if (-not (Test-Path (Join-Path $sqlServerPath "Dockerfile"))) { + Write-Host "Dockerfile not found in $sqlServerPath" -ForegroundColor Red + exit 1 +} + +try { + # Change to the SQL Server directory + Push-Location $sqlServerPath + + # Build the Docker image + Write-Host "Building Docker image '$imageName'..." -ForegroundColor Yellow + docker build -t $imageName . + + if ($LASTEXITCODE -eq 0) { + Write-Host "Docker image built successfully!" -ForegroundColor Green + } else { + Write-Host "Failed to build Docker image" -ForegroundColor Red + exit 1 + } +} catch { + Write-Host "An error occurred: $_" -ForegroundColor Red + exit 1 +} finally { + # Return to original directory + Pop-Location +} \ No newline at end of file diff --git a/ef-migration/infrastructure/Manage-Containers.ps1 b/ef-migration/infrastructure/Manage-Containers.ps1 new file mode 100644 index 0000000..b5eab07 --- /dev/null +++ b/ef-migration/infrastructure/Manage-Containers.ps1 @@ -0,0 +1,89 @@ +# Manage-Containers.ps1 +param ( + [Parameter(Mandatory=$true)] + [ValidateSet('run', 'stop', 'remove')] + [string]$Action, + [switch]$Force +) + +$ErrorActionPreference = "Stop" + +# Define container names +$containerName = "st-db" +$imageName = "st-database" + +function Start-Container { + Write-Host "Starting container '$containerName'..." -ForegroundColor Yellow + + # Check if container exists and is stopped + $existingContainer = docker ps -a --filter "name=$containerName" --format "{{.Names}}" + if ($existingContainer) { + Write-Host "Container already exists, starting it..." -ForegroundColor Yellow + docker start $containerName + } else { + # Run new container + Write-Host "Creating and starting new container..." -ForegroundColor Yellow + docker run -d -p 1433:1433 --name $containerName $imageName + } + + if ($LASTEXITCODE -eq 0) { + Write-Host "Container started successfully!" -ForegroundColor Green + } else { + Write-Host "Failed to start container" -ForegroundColor Red + exit 1 + } +} + +function Stop-Container { + Write-Host "Stopping container '$containerName'..." -ForegroundColor Yellow + + # Check if container exists and is running + $runningContainer = docker ps --filter "name=$containerName" --format "{{.Names}}" + if ($runningContainer) { + docker stop $containerName + if ($LASTEXITCODE -eq 0) { + Write-Host "Container stopped successfully!" -ForegroundColor Green + } else { + Write-Host "Failed to stop container" -ForegroundColor Red + exit 1 + } + } else { + Write-Host "Container is not running" -ForegroundColor Yellow + } +} + +function Remove-Container { + Write-Host "Removing container '$containerName'..." -ForegroundColor Yellow + + # Stop container if running + $runningContainer = docker ps --filter "name=$containerName" --format "{{.Names}}" + if ($runningContainer) { + Write-Host "Stopping container first..." -ForegroundColor Yellow + docker stop $containerName + } + + # Remove container + $existingContainer = docker ps -a --filter "name=$containerName" --format "{{.Names}}" + if ($existingContainer) { + docker rm $containerName + if ($LASTEXITCODE -eq 0) { + Write-Host "Container removed successfully!" -ForegroundColor Green + } else { + Write-Host "Failed to remove container" -ForegroundColor Red + exit 1 + } + } else { + Write-Host "Container does not exist" -ForegroundColor Yellow + } +} + +try { + switch ($Action) { + 'run' { Start-Container } + 'stop' { Stop-Container } + 'remove' { Remove-Container } + } +} catch { + Write-Host "An error occurred: $_" -ForegroundColor Red + exit 1 +} \ No newline at end of file diff --git a/ef-migration/infrastructure/sql-server/Dockerfile b/ef-migration/infrastructure/sql-server/Dockerfile new file mode 100644 index 0000000..f87c7cf --- /dev/null +++ b/ef-migration/infrastructure/sql-server/Dockerfile @@ -0,0 +1,26 @@ +# Use the lightweight SQL Server 2022 image +FROM mcr.microsoft.com/mssql/server:2022-latest + +# Set environment variables +ENV ACCEPT_EULA=Y +ENV MSSQL_PID=Express +ENV SA_PASSWORD=YourStrong@Passw0rd + +# Create a directory for database scripts +WORKDIR /usr/src/app + +# Copy the schema files +COPY dbo_schema_database_statements_small.sql ./schemas/ +COPY fp_schema_database_statements_small.sql ./schemas/ +COPY fw_schema_database_statements_small.sql ./schemas/ +COPY int_schema_database_statements_small.sql ./schemas/ +COPY ob_schema_database_statements_small.sql ./schemas/ + +# Create initialization script +COPY init.sql ./ + +# Create setup script that will run the schema creation +COPY setup.sh ./ +RUN chmod +x setup.sh + +CMD /bin/bash ./setup.sh \ No newline at end of file diff --git a/ef-migration/infrastructure/sql-server/init.sql b/ef-migration/infrastructure/sql-server/init.sql new file mode 100644 index 0000000..1c752a2 --- /dev/null +++ b/ef-migration/infrastructure/sql-server/init.sql @@ -0,0 +1,30 @@ +-- Create the database +IF NOT EXISTS (SELECT * FROM sys.databases WHERE name = 'st-database') +BEGIN + CREATE DATABASE [st-database] +END +GO + +USE [st-database] +GO + +-- Create schemas if they don't exist +IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'dbo') + EXEC('CREATE SCHEMA [dbo]') +GO + +IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'fp') + EXEC('CREATE SCHEMA [fp]') +GO + +IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'fw') + EXEC('CREATE SCHEMA [fw]') +GO + +IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'int') + EXEC('CREATE SCHEMA [int]') +GO + +IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'ob') + EXEC('CREATE SCHEMA [ob]') +GO \ No newline at end of file diff --git a/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements.sql b/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements.sql new file mode 100644 index 0000000..4734fd5 --- /dev/null +++ b/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements.sql @@ -0,0 +1,50121 @@ +-- SCHEMA: dbo + +--------------------------------------------- +-- TABLES +--------------------------------------------- + + +--------------------------------------------- +-- dbo.AMAssumptionView ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[AMAssumptionView] ( + [AssumptionViewGUID] uniqueidentifier NOT NULL, + [AssumptionGroupGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(450) NOT NULL, + [ColumnWidths] varchar(8000) NOT NULL, + [AssumptionJoinDataGUID] uniqueidentifier NOT NULL, + [FolderGUID] uniqueidentifier NOT NULL, + [IsDistributionModeActive] bit NOT NULL, + [DistributionInfo] xml(max) NOT NULL, + [ProviderGUID] uniqueidentifier NOT NULL, + [CreatedDate] datetime NOT NULL, + [CreatedBy] uniqueidentifier NOT NULL, + [LastUsedDate] datetime NOT NULL, + PRIMARY KEY ([AssumptionViewGUID]) +); +GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_CreatedBy] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CreatedBy]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_CreatedDate] DEFAULT (getdate()) FOR [CreatedDate]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_LastUsedDate] DEFAULT (getdate()) FOR [LastUsedDate]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_Table_1_AssumptionViewGUID] DEFAULT (newid()) FOR [AssumptionViewGUID]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_ASSUMPTIONGROUPGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssumptionGroupGUID]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_COLUMNWIDTHS] DEFAULT ('') FOR [ColumnWidths]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_ASSUMPTIONCUBEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssumptionJoinDataGUID]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_FOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_ISDISTRIBUTIONMODEACTIVE] DEFAULT ((0)) FOR [IsDistributionModeActive]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_DISTRIBUTIONINFOXML] DEFAULT ('') FOR [DistributionInfo]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_PROVIDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ProviderGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.AMCalculatedColumn ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[AMCalculatedColumn] ( + [CalculatedColumnGUID] uniqueidentifier NOT NULL, + [AssumptionViewGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(450) NOT NULL, + [ColumnBase] nvarchar(4000) NOT NULL, + [ColumnCompare] nvarchar(4000) NOT NULL, + [Type] int NOT NULL, + [IsEditable] bit NOT NULL, + [Position] int NOT NULL, + PRIMARY KEY ([CalculatedColumnGUID]) +); +GO +ALTER TABLE [dbo].[AMCalculatedColumn] ADD CONSTRAINT [DF_AMCalculatedColumn_CALCULATEDCOLUMNGUID] DEFAULT (newid()) FOR [CalculatedColumnGUID]; GO +ALTER TABLE [dbo].[AMCalculatedColumn] ADD CONSTRAINT [DF_AMCalculatedColumn_ASSUMPTIONVIEWGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssumptionViewGUID]; GO +ALTER TABLE [dbo].[AMCalculatedColumn] ADD CONSTRAINT [DF_AMCalculatedColumn_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[AMCalculatedColumn] ADD CONSTRAINT [DF_AMCalculatedColumn_COLUMNBASE] DEFAULT ('') FOR [ColumnBase]; GO +ALTER TABLE [dbo].[AMCalculatedColumn] ADD CONSTRAINT [DF_AMCalculatedColumn_TYPE] DEFAULT ((0)) FOR [Type]; GO +ALTER TABLE [dbo].[AMCalculatedColumn] ADD CONSTRAINT [DF_AMCalculatedColumn_ISEDITABLE] DEFAULT ((0)) FOR [IsEditable]; GO +ALTER TABLE [dbo].[AMCalculatedColumn] ADD CONSTRAINT [DF_AMCalculatedColumn_POSITION] DEFAULT ((0)) FOR [Position]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.AMCorrelationGroup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[AMCorrelationGroup] ( + [CorrelationGroupGUID] uniqueidentifier NOT NULL, + [AssumptionGroupGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [IsGlobal] bit NOT NULL, + [MembersXML] xml(max) NOT NULL, + PRIMARY KEY ([CorrelationGroupGUID]) +); +GO +ALTER TABLE [dbo].[AMCorrelationGroup] ADD CONSTRAINT [DF_AMCorrelationGroup_CorrelationGroupGUID] DEFAULT (newid()) FOR [CorrelationGroupGUID]; GO +ALTER TABLE [dbo].[AMCorrelationGroup] ADD CONSTRAINT [DF_AMCorrelationGroup_AssumptionGroupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssumptionGroupGUID]; GO +ALTER TABLE [dbo].[AMCorrelationGroup] ADD CONSTRAINT [DF_AMCorrelationGroup_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[AMCorrelationGroup] ADD CONSTRAINT [DF_AMCorrelationGroup_IsGlobal] DEFAULT ((0)) FOR [IsGlobal]; GO +ALTER TABLE [dbo].[AMCorrelationGroup] ADD CONSTRAINT [DF_AMCorrelationGroup_MembersXML] DEFAULT ('') FOR [MembersXML]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.AMDimensionLevelBinding ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[AMDimensionLevelBinding] ( + [DimensionLevelBindingGUID] uniqueidentifier NOT NULL, + [DimensionSetupGUID] uniqueidentifier NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + [LevelName] nvarchar(450) NOT NULL, + [LevelIndex] int NOT NULL, + [DisplayOrder] int NOT NULL, + [IsBound] bit NOT NULL, + PRIMARY KEY ([DimensionLevelBindingGUID]) +); +GO +ALTER TABLE [dbo].[AMDimensionLevelBinding] ADD CONSTRAINT [FK_AMDimensionLevelBinding_AMDimensionSetup] FOREIGN KEY ([DimensionSetupGUID]) REFERENCES [dbo].[AMDimensionSetup] ([DimensionSetupGUID]); GO +ALTER TABLE [dbo].[AMDimensionLevelBinding] ADD CONSTRAINT [DF_AMDimensionLevelBinding_DIMENSIONLEVELBINDINGGUID] DEFAULT (newid()) FOR [DimensionLevelBindingGUID]; GO +ALTER TABLE [dbo].[AMDimensionLevelBinding] ADD CONSTRAINT [DF_AMDimensionLevelBinding_ASSUMPTIONVIEWGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionSetupGUID]; GO +ALTER TABLE [dbo].[AMDimensionLevelBinding] ADD CONSTRAINT [DF_AMDimensionLevelBinding_DIMENSIONGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO +ALTER TABLE [dbo].[AMDimensionLevelBinding] ADD CONSTRAINT [DF_AMDimensionLevelBinding_LEVELNAME] DEFAULT ('') FOR [LevelName]; GO +ALTER TABLE [dbo].[AMDimensionLevelBinding] ADD CONSTRAINT [DF_AMDimensionLevelBinding_LEVELINDEX] DEFAULT ((0)) FOR [LevelIndex]; GO +ALTER TABLE [dbo].[AMDimensionLevelBinding] ADD CONSTRAINT [DF_AMDimensionLevelBinding_DISPLAYORDER] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[AMDimensionLevelBinding] ADD CONSTRAINT [DF_AMDimensionLevelBinding_ISBOUND] DEFAULT ((0)) FOR [IsBound]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.AMDimensionSetup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[AMDimensionSetup] ( + [DimensionSetupGUID] uniqueidentifier NOT NULL, + [AssumptionViewGUID] uniqueidentifier NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + [DimensionName] nvarchar(450) NOT NULL, + [IsFiltered] bit NOT NULL, + [IsRequired] bit NOT NULL, + [DisplayType] int NOT NULL, + [IsFilterOnLoad] bit NOT NULL, + PRIMARY KEY ([DimensionSetupGUID]) +); + +CREATE CLUSTERED INDEX [IX_AMDimensionSetup] ON [dbo].[AMDimensionSetup] ([AssumptionViewGUID]); +GO +ALTER TABLE [dbo].[AMDimensionSetup] ADD CONSTRAINT [FK_AMDimensionSetup_AMAssumptionView] FOREIGN KEY ([AssumptionViewGUID]) REFERENCES [dbo].[AMAssumptionView] ([AssumptionViewGUID]); GO +ALTER TABLE [dbo].[AMDimensionSetup] ADD CONSTRAINT [DF_AMDimensionSetup_IsFilterOnLoad] DEFAULT ((0)) FOR [IsFilterOnLoad]; GO +ALTER TABLE [dbo].[AMDimensionSetup] ADD CONSTRAINT [DF_AMDimensionSetup_DIMENSIONSETUPGUID] DEFAULT (newid()) FOR [DimensionSetupGUID]; GO +ALTER TABLE [dbo].[AMDimensionSetup] ADD CONSTRAINT [DF_AMDimensionSetup_ASSUMPTIONVIEWGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssumptionViewGUID]; GO +ALTER TABLE [dbo].[AMDimensionSetup] ADD CONSTRAINT [DF_AMDimensionSetup_DIMENSIONID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO +ALTER TABLE [dbo].[AMDimensionSetup] ADD CONSTRAINT [DF_AMDimensionSetup_DIMENSIONNAME] DEFAULT ('') FOR [DimensionName]; GO +ALTER TABLE [dbo].[AMDimensionSetup] ADD CONSTRAINT [DF_AMDimensionSetup_ISFILTERED] DEFAULT ((0)) FOR [IsFiltered]; GO +ALTER TABLE [dbo].[AMDimensionSetup] ADD CONSTRAINT [DF_AMDimensionSetup_ISREQUIRED] DEFAULT ((0)) FOR [IsRequired]; GO +ALTER TABLE [dbo].[AMDimensionSetup] ADD CONSTRAINT [DF_AMDimensionSetup_DISPLAYTYPE] DEFAULT ((0)) FOR [DisplayType]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.AMGridSetting ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[AMGridSetting] ( + [GridSettingGUID] uniqueidentifier NOT NULL, + [AssumptionViewGUID] uniqueidentifier NOT NULL, + [Size] int NOT NULL, + [SettingType] int NOT NULL, + [FieldKey] nvarchar(4000) NOT NULL, + [IsVisible] bit NOT NULL, + PRIMARY KEY ([GridSettingGUID]) +); + +CREATE CLUSTERED INDEX [IX_AMGridSetting] ON [dbo].[AMGridSetting] ([AssumptionViewGUID]); +GO +ALTER TABLE [dbo].[AMGridSetting] ADD CONSTRAINT [FK_AMGridSetting_AMAssumptionView] FOREIGN KEY ([AssumptionViewGUID]) REFERENCES [dbo].[AMAssumptionView] ([AssumptionViewGUID]); GO +ALTER TABLE [dbo].[AMGridSetting] ADD CONSTRAINT [DF_AMGridSetting_GRIDSETTINGGUID] DEFAULT (newid()) FOR [GridSettingGUID]; GO +ALTER TABLE [dbo].[AMGridSetting] ADD CONSTRAINT [DF_AMGridSetting_ASSUMPTIONVIEWGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssumptionViewGUID]; GO +ALTER TABLE [dbo].[AMGridSetting] ADD CONSTRAINT [DF_AMGridSetting_COLUMNWIDTH] DEFAULT ((100)) FOR [Size]; GO +ALTER TABLE [dbo].[AMGridSetting] ADD CONSTRAINT [DF_AMGridSetting_SETTINGTYPE] DEFAULT ((0)) FOR [SettingType]; GO +ALTER TABLE [dbo].[AMGridSetting] ADD CONSTRAINT [DF_AMGridSetting_KEY] DEFAULT ('') FOR [FieldKey]; GO +ALTER TABLE [dbo].[AMGridSetting] ADD CONSTRAINT [DF_AMGridSetting_ISVISIBLE] DEFAULT ((1)) FOR [IsVisible]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.AMIncludedMember ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[AMIncludedMember] ( + [IncludedMemberGUID] uniqueidentifier NOT NULL, + [DimensionMemberID] nvarchar(450) NOT NULL, + [Name] nvarchar(450) NOT NULL, + [DimensionSetupGUID] uniqueidentifier NOT NULL, + [IsDataMember] bit NOT NULL, + [ParentIncludedMemberGUID] uniqueidentifier NOT NULL, + [OutlineLevel] int NOT NULL, + PRIMARY KEY ([IncludedMemberGUID]) +); + +CREATE CLUSTERED INDEX [IX_AMIncludedMember] ON [dbo].[AMIncludedMember] ([DimensionSetupGUID]); +GO +ALTER TABLE [dbo].[AMIncludedMember] ADD CONSTRAINT [FK_AMIncludedMember_AMDimensionSetup1] FOREIGN KEY ([DimensionSetupGUID]) REFERENCES [dbo].[AMDimensionSetup] ([DimensionSetupGUID]); GO +ALTER TABLE [dbo].[AMIncludedMember] ADD CONSTRAINT [DF_AMIncludedMember_INCLUDEDMEMBERGUID] DEFAULT (newid()) FOR [IncludedMemberGUID]; GO +ALTER TABLE [dbo].[AMIncludedMember] ADD CONSTRAINT [DF_AMIncludedMember_MEMBERID] DEFAULT ('') FOR [DimensionMemberID]; GO +ALTER TABLE [dbo].[AMIncludedMember] ADD CONSTRAINT [DF_AMIncludedMember_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[AMIncludedMember] ADD CONSTRAINT [DF_AMIncludedMember_DIMENSIONSETUPGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionSetupGUID]; GO +ALTER TABLE [dbo].[AMIncludedMember] ADD CONSTRAINT [DF_AMIncludedMember_ISDATAMEMBER] DEFAULT ((0)) FOR [IsDataMember]; GO +ALTER TABLE [dbo].[AMIncludedMember] ADD CONSTRAINT [DF_AMIncludedMember_PARENTINCLUDEDMEMBERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentIncludedMemberGUID]; GO +ALTER TABLE [dbo].[AMIncludedMember] ADD CONSTRAINT [DF_AMIncludedMember_OUTLINELEVEL] DEFAULT ((-1)) FOR [OutlineLevel]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.AMMultiEditGroup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[AMMultiEditGroup] ( + [MultiEditGroupGUID] uniqueidentifier NOT NULL, + [AssumptionViewGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + [KeyDimensionMemberID] nvarchar(450) NOT NULL, + [IncludedMemberIDs] nvarchar(max) NOT NULL, + [IsAbsolute] bit NOT NULL, + [Mode] int NOT NULL, + PRIMARY KEY ([MultiEditGroupGUID]) +); +GO +ALTER TABLE [dbo].[AMMultiEditGroup] ADD CONSTRAINT [DF_AMMultiEditGroup_MULTIEDITGROUPGUID] DEFAULT (newid()) FOR [MultiEditGroupGUID]; GO +ALTER TABLE [dbo].[AMMultiEditGroup] ADD CONSTRAINT [DF_AMMultiEditGroup_ASSUMPTIONVIEWGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssumptionViewGUID]; GO +ALTER TABLE [dbo].[AMMultiEditGroup] ADD CONSTRAINT [DF_AMMultiEditGroup_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[AMMultiEditGroup] ADD CONSTRAINT [DF_AMMultiEditGroup_DIMENSIONGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO +ALTER TABLE [dbo].[AMMultiEditGroup] ADD CONSTRAINT [DF_AMMultiEditGroup_KEYDIMENSIONMEMBERID] DEFAULT ('') FOR [KeyDimensionMemberID]; GO +ALTER TABLE [dbo].[AMMultiEditGroup] ADD CONSTRAINT [DF_AMMultiEditGroup_INCLUDEDMEMBERIDS] DEFAULT ('') FOR [IncludedMemberIDs]; GO +ALTER TABLE [dbo].[AMMultiEditGroup] ADD CONSTRAINT [DF_AMMultiEditGroup_ISABSOLUTE] DEFAULT ((0)) FOR [IsAbsolute]; GO +ALTER TABLE [dbo].[AMMultiEditGroup] ADD CONSTRAINT [DF_AMMultiEditGroup_Mode] DEFAULT ((0)) FOR [Mode]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ActionLog ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ActionLog] ( + [RowID] int NOT NULL, + [Action] varchar(64) NOT NULL, + [SubAction] varchar(400) NOT NULL, + [Details] varchar(400) NOT NULL, + [Username] varchar(64) NOT NULL, + [DateTimeStamp] datetime NOT NULL, + [Duration] int NOT NULL, + [TokenGUID] uniqueidentifier NOT NULL, + [DateTimeStampUtc] datetime NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [dbo].[ActionLog] ADD CONSTRAINT [DF_ActionLog_TokenGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TokenGUID]; GO +ALTER TABLE [dbo].[ActionLog] ADD CONSTRAINT [DF__ActionLog__DateT__45DC8664] DEFAULT (getutcdate()) FOR [DateTimeStampUtc]; GO +ALTER TABLE [dbo].[ActionLog] ADD CONSTRAINT [DF_ActionLog_Action] DEFAULT ('') FOR [Action]; GO +ALTER TABLE [dbo].[ActionLog] ADD CONSTRAINT [DF_ActionLog_SubAction] DEFAULT ('') FOR [SubAction]; GO +ALTER TABLE [dbo].[ActionLog] ADD CONSTRAINT [DF_ActionLog_Detail] DEFAULT ('') FOR [Details]; GO +ALTER TABLE [dbo].[ActionLog] ADD CONSTRAINT [DF_ActionLog_Username] DEFAULT ('') FOR [Username]; GO +ALTER TABLE [dbo].[ActionLog] ADD CONSTRAINT [DF_ActionLog_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO +ALTER TABLE [dbo].[ActionLog] ADD CONSTRAINT [DF_ActionLog_Duration] DEFAULT ((0)) FOR [Duration]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ActionLogHistory ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ActionLogHistory] ( + [Year] int NULL, + [Month] int NULL, + [Day] int NULL, + [Action] varchar(64) NOT NULL, + [SubAction] varchar(64) NOT NULL, + [SumDuration] int NULL, + [AvgDuration] int NULL, + [MinDuration] int NULL, + [MaxDuration] int NULL, + [StdevDuration] float NULL, + [Count] int NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ActiveControllers ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ActiveControllers] ( + [ControllerID] uniqueidentifier NOT NULL, + [WorkerID] uniqueidentifier NOT NULL, + [TimeStamp] datetime NOT NULL +); +GO +ALTER TABLE [dbo].[ActiveControllers] ADD CONSTRAINT [DF_ActiveControllers_ControllerID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ControllerID]; GO +ALTER TABLE [dbo].[ActiveControllers] ADD CONSTRAINT [DF_ActiveControllers_WorkerID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkerID]; GO +ALTER TABLE [dbo].[ActiveControllers] ADD CONSTRAINT [DF_ActiveControllers_TimeStamp] DEFAULT (getdate()) FOR [TimeStamp]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.Announcement ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[Announcement] ( + [AnnouncementGUID] uniqueidentifier NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [Message] nvarchar(max) NOT NULL, + [DateCreated] datetime NOT NULL, + [DateModified] datetime NOT NULL, + [ModuleGUID_DEPRECATED] uniqueidentifier NOT NULL, + [IsUrgent] bit NOT NULL, + PRIMARY KEY ([AnnouncementGUID]) +); +GO +ALTER TABLE [dbo].[Announcement] ADD CONSTRAINT [DF__Announcem__IsUrg__5513AB32] DEFAULT ((0)) FOR [IsUrgent]; GO +ALTER TABLE [dbo].[Announcement] ADD CONSTRAINT [DF__Announcem__Annou__59CA45FB] DEFAULT (newid()) FOR [AnnouncementGUID]; GO +ALTER TABLE [dbo].[Announcement] ADD CONSTRAINT [DF__Announcem__Autho__5ABE6A34] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [dbo].[Announcement] ADD CONSTRAINT [DF__Announcem__Autho__5BB28E6D] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [dbo].[Announcement] ADD CONSTRAINT [DF__Announcem__Messa__5CA6B2A6] DEFAULT ('') FOR [Message]; GO +ALTER TABLE [dbo].[Announcement] ADD CONSTRAINT [DF__Announcem__DateC__5D9AD6DF] DEFAULT (getdate()) FOR [DateCreated]; GO +ALTER TABLE [dbo].[Announcement] ADD CONSTRAINT [DF__Announcem__DateM__5E8EFB18] DEFAULT (getdate()) FOR [DateModified]; GO +ALTER TABLE [dbo].[Announcement] ADD CONSTRAINT [DF__Announcem__Modul__775AA8E2] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModuleGUID_DEPRECATED]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ApplicationMode ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ApplicationMode] ( + [ApplicationModeID] tinyint NOT NULL, + [Name] nvarchar(128) NOT NULL, + [AccessLevel] tinyint NOT NULL, + PRIMARY KEY ([ApplicationModeID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ApplyAssumptionsHistoryDetail ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ApplyAssumptionsHistoryDetail] ( + [HistoryMemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [AssumptionGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [AssumptionSetName] nvarchar(100) NOT NULL, + [AssumptionName] nvarchar(100) NOT NULL, + [TimeClass] nvarchar(50) NOT NULL, + [Dimensionality] nvarchar(max) NOT NULL, + [OldValue] decimal NOT NULL, + [NewValue] decimal NOT NULL, + [OldValueText] nvarchar(50) NULL, + [NewValueText] nvarchar(50) NULL, + [OldFormula] nvarchar(max) NOT NULL, + [NewFormula] nvarchar(max) NOT NULL, + [DateTimeStamp] datetime NOT NULL, + [ValueDisplayType] int NOT NULL, + PRIMARY KEY ([HistoryMemberGUID]) +); +GO +ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_ValueDisplayType] DEFAULT ((0)) FOR [ValueDisplayType]; GO +ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_HistoryMemberGUID] DEFAULT (newid()) FOR [HistoryMemberGUID]; GO +ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_AssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssumptionGUID]; GO +ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_AssumptionSetName] DEFAULT ('') FOR [AssumptionSetName]; GO +ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_AssumptionName] DEFAULT ('') FOR [AssumptionName]; GO +ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_TimeClass] DEFAULT ('') FOR [TimeClass]; GO +ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_Dimensionality] DEFAULT ('') FOR [Dimensionality]; GO +ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_OldValue] DEFAULT ((0)) FOR [OldValue]; GO +ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_NewValue] DEFAULT ((0)) FOR [NewValue]; GO +ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_OldValueText] DEFAULT ('') FOR [OldValueText]; GO +ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_NewValueText] DEFAULT ('') FOR [NewValueText]; GO +ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_OldFormula] DEFAULT ('d') FOR [OldFormula]; GO +ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_NewFormula] DEFAULT ('') FOR [NewFormula]; GO +ALTER TABLE [dbo].[ApplyAssumptionsHistoryDetail] ADD CONSTRAINT [DF_ApplyAssumptionsHistoryDetail_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.BackupIsUsedScoreKeyLinkSetting ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[BackupIsUsedScoreKeyLinkSetting] ( + [ScoreKeyLinkSettingGuid] uniqueidentifier NOT NULL, + [KeyGUID] uniqueidentifier NOT NULL, + [DataTableGUID] uniqueidentifier NOT NULL, + [IsUsed] bit NOT NULL, + [IsCustom] bit NOT NULL, + [IsMarkedForDeletion] bit NOT NULL, + [IsRequired] bit NOT NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.BackupIsUsedScoreMeasureSetting ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[BackupIsUsedScoreMeasureSetting] ( + [ScoreMeasureSettingGuid] uniqueidentifier NOT NULL, + [MeasureGUID] uniqueidentifier NOT NULL, + [DataTableGUID] uniqueidentifier NOT NULL, + [IsUsed] bit NOT NULL, + [IsCustom] bit NOT NULL, + [IsMarkedForDeletion] bit NOT NULL, + [ColumnName] nvarchar(128) NOT NULL, + [IsRequired] bit NOT NULL, + [ObjectName] nvarchar(128) NOT NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.BudgetFileAttachment ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[BudgetFileAttachment] ( + [FileAttachmentGUID] uniqueidentifier NOT NULL, + [FileName] nvarchar(250) NOT NULL, + [NumBytes] float NOT NULL, + [DepartmentId] int NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [DateCreated] datetime NOT NULL, + [LastSeenpath] nvarchar(4000) NOT NULL, + PRIMARY KEY ([FileAttachmentGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_BudgetFileAttachment_Unique] ON [dbo].[BudgetFileAttachment] ([DepartmentId], [FileName]); +GO +ALTER TABLE [dbo].[BudgetFileAttachment] ADD CONSTRAINT [DF_BudgetFileAttachment_FILEATTACHMENTGUID] DEFAULT (newid()) FOR [FileAttachmentGUID]; GO +ALTER TABLE [dbo].[BudgetFileAttachment] ADD CONSTRAINT [DF_BudgetFileAttachment_FILENAME] DEFAULT ('') FOR [FileName]; GO +ALTER TABLE [dbo].[BudgetFileAttachment] ADD CONSTRAINT [DF_BudgetFileAttachment_NUMBYTES] DEFAULT ((0)) FOR [NumBytes]; GO +ALTER TABLE [dbo].[BudgetFileAttachment] ADD CONSTRAINT [DF_BudgetFileAttachment_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[BudgetFileAttachment] ADD CONSTRAINT [DF_BudgetFileAttachment_LASTSEENPATH] DEFAULT ('') FOR [LastSeenpath]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CECubeAlias ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CECubeAlias] ( + [CubeAliasGUID] uniqueidentifier NOT NULL, + [CubeName] nvarchar(64) NOT NULL, + [ObjectID] nvarchar(max) NOT NULL, + [AliasName] nvarchar(max) NOT NULL, + [AliasGUID] uniqueidentifier NOT NULL, + [ObjectType] int NOT NULL, + PRIMARY KEY ([CubeAliasGUID]) +); +GO +ALTER TABLE [dbo].[CECubeAlias] ADD CONSTRAINT [DF_CubeAlias_CubeAliasGUID] DEFAULT (newid()) FOR [CubeAliasGUID]; GO +ALTER TABLE [dbo].[CECubeAlias] ADD CONSTRAINT [DF_CubeAlias_CubeName] DEFAULT ('') FOR [CubeName]; GO +ALTER TABLE [dbo].[CECubeAlias] ADD CONSTRAINT [DF_CubeAlias_ObjectID] DEFAULT ('') FOR [ObjectID]; GO +ALTER TABLE [dbo].[CECubeAlias] ADD CONSTRAINT [DF_CubeAlias_Alias] DEFAULT ('') FOR [AliasName]; GO +ALTER TABLE [dbo].[CECubeAlias] ADD CONSTRAINT [DF_CECubeAlias_AliasGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AliasGUID]; GO +ALTER TABLE [dbo].[CECubeAlias] ADD CONSTRAINT [DF_CubeAlias_ObjectType] DEFAULT ((0)) FOR [ObjectType]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CECubeConnection ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CECubeConnection] ( + [CubeConnectionGUID] uniqueidentifier NOT NULL, + [ServerName] nvarchar(64) NOT NULL, + [DatabaseName] nvarchar(128) NOT NULL, + [CubeName] nvarchar(64) NOT NULL, + [ConnectionType] int NOT NULL, + [IsActive] bit NOT NULL, + [DataPath] nvarchar(max) NOT NULL, + PRIMARY KEY ([CubeConnectionGUID]) +); +GO +ALTER TABLE [dbo].[CECubeConnection] ADD CONSTRAINT [DF_CEConnection_ConnectionGUID] DEFAULT (newid()) FOR [CubeConnectionGUID]; GO +ALTER TABLE [dbo].[CECubeConnection] ADD CONSTRAINT [DF_CEConnection_ServerName] DEFAULT ('') FOR [ServerName]; GO +ALTER TABLE [dbo].[CECubeConnection] ADD CONSTRAINT [DF_CEConnection_DatabaseName] DEFAULT ('') FOR [DatabaseName]; GO +ALTER TABLE [dbo].[CECubeConnection] ADD CONSTRAINT [DF_CEConnection_CubeName] DEFAULT ('') FOR [CubeName]; GO +ALTER TABLE [dbo].[CECubeConnection] ADD CONSTRAINT [DF_CEConnection_Type] DEFAULT ((0)) FOR [ConnectionType]; GO +ALTER TABLE [dbo].[CECubeConnection] ADD CONSTRAINT [DF_CEConnection_IsActive] DEFAULT ((0)) FOR [IsActive]; GO +ALTER TABLE [dbo].[CECubeConnection] ADD CONSTRAINT [DF_CECubeConnection_DataPath] DEFAULT ('') FOR [DataPath]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CECubeReportLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CECubeReportLink] ( + [CubeReportLinkGUID] uniqueidentifier NOT NULL, + [CubeGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([CubeReportLinkGUID]) +); +GO +ALTER TABLE [dbo].[CECubeReportLink] ADD CONSTRAINT [FK__CECubeRep__CubeG__4A0B4183] FOREIGN KEY ([CubeGUID]) REFERENCES [dbo].[EMFCubeStub] ([CubeGUID]); GO +ALTER TABLE [dbo].[CECubeReportLink] ADD CONSTRAINT [FK__CECubeRep__Repor__4AFF65BC] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[CECubeReportLink] ADD CONSTRAINT [DF__CECubeRep__CubeR__49171D4A] DEFAULT (newid()) FOR [CubeReportLinkGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMBucket ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMBucket] ( + [BucketGUID] uniqueidentifier NOT NULL, + [CategoryGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(50) NOT NULL, + PRIMARY KEY ([BucketGUID]) +); +GO +ALTER TABLE [dbo].[CMBucket] ADD CONSTRAINT [FK_ClassificationBucket_ClassificationCategory] FOREIGN KEY ([CategoryGUID]) REFERENCES [dbo].[CMCategory] ([CategoryGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMCategory ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMCategory] ( + [CategoryGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(50) NOT NULL, + [Mutex] bit NOT NULL, + PRIMARY KEY ([CategoryGUID]) +); +GO +ALTER TABLE [dbo].[CMCategory] ADD CONSTRAINT [DF_ClassificationCategory_ClassificationCategoryGUID] DEFAULT (newid()) FOR [CategoryGUID]; GO +ALTER TABLE [dbo].[CMCategory] ADD CONSTRAINT [DF_ClassificationCategory_Mutex] DEFAULT ((0)) FOR [Mutex]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMCategoryFramework ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMCategoryFramework] ( + [CategoryGUID] uniqueidentifier NOT NULL, + [FrameworkID] tinyint NOT NULL, + PRIMARY KEY ([CategoryGUID], [FrameworkID]) +); +GO +ALTER TABLE [dbo].[CMCategoryFramework] ADD CONSTRAINT [FK_CMCategoryFramework_CMCategory] FOREIGN KEY ([CategoryGUID]) REFERENCES [dbo].[CMCategory] ([CategoryGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMCategoryTag ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMCategoryTag] ( + [CategoryGUID] uniqueidentifier NOT NULL, + [TagGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([CategoryGUID], [TagGUID]) +); +GO +ALTER TABLE [dbo].[CMCategoryTag] ADD CONSTRAINT [FK_CMCategoryTag_CMCategory] FOREIGN KEY ([CategoryGUID]) REFERENCES [dbo].[CMCategory] ([CategoryGUID]); GO +ALTER TABLE [dbo].[CMCategoryTag] ADD CONSTRAINT [FK_CMCategoryTag_Tag] FOREIGN KEY ([TagGUID]) REFERENCES [dbo].[Tag] ([TagGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMFacts ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMFacts] ( + [DimensionGUID] uniqueidentifier NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [BucketGUID] uniqueidentifier NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [GroupingID] int NOT NULL, + PRIMARY KEY ([DimensionGUID], [MemberGUID], [BucketGUID], [GroupingGUID]) +); +GO +ALTER TABLE [dbo].[CMFacts] ADD CONSTRAINT [FK_ClassificationFacts_ClassificationBucket] FOREIGN KEY ([BucketGUID]) REFERENCES [dbo].[CMBucket] ([BucketGUID]); GO +ALTER TABLE [dbo].[CMFacts] ADD CONSTRAINT [FK_CMFacts_ScoreDimension] FOREIGN KEY ([DimensionGUID]) REFERENCES [dbo].[ScoreDimension] ([DimensionGUID]); GO +ALTER TABLE [dbo].[CMFacts] ADD CONSTRAINT [DF_CMFacts_MemberGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MemberGUID]; GO +ALTER TABLE [dbo].[CMFacts] ADD CONSTRAINT [DF_CMFacts_GroupingGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [dbo].[CMFacts] ADD CONSTRAINT [DF_CMFacts_GroupingID] DEFAULT ((0)) FOR [GroupingID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMFlex ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMFlex] ( + [FlexGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + PRIMARY KEY ([FlexGUID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMFlexKeyLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMFlexKeyLink] ( + [FlexGUID] uniqueidentifier NOT NULL, + [FlexKeyLinkGUID] uniqueidentifier NOT NULL, + [IsUsedInFlex] bit NOT NULL, + PRIMARY KEY ([FlexGUID], [FlexKeyLinkGUID]) +); +GO +ALTER TABLE [dbo].[CMFlexKeyLink] ADD CONSTRAINT [FK_CMFlexKeyLink_CMFlex] FOREIGN KEY ([FlexGUID]) REFERENCES [dbo].[CMFlex] ([FlexGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMFlexMeasureMapping ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMFlexMeasureMapping] ( + [MeasureMappingGUID] uniqueidentifier NOT NULL, + [FlexGUID] uniqueidentifier NOT NULL, + [TargetMeasureGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([MeasureMappingGUID]) +); +GO +ALTER TABLE [dbo].[CMFlexMeasureMapping] ADD CONSTRAINT [FK_CMFlexMeasureMapping_CMFlex] FOREIGN KEY ([FlexGUID]) REFERENCES [dbo].[CMFlex] ([FlexGUID]); GO +ALTER TABLE [dbo].[CMFlexMeasureMapping] ADD CONSTRAINT [FK_CMFlexMeasureMapping_CMFlexMeasureMapping] FOREIGN KEY ([MeasureMappingGUID]) REFERENCES [dbo].[CMFlexMeasureMapping] ([MeasureMappingGUID]); GO +ALTER TABLE [dbo].[CMFlexMeasureMapping] ADD CONSTRAINT [FK_CMFlexMeasureMapping_ScoreMeasure] FOREIGN KEY ([TargetMeasureGUID]) REFERENCES [dbo].[ScoreMeasure] ([MeasureGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMFlexSourceMeasureMappingLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMFlexSourceMeasureMappingLink] ( + [MeasureMappingGUID] uniqueidentifier NOT NULL, + [MeasureGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([MeasureMappingGUID], [MeasureGUID]) +); +GO +ALTER TABLE [dbo].[CMFlexSourceMeasureMappingLink] ADD CONSTRAINT [FK_CMFlexSourceMeasureMappingLink_ScoreMeasure] FOREIGN KEY ([MeasureGUID]) REFERENCES [dbo].[ScoreMeasure] ([MeasureGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMFlexSourceTableLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMFlexSourceTableLink] ( + [FlexGUID] uniqueidentifier NOT NULL, + [DataTableGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([FlexGUID], [DataTableGUID]) +); +GO +ALTER TABLE [dbo].[CMFlexSourceTableLink] ADD CONSTRAINT [FK_CMFlexSourceTableLink_CMFlex] FOREIGN KEY ([FlexGUID]) REFERENCES [dbo].[CMFlex] ([FlexGUID]); GO +ALTER TABLE [dbo].[CMFlexSourceTableLink] ADD CONSTRAINT [FK_CMFlexSourceTableLink_ScoreDataTable] FOREIGN KEY ([DataTableGUID]) REFERENCES [dbo].[ScoreDataTable] ([DataTableGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMFlexTargetTableLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMFlexTargetTableLink] ( + [FlexGUID] uniqueidentifier NOT NULL, + [DataTableGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([FlexGUID], [DataTableGUID]) +); +GO +ALTER TABLE [dbo].[CMFlexTargetTableLink] ADD CONSTRAINT [FK_CMFlexTargetTableLink_CMFlex] FOREIGN KEY ([FlexGUID]) REFERENCES [dbo].[CMFlex] ([FlexGUID]); GO +ALTER TABLE [dbo].[CMFlexTargetTableLink] ADD CONSTRAINT [FK_CMFlexTargetTableLink_ScoreDataTable] FOREIGN KEY ([DataTableGUID]) REFERENCES [dbo].[ScoreDataTable] ([DataTableGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMMetric ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMMetric] ( + [MetricGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(50) NOT NULL, + [MetricCode] nvarchar(50) NOT NULL, + [IsAggregable] bit NOT NULL, + [ToleranceValue] float NOT NULL, + [TolerancePercent] float NOT NULL, + [IsInverted] bit NOT NULL, + [FormatString] nvarchar(100) NULL, + [DisplayOrder] int NOT NULL, + [Category] nvarchar(100) NOT NULL, + [MeasureGUID] uniqueidentifier NOT NULL, + [Calculation] nvarchar(max) NOT NULL, + [BucketGUID] uniqueidentifier NOT NULL, + [IsCustomOverride] bit NOT NULL, + [CalculationParts] nvarchar(max) NOT NULL, + [CommentType] tinyint NOT NULL, + [DimensionType] tinyint NOT NULL, + [FriendlyName] nvarchar(256) NULL, + [CalculationPartTypes] nvarchar(100) NOT NULL, + [ClinicalIndicatorID] int NOT NULL, + [IsPositiveFavorable] bit NOT NULL, + [VarianceRule] tinyint NOT NULL, + [IsHidden] bit NOT NULL, + [UseBaselineTarget] bit NOT NULL, + [DateCreated] datetime NOT NULL, + [IsShownForSystem] bit NOT NULL, + [IsShownForEntity] bit NOT NULL, + [IsShownForDepartmentRollup1] bit NOT NULL, + [IsShownForDepartmentRollup2] bit NOT NULL, + [IsShownForDepartmentRollup3] bit NOT NULL, + [IsShownForDepartmentRollup4] bit NOT NULL, + [IsShownForDepartmentRollup5] bit NOT NULL, + [IsShownForDepartmentRollup6] bit NOT NULL, + [IsShownForDepartment] bit NOT NULL, + [TimeFrame] tinyint NOT NULL, + [Description] nvarchar(300) NOT NULL, + [ThresholdMaterialityValue] float NULL, + [DepartmentsType] tinyint NULL, + [IsStandard] bit NOT NULL, + [ToBeDeleted] bit NOT NULL, + PRIMARY KEY ([MetricGUID]) +); +GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [CHK_CMMetric_DepartmentsType] CHECK ([DepartmentsType]=(1) OR [DepartmentsType]=(0)); GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_UseBaselineTarget] DEFAULT ((0)) FOR [UseBaselineTarget]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_ClassificationMetric_ClassificationMetricGUID] DEFAULT (newid()) FOR [MetricGUID]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_MetricCode] DEFAULT ('') FOR [MetricCode]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_ClassificationMetric_IsAggregable] DEFAULT ((1)) FOR [IsAggregable]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_ToleranceValue] DEFAULT ((0)) FOR [ToleranceValue]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__Commen__1523DCDC] DEFAULT ((0)) FOR [CommentType]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_TolerancePercent] DEFAULT ((0)) FOR [TolerancePercent]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsInverted] DEFAULT ((0)) FOR [IsInverted]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_FormatString] DEFAULT ('') FOR [FormatString]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__Clinic__22C8BC14] DEFAULT ((0)) FOR [ClinicalIndicatorID]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__Descri__28A4F021] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_CalculationParts] DEFAULT ('') FOR [CalculationParts]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__Bucket__46CEB05B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BucketGUID]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_VarianceRule] DEFAULT ((0)) FOR [VarianceRule]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsHidden] DEFAULT ((0)) FOR [IsHidden]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__Measur__479D17D8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__Calcul__49D53A38] DEFAULT ('') FOR [Calculation]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_DisplayOrder_1] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__Catego__5561274A] DEFAULT ('') FOR [Category]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsShownForSystem] DEFAULT ((1)) FOR [IsShownForSystem]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsShownForEntity] DEFAULT ((1)) FOR [IsShownForEntity]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsShownForDepartmentRollup1] DEFAULT ((1)) FOR [IsShownForDepartmentRollup1]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsShownForDepartmentRollup2] DEFAULT ((1)) FOR [IsShownForDepartmentRollup2]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsShownForDepartmentRollup3] DEFAULT ((1)) FOR [IsShownForDepartmentRollup3]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsShownForDepartmentRollup4] DEFAULT ((1)) FOR [IsShownForDepartmentRollup4]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsShownForDepartmentRollup5] DEFAULT ((1)) FOR [IsShownForDepartmentRollup5]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__IsCust__5C3ECE8D] DEFAULT ((0)) FOR [IsCustomOverride]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsShownForDepartmentRollup6] DEFAULT ((1)) FOR [IsShownForDepartmentRollup6]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsShownForDepartment] DEFAULT ((1)) FOR [IsShownForDepartment]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsPositiveFavorable] DEFAULT ((1)) FOR [IsPositiveFavorable]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__Calcul__661ED530] DEFAULT ('') FOR [CalculationPartTypes]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_IsStandard] DEFAULT ((0)) FOR [IsStandard]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF_CMMetric_DimensionType] DEFAULT ((0)) FOR [DimensionType]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__TimeFr__7622C69E] DEFAULT ((0)) FOR [TimeFrame]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__ToBeDe__7777DAAB] DEFAULT ((0)) FOR [ToBeDeleted]; GO +ALTER TABLE [dbo].[CMMetric] ADD CONSTRAINT [DF__CMMetric__DateCr__79DB1B8D] DEFAULT (getdate()) FOR [DateCreated]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMMetricCommentDepartmentFilter ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMMetricCommentDepartmentFilter] ( + [MetricCommentDepartmentFilterGUID] uniqueidentifier NOT NULL, + [MetricGUID] uniqueidentifier NOT NULL, + [Value] nvarchar(256) NOT NULL, + [NameValue] nvarchar(max) NULL, + PRIMARY KEY ([MetricCommentDepartmentFilterGUID]) +); +GO +ALTER TABLE [dbo].[CMMetricCommentDepartmentFilter] ADD CONSTRAINT [DF_CMMetricCommentDepartmentFilter_MetricCommentDepartmentFilterGUID] DEFAULT (newid()) FOR [MetricCommentDepartmentFilterGUID]; GO +ALTER TABLE [dbo].[CMMetricCommentDepartmentFilter] ADD CONSTRAINT [DF_CMMetricCommentDepartmentFilter_MetricGUID] DEFAULT (newid()) FOR [MetricGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMMetricCommentDepartmentFilterCache ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMMetricCommentDepartmentFilterCache] ( + [MetricGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + PRIMARY KEY ([MetricGUID], [DepartmentID]) +); +GO +ALTER TABLE [dbo].[CMMetricCommentDepartmentFilterCache] ADD CONSTRAINT [FK_DBO_CMMetricCommentDepartmentFilterCache_CMMetric] FOREIGN KEY ([MetricGUID]) REFERENCES [dbo].[CMMetric] ([MetricGUID]); GO +ALTER TABLE [dbo].[CMMetricCommentDepartmentFilterCache] ADD CONSTRAINT [FK_DBO_CMMetricCommentDepartmentFilterCache_DimDepartment] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMMetricFramework ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMMetricFramework] ( + [MetricGUID] uniqueidentifier NOT NULL, + [FrameworkID] tinyint NOT NULL, + PRIMARY KEY ([MetricGUID], [FrameworkID]) +); +GO +ALTER TABLE [dbo].[CMMetricFramework] ADD CONSTRAINT [FK_CMMetricFramework_CMMetric] FOREIGN KEY ([MetricGUID]) REFERENCES [dbo].[CMMetric] ([MetricGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMMetricOverride ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMMetricOverride] ( + [MetricGUID] uniqueidentifier NOT NULL, + [ItemID] int NOT NULL, + [RollupLevel] nvarchar(100) NOT NULL, + [ToleranceValue] float NOT NULL, + [TolerancePercent] float NOT NULL, + [CommentType] tinyint NOT NULL, + [ThresholdMaterialityValue] float NULL, + PRIMARY KEY ([MetricGUID], [ItemID], [RollupLevel]) +); +GO +ALTER TABLE [dbo].[CMMetricOverride] ADD CONSTRAINT [FK_CMMetricOverride_MetricGUID] FOREIGN KEY ([MetricGUID]) REFERENCES [dbo].[CMMetric] ([MetricGUID]); GO +ALTER TABLE [dbo].[CMMetricOverride] ADD CONSTRAINT [CK_CMMetricOverride_RollupLevel] CHECK ([RollupLevel]='DepartmentRollup6' OR [RollupLevel]='DepartmentRollup5' OR [RollupLevel]='DepartmentRollup4' OR [RollupLevel]='DepartmentRollup3' OR [RollupLevel]='DepartmentRollup2' OR [RollupLevel]='DepartmentRollup1' OR [RollupLevel]='Entity' OR [RollupLevel]='System'); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMMetricTag ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMMetricTag] ( + [MetricGUID] uniqueidentifier NOT NULL, + [TagGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([MetricGUID], [TagGUID]) +); +GO +ALTER TABLE [dbo].[CMMetricTag] ADD CONSTRAINT [FK_CMMetricTag_CMMetric] FOREIGN KEY ([MetricGUID]) REFERENCES [dbo].[CMMetric] ([MetricGUID]); GO +ALTER TABLE [dbo].[CMMetricTag] ADD CONSTRAINT [FK_CMMetricTag_Tag] FOREIGN KEY ([TagGUID]) REFERENCES [dbo].[Tag] ([TagGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMRule ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMRule] ( + [RuleGUID] uniqueidentifier NOT NULL, + [BucketGUID] uniqueidentifier NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + [RuleType] int NOT NULL, + PRIMARY KEY ([RuleGUID]) +); +GO +ALTER TABLE [dbo].[CMRule] ADD CONSTRAINT [FK_ClassificationRule_ClassificationBucket] FOREIGN KEY ([BucketGUID]) REFERENCES [dbo].[CMBucket] ([BucketGUID]); GO +ALTER TABLE [dbo].[CMRule] ADD CONSTRAINT [DF_ClassificationRule_ClassificationRuleGUID] DEFAULT (newid()) FOR [RuleGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMRuleTag ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMRuleTag] ( + [RuleGUID] uniqueidentifier NOT NULL, + [TagGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([RuleGUID], [TagGUID]) +); +GO +ALTER TABLE [dbo].[CMRuleTag] ADD CONSTRAINT [FK__CMRuleTag__RuleG__3749B010] FOREIGN KEY ([RuleGUID]) REFERENCES [dbo].[CMRule] ([RuleGUID]); GO +ALTER TABLE [dbo].[CMRuleTag] ADD CONSTRAINT [FK__CMRuleTag__TagGU__383DD449] FOREIGN KEY ([TagGUID]) REFERENCES [dbo].[Tag] ([TagGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMRuleValue ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMRuleValue] ( + [RuleValueGUID] uniqueidentifier NOT NULL, + [RuleGUID] uniqueidentifier NOT NULL, + [Value] nvarchar(100) NOT NULL, + [SortOrder] int NOT NULL, + [IsExcluding] bit NOT NULL, + [GroupingID] int NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + [NameValue] nvarchar(max) NULL, + PRIMARY KEY ([RuleValueGUID]) +); +GO +ALTER TABLE [dbo].[CMRuleValue] ADD CONSTRAINT [FK_ClassificationRuleValue_ClassificationRule] FOREIGN KEY ([RuleGUID]) REFERENCES [dbo].[CMRule] ([RuleGUID]); GO +ALTER TABLE [dbo].[CMRuleValue] ADD CONSTRAINT [DF_ClassificationRuleValue_ClassificationRuleValueGUID] DEFAULT (newid()) FOR [RuleValueGUID]; GO +ALTER TABLE [dbo].[CMRuleValue] ADD CONSTRAINT [DF_CMRuleValue_IsExcluding] DEFAULT ((0)) FOR [IsExcluding]; GO +ALTER TABLE [dbo].[CMRuleValue] ADD CONSTRAINT [DF_CMRuleValue_GroupingID] DEFAULT ((0)) FOR [GroupingID]; GO +ALTER TABLE [dbo].[CMRuleValue] ADD CONSTRAINT [DF_CMRuleValue_GroupingGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [dbo].[CMRuleValue] ADD CONSTRAINT [DF_CMRuleValue_DimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMSampleTable ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMSampleTable] ( + [SampleTableGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [isLocked] bit NOT NULL, + PRIMARY KEY ([SampleTableGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_ClassificationSampleTable] ON [dbo].[CMSampleTable] ([Name]); +GO +ALTER TABLE [dbo].[CMSampleTable] ADD CONSTRAINT [DF_ClassificationSampleTable_ClassificationSampleTableGUID] DEFAULT (newid()) FOR [SampleTableGUID]; GO +ALTER TABLE [dbo].[CMSampleTable] ADD CONSTRAINT [DF_ClassificationSampleTable_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[CMSampleTable] ADD CONSTRAINT [DF_CMSampleTable_isLocked] DEFAULT ((0)) FOR [isLocked]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMSampleTableDataLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMSampleTableDataLink] ( + [SampleTableDataLinkGUID] uniqueidentifier NOT NULL, + [SampleTableGUID] uniqueidentifier NOT NULL, + [ScoreDataTableGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([SampleTableDataLinkGUID]) +); +GO +ALTER TABLE [dbo].[CMSampleTableDataLink] ADD CONSTRAINT [FK_CMSampleTableDataLink_CMSampleTable] FOREIGN KEY ([SampleTableGUID]) REFERENCES [dbo].[CMSampleTable] ([SampleTableGUID]); GO +ALTER TABLE [dbo].[CMSampleTableDataLink] ADD CONSTRAINT [FK_CMSampleTableDataLink_ScoreDataTable] FOREIGN KEY ([ScoreDataTableGUID]) REFERENCES [dbo].[ScoreDataTable] ([DataTableGUID]); GO +ALTER TABLE [dbo].[CMSampleTableDataLink] ADD CONSTRAINT [DF_CMSampleTableDataLink_SampleTableDataLinkGUID] DEFAULT (newid()) FOR [SampleTableDataLinkGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMSampleTableFramework ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMSampleTableFramework] ( + [SampleTableGUID] uniqueidentifier NOT NULL, + [FrameworkID] tinyint NOT NULL, + PRIMARY KEY ([SampleTableGUID], [FrameworkID]) +); +GO +ALTER TABLE [dbo].[CMSampleTableFramework] ADD CONSTRAINT [FK_CMSampleTableFramework_CMSampleTable] FOREIGN KEY ([SampleTableGUID]) REFERENCES [dbo].[CMSampleTable] ([SampleTableGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMSampleTableKeyLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMSampleTableKeyLink] ( + [SampleTableKeyLinkGUID] uniqueidentifier NOT NULL, + [SampleTableGUID] uniqueidentifier NOT NULL, + [KeyGUID] uniqueidentifier NOT NULL, + [KeyAlternateAttributeGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([SampleTableKeyLinkGUID]) +); +GO +ALTER TABLE [dbo].[CMSampleTableKeyLink] ADD CONSTRAINT [FK_CMSampleTableKeyLink_CMSampleTable] FOREIGN KEY ([SampleTableGUID]) REFERENCES [dbo].[CMSampleTable] ([SampleTableGUID]); GO +ALTER TABLE [dbo].[CMSampleTableKeyLink] ADD CONSTRAINT [FK_CMSampleTableKeyLink_ScoreAttribute] FOREIGN KEY ([KeyGUID]) REFERENCES [dbo].[ScoreAttribute] ([AttributeGUID]); GO +ALTER TABLE [dbo].[CMSampleTableKeyLink] ADD CONSTRAINT [DF_ClassificationSampleTableKeyLink_ClassificationSampleTableKeyLinkGUID] DEFAULT (newid()) FOR [SampleTableKeyLinkGUID]; GO +ALTER TABLE [dbo].[CMSampleTableKeyLink] ADD CONSTRAINT [DF_ClassificationSampleTableKeyLink_ClassificationSampleTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SampleTableGUID]; GO +ALTER TABLE [dbo].[CMSampleTableKeyLink] ADD CONSTRAINT [DF__CMSampleT__KeyAl__45B4CF66] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [KeyAlternateAttributeGUID]; GO +ALTER TABLE [dbo].[CMSampleTableKeyLink] ADD CONSTRAINT [DF_CMSampleTableKeyLink_KeyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [KeyGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMSampleTableMeasure ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMSampleTableMeasure] ( + [MeasureGUID] uniqueidentifier NOT NULL, + [SampleTableGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + PRIMARY KEY ([MeasureGUID]) +); +GO +ALTER TABLE [dbo].[CMSampleTableMeasure] ADD CONSTRAINT [FK_CMSampleTableMeasure_CMSampleTable] FOREIGN KEY ([SampleTableGUID]) REFERENCES [dbo].[CMSampleTable] ([SampleTableGUID]); GO +ALTER TABLE [dbo].[CMSampleTableMeasure] ADD CONSTRAINT [DF_CMSampleTableMeasure_MeasureGUID] DEFAULT (newid()) FOR [MeasureGUID]; GO +ALTER TABLE [dbo].[CMSampleTableMeasure] ADD CONSTRAINT [DF_CMSampleTableMeasure_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[CMSampleTableMeasure] ADD CONSTRAINT [DF_CMSampleTableMeasure_SampleTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SampleTableGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMSampleTableMetricLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMSampleTableMetricLink] ( + [SampleTableGUID] uniqueidentifier NOT NULL, + [MetricGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([SampleTableGUID], [MetricGUID]) +); +GO +ALTER TABLE [dbo].[CMSampleTableMetricLink] ADD CONSTRAINT [FK_CMSampleTableMetricLink_CMMetric] FOREIGN KEY ([MetricGUID]) REFERENCES [dbo].[CMMetric] ([MetricGUID]); GO +ALTER TABLE [dbo].[CMSampleTableMetricLink] ADD CONSTRAINT [FK_CMSampleTableMetricLink_CMSampleTable] FOREIGN KEY ([SampleTableGUID]) REFERENCES [dbo].[CMSampleTable] ([SampleTableGUID]); GO +ALTER TABLE [dbo].[CMSampleTableMetricLink] ADD CONSTRAINT [DF_Table_1_MetricGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MetricGUID]; GO +ALTER TABLE [dbo].[CMSampleTableMetricLink] ADD CONSTRAINT [DF_ClassificationSampleTableMetricLink_ClassificationSampleTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SampleTableGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMSampleTableMetricMapping ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMSampleTableMetricMapping] ( + [SampleTableMetricMappingGUID] uniqueidentifier NOT NULL, + [MetricGUID] uniqueidentifier NOT NULL, + [SampleTableDataLinkGUID] uniqueidentifier NOT NULL, + [ScoreMeasureGUID] uniqueidentifier NOT NULL, + [SampleTableMeasureGUID] uniqueidentifier NOT NULL, + [SampleTableGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([SampleTableMetricMappingGUID]) +); +GO +ALTER TABLE [dbo].[CMSampleTableMetricMapping] ADD CONSTRAINT [FK_CMSampleTableMetricMapping_CMMetric] FOREIGN KEY ([MetricGUID]) REFERENCES [dbo].[CMMetric] ([MetricGUID]); GO +ALTER TABLE [dbo].[CMSampleTableMetricMapping] ADD CONSTRAINT [FK_CMSampleTableMetricMapping_ScoreMeasure] FOREIGN KEY ([ScoreMeasureGUID]) REFERENCES [dbo].[ScoreMeasure] ([MeasureGUID]); GO +ALTER TABLE [dbo].[CMSampleTableMetricMapping] ADD CONSTRAINT [DF_CMSampleTableMetricMapping_SampleTableMetricMappingGUID] DEFAULT (newid()) FOR [SampleTableMetricMappingGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CMSampleTableTargetFilter ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CMSampleTableTargetFilter] ( + [TargetFilterGUID] uniqueidentifier NOT NULL, + [SampleTableGUID] uniqueidentifier NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([TargetFilterGUID]) +); +GO +ALTER TABLE [dbo].[CMSampleTableTargetFilter] ADD CONSTRAINT [FK_CMSampleTableTargetFilter_CMSampleTable] FOREIGN KEY ([SampleTableGUID]) REFERENCES [dbo].[CMSampleTable] ([SampleTableGUID]); GO +ALTER TABLE [dbo].[CMSampleTableTargetFilter] ADD CONSTRAINT [FK_CMSampleTableTargetFilter_ScoreDimension] FOREIGN KEY ([DimensionGUID]) REFERENCES [dbo].[ScoreDimension] ([DimensionGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CSDimensionConstant ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CSDimensionConstant] ( + [DimensionConstantGUID] uniqueidentifier NOT NULL, + [SetupGUID] uniqueidentifier NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + [DimensionMemberGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([DimensionConstantGUID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ClientContact ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ClientContact] ( + [ClientContactGUID] uniqueidentifier NOT NULL, + [ModuleGUID] uniqueidentifier NOT NULL, + [ContactName] nvarchar(256) NOT NULL, + [ContactInfo] nvarchar(max) NOT NULL, + PRIMARY KEY ([ClientContactGUID]) +); +GO +ALTER TABLE [dbo].[ClientContact] ADD CONSTRAINT [FK__ClientCon__Modul__25217392] FOREIGN KEY ([ModuleGUID]) REFERENCES [dbo].[SystemCenterModule] ([ModuleGUID]); GO +ALTER TABLE [dbo].[ClientContact] ADD CONSTRAINT [DF__ClientCon__Clien__242D4F59] DEFAULT (newid()) FOR [ClientContactGUID]; GO +ALTER TABLE [dbo].[ClientContact] ADD CONSTRAINT [DF__ClientCon__Conta__261597CB] DEFAULT ('') FOR [ContactName]; GO +ALTER TABLE [dbo].[ClientContact] ADD CONSTRAINT [DF__ClientCon__Conta__2709BC04] DEFAULT ('') FOR [ContactInfo]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ClientDefinedColumns ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ClientDefinedColumns] ( + [ClientDefinedColumnGUID] uniqueidentifier NOT NULL, + [OptimizationPoolGUID] uniqueidentifier NOT NULL, + [FormFieldGUID] uniqueidentifier NOT NULL, + [SortOrder] int NULL, + PRIMARY KEY ([ClientDefinedColumnGUID]) +); +GO +ALTER TABLE [dbo].[ClientDefinedColumns] ADD CONSTRAINT [FK_ClientDefinedColumns_FormFieldGUID] FOREIGN KEY ([FormFieldGUID]) REFERENCES [dbo].[FE2FormField] ([FormFieldGUID]); GO +ALTER TABLE [dbo].[ClientDefinedColumns] ADD CONSTRAINT [FK_ClientDefinedColumns_OMZPool] FOREIGN KEY ([OptimizationPoolGUID]) REFERENCES [dbo].[OMZPool] ([PoolGUID]); GO +ALTER TABLE [dbo].[ClientDefinedColumns] ADD CONSTRAINT [DF__ClientDef__Clien__1AEA68C3] DEFAULT (newid()) FOR [ClientDefinedColumnGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ColumnStoreIndex ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ColumnStoreIndex] ( + [i] int NOT NULL +); + +CREATE NONCLUSTERED COLUMNSTORE INDEX [nccx_ColumnStoreIndex] ON [dbo].[ColumnStoreIndex] () INCLUDE ([i]); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ContentMigrationAttributeMapping ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ContentMigrationAttributeMapping] ( + [ContentMigrationAttributeMappingID] int NOT NULL, + [ScoreDimensionGUID] uniqueidentifier NULL, + [ScoreAttributeGUID] uniqueidentifier NULL, + [ParentDimensionGUID] uniqueidentifier NULL, + [ScoreDatatableGUID] uniqueidentifier NULL, + [CubeDimensionName] nvarchar(200) NULL, + [CubeAttributeName] nvarchar(200) NULL, + [CubeDataType] nvarchar(200) NULL, + [ParentSqlObjectDefinition] nvarchar(200) NULL, + [BaseSqlObjectDefinition] nvarchar(200) NULL, + [SqlObjectDefinition] nvarchar(200) NULL, + [SqlColumnName] nvarchar(200) NULL, + [SnowflakeObjectDefinition] nvarchar(200) NULL, + [SnowflakeColumnName] nvarchar(200) NULL, + [SisenseDataMart] nvarchar(200) NULL, + [SisenseColumnName] nvarchar(200) NULL, + [SisenseTableName] nvarchar(200) NULL, + [SqlDataType] nvarchar(100) NOT NULL, + [ScoreDimensionName] nvarchar(100) NOT NULL, + PRIMARY KEY ([ContentMigrationAttributeMappingID]) +); +GO +ALTER TABLE [dbo].[ContentMigrationAttributeMapping] ADD CONSTRAINT [DF__ContentMi__SqlDa__3922751B] DEFAULT ('') FOR [SqlDataType]; GO +ALTER TABLE [dbo].[ContentMigrationAttributeMapping] ADD CONSTRAINT [DF__ContentMi__Score__69268DF8] DEFAULT ('') FOR [ScoreDimensionName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ContentMigrationCalculationMapping ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ContentMigrationCalculationMapping] ( + [CubeCalculationName] nvarchar(200) NULL, + [CubeMeasureGroupName] nvarchar(200) NULL, + [CubeCalculation] nvarchar(2000) NULL, + [CubeIncludedMeasuresCSV] nvarchar(2000) NULL, + [SisenseDataMart] nvarchar(200) NULL, + [SisenseColumnName] nvarchar(200) NULL, + [ContentMigrationCalculationMappingID] int NOT NULL, + PRIMARY KEY ([ContentMigrationCalculationMappingID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ContentMigrationMeasureMapping ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ContentMigrationMeasureMapping] ( + [ContentMigrationMeasureMappingID] int NOT NULL, + [ScoreDatatableGUID] uniqueidentifier NULL, + [ScoreMeasureGUID] uniqueidentifier NULL, + [CubeMeasureGroupName] nvarchar(200) NULL, + [CubeMeasureName] nvarchar(200) NULL, + [CubeDataType] nvarchar(200) NULL, + [CubeAggregationType] nvarchar(200) NULL, + [SqlObjectDefinition] nvarchar(200) NULL, + [SqlColumnName] nvarchar(200) NULL, + [SnowflakeObjectDefinition] nvarchar(200) NULL, + [SnowflakeColumnName] nvarchar(200) NULL, + [SisenseDataMart] nvarchar(200) NULL, + [SisenseColumnName] nvarchar(200) NULL, + [SisenseTableName] nvarchar(200) NULL, + [SqlDataType] nvarchar(100) NOT NULL, + PRIMARY KEY ([ContentMigrationMeasureMappingID]) +); +GO +ALTER TABLE [dbo].[ContentMigrationMeasureMapping] ADD CONSTRAINT [DF__ContentMi__SqlDa__3A169954] DEFAULT ('') FOR [SqlDataType]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CubeDirtyPartitionInfo ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CubeDirtyPartitionInfo] ( + [CubeDirtyPartitionInfoGuid] uniqueidentifier NOT NULL, + [Status] tinyint NOT NULL, + [PartitionNames] nvarchar(max) NOT NULL, + [StartTimeUtc] datetime NOT NULL, + [EndTimeUtc] datetime NULL, + [LastSuccessfulChangeTrackingID] bigint NOT NULL, + [CurrentChangeTrackingID] bigint NOT NULL, + [CubeProcessSuccess] bit NOT NULL, + PRIMARY KEY ([CubeDirtyPartitionInfoGuid]) +); +GO +ALTER TABLE [dbo].[CubeDirtyPartitionInfo] ADD CONSTRAINT [DF__CubeDirty__CubeD__24F3F30B] DEFAULT (newid()) FOR [CubeDirtyPartitionInfoGuid]; GO +ALTER TABLE [dbo].[CubeDirtyPartitionInfo] ADD CONSTRAINT [DF__CubeDirty__Statu__25E81744] DEFAULT ((0)) FOR [Status]; GO +ALTER TABLE [dbo].[CubeDirtyPartitionInfo] ADD CONSTRAINT [DF__CubeDirty__Parti__26DC3B7D] DEFAULT ('') FOR [PartitionNames]; GO +ALTER TABLE [dbo].[CubeDirtyPartitionInfo] ADD CONSTRAINT [DF__CubeDirty__Start__27D05FB6] DEFAULT (getutcdate()) FOR [StartTimeUtc]; GO +ALTER TABLE [dbo].[CubeDirtyPartitionInfo] ADD CONSTRAINT [DF__CubeDirty__LastS__28C483EF] DEFAULT ((0)) FOR [LastSuccessfulChangeTrackingID]; GO +ALTER TABLE [dbo].[CubeDirtyPartitionInfo] ADD CONSTRAINT [DF__CubeDirty__Curre__29B8A828] DEFAULT ((0)) FOR [CurrentChangeTrackingID]; GO +ALTER TABLE [dbo].[CubeDirtyPartitionInfo] ADD CONSTRAINT [DF__CubeDirty__CubeP__2AACCC61] DEFAULT ((0)) FOR [CubeProcessSuccess]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CubeIncrementalProcessMeasureGroups ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CubeIncrementalProcessMeasureGroups] ( + [RowID] int NOT NULL, + [MeasureGroupID] nvarchar(800) NOT NULL, + PRIMARY KEY ([RowID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CubeMeasureGroupDefaultMeasure ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CubeMeasureGroupDefaultMeasure] ( + [CubeMeasureGroupDefaultMeasureID] int NOT NULL, + [CubeName] nvarchar(100) NOT NULL, + [MeasureGroupName] nvarchar(100) NOT NULL, + [DefaultMeasureMDX] nvarchar(400) NOT NULL, + PRIMARY KEY ([CubeMeasureGroupDefaultMeasureID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [UQ_CUBENAMEMEASUREGROUPNAME] ON [dbo].[CubeMeasureGroupDefaultMeasure] ([CubeName], [MeasureGroupName]); +GO +ALTER TABLE [dbo].[CubeMeasureGroupDefaultMeasure] ADD CONSTRAINT [DF__CubeMeasu__Defau__00950485] DEFAULT ('') FOR [DefaultMeasureMDX]; GO +ALTER TABLE [dbo].[CubeMeasureGroupDefaultMeasure] ADD CONSTRAINT [DF__CubeMeasu__CubeN__7EACBC13] DEFAULT ('') FOR [CubeName]; GO +ALTER TABLE [dbo].[CubeMeasureGroupDefaultMeasure] ADD CONSTRAINT [DF__CubeMeasu__Measu__7FA0E04C] DEFAULT ('') FOR [MeasureGroupName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CubeUserRole ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CubeUserRole] ( + [CubeUserRoleGUID] uniqueidentifier NOT NULL, + [RoleName] nvarchar(100) NOT NULL, + [ServerName] nvarchar(400) NOT NULL, + [DatabaseName] nvarchar(400) NOT NULL, + [UserGroupGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([CubeUserRoleGUID]) +); +GO +ALTER TABLE [dbo].[CubeUserRole] ADD CONSTRAINT [FK__CubeUserR__UserG__2BF9C16D] FOREIGN KEY ([UserGroupGUID]) REFERENCES [dbo].[UserGroup] ([UserGroupGUID]); GO +ALTER TABLE [dbo].[CubeUserRole] ADD CONSTRAINT [DF__CubeUserR__Serve__258A58FB] DEFAULT ('') FOR [ServerName]; GO +ALTER TABLE [dbo].[CubeUserRole] ADD CONSTRAINT [DF__CubeUserR__Datab__267E7D34] DEFAULT ('') FOR [DatabaseName]; GO +ALTER TABLE [dbo].[CubeUserRole] ADD CONSTRAINT [DF__CubeUserR__CubeU__45380E7E] DEFAULT (newid()) FOR [CubeUserRoleGUID]; GO +ALTER TABLE [dbo].[CubeUserRole] ADD CONSTRAINT [DF__CubeUserR__RoleN__48147B29] DEFAULT ('') FOR [RoleName]; GO +ALTER TABLE [dbo].[CubeUserRole] ADD CONSTRAINT [DF__CubeUserR__UserG__2B059D34] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGroupGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CurrentUser ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CurrentUser] ( + [TokenGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [MachineGUID] uniqueidentifier NOT NULL, + [TokenType] int NOT NULL, + [UserName] nvarchar(64) NOT NULL, + [IPAddress] nvarchar(100) NOT NULL, + [LoginStampUtc] datetime NOT NULL, + [LastActionStampUtc] datetime NOT NULL, + [IdentityServerSessionId] nvarchar(100) NULL, + PRIMARY KEY ([TokenGUID]) +); +GO +ALTER TABLE [dbo].[CurrentUser] ADD CONSTRAINT [DF_CurrentUser_UserName] DEFAULT ('') FOR [UserName]; GO +ALTER TABLE [dbo].[CurrentUser] ADD CONSTRAINT [DF__CurrentUs__IPAdd__39D3430C] DEFAULT ('') FOR [IPAddress]; GO +ALTER TABLE [dbo].[CurrentUser] ADD CONSTRAINT [DF_CurrentUser_MachineGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MachineGUID]; GO +ALTER TABLE [dbo].[CurrentUser] ADD CONSTRAINT [DF_CurrentUser_TokenType] DEFAULT ((0)) FOR [TokenType]; GO +ALTER TABLE [dbo].[CurrentUser] ADD CONSTRAINT [DF__CurrentUs__Login__53368182] DEFAULT (getutcdate()) FOR [LoginStampUtc]; GO +ALTER TABLE [dbo].[CurrentUser] ADD CONSTRAINT [DF__CurrentUs__LastA__542AA5BB] DEFAULT (getutcdate()) FOR [LastActionStampUtc]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CustomAction ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CustomAction] ( + [ActionGUID] uniqueidentifier NOT NULL, + [AssemblyName] nvarchar(450) NOT NULL, + [ClassName] nvarchar(450) NOT NULL, + [Metadata] nvarchar(max) NOT NULL, + [Description] nvarchar(450) NOT NULL, + [ActionType] int NOT NULL, + [FolderGUID] uniqueidentifier NOT NULL, + [Confirmation] nvarchar(450) NOT NULL, + [SuccessMessage] nvarchar(450) NOT NULL, + [IsUsingContext] bit NOT NULL, + [IconKey] int NOT NULL, + PRIMARY KEY ([ActionGUID]) +); +GO +ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_ACTIONGUID] DEFAULT (newid()) FOR [ActionGUID]; GO +ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_ASSEMBLYNAME] DEFAULT ('') FOR [AssemblyName]; GO +ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_CLASSNAME] DEFAULT ('') FOR [ClassName]; GO +ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_ICONKEY] DEFAULT ((0)) FOR [IconKey]; GO +ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_METADATA] DEFAULT ('') FOR [Metadata]; GO +ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_ACTIONTYPE] DEFAULT ((1)) FOR [ActionType]; GO +ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_FolderGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO +ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_Confirmation] DEFAULT ('') FOR [Confirmation]; GO +ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_SuccessMessage] DEFAULT ('') FOR [SuccessMessage]; GO +ALTER TABLE [dbo].[CustomAction] ADD CONSTRAINT [DF_CustomAction_IsUsingContext] DEFAULT ((1)) FOR [IsUsingContext]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CustomMenu ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CustomMenu] ( + [CustomMenuGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Description] nvarchar(450) NOT NULL, + [PageID] nvarchar(64) NOT NULL, + [Type] int NOT NULL, + [IsGlobal] bit NOT NULL, + PRIMARY KEY ([CustomMenuGUID]) +); +GO +ALTER TABLE [dbo].[CustomMenu] ADD CONSTRAINT [DF_Table_1_WORKSPACETOOLBARGUID] DEFAULT (newid()) FOR [CustomMenuGUID]; GO +ALTER TABLE [dbo].[CustomMenu] ADD CONSTRAINT [DF_CustomMenu_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[CustomMenu] ADD CONSTRAINT [DF_CustomMenu_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[CustomMenu] ADD CONSTRAINT [DF_CustomMenu_PAGEID] DEFAULT ('') FOR [PageID]; GO +ALTER TABLE [dbo].[CustomMenu] ADD CONSTRAINT [DF_CustomMenu_TYPE] DEFAULT ((0)) FOR [Type]; GO +ALTER TABLE [dbo].[CustomMenu] ADD CONSTRAINT [DF_CustomMenu_ISGLOBAL] DEFAULT ((0)) FOR [IsGlobal]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CustomMenuContent ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CustomMenuContent] ( + [CustomMenuContentGUID] uniqueidentifier NOT NULL, + [CustomMenuGUID] uniqueidentifier NOT NULL, + [ContentXML] xml(max) NOT NULL, + PRIMARY KEY ([CustomMenuContentGUID]) +); +GO +ALTER TABLE [dbo].[CustomMenuContent] ADD CONSTRAINT [FK_CustomMenuContent_CustomMenu] FOREIGN KEY ([CustomMenuGUID]) REFERENCES [dbo].[CustomMenu] ([CustomMenuGUID]); GO +ALTER TABLE [dbo].[CustomMenuContent] ADD CONSTRAINT [DF_CustomMenuContent_CUSTOMMENUCONTENTGUID] DEFAULT (newid()) FOR [CustomMenuContentGUID]; GO +ALTER TABLE [dbo].[CustomMenuContent] ADD CONSTRAINT [DF_CustomMenuContent_CUSTOMMENUGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CustomMenuGUID]; GO +ALTER TABLE [dbo].[CustomMenuContent] ADD CONSTRAINT [DF_CustomMenuContent_CONTENTXML] DEFAULT ('') FOR [ContentXML]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.CustomScript ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[CustomScript] ( + [CustomScriptGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Description] nvarchar(450) NOT NULL, + [TimeoutSeconds] int NOT NULL, + [ScriptText] nvarchar(max) NOT NULL, + [IsSynchronous] bit NOT NULL, + [ScriptType] int NOT NULL, + [GlobalID] nvarchar(100) NOT NULL, + [FolderGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([CustomScriptGUID]) +); +GO +ALTER TABLE [dbo].[CustomScript] ADD CONSTRAINT [DF_CustomScript_Type] DEFAULT ((0)) FOR [ScriptType]; GO +ALTER TABLE [dbo].[CustomScript] ADD CONSTRAINT [DF_CustomScript_IsSynchronous] DEFAULT ((1)) FOR [IsSynchronous]; GO +ALTER TABLE [dbo].[CustomScript] ADD CONSTRAINT [DF__CustomScr__Globa__5378DED8] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [dbo].[CustomScript] ADD CONSTRAINT [DF_CustomScript_CustomSCRIPT] DEFAULT (newid()) FOR [CustomScriptGUID]; GO +ALTER TABLE [dbo].[CustomScript] ADD CONSTRAINT [DF_CustomScript_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[CustomScript] ADD CONSTRAINT [DF_CustomScript_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[CustomScript] ADD CONSTRAINT [DF_CustomScript_ScriptText] DEFAULT ('') FOR [ScriptText]; GO +ALTER TABLE [dbo].[CustomScript] ADD CONSTRAINT [DF_CustomScript_TimeoutSeconds] DEFAULT ((60)) FOR [TimeoutSeconds]; GO +ALTER TABLE [dbo].[CustomScript] ADD CONSTRAINT [DF__CustomScr__Folde__6776813B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DBSetting ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DBSetting] ( + [DBSettingGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(128) NOT NULL, + [Setting] nvarchar(4000) NOT NULL, + [LastModifiedDate] datetime NOT NULL, + [IsUserEditable] bit NOT NULL, + [IsUserReadable] bit NOT NULL, + [FriendlyName] nvarchar(64) NOT NULL, + PRIMARY KEY ([DBSettingGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_DBSetting] ON [dbo].[DBSetting] ([Name]); +GO +ALTER TABLE [dbo].[DBSetting] ADD CONSTRAINT [DF_DBSetting_IsUserEditable] DEFAULT ((0)) FOR [IsUserEditable]; GO +ALTER TABLE [dbo].[DBSetting] ADD CONSTRAINT [DF_DBSetting_IsUserReadDenied] DEFAULT ((0)) FOR [IsUserReadable]; GO +ALTER TABLE [dbo].[DBSetting] ADD CONSTRAINT [DF_DBSetting_FriendlyName] DEFAULT ('') FOR [FriendlyName]; GO +ALTER TABLE [dbo].[DBSetting] ADD CONSTRAINT [DF_DBSetting_DBSETTINGGUID] DEFAULT (newid()) FOR [DBSettingGUID]; GO +ALTER TABLE [dbo].[DBSetting] ADD CONSTRAINT [DF_DBSetting_LASTMODIFIEDDATE] DEFAULT (getdate()) FOR [LastModifiedDate]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DCInputConfig ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DCInputConfig] ( + [InputConfigGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [InputPluginAssembly] nvarchar(256) NOT NULL, + [InputPluginXML] nvarchar(max) NOT NULL, + [DCTableGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([InputConfigGUID]) +); +GO +ALTER TABLE [dbo].[DCInputConfig] ADD CONSTRAINT [DF_DCInputConfig_INPUTCONFIGGUID] DEFAULT (newid()) FOR [InputConfigGUID]; GO +ALTER TABLE [dbo].[DCInputConfig] ADD CONSTRAINT [DF_DCInputConfig_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[DCInputConfig] ADD CONSTRAINT [DF_DCInputConfig_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[DCInputConfig] ADD CONSTRAINT [DF_DCInputConfig_INPUTPLUGINSOURCE] DEFAULT ('') FOR [InputPluginAssembly]; GO +ALTER TABLE [dbo].[DCInputConfig] ADD CONSTRAINT [DF_DCInputConfig_INPUTPLUGINXML] DEFAULT ('') FOR [InputPluginXML]; GO +ALTER TABLE [dbo].[DCInputConfig] ADD CONSTRAINT [DF_DCInputConfig_DCTABLEGUID] DEFAULT (newid()) FOR [DCTableGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DCOutputConfig ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DCOutputConfig] ( + [OutputConfigGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [OutputPluginAssembly] nvarchar(256) NOT NULL, + [OutputPluginXML] nvarchar(max) NOT NULL, + [LastRunDate] datetime NOT NULL, + PRIMARY KEY ([OutputConfigGUID]) +); +GO +ALTER TABLE [dbo].[DCOutputConfig] ADD CONSTRAINT [DF_DCOutputConfig_OUTPUTCONFIGGUID] DEFAULT (newid()) FOR [OutputConfigGUID]; GO +ALTER TABLE [dbo].[DCOutputConfig] ADD CONSTRAINT [DF_DCOutputConfig_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[DCOutputConfig] ADD CONSTRAINT [DF_DCOutputConfig_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[DCOutputConfig] ADD CONSTRAINT [DF_DCOutputConfig_OUTPUTPLUGINASSEMBLY] DEFAULT ('') FOR [OutputPluginAssembly]; GO +ALTER TABLE [dbo].[DCOutputConfig] ADD CONSTRAINT [DF_DCOutputConfig_OUTPUTPLUGINXML] DEFAULT ('') FOR [OutputPluginXML]; GO +ALTER TABLE [dbo].[DCOutputConfig] ADD CONSTRAINT [DF_DCOutputConfig_LASTRUNDATE] DEFAULT ('1/1/2000') FOR [LastRunDate]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DCTable ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DCTable] ( + [TableGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [Source] nvarchar(256) NOT NULL, + [DateCreated] datetime NOT NULL, + [LastUpdatedDate] datetime NOT NULL, + PRIMARY KEY ([TableGUID]) +); +GO +ALTER TABLE [dbo].[DCTable] ADD CONSTRAINT [DF_DATACENTERTABLE_DATACENTERTABLEGUID] DEFAULT (newid()) FOR [TableGUID]; GO +ALTER TABLE [dbo].[DCTable] ADD CONSTRAINT [DF_DATACENTERTABLE_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[DCTable] ADD CONSTRAINT [DF_DATACENTERTABLE_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[DCTable] ADD CONSTRAINT [DF_DCTable_FILENAME] DEFAULT ('') FOR [Source]; GO +ALTER TABLE [dbo].[DCTable] ADD CONSTRAINT [DF_DCTable_DATECREATED] DEFAULT (getdate()) FOR [DateCreated]; GO +ALTER TABLE [dbo].[DCTable] ADD CONSTRAINT [DF_DCTable_LASTUPDATEDDATE] DEFAULT ('1/1/2000') FOR [LastUpdatedDate]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DashboardWidget ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DashboardWidget] ( + [DashboardWidgetGUID] uniqueidentifier NOT NULL, + [DesktopTemplateGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Row] int NOT NULL, + [Col] int NOT NULL, + [Height] int NOT NULL, + [Width] int NOT NULL, + [WidgetJSON] nvarchar(max) NOT NULL, + [WidgetClassName] nvarchar(100) NOT NULL, + [DataSourceGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([DashboardWidgetGUID]) +); +GO +ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [FK__Dashboard__Deskt__05EB2160] FOREIGN KEY ([DesktopTemplateGUID]) REFERENCES [dbo].[DesktopTemplate] ([DesktopTemplateGUID]); GO +ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [DF__Dashboard__Dashb__0402D8EE] DEFAULT (newid()) FOR [DashboardWidgetGUID]; GO +ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [DF__Dashboard__Deskt__04F6FD27] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DesktopTemplateGUID]; GO +ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [DF__DashboardW__Name__06DF4599] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [DF__DashboardWi__Row__07D369D2] DEFAULT ((0)) FOR [Row]; GO +ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [DF__DashboardWi__Col__08C78E0B] DEFAULT ((0)) FOR [Col]; GO +ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [DF__Dashboard__Heigh__09BBB244] DEFAULT ((0)) FOR [Height]; GO +ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [DF__Dashboard__Width__0AAFD67D] DEFAULT ((0)) FOR [Width]; GO +ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [DF__Dashboard__Widge__0B39E662] DEFAULT ('') FOR [WidgetJSON]; GO +ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [DF__Dashboard__Widge__0C2E0A9B] DEFAULT ('') FOR [WidgetClassName]; GO +ALTER TABLE [dbo].[DashboardWidget] ADD CONSTRAINT [DF__Dashboard__DataS__404D9876] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataSourceGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DashboardWidgetCache ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DashboardWidgetCache] ( + [DashboardWidgetCacheGUID] uniqueidentifier NOT NULL, + [DashboardWidgetGUID] uniqueidentifier NOT NULL, + [DesktopTemplateGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [Data] nvarchar(max) NOT NULL, + [DateCreated] datetime NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + PRIMARY KEY ([DashboardWidgetCacheGUID]) +); +GO +ALTER TABLE [dbo].[DashboardWidgetCache] ADD CONSTRAINT [FK__Dashboard__Dashb__38AC76AE] FOREIGN KEY ([DashboardWidgetGUID]) REFERENCES [dbo].[DashboardWidget] ([DashboardWidgetGUID]); GO +ALTER TABLE [dbo].[DashboardWidgetCache] ADD CONSTRAINT [DF__Dashboard__Dashb__36C42E3C] DEFAULT (newid()) FOR [DashboardWidgetCacheGUID]; GO +ALTER TABLE [dbo].[DashboardWidgetCache] ADD CONSTRAINT [DF__Dashboard__DateC__378E670D] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [dbo].[DashboardWidgetCache] ADD CONSTRAINT [DF__Dashboard__Dashb__37B85275] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DashboardWidgetGUID]; GO +ALTER TABLE [dbo].[DashboardWidgetCache] ADD CONSTRAINT [DF__Dashboard__Deskt__39A09AE7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DesktopTemplateGUID]; GO +ALTER TABLE [dbo].[DashboardWidgetCache] ADD CONSTRAINT [DF__Dashboard__UserG__3A94BF20] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[DashboardWidgetCache] ADD CONSTRAINT [DF__DashboardW__Data__3B88E359] DEFAULT ('') FOR [Data]; GO +ALTER TABLE [dbo].[DashboardWidgetCache] ADD CONSTRAINT [DF__Dashboard__DateC__3C7D0792] DEFAULT (getdate()) FOR [DateCreated]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DataCenterCustomReportLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DataCenterCustomReportLink] ( + [ReportLinkGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [ModuleGUID] uniqueidentifier NOT NULL, + [TileGlobalID] varchar(100) NOT NULL, + PRIMARY KEY ([ReportLinkGUID]) +); +GO +ALTER TABLE [dbo].[DataCenterCustomReportLink] ADD CONSTRAINT [FK__DataCente__Modul__1893E180] FOREIGN KEY ([ModuleGUID]) REFERENCES [dbo].[SystemCenterModule] ([ModuleGUID]); GO +ALTER TABLE [dbo].[DataCenterCustomReportLink] ADD CONSTRAINT [FK__DataCente__Repor__179FBD47] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[DataCenterCustomReportLink] ADD CONSTRAINT [DF__DataCente__Repor__16AB990E] DEFAULT (newid()) FOR [ReportLinkGUID]; GO +ALTER TABLE [dbo].[DataCenterCustomReportLink] ADD CONSTRAINT [DF__DataCente__TileG__22682FD4] DEFAULT ('') FOR [TileGlobalID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DataCenterCustomReportWorkbookLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DataCenterCustomReportWorkbookLink] ( + [ReportLinkGUID] uniqueidentifier NOT NULL, + [ModuleGUID] uniqueidentifier NOT NULL, + [TileGlobalID] nvarchar(100) NOT NULL, + [WorkbookID] int NOT NULL, + PRIMARY KEY ([ReportLinkGUID]) +); +GO +ALTER TABLE [dbo].[DataCenterCustomReportWorkbookLink] ADD CONSTRAINT [FK_CustomReportWorkbook_Module] FOREIGN KEY ([ModuleGUID]) REFERENCES [dbo].[SystemCenterModule] ([ModuleGUID]); GO +ALTER TABLE [dbo].[DataCenterCustomReportWorkbookLink] ADD CONSTRAINT [DF__DataCente__Repor__7C3C8FC8] DEFAULT (newid()) FOR [ReportLinkGUID]; GO +ALTER TABLE [dbo].[DataCenterCustomReportWorkbookLink] ADD CONSTRAINT [DF__DataCente__TileG__7D30B401] DEFAULT ('') FOR [TileGlobalID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DataCenterDimensionConfig ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DataCenterDimensionConfig] ( + [DimensionName] nvarchar(200) NOT NULL, + [DataCenterPageName] nvarchar(200) NOT NULL, + [SystemCenterStepGlobalIDExisting] nvarchar(100) NOT NULL, + [SystemCenterStepGlobalIDNew] nvarchar(100) NOT NULL, + PRIMARY KEY ([DimensionName]) +); +GO +ALTER TABLE [dbo].[DataCenterDimensionConfig] ADD CONSTRAINT [DF__DataCente__DataC__02C4CDBC] DEFAULT ('') FOR [DataCenterPageName]; GO +ALTER TABLE [dbo].[DataCenterDimensionConfig] ADD CONSTRAINT [DF__DataCente__Syste__03B8F1F5] DEFAULT ('') FOR [SystemCenterStepGlobalIDExisting]; GO +ALTER TABLE [dbo].[DataCenterDimensionConfig] ADD CONSTRAINT [DF__DataCente__Syste__04AD162E] DEFAULT ('') FOR [SystemCenterStepGlobalIDNew]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DataDictionaryFieldValueExample ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DataDictionaryFieldValueExample] ( + [ScoreGUID] uniqueidentifier NOT NULL, + [ExampleValue] nvarchar(4000) NOT NULL, + PRIMARY KEY ([ScoreGUID]) +); +GO +ALTER TABLE [dbo].[DataDictionaryFieldValueExample] ADD CONSTRAINT [DF_DataDictionaryFieldValueExample_ScoreGUID] DEFAULT (newid()) FOR [ScoreGUID]; GO +ALTER TABLE [dbo].[DataDictionaryFieldValueExample] ADD CONSTRAINT [DF_DataDictionaryFieldValueExample_ExampleValue] DEFAULT ('') FOR [ExampleValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DataPathFile ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DataPathFile] ( + [FileGUID] uniqueidentifier NOT NULL, + [FullPath] varchar(450) NOT NULL, + [FileName] varchar(450) NOT NULL, + [CreationTime] datetime NOT NULL, + [LastModifiedTime] datetime NOT NULL, + [Data] varbinary(max) NOT NULL, + [IsLocked] bit NOT NULL, + [LockTime] datetime NOT NULL, + [LockOwner] uniqueidentifier NOT NULL, + PRIMARY KEY ([FileGUID]) +); + +CREATE UNIQUE CLUSTERED INDEX [IDX_DataPathFile] ON [dbo].[DataPathFile] ([FullPath]); +GO +ALTER TABLE [dbo].[DataPathFile] ADD CONSTRAINT [DF_DataPathFile_LockOwner] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LockOwner]; GO +ALTER TABLE [dbo].[DataPathFile] ADD CONSTRAINT [DF_DataPathFile_IsLocked] DEFAULT ((0)) FOR [IsLocked]; GO +ALTER TABLE [dbo].[DataPathFile] ADD CONSTRAINT [DF_DataPathFile_LockTime] DEFAULT (getdate()) FOR [LockTime]; GO +ALTER TABLE [dbo].[DataPathFile] ADD CONSTRAINT [DF_DataPathFile_CreationTime] DEFAULT (getdate()) FOR [CreationTime]; GO +ALTER TABLE [dbo].[DataPathFile] ADD CONSTRAINT [DF_DataPathFile_LastModifiedTime] DEFAULT (getdate()) FOR [LastModifiedTime]; GO +ALTER TABLE [dbo].[DataPathFile] ADD CONSTRAINT [DF_DataPathFile_FileGUID] DEFAULT (newid()) FOR [FileGUID]; GO +ALTER TABLE [dbo].[DataPathFile] ADD CONSTRAINT [DF_DataPathFile_FullPath] DEFAULT ('') FOR [FullPath]; GO +ALTER TABLE [dbo].[DataPathFile] ADD CONSTRAINT [DF_DataPathFile_FileName] DEFAULT ('') FOR [FileName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DataPathFile_History ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DataPathFile_History] ( + [FileGUID] uniqueidentifier NOT NULL, + [FullPath] varchar(450) NOT NULL, + [FileName] varchar(450) NOT NULL, + [CreationTime] datetime NOT NULL, + [LastModifiedTime] datetime NOT NULL, + [Data] varbinary(max) NOT NULL, + [IsLocked] bit NOT NULL, + [LockTime] datetime NOT NULL, + [LockOwner] uniqueidentifier NOT NULL, + PRIMARY KEY ([FileGUID]) +); + +CREATE CLUSTERED INDEX [C_DataPathFile_History] ON [dbo].[DataPathFile_History] ([FullPath], [LockOwner], [IsLocked]); +CREATE NONCLUSTERED INDEX [NCNU_FullPath] ON [dbo].[DataPathFile_History] ([FullPath]); +GO +ALTER TABLE [dbo].[DataPathFile_History] ADD CONSTRAINT [DF_DataPathFile_History_FileGUID] DEFAULT (newid()) FOR [FileGUID]; GO +ALTER TABLE [dbo].[DataPathFile_History] ADD CONSTRAINT [DF_DataPathFile_History_FullPath] DEFAULT ('') FOR [FullPath]; GO +ALTER TABLE [dbo].[DataPathFile_History] ADD CONSTRAINT [DF_DataPathFile_History_FileName] DEFAULT ('') FOR [FileName]; GO +ALTER TABLE [dbo].[DataPathFile_History] ADD CONSTRAINT [DF_DataPathFile_History_CreationTime] DEFAULT (getdate()) FOR [CreationTime]; GO +ALTER TABLE [dbo].[DataPathFile_History] ADD CONSTRAINT [DF_DataPathFile_History_LastModifiedTime] DEFAULT (getdate()) FOR [LastModifiedTime]; GO +ALTER TABLE [dbo].[DataPathFile_History] ADD CONSTRAINT [DF_DataPathFile_History_IsLocked] DEFAULT ((0)) FOR [IsLocked]; GO +ALTER TABLE [dbo].[DataPathFile_History] ADD CONSTRAINT [DF_DataPathFile_History_LockTime] DEFAULT (getdate()) FOR [LockTime]; GO +ALTER TABLE [dbo].[DataPathFile_History] ADD CONSTRAINT [DF_DataPathFile_History_LockOwner] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LockOwner]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DataPathFile_Improv ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DataPathFile_Improv] ( + [FileGUID] uniqueidentifier NOT NULL, + [FullPath] varchar(450) NOT NULL, + [FileName] varchar(450) NOT NULL, + [CreationTime] datetime NOT NULL, + [LastModifiedTime] datetime NOT NULL, + [Data] varbinary(max) NOT NULL, + [IsLocked] bit NOT NULL, + [LockTime] datetime NOT NULL, + [LockOwner] uniqueidentifier NOT NULL, + PRIMARY KEY ([FileGUID]) +); + +CREATE CLUSTERED INDEX [C_DataPathFile_Improv] ON [dbo].[DataPathFile_Improv] ([FullPath], [LockOwner], [IsLocked]); +CREATE NONCLUSTERED INDEX [NCNU_FullPath] ON [dbo].[DataPathFile_Improv] ([FullPath]); +GO +ALTER TABLE [dbo].[DataPathFile_Improv] ADD CONSTRAINT [DF_DataPathFile_Improv_FileGUID] DEFAULT (newid()) FOR [FileGUID]; GO +ALTER TABLE [dbo].[DataPathFile_Improv] ADD CONSTRAINT [DF_DataPathFile_Improv_FullPath] DEFAULT ('') FOR [FullPath]; GO +ALTER TABLE [dbo].[DataPathFile_Improv] ADD CONSTRAINT [DF_DataPathFile_Improv_FileName] DEFAULT ('') FOR [FileName]; GO +ALTER TABLE [dbo].[DataPathFile_Improv] ADD CONSTRAINT [DF_DataPathFile_Improv_CreationTime] DEFAULT (getdate()) FOR [CreationTime]; GO +ALTER TABLE [dbo].[DataPathFile_Improv] ADD CONSTRAINT [DF_DataPathFile_Improv_LastModifiedTime] DEFAULT (getdate()) FOR [LastModifiedTime]; GO +ALTER TABLE [dbo].[DataPathFile_Improv] ADD CONSTRAINT [DF_DataPathFile_Improv_IsLocked] DEFAULT ((0)) FOR [IsLocked]; GO +ALTER TABLE [dbo].[DataPathFile_Improv] ADD CONSTRAINT [DF_DataPathFile_Improv_LockTime] DEFAULT (getdate()) FOR [LockTime]; GO +ALTER TABLE [dbo].[DataPathFile_Improv] ADD CONSTRAINT [DF_DataPathFile_Improv_LockOwner] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LockOwner]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DataPathFile_ModelTemplate ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DataPathFile_ModelTemplate] ( + [FileGUID] uniqueidentifier NOT NULL, + [FullPath] varchar(450) NOT NULL, + [FileName] varchar(450) NOT NULL, + [CreationTime] datetime NOT NULL, + [LastModifiedTime] datetime NOT NULL, + [Data] varbinary(max) NOT NULL, + [IsLocked] bit NOT NULL, + [LockTime] datetime NOT NULL, + [LockOwner] uniqueidentifier NOT NULL, + PRIMARY KEY ([FileGUID]) +); + +CREATE NONCLUSTERED INDEX [NCNU_FullPath] ON [dbo].[DataPathFile_ModelTemplate] ([FullPath]); +GO +ALTER TABLE [dbo].[DataPathFile_ModelTemplate] ADD CONSTRAINT [DF_DataPathFile_ModelTemplate_FileGUID] DEFAULT (newid()) FOR [FileGUID]; GO +ALTER TABLE [dbo].[DataPathFile_ModelTemplate] ADD CONSTRAINT [DF_DataPathFile_ModelTemplate_FullPath] DEFAULT ('') FOR [FullPath]; GO +ALTER TABLE [dbo].[DataPathFile_ModelTemplate] ADD CONSTRAINT [DF_DataPathFile_ModelTemplate_LockOwner] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LockOwner]; GO +ALTER TABLE [dbo].[DataPathFile_ModelTemplate] ADD CONSTRAINT [DF_DataPathFile_ModelTemplate_FileName] DEFAULT ('') FOR [FileName]; GO +ALTER TABLE [dbo].[DataPathFile_ModelTemplate] ADD CONSTRAINT [DF_DataPathFile_ModelTemplate_CreationTime] DEFAULT (getdate()) FOR [CreationTime]; GO +ALTER TABLE [dbo].[DataPathFile_ModelTemplate] ADD CONSTRAINT [DF_DataPathFile_ModelTemplate_LastModifiedTime] DEFAULT (getdate()) FOR [LastModifiedTime]; GO +ALTER TABLE [dbo].[DataPathFile_ModelTemplate] ADD CONSTRAINT [DF_DataPathFile_ModelTemplate_IsLocked] DEFAULT ((0)) FOR [IsLocked]; GO +ALTER TABLE [dbo].[DataPathFile_ModelTemplate] ADD CONSTRAINT [DF_DataPathFile_ModelTemplate_LockTime] DEFAULT (getdate()) FOR [LockTime]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DataPathFile_Reporting ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DataPathFile_Reporting] ( + [FileGUID] uniqueidentifier NOT NULL, + [FullPath] varchar(450) NOT NULL, + [FileName] varchar(450) NOT NULL, + [CreationTime] datetime NOT NULL, + [LastModifiedTime] datetime NOT NULL, + [Data] varbinary(max) NOT NULL, + [IsLocked] bit NOT NULL, + [LockTime] datetime NOT NULL, + [LockOwner] uniqueidentifier NOT NULL, + PRIMARY KEY ([FileGUID]) +); + +CREATE CLUSTERED INDEX [C_DataPathFile_Reporting] ON [dbo].[DataPathFile_Reporting] ([FullPath], [LockOwner], [IsLocked]); +CREATE NONCLUSTERED INDEX [NCNU_FullPath] ON [dbo].[DataPathFile_Reporting] ([FullPath]); +GO +ALTER TABLE [dbo].[DataPathFile_Reporting] ADD CONSTRAINT [DF_DataPathFile_Reporting_LockOwner] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LockOwner]; GO +ALTER TABLE [dbo].[DataPathFile_Reporting] ADD CONSTRAINT [DF_DataPathFile_Reporting_FileGUID] DEFAULT (newid()) FOR [FileGUID]; GO +ALTER TABLE [dbo].[DataPathFile_Reporting] ADD CONSTRAINT [DF_DataPathFile_Reporting_FullPath] DEFAULT ('') FOR [FullPath]; GO +ALTER TABLE [dbo].[DataPathFile_Reporting] ADD CONSTRAINT [DF_DataPathFile_Reporting_FileName] DEFAULT ('') FOR [FileName]; GO +ALTER TABLE [dbo].[DataPathFile_Reporting] ADD CONSTRAINT [DF_DataPathFile_Reporting_CreationTime] DEFAULT (getdate()) FOR [CreationTime]; GO +ALTER TABLE [dbo].[DataPathFile_Reporting] ADD CONSTRAINT [DF_DataPathFile_Reporting_LastModifiedTime] DEFAULT (getdate()) FOR [LastModifiedTime]; GO +ALTER TABLE [dbo].[DataPathFile_Reporting] ADD CONSTRAINT [DF_DataPathFile_Reporting_IsLocked] DEFAULT ((0)) FOR [IsLocked]; GO +ALTER TABLE [dbo].[DataPathFile_Reporting] ADD CONSTRAINT [DF_DataPathFile_Reporting_LockTime] DEFAULT (getdate()) FOR [LockTime]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DataSourceContent ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DataSourceContent] ( + [DataSourceContentGUID] uniqueidentifier NOT NULL, + [DataSourceGUID] uniqueidentifier NOT NULL, + [ParentGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Description] nvarchar(450) NOT NULL, + [AssemblyQualifiedName] nvarchar(450) NOT NULL, + [LastRefreshDate] datetime NOT NULL, + [SetupXML] nvarchar(max) NOT NULL, + [DataXML] nvarchar(max) NOT NULL, + PRIMARY KEY ([DataSourceContentGUID]) +); +GO +ALTER TABLE [dbo].[DataSourceContent] ADD CONSTRAINT [DF_DataSourceContent_DATASOURCECONTENTGUID] DEFAULT (newid()) FOR [DataSourceContentGUID]; GO +ALTER TABLE [dbo].[DataSourceContent] ADD CONSTRAINT [DF_DataSourceContent_DATASOURCEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataSourceGUID]; GO +ALTER TABLE [dbo].[DataSourceContent] ADD CONSTRAINT [DF_DataSourceContent_PARENTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentGUID]; GO +ALTER TABLE [dbo].[DataSourceContent] ADD CONSTRAINT [DF_DataSourceContent_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[DataSourceContent] ADD CONSTRAINT [DF_DataSourceContent_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[DataSourceContent] ADD CONSTRAINT [DF_DataSourceContent_ASSEMBLYQUALIFIEDNAME] DEFAULT ('') FOR [AssemblyQualifiedName]; GO +ALTER TABLE [dbo].[DataSourceContent] ADD CONSTRAINT [DF_DataSourceContent_SETUPXML] DEFAULT ('') FOR [SetupXML]; GO +ALTER TABLE [dbo].[DataSourceContent] ADD CONSTRAINT [DF_DataSourceContent_DATAXML] DEFAULT ('') FOR [DataXML]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DataView ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DataView] ( + [DataViewGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [SQLViewName] nvarchar(450) NOT NULL, + [SourceGUID] uniqueidentifier NOT NULL, + [SourceType] int NOT NULL, + [SecurityColumns] nvarchar(450) NOT NULL, + [SampleTableGUID] uniqueidentifier NOT NULL, + [MetricColumnName] nvarchar(50) NOT NULL, + [PlanColumnName] nvarchar(100) NOT NULL, + [Description] nvarchar(2000) NOT NULL, + [FrameworkGUID] uniqueidentifier NOT NULL, + [IsOptionRecompile] bit NOT NULL, + PRIMARY KEY ([DataViewGUID]) +); +GO +ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF_DataView_PlanColumnName] DEFAULT ('') FOR [PlanColumnName]; GO +ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF__DataView__Descri__2A6519D2] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF__DataView__Framew__3F59743D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FrameworkGUID]; GO +ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF_DataView_DataViewGUID] DEFAULT (newid()) FOR [DataViewGUID]; GO +ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF_DataView_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF_DataView_SQLViewName] DEFAULT ('') FOR [SQLViewName]; GO +ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF_DataView_SourceGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SourceGUID]; GO +ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF_DataView_SourceType] DEFAULT ((0)) FOR [SourceType]; GO +ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF_DataView_SecurityColumns] DEFAULT ('') FOR [SecurityColumns]; GO +ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF_DataView_SampleTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SampleTableGUID]; GO +ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF_DataView_MetricColumnName] DEFAULT ('') FOR [MetricColumnName]; GO +ALTER TABLE [dbo].[DataView] ADD CONSTRAINT [DF__DataView__IsOpti__7B3F1545] DEFAULT ((0)) FOR [IsOptionRecompile]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DateMap ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DateMap] ( + [SourceDate] date NULL, + [TargetDate] date NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DemoUser ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DemoUser] ( + [UserGUID] uniqueidentifier NOT NULL, + [DisplayName] nvarchar(100) NOT NULL, + PRIMARY KEY ([UserGUID]) +); +GO +ALTER TABLE [dbo].[DemoUser] ADD CONSTRAINT [FK_DemoUser_UserProfile] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO +ALTER TABLE [dbo].[DemoUser] ADD CONSTRAINT [DF_DemoUser_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[DemoUser] ADD CONSTRAINT [DF_DemoUser_DisplayName] DEFAULT ('') FOR [DisplayName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DepartmentIDLog ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DepartmentIDLog] ( + [RowID] int NOT NULL, + [Step] nvarchar(100) NOT NULL, + [Type] nvarchar(10) NOT NULL, + [Script] nvarchar(max) NOT NULL, + [StartTime] datetime NULL, + [EndTime] datetime NULL, + [IsComplete] bit NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [dbo].[DepartmentIDLog] ADD CONSTRAINT [DF_DepartmentIDLog_Step] DEFAULT ('') FOR [Step]; GO +ALTER TABLE [dbo].[DepartmentIDLog] ADD CONSTRAINT [DF_DepartmentIDLog_Type] DEFAULT ('') FOR [Type]; GO +ALTER TABLE [dbo].[DepartmentIDLog] ADD CONSTRAINT [DF_DepartmentIDLog_Script] DEFAULT ('') FOR [Script]; GO +ALTER TABLE [dbo].[DepartmentIDLog] ADD CONSTRAINT [DF_DepartmentIDLog_IsComplete] DEFAULT ((0)) FOR [IsComplete]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DesktopCategory ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DesktopCategory] ( + [DesktopCategoryGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(50) NOT NULL, + [IconCls] nvarchar(50) NOT NULL, + [ModuleGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([DesktopCategoryGUID]) +); +GO +ALTER TABLE [dbo].[DesktopCategory] ADD CONSTRAINT [DF__DesktopCa__Modul__1BE2221B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModuleGUID]; GO +ALTER TABLE [dbo].[DesktopCategory] ADD CONSTRAINT [DF_DesktopCategory_DesktopCategoryGUID] DEFAULT (newid()) FOR [DesktopCategoryGUID]; GO +ALTER TABLE [dbo].[DesktopCategory] ADD CONSTRAINT [DF_DesktopTemplateCategory_CategoryIconCls] DEFAULT ('') FOR [IconCls]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DesktopColumn ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DesktopColumn] ( + [DesktopColumnGUID] uniqueidentifier NOT NULL, + [DesktopTemplateGUID] uniqueidentifier NOT NULL, + [WidthRatio] float NOT NULL, + [ColumnIndex] int NOT NULL, + PRIMARY KEY ([DesktopColumnGUID]) +); +GO +ALTER TABLE [dbo].[DesktopColumn] ADD CONSTRAINT [FK_DesktopColumn_DesktopTemplate] FOREIGN KEY ([DesktopTemplateGUID]) REFERENCES [dbo].[DesktopTemplate] ([DesktopTemplateGUID]); GO +ALTER TABLE [dbo].[DesktopColumn] ADD CONSTRAINT [DF_DesktopColumn_DesktopColumnGUID] DEFAULT (newid()) FOR [DesktopColumnGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DesktopParameter ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DesktopParameter] ( + [DesktopParameterGUID] uniqueidentifier NOT NULL, + [DesktopTemplateGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(200) NOT NULL, + [ColumnName] nvarchar(200) NOT NULL, + [ParameterXML] nvarchar(max) NOT NULL, + [DimensionId] nvarchar(200) NOT NULL, + [AttributeId] nvarchar(200) NOT NULL, + [MeasureId] nvarchar(200) NOT NULL, + [ParameterValueAQN] nvarchar(400) NOT NULL, + [ReportGuidsCSV] nvarchar(max) NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [DimensionName] nvarchar(200) NOT NULL, + [AttributeName] nvarchar(200) NOT NULL, + [DataSourceGUID] uniqueidentifier NOT NULL, + [ExcludedWidgetGuidsCSV] nvarchar(max) NOT NULL, + PRIMARY KEY ([DesktopParameterGUID]) +); +GO +ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [FK__DesktopPa__Deskt__43084118] FOREIGN KEY ([DesktopTemplateGUID]) REFERENCES [dbo].[DesktopTemplate] ([DesktopTemplateGUID]); GO +ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Exclu__30C13C23] DEFAULT ('') FOR [ExcludedWidgetGuidsCSV]; GO +ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__UserG__33E7C191] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Deskt__42141CDF] DEFAULT (newid()) FOR [DesktopParameterGUID]; GO +ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPar__Name__43FC6551] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Colum__44F0898A] DEFAULT ('') FOR [ColumnName]; GO +ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Param__45E4ADC3] DEFAULT ('') FOR [ParameterXML]; GO +ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Dimen__46D8D1FC] DEFAULT ('') FOR [DimensionId]; GO +ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Attri__47CCF635] DEFAULT ('') FOR [AttributeId]; GO +ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Measu__48C11A6E] DEFAULT ('') FOR [MeasureId]; GO +ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Param__49B53EA7] DEFAULT ('') FOR [ParameterValueAQN]; GO +ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Repor__4AA962E0] DEFAULT ('') FOR [ReportGuidsCSV]; GO +ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Dimen__53606CEA] DEFAULT ('') FOR [DimensionName]; GO +ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__Attri__54549123] DEFAULT ('') FOR [AttributeName]; GO +ALTER TABLE [dbo].[DesktopParameter] ADD CONSTRAINT [DF__DesktopPa__DataS__5548B55C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataSourceGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DesktopTemplate ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DesktopTemplate] ( + [DesktopTemplateGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [ReadableUserCount] int NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [ModuleGUID] uniqueidentifier NOT NULL, + [DateCreated] datetime NOT NULL, + [IsLegacy] bit NOT NULL, + [Description] nvarchar(450) NOT NULL, + [StrataSphereDashboardGUID] uniqueidentifier NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + PRIMARY KEY ([DesktopTemplateGUID]) +); +GO +ALTER TABLE [dbo].[DesktopTemplate] ADD CONSTRAINT [DF__DesktopTe__Descr__0BA3FAB6] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[DesktopTemplate] ADD CONSTRAINT [DF_DesktopTemplate_DesktopTemplateGUID_1] DEFAULT (newid()) FOR [DesktopTemplateGUID]; GO +ALTER TABLE [dbo].[DesktopTemplate] ADD CONSTRAINT [DF_DesktopTemplate_Name_1] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[DesktopTemplate] ADD CONSTRAINT [DF_DesktopTemplate_ReadableUserCount] DEFAULT ((1)) FOR [ReadableUserCount]; GO +ALTER TABLE [dbo].[DesktopTemplate] ADD CONSTRAINT [DF__DesktopTe__DateC__38828B46] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [dbo].[DesktopTemplate] ADD CONSTRAINT [DF_DesktopTemplate_AuthorGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [dbo].[DesktopTemplate] ADD CONSTRAINT [DF__DesktopTe__Modul__7C61B726] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModuleGUID]; GO +ALTER TABLE [dbo].[DesktopTemplate] ADD CONSTRAINT [DF__DesktopTe__DateC__7D55DB5F] DEFAULT (getdate()) FOR [DateCreated]; GO +ALTER TABLE [dbo].[DesktopTemplate] ADD CONSTRAINT [DF__DesktopTe__IsLeg__7E49FF98] DEFAULT ((0)) FOR [IsLegacy]; GO +ALTER TABLE [dbo].[DesktopTemplate] ADD CONSTRAINT [DF_DesktopTemplate_StrataSphereDashboardGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [StrataSphereDashboardGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DesktopTemplateUserLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DesktopTemplateUserLink] ( + [DesktopTemplateGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [DisplayOrder] smallint NOT NULL, + [IsVisible] bit NOT NULL, + PRIMARY KEY ([DesktopTemplateGUID], [UserGUID]) +); +GO +ALTER TABLE [dbo].[DesktopTemplateUserLink] ADD CONSTRAINT [FK_DesktopTemplateUserLink_DesktopTemplate] FOREIGN KEY ([DesktopTemplateGUID]) REFERENCES [dbo].[DesktopTemplate] ([DesktopTemplateGUID]); GO +ALTER TABLE [dbo].[DesktopTemplateUserLink] ADD CONSTRAINT [DF_DesktopTemplateUserLink_Visible] DEFAULT ((1)) FOR [IsVisible]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DesktopWidget ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DesktopWidget] ( + [DesktopWidgetGUID] uniqueidentifier NOT NULL, + [DesktopTemplateGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [HelpText] nvarchar(4000) NOT NULL, + [IsCollapsed] bit NOT NULL, + [IsCollapsible] bit NOT NULL, + [IsMovable] bit NOT NULL, + [RowIndex] int NOT NULL, + [ColumnIndex] int NOT NULL, + [WidgetFullName] nvarchar(4000) NOT NULL, + [WidgetXML] nvarchar(max) NOT NULL, + [Height] int NOT NULL, + PRIMARY KEY ([DesktopWidgetGUID]) +); +GO +ALTER TABLE [dbo].[DesktopWidget] ADD CONSTRAINT [FK_DesktopWidget_DesktopTemplate] FOREIGN KEY ([DesktopTemplateGUID]) REFERENCES [dbo].[DesktopTemplate] ([DesktopTemplateGUID]); GO +ALTER TABLE [dbo].[DesktopWidget] ADD CONSTRAINT [DF_DesktopWidget_DesktopWidgetGUID] DEFAULT (newid()) FOR [DesktopWidgetGUID]; GO +ALTER TABLE [dbo].[DesktopWidget] ADD CONSTRAINT [DF_DesktopWidget_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[DesktopWidget] ADD CONSTRAINT [DF_DesktopWidget_HelpText] DEFAULT ('') FOR [HelpText]; GO +ALTER TABLE [dbo].[DesktopWidget] ADD CONSTRAINT [DF_DesktopWidget_IsCollapsed] DEFAULT ((0)) FOR [IsCollapsed]; GO +ALTER TABLE [dbo].[DesktopWidget] ADD CONSTRAINT [DF_DesktopWidget_Collapsible] DEFAULT ((0)) FOR [IsCollapsible]; GO +ALTER TABLE [dbo].[DesktopWidget] ADD CONSTRAINT [DF_DesktopWidget_Movable] DEFAULT ((1)) FOR [IsMovable]; GO +ALTER TABLE [dbo].[DesktopWidget] ADD CONSTRAINT [DF_DesktopWidget_RowIndex] DEFAULT ((0)) FOR [RowIndex]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DimensionInfo ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DimensionInfo] ( + [DimensionGUID] uniqueidentifier NOT NULL, + [CubeStubGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Type] int NOT NULL, + PRIMARY KEY ([DimensionGUID], [CubeStubGUID]) +); +GO +ALTER TABLE [dbo].[DimensionInfo] ADD CONSTRAINT [DF_DimensionInfo_DIMENSIONGUID] DEFAULT (newid()) FOR [DimensionGUID]; GO +ALTER TABLE [dbo].[DimensionInfo] ADD CONSTRAINT [DF_DimensionInfo_CubeStubGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CubeStubGUID]; GO +ALTER TABLE [dbo].[DimensionInfo] ADD CONSTRAINT [DF_DimensionInfo_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[DimensionInfo] ADD CONSTRAINT [DF_DimensionInfo_DIMENSIONTYPE] DEFAULT ((0)) FOR [Type]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.DimensionMemberCleanupHistory ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[DimensionMemberCleanupHistory] ( + [RowID] bigint NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [UserName] varchar(128) NOT NULL, + [SourceTableName] varchar(200) NOT NULL, + [BackupTableName] varchar(200) NOT NULL, + [RequestDateTime] datetime NOT NULL, + [SessionSuffix] varchar(20) NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [dbo].[DimensionMemberCleanupHistory] ADD CONSTRAINT [DF_DimensionMemberCleanupHistory_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[DimensionMemberCleanupHistory] ADD CONSTRAINT [DF_DimensionMemberCleanupHistory_UserName] DEFAULT ('') FOR [UserName]; GO +ALTER TABLE [dbo].[DimensionMemberCleanupHistory] ADD CONSTRAINT [DF_DimensionMemberCleanupHistory_SourceTableName] DEFAULT ('') FOR [SourceTableName]; GO +ALTER TABLE [dbo].[DimensionMemberCleanupHistory] ADD CONSTRAINT [DF_DimensionMemberCleanupHistory_BackupTableName] DEFAULT ('') FOR [BackupTableName]; GO +ALTER TABLE [dbo].[DimensionMemberCleanupHistory] ADD CONSTRAINT [DF_DimensionMemberCleanupHistory_RequestDateTime] DEFAULT (getdate()) FOR [RequestDateTime]; GO +ALTER TABLE [dbo].[DimensionMemberCleanupHistory] ADD CONSTRAINT [DF_DimensionMemberCleanupHistory_SessionSuffix] DEFAULT ('') FOR [SessionSuffix]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ECRIComponent ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ECRIComponent] ( + [ECRIComponentGUID] uniqueidentifier NOT NULL, + [ECRIDealGUID] uniqueidentifier NOT NULL, + [CatalogNumber] varchar(64) NOT NULL, + [Description] varchar(1000) NOT NULL, + [Quantity] int NOT NULL, + [QuotedPrice] float NOT NULL, + PRIMARY KEY ([ECRIComponentGUID]) +); +GO +ALTER TABLE [dbo].[ECRIComponent] ADD CONSTRAINT [FK_ECRIComponent_ECRIDeal] FOREIGN KEY ([ECRIDealGUID]) REFERENCES [dbo].[ECRIDeal] ([ECRIDealGUID]); GO +ALTER TABLE [dbo].[ECRIComponent] ADD CONSTRAINT [DF_ECRIComponent_ECRICOMPONENTGUID] DEFAULT (newid()) FOR [ECRIComponentGUID]; GO +ALTER TABLE [dbo].[ECRIComponent] ADD CONSTRAINT [DF_ECRIComponent_ECRIDEALGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ECRIDealGUID]; GO +ALTER TABLE [dbo].[ECRIComponent] ADD CONSTRAINT [DF_ECRIComponent_CatalogNumber] DEFAULT ('') FOR [CatalogNumber]; GO +ALTER TABLE [dbo].[ECRIComponent] ADD CONSTRAINT [DF_ECRIComponent_Description] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[ECRIComponent] ADD CONSTRAINT [DF_ECRIComponent_QUANTITY] DEFAULT ((1)) FOR [Quantity]; GO +ALTER TABLE [dbo].[ECRIComponent] ADD CONSTRAINT [DF_ECRIComponent_QUOTEDPRICE] DEFAULT ((0)) FOR [QuotedPrice]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ECRIDeal ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ECRIDeal] ( + [ECRIDealGUID] uniqueidentifier NOT NULL, + [ECRIModelGUID] uniqueidentifier NOT NULL, + [ReferenceNumber] int NOT NULL, + [QuotedPrice] float NOT NULL, + [ListPrice] float NOT NULL, + [Units] float NOT NULL, + [Comments] varchar(4000) NOT NULL, + [Discount] float NOT NULL, + [DealDate] nvarchar(64) NOT NULL, + PRIMARY KEY ([ECRIDealGUID]) +); +GO +ALTER TABLE [dbo].[ECRIDeal] ADD CONSTRAINT [FK_ECRIDeal_ECRIModel] FOREIGN KEY ([ECRIModelGUID]) REFERENCES [dbo].[ECRIModel] ([ECRIModelGUID]); GO +ALTER TABLE [dbo].[ECRIDeal] ADD CONSTRAINT [DF_ECRIDeal_ECRIDEALGUID] DEFAULT (newid()) FOR [ECRIDealGUID]; GO +ALTER TABLE [dbo].[ECRIDeal] ADD CONSTRAINT [DF_ECRIDeal_ECRIMODELGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ECRIModelGUID]; GO +ALTER TABLE [dbo].[ECRIDeal] ADD CONSTRAINT [DF_ECRIDeal_ReferenceNumber] DEFAULT ((0)) FOR [ReferenceNumber]; GO +ALTER TABLE [dbo].[ECRIDeal] ADD CONSTRAINT [DF_ECRIDeal_QUOTEDPRICE] DEFAULT ((0)) FOR [QuotedPrice]; GO +ALTER TABLE [dbo].[ECRIDeal] ADD CONSTRAINT [DF_ECRIDeal_LISTPRICE] DEFAULT ((0)) FOR [ListPrice]; GO +ALTER TABLE [dbo].[ECRIDeal] ADD CONSTRAINT [DF_ECRIDeal_UNITS] DEFAULT ((0)) FOR [Units]; GO +ALTER TABLE [dbo].[ECRIDeal] ADD CONSTRAINT [DF_ECRIDeal_Comments] DEFAULT ('') FOR [Comments]; GO +ALTER TABLE [dbo].[ECRIDeal] ADD CONSTRAINT [DF_ECRIDeal_Discount] DEFAULT ((0)) FOR [Discount]; GO +ALTER TABLE [dbo].[ECRIDeal] ADD CONSTRAINT [DF_ECRIDeal_Date] DEFAULT ('') FOR [DealDate]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ECRIDocument ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ECRIDocument] ( + [ECRIDocumentGUID] uniqueidentifier NOT NULL, + [ECRIPackageGUID] uniqueidentifier NOT NULL, + [Title] varchar(200) NOT NULL, + [Source] int NOT NULL, + [ResultID] varchar(64) NOT NULL, + [RadarInfo] varchar(10) NOT NULL, + [RadarComment1] varchar(8000) NOT NULL, + [RadarComment2] varchar(8000) NOT NULL, + [RadarComment3] varchar(8000) NOT NULL, + [RadarComment4] varchar(8000) NOT NULL, + [RadarComment5] varchar(8000) NOT NULL, + PRIMARY KEY ([ECRIDocumentGUID]) +); +GO +ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [FK_ECRIDocument_ECRIPackage] FOREIGN KEY ([ECRIPackageGUID]) REFERENCES [dbo].[ECRIPackage] ([ECRIPackageGUID]); GO +ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_ECRIDocumentGUID] DEFAULT (newid()) FOR [ECRIDocumentGUID]; GO +ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_ECRIPackageGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ECRIPackageGUID]; GO +ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_Title] DEFAULT ('') FOR [Title]; GO +ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_Source] DEFAULT ((0)) FOR [Source]; GO +ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_Identifier] DEFAULT ('') FOR [ResultID]; GO +ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_RadarInfo] DEFAULT ('') FOR [RadarInfo]; GO +ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_RadarComment1] DEFAULT ('') FOR [RadarComment1]; GO +ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_RadarComment2] DEFAULT ('') FOR [RadarComment2]; GO +ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_RadarComment3] DEFAULT ('') FOR [RadarComment3]; GO +ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_RadarComment4] DEFAULT ('') FOR [RadarComment4]; GO +ALTER TABLE [dbo].[ECRIDocument] ADD CONSTRAINT [DF_ECRIDocument_RadarComment5] DEFAULT ('') FOR [RadarComment5]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ECRIDocumentSection ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ECRIDocumentSection] ( + [ECRIDocumentSectionGUID] uniqueidentifier NOT NULL, + [ECRIDocumentGUID] uniqueidentifier NOT NULL, + [Header] varchar(200) NOT NULL, + [Text] nvarchar(max) NOT NULL, + [DisplayOrder] int NOT NULL, + PRIMARY KEY ([ECRIDocumentSectionGUID]) +); +GO +ALTER TABLE [dbo].[ECRIDocumentSection] ADD CONSTRAINT [FK_ECRIDocumentSection_ECRIDocument] FOREIGN KEY ([ECRIDocumentGUID]) REFERENCES [dbo].[ECRIDocument] ([ECRIDocumentGUID]); GO +ALTER TABLE [dbo].[ECRIDocumentSection] ADD CONSTRAINT [DF_ECRIDocumentSection_ECRIDocumentSectionGUID] DEFAULT (newid()) FOR [ECRIDocumentSectionGUID]; GO +ALTER TABLE [dbo].[ECRIDocumentSection] ADD CONSTRAINT [DF_ECRIDocumentSection_ECRIDocumentGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ECRIDocumentGUID]; GO +ALTER TABLE [dbo].[ECRIDocumentSection] ADD CONSTRAINT [DF_ECRIDocumentSection_Text] DEFAULT ('') FOR [Text]; GO +ALTER TABLE [dbo].[ECRIDocumentSection] ADD CONSTRAINT [DF_ECRIDocumentSection_Header] DEFAULT ('') FOR [Header]; GO +ALTER TABLE [dbo].[ECRIDocumentSection] ADD CONSTRAINT [DF_ECRIDocumentSection_DisplayOrder] DEFAULT ((0)) FOR [DisplayOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ECRIEquipment ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ECRIEquipment] ( + [ECRIEquipmentGUID] uniqueidentifier NOT NULL, + [ECRIPackageGUID] uniqueidentifier NOT NULL, + [Name] varchar(120) NOT NULL, + PRIMARY KEY ([ECRIEquipmentGUID]) +); +GO +ALTER TABLE [dbo].[ECRIEquipment] ADD CONSTRAINT [FK_ECRIEquipmentName_ECRIPackage] FOREIGN KEY ([ECRIPackageGUID]) REFERENCES [dbo].[ECRIPackage] ([ECRIPackageGUID]); GO +ALTER TABLE [dbo].[ECRIEquipment] ADD CONSTRAINT [DF_ECRIEquipmentName_DeviceTerm] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[ECRIEquipment] ADD CONSTRAINT [DF_ECRIEquipmentName_ECRIEquipmentNameGUID] DEFAULT (newid()) FOR [ECRIEquipmentGUID]; GO +ALTER TABLE [dbo].[ECRIEquipment] ADD CONSTRAINT [DF_ECRIEquipmentName_ECRIPackageGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ECRIPackageGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ECRIModel ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ECRIModel] ( + [ECRIModelGUID] uniqueidentifier NOT NULL, + [ECRIPackageGUID] uniqueidentifier NOT NULL, + [ECRIEquipmentGUID] uniqueidentifier NOT NULL, + [ECRIVendorGUID] uniqueidentifier NOT NULL, + [Name] varchar(300) NOT NULL, + [ResultID] varchar(64) NOT NULL, + PRIMARY KEY ([ECRIModelGUID]) +); +GO +ALTER TABLE [dbo].[ECRIModel] ADD CONSTRAINT [FK_ECRIModel_ECRIPackage] FOREIGN KEY ([ECRIPackageGUID]) REFERENCES [dbo].[ECRIPackage] ([ECRIPackageGUID]); GO +ALTER TABLE [dbo].[ECRIModel] ADD CONSTRAINT [DF_ECRIModel_ECRIMODELGUID] DEFAULT (newid()) FOR [ECRIModelGUID]; GO +ALTER TABLE [dbo].[ECRIModel] ADD CONSTRAINT [DF_ECRIModel_ECRIPackageGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ECRIPackageGUID]; GO +ALTER TABLE [dbo].[ECRIModel] ADD CONSTRAINT [DF_ECRIModel_ECRIEquipmentGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ECRIEquipmentGUID]; GO +ALTER TABLE [dbo].[ECRIModel] ADD CONSTRAINT [DF_ECRIModel_ECRIVendorGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ECRIVendorGUID]; GO +ALTER TABLE [dbo].[ECRIModel] ADD CONSTRAINT [DF_ECRIModel_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[ECRIModel] ADD CONSTRAINT [DF_ECRIModel_ECRIResultID] DEFAULT ('') FOR [ResultID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ECRIPackage ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ECRIPackage] ( + [ECRIPackageGUID] uniqueidentifier NOT NULL, + [PlanGUID] uniqueidentifier NOT NULL, + [SearchTerm] nvarchar(4000) NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [DateCreated] datetime NOT NULL, + PRIMARY KEY ([ECRIPackageGUID]) +); +GO +ALTER TABLE [dbo].[ECRIPackage] ADD CONSTRAINT [DF_ECRIPlanSelection_ECRIPlanSelectionGUID] DEFAULT (newid()) FOR [ECRIPackageGUID]; GO +ALTER TABLE [dbo].[ECRIPackage] ADD CONSTRAINT [DF_ECRIPlanSelection_PlanGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanGUID]; GO +ALTER TABLE [dbo].[ECRIPackage] ADD CONSTRAINT [DF_ECRIPackage_Search] DEFAULT ('') FOR [SearchTerm]; GO +ALTER TABLE [dbo].[ECRIPackage] ADD CONSTRAINT [DF_ECRIPlanSelection_ECRIEquipmentNames] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[ECRIPackage] ADD CONSTRAINT [DF_ECRIPlanSelection_ECRIVendors] DEFAULT (getdate()) FOR [DateCreated]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ECRIVendor ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ECRIVendor] ( + [ECRIVendorGUID] uniqueidentifier NOT NULL, + [ECRIPackageGUID] uniqueidentifier NOT NULL, + [Name] varchar(121) NOT NULL, + PRIMARY KEY ([ECRIVendorGUID]) +); +GO +ALTER TABLE [dbo].[ECRIVendor] ADD CONSTRAINT [FK_ECRIVendor_ECRIPackage] FOREIGN KEY ([ECRIPackageGUID]) REFERENCES [dbo].[ECRIPackage] ([ECRIPackageGUID]); GO +ALTER TABLE [dbo].[ECRIVendor] ADD CONSTRAINT [DF_ECRIVendor_ECRIVendorGUID] DEFAULT (newid()) FOR [ECRIVendorGUID]; GO +ALTER TABLE [dbo].[ECRIVendor] ADD CONSTRAINT [DF_ECRIVendor_ECRIPackageGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ECRIPackageGUID]; GO +ALTER TABLE [dbo].[ECRIVendor] ADD CONSTRAINT [DF_ECRIVendor_Name] DEFAULT ('') FOR [Name]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFCalculatedMeasure ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFCalculatedMeasure] ( + [CalculatedMeasureGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(450) NOT NULL, + [IsVisible] bit NOT NULL, + [MDXName] nvarchar(450) NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [DisplayFormat] nvarchar(450) NOT NULL, + [DisplayFolder] nvarchar(450) NOT NULL, + [NonEmptyBehavior] nvarchar(max) NOT NULL, + [CubeStubGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([CalculatedMeasureGUID]) +); + +CREATE NONCLUSTERED INDEX [IX_EMFCalculatedMeasure_DisplayFormat] ON [dbo].[EMFCalculatedMeasure] ([DisplayFormat]); +GO +ALTER TABLE [dbo].[EMFCalculatedMeasure] ADD CONSTRAINT [DF_EMFCalculatedMeasure_CALCULATEDMEASUREGUID] DEFAULT (newid()) FOR [CalculatedMeasureGUID]; GO +ALTER TABLE [dbo].[EMFCalculatedMeasure] ADD CONSTRAINT [DF_EMFCalculatedMeasure_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[EMFCalculatedMeasure] ADD CONSTRAINT [DF_EMFCalculatedMeasure_ISVISIBLE] DEFAULT ((1)) FOR [IsVisible]; GO +ALTER TABLE [dbo].[EMFCalculatedMeasure] ADD CONSTRAINT [DF_EMFCalculatedMeasure_MDXNAME] DEFAULT ('') FOR [MDXName]; GO +ALTER TABLE [dbo].[EMFCalculatedMeasure] ADD CONSTRAINT [DF_EMFCalculatedMeasure_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[EMFCalculatedMeasure] ADD CONSTRAINT [DF_EMFCalculatedMeasure_FORMATSTRING] DEFAULT ('') FOR [DisplayFormat]; GO +ALTER TABLE [dbo].[EMFCalculatedMeasure] ADD CONSTRAINT [DF_EMFCalculatedMeasure_DISPLAYFOLDER] DEFAULT ('') FOR [DisplayFolder]; GO +ALTER TABLE [dbo].[EMFCalculatedMeasure] ADD CONSTRAINT [DF_EMFCalculatedMeasure_NONEMPTYBEHAVIOR] DEFAULT ('') FOR [NonEmptyBehavior]; GO +ALTER TABLE [dbo].[EMFCalculatedMeasure] ADD CONSTRAINT [DF_EMFCalculatedMeasure_CUBESTUBGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CubeStubGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFCubeStub ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFCubeStub] ( + [CubeGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [DateCreated] datetime NOT NULL, + [DateProcessed] datetime NOT NULL, + [ServerName] nvarchar(64) NOT NULL, + [DatabaseFriendlyName] nvarchar(32) NOT NULL, + [DatabasePrefixName] nvarchar(64) NOT NULL, + [Status] int NOT NULL, + [Type] int NOT NULL, + [IsReportable] bit NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [KeyDimension] nvarchar(450) NOT NULL, + [IsEditable] bit NOT NULL, + [CubeType] int NOT NULL, + [IsAutoProcessEnabled] bit NOT NULL, + [IsAutoUpdateEnabled] bit NOT NULL, + [MaxParallel] int NOT NULL, + [IsUsingBatchProcessing] bit NOT NULL, + [DateModified] datetime NOT NULL, + [GlobalID] nvarchar(100) NOT NULL, + [IsUsingDSCubeReportIntelliCross] bit NOT NULL, + PRIMARY KEY ([CubeGUID]) +); +GO +ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF__EMFCubeSt__IsUsi__0A45C229] DEFAULT ((0)) FOR [IsUsingDSCubeReportIntelliCross]; GO +ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF__EMFCubeSt__DateM__0B2E640C] DEFAULT (getdate()) FOR [DateModified]; GO +ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_CUBEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CubeGUID]; GO +ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_DATABASEPREFIXNAME] DEFAULT ('') FOR [DatabasePrefixName]; GO +ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCube_STATUS] DEFAULT ((0)) FOR [Status]; GO +ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCube_TYPE] DEFAULT ((0)) FOR [Type]; GO +ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_ISREPORTABLE] DEFAULT ((0)) FOR [IsReportable]; GO +ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_KEYDIMENSION] DEFAULT ('') FOR [KeyDimension]; GO +ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_ISEDITABLE] DEFAULT ((1)) FOR [IsEditable]; GO +ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_CUBETYPE] DEFAULT ((0)) FOR [CubeType]; GO +ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_IsAutoProcessEnabled] DEFAULT ((1)) FOR [IsAutoProcessEnabled]; GO +ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_IsAutoUpdateEnabled] DEFAULT ((0)) FOR [IsAutoUpdateEnabled]; GO +ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_MaxParallel] DEFAULT ((0)) FOR [MaxParallel]; GO +ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_IsUsingBatchProcessing] DEFAULT ((0)) FOR [IsUsingBatchProcessing]; GO +ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF__EMFCubeSt__Globa__5A2C0555] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_ServerName] DEFAULT ('') FOR [ServerName]; GO +ALTER TABLE [dbo].[EMFCubeStub] ADD CONSTRAINT [DF_EMFCubeStub_DatabaseFriendlyName] DEFAULT ('') FOR [DatabaseFriendlyName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFCubeStubCrosswalk ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFCubeStubCrosswalk] ( + [CUBESTUBCROSSWALKGUID] uniqueidentifier NOT NULL, + [CubeStubGUID] uniqueidentifier NOT NULL, + [StructureGUID] uniqueidentifier NOT NULL, + [LinkedStructureGUID] uniqueidentifier NOT NULL, + [LinkedDimensionGUID] uniqueidentifier NOT NULL, + [LinkedMeasureGUID] uniqueidentifier NOT NULL, + [JoinType] int NOT NULL, + PRIMARY KEY ([CUBESTUBCROSSWALKGUID]) +); +GO +ALTER TABLE [dbo].[EMFCubeStubCrosswalk] ADD CONSTRAINT [FK_EMFCubeStubCrosswalkLink_EMFCubeStub] FOREIGN KEY ([CubeStubGUID]) REFERENCES [dbo].[EMFCubeStub] ([CubeGUID]); GO +ALTER TABLE [dbo].[EMFCubeStubCrosswalk] ADD CONSTRAINT [DF_EMFCubeStubCrosswalkLink_CUBESTUBCROSSWALKLINKGUID] DEFAULT (newid()) FOR [CUBESTUBCROSSWALKGUID]; GO +ALTER TABLE [dbo].[EMFCubeStubCrosswalk] ADD CONSTRAINT [DF_EMFCubeStubCrosswalk_JOINTYPE] DEFAULT ((0)) FOR [JoinType]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFCubeStubCustomDimension ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFCubeStubCustomDimension] ( + [StructureGUID] uniqueidentifier NOT NULL, + [CubeStubGUID] uniqueidentifier NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + [NewDimensionGUID] uniqueidentifier NOT NULL, + [NewName] varchar(450) NOT NULL, + [NewSQL] varchar(max) NOT NULL, + [NewSQLType] int NOT NULL, + [NewSQLTableIDColName] varchar(64) NOT NULL, + [NewSQLTableParentColName] varchar(64) NOT NULL, + [NewSQLTableOrderColName] nvarchar(64) NOT NULL, + [NewSQLTableValueColName] varchar(64) NOT NULL, + [NewSQLTableOperatorColName] varchar(64) NOT NULL, + [NewFactTableColName] nvarchar(64) NOT NULL, + [NewSQLTableName] nvarchar(64) NOT NULL, + [NewLevelNamingTemplate] nvarchar(50) NOT NULL, + [NewDefaultMemberMDXName] varchar(450) NOT NULL, + [NewAggregationType] int NOT NULL, + [NewIsVisible] bit NOT NULL, + [NewIsMultiLevel] bit NOT NULL, + [NewIsQuery] bit NOT NULL, + [IsOverridingSQLTableName] bit NOT NULL, + [IsOverridingLevelNamingTemplate] bit NOT NULL, + [IsOverridingDefaultMemberMDXName] bit NOT NULL, + [IsOverridingAggregationType] bit NOT NULL, + [IsOverridingIsVisible] bit NOT NULL, + [IsOverridingIsMultiLevel] bit NOT NULL, + [IsOverridingIsQuery] bit NOT NULL, + PRIMARY KEY ([StructureGUID], [CubeStubGUID], [DimensionGUID]) +); +GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [FK_EMFCubeStubCustomDimension_EMFCubeStub] FOREIGN KEY ([CubeStubGUID]) REFERENCES [dbo].[EMFCubeStub] ([CubeGUID]); GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_STRUCTUREGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [StructureGUID]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_CUBESTUBGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CubeStubGUID]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_DIMENSIONGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWDIMENSIONGUID] DEFAULT (newid()) FOR [NewDimensionGUID]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWNAME] DEFAULT ('') FOR [NewName]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_FILTERSQL] DEFAULT ('') FOR [NewSQL]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_FULLSQL] DEFAULT ((0)) FOR [NewSQLType]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWSQLTABLEIDCOLNAME] DEFAULT ('') FOR [NewSQLTableIDColName]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWSQLTABLEPARENTCOLNAME] DEFAULT ('') FOR [NewSQLTableParentColName]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWSQLTABLEORDERCOLNAME] DEFAULT ('') FOR [NewSQLTableOrderColName]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWSQLTABLEVALUECOLNAME] DEFAULT ('') FOR [NewSQLTableValueColName]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWSQLTABLEOPERATORCOLNAME] DEFAULT ('') FOR [NewSQLTableOperatorColName]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWFACTTABLECOLNAME] DEFAULT ('') FOR [NewFactTableColName]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWSQLTABLENAME] DEFAULT ('') FOR [NewSQLTableName]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWLEVELNAMINGTEMPLATE] DEFAULT ('') FOR [NewLevelNamingTemplate]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWDEFAULTMEMBERMDXNAME] DEFAULT ('') FOR [NewDefaultMemberMDXName]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWAGGREGATIONTYPE] DEFAULT ((0)) FOR [NewAggregationType]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWISVISIBLE] DEFAULT ((0)) FOR [NewIsVisible]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWISMULTILEVEL] DEFAULT ((0)) FOR [NewIsMultiLevel]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_NEWISQUERY] DEFAULT ((0)) FOR [NewIsQuery]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_ISOVERRIDINGSQLTABLENAME] DEFAULT ((0)) FOR [IsOverridingSQLTableName]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_ISOVERRIDINGLEVELNAMINGTEMPLATE] DEFAULT ((0)) FOR [IsOverridingLevelNamingTemplate]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_ISOVERRIDINGDEFAULTMEMBERMDXNAME] DEFAULT ((0)) FOR [IsOverridingDefaultMemberMDXName]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_ISOVERRIDINGAGGREGATIONTYPE] DEFAULT ((0)) FOR [IsOverridingAggregationType]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_ISOVERRIDINGISVISIBLE] DEFAULT ((0)) FOR [IsOverridingIsVisible]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_ISOVERRIDINGISMULTILEVEL] DEFAULT ((0)) FOR [IsOverridingIsMultiLevel]; GO +ALTER TABLE [dbo].[EMFCubeStubCustomDimension] ADD CONSTRAINT [DF_EMFCubeStubCustomDimension_ISOVERRIDINGISQUERY] DEFAULT ((0)) FOR [IsOverridingIsQuery]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFCubeStubFormFieldLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFCubeStubFormFieldLink] ( + [CubeStubGUID] uniqueidentifier NOT NULL, + [FormFieldGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([CubeStubGUID], [FormFieldGUID]) +); +GO +ALTER TABLE [dbo].[EMFCubeStubFormFieldLink] ADD CONSTRAINT [FK_EMFCubeStubFormFieldLink_EMFCubeStub] FOREIGN KEY ([CubeStubGUID]) REFERENCES [dbo].[EMFCubeStub] ([CubeGUID]); GO +ALTER TABLE [dbo].[EMFCubeStubFormFieldLink] ADD CONSTRAINT [FK_EMFCubeStubFormFieldLink_FEFormField] FOREIGN KEY ([FormFieldGUID]) REFERENCES [dbo].[FEFormField] ([FORMFIELDGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFCubeStubModelDataConfigLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFCubeStubModelDataConfigLink] ( + [ModelDataConfigGUID] uniqueidentifier NOT NULL, + [CubeGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([ModelDataConfigGUID], [CubeGUID]) +); +GO +ALTER TABLE [dbo].[EMFCubeStubModelDataConfigLink] ADD CONSTRAINT [FK_EMFCubeStubModelDataConfigLink_EMFCubeStub] FOREIGN KEY ([CubeGUID]) REFERENCES [dbo].[EMFCubeStub] ([CubeGUID]); GO +ALTER TABLE [dbo].[EMFCubeStubModelDataConfigLink] ADD CONSTRAINT [FK_EMFCubeStubModelDataConfigLink_EMFModelDataConfig] FOREIGN KEY ([ModelDataConfigGUID]) REFERENCES [dbo].[EMFModelDataConfig] ([ModelDataConfigGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFCubeStubModelKeyValue ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFCubeStubModelKeyValue] ( + [CubeStubModelKeyValueGUID] uniqueidentifier NOT NULL, + [CubeStubGUID] uniqueidentifier NOT NULL, + [ModelGUID] uniqueidentifier NOT NULL, + [MemberID] nvarchar(450) NOT NULL, + PRIMARY KEY ([CubeStubModelKeyValueGUID]) +); + +CREATE CLUSTERED INDEX [IX_EMFCubeStubModelKeyValue] ON [dbo].[EMFCubeStubModelKeyValue] ([CubeStubGUID], [ModelGUID]); +GO +ALTER TABLE [dbo].[EMFCubeStubModelKeyValue] ADD CONSTRAINT [DF_EMFCubeStubModelKeyValue_CUBESTUBMODELKEYVALUEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CubeStubModelKeyValueGUID]; GO +ALTER TABLE [dbo].[EMFCubeStubModelKeyValue] ADD CONSTRAINT [DF_EMFCubeStubModelKeyValue_CUBESTUBGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CubeStubGUID]; GO +ALTER TABLE [dbo].[EMFCubeStubModelKeyValue] ADD CONSTRAINT [DF_EMFCubeStubModelKeyValue_MODELGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO +ALTER TABLE [dbo].[EMFCubeStubModelKeyValue] ADD CONSTRAINT [DF_Table_1_MEMBERGUID] DEFAULT ('') FOR [MemberID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFCubeStubSubtableLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFCubeStubSubtableLink] ( + [CubeStubGUID] uniqueidentifier NOT NULL, + [SubtableGUID] uniqueidentifier NOT NULL, + [UpdateBoolean] bit NOT NULL, + PRIMARY KEY ([CubeStubGUID], [SubtableGUID]) +); +GO +ALTER TABLE [dbo].[EMFCubeStubSubtableLink] ADD CONSTRAINT [FK_EMFCubeStubSubtableLink_EMFCubeStub] FOREIGN KEY ([CubeStubGUID]) REFERENCES [dbo].[EMFCubeStub] ([CubeGUID]); GO +ALTER TABLE [dbo].[EMFCubeStubSubtableLink] ADD CONSTRAINT [FK_EMFCubeStubSubtableLink_EMFSubtable] FOREIGN KEY ([SubtableGUID]) REFERENCES [dbo].[EMFSubtable] ([SUBTABLEGUID]); GO +ALTER TABLE [dbo].[EMFCubeStubSubtableLink] ADD CONSTRAINT [DF_EMFCubeStubSubtableLink_UPDATEBOOLEAN] DEFAULT ((0)) FOR [UpdateBoolean]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFFillIn ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFFillIn] ( + [FillInGUID] uniqueidentifier NOT NULL, + [ModelGUID] uniqueidentifier NOT NULL, + [PlaceholderMemberGUID] uniqueidentifier NOT NULL, + [FilledInMemberGUID] uniqueidentifier NOT NULL, + [IsSetByUser] bit NOT NULL, + [Version] timestamp NOT NULL, + PRIMARY KEY ([FillInGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_EMFFillIn] ON [dbo].[EMFFillIn] ([ModelGUID], [PlaceholderMemberGUID]); +GO +ALTER TABLE [dbo].[EMFFillIn] ADD CONSTRAINT [FK_EMFFillIn_XPlan] FOREIGN KEY ([ModelGUID]) REFERENCES [dbo].[XPlan] ([PlanGUID]); GO +ALTER TABLE [dbo].[EMFFillIn] ADD CONSTRAINT [DF_EMFFillIn_FillInGUID] DEFAULT (newsequentialid()) FOR [FillInGUID]; GO +ALTER TABLE [dbo].[EMFFillIn] ADD CONSTRAINT [DF_EMFFillIn_ModelGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO +ALTER TABLE [dbo].[EMFFillIn] ADD CONSTRAINT [DF_EMFFillIn_IsSetByUser] DEFAULT ((0)) FOR [IsSetByUser]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFFillInSetManyStaging ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFFillInSetManyStaging] ( + [InstanceGUID] uniqueidentifier NULL, + [PHDimensionGUID] uniqueidentifier NULL, + [ModelGUID] uniqueidentifier NULL, + [ParentPHMemberGUID] uniqueidentifier NULL, + [FillInGUID] uniqueidentifier NULL, + [SortOrder] nvarchar(4000) NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFJoinedStructureCalculatedMeasure ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFJoinedStructureCalculatedMeasure] ( + [CALCULATEDMEASUREGUID] uniqueidentifier NOT NULL, + [StructureGUID] uniqueidentifier NOT NULL, + [NAME] nvarchar(64) NOT NULL, + [FORMATSTRING] nvarchar(64) NOT NULL, + [ColumnWidth] int NOT NULL, + PRIMARY KEY ([CALCULATEDMEASUREGUID]) +); +GO +ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasure] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasure_CALCULATEDMEASUREGUID] DEFAULT (newid()) FOR [CALCULATEDMEASUREGUID]; GO +ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasure] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasure_JOINEDSTRUCTUREGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [StructureGUID]; GO +ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasure] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasure_NAME] DEFAULT ('') FOR [NAME]; GO +ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasure] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasure_FORMATSTRING] DEFAULT ('#,#0;(#,#0)') FOR [FORMATSTRING]; GO +ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasure] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasure_ColumnWidth] DEFAULT ((125)) FOR [ColumnWidth]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFJoinedStructureCalculatedMeasureVariable ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFJoinedStructureCalculatedMeasureVariable] ( + [CalculatedMeasureVariableGUID] uniqueidentifier NOT NULL, + [CalculatedMeasureGUID] uniqueidentifier NOT NULL, + [MeasureGUID] uniqueidentifier NOT NULL, + [StructureGUID] uniqueidentifier NOT NULL, + [ConstantValue] float NOT NULL, + [Operation] int NOT NULL, + [ExecutionOrder] int NOT NULL, + PRIMARY KEY ([CalculatedMeasureVariableGUID]) +); +GO +ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasureVariable] ADD CONSTRAINT [FK_EMFJoinedStructureCalculatedMeasureVariable_EMFJoinedStructureCalculatedMeasure] FOREIGN KEY ([CalculatedMeasureGUID]) REFERENCES [dbo].[EMFJoinedStructureCalculatedMeasure] ([CALCULATEDMEASUREGUID]); GO +ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasureVariable] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasureVariable_CALCULATEDMEASUREVARIABLEGUID] DEFAULT (newid()) FOR [CalculatedMeasureVariableGUID]; GO +ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasureVariable] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasureVariable_CALCULATEDMEASUREGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CalculatedMeasureGUID]; GO +ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasureVariable] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasureVariable_MEASUREGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO +ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasureVariable] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasureVariable_STRUCTUREGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [StructureGUID]; GO +ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasureVariable] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasureVariable_CONSTANTVALUE] DEFAULT ((0)) FOR [ConstantValue]; GO +ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasureVariable] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasureVariable_OPERATION] DEFAULT ((2)) FOR [Operation]; GO +ALTER TABLE [dbo].[EMFJoinedStructureCalculatedMeasureVariable] ADD CONSTRAINT [DF_EMFJoinedStructureCalculatedMeasureVariable_ExecutionOrder] DEFAULT ((0)) FOR [ExecutionOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFMeasure ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFMeasure] ( + [MEASUREGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Description] nvarchar(max) NOT NULL, + [DataType] int NOT NULL, + [DisplayFormat] nvarchar(255) NOT NULL, + [IsVisible] bit NOT NULL, + [IsModelMeasure] bit NOT NULL, + [AggregateFunctionType] int NOT NULL, + [IsTextOnly] bit NOT NULL, + [MinimumValue] float NOT NULL, + [MaximumValue] float NOT NULL, + [BoundsType] int NOT NULL, + [FolderGUID] uniqueidentifier NOT NULL, + [IsPlaceholderLabel] bit NOT NULL, + [PlaceholderDimensionGUID] uniqueidentifier NOT NULL, + [FillInPropertyIndex] int NOT NULL, + [IsHideRowIfUnfilled] bit NOT NULL, + [IsHideColumnIfUnfilled] bit NOT NULL, + PRIMARY KEY ([MEASUREGUID]) +); +GO +ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_MEASUREGUID] DEFAULT (newid()) FOR [MEASUREGUID]; GO +ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_DATATYPE] DEFAULT ((0)) FOR [DataType]; GO +ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_DISPLAYFORMAT] DEFAULT ('') FOR [DisplayFormat]; GO +ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_VISIBLE] DEFAULT ((1)) FOR [IsVisible]; GO +ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_ISMODELMEASURE] DEFAULT ((1)) FOR [IsModelMeasure]; GO +ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_AGGREGATEFUNCTIONTYPE] DEFAULT ((0)) FOR [AggregateFunctionType]; GO +ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_ISTEXTONLY] DEFAULT ('False') FOR [IsTextOnly]; GO +ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_MINIMUMVALUE] DEFAULT ((0)) FOR [MinimumValue]; GO +ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_MAXIMUMVALUE] DEFAULT ((0)) FOR [MaximumValue]; GO +ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_BOUNDSTYPE] DEFAULT ((0)) FOR [BoundsType]; GO +ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_FolderGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO +ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_IsFillInLabel] DEFAULT ((0)) FOR [IsPlaceholderLabel]; GO +ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_PlaceholderDimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlaceholderDimensionGUID]; GO +ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_FillInLabelPropertyIndex] DEFAULT ((-1)) FOR [FillInPropertyIndex]; GO +ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_IsHideRowsIfUnfilled] DEFAULT ((0)) FOR [IsHideRowIfUnfilled]; GO +ALTER TABLE [dbo].[EMFMeasure] ADD CONSTRAINT [DF_EMFMeasure_IsHideColumnsIfUnfilled] DEFAULT ((0)) FOR [IsHideColumnIfUnfilled]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFModelDataConfig ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFModelDataConfig] ( + [ModelDataConfigGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Description] nvarchar(max) NOT NULL, + [Version] timestamp NOT NULL, + [FolderGUID] uniqueidentifier NOT NULL, + [IsExpandable] bit NOT NULL, + [LastProcessed] datetime NOT NULL, + [LastProcessRequest] datetime NOT NULL, + [ProcessInterval] int NOT NULL, + [ShortcutName] nvarchar(16) NOT NULL, + [FormatOverrideDimensionGUID] uniqueidentifier NOT NULL, + [IsSetupLocked] bit NOT NULL, + PRIMARY KEY ([ModelDataConfigGUID]) +); +GO +ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelDataConfig_FormatOverrideDimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormatOverrideDimensionGUID]; GO +ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelSetup_MODELSETUPGUID] DEFAULT (newid()) FOR [ModelDataConfigGUID]; GO +ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelSetup_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelDataConfig_IsSetupLocked] DEFAULT ((0)) FOR [IsSetupLocked]; GO +ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelStructure_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelDataConfig_FOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO +ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelDataConfig_LastProcessed] DEFAULT (getdate()) FOR [LastProcessed]; GO +ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelDataConfig_LastProcessRequest] DEFAULT (getdate()) FOR [LastProcessRequest]; GO +ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelDataConfig_ProcessInterval] DEFAULT ((900)) FOR [ProcessInterval]; GO +ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelDataConfig_ShortcutName] DEFAULT ('') FOR [ShortcutName]; GO +ALTER TABLE [dbo].[EMFModelDataConfig] ADD CONSTRAINT [DF_EMFModelDataConfig_IsExpandable] DEFAULT ((0)) FOR [IsExpandable]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFModelDataConfigDimensionLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFModelDataConfigDimensionLink] ( + [ModelDataConfigGUID] uniqueidentifier NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + [IsModelKey] bit NOT NULL, + [IsFilterMember] bit NOT NULL, + [IsUniqueIndexMember] bit NOT NULL, + [Version] timestamp NOT NULL, + PRIMARY KEY ([ModelDataConfigGUID], [DimensionGUID]) +); +GO +ALTER TABLE [dbo].[EMFModelDataConfigDimensionLink] ADD CONSTRAINT [FK_MDC_MDC_Dim_Link] FOREIGN KEY ([ModelDataConfigGUID]) REFERENCES [dbo].[EMFModelDataConfig] ([ModelDataConfigGUID]); GO +ALTER TABLE [dbo].[EMFModelDataConfigDimensionLink] ADD CONSTRAINT [DF_DimensionSet_DIMENSIONSETGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelDataConfigGUID]; GO +ALTER TABLE [dbo].[EMFModelDataConfigDimensionLink] ADD CONSTRAINT [DF_DimensionSet_NAME] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO +ALTER TABLE [dbo].[EMFModelDataConfigDimensionLink] ADD CONSTRAINT [DF_EMFModelDataConfigDimensionLink_ISMODELKEY] DEFAULT ((0)) FOR [IsModelKey]; GO +ALTER TABLE [dbo].[EMFModelDataConfigDimensionLink] ADD CONSTRAINT [DF_EMFModelDataConfigDimensionLink_ISFILTERMEMBER] DEFAULT ((0)) FOR [IsFilterMember]; GO +ALTER TABLE [dbo].[EMFModelDataConfigDimensionLink] ADD CONSTRAINT [DF_EMFModelDataConfigDimensionLink_ISUNIQUEINDEXMEMBER] DEFAULT ((0)) FOR [IsUniqueIndexMember]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFModelDataConfigMeasureLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFModelDataConfigMeasureLink] ( + [ModelDataConfigGUID] uniqueidentifier NOT NULL, + [MeasureGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + PRIMARY KEY ([ModelDataConfigGUID], [MeasureGUID]) +); +GO +ALTER TABLE [dbo].[EMFModelDataConfigMeasureLink] ADD CONSTRAINT [FK_MDC_MDC_Meas_Link] FOREIGN KEY ([ModelDataConfigGUID]) REFERENCES [dbo].[EMFModelDataConfig] ([ModelDataConfigGUID]); GO +ALTER TABLE [dbo].[EMFModelDataConfigMeasureLink] ADD CONSTRAINT [FK_Meas_MDC_Meas_Link] FOREIGN KEY ([MeasureGUID]) REFERENCES [dbo].[EMFMeasure] ([MEASUREGUID]); GO +ALTER TABLE [dbo].[EMFModelDataConfigMeasureLink] ADD CONSTRAINT [DF_EMFModelSetupMeasureLink_MODELSETUPGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelDataConfigGUID]; GO +ALTER TABLE [dbo].[EMFModelDataConfigMeasureLink] ADD CONSTRAINT [DF_EMFModelSetupMeasureLink_MEASUREGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFModelDataLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFModelDataLink] ( + [ModelDataLinkGUID] uniqueidentifier NOT NULL, + [LinkSourceGUID] uniqueidentifier NOT NULL, + [ModelGUID] uniqueidentifier NOT NULL, + [ParentModelGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([ModelDataLinkGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_EMFMODELDATALINK] ON [dbo].[EMFModelDataLink] ([ModelGUID], [LinkSourceGUID], [ParentModelGUID]); +GO +ALTER TABLE [dbo].[EMFModelDataLink] ADD CONSTRAINT [FK_EMFModelLink_EMFModelTemplateLinkSource] FOREIGN KEY ([LinkSourceGUID]) REFERENCES [dbo].[EMFModelTemplateLinkSource] ([LinkSourceGUID]); GO +ALTER TABLE [dbo].[EMFModelDataLink] ADD CONSTRAINT [DF_EMFModelDataLink_MODELDATALINKGUID] DEFAULT (newid()) FOR [ModelDataLinkGUID]; GO +ALTER TABLE [dbo].[EMFModelDataLink] ADD CONSTRAINT [DF_EMFModelDependency_MODELGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO +ALTER TABLE [dbo].[EMFModelDataLink] ADD CONSTRAINT [DF_EMFModelDependency_PARENTMODELGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentModelGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFModelTemplate ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFModelTemplate] ( + [ModelTemplateGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [Version] timestamp NOT NULL, + [Type] int NOT NULL, + [IsPublished] bit NOT NULL, + [IsExpanded] bit NOT NULL, + [IsSafeModeOn] bit NOT NULL, + [DefaultFormGUID] uniqueidentifier NOT NULL, + [IsNewLabelsOnly] bit NOT NULL, + [IsUsingHashJoin] bit NOT NULL, + [IsScoreFillinAdvancedMode] bit NOT NULL, + [IsModelWorkbookCachable] bit NOT NULL, + [HasModelDependents] bit NOT NULL, + [IsModelRefreshOnFillinChange] bit NOT NULL, + [IsReadUncommittedLoad] bit NOT NULL, + [IsReadUncommittedSave] bit NOT NULL, + [IsMemoryCachable] bit NOT NULL, + [PublishOrder] int NOT NULL, + [EditExpansionsMode] tinyint NOT NULL, + [TemplateVersion] varchar(20) NOT NULL, + [IsUsingOpenWorkbookFormat] bit NOT NULL, + [IsHidden] bit NOT NULL, + PRIMARY KEY ([ModelTemplateGUID]) +); +GO +ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF__EMFModelT__Templ__044BF490] DEFAULT ('') FOR [TemplateVersion]; GO +ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_IsHidden] DEFAULT ((0)) FOR [IsHidden]; GO +ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF__EMFModelT__Publi__23B81C43] DEFAULT ((0)) FOR [PublishOrder]; GO +ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF__EMFModelT__IsMem__29502EB1] DEFAULT ((0)) FOR [IsMemoryCachable]; GO +ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF__EMFModelT__IsMod__3B6DE1CB] DEFAULT ((0)) FOR [IsModelWorkbookCachable]; GO +ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_HasModelDependents] DEFAULT ((1)) FOR [HasModelDependents]; GO +ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF__EMFModelT__IsMod__3E4A4E76] DEFAULT ((1)) FOR [IsModelRefreshOnFillinChange]; GO +ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF__EMFModelT__IsRea__3F3E72AF] DEFAULT ((0)) FOR [IsReadUncommittedLoad]; GO +ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF__EMFModelT__IsRea__403296E8] DEFAULT ((0)) FOR [IsReadUncommittedSave]; GO +ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_IsUsingHashJoin] DEFAULT ((0)) FOR [IsUsingHashJoin]; GO +ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_IsUsingOpenWorkbookFormat] DEFAULT ((0)) FOR [IsUsingOpenWorkbookFormat]; GO +ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_MODELTEMPLATEGUID] DEFAULT (newid()) FOR [ModelTemplateGUID]; GO +ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_EditExpansionsMode] DEFAULT ((0)) FOR [EditExpansionsMode]; GO +ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_DefaultFormGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultFormGUID]; GO +ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_IsNewLabelsOnly] DEFAULT ((0)) FOR [IsNewLabelsOnly]; GO +ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_TYPE] DEFAULT ((0)) FOR [Type]; GO +ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_ISPUBLISHED] DEFAULT ((0)) FOR [IsPublished]; GO +ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_IsSafeModeOn] DEFAULT ((0)) FOR [IsSafeModeOn]; GO +ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_IsExpanded] DEFAULT ((1)) FOR [IsExpanded]; GO +ALTER TABLE [dbo].[EMFModelTemplate] ADD CONSTRAINT [DF_EMFModelTemplate_IsScoreFillinAdvancedMode] DEFAULT ((0)) FOR [IsScoreFillinAdvancedMode]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFModelTemplateExpansion ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFModelTemplateExpansion] ( + [ExpansionGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [CellGUID] uniqueidentifier NOT NULL, + [DimensionMemberGUID] uniqueidentifier NOT NULL, + [DisplayOrder] int NOT NULL, + PRIMARY KEY ([ExpansionGUID]) +); +GO +ALTER TABLE [dbo].[EMFModelTemplateExpansion] ADD CONSTRAINT [DF_EMFExpansionInfo_EXPANSIONGUID] DEFAULT (newid()) FOR [ExpansionGUID]; GO +ALTER TABLE [dbo].[EMFModelTemplateExpansion] ADD CONSTRAINT [DF_EMFModelTemplateExpansion_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[EMFModelTemplateExpansion] ADD CONSTRAINT [DF_EMFModelTemplateExpansion_CellGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CellGUID]; GO +ALTER TABLE [dbo].[EMFModelTemplateExpansion] ADD CONSTRAINT [DF_EMFExpansionInfo_DIMENSIONMEMBERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionMemberGUID]; GO +ALTER TABLE [dbo].[EMFModelTemplateExpansion] ADD CONSTRAINT [DF_EMFModelTemplateExpansion_DISPLAYORDER] DEFAULT ((0)) FOR [DisplayOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFModelTemplateFormFieldMapping ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFModelTemplateFormFieldMapping] ( + [FormFieldGUID] uniqueidentifier NOT NULL, + [CellGUID] uniqueidentifier NOT NULL +); +GO +ALTER TABLE [dbo].[EMFModelTemplateFormFieldMapping] ADD CONSTRAINT [DF_EMFModelTemplateFormFieldMapping_FORMFIELDGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormFieldGUID]; GO +ALTER TABLE [dbo].[EMFModelTemplateFormFieldMapping] ADD CONSTRAINT [DF_EMFModelTemplateFormFieldMapping_CellGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CellGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFModelTemplateFramework ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFModelTemplateFramework] ( + [ModelTemplateGUID] uniqueidentifier NOT NULL, + [FrameworkID] tinyint NOT NULL, + PRIMARY KEY ([ModelTemplateGUID], [FrameworkID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFModelTemplateLinkSource ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFModelTemplateLinkSource] ( + [LinkSourceGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [ModelTemplateGUID] uniqueidentifier NOT NULL, + [ParentSubtableGUID] uniqueidentifier NOT NULL, + [ParentModelDataConfigGUID] uniqueidentifier NOT NULL, + [ParentScoreCompositeTableGUID] uniqueidentifier NOT NULL, + [IsSelf] bit NOT NULL, + [Version] timestamp NOT NULL, + PRIMARY KEY ([LinkSourceGUID]) +); +GO +ALTER TABLE [dbo].[EMFModelTemplateLinkSource] ADD CONSTRAINT [FK_EMFModelTemplateLinkSource_EMFModelTemplate] FOREIGN KEY ([ModelTemplateGUID]) REFERENCES [dbo].[EMFModelTemplate] ([ModelTemplateGUID]); GO +ALTER TABLE [dbo].[EMFModelTemplateLinkSource] ADD CONSTRAINT [DF_EMFModelTemplateLinkSource_ParentScoreCompositeTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentScoreCompositeTableGUID]; GO +ALTER TABLE [dbo].[EMFModelTemplateLinkSource] ADD CONSTRAINT [DF_EMFModelTemplateLinkSource_ISSELF] DEFAULT ((0)) FOR [IsSelf]; GO +ALTER TABLE [dbo].[EMFModelTemplateLinkSource] ADD CONSTRAINT [DF_EMFLinkSource_LINKSOURCEGUID] DEFAULT (newid()) FOR [LinkSourceGUID]; GO +ALTER TABLE [dbo].[EMFModelTemplateLinkSource] ADD CONSTRAINT [DF_EMFLinkSource_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[EMFModelTemplateLinkSource] ADD CONSTRAINT [DF_EMFLinkSource_MODELTEMPLATEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelTemplateGUID]; GO +ALTER TABLE [dbo].[EMFModelTemplateLinkSource] ADD CONSTRAINT [DF_EMFModelTemplateLinkSource_PARENTSUBTABLEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentSubtableGUID]; GO +ALTER TABLE [dbo].[EMFModelTemplateLinkSource] ADD CONSTRAINT [DF_EMFModelTemplateLinkSource_PARENTSTRUCTUREGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentModelDataConfigGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFModelTemplatePlaceholderLabelMapping ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ( + [MappingGUID] uniqueidentifier NOT NULL, + [PlaceholderDimensionGUID] uniqueidentifier NOT NULL, + [PlaceholderMemberGUID] uniqueidentifier NOT NULL, + [LabelPropertyGUID] uniqueidentifier NOT NULL, + [IsHidingRow] bit NOT NULL, + [IsHidingCol] bit NOT NULL, + [CellGUID] uniqueidentifier NOT NULL, + [RowExpanded] int NOT NULL, + [IsUserMapped] bit NOT NULL, + [IsClearingRow] bit NOT NULL, + [IsClearingCol] bit NOT NULL, + PRIMARY KEY ([MappingGUID]) +); +GO +ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_EMFModelTemplatePlaceholderLabelMapping_MappingGUID] DEFAULT (newid()) FOR [MappingGUID]; GO +ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_EMFModelTemplatePlaceholderLabelMapping_PlaceholderDimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlaceholderDimensionGUID]; GO +ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_EMFModelTemplatePlaceholderLabelMapping_PlaceholderMemberGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlaceholderMemberGUID]; GO +ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_Table_1_PropertyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LabelPropertyGUID]; GO +ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_Table_1_IsHidingRow] DEFAULT ((1)) FOR [IsHidingRow]; GO +ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_Table_1_IsHidingCol] DEFAULT ((0)) FOR [IsHidingCol]; GO +ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_EMFModelTemplatePlaceholderLabelMapping_CellGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CellGUID]; GO +ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_EMFModelTemplatePlaceholderLabelMapping_Row] DEFAULT ((0)) FOR [RowExpanded]; GO +ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_EMFModelTemplatePlaceholderLabelMapping_IsUserMapped] DEFAULT ((1)) FOR [IsUserMapped]; GO +ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_EMFModelTemplatePlaceholderLabelMapping_IsClearingRow] DEFAULT ((0)) FOR [IsClearingRow]; GO +ALTER TABLE [dbo].[EMFModelTemplatePlaceholderLabelMapping] ADD CONSTRAINT [DF_EMFModelTemplatePlaceholderLabelMapping_IsClearingCol] DEFAULT ((0)) FOR [IsClearingCol]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFModelTemplateWorksheet ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFModelTemplateWorksheet] ( + [WorksheetGUID] uniqueidentifier NOT NULL, + [ModelTemplateGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(max) NOT NULL, + [DesignerMetaData] nvarchar(max) NOT NULL, + [TransformStateGUID] uniqueidentifier NOT NULL, + [IsImprov] bit NOT NULL, + [IsHiddenOnExpand] bit NOT NULL, + [HiddenRows] int NOT NULL, + [HiddenColumns] int NOT NULL, + [IsHeadingsHiddenOnExpand] bit NOT NULL, + [ZoomLevel] int NOT NULL, + [IsChartsEnabled] bit NOT NULL, + [NameSourceAddress] nvarchar(50) NOT NULL, + [DefaultCellAddress] nvarchar(50) NOT NULL, + [FreezePanesCellAddress] nvarchar(50) NOT NULL, + [IsDefaultSheet] bit NOT NULL, + [CounterCellAddress] nvarchar(50) NOT NULL, + [CloneCount] tinyint NOT NULL, + [IsClearingByNameCell] bit NOT NULL, + PRIMARY KEY ([WorksheetGUID]) +); + +CREATE NONCLUSTERED INDEX [NC_TEMPLATE] ON [dbo].[EMFModelTemplateWorksheet] ([WorksheetGUID], [ModelTemplateGUID]); +GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [FK_EMFModelTemplateWorksheet_EMFModelTemplate] FOREIGN KEY ([ModelTemplateGUID]) REFERENCES [dbo].[EMFModelTemplate] ([ModelTemplateGUID]); GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFMODELTEMPLATEWORKSHEET_WORKSHEETGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorksheetGUID]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFMODELTEMPLATEWORKSHEET_MODELTEMPLATEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelTemplateGUID]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFMODELTEMPLATEWORKSHEET_WORKSHEETNAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_DESIGNERMETADATAXML] DEFAULT ('') FOR [DesignerMetaData]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_TRANSFORMSTATEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TransformStateGUID]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_IsImprov] DEFAULT ((0)) FOR [IsImprov]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_IsHiddenOnExpand] DEFAULT ((0)) FOR [IsHiddenOnExpand]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_HiddenRows] DEFAULT ((0)) FOR [HiddenRows]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_HiddenColumns] DEFAULT ((0)) FOR [HiddenColumns]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_IsHeadingsHiddenOnExpand] DEFAULT ((0)) FOR [IsHeadingsHiddenOnExpand]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_ZoomLevel] DEFAULT ((0)) FOR [ZoomLevel]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_IsChartsEnabled] DEFAULT ((0)) FOR [IsChartsEnabled]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_IsClearingByNameCell] DEFAULT ((0)) FOR [IsClearingByNameCell]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_NameSourceAddress] DEFAULT ('') FOR [NameSourceAddress]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_DefaultCellAddress] DEFAULT ('') FOR [DefaultCellAddress]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_FreezePanesCellAddress] DEFAULT ('') FOR [FreezePanesCellAddress]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_IsDefaultSheet] DEFAULT ((0)) FOR [IsDefaultSheet]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_CounterCellAddress] DEFAULT ('') FOR [CounterCellAddress]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheet] ADD CONSTRAINT [DF_EMFModelTemplateWorksheet_CloneCount] DEFAULT ((0)) FOR [CloneCount]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFModelTemplateWorksheetRange ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFModelTemplateWorksheetRange] ( + [ModelTemplateRangeGUID] uniqueidentifier NOT NULL, + [WorksheetGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(128) NOT NULL, + [RangeName] nvarchar(128) NOT NULL, + [IsCustomizable] bit NOT NULL, + PRIMARY KEY ([ModelTemplateRangeGUID]) +); +GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheetRange] ADD CONSTRAINT [FK_EMFModelTemplateWorksheetRange_EMFModelTemplateWorksheet] FOREIGN KEY ([WorksheetGUID]) REFERENCES [dbo].[EMFModelTemplateWorksheet] ([WorksheetGUID]); GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheetRange] ADD CONSTRAINT [DF__EMFModelT__Model__6C2393F0] DEFAULT (newid()) FOR [ModelTemplateRangeGUID]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheetRange] ADD CONSTRAINT [DF__EMFModelTe__Name__6E0BDC62] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheetRange] ADD CONSTRAINT [DF_EMFModelTemplateWorksheetRange_RangeName] DEFAULT ('') FOR [RangeName]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheetRange] ADD CONSTRAINT [DF__EMFModelT__IsCus__6F00009B] DEFAULT ((0)) FOR [IsCustomizable]; GO +ALTER TABLE [dbo].[EMFModelTemplateWorksheetRange] ADD CONSTRAINT [DF__EMFModelT__Works__6D17B829] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorksheetGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFScenario ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFScenario] ( + [SCENARIOGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Type] int NOT NULL, + PRIMARY KEY ([SCENARIOGUID]) +); +GO +ALTER TABLE [dbo].[EMFScenario] ADD CONSTRAINT [DF_EMFScenario_Type] DEFAULT ((0)) FOR [Type]; GO +ALTER TABLE [dbo].[EMFScenario] ADD CONSTRAINT [DF_EMFScenario_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[EMFScenario] ADD CONSTRAINT [DF_EMFScenario_ScenarioGUID] DEFAULT (newid()) FOR [SCENARIOGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFStrataStructureConvertedScoreCompositeLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFStrataStructureConvertedScoreCompositeLink] ( + [StructureGUID] uniqueidentifier NOT NULL, + [ScoreCompositeGUID] uniqueidentifier NOT NULL, + [StructureType] int NOT NULL, + PRIMARY KEY ([StructureGUID]) +); +GO +ALTER TABLE [dbo].[EMFStrataStructureConvertedScoreCompositeLink] ADD CONSTRAINT [DF__EMFStrata__Struc__420E29EA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [StructureGUID]; GO +ALTER TABLE [dbo].[EMFStrataStructureConvertedScoreCompositeLink] ADD CONSTRAINT [DF__EMFStrata__Score__43024E23] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScoreCompositeGUID]; GO +ALTER TABLE [dbo].[EMFStrataStructureConvertedScoreCompositeLink] ADD CONSTRAINT [DF__EMFStrata__Struc__43F6725C] DEFAULT ((0)) FOR [StructureType]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFSubtable ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFSubtable] ( + [SUBTABLEGUID] uniqueidentifier NOT NULL, + [MODELDATACONFIGGUID] uniqueidentifier NOT NULL, + [PARENTSUBTABLEGUID] uniqueidentifier NOT NULL, + [FOLDERGUID] uniqueidentifier NOT NULL, + [NAME] nvarchar(64) NOT NULL, + [DESCRIPTION] nvarchar(450) NOT NULL, + [MEASUREGUID] uniqueidentifier NOT NULL, + [AGGREGATIONFUNCTION] int NOT NULL, + [ISALLOWINGFROZENROWS] bit NOT NULL, + [ISALLOWINGFROZENCOLUMNS] bit NOT NULL, + [CUSTOMMENUGUID] uniqueidentifier NOT NULL, + [IsLoadingExistingData] bit NOT NULL, + [IsReadOnly] bit NOT NULL, + [IsShowingDateTimeStamp] bit NOT NULL, + [RowHeight] int NOT NULL, + [IsShowingModifiedUser] bit NOT NULL, + [IsAutoRefreshingPlanCalculations] bit NOT NULL, + PRIMARY KEY ([SUBTABLEGUID]) +); +GO +ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubTableConfig_SUBTABLECONFIGGUID] DEFAULT (newid()) FOR [SUBTABLEGUID]; GO +ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubTableConfig_SUBTABLEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MODELDATACONFIGGUID]; GO +ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubTableConfig_PARENTSUBTABLECONFIGGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PARENTSUBTABLEGUID]; GO +ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubTableConfig_FOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FOLDERGUID]; GO +ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubTableConfig_NAME] DEFAULT ('') FOR [NAME]; GO +ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubTableConfig_DESCRIPTION] DEFAULT ('') FOR [DESCRIPTION]; GO +ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubTableConfig_MEASUREGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MEASUREGUID]; GO +ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubTableConfig_AGGREGATIONFUNCTION] DEFAULT ((0)) FOR [AGGREGATIONFUNCTION]; GO +ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubtable_ISALLOWINGNEWROWS] DEFAULT ((1)) FOR [ISALLOWINGFROZENROWS]; GO +ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubtable_ISALLOWINGNEWCOLUMNS] DEFAULT ((0)) FOR [ISALLOWINGFROZENCOLUMNS]; GO +ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubtable_CUSTOMMENUGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CUSTOMMENUGUID]; GO +ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubtable_IsLoadingExistingData] DEFAULT ((1)) FOR [IsLoadingExistingData]; GO +ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubtable_IsReadOnly] DEFAULT ((0)) FOR [IsReadOnly]; GO +ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubtable_IsShowingDateTimeStamp] DEFAULT ((0)) FOR [IsShowingDateTimeStamp]; GO +ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubtable_RowHeight] DEFAULT ((25)) FOR [RowHeight]; GO +ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubtable_IsShowingLastUserModified] DEFAULT ((0)) FOR [IsShowingModifiedUser]; GO +ALTER TABLE [dbo].[EMFSubtable] ADD CONSTRAINT [DF_EMFSubtable_IsAutoRefreshingPlanCalculations] DEFAULT ((0)) FOR [IsAutoRefreshingPlanCalculations]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFSubtableDefaultTuple ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFSubtableDefaultTuple] ( + [SUBTABLEDEFAULTTUPLEGUID] uniqueidentifier NOT NULL, + [SUBTABLEGUID] uniqueidentifier NOT NULL, + [ISONCOLUMN] bit NOT NULL, + [DIMENSIONTUPLEXML] xml(max) NOT NULL, + PRIMARY KEY ([SUBTABLEDEFAULTTUPLEGUID]) +); +GO +ALTER TABLE [dbo].[EMFSubtableDefaultTuple] ADD CONSTRAINT [FK_EMFSubtableDefaultTuple_EMFSubtable] FOREIGN KEY ([SUBTABLEGUID]) REFERENCES [dbo].[EMFSubtable] ([SUBTABLEGUID]); GO +ALTER TABLE [dbo].[EMFSubtableDefaultTuple] ADD CONSTRAINT [DF_EMFSubtableDefaultTuple_SUBTABLEDEFAULTTUPLEGUID] DEFAULT (newid()) FOR [SUBTABLEDEFAULTTUPLEGUID]; GO +ALTER TABLE [dbo].[EMFSubtableDefaultTuple] ADD CONSTRAINT [DF_EMFSubtableDefaultTuple_SUBTABLEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SUBTABLEGUID]; GO +ALTER TABLE [dbo].[EMFSubtableDefaultTuple] ADD CONSTRAINT [DF_EMFSubtableDefaultTuple_ISONCOLUMN] DEFAULT ((0)) FOR [ISONCOLUMN]; GO +ALTER TABLE [dbo].[EMFSubtableDefaultTuple] ADD CONSTRAINT [DF_EMFSubtableDefaultTuple_DIMENSIONTUPLEXML] DEFAULT ('') FOR [DIMENSIONTUPLEXML]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFSubtableDimensionLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFSubtableDimensionLink] ( + [SUBTABLEDIMENSIONLINKGUID] uniqueidentifier NOT NULL, + [SubtableGUID] uniqueidentifier NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + [FilterParentMemberGUID] uniqueidentifier NOT NULL, + [Level] int NOT NULL, + [IsParameter] bit NOT NULL, + [IsAggregable] bit NOT NULL, + [IsDisplayOnColumns] bit NOT NULL, + [IsEditable] bit NOT NULL, + [IsVisible] bit NOT NULL, + [DefaultMemberGUID] uniqueidentifier NOT NULL, + [DisplayOrder] int NOT NULL, + [ColumnWidth] int NOT NULL, + [ISLOADINGCHILDMEMBERS] bit NOT NULL, + [FRIENDLYNAME] nvarchar(64) NOT NULL, + [AutoCompleteSearchType] int NOT NULL, + [IsIgnoringReadSecurity] bit NOT NULL, + PRIMARY KEY ([SUBTABLEDIMENSIONLINKGUID]) +); +GO +ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [FK_EMFSubTableDimensionLink_EMFSubTable] FOREIGN KEY ([SubtableGUID]) REFERENCES [dbo].[EMFSubtable] ([SUBTABLEGUID]); GO +ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubtableDimensionLink_IsIgnoringReadSecurity] DEFAULT ((0)) FOR [IsIgnoringReadSecurity]; GO +ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubTableConfigDimensionLink_SUBTABLECONFIGDIMENSIONLINKGUID] DEFAULT (newid()) FOR [SUBTABLEDIMENSIONLINKGUID]; GO +ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_SubTableConfigDimensionLink_SUBTABLECONFIGGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SubtableGUID]; GO +ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_SubTableConfigDimensionLink_DIMENSIONGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO +ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubTableConfigDimensionLink_DIMENSIONMEMBERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FilterParentMemberGUID]; GO +ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubTableConfigDimension_DIMENSIONLEVEL] DEFAULT ((0)) FOR [Level]; GO +ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_SubTableConfigDimensionLink_ISPARAMETER] DEFAULT ((0)) FOR [IsParameter]; GO +ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_SubTableConfigDimensionLink_ISAGGREGATABLE] DEFAULT ((0)) FOR [IsAggregable]; GO +ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubtableDimensionLink_ISDISPLAYONCOLUMNS] DEFAULT ((0)) FOR [IsDisplayOnColumns]; GO +ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubtableDimensionLink_ISALLOWINGDEFAULTMEMBERONLY] DEFAULT ((1)) FOR [IsEditable]; GO +ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubtableDimensionLink_ISVISIBLE] DEFAULT ((1)) FOR [IsVisible]; GO +ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubtableDimensionLink_DEFAULTMEMBERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultMemberGUID]; GO +ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubtableDimensionLink_DISPLAYORDER] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubtableDimensionLink_COLUMNWIDTH] DEFAULT ((100)) FOR [ColumnWidth]; GO +ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubtableDimensionLink_ISLOADINGCHILDMEMBERS] DEFAULT ((0)) FOR [ISLOADINGCHILDMEMBERS]; GO +ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubtableDimensionLink_FRIENDLYNAME] DEFAULT ('') FOR [FRIENDLYNAME]; GO +ALTER TABLE [dbo].[EMFSubtableDimensionLink] ADD CONSTRAINT [DF_EMFSubtableDimensionLink_AutoCompleteSearchType] DEFAULT ((0)) FOR [AutoCompleteSearchType]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFSubtableFilter ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFSubtableFilter] ( + [SubtableDimensionLinkGUID] uniqueidentifier NOT NULL, + [DimensionMemberGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([SubtableDimensionLinkGUID], [DimensionMemberGUID]) +); +GO +ALTER TABLE [dbo].[EMFSubtableFilter] ADD CONSTRAINT [FK_EMFSubTableFilter_EMFSubTableDimensionLink] FOREIGN KEY ([SubtableDimensionLinkGUID]) REFERENCES [dbo].[EMFSubtableDimensionLink] ([SUBTABLEDIMENSIONLINKGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EMFSubtableMeasureLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EMFSubtableMeasureLink] ( + [SubtableMeasureLinkGUID] uniqueidentifier NOT NULL, + [SubtableGUID] uniqueidentifier NOT NULL, + [MeasureGUID] uniqueidentifier NOT NULL, + [AggregationFunction] int NOT NULL, + [DisplayOrder] int NOT NULL, + [ColumnWidth] int NOT NULL, + [IsRequired] bit NOT NULL, + [IsReadOnly] bit NOT NULL, + PRIMARY KEY ([SubtableMeasureLinkGUID]) +); +GO +ALTER TABLE [dbo].[EMFSubtableMeasureLink] ADD CONSTRAINT [DF_EMFSubtableMeasureLink_SUBTABLEMEASURELINKGUID] DEFAULT (newid()) FOR [SubtableMeasureLinkGUID]; GO +ALTER TABLE [dbo].[EMFSubtableMeasureLink] ADD CONSTRAINT [DF_EMFSubtableMeasureLink_AGGREGATIONFUNCTION] DEFAULT ((0)) FOR [AggregationFunction]; GO +ALTER TABLE [dbo].[EMFSubtableMeasureLink] ADD CONSTRAINT [DF_EMFSubtableMeasureLink_DISPLAYORDER] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[EMFSubtableMeasureLink] ADD CONSTRAINT [DF_EMFSubtableMeasureLink_COLUMNWIDTH] DEFAULT ((125)) FOR [ColumnWidth]; GO +ALTER TABLE [dbo].[EMFSubtableMeasureLink] ADD CONSTRAINT [DF_EMFSubtableMeasureLink_IsRequired] DEFAULT ((0)) FOR [IsRequired]; GO +ALTER TABLE [dbo].[EMFSubtableMeasureLink] ADD CONSTRAINT [DF_EMFSubtableMeasureLink_IsReadOnly] DEFAULT ((0)) FOR [IsReadOnly]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EmailMessage ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EmailMessage] ( + [EmailMessageGUID] uniqueidentifier NOT NULL, + [EmailThreadGUID] uniqueidentifier NOT NULL, + [Subject] nvarchar(450) NOT NULL, + [DateTimeStamp] datetime NOT NULL, + [Body] nvarchar(max) NOT NULL, + [SenderUserGUID] uniqueidentifier NOT NULL, + [Priority] tinyint NOT NULL, + PRIMARY KEY ([EmailMessageGUID]) +); +GO +ALTER TABLE [dbo].[EmailMessage] ADD CONSTRAINT [FK_EmailMessage_EmailThread] FOREIGN KEY ([EmailThreadGUID]) REFERENCES [dbo].[EmailThread] ([EmailThreadGUID]); GO +ALTER TABLE [dbo].[EmailMessage] ADD CONSTRAINT [DF_EmailMessage_EmailMessageThreadGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EmailThreadGUID]; GO +ALTER TABLE [dbo].[EmailMessage] ADD CONSTRAINT [DF_EmailMessage_EmailMessageGUID] DEFAULT (newid()) FOR [EmailMessageGUID]; GO +ALTER TABLE [dbo].[EmailMessage] ADD CONSTRAINT [DF_EmailMessage_Subject] DEFAULT ('') FOR [Subject]; GO +ALTER TABLE [dbo].[EmailMessage] ADD CONSTRAINT [DF_EmailMessage_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO +ALTER TABLE [dbo].[EmailMessage] ADD CONSTRAINT [DF_EmailMessage_Body] DEFAULT ('') FOR [Body]; GO +ALTER TABLE [dbo].[EmailMessage] ADD CONSTRAINT [DF_EmailMessage_SenderUserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SenderUserGUID]; GO +ALTER TABLE [dbo].[EmailMessage] ADD CONSTRAINT [DF_EmailMessage_Priority] DEFAULT ((0)) FOR [Priority]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EmailRecipient ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EmailRecipient] ( + [EmailRecipientGUID] uniqueidentifier NOT NULL, + [EmailMessageGUID] uniqueidentifier NOT NULL, + [IdentityGUID] uniqueidentifier NOT NULL, + [IdentityType] tinyint NOT NULL, + [RecipientType] tinyint NOT NULL, + PRIMARY KEY ([EmailRecipientGUID]) +); +GO +ALTER TABLE [dbo].[EmailRecipient] ADD CONSTRAINT [FK_EmailRecipient_EmailMessage] FOREIGN KEY ([EmailMessageGUID]) REFERENCES [dbo].[EmailMessage] ([EmailMessageGUID]); GO +ALTER TABLE [dbo].[EmailRecipient] ADD CONSTRAINT [DF_EmailRecipient_EmailMessageGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EmailMessageGUID]; GO +ALTER TABLE [dbo].[EmailRecipient] ADD CONSTRAINT [DF_EmailRecipient_IdentityGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [IdentityGUID]; GO +ALTER TABLE [dbo].[EmailRecipient] ADD CONSTRAINT [DF_EmailRecipient_EmailRecipientGUID] DEFAULT (newid()) FOR [EmailRecipientGUID]; GO +ALTER TABLE [dbo].[EmailRecipient] ADD CONSTRAINT [DF_EmailRecipient_IdentityType] DEFAULT ((0)) FOR [IdentityType]; GO +ALTER TABLE [dbo].[EmailRecipient] ADD CONSTRAINT [DF_EmailRecipient_RecipientType] DEFAULT ((0)) FOR [RecipientType]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EmailThread ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EmailThread] ( + [EmailThreadGUID] uniqueidentifier NOT NULL, + [Subject] nvarchar(450) NOT NULL, + [DateTimeStamp] datetime NOT NULL, + [ItemGUID] uniqueidentifier NOT NULL, + [IsForReporting] bit NOT NULL, + [IsPrivate] bit NOT NULL, + PRIMARY KEY ([EmailThreadGUID]) +); +GO +ALTER TABLE [dbo].[EmailThread] ADD CONSTRAINT [DF_EmailThread_EmailThreadGUID] DEFAULT (newid()) FOR [EmailThreadGUID]; GO +ALTER TABLE [dbo].[EmailThread] ADD CONSTRAINT [DF_EmailThread_Subject] DEFAULT ('') FOR [Subject]; GO +ALTER TABLE [dbo].[EmailThread] ADD CONSTRAINT [DF_EmailThread_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO +ALTER TABLE [dbo].[EmailThread] ADD CONSTRAINT [DF_EmailThread_ItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ItemGUID]; GO +ALTER TABLE [dbo].[EmailThread] ADD CONSTRAINT [DF_EmailThread_IsPrivate] DEFAULT ((0)) FOR [IsPrivate]; GO +ALTER TABLE [dbo].[EmailThread] ADD CONSTRAINT [DF_EmailThread_IsForReporting] DEFAULT ((0)) FOR [IsForReporting]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.EntityView ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[EntityView] ( + [ENTITYVIEWGUID] uniqueidentifier NOT NULL, + [NAME] nvarchar(64) NOT NULL, + [DESCRIPTION] nvarchar(4000) NOT NULL, + [DATECREATED] datetime NOT NULL, + [FOLDERGUID] uniqueidentifier NOT NULL, + [USERGUID] uniqueidentifier NOT NULL, + [VIEWTYPE] int NOT NULL, + [SearchText] nvarchar(max) NOT NULL, + [SearchDescription] nvarchar(max) NOT NULL, + [ProviderType] int NOT NULL, + [PlanTypeGUID] uniqueidentifier NOT NULL, + [GridTemplateGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([ENTITYVIEWGUID]) +); +GO +ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_View_VIEWGUID] DEFAULT (newid()) FOR [ENTITYVIEWGUID]; GO +ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_View_NAME] DEFAULT ('') FOR [NAME]; GO +ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_EntityView_DESCRIPTION] DEFAULT ('') FOR [DESCRIPTION]; GO +ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_EntityView_FOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FOLDERGUID]; GO +ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_EntityView_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [USERGUID]; GO +ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_EntityView_VIEWTYPE] DEFAULT ((0)) FOR [VIEWTYPE]; GO +ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_EntityView_GridTemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GridTemplateGUID]; GO +ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_EntityView_SearchText] DEFAULT ('') FOR [SearchText]; GO +ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_EntityView_SearchDescription] DEFAULT ('') FOR [SearchDescription]; GO +ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_EntityView_ProviderType] DEFAULT ((0)) FOR [ProviderType]; GO +ALTER TABLE [dbo].[EntityView] ADD CONSTRAINT [DF_EntityView_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.Event ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[Event] ( + [EventName] varchar(64) NOT NULL, + [Version] timestamp NOT NULL, + PRIMARY KEY ([EventName]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ExtractReportSetup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ExtractReportSetup] ( + [ExtractReportSetupID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [ColumnSetupXML] nvarchar(max) NOT NULL, + [SetupXML] nvarchar(max) NOT NULL, + [ReportTypeVal] tinyint NOT NULL +); +GO +ALTER TABLE [dbo].[ExtractReportSetup] ADD CONSTRAINT [DF__ExtractRep__Name__4C5C079B] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[ExtractReportSetup] ADD CONSTRAINT [DF__ExtractRe__Colum__4D502BD4] DEFAULT ('') FOR [ColumnSetupXML]; GO +ALTER TABLE [dbo].[ExtractReportSetup] ADD CONSTRAINT [DF__ExtractRe__Setup__4E44500D] DEFAULT ('') FOR [SetupXML]; GO +ALTER TABLE [dbo].[ExtractReportSetup] ADD CONSTRAINT [DF__ExtractRe__Repor__4F387446] DEFAULT ((0)) FOR [ReportTypeVal]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FE2AccessOverride ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FE2AccessOverride] ( + [AccessOverrideGUID] uniqueidentifier NOT NULL, + [FormFieldGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [EntityGUID] uniqueidentifier NOT NULL, + [IsWriteDeny] bit NOT NULL, + [IsWriteAllow] bit NOT NULL, + PRIMARY KEY ([AccessOverrideGUID]) +); + +CREATE NONCLUSTERED INDEX [NCNU_FormFieldGUID] ON [dbo].[FE2AccessOverride] ([FormFieldGUID]); +CREATE NONCLUSTERED INDEX [NCNU_FormFieldGUID_EntityGUID] ON [dbo].[FE2AccessOverride] ([FormFieldGUID], [EntityGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_FormFieldGUID_EntityGUID_UserGUID] ON [dbo].[FE2AccessOverride] ([FormFieldGUID], [EntityGUID], [UserGUID]); +GO +ALTER TABLE [dbo].[FE2AccessOverride] ADD CONSTRAINT [FK_FE2AccessOverride_UserProfile] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO +ALTER TABLE [dbo].[FE2AccessOverride] ADD CONSTRAINT [FK_FE2AccessOverride_XPlan] FOREIGN KEY ([EntityGUID]) REFERENCES [dbo].[XPlan] ([PlanGUID]); GO +ALTER TABLE [dbo].[FE2AccessOverride] ADD CONSTRAINT [DF_FE2AccessOverride_IsReadDeny] DEFAULT ((0)) FOR [IsWriteDeny]; GO +ALTER TABLE [dbo].[FE2AccessOverride] ADD CONSTRAINT [DF_FE2AccessOverride_IsWriteAllow] DEFAULT ((0)) FOR [IsWriteAllow]; GO +ALTER TABLE [dbo].[FE2AccessOverride] ADD CONSTRAINT [DF_FE2AccessOverride_AccessOverrideGUID] DEFAULT (newid()) FOR [AccessOverrideGUID]; GO +ALTER TABLE [dbo].[FE2AccessOverride] ADD CONSTRAINT [DF_FE2AccessOverride_FormFieldGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormFieldGUID]; GO +ALTER TABLE [dbo].[FE2AccessOverride] ADD CONSTRAINT [DF_FE2AccessOverride_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[FE2AccessOverride] ADD CONSTRAINT [DF_FE2AccessOverride_EntityGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FE2CapitalHiddenElement_TK28067 ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FE2CapitalHiddenElement_TK28067] ( + [FormElementGUID] uniqueidentifier NOT NULL, + [FormGUID] uniqueidentifier NOT NULL, + [ProjectTypeID] int NOT NULL +); +GO +ALTER TABLE [dbo].[FE2CapitalHiddenElement_TK28067] ADD CONSTRAINT [FK__FE2Capita__FormG__7AABE50F] FOREIGN KEY ([FormGUID]) REFERENCES [dbo].[FE2Form] ([FormGUID]); GO +ALTER TABLE [dbo].[FE2CapitalHiddenElement_TK28067] ADD CONSTRAINT [DF__FE2Capita__Proje__7BA00948] DEFAULT ((0)) FOR [ProjectTypeID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FE2Form ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FE2Form] ( + [FormGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Description] nvarchar(400) NOT NULL, + [GlobalID] nvarchar(100) NOT NULL, + [CustomToolbarGUID] uniqueidentifier NOT NULL, + [PlanTypeGUID] uniqueidentifier NOT NULL, + [IsHidden] bit NOT NULL, + [CustomMenuGUID] uniqueidentifier NOT NULL, + [OldFormGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([FormGUID]) +); +GO +ALTER TABLE [dbo].[FE2Form] ADD CONSTRAINT [DF__FE2Form__OldForm__21DE87B2] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OldFormGUID]; GO +ALTER TABLE [dbo].[FE2Form] ADD CONSTRAINT [DF__FE2Form__PlanTyp__7691D4F5] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO +ALTER TABLE [dbo].[FE2Form] ADD CONSTRAINT [DF__FE2Form__FormGUI__35B835D1] DEFAULT (newid()) FOR [FormGUID]; GO +ALTER TABLE [dbo].[FE2Form] ADD CONSTRAINT [DF__FE2Form__Name__36AC5A0A] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[FE2Form] ADD CONSTRAINT [DF__FE2Form__Descrip__37A07E43] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[FE2Form] ADD CONSTRAINT [DF__FE2Form__GlobalI__3894A27C] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [dbo].[FE2Form] ADD CONSTRAINT [DF__FE2Form__CustomT__3988C6B5] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CustomToolbarGUID]; GO +ALTER TABLE [dbo].[FE2Form] ADD CONSTRAINT [DF__FE2Form__IsHidde__6A8E52C8] DEFAULT ((0)) FOR [IsHidden]; GO +ALTER TABLE [dbo].[FE2Form] ADD CONSTRAINT [DF__FE2Form__CustomM__713B5057] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CustomMenuGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FE2FormField ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FE2FormField] ( + [FormFieldGUID] uniqueidentifier NOT NULL, + [FormSectionGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(200) NULL, + [GlobalID] nvarchar(100) NOT NULL, + [FieldType] tinyint NOT NULL, + [DataSourceType] tinyint NOT NULL, + [DataSourceGUID] uniqueidentifier NOT NULL, + [Row] int NOT NULL, + [Col] int NOT NULL, + [HelpText] nvarchar(2000) NOT NULL, + [FormatString] nvarchar(100) NOT NULL, + [DisplayOrder] int NOT NULL, + [ColSpan] tinyint NOT NULL, + [IsReadOnly] bit NOT NULL, + [IsRequired] tinyint NOT NULL, + [DefaultSortOrder] tinyint NOT NULL, + [HelpTextDisplayType] tinyint NOT NULL, + [DefaultValue] nvarchar(450) NOT NULL, + [MinValue] decimal NOT NULL, + [MaxValue] decimal NOT NULL, + [MinLength] int NOT NULL, + [MaxLength] int NOT NULL, + [SpecialFieldClassName] nvarchar(100) NOT NULL, + [SpecialFieldConfig] nvarchar(max) NOT NULL, + [ComputedFieldClassName] nvarchar(100) NOT NULL, + [ComputedFieldConfig] nvarchar(max) NOT NULL, + [ListSourceClassName] nvarchar(100) NOT NULL, + [ListSourceConfig] nvarchar(max) NOT NULL, + [IsFullTextSearchable] bit NOT NULL, + [Abbreviation] nvarchar(100) NOT NULL, + [HasLabel] bit NOT NULL, + [RenderType] int NOT NULL, + [RenderThreshold] float NOT NULL, + [RenderComparisonFieldGUID] uniqueidentifier NOT NULL, + [RenderComparisonOperator] int NOT NULL, + [OldFormFieldGUID] uniqueidentifier NOT NULL, + [OldFormFieldName] nvarchar(450) NULL, + [ShowInDirectory] bit NOT NULL, + [IsEditableInDirectory] bit NOT NULL, + [Height] int NOT NULL, + [IsDeletable] bit NOT NULL, + [IsStrataField] bit NOT NULL, + [IsDesignerEditable] bit NOT NULL, + [IsDesignerHidden] bit NOT NULL, + PRIMARY KEY ([FormFieldGUID]) +); +GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [FK__FE2FormFi__FormS__506C2C0D] FOREIGN KEY ([FormSectionGUID]) REFERENCES [dbo].[FE2FormSection] ([FormSectionGUID]); GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_ComputedFieldClassName] DEFAULT ('') FOR [ComputedFieldClassName]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_ComputedFieldConfig] DEFAULT ('') FOR [ComputedFieldConfig]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__HasLa__06366D3D] DEFAULT ((1)) FOR [HasLabel]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Rende__072A9176] DEFAULT ((0)) FOR [RenderType]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Rende__081EB5AF] DEFAULT ((0)) FOR [RenderThreshold]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Rende__0912D9E8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RenderComparisonFieldGUID]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__ListS__09A4A969] DEFAULT ('') FOR [ListSourceClassName]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Rende__0A06FE21] DEFAULT ((0)) FOR [RenderComparisonOperator]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__ListS__0A98CDA2] DEFAULT ('') FOR [ListSourceConfig]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_OldFormFieldName] DEFAULT ('') FOR [OldFormFieldName]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Sourc__5530E12A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataSourceGUID]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__ShowI__1FF63F40] DEFAULT ((0)) FOR [ShowInDirectory]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_OldFormFieldGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OldFormFieldGUID]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__FormF__4F7807D4] DEFAULT (newid()) FOR [FormFieldGUID]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFie__Name__51605046] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Globa__5254747F] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Field__534898B8] DEFAULT ((0)) FOR [FieldType]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Sourc__543CBCF1] DEFAULT ((0)) FOR [DataSourceType]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFiel__Row__56250563] DEFAULT ((0)) FOR [Row]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFiel__Col__5719299C] DEFAULT ((0)) FOR [Col]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__IsDes__585960DA] DEFAULT ((0)) FOR [IsDesignerHidden]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__HelpT__59F59647] DEFAULT ('') FOR [HelpText]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Forma__5AE9BA80] DEFAULT ('') FOR [FormatString]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Heigh__5F4853FC] DEFAULT ((0)) FOR [Height]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Displ__637F0081] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__ColSp__656748F3] DEFAULT ((0)) FOR [ColSpan]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_IsReadOnly] DEFAULT ((0)) FOR [IsReadOnly]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_IsRequired] DEFAULT ((0)) FOR [IsRequired]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_DefaultSortOrder] DEFAULT ((0)) FOR [DefaultSortOrder]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_HelpTextDisplayType] DEFAULT ((0)) FOR [HelpTextDisplayType]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_DefaultValue] DEFAULT ('') FOR [DefaultValue]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_MinValue] DEFAULT ((0)) FOR [MinValue]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__IsFul__6B827701] DEFAULT ((0)) FOR [IsFullTextSearchable]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_MaxValue] DEFAULT ((0)) FOR [MaxValue]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF_FE2FormField_Abbreviation] DEFAULT ('') FOR [Abbreviation]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__MinLe__3A42832D] DEFAULT ((0)) FOR [MinLength]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__MaxLe__394E5EF4] DEFAULT ((0)) FOR [MaxLength]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__IsEdi__75E0D53A] DEFAULT ((0)) FOR [IsEditableInDirectory]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__IsDel__76DB542B] DEFAULT ((1)) FOR [IsDeletable]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Speci__796E41A0] DEFAULT ('') FOR [SpecialFieldClassName]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__Speci__7A6265D9] DEFAULT ('') FOR [SpecialFieldConfig]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__IsStr__7D15E43D] DEFAULT ((0)) FOR [IsStrataField]; GO +ALTER TABLE [dbo].[FE2FormField] ADD CONSTRAINT [DF__FE2FormFi__IsDes__7E0A0876] DEFAULT ((1)) FOR [IsDesignerEditable]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FE2FormFieldRefreshRequest ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FE2FormFieldRefreshRequest] ( + [RequestGUID] uniqueidentifier NOT NULL, + [FormFieldGUIDCSV] nvarchar(max) NOT NULL, + [PlanLookupSQL] nvarchar(max) NOT NULL, + [PlanTypeGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([RequestGUID]) +); +GO +ALTER TABLE [dbo].[FE2FormFieldRefreshRequest] ADD CONSTRAINT [DF_FE2FormFieldRefreshRequest_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO +ALTER TABLE [dbo].[FE2FormFieldRefreshRequest] ADD CONSTRAINT [DF_FE2FormFieldRefreshRequest_RequestGUID] DEFAULT (newid()) FOR [RequestGUID]; GO +ALTER TABLE [dbo].[FE2FormFieldRefreshRequest] ADD CONSTRAINT [DF_FE2FormFieldRefreshRequest_FormFieldGUIDCSV] DEFAULT ('') FOR [FormFieldGUIDCSV]; GO +ALTER TABLE [dbo].[FE2FormFieldRefreshRequest] ADD CONSTRAINT [DF_FE2FormFieldRefreshRequest_PlanLookupSQL] DEFAULT ('') FOR [PlanLookupSQL]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FE2FormFieldSynonym ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FE2FormFieldSynonym] ( + [SynonymGUID] uniqueidentifier NOT NULL, + [FormFieldGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + PRIMARY KEY ([SynonymGUID]) +); +GO +ALTER TABLE [dbo].[FE2FormFieldSynonym] ADD CONSTRAINT [FK_FE2FormFieldSynonym_FE2FormField] FOREIGN KEY ([FormFieldGUID]) REFERENCES [dbo].[FE2FormField] ([FormFieldGUID]); GO +ALTER TABLE [dbo].[FE2FormFieldSynonym] ADD CONSTRAINT [DF_FEFormFieldSynonym_SynonymGUID] DEFAULT (newid()) FOR [SynonymGUID]; GO +ALTER TABLE [dbo].[FE2FormFieldSynonym] ADD CONSTRAINT [DF_FEFormFieldSynonym_Value] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[FE2FormFieldSynonym] ADD CONSTRAINT [DF_FEFormFieldSynonym_FormFieldGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormFieldGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FE2FormSection ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FE2FormSection] ( + [FormSectionGUID] uniqueidentifier NOT NULL, + [FormTabGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [DisplayOrder] int NOT NULL, + [ColumnCount] int NOT NULL, + [HasSectionBreak] bit NOT NULL, + [LabelAlign] tinyint NOT NULL, + [LabelWidth] int NOT NULL, + [GlobalID] nvarchar(100) NOT NULL, + [IsPrintable] bit NOT NULL, + [IsPageBreak] bit NOT NULL, + PRIMARY KEY ([FormSectionGUID]) +); +GO +ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [FK__FE2FormSe__FormT__46E2C1D3] FOREIGN KEY ([FormTabGUID]) REFERENCES [dbo].[FE2FormTab] ([FormTabGUID]); GO +ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [DF__FE2FormSe__Globa__035A0092] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [DF__FE2FormSe__IsPag__2DB687C9] DEFAULT ((0)) FOR [IsPageBreak]; GO +ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [DF__FE2FormSe__FormS__45EE9D9A] DEFAULT (newid()) FOR [FormSectionGUID]; GO +ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [DF__FE2FormSec__Name__47D6E60C] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [DF__FE2FormSe__Displ__48CB0A45] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [DF__FE2FormSe__Colum__4AB352B7] DEFAULT ((0)) FOR [ColumnCount]; GO +ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [DF__FE2FormSe__IsPri__5E3FEC81] DEFAULT ((1)) FOR [IsPrintable]; GO +ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [DF__FE2FormSe__hasSe__7B568A12] DEFAULT ((1)) FOR [HasSectionBreak]; GO +ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [DF__FE2FormSe__Label__7C4AAE4B] DEFAULT ((0)) FOR [LabelAlign]; GO +ALTER TABLE [dbo].[FE2FormSection] ADD CONSTRAINT [DF__FE2FormSe__Label__7D3ED284] DEFAULT ((0)) FOR [LabelWidth]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FE2FormTab ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FE2FormTab] ( + [FormTabGUID] uniqueidentifier NOT NULL, + [FormGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [DisplayOrder] int NOT NULL, + [GlobalID] nvarchar(100) NOT NULL, + [IsPrintable] bit NOT NULL, + PRIMARY KEY ([FormTabGUID]) +); +GO +ALTER TABLE [dbo].[FE2FormTab] ADD CONSTRAINT [FK__FE2FormTa__FormG__3F41A00B] FOREIGN KEY ([FormGUID]) REFERENCES [dbo].[FE2Form] ([FormGUID]); GO +ALTER TABLE [dbo].[FE2FormTab] ADD CONSTRAINT [DF__FE2FormTa__Globa__0265DC59] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [dbo].[FE2FormTab] ADD CONSTRAINT [DF__FE2FormTa__FormT__3E4D7BD2] DEFAULT (newid()) FOR [FormTabGUID]; GO +ALTER TABLE [dbo].[FE2FormTab] ADD CONSTRAINT [DF__FE2FormTab__Name__4035C444] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[FE2FormTab] ADD CONSTRAINT [DF__FE2FormTa__Displ__4129E87D] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[FE2FormTab] ADD CONSTRAINT [DF__FE2FormTa__IsPri__54B05959] DEFAULT ((1)) FOR [IsPrintable]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FE2FormTextData ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FE2FormTextData] ( + [FormDataGUID] uniqueidentifier NOT NULL, + [FormFieldGUID] uniqueidentifier NOT NULL, + [EntityGUID] uniqueidentifier NOT NULL, + [Value] nvarchar(max) NOT NULL, + PRIMARY KEY ([FormDataGUID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_EntityGUID] ON [dbo].[FE2FormTextData] ([EntityGUID]); +GO +ALTER TABLE [dbo].[FE2FormTextData] ADD CONSTRAINT [FK__FE2FormDa__FormF__60A293D6] FOREIGN KEY ([FormFieldGUID]) REFERENCES [dbo].[FE2FormField] ([FormFieldGUID]); GO +ALTER TABLE [dbo].[FE2FormTextData] ADD CONSTRAINT [FK_FE2FormTextData_EntityID] FOREIGN KEY ([EntityGUID]) REFERENCES [dbo].[XPlan] ([PlanGUID]); GO +ALTER TABLE [dbo].[FE2FormTextData] ADD CONSTRAINT [DF__FE2FormDa__Entit__6196B80F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGUID]; GO +ALTER TABLE [dbo].[FE2FormTextData] ADD CONSTRAINT [DF__FE2FormDa__FormD__5FAE6F9D] DEFAULT (newid()) FOR [FormDataGUID]; GO +ALTER TABLE [dbo].[FE2FormTextData] ADD CONSTRAINT [DF__FE2FormDa__Value__628ADC48] DEFAULT ('') FOR [Value]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FE2RuleConfig ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FE2RuleConfig] ( + [RuleConfigGUID] uniqueidentifier NOT NULL, + [FormGUID] uniqueidentifier NOT NULL, + [FormElementGUID] uniqueidentifier NOT NULL, + [RuleClassName] nvarchar(100) NOT NULL, + [RuleXML] nvarchar(max) NOT NULL, + [IsUsingOr] bit NOT NULL, + [DisplayOrder] int NOT NULL, + PRIMARY KEY ([RuleConfigGUID]) +); +GO +ALTER TABLE [dbo].[FE2RuleConfig] ADD CONSTRAINT [FK__FE2RuleCo__FormG__1E9FC64F] FOREIGN KEY ([FormGUID]) REFERENCES [dbo].[FE2Form] ([FormGUID]); GO +ALTER TABLE [dbo].[FE2RuleConfig] ADD CONSTRAINT [DF__FE2RuleCo__RuleC__1DABA216] DEFAULT (newid()) FOR [RuleConfigGUID]; GO +ALTER TABLE [dbo].[FE2RuleConfig] ADD CONSTRAINT [DF__FE2RuleCo__RuleC__20880EC1] DEFAULT ('') FOR [RuleClassName]; GO +ALTER TABLE [dbo].[FE2RuleConfig] ADD CONSTRAINT [DF__FE2RuleCo__RuleX__217C32FA] DEFAULT ('') FOR [RuleXML]; GO +ALTER TABLE [dbo].[FE2RuleConfig] ADD CONSTRAINT [DF__FE2RuleCo__IsUsi__22705733] DEFAULT ((1)) FOR [IsUsingOr]; GO +ALTER TABLE [dbo].[FE2RuleConfig] ADD CONSTRAINT [DF__FE2RuleCo__Displ__41F05A65] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[FE2RuleConfig] ADD CONSTRAINT [DF__FE2RuleCo__FormE__1F93EA88] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormElementGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FE2ScriptSnippetHistory ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FE2ScriptSnippetHistory] ( + [SnippetGUID] uniqueidentifier NOT NULL, + [OldValue] nvarchar(max) NOT NULL, + [NewValue] nvarchar(max) NOT NULL, + [IsComplete] bit NOT NULL, + [HistoryGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([SnippetGUID]) +); +GO +ALTER TABLE [dbo].[FE2ScriptSnippetHistory] ADD CONSTRAINT [DF_FE2ScriptSnippetHistory_HistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryGUID]; GO +ALTER TABLE [dbo].[FE2ScriptSnippetHistory] ADD CONSTRAINT [DF_FE2ScriptSnippetHistory_SnippetGUID] DEFAULT (newid()) FOR [SnippetGUID]; GO +ALTER TABLE [dbo].[FE2ScriptSnippetHistory] ADD CONSTRAINT [DF_FE2ScriptSnippetHistory_OldValue] DEFAULT ('') FOR [OldValue]; GO +ALTER TABLE [dbo].[FE2ScriptSnippetHistory] ADD CONSTRAINT [DF_FE2ScriptSnippetHistory_NewValue] DEFAULT ('') FOR [NewValue]; GO +ALTER TABLE [dbo].[FE2ScriptSnippetHistory] ADD CONSTRAINT [DF_FE2ScriptSnippetHistory_IsComplete] DEFAULT ((0)) FOR [IsComplete]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FE2ScriptUpgradeHistory ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FE2ScriptUpgradeHistory] ( + [CustomScriptGUID] uniqueidentifier NOT NULL, + [SQLObjectName] nvarchar(100) NOT NULL, + [OldValue] nvarchar(max) NOT NULL, + [NewValue] nvarchar(max) NOT NULL, + [RiskLevel] tinyint NOT NULL, + [IsComplete] bit NOT NULL, + [HistoryGUID] uniqueidentifier NOT NULL, + [ErrorGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([HistoryGUID]) +); +GO +ALTER TABLE [dbo].[FE2ScriptUpgradeHistory] ADD CONSTRAINT [DF_FE2ScriptUpgradeHistory_SQLObjectName] DEFAULT ('') FOR [SQLObjectName]; GO +ALTER TABLE [dbo].[FE2ScriptUpgradeHistory] ADD CONSTRAINT [DF_FE2ScriptUpgradeHistory_OldValue] DEFAULT ('') FOR [OldValue]; GO +ALTER TABLE [dbo].[FE2ScriptUpgradeHistory] ADD CONSTRAINT [DF_FE2ScriptUpgradeHistory_NewValue] DEFAULT ('') FOR [NewValue]; GO +ALTER TABLE [dbo].[FE2ScriptUpgradeHistory] ADD CONSTRAINT [DF_FE2ScriptUpgradeHistory_RiskLevel] DEFAULT ((0)) FOR [RiskLevel]; GO +ALTER TABLE [dbo].[FE2ScriptUpgradeHistory] ADD CONSTRAINT [DF_FE2ScriptUpgradeHistory_IsComplete] DEFAULT ((0)) FOR [IsComplete]; GO +ALTER TABLE [dbo].[FE2ScriptUpgradeHistory] ADD CONSTRAINT [DF_FE2ScriptUpgradeHistory_HistoryGUID] DEFAULT (newid()) FOR [HistoryGUID]; GO +ALTER TABLE [dbo].[FE2ScriptUpgradeHistory] ADD CONSTRAINT [DF_FE2ScriptUpgradeHistory_ErrorGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ErrorGUID]; GO +ALTER TABLE [dbo].[FE2ScriptUpgradeHistory] ADD CONSTRAINT [DF_FE2ScriptUpgradeHistory_CustomScriptGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CustomScriptGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FEAccessOverride ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FEAccessOverride] ( + [AccessOverrideGUID] uniqueidentifier NOT NULL, + [FormFieldGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [EntityGUID] uniqueidentifier NOT NULL, + [IsWriteDeny] bit NOT NULL, + [IsWriteAllow] bit NOT NULL, + PRIMARY KEY ([AccessOverrideGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_FEAccessOverride_Unique] ON [dbo].[FEAccessOverride] ([FormFieldGUID], [EntityGUID], [UserGUID]); +GO +ALTER TABLE [dbo].[FEAccessOverride] ADD CONSTRAINT [FK_FEAccessOverride_FEFormField] FOREIGN KEY ([FormFieldGUID]) REFERENCES [dbo].[FEFormField] ([FORMFIELDGUID]); GO +ALTER TABLE [dbo].[FEAccessOverride] ADD CONSTRAINT [FK_FEAccessOverride_UserProfile] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO +ALTER TABLE [dbo].[FEAccessOverride] ADD CONSTRAINT [FK_FEAccessOverride_XPlan] FOREIGN KEY ([EntityGUID]) REFERENCES [dbo].[XPlan] ([PlanGUID]); GO +ALTER TABLE [dbo].[FEAccessOverride] ADD CONSTRAINT [DF_FEAccessOverride_AccessOverrideGUID] DEFAULT (newid()) FOR [AccessOverrideGUID]; GO +ALTER TABLE [dbo].[FEAccessOverride] ADD CONSTRAINT [DF_FEAccessOverride_FormFieldGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormFieldGUID]; GO +ALTER TABLE [dbo].[FEAccessOverride] ADD CONSTRAINT [DF_Table_1_IdentityGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[FEAccessOverride] ADD CONSTRAINT [DF_FEAccessOverride_EntityGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGUID]; GO +ALTER TABLE [dbo].[FEAccessOverride] ADD CONSTRAINT [DF_FEAccessOverride_IsReadDeny] DEFAULT ((0)) FOR [IsWriteDeny]; GO +ALTER TABLE [dbo].[FEAccessOverride] ADD CONSTRAINT [DF_FEAccessOverride_IsWriteAllow] DEFAULT ((0)) FOR [IsWriteAllow]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FEComment ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FEComment] ( + [CommentGUID] uniqueidentifier NOT NULL, + [EntityGUID] uniqueidentifier NOT NULL, + [FormFieldGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [UserNameFull] nvarchar(100) NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [DateTimeStamp] datetime NOT NULL, + PRIMARY KEY ([CommentGUID]) +); +GO +ALTER TABLE [dbo].[FEComment] ADD CONSTRAINT [FK_FEComment_XPlan] FOREIGN KEY ([EntityGUID]) REFERENCES [dbo].[XPlan] ([PlanGUID]); GO +ALTER TABLE [dbo].[FEComment] ADD CONSTRAINT [DF_Table_1_EntityGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGUID]; GO +ALTER TABLE [dbo].[FEComment] ADD CONSTRAINT [DF_FEComment_FormFieldGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormFieldGUID]; GO +ALTER TABLE [dbo].[FEComment] ADD CONSTRAINT [DF_FEComment_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[FEComment] ADD CONSTRAINT [DF_FEComment_CommentGUID] DEFAULT (newid()) FOR [CommentGUID]; GO +ALTER TABLE [dbo].[FEComment] ADD CONSTRAINT [DF_FEComment_UserNameFull] DEFAULT ('') FOR [UserNameFull]; GO +ALTER TABLE [dbo].[FEComment] ADD CONSTRAINT [DF_FEComment_Comment] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [dbo].[FEComment] ADD CONSTRAINT [DF_FEComment_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FEFormData ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FEFormData] ( + [FormDataGUID] uniqueidentifier NOT NULL, + [FormFieldGUID] uniqueidentifier NOT NULL, + [EntityGUID] uniqueidentifier NOT NULL, + [PlanTypeGUID] uniqueidentifier NOT NULL, + [ValueVarChar] nvarchar(max) NOT NULL, + [ValueSearch] nvarchar(max) NULL, + [ValueGUID] uniqueidentifier NOT NULL, + [ValueGUIDS] nvarchar(max) NOT NULL, + [ValueFloat] float NOT NULL, + [ValueDate] datetime NOT NULL, + [ValueBit] bit NOT NULL, + PRIMARY KEY ([FormDataGUID]) +); + +CREATE CLUSTERED INDEX [IX_FEFormData_FF_E_Cluster] ON [dbo].[FEFormData] ([PlanTypeGUID], [FormFieldGUID], [EntityGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_FEFormData] ON [dbo].[FEFormData] ([EntityGUID], [FormFieldGUID]); +GO +ALTER TABLE [dbo].[FEFormData] ADD CONSTRAINT [FK_FEFormData_FEFormField] FOREIGN KEY ([FormFieldGUID]) REFERENCES [dbo].[FEFormField] ([FORMFIELDGUID]); GO +ALTER TABLE [dbo].[FEFormData] ADD CONSTRAINT [DF_FEFormData_FORMDATAGUID] DEFAULT (newid()) FOR [FormDataGUID]; GO +ALTER TABLE [dbo].[FEFormData] ADD CONSTRAINT [DF_FEFormData_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO +ALTER TABLE [dbo].[FEFormData] ADD CONSTRAINT [DF_FEFormData_VALUEVARCHAR] DEFAULT ('') FOR [ValueVarChar]; GO +ALTER TABLE [dbo].[FEFormData] ADD CONSTRAINT [DF_FEFormData_VALUEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ValueGUID]; GO +ALTER TABLE [dbo].[FEFormData] ADD CONSTRAINT [DF_FEFormData_VALUEGUIDS] DEFAULT ('') FOR [ValueGUIDS]; GO +ALTER TABLE [dbo].[FEFormData] ADD CONSTRAINT [DF_FEFormData_VALUEFLOAT] DEFAULT ((0)) FOR [ValueFloat]; GO +ALTER TABLE [dbo].[FEFormData] ADD CONSTRAINT [DF_FEFormData_VALUEDATE] DEFAULT (((1)/(1))/(1980)) FOR [ValueDate]; GO +ALTER TABLE [dbo].[FEFormData] ADD CONSTRAINT [DF_FEFormData_VALUEBIT] DEFAULT ((0)) FOR [ValueBit]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FEFormDataHistory ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FEFormDataHistory] ( + [RowID] int NOT NULL, + [EntityGUID] uniqueidentifier NOT NULL, + [EntityName] nvarchar(max) NOT NULL, + [FormFieldGUID] uniqueidentifier NOT NULL, + [FormFieldName] nvarchar(64) NOT NULL, + [ValueVarChar] nvarchar(max) NOT NULL, + [ValueGUID] uniqueidentifier NOT NULL, + [ValueGUIDS] nvarchar(max) NOT NULL, + [ValueFloat] float NOT NULL, + [ValueDate] datetime NOT NULL, + [ValueBit] bit NOT NULL, + [DateTimeStamp] datetime NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [dbo].[FEFormDataHistory] ADD CONSTRAINT [DF_FEFormDataHistory_FormDataGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGUID]; GO +ALTER TABLE [dbo].[FEFormDataHistory] ADD CONSTRAINT [DF_FEFormDataHistory_EntityName] DEFAULT ('') FOR [EntityName]; GO +ALTER TABLE [dbo].[FEFormDataHistory] ADD CONSTRAINT [DF_FEFormDataHistory_VALUEVARCHAR] DEFAULT ('') FOR [ValueVarChar]; GO +ALTER TABLE [dbo].[FEFormDataHistory] ADD CONSTRAINT [DF_FEFormDataHistory_VALUEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ValueGUID]; GO +ALTER TABLE [dbo].[FEFormDataHistory] ADD CONSTRAINT [DF_FEFormDataHistory_VALUEGUIDS] DEFAULT ('') FOR [ValueGUIDS]; GO +ALTER TABLE [dbo].[FEFormDataHistory] ADD CONSTRAINT [DF_FEFormDataHistory_VALUEFLOAT] DEFAULT ((0)) FOR [ValueFloat]; GO +ALTER TABLE [dbo].[FEFormDataHistory] ADD CONSTRAINT [DF_FEFormDataHistory_VALUEDATE] DEFAULT (((1)/(1))/(1980)) FOR [ValueDate]; GO +ALTER TABLE [dbo].[FEFormDataHistory] ADD CONSTRAINT [DF_FEFormDataHistory_VALUEBIT] DEFAULT ((0)) FOR [ValueBit]; GO +ALTER TABLE [dbo].[FEFormDataHistory] ADD CONSTRAINT [DF_FEFormDataHistory_HistoryDateTime] DEFAULT (getdate()) FOR [DateTimeStamp]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FEFormDef ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FEFormDef] ( + [FORMDEFGUID] uniqueidentifier NOT NULL, + [RootFormSectionGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Alias] nvarchar(64) NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [ImageIndex] int NOT NULL, + [CustomMenuGUID] uniqueidentifier NOT NULL, + [CustomToolbarGUID] uniqueidentifier NOT NULL, + [StyleIndex] int NOT NULL, + [GlobalID] nvarchar(100) NOT NULL, + [PlanTypeGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([FORMDEFGUID]) +); +GO +ALTER TABLE [dbo].[FEFormDef] ADD CONSTRAINT [DF_FEFormDef_StyleIndex] DEFAULT ((0)) FOR [StyleIndex]; GO +ALTER TABLE [dbo].[FEFormDef] ADD CONSTRAINT [DF__FEFormDef__PlanT__759DB0BC] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO +ALTER TABLE [dbo].[FEFormDef] ADD CONSTRAINT [DF__FEFormDef__Globa__194C3D43] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [dbo].[FEFormDef] ADD CONSTRAINT [DF_FEFormDef_FORMDEFGUID] DEFAULT (newid()) FOR [FORMDEFGUID]; GO +ALTER TABLE [dbo].[FEFormDef] ADD CONSTRAINT [DF_FEFormDef_ROOTFORMSECTIONGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RootFormSectionGUID]; GO +ALTER TABLE [dbo].[FEFormDef] ADD CONSTRAINT [DF_FEFormDef_ALIAS] DEFAULT ('') FOR [Alias]; GO +ALTER TABLE [dbo].[FEFormDef] ADD CONSTRAINT [DF_FEFormDef_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[FEFormDef] ADD CONSTRAINT [DF_FEFormDef_IMAGEINDEX] DEFAULT ((0)) FOR [ImageIndex]; GO +ALTER TABLE [dbo].[FEFormDef] ADD CONSTRAINT [DF_FEFormDef_CUSTOMMENUGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CustomMenuGUID]; GO +ALTER TABLE [dbo].[FEFormDef] ADD CONSTRAINT [DF_FEFormDef_CUSTOMTOOLBARGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CustomToolbarGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FEFormField ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FEFormField] ( + [FORMFIELDGUID] uniqueidentifier NOT NULL, + [GlobalID] nvarchar(100) NOT NULL, + [Name] nvarchar(100) NOT NULL, + [FieldType] int NOT NULL, + [MaxLength] int NOT NULL, + [MinLength] int NOT NULL, + [DataFormat] nvarchar(256) NOT NULL, + [DefaultValue] nvarchar(1000) NOT NULL, + [HelpText] nvarchar(4000) NOT NULL, + [IsReadOnly] bit NOT NULL, + [HasNumericMaxValue] bit NOT NULL, + [NumericMaxValue] float NOT NULL, + [HasNumericMinValue] bit NOT NULL, + [NumericMinValue] float NOT NULL, + [StringMask] nvarchar(256) NOT NULL, + [DecimalPlaces] int NOT NULL, + [UseThousandsSeparator] bit NOT NULL, + [UseNegParentheses] bit NOT NULL, + [HasLabel] bit NOT NULL, + [LabelDisplayType] int NOT NULL, + [LabelWidth] int NOT NULL, + [IsInDirectory] bit NOT NULL, + [SourceType] int NOT NULL, + [SourcePath] nvarchar(max) NOT NULL, + [SourceGUID] uniqueidentifier NOT NULL, + [Rows] int NOT NULL, + [UsePicker] bit NOT NULL, + [DefaultSortOrder] bit NOT NULL, + [IsRequired] bit NOT NULL, + [Mask] nvarchar(256) NOT NULL, + [HelpTextDisplayType] int NOT NULL, + [HasOptionHelpText] bit NOT NULL, + [DefaultValueType] int NOT NULL, + [Label] nvarchar(450) NOT NULL, + [HasRowNumbers] bit NOT NULL, + [FolderGUID] uniqueidentifier NOT NULL, + [SpecialFieldType] int NOT NULL, + [SourceDisplayFormat] nvarchar(450) NOT NULL, + [ExecutionOrder] int NOT NULL, + [DirectoryName] nvarchar(64) NOT NULL, + [ScaleDisplayFactor] int NOT NULL, + [DateCreated] datetime NOT NULL, + [DateModified] datetime NOT NULL, + [IsRecordingHistory] bit NOT NULL, + [IsCleared] bit NOT NULL, + [DisplayFormatOverride] nvarchar(64) NOT NULL, + [ResizeOffset] int NOT NULL, + [IsSetupLocked] bit NOT NULL, + [IsCoolite] bit NOT NULL, + [IsCopied] bit NOT NULL, + [RenderType] int NOT NULL, + [RenderThreshold] float NOT NULL, + [RenderComparisonFieldGUID] uniqueidentifier NOT NULL, + [RenderComparisonOperator] int NOT NULL, + [RefreshMode] tinyint NOT NULL, + [TypeConfigXML] xml(max) NOT NULL, + PRIMARY KEY ([FORMFIELDGUID]) +); + +CREATE NONCLUSTERED INDEX [IX_FEFormField_1] ON [dbo].[FEFormField] ([SourceType]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_FEFormField] ON [dbo].[FEFormField] ([Name]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_FEFormField_GlobalID] ON [dbo].[FEFormField] ([GlobalID]); +GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_DATAFORMAT] DEFAULT ('') FOR [DataFormat]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_DEFAULTVALUE] DEFAULT ('') FOR [DefaultValue]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_HELPTEXT] DEFAULT ('') FOR [HelpText]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_ISREADONLY] DEFAULT ((0)) FOR [IsReadOnly]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_HASNUMERICMAXVALUE] DEFAULT ((0)) FOR [HasNumericMaxValue]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_NUMERICMAXVALUE] DEFAULT ((0)) FOR [NumericMaxValue]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_HASNUMERICMINVALUE] DEFAULT ((0)) FOR [HasNumericMinValue]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_NUMERICMINVALUE] DEFAULT ((0)) FOR [NumericMinValue]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_STRINGMASK] DEFAULT ('') FOR [StringMask]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_DECIMALPLACES] DEFAULT ((0)) FOR [DecimalPlaces]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_USETHOUSANDSSEPARATOR] DEFAULT ((1)) FOR [UseThousandsSeparator]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_USENEGPARENTHESE] DEFAULT ((0)) FOR [UseNegParentheses]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_HASLABEL] DEFAULT ((1)) FOR [HasLabel]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_LABELDISPLAYTYPE] DEFAULT ((0)) FOR [LabelDisplayType]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_RefreshMode] DEFAULT ((0)) FOR [RefreshMode]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_LABELWIDTH] DEFAULT ((100)) FOR [LabelWidth]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_LABEL] DEFAULT ('') FOR [Label]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_ISINDIRECTORY] DEFAULT ((0)) FOR [IsInDirectory]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_SOURCETYPE] DEFAULT ((0)) FOR [SourceType]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_SOURCEPATH] DEFAULT ('') FOR [SourcePath]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_SOURCEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SourceGUID]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_ROWS] DEFAULT ((0)) FOR [Rows]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_USEPICKER] DEFAULT ((0)) FOR [UsePicker]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_DEFAULTSORTORDER] DEFAULT ((0)) FOR [DefaultSortOrder]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_ISREQUIRED] DEFAULT ((0)) FOR [IsRequired]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_MASK] DEFAULT ('') FOR [Mask]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_HELPTEXTDISPLAYTYPE] DEFAULT ((0)) FOR [HelpTextDisplayType]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_HASOPTIONHELPTEXT] DEFAULT ((0)) FOR [HasOptionHelpText]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_DEFAULTVALUETYPE] DEFAULT ((0)) FOR [DefaultValueType]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_HASROWNUMBERS] DEFAULT ((1)) FOR [HasRowNumbers]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_FOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_SPECIALFIELDTYPE] DEFAULT ((0)) FOR [SpecialFieldType]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_SOURCEDISPLAYFORMAT] DEFAULT ('') FOR [SourceDisplayFormat]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_EXECUTIONORDER] DEFAULT ((0)) FOR [ExecutionOrder]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_DirectoryName] DEFAULT ('') FOR [DirectoryName]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_ScaleDisplayFactor] DEFAULT ((1)) FOR [ScaleDisplayFactor]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_DateCreated] DEFAULT (getdate()) FOR [DateCreated]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_DateModified] DEFAULT (getdate()) FOR [DateModified]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF__FEFormFie__IsRec__4AC6670E] DEFAULT ((0)) FOR [IsRecordingHistory]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_IsCleared] DEFAULT ((0)) FOR [IsCleared]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_DisplayFormatOverride] DEFAULT ('') FOR [DisplayFormatOverride]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_ResizeOffset] DEFAULT ((0)) FOR [ResizeOffset]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_IsSetupLocked] DEFAULT ((0)) FOR [IsSetupLocked]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_IsCoolite] DEFAULT ((0)) FOR [IsCoolite]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_RenderType] DEFAULT ((0)) FOR [RenderType]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_RenderThreshold] DEFAULT ((0)) FOR [RenderThreshold]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_RenderComparisonFieldGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RenderComparisonFieldGUID]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_RenderComparisonOperator] DEFAULT ((0)) FOR [RenderComparisonOperator]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_IsCopied] DEFAULT ((1)) FOR [IsCopied]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_TypeConfigXML] DEFAULT ('') FOR [TypeConfigXML]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_FORMFIELDGUID] DEFAULT (newid()) FOR [FORMFIELDGUID]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_FIELDTYPE] DEFAULT ((0)) FOR [FieldType]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FormField_MAXLENGTH] DEFAULT ((0)) FOR [MaxLength]; GO +ALTER TABLE [dbo].[FEFormField] ADD CONSTRAINT [DF_FEFormField_MINLENGTH] DEFAULT ((0)) FOR [MinLength]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FEFormFieldCalculationTestResult ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FEFormFieldCalculationTestResult] ( + [FormFieldGUID] uniqueidentifier NOT NULL, + [PlanTypeGUID] uniqueidentifier NOT NULL, + [IsSuccess] bit NOT NULL, + [Duration] int NOT NULL, + [RunDate] datetime NOT NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FEFormFieldDefaultOverride ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FEFormFieldDefaultOverride] ( + [DefaultOverrideGUID] uniqueidentifier NOT NULL, + [FormFieldGUID] uniqueidentifier NOT NULL, + [FormDefGUID] uniqueidentifier NOT NULL, + [DefaultValueType] int NOT NULL, + [DefaultValue] nvarchar(1000) NOT NULL, + [DisplayValue] nvarchar(450) NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([DefaultOverrideGUID]) +); +GO +ALTER TABLE [dbo].[FEFormFieldDefaultOverride] ADD CONSTRAINT [FK_FEFormFieldDefaultOverride_FEFormDef] FOREIGN KEY ([FormDefGUID]) REFERENCES [dbo].[FEFormDef] ([FORMDEFGUID]); GO +ALTER TABLE [dbo].[FEFormFieldDefaultOverride] ADD CONSTRAINT [FK_FEFormFieldDefaultOverride_FEFormField] FOREIGN KEY ([FormFieldGUID]) REFERENCES [dbo].[FEFormField] ([FORMFIELDGUID]); GO +ALTER TABLE [dbo].[FEFormFieldDefaultOverride] ADD CONSTRAINT [DF_FEFormFieldDefaultOverride_DefaultOverrideGUID] DEFAULT (newid()) FOR [DefaultOverrideGUID]; GO +ALTER TABLE [dbo].[FEFormFieldDefaultOverride] ADD CONSTRAINT [DF_FEFormFieldDefaultOverride_DefaultValueType] DEFAULT ((0)) FOR [DefaultValueType]; GO +ALTER TABLE [dbo].[FEFormFieldDefaultOverride] ADD CONSTRAINT [DF_FEFormFieldDefaultOverride_DefaultValue] DEFAULT ('') FOR [DefaultValue]; GO +ALTER TABLE [dbo].[FEFormFieldDefaultOverride] ADD CONSTRAINT [DF_FEFormFieldDefaultOverride_DisplayValue] DEFAULT ('') FOR [DisplayValue]; GO +ALTER TABLE [dbo].[FEFormFieldDefaultOverride] ADD CONSTRAINT [DF_FEFormFieldDefaultOverride_FormDefGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormDefGUID]; GO +ALTER TABLE [dbo].[FEFormFieldDefaultOverride] ADD CONSTRAINT [DF_FEFormFieldDefaultOverride_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[FEFormFieldDefaultOverride] ADD CONSTRAINT [DF_FEFormFieldDefaultOverride_FormFieldGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormFieldGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FEFormFieldSetup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FEFormFieldSetup] ( + [FORMFIELDSETUPGUID] uniqueidentifier NOT NULL, + [FormFieldGUID] uniqueidentifier NOT NULL, + [FormDefGUID] uniqueidentifier NOT NULL, + [FormSectionGUID] uniqueidentifier NOT NULL, + [SetupUsePicker] bit NOT NULL, + [SetupDecimalPlaces] int NOT NULL, + [SetupUseThousandsSeparator] bit NOT NULL, + [SetupUseNegParentheses] bit NOT NULL, + [SetupHasLabel] bit NOT NULL, + [SetupLabelDisplayType] int NOT NULL, + [SetupRows] int NOT NULL, + [SetupIsReadOnly] bit NOT NULL, + [SetupLabelWidth] int NOT NULL, + [SetupHelpTextDisplayType] int NOT NULL, + [SetupHasOptionHelpText] bit NOT NULL, + [SetupHasRowNumbers] bit NOT NULL, + [SetupResizeOffset] int NOT NULL, + PRIMARY KEY ([FORMFIELDSETUPGUID]) +); + +CREATE CLUSTERED INDEX [IX_FEFormFieldSetup_FormDef] ON [dbo].[FEFormFieldSetup] ([FormDefGUID]); +CREATE NONCLUSTERED INDEX [IX_FEFormFieldSetup_FormField] ON [dbo].[FEFormFieldSetup] ([FormFieldGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_FEFormFieldSetup] ON [dbo].[FEFormFieldSetup] ([FormFieldGUID], [FormDefGUID]); +GO +ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [FK_FEFormFieldSetup_FEFormDef] FOREIGN KEY ([FormDefGUID]) REFERENCES [dbo].[FEFormDef] ([FORMDEFGUID]); GO +ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [FK_FEFormFieldSetup_FEFormField] FOREIGN KEY ([FormFieldGUID]) REFERENCES [dbo].[FEFormField] ([FORMFIELDGUID]); GO +ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_FORMFIELDSETUPGUID] DEFAULT (newid()) FOR [FORMFIELDSETUPGUID]; GO +ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_FORMFIELDGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [FormFieldGUID]; GO +ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_FORMGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [FormDefGUID]; GO +ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_FormFieldSectionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormSectionGUID]; GO +ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_USEPICKER] DEFAULT ((0)) FOR [SetupUsePicker]; GO +ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_DECIMALPLACES] DEFAULT ((0)) FOR [SetupDecimalPlaces]; GO +ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_USETHOUSANDSSEPARATOR] DEFAULT ((1)) FOR [SetupUseThousandsSeparator]; GO +ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_USENEGPARENTHESES] DEFAULT ((0)) FOR [SetupUseNegParentheses]; GO +ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_HASLABEL] DEFAULT ((1)) FOR [SetupHasLabel]; GO +ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_LABELDISPLAYTYPE] DEFAULT ((0)) FOR [SetupLabelDisplayType]; GO +ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_ROWS] DEFAULT ((0)) FOR [SetupRows]; GO +ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_ISREADONLY] DEFAULT ((0)) FOR [SetupIsReadOnly]; GO +ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_SETUPLABELWIDTH] DEFAULT ((100)) FOR [SetupLabelWidth]; GO +ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_SETUPHELPTEXTDISPLAYTYPE] DEFAULT ((0)) FOR [SetupHelpTextDisplayType]; GO +ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_SETUPHASOPTIONHELPTEXT] DEFAULT ((0)) FOR [SetupHasOptionHelpText]; GO +ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_SETUPHASROWNUMBERS] DEFAULT ((1)) FOR [SetupHasRowNumbers]; GO +ALTER TABLE [dbo].[FEFormFieldSetup] ADD CONSTRAINT [DF_FEFormFieldSetup_SetupResizeOffset] DEFAULT ((0)) FOR [SetupResizeOffset]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FEFormFieldSynonym ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FEFormFieldSynonym] ( + [SynonymGUID] uniqueidentifier NOT NULL, + [FormFieldGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + PRIMARY KEY ([SynonymGUID]) +); +GO +ALTER TABLE [dbo].[FEFormFieldSynonym] ADD CONSTRAINT [DF_FEFormFieldSynonym_FormFieldGUID_1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormFieldGUID]; GO +ALTER TABLE [dbo].[FEFormFieldSynonym] ADD CONSTRAINT [DF_FEFormFieldSynonym_SynonymGUID_1] DEFAULT (newid()) FOR [SynonymGUID]; GO +ALTER TABLE [dbo].[FEFormFieldSynonym] ADD CONSTRAINT [DF_FEFormFieldSynonym_Name] DEFAULT ('') FOR [Name]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FEFormSection ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FEFormSection] ( + [FORMSECTIONGUID] uniqueidentifier NOT NULL, + [FormDefGUID] uniqueidentifier NOT NULL, + [ParentFormSectionGUID] uniqueidentifier NOT NULL, + [DisplayOrder] int NOT NULL, + [Name] nvarchar(64) NOT NULL, + [DisplayChildrenAsTabs] bit NOT NULL, + [Height] int NOT NULL, + [Width] int NOT NULL, + [HTML] nvarchar(max) NOT NULL, + [HTMLDesign] nvarchar(max) NOT NULL, + [IsParentSection] bit NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [RuleGroupType] int NOT NULL, + [IsBreakVisible] bit NOT NULL, + [IsAjaxEnabled] bit NOT NULL, + [GlobalID] nvarchar(100) NOT NULL, + [DisplayMode] int NOT NULL, + PRIMARY KEY ([FORMSECTIONGUID]) +); + +CREATE CLUSTERED INDEX [IX_FEFormSection] ON [dbo].[FEFormSection] ([FormDefGUID]); +CREATE NONCLUSTERED INDEX [IX_FEFormSection_DisplayOrder] ON [dbo].[FEFormSection] ([DisplayOrder]); +GO +ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [FK_FEFormSection_FEFormDef] FOREIGN KEY ([FormDefGUID]) REFERENCES [dbo].[FEFormDef] ([FORMDEFGUID]); GO +ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_FORMSECTIONGUID] DEFAULT (newid()) FOR [FORMSECTIONGUID]; GO +ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_DISPLAYORDER] DEFAULT ((1)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_DisplayChildrenAsTabs] DEFAULT ((0)) FOR [DisplayChildrenAsTabs]; GO +ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_Height] DEFAULT ((0)) FOR [Height]; GO +ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_Width] DEFAULT ((0)) FOR [Width]; GO +ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_HTML] DEFAULT ('') FOR [HTML]; GO +ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_HTMLDesign] DEFAULT ('') FOR [HTMLDesign]; GO +ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_ISPARENTSECTION] DEFAULT ((0)) FOR [IsParentSection]; GO +ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF__FEFormSec__IsAja__18260A72] DEFAULT ((0)) FOR [IsAjaxEnabled]; GO +ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF__FEFormSec__Globa__1A40617C] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF__FEFormSec__Displ__1EBAFDD6] DEFAULT ((0)) FOR [DisplayMode]; GO +ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_IsBreakVisible] DEFAULT ((1)) FOR [IsBreakVisible]; GO +ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_RuleGroupType] DEFAULT ((0)) FOR [RuleGroupType]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FEFormSectionRule ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FEFormSectionRule] ( + [FormSectionRuleGUID] uniqueidentifier NOT NULL, + [FormSectionGUID] uniqueidentifier NOT NULL, + [RuleXML] xml(max) NOT NULL, + [Description] nvarchar(max) NOT NULL, + [RuleType] int NOT NULL, + PRIMARY KEY ([FormSectionRuleGUID]) +); +GO +ALTER TABLE [dbo].[FEFormSectionRule] ADD CONSTRAINT [FK_FEFormSectionRule_FEFormSection] FOREIGN KEY ([FormSectionGUID]) REFERENCES [dbo].[FEFormSection] ([FORMSECTIONGUID]); GO +ALTER TABLE [dbo].[FEFormSectionRule] ADD CONSTRAINT [DF_FEFormSectionRule_FormSectionRuleGUID] DEFAULT (newid()) FOR [FormSectionRuleGUID]; GO +ALTER TABLE [dbo].[FEFormSectionRule] ADD CONSTRAINT [DF_FEFormSectionRule_FormSectionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormSectionGUID]; GO +ALTER TABLE [dbo].[FEFormSectionRule] ADD CONSTRAINT [DF_FEFormSectionRule_RuleXML] DEFAULT ('') FOR [RuleXML]; GO +ALTER TABLE [dbo].[FEFormSectionRule] ADD CONSTRAINT [DF_FEFormSectionRule_Description] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[FEFormSectionRule] ADD CONSTRAINT [DF_FEFormSectionRule_RuleType] DEFAULT ((0)) FOR [RuleType]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FEFormTemplateArea ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FEFormTemplateArea] ( + [FormTemplateAreaGUID] uniqueidentifier NOT NULL, + [HTML] nvarchar(max) NOT NULL, + [AreaType] int NOT NULL, + PRIMARY KEY ([FormTemplateAreaGUID]) +); +GO +ALTER TABLE [dbo].[FEFormTemplateArea] ADD CONSTRAINT [DF_FormTemplateArea_FormTemplateAreaGUID] DEFAULT (newid()) FOR [FormTemplateAreaGUID]; GO +ALTER TABLE [dbo].[FEFormTemplateArea] ADD CONSTRAINT [DF_FormTemplateArea_HTML] DEFAULT ('') FOR [HTML]; GO +ALTER TABLE [dbo].[FEFormTemplateArea] ADD CONSTRAINT [DF_FormTemplateArea_AreaType] DEFAULT ((0)) FOR [AreaType]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FRDimension ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FRDimension] ( + [FWDimensionGUID] uniqueidentifier NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(200) NOT NULL, + PRIMARY KEY ([FWDimensionGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_FRDimension_Name] ON [dbo].[FRDimension] ([Name]); +GO +ALTER TABLE [dbo].[FRDimension] ADD CONSTRAINT [FK_FRDimension_ScoreDimension] FOREIGN KEY ([DimensionGUID]) REFERENCES [dbo].[ScoreDimension] ([DimensionGUID]); GO +ALTER TABLE [dbo].[FRDimension] ADD CONSTRAINT [DF__FRDimensi__FWDim__2703FAD9] DEFAULT (newid()) FOR [FWDimensionGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FRFinancialStatement ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FRFinancialStatement] ( + [FinancialStatementGUID] uniqueidentifier NOT NULL, + [FWDimensionGUID] uniqueidentifier NOT NULL, + [Statement] nvarchar(200) NOT NULL, + [TemplateName] nvarchar(200) NOT NULL, + [ColumnFirstYear] nvarchar(200) NOT NULL, + [ColumnLastYear] nvarchar(200) NOT NULL, + [ColumnDisplayName] nvarchar(200) NOT NULL, + [ColumnFinancialReporting] nvarchar(200) NOT NULL, + [ColumnDataStructure] nvarchar(200) NOT NULL, + [ColumnReportingMappingType] nvarchar(200) NOT NULL, + [RowStartLabel] nvarchar(200) NOT NULL, + [RowEndLabel] nvarchar(200) NOT NULL, + [FinancialStatementSheet] nvarchar(200) NOT NULL, + [CompositeGUID] uniqueidentifier NOT NULL, + [ColumnAccountRollupLabel] nvarchar(200) NOT NULL, + [SampleViewName] nvarchar(200) NOT NULL, + [IsReportable] bit NOT NULL, + [TemplateGUID] uniqueidentifier NOT NULL, + [PlanTypeGUID] uniqueidentifier NOT NULL, + [SortOrder] int NOT NULL, + PRIMARY KEY ([FinancialStatementGUID]) +); +GO +ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Finan__3A16CF4D] DEFAULT (newid()) FOR [FinancialStatementGUID]; GO +ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Templ__3B0AF386] DEFAULT ('') FOR [TemplateName]; GO +ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Colum__3BFF17BF] DEFAULT ('') FOR [ColumnFirstYear]; GO +ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Colum__3CF33BF8] DEFAULT ('') FOR [ColumnLastYear]; GO +ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Colum__3DE76031] DEFAULT ('') FOR [ColumnDisplayName]; GO +ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Colum__3EDB846A] DEFAULT ('') FOR [ColumnFinancialReporting]; GO +ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Colum__3FCFA8A3] DEFAULT ('') FOR [ColumnDataStructure]; GO +ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Colum__40C3CCDC] DEFAULT ('') FOR [ColumnReportingMappingType]; GO +ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__RowSt__41B7F115] DEFAULT ('') FOR [RowStartLabel]; GO +ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__RowEn__42AC154E] DEFAULT ('') FOR [RowEndLabel]; GO +ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF_FRFinancialStatement_TemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TemplateGUID]; GO +ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Finan__43A03987] DEFAULT ('') FOR [FinancialStatementSheet]; GO +ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Compo__467CA632] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CompositeGUID]; GO +ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF_FRFinancialStatement_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO +ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__Colum__602834F3] DEFAULT ('') FOR [ColumnAccountRollupLabel]; GO +ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF_FRFinancialStatement_SampleViewName] DEFAULT ('') FOR [SampleViewName]; GO +ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF_FRFinancialStatement_IsReportable] DEFAULT ((1)) FOR [IsReportable]; GO +ALTER TABLE [dbo].[FRFinancialStatement] ADD CONSTRAINT [DF__FRFinanci__SortO__77FFBE84] DEFAULT ((0)) FOR [SortOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FRLineItem ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FRLineItem] ( + [LineItemGUID] uniqueidentifier NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [FWDimensionGUID] uniqueidentifier NOT NULL, + [SectionGUID] uniqueidentifier NOT NULL, + [LineName] nvarchar(200) NOT NULL, + [Name] nvarchar(200) NOT NULL, + [IsBold] bit NOT NULL, + [Indent] int NOT NULL, + [IsSpaceAbove] bit NOT NULL, + [Type] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [Calculation] nvarchar(2000) NOT NULL, + [Statement] nvarchar(200) NOT NULL, + [SectionName] nvarchar(200) NOT NULL, + [SortOrder] int NOT NULL, + [Format] int NOT NULL, + [IsSR] bit NOT NULL, + [IsYearOverYear] bit NOT NULL, + [IsBalanceSheetOnly] bit NOT NULL, + [IsRequired] bit NOT NULL, + [IsVolume] bit NOT NULL, + [IsEditable] bit NOT NULL, + [IsBottomBorder] bit NOT NULL, + [IsFTERollup] bit NOT NULL, + [IsExpense] bit NOT NULL, + [DecimalCount] tinyint NOT NULL, + [GlobalID] nvarchar(100) NOT NULL, + [IsDragAndDropAllowed] bit NOT NULL, + [IsDeletable] bit NOT NULL, + [IsConfigurable] bit NOT NULL, + [ToBeDeleted] bit NOT NULL, + PRIMARY KEY ([LineItemGUID]) +); +GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsVol__0C06B731] DEFAULT ((0)) FOR [IsVolume]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsEdi__0CFADB6A] DEFAULT ((1)) FOR [IsEditable]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsCon__1C113521] DEFAULT ((1)) FOR [IsConfigurable]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsExp__225AAF0D] DEFAULT ((0)) FOR [IsExpense]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__ToBeD__239FAA55] DEFAULT ((0)) FOR [ToBeDeleted]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsFTE__2E46C09C] DEFAULT ((0)) FOR [IsFTERollup]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__LineI__3181894C] DEFAULT (newid()) FOR [LineItemGUID]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__Secti__3275AD85] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0),0),0)) FOR [SectionGUID]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsBol__3369D1BE] DEFAULT ((0)) FOR [IsBold]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__Inden__345DF5F7] DEFAULT ((1)) FOR [Indent]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsSpa__35521A30] DEFAULT ((0)) FOR [IsSpaceAbove]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineItem__Type__36463E69] DEFAULT ((0)) FOR [Type]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__Calcu__373A62A2] DEFAULT ('') FOR [Calculation]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__Decim__43718A15] DEFAULT ((0)) FOR [DecimalCount]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsDra__51392A77] DEFAULT ((1)) FOR [IsDragAndDropAllowed]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsDel__522D4EB0] DEFAULT ((1)) FOR [IsDeletable]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF_FRLineItem_GlobalID] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineItem__IsSR__62107D65] DEFAULT ((0)) FOR [IsSR]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsYea__63F8C5D7] DEFAULT ((0)) FOR [IsYearOverYear]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsBal__64ECEA10] DEFAULT ((0)) FOR [IsBalanceSheetOnly]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsReq__65E10E49] DEFAULT ((0)) FOR [IsRequired]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF__FRLineIte__IsBot__6DA22BA2] DEFAULT ((0)) FOR [IsBottomBorder]; GO +ALTER TABLE [dbo].[FRLineItem] ADD CONSTRAINT [DF_FRLineItem_Format] DEFAULT ((2)) FOR [Format]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FRSection ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FRSection] ( + [SectionGUID] uniqueidentifier NOT NULL, + [FWDimensionGUID] uniqueidentifier NOT NULL, + [Statement] nvarchar(200) NOT NULL, + [Name] nvarchar(200) NOT NULL, + [IsBold] bit NOT NULL, + [Indent] int NOT NULL, + [IsSpaceAbove] bit NOT NULL, + [IsVisible] bit NOT NULL, + [IsEditable] bit NOT NULL, + [IsRequired] bit NOT NULL, + [GlobalID] nvarchar(100) NOT NULL, + [IsDragAndDropAllowed] bit NOT NULL, + [IsDeletable] bit NOT NULL, + [IsConfigurable] bit NOT NULL, + [ToBeDeleted] bit NOT NULL, + PRIMARY KEY ([SectionGUID]) +); +GO +ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__IsEdi__0DEEFFA3] DEFAULT ((1)) FOR [IsEditable]; GO +ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__IsReq__0EE323DC] DEFAULT ((0)) FOR [IsRequired]; GO +ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__IsCon__1D05595A] DEFAULT ((1)) FOR [IsConfigurable]; GO +ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__ToBeD__22AB861C] DEFAULT ((0)) FOR [ToBeDeleted]; GO +ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__Secti__2AD48BBD] DEFAULT (newid()) FOR [SectionGUID]; GO +ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__IsBol__2BC8AFF6] DEFAULT ((1)) FOR [IsBold]; GO +ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__Inden__2CBCD42F] DEFAULT ((0)) FOR [Indent]; GO +ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__IsSpa__2DB0F868] DEFAULT ((1)) FOR [IsSpaceAbove]; GO +ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__IsVis__2EA51CA1] DEFAULT ((1)) FOR [IsVisible]; GO +ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__IsDra__54159722] DEFAULT ((1)) FOR [IsDragAndDropAllowed]; GO +ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__IsDel__5509BB5B] DEFAULT ((1)) FOR [IsDeletable]; GO +ALTER TABLE [dbo].[FRSection] ADD CONSTRAINT [DF__FRSection__Globa__576B33C5] DEFAULT ('') FOR [GlobalID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FRStatementFormula ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FRStatementFormula] ( + [FinancialStatementGUID] uniqueidentifier NOT NULL, + [Column] nvarchar(5) NOT NULL, + [StandardFormula] nvarchar(max) NOT NULL, + [MappingFormula] nvarchar(max) NOT NULL, + [AlternateMappingFormula] nvarchar(max) NOT NULL, + [FormatOverride] int NOT NULL, + [UseStandardAlways] bit NOT NULL, + [DecimalCount] tinyint NOT NULL +); +GO +ALTER TABLE [dbo].[FRStatementFormula] ADD CONSTRAINT [DF__FRStateme__Colum__1EF36726] DEFAULT ('') FOR [Column]; GO +ALTER TABLE [dbo].[FRStatementFormula] ADD CONSTRAINT [DF__FRStateme__Stand__1FE78B5F] DEFAULT ('') FOR [StandardFormula]; GO +ALTER TABLE [dbo].[FRStatementFormula] ADD CONSTRAINT [DF__FRStateme__Mappi__20DBAF98] DEFAULT ('') FOR [MappingFormula]; GO +ALTER TABLE [dbo].[FRStatementFormula] ADD CONSTRAINT [DF__FRStateme__Alter__21CFD3D1] DEFAULT ('') FOR [AlternateMappingFormula]; GO +ALTER TABLE [dbo].[FRStatementFormula] ADD CONSTRAINT [DF__FRStateme__Forma__22C3F80A] DEFAULT ((-1)) FOR [FormatOverride]; GO +ALTER TABLE [dbo].[FRStatementFormula] ADD CONSTRAINT [DF__FRStateme__UseSt__2B0F2548] DEFAULT ((0)) FOR [UseStandardAlways]; GO +ALTER TABLE [dbo].[FRStatementFormula] ADD CONSTRAINT [DF__FRStateme__Decim__7469C72B] DEFAULT ((0)) FOR [DecimalCount]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FileAttachment ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FileAttachment] ( + [FileAttachmentGUID] uniqueidentifier NOT NULL, + [EntityGUID] uniqueidentifier NOT NULL, + [EntityType] int NOT NULL, + [FileName] nvarchar(250) NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [NumBytes] float NOT NULL, + [FolderGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [DateCreated] datetime NOT NULL, + [LastSeenpath] nvarchar(4000) NOT NULL, + [IsHome] bit NOT NULL, + PRIMARY KEY ([FileAttachmentGUID]) +); + +CREATE CLUSTERED INDEX [IX_FileAttachment_ByPlanGUID] ON [dbo].[FileAttachment] ([EntityGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_FileAttachment_Unique] ON [dbo].[FileAttachment] ([EntityGUID], [FolderGUID], [FileName]); +GO +ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_FILEATTACHMENTGUID] DEFAULT (newid()) FOR [FileAttachmentGUID]; GO +ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_PLANGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGUID]; GO +ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_ENTITYTYPE] DEFAULT ((0)) FOR [EntityType]; GO +ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_FILENAME] DEFAULT ('') FOR [FileName]; GO +ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_NUMBYTES] DEFAULT ((0)) FOR [NumBytes]; GO +ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_FOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO +ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_DATECREATED] DEFAULT (getdate()) FOR [DateCreated]; GO +ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_LASTSEENPATH] DEFAULT ('') FOR [LastSeenpath]; GO +ALTER TABLE [dbo].[FileAttachment] ADD CONSTRAINT [DF_FileAttachment_IsHome] DEFAULT ((0)) FOR [IsHome]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FileAttachmentPublicLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FileAttachmentPublicLink] ( + [FileAttachmentPublicLinkGUID] uniqueidentifier NOT NULL, + [FileAttachmentGUID] uniqueidentifier NOT NULL, + [AuthorGuid] uniqueidentifier NOT NULL, + [Description] nvarchar(200) NOT NULL, + [DateCreated] datetime NOT NULL, + [Link] nvarchar(2000) NOT NULL, + PRIMARY KEY ([FileAttachmentPublicLinkGUID]) +); +GO +ALTER TABLE [dbo].[FileAttachmentPublicLink] ADD CONSTRAINT [FK__FileAttac__FileA__3AAA6746] FOREIGN KEY ([FileAttachmentGUID]) REFERENCES [dbo].[FileAttachment] ([FileAttachmentGUID]); GO +ALTER TABLE [dbo].[FileAttachmentPublicLink] ADD CONSTRAINT [DF__FileAttac__FileA__39B6430D] DEFAULT (newid()) FOR [FileAttachmentPublicLinkGUID]; GO +ALTER TABLE [dbo].[FileAttachmentPublicLink] ADD CONSTRAINT [DF__FileAttac__Autho__3B9E8B7F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGuid]; GO +ALTER TABLE [dbo].[FileAttachmentPublicLink] ADD CONSTRAINT [DF__FileAttac__Descr__3C92AFB8] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[FileAttachmentPublicLink] ADD CONSTRAINT [DF__FileAttac__DateC__3D86D3F1] DEFAULT (getdate()) FOR [DateCreated]; GO +ALTER TABLE [dbo].[FileAttachmentPublicLink] ADD CONSTRAINT [DF__FileAttach__Link__69304C05] DEFAULT ('') FOR [Link]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FileAttachmentPublicRequest ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FileAttachmentPublicRequest] ( + [FileAttachmentPublicRequestGUID] uniqueidentifier NOT NULL, + [FileAttachmentPublicLinkGUID] uniqueidentifier NOT NULL, + [IPAddress] nvarchar(100) NOT NULL, + [DateCreated] datetime NOT NULL, + PRIMARY KEY ([FileAttachmentPublicRequestGUID]) +); +GO +ALTER TABLE [dbo].[FileAttachmentPublicRequest] ADD CONSTRAINT [FK__FileAttac__FileA__415764D5] FOREIGN KEY ([FileAttachmentPublicLinkGUID]) REFERENCES [dbo].[FileAttachmentPublicLink] ([FileAttachmentPublicLinkGUID]); GO +ALTER TABLE [dbo].[FileAttachmentPublicRequest] ADD CONSTRAINT [DF__FileAttac__FileA__4063409C] DEFAULT (newid()) FOR [FileAttachmentPublicRequestGUID]; GO +ALTER TABLE [dbo].[FileAttachmentPublicRequest] ADD CONSTRAINT [DF__FileAttac__IPAdd__424B890E] DEFAULT ('') FOR [IPAddress]; GO +ALTER TABLE [dbo].[FileAttachmentPublicRequest] ADD CONSTRAINT [DF__FileAttac__DateC__433FAD47] DEFAULT (getdate()) FOR [DateCreated]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FileListener ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FileListener] ( + [FileListenerGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(450) NOT NULL, + [Description] nvarchar(450) NOT NULL, + [FileFilter] nvarchar(450) NOT NULL, + [ExecutionOrder] int NOT NULL, + [ActionGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([FileListenerGUID]) +); +GO +ALTER TABLE [dbo].[FileListener] ADD CONSTRAINT [DF_FileListener_ExecutionOrder] DEFAULT ((0)) FOR [ExecutionOrder]; GO +ALTER TABLE [dbo].[FileListener] ADD CONSTRAINT [DF_FileListener_ActionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ActionGUID]; GO +ALTER TABLE [dbo].[FileListener] ADD CONSTRAINT [DF_FileListener_FileListenerGUID] DEFAULT (newid()) FOR [FileListenerGUID]; GO +ALTER TABLE [dbo].[FileListener] ADD CONSTRAINT [DF_FileListener_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[FileListener] ADD CONSTRAINT [DF_FileListener_Description] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[FileListener] ADD CONSTRAINT [DF_FileListener_FileFilter] DEFAULT ('') FOR [FileFilter]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FillinMgmtUpdateHistory ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FillinMgmtUpdateHistory] ( + [MemberGUID] uniqueidentifier NOT NULL, + [FillinUpdateTypeID] int NOT NULL, + [Departments] nvarchar(max) NOT NULL, + [FillinMembers] nvarchar(max) NOT NULL, + [Status] nvarchar(50) NOT NULL, + [TimeStamp] datetime NOT NULL, + [HistoryTaskGUID] uniqueidentifier NOT NULL, + [OperationType] nvarchar(50) NOT NULL, + [Sections] nvarchar(max) NOT NULL, + PRIMARY KEY ([MemberGUID]) +); +GO +ALTER TABLE [dbo].[FillinMgmtUpdateHistory] ADD CONSTRAINT [DF_FillinMgmtUpdateHistory_Sections] DEFAULT ('') FOR [Sections]; GO +ALTER TABLE [dbo].[FillinMgmtUpdateHistory] ADD CONSTRAINT [DF__FillinMgm__Opera__3E43BDC5] DEFAULT ('') FOR [OperationType]; GO +ALTER TABLE [dbo].[FillinMgmtUpdateHistory] ADD CONSTRAINT [DF_FillinMgmtUpdateHistory_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [dbo].[FillinMgmtUpdateHistory] ADD CONSTRAINT [DF_FillinMgmtUpdateHistory_FillinUpdateTypeID] DEFAULT ((0)) FOR [FillinUpdateTypeID]; GO +ALTER TABLE [dbo].[FillinMgmtUpdateHistory] ADD CONSTRAINT [DF_FillinMgmtUpdateHistory_Departments] DEFAULT ('') FOR [Departments]; GO +ALTER TABLE [dbo].[FillinMgmtUpdateHistory] ADD CONSTRAINT [DF_FillinMgmtUpdateHistory_FillinMembers] DEFAULT ('') FOR [FillinMembers]; GO +ALTER TABLE [dbo].[FillinMgmtUpdateHistory] ADD CONSTRAINT [DF_FillinMgmtUpdateHistory_Status] DEFAULT ('') FOR [Status]; GO +ALTER TABLE [dbo].[FillinMgmtUpdateHistory] ADD CONSTRAINT [DF_FillinMgmtUpdateHistory_TimeStamp] DEFAULT (getdate()) FOR [TimeStamp]; GO +ALTER TABLE [dbo].[FillinMgmtUpdateHistory] ADD CONSTRAINT [DF_FillinMgmtUpdateHistory_HistoryTaskGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryTaskGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FillinMgmtUpdateType ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FillinMgmtUpdateType] ( + [MemberGUID] uniqueidentifier NOT NULL, + [FillinUpdateTypeID] int NOT NULL, + [FillinUpdateTypeName] nvarchar(50) NOT NULL, + PRIMARY KEY ([MemberGUID]) +); +GO +ALTER TABLE [dbo].[FillinMgmtUpdateType] ADD CONSTRAINT [DF_FillinMgmtUpdateType_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [dbo].[FillinMgmtUpdateType] ADD CONSTRAINT [DF_FillinMgmtUpdateType_FillinUpdateTypeID] DEFAULT ((0)) FOR [FillinUpdateTypeID]; GO +ALTER TABLE [dbo].[FillinMgmtUpdateType] ADD CONSTRAINT [DF_FillinMgmtUpdateType_FillinUpdateTypeName] DEFAULT ('') FOR [FillinUpdateTypeName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FillinRefreshRequest ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FillinRefreshRequest] ( + [RequestGUID] uniqueidentifier NOT NULL, + [PlanTypeGUID] uniqueidentifier NOT NULL, + [PlaceHolderSectionGUID] uniqueidentifier NOT NULL, + [ModelTemplateGUID] uniqueidentifier NOT NULL, + [IssuedAt] datetime NOT NULL, + [ErrorGUID] uniqueidentifier NOT NULL, + [PlanGUID] uniqueidentifier NOT NULL, + [AllowClearOnRefresh] bit NOT NULL, + PRIMARY KEY ([RequestGUID]) +); +GO +ALTER TABLE [dbo].[FillinRefreshRequest] ADD CONSTRAINT [DF_FillinRefreshRequest_RequestGUID] DEFAULT (newid()) FOR [RequestGUID]; GO +ALTER TABLE [dbo].[FillinRefreshRequest] ADD CONSTRAINT [DF_FillinRefreshRequest_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO +ALTER TABLE [dbo].[FillinRefreshRequest] ADD CONSTRAINT [DF_FillinRefreshRequest_PlaceHolderSectionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlaceHolderSectionGUID]; GO +ALTER TABLE [dbo].[FillinRefreshRequest] ADD CONSTRAINT [DF_FillinRefreshRequest_ModelTemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelTemplateGUID]; GO +ALTER TABLE [dbo].[FillinRefreshRequest] ADD CONSTRAINT [DF_FillinRefreshRequest_IssuedAt] DEFAULT (getdate()) FOR [IssuedAt]; GO +ALTER TABLE [dbo].[FillinRefreshRequest] ADD CONSTRAINT [DF_FillinRefreshRequest_AllowClearOnRefresh] DEFAULT ((1)) FOR [AllowClearOnRefresh]; GO +ALTER TABLE [dbo].[FillinRefreshRequest] ADD CONSTRAINT [DF__FillinRef__Error__29293EDB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ErrorGUID]; GO +ALTER TABLE [dbo].[FillinRefreshRequest] ADD CONSTRAINT [DF_FillinRefreshRequest_PlanGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.Folder ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[Folder] ( + [FolderGuid] uniqueidentifier NOT NULL, + [FolderSetGUID] uniqueidentifier NOT NULL, + [ParentFolderGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(450) NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [DateCreated] datetime NOT NULL, + [DateModified] datetime NOT NULL, + [OutlineLevel] int NOT NULL, + [DisplayOrder] int NOT NULL, + [ImageType] int NOT NULL, + [FolderType] int NOT NULL, + [QueryRootXML] nvarchar(max) NOT NULL, + [IsDeletedFolder] bit NOT NULL, + [BasedOnFolderGUID] uniqueidentifier NOT NULL, + [UpgradeHierarchyPath] nvarchar(max) NOT NULL, + [GlobalID] nvarchar(50) NOT NULL, + PRIMARY KEY ([FolderGuid]) +); + +CREATE CLUSTERED INDEX [IX_Folder_FolderSetGUID] ON [dbo].[Folder] ([FolderSetGUID]); +CREATE NONCLUSTERED INDEX [IX_Folder_ParentFolderGUID] ON [dbo].[Folder] ([ParentFolderGUID]); +GO +ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [FK_Folder_FolderSet] FOREIGN KEY ([FolderSetGUID]) REFERENCES [dbo].[FolderSet] ([FolderSetGUID]); GO +ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_UpgradeHierarchyPath] DEFAULT ('') FOR [UpgradeHierarchyPath]; GO +ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_GlobalID] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_FolderGUID] DEFAULT (newid()) FOR [FolderGuid]; GO +ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_FOLDERSETGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderSetGUID]; GO +ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_PARENTFOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentFolderGUID]; GO +ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_DATECREATED] DEFAULT (((1)/(1))/(2000)) FOR [DateCreated]; GO +ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_DATEMODIFIED] DEFAULT (((1)/(1))/(2000)) FOR [DateModified]; GO +ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_OUTLINELEVEL] DEFAULT ((0)) FOR [OutlineLevel]; GO +ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_DISPLAYORDER] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_IMAGEINDEX] DEFAULT ((0)) FOR [ImageType]; GO +ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_FOLDERTYPE] DEFAULT ((0)) FOR [FolderType]; GO +ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_QUERYROOTXML] DEFAULT ('') FOR [QueryRootXML]; GO +ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_ISDELETEDFOLDER] DEFAULT ((0)) FOR [IsDeletedFolder]; GO +ALTER TABLE [dbo].[Folder] ADD CONSTRAINT [DF_Folder_BASEDONFOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BasedOnFolderGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.FolderSet ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[FolderSet] ( + [FolderSetGUID] uniqueidentifier NOT NULL, + [RootFolderGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Type] int NOT NULL, + [OwnerGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([FolderSetGUID]) +); + +CREATE CLUSTERED INDEX [IX_FolderSet_Type] ON [dbo].[FolderSet] ([Type]); +GO +ALTER TABLE [dbo].[FolderSet] ADD CONSTRAINT [DF_FolderSet_FolderSetGUID] DEFAULT (newid()) FOR [FolderSetGUID]; GO +ALTER TABLE [dbo].[FolderSet] ADD CONSTRAINT [DF_FolderSet_ROOTFOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RootFolderGUID]; GO +ALTER TABLE [dbo].[FolderSet] ADD CONSTRAINT [DF_FolderSet_TYPE] DEFAULT ((0)) FOR [Type]; GO +ALTER TABLE [dbo].[FolderSet] ADD CONSTRAINT [DF_FolderSet_OWNERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OwnerGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.GUIDTable ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[GUIDTable] ( + [MemberGUID] uniqueidentifier NOT NULL, + [SPLongRangePlanID] int NOT NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.GlobalAssumption ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[GlobalAssumption] ( + [GlobalAssumptionGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [GlobalAssumptionSetGUID] uniqueidentifier NOT NULL, + [TimeClassID] tinyint NOT NULL, + [PlanFiltered] bit NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [DateCreated] datetime NOT NULL, + [LastRefresh] datetime NULL, + [Commentary] nvarchar(max) NOT NULL, + [NumberOfBudgetsInRule] int NULL, + PRIMARY KEY ([GlobalAssumptionGUID]) +); +GO +ALTER TABLE [dbo].[GlobalAssumption] ADD CONSTRAINT [FK_GlobalAssumption_GlobalAssumptionSet] FOREIGN KEY ([GlobalAssumptionSetGUID]) REFERENCES [dbo].[GlobalAssumptionSet] ([GlobalAssumptionSetGUID]); GO +ALTER TABLE [dbo].[GlobalAssumption] ADD CONSTRAINT [DF_GlobalAssumption_PlanFiltered] DEFAULT ((0)) FOR [PlanFiltered]; GO +ALTER TABLE [dbo].[GlobalAssumption] ADD CONSTRAINT [DF__GlobalAss__Comme__00939FA1] DEFAULT ('') FOR [Commentary]; GO +ALTER TABLE [dbo].[GlobalAssumption] ADD CONSTRAINT [DF_GlobalAssumption_AuthorGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [dbo].[GlobalAssumption] ADD CONSTRAINT [DF_GlobalAssumption_DateCreated] DEFAULT (getdate()) FOR [DateCreated]; GO +ALTER TABLE [dbo].[GlobalAssumption] ADD CONSTRAINT [DF_GlobalAssumption_NumberOfBudgetsInRule] DEFAULT (NULL) FOR [NumberOfBudgetsInRule]; GO +ALTER TABLE [dbo].[GlobalAssumption] ADD CONSTRAINT [DF_GlobalAssumption_GlobalAssumptionGUID] DEFAULT (newid()) FOR [GlobalAssumptionGUID]; GO +ALTER TABLE [dbo].[GlobalAssumption] ADD CONSTRAINT [DF_GlobalAssumption_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[GlobalAssumption] ADD CONSTRAINT [DF_GlobalAssumption_AssumptionSetGuid] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionSetGUID]; GO +ALTER TABLE [dbo].[GlobalAssumption] ADD CONSTRAINT [DF_GlobalAssumption_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.GlobalAssumptionFillinKeep ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[GlobalAssumptionFillinKeep] ( + [RowID] int NOT NULL, + [GlobalAssumptionSetGUID] uniqueidentifier NOT NULL, + [DepartmentalBudgetGUID] uniqueidentifier NOT NULL, + [DepartmentalBudgetID] int NOT NULL, + [FillinGUID] uniqueidentifier NOT NULL, + [FillinID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalMonthCode] nvarchar(20) NOT NULL, + [TimeClassID] tinyint NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [dbo].[GlobalAssumptionFillinKeep] ADD CONSTRAINT [DF_GlobalAssumptionFillinKeep_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionSetGUID]; GO +ALTER TABLE [dbo].[GlobalAssumptionFillinKeep] ADD CONSTRAINT [DF_GlobalAssumptionFillinKeep_DepartmentalBudgetGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DepartmentalBudgetGUID]; GO +ALTER TABLE [dbo].[GlobalAssumptionFillinKeep] ADD CONSTRAINT [DF_GlobalAssumptionFillinKeep_DepartmentalBudgetID] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO +ALTER TABLE [dbo].[GlobalAssumptionFillinKeep] ADD CONSTRAINT [DF_GlobalAssumptionFillinKeep_FillinGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FillinGUID]; GO +ALTER TABLE [dbo].[GlobalAssumptionFillinKeep] ADD CONSTRAINT [DF_GlobalAssumptionFillinKeep_FillinID] DEFAULT ((0)) FOR [FillinID]; GO +ALTER TABLE [dbo].[GlobalAssumptionFillinKeep] ADD CONSTRAINT [DF_GlobalAssumptionFillinKeep_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [dbo].[GlobalAssumptionFillinKeep] ADD CONSTRAINT [DF_GlobalAssumptionFillinKeep_FiscalMonthCode] DEFAULT ('0') FOR [FiscalMonthCode]; GO +ALTER TABLE [dbo].[GlobalAssumptionFillinKeep] ADD CONSTRAINT [DF_GlobalAssumptionFillinKeep_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.GlobalAssumptionHistoryEntry ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[GlobalAssumptionHistoryEntry] ( + [HistoryEntryGUID] uniqueidentifier NOT NULL, + [GlobalAssumptionGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [DateTimeStamp] datetime NULL, + [AffectedPlansCount] int NOT NULL, + PRIMARY KEY ([HistoryEntryGUID]) +); +GO +ALTER TABLE [dbo].[GlobalAssumptionHistoryEntry] ADD CONSTRAINT [FK_GlobalAssumptionHistory_GlobalAssumption] FOREIGN KEY ([GlobalAssumptionGUID]) REFERENCES [dbo].[GlobalAssumption] ([GlobalAssumptionGUID]); GO +ALTER TABLE [dbo].[GlobalAssumptionHistoryEntry] ADD CONSTRAINT [DF_GlobalAssumptionHistoryEntry_HistoryEntryGUID] DEFAULT (newid()) FOR [HistoryEntryGUID]; GO +ALTER TABLE [dbo].[GlobalAssumptionHistoryEntry] ADD CONSTRAINT [DF_GlobalAssumptionHistoryEntry_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionGUID]; GO +ALTER TABLE [dbo].[GlobalAssumptionHistoryEntry] ADD CONSTRAINT [DF_GlobalAssumptionHistoryEntry_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[GlobalAssumptionHistoryEntry] ADD CONSTRAINT [DF_GlobalAssumptionHistoryEntry_DateTimeStamp] DEFAULT (NULL) FOR [DateTimeStamp]; GO +ALTER TABLE [dbo].[GlobalAssumptionHistoryEntry] ADD CONSTRAINT [DF_GlobalAssumptionHistoryEntry_AffectedPlansCount] DEFAULT ((0)) FOR [AffectedPlansCount]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.GlobalAssumptionHistoryEntryItems ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[GlobalAssumptionHistoryEntryItems] ( + [HistoryItemGUID] uniqueidentifier NOT NULL, + [HistoryEntryGUID] uniqueidentifier NOT NULL, + [PlanGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([HistoryItemGUID]) +); +GO +ALTER TABLE [dbo].[GlobalAssumptionHistoryEntryItems] ADD CONSTRAINT [FK_GlobalAssumptionHistoryEntryItems_GlobalAssumptionHistoryEntry] FOREIGN KEY ([HistoryEntryGUID]) REFERENCES [dbo].[GlobalAssumptionHistoryEntry] ([HistoryEntryGUID]); GO +ALTER TABLE [dbo].[GlobalAssumptionHistoryEntryItems] ADD CONSTRAINT [DF_GlobalAssumptionHistoryEntryItems_HistoryItemGUID] DEFAULT (newid()) FOR [HistoryItemGUID]; GO +ALTER TABLE [dbo].[GlobalAssumptionHistoryEntryItems] ADD CONSTRAINT [DF_GlobalAssumptionHistoryEntryItems_HistoryEntryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryEntryGUID]; GO +ALTER TABLE [dbo].[GlobalAssumptionHistoryEntryItems] ADD CONSTRAINT [DF_GlobalAssumptionHistoryEntryItems_PlanGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.GlobalAssumptionPlanFilter ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[GlobalAssumptionPlanFilter] ( + [GlobalAssumptionPlanFilterGUID] uniqueidentifier NOT NULL, + [GlobalAssumptionGUID] uniqueidentifier NOT NULL, + [Value] nvarchar(256) NOT NULL, + PRIMARY KEY ([GlobalAssumptionPlanFilterGUID]) +); +GO +ALTER TABLE [dbo].[GlobalAssumptionPlanFilter] ADD CONSTRAINT [FK_GlobalAssumptionPlanFilter_GlobalAssumption] FOREIGN KEY ([GlobalAssumptionGUID]) REFERENCES [dbo].[GlobalAssumption] ([GlobalAssumptionGUID]); GO +ALTER TABLE [dbo].[GlobalAssumptionPlanFilter] ADD CONSTRAINT [DF_GlobalAssumptionPlanFilter_GlobalAssumptionPlanFilterGUID] DEFAULT (newid()) FOR [GlobalAssumptionPlanFilterGUID]; GO +ALTER TABLE [dbo].[GlobalAssumptionPlanFilter] ADD CONSTRAINT [DF_GlobalAssumptionPlanFilter_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionGUID]; GO +ALTER TABLE [dbo].[GlobalAssumptionPlanFilter] ADD CONSTRAINT [DF_GlobalAssumptionPlanFilter_Value] DEFAULT ('') FOR [Value]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.GlobalAssumptionSet ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[GlobalAssumptionSet] ( + [GlobalAssumptionSetGUID] uniqueidentifier NOT NULL, + [PlanTypeGUID] uniqueidentifier NOT NULL, + [PHSectionGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Type] tinyint NOT NULL, + [ModelDataTableName] nvarchar(50) NOT NULL, + [RollupAssumptionsTableName] nvarchar(50) NOT NULL, + [DetailAssumptionsTableName] nvarchar(50) NOT NULL, + [Dimensionality] nvarchar(max) NOT NULL, + [IsPercentage] bit NOT NULL, + [SortOrder] int NOT NULL, + PRIMARY KEY ([GlobalAssumptionSetGUID]) +); +GO +ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_SortOrder] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_GlobalAssumptionSetGUID] DEFAULT (newid()) FOR [GlobalAssumptionSetGUID]; GO +ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO +ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_PHSectionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PHSectionGUID]; GO +ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_Type] DEFAULT ((0)) FOR [Type]; GO +ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_BaseTableName] DEFAULT ('') FOR [ModelDataTableName]; GO +ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_GlobalAssumptionSetTableName] DEFAULT ('') FOR [RollupAssumptionsTableName]; GO +ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_DetailAssumptionsTableName] DEFAULT ('') FOR [DetailAssumptionsTableName]; GO +ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_Dimensionality] DEFAULT ('') FOR [Dimensionality]; GO +ALTER TABLE [dbo].[GlobalAssumptionSet] ADD CONSTRAINT [DF_GlobalAssumptionSet_IsPercentage] DEFAULT ((0)) FOR [IsPercentage]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.GridColumn ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[GridColumn] ( + [GridColumnGUID] uniqueidentifier NOT NULL, + [GridTemplateGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [AttributeGUID] uniqueidentifier NOT NULL, + [SpecialColumnName] nvarchar(100) NOT NULL, + [Width] int NOT NULL, + [DisplayOrder] int NOT NULL, + [IsFrozen] bit NOT NULL, + [SortIndex] int NOT NULL, + [SortOrder] tinyint NOT NULL, + [TotalIndex] int NOT NULL, + PRIMARY KEY ([GridColumnGUID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_AttributeGUID] ON [dbo].[GridColumn] ([AttributeGUID]); +CREATE NONCLUSTERED INDEX [NUNC_UserGUID] ON [dbo].[GridColumn] ([UserGUID]); +GO +ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [FK__GridColum__GridT__5963C6C6] FOREIGN KEY ([GridTemplateGUID]) REFERENCES [dbo].[GridTemplate] ([GRIDTEMPLATEGUID]); GO +ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [DF__GridColum__GridC__586FA28D] DEFAULT (newid()) FOR [GridColumnGUID]; GO +ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [DF__GridColum__UserG__5A57EAFF] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [DF__GridColum__Speci__5C403371] DEFAULT ('') FOR [SpecialColumnName]; GO +ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [DF__GridColum__Width__5D3457AA] DEFAULT ((150)) FOR [Width]; GO +ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [DF__GridColum__Displ__5E287BE3] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [DF__GridColum__IsFro__5F1CA01C] DEFAULT ((0)) FOR [IsFrozen]; GO +ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [DF__GridColum__SortI__6010C455] DEFAULT ((-1)) FOR [SortIndex]; GO +ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [DF__GridColum__SortO__6104E88E] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [DF__GridColum__Total__699A2E8F] DEFAULT ((-1)) FOR [TotalIndex]; GO +ALTER TABLE [dbo].[GridColumn] ADD CONSTRAINT [DF__GridColum__Attri__5B4C0F38] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AttributeGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.GridSetting ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[GridSetting] ( + [GRIDSETTINGGUID] uniqueidentifier NOT NULL, + [USERGUID] uniqueidentifier NOT NULL, + [COLUMNID] nvarchar(64) NOT NULL, + [WIDTH] float NOT NULL, + [DISPLAYORDER] int NOT NULL, + [ISFROZEN] bit NOT NULL, + [ISENABLED] bit NOT NULL, + [SORTINDEX] int NOT NULL, + [GRIDTEMPLATEGUID] uniqueidentifier NOT NULL, + [PLANTYPEGUID] uniqueidentifier NOT NULL, + [SORTORDER] int NOT NULL, + [ISAVAILABLE] bit NOT NULL, + [WorkspaceGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([GRIDSETTINGGUID]) +); + +CREATE CLUSTERED INDEX [IX_GridSetting_UserType] ON [dbo].[GridSetting] ([USERGUID], [PLANTYPEGUID]); +GO +ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_ISAVAILABLE] DEFAULT ((1)) FOR [ISAVAILABLE]; GO +ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_GRIDSETTINGGUID] DEFAULT (newid()) FOR [GRIDSETTINGGUID]; GO +ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [USERGUID]; GO +ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_COLUMNID] DEFAULT ('') FOR [COLUMNID]; GO +ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_WIDTH] DEFAULT ((100)) FOR [WIDTH]; GO +ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_WorkspaceGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkspaceGUID]; GO +ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_DISPLAYORDER] DEFAULT ((-1)) FOR [DISPLAYORDER]; GO +ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_FROZEN] DEFAULT ((0)) FOR [ISFROZEN]; GO +ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_ISENABLED] DEFAULT ((1)) FOR [ISENABLED]; GO +ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_SORTINDEX] DEFAULT ((-1)) FOR [SORTINDEX]; GO +ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_SORTDIRECTION] DEFAULT ((0)) FOR [SORTORDER]; GO +ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_GRIDTEMPLATEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GRIDTEMPLATEGUID]; GO +ALTER TABLE [dbo].[GridSetting] ADD CONSTRAINT [DF_GridSetting_PLANTYPEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PLANTYPEGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.GridTemplate ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[GridTemplate] ( + [GRIDTEMPLATEGUID] uniqueidentifier NOT NULL, + [NAME] nvarchar(64) NOT NULL, + [DESCRIPTION] nvarchar(450) NOT NULL, + [ISDEFAULT] bit NOT NULL, + [PlanTypeGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([GRIDTEMPLATEGUID]) +); +GO +ALTER TABLE [dbo].[GridTemplate] ADD CONSTRAINT [DF__GridTempl__PlanT__61F90CC7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO +ALTER TABLE [dbo].[GridTemplate] ADD CONSTRAINT [DF_GridTemplate_GRIDTEMPLATEGUID] DEFAULT (newid()) FOR [GRIDTEMPLATEGUID]; GO +ALTER TABLE [dbo].[GridTemplate] ADD CONSTRAINT [DF_GridTemplate_NAME] DEFAULT ('') FOR [NAME]; GO +ALTER TABLE [dbo].[GridTemplate] ADD CONSTRAINT [DF_GridTemplate_DESCRIPTION] DEFAULT ('') FOR [DESCRIPTION]; GO +ALTER TABLE [dbo].[GridTemplate] ADD CONSTRAINT [DF_GridTemplate_ISDEFAULT] DEFAULT ((0)) FOR [ISDEFAULT]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.GridTemplateFormFieldLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[GridTemplateFormFieldLink] ( + [GRIDTEMPLATEFORMFIELDLINKGUID] uniqueidentifier NOT NULL, + [GRIDTEMPLATEGUID] uniqueidentifier NOT NULL, + [FORMFIELDGUID] uniqueidentifier NOT NULL, + [DisplayOrder] int NOT NULL, + PRIMARY KEY ([GRIDTEMPLATEFORMFIELDLINKGUID]) +); +GO +ALTER TABLE [dbo].[GridTemplateFormFieldLink] ADD CONSTRAINT [FK_GridTemplateFormFieldLink_FEFormField] FOREIGN KEY ([FORMFIELDGUID]) REFERENCES [dbo].[FEFormField] ([FORMFIELDGUID]); GO +ALTER TABLE [dbo].[GridTemplateFormFieldLink] ADD CONSTRAINT [FK_GridTemplateFormFieldLink_GridTemplate] FOREIGN KEY ([GRIDTEMPLATEGUID]) REFERENCES [dbo].[GridTemplate] ([GRIDTEMPLATEGUID]); GO +ALTER TABLE [dbo].[GridTemplateFormFieldLink] ADD CONSTRAINT [DF__GridTempl__Displ__322DC4FD] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[GridTemplateFormFieldLink] ADD CONSTRAINT [DF_GridTemplateFormFieldLink_GRIDTEMPLATEFORMFIELDLINKGUID] DEFAULT (newid()) FOR [GRIDTEMPLATEFORMFIELDLINKGUID]; GO +ALTER TABLE [dbo].[GridTemplateFormFieldLink] ADD CONSTRAINT [DF_GridTemplateFormFieldLink_GRIDTEMPLATEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GRIDTEMPLATEGUID]; GO +ALTER TABLE [dbo].[GridTemplateFormFieldLink] ADD CONSTRAINT [DF_GridTemplateFormFieldLink_FORMFIELDGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FORMFIELDGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.GridTemplateUserLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[GridTemplateUserLink] ( + [UserGUID] uniqueidentifier NOT NULL, + [EntityViewGUID] uniqueidentifier NOT NULL, + [GridTemplateGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([UserGUID], [EntityViewGUID]) +); +GO +ALTER TABLE [dbo].[GridTemplateUserLink] ADD CONSTRAINT [FK__GridTempl__Entit__67B1E61D] FOREIGN KEY ([EntityViewGUID]) REFERENCES [dbo].[EntityView] ([ENTITYVIEWGUID]); GO +ALTER TABLE [dbo].[GridTemplateUserLink] ADD CONSTRAINT [FK__GridTempl__GridT__68A60A56] FOREIGN KEY ([GridTemplateGUID]) REFERENCES [dbo].[GridTemplate] ([GRIDTEMPLATEGUID]); GO +ALTER TABLE [dbo].[GridTemplateUserLink] ADD CONSTRAINT [FK__GridTempl__UserG__66BDC1E4] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.HangfireAuthenticationToken ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[HangfireAuthenticationToken] ( + [TokenGuid] uniqueidentifier NOT NULL, + [UserName] varchar(100) NOT NULL, + PRIMARY KEY ([TokenGuid]) +); +GO +ALTER TABLE [dbo].[HangfireAuthenticationToken] ADD CONSTRAINT [DF__HangfireA__Token__42F82853] DEFAULT (newid()) FOR [TokenGuid]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.HangfireJobQueueOverride ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[HangfireJobQueueOverride] ( + [TypeName] varchar(250) NOT NULL, + [MethodName] varchar(100) NOT NULL, + [QueueName] varchar(100) NOT NULL +); + +CREATE UNIQUE NONCLUSTERED INDEX [UC_HangfireJobQueueOverride_TypeName_MethodName] ON [dbo].[HangfireJobQueueOverride] ([TypeName], [MethodName]); +GO +ALTER TABLE [dbo].[HangfireJobQueueOverride] ADD CONSTRAINT [DF__HangfireJ__Queue__3F27976F] DEFAULT ('default') FOR [QueueName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.HistoryItem ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[HistoryItem] ( + [HISTORYITEMGUID] uniqueidentifier NOT NULL, + [OBJECTGUID] uniqueidentifier NOT NULL, + [OBJECTTYPE] nvarchar(256) NOT NULL, + [DATETIMESTAMP] datetime NOT NULL, + [MODIFIERUSERGUID] uniqueidentifier NOT NULL, + [CATEGORY] nvarchar(64) NOT NULL, + [DESCRIPTION] nvarchar(4000) NOT NULL, + [USERCOMMENTS] nvarchar(256) NOT NULL, + [METAXML] xml(max) NOT NULL, + [VERSION] timestamp NOT NULL, + [MODIFIERUSERNAME] nvarchar(256) NOT NULL, + [ITEMCOUNT] int NOT NULL, + [ELAPSEDMS] int NOT NULL, + [TransactionID] varchar(50) NULL, + [DATETIMESTAMPUTC] datetime NOT NULL, + PRIMARY KEY ([HISTORYITEMGUID]) +); + +CREATE NONCLUSTERED INDEX [IX_HistoryItem_DateTimeStamp] ON [dbo].[HistoryItem] ([DATETIMESTAMP], [VERSION]); +CREATE NONCLUSTERED INDEX [IDX_HistoryItem] ON [dbo].[HistoryItem] ([OBJECTGUID], [CATEGORY]); +CREATE NONCLUSTERED INDEX [IDX_HistoryItem_RunTime] ON [dbo].[HistoryItem] ([CATEGORY], [DATETIMESTAMP]) INCLUDE ([DESCRIPTION]); +GO +ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_ITEMCOUNT] DEFAULT ((0)) FOR [ITEMCOUNT]; GO +ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_HISTORYGUID] DEFAULT (newid()) FOR [HISTORYITEMGUID]; GO +ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_OBJECTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OBJECTGUID]; GO +ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_OBJECTTYPE] DEFAULT ('') FOR [OBJECTTYPE]; GO +ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_DATETIMESTAMP] DEFAULT (getdate()) FOR [DATETIMESTAMP]; GO +ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_MODIFIERUSERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MODIFIERUSERGUID]; GO +ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_CATEGORY] DEFAULT ('') FOR [CATEGORY]; GO +ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_DESCRIPTION] DEFAULT ('') FOR [DESCRIPTION]; GO +ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF__HistoryIt__DATET__43F43DF2] DEFAULT (getutcdate()) FOR [DATETIMESTAMPUTC]; GO +ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_USERCOMMENTS] DEFAULT ('') FOR [USERCOMMENTS]; GO +ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_MODIFIERUSERNAME] DEFAULT ('') FOR [MODIFIERUSERNAME]; GO +ALTER TABLE [dbo].[HistoryItem] ADD CONSTRAINT [DF_HistoryItem_ELAPSEDMS] DEFAULT ((0)) FOR [ELAPSEDMS]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.HistoryItemBlankFactTable ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[HistoryItemBlankFactTable] ( + [HistoryItemGUID] uniqueidentifier NOT NULL, + [SourceFilePath] nvarchar(256) NOT NULL, + [ModelDataConfigGUID] uniqueidentifier NOT NULL, + [CubeStubGUID] uniqueidentifier NOT NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.HistoryItemLine ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[HistoryItemLine] ( + [HistoryItemLineID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NULL, + [DateTimeStamp] datetime NOT NULL, + [SQLUser] nvarchar(128) NOT NULL, + [TableName] nvarchar(64) NOT NULL, + [RowID] int NULL, + [BeforeValues] nvarchar(max) NULL, + [AfterValues] nvarchar(max) NULL, + [DateTimeStampUtc] datetime NOT NULL, + PRIMARY KEY ([HistoryItemLineID]) +); +GO +ALTER TABLE [dbo].[HistoryItemLine] ADD CONSTRAINT [DF_HistoryItemLine_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO +ALTER TABLE [dbo].[HistoryItemLine] ADD CONSTRAINT [DF_HistoryItemLine_SQLUser] DEFAULT (suser_sname()) FOR [SQLUser]; GO +ALTER TABLE [dbo].[HistoryItemLine] ADD CONSTRAINT [DF__HistoryIt__DateT__44E8622B] DEFAULT (getutcdate()) FOR [DateTimeStampUtc]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.HistoryItemObject ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[HistoryItemObject] ( + [HistoryItemGUID] uniqueidentifier NOT NULL, + [ObjectGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([HistoryItemGUID], [ObjectGUID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IPAddressWhiteList ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IPAddressWhiteList] ( + [IPAddressRangeGUID] uniqueidentifier NOT NULL, + [IPAddressRangeStart] nvarchar(100) NOT NULL, + [IPAddressRangeEnd] nvarchar(100) NOT NULL, + PRIMARY KEY ([IPAddressRangeGUID]) +); +GO +ALTER TABLE [dbo].[IPAddressWhiteList] ADD CONSTRAINT [DF__IPAddress__IPAdd__2CD47697] DEFAULT (newid()) FOR [IPAddressRangeGUID]; GO +ALTER TABLE [dbo].[IPAddressWhiteList] ADD CONSTRAINT [DF__IPAddress__IPAdd__2DC89AD0] DEFAULT ('') FOR [IPAddressRangeStart]; GO +ALTER TABLE [dbo].[IPAddressWhiteList] ADD CONSTRAINT [DF__IPAddress__IPAdd__2EBCBF09] DEFAULT ('') FOR [IPAddressRangeEnd]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IRCChat ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IRCChat] ( + [IRCChatGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Description] varchar(802) NOT NULL, + [CreationTime] datetime NOT NULL, + [SQLTableName] nvarchar(128) NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [LastModifiedUserGUID] uniqueidentifier NOT NULL, + [RowID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [IsChatDeleted] bit NOT NULL, + PRIMARY KEY ([IRCChatGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [UQ__IRCChat__737584F6754087D1] ON [dbo].[IRCChat] ([Name]); +CREATE UNIQUE NONCLUSTERED INDEX [UQ__IRCChat__7CE2D9A872641B26] ON [dbo].[IRCChat] ([SQLTableName]); +GO +ALTER TABLE [dbo].[IRCChat] ADD CONSTRAINT [DF_IRCChat_AuthorGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [dbo].[IRCChat] ADD CONSTRAINT [DF__IRCChat__IRCChat__7728D043] DEFAULT (newid()) FOR [IRCChatGUID]; GO +ALTER TABLE [dbo].[IRCChat] ADD CONSTRAINT [DF__IRCChat__Name__781CF47C] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[IRCChat] ADD CONSTRAINT [DF__IRCChat__Descrip__791118B5] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[IRCChat] ADD CONSTRAINT [DF__IRCChat__Creatio__7A053CEE] DEFAULT (getdate()) FOR [CreationTime]; GO +ALTER TABLE [dbo].[IRCChat] ADD CONSTRAINT [DF_IRCChat_LastModifiedUserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LastModifiedUserGUID]; GO +ALTER TABLE [dbo].[IRCChat] ADD CONSTRAINT [DF__IRCChat__SQLTabl__7AF96127] DEFAULT ('') FOR [SQLTableName]; GO +ALTER TABLE [dbo].[IRCChat] ADD CONSTRAINT [DF_IRCChat_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [dbo].[IRCChat] ADD CONSTRAINT [DF_IRCChat_IsDeleted] DEFAULT ((0)) FOR [IsChatDeleted]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IRCChatMembership ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IRCChatMembership] ( + [UserGUID] uniqueidentifier NOT NULL, + [IRCChatGUID] uniqueidentifier NOT NULL, + [LastCheckinTime] datetime NOT NULL +); + +CREATE CLUSTERED INDEX [CLUSTERED_LASTCHECKINTIME] ON [dbo].[IRCChatMembership] ([LastCheckinTime]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_USERGUID_CHATGUID] ON [dbo].[IRCChatMembership] ([UserGUID], [IRCChatGUID]); +GO +ALTER TABLE [dbo].[IRCChatMembership] ADD CONSTRAINT [DF__IRCChatMe__UserG__7CE1A999] DEFAULT (newid()) FOR [UserGUID]; GO +ALTER TABLE [dbo].[IRCChatMembership] ADD CONSTRAINT [DF__IRCChatMe__IRCCh__7DD5CDD2] DEFAULT (newid()) FOR [IRCChatGUID]; GO +ALTER TABLE [dbo].[IRCChatMembership] ADD CONSTRAINT [DF__IRCChatMe__Check__7EC9F20B] DEFAULT (getdate()) FOR [LastCheckinTime]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IdentityCompressionLog ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IdentityCompressionLog] ( + [runTime] datetime NOT NULL, + [schemaName] nvarchar(100) NOT NULL, + [tableName] nvarchar(100) NOT NULL, + [status] smallint NULL, + PRIMARY KEY ([runTime], [schemaName], [tableName]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ImportCSVConfig ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ImportCSVConfig] ( + [ImportCSVConfigGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Description] nvarchar(450) NOT NULL, + [ConfigXML] xml(max) NOT NULL, + [TimeoutSeconds] int NOT NULL, + PRIMARY KEY ([ImportCSVConfigGUID]) +); +GO +ALTER TABLE [dbo].[ImportCSVConfig] ADD CONSTRAINT [DF_ImportCSVConfig_ImportCSVConfig] DEFAULT (newid()) FOR [ImportCSVConfigGUID]; GO +ALTER TABLE [dbo].[ImportCSVConfig] ADD CONSTRAINT [DF_ImportCSVConfig_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[ImportCSVConfig] ADD CONSTRAINT [DF_ImportCSVConfig_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[ImportCSVConfig] ADD CONSTRAINT [DF_ImportCSVConfig_TimeoutSeconds] DEFAULT ((60)) FOR [TimeoutSeconds]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntCapERPConnectorConfig ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntCapERPConnectorConfig] ( + [ConnectorConfigGUID] uniqueidentifier NOT NULL, + [DataType] smallint NOT NULL, + [ServerAddress] varchar(255) NOT NULL, + [Port] int NOT NULL, + [UserName] nvarchar(255) NOT NULL, + [Password] nvarchar(4000) NOT NULL, + [IsSSL] bit NOT NULL, + [PollFrequency] int NOT NULL, + [EnvironmentType] tinyint NOT NULL, + [SystemType] smallint NOT NULL, + [AdditionalDataXML] xml(max) NOT NULL, + PRIMARY KEY ([ConnectorConfigGUID]) +); +GO +ALTER TABLE [dbo].[IntCapERPConnectorConfig] ADD CONSTRAINT [DF_IntCapERPSystemConfig_PollFrequency] DEFAULT ((900)) FOR [PollFrequency]; GO +ALTER TABLE [dbo].[IntCapERPConnectorConfig] ADD CONSTRAINT [DF_IntCapERPSystemConfig_EnvironmentType] DEFAULT ((0)) FOR [EnvironmentType]; GO +ALTER TABLE [dbo].[IntCapERPConnectorConfig] ADD CONSTRAINT [DF_IntCapERPSystemConfig_AdditionalDataXML] DEFAULT ('') FOR [AdditionalDataXML]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntCapERPFieldMapping ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntCapERPFieldMapping] ( + [FieldMappingGUID] uniqueidentifier NOT NULL, + [ConnectorConfigGUID] uniqueidentifier NOT NULL, + [ERPFieldName] nvarchar(4000) NOT NULL, + [Direction] smallint NOT NULL, + [JazzFieldGUID] uniqueidentifier NOT NULL, + [Filter] nvarchar(4000) NOT NULL, + [MappingType] smallint NOT NULL, + [JazzFieldValue] nvarchar(4000) NOT NULL, + [AttributeOverrideGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([FieldMappingGUID]) +); +GO +ALTER TABLE [dbo].[IntCapERPFieldMapping] ADD CONSTRAINT [FK_IntCapERPFieldMapping_IntCapERPSystemConfig] FOREIGN KEY ([ConnectorConfigGUID]) REFERENCES [dbo].[IntCapERPConnectorConfig] ([ConnectorConfigGUID]); GO +ALTER TABLE [dbo].[IntCapERPFieldMapping] ADD CONSTRAINT [DF_IntCapERPFieldMapping_Direction] DEFAULT ((0)) FOR [Direction]; GO +ALTER TABLE [dbo].[IntCapERPFieldMapping] ADD CONSTRAINT [DF__IntCapERP__JazzF__4A1138A7] DEFAULT ('') FOR [JazzFieldValue]; GO +ALTER TABLE [dbo].[IntCapERPFieldMapping] ADD CONSTRAINT [DF__IntCapERP__JazzF__51DC77A1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [JazzFieldGUID]; GO +ALTER TABLE [dbo].[IntCapERPFieldMapping] ADD CONSTRAINT [DF__IntCapERP__Filte__53C4C013] DEFAULT ('') FOR [Filter]; GO +ALTER TABLE [dbo].[IntCapERPFieldMapping] ADD CONSTRAINT [DF__IntCapERP__Mappi__54B8E44C] DEFAULT ((0)) FOR [MappingType]; GO +ALTER TABLE [dbo].[IntCapERPFieldMapping] ADD CONSTRAINT [DF__IntCapERP__Attri__5B3BC4A9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AttributeOverrideGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntCapERPFieldMappingDefaults ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntCapERPFieldMappingDefaults] ( + [FieldMappingGUID] uniqueidentifier NOT NULL, + [ERPFieldName] nvarchar(4000) NOT NULL, + [JazzFieldName] nvarchar(4000) NOT NULL, + [JazzFieldValue] nvarchar(4000) NOT NULL, + [Direction] smallint NOT NULL, + [MappingType] smallint NOT NULL, + [DataType] smallint NOT NULL, + [SystemType] smallint NOT NULL, + [SourceName] nvarchar(4000) NOT NULL, + [IsRequired] bit NOT NULL, + PRIMARY KEY ([FieldMappingGUID]) +); +GO +ALTER TABLE [dbo].[IntCapERPFieldMappingDefaults] ADD CONSTRAINT [DF_IntCapERPFieldMappingDefaults_ERPFieldName] DEFAULT ('') FOR [ERPFieldName]; GO +ALTER TABLE [dbo].[IntCapERPFieldMappingDefaults] ADD CONSTRAINT [DF_IntCapERPFieldMappingDefaults_JazzFieldName] DEFAULT ('') FOR [JazzFieldName]; GO +ALTER TABLE [dbo].[IntCapERPFieldMappingDefaults] ADD CONSTRAINT [DF_IntCapERPFieldMappingDefaults_JazzFieldValue] DEFAULT ('') FOR [JazzFieldValue]; GO +ALTER TABLE [dbo].[IntCapERPFieldMappingDefaults] ADD CONSTRAINT [DF_IntCapERPFieldMappingDefaults_Direction] DEFAULT ((0)) FOR [Direction]; GO +ALTER TABLE [dbo].[IntCapERPFieldMappingDefaults] ADD CONSTRAINT [DF_IntCapERPFieldMappingDefaults_MappingType] DEFAULT ((0)) FOR [MappingType]; GO +ALTER TABLE [dbo].[IntCapERPFieldMappingDefaults] ADD CONSTRAINT [DF_IntCapERPFieldMappingDefaults_DataType] DEFAULT ((0)) FOR [DataType]; GO +ALTER TABLE [dbo].[IntCapERPFieldMappingDefaults] ADD CONSTRAINT [DF_IntCapERPFieldMappingDefaults_SystemType] DEFAULT ((0)) FOR [SystemType]; GO +ALTER TABLE [dbo].[IntCapERPFieldMappingDefaults] ADD CONSTRAINT [DF_IntCapERPFieldMappingDefaults_FieldMappingGUID] DEFAULT (newid()) FOR [FieldMappingGUID]; GO +ALTER TABLE [dbo].[IntCapERPFieldMappingDefaults] ADD CONSTRAINT [DF__IntCapERP__Sourc__56770F8C] DEFAULT ('') FOR [SourceName]; GO +ALTER TABLE [dbo].[IntCapERPFieldMappingDefaults] ADD CONSTRAINT [DF__IntCapERP__IsReq__5A47A070] DEFAULT ((0)) FOR [IsRequired]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntConfig ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntConfig] ( + [ConfigID] uniqueidentifier NOT NULL, + [AuthorGUID] uniqueidentifier NULL, + [Name] nvarchar(100) NOT NULL, + [IntegrationTypeVal] tinyint NOT NULL, + [DropDirectoryPath] varchar(max) NOT NULL, + [DesignerXML] varchar(max) NOT NULL, + [DataInterfaceID] uniqueidentifier NOT NULL, + [Summary] varchar(max) NOT NULL, + [IsHidden] bit NOT NULL, + [FrameworkID] tinyint NOT NULL, + [EmailLevelVal] tinyint NOT NULL, + [IsCompressed] bit NOT NULL, + [IsEncrypted] bit NOT NULL, + [CustomEmailAddress] nvarchar(2000) NOT NULL, + [IsRunOncePostAction] bit NOT NULL, + [LastRunAtUtc] datetime NOT NULL, + [CreatedAtUtc] datetime NOT NULL, + [ModifiedAtUtc] datetime NOT NULL, + PRIMARY KEY ([ConfigID]) +); +GO +ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__DropD__070736BF] DEFAULT ('') FOR [DropDirectoryPath]; GO +ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__Email__19F11CEC] DEFAULT ((0)) FOR [EmailLevelVal]; GO +ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__IsRun__1A0A5602] DEFAULT ((0)) FOR [IsRunOncePostAction]; GO +ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__Desig__258BBDDF] DEFAULT ('') FOR [DesignerXML]; GO +ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__Summa__2DB6EF8C] DEFAULT ('') FOR [Summary]; GO +ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF_intConfig_CustomEmails] DEFAULT ('') FOR [CustomEmailAddress]; GO +ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__Confi__31327AB5] DEFAULT (newid()) FOR [ConfigID]; GO +ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__Autho__32269EEE] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__Name__331AC327] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__Integ__340EE760] DEFAULT ('0') FOR [IntegrationTypeVal]; GO +ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__IsCom__3A9EE0C1] DEFAULT ((0)) FOR [IsCompressed]; GO +ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__IsEnc__3B9304FA] DEFAULT ((0)) FOR [IsEncrypted]; GO +ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__LastR__3C531C2A] DEFAULT (getutcdate()) FOR [LastRunAtUtc]; GO +ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__Creat__3D474063] DEFAULT (getutcdate()) FOR [CreatedAtUtc]; GO +ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__Modif__3E3B649C] DEFAULT (getutcdate()) FOR [ModifiedAtUtc]; GO +ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__DataI__4B7C5C9D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataInterfaceID]; GO +ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF__IntConfig__IsHid__5B20298E] DEFAULT ('0') FOR [IsHidden]; GO +ALTER TABLE [dbo].[IntConfig] ADD CONSTRAINT [DF_IntConfig_FrameworkID] DEFAULT ((0)) FOR [FrameworkID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntConfigFramework ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntConfigFramework] ( + [ConfigID] uniqueidentifier NOT NULL, + [FrameworkID] tinyint NOT NULL, + PRIMARY KEY ([ConfigID], [FrameworkID]) +); +GO +ALTER TABLE [dbo].[IntConfigFramework] ADD CONSTRAINT [FK_IntConfigFramework_IntConfig] FOREIGN KEY ([ConfigID]) REFERENCES [dbo].[IntConfig] ([ConfigID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntConfigResponse ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntConfigResponse] ( + [ConfigResponseID] uniqueidentifier NOT NULL, + [ConfigID] uniqueidentifier NOT NULL, + [ProcessStateVal] int NOT NULL, + [ResponseTypeVal] int NOT NULL, + PRIMARY KEY ([ConfigResponseID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [UQ__IntConfi__EC4B467370ADE14C] ON [dbo].[IntConfigResponse] ([ConfigID], [ProcessStateVal], [ResponseTypeVal]); +GO +ALTER TABLE [dbo].[IntConfigResponse] ADD CONSTRAINT [FK__IntConfig__Confi__7666BAA2] FOREIGN KEY ([ConfigID]) REFERENCES [dbo].[IntConfig] ([ConfigID]); GO +ALTER TABLE [dbo].[IntConfigResponse] ADD CONSTRAINT [DF__IntConfig__Confi__729629BE] DEFAULT (newid()) FOR [ConfigResponseID]; GO +ALTER TABLE [dbo].[IntConfigResponse] ADD CONSTRAINT [DF__IntConfig__Proce__747E7230] DEFAULT ((0)) FOR [ProcessStateVal]; GO +ALTER TABLE [dbo].[IntConfigResponse] ADD CONSTRAINT [DF__IntConfig__Respo__75729669] DEFAULT ((0)) FOR [ResponseTypeVal]; GO +ALTER TABLE [dbo].[IntConfigResponse] ADD CONSTRAINT [DF__IntConfig__Confi__738A4DF7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ConfigID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntConfigSchedule ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntConfigSchedule] ( + [ConfigScheduleID] uniqueidentifier NOT NULL, + [ConfigID] uniqueidentifier NOT NULL, + [Name] nvarchar(128) NOT NULL, + [TaskName] nvarchar(128) NOT NULL, + [Description] varchar(max) NOT NULL, + [IsEnabled] bit NOT NULL, + [IsExpiring] bit NOT NULL, + [ExpirationDate] datetime NOT NULL, + [StartTime] datetime NOT NULL, + [SchedulePeriodVal] int NOT NULL, + [RecurRate] int NOT NULL, + [DaysOfWeekVal] int NOT NULL, + [MonthsOfYearVal] int NOT NULL, + [Days] nvarchar(83) NOT NULL, + [OrderIndex] int NOT NULL, + [DropDirectory] nvarchar(max) NOT NULL, + [ArchiveDirectory] nvarchar(max) NOT NULL, + [ScheduledTaskGuid] uniqueidentifier NOT NULL, + [IsStopImport] bit NOT NULL, + [PreviousConfigGUID] uniqueidentifier NULL, + PRIMARY KEY ([ConfigScheduleID]) +); +GO +ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [FK__IntConfig__Confi__6388F058] FOREIGN KEY ([ConfigID]) REFERENCES [dbo].[IntConfig] ([ConfigID]); GO +ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__DropD__23647B6C] DEFAULT ('') FOR [DropDirectory]; GO +ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__IsSto__35FA2735] DEFAULT ((0)) FOR [IsStopImport]; GO +ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Archi__49F69AAD] DEFAULT ('') FOR [ArchiveDirectory]; GO +ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Confi__6294CC1F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ConfigID]; GO +ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Order__5E5A26E7] DEFAULT ((0)) FOR [OrderIndex]; GO +ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Confi__61A0A7E6] DEFAULT (newid()) FOR [ConfigScheduleID]; GO +ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfigS__Name__647D1491] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__TaskN__657138CA] DEFAULT ('') FOR [TaskName]; GO +ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Descr__66655D03] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__IsEna__6759813C] DEFAULT ((0)) FOR [IsEnabled]; GO +ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__IsExp__684DA575] DEFAULT ((0)) FOR [IsExpiring]; GO +ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Expir__6941C9AE] DEFAULT (getdate()) FOR [ExpirationDate]; GO +ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Start__6A35EDE7] DEFAULT (getdate()) FOR [StartTime]; GO +ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Sched__6B2A1220] DEFAULT ((0)) FOR [SchedulePeriodVal]; GO +ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Recur__6C1E3659] DEFAULT ((0)) FOR [RecurRate]; GO +ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__DaysO__6D125A92] DEFAULT ((0)) FOR [DaysOfWeekVal]; GO +ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Month__6E067ECB] DEFAULT ((0)) FOR [MonthsOfYearVal]; GO +ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfigS__Days__6EFAA304] DEFAULT ('') FOR [Days]; GO +ALTER TABLE [dbo].[IntConfigSchedule] ADD CONSTRAINT [DF__IntConfig__Sched__7862133C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScheduledTaskGuid]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntConfigUserGroupNotification ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntConfigUserGroupNotification] ( + [GroupNotificationGUID] uniqueidentifier NOT NULL, + [ConfigID] uniqueidentifier NOT NULL, + [UserGroupGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([GroupNotificationGUID]) +); +GO +ALTER TABLE [dbo].[IntConfigUserGroupNotification] ADD CONSTRAINT [FK_IntConfigUserGroupNotification_UserGroupGUID] FOREIGN KEY ([UserGroupGUID]) REFERENCES [dbo].[UserGroup] ([UserGroupGUID]); GO +ALTER TABLE [dbo].[IntConfigUserGroupNotification] ADD CONSTRAINT [DF__IntConfig__Confi__2DC4D3E7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ConfigID]; GO +ALTER TABLE [dbo].[IntConfigUserGroupNotification] ADD CONSTRAINT [DF_IntConfigUserGroupNotification_GroupNotificationGUID] DEFAULT (newid()) FOR [GroupNotificationGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntDataInterface ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntDataInterface] ( + [DataInterfaceID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Description] nvarchar(max) NOT NULL, + [DescriptionXAML] varchar(max) NOT NULL, + [IntegrationTypeVal] tinyint NOT NULL, + [GlobalID] nvarchar(100) NOT NULL, + PRIMARY KEY ([DataInterfaceID]) +); +GO +ALTER TABLE [dbo].[IntDataInterface] ADD CONSTRAINT [DF_IntDataInterface_GlobalID] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [dbo].[IntDataInterface] ADD CONSTRAINT [DF__IntDataIn__DataI__29274499] DEFAULT (newid()) FOR [DataInterfaceID]; GO +ALTER TABLE [dbo].[IntDataInterface] ADD CONSTRAINT [DF__IntDataIn__Descr__2ADA82E1] DEFAULT ('') FOR [DescriptionXAML]; GO +ALTER TABLE [dbo].[IntDataInterface] ADD CONSTRAINT [DF__IntDataInt__Name__2B0F8D0B] DEFAULT ('''') FOR [Name]; GO +ALTER TABLE [dbo].[IntDataInterface] ADD CONSTRAINT [DF__IntDataIn__Descr__4D64A50F] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[IntDataInterface] ADD CONSTRAINT [DF__IntDataIn__Integ__56B9051F] DEFAULT ('0') FOR [IntegrationTypeVal]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntDataInterfaceField ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntDataInterfaceField] ( + [DataInterfaceFieldID] uniqueidentifier NOT NULL, + [DataInterfaceSectionID] uniqueidentifier NOT NULL, + [ScoreKeyGUID] uniqueidentifier NOT NULL, + [OrderIndex] smallint NOT NULL, + [IsRequired] bit NOT NULL, + [FieldName] nvarchar(100) NOT NULL, + [ColumnTypeVal] tinyint NOT NULL, + [MaxLength] smallint NOT NULL, + [Precision] tinyint NOT NULL, + [Scale] tinyint NOT NULL, + [IsMeasure] bit NOT NULL, + [IsKey] bit NOT NULL, + [GivenScoreAttributeGUID] uniqueidentifier NOT NULL, + [IsAllowingCreate] bit NOT NULL, + [ImportName] nvarchar(200) NOT NULL, + [IsHidden] bit NOT NULL, + [IsForeignKey] bit NOT NULL, + [Description] varchar(max) NOT NULL, + [IsScoreRequired] bit NOT NULL, + [isReplaceKey] bit NOT NULL, + PRIMARY KEY ([DataInterfaceFieldID]) +); +GO +ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [FK__IntDataIn__DataI__38698829] FOREIGN KEY ([DataInterfaceSectionID]) REFERENCES [dbo].[IntDataInterfaceSection] ([DataInterfaceSectionID]); GO +ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__isRep__0C811614] DEFAULT ((0)) FOR [isReplaceKey]; GO +ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__IsHid__13F71D89] DEFAULT ((0)) FOR [IsHidden]; GO +ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__IsFor__14EB41C2] DEFAULT ((0)) FOR [IsForeignKey]; GO +ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__Order__3A51D09B] DEFAULT ('0') FOR [OrderIndex]; GO +ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__Descr__2615CDC4] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__IsSco__3562FE4C] DEFAULT ('0') FOR [IsScoreRequired]; GO +ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__DataI__377563F0] DEFAULT (newid()) FOR [DataInterfaceFieldID]; GO +ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__Score__395DAC62] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScoreKeyGUID]; GO +ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__IsReq__3B45F4D4] DEFAULT ('0') FOR [IsRequired]; GO +ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__Field__3C3A190D] DEFAULT ('''') FOR [FieldName]; GO +ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__Colum__3D2E3D46] DEFAULT ('0') FOR [ColumnTypeVal]; GO +ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__MaxLe__3F1685B8] DEFAULT ('0') FOR [MaxLength]; GO +ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__Preci__400AA9F1] DEFAULT ('0') FOR [Precision]; GO +ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__Scale__40FECE2A] DEFAULT ('0') FOR [Scale]; GO +ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__IsMea__42E7169C] DEFAULT ((0)) FOR [IsMeasure]; GO +ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__IsKey__4F4CED81] DEFAULT ('0') FOR [IsKey]; GO +ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__Given__504111BA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GivenScoreAttributeGUID]; GO +ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__IsAll__616B9DBC] DEFAULT ((0)) FOR [IsAllowingCreate]; GO +ALTER TABLE [dbo].[IntDataInterfaceField] ADD CONSTRAINT [DF__IntDataIn__Impor__784F0314] DEFAULT ('') FOR [ImportName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntDataInterfaceMap ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntDataInterfaceMap] ( + [DataInterfaceMapID] uniqueidentifier NOT NULL, + [SourceColumnID] uniqueidentifier NOT NULL, + [DataInterfaceFieldID] uniqueidentifier NOT NULL, + PRIMARY KEY ([DataInterfaceMapID]) +); +GO +ALTER TABLE [dbo].[IntDataInterfaceMap] ADD CONSTRAINT [FK__IntDataIn__DataI__4994142B] FOREIGN KEY ([DataInterfaceFieldID]) REFERENCES [dbo].[IntDataInterfaceField] ([DataInterfaceFieldID]); GO +ALTER TABLE [dbo].[IntDataInterfaceMap] ADD CONSTRAINT [FK__IntDataIn__Sourc__489FEFF2] FOREIGN KEY ([SourceColumnID]) REFERENCES [dbo].[IntSourceField] ([SourceColumnID]); GO +ALTER TABLE [dbo].[IntDataInterfaceMap] ADD CONSTRAINT [DF__IntDataIn__DataI__47ABCBB9] DEFAULT (newid()) FOR [DataInterfaceMapID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntDataInterfaceSection ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntDataInterfaceSection] ( + [DataInterfaceSectionID] uniqueidentifier NOT NULL, + [DataInterfaceID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [SectionTypeVal] tinyint NOT NULL, + [ScoreGUID] uniqueidentifier NOT NULL, + [Description] nvarchar(max) NOT NULL, + [SampleTypeVal] tinyint NOT NULL, + [ScriptGUID] uniqueidentifier NOT NULL, + [OrderIndex] tinyint NOT NULL, + [TableName] nvarchar(200) NULL, + [IsSummary] bit NOT NULL, + [MergeTypeVal] tinyint NOT NULL, + [AllowColumnPassthrough] bit NOT NULL, + [IsDisabled] bit NOT NULL, + PRIMARY KEY ([DataInterfaceSectionID]) +); +GO +ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [FK__IntDataIn__DataI__30C86661] FOREIGN KEY ([DataInterfaceID]) REFERENCES [dbo].[IntDataInterface] ([DataInterfaceID]); GO +ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__IsDis__01F5D0E1] DEFAULT ((0)) FOR [IsDisabled]; GO +ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__Order__15DF65FB] DEFAULT ('0') FOR [OrderIndex]; GO +ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__Merge__2E5D3419] DEFAULT ('0') FOR [MergeTypeVal]; GO +ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__DataI__2FD44228] DEFAULT (newid()) FOR [DataInterfaceSectionID]; GO +ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataInt__Name__31BC8A9A] DEFAULT ('''') FOR [Name]; GO +ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__Secti__32B0AED3] DEFAULT ('0') FOR [SectionTypeVal]; GO +ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__Score__4C7080D6] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScoreGUID]; GO +ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__Descr__4E58C948] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__Table__50961775] DEFAULT ('') FOR [TableName]; GO +ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__Allow__5D240D1B] DEFAULT ((0)) FOR [AllowColumnPassthrough]; GO +ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__Sampl__5F83554A] DEFAULT ((1)) FOR [SampleTypeVal]; GO +ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__Scrip__60777983] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScriptGUID]; GO +ALTER TABLE [dbo].[IntDataInterfaceSection] ADD CONSTRAINT [DF__IntDataIn__IsSum__7DF2CDD1] DEFAULT ('0') FOR [IsSummary]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntDataInterfaceSync ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntDataInterfaceSync] ( + [DataInterfaceID] uniqueidentifier NOT NULL, + [DataInterfaceSectionID] uniqueidentifier NOT NULL +); +GO +ALTER TABLE [dbo].[IntDataInterfaceSync] ADD CONSTRAINT [DF__IntDataIn__DataI__5F1E9A5E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataInterfaceID]; GO +ALTER TABLE [dbo].[IntDataInterfaceSync] ADD CONSTRAINT [DF__IntDataIn__DataI__6012BE97] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataInterfaceSectionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntDataInterfaceSyncLog ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntDataInterfaceSyncLog] ( + [LogGUID] uniqueidentifier NOT NULL, + [DataInterfaceID] uniqueidentifier NOT NULL, + [DataInterfaceSectionID] uniqueidentifier NOT NULL, + [Description] varchar(max) NOT NULL, + [TimeStampUtc] datetime NOT NULL, + PRIMARY KEY ([LogGUID]) +); +GO +ALTER TABLE [dbo].[IntDataInterfaceSyncLog] ADD CONSTRAINT [DF__IntDataIn__TimeS__3F2F88D5] DEFAULT (getutcdate()) FOR [TimeStampUtc]; GO +ALTER TABLE [dbo].[IntDataInterfaceSyncLog] ADD CONSTRAINT [DF__IntDataIn__LogGU__62EF2B42] DEFAULT (newid()) FOR [LogGUID]; GO +ALTER TABLE [dbo].[IntDataInterfaceSyncLog] ADD CONSTRAINT [DF__IntDataIn__DataI__63E34F7B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataInterfaceID]; GO +ALTER TABLE [dbo].[IntDataInterfaceSyncLog] ADD CONSTRAINT [DF__IntDataIn__DataI__64D773B4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataInterfaceSectionID]; GO +ALTER TABLE [dbo].[IntDataInterfaceSyncLog] ADD CONSTRAINT [DF__IntDataIn__Descr__65CB97ED] DEFAULT ('') FOR [Description]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntDataSetType ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntDataSetType] ( + [DataSetTypeID] uniqueidentifier NOT NULL, + [DataSetType] varchar(128) NOT NULL, + [SortOrder] tinyint NOT NULL, + PRIMARY KEY ([DataSetTypeID]) +); +GO +ALTER TABLE [dbo].[IntDataSetType] ADD CONSTRAINT [DF__IntDataSe__DataS__5F3B6893] DEFAULT (newid()) FOR [DataSetTypeID]; GO +ALTER TABLE [dbo].[IntDataSetType] ADD CONSTRAINT [DF__IntDataSe__DataS__602F8CCC] DEFAULT ('') FOR [DataSetType]; GO +ALTER TABLE [dbo].[IntDataSetType] ADD CONSTRAINT [DF_IntDataSetType_SortOrder] DEFAULT ((0)) FOR [SortOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntNotification ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntNotification] ( + [NotificationID] uniqueidentifier NOT NULL, + [DatabaseName] varchar(200) NOT NULL, + [TransactionGUID] uniqueidentifier NOT NULL, + [ErrorMessage] varchar(1000) NOT NULL, + [ErrorGUID] varchar(50) NOT NULL, + [LastPostAction] varchar(200) NOT NULL, + PRIMARY KEY ([NotificationID]) +); +GO +ALTER TABLE [dbo].[IntNotification] ADD CONSTRAINT [DF__IntNotifi__Notif__4ECFF6A0] DEFAULT (newid()) FOR [NotificationID]; GO +ALTER TABLE [dbo].[IntNotification] ADD CONSTRAINT [DF__IntNotifi__Datab__4FC41AD9] DEFAULT ('') FOR [DatabaseName]; GO +ALTER TABLE [dbo].[IntNotification] ADD CONSTRAINT [DF__IntNotifi__Error__50B83F12] DEFAULT ('') FOR [ErrorMessage]; GO +ALTER TABLE [dbo].[IntNotification] ADD CONSTRAINT [DF__IntNotifi__Error__51AC634B] DEFAULT ('') FOR [ErrorGUID]; GO +ALTER TABLE [dbo].[IntNotification] ADD CONSTRAINT [DF__IntNotifi__LastP__52A08784] DEFAULT ('') FOR [LastPostAction]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntPostAction ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntPostAction] ( + [PostActionID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [PostActionXML] nvarchar(max) NOT NULL, + [PostActionTypeVal] tinyint NOT NULL, + [SeqOrder] tinyint NOT NULL, + [ActionGUID] uniqueidentifier NOT NULL, + [ConfigID] uniqueidentifier NOT NULL, + PRIMARY KEY ([PostActionID]) +); +GO +ALTER TABLE [dbo].[IntPostAction] ADD CONSTRAINT [DF__IntPostAc__Actio__5E8F3111] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ActionGUID]; GO +ALTER TABLE [dbo].[IntPostAction] ADD CONSTRAINT [DF__IntPostAc__Confi__60426F59] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ConfigID]; GO +ALTER TABLE [dbo].[IntPostAction] ADD CONSTRAINT [DF__IntPostAc__PostA__5A349048] DEFAULT (newid()) FOR [PostActionID]; GO +ALTER TABLE [dbo].[IntPostAction] ADD CONSTRAINT [DF__IntPostAct__Name__5C1CD8BA] DEFAULT ('''') FOR [Name]; GO +ALTER TABLE [dbo].[IntPostAction] ADD CONSTRAINT [DF__IntPostAc__PostA__5D10FCF3] DEFAULT ('''') FOR [PostActionXML]; GO +ALTER TABLE [dbo].[IntPostAction] ADD CONSTRAINT [DF__IntPostAc__PostA__5E05212C] DEFAULT ('0') FOR [PostActionTypeVal]; GO +ALTER TABLE [dbo].[IntPostAction] ADD CONSTRAINT [DF__IntPostAc__SeqOr__5EF94565] DEFAULT ('0') FOR [SeqOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntSourceField ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntSourceField] ( + [SourceColumnID] uniqueidentifier NOT NULL, + [DataSourceID] uniqueidentifier NOT NULL, + [ColumnName] nvarchar(128) NOT NULL, + [IsKey] bit NOT NULL, + [ColumnTypeVal] tinyint NOT NULL, + [MaxLength] smallint NOT NULL, + [Precision] tinyint NOT NULL, + [Scale] tinyint NOT NULL, + [OrderIndex] int NOT NULL, + [IsMeasure] bit NOT NULL, + [FixedCharacterWidth] int NOT NULL, + [ColumnAffinityVal] tinyint NOT NULL, + [FixedStartIndex] int NOT NULL, + [IsTrimEnabled] bit NOT NULL, + [SequenceCode] nvarchar(20) NOT NULL, + [RecordNumber] nvarchar(20) NOT NULL, + [ClientField] varchar(1000) NOT NULL, + PRIMARY KEY ([SourceColumnID]) +); +GO +ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__Sourc__014E5D69] DEFAULT (newid()) FOR [SourceColumnID]; GO +ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__Colum__0336A5DB] DEFAULT ('''') FOR [ColumnName]; GO +ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__IsKey__042ACA14] DEFAULT ('0') FOR [IsKey]; GO +ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__Colum__051EEE4D] DEFAULT ('0') FOR [ColumnTypeVal]; GO +ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF_IntSourceColumn_MaxLength] DEFAULT ((0)) FOR [MaxLength]; GO +ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF_IntSourceColumn_Precision] DEFAULT ((0)) FOR [Precision]; GO +ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF_IntSourceColumn_Scale] DEFAULT ((0)) FOR [Scale]; GO +ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__Recor__0B8CF1DB] DEFAULT ('') FOR [RecordNumber]; GO +ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__Clien__0BBC36AB] DEFAULT ('') FOR [ClientField]; GO +ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__Order__1DEA9C17] DEFAULT ((0)) FOR [OrderIndex]; GO +ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__IsMea__3992B68C] DEFAULT ((0)) FOR [IsMeasure]; GO +ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__Seque__3D96ECB6] DEFAULT ('') FOR [SequenceCode]; GO +ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__Fixed__4A532E3A] DEFAULT ((0)) FOR [FixedStartIndex]; GO +ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__Fixed__525E6456] DEFAULT ((-1)) FOR [FixedCharacterWidth]; GO +ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__IsTri__599571CA] DEFAULT ((0)) FOR [IsTrimEnabled]; GO +ALTER TABLE [dbo].[IntSourceField] ADD CONSTRAINT [DF__IntSource__Colum__5D9B0CD8] DEFAULT ((0)) FOR [ColumnAffinityVal]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntSourceFile ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntSourceFile] ( + [SourceFileID] uniqueidentifier NOT NULL, + [ConfigID] uniqueidentifier NOT NULL, + [ExpectedFileName] nvarchar(1024) NOT NULL, + [OrderIndex] int NOT NULL, + [SourceFileTypeVal] tinyint NOT NULL, + [ConfigXML] varchar(max) NOT NULL, + [Name] nvarchar(128) NOT NULL, + [IsRepeatable] bit NOT NULL, + [MatchModeVal] tinyint NOT NULL, + [PartialMatchString] varchar(800) NOT NULL, + [AutoSkipLineCount] int NOT NULL, + [SourceSystem] nvarchar(500) NOT NULL, + PRIMARY KEY ([SourceFileID]) +); +GO +ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [FK__IntSource__Confi__77C4F32F] FOREIGN KEY ([ConfigID]) REFERENCES [dbo].[IntConfig] ([ConfigID]); GO +ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSourceF__Name__1F9DDA5F] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSource__Order__267FE218] DEFAULT ((0)) FOR [OrderIndex]; GO +ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSource__IsRep__29E65EA8] DEFAULT ((0)) FOR [IsRepeatable]; GO +ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSource__Match__2BCEA71A] DEFAULT ((0)) FOR [MatchModeVal]; GO +ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSource__Parti__2CC2CB53] DEFAULT ('') FOR [PartialMatchString]; GO +ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSource__Sourc__516A401D] DEFAULT ((0)) FOR [SourceFileTypeVal]; GO +ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSource__Confi__5352888F] DEFAULT ('') FOR [ConfigXML]; GO +ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSource__Sourc__541F86F9] DEFAULT ('') FOR [SourceSystem]; GO +ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSource__AutoS__5A899603] DEFAULT ((0)) FOR [AutoSkipLineCount]; GO +ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSource__Sourc__76D0CEF6] DEFAULT (newid()) FOR [SourceFileID]; GO +ALTER TABLE [dbo].[IntSourceFile] ADD CONSTRAINT [DF__IntSource__Expec__78B91768] DEFAULT ('') FOR [ExpectedFileName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntSourceFileLocation ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntSourceFileLocation] ( + [UserGUID] uniqueidentifier NOT NULL, + [SourceFileID] uniqueidentifier NOT NULL, + [LastFullPathSeen] varchar(800) NOT NULL, + PRIMARY KEY ([UserGUID], [SourceFileID]) +); +GO +ALTER TABLE [dbo].[IntSourceFileLocation] ADD CONSTRAINT [FK_IntSourceFileLocation_IntSourceFile] FOREIGN KEY ([SourceFileID]) REFERENCES [dbo].[IntSourceFile] ([SourceFileID]); GO +ALTER TABLE [dbo].[IntSourceFileLocation] ADD CONSTRAINT [FK_IntSourceFileLocation_UserProfile] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO +ALTER TABLE [dbo].[IntSourceFileLocation] ADD CONSTRAINT [DF__IntSource__LastF__22AF5134] DEFAULT ('') FOR [LastFullPathSeen]; GO +ALTER TABLE [dbo].[IntSourceFileLocation] ADD CONSTRAINT [DF__IntSource__UserG__20C708C2] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[IntSourceFileLocation] ADD CONSTRAINT [DF__IntSource__Sourc__21BB2CFB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SourceFileID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntSourceSystemDetail ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntSourceSystemDetail] ( + [SourceSystemDetailID] uniqueidentifier NOT NULL, + [DataSetSource] varchar(128) NOT NULL, + [SourceID] varchar(128) NOT NULL, + [Notes] varchar(1000) NOT NULL, + [DataSetTypeID] uniqueidentifier NOT NULL, + [IsCustom] bit NOT NULL, + PRIMARY KEY ([SourceSystemDetailID]) +); +GO +ALTER TABLE [dbo].[IntSourceSystemDetail] ADD CONSTRAINT [FK__IntSource__DataS__66DC8A5B] FOREIGN KEY ([DataSetTypeID]) REFERENCES [dbo].[IntDataSetType] ([DataSetTypeID]); GO +ALTER TABLE [dbo].[IntSourceSystemDetail] ADD CONSTRAINT [DF__IntSource__IsCus__594D8513] DEFAULT ((0)) FOR [IsCustom]; GO +ALTER TABLE [dbo].[IntSourceSystemDetail] ADD CONSTRAINT [DF__IntSource__Sourc__630BF977] DEFAULT (newid()) FOR [SourceSystemDetailID]; GO +ALTER TABLE [dbo].[IntSourceSystemDetail] ADD CONSTRAINT [DF__IntSource__DataS__64001DB0] DEFAULT ('') FOR [DataSetSource]; GO +ALTER TABLE [dbo].[IntSourceSystemDetail] ADD CONSTRAINT [DF__IntSource__Sourc__64F441E9] DEFAULT ('') FOR [SourceID]; GO +ALTER TABLE [dbo].[IntSourceSystemDetail] ADD CONSTRAINT [DF__IntSource__Notes__65E86622] DEFAULT ('') FOR [Notes]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntTransaction ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntTransaction] ( + [TransactionGUID] uniqueidentifier NOT NULL, + [ConfigID] uniqueidentifier NOT NULL, + [UserID] uniqueidentifier NOT NULL, + [IsSuccess] bit NOT NULL, + [HasCompleted] bit NOT NULL, + [FileCheckSum] varchar(8000) NOT NULL, + [HasStarted] bit NOT NULL, + [ProcessStateVal] tinyint NOT NULL, + [LocationVal] tinyint NOT NULL, + [Comment] nvarchar(400) NOT NULL, + [Files] nvarchar(max) NOT NULL, + [IsManualEntry] bit NOT NULL, + [CanDelete] bit NOT NULL, + [TransactionID] int NOT NULL, + [ProcessStateFailedValue] tinyint NOT NULL, + [PostActionDuration] int NOT NULL, + [EndTimeUtc] datetime NOT NULL, + [StartTimeUtc] datetime NOT NULL, + PRIMARY KEY ([TransactionGUID]) +); + +CREATE NONCLUSTERED INDEX [NC_IntTransaction_ConfigIDWithCheckSum] ON [dbo].[IntTransaction] ([ConfigID]) INCLUDE ([FileCheckSum]); +GO +ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__Trans__1AEC313B] DEFAULT (newid()) FOR [TransactionGUID]; GO +ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__Confi__1BE05574] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ConfigID]; GO +ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__UserI__1CD479AD] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserID]; GO +ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__IsSuc__1DC89DE6] DEFAULT ((0)) FOR [IsSuccess]; GO +ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__HasCo__1EBCC21F] DEFAULT ((0)) FOR [HasCompleted]; GO +ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__FileC__1FB0E658] DEFAULT ('') FOR [FileCheckSum]; GO +ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__HasSt__20A50A91] DEFAULT ((0)) FOR [HasStarted]; GO +ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__Proce__21992ECA] DEFAULT ((0)) FOR [ProcessStateVal]; GO +ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__Locat__228D5303] DEFAULT ((0)) FOR [LocationVal]; GO +ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__Comme__2381773C] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__Files__24759B75] DEFAULT ('') FOR [Files]; GO +ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__IsMan__2569BFAE] DEFAULT ((0)) FOR [IsManualEntry]; GO +ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__CanDe__265DE3E7] DEFAULT ((0)) FOR [CanDelete]; GO +ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__Proce__27520820] DEFAULT ((0)) FOR [ProcessStateFailedValue]; GO +ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__PostA__28462C59] DEFAULT ((0)) FOR [PostActionDuration]; GO +ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__EndTi__293A5092] DEFAULT (getutcdate()) FOR [EndTimeUtc]; GO +ALTER TABLE [dbo].[IntTransaction] ADD CONSTRAINT [DF__IntTransa__Start__2A2E74CB] DEFAULT (getutcdate()) FOR [StartTimeUtc]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntTransactionData ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntTransactionData] ( + [TransactionDataID] uniqueidentifier NOT NULL, + [TransactionGUID] uniqueidentifier NOT NULL, + [DataInterfaceSectionID] uniqueidentifier NOT NULL, + [RowsImported] int NOT NULL, + [CanDelete] bit NOT NULL, + [IsImportDeleted] bit NOT NULL, + [TransactionID] int NOT NULL, + [RowsRejected] int NOT NULL, + [TotalRows] int NOT NULL, + [Files] varchar(max) NOT NULL, + [FileSize] bigint NOT NULL, + [HasDummyFile] bit NOT NULL, + [IsAdhocImport] bit NOT NULL, + PRIMARY KEY ([TransactionDataID]) +); + +CREATE CLUSTERED INDEX [IX_TransactionGUID] ON [dbo].[IntTransactionData] ([TransactionGUID]); +GO +ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__Trans__2A1178FB] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__Total__34BBEA39] DEFAULT ((0)) FOR [TotalRows]; GO +ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__IsAdh__3E0987CE] DEFAULT ((0)) FOR [IsAdhocImport]; GO +ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__RowsR__3ED8570E] DEFAULT ((0)) FOR [RowsRejected]; GO +ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__FileS__4F50E205] DEFAULT ((0)) FOR [FileSize]; GO +ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__Files__526C48B1] DEFAULT ('') FOR [Files]; GO +ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__Trans__5FEC04BA] DEFAULT (newid()) FOR [TransactionDataID]; GO +ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__Trans__60E028F3] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TransactionGUID]; GO +ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__DataI__61D44D2C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataInterfaceSectionID]; GO +ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__RowsI__62C87165] DEFAULT ((0)) FOR [RowsImported]; GO +ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__CanDe__63BC959E] DEFAULT ((1)) FOR [CanDelete]; GO +ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__IsImp__64B0B9D7] DEFAULT ((0)) FOR [IsImportDeleted]; GO +ALTER TABLE [dbo].[IntTransactionData] ADD CONSTRAINT [DF__IntTransa__HasDu__78A03DB7] DEFAULT ((0)) FOR [HasDummyFile]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntTransformation ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntTransformation] ( + [TransformationID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [TransformXML] nvarchar(max) NULL, + [TransformationTypeVal] tinyint NOT NULL, + [TransformationLocationVal] tinyint NOT NULL, + [SeqOrder] tinyint NOT NULL, + [Description] varchar(2000) NOT NULL, + [Level] int NOT NULL, + [ConfigID] uniqueidentifier NOT NULL, + [IsCopied] bit NOT NULL, + PRIMARY KEY ([TransformationID]) +); +GO +ALTER TABLE [dbo].[IntTransformation] ADD CONSTRAINT [DF_IntTransformation_Description] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[IntTransformation] ADD CONSTRAINT [DF__IntTransf__IsCop__272CE4F1] DEFAULT ((0)) FOR [IsCopied]; GO +ALTER TABLE [dbo].[IntTransformation] ADD CONSTRAINT [DF__IntTransf__Trans__4721BBD4] DEFAULT (newid()) FOR [TransformationID]; GO +ALTER TABLE [dbo].[IntTransformation] ADD CONSTRAINT [DF__IntTransfo__Name__490A0446] DEFAULT ('''') FOR [Name]; GO +ALTER TABLE [dbo].[IntTransformation] ADD CONSTRAINT [DF__IntTransf__Trans__49FE287F] DEFAULT ('0') FOR [TransformationTypeVal]; GO +ALTER TABLE [dbo].[IntTransformation] ADD CONSTRAINT [DF__IntTransf__Level__4A883864] DEFAULT ((-1)) FOR [Level]; GO +ALTER TABLE [dbo].[IntTransformation] ADD CONSTRAINT [DF__IntTransf__Trans__4AF24CB8] DEFAULT ('0') FOR [TransformationLocationVal]; GO +ALTER TABLE [dbo].[IntTransformation] ADD CONSTRAINT [DF__IntTransf__SeqOr__4BE670F1] DEFAULT ('0') FOR [SeqOrder]; GO +ALTER TABLE [dbo].[IntTransformation] ADD CONSTRAINT [DF__IntTransf__Confi__61369392] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ConfigID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.IntTransformationLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[IntTransformationLink] ( + [TargetDataSourceID] uniqueidentifier NOT NULL, + [SourceDataSourceID] uniqueidentifier NOT NULL, + PRIMARY KEY ([TargetDataSourceID], [SourceDataSourceID]) +); +GO +ALTER TABLE [dbo].[IntTransformationLink] ADD CONSTRAINT [DF__IntTransf__DataS__1AD92542] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TargetDataSourceID]; GO +ALTER TABLE [dbo].[IntTransformationLink] ADD CONSTRAINT [DF__IntTransf__Paren__1BCD497B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SourceDataSourceID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.LastSecurityCheck ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[LastSecurityCheck] ( + [UserGUID] uniqueidentifier NOT NULL, + [Checksum] int NULL, + [EmailAddress] nvarchar(450) NOT NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.Lock ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[Lock] ( + [LockGUID] uniqueidentifier NOT NULL, + [ItemGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [DateLocked] datetime NOT NULL, + [LockGroup] nvarchar(64) NOT NULL, + [DateLastActive] datetime NOT NULL, + [UserName] nvarchar(256) NOT NULL, + [DateLockedUtc] datetime NOT NULL, + [DateLastActiveUtc] datetime NOT NULL +); +GO +ALTER TABLE [dbo].[Lock] ADD CONSTRAINT [DF_Lock_LOCKGUID] DEFAULT (newid()) FOR [LockGUID]; GO +ALTER TABLE [dbo].[Lock] ADD CONSTRAINT [DF_Lock_ITEMGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ItemGUID]; GO +ALTER TABLE [dbo].[Lock] ADD CONSTRAINT [DF_Lock_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[Lock] ADD CONSTRAINT [DF_Lock_DATELOCKED] DEFAULT (getdate()) FOR [DateLocked]; GO +ALTER TABLE [dbo].[Lock] ADD CONSTRAINT [DF_Lock_LOCKGROUP] DEFAULT ('') FOR [LockGroup]; GO +ALTER TABLE [dbo].[Lock] ADD CONSTRAINT [DF_Lock_DATELASTACTIVE] DEFAULT (getdate()) FOR [DateLastActive]; GO +ALTER TABLE [dbo].[Lock] ADD CONSTRAINT [DF__Lock__DateLocked__3976AF7F] DEFAULT (getutcdate()) FOR [DateLockedUtc]; GO +ALTER TABLE [dbo].[Lock] ADD CONSTRAINT [DF__Lock__DateLastAc__3A6AD3B8] DEFAULT (getutcdate()) FOR [DateLastActiveUtc]; GO +ALTER TABLE [dbo].[Lock] ADD CONSTRAINT [DF_Lock_UserName] DEFAULT ('') FOR [UserName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.LoginHistory ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[LoginHistory] ( + [TokenGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [LoginStamp] datetime NOT NULL, + [LastActionStamp] datetime NULL, + [LogoutStamp] datetime NULL, + [UserName] nvarchar(64) NOT NULL, + [IPAddress] nvarchar(100) NULL, + PRIMARY KEY ([TokenGUID]) +); +GO +ALTER TABLE [dbo].[LoginHistory] ADD CONSTRAINT [DF_LoginHistory_UserName] DEFAULT ('') FOR [UserName]; GO +ALTER TABLE [dbo].[LoginHistory] ADD CONSTRAINT [DF_dbo.LoginHistory_TOKENGUID] DEFAULT (newid()) FOR [TokenGUID]; GO +ALTER TABLE [dbo].[LoginHistory] ADD CONSTRAINT [DF_LoginHistory_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[LoginHistory] ADD CONSTRAINT [DF_dbo.LoginHistory_LOGINSTAMP] DEFAULT (getdate()) FOR [LoginStamp]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MECacheInvalidateLog ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MECacheInvalidateLog] ( + [RowID] int NOT NULL, + [ModelGUID] uniqueidentifier NOT NULL, + [Source] nvarchar(100) NOT NULL, + [DateTimeStamp] datetime NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [dbo].[MECacheInvalidateLog] ADD CONSTRAINT [DF_MECacheInvalidateLog_Source] DEFAULT ('') FOR [Source]; GO +ALTER TABLE [dbo].[MECacheInvalidateLog] ADD CONSTRAINT [DF_MECacheInvalidateLog_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO +ALTER TABLE [dbo].[MECacheInvalidateLog] ADD CONSTRAINT [DF_MECacheInvalidateLog_ModelGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MEExcelCell ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MEExcelCell] ( + [ExcelCellGUID] uniqueidentifier NOT NULL, + [ExcelSheetGUID] uniqueidentifier NOT NULL, + [Row] int NOT NULL, + [Row2] int NOT NULL, + [Col] int NOT NULL, + [MappingFormula] nvarchar(max) NOT NULL, + [DefaultFormula] nvarchar(max) NOT NULL, + [TestDataFormula] nvarchar(max) NOT NULL, + [DataSourceGUID] uniqueidentifier NOT NULL, + [IsReadFromDB] bit NOT NULL, + [IsWrittenToDB] bit NOT NULL, + [IsLocked] bit NOT NULL, + [IsAssumptionInput] bit NOT NULL, + [IsAssumptionOutput] bit NOT NULL, + [IsWrittenIfZero] bit NOT NULL, + [IsAssumptionDriver] bit NOT NULL, + PRIMARY KEY ([ExcelCellGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_ModelLoad] ON [dbo].[MEExcelCell] ([IsReadFromDB], [ExcelSheetGUID], [ExcelCellGUID], [Col], [IsLocked], [IsAssumptionInput], [IsAssumptionOutput]) INCLUDE ([DefaultFormula]); +CREATE NONCLUSTERED INDEX [IX_IsWrittenToDB] ON [dbo].[MEExcelCell] ([IsWrittenToDB]) INCLUDE ([ExcelCellGUID], [ExcelSheetGUID], [Col]); +CREATE NONCLUSTERED INDEX [IDX_MEExcelCell] ON [dbo].[MEExcelCell] ([ExcelSheetGUID]); +GO +ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [FK_MEExcelCell_EMFModelTemplateWorksheet] FOREIGN KEY ([ExcelSheetGUID]) REFERENCES [dbo].[EMFModelTemplateWorksheet] ([WorksheetGUID]); GO +ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_TestDataFormula] DEFAULT ('') FOR [TestDataFormula]; GO +ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_CompositeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataSourceGUID]; GO +ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_IsReadFromDB] DEFAULT ((0)) FOR [IsReadFromDB]; GO +ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_IsWrittenToDB] DEFAULT ((0)) FOR [IsWrittenToDB]; GO +ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_IsLocked] DEFAULT ((0)) FOR [IsLocked]; GO +ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_IsAssumptionInput] DEFAULT ((0)) FOR [IsAssumptionInput]; GO +ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_IsAssumptionOutput] DEFAULT ((0)) FOR [IsAssumptionOutput]; GO +ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_IsWrittenIfZero] DEFAULT ((0)) FOR [IsWrittenIfZero]; GO +ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MFExcelCell_ExcelCellGUID] DEFAULT (newid()) FOR [ExcelCellGUID]; GO +ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_Row2] DEFAULT ((0)) FOR [Row2]; GO +ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_MappingFormula] DEFAULT ('') FOR [MappingFormula]; GO +ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_DefaultFormula] DEFAULT ('') FOR [DefaultFormula]; GO +ALTER TABLE [dbo].[MEExcelCell] ADD CONSTRAINT [DF_MEExcelCell_IsAssumptionDriver] DEFAULT ((0)) FOR [IsAssumptionDriver]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MEFillinTemplate ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MEFillinTemplate] ( + [FillinTemplateGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(400) NOT NULL, + [ModelTemplateGUID] uniqueidentifier NOT NULL, + [IsDefault] bit NOT NULL, + PRIMARY KEY ([FillinTemplateGUID]) +); +GO +ALTER TABLE [dbo].[MEFillinTemplate] ADD CONSTRAINT [FK_MEFillinTemplate_EMFModelTemplate] FOREIGN KEY ([ModelTemplateGUID]) REFERENCES [dbo].[EMFModelTemplate] ([ModelTemplateGUID]); GO +ALTER TABLE [dbo].[MEFillinTemplate] ADD CONSTRAINT [DF__FillinTem__Filli__36CAF0B7] DEFAULT (newid()) FOR [FillinTemplateGUID]; GO +ALTER TABLE [dbo].[MEFillinTemplate] ADD CONSTRAINT [DF__FillinTemp__Name__37BF14F0] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[MEFillinTemplate] ADD CONSTRAINT [DF__FillinTem__Model__38B33929] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelTemplateGUID]; GO +ALTER TABLE [dbo].[MEFillinTemplate] ADD CONSTRAINT [DF_MEFillinTemplate_IsDefault] DEFAULT ((0)) FOR [IsDefault]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MEImprovData ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MEImprovData] ( + [ImprovDataGUID] uniqueidentifier NOT NULL, + [ModelGUID] uniqueidentifier NOT NULL, + [WorksheetGUID] uniqueidentifier NOT NULL, + [Row] int NOT NULL, + [Col] int NOT NULL, + [Formula] nvarchar(4000) NOT NULL, + [CellValue] nvarchar(4000) NOT NULL, + [OriginalComment] nvarchar(4000) NOT NULL, + PRIMARY KEY ([ImprovDataGUID]) +); + +CREATE UNIQUE CLUSTERED INDEX [IX_MEImprovData] ON [dbo].[MEImprovData] ([ModelGUID], [WorksheetGUID], [Row], [Col]); +GO +ALTER TABLE [dbo].[MEImprovData] ADD CONSTRAINT [FK_MEImprovData_MEImprovData] FOREIGN KEY ([ImprovDataGUID]) REFERENCES [dbo].[MEImprovData] ([ImprovDataGUID]); GO +ALTER TABLE [dbo].[MEImprovData] ADD CONSTRAINT [DF_MEImprovData_OriginalStyleName] DEFAULT ('') FOR [OriginalComment]; GO +ALTER TABLE [dbo].[MEImprovData] ADD CONSTRAINT [DF_MEImprovData_RowGUID] DEFAULT (newsequentialid()) FOR [ImprovDataGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MEModelRefreshQueue ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MEModelRefreshQueue] ( + [ModelGUID] uniqueidentifier NOT NULL, + [DateTimeStamp] datetime NOT NULL, + [ErrorLogGUID] uniqueidentifier NOT NULL, + [UserName] nvarchar(64) NOT NULL, + [Source] nvarchar(100) NOT NULL, + [CompositeGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([ModelGUID]) +); +GO +ALTER TABLE [dbo].[MEModelRefreshQueue] ADD CONSTRAINT [DF_MEModelRefreshQueue_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO +ALTER TABLE [dbo].[MEModelRefreshQueue] ADD CONSTRAINT [DF_MEModelRefreshQueue_ModelGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO +ALTER TABLE [dbo].[MEModelRefreshQueue] ADD CONSTRAINT [DF_MEModelRefreshQueue_Source] DEFAULT ('') FOR [Source]; GO +ALTER TABLE [dbo].[MEModelRefreshQueue] ADD CONSTRAINT [DF__MEModelRe__UserN__5C2FE8E2] DEFAULT ('') FOR [UserName]; GO +ALTER TABLE [dbo].[MEModelRefreshQueue] ADD CONSTRAINT [DF_MEModelRefreshQueue_ErrorLogGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ErrorLogGUID]; GO +ALTER TABLE [dbo].[MEModelRefreshQueue] ADD CONSTRAINT [DF_MEModelRefreshQueue_CompositeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CompositeGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MEPHSection ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MEPHSection] ( + [PHSectionGUID] uniqueidentifier NOT NULL, + [ModelTemplateGUID] uniqueidentifier NOT NULL, + [PHSectionDimensionGUID] uniqueidentifier NOT NULL, + [PHSectionMemberGUID] uniqueidentifier NOT NULL, + [PlanTypeGUID] uniqueidentifier NOT NULL, + [FriendlyName] nvarchar(100) NOT NULL, + [SortType] int NOT NULL, + [IsConstantIndex] bit NOT NULL, + [RootHierarchyPath] nvarchar(max) NOT NULL, + [DefaultHierarchyPath] nvarchar(max) NOT NULL, + [IsAppend] bit NOT NULL, + [IsHidden] bit NOT NULL, + [IsReadOnly] bit NOT NULL, + [IsExclusive] bit NOT NULL, + [RuleType] smallint NOT NULL, + [IsOneTime] bit NOT NULL, + [IsClearOnRefresh] bit NOT NULL, + [ExclusivityGroup] nvarchar(100) NOT NULL, + [IsOrderByName] bit NOT NULL, + [IsOrderByNameSkippingCode] bit NOT NULL, + PRIMARY KEY ([PHSectionGUID]) +); +GO +ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [FK_MEPHSectionConfig_EMFModelTemplate] FOREIGN KEY ([ModelTemplateGUID]) REFERENCES [dbo].[EMFModelTemplate] ([ModelTemplateGUID]); GO +ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSectionConfig_IsReadOnly] DEFAULT ((0)) FOR [IsReadOnly]; GO +ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSection_IsExclusive] DEFAULT ((0)) FOR [IsExclusive]; GO +ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF__MEPHSecti__Exclu__0282DC58] DEFAULT ('') FOR [ExclusivityGroup]; GO +ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSection_RuleType] DEFAULT ((0)) FOR [RuleType]; GO +ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSection_IsOrderByNameSkippingCode] DEFAULT ((0)) FOR [IsOrderByNameSkippingCode]; GO +ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSection_IsOrderByName] DEFAULT ((0)) FOR [IsOrderByName]; GO +ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF__MEPHSecti__IsCle__3CD0AC98] DEFAULT ((0)) FOR [IsClearOnRefresh]; GO +ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSection_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO +ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF__MEPHSecti__IsOne__77E6856E] DEFAULT ((0)) FOR [IsOneTime]; GO +ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSectionConfig_PHSectionConfigGUID] DEFAULT (newid()) FOR [PHSectionGUID]; GO +ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSectionConfig_FriendlyName] DEFAULT ('') FOR [FriendlyName]; GO +ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSectionConfig_IsAutoSort] DEFAULT ((0)) FOR [SortType]; GO +ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSectionConfig_IsConstantIndex] DEFAULT ((0)) FOR [IsConstantIndex]; GO +ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSectionConfig_RootHierarchyPath] DEFAULT ('') FOR [RootHierarchyPath]; GO +ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSectionConfig_DefaultHierarchyPath] DEFAULT ('') FOR [DefaultHierarchyPath]; GO +ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSection_IsAppend] DEFAULT ((0)) FOR [IsAppend]; GO +ALTER TABLE [dbo].[MEPHSection] ADD CONSTRAINT [DF_MEPHSectionConfig_IsHidden] DEFAULT ((0)) FOR [IsHidden]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MEPHSectionDataTableLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MEPHSectionDataTableLink] ( + [PHSectionConfigGUID] uniqueidentifier NOT NULL, + [DataTableGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([PHSectionConfigGUID], [DataTableGUID]) +); +GO +ALTER TABLE [dbo].[MEPHSectionDataTableLink] ADD CONSTRAINT [FK_MEPHSectionDataTableLink_MEPHSectionConfig] FOREIGN KEY ([PHSectionConfigGUID]) REFERENCES [dbo].[MEPHSection] ([PHSectionGUID]); GO +ALTER TABLE [dbo].[MEPHSectionDataTableLink] ADD CONSTRAINT [FK_MEPHSectionDataTableLink_ScoreDataTable] FOREIGN KEY ([DataTableGUID]) REFERENCES [dbo].[ScoreDataTable] ([DataTableGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MEPHSectionRuleValue ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MEPHSectionRuleValue] ( + [PHSectionRuleValueGUID] uniqueidentifier NOT NULL, + [PHSectionGUID] uniqueidentifier NOT NULL, + [RuleValueKey] nvarchar(50) NOT NULL, + [RuleValue] nvarchar(max) NOT NULL, + [SortOrder] int NULL, + [FillinTemplateGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([PHSectionRuleValueGUID]) +); +GO +ALTER TABLE [dbo].[MEPHSectionRuleValue] ADD CONSTRAINT [FK_MEPHSectionRuleValue_MEPHSection] FOREIGN KEY ([PHSectionGUID]) REFERENCES [dbo].[MEPHSection] ([PHSectionGUID]); GO +ALTER TABLE [dbo].[MEPHSectionRuleValue] ADD CONSTRAINT [DF__dbo_MEPHSectionRuleValue_SortOrder] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [dbo].[MEPHSectionRuleValue] ADD CONSTRAINT [DF__MEPHSecti__Filli__3A9B819B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FillinTemplateGUID]; GO +ALTER TABLE [dbo].[MEPHSectionRuleValue] ADD CONSTRAINT [DF_MEPHSectionRuleValue_PHSectionRuleGUID] DEFAULT (newid()) FOR [PHSectionRuleValueGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MEReportLinkTemplateMapping ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MEReportLinkTemplateMapping] ( + [ReportLinkTemplateMappingGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [CellGUID] uniqueidentifier NOT NULL, + [RowExpanded] int NOT NULL, + [ReportParams] nvarchar(max) NOT NULL, + PRIMARY KEY ([ReportLinkTemplateMappingGUID]) +); +GO +ALTER TABLE [dbo].[MEReportLinkTemplateMapping] ADD CONSTRAINT [FK_MEReportLinkTemplateMapping_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[MEReportLinkTemplateMapping] ADD CONSTRAINT [DF_MEReportLinkTemplateMapping_ReportLinkTemplateMappingGUID] DEFAULT (newid()) FOR [ReportLinkTemplateMappingGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MESaveErrorLog ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MESaveErrorLog] ( + [LogGUID] uniqueidentifier NOT NULL, + [ModelGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [DateTimeStamp] datetime NOT NULL, + [ErrorLogGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([LogGUID]) +); +GO +ALTER TABLE [dbo].[MESaveErrorLog] ADD CONSTRAINT [DF_Table_1_HistoryGUID] DEFAULT (newid()) FOR [LogGUID]; GO +ALTER TABLE [dbo].[MESaveErrorLog] ADD CONSTRAINT [DF_MESaveErrorLog_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO +ALTER TABLE [dbo].[MESaveErrorLog] ADD CONSTRAINT [DF_MESaveErrorLog_ModelGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO +ALTER TABLE [dbo].[MESaveErrorLog] ADD CONSTRAINT [DF_MESaveErrorLog_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[MESaveErrorLog] ADD CONSTRAINT [DF_MESaveErrorLog_ErrorLogGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ErrorLogGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MEScoreExpansion ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MEScoreExpansion] ( + [ExcelCellGUID] uniqueidentifier NOT NULL, + [ExpansionGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [IndexName] nvarchar(64) NOT NULL, + [Count] int NOT NULL, + [ExecutionOrder] int NOT NULL, + [GlobalID] nvarchar(100) NOT NULL, + PRIMARY KEY ([ExpansionGUID]) +); +GO +ALTER TABLE [dbo].[MEScoreExpansion] ADD CONSTRAINT [DF_ScoreExpansion_ExpansionGUID] DEFAULT (newid()) FOR [ExpansionGUID]; GO +ALTER TABLE [dbo].[MEScoreExpansion] ADD CONSTRAINT [DF_ScoreExpansion_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[MEScoreExpansion] ADD CONSTRAINT [DF_ScoreExpansion_IndexName] DEFAULT ('') FOR [IndexName]; GO +ALTER TABLE [dbo].[MEScoreExpansion] ADD CONSTRAINT [DF_ScoreExpansion_Count] DEFAULT ((0)) FOR [Count]; GO +ALTER TABLE [dbo].[MEScoreExpansion] ADD CONSTRAINT [DF_ScoreExpansion_ExecutionOrder] DEFAULT ((0)) FOR [ExecutionOrder]; GO +ALTER TABLE [dbo].[MEScoreExpansion] ADD CONSTRAINT [DF_MEScoreExpansion_GlobalID] DEFAULT ('') FOR [GlobalID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MEScoreExpansionOverride ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MEScoreExpansionOverride] ( + [OverrideGUID] uniqueidentifier NOT NULL, + [ExpansionProfileGUID] uniqueidentifier NOT NULL, + [ExpansionGlobalID] nvarchar(100) NOT NULL, + [CountOverride] int NOT NULL, + PRIMARY KEY ([OverrideGUID]) +); +GO +ALTER TABLE [dbo].[MEScoreExpansionOverride] ADD CONSTRAINT [FK_MEScoreExpansionOverride_MEScoreExpansionProfile] FOREIGN KEY ([ExpansionProfileGUID]) REFERENCES [dbo].[MEScoreExpansionProfile] ([ExpansionProfileGUID]); GO +ALTER TABLE [dbo].[MEScoreExpansionOverride] ADD CONSTRAINT [DF_MEScoreExpansionOverride_OverrideGUID] DEFAULT (newid()) FOR [OverrideGUID]; GO +ALTER TABLE [dbo].[MEScoreExpansionOverride] ADD CONSTRAINT [DF_MEScoreExpansionOverride_ExpansionGlobalID] DEFAULT ('') FOR [ExpansionGlobalID]; GO +ALTER TABLE [dbo].[MEScoreExpansionOverride] ADD CONSTRAINT [DF_MEScoreExpansionOverride_ExpansionProfileGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ExpansionProfileGUID]; GO +ALTER TABLE [dbo].[MEScoreExpansionOverride] ADD CONSTRAINT [DF_MEScoreExpansionOverride_Count] DEFAULT ((0)) FOR [CountOverride]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MEScoreExpansionProfile ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MEScoreExpansionProfile] ( + [ExpansionProfileGUID] uniqueidentifier NOT NULL, + [ParentModelTemplateGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [ChildModelTemplateGUID] uniqueidentifier NOT NULL, + [UsageOrder] tinyint NOT NULL, + [IsOutlier] bit NOT NULL, + PRIMARY KEY ([ExpansionProfileGUID]) +); +GO +ALTER TABLE [dbo].[MEScoreExpansionProfile] ADD CONSTRAINT [FK_MEScoreExpansionProfile_EMFModelTemplate] FOREIGN KEY ([ParentModelTemplateGUID]) REFERENCES [dbo].[EMFModelTemplate] ([ModelTemplateGUID]); GO +ALTER TABLE [dbo].[MEScoreExpansionProfile] ADD CONSTRAINT [DF_MEScoreExpansionProfile_ModelTemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentModelTemplateGUID]; GO +ALTER TABLE [dbo].[MEScoreExpansionProfile] ADD CONSTRAINT [DF_MEScoreExpansionProfile_IsOutlier] DEFAULT ((0)) FOR [IsOutlier]; GO +ALTER TABLE [dbo].[MEScoreExpansionProfile] ADD CONSTRAINT [DF_MEScoreExpansionProfile_ChildModelTemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ChildModelTemplateGUID]; GO +ALTER TABLE [dbo].[MEScoreExpansionProfile] ADD CONSTRAINT [DF_MEScoreExpansionProfile_ExpansionProfileGUID] DEFAULT (newid()) FOR [ExpansionProfileGUID]; GO +ALTER TABLE [dbo].[MEScoreExpansionProfile] ADD CONSTRAINT [DF_MEScoreExpansionProfile_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[MEScoreExpansionProfile] ADD CONSTRAINT [DF_MEScoreExpansionProfile_UsageOrder] DEFAULT ((0)) FOR [UsageOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MEScoreExpansionRecommendedMaxCount ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MEScoreExpansionRecommendedMaxCount] ( + [RecommendedMaxCountID] int NOT NULL, + [SectionName] nvarchar(100) NOT NULL, + [RecommendedMaxCount] int NOT NULL, + PRIMARY KEY ([RecommendedMaxCountID]) +); +GO +ALTER TABLE [dbo].[MEScoreExpansionRecommendedMaxCount] ADD CONSTRAINT [DF_MEScoreExpansionRecommendedMaxCount_SectionName] DEFAULT ('') FOR [SectionName]; GO +ALTER TABLE [dbo].[MEScoreExpansionRecommendedMaxCount] ADD CONSTRAINT [DF_MEScoreExpansionRecommendedMaxCount_RecommendedMaxCount] DEFAULT ((0)) FOR [RecommendedMaxCount]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MEScorePlaceholderLabel ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MEScorePlaceholderLabel] ( + [CellGUID] uniqueidentifier NOT NULL, + [RowExpanded] int NOT NULL, + [SectionMemberGUID] uniqueidentifier NOT NULL, + [PHIndex] int NOT NULL, + [FillinDimensionGUID] uniqueidentifier NOT NULL, + [FillinAttributeGUID] uniqueidentifier NOT NULL, + [IsHidingRow] bit NOT NULL, + [IsHidingColumn] bit NOT NULL, + [IsUserMapped] bit NOT NULL, + [IsExpanded] bit NOT NULL, + [IsClearingRow] bit NOT NULL, + [IsClearingColumn] bit NOT NULL, + [PlaceholderLabelID] bigint NOT NULL, + PRIMARY KEY ([PlaceholderLabelID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [idx_uniquelabel] ON [dbo].[MEScorePlaceholderLabel] ([CellGUID], [RowExpanded]); +GO +ALTER TABLE [dbo].[MEScorePlaceholderLabel] ADD CONSTRAINT [FK_MEScorePlaceholderLabel_MEExcelCell] FOREIGN KEY ([CellGUID]) REFERENCES [dbo].[MEExcelCell] ([ExcelCellGUID]); GO +ALTER TABLE [dbo].[MEScorePlaceholderLabel] ADD CONSTRAINT [FK_MEScorePlaceholderLabel_ScoreAttribute] FOREIGN KEY ([FillinAttributeGUID]) REFERENCES [dbo].[ScoreAttribute] ([AttributeGUID]); GO +ALTER TABLE [dbo].[MEScorePlaceholderLabel] ADD CONSTRAINT [FK_MEScorePlaceholderLabel_ScoreDimension] FOREIGN KEY ([FillinDimensionGUID]) REFERENCES [dbo].[ScoreDimension] ([DimensionGUID]); GO +ALTER TABLE [dbo].[MEScorePlaceholderLabel] ADD CONSTRAINT [DF_MEScorePlaceholderLabel_IsHidingRow] DEFAULT ((0)) FOR [IsHidingRow]; GO +ALTER TABLE [dbo].[MEScorePlaceholderLabel] ADD CONSTRAINT [DF_MEScorePlaceholderLabel_IsHidingColumn] DEFAULT ((0)) FOR [IsHidingColumn]; GO +ALTER TABLE [dbo].[MEScorePlaceholderLabel] ADD CONSTRAINT [DF_MEScorePlaceholderLabel_IsUserMapped] DEFAULT ((0)) FOR [IsUserMapped]; GO +ALTER TABLE [dbo].[MEScorePlaceholderLabel] ADD CONSTRAINT [DF_MEScorePlaceholderLabel_IsExpanded] DEFAULT ((1)) FOR [IsExpanded]; GO +ALTER TABLE [dbo].[MEScorePlaceholderLabel] ADD CONSTRAINT [DF_MEScorePlaceholderLabel_IsClearingRow] DEFAULT ((0)) FOR [IsClearingRow]; GO +ALTER TABLE [dbo].[MEScorePlaceholderLabel] ADD CONSTRAINT [DF_MEScorePlaceholderLabel_IsClearingColumn] DEFAULT ((0)) FOR [IsClearingColumn]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MSchange_tracking_history ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MSchange_tracking_history] ( + [internal_table_name] nvarchar(128) NOT NULL, + [table_name] nvarchar(128) NOT NULL, + [start_time] datetime NOT NULL, + [end_time] datetime NOT NULL, + [rows_cleaned_up] bigint NOT NULL, + [cleanup_version] bigint NOT NULL, + [comments] nvarchar(max) NOT NULL +); + +CREATE NONCLUSTERED INDEX [IX_MSchange_tracking_history_start_time] ON [dbo].[MSchange_tracking_history] ([start_time]); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MenuItemSecurity ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MenuItemSecurity] ( + [MenuItemSecurityGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(400) NOT NULL, + PRIMARY KEY ([MenuItemSecurityGUID]) +); +GO +ALTER TABLE [dbo].[MenuItemSecurity] ADD CONSTRAINT [DF__MenuItemS__MenuI__539C6B59] DEFAULT (newid()) FOR [MenuItemSecurityGUID]; GO +ALTER TABLE [dbo].[MenuItemSecurity] ADD CONSTRAINT [DF__MenuItemSe__Name__54908F92] DEFAULT ('') FOR [Name]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MergedRoleRoles ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MergedRoleRoles] ( + [MergedRoleRolesGUID] uniqueidentifier NOT NULL, + [MergedRoleGUID] uniqueidentifier NOT NULL, + [UserRoleGuid] uniqueidentifier NOT NULL, + PRIMARY KEY ([MergedRoleGUID], [UserRoleGuid]) +); +GO +ALTER TABLE [dbo].[MergedRoleRoles] ADD CONSTRAINT [DF__MergedRol__Merge__36F3DACF] DEFAULT (newid()) FOR [MergedRoleRolesGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MergedRoles ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MergedRoles] ( + [MergedRoleGUID] uniqueidentifier NOT NULL, + [Name] varchar(100) NOT NULL, + PRIMARY KEY ([MergedRoleGUID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MobileDashboardFilterCache ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MobileDashboardFilterCache] ( + [MobileDashboardFilterCacheGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [DashboardGUID] uniqueidentifier NOT NULL, + [ParameterGUID] uniqueidentifier NOT NULL, + [Filter] nvarchar(max) NOT NULL, + [DateCreatedUTC] datetime NOT NULL, + PRIMARY KEY ([MobileDashboardFilterCacheGUID]) +); +GO +ALTER TABLE [dbo].[MobileDashboardFilterCache] ADD CONSTRAINT [DF_dbo_MobileDashboardFilterCache_DateCreatedUTC] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO +ALTER TABLE [dbo].[MobileDashboardFilterCache] ADD CONSTRAINT [DF__MobileDas__Mobil__6FFCDD62] DEFAULT (newid()) FOR [MobileDashboardFilterCacheGUID]; GO +ALTER TABLE [dbo].[MobileDashboardFilterCache] ADD CONSTRAINT [DF__MobileDas__Filte__70F1019B] DEFAULT ('') FOR [Filter]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MobileDashboardWidgetCache ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MobileDashboardWidgetCache] ( + [MobileDashboardWidgetCacheGUID] uniqueidentifier NOT NULL, + [DashboardWidgetGUID] uniqueidentifier NOT NULL, + [DesktopTemplateGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [Data] nvarchar(max) NOT NULL, + [DateCreated] datetime NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + [IsCube] bit NOT NULL, + PRIMARY KEY ([MobileDashboardWidgetCacheGUID]) +); +GO +ALTER TABLE [dbo].[MobileDashboardWidgetCache] ADD CONSTRAINT [FK__MobileDas__Dashb__7714BA9C] FOREIGN KEY ([DashboardWidgetGUID]) REFERENCES [dbo].[DashboardWidget] ([DashboardWidgetGUID]); GO +ALTER TABLE [dbo].[MobileDashboardWidgetCache] ADD CONSTRAINT [DF__MobileDas__Mobil__6F7398D4] DEFAULT (newid()) FOR [MobileDashboardWidgetCacheGUID]; GO +ALTER TABLE [dbo].[MobileDashboardWidgetCache] ADD CONSTRAINT [DF__MobileDas__Dashb__7067BD0D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DashboardWidgetGUID]; GO +ALTER TABLE [dbo].[MobileDashboardWidgetCache] ADD CONSTRAINT [DF__MobileDas__Deskt__715BE146] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DesktopTemplateGUID]; GO +ALTER TABLE [dbo].[MobileDashboardWidgetCache] ADD CONSTRAINT [DF__MobileDas__UserG__7250057F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[MobileDashboardWidgetCache] ADD CONSTRAINT [DF__MobileDash__Data__734429B8] DEFAULT ('') FOR [Data]; GO +ALTER TABLE [dbo].[MobileDashboardWidgetCache] ADD CONSTRAINT [DF__MobileDas__DateC__74384DF1] DEFAULT (getdate()) FOR [DateCreated]; GO +ALTER TABLE [dbo].[MobileDashboardWidgetCache] ADD CONSTRAINT [DF__MobileDas__DateC__752C722A] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [dbo].[MobileDashboardWidgetCache] ADD CONSTRAINT [DF__MobileDas__IsCub__76209663] DEFAULT ((0)) FOR [IsCube]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MobileSecurity ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MobileSecurity] ( + [UserGUID] uniqueidentifier NOT NULL, + [MobileSecurityGUID] uniqueidentifier NOT NULL, + [DashboardGUID] uniqueidentifier NOT NULL, + [DateCreatedUTC] datetime NOT NULL, + PRIMARY KEY ([MobileSecurityGUID]) +); +GO +ALTER TABLE [dbo].[MobileSecurity] ADD CONSTRAINT [DF_dbo_MobileSecurity_DateCreatedUTC] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO +ALTER TABLE [dbo].[MobileSecurity] ADD CONSTRAINT [DF__MobileSec__Dashb__2AB38EDC] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DashboardGUID]; GO +ALTER TABLE [dbo].[MobileSecurity] ADD CONSTRAINT [DF__MobileSec__Mobil__6C2C4C7E] DEFAULT (newid()) FOR [MobileSecurityGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ModelCacheLookup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ModelCacheLookup] ( + [ModelCacheLookupID] uniqueidentifier NOT NULL, + [ModelGuid] uniqueidentifier NULL, + [ModelCacheServer] nvarchar(400) NOT NULL, + [DateCached] datetime NOT NULL, + PRIMARY KEY ([ModelCacheLookupID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_ModelGuid] ON [dbo].[ModelCacheLookup] ([ModelGuid]); +GO +ALTER TABLE [dbo].[ModelCacheLookup] ADD CONSTRAINT [FK_ModelCacheLookup_XPlan] FOREIGN KEY ([ModelGuid]) REFERENCES [dbo].[XPlan] ([PlanGUID]); GO +ALTER TABLE [dbo].[ModelCacheLookup] ADD CONSTRAINT [DF__ModelCach__Model__33558E7C] DEFAULT (newid()) FOR [ModelCacheLookupID]; GO +ALTER TABLE [dbo].[ModelCacheLookup] ADD CONSTRAINT [DF__ModelCach__Model__3449B2B5] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGuid]; GO +ALTER TABLE [dbo].[ModelCacheLookup] ADD CONSTRAINT [DF__ModelCach__Model__353DD6EE] DEFAULT ('') FOR [ModelCacheServer]; GO +ALTER TABLE [dbo].[ModelCacheLookup] ADD CONSTRAINT [DF__ModelCach__DateC__6A7BA634] DEFAULT (getdate()) FOR [DateCached]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ModelImportExportLock ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ModelImportExportLock] ( + [ModelImportExportLockGuid] uniqueidentifier NOT NULL, + [PlanGuid] uniqueidentifier NOT NULL, + [UserGuid] uniqueidentifier NOT NULL, + [UserName] nvarchar(max) NOT NULL, + [DateExportedUtc] datetime NOT NULL, + [DateImportedUtc] datetime NOT NULL, + [IsImported] bit NOT NULL, + PRIMARY KEY ([ModelImportExportLockGuid]) +); +GO +ALTER TABLE [dbo].[ModelImportExportLock] ADD CONSTRAINT [FK__ModelImpo__PlanG__44D4EA40] FOREIGN KEY ([PlanGuid]) REFERENCES [dbo].[XPlan] ([PlanGUID]); GO +ALTER TABLE [dbo].[ModelImportExportLock] ADD CONSTRAINT [DF__ModelImpo__Model__43E0C607] DEFAULT (newid()) FOR [ModelImportExportLockGuid]; GO +ALTER TABLE [dbo].[ModelImportExportLock] ADD CONSTRAINT [DF__ModelImpo__UserG__45C90E79] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGuid]; GO +ALTER TABLE [dbo].[ModelImportExportLock] ADD CONSTRAINT [DF__ModelImpo__UserN__46BD32B2] DEFAULT ('') FOR [UserName]; GO +ALTER TABLE [dbo].[ModelImportExportLock] ADD CONSTRAINT [DF__ModelImpo__DateE__47B156EB] DEFAULT (getutcdate()) FOR [DateExportedUtc]; GO +ALTER TABLE [dbo].[ModelImportExportLock] ADD CONSTRAINT [DF__ModelImpo__DateI__48A57B24] DEFAULT (getutcdate()) FOR [DateImportedUtc]; GO +ALTER TABLE [dbo].[ModelImportExportLock] ADD CONSTRAINT [DF__ModelImpo__IsImp__49999F5D] DEFAULT ((0)) FOR [IsImported]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ModelSection ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ModelSection] ( + [ModelSectionGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(400) NOT NULL, + [Range] nvarchar(400) NOT NULL, + [Address] nvarchar(400) NOT NULL, + [SheetGUID] uniqueidentifier NOT NULL, + [ParentGUID] uniqueidentifier NOT NULL, + [SortOrder] int NOT NULL, + [IsInherit] bit NOT NULL, + [IsHidden] bit NOT NULL, + PRIMARY KEY ([ModelSectionGUID]) +); + +CREATE NONCLUSTERED INDEX [IX_ModelSection_SheetGUID] ON [dbo].[ModelSection] ([SheetGUID]); +GO +ALTER TABLE [dbo].[ModelSection] ADD CONSTRAINT [DF__ModelSect__Model__46535457] DEFAULT (newid()) FOR [ModelSectionGUID]; GO +ALTER TABLE [dbo].[ModelSection] ADD CONSTRAINT [DF__ModelSecti__Name__47477890] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[ModelSection] ADD CONSTRAINT [DF__ModelSect__Range__483B9CC9] DEFAULT ('') FOR [Range]; GO +ALTER TABLE [dbo].[ModelSection] ADD CONSTRAINT [DF__ModelSect__Addre__492FC102] DEFAULT ('') FOR [Address]; GO +ALTER TABLE [dbo].[ModelSection] ADD CONSTRAINT [DF__ModelSect__Sheet__4A23E53B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SheetGUID]; GO +ALTER TABLE [dbo].[ModelSection] ADD CONSTRAINT [DF__ModelSect__Paren__4B180974] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentGUID]; GO +ALTER TABLE [dbo].[ModelSection] ADD CONSTRAINT [DF__ModelSect__SortO__4C0C2DAD] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [dbo].[ModelSection] ADD CONSTRAINT [DF__ModelSect__IsInh__4D0051E6] DEFAULT ((1)) FOR [IsInherit]; GO +ALTER TABLE [dbo].[ModelSection] ADD CONSTRAINT [DF__ModelSect__IsHid__4DF4761F] DEFAULT ((0)) FOR [IsHidden]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MsgAttachment ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MsgAttachment] ( + [AttachmentGUID] uniqueidentifier NOT NULL, + [MessageGUID] uniqueidentifier NOT NULL, + [Filename] nvarchar(64) NOT NULL, + [FileSize] int NOT NULL, + [FileDirectory] nvarchar(450) NOT NULL, + PRIMARY KEY ([AttachmentGUID]) +); +GO +ALTER TABLE [dbo].[MsgAttachment] ADD CONSTRAINT [FK_MsgAttachment_MsgMessage] FOREIGN KEY ([MessageGUID]) REFERENCES [dbo].[MsgMessage] ([MessageGUID]); GO +ALTER TABLE [dbo].[MsgAttachment] ADD CONSTRAINT [DF_MsgAttachment_ATTACHMENTGUID] DEFAULT (newid()) FOR [AttachmentGUID]; GO +ALTER TABLE [dbo].[MsgAttachment] ADD CONSTRAINT [DF_MsgAttachment_MESSAGEGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [MessageGUID]; GO +ALTER TABLE [dbo].[MsgAttachment] ADD CONSTRAINT [DF_MsgAttachment_FILENAME] DEFAULT ('') FOR [Filename]; GO +ALTER TABLE [dbo].[MsgAttachment] ADD CONSTRAINT [DF_MsgAttachment_FILESIZE] DEFAULT ((0)) FOR [FileSize]; GO +ALTER TABLE [dbo].[MsgAttachment] ADD CONSTRAINT [DF_MsgAttachment_FILEDIRECTORY] DEFAULT ('') FOR [FileDirectory]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MsgBookmark ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MsgBookmark] ( + [BookmarkGUID] uniqueidentifier NOT NULL, + [ForumGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([BookmarkGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [ak_bookmarkforumuser] ON [dbo].[MsgBookmark] ([ForumGUID], [UserGUID]); +GO +ALTER TABLE [dbo].[MsgBookmark] ADD CONSTRAINT [FK_MsgBookmark_MsgForum] FOREIGN KEY ([ForumGUID]) REFERENCES [dbo].[MsgForum] ([ForumGUID]); GO +ALTER TABLE [dbo].[MsgBookmark] ADD CONSTRAINT [FK_MsgBookmark_UserProfile] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO +ALTER TABLE [dbo].[MsgBookmark] ADD CONSTRAINT [DF_MsgBookmark_BOOKMARKGUID] DEFAULT (newid()) FOR [BookmarkGUID]; GO +ALTER TABLE [dbo].[MsgBookmark] ADD CONSTRAINT [DF_MsgBookmark_FORUMGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [ForumGUID]; GO +ALTER TABLE [dbo].[MsgBookmark] ADD CONSTRAINT [DF_MsgBookmark_USERGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [UserGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MsgEmailActivity ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MsgEmailActivity] ( + [EmailActivityID] bigint NOT NULL, + [EmailSummaryID] int NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [EmailAddress] nvarchar(450) NOT NULL, + [MessageGUID] uniqueidentifier NOT NULL, + [Timestamp] datetime NOT NULL, + [IsSuccess] bit NOT NULL, + [Description] nvarchar(max) NOT NULL, + [ErrorLogGUID] uniqueidentifier NOT NULL, + [DateCreated] datetime NOT NULL, + PRIMARY KEY ([EmailActivityID]) +); + +CREATE NONCLUSTERED INDEX [NCNU_Timestamp_Index] ON [dbo].[MsgEmailActivity] ([Timestamp]); +GO +ALTER TABLE [dbo].[MsgEmailActivity] ADD CONSTRAINT [FK_MsgEmailActivity_MsgEmailSummary] FOREIGN KEY ([EmailSummaryID]) REFERENCES [dbo].[MsgEmailSummary] ([EmailSummaryID]); GO +ALTER TABLE [dbo].[MsgEmailActivity] ADD CONSTRAINT [DF__MsgEmailA__Messa__4F1A1392] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MessageGUID]; GO +ALTER TABLE [dbo].[MsgEmailActivity] ADD CONSTRAINT [DF_MsgEmailActivity_LogGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ErrorLogGUID]; GO +ALTER TABLE [dbo].[MsgEmailActivity] ADD CONSTRAINT [DF_MsgEmailActivity_DateCreated] DEFAULT (getdate()) FOR [DateCreated]; GO +ALTER TABLE [dbo].[MsgEmailActivity] ADD CONSTRAINT [DF__MsgEmailA__Email__4C3DA6E7] DEFAULT ((0)) FOR [EmailSummaryID]; GO +ALTER TABLE [dbo].[MsgEmailActivity] ADD CONSTRAINT [DF__MsgEmailA__Email__4E25EF59] DEFAULT ('') FOR [EmailAddress]; GO +ALTER TABLE [dbo].[MsgEmailActivity] ADD CONSTRAINT [DF__MsgEmailA__Times__500E37CB] DEFAULT (getdate()) FOR [Timestamp]; GO +ALTER TABLE [dbo].[MsgEmailActivity] ADD CONSTRAINT [DF__MsgEmailA__IsSuc__51025C04] DEFAULT ((0)) FOR [IsSuccess]; GO +ALTER TABLE [dbo].[MsgEmailActivity] ADD CONSTRAINT [DF_MsgEmailActivity_Description] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[MsgEmailActivity] ADD CONSTRAINT [DF__MsgEmailA__UserG__4D31CB20] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MsgEmailSummary ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MsgEmailSummary] ( + [EmailSummaryID] int NOT NULL, + [Timestamp] datetime NOT NULL, + [IsSuccess] bit NOT NULL, + PRIMARY KEY ([EmailSummaryID]) +); + +CREATE NONCLUSTERED INDEX [NCNU_Timestamp_Index] ON [dbo].[MsgEmailSummary] ([Timestamp]); +GO +ALTER TABLE [dbo].[MsgEmailSummary] ADD CONSTRAINT [DF__MsgEmailS__Times__52EAA476] DEFAULT (getdate()) FOR [Timestamp]; GO +ALTER TABLE [dbo].[MsgEmailSummary] ADD CONSTRAINT [DF__MsgEmailS__IsSuc__53DEC8AF] DEFAULT ((0)) FOR [IsSuccess]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MsgForum ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MsgForum] ( + [ForumGUID] uniqueidentifier NOT NULL, + [EntityGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(450) NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [ForumType] int NOT NULL, + PRIMARY KEY ([ForumGUID]) +); +GO +ALTER TABLE [dbo].[MsgForum] ADD CONSTRAINT [DF_MsgForum_FORUMGUID] DEFAULT (newid()) FOR [ForumGUID]; GO +ALTER TABLE [dbo].[MsgForum] ADD CONSTRAINT [DF_MsgForum_ENTITYGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [EntityGUID]; GO +ALTER TABLE [dbo].[MsgForum] ADD CONSTRAINT [DF_MsgForum_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[MsgForum] ADD CONSTRAINT [DF_MsgForum_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[MsgForum] ADD CONSTRAINT [DF_MsgForum_FORUMTYPE] DEFAULT ((0)) FOR [ForumType]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MsgForumRead ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MsgForumRead] ( + [ForumReadGUID] uniqueidentifier NOT NULL, + [ForumGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [DateViewed] datetime NOT NULL +); + +CREATE UNIQUE NONCLUSTERED INDEX [ak_forumreadforumuser] ON [dbo].[MsgForumRead] ([ForumGUID], [UserGUID]); +GO +ALTER TABLE [dbo].[MsgForumRead] ADD CONSTRAINT [FK_MsgForumRead_MsgForum] FOREIGN KEY ([ForumGUID]) REFERENCES [dbo].[MsgForum] ([ForumGUID]); GO +ALTER TABLE [dbo].[MsgForumRead] ADD CONSTRAINT [FK_MsgForumRead_UserProfile] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO +ALTER TABLE [dbo].[MsgForumRead] ADD CONSTRAINT [DF_MsgForumRead_FORUMREADGUID] DEFAULT (newid()) FOR [ForumReadGUID]; GO +ALTER TABLE [dbo].[MsgForumRead] ADD CONSTRAINT [DF_MsgForumRead_FORUMGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [ForumGUID]; GO +ALTER TABLE [dbo].[MsgForumRead] ADD CONSTRAINT [DF_MsgForumRead_USERGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [UserGUID]; GO +ALTER TABLE [dbo].[MsgForumRead] ADD CONSTRAINT [DF_MsgForumRead_DATEVIEWED] DEFAULT (getdate()) FOR [DateViewed]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MsgForumViewed ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MsgForumViewed] ( + [UserGUID] uniqueidentifier NOT NULL, + [ForumGUID] uniqueidentifier NOT NULL, + [LastViewDate] datetime NOT NULL, + PRIMARY KEY ([UserGUID], [ForumGUID]) +); +GO +ALTER TABLE [dbo].[MsgForumViewed] ADD CONSTRAINT [DF_MsgForumViewed_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[MsgForumViewed] ADD CONSTRAINT [DF_MsgForumViewed_FORUMGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ForumGUID]; GO +ALTER TABLE [dbo].[MsgForumViewed] ADD CONSTRAINT [DF_MsgForumViewed_LASTVIEWDATE] DEFAULT (((1)-(1))-(2000)) FOR [LastViewDate]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MsgMessage ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MsgMessage] ( + [MessageGUID] uniqueidentifier NOT NULL, + [TopicGUID] uniqueidentifier NOT NULL, + [MessageTypeGUID] uniqueidentifier NOT NULL, + [ReplyToMsgGUID] uniqueidentifier NOT NULL, + [Subject] nvarchar(450) NOT NULL, + [Body] nvarchar(max) NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [DateCreated] datetime NOT NULL, + [DateSent] datetime NOT NULL, + [HasAttachments] bit NOT NULL, + [IsSent] bit NOT NULL, + PRIMARY KEY ([MessageGUID]) +); + +CREATE NONCLUSTERED INDEX [NCNU_TopicGUID] ON [dbo].[MsgMessage] ([TopicGUID]); +GO +ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [FK_MsgMessage_MsgTopic] FOREIGN KEY ([TopicGUID]) REFERENCES [dbo].[MsgTopic] ([TopicGUID]); GO +ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [DF_MsgMessage_MESSAGEGUID] DEFAULT (newid()) FOR [MessageGUID]; GO +ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [DF_MsgMessage_TOPICGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [TopicGUID]; GO +ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [DF_MsgMessage_MESSAGETYPEGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [MessageTypeGUID]; GO +ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [DF_MsgMessage_REPLYTOMSGGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [ReplyToMsgGUID]; GO +ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [DF_MsgMessage_SUBJECT] DEFAULT ('') FOR [Subject]; GO +ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [DF_MsgMessage_BODY] DEFAULT ('') FOR [Body]; GO +ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [DF_MsgMessage_AUTHORGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [AuthorGUID]; GO +ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [DF_MsgMessage_DATECREATED] DEFAULT (getdate()) FOR [DateCreated]; GO +ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [DF_MsgMessage_HASATTACHMENTS] DEFAULT ((0)) FOR [HasAttachments]; GO +ALTER TABLE [dbo].[MsgMessage] ADD CONSTRAINT [DF_MsgMessage_ISSENT] DEFAULT ((0)) FOR [IsSent]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MsgMessagePlanLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MsgMessagePlanLink] ( + [MessageGUID] uniqueidentifier NOT NULL, + [PlanGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([MessageGUID], [PlanGUID]) +); +GO +ALTER TABLE [dbo].[MsgMessagePlanLink] ADD CONSTRAINT [FK_MsgMessagePlanLink_MsgMessage] FOREIGN KEY ([MessageGUID]) REFERENCES [dbo].[MsgMessage] ([MessageGUID]); GO +ALTER TABLE [dbo].[MsgMessagePlanLink] ADD CONSTRAINT [DF_MsgMessagePlanLink_MESSAGEGUID] DEFAULT (newid()) FOR [MessageGUID]; GO +ALTER TABLE [dbo].[MsgMessagePlanLink] ADD CONSTRAINT [DF_MsgMessagePlanLink_PLANGUID] DEFAULT (newid()) FOR [PlanGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MsgMessageRead ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MsgMessageRead] ( + [UserGUID] uniqueidentifier NOT NULL, + [MessageGUID] uniqueidentifier NOT NULL, + [IsRead] bit NOT NULL, + [DateRead] datetime NOT NULL, + PRIMARY KEY ([UserGUID], [MessageGUID]) +); +GO +ALTER TABLE [dbo].[MsgMessageRead] ADD CONSTRAINT [FK_MsgMessageRead_MsgMessage] FOREIGN KEY ([MessageGUID]) REFERENCES [dbo].[MsgMessage] ([MessageGUID]); GO +ALTER TABLE [dbo].[MsgMessageRead] ADD CONSTRAINT [FK_MsgMessageRead_UserProfile] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO +ALTER TABLE [dbo].[MsgMessageRead] ADD CONSTRAINT [DF_MsgMessageRead_USERGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [UserGUID]; GO +ALTER TABLE [dbo].[MsgMessageRead] ADD CONSTRAINT [DF_MsgMessageRead_MESSAGEGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [MessageGUID]; GO +ALTER TABLE [dbo].[MsgMessageRead] ADD CONSTRAINT [DF_MsgMessageRead_ISUNREAD] DEFAULT ((1)) FOR [IsRead]; GO +ALTER TABLE [dbo].[MsgMessageRead] ADD CONSTRAINT [DF_MsgMessageRead_DATEREAD] DEFAULT (((1)-(1))-(2000)) FOR [DateRead]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MsgMessageType ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MsgMessageType] ( + [MessageTypeGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Description] nvarchar(450) NOT NULL, + [ImageType] int NOT NULL, + [LinkType] int NOT NULL, + [Type] int NOT NULL, + [SubjectPrefix] nvarchar(64) NOT NULL, + [Header] nvarchar(max) NOT NULL, + [Footer] nvarchar(max) NOT NULL, + [BuiltInType] int NOT NULL, + [IsAllowingReplyViaEmail] bit NOT NULL, + [IsMarkingReadForNewMessages] bit NOT NULL, + [IsVisible] bit NOT NULL, + PRIMARY KEY ([MessageTypeGUID]) +); +GO +ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_MESSAGETYPEGUID] DEFAULT (newid()) FOR [MessageTypeGUID]; GO +ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_ICONNAME] DEFAULT ((0)) FOR [ImageType]; GO +ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_LINKTYPE] DEFAULT ((0)) FOR [LinkType]; GO +ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_TYPE] DEFAULT ((0)) FOR [Type]; GO +ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_SUBJECTPREFIX] DEFAULT ('') FOR [SubjectPrefix]; GO +ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_HEADER] DEFAULT ('') FOR [Header]; GO +ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_FOOTER] DEFAULT ('') FOR [Footer]; GO +ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_BuiltInType] DEFAULT ((0)) FOR [BuiltInType]; GO +ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_IsVisible] DEFAULT ((1)) FOR [IsVisible]; GO +ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_IsMarkingReadForNewMessages] DEFAULT ((0)) FOR [IsMarkingReadForNewMessages]; GO +ALTER TABLE [dbo].[MsgMessageType] ADD CONSTRAINT [DF_MsgMessageType_IsAllowingReplyViaEmail] DEFAULT ((0)) FOR [IsAllowingReplyViaEmail]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MsgTopic ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MsgTopic] ( + [TopicGUID] uniqueidentifier NOT NULL, + [ForumGUID] uniqueidentifier NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(450) NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [TopicType] int NOT NULL, + [DateCreated] datetime NOT NULL, + [Tag] nvarchar(450) NOT NULL, + PRIMARY KEY ([TopicGUID]) +); +GO +ALTER TABLE [dbo].[MsgTopic] ADD CONSTRAINT [DF_MsgTopic_TOPICGUID] DEFAULT (newid()) FOR [TopicGUID]; GO +ALTER TABLE [dbo].[MsgTopic] ADD CONSTRAINT [DF_MsgTopic_FORUMGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [ForumGUID]; GO +ALTER TABLE [dbo].[MsgTopic] ADD CONSTRAINT [DF_MsgTopic_AUTHORGUID] DEFAULT ('{00000000-0000-0000-0000-000000000000}') FOR [AuthorGUID]; GO +ALTER TABLE [dbo].[MsgTopic] ADD CONSTRAINT [DF_MsgTopic_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[MsgTopic] ADD CONSTRAINT [DF_MsgTopic_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[MsgTopic] ADD CONSTRAINT [DF_MsgTopic_TOPICTYPE] DEFAULT ((0)) FOR [TopicType]; GO +ALTER TABLE [dbo].[MsgTopic] ADD CONSTRAINT [DF_MsgTopic_DATECREATED] DEFAULT (getdate()) FOR [DateCreated]; GO +ALTER TABLE [dbo].[MsgTopic] ADD CONSTRAINT [DF_MsgTopic_Tag] DEFAULT ('') FOR [Tag]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.MsgTopicArchive ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[MsgTopicArchive] ( + [UserGUID] uniqueidentifier NOT NULL, + [TopicGUID] uniqueidentifier NOT NULL, + [DateArchived] datetime NOT NULL, + PRIMARY KEY ([UserGUID], [TopicGUID]) +); + +CREATE NONCLUSTERED INDEX [NCNU_TopicGUID_UserGUID] ON [dbo].[MsgTopicArchive] ([TopicGUID], [UserGUID]); +GO +ALTER TABLE [dbo].[MsgTopicArchive] ADD CONSTRAINT [FK_MsgTopicArchive_UserProfile] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO +ALTER TABLE [dbo].[MsgTopicArchive] ADD CONSTRAINT [DF_MsgTopicArchive_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[MsgTopicArchive] ADD CONSTRAINT [DF_MsgTopicArchive_TopicGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TopicGUID]; GO +ALTER TABLE [dbo].[MsgTopicArchive] ADD CONSTRAINT [DF_MsgTopicArchive_DateArchived] DEFAULT ('1/1/1900') FOR [DateArchived]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.OMZCriterion ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[OMZCriterion] ( + [CriterionGUID] uniqueidentifier NOT NULL, + [ProviderSettingsGUID] uniqueidentifier NOT NULL, + [DimensionMemberGUID] uniqueidentifier NOT NULL, + [CriterionType] int NOT NULL, + [WeightingType] int NOT NULL, + [FormFieldGUID] uniqueidentifier NOT NULL +); +GO +ALTER TABLE [dbo].[OMZCriterion] ADD CONSTRAINT [DF_OMZCriterion_PROVIDERSETTINGSGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ProviderSettingsGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.OMZEvaluatorStatus ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[OMZEvaluatorStatus] ( + [EvaluatorStatusGUID] uniqueidentifier NOT NULL, + [PoolGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [Type] int NOT NULL, + [Status] int NOT NULL, + PRIMARY KEY ([EvaluatorStatusGUID]) +); +GO +ALTER TABLE [dbo].[OMZEvaluatorStatus] ADD CONSTRAINT [FK_OMZEvaluatorStatus_OMZPool] FOREIGN KEY ([PoolGUID]) REFERENCES [dbo].[OMZPool] ([PoolGUID]); GO +ALTER TABLE [dbo].[OMZEvaluatorStatus] ADD CONSTRAINT [DF_Table_1_POOLEVALUATORSTATUSGUID] DEFAULT (newid()) FOR [EvaluatorStatusGUID]; GO +ALTER TABLE [dbo].[OMZEvaluatorStatus] ADD CONSTRAINT [DF_OMZEvaluatorStatus_POOLGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PoolGUID]; GO +ALTER TABLE [dbo].[OMZEvaluatorStatus] ADD CONSTRAINT [DF_OMZEvaluatorStatus_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[OMZEvaluatorStatus] ADD CONSTRAINT [DF_OMZEvaluatorStatus_TYPE] DEFAULT ((0)) FOR [Type]; GO +ALTER TABLE [dbo].[OMZEvaluatorStatus] ADD CONSTRAINT [DF_OMZEvaluatorStatus_STATUS] DEFAULT ((0)) FOR [Status]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.OMZMapping ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[OMZMapping] ( + [MappingGUID] uniqueidentifier NOT NULL, + [Category] nvarchar(64) NOT NULL, + [ParentGUID] uniqueidentifier NOT NULL, + [SourceGUID] uniqueidentifier NOT NULL, + [TargetGUID] uniqueidentifier NOT NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.OMZPool ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[OMZPool] ( + [PoolGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [ProviderSettingsGUID] uniqueidentifier NOT NULL, + [PoolDimensionMemberGUID] uniqueidentifier NOT NULL, + [Metadata] xml(max) NOT NULL, + [ApprovedFormFieldGUID] uniqueidentifier NOT NULL, + [PlanTypeGUID] uniqueidentifier NOT NULL, + [IsUsingFinancialReturn] bit NOT NULL, + [ScoringReportGUID] uniqueidentifier NOT NULL, + [LastDistributeDate] datetime NOT NULL, + [IsScoringLocked] bit NOT NULL, + [ProjectTypeID] tinyint NOT NULL, + PRIMARY KEY ([PoolGUID]) +); +GO +ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_OPTIMIZATIONPOOLGUID] DEFAULT (newid()) FOR [PoolGUID]; GO +ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_INPUTDATACONFIGGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ProviderSettingsGUID]; GO +ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_POOLDIMENSIONMEMBERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PoolDimensionMemberGUID]; GO +ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_METADATA] DEFAULT ('') FOR [Metadata]; GO +ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_APPROVEDFORMFIELDGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ApprovedFormFieldGUID]; GO +ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_ProjectTypeID] DEFAULT ((1)) FOR [ProjectTypeID]; GO +ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_IsUsingFinancialReturn] DEFAULT ((1)) FOR [IsUsingFinancialReturn]; GO +ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_LastDistributeDate] DEFAULT ('2000-01-01 00:00:00.000') FOR [LastDistributeDate]; GO +ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_IsScoringLocked] DEFAULT ((0)) FOR [IsScoringLocked]; GO +ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO +ALTER TABLE [dbo].[OMZPool] ADD CONSTRAINT [DF_OMZPool_ScoringReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScoringReportGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.OMZProviderSettings ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[OMZProviderSettings] ( + [ProviderSettingsGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [AssemblyQualifiedName] nvarchar(450) NOT NULL, + [Metadata] xml(max) NOT NULL, + [ProviderAssemblyQualifiedName] nvarchar(450) NOT NULL, + [PoolDimensionGUID] uniqueidentifier NOT NULL, + [DefaultEvaluatorRoleGUID] uniqueidentifier NOT NULL, + [DefaultGridTemplateGUID] uniqueidentifier NOT NULL, + [DefaultApprovedFieldGUID] uniqueidentifier NOT NULL, + [DefaultScoringReportGUID] uniqueidentifier NOT NULL, + [DefaultPlanTypeGUID] uniqueidentifier NOT NULL, + [IsActive] bit NOT NULL, + PRIMARY KEY ([ProviderSettingsGUID]) +); +GO +ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_METADATA] DEFAULT ('') FOR [Metadata]; GO +ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_PROVIDERASSEMBLYQUALIFIEDNAME] DEFAULT ('') FOR [ProviderAssemblyQualifiedName]; GO +ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_POOLDIMENSIONGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PoolDimensionGUID]; GO +ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_DefaultScoringReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultScoringReportGUID]; GO +ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_DefaultPlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultPlanTypeGUID]; GO +ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_IsActive] DEFAULT ((1)) FOR [IsActive]; GO +ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_DefaultEvaluatorRoleGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultEvaluatorRoleGUID]; GO +ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_DefaultGridTemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultGridTemplateGUID]; GO +ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_DefaultApprovedFieldGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultApprovedFieldGUID]; GO +ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_PROVIDERSETTINGSGUID] DEFAULT (newid()) FOR [ProviderSettingsGUID]; GO +ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[OMZProviderSettings] ADD CONSTRAINT [DF_OMZProviderSettings_ASSEMBLYQUALIFIEDNAME] DEFAULT ('') FOR [AssemblyQualifiedName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.OMZScenario ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[OMZScenario] ( + [ScenarioGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [PoolGUID] uniqueidentifier NOT NULL, + [Metadata] xml(max) NOT NULL, + PRIMARY KEY ([ScenarioGUID]) +); +GO +ALTER TABLE [dbo].[OMZScenario] ADD CONSTRAINT [DF_OMZScenario_Description] DEFAULT ('') FOR [Description]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.OMZWorkspaceColumn ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[OMZWorkspaceColumn] ( + [WorkspaceColumnGUID] uniqueidentifier NOT NULL, + [WorkspaceTabGUID] uniqueidentifier NOT NULL, + [ColumnID] nvarchar(64) NOT NULL, + [ColumnIndex] int NOT NULL, + [Width] int NOT NULL, + [IsVisible] bit NOT NULL, + [IsTotal] bit NOT NULL, + PRIMARY KEY ([WorkspaceColumnGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_OMZWorkspaceColumn] ON [dbo].[OMZWorkspaceColumn] ([WorkspaceTabGUID], [ColumnID]); +GO +ALTER TABLE [dbo].[OMZWorkspaceColumn] ADD CONSTRAINT [FK_OMZWorkspaceColumn_OMZWorkspaceTab] FOREIGN KEY ([WorkspaceTabGUID]) REFERENCES [dbo].[OMZWorkspaceTab] ([WorkspaceTabGUID]); GO +ALTER TABLE [dbo].[OMZWorkspaceColumn] ADD CONSTRAINT [DF_Table_1_WORKSPACETABCOLUMNGUID] DEFAULT (newid()) FOR [WorkspaceColumnGUID]; GO +ALTER TABLE [dbo].[OMZWorkspaceColumn] ADD CONSTRAINT [DF_OMZWorkspaceColumn_WORKSPACETABGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkspaceTabGUID]; GO +ALTER TABLE [dbo].[OMZWorkspaceColumn] ADD CONSTRAINT [DF_OMZWorkspaceColumn_COLUMNID] DEFAULT ('') FOR [ColumnID]; GO +ALTER TABLE [dbo].[OMZWorkspaceColumn] ADD CONSTRAINT [DF_OMZWorkspaceColumn_INDEX] DEFAULT ((-1)) FOR [ColumnIndex]; GO +ALTER TABLE [dbo].[OMZWorkspaceColumn] ADD CONSTRAINT [DF_OMZWorkspaceColumn_WIDTH] DEFAULT ((-1)) FOR [Width]; GO +ALTER TABLE [dbo].[OMZWorkspaceColumn] ADD CONSTRAINT [DF_OMZWorkspaceColumn_ISVISIBLE] DEFAULT ((0)) FOR [IsVisible]; GO +ALTER TABLE [dbo].[OMZWorkspaceColumn] ADD CONSTRAINT [DF_OMZWorkspaceColumn_ISTOTAL] DEFAULT ((0)) FOR [IsTotal]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.OMZWorkspaceLayout ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[OMZWorkspaceLayout] ( + [WorkspaceLayoutGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [ProviderAssemblyQualifiedName] nvarchar(450) NOT NULL, + [LayoutXML] nvarchar(max) NOT NULL, + [IsFlyoutCollapsed] bit NOT NULL, + PRIMARY KEY ([WorkspaceLayoutGUID]) +); +GO +ALTER TABLE [dbo].[OMZWorkspaceLayout] ADD CONSTRAINT [DF_OMZWorkspaceLayout_IsFlyoutCollapsed] DEFAULT ((0)) FOR [IsFlyoutCollapsed]; GO +ALTER TABLE [dbo].[OMZWorkspaceLayout] ADD CONSTRAINT [DF_OMZWorkspaceLayout_WORKSPACELAYOUTGUID] DEFAULT (newid()) FOR [WorkspaceLayoutGUID]; GO +ALTER TABLE [dbo].[OMZWorkspaceLayout] ADD CONSTRAINT [DF_OMZWorkspaceLayout_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[OMZWorkspaceLayout] ADD CONSTRAINT [DF_OMZWorkspaceLayout_PROVIDERASSEMBLYQUALIFIEDNAME] DEFAULT ('') FOR [ProviderAssemblyQualifiedName]; GO +ALTER TABLE [dbo].[OMZWorkspaceLayout] ADD CONSTRAINT [DF_OMZWorkspaceLayout_LAYOUTXML] DEFAULT ('') FOR [LayoutXML]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.OMZWorkspacePanel ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[OMZWorkspacePanel] ( + [WorkspacePanelGUID] uniqueidentifier NOT NULL, + [WorkspaceLayoutGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + PRIMARY KEY ([WorkspacePanelGUID]) +); +GO +ALTER TABLE [dbo].[OMZWorkspacePanel] ADD CONSTRAINT [FK_OMZWorkspacePanel_OMZWorkspaceLayout] FOREIGN KEY ([WorkspaceLayoutGUID]) REFERENCES [dbo].[OMZWorkspaceLayout] ([WorkspaceLayoutGUID]); GO +ALTER TABLE [dbo].[OMZWorkspacePanel] ADD CONSTRAINT [DF_OMZWorkspacePanel_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[OMZWorkspacePanel] ADD CONSTRAINT [DF_OMZWorkspacePanel_WORKSPACEPANELGUID] DEFAULT (newid()) FOR [WorkspacePanelGUID]; GO +ALTER TABLE [dbo].[OMZWorkspacePanel] ADD CONSTRAINT [DF_OMZWorkspacePanel_WORKSPACELAYOUTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkspaceLayoutGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.OMZWorkspaceTab ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[OMZWorkspaceTab] ( + [WorkspaceTabGUID] uniqueidentifier NOT NULL, + [WorkspacePanelGUID] uniqueidentifier NOT NULL, + [ViewID] nvarchar(64) NOT NULL, + [NumFrozenColumns] int NOT NULL, + [PrimarySortColumnID] nvarchar(450) NOT NULL, + [SecondarySortColumnID] nvarchar(450) NOT NULL, + [PrimarySortDirection] int NOT NULL, + [SecondarySortDirection] int NOT NULL, + PRIMARY KEY ([WorkspaceTabGUID]) +); +GO +ALTER TABLE [dbo].[OMZWorkspaceTab] ADD CONSTRAINT [FK_OMZWorkspaceTab_OMZWorkspacePanel] FOREIGN KEY ([WorkspacePanelGUID]) REFERENCES [dbo].[OMZWorkspacePanel] ([WorkspacePanelGUID]); GO +ALTER TABLE [dbo].[OMZWorkspaceTab] ADD CONSTRAINT [DF_OMZWorkspaceTab_WORKSPACETABGUID] DEFAULT (newid()) FOR [WorkspaceTabGUID]; GO +ALTER TABLE [dbo].[OMZWorkspaceTab] ADD CONSTRAINT [DF_OMZWorkspaceTab_WORKSPACEPANELGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkspacePanelGUID]; GO +ALTER TABLE [dbo].[OMZWorkspaceTab] ADD CONSTRAINT [DF_OMZWorkspaceTab_VIEWID] DEFAULT ('') FOR [ViewID]; GO +ALTER TABLE [dbo].[OMZWorkspaceTab] ADD CONSTRAINT [DF_OMZWorkspaceTab_NUMFROZENCOLUMNS] DEFAULT ((0)) FOR [NumFrozenColumns]; GO +ALTER TABLE [dbo].[OMZWorkspaceTab] ADD CONSTRAINT [DF_OMZWorkspaceTab_SORTCOLUMNID] DEFAULT ('') FOR [PrimarySortColumnID]; GO +ALTER TABLE [dbo].[OMZWorkspaceTab] ADD CONSTRAINT [DF_OMZWorkspaceTab_SECONDARYSORTCOLUMNID] DEFAULT ('') FOR [SecondarySortColumnID]; GO +ALTER TABLE [dbo].[OMZWorkspaceTab] ADD CONSTRAINT [DF_OMZWorkspaceTab_PRIMARYSORTDIRECTION] DEFAULT ((0)) FOR [PrimarySortDirection]; GO +ALTER TABLE [dbo].[OMZWorkspaceTab] ADD CONSTRAINT [DF_OMZWorkspaceTab_SECONDARYSORTDIRECTION] DEFAULT ((0)) FOR [SecondarySortDirection]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.PHILogExtractHistory ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[PHILogExtractHistory] ( + [ExtractID] int NOT NULL, + [UserName] nvarchar(128) NOT NULL, + [DateTimeStampUtc] datetime NOT NULL, + [StartDate] datetime NOT NULL, + [EndDate] datetime NOT NULL, + [ExtractReason] nvarchar(255) NOT NULL, + [Status] tinyint NOT NULL, + PRIMARY KEY ([ExtractID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.PartitionInfo ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[PartitionInfo] ( + [DatabaseID] varchar(200) NOT NULL, + [CubeID] varchar(200) NOT NULL, + [MeasureGroupID] varchar(400) NOT NULL, + [PartitionID] varchar(400) NOT NULL, + [PartitionName] varchar(400) NOT NULL, + [QueryDefinition] varchar(4000) NOT NULL, + [Filter] varchar(2000) NULL, + [Dirty] bit NULL, + [Version] varchar(200) NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.PasswordHistory ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[PasswordHistory] ( + [HistoryID] bigint NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [HashedPassword] nvarchar(64) NOT NULL, + [Iteration] tinyint NOT NULL, + PRIMARY KEY ([HistoryID]) +); +GO +ALTER TABLE [dbo].[PasswordHistory] ADD CONSTRAINT [DF_PasswordHistory_HashedPassword] DEFAULT ('') FOR [HashedPassword]; GO +ALTER TABLE [dbo].[PasswordHistory] ADD CONSTRAINT [DF_PasswordHistory_Iteration] DEFAULT ((0)) FOR [Iteration]; GO +ALTER TABLE [dbo].[PasswordHistory] ADD CONSTRAINT [DF_PasswordHistory_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.PlanPrint ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[PlanPrint] ( + [PlanPrintGuid] uniqueidentifier NOT NULL, + [FileName] nvarchar(200) NOT NULL, + [FilePath] nvarchar(400) NOT NULL, + [DateCreated] datetime NOT NULL, + [UserGuid] uniqueidentifier NOT NULL, + [FileSize] int NOT NULL, + [PlanNames] nvarchar(max) NOT NULL, + PRIMARY KEY ([PlanPrintGuid]) +); +GO +ALTER TABLE [dbo].[PlanPrint] ADD CONSTRAINT [DF__PlanPrint__PlanP__5D1B8228] DEFAULT (newid()) FOR [PlanPrintGuid]; GO +ALTER TABLE [dbo].[PlanPrint] ADD CONSTRAINT [DF__PlanPrint__FileN__5E0FA661] DEFAULT ('') FOR [FileName]; GO +ALTER TABLE [dbo].[PlanPrint] ADD CONSTRAINT [DF__PlanPrint__FileP__5F03CA9A] DEFAULT ('') FOR [FilePath]; GO +ALTER TABLE [dbo].[PlanPrint] ADD CONSTRAINT [DF__PlanPrint__DateC__5FF7EED3] DEFAULT ('') FOR [DateCreated]; GO +ALTER TABLE [dbo].[PlanPrint] ADD CONSTRAINT [DF__PlanPrint__UserG__60EC130C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGuid]; GO +ALTER TABLE [dbo].[PlanPrint] ADD CONSTRAINT [DF__PlanPrint__FileS__61E03745] DEFAULT ((0)) FOR [FileSize]; GO +ALTER TABLE [dbo].[PlanPrint] ADD CONSTRAINT [DF__PlanPrint__PlanN__62D45B7E] DEFAULT ('') FOR [PlanNames]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.PlanType ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[PlanType] ( + [PlanTypeGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(256) NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [FolderGUID] uniqueidentifier NOT NULL, + [ModelDataConfigGUID] uniqueidentifier NOT NULL, + [GridTemplateGUID] uniqueidentifier NOT NULL, + [DisplayOrder] int NOT NULL, + [IsPermissionCopyEnabled] bit NOT NULL, + [NameFormFieldGUID] uniqueidentifier NOT NULL, + [WorkflowGridTemplateGUID] uniqueidentifier NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + [OnSaveCustomScriptGUID] uniqueidentifier NOT NULL, + [OnSaveCustomScript2GUID] uniqueidentifier NOT NULL, + [OnTemplateChangeCustomScriptGUID] uniqueidentifier NOT NULL, + [ScoreDefaultFillInTemplateName] nvarchar(100) NOT NULL, + [DefaultMessageSubject] nvarchar(450) NOT NULL, + [FriendlyName] nvarchar(256) NOT NULL, + [OnAfterModelRefreshCustomScriptGUID] uniqueidentifier NOT NULL, + [LootIDSQLExpression] nvarchar(450) NOT NULL, + [OnCopyCustomScriptGUID] uniqueidentifier NOT NULL, + [IsSimpleRoutingSlip] bit NOT NULL, + [AssumptionInputNameFormat] nvarchar(450) NOT NULL, + [AssumptionOutputNameFormat] nvarchar(450) NOT NULL, + [OpenPlanUrl] nvarchar(100) NOT NULL, + [GlobalID] nvarchar(100) NOT NULL, + [IsSavingNewWay] bit NOT NULL, + [FinancialsAlias] nvarchar(100) NOT NULL, + [AllowPublicAttachment] bit NOT NULL, + [OnModelSaveCustomScriptGUID] uniqueidentifier NOT NULL, + [DefaultModelTemplateGUID] uniqueidentifier NOT NULL, + [HelpID] nvarchar(400) NOT NULL, + [FormHelpID] nvarchar(50) NOT NULL, + [IsSystemSetFillinEditable] bit NOT NULL, + [IsModelRefreshEnabled] bit NOT NULL, + [IsBulkDeleteAllowed] bit NOT NULL, + PRIMARY KEY ([PlanTypeGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_PlanType] ON [dbo].[PlanType] ([Name]); +CREATE NONCLUSTERED INDEX [NCNU_PlanTypeGUID] ON [dbo].[PlanType] ([PlanTypeGUID]); +GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [FK_PlanType_Folder] FOREIGN KEY ([FolderGUID]) REFERENCES [dbo].[Folder] ([FolderGuid]); GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_LootIDSQLExpression] DEFAULT ('') FOR [LootIDSQLExpression]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__IsMode__14442DAF] DEFAULT ((1)) FOR [IsModelRefreshEnabled]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_dbo_PlanType_IsSystemSetFillinEditable] DEFAULT ((0)) FOR [IsSystemSetFillinEditable]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_AssumptionInputNameFormat] DEFAULT ('') FOR [AssumptionInputNameFormat]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_AssumptionOutputNameFormat] DEFAULT ('') FOR [AssumptionOutputNameFormat]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__Defaul__26D57D31] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultModelTemplateGUID]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_DefaultMessageSubject] DEFAULT ('New Message') FOR [DefaultMessageSubject]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_FriendlyName] DEFAULT ('') FOR [FriendlyName]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__AllowP__366FC20E] DEFAULT ((0)) FOR [AllowPublicAttachment]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__OnAfte__7E0E0558] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OnAfterModelRefreshCustomScriptGUID]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_OnModelSaveCustomScriptGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OnModelSaveCustomScriptGUID]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__IsBulk__509A0BF9] DEFAULT ((1)) FOR [IsBulkDeleteAllowed]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_OnSaveCustomScriptGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OnSaveCustomScriptGUID]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_OnSaveCustomScriptGUID1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OnSaveCustomScript2GUID]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__OpenPl__53862DD5] DEFAULT ('') FOR [OpenPlanUrl]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__Global__556E7647] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__Financ__55E212AF] DEFAULT ('') FOR [FinancialsAlias]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_IsSimpleRoutingSlip] DEFAULT ((0)) FOR [IsSimpleRoutingSlip]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_PlanTypeGUID] DEFAULT (newid()) FOR [PlanTypeGUID]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_FOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__FormHe__6F7BF1FD] DEFAULT ('') FOR [FormHelpID]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_MODELDATACONFIGGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelDataConfigGUID]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_GRIDTEMPLATEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GridTemplateGUID]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_DISPLAYORDER] DEFAULT ((-1)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_OnCopyCustomScriptGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OnCopyCustomScriptGUID]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_ISPERMISSIONCOPYENABLED] DEFAULT ((1)) FOR [IsPermissionCopyEnabled]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__HelpID__74BEFEB0] DEFAULT ('') FOR [HelpID]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF__PlanType__IsSavi__74C42A7D] DEFAULT ((0)) FOR [IsSavingNewWay]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_NAMEFORMFIELDGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [NameFormFieldGUID]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_WorkflowGridTemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkflowGridTemplateGUID]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_ScoreDimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_ScoreDefaultFillInTemplateName] DEFAULT ('') FOR [ScoreDefaultFillInTemplateName]; GO +ALTER TABLE [dbo].[PlanType] ADD CONSTRAINT [DF_PlanType_OnTemplateChangeCustomScriptGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OnTemplateChangeCustomScriptGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.PlanTypeCalculatedFieldLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[PlanTypeCalculatedFieldLink] ( + [PlanTypeGUID] uniqueidentifier NOT NULL, + [FormFieldGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([PlanTypeGUID], [FormFieldGUID]) +); +GO +ALTER TABLE [dbo].[PlanTypeCalculatedFieldLink] ADD CONSTRAINT [FK_PlanTypeCalculatedFieldLink_FEFormField] FOREIGN KEY ([FormFieldGUID]) REFERENCES [dbo].[FEFormField] ([FORMFIELDGUID]); GO +ALTER TABLE [dbo].[PlanTypeCalculatedFieldLink] ADD CONSTRAINT [FK_PlanTypeCalculatedFieldLink_PlanType] FOREIGN KEY ([PlanTypeGUID]) REFERENCES [dbo].[PlanType] ([PlanTypeGUID]); GO +ALTER TABLE [dbo].[PlanTypeCalculatedFieldLink] ADD CONSTRAINT [DF_PlanTypeCalculatedFieldLink_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO +ALTER TABLE [dbo].[PlanTypeCalculatedFieldLink] ADD CONSTRAINT [DF_PlanTypeCalculatedFieldLink_FormFieldGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormFieldGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.PlanTypeFormDefLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[PlanTypeFormDefLink] ( + [PlanTypeGUID] uniqueidentifier NOT NULL, + [FormDefGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([PlanTypeGUID], [FormDefGUID]) +); +GO +ALTER TABLE [dbo].[PlanTypeFormDefLink] ADD CONSTRAINT [FK_PlanTypeFormDefLink_PlanType1] FOREIGN KEY ([PlanTypeGUID]) REFERENCES [dbo].[PlanType] ([PlanTypeGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.PlanTypeGridFieldLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[PlanTypeGridFieldLink] ( + [PlanTypeGUID] uniqueidentifier NOT NULL, + [FormFieldGUID] uniqueidentifier NOT NULL, + [IsFullTextSearchField] bit NOT NULL, + PRIMARY KEY ([PlanTypeGUID], [FormFieldGUID]) +); +GO +ALTER TABLE [dbo].[PlanTypeGridFieldLink] ADD CONSTRAINT [FK_PlanTypeGridFieldLink_FEFormField] FOREIGN KEY ([FormFieldGUID]) REFERENCES [dbo].[FEFormField] ([FORMFIELDGUID]); GO +ALTER TABLE [dbo].[PlanTypeGridFieldLink] ADD CONSTRAINT [FK_PlanTypeGridFieldLink_PlanType] FOREIGN KEY ([PlanTypeGUID]) REFERENCES [dbo].[PlanType] ([PlanTypeGUID]); GO +ALTER TABLE [dbo].[PlanTypeGridFieldLink] ADD CONSTRAINT [DF_PlanTypeGridFieldLink_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO +ALTER TABLE [dbo].[PlanTypeGridFieldLink] ADD CONSTRAINT [DF_PlanTypeGridFieldLink_FormFieldGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormFieldGUID]; GO +ALTER TABLE [dbo].[PlanTypeGridFieldLink] ADD CONSTRAINT [DF_PlanTypeGridFieldLink_IsFullTextSearchField] DEFAULT ((0)) FOR [IsFullTextSearchField]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.PlanTypeModelDataConfigLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[PlanTypeModelDataConfigLink] ( + [PlanTypeGUID] uniqueidentifier NOT NULL, + [ModelDataConfigGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([PlanTypeGUID], [ModelDataConfigGUID]) +); +GO +ALTER TABLE [dbo].[PlanTypeModelDataConfigLink] ADD CONSTRAINT [FK_PlanTypeModelDataConfigLink_EMFModelDataConfig] FOREIGN KEY ([ModelDataConfigGUID]) REFERENCES [dbo].[EMFModelDataConfig] ([ModelDataConfigGUID]); GO +ALTER TABLE [dbo].[PlanTypeModelDataConfigLink] ADD CONSTRAINT [FK_PlanTypeModelDataConfigLink_PlanType] FOREIGN KEY ([PlanTypeGUID]) REFERENCES [dbo].[PlanType] ([PlanTypeGUID]); GO +ALTER TABLE [dbo].[PlanTypeModelDataConfigLink] ADD CONSTRAINT [DF_PlanTypeModelDataConfigLink_PlanTypeGUID] DEFAULT (newid()) FOR [PlanTypeGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.PlanTypeModelTemplateLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[PlanTypeModelTemplateLink] ( + [PlanTypeGUID] uniqueidentifier NOT NULL, + [ModelTemplateGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([PlanTypeGUID], [ModelTemplateGUID]) +); +GO +ALTER TABLE [dbo].[PlanTypeModelTemplateLink] ADD CONSTRAINT [FK_PlanTypeModelTemplateLink_ModelTemplate] FOREIGN KEY ([ModelTemplateGUID]) REFERENCES [dbo].[EMFModelTemplate] ([ModelTemplateGUID]); GO +ALTER TABLE [dbo].[PlanTypeModelTemplateLink] ADD CONSTRAINT [FK_PlanTypeModelTemplateLink_PlanTypeGUID] FOREIGN KEY ([PlanTypeGUID]) REFERENCES [dbo].[PlanType] ([PlanTypeGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.PlanTypePHSectionLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[PlanTypePHSectionLink] ( + [PlanTypeGUID] uniqueidentifier NOT NULL, + [PlaceholderSectionMemberGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([PlanTypeGUID], [PlaceholderSectionMemberGUID]) +); +GO +ALTER TABLE [dbo].[PlanTypePHSectionLink] ADD CONSTRAINT [FK_PlanTypePHSectionLink_PlanType] FOREIGN KEY ([PlanTypeGUID]) REFERENCES [dbo].[PlanType] ([PlanTypeGUID]); GO +ALTER TABLE [dbo].[PlanTypePHSectionLink] ADD CONSTRAINT [DF_PlanTypePHSectionLink_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO +ALTER TABLE [dbo].[PlanTypePHSectionLink] ADD CONSTRAINT [DF_PlanTypePHSectionLink_PlaceholderSectionMemberGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlaceholderSectionMemberGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.PlanTypeReportLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[PlanTypeReportLink] ( + [PlanTypeGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([PlanTypeGUID], [ReportGUID]) +); +GO +ALTER TABLE [dbo].[PlanTypeReportLink] ADD CONSTRAINT [FK_PlanTypeReportLink_PlanType] FOREIGN KEY ([PlanTypeGUID]) REFERENCES [dbo].[PlanType] ([PlanTypeGUID]); GO +ALTER TABLE [dbo].[PlanTypeReportLink] ADD CONSTRAINT [FK_PlanTypeReportLink_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[PlanTypeReportLink] ADD CONSTRAINT [DF_PlanTypeReportLink_PLANTYPEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO +ALTER TABLE [dbo].[PlanTypeReportLink] ADD CONSTRAINT [DF_PlanTypeReportLink_REPORTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.PlanTypeWorkflowMapLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[PlanTypeWorkflowMapLink] ( + [PlanTypeGUID] uniqueidentifier NOT NULL, + [WorkflowMapGUID] uniqueidentifier NOT NULL, + [IsRequiredWorkflow] bit NOT NULL, + PRIMARY KEY ([PlanTypeGUID], [WorkflowMapGUID]) +); +GO +ALTER TABLE [dbo].[PlanTypeWorkflowMapLink] ADD CONSTRAINT [FK_PlanTypeWorkflowMapLink_PlanType] FOREIGN KEY ([PlanTypeGUID]) REFERENCES [dbo].[PlanType] ([PlanTypeGUID]); GO +ALTER TABLE [dbo].[PlanTypeWorkflowMapLink] ADD CONSTRAINT [FK_PlanTypeWorkflowMapLink_WFWorkflowMap] FOREIGN KEY ([WorkflowMapGUID]) REFERENCES [dbo].[WFWorkflowMap] ([WorkflowMapGUID]); GO +ALTER TABLE [dbo].[PlanTypeWorkflowMapLink] ADD CONSTRAINT [DF_PlanTypeWorkflowMapLink_ISREQUIREDWORKFLOW] DEFAULT ((0)) FOR [IsRequiredWorkflow]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RECachedReport ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RECachedReport] ( + [CachedReportGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [Identifier] nvarchar(4000) NOT NULL, + [CachedDataType] int NOT NULL, + [LastRefreshDate] datetime NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [ReportMetaData] nvarchar(max) NOT NULL, + PRIMARY KEY ([CachedReportGUID]) +); +GO +ALTER TABLE [dbo].[RECachedReport] ADD CONSTRAINT [FK_RECachedReport_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[RECachedReport] ADD CONSTRAINT [DF_CachedReport_CachedReportGUID] DEFAULT (newid()) FOR [CachedReportGUID]; GO +ALTER TABLE [dbo].[RECachedReport] ADD CONSTRAINT [DF_RECachedReport_Parameters] DEFAULT ('') FOR [Identifier]; GO +ALTER TABLE [dbo].[RECachedReport] ADD CONSTRAINT [DF_RECachedReport_CACHEDDATATYPE] DEFAULT ((0)) FOR [CachedDataType]; GO +ALTER TABLE [dbo].[RECachedReport] ADD CONSTRAINT [DF_RECachedReport_LastRefreshDate] DEFAULT (getdate()) FOR [LastRefreshDate]; GO +ALTER TABLE [dbo].[RECachedReport] ADD CONSTRAINT [DF_RECachedReport_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[RECachedReport] ADD CONSTRAINT [DF_RECachedReport_ReportMetaData] DEFAULT ('') FOR [ReportMetaData]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REClientReportCalculation ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REClientReportCalculation] ( + [ClientReportCalculationGUID] uniqueidentifier NOT NULL, + [ClientReportSectionGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(1000) NULL, + [DisplayOrder] int NOT NULL, + [CalculationAssemblyQualifiedName] nvarchar(400) NOT NULL, + [CalculationXML] nvarchar(max) NOT NULL, + [DetailReportGUID] uniqueidentifier NOT NULL, + [DisplayFormat] nvarchar(max) NOT NULL, + [ColumnWidth] int NOT NULL, + [IsAttributeMember] bit NOT NULL, + [CSSClass] nvarchar(100) NOT NULL, + [DetailReportGUIDsCSV] nvarchar(2000) NOT NULL, + [IsColumnCalculationTakePrecedent] bit NOT NULL, + PRIMARY KEY ([ClientReportCalculationGUID]) +); +GO +ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [FK__REClientR__Clien__590B61E5] FOREIGN KEY ([ClientReportSectionGUID]) REFERENCES [dbo].[REClientReportSection] ([ClientReportSectionGUID]); GO +ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__Displ__17C7AE6D] DEFAULT ('') FOR [DisplayFormat]; GO +ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__Colum__18BBD2A6] DEFAULT ((0)) FOR [ColumnWidth]; GO +ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__CSSCl__34C4AB25] DEFAULT ('') FOR [CSSClass]; GO +ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__Detai__3C66CA0E] DEFAULT ('') FOR [DetailReportGUIDsCSV]; GO +ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__Clien__58173DAC] DEFAULT (newid()) FOR [ClientReportCalculationGUID]; GO +ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientRe__Name__59FF861E] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__Detai__5ABEA02D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DetailReportGUID]; GO +ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__Displ__5AF3AA57] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__Calcu__5BE7CE90] DEFAULT ('') FOR [CalculationAssemblyQualifiedName]; GO +ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__IsAtt__5C71DE75] DEFAULT ((0)) FOR [IsAttributeMember]; GO +ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__Calcu__5CDBF2C9] DEFAULT ('') FOR [CalculationXML]; GO +ALTER TABLE [dbo].[REClientReportCalculation] ADD CONSTRAINT [DF__REClientR__IsCol__641F1C20] DEFAULT ((0)) FOR [IsColumnCalculationTakePrecedent]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REClientReportConditionalFormat ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REClientReportConditionalFormat] ( + [ClientReportConditionalFormatGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [ColumnTupleInfoXML] nvarchar(max) NOT NULL, + [OperatorValue] int NOT NULL, + [ValueToCompareAsString] nvarchar(1000) NOT NULL, + [CSSClass] nvarchar(100) NOT NULL, + [DisplayOrder] int NOT NULL, + [Comment] nvarchar(4000) NOT NULL, + PRIMARY KEY ([ClientReportConditionalFormatGUID]) +); +GO +ALTER TABLE [dbo].[REClientReportConditionalFormat] ADD CONSTRAINT [FK__REClientR__Repor__1E74ABFC] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[REClientReportConditionalFormat] ADD CONSTRAINT [DF__REClientR__Clien__1D8087C3] DEFAULT (newid()) FOR [ClientReportConditionalFormatGUID]; GO +ALTER TABLE [dbo].[REClientReportConditionalFormat] ADD CONSTRAINT [DF__REClientR__Colum__1F68D035] DEFAULT ('') FOR [ColumnTupleInfoXML]; GO +ALTER TABLE [dbo].[REClientReportConditionalFormat] ADD CONSTRAINT [DF__REClientR__Opera__205CF46E] DEFAULT ((0)) FOR [OperatorValue]; GO +ALTER TABLE [dbo].[REClientReportConditionalFormat] ADD CONSTRAINT [DF__REClientR__Value__215118A7] DEFAULT ('') FOR [ValueToCompareAsString]; GO +ALTER TABLE [dbo].[REClientReportConditionalFormat] ADD CONSTRAINT [DF__REClientR__CSSCl__22453CE0] DEFAULT ('') FOR [CSSClass]; GO +ALTER TABLE [dbo].[REClientReportConditionalFormat] ADD CONSTRAINT [DF__REClientR__Displ__23396119] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[REClientReportConditionalFormat] ADD CONSTRAINT [DF__REClientR__Comme__2521A98B] DEFAULT ('') FOR [Comment]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REClientReportDataSourceLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REClientReportDataSourceLink] ( + [ReportGUID] uniqueidentifier NOT NULL, + [DataSourceGUID] uniqueidentifier NOT NULL, + [ProviderAssemblyQualifiedName] nvarchar(450) NOT NULL, + [IsDefault] bit NOT NULL, + PRIMARY KEY ([ReportGUID], [DataSourceGUID]) +); +GO +ALTER TABLE [dbo].[REClientReportDataSourceLink] ADD CONSTRAINT [FK__REClientR__Repor__0E9CA038] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[REClientReportDataSourceLink] ADD CONSTRAINT [DF__REClientR__Provi__1084E8AA] DEFAULT ('') FOR [ProviderAssemblyQualifiedName]; GO +ALTER TABLE [dbo].[REClientReportDataSourceLink] ADD CONSTRAINT [DF__REClientR__DataS__0F90C471] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataSourceGUID]; GO +ALTER TABLE [dbo].[REClientReportDataSourceLink] ADD CONSTRAINT [DF__REClientR__IsDef__775ADEDB] DEFAULT ((0)) FOR [IsDefault]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REClientReportParameter ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REClientReportParameter] ( + [ClientReportParameterGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [ClientReportSectionItemGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [ColumnName] nvarchar(150) NOT NULL, + [SourceTypeValue] int NOT NULL, + [IsUserEditable] bit NOT NULL, + [DisplayOrder] int NOT NULL, + [ParameterXML] nvarchar(max) NOT NULL, + [DimensionID] nvarchar(100) NOT NULL, + [AttributeID] nvarchar(100) NOT NULL, + [MeasureID] nvarchar(100) NOT NULL, + [ParameterValueAQN] nvarchar(400) NOT NULL, + [ClientReportParameterGroupGUID] uniqueidentifier NOT NULL, + [IsExpandingColumns] bit NOT NULL, + [HierarchyID] nvarchar(100) NOT NULL, + PRIMARY KEY ([ClientReportParameterGUID]) +); +GO +ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [FK__REClientR__Repor__49C91E55] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Dimen__02CC9187] DEFAULT ('') FOR [DimensionID]; GO +ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Attri__111AB0DE] DEFAULT ('') FOR [AttributeID]; GO +ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Measu__120ED517] DEFAULT ('') FOR [MeasureID]; GO +ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF_REClientReportParameter_HierarchyID] DEFAULT ('') FOR [HierarchyID]; GO +ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Clien__48D4FA1C] DEFAULT (newid()) FOR [ClientReportParameterGUID]; GO +ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientRe__Name__4BB166C7] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Sourc__4CA58B00] DEFAULT ('') FOR [ColumnName]; GO +ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Sourc__4D99AF39] DEFAULT ((0)) FOR [SourceTypeValue]; GO +ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__IsUse__4E8DD372] DEFAULT ((0)) FOR [IsUserEditable]; GO +ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Displ__4F81F7AB] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF_REClientReportParameter_IsExpandingColumns] DEFAULT ((0)) FOR [IsExpandingColumns]; GO +ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Param__50761BE4] DEFAULT ('') FOR [ParameterXML]; GO +ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Param__53EEAB7B] DEFAULT ('') FOR [ParameterValueAQN]; GO +ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Clien__678D2682] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ClientReportParameterGroupGUID]; GO +ALTER TABLE [dbo].[REClientReportParameter] ADD CONSTRAINT [DF__REClientR__Clien__4ABD428E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ClientReportSectionItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REClientReportParameterGroup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REClientReportParameterGroup] ( + [ClientReportParameterGroupGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [IsMerged] bit NOT NULL, + PRIMARY KEY ([ClientReportParameterGroupGUID]) +); +GO +ALTER TABLE [dbo].[REClientReportParameterGroup] ADD CONSTRAINT [FK__REClientR__Repor__14FEEB77] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[REClientReportParameterGroup] ADD CONSTRAINT [DF__REClientR__Clien__140AC73E] DEFAULT (newid()) FOR [ClientReportParameterGroupGUID]; GO +ALTER TABLE [dbo].[REClientReportParameterGroup] ADD CONSTRAINT [DF__REClientRe__Name__15F30FB0] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[REClientReportParameterGroup] ADD CONSTRAINT [DF__REClientR__IsMer__16E733E9] DEFAULT ((0)) FOR [IsMerged]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REClientReportSection ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REClientReportSection] ( + [ClientReportSectionGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [DisplayLabel] nvarchar(100) NOT NULL, + [IsTemplate] bit NOT NULL, + [ShowSectionLabel] bit NOT NULL, + [ShowGrandTotal] bit NOT NULL, + [IsAutoNameFilter] bit NOT NULL, + [IsMergingRepeatHeader] bit NOT NULL, + [IsHidden] bit NOT NULL, + [ShowMargin] bit NOT NULL, + [IsTimeRelative] bit NOT NULL, + PRIMARY KEY ([ClientReportSectionGUID]) +); +GO +ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF_REClientReportSection_ShowSectionLabel] DEFAULT ((0)) FOR [ShowSectionLabel]; GO +ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF_REClientReportSection_ShowGrandTotal] DEFAULT ((0)) FOR [ShowGrandTotal]; GO +ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF__REClientR__IsHid__113187EF] DEFAULT ((0)) FOR [IsHidden]; GO +ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF__REClientR__Clien__2C38BB6E] DEFAULT (newid()) FOR [ClientReportSectionGUID]; GO +ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF__REClientRe__Name__2D2CDFA7] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF__REClientR__Displ__2E2103E0] DEFAULT ('') FOR [DisplayLabel]; GO +ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF__REClientR__IsTem__30094C52] DEFAULT ((0)) FOR [IsTemplate]; GO +ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF__REClientR__IsTim__3FF3035A] DEFAULT ((0)) FOR [IsTimeRelative]; GO +ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF__REClientR__ShowM__4AEABEE6] DEFAULT ((1)) FOR [ShowMargin]; GO +ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF__REClientR__IsAut__5D6602AE] DEFAULT ((0)) FOR [IsAutoNameFilter]; GO +ALTER TABLE [dbo].[REClientReportSection] ADD CONSTRAINT [DF__REClientR__IsMer__6C51DB9F] DEFAULT ((1)) FOR [IsMergingRepeatHeader]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REClientReportSectionAttribute ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REClientReportSectionAttribute] ( + [ClientReportSectionAttributeGUID] uniqueidentifier NOT NULL, + [ClientReportSectionGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [ColumnName] nvarchar(200) NOT NULL, + [AttributeID] nvarchar(200) NOT NULL, + [DimensionID] nvarchar(200) NOT NULL, + [HierarchyID] nvarchar(200) NOT NULL, + [HierarchyNameCached] nvarchar(100) NOT NULL, + [DrilldownStatusValue] int NOT NULL, + [DisplayOrder] int NOT NULL, + [VisibilityStatusValue] int NOT NULL, + [ColumnWidth] int NOT NULL, + [DetailReportGUID] uniqueidentifier NOT NULL, + [FilterMemberCSV] nvarchar(max) NOT NULL, + [SortOrderValue] int NOT NULL, + [ShowSubtotal] bit NOT NULL, + [DetailReportGUIDsCSV] nvarchar(2000) NOT NULL, + PRIMARY KEY ([ClientReportSectionAttributeGUID]) +); +GO +ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [FK__REClientR__Clien__74B37C5A] FOREIGN KEY ([ClientReportSectionGUID]) REFERENCES [dbo].[REClientReportSection] ([ClientReportSectionGUID]); GO +ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Visib__227A470A] DEFAULT ((0)) FOR [VisibilityStatusValue]; GO +ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Colum__236E6B43] DEFAULT ((0)) FOR [ColumnWidth]; GO +ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Detai__3A7E819C] DEFAULT ('') FOR [DetailReportGUIDsCSV]; GO +ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Detai__58D657BB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DetailReportGUID]; GO +ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Filte__5CA6E89F] DEFAULT ('') FOR [FilterMemberCSV]; GO +ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__SortO__6353E62E] DEFAULT ((-1)) FOR [SortOrderValue]; GO +ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__ShowS__6D45FFD8] DEFAULT ((0)) FOR [ShowSubtotal]; GO +ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Clien__73BF5821] DEFAULT (newid()) FOR [ClientReportSectionAttributeGUID]; GO +ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientRe__Name__75A7A093] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Colum__769BC4CC] DEFAULT ('') FOR [ColumnName]; GO +ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Attri__778FE905] DEFAULT ('') FOR [AttributeID]; GO +ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Dimen__78840D3E] DEFAULT ('') FOR [DimensionID]; GO +ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Hiera__79783177] DEFAULT ('') FOR [HierarchyID]; GO +ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Hiera__7A6C55B0] DEFAULT ('') FOR [HierarchyNameCached]; GO +ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Drill__7B6079E9] DEFAULT ((0)) FOR [DrilldownStatusValue]; GO +ALTER TABLE [dbo].[REClientReportSectionAttribute] ADD CONSTRAINT [DF__REClientR__Displ__7D48C25B] DEFAULT ((0)) FOR [DisplayOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REClientReportSectionLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REClientReportSectionLink] ( + [ClientReportSectionLinkGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [ClientReportSectionGUID] uniqueidentifier NOT NULL, + [DisplayOrder] int NOT NULL, + [IsOnColumn] bit NOT NULL, + PRIMARY KEY ([ClientReportSectionLinkGUID]) +); +GO +ALTER TABLE [dbo].[REClientReportSectionLink] ADD CONSTRAINT [FK__REClientR__Clien__36B649E1] FOREIGN KEY ([ClientReportSectionGUID]) REFERENCES [dbo].[REClientReportSection] ([ClientReportSectionGUID]); GO +ALTER TABLE [dbo].[REClientReportSectionLink] ADD CONSTRAINT [FK__REClientR__Repor__35C225A8] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[REClientReportSectionLink] ADD CONSTRAINT [DF__REClientR__Clien__34CE016F] DEFAULT (newid()) FOR [ClientReportSectionLinkGUID]; GO +ALTER TABLE [dbo].[REClientReportSectionLink] ADD CONSTRAINT [DF__REClientR__Displ__37AA6E1A] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[REClientReportSectionLink] ADD CONSTRAINT [DF__REClientR__IsOnC__389E9253] DEFAULT ((0)) FOR [IsOnColumn]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REClientReportSectionMeasure ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REClientReportSectionMeasure] ( + [ClientReportSectionMeasureGUID] uniqueidentifier NOT NULL, + [ClientReportSectionGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [MeasureID] nvarchar(100) NOT NULL, + [DisplayFormatCached] nvarchar(100) NOT NULL, + [DisplayOrder] int NOT NULL, + [ColumnWidth] int NOT NULL, + [DetailReportGUID] uniqueidentifier NOT NULL, + [LinkedSectionGUIDsCSV] nvarchar(max) NOT NULL, + [DetailReportGUIDsCSV] nvarchar(2000) NOT NULL, + [AggregationType] tinyint NOT NULL, + PRIMARY KEY ([ClientReportSectionMeasureGUID]) +); +GO +ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [FK__REClientR__Clien__03019BB1] FOREIGN KEY ([ClientReportSectionGUID]) REFERENCES [dbo].[REClientReportSection] ([ClientReportSectionGUID]); GO +ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [DF__REClientR__Clien__020D7778] DEFAULT (newid()) FOR [ClientReportSectionMeasureGUID]; GO +ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [DF__REClientRe__Name__03F5BFEA] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [DF__REClientR__Measu__04E9E423] DEFAULT ('') FOR [MeasureID]; GO +ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [DF__REClientR__Displ__05DE085C] DEFAULT ('') FOR [DisplayFormatCached]; GO +ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [DF__REClientR__Displ__06D22C95] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [DF__REClientR__Linke__16D38A34] DEFAULT ('') FOR [LinkedSectionGUIDsCSV]; GO +ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [DF__REClientR__Colum__24628F7C] DEFAULT ((0)) FOR [ColumnWidth]; GO +ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [DF__REClientR__Detai__3B72A5D5] DEFAULT ('') FOR [DetailReportGUIDsCSV]; GO +ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [DF__REClientR__Aggre__3D0580C9] DEFAULT ((0)) FOR [AggregationType]; GO +ALTER TABLE [dbo].[REClientReportSectionMeasure] ADD CONSTRAINT [DF__REClientR__Detai__59CA7BF4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DetailReportGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REClientReportSetup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REClientReportSetup] ( + [ClientReportSetupGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [LaunchMode] int NOT NULL, + [IsDrilldownIndented] bit NOT NULL, + [Style] nvarchar(100) NOT NULL, + [IsAutoRefresh] bit NOT NULL, + [SortArgsXML] nvarchar(max) NOT NULL, + [IsTitleVisible] bit NOT NULL, + [HideEmptyData] bit NOT NULL, + [HasPHIData] bit NOT NULL, + [IsPaneFrozen] bit NOT NULL, + [IsExcelOnly] bit NOT NULL, + [IsAutoHidingRows] bit NOT NULL, + [ChartConfigJSON] nvarchar(max) NOT NULL, + [ChartConfigAQN] nvarchar(max) NOT NULL, + PRIMARY KEY ([ClientReportSetupGUID]) +); +GO +ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [FK__REClientR__Repor__0BC0338D] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__Clien__0ACC0F54] DEFAULT (newid()) FOR [ClientReportSetupGUID]; GO +ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__Launc__0CB457C6] DEFAULT ((0)) FOR [LaunchMode]; GO +ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF_REClientReportSetup_IsAutoHidingRows] DEFAULT ((0)) FOR [IsAutoHidingRows]; GO +ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__IsAut__0F32686C] DEFAULT ((0)) FOR [IsAutoRefresh]; GO +ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__SortA__1302F950] DEFAULT ('') FOR [SortArgsXML]; GO +ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__Chart__162C7621] DEFAULT ('') FOR [ChartConfigJSON]; GO +ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__Chart__17209A5A] DEFAULT ('') FOR [ChartConfigAQN]; GO +ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__IsDri__2091FE98] DEFAULT ((0)) FOR [IsDrilldownIndented]; GO +ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__Style__218622D1] DEFAULT ('') FOR [Style]; GO +ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF_REClientReportSetup_IsTitleVisible] DEFAULT ((0)) FOR [IsTitleVisible]; GO +ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__HideE__2866C5A6] DEFAULT ((0)) FOR [HideEmptyData]; GO +ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__IsExc__4133A25B] DEFAULT ((0)) FOR [IsExcelOnly]; GO +ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__HasPH__5E542FC3] DEFAULT ((0)) FOR [HasPHIData]; GO +ALTER TABLE [dbo].[REClientReportSetup] ADD CONSTRAINT [DF__REClientR__IsPan__7FF153C7] DEFAULT ((0)) FOR [IsPaneFrozen]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RECubeReportDimension ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RECubeReportDimension] ( + [CubeReportDimensionGUID] uniqueidentifier NOT NULL, + [CubeReportSetupGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [HierarchyID] nvarchar(400) NOT NULL, + [DimensionType] int NOT NULL, + [IsConsolidatable] bit NOT NULL, + [IsOnColumn] bit NOT NULL, + [DisplayOrder] int NOT NULL, + PRIMARY KEY ([CubeReportDimensionGUID]) +); +GO +ALTER TABLE [dbo].[RECubeReportDimension] ADD CONSTRAINT [FK_CubeReportDimension_CubeReportSetup] FOREIGN KEY ([CubeReportSetupGUID]) REFERENCES [dbo].[RECubeReportSetup] ([CubeReportSetupGUID]); GO +ALTER TABLE [dbo].[RECubeReportDimension] ADD CONSTRAINT [DF_CubeReportDimension_CubeReportDimensionGUID] DEFAULT (newid()) FOR [CubeReportDimensionGUID]; GO +ALTER TABLE [dbo].[RECubeReportDimension] ADD CONSTRAINT [DF_CubeReportDimension_CubeReportSetupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CubeReportSetupGUID]; GO +ALTER TABLE [dbo].[RECubeReportDimension] ADD CONSTRAINT [DF_CubeReportDimension_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[RECubeReportDimension] ADD CONSTRAINT [DF_CubeReportDimension_HierarchyID] DEFAULT ('') FOR [HierarchyID]; GO +ALTER TABLE [dbo].[RECubeReportDimension] ADD CONSTRAINT [DF_CubeReportDimension_DimensionType] DEFAULT ((0)) FOR [DimensionType]; GO +ALTER TABLE [dbo].[RECubeReportDimension] ADD CONSTRAINT [DF_CubeReportDimension_IsConsolidatable] DEFAULT ((0)) FOR [IsConsolidatable]; GO +ALTER TABLE [dbo].[RECubeReportDimension] ADD CONSTRAINT [DF_CubeReportDimension_IsOnColumn] DEFAULT ((0)) FOR [IsOnColumn]; GO +ALTER TABLE [dbo].[RECubeReportDimension] ADD CONSTRAINT [DF_CubeReportDimension_DisplayOrder] DEFAULT ((-1)) FOR [DisplayOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RECubeReportLevel ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RECubeReportLevel] ( + [CubeReportLevelGUID] uniqueidentifier NOT NULL, + [CubeReportDimensionGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [LevelID] nvarchar(400) NOT NULL, + [LevelIndex] int NOT NULL, + [IsConsolidated] bit NOT NULL, + [MDXName] nvarchar(400) NOT NULL, + PRIMARY KEY ([CubeReportLevelGUID]) +); +GO +ALTER TABLE [dbo].[RECubeReportLevel] ADD CONSTRAINT [FK_CubeReportLevel_CubeReportDimension] FOREIGN KEY ([CubeReportDimensionGUID]) REFERENCES [dbo].[RECubeReportDimension] ([CubeReportDimensionGUID]); GO +ALTER TABLE [dbo].[RECubeReportLevel] ADD CONSTRAINT [DF_CubeReportLevel_CubeReportLevelGUID] DEFAULT (newid()) FOR [CubeReportLevelGUID]; GO +ALTER TABLE [dbo].[RECubeReportLevel] ADD CONSTRAINT [DF_CubeReportLevel_CubeReportSetupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CubeReportDimensionGUID]; GO +ALTER TABLE [dbo].[RECubeReportLevel] ADD CONSTRAINT [DF_CubeReportLevel_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[RECubeReportLevel] ADD CONSTRAINT [DF_CubeReportLevel_LevelID] DEFAULT ('') FOR [LevelID]; GO +ALTER TABLE [dbo].[RECubeReportLevel] ADD CONSTRAINT [DF_CubeReportLevel_LevelIndex] DEFAULT ((-1)) FOR [LevelIndex]; GO +ALTER TABLE [dbo].[RECubeReportLevel] ADD CONSTRAINT [DF_CubeReportLevel_IsConsolidated] DEFAULT ((0)) FOR [IsConsolidated]; GO +ALTER TABLE [dbo].[RECubeReportLevel] ADD CONSTRAINT [DF_CubeReportLevel_MDXName] DEFAULT ('') FOR [MDXName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RECubeReportMeasure ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RECubeReportMeasure] ( + [CubeReportMeasureGUID] uniqueidentifier NOT NULL, + [CubeReportSetupGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [MeasureID] nvarchar(400) NOT NULL, + [MDXName] nvarchar(400) NOT NULL, + [DisplayOrder] int NOT NULL, + PRIMARY KEY ([CubeReportMeasureGUID]) +); +GO +ALTER TABLE [dbo].[RECubeReportMeasure] ADD CONSTRAINT [FK_CubeReportMeasure_CubeReportSetup] FOREIGN KEY ([CubeReportSetupGUID]) REFERENCES [dbo].[RECubeReportSetup] ([CubeReportSetupGUID]); GO +ALTER TABLE [dbo].[RECubeReportMeasure] ADD CONSTRAINT [DF_CubeReportMeasure_CubeReportMeasureGUID] DEFAULT (newid()) FOR [CubeReportMeasureGUID]; GO +ALTER TABLE [dbo].[RECubeReportMeasure] ADD CONSTRAINT [DF_CubeReportMeasure_CubeReportSetupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CubeReportSetupGUID]; GO +ALTER TABLE [dbo].[RECubeReportMeasure] ADD CONSTRAINT [DF_CubeReportMeasure_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[RECubeReportMeasure] ADD CONSTRAINT [DF_CubeReportMeasure_MeasureID] DEFAULT ('') FOR [MeasureID]; GO +ALTER TABLE [dbo].[RECubeReportMeasure] ADD CONSTRAINT [DF_CubeReportMeasure_MDXName] DEFAULT ('') FOR [MDXName]; GO +ALTER TABLE [dbo].[RECubeReportMeasure] ADD CONSTRAINT [DF_CubeReportMeasure_DisplayOrder] DEFAULT ((-1)) FOR [DisplayOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RECubeReportParameter ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RECubeReportParameter] ( + [CubeReportParameterGUID] uniqueidentifier NOT NULL, + [CubeReportSetupGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [HierarchyID] nvarchar(400) NOT NULL, + [IsEditable] bit NOT NULL, + [MemberIDs] nvarchar(max) NOT NULL, + [MemberNames] nvarchar(max) NOT NULL, + PRIMARY KEY ([CubeReportParameterGUID]) +); +GO +ALTER TABLE [dbo].[RECubeReportParameter] ADD CONSTRAINT [FK_CubeReportParameter_CubeReportSetup] FOREIGN KEY ([CubeReportSetupGUID]) REFERENCES [dbo].[RECubeReportSetup] ([CubeReportSetupGUID]); GO +ALTER TABLE [dbo].[RECubeReportParameter] ADD CONSTRAINT [DF_CubeReportParameter_CubeReportParameterGUID] DEFAULT (newid()) FOR [CubeReportParameterGUID]; GO +ALTER TABLE [dbo].[RECubeReportParameter] ADD CONSTRAINT [DF_CubeReportParameter_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CubeReportSetupGUID]; GO +ALTER TABLE [dbo].[RECubeReportParameter] ADD CONSTRAINT [DF_CubeReportParameter_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[RECubeReportParameter] ADD CONSTRAINT [DF_CubeReportParameter_HierarchyID] DEFAULT ('') FOR [HierarchyID]; GO +ALTER TABLE [dbo].[RECubeReportParameter] ADD CONSTRAINT [DF_CubeReportParameter_IsEditable] DEFAULT ((1)) FOR [IsEditable]; GO +ALTER TABLE [dbo].[RECubeReportParameter] ADD CONSTRAINT [DF_CubeReportParameter_MemberIDs] DEFAULT ('') FOR [MemberIDs]; GO +ALTER TABLE [dbo].[RECubeReportParameter] ADD CONSTRAINT [DF_CubeReportParameter_MemberNames] DEFAULT ('') FOR [MemberNames]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RECubeReportSetup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RECubeReportSetup] ( + [CubeReportSetupGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [CubeName] nvarchar(64) NOT NULL, + [IsNonEmptyColumns] bit NOT NULL, + [IsNonEmptyRows] bit NOT NULL, + [IsShowingTotal] bit NOT NULL, + [IsUsingMDXOverride] bit NOT NULL, + [MDXOverride] nvarchar(max) NOT NULL, + PRIMARY KEY ([CubeReportSetupGUID]) +); +GO +ALTER TABLE [dbo].[RECubeReportSetup] ADD CONSTRAINT [FK_RECubeReportSetup_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[RECubeReportSetup] ADD CONSTRAINT [DF_CubeReportSetup_CubeReportSetupGUID] DEFAULT (newid()) FOR [CubeReportSetupGUID]; GO +ALTER TABLE [dbo].[RECubeReportSetup] ADD CONSTRAINT [DF_CubeReportSetup_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO +ALTER TABLE [dbo].[RECubeReportSetup] ADD CONSTRAINT [DF_CubeReportSetup_CubeName] DEFAULT ('') FOR [CubeName]; GO +ALTER TABLE [dbo].[RECubeReportSetup] ADD CONSTRAINT [DF_CubeReportSetup_IsNonEmptyColumns] DEFAULT ((0)) FOR [IsNonEmptyColumns]; GO +ALTER TABLE [dbo].[RECubeReportSetup] ADD CONSTRAINT [DF_CubeReportSetup_IsNonEmptyRows] DEFAULT ((0)) FOR [IsNonEmptyRows]; GO +ALTER TABLE [dbo].[RECubeReportSetup] ADD CONSTRAINT [DF_CubeReportSetup_IsShowingTotal] DEFAULT ((1)) FOR [IsShowingTotal]; GO +ALTER TABLE [dbo].[RECubeReportSetup] ADD CONSTRAINT [DF_RECubeReportSetup_IsUsingMDXOverride] DEFAULT ((0)) FOR [IsUsingMDXOverride]; GO +ALTER TABLE [dbo].[RECubeReportSetup] ADD CONSTRAINT [DF_RECubeReportSetup_MDXOverride] DEFAULT ('') FOR [MDXOverride]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REDSCubeReportCalculation ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REDSCubeReportCalculation] ( + [DSCubeReportCalculationGUID] uniqueidentifier NOT NULL, + [DSCubeReportSectionGUID] uniqueidentifier NULL, + [Name] nvarchar(1000) NULL, + [DisplayOrder] int NOT NULL, + [CalculationAssemblyQualifiedName] nvarchar(400) NOT NULL, + [CalculationXML] nvarchar(max) NOT NULL, + [DetailReportGUID] uniqueidentifier NOT NULL, + [DisplayFormat] nvarchar(max) NOT NULL, + [ColumnWidth] int NOT NULL, + [IsAttributeMember] bit NOT NULL, + [CSSClass] nvarchar(100) NOT NULL, + [DetailReportGUIDsCSV] nvarchar(2000) NOT NULL, + [IsColumnCalculationTakePrecedent] bit NOT NULL, + PRIMARY KEY ([DSCubeReportCalculationGUID]) +); +GO +ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [FK__REDSCubeR__DSCub__1789E357] FOREIGN KEY ([DSCubeReportSectionGUID]) REFERENCES [dbo].[REDSCubeReportSection] ([DSCubeReportSectionGUID]); GO +ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__DSCub__15A19AE5] DEFAULT (newid()) FOR [DSCubeReportCalculationGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__DSCub__1695BF1E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DSCubeReportSectionGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeRe__Name__187E0790] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__Displ__19722BC9] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__Calcu__1A665002] DEFAULT ('') FOR [CalculationAssemblyQualifiedName]; GO +ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__Calcu__1B5A743B] DEFAULT ('') FOR [CalculationXML]; GO +ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__Detai__1C4E9874] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DetailReportGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__Displ__1D42BCAD] DEFAULT ('') FOR [DisplayFormat]; GO +ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__Colum__1E36E0E6] DEFAULT ((0)) FOR [ColumnWidth]; GO +ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__IsAtt__1F2B051F] DEFAULT ((0)) FOR [IsAttributeMember]; GO +ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__CSSCl__201F2958] DEFAULT ('') FOR [CSSClass]; GO +ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__Detai__21134D91] DEFAULT ('') FOR [DetailReportGUIDsCSV]; GO +ALTER TABLE [dbo].[REDSCubeReportCalculation] ADD CONSTRAINT [DF__REDSCubeR__IsCol__220771CA] DEFAULT ((0)) FOR [IsColumnCalculationTakePrecedent]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REDSCubeReportConditionalFormat ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REDSCubeReportConditionalFormat] ( + [DSCubeReportConditionalFormatGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [ColumnTupleInfoXML] nvarchar(max) NOT NULL, + [OperatorValue] int NOT NULL, + [ValueToCompareAsString] nvarchar(1000) NOT NULL, + [CSSClass] nvarchar(100) NOT NULL, + [DisplayOrder] int NOT NULL, + [Comment] nvarchar(4000) NOT NULL, + PRIMARY KEY ([DSCubeReportConditionalFormatGUID]) +); +GO +ALTER TABLE [dbo].[REDSCubeReportConditionalFormat] ADD CONSTRAINT [FK__REDSCubeR__Repor__4EDA1841] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[REDSCubeReportConditionalFormat] ADD CONSTRAINT [DF__REDSCubeR__DSCub__4CF1CFCF] DEFAULT (newid()) FOR [DSCubeReportConditionalFormatGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportConditionalFormat] ADD CONSTRAINT [DF__REDSCubeR__Repor__4DE5F408] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportConditionalFormat] ADD CONSTRAINT [DF__REDSCubeR__Colum__4FCE3C7A] DEFAULT ('') FOR [ColumnTupleInfoXML]; GO +ALTER TABLE [dbo].[REDSCubeReportConditionalFormat] ADD CONSTRAINT [DF__REDSCubeR__Opera__50C260B3] DEFAULT ((0)) FOR [OperatorValue]; GO +ALTER TABLE [dbo].[REDSCubeReportConditionalFormat] ADD CONSTRAINT [DF__REDSCubeR__Value__51B684EC] DEFAULT ('') FOR [ValueToCompareAsString]; GO +ALTER TABLE [dbo].[REDSCubeReportConditionalFormat] ADD CONSTRAINT [DF__REDSCubeR__CSSCl__52AAA925] DEFAULT ('') FOR [CSSClass]; GO +ALTER TABLE [dbo].[REDSCubeReportConditionalFormat] ADD CONSTRAINT [DF__REDSCubeR__Displ__539ECD5E] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[REDSCubeReportConditionalFormat] ADD CONSTRAINT [DF__REDSCubeR__Comme__5492F197] DEFAULT ('') FOR [Comment]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REDSCubeReportDataSourceLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REDSCubeReportDataSourceLink] ( + [ReportGUID] uniqueidentifier NOT NULL, + [DataSourceGUID] uniqueidentifier NOT NULL, + [ProviderAssemblyQualifiedName] nvarchar(450) NOT NULL, + [IsDefault] bit NOT NULL, + PRIMARY KEY ([ReportGUID], [DataSourceGUID]) +); +GO +ALTER TABLE [dbo].[REDSCubeReportDataSourceLink] ADD CONSTRAINT [FK__REDSCubeR__Repor__5863827B] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[REDSCubeReportDataSourceLink] ADD CONSTRAINT [DF__REDSCubeR__Repor__576F5E42] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportDataSourceLink] ADD CONSTRAINT [DF__REDSCubeR__DataS__5957A6B4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataSourceGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportDataSourceLink] ADD CONSTRAINT [DF__REDSCubeR__Provi__5A4BCAED] DEFAULT ('') FOR [ProviderAssemblyQualifiedName]; GO +ALTER TABLE [dbo].[REDSCubeReportDataSourceLink] ADD CONSTRAINT [DF__REDSCubeR__IsDef__5B3FEF26] DEFAULT ((0)) FOR [IsDefault]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REDSCubeReportParameter ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REDSCubeReportParameter] ( + [DSCubeReportParameterGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [DSCubeReportSectionItemGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [ColumnName] nvarchar(150) NOT NULL, + [SourceTypeValue] int NOT NULL, + [IsUserEditable] bit NOT NULL, + [DisplayOrder] int NOT NULL, + [ParameterXML] nvarchar(max) NOT NULL, + [DimensionID] nvarchar(100) NOT NULL, + [AttributeID] nvarchar(100) NOT NULL, + [MeasureID] nvarchar(100) NOT NULL, + [ParameterValueAQN] nvarchar(400) NOT NULL, + [DSCubeReportParameterGroupGUID] uniqueidentifier NOT NULL, + [IsExpandingColumns] bit NOT NULL, + [HierarchyID] nvarchar(100) NOT NULL, + PRIMARY KEY ([DSCubeReportParameterGUID]) +); +GO +ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [FK__REDSCubeR__Repor__6004A443] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__DSCub__5E1C5BD1] DEFAULT (newid()) FOR [DSCubeReportParameterGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__Repor__5F10800A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__DSCub__60F8C87C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DSCubeReportSectionItemGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeRe__Name__61ECECB5] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__Colum__62E110EE] DEFAULT ('') FOR [ColumnName]; GO +ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__Sourc__63D53527] DEFAULT ((0)) FOR [SourceTypeValue]; GO +ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__IsUse__64C95960] DEFAULT ((0)) FOR [IsUserEditable]; GO +ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__Displ__65BD7D99] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__Param__66B1A1D2] DEFAULT ('') FOR [ParameterXML]; GO +ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__Dimen__67A5C60B] DEFAULT ('') FOR [DimensionID]; GO +ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__Attri__6899EA44] DEFAULT ('') FOR [AttributeID]; GO +ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__Measu__698E0E7D] DEFAULT ('') FOR [MeasureID]; GO +ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__Param__6A8232B6] DEFAULT ('') FOR [ParameterValueAQN]; GO +ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__DSCub__6B7656EF] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DSCubeReportParameterGroupGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__IsExp__6C6A7B28] DEFAULT ((0)) FOR [IsExpandingColumns]; GO +ALTER TABLE [dbo].[REDSCubeReportParameter] ADD CONSTRAINT [DF__REDSCubeR__Hiera__6D5E9F61] DEFAULT ('') FOR [HierarchyID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REDSCubeReportParameterGroup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REDSCubeReportParameterGroup] ( + [DSCubeReportParameterGroupGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [IsMerged] bit NOT NULL, + PRIMARY KEY ([DSCubeReportParameterGroupGUID]) +); +GO +ALTER TABLE [dbo].[REDSCubeReportParameterGroup] ADD CONSTRAINT [FK__REDSCubeR__Repor__7223547E] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[REDSCubeReportParameterGroup] ADD CONSTRAINT [DF__REDSCubeR__DSCub__703B0C0C] DEFAULT (newid()) FOR [DSCubeReportParameterGroupGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportParameterGroup] ADD CONSTRAINT [DF__REDSCubeR__Repor__712F3045] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportParameterGroup] ADD CONSTRAINT [DF__REDSCubeRe__Name__731778B7] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[REDSCubeReportParameterGroup] ADD CONSTRAINT [DF__REDSCubeR__IsMer__740B9CF0] DEFAULT ((0)) FOR [IsMerged]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REDSCubeReportSection ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REDSCubeReportSection] ( + [DSCubeReportSectionGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [DisplayLabel] nvarchar(100) NOT NULL, + [IsTemplate] bit NOT NULL, + [ShowSectionLabel] bit NOT NULL, + [ShowGrandTotal] bit NOT NULL, + [IsAutoNameFilter] bit NOT NULL, + [IsMergingRepeatHeader] bit NOT NULL, + [IsHidden] bit NOT NULL, + [ShowMargin] bit NOT NULL, + [IsTimeRelative] bit NOT NULL, + PRIMARY KEY ([DSCubeReportSectionGUID]) +); +GO +ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeR__DSCub__093BC400] DEFAULT (newid()) FOR [DSCubeReportSectionGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeRe__Name__0A2FE839] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeR__Displ__0B240C72] DEFAULT ('') FOR [DisplayLabel]; GO +ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeR__IsTem__0C1830AB] DEFAULT ((0)) FOR [IsTemplate]; GO +ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeR__ShowS__0D0C54E4] DEFAULT ((0)) FOR [ShowSectionLabel]; GO +ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeR__ShowG__0E00791D] DEFAULT ((0)) FOR [ShowGrandTotal]; GO +ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeR__IsAut__0EF49D56] DEFAULT ((0)) FOR [IsAutoNameFilter]; GO +ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeR__IsMer__0FE8C18F] DEFAULT ((1)) FOR [IsMergingRepeatHeader]; GO +ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeR__IsHid__10DCE5C8] DEFAULT ((0)) FOR [IsHidden]; GO +ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeR__ShowM__11D10A01] DEFAULT ((1)) FOR [ShowMargin]; GO +ALTER TABLE [dbo].[REDSCubeReportSection] ADD CONSTRAINT [DF__REDSCubeR__IsTim__12C52E3A] DEFAULT ((0)) FOR [IsTimeRelative]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REDSCubeReportSectionAttribute ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REDSCubeReportSectionAttribute] ( + [DSCubeReportSectionAttributeGUID] uniqueidentifier NOT NULL, + [DSCubeReportSectionGUID] uniqueidentifier NULL, + [Name] nvarchar(100) NOT NULL, + [ColumnName] nvarchar(200) NOT NULL, + [AttributeID] nvarchar(200) NOT NULL, + [DimensionID] nvarchar(200) NOT NULL, + [HierarchyID] nvarchar(200) NOT NULL, + [HierarchyNameCached] nvarchar(100) NOT NULL, + [DrilldownStatusValue] int NOT NULL, + [DisplayOrder] int NOT NULL, + [VisibilityStatusValue] int NOT NULL, + [ColumnWidth] int NOT NULL, + [DetailReportGUID] uniqueidentifier NOT NULL, + [FilterMemberCSV] nvarchar(max) NOT NULL, + [SortOrderValue] int NOT NULL, + [ShowSubtotal] bit NOT NULL, + [DetailReportGUIDsCSV] nvarchar(2000) NOT NULL, + PRIMARY KEY ([DSCubeReportSectionAttributeGUID]) +); +GO +ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [FK__REDSCubeR__DSCub__26CC26E7] FOREIGN KEY ([DSCubeReportSectionGUID]) REFERENCES [dbo].[REDSCubeReportSection] ([DSCubeReportSectionGUID]); GO +ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__DSCub__24E3DE75] DEFAULT (newid()) FOR [DSCubeReportSectionAttributeGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__DSCub__25D802AE] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DSCubeReportSectionGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeRe__Name__27C04B20] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Colum__28B46F59] DEFAULT ('') FOR [ColumnName]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Attri__29A89392] DEFAULT ('') FOR [AttributeID]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Dimen__2A9CB7CB] DEFAULT ('') FOR [DimensionID]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Hiera__2B90DC04] DEFAULT ('') FOR [HierarchyID]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Hiera__2C85003D] DEFAULT ('') FOR [HierarchyNameCached]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Drill__2D792476] DEFAULT ((0)) FOR [DrilldownStatusValue]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Displ__2E6D48AF] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Visib__2F616CE8] DEFAULT ((0)) FOR [VisibilityStatusValue]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Colum__30559121] DEFAULT ((0)) FOR [ColumnWidth]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Detai__3149B55A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DetailReportGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Filte__323DD993] DEFAULT ('') FOR [FilterMemberCSV]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__SortO__3331FDCC] DEFAULT ((-1)) FOR [SortOrderValue]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__ShowS__34262205] DEFAULT ((0)) FOR [ShowSubtotal]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionAttribute] ADD CONSTRAINT [DF__REDSCubeR__Detai__351A463E] DEFAULT ('') FOR [DetailReportGUIDsCSV]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REDSCubeReportSectionLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REDSCubeReportSectionLink] ( + [DSCubeReportSectionLinkGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [DSCubeReportSectionGUID] uniqueidentifier NOT NULL, + [DisplayOrder] int NOT NULL, + [IsOnColumn] bit NOT NULL, + PRIMARY KEY ([DSCubeReportSectionLinkGUID]) +); +GO +ALTER TABLE [dbo].[REDSCubeReportSectionLink] ADD CONSTRAINT [FK__REDSCubeR__DSCub__7AB89A7F] FOREIGN KEY ([DSCubeReportSectionGUID]) REFERENCES [dbo].[REDSCubeReportSection] ([DSCubeReportSectionGUID]); GO +ALTER TABLE [dbo].[REDSCubeReportSectionLink] ADD CONSTRAINT [FK__REDSCubeR__Repor__78D0520D] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[REDSCubeReportSectionLink] ADD CONSTRAINT [DF__REDSCubeR__DSCub__76E8099B] DEFAULT (newid()) FOR [DSCubeReportSectionLinkGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionLink] ADD CONSTRAINT [DF__REDSCubeR__Repor__77DC2DD4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionLink] ADD CONSTRAINT [DF__REDSCubeR__DSCub__79C47646] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DSCubeReportSectionGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionLink] ADD CONSTRAINT [DF__REDSCubeR__Displ__7BACBEB8] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionLink] ADD CONSTRAINT [DF__REDSCubeR__IsOnC__7CA0E2F1] DEFAULT ((0)) FOR [IsOnColumn]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REDSCubeReportSectionMeasure ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REDSCubeReportSectionMeasure] ( + [DSCubeReportSectionMeasureGUID] uniqueidentifier NOT NULL, + [DSCubeReportSectionGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [MeasureID] nvarchar(100) NOT NULL, + [DisplayFormatCached] nvarchar(100) NOT NULL, + [DisplayOrder] int NOT NULL, + [ColumnWidth] int NOT NULL, + [DetailReportGUID] uniqueidentifier NOT NULL, + [LinkedSectionGUIDsCSV] nvarchar(max) NOT NULL, + [DetailReportGUIDsCSV] nvarchar(2000) NOT NULL, + [AggregationType] tinyint NOT NULL, + PRIMARY KEY ([DSCubeReportSectionMeasureGUID]) +); +GO +ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [FK__REDSCubeR__DSCub__41801D23] FOREIGN KEY ([DSCubeReportSectionGUID]) REFERENCES [dbo].[REDSCubeReportSection] ([DSCubeReportSectionGUID]); GO +ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeR__DSCub__3F97D4B1] DEFAULT (newid()) FOR [DSCubeReportSectionMeasureGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeR__DSCub__408BF8EA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DSCubeReportSectionGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeRe__Name__4274415C] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeR__Measu__43686595] DEFAULT ('') FOR [MeasureID]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeR__Displ__445C89CE] DEFAULT ('') FOR [DisplayFormatCached]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeR__Displ__4550AE07] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeR__Colum__4644D240] DEFAULT ((0)) FOR [ColumnWidth]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeR__Detai__4738F679] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DetailReportGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeR__Linke__482D1AB2] DEFAULT ('') FOR [LinkedSectionGUIDsCSV]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeR__Detai__49213EEB] DEFAULT ('') FOR [DetailReportGUIDsCSV]; GO +ALTER TABLE [dbo].[REDSCubeReportSectionMeasure] ADD CONSTRAINT [DF__REDSCubeR__Aggre__4A156324] DEFAULT ((0)) FOR [AggregationType]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REDSCubeReportSetup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REDSCubeReportSetup] ( + [DSCubeReportSetupGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [LaunchMode] int NOT NULL, + [IsDrilldownIndented] bit NOT NULL, + [Style] nvarchar(100) NOT NULL, + [IsAutoRefresh] bit NOT NULL, + [SortArgsXML] nvarchar(max) NOT NULL, + [IsTitleVisible] bit NOT NULL, + [HideEmptyData] bit NOT NULL, + [HasPHIData] bit NOT NULL, + [IsPaneFrozen] bit NOT NULL, + [IsExcelOnly] bit NOT NULL, + [ChartConfigJSON] nvarchar(max) NOT NULL, + [ChartConfigAQN] nvarchar(max) NOT NULL, + PRIMARY KEY ([DSCubeReportSetupGUID]) +); +GO +ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [FK__REDSCubeR__Repor__7CD5ED1B] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__IsAut__00A67DFF] DEFAULT ((0)) FOR [IsAutoRefresh]; GO +ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__SortA__019AA238] DEFAULT ('') FOR [SortArgsXML]; GO +ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__IsTit__028EC671] DEFAULT ((0)) FOR [IsTitleVisible]; GO +ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__HideE__0382EAAA] DEFAULT ((0)) FOR [HideEmptyData]; GO +ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__HasPH__04770EE3] DEFAULT ((0)) FOR [HasPHIData]; GO +ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__IsPan__056B331C] DEFAULT ((0)) FOR [IsPaneFrozen]; GO +ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__IsExc__065F5755] DEFAULT ((0)) FOR [IsExcelOnly]; GO +ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__Chart__6FC6D617] DEFAULT ('') FOR [ChartConfigJSON]; GO +ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__Chart__72A342C2] DEFAULT ('') FOR [ChartConfigAQN]; GO +ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__DSCub__7AEDA4A9] DEFAULT (newid()) FOR [DSCubeReportSetupGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__Repor__7BE1C8E2] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO +ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__Launc__7DCA1154] DEFAULT ((0)) FOR [LaunchMode]; GO +ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__IsDri__7EBE358D] DEFAULT ((0)) FOR [IsDrilldownIndented]; GO +ALTER TABLE [dbo].[REDSCubeReportSetup] ADD CONSTRAINT [DF__REDSCubeR__Style__7FB259C6] DEFAULT ('') FOR [Style]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REDataSource ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REDataSource] ( + [DataSourceGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [SourceGUID] uniqueidentifier NOT NULL, + [SourceType] int NOT NULL, + [Name] nvarchar(max) NOT NULL, + [SkipBlanks] bit NOT NULL, + [SimpleNames] bit NOT NULL, + PRIMARY KEY ([DataSourceGUID]) +); + +CREATE NONCLUSTERED INDEX [IDX_REDataSource] ON [dbo].[REDataSource] ([ReportGUID]); +GO +ALTER TABLE [dbo].[REDataSource] ADD CONSTRAINT [FK_REDataSource_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REERHelpText ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REERHelpText] ( + [ERHelpID] smallint NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Text] nvarchar(max) NOT NULL, + [Grouping] nvarchar(20) NOT NULL, + [ImagePath] nvarchar(50) NOT NULL, + PRIMARY KEY ([ERHelpID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REExConfig ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REExConfig] ( + [ExConfigGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(max) NOT NULL, + [SheetGUID] uniqueidentifier NOT NULL, + [ParentGUID] uniqueidentifier NOT NULL, + [ConfigType] int NOT NULL, + [DataSource] nvarchar(max) NOT NULL, + [Dimension] nvarchar(max) NOT NULL, + [UseParentContext] bit NOT NULL, + [RangeAddress] nvarchar(max) NOT NULL, + [Descending] bit NOT NULL, + [IsWebDrillDownable] bit NOT NULL, + [HiddenPIndex] int NOT NULL, + [DDIconAlignment] bit NOT NULL, + [DrillDownDimension] nvarchar(max) NOT NULL, + [ClickCellAddress] nchar(10) NOT NULL, + [FilterDimensionMember] nvarchar(max) NOT NULL, + [HideConsolidatedMembers] bit NOT NULL, + PRIMARY KEY ([ExConfigGUID]) +); +GO +ALTER TABLE [dbo].[REExConfig] ADD CONSTRAINT [FK_REExConfig_REExConfig] FOREIGN KEY ([SheetGUID]) REFERENCES [dbo].[RESheetConfig] ([SheetGUID]); GO +ALTER TABLE [dbo].[REExConfig] ADD CONSTRAINT [DF_REExConfig_IsWebDrillDownable] DEFAULT ((0)) FOR [IsWebDrillDownable]; GO +ALTER TABLE [dbo].[REExConfig] ADD CONSTRAINT [DF_REExConfig_HiddenPIndex] DEFAULT ((0)) FOR [HiddenPIndex]; GO +ALTER TABLE [dbo].[REExConfig] ADD CONSTRAINT [DF_REExConfig_ClickPIndex] DEFAULT ((0)) FOR [DDIconAlignment]; GO +ALTER TABLE [dbo].[REExConfig] ADD CONSTRAINT [DF_REExConfig_DrillDownDimension] DEFAULT ('') FOR [DrillDownDimension]; GO +ALTER TABLE [dbo].[REExConfig] ADD CONSTRAINT [DF_REExConfig_ClickCellAddress] DEFAULT ('0') FOR [ClickCellAddress]; GO +ALTER TABLE [dbo].[REExConfig] ADD CONSTRAINT [DF_REExConfig_FilterDimensionMember] DEFAULT ('') FOR [FilterDimensionMember]; GO +ALTER TABLE [dbo].[REExConfig] ADD CONSTRAINT [DF_REExConfig_HideConsolidatedMembers] DEFAULT ((0)) FOR [HideConsolidatedMembers]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REExConfigFilterMembers ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REExConfigFilterMembers] ( + [ExConfigGUID] uniqueidentifier NOT NULL, + [FilterMember] nvarchar(100) NOT NULL, + PRIMARY KEY ([ExConfigGUID], [FilterMember]) +); +GO +ALTER TABLE [dbo].[REExConfigFilterMembers] ADD CONSTRAINT [FK_REEXCONFIG_EXCONFIGGUID] FOREIGN KEY ([ExConfigGUID]) REFERENCES [dbo].[REExConfig] ([ExConfigGUID]); GO +ALTER TABLE [dbo].[REExConfigFilterMembers] ADD CONSTRAINT [DF_REExConfigFilterMembers_FilterMember] DEFAULT ('') FOR [FilterMember]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REExReportSetup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REExReportSetup] ( + [ExReportSetupGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [ExReportTemplateGUID] uniqueidentifier NOT NULL, + [OutputType] nvarchar(64) NOT NULL, + [ParametersXML] nvarchar(max) NOT NULL, + PRIMARY KEY ([ExReportSetupGUID]) +); +GO +ALTER TABLE [dbo].[REExReportSetup] ADD CONSTRAINT [FK_REExReportSetup_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[REExReportSetup] ADD CONSTRAINT [DF_REExReportSetup_ExReportSetupGUID] DEFAULT (newid()) FOR [ExReportSetupGUID]; GO +ALTER TABLE [dbo].[REExReportSetup] ADD CONSTRAINT [DF_REExReportSetup_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO +ALTER TABLE [dbo].[REExReportSetup] ADD CONSTRAINT [DF_REExReportSetup_ExReportTemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ExReportTemplateGUID]; GO +ALTER TABLE [dbo].[REExReportSetup] ADD CONSTRAINT [DF_REExReportSetup_OutputType] DEFAULT ('') FOR [OutputType]; GO +ALTER TABLE [dbo].[REExReportSetup] ADD CONSTRAINT [DF_REExReportSetup_ParametersXML] DEFAULT ('') FOR [ParametersXML]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REExtractReportOutputColumn ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REExtractReportOutputColumn] ( + [ExtractReportOutputFormatColumnGUID] uniqueidentifier NOT NULL, + [ClientReportSetupGUID] uniqueidentifier NULL, + [ClientReportSectionIdentifierGUID] uniqueidentifier NULL, + [DisplayOrder] int NOT NULL, + [IsTrimLeadingZeroes] bit NOT NULL, + [FormatString] nvarchar(100) NOT NULL, + [NullHandler] smallint NOT NULL, + PRIMARY KEY ([ExtractReportOutputFormatColumnGUID]) +); +GO +ALTER TABLE [dbo].[REExtractReportOutputColumn] ADD CONSTRAINT [FK__REExtract__Clien__494731A0] FOREIGN KEY ([ClientReportSetupGUID]) REFERENCES [dbo].[REClientReportSetup] ([ClientReportSetupGUID]); GO +ALTER TABLE [dbo].[REExtractReportOutputColumn] ADD CONSTRAINT [DF__REExtract__NullH__004E191E] DEFAULT ((0)) FOR [NullHandler]; GO +ALTER TABLE [dbo].[REExtractReportOutputColumn] ADD CONSTRAINT [DF__REExtract__Extra__475EE92E] DEFAULT (newid()) FOR [ExtractReportOutputFormatColumnGUID]; GO +ALTER TABLE [dbo].[REExtractReportOutputColumn] ADD CONSTRAINT [DF__REExtract__Clien__48530D67] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ClientReportSetupGUID]; GO +ALTER TABLE [dbo].[REExtractReportOutputColumn] ADD CONSTRAINT [DF__REExtract__Clien__4A3B55D9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ClientReportSectionIdentifierGUID]; GO +ALTER TABLE [dbo].[REExtractReportOutputColumn] ADD CONSTRAINT [DF__REExtract__Displ__4B2F7A12] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[REExtractReportOutputColumn] ADD CONSTRAINT [DF__REExtract__IsTri__4C239E4B] DEFAULT ((0)) FOR [IsTrimLeadingZeroes]; GO +ALTER TABLE [dbo].[REExtractReportOutputColumn] ADD CONSTRAINT [DF__REExtract__Forma__4D17C284] DEFAULT ('') FOR [FormatString]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REExtractReportOutputFormat ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REExtractReportOutputFormat] ( + [ExtractReportOutputFormatGUID] uniqueidentifier NOT NULL, + [ClientReportSetupGUID] uniqueidentifier NULL, + [FilenameExtension] nvarchar(10) NOT NULL, + [SourceFileTypeVal] smallint NOT NULL, + [ConfigXML] nvarchar(max) NOT NULL, + [IsCompressed] bit NOT NULL, + [IsDatetimeIncluded] bit NOT NULL, + [IsCleaningCarriageReturn] bit NOT NULL, + [IsCleaningSpecialCharacters] bit NOT NULL, + PRIMARY KEY ([ExtractReportOutputFormatGUID]) +); +GO +ALTER TABLE [dbo].[REExtractReportOutputFormat] ADD CONSTRAINT [FK__REExtract__Clien__3EC9A32D] FOREIGN KEY ([ClientReportSetupGUID]) REFERENCES [dbo].[REClientReportSetup] ([ClientReportSetupGUID]); GO +ALTER TABLE [dbo].[REExtractReportOutputFormat] ADD CONSTRAINT [DF__REExtract__IsDat__1660B4F4] DEFAULT ((0)) FOR [IsDatetimeIncluded]; GO +ALTER TABLE [dbo].[REExtractReportOutputFormat] ADD CONSTRAINT [DF__REExtract__IsCle__1754D92D] DEFAULT ((0)) FOR [IsCleaningCarriageReturn]; GO +ALTER TABLE [dbo].[REExtractReportOutputFormat] ADD CONSTRAINT [DF__REExtract__IsCle__1848FD66] DEFAULT ((0)) FOR [IsCleaningSpecialCharacters]; GO +ALTER TABLE [dbo].[REExtractReportOutputFormat] ADD CONSTRAINT [DF__REExtract__Extra__3CE15ABB] DEFAULT (newid()) FOR [ExtractReportOutputFormatGUID]; GO +ALTER TABLE [dbo].[REExtractReportOutputFormat] ADD CONSTRAINT [DF__REExtract__Clien__3DD57EF4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ClientReportSetupGUID]; GO +ALTER TABLE [dbo].[REExtractReportOutputFormat] ADD CONSTRAINT [DF__REExtract__Filen__3FBDC766] DEFAULT ('') FOR [FilenameExtension]; GO +ALTER TABLE [dbo].[REExtractReportOutputFormat] ADD CONSTRAINT [DF__REExtract__Sourc__40B1EB9F] DEFAULT ((0)) FOR [SourceFileTypeVal]; GO +ALTER TABLE [dbo].[REExtractReportOutputFormat] ADD CONSTRAINT [DF__REExtract__Confi__41A60FD8] DEFAULT ('') FOR [ConfigXML]; GO +ALTER TABLE [dbo].[REExtractReportOutputFormat] ADD CONSTRAINT [DF__REExtract__IsCom__668E471B] DEFAULT ((0)) FOR [IsCompressed]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REFileReportSetup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REFileReportSetup] ( + [FileReportSetupGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [Extension] nvarchar(64) NOT NULL, + [ImageName] nvarchar(64) NOT NULL, + [OriginalFileName] nvarchar(400) NOT NULL, + [ContentLengthInByte] int NOT NULL, + PRIMARY KEY ([FileReportSetupGUID]) +); +GO +ALTER TABLE [dbo].[REFileReportSetup] ADD CONSTRAINT [FK_REFileReportSetup_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[REFileReportSetup] ADD CONSTRAINT [DF_REFileReportSetupGUID_FileReportSetupGUID] DEFAULT (newid()) FOR [FileReportSetupGUID]; GO +ALTER TABLE [dbo].[REFileReportSetup] ADD CONSTRAINT [DF_REFileReportSetupGUID_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO +ALTER TABLE [dbo].[REFileReportSetup] ADD CONSTRAINT [DF_REFileReportSetupGUID_Extension] DEFAULT ('') FOR [Extension]; GO +ALTER TABLE [dbo].[REFileReportSetup] ADD CONSTRAINT [DF_REFileReportSetupGUID_ImageName] DEFAULT ('') FOR [ImageName]; GO +ALTER TABLE [dbo].[REFileReportSetup] ADD CONSTRAINT [DF_REFileReportSetupGUID_OriginalFileName] DEFAULT ('') FOR [OriginalFileName]; GO +ALTER TABLE [dbo].[REFileReportSetup] ADD CONSTRAINT [DF_REFileReportSetupGUID_ContentLengthInByte] DEFAULT ((0)) FOR [ContentLengthInByte]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REFormReportSetup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REFormReportSetup] ( + [FormReportSetupGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [FormGUID] uniqueidentifier NOT NULL, + [PlanGUIDs] nvarchar(max) NOT NULL, + [PlanNames] nvarchar(max) NOT NULL, + PRIMARY KEY ([FormReportSetupGUID]) +); +GO +ALTER TABLE [dbo].[REFormReportSetup] ADD CONSTRAINT [DF_REFormReportSetup_FormReportSetupGUID] DEFAULT (newid()) FOR [FormReportSetupGUID]; GO +ALTER TABLE [dbo].[REFormReportSetup] ADD CONSTRAINT [DF_REFormReportSetup_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO +ALTER TABLE [dbo].[REFormReportSetup] ADD CONSTRAINT [DF_REFormReportSetup_FormGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormGUID]; GO +ALTER TABLE [dbo].[REFormReportSetup] ADD CONSTRAINT [DF_REFormReportSetup_PlanGUIDs] DEFAULT ('') FOR [PlanGUIDs]; GO +ALTER TABLE [dbo].[REFormReportSetup] ADD CONSTRAINT [DF_REFormReportSetup_PlanNames] DEFAULT ('') FOR [PlanNames]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REGroupingParameter ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REGroupingParameter] ( + [GroupingParameterGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [ParameterValueXML] nvarchar(max) NOT NULL, + [IsEditable] bit NOT NULL, + [DefaultLinkedParameterGUID] uniqueidentifier NOT NULL, + [SortOrder] int NOT NULL, + [IsMultiSelect] bit NOT NULL, + [IsExpandable] bit NOT NULL, + PRIMARY KEY ([GroupingParameterGUID]) +); +GO +ALTER TABLE [dbo].[REGroupingParameter] ADD CONSTRAINT [FK_REGroupingParameter_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[REGroupingParameter] ADD CONSTRAINT [DF_REGroupingParameter_DefaultLinkedParameterGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultLinkedParameterGUID]; GO +ALTER TABLE [dbo].[REGroupingParameter] ADD CONSTRAINT [DF_REGroupingParameter_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO +ALTER TABLE [dbo].[REGroupingParameter] ADD CONSTRAINT [DF_REGroupingParameter2_GroupingParameterGUID] DEFAULT (newid()) FOR [GroupingParameterGUID]; GO +ALTER TABLE [dbo].[REGroupingParameter] ADD CONSTRAINT [DF_REGroupingParameter_IsEditable] DEFAULT ((1)) FOR [IsEditable]; GO +ALTER TABLE [dbo].[REGroupingParameter] ADD CONSTRAINT [DF_REGroupingParameter_Order] DEFAULT ((-1)) FOR [SortOrder]; GO +ALTER TABLE [dbo].[REGroupingParameter] ADD CONSTRAINT [DF_REGroupingParameter_IsMultiSelect] DEFAULT ((1)) FOR [IsMultiSelect]; GO +ALTER TABLE [dbo].[REGroupingParameter] ADD CONSTRAINT [DF__REGroupin__IsExp__65114617] DEFAULT ((1)) FOR [IsExpandable]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REGroupingParameterLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REGroupingParameterLink] ( + [GroupingParameterLinkGUID] uniqueidentifier NOT NULL, + [GroupingParameterGUID] uniqueidentifier NOT NULL, + [LinkedSourceGUID] uniqueidentifier NOT NULL, + [LinkedParameterGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([GroupingParameterLinkGUID]) +); +GO +ALTER TABLE [dbo].[REGroupingParameterLink] ADD CONSTRAINT [FK_REGroupingParameterLink_REGroupingParameter] FOREIGN KEY ([GroupingParameterGUID]) REFERENCES [dbo].[REGroupingParameter] ([GroupingParameterGUID]); GO +ALTER TABLE [dbo].[REGroupingParameterLink] ADD CONSTRAINT [DF_REGroupingParameterParameterLink_GroupingParameterParameterLinkGUID] DEFAULT (newid()) FOR [GroupingParameterLinkGUID]; GO +ALTER TABLE [dbo].[REGroupingParameterLink] ADD CONSTRAINT [DF_REGroupingParameterParameterLink_GroupingParameterGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingParameterGUID]; GO +ALTER TABLE [dbo].[REGroupingParameterLink] ADD CONSTRAINT [DF_REGroupingParameterParameterLink_LinkedSourceGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LinkedSourceGUID]; GO +ALTER TABLE [dbo].[REGroupingParameterLink] ADD CONSTRAINT [DF_REGroupingParameterParameterLink_LinkedParameterGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LinkedParameterGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RELootType ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RELootType] ( + [ID] uniqueidentifier NOT NULL, + [LootType] int NOT NULL, + [LootTypeName] nvarchar(64) NOT NULL, + [VERSION] timestamp NOT NULL, + PRIMARY KEY ([ID]) +); +GO +ALTER TABLE [dbo].[RELootType] ADD CONSTRAINT [DF_RELootType_ID] DEFAULT (newid()) FOR [ID]; GO +ALTER TABLE [dbo].[RELootType] ADD CONSTRAINT [DF_RELootType_LootType] DEFAULT ((0)) FOR [LootType]; GO +ALTER TABLE [dbo].[RELootType] ADD CONSTRAINT [DF_RELootType_LootTypeName] DEFAULT ('') FOR [LootTypeName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REModelDataReportSetup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REModelDataReportSetup] ( + [ModelDataReportSetupGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [ModelTemplateGUID] uniqueidentifier NOT NULL, + [Ranges] nvarchar(max) NOT NULL, + [EntityViewGUID] uniqueidentifier NOT NULL, + [PlanGUIDs] nvarchar(max) NOT NULL, + [PrintArea] nvarchar(64) NOT NULL, + [PrintTitleRows] nvarchar(64) NOT NULL, + [PrintTitleColumns] nvarchar(64) NOT NULL, + PRIMARY KEY ([ModelDataReportSetupGUID]) +); +GO +ALTER TABLE [dbo].[REModelDataReportSetup] ADD CONSTRAINT [DF_REModelDataReportSetup_PrintArea] DEFAULT ('') FOR [PrintArea]; GO +ALTER TABLE [dbo].[REModelDataReportSetup] ADD CONSTRAINT [DF_REModelDataReportSetup_PrintTitleRows] DEFAULT ('') FOR [PrintTitleRows]; GO +ALTER TABLE [dbo].[REModelDataReportSetup] ADD CONSTRAINT [DF_REModelDataReportSetup_PrintTitleColumns] DEFAULT ('') FOR [PrintTitleColumns]; GO +ALTER TABLE [dbo].[REModelDataReportSetup] ADD CONSTRAINT [DF_REModelDataReportSetup_ModelDataReportSetupGUID] DEFAULT (newid()) FOR [ModelDataReportSetupGUID]; GO +ALTER TABLE [dbo].[REModelDataReportSetup] ADD CONSTRAINT [DF_REModelDataReportSetup_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO +ALTER TABLE [dbo].[REModelDataReportSetup] ADD CONSTRAINT [DF_REModelDataReportSetup_ModelTemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelTemplateGUID]; GO +ALTER TABLE [dbo].[REModelDataReportSetup] ADD CONSTRAINT [DF_REModelDataReportSetup_Ranges] DEFAULT ('') FOR [Ranges]; GO +ALTER TABLE [dbo].[REModelDataReportSetup] ADD CONSTRAINT [DF_REModelDataReportSetup_EntityViewGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityViewGUID]; GO +ALTER TABLE [dbo].[REModelDataReportSetup] ADD CONSTRAINT [DF_REModelDataReportSetup_PlanGUIDs] DEFAULT ('') FOR [PlanGUIDs]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RENumberingParameter ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RENumberingParameter] ( + [ParameterGUID] uniqueidentifier NOT NULL, + [DataSourceGUID] uniqueidentifier NOT NULL, + [StartValue] int NOT NULL, + [StopValue] int NOT NULL, + [StepValue] int NOT NULL, + PRIMARY KEY ([ParameterGUID]) +); +GO +ALTER TABLE [dbo].[RENumberingParameter] ADD CONSTRAINT [FK_RENumberingParameter_REDataSource1] FOREIGN KEY ([DataSourceGUID]) REFERENCES [dbo].[REDataSource] ([DataSourceGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REParameterCache ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REParameterCache] ( + [ReportGUID] uniqueidentifier NOT NULL, + [ParameterCacheGUID] uniqueidentifier NOT NULL, + [Parameters] nvarchar(max) NOT NULL, + [CreatedAt] datetime NOT NULL, + PRIMARY KEY ([ParameterCacheGUID]) +); +GO +ALTER TABLE [dbo].[REParameterCache] ADD CONSTRAINT [FK__REParamet__Repor__2D7196A4] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[REParameterCache] ADD CONSTRAINT [DF__REParamet__Param__2E65BADD] DEFAULT (newid()) FOR [ParameterCacheGUID]; GO +ALTER TABLE [dbo].[REParameterCache] ADD CONSTRAINT [DF__REParamet__Param__2F59DF16] DEFAULT ('') FOR [Parameters]; GO +ALTER TABLE [dbo].[REParameterCache] ADD CONSTRAINT [DF__REParamet__Creat__304E034F] DEFAULT (getdate()) FOR [CreatedAt]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REParameterCrosswalk ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REParameterCrosswalk] ( + [ParameterCrosswalkGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [StructureGUID] uniqueidentifier NOT NULL, + [IsExpanding] bit NOT NULL, + [IsScore] bit NOT NULL, + PRIMARY KEY ([ParameterCrosswalkGUID]) +); +GO +ALTER TABLE [dbo].[REParameterCrosswalk] ADD CONSTRAINT [DF_REParameterCrosswalk_IsExpanding] DEFAULT ((0)) FOR [IsExpanding]; GO +ALTER TABLE [dbo].[REParameterCrosswalk] ADD CONSTRAINT [DF_REParameterCrosswalk_ParameterCrosswalkGUID] DEFAULT (newid()) FOR [ParameterCrosswalkGUID]; GO +ALTER TABLE [dbo].[REParameterCrosswalk] ADD CONSTRAINT [DF_REParameterCrosswalk_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO +ALTER TABLE [dbo].[REParameterCrosswalk] ADD CONSTRAINT [DF_REParameterCrosswalk_StructureGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [StructureGUID]; GO +ALTER TABLE [dbo].[REParameterCrosswalk] ADD CONSTRAINT [DF_REParameterCrosswalk_IsScore] DEFAULT ((0)) FOR [IsScore]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REParameterSet ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REParameterSet] ( + [ParameterSetGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [IsEditable] bit NOT NULL, + [IsRecombiningAfterExpand] bit NOT NULL, + [IsSchedulable] bit NOT NULL, + PRIMARY KEY ([ParameterSetGUID]) +); +GO +ALTER TABLE [dbo].[REParameterSet] ADD CONSTRAINT [DF_REParameterSet_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[REParameterSet] ADD CONSTRAINT [DF_REParameterSet_IsPermanent] DEFAULT ((0)) FOR [IsEditable]; GO +ALTER TABLE [dbo].[REParameterSet] ADD CONSTRAINT [DF_REParameterSet_IsExpanding] DEFAULT ((0)) FOR [IsRecombiningAfterExpand]; GO +ALTER TABLE [dbo].[REParameterSet] ADD CONSTRAINT [DF_REParameterSet_IsScheduleable] DEFAULT ((0)) FOR [IsSchedulable]; GO +ALTER TABLE [dbo].[REParameterSet] ADD CONSTRAINT [DF_REParameterSet_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [dbo].[REParameterSet] ADD CONSTRAINT [DF_REParameterSet_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REParameterSetParameter ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REParameterSetParameter] ( + [ParameterSetParameterGUID] uniqueidentifier NOT NULL, + [ParameterSetGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + [ParameterValueXML] nvarchar(max) NOT NULL, + [SourceID] nvarchar(100) NOT NULL, + [ParameterValueAQN] nvarchar(400) NOT NULL, + PRIMARY KEY ([ParameterSetParameterGUID]) +); +GO +ALTER TABLE [dbo].[REParameterSetParameter] ADD CONSTRAINT [FK_REParameterSetParameter_REParameterSet] FOREIGN KEY ([ParameterSetGUID]) REFERENCES [dbo].[REParameterSet] ([ParameterSetGUID]); GO +ALTER TABLE [dbo].[REParameterSetParameter] ADD CONSTRAINT [DF__REParamet__Sourc__18CF7C5B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SourceID]; GO +ALTER TABLE [dbo].[REParameterSetParameter] ADD CONSTRAINT [DF__REParamet__Param__3CA2C87D] DEFAULT ('') FOR [ParameterValueAQN]; GO +ALTER TABLE [dbo].[REParameterSetParameter] ADD CONSTRAINT [DF_REParameterSetParameter_ParameterSetGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParameterSetGUID]; GO +ALTER TABLE [dbo].[REParameterSetParameter] ADD CONSTRAINT [DF_REParameterSetParameter_DimensionGUID_1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO +ALTER TABLE [dbo].[REParameterSetParameter] ADD CONSTRAINT [DF_REParameterSetParameter_ParameterSetParameterGUID] DEFAULT (newid()) FOR [ParameterSetParameterGUID]; GO +ALTER TABLE [dbo].[REParameterSetParameter] ADD CONSTRAINT [DF_REParameterSetParameter_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[REParameterSetParameter] ADD CONSTRAINT [DF_REParameterSetParameter_DimensionGUID] DEFAULT ('') FOR [ParameterValueXML]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REParameterValue ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REParameterValue] ( + [ParameterValueGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [DataSourceGUID] uniqueidentifier NOT NULL, + [ParameterValueXML] nvarchar(max) NOT NULL, + [AssemblyQualifiedName] nvarchar(450) NOT NULL, + PRIMARY KEY ([ParameterValueGUID]) +); +GO +ALTER TABLE [dbo].[REParameterValue] ADD CONSTRAINT [FK_REParameterValue_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REPatientPopulationLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REPatientPopulationLink] ( + [ReportGUID] uniqueidentifier NOT NULL, + [PatientPopulationID] int NOT NULL +); + +CREATE UNIQUE NONCLUSTERED INDEX [UC_ReportPatientPopulation] ON [dbo].[REPatientPopulationLink] ([ReportGUID], [PatientPopulationID]); +GO +ALTER TABLE [dbo].[REPatientPopulationLink] ADD CONSTRAINT [FK__REPatient__Patie__1E01D6BC] FOREIGN KEY ([PatientPopulationID]) REFERENCES [dss].[DimClinicalIndicator] ([ClinicalIndicatorID]); GO +ALTER TABLE [dbo].[REPatientPopulationLink] ADD CONSTRAINT [FK__REPatient__Repor__1C198E4A] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[REPatientPopulationLink] ADD CONSTRAINT [DF__REPatient__Repor__1B256A11] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO +ALTER TABLE [dbo].[REPatientPopulationLink] ADD CONSTRAINT [DF__REPatient__Patie__1D0DB283] DEFAULT ((0)) FOR [PatientPopulationID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REPlanHackParameterValue ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REPlanHackParameterValue] ( + [ParameterValueGUID] uniqueidentifier NOT NULL, + [ParameterGUID] uniqueidentifier NOT NULL, + [PlanGUIDs] nvarchar(max) NOT NULL, + [EntityViewGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([ParameterValueGUID]) +); +GO +ALTER TABLE [dbo].[REPlanHackParameterValue] ADD CONSTRAINT [DF_REPlanHackParameterValue_ParameterValueGUID] DEFAULT (newid()) FOR [ParameterValueGUID]; GO +ALTER TABLE [dbo].[REPlanHackParameterValue] ADD CONSTRAINT [DF_REPlanHackParameterValue_ParameterGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParameterGUID]; GO +ALTER TABLE [dbo].[REPlanHackParameterValue] ADD CONSTRAINT [DF_REPlanHackParameterValue_PlanGUIDs] DEFAULT ('') FOR [PlanGUIDs]; GO +ALTER TABLE [dbo].[REPlanHackParameterValue] ADD CONSTRAINT [DF_REPlanHackParameterValue_EntityViewGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityViewGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REQueryParameter ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REQueryParameter] ( + [ParameterGUID] uniqueidentifier NOT NULL, + [DataSourceGUID] uniqueidentifier NOT NULL, + [QueryString] nvarchar(max) NOT NULL, + PRIMARY KEY ([ParameterGUID]) +); +GO +ALTER TABLE [dbo].[REQueryParameter] ADD CONSTRAINT [FK_REQueryParameter_REDataSource] FOREIGN KEY ([DataSourceGUID]) REFERENCES [dbo].[REDataSource] ([DataSourceGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REReport ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REReport] ( + [ReportGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Description] nvarchar(450) NOT NULL, + [AssemblyQualifiedName] nvarchar(450) NOT NULL, + [DateCreated] datetime NOT NULL, + [IsBuiltIn] bit NOT NULL, + [IsScheduleable] bit NOT NULL, + [IsDesktopEmbeddable] bit NOT NULL, + [IsPlanEmbeddable] bit NOT NULL, + [IsExecReportEmbeddable] bit NOT NULL, + [IsDirectoryReportable] bit NOT NULL, + [FolderGUID] uniqueidentifier NOT NULL, + [ReportXML] nvarchar(max) NOT NULL, + [IsUserDeletable] bit NOT NULL, + [ImageName] nvarchar(450) NOT NULL, + [DateLastModified] datetime NOT NULL, + [IsCacheable] bit NOT NULL, + [IsCachedPerUser] bit NOT NULL, + [IsBatchReport] bit NOT NULL, + [ReportDetailsXML] nvarchar(max) NOT NULL, + [IsBatchProcessable] bit NOT NULL, + [IsUsingDefaultTime] bit NOT NULL, + [AuthorUserGUID] uniqueidentifier NOT NULL, + [ConsolidatedItemsCSV] nvarchar(max) NOT NULL, + [ExpandedParametersCSV] nvarchar(max) NOT NULL, + [IsUsingZeroViewer] bit NOT NULL, + [IsRecombiningAfterExpand] bit NOT NULL, + [IsDataSource] bit NOT NULL, + [IsUsingPlanAttributes] bit NOT NULL, + [GlobalID] nvarchar(50) NOT NULL, + [IsERMacroEnabled] bit NOT NULL, + [IsAutoSizeRows] bit NOT NULL, + [DateAccessed] datetime NOT NULL, + [ScheduledTaskGUID] uniqueidentifier NOT NULL, + [LastRunDuration] int NOT NULL, + [LastRunRowCount] int NOT NULL, + [SourceReportGuid] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(256) NOT NULL, + [ModuleGUID] uniqueidentifier NOT NULL, + [IsPublished] bit NOT NULL, + [StrataSphereReportGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([ReportGUID]) +); +GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REREPORTTEMP_REPORTGUID] DEFAULT (newid()) FOR [ReportGUID]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REREPORTTEMP_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REREPORTTEMP_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReportTemp_ASSEMBLYQUALIFIEDNAME] DEFAULT ('') FOR [AssemblyQualifiedName]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReportTemp_ISBUILTIN] DEFAULT ((0)) FOR [IsBuiltIn]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReportTemp_ISSCHEDULEABLE] DEFAULT ((0)) FOR [IsScheduleable]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReportTemp_ISDESKTOPEMBEDDABLE] DEFAULT ((0)) FOR [IsDesktopEmbeddable]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF__REReport__Author__0A7E933C] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReportTemp_ISPLANEMBEDDABLE] DEFAULT ((0)) FOR [IsPlanEmbeddable]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReportTemp_ISEXECREPORTEMBEDDABLE] DEFAULT ((0)) FOR [IsExecReportEmbeddable]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReportTemp_ISDIRECTORYREPORTABLE] DEFAULT ((0)) FOR [IsDirectoryReportable]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REREPORTTEMP_REPORTXML] DEFAULT ('') FOR [ReportXML]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_ISUSERDELETABLE] DEFAULT ((1)) FOR [IsUserDeletable]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_IMAGENAME] DEFAULT ('') FOR [ImageName]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_DateLastModified] DEFAULT (getdate()) FOR [DateLastModified]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_IsCacheable] DEFAULT ((0)) FOR [IsCacheable]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_IsCachedPerUser] DEFAULT ((1)) FOR [IsCachedPerUser]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_IsBatchReport] DEFAULT ((0)) FOR [IsBatchReport]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_IsUsingZeroViewer] DEFAULT ((0)) FOR [IsUsingZeroViewer]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_IsRecombiningAfterExpand] DEFAULT ((0)) FOR [IsRecombiningAfterExpand]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF__REReport__Module__1CD64654] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModuleGUID]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF__REReport__LastRu__269488EE] DEFAULT ((0)) FOR [LastRunDuration]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF__REReport__LastRu__2788AD27] DEFAULT ((0)) FOR [LastRunRowCount]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF__REReport__IsPubl__2ABA5157] DEFAULT ((0)) FOR [IsPublished]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF__REReport__DateAc__3120CB42] DEFAULT (getdate()) FOR [DateAccessed]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_IsBatchProcessable] DEFAULT ((0)) FOR [IsBatchProcessable]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_IsUsingDefaultTime] DEFAULT ((0)) FOR [IsUsingDefaultTime]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_IsDataSource] DEFAULT ((0)) FOR [IsDataSource]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_IsUsingPlanAttributes] DEFAULT ((0)) FOR [IsUsingPlanAttributes]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF__REReport__Schedu__429A3411] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScheduledTaskGUID]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_AuthorUserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorUserGUID]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_ConsolidatedItems] DEFAULT ('') FOR [ConsolidatedItemsCSV]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_ExpandedParameters] DEFAULT ('') FOR [ExpandedParametersCSV]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF__REReport__IsERMa__5937E11C] DEFAULT ((0)) FOR [IsERMacroEnabled]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_GlobalID] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_StrataSphereReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [StrataSphereReportGUID]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF_REReport_ReportDetailsXML] DEFAULT ('') FOR [ReportDetailsXML]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF__REReport__Source__76114D24] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SourceReportGuid]; GO +ALTER TABLE [dbo].[REReport] ADD CONSTRAINT [DF__REReport__IsAuto__7B71C199] DEFAULT ((0)) FOR [IsAutoSizeRows]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.REReportCustomActionLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[REReportCustomActionLink] ( + [REReportCustomActionLink] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [ActionGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([REReportCustomActionLink]) +); +GO +ALTER TABLE [dbo].[REReportCustomActionLink] ADD CONSTRAINT [FK_REReportCustomActionLink_CustomAction] FOREIGN KEY ([ActionGUID]) REFERENCES [dbo].[CustomAction] ([ActionGUID]); GO +ALTER TABLE [dbo].[REReportCustomActionLink] ADD CONSTRAINT [FK_REReportCustomActionLink_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RESQLReportDisplayColumn ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RESQLReportDisplayColumn] ( + [DisplayColumnGUID] uniqueidentifier NOT NULL, + [SQLReportSetupGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [DrillDownParentColumnGUID] uniqueidentifier NOT NULL, + [IsDrillDown] bit NOT NULL, + [DisplayOrder] int NOT NULL, + [ColumnWidth] int NOT NULL, + [AggregateFunction] int NOT NULL, + [FormatString] nvarchar(64) NOT NULL, + [ColumnName] nvarchar(64) NOT NULL, + [IsConsolidatable] bit NOT NULL, + [IsConsolidated] bit NOT NULL, + [SimpleDataType] int NOT NULL, + [LayoutType] int NOT NULL, + [SortOrder] int NOT NULL, + [IsAutoWidth] bit NOT NULL, + PRIMARY KEY ([DisplayColumnGUID]) +); +GO +ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [FK_RESQLReportDisplayColumn_RESQLReportSetup] FOREIGN KEY ([SQLReportSetupGUID]) REFERENCES [dbo].[RESQLReportSetup] ([SQLReportSetupGUID]); GO +ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_SortOrder] DEFAULT ((-1)) FOR [SortOrder]; GO +ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_DisplayColumnGUID] DEFAULT (newid()) FOR [DisplayColumnGUID]; GO +ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_IsAutoWidth] DEFAULT ((0)) FOR [IsAutoWidth]; GO +ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_SQLReportSetupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SQLReportSetupGUID]; GO +ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_DrillDownParentColumnGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DrillDownParentColumnGUID]; GO +ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_IsDrillDown] DEFAULT ((0)) FOR [IsDrillDown]; GO +ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_DisplayOrder] DEFAULT ((-1)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_ColumnWidth] DEFAULT ((150)) FOR [ColumnWidth]; GO +ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_AggregateFunction] DEFAULT ((0)) FOR [AggregateFunction]; GO +ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_FormatString] DEFAULT ('') FOR [FormatString]; GO +ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_ColumnName] DEFAULT ('') FOR [ColumnName]; GO +ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_IsConsolidtable] DEFAULT ((0)) FOR [IsConsolidatable]; GO +ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_IsConsolidated] DEFAULT ((0)) FOR [IsConsolidated]; GO +ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_SimpleDataType] DEFAULT ((0)) FOR [SimpleDataType]; GO +ALTER TABLE [dbo].[RESQLReportDisplayColumn] ADD CONSTRAINT [DF_RESQLReportDisplayColumn_LayoutType] DEFAULT ((0)) FOR [LayoutType]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RESQLReportFilterColumn ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RESQLReportFilterColumn] ( + [FilterColumnGUID] uniqueidentifier NOT NULL, + [SQLReportSetupGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [ColumnName] nvarchar(64) NOT NULL, + [ColumnSourceGUID] uniqueidentifier NOT NULL, + [DataViewColumnType] int NOT NULL, + [IsUserEditable] bit NOT NULL, + [SimpleDataType] int NOT NULL, + [ParameterXML] nvarchar(max) NOT NULL, + [IsSQLOperatorEditable] bit NOT NULL, + [DisplayOrder] int NOT NULL, + PRIMARY KEY ([FilterColumnGUID]) +); +GO +ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [FK_RESQLReportFilterColumn_RESQLReportSetup] FOREIGN KEY ([SQLReportSetupGUID]) REFERENCES [dbo].[RESQLReportSetup] ([SQLReportSetupGUID]); GO +ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_FilterColumnGUID] DEFAULT (newid()) FOR [FilterColumnGUID]; GO +ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_SQLReportSetupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SQLReportSetupGUID]; GO +ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_ColumnName] DEFAULT ('') FOR [ColumnName]; GO +ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_ColumnSourceGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ColumnSourceGUID]; GO +ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_DataViewColumnType] DEFAULT ((0)) FOR [DataViewColumnType]; GO +ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_IsUserEditable] DEFAULT ((0)) FOR [IsUserEditable]; GO +ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_SimpleDataType] DEFAULT ((0)) FOR [SimpleDataType]; GO +ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_ParameterXML] DEFAULT ('') FOR [ParameterXML]; GO +ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_DisplayOrder] DEFAULT ((-1)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[RESQLReportFilterColumn] ADD CONSTRAINT [DF_RESQLReportFilterColumn_IsSQLOperatorEditable] DEFAULT ((1)) FOR [IsSQLOperatorEditable]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RESQLReportPivotColumn ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RESQLReportPivotColumn] ( + [PivotColumnGUID] uniqueidentifier NOT NULL, + [SQLReportSetupGUID] uniqueidentifier NOT NULL, + [ValueColumnName] nvarchar(64) NOT NULL, + [DisplayOrder] int NOT NULL, + PRIMARY KEY ([PivotColumnGUID]) +); +GO +ALTER TABLE [dbo].[RESQLReportPivotColumn] ADD CONSTRAINT [FK_RESQLReportPivotColumn_RESQLReportSetup] FOREIGN KEY ([SQLReportSetupGUID]) REFERENCES [dbo].[RESQLReportSetup] ([SQLReportSetupGUID]); GO +ALTER TABLE [dbo].[RESQLReportPivotColumn] ADD CONSTRAINT [DF_RESQLReportPivotColumn_PivotColumnGUID] DEFAULT (newid()) FOR [PivotColumnGUID]; GO +ALTER TABLE [dbo].[RESQLReportPivotColumn] ADD CONSTRAINT [DF_RESQLReportPivotColumn_ValueColumnName] DEFAULT ('') FOR [ValueColumnName]; GO +ALTER TABLE [dbo].[RESQLReportPivotColumn] ADD CONSTRAINT [DF_RESQLReportPivotColumn_DisplayOrder] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[RESQLReportPivotColumn] ADD CONSTRAINT [DF_RESQLReportPivotColumn_SQLReportSetupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SQLReportSetupGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RESQLReportPivotColumnFilter ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RESQLReportPivotColumnFilter] ( + [PivotColumnFilterGUID] uniqueidentifier NOT NULL, + [PivotColumnGUID] uniqueidentifier NOT NULL, + [ColumnName] nvarchar(64) NOT NULL, + [ColumnValue] nvarchar(400) NOT NULL, + [SimpleDataType] int NOT NULL, + PRIMARY KEY ([PivotColumnFilterGUID]) +); +GO +ALTER TABLE [dbo].[RESQLReportPivotColumnFilter] ADD CONSTRAINT [FK_RESQLReportPivotColumnFilter_RESQLReportPivotColumn] FOREIGN KEY ([PivotColumnGUID]) REFERENCES [dbo].[RESQLReportPivotColumn] ([PivotColumnGUID]); GO +ALTER TABLE [dbo].[RESQLReportPivotColumnFilter] ADD CONSTRAINT [DF_RESQLReportPivotColumnFilter_PivotColumnFilterGUID] DEFAULT (newid()) FOR [PivotColumnFilterGUID]; GO +ALTER TABLE [dbo].[RESQLReportPivotColumnFilter] ADD CONSTRAINT [DF_RESQLReportPivotColumnFilter_ColumnName] DEFAULT ('') FOR [ColumnName]; GO +ALTER TABLE [dbo].[RESQLReportPivotColumnFilter] ADD CONSTRAINT [DF_RESQLReportPivotColumnFilter_Value] DEFAULT ('') FOR [ColumnValue]; GO +ALTER TABLE [dbo].[RESQLReportPivotColumnFilter] ADD CONSTRAINT [DF_RESQLReportPivotColumnFilter_SimpleDataType] DEFAULT ((0)) FOR [SimpleDataType]; GO +ALTER TABLE [dbo].[RESQLReportPivotColumnFilter] ADD CONSTRAINT [DF_RESQLReportPivotColumnFilter_PivotColumnGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PivotColumnGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RESQLReportRegisteredAttribute ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RESQLReportRegisteredAttribute] ( + [RegisteredAttributeGUID] uniqueidentifier NOT NULL, + [RegisteredDimensionGUID] uniqueidentifier NOT NULL, + [AttributeGUID] uniqueidentifier NOT NULL, + [ColumnAlias] nvarchar(100) NOT NULL, + PRIMARY KEY ([RegisteredAttributeGUID]) +); +GO +ALTER TABLE [dbo].[RESQLReportRegisteredAttribute] ADD CONSTRAINT [FK_RESQLReportRegisteredAttribute_RESQLReportRegisteredDimension] FOREIGN KEY ([RegisteredDimensionGUID]) REFERENCES [dbo].[RESQLReportRegisteredDimension] ([RegisteredDimensionGUID]); GO +ALTER TABLE [dbo].[RESQLReportRegisteredAttribute] ADD CONSTRAINT [DF_RESQLReportRegisteredDimensionAttribute_SQLReportRegisteredDimensionAttributeGUID] DEFAULT (newid()) FOR [RegisteredAttributeGUID]; GO +ALTER TABLE [dbo].[RESQLReportRegisteredAttribute] ADD CONSTRAINT [DF_RESQLReportRegisteredAttribute_AliasedColumnName] DEFAULT ('') FOR [ColumnAlias]; GO +ALTER TABLE [dbo].[RESQLReportRegisteredAttribute] ADD CONSTRAINT [DF_RESQLReportRegisteredDimensionAttribute_SQLReportRegisteredDimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RegisteredDimensionGUID]; GO +ALTER TABLE [dbo].[RESQLReportRegisteredAttribute] ADD CONSTRAINT [DF_RESQLReportRegisteredDimensionAttribute_AttributeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AttributeGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RESQLReportRegisteredDimension ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RESQLReportRegisteredDimension] ( + [RegisteredDimensionGUID] uniqueidentifier NOT NULL, + [DataViewGUID] uniqueidentifier NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + [HierarchyGUID] uniqueidentifier NOT NULL, + [SQLColumnNames] nvarchar(max) NOT NULL, + [KeyColumnName] nvarchar(64) NOT NULL, + [KeyGUID] uniqueidentifier NOT NULL, + [IsKeyColumnVisible] bit NOT NULL, + [KeyJoinType] int NOT NULL, + [IsSecured] bit NOT NULL, + PRIMARY KEY ([RegisteredDimensionGUID]) +); +GO +ALTER TABLE [dbo].[RESQLReportRegisteredDimension] ADD CONSTRAINT [FK_RESQLReportRegisteredDimension_DataView] FOREIGN KEY ([DataViewGUID]) REFERENCES [dbo].[DataView] ([DataViewGUID]); GO +ALTER TABLE [dbo].[RESQLReportRegisteredDimension] ADD CONSTRAINT [DF_RESQLReportRegisteredDimension_IsKeyColumnVisible] DEFAULT ((1)) FOR [IsKeyColumnVisible]; GO +ALTER TABLE [dbo].[RESQLReportRegisteredDimension] ADD CONSTRAINT [DF_RESQLReportRegisteredDimension_KeyJoinType] DEFAULT ((0)) FOR [KeyJoinType]; GO +ALTER TABLE [dbo].[RESQLReportRegisteredDimension] ADD CONSTRAINT [DF_RESQLReportRegisteredDimension_IsSecured] DEFAULT ((0)) FOR [IsSecured]; GO +ALTER TABLE [dbo].[RESQLReportRegisteredDimension] ADD CONSTRAINT [DF_RESQLReportRegisteredDimension_HierarchyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HierarchyGUID]; GO +ALTER TABLE [dbo].[RESQLReportRegisteredDimension] ADD CONSTRAINT [DF_RESQLReportRegisteredDimension_RegisteredDimensionGUID] DEFAULT (newid()) FOR [RegisteredDimensionGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RESQLReportSetup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RESQLReportSetup] ( + [SQLReportSetupGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [DataViewGUID] uniqueidentifier NOT NULL, + [IsAutoRefresh] bit NOT NULL, + [IsAutoPivotColumn] bit NOT NULL, + [TableStyleName] nvarchar(64) NOT NULL, + [IsAutoColumnWidth] bit NOT NULL, + [LaunchOption] int NOT NULL, + [IsShowingTotals] bit NOT NULL, + [TopRowCount] int NOT NULL, + [IsGroupBy] bit NOT NULL, + [IsSecurityHashJoin] bit NOT NULL, + PRIMARY KEY ([SQLReportSetupGUID]) +); +GO +ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [FK_RESQLReportSetup_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLReportSetup_IsSecurityHashJoin] DEFAULT ((0)) FOR [IsSecurityHashJoin]; GO +ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLReportSetup_IsGroupBy] DEFAULT ((1)) FOR [IsGroupBy]; GO +ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLTableReportSetup_SQLReportSetupGUID] DEFAULT (newid()) FOR [SQLReportSetupGUID]; GO +ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLTableReportSetup_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO +ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLTableReportSetup_DataViewGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataViewGUID]; GO +ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLReportSetup_IsAutoRefresh] DEFAULT ((0)) FOR [IsAutoRefresh]; GO +ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLReportSetup_IsAutoPivotColumn] DEFAULT ((1)) FOR [IsAutoPivotColumn]; GO +ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLReportSetup_TableStyle] DEFAULT ('Blue') FOR [TableStyleName]; GO +ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLReportSetup_IsAutoColumnWidth] DEFAULT ((1)) FOR [IsAutoColumnWidth]; GO +ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLReportSetup_LaunchOption] DEFAULT ((0)) FOR [LaunchOption]; GO +ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLReportSetup_IsShowingTotals] DEFAULT ((0)) FOR [IsShowingTotals]; GO +ALTER TABLE [dbo].[RESQLReportSetup] ADD CONSTRAINT [DF_RESQLReportSetup_TopRowCount] DEFAULT ((100)) FOR [TopRowCount]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RESRReportFile ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RESRReportFile] ( + [SRReportFileGUID] uniqueidentifier NOT NULL, + [SRReportSetupGUID] uniqueidentifier NOT NULL, + [FileContent] nvarchar(max) NOT NULL, + PRIMARY KEY ([SRReportFileGUID]) +); +GO +ALTER TABLE [dbo].[RESRReportFile] ADD CONSTRAINT [FK_RESRReportFile_RESRReportSetup] FOREIGN KEY ([SRReportSetupGUID]) REFERENCES [dbo].[RESRReportSetup] ([SRReportSetupGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RESRReportSetup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RESRReportSetup] ( + [SRReportSetupGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([SRReportSetupGUID]) +); +GO +ALTER TABLE [dbo].[RESRReportSetup] ADD CONSTRAINT [FK_RESRReportSetup_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RESelector ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RESelector] ( + [ID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Value] int NOT NULL, + [Type] nvarchar(64) NOT NULL, + [VERSION] timestamp NOT NULL +); +GO +ALTER TABLE [dbo].[RESelector] ADD CONSTRAINT [DF_REBooleanSelector_ID] DEFAULT (newid()) FOR [ID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RESheetConfig ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RESheetConfig] ( + [SheetGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([SheetGUID]) +); +GO +ALTER TABLE [dbo].[RESheetConfig] ADD CONSTRAINT [FK_RESheetConfig_REReport] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RESortingParameter ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RESortingParameter] ( + [ParameterGUID] uniqueidentifier NOT NULL, + [DataSourceGUID] uniqueidentifier NOT NULL, + [ColumnName] nvarchar(450) NOT NULL, + [Direction] bit NOT NULL, + [SortOrder] int NOT NULL, + PRIMARY KEY ([ParameterGUID]) +); +GO +ALTER TABLE [dbo].[RESortingParameter] ADD CONSTRAINT [FK_RESortingParameter_REDataSource1] FOREIGN KEY ([DataSourceGUID]) REFERENCES [dbo].[REDataSource] ([DataSourceGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RETemplateColumn ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RETemplateColumn] ( + [RETemplateColumnGUID] uniqueidentifier NOT NULL, + [DataSourceGUID] uniqueidentifier NOT NULL, + [ColumnName] varchar(512) NOT NULL, + [ColumnType] int NOT NULL, + [DisplayOrder] int NOT NULL, + PRIMARY KEY ([RETemplateColumnGUID]) +); +GO +ALTER TABLE [dbo].[RETemplateColumn] ADD CONSTRAINT [FK__RETemplat__DataS__1B6C8B71] FOREIGN KEY ([DataSourceGUID]) REFERENCES [dbo].[REDataSource] ([DataSourceGUID]); GO +ALTER TABLE [dbo].[RETemplateColumn] ADD CONSTRAINT [DF__RETemplat__Colum__198442FF] DEFAULT ('') FOR [ColumnName]; GO +ALTER TABLE [dbo].[RETemplateColumn] ADD CONSTRAINT [DF__RETemplat__Colum__1A786738] DEFAULT ((0)) FOR [ColumnType]; GO +ALTER TABLE [dbo].[RETemplateColumn] ADD CONSTRAINT [DF__RETemplat__Displ__1B6C8B71] DEFAULT ((0)) FOR [DisplayOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RETemplateMeasure ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RETemplateMeasure] ( + [RETemplateMeasureGUID] uniqueidentifier NOT NULL, + [DataSourceGUID] uniqueidentifier NOT NULL, + [ColumnName] varchar(512) NOT NULL, + [ColumnType] int NOT NULL, + [DisplayOrder] int NOT NULL, + PRIMARY KEY ([RETemplateMeasureGUID]) +); +GO +ALTER TABLE [dbo].[RETemplateMeasure] ADD CONSTRAINT [FK__RETemplat__DataS__230DAD39] FOREIGN KEY ([DataSourceGUID]) REFERENCES [dbo].[REDataSource] ([DataSourceGUID]); GO +ALTER TABLE [dbo].[RETemplateMeasure] ADD CONSTRAINT [DF__RETemplat__Colum__212564C7] DEFAULT ('') FOR [ColumnName]; GO +ALTER TABLE [dbo].[RETemplateMeasure] ADD CONSTRAINT [DF__RETemplat__Colum__22198900] DEFAULT ((0)) FOR [ColumnType]; GO +ALTER TABLE [dbo].[RETemplateMeasure] ADD CONSTRAINT [DF__RETemplat__Displ__230DAD39] DEFAULT ((0)) FOR [DisplayOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ReasonableURL ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ReasonableURL] ( + [ReasonableURLGUID] uniqueidentifier NOT NULL, + [URL] nvarchar(max) NOT NULL, + [CreatedDate] datetime NOT NULL, + [LastUsedDate] datetime NOT NULL, + [UseCount] int NOT NULL, + PRIMARY KEY ([ReasonableURLGUID]) +); +GO +ALTER TABLE [dbo].[ReasonableURL] ADD CONSTRAINT [DF_ReasonableURL_ReasonableURLGUID] DEFAULT (newsequentialid()) FOR [ReasonableURLGUID]; GO +ALTER TABLE [dbo].[ReasonableURL] ADD CONSTRAINT [DF_ReasonableURL_CreatedDate] DEFAULT (getdate()) FOR [CreatedDate]; GO +ALTER TABLE [dbo].[ReasonableURL] ADD CONSTRAINT [DF_ReasonableURL_LastUsedDate] DEFAULT (getdate()) FOR [LastUsedDate]; GO +ALTER TABLE [dbo].[ReasonableURL] ADD CONSTRAINT [DF_ReasonableURL_UseCount] DEFAULT ((0)) FOR [UseCount]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RefreshViewsLog ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RefreshViewsLog] ( + [RowID] int NOT NULL, + [BrokenViewName] nvarchar(450) NOT NULL, + [BrokenViewDropSQL] nvarchar(450) NOT NULL, + [BrokenViewSelectSQL] nvarchar(450) NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [dbo].[RefreshViewsLog] ADD CONSTRAINT [DF_RefreshViewsLog_BrokenViewName] DEFAULT ('') FOR [BrokenViewName]; GO +ALTER TABLE [dbo].[RefreshViewsLog] ADD CONSTRAINT [DF_RefreshViewsLog_BrokenViewDropSQL] DEFAULT ('') FOR [BrokenViewDropSQL]; GO +ALTER TABLE [dbo].[RefreshViewsLog] ADD CONSTRAINT [DF_RefreshViewsLog_BrokenViewSelectSQL] DEFAULT ('') FOR [BrokenViewSelectSQL]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ReplicationTable ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ReplicationTable] ( + [TableName] nvarchar(200) NOT NULL, + [LastRefreshDateTimeUtc] datetime NULL, + [LastRefreshChangeTrackingVersion] bigint NULL, + [ReplicationFrequencyCron] varchar(100) NOT NULL, + [IsDisabled] bit NOT NULL, + [SelectFromQuery] nvarchar(200) NOT NULL, + [LastChangeDateTimeUtc] datetime NULL, + [HangfireQueue] nvarchar(200) NOT NULL, + [BeginChangeTrackingVersion] bigint NOT NULL, + [NumParallelBatches] int NOT NULL, + [ColumnDataJSON] nvarchar(max) NOT NULL, + PRIMARY KEY ([TableName]) +); +GO +ALTER TABLE [dbo].[ReplicationTable] ADD CONSTRAINT [DF__Replicati__Repli__0582D584] DEFAULT ('*/5 * * * *') FOR [ReplicationFrequencyCron]; GO +ALTER TABLE [dbo].[ReplicationTable] ADD CONSTRAINT [DF__Replicati__IsDis__0676F9BD] DEFAULT ((0)) FOR [IsDisabled]; GO +ALTER TABLE [dbo].[ReplicationTable] ADD CONSTRAINT [DF__Replicati__Begin__0F02E974] DEFAULT ((0)) FOR [BeginChangeTrackingVersion]; GO +ALTER TABLE [dbo].[ReplicationTable] ADD CONSTRAINT [DF__Replicati__NumPa__0FF70DAD] DEFAULT ((1)) FOR [NumParallelBatches]; GO +ALTER TABLE [dbo].[ReplicationTable] ADD CONSTRAINT [DF__Replicati__Selec__16AD6186] DEFAULT ('') FOR [SelectFromQuery]; GO +ALTER TABLE [dbo].[ReplicationTable] ADD CONSTRAINT [DF__Replicati__Hangf__4104595C] DEFAULT ('default') FOR [HangfireQueue]; GO +ALTER TABLE [dbo].[ReplicationTable] ADD CONSTRAINT [DF__Replicati__Colum__65634C11] DEFAULT ('[]') FOR [ColumnDataJSON]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ReplicationTableHistory ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ReplicationTableHistory] ( + [RowID] bigint NOT NULL, + [ReplicationTableName] nvarchar(200) NOT NULL, + [DateTimeStamp] datetime NOT NULL, + [Description] nvarchar(1000) NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [dbo].[ReplicationTableHistory] ADD CONSTRAINT [DF__Replicati__DateT__5DAAB9AB] DEFAULT (getdate()) FOR [DateTimeStamp]; GO +ALTER TABLE [dbo].[ReplicationTableHistory] ADD CONSTRAINT [DF__Replicati__Descr__5E9EDDE4] DEFAULT ('') FOR [Description]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ReplicationTableTrackingTable ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ReplicationTableTrackingTable] ( + [BaseTableName] nvarchar(200) NOT NULL, + [TableName] nvarchar(200) NOT NULL, + [LastRefreshChangeTrackingVersion] bigint NULL, + PRIMARY KEY ([BaseTableName], [TableName]) +); +GO +ALTER TABLE [dbo].[ReplicationTableTrackingTable] ADD CONSTRAINT [FK__Replicati__BaseT__00540C13] FOREIGN KEY ([BaseTableName]) REFERENCES [dbo].[ReplicationTable] ([TableName]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ReportArchiveEntry ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ReportArchiveEntry] ( + [ReportArchiveEntryGUID] uniqueidentifier NOT NULL, + [ReportArchivePath] nvarchar(1000) NOT NULL, + [ReportArchiveType] int NOT NULL, + [ReportArchiveDate] datetime NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [UserName] nvarchar(128) NOT NULL, + [DateArchivedUtc] datetime NOT NULL, + [NotificationMessageGUID] uniqueidentifier NOT NULL, + [IsS3] bit NOT NULL, + PRIMARY KEY ([ReportArchiveEntryGUID]) +); +GO +ALTER TABLE [dbo].[ReportArchiveEntry] ADD CONSTRAINT [DF__ReportArc__Repor__030D1E07] DEFAULT (getdate()) FOR [ReportArchiveDate]; GO +ALTER TABLE [dbo].[ReportArchiveEntry] ADD CONSTRAINT [DF__ReportArch__IsS3__0D9B5A9D] DEFAULT ((0)) FOR [IsS3]; GO +ALTER TABLE [dbo].[ReportArchiveEntry] ADD CONSTRAINT [DF__ReportArc__DateA__369A42D4] DEFAULT (getutcdate()) FOR [DateArchivedUtc]; GO +ALTER TABLE [dbo].[ReportArchiveEntry] ADD CONSTRAINT [DF__ReportArc__Notif__42C34FF3] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [NotificationMessageGUID]; GO +ALTER TABLE [dbo].[ReportArchiveEntry] ADD CONSTRAINT [DF__ReportArc__UserG__4FE27FBC] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[ReportArchiveEntry] ADD CONSTRAINT [DF__ReportArc__UserN__50D6A3F5] DEFAULT ('') FOR [UserName]; GO +ALTER TABLE [dbo].[ReportArchiveEntry] ADD CONSTRAINT [DF__ReportArc__Repor__779B6B5B] DEFAULT (newid()) FOR [ReportArchiveEntryGUID]; GO +ALTER TABLE [dbo].[ReportArchiveEntry] ADD CONSTRAINT [DF__ReportArc__Repor__788F8F94] DEFAULT ('') FOR [ReportArchivePath]; GO +ALTER TABLE [dbo].[ReportArchiveEntry] ADD CONSTRAINT [DF__ReportArc__Repor__7983B3CD] DEFAULT ((0)) FOR [ReportArchiveType]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ReportArchiveEntryDetail ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ReportArchiveEntryDetail] ( + [ReportArchiveEntryDetailGUID] uniqueidentifier NOT NULL, + [ReportArchiveEntryGUID] uniqueidentifier NOT NULL, + [ReportArchiveDetailAQN] nvarchar(400) NOT NULL, + [ReportArchiveDetailXML] xml(max) NOT NULL, + PRIMARY KEY ([ReportArchiveEntryDetailGUID]) +); +GO +ALTER TABLE [dbo].[ReportArchiveEntryDetail] ADD CONSTRAINT [FK__ReportArc__Repor__7F3C8D23] FOREIGN KEY ([ReportArchiveEntryGUID]) REFERENCES [dbo].[ReportArchiveEntry] ([ReportArchiveEntryGUID]); GO +ALTER TABLE [dbo].[ReportArchiveEntryDetail] ADD CONSTRAINT [DF__ReportArc__Repor__0030B15C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportArchiveEntryGUID]; GO +ALTER TABLE [dbo].[ReportArchiveEntryDetail] ADD CONSTRAINT [DF__ReportArc__Repor__0124D595] DEFAULT ('') FOR [ReportArchiveDetailAQN]; GO +ALTER TABLE [dbo].[ReportArchiveEntryDetail] ADD CONSTRAINT [DF__ReportArc__Repor__0218F9CE] DEFAULT ('') FOR [ReportArchiveDetailXML]; GO +ALTER TABLE [dbo].[ReportArchiveEntryDetail] ADD CONSTRAINT [DF__ReportArc__Repor__7E4868EA] DEFAULT (newid()) FOR [ReportArchiveEntryDetailGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RoleAssignmentAutomationHistoryLog ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RoleAssignmentAutomationHistoryLog] ( + [RoleAssignmentAutomationHistoryLogGuid] uniqueidentifier NOT NULL, + [ImportDate] datetime NOT NULL, + [Status] varchar(7) NOT NULL, + [ImportedRowCount] int NOT NULL, + [NewAssignments] int NOT NULL, + [RemovedAssignments] int NOT NULL, + [InvalidAssignments] int NOT NULL, + PRIMARY KEY ([RoleAssignmentAutomationHistoryLogGuid]) +); +GO +ALTER TABLE [dbo].[RoleAssignmentAutomationHistoryLog] ADD CONSTRAINT [DF__RoleAssig__RoleA__23E03B04] DEFAULT (newid()) FOR [RoleAssignmentAutomationHistoryLogGuid]; GO +ALTER TABLE [dbo].[RoleAssignmentAutomationHistoryLog] ADD CONSTRAINT [DF__RoleAssig__Impor__24D45F3D] DEFAULT ((0)) FOR [ImportedRowCount]; GO +ALTER TABLE [dbo].[RoleAssignmentAutomationHistoryLog] ADD CONSTRAINT [DF__RoleAssig__NewAs__25C88376] DEFAULT ((0)) FOR [NewAssignments]; GO +ALTER TABLE [dbo].[RoleAssignmentAutomationHistoryLog] ADD CONSTRAINT [DF__RoleAssig__Remov__26BCA7AF] DEFAULT ((0)) FOR [RemovedAssignments]; GO +ALTER TABLE [dbo].[RoleAssignmentAutomationHistoryLog] ADD CONSTRAINT [DF__RoleAssig__Inval__27B0CBE8] DEFAULT ((0)) FOR [InvalidAssignments]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RoleVisibilityRule ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RoleVisibilityRule] ( + [RoleVisibilityRuleGUID] uniqueidentifier NOT NULL, + [PermissionSetID] tinyint NOT NULL, + [RoleID] smallint NOT NULL, + [UserGroupGUID] uniqueidentifier NOT NULL, + [IsVisible] bit NOT NULL, + PRIMARY KEY ([RoleVisibilityRuleGUID]) +); +GO +ALTER TABLE [dbo].[RoleVisibilityRule] ADD CONSTRAINT [DF__RoleVisib__RoleV__2567FB65] DEFAULT (newid()) FOR [RoleVisibilityRuleGUID]; GO +ALTER TABLE [dbo].[RoleVisibilityRule] ADD CONSTRAINT [DF__RoleVisib__Permi__265C1F9E] DEFAULT ((0)) FOR [PermissionSetID]; GO +ALTER TABLE [dbo].[RoleVisibilityRule] ADD CONSTRAINT [DF__RoleVisib__RoleI__275043D7] DEFAULT ((0)) FOR [RoleID]; GO +ALTER TABLE [dbo].[RoleVisibilityRule] ADD CONSTRAINT [DF__RoleVisib__IsVis__29388C49] DEFAULT ((1)) FOR [IsVisible]; GO +ALTER TABLE [dbo].[RoleVisibilityRule] ADD CONSTRAINT [DF__RoleVisib__UserG__28446810] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGroupGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RuleAction ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RuleAction] ( + [RuleActionGUID] uniqueidentifier NOT NULL, + [RuleSetGUID] uniqueidentifier NOT NULL, + [ExecutionOrder] int NOT NULL, + [RuleActionTypeAQN] nvarchar(450) NOT NULL, + [RuleActionTypeConfigXML] xml(max) NOT NULL, + PRIMARY KEY ([RuleActionGUID]) +); + +CREATE XML INDEX [es19833_RuleActionTypeConfigXML] ON [dbo].[RuleAction] ([RuleActionTypeConfigXML]); +GO +ALTER TABLE [dbo].[RuleAction] ADD CONSTRAINT [FK_RuleAction_RuleSet] FOREIGN KEY ([RuleSetGUID]) REFERENCES [dbo].[RuleSet] ([RuleSetGUID]); GO +ALTER TABLE [dbo].[RuleAction] ADD CONSTRAINT [DF_RuleAction_RuleActionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RuleActionGUID]; GO +ALTER TABLE [dbo].[RuleAction] ADD CONSTRAINT [DF_RuleAction_RuleSetGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RuleSetGUID]; GO +ALTER TABLE [dbo].[RuleAction] ADD CONSTRAINT [DF_RuleAction_ExecutionOrder] DEFAULT ((0)) FOR [ExecutionOrder]; GO +ALTER TABLE [dbo].[RuleAction] ADD CONSTRAINT [DF_RuleAction_RuleActionTypeAQN] DEFAULT ('') FOR [RuleActionTypeAQN]; GO +ALTER TABLE [dbo].[RuleAction] ADD CONSTRAINT [DF_RuleAction_RuleActionTypeConfigXML] DEFAULT ('') FOR [RuleActionTypeConfigXML]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RuleGroup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RuleGroup] ( + [RuleGroupGUID] uniqueidentifier NOT NULL, + [RuleSetGUID] uniqueidentifier NOT NULL, + [GroupType] int NOT NULL, + [DisplayOrder] int NOT NULL, + [ParentRuleGroupGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([RuleGroupGUID]) +); +GO +ALTER TABLE [dbo].[RuleGroup] ADD CONSTRAINT [FK_RuleGroup_RuleSet] FOREIGN KEY ([RuleSetGUID]) REFERENCES [dbo].[RuleSet] ([RuleSetGUID]); GO +ALTER TABLE [dbo].[RuleGroup] ADD CONSTRAINT [DF_RuleGroup_RuleGroupGUID] DEFAULT (newid()) FOR [RuleGroupGUID]; GO +ALTER TABLE [dbo].[RuleGroup] ADD CONSTRAINT [DF_Table_1_Type] DEFAULT ((0)) FOR [GroupType]; GO +ALTER TABLE [dbo].[RuleGroup] ADD CONSTRAINT [DF_RuleGroup_DisplayOrder] DEFAULT ((-1)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[RuleGroup] ADD CONSTRAINT [DF_RuleGroup_RuleSetGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RuleSetGUID]; GO +ALTER TABLE [dbo].[RuleGroup] ADD CONSTRAINT [DF_RuleGroup_ParentRuleGroupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentRuleGroupGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RuleItem ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RuleItem] ( + [RuleGUID] uniqueidentifier NOT NULL, + [RuleGroupGUID] uniqueidentifier NOT NULL, + [RuleTypeAQN] nvarchar(450) NOT NULL, + [RuleTypeConfigXML] xml(max) NOT NULL, + [DisplayOrder] int NOT NULL, + [Name] nvarchar(100) NOT NULL, + PRIMARY KEY ([RuleGUID]) +); + +CREATE NONCLUSTERED INDEX [NC_RuleItem_RuleGroupGUID] ON [dbo].[RuleItem] ([RuleGroupGUID]) INCLUDE ([RuleTypeConfigXML]); +GO +ALTER TABLE [dbo].[RuleItem] ADD CONSTRAINT [FK_Rule_RuleGroup] FOREIGN KEY ([RuleGroupGUID]) REFERENCES [dbo].[RuleGroup] ([RuleGroupGUID]); GO +ALTER TABLE [dbo].[RuleItem] ADD CONSTRAINT [DF_Rule_RuleGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RuleGUID]; GO +ALTER TABLE [dbo].[RuleItem] ADD CONSTRAINT [DF_Rule_RuleTypeAQN] DEFAULT ('') FOR [RuleTypeAQN]; GO +ALTER TABLE [dbo].[RuleItem] ADD CONSTRAINT [DF_Rule_RuleTypeConfigXML] DEFAULT ('') FOR [RuleTypeConfigXML]; GO +ALTER TABLE [dbo].[RuleItem] ADD CONSTRAINT [DF_Rule_DisplayOrder] DEFAULT ((-1)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[RuleItem] ADD CONSTRAINT [DF_Rule_RuleGroupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RuleGroupGUID]; GO +ALTER TABLE [dbo].[RuleItem] ADD CONSTRAINT [DF__RuleItem__Name__54D0BCAD] DEFAULT ('') FOR [Name]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.RuleSet ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[RuleSet] ( + [RuleSetGUID] uniqueidentifier NOT NULL, + [Category] nvarchar(100) NOT NULL, + [ExecutionOrder] int NOT NULL, + [RootRuleGroupGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Description] nvarchar(800) NOT NULL, + [RuleSetID] int NOT NULL, + [Tag] nvarchar(100) NOT NULL, + [MetadataXML] nvarchar(max) NOT NULL, + [MetadataAssemblyQualifiedName] nvarchar(400) NOT NULL, + PRIMARY KEY ([RuleSetGUID]) +); + +CREATE NONCLUSTERED INDEX [NC_RuleSet_Category] ON [dbo].[RuleSet] ([Category]); +CREATE NONCLUSTERED INDEX [NC_RS_RuleSetID_Category] ON [dbo].[RuleSet] ([RuleSetID]) INCLUDE ([Category]); +GO +ALTER TABLE [dbo].[RuleSet] ADD CONSTRAINT [DF_RuleSet_RuleSetGUID] DEFAULT (newid()) FOR [RuleSetGUID]; GO +ALTER TABLE [dbo].[RuleSet] ADD CONSTRAINT [DF_RuleSet_Category] DEFAULT ('') FOR [Category]; GO +ALTER TABLE [dbo].[RuleSet] ADD CONSTRAINT [DF_RuleSet_ExecutionOrder] DEFAULT ((-1)) FOR [ExecutionOrder]; GO +ALTER TABLE [dbo].[RuleSet] ADD CONSTRAINT [DF__RuleSet__Name__3ABA800B] DEFAULT ('Term') FOR [Name]; GO +ALTER TABLE [dbo].[RuleSet] ADD CONSTRAINT [DF__RuleSet__Discrip__3BAEA444] DEFAULT ('New Term') FOR [Description]; GO +ALTER TABLE [dbo].[RuleSet] ADD CONSTRAINT [DF_RuleSet_RootRuleGroupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RootRuleGroupGUID]; GO +ALTER TABLE [dbo].[RuleSet] ADD CONSTRAINT [DF__RuleSet__Tag__787A1D67] DEFAULT ('') FOR [Tag]; GO +ALTER TABLE [dbo].[RuleSet] ADD CONSTRAINT [DF__RuleSet__Metadat__7E32F6BD] DEFAULT ('') FOR [MetadataXML]; GO +ALTER TABLE [dbo].[RuleSet] ADD CONSTRAINT [DF__RuleSet__Metadat__7F271AF6] DEFAULT ('') FOR [MetadataAssemblyQualifiedName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.S3AutomationNotification ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[S3AutomationNotification] ( + [SecurityAutomationNotificationGUID] uniqueidentifier NOT NULL, + [RecipientGuid] uniqueidentifier NOT NULL, + PRIMARY KEY ([SecurityAutomationNotificationGUID]) +); +GO +ALTER TABLE [dbo].[S3AutomationNotification] ADD CONSTRAINT [DF__SecurityA__Secur__378675A7] DEFAULT (newid()) FOR [SecurityAutomationNotificationGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.S3AutomationRole ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[S3AutomationRole] ( + [SecurityAutomationRoleGUID] uniqueidentifier NOT NULL, + [UserRoleGUID] uniqueidentifier NOT NULL, + [ColumnName] nvarchar(100) NOT NULL, + PRIMARY KEY ([SecurityAutomationRoleGUID]) +); +GO +ALTER TABLE [dbo].[S3AutomationRole] ADD CONSTRAINT [FK_SecurityAutomationRole_UserRoleGUID] FOREIGN KEY ([UserRoleGUID]) REFERENCES [dbo].[UserRole] ([UserRoleGUID]); GO +ALTER TABLE [dbo].[S3AutomationRole] ADD CONSTRAINT [DF__SecurityA__Secur__3A62E252] DEFAULT (newid()) FOR [SecurityAutomationRoleGUID]; GO +ALTER TABLE [dbo].[S3AutomationRole] ADD CONSTRAINT [DF__SecurityA__Colum__3B57068B] DEFAULT ('') FOR [ColumnName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.S3IdentityLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[S3IdentityLink] ( + [MemberGUID] uniqueidentifier NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [Fullpath] varchar(800) NOT NULL, + [Distance] int NOT NULL, + [Version] timestamp NOT NULL, + PRIMARY KEY ([MemberGUID], [GroupingGUID], [Fullpath]) +); + +CREATE NONCLUSTERED INDEX [IX_S3IdentityLink] ON [dbo].[S3IdentityLink] ([GroupingGUID], [MemberGUID]); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.S3Loot ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[S3Loot] ( + [LootID] nvarchar(128) NOT NULL, + [PermissionSetID] smallint NOT NULL, + [LootGroupPrefix] nvarchar(128) NULL, + PRIMARY KEY ([LootID]) +); +GO +ALTER TABLE [dbo].[S3Loot] ADD CONSTRAINT [DF_S3Loot_LootGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LootID]; GO +ALTER TABLE [dbo].[S3Loot] ADD CONSTRAINT [DF_S3Loot_PermissionSetID] DEFAULT ((0)) FOR [PermissionSetID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.S3LootGroup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[S3LootGroup] ( + [LootID] nvarchar(128) NOT NULL, + [LootGroupID] nvarchar(128) NOT NULL, + PRIMARY KEY ([LootID], [LootGroupID]) +); + +CREATE NONCLUSTERED INDEX [IX_S3LootGroup] ON [dbo].[S3LootGroup] ([LootGroupID], [LootID]); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.S3LootRefreshLog ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[S3LootRefreshLog] ( + [RowID] bigint NOT NULL, + [PlanGUID] uniqueidentifier NOT NULL, + [OldCachedLootID] nvarchar(128) NOT NULL, + [NewCachedLootID] nvarchar(128) NOT NULL, + [DateRefreshed] datetime NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [dbo].[S3LootRefreshLog] ADD CONSTRAINT [DF_S3LootRefreshLog_PlanGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanGUID]; GO +ALTER TABLE [dbo].[S3LootRefreshLog] ADD CONSTRAINT [DF_S3LootRefreshLog_OldCachedLootID] DEFAULT ('') FOR [OldCachedLootID]; GO +ALTER TABLE [dbo].[S3LootRefreshLog] ADD CONSTRAINT [DF_S3LootRefreshLog_NewCachedLootID] DEFAULT ('') FOR [NewCachedLootID]; GO +ALTER TABLE [dbo].[S3LootRefreshLog] ADD CONSTRAINT [DF_S3LootRefreshLog_DateRefreshed] DEFAULT (getdate()) FOR [DateRefreshed]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.S3Permission ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[S3Permission] ( + [PermissionSetID] smallint NOT NULL, + [RoleID] smallint NOT NULL, + [Weight] tinyint NOT NULL, + [ReadValue] bit NULL, + [WriteValue] bit NULL, + [SecureValue] bit NULL, + [CreateValue] bit NULL, + [DeleteValue] bit NULL, + [ReadAllowPts] decimal NOT NULL, + [ReadDenyPts] decimal NOT NULL, + [WriteAllowPts] decimal NOT NULL, + [WriteDenyPts] decimal NOT NULL, + [SecureAllowPts] decimal NOT NULL, + [SecureDenyPts] decimal NOT NULL, + [CreateAllowPts] decimal NOT NULL, + [CreateDenyPts] decimal NOT NULL, + [DeleteAllowPts] decimal NOT NULL, + [DeleteDenyPts] decimal NOT NULL, + PRIMARY KEY ([PermissionSetID], [RoleID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.S3PermissionSet ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[S3PermissionSet] ( + [PermissionSetID] smallint NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Description] varchar(max) NOT NULL, + [MetaForUpgrade] varchar(max) NULL, + [IsLocked] bit NOT NULL, + PRIMARY KEY ([PermissionSetID]) +); +GO +ALTER TABLE [dbo].[S3PermissionSet] ADD CONSTRAINT [DF_S3PermissionSet_Description] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[S3PermissionSet] ADD CONSTRAINT [DF_S3PermissionSet_IsLocked] DEFAULT ((0)) FOR [IsLocked]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.S3RoleAssignment ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[S3RoleAssignment] ( + [RowID] int NOT NULL, + [IdentityGUID] uniqueidentifier NOT NULL, + [RoleID] smallint NOT NULL, + [LootGroupID] nvarchar(128) NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [IsMarkedDeleted] bit NOT NULL, + [LootGroupPrefix] nvarchar(128) NULL, + PRIMARY KEY ([IdentityGUID], [RoleID], [LootGroupID]) +); + +CREATE NONCLUSTERED INDEX [IX_S3RoleAssignment] ON [dbo].[S3RoleAssignment] ([LootGroupID], [RoleID], [IdentityGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [UX_S3RoleAssignment] ON [dbo].[S3RoleAssignment] ([RowID]); +GO +ALTER TABLE [dbo].[S3RoleAssignment] ADD CONSTRAINT [DF_S3RoleAssignment_IsDeleted] DEFAULT ((0)) FOR [IsMarkedDeleted]; GO +ALTER TABLE [dbo].[S3RoleAssignment] ADD CONSTRAINT [DF_S3RoleAssignment_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.S3SimplePermission ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[S3SimplePermission] ( + [PermissionGUID] uniqueidentifier NOT NULL, + [LootID] uniqueidentifier NOT NULL, + [IdentityGUID] uniqueidentifier NOT NULL, + [ReadValue] bit NOT NULL, + [WriteValue] bit NOT NULL, + [SecureValue] bit NOT NULL, + PRIMARY KEY ([PermissionGUID]) +); + +CREATE NONCLUSTERED INDEX [IX_S3SimplePermission_ByLootIdentity] ON [dbo].[S3SimplePermission] ([LootID], [IdentityGUID]) INCLUDE ([PermissionGUID], [ReadValue], [WriteValue], [SecureValue]); +CREATE NONCLUSTERED INDEX [IX_S3SimplePermission_ByIdentityLoot] ON [dbo].[S3SimplePermission] ([IdentityGUID], [LootID]) INCLUDE ([ReadValue], [WriteValue]); +GO +ALTER TABLE [dbo].[S3SimplePermission] ADD CONSTRAINT [DF_S3SimplePermission_PermissionGUID] DEFAULT (newid()) FOR [PermissionGUID]; GO +ALTER TABLE [dbo].[S3SimplePermission] ADD CONSTRAINT [DF_S3SimplePermission_LootID] DEFAULT (newid()) FOR [LootID]; GO +ALTER TABLE [dbo].[S3SimplePermission] ADD CONSTRAINT [DF_S3SimplePermission_IdentityGUID] DEFAULT (newid()) FOR [IdentityGUID]; GO +ALTER TABLE [dbo].[S3SimplePermission] ADD CONSTRAINT [DF_S3SimplePermission_ReadValue] DEFAULT ('0') FOR [ReadValue]; GO +ALTER TABLE [dbo].[S3SimplePermission] ADD CONSTRAINT [DF_S3SimplePermission_WriteValue] DEFAULT ('0') FOR [WriteValue]; GO +ALTER TABLE [dbo].[S3SimplePermission] ADD CONSTRAINT [DF_S3SimplePermission_SecureValue] DEFAULT ('0') FOR [SecureValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.S3SimplePermissionDefault ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[S3SimplePermissionDefault] ( + [EntityType] int NOT NULL, + [IdentityGUID] uniqueidentifier NOT NULL, + [ReadValue] bit NOT NULL, + [WriteValue] bit NOT NULL, + [SecureValue] bit NOT NULL, + PRIMARY KEY ([EntityType], [IdentityGUID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.S3UserACLRegenRequest ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[S3UserACLRegenRequest] ( + [RequestGUID] uniqueidentifier NOT NULL, + [IssuedAt] datetime NOT NULL, + PRIMARY KEY ([RequestGUID]) +); +GO +ALTER TABLE [dbo].[S3UserACLRegenRequest] ADD CONSTRAINT [DF__S3UserACL__Reque__4734CBFC] DEFAULT (newid()) FOR [RequestGUID]; GO +ALTER TABLE [dbo].[S3UserACLRegenRequest] ADD CONSTRAINT [DF__S3UserACL__Issue__4828F035] DEFAULT (getdate()) FOR [IssuedAt]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SAScenarioShockLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SAScenarioShockLink] ( + [LinkGUID] uniqueidentifier NOT NULL, + [ScenarioGUID] uniqueidentifier NOT NULL, + [ShockGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([LinkGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IU_ScenarioGUID_ShockGUID] ON [dbo].[SAScenarioShockLink] ([ScenarioGUID], [ShockGUID]); +GO +ALTER TABLE [dbo].[SAScenarioShockLink] ADD CONSTRAINT [DF_SAScenarioShockLink_LinkGUID] DEFAULT (newid()) FOR [LinkGUID]; GO +ALTER TABLE [dbo].[SAScenarioShockLink] ADD CONSTRAINT [DF_SAScenarioShockLink_ScenarioGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScenarioGUID]; GO +ALTER TABLE [dbo].[SAScenarioShockLink] ADD CONSTRAINT [DF_SAScenarioShockLink_ShockGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ShockGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SAShock ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SAShock] ( + [ShockGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(200) NULL, + [PlanTypeGUID] uniqueidentifier NOT NULL, + [PlanFilter] nvarchar(max) NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [DateCreated] datetime NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [ValueType] smallint NOT NULL, + [IsDeleted] bit NOT NULL, + [ShockAssumptionTypeGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([ShockGUID]) +); +GO +ALTER TABLE [dbo].[SAShock] ADD CONSTRAINT [DF__SAShock__ShockAs__06F35711] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ShockAssumptionTypeGUID]; GO +ALTER TABLE [dbo].[SAShock] ADD CONSTRAINT [DF_SAShock_ShockGUID] DEFAULT (newid()) FOR [ShockGUID]; GO +ALTER TABLE [dbo].[SAShock] ADD CONSTRAINT [DF_SAShock_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SAShock] ADD CONSTRAINT [DF_SAShock_PlanFilter] DEFAULT ('') FOR [PlanFilter]; GO +ALTER TABLE [dbo].[SAShock] ADD CONSTRAINT [DF_SAShock_DateCreated] DEFAULT (getdate()) FOR [DateCreated]; GO +ALTER TABLE [dbo].[SAShock] ADD CONSTRAINT [DF_SAShock_Comment] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [dbo].[SAShock] ADD CONSTRAINT [DF_SAShock_ValueType] DEFAULT ((0)) FOR [ValueType]; GO +ALTER TABLE [dbo].[SAShock] ADD CONSTRAINT [DF__FactAccShock__IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [dbo].[SAShock] ADD CONSTRAINT [DF_SAShock_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO +ALTER TABLE [dbo].[SAShock] ADD CONSTRAINT [DF_SAShock_AuthorGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SAShockAssumptionColumnConfig ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SAShockAssumptionColumnConfig] ( + [ShockAssumptionColumnConfigID] int NOT NULL, + [ShockAssumptionTypeGUID] uniqueidentifier NOT NULL, + [DataIndexName] nvarchar(50) NOT NULL, + [DisplayName] nvarchar(50) NOT NULL, + [IsHiddenColumn] bit NOT NULL, + [DimensionGuid] uniqueidentifier NOT NULL, + PRIMARY KEY ([ShockAssumptionColumnConfigID]) +); +GO +ALTER TABLE [dbo].[SAShockAssumptionColumnConfig] ADD CONSTRAINT [DF__ShockAssu__Shock__022EA1F4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ShockAssumptionTypeGUID]; GO +ALTER TABLE [dbo].[SAShockAssumptionColumnConfig] ADD CONSTRAINT [DF_ShockAssumptionColumnConfig_DataIndexName] DEFAULT ('') FOR [DataIndexName]; GO +ALTER TABLE [dbo].[SAShockAssumptionColumnConfig] ADD CONSTRAINT [DF_ShockAssumptionColumnConfig_DisplayName] DEFAULT ('') FOR [DisplayName]; GO +ALTER TABLE [dbo].[SAShockAssumptionColumnConfig] ADD CONSTRAINT [DF_ShockAssumptionColumnConfig_IsHiddenColumn] DEFAULT ((0)) FOR [IsHiddenColumn]; GO +ALTER TABLE [dbo].[SAShockAssumptionColumnConfig] ADD CONSTRAINT [DF__SAShockAs__Dimen__5A75B655] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGuid]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SAShockAssumptionType ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SAShockAssumptionType] ( + [ShockAssumptionTypeGUID] uniqueidentifier NOT NULL, + [AssumptionGroupID] smallint NOT NULL, + [PlanTypeGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [BaseTableName] nvarchar(50) NOT NULL, + [ShockTableName] nvarchar(50) NOT NULL, + [WhereClauseXML] xml(max) NOT NULL, + [DisplayFormat] nvarchar(50) NOT NULL, + [IsPercentage] bit NOT NULL, + [FormulaColumnName] nvarchar(max) NOT NULL, + [CommentColumnName] nvarchar(max) NOT NULL, + PRIMARY KEY ([ShockAssumptionTypeGUID]) +); +GO +ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF_dbo.SAShockAssumptionType_FormulaColumnName] DEFAULT ('') FOR [FormulaColumnName]; GO +ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF_dbo.SAShockAssumptionType_CommentColumnName] DEFAULT ('') FOR [CommentColumnName]; GO +ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF__ShockAssu__Shock__77B11381] DEFAULT (newid()) FOR [ShockAssumptionTypeGUID]; GO +ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF_dbo.ShockAssumptionType_AssumptionGroupID] DEFAULT ((0)) FOR [AssumptionGroupID]; GO +ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF__ShockAssu__PlanT__79995BF3] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO +ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF_dbo.ShockAssumptionType_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF_dbo.ShockAssumptionType_BaseTableName] DEFAULT ('') FOR [BaseTableName]; GO +ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF_dbo.ShockAssumptionType_ShockTableName] DEFAULT ('') FOR [ShockTableName]; GO +ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF_dbo.ShockAssumptionType_WhereClauseXML] DEFAULT ('') FOR [WhereClauseXML]; GO +ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF_dbo.ShockAssumptionType_DisplayFormat] DEFAULT ('') FOR [DisplayFormat]; GO +ALTER TABLE [dbo].[SAShockAssumptionType] ADD CONSTRAINT [DF_dbo.ShockAssumptionType_IsPercentage] DEFAULT ((0)) FOR [IsPercentage]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SAShockViewByOptions ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SAShockViewByOptions] ( + [RowID] bigint NOT NULL, + [ShockGUID] uniqueidentifier NOT NULL, + [ChkPatientClass] bit NOT NULL, + [ChkServiceLineRollup] bit NOT NULL, + [ChkServiceLine] bit NOT NULL, + [ChkMedicalSurgical] bit NOT NULL, + [ChkAgeCohort] bit NOT NULL, + [ChkPayorOrPayorGroup] bit NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [dbo].[SAShockViewByOptions] ADD CONSTRAINT [FK_SAShockViewByOptions_SAShock] FOREIGN KEY ([ShockGUID]) REFERENCES [dbo].[SAShock] ([ShockGUID]); GO +ALTER TABLE [dbo].[SAShockViewByOptions] ADD CONSTRAINT [DF_SAShockViewByOptions_ShockGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ShockGUID]; GO +ALTER TABLE [dbo].[SAShockViewByOptions] ADD CONSTRAINT [DF_SAShockViewByOptions_ChkPatientClass] DEFAULT ((0)) FOR [ChkPatientClass]; GO +ALTER TABLE [dbo].[SAShockViewByOptions] ADD CONSTRAINT [DF_SAShockViewByOptions_ChkServiceLineRollup] DEFAULT ((0)) FOR [ChkServiceLineRollup]; GO +ALTER TABLE [dbo].[SAShockViewByOptions] ADD CONSTRAINT [DF_SAShockViewByOptions_ChkServiceLine] DEFAULT ((0)) FOR [ChkServiceLine]; GO +ALTER TABLE [dbo].[SAShockViewByOptions] ADD CONSTRAINT [DF_SAShockViewByOptions_ChkMedicalSurgical] DEFAULT ((0)) FOR [ChkMedicalSurgical]; GO +ALTER TABLE [dbo].[SAShockViewByOptions] ADD CONSTRAINT [DF_SAShockViewByOptions_ChkAgeCohort] DEFAULT ((0)) FOR [ChkAgeCohort]; GO +ALTER TABLE [dbo].[SAShockViewByOptions] ADD CONSTRAINT [DF_SAShockViewByOptions_ChkPayorOrPayorGroup] DEFAULT ((0)) FOR [ChkPayorOrPayorGroup]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SBKeyColumn ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SBKeyColumn] ( + [SBKeyColumnGUID] uniqueidentifier NOT NULL, + [SBTargetGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(400) NOT NULL, + [VERSION] timestamp NOT NULL, + PRIMARY KEY ([SBKeyColumnGUID]) +); +GO +ALTER TABLE [dbo].[SBKeyColumn] ADD CONSTRAINT [DF_SBKeyColumn_SBKeyColumnGUID] DEFAULT (newid()) FOR [SBKeyColumnGUID]; GO +ALTER TABLE [dbo].[SBKeyColumn] ADD CONSTRAINT [DF_SBKeyColumn_SBTargetGUID] DEFAULT (newid()) FOR [SBTargetGUID]; GO +ALTER TABLE [dbo].[SBKeyColumn] ADD CONSTRAINT [DF_SBKeyColumn_Name] DEFAULT ('') FOR [Name]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SBProject ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SBProject] ( + [SBProjectGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(400) NOT NULL, + [TemplateFilePath] nvarchar(400) NOT NULL, + [Context] nvarchar(2000) NOT NULL, + [VERSION] timestamp NOT NULL, + PRIMARY KEY ([SBProjectGUID]) +); +GO +ALTER TABLE [dbo].[SBProject] ADD CONSTRAINT [DF_SBProject_SBProjectGUID] DEFAULT (newid()) FOR [SBProjectGUID]; GO +ALTER TABLE [dbo].[SBProject] ADD CONSTRAINT [DF_SBProject_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SBProject] ADD CONSTRAINT [DF_SBProject_TemplateFilePath] DEFAULT ('') FOR [TemplateFilePath]; GO +ALTER TABLE [dbo].[SBProject] ADD CONSTRAINT [DF_SBProject_Context] DEFAULT ('') FOR [Context]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SBSource ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SBSource] ( + [SBSourceGUID] uniqueidentifier NOT NULL, + [SQLQuery] nvarchar(max) NOT NULL, + [SBProjectGUID] uniqueidentifier NOT NULL, + [VERSION] timestamp NOT NULL, + PRIMARY KEY ([SBSourceGUID]) +); +GO +ALTER TABLE [dbo].[SBSource] ADD CONSTRAINT [DF_SBSource_SBSource] DEFAULT (newid()) FOR [SBSourceGUID]; GO +ALTER TABLE [dbo].[SBSource] ADD CONSTRAINT [DF_SBSource_SQLQuery] DEFAULT ('') FOR [SQLQuery]; GO +ALTER TABLE [dbo].[SBSource] ADD CONSTRAINT [DF_SBSource_SBProjectGUID] DEFAULT (newid()) FOR [SBProjectGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SBTarget ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SBTarget] ( + [SBTargetGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(400) NOT NULL, + [TableName] nvarchar(400) NOT NULL, + [SBProjectGUID] uniqueidentifier NOT NULL, + [VERSION] timestamp NOT NULL, + PRIMARY KEY ([SBTargetGUID]) +); +GO +ALTER TABLE [dbo].[SBTarget] ADD CONSTRAINT [DF_SBTarget_SBTargetGUID] DEFAULT (newid()) FOR [SBTargetGUID]; GO +ALTER TABLE [dbo].[SBTarget] ADD CONSTRAINT [DF_SBTarget_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SBTarget] ADD CONSTRAINT [DF_SBTarget_TableName] DEFAULT ('') FOR [TableName]; GO +ALTER TABLE [dbo].[SBTarget] ADD CONSTRAINT [DF_SBTarget_SBProjectGUID] DEFAULT (newid()) FOR [SBProjectGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SBValueColumn ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SBValueColumn] ( + [SBValueColumnGUID] uniqueidentifier NOT NULL, + [SBTargetGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(400) NOT NULL, + [AggregateFunction] nvarchar(400) NOT NULL, + [VERSION] timestamp NOT NULL, + PRIMARY KEY ([SBValueColumnGUID]) +); +GO +ALTER TABLE [dbo].[SBValueColumn] ADD CONSTRAINT [DF_SBValueColumn_SBValueColumnGUID] DEFAULT (newid()) FOR [SBValueColumnGUID]; GO +ALTER TABLE [dbo].[SBValueColumn] ADD CONSTRAINT [DF_SBValueColumn_SBTargetGUID] DEFAULT (newid()) FOR [SBTargetGUID]; GO +ALTER TABLE [dbo].[SBValueColumn] ADD CONSTRAINT [DF_SBValueColumn_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SBValueColumn] ADD CONSTRAINT [DF_SBValueColumn_AggregateFunction] DEFAULT ('') FOR [AggregateFunction]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SEScript ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SEScript] ( + [ScriptGUID] uniqueidentifier NOT NULL, + [Name] varchar(20) NOT NULL, + [Description] varchar(64) NOT NULL, + [Engine] varchar(3) NOT NULL, + [ScriptCode] varchar(max) NOT NULL, + PRIMARY KEY ([ScriptGUID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SR2CorrelationGroup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SR2CorrelationGroup] ( + [CorrelationGroupGUID] uniqueidentifier NOT NULL, + [TableEditorConfigGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + PRIMARY KEY ([CorrelationGroupGUID]) +); +GO +ALTER TABLE [dbo].[SR2CorrelationGroup] ADD CONSTRAINT [FK_SR2CorrelationGroup_ScoreTableEditorConfig] FOREIGN KEY ([TableEditorConfigGUID]) REFERENCES [dbo].[ScoreTableEditorConfig] ([TableEditorConfigGUID]); GO +ALTER TABLE [dbo].[SR2CorrelationGroup] ADD CONSTRAINT [DF_SR2CorrelationGroup_CorrelationGroupGUID] DEFAULT (newid()) FOR [CorrelationGroupGUID]; GO +ALTER TABLE [dbo].[SR2CorrelationGroup] ADD CONSTRAINT [DF_SR2CorrelationGroup_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SR2CorrelationGroup] ADD CONSTRAINT [DF_SR2CorrelationGroup_TableEditorConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TableEditorConfigGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SR2CorrelationGroupMember ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SR2CorrelationGroupMember] ( + [MemberGUID] uniqueidentifier NOT NULL, + [CorrelationGroupGUID] uniqueidentifier NOT NULL, + [DataTableGUID] uniqueidentifier NOT NULL, + [RowID] int NOT NULL, + [MeasureGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([MemberGUID]) +); +GO +ALTER TABLE [dbo].[SR2CorrelationGroupMember] ADD CONSTRAINT [FK_SR2CorrelationGroupMember_SR2CorrelationGroup] FOREIGN KEY ([CorrelationGroupGUID]) REFERENCES [dbo].[SR2CorrelationGroup] ([CorrelationGroupGUID]); GO +ALTER TABLE [dbo].[SR2CorrelationGroupMember] ADD CONSTRAINT [DF_SR2CorrelationGroupMember_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [dbo].[SR2CorrelationGroupMember] ADD CONSTRAINT [DF_SR2CorrelationGroupMember_RowID] DEFAULT ((0)) FOR [RowID]; GO +ALTER TABLE [dbo].[SR2CorrelationGroupMember] ADD CONSTRAINT [DF_SR2CorrelationGroupMember_CorrelationGroupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CorrelationGroupGUID]; GO +ALTER TABLE [dbo].[SR2CorrelationGroupMember] ADD CONSTRAINT [DF_SR2CorrelationGroupMember_DataTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTableGUID]; GO +ALTER TABLE [dbo].[SR2CorrelationGroupMember] ADD CONSTRAINT [DF_SR2CorrelationGroupMember_MeasureGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SR2Project ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SR2Project] ( + [ProjectGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [InputNameFormat] nvarchar(450) NOT NULL, + [OutputNameFormat] nvarchar(450) NOT NULL, + [SensitivityConfigGUID] uniqueidentifier NOT NULL, + [RiskConfigGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([ProjectGUID]) +); +GO +ALTER TABLE [dbo].[SR2Project] ADD CONSTRAINT [DF_SR2Project_SensitivityConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SensitivityConfigGUID]; GO +ALTER TABLE [dbo].[SR2Project] ADD CONSTRAINT [DF_SR2Project_RiskConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RiskConfigGUID]; GO +ALTER TABLE [dbo].[SR2Project] ADD CONSTRAINT [DF_SNRProject_PackageGUID] DEFAULT (newid()) FOR [ProjectGUID]; GO +ALTER TABLE [dbo].[SR2Project] ADD CONSTRAINT [DF_SR2Project_InputNameFormat] DEFAULT ('') FOR [InputNameFormat]; GO +ALTER TABLE [dbo].[SR2Project] ADD CONSTRAINT [DF_SR2Project_OutputNameFormat] DEFAULT ('') FOR [OutputNameFormat]; GO +ALTER TABLE [dbo].[SR2Project] ADD CONSTRAINT [DF_SNRProject_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SR2Project] ADD CONSTRAINT [DF_SNRProject_Description] DEFAULT ('') FOR [Description]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SR2ProjectModelLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SR2ProjectModelLink] ( + [LinkGUID] uniqueidentifier NOT NULL, + [ProjectGUID] uniqueidentifier NOT NULL, + [ModelGUID] uniqueidentifier NOT NULL, + [ProcessLevel] int NOT NULL, + PRIMARY KEY ([LinkGUID]) +); +GO +ALTER TABLE [dbo].[SR2ProjectModelLink] ADD CONSTRAINT [FK_SNRProjectModelLink_SNRProject] FOREIGN KEY ([ProjectGUID]) REFERENCES [dbo].[SR2Project] ([ProjectGUID]); GO +ALTER TABLE [dbo].[SR2ProjectModelLink] ADD CONSTRAINT [FK_SNRProjectModelLink_XPlan] FOREIGN KEY ([ModelGUID]) REFERENCES [dbo].[XPlan] ([PlanGUID]); GO +ALTER TABLE [dbo].[SR2ProjectModelLink] ADD CONSTRAINT [DF_SR2ProjectModelLink_ProcessLevel] DEFAULT ((-1)) FOR [ProcessLevel]; GO +ALTER TABLE [dbo].[SR2ProjectModelLink] ADD CONSTRAINT [DF_SNRProjectModelLink_LinkGUID] DEFAULT (newid()) FOR [LinkGUID]; GO +ALTER TABLE [dbo].[SR2ProjectModelLink] ADD CONSTRAINT [DF_SNRProjectModelLink_ProjectGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ProjectGUID]; GO +ALTER TABLE [dbo].[SR2ProjectModelLink] ADD CONSTRAINT [DF_SNRProjectModelLink_ModelGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SR2ProjectViewLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SR2ProjectViewLink] ( + [LinkGUID] uniqueidentifier NOT NULL, + [ProjectGUID] uniqueidentifier NOT NULL, + [TableEditorConfigGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([LinkGUID]) +); +GO +ALTER TABLE [dbo].[SR2ProjectViewLink] ADD CONSTRAINT [FK_SNRProjectViewLink_ScoreTableEditorConfig] FOREIGN KEY ([TableEditorConfigGUID]) REFERENCES [dbo].[ScoreTableEditorConfig] ([TableEditorConfigGUID]); GO +ALTER TABLE [dbo].[SR2ProjectViewLink] ADD CONSTRAINT [FK_SNRProjectViewLink_SNRProject] FOREIGN KEY ([ProjectGUID]) REFERENCES [dbo].[SR2Project] ([ProjectGUID]); GO +ALTER TABLE [dbo].[SR2ProjectViewLink] ADD CONSTRAINT [DF_SNRProjectViewLink_LinkGUID] DEFAULT (newid()) FOR [LinkGUID]; GO +ALTER TABLE [dbo].[SR2ProjectViewLink] ADD CONSTRAINT [DF_SNRProjectViewLink_ProjectGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ProjectGUID]; GO +ALTER TABLE [dbo].[SR2ProjectViewLink] ADD CONSTRAINT [DF_SNRProjectViewLink_TableEditorConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TableEditorConfigGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SR2RiskConfig ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SR2RiskConfig] ( + [RiskConfigGUID] uniqueidentifier NOT NULL, + [ProjectGUID] uniqueidentifier NOT NULL, + [BinCount] int NOT NULL, + [TrialCount] int NOT NULL, + [DistributionType] smallint NOT NULL, + [CachedSummary] nvarchar(4000) NOT NULL, + [TaskState] int NOT NULL, + [TaskNumModelsComplete] int NOT NULL, + [TaskErrorGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([RiskConfigGUID]) +); +GO +ALTER TABLE [dbo].[SR2RiskConfig] ADD CONSTRAINT [FK_SR2RiskConfig_SR2Project] FOREIGN KEY ([ProjectGUID]) REFERENCES [dbo].[SR2Project] ([ProjectGUID]); GO +ALTER TABLE [dbo].[SR2RiskConfig] ADD CONSTRAINT [DF_SR2RiskConfig_ExecutionState] DEFAULT ((0)) FOR [TaskState]; GO +ALTER TABLE [dbo].[SR2RiskConfig] ADD CONSTRAINT [DF_SR2RiskConfig_ExecutionPercentComplete] DEFAULT ((0)) FOR [TaskNumModelsComplete]; GO +ALTER TABLE [dbo].[SR2RiskConfig] ADD CONSTRAINT [DF_SR2RiskConfig_TaskErrorGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TaskErrorGUID]; GO +ALTER TABLE [dbo].[SR2RiskConfig] ADD CONSTRAINT [DF_SR2RiskConfig_RiskConfigGUID] DEFAULT (newid()) FOR [RiskConfigGUID]; GO +ALTER TABLE [dbo].[SR2RiskConfig] ADD CONSTRAINT [DF_SR2RiskConfig_BinCount] DEFAULT ((0)) FOR [BinCount]; GO +ALTER TABLE [dbo].[SR2RiskConfig] ADD CONSTRAINT [DF_SR2RiskConfig_TrialCount] DEFAULT ((0)) FOR [TrialCount]; GO +ALTER TABLE [dbo].[SR2RiskConfig] ADD CONSTRAINT [DF_SR2RiskConfig_DistributionType] DEFAULT ((0)) FOR [DistributionType]; GO +ALTER TABLE [dbo].[SR2RiskConfig] ADD CONSTRAINT [DF_SR2RiskConfig_CachedSummary] DEFAULT ('') FOR [CachedSummary]; GO +ALTER TABLE [dbo].[SR2RiskConfig] ADD CONSTRAINT [DF_SR2RiskConfig_ProjectGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ProjectGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SR2RiskConfigInput ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SR2RiskConfigInput] ( + [InputGUID] uniqueidentifier NOT NULL, + [RiskConfigGUID] uniqueidentifier NOT NULL, + [ModelGUID] uniqueidentifier NOT NULL, + [DataTableGUID] uniqueidentifier NOT NULL, + [RowID] int NOT NULL, + [MeasureGUID] uniqueidentifier NOT NULL, + [CachedName] nvarchar(450) NOT NULL, + [GroupName] nvarchar(450) NOT NULL, + [GroupID] int NOT NULL, + PRIMARY KEY ([InputGUID]) +); +GO +ALTER TABLE [dbo].[SR2RiskConfigInput] ADD CONSTRAINT [FK_SR2RiskConfigInput_SR2RiskConfig] FOREIGN KEY ([RiskConfigGUID]) REFERENCES [dbo].[SR2RiskConfig] ([RiskConfigGUID]); GO +ALTER TABLE [dbo].[SR2RiskConfigInput] ADD CONSTRAINT [DF_SR2RiskConfigInput_MeasureGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO +ALTER TABLE [dbo].[SR2RiskConfigInput] ADD CONSTRAINT [DF_SR2RiskConfigInput_ModelGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO +ALTER TABLE [dbo].[SR2RiskConfigInput] ADD CONSTRAINT [DF_SR2RiskConfigInput_DataTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTableGUID]; GO +ALTER TABLE [dbo].[SR2RiskConfigInput] ADD CONSTRAINT [DF_SR2RiskConfigInput_CachedName] DEFAULT ('') FOR [CachedName]; GO +ALTER TABLE [dbo].[SR2RiskConfigInput] ADD CONSTRAINT [DF__SR2RiskCo__Group__39C65BD2] DEFAULT ('') FOR [GroupName]; GO +ALTER TABLE [dbo].[SR2RiskConfigInput] ADD CONSTRAINT [DF_SR2RiskConfigInput_GroupID] DEFAULT ((0)) FOR [GroupID]; GO +ALTER TABLE [dbo].[SR2RiskConfigInput] ADD CONSTRAINT [DF_SR2RiskConfigInput_InputGUID] DEFAULT (newid()) FOR [InputGUID]; GO +ALTER TABLE [dbo].[SR2RiskConfigInput] ADD CONSTRAINT [DF_SR2RiskConfigInput_RowID] DEFAULT ((0)) FOR [RowID]; GO +ALTER TABLE [dbo].[SR2RiskConfigInput] ADD CONSTRAINT [DF_SR2RiskConfigInput_RiskConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RiskConfigGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SR2RiskConfigOutput ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SR2RiskConfigOutput] ( + [OutputGUID] uniqueidentifier NOT NULL, + [RiskConfigGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(450) NOT NULL, + [DisplayFormat] nvarchar(100) NOT NULL, + PRIMARY KEY ([OutputGUID]) +); +GO +ALTER TABLE [dbo].[SR2RiskConfigOutput] ADD CONSTRAINT [FK_SR2RiskConfigOutput_SR2RiskConfig] FOREIGN KEY ([RiskConfigGUID]) REFERENCES [dbo].[SR2RiskConfig] ([RiskConfigGUID]); GO +ALTER TABLE [dbo].[SR2RiskConfigOutput] ADD CONSTRAINT [DF_SR2RiskConfigOutput_DisplayFormat] DEFAULT ('') FOR [DisplayFormat]; GO +ALTER TABLE [dbo].[SR2RiskConfigOutput] ADD CONSTRAINT [DF_SR2RiskConfigOutput_RiskConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RiskConfigGUID]; GO +ALTER TABLE [dbo].[SR2RiskConfigOutput] ADD CONSTRAINT [DF_SR2RiskConfigOutput_OutputGUID] DEFAULT (newid()) FOR [OutputGUID]; GO +ALTER TABLE [dbo].[SR2RiskConfigOutput] ADD CONSTRAINT [DF_SR2RiskConfigOutput_Name] DEFAULT ('') FOR [Name]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SR2RiskConfigOutputMember ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SR2RiskConfigOutputMember] ( + [OutputMemberGUID] uniqueidentifier NOT NULL, + [OutputGUID] uniqueidentifier NOT NULL, + [ModelGUID] uniqueidentifier NOT NULL, + [DataTableGUID] uniqueidentifier NOT NULL, + [RowID] int NOT NULL, + [MeasureGUID] uniqueidentifier NOT NULL, + [CachedName] nvarchar(450) NOT NULL, + PRIMARY KEY ([OutputMemberGUID]) +); +GO +ALTER TABLE [dbo].[SR2RiskConfigOutputMember] ADD CONSTRAINT [FK_SR2RiskConfigOutputMember_SR2RiskConfigOutput] FOREIGN KEY ([OutputGUID]) REFERENCES [dbo].[SR2RiskConfigOutput] ([OutputGUID]); GO +ALTER TABLE [dbo].[SR2RiskConfigOutputMember] ADD CONSTRAINT [DF_SR2RiskConfigOutputMember_OutputGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OutputGUID]; GO +ALTER TABLE [dbo].[SR2RiskConfigOutputMember] ADD CONSTRAINT [DF_SR2RiskConfigOutputMember_MeasureGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO +ALTER TABLE [dbo].[SR2RiskConfigOutputMember] ADD CONSTRAINT [DF_SR2RiskConfigOutputMember_ModelGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO +ALTER TABLE [dbo].[SR2RiskConfigOutputMember] ADD CONSTRAINT [DF_SR2RiskConfigOutputMember_CachedName] DEFAULT ('') FOR [CachedName]; GO +ALTER TABLE [dbo].[SR2RiskConfigOutputMember] ADD CONSTRAINT [DF_SR2RiskConfigOutputMember_DataTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTableGUID]; GO +ALTER TABLE [dbo].[SR2RiskConfigOutputMember] ADD CONSTRAINT [DF_SR2RiskConfigOutputMember_OutputMemberGUID] DEFAULT (newid()) FOR [OutputMemberGUID]; GO +ALTER TABLE [dbo].[SR2RiskConfigOutputMember] ADD CONSTRAINT [DF_SR2RiskConfigOutputMember_RowID] DEFAULT ((0)) FOR [RowID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SR2RiskResult ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SR2RiskResult] ( + [RiskResultGUID] uniqueidentifier NOT NULL, + [RiskConfigGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [DateCreated] datetime NOT NULL, + [BinCount] int NOT NULL, + PRIMARY KEY ([RiskResultGUID]) +); +GO +ALTER TABLE [dbo].[SR2RiskResult] ADD CONSTRAINT [FK_SR2RiskResult_SR2RiskConfig] FOREIGN KEY ([RiskConfigGUID]) REFERENCES [dbo].[SR2RiskConfig] ([RiskConfigGUID]); GO +ALTER TABLE [dbo].[SR2RiskResult] ADD CONSTRAINT [DF_SR2RiskResult_RiskConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RiskConfigGUID]; GO +ALTER TABLE [dbo].[SR2RiskResult] ADD CONSTRAINT [DF_SR2RiskResult_BinCount] DEFAULT ((0)) FOR [BinCount]; GO +ALTER TABLE [dbo].[SR2RiskResult] ADD CONSTRAINT [DF_SR2RiskResult_RiskResultGUID] DEFAULT (newid()) FOR [RiskResultGUID]; GO +ALTER TABLE [dbo].[SR2RiskResult] ADD CONSTRAINT [DF_SR2RiskResult_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SR2RiskResult] ADD CONSTRAINT [DF_SR2RiskResult_DateCreated] DEFAULT (getdate()) FOR [DateCreated]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SR2RiskResultDetail ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SR2RiskResultDetail] ( + [RowID] int NOT NULL, + [RiskResultGUID] uniqueidentifier NOT NULL, + [TrialNumber] int NOT NULL, + [OutputGUID] uniqueidentifier NOT NULL, + [BinNumber] int NOT NULL, + [Value] decimal NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [IsDeleted] bit NOT NULL, + [DetailGUID] uniqueidentifier NOT NULL, + [OutputUniqueID] nvarchar(80) NOT NULL, + [CachedOutputName] nvarchar(450) NOT NULL, + [CachedOutputDisplayFormat] nvarchar(450) NOT NULL, + PRIMARY KEY ([DetailGUID]) +); + +CREATE NONCLUSTERED INDEX [idx_SR2RiskReport] ON [dbo].[SR2RiskResultDetail] ([RiskResultGUID], [OutputGUID]) INCLUDE ([RowID], [TrialNumber], [BinNumber], [Value], [HistoryItemGUID], [IsDeleted], [DetailGUID], [OutputUniqueID]); +GO +ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [FK_SR2RiskResultDetail_SR2RiskResult] FOREIGN KEY ([RiskResultGUID]) REFERENCES [dbo].[SR2RiskResult] ([RiskResultGUID]); GO +ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [DF_SR2RiskResultDetail_BinNumber] DEFAULT ((0)) FOR [BinNumber]; GO +ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [DF_SR2RiskResultDetail_Value] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [DF_SR2RiskResultDetail_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [DF_SR2RiskResultDetail_CachedOutputName] DEFAULT ('') FOR [CachedOutputName]; GO +ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [DF_SR2RiskResultDetail_DetailGUID] DEFAULT (newid()) FOR [DetailGUID]; GO +ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [DF_SR2RiskResultDetail_CachedOutputDisplayFormat] DEFAULT ('') FOR [CachedOutputDisplayFormat]; GO +ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [DF_SR2RiskResultDetail_OutputGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OutputGUID]; GO +ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [DF_SR2RiskResultDetail_RiskResultGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RiskResultGUID]; GO +ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [DF_SR2RiskResultDetail_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [dbo].[SR2RiskResultDetail] ADD CONSTRAINT [DF_SR2RiskResultDetail_TrialNumber] DEFAULT ((0)) FOR [TrialNumber]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SR2RiskTrial ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SR2RiskTrial] ( + [RiskTrialGUID] uniqueidentifier NOT NULL, + [RiskConfigGUID] uniqueidentifier NOT NULL, + [TrialNumber] int NOT NULL, + PRIMARY KEY ([RiskTrialGUID]) +); +GO +ALTER TABLE [dbo].[SR2RiskTrial] ADD CONSTRAINT [DF_SR2RiskTrial_TrialNumber] DEFAULT ((0)) FOR [TrialNumber]; GO +ALTER TABLE [dbo].[SR2RiskTrial] ADD CONSTRAINT [DF_SR2RiskTrial_RiskTrialGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RiskTrialGUID]; GO +ALTER TABLE [dbo].[SR2RiskTrial] ADD CONSTRAINT [DF_SR2RiskTrial_RiskConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RiskConfigGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SR2RiskTrialInput ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SR2RiskTrialInput] ( + [RiskTrialInputGUID] uniqueidentifier NOT NULL, + [RiskTrialGUID] uniqueidentifier NOT NULL, + [InputGUID] uniqueidentifier NOT NULL, + [DistributionPoint] int NOT NULL, + PRIMARY KEY ([RiskTrialInputGUID]) +); +GO +ALTER TABLE [dbo].[SR2RiskTrialInput] ADD CONSTRAINT [FK_SR2RiskTrialInput_SR2RiskTrial] FOREIGN KEY ([RiskTrialGUID]) REFERENCES [dbo].[SR2RiskTrial] ([RiskTrialGUID]); GO +ALTER TABLE [dbo].[SR2RiskTrialInput] ADD CONSTRAINT [DF_SR2RiskTrialInput_RiskTrialGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RiskTrialGUID]; GO +ALTER TABLE [dbo].[SR2RiskTrialInput] ADD CONSTRAINT [DF_SR2RiskTrialInput_DistributionPoint] DEFAULT ((0)) FOR [DistributionPoint]; GO +ALTER TABLE [dbo].[SR2RiskTrialInput] ADD CONSTRAINT [DF_SR2RiskTrialInput_InputGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [InputGUID]; GO +ALTER TABLE [dbo].[SR2RiskTrialInput] ADD CONSTRAINT [DF_SR2RiskTrialInput_RiskTrialInputGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RiskTrialInputGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SR2SensitivityConfig ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SR2SensitivityConfig] ( + [SensitivityConfigGUID] uniqueidentifier NOT NULL, + [ProjectGUID] uniqueidentifier NOT NULL, + [CachedSummary] nvarchar(4000) NOT NULL, + [TaskState] int NOT NULL, + [TaskNumModelsComplete] int NOT NULL, + [TaskErrorGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([SensitivityConfigGUID]) +); +GO +ALTER TABLE [dbo].[SR2SensitivityConfig] ADD CONSTRAINT [FK_SR2SensitivityConfig_SR2Project] FOREIGN KEY ([ProjectGUID]) REFERENCES [dbo].[SR2Project] ([ProjectGUID]); GO +ALTER TABLE [dbo].[SR2SensitivityConfig] ADD CONSTRAINT [DF_SR2SensitivityConfig_ExecutionState] DEFAULT ((0)) FOR [TaskState]; GO +ALTER TABLE [dbo].[SR2SensitivityConfig] ADD CONSTRAINT [DF_SR2SensitivityConfig_ExecutionPercentComplete] DEFAULT ((0)) FOR [TaskNumModelsComplete]; GO +ALTER TABLE [dbo].[SR2SensitivityConfig] ADD CONSTRAINT [DF_SR2SensitivityConfig_SensitivityConfigGUID] DEFAULT (newid()) FOR [SensitivityConfigGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityConfig] ADD CONSTRAINT [DF_SR2SensitivityConfig_CachedSummary] DEFAULT ('') FOR [CachedSummary]; GO +ALTER TABLE [dbo].[SR2SensitivityConfig] ADD CONSTRAINT [DF_SR2SensitivityConfig_TaskErrorGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TaskErrorGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityConfig] ADD CONSTRAINT [DF_SR2SensitivityConfig_ProjectGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ProjectGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SR2SensitivityConfigAutoGroupLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SR2SensitivityConfigAutoGroupLink] ( + [AutoGroupGUID] uniqueidentifier NOT NULL, + [SensitivityConfigGUID] uniqueidentifier NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([AutoGroupGUID]) +); +GO +ALTER TABLE [dbo].[SR2SensitivityConfigAutoGroupLink] ADD CONSTRAINT [FK_SR2SensitivityConfigAutoGroupLink_SR2SensitivityConfig] FOREIGN KEY ([SensitivityConfigGUID]) REFERENCES [dbo].[SR2SensitivityConfig] ([SensitivityConfigGUID]); GO +ALTER TABLE [dbo].[SR2SensitivityConfigAutoGroupLink] ADD CONSTRAINT [DF_SR2SensitivityConfigAutoGroupLink_DimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityConfigAutoGroupLink] ADD CONSTRAINT [DF_SR2SensitivityConfigAutoGroupLink_AutoGroupGUID] DEFAULT (newid()) FOR [AutoGroupGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityConfigAutoGroupLink] ADD CONSTRAINT [DF_SR2SensitivityConfigAutoGroupLink_SensitivityConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SensitivityConfigGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SR2SensitivityConfigCorrelationGroupLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SR2SensitivityConfigCorrelationGroupLink] ( + [LinkGUID] uniqueidentifier NOT NULL, + [SensitivityConfigGUID] uniqueidentifier NOT NULL, + [CorrelationGroupGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([LinkGUID]) +); +GO +ALTER TABLE [dbo].[SR2SensitivityConfigCorrelationGroupLink] ADD CONSTRAINT [FK_SR2SensitivityConfigCorrelationGroupLink_SR2CorrelationGroup] FOREIGN KEY ([CorrelationGroupGUID]) REFERENCES [dbo].[SR2CorrelationGroup] ([CorrelationGroupGUID]); GO +ALTER TABLE [dbo].[SR2SensitivityConfigCorrelationGroupLink] ADD CONSTRAINT [FK_SR2SensitivityConfigCorrelationGroupLink_SR2SensitivityConfig] FOREIGN KEY ([SensitivityConfigGUID]) REFERENCES [dbo].[SR2SensitivityConfig] ([SensitivityConfigGUID]); GO +ALTER TABLE [dbo].[SR2SensitivityConfigCorrelationGroupLink] ADD CONSTRAINT [DF_SR2SensitivityConfigCorrelationGroupLink_SensitivityConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SensitivityConfigGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityConfigCorrelationGroupLink] ADD CONSTRAINT [DF_SR2SensitivityConfigCorrelationGroupLink_CorrelationGroupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CorrelationGroupGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityConfigCorrelationGroupLink] ADD CONSTRAINT [DF_SR2SensitivityConfigCorrelationGroupLink_LinkGUID] DEFAULT (newid()) FOR [LinkGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SR2SensitivityConfigInput ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SR2SensitivityConfigInput] ( + [InputGUID] uniqueidentifier NOT NULL, + [SensitivityConfigGUID] uniqueidentifier NOT NULL, + [ModelGUID] uniqueidentifier NOT NULL, + [DataTableGUID] uniqueidentifier NOT NULL, + [RowID] int NOT NULL, + [MeasureGUID] uniqueidentifier NOT NULL, + [CachedName] nvarchar(450) NOT NULL, + [GroupName] nvarchar(450) NOT NULL, + [GroupID] int NOT NULL, + PRIMARY KEY ([InputGUID]) +); +GO +ALTER TABLE [dbo].[SR2SensitivityConfigInput] ADD CONSTRAINT [FK_SR2SensitivityConfigInput_SR2SensitivityConfig] FOREIGN KEY ([SensitivityConfigGUID]) REFERENCES [dbo].[SR2SensitivityConfig] ([SensitivityConfigGUID]); GO +ALTER TABLE [dbo].[SR2SensitivityConfigInput] ADD CONSTRAINT [DF_SR2SensitivityConfigInput_SensitivityConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SensitivityConfigGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityConfigInput] ADD CONSTRAINT [DF_SR2SensitivityConfigInput_InputGUID] DEFAULT (newid()) FOR [InputGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityConfigInput] ADD CONSTRAINT [DF_SR2SensitivityConfigInput_RowID] DEFAULT ((0)) FOR [RowID]; GO +ALTER TABLE [dbo].[SR2SensitivityConfigInput] ADD CONSTRAINT [DF_SR2SensitivityConfigInput_ModelGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityConfigInput] ADD CONSTRAINT [DF_SR2SensitivityConfigInput_CachedName] DEFAULT ('') FOR [CachedName]; GO +ALTER TABLE [dbo].[SR2SensitivityConfigInput] ADD CONSTRAINT [DF_SR2SensitivityConfigInput_MeasureGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityConfigInput] ADD CONSTRAINT [DF_SR2SensitivityConfigInput_DataTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTableGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityConfigInput] ADD CONSTRAINT [DF__SR2Sensit__Group__38D23799] DEFAULT ('') FOR [GroupName]; GO +ALTER TABLE [dbo].[SR2SensitivityConfigInput] ADD CONSTRAINT [DF_SR2SensitivityConfigInput_GroupID] DEFAULT ((0)) FOR [GroupID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SR2SensitivityConfigOutput ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SR2SensitivityConfigOutput] ( + [OutputGUID] uniqueidentifier NOT NULL, + [SensitivityConfigGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(450) NOT NULL, + [DisplayFormat] nvarchar(100) NOT NULL, + PRIMARY KEY ([OutputGUID]) +); +GO +ALTER TABLE [dbo].[SR2SensitivityConfigOutput] ADD CONSTRAINT [FK_SR2SensitivityConfigOutput_SR2SensitivityConfig] FOREIGN KEY ([SensitivityConfigGUID]) REFERENCES [dbo].[SR2SensitivityConfig] ([SensitivityConfigGUID]); GO +ALTER TABLE [dbo].[SR2SensitivityConfigOutput] ADD CONSTRAINT [DF_SR2SensitivityConfigOutput_DisplayFormat] DEFAULT ('') FOR [DisplayFormat]; GO +ALTER TABLE [dbo].[SR2SensitivityConfigOutput] ADD CONSTRAINT [DF_SR2SensitivityConfigOutput_OutputGUID] DEFAULT (newid()) FOR [OutputGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityConfigOutput] ADD CONSTRAINT [DF_SR2SensitivityConfigOutput_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SR2SensitivityConfigOutput] ADD CONSTRAINT [DF_SR2SensitivityConfigOutput_SensitivityConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SensitivityConfigGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SR2SensitivityConfigOutputMember ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SR2SensitivityConfigOutputMember] ( + [OutputMemberGUID] uniqueidentifier NOT NULL, + [OutputGUID] uniqueidentifier NOT NULL, + [ModelGUID] uniqueidentifier NOT NULL, + [DataTableGUID] uniqueidentifier NOT NULL, + [RowID] int NOT NULL, + [MeasureGUID] uniqueidentifier NOT NULL, + [CachedName] nvarchar(450) NOT NULL, + PRIMARY KEY ([OutputMemberGUID]) +); +GO +ALTER TABLE [dbo].[SR2SensitivityConfigOutputMember] ADD CONSTRAINT [FK_SR2SensitivityConfigOutputMember_SR2SensitivityConfigOutput] FOREIGN KEY ([OutputGUID]) REFERENCES [dbo].[SR2SensitivityConfigOutput] ([OutputGUID]); GO +ALTER TABLE [dbo].[SR2SensitivityConfigOutputMember] ADD CONSTRAINT [DF_SR2SensitivityConfigOutputMember_OutputGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OutputGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityConfigOutputMember] ADD CONSTRAINT [DF_SR2SensitivityConfigOutputMember_CachedName] DEFAULT ('') FOR [CachedName]; GO +ALTER TABLE [dbo].[SR2SensitivityConfigOutputMember] ADD CONSTRAINT [DF_SR2SensitivityConfigOutputMember_ModelGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityConfigOutputMember] ADD CONSTRAINT [DF_SR2SensitivityConfigOutputMember_DataTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTableGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityConfigOutputMember] ADD CONSTRAINT [DF_SR2SensitivityConfigOutputMember_MeasureGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityConfigOutputMember] ADD CONSTRAINT [DF_SR2SensitivityConfigOutputMember_OutputMemberGUID] DEFAULT (newid()) FOR [OutputMemberGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityConfigOutputMember] ADD CONSTRAINT [DF_SR2SensitivityConfigOutputMember_RowID] DEFAULT ((0)) FOR [RowID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SR2SensitivityResult ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SR2SensitivityResult] ( + [SensitivityResultGUID] uniqueidentifier NOT NULL, + [SensitivityConfigGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [DateCreated] datetime NOT NULL, + PRIMARY KEY ([SensitivityResultGUID]) +); +GO +ALTER TABLE [dbo].[SR2SensitivityResult] ADD CONSTRAINT [FK_SR2SensitivityResult_SR2SensitivityConfig] FOREIGN KEY ([SensitivityConfigGUID]) REFERENCES [dbo].[SR2SensitivityConfig] ([SensitivityConfigGUID]); GO +ALTER TABLE [dbo].[SR2SensitivityResult] ADD CONSTRAINT [DF_SR2SensitivityResult_SensitivityConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SensitivityConfigGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityResult] ADD CONSTRAINT [DF_SR2SensitivityResult_SensitivityResultGUID] DEFAULT (newid()) FOR [SensitivityResultGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityResult] ADD CONSTRAINT [DF_SR2SensitivityResult_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SR2SensitivityResult] ADD CONSTRAINT [DF_SR2SensitivityResult_DateCreated] DEFAULT (getdate()) FOR [DateCreated]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SR2SensitivityResultDetail ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SR2SensitivityResultDetail] ( + [RowID] int NOT NULL, + [SensitivityResultGUID] uniqueidentifier NOT NULL, + [OutputGUID] uniqueidentifier NOT NULL, + [ValueLow] decimal NOT NULL, + [ValueHigh] decimal NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [IsDeleted] bit NOT NULL, + [DetailGUID] uniqueidentifier NOT NULL, + [InputGUID] uniqueidentifier NOT NULL, + [ValueBaseline] decimal NOT NULL, + [OutputUniqueID] nvarchar(80) NOT NULL, + [CachedInputName] nvarchar(450) NOT NULL, + [CachedGroupName] nvarchar(450) NOT NULL, + [CachedOutputName] nvarchar(450) NOT NULL, + [CachedOutputDisplayFormat] nvarchar(450) NOT NULL, + PRIMARY KEY ([DetailGUID]) +); + +CREATE NONCLUSTERED INDEX [idx_SR2SensReport] ON [dbo].[SR2SensitivityResultDetail] ([SensitivityResultGUID], [OutputGUID], [InputGUID]) INCLUDE ([RowID], [ValueLow], [ValueHigh], [HistoryItemGUID], [IsDeleted], [DetailGUID], [ValueBaseline], [OutputUniqueID]); +GO +ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [FK_SR2SensitivityResultDetail_SR2SensitivityResult] FOREIGN KEY ([SensitivityResultGUID]) REFERENCES [dbo].[SR2SensitivityResult] ([SensitivityResultGUID]); GO +ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_CachedInputName] DEFAULT ('') FOR [CachedInputName]; GO +ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_CachedGroupName] DEFAULT ('') FOR [CachedGroupName]; GO +ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_CachedOutputName] DEFAULT ('') FOR [CachedOutputName]; GO +ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_ValueBaseline] DEFAULT ((0)) FOR [ValueBaseline]; GO +ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_SensitivityResultGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SensitivityResultGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_DetailGUID] DEFAULT (newid()) FOR [DetailGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_CachedOutputDisplayFormat] DEFAULT ('') FOR [CachedOutputDisplayFormat]; GO +ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_InputGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [InputGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_OutputGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OutputGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_ValueLow] DEFAULT ((0)) FOR [ValueLow]; GO +ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_ValueHigh] DEFAULT ((0)) FOR [ValueHigh]; GO +ALTER TABLE [dbo].[SR2SensitivityResultDetail] ADD CONSTRAINT [DF_SR2SensitivityResultDetail_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SRAssumption ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SRAssumption] ( + [AssumptionID] int NOT NULL, + [AssumptionSetID] int NOT NULL, + [Name] nvarchar(100) NOT NULL, + PRIMARY KEY ([AssumptionID]) +); +GO +ALTER TABLE [dbo].[SRAssumption] ADD CONSTRAINT [FK_SRAssumptionSetMember_SRAssumptionSet] FOREIGN KEY ([AssumptionSetID]) REFERENCES [dbo].[SRAssumptionSet] ([AssumptionSetID]); GO +ALTER TABLE [dbo].[SRAssumption] ADD CONSTRAINT [DF_AMAssumptionSetMember_AssumptionSetID] DEFAULT ((0)) FOR [AssumptionSetID]; GO +ALTER TABLE [dbo].[SRAssumption] ADD CONSTRAINT [DF_AMAssumptionSetMember_Name] DEFAULT ('') FOR [Name]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SRAssumptionLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SRAssumptionLink] ( + [AssumptionID] int NOT NULL, + [ParentAssumptionID] int NOT NULL, + [ScenarioID] int NOT NULL, + [ParentScenarioID] int NOT NULL, + PRIMARY KEY ([ParentAssumptionID], [AssumptionID]) +); +GO +ALTER TABLE [dbo].[SRAssumptionLink] ADD CONSTRAINT [FK_SRAssumptionSetMemberLink_SRAssumptionSetMember] FOREIGN KEY ([ParentAssumptionID]) REFERENCES [dbo].[SRAssumption] ([AssumptionID]); GO +ALTER TABLE [dbo].[SRAssumptionLink] ADD CONSTRAINT [FK_SRAssumptionSetMemberLink_SRAssumptionSetMember2] FOREIGN KEY ([AssumptionID]) REFERENCES [dbo].[SRAssumption] ([AssumptionID]); GO +ALTER TABLE [dbo].[SRAssumptionLink] ADD CONSTRAINT [FK_SRAssumptionSetMemberLink_SRScenario] FOREIGN KEY ([ScenarioID]) REFERENCES [dbo].[SRScenario] ([ScenarioID]); GO +ALTER TABLE [dbo].[SRAssumptionLink] ADD CONSTRAINT [FK_SRAssumptionSetMemberLink_SRScenario1] FOREIGN KEY ([ParentScenarioID]) REFERENCES [dbo].[SRScenario] ([ScenarioID]); GO +ALTER TABLE [dbo].[SRAssumptionLink] ADD CONSTRAINT [DF_SRCorrelation_AssumptionSetMemberID] DEFAULT ((0)) FOR [AssumptionID]; GO +ALTER TABLE [dbo].[SRAssumptionLink] ADD CONSTRAINT [DF_SRCorrelation_ParentAssumptionSetMemberID] DEFAULT ((0)) FOR [ParentAssumptionID]; GO +ALTER TABLE [dbo].[SRAssumptionLink] ADD CONSTRAINT [DF_SRAssumptionSetMemberLink_ScenarioID] DEFAULT ((0)) FOR [ScenarioID]; GO +ALTER TABLE [dbo].[SRAssumptionLink] ADD CONSTRAINT [DF_SRAssumptionSetMemberLink_ParentScenarioID] DEFAULT ((0)) FOR [ParentScenarioID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SRAssumptionSet ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SRAssumptionSet] ( + [AssumptionSetID] int NOT NULL, + [Name] nvarchar(100) NOT NULL, + [IsInputSet] bit NOT NULL, + [IsOutputSet] bit NOT NULL, + [IsGroupingTime] bit NOT NULL, + [IsGroupingPlans] bit NOT NULL, + PRIMARY KEY ([AssumptionSetID]) +); +GO +ALTER TABLE [dbo].[SRAssumptionSet] ADD CONSTRAINT [DF_AMAssumptionSet_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SRAssumptionSet] ADD CONSTRAINT [DF_AMAssumptionSet_IsInputSet] DEFAULT ((0)) FOR [IsInputSet]; GO +ALTER TABLE [dbo].[SRAssumptionSet] ADD CONSTRAINT [DF_AMAssumptionSet_IsOutputSet] DEFAULT ((0)) FOR [IsOutputSet]; GO +ALTER TABLE [dbo].[SRAssumptionSet] ADD CONSTRAINT [DF_SRAssumptionSet_IsGroupingTime] DEFAULT ((0)) FOR [IsGroupingTime]; GO +ALTER TABLE [dbo].[SRAssumptionSet] ADD CONSTRAINT [DF_SRAssumptionSet_IsGroupingPlans] DEFAULT ((0)) FOR [IsGroupingPlans]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SRAssumptionTuple ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SRAssumptionTuple] ( + [AssumptionID] int NOT NULL, + [DimensionMemberGUID] uniqueidentifier NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([AssumptionID], [DimensionMemberGUID]) +); +GO +ALTER TABLE [dbo].[SRAssumptionTuple] ADD CONSTRAINT [FK_SRAssumptionSetMemberTuple_SRAssumptionSetMember] FOREIGN KEY ([AssumptionID]) REFERENCES [dbo].[SRAssumption] ([AssumptionID]); GO +ALTER TABLE [dbo].[SRAssumptionTuple] ADD CONSTRAINT [DF_AMAssumptionSetMemberTuple_AssumptionSetMemberID] DEFAULT ((0)) FOR [AssumptionID]; GO +ALTER TABLE [dbo].[SRAssumptionTuple] ADD CONSTRAINT [DF_AMAssumptionSetMemberTuple_DimensionMemberGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionMemberGUID]; GO +ALTER TABLE [dbo].[SRAssumptionTuple] ADD CONSTRAINT [DF_AMAssumptionSetMemberTuple_DimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SRPackage ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SRPackage] ( + [PackageGUID] uniqueidentifier NOT NULL, + [ProjectID] int NOT NULL, + [Name] nvarchar(100) NOT NULL, + [FolderGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([PackageGUID]) +); +GO +ALTER TABLE [dbo].[SRPackage] ADD CONSTRAINT [FK_SRPackage_Folder] FOREIGN KEY ([FolderGUID]) REFERENCES [dbo].[Folder] ([FolderGuid]); GO +ALTER TABLE [dbo].[SRPackage] ADD CONSTRAINT [FK_SRPackage_SRProject] FOREIGN KEY ([ProjectID]) REFERENCES [dbo].[SRProject] ([ProjectID]); GO +ALTER TABLE [dbo].[SRPackage] ADD CONSTRAINT [DF_SRPackage_PackageGUID] DEFAULT (newid()) FOR [PackageGUID]; GO +ALTER TABLE [dbo].[SRPackage] ADD CONSTRAINT [DF_SRPackage_ProjectID] DEFAULT ((0)) FOR [ProjectID]; GO +ALTER TABLE [dbo].[SRPackage] ADD CONSTRAINT [DF_SRPackage_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SRPackage] ADD CONSTRAINT [DF_SRPackage_FolderGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SRPackageConfigLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SRPackageConfigLink] ( + [PackageConfigLinkGUID] uniqueidentifier NOT NULL, + [PackageGUID] uniqueidentifier NOT NULL, + [TableEditorConfigGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([PackageConfigLinkGUID]) +); +GO +ALTER TABLE [dbo].[SRPackageConfigLink] ADD CONSTRAINT [FK_SRPackageConfigLink_ScoreTableEditorConfig] FOREIGN KEY ([TableEditorConfigGUID]) REFERENCES [dbo].[ScoreTableEditorConfig] ([TableEditorConfigGUID]); GO +ALTER TABLE [dbo].[SRPackageConfigLink] ADD CONSTRAINT [FK_SRPackageConfigLink_SRPackageConfigLink] FOREIGN KEY ([PackageGUID]) REFERENCES [dbo].[SRPackage] ([PackageGUID]); GO +ALTER TABLE [dbo].[SRPackageConfigLink] ADD CONSTRAINT [DF_SRPackageConfigLink_PackageConfigLinkGUID] DEFAULT (newid()) FOR [PackageConfigLinkGUID]; GO +ALTER TABLE [dbo].[SRPackageConfigLink] ADD CONSTRAINT [DF_SRPackageConfigLink_PackageGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PackageGUID]; GO +ALTER TABLE [dbo].[SRPackageConfigLink] ADD CONSTRAINT [DF_SRPackageConfigLink_TableEditorConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TableEditorConfigGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SRProject ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SRProject] ( + [ProjectID] int NOT NULL, + [Name] nvarchar(100) NOT NULL, + [SensitivityConfigID] int NOT NULL, + [RiskConfigID] int NOT NULL, + PRIMARY KEY ([ProjectID]) +); +GO +ALTER TABLE [dbo].[SRProject] ADD CONSTRAINT [FK_SRProject_SRRiskConfig] FOREIGN KEY ([RiskConfigID]) REFERENCES [dbo].[SRRiskConfig] ([RiskConfigID]); GO +ALTER TABLE [dbo].[SRProject] ADD CONSTRAINT [FK_SRProject_SRSensitivityConfig] FOREIGN KEY ([SensitivityConfigID]) REFERENCES [dbo].[SRSensitivityConfig] ([SensitivityConfigID]); GO +ALTER TABLE [dbo].[SRProject] ADD CONSTRAINT [DF_SRProject_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SRProject] ADD CONSTRAINT [DF_SRProject_SensitivityConfigID] DEFAULT ((0)) FOR [SensitivityConfigID]; GO +ALTER TABLE [dbo].[SRProject] ADD CONSTRAINT [DF_SRProject_RiskConfigID] DEFAULT ((0)) FOR [RiskConfigID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SRProjectModelLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SRProjectModelLink] ( + [ProjectID] int NOT NULL, + [ModelGUID] uniqueidentifier NOT NULL, + [IsPrimary] bit NOT NULL, + PRIMARY KEY ([ProjectID], [ModelGUID]) +); +GO +ALTER TABLE [dbo].[SRProjectModelLink] ADD CONSTRAINT [FK_SRProjectModelLink_SRProject] FOREIGN KEY ([ProjectID]) REFERENCES [dbo].[SRProject] ([ProjectID]); GO +ALTER TABLE [dbo].[SRProjectModelLink] ADD CONSTRAINT [FK_SRProjectModelLink_XPlan] FOREIGN KEY ([ModelGUID]) REFERENCES [dbo].[XPlan] ([PlanGUID]); GO +ALTER TABLE [dbo].[SRProjectModelLink] ADD CONSTRAINT [DF_SRProjectModelLink_IsPrimaryModel] DEFAULT ((0)) FOR [IsPrimary]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SRRiskConfig ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SRRiskConfig] ( + [RiskConfigID] int NOT NULL, + [InputAssumptionSetID] int NOT NULL, + [OutputAssumptionSetID] int NOT NULL, + [Trials] int NOT NULL, + [Bins] int NOT NULL, + [LowScenarioID] int NOT NULL, + [HighScenarioID] int NOT NULL, + PRIMARY KEY ([RiskConfigID]) +); +GO +ALTER TABLE [dbo].[SRRiskConfig] ADD CONSTRAINT [FK_SRRiskConfig_SRAssumptionSet] FOREIGN KEY ([InputAssumptionSetID]) REFERENCES [dbo].[SRAssumptionSet] ([AssumptionSetID]); GO +ALTER TABLE [dbo].[SRRiskConfig] ADD CONSTRAINT [FK_SRRiskConfig_SRAssumptionSet1] FOREIGN KEY ([OutputAssumptionSetID]) REFERENCES [dbo].[SRAssumptionSet] ([AssumptionSetID]); GO +ALTER TABLE [dbo].[SRRiskConfig] ADD CONSTRAINT [FK_SRRiskConfig_SRScenario] FOREIGN KEY ([LowScenarioID]) REFERENCES [dbo].[SRScenario] ([ScenarioID]); GO +ALTER TABLE [dbo].[SRRiskConfig] ADD CONSTRAINT [FK_SRRiskConfig_SRScenario1] FOREIGN KEY ([HighScenarioID]) REFERENCES [dbo].[SRScenario] ([ScenarioID]); GO +ALTER TABLE [dbo].[SRRiskConfig] ADD CONSTRAINT [DF_SRRiskConfig_InputAssumptionSetID] DEFAULT ((0)) FOR [InputAssumptionSetID]; GO +ALTER TABLE [dbo].[SRRiskConfig] ADD CONSTRAINT [DF_SRRiskConfig_OutputAssumptionSetID] DEFAULT ((0)) FOR [OutputAssumptionSetID]; GO +ALTER TABLE [dbo].[SRRiskConfig] ADD CONSTRAINT [DF_SRRiskConfig_Trials] DEFAULT ((0)) FOR [Trials]; GO +ALTER TABLE [dbo].[SRRiskConfig] ADD CONSTRAINT [DF_SRRiskConfig_Bins] DEFAULT ((0)) FOR [Bins]; GO +ALTER TABLE [dbo].[SRRiskConfig] ADD CONSTRAINT [DF_SRRiskConfig_LowScenarioID] DEFAULT ((0)) FOR [LowScenarioID]; GO +ALTER TABLE [dbo].[SRRiskConfig] ADD CONSTRAINT [DF_SRRiskConfig_HighScenarioID] DEFAULT ((0)) FOR [HighScenarioID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SRScenario ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SRScenario] ( + [ScenarioID] int NOT NULL, + [Name] nvarchar(100) NOT NULL, + [IsCustom] bit NOT NULL, + PRIMARY KEY ([ScenarioID]) +); +GO +ALTER TABLE [dbo].[SRScenario] ADD CONSTRAINT [DF_ScoreScenario_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SRScenario] ADD CONSTRAINT [DF_ScoreScenario_IsSystem] DEFAULT ((0)) FOR [IsCustom]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SRSensitivityConfig ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SRSensitivityConfig] ( + [SensitivityConfigID] int NOT NULL, + [InputAssumptionSetID] int NOT NULL, + [OutputAssumptionSetID] int NOT NULL, + [LowScenarioID] int NOT NULL, + [HighScenarioID] int NOT NULL, + PRIMARY KEY ([SensitivityConfigID]) +); +GO +ALTER TABLE [dbo].[SRSensitivityConfig] ADD CONSTRAINT [FK_SRSensitivityConfig_SRAssumptionSet] FOREIGN KEY ([InputAssumptionSetID]) REFERENCES [dbo].[SRAssumptionSet] ([AssumptionSetID]); GO +ALTER TABLE [dbo].[SRSensitivityConfig] ADD CONSTRAINT [FK_SRSensitivityConfig_SRAssumptionSet1] FOREIGN KEY ([OutputAssumptionSetID]) REFERENCES [dbo].[SRAssumptionSet] ([AssumptionSetID]); GO +ALTER TABLE [dbo].[SRSensitivityConfig] ADD CONSTRAINT [FK_SRSensitivityConfig_SRScenario] FOREIGN KEY ([LowScenarioID]) REFERENCES [dbo].[SRScenario] ([ScenarioID]); GO +ALTER TABLE [dbo].[SRSensitivityConfig] ADD CONSTRAINT [FK_SRSensitivityConfig_SRScenario1] FOREIGN KEY ([HighScenarioID]) REFERENCES [dbo].[SRScenario] ([ScenarioID]); GO +ALTER TABLE [dbo].[SRSensitivityConfig] ADD CONSTRAINT [DF_SRSensitivityConfig_InputAssumptionSetID] DEFAULT ((0)) FOR [InputAssumptionSetID]; GO +ALTER TABLE [dbo].[SRSensitivityConfig] ADD CONSTRAINT [DF_SRSensitivityConfig_OutputAssumptionSetID] DEFAULT ((0)) FOR [OutputAssumptionSetID]; GO +ALTER TABLE [dbo].[SRSensitivityConfig] ADD CONSTRAINT [DF_SRSensitivityConfig_LowScenarioID] DEFAULT ((0)) FOR [LowScenarioID]; GO +ALTER TABLE [dbo].[SRSensitivityConfig] ADD CONSTRAINT [DF_SRSensitivityConfig_HighScenarioID] DEFAULT ((0)) FOR [HighScenarioID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreAttribute ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreAttribute] ( + [AttributeGUID] uniqueidentifier NOT NULL, + [DimensionGroupGUID] uniqueidentifier NOT NULL, + [FriendlyName] nvarchar(200) NULL, + [IsWrittenToDB] bit NOT NULL, + [IsKey] bit NOT NULL, + [IsSecuredLootID] bit NOT NULL, + [IsSecuredLootConfigID] bit NOT NULL, + [IsSecuredLootGroupID] bit NOT NULL, + [SecuredLootGroupPrefix] nvarchar(128) NOT NULL, + [SQLColumnName] nvarchar(64) NOT NULL, + [DefaultSortAttributeGUID] uniqueidentifier NOT NULL, + [ForeignKeyGUID] uniqueidentifier NOT NULL, + [IsRequired] bit NOT NULL, + [SpecialAttributeIndex] tinyint NOT NULL, + [IsCopiedWithPlan] bit NOT NULL, + [DisplayOrder] smallint NOT NULL, + [IsHidden] bit NOT NULL, + [DateModified] datetime NOT NULL, + [AttributeType] tinyint NOT NULL, + [MetaXML] varchar(max) NOT NULL, + [InferredSourceGUID] uniqueidentifier NOT NULL, + [InferredColumnName] nvarchar(128) NOT NULL, + [InferredAttributeGUID] uniqueidentifier NOT NULL, + [HelpText] nvarchar(800) NOT NULL, + [ColumnType] tinyint NOT NULL, + [ComputedValueDefinition] nvarchar(max) NOT NULL, + [IsComputed] bit NOT NULL, + [IsIdentity] bit NOT NULL, + [IdentityIncrement] int NOT NULL, + [IdentitySeed] int NOT NULL, + [IsNullable] bit NOT NULL, + [DefaultValueDefinition] nvarchar(max) NOT NULL, + [Precision] tinyint NOT NULL, + [Scale] tinyint NOT NULL, + [MaxLength] smallint NOT NULL, + [IsColumnExist] bit NOT NULL, + [IsForeignKeyed] bit NOT NULL, + [ForeignKeySchema] nvarchar(128) NOT NULL, + [ForeignKeyTable] nvarchar(128) NOT NULL, + [ForeignKeyColumn] nvarchar(128) NOT NULL, + [ForeignKeyOnDelete] nvarchar(100) NOT NULL, + [CachedInferredSQLColumnType] tinyint NOT NULL, + [IsFKAutoFilter] bit NOT NULL, + [JoinTypeVal] int NOT NULL, + [IsCustomNumberFormat] bit NOT NULL, + [CustomNumberFormat] varchar(128) NOT NULL, + [IsLocked] bit NOT NULL, + [ForeignKeyHierarchyGUID] uniqueidentifier NOT NULL, + [PHIDisclaimer] nvarchar(2000) NOT NULL, + [CopyrightDisclaimer] nvarchar(2000) NOT NULL, + [IsFormField] bit NOT NULL, + [FrameworkID] tinyint NOT NULL, + [IsModelDriver] bit NOT NULL, + [Description] nvarchar(1000) NOT NULL, + [DSSIsUsed] bit NOT NULL, + PRIMARY KEY ([AttributeGUID]) +); + +CREATE CLUSTERED INDEX [ix_ScoreAttribute] ON [dbo].[ScoreAttribute] ([DimensionGroupGUID]); +GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [FK_ScoreAttribute_ScoreDimensionGroup] FOREIGN KEY ([DimensionGroupGUID]) REFERENCES [dbo].[ScoreDimensionGroup] ([DimensionGroupGUID]); GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__IsCus__1A0E52E4] DEFAULT ((0)) FOR [IsCustomNumberFormat]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Custo__1B02771D] DEFAULT ('') FOR [CustomNumberFormat]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_DimensionGroupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGroupGUID]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__IsLoc__2185577A] DEFAULT ((0)) FOR [IsLocked]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Descr__235CED9A] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__PHIDi__23998596] DEFAULT ('') FOR [PHIDisclaimer]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Copyr__248DA9CF] DEFAULT ('') FOR [CopyrightDisclaimer]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_DateModified] DEFAULT (getdate()) FOR [DateModified]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_AttributeType] DEFAULT ((0)) FOR [AttributeType]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_MetaXML] DEFAULT ('') FOR [MetaXML]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__DSSIs__2867F491] DEFAULT ((1)) FOR [DSSIsUsed]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_InferredColumnName] DEFAULT ('') FOR [InferredColumnName]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_HelpText] DEFAULT ('') FOR [HelpText]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Colum__3DA96780] DEFAULT ((0)) FOR [ColumnType]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Compu__3E9D8BB9] DEFAULT ('') FOR [ComputedValueDefinition]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__IsCom__3F91AFF2] DEFAULT ((0)) FOR [IsComputed]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__IsIde__4085D42B] DEFAULT ((0)) FOR [IsIdentity]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Ident__4179F864] DEFAULT ((0)) FOR [IdentityIncrement]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Ident__426E1C9D] DEFAULT ((0)) FOR [IdentitySeed]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__IsNul__436240D6] DEFAULT ((0)) FOR [IsNullable]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Defau__4456650F] DEFAULT ('') FOR [DefaultValueDefinition]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Preci__454A8948] DEFAULT ((0)) FOR [Precision]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Scale__463EAD81] DEFAULT ((0)) FOR [Scale]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__MaxLe__4732D1BA] DEFAULT ((0)) FOR [MaxLength]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__IsCol__4826F5F3] DEFAULT ((0)) FOR [IsColumnExist]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__IsFor__491B1A2C] DEFAULT ((0)) FOR [IsForeignKeyed]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Forei__4A0F3E65] DEFAULT ('') FOR [ForeignKeySchema]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Forei__4B03629E] DEFAULT ('') FOR [ForeignKeyTable]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Forei__4BF786D7] DEFAULT ('') FOR [ForeignKeyColumn]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Forei__4CEBAB10] DEFAULT ('') FOR [ForeignKeyOnDelete]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Cache__4DDFCF49] DEFAULT ((0)) FOR [CachedInferredSQLColumnType]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_IsFKAutoFilter] DEFAULT ((1)) FOR [IsFKAutoFilter]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_InferredAttributeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [InferredSourceGUID]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Forei__5284BA9F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ForeignKeyHierarchyGUID]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_IsModelDriver] DEFAULT ((0)) FOR [IsModelDriver]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_AttributeGUID] DEFAULT (newid()) FOR [AttributeGUID]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__Frame__66D53282] DEFAULT ((0)) FOR [FrameworkID]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_JoinType] DEFAULT ((0)) FOR [JoinTypeVal]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_Name] DEFAULT ('') FOR [FriendlyName]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_IsWrittenToDB] DEFAULT ((0)) FOR [IsWrittenToDB]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_IsKey] DEFAULT ((0)) FOR [IsKey]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_IsSecuredLootID] DEFAULT ((0)) FOR [IsSecuredLootID]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_IsSecuredConfigID] DEFAULT ((0)) FOR [IsSecuredLootConfigID]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_IsSecuredLootGroupID] DEFAULT ((0)) FOR [IsSecuredLootGroupID]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_InferredAttributeGUID_1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [InferredAttributeGUID]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_SecuredLootGroupPrefix] DEFAULT ('') FOR [SecuredLootGroupPrefix]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_SQLColumnName_1] DEFAULT ('') FOR [SQLColumnName]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_DefaultSortAttributeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultSortAttributeGUID]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_ForeignKeyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ForeignKeyGUID]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_IsRequired] DEFAULT ((1)) FOR [IsRequired]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_SpecialAttributeIndex] DEFAULT ((0)) FOR [SpecialAttributeIndex]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_IsCopiedWithPlan] DEFAULT ((1)) FOR [IsCopiedWithPlan]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF__ScoreAttr__IsSys__74A98C83] DEFAULT ((0)) FOR [IsFormField]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_DisplayOrder] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[ScoreAttribute] ADD CONSTRAINT [DF_ScoreAttribute_IsHidden] DEFAULT ((0)) FOR [IsHidden]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreAttributeSetting ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreAttributeSetting] ( + [ScoreAttributeSettingGuid] uniqueidentifier NOT NULL, + [AttributeGUID] uniqueidentifier NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + [IsCustom] bit NOT NULL, + [IsMarkedForDeletion] bit NOT NULL, + [IsUsed] bit NOT NULL, + [CAPIsUsed] bit NOT NULL, + [DSSIsUsed] bit NOT NULL, + [MRIsUsed] bit NOT NULL, + [OBIsUsed] bit NOT NULL, + [PRIsUsed] bit NOT NULL, + [SPIsUsed] bit NOT NULL, + PRIMARY KEY ([ScoreAttributeSettingGuid]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [UQ_SCOREATTRIBUTESETTING_ATTRIBUTEGUID] ON [dbo].[ScoreAttributeSetting] ([AttributeGUID]); +GO +ALTER TABLE [dbo].[ScoreAttributeSetting] ADD CONSTRAINT [DF_CAPIsUsed] DEFAULT ((0)) FOR [CAPIsUsed]; GO +ALTER TABLE [dbo].[ScoreAttributeSetting] ADD CONSTRAINT [DF_DSSIsUsed] DEFAULT ((0)) FOR [DSSIsUsed]; GO +ALTER TABLE [dbo].[ScoreAttributeSetting] ADD CONSTRAINT [DF_MRIsUsed] DEFAULT ((0)) FOR [MRIsUsed]; GO +ALTER TABLE [dbo].[ScoreAttributeSetting] ADD CONSTRAINT [DF_OBIsUsed] DEFAULT ((0)) FOR [OBIsUsed]; GO +ALTER TABLE [dbo].[ScoreAttributeSetting] ADD CONSTRAINT [DF_PRIsUsed] DEFAULT ((0)) FOR [PRIsUsed]; GO +ALTER TABLE [dbo].[ScoreAttributeSetting] ADD CONSTRAINT [DF_SPIsUsed] DEFAULT ((0)) FOR [SPIsUsed]; GO +ALTER TABLE [dbo].[ScoreAttributeSetting] ADD CONSTRAINT [DF__ScoreAttr__IsMar__3DA3D3F0] DEFAULT ((0)) FOR [IsMarkedForDeletion]; GO +ALTER TABLE [dbo].[ScoreAttributeSetting] ADD CONSTRAINT [DF_IsUsed] DEFAULT ((0)) FOR [IsUsed]; GO +ALTER TABLE [dbo].[ScoreAttributeSetting] ADD CONSTRAINT [DF__ScoreAttr__Score__5E8C9913] DEFAULT (newid()) FOR [ScoreAttributeSettingGuid]; GO +ALTER TABLE [dbo].[ScoreAttributeSetting] ADD CONSTRAINT [DF__ScoreAttr__IsCus__616905BE] DEFAULT ((0)) FOR [IsCustom]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreAttributeType ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreAttributeType] ( + [ScoreAttributeTypeID] tinyint NOT NULL, + [Name] nvarchar(50) NOT NULL, + PRIMARY KEY ([ScoreAttributeTypeID]) +); +GO +ALTER TABLE [dbo].[ScoreAttributeType] ADD CONSTRAINT [DF_Table_1_name] DEFAULT ('') FOR [Name]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreComposite ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreComposite] ( + [CompositeGUID] uniqueidentifier NOT NULL, + [DataTableGUID1] uniqueidentifier NOT NULL, + [DataTableGUID2] uniqueidentifier NOT NULL, + [IsWrittenToDB] bit NOT NULL, + [FriendlyName] nvarchar(64) NOT NULL, + [Description] varchar(2000) NOT NULL, + [FrameworkID] tinyint NOT NULL, + [ModifiedAt] datetime NOT NULL, + [TableEditorConfigGUID] uniqueidentifier NOT NULL, + [isSubtable] bit NOT NULL, + [BoundsDataTableGUID] uniqueidentifier NOT NULL, + [ModelQueryHint] nvarchar(450) NOT NULL, + [IsUsingHashJoin] bit NOT NULL, + PRIMARY KEY ([CompositeGUID]) +); +GO +ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [FK_ScoreComposite_ScoreDataTable] FOREIGN KEY ([DataTableGUID1]) REFERENCES [dbo].[ScoreDataTable] ([DataTableGUID]); GO +ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [FK_ScoreComposite_ScoreDataTable1] FOREIGN KEY ([DataTableGUID2]) REFERENCES [dbo].[ScoreDataTable] ([DataTableGUID]); GO +ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF_ScoreComposite_ModelQueryHint] DEFAULT ('OPTION(RECOMPILE)') FOR [ModelQueryHint]; GO +ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF__ScoreComp__isSub__1BD46F8A] DEFAULT ((0)) FOR [isSubtable]; GO +ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF_ScoreComposite_Description] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF_ScoreComposite_FrameworkID] DEFAULT ((0)) FOR [FrameworkID]; GO +ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF_ScoreComposite_BoundsDataTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BoundsDataTableGUID]; GO +ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF__ScoreComp__Modif__7E73876C] DEFAULT (getdate()) FOR [ModifiedAt]; GO +ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF_ScoreComposite_TableEditorConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TableEditorConfigGUID]; GO +ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF__ScoreComp__IsUsi__78DC0A5C] DEFAULT ((0)) FOR [IsUsingHashJoin]; GO +ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF_ScoreComposite_CompositeGUID] DEFAULT (newid()) FOR [CompositeGUID]; GO +ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF_ScoreComposite_IsWrittenToDB] DEFAULT ((1)) FOR [IsWrittenToDB]; GO +ALTER TABLE [dbo].[ScoreComposite] ADD CONSTRAINT [DF_ScoreComposite_FriendlyNam] DEFAULT ('') FOR [FriendlyName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreCompositeLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreCompositeLink] ( + [CompositeLinkGUID] uniqueidentifier NOT NULL, + [CompositeGUID] uniqueidentifier NOT NULL, + [Type] smallint NOT NULL, + [Key1GUID] uniqueidentifier NOT NULL, + [Key2GUID] uniqueidentifier NOT NULL, + [Key1AttributeGUID] uniqueidentifier NOT NULL, + [Key2AttributeGUID] uniqueidentifier NOT NULL, + [SQLCustomLinkExpression] nvarchar(4000) NOT NULL, + [PlaceholderIndexMeasureGUID] uniqueidentifier NOT NULL, + [IsPlaceholder] bit NOT NULL, + [IsFixedIndex] bit NOT NULL, + [CompositeLinkID] int NOT NULL, + [ModifiedAt] datetime NOT NULL, + PRIMARY KEY ([CompositeLinkGUID]) +); +GO +ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [FK_ScoreCompositeLink_ScoreAttribute] FOREIGN KEY ([Key1GUID]) REFERENCES [dbo].[ScoreAttribute] ([AttributeGUID]); GO +ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [FK_ScoreCompositeLink_ScoreAttribute1] FOREIGN KEY ([Key2GUID]) REFERENCES [dbo].[ScoreAttribute] ([AttributeGUID]); GO +ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [FK_ScoreCompositeLink_ScoreComposite] FOREIGN KEY ([CompositeGUID]) REFERENCES [dbo].[ScoreComposite] ([CompositeGUID]); GO +ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_ScoreCompositeLink_PlaceholderIndexMeasureGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlaceholderIndexMeasureGUID]; GO +ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_ScoreCompositeLink_IsPlaceholder] DEFAULT ((0)) FOR [IsPlaceholder]; GO +ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_ScoreCompositeLink_IsFixedIndex] DEFAULT ((0)) FOR [IsFixedIndex]; GO +ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF__ScoreComp__Modif__005BCFDE] DEFAULT (getdate()) FOR [ModifiedAt]; GO +ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_Table_1_DimensionKeyMappingGUID] DEFAULT (newid()) FOR [CompositeLinkGUID]; GO +ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_ScoreCompositeLink_CompositeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CompositeGUID]; GO +ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_ScoreCompositeLink_Type] DEFAULT ((0)) FOR [Type]; GO +ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_ScoreCompositeLink_Key1GUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [Key1GUID]; GO +ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_ScoreCompositeLink_Key2GUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [Key2GUID]; GO +ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_ScoreCompositeLink_Key1AttributeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [Key1AttributeGUID]; GO +ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_ScoreCompositeLink_Key2AttributeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [Key2AttributeGUID]; GO +ALTER TABLE [dbo].[ScoreCompositeLink] ADD CONSTRAINT [DF_ScoreCompositeLink_SQLCustomLinkExpression] DEFAULT ('') FOR [SQLCustomLinkExpression]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreDataHistoryLine ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreDataHistoryLine] ( + [DataHistoryLineID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [DateTimeStamp] datetime NOT NULL, + [TableName] nvarchar(64) NOT NULL, + [RowID] int NOT NULL, + [BeforeValues] nvarchar(max) NOT NULL, + [AfterValues] nvarchar(max) NOT NULL, + PRIMARY KEY ([DataHistoryLineID]) +); +GO +ALTER TABLE [dbo].[ScoreDataHistoryLine] ADD CONSTRAINT [DF_ScoreDataHistoryLine_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreDataTable ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreDataTable] ( + [DataTableGUID] uniqueidentifier NOT NULL, + [FriendlyName] nvarchar(64) NOT NULL, + [Description] varchar(2000) NOT NULL, + [SQLSchemaName] nvarchar(128) NOT NULL, + [SQLObjectName] nvarchar(128) NOT NULL, + [SQLTableAlias] nvarchar(50) NOT NULL, + [IsWrittenToDB] bit NOT NULL, + [DisplayFormatAttributeGUID] uniqueidentifier NOT NULL, + [DataTableID] int NOT NULL, + [SQLTableAliasUnique] nvarchar(72) NULL, + [IsCompositeMappingTable] bit NOT NULL, + [FrameworkID] tinyint NOT NULL, + [ModifiedAt] datetime NOT NULL, + [IsWrittenIfZero] bit NOT NULL, + [GlobalID] nvarchar(128) NULL, + [IsCompositeBoundsTable] bit NOT NULL, + [DisplayFormatAttributeDimensionGUID] uniqueidentifier NOT NULL, + [IsClientFriendly] bit NOT NULL, + [OverrideLoadBySQLSchemaName] nvarchar(200) NOT NULL, + [OverrideLoadBySQLObjectName] nvarchar(200) NOT NULL, + [IsGeneratingSelectIntoTempTable] bit NOT NULL, + [ModelQueryHint] nvarchar(900) NOT NULL, + [DIDeleteQueryHint] nvarchar(900) NOT NULL, + PRIMARY KEY ([DataTableGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_ScoreDataTable_SQLTableAlias] ON [dbo].[ScoreDataTable] ([SQLTableAliasUnique]); +GO +ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF__ScoreData__DIDel__0AC084A0] DEFAULT ('') FOR [DIDeleteQueryHint]; GO +ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_ScoreDataTableGUID] DEFAULT (newid()) FOR [DataTableGUID]; GO +ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_FriendlyName] DEFAULT ('') FOR [FriendlyName]; GO +ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_Description] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_SQLSchemaName] DEFAULT ('') FOR [SQLSchemaName]; GO +ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_SQLObjectName] DEFAULT ('') FOR [SQLObjectName]; GO +ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_SQLTableAlias] DEFAULT ('') FOR [SQLTableAlias]; GO +ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_IsWrittenToDB] DEFAULT ((1)) FOR [IsWrittenToDB]; GO +ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_DisplayFormatAttributeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DisplayFormatAttributeGUID]; GO +ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_IsCompositeMappingTable] DEFAULT ((0)) FOR [IsCompositeMappingTable]; GO +ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_FrameworkID] DEFAULT ((0)) FOR [FrameworkID]; GO +ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF__ScoreData__Overr__235C540D] DEFAULT ('') FOR [OverrideLoadBySQLSchemaName]; GO +ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_IsWrittenIfZero] DEFAULT ((0)) FOR [IsWrittenIfZero]; GO +ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF__ScoreData__Overr__24507846] DEFAULT ('') FOR [OverrideLoadBySQLObjectName]; GO +ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF__ScoreData__IsCli__302CA709] DEFAULT ((0)) FOR [IsClientFriendly]; GO +ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_DisplayFormatAttributeDimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DisplayFormatAttributeDimensionGUID]; GO +ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF__ScoreData__IsGen__426291E9] DEFAULT ((0)) FOR [IsGeneratingSelectIntoTempTable]; GO +ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_GlobalID] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF_ScoreDataTable_IsCompositeBoundsTable] DEFAULT ((0)) FOR [IsCompositeBoundsTable]; GO +ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF__ScoreData__Modif__02441850] DEFAULT (getdate()) FOR [ModifiedAt]; GO +ALTER TABLE [dbo].[ScoreDataTable] ADD CONSTRAINT [DF__ScoreData__Model__7F575CE7] DEFAULT ('OPTION(RECOMPILE)') FOR [ModelQueryHint]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreDataTableKeyLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreDataTableKeyLink] ( + [DataTableKeyLinkGUID] uniqueidentifier NOT NULL, + [DataTableGUID] uniqueidentifier NOT NULL, + [KeyGUID] uniqueidentifier NOT NULL, + [ObjectID] int NOT NULL, + [ColumnID] int NOT NULL, + [SchemaName] nvarchar(128) NOT NULL, + [ObjectName] nvarchar(128) NOT NULL, + [ColumnName] nvarchar(128) NOT NULL, + [ObjectType] int NOT NULL, + [MaxLength] smallint NOT NULL, + [IsComputed] bit NOT NULL, + [IsNullable] bit NOT NULL, + [Scale] tinyint NOT NULL, + [Precision] tinyint NOT NULL, + [IsIdentity] bit NOT NULL, + [ColumnTypeValue] tinyint NOT NULL, + [IdentityIncrement] int NOT NULL, + [IdentitySeed] int NOT NULL, + [DefaultValueDefinition] nvarchar(max) NOT NULL, + [IsPartOfUniqueIndex] bit NOT NULL, + [IsUniqueIndex] bit NOT NULL, + [IsPartOfPrimaryKey] bit NOT NULL, + [IsPrimaryKey] bit NOT NULL, + [ComputedValueDefinition] nvarchar(max) NOT NULL, + [IsForeignKeyed] bit NOT NULL, + [ForeignKeySchema] nvarchar(128) NOT NULL, + [ForeignKeyTable] nvarchar(128) NOT NULL, + [ForeignKeyColumn] nvarchar(128) NOT NULL, + [ForeignKeyOnDelete] nvarchar(128) NOT NULL, + [ModifiedAt] datetime NOT NULL, + [IsRequired] bit NOT NULL, + [Description] nvarchar(1000) NOT NULL, + PRIMARY KEY ([DataTableKeyLinkGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_ScoreDataTableKeyLink_UniqueKey] ON [dbo].[ScoreDataTableKeyLink] ([DataTableGUID], [KeyGUID]); +GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [FK_ScoreDataTableKeyLink_ScoreAttribute] FOREIGN KEY ([KeyGUID]) REFERENCES [dbo].[ScoreAttribute] ([AttributeGUID]); GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [FK_ScoreDataTableKeyLink_ScoreDataTable] FOREIGN KEY ([DataTableGUID]) REFERENCES [dbo].[ScoreDataTable] ([DataTableGUID]); GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__IsIde__36ECEAB9] DEFAULT ((0)) FOR [IsIdentity]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Colum__37E10EF2] DEFAULT ((0)) FOR [ColumnTypeValue]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Ident__38D5332B] DEFAULT ((0)) FOR [IdentityIncrement]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Ident__39C95764] DEFAULT ((0)) FOR [IdentitySeed]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Defau__3ABD7B9D] DEFAULT ('') FOR [DefaultValueDefinition]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__IsPar__3BB19FD6] DEFAULT ((0)) FOR [IsPartOfUniqueIndex]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__IsUni__3CA5C40F] DEFAULT ((0)) FOR [IsUniqueIndex]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF_ScoreDataTableKeyLink_DataTableKeyLinkGUID] DEFAULT (newid()) FOR [DataTableKeyLinkGUID]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__IsPar__3D99E848] DEFAULT ((0)) FOR [IsPartOfPrimaryKey]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF_ScoreDataTableKeyLink_DataTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTableGUID]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__IsPri__3E8E0C81] DEFAULT ((0)) FOR [IsPrimaryKey]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF_ScoreDataTableKeyLink_KeyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [KeyGUID]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Compu__3F8230BA] DEFAULT ('') FOR [ComputedValueDefinition]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__IsFor__407654F3] DEFAULT ((0)) FOR [IsForeignKeyed]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Forei__416A792C] DEFAULT ('') FOR [ForeignKeySchema]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Forei__425E9D65] DEFAULT ('') FOR [ForeignKeyTable]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Forei__4352C19E] DEFAULT ('') FOR [ForeignKeyColumn]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Forei__4446E5D7] DEFAULT ('') FOR [ForeignKeyOnDelete]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Modif__0614A934] DEFAULT (getdate()) FOR [ModifiedAt]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Descr__1854B5B5] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__IsReq__749BD5C3] DEFAULT ((0)) FOR [IsRequired]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Objec__2C6F5C46] DEFAULT ((0)) FOR [ObjectID]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Colum__2D63807F] DEFAULT ((0)) FOR [ColumnID]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Schem__2E57A4B8] DEFAULT ('') FOR [SchemaName]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Objec__2F4BC8F1] DEFAULT ('') FOR [ObjectName]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Colum__303FED2A] DEFAULT ('') FOR [ColumnName]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Objec__31341163] DEFAULT ((0)) FOR [ObjectType]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__MaxLe__3228359C] DEFAULT ((0)) FOR [MaxLength]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__IsCom__331C59D5] DEFAULT ((0)) FOR [IsComputed]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__IsNul__34107E0E] DEFAULT ((0)) FOR [IsNullable]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Scale__3504A247] DEFAULT ((0)) FOR [Scale]; GO +ALTER TABLE [dbo].[ScoreDataTableKeyLink] ADD CONSTRAINT [DF__ScoreData__Preci__35F8C680] DEFAULT ((0)) FOR [Precision]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreDataTableLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreDataTableLink] ( + [DataTableLinkGUID] uniqueidentifier NOT NULL, + [DataTable1GUID] uniqueidentifier NOT NULL, + [DataTable1KeyGUID] uniqueidentifier NOT NULL, + [DataTable2GUID] uniqueidentifier NOT NULL, + [DataTable2KeyGUID] uniqueidentifier NOT NULL, + [IsReportingOnly] bit NOT NULL, + [IsReceivingParentTableColumns] bit NOT NULL, + [IsChildDataCached] bit NOT NULL, + PRIMARY KEY ([DataTableLinkGUID]) +); +GO +ALTER TABLE [dbo].[ScoreDataTableLink] ADD CONSTRAINT [DF_ScoreDataTableLink_DataTable1GUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTable1GUID]; GO +ALTER TABLE [dbo].[ScoreDataTableLink] ADD CONSTRAINT [DF_ScoreDataTableLink_DataTable1KeyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTable1KeyGUID]; GO +ALTER TABLE [dbo].[ScoreDataTableLink] ADD CONSTRAINT [DF_ScoreDataTableLink_DataTable2GUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTable2GUID]; GO +ALTER TABLE [dbo].[ScoreDataTableLink] ADD CONSTRAINT [df_IsChildDataCached] DEFAULT ((0)) FOR [IsChildDataCached]; GO +ALTER TABLE [dbo].[ScoreDataTableLink] ADD CONSTRAINT [DF_ScoreDataTableLink_DataTableLinkGUID] DEFAULT (newid()) FOR [DataTableLinkGUID]; GO +ALTER TABLE [dbo].[ScoreDataTableLink] ADD CONSTRAINT [DF_ScoreDataTableLink_DataTable2KeyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTable2KeyGUID]; GO +ALTER TABLE [dbo].[ScoreDataTableLink] ADD CONSTRAINT [DF__ScoreData__IsRep__6B365FCD] DEFAULT ((0)) FOR [IsReportingOnly]; GO +ALTER TABLE [dbo].[ScoreDataTableLink] ADD CONSTRAINT [DF__ScoreData__IsRec__6E738A82] DEFAULT ((0)) FOR [IsReceivingParentTableColumns]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreDataTableMeasureGroup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreDataTableMeasureGroup] ( + [ScoreDataTableMeasureGroupGUID] uniqueidentifier NOT NULL, + [MeasureGroupName] nvarchar(200) NOT NULL, + [CubeViewName] nvarchar(200) NOT NULL, + [ScoreDataTableGUID] uniqueidentifier NOT NULL, + [IsPrimary] bit NOT NULL, + [DatasourceViewName] nvarchar(200) NOT NULL, + PRIMARY KEY ([ScoreDataTableMeasureGroupGUID]) +); +GO +ALTER TABLE [dbo].[ScoreDataTableMeasureGroup] ADD CONSTRAINT [DF__ScoreData__IsPri__0B96ABB9] DEFAULT ((0)) FOR [IsPrimary]; GO +ALTER TABLE [dbo].[ScoreDataTableMeasureGroup] ADD CONSTRAINT [DF__ScoreData__Datas__152015F3] DEFAULT ('') FOR [DatasourceViewName]; GO +ALTER TABLE [dbo].[ScoreDataTableMeasureGroup] ADD CONSTRAINT [DF__ScoreData__Score__161E5BCD] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScoreDataTableGUID]; GO +ALTER TABLE [dbo].[ScoreDataTableMeasureGroup] ADD CONSTRAINT [DF__ScoreData__Score__5E778A7A] DEFAULT (newid()) FOR [ScoreDataTableMeasureGroupGUID]; GO +ALTER TABLE [dbo].[ScoreDataTableMeasureGroup] ADD CONSTRAINT [DF__ScoreData__Measu__6153F725] DEFAULT ('') FOR [MeasureGroupName]; GO +ALTER TABLE [dbo].[ScoreDataTableMeasureGroup] ADD CONSTRAINT [DF__ScoreData__CubeV__62481B5E] DEFAULT ('') FOR [CubeViewName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreDatatableSetting ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreDatatableSetting] ( + [DataTableGUID] uniqueidentifier NOT NULL, + [IsUsed] bit NOT NULL, + [IsRequired] bit NOT NULL, + PRIMARY KEY ([DataTableGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [UQ_SCOREDATATABLESETTING_DATATABLEGUID] ON [dbo].[ScoreDatatableSetting] ([DataTableGUID]); +GO +ALTER TABLE [dbo].[ScoreDatatableSetting] ADD CONSTRAINT [DF__ScoreData__DataT__4D620D11] DEFAULT (newid()) FOR [DataTableGUID]; GO +ALTER TABLE [dbo].[ScoreDatatableSetting] ADD CONSTRAINT [DF__ScoreData__IsUse__4E56314A] DEFAULT ((0)) FOR [IsUsed]; GO +ALTER TABLE [dbo].[ScoreDatatableSetting] ADD CONSTRAINT [DF__ScoreData__IsReq__5EAC94A4] DEFAULT ((0)) FOR [IsRequired]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreDimension ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreDimension] ( + [DimensionGUID] uniqueidentifier NOT NULL, + [FriendlyName] nvarchar(128) NOT NULL, + [Description] varchar(2000) NOT NULL, + [SQLTableAlias] nvarchar(50) NOT NULL, + [DefaultKeyGUID] uniqueidentifier NOT NULL, + [DefaultHierarchyGUID] uniqueidentifier NOT NULL, + [DefaultLookupKeyGUID] uniqueidentifier NOT NULL, + [IsSecured] bit NOT NULL, + [PermissionSetID] smallint NOT NULL, + [SQLSchemaName] nvarchar(128) NOT NULL, + [SQLObjectName] nvarchar(max) NOT NULL, + [DefaultMemberGUID] uniqueidentifier NOT NULL, + [IsSysAdminOnly] bit NOT NULL, + [IsAllowMemberDelete] bit NOT NULL, + [IsAllowMemberAdd] bit NOT NULL, + [PrimaryGroupGUID] uniqueidentifier NOT NULL, + [SQLTableAliasUnique] nvarchar(72) NULL, + [DimensionID] int NOT NULL, + [IsStock] bit NOT NULL, + [DateModified] datetime NOT NULL, + [PickerType] int NOT NULL, + [IsSharingSecurity] bit NOT NULL, + [DimensionVersion] int NOT NULL, + [IsGeneratingWrapperView] bit NOT NULL, + [GlobalID] nvarchar(50) NOT NULL, + [DimensionEditorMode] int NOT NULL, + [IsSensitivityRiskHidden] bit NOT NULL, + [PHIDisclaimer] nvarchar(2000) NOT NULL, + [CopyrightDisclaimer] nvarchar(2000) NOT NULL, + [IsSecurityReadOnly] bit NOT NULL, + [IsSecuredSetupOnly] bit NOT NULL, + [IsClientFriendly] bit NOT NULL, + [IsSecurityTriggersEnabled] bit NOT NULL, + [HelpTextAttributeGUID] uniqueidentifier NOT NULL, + [IsEditable] bit NOT NULL, + [IsCustomAttributeAllowed] bit NOT NULL, + [IsCustom] bit NOT NULL, + [ParentDimensionGUID] uniqueidentifier NOT NULL, + [StandardCodesLastUpdated] smalldatetime NOT NULL, + [StandardCodesVersion] smalldatetime NOT NULL, + [IsStandard] bit NOT NULL, + [IsDisablingHistoryTriggers] bit NOT NULL, + PRIMARY KEY ([DimensionGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [NCU_FriendlyName] ON [dbo].[ScoreDimension] ([FriendlyName]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_ScoreDimension_SQLTableAlias] ON [dbo].[ScoreDimension] ([SQLTableAliasUnique]); +GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_Description] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_SQLTableAlias] DEFAULT ('') FOR [SQLTableAlias]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_IsSecuredSetupOnly] DEFAULT ((0)) FOR [IsSecuredSetupOnly]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_DefaultKeyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultKeyGUID]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_DefaultHeirarchyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultHierarchyGUID]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_DefaultLookupKeyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultLookupKeyGUID]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_IsSecured] DEFAULT ((0)) FOR [IsSecured]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_PermissionSetID] DEFAULT ((0)) FOR [PermissionSetID]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_SQLSchema] DEFAULT ('') FOR [SQLSchemaName]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_SQLObjectName] DEFAULT ('') FOR [SQLObjectName]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_DefaultMemberGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultMemberGUID]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_IsSysAdminOnly] DEFAULT ((0)) FOR [IsSysAdminOnly]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_IsAllowMemberDelete] DEFAULT ((1)) FOR [IsAllowMemberDelete]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_IsAllowMemberAdd] DEFAULT ((1)) FOR [IsAllowMemberAdd]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__Stand__0D222ED4] DEFAULT ('1900-01-01 00:00:00') FOR [StandardCodesLastUpdated]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_IsStock] DEFAULT ((0)) FOR [IsStock]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__Stand__0E16530D] DEFAULT ('1900-01-01 00:00:00') FOR [StandardCodesVersion]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_DateModified] DEFAULT (getdate()) FOR [DateModified]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__IsSta__0F0A7746] DEFAULT ((0)) FOR [IsStandard]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_PickerType] DEFAULT ((0)) FOR [PickerType]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_DimensionVersion] DEFAULT ((2)) FOR [DimensionVersion]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_IsGeneratingWrapperView] DEFAULT ((0)) FOR [IsGeneratingWrapperView]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__PHIDi__21B13D24] DEFAULT ('') FOR [PHIDisclaimer]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__Copyr__22A5615D] DEFAULT ('') FOR [CopyrightDisclaimer]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__IsDis__26F8A61E] DEFAULT ((0)) FOR [IsDisablingHistoryTriggers]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__IsCli__2F3882D0] DEFAULT ((0)) FOR [IsClientFriendly]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_IsSecurityTriggersEnabled] DEFAULT ((1)) FOR [IsSecurityTriggersEnabled]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__IsCus__3AC439E9] DEFAULT ((0)) FOR [IsCustom]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__IsCus__40E72793] DEFAULT ((1)) FOR [IsCustomAttributeAllowed]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__HelpT__4B0195F7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HelpTextAttributeGUID]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_DimensionEditorMode] DEFAULT ((0)) FOR [DimensionEditorMode]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_GlobalID] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_IsSharingSecurity] DEFAULT ((0)) FOR [IsSharingSecurity]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__Paren__60F66677] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentDimensionGUID]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__IsSen__65A4DE10] DEFAULT ((0)) FOR [IsSensitivityRiskHidden]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF__ScoreDime__IsEdi__664DB66C] DEFAULT ((1)) FOR [IsEditable]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_PrimaryGroupGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PrimaryGroupGUID]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_IsSecurityReadOnly] DEFAULT ((0)) FOR [IsSecurityReadOnly]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_DimensionGUID] DEFAULT (newid()) FOR [DimensionGUID]; GO +ALTER TABLE [dbo].[ScoreDimension] ADD CONSTRAINT [DF_ScoreDimension_FriendlyName] DEFAULT ('') FOR [FriendlyName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreDimensionFramework ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreDimensionFramework] ( + [DimensionGUID] uniqueidentifier NOT NULL, + [FrameworkID] tinyint NOT NULL, + PRIMARY KEY ([DimensionGUID], [FrameworkID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreDimensionGroup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreDimensionGroup] ( + [DimensionGroupGUID] uniqueidentifier NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(128) NOT NULL, + [Description] varchar(2000) NOT NULL, + [SchemaName] nvarchar(128) NOT NULL, + [ObjectName] nvarchar(128) NOT NULL, + [IsStock] bit NOT NULL, + [DateModified] datetime NOT NULL, + PRIMARY KEY ([DimensionGroupGUID]) +); +GO +ALTER TABLE [dbo].[ScoreDimensionGroup] ADD CONSTRAINT [FK_ScoreDimensionGroup_ScoreDimension] FOREIGN KEY ([DimensionGUID]) REFERENCES [dbo].[ScoreDimension] ([DimensionGUID]); GO +ALTER TABLE [dbo].[ScoreDimensionGroup] ADD CONSTRAINT [DF__ScoreDime__Dimen__758215A1] DEFAULT (newid()) FOR [DimensionGroupGUID]; GO +ALTER TABLE [dbo].[ScoreDimensionGroup] ADD CONSTRAINT [DF__ScoreDimen__Name__776A5E13] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[ScoreDimensionGroup] ADD CONSTRAINT [DF__ScoreDime__Descr__785E824C] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[ScoreDimensionGroup] ADD CONSTRAINT [DF__ScoreDime__Schem__7952A685] DEFAULT ('') FOR [SchemaName]; GO +ALTER TABLE [dbo].[ScoreDimensionGroup] ADD CONSTRAINT [DF__ScoreDime__Objec__7A46CABE] DEFAULT ('') FOR [ObjectName]; GO +ALTER TABLE [dbo].[ScoreDimensionGroup] ADD CONSTRAINT [DF__ScoreDime__IsSto__7B3AEEF7] DEFAULT ((0)) FOR [IsStock]; GO +ALTER TABLE [dbo].[ScoreDimensionGroup] ADD CONSTRAINT [DF_ScoreDimensionGroup_DateModified] DEFAULT (getdate()) FOR [DateModified]; GO +ALTER TABLE [dbo].[ScoreDimensionGroup] ADD CONSTRAINT [DF__ScoreDime__Dimen__767639DA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreDimensionGroupViewHistory ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreDimensionGroupViewHistory] ( + [ScoreDimensionGroupViewHistoryID] int NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + [DimensionGroupGUID] uniqueidentifier NOT NULL, + [ViewBefore] nvarchar(max) NOT NULL, + [ViewAfter] nvarchar(max) NOT NULL, + [DateModified] datetime NOT NULL, + PRIMARY KEY ([ScoreDimensionGroupViewHistoryID]) +); +GO +ALTER TABLE [dbo].[ScoreDimensionGroupViewHistory] ADD CONSTRAINT [DF__ScoreDime__Dimen__5ECBC4DE] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO +ALTER TABLE [dbo].[ScoreDimensionGroupViewHistory] ADD CONSTRAINT [DF__ScoreDime__Dimen__5FBFE917] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGroupGUID]; GO +ALTER TABLE [dbo].[ScoreDimensionGroupViewHistory] ADD CONSTRAINT [DF__ScoreDime__ViewB__60B40D50] DEFAULT ('') FOR [ViewBefore]; GO +ALTER TABLE [dbo].[ScoreDimensionGroupViewHistory] ADD CONSTRAINT [DF__ScoreDime__ViewA__61A83189] DEFAULT ('') FOR [ViewAfter]; GO +ALTER TABLE [dbo].[ScoreDimensionGroupViewHistory] ADD CONSTRAINT [DF__ScoreDime__DateM__629C55C2] DEFAULT (getdate()) FOR [DateModified]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreDimensionHistoryLine ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreDimensionHistoryLine] ( + [DimensionHistoryLineID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [DateTimeStamp] datetime NOT NULL, + [TableName] nvarchar(64) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [BeforeValues] nvarchar(max) NOT NULL, + [AfterValues] nvarchar(max) NOT NULL, + PRIMARY KEY ([DimensionHistoryLineID]) +); + +CREATE NONCLUSTERED INDEX [NC_HISTORYITEMGUID_DATETIMESTAMP] ON [dbo].[ScoreDimensionHistoryLine] ([HistoryItemGUID], [DateTimeStamp]); +CREATE NONCLUSTERED INDEX [NC_MEMBERGUID_DATETIMESTAMP] ON [dbo].[ScoreDimensionHistoryLine] ([MemberGUID], [DateTimeStamp]); +GO +ALTER TABLE [dbo].[ScoreDimensionHistoryLine] ADD CONSTRAINT [DF_ScoreDimensionHistoryLine_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO +ALTER TABLE [dbo].[ScoreDimensionHistoryLine] ADD CONSTRAINT [DF_ScoreDimensionHistoryLine_TableName] DEFAULT ('') FOR [TableName]; GO +ALTER TABLE [dbo].[ScoreDimensionHistoryLine] ADD CONSTRAINT [DF_ScoreDimensionHistoryLine_BeforeValues] DEFAULT ('') FOR [BeforeValues]; GO +ALTER TABLE [dbo].[ScoreDimensionHistoryLine] ADD CONSTRAINT [DF_ScoreDimensionHistoryLine_AfterValues] DEFAULT ('') FOR [AfterValues]; GO +ALTER TABLE [dbo].[ScoreDimensionHistoryLine] ADD CONSTRAINT [DF_ScoreDimensionHistoryLine_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [dbo].[ScoreDimensionHistoryLine] ADD CONSTRAINT [DF_ScoreDimensionHistoryLine_MemberGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MemberGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreDimensionRegenRequest ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreDimensionRegenRequest] ( + [RequestGUID] uniqueidentifier NOT NULL, + [GlobalID] nvarchar(100) NOT NULL, + [IssuedAt] datetime NOT NULL, + [ErrorMessage] nvarchar(max) NOT NULL, + [Recommendation] nvarchar(max) NOT NULL, + [Author] nvarchar(100) NOT NULL, + [MigrationName] nvarchar(400) NOT NULL, + [LastProcessAttempt] datetime NOT NULL, + PRIMARY KEY ([RequestGUID]) +); +GO +ALTER TABLE [dbo].[ScoreDimensionRegenRequest] ADD CONSTRAINT [DF_ScoreDimensionRegenRequest_LastProcessAttempt] DEFAULT ('1/1/1900 12:00:00 AM') FOR [LastProcessAttempt]; GO +ALTER TABLE [dbo].[ScoreDimensionRegenRequest] ADD CONSTRAINT [DF_ScoreDimensionRegenRequest_MigrationName] DEFAULT ('') FOR [MigrationName]; GO +ALTER TABLE [dbo].[ScoreDimensionRegenRequest] ADD CONSTRAINT [DF_ScoreDimensionRegenRequest_ErrorMessage] DEFAULT ('') FOR [ErrorMessage]; GO +ALTER TABLE [dbo].[ScoreDimensionRegenRequest] ADD CONSTRAINT [DF_ScoreDimensionRegenRequest_Recommendation] DEFAULT ('') FOR [Recommendation]; GO +ALTER TABLE [dbo].[ScoreDimensionRegenRequest] ADD CONSTRAINT [DF_ScoreDimensionRegenRequest_Author] DEFAULT ('') FOR [Author]; GO +ALTER TABLE [dbo].[ScoreDimensionRegenRequest] ADD CONSTRAINT [DF_ScoreDimensionRegenRequest_RequestGUID] DEFAULT (newid()) FOR [RequestGUID]; GO +ALTER TABLE [dbo].[ScoreDimensionRegenRequest] ADD CONSTRAINT [DF_ScoreDimensionRegenRequest_GlobalID] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [dbo].[ScoreDimensionRegenRequest] ADD CONSTRAINT [DF_ScoreDimensionRegenRequest_IssuedAt] DEFAULT (getdate()) FOR [IssuedAt]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreFillInTemplateItem ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreFillInTemplateItem] ( + [FillInTemplateName] nvarchar(100) NOT NULL, + [FillInTemplateItemID] int NOT NULL, + [PlaceholderSectionMemberGUID] uniqueidentifier NOT NULL, + [PlaceholderSectionIndex] int NULL, + [IsQuery] bit NOT NULL, + [Query] nvarchar(max) NULL, + [IsCurrentModelGUID] bit NOT NULL, + [IsConstantMemberGUID] bit NOT NULL, + [ConstantMemberGUID] uniqueidentifier NULL, + PRIMARY KEY ([FillInTemplateItemID]) +); +GO +ALTER TABLE [dbo].[ScoreFillInTemplateItem] ADD CONSTRAINT [DF_ScoreFillInTemplateItem_FillInTemplateName] DEFAULT ('') FOR [FillInTemplateName]; GO +ALTER TABLE [dbo].[ScoreFillInTemplateItem] ADD CONSTRAINT [DF_ScoreFillInTemplate_IsQuery] DEFAULT ((0)) FOR [IsQuery]; GO +ALTER TABLE [dbo].[ScoreFillInTemplateItem] ADD CONSTRAINT [DF_ScoreFillInTemplate_IsCurrentModelGUID] DEFAULT ((0)) FOR [IsCurrentModelGUID]; GO +ALTER TABLE [dbo].[ScoreFillInTemplateItem] ADD CONSTRAINT [DF_ScoreFillInTemplateItem_IsConstantMemberGUID] DEFAULT ((0)) FOR [IsConstantMemberGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreFillin ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreFillin] ( + [FillinGUID] uniqueidentifier NOT NULL, + [ModelGUID] uniqueidentifier NOT NULL, + [PlaceholderSectionMemberGUID] uniqueidentifier NOT NULL, + [PlaceholderIndex] int NOT NULL, + [FillinMemberGUID] uniqueidentifier NOT NULL, + [FillinMemberName] nvarchar(max) NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [RowID] int NOT NULL, + [IsSystemSet] bit NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_ScoreFillin_Cluster] ON [dbo].[ScoreFillin] ([ModelGUID], [PlaceholderSectionMemberGUID]); +CREATE NONCLUSTERED INDEX [idx_isdeleted] ON [dbo].[ScoreFillin] ([IsDeleted]) INCLUDE ([FillinGUID]); +CREATE NONCLUSTERED INDEX [IDX_ScoreFillin] ON [dbo].[ScoreFillin] ([ModelGUID], [PlaceholderSectionMemberGUID], [FillinMemberGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [IDX_ScoreFillin_Unique] ON [dbo].[ScoreFillin] ([ModelGUID], [PlaceholderSectionMemberGUID], [PlaceholderIndex], [FillinMemberGUID], [IsDeleted]); +CREATE NONCLUSTERED INDEX [IDX_ScoreFillin_FillinMemberGUID] ON [dbo].[ScoreFillin] ([FillinMemberGUID]); +GO +ALTER TABLE [dbo].[ScoreFillin] ADD CONSTRAINT [FK_ScoreFillin_XPlan] FOREIGN KEY ([ModelGUID]) REFERENCES [dbo].[XPlan] ([PlanGUID]); GO +ALTER TABLE [dbo].[ScoreFillin] ADD CONSTRAINT [DF_ScoreFillin_PlaceholderIndex] DEFAULT ((0)) FOR [PlaceholderIndex]; GO +ALTER TABLE [dbo].[ScoreFillin] ADD CONSTRAINT [DF_ScoreFillin_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [dbo].[ScoreFillin] ADD CONSTRAINT [DF_ScoreFillin_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [dbo].[ScoreFillin] ADD CONSTRAINT [DF_ScoreFillin_ScoreFillinGUID] DEFAULT (newid()) FOR [FillinGUID]; GO +ALTER TABLE [dbo].[ScoreFillin] ADD CONSTRAINT [DF_ScoreFillin_FillInMemberName] DEFAULT (N'default') FOR [FillinMemberName]; GO +ALTER TABLE [dbo].[ScoreFillin] ADD CONSTRAINT [DF__ScoreFill__IsSys__7440DD13] DEFAULT ((0)) FOR [IsSystemSet]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreFillinExclusivityLogItem ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreFillinExclusivityLogItem] ( + [ScoreFillinExclusivityLogItemGUID] uniqueidentifier NOT NULL, + [ModelGUID] uniqueidentifier NOT NULL, + [FillinGUID] uniqueidentifier NOT NULL, + [FillinMemberGUID] uniqueidentifier NOT NULL, + [DateTimeStamp] datetime NOT NULL, + [Message] nvarchar(max) NOT NULL, + [TaskGUID] uniqueidentifier NOT NULL, + [IsError] bit NOT NULL, + [PlanTypeGUID] uniqueidentifier NOT NULL, + [FillinDimensionGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([ScoreFillinExclusivityLogItemGUID]) +); +GO +ALTER TABLE [dbo].[ScoreFillinExclusivityLogItem] ADD CONSTRAINT [DF_dbo_ScoreFillinExclusivityLogItem_FillinDimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FillinDimensionGUID]; GO +ALTER TABLE [dbo].[ScoreFillinExclusivityLogItem] ADD CONSTRAINT [DF_dbo_ScoreFillinExclusivityLogItem_IsError] DEFAULT ((0)) FOR [IsError]; GO +ALTER TABLE [dbo].[ScoreFillinExclusivityLogItem] ADD CONSTRAINT [DF_dbo_ScoreFillinExclusivityLogItem_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO +ALTER TABLE [dbo].[ScoreFillinExclusivityLogItem] ADD CONSTRAINT [DF_ScoreFillinExclusivityLogItem_ScoreFillinExclusivityLogItemGUID] DEFAULT (newid()) FOR [ScoreFillinExclusivityLogItemGUID]; GO +ALTER TABLE [dbo].[ScoreFillinExclusivityLogItem] ADD CONSTRAINT [DF_ScoreFillinExclusivityLogItem_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreFillinRefreshLogItem ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreFillinRefreshLogItem] ( + [ScoreFillinRefreshLogItemGUID] uniqueidentifier NOT NULL, + [FillinGUID] uniqueidentifier NOT NULL, + [FillinMemberGUID] uniqueidentifier NOT NULL, + [Action] smallint NOT NULL, + [DateTimeStamp] datetime NOT NULL, + [TaskGUID] uniqueidentifier NOT NULL, + [ModelGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [IsSystemSet] bit NOT NULL, + [FillinMemberName] nvarchar(max) NOT NULL, + [SectionName] nvarchar(100) NOT NULL, + PRIMARY KEY ([ScoreFillinRefreshLogItemGUID]) +); + +CREATE NONCLUSTERED INDEX [IX_ScoreFillinRefreshLogItem_FillinMemberGUID] ON [dbo].[ScoreFillinRefreshLogItem] ([FillinMemberGUID]) INCLUDE ([ModelGUID], [FillinMemberName]); +CREATE NONCLUSTERED INDEX [IX_ScoreFillinRefreshLogItem_ModelGUID] ON [dbo].[ScoreFillinRefreshLogItem] ([ModelGUID]); +CREATE NONCLUSTERED INDEX [NCNU_HistoryItemGUID] ON [dbo].[ScoreFillinRefreshLogItem] ([HistoryItemGUID]); +GO +ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF__ScoreFill__IsSys__08325F64] DEFAULT ((0)) FOR [IsSystemSet]; GO +ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF__ScoreFill__Filli__0926839D] DEFAULT ('') FOR [FillinMemberName]; GO +ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF__ScoreFill__Histo__073E3B2B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF_ScoreFillinRefreshLogItem_ScoreFillinRefreshLogItemGUID] DEFAULT (newid()) FOR [ScoreFillinRefreshLogItemGUID]; GO +ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF_ScoreFillinRefreshLogItem_FillinGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FillinGUID]; GO +ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF_ScoreFillinRefreshLogItem_FillinMemberGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FillinMemberGUID]; GO +ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF_ScoreFillinRefreshLogItem_Action] DEFAULT ((-1)) FOR [Action]; GO +ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF__ScoreFill__Secti__2A1D6314] DEFAULT ('') FOR [SectionName]; GO +ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF_ScoreFillinRefreshLogItem_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO +ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF_ScoreFillinRefreshLogItem_TaskGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TaskGUID]; GO +ALTER TABLE [dbo].[ScoreFillinRefreshLogItem] ADD CONSTRAINT [DF__ScoreFill__Model__7AB868B5] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreFillinSetManyStaging ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreFillinSetManyStaging] ( + [InstanceGUID] uniqueidentifier NOT NULL, + [ModelGUID] uniqueidentifier NOT NULL, + [PlaceholderSectionMemberGUID] uniqueidentifier NOT NULL, + [SortOrder] int NOT NULL, + [FillinMemberGUID] uniqueidentifier NOT NULL, + [FillinMemberName] nvarchar(50) NOT NULL, + [MakeUnique] uniqueidentifier NOT NULL +); +GO +ALTER TABLE [dbo].[ScoreFillinSetManyStaging] ADD CONSTRAINT [DF_ScoreFillinSetManyStaging_MakeUnique] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MakeUnique]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreFillin_old ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreFillin_old] ( + [FillinGUID] uniqueidentifier NOT NULL, + [ModelGUID] uniqueidentifier NOT NULL, + [PlaceholderSectionMemberGUID] uniqueidentifier NOT NULL, + [PlaceholderIndex] int NOT NULL, + [FillinMemberGUID] uniqueidentifier NOT NULL, + [FillinMemberName] nvarchar(max) NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [RowID] int NOT NULL, + [IsSystemSet] bit NOT NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreHierarchy ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreHierarchy] ( + [HierarchyGUID] uniqueidentifier NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + [FriendlyName] nvarchar(128) NOT NULL, + [PathAlias] nvarchar(12) NOT NULL, + [DateModified] datetime NOT NULL, + [HierarchyID] int NOT NULL, + [GlobalID] nvarchar(128) NOT NULL, + [IsMR] bit NOT NULL, + PRIMARY KEY ([HierarchyGUID]) +); +GO +ALTER TABLE [dbo].[ScoreHierarchy] ADD CONSTRAINT [FK_ScoreHierarchy_ScoreDimension] FOREIGN KEY ([DimensionGUID]) REFERENCES [dbo].[ScoreDimension] ([DimensionGUID]); GO +ALTER TABLE [dbo].[ScoreHierarchy] ADD CONSTRAINT [DF__ScoreHiera__IsMR__09519DF0] DEFAULT ((0)) FOR [IsMR]; GO +ALTER TABLE [dbo].[ScoreHierarchy] ADD CONSTRAINT [DF_ScoreHierarchy_DateModified] DEFAULT (getdate()) FOR [DateModified]; GO +ALTER TABLE [dbo].[ScoreHierarchy] ADD CONSTRAINT [DF__ScoreHier__Globa__177240EF] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [dbo].[ScoreHierarchy] ADD CONSTRAINT [DF_ScoreHierarchy_PathAlias] DEFAULT ('') FOR [PathAlias]; GO +ALTER TABLE [dbo].[ScoreHierarchy] ADD CONSTRAINT [DF_ScoreHeirarchy_HeirarchyGUID] DEFAULT (newid()) FOR [HierarchyGUID]; GO +ALTER TABLE [dbo].[ScoreHierarchy] ADD CONSTRAINT [DF_ScoreHeirarchy_DimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreHierarchyAttributeLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreHierarchyAttributeLink] ( + [HierarchyAttributeLinkGUID] uniqueidentifier NOT NULL, + [HierarchyGUID] uniqueidentifier NOT NULL, + [AttributeGUID] uniqueidentifier NOT NULL, + [DisplayAttributeGUID] uniqueidentifier NOT NULL, + [SortOrder] int NOT NULL, + [IsDependentOnChild] bit NOT NULL, + [DateModified] datetime NOT NULL, + [IsAttributeFiltered] bit NOT NULL, + [FilterAttributeGUID] uniqueidentifier NOT NULL, + [FilterString] nvarchar(250) NOT NULL, + PRIMARY KEY ([HierarchyAttributeLinkGUID]) +); +GO +ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [FK_ScoreHeirarchyAttributeLink_ScoreAttribute] FOREIGN KEY ([AttributeGUID]) REFERENCES [dbo].[ScoreAttribute] ([AttributeGUID]); GO +ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [FK_ScoreHeirarchyAttributeLink_ScoreHeirarchy] FOREIGN KEY ([HierarchyGUID]) REFERENCES [dbo].[ScoreHierarchy] ([HierarchyGUID]); GO +ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [DF_ScoreHierarchyAttributeLink_FilterAttributeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FilterAttributeGUID]; GO +ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [DF_ScoreHierarchyAttributeLink_DateModified] DEFAULT (getdate()) FOR [DateModified]; GO +ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [DF_ScoreHierarchyAttributeLink_IsAttributeFiltered] DEFAULT ((0)) FOR [IsAttributeFiltered]; GO +ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [DF_ScoreHierarchyAttributeLink_FilterString] DEFAULT ('') FOR [FilterString]; GO +ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [DF_ScoreHeirarchyAttributeLink_ScoreHeirarchyAttributeLinkGUID] DEFAULT (newid()) FOR [HierarchyAttributeLinkGUID]; GO +ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [DF_ScoreHeirarchyAttributeLink_HeirarchyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HierarchyGUID]; GO +ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [DF_ScoreHierarchyAttributeLink_AttributeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AttributeGUID]; GO +ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [DF_ScoreHierarchyAttributeLink_DisplayAttributeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DisplayAttributeGUID]; GO +ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [DF_ScoreHeirarchyAttributeLink_SortOrder] DEFAULT ((1)) FOR [SortOrder]; GO +ALTER TABLE [dbo].[ScoreHierarchyAttributeLink] ADD CONSTRAINT [DF_ScoreHierarchyAttributeLink_IsDependentOnChild] DEFAULT ((0)) FOR [IsDependentOnChild]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreKeyLinkSetting ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreKeyLinkSetting] ( + [ScoreKeyLinkSettingGuid] uniqueidentifier NOT NULL, + [KeyGUID] uniqueidentifier NOT NULL, + [DataTableGUID] uniqueidentifier NOT NULL, + [IsUsed] bit NOT NULL, + [IsCustom] bit NOT NULL, + [IsMarkedForDeletion] bit NOT NULL, + PRIMARY KEY ([ScoreKeyLinkSettingGuid]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [UQ_SCOREKEYLINKSETTING_DATATABLEGUIDKEYGUID] ON [dbo].[ScoreKeyLinkSetting] ([DataTableGUID], [KeyGUID]); +GO +ALTER TABLE [dbo].[ScoreKeyLinkSetting] ADD CONSTRAINT [FK__ScoreKeyL__DataT__5226C22E] FOREIGN KEY ([DataTableGUID]) REFERENCES [dbo].[ScoreDatatableSetting] ([DataTableGUID]); GO +ALTER TABLE [dbo].[ScoreKeyLinkSetting] ADD CONSTRAINT [DF__ScoreKeyL__IsMar__3BBB8B7E] DEFAULT ((0)) FOR [IsMarkedForDeletion]; GO +ALTER TABLE [dbo].[ScoreKeyLinkSetting] ADD CONSTRAINT [DF__ScoreKeyL__Score__51329DF5] DEFAULT (newid()) FOR [ScoreKeyLinkSettingGuid]; GO +ALTER TABLE [dbo].[ScoreKeyLinkSetting] ADD CONSTRAINT [DF__ScoreKeyL__IsUse__531AE667] DEFAULT ((0)) FOR [IsUsed]; GO +ALTER TABLE [dbo].[ScoreKeyLinkSetting] ADD CONSTRAINT [DF__ScoreKeyL__IsCus__55032ED9] DEFAULT ((0)) FOR [IsCustom]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreMeasure ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreMeasure] ( + [MeasureGUID] uniqueidentifier NOT NULL, + [FriendlyName] nvarchar(64) NOT NULL, + [DataTableGUID] uniqueidentifier NOT NULL, + [IsReadFromDB] bit NOT NULL, + [IsWrittenToDB] bit NOT NULL, + [SQLColumnName] nvarchar(64) NOT NULL, + [DisplayFormat] nvarchar(64) NOT NULL, + [HasMin] bit NOT NULL, + [Min] decimal NOT NULL, + [HasMax] bit NOT NULL, + [Max] decimal NOT NULL, + [HasMinLength] bit NOT NULL, + [MinLength] int NOT NULL, + [DefaultValue] nvarchar(64) NOT NULL, + [AggType] int NOT NULL, + [SpecialMeasureIndex] tinyint NOT NULL, + [SpecialFormulaSQLColumnName] nvarchar(64) NOT NULL, + [SpecialCommentSQLColumnName] nvarchar(64) NOT NULL, + [HasRestrictedValues] bit NOT NULL, + [RestrictedValues] nvarchar(max) NOT NULL, + [ObjectID] int NOT NULL, + [ColumnID] int NOT NULL, + [SchemaName] nvarchar(128) NOT NULL, + [ObjectName] nvarchar(128) NOT NULL, + [ColumnName] nvarchar(128) NOT NULL, + [ObjectType] int NOT NULL, + [MaxLength] smallint NOT NULL, + [IsComputed] bit NOT NULL, + [IsNullable] bit NOT NULL, + [Scale] tinyint NOT NULL, + [Precision] tinyint NOT NULL, + [IsIdentity] bit NOT NULL, + [ColumnTypeValue] tinyint NOT NULL, + [IdentityIncrement] int NOT NULL, + [IdentitySeed] int NOT NULL, + [DefaultValueDefinition] nvarchar(max) NOT NULL, + [IsPartOfUniqueIndex] bit NOT NULL, + [IsUniqueIndex] bit NOT NULL, + [IsPartOfPrimaryKey] bit NOT NULL, + [IsPrimaryKey] bit NOT NULL, + [ComputedValueDefinition] nvarchar(max) NOT NULL, + [IsForeignKeyed] bit NOT NULL, + [ForeignKeySchema] nvarchar(128) NOT NULL, + [ForeignKeyTable] nvarchar(128) NOT NULL, + [ForeignKeyColumn] nvarchar(128) NOT NULL, + [ForeignKeyOnDelete] nvarchar(128) NOT NULL, + [ModifiedAt] datetime NOT NULL, + [IsHidden] bit NOT NULL, + [GlobalID] nvarchar(100) NOT NULL, + [IsRequired] bit NOT NULL, + [Description] nvarchar(1000) NOT NULL, + [DisplayFolder] nvarchar(50) NOT NULL, + PRIMARY KEY ([MeasureGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_ScoreMeasure_UniqueColumn] ON [dbo].[ScoreMeasure] ([DataTableGUID], [SQLColumnName]); +CREATE NONCLUSTERED INDEX [IX_MemberGUID] ON [dbo].[ScoreMeasure] ([MeasureGUID]) INCLUDE ([SQLColumnName]); +GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [FK_ScoreMeasure_ScoreDataTable] FOREIGN KEY ([DataTableGUID]) REFERENCES [dbo].[ScoreDataTable] ([DataTableGUID]); GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Objec__13A3AE7C] DEFAULT ((0)) FOR [ObjectID]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Colum__1497D2B5] DEFAULT ((0)) FOR [ColumnID]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Schem__158BF6EE] DEFAULT ('') FOR [SchemaName]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Objec__16801B27] DEFAULT ('') FOR [ObjectName]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Colum__17743F60] DEFAULT ('') FOR [ColumnName]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Objec__18686399] DEFAULT ((0)) FOR [ObjectType]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__MaxLe__195C87D2] DEFAULT ((0)) FOR [MaxLength]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__IsCom__1A50AC0B] DEFAULT ((0)) FOR [IsComputed]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__IsNul__1B44D044] DEFAULT ((0)) FOR [IsNullable]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Scale__1C38F47D] DEFAULT ((0)) FOR [Scale]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Preci__1D2D18B6] DEFAULT ((0)) FOR [Precision]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Descr__1948D9EE] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__IsIde__1E213CEF] DEFAULT ((0)) FOR [IsIdentity]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Colum__1F156128] DEFAULT ((0)) FOR [ColumnTypeValue]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Displ__1BD9C8F2] DEFAULT ('') FOR [DisplayFolder]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Ident__20098561] DEFAULT ((0)) FOR [IdentityIncrement]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Ident__20FDA99A] DEFAULT ((0)) FOR [IdentitySeed]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Defau__21F1CDD3] DEFAULT ('') FOR [DefaultValueDefinition]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__IsPar__22E5F20C] DEFAULT ((0)) FOR [IsPartOfUniqueIndex]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__IsUni__23DA1645] DEFAULT ((0)) FOR [IsUniqueIndex]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__IsPar__24CE3A7E] DEFAULT ((0)) FOR [IsPartOfPrimaryKey]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__IsPri__25C25EB7] DEFAULT ((0)) FOR [IsPrimaryKey]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Compu__26B682F0] DEFAULT ('') FOR [ComputedValueDefinition]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__IsFor__27AAA729] DEFAULT ((0)) FOR [IsForeignKeyed]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Forei__289ECB62] DEFAULT ('') FOR [ForeignKeySchema]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Forei__2992EF9B] DEFAULT ('') FOR [ForeignKeyTable]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Forei__2A8713D4] DEFAULT ('') FOR [ForeignKeyColumn]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Forei__2B7B380D] DEFAULT ('') FOR [ForeignKeyOnDelete]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Modif__042C60C2] DEFAULT (getdate()) FOR [ModifiedAt]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__IsHid__30F380B4] DEFAULT ((0)) FOR [IsHidden]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_SpecialMeasureIndex] DEFAULT ((0)) FOR [SpecialMeasureIndex]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_HasRestrictedValues] DEFAULT ((0)) FOR [HasRestrictedValues]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_SpecialFormulaSQLColumnName] DEFAULT ('') FOR [SpecialFormulaSQLColumnName]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_RestrictedValues] DEFAULT ('') FOR [RestrictedValues]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_SpecialCommentSQLColumnName] DEFAULT ('') FOR [SpecialCommentSQLColumnName]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_AggType] DEFAULT ((1)) FOR [AggType]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_MeasureGUID] DEFAULT (newid()) FOR [MeasureGUID]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_FriendlyName] DEFAULT ('') FOR [FriendlyName]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_DataTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTableGUID]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_IsReadFromDB] DEFAULT ((1)) FOR [IsReadFromDB]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_IsWrittenToDB] DEFAULT ((1)) FOR [IsWrittenToDB]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__IsReq__5DB8706B] DEFAULT ((0)) FOR [IsRequired]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_SQLColumnName] DEFAULT ('') FOR [SQLColumnName]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_Min] DEFAULT ((0)) FOR [Min]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_DisplayFormat] DEFAULT ('') FOR [DisplayFormat]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_Max] DEFAULT ((0)) FOR [Max]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_HasMin] DEFAULT ((0)) FOR [HasMin]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_HasMax] DEFAULT ((0)) FOR [HasMax]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_HasMinLength] DEFAULT ((0)) FOR [HasMinLength]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_MinLength] DEFAULT ((0)) FOR [MinLength]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF_ScoreMeasure_DefaultValue] DEFAULT ('') FOR [DefaultValue]; GO +ALTER TABLE [dbo].[ScoreMeasure] ADD CONSTRAINT [DF__ScoreMeas__Globa__73B5684A] DEFAULT ('') FOR [GlobalID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreMeasureLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreMeasureLink] ( + [MeasureLinkID] int NOT NULL, + [MeasureGUID] uniqueidentifier NOT NULL, + [ParentMeasureGUID] uniqueidentifier NOT NULL, + [MeasureLinkType] int NOT NULL, + PRIMARY KEY ([MeasureLinkID]) +); +GO +ALTER TABLE [dbo].[ScoreMeasureLink] ADD CONSTRAINT [FK_ScoreMeasureLink_ScoreMeasure] FOREIGN KEY ([MeasureGUID]) REFERENCES [dbo].[ScoreMeasure] ([MeasureGUID]); GO +ALTER TABLE [dbo].[ScoreMeasureLink] ADD CONSTRAINT [FK_ScoreMeasureLink_ScoreMeasure1] FOREIGN KEY ([ParentMeasureGUID]) REFERENCES [dbo].[ScoreMeasure] ([MeasureGUID]); GO +ALTER TABLE [dbo].[ScoreMeasureLink] ADD CONSTRAINT [DF_ScoreMeasureLink_MeasureGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO +ALTER TABLE [dbo].[ScoreMeasureLink] ADD CONSTRAINT [DF_ScoreMeasureLink_MeasureLinkType] DEFAULT ((0)) FOR [MeasureLinkType]; GO +ALTER TABLE [dbo].[ScoreMeasureLink] ADD CONSTRAINT [DF_ScoreMeasureLink_ParentMeasureGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentMeasureGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreMeasureLinkParameter ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreMeasureLinkParameter] ( + [MeasureLinkID] int NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Value] nvarchar(max) NOT NULL, + PRIMARY KEY ([MeasureLinkID], [Name]) +); +GO +ALTER TABLE [dbo].[ScoreMeasureLinkParameter] ADD CONSTRAINT [FK_ScoreMeasureLinkParameter_ScoreMeasureLink] FOREIGN KEY ([MeasureLinkID]) REFERENCES [dbo].[ScoreMeasureLink] ([MeasureLinkID]); GO +ALTER TABLE [dbo].[ScoreMeasureLinkParameter] ADD CONSTRAINT [DF_ScoreMeasureLinkParameter_MeasureLinkID] DEFAULT ((0)) FOR [MeasureLinkID]; GO +ALTER TABLE [dbo].[ScoreMeasureLinkParameter] ADD CONSTRAINT [DF_ScoreMeasureLinkParameter_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[ScoreMeasureLinkParameter] ADD CONSTRAINT [DF_ScoreMeasureLinkParameter_Value] DEFAULT ('') FOR [Value]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreMeasureSetting ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreMeasureSetting] ( + [ScoreMeasureSettingGuid] uniqueidentifier NOT NULL, + [MeasureGUID] uniqueidentifier NOT NULL, + [DataTableGUID] uniqueidentifier NOT NULL, + [IsUsed] bit NOT NULL, + [IsCustom] bit NOT NULL, + [IsMarkedForDeletion] bit NOT NULL, + PRIMARY KEY ([ScoreMeasureSettingGuid]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [UQ_SCOREMEASURESETTING_MEASUREGUID] ON [dbo].[ScoreMeasureSetting] ([MeasureGUID]); +GO +ALTER TABLE [dbo].[ScoreMeasureSetting] ADD CONSTRAINT [FK__ScoreMeas__DataT__58D3BFBD] FOREIGN KEY ([DataTableGUID]) REFERENCES [dbo].[ScoreDatatableSetting] ([DataTableGUID]); GO +ALTER TABLE [dbo].[ScoreMeasureSetting] ADD CONSTRAINT [DF__ScoreMeas__IsMar__3CAFAFB7] DEFAULT ((0)) FOR [IsMarkedForDeletion]; GO +ALTER TABLE [dbo].[ScoreMeasureSetting] ADD CONSTRAINT [DF__ScoreMeas__Score__57DF9B84] DEFAULT (newid()) FOR [ScoreMeasureSettingGuid]; GO +ALTER TABLE [dbo].[ScoreMeasureSetting] ADD CONSTRAINT [DF__ScoreMeas__IsUse__59C7E3F6] DEFAULT ((0)) FOR [IsUsed]; GO +ALTER TABLE [dbo].[ScoreMeasureSetting] ADD CONSTRAINT [DF__ScoreMeas__IsCus__5BB02C68] DEFAULT ((0)) FOR [IsCustom]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreModelLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreModelLink] ( + [ModelLinkID] int NOT NULL, + [SourceModelGUID] uniqueidentifier NOT NULL, + [TargetModelGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([ModelLinkID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreTableEditorColumn ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreTableEditorColumn] ( + [TableEditorColumnGUID] uniqueidentifier NOT NULL, + [TableEditorConfigGUID] uniqueidentifier NOT NULL, + [KeyGUID] uniqueidentifier NOT NULL, + [Type] int NOT NULL, + [PixelWidth] int NOT NULL, + [DisplayOrder] int NOT NULL, + [MetaData] xml(max) NOT NULL, + [DisplayName] nvarchar(450) NOT NULL, + [DefaultMemberType] int NOT NULL, + [IsTextWrap] bit NOT NULL, + [IsSortedByDefault] bit NOT NULL, + [DefaultSortDirectionValue] int NOT NULL, + [DefaultSortIndex] int NOT NULL, + [TableEditorColumnGroupGUID] uniqueidentifier NOT NULL, + [IsRequired] bit NOT NULL, + [IsLocked] bit NOT NULL, + [IsNonFilterable] bit NOT NULL, + PRIMARY KEY ([TableEditorColumnGUID]) +); +GO +ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [FK_ScoreTableEditorColumn_ScoreTableEditorConfig] FOREIGN KEY ([TableEditorConfigGUID]) REFERENCES [dbo].[ScoreTableEditorConfig] ([TableEditorConfigGUID]); GO +ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF__ScoreTabl__Table__7586401E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TableEditorColumnGroupGUID]; GO +ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_IsTextWrap] DEFAULT ((0)) FOR [IsTextWrap]; GO +ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF__ScoreTabl__IsReq__2B67F1EC] DEFAULT ((0)) FOR [IsRequired]; GO +ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_IsDefaultSorted] DEFAULT ((0)) FOR [IsSortedByDefault]; GO +ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF__ScoreTabl__IsLoc__2D503A5E] DEFAULT ((0)) FOR [IsLocked]; GO +ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_DefaultSortDirectionValue] DEFAULT ((0)) FOR [DefaultSortDirectionValue]; GO +ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_DefaultSortIndex] DEFAULT ((0)) FOR [DefaultSortIndex]; GO +ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF__ScoreTabl__IsNon__330913B4] DEFAULT ((0)) FOR [IsNonFilterable]; GO +ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_DisplayName] DEFAULT ('') FOR [DisplayName]; GO +ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_DefaultMemberType] DEFAULT ((0)) FOR [DefaultMemberType]; GO +ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_TableEditorColumnGUID] DEFAULT (newid()) FOR [TableEditorColumnGUID]; GO +ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_TableEditorConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TableEditorConfigGUID]; GO +ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_KeyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [KeyGUID]; GO +ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_IsMeasure] DEFAULT ((0)) FOR [Type]; GO +ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_PixelWidth] DEFAULT ((150)) FOR [PixelWidth]; GO +ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_DisplayOrder] DEFAULT ((-1)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[ScoreTableEditorColumn] ADD CONSTRAINT [DF_ScoreTableEditorColumn_MetaData] DEFAULT ('') FOR [MetaData]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreTableEditorColumnGroup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreTableEditorColumnGroup] ( + [TableEditorColumnGroupGUID] uniqueidentifier NOT NULL, + [TableEditorConfigGUID] uniqueidentifier NOT NULL, + [DisplayColumnGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [GroupType] int NOT NULL, + [IsActive] bit NOT NULL, + PRIMARY KEY ([TableEditorColumnGroupGUID]) +); +GO +ALTER TABLE [dbo].[ScoreTableEditorColumnGroup] ADD CONSTRAINT [FK__ScoreTabl__Table__4DCD547F] FOREIGN KEY ([TableEditorConfigGUID]) REFERENCES [dbo].[ScoreTableEditorConfig] ([TableEditorConfigGUID]); GO +ALTER TABLE [dbo].[ScoreTableEditorColumnGroup] ADD CONSTRAINT [DF__ScoreTabl__Table__4CD93046] DEFAULT (newid()) FOR [TableEditorColumnGroupGUID]; GO +ALTER TABLE [dbo].[ScoreTableEditorColumnGroup] ADD CONSTRAINT [DF__ScoreTabl__Displ__4EC178B8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DisplayColumnGUID]; GO +ALTER TABLE [dbo].[ScoreTableEditorColumnGroup] ADD CONSTRAINT [DF__ScoreTable__Name__4FB59CF1] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[ScoreTableEditorColumnGroup] ADD CONSTRAINT [DF__ScoreTabl__Group__50A9C12A] DEFAULT ((0)) FOR [GroupType]; GO +ALTER TABLE [dbo].[ScoreTableEditorColumnGroup] ADD CONSTRAINT [DF__ScoreTabl__IsAct__519DE563] DEFAULT ((0)) FOR [IsActive]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreTableEditorConfig ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreTableEditorConfig] ( + [TableEditorConfigGUID] uniqueidentifier NOT NULL, + [DataSourceGUID] uniqueidentifier NOT NULL, + [FriendlyName] nvarchar(64) NOT NULL, + [MaxRecords] int NOT NULL, + [DefaultSortColumnGUID] uniqueidentifier NOT NULL, + [DefaultSortDirection] bit NOT NULL, + [IsShowingExpanded] bit NOT NULL, + [IsMeasureEditOnly] bit NOT NULL, + [FolderGUID] uniqueidentifier NOT NULL, + [IsTemplateBased] bit NOT NULL, + [FixedRowHeight] int NOT NULL, + [IsDeleteAllowed] bit NOT NULL, + [RowNumberColumnGUID] uniqueidentifier NOT NULL, + [CreatedDate] datetime NOT NULL, + [CreatedBy] uniqueidentifier NOT NULL, + [LastUsedDate] datetime NOT NULL, + [IsPromptForFilter] bit NOT NULL, + [IsAutoAddRow] bit NOT NULL, + [IsPlanFKFilterEnabled] bit NOT NULL, + [IsForModel] bit NOT NULL, + [IsSaveCommentsRequired] bit NOT NULL, + [VarianceMode] int NOT NULL, + [IsSensitivityRiskEnabled] bit NOT NULL, + [IsReadOnly] bit NOT NULL, + [IsBaselineLocked] bit NOT NULL, + [IsAddAllowed] bit NOT NULL, + [IsScoreFillinAdvancedMode] bit NOT NULL, + [OnSaveCustomScriptGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([TableEditorConfigGUID]) +); +GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsScoreFillinAdvancedMode] DEFAULT ((0)) FOR [IsScoreFillinAdvancedMode]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_CreatedBy] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CreatedBy]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsSensitivityRiskEnabled] DEFAULT ((0)) FOR [IsSensitivityRiskEnabled]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_TableEditorConfigGUID] DEFAULT (newid()) FOR [TableEditorConfigGUID]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_DataSourceGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataSourceGUID]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_Name] DEFAULT ('') FOR [FriendlyName]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_MaxRecords] DEFAULT ((500)) FOR [MaxRecords]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_DefaultSortKeyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultSortColumnGUID]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_DefaultSortDirection] DEFAULT ((0)) FOR [DefaultSortDirection]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsShowingExpanded] DEFAULT ((0)) FOR [IsShowingExpanded]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsMeasureEditOnly] DEFAULT ((0)) FOR [IsMeasureEditOnly]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_FolderGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsTemplateBased] DEFAULT ((0)) FOR [IsTemplateBased]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_FixedRowHeight] DEFAULT ((50)) FOR [FixedRowHeight]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsDeleteAllowed] DEFAULT ((1)) FOR [IsDeleteAllowed]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsReadOnly] DEFAULT ((0)) FOR [IsReadOnly]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF__ScoreTabl__Varia__231800A4] DEFAULT ((0)) FOR [VarianceMode]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsAutoAddRow] DEFAULT ((0)) FOR [IsAutoAddRow]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_OnSaveCustomScriptGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OnSaveCustomScriptGUID]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsForModel] DEFAULT ((0)) FOR [IsForModel]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_CreatedDate] DEFAULT (getdate()) FOR [CreatedDate]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_LastUsedDate] DEFAULT (getdate()) FOR [LastUsedDate]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsPromptForFilter] DEFAULT ((0)) FOR [IsPromptForFilter]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF__ScoreTabl__IsBas__66990249] DEFAULT ((0)) FOR [IsBaselineLocked]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF__ScoreTabl__IsSav__686AA574] DEFAULT ((0)) FOR [IsSaveCommentsRequired]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsAddAllowed] DEFAULT ((1)) FOR [IsAddAllowed]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_RowNumberColumnGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RowNumberColumnGUID]; GO +ALTER TABLE [dbo].[ScoreTableEditorConfig] ADD CONSTRAINT [DF_ScoreTableEditorConfig_IsPlanFKFilterEnabled] DEFAULT ((1)) FOR [IsPlanFKFilterEnabled]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreTableEditorFilter ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreTableEditorFilter] ( + [TableEditorFilterGUID] uniqueidentifier NOT NULL, + [TableEditorConfigGUID] uniqueidentifier NOT NULL, + [KeyGUID] uniqueidentifier NOT NULL, + [HierarchyPath] nvarchar(4000) NOT NULL, + [FriendlyName] nvarchar(450) NOT NULL, + [FilterType] int NOT NULL, + [MetaData] nvarchar(max) NOT NULL, + PRIMARY KEY ([TableEditorFilterGUID]) +); +GO +ALTER TABLE [dbo].[ScoreTableEditorFilter] ADD CONSTRAINT [FK_ScoreTableEditorFilter_ScoreTableEditorConfig] FOREIGN KEY ([TableEditorConfigGUID]) REFERENCES [dbo].[ScoreTableEditorConfig] ([TableEditorConfigGUID]); GO +ALTER TABLE [dbo].[ScoreTableEditorFilter] ADD CONSTRAINT [DF_ScoreTableEditorFilter_TableEditorFilterGUID] DEFAULT (newid()) FOR [TableEditorFilterGUID]; GO +ALTER TABLE [dbo].[ScoreTableEditorFilter] ADD CONSTRAINT [DF_ScoreTableEditorFilter_TableEditorConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TableEditorConfigGUID]; GO +ALTER TABLE [dbo].[ScoreTableEditorFilter] ADD CONSTRAINT [DF_ScoreTableEditorFilter_KeyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [KeyGUID]; GO +ALTER TABLE [dbo].[ScoreTableEditorFilter] ADD CONSTRAINT [DF_ScoreTableEditorFilter_HierarchyPath] DEFAULT ('') FOR [HierarchyPath]; GO +ALTER TABLE [dbo].[ScoreTableEditorFilter] ADD CONSTRAINT [DF_ScoreTableEditorFilter_FriendlyName] DEFAULT ('') FOR [FriendlyName]; GO +ALTER TABLE [dbo].[ScoreTableEditorFilter] ADD CONSTRAINT [DF_ScoreTableEditorFilter_FilterType] DEFAULT ((0)) FOR [FilterType]; GO +ALTER TABLE [dbo].[ScoreTableEditorFilter] ADD CONSTRAINT [DF_ScoreTableEditorFilter_MetaData] DEFAULT ('') FOR [MetaData]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ScoreTupleDataHistoryChangeItem ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ( + [RowID] int NOT NULL, + [ChangedRowID] bigint NOT NULL, + [DataTableGUID] uniqueidentifier NOT NULL, + [WorksheetName] nvarchar(max) NOT NULL, + [CellAddress] nvarchar(100) NOT NULL, + [MeasureGUID] uniqueidentifier NOT NULL, + [TupleString] nvarchar(max) NOT NULL, + [BeforeValueString] nvarchar(max) NOT NULL, + [BeforeFormula] nvarchar(max) NOT NULL, + [BeforeValueIsNumeric] bit NOT NULL, + [AfterValueString] nvarchar(max) NOT NULL, + [AfterFormula] nvarchar(max) NOT NULL, + [AfterValueIsNumeric] bit NOT NULL, + [IsUserSet] bit NOT NULL, + [IdentityGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_ScoreTupleDataHistoryChangeItem] ON [dbo].[ScoreTupleDataHistoryChangeItem] ([HistoryItemGUID]); +GO +ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_DataTableGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DataTableGUID]; GO +ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_IdentityGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [IdentityGUID]; GO +ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_MeasureGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO +ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_WorksheetName] DEFAULT ('') FOR [WorksheetName]; GO +ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_CellAddress] DEFAULT ('') FOR [CellAddress]; GO +ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_TupleString] DEFAULT ('') FOR [TupleString]; GO +ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_BeforeValueString] DEFAULT ('') FOR [BeforeValueString]; GO +ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_BeforeFormula] DEFAULT ('') FOR [BeforeFormula]; GO +ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_BeforeValueIsNumeric] DEFAULT ((0)) FOR [BeforeValueIsNumeric]; GO +ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_AfterValueString] DEFAULT ('') FOR [AfterValueString]; GO +ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_AfterFormula] DEFAULT ('') FOR [AfterFormula]; GO +ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_AfterValueIsNumeric] DEFAULT ((0)) FOR [AfterValueIsNumeric]; GO +ALTER TABLE [dbo].[ScoreTupleDataHistoryChangeItem] ADD CONSTRAINT [DF_ScoreTupleDataHistoryChangeItem_IsUserSet] DEFAULT ((0)) FOR [IsUserSet]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SecureList ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SecureList] ( + [ListGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(128) NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [FolderGUID] uniqueidentifier NOT NULL, + [DefaultListMemberGUID] uniqueidentifier NOT NULL, + [DisplayOrder] int NOT NULL, + [AggregationType] int NOT NULL, + [OriginalGUID] uniqueidentifier NOT NULL, + [ListType] int NOT NULL, + [DimensionType] int NOT NULL, + [Version] timestamp NOT NULL, + [DefaultListMemberID] nvarchar(450) NOT NULL, + [IsSecured] bit NOT NULL, + [UnknownMemberBehavior] int NOT NULL, + [IsPlaceholder] bit NOT NULL, + [FillInDimensionGUID] uniqueidentifier NOT NULL, + [PermissionSetID] smallint NOT NULL, + [IsSetupLocked] bit NOT NULL, + [IsSecurityHackEnabled] bit NOT NULL, + [IsEditLocked] bit NOT NULL, + [SyncedScoreDimensionGUID] uniqueidentifier NULL, + [SyncedScoreNameAttributeGUID] uniqueidentifier NULL, + [ConvertedScoreDimensionGUID] uniqueidentifier NULL, + [SyncedScoreOrderByAttributeGUID] uniqueidentifier NULL, + PRIMARY KEY ([ListGUID]) +); +GO +ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_PermissionSetID] DEFAULT ((0)) FOR [PermissionSetID]; GO +ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_IsSetupLocked] DEFAULT ((0)) FOR [IsSetupLocked]; GO +ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_ConvertedScoreDimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ConvertedScoreDimensionGUID]; GO +ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_DPList_ListGUID] DEFAULT (newid()) FOR [ListGUID]; GO +ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_DPList_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_DPList_Description] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_DPList_FolderGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO +ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_DPList_DEFAULTLISTITEMGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultListMemberGUID]; GO +ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_DPList_DISPLAYORDER_1] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_IsAggregatable] DEFAULT ((1)) FOR [AggregationType]; GO +ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_ORIGINALGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OriginalGUID]; GO +ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_LISTOWNERTYPE] DEFAULT ((0)) FOR [ListType]; GO +ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_LISTTYPE] DEFAULT ((0)) FOR [DimensionType]; GO +ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_DEFAULTLISTMEMBERID] DEFAULT ('') FOR [DefaultListMemberID]; GO +ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_IsSecured] DEFAULT ((0)) FOR [IsSecured]; GO +ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_UNKNOWNMEMBERBEHAVIOR] DEFAULT ((0)) FOR [UnknownMemberBehavior]; GO +ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_IsPlaceholder] DEFAULT ((0)) FOR [IsPlaceholder]; GO +ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_FillInDimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FillInDimensionGUID]; GO +ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_IsEditLocked] DEFAULT ((0)) FOR [IsEditLocked]; GO +ALTER TABLE [dbo].[SecureList] ADD CONSTRAINT [DF_SecureList_IsSecurityHackEnabled] DEFAULT ((0)) FOR [IsSecurityHackEnabled]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SecureListInsertionPoint ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SecureListInsertionPoint] ( + [ListInsertionPointGUID] uniqueidentifier NOT NULL, + [ListGUID] uniqueidentifier NOT NULL, + [ParentListMemberGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Description] nvarchar(450) NOT NULL, + PRIMARY KEY ([ListInsertionPointGUID]) +); +GO +ALTER TABLE [dbo].[SecureListInsertionPoint] ADD CONSTRAINT [FK_SecureListInsertionPoint_SecureList] FOREIGN KEY ([ListGUID]) REFERENCES [dbo].[SecureList] ([ListGUID]); GO +ALTER TABLE [dbo].[SecureListInsertionPoint] ADD CONSTRAINT [DF_SecureListInsertionPoint_LISTINSERTIONPOINTGUID] DEFAULT (newid()) FOR [ListInsertionPointGUID]; GO +ALTER TABLE [dbo].[SecureListInsertionPoint] ADD CONSTRAINT [DF_SecureListInsertionPoint_LISTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ListGUID]; GO +ALTER TABLE [dbo].[SecureListInsertionPoint] ADD CONSTRAINT [DF_SecureListInsertionPoint_PARENTLISTMEMBERGUID_1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentListMemberGUID]; GO +ALTER TABLE [dbo].[SecureListInsertionPoint] ADD CONSTRAINT [DF_SecureListInsertionPoint_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SecureListInsertionPoint] ADD CONSTRAINT [DF_SecureListInsertionPoint_DESCRIPTION] DEFAULT ('') FOR [Description]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SecureListLevel ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SecureListLevel] ( + [ListLevelGUID] uniqueidentifier NOT NULL, + [ListGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [LevelIndex] int NOT NULL, + [LevelType] int NOT NULL, + [Version] timestamp NOT NULL, + PRIMARY KEY ([ListLevelGUID]) +); + +CREATE CLUSTERED INDEX [IX_SecureListLevel] ON [dbo].[SecureListLevel] ([ListGUID], [LevelIndex]); +GO +ALTER TABLE [dbo].[SecureListLevel] ADD CONSTRAINT [FK_SecureListLevel_SecureList] FOREIGN KEY ([ListGUID]) REFERENCES [dbo].[SecureList] ([ListGUID]); GO +ALTER TABLE [dbo].[SecureListLevel] ADD CONSTRAINT [DF_Table_1_SECURELISTLEVEL] DEFAULT (newid()) FOR [ListLevelGUID]; GO +ALTER TABLE [dbo].[SecureListLevel] ADD CONSTRAINT [DF_SecureListLevel_SECURELISTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ListGUID]; GO +ALTER TABLE [dbo].[SecureListLevel] ADD CONSTRAINT [DF_SecureListLevel_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SecureListLevel] ADD CONSTRAINT [DF_SecureListLevel_INDEX] DEFAULT ((0)) FOR [LevelIndex]; GO +ALTER TABLE [dbo].[SecureListLevel] ADD CONSTRAINT [DF_SecureListLevel_LEVELTYPE] DEFAULT ((0)) FOR [LevelType]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SecureListMember ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SecureListMember] ( + [ListMemberGUID] uniqueidentifier NOT NULL, + [ListGUID] uniqueidentifier NOT NULL, + [ParentListMemberGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(128) NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [FullPath] nvarchar(4000) NOT NULL, + [DisplayOrder] int NOT NULL, + [OutlineLevel] int NOT NULL, + [OperatorType] int NOT NULL, + [Version] timestamp NOT NULL, + [IsIDLocked] bit NOT NULL, + [IsNameLocked] bit NOT NULL, + [IsDeleteLocked] bit NOT NULL, + [IsNewChildLocked] bit NOT NULL, + [IsParentAssociationLocked] bit NOT NULL, + [IsEditAttributeLocked] bit NOT NULL, + [ListMemberID] nvarchar(400) NOT NULL, + [SortOrderFullPath] nvarchar(4000) NOT NULL, + [FillInConfigGUID] uniqueidentifier NOT NULL, + [FillInDimensionGUID] uniqueidentifier NULL, + [DateCreated] datetime NOT NULL, + [DateModified] datetime NOT NULL, + [LootIDOverride] nvarchar(128) NULL, + [LootID] nvarchar(128) NULL, + PRIMARY KEY ([ListMemberGUID]) +); + +CREATE CLUSTERED INDEX [IX_ListMember_ListGUID] ON [dbo].[SecureListMember] ([ListGUID]); +CREATE NONCLUSTERED INDEX [IX_ListMember_ParentGUID] ON [dbo].[SecureListMember] ([ParentListMemberGUID]); +CREATE NONCLUSTERED INDEX [IX_ListMember_DisplayOrder] ON [dbo].[SecureListMember] ([DisplayOrder]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_ListMember_UniqueDK] ON [dbo].[SecureListMember] ([ListGUID], [ListMemberID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_ListMember_Unique] ON [dbo].[SecureListMember] ([ListGUID], [ParentListMemberGUID], [Name]); +GO +ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_DateModified] DEFAULT (getdate()) FOR [DateModified]; GO +ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SCListItem_PARENTLISTITEMGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentListMemberGUID]; GO +ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SCListItem_LISTITEMGUID] DEFAULT (newid()) FOR [ListMemberGUID]; GO +ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SCListItem_LISTGUID] DEFAULT (newid()) FOR [ListGUID]; GO +ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SCListItem_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SCListItem_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SCListItem_FULLPATH] DEFAULT ('') FOR [FullPath]; GO +ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SCListItem_DISPLAYORDER] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_OUTLINELEVEL] DEFAULT ((0)) FOR [OutlineLevel]; GO +ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_OPERATORTYPE] DEFAULT ((0)) FOR [OperatorType]; GO +ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_ISIDLOCKED] DEFAULT ((0)) FOR [IsIDLocked]; GO +ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_ISNAMELOCKED] DEFAULT ((0)) FOR [IsNameLocked]; GO +ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_ISDELETELOCKED] DEFAULT ((0)) FOR [IsDeleteLocked]; GO +ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_ISNEWCHILDLOCKED] DEFAULT ((0)) FOR [IsNewChildLocked]; GO +ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_ISPARENTLOCKED] DEFAULT ((0)) FOR [IsParentAssociationLocked]; GO +ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_ISEDITATTRIBUTELOCKED] DEFAULT ((0)) FOR [IsEditAttributeLocked]; GO +ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_LISTMEMBERID] DEFAULT ('') FOR [ListMemberID]; GO +ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_DISPLAYORDERFULLPATH] DEFAULT ('') FOR [SortOrderFullPath]; GO +ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_FillInDimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FillInConfigGUID]; GO +ALTER TABLE [dbo].[SecureListMember] ADD CONSTRAINT [DF_SecureListMember_DateCreated] DEFAULT (getdate()) FOR [DateCreated]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SecureListMemberValue ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SecureListMemberValue] ( + [ListMemberValueGUID] uniqueidentifier NOT NULL, + [ListMemberGUID] uniqueidentifier NOT NULL, + [ListGUID] uniqueidentifier NOT NULL, + [Type] int NOT NULL, + [ValueFloat] float NOT NULL, + [ValueText] nvarchar(1000) NOT NULL, + [ValueIndex] int NOT NULL, + [DateCreated] datetime NOT NULL, + [DateModified] datetime NOT NULL, + [Version] timestamp NOT NULL +); + +CREATE CLUSTERED INDEX [IX_ListMemberValue_ListGUID] ON [dbo].[SecureListMemberValue] ([ListGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [PK_ListMemberValue] ON [dbo].[SecureListMemberValue] ([ListMemberValueGUID]); +CREATE NONCLUSTERED INDEX [IX_ListMemberValue_ListMemberGUID] ON [dbo].[SecureListMemberValue] ([ListMemberGUID]); +CREATE NONCLUSTERED INDEX [IX_ListMemberValue_ValueIndex] ON [dbo].[SecureListMemberValue] ([ValueIndex]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_SecureListMemberValue] ON [dbo].[SecureListMemberValue] ([ListMemberGUID], [ValueIndex]); +GO +ALTER TABLE [dbo].[SecureListMemberValue] ADD CONSTRAINT [FK_SecureListMemberValue_SecureListMember] FOREIGN KEY ([ListMemberGUID]) REFERENCES [dbo].[SecureListMember] ([ListMemberGUID]); GO +ALTER TABLE [dbo].[SecureListMemberValue] ADD CONSTRAINT [DF_SCListItemValue_VALUEFLOAT] DEFAULT ((0)) FOR [ValueFloat]; GO +ALTER TABLE [dbo].[SecureListMemberValue] ADD CONSTRAINT [DF_SecureListMemberValue_DateCreated] DEFAULT (getdate()) FOR [DateCreated]; GO +ALTER TABLE [dbo].[SecureListMemberValue] ADD CONSTRAINT [DF_SecureListMemberValue_DateModified] DEFAULT (getdate()) FOR [DateModified]; GO +ALTER TABLE [dbo].[SecureListMemberValue] ADD CONSTRAINT [DF_SecureListMemberValue_INDEX] DEFAULT ((0)) FOR [ValueIndex]; GO +ALTER TABLE [dbo].[SecureListMemberValue] ADD CONSTRAINT [DF_SCListItemValue_VALUETEXT] DEFAULT ('') FOR [ValueText]; GO +ALTER TABLE [dbo].[SecureListMemberValue] ADD CONSTRAINT [DF_SCListItemValue_LISTITEMVALUEGUID] DEFAULT (newid()) FOR [ListMemberValueGUID]; GO +ALTER TABLE [dbo].[SecureListMemberValue] ADD CONSTRAINT [DF_SCListItemValue_LISTITEMGUID] DEFAULT (newid()) FOR [ListMemberGUID]; GO +ALTER TABLE [dbo].[SecureListMemberValue] ADD CONSTRAINT [DF_SCListItemValue_LISTGUID] DEFAULT (newid()) FOR [ListGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SecureListProperty ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SecureListProperty] ( + [ListPropertyGUID] uniqueidentifier NOT NULL, + [ListGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [PropertyIndex] int NOT NULL, + [PropertyType] int NOT NULL, + [Version] timestamp NOT NULL, + PRIMARY KEY ([ListPropertyGUID]) +); +GO +ALTER TABLE [dbo].[SecureListProperty] ADD CONSTRAINT [FK_SecureListProperty_SecureList] FOREIGN KEY ([ListGUID]) REFERENCES [dbo].[SecureList] ([ListGUID]); GO +ALTER TABLE [dbo].[SecureListProperty] ADD CONSTRAINT [DF_SecureListProperty_SECURELISTPROPERTYGUID] DEFAULT (newid()) FOR [ListPropertyGUID]; GO +ALTER TABLE [dbo].[SecureListProperty] ADD CONSTRAINT [DF_SecureListProperty_SECURELISTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ListGUID]; GO +ALTER TABLE [dbo].[SecureListProperty] ADD CONSTRAINT [DF_SecureListProperty_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SecureListProperty] ADD CONSTRAINT [DF_SecureListProperty_INDEX] DEFAULT ((0)) FOR [PropertyIndex]; GO +ALTER TABLE [dbo].[SecureListProperty] ADD CONSTRAINT [DF_SecureListProperty_PROPERTYTYPE] DEFAULT ((0)) FOR [PropertyType]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SecurityHistoryItem ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SecurityHistoryItem] ( + [HistoryItemGUID] uniqueidentifier NOT NULL, + [UserName] nvarchar(64) NOT NULL, + [Type] nvarchar(64) NOT NULL, + [Change] nvarchar(64) NOT NULL, + [Field1] nvarchar(64) NOT NULL, + [Field2] nvarchar(64) NOT NULL, + [BeforeValue] nvarchar(1024) NOT NULL, + [AfterValue] nvarchar(1024) NOT NULL, + [TimeStampUtc] datetime NOT NULL, + PRIMARY KEY ([HistoryItemGUID]) +); +GO +ALTER TABLE [dbo].[SecurityHistoryItem] ADD CONSTRAINT [DF__SecurityH__After__00A05511] DEFAULT ('') FOR [AfterValue]; GO +ALTER TABLE [dbo].[SecurityHistoryItem] ADD CONSTRAINT [DF__SecurityH__TimeS__52425D49] DEFAULT (getutcdate()) FOR [TimeStampUtc]; GO +ALTER TABLE [dbo].[SecurityHistoryItem] ADD CONSTRAINT [DF__SecurityH__Histo__78FF3349] DEFAULT (newid()) FOR [HistoryItemGUID]; GO +ALTER TABLE [dbo].[SecurityHistoryItem] ADD CONSTRAINT [DF__SecurityH__UserN__7AE77BBB] DEFAULT ('') FOR [UserName]; GO +ALTER TABLE [dbo].[SecurityHistoryItem] ADD CONSTRAINT [DF__SecurityHi__Type__7BDB9FF4] DEFAULT ('') FOR [Type]; GO +ALTER TABLE [dbo].[SecurityHistoryItem] ADD CONSTRAINT [DF__SecurityH__Chang__7CCFC42D] DEFAULT ('') FOR [Change]; GO +ALTER TABLE [dbo].[SecurityHistoryItem] ADD CONSTRAINT [DF__SecurityH__Field__7DC3E866] DEFAULT ('') FOR [Field1]; GO +ALTER TABLE [dbo].[SecurityHistoryItem] ADD CONSTRAINT [DF__SecurityH__Field__7EB80C9F] DEFAULT ('') FOR [Field2]; GO +ALTER TABLE [dbo].[SecurityHistoryItem] ADD CONSTRAINT [DF__SecurityH__Befor__7FAC30D8] DEFAULT ('') FOR [BeforeValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SisenseDataMart ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SisenseDataMart] ( + [SisenseDataMartGUID] uniqueidentifier NOT NULL, + [DataMartName] nvarchar(200) NOT NULL, + [StrataId] nvarchar(5) NOT NULL, + [FactTableName] nvarchar(100) NOT NULL, + [DataTableGuid] uniqueidentifier NOT NULL, + [QueryTag] nvarchar(50) NOT NULL, + [FactTablePrefix] nvarchar(100) NOT NULL, + [SisenseFactTable] nvarchar(200) NOT NULL, + [IsUsingDepartmentSecurity] bit NOT NULL, + [IsAppendedOnly] bit NOT NULL, + [WarehouseSize] nvarchar(200) NOT NULL, + [IsUsingReportingSchema] bit NOT NULL, + PRIMARY KEY ([SisenseDataMartGUID]) +); +GO +ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [FK__SisenseDa__DataT__14C51914] FOREIGN KEY ([DataTableGuid]) REFERENCES [dbo].[ScoreDataTable] ([DataTableGUID]); GO +ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__Sisen__0518C130] DEFAULT ('') FOR [SisenseFactTable]; GO +ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__Sisen__0F0C3FBE] DEFAULT (newid()) FOR [SisenseDataMartGUID]; GO +ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__DataM__100063F7] DEFAULT ('') FOR [DataMartName]; GO +ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__Strat__10F48830] DEFAULT ('') FOR [StrataId]; GO +ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__FactT__11E8AC69] DEFAULT ('') FOR [FactTableName]; GO +ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__Query__12DCD0A2] DEFAULT ('') FOR [QueryTag]; GO +ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__FactT__13D0F4DB] DEFAULT ('') FOR [FactTablePrefix]; GO +ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__Wareh__261A8D9F] DEFAULT ('REPORT_XS_WH') FOR [WarehouseSize]; GO +ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__IsApp__286CEA65] DEFAULT ((0)) FOR [IsAppendedOnly]; GO +ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__IsUsi__40103523] DEFAULT ((0)) FOR [IsUsingReportingSchema]; GO +ALTER TABLE [dbo].[SisenseDataMart] ADD CONSTRAINT [DF__SisenseDa__IsUsi__6EDF674E] DEFAULT ((0)) FOR [IsUsingDepartmentSecurity]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SnapinActionConfig ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SnapinActionConfig] ( + [SnapinActionConfigGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(50) NOT NULL, + PRIMARY KEY ([SnapinActionConfigGUID]) +); +GO +ALTER TABLE [dbo].[SnapinActionConfig] ADD CONSTRAINT [DF_SnapinActionConfig_SnapinActionGUID] DEFAULT (newid()) FOR [SnapinActionConfigGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SnapinActionItem ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SnapinActionItem] ( + [SnapinActionItemGUID] uniqueidentifier NOT NULL, + [SnapinActionConfigGUID] uniqueidentifier NOT NULL, + [SnapinGUID] uniqueidentifier NOT NULL, + [Description] nvarchar(max) NOT NULL, + [DisplayOrder] smallint NOT NULL, + [Mode] tinyint NOT NULL, + PRIMARY KEY ([SnapinActionItemGUID]) +); +GO +ALTER TABLE [dbo].[SnapinActionItem] ADD CONSTRAINT [FK_SnapinActionItem_SnapinActionConfig] FOREIGN KEY ([SnapinActionConfigGUID]) REFERENCES [dbo].[SnapinActionConfig] ([SnapinActionConfigGUID]); GO +ALTER TABLE [dbo].[SnapinActionItem] ADD CONSTRAINT [DF_Table_1_SnapinActionStripItemGUID] DEFAULT (newid()) FOR [SnapinActionItemGUID]; GO +ALTER TABLE [dbo].[SnapinActionItem] ADD CONSTRAINT [DF_SnapinActionItem_Description] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[SnapinActionItem] ADD CONSTRAINT [DF_SnapinActionItem_Mode] DEFAULT ((0)) FOR [Mode]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SnapinActionItemFramework ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SnapinActionItemFramework] ( + [SnapinActionItemGUID] uniqueidentifier NOT NULL, + [FrameworkID] tinyint NOT NULL +); +GO +ALTER TABLE [dbo].[SnapinActionItemFramework] ADD CONSTRAINT [FK_SnapinActionItemFramework_SnapinActionItem] FOREIGN KEY ([SnapinActionItemGUID]) REFERENCES [dbo].[SnapinActionItem] ([SnapinActionItemGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SnapinActionItemTag ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SnapinActionItemTag] ( + [SnapinActionItemGUID] uniqueidentifier NOT NULL, + [TagGUID] uniqueidentifier NOT NULL +); +GO +ALTER TABLE [dbo].[SnapinActionItemTag] ADD CONSTRAINT [FK_SnapinActionItemTag_SnapinActionItem] FOREIGN KEY ([SnapinActionItemGUID]) REFERENCES [dbo].[SnapinActionItem] ([SnapinActionItemGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.StandardCodesDimensionUpgradeRequest ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[StandardCodesDimensionUpgradeRequest] ( + [StandardCodesDimensionUpgradeRequestGUID] uniqueidentifier NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + [StandardCodesDimensionName] nvarchar(400) NOT NULL, + PRIMARY KEY ([StandardCodesDimensionUpgradeRequestGUID]) +); +GO +ALTER TABLE [dbo].[StandardCodesDimensionUpgradeRequest] ADD CONSTRAINT [DF__StandardC__Dimen__1523434F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO +ALTER TABLE [dbo].[StandardCodesDimensionUpgradeRequest] ADD CONSTRAINT [DF__StandardC__Stand__142F1F16] DEFAULT (newid()) FOR [StandardCodesDimensionUpgradeRequestGUID]; GO +ALTER TABLE [dbo].[StandardCodesDimensionUpgradeRequest] ADD CONSTRAINT [DF__StandardC__Stand__16176788] DEFAULT ('') FOR [StandardCodesDimensionName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.StandardCodesUpdateRulesRequest ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[StandardCodesUpdateRulesRequest] ( + [StandardCodesDimensionUpgradeRequestGUID] uniqueidentifier NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([StandardCodesDimensionUpgradeRequestGUID]) +); +GO +ALTER TABLE [dbo].[StandardCodesUpdateRulesRequest] ADD CONSTRAINT [DF__StandardC__Dimen__76A9DAF1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO +ALTER TABLE [dbo].[StandardCodesUpdateRulesRequest] ADD CONSTRAINT [DF__StandardC__Stand__75B5B6B8] DEFAULT (newid()) FOR [StandardCodesDimensionUpgradeRequestGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.StandardDefinitionMapping ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[StandardDefinitionMapping] ( + [MappingId] int NOT NULL, + [StandardDefinitionGUID] uniqueidentifier NOT NULL, + [StandardDefinitionType] nvarchar(200) NOT NULL, + [MappingMemberValue] nvarchar(max) NULL, + PRIMARY KEY ([MappingId]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.Survey ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[Survey] ( + [SurveyGUID] uniqueidentifier NOT NULL, + [FriendlyName] nvarchar(128) NOT NULL, + [Description] varchar(400) NOT NULL, + PRIMARY KEY ([SurveyGUID]) +); +GO +ALTER TABLE [dbo].[Survey] ADD CONSTRAINT [DF_Survey_SurveyGUID] DEFAULT (newid()) FOR [SurveyGUID]; GO +ALTER TABLE [dbo].[Survey] ADD CONSTRAINT [DF_Survey_FriendlyName] DEFAULT ('') FOR [FriendlyName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SurveyItem ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SurveyItem] ( + [SurveyItemGUID] uniqueidentifier NOT NULL, + [SurveyGUID] uniqueidentifier NOT NULL, + [FriendlyName] nvarchar(128) NOT NULL, + [SurveyItemType] smallint NOT NULL, + [ContextXML] varchar(max) NOT NULL, + [SurveyText] nvarchar(400) NOT NULL, + [Footer] nvarchar(400) NOT NULL, + [DisplayOrder] smallint NOT NULL, + [IsRequired] bit NOT NULL, + PRIMARY KEY ([SurveyItemGUID]) +); +GO +ALTER TABLE [dbo].[SurveyItem] ADD CONSTRAINT [DF_SurveyItem_Isrequired] DEFAULT ((0)) FOR [IsRequired]; GO +ALTER TABLE [dbo].[SurveyItem] ADD CONSTRAINT [DF_SurveyQuestion_SurveyQuestionGUID] DEFAULT (newid()) FOR [SurveyItemGUID]; GO +ALTER TABLE [dbo].[SurveyItem] ADD CONSTRAINT [DF_SurveyItem_SurveyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SurveyGUID]; GO +ALTER TABLE [dbo].[SurveyItem] ADD CONSTRAINT [DF_SurveyQuestion_FriendlyName] DEFAULT ('') FOR [FriendlyName]; GO +ALTER TABLE [dbo].[SurveyItem] ADD CONSTRAINT [DF_SurveyQuestion_SurveyQuestionType] DEFAULT ((0)) FOR [SurveyItemType]; GO +ALTER TABLE [dbo].[SurveyItem] ADD CONSTRAINT [DF_SurveyQuestion_ContextXML] DEFAULT ('') FOR [ContextXML]; GO +ALTER TABLE [dbo].[SurveyItem] ADD CONSTRAINT [DF_SurveyQuestion_QuestionText] DEFAULT ('') FOR [SurveyText]; GO +ALTER TABLE [dbo].[SurveyItem] ADD CONSTRAINT [DF_SurveyItem_DisplayOrder] DEFAULT ((-1)) FOR [DisplayOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SurveyResults ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SurveyResults] ( + [DatabaseGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [UserName] varchar(100) NOT NULL, + [DepartmentID] int NOT NULL, + [FiscalYear] int NOT NULL, + [ResultSelection] smallint NOT NULL, + [ResultText] varchar(250) NULL, + [ResearchSignup] bit NOT NULL, + [SubmitDate] datetime NULL, + PRIMARY KEY ([DatabaseGUID], [UserGUID], [FiscalYear]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SyncLog ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SyncLog] ( + [SyncLogGUID] uniqueidentifier NOT NULL, + [SyncDate] datetime NOT NULL, + [SyncSource] nvarchar(400) NOT NULL, + [Message] nvarchar(max) NOT NULL, + [VERSION] timestamp NOT NULL, + PRIMARY KEY ([SyncLogGUID]) +); +GO +ALTER TABLE [dbo].[SyncLog] ADD CONSTRAINT [DF_SyncLog_SyncLogGUID] DEFAULT (newid()) FOR [SyncLogGUID]; GO +ALTER TABLE [dbo].[SyncLog] ADD CONSTRAINT [DF_SyncLog_SyncDate] DEFAULT (getdate()) FOR [SyncDate]; GO +ALTER TABLE [dbo].[SyncLog] ADD CONSTRAINT [DF_SyncLog_SyncSource] DEFAULT ('') FOR [SyncSource]; GO +ALTER TABLE [dbo].[SyncLog] ADD CONSTRAINT [DF_SyncLog_Message] DEFAULT ('') FOR [Message]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SysMessage ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SysMessage] ( + [MessageID] int NOT NULL, + [SeverityVal] tinyint NOT NULL, + [MessageVal] varchar(max) NOT NULL, + [DiscriminatorVal] int NOT NULL, + [IdentifierID] uniqueidentifier NOT NULL, + [IsDeleted] bit NOT NULL, + [Tag] nvarchar(100) NOT NULL, + [TimeStampUtc] datetime NOT NULL, + PRIMARY KEY ([MessageID]) +); + +CREATE NONCLUSTERED INDEX [NC_SysMessage_IdentifierID] ON [dbo].[SysMessage] ([IdentifierID]); +GO +ALTER TABLE [dbo].[SysMessage] ADD CONSTRAINT [DF__SysMessage__Tag__098D38CB] DEFAULT ('') FOR [Tag]; GO +ALTER TABLE [dbo].[SysMessage] ADD CONSTRAINT [DF__SysMessag__Sever__0A6DB34F] DEFAULT ((1)) FOR [SeverityVal]; GO +ALTER TABLE [dbo].[SysMessage] ADD CONSTRAINT [DF__SysMessag__Messa__0B61D788] DEFAULT ('') FOR [MessageVal]; GO +ALTER TABLE [dbo].[SysMessage] ADD CONSTRAINT [DF__SysMessag__Discr__0C55FBC1] DEFAULT ((0)) FOR [DiscriminatorVal]; GO +ALTER TABLE [dbo].[SysMessage] ADD CONSTRAINT [DF__SysMessag__IsDel__0E3E4433] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [dbo].[SysMessage] ADD CONSTRAINT [DF__SysMessag__TimeS__420BF580] DEFAULT (getutcdate()) FOR [TimeStampUtc]; GO +ALTER TABLE [dbo].[SysMessage] ADD CONSTRAINT [DF__SysMessag__Ident__0D4A1FFA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [IdentifierID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SystemCenterCategory ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SystemCenterCategory] ( + [CategoryGUID] uniqueidentifier NOT NULL, + [ModuleGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(200) NOT NULL, + [SortOrder] int NOT NULL, + [IsMaintenanceMode] bit NOT NULL, + [NameHtml] nvarchar(200) NOT NULL, + PRIMARY KEY ([CategoryGUID]) +); +GO +ALTER TABLE [dbo].[SystemCenterCategory] ADD CONSTRAINT [FK_SystemCenterCategory_SystemCenterModule] FOREIGN KEY ([ModuleGUID]) REFERENCES [dbo].[SystemCenterModule] ([ModuleGUID]); GO +ALTER TABLE [dbo].[SystemCenterCategory] ADD CONSTRAINT [DF__SystemCen__Categ__401B89DE] DEFAULT (newid()) FOR [CategoryGUID]; GO +ALTER TABLE [dbo].[SystemCenterCategory] ADD CONSTRAINT [DF__SystemCent__Name__410FAE17] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SystemCenterCategory] ADD CONSTRAINT [DF__SystemCen__SortO__4203D250] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [dbo].[SystemCenterCategory] ADD CONSTRAINT [DF__SystemCen__IsMai__42F7F689] DEFAULT ((0)) FOR [IsMaintenanceMode]; GO +ALTER TABLE [dbo].[SystemCenterCategory] ADD CONSTRAINT [DF__SystemCen__NameH__6C02FAA3] DEFAULT ('') FOR [NameHtml]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SystemCenterImportHistory ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SystemCenterImportHistory] ( + [HistoryGUID] uniqueidentifier NOT NULL, + [StepGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [UserName] nvarchar(200) NOT NULL, + [DateTimeStamp] datetime NOT NULL, + [TempFilePath] nvarchar(4000) NOT NULL, + PRIMARY KEY ([HistoryGUID]) +); +GO +ALTER TABLE [dbo].[SystemCenterImportHistory] ADD CONSTRAINT [FK_SystemCenterImportHistory_SystemCenterStep] FOREIGN KEY ([StepGUID]) REFERENCES [dbo].[SystemCenterStep] ([StepGUID]); GO +ALTER TABLE [dbo].[SystemCenterImportHistory] ADD CONSTRAINT [DF__SystemCen__Histo__013B7ADC] DEFAULT (newid()) FOR [HistoryGUID]; GO +ALTER TABLE [dbo].[SystemCenterImportHistory] ADD CONSTRAINT [DF__SystemCen__UserN__0323C34E] DEFAULT ('') FOR [UserName]; GO +ALTER TABLE [dbo].[SystemCenterImportHistory] ADD CONSTRAINT [DF__SystemCen__DateT__0417E787] DEFAULT (getdate()) FOR [DateTimeStamp]; GO +ALTER TABLE [dbo].[SystemCenterImportHistory] ADD CONSTRAINT [DF__SystemCen__TempF__050C0BC0] DEFAULT ('') FOR [TempFilePath]; GO +ALTER TABLE [dbo].[SystemCenterImportHistory] ADD CONSTRAINT [DF__SystemCen__UserG__022F9F15] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SystemCenterModule ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SystemCenterModule] ( + [ModuleGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(200) NOT NULL, + [SolutionGUID] uniqueidentifier NOT NULL, + [SortOrder] int NOT NULL, + [IsLicensed] bit NOT NULL, + [IsSetupComplete] bit NOT NULL, + [IsUsed_DEPRECATED] bit NOT NULL, + [NameHtml] nvarchar(200) NOT NULL, + PRIMARY KEY ([ModuleGUID]) +); +GO +ALTER TABLE [dbo].[SystemCenterModule] ADD CONSTRAINT [DF__SystemCen__Modul__396E8C4F] DEFAULT (newid()) FOR [ModuleGUID]; GO +ALTER TABLE [dbo].[SystemCenterModule] ADD CONSTRAINT [DF__SystemCent__Name__3A62B088] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SystemCenterModule] ADD CONSTRAINT [DF__SystemCen__SortO__3B56D4C1] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [dbo].[SystemCenterModule] ADD CONSTRAINT [DF__SystemCen__IsLic__3C4AF8FA] DEFAULT ((0)) FOR [IsLicensed]; GO +ALTER TABLE [dbo].[SystemCenterModule] ADD CONSTRAINT [DF__SystemCen__IsSet__3D3F1D33] DEFAULT ((0)) FOR [IsSetupComplete]; GO +ALTER TABLE [dbo].[SystemCenterModule] ADD CONSTRAINT [DF__SystemCen__NameH__6CF71EDC] DEFAULT ('') FOR [NameHtml]; GO +ALTER TABLE [dbo].[SystemCenterModule] ADD CONSTRAINT [DF__SystemCen__IsUse__708B4DBD] DEFAULT ((1)) FOR [IsUsed_DEPRECATED]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SystemCenterSection ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SystemCenterSection] ( + [SectionGUID] uniqueidentifier NOT NULL, + [SortOrder] int NOT NULL, + [CategoryGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(200) NOT NULL, + [LastUserGUID] uniqueidentifier NULL, + [Date] datetime NOT NULL, + [SectionState] tinyint NOT NULL, + [ViewModelClassName] nvarchar(400) NOT NULL, + [SessionClassName] nvarchar(100) NOT NULL, + [GlobalID] nvarchar(100) NOT NULL, + [Info] nvarchar(max) NOT NULL, + [LastUserNameFull] nvarchar(200) NOT NULL, + [NameHtml] nvarchar(200) NOT NULL, + PRIMARY KEY ([SectionGUID]) +); +GO +ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [FK_SystemCenterSection_SystemCenterCategory] FOREIGN KEY ([CategoryGUID]) REFERENCES [dbo].[SystemCenterCategory] ([CategoryGUID]); GO +ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCen__Secti__46C8876D] DEFAULT (newid()) FOR [SectionGUID]; GO +ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCen__SortO__47BCABA6] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCent__Name__48B0CFDF] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCen__LastU__49A4F418] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LastUserGUID]; GO +ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCent__Date__4A991851] DEFAULT (CONVERT([datetime],(0))) FOR [Date]; GO +ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCen__Secti__4B8D3C8A] DEFAULT ((0)) FOR [SectionState]; GO +ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCen__ViewM__4C8160C3] DEFAULT ('') FOR [ViewModelClassName]; GO +ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCen__Sessi__4D7584FC] DEFAULT ('') FOR [SessionClassName]; GO +ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCen__Globa__4E69A935] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCent__Info__4F5DCD6E] DEFAULT ('') FOR [Info]; GO +ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCen__NameH__6B0ED66A] DEFAULT ('') FOR [NameHtml]; GO +ALTER TABLE [dbo].[SystemCenterSection] ADD CONSTRAINT [DF__SystemCen__LastU__717F71F6] DEFAULT ('') FOR [LastUserNameFull]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SystemCenterSolution ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SystemCenterSolution] ( + [SolutionGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(200) NOT NULL, + [SortOrder] int NOT NULL, + [Abbreviation] nvarchar(10) NOT NULL, + [IsStatusDisabled] bit NOT NULL, + PRIMARY KEY ([SolutionGUID]) +); +GO +ALTER TABLE [dbo].[SystemCenterSolution] ADD CONSTRAINT [DF__SystemCen__IsSta__0E8826FD] DEFAULT ((0)) FOR [IsStatusDisabled]; GO +ALTER TABLE [dbo].[SystemCenterSolution] ADD CONSTRAINT [DF__SystemCen__Solut__34A9D732] DEFAULT (newid()) FOR [SolutionGUID]; GO +ALTER TABLE [dbo].[SystemCenterSolution] ADD CONSTRAINT [DF__SystemCent__Name__359DFB6B] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SystemCenterSolution] ADD CONSTRAINT [DF__SystemCen__SortO__36921FA4] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [dbo].[SystemCenterSolution] ADD CONSTRAINT [DF__SystemCen__Abbre__507383E6] DEFAULT ('') FOR [Abbreviation]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SystemCenterStep ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SystemCenterStep] ( + [StepGUID] uniqueidentifier NOT NULL, + [SortOrder] int NOT NULL, + [SectionGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(200) NOT NULL, + [PropertyXML] xml(max) NOT NULL, + [Url] nvarchar(400) NOT NULL, + [GlobalID] nvarchar(100) NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [HelpID] nvarchar(200) NOT NULL, + [HelpFileName] nvarchar(200) NOT NULL, + PRIMARY KEY ([StepGUID]) +); +GO +ALTER TABLE [dbo].[SystemCenterStep] ADD CONSTRAINT [FK_SystemCenterStep_SystemCenterSection] FOREIGN KEY ([SectionGUID]) REFERENCES [dbo].[SystemCenterSection] ([SectionGUID]); GO +ALTER TABLE [dbo].[SystemCenterStep] ADD CONSTRAINT [DF__SystemCen__HelpI__1223ADB7] DEFAULT ('') FOR [HelpID]; GO +ALTER TABLE [dbo].[SystemCenterStep] ADD CONSTRAINT [DF__SystemCen__HelpF__4485DBA9] DEFAULT ('') FOR [HelpFileName]; GO +ALTER TABLE [dbo].[SystemCenterStep] ADD CONSTRAINT [DF__SystemCen__StepG__532E5E52] DEFAULT (newid()) FOR [StepGUID]; GO +ALTER TABLE [dbo].[SystemCenterStep] ADD CONSTRAINT [DF__SystemCen__SortO__5422828B] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [dbo].[SystemCenterStep] ADD CONSTRAINT [DF__SystemCent__Name__5516A6C4] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SystemCenterStep] ADD CONSTRAINT [DF__SystemCen__Prope__560ACAFD] DEFAULT ('') FOR [PropertyXML]; GO +ALTER TABLE [dbo].[SystemCenterStep] ADD CONSTRAINT [DF__SystemCente__Url__56FEEF36] DEFAULT ('') FOR [Url]; GO +ALTER TABLE [dbo].[SystemCenterStep] ADD CONSTRAINT [DF__SystemCen__Globa__57F3136F] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [dbo].[SystemCenterStep] ADD CONSTRAINT [DF__SystemCen__Descr__58E737A8] DEFAULT ('') FOR [Description]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.SystemSection ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[SystemSection] ( + [SYSTEMSECTIONGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [ID] nvarchar(64) NOT NULL, + [ParentGUID] uniqueidentifier NOT NULL, + [FullPath] nvarchar(4000) NOT NULL, + [ImageName] nvarchar(64) NOT NULL, + [LootID] varchar(36) NULL, + [IsCrossBrowser] bit NOT NULL, + PRIMARY KEY ([SYSTEMSECTIONGUID]) +); + +CREATE CLUSTERED INDEX [IX_SystemSection] ON [dbo].[SystemSection] ([ID]); +GO +ALTER TABLE [dbo].[SystemSection] ADD CONSTRAINT [DF_SystemSection_IsCrossBrowser] DEFAULT ((1)) FOR [IsCrossBrowser]; GO +ALTER TABLE [dbo].[SystemSection] ADD CONSTRAINT [DF_SystemSection_SYSTEMSECTIONGUID] DEFAULT (newid()) FOR [SYSTEMSECTIONGUID]; GO +ALTER TABLE [dbo].[SystemSection] ADD CONSTRAINT [DF_SystemSection_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[SystemSection] ADD CONSTRAINT [DF_SystemSection_ID] DEFAULT ('') FOR [ID]; GO +ALTER TABLE [dbo].[SystemSection] ADD CONSTRAINT [DF_SystemSection_PARENTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentGUID]; GO +ALTER TABLE [dbo].[SystemSection] ADD CONSTRAINT [DF_SystemSection_FULLPATH] DEFAULT ('') FOR [FullPath]; GO +ALTER TABLE [dbo].[SystemSection] ADD CONSTRAINT [DF_SystemSection_IMAGENAME] DEFAULT ('') FOR [ImageName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.TEDisabledDatabase ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[TEDisabledDatabase] ( + [DisabledDBConnectionGUID] uniqueidentifier NOT NULL, + [Comment] nvarchar(max) NOT NULL, + PRIMARY KEY ([DisabledDBConnectionGUID]) +); +GO +ALTER TABLE [dbo].[TEDisabledDatabase] ADD CONSTRAINT [DF_TEDisabledDatabase_DBCONNECTIONGUID] DEFAULT (newid()) FOR [DisabledDBConnectionGUID]; GO +ALTER TABLE [dbo].[TEDisabledDatabase] ADD CONSTRAINT [DF_TEDisabledDatabase_COMMENT] DEFAULT ('No comment') FOR [Comment]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.TEScheduledReminder ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[TEScheduledReminder] ( + [ScheduledTaskReminderGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [RepeatType] int NOT NULL, + [RepeatFrequency] int NOT NULL, + [DayOfWeek] int NOT NULL, + [DayOfMonth] int NOT NULL, + [StartDate] datetime NOT NULL, + [EndDate] datetime NOT NULL, + [HasEndDate] bit NOT NULL, + [IsDisabled] bit NOT NULL, + [HasDisabledExpirationDate] bit NOT NULL, + [DisabledExpirationDate] datetime NOT NULL, + [TaskDuration] int NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + [LastSubmittedDateUtc] datetime NOT NULL, + [TimeZoneId] nvarchar(50) NOT NULL, + [StartTime] time NOT NULL, + PRIMARY KEY ([ScheduledTaskReminderGUID]) +); +GO +ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__DateC__4E71CC65] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__LastS__4F65F09E] DEFAULT (getutcdate()) FOR [LastSubmittedDateUtc]; GO +ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__TimeZ__505A14D7] DEFAULT ('Central Standard Time') FOR [TimeZoneId]; GO +ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__Start__514E3910] DEFAULT ('00:00:00') FOR [StartTime]; GO +ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__Sched__60D1D8A6] DEFAULT (newid()) FOR [ScheduledTaskReminderGUID]; GO +ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedule__Name__61C5FCDF] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__Repea__63AE4551] DEFAULT ((0)) FOR [RepeatType]; GO +ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__Repea__64A2698A] DEFAULT ((0)) FOR [RepeatFrequency]; GO +ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__DayOf__65968DC3] DEFAULT ((0)) FOR [DayOfWeek]; GO +ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__DayOf__668AB1FC] DEFAULT ((0)) FOR [DayOfMonth]; GO +ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__Start__6872FA6E] DEFAULT ('1/1/1900') FOR [StartDate]; GO +ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__EndDa__69671EA7] DEFAULT ('1/1/1900') FOR [EndDate]; GO +ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__HasEn__6A5B42E0] DEFAULT ((1)) FOR [HasEndDate]; GO +ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__IsDis__6C438B52] DEFAULT ((0)) FOR [IsDisabled]; GO +ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__HasDi__6D37AF8B] DEFAULT ((0)) FOR [HasDisabledExpirationDate]; GO +ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__Disab__6E2BD3C4] DEFAULT ('1/1/1900') FOR [DisabledExpirationDate]; GO +ALTER TABLE [dbo].[TEScheduledReminder] ADD CONSTRAINT [DF__TESchedul__TaskD__6F1FF7FD] DEFAULT ((0)) FOR [TaskDuration]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.TEScheduledTask ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[TEScheduledTask] ( + [ScheduledTaskGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Description] nvarchar(450) NOT NULL, + [RepeatType] int NOT NULL, + [RepeatFrequency] int NOT NULL, + [DayOfWeek] int NOT NULL, + [DayOfMonth] int NOT NULL, + [StartDate] datetime NOT NULL, + [EndDate] datetime NOT NULL, + [HasEndDate] bit NOT NULL, + [SetupXML] nvarchar(max) NOT NULL, + [AssemblyQualifiedName] nvarchar(450) NOT NULL, + [HasRun] bit NOT NULL, + [IsDisabled] bit NOT NULL, + [HasDisabledExpirationDate] bit NOT NULL, + [DisabledExpirationDate] datetime NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + [LastRunDateUtc] datetime NOT NULL, + [LastSubmittedDateUtc] datetime NOT NULL, + [StartTime] time NOT NULL, + [TimeZoneId] nvarchar(50) NOT NULL, + PRIMARY KEY ([ScheduledTaskGUID]) +); +GO +ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_REPEATFREQUENCY] DEFAULT ((0)) FOR [RepeatFrequency]; GO +ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_DAYOFWEEK] DEFAULT ((0)) FOR [DayOfWeek]; GO +ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_DAYOFMONTH] DEFAULT ((0)) FOR [DayOfMonth]; GO +ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_STARTDATE] DEFAULT ('1/1/1900') FOR [StartDate]; GO +ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_ENDDATE] DEFAULT ('1/1/1900') FOR [EndDate]; GO +ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_TEScheduledTask_HASENDDATE] DEFAULT ((1)) FOR [HasEndDate]; GO +ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_SETUPXML] DEFAULT ('') FOR [SetupXML]; GO +ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_CLASSFULLNAME] DEFAULT ('') FOR [AssemblyQualifiedName]; GO +ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_TEScheduledTask_HASRUN] DEFAULT ((0)) FOR [HasRun]; GO +ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_TEScheduledTask_HasDisabledExpirationDate] DEFAULT ((0)) FOR [HasDisabledExpirationDate]; GO +ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_TEScheduledTask_DisabledExpirationDate] DEFAULT ('1/1/1900') FOR [DisabledExpirationDate]; GO +ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF__TESchedul__DateC__49AD1748] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF__TESchedul__LastR__4AA13B81] DEFAULT (getutcdate()) FOR [LastRunDateUtc]; GO +ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF__TESchedul__LastS__4B955FBA] DEFAULT (getutcdate()) FOR [LastSubmittedDateUtc]; GO +ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF__TESchedul__Start__4C8983F3] DEFAULT ('00:00:00') FOR [StartTime]; GO +ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF__TESchedul__TimeZ__4D7DA82C] DEFAULT ('Central Standard Time') FOR [TimeZoneId]; GO +ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_TEScheduledTask_IsDisabled] DEFAULT ((0)) FOR [IsDisabled]; GO +ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_SCHEDULEEVENTGUID] DEFAULT (newid()) FOR [ScheduledTaskGUID]; GO +ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[TEScheduledTask] ADD CONSTRAINT [DF_ScheduleEvent_REPEATTYPE] DEFAULT ((0)) FOR [RepeatType]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.TETask ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[TETask] ( + [TaskID] int NOT NULL, + [TaskGUID] uniqueidentifier NOT NULL, + [Name] varchar(450) NOT NULL, + [Status] int NOT NULL, + [ContextXML] varchar(max) NOT NULL, + [CreationTime] datetime NOT NULL, + [StartTime] datetime NOT NULL, + [NextRunTime] datetime NOT NULL, + [LastRunTime] datetime NOT NULL, + [Priority] int NOT NULL, + [DBConnectionGUID] uniqueidentifier NOT NULL, + [AssemblyQualifiedName] varchar(1024) NOT NULL, + [ISCollapsible] bit NOT NULL, + [CollapsibleID] nvarchar(max) NOT NULL, + [RetryCount] int NOT NULL, + [TokenGUID] uniqueidentifier NOT NULL, + [FromScheduledTaskGUID] uniqueidentifier NOT NULL, + [AssemblyKey] varchar(64) NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [TaskSource] varchar(450) NULL, + [WorkerID] uniqueidentifier NOT NULL, + [GroupingID] nvarchar(100) NOT NULL, + [GroupingIndex] smallint NOT NULL, + [UserName] nvarchar(100) NOT NULL, + PRIMARY KEY ([TaskGUID], [Status], [Priority], [AssemblyKey]) +); + +CREATE NONCLUSTERED INDEX [NCNU_Name] ON [dbo].[TETask] ([Name]); +CREATE NONCLUSTERED INDEX [OrderBy] ON [dbo].[TETask] ([Priority], [CreationTime]); +GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_TASKGUID] DEFAULT (newid()) FOR [TaskGUID]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_STATUS] DEFAULT ((0)) FOR [Status]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_CONTEXTXML] DEFAULT ('') FOR [ContextXML]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_CREATIONTIME] DEFAULT (getdate()) FOR [CreationTime]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_STARTTIME] DEFAULT ('1/1/1900') FOR [StartTime]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_LASTRUNTIME] DEFAULT ('1/1/1900') FOR [LastRunTime]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_PRIORITY] DEFAULT ((0)) FOR [Priority]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_DBCONNECTIONGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DBConnectionGUID]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_ASSEMBLYQUALIFIEDNAME] DEFAULT ('') FOR [AssemblyQualifiedName]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_ISCOLLAPSABLE] DEFAULT ((0)) FOR [ISCollapsible]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_COLLAPSABLEID] DEFAULT ('') FOR [CollapsibleID]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_RETRIES] DEFAULT ((0)) FOR [RetryCount]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_TOKENGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TokenGUID]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_FROMSCHEDULEDTASKGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FromScheduledTaskGUID]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_ASSEMBLYKEY] DEFAULT ('') FOR [AssemblyKey]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_TaskSource] DEFAULT ('') FOR [TaskSource]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_GroupingID] DEFAULT ('') FOR [GroupingID]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_GroupingIndex] DEFAULT ((0)) FOR [GroupingIndex]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_NextRunTime] DEFAULT (getdate()) FOR [NextRunTime]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_UserName] DEFAULT ('') FOR [UserName]; GO +ALTER TABLE [dbo].[TETask] ADD CONSTRAINT [DF_TETask_WorkerID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkerID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.TETaskHistory ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[TETaskHistory] ( + [TaskID] int NULL, + [TaskGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(450) NOT NULL, + [Status] int NOT NULL, + [ContextXML] xml(max) NOT NULL, + [CreationTime] datetime NOT NULL, + [StartTime] datetime NOT NULL, + [LastRunTime] datetime NOT NULL, + [Priority] int NOT NULL, + [DBConnectionGUID] uniqueidentifier NOT NULL, + [AssemblyQualifiedName] nvarchar(1024) NOT NULL, + [IsCollapsible] bit NOT NULL, + [CollapsibleID] nvarchar(max) NOT NULL, + [RetryCount] int NOT NULL, + [TokenGUID] uniqueidentifier NOT NULL, + [FromScheduledTaskGUID] uniqueidentifier NOT NULL, + [AssemblyKey] nvarchar(1024) NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [NextRunTime] datetime NOT NULL, + [DEQUEUETIME] datetime NULL, + [TASKSOURCE] varchar(450) NULL, + [WORKERNAME] varchar(1024) NULL, + [ERRORLOGGUID] uniqueidentifier NULL, + [TASKENGINEVERSION] varchar(450) NULL, + [TASKHISTORYID] int NOT NULL, + [WORKERID] uniqueidentifier NOT NULL, + [GroupingID] nvarchar(100) NOT NULL, + [GroupingIndex] smallint NOT NULL, + [UserName] nvarchar(100) NOT NULL, + PRIMARY KEY ([TASKHISTORYID]) +); + +CREATE NONCLUSTERED INDEX [IX_NC_TASKGUID] ON [dbo].[TETaskHistory] ([TaskGUID]); +GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_GroupingID] DEFAULT ('') FOR [GroupingID]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_GroupingIndex] DEFAULT ((0)) FOR [GroupingIndex]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_TASKGUID] DEFAULT (newid()) FOR [TaskGUID]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_WORKERID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WORKERID]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_STATUS] DEFAULT ((0)) FOR [Status]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_CONTEXTXML] DEFAULT ('') FOR [ContextXML]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_CREATIONTIME] DEFAULT (getdate()) FOR [CreationTime]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_STARTTIME] DEFAULT ('1/1/1900') FOR [StartTime]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_LASTRUNTIME] DEFAULT ('1/1/1900') FOR [LastRunTime]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_PRIORITY] DEFAULT ((0)) FOR [Priority]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_DBCONNECTIONGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DBConnectionGUID]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_ASSEMBLYQUALIFIEDNAME] DEFAULT ('') FOR [AssemblyQualifiedName]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_ISCOLLAPSABLE] DEFAULT ((0)) FOR [IsCollapsible]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_COLLAPSABLEID] DEFAULT ('') FOR [CollapsibleID]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_RETRIES] DEFAULT ((0)) FOR [RetryCount]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_TOKENGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TokenGUID]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_FROMSCHEDULEDTASKGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FromScheduledTaskGUID]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_ASSEMBLYKEY] DEFAULT ('') FOR [AssemblyKey]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_USERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_NextRunTime] DEFAULT ('1/1/1900') FOR [NextRunTime]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_DEQUEUETIME] DEFAULT (getdate()) FOR [DEQUEUETIME]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_TASKSOURCE] DEFAULT ('') FOR [TASKSOURCE]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_WORKERNAME] DEFAULT ('') FOR [WORKERNAME]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_UserName] DEFAULT ('') FOR [UserName]; GO +ALTER TABLE [dbo].[TETaskHistory] ADD CONSTRAINT [DF_TETaskHistory_TASKENGINEVERSION] DEFAULT ('') FOR [TASKENGINEVERSION]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.TableDeleteVersion ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[TableDeleteVersion] ( + [TableName] nvarchar(64) NOT NULL, + [DeleteVersion] timestamp NOT NULL +); +GO +ALTER TABLE [dbo].[TableDeleteVersion] ADD CONSTRAINT [DF_Table_1_TableName] DEFAULT ('') FOR [TableName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.Tag ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[Tag] ( + [TagGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(400) NOT NULL, + PRIMARY KEY ([TagGUID]) +); +GO +ALTER TABLE [dbo].[Tag] ADD CONSTRAINT [DF_Tag_TagGUID] DEFAULT (newid()) FOR [TagGUID]; GO +ALTER TABLE [dbo].[Tag] ADD CONSTRAINT [DF_Tag_Tag] DEFAULT ('') FOR [Name]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.TaskProgressStatus ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[TaskProgressStatus] ( + [RowID] bigint NOT NULL, + [TaskGUID] uniqueidentifier NOT NULL, + [DataXML] xml(max) NOT NULL, + [StartTime] datetime NOT NULL, + [TaskStatus] nvarchar(100) NOT NULL, + [GlobalID] nvarchar(100) NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [dbo].[TaskProgressStatus] ADD CONSTRAINT [DF_TaskProgressStatus_TaskGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TaskGUID]; GO +ALTER TABLE [dbo].[TaskProgressStatus] ADD CONSTRAINT [DF_TaskProgressStatus_MetaInfoXML] DEFAULT ('') FOR [DataXML]; GO +ALTER TABLE [dbo].[TaskProgressStatus] ADD CONSTRAINT [DF_TaskProgressStatus_StartTime] DEFAULT (getdate()) FOR [StartTime]; GO +ALTER TABLE [dbo].[TaskProgressStatus] ADD CONSTRAINT [DF_TaskProgressStatus_TaskStatus] DEFAULT ('') FOR [TaskStatus]; GO +ALTER TABLE [dbo].[TaskProgressStatus] ADD CONSTRAINT [DF_TaskProgressStatus_GlobalID] DEFAULT ('') FOR [GlobalID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.TemplatePublishRequest ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[TemplatePublishRequest] ( + [RequestGUID] uniqueidentifier NOT NULL, + [IssuedAt] datetime NOT NULL, + [FrameworkID] int NOT NULL, + [ExcludedTemplateGUIDs] nvarchar(max) NOT NULL, + [PreSQL] nvarchar(max) NOT NULL, + PRIMARY KEY ([RequestGUID]) +); +GO +ALTER TABLE [dbo].[TemplatePublishRequest] ADD CONSTRAINT [DF_TemplatePublishRequest_RequestGUID] DEFAULT (newid()) FOR [RequestGUID]; GO +ALTER TABLE [dbo].[TemplatePublishRequest] ADD CONSTRAINT [DF_TemplatePublishRequest_IssuedAt] DEFAULT (getdate()) FOR [IssuedAt]; GO +ALTER TABLE [dbo].[TemplatePublishRequest] ADD CONSTRAINT [DF__TemplateP__Frame__4DA5CB1C] DEFAULT ((0)) FOR [FrameworkID]; GO +ALTER TABLE [dbo].[TemplatePublishRequest] ADD CONSTRAINT [DF__TemplateP__Exclu__58E43C16] DEFAULT ('') FOR [ExcludedTemplateGUIDs]; GO +ALTER TABLE [dbo].[TemplatePublishRequest] ADD CONSTRAINT [DF__TemplateP__PreSQ__78DB70CF] DEFAULT ('') FOR [PreSQL]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.TemplatePublishRequestData ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[TemplatePublishRequestData] ( + [FileGUID] uniqueidentifier NOT NULL, + [RequestGUID] uniqueidentifier NOT NULL, + [ModelTemplateGUID] uniqueidentifier NOT NULL, + [LastModified] datetime NOT NULL, + [Data] varbinary(max) NOT NULL, + PRIMARY KEY ([FileGUID]) +); +GO +ALTER TABLE [dbo].[TemplatePublishRequestData] ADD CONSTRAINT [FK_TemplatePublishRequestData_TemplatePublishRequest] FOREIGN KEY ([RequestGUID]) REFERENCES [dbo].[TemplatePublishRequest] ([RequestGUID]); GO +ALTER TABLE [dbo].[TemplatePublishRequestData] ADD CONSTRAINT [DF_TemplatePublishRequestData_RequestGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [RequestGUID]; GO +ALTER TABLE [dbo].[TemplatePublishRequestData] ADD CONSTRAINT [DF_TemplatePublishRequestData_ModelTemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelTemplateGUID]; GO +ALTER TABLE [dbo].[TemplatePublishRequestData] ADD CONSTRAINT [DF_TemplatePublishRequestData_FileGUID] DEFAULT (newid()) FOR [FileGUID]; GO +ALTER TABLE [dbo].[TemplatePublishRequestData] ADD CONSTRAINT [DF_TemplatePublishRequestData_LastModified] DEFAULT (getdate()) FOR [LastModified]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.TemplateSettings ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[TemplateSettings] ( + [TemplateGUID] uniqueidentifier NOT NULL, + [SettingID] nvarchar(200) NOT NULL, + [Value] nvarchar(max) NOT NULL +); + +CREATE UNIQUE CLUSTERED INDEX [CU_TemplateGUID_SettingID] ON [dbo].[TemplateSettings] ([TemplateGUID], [SettingID]); +GO +ALTER TABLE [dbo].[TemplateSettings] ADD CONSTRAINT [DF__TemplateS__Templ__35A28DAB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [TemplateGUID]; GO +ALTER TABLE [dbo].[TemplateSettings] ADD CONSTRAINT [DF__TemplateS__Setti__3696B1E4] DEFAULT ('') FOR [SettingID]; GO +ALTER TABLE [dbo].[TemplateSettings] ADD CONSTRAINT [DF__TemplateS__Value__378AD61D] DEFAULT ('') FOR [Value]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.ThemeInfo ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[ThemeInfo] ( + [ThemeInfoGUID] uniqueidentifier NOT NULL, + [Theme] nvarchar(64) NOT NULL, + [InfoType] nvarchar(64) NOT NULL, + [Value] nvarchar(450) NOT NULL, + PRIMARY KEY ([ThemeInfoGUID]) +); +GO +ALTER TABLE [dbo].[ThemeInfo] ADD CONSTRAINT [DF_ThemeInfo_ThemeInfoGUID] DEFAULT (newid()) FOR [ThemeInfoGUID]; GO +ALTER TABLE [dbo].[ThemeInfo] ADD CONSTRAINT [DF_ThemeInfo_Theme] DEFAULT ('') FOR [Theme]; GO +ALTER TABLE [dbo].[ThemeInfo] ADD CONSTRAINT [DF_ThemeInfo_InfoType] DEFAULT ('') FOR [InfoType]; GO +ALTER TABLE [dbo].[ThemeInfo] ADD CONSTRAINT [DF_ThemeInfo_Value] DEFAULT ('') FOR [Value]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.UpgradeLog ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[UpgradeLog] ( + [ID] int NOT NULL, + [Version] nvarchar(8) NOT NULL, + [Step] nvarchar(64) NOT NULL, + [Message] nvarchar(max) NOT NULL, + [LogDate] datetime NOT NULL, + [LogDateUtc] datetime NOT NULL, + PRIMARY KEY ([ID]) +); +GO +ALTER TABLE [dbo].[UpgradeLog] ADD CONSTRAINT [DF__UpgradeLo__LogDa__46D0AA9D] DEFAULT (getutcdate()) FOR [LogDateUtc]; GO +ALTER TABLE [dbo].[UpgradeLog] ADD CONSTRAINT [DF_UpgradeLog_Version] DEFAULT ('') FOR [Version]; GO +ALTER TABLE [dbo].[UpgradeLog] ADD CONSTRAINT [DF_UpgradeLog_Step] DEFAULT ('') FOR [Step]; GO +ALTER TABLE [dbo].[UpgradeLog] ADD CONSTRAINT [DF_UpgradeLog_Message] DEFAULT ('') FOR [Message]; GO +ALTER TABLE [dbo].[UpgradeLog] ADD CONSTRAINT [DF_UpgradeLog_LogDate] DEFAULT (getdate()) FOR [LogDate]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.UserDirectoryDefaultView ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[UserDirectoryDefaultView] ( + [UserGUID] uniqueidentifier NOT NULL, + [WorkspaceGUID] uniqueidentifier NOT NULL, + [PlanTypeGUID] uniqueidentifier NOT NULL, + [ViewGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([UserGUID], [WorkspaceGUID], [PlanTypeGUID]) +); +GO +ALTER TABLE [dbo].[UserDirectoryDefaultView] ADD CONSTRAINT [DF_UserDirectoryDefaultView_ViewGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ViewGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.UserFavorite ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[UserFavorite] ( + [UserFavoriteGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [ItemGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(200) NOT NULL, + [Url] nvarchar(200) NOT NULL, + [UrlParams] nvarchar(2000) NOT NULL, + [LinkTypeClassName] nvarchar(100) NOT NULL, + [LinkTypeConfig] nvarchar(max) NOT NULL, + [DateCreated] datetime NOT NULL, + PRIMARY KEY ([UserFavoriteGUID]) +); +GO +ALTER TABLE [dbo].[UserFavorite] ADD CONSTRAINT [FK__UserFavor__UserG__6C068FC2] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO +ALTER TABLE [dbo].[UserFavorite] ADD CONSTRAINT [DF__UserFavor__UserF__6B126B89] DEFAULT (newid()) FOR [UserFavoriteGUID]; GO +ALTER TABLE [dbo].[UserFavorite] ADD CONSTRAINT [DF__UserFavor__ItemG__6CFAB3FB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ItemGUID]; GO +ALTER TABLE [dbo].[UserFavorite] ADD CONSTRAINT [DF__UserFavori__Name__6DEED834] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[UserFavorite] ADD CONSTRAINT [DF__UserFavorit__Url__6EE2FC6D] DEFAULT ('') FOR [Url]; GO +ALTER TABLE [dbo].[UserFavorite] ADD CONSTRAINT [DF__UserFavor__UrlPa__6FD720A6] DEFAULT ('') FOR [UrlParams]; GO +ALTER TABLE [dbo].[UserFavorite] ADD CONSTRAINT [DF__UserFavor__LinkT__70CB44DF] DEFAULT ('') FOR [LinkTypeClassName]; GO +ALTER TABLE [dbo].[UserFavorite] ADD CONSTRAINT [DF__UserFavor__LinkT__71BF6918] DEFAULT ('') FOR [LinkTypeConfig]; GO +ALTER TABLE [dbo].[UserFavorite] ADD CONSTRAINT [DF__UserFavor__DateC__72B38D51] DEFAULT (getdate()) FOR [DateCreated]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.UserFeedback ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[UserFeedback] ( + [UserFeedbackGUID] uniqueidentifier NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [DateCreated] datetime NOT NULL, + PRIMARY KEY ([UserFeedbackGUID]) +); +GO +ALTER TABLE [dbo].[UserFeedback] ADD CONSTRAINT [DF__UserFeedb__UserF__37601F5E] DEFAULT (newid()) FOR [UserFeedbackGUID]; GO +ALTER TABLE [dbo].[UserFeedback] ADD CONSTRAINT [DF__UserFeedb__Autho__38544397] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [dbo].[UserFeedback] ADD CONSTRAINT [DF__UserFeedb__Autho__394867D0] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [dbo].[UserFeedback] ADD CONSTRAINT [DF__UserFeedb__Comme__3A3C8C09] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [dbo].[UserFeedback] ADD CONSTRAINT [DF__UserFeedb__DateC__3B30B042] DEFAULT (getdate()) FOR [DateCreated]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.UserGroup ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[UserGroup] ( + [UserGroupGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Type] int NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [Category] nvarchar(64) NOT NULL, + [GlobalID] nvarchar(100) NOT NULL, + [IsAdmin] bit NOT NULL, + [IsSysAdmin] bit NOT NULL, + PRIMARY KEY ([UserGroupGUID]) +); + +CREATE NONCLUSTERED INDEX [IX_UserGroup] ON [dbo].[UserGroup] ([Name]); +GO +ALTER TABLE [dbo].[UserGroup] ADD CONSTRAINT [DF_UserGroup_USERGROUPGUID] DEFAULT (newid()) FOR [UserGroupGUID]; GO +ALTER TABLE [dbo].[UserGroup] ADD CONSTRAINT [DF_UserGroup_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[UserGroup] ADD CONSTRAINT [DF_UserGroup_TYPE] DEFAULT ((0)) FOR [Type]; GO +ALTER TABLE [dbo].[UserGroup] ADD CONSTRAINT [DF_UserGroup_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[UserGroup] ADD CONSTRAINT [DF_UserGroup_CATEGORY] DEFAULT ('') FOR [Category]; GO +ALTER TABLE [dbo].[UserGroup] ADD CONSTRAINT [DF_dbo_UserGroup_IsAdmin] DEFAULT ((0)) FOR [IsAdmin]; GO +ALTER TABLE [dbo].[UserGroup] ADD CONSTRAINT [DF__UserGroup__Globa__62BB2268] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [dbo].[UserGroup] ADD CONSTRAINT [DF_dbo_UserGroup_IsSysAdmin] DEFAULT ((0)) FOR [IsSysAdmin]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.UserLimit ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[UserLimit] ( + [UserLimitGUID] uniqueidentifier NOT NULL, + [NumUsers] int NOT NULL, + [ModuleGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([UserLimitGUID]) +); +GO +ALTER TABLE [dbo].[UserLimit] ADD CONSTRAINT [FK_UserLimit_SystemCenterModule] FOREIGN KEY ([ModuleGUID]) REFERENCES [dbo].[SystemCenterModule] ([ModuleGUID]); GO +ALTER TABLE [dbo].[UserLimit] ADD CONSTRAINT [DF_UserLimit_ModuleGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModuleGUID]; GO +ALTER TABLE [dbo].[UserLimit] ADD CONSTRAINT [DF_UserLimit_UserLimitGUID] DEFAULT (newid()) FOR [UserLimitGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.UserProfile ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[UserProfile] ( + [UserGUID] uniqueidentifier NOT NULL, + [UserName] nvarchar(64) NOT NULL, + [HashedPassword] nvarchar(64) NOT NULL, + [NameFirst] nvarchar(64) NOT NULL, + [NameLast] nvarchar(64) NOT NULL, + [NameFull] nvarchar(130) NOT NULL, + [EmailAddress] nvarchar(450) NOT NULL, + [PhoneNumber] nvarchar(64) NOT NULL, + [IsSysAdmin_DEPRECATED] bit NOT NULL, + [AuthID] nvarchar(128) NOT NULL, + [IsDisabled] bit NOT NULL, + [BackupPassword] nvarchar(64) NOT NULL, + [DefaultAppModeLevel] tinyint NOT NULL, + [BrowserVersion] nvarchar(64) NOT NULL, + [UserAgent] nvarchar(512) NOT NULL, + [Domain] varchar(64) NOT NULL, + [HIPAADisclaimerStatus] tinyint NOT NULL, + [Custom1] nvarchar(450) NOT NULL, + [Custom2] nvarchar(450) NOT NULL, + [Custom3] nvarchar(450) NOT NULL, + [Custom4] nvarchar(450) NOT NULL, + [IsHidden] bit NOT NULL, + [DotNetVersion] nvarchar(250) NOT NULL, + [LastChangedPasswordUtc] datetime NOT NULL, + [LastLoginDateUtc] datetime NOT NULL, + [Salt] uniqueidentifier NOT NULL, + [NeedsPasswordChange] bit NOT NULL, + PRIMARY KEY ([UserGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_UserProfile] ON [dbo].[UserProfile] ([UserName]); +GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_IsDisabled] DEFAULT ((0)) FOR [IsDisabled]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_BackupPassword] DEFAULT ('') FOR [BackupPassword]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_USERGUID] DEFAULT (newid()) FOR [UserGUID]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF__UserProfi__IsHid__1591E9E3] DEFAULT ((0)) FOR [IsHidden]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_UserName] DEFAULT ('') FOR [UserName]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_HASHEDPASSWORD] DEFAULT ('') FOR [HashedPassword]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_NameFirst] DEFAULT ('') FOR [NameFirst]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_NameLast] DEFAULT ('') FOR [NameLast]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_EmailAddress] DEFAULT ('') FOR [EmailAddress]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_Custom1] DEFAULT ('') FOR [Custom1]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_PhoneNumber] DEFAULT ('') FOR [PhoneNumber]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_Custom2] DEFAULT ('') FOR [Custom2]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_Custom3] DEFAULT ('') FOR [Custom3]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_IsSysAdmin] DEFAULT ((0)) FOR [IsSysAdmin_DEPRECATED]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_Custom4] DEFAULT ('') FOR [Custom4]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_AuthID] DEFAULT ('') FOR [AuthID]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF__UserProfil__Salt__2F990AE1] DEFAULT (newid()) FOR [Salt]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF__UserProfi__Domai__36F27A1A] DEFAULT ('') FOR [Domain]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF__UserProfi__HIPAA__398A5D63] DEFAULT ((0)) FOR [HIPAADisclaimerStatus]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_DefaultAppModeLevel] DEFAULT ((1)) FOR [DefaultAppModeLevel]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_BrowserVersion] DEFAULT ('Unknown') FOR [BrowserVersion]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_UserAgent] DEFAULT ('Unknown') FOR [UserAgent]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF_UserProfile_NeedsPasswordChange] DEFAULT ((0)) FOR [NeedsPasswordChange]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF__UserProfi__LastC__551EC9F4] DEFAULT (getutcdate()) FOR [LastChangedPasswordUtc]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF__UserProfi__LastL__5612EE2D] DEFAULT (getutcdate()) FOR [LastLoginDateUtc]; GO +ALTER TABLE [dbo].[UserProfile] ADD CONSTRAINT [DF__UserProfi__DotNe__6AE25733] DEFAULT ('') FOR [DotNetVersion]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.UserProfileAppModeAccessLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[UserProfileAppModeAccessLink] ( + [UserGUID] uniqueidentifier NOT NULL, + [AccessLevel] tinyint NOT NULL, + PRIMARY KEY ([UserGUID], [AccessLevel]) +); +GO +ALTER TABLE [dbo].[UserProfileAppModeAccessLink] ADD CONSTRAINT [DF__UserProfi__Acces__6D81CC7D] DEFAULT ((1)) FOR [AccessLevel]; GO +ALTER TABLE [dbo].[UserProfileAppModeAccessLink] ADD CONSTRAINT [DF__UserProfi__UserG__6C8DA844] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.UserRole ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[UserRole] ( + [UserRoleGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Description] nvarchar(450) NOT NULL, + [Type] int NOT NULL, + [Category] nvarchar(64) NOT NULL, + [RoleID] smallint NOT NULL, + [GlobalID] nvarchar(100) NOT NULL, + PRIMARY KEY ([UserRoleGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_UserRole_RoleID] ON [dbo].[UserRole] ([RoleID]); +GO +ALTER TABLE [dbo].[UserRole] ADD CONSTRAINT [DF_UserRole_USERROLEGUID] DEFAULT (newid()) FOR [UserRoleGUID]; GO +ALTER TABLE [dbo].[UserRole] ADD CONSTRAINT [DF_UserRole_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[UserRole] ADD CONSTRAINT [DF_UserRole_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[UserRole] ADD CONSTRAINT [DF_UserRole_TYPE] DEFAULT ((0)) FOR [Type]; GO +ALTER TABLE [dbo].[UserRole] ADD CONSTRAINT [DF_UserRole_CATEGORY] DEFAULT ('') FOR [Category]; GO +ALTER TABLE [dbo].[UserRole] ADD CONSTRAINT [DF__UserRole__Global__78CA5F18] DEFAULT ('') FOR [GlobalID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.UserSecurityLastModifiedDate ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[UserSecurityLastModifiedDate] ( + [UserGUID] uniqueidentifier NOT NULL, + [LastModifiedDate] datetime NOT NULL, + PRIMARY KEY ([UserGUID]) +); +GO +ALTER TABLE [dbo].[UserSecurityLastModifiedDate] ADD CONSTRAINT [DF_UserSecurityLastModifiedDate_UserGUID] DEFAULT (newid()) FOR [UserGUID]; GO +ALTER TABLE [dbo].[UserSecurityLastModifiedDate] ADD CONSTRAINT [DF_UserSecurityLastModifiedDate_LastModifiedDate] DEFAULT (getdate()) FOR [LastModifiedDate]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.UserSetting ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[UserSetting] ( + [UserSettingGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(128) NOT NULL, + [Setting] nvarchar(max) NOT NULL, + PRIMARY KEY ([UserSettingGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [CORE_UserGUID_Name] ON [dbo].[UserSetting] ([UserGUID], [Name]); +GO +ALTER TABLE [dbo].[UserSetting] ADD CONSTRAINT [DF_UserSetting_SETTING] DEFAULT ('') FOR [Setting]; GO +ALTER TABLE [dbo].[UserSetting] ADD CONSTRAINT [DF_UserSetting_USERSETTINGGUID] DEFAULT (newid()) FOR [UserSettingGUID]; GO +ALTER TABLE [dbo].[UserSetting] ADD CONSTRAINT [DF_UserSetting_USERPROFILEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[UserSetting] ADD CONSTRAINT [DF_UserSetting_NAME] DEFAULT ('') FOR [Name]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.UserTag ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[UserTag] ( + [UserTagGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [LicenseGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([UserTagGUID]) +); +GO +ALTER TABLE [dbo].[UserTag] ADD CONSTRAINT [FK_UserTag_UserProfile] FOREIGN KEY ([UserGUID]) REFERENCES [dbo].[UserProfile] ([UserGUID]); GO +ALTER TABLE [dbo].[UserTag] ADD CONSTRAINT [DF__UserTag__License__4F638E99] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LicenseGUID]; GO +ALTER TABLE [dbo].[UserTag] ADD CONSTRAINT [DF_UserTag_UserTagGUID] DEFAULT (newid()) FOR [UserTagGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WFComment ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WFComment] ( + [CommentGUID] uniqueidentifier NOT NULL, + [WorkflowMapGUID] uniqueidentifier NOT NULL, + [PositionX] float NOT NULL, + [PositionY] float NOT NULL, + [Text] nvarchar(450) NOT NULL, + PRIMARY KEY ([CommentGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_WFComment] ON [dbo].[WFComment] ([CommentGUID]); +CREATE NONCLUSTERED INDEX [IX_WFComment_ByWorkflowMap] ON [dbo].[WFComment] ([WorkflowMapGUID]); +GO +ALTER TABLE [dbo].[WFComment] ADD CONSTRAINT [FK_WFComment_WFWorkflowMap] FOREIGN KEY ([WorkflowMapGUID]) REFERENCES [dbo].[WFWorkflowMap] ([WorkflowMapGUID]); GO +ALTER TABLE [dbo].[WFComment] ADD CONSTRAINT [DF_WFComment_COMMENTGUID] DEFAULT (newid()) FOR [CommentGUID]; GO +ALTER TABLE [dbo].[WFComment] ADD CONSTRAINT [DF_WFComment_WORKFLOWGUID] DEFAULT (newid()) FOR [WorkflowMapGUID]; GO +ALTER TABLE [dbo].[WFComment] ADD CONSTRAINT [DF_WFComment_POSITIONX] DEFAULT ((0)) FOR [PositionX]; GO +ALTER TABLE [dbo].[WFComment] ADD CONSTRAINT [DF_WFComment_POSITIONY] DEFAULT ((0)) FOR [PositionY]; GO +ALTER TABLE [dbo].[WFComment] ADD CONSTRAINT [DF_WFComment_TEXT] DEFAULT ('') FOR [Text]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WFCondition ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WFCondition] ( + [ConditionGUID] uniqueidentifier NOT NULL, + [ConditionSetGUID] uniqueidentifier NOT NULL, + [ConditionType] int NOT NULL, + [ParentConditionGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Metadata] nvarchar(max) NOT NULL, + [Description] nvarchar(450) NOT NULL, + [AssemblyName] nvarchar(450) NOT NULL, + [ClassName] nvarchar(450) NOT NULL, + PRIMARY KEY ([ConditionGUID]) +); + +CREATE CLUSTERED INDEX [IX_WFCondition_BySet] ON [dbo].[WFCondition] ([ConditionSetGUID]); +CREATE NONCLUSTERED INDEX [IX_WFCondition_ByParent] ON [dbo].[WFCondition] ([ParentConditionGUID]); +GO +ALTER TABLE [dbo].[WFCondition] ADD CONSTRAINT [FK_WFCondition_WFConditionSet] FOREIGN KEY ([ConditionSetGUID]) REFERENCES [dbo].[WFConditionSet] ([ConditionSetGUID]); GO +ALTER TABLE [dbo].[WFCondition] ADD CONSTRAINT [DF_WFCondition_CONDITIONGUID] DEFAULT (newid()) FOR [ConditionGUID]; GO +ALTER TABLE [dbo].[WFCondition] ADD CONSTRAINT [DF_WFCondition_CONDITIONSETGUID] DEFAULT (newid()) FOR [ConditionSetGUID]; GO +ALTER TABLE [dbo].[WFCondition] ADD CONSTRAINT [DF_WFCondition_CONDITIONTYPE] DEFAULT ((0)) FOR [ConditionType]; GO +ALTER TABLE [dbo].[WFCondition] ADD CONSTRAINT [DF_WFCondition_PARENTCONDITIONGUID] DEFAULT (newid()) FOR [ParentConditionGUID]; GO +ALTER TABLE [dbo].[WFCondition] ADD CONSTRAINT [DF_WFCondition_NAME_1] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[WFCondition] ADD CONSTRAINT [DF_WFCondition_FIELDNAME] DEFAULT ('') FOR [Metadata]; GO +ALTER TABLE [dbo].[WFCondition] ADD CONSTRAINT [DF_WFCondition_DISPLAYVALUE] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[WFCondition] ADD CONSTRAINT [DF_WFCondition_ASSEMBLYNAME] DEFAULT ('') FOR [AssemblyName]; GO +ALTER TABLE [dbo].[WFCondition] ADD CONSTRAINT [DF_WFCondition_CLASSNAME] DEFAULT ('') FOR [ClassName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WFConditionSet ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WFConditionSet] ( + [ConditionSetGUID] uniqueidentifier NOT NULL, + [RootConditionGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([ConditionSetGUID]) +); +GO +ALTER TABLE [dbo].[WFConditionSet] ADD CONSTRAINT [DF_WFConditionSet_CONDITIONSETGUID] DEFAULT (newid()) FOR [ConditionSetGUID]; GO +ALTER TABLE [dbo].[WFConditionSet] ADD CONSTRAINT [DF_WFConditionSet_ROOTCONDITIONGUID] DEFAULT (newid()) FOR [RootConditionGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WFEmailNotificationRequest ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WFEmailNotificationRequest] ( + [EmailNotificationRequestGuid] uniqueidentifier NOT NULL, + [PlanGuid] uniqueidentifier NOT NULL, + [StepGuid] uniqueidentifier NOT NULL, + [UserGuid] uniqueidentifier NOT NULL, + [DateTimeStamp] datetime NOT NULL, + PRIMARY KEY ([EmailNotificationRequestGuid]) +); +GO +ALTER TABLE [dbo].[WFEmailNotificationRequest] ADD CONSTRAINT [DF__WFEmailNo__Email__3FD6CEB2] DEFAULT (newid()) FOR [EmailNotificationRequestGuid]; GO +ALTER TABLE [dbo].[WFEmailNotificationRequest] ADD CONSTRAINT [DF__WFEmailNo__PlanG__40CAF2EB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanGuid]; GO +ALTER TABLE [dbo].[WFEmailNotificationRequest] ADD CONSTRAINT [DF__WFEmailNo__StepG__41BF1724] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [StepGuid]; GO +ALTER TABLE [dbo].[WFEmailNotificationRequest] ADD CONSTRAINT [DF__WFEmailNo__UserG__42B33B5D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGuid]; GO +ALTER TABLE [dbo].[WFEmailNotificationRequest] ADD CONSTRAINT [DF__WFEmailNo__DateT__43A75F96] DEFAULT (getdate()) FOR [DateTimeStamp]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WFEventPlan ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WFEventPlan] ( + [EventPlanGUID] uniqueidentifier NOT NULL, + [RootEventPlanStatementGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([EventPlanGUID]) +); +GO +ALTER TABLE [dbo].[WFEventPlan] ADD CONSTRAINT [FK_WFEventPlan_WFEventPlanStatement] FOREIGN KEY ([RootEventPlanStatementGUID]) REFERENCES [dbo].[WFEventPlanStatement] ([EventPlanStatementGUID]); GO +ALTER TABLE [dbo].[WFEventPlan] ADD CONSTRAINT [DF_WFEventPlan_EVENTPLANGUID] DEFAULT (newid()) FOR [EventPlanGUID]; GO +ALTER TABLE [dbo].[WFEventPlan] ADD CONSTRAINT [DF_WFEventPlan_ROOTEVENTPLANSTATEMENTGUID] DEFAULT (newid()) FOR [RootEventPlanStatementGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WFEventPlanStatement ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WFEventPlanStatement] ( + [EventPlanStatementGUID] uniqueidentifier NOT NULL, + [ParentEventPlanStatementGUID] uniqueidentifier NOT NULL, + [Type] int NOT NULL, + [StatementGUID] uniqueidentifier NOT NULL, + [EventPlanGUID] uniqueidentifier NOT NULL, + [ExecutionOrder] int NOT NULL, + PRIMARY KEY ([EventPlanStatementGUID]) +); + +CREATE CLUSTERED INDEX [IX_WFEventPlanStatement] ON [dbo].[WFEventPlanStatement] ([EventPlanGUID]); +GO +ALTER TABLE [dbo].[WFEventPlanStatement] ADD CONSTRAINT [FK_WFEventPlanStatement_WFAction] FOREIGN KEY ([StatementGUID]) REFERENCES [dbo].[CustomAction] ([ActionGUID]); GO +ALTER TABLE [dbo].[WFEventPlanStatement] ADD CONSTRAINT [FK_WFEventPlanStatement_WFConditionSet] FOREIGN KEY ([StatementGUID]) REFERENCES [dbo].[WFConditionSet] ([ConditionSetGUID]); GO +ALTER TABLE [dbo].[WFEventPlanStatement] ADD CONSTRAINT [DF_WFEventPlanStatement_EVENTPLANSTATEMENTGUID] DEFAULT (newid()) FOR [EventPlanStatementGUID]; GO +ALTER TABLE [dbo].[WFEventPlanStatement] ADD CONSTRAINT [DF_WFEventPlanStatement_PARENTEVENTPLANSTATEMENTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentEventPlanStatementGUID]; GO +ALTER TABLE [dbo].[WFEventPlanStatement] ADD CONSTRAINT [DF_WFEventPlanStatement_TYPE] DEFAULT ((0)) FOR [Type]; GO +ALTER TABLE [dbo].[WFEventPlanStatement] ADD CONSTRAINT [DF_WFEventPlanStatement_STATEMENTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [StatementGUID]; GO +ALTER TABLE [dbo].[WFEventPlanStatement] ADD CONSTRAINT [DF_WFEventPlanStatement_EVENTPLANGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EventPlanGUID]; GO +ALTER TABLE [dbo].[WFEventPlanStatement] ADD CONSTRAINT [DF_WFEventPlanStatement_ExecutionOrder] DEFAULT ((0)) FOR [ExecutionOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WFHistory ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WFHistory] ( + [WorkflowHistoryGUID] uniqueidentifier NOT NULL, + [WorkflowMapGUID] uniqueidentifier NOT NULL, + [WorkflowStepGUID] uniqueidentifier NOT NULL, + [EntityGUID] uniqueidentifier NOT NULL, + [HistoryType] int NOT NULL, + [DateTimeStamp] datetime NOT NULL, + [IsDeleted] bit NOT NULL, + [SkippingReason] nvarchar(2000) NULL, + PRIMARY KEY ([WorkflowHistoryGUID]) +); + +CREATE NONCLUSTERED COLUMNSTORE INDEX [NCCNU_WorkflowHistoryGUID] ON [dbo].[WFHistory] () INCLUDE ([WorkflowHistoryGUID]); +GO +ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [FK_WFHistory_WFWorkflowMap] FOREIGN KEY ([WorkflowMapGUID]) REFERENCES [dbo].[WFWorkflowMap] ([WorkflowMapGUID]); GO +ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [FK_WFHistory_WFWorkflowStep] FOREIGN KEY ([WorkflowStepGUID]) REFERENCES [dbo].[WFWorkflowStep] ([WorkflowStepGUID]); GO +ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [DF_WFHistory_WorkflowMapGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkflowMapGUID]; GO +ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [DF_WFHistory_WorkflowStepGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkflowStepGUID]; GO +ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [DF_WFHistory_EntityGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGUID]; GO +ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [DF_WFHistory_WorkflowHistoryGUID] DEFAULT (newid()) FOR [WorkflowHistoryGUID]; GO +ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [DF_WFHistory_HistoryType] DEFAULT ((0)) FOR [HistoryType]; GO +ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [DF_WFHistory_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO +ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [DF_WFHistory_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [DF__WFHistory__Skipp__7A1719FC] DEFAULT ('') FOR [SkippingReason]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WFOverdueReviewLog ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WFOverdueReviewLog] ( + [LogGUID] uniqueidentifier NOT NULL, + [PlanGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [WorkflowStepGUID] uniqueidentifier NOT NULL, + [WorkflowMapGUID] uniqueidentifier NOT NULL, + [DateTimeStamp] datetime NOT NULL, + [MessageGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([LogGUID]) +); +GO +ALTER TABLE [dbo].[WFOverdueReviewLog] ADD CONSTRAINT [DF_WFOverdueReviewLog_PlanGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanGUID]; GO +ALTER TABLE [dbo].[WFOverdueReviewLog] ADD CONSTRAINT [DF_WFOverdueReviewLog_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO +ALTER TABLE [dbo].[WFOverdueReviewLog] ADD CONSTRAINT [DF_WFOverdueReviewLog_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [dbo].[WFOverdueReviewLog] ADD CONSTRAINT [DF_WFOverdueReviewLog_WorkflowStepGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkflowStepGUID]; GO +ALTER TABLE [dbo].[WFOverdueReviewLog] ADD CONSTRAINT [DF_WFOverdueReviewLog_WorkflowMapGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkflowMapGUID]; GO +ALTER TABLE [dbo].[WFOverdueReviewLog] ADD CONSTRAINT [DF_WFOverdueReviewLog_MessageGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MessageGUID]; GO +ALTER TABLE [dbo].[WFOverdueReviewLog] ADD CONSTRAINT [DF_WFOverdueReviewLog_LogGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LogGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WFProcess ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WFProcess] ( + [ProcessGUID] uniqueidentifier NOT NULL, + [WorkflowMapGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [DisplayOrder] int NOT NULL, + [IsConcurrent] bit NOT NULL, + PRIMARY KEY ([ProcessGUID]) +); + +CREATE NONCLUSTERED INDEX [IX_WFProcess_ByMap] ON [dbo].[WFProcess] ([WorkflowMapGUID]); +CREATE NONCLUSTERED INDEX [IX_WFProcess_DisplayOrder] ON [dbo].[WFProcess] ([DisplayOrder]); +GO +ALTER TABLE [dbo].[WFProcess] ADD CONSTRAINT [FK_WFProcess_WFWorkflowMap] FOREIGN KEY ([WorkflowMapGUID]) REFERENCES [dbo].[WFWorkflowMap] ([WorkflowMapGUID]); GO +ALTER TABLE [dbo].[WFProcess] ADD CONSTRAINT [DF_WFProcess_PROCESSGUID] DEFAULT (newid()) FOR [ProcessGUID]; GO +ALTER TABLE [dbo].[WFProcess] ADD CONSTRAINT [DF_WFProcess_WORKFLOWGUID] DEFAULT (newid()) FOR [WorkflowMapGUID]; GO +ALTER TABLE [dbo].[WFProcess] ADD CONSTRAINT [DF_WFProcess_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[WFProcess] ADD CONSTRAINT [DF_WFProcess_DISPLAYORDER] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[WFProcess] ADD CONSTRAINT [DF_WFProcess_HASCONCURRENTSTEPS] DEFAULT ((0)) FOR [IsConcurrent]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WFProcessStepLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WFProcessStepLink] ( + [ProcessStepLinkGUID] uniqueidentifier NOT NULL, + [WorkflowMapGUID] uniqueidentifier NOT NULL, + [ProcessGUID] uniqueidentifier NOT NULL, + [WorkflowStepGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([ProcessStepLinkGUID]) +); + +CREATE CLUSTERED INDEX [IX_WFProcessStepLink_ByMap] ON [dbo].[WFProcessStepLink] ([WorkflowMapGUID]); +GO +ALTER TABLE [dbo].[WFProcessStepLink] ADD CONSTRAINT [FK_WFProcessStepLink_WFProcess] FOREIGN KEY ([ProcessGUID]) REFERENCES [dbo].[WFProcess] ([ProcessGUID]); GO +ALTER TABLE [dbo].[WFProcessStepLink] ADD CONSTRAINT [FK_WFProcessStepLink_WFWorkflowStep] FOREIGN KEY ([WorkflowStepGUID]) REFERENCES [dbo].[WFWorkflowStep] ([WorkflowStepGUID]); GO +ALTER TABLE [dbo].[WFProcessStepLink] ADD CONSTRAINT [DF_WFProcessStepLink_WORKFLOWGROUPINGGUID] DEFAULT (newid()) FOR [ProcessStepLinkGUID]; GO +ALTER TABLE [dbo].[WFProcessStepLink] ADD CONSTRAINT [DF_WFProcessStepLink_WORKFLOWMAPGUID] DEFAULT (newid()) FOR [WorkflowMapGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WFReviewValue ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WFReviewValue] ( + [ReviewValueGUID] uniqueidentifier NOT NULL, + [IdentityGUID] uniqueidentifier NOT NULL, + [EntityGUID] uniqueidentifier NOT NULL, + [WorkflowStepGUID] uniqueidentifier NOT NULL, + [ReviewValueTypeGUID] uniqueidentifier NOT NULL, + [Comments] nvarchar(max) NOT NULL, + [DateTimeStamp] datetime NOT NULL, + PRIMARY KEY ([ReviewValueGUID]) +); + +CREATE NONCLUSTERED INDEX [IX_EntityGuid_Workflowstepguid] ON [dbo].[WFReviewValue] ([EntityGUID], [WorkflowStepGUID]); +GO +ALTER TABLE [dbo].[WFReviewValue] ADD CONSTRAINT [DF_WFReviewValue_REVIEWVALUEGUID] DEFAULT (newid()) FOR [ReviewValueGUID]; GO +ALTER TABLE [dbo].[WFReviewValue] ADD CONSTRAINT [DF_WFReviewValue_IDENTITYGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [IdentityGUID]; GO +ALTER TABLE [dbo].[WFReviewValue] ADD CONSTRAINT [DF_WFReviewValue_ENTITYGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGUID]; GO +ALTER TABLE [dbo].[WFReviewValue] ADD CONSTRAINT [DF_WFReviewValue_WORKFLOWSTEPGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkflowStepGUID]; GO +ALTER TABLE [dbo].[WFReviewValue] ADD CONSTRAINT [DF_WFReviewValue_REVIEWVALUETYPEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReviewValueTypeGUID]; GO +ALTER TABLE [dbo].[WFReviewValue] ADD CONSTRAINT [DF_WFReviewValue_COMMENTS] DEFAULT ('') FOR [Comments]; GO +ALTER TABLE [dbo].[WFReviewValue] ADD CONSTRAINT [DF_WFReviewValue_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WFReviewValueType ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WFReviewValueType] ( + [ReviewValueTypeGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [FriendlyName] nvarchar(64) NOT NULL, + [ImageIndex] int NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [HasRequiredComments] bit NOT NULL, + [NotificationType] uniqueidentifier NOT NULL, + [IsMovingForward] bit NOT NULL, + [IsNotificationEnabled] bit NOT NULL, + PRIMARY KEY ([ReviewValueTypeGUID]) +); +GO +ALTER TABLE [dbo].[WFReviewValueType] ADD CONSTRAINT [DF_WFReviewValueType_IsNotificationEnabled] DEFAULT ((1)) FOR [IsNotificationEnabled]; GO +ALTER TABLE [dbo].[WFReviewValueType] ADD CONSTRAINT [DF_WFReviewValueType_REVIEWVALUETYPEGUID] DEFAULT (newid()) FOR [ReviewValueTypeGUID]; GO +ALTER TABLE [dbo].[WFReviewValueType] ADD CONSTRAINT [DF_WFReviewValueType_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[WFReviewValueType] ADD CONSTRAINT [DF_WFReviewValueType_FriendlyName] DEFAULT ('') FOR [FriendlyName]; GO +ALTER TABLE [dbo].[WFReviewValueType] ADD CONSTRAINT [DF_WFReviewValueType_IMAGEINDEX] DEFAULT ((0)) FOR [ImageIndex]; GO +ALTER TABLE [dbo].[WFReviewValueType] ADD CONSTRAINT [DF_WFReviewValueType_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[WFReviewValueType] ADD CONSTRAINT [DF_WFReviewValueType_HASREQUIREDCOMMENTS] DEFAULT ((0)) FOR [HasRequiredComments]; GO +ALTER TABLE [dbo].[WFReviewValueType] ADD CONSTRAINT [DF_WFReviewValueType_NOTIFICATIONTYPE] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [NotificationType]; GO +ALTER TABLE [dbo].[WFReviewValueType] ADD CONSTRAINT [DF_WFReviewValueType_IsMovingForward] DEFAULT ((1)) FOR [IsMovingForward]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WFReviewerAssignment ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WFReviewerAssignment] ( + [ReviewerAssignmentGUID] uniqueidentifier NOT NULL, + [WorkflowStepGUID] uniqueidentifier NOT NULL, + [IdentityGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([ReviewerAssignmentGUID]) +); + +CREATE CLUSTERED INDEX [IX_WFReviewerAssignment] ON [dbo].[WFReviewerAssignment] ([WorkflowStepGUID]); +GO +ALTER TABLE [dbo].[WFReviewerAssignment] ADD CONSTRAINT [FK_WFReviewerAssignment_WFWorkflowStep] FOREIGN KEY ([WorkflowStepGUID]) REFERENCES [dbo].[WFWorkflowStep] ([WorkflowStepGUID]); GO +ALTER TABLE [dbo].[WFReviewerAssignment] ADD CONSTRAINT [DF_WFReviewerAssignment_REVIEWERASSIGNMENTGUID] DEFAULT (newid()) FOR [ReviewerAssignmentGUID]; GO +ALTER TABLE [dbo].[WFReviewerAssignment] ADD CONSTRAINT [DF_WFReviewerAssignment_WORKFLOWSTEPGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkflowStepGUID]; GO +ALTER TABLE [dbo].[WFReviewerAssignment] ADD CONSTRAINT [DF_WFReviewerAssignment_IDENTITYGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [IdentityGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WFReviewerDelegate ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WFReviewerDelegate] ( + [ReviewerDelegateGUID] uniqueidentifier NOT NULL, + [WorkflowStepGUID] uniqueidentifier NOT NULL, + [EntityGUID] uniqueidentifier NOT NULL, + [ReviewerUserGUID] uniqueidentifier NOT NULL, + [DelegateUserGUID] uniqueidentifier NOT NULL, + [IsFromOutOfOfficeSchedule] bit NOT NULL, + PRIMARY KEY ([ReviewerDelegateGUID]) +); +GO +ALTER TABLE [dbo].[WFReviewerDelegate] ADD CONSTRAINT [FK_WFReviewerDelegate_WFWorkflowStep] FOREIGN KEY ([WorkflowStepGUID]) REFERENCES [dbo].[WFWorkflowStep] ([WorkflowStepGUID]); GO +ALTER TABLE [dbo].[WFReviewerDelegate] ADD CONSTRAINT [DF_Table_1_ReviewerIdentityGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReviewerUserGUID]; GO +ALTER TABLE [dbo].[WFReviewerDelegate] ADD CONSTRAINT [DF_WFReviewerDelegate_DelegateUserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DelegateUserGUID]; GO +ALTER TABLE [dbo].[WFReviewerDelegate] ADD CONSTRAINT [DF_Table_1_DelegateGUID] DEFAULT (newid()) FOR [ReviewerDelegateGUID]; GO +ALTER TABLE [dbo].[WFReviewerDelegate] ADD CONSTRAINT [DF_WFReviewerDelegate_WorkflowStepGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkflowStepGUID]; GO +ALTER TABLE [dbo].[WFReviewerDelegate] ADD CONSTRAINT [DF__WFReviewe__IsFro__6618AC42] DEFAULT ((0)) FOR [IsFromOutOfOfficeSchedule]; GO +ALTER TABLE [dbo].[WFReviewerDelegate] ADD CONSTRAINT [DF_WFReviewerDelegate_EntityGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WFReviewerOutOfOffice ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WFReviewerOutOfOffice] ( + [ReviewerGUID] uniqueidentifier NOT NULL, + [StartDateTime] datetime NOT NULL, + [EndDateTime] datetime NOT NULL, + [IsOutOfOffice] bit NOT NULL, + [DelegatedReviewerGUID] uniqueidentifier NOT NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WFStepReviewValueTypeLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WFStepReviewValueTypeLink] ( + [StepReviewValueTypeLinkGUID] uniqueidentifier NOT NULL, + [WorkflowStepGUID] uniqueidentifier NOT NULL, + [ReviewValueTypeGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([StepReviewValueTypeLinkGUID]) +); + +CREATE CLUSTERED INDEX [IX_WFStepReviewValueLink] ON [dbo].[WFStepReviewValueTypeLink] ([WorkflowStepGUID]); +GO +ALTER TABLE [dbo].[WFStepReviewValueTypeLink] ADD CONSTRAINT [FK_WFStepReviewValueTypeLink_WFReviewValueType] FOREIGN KEY ([ReviewValueTypeGUID]) REFERENCES [dbo].[WFReviewValueType] ([ReviewValueTypeGUID]); GO +ALTER TABLE [dbo].[WFStepReviewValueTypeLink] ADD CONSTRAINT [FK_WFStepReviewValueTypeLink_WFWorkflowStep] FOREIGN KEY ([WorkflowStepGUID]) REFERENCES [dbo].[WFWorkflowStep] ([WorkflowStepGUID]); GO +ALTER TABLE [dbo].[WFStepReviewValueTypeLink] ADD CONSTRAINT [DF_WFStepReviewValueLink_STEPREVIEWVALUELINKGUID] DEFAULT (newid()) FOR [StepReviewValueTypeLinkGUID]; GO +ALTER TABLE [dbo].[WFStepReviewValueTypeLink] ADD CONSTRAINT [DF_WFStepReviewValueLink_WORKFLOWSTEPGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkflowStepGUID]; GO +ALTER TABLE [dbo].[WFStepReviewValueTypeLink] ADD CONSTRAINT [DF_WFStepReviewValueLink_REVIEWVALUETYPEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReviewValueTypeGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WFToken ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WFToken] ( + [WorkflowTokenGUID] uniqueidentifier NOT NULL, + [WorkflowMapGUID] uniqueidentifier NOT NULL, + [EntityGUID] uniqueidentifier NOT NULL, + [WorkflowStepGUID] uniqueidentifier NOT NULL, + [IsFromManualMove] bit NOT NULL, + PRIMARY KEY ([WorkflowTokenGUID]) +); + +CREATE NONCLUSTERED INDEX [IX_WFToken_ByMap] ON [dbo].[WFToken] ([WorkflowMapGUID]); +CREATE NONCLUSTERED INDEX [IX_WFToken_ByEntity] ON [dbo].[WFToken] ([EntityGUID]); +CREATE NONCLUSTERED INDEX [IX_WFToken_ByStep] ON [dbo].[WFToken] ([WorkflowStepGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_WFToken_ByStepEntity] ON [dbo].[WFToken] ([WorkflowStepGUID], [EntityGUID]); +GO +ALTER TABLE [dbo].[WFToken] ADD CONSTRAINT [FK_WFToken_WFWorkflowMap] FOREIGN KEY ([WorkflowMapGUID]) REFERENCES [dbo].[WFWorkflowMap] ([WorkflowMapGUID]); GO +ALTER TABLE [dbo].[WFToken] ADD CONSTRAINT [DF_WFToken_IsFromManualMove] DEFAULT ((0)) FOR [IsFromManualMove]; GO +ALTER TABLE [dbo].[WFToken] ADD CONSTRAINT [DF_WFWorkflowToken_WORKFLOWTOKENGUID] DEFAULT (newid()) FOR [WorkflowTokenGUID]; GO +ALTER TABLE [dbo].[WFToken] ADD CONSTRAINT [DF_WFToken_WORKFLOWMAPGUID] DEFAULT (newid()) FOR [WorkflowMapGUID]; GO +ALTER TABLE [dbo].[WFToken] ADD CONSTRAINT [DF_WFWorkflowToken_ENTITYGUID] DEFAULT (newid()) FOR [EntityGUID]; GO +ALTER TABLE [dbo].[WFToken] ADD CONSTRAINT [DF_WFWorkflowToken_WORKFLOWSTEPGUID] DEFAULT (newid()) FOR [WorkflowStepGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WFTransition ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WFTransition] ( + [TransitionGUID] uniqueidentifier NOT NULL, + [WorkflowMapGUID] uniqueidentifier NOT NULL, + [WorkflowStepFromGUID] uniqueidentifier NOT NULL, + [WorkflowStepToGUID] uniqueidentifier NOT NULL, + [ConditionSetGUID] uniqueidentifier NOT NULL, + [EventPlanGUID] uniqueidentifier NOT NULL, + [Text] nvarchar(64) NOT NULL, + [PortFrom] int NOT NULL, + [PortTo] int NOT NULL, + [IsLoopback] bit NOT NULL, + PRIMARY KEY ([TransitionGUID]) +); + +CREATE NONCLUSTERED INDEX [IX_WFTransition_ByMap] ON [dbo].[WFTransition] ([WorkflowMapGUID]); +CREATE NONCLUSTERED INDEX [IX_WFTransition_ByStepFrom] ON [dbo].[WFTransition] ([WorkflowStepFromGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_WFTransition_ByFromTo] ON [dbo].[WFTransition] ([WorkflowStepFromGUID], [WorkflowStepToGUID], [IsLoopback]); +GO +ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [FK_WFTransition_WFConditionSet] FOREIGN KEY ([ConditionSetGUID]) REFERENCES [dbo].[WFConditionSet] ([ConditionSetGUID]); GO +ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [FK_WFTransition_WFEventPlan] FOREIGN KEY ([EventPlanGUID]) REFERENCES [dbo].[WFEventPlan] ([EventPlanGUID]); GO +ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [FK_WFTransition_WFWorkflowStep_From] FOREIGN KEY ([WorkflowStepFromGUID]) REFERENCES [dbo].[WFWorkflowStep] ([WorkflowStepGUID]); GO +ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [FK_WFTransition_WFWorkflowStep_To] FOREIGN KEY ([WorkflowStepToGUID]) REFERENCES [dbo].[WFWorkflowStep] ([WorkflowStepGUID]); GO +ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [DF_WFTransition_TRANSITIONGUID] DEFAULT (newid()) FOR [TransitionGUID]; GO +ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [DF_WFTransition_WORKFLOWMAPGUID] DEFAULT (newid()) FOR [WorkflowMapGUID]; GO +ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [DF_WFTransition_STEPFROMGUID] DEFAULT (newid()) FOR [WorkflowStepFromGUID]; GO +ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [DF_WFTransition_STEPTOGUID] DEFAULT (newid()) FOR [WorkflowStepToGUID]; GO +ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [DF_WFTransition_CONDITIONGUID] DEFAULT (newid()) FOR [ConditionSetGUID]; GO +ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [DF_WFTransition_CONDITIONALACTIONGUID] DEFAULT (newid()) FOR [EventPlanGUID]; GO +ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [DF_WFTransition_TEXT] DEFAULT ('') FOR [Text]; GO +ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [DF_WFTransition_PORTFROM] DEFAULT ((0)) FOR [PortFrom]; GO +ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [DF_WFTransition_PORTTO] DEFAULT ((0)) FOR [PortTo]; GO +ALTER TABLE [dbo].[WFTransition] ADD CONSTRAINT [DF_WFTransition_IsLoopback] DEFAULT ((0)) FOR [IsLoopback]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WFWorkflowMap ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WFWorkflowMap] ( + [WorkflowMapGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [IsLocked] bit NOT NULL, + [FolderGUID] uniqueidentifier NOT NULL, + [ReviewFolderGUID] uniqueidentifier NOT NULL, + [IsEmailIntegrationEnabled] bit NOT NULL, + [AssociatedReportGUID] uniqueidentifier NOT NULL, + [TimeInStepThreshold] int NOT NULL, + [IsCopiedWithPlan] bit NOT NULL, + [IsSkippedStepByAuthor] bit NOT NULL, + [IsSkippedStepBySubordinates] bit NOT NULL, + PRIMARY KEY ([WorkflowMapGUID]) +); +GO +ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF__WFWorkflo__IsSki__0F61AD3C] DEFAULT ((0)) FOR [IsSkippedStepBySubordinates]; GO +ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF__WFWorkflo__IsSki__20CB6509] DEFAULT ((0)) FOR [IsSkippedStepByAuthor]; GO +ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF_WFWorkflowMap_IsCopiedWithPlan] DEFAULT ((1)) FOR [IsCopiedWithPlan]; GO +ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF_WFWorkflowMap_WORKFLOWMAPGUID] DEFAULT (newid()) FOR [WorkflowMapGUID]; GO +ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF_WFWorkflowMap_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF_WFWorkflowMap_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF_WFWorkflowMap_ISLOCKEDFORREFRESH] DEFAULT ((0)) FOR [IsLocked]; GO +ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF_WFWorkflowMap_FolderGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO +ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF_WFWorkflowMap_ReviewFolderGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReviewFolderGUID]; GO +ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF_WFWorkflowMap_IsEmailIntegrationEnabled] DEFAULT ((0)) FOR [IsEmailIntegrationEnabled]; GO +ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF_WFWorkflowMap_AssociatedReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssociatedReportGUID]; GO +ALTER TABLE [dbo].[WFWorkflowMap] ADD CONSTRAINT [DF_WFWorkflowMap_TimeInStepThreshold] DEFAULT ((0)) FOR [TimeInStepThreshold]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WFWorkflowStep ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WFWorkflowStep] ( + [WorkflowStepGUID] uniqueidentifier NOT NULL, + [WorkflowMapGUID] uniqueidentifier NOT NULL, + [IsStart] bit NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Description] nvarchar(4000) NOT NULL, + [OnStartEventPlanGUID] uniqueidentifier NOT NULL, + [OnEndEventPlanGUID] uniqueidentifier NOT NULL, + [PositionX] float NOT NULL, + [PositionY] float NOT NULL, + [DisplayOrder] int NOT NULL, + [Type] int NOT NULL, + [IsHidden] bit NOT NULL, + [IsAdvancedCondition] bit NOT NULL, + [IsAdvancedStartEvent] bit NOT NULL, + [IsAdvancedEndEvent] bit NOT NULL, + [QualifyConditionSetGUID] uniqueidentifier NOT NULL, + [IsAdvancedQualification] bit NOT NULL, + [IsAdvancedLoopback] bit NOT NULL, + [IsHiddenInRouting] bit NOT NULL, + [Version] timestamp NOT NULL, + [ReviewerAccess] int NOT NULL, + [ReviewerExitAccess] int NOT NULL, + [AssociatedReportGUID] uniqueidentifier NOT NULL, + [Icon] int NOT NULL, + [ReminderDaysThreshold] int NOT NULL, + PRIMARY KEY ([WorkflowStepGUID]) +); + +CREATE NONCLUSTERED INDEX [IX_WFWorkflowStep_ByMap] ON [dbo].[WFWorkflowStep] ([WorkflowMapGUID]); +CREATE NONCLUSTERED INDEX [IX_WFWorkflowStep_DisplayOrder] ON [dbo].[WFWorkflowStep] ([DisplayOrder]); +GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [FK_WFWorkflowStep_WFEventPlan_End] FOREIGN KEY ([OnEndEventPlanGUID]) REFERENCES [dbo].[WFEventPlan] ([EventPlanGUID]); GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [FK_WFWorkflowStep_WFEventPlan_Start] FOREIGN KEY ([OnStartEventPlanGUID]) REFERENCES [dbo].[WFEventPlan] ([EventPlanGUID]); GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_IconIndex] DEFAULT ((0)) FOR [Icon]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_ReminderDaysThreshold] DEFAULT ((0)) FOR [ReminderDaysThreshold]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_ReviewerAccess] DEFAULT ((-1)) FOR [ReviewerAccess]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_IsHiddenInRouting] DEFAULT ((0)) FOR [IsHiddenInRouting]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_AssociatedReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssociatedReportGUID]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_WorkflowStepGUID] DEFAULT (newid()) FOR [WorkflowStepGUID]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_WORKFLOWGUID] DEFAULT (newid()) FOR [WorkflowMapGUID]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_IsStart] DEFAULT ((0)) FOR [IsStart]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_ONSTARTEVENTGUID] DEFAULT (newid()) FOR [OnStartEventPlanGUID]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_ONENDEVENTGUID] DEFAULT (newid()) FOR [OnEndEventPlanGUID]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_POSITIONX] DEFAULT ((0)) FOR [PositionX]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_POSITIONY] DEFAULT ((0)) FOR [PositionY]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_DISPLAYORDER] DEFAULT ((0)) FOR [DisplayOrder]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_TYPE] DEFAULT ((0)) FOR [Type]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_ISHIDDEN] DEFAULT ((0)) FOR [IsHidden]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_ISADVANCEDCONDITION] DEFAULT ((1)) FOR [IsAdvancedCondition]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_ISADVANCEDSTARTEVENT] DEFAULT ((1)) FOR [IsAdvancedStartEvent]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_ISADVANCEDENDEVENT] DEFAULT ((1)) FOR [IsAdvancedEndEvent]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_QualifyConditionSetGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [QualifyConditionSetGUID]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_IsAdvancedQualification] DEFAULT ((1)) FOR [IsAdvancedQualification]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_IsAdvancedLoopback] DEFAULT ((0)) FOR [IsAdvancedLoopback]; GO +ALTER TABLE [dbo].[WFWorkflowStep] ADD CONSTRAINT [DF_WFWorkflowStep_ReviewerExitAccess] DEFAULT ((-1)) FOR [ReviewerExitAccess]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WorkerLog ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WorkerLog] ( + [WorkerID] uniqueidentifier NOT NULL, + [WorkerGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(150) NOT NULL, + [IPAddress] nvarchar(50) NOT NULL, + [CreationTime] datetime NOT NULL, + [ServerName] nvarchar(150) NOT NULL, + [StopTime] datetime NULL, + [TaskEngineVersion] varchar(100) NULL, + PRIMARY KEY ([WorkerID]) +); +GO +ALTER TABLE [dbo].[WorkerLog] ADD CONSTRAINT [DF_WorkerLog_StopTime] DEFAULT ('1/1/1900') FOR [StopTime]; GO +ALTER TABLE [dbo].[WorkerLog] ADD CONSTRAINT [DF_WorkerLog_TaskEngineVersion] DEFAULT ('') FOR [TaskEngineVersion]; GO +ALTER TABLE [dbo].[WorkerLog] ADD CONSTRAINT [DF_WorkerLog_WorkerID] DEFAULT (newid()) FOR [WorkerID]; GO +ALTER TABLE [dbo].[WorkerLog] ADD CONSTRAINT [DF_dbo.WorkerLog_WorkerGUID] DEFAULT (newid()) FOR [WorkerGUID]; GO +ALTER TABLE [dbo].[WorkerLog] ADD CONSTRAINT [DF_dbo.WorkerLog_WorkerName] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[WorkerLog] ADD CONSTRAINT [DF_dbo.WorkerLog_IPAddress] DEFAULT ('0.0.0.0') FOR [IPAddress]; GO +ALTER TABLE [dbo].[WorkerLog] ADD CONSTRAINT [DF_dbo.WorkerLog_CreationTime] DEFAULT ('1/1/1900') FOR [CreationTime]; GO +ALTER TABLE [dbo].[WorkerLog] ADD CONSTRAINT [DF_WorkerLog_ServerName] DEFAULT ('') FOR [ServerName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WorkflowAttachModelFailure ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WorkflowAttachModelFailure] ( + [MemberGUID] uniqueidentifier NOT NULL, + [PlanGUID] uniqueidentifier NOT NULL, + [ErrorLogGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([MemberGUID]) +); +GO +ALTER TABLE [dbo].[WorkflowAttachModelFailure] ADD CONSTRAINT [DF_WorkflowAttachModelFailure_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [dbo].[WorkflowAttachModelFailure] ADD CONSTRAINT [DF_WorkflowAttachModelFailure_PlanGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanGUID]; GO +ALTER TABLE [dbo].[WorkflowAttachModelFailure] ADD CONSTRAINT [DF__WorkflowA__Error__47CD59C9] DEFAULT (newid()) FOR [ErrorLogGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.Workspace ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[Workspace] ( + [WorkspaceGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(64) NOT NULL, + [Description] nvarchar(450) NOT NULL, + [IsPanelEnabled] bit NOT NULL, + [CustomMenuGUID] uniqueidentifier NOT NULL, + [CustomToolbarGUID] uniqueidentifier NOT NULL, + [CustomContextMenuGUID] uniqueidentifier NOT NULL, + [DefaultEntityViewGUID] uniqueidentifier NOT NULL, + [DefaultPlanTypeGUID] uniqueidentifier NOT NULL, + [FilterEntityViewGUID] uniqueidentifier NOT NULL, + [DefaultFormDefGUID] uniqueidentifier NOT NULL, + [ProviderType] int NOT NULL, + [IsLoadingHierarchyMembers] bit NOT NULL, + [IsWorkflowColumnsEnabled] bit NOT NULL, + [ModuleGUID] uniqueidentifier NOT NULL, + [IsModuleDefault] bit NOT NULL, + [HelpID] nvarchar(50) NOT NULL, + PRIMARY KEY ([WorkspaceGUID]) +); +GO +ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_ProviderType] DEFAULT ((0)) FOR [ProviderType]; GO +ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_IsLoadingHierarchyMembers] DEFAULT ((0)) FOR [IsLoadingHierarchyMembers]; GO +ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_DefaultFormDefGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultFormDefGUID]; GO +ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF__Workspace__IsMod__1EAB16DB] DEFAULT ((0)) FOR [IsModuleDefault]; GO +ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_IsWorkflowColumnsEnabled] DEFAULT ((0)) FOR [IsWorkflowColumnsEnabled]; GO +ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF__Workspace__Modul__65F025BE] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModuleGUID]; GO +ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF__Workspace__HelpI__70701636] DEFAULT ('') FOR [HelpID]; GO +ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_WORKSPACEGUID] DEFAULT (newid()) FOR [WorkspaceGUID]; GO +ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_DESCRIPTION] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_ISPANELENABLED] DEFAULT ((0)) FOR [IsPanelEnabled]; GO +ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_CUSTOMMENUGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CustomMenuGUID]; GO +ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_CUSTOMTOOLBARGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CustomToolbarGUID]; GO +ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_CUSTOMCONTEXTMENUGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CustomContextMenuGUID]; GO +ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_DefaultEntityViewGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultEntityViewGUID]; GO +ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_DefaultPlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultPlanTypeGUID]; GO +ALTER TABLE [dbo].[Workspace] ADD CONSTRAINT [DF_Workspace_FilterEntityViewGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FilterEntityViewGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WorkspaceContentLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WorkspaceContentLink] ( + [WorkspaceContentLinkGUID] uniqueidentifier NOT NULL, + [WorkspaceGUID] uniqueidentifier NOT NULL, + [ContentGUID] uniqueidentifier NOT NULL, + [ContentType] int NOT NULL, + [DisplayOrder] int NOT NULL, + PRIMARY KEY ([WorkspaceContentLinkGUID]) +); +GO +ALTER TABLE [dbo].[WorkspaceContentLink] ADD CONSTRAINT [FK_WorkspaceContentLink_Workspace] FOREIGN KEY ([WorkspaceGUID]) REFERENCES [dbo].[Workspace] ([WorkspaceGUID]); GO +ALTER TABLE [dbo].[WorkspaceContentLink] ADD CONSTRAINT [DF_WorkspaceContentLink_WORKSPACECONTENTLINKGUID] DEFAULT (newid()) FOR [WorkspaceContentLinkGUID]; GO +ALTER TABLE [dbo].[WorkspaceContentLink] ADD CONSTRAINT [DF_WorkspaceContentLink_WORKSPACEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkspaceGUID]; GO +ALTER TABLE [dbo].[WorkspaceContentLink] ADD CONSTRAINT [DF_WorkspaceContentLink_CONTENTGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ContentGUID]; GO +ALTER TABLE [dbo].[WorkspaceContentLink] ADD CONSTRAINT [DF_WorkspaceContentLink_CONTENTTYPE] DEFAULT ((0)) FOR [ContentType]; GO +ALTER TABLE [dbo].[WorkspaceContentLink] ADD CONSTRAINT [DF_WorkspaceContentLink_DisplayOrder] DEFAULT ((0)) FOR [DisplayOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WorkspaceDimensionLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WorkspaceDimensionLink] ( + [WorkspaceDimensionLinkGUID] uniqueidentifier NOT NULL, + [WorkspaceGUID] uniqueidentifier NOT NULL, + [DimensionGUID] uniqueidentifier NOT NULL, + [HierarchyGUID] uniqueidentifier NOT NULL, + [IsDefault] bit NOT NULL, + PRIMARY KEY ([WorkspaceDimensionLinkGUID]) +); +GO +ALTER TABLE [dbo].[WorkspaceDimensionLink] ADD CONSTRAINT [FK_WorkspaceDimensionLink_Workspace] FOREIGN KEY ([WorkspaceGUID]) REFERENCES [dbo].[Workspace] ([WorkspaceGUID]); GO +ALTER TABLE [dbo].[WorkspaceDimensionLink] ADD CONSTRAINT [DF_WorkspaceDimensionLink_HierarchyGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HierarchyGUID]; GO +ALTER TABLE [dbo].[WorkspaceDimensionLink] ADD CONSTRAINT [DF_WorkspaceDimensionLink_IsDefault] DEFAULT ((0)) FOR [IsDefault]; GO +ALTER TABLE [dbo].[WorkspaceDimensionLink] ADD CONSTRAINT [DF_WorkspaceDimensionLink_WorkspaceDimensionLinkGUID] DEFAULT (newid()) FOR [WorkspaceDimensionLinkGUID]; GO +ALTER TABLE [dbo].[WorkspaceDimensionLink] ADD CONSTRAINT [DF_WorkspaceDimensionLink_WorkspaceGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkspaceGUID]; GO +ALTER TABLE [dbo].[WorkspaceDimensionLink] ADD CONSTRAINT [DF_WorkspaceDimensionLink_DimensionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DimensionGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WorkspaceEntityViewLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WorkspaceEntityViewLink] ( + [WorkspaceEntityViewLinkGUID] uniqueidentifier NOT NULL, + [WorkspaceGUID] uniqueidentifier NOT NULL, + [EntityViewGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([WorkspaceEntityViewLinkGUID]) +); +GO +ALTER TABLE [dbo].[WorkspaceEntityViewLink] ADD CONSTRAINT [FK_WorkspaceEntityViewLink_Workspace] FOREIGN KEY ([WorkspaceGUID]) REFERENCES [dbo].[Workspace] ([WorkspaceGUID]); GO +ALTER TABLE [dbo].[WorkspaceEntityViewLink] ADD CONSTRAINT [DF_WorkspaceEntityViewLink_WorkspaceEntityViewLinkGUID] DEFAULT (newid()) FOR [WorkspaceEntityViewLinkGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.WorkspacePlanTypeLink ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[WorkspacePlanTypeLink] ( + [WorkspacePlanTypeLinkGUID] uniqueidentifier NOT NULL, + [WorkspaceGUID] uniqueidentifier NOT NULL, + [GridTemplateGUID] uniqueidentifier NOT NULL, + [PlanTypeGUID] uniqueidentifier NOT NULL, + [IsDefault] bit NOT NULL, + [FormDefGUID] uniqueidentifier NOT NULL, + [HiddenToolIDList] nvarchar(max) NOT NULL, + [IsEnabled] bit NOT NULL, + PRIMARY KEY ([WorkspacePlanTypeLinkGUID]) +); +GO +ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [FK_WorkspaceGridTemplateLink_GridTemplate] FOREIGN KEY ([GridTemplateGUID]) REFERENCES [dbo].[GridTemplate] ([GRIDTEMPLATEGUID]); GO +ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [FK_WorkspaceGridTemplateLink_PlanType] FOREIGN KEY ([PlanTypeGUID]) REFERENCES [dbo].[PlanType] ([PlanTypeGUID]); GO +ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [FK_WorkspaceGridTemplateLink_Workspace] FOREIGN KEY ([WorkspaceGUID]) REFERENCES [dbo].[Workspace] ([WorkspaceGUID]); GO +ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [DF_WorkspaceGridTemplateLink_WorkspaceGridTemplateLinkGUID] DEFAULT (newid()) FOR [WorkspacePlanTypeLinkGUID]; GO +ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [DF_WorkspaceGridTemplateLink_WorkspaceGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [WorkspaceGUID]; GO +ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [DF_WorkspaceGridTemplateLink_GridTemplateGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GridTemplateGUID]; GO +ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [DF_WorkspaceGridTemplateLink_PlanTypeGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO +ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [DF_WorkspacePlanTypeLink_IsDefault] DEFAULT ((0)) FOR [IsDefault]; GO +ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [DF_WorkspacePlanTypeLink_FormDefGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FormDefGUID]; GO +ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [DF_WorkspacePlanTypeLink_HiddenToolIDList] DEFAULT ('') FOR [HiddenToolIDList]; GO +ALTER TABLE [dbo].[WorkspacePlanTypeLink] ADD CONSTRAINT [DF__Workspace__IsEna__76206499] DEFAULT ((1)) FOR [IsEnabled]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.XPlan ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[XPlan] ( + [PlanGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(450) NOT NULL, + [ParentEntityGUID] uniqueidentifier NOT NULL, + [DefaultFormDefGUID] uniqueidentifier NOT NULL, + [DateCreated] datetime NOT NULL, + [LastModelTemplateGroupGUID] uniqueidentifier NOT NULL, + [ModelDatasetGUID] uniqueidentifier NOT NULL, + [ModelTemplateGUID] uniqueidentifier NOT NULL, + [ScoreMemberGUID] uniqueidentifier NOT NULL, + [IsDeletedPlan] bit NOT NULL, + [IsConsolidation] bit NOT NULL, + [IsModelRefreshEnabled] bit NOT NULL, + [PlanTypeGUID] uniqueidentifier NOT NULL, + [PlanID] int NOT NULL, + [CachedLootID] nvarchar(128) NOT NULL, + [AuthorUserGUID] uniqueidentifier NOT NULL, + [IsArchived] bit NOT NULL, + [IsFinancialsLocked] bit NOT NULL, + [IsModelWorkbookCached] bit NOT NULL, + [CachedWorkflowStep] nvarchar(400) NULL, + [CachedWorkflowStepGUIDsCSV] nvarchar(800) NULL, + [LastModifiedFormDate] datetime NOT NULL, + [LastModifiedFormUserGUID] uniqueidentifier NOT NULL, + [LastModifiedModelDate] datetime NOT NULL, + [LastModifiedModelUserGUID] uniqueidentifier NOT NULL, + [ModelMemoryHit] int NOT NULL, + [ModelFileCacheHit] int NOT NULL, + [ModelDatabaseHit] int NOT NULL, + [LastModelCacheInvalidateReason] nvarchar(100) NOT NULL, + [LastRefreshModelDate] datetime NOT NULL, + [FillinTemplateGUID] uniqueidentifier NOT NULL, + [LastModelCacheInvalidateDate] datetime NOT NULL, + [AuthorFullName] nvarchar(256) NOT NULL, + [LastModifiedFormUserName] nvarchar(256) NOT NULL, + [LastModifiedModelUserName] nvarchar(256) NOT NULL, + [IsHiddenFromWorkflowNotification] bit NOT NULL, + [IsCacheable] bit NOT NULL, + [IsSuspended] bit NOT NULL, + [SuspendedByUserGUID] uniqueidentifier NOT NULL, + [SuspendedByUserName] nvarchar(256) NOT NULL, + [DateSuspended] datetime NOT NULL, + [SuspensionModeSource] nvarchar(max) NOT NULL, + PRIMARY KEY ([PlanGUID]) +); + +CREATE NONCLUSTERED INDEX [idx_XPlan_PlanGUID_With_Name] ON [dbo].[XPlan] ([PlanGUID]) INCLUDE ([Name]); +CREATE NONCLUSTERED INDEX [NCNU_PlanTypeGUID] ON [dbo].[XPlan] ([PlanTypeGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_XPlan_IsDeleted] ON [dbo].[XPlan] ([IsDeletedPlan], [PlanGUID], [PlanTypeGUID]) INCLUDE ([DateCreated]); +CREATE NONCLUSTERED INDEX [IDX_XPlan_CachedLooID_INCL_PlanGUID] ON [dbo].[XPlan] ([CachedLootID]) INCLUDE ([PlanGUID]); +GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_SuspendedByUserName] DEFAULT ('') FOR [SuspendedByUserName]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__AuthorFul__098A6F03] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__FillinTem__1495D444] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FillinTemplateGUID]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_CachedLootID] DEFAULT ('') FOR [CachedLootID]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__IsHiddenF__16DD75DC] DEFAULT ((0)) FOR [IsHiddenFromWorkflowNotification]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_LastRefreshModelDate] DEFAULT (getdate()) FOR [LastRefreshModelDate]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_AuthorUserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorUserGUID]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_LastModelCacheInvalidateDate] DEFAULT (getdate()) FOR [LastModelCacheInvalidateDate]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_LastModifiedFormDate] DEFAULT (getdate()) FOR [LastModifiedFormDate]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_CachedWorkflowStep] DEFAULT ('') FOR [CachedWorkflowStep]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_LastModifiedModelDate] DEFAULT (getdate()) FOR [LastModifiedModelDate]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_LastModifiedFormUserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LastModifiedFormUserGUID]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_SuspendedByUserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SuspendedByUserGUID]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__IsModelWo__3A79BD92] DEFAULT ((0)) FOR [IsModelWorkbookCached]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__LastModif__48BBBCD7] DEFAULT ('') FOR [LastModifiedFormUserName]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__LastModif__49AFE110] DEFAULT ('') FOR [LastModifiedModelUserName]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_LastModifiedModelUserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LastModifiedModelUserGUID]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_Entity_ENTITYGUID] DEFAULT (newid()) FOR [PlanGUID]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_Entity_PARENTENTITYGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentEntityGUID]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_Entity_DEFAULTFORMDEFGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DefaultFormDefGUID]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_Entity_DATECREATED] DEFAULT (getdate()) FOR [DateCreated]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_Entity_LASTMODELDATASETGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LastModelTemplateGroupGUID]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_Entity_MODELDATASETGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelDatasetGUID]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_Entity_MODELTEMPLATEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModelTemplateGUID]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_LastModelCacheInvalidateReason] DEFAULT ('') FOR [LastModelCacheInvalidateReason]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_PlaceholderMemberGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScoreMemberGUID]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_ISDELETED] DEFAULT ((0)) FOR [IsDeletedPlan]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_ISCONSOLIDATION] DEFAULT ((0)) FOR [IsConsolidation]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_IsModelRefreshEnabled] DEFAULT ((1)) FOR [IsModelRefreshEnabled]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_PLANTYPEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PlanTypeGUID]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__IsCacheab__5C1D6E18] DEFAULT ((1)) FOR [IsCacheable]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_IsArchived] DEFAULT ((0)) FOR [IsArchived]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__IsFinanci__66056A50] DEFAULT ((0)) FOR [IsFinancialsLocked]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__CachedWor__6D6ABF73] DEFAULT ('') FOR [CachedWorkflowStepGUIDsCSV]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_SuspensionModeSource] DEFAULT ('') FOR [SuspensionModeSource]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_DateSuspended] DEFAULT (getdate()) FOR [DateSuspended]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__ModelMemo__74D0AE23] DEFAULT ((0)) FOR [ModelMemoryHit]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__ModelFile__75C4D25C] DEFAULT ((0)) FOR [ModelFileCacheHit]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF__XPlan__ModelData__76B8F695] DEFAULT ((0)) FOR [ModelDatabaseHit]; GO +ALTER TABLE [dbo].[XPlan] ADD CONSTRAINT [DF_XPlan_IsSuspended] DEFAULT ((0)) FOR [IsSuspended]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo._data_Fairview_RS_2_d4b011b67c6e4a0ca94ee153867d9e42_ ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[_data_Fairview_RS_2_d4b011b67c6e4a0ca94ee153867d9e42_] ( + [EncounterID] bigint NOT NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo._data_Rule_Set_Measure_Child_663d423c1a234dea8fba2e3c429437d1_ ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[_data_Rule_Set_Measure_Child_663d423c1a234dea8fba2e3c429437d1_] ( + [EncounterID] bigint NOT NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo._data_Rule_Set_Measure_Less_Than_And_Less_Than_Equal_Child_c279feaa6d9b4253ab44871e1dba1480_ ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[_data_Rule_Set_Measure_Less_Than_And_Less_Than_Equal_Child_c279feaa6d9b4253ab44871e1dba1480_] ( + [EncounterID] bigint NOT NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo._data_SingleExclude_ExcludesAllRows_ExpectFalse_eb1eab34ef0041c5b7e3ddcebd30beaa_ ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[_data_SingleExclude_ExcludesAllRows_ExpectFalse_eb1eab34ef0041c5b7e3ddcebd30beaa_] ( + [EncounterID] bigint NOT NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.aaVersion ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[aaVersion] ( + [id] int NOT NULL, + [Name] nvarchar(256) NOT NULL, + [Value] nvarchar(4000) NOT NULL, + [ModifiedDate] smalldatetime NOT NULL, + PRIMARY KEY ([id]) +); +GO +ALTER TABLE [dbo].[aaVersion] ADD CONSTRAINT [DF_aaVersion_New_Purpose] DEFAULT ('Not specified') FOR [Name]; GO +ALTER TABLE [dbo].[aaVersion] ADD CONSTRAINT [DF_aaVersion__New_ExpirationDate] DEFAULT ('Not specified') FOR [Value]; GO +ALTER TABLE [dbo].[aaVersion] ADD CONSTRAINT [DF_aaVersion_New_LastSync] DEFAULT (getdate()) FOR [ModifiedDate]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.dtproperties ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[dtproperties] ( + [id] int NOT NULL, + [objectid] int NULL, + [property] varchar(64) NOT NULL, + [value] varchar(255) NULL, + [uvalue] nvarchar(255) NULL, + [lvalue] image(2147483647) NULL, + [version] int NOT NULL, + PRIMARY KEY ([id], [property]) +); +GO +ALTER TABLE [dbo].[dtproperties] ADD CONSTRAINT [DF__dtpropert__versi__77BFCB91] DEFAULT (0) FOR [version]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.filterMemberCsvBkp ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[filterMemberCsvBkp] ( + [filtermembercsvCopy] nvarchar(max) NOT NULL, + [ClientReportSectionAttributeGUID] uniqueidentifier NOT NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.intClientComment ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[intClientComment] ( + [ClientCommentGUID] uniqueidentifier NOT NULL, + [DataInterfaceMapID] uniqueidentifier NOT NULL, + [ClientComment] nvarchar(2000) NOT NULL, + [ModifiedUserGUID] uniqueidentifier NOT NULL, + [DateModifiedUtc] datetime NOT NULL, + PRIMARY KEY ([ClientCommentGUID]) +); +GO +ALTER TABLE [dbo].[intClientComment] ADD CONSTRAINT [FK_IntClientComment_DataInterfaceMapID] FOREIGN KEY ([DataInterfaceMapID]) REFERENCES [dbo].[IntDataInterfaceMap] ([DataInterfaceMapID]); GO +ALTER TABLE [dbo].[intClientComment] ADD CONSTRAINT [DF__intClient__DateM__3B5EF7F1] DEFAULT (getutcdate()) FOR [DateModifiedUtc]; GO +ALTER TABLE [dbo].[intClientComment] ADD CONSTRAINT [DF_IntClientComment_ModifiedUserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ModifiedUserGUID]; GO +ALTER TABLE [dbo].[intClientComment] ADD CONSTRAINT [DF_intClientComment_ClientCommentGUID] DEFAULT (newid()) FOR [ClientCommentGUID]; GO +ALTER TABLE [dbo].[intClientComment] ADD CONSTRAINT [DF_IntClientComment_ClientComment] DEFAULT ('') FOR [ClientComment]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.intSFTPConnection ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[intSFTPConnection] ( + [SFTPConnectionGUID] uniqueidentifier NOT NULL, + [ConfigID] uniqueidentifier NOT NULL, + [Server] nvarchar(400) NOT NULL, + [Port] nvarchar(400) NOT NULL, + [Directory] nvarchar(400) NOT NULL, + [UserName] nvarchar(400) NOT NULL, + [Password] nvarchar(400) NOT NULL, + [IsArchiveOnImport] bit NOT NULL, + [IsDeleteFileOnImport] bit NOT NULL, + [IsEncrypted] bit NOT NULL, + [ArchiveDirectory] nvarchar(400) NOT NULL, + PRIMARY KEY ([SFTPConnectionGUID]) +); +GO +ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCo__SFTPC__63D2D322] DEFAULT (newid()) FOR [SFTPConnectionGUID]; GO +ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCo__Confi__64C6F75B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ConfigID]; GO +ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCo__Serve__65BB1B94] DEFAULT ('') FOR [Server]; GO +ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCon__Port__66AF3FCD] DEFAULT ('') FOR [Port]; GO +ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCo__Direc__67A36406] DEFAULT ('') FOR [Directory]; GO +ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCo__UserN__6897883F] DEFAULT ('') FOR [UserName]; GO +ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCo__Passw__698BAC78] DEFAULT ('') FOR [Password]; GO +ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCo__IsArc__6A7FD0B1] DEFAULT ((1)) FOR [IsArchiveOnImport]; GO +ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCo__IsDel__6B73F4EA] DEFAULT ((1)) FOR [IsDeleteFileOnImport]; GO +ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCo__IsEnc__6C681923] DEFAULT ((0)) FOR [IsEncrypted]; GO +ALTER TABLE [dbo].[intSFTPConnection] ADD CONSTRAINT [DF__intSFTPCo__Archi__6D5C3D5C] DEFAULT ('') FOR [ArchiveDirectory]; GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.sysdiagrams ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[sysdiagrams] ( + [name] nvarchar(128) NOT NULL, + [principal_id] int NOT NULL, + [diagram_id] int NOT NULL, + [version] int NULL, + [definition] varbinary(max) NULL, + PRIMARY KEY ([diagram_id]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [UK_principal_name] ON [dbo].[sysdiagrams] ([principal_id], [name]); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.tempcosts ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[tempcosts] ( + [FiscalYearID] smallint NOT NULL, + [Name] nvarchar(100) NOT NULL, + [DepartmentCode] nvarchar(100) NOT NULL, + [ChargeCode] nvarchar(100) NOT NULL, + [UnitCost] numeric NOT NULL, + [Volume] numeric NULL, + [TotalCost] numeric NULL, + [CostingResultID] int NOT NULL, + [FixeddirectUnitCost] numeric NOT NULL, + [FixedIndirectUnitCost] numeric NOT NULL, + [VariableDirectUnitCost] numeric NOT NULL, + [VariableIndirectUnitCost] numeric NOT NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- dbo.tempdssDimDRG ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[tempdssDimDRG] ( + [DRGID] int NOT NULL, + [DRGCode] varchar(10) NOT NULL, + [DescriptionShort] varchar(100) NOT NULL, + [Description] varchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [ServiceLineID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [MDCID] int NOT NULL, + [Type] nvarchar(25) NOT NULL, + [FinalRulePostAcuteDRG] nvarchar(25) NOT NULL, + [ICD9Inclusion] nvarchar(50) NOT NULL, + [TransactionID] int NULL, + [DRGSchema] nvarchar(100) NOT NULL, + [ImportName] nvarchar(100) NOT NULL +); +GO + +--------------------------------------------- +--------------------------------------------- +-- VIEWS +--------------------------------------------- + +-- dbo.SysViewObjects +CREATE VIEW [dbo].[SysViewObjects] +AS +select + S.name + '.' + O.name as Expression, + S.name as SchemaName, + O.name as Objectname, + case when O.type_desc = 'VIEW' then CAST(1 as bit) else CAST(0 as bit) end as IsView +from sys.objects O + inner join sys.schemas S on S.schema_id = O.schema_id +where O.type_desc = 'USER_TABLE' OR O.type_desc = 'VIEW' +GO + + +--------------------------------------------- + +-- dbo.ViewSysTables +CREATE view [dbo].[ViewSysTables] +AS +select * from viewSysAllObjects where type_desc = 'USER_TABLE' +GO + + +--------------------------------------------- + +-- dbo.ViewSysTriggers +CREATE VIEW [dbo].[ViewSysTriggers] +AS +select + T.object_id as [TriggerID], + T.name as Name, + S.name as SchemaName, + OB.name as ObjectName, + T.create_date as CreationDate, + case when OB.type_desc = 'VIEW' then 1 else 0 end as IsViewTrigger, + M.definition, + case when M.definition like '%INSTEAD OF%' then 1 else 0 end as [IsInsteadOfTrigger] +from sys.triggers T + inner join sys.objects O on O.object_id = T.object_id + inner join sys.schemas S on S.schema_id = O.schema_id + inner join sys.objects OB on OB.object_id = O.parent_object_id + inner join sys.sql_modules M on M.object_id = T.object_id +GO + + +--------------------------------------------- + +-- dbo.ViewSysViews +CREATE VIEW [dbo].[ViewSysViews] +AS +select + O.*, + M.definition as [ViewDefinition] +from viewSysAllObjects O + inner join sys.all_sql_modules M on M.object_id = O.ObjectID +where O.type_desc = 'VIEW' + AND SchemaName <> 'sys' AND SchemaName <> 'INFORMATION_SCHEMA' +GO + + +--------------------------------------------- + +-- dbo.viewAMAssumptionView +CREATE view dbo.viewAMAssumptionView +as +SELECT [AssumptionViewGUID] + ,[AssumptionGroupGUID] + ,[Name] + ,[ColumnWidths] + ,[AssumptionJoinDataGUID] + ,[FolderGUID] + ,[IsDistributionModeActive] + ,cast([DistributionInfo] as nvarchar(max)) as DistributionInfo + ,[ProviderGUID] + ,[CreatedDate] + ,[CreatedBy] + ,[LastUsedDate] + FROM [dbo].[AMAssumptionView] +GO + + +--------------------------------------------- + +-- dbo.viewActionLog +--Forward +create view viewActionLog +as + select + A.RowID, + A.Action, + A.SubAction, + A.Details, + A.Username, + A.DateTimeStamp, + A.Duration, + A.TokenGUID, + MAX(D.Version) as Version + from + ActionLog A + inner join viewUpgradeDate D on D.UpgradeDate < A.DateTimeStamp + group by + A.RowID, + A.Action, + A.SubAction, + A.Details, + A.Username, + A.DateTimeStamp, + A.Duration, + A.TokenGUID +GO + + +--------------------------------------------- + +-- dbo.viewActionLogSummary +CREATE view viewActionLogSummary as +select + YEAR(DateTimeStamp) as Year, + MONTH(DateTimeStamp) as Month, + DAY(DateTimeStamp) as Day, + Action, + SubAction, + SUM(Duration) as SumDuration, + avg(Duration) as AvgDuration, + Min(Duration) as MinDuration, + Max(Duration) as MaxDuration, + stdev(Duration) as StdevDuration, + COUNT(*) as Count +from ActionLog +group by YEAR(DateTimeStamp) , MONTH(DateTimeStamp) ,DAY(DateTimeStamp) , Action, SubAction +GO + + +--------------------------------------------- + +-- dbo.viewCMBucket +--Forward + + +CREATE view [dbo].[viewCMBucket] +as + +-- hack default member required for foreign key to work in score config tool +Select + '00000000-0000-0000-0000-000000000000' as MemberGUID, + '00000000-0000-0000-0000-000000000000' as CategoryGUID, + 'Not Specified' as Name, + 'Not Specified' as Category + +union + +SELECT + B.BucketGUID As MemberGUID, + B.CategoryGUID, + B.Name, + C.Name As Category +FROM + CMBucket B +INNER JOIN + CMCategory C ON C.CategoryGUID = B.CategoryGUID +GO + + +--------------------------------------------- + +-- dbo.viewCMMetric +CREATE view [dbo].[viewCMMetric] +AS + SELECT + CM.*, + CM.MetricGUID As MemberGUID, CM.Name As Metric, cast(0 as bit) as IsInternal + FROM + CMMetric CM with (readuncommitted) +GO + + +--------------------------------------------- + +-- dbo.viewCMMetricWithFramework +CREATE view [dbo].[viewCMMetricWithFramework] +AS + SELECT + CM.MetricGUID As MemberGUID, CM.MetricGUID As MetricGUID, CM.Name As Name, + CM.Name As Metric, CM.MetricCode As MetricCode, CM.IsAggregable, CM.ToleranceValue, CM.TolerancePercent, CM.IsInverted, CM.FormatString, CM.DisplayOrder, cast(0 as bit) as IsInternal, + COALESCE(VFW.FrameworkID, '0') As FrameworkID, + COALESCE(VFW.Framework, 'Not Specified') As Framework, + COALESCE(VFW.FrameworkSchemaName, 'Not Specified') As FrameworkSchema + FROM + CMMetric CM with (readuncommitted) + LEFT JOIN CMMetricFramework FW with (readuncommitted) ON FW.MetricGUID = CM.MetricGUID + LEFT JOIN viewFramework VFW with (readuncommitted) ON VFW.FrameworkID = FW.FrameworkID +GO + + +--------------------------------------------- + +-- dbo.viewCMSampleTableMetricLinks +CREATE view dbo.viewCMSampleTableMetricLinks AS +select ML.*, M.Name from CMSampleTableMetricLink ML + inner join CMMetric M on M.MetricGUID = ML.MetricGUID +GO + + +--------------------------------------------- + +-- dbo.viewCurrentUsers +CREATE VIEW [dbo].[viewCurrentUsers] AS + SELECT cu.TokenGUID, cu.IPAddress, up.UserName, up.NameFirst, up.NameLast, up.UserGUID, up.PhoneNumber, cu.IdentityServerSessionId, cu.LoginStampUtc, cu.LastActionStampUtc, + CASE WHEN LastActionStampUtc > GETUTCDATE() THEN 0 ELSE DATEDIFF(MI, LastActionStampUtc, GETUTCDATE()) END AS inactiveMinutes + FROM CurrentUser cu LEFT JOIN UserProfile up + ON cu.UserGUID = up.UserGUID +GO + + +--------------------------------------------- + +-- dbo.viewCustomActionDependencies +CREATE view [dbo].[viewCustomActionDependencies] +as + select + 'Workflow' as ReferrerType, + WFM.Name as ReferrerName, + CA.Description as ActionName, + WFM.WorkflowMapGUID as ReferrerGUID, + CA.ActionGUID + from + CustomAction CA + inner join WFEventPlanStatement EPS on EPS.StatementGUID = CA.ActionGUID + inner join WFEventPlan EP on EP.EventPlanGUID = EPS.EventPlanGUID + inner join WFWorkflowStep WFS on WFS.OnStartEventPlanGUID = EP.EventPlanGUID or WFS.OnEndEventPlanGUID = EPS.EventPlanGUID + inner join WFWorkflowMap WFM on WFM.WorkflowMapGUID = WFS.WorkflowMapGUID + union all + select + 'Custom Menu' as ReferrerType, + CM.Name as ReferrerName, + CA.Description as ActionName, + CM.CustomMenuGUID as ReferrerGUID, + CA.ActionGUID + from + CustomAction CA + inner join CustomMenuContent CMC on cast(CMC.ContentXML as nvarchar(max)) like '%G' + replace(CAST(CA.ActionGUID as nvarchar(36)), '-', '') + '%' + inner join CustomMenu CM on CM.CustomMenuGUID = CMC.CustomMenuGUID + union all + select + 'File Listener' as ReferrerType, + FL.Name as ReferrerName, + CA.Description as ActionName, + FL.FileListenerGUID as ReferrerGUID, + CA.ActionGUID + from + CustomAction CA + inner join FileListener FL on FL.ActionGUID = CA.ActionGUID + union all + select + 'Conditional Action' as ReferrerType, + CA2.Description as ReferrerName, + CA.Description as ActionName, + CA2.ActionGUID as ReferrerGUID, + CA.ActionGUID + from + CustomAction CA + inner join CustomAction CA2 on CA2.ClassName like '%ConditionalAction%' and CA2.Metadata like '%' + CAST(CA.ActionGUID as nvarchar(36)) + '%' + union all + select + 'Scheduled Task' as ReferrerType, + TE.Name as ReferrerName, + CA.Description as ActionName, + TE.ScheduledTaskGUID as ReferrerGUID, + CA.ActionGUID + from + CustomAction CA + inner join TEScheduledTask TE on TE.SetupXML like '%' + CAST(CA.ActionGUID as nvarchar(36)) + '%' + union all + select + 'Desktop' as ReferrerType, + DT.Name as ReferrerName, + CA.Description as ActionName, + DW.DesktopTemplateGUID as ReferrerGUID, + CA.ActionGUID + from + CustomAction CA + inner join DesktopWidget DW on cast(DW.WidgetXML as nvarchar(max)) like '%' + CAST(CA.ActionGUID as nvarchar(36)) + '%' + inner join DesktopTemplate DT on DT.DesktopTemplateGUID = DW.DesktopTemplateGUID +GO + + +--------------------------------------------- + +-- dbo.viewCustomMenuContent +create view viewCustomMenuContent +as +select CustomMenuContentGUID, CustomMenuGUID, cast(ContentXML as nvarchar(max)) as ContentXML from CustomMenuContent +GO + + +--------------------------------------------- + +-- dbo.viewCustomScriptDependencies +CREATE view [dbo].[viewCustomScriptDependencies] +as +select + 'Workflow Condition' as ReferrerType, + WFM.Name + ' - ' + WFS.Name as ReferrerName, + CS.Name as ScriptName, + WFS.WorkflowStepGUID as ReferrerGUID, + CS.CustomScriptGUID as ScriptGUID +from + CustomScript CS + inner join WFCondition WFC on cast(WFC.Metadata as nvarchar(max)) like '%' + CAST(CS.CustomScriptGUID as nvarchar(36)) + '%' + inner join WFConditionSet WFCS on WFC.ConditionSetGUID = WFCS.ConditionSetGUID + inner join WFTransition WFT on WFT.ConditionSetGUID = WFCS.ConditionSetGUID + inner join WFWorkflowStep WFS on WFS.WorkflowStepGUID = WFT.WorkflowStepFromGUID + inner join WFWorkflowMap WFM on WFM.WorkflowMapGUID = WFS.WorkflowMapGUID +union +select + 'Custom Action' as ReferrerType, + CA.Description as ReferrerName, + CS.Name as ScriptName, + CA.ActionGUID as ReferrerGUID, + CS.CustomScriptGUID as ScriptGUID +from + CustomScript CS + inner join CustomAction CA on cast(CA.Metadata as nvarchar(max)) like '%' + CAST(CS.CustomScriptGUID as nvarchar(36)) + '%' +union +select + 'Scheduled Task' as ReferrerType, + ST.Name as ReferrerName, + CS.Name as ScriptName, + ST.ScheduledTaskGUID as ReferrerGUID, + CS.CustomScriptGUID as ScriptGUID +from + CustomScript CS + inner join TEScheduledTask ST on cast(ST.SetupXML as nvarchar(max)) like '%' + CAST(CS.CustomScriptGUID as nvarchar(36)) + '%' +union +select + 'Plan Type' as ReferrerType, + PT.Name as [ReferrerName], + CS.Name as [ScriptName], + PT.PlanTypeGUID as [ReferrerGUID], + CS.CustomScriptGUID as [ScriptGUID] +from + PlanType PT + inner join CustomScript CS on CS.CustomScriptGUID = PT.OnSaveCustomScriptGUID +union +select + 'Plan Type' as ReferrerType, + PT.Name as [ReferrerName], + CS.Name as [ScriptName], + PT.PlanTypeGUID as [ReferrerGUID], + CS.CustomScriptGUID as [ScriptGUID] +from + PlanType PT + inner join CustomScript CS on CS.CustomScriptGUID = PT.OnSaveCustomScript2GUID +union +select + 'Plan Type' as ReferrerType, + PT.Name as [ReferrerName], + CS.Name as [ScriptName], + PT.PlanTypeGUID as [ReferrerGUID], + CS.CustomScriptGUID as [ScriptGUID] +from + PlanType PT + inner join CustomScript CS on CS.CustomScriptGUID = PT.OnAfterModelRefreshCustomScriptGUID +union +select + 'Plan Type' as ReferrerType, + PT.Name as [ReferrerName], + CS.Name as [ScriptName], + PT.PlanTypeGUID as [ReferrerGUID], + CS.CustomScriptGUID as [ScriptGUID] +from + PlanType PT + inner join CustomScript CS on CS.CustomScriptGUID = PT.OnTemplateChangeCustomScriptGUID +GO + + +--------------------------------------------- + +-- dbo.viewCustomScriptDependenciesFast +CREATE view [dbo].[viewCustomScriptDependenciesFast] +AS +select 'Plan Type' as [Type], Name, OnSaveCustomScriptGUID as [ScriptGUID] from PlanType where OnSaveCustomScriptGUID <> dbo.ZeroGUID() +UNION ALL +select 'Plan Type' as [Type], Name, OnSaveCustomScript2GUID as [ScriptGUID] from PlanType where OnSaveCustomScript2GUID <> dbo.ZeroGUID() +UNION ALL +select 'Plan Type' as [Type], Name, OnAfterModelRefreshCustomScriptGUID as [ScriptGUID] from PlanType where OnAfterModelRefreshCustomScriptGUID <> dbo.ZeroGUID() +UNION ALL +select 'Plan Type' as [Type], Name, OnTemplateChangeCustomScriptGUID as [ScriptGUID] from PlanType where OnTemplateChangeCustomScriptGUID <> dbo.ZeroGUID() +UNION ALL +select + 'Custom Action', + [Description], + (CAST(MetaData as XML)).value('(CUSTOMSCRIPTGUID)[1]', 'uniqueidentifier') as [ScriptGUID] +from dbo.CustomAction + where ClassName = 'Strata.X.CustomActions.RunCustomScript' +UNION ALL +select + 'Workflow Condition', + WFM.Name + ' - ' + WFS.Name, + (CAST(WFC.MetaData as XML)).value('(//SOURCEPARAMETERS/SCRIPTGUID)[1]', 'uniqueidentifier') as [ScriptGUID] +from dbo.WFCondition WFC + inner join WFConditionSet WFCS on WFC.ConditionSetGUID = WFCS.ConditionSetGUID + inner join WFTransition WFT on WFT.ConditionSetGUID = WFCS.ConditionSetGUID + inner join WFWorkflowStep WFS on WFS.WorkflowStepGUID = WFT.WorkflowStepFromGUID + inner join WFWorkflowMap WFM on WFM.WorkflowMapGUID = WFS.WorkflowMapGUID + where WFC.ClassName = 'Strata.X.Biz.Workflow.Conditions.CalculatedValue' +UNION ALL +select + 'Scheduled Task', + [Name], + (CAST(SetupXML as XML)).value('(//CUSTOMSCRIPTSCHEDULEDTASKSETUP/CUSTOMSCRIPTGUID)[1]', 'uniqueidentifier') as [ScriptGUID] +from dbo.TEScheduledTask + where AssemblyQualifiedName like 'Strata.X.Biz.ScheduledTasks.CustomScriptScheduledTask%' +GO + + +--------------------------------------------- + +-- dbo.viewDataCenterDimensionConfig +CREATE VIEW dbo.viewDataCenterDimensionConfig +AS +WITH DimensionConfig AS +( + SELECT c.DimensionName, c.DataCenterPageName, + RIGHT(stepExisting.[Url], LEN(stepExisting.[Url])-1) StepURLExisting, + CONVERT(VARCHAR(36),stepExisting.StepGUID) StepGUIDExisting, + RIGHT(stepNew.[Url], LEN(stepNew.[Url])-1) StepURLNew, + CONVERT(VARCHAR(36),stepNew.StepGUID) StepGUIDNew + FROM dbo.DataCenterDimensionConfig c + LEFT JOIN dbo.SystemCenterStep stepExisting ON c.SystemCenterStepGlobalIDExisting = stepExisting.GlobalID AND c.SystemCenterStepGlobalIDExisting != '' + LEFT JOIN dbo.SystemCenterStep stepNew ON c.SystemCenterStepGlobalIDNew = stepNew.GlobalID AND c.SystemCenterStepGlobalIDNew != '' +) +SELECT DimensionConfig.DimensionName, +'/DataCenter/Configuration/' + DimensionConfig.DataCenterPageName +'?dimCode=' AS DataCenterURL, +ISNULL(DimensionConfig.StepURLExisting + '?step=' + DimensionConfig.StepGUIDExisting,'') SystemCenterURLExistingMembers, +ISNULL(DimensionConfig.StepURLNew + '?step=' + DimensionConfig.StepGUIDNew,'') SystemCenterURLNewMembers +FROM DimensionConfig +GO + + +--------------------------------------------- + +-- dbo.viewDataCenterDimensionModules +CREATE VIEW dbo.viewDataCenterDimensionModules AS + SELECT d.GlobalID, d.SQLSchemaName, d.SQLObjectName, keyAttr.SQLColumnName KeyColumnName, a.SQLColumnName, f.[Name] AS ModuleName, f.Abbreviation AS Abbreviation + FROM dbo.DataCenterDimensionConfig dcDim + INNER JOIN dbo.ScoreDimension d ON dcDim.DimensionName = d.GlobalID + INNER JOIN dbo.ScoreDimensionGroup dg ON d.DimensionGUID = dg.DimensionGUID + INNER JOIN dbo.ScoreAttribute a ON a.DimensionGroupGUID = dg.DimensionGroupGUID + INNER JOIN dbo.ScoreAttribute keyAttr ON d.DefaultKeyGUID = keyAttr.AttributeGUID + INNER JOIN fw.DimFramework f ON f.Abbreviation = + CASE + WHEN REPLACE(a.SQLColumnName, 'IsDefined', '') = 'CI' THEN 'CCI' + WHEN REPLACE(a.SQLColumnName, 'IsDefined', '') = 'CAP' THEN 'CM' + WHEN REPLACE(a.SQLColumnName, 'IsDefined', '') = 'PR' THEN 'PI' + WHEN REPLACE(a.SQLColumnName, 'IsDefined', '') = 'FW' THEN 'GM' + ELSE REPLACE(a.SQLColumnName, 'IsDefined', '') + END + + WHERE a.SQLColumnName IN ( + 'CAPIsDefined', + 'CIIsDefined', + 'DSSIsDefined', + 'FWIsDefined', + 'MRIsDefined', + 'OBIsDefined', + 'PRIsDefined', + 'SPIsDefined' + ) + AND NOT (d.GlobalID = 'Account' AND a.SQLColumnName = 'CAPIsDefined') +GO + + +--------------------------------------------- + +-- dbo.viewDataDictionary +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-10-13 IP D-06327 Change view from using ad-hod calculation of ClientField to precalculated field +** 2 2019-05-07 DF B-23035 Add ConfigID to apply simple security assigned to IntConfig table +*************************************************************/ +CREATE VIEW [dbo].[viewDataDictionary] AS + +with SharedPart AS ( + select + idm.DataInterfaceMapID, + f1.FieldName as ClientFieldName, + isf.SourceSystem as ClientSourceSystem, + isfd.ClientField, + isf.Name as DataSet, + f1.GivenScoreAttributeGUID, + f1.ScoreKeyGUID, + f1.IsMeasure, + f1.IsKey, + dis.SectionTypeVal, + dis.ScoreGuid, + dis.Name as SectionName, + f1.IsHidden, + ic.ConfigID ConfigID, + ic.Name as ImportConfiguration, + IsNull(icc.ClientComment, '') as ClientComments, + IsNull(icc.DateModifiedUtc, GETUTCDATE()) as DateModifiedUtc, + IsNull(icc.ModifiedUserGUID, '00000000-0000-0000-0000-000000000000') as ModifiedUserGUID, + IsNull(up.NameFull, '') as ModifiedUserName, + CASE + WHEN isf.MatchModeVal = 2 THEN isf.PartialMatchString + ELSE isf.ExpectedFileName + END as ClientFile, + isfd.SourceColumnId, + dif.DataInterfaceID + from IntDataInterfaceField f1 + join IntDataInterfaceSection dis on dis.DataInterfaceSectionID=f1.DataInterfaceSectionID + join IntDataInterface dif on dis.DataInterfaceID=dif.DataInterfaceID + join IntConfig ic on ic.DataInterfaceID=dif.DataInterfaceID and ic.IsHidden = 0 + join IntTransformation it on it.ConfigID=ic.ConfigID + cross apply intGetTransformationSourceFileList(it.TransformationID) tsfl + join IntSourceFile isf on isf.SourceFileID = tsfl.SourceFileID + join IntDataInterfaceMap idm on f1.DataInterfaceFieldID=idm.DataInterfaceFieldID + join IntSourceField isfd on isfd.DataSourceID=it.TransformationID and idm.SourceColumnID=isfd.SourceColumnID + left join intClientComment icc on icc.DataInterfaceMapID = idm.DataInterfaceMapID + left join UserProfile up on up.UserGUID = icc.ModifiedUserGUID + where f1.IsHidden = 0) + + select distinct sp.DataInterfaceMapID, sa.FriendlyName as FieldName, sa.[Description] as [Description], sd.FriendlyName as DimensionName, + sp.ClientFieldName, [dbo].[GetSQLColumnFullType](sa.ColumnType, sa.MaxLength, sa.Scale, sa.Precision) as [Type], IsNull(sas.IsCustom, 0) as IsCustom, + sp.DateModifiedUtc, sp.ModifiedUserGUID, sp.ModifiedUserName, sp.ClientComments, sa.AttributeGuid as ScoreGuid, sp.ClientSourceSystem, sp.ClientField, + sp.ConfigID, sp.ImportConfiguration, sp.DataSet, sp.ClientFile, sp.SectionName, IsNull(ex.ExampleValue, '') as ExampleValue, GivenScoreAttributeGUID + from SharedPart sp + join ScoreAttribute sa on sa.AttributeGuid=sp.GivenScoreAttributeGUID and sp.IsMeasure=0 and SectionTypeVal=0 + join ScoreDimension sd on sd.DimensionGuid=sp.ScoreGuid + left join ScoreAttributeSetting sas on sas.AttributeGuid=sa.AttributeGuid + left join [dbo].[DataDictionaryFieldValueExample] ex on ex.ScoreGUID = sa.AttributeGuid + where not exists ( + select * from SharedPart sp2 + join ScoreDataTableKeyLink dtl on sp2.DataInterfaceID=sp.DataInterfaceID and dtl.KeyGuid=sp2.ScoreKeyGUID and dtl.DataTableGuid=sp2.ScoreGuid + and sp2.GivenScoreAttributeGuid=sp.GivenScoreAttributeGuid + join ScoreAttribute sa on sa.AttributeGuid=sp2.GivenScoreAttributeGUID + join ScoreDataTable dt on dt.DataTableGuid=dtl.DataTableGuid) + + union all + + select distinct sp.DataInterfaceMapID, sm.FriendlyName as FieldName, sm.[Description] as [Description], dt.FriendlyName as DimensionName, + sp.ClientFieldName, [dbo].[GetSQLColumnFullType](sm.ColumnTypeValue, sm.MaxLength, sm.Scale, sm.Precision) as [Type], IsNull(sms.IsCustom, 0) as IsCustom, + sp.DateModifiedUtc, sp.ModifiedUserGUID, sp.ModifiedUserName, sp.ClientComments, sm.MeasureGuid as ScoreGuid, sp.ClientSourceSystem, sp.ClientField, + sp.ConfigID, sp.ImportConfiguration, sp.DataSet, sp.ClientFile, sp.SectionName, IsNull(ex.ExampleValue, '') as ExampleValue, GivenScoreAttributeGUID + from SharedPart sp + join ScoreMeasure sm on sm.MeasureGuid=sp.GivenScoreAttributeGUID and sp.IsMeasure=1 + join ScoreDataTable dt on dt.DataTableGuid=sm.DataTableGuid + left join ScoreMeasureSetting sms on sms.MeasureGuid=sm.MeasureGuid + left join [dbo].[DataDictionaryFieldValueExample] ex on ex.ScoreGUID = sm.MeasureGuid + + union all + + select distinct sp.DataInterfaceMapID, + case when SectionTypeVal = 0 then sa.FriendlyName else sd.FriendlyName + ' - ' + sa.FriendlyName end as FieldName, + dtl.[Description] as [Description], dt.FriendlyName as DimensionName, + sp.ClientFieldName, [dbo].[GetSQLColumnFullType](sa.ColumnType, sa.MaxLength, sa.Scale, sa.Precision) as [Type], IsNull(sks.IsCustom, 0) as IsCustom, + sp.DateModifiedUtc, sp.ModifiedUserGUID, sp.ModifiedUserName, sp.ClientComments, dtl.dataTableKeyLinkGuid as ScoreGuid, sp.ClientSourceSystem, sp.ClientField, + sp.ConfigID, sp.ImportConfiguration, sp.DataSet, sp.ClientFile, sp.SectionName, IsNull(ex.ExampleValue, '') as ExampleValue, GivenScoreAttributeGUID + from SharedPart sp + join ScoreDataTableKeyLink dtl on dtl.KeyGuid=sp.ScoreKeyGUID and dtl.DataTableGuid=sp.ScoreGuid + join ScoreAttribute sa on sa.AttributeGuid=sp.GivenScoreAttributeGUID + join ScoreDimensionGroup sdg on sdg.DimensionGroupGuid=sa.DimensionGroupGuid + join ScoreDimension sd on sd.DimensionGuid=sdg.DimensionGuid + join ScoreDataTable dt on dt.DataTableGuid=dtl.DataTableGuid + left join ScoreKeyLinkSetting sks on sks.KeyGuid=dtl.KeyGuid and sks.DataTableGuid=dtl.DataTableGuid + left join [dbo].[DataDictionaryFieldValueExample] ex on ex.ScoreGUID = sp.GivenScoreAttributeGUID +GO + + +--------------------------------------------- + +-- dbo.viewDataView +CREATE view [dbo].[viewDataView] + as + select + DV.DataViewGUID, + DV.Name, + DV.SQLViewName, + DV.SecurityColumns, + coalesce(S.name, 'dbo') as SchemaName, + coalesce(V.name, '???') as ViewName, + case when coalesce(C.name, '???') = '???' then 0 else 1 end as SecurityColumnsExistInSQL + from + DataView DV + left join sys.schemas S on replace(replace(DV.SQLViewName, '[', ''), ']', '') like (S.name + '.%') + left join sys.views V on coalesce(S.schema_id, (select SDef.schema_id from sys.schemas SDef where SDef.name = 'dbo')) = V.schema_id and V.name = replace(replace(replace(REPLACE(DV.SQLViewName, '[' + coalesce(S.name, 'dbo') + '].', ''), coalesce(S.name, 'dbo') + '.', ''), '[', ''), ']', '') + left join sys.columns C on C.object_id = V.object_id and C.name = DV.SecurityColumns + --where DV.SecurityColumns != '' +GO + + +--------------------------------------------- + +-- dbo.viewDesktopParameter_Broken +create view dbo.viewDesktopParameter_Broken +as + select + dp.* + from + DesktopParameter dp + where + ColumnName != AttributeID + and not exists(select 1 from REReport r inner join viewRESQLReportRegisteredAttribute_ByReport ra on ra.ReportGUID = r.ReportGUID and cast(ra.AttributeGUID as nvarchar(36)) = dp.AttributeID and ltrim(ra.ColumnName) = ltrim(dp.ColumnName) where dp.ReportGuidsCSV like '%' + cast(r.ReportGUID as nvarchar(36)) + '%') +GO + + +--------------------------------------------- + +-- dbo.viewDesktopTemplateByUser +Create view [dbo].viewDesktopTemplateByUser +as + +select + up.UserGUID, + up.UserName as UserName, + up.NameFull as UserFullName, + dt.DesktopTemplateGUID, + dt.Name as DesktopTemplate, + link.IsVisible, + case when us.Setting = dt.DesktopTemplateGUID then 1 else 0 end as IsDefault +from + DesktopTemplateUserLink link + inner join UserProfile up on link.UserGUID=up.UserGUID + inner join DesktopTemplate dt on dt.DesktopTemplateGUID = link.DesktopTemplateGUID + inner join UserSetting us on us.UserGUID = up.UserGUID and us.Name = 'DESKTOPDEFAULTTEMPLATE' +GO + + +--------------------------------------------- + +-- dbo.viewDimRiskOutputs +CREATE view [dbo].[viewDimRiskOutputs] as +select ROW_NUMBER() OVER(ORDER BY rrd.RiskConfigOutputName ASC) as RowID + , newid() as MemberGUID + , rrd.OutputUniqueID + , rrd.RiskResultName + , rrd.RiskConfigOutputName + ' - ' + rrd.RiskResultName as RiskConfigOutputName + , rrd.RiskResultGUID + , 0 as IsDeleted +from [dbo].[viewSR2RiskResultDetail] rrd +group by rrd.OutputUniqueID, rrd.RiskResultName, rrd.RiskConfigOutputName, RiskResultGUID +GO + + +--------------------------------------------- + +-- dbo.viewDimSensitivityOutputs +CREATE view [dbo].[viewDimSensitivityOutputs] as +select ROW_NUMBER() OVER(ORDER BY srd.SensitivityConfigOutputName ASC) as RowID + , newid() as MemberGUID + , srd.OutputUniqueID + , srd.SensitivityResultName + , srd.SensitivityConfigOutputName + ' - ' + srd.SensitivityResultName As SensitivityConfigOutputName + , srd.SensitivityResultGUID + , 0 as IsDeleted +from [dbo].[viewSR2SensitivityResultDetail] srd +group by srd.OutputUniqueID, srd.SensitivityResultName, srd.SensitivityConfigOutputName, srd.SensitivityResultGUID +GO + + +--------------------------------------------- + +-- dbo.viewEMFFillIns +CREATE view [dbo].[viewEMFFillIns] as --with schemabinding as +select + ModelGUID, + p.Name as PlanName, + PlaceholderMemberGuid, + phm.Name as PlaceholderName, + FilledInMemberGuid, + fi.name as FillInName, + phm.sortorderfullpath as PlaceholderSort, + fi.SortOrderFullPath as FillinSort, + phmp.listmemberguid as PlaceholderSectionGUID, + phmp.Name as PlaceholderSection +from + dbo.emffillin efi (readuncommitted) + inner join dbo.XPlan p (readuncommitted) on p.PlanGUID = efi.ModelGUID + inner join dbo.securelistmember phm (readuncommitted) on efi.placeholdermemberguid = phm.listmemberguid + inner join dbo.SecureListMember phmp (readuncommitted) on phm.ParentListMemberGUID = phmp.ListMemberGUID + inner join dbo.securelistmember fi (readuncommitted) on efi.filledinmemberguid = fi.listmemberguid +GO + + +--------------------------------------------- + +-- dbo.viewEMFFillInsPossibleDupes +CREATE view [dbo].[viewEMFFillInsPossibleDupes] as --with schemabinding as +--select * from viewEMFfillins fi +--where +--exists ( +-- select 1 +-- from emffillin fidupe +-- group by modelguid, filledinmemberguid +-- having +-- fi.modelguid = fidupe.modelguid +-- and fi.filledinmemberguid = fidupe.filledinmemberguid +-- and count(*) > 1 +-- ) +select + modelguid, placeholdermemberguid, filledinmemberguid, planname,placeholdername, fillinname +from dbo.viewemffillins vfi +where + exists ( + select modelguid, filledinmemberguid from dbo.emffillin fi group by modelguid, filledinmemberguid + having count(*) > 1 + and fi.modelguid = vfi.modelguid and fi.filledinmemberguid = vfi.filledinmemberguid + ) +GO + + +--------------------------------------------- + +-- dbo.viewEMFFillinsOutOfOrder +CREATE view [dbo].[viewEMFFillinsOutOfOrder] as --with schemabinding as +select + fi.SortedPHIndex , + fi.ModelGUID, + fi.PlanName, + fi.PlaceholderMemberGuid, + fi.PlaceholderName, + fi.FilledInMemberGuid, + fi.FillInName, + fi.PlaceholderSort, + fi.FillinSort, + fi.PlaceholderSectionGUID, + fi.PlaceholderSection, + REPL.PlaceholderMember as SortedPHMember, REPL.PlaceholderMemberGUID as SortedPHMemberGUID +from + dbo.viewEMFFillinsSorted FI + left join dbo.viewPlaceholders REPL on FI.PlaceholderSectionGUID = REPL.PlaceholderParentMemberGUID + and FI.SortedPHIndex = REPL.PHIndex +where + FI.PlaceholderMemberGuid <> REPL.PlaceholderMemberGUID +GO + + +--------------------------------------------- + +-- dbo.viewEMFFillinsSorted +CREATE view [dbo].[viewEMFFillinsSorted] as --with schemabinding as +select + row_number() over (partition by fi.modelguid, + fi.placeholdersection order by fi.fillinsort) -1 as SortedPHIndex , + ModelGUID, + PlanName, + PlaceholderMemberGuid, + PlaceholderName, + FilledInMemberGuid, + FillInName, + PlaceholderSort, + FillinSort, + PlaceholderSectionGUID, + PlaceholderSection +from + dbo.viewemffillins fi +GO + + +--------------------------------------------- + +-- dbo.viewEMFFillinsUsage +create view viewEMFFillinsUsage +as +select + PD.Name as Dimension, + P.Name as Section, + (select COUNT(*) from SecureListMember PC where PC.ParentListMemberGUID = P.ListMemberGUID) as SectionChildCount, + coalesce((select MAX(U.UsedCount) from(select FI.ModelGUID, LM.ParentListMemberGUID, COUNT(*) as UsedCount from EMFFillIn FI inner join SecureListMember LM on LM.ListMemberGUID = FI.PlaceholderMemberGUID and LM.ParentListMemberGUID = P.ListMemberGUID group by FI.ModelGUID, LM.ParentListMemberGUID) U), 0) as UsedCount +from + SecureListMember P + inner join SecureList PD on PD.ListGUID = P.ListGUID +where + P.OutlineLevel = 0 + and (select COUNT(*) from SecureListMember PC where PC.ParentListMemberGUID = P.ListMemberGUID) > 0 +GO + + +--------------------------------------------- + +-- dbo.viewEMFModelDataConfigDimensionLinkDetail +--Author: gforeman +--Branch: DSS +--Forward +CREATE view viewEMFModelDataConfigDimensionLinkDetail as +select + dbo.GetFolderFullPath(mdc.FolderGUID) as FolderFullpath, + mdc.Name,sl.Name as DimensionName, + mdc.ModelDataConfigGUID, + sl.ListGUID as DimensionGUID, + case when sl.ListGUID = mdc.FormatOverrideDimensionGUID then 1 else 0 end as IsFormatOverride, + sl.IsSecured, + sl.IsPlaceholder, + fisl.ListGUID as FillInDimensionGUID, + fisl.Name as FillInDimensionName, + mdcdl.IsModelKey +from + emfmodeldataconfig mdc + inner join EMFModelDataConfigDimensionLink mdcdl on mdc.ModelDataConfigGUID = mdcdl.ModelDataConfigGUID + inner join SecureList sl on mdcdl.DimensionGUID = sl.ListGUID + left join securelist fisl on sl.FillInDimensionGUID = fisl.ListGUID +GO + + +--------------------------------------------- + +-- dbo.viewEMFModelDataLink +CREATE view [dbo].[viewEMFModelDataLink] as --with schemabinding as +select + p.PlanGUID as ModelGUID, + p.Name as ModelName, + p.PlanTypeGUID as PlanTypeGUID, + pt.Name as PlanTypeName, + mt.ModelTemplateGUID, + mt.Name as ModelTemplateName, + ls.LinkSourceGUID, + ls.Name as LinkSourceName, + mdl.ParentModelGUID, + pp.Name as ParentModelName, + pp.PlanTypeGUID as ParentPlanTypeGUID, + ppt.Name as ParentPlanTypeName +from + XPlan p + left join EMFModelTemplate mt on p.ModelTemplateGUID = mt.ModelTemplateGUID + left join PlanType pt on p.PlanTypeGUID = pt.PlanTypeGUID + left join EMFModelTemplateLinkSource ls on mt.ModelTemplateGUID = ls.ModelTemplateGUID + left join EMFModelDataLink mdl on ls.LinkSourceGUID = mdl.LinkSourceGUID and p.PlanGUID = mdl.ModelGUID + left join XPlan pp on mdl.ParentModelGUID = pp.PlanGUID + left join PlanType ppt on pp.PlanTypeGUID = ppt.PlanTypeGUID +GO + + +--------------------------------------------- + +-- dbo.viewEMFModelTemplateExpansion +CREATE view [dbo].[viewEMFModelTemplateExpansion] as +select + map.*, + slm.ListGUID as DimensionGUID, + ws.ModelTemplateGUID, + ws.name as SheetName, + cell.ExcelSheetGUID as WorksheetGUID, + cell.Row as Row1OneBased, + cell.Row2 as Row2OneBased, + cell.Col as ColOneBased +from + EMFModelTemplateExpansion map + inner join SecureListMember slm on map.DimensionMemberGUID = slm.ListMemberGUID + inner join MEExcelCell cell on map.CellGUID = cell.ExcelCellGUID --left for backwards compat :( + inner join EMFModelTemplateWorksheet ws on cell.ExcelSheetGUID = ws.WorksheetGUID --left for backwards compat :( + + + --left join MEExcelSheet sheet on cell.ExcelSheetGUID = sheet.ExcelSheetGUID +GO + + +--------------------------------------------- + +-- dbo.viewEMFModelTemplateFormFieldMapping +CREATE view [dbo].[viewEMFModelTemplateFormFieldMapping] as +select + map.FormFieldGUID, + map.[CellGUID], + ws.ModelTemplateGUID, + ws.name as WorksheetName, + cell.ExcelSheetGUID as WorksheetGUID, + cell.Row, + cell.Col +from + EMFModelTemplateFormFieldMapping map + inner join MEExcelCell cell on map.CellGUID = cell.ExcelCellGUID + inner join EMFModelTemplateWorksheet ws on cell.ExcelSheetGUID = ws.WorksheetGUID +GO + + +--------------------------------------------- + +-- dbo.viewEMFModelTemplateFormFieldMappingData +CREATE view [dbo].[viewEMFModelTemplateFormFieldMappingData] as +SELECT + map.CellGUID, + MAP.ModelTemplateGUID, + map.WorksheetGUID, + map.WorksheetName, + map.Row -1 as RowZeroBased, + map.Col -1 as ColZeroBased, + FF.FormFieldGUID, + '' as Value +FROM + viewEMFModelTemplateFormFieldMapping MAP + INNER JOIN FE2FormField FF ON FF.formfieldguid = map.formfieldguid +GO + + +--------------------------------------------- + +-- dbo.viewEMFModelTemplateLastPublished +CREATE view viewEMFModelTemplateLastPublished as +select + mt.ModelTemplateGUID, + mt.Name, + isnull(MAX(DATETIMESTAMP), cast('2000-01-01' as datetime)) as LastPublished +from + EMFModelTemplate mt + left join HistoryItem hi on mt.ModelTemplateGUID = hi.OBJECTGUID +group by + mt.ModelTemplateGUID, + mt.Name +GO + + +--------------------------------------------- + +-- dbo.viewEMFModelTemplateLinkSource +CREATE view [dbo].[viewEMFModelTemplateLinkSource] as + + +select + mt.name as TemplateName, + ls.name as LinkSourceName, + mdc.name as StructureName, + st.name as SubtableName, + sc.FriendlyName as CompositeName, + sd1.FriendlyName as ScoreMappingDataTableName, + sd2.FriendlyName as ScoreDataDataTableName, + mt.ModelTemplateGUID, + ls.LinkSourceGUID, + st.SubtableGUID, + mdc.modeldataconfigguid as StructureGUID, + sc.CompositeGUID, + sd1.datatableguid as ScoreMappingDataTableGUID, + sd2.datatableguid as ScoreDataDataTableGUID +from + emfmodeltemplate mt + inner join emfmodeltemplatelinksource ls on mt.modeltemplateguid = ls.modeltemplateguid + left join emfsubtable st on ls.parentsubtableguid = st.subtableguid + left join emfmodeldataconfig mdc on isnull(st.modeldataconfigguid,ls.parentmodeldataconfigguid) = mdc.modeldataconfigguid + left join scorecomposite sc on ls.parentscorecompositetableguid = sc.compositeguid + left join scoredatatable sd1 on sc.datatableguid1 = sd1.datatableguid + left join scoredatatable sd2 on sc.datatableguid2 = sd2.datatableguid +GO + + +--------------------------------------------- + +-- dbo.viewEMFModelTemplateMDCs +create view viewEMFModelTemplateMDCs as +select ls.modeltemplateguid, coalesce(st.MODELDATACONFIGGUID,ls.parentmodeldataconfigguid) as modeldataconfigguid from EMFModelTemplateLinkSource ls left join EMFSubtable st on ls.ParentSubtableGUID = st.SUBTABLEGUID +GO + + +--------------------------------------------- + +-- dbo.viewEMFModelTemplateNewLabelsOnly +create view viewEMFModelTemplateNewLabelsOnly +as +select + mt2.modeltemplateguid, + + case when + mt2.isnewlabelsonly = 1 + or not exists ( + select 1 + from + EMFModelTemplate mt + inner join EMFModelTemplateLinkSource ls on mt.ModelTemplateGUID = ls.ModelTemplateGUID + inner join EMFModelDataConfigMeasureLink ml on ls.ParentModelDataConfigGUID = ml.ModelDataConfigGUID + inner join EMFMeasure m on ml.MeasureGUID = m.MEASUREGUID + where + m.IsPlaceholderLabel = 1 + and mt.modeltemplateguid = mt2.modeltemplateguid + ) + then cast(1 as bit) + else + cast(0 as bit) end as IsNewLabelsOnly +from + emfmodeltemplate mt2 +GO + + +--------------------------------------------- + +-- dbo.viewEMFModelTemplatePlaceholderLabelMapping +CREATE view [dbo].[viewEMFModelTemplatePlaceholderLabelMapping] as +select + map.[MappingGUID] + ,map.[PlaceholderDimensionGUID] + ,map.[PlaceholderMemberGUID] + ,map.[LabelPropertyGUID] + ,map.[IsHidingRow] + ,map.[IsHidingCol] + ,map.[IsClearingRow] + ,map.[IsClearingCol] + ,map.[RowExpanded] + ,map.[CellGUID] + ,map.[IsUserMapped], + ws.modeltemplateguid as BookGUID, + ws.name as SheetName, + cell.ExcelSheetGUID, + cell.Row, + cell.Col +from + EMFModelTemplatePlaceholderLabelMapping map (readuncommitted) + inner join MEExcelCell cell (readuncommitted) on map.CellGUID = cell.ExcelCellGUID + inner join EMFModelTemplateWorksheet ws (readuncommitted) on cell.ExcelSheetGUID = ws.WorksheetGUID +GO + + +--------------------------------------------- + +-- dbo.viewEMFModelTemplatePlaceholderLabelMappingDetail +CREATE view [dbo].[viewEMFModelTemplatePlaceholderLabelMappingDetail] as +select + map.[MappingGUID] + ,map.[PlaceholderDimensionGUID] + ,phsl.Name as PlaceholderDimensionName + ,map.[PlaceholderMemberGUID] + ,phslm.Name as PlaceholderMemberName + ,map.[LabelPropertyGUID] + ,case when map.LabelPropertyGUID = dbo.ZeroGUID() then 'Name' else slp.name end as LabelPropertyName + ,map.[IsHidingRow] + ,map.[IsHidingCol] + ,map.[IsClearingRow] + ,map.[IsClearingCol] + ,map.[RowExpanded] + ,map.[CellGUID] + ,map.[IsUserMapped], + ws.modeltemplateguid as BookGUID, + mt.Name as TemplateName, + ws.name as SheetName, + cell.ExcelSheetGUID, + cell.Row, + cell.Col +from + EMFModelTemplatePlaceholderLabelMapping map + inner join MEExcelCell cell on map.CellGUID = cell.ExcelCellGUID --left for backwards compat :( + inner join EMFModelTemplateWorksheet ws on cell.ExcelSheetGUID = ws.WorksheetGUID --left for backwards compat :( + left join SecureListMember phslm on map.PlaceholderMemberGUID = phslm.ListMemberGUID + left join SecureList phsl on map.PlaceholderDimensionGUID = phsl.ListGUID + left join SecureListProperty slp on map.LabelPropertyGUID = slp.ListPropertyGUID + left join EMFModelTemplate mt on ws.ModelTemplateGUID = mt.ModelTemplateGUID + --left join MEExcelSheet sheet on cell.ExcelSheetGUID = sheet.ExcelSheetGUID +GO + + +--------------------------------------------- + +-- dbo.viewEMFModelTemplatePossibleLinks +create view viewEMFModelTemplatePossibleLinks as +select distinct + tgt.ModelTemplateGuid as TargetModelTemplateGuid, + tgt.ModelDataConfigGuid as TargetModelDataConfigGuid, + tgt.IsSubtable as TargetIsSubtable, + isnull(tgt.SubtableGuid, dbo.zeroguid()) as TargetSubtableGuid +from + (select + ls.ModelTemplateGUID, mdc.ModelDataConfigGUID, case when st.NAME is null then cast(0 as bit) else cast(1 as bit) end as IsSubtable, st.SUBTABLEGUID + from + [dbo].[EMFModelTemplateLinkSource] ls + left join [dbo].[EMFSubtable] st on ls.ParentSubtableGUID = st.SUBTABLEGUID + left join [dbo].[EMFModelDataConfig] mdc on isnull(st.MODELDATACONFIGGUID, ls.ParentModelDataConfigGUID) = mdc.ModelDataConfigGUID + where + ls.IsSelf = 0 + ) tgt + inner join + (select + ls.ModelTemplateGUID, mdc.ModelDataConfigGUID, ls.Name + from + [dbo].[EMFModelTemplateLinkSource] ls + inner join [dbo].[EMFModelDataConfig] mdc on ls.ParentModelDataConfigGUID = mdc.ModelDataConfigGUID + where + ls.IsSelf = 1 + ) src on src.ModelDataConfigGuid = tgt.ModelDataConfigGuid +GO + + +--------------------------------------------- + +-- dbo.viewEMFPlaceholderSummary +CREATE view viewEMFPlaceholderSummary as +select + sl.ListGUID as PHDimensionGUID, + sl.name as PHDimensionName, +slm.ListMemberGUID as PHSectionGUID , +slm.name as PHSectionName, +(select count(*) from securelistmember cslm where cslm.parentlistmemberguid = slm.listmemberguid) as Children, +(select top 1 listmemberguid from securelistmember cslm where cslm.parentlistmemberguid = slm.listmemberguid order by cslm.SortOrderFullPath) as FirstPHMemberGUID, + slm.SortOrderFullPath +from + securelistmember slm + inner join securelist sl on slm.listguid = sl.listguid +where + sl.isplaceholder = 1 + and slm.outlinelevel = 0 +GO + + +--------------------------------------------- + +-- dbo.viewEMFStructuresInTemplates +CREATE VIEW [dbo].[viewEMFStructuresInTemplates] +AS +SELECT + TE.ModelTemplateGUID, + TE.Name As [Template Name], + COALESCE(MDC.ModelDataConfigGUID, SV.SubtableGUID, COMP.CompositeGUID) as [StructureGUID], + COALESCE(MDC.Name, SV.Name, COMP.FriendlyName) as [Structure Name], + CASE + WHEN TLS.ParentModelDataConfigGUID <> '00000000-0000-0000-0000-000000000000' THEN 'EMF Structure' + WHEN TLS.ParentSubtableGUID <> '00000000-0000-0000-0000-000000000000' THEN 'EMF Subtable' + WHEN TLS.ParentScoreCompositeTableGUID <> '00000000-0000-0000-0000-000000000000' Then 'Score Composite' + END AS [Config Type] +FROM + dbo.EMFModelTemplate AS TE + INNER JOIN dbo.EMFModelTemplateLinkSource AS TLS ON TLS.ModelTemplateGUID = TE.ModelTemplateGUID + LEFT JOIN dbo.EMFModelDataConfig MDC ON MDC.ModelDataConfigGUID = TLS.ParentModelDataConfigGUID + LEFT JOIN dbo.EMFSubtable SV ON SV.SUBTABLEGUID = TLS.ParentSubtableGUID + LEFT JOIN dbo.ScoreComposite COMP ON COMP.CompositeGUID = TLS.ParentScoreCompositeTableGUID +GO + + +--------------------------------------------- + +-- dbo.viewEmailMessage +CREATE view [dbo].[viewEmailMessage] +as + select + M.*, + coalesce(U.NameFull, '') as SenderFullName, + coalesce(U.EmailAddress, '') as SenderEmailAddress + from + [dbo].[EmailMessage] M + left join [dbo].[UserProfile] U (readuncommitted) on U.UserGUID = M.SenderUserGUID +GO + + +--------------------------------------------- + +-- dbo.viewEmailRecipient +CREATE view dbo.viewEmailRecipient +as +select + R.*, + coalesce(coalesce(coalesce(U.NameFull, UG.Name), UR.Name), '') as IdentityFullName +from + EmailRecipient R + left join UserProfile U (readuncommitted) on U.UserGUID = R.IdentityGUID and R.IdentityType = 0 + left join UserGroup UG (readuncommitted) on UG.UserGroupGUID = R.IdentityGUID and R.IdentityType = 1 + left join UserRole UR (readuncommitted) on UR.UserRoleGUID = R.IdentityGUID and R.IdentityType = 2 +GO + + +--------------------------------------------- + +-- dbo.viewFE2FormField +CREATE VIEW [dbo].[viewFE2FormField] +AS +SELECT + FF.*, + isnull(SA.AttributeGUID, dbo.ZeroGUID()) as AttributeGUID, + isnull(SA.IsCopiedWithPlan,0) as IsCopiedWithPlan, + isnull(SA.SQLColumnName, '') as ColumnName, + isnull(SA.ColumnType, 0) as ColumnType, + isnull(SA.Precision, 0) as ColumnPrecision, + isnull(SA.Scale, 0) as ColumnScale, + isnull(SA.MaxLength, 0) as ColumnMaxLength, + ISNULL(SA.IsFormField, 1) as IsAttributeEditable, + case when isnull(SA.IsSecuredLootID, 0) = 1 or isnull(SA.IsSecuredLootGroupID, 0) = 1 then cast(1 as bit) else cast(0 as bit) end as IsAttributeSecured, + isnull(DG.DimensionGUID, dbo.ZeroGUID()) as DimensionGUID, + isnull(DG.SchemaName + '.' + DG.ObjectName, '') as DimensionGroupSQLExpression, + isnull(SD.SQLSchemaName + '.' + SD.SQLObjectName, '') as DimensionSQLExpression, + coalesce(F.PlanTypeGUID, dbo.ZeroGUID()) as PlanTypeGUID, + coalesce(F.FormGUID, dbo.ZeroGUID()) as FormGUID, + isnull(F.IsHidden, 0) as IsDirectoryOnly, + coalesce(FT.Name, '') as FormTab, + coalesce(FT.DisplayOrder, 0) as FormTabDisplayOrder, + coalesce(FS.DisplayOrder, 0) as FormSectionDisplayOrder + +FROM + FE2FormField FF (readuncommitted) + left join [dbo].[ScoreAttribute] SA (readuncommitted) on SA.AttributeGUID = FF.DataSourceGUID + left join [dbo].[ScoreDimensionGroup] DG (readuncommitted) on DG.DimensionGroupGUID = SA.DimensionGroupGUID + left join [dbo].[ScoreDimension] SD (readuncommitted) on SD.DimensionGUID = DG.DimensionGUID + left join [dbo].[FE2FormSection] FS (readuncommitted) on FS.FormSectionGUID = FF.FormSectionGUID + left join [dbo].[FE2FormTab] FT (readuncommitted) on FT.FormTabGUID = FS.FormTabGUID + left join [dbo].[FE2Form] F (readuncommitted) on F.FormGUID = FT.FormGUID +GO + + +--------------------------------------------- + +-- dbo.viewFE2FormFieldComputed +CREATE VIEW dbo.viewFE2FormFieldComputed +AS + select + case when cast(cast(ComputedFieldConfig as xml).query('//IsActive[1]/text()') as nvarchar(10)) = 'true' then cast(1 as bit) else cast(0 as bit) end as IsComputedFieldActive, + cast(cast(cast(ComputedFieldConfig as xml).query('//LastRefreshErrorGUID[1]/text()') as nvarchar(36)) as uniqueidentifier) as LastRefreshErrorGUID, + cast(cast(ComputedFieldConfig as xml).query('//LastRunTime[1]/text()') as nvarchar(100)) as LastRunTimeSeconds, + cast(cast(ComputedFieldConfig as xml).query('//SQL[1]/text()') as nvarchar(max)) as SQL, + cast(cast(ComputedFieldConfig as xml).query('//LastRefreshSQL[1]/text()') as nvarchar(max)) as LastRefreshSQL, + cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int) as CustomSQLType, + case + when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=0 then 'Unspecified' + when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=1 then 'DateCreated' + when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=2 then 'DBSetting' + when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=3 then 'DimensionDriven' + when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=4 then 'FileAttachment' + when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=5 then 'FillinDriven' + when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=6 then 'FormFieldDriven' + when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=7 then 'ModelDriven' + when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=8 then 'Workflow' + when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=9 then 'NotApplicable' + when cast(cast(cast(ComputedFieldConfig as xml).query('//CustomSQLType[1]/text()') as nvarchar(10)) as int)=10 then 'AlwaysUpdate' end as CustomSQLTypeName, + case when cast(cast(ComputedFieldConfig as xml).query('//IsAsynchronous[1]/text()') as nvarchar(5)) = 'true' then cast(1 as bit) else cast(0 as bit) end as IsAsynchronous, + * + from + [dbo].[viewFE2FormField] + where + ComputedFieldClassName != '' +GO + + +--------------------------------------------- + +-- dbo.viewFE2ScriptSnippetHistory +CREATE view [dbo].[viewFE2ScriptSnippetHistory] +AS +select + S.*, + H.Name, + H.Type, + H.ErrorGUID +from + [dbo].[FE2ScriptSnippetHistory] S + inner join [dbo].[viewFE2ScriptUpgradeHistory] H on H.HistoryGUID = S.HistoryGUID +GO + + +--------------------------------------------- + +-- dbo.viewFE2ScriptUpgradeHistory +CREATE view dbo.viewFE2ScriptUpgradeHistory +as + +select + H.HistoryGUID, + 'SQL Object' as Type, + H.SQLObjectName as Name, + H.OldValue, + H.NewValue, + H.RiskLevel, + H.IsComplete, + H.CustomScriptGUID, + H.ErrorGUID + from + [dbo].[FE2ScriptUpgradeHistory] H + where + H.SQLObjectName != '' + union all + select + H.HistoryGUID, + 'Registered Script' as Type, + CS.Name as Name, + H.OldValue, + H.NewValue, + H.RiskLevel, + H.IsComplete, + H.CustomScriptGUID, + H.ErrorGUID + from + [dbo].[FE2ScriptUpgradeHistory] H + inner join [dbo].[CustomScript] CS on CS.CustomScriptGUID = H.CustomScriptGUID + union all + select + H.HistoryGUID, + 'Calculated Field' as Type, + FF.Name as Name, + H.OldValue, + H.NewValue, + H.RiskLevel, + H.IsComplete, + H.CustomScriptGUID, + H.ErrorGUID + from + [dbo].[FE2ScriptUpgradeHistory] H + inner join [dbo].[FEFormField] FF on FF.FORMFIELDGUID = H.CustomScriptGUID +GO + + +--------------------------------------------- + +-- dbo.viewFE2ScriptUpgradeWorkflow +CREATE view dbo.viewFE2ScriptUpgradeWorkflow +as + select + cs.CustomScriptGUID, cs.Name as CustomScriptName, dbo.straggr(distinct wfm.Name, ', ', '') as WorkflowNames + from + WFEventPlanStatement eps (readuncommitted) + inner join [dbo].[CustomAction] ca (readuncommitted) on ca.ActionGUID = eps.StatementGUID + inner join [dbo].[CustomScript] cs (readuncommitted) on ca.Metadata = '' + cast(cs.CustomScriptGUID as nvarchar(36)) + '' + inner join WFEventPlan ep (readuncommitted) on ep.EventPlanGUID = eps.EventPlanGUID + inner join WFWorkflowStep wfs (readuncommitted) on wfs.OnStartEventPlanGUID = ep.EventPlanGUID or wfs.OnEndEventPlanGUID = ep.EventPlanGUID + inner join WFWorkflowMap wfm (readuncommitted) on wfm.WorkflowMapGUID = wfs.WorkflowMapGUID + inner join FE2ScriptUpgradeHistory suh (readuncommitted) on suh.CustomScriptGUID = cs.CustomScriptGUID + group by + cs.CustomScriptGUID, cs.Name + having + count(distinct wfm.Name) > 1 + union all + select + cs.CustomScriptGUID, cs.Name as CustomScriptName, dbo.straggr(distinct wfm.Name, ', ', '') as WorkflowNames + from + WFCondition c (readuncommitted) + inner join [dbo].[CustomScript] cs (readuncommitted) on cast(cast(c.Metadata as xml).query('//CUSTOMSCRIPTGUID[1]/text()') as nvarchar(36)) = cast(cs.CustomScriptGUID as nvarchar(36)) + inner join WFConditionSet wfcs (readuncommitted) on wfcs.ConditionSetGUID = c.ConditionSetGUID + inner join WFEventPlanStatement eps (readuncommitted) on eps.StatementGUID = wfcs.ConditionSetGUID + inner join WFEventPlan ep (readuncommitted) on ep.EventPlanGUID = eps.EventPlanGUID + inner join WFWorkflowStep wfs (readuncommitted) on wfs.OnStartEventPlanGUID = ep.EventPlanGUID + inner join WFWorkflowMap wfm (readuncommitted) on wfm.WorkflowMapGUID = wfs.WorkflowMapGUID or wfs.OnEndEventPlanGUID = ep.EventPlanGUID or wfs.QualifyConditionSetGUID = wfcs.ConditionSetGUID + inner join FE2ScriptUpgradeHistory suh (readuncommitted) on suh.CustomScriptGUID = cs.CustomScriptGUID + group by + cs.CustomScriptGUID, cs.Name + having + count(distinct wfm.Name) > 1 + union all + select + cs.CustomScriptGUID, cs.Name as CustomScriptName, dbo.straggr(distinct wfm.Name, ', ', '') as WorkflowNames + from + WFCondition c (readuncommitted) + inner join [dbo].[CustomScript] cs (readuncommitted) on cast(cast(c.Metadata as xml).query('//CUSTOMSCRIPTGUID[1]/text()') as nvarchar(36)) = cast(cs.CustomScriptGUID as nvarchar(36)) + inner join WFConditionSet wfcs (readuncommitted) on wfcs.ConditionSetGUID = c.ConditionSetGUID + inner join WFTransition t (readuncommitted) on t.ConditionSetGUID = wfcs.ConditionSetGUID + inner join WFWorkflowStep wfs (readuncommitted) on wfs.WorkflowStepGUID = t.WorkflowStepFromGUID + inner join WFWorkflowMap wfm (readuncommitted) on wfm.WorkflowMapGUID = wfs.WorkflowMapGUID + inner join FE2ScriptUpgradeHistory suh (readuncommitted) on suh.CustomScriptGUID = cs.CustomScriptGUID + group by + cs.CustomScriptGUID, cs.Name + having + count(distinct wfm.Name) > 1 +GO + + +--------------------------------------------- + +-- dbo.viewFEFormDataHistory +CREATE VIEW [dbo].[viewFEFormDataHistory] AS +SELECT + HIST.RowID + , HIST.EntityGUID as PlanGUID + ,isnull(fd.name,hist.EntityName) as PlanName + ,HIST.FormFieldGUID + ,ISNULL(ff.name,hist.FormFieldName) as FormFieldName + ,HIST.DateTimeStamp + ,CASE + WHEN FF.FieldType IN (1,2,3,15,17) THEN CAST(HIST.ValueFloat AS NVARCHAR(MAX)) + ELSE HIST.ValueVarChar + END AS [Value] + ,HIST.ValueBit + ,HIST.ValueDate + ,HIST.ValueFloat + ,HIST.ValueGUID + ,HIST.ValueGUIDS + ,HIST.ValueVarChar +FROM + dbo.FEFormDataHistory HIST (readuncommitted) + LEFT JOIN dbo.FE2FormField FF (readuncommitted) ON (hist.FormFieldGUID = FF.FormFieldGUID) + left join XPlan fd (readuncommitted) on HIST.EntityGUID = fd.PlanGUID +GO + + +--------------------------------------------- + +-- dbo.viewFEFormField +--used for framework transfers, which require xml cols to be cast to varchar for cross-db scripting +create view dbo.viewFEFormField +as +SELECT [FormFieldGUID] + ,[GlobalID] + ,[Name] + ,[FieldType] + ,[MaxLength] + ,[MinLength] + ,[DataFormat] + ,[DefaultValue] + ,[HelpText] + ,[IsReadOnly] + ,[HasNumericMaxValue] + ,[NumericMaxValue] + ,[HasNumericMinValue] + ,[NumericMinValue] + ,[StringMask] + ,[DecimalPlaces] + ,[UseThousandsSeparator] + ,[UseNegParentheses] + ,[HasLabel] + ,[LabelDisplayType] + ,[LabelWidth] + ,[IsInDirectory] + ,[SourceType] + ,[SourcePath] + ,[SourceGUID] + ,[Rows] + ,[UsePicker] + ,[DefaultSortOrder] + ,[IsRequired] + ,[Mask] + ,[HelpTextDisplayType] + ,[HasOptionHelpText] + ,[DefaultValueType] + ,[Label] + ,[HasRowNumbers] + ,[FolderGUID] + ,[SpecialFieldType] + ,[SourceDisplayFormat] + ,[ExecutionOrder] + ,[DirectoryName] + ,[ScaleDisplayFactor] + ,[DateCreated] + ,[DateModified] + ,[IsRecordingHistory] + ,[IsCleared] + ,[DisplayFormatOverride] + ,[ResizeOffset] + ,[IsSetupLocked] + ,[IsCoolite] + ,[IsCopied] + ,[RenderType] + ,[RenderThreshold] + ,[RenderComparisonFieldGUID] + ,[RenderComparisonOperator] + ,[RefreshMode] + ,cast([TypeConfigXML] as nvarchar(max)) as [TypeConfigXML] + FROM [dbo].[FEFormField] +GO + + +--------------------------------------------- + +-- dbo.viewFEFormFieldCore +CREATE VIEW [dbo].[viewFEFormFieldCore] as +SELECT [FormFieldGUID] + ,[GlobalID] + ,[Name] + ,[FieldType] + ,[MaxLength] + ,[MinLength] + ,[IsReadOnly] + ,[HasNumericMaxValue] + ,[NumericMaxValue] + ,[HasNumericMinValue] + ,[NumericMinValue] + ,[DecimalPlaces] + ,[UseThousandsSeparator] + ,[UseNegParentheses] + ,[HasLabel] + ,[LabelDisplayType] + ,[LabelWidth] + ,[IsInDirectory] + ,[SourceType] + ,[SourceGUID] + ,[Rows] + ,[UsePicker] + ,[DefaultSortOrder] + ,[IsRequired] + ,[HelpTextDisplayType] + ,[HasOptionHelpText] + ,[DefaultValueType] + ,[HasRowNumbers] + --,[IsInheritingPermissions] + --,[IsAdvancedMode] + ,[FolderGUID] + ,[SpecialFieldType] + ,[ExecutionOrder] + ,[DirectoryName] + ,[ScaleDisplayFactor] + ,[DisplayFormatOverride] + ,[ResizeOffset] + ,[IsSetupLocked] + ,[IsCoolite] + ,[IsCopied] + ,[RenderType] + ,[RenderThreshold] + ,[RenderComparisonFieldGUID] + ,[RenderComparisonOperator] + ,[RefreshMode] + ,[DateCreated] + ,[DateModified] + ,[IsRecordingHistory] + ,[IsCleared] + ,'' as [StringMask] + ,'' as [SourcePath] + ,'' as [Mask] + ,'' as [Label] + ,'' as [SourceDisplayFormat] + ,'' as [DataFormat] + ,'' as [DefaultValue] + ,'' as [HelpText] + FROM [dbo].[FEFormField] +GO + + +--------------------------------------------- + +-- dbo.viewFEFormSectionRule +CREATE view [dbo].[viewFEFormSectionRule] +as +select FormSectionRuleGUID, FormSectionGUID, cast(RuleXML as nvarchar(max)) as RuleXML, Description, RuleType from FEFormSectionRule +GO + + +--------------------------------------------- + +-- dbo.viewFormFieldUsage +CREATE view viewFormFieldUsage +as +select + FF.FormFieldGUID, + FF.Name as FormFieldName, + --FFS.FormDefGUID, + FD.Name as FormName, + --FFS.FormSectionGUID, + FS.Name as FormSectionName +from + FE2FormField FF + inner join [dbo].[FE2FormSection] FS on FS.FormSectionGUID = FF.FormSectionGUID + inner join [dbo].[FE2FormTab] FT on FT.FormTabGUID = FS.FormTabGUID + inner join [dbo].[FE2Form] FD on FT.FormGUID = FD.FormGUID +GO + + +--------------------------------------------- + +-- dbo.viewFramework +CREATE view [dbo].[viewFramework] +AS + SELECT + FrameworkID, Framework, FrameworkSchemaName, ClientSchemaName, Abbreviation + FROM + (SELECT + 1 AS FrameworkID, 'Capital Management' AS Framework, 'cap' AS FrameworkSchemaName, 'clientcap' AS ClientSchemaName, 'CAP' AS Abbreviation + UNION ALL + SELECT + 2 AS FrameworkID, 'Management Reporting' AS Framework, 'mr' AS FrameworkSchemaName, 'clientmr' AS ClientSchemaName, 'MR' AS Abbreviation + UNION ALL + SELECT + 3 AS FrameworkID, 'Productivity Improvement' AS Framework, 'pi' AS FrameworkSchemaName, 'clientpi' AS ClientSchemaName, 'PI' AS Abbreviation + UNION ALL + SELECT + 4 AS FrameworkID, 'Operating Budgeting' AS Framework, 'ob' AS FrameworkSchemaName, 'clientob' AS ClientSchemaName, 'OB' AS Abbreviation + UNION ALL + SELECT + 5 AS FrameworkID, 'Stategic Planning' AS Framework, 'lrfp' AS FrameworkSchemaName, 'clientlrfp' AS ClientSchemaName, 'LRPF' AS Abbreviation) FRAMEWORKS +GO + + +--------------------------------------------- + +-- dbo.viewHistoryItem +create view dbo.viewHistoryItem +as + --casting xml columns to nvarchar so this can be used for cross-server scripts (Alchemy only) + SELECT [HISTORYITEMGUID], [OBJECTGUID], [OBJECTTYPE], [DATETIMESTAMP], [MODIFIERUSERGUID], [CATEGORY], [DESCRIPTION], [USERCOMMENTS], cast([METAXML] as nvarchar(max)) as [METAXML], [VERSION], [MODIFIERUSERNAME], [ITEMCOUNT], [ELAPSEDMS], [TransactionID] + FROM [dbo].[HistoryItem] +GO + + +--------------------------------------------- + +-- dbo.viewIRCChat +CREATE view [dbo].[viewIRCChat] +as +select + C.IRCChatGUID, + C.Name, + C.Description, + C.CreationTime, + C.SQLTableName, + C.AuthorGUID, + C.LastModifiedUserGUID, + C.RowID, + C.HistoryItemGUID, + C.Version, + C.IsChatDeleted, + coalesce(UP.NAMELAST + ', ' + UP.NameFirst, CASE WHEN C.AuthorGUID = dbo.GetSuperUserGUID() THEN 'Strata' else 'Unknown' end) as Author, + coalesce(UP1.NAMELAST + ', ' + UP1.NameFirst, CASE WHEN C.LastModifiedUserGUID = dbo.GetSuperUserGUID() THEN 'Strata' else 'Unknown' end) as LastModifiedBy +from dbo.IRCChat C + left join dbo.UserProfile UP on C.AuthorGUID = UP.UserGUID + left join dbo.UserProfile UP1 on C.LastModifiedUserGUID = UP1.UserGUID +GO + + +--------------------------------------------- + +-- dbo.viewIRCChatMembership +CREATE view [dbo].[viewIRCChatMembership] +AS + select + C.Name as [Chat], + UP.NameLast + ', ' + UP.NameFirst as [UserFullName], + UP.UserName as [UserName], + M.LastCheckinTime as [LastCheckin] + from dbo.IRCChat C + inner join dbo.IRCChatMembership M on C.IRCChatGUID = M.IRCChatGUID + inner join dbo.UserProfile UP on UP.UserGUID = M.UserGUID +GO + + +--------------------------------------------- + +-- dbo.viewImportCSVConfig +CREATE view [dbo].[viewImportCSVConfig] +as +SELECT [ImportCSVConfigGUID] + ,[Name] + ,[Description] + ,cast([ConfigXML] as nvarchar(max)) as ConfigXML + ,[TimeoutSeconds] + FROM [dbo].[ImportCSVConfig] +GO + + +--------------------------------------------- + +-- dbo.viewIntTransaction +CREATE VIEW [dbo].[viewIntTransaction] +AS + with IntTransactionDataAgg as ( + select + TransactionGUID, + SUM(RowsImported) as RowsImported, + SUM(RowsRejected) AS RowsRejected, + case when SUM(cast(IsImportDeleted as int)) > 0 then CAST(1 as bit) else CAST(0 as bit) end as IsImportDeleted, + case when SUM(cast(HasDummyFile as int)) > 0 then CAST(1 as bit) else CAST(0 as bit) end as HasDummyFile, + CAST(MAX(CAST(IsAdhocImport AS INT)) AS BIT) as IsAdhocImport + from + [dbo].[IntTransactionData] + group by + TransactionGUID + ) + select + trn.*, + isnull(cfg.Name, 'Unknown') as ConfigName, + isnull(cfg.IntegrationTypeVal, 0) as IntegrationTypeVal, + DateDiff(second, trn.StartTimeUtc, trn.EndTimeUtc) as Duration, + isnull(usr.NameFirst, case when UserId = '10101010-1111-0000-1111-101010101010' then 'Strata' else 'Unknown' end) as UserNameFirst, + isnull(usr.NameLast, case when UserId = '10101010-1111-0000-1111-101010101010' then 'Strata' else 'Unknown' end) as UserNameLast, + isnull(usr.UserName, case when UserId = '10101010-1111-0000-1111-101010101010' then 'Strata' else 'Unknown' end) as UserName, + isnull(usr.EmailAddress, 'Unknown') as UserEmailAddress, + isnull(td.IsImportDeleted, cast(0 as bit)) as IsImportDeleted, + isnull(td.RowsImported, 0) as RowsImported, + ISNULL(td.RowsRejected, 0) AS RowsRejected, + isnull(td.HasDummyFile, cast(0 as bit)) as HasDummyFile, + ISNULL(td.IsAdhocImport, CAST(0 AS BIT)) AS IsAdhocImport + from + [dbo].[IntTransaction] trn + left join IntTransactionDataAgg td on td.TransactionGUID = trn.TransactionGUID + left join [dbo].[IntConfig] cfg on trn.ConfigID = cfg.ConfigID + left join [dbo].[UserProfile] usr on trn.UserID = usr.UserGUID +GO + + +--------------------------------------------- + +-- dbo.viewKeys +CREATE VIEW dbo.viewKeys +AS +select S.name as SchemaName, O1.name as ObjectName, CST.name as [Name] from sys.key_constraints CST + inner join sys.schemas S on S.schema_id = CST.schema_id + inner join sys.objects O on CST.object_id = O.object_id + inner join sys.objects O1 on O1.object_id = CST.parent_object_id +UNION ALL +select S.name as SchemaName, O1.name as ObjectName, FK.name as [Name] from sys.foreign_keys FK + inner join sys.schemas S on S.schema_id = FK.schema_id + inner join sys.objects O on FK.object_id = O.object_id + inner join sys.objects O1 on O1.object_id = FK.parent_object_id +GO + + +--------------------------------------------- + +-- dbo.viewMDCs +CREATE view [dbo].[viewMDCs] as +select *,'zzEMFModelData_' + lower(replace(cast(modeldataconfigguid as varchar(36)), '-', '_')) as dataName from emfmodeldataconfig +GO + + +--------------------------------------------- + +-- dbo.viewMECell +CREATE view [dbo].[viewMECell] as +select + cell.*, + cell.ExcelCellGUID as CellGUID, + cell.ExcelSheetGUID as SheetGUID, + book.ModelTemplateGUID, + book.Name as TemplateName, + SHEET.Name as WorksheetName, + book.ModelTemplateGUID as BookGUID, --duplicate for backwards compat + book.Name as BookName, --duplicate for backwards compat + sheet.Name as SheetName --duplicate for backwards compat +from + MEExcelCell CELL (readuncommitted) + inner join EMFModelTemplateWorksheet SHEET (readuncommitted) ON SHEET.WorksheetGUID = CELL.ExcelSheetGUID + inner join emfmodeltemplate BOOK (readuncommitted) on BOOK.ModelTemplateGUID = SHEET.ModelTemplateGUID +GO + + +--------------------------------------------- + +-- dbo.viewMEModelRefreshQueue +CREATE view [dbo].[viewMEModelRefreshQueue] +as + select + Q.ModelGUID, + Q.DateTimeStamp, + Q.ErrorLogGUID, + Q.UserName, + Q.Source, + Q.CompositeGUID, + isnull(C.FriendlyName, 'All') as CompositeName, + isnull(P.ModelTemplateGUID, dbo.ZeroGUID()) as ModelTemplateGUID + from + [dbo].[MEModelRefreshQueue] Q with (readuncommitted) + left join [dbo].[XPlan] P with (readuncommitted) on P.PlanGUID = Q.ModelGUID + left join [dbo].[ScoreComposite] C with (readuncommitted) on C.CompositeGUID = Q.CompositeGUID +GO + + +--------------------------------------------- + +-- dbo.viewMEPHSection +-- Forward + +CREATE view [dbo].[viewMEPHSection] as +select + phsc.*, + phdim.FriendlyName as PHDimensionFriendlyName, + fidim.DimensionGUID as FillInDimensionGUID, + fidim.FriendlyName as FillInDimensionFriendlyName +from + dbo.MEPHSection phsc + inner join dbo.ScoreDimension phdim on phsc.PHSectionDimensionGUID = phdim.DimensionGUID + inner join dbo.EMFModelTemplate mt on phsc.ModelTemplateGUID = mt.ModelTemplateGUID + + --is there a better way? + inner join dbo.ScoreDimension fidim on fidim.DimensionGUID = ( + select distinct + sdg2.DimensionGUID + from + EMFModelTemplateLinkSource ls + inner join ScoreComposite sc on ls.ParentScoreCompositeTableGUID = sc.CompositeGUID + inner join ScoreCompositeLink scl on sc.CompositeGUID = scl.CompositeGUID + inner join ScoreAttribute k1 on scl.Key1GUID = k1.AttributeGUID + inner join ScoreDimensionGroup sdg1 on sdg1.DimensionGroupGUID=k1.DimensionGroupGUID + inner join ScoreAttribute k2 on scl.Key2GUID = k2.AttributeGUID + inner join ScoreDimensionGroup sdg2 on sdg2.DimensionGroupGUID=k2.DimensionGroupGUID + where + sdg1.DimensionGUID = phsc.PHSectionDimensionGUID + and ls.ModelTemplateGUID = mt.modeltemplateguid + ) +GO + + +--------------------------------------------- + +-- dbo.viewMEPHSectionAnalysis +CREATE view dbo.viewMEPHSectionAnalysis +as + select + ModelTemplateGUID, + PlaceholderSectionMemberGUID, + MemberName as PlaceholderSectionMemberName, + isnull([1],1) as Decile01, + case when isnull([1],1) < 25 then isnull([1],1) else isnull([2],1) end as Decile02, + case when isnull([1],1) < 25 then isnull([1],1) else isnull([3],1) end as Decile03, + case when isnull([1],1) < 25 then isnull([1],1) else isnull([4],1) end as Decile04, + case when isnull([1],1) < 25 then isnull([1],1) else isnull([5],1) end as Decile05, + case when isnull([1],1) < 25 then isnull([1],1) else isnull([6],1) end as Decile06, + case when isnull([1],1) < 25 then isnull([1],1) else isnull([7],1) end as Decile07, + case when isnull([1],1) < 25 then isnull([1],1) else isnull([8],1) end as Decile08, + case when isnull([1],1) < 25 then isnull([1],1) else isnull([9],1) end as Decile09, + case when isnull([1],1) < 25 then isnull([1],1) else isnull([10],1) end as Decile10 + from ( + select + ModelTemplateGUID, + PlaceholderSectionMemberGUID, + MemberName, + max(Total) as [Count], + Decile + from ( + select + PlanGUID, + Name, + ModelTemplateGUID, + PlaceholderSectionMemberGUID, + MemberName, + Total, + NTILE(10) OVER(PARTITION BY PlaceholderSectionMemberGUID ORDER BY TOTAL DESC) as Decile + from ( + select + ModelGUID as PlanGUID, + db.Name, + db.ModelTemplateGUID, + PlaceholderSectionMemberGUID, + MEPH.FriendlyName as MemberName, + Count(FillinMemberGUID) as Total + from + [dbo].[ScoreFillin] fill with (readuncommitted) + inner join [dbo].[XPlan] db with (readuncommitted) on db.PlanGUID=fill.ModelGUID + inner join [dbo].[MEPHSection] MEPH with (readuncommitted) on MEPH.PHSectionMemberGUID = fill.PlaceholderSectionMemberGUID and MEPH.ModelTemplateGUID = db.ModelTemplateGUID + inner join [dbo].[ScoreDimension] SD with (readuncommitted) on SD.DimensionGUID = MEPH.PHSectionDimensionGUID + where + db.IsDeletedPlan = 0 + and MEPH.PHSectionMemberGUID != '00000000-0000-0000-0000-000000000000' + and SD.GlobalID not in('Fiscal Year PH','OB Departmental Budget PH','Time Class PH') + group by + ModelGUID, + db.Name, + db.ModelTemplateGUID, + PlaceholderSectionMemberGUID, + MEPH.FriendlyName + ) as groupedTable + ) as deciletable + group by + ModelTemplateGUID, + PlaceholderSectionMemberGUID, + MemberName, + Decile + ) as maxtable + pivot ( + max([Count]) FOR Decile IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10]) + ) as PivotTable +GO + + +--------------------------------------------- + +-- dbo.viewMEPHSectionAnalysisRecommendation +CREATE VIEW [dbo].[viewMEPHSectionAnalysisRecommendation] +AS + SELECT + SUGGESTED.[ModelTemplateGUID], + SUGGESTED.[ExpansionGlobalID], + SUGGESTED.[Count], + CASE + WHEN SUGGESTED.[CountOverride] <= ISNULL(RECOMMENDED.[RecommendedMaxCount], SUGGESTED.[CountOverride]) + THEN SUGGESTED.[CountOverride] + ELSE RECOMMENDED.[RecommendedMaxCount] + END AS [CountOverride] + FROM + ( + SELECT + A.[ModelTemplateGUID], + A.[PlaceholderSectionMemberName] AS [ExpansionGlobalID], + MAX(E.[Count]) AS [Count], + (A.[Decile02] + 10) AS [CountOverride] + FROM + [dbo].[viewMEPHSectionAnalysis] AS A + INNER JOIN [dbo].[MEScoreExpansion] AS E WITH (READUNCOMMITTED) ON E.[GlobalID] = A.[PlaceholderSectionMemberName] + INNER JOIN [dbo].[viewMECell] AS C ON C.ExcelCellGUID = E.[ExcelCellGUID] AND C.[ModelTemplateGUID] = A.[ModelTemplateGUID] + GROUP BY + A.[ModelTemplateGUID], + A.[PlaceholderSectionMemberName], + A.[Decile01], + A.[Decile02] + HAVING + A.[Decile01] != A.[Decile02] + AND A.[Decile02] <= MAX(E.[Count]) - 10 - 25 -- count - padding - useful threshold + ) AS SUGGESTED + LEFT JOIN [dbo].[MEScoreExpansionRecommendedMaxCount] AS RECOMMENDED ON RECOMMENDED.[SectionName] = SUGGESTED.[ExpansionGlobalID] +GO + + +--------------------------------------------- + +-- dbo.viewMEPHSectionAnalysisRecommendationOutliers +CREATE view dbo.viewMEPHSectionAnalysisRecommendationOutliers +as + select + P.ModelTemplateGUID, + MT.Name as ModelTemplateName, + P.PlanGUID, + P.Name as PlanName, + PHS.FriendlyName as ExpansionGlobalID, + max(AR.CountOverride) as ExpansionRecommendation, + count(*) as PlanCount, + max(AR.[Count]) as ExpansionMax + from + [dbo].[XPlan] P with (readuncommitted) + inner join [dbo].[EMFModelTemplate] MT with (readuncommitted) on MT.ModelTemplateGUID = P.ModelTemplateGUID + inner join [dbo].[ScoreFillin] FI with (readuncommitted) on FI.ModelGUID = P.PlanGUID + inner join [dbo].[MEPHSection] PHS with (readuncommitted) on PHS.PHSectionMemberGUID = FI.PlaceholderSectionMemberGUID and PHS.ModelTemplateGUID = P.ModelTemplateGUID + inner join [dbo].[viewMEPHSectionAnalysisRecommendation] AR on AR.ModelTemplateGUID = P.ModelTemplateGUID and AR.ExpansionGlobalID = PHS.FriendlyName + group by + P.ModelTemplateGUID, + MT.Name, + P.PlanGUID, + P.Name, + PHS.FriendlyName + having + count(*) > max(AR.CountOverride) + union all + select + MT.ModelTemplateGUID, + MT.Name as ModelTemplateName, + P.PlanGUID, + P.Name as PlanName, + PHS.FriendlyName as ExpansionGlobalID, + E.[Count] as ExpansionRecommendation, + count(*) as PlanCount, + E.[Count] as ExpansionMax + from + [dbo].[XPlan] P with (readuncommitted) + inner join [dbo].[EMFModelTemplate] MT with (readuncommitted) on MT.ModelTemplateGUID = P.ModelTemplateGUID + inner join [dbo].[ScoreFillin] FI with (readuncommitted) on FI.ModelGUID = P.PlanGUID + inner join [dbo].[MEPHSection] PHS with (readuncommitted) on PHS.PHSectionMemberGUID = FI.PlaceholderSectionMemberGUID and PHS.ModelTemplateGUID = P.ModelTemplateGUID + inner join ( + select + C.ModelTemplateGUID, + E.GlobalID, + max(E.[Count]) as [Count] + from + [dbo].[MEScoreExpansion] E with (readuncommitted) + inner join [dbo].[viewMECell] C on C.ExcelCellGUID = E.ExcelCellGUID + group by + C.ModelTemplateGUID, + E.GlobalID) E on E.GlobalID = PHS.FriendlyName and E.ModelTemplateGUID = MT.ModelTemplateGUID + where + not exists(select 1 from [dbo].[viewMEPHSectionAnalysisRecommendation] AR where AR.ModelTemplateGUID = MT.ModelTemplateGUID and AR.ExpansionGlobalID = PHS.FriendlyName) + group by + MT.ModelTemplateGUID, + MT.Name, + P.PlanGUID, + P.Name, + PHS.FriendlyName, + E.[Count] + having + count(*) > E.[Count] +GO + + +--------------------------------------------- + +-- dbo.viewMEPHSectionAnalysis_InvalidConfigs +CREATE view dbo.viewMEPHSectionAnalysis_InvalidConfigs +AS + select + MT.ModelTemplateGUID, + MT.Name as ModelTemplateName, + P.PlanGUID, + P.Name as PlanName, + PHS.FriendlyName as ExpansionGlobalID, + E.[Count] as ExpansionRecommendation, + count(*) as PlanCount, + E.[Count] as ExpansionMax + from + [dbo].[XPlan] P with (readuncommitted) + inner join [dbo].[EMFModelTemplate] MT with (readuncommitted) on MT.ModelTemplateGUID = P.ModelTemplateGUID + inner join [dbo].[ScoreFillin] FI with (readuncommitted) on FI.ModelGUID = P.PlanGUID + inner join [dbo].[MEPHSection] PHS with (readuncommitted) on PHS.PHSectionMemberGUID = FI.PlaceholderSectionMemberGUID and PHS.ModelTemplateGUID = P.ModelTemplateGUID + inner join ( + select + C.ModelTemplateGUID, + E.GlobalID, + max(E.[Count]) as [Count] + from + [dbo].[MEScoreExpansion] E with (readuncommitted) + inner join [dbo].[viewMECell] C on C.ExcelCellGUID = E.ExcelCellGUID + group by + C.ModelTemplateGUID, + E.GlobalID) E on E.GlobalID = PHS.FriendlyName and E.ModelTemplateGUID = MT.ModelTemplateGUID + where + not exists(select 1 from [dbo].[viewMEPHSectionAnalysisRecommendation] AR where AR.ModelTemplateGUID = MT.ModelTemplateGUID and AR.ExpansionGlobalID = PHS.FriendlyName) + group by + MT.ModelTemplateGUID, + MT.Name, + P.PlanGUID, + P.Name, + PHS.FriendlyName, + E.[Count] + having + count(*) > E.[Count] +GO + + +--------------------------------------------- + +-- dbo.viewMEPHSectionAnalysis_LargeDepartments +CREATE view dbo.viewMEPHSectionAnalysis_LargeDepartments +AS + select + P.ModelTemplateGUID, + MT.Name as ModelTemplateName, + P.PlanGUID, + P.Name as PlanName, + PHS.FriendlyName as ExpansionGlobalID, + max(AR.CountOverride) as ExpansionRecommendation, + count(*) as PlanCount, + max(AR.[Count]) as ExpansionMax + from + [dbo].[XPlan] P with (readuncommitted) + inner join [dbo].[EMFModelTemplate] MT with (readuncommitted) on MT.ModelTemplateGUID = P.ModelTemplateGUID + inner join [dbo].[ScoreFillin] FI with (readuncommitted) on FI.ModelGUID = P.PlanGUID + inner join [dbo].[MEPHSection] PHS with (readuncommitted) on PHS.PHSectionMemberGUID = FI.PlaceholderSectionMemberGUID and PHS.ModelTemplateGUID = P.ModelTemplateGUID + inner join [dbo].[viewMEPHSectionAnalysisRecommendation] AR on AR.ModelTemplateGUID = P.ModelTemplateGUID and AR.ExpansionGlobalID = PHS.FriendlyName + group by + P.ModelTemplateGUID, + MT.Name, + P.PlanGUID, + P.Name, + PHS.FriendlyName + having + count(*) > max(AR.CountOverride) +GO + + +--------------------------------------------- + +-- dbo.viewMEPHSectionDuplicates +create view dbo.viewMEPHSectionDuplicates +as + select + phs.* + from + [dbo].[MEPHSection] phs + where + exists(select 1 from [dbo].[MEPHSection] d where d.ModelTemplateGUID = phs.ModelTemplateGUID and d.PHSectionDimensionGUID = phs.PHSectionDimensionGUID and d.PHSectionMemberGUID = phs.PHSectionMemberGUID and d.PlanTypeGUID = phs.PlanTypeGUID group by d.ModelTemplateGUID, d.PHSectionDimensionGUID, d.PHSectionMemberGUID, d.PlanTypeGUID having count(*) > 1) +GO + + +--------------------------------------------- + +-- dbo.viewMEReportLinkTemplateMapping +CREATE view [dbo].[viewMEReportLinkTemplateMapping] as +select + map.ReportLinkTemplateMappingGUID, + map.ReportGUID, + map.CellGUID, + map.RowExpanded, + map.ReportParams, + sheet.ModelTemplateGUID as BookGUID, + sheet.Name as SheetName, + cell.ExcelSheetGUID, + cell.Row, + cell.Col +from + MEReportLinkTemplateMapping map + inner join MEExcelCell cell on map.CellGUID = cell.ExcelCellGUID + inner join EMFModelTemplateWorksheet sheet on cell.ExcelSheetGUID = sheet.WorksheetGUID +GO + + +--------------------------------------------- + +-- dbo.viewMEScoreExpansion +CREATE view [dbo].[viewMEScoreExpansion] as +select + scexp.*, + cell.ExcelSheetGUID, + cell.Row, + cell.Row2, + cell.Col, + sheet.Name as SheetName, + book.ModelTemplateGUID as ExcelBookGUID, + book.Name as BookName +from + MEScoreExpansion scexp + inner join MEExcelCell cell on scexp.excelcellguid = cell.ExcelCellGUID + inner join EMFModelTemplateWorksheet sheet on cell.ExcelSheetGUID = sheet.WorksheetGUID + inner join EMFModelTemplate book on sheet.ModelTemplateGUID = book.ModelTemplateGUID +GO + + +--------------------------------------------- + +-- dbo.viewMEScoreExpansionOutliers +create view dbo.viewMEScoreExpansionOutliers +as + select + p.Name as Budget, + phs.FriendlyName as ModelSection, + COUNT(*) as FillinCount, + mx.RecommendedMaxCount as MaxCount + from + dbo.MEScoreExpansionRecommendedMaxCount mx + inner join MEPHSection phs on phs.FriendlyName = mx.SectionName + inner join ScoreFillin fi on fi.PlaceholderSectionMemberGUID = phs.PHSectionMemberGUID + inner join XPlan p on p.PlanGUID = fi.ModelGUID + inner join EMFModelTemplate mt on mt.ModelTemplateGUID = p.ModelTemplateGUID + where + mt.Name like 'ob departmental%' + group by + p.Name, + phs.FriendlyName, + mx.RecommendedMaxCount + having + COUNT(*) > mx.RecommendedMaxCount +GO + + +--------------------------------------------- + +-- dbo.viewMEScoreExpansionOverride +CREATE view dbo.viewMEScoreExpansionOverride +as + select + EO.OverrideGUID, + EO.ExpansionProfileGUID, + EO.ExpansionGlobalID, + max(E.[Count]) as [Count], + EO.CountOverride + from + [dbo].[MEScoreExpansionOverride] EO with (readuncommitted) + inner join [dbo].[MEScoreExpansionProfile] EP with (readuncommitted) on EP.ExpansionProfileGUID = Eo.ExpansionProfileGUID + inner join [dbo].[MEScoreExpansion] E with (readuncommitted) on E.GlobalID = EO.ExpansionGlobalID + inner join [dbo].[viewMECell] C on C.ExcelCellGUID = E.ExcelCellGUID and C.ModelTemplateGUID = EP.ParentModelTemplateGUID + group by + EO.OverrideGUID, + EO.ExpansionProfileGUID, + EO.ExpansionGlobalID, + EO.CountOverride +GO + + +--------------------------------------------- + +-- dbo.viewMEScorePlaceholderLabel +CREATE view [dbo].[viewMEScorePlaceholderLabel] as +select + map.*, + sheet.ModelTemplateGUID as BookGUID, + sheet.Name as SheetName, + cell.ExcelSheetGUID, + cell.Row, + cell.Col +from + MEScorePlaceholderLabel map (readuncommitted) + inner join MEExcelCell cell (readuncommitted) on map.CellGUID = cell.ExcelCellGUID + inner join EMFModelTemplateWorksheet sheet (readuncommitted) on cell.ExcelSheetGUID = sheet.WorksheetGUID +GO + + +--------------------------------------------- + +-- dbo.viewMEScoreSource +CREATE view viewMEScoreSource as +select + ModelTemplateGUID as BookGUID, linksourceguid as SourceGUID, ParentScoreCompositeTableGUID as CompositeGUID, Name, IsSelf +from + EMFModelTemplateLinkSource +where + ParentScoreCompositeTableGUID <> '00000000-0000-0000-0000-000000000000' +GO + + +--------------------------------------------- + +-- dbo.viewMessageQueue +CREATE VIEW [dbo].[viewMessageQueue] +AS +SELECT TOP 100 PERCENT + t.Name as ThreadName, + m.subject as [Subject], + m.body as Body, + coalesce(mt.Name, '') as MessageTypeName, + coalesce(author.UserName, '') as Author, + m.datecreated as DateCreated, + m.hasattachments as HasAttachments, + u.UserName as RecipientUsername, + u.namefirst as RecipientFirstName, + u.namelast as RecipientLastName, + u.emailaddress as RecipientEmailAddress +FROM + msgmessage m inner join msgtopic t on t.topicguid = m.topicguid + inner join viewS3ACLSimple acl on acl.LootID = t.TopicGUID + inner join userprofile u on u.userguid = acl.UserGUID + LEFT join UserProfile author on m.AuthorGUID = author.UserGUID + left join MsgMessageType mt on mt.MessageTypeGUID = m.MessageTypeGUID + left join msgforum f on f.forumguid = t.forumguid +WHERE u.userguid != m.authorguid and m.issent = 0 +GROUP BY + t.Name, + m.subject, + m.body, + mt.Name, + author.UserName, + m.datecreated, + m.hasattachments, + u.username, + u.namefirst, + u.namelast, + u.emailaddress +ORDER BY m.DateCreated +GO + + +--------------------------------------------- + +-- dbo.viewModelDependencies +CREATE view [dbo].[viewModelDependencies] +AS + select + EL.ModelGUID as [ModelGUID], + EL.ParentModelGUID as [ParentModelGUID] + from + EMFModelDataLink EL (readuncommitted) + where + exists(select 1 from XPlan P1 (readuncommitted) where P1.PlanGUID = EL.ModelGUID and IsDeletedPlan = 0) + and exists(select 1 from XPlan P2 (readuncommitted) where P2.PlanGUID = EL.ModelGUID and IsDeletedPlan = 0) + UNION ALL + select + FI.ModelGUID, + FI.FillinMemberGUID as ParentModelGUID + from + [dbo].[ScoreFillin] FI (readuncommitted) + where + exists(select 1 from XPlan P1 (readuncommitted) where P1.PlanGUID = FI.ModelGUID and IsDeletedPlan = 0) + and exists(select 1 from XPlan P2 (readuncommitted) where P2.PlanGUID = FI.FillinMemberGUID and IsDeletedPlan = 0) +GO + + +--------------------------------------------- + +-- dbo.viewModelSectionSecured +CREATE view dbo.viewModelSectionSecured +as + with ModelSectionInheritance as ( + select + ms.ModelSectionGUID, + case when ms.ParentGUID != '00000000-0000-0000-0000-000000000000' and ms.IsInherit = 1 and isnull(pms.ModelSectionGUID, '00000000-0000-0000-0000-000000000000') != '00000000-0000-0000-0000-000000000000' then ( + case when pms.ParentGUID != '00000000-0000-0000-0000-000000000000' and pms.IsInherit = 1 and isnull(ppms.ModelSectionGUID, '00000000-0000-0000-0000-000000000000') != '00000000-0000-0000-0000-000000000000' then ( + case when ppms.ParentGUID != '00000000-0000-0000-0000-000000000000' and ppms.IsInherit = 1 and isnull(pppms.ModelSectionGUID, '00000000-0000-0000-0000-000000000000') != '00000000-0000-0000-0000-000000000000' then ( + case when pppms.ParentGUID != '00000000-0000-0000-0000-000000000000' and pppms.IsInherit = 1 then pppms.ParentGUID else pppms.ModelSectionGUID end + ) else ppms.ModelSectionGUID end + ) else pms.ModelSectionGUID end + ) else ms.ModelSectionGUID end as LootGUID + from + ModelSection ms + left join ModelSection pms on pms.ModelSectionGUID = ms.ParentGUID + left join ModelSection ppms on ppms.ModelSectionGUID = pms.ParentGUID + left join ModelSection pppms on pppms.ModelSectionGUID = ppms.ParentGUID + ) + select + ms.ModelSectionGUID, + ms.Name, + ms.[Range], + ms.[Address], + ms.SheetGUID, + ms.ParentGUID, + msi.LootGUID, + ws.Name as SheetName, + acl.UserGUID, + isnull(acl.IsReadable, cast(1 as bit)) as IsReadable, + isnull(acl.IsWritable, cast(1 as bit)) as IsWritable + from + ModelSection ms with (readuncommitted) + inner join ModelSectionInheritance msi with (readuncommitted) on msi.ModelSectionGUID = ms.ModelSectionGUID + inner join EMFModelTemplateWorksheet ws with (readuncommitted) on ws.WorksheetGUID = ms.SheetGUID + inner join viewS3ACLSimple acl on acl.LootID = msi.LootGUID + where + acl.IsReadable = 0 or acl.IsWritable = 0 + union all + select + ws.WorksheetGUID as ModelSectionGUID, + ws.Name, + '' as [Range], + '' as [Address], + ws.WorksheetGUID as SheetGUID, + dbo.ZeroGUID() as ParentGUID, + ws.WorksheetGUID as LootGUID, + ws.Name as SheetName, + acl.UserGUID, + isnull(acl.IsReadable, cast(1 as bit)) as IsReadable, + isnull(acl.IsWritable, cast(1 as bit)) as IsWritable + from + EMFModelTemplateWorksheet ws with (readuncommitted) + inner join viewS3ACLSimple acl on acl.LootID = ws.WorksheetGUID + where + acl.IsReadable = 0 or acl.IsWritable = 0 +GO + + +--------------------------------------------- + +-- dbo.viewMsgEmailActivity +CREATE VIEW [dbo].[viewMsgEmailActivity] +AS +SELECT + ea.EmailActivityID, + ea.EmailSummaryID, + ea.UserGUID, + ea.EmailAddress, + u.UserName, + ea.MessageGUID, + m.Subject, + ea.Timestamp, + ea.IsSuccess, + ea.Description +FROM + dbo.MsgEmailActivity ea (readuncommitted) + left join MsgMessage m (readuncommitted) on ea.MessageGUID = m.MessageGUID + left join UserProfile u (readuncommitted) on ea.UserGUID = u.UserGUID +GO + + +--------------------------------------------- + +-- dbo.viewOMZProviderSettings +CREATE view [dbo].[viewOMZProviderSettings] +as +SELECT [ProviderSettingsGUID] + ,[Name] + ,[AssemblyQualifiedName] + ,cast([Metadata] as nvarchar(max)) as Metadata + ,[ProviderAssemblyQualifiedName] + ,[PoolDimensionGUID] + ,[DefaultEvaluatorRoleGUID] + ,[DefaultGridTemplateGUID] + ,[DefaultApprovedFieldGUID] + ,[DefaultScoringReportGUID] + ,[DefaultPlanTypeGUID] + FROM [dbo].[OMZProviderSettings] +GO + + +--------------------------------------------- + +-- dbo.viewPlaceholders +CREATE view [dbo].[viewPlaceholders] with schemabinding as +select + sl.listguid as PlaceholderDimensionGUID, + slm.listmemberguid as PlaceholderMemberGUID, + sortorderfullpath as SortOrder, + slm.parentlistmemberguid as PlaceholderParentMemberGUID, + ROW_NUMBER() over (partition by slm.parentlistmemberguid order by sortorderfullpath) -1 as PHIndex, + slm.Name as PlaceholderMember +from + dbo.securelist sl + inner join dbo.securelistmember slm on sl.listguid = slm.listguid +where + sl.isplaceholder = 1 + and slm.outlinelevel = 1 +GO + + +--------------------------------------------- + +-- dbo.viewPlanLocks +create view viewPlanLocks +as +select + P.PlanGUID, + dbo.GetPlanName(P.PlanGUID) as PlanName, + L.UserGUID, + UP.UserName, + L.DateLocked, + L.DateLastActive +from + Lock L + inner join XPlan P on L.ItemGUID = P.PlanGUID + left join UserProfile UP on L.UserGUID = UP.UserGUID +where + L.LockGroup = 'PlanLock' +GO + + +--------------------------------------------- + +-- dbo.viewPlanTypeModelTemplate +CREATE view dbo.viewPlanTypeModelTemplate as --with schemabinding as +select + p.PlanTypeGUID, + p.ModelTemplateGUID, + mt.DefaultFormGUID, + mt.Description, + mt.IsExpanded, + mt.IsNewLabelsOnly, + mt.IsPublished, + mt.IsSafeModeOn, + mt.Name, + mt.Type, + mt.Version +from + PlanTypeModelTemplateLink p + inner join EMFModelTemplate mt on p.ModelTemplateGUID = mt.ModelTemplateGUID +GO + + +--------------------------------------------- + +-- dbo.viewPlanTypeWorkflowMapLink +CREATE view [dbo].[viewPlanTypeWorkflowMapLink] as +SELECT + WML.PlanTypeGuid, + WML.WorkflowMapGuid, + WML.IsRequiredWorkflow, + WM.Name as WorkflowName, + PT.Name as PlanTypeName +FROM + PlanTypeWorkflowMapLink WML + INNER JOIN WFWorkflowMap WM on WML.WorkflowMapGUID = WM.WorkflowMapGUID + INNER JOIN PlanType PT ON WML.PlanTypeGUID = PT.PlanTypeGUID +GO + + +--------------------------------------------- + +-- dbo.viewPlans +CREATE view [dbo].[viewPlans] as +select + planguid, + p.Name , + p.plantypeguid, + pt.name as PlanTypeName, + p.ModelTemplateGUID, + mt.Name as TemplateName, + p.DefaultFormDefGUID, + f.Name as FormName, + p.CachedLootID, + l.PermissionSetID, + ps.Name as PermissionSet, + pt.DimensionGUID, + sd.FriendlyName as DimensionName, + p.DateCreated, + p.IsDeletedPlan +from + xplan p (readuncommitted) + left join plantype pt (readuncommitted) on pt.plantypeguid = p.plantypeguid + left join EMFModelTemplate mt (readuncommitted) on p.ModelTemplateGUID = mt.ModelTemplateGUID + left join FE2Form f (readuncommitted) on p.DefaultFormDefGUID = f.FORMGUID + left join ScoreDimension sd (readuncommitted) on pt.DimensionGUID = sd.DimensionGUID + left join S3Loot l (readuncommitted) on l.LootID = p.CachedLootID + left join S3PermissionSet ps (readuncommitted) on ps.PermissionSetID = l.PermissionSetID +GO + + +--------------------------------------------- + +-- dbo.viewPlansRecentlyOpened +CREATE VIEW dbo.viewPlansRecentlyOpened +AS +select A.*, P.Name, P.PlanGUID, U.UserGUID + +from ActionLog A + inner join XPlan P on A.Details = CAST(P.PlanGUID as nvarchar(36)) + inner join UserProfile U on U.UserName = A.Username + +where A.Action='Form Edit' and A.SubAction='Initial Load' and DATEDIFF(DD, DateTimeStamp, GETDATE()) < 5 +GO + + +--------------------------------------------- + +-- dbo.viewREClientReportParameter_Broken +CREATE view dbo.viewREClientReportParameter_Broken +as + select + 'Invalid attribute' as Issue, + r.Name as ReportName, + p.* + from + REReport r + inner join REClientReportParameter p on p.ReportGUID = r.ReportGUID + where + exists (select 1 from REClientReportDataSourceLink ds where ds.ReportGUID = r.ReportGUID and ds.ProviderAssemblyQualifiedName like '%SQLProvider%') + and not exists( + select 1 + from + REClientReportDataSourceLink ds + inner join DataView dv on dv.DataViewGUID = ds.DataSourceGUID + inner join RESQLReportRegisteredDimension rd on rd.DataViewGUID = dv.DataViewGUID and cast(rd.DimensionGUID as nvarchar(36)) = p.DimensionID + inner join RESQLReportRegisteredAttribute ra on ra.RegisteredDimensionGUID = rd.RegisteredDimensionGUID and cast(ra.AttributeGUID as nvarchar(36)) = p.AttributeID + inner join viewScoreAttribute a on a.AttributeGUID = ra.AttributeGUID + where + ltrim(p.ColumnName) = case when ra.ColumnAlias = '' then a.SQLColumnName else ltrim(ra.ColumnAlias) end + and ds.ReportGUID = r.ReportGUID + ) + and p.SourceTypeValue = 0 + union all + --MR-specific parameter issues + select + 'Invalid selection' as Issue, + r.Name as ReportName, + p.* + from + REReport r + inner join REClientReportParameter p on p.ReportGUID = r.ReportGUID + where + (p.DimensionID = 'ae2104b1-e2d5-4cc0-88a5-e729b744fde7' and cast(p.parameterxml as nvarchar(max)) like '%dept|%' and cast(p.parameterxml as nvarchar(max)) not like '%mrdept|%') + or (p.parameterxml like '%MRDEPT|KEY|%' and p.parameterxml like '%MRDepartmentID%' and p.parameterxml not like '%MRDEPT|KEY|' + (select cast(defaultkeyguid as nvarchar(36)) from scoredimension where friendlyname = 'mr department') + '%' ) +GO + + +--------------------------------------------- + +-- dbo.viewREClientReportSectionAttribute_Broken +CREATE view dbo.viewREClientReportSectionAttribute_Broken +as + select + r.ReportGUID, + r.Name as ReportName, + sa.* + from + REReport r + inner join REClientReportSectionLink sl on sl.ReportGUID = r.ReportGUID + inner join REClientReportSectionAttribute sa on sa.ClientReportSectionGUID = sl.ClientReportSectionGUID + where + exists (select 1 from REClientReportDataSourceLink ds where ds.ReportGUID = r.ReportGUID and ds.ProviderAssemblyQualifiedName like '%SQLProvider%') + and not exists( + select 1 + from + REClientReportDataSourceLink ds + inner join DataView dv on dv.DataViewGUID = ds.DataSourceGUID + inner join RESQLReportRegisteredDimension rd on rd.DataViewGUID = dv.DataViewGUID and cast(rd.DimensionGUID as nvarchar(36)) = sa.DimensionID + inner join RESQLReportRegisteredAttribute ra on ra.RegisteredDimensionGUID = rd.RegisteredDimensionGUID and cast(ra.AttributeGUID as nvarchar(36)) = sa.AttributeID + inner join viewScoreAttribute a on a.AttributeGUID = ra.AttributeGUID + where + ltrim(sa.ColumnName) = case when ra.ColumnAlias = '' then a.SQLColumnName else ltrim(ra.ColumnAlias) end + and ds.ReportGUID = r.ReportGUID + ) +GO + + +--------------------------------------------- + +-- dbo.viewRESQLReportDisplayColumn_Broken +CREATE view dbo.viewRESQLReportDisplayColumn_Broken +as + with cols_physical as ( + select + t.object_id, + s.name + '.' + t.name as obj, + c.name as col + from + sys.columns c + inner join sys.tables t on t.object_id = c.object_id + inner join sys.schemas s on s.schema_id = t.schema_id + inner join dbo.dataview dv on s.name + '.' + t.name = replace(replace(dv.SQLViewName, '[', ''), ']', '') + union all + select + v.object_id, + s.name + '.' + v.name as obj, + c.name as col + from + sys.columns c + inner join sys.views v on v.object_id = c.object_id + inner join sys.schemas s on s.schema_id = v.schema_id + inner join dbo.dataview dv on s.name + '.' + v.name = replace(replace(dv.SQLViewName, '[', ''), ']', '') + ), + cols_registered as ( + select + ax.attributeguid, + rdx.dataviewguid, + case when rax.columnalias = '' then ax.sqlcolumnname else ltrim(rax.columnalias) end as columnname + from + resqlreportregistereddimension rdx + inner join resqlreportregisteredattribute rax on rax.registereddimensionguid = rdx.registereddimensionguid + inner join viewscoreattribute ax on ax.attributeguid = rax.attributeguid + ) + select + r.ReportGUID, + r.Name as ReportName, + dc.* + from + REReport r + inner join RESQLReportSetup rs on rs.ReportGUID = r.ReportGUID + inner join DataView dv on dv.dataviewguid = rs.dataviewguid + inner join resqlreportdisplaycolumn dc on dc.sqlreportsetupguid = rs.sqlreportsetupguid + left join cols_physical cp on cp.obj = replace(replace(dv.SQLViewName, '[', ''), ']', '') and cp.col = ltrim(dc.columnname) + left join cols_registered cr on cr.dataviewguid = dv.dataviewguid and cr.columnname = ltrim(dc.columnname) + where + cp.object_id is null + and cr.attributeguid is null +GO + + +--------------------------------------------- + +-- dbo.viewRESQLReportFilterColumn_Broken +CREATE view dbo.viewRESQLReportFilterColumn_Broken +as + with cols_physical as ( + select + t.object_id, + s.name + '.' + t.name as obj, + c.name as col + from + sys.columns c + inner join sys.tables t on t.object_id = c.object_id + inner join sys.schemas s on s.schema_id = t.schema_id + inner join dbo.dataview dv on s.name + '.' + t.name = replace(replace(dv.SQLViewName, '[', ''), ']', '') + union all + select + v.object_id, + s.name + '.' + v.name as obj, + c.name as col + from + sys.columns c + inner join sys.views v on v.object_id = c.object_id + inner join sys.schemas s on s.schema_id = v.schema_id + inner join dbo.dataview dv on s.name + '.' + v.name = replace(replace(dv.SQLViewName, '[', ''), ']', '') + ), + cols_registered as ( + select + ax.attributeguid, + rdx.dataviewguid, + case when rax.columnalias = '' then ax.sqlcolumnname else ltrim(rax.columnalias) end as columnname + from + resqlreportregistereddimension rdx + inner join resqlreportregisteredattribute rax on rax.registereddimensionguid = rdx.registereddimensionguid + inner join viewscoreattribute ax on ax.attributeguid = rax.attributeguid + ) + select + 'Invalid attribute' as Issue, + r.ReportGUID, + r.Name as ReportName, + dc.* + from + REReport r + inner join RESQLReportSetup rs on rs.ReportGUID = r.ReportGUID + inner join DataView dv on dv.dataviewguid = rs.dataviewguid + inner join resqlreportFiltercolumn dc on dc.sqlreportsetupguid = rs.sqlreportsetupguid + left join cols_physical cp on cp.obj = replace(replace(dv.SQLViewName, '[', ''), ']', '') and cp.col = ltrim(dc.columnname) + left join cols_registered cr on cr.dataviewguid = dv.dataviewguid and cr.columnname = ltrim(dc.columnname) + where + cp.object_id is null + and cr.attributeguid is null + union all + --MR-specific issues + select + 'Invalid selection' as Issue, + r.ReportGUID, + r.Name as ReportName, + fc.* + from + resqlreportsetup rs + inner join rereport r on r.reportguid = rs.reportguid + inner join RESQLReportFilterColumn fc on fc.SQLReportSetupGUID = rs.SQLReportSetupGUID + where + exists(select 1 from RESQLReportRegisteredDimension rd where rd.DataViewGUID = rs.DataViewGUID and rd.DimensionGUID = 'AE2104B1-E2D5-4CC0-88A5-E729B744FDE7') + and fc.ParameterXML like '%DEPT|%' and fc.ParameterXML not like '%MRDEPT|%' +GO + + +--------------------------------------------- + +-- dbo.viewRESQLReportRegisteredAttribute +create view dbo.viewRESQLReportRegisteredAttribute +as + select + dv.DataViewGUID, + dv.Name, + dv.SQLViewName, + rd.RegisteredDimensionGUID, + rd.DimensionGUID, + rd.KeyGUID, + rd.KeyColumnName, + ra.RegisteredAttributeGUID, + ra.AttributeGUID, + ra.ColumnAlias + from + dbo.DataView dv with (readuncommitted) + inner join dbo.RESQLReportRegisteredDimension rd with (readuncommitted) on rd.DataViewGUID = dv.DataViewGUID + inner join dbo.RESQLReportRegisteredAttribute ra with (readuncommitted) on ra.RegisteredDimensionGUID = rd.RegisteredDimensionGUID +GO + + +--------------------------------------------- + +-- dbo.viewRESQLReportRegisteredAttribute_ByReport +CREATE view dbo.viewRESQLReportRegisteredAttribute_ByReport +as + select distinct + r.ReportGUID, + a.AttributeGUID, + case when ra.ColumnAlias = '' then a.SQLColumnName else ltrim(ra.ColumnAlias) end as ColumnName + from + REReport r + inner join REClientReportDataSourceLink ds on ds.ReportGUID = r.ReportGUID + inner join RESQLReportRegisteredDimension rd on rd.DataViewGUID = ds.DataSourceGUID + inner join RESQLReportRegisteredAttribute ra on rd.RegisteredDimensionGUID = ra.RegisteredDimensionGUID + inner join ScoreAttribute a on a.AttributeGUID = ra.AttributeGUID + union all + select distinct + r.ReportGUID, + a.AttributeGUID, + case when ra.ColumnAlias = '' then a.SQLColumnName else ltrim(ra.ColumnAlias) end as ColumnName + from + REReport r + inner join REDataSource ds on ds.ReportGUID = r.ReportGUID + inner join RESQLReportSetup rs on rs.ReportGUID = ds.SourceGUID + inner join RESQLReportRegisteredDimension rd on rd.DataViewGUID = rs.DataViewGUID + inner join RESQLReportRegisteredAttribute ra on rd.RegisteredDimensionGUID = ra.RegisteredDimensionGUID + inner join ScoreAttribute a on a.AttributeGUID = ra.AttributeGUID + union all + select distinct + r.ReportGUID, + a.AttributeGUID, + case when ra.ColumnAlias = '' then a.SQLColumnName else ltrim(ra.ColumnAlias) end as ColumnName + from + REReport r + inner join RESQLReportSetup rs on rs.ReportGUID = r.ReportGUID + inner join RESQLReportRegisteredDimension rd on rd.DataViewGUID = rs.DataViewGUID + inner join RESQLReportRegisteredAttribute ra on rd.RegisteredDimensionGUID = ra.RegisteredDimensionGUID + inner join ScoreAttribute a on a.AttributeGUID = ra.AttributeGUID +GO + + +--------------------------------------------- + +-- dbo.viewRESQLReportRegisteredAttribute_Duplicates +create view dbo.viewRESQLReportRegisteredAttribute_Duplicates +as + select + dv.DataViewGUID, + dv.Name, + case when ra.ColumnAlias = '' then a.SQLColumnName else ltrim(ra.ColumnAlias) end as Attribute, + count(*) as DuplicateCount + from + RESQLReportRegisteredAttribute ra + inner join RESQLReportRegisteredDimension rd on rd.RegisteredDimensionGUID = ra.RegisteredDimensionGUID + inner join DataView dv on dv.DataViewGUID = rd.DataViewGUID + inner join viewScoreAttribute a on a.AttributeGUID = ra.AttributeGUID + group by + dv.DataViewGUID, + dv.Name, + case when ra.ColumnAlias = '' then a.SQLColumnName else ltrim(ra.ColumnAlias) end + having + count(*) > 1 +GO + + +--------------------------------------------- + +-- dbo.viewRESQLReportRegisteredDimension +CREATE view [dbo].[viewRESQLReportRegisteredDimension] as + + select + dv.name as DataviewName, + dv.sqlviewname, + sd.friendlyname as ScoreDimension, + sa.friendlyname as AttributeKeyName, + rd.* from dbo.RESQLReportRegisteredDimension rd + left join dataview dv + on dv.dataviewguid = rd.dataviewguid + left join scoredimension sd + on sd.dimensionguid = rd.dimensionguid + left join scoreattribute sa + on sa.attributeguid = rd.keyguid +GO + + +--------------------------------------------- + +-- dbo.viewRESortingParameter_Broken +CREATE view dbo.viewRESortingParameter_Broken +as + select + r.ReportGUID, + r.Name as ReportName, + ds.SourceGUID as DataViewGUID, + p.* + from + REDataSource ds + inner join REReport r on r.ReportGUID = ds.ReportGUID + inner join RESortingParameter p on p.DataSourceGUID = ds.DataSourceGUID + where + not exists( + select 1 + from + RESQLReportDisplayColumn dc + inner join RESQLReportSetup rs on dc.sqlreportsetupguid = rs.sqlreportsetupguid and rs.reportguid = ds.sourceguid + where + dc.columnname = p.columnname + ) +GO + + +--------------------------------------------- + +-- dbo.viewRandomNumber +CREATE VIEW viewRandomNumber +AS +SELECT RAND() as RandNumber +GO + + +--------------------------------------------- + +-- dbo.viewReportRunHistory +CREATE VIEW [dbo].[viewReportRunHistory] +AS + +select + L.Username as [UserName], + case L.Action + when 'ZEROVIEWER' then 'Excel' + when 'Excel Reporter' then 'Excel' + when 'SQL Report' then 'SQL' + else 'Not Specified' + end as [Report Type], + replace(coalesce(R.Name, L.SubAction) , 'BATCH_', '')as [ReportName], + L.DatetimeStamp as [LaunchTime], + L.Duration/1000 as [DurationInSeconds] +from + ActionLog L (nolock) + inner join REReport R on RIGHT(L.SubAction, 36) = cast(R.ReportGUID as nvarchar(36)) or replace(L.SubAction, 'BATCH_', '')=R.Name +where + L.Action in ('ZEROVIEWER', 'Excel Reporter', 'SQL Report') + and L.SubAction not like 'DrillDown%' +GO + + +--------------------------------------------- + +-- dbo.viewRoleVisibilityRule +CREATE view dbo.viewRoleVisibilityRule as +select + ISNULL(rvr.RoleVisibilityRuleGUID, newid()) as RoleVisibilityRuleGUID + ,ps.PermissionSetID as PermissionSetID + ,ps.RoleID as RoleID + ,ps.RoleName as RoleName + ,ISNULL(rvr.UserGroupGUID , '00000000-0000-0000-0000-000000000001') as UserGroupGUID + ,ISNULL(rvr.IsVisible, 1) as IsVisible + ,cast(case when rvr.IsVisible is null then 1 else 0 end as bit) as IsViewGenerated +from [dbo].[RoleVisibilityRule] rvr +right join [dbo].[viewS3PermissionSet] ps on rvr.PermissionSetID = ps.PermissionSetID and rvr.RoleID = ps.RoleID +GO + + +--------------------------------------------- + +-- dbo.viewS3ACL +CREATE view [dbo].[viewS3ACL] as + SELECT + il.MemberGUID AS UserGUID, + acl.LootID, + acl.LootGroupPrefix, + case when sum(acl.ReadAllowpts) > sum(acl.ReadDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsReadable, + case when sum(acl.WriteAllowpts) > sum(acl.WriteDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsWritable, + case when sum(acl.SecureAllowpts) > sum(acl.SecureDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsSecurable, + case when sum(acl.DeleteAllowpts) > sum(acl.DeleteDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsDeletable, + case when sum(acl.CreateAllowpts) > sum(acl.CreateDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsCreatable + FROM + ( + SELECT + RA.IdentityGUID, + L.LootID, + L.LootGroupPrefix, + ReadAllowPts, + ReadDenyPts, + WriteAllowPts, + WriteDenyPts, + SecureAllowPts, + SecureDenyPts, + DeleteAllowPts, + DeleteDenyPts, + CreateAllowPts, + CreateDenyPts + FROM + dbo.S3LootGroup LG WITH (READUNCOMMITTED) + INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED) ON L.LootID = LG.LootID + INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) ON LG.LootGroupID = RA.LootGroupID + INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID + ) AS acl + INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) ON acl.identityguid = il.GroupingGUID + GROUP BY + il.MemberGUID, + acl.LootID, + acl.LootGroupPrefix +GO + + +--------------------------------------------- + +-- dbo.viewS3ACLDepartment +CREATE view [dbo].[viewS3ACLDepartment] as + + SELECT + il.MemberGUID as UserGUID, + Cast(Replace(LootID, 'DEPT|', '') as int) as DepartmentID, + 1 as IsReadable, + case when sum(acl.WriteAllowpts) > sum(acl.WriteDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsWritable + FROM + ( + SELECT + RA.IdentityGUID, + L.LootID, + ReadAllowPts, + ReadDenyPts, + WriteAllowPts, + WriteDenyPts + FROM + dbo.S3LootGroup LG WITH (READUNCOMMITTED) + INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED) ON L.LootID = LG.LootID + INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) ON LG.LootGroupID = RA.LootGroupID + INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID + where L.LootGroupPrefix='DEPT' + ) AS acl + INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) ON acl.identityguid = il.GroupingGUID + GROUP BY + il.MemberGUID, + acl.LootID + HAVING + sum(ReadAllowPts) > sum(ReadDenyPts) +GO + + +--------------------------------------------- + +-- dbo.viewS3ACLDepartmentForOB +CREATE view [dbo].[viewS3ACLDepartmentForOB] as + + SELECT + il.MemberGUID as UserGUID, + Cast(Replace(LootID, 'DEPT|', '') as int) as DepartmentID, + 1 as IsReadable, + case when sum(acl.WriteAllowpts) > sum(acl.WriteDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsWritable + FROM + ( + SELECT + RA.IdentityGUID, + L.LootID, + ReadAllowPts, + ReadDenyPts, + WriteAllowPts, + WriteDenyPts + FROM + dbo.S3LootGroup LG WITH (READUNCOMMITTED) + INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED) ON L.LootID = LG.LootID + INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) ON LG.LootGroupID = RA.LootGroupID + INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID + INNER JOIN dbo.UserRole AS UR ON UR.RoleID = RA.RoleID + where L.LootGroupPrefix='DEPT' and ur.Category = 'OB' + ) AS acl + INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) ON acl.identityguid = il.GroupingGUID + GROUP BY + il.MemberGUID, + acl.LootID + HAVING + sum(ReadAllowPts) > sum(ReadDenyPts) +GO + + +--------------------------------------------- + +-- dbo.viewS3ACLDetail +CREATE view [dbo].[viewS3ACLDetail] + as +SELECT + IL.MemberGUID as UserGUID, + up.NameFull as UserName, + IL.Distance, + IL.GroupingGUID as IdentityGUID, + coalesce(ug.Name,up2.namefull) as IdentityName, + RA.RoleID, + ur.Name as RoleName, + L.LootID, + LG.LootGroupID, + P.ReadAllowPts as ReadAllowPts, + P.ReadDenyPts as ReadDenyPts, + P.WriteAllowPts as WriteAllowPts, + P.WriteDenyPts as WriteDenyPts, + P.SecureAllowPts as SecureAllowPts, + P.SecureDenyPts as SecureDenyPts, + P.DeleteAllowPts as DeleteAllowPts, + P.DeleteDenyPts as DeleteDenyPts, + P.CreateAllowPts as CreateAllowPts, + P.CreateDenyPts as CreateDenyPts +FROM + dbo.S3LootGroup LG + INNER JOIN dbo.S3Loot L on L.LootID = LG.LootID + INNER JOIN dbo.S3RoleAssignment RA on LG.LootGroupID = RA.LootGroupID + INNER JOIN dbo.S3IdentityLink IL on IL.GroupingGUID = RA.IdentityGUID + inner JOIN dbo.S3Permission P on RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID + LEFT JOIN UserGroup ug on IL.GroupingGUID = ug.UserGroupGUID + LEFT JOIN UserProfile up on IL.MemberGUID = up.UserGUID + LEFT JOIN UserProfile up2 on IL.GroupingGUID = up2.UserGUID + LEFT JOIN UserRole ur on RA.RoleID = ur.RoleID +--WHERE +-- IL.IsUser = 1 --slows it down cause it goes out of order, filtering first on this :( + +/* + create unique clustered index idx_s3acl on dbo.viewS3ACLsb (userguid, lootid) +*/ +GO + + +--------------------------------------------- + +-- dbo.viewS3ACLRead +------------------------------------------------------------------------------------------------------------ + +CREATE view [dbo].[viewS3ACLRead] as +select + il.MemberGUID as UserGUID, + LootID +from + (SELECT + RA.IdentityGUID, + L.LootID, + ReadAllowPts, + ReadDenyPts, + WriteAllowPts, + WriteDenyPts, + SecureAllowPts, + SecureDenyPts, + DeleteAllowPts, + DeleteDenyPts, + CreateAllowPts, + CreateDenyPts + FROM + dbo.S3LootGroup LG WITH (READUNCOMMITTED) + INNER JOIN + dbo.S3Loot L WITH (READUNCOMMITTED) + ON L.LootID = LG.LootID + INNER JOIN + dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) + ON LG.LootGroupID = RA.LootGroupID + INNER JOIN + dbo.S3Permission P WITH (READUNCOMMITTED) + ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID) AS acl + inner join + dbo.S3IdentityLink il on acl.identityguid = il.GroupingGUID +group by + il.MemberGUID, + LootID +having + sum(ReadAllowPts) > sum(ReadDenyPts) +GO + + +--------------------------------------------- + +-- dbo.viewS3ACLReadDepartment +CREATE view [dbo].[viewS3ACLReadDepartment] as + +select + il.MemberGUID as UserGUID, + Cast(Replace(LootID, 'DEPT|', '') as int) as DepartmentID +from + ( + SELECT + RA.IdentityGUID, + L.LootID, + ReadAllowPts, + ReadDenyPts + FROM + dbo.S3LootGroup LG WITH (READUNCOMMITTED) + INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED) ON L.LootID = LG.LootID + INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) ON LG.LootGroupID = RA.LootGroupID + INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID + where L.LootGroupPrefix='DEPT' + ) AS acl + INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) on acl.identityguid = il.GroupingGUID + +group by + il.MemberGUID, + LootID + +having + sum(ReadAllowPts) > sum(ReadDenyPts) +GO + + +--------------------------------------------- + +-- dbo.viewS3ACLReadDepartmentForMRRoles +CREATE VIEW [dbo].[viewS3ACLReadDepartmentForMRRoles] as +/** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-06-27 HV JAZZ-39147 PR Roles - Prepare databases for MR PR security separation +*************************************************************/ +SELECT + DISTINCT + il.MemberGUID as UserGUID, + Cast(Replace(LootID, 'MRDEPT|', '') as int) as DepartmentID +FROM + ( + SELECT + RA.IdentityGUID, + L.LootID, + P.ReadAllowPts, + P.ReadDenyPts + FROM + dbo.S3LootGroup LG WITH (READUNCOMMITTED) + INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED) ON L.LootID = LG.LootID + INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) ON LG.LootGroupID = RA.LootGroupID + INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID + INNER JOIN dbo.UserRole AS UR ON UR.RoleID = RA.RoleID + WHERE L.LootGroupPrefix='MRDEPT' AND UR.Category = 'MR' + ) AS acl + INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) on acl.identityguid = il.GroupingGUID + INNER JOIN dbo.UserProfile UP ON up.UserGUID = il.MemberGUID +GROUP BY + il.MemberGUID, + LootID +HAVING + SUM(acl.ReadAllowPts) > SUM(acl.ReadDenyPts) +GO + + +--------------------------------------------- + +-- dbo.viewS3ACLReadDepartmentForPRRoles +CREATE VIEW [dbo].[viewS3ACLReadDepartmentForPRRoles] as +/** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-06-27 HV JAZZ-39147 PR Roles - Prepare databases for MR PR security separation +*************************************************************/ +SELECT + DISTINCT + il.MemberGUID as UserGUID, + Cast(Replace(LootID, 'MRDEPT|', '') as int) as DepartmentID +FROM + ( + SELECT + RA.IdentityGUID, + L.LootID, + P.ReadAllowPts, + P.ReadDenyPts + FROM + dbo.S3LootGroup LG WITH (READUNCOMMITTED) + INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED) ON L.LootID = LG.LootID + INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) ON LG.LootGroupID = RA.LootGroupID + INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID + INNER JOIN dbo.UserRole AS UR ON UR.RoleID = RA.RoleID + WHERE L.LootGroupPrefix='MRDEPT' AND UR.Category = 'PR' + ) AS acl + INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) on acl.identityguid = il.GroupingGUID + INNER JOIN dbo.UserProfile UP ON up.UserGUID = il.MemberGUID +GROUP BY + il.MemberGUID, + LootID +HAVING + SUM(acl.ReadAllowPts) > SUM(acl.ReadDenyPts) +GO + + +--------------------------------------------- + +-- dbo.viewS3ACLReadMRDepartment +Create view [dbo].[viewS3ACLReadMRDepartment] as + +select + distinct + il.MemberGUID as UserGUID, + up.EmailAddress, + Cast(Replace(Replace(LootID, 'MRDEPT|', ''), 'DEPT|', '') as int) as DepartmentID +from + ( + SELECT + RA.IdentityGUID, + L.LootID, + ReadAllowPts, + ReadDenyPts + FROM + dbo.S3LootGroup LG WITH (READUNCOMMITTED) + INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED) ON L.LootID = LG.LootID + INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) ON LG.LootGroupID = RA.LootGroupID + INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID + where L.LootGroupPrefix='MRDEPT' or L.LootGroupPrefix='DEPT' + ) AS acl + INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) on acl.identityguid = il.GroupingGUID + INNER JOIN dbo.UserProfile UP ON up.UserGUID = il.MemberGUID + +group by + il.MemberGUID, + up.EmailAddress, + LootID + +having + sum(ReadAllowPts) > sum(ReadDenyPts) +GO + + +--------------------------------------------- + +-- dbo.viewS3ACLReadMROnlyDepartment +CREATE VIEW [dbo].[viewS3ACLReadMROnlyDepartment] as +/** Change History +************************************************************** +** CID Date Author WI Description +** 1 2021-02-02 KF JAZZ-14166 MR - Performance - Security / Dashboard Optimizations +*************************************************************/ +SELECT + DISTINCT + il.MemberGUID as UserGUID, + Cast(Replace(LootID, 'MRDEPT|', '') as int) as DepartmentID +FROM + ( + SELECT + RA.IdentityGUID, + L.LootID, + P.ReadAllowPts, + P.ReadDenyPts + FROM + dbo.S3LootGroup LG WITH (READUNCOMMITTED) + INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED) ON L.LootID = LG.LootID + INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) ON LG.LootGroupID = RA.LootGroupID + INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID + WHERE L.LootGroupPrefix='MRDEPT' + ) AS acl + INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) on acl.identityguid = il.GroupingGUID + INNER JOIN dbo.UserProfile UP ON up.UserGUID = il.MemberGUID +GROUP BY + il.MemberGUID, + LootID +HAVING + SUM(acl.ReadAllowPts) > SUM(acl.ReadDenyPts) +GO + + +--------------------------------------------- + +-- dbo.viewS3ACLReadWMOnlyDepartment +CREATE VIEW [dbo].[viewS3ACLReadWMOnlyDepartment] as +SELECT DISTINCT + il.MemberGUID as UserGUID, + Cast(Replace(LootID, 'DEPT|', '') as int) as DepartmentID + FROM + ( + SELECT + RA.IdentityGUID, + L.LootID, + P.ReadAllowPts, + P.ReadDenyPts + FROM + dbo.S3LootGroup LG WITH (READUNCOMMITTED) + INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED) + ON L.LootID = LG.LootID + INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) + ON LG.LootGroupID = RA.LootGroupID + INNER JOIN dbo.USERROLE RR WITH (READUNCOMMITTED) + ON RA.RoleID = RR.RoleID + INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) + ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID + WHERE RR.Category='WM' AND L.LootGroupPrefix='DEPT' + ) AS acl + INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) + ON acl.identityguid = il.GroupingGUID + INNER JOIN dbo.UserProfile UP ON + UP.UserGUID = il.MemberGUID + GROUP BY + il.MemberGUID, + LootID + HAVING SUM(acl.ReadAllowPts) > SUM(acl.ReadDenyPts) +GO + + +--------------------------------------------- + +-- dbo.viewS3ACLSimple +CREATE view dbo.viewS3ACLSimple +as + SELECT + IL.MemberGUID as UserGUID, + P.LootID as LootID, + cast(sum(cast(P.ReadValue as int)) as bit) as IsReadable, + cast(sum(cast(P.WriteValue as int)) as bit) as IsWritable, + cast(sum(cast(P.SecureValue as int)) as bit) as IsSecurable + FROM + dbo.UserProfile U with (readuncommitted) + INNER JOIN dbo.S3IdentityLink IL with (readuncommitted) on U.UserGUID = IL.MemberGUID + inner join dbo.S3SimplePermission P with (readuncommitted) on P.IdentityGUID = IL.GroupingGUID + GROUP BY + IL.MemberGUID, P.LootID +GO + + +--------------------------------------------- + +-- dbo.viewS3ACLWrite +------------------------------------------------------------------------------------------------------------ + +CREATE view [dbo].[viewS3ACLWrite] as +select + il.MemberGUID as UserGUID, + LootID +from + (SELECT + RA.IdentityGUID, + L.LootID, + ReadAllowPts, + ReadDenyPts, + WriteAllowPts, + WriteDenyPts, + SecureAllowPts, + SecureDenyPts, + DeleteAllowPts, + DeleteDenyPts, + CreateAllowPts, + CreateDenyPts + FROM + dbo.S3LootGroup LG WITH (READUNCOMMITTED) + INNER JOIN + dbo.S3Loot L WITH (READUNCOMMITTED) + ON L.LootID = LG.LootID + INNER JOIN + dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) + ON LG.LootGroupID = RA.LootGroupID + INNER JOIN + dbo.S3Permission P WITH (READUNCOMMITTED) + ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID) AS acl + inner join + dbo.S3IdentityLink il on acl.identityguid = il.GroupingGUID +group by + il.MemberGUID, + LootID +having + sum(WriteAllowPts) > sum(WriteDenyPts) +GO + + +--------------------------------------------- + +-- dbo.viewS3ACLWriteDepartment +CREATE view [dbo].[viewS3ACLWriteDepartment] as + +select + il.MemberGUID as UserGUID, + Cast(Replace(LootID, 'DEPT|', '') as int) as DepartmentID +from + ( + SELECT + RA.IdentityGUID, + L.LootID, + WriteAllowPts, + WriteDenyPts + FROM + dbo.S3LootGroup LG WITH (READUNCOMMITTED) + INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED) ON L.LootID = LG.LootID + INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) ON LG.LootGroupID = RA.LootGroupID + INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID + where L.LootGroupPrefix='DEPT' + ) AS acl + INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) on acl.identityguid = il.GroupingGUID + +group by + il.MemberGUID, + LootID + +having + sum(WriteAllowPts) > sum(WriteDenyPts) +GO + + +--------------------------------------------- + +-- dbo.viewS3GroupAssignment +CREATE view [dbo].[viewS3GroupAssignment] as +select + UG.UserGroupGUID, + UG.Name as UserGroupName, + UP.UserGUID as UserGUID, + UP.NameFirst + ' ' + UP.NameLast as UserName +from + S3IdentityLink IL + inner join UserGroup UG with (readuncommitted) on UG.UserGroupGUID = IL.GroupingGUID + inner join UserProfile UP with (readuncommitted) on UP.UserGUID = IL.MemberGUID +GO + + +--------------------------------------------- + +-- dbo.viewS3IdentityLinkOrphans +CREATE view viewS3IdentityLinkOrphans +as + select + il.*, + 'Broken Link' as Reason + from + [dbo].[S3IdentityLink] il (readuncommitted) + left join [dbo].[S3IdentityLink] p (readuncommitted) on p.Fullpath = replace(il.Fullpath, '\' + cast(il.GroupingGUID as nvarchar(36)), '') + where + il.Distance > 0 + and p.MemberGUID is null + + union all + + select + il.*, + 'Invalid Group' as Reason + from + [dbo].[S3IdentityLink] il (readuncommitted) + where + il.MemberGUID != il.GroupingGUID + and il.GroupingGUID not in(select ug.UserGroupGUID from [dbo].[UserGroup] ug) + + union all + + select + il.*, + 'Missing Member' as Reason + from + [dbo].[S3IdentityLink] il (readuncommitted) + where + not exists (select 1 from [dbo].[UserProfile] up (readuncommitted) where up.UserGUID = il.MemberGUID) + and not exists (select 1 from [dbo].[UserGroup] ug (readuncommitted) where ug.UserGroupGUID = il.MemberGUID) +GO + + +--------------------------------------------- + +-- dbo.viewS3PermissionSet +create view viewS3PermissionSet as +select + ps.PermissionSetID, ps.Name as PermissionSetName, ur.RoleID, ur.Name as RoleName, p.Weight, p.ReadValue, p.WriteValue, p.SecureValue, p.CreateValue, p.DeleteValue +from + S3PermissionSet ps + inner join S3Permission p on ps.PermissionSetID = p.PermissionSetID + inner join UserRole ur on p.RoleID = ur.RoleID +GO + + +--------------------------------------------- + +-- dbo.viewS3RoleAssignment +CREATE view [dbo].[viewS3RoleAssignment] as +select + lg.LootID as LootGroupID, + ra.RoleID, + il.memberguid as IdentityGUID, + case when min(il.Distance ) = 0 and max(case when lg.LootID = lg.LootGroupID then 1 else 0 end) = 1 then cast(1 as bit) else cast(0 as bit) end as IsDirectlyAssigned +from + S3LootGroup lg with (readuncommitted) + inner join S3RoleAssignment ra with (readuncommitted) on lg.LootGroupID = ra.LootGroupID + inner join S3identitylink il with (readuncommitted) on ra.IdentityGUID = il.GroupingGUID +group by + il.memberguid, + lg.LootID, + ra.RoleID +GO + + +--------------------------------------------- + +-- dbo.viewS3RoleAssignmentDetail +CREATE view [dbo].[viewS3RoleAssignmentDetail] as +select + RA.RowID, + UP.UserGUID, + UP.NameFirst + ' ' + UP.NameLast as UserName, + RA.IdentityGUID, + isnull(IUG.Name, IUP.NameFull) as IdentityName, + il.distance as UserGroupDistance, + case when LG.LootGroupID = LG.LootID then 0 else 1 end as LootDistance, + il.Distance + case when LG.LootGroupID = LG.LootID then 0 else 1 end as Distance, + RA.RoleID, + UR.Name as RoleName, + LG.LootID, + LG.LootGroupID, + isnull(case when LG.LootID = LG.LootGroupID then cast(1 as bit) else cast(0 as bit) end, cast(0 as bit)) as IsDirectAssignment +from + S3RoleAssignment RA (readuncommitted) + inner join S3LootGroup LG (readuncommitted) on LG.LootGroupID = RA.LootGroupID + inner join S3IdentityLink IL (readuncommitted) on IL.GroupingGUID = RA.IdentityGUID + inner join UserProfile UP (readuncommitted) on UP.UserGUID = IL.MemberGUID + inner join UserRole UR (readuncommitted) on UR.RoleID = RA.RoleID + left join UserProfile IUP (readuncommitted) on IUP.UserGUID = IL.GroupingGUID + left join UserGroup IUG (readuncommitted) on IUG.UserGroupGUID = IL.GroupingGUID +GO + + +--------------------------------------------- + +-- dbo.viewS3RoleAssignmentDirect +CREATE view [dbo].[viewS3RoleAssignmentDirect] as +select + ra.LootGroupID, + ra.RoleID, + ra.IdentityGUID as IdentityGUID, + isnull(cast(1 as bit),cast(1 as bit)) as IsDirectlyAssigned +from + --S3LootGroup lg with (readuncommitted) + --inner join + S3RoleAssignment ra with (readuncommitted) --on lg.LootGroupID = ra.LootGroupID + +group by + ra.IdentityGUID, + ra.LootGroupID, + ra.RoleID +GO + + +--------------------------------------------- + +-- dbo.viewS3RoleAssignmentNoGroupBy +create view [dbo].[viewS3RoleAssignmentNoGroupBy] as +select + lg.LootID as LootGroupID, + ra.RoleID, + il.memberguid as IdentityGUID, + case when il.Distance = 0 and lg.LootID = lg.LootGroupID then cast(1 as bit) else cast(0 as bit) end as IsDirectlyAssigned +from + S3LootGroup lg with (readuncommitted) + inner join S3RoleAssignment ra with (readuncommitted) on lg.LootGroupID = ra.LootGroupID + inner join S3identitylink il with (readuncommitted) on ra.IdentityGUID = il.GroupingGUID +GO + + +--------------------------------------------- + +-- dbo.viewSR2CorrelationGroupMember +create view [dbo].[viewSR2CorrelationGroupMember] +as + select + cgm.*, cg.Name as GroupName + from + SR2CorrelationGroupMember cgm + inner join SR2CorrelationGroup cg on cgm.CorrelationGroupGUID = cg.CorrelationGroupGUID +GO + + +--------------------------------------------- + +-- dbo.viewSR2RiskResultDetail +CREATE view dbo.viewSR2RiskResultDetail as +select + rrdet.RowID + ,rrdet.DetailGUID + ,rrdet.RiskResultGUID + ,rrdet.TrialNumber + ,rrdet.OutputGUID + ,rr.Bincount as BinNumber + ,rrdet.Value + ,rrdet.HistoryItemGUID + ,rrdet.IsDeleted + ,rr.RiskConfigGUID + ,rr.Name as RiskResultName + ,rr.DateCreated + ,rrdet.CachedOutputName as [RiskConfigOutputName] + ,rrdet.OutputUniqueID + ,rrdet.CachedOutputDisplayFormat + ,(select top 1 srdet.valuebaseline + from [dbo].[SR2SensitivityResultDetail] srdet (readuncommitted) + inner join [dbo].[SR2SensitivityResult] sr (readuncommitted) on sr.SensitivityResultGUID = srdet.SensitivityResultGUID + where rrdet.OutputGUID=srdet.OutputGUID + order by sr.DateCreated desc) as SensitivityBaseline +from [dbo].[SR2RiskResultDetail] rrdet (readuncommitted) +inner join [dbo].[SR2RiskResult] rr (readuncommitted) on rr.RiskResultGUID = rrdet.RiskResultGUID +GO + + +--------------------------------------------- + +-- dbo.viewSR2SensitivityResultDetail +CREATE view [dbo].[viewSR2SensitivityResultDetail] as + +select + srdet.OutputGUID + ,Max(srdet.ValueBaseline) as [ValueBaseline] + ,srdet.IsDeleted + ,sr.SensitivityResultGUID + ,sr.Name as [SensitivityResultName] + ,sr.DateCreated + ,srdet.CachedOutputName as [SensitivityConfigOutputName] + ,srdet.OutputUniqueID + ,srdet.CachedGroupName as [GroupName] + ,ABS(Sum(srdet.ValueHigh)-Sum(srdet.ValueLow)) as SensitivityCalculation + ,Case When Sum(srdet.ValueHigh) > Sum(srdet.ValueBaseline) Then (Sum(srdet.ValueHigh) - Sum(srdet.ValueBaseline)) Else (Sum(srdet.ValueBaseline) - Sum(srdet.ValueHigh)) End as DeltaHigh + ,Case When Sum(srdet.ValueLow) < Sum(srdet.ValueBaseline) Then (Sum(srdet.ValueLow) - Sum(srdet.ValueBaseline)) Else (Sum(srdet.ValueBaseline) - Sum(srdet.ValueLow)) End as DeltaLow + ,srdet.CachedOutputDisplayFormat +from [dbo].[SR2SensitivityResultDetail] srdet (readuncommitted) +inner join [dbo].[SR2SensitivityResult] sr (readuncommitted) on sr.SensitivityResultGUID = srdet.SensitivityResultGUID where srdet.CachedGroupName<>'' +Group By + srdet.OutputGUID + ,srdet.IsDeleted + ,sr.SensitivityResultGUID + ,sr.Name + ,sr.DateCreated + ,srdet.CachedOutputName + ,srdet.OutputUniqueID + ,srdet.CachedGroupName + ,srdet.CachedOutputDisplayFormat + +Union All + +select + srdet.OutputGUID + ,srdet.ValueBaseline + ,srdet.IsDeleted + ,sr.SensitivityResultGUID + ,sr.Name as [SensitivityResultName] + ,sr.DateCreated + ,srdet.CachedOutputName as [SensitivityConfigOutputName] + ,srdet.OutputUniqueID + ,srdet.CachedInputName as [GroupName] + ,ABS(srdet.ValueHigh-srdet.ValueLow) as SensitivityCalculation + ,Case When srdet.ValueHigh > srdet.ValueBaseline Then (srdet.ValueHigh - srdet.ValueBaseline) Else (srdet.ValueBaseline - srdet.ValueHigh) End as DeltaHigh + ,Case When srdet.ValueLow < srdet.ValueBaseline Then (srdet.ValueLow - srdet.ValueBaseline) Else (srdet.ValueBaseline - srdet.ValueLow) End as DeltaLow + ,srdet.CachedOutputDisplayFormat +from [dbo].[SR2SensitivityResultDetail] srdet (readuncommitted) +inner join [dbo].[SR2SensitivityResult] sr (readuncommitted) on sr.SensitivityResultGUID = srdet.SensitivityResultGUID where srdet.CachedGroupName='' +GO + + +--------------------------------------------- + +-- dbo.viewScoreAttribute +CREATE view [dbo].[viewScoreAttribute] +AS +select + * +from dbo.viewScoreAttributeCore30 +GO + + +--------------------------------------------- + +-- dbo.viewScoreAttributeCore30 +CREATE VIEW [dbo].[viewScoreAttributeCore30] +AS +select + A.AttributeGUID, + D.DimensionGUID, + A.DimensionGroupGUID, + A.FriendlyName, + A.IsWrittenToDB, + A.IsSecuredLootConfigID, + A.IsSecuredLootGroupID, + A.IsSecuredLootID, + A.SecuredLootGroupPrefix, + A.DefaultSortAttributeGUID, + A.ForeignKeyGUID, + A.IsRequired, + A.SpecialAttributeIndex, + A.IsCopiedWithPlan, + A.[CustomNumberFormat], + A.[IsCustomNumberFormat], + A.DisplayOrder, + A.IsHidden, + A.DSSIsUsed, + A.IsLocked, + A.IsKey, + A.JoinTypeVal, + A.DateModified, + A.SQLColumnName, -- need to use this, cause we have to update it , the join pulls in the rest of the data + A.AttributeType, + A.MetaXML, + A.InferredSourceGUID, + A.InferredAttributeGUID, + A.InferredColumnName, + A.HelpText, + dbo.GetSQLTableExpression(D.SQLSchemaName, D.SQLObjectName) as [DimensionSQLObjectExpression], + g.SchemaName as DimensionGroupSQLSchemaName, + g.ObjectName as DimensionGroupSQLObjectName, + g.Name as [CachedDimensionGroupName], + isnull(case when 1 = dbo.TableExists(g.SchemaName,g.ObjectName) then CAST(1 as bit) else cast(0 as bit) end, CAST(0 as bit)) as DimensionGroupIsTable, + D.SQLTableAlias as [DimensionSQLTableAlias], + D.sqltablealias + A.SQLColumnName as SQLColumnAlias, + D.IsSecured as [IsDimensionSecured], + D.IsSecuredSetupOnly as [IsDimensionSecuredSetupOnly], + D.FriendlyName as [DimensionName], + A.[ColumnType], + A.[ComputedValueDefinition], + A.[IsComputed], + A.[IsIdentity], + A.[IdentityIncrement], + A.[IdentitySeed], + A.[IsNullable], + A.[DefaultValueDefinition], + A.[Precision], + A.[Scale], + A.[MaxLength], + A.[IsColumnExist], + A.ForeignKeyHierarchyGUID, + ISNULL(FH.FriendlyName, '') as [CachedFKHierarchyName], + ISNULL(FK.FriendlyName,'') as [CachedFKMemberName], + ISNULL(FKD.FriendlyName,'') as [CachedFKDimensionName], + ISNULL(FKD.DimensionGUID,dbo.ZeroGUID()) as [CachedFKDimensionGUID], + ISNULL(FKD.DefaultLookupKeyGUID, dbo.ZeroGUID()) as [CachedFKDefaultLookupKeyGUID], + --ISNULL(FKG.Name,'') as [CachedDimensionGroupName], + A.IsForeignKeyed, + A.ForeignKeySchema, + A.ForeignKeyTable, + A.ForeignKeyColumn, + A.ForeignKeyOnDelete + ,ISNULL(IA.SQLColumnName, '') as [CachedInferredSQLColumnName] + ,ISNULL(IAG.SchemaName, '') as [CachedInferredSQLSchemaName] + ,ISNULL(IAG.ObjectName, '') as [CachedInferredSQLObjectName] + ,A.[CachedInferredSQLColumnType] + ,A.IsFKAutoFilter + ,D.DimensionVersion as [DimensionVersion] + ,A.IsFormField + ,A.FrameworkID + ,A.IsModelDriver +from ScoreAttribute A (readuncommitted) + inner join ScoreAttributeType AT (readuncommitted) on AT.ScoreAttributeTypeID = A.AttributeType + inner join ScoreDimensionGroup G (readuncommitted) on A.DimensionGroupGUID = G.DimensionGroupGUID + inner join ScoreDimension D (readuncommitted) on G.DimensionGUID = D.DimensionGUID + + --foreign key + left join ScoreAttribute FK (readuncommitted) on FK.AttributeGUID = A.ForeignKeyGUID + left join ScoreDimensionGroup FKG (readuncommitted) on FKG.DimensionGroupGUID = FK.DimensionGroupGUID + left join ScoreDimension FKD (readuncommitted) on FKD.DimensionGUID = FKG.DimensionGUID + --foreign hierarchy + left join ScoreHierarchy FH (readuncommitted) on FH.HierarchyGUID = A.ForeignKeyHierarchyGUID + --infer + left join ScoreAttribute IA (readuncommitted) on IA.AttributeGUID = A.InferredAttributeGUID + left join ScoreDimensionGroup IAG (readuncommitted) on IA.DimensionGroupGUID = IAG.DimensionGroupGUID + left join ScoreDimension IAD (readuncommitted) on IAD.DimensionGUID = IAG.DimensionGUID +GO + + +--------------------------------------------- + +-- dbo.viewScoreAttributeFramework +CREATE view dbo.viewScoreAttributeFramework +as + select distinct * from ( + select + a.AttributeGUID, + a.FrameworkID + from + viewScoreAttribute a + where + a.FrameworkID != 0 + union all + select + a.AttributeGUID, + df.FrameworkID + from + viewScoreAttribute a + inner join ScoreDimension d on d.DimensionGUID = a.DimensionGUID + inner join ScoreDimensionFramework df on df.DimensionGUID = d.DimensionGUID + where + a.FrameworkID = 0 + union all + select + a.AttributeGUID, + fkdf.FrameworkID + from + viewScoreAttribute a + inner join ScoreDimension d on d.DimensionGUID = a.DimensionGUID + inner join ScoreDimension fkd on fkd.FriendlyName = a.CachedFKDimensionName + inner join ScoreDimensionFramework fkdf on fkdf.DimensionGUID = fkd.DImensionGUID + where + a.FrameworkID = 0 + union all + select + a.AttributeGUID, + idf.FrameworkID + from + viewScoreAttribute a + inner join ScoreDimension d on d.DimensionGUID = a.DimensionGUID + inner join viewScoreAttribute ia on ia.AttributeGUID = a.InferredSourceGUID + inner join ScoreDimension id on id.FriendlyName = ia.CachedFKDimensionName + inner join ScoreDimensionFramework idf on idf.DimensionGUID = id.DImensionGUID + where + a.FrameworkID = 0 + ) a +GO + + +--------------------------------------------- + +-- dbo.viewScoreAttributeSchemaInfo +CREATE VIEW [viewScoreAttributeSchemaInfo] +AS +select + A.AttributeGUID, + isnull(case when 1 = dbo.TableExists(g.SchemaName,g.ObjectName) then CAST(1 as bit) else cast(0 as bit) end, CAST(0 as bit)) as DimensionGroupIsTable, + case when AT.ScoreAttributeTypeID = 3 then ISNULL(IAC.ColumnTypeValue,0) else ISNULL(COL.ColumnTypeValue,0) end as [ColumnType], + case when AT.ScoreAttributeTypeID = 3 then '' else ISNULL(COL.ComputedValueDefinition,'') end as [ComputedValueDefinition], + case when AT.ScoreAttributeTypeID = 3 then 0 else ISNULL(COL.IsComputed, 0) end as [IsComputed], + case when AT.ScoreAttributeTypeID = 3 then ISNULL(IAC.IsIdentity, 0) else ISNULL(COL.IsIdentity, 0) end as [IsIdentity], + case when AT.ScoreAttributeTypeID = 3 then -1 else ISNULL(COL.IdentityIncrement, 1) end as [IdentityIncrement], + case when AT.ScoreAttributeTypeID = 3 then -1 else ISNULL(COL.IdentitySeed, 1) end as [IdentitySeed], + case when AT.ScoreAttributeTypeID = 3 then ISNULL(IAC.IsNullable, 0) else ISNULL(COL.IsNullable, 0) end as [IsNullable], + case when AT.ScoreAttributeTypeID = 3 then ISNULL(IAC.DefaultValueDefinition, '') else ISNULL(COL.DefaultValueDefinition, '') end as [DefaultValueDefinition], + case when AT.ScoreAttributeTypeID = 3 then ISNULL(IAC.Precision, 0) else ISNULL(COL.Precision, 0) end as [Precision], + case when AT.ScoreAttributeTypeID = 3 then ISNULL(IAC.Scale,0) else ISNULL(COL.Scale,0) end as [Scale], + case when AT.ScoreAttributeTypeID = 3 then ISNULL(IAC.MaxLength,0) else ISNULL(COL.MaxLength,0) end as [MaxLength], + ISNULL(cast((case when COL.ColumnName is null then 0 else 1 end) as bit), 0) as [IsColumnExist], + isnull(COL.IsForeignKeyed,CAST(0 as bit)) as IsForeignKeyed, + isnull(COL.ForeignKeySchema,'') as ForeignKeySchema, + isnull(COL.ForeignKeyTable,'') as ForeignKeyTable, + isnull(COL.ForeignKeyColumn,'') as ForeignKeyColumn, + isnull(COL.ForeignKeyOnDelete,'') as ForeignKeyOnDelete + ,isnull(IA.SQLColumnName, '') as [CachedInferredSQLColumnName] + ,isnull(IAC.ColumnTypeValue,0) as [CachedInferredSQLColumnType] +from ScoreAttribute A + inner join ScoreAttributeType AT on AT.ScoreAttributeTypeID = A.AttributeType + inner join ScoreDimensionGroup G on A.DimensionGroupGUID = G.DimensionGroupGUID + inner join ScoreDimension D on G.DimensionGUID = D.DimensionGUID + left join viewSysColumns COL on COL.ColumnName = A.SQLColumnName + AND case when AT.ScoreAttributeTypeID = 1 then G.ObjectName ELSE D.SQLObjectName end = COL.ObjectName --CHANGED + and case when AT.ScoreAttributeTypeID = 1 then G.SchemaName ELSE D.SQLSchemaName end = COL.SchemaName --CHANGED group could have different schema + + --foreign key + left join ScoreAttribute FK on FK.AttributeGUID = A.ForeignKeyGUID + left join ScoreDimensionGroup FKG on FKG.DimensionGroupGUID = FK.DimensionGroupGUID + left join ScoreDimension FKD on FKD.DimensionGUID = FKG.DimensionGUID + + --infer + left join ScoreAttribute IA on IA.AttributeGUID = A.InferredAttributeGUID + left join ScoreAttributeType AIT on AIT.ScoreAttributeTypeID = IA.AttributeType --CHANGED Was looking at the base Attribute type not the type of the inferred + left join ScoreDimensionGroup IAG on IA.DimensionGroupGUID = IAG.DimensionGroupGUID + left join ScoreDimension IAD on IAD.DimensionGUID = IAG.DimensionGUID + left join viewSysColumns IAC on IAC.ColumnName = IA.SQLColumnName + AND case when AIT.ScoreAttributeTypeID = 1 then IAG.ObjectName ELSE IAD.SQLObjectName end = IAC.ObjectName --CHANGED Was a straight join on the inferred attribute info (could be calculated on the base) + and case when AIT.ScoreAttributeTypeID = 1 then IAG.SchemaName ELSE IAD.SQLSchemaName end = IAC.SchemaName --CHANGED schema same as above +GO + + +--------------------------------------------- + +-- dbo.viewScoreAttribute_StrataSchema +CREATE view [dbo].[viewScoreAttribute_StrataSchema] +AS +select + A.AttributeGUID + ,A.DimensionGUID + ,A.DimensionGroupGUID + ,A.FriendlyName + ,A.IsWrittenToDB + ,A.IsSecuredLootConfigID + ,A.IsSecuredLootGroupID + ,A.IsSecuredLootID + ,A.SecuredLootGroupPrefix + ,A.DefaultSortAttributeGUID + ,A.ForeignKeyGUID + ,A.IsRequired + ,A.SpecialAttributeIndex + ,A.IsCopiedWithPlan + ,A.CustomNumberFormat + ,A.IsCustomNumberFormat + ,A.DisplayOrder + ,A.IsHidden + ,A.DSSIsUsed + ,A.IsLocked + ,A.IsKey + ,A.JoinTypeVal + ,A.DateModified + ,A.SQLColumnName + ,A.AttributeType + ,A.MetaXML + ,A.InferredSourceGUID + ,A.InferredAttributeGUID + ,A.InferredColumnName + ,A.HelpText + ,A.DimensionSQLObjectExpression + ,A.DimensionGroupSQLSchemaName + ,A.DimensionGroupSQLObjectName + ,A.CachedDimensionGroupName + ,A.DimensionGroupIsTable + ,A.DimensionSQLTableAlias + ,A.SQLColumnAlias + ,A.IsDimensionSecured + ,A.IsDimensionSecuredSetupOnly + ,A.DimensionName + ,A.ColumnType + ,A.ComputedValueDefinition + ,A.IsComputed + ,A.IsIdentity + ,A.IdentityIncrement + ,A.IdentitySeed + ,A.IsNullable + ,A.DefaultValueDefinition + ,A.Precision + ,A.Scale + ,A.MaxLength + ,A.IsColumnExist + ,A.ForeignKeyHierarchyGUID + ,A.CachedFKHierarchyName + ,A.CachedFKMemberName + ,A.CachedFKDimensionName + ,A.CachedFKDimensionGUID + ,A.CachedFKDefaultLookupKeyGUID + ,A.IsForeignKeyed + ,A.ForeignKeySchema + ,A.ForeignKeyTable + ,A.ForeignKeyColumn + ,A.ForeignKeyOnDelete + ,A.CachedInferredSQLColumnName + ,A.CachedInferredSQLSchemaName + ,A.CachedInferredSQLObjectName + ,A.CachedInferredSQLColumnType + ,A.IsFKAutoFilter + ,A.DimensionVersion + ,A.IsFormField + ,A.FrameworkID + ,A.IsModelDriver + ,CAST(COALESCE(ATS.IsCustom, 0) AS BIT) AS IsCustom + ,CAST(COALESCE(ATS.IsMarkedForDeletion, 0) AS BIT) AS IsMarkedForDeletion + ,CAST(COALESCE(ATS.IsUsed, 1) AS BIT) AS IsUsed + ,CAST(COALESCE(ATS.CAPIsUsed, 1) AS BIT) AS CAPIsUsed + ,CAST(COALESCE(ATS.MRIsUsed, 1) AS BIT) AS MRIsUsed + ,CAST(COALESCE(ATS.OBIsUsed, 1) AS BIT) AS OBIsUsed + ,CAST(COALESCE(ATS.PRIsUsed, 1) AS BIT) AS PRIsUsed + ,CAST(COALESCE(ATS.SPIsUsed, 1) AS BIT) AS SPIsUsed +from dbo.viewScoreAttributeCore30 A +LEFT JOIN [dbo].[ScoreAttributeSetting] ATS ON ATS.AttributeGUID = A.AttributeGUID +GO + + +--------------------------------------------- + +-- dbo.viewScoreCompositeLinkDetail +CREATE view [dbo].[viewScoreCompositeLinkDetail] as +select + scl.*, + sc.FriendlyName as CompositeName, + dt1.DataTableGUID as DataTable1GUID, + dt1.FriendlyName as DataTable1Name, + dt2.DataTableGUID as DataTable2GUID, + dt2.FriendlyName as DataTable2Name, + sk1.AttributeGUID as MappingKeyGUID, + sk1.FriendlyName as MappingKeyName, + isnull(msr.MeasureGUID, dbo.ZeroGUID()) as PlaceholderMeasureGUID, + isnull(msr.FriendlyName, '') as PlaceholderMeasureName, + sk2.AttributeGUID as DataKeyGUID, + sk2.FriendlyName as DataKeyName, + sdg1.DimensionGUID as MappingDimensionGUID, + sdg2.DimensionGUID as DataDimensionGUID, + sd2.FriendlyName as DataDimensionName +from + ScoreComposite sc + inner join scoredatatable dt1 on sc.DataTableGUID1 = dt1.DataTableGUID + inner join scoredatatable dt2 on sc.DataTableGUID2 = dt2.DataTableGUID + inner join ScoreCompositeLink scl on sc.CompositeGUID = scl.CompositeGUID + inner join ScoreAttribute sk1 on scl.Key1GUID = sk1.AttributeGUID + inner join ScoreDimensionGroup sdg1 on sk1.DimensionGroupGUID = sdg1.DimensionGroupGUID + inner join ScoreAttribute sk2 on scl.Key2GUID = sk2.AttributeGUID + inner join ScoreDimensionGroup sdg2 on sk2.DimensionGroupGUID = sdg2.DimensionGroupGUID + inner join ScoreDimension sd2 on sdg2.DimensionGUID = sd2.DimensionGUID + left join ScoreMeasure msr on scl.PlaceholderIndexMeasureGUID = msr.MeasureGUID +GO + + +--------------------------------------------- + +-- dbo.viewScoreDataSource +CREATE View [dbo].[viewScoreDataSource] +AS +select * from +( + select + DatatableGUID as DataSourceGUID, + FriendlyName as FriendlyName, + 0 as DataSourceType + from + ScoreDataTable + + UNION + + select + CompositeGUID as DataSourceGUID, + FriendlyName as FriendlyName, + 1 as DataSourceType + from + ScoreComposite +) AS Test +GO + + +--------------------------------------------- + +-- dbo.viewScoreDataTable +CREATE VIEW [dbo].[viewScoreDataTable] + AS + select + DataTableGUID, + FriendlyName, + Description, + SQLTableAlias, + IsWrittenToDB, + DisplayFormatAttributeGUID, + DisplayFormatAttributeDimensionGUID, + IsCompositeMappingTable, + IsCompositeBoundsTable, + FrameworkID, + SQLSchemaName, + SQLObjectName, + IsWrittenIfZero, + GlobalID, + ModifiedAt, + IsClientFriendly, + OverrideLoadBySQLSchemaName, + OverrideLoadBySQLObjectName, + IsGeneratingSelectIntoTempTable, + ModelQueryHint, + DIDeleteQueryHint, + ISNULL(cast(case when object_ID(dbo.GetSQLTableExpression(SQLSchemaName, SQLObjectName)) is not null then 1 else 0 end as bit), cast(0 as bit)) as [IsBackingObjectExist], + ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(SQLSchemaName, SQLObjectName)), 'IsView') as bit), cast(0 as bit)) as [IsView] +from + ScoreDataTable +GO + + +--------------------------------------------- + +-- dbo.viewScoreDataTableBadColumns +create view viewScoreDatatableBadColumns as +select sd.datatableguid, sd.friendlyname, sa.attributeguid, sa.sqlcolumnname, sm.measureguid +from + scoredatatable sd + inner join scoredatatablekeylink kl on sd.datatableguid = kl.datatableguid + inner join scoreattribute sa on kl.keyguid = sa.attributeguid + left join scoremeasure sm on sm.datatableguid = kl.datatableguid and sm.sqlcolumnname = sa.sqlcolumnname +where + sm.measureguid is not null +GO + + +--------------------------------------------- + +-- dbo.viewScoreDataTableKeyLink +CREATE view [dbo].[viewScoreDataTableKeyLink] as +select + + dt.SQLTableAlias, + sd.FriendlyName as DimensionName, + sd.GlobalID as DimensionGlobalID, + sa.FriendlyName, + + --dt.SQLSchemaName, + --dt.SQLObjectName, + --sa.SQLColumnName, + sdg.DimensionGUID, + --careful if you edit this view as these col columns need to be last! + --and if you add/remove columns before them you need to update the codegen + dtkl.IsRequired, + dtkl.DataTableKeyLinkGUID, + dtkl.DataTableGUID, + dtkl.KeyGUID, + dtkl.ObjectID, + dtkl.ColumnID, + dtkl.SchemaName, + dtkl.ObjectName, + dtkl.ColumnName, + dtkl.ObjectType, + dtkl.MaxLength, + dtkl.IsComputed, + dtkl.IsNullable, + dtkl.Scale, + dtkl.Precision, + dtkl.IsIdentity, + dtkl.ColumnTypeValue, + dtkl.IdentityIncrement, + dtkl.IdentitySeed, + dtkl.DefaultValueDefinition, + dtkl.IsPartOfUniqueIndex, + dtkl.IsUniqueIndex, + dtkl.IsPartOfPrimaryKey, + dtkl.IsPrimaryKey, + dtkl.ComputedValueDefinition, + dtkl.IsForeignKeyed, + dtkl.ForeignKeySchema, + dtkl.ForeignKeyTable, + dtkl.ForeignKeyColumn, + dtkl.ForeignKeyOnDelete, + dtkl.ModifiedAt + +from + ScoreDataTableKeyLink dtkl + inner join ScoreDataTable dt on dt.DataTableGUID = dtkl.DataTableGUID + inner join ScoreAttribute sa on dtkl.KeyGUID = sa.AttributeGUID + inner join ScoreDimensionGroup sdg on sa.DimensionGroupGUID = sdg.DimensionGroupGUID + inner join ScoreDimension sd on sdg.DimensionGUID = sd.DimensionGUID +GO + + +--------------------------------------------- + +-- dbo.viewScoreDataTableKeyLinkSchemaInfo +create view viewScoreDataTableKeyLinkSchemaInfo as +select + m.DataTableKeyLinkGUID, + col.* +from + ScoreDataTableKeyLink m + INNER JOIN dbo.ScoreDataTable dt ON m.DataTableGUID = dt.DataTableGUID + INNER JOIN dbo.ScoreAttribute SA on m.keyguid = sa.attributeguid + + --should be inner? should it use something more specialized? + INNER JOIN viewSysColumns col on + col.SchemaName = dt.SQLSchemaName + and col.ObjectName = dt.SQLObjectName + and col.ColumnName = sa.SQLColumnName +GO + + +--------------------------------------------- + +-- dbo.viewScoreDataTableKeyLink_StrataSchema +CREATE VIEW dbo.viewScoreDataTableKeyLink_StrataSchema AS +SELECT + DTKL.DataTableKeyLinkGUID + ,DTKL.DataTableGUID + ,DTKL.KeyGUID + ,DTKL.ObjectID + ,DTKL.ColumnID + ,DTKL.SchemaName + ,DTKL.ObjectName + ,DTKL.ColumnName + ,DTKL.ObjectType + ,DTKL.MaxLength + ,DTKL.IsComputed + ,DTKL.IsNullable + ,DTKL.Scale + ,DTKL.Precision + ,DTKL.IsIdentity + ,DTKL.ColumnTypeValue + ,DTKL.IdentityIncrement + ,DTKL.IdentitySeed + ,DTKL.DefaultValueDefinition + ,DTKL.IsPartOfUniqueIndex + ,DTKL.IsUniqueIndex + ,DTKL.IsPartOfPrimaryKey + ,DTKL.IsPrimaryKey + ,DTKL.ComputedValueDefinition + ,DTKL.IsForeignKeyed + ,DTKL.ForeignKeySchema + ,DTKL.ForeignKeyTable + ,DTKL.ForeignKeyColumn + ,DTKL.ForeignKeyOnDelete + ,DTKL.ModifiedAt + ,DTKL.IsRequired + ,DTKL.Description + ,D.DimensionGuid + ,CAST(COALESCE(KLS.IsCustom, 0) AS BIT) AS IsCustom + ,CAST(COALESCE(KLS.IsUsed, 1) AS BIT) AS IsUsed + ,CAST(COALESCE(KLS.IsMarkedForDeletion, 0) AS BIT) AS IsMarkedForDeletion +FROM [dbo].[ScoreDataTableKeyLink] DTKL +INNER JOIN [dbo].[ScoreDimension] D ON D.DefaultKeyGUID = DTKL.KeyGUID +LEFT JOIN [dbo].[ScoreKeyLinkSetting] KLS ON DTKL.DataTableGUID = KLS.DataTableGUID AND DTKL.KeyGUID = KLS.KeyGUID +GO + + +--------------------------------------------- + +-- dbo.viewScoreDataTable_StrataSchema +CREATE VIEW viewScoreDataTable_StrataSchema +AS + SELECT + DT.DataTableGUID + ,DT.FriendlyName + ,DT.Description + ,DT.SQLSchemaName + ,DT.SQLObjectName + ,DT.SQLTableAlias + ,DT.IsWrittenToDB + ,DT.DisplayFormatAttributeGUID + ,DT.DataTableID + ,DT.SQLTableAliasUnique + ,DT.IsCompositeMappingTable + ,DT.FrameworkID + ,DT.ModifiedAt + ,DT.IsWrittenIfZero + ,DT.GlobalID + ,DT.IsCompositeBoundsTable + ,DT.DisplayFormatAttributeDimensionGUID + ,DT.IsClientFriendly + ,DT.OverrideLoadBySQLSchemaName + ,DT.OverrideLoadBySQLObjectName + ,CAST(COALESCE(dts.IsRequired, 1) AS BIT) IsRequired + ,CAST(COALESCE(dts.IsUsed, 1) AS BIT) IsUsed + FROM + [dbo].[ScoreDataTable] dt + LEFT JOIN [dbo].[ScoreDatatableSetting] dts ON dts.DataTableGUID = dt.DataTableGUID +GO + + +--------------------------------------------- + +-- dbo.viewScoreDimension +CREATE view [dbo].[viewScoreDimension] +as + select + sd.DefaultHierarchyGUID, + sd.DefaultKeyGUID, + sd.DefaultLookupKeyGUID, + sd.HelpTextAttributeGUID, + sd.PrimaryGroupGUID, + sd.DimensionGUID, + sd.FriendlyName, + sd.IsSecured, + sd.PermissionSetID, + sd.SQLObjectName, + sd.SQLSchemaName, + sd.SQLTableAlias, + sd.DefaultMemberGUID, + sd.IsSysAdminOnly, + sd.IsAllowMemberDelete, + sd.IsAllowMemberAdd, + sd.IsSharingSecurity, + sd.IsStock, + sd.IsSensitivityRiskHidden, + sd.Description, + sd.PHIDisclaimer, + sd.CopyrightDisclaimer, + sd.DateModified, + sd.PickerType, + sd.DimensionVersion, + sd.IsGeneratingWrapperView, + sd.GlobalID, + sd.DimensionEditorMode, + sd.IsSecuredSetupOnly, + sd.IsClientFriendly, + sd.IsEditable, + sd.IsCustomAttributeAllowed, + sd.IsCustom, + sd.ParentDimensionGUID, + sd.IsStandard, + sd.StandardCodesLastUpdated, + sd.StandardCodesVersion, + sd.IsDisablingHistoryTriggers, + ISNULL(cast(case when object_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)) is not null then 1 else 0 end as bit), cast(0 as bit)) as [IsBackingObjectExist] , + ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'IsTable') as bit), cast(0 as bit)) as [IsTable] , + ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'IsView') as bit), cast(0 as bit)) as [IsView] , + ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'HasUpdateTrigger') as bit), cast(0 as bit)) as [HasUpdateTrigger] , + ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'HasInsertTrigger') as bit), CAST(0 as bit)) as [HasInsertTrigger] , + ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'HasDeleteTrigger') as bit), CAST(0 as bit)) as [HasDeleteTrigger] , + ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'HasInsteadOfTrigger') as bit), CAST(0 as bit)) as HasInsteadOfTrigger , + coalesce(OBJECT_DEFINITION(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName))), '') as [ObjectDefinition] , + case when exists (SELECT 1 FROM ScoreCompositeLink l WHERE sd.DefaultKeyGUID = l.Key1GUID and l.IsPlaceholder = 1) then CAST(1 as bit) else CAST(0 as bit) end as IsUsedAsPlaceholder , + (select max(datemodified) from (select datemodified from ScoreDimension where DimensionGUID = sd.dimensionguid union all select datemodified from ScoreAttribute where DimensionGUID = sd.dimensionguid union all select datemodified from ScoreDimensionGroup where DimensionGUID = sd.dimensionguid union all select datemodified from ScoreHierarchy where DimensionGUID = sd.dimensionguid union all select datemodified from ScoreHierarchyAttributeLink shal where shal.HierarchyGUID in (select HierarchyGUID from ScoreHierarchy where DimensionGUID = sd.dimensionguid)) x) as LastModifiedIncludingChildren + ,ISNULL(case when EXISTS (select 1 from PlanType PT (readuncommitted) where PT.DimensionGUID = sd.DimensionGUID) then cast(1 as bit) else cast(0 as bit) end, CAST(0 as bit)) as [IsPlanDimension] + ,case when exists (SELECT 1 FROM SecureList emf (readuncommitted) where emf.SyncedScoreDimensionGUID = sd.DimensionGUID) then CAST(1 as bit) else CAST(0 as bit) end as IsEMFSyncEnabled + from + ScoreDimension sd +GO + + +--------------------------------------------- + +-- dbo.viewScoreDimensionDependency +CREATE view dbo.viewScoreDimensionDependency +as + select distinct + A.DimensionGUID as ParentDimensionGUID, + D.FriendlyName as ParentDimensionName, + FK.DimensionGUID as ChildDimensionGUID, + FKD.FriendlyName as ChildDimensionName + from + viewScoreAttribute A + inner join ScoreDimension D on D.DimensionGUID = A.DimensionGUID + inner join viewScoreAttribute FK on FK.ForeignKeyGUID = A.AttributeGUID + inner join ScoreDimension FKD with (readuncommitted) on FKD.DimensionGUID = FK.DimensionGUID + where + A.DimensionGUID != FK.DimensionGUID + and FKD.DimensionVersion = 3 +GO + + +--------------------------------------------- + +-- dbo.viewScoreDimensionDisclaimer +create view [dbo].[viewScoreDimensionDisclaimer] +as + select + DimensionGUID, + GlobalID as DimensionName, + PHIDisclaimer, + CopyrightDisclaimer + from + ScoreDimension + where + PHIDisclaimer != '' or CopyrightDisclaimer != '' +GO + + +--------------------------------------------- + +-- dbo.viewScoreDimensionGroups +CREATE view [dbo].[viewScoreDimensionGroups] +AS +select + G.* + ,ISNULL(cast(case when object_ID(dbo.GetSQLTableExpression(G.SchemaName, G.ObjectName)) is not null then 1 else 0 end as bit), cast(0 as bit)) as [IsBackingObjectExist] + ,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(G.SchemaName, G.ObjectName)), 'IsTable') as bit), cast(0 as bit)) as [IsTable] + ,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(G.SchemaName, G.ObjectName)), 'IsView') as bit), cast(0 as bit)) as [IsView] + ,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(G.SchemaName, G.ObjectName)), 'HasUpdateTrigger') as bit), cast(0 as bit)) as [HasUpdateTrigger] + ,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(G.SchemaName, G.ObjectName)), 'HasInsertTrigger') as bit), CAST(0 as bit)) as [HasInsertTrigger] + ,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(G.SchemaName, G.ObjectName)), 'HaGeleteTrigger') as bit), CAST(0 as bit)) as [HaGeleteTrigger] + ,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(G.SchemaName, G.ObjectName)), 'HasInsteadOfTrigger') as bit), CAST(0 as bit)) as HasInsteadOfTrigger + ,coalesce(OBJECT_DEFINITION(OBJECT_ID(dbo.GetSQLTableExpression(G.SchemaName, G.ObjectName))), '') as [ObjectDefinition] +from ScoreDimensionGroup G + inner join ScoreDimension D on D.DimensionGUID = G.DimensionGUID +GO + + +--------------------------------------------- + +-- dbo.viewScoreDimensionHistory +CREATE view dbo.viewScoreDimensionHistory +AS +select + HL.DimensionHistoryLineID + ,ISNULL(UP.UserName, case when HI.MODIFIERUSERGUID = dbo.GetSuperUserGUID() then 'Strata' else '' end) as [UserName] + ,ISNULL(UP.NameLast + ', ' + UP.NameFirst, case when HI.MODIFIERUSERGUID = dbo.GetSuperUserGUID() then 'Strata' else '' end) as [User] + ,HI.DateTimeStamp + ,HL.TableName + ,HL.MemberGUID + ,HL.BeforeValues + ,HL.AfterValues +from ScoreDimensionHistoryLine HL + inner join HistoryItem HI on HI.HISTORYITEMGUID = HL.HistoryItemGUID + left join UserProfile UP on UP.UserGUID = HI.MODIFIERUSERGUID +GO + + +--------------------------------------------- + +-- dbo.viewScoreDimension_StrataSchema +CREATE VIEW dbo.viewScoreDimension_StrataSchema AS +SELECT + D.* + ,G.SchemaName AS GroupSchemaName + ,G.ObjectName as GroupObjectName + ,COALESCE(GPARENT.SchemaName, G.SchemaName) SourceTableSchema + ,COALESCE(GPARENT.ObjectName, G.ObjectName) SourceTableName +FROM [dbo].[ScoreDimension] D +INNER JOIN [dbo].[ScoreDimensionGroup] G ON G.DimensionGroupGUID = D.PrimaryGroupGUID +LEFT JOIN [dbo].[ScoreDimension] DPARENT ON DPARENT.DimensionGUID = D.ParentDimensionGUID +LEFT JOIN [dbo].[ScoreDimensionGroup] GPARENT ON GPARENT.DimensionGroupGUID = DPARENT.PrimaryGroupGUID +GO + + +--------------------------------------------- + +-- dbo.viewScoreDimensions +CREATE view [dbo].[viewScoreDimensions] +as +select + sd.DefaultHierarchyGUID, + sd.DefaultKeyGUID, + sd.DefaultLookupKeyGUID, + sd.PrimaryGroupGUID, + sd.DimensionGUID, + sd.FriendlyName, + sd.IsSecured, + sd.PermissionSetID, + sd.SQLObjectName, + sd.SQLSchemaName, + sd.SQLTableAlias, + sd.DefaultMemberGUID, + sd.IsSysAdminOnly, + sd.IsAllowMemberDelete, + sd.IsAllowMemberAdd, + sd.IsStock, + sd.Description, + sd.DateModified, + ISNULL(cast(case when object_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)) is not null then 1 else 0 end as bit), cast(0 as bit)) as [IsBackingObjectExist] + ,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'IsTable') as bit), cast(0 as bit)) as [IsTable] + ,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'IsView') as bit), cast(0 as bit)) as [IsView] + ,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'HasUpdateTrigger') as bit), cast(0 as bit)) as [HasUpdateTrigger] + ,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'HasInsertTrigger') as bit), CAST(0 as bit)) as [HasInsertTrigger] + ,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'HasDeleteTrigger') as bit), CAST(0 as bit)) as [HasDeleteTrigger] + ,ISNULL(cast(OBJECTPROPERTY(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName)), 'HasInsteadOfTrigger') as bit), CAST(0 as bit)) as HasInsteadOfTrigger + ,coalesce(OBJECT_DEFINITION(OBJECT_ID(dbo.GetSQLTableExpression(sd.SQLSchemaName, sd.SQLObjectName))), '') as [ObjectDefinition] +from + ScoreDimension sd +GO + + +--------------------------------------------- + +-- dbo.viewScoreHierarchy +CREATE view [dbo].[viewScoreHierarchy] as +select top 100 percent + sh.HierarchyGUID, + sh.FriendlyName as HierarchyName, + sh.PathAlias, + sh.DateModified, + shal.SortOrder, + sa.AttributeGUID, + sa.FriendlyName, + sh.DimensionGUID, + sd.FriendlyName as DimensionName +from + ScoreHierarchy sh + inner join ScoreDImension sd on sd.DimensionGUID = sh.DimensionGUID + inner join ScoreHierarchyAttributeLink shal on sh.HierarchyGUID = shal.HierarchyGUID + inner join ScoreAttribute sa on shal.AttributeGUID = sa.AttributeGUID +order by sd.FriendlyName, sh.FriendlyName, shal.SortOrder +GO + + +--------------------------------------------- + +-- dbo.viewScoreHierarchyAttributeLink +CREATE view [dbo].[viewScoreHierarchyAttributeLink] +AS +select + L.HierarchyAttributeLinkGUID, + L.HierarchyGUID, + L.DisplayAttributeGUID, + L.SortOrder, + L.IsDependentOnChild, + L.AttributeGUID, + D.FriendlyName as [DisplayAttributeName], + D.SQLColumnName as [DisplayAttributeColumnName], + A.SQLColumnName, + A.ColumnType, + A.IsNullable, + A.IsRequired, + A.IsComputed, + A.IsCopiedWithPlan, + A.IsIdentity, + A.IdentityIncrement, + A.IdentitySeed, + A.Scale, + A.Precision, + A.DefaultValueDefinition, + A.MaxLength +from ScoreHierarchyAttributeLink L + inner join viewScoreAttributeCore30 A on L.AttributeGUID = A.AttributeGUID + inner join ScoreAttribute D on D.AttributeGUID = L.DisplayAttributeGUID +GO + + +--------------------------------------------- + +-- dbo.viewScoreHierarchyAttributeLinkCore30 +CREATE view [dbo].[viewScoreHierarchyAttributeLinkCore30] +AS +select + L.HierarchyAttributeLinkGUID, + L.HierarchyGUID, + L.DisplayAttributeGUID, + L.SortOrder, + L.IsDependentOnChild, + L.AttributeGUID, + L.DateModified, + L.IsAttributeFiltered, + L.FilterAttributeGUID, + L.FilterString, + D.FriendlyName as [DisplayAttributeName], + D.SQLColumnName as [DisplayAttributeColumnName], + A.SQLColumnName as [ColumnName], + A.FriendlyName, + A.DimensionGUID, + A.DimensionGroupGUID, + A.ColumnType, + A.SecuredLootGroupPrefix, + A.IsSecuredLootGroupID, + A.IsSecuredLootID, + A.ForeignKeyGUID, + A.DefaultSortAttributeGUID, + A.IsRequired, + A.IsHidden, + A.IsKey, + A.IsWrittenToDB, + A.IsCustomNumberFormat, + A.CustomNumberFormat, + A.IsComputed, + A.IsCopiedWithPlan, + A.IsNullable, + A.IsIdentity, + A.IdentityIncrement, + A.IdentitySeed, + A.Scale, + A.Precision, + A.DefaultValueDefinition, + A.ComputedValueDefinition, + A.MaxLength, + A.DimensionSQLObjectExpression, + A.DimensionSQLTableAlias, + A.IsDimensionSecured, + A.IsDimensionSecuredSetupOnly, + A.DimensionName, + A.IsForeignKeyed, + A.ForeignKeySchema, + A.ForeignKeyTable, + A.ForeignKeyColumn, + A.ForeignKeyOnDelete, + A.AttributeType, + A.MetaXML, + A.IsFKAutoFilter + +from ScoreHierarchyAttributeLink L + inner join viewScoreAttributeCore30 A on L.AttributeGUID = A.AttributeGUID + inner join ScoreAttribute D on D.AttributeGUID = L.DisplayAttributeGUID +GO + + +--------------------------------------------- + +-- dbo.viewScoreHierarchyCore30 +CREATE view [dbo].[viewScoreHierarchyCore30] as +select + sh.HierarchyGUID, + sh.FriendlyName, + sh.HierarchyID, + sh.DateModified, + sh.DimensionGUID, + sh.PathAlias, + sd.FriendlyName as DimensionName, + Replace(sh.PathAlias + cast(sh.HierarchyID as nvarchar(11)), ' ','') as [UniquePathAlias], + sh.GlobalID, + sh.IsMR +from + ScoreHierarchy sh + inner join ScoreDImension sd on sd.DimensionGUID = sh.DimensionGUID +GO + + +--------------------------------------------- + +-- dbo.viewScoreHierarchyRoleLink +create view dbo.viewScoreHierarchyRoleLink +as +select + d.DimensionGUID, + d.FriendlyName as DimensionName, + d.GlobalID as DimensionGlobalID, + h.HierarchyGUID, + h.FriendlyName as HierarchyName, + r.RoleID, + r.Name as RoleName, + al.SortOrder +from + [dbo].[ScoreHierarchy] h with (readuncommitted) + inner join [dbo].[ScoreHierarchyAttributeLink] al with (readuncommitted) on al.HierarchyGUID = h.HierarchyGUID + inner join [dbo].[viewScoreAttribute] a on a.AttributeGUID = al.AttributeGUID + inner join [dbo].[viewFE2FormField] ff on ff.AttributeGUID = a.AttributeGUID + inner join [dbo].[UserRole] r with (readuncommitted) on ff.ComputedFieldConfig like '%' + cast(r.UserRoleGUID as nvarchar(36)) + '%' + inner join [dbo].[ScoreDimension] d with (readuncommitted) on d.DimensionGUID = h.DimensionGUID +where + ff.ComputedFieldClassName = 'RoleAssignment' +GO + + +--------------------------------------------- + +-- dbo.viewScoreInvalidAttributes +CREATE view [dbo].[viewScoreInvalidAttributes] +AS +select + D.FriendlyName as [Dimension] + ,G.SchemaName as [Schema] + ,G.ObjectName as [Table] + ,A.FriendlyName as [Attribute] + ,A.SQLColumnName as [ColumnName] + ,'Column not found.' as [Description] +from ScoreDimension D + inner join ScoreDimensionGroup G on G.DimensionGUID = D.DimensionGUID + inner join ScoreAttribute A on A.DimensionGroupGUID = G.DimensionGroupGUID + left join viewSysColumns C + on C.ColumnName = A.SQLColumnName + and C.ObjectID = OBJECT_ID(dbo.GetSQLTableExpression(D.SQLSchemaName, D.SQLObjectName)) +where + C.ColumnID is null +GO + + +--------------------------------------------- + +-- dbo.viewScoreMeasure +CREATE VIEW [dbo].[viewScoreMeasure] +AS +SELECT + dt.SQLTableAlias, + dt.IsWrittenIfZero, + m.* +FROM + dbo.ScoreMeasure AS m + INNER JOIN dbo.ScoreDataTable AS dt ON m.DataTableGUID = dt.DataTableGUID +GO + + +--------------------------------------------- + +-- dbo.viewScoreMeasureSchemaInfo +create view viewScoreMeasureSchemaInfo as +select + m.MeasureGUID, + col.* +from + ScoreMeasure m + INNER JOIN dbo.ScoreDataTable AS dt ON m.DataTableGUID = dt.DataTableGUID + + --should be inner? should it use something more specialized? + INNER JOIN viewSysColumns col on + col.SchemaName = dt.SQLSchemaName + and col.ObjectName = dt.SQLObjectName + and col.ColumnName = m.SQLColumnName +GO + + +--------------------------------------------- + +-- dbo.viewScoreMeasure_StrataSchema +CREATE VIEW dbo.viewScoreMeasure_StrataSchema +AS + SELECT + M.MeasureGUID + ,M.FriendlyName + ,M.DataTableGUID + ,M.IsReadFromDB + ,M.IsWrittenToDB + ,M.SQLColumnName + ,M.DisplayFormat + ,M.HasMin + ,M.Min + ,M.HasMax + ,M.Max + ,M.HasMinLength + ,M.MinLength + ,M.DefaultValue + ,M.AggType + ,M.SpecialMeasureIndex + ,M.SpecialFormulaSQLColumnName + ,M.SpecialCommentSQLColumnName + ,M.HasRestrictedValues + ,M.RestrictedValues + ,M.ObjectID + ,M.ColumnID + ,M.SchemaName + ,M.ObjectName + ,M.ColumnName + ,M.ObjectType + ,M.MaxLength + ,M.IsComputed + ,M.IsNullable + ,M.Scale + ,M.Precision + ,M.IsIdentity + ,M.ColumnTypeValue + ,M.IdentityIncrement + ,M.IdentitySeed + ,M.DefaultValueDefinition + ,M.IsPartOfUniqueIndex + ,M.IsUniqueIndex + ,M.IsPartOfPrimaryKey + ,M.IsPrimaryKey + ,M.ComputedValueDefinition + ,M.IsForeignKeyed + ,M.ForeignKeySchema + ,M.ForeignKeyTable + ,M.ForeignKeyColumn + ,M.ForeignKeyOnDelete + ,M.ModifiedAt + ,M.IsHidden + ,M.GlobalID + ,M.IsRequired + ,M.Description + ,M.DisplayFolder + ,CAST(COALESCE(MS.IsCustom, 0) AS BIT) AS IsCustom + ,CAST(COALESCE(MS.IsUsed, 1) AS BIT) AS IsUsed + ,CAST(COALESCE(MS.IsMarkedForDeletion, 0) AS BIT) AS IsMarkedForDeletion + FROM [dbo].[ScoreMeasure] M + LEFT JOIN [dbo].[ScoreMeasureSetting] MS ON MS.MeasureGUID = M.MeasureGUID +GO + + +--------------------------------------------- + +-- dbo.viewScoreOrphanedLootTriggers +CREATE VIEW [dbo].[viewScoreOrphanedLootTriggers] +AS +select S.Name as [Schema], O.[Name] as [Object], TRG.Name as [Trigger] from sys.triggers TRG + inner join sys.objects O on O.object_id = TRG.parent_id + inner join sys.schemas S on S.schema_id = O.schema_id +where TRG.name like 'trg_ScoreDimension_%_LootRefresh_%' +and SUBSTRING(TRG.Name, 20, 32) not in (select Replace(cast(DimensionGUID as nvarchar(36)),'-','') from ScoreDimension) +GO + + +--------------------------------------------- + +-- dbo.viewScorePlaceholderSection +CREATE view [dbo].[viewScorePlaceholderSection] +AS + +select distinct + SC.CompositeGUID as CompositeGUID, + SG1.DimensionGUID as DIMENSIONGUID, + SD1.FriendlyName as DIMENSIONNAME, + SD1.SQLSchemaName as DIMENSIONSCHEMANAME, + SD1.SQLObjectName as DIMENSIONOBJECTNAME, + SG2.DimensionGUID as FILLINDIMGUID, + SD2.FriendlyName as FILLINDIMNAME, + SD2.SQLObjectName as FILLINOBJECTNAME, + SD2.SQLSchemaName as FILLINSCHEMANAME, + SCL.IsFixedIndex As IsFixedIndex +from dbo.ScoreComposite SC + inner join dbo.ScoreDataTable DT1 on DT1.DataTableGUID = SC.DataTableGUID1 + inner join dbo.ScoreDataTable DT2 on DT2.DataTableGUID = SC.DataTableGUID2 + inner join dbo.ScoreCompositeLink SCL on SCL.CompositeGUID = SC.CompositeGUID + inner join dbo.ScoreAttribute SA1 on SA1.AttributeGUID = SCL.Key1GUID + inner join dbo.ScoreAttribute SA2 on SA2.AttributeGUID = SCL.Key2GUID + inner join dbo.ScoreDimensionGroup SG1 on SG1.DimensionGroupGUID = SA1.DimensionGroupGUID + inner join dbo.ScoreDimensionGroup SG2 on SG2.DimensionGroupGUID = SA2.DimensionGroupGUID + inner join dbo.ScoreDimension SD1 on SD1.DimensionGUID = SG1.DimensionGUID + inner join dbo.ScoreDimension SD2 on SD2.DimensionGUID = SG2.DimensionGUID +where SCL.IsPlaceholder = 1 +GO + + +--------------------------------------------- + +-- dbo.viewScoreSecurityTriggers +CREATE view [dbo].[viewScoreSecurityTriggers] +AS +select + T.Name, + SUBSTRING(T.definition, CHARINDEX('EXEC procScoreSetDimensionSecurity30 ''', T.definition) - 1, 80) as Definition, + Substring(SUBSTRING(T.definition, CHARINDEX('EXEC procScoreSetDimensionSecurity30 ''', T.definition) - 1, 80), 78,1) as [IsDebugOnly], + Substring(SUBSTRING(T.definition, CHARINDEX('EXEC procScoreSetDimensionSecurity30 ''', T.definition) - 1, 80), 80,1) as [IsUsingVersionColumn], + D.FriendlyName as [SourceDimension], + D.DimensionGUID as [SourceDimensionGUID], + dbo.GetSQLTableExpression(D.SQLSchemaName, D.sqlobjectname) as [SourceExpression], + DT.FriendlyName as [TargetDimension], + DT.DimensionGUID as [TargetDimensionGUID], + dbo.GetSQLTableExpression(DT.SQLSchemaName, DT.SQLObjectName) as [TargetExpression], + case when + SUM( case when(C.ColumnName = 'Version' and C.ColumnTypeValue = 189) then 1 else 0 end) = 1 then 1 + else 0 + end as [TargetHasVersionColumn] + +from ScoreDimension D + inner join ViewSysTriggers T on T.SchemaName = D.SQLSchemaName and T.ObjectName = D.SQLObjectName + inner join ScoreDimension DT on REPLACE(DT.DimensionGUID,'-','') = SUBSTRING(T.Name, 20, 32) + inner join viewSysObjects O on O.SchemaName = DT.SQLSchemaName and O.Objectname = DT.SQLObjectName + inner join viewSysColumns C on C.SchemaName = O.SchemaName and C.ObjectName = O.Objectname +GROUP BY + T.Name, + SUBSTRING(T.definition, CHARINDEX('EXEC procScoreSetDimensionSecurity30 ''', T.definition) - 1, 80), + Substring(SUBSTRING(T.definition, CHARINDEX('EXEC procScoreSetDimensionSecurity30 ''', T.definition) - 1, 80), 78,1), + Substring(SUBSTRING(T.definition, CHARINDEX('EXEC procScoreSetDimensionSecurity30 ''', T.definition) - 1, 80), 80,1), + D.FriendlyName, + D.DimensionGUID, + dbo.GetSQLTableExpression(D.SQLSchemaName, D.sqlobjectname), + DT.FriendlyName, + DT.DimensionGUID, + dbo.GetSQLTableExpression(DT.SQLSchemaName, DT.SQLObjectName) +GO + + +--------------------------------------------- + +-- dbo.viewScoreTableEditorColumn +CREATE view viewScoreTableEditorColumn +as + SELECT + [TableEditorColumnGUID] + ,[TableEditorConfigGUID] + ,[KeyGUID] + ,[Type] + ,[PixelWidth] + ,[DisplayOrder] + ,cast([MetaData] as nvarchar(max)) as MetaData + ,[DisplayName] + ,[DefaultMemberType] + ,[IsTextWrap] + ,[IsSortedByDefault] + ,[DefaultSortDirectionValue] + ,[DefaultSortIndex] + ,[TableEditorColumnGroupGUID] + ,[IsRequired] + ,[IsLocked] + ,[IsNonFilterable] + FROM + [ScoreTableEditorColumn] +GO + + +--------------------------------------------- + +-- dbo.viewSecurableEntities +CREATE VIEW [dbo].[viewSecurableEntities] +AS +SELECT PlanGUID AS ENTITYGUID, dbo.ZeroGUID() as ParentEntityGUID, dbo.GetPlanName(PlanGUID) AS NAME, 0 AS ENTITYTYPE, DateCreated +FROM dbo.XPlan +UNION ALL +SELECT F.FolderGuid AS ENTITYGUID, (CASE WHEN (ISDELETEDFOLDER = 1 AND BASEDONFOLDERGUID != '00000000-0000-0000-0000-000000000000') + THEN BASEDONFOLDERGUID ELSE PARENTFOLDERGUID END) AS PARENTENTITYGUID, F.Name, 1 AS ENTITYTYPE, F.DateCreated +FROM dbo.Folder AS F INNER JOIN + dbo.FolderSet AS FS ON F.FolderSetGUID = FS.FolderSetGUID +WHERE (NOT (FS.Type IN (0, 2, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15))) +UNION ALL +SELECT ListGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTENTITYGUID, Name, 2 AS ENTITYTYPE, GETDATE() AS Expr2 +FROM dbo.SecureList +WHERE (ListType = 0) AND (IsSecured = 1) +UNION ALL +SELECT ListMemberGUID AS ENTITYGUID, CASE WHEN (PARENTLISTMEMBERGUID = '00000000-0000-0000-0000-000000000000') + THEN LISTGUID ELSE PARENTLISTMEMBERGUID END AS PARENTENTITYGUID, Name, 2 AS ENTITYTYPE, GETDATE() AS DATECREATED +FROM dbo.SecureListMember +WHERE (ListGUID IN + (SELECT ListGUID + FROM dbo.SecureList AS SecureList_1 + WHERE (IsSecured = 1))) +UNION ALL +SELECT ReportGUID AS ENTITYGUID, FolderGUID AS PARENTGUID, Name, 3 AS SECURABLEENTITYTYPE, DateCreated +FROM dbo.REReport +UNION ALL +SELECT PlanTypeGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name, 4 AS SECURABLEENTITYTYPE, GETDATE() + AS Expr1 +FROM dbo.PlanType +UNION ALL +SELECT ForumGUID AS ENTITYGUID, EntityGUID AS PARENTGUID, Name, 5 AS SECURABLEENTITYTYPE, GETDATE() AS DATECREATED +FROM dbo.MsgForum +UNION ALL +SELECT TopicGUID AS ENTITYGUID, ForumGUID AS PARENTGUID, Name, 6 AS SECURABLEENTITYTYPE, GETDATE() AS DATECREATED +FROM dbo.MsgTopic +UNION ALL +SELECT SYSTEMSECTIONGUID AS ENTITYGUID, ParentGUID, Name, 7 AS SECURABLEENTITYTYPE, GETDATE() AS DATECREATED +FROM dbo.SystemSection +UNION ALL +SELECT FORMFIELDGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS Expr1, Name, 8 AS SECURABLEENTITYTYPE, GETDATE() + AS DATECREATED +FROM dbo.FE2FormField +UNION ALL +SELECT PoolGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name, 10 AS SECURABLEENTITYTYPE, GETDATE() + AS DATECREATED +FROM dbo.OMZPool +UNION ALL +SELECT ListInsertionPointGUID AS ENTITYGUID, ParentListMemberGUID AS PARENTGUID, Name, 11 AS SECURABLEENTITYTYPE, GETDATE() + AS DATECREATED +FROM dbo.SecureListInsertionPoint +UNION ALL +SELECT ActionGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Description, 12 AS SECURABLEENTITYTYPE, GETDATE() + AS DATECREATED +FROM dbo.CustomAction +UNION ALL +SELECT UserGroupGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name AS NAME, 13 AS SECURABLEENTITYTYPE, + GETDATE() AS DATECREATED +FROM dbo.UserGroup +UNION ALL +SELECT WorkflowMapGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name, 14 AS SECURABLEENTITYTYPE, GETDATE() + AS DATECREATED +FROM dbo.WFWorkflowMap +UNION ALL +SELECT IRCChatGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name, 15 as SECURABLEENTITYTYPE, getdate() +FROM dbo.IRCChat +UNION ALL +SELECT DesktopTemplateGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name, 16 AS SECURABLEENTITYTYPE, GETDATE() + AS DATECREATED +FROM dbo.DesktopTemplate +UNION ALL +SELECT DimensionGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, FriendlyName, 19 as SECURABLEENTITYTYPE, getdate() +FROM dbo.ScoreDimension +UNION ALL +SELECT WorkflowStepGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name, 21 as SECURABLEENTITYTYPE, getdate() +FROM dbo.WFWorkflowStep +UNION ALL +SELECT DataViewGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name, 22 as SECURABLEENTITYTYPE, getdate() +FROM dbo.DataView +UNION ALL +SELECT ParameterSetGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name, 23 as SECURABLEENTITYTYPE, getdate() +FROM dbo.REParameterSet +UNION ALL +SELECT CubeGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name, 24 as SECURABLEENTITYTYPE, getdate() +FROM dbo.EMFCubeStub +UNION ALL +SELECT TableEditorConfigGUID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, FriendlyName, 26 AS SECURABLEENTITYTYPE, GETDATE() +FROM dbo.ScoreTableEditorConfig +UNION ALL +SELECT ConfigID AS ENTITYGUID, '00000000-0000-0000-0000-000000000000' AS PARENTGUID, Name, 39 AS SECURABLEENTITYTYPE, GETDATE() FROM dbo.IntConfig +GO + + +--------------------------------------------- + +-- dbo.viewSecurableIdentity +--========================================================================================== + + + CREATE VIEW [dbo].[viewSecurableIdentity] +AS + SELECT USERGUID AS IDENTITYGUID, NAMELAST + ', ' + NAMEFIRST AS NAME, 0 AS SECURABLEIDENTITYTYPE, IsDisabled +FROM dbo.UserProfile +UNION ALL +SELECT USERGROUPGUID AS IDENTITYGUID, NAME, 1 AS SECURABLEIDENTITYTYPE, 0 AS IsDisabled +FROM dbo.UserGroup +WHERE (TYPE = 0) +UNION ALL +SELECT USERROLEGUID AS IDENTITYGUID, NAME, 2 AS SECURABLEIDENTITYTYPE, 0 AS IsDisabled +FROM dbo.UserRole +GO + + +--------------------------------------------- + +-- dbo.viewSecureListMembersFlat +create view viewSecureListMembersFlat as +select + slm.ListGUID, + slm.ListMemberGUID , + slmp1.ListMemberGUID as Parent1, + slmp2.ListMemberGUID as Parent2, + slmp3.ListMemberGUID as Parent3, + slmp4.ListMemberGUID as Parent4, + slmp5.ListMemberGUID as Parent5, + slmp6.ListMemberGUID as Parent6, + slmp7.ListMemberGUID as Parent7, + slmp8.ListMemberGUID as Parent8, + slmp9.ListMemberGUID as Parent9, + slmp10.ListMemberGUID as Parent10, + slmp11.ListMemberGUID as Parent11, + slmp12.ListMemberGUID as Parent12 +from + SecureListMember slm + left join SecureListMember slmp1 on slm.ParentListMemberGUID = slmp1.ListMemberGUID + left join SecureListMember slmp2 on slmp1.ParentListMemberGUID = slmp2.ListMemberGUID + left join SecureListMember slmp3 on slmp2.ParentListMemberGUID = slmp3.ListMemberGUID + left join SecureListMember slmp4 on slmp3.ParentListMemberGUID = slmp4.ListMemberGUID + left join SecureListMember slmp5 on slmp4.ParentListMemberGUID = slmp5.ListMemberGUID + left join SecureListMember slmp6 on slmp5.ParentListMemberGUID = slmp6.ListMemberGUID + left join SecureListMember slmp7 on slmp6.ParentListMemberGUID = slmp7.ListMemberGUID + left join SecureListMember slmp8 on slmp7.ParentListMemberGUID = slmp8.ListMemberGUID + left join SecureListMember slmp9 on slmp8.ParentListMemberGUID = slmp9.ListMemberGUID + left join SecureListMember slmp10 on slmp9.ParentListMemberGUID = slmp10.ListMemberGUID + left join SecureListMember slmp11 on slmp10.ParentListMemberGUID = slmp11.ListMemberGUID + left join SecureListMember slmp12 on slmp11.ParentListMemberGUID = slmp12.ListMemberGUID +GO + + +--------------------------------------------- + +-- dbo.viewSecureListParent +CREATE view viewSecureListParent as +SELECT + SL.ListGUID, + CASE WHEN SL.ListType = 1 THEN FF.FormFieldGUID + ELSE '00000000-0000-0000-0000-000000000000' + END as ParentEntityGUID +FROM + SecureList SL + LEFT JOIN FE2FormField FF ON FF.ListSourceConfig like '%' + cast(SL.ListGUID as nvarchar(36)) + '%' +GO + + +--------------------------------------------- + +-- dbo.viewSysAllObjects +CREATE VIEW [dbo].[viewSysAllObjects] +AS +select OBJ.object_id as [ObjectID], S.name as [SchemaName], OBJ.name as [ObjectName], OBJ.type_desc + from sys.all_objects OBJ + inner join sys.schemas S on S.schema_id = OBJ.schema_id +GO + + +--------------------------------------------- + +-- dbo.viewSysChangeTrackingTables +CREATE VIEW dbo.viewSysChangeTrackingTables +AS + +SELECT + s.Name AS SchemaName, + t.Name AS TableName, + p.rows AS ApproximateRowCount +FROM sys.change_tracking_tables ct +INNER JOIN sys.tables t ON ct.object_id = t.object_id +INNER JOIN sys.schemas s ON t.schema_id = s.schema_id +INNER JOIN sys.partitions p ON t.object_id = p.object_id +GROUP BY t.Name, s.Name, p.Rows +GO + + +--------------------------------------------- + +-- dbo.viewSysColumns +CREATE VIEW [dbo].[viewSysColumns] +AS +select + O.object_id as ObjectID, + COL.Column_id as ColumnID, + S.name as SchemaName, + O.Name as ObjectName, + COL.name as ColumnName, + case when O.type_desc = 'VIEW' then 2 when O.type_desc = 'USER_TABLE' then 1 else 0 end as ObjectType, + COL.max_length as MaxLength, + COL.is_computed as IsComputed, + ISNULL(cast(case when COL.is_nullable is not null then COL.is_nullable else 0 end as bit),0) as IsNullable, + COL.scale as Scale, + COL.Precision as Precision, + COL.is_identity as IsIdentity, + COL.system_type_id as ColumnTypeValue, + cast(ISNULL(IDENT.increment_value, -1) as int) as IdentityIncrement, + cast(ISNULL(IDENT.seed_value, -1) as int) as IdentitySeed, + --'' as ComputedValueDefinition, + case when DEF.definition is not null then DEF.definition else '' end as DefaultValueDefinition, + --'' as DefaultValueDefinition, + + CAST(0 as bit) as IsPartOfUniqueIndex, + CAST(0 as bit) as IsUniqueIndex, + CAST(0 as bit) as IsPartOfPrimaryKey, + CAST(0 as bit) as IsPrimaryKey, + --case when COL.is_identity = 1 then cast(IDENT.increment_value as int) else -1 end as IdentityIncrement, + --case when COL.is_identity = 1 then cast(IDENT.seed_value as int) else -1 end as IdentitySeed, + case when COMPUTED.Definition is not null then COMPUTED.definition else '' end as ComputedValueDefinition + + --isnull(case when idx.is_unique_count > 0 then CAST(1 as bit) else cast(0 as bit) end, CAST(0 as bit)) as IsPartOfUniqueIndex, + --isnull(case when idx.is_unique_count = 1 then CAST(1 as bit) else cast(0 as bit) end, CAST(0 as bit)) as IsUniqueIndex, + --isnull(case when idx.is_unique_count > 0 then CAST(1 as bit) else cast(0 as bit) end, CAST(0 as bit)) as IsPartOfPrimaryKey, + --isnull(case when idx.is_unique_count = 1 then CAST(1 as bit) else cast(0 as bit) end, CAST(0 as bit)) as IsPrimaryKey + + --fk stuff + , CAST(0 as bit) as IsForeignKeyed + ,'' as ForeignKeySchema + ,'' as ForeignKeyTable + ,'' as ForeignKeyColumn + ,'' as ForeignKeyOnDelete + --,isnull(case when fkc.column_id is not null then CAST(1 as bit) else CAST(0 as bit) end,cast(0 as bit)) as IsForeignKeyed, + --ISNULL(fks.name,'') as ForeignKeySchema, + --ISNULL(fkt.name,'') as ForeignKeyTable, + --ISNULL(fkc.name,'') as ForeignKeyColumn, + --ISNULL(case when fkdef.delete_referential_action_desc = 'NO_ACTION' then null else fkdef.delete_referential_action_desc end,'') as ForeignKeyOnDelete +from sys.columns COL + inner join sys.objects O on O.object_id = COL.object_id + inner join sys.schemas S on O.schema_id = S.schema_id + left join sys.identity_columns IDENT on IDENT.column_id = COL.column_id and IDENT.object_id = O.object_id + left join sys.computed_columns COMPUTED on COMPUTED.column_id = COL.column_id and COMPUTED.object_id = O.object_id + left join sys.default_constraints DEF on DEF.parent_object_id = O.object_id and DEF.parent_column_id = COL.column_id + + --m2m + --LEFT join ( + -- select + -- IND_COL.object_id, + -- IND_COL.column_id, + -- sum(CASE WHEN IND.is_unique = 1 then 1 else 0 end) as is_unique_count, + -- sum(CASE WHEN IND.is_primary_key = 1 then 1 else 0 end) as is_primary_key_count + -- from + -- sys.index_columns IND_COL + -- inner join sys.indexes IND on IND.object_id = IND_COL.object_id and IND.index_id = IND_COL.index_id + -- group by + -- IND_COL.object_id, + -- IND_COL.column_id + --) idx on idx.column_id = COL.column_id and idx.object_id = O.object_id + + + --FK stuff + --left join sys.foreign_key_columns fk on COL.column_id = fk.parent_column_id and COL.object_id = fk.parent_object_id + --left join sys.columns fkc on fk.referenced_column_id = fkc.column_id and fk.referenced_object_id = fkc.object_id + --left join sys.tables fkt on fkc.object_id = fkt.object_id + --left join sys.schemas fks on fkt.schema_id = fks.schema_id + --left join sys.foreign_keys fkdef on fk.constraint_object_id = fkdef.object_id +--where +-- --replace(replace(replace('[{0}].[{1}].[{2}]','{0}', s.name),'{1}', o.name),'{2}', col.name) = '[dbo].[zzviewModelTemplateMapping_GJFModeling].[IsUserMapped]' +-- --s.name + '-' + o.name + '-' + col.name = 'dbo-zzviewModelTemplateMapping_GJFModeling-IsUserMapped' +-- s.name = 'dbo' +-- and o.name = 'zzviewModelTemplateMapping_GJFModeling' +-- and col.name = 'IsUserMapped' + +--GROUP BY +-- dbo.IntToGUID(O.object_id), O.object_id, COL.object_id, COL.Column_ID, S.name, O.name, O.type_desc, COL.name, COL.max_length, COL.is_computed, COL.is_nullable, COL.scale,COL.precision, COL.is_identity, +-- COL.system_type_id +GO + + +--------------------------------------------- + +-- dbo.viewSysForeignKeys +CREATE VIEW [dbo].[viewSysForeignKeys] +AS +SELECT + FK_Schema = FK.TABLE_SCHEMA, + FK_Table = FK.TABLE_NAME, + FK_Column = CU.COLUMN_NAME, + PK_Schema = PK.TABLE_SCHEMA, + PK_Table = PK.TABLE_NAME, + PK_Column = PT.COLUMN_NAME, + Constraint_Name = C.CONSTRAINT_NAME +FROM + INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C + INNER JOIN + INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK + ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME + INNER JOIN + INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK + ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME + INNER JOIN + INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU + ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME + INNER JOIN + ( + SELECT + i1.TABLE_NAME, i2.COLUMN_NAME + FROM + INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 + INNER JOIN + INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 + ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME + WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY' + ) PT + ON PT.TABLE_NAME = PK.TABLE_NAME +GO + + +--------------------------------------------- + +-- dbo.viewSysFunctionParameters +CREATE VIEW [dbo].[viewSysFunctionParameters] +AS +select + S.name as [SchemaName], + F.name as [ObjectName], + F.is_ms_shipped as [IsMSShipped], + F.create_date as [CreationDate], + case when F.type = 'FN' then 'Scalar' when f.type='TF' then 'TableValued' end as [FunctionType], + PM.name as [ParameterName], + PM.max_length as [MaxLength], + PM.precision as [Precision], + PM.scale as [Scale], + PM.is_output as [IsOutput], + PM.system_type_id as [DataType] +from sys.all_objects F + inner join sys.schemas S on S.schema_id = F.schema_id + inner join sys.parameters PM on PM.object_id = F.object_id +where F.type = 'FN' or F.type = 'TF' +GO + + +--------------------------------------------- + +-- dbo.viewSysIndexColumns +CREATE VIEW [dbo].[viewSysIndexColumns] +AS +select S.name as SchemaName, O.name as ObjectName, + COL.name as ColumnName, + IND.index_id as IndexID, + INDC.is_included_column as IsIncludedColumn, + INDC.index_column_id as ColumnOrder, + INDC.is_descending_key as IsDescending, + COL.max_length as MaxLength, + COL.is_computed as IsComputed, + COL.is_nullable as IsNullable, + COL.scale as Scale, + COL.Precision as Precision, + COL.is_identity as IsIdentity, + COL.system_type_id as ColumnType, + case when COL.is_identity = 1 then cast(IDENT.increment_value as int) else -1 end as IncrementValue, + case when COL.is_identity = 1 then cast(IDENT.seed_value as int) else -1 end as SeedValue, + case when COMPUTED.Definition is not null then COMPUTED.definition else '' end as ComputedDefinition, + case when DEF.definition is not null then DEF.definition else '' end as DefaultValue + from sys.indexes IND + inner join sys.objects O on O.object_id = IND.object_id + inner join sys.schemas S on S.schema_id = O.schema_id + inner join sys.index_columns INDC on INDC.index_id = IND.index_id and INDC.object_id = IND.object_id + inner join sys.columns COL on COL.column_id = INDC.column_id and COL.object_id = INDC.object_id + left join sys.identity_columns IDENT on IDENT.column_id = COL.column_id and IDENT.object_id = O.object_id + left join sys.computed_columns COMPUTED on COMPUTED.column_id = COL.column_id and COMPUTED.object_id = O.object_id + left join sys.default_constraints DEF on DEF.parent_object_id = O.object_id and DEF.parent_column_id = COL.column_id +GO + + +--------------------------------------------- + +-- dbo.viewSysIndexDefinitions +--Forward +create view dbo.viewSysIndexDefinitions +as + WITH indexCTE AS + ( + SELECT DISTINCT + i.index_id, i.name, i.object_id, i.is_primary_key + FROM + sys.indexes i + INNER JOIN sys.index_columns ic ON i.index_id = ic.index_id AND i.object_id = ic.object_id + ), + indexCTE2 AS + ( + SELECT + cte.name as IndexName, + OBJECT_NAME(cte.object_ID) as ObjectName, + s.name as SchemaName, + CASE + cte.index_id + WHEN 1 THEN 'CLUSTERED' + ELSE 'NONCLUSTERED' + END AS IndexType, + ( + SELECT DISTINCT c.name + ',' + FROM + sys.columns c + INNER JOIN sys.index_columns ic on c.object_id = ic.object_id AND ic.column_id = c.column_id AND ic.Is_Included_Column = 0 + WHERE + cte.OBJECT_ID = ic.object_id + AND cte.index_id = ic.index_id + FOR XML PATH('')) as ixcols, + ISNULL(( + SELECT DISTINCT c.name + ',' + FROM + sys.columns c + INNER JOIN sys.index_columns ic ON c.object_id = ic.object_id AND ic.column_id = c.column_id AND ic.Is_Included_Column = 1 + WHERE + cte.OBJECT_ID = ic.object_id + AND cte.index_id = ic.index_id + FOR XML PATH('')), '') as includedcols, + cte.is_primary_key as IsPrimaryKey + FROM + indexCTE cte + inner join sys.tables t on t.object_id = cte.object_id + inner join sys.schemas s on s.schema_id = t.schema_id + ) + SELECT + SchemaName, + ObjectName, + IndexName, + IsPrimaryKey, + 'CREATE ' + IndexType + ' INDEX ' + IndexName + ' ON ' + SchemaName + '.' + ObjectName + '(' + SUBSTRING(ixcols, 1, LEN(ixcols)-1) + CASE LEN(includedcols) WHEN 0 THEN ')' ELSE ') INCLUDE (' + SUBSTRING(includedcols, 1, LEN(includedcols)-1) + ')' END as IndexScript + FROM + indexCTE2 +GO + + +--------------------------------------------- + +-- dbo.viewSysIndexes +CREATE VIEW [dbo].[viewSysIndexes] +AS +select + S.name as [SchemaName], + O.name as [ObjectName], + IND.index_id as [IndexID], + IND.name as [Name], + IND.type_desc as [Description], + IND.is_unique as [IsUnique], + IND.is_primary_key as [IsPrimaryKey] +from sys.indexes IND + inner join sys.objects O on O.object_id = IND.object_id + inner join sys.schemas S on S.schema_id = O.schema_id +GO + + +--------------------------------------------- + +-- dbo.viewSysObjects +CREATE VIEW [dbo].[viewSysObjects] +AS +select + S.name + '.' + O.name as SQLObjectExpression, + S.name as SchemaName, + O.name as ObjectName, + isnull(case when O.type_desc = 'VIEW' then CAST(1 as bit) else CAST(0 as bit) end, CAST(1 as bit)) as IsView +from sys.objects O + inner join sys.schemas S on S.schema_id = O.schema_id +where O.type_desc = 'USER_TABLE' OR O.type_desc = 'VIEW' +GO + + +--------------------------------------------- + +-- dbo.viewSysProcParameters +CREATE VIEW [dbo].[viewSysProcParameters] +AS +SELECT S.NAME AS [SchemaName] + ,P.NAME AS [ObjectName] + ,dbo.StripNewLine(SUBSTRING(SUBSTRING(M.DEFINITION, PATINDEX('%CREATE PROC%', M.DEFINITION), LEN(M.DEFINITION)), 1, PATINDEX('%[^a-Z]AS%', SUBSTRING(M.DEFINITION, PATINDEX('%CREATE PROC%', M.DEFINITION), LEN(M.DEFINITION))) - 1)) AS [Comments] + ,SUBSTRING(M.DEFINITION, CHARINDEX('CREATE PROC', M.DEFINITION), LEN(M.DEFINITION)) AS [Definition] + ,P.is_ms_shipped AS [IsMSShipped] + ,P.create_date AS [CreationDate] + ,PM.NAME AS [ParameterName] + ,PM.max_length AS [MaxLength] + ,PM.precision AS [Precision] + ,PM.scale AS [Scale] + ,PM.is_output AS [IsOutput] + ,PM.system_type_id AS [DataType] + ,PM.user_type_id AS [UserType] +FROM sys.procedures P +INNER JOIN sys.parameters PM ON P.object_id = PM.object_id +INNER JOIN sys.schemas S ON S.schema_id = P.schema_id +INNER JOIN sys.sql_modules M ON M.object_id = P.object_id +GO + + +--------------------------------------------- + +-- dbo.viewSysProcWithParameters +CREATE VIEW [dbo].[viewSysProcWithParameters] +AS +SELECT P.SchemaName + ,P.ObjectName + ,ISNULL(PM.Comments, '') AS [Comments] + ,ISNULL(PM.DEFINITION, SUBSTRING(M.DEFINITION, CHARINDEX('CREATE PROC', M.DEFINITION), LEN(M.DEFINITION))) + '' AS [Definition] + ,ISNULL(PM.IsMSShipped, 0) AS [IsMSShipped] + ,ISNULL(PM.CreationDate, GETDATE()) AS [CreationDate] + ,ISNULL(PM.ParameterName, '') AS [ParameterName] + ,ISNULL(PM.MaxLength, 0) AS [MaxLength] + ,ISNULL(PM.Precision, 0) AS [Precision] + ,ISNULL(PM.Scale, 0) AS [Scale] + ,ISNULL(PM.DataType, 0) AS [DataType] + ,ISNULL(PM.UserType, 0) AS [UserType] + ,ISNULL(PM.IsOutput, 0) AS [IsOutput] + ,ISNULL(SUBSTRING(PM.ParameterName, 2, Len(ParameterName)), '') AS [ArgumentName] +FROM viewSysProcedures P +INNER JOIN sys.sql_modules M ON M.object_id = P.object_id +LEFT JOIN viewsysprocparameters PM ON P.ObjectName = PM.ObjectName + AND p.SchemaName = PM.SchemaName +GO + + +--------------------------------------------- + +-- dbo.viewSysProcedures +CREATE VIEW [dbo].[viewSysProcedures] +AS +select S.name as [SchemaName], PR.name as [ObjectName], PR.object_id + from sys.procedures PR + inner join sys.schemas S on S.schema_id = PR.schema_id +GO + + +--------------------------------------------- + +-- dbo.viewSysViewBaseTables +CREATE view [dbo].[viewSysViewBaseTables] +AS + + +WITH TBLS (ViewSchema, ViewName, TableSchema, TableName, TableType, [Level]) +AS +( + select + U.VIEW_SCHEMA + ,U.VIEW_NAME + ,U.TABLE_SCHEMA + ,U.TABLE_NAME + ,T.TABLE_TYPE + ,0 + from INFORMATION_SCHEMA.VIEW_TABLE_USAGE U + inner join INFORMATION_SCHEMA.TABLES T on T.TABLE_CATALOG = U.TABLE_CATALOG and T.TABLE_SCHEMA = U.TABLE_SCHEMA and T.TABLE_NAME = U.TABLE_NAME + where (U.VIEW_NAME <> U.TABLE_NAME or (U.VIEW_SCHEMA <> U.TABLE_SCHEMA and U.VIEW_NAME = U.TABLE_NAME)) + UNION ALL + select + ANCHOR.ViewSchema + ,ANCHOR.ViewName + ,REC.TABLE_SCHEMA + ,REC.TABLE_NAME + ,T.TABLE_TYPE + ,[Level] + 1 + from INFORMATION_SCHEMA.VIEW_TABLE_USAGE REC + inner join TBLS ANCHOR on ANCHOR.TableName = REC.VIEW_NAME and ANCHOR.TableSchema = REC.VIEW_SCHEMA + inner join INFORMATION_SCHEMA.TABLES T on T.TABLE_CATALOG = REC.TABLE_CATALOG and T.TABLE_SCHEMA = REC.TABLE_SCHEMA and T.TABLE_NAME = REC.TABLE_NAME + where (REC.VIEW_NAME <> REC.TABLE_NAME or (REC.VIEW_SCHEMA <> REC.TABLE_SCHEMA and REC.VIEW_NAME = REC.TABLE_NAME)) +) +SELECT + ViewSchema, ViewName, TableSchema, TableName, TableType, MIN(LEVEL) as [Level] +FROM TBLS + group by ViewSchema, ViewName, TableSchema, TableName, TableType +GO + + +--------------------------------------------- + +-- dbo.viewSystemCenterStep +create view dbo.viewSystemCenterStep +as +select + s.Name as Solution, + m.Name as Module, + c.Name as Category, + sc.Name as Section, + s.* +from + SystemCenterStep s + inner join SystemCenterSection sc on sc.SectionGUID = s.SectionGUID + inner join SystemCenterCategory c on c.CategoryGUID = sc.CategoryGUID + inner join SystemCenterModule m on m.ModuleGUID = c.ModuleGUID + inner join SystemCenterSolution sl on sl.SolutionGUID = m.SolutionGUID +GO + + +--------------------------------------------- + +-- dbo.viewSystemSectionFlat +CREATE view [dbo].[viewSystemSectionFlat] as + select + ss1.SYSTEMSECTIONGUID as ss1, + ss2.SYSTEMSECTIONGUID as ss2, + ss3.SYSTEMSECTIONGUID as ss3, + ss4.SYSTEMSECTIONGUID as ss4, + ss5.SYSTEMSECTIONGUID as ss5, + ss6.SYSTEMSECTIONGUID as ss6 + from + SystemSection ss1 + left join SystemSection ss2 on ss1.ParentGUID = ss2.SYSTEMSECTIONGUID + left join SystemSection ss3 on ss2.ParentGUID = ss3.SYSTEMSECTIONGUID + left join SystemSection ss4 on ss3.ParentGUID = ss4.SYSTEMSECTIONGUID + left join SystemSection ss5 on ss4.ParentGUID = ss5.SYSTEMSECTIONGUID + left join SystemSection ss6 on ss5.ParentGUID = ss6.SYSTEMSECTIONGUID +GO + + +--------------------------------------------- + +-- dbo.viewTemplateSectionCounts +CREATE VIEW [dbo].[viewTemplateSectionCounts] +AS +WITH +actualFillinCountByMainTemplate AS ( + SELECT + COALESCE(SEP.[ParentModelTemplateGUID], P.[ModelTemplateGUID]) AS [ModelTemplateGUID], + SF.[ModelGUID], + SF.[PlaceholderSectionMemberGUID], + COUNT(SF.[FillinGUID]) AS [Total] + FROM [dbo].[ScoreFillin] AS SF + INNER JOIN [dbo].[XPlan] AS P + ON P.[PlanGUID] = SF.[ModelGUID] + LEFT JOIN [dbo].[MEScoreExpansionProfile] AS SEP + ON SEP.[ChildModelTemplateGUID] = P.[ModelTemplateGUID] + GROUP BY COALESCE(SEP.[ParentModelTemplateGUID], P.[ModelTemplateGUID]), SF.[ModelGUID], SF.[PlaceholderSectionMemberGUID] +) +SELECT + TS.[TemplateGUID] AS [TemplateGUID], + PH.[FriendlyName] AS [SectionName], + TS.[SettingID], + COALESCE(MAX(FC.[Total]), 0) AS [ActualMaxNumberOfFillins], + COALESCE(MAX(TS.[Value]), 0) AS [ActualSectionCount] +FROM [dbo].[TemplateSettings] AS TS + INNER JOIN [dbo].[MEPHSection] AS PH + ON TS.[TemplateGUID] = PH.[ModelTemplateGUID] AND PH.[FriendlyName] = SUBSTRING(TS.[SettingID], 18, LEN(TS.[SettingID])) + LEFT JOIN actualFillinCountByMainTemplate AS FC + ON FC.[PlaceholderSectionMemberGUID] = PH.[PHSectionMemberGUID] AND FC.[ModelTemplateGUID] = TS.[TemplateGUID] +WHERE 1=1 + AND TS.[SettingID] LIKE 'Section Counts%' +GROUP BY TS.[TemplateGUID], PH.[FriendlyName], TS.[SettingID] +GO + + +--------------------------------------------- + +-- dbo.viewTemplateSectionCountsWithRecommended +CREATE VIEW [dbo].[viewTemplateSectionCountsWithRecommended] +AS +SELECT + SC.[TemplateGUID], + SC.[SectionName], + SC.[SettingID], + SC.[ActualMaxNumberOfFillins], + SC.[ActualSectionCount], + SC.[ActualMaxNumberOfFillins] + 10 AS [RecommendedSectionCount] +FROM [dbo].[viewTemplateSectionCounts] AS SC +GO + + +--------------------------------------------- + +-- dbo.viewUpgradeDate +--Forward +create view viewUpgradeDate +as + select + [Version], + MIN(LogDate) UpgradeDate + from + UpgradeLog + group by + [Version] +GO + + +--------------------------------------------- + +-- dbo.viewUserLimit_UnassignedUsers +CREATE view viewUserLimit_UnassignedUsers as +select * +from + UserProfile (Nolock) +where + UserGUID not in (select UserGUID from UserTag) +GO + + +--------------------------------------------- + +-- dbo.viewUserLoginHistory +CREATE VIEW [dbo].[viewUserLoginHistory] AS + SELECT up.UserGUID, up.namefirst + ' ' + up.namelast AS Name, MAX(loginstamp) AS LastLogin, MIN(loginstamp) AS FirstLogin, COUNT(*) AS NumLogins + FROM loginhistory lh (READUNCOMMITTED) INNER JOIN userprofile up (READUNCOMMITTED) + ON lh.userguid = up.userguid + GROUP BY up.UserGUID, up.namefirst + ' ' + up.namelast +GO + + +--------------------------------------------- + +-- dbo.viewWFChangeHistory +CREATE view [dbo].[viewWFChangeHistory] as +select WFM.Name as WORKFLOWNAME, U.UserName as MODIFIER, H.* from HistoryItem H +inner join WFWorkFlowMap WFM on H.OBJECTGUID = WFM.WorkFlowMapGUID +left join UserProfile U on H.ModifierUserGUID = U.UserGUID +GO + + +--------------------------------------------- + +-- dbo.viewWFEntity +CREATE VIEW [dbo].[viewWFEntity] + WITH SCHEMABINDING + AS + SELECT + PlanGUID AS EntityGUID, + Name AS EntityName, + PlanTypeGUID, + CachedLootID, + AuthorUserGUID + FROM [dbo].[XPlan] + WHERE PlanTypeGUID <> '2898A6EB-3CAE-47D9-AF28-FC959F1E3955' -- Substitution Plan Type GUID + AND IsDeletedPlan = 0 + UNION ALL + SELECT + MemberGUID AS EntityGUID, + COALESCE(xplan.Name, NameCalc) AS EntityName, + '2898A6EB-3CAE-47D9-AF28-FC959F1E3955' AS PlanTypeGUID, -- Substitution Plan Type GUID + 'P|' + CONVERT(VARCHAR, [LootID]) AS CachedLootID, + AuthorGUID AS AuthorUserGUID + FROM [cap].[DimSubstitution] substitution + LEFT JOIN [dbo].[XPlan] xplan ON xplan.PlanGUID = substitution.MemberGUID + WHERE xplan.IsDeletedPlan = 0 OR xplan.IsDeletedPlan IS NULL +GO + + +--------------------------------------------- + +-- dbo.viewWFMissingReviewerPermissions +--Forward +CREATE view [dbo].[viewWFMissingReviewerPermissions] +as + --permissions for plan type's permission set + select distinct + S.WorkflowMapGUID, + PS.PermissionSetID, + UR.RoleID, + 0 as [Weight], + null as ReadValue, + null as WriteValue, + null as SecureValue, + null as CreateValue, + null as DeleteValue + from + WFReviewerAssignment RA + inner join WFWorkflowStep S on S.WorkflowStepGUID = RA.WorkflowStepGUID + inner join UserRole UR on UR.UserRoleGUID = RA.IdentityGUID + inner join PlanTypeWorkflowMapLink L on L.WorkflowMapGUID = S.WorkflowMapGUID + inner join PlanType PT on PT.PlanTypeGUID = L.PlanTypeGUID + inner join ScoreDimension D on D.DimensionGUID = PT.DimensionGUID and D.IsSecured = 1 + inner join S3PermissionSet PS on PS.PermissionSetID = D.PermissionSetID + where + not exists(select 1 from S3Permission P where P.PermissionSetID = PS.PermissionSetID and P.RoleID = UR.RoleID) + and PS.IsLocked = 0 + union all + --permission for any parent dimensions of plan dimension + select distinct + S.WorkflowMapGUID, + PS.PermissionSetID, + UR.RoleID, + 0 as [Weight], + null as ReadValue, + null as WriteValue, + null as SecureValue, + null as CreateValue, + null as DeleteValue + from + WFReviewerAssignment RA + inner join WFWorkflowStep S on S.WorkflowStepGUID = RA.WorkflowStepGUID + inner join UserRole UR on UR.UserRoleGUID = RA.IdentityGUID + inner join PlanTypeWorkflowMapLink L on L.WorkflowMapGUID = S.WorkflowMapGUID + inner join PlanType PT on PT.PlanTypeGUID = L.PlanTypeGUID + inner join ScoreDimension D on D.DimensionGUID = PT.DimensionGUID and D.IsSecured = 1 + inner join viewScoreAttribute A on A.DimensionGUID = D.DimensionGUID and A.IsSecuredLootGroupID = 1 + inner join viewScoreAttribute FKA on FKA.AttributeGUID = A.ForeignKeyGUID + inner join ScoreDimension FKD on FKD.DimensionGUID = FKA.DimensionGUID and FKD.IsSecured = 1 + inner join S3PermissionSet PS on PS.PermissionSetID = FKD.PermissionSetID and PS.PermissionSetID != D.PermissionSetID + where + not exists(select 1 from S3Permission P where P.PermissionSetID = PS.PermissionSetID and P.RoleID = UR.RoleID) + and PS.IsLocked = 0 +GO + + +--------------------------------------------- + +-- dbo.viewWFObjectsByFolder +CREATE view [dbo].[viewWFObjectsByFolder] +as + --workflows + select WF.WorkflowMapGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFWorkflowMap WF + union all + --phases + select P.ProcessGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFProcess P inner join WFWorkflowMap WF on WF.WorkflowMapGUID = P.WORKFLOWMAPGUID + union all + --steps + select S.WorkflowStepGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFWorkflowStep S inner join WFWorkflowMap WF on WF.WorkflowMapGUID = S.WORKFLOWMAPGUID + union all + --process-step links + select L.PROCESSSTEPLINKGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFProcessStepLink L inner join WFWorkflowMap WF on WF.WorkflowMapGUID = L.WORKFLOWMAPGUID + union all + --transitions + select T.TRANSITIONGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFTransition T inner join WFWorkflowMap WF on WF.WorkflowMapGUID = T.WORKFLOWMAPGUID + union all + --step reviewers + select RA.REVIEWERASSIGNMENTGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFReviewerAssignment RA inner join WFWorkflowStep S on S.WorkflowStepGUID = RA.WORKFLOWSTEPGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = S.WorkflowMapGUID + union all + --step review values + select RVT.STEPREVIEWVALUETYPELINKGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFStepReviewValueTypeLink RVT inner join WFWorkflowStep S on S.WorkflowStepGUID = RVT.WORKFLOWSTEPGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = S.WorkflowMapGUID + union all + --step events + select EP.EVENTPLANGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFEventPlan EP inner join WFWorkflowStep S on S.OnStartEventPlanGUID = EP.EVENTPLANGUID or S.OnEndEventPlanGUID = EP.EVENTPLANGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = S.WorkflowMapGUID + union all + --transition events + select EP.EVENTPLANGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFEventPlan EP inner join WFTransition T on T.EventPlanGUID = EP.EVENTPLANGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = T.WorkflowMapGUID + union all + --step event statements + select EPS.EventPlanStatementGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFEventPlanStatement EPS inner join WFEventPlan EP on EP.EVENTPLANGUID = EPS.EventPlanGUID inner join WFWorkflowStep S on S.OnStartEventPlanGUID = EP.EVENTPLANGUID or S.OnEndEventPlanGUID = EP.EVENTPLANGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = S.WorkflowMapGUID + union all + --transition event statements + select EPS.EventPlanStatementGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFEventPlanStatement EPS inner join WFEventPlan EP on EP.EVENTPLANGUID = EPS.EventPlanGUID inner join WFTransition T on T.EventPlanGUID = EP.EVENTPLANGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = T.WorkflowMapGUID + union all + --exit conditionsets + select CS.ConditionSetGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFConditionSet CS inner join WFTransition T on T.CONDITIONSETGUID = CS.CONDITIONSETGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = T.WORKFLOWMAPGUID + union all + --qualification conditionsets + select CS.ConditionSetGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFConditionSet CS inner join WFWorkflowStep S on S.QualifyConditionSetGUID = CS.CONDITIONSETGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = S.WorkflowMapGUID + union all + --step event conditionsets + select CS.ConditionSetGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFConditionSet CS inner join WFEventPlanStatement EPS on EPS.StatementGUID = CS.CONDITIONSETGUID inner join WFEventPlan EP on EP.EVENTPLANGUID = EPS.EventPlanGUID inner join WFWorkflowStep S on S.OnStartEventPlanGUID = EP.EVENTPLANGUID or S.OnEndEventPlanGUID = EP.EVENTPLANGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = S.WorkflowMapGUID + union all + --transition event conditionsets + select CS.ConditionSetGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFConditionSet CS inner join WFEventPlanStatement EPS on EPS.StatementGUID = CS.CONDITIONSETGUID inner join WFEventPlan EP on EP.EVENTPLANGUID = EPS.EventPlanGUID inner join WFTransition T on T.EventPlanGUID = EP.EVENTPLANGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = T.WorkflowMapGUID + union all + --exit conditions + select C.ConditionGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFCondition C inner join WFConditionSet CS on CS.CONDITIONSETGUID = C.ConditionSetGUID inner join WFTransition T on T.CONDITIONSETGUID = CS.CONDITIONSETGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = T.WORKFLOWMAPGUID + union all + --qualification conditions + select C.ConditionGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFCondition C inner join WFConditionSet CS on CS.CONDITIONSETGUID = C.ConditionSetGUID inner join WFWorkflowStep S on S.QualifyConditionSetGUID = CS.CONDITIONSETGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = S.WorkflowMapGUID + union all + --step event conditions + select C.ConditionGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFCondition C inner join WFConditionSet CS on CS.CONDITIONSETGUID = C.ConditionSetGUID inner join WFEventPlanStatement EPS on EPS.StatementGUID = CS.CONDITIONSETGUID inner join WFEventPlan EP on EP.EVENTPLANGUID = EPS.EventPlanGUID inner join WFWorkflowStep S on S.OnStartEventPlanGUID = EP.EVENTPLANGUID or S.OnEndEventPlanGUID = EP.EVENTPLANGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = S.WorkflowMapGUID + union all + --transition event conditions + select C.ConditionGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from WFCondition C inner join WFConditionSet CS on CS.CONDITIONSETGUID = C.ConditionSetGUID inner join WFEventPlanStatement EPS on EPS.StatementGUID = CS.CONDITIONSETGUID inner join WFEventPlan EP on EP.EVENTPLANGUID = EPS.EventPlanGUID inner join WFTransition T on T.EventPlanGUID = EP.EVENTPLANGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = T.WorkflowMapGUID + union all + --step event actions + select CA.ActionGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from CustomAction CA inner join WFEventPlanStatement EPS on EPS.StatementGUID = CA.ActionGUID inner join WFEventPlan EP on EP.EVENTPLANGUID = EPS.EventPlanGUID inner join WFWorkflowStep S on S.OnStartEventPlanGUID = EP.EVENTPLANGUID or S.OnEndEventPlanGUID = EP.EVENTPLANGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = S.WorkflowMapGUID where CA.ActionType = 1 + union all + --transition event actions + select CA.ActionGUID as ObjectGUID, WF.WorkflowMapGUID, WF.FolderGUID from CustomAction CA inner join WFEventPlanStatement EPS on EPS.StatementGUID = CA.ActionGUID inner join WFEventPlan EP on EP.EVENTPLANGUID = EPS.EventPlanGUID inner join WFTransition T on T.EventPlanGUID = EP.EVENTPLANGUID inner join WFWorkflowMap WF on WF.WorkflowMapGUID = T.WorkflowMapGUID where CA.ActionType = 1 +GO + + +--------------------------------------------- + +-- dbo.viewWFOverdueReviewLogToday +create view dbo.viewWFOverdueReviewLogToday +as +select * from [dbo].[WFOverdueReviewLog] where DateTimeStamp >= getdate() - 1 +GO + + +--------------------------------------------- + +-- dbo.viewWFOverdueReviews +CREATE view [dbo].[viewWFOverdueReviews] +as + select distinct + R.PlanGUID, + R.UserGUID, + R.WorkflowStepGUID, + S.WorkflowMapGUID + from + viewWFReviewerAssignment R + inner join WFToken T (readuncommitted) on T.WorkflowStepGUID = R.WorkflowStepGUID and T.EntityGUID = R.PlanGUID + inner join WFWorkflowStep S (readuncommitted) on S.WorkflowStepGUID = R.WorkflowStepGUID + inner join dbo.viewWFEntity E on E.EntityGUID = R.PlanGUID + where + S.ReminderDaysThreshold > 0 + and S.ReminderDaysThreshold <= (select DATEDIFF(day, MAX(H.DateTimeStamp), GETDATE()) from WFHistory H (readuncommitted) where H.HistoryType = 1 and H.EntityGUID = R.PlanGUID and H.WorkflowStepGUID = R.WorkflowStepGUID) + and not exists(select 1 from [dbo].[WFReviewValue] rv (readuncommitted) where rv.WorkflowStepGUID = S.WorkflowStepGUID and rv.IdentityGUID = R.UserGUID and rv.EntityGUID = E.EntityGUID) +GO + + +--------------------------------------------- + +-- dbo.viewWFReviewerAssignment +CREATE view [dbo].[viewWFReviewerAssignment] +as + --NOTE: results may not be distinct, so this is best used within an exists clause + + select + E.EntityGUID as PlanGUID, + RA.WorkflowStepGUID, + isnull(RD.DelegateUserGUID, UP.UserGUID) as UserGUID + from + viewWFEntity E (readuncommitted) + inner join S3Loot L (readuncommitted) on L.LootID = E.CachedLootID + inner join WFToken T (readuncommitted) on T.ENTITYGUID = E.EntityGUID + inner join WFWorkflowStep WFS (readuncommitted) on WFS.WorkflowMapGUID = T.WorkflowMapGUID + inner join WFReviewerAssignment RA (readuncommitted) on RA.WORKFLOWSTEPGUID = WFS.WORKFLOWSTEPGUID + + inner join S3IdentityLink sIL (readuncommitted) on sIL.GroupingGUID = RA.IdentityGUID + + inner join UserProfile UP (readuncommitted) on UP.UserGUID = sIL.MemberGUID + left join WFReviewerDelegate RD (readuncommitted) on RD.WorkflowStepGUID = RA.WorkflowStepGUID and RD.EntityGUID = E.EntityGUID and RD.ReviewerUserGUID = UP.UserGUID + + union all + + select + E.EntityGUID as PlanGUID, + RA.WorkflowStepGUID, + isnull(RD.DelegateUserGUID, UP.UserGUID) as UserGUID + from + viewWFEntity E (readuncommitted) + inner join S3Loot L (readuncommitted) on L.LootID = E.CachedLootID + inner join WFToken T (readuncommitted) on T.ENTITYGUID = E.EntityGUID + inner join WFWorkflowStep WFS (readuncommitted) on WFS.WorkflowMapGUID = T.WorkflowMapGUID + inner join WFReviewerAssignment RA (readuncommitted) on RA.WORKFLOWSTEPGUID = WFS.WORKFLOWSTEPGUID + + inner join S3LootGroup sLG (readuncommitted) on sLG.LootID = L.LootID + inner join UserRole sR (readuncommitted) on sR.UserRoleGUID = RA.IdentityGUID + inner join S3RoleAssignment sRA (readuncommitted) on sRA.LootGroupID = sLG.LootGroupID and sR.RoleID = sRA.RoleID + + inner join UserProfile UP (readuncommitted) on UP.UserGUID = sRA.IdentityGUID + left join WFReviewerDelegate RD (readuncommitted) on RD.WorkflowStepGUID = RA.WorkflowStepGUID and RD.EntityGUID = E.EntityGUID and RD.ReviewerUserGUID = UP.UserGUID + + union all + + select + E.EntityGUID as PlanGUID, + RA.WorkflowStepGUID, + isnull(RD.DelegateUserGUID, UP.UserGUID) as UserGUID + from + viewWFEntity E (readuncommitted) + inner join S3Loot L (readuncommitted) on L.LootID = E.CachedLootID + inner join WFToken T (readuncommitted) on T.ENTITYGUID = E.EntityGUID + inner join WFWorkflowStep WFS (readuncommitted) on WFS.WorkflowMapGUID = T.WorkflowMapGUID + inner join WFReviewerAssignment RA (readuncommitted) on RA.WORKFLOWSTEPGUID = WFS.WORKFLOWSTEPGUID + + inner join S3LootGroup sLG (readuncommitted) on sLG.LootID = L.LootID + inner join UserRole sR (readuncommitted) on sR.UserRoleGUID = RA.IdentityGUID + inner join S3RoleAssignment sRA (readuncommitted) on sRA.LootGroupID = sLG.LootGroupID and sR.RoleID = sRA.RoleID + inner join S3IdentityLink sIL (readuncommitted) on sIL.GroupingGUID = sRA.IdentityGUID + + inner join UserProfile UP (readuncommitted) on UP.UserGUID = sIL.MemberGUID + left join WFReviewerDelegate RD (readuncommitted) on RD.WorkflowStepGUID = RA.WorkflowStepGUID and RD.EntityGUID = E.EntityGUID and RD.ReviewerUserGUID = UP.UserGUID +GO + + +--------------------------------------------- + +-- dbo.viewWFReviewerAssignmentIndexedAll +CREATE view [dbo].[viewWFReviewerAssignmentIndexedAll] +as + --NOTE: results may not be distinct, so this is best used within an exists clause + + SELECT + OBJ.PlanGUID, + OBJ.WorkflowStepGUID, + OBJ.UserGUID + FROM + dbo.viewWFReviewerAssignmentIndexedByGroup OBJ (readuncommitted) + + union + + SELECT + OBJ.PlanGUID, + OBJ.WorkflowStepGUID, + OBJ.UserGUID + FROM + dbo.viewWFReviewerAssignmentIndexedByRole OBJ (readuncommitted) + + union + + SELECT + OBJ.PlanGUID, + OBJ.WorkflowStepGUID, + OBJ.UserGUID + FROM + dbo.viewWFReviewerAssignmentIndexedByRoleGroup OBJ (readuncommitted) +GO + + +--------------------------------------------- + +-- dbo.viewWFReviewerAssignmentIndexedByGroup +CREATE view [dbo].[viewWFReviewerAssignmentIndexedByGroup] +as + select + RA.PlanGUID, + RA.WorkflowStepGUID, + coalesce(D.DelegateUserGUID, RA.UserGUID) as UserGUID + from + viewWFReviewerAssignmentNoDelegatesByGroup RA with (noexpand) + left join WFReviewerDelegate D (readuncommitted) on D.ReviewerUserGUID = RA.UserGUID and D.WorkflowStepGUID = RA.WorkflowStepGUID and D.EntityGUID = RA.PlanGUID +GO + + +--------------------------------------------- + +-- dbo.viewWFReviewerAssignmentIndexedByRole +CREATE view [dbo].[viewWFReviewerAssignmentIndexedByRole] +as + select + RA.PlanGUID, + RA.WorkflowStepGUID, + coalesce(D.DelegateUserGUID, RA.UserGUID) as UserGUID + from + viewWFReviewerAssignmentNoDelegatesByRole RA with (noexpand) + left join WFReviewerDelegate D (readuncommitted) on D.ReviewerUserGUID = RA.UserGUID and D.WorkflowStepGUID = RA.WorkflowStepGUID and D.EntityGUID = RA.PlanGUID +GO + + +--------------------------------------------- + +-- dbo.viewWFReviewerAssignmentIndexedByRoleGroup +--Author: gforeman +--Branch: Firefly +--Forward +create view [dbo].[viewWFReviewerAssignmentIndexedByRoleGroup] +as + select + RA.PlanGUID, + RA.WorkflowStepGUID, + coalesce(D.DelegateUserGUID, RA.UserGUID) as UserGUID + from + viewWFReviewerAssignmentNoDelegatesByRoleGroup RA with (noexpand) + left join WFReviewerDelegate D (readuncommitted) on D.ReviewerUserGUID = RA.UserGUID and D.WorkflowStepGUID = RA.WorkflowStepGUID and D.EntityGUID = RA.PlanGUID +GO + + +--------------------------------------------- + +-- dbo.viewWFReviewerAssignmentNoDelegatesByGroup +CREATE view [dbo].[viewWFReviewerAssignmentNoDelegatesByGroup] with schemabinding +as + --NOTE: results may not be distinct, so this is best used within an exists clause + + select + T.EntityGUID as PlanGUID, + WFS.WorkflowStepGUID, + sIL.MemberGUID as UserGUID, + COUNT_BIG(*) as Cnt + from + dbo.WFToken T + inner join dbo.WFWorkflowStep WFS on WFS.WorkflowMapGUID = T.WorkflowMapGUID + inner join dbo.WFReviewerAssignment RA on RA.WORKFLOWSTEPGUID = WFS.WORKFLOWSTEPGUID + inner join dbo.S3IdentityLink sIL on sIL.GroupingGUID = RA.IdentityGUID + group by + T.EntityGUID, + WFS.WorkflowStepGUID, + sIL.MemberGUID +GO + + +--------------------------------------------- + +-- dbo.viewWFReviewerAssignmentNoDelegatesByRole +CREATE view [dbo].[viewWFReviewerAssignmentNoDelegatesByRole] with schemabinding +as + --NOTE: results may not be distinct, so this is best used within an exists clause + + select + P.PlanGUID, + WFS.WorkflowStepGUID, + sRA.IdentityGUID as UserGUID, + COUNT_BIG(*) as Cnt + from + dbo.XPlan P + inner join dbo.WFToken T on T.ENTITYGUID = P.PlanGUID + inner join dbo.WFWorkflowStep WFS on WFS.WorkflowMapGUID = T.WorkflowMapGUID + inner join dbo.WFReviewerAssignment RA on RA.WORKFLOWSTEPGUID = WFS.WORKFLOWSTEPGUID + inner join dbo.S3LootGroup sLG on sLG.LootID = P.CachedLootID + inner join dbo.UserRole sR on sR.UserRoleGUID = RA.IdentityGUID + inner join dbo.S3RoleAssignment sRA on sRA.LootGroupID = sLG.LootGroupID and sR.RoleID = sRA.RoleID + group by + P.PlanGUID, + WFS.WorkflowStepGUID, + sRA.IdentityGUID +GO + + +--------------------------------------------- + +-- dbo.viewWFReviewerAssignmentNoDelegatesByRoleGroup +CREATE view [dbo].[viewWFReviewerAssignmentNoDelegatesByRoleGroup] with schemabinding +as + --NOTE: results may not be distinct, so this is best used within an exists clause + --Includes only reviewers that are assigned to a group that is in a role that is the direct reviewer + + select + P.PlanGUID, + WFS.WorkflowStepGUID, + sIL.MemberGUID as UserGUID, + COUNT_BIG(*) as Cnt + from + dbo.XPlan P + inner join dbo.WFToken T on T.ENTITYGUID = P.PlanGUID + inner join dbo.WFWorkflowStep WFS on WFS.WorkflowMapGUID = T.WorkflowMapGUID + inner join dbo.WFReviewerAssignment RA on RA.WORKFLOWSTEPGUID = WFS.WORKFLOWSTEPGUID + inner join dbo.S3LootGroup sLG on sLG.LootID = P.CachedLootID + inner join dbo.UserRole sR on sR.UserRoleGUID = RA.IdentityGUID + inner join dbo.S3RoleAssignment sRA on sRA.LootGroupID = sLG.LootGroupID and sR.RoleID = sRA.RoleID + inner join dbo.S3IdentityLink sIL on sIL.GroupingGUID = sRA.IdentityGUID + group by + P.PlanGUID, + WFS.WorkflowStepGUID, + sIL.MemberGUID +GO + + +--------------------------------------------- + +-- dbo.viewWFSetup +CREATE view [dbo].[viewWFSetup] as +SELECT + PT.PlanTypeGUID, + PT.Name AS PTName, + WM.WorkflowMapGUID, + WM.Name AS WMName, + P.ProcessGUID, + P.Name AS PName, + WS.WorkflowStepGUID, + WS.Name AS WSName, + P.DisplayOrder as PDisplayOrder, + WS.DisplayOrder as WSDisplayOrder +FROM + PlanType PT + INNER JOIN PlanTypeWorkflowMapLink L ON PT.PlanTypeGUID = L.PlanTypeGUID + INNER JOIN WFWorkflowMap WM ON WM.WorkflowMapGUID = L.WorkflowMapGUID + INNER JOIN WFWorkflowStep WS ON WS.WorkflowMapGUID = WM.WorkflowMapGUID + LEFT JOIN WFProcessStepLink PSL ON PSL.WorkflowStepGUID = WS.WorkflowStepGUID + LEFT JOIN WFProcess P ON P.ProcessGUID = PSL.ProcessGUID +--ORDER BY +-- PT.Name, WM.Name, P.DisplayOrder, WS.DisplayOrder +GO + + +--------------------------------------------- + +-- dbo.viewWFWorkflowStepCore30 +CREATE view dbo.viewWFWorkflowStepCore30 +as + select + isnull(m.Name, 'Step Templates') as WorkflowMapName, + s.* + from + dbo.WFWorkflowStep s + left join dbo.WFWorkflowMap m on m.WorkflowMapGUID = s.WorkflowMapGUID +GO + + +--------------------------------------------- + +-- dbo.viewXPlanWithLocks +CREATE view [dbo].[viewXPlanWithLocks] +as + select + isnull( + case + when L.LockGUID is not null or P.IsFinancialsLocked = 1 or P.IsSuspended = 1 then cast(1 as bit) + else cast(0 as bit) end, + cast(0 as bit)) as IsLocked, + + case + when L.LockGUID is not null then 'Locked for edit by ' + L.UserName + ' (' + cast(L.DateLocked as nvarchar(max)) + ')' + when P.IsFinancialsLocked = 1 then 'This plan has been finalized and is no longer editable' + when P.IsSuspended = 1 then 'Budget suspended by ' + P.SuspendedByUserName + ' (' + cast(P.DateSuspended as nvarchar(max)) + ')' + else '' end as LockReason, + P.* + from + dbo.XPlan P with (readuncommitted) + left join Lock L with (readuncommitted) on L.ItemGUID = P.PlanGUID and L.LockGroup = 'PlanLock' + inner join EMFModelTemplate MT on P.ModelTemplateGUID = MT.ModelTemplateGUID +GO + + +--------------------------------------------- + +--------------------------------------------- +-- PROCEDURES +--------------------------------------------- + +-- dbo.ConvertIntToBigIntByColumnNameNoCompression +CREATE PROCEDURE [dbo].[ConvertIntToBigIntByColumnNameNoCompression] (@sourceSchema nvarchar(100), @sourceTable nvarchar(200), @columnName nvarchar(200), @debug bit=0, @expectedType nvarchar(100)='bigint') + AS + SET NOCOUNT ON + + DECLARE @runTime datetime=getdate() + DECLARE @cmd nvarchar(max) + DECLARE @targetTable nvarchar(200) + DECLARE @objectId int + DECLARE @name nvarchar(max) + DECLARE @definition nvarchar(4000) + DECLARE @colName nvarchar(100) + DECLARE @conName nvarchar(100) + DECLARE @compressionDesc nvarchar(20) + DECLARE @indexId int + DECLARE @conType nvarchar(5) + DECLARE @indexType nvarchar(50) + DECLARE @uniqueness nvarchar(50) + DECLARE @indexName nvarchar(100) + DECLARE @suffix nvarchar(50) + DECLARE @mergedSource nvarchar(100) + DECLARE @fullSourceName sysname + DECLARE @dataType nvarchar(200) + + SELECT @dataType = DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_NAME = @sourceTable and COLUMN_NAME = @columnName and TABLE_SCHEMA = @sourceSchema + + IF (dbo.TableExists(@sourceSchema, @sourceTable) = 0 or @dataType = @expectedType) + BEGIN + RETURN + END + + IF (NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'identityCompression')) + BEGIN + EXEC ('CREATE SCHEMA [identityCompression] AUTHORIZATION [dbo]') + END + +----create suffix in the format of _YYYYMMDD for backup table + SELECT @fullSourceName=@sourceSchema+'.'+@sourceTable + SELECT @suffix=REPLACE(convert(nvarchar,GETDATE(),102),'.','')+'_'+REPLACE(LEFT(CONVERT(varchar,CONVERT(time,GETDATE(),8)),8),':','') + SELECT @objectId=object_id FROM sys.objects WHERE schema_id=schema_id(@sourceSchema) AND name=@sourceTable + SELECT @targetTable='identityCompression.['+@sourceTable+'_'+REPLACE(CONVERT(nvarchar(max),NEWID()),'-','_')+']' + SELECT @mergedSource='['+@sourceSchema+'].['+@sourceTable+']' +/* Create table Compress table (if required) Create default constraints */ +-- create the new target table + + DECLARE @def nvarchar(max) + DECLARE c1 CURSOR FOR + SELECT '['+c.name+']' + + CASE + WHEN c.is_computed=0 THEN CASE WHEN c.name!=@columnName then ' ['+t.name+']' else ' ['+@expectedType+']' end + + CASE + WHEN c.is_identity=1 THEN ' identity('+CONVERT(varchar,ident_seed(@mergedSource)) +','+CONVERT(varchar,ident_incr(@mergedSource))+')' + ELSE '' + END + + CASE + WHEN t.name LIKE 'n%char' AND c.max_length = -1 THEN '(max)' + WHEN t.name LIKE 'n%char' THEN ' ('+CONVERT(varchar,c.max_length/2)+')' + WHEN t.name LIKE '%char%' THEN ' ('+CONVERT(varchar,c.max_length)+')' + WHEN t.name IN ('numeric','decimal') THEN '('+CONVERT(varchar,c.precision)+','+CONVERT(varchar,c.scale)+')' + ELSE '' + END + + CASE + WHEN cc.is_persisted=1 THEN ' PERSISTED' + ELSE '' + END + + CASE + WHEN c.is_nullable=1 THEN ' NULL' + ELSE ' NOT NULL' + END + ELSE ' as ' + + cc.definition + + CASE + WHEN cc.is_persisted=1 THEN ' PERSISTED' + ELSE '' + END + + CASE + WHEN cc.is_persisted=1 AND c.is_nullable=0 THEN ' NOT NULL' + ELSE '' + END + END + FROM sys.columns c + INNER JOIN sys.types t + ON t.system_type_id = c.system_type_id + AND t.user_type_id = c.user_type_id + + LEFT JOIN sys.computed_columns cc + ON cc.object_id = c.object_id + AND cc.name = c.name + WHERE c.object_id = @objectId + ORDER BY c.column_id + OPEN c1 + FETCH c1 INTO @def + SELECT @cmd = 'create table ' + @targetTable + '(' + @def + FETCH c1 INTO @def + WHILE @@FETCH_STATUS = 0 + BEGIN + SELECT @cmd = @cmd + ',' + @def + FETCH c1 INTO @def + END + SELECT @cmd = @cmd + ')' + CLOSE c1 + DEALLOCATE c1 + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + +-- select the compression type of the table + SELECT TOP 1 @compressionDesc = [data_compression_desc] + FROM sys.partitions + WHERE object_id=@objectId + SELECT @cmd = 'ALTER TABLE ' + @targetTable + ' rebuild partition = all with (data_compression = ' + @compressionDesc + ')' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) +--duplicate defaults for the target table from the source + + DECLARE c1 CURSOR FOR + SELECT con.name, con.definition, col.name + FROM sys.default_constraints con + INNER JOIN sys.columns col + ON con.parent_column_id = col.column_id + AND col.object_id = con.parent_object_id + WHERE con.parent_object_id = @objectId + AND con.type = 'D' + OPEN c1 + FETCH c1 INTO @name, @definition, @colName + WHILE @@FETCH_STATUS=0 + BEGIN + SELECT @cmd = 'SP_RENAME '''+@sourceSchema+'.'+@name+''','''+@name+'_'+@suffix+'''' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + SELECT @cmd = 'ALTER TABLE '+@targetTable+' ADD CONSTRAINT ['+@name+'] DEFAULT '+@definition+' FOR ['+@colName+']' + BEGIN TRY + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + END TRY + BEGIN CATCH + PRINT 'Error: ' + @cmd + END CATCH + FETCH c1 INTO @name, @definition, @colName + END + CLOSE c1 +DEALLOCATE c1 +--Check if source table has an identity column + + DECLARE @isIdentity bit + DECLARE @colList nvarchar(max) + DECLARE @srcList nvarchar(max) + IF EXISTS (SELECT 1 FROM sys.columns WHERE object_id = @objectId AND is_identity = 1) + SELECT @isIdentity=1 + ELSE + SELECT @isIdentity = 0 +--Create list of columns in the source/target tables. Omit timestamp columns + + DECLARE c2 CURSOR FOR + SELECT DISTINCT '['+c.name+']' + FROM sys.columns c + LEFT JOIN sys.systypes t + ON t.xtype = c.system_type_id + WHERE c.object_id=@objectId + AND t.name != 'timestamp' + AND c.is_computed=0 + --AND c.is_identity=0 + ORDER BY '['+c.name+']' + OPEN c2 + FETCH c2 INTO @colName + SELECT @colList = @colName + SELECT @srcList = 'src.' + @colName + FETCH c2 INTO @colName + WHILE @@FETCH_STATUS = 0 + BEGIN + SELECT @colList=@colList+','+@colName + SELECT @srcList=@srcList+',src.'+@colName + FETCH c2 INTO @colName + END + CLOSE c2 +DEALLOCATE c2 +---- PRINT @colList +--Populate the target table. + select @cmd='' + + if @isIdentity=1 + begin + select @cmd='set identity_insert '+@targetTable+' on; ' + --exec (@cmd) + end + + SELECT @cmd = @cmd+'INSERT ' + @targetTable + ' WITH (tablock) (' + @colList + ') SELECT ' + @colList + ' FROM [' + @sourceSchema + '].[' + @sourceTable + '] src ;' + --PRINT @cmd + --IF @debug=0 + --EXEC (@cmd) + + if @isIdentity=1 + begin + select @cmd=@cmd+'; set identity_insert '+@targetTable+' off' + --exec (@cmd) + end + + PRINT @cmd + IF @debug=0 + EXEC (@cmd) +--Replicate the primary and unique keys for the target table + + DECLARE c1 CURSOR FOR + SELECT c.name, c.unique_index_id, c.type, i.type_desc + FROM sys.key_constraints c + INNER JOIN sys.indexes i + ON i.object_id = c.parent_object_id + AND i.index_id=c.unique_index_id + WHERE c.type IN ('PK','UQ') + AND c.parent_object_id=@objectId + OPEN c1 + FETCH c1 INTO @conName, @indexId, @conType, @indexType + WHILE @@FETCH_STATUS=0 + BEGIN + PRINT @conName +' ' + convert(varchar,@indexId)+' '+@conType + DECLARE c2 CURSOR FOR + SELECT '[' + c.name + ']' + FROM sys.index_columns ic + INNER JOIN sys.columns c + ON ic.object_id = c.object_id + AND c.column_id=ic.column_id + AND ic.is_included_column=0 + WHERE ic.object_id = @objectId + AND ic.index_id = @indexId + --ORDER BY ic.index_column_id + ORDER BY ic.key_ordinal + OPEN c2 + --SELECT @objectId,@indexId + FETCH c2 INTO @colName + PRINT @colName + SELECT @colList = @colName + FETCH c2 INTO @colName + WHILE @@FETCH_STATUS = 0 + BEGIN + SELECT @colList = @colList + ',' + @colName + FETCH c2 INTO @colName + END + CLOSE c2 + DEALLOCATE c2 + IF @conType='PK' + SELECT @cmd='alter table '+@targetTable+' add constraint '+@conName+' primary key '+@indexType+' ('+@colList+') with (data_compression='+@compressionDesc+')' + IF @conType='UQ' + SELECT @cmd='alter table '+@targetTable+' add constraint '+@conName+' unique '+@indexType+' ('+@colList+') with (data_compression='+@compressionDesc+')' + PRINT @cmd + IF @debug=0 + EXEC (@cmd) + FETCH c1 INTO @conName,@indexId,@conType,@indexType + END + CLOSE c1 +DEALLOCATE c1 +--Create check constraints + + DECLARE c1 CURSOR FOR + SELECT [name],[definition] + FROM sys.check_constraints + WHERE parent_object_id = @objectId + OPEN c1 + FETCH c1 INTO @conName,@definition + WHILE @@FETCH_STATUS = 0 + BEGIN + SELECT @cmd = 'SP_RENAME '''+@sourceSchema+'.'+@conName+''','''+@conName+'_'+@suffix+'''' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + + SELECT @cmd = 'ALTER TABLE ' + @targetTable + ' ADD CONSTRAINT ' + @conName + ' check ' + @definition + IF @debug = 0 + EXEC (@cmd) + FETCH c1 INTO @conName, @definition + END + CLOSE c1 +DEALLOCATE c1 +----Create indexes + + DECLARE @incList nvarchar(max) + DECLARE @incName nvarchar(100) + DECLARE @ascDesc nvarchar(10) + DECLARE c1 CURSOR FOR + SELECT name, index_id, type_desc, + CASE + WHEN is_unique=1 THEN 'UNIQUE' + ELSE '' + END + FROM sys.indexes i + WHERE i.object_id = @ObjectId + AND NOT EXISTS + (SELECT 1 + FROM sys.key_constraints kc + WHERE kc.parent_object_id = i.object_id + AND i.index_id = kc.unique_index_id) + OPEN c1 + FETCH c1 INTO @indexName, @indexId, @indexType, @uniqueness + WHILE @@FETCH_STATUS = 0 + BEGIN + DECLARE c2 CURSOR FOR + SELECT '[' + c.name + ']' , + CASE + WHEN ic.is_descending_key = 1 THEN 'DESC' + ELSE 'ASC' + END + FROM sys.index_columns ic + INNER JOIN sys.columns c + ON ic.object_id = c.object_id + AND c.column_id = ic.column_id + AND ic.is_included_column = 0 + WHERE ic.object_id = @objectId + AND ic.index_id = @indexId + --ORDER BY ic.index_column_id + ORDER BY ic.key_ordinal + + OPEN c2 + FETCH c2 INTO @colName,@ascDesc + SELECT @colList = @colName + ' ' + @ascDesc + FETCH c2 INTO @colName, @ascDesc + WHILE @@FETCH_STATUS=0 + BEGIN + SELECT @colList = @colList + ',' + @colName + ' ' + @ascDesc + FETCH c2 INTO @colName, @ascDesc + END + CLOSE c2 + DEALLOCATE c2 + SELECT @colName = '' + DECLARE c2 CURSOR FOR + SELECT '[' + c.name + ']' + FROM sys.index_columns ic + INNER JOIN sys.columns c + ON ic.object_id = c.object_id + AND c.column_id = ic.column_id + AND ic.is_included_column = 1 + WHERE ic.object_id = @objectId + AND ic.index_id = @indexId + --ORDER BY ic.index_column_id + ORDER BY ic.key_ordinal + + OPEN c2 + FETCH c2 INTO @colName + SELECT @incList = @colName + FETCH c2 INTO @colName + WHILE @@FETCH_STATUS=0 + BEGIN + SELECT @incList = @incList + ',' + @colName + FETCH c2 INTO @colName + END + CLOSE c2 + DEALLOCATE c2 + PRINT @indexName +' : ' + @colList + ' : '+@inclist + SELECT @cmd = 'CREATE ' + @uniqueness + ' ' + @indexType+ + +' INDEX [' + @indexName + '] ON ' + @targetTable + ' (' + @colList + ')' + + CASE + WHEN @incList = '' THEN '' + ELSE ' include (' + @incList + ')' + END + +' WITH (data_compression=' + @compressionDesc + ')' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + FETCH c1 INTO @indexName, @indexId, @indexType, @uniqueness + END + CLOSE c1 +DEALLOCATE c1 +----Create foreign keys + + DECLARE @refColName nvarchar(max) + DECLARE @refColList nvarchar(max) + DECLARE @refTable nvarchar(100) + DECLARE @onDelete nvarchar(50) + DECLARE @onUpdate nvarchar(50) + + DECLARE c1 CURSOR FOR + SELECT name, delete_referential_action_desc, update_referential_action_desc + FROM sys.foreign_keys + WHERE parent_object_id = @objectId + OPEN c1 + FETCH c1 INTO @conName, @onDelete, @onUpdate + WHILE @@fetch_status = 0 + BEGIN + DECLARE c2 CURSOR FOR + SELECT pc.name, rc.name, '[' + schema_name(t.schema_id) + '].[' + t.name + ']' + FROM sys.foreign_key_columns fkc + INNER JOIN sys.foreign_keys fk + ON fkc.constraint_object_id = fk.object_id + INNER JOIN sys.columns pc + ON pc.column_id = fkc.parent_column_id + AND pc.object_id = @objectId + INNER JOIN sys.columns rc + ON rc.column_id = fkc.referenced_column_id + AND rc.object_id = fkc.referenced_object_id + INNER JOIN sys.tables t + ON t.object_id = fkc.referenced_object_id + WHERE fk.parent_object_id=@objectId + AND fk.name = @conName + ORDER BY fkc.constraint_column_id + + OPEN c2 + FETCH c2 INTO @colName, @refColName, @refTable + SELECT @colList = @colName + SELECT @refColList = @refColName + FETCH c2 INTO @colName, @refColName, @refTable + WHILE @@FETCH_STATUS = 0 + BEGIN + SELECT @colList = ',' + @colName + SELECT @refColList = ',' + @refColName + FETCH c2 INTO @colName,@refColName,@refTable + END + CLOSE c2 + DEALLOCATE c2 + SELECT @cmd = 'ALTER TABLE ' + @targetTable + ' ADD CONSTRAINT [' + @conName + '] FOREIGN KEY (' + @colList + ') REFERENCES ' + @refTable + '(' + @refColList + ') ' + + CASE + WHEN @onDelete != 'NO_ACTION' THEN 'on delete ' + @onDelete + ELSE '' + END + + CASE + WHEN @onUpdate != 'NO_ACTION' THEN ' on update ' + @onUpdate + ELSE '' + END + PRINT @cmd + IF @debug=0 + EXEC (@cmd) + FETCH c1 INTO @conName, @onDelete, @onUpdate + END + CLOSE c1 +DEALLOCATE c1 +-- Rename the primary key and drop foreign keys in the source table + DECLARE c1 CURSOR FOR + SELECT name, type + FROM sys.key_constraints + WHERE parent_object_id = @objectId + UNION ALL + SELECT name,type + FROM sys.foreign_keys + WHERE parent_object_id = @objectId + OPEN c1 + FETCH c1 INTO @conName, @conType + WHILE @@FETCH_STATUS = 0 + BEGIN + IF @conType = 'F' + SELECT @cmd = 'ALTER TABLE [' + @sourceSchema + '].[' + @sourceTable + '] DROP CONSTRAINT [' + @conName + ']' + ELSE + SELECT @cmd = 'sp_rename ''' + @sourceSchema + '.' + @sourceTable + '.' + @conName + ''',' + '''' + @conName + '_' + @suffix + '''' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + FETCH c1 INTO @conName,@conType + END + CLOSE c1 +DEALLOCATE c1 +-- Turn on change tracking if required + IF EXISTS (SELECT 1 FROM sys.change_tracking_tables WHERE OBJECT_ID=@objectId) + BEGIN + SELECT @cmd='ALTER TABLE '+@targetTable+' enable Change_tracking' + exec (@cmd) + END +-- Replace the source table with the target table. Move the source table to the bak schema and append @suffix + SELECT @cmd = 'sp_rename ''' + @sourceSchema + '.' + @sourceTable + '''' + ',''' + @sourceTable + '_' + @suffix + '''' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + SELECT @cmd = 'sp_rename ''' + REPLACE(REPLACE(@targetTable,'[',''),']','') + ''',''' + @sourceTable + '''' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + SELECT @cmd = 'ALTER SCHEMA [' + @sourceSchema + '] TRANSFER [identityCompression].[' + @sourceTable + ']' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + SELECT @cmd = 'ALTER SCHEMA [BAK] TRANSFER [' + @sourceSchema + '].[' + @sourceTable + '_' + @suffix + ']' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) +-- Create triggers here + DECLARE @triggerDef varchar(MAX) = '' + DECLARE @triggerName varchar(MAX) = '' + DECLARE @triggerDisabled bit = 0 + DECLARE @triggerSql varchar(MAX) = '' + + SELECT m.definition, obj.name, t.is_disabled + into #tmpTriggers + FROM sys.sql_modules m + INNER JOIN sys.objects obj on obj.object_id = m.object_id + INNER JOIN sys.triggers t on t.object_id = m.object_id + WHERE obj.type = 'TR' and obj.parent_object_id = OBJECT_ID('[BAK].[' + @sourceTable + '_' + @suffix + ']') + + DECLARE c1 CURSOR FOR + SELECT definition, name, is_disabled + FROM #tmpTriggers + OPEN c1 + FETCH c1 INTO @triggerDef, @triggerName, @triggerDisabled + WHILE @@FETCH_STATUS = 0 + BEGIN + --There is no renaming trigger so a drop and create is necessary to put the original trigger on the bak table + SET @triggerSql = 'DROP TRIGGER IF EXISTS [BAK].[' + @triggerName + ']' + PRINT @triggerSql + IF @debug = 0 + EXEC (@triggerSql) + + --create the trigger replacing the orig table name with bak name + SET @triggerSql = REPLACE(@triggerDef, @triggerName, @triggerName + '_' + @suffix) + SET @triggerSql = REPLACE(@triggerSql, '[' + @sourceSchema + ']','[bak]') + SET @triggerSql = REPLACE(@triggerSql, '[' + @sourceTable, '[' + @sourceTable + '_' + @suffix) + SET @triggerSql = REPLACE(@triggerSql, @sourceSchema + '.' + @sourceTable, 'bak.' + @sourcetable + '_' + @suffix) + PRINT @triggerSql + IF @debug = 0 + EXEC (@triggerSql) + + --create trigger on new table + PRINT @triggerDef + IF @debug = 0 + EXEC (@triggerDef) + --disable trigger if it was previously disabled + IF (@triggerDisabled <> 0) + BEGIN + SET @triggerSql = 'DISABLE TRIGGER [' + @sourceSchema + '].[' + @triggerName + '] on [' + @sourceSchema + '].[' + @sourceTable + ']' + PRINT @triggerSql + IF @debug = 0 + EXEC (@triggerSql) + END + FETCH c1 INTO @triggerDef, @triggerName, @triggerDisabled + END + CLOSE c1 +DEALLOCATE c1 +--Update replication table if required + IF EXISTS (SELECT 1 FROM dbo.ReplicationTable WHERE TableName=@fullSourceName) + BEGIN + UPDATE dbo.ReplicationTable set LastRefreshChangeTrackingVersion = null + WHERE TableName = @fullSourceName + END +GO + + +--------------------------------------------- + +-- dbo.CopyData +CREATE PROCEDURE [dbo].[CopyData] (@sourceSchema nvarchar(100), @sourceTable nvarchar(200), @whereClause nvarchar(2000), @debug bit=0, @identityCompression bit=0) + AS + SET NOCOUNT ON + DECLARE @cmd nvarchar(max) + DECLARE @targetTable nvarchar(200) + DECLARE @objectId int + DECLARE @name nvarchar(100) + DECLARE @definition nvarchar(4000) + DECLARE @colName nvarchar(100) + DECLARE @conName nvarchar(100) + DECLARE @compressionDesc nvarchar(20) + DECLARE @indexId int + DECLARE @conType nvarchar(5) + DECLARE @indexType nvarchar(50) + DECLARE @uniqueness nvarchar(50) + DECLARE @indexName nvarchar(100) + DECLARE @suffix nvarchar(50) + DECLARE @mergedSource nvarchar(100) + +----create suffix in the format of _YYYYMMDD for backup table + + SELECT @suffix=REPLACE(convert(nvarchar,GETDATE(),102),'.','')+'_'+REPLACE(LEFT(CONVERT(varchar,CONVERT(time,GETDATE(),8)),8),':','') + SELECT @objectId=object_id FROM sys.objects WHERE schema_id=schema_id(@sourceSchema) AND name=@sourceTable + SELECT @targetTable='data.['+@sourceTable+'_'+REPLACE(CONVERT(nvarchar(max),NEWID()),'-','_')+']' + SELECT @mergedSource='['+@sourceSchema+'].['+@sourceTable+']' + +/* Create table Compress table (if required) Create default constraints */ +-- create the new target table + + IF EXISTS (SELECT 1 FROM sys.columns WHERE object_id=@objectId AND is_computed=1) + BEGIN + DECLARE @def nvarchar(max) + DECLARE c1 CURSOR FOR + SELECT '['+c.name+']' + + CASE + WHEN c.is_computed=0 THEN ' ['+t.name+']' + + CASE + WHEN c.is_identity=1 THEN ' identity('+CONVERT(varchar,ident_seed(@mergedSource)) +','+CONVERT(varchar,ident_incr(@mergedSource))+')' + ELSE '' + END + + CASE + WHEN t.name LIKE 'n%char' AND c.max_length = -1 THEN '(max)' + WHEN t.name LIKE 'n%char' THEN ' ('+CONVERT(varchar,c.max_length/2)+')' + WHEN t.name LIKE '%char%' THEN ' ('+CONVERT(varchar,c.max_length)+')' + WHEN t.name IN ('numeric','decimal') THEN '('+CONVERT(varchar,c.precision)+','+CONVERT(varchar,c.scale)+')' + ELSE '' + END + + CASE + WHEN c.is_nullable=1 THEN ' NULL' + ELSE ' NOT NULL' + END + ELSE ' as ' + + cc.definition + END + FROM sys.columns c + INNER JOIN sys.types t + ON t.system_type_id = c.system_type_id + AND t.user_type_id = c.user_type_id + + LEFT JOIN sys.computed_columns cc + ON cc.object_id = c.object_id + AND cc.name = c.name + WHERE c.object_id = @objectId + ORDER BY c.column_id + + OPEN c1 + FETCH c1 INTO @def + SELECT @cmd = 'create table ' + @targetTable + '(' + @def + FETCH c1 INTO @def + WHILE @@FETCH_STATUS = 0 + BEGIN + SELECT @cmd = @cmd + ',' + @def + FETCH c1 INTO @def + END + SELECT @cmd = @cmd + ')' + CLOSE c1 + DEALLOCATE c1 + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + END + ELSE + BEGIN + SELECT @cmd='SELECT * INTO '+@targetTable+' FROM ['+@sourceSchema+'].['+@sourceTable +'] WHERE 1=2' + PRINT @cmd + IF @debug=0 + EXEC (@cmd) + END + +-- select the compression type of the table + + SELECT TOP 1 @compressionDesc = [data_compression_desc] + FROM sys.partitions + WHERE object_id=@objectId + SELECT @cmd = 'ALTER TABLE ' + @targetTable + ' rebuild partition = all with (data_compression = ' + @compressionDesc + ')' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + +--duplicate defaults for the target table from the source + + DECLARE c1 CURSOR FOR + SELECT con.name, con.definition, col.name + FROM sys.default_constraints con + INNER JOIN sys.columns col + ON con.parent_column_id = col.column_id + AND col.object_id = con.parent_object_id + WHERE con.parent_object_id = @objectId + AND con.type = 'D' + OPEN c1 + FETCH c1 INTO @name, @definition, @colName + WHILE @@FETCH_STATUS=0 + BEGIN + SELECT @cmd = 'ALTER TABLE '+@targetTable+' ADD DEFAULT '+@definition+' FOR ['+@colName+']' + BEGIN TRY + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + END TRY + BEGIN CATCH + PRINT 'Error: ' + @cmd + END CATCH + FETCH c1 INTO @name, @definition, @colName + END + CLOSE c1 +DEALLOCATE c1 + +--Check if source table has an identity column + + DECLARE @isIdentity bit + DECLARE @colList nvarchar(max) + DECLARE @srcList nvarchar(max) + IF EXISTS (SELECT 1 FROM sys.columns WHERE object_id = @objectId AND is_identity = 1) + SELECT @isIdentity=1 + ELSE + SELECT @isIdentity = 0 + +--Create list of columns in the source/target tables. Omit timestamp columns and identity column if @identityCompression=1 + + DECLARE c2 CURSOR FOR + SELECT DISTINCT '['+c.name+']' + FROM sys.columns c + LEFT JOIN sys.systypes t + ON t.xtype = c.system_type_id + WHERE c.object_id=@objectId + AND t.name != 'timestamp' + AND c.is_computed=0 + AND (c.is_identity=0 or @identityCompression=0) + ORDER BY '['+c.name+']' + OPEN c2 + FETCH c2 INTO @colName + SELECT @colList = @colName + SELECT @srcList = 'src.' + @colName + FETCH c2 INTO @colName + WHILE @@FETCH_STATUS = 0 + BEGIN + SELECT @colList=@colList+','+@colName + SELECT @srcList=@srcList+',src.'+@colName + FETCH c2 INTO @colName + END + CLOSE c2 +DEALLOCATE c2 + +---- PRINT @colList +--Populate the target table. + + IF @identityCompression = 0 + BEGIN + SELECT @cmd = CASE + WHEN @isIdentity = 1 THEN 'SET identity_insert ' + @targetTable + ' ON;' + ELSE '' + END + SELECT @cmd = @cmd + 'INSERT ' + @targetTable + ' WITH (tablock) (' + @colList + ') SELECT ' + @srcList + ' FROM [' + @sourceSchema + '].[' + @sourceTable + '] src ' + @whereClause + ';' + SELECT @cmd = @cmd + + CASE + WHEN @isIdentity = 1 THEN 'SET identity_insert ' + @targetTable + ' OFF;' + ELSE '' + END + END + ELSE + BEGIN + SELECT @cmd = 'INSERT ' + @targetTable + ' WITH (tablock) (' + @colList + ') SELECT ' + @colList + ' FROM [' + @sourceSchema + '].[' + @sourceTable + '] src ' + @whereClause + ';' + END + PRINT @cmd + IF @debug=0 + EXEC (@cmd) + +--Replicate the primary and unique keys for the target table + + DECLARE c1 CURSOR FOR + SELECT c.name, c.unique_index_id, c.type, i.type_desc + FROM sys.key_constraints c + INNER JOIN sys.indexes i + ON i.object_id = c.parent_object_id + AND i.index_id=c.unique_index_id + WHERE c.type IN ('PK','UQ') + AND c.parent_object_id=@objectId + OPEN c1 + FETCH c1 INTO @conName, @indexId, @conType, @indexType + WHILE @@FETCH_STATUS=0 + BEGIN + --PRINT @conName +' ' + convert(varchar,@indexId)+' '+@conType + DECLARE c2 CURSOR FOR + SELECT '[' + c.name + ']' + FROM sys.index_columns ic + INNER JOIN sys.columns c + ON ic.object_id = c.object_id + AND c.column_id=ic.column_id + AND ic.is_included_column=0 + WHERE ic.object_id = @objectId + AND ic.index_id = @indexId + ORDER BY ic.index_column_id + OPEN c2 + --SELECT @objectId,@indexId + FETCH c2 INTO @colName + --PRINT @colName + SELECT @colList = @colName + FETCH c2 INTO @colName + WHILE @@FETCH_STATUS = 0 + BEGIN + SELECT @colList = @colList + ',' + @colName + FETCH c2 INTO @colName + END + CLOSE c2 + DEALLOCATE c2 + IF @conType='PK' + SELECT @cmd='alter table '+@targetTable+' add constraint '+@conName+' primary key '+@indexType+' ('+@colList+') with (data_compression='+@compressionDesc+')' + IF @conType='UQ' + SELECT @cmd='alter table '+@targetTable+' add constraint '+@conName+' unique '+@indexType+' ('+@colList+') with (data_compression='+@compressionDesc+')' + PRINT @cmd + IF @debug=0 + EXEC (@cmd) + FETCH c1 INTO @conName,@indexId,@conType,@indexType + END + CLOSE c1 +DEALLOCATE c1 + +--Create check constraints + + DECLARE c1 CURSOR FOR + SELECT [name],[definition] + FROM sys.check_constraints + WHERE parent_object_id = @objectId + OPEN c1 + FETCH c1 INTO @conName,@definition + WHILE @@FETCH_STATUS = 0 + BEGIN + SELECT @cmd = 'ALTER TABLE ' + @targetTable + ' ADD CONSTRAINT ' + @conName + ' check ' + @definition + IF @debug = 0 + EXEC (@cmd) + FETCH c1 INTO @conName, @definition + END + CLOSE c1 +DEALLOCATE c1 + +----Create indexes + + DECLARE @incList nvarchar(max) + DECLARE @incName nvarchar(100) + DECLARE @ascDesc nvarchar(10) + DECLARE c1 CURSOR FOR + SELECT name, index_id, type_desc, + CASE + WHEN is_unique=1 THEN 'UNIQUE' + ELSE 'NONUNIQUE' + END + FROM sys.indexes i + WHERE i.object_id = @ObjectId + AND NOT EXISTS + (SELECT 1 + FROM sys.key_constraints kc + WHERE kc.parent_object_id = i.object_id + AND i.index_id = kc.unique_index_id) + + OPEN c1 + FETCH c1 INTO @indexName, @indexId, @indexType, @uniqueness + WHILE @@FETCH_STATUS = 0 + BEGIN + DECLARE c2 CURSOR FOR + SELECT '[' + c.name + ']' , + CASE + WHEN ic.is_descending_key = 1 THEN 'DESC' + ELSE 'ASC' + END + FROM sys.index_columns ic + INNER JOIN sys.columns c + ON ic.object_id = c.object_id + AND c.column_id = ic.column_id + AND ic.is_included_column = 0 + WHERE ic.object_id = @objectId + AND ic.index_id = @indexId + ORDER BY ic.index_column_id + + OPEN c2 + FETCH c2 INTO @colName,@ascDesc + SELECT @colList = @colName + ' ' + @ascDesc + FETCH c2 INTO @colName, @ascDesc + WHILE @@FETCH_STATUS=0 + BEGIN + SELECT @colList = @colList + ',' + @colName + ' ' + @ascDesc + FETCH c2 INTO @colName, @ascDesc + END + CLOSE c2 + DEALLOCATE c2 + SELECT @colName = '' + DECLARE c2 CURSOR FOR + SELECT '[' + c.name + ']' + FROM sys.index_columns ic + INNER JOIN sys.columns c + ON ic.object_id = c.object_id + AND c.column_id = ic.column_id + AND ic.is_included_column = 1 + WHERE ic.object_id = @objectId + AND ic.index_id = @indexId + ORDER BY ic.index_column_id + + OPEN c2 + FETCH c2 INTO @colName + SELECT @incList = @colName + FETCH c2 INTO @colName + WHILE @@FETCH_STATUS=0 + BEGIN + SELECT @incList = @incList + ',' + @colName + FETCH c2 INTO @colName + END + CLOSE c2 + DEALLOCATE c2 + --PRINT @indexName +' : ' + @colList + ' : '+@inclist + SELECT @cmd = 'CREATE ' + @indexType+ + +' INDEX [' + @indexName + '] ON ' + @targetTable + ' (' + @colList + ')' + + CASE + WHEN @incList = '' THEN '' + ELSE ' include (' + @incList + ')' + END + +' WITH (data_compression=' + @compressionDesc + ')' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + FETCH c1 INTO @indexName, @indexId, @indexType, @uniqueness + END + CLOSE c1 +DEALLOCATE c1 + +----Create foreign keys + + DECLARE @refColName nvarchar(max) + DECLARE @refColList nvarchar(max) + DECLARE @refTable nvarchar(100) + DECLARE @onDelete nvarchar(50) + DECLARE @onUpdate nvarchar(50) + + DECLARE c1 CURSOR FOR + SELECT name, delete_referential_action_desc, update_referential_action_desc + FROM sys.foreign_keys + WHERE parent_object_id = @objectId + OPEN c1 + FETCH c1 INTO @conName, @onDelete, @onUpdate + WHILE @@fetch_status = 0 + BEGIN + DECLARE c2 CURSOR FOR + SELECT pc.name, rc.name, '[' + schema_name(t.schema_id) + '].[' + t.name + ']' + FROM sys.foreign_key_columns fkc + INNER JOIN sys.foreign_keys fk + ON fkc.constraint_object_id = fk.object_id + INNER JOIN sys.columns pc + ON pc.column_id = fkc.parent_column_id + AND pc.object_id = @objectId + INNER JOIN sys.columns rc + ON rc.column_id = fkc.referenced_column_id + AND rc.object_id = fkc.referenced_object_id + INNER JOIN sys.tables t + ON t.object_id = fkc.referenced_object_id + WHERE fk.parent_object_id=@objectId + AND fk.name = @conName + ORDER BY fkc.constraint_column_id + + OPEN c2 + FETCH c2 INTO @colName, @refColName, @refTable + SELECT @colList = @colName + SELECT @refColList = @refColName + FETCH c2 INTO @colName, @refColName, @refTable + WHILE @@FETCH_STATUS = 0 + BEGIN + SELECT @colList = ',' + @colName + SELECT @refColList = ',' + @refColName + FETCH c2 INTO @colName,@refColName,@refTable + END + CLOSE c2 + DEALLOCATE c2 + SELECT @cmd = 'ALTER TABLE ' + @targetTable + ' ADD CONSTRAINT [' + @conName + '] FOREIGN KEY (' + @colList + ') REFERENCES ' + @refTable + '(' + @refColList + ') ' + + CASE + WHEN @onDelete != 'NO_ACTION' THEN 'on delete ' + @onDelete + ELSE '' + END + + CASE + WHEN @onUpdate != 'NO_ACTION' THEN 'on update ' + @onUpdate + ELSE '' + END + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + FETCH c1 INTO @conName, @onDelete, @onUpdate + END + CLOSE c1 +DEALLOCATE c1 + +-- Rename the primary key and drop foreign keys in the source table + + DECLARE c1 CURSOR FOR + SELECT name, type + FROM sys.key_constraints + WHERE parent_object_id = @objectId + UNION ALL + SELECT name,type + FROM sys.foreign_keys + WHERE parent_object_id = @objectId + OPEN c1 + FETCH c1 INTO @conName, @conType + WHILE @@FETCH_STATUS = 0 + BEGIN + IF @conType = 'F' + SELECT @cmd = 'ALTER TABLE [' + @sourceSchema + '].[' + @sourceTable + '] DROP CONSTRAINT [' + @conName + ']' + ELSE + SELECT @cmd = 'sp_rename ''' + @sourceSchema + '.' + @sourceTable + '.' + @conName + ''',' + '''' + @conName + '_' + @suffix + '''' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + FETCH c1 INTO @conName,@conType + END + CLOSE c1 +DEALLOCATE c1 + +-- Create CopyDataBAK schema + + IF NOT EXISTS (SELECT 1 FROM sys.schemas WHERE name = 'CopyDataBAK') + BEGIN + SELECT @cmd = 'CREATE SCHEMA CopyDataBAK' + PRINT @cmd + IF @debug = 0 + EXEC ('CREATE SCHEMA CopyDataBAK') + END + +-- Replace the source table with the target table. Move the source table to the bak schema and append @suffix + + SELECT @cmd = 'sp_rename ''' + @sourceSchema + '.' + @sourceTable + '''' + ',''' + @sourceTable + '_' + @suffix + '''' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + SELECT @cmd = 'sp_rename ''' + REPLACE(REPLACE(@targetTable,'[',''),']','') + ''',''' + @sourceTable + '''' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + SELECT @cmd = 'ALTER SCHEMA [' + @sourceSchema + '] TRANSFER [data].[' + @sourceTable + ']' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + SELECT @cmd = 'ALTER SCHEMA [CopyDataBAK] TRANSFER [' + @sourceSchema + '].[' + @sourceTable + '_' + @suffix + ']' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) +GO + + +--------------------------------------------- + +-- dbo.GetScoreDataTableColumnValidationResults +CREATE PROCEDURE dbo.GetScoreDataTableColumnValidationResults +( + @SchemaList VARCHAR(MAX),-- = 'clientdss,dss' + @IgnoreColumnList VARCHAR(MAX)-- = 'TransactionID,RowID,Version' +) +AS +BEGIN + + SELECT s.name AS [Schema] + ,t.name AS [Table] + ,c.COLUMN_NAME AS [Column] + ,CONVERT(BIT, CASE WHEN c.IS_NULLABLE = 'YES' THEN 1 ELSE 0 END) AS Nullable + ,CONVERT(BIT, CASE WHEN c.COLUMN_DEFAULT IS NULL THEN 1 ELSE 0 END) AS HasDefault + FROM sys.tables t + INNER JOIN sys.schemas s ON s.schema_id = t.schema_id + INNER JOIN INFORMATION_SCHEMA.COLUMNS c ON c.TABLE_NAME = t.name AND c.TABLE_SCHEMA = s.name + INNER JOIN [dbo].[ConvertCSValuesToTable](@SchemaList, ',') schemasToCheck ON schemasToCheck.val = s.name + INNER JOIN dbo.ScoreDataTable dt ON dt.SQLObjectName = t.name AND dt.SQLSchemaName = s.name + LEFT JOIN [dbo].[ConvertCSValuesToTable](@IgnoreColumnList, ',') ignore ON ignore.val = c.COLUMN_NAME + WHERE (c.IS_NULLABLE = 'YES' OR c.COLUMN_DEFAULT IS NULL) + AND ignore.pos IS NULL +END +GO + + +--------------------------------------------- + +-- dbo.GetScoreViewValidationResults +CREATE PROCEDURE dbo.GetScoreViewValidationResults +( + @SchemaList VARCHAR(MAX)-- = 'clientdss,dss' +) +AS +BEGIN + DECLARE @checkSchema NVARCHAR(500) + DECLARE @checkObject NVARCHAR(500) + DECLARE @checkColumn NVARCHAR(500) + DECLARE @checkSQL NVARCHAR(500) + DECLARE @DimensionName NVARCHAR(500) + DECLARE @devnull INT + + DECLARE @ErrorLog TABLE ( + Dimension NVARCHAR(500) + ,Error NVARCHAR(500) + ,[Table] NVARCHAR(500) + ,[Column] NVARCHAR(500) + ,[Schema] VARCHAR(MAX) + ) + + DECLARE c_schemacheck CURSOR FAST_FORWARD FOR + + SELECT + sd.FriendlyName + ,sd.SQLSchemaName + ,sd.SQLObjectName + ,sa.SQLColumnName + FROM + ScoreDimension sd + INNER JOIN ScoreDimensionGroup sdg ON sd.DimensionGUID=sdg.DimensionGUID + INNER JOIN ScoreAttribute sa ON sdg.DimensionGroupGUID=sa.DimensionGroupGUID + INNER JOIN [dbo].[ConvertCSValuesToTable](@SchemaList, ',') schemasToCheck ON schemasToCheck.val = sd.SQLSchemaName + ORDER BY + sd.FriendlyName + ,sd.SQLSchemaName + ,sd.SQLObjectName + ,sa.SQLColumnName + ; + + OPEN c_schemacheck; + + FETCH NEXT FROM c_schemacheck INTO @DimensionName, @checkSchema, @checkObject, @checkColumn + + WHILE @@FETCH_STATUS=0 + BEGIN + --SET @checkSQL='DECLARE @devnull INT; SELECT TOP 1 @devnull=COUNT([' + @checkColumn + ']) FROM [' + @checkSchema + '].[' + @checkObject + '] OPTION(FAST 1)' + SET @checkSQL='DECLARE @devnull INT; SELECT TOP 0 @devnull=COUNT([' + @checkColumn + ']) FROM [' + @checkSchema + '].[' + @checkObject + '] (READUNCOMMITTED)' + --PRINT @checkSQL + + BEGIN TRY + exec sp_executesql @checkSQL + END TRY + BEGIN CATCH + INSERT INTO @ErrorLog (Dimension,Error,[Table],[Column],[Schema]) VALUES (@DimensionName,ERROR_MESSAGE(),@checkObject,@checkColumn, @checkSchema) + --PRINT ERROR_MESSAGE() + ' SELECT [' + @checkColumn + '] FROM [' + @checkSchema + '].[' + @checkObject + ']' + END CATCH + + + FETCH NEXT FROM c_schemacheck INTO @DimensionName, @checkSchema, @checkObject, @checkColumn + END + + CLOSE c_schemacheck; + DEALLOCATE c_schemacheck; + + SELECT + Dimension + ,Error + ,[Table] + ,[Column] + ,[Schema] + FROM @ErrorLog + +END +GO + + +--------------------------------------------- + +-- dbo.IdentityCompression +CREATE PROCEDURE [dbo].[IdentityCompression] (@sourceSchema nvarchar(100), @sourceTable nvarchar(200), @debug bit=0) + AS + SET NOCOUNT ON + + declare @checkCmd nvarchar(1000) + declare @resultsTable table (TableIsVetted int) + select @checkCmd='if exists (select 1 from ['+setting+'].SQLAdministration.dbo.IdentityCompressionVetted where SchemaName='''+ + @sourceSchema + ''' and TableName='''+@sourceTable+''') select 1 else select 0' from dbsetting where name='SMC_PRIMARY_SERVER' + + begin try + insert @resultsTable exec (@checkCmd) + end try + begin catch + print 'Could not locate SQLAdministration.dbo.IdentityCompressionVetted on SMC_PRIMARY_SERVER' + end catch + + if not exists (select 1 from @resultsTable where TableIsVetted=1) + begin + PRINT 'Table '+@sourceSchema+'.'+@sourceTable+ ' is not vetted for use with this stored procedure.' + RETURN 0 + end + + /* + IF NOT EXISTS (SELECT 1 FROM IdentityCompressionVetted WHERE SchemaName=@sourceSchema and TableName=@sourceTable) + BEGIN + PRINT 'Table '+@sourceSchema+'.'+@sourceTable+ ' is not vetted for use with this stored procedure.' + RETURN 0 + END + */ + + DECLARE @runTime datetime=getdate() + DECLARE @cmd nvarchar(max) + DECLARE @targetTable nvarchar(200) + DECLARE @objectId int + DECLARE @name nvarchar(100) + DECLARE @definition nvarchar(4000) + DECLARE @colName nvarchar(100) + DECLARE @conName nvarchar(100) + DECLARE @compressionDesc nvarchar(20) + DECLARE @indexId int + DECLARE @conType nvarchar(5) + DECLARE @indexType nvarchar(50) + DECLARE @uniqueness nvarchar(50) + DECLARE @indexName nvarchar(100) + DECLARE @suffix nvarchar(50) + DECLARE @mergedSource nvarchar(100) + DECLARE @fullSourceName sysname + + +----create suffix in the format of _YYYYMMDD for backup table + SELECT @fullSourceName=@sourceSchema+'.'+@sourceTable + SELECT @suffix=REPLACE(convert(nvarchar,GETDATE(),102),'.','')+'_'+REPLACE(LEFT(CONVERT(varchar,CONVERT(time,GETDATE(),8)),8),':','') + SELECT @objectId=object_id FROM sys.objects WHERE schema_id=schema_id(@sourceSchema) AND name=@sourceTable + SELECT @targetTable='data.['+@sourceTable+'_'+REPLACE(CONVERT(nvarchar(max),NEWID()),'-','_')+']' + SELECT @mergedSource='['+@sourceSchema+'].['+@sourceTable+']' + +/* Create table Compress table (if required) Create default constraints */ +-- create the new target table + + INSERT IdentityCompressionLog select @runTime,@sourceSchema,@sourceTable,1 + + IF EXISTS (SELECT 1 FROM sys.columns WHERE object_id=@objectId AND is_computed=1) + BEGIN + DECLARE @def nvarchar(max) + DECLARE c1 CURSOR FOR + SELECT '['+c.name+']' + + CASE + WHEN c.is_computed=0 THEN ' ['+t.name+']' + + CASE + WHEN c.is_identity=1 THEN ' identity('+CONVERT(varchar,ident_seed(@mergedSource)) +','+CONVERT(varchar,ident_incr(@mergedSource))+')' + ELSE '' + END + + CASE + WHEN t.name LIKE 'n%char' AND c.max_length = -1 THEN '(max)' + WHEN t.name LIKE 'n%char' THEN ' ('+CONVERT(varchar,c.max_length/2)+')' + WHEN t.name LIKE '%char%' THEN ' ('+CONVERT(varchar,c.max_length)+')' + WHEN t.name IN ('numeric','decimal') THEN '('+CONVERT(varchar,c.precision)+','+CONVERT(varchar,c.scale)+')' + ELSE '' + END + + CASE + WHEN c.is_nullable=1 THEN ' NULL' + ELSE ' NOT NULL' + END + ELSE ' as ' + + cc.definition + END + FROM sys.columns c + INNER JOIN sys.types t + ON t.system_type_id = c.system_type_id + AND t.user_type_id = c.user_type_id + + LEFT JOIN sys.computed_columns cc + ON cc.object_id = c.object_id + AND cc.name = c.name + WHERE c.object_id = @objectId + ORDER BY c.column_id + + OPEN c1 + FETCH c1 INTO @def + SELECT @cmd = 'create table ' + @targetTable + '(' + @def + FETCH c1 INTO @def + WHILE @@FETCH_STATUS = 0 + BEGIN + SELECT @cmd = @cmd + ',' + @def + FETCH c1 INTO @def + END + SELECT @cmd = @cmd + ')' + CLOSE c1 + DEALLOCATE c1 + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + END + ELSE + BEGIN + SELECT @cmd='SELECT * INTO '+@targetTable+' FROM ['+@sourceSchema+'].['+@sourceTable +'] WHERE 1=2' + PRINT @cmd + IF @debug=0 + EXEC (@cmd) + END + +-- select the compression type of the table + UPDATE IdentityCompressionLog SET status=2 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable + + SELECT TOP 1 @compressionDesc = [data_compression_desc] + FROM sys.partitions + WHERE object_id=@objectId + SELECT @cmd = 'ALTER TABLE ' + @targetTable + ' rebuild partition = all with (data_compression = ' + @compressionDesc + ')' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + +--duplicate defaults for the target table from the source + UPDATE IdentityCompressionLog SET status=3 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable + DECLARE c1 CURSOR FOR + SELECT con.name, con.definition, col.name + FROM sys.default_constraints con + INNER JOIN sys.columns col + ON con.parent_column_id = col.column_id + AND col.object_id = con.parent_object_id + WHERE con.parent_object_id = @objectId + AND con.type = 'D' + OPEN c1 + FETCH c1 INTO @name, @definition, @colName + WHILE @@FETCH_STATUS=0 + BEGIN + SELECT @cmd = 'SP_RENAME '''+@sourceSchema+'.'+@name+''','''+@name+'_'+@suffix+'''' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + SELECT @cmd = 'ALTER TABLE '+@targetTable+' ADD CONSTRAINT ['+@name+'] DEFAULT '+@definition+' FOR ['+@colName+']' + BEGIN TRY + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + END TRY + BEGIN CATCH + PRINT 'Error: ' + @cmd + END CATCH + FETCH c1 INTO @name, @definition, @colName + END + CLOSE c1 +DEALLOCATE c1 + +--Check if source table has an identity column + UPDATE IdentityCompressionLog SET status=4 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable + DECLARE @isIdentity bit + DECLARE @colList nvarchar(max) + DECLARE @srcList nvarchar(max) + IF EXISTS (SELECT 1 FROM sys.columns WHERE object_id = @objectId AND is_identity = 1) + SELECT @isIdentity=1 + ELSE + SELECT @isIdentity = 0 + +--Create list of columns in the source/target tables. Omit timestamp columns and identity column + UPDATE IdentityCompressionLog SET status=5 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable + DECLARE c2 CURSOR FOR + SELECT DISTINCT '['+c.name+']' + FROM sys.columns c + LEFT JOIN sys.systypes t + ON t.xtype = c.system_type_id + WHERE c.object_id=@objectId + AND t.name != 'timestamp' + AND c.is_computed=0 + AND c.is_identity=0 + ORDER BY '['+c.name+']' + OPEN c2 + FETCH c2 INTO @colName + SELECT @colList = @colName + SELECT @srcList = 'src.' + @colName + FETCH c2 INTO @colName + WHILE @@FETCH_STATUS = 0 + BEGIN + SELECT @colList=@colList+','+@colName + SELECT @srcList=@srcList+',src.'+@colName + FETCH c2 INTO @colName + END + CLOSE c2 +DEALLOCATE c2 + +---- PRINT @colList +--Populate the target table. + UPDATE IdentityCompressionLog SET status=6 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable + + SELECT @cmd = 'INSERT ' + @targetTable + ' WITH (tablock) (' + @colList + ') SELECT ' + @colList + ' FROM [' + @sourceSchema + '].[' + @sourceTable + '] src ;' + + PRINT @cmd + IF @debug=0 + EXEC (@cmd) + +--Replicate the primary and unique keys for the target table + UPDATE IdentityCompressionLog SET status=7 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable + DECLARE c1 CURSOR FOR + SELECT c.name, c.unique_index_id, c.type, i.type_desc + FROM sys.key_constraints c + INNER JOIN sys.indexes i + ON i.object_id = c.parent_object_id + AND i.index_id=c.unique_index_id + WHERE c.type IN ('PK','UQ') + AND c.parent_object_id=@objectId + OPEN c1 + FETCH c1 INTO @conName, @indexId, @conType, @indexType + WHILE @@FETCH_STATUS=0 + BEGIN + PRINT @conName +' ' + convert(varchar,@indexId)+' '+@conType + DECLARE c2 CURSOR FOR + SELECT '[' + c.name + ']' + FROM sys.index_columns ic + INNER JOIN sys.columns c + ON ic.object_id = c.object_id + AND c.column_id=ic.column_id + AND ic.is_included_column=0 + WHERE ic.object_id = @objectId + AND ic.index_id = @indexId + --ORDER BY ic.index_column_id + ORDER BY ic.key_ordinal + OPEN c2 + --SELECT @objectId,@indexId + FETCH c2 INTO @colName + PRINT @colName + SELECT @colList = @colName + FETCH c2 INTO @colName + WHILE @@FETCH_STATUS = 0 + BEGIN + SELECT @colList = @colList + ',' + @colName + FETCH c2 INTO @colName + END + CLOSE c2 + DEALLOCATE c2 + IF @conType='PK' + SELECT @cmd='alter table '+@targetTable+' add constraint '+@conName+' primary key '+@indexType+' ('+@colList+') with (data_compression='+@compressionDesc+')' + IF @conType='UQ' + SELECT @cmd='alter table '+@targetTable+' add constraint '+@conName+' unique '+@indexType+' ('+@colList+') with (data_compression='+@compressionDesc+')' + PRINT @cmd + IF @debug=0 + EXEC (@cmd) + FETCH c1 INTO @conName,@indexId,@conType,@indexType + END + CLOSE c1 +DEALLOCATE c1 + +--Create check constraints + UPDATE IdentityCompressionLog SET status=8 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable + DECLARE c1 CURSOR FOR + SELECT [name],[definition] + FROM sys.check_constraints + WHERE parent_object_id = @objectId + OPEN c1 + FETCH c1 INTO @conName,@definition + WHILE @@FETCH_STATUS = 0 + BEGIN + SELECT @cmd = 'ALTER TABLE ' + @targetTable + ' ADD CONSTRAINT ' + @conName + ' check ' + @definition + IF @debug = 0 + EXEC (@cmd) + FETCH c1 INTO @conName, @definition + END + CLOSE c1 +DEALLOCATE c1 + +----Create indexes + UPDATE IdentityCompressionLog SET status=9 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable + DECLARE @incList nvarchar(max) + DECLARE @incName nvarchar(100) + DECLARE @ascDesc nvarchar(10) + DECLARE c1 CURSOR FOR + SELECT name, index_id, type_desc, + CASE + WHEN is_unique=1 THEN 'UNIQUE' + ELSE '' + END + FROM sys.indexes i + WHERE i.object_id = @ObjectId + AND NOT EXISTS + (SELECT 1 + FROM sys.key_constraints kc + WHERE kc.parent_object_id = i.object_id + AND i.index_id = kc.unique_index_id) + + OPEN c1 + FETCH c1 INTO @indexName, @indexId, @indexType, @uniqueness + WHILE @@FETCH_STATUS = 0 + BEGIN + DECLARE c2 CURSOR FOR + SELECT '[' + c.name + ']' , + CASE + WHEN ic.is_descending_key = 1 THEN 'DESC' + ELSE 'ASC' + END + FROM sys.index_columns ic + INNER JOIN sys.columns c + ON ic.object_id = c.object_id + AND c.column_id = ic.column_id + AND ic.is_included_column = 0 + WHERE ic.object_id = @objectId + AND ic.index_id = @indexId + --ORDER BY ic.index_column_id + ORDER BY ic.key_ordinal + + OPEN c2 + FETCH c2 INTO @colName,@ascDesc + SELECT @colList = @colName + ' ' + @ascDesc + FETCH c2 INTO @colName, @ascDesc + WHILE @@FETCH_STATUS=0 + BEGIN + SELECT @colList = @colList + ',' + @colName + ' ' + @ascDesc + FETCH c2 INTO @colName, @ascDesc + END + CLOSE c2 + DEALLOCATE c2 + SELECT @colName = '' + DECLARE c2 CURSOR FOR + SELECT '[' + c.name + ']' + FROM sys.index_columns ic + INNER JOIN sys.columns c + ON ic.object_id = c.object_id + AND c.column_id = ic.column_id + AND ic.is_included_column = 1 + WHERE ic.object_id = @objectId + AND ic.index_id = @indexId + --ORDER BY ic.index_column_id + ORDER BY ic.key_ordinal + + OPEN c2 + FETCH c2 INTO @colName + SELECT @incList = @colName + FETCH c2 INTO @colName + WHILE @@FETCH_STATUS=0 + BEGIN + SELECT @incList = @incList + ',' + @colName + FETCH c2 INTO @colName + END + CLOSE c2 + DEALLOCATE c2 + PRINT @indexName +' : ' + @colList + ' : '+@inclist + SELECT @cmd = 'CREATE ' + @uniqueness + ' ' + @indexType+ + +' INDEX [' + @indexName + '] ON ' + @targetTable + ' (' + @colList + ')' + + CASE + WHEN @incList = '' THEN '' + ELSE ' include (' + @incList + ')' + END + +' WITH (data_compression=' + @compressionDesc + ')' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + FETCH c1 INTO @indexName, @indexId, @indexType, @uniqueness + END + CLOSE c1 +DEALLOCATE c1 + +----Create foreign keys + UPDATE IdentityCompressionLog SET status=10 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable + DECLARE @refColName nvarchar(max) + DECLARE @refColList nvarchar(max) + DECLARE @refTable nvarchar(100) + DECLARE @onDelete nvarchar(50) + DECLARE @onUpdate nvarchar(50) + + DECLARE c1 CURSOR FOR + SELECT name, delete_referential_action_desc, update_referential_action_desc + FROM sys.foreign_keys + WHERE parent_object_id = @objectId + OPEN c1 + FETCH c1 INTO @conName, @onDelete, @onUpdate + WHILE @@fetch_status = 0 + BEGIN + DECLARE c2 CURSOR FOR + SELECT pc.name, rc.name, '[' + schema_name(t.schema_id) + '].[' + t.name + ']' + FROM sys.foreign_key_columns fkc + INNER JOIN sys.foreign_keys fk + ON fkc.constraint_object_id = fk.object_id + INNER JOIN sys.columns pc + ON pc.column_id = fkc.parent_column_id + AND pc.object_id = @objectId + INNER JOIN sys.columns rc + ON rc.column_id = fkc.referenced_column_id + AND rc.object_id = fkc.referenced_object_id + INNER JOIN sys.tables t + ON t.object_id = fkc.referenced_object_id + WHERE fk.parent_object_id=@objectId + AND fk.name = @conName + ORDER BY fkc.constraint_column_id + + OPEN c2 + FETCH c2 INTO @colName, @refColName, @refTable + SELECT @colList = @colName + SELECT @refColList = @refColName + FETCH c2 INTO @colName, @refColName, @refTable + WHILE @@FETCH_STATUS = 0 + BEGIN + SELECT @colList = ',' + @colName + SELECT @refColList = ',' + @refColName + FETCH c2 INTO @colName,@refColName,@refTable + END + CLOSE c2 + DEALLOCATE c2 + SELECT @cmd = 'ALTER TABLE ' + @targetTable + ' ADD CONSTRAINT [' + @conName + '] FOREIGN KEY (' + @colList + ') REFERENCES ' + @refTable + '(' + @refColList + ') ' + + CASE + WHEN @onDelete != 'NO_ACTION' THEN 'on delete ' + @onDelete + ELSE '' + END + + CASE + WHEN @onUpdate != 'NO_ACTION' THEN 'on update ' + @onUpdate + ELSE '' + END + PRINT @cmd + IF @debug=0 + EXEC (@cmd) + FETCH c1 INTO @conName, @onDelete, @onUpdate + END + CLOSE c1 +DEALLOCATE c1 + +-- Rename the primary key and drop foreign keys in the source table +UPDATE IdentityCompressionLog SET status=11 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable + DECLARE c1 CURSOR FOR + SELECT name, type + FROM sys.key_constraints + WHERE parent_object_id = @objectId + UNION ALL + SELECT name,type + FROM sys.foreign_keys + WHERE parent_object_id = @objectId + OPEN c1 + FETCH c1 INTO @conName, @conType + WHILE @@FETCH_STATUS = 0 + BEGIN + IF @conType = 'F' + SELECT @cmd = 'ALTER TABLE [' + @sourceSchema + '].[' + @sourceTable + '] DROP CONSTRAINT [' + @conName + ']' + ELSE + SELECT @cmd = 'sp_rename ''' + @sourceSchema + '.' + @sourceTable + '.' + @conName + ''',' + '''' + @conName + '_' + @suffix + '''' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + FETCH c1 INTO @conName,@conType + END + CLOSE c1 +DEALLOCATE c1 + +-- Turn on change tracking if required +UPDATE IdentityCompressionLog SET status=12 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable + IF EXISTS (SELECT 1 FROM sys.change_tracking_tables WHERE OBJECT_ID=@objectId) + BEGIN + SELECT @cmd='ALTER TABLE '+@targetTable+' enable Change_tracking' + exec (@cmd) + END + + + + +-- Replace the source table with the target table. Move the source table to the bak schema and append @suffix +UPDATE IdentityCompressionLog SET status=13 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable + SELECT @cmd = 'sp_rename ''' + @sourceSchema + '.' + @sourceTable + '''' + ',''' + @sourceTable + '_' + @suffix + '''' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + SELECT @cmd = 'sp_rename ''' + REPLACE(REPLACE(@targetTable,'[',''),']','') + ''',''' + @sourceTable + '''' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + SELECT @cmd = 'ALTER SCHEMA [' + @sourceSchema + '] TRANSFER [data].[' + @sourceTable + ']' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + SELECT @cmd = 'ALTER SCHEMA [BAK] TRANSFER [' + @sourceSchema + '].[' + @sourceTable + '_' + @suffix + ']' + PRINT @cmd + IF @debug = 0 + EXEC (@cmd) + +--Update replication table if required + UPDATE IdentityCompressionLog SET status=14 WHERE runtime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable + IF EXISTS (SELECT 1 FROM dbo.ReplicationTable WHERE TableName=@fullSourceName) + BEGIN + UPDATE dbo.ReplicationTable set LastRefreshChangeTrackingVersion = null + WHERE TableName = @fullSourceName + END + +UPDATE IdentityCompressionLog SET status=0 WHERE runTime=@runTime and schemaName=@sourceSchema and tableName=@sourceTable +GO + + +--------------------------------------------- + +-- dbo.IntAddSimpleSecurityForActions +create proc dbo.IntAddSimpleSecurityForActions +AS +BEGIN + declare @everyone uniqueidentifier = '00000000-0000-0000-0000-000000000001'; + declare @count int; + select @count = COUNT(PermissionGuid) from S3SimplePermission P where P.LootID = '18F307C3-C344-424F-A38E-1F7ABCD295A5' and P.IdentityGUID = @everyone; + if (@count = 0) begin + insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) + VALUES ('18F307C3-C344-424F-A38E-1F7ABCD295A5', @everyone, 1,1,1); + end + set @count = 0; + select @count = COUNT(PermissionGuid) from S3SimplePermission P where P.LootID = '38CF0A6C-FBA8-44F9-A707-B8BAA2234EEB' and P.IdentityGUID = @everyone; + if (@count = 0) begin + insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) + VALUES ('38CF0A6C-FBA8-44F9-A707-B8BAA2234EEB', @everyone, 1,1,1); + end + set @count = 0; + select @count = COUNT(PermissionGuid) from S3SimplePermission P where P.LootID = 'BA71645B-30B9-4ED1-A43B-89EFC06931B9' and P.IdentityGUID = @everyone; + if (@count = 0) begin + insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) + VALUES ('BA71645B-30B9-4ED1-A43B-89EFC06931B9', @everyone, 1,1,1); + end + set @count = 0; + select @count = COUNT(PermissionGuid) from S3SimplePermission P where P.LootID = '74DAD74D-3F8C-4C31-A5FD-972EC0868A50' and P.IdentityGUID = @everyone; + if (@count = 0) begin + insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) + VALUES ('74DAD74D-3F8C-4C31-A5FD-972EC0868A50', @everyone, 1,1,1); + end +END +GO + + +--------------------------------------------- + +-- dbo.dt_addtosourcecontrol +create proc dbo.dt_addtosourcecontrol + @vchSourceSafeINI varchar(255) = '', + @vchProjectName varchar(255) ='', + @vchComment varchar(255) ='', + @vchLoginName varchar(255) ='', + @vchPassword varchar(255) ='' + +as + +set nocount on + +declare @iReturn int +declare @iObjectId int +select @iObjectId = 0 + +declare @iStreamObjectId int +select @iStreamObjectId = 0 + +declare @VSSGUID varchar(100) +select @VSSGUID = 'SQLVersionControl.VCS_SQL' + +declare @vchDatabaseName varchar(255) +select @vchDatabaseName = db_name() + +declare @iReturnValue int +select @iReturnValue = 0 + +declare @iPropertyObjectId int +declare @vchParentId varchar(255) + +declare @iObjectCount int +select @iObjectCount = 0 + + exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT + if @iReturn <> 0 GOTO E_OAError + + + /* Create Project in SS */ + exec @iReturn = sp_OAMethod @iObjectId, + 'AddProjectToSourceSafe', + NULL, + @vchSourceSafeINI, + @vchProjectName output, + @@SERVERNAME, + @vchDatabaseName, + @vchLoginName, + @vchPassword, + @vchComment + + + if @iReturn <> 0 GOTO E_OAError + + exec @iReturn = sp_OAGetProperty @iObjectId, 'GetStreamObject', @iStreamObjectId OUT + + if @iReturn <> 0 GOTO E_OAError + + /* Set Database Properties */ + + begin tran SetProperties + + /* add high level object */ + + exec @iPropertyObjectId = dbo.dt_adduserobject_vcs 'VCSProjectID' + + select @vchParentId = CONVERT(varchar(255),@iPropertyObjectId) + + exec dbo.dt_setpropertybyid @iPropertyObjectId, 'VCSProjectID', @vchParentId , NULL + exec dbo.dt_setpropertybyid @iPropertyObjectId, 'VCSProject' , @vchProjectName , NULL + exec dbo.dt_setpropertybyid @iPropertyObjectId, 'VCSSourceSafeINI' , @vchSourceSafeINI , NULL + exec dbo.dt_setpropertybyid @iPropertyObjectId, 'VCSSQLServer', @@SERVERNAME, NULL + exec dbo.dt_setpropertybyid @iPropertyObjectId, 'VCSSQLDatabase', @vchDatabaseName, NULL + + if @@error <> 0 GOTO E_General_Error + + commit tran SetProperties + + declare cursorProcNames cursor for + select convert(varchar(255), name) from sysobjects where type = 'P' and name not like 'dt_%' + open cursorProcNames + + while 1 = 1 + begin + declare @vchProcName varchar(255) + fetch next from cursorProcNames into @vchProcName + if @@fetch_status <> 0 + break + + select colid, text into #ProcLines + from syscomments + where id = object_id(@vchProcName) + order by colid + + declare @iCurProcLine int + declare @iProcLines int + select @iCurProcLine = 1 + select @iProcLines = (select count(*) from #ProcLines) + while @iCurProcLine <= @iProcLines + begin + declare @pos int + select @pos = 1 + declare @iCurLineSize int + select @iCurLineSize = len((select text from #ProcLines where colid = @iCurProcLine)) + while @pos <= @iCurLineSize + begin + declare @vchProcLinePiece varchar(255) + select @vchProcLinePiece = convert(varchar(255), + substring((select text from #ProcLines where colid = @iCurProcLine), + @pos, 255 )) + exec @iReturn = sp_OAMethod @iStreamObjectId, 'AddStream', @iReturnValue OUT, @vchProcLinePiece + if @iReturn <> 0 GOTO E_OAError + select @pos = @pos + 255 + end + select @iCurProcLine = @iCurProcLine + 1 + end + drop table #ProcLines + + exec @iReturn = sp_OAMethod @iObjectId, + 'CheckIn_StoredProcedure', + NULL, + @sProjectName = @vchProjectName, + @sSourceSafeINI = @vchSourceSafeINI, + @sServerName = @@SERVERNAME, + @sDatabaseName = @vchDatabaseName, + @sObjectName = @vchProcName, + @sComment = @vchComment, + @sLoginName = @vchLoginName, + @sPassword = @vchPassword, + @iVCSFlags = 0, + @iActionFlag = 0, + @sStream = '' + + if @iReturn = 0 select @iObjectCount = @iObjectCount + 1 + + end + +CleanUp: + close cursorProcNames + deallocate cursorProcNames + select @vchProjectName + select @iObjectCount + return + +E_General_Error: + /* this is an all or nothing. No specific error messages */ + goto CleanUp + +E_OAError: + exec dbo.dt_displayoaerror @iObjectId, @iReturn + goto CleanUp +GO + + +--------------------------------------------- + +-- dbo.dt_addtosourcecontrol_u +create proc dbo.dt_addtosourcecontrol_u + @vchSourceSafeINI nvarchar(255) = '', + @vchProjectName nvarchar(255) ='', + @vchComment nvarchar(255) ='', + @vchLoginName nvarchar(255) ='', + @vchPassword nvarchar(255) ='' + +as + +set nocount on + +declare @iReturn int +declare @iObjectId int +select @iObjectId = 0 + +declare @iStreamObjectId int +select @iStreamObjectId = 0 + +declare @VSSGUID nvarchar(100) +select @VSSGUID = N'SQLVersionControl.VCS_SQL' + +declare @vchDatabaseName varchar(255) +select @vchDatabaseName = db_name() + +declare @iReturnValue int +select @iReturnValue = 0 + +declare @iPropertyObjectId int +declare @vchParentId nvarchar(255) + +declare @iObjectCount int +select @iObjectCount = 0 + + exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT + if @iReturn <> 0 GOTO E_OAError + + + /* Create Project in SS */ + exec @iReturn = sp_OAMethod @iObjectId, + 'AddProjectToSourceSafe', + NULL, + @vchSourceSafeINI, + @vchProjectName output, + @@SERVERNAME, + @vchDatabaseName, + @vchLoginName, + @vchPassword, + @vchComment + + + if @iReturn <> 0 GOTO E_OAError + + exec @iReturn = sp_OAGetProperty @iObjectId, N'GetStreamObject', @iStreamObjectId OUT + + if @iReturn <> 0 GOTO E_OAError + + /* Set Database Properties */ + + begin tran SetProperties + + /* add high level object */ + + exec @iPropertyObjectId = dbo.dt_adduserobject_vcs 'VCSProjectID' + + select @vchParentId = CONVERT(nvarchar(255),@iPropertyObjectId) + + exec dbo.dt_setpropertybyid_u @iPropertyObjectId, 'VCSProjectID', @vchParentId , NULL + exec dbo.dt_setpropertybyid_u @iPropertyObjectId, 'VCSProject' , @vchProjectName , NULL + exec dbo.dt_setpropertybyid_u @iPropertyObjectId, 'VCSSourceSafeINI' , @vchSourceSafeINI , NULL + exec dbo.dt_setpropertybyid_u @iPropertyObjectId, 'VCSSQLServer', @@SERVERNAME, NULL + exec dbo.dt_setpropertybyid_u @iPropertyObjectId, 'VCSSQLDatabase', @vchDatabaseName, NULL + + if @@error <> 0 GOTO E_General_Error + + commit tran SetProperties + + declare cursorProcNames cursor for + select convert(nvarchar(255), name) from sysobjects where type = N'P' and name not like N'dt_%' + open cursorProcNames + + while 1 = 1 + begin + declare @vchProcName nvarchar(255) + fetch next from cursorProcNames into @vchProcName + if @@fetch_status <> 0 + break + + select colid, text into #ProcLines + from syscomments + where id = object_id(@vchProcName) + order by colid + + declare @iCurProcLine int + declare @iProcLines int + select @iCurProcLine = 1 + select @iProcLines = (select count(*) from #ProcLines) + while @iCurProcLine <= @iProcLines + begin + declare @pos int + select @pos = 1 + declare @iCurLineSize int + select @iCurLineSize = len((select text from #ProcLines where colid = @iCurProcLine)) + while @pos <= @iCurLineSize + begin + declare @vchProcLinePiece nvarchar(255) + select @vchProcLinePiece = convert(nvarchar(255), + substring((select text from #ProcLines where colid = @iCurProcLine), + @pos, 255 )) + exec @iReturn = sp_OAMethod @iStreamObjectId, N'AddStream', @iReturnValue OUT, @vchProcLinePiece + if @iReturn <> 0 GOTO E_OAError + select @pos = @pos + 255 + end + select @iCurProcLine = @iCurProcLine + 1 + end + drop table #ProcLines + + exec @iReturn = sp_OAMethod @iObjectId, + 'CheckIn_StoredProcedure', + NULL, + @sProjectName = @vchProjectName, + @sSourceSafeINI = @vchSourceSafeINI, + @sServerName = @@SERVERNAME, + @sDatabaseName = @vchDatabaseName, + @sObjectName = @vchProcName, + @sComment = @vchComment, + @sLoginName = @vchLoginName, + @sPassword = @vchPassword, + @iVCSFlags = 0, + @iActionFlag = 0, + @sStream = '' + + if @iReturn = 0 select @iObjectCount = @iObjectCount + 1 + + end + +CleanUp: + close cursorProcNames + deallocate cursorProcNames + select @vchProjectName + select @iObjectCount + return + +E_General_Error: + /* this is an all or nothing. No specific error messages */ + goto CleanUp + +E_OAError: + exec dbo.dt_displayoaerror_u @iObjectId, @iReturn + goto CleanUp +GO + + +--------------------------------------------- + +-- dbo.dt_adduserobject +/* +** Add an object to the dtproperties table +*/ +create procedure dbo.dt_adduserobject +as + set nocount on + /* + ** Create the user object if it does not exist already + */ + begin transaction + insert dbo.dtproperties (property) VALUES ('DtgSchemaOBJECT') + update dbo.dtproperties set objectid=@@identity + where id=@@identity and property='DtgSchemaOBJECT' + commit + return @@identity +GO + + +--------------------------------------------- + +-- dbo.dt_adduserobject_vcs +create procedure dbo.dt_adduserobject_vcs + @vchProperty varchar(64) + +as + +set nocount on + +declare @iReturn int + /* + ** Create the user object if it does not exist already + */ + begin transaction + select @iReturn = objectid from dbo.dtproperties where property = @vchProperty + if @iReturn IS NULL + begin + insert dbo.dtproperties (property) VALUES (@vchProperty) + update dbo.dtproperties set objectid=@@identity + where id=@@identity and property=@vchProperty + select @iReturn = @@identity + end + commit + return @iReturn +GO + + +--------------------------------------------- + +-- dbo.dt_checkinobject +create proc dbo.dt_checkinobject + @chObjectType char(4), + @vchObjectName varchar(255), + @vchComment varchar(255)='', + @vchLoginName varchar(255), + @vchPassword varchar(255)='', + @iVCSFlags int = 0, + @iActionFlag int = 0, /* 0 => AddFile, 1 => CheckIn */ + @txStream1 Text = '', /* There is a bug that if items are NULL they do not pass to OLE servers */ + @txStream2 Text = '', + @txStream3 Text = '' + + +as + +set nocount on + +declare @iReturn int +declare @iObjectId int +select @iObjectId = 0 + +declare @VSSGUID varchar(100) +select @VSSGUID = 'SQLVersionControl.VCS_SQL' + + +declare @iPropertyObjectId int +select @iPropertyObjectId = 0 + + select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID') + + declare @vchProjectName varchar(255) + declare @vchSourceSafeINI varchar(255) + declare @vchServerName varchar(255) + declare @vchDatabaseName varchar(255) + exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSProject', @vchProjectName OUT + exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT + exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLServer', @vchServerName OUT + exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLDatabase', @vchDatabaseName OUT + + if @chObjectType = 'PROC' + begin + if @iActionFlag = 1 + begin + /* Procedure Can have up to three streams + Drop Stream, Create Stream, GRANT stream */ + + begin tran compile_all + + /* try to compile the streams */ + exec (@txStream1) + if @@error <> 0 GOTO E_Compile_Fail + + exec (@txStream2) + if @@error <> 0 GOTO E_Compile_Fail + + exec (@txStream3) + if @@error <> 0 GOTO E_Compile_Fail + end + + exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT + if @iReturn <> 0 GOTO E_OAError + + if @iActionFlag = 1 + begin + exec @iReturn = sp_OAMethod @iObjectId, + 'CheckIn_StoredProcedure', + NULL, + @sProjectName = @vchProjectName, + @sSourceSafeINI = @vchSourceSafeINI, + @sServerName = @vchServerName, + @sDatabaseName = @vchDatabaseName, + @sObjectName = @vchObjectName, + @sComment = @vchComment, + @sLoginName = @vchLoginName, + @sPassword = @vchPassword, + @iVCSFlags = @iVCSFlags, + @iActionFlag = @iActionFlag, + @sStream = @txStream2 + end + else + begin + declare @iStreamObjectId int + declare @iReturnValue int + + exec @iReturn = sp_OAGetProperty @iObjectId, 'GetStreamObject', @iStreamObjectId OUT + if @iReturn <> 0 GOTO E_OAError + + select colid, text into #ProcLines + from syscomments + where id = object_id(@vchObjectName) + order by colid + + declare @iCurProcLine int + declare @iProcLines int + select @iCurProcLine = 1 + select @iProcLines = (select count(*) from #ProcLines) + while @iCurProcLine <= @iProcLines + begin + declare @pos int + select @pos = 1 + declare @iCurLineSize int + select @iCurLineSize = len((select text from #ProcLines where colid = @iCurProcLine)) + while @pos <= @iCurLineSize + begin + declare @vchProcLinePiece varchar(255) + select @vchProcLinePiece = convert(varchar(255), + substring((select text from #ProcLines where colid = @iCurProcLine), + @pos, 255 )) + exec @iReturn = sp_OAMethod @iStreamObjectId, 'AddStream', @iReturnValue OUT, @vchProcLinePiece + if @iReturn <> 0 GOTO E_OAError + select @pos = @pos + 255 + end + select @iCurProcLine = @iCurProcLine + 1 + end + drop table #ProcLines + + exec @iReturn = sp_OAMethod @iObjectId, + 'CheckIn_StoredProcedure', + NULL, + @sProjectName = @vchProjectName, + @sSourceSafeINI = @vchSourceSafeINI, + @sServerName = @vchServerName, + @sDatabaseName = @vchDatabaseName, + @sObjectName = @vchObjectName, + @sComment = @vchComment, + @sLoginName = @vchLoginName, + @sPassword = @vchPassword, + @iVCSFlags = @iVCSFlags, + @iActionFlag = @iActionFlag, + @sStream = '' + end + + if @iReturn <> 0 GOTO E_OAError + + if @iActionFlag = 1 + begin + commit tran compile_all + if @@error <> 0 GOTO E_Compile_Fail + end + + end + +CleanUp: + return + +E_Compile_Fail: + declare @lerror int + select @lerror = @@error + rollback tran compile_all + RAISERROR (@lerror,16,-1) + goto CleanUp + +E_OAError: + if @iActionFlag = 1 rollback tran compile_all + exec dbo.dt_displayoaerror @iObjectId, @iReturn + goto CleanUp +GO + + +--------------------------------------------- + +-- dbo.dt_checkinobject_u +create proc dbo.dt_checkinobject_u + @chObjectType char(4), + @vchObjectName nvarchar(255), + @vchComment nvarchar(255)='', + @vchLoginName nvarchar(255), + @vchPassword nvarchar(255)='', + @iVCSFlags int = 0, + @iActionFlag int = 0, /* 0 => AddFile, 1 => CheckIn */ + @txStream1 Text = '', /* There is a bug that if items are NULL they do not pass to OLE servers */ + @txStream2 Text = '', + @txStream3 Text = '' + + +as + +set nocount on + +declare @iReturn int +declare @iObjectId int +select @iObjectId = 0 + +declare @VSSGUID nvarchar(100) +select @VSSGUID = N'SQLVersionControl.VCS_SQL' + + +declare @iPropertyObjectId int +select @iPropertyObjectId = 0 + + select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID') + + declare @vchProjectName nvarchar(255) + declare @vchSourceSafeINI nvarchar(255) + declare @vchServerName nvarchar(255) + declare @vchDatabaseName nvarchar(255) + exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSProject', @vchProjectName OUT + exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT + exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSQLServer', @vchServerName OUT + exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSQLDatabase', @vchDatabaseName OUT + + if @chObjectType = 'PROC' + begin + if @iActionFlag = 1 + begin + /* Procedure Can have up to three streams + Drop Stream, Create Stream, GRANT stream */ + + begin tran compile_all + + /* try to compile the streams */ + exec (@txStream1) + if @@error <> 0 GOTO E_Compile_Fail + + exec (@txStream2) + if @@error <> 0 GOTO E_Compile_Fail + + exec (@txStream3) + if @@error <> 0 GOTO E_Compile_Fail + end + + exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT + if @iReturn <> 0 GOTO E_OAError + + if @iActionFlag = 1 + begin + exec @iReturn = sp_OAMethod @iObjectId, + N'CheckIn_StoredProcedure', + NULL, + @sProjectName = @vchProjectName, + @sSourceSafeINI = @vchSourceSafeINI, + @sServerName = @vchServerName, + @sDatabaseName = @vchDatabaseName, + @sObjectName = @vchObjectName, + @sComment = @vchComment, + @sLoginName = @vchLoginName, + @sPassword = @vchPassword, + @iVCSFlags = @iVCSFlags, + @iActionFlag = @iActionFlag, + @sStream = @txStream2 + end + else + begin + declare @iStreamObjectId int + declare @iReturnValue int + + exec @iReturn = sp_OAGetProperty @iObjectId, N'GetStreamObject', @iStreamObjectId OUT + if @iReturn <> 0 GOTO E_OAError + + select colid, text into #ProcLines + from syscomments + where id = object_id(@vchObjectName) + order by colid + + declare @iCurProcLine int + declare @iProcLines int + select @iCurProcLine = 1 + select @iProcLines = (select count(*) from #ProcLines) + while @iCurProcLine <= @iProcLines + begin + declare @pos int + select @pos = 1 + declare @iCurLineSize int + select @iCurLineSize = len((select text from #ProcLines where colid = @iCurProcLine)) + while @pos <= @iCurLineSize + begin + declare @vchProcLinePiece nvarchar(255) + select @vchProcLinePiece = convert(nvarchar(255), + substring((select text from #ProcLines where colid = @iCurProcLine), + @pos, 255 )) + exec @iReturn = sp_OAMethod @iStreamObjectId, N'AddStream', @iReturnValue OUT, @vchProcLinePiece + if @iReturn <> 0 GOTO E_OAError + select @pos = @pos + 255 + end + select @iCurProcLine = @iCurProcLine + 1 + end + drop table #ProcLines + + exec @iReturn = sp_OAMethod @iObjectId, + N'CheckIn_StoredProcedure', + NULL, + @sProjectName = @vchProjectName, + @sSourceSafeINI = @vchSourceSafeINI, + @sServerName = @vchServerName, + @sDatabaseName = @vchDatabaseName, + @sObjectName = @vchObjectName, + @sComment = @vchComment, + @sLoginName = @vchLoginName, + @sPassword = @vchPassword, + @iVCSFlags = @iVCSFlags, + @iActionFlag = @iActionFlag, + @sStream = '' + end + + if @iReturn <> 0 GOTO E_OAError + + if @iActionFlag = 1 + begin + commit tran compile_all + if @@error <> 0 GOTO E_Compile_Fail + end + + end + +CleanUp: + return + +E_Compile_Fail: + declare @lerror int + select @lerror = @@error + rollback tran compile_all + RAISERROR (@lerror,16,-1) + goto CleanUp + +E_OAError: + if @iActionFlag = 1 rollback tran compile_all + exec dbo.dt_displayoaerror_u @iObjectId, @iReturn + goto CleanUp +GO + + +--------------------------------------------- + +-- dbo.dt_checkoutobject +create proc dbo.dt_checkoutobject + @chObjectType char(4), + @vchObjectName varchar(255), + @vchComment varchar(255), + @vchLoginName varchar(255), + @vchPassword varchar(255), + @iVCSFlags int = 0, + @iActionFlag int = 0/* 0 => Checkout, 1 => GetLatest, 2 => UndoCheckOut */ + +as + +set nocount on + +declare @iReturn int +declare @iObjectId int +select @iObjectId =0 + +declare @VSSGUID varchar(100) +select @VSSGUID = 'SQLVersionControl.VCS_SQL' + +declare @iReturnValue int +select @iReturnValue = 0 + +declare @vchTempText varchar(255) + +/* this is for our strings */ +declare @iStreamObjectId int +select @iStreamObjectId = 0 + + declare @iPropertyObjectId int + select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID') + + declare @vchProjectName varchar(255) + declare @vchSourceSafeINI varchar(255) + declare @vchServerName varchar(255) + declare @vchDatabaseName varchar(255) + exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSProject', @vchProjectName OUT + exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT + exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLServer', @vchServerName OUT + exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLDatabase', @vchDatabaseName OUT + + if @chObjectType = 'PROC' + begin + /* Procedure Can have up to three streams + Drop Stream, Create Stream, GRANT stream */ + + exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT + + if @iReturn <> 0 GOTO E_OAError + + exec @iReturn = sp_OAMethod @iObjectId, + 'CheckOut_StoredProcedure', + NULL, + @sProjectName = @vchProjectName, + @sSourceSafeINI = @vchSourceSafeINI, + @sObjectName = @vchObjectName, + @sServerName = @vchServerName, + @sDatabaseName = @vchDatabaseName, + @sComment = @vchComment, + @sLoginName = @vchLoginName, + @sPassword = @vchPassword, + @iVCSFlags = @iVCSFlags, + @iActionFlag = @iActionFlag + + if @iReturn <> 0 GOTO E_OAError + + + exec @iReturn = sp_OAGetProperty @iObjectId, 'GetStreamObject', @iStreamObjectId OUT + + if @iReturn <> 0 GOTO E_OAError + + create table #commenttext (id int identity, sourcecode varchar(255)) + + + select @vchTempText = 'STUB' + while @vchTempText IS NOT NULL + begin + exec @iReturn = sp_OAMethod @iStreamObjectId, 'GetStream', @iReturnValue OUT, @vchTempText OUT + if @iReturn <> 0 GOTO E_OAError + + if (@vchTempText IS NOT NULL) insert into #commenttext (sourcecode) select @vchTempText + end + + select 'VCS'=sourcecode from #commenttext order by id + select 'SQL'=text from syscomments where id = object_id(@vchObjectName) order by colid + + end + +CleanUp: + return + +E_OAError: + exec dbo.dt_displayoaerror @iObjectId, @iReturn + GOTO CleanUp +GO + + +--------------------------------------------- + +-- dbo.dt_checkoutobject_u +create proc dbo.dt_checkoutobject_u + @chObjectType char(4), + @vchObjectName nvarchar(255), + @vchComment nvarchar(255), + @vchLoginName nvarchar(255), + @vchPassword nvarchar(255), + @iVCSFlags int = 0, + @iActionFlag int = 0/* 0 => Checkout, 1 => GetLatest, 2 => UndoCheckOut */ + +as + +set nocount on + +declare @iReturn int +declare @iObjectId int +select @iObjectId =0 + +declare @VSSGUID nvarchar(100) +select @VSSGUID = N'SQLVersionControl.VCS_SQL' + +declare @iReturnValue int +select @iReturnValue = 0 + +declare @vchTempText nvarchar(255) + +/* this is for our strings */ +declare @iStreamObjectId int +select @iStreamObjectId = 0 + + declare @iPropertyObjectId int + select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID') + + declare @vchProjectName nvarchar(255) + declare @vchSourceSafeINI nvarchar(255) + declare @vchServerName nvarchar(255) + declare @vchDatabaseName nvarchar(255) + exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSProject', @vchProjectName OUT + exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT + exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSQLServer', @vchServerName OUT + exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSQLDatabase', @vchDatabaseName OUT + + if @chObjectType = 'PROC' + begin + /* Procedure Can have up to three streams + Drop Stream, Create Stream, GRANT stream */ + + exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT + + if @iReturn <> 0 GOTO E_OAError + + exec @iReturn = sp_OAMethod @iObjectId, + N'CheckOut_StoredProcedure', + NULL, + @sProjectName = @vchProjectName, + @sSourceSafeINI = @vchSourceSafeINI, + @sObjectName = @vchObjectName, + @sServerName = @vchServerName, + @sDatabaseName = @vchDatabaseName, + @sComment = @vchComment, + @sLoginName = @vchLoginName, + @sPassword = @vchPassword, + @iVCSFlags = @iVCSFlags, + @iActionFlag = @iActionFlag + + if @iReturn <> 0 GOTO E_OAError + + + exec @iReturn = sp_OAGetProperty @iObjectId, N'GetStreamObject', @iStreamObjectId OUT + + if @iReturn <> 0 GOTO E_OAError + + create table #commenttext (id int identity, sourcecode nvarchar(255)) + + + select @vchTempText = N'STUB' + while @vchTempText IS NOT NULL + begin + exec @iReturn = sp_OAMethod @iStreamObjectId, N'GetStream', @iReturnValue OUT, @vchTempText OUT + if @iReturn <> 0 GOTO E_OAError + + if (@vchTempText IS NOT NULL) insert into #commenttext (sourcecode) select @vchTempText + end + + select N'VCS'=sourcecode from #commenttext order by id + select N'SQL'=text from syscomments where id = object_id(@vchObjectName) order by colid + + end + +CleanUp: + return + +E_OAError: + exec dbo.dt_displayoaerror_u @iObjectId, @iReturn + GOTO CleanUp +GO + + +--------------------------------------------- + +-- dbo.dt_displayoaerror +CREATE PROCEDURE dbo.dt_displayoaerror + @iObject int, + @iresult int +as + +set nocount on + +declare @vchOutput varchar(255) +declare @hr int +declare @vchSource varchar(255) +declare @vchDescription varchar(255) + + exec @hr = sp_OAGetErrorInfo @iObject, @vchSource OUT, @vchDescription OUT + + select @vchOutput = @vchSource + ': ' + @vchDescription + raiserror (@vchOutput,16,-1) + + return +GO + + +--------------------------------------------- + +-- dbo.dt_displayoaerror_u +CREATE PROCEDURE dbo.dt_displayoaerror_u + @iObject int, + @iresult int +as + +set nocount on + +declare @vchOutput nvarchar(255) +declare @hr int +declare @vchSource nvarchar(255) +declare @vchDescription nvarchar(255) + + exec @hr = sp_OAGetErrorInfo @iObject, @vchSource OUT, @vchDescription OUT + + select @vchOutput = @vchSource + ': ' + @vchDescription + raiserror (@vchOutput,16,-1) + + return +GO + + +--------------------------------------------- + +-- dbo.dt_droppropertiesbyid +/* +** Drop one or all the associated properties of an object or an attribute +** +** dt_dropproperties objid, null or '' -- drop all properties of the object itself +** dt_dropproperties objid, property -- drop the property +*/ +create procedure dbo.dt_droppropertiesbyid + @id int, + @property varchar(64) +as + set nocount on + + if (@property is null) or (@property = '') + delete from dbo.dtproperties where objectid=@id + else + delete from dbo.dtproperties + where objectid=@id and property=@property +GO + + +--------------------------------------------- + +-- dbo.dt_dropuserobjectbyid +/* +** Drop an object from the dbo.dtproperties table +*/ +create procedure dbo.dt_dropuserobjectbyid + @id int +as + set nocount on + delete from dbo.dtproperties where objectid=@id +GO + + +--------------------------------------------- + +-- dbo.dt_generateansiname +/* +** Generate an ansi name that is unique in the dtproperties.value column +*/ +create procedure dbo.dt_generateansiname(@name varchar(255) output) +as + declare @prologue varchar(20) + declare @indexstring varchar(20) + declare @index integer + + set @prologue = 'MSDT-A-' + set @index = 1 + + while 1 = 1 + begin + set @indexstring = cast(@index as varchar(20)) + set @name = @prologue + @indexstring + if not exists (select value from dtproperties where value = @name) + break + + set @index = @index + 1 + + if (@index = 10000) + goto TooMany + end + +Leave: + + return + +TooMany: + + set @name = 'DIAGRAM' + goto Leave +GO + + +--------------------------------------------- + +-- dbo.dt_getobjwithprop +/* +** Retrieve the owner object(s) of a given property +*/ +create procedure dbo.dt_getobjwithprop + @property varchar(30), + @value varchar(255) +as + set nocount on + + if (@property is null) or (@property = '') + begin + raiserror('Must specify a property name.',-1,-1) + return (1) + end + + if (@value is null) + select objectid id from dbo.dtproperties + where property=@property + + else + select objectid id from dbo.dtproperties + where property=@property and value=@value +GO + + +--------------------------------------------- + +-- dbo.dt_getobjwithprop_u +/* +** Retrieve the owner object(s) of a given property +*/ +create procedure dbo.dt_getobjwithprop_u + @property varchar(30), + @uvalue nvarchar(255) +as + set nocount on + + if (@property is null) or (@property = '') + begin + raiserror('Must specify a property name.',-1,-1) + return (1) + end + + if (@uvalue is null) + select objectid id from dbo.dtproperties + where property=@property + + else + select objectid id from dbo.dtproperties + where property=@property and uvalue=@uvalue +GO + + +--------------------------------------------- + +-- dbo.dt_getpropertiesbyid +/* +** Retrieve properties by id's +** +** dt_getproperties objid, null or '' -- retrieve all properties of the object itself +** dt_getproperties objid, property -- retrieve the property specified +*/ +create procedure dbo.dt_getpropertiesbyid + @id int, + @property varchar(64) +as + set nocount on + + if (@property is null) or (@property = '') + select property, version, value, lvalue + from dbo.dtproperties + where @id=objectid + else + select property, version, value, lvalue + from dbo.dtproperties + where @id=objectid and @property=property +GO + + +--------------------------------------------- + +-- dbo.dt_getpropertiesbyid_u +/* +** Retrieve properties by id's +** +** dt_getproperties objid, null or '' -- retrieve all properties of the object itself +** dt_getproperties objid, property -- retrieve the property specified +*/ +create procedure dbo.dt_getpropertiesbyid_u + @id int, + @property varchar(64) +as + set nocount on + + if (@property is null) or (@property = '') + select property, version, uvalue, lvalue + from dbo.dtproperties + where @id=objectid + else + select property, version, uvalue, lvalue + from dbo.dtproperties + where @id=objectid and @property=property +GO + + +--------------------------------------------- + +-- dbo.dt_getpropertiesbyid_vcs +create procedure dbo.dt_getpropertiesbyid_vcs + @id int, + @property varchar(64), + @value varchar(255) = NULL OUT + +as + + set nocount on + + select @value = ( + select value + from dbo.dtproperties + where @id=objectid and @property=property + ) +GO + + +--------------------------------------------- + +-- dbo.dt_getpropertiesbyid_vcs_u +create procedure dbo.dt_getpropertiesbyid_vcs_u + @id int, + @property varchar(64), + @value nvarchar(255) = NULL OUT + +as + + set nocount on + + select @value = ( + select uvalue + from dbo.dtproperties + where @id=objectid and @property=property + ) +GO + + +--------------------------------------------- + +-- dbo.dt_isundersourcecontrol +create proc dbo.dt_isundersourcecontrol + @vchLoginName varchar(255) = '', + @vchPassword varchar(255) = '', + @iWhoToo int = 0 /* 0 => Just check project; 1 => get list of objs */ + +as + +set nocount on + +declare @iReturn int +declare @iObjectId int +select @iObjectId = 0 + +declare @VSSGUID varchar(100) +select @VSSGUID = 'SQLVersionControl.VCS_SQL' + +declare @iReturnValue int +select @iReturnValue = 0 + +declare @iStreamObjectId int +select @iStreamObjectId = 0 + +declare @vchTempText varchar(255) + + declare @iPropertyObjectId int + select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID') + + declare @vchProjectName varchar(255) + declare @vchSourceSafeINI varchar(255) + declare @vchServerName varchar(255) + declare @vchDatabaseName varchar(255) + exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSProject', @vchProjectName OUT + exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT + exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLServer', @vchServerName OUT + exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLDatabase', @vchDatabaseName OUT + + if (@vchProjectName IS NULL) or (@vchSourceSafeINI IS NULL) or (@vchServerName IS NULL) or (@vchDatabaseName IS NULL) + begin + RAISERROR('Not Under Source Control',16,-1) + return + end + + if @iWhoToo = 1 + begin + + /* Get List of Procs in the project */ + exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT + if @iReturn <> 0 GOTO E_OAError + + exec @iReturn = sp_OAMethod @iObjectId, + 'GetListOfObjects', + NULL, + @vchProjectName, + @vchSourceSafeINI, + @vchServerName, + @vchDatabaseName, + @vchLoginName, + @vchPassword + + if @iReturn <> 0 GOTO E_OAError + + exec @iReturn = sp_OAGetProperty @iObjectId, 'GetStreamObject', @iStreamObjectId OUT + + if @iReturn <> 0 GOTO E_OAError + + create table #ObjectList (id int identity, vchObjectlist varchar(255)) + + select @vchTempText = 'STUB' + while @vchTempText IS NOT NULL + begin + exec @iReturn = sp_OAMethod @iStreamObjectId, 'GetStream', @iReturnValue OUT, @vchTempText OUT + if @iReturn <> 0 GOTO E_OAError + + if (@vchTempText IS NOT NULL) insert into #ObjectList (vchObjectlist ) select @vchTempText + end + + select vchObjectlist from #ObjectList order by id + end + +CleanUp: + return + +E_OAError: + exec dbo.dt_displayoaerror @iObjectId, @iReturn + goto CleanUp +GO + + +--------------------------------------------- + +-- dbo.dt_isundersourcecontrol_u +create proc dbo.dt_isundersourcecontrol_u + @vchLoginName nvarchar(255) = '', + @vchPassword nvarchar(255) = '', + @iWhoToo int = 0 /* 0 => Just check project; 1 => get list of objs */ + +as + + set nocount on + + declare @iReturn int + declare @iObjectId int + select @iObjectId = 0 + + declare @VSSGUID nvarchar(100) + select @VSSGUID = N'SQLVersionControl.VCS_SQL' + + declare @iReturnValue int + select @iReturnValue = 0 + + declare @iStreamObjectId int + select @iStreamObjectId = 0 + + declare @vchTempText nvarchar(255) + + declare @iPropertyObjectId int + select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID') + + declare @vchProjectName nvarchar(255) + declare @vchSourceSafeINI nvarchar(255) + declare @vchServerName nvarchar(255) + declare @vchDatabaseName nvarchar(255) + exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSProject', @vchProjectName OUT + exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT + exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSQLServer', @vchServerName OUT + exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSQLDatabase', @vchDatabaseName OUT + + if (@vchProjectName IS NULL) or (@vchSourceSafeINI IS NULL) or (@vchServerName IS NULL) or (@vchDatabaseName IS NULL) + begin + RAISERROR(N'Not Under Source Control',16,-1) + return + end + + if @iWhoToo = 1 + begin + + /* Get List of Procs in the project */ + exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT + if @iReturn <> 0 GOTO E_OAError + + exec @iReturn = sp_OAMethod @iObjectId, + N'GetListOfObjects', + NULL, + @vchProjectName, + @vchSourceSafeINI, + @vchServerName, + @vchDatabaseName, + @vchLoginName, + @vchPassword + + if @iReturn <> 0 GOTO E_OAError + + exec @iReturn = sp_OAGetProperty @iObjectId, N'GetStreamObject', @iStreamObjectId OUT + + if @iReturn <> 0 GOTO E_OAError + + create table #ObjectList (id int identity, vchObjectlist nvarchar(255)) + + select @vchTempText = N'STUB' + while @vchTempText IS NOT NULL + begin + exec @iReturn = sp_OAMethod @iStreamObjectId, N'GetStream', @iReturnValue OUT, @vchTempText OUT + if @iReturn <> 0 GOTO E_OAError + + if (@vchTempText IS NOT NULL) insert into #ObjectList (vchObjectlist ) select @vchTempText + end + + select vchObjectlist from #ObjectList order by id + end + +CleanUp: + return + +E_OAError: + exec dbo.dt_displayoaerror_u @iObjectId, @iReturn + goto CleanUp +GO + + +--------------------------------------------- + +-- dbo.dt_removefromsourcecontrol +create procedure dbo.dt_removefromsourcecontrol + +as + + set nocount on + + declare @iPropertyObjectId int + select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID') + + exec dbo.dt_droppropertiesbyid @iPropertyObjectId, null + + /* -1 is returned by dt_droppopertiesbyid */ + if @@error <> 0 and @@error <> -1 return 1 + + return 0 +GO + + +--------------------------------------------- + +-- dbo.dt_setpropertybyid +/* +** If the property already exists, reset the value; otherwise add property +** id -- the id in sysobjects of the object +** property -- the name of the property +** value -- the text value of the property +** lvalue -- the binary value of the property (image) +*/ +create procedure dbo.dt_setpropertybyid + @id int, + @property varchar(64), + @value varchar(255), + @lvalue image +as + set nocount on + declare @uvalue nvarchar(255) + set @uvalue = convert(nvarchar(255), @value) + if exists (select * from dbo.dtproperties + where objectid=@id and property=@property) + begin + -- + -- bump the version count for this row as we update it + -- + update dbo.dtproperties set value=@value, uvalue=@uvalue, lvalue=@lvalue, version=version+1 + where objectid=@id and property=@property + end + else + begin + -- + -- version count is auto-set to 0 on initial insert + -- + insert dbo.dtproperties (property, objectid, value, uvalue, lvalue) + values (@property, @id, @value, @uvalue, @lvalue) + end +GO + + +--------------------------------------------- + +-- dbo.dt_setpropertybyid_u +/* +** If the property already exists, reset the value; otherwise add property +** id -- the id in sysobjects of the object +** property -- the name of the property +** uvalue -- the text value of the property +** lvalue -- the binary value of the property (image) +*/ +create procedure dbo.dt_setpropertybyid_u + @id int, + @property varchar(64), + @uvalue nvarchar(255), + @lvalue image +as + set nocount on + -- + -- If we are writing the name property, find the ansi equivalent. + -- If there is no lossless translation, generate an ansi name. + -- + declare @avalue varchar(255) + set @avalue = null + if (@uvalue is not null) + begin + if (convert(nvarchar(255), convert(varchar(255), @uvalue)) = @uvalue) + begin + set @avalue = convert(varchar(255), @uvalue) + end + else + begin + if 'DtgSchemaNAME' = @property + begin + exec dbo.dt_generateansiname @avalue output + end + end + end + if exists (select * from dbo.dtproperties + where objectid=@id and property=@property) + begin + -- + -- bump the version count for this row as we update it + -- + update dbo.dtproperties set value=@avalue, uvalue=@uvalue, lvalue=@lvalue, version=version+1 + where objectid=@id and property=@property + end + else + begin + -- + -- version count is auto-set to 0 on initial insert + -- + insert dbo.dtproperties (property, objectid, value, uvalue, lvalue) + values (@property, @id, @avalue, @uvalue, @lvalue) + end +GO + + +--------------------------------------------- + +-- dbo.dt_validateloginparams +create proc dbo.dt_validateloginparams + @vchLoginName varchar(255), + @vchPassword varchar(255) +as + +set nocount on + +declare @iReturn int +declare @iObjectId int +select @iObjectId =0 + +declare @VSSGUID varchar(100) +select @VSSGUID = 'SQLVersionControl.VCS_SQL' + + declare @iPropertyObjectId int + select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID') + + declare @vchSourceSafeINI varchar(255) + exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT + + exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT + if @iReturn <> 0 GOTO E_OAError + + exec @iReturn = sp_OAMethod @iObjectId, + 'ValidateLoginParams', + NULL, + @sSourceSafeINI = @vchSourceSafeINI, + @sLoginName = @vchLoginName, + @sPassword = @vchPassword + if @iReturn <> 0 GOTO E_OAError + +CleanUp: + return + +E_OAError: + exec dbo.dt_displayoaerror @iObjectId, @iReturn + GOTO CleanUp +GO + + +--------------------------------------------- + +-- dbo.dt_validateloginparams_u +create proc dbo.dt_validateloginparams_u + @vchLoginName nvarchar(255), + @vchPassword nvarchar(255) +as + +set nocount on + +declare @iReturn int +declare @iObjectId int +select @iObjectId =0 + +declare @VSSGUID nvarchar(100) +select @VSSGUID = N'SQLVersionControl.VCS_SQL' + + declare @iPropertyObjectId int + select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID') + + declare @vchSourceSafeINI nvarchar(255) + exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT + + exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT + if @iReturn <> 0 GOTO E_OAError + + exec @iReturn = sp_OAMethod @iObjectId, + N'ValidateLoginParams', + NULL, + @sSourceSafeINI = @vchSourceSafeINI, + @sLoginName = @vchLoginName, + @sPassword = @vchPassword + if @iReturn <> 0 GOTO E_OAError + +CleanUp: + return + +E_OAError: + exec dbo.dt_displayoaerror_u @iObjectId, @iReturn + GOTO CleanUp +GO + + +--------------------------------------------- + +-- dbo.dt_vcsenabled +create proc dbo.dt_vcsenabled + +as + +set nocount on + +declare @iObjectId int +select @iObjectId = 0 + +declare @VSSGUID varchar(100) +select @VSSGUID = 'SQLVersionControl.VCS_SQL' + + declare @iReturn int + exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT + if @iReturn <> 0 raiserror('', 16, -1) /* Can't Load Helper DLLC */ +GO + + +--------------------------------------------- + +-- dbo.dt_verstamp006 +/* +** This procedure returns the version number of the stored +** procedures used by the Microsoft Visual Database Tools. +** Current version is 7.0.00. +*/ +create procedure dbo.dt_verstamp006 +as + select 7000 +GO + + +--------------------------------------------- + +-- dbo.dt_verstamp007 +/* +** This procedure returns the version number of the stored +** procedures used by the the Microsoft Visual Database Tools. +** Version is 7.0.05. +*/ +create procedure dbo.dt_verstamp007 +as + select 7005 +GO + + +--------------------------------------------- + +-- dbo.dt_whocheckedout +create proc dbo.dt_whocheckedout + @chObjectType char(4), + @vchObjectName varchar(255), + @vchLoginName varchar(255), + @vchPassword varchar(255) + +as + +set nocount on + +declare @iReturn int +declare @iObjectId int +select @iObjectId =0 + +declare @VSSGUID varchar(100) +select @VSSGUID = 'SQLVersionControl.VCS_SQL' + + declare @iPropertyObjectId int + + select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID') + + declare @vchProjectName varchar(255) + declare @vchSourceSafeINI varchar(255) + declare @vchServerName varchar(255) + declare @vchDatabaseName varchar(255) + exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSProject', @vchProjectName OUT + exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT + exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLServer', @vchServerName OUT + exec dbo.dt_getpropertiesbyid_vcs @iPropertyObjectId, 'VCSSQLDatabase', @vchDatabaseName OUT + + if @chObjectType = 'PROC' + begin + exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT + + if @iReturn <> 0 GOTO E_OAError + + declare @vchReturnValue varchar(255) + select @vchReturnValue = '' + + exec @iReturn = sp_OAMethod @iObjectId, + 'WhoCheckedOut', + @vchReturnValue OUT, + @sProjectName = @vchProjectName, + @sSourceSafeINI = @vchSourceSafeINI, + @sObjectName = @vchObjectName, + @sServerName = @vchServerName, + @sDatabaseName = @vchDatabaseName, + @sLoginName = @vchLoginName, + @sPassword = @vchPassword + + if @iReturn <> 0 GOTO E_OAError + + select @vchReturnValue + + end + +CleanUp: + return + +E_OAError: + exec dbo.dt_displayoaerror @iObjectId, @iReturn + GOTO CleanUp +GO + + +--------------------------------------------- + +-- dbo.dt_whocheckedout_u +create proc dbo.dt_whocheckedout_u + @chObjectType char(4), + @vchObjectName nvarchar(255), + @vchLoginName nvarchar(255), + @vchPassword nvarchar(255) + +as + +set nocount on + +declare @iReturn int +declare @iObjectId int +select @iObjectId =0 + +declare @VSSGUID nvarchar(100) +select @VSSGUID = N'SQLVersionControl.VCS_SQL' + + declare @iPropertyObjectId int + + select @iPropertyObjectId = (select objectid from dbo.dtproperties where property = 'VCSProjectID') + + declare @vchProjectName nvarchar(255) + declare @vchSourceSafeINI nvarchar(255) + declare @vchServerName nvarchar(255) + declare @vchDatabaseName nvarchar(255) + exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSProject', @vchProjectName OUT + exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSourceSafeINI', @vchSourceSafeINI OUT + exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSQLServer', @vchServerName OUT + exec dbo.dt_getpropertiesbyid_vcs_u @iPropertyObjectId, 'VCSSQLDatabase', @vchDatabaseName OUT + + if @chObjectType = 'PROC' + begin + exec @iReturn = sp_OACreate @VSSGUID, @iObjectId OUT + + if @iReturn <> 0 GOTO E_OAError + + declare @vchReturnValue nvarchar(255) + select @vchReturnValue = '' + + exec @iReturn = sp_OAMethod @iObjectId, + N'WhoCheckedOut', + @vchReturnValue OUT, + @sProjectName = @vchProjectName, + @sSourceSafeINI = @vchSourceSafeINI, + @sObjectName = @vchObjectName, + @sServerName = @vchServerName, + @sDatabaseName = @vchDatabaseName, + @sLoginName = @vchLoginName, + @sPassword = @vchPassword + + if @iReturn <> 0 GOTO E_OAError + + select @vchReturnValue + + end + +CleanUp: + return + +E_OAError: + exec dbo.dt_displayoaerror_u @iObjectId, @iReturn + GOTO CleanUp +GO + + +--------------------------------------------- + +-- dbo.procActionLogSummarize +create proc procActionLogSummarize as +insert into actionloghistory (Year, Month, Day, Action, SubAction, SumDuration, AvgDuration, MinDuration, MaxDuration, StdevDuration, Count) +select Year, Month, Day, Action, SubAction, SumDuration, AvgDuration, MinDuration, MaxDuration, StdevDuration, Count +from viewactionlogsummary + +truncate table actionlog +GO + + +--------------------------------------------- + +-- dbo.procAddIdentityColumnToTable +--NOTE: This procedure may fail if there's already an Identity Column in the table. +CREATE proc [dbo].[procAddIdentityColumnToTable]( + @SchemaName NVARCHAR(128), + @TableName NVARCHAR(MAX), + @ColumnName NVARCHAR(128), + @DebugMode bit = 0, @Seed NVARCHAR(128) = '1', @Increment nvarchar(128) = '1') + +AS +BEGIN + +DECLARE @sql varchar(max) + +IF dbo.tableColumnExists(@SchemaName, @TableName, @ColumnName)=0 BEGIN + SET @SQL = 'ALTER TABLE ' + (select [dbo].[GetSQLTableExpression](@SchemaName, @TableName)) + SET @SQL = @SQL + ' ADD ' + @ColumnName + SET @SQL = @SQL + ' ' + 'int' + SET @SQL = @SQL + ' NOT NULL CONSTRAINT DF_' + replace(@TableName,' ','_') + '_' + @ColumnName + SET @SQL = @SQL + ' IDENTITY(' + @Seed + ',' + @Increment + ');' + SET @SQL = @SQL + ' ALTER TABLE ' + (select [dbo].[GetSQLTableExpression](@SchemaName, @TableName)) + SET @SQL = @SQL + ' ADD PRIMARY KEY (' + @ColumnName + ');' + IF @DebugMode = 0 BEGIN + EXEC (@SQL) + PRINT @ColumnName + ' added to ' + @TableName + END ELSE BEGIN + PRINT @SQL + END + +END + + +END +GO + + +--------------------------------------------- + +-- dbo.procAddPlansDimensionToAllModelDataConfigs +CREATE proc [dbo].[procAddPlansDimensionToAllModelDataConfigs] + @override bit = 0 +as + +declare @cnt int +select @cnt = count(*) from emfsubtable +if @cnt = 0 or @override = 1 begin + insert into emfmodeldataconfigdimensionlink (modeldataconfigguid, dimensionguid) + select mdc.modeldataconfigguid, (select listguid from securelist where listtype =2) from emfmodeldataconfig mdc left join emfmodeldataconfigdimensionlink mdcdl on mdc.modeldataconfigguid = mdcdl.modeldataconfigguid and mdcdl.dimensionguid = (select listguid from securelist where listtype =2) + where mdcdl.modeldataconfigguid is null + + update emfmodeldataconfigdimensionlink set ismodelkey =1 +end +GO + + +--------------------------------------------- + +-- dbo.procAddTableDeleteVersionRows +CREATE proc procAddTableDeleteVersionRows +as + + + insert into tabledeleteversion(tablename) select 'UserUserGroupLink' where 0 = (select count(*) from tabledeleteversion where tablename = 'UserUserGroupLink') +GO + + +--------------------------------------------- + +-- dbo.procAddWorkerToActiveController +CREATE PROCEDURE [dbo].[procAddWorkerToActiveController] +@ControllerID as uniqueidentifier, +@WorkerID as uniqueidentifier + AS + +IF ((select count(*) from [dbo].[ActiveControllers] where ControllerID=@ControllerID AND WorkerID=@WorkerID) = 0) +BEGIN + INSERT INTO [dbo].[ActiveControllers] (ControllerID,WorkerID,[TimeStamp]) VALUES (@ControllerID, @WorkerID, getdate()) +END +GO + + +--------------------------------------------- + +-- dbo.procAdjustTemplateSectionCounts +CREATE PROCEDURE [dbo].[procAdjustTemplateSectionCounts] (@templateGUID UNIQUEIDENTIFIER) +AS +BEGIN + + IF EXISTS(SELECT TOP 1 1 FROM [dbo].[MEScoreExpansionProfile] WHERE [ChildModelTemplateGUID] = @templateGUID) + BEGIN + -- child profiles do not have their own settings (main template should be used instead) + RETURN; -- do nothing + END + + ;WITH newSectionCounts AS ( + SELECT + TSC.[TemplateGUID], + TSC.[SettingID], + CASE + WHEN (RM.[RecommendedMaxCount] IS NOT NULL) AND ((RM.[RecommendedMaxCount] - TSC.[ActualMaxNumberOfFillins]) BETWEEN 0 AND 10) -- 10 is placeholder + THEN + RM.[RecommendedMaxCount] -- user recommended max section count because fill-ins can fit into it and won't force profile creation + WHEN ((TSC.[ActualSectionCount] - TSC.[ActualMaxNumberOfFillins]) BETWEEN 0 AND 10) -- 10 is placeholder + THEN + TSC.[ActualSectionCount] -- use existing section count because fill-ins can fit into the placeholder + ELSE + TSC.[RecommendedSectionCount] -- use recommended section count because the difference is too high + END AS [NewSectionCountToUse] + + FROM [dbo].[viewTemplateSectionCountsWithRecommended] AS TSC + INNER JOIN [dbo].[EMFModelTemplate] AS MT + ON TSC.[TemplateGUID] = MT.[ModelTemplateGUID] + LEFT JOIN [dbo].[MEScoreExpansionRecommendedMaxCount] AS RM + ON RM.[SectionName] = TSC.[SectionName] AND MT.[Name] = 'OB Departmental Budget' -- only 'OB Departmental Budget' supports expansion profiles + ) + UPDATE TS + SET TS.[Value] = SC.[NewSectionCountToUse] + FROM [dbo].[TemplateSettings] AS TS + INNER JOIN newSectionCounts AS SC + ON SC.[TemplateGUID] = TS.[TemplateGUID] AND SC.[SettingID] = TS.[SettingID] + WHERE 1=1 + AND TS.[TemplateGUID] = @templateGUID + AND TS.[Value] <> SC.[NewSectionCountToUse]; + +END +GO + + +--------------------------------------------- + +-- dbo.procBackupTable +CREATE PROCEDURE [dbo].[procBackupTable] + @tablename [nvarchar](400), + @schema [nvarchar](400), + @where [nvarchar](max) = '' +AS +declare @dbname nvarchar(400) = DB_Name() +declare @username nvarchar(400) = replace(system_user, 'sdt\', '') +declare @count int +declare @BackupName nvarchar(max) = @dbname + '_' + @tablename + '_' + replace(convert(nvarchar(10), getdate(), 102), '.', '') + '_' + @username + +begin try +--Check for dupe backup names +select @count = COUNT(*) from TempTableBackups.sys.tables where name like '%' + @BackupName + '%' +set @BackupName = @BackupName + '_' + right('0' + CAST((@count+1) as nvarchar(10)), 2) + + --Create bak table + print @BackupName + declare @sql nvarchar(max) = 'select * into TempTableBackups.[dbo].[' + @BackupName + '] from ' + @schema + '.' + @tablename + if (@where != '') set @sql = @sql + ' where ' + @where + exec (@sql) +end try +begin catch + print 'Error: ' + error_message() +end catch +GO + + +--------------------------------------------- + +-- dbo.procBatchDeleteOnTable +CREATE PROCEDURE [dbo].[procBatchDeleteOnTable] +( + @FromClause NVARCHAR(MAX), + @WhereClause NVARCHAR(MAX), + @BaseTableAlias NVARCHAR(10) = '', + @BatchSize INT = 100000, + @IsDebugStatement BIT = 0 +) +AS +BEGIN + SET NOCOUNT ON; + DECLARE @msg NVARCHAR(200); + + IF (@FromClause LIKE '%join%' AND @BaseTableAlias = '') + BEGIN + SET @msg = N'@FromClause with JOINs requires a @BaseTableAlias value.'; + RAISERROR(@msg, 0, 1) WITH NOWAIT; + RETURN; + END + + DECLARE @sql NVARCHAR(MAX); + + SET @sql = N' + WHILE (1=1) + BEGIN + DELETE TOP ('+CAST(@BatchSize AS VARCHAR)+') '+@BaseTableAlias+' + FROM '+@FromClause+' WHERE '+@WhereClause+'; + + IF (@@ROWCOUNT = 0) BREAK; + END'; + + IF @IsDebugStatement = 1 SET @sql = 'PRINT ''' + @sql + ''''; + + EXEC (@sql); + +END +GO + + +--------------------------------------------- + +-- dbo.procCallRestApi +CREATE PROCEDURE [dbo].[procCallRestApi] + @url VARCHAR(2083), + @method VARCHAR(10) = 'get', + @body VARCHAR(MAX) = NULL, + @authorization VARCHAR(100) = NULL, + @responseText VARCHAR(8000) OUTPUT, + @statusCode INT OUTPUT, + @statusText VARCHAR(1000) OUTPUT +AS +BEGIN + DECLARE @object AS INT; + DECLARE @error AS INT; + DECLARE @MessageError VARCHAR(255); + DECLARE @MessageErrorNumber VARCHAR(255); + + SET @statusCode = -1; + SET @statusText = 'Unexpected error'; + SET @responseText = 'Unexpected error'; + SET @MessageError = 'Unexpected error'; + + EXEC @error = sys.sp_OACreate 'MSXML2.ServerXMLHttp', @object OUT; + IF @error <> 0 + BEGIN + SET @MessageError = 'sp_OACreate MSXML2.ServerXMLHttp failed'; + GOTO fini; + END; + + EXEC @error = sys.sp_OAMethod @object, 'open', NULL, @method, @url, false; + IF @error <> 0 + BEGIN + SET @MessageError = 'sp_OAMethod Open failed'; + GOTO fini; + END; + + EXEC @error = sp_OAMethod + @object, + 'setRequestHeader', + NULL, + 'Content-Type', + 'application/json'; + IF @error <> 0 + BEGIN + SET @MessageError = 'sp_OAMethod setRequestHeader failed'; + GOTO fini; + END; + + -- *HACK* to get around the CSRF filter. We will remove this once we change the location of the endpoint + EXEC @error = sp_OAMethod @object, 'setRequestHeader', NULL, 'CSRF', ' '; + IF @error <> 0 + BEGIN + SET @MessageError = 'sp_OAMethod setRequestHeader failed'; + GOTO fini; + END; + + IF @authorization IS NOT NULL + BEGIN + EXEC @error = sp_OAMethod @object, 'setRequestHeader', NULL, 'Authorization', @authorization; + IF @error <> 0 + BEGIN + SET @MessageError = 'sp_OAMethod setRequestHeader failed'; + GOTO fini; + END; + END; + + EXEC @error = sys.sp_OAMethod @object, 'send', NULL, @body; + IF @error <> 0 + BEGIN + SET @MessageError = 'sp_OAMethod Send failed'; + GOTO fini; + END; + + EXEC @error = sys.sp_OAGetProperty @object, 'status', @statusCode OUT; + IF @error <> 0 + BEGIN + SET @MessageError = 'sp_OAGetProperty read status failed'; + GOTO fini; + END; + + EXEC @error = sys.sp_OAGetProperty @object, 'StatusText', @statusText OUT; + IF @error <> 0 + BEGIN + SET @MessageError = 'sp_OAGetProperty statusText failed'; + GOTO fini; + END; + + EXEC @error = sys.sp_OAGetProperty + @object, + 'responseText', + @responseText OUT; + IF @error <> 0 + BEGIN + SET @MessageError = 'sp_OAGetProperty responseText failed'; + GOTO fini; + END; + + EXEC sys.sp_OADestroy @object; + + PRINT @statusText + ' ' + CAST(@statusCode AS VARCHAR(MAX)) + ' ' + @responseText; + + RETURN; + + fini: + PRINT @MessageError; + DECLARE @src VARCHAR(1000); + DECLARE @desc VARCHAR(1000); + EXEC @error = sys.sp_OAGetErrorInfo @object, @src OUT, @desc OUT; + + IF @error <> 0 + BEGIN + SELECT + CONVERT(VARBINARY(4), @error) [error], + @src [Source], + @desc [Description]; + END; + + + EXEC sp_OADestroy @object; + + SET @MessageErrorNumber = 'Error : ' + CAST(@error AS VARCHAR) + ' - ' + @MessageError; + + SELECT @MessageErrorNumber + --RAISERROR(@MessageErrorNumber, 16, 1); + + RETURN; + +END; +GO + + +--------------------------------------------- + +-- dbo.procCapEMFSetYearFillins +CREATE proc dbo.procCapEMFSetYearFillins + @PLANGUID UniqueIdentifier + ,@PHSectionGUID UniqueIdentifier + ,@TargetFirstMemberGUID uniqueidentifier + ,@NumMembers int +as + +declare @FirstMemberGUID uniqueidentifier +set @FirstMemberGUID = dbo.GetModelFirstFillInSection(@planguid, @phsectionguid) + + +if @FirstMemberGUID = '00000000-0000-0000-0000-000000000000' begin + exec procEMFFillInAddToEndSection @phsectionguid, @targetfirstmemberguid, @planguid + set @firstmemberguid = @targetfirstmemberguid +end + +DECLARE @OFFSET Int + +SELECT @OFFSET = tfm.DisplayOrder - fm.DisplayOrder +FROM + SecureListMember fm + inner join SecureListMember tfm on fm.ListMemberGUID = @FirstMemberGUID and tfm.ListMemberGUID = @TargetFirstMemberGUID + +if @OFFSET is null return + +DECLARE @ONEGUID UniqueIdentifier +SET @ONEGUID = '11111111-1111-1111-1111-111111111111' + +declare @PHDimGUID uniqueidentifier +SELECT @PHDimGUID = listguid from SecureListMember where ListMemberGUID = @PHSectionGUID + +if @PHDimGUID is null return + +declare @fidimguid uniqueidentifier +select @fidimguid = fillindimensionguid from SecureList where ListGUID = @PHDimGUID + +if @fidimguid is null return + +declare @higuid uniqueidentifier + +declare @cnt int +exec procLogObjectHistory @PlanGUID, 'Changing base fill-in', 0, @higuid output + +--FIX FILLINS +UPDATE EMFFillIn SET FilledInMemberGUID = dbo.GetSecureListOffsetMember(FilledInMemberGUID,@offset) +WHERE + ModelGUID = @PlanGUID + AND PlaceholderMemberGUID IN (SELECT ListMemberGUID FROM SecureListMember WHERE ParentListMemberGUID = @PHSectionGUID) + +--DELETE FILLINS PUSHED OFF THE END of possible members +DELETE FROM EMFFillIn WHERE + MODELGUID = @PLANGUID + and FilledInMemberGUID = @ONEGUID + +--DELETE FILLINS PUSHED OFF THE END of # of members +DELETE FROM EMFFillIn WHERE ModelGUID = @PlanGUID AND FilledInMemberGUID IN (SELECT GUID FROM dbo.getFillinMembersPastMaxIndex(@PLANGUID, @PHDimGUID, @NumMembers)) + +--add FILLINS to equal # of members +exec procEMFFillInAdd @planguid, @PHDimGUID, @NumMembers + +declare @sql varchar(max) +declare @mdTableName varchar(max) + +declare @phDimColumnName varchar(max) +set @phDimColumnName = 'G' + REPLACE(cast(@phdimguid as varchar(36)),'-','_') + +set @sql = ' +declare @msg varchar(max) +declare @cnt int +declare @planguid uniqueidentifier +set @planguid = ''' + cast(@planguid as varchar(36))+ ''' + +declare @fidimguid uniqueidentifier +set @fidimguid = ''' + cast(@fidimguid as varchar(36))+ ''' + +declare @PHSectionGUID uniqueidentifier +set @PHSectionGUID = ''' + cast(@PHSectionGUID as varchar(36))+ ''' + +declare @oneguid uniqueidentifier +set @oneguid = ''11111111-1111-1111-1111-111111111111'' + +declare @higuid uniqueidentifier +set @higuid = ''' + cast(@higuid as varchar(36)) + ''' + +UPDATE zzemfmodeldata_{mdcguidfriendly} +SET + zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' = dbo.GetSecureListOffsetMember(zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ',' + cast(@offset as varchar(4)) + ') + ,HISTORYITEMGUID = @higuid +WHERE + MODELGUID = @planguid + --ONLY Update data who was previously assigned to a member that was filling in the section we are updating, altho this could cause a duplicate issue + AND zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' + IN ( SELECT FI.FilledInMemberGUID FROM EMFFillIn FI WHERE FI.PlaceholderMemberGUID + IN (SELECT ListMemberGUID FROM SecureListMember WHERE ParentListMemberGUID = @PHSectionGUID)) + +DELETE FROM zzemfmodeldata_{mdcguidfriendly} WHERE VALUE = 0 AND MODELGUID = @PLANGUID and zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' = @ONEGUID +DELETE FROM zzemfmodeldata_{mdcguidfriendly} WHERE MODELGUID = @PLANGUID and (zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' = @ONEGUID + OR ( + not zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' in (select filledinmemberguid from emffillin where modelguid = @planguid) --orphan cause not filled in + and + not zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' = ''00000000-0000-0000-0000-000000000000'' --not orphaned because emptyguid is ok + ) + ) + +set @cnt = @@rowcount +if @cnt > 0 begin + set @msg = ''Cleared orphaned nonzero cells from {mdcname} while changing Year configuration'' + exec procLogObjectHistory @PlanGUID, @msg, @cnt, @higuid +end + +' + + +declare @mtguid uniqueidentifier +select @mtguid = modeltemplateguid from XPlan where PlanGUID = @PLANGUID + +--FOR EACH MD TABLE USED BY THIS PLAN +declare @where varchar(max) +set @where = 'where modeldataconfigguid in (select modeldataconfigguid from viewEMFModelTemplateMDCs where modeltemplateguid = ''' + cast(@mtguid as varchar(36)) + ''') + and modeldataconfigguid in (select modeldataconfigguid from emfmodeldataconfigdimensionlink where dimensionguid = ''' + cast(@PHDimGUID as varchar(36)) + ''') +' + +exec procEMFRunForManyStructures @sql, @where, 1 +GO + + +--------------------------------------------- + +-- dbo.procChangeDBSetting +--Author: gforeman +--Branch: EarwigJFS +--Forward +CREATE procedure [dbo].[procChangeDBSetting] +@settingname as nvarchar(128), +@value as nvarchar(4000) +as +if (select count(*) from dbsetting where name = @settingname) = 1 begin + update dbsetting set setting = @value, LastModifiedDate = getdate() where name = @settingname +end else begin + insert into dbsetting (name, setting, LastModifiedDate) select rtrim(ltrim(@settingname)), @value, getdate() +end +GO + + +--------------------------------------------- + +-- dbo.procCheckDimensionMemberIntegrity +CREATE PROCEDURE [dbo].[procCheckDimensionMemberIntegrity] + @moreinfo as bit = 0 +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + DECLARE @LEVEL int + SET @LEVEL = 0 + + CREATE TABLE #LISTMEMBERVALIDATION (LISTMEMBERGUID uniqueidentifier, PARENTLISTMEMBERGUID uniqueidentifier, OUTLINELEVEL int, LISTGUID uniqueidentifier) + CREATE TABLE #INVALIDLISTINFO (LISTGUID uniqueidentifier) + + INSERT #LISTMEMBERVALIDATION + SELECT + LISTMEMBERGUID, + PARENTLISTMEMBERGUID, + OUTLINELEVEL, + LISTGUID + FROM + SecureListMember + WHERE + PARENTLISTMEMBERGUID = '00000000-0000-0000-0000-000000000000' + + INSERT #INVALIDLISTINFO SELECT DISTINCT LISTGUID FROM #LISTMEMBERVALIDATION WHERE OUTLINELEVEL != @LEVEL AND LISTGUID NOT IN(SELECT LISTGUID FROM #INVALIDLISTINFO) + + WHILE((SELECT COUNT(*) FROM #LISTMEMBERVALIDATION) > 0) BEGIN + SET @LEVEL = @LEVEL + 1 + + INSERT #LISTMEMBERVALIDATION + SELECT + LISTMEMBERGUID, + PARENTLISTMEMBERGUID, + OUTLINELEVEL, + LISTGUID + FROM + SecureListMember + WHERE + PARENTLISTMEMBERGUID IN (SELECT LISTMEMBERGUID FROM #LISTMEMBERVALIDATION) + + DELETE FROM #LISTMEMBERVALIDATION WHERE PARENTLISTMEMBERGUID NOT IN(SELECT LISTMEMBERGUID FROM #LISTMEMBERVALIDATION) + + INSERT #INVALIDLISTINFO SELECT DISTINCT LISTGUID FROM #LISTMEMBERVALIDATION WHERE OUTLINELEVEL != @LEVEL AND LISTGUID NOT IN(SELECT LISTGUID FROM #INVALIDLISTINFO) + END + + IF (@moreinfo = 1) BEGIN + SELECT I.*, L.NAME FROM #INVALIDLISTINFO I LEFT JOIN SecureList L ON I.LISTGUID = L.LISTGUID + END ELSE BEGIN + SELECT COUNT(*) FROM #INVALIDLISTINFO + END + + DROP TABLE #INVALIDLISTINFO + DROP TABLE #LISTMEMBERVALIDATION +END +GO + + +--------------------------------------------- + +-- dbo.procCleanNamespace +CREATE procedure [dbo].[procCleanNamespace] + +as +set nocount on + +declare @tablename varchar(max) +declare @columnName varchar(max) + +--set @tablename = 'DesktopContent' +--set @columnName = 'ContentFullName' +--exec procCleanNamespaceSingle @tablename,@columnName, ' Strata.X.Controls,',' Strata.Jazz.UI,' +GO + + +--------------------------------------------- + +-- dbo.procCleanNamespaceSingle +CREATE proc [dbo].[procCleanNamespaceSingle] + @tablename varchar(max) + ,@columnname varchar(max) + ,@original varchar(max) + ,@new varchar(max) +as + set nocount on + + declare @sql varchar(max) + set @sql = ' + update + ' + @tablename + ' + set + ' + @columnname + ' = REPLACE(cast(' + @columnname + ' as nvarchar(max)),''' + @original + ''',''' + @new + ''') + where + cast(' + @columnname + ' as nvarchar(max)) <> REPLACE(cast(' + @columnname + ' as nvarchar(max)),''' + @original + ''',''' + @new + ''') + ' + + declare @cnt int + exec( @sql) + set @cnt = @@ROWCOUNT + if @cnt > 0 begin + print cast(@cnt as varchar(max)) + ' changes in ' + @tablename + '.' + @columnname + ' from ' + @original + ' to ' + @new + end +GO + + +--------------------------------------------- + +-- dbo.procCleanOrphanFolderItems +CREATE procedure [dbo].[procCleanOrphanFolderItems] + +as + +update REReport +set FolderGUID = (select rootfolderguid from FolderSet where Type=4) +where FolderGUID not in (select FolderGUID from REReport) +GO + + +--------------------------------------------- + +-- dbo.procCleanOrphanFolders +CREATE procedure [dbo].[procCleanOrphanFolders] + +as +delete from folder where parentfolderguid not in (select folderguid from folder) and parentfolderguid <> '00000000-0000-0000-0000-000000000000' +GO + + +--------------------------------------------- + +-- dbo.procCleanOrphanListMembers +CREATE procedure [dbo].[procCleanOrphanListMembers] + +as +delete from securelistmember where parentlistmemberguid not in (select listmemberguid from securelistmember) and parentlistmemberguid <> '00000000-0000-0000-0000-000000000000' +GO + + +--------------------------------------------- + +-- dbo.procClearCachedReportsByName +-- ============================================= +-- Author: Derek Daniel +-- Create date: 20070501 +-- Description: Delete cached reports that contain the word "historical". +-- In Eisenhower production, the "historical" reports are used in the template +-- to bring in actual data. Long term, this will need to be refined to +-- clear cached reports only for specific cubes when those cubes are refreshed +-- with new data. (see change request 11786) +-- ============================================= +CREATE PROCEDURE [dbo].[procClearCachedReportsByName] + -- Add the parameters for the stored procedure here + @reportNameContains as nvarchar(256) +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + -- Insert statements for procedure here +DELETE +FROM RECachedReport +WHERE CACHEDREPORTGUID IN +( +SELECT cached.CACHEDREPORTGUID +FROM RECachedReport cached +INNER JOIN REReport rer +ON cached.REPORTGUID = rer.REPORTGUID +WHERE (rer.NAME LIKE @reportNameContains) +) + +END +GO + + +--------------------------------------------- + +-- dbo.procClearChangeTrackingFile +create proc dbo.procClearChangeTrackingFile + @ModelTemplateGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000' +AS BEGIN + +delete from [dbo].[DataPathFile_ModelTemplate] +where FullPath like '%' + cast(@ModelTemplateGUID as nvarchar(50)) + '%' +and FullPath like '%.ChangeTracking.csv' + +END +GO + + +--------------------------------------------- + +-- dbo.procClearDataIntSectionObjects +--Forward + +create procedure dbo.procClearDataIntSectionObjects( + @SectionID uniqueidentifier +) +AS +BEGIN + + declare @name varchar(max); + select @name = Name from dbo.IntDataInterfaceSection where DataInterfaceSectionID = @SectionID + + declare @importTable varchar(max); + declare @rejectTable varchar(max); + select @importTable = dbo.GetDataIntSectionAcceptedTableName(@SectionID); + select @rejectTable = dbo.GetDataIntSectionRejectedTableName(@SectionID); + + declare @importView varchar(max); + declare @rejectView varchar(max); + select @importView = dbo.GetDataIntSectionAcceptedViewName(@name, @SectionID); + select @rejectView = dbo.GetDataIntSectionRejectedViewName(@name, @SectionID); + + + declare @schema sysname; + declare @object sysname; + declare @isview bit; + + declare crsCursor CURSOR LOCAL FAST_FORWARD FOR + select SchemaName, ObjectName, 0 as [IsView] from ViewSysTables where SchemaName = dbo.DataIntegrationSchema() + and ((ObjectName = @importTable) or (ObjectName = @rejectTable)) + union all + select SchemaName, ObjectName, 1 as [IsView] from ViewSysViews where SchemaName = dbo.DataIntegrationSchema() + and ((ObjectName = @importView) or (ObjectName = @rejectView)) + + open crsCursor; + + FETCH NEXT FROM crsCursor into @schema, @object, @isview + WHILE (@@FETCH_STATUS = 0) + BEGIN + + if (@isview = 1) begin + print 'Dropping View: [' + @schema + '].[' + @object + ']'; + exec procSysDropView @schema, @object; + end + else begin + print 'Dropping Table: [' + @schema + '].[' + @object + ']'; + exec procSysDropTable @schema, @object; + end + + FETCH NEXT FROM crsCursor into @schema, @object, @isview + END + close crsCursor; + DEALLOCATE crsCursor; +END + +RETURN +GO + + +--------------------------------------------- + +-- dbo.procClearDataIntSectionObjectsAll +CREATE procedure [dbo].[procClearDataIntSectionObjectsAll]( + @IsDebugOnly bit = 1 +) +AS +BEGIN + + declare @schema sysname; + declare @object sysname; + declare @isview bit; + + declare crsCursor CURSOR LOCAL FAST_FORWARD FOR + select SchemaName, ObjectName, 0 as [IsView] from ViewSysTables where SchemaName = dbo.DataIntegrationSchema() + union all + select SchemaName, ObjectName, 1 as [IsView] from ViewSysViews where SchemaName = dbo.DataIntegrationSchema() + + open crsCursor; + + FETCH NEXT FROM crsCursor into @schema, @object, @isview + WHILE (@@FETCH_STATUS = 0) + BEGIN + + if (@isview = 1) begin + print 'Dropping View: [' + @schema + '].[' + @object + ']'; + if (@IsDebugOnly = 0) begin + exec procSysDropView @schema, @object; + end + end + else begin + print 'Dropping Table: [' + @schema + '].[' + @object + ']'; + if (@IsDebugOnly = 0) begin + exec procSysDropTable @schema, @object; + end + end + + FETCH NEXT FROM crsCursor into @schema, @object, @isview + END + close crsCursor; + DEALLOCATE crsCursor; +END +GO + + +--------------------------------------------- + +-- dbo.procCollapseTasks +CREATE PROCEDURE [dbo].[procCollapseTasks] +@TaskGUID as uniqueidentifier, +@AssemblyQualifiedName as nvarchar(1024), +@CollapsibleID as nvarchar(MAX), +@DBConnectionGUID as uniqueidentifier + AS + +delete from tetask +where + taskguid <> @taskguid + and [status] <> 1 + and iscollapsible = 1 + and Assemblyqualifiedname = @AssemblyQualifiedName + and collapsibleid = @CollapsibleID + and collapsibleid <> '' + and DBConnectionGUID = @DBConnectionGUID + --dont collapse grouping tasks + and GroupingID = '' +GO + + +--------------------------------------------- + +-- dbo.procConvertCSGuidsToTempTable +CREATE PROCEDURE procConvertCSGuidsToTempTable + (@list text, + @delimiter char(1) = N',') +AS +SET NOCOUNT ON + + CREATE TABLE #CSGUIDTABLE (listpos int IDENTITY(1, 1) NOT NULL, + guid uniqueidentifier) + + DECLARE @pos int, + @textpos int, + @chunklen smallint, + @tmpstr nvarchar(4000), + @leftover nvarchar(4000), + @tmpval uniqueidentifier + + SET @textpos = 1 + SET @leftover = '' + WHILE @textpos <= datalength(@list) / 2 + BEGIN + SET @chunklen = 4000 - datalength(@leftover) / 2 + SET @tmpstr = @leftover + substring(@list, @textpos, @chunklen) + SET @textpos = @textpos + @chunklen + + SET @pos = charindex(@delimiter, @tmpstr) + + WHILE @pos > 0 + BEGIN + SET @tmpval = cast(ltrim(rtrim(left(@tmpstr, @pos - 1))) as uniqueidentifier) + + INSERT #CSGUIDTABLE (guid) VALUES (@tmpval) + SET @tmpstr = substring(@tmpstr, @pos + 1, len(@tmpstr)) + SET @pos = charindex(@delimiter, @tmpstr) + END + + SET @leftover = @tmpstr + END + + INSERT #CSGUIDTABLE(guid) VALUES (cast(ltrim(rtrim(@leftover)) as uniqueidentifier)) +GO + + +--------------------------------------------- + +-- dbo.procConvertColumnTypeWithFKReferencingTable +CREATE PROCEDURE [dbo].[procConvertColumnTypeWithFKReferencingTable] + @Schema NVARCHAR(100), -- ex. dss + @TableName NVARCHAR(200), -- ex. DimCPT + @ColumnName NVARCHAR(200), -- ex.CPTID + @Type NVARCHAR(100), -- ex. 'smallint', 'int', 'bigint', + @Debug BIT = 0 -- Set to false by default. +AS +BEGIN +SET NOCOUNT ON; +DECLARE @TimeStamp VARCHAR(30) = CONVERT(VARCHAR, GETDATE(), 121), +@ProcName VARCHAR(100) = OBJECT_NAME(@@PROCID), +@Count INT = 0, @SQL NVARCHAR(4000), +@FKName NVARCHAR(4000), +@FKSchema NVARCHAR(4000), +@FKTableName NVARCHAR(4000), +@FKColumnName NVARCHAR(4000), +@DeleteText NVARCHAR(15), +@UpdateText NVARCHAR(15), +@IDColumnName NVARCHAR(4000), +@FullTableName NVARCHAR (4000) = @Schema + '.' + @TableName, +@FKIsDisabled BIT; +RAISERROR('%s: Starting %s', 0, 1, @TimeStamp, @ProcName) WITH NOWAIT; +SELECT @IDColumnName = name + FROM sys.columns + WHERE object_id = OBJECT_ID(@FullTableName) + AND is_identity = 1; +SET @Count = @@ROWCOUNT; +IF (@Count != 0) +BEGIN +SELECT + fk.name FKName, + OBJECT_SCHEMA_NAME(fk.parent_object_id) FKSchema, + OBJECT_NAME(fk.parent_object_id) FKTableName, + COL_NAME(fc.parent_object_id, fc.parent_column_id) AS FKColumnName, + CASE (fk.delete_referential_action) + WHEN 1 THEN 'CASCADE' + WHEN 2 THEN 'SET NULL' + WHEN 3 THEN 'SET DEFAULT' + ELSE 'NO ACTION' + END DeleteAction, + CASE (fk.update_referential_action) + WHEN 1 THEN 'CASCADE' + WHEN 2 THEN 'SET NULL' + WHEN 3 THEN 'SET DEFAULT' + ELSE 'NO ACTION' + END UpdateAction, + CASE + WHEN fk.is_disabled = 1 OR fk.is_not_trusted = 1 THEN 1 + ELSE 0 + END AS FKIsDisabled +INTO #ForeignKeys +FROM sys.foreign_keys AS fk +INNER JOIN sys.foreign_key_columns AS fc + ON fk.object_id = fc.constraint_object_id +WHERE OBJECT_SCHEMA_NAME(fk.referenced_object_id) = @Schema + AND OBJECT_NAME(fk.referenced_object_id) = @TableName + AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = @IDColumnName; + +SET @Count = @@ROWCOUNT; +END +IF (@Count != 0) +BEGIN +-- Drop FK Constraints + SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121); + RAISERROR('%s: Found %d foreign key references.', 0, 1, @TimeStamp, @Count) WITH NOWAIT; + DECLARE Drop_FK_Cursor CURSOR FOR + SELECT FKName, FKSchema, FKTableName + FROM #ForeignKeys + ORDER BY FKName; + OPEN Drop_FK_Cursor; + FETCH NEXT FROM Drop_FK_Cursor INTO @FKName, @FKSchema, @FKTableName; + WHILE @@FETCH_STATUS = 0 + BEGIN + -- Drop FK constraint + SET @SQL = 'ALTER TABLE [' + @FKSchema + '].[' + @FKTableName + '] DROP CONSTRAINT [' + @FKName + ']'; + SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121); + RAISERROR('%s: %s', 0, 1, @TimeStamp, @SQL) WITH NOWAIT; + IF (@Debug = 0) + EXEC sp_executesql @SQL; + FETCH NEXT FROM Drop_FK_Cursor INTO @FKName, @FKSchema, @FKTableName; + END + CLOSE Drop_FK_Cursor; + DEALLOCATE Drop_FK_Cursor; +END +SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121); +RAISERROR('%s: Changing PK type to %s.', 0, 1, @TimeStamp, @Type) WITH NOWAIT; +-- Change parent table type +SET @SQL = 'EXEC dbo.ConvertIntToBigIntByColumnNameNoCompression @sourceSchema=''' + @Schema + ''', @sourceTable=''' + @TableName + ''', @columnName=''' + @ColumnName + ''', @expectedType=''' + @Type + ''';' +SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121); +RAISERROR('%s: %s', 0, 1, @TimeStamp, @SQL) WITH NOWAIT; +IF (@Debug = 0) +EXEC sp_executesql @SQL; +IF (@Count != 0) +BEGIN + SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121); + RAISERROR('%s: Recreating foreign keys.', 0, 1, @TimeStamp) WITH NOWAIT; + -- Recreate foreign key constraints with ON DELETE and ON UPDATE actions + DECLARE Create_FK_Cursor CURSOR FOR + SELECT FKName, FKSchema, FKTableName, FKColumnName, DeleteAction, UpdateAction, FKIsDisabled + FROM #ForeignKeys + ORDER BY FKName; + OPEN Create_FK_Cursor; + FETCH NEXT FROM Create_FK_Cursor INTO @FKName, @FKSchema, @FKTableName, @FKColumnName, @DeleteText, @UpdateText, @FKIsDisabled; + WHILE @@FETCH_STATUS = 0 + BEGIN + -- Recreate FK constraint with the specific ON DELETE and ON UPDATE actions + SET @SQL = 'ALTER TABLE [' + @FKSchema + '].[' + @FKTableName + ']' + CASE (@FKIsDisabled) WHEN 1 THEN ' WITH NOCHECK' ELSE '' END + ' ADD CONSTRAINT [' + @FKName + '] FOREIGN KEY (' + @FKColumnName + ') REFERENCES [' + @Schema + '].[' + @TableName + + ']([' + @IDColumnName + ']) ON DELETE ' + @DeleteText + ' ON UPDATE ' + @UpdateText; + SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121); + RAISERROR('%s: %s', 0, 1, @TimeStamp, @SQL) WITH NOWAIT; + IF (@Debug = 0) + EXEC sp_executesql @SQL; + FETCH NEXT FROM Create_FK_Cursor INTO @FKName, @FKSchema, @FKTableName, @FKColumnName, @DeleteText, @UpdateText, @FKIsDisabled; + END + CLOSE Create_FK_Cursor; + DEALLOCATE Create_FK_Cursor; +END +END +GO + + +--------------------------------------------- + +-- dbo.procConvertFKReferencingTablePKToReferencedTableType +CREATE PROCEDURE dbo.procConvertFKReferencingTablePKToReferencedTableType + @Schema NVARCHAR(100), -- ex. dss + @TableName NVARCHAR(200), -- ex. DimCPT + @ColumnName NVARCHAR(200), -- ex.CPTID + @Type NVARCHAR(100), -- ex. 'smallint', 'int', 'bigint', + @Debug BIT = 0 -- Set to false by default. +AS +BEGIN +SET NOCOUNT ON; + +DECLARE @TimeStamp VARCHAR(30) = CONVERT(VARCHAR, GETDATE(), 121), +@ProcName VARCHAR(100) = OBJECT_NAME(@@PROCID), +@Count INT = 0, @SQL NVARCHAR(4000), +@FKName NVARCHAR(4000), +@FKSchema NVARCHAR(4000), +@FKTableName NVARCHAR(4000), +@FKColumnName NVARCHAR(4000), +@DeleteText NVARCHAR(15), +@UpdateText NVARCHAR(15); + +RAISERROR('%s: Starting %s', 0, 1, @TimeStamp, @ProcName) WITH NOWAIT; + +SELECT + fk.name FKName, + OBJECT_SCHEMA_NAME(fk.parent_object_id) FKSchema, + OBJECT_NAME(fk.parent_object_id) FKTableName, + COL_NAME(fc.parent_object_id, fc.parent_column_id) AS FKColumnName, + CASE (fk.delete_referential_action) + WHEN 1 THEN 'CASCADE' + WHEN 2 THEN 'SET NULL' + WHEN 3 THEN 'SET DEFAULT' + ELSE 'NO ACTION' + END DeleteAction, + CASE (fk.update_referential_action) + WHEN 1 THEN 'CASCADE' + WHEN 2 THEN 'SET NULL' + WHEN 3 THEN 'SET DEFAULT' + ELSE 'NO ACTION' + END UpdateAction +INTO #ForeignKeys +FROM sys.foreign_keys AS fk +INNER JOIN sys.foreign_key_columns AS fc + ON fk.object_id = fc.constraint_object_id +WHERE OBJECT_SCHEMA_NAME(fk.referenced_object_id) = @Schema + AND OBJECT_NAME(fk.referenced_object_id) = @TableName + AND COL_NAME(fc.referenced_object_id, fc.referenced_column_id) = @ColumnName; + +SET @Count = @@ROWCOUNT; + +IF (@Count != 0) +BEGIN +-- Drop FK Constraints, alter column type. + SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121); + RAISERROR('%s: Found %d foreign key references.', 0, 1, @TimeStamp, @Count) WITH NOWAIT; + + DECLARE Drop_FK_Cursor CURSOR FOR + SELECT FKName, FKSchema, FKTableName, FKColumnName + FROM #ForeignKeys + ORDER BY FKName; + + OPEN Drop_FK_Cursor; + FETCH NEXT FROM Drop_FK_Cursor INTO @FKName, @FKSchema, @FKTableName, @FKColumnName; + + WHILE @@FETCH_STATUS = 0 + BEGIN + -- Drop FK constraint + SET @SQL = 'ALTER TABLE [' + @FKSchema + '].[' + @FKTableName + '] DROP CONSTRAINT [' + @FKName + ']'; + SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121); + RAISERROR('%s: %s', 0, 1, @TimeStamp, @SQL) WITH NOWAIT; + + IF (@Debug = 0) + EXEC sp_executesql @SQL; + + -- Alter column type + SET @SQL = 'EXEC dbo.ConvertIntToBigIntByColumnNameNoCompression @sourceSchema=''' + @FKSchema + ''', @sourceTable=''' + @FKTableName + ''', @columnName=''' + @FKColumnName + ''', @expectedType=''' + @Type + ''';' + + IF (@Debug = 0) + EXEC sp_executesql @SQL; + + FETCH NEXT FROM Drop_FK_Cursor INTO @FKName, @FKSchema, @FKTableName, @FKColumnName; + END + + CLOSE Drop_FK_Cursor; + DEALLOCATE Drop_FK_Cursor; +END + +SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121); +RAISERROR('%s: Changing PK type to %s.', 0, 1, @TimeStamp, @Type) WITH NOWAIT; +-- Change PK type +SET @SQL = 'EXEC dbo.ConvertIntToBigIntByColumnNameNoCompression @sourceSchema=''' + @Schema + ''', @sourceTable=''' + @TableName + ''', @columnName=''' + @ColumnName + ''', @expectedType=''' + @Type + ''';' +SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121); +RAISERROR('%s: %s', 0, 1, @TimeStamp, @SQL) WITH NOWAIT; + +IF (@Debug = 0) +EXEC sp_executesql @SQL; + +IF (@Count != 0) +BEGIN + SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121); + RAISERROR('%s: Recreating foreign keys.', 0, 1, @TimeStamp) WITH NOWAIT; + -- Recreate foreign key constraints with ON DELETE and ON UPDATE actions + DECLARE Create_FK_Cursor CURSOR FOR + SELECT FKName, FKSchema, FKTableName, FKColumnName, DeleteAction, UpdateAction + FROM #ForeignKeys + ORDER BY FKName; + + OPEN Create_FK_Cursor; + FETCH NEXT FROM Create_FK_Cursor INTO @FKName, @FKSchema, @FKTableName, @FKColumnName, @DeleteText, @UpdateText; + + WHILE @@FETCH_STATUS = 0 + BEGIN + -- Recreate FK constraint with the specific ON DELETE and ON UPDATE actions + SET @SQL = 'ALTER TABLE [' + @FKSchema + '].[' + @FKTableName + '] ADD CONSTRAINT [' + @FKName + '] FOREIGN KEY (' + @FKColumnName + ') REFERENCES [' + @Schema + '].[' + @TableName + ']([' + @ColumnName + ']) ON DELETE ' + @DeleteText + ' ON UPDATE ' + @UpdateText; + SET @TimeStamp = CONVERT(VARCHAR, GETDATE(), 121); + RAISERROR('%s: %s', 0, 1, @TimeStamp, @SQL) WITH NOWAIT; + + IF (@Debug = 0) + EXEC sp_executesql @SQL; + + FETCH NEXT FROM Create_FK_Cursor INTO @FKName, @FKSchema, @FKTableName, @FKColumnName, @DeleteText, @UpdateText; + END + + CLOSE Create_FK_Cursor; + DEALLOCATE Create_FK_Cursor; +END + +END +GO + + +--------------------------------------------- + +-- dbo.procConvertSecureListMemberValues +-- ============================================= +-- Author: +-- Create date: +-- Description: +-- ============================================= +CREATE PROCEDURE [dbo].[procConvertSecureListMemberValues] +@listguid uniqueidentifier, +@valueindex int, +@sourceType int, +@targetType int +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; +--set @listguid = 'F7CDA86B-F23E-40A1-B081-0B46772591A7' +--set @valueindex = 0 +--set @sourceType = 0 +--set @targettype = 1 + +If (@sourceType<>0 AND @sourceType<>1) +BEGIN +Print 'Error: SourceType can only be 0 or 1: Text = 0 or Numeric = 1' +RETURN +END + +If (@targetType<>0 AND @targetType<>1) +BEGIN +Print 'Error: targetType can only be 0 or 1: Text = 0 or Numeric = 1' +RETURN +END + +If (@sourceType = @targetType) +BEGIN +Print 'Error: sourcetype and targettype shouldn''t be the same. ' +RETURN +END + + +If (@sourceType = 0) +BEGIN +UPDATE dbo.[SecureListMemberValue] +SET +VALUEFLOAT = ( +CASE ISNUMERIC(VALUETEXT) +WHEN 1 THEN Cast(VALUETEXT AS float) +ELSE 0 +END +), +VALUETEXT = '', +[TYPE] = @targetType +Where LISTGUID = @listguid and VALUEINDEX = @valueindex and [TYPE] = @sourceType +END + +If (@sourceType = 1) +BEGIN + UPDATE dbo.SecureListMemberValue + SET +VALUETEXT = VALUEFLOAT, + VALUEFLOAT = 0, +[TYPE] = @targetType + Where LISTGUID = @listguid and VALUEINDEX = @valueindex and TYPE = @sourceType +END + + + +END +GO + + +--------------------------------------------- + +-- dbo.procCopyFrameworkDatabaseObjects +create procedure [dbo].[procCopyFrameworkDatabaseObjects] +( + @FrameworkSchema nvarchar(128), + @TargetDatabase nvarchar(512), + @IsIncludeMembers bit, + @IsDebugOnly bit = 0 +) +AS + +DECLARE @Guid uniqueidentifier +DECLARE @Name nvarchar(128) + +--Step 1: +-- COPY ALL COMPOSITES +declare crsComposite CURSOR FAST_FORWARD FOR + select C.CompositeGUID, C.FriendlyName from dbo.ScoreComposite C + left join dbo.ScoreDataTable D1 on D1.DataTableGuid = C.DataTableGUID1 + left join dbo.ScoreDataTable D2 on D2.DataTableGuid = C.DatatableGUID2 + WHERE D1.SqlSchemaName = @FrameworkSchema OR D2.SqlSchemaName = @FrameworkSchema +open crsComposite; + +FETCH NEXT FROM crsComposite into @Guid, @Name +WHILE (@@FETCH_STATUS = 0) + BEGIN + exec dbo.procScoreCopyComposite @Guid, @TargetDatabase, @IsIncludeMembers,@IsDebugOnly + FETCH NEXT FROM crsComposite into @Guid, @Name + END +close crsComposite; +DEALLOCATE crsComposite; + + +--Step 2: +-- COPY ALL DATATABLES (in case we missed any) +declare crsDataTable CURSOR FAST_FORWARD FOR + select DataTableGUID, FriendlyName from dbo.ScoreDataTable + where SQLSchemaName = @FrameworkSchema +open crsDataTable; + +FETCH NEXT FROM crsDataTable into @Guid, @Name +WHILE (@@FETCH_STATUS = 0) + BEGIN + exec dbo.procScoreCopyDataTable @Guid, @TargetDatabase, @IsIncludeMembers,@IsDebugOnly + FETCH NEXT FROM crsDataTable into @Guid, @Name + END +close crsDataTable; +DEALLOCATE crsDataTable; + +--Step 3: +-- COPY ALL DIMENSIONS (In case we missed any) +declare crsDimension CURSOR FAST_FORWARD FOR + select DimensionGUID, FriendlyName from dbo.ScoreDimension + where SQLSchemaName = @FrameworkSchema +open crsDimension; + +FETCH NEXT FROM crsDimension into @Guid, @Name +WHILE (@@FETCH_STATUS = 0) + BEGIN + exec dbo.procScoreCopyDimension @Guid, @TargetDatabase, @IsIncludeMembers,@IsDebugOnly + FETCH NEXT FROM crsDimension into @Guid, @Name + END +close crsDimension; +DEALLOCATE crsDimension; +GO + + +--------------------------------------------- + +-- dbo.procCopySimpleSecurity +CREATE proc [dbo].[procCopySimpleSecurity] + @SourceEntityGUID uniqueidentifier, + @TargetEntityGUID uniqueidentifier, + @CleanTargetEntitySecurity bit = 0 +as + +if @CleanTargetEntitySecurity = 1 + delete from S3SimplePermission where LootID = @TargetEntityGUID +else + delete from S3SimplePermission where LootID = @TargetEntityGUID + and IdentityGUID in ( + select IdentityGUID from S3SimplePermission where LootID = @SourceEntityGUID + ) + +insert into S3SimplePermission + (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) +select + @TargetEntityGUID, + ACL.IdentityGUID, + ACL.ReadValue, + ACL.WriteValue, + ACL.SecureValue +from + S3SimplePermission ACL +where + ACL.LootID = @SourceEntityGUID +GO + + +--------------------------------------------- + +-- dbo.procCreateTask +CREATE PROCEDURE [dbo].[procCreateTask] + @taskTypeName VARCHAR(1000), + @contextXML NVARCHAR(MAX), + @userName VARCHAR(100) = 'Strata', + @statusCode INT OUTPUT, + @taskSource VARCHAR(500) = 'HangfireController' +AS +BEGIN + + DECLARE @baseUrl VARCHAR(200); + SELECT @baseUrl = dbo.GetHangfireApiEndpoint(); + + DECLARE @url AS VARCHAR(2083) = @baseUrl + '/Jobs'; + + DECLARE @databaseGUID UNIQUEIDENTIFIER; + /* Old block + EXEC dbo.procSMCGetDatabaseGUID @ReturnVal = @DatabaseGUID OUTPUT; + IF (@databaseGUID IS NULL) + BEGIN + RAISERROR('Unable to determine SMC Database GUID, check to ensure your SMC database settings are correct.', 18, 0); + RETURN; + END; + */ + + -- New block + if exists (select 1 from DBSetting where name = 'dbguid_cache') + select @databaseGUID=setting from DBSetting where name = 'dbguid_cache' + else + begin + EXEC dbo.procSMCGetDatabaseGUID @ReturnVal = @databaseGUID OUTPUT; + IF (@databaseGUID IS NULL) + BEGIN + RAISERROR('Unable to determine SMC Database GUID, check to ensure your SMC database settings are correct.', 18, 0); + RETURN; + END + else + exec dbo.procChangeDBSetting 'dbguid_cache', @databaseGUID; + end + + -- end new block + + DECLARE @auth VARCHAR(100) = 'Hangfire ' + CAST(@databaseGUID AS VARCHAR(36)); + + DECLARE @body AS VARCHAR(MAX); + + SET @body = + ( + + SELECT @taskTypeName AS TaskName + , @databaseGUID AS DatabaseGuid + , '10101010-1111-0000-1111-101010101010' AS UserGuid + , @userName AS UserName + , @contextXML AS ContextData + , @taskSource AS TaskSource + FOR JSON PATH, WITHOUT_ARRAY_WRAPPER + ); + + + DECLARE @statusText NVARCHAR(1000); + DECLARE @responseText VARCHAR(1000); + EXEC dbo.procCallRestApi + @url = @url, + @method = 'POST', + @body = @body, + @authorization = @auth, + @responseText = @responseText OUTPUT, + @statusCode = @statusCode OUTPUT, + @statusText = @statusText OUTPUT; + +END; +GO + + +--------------------------------------------- + +-- dbo.procCreateTokenForUser +CREATE PROC [dbo].[procCreateTokenForUser] + @username VARCHAR(MAX) +AS + DECLARE @userguid UNIQUEIDENTIFIER + SELECT @userguid = userguid FROM userprofile WHERE username = @username + + DECLARE @cnt INT + SELECT @cnt = COUNT(*) FROM CurrentUser WHERE tokenguid = @userguid + + IF @cnt = 0 BEGIN + INSERT INTO CurrentUser (tokenguid, userguid, ipaddress, loginstamputc, lastactionstamputc, username) + VALUES (@userguid, @userguid, '127.0.0.1', GETUTCDATE(), '2020-01-01', @username) + END + PRINT @userguid +GO + + +--------------------------------------------- + +-- dbo.procCreatezzFactTableIndex +CREATE PROCEDURE [dbo].[procCreatezzFactTableIndex] +@zzTableName nvarchar(256) +AS +DECLARE @sql nvarchar(1204) +SET @sql =' + IF EXISTS (SELECT name FROM sys.indexes WHERE name = ''HistoryItemGUID'' + AND object_id = (SELECT object_id(''' + @zzTableName + ''') ) ) + BEGIN + CREATE NONCLUSTERED INDEX [HistoryItemGUID] ON ' + @zzTableName + ' + ( + [HISTORYITEMGUID] ASC + ) + WITH DROP_EXISTING + END + ELSE + BEGIN + CREATE NONCLUSTERED INDEX [HistoryItemGUID] ON ' + @zzTableName + ' + ( + [HISTORYITEMGUID] ASC + ) + END +' +EXEC sp_executesql @sql +GO + + +--------------------------------------------- + +-- dbo.procCustomScriptGet +CREATE proc [dbo].[procCustomScriptGet] + @customScriptGUID uniqueidentifier, + @encode bit = 0 +as + declare @script nvarchar(max) + select @script = ScriptText from CustomScript where CustomScriptGUID = @customScriptGUID + if(@encode = 1) begin + select @script = REPLACE(@script, '''', '''''') + end + + if(LEN(@script) > 4000) begin + print '*********************************************************************************************************************' + print 'WARNING: SCRIPT LENGTH EXCEEDS 4000 CHARACTERS - PRINT OUT CONTAINS EXTRA LINE BREAKS THAT MAY BREAK THE SCRIPT' + print '*********************************************************************************************************************' + print '' + end + + declare @pos int + set @pos = 0 + while(@pos < len(@script)) begin + print substring(@script, @pos, @pos + 4000) + set @pos = @pos + 4000 + end +GO + + +--------------------------------------------- + +-- dbo.procCustomScriptSet +create proc procCustomScriptSet + @customScriptGUID uniqueidentifier, + @scriptText nvarchar(max) +as + update CustomScript set ScriptText = @scriptText where CustomScriptGUID = @customScriptGUID +GO + + +--------------------------------------------- + +-- dbo.procDIRefreshClientField +CREATE PROCEDURE [dbo].[procDIRefreshClientField] +( + @ConfigID uniqueidentifier +) +AS +begin + update isfd + set isfd.ClientField = dbo.intGetTransformationSourceField(isfd.SourceColumnId) + from IntDataInterfaceField f1 + join IntDataInterfaceSection dis on dis.DataInterfaceSectionID=f1.DataInterfaceSectionID + join IntDataInterface dif on dis.DataInterfaceID=dif.DataInterfaceID + join IntConfig ic on ic.DataInterfaceID=dif.DataInterfaceID and ic.IsHidden = 0 + join IntTransformation it on it.ConfigID=ic.ConfigID + cross apply intGetTransformationSourceFileList(it.TransformationID) tsfl + join IntSourceFile isf on isf.SourceFileID = tsfl.SourceFileID + join IntDataInterfaceMap idm on f1.DataInterfaceFieldID=idm.DataInterfaceFieldID + join IntSourceField isfd on isfd.DataSourceID=it.TransformationID and idm.SourceColumnID=isfd.SourceColumnID + where f1.IsHidden = 0 and ic.ConfigID=@ConfigID +end +GO + + +--------------------------------------------- + +-- dbo.procDashboardInvalidateCacheByAttributeGUID +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-01-28 HV JAZZ-29025 Fiscal Time Period - Count from Current Month +*************************************************************/ +CREATE PROCEDURE [dbo].[procDashboardInvalidateCacheByAttributeGUID] + @attributeGUID uniqueidentifier +AS + +DELETE c FROM dbo.DashboardWidgetCache c +INNER JOIN ( + SELECT DISTINCT w.DashboardWidgetGUID + FROM dbo.DashboardWidget w + INNER JOIN dbo.DataView dv on dv.dataviewguid = w.datasourceguid + INNER JOIN dbo.RESqlReportRegisteredDimension rd ON rd.DataViewGUID=dv.DataViewGUID + INNER JOIN dbo.RESQLReportRegisteredAttribute a ON rd.RegisteredDimensionGUID = a.RegisteredDimensionGUID + WHERE a.AttributeGuid = @attributeGuid) t +ON t.DashboardWidgetGUID = c.DashboardWidgetGUID +GO + + +--------------------------------------------- + +-- dbo.procDashboardInvalidateCacheByFrameworkID +CREATE PROC dbo.procDashboardInvalidateCacheByFrameworkID + @frameworkId int +AS + +delete from DashboardWidgetCache +where DesktopTemplateGUID in ( + select DesktopTemplateGUID + from DashboardWidget w + inner join dataview dv on dv.dataviewguid = w.datasourceguid + inner join fw.DimFramework f on dv.FrameworkGUID = f.MemberGUID + where f.FrameworkID = @frameworkId) +GO + + +--------------------------------------------- + +-- dbo.procDashboardInvalidateCacheByReportGUID +CREATE PROC dbo.procDashboardInvalidateCacheByReportGUID + @reportGUID uniqueidentifier +AS + +-- remove all cache for dashboards that contain this report +delete from DashboardWidgetCache +where DesktopTemplateGUID in ( + select DesktopTemplateGUID + from DashboardWidget + where WidgetJSON like '%' + cast(@reportGUID as nvarchar(36)) + '%' +) +GO + + +--------------------------------------------- + +-- dbo.procDashboardInvalidateCacheForCube +CREATE PROC dbo.procDashboardInvalidateCacheForCube + +AS + delete from DashboardWidgetCache + where DesktopTemplateGUID in ( + select DesktopTemplateGUID + from DashboardWidget w inner join EMFCubeStub c on w.DataSourceGUID = c.CubeGUID) +GO + + +--------------------------------------------- + +-- dbo.procDataPathCopyFile +--select * from datapathfile + +CREATE proc [dbo].[procDataPathCopyFile] + @originalFileGUID uniqueidentifier, + @newfullpath varchar(max) +as + +delete from DataPathFile where FullPath = @newfullpath +insert into DataPathFile(FileGUID,FullPath,FileName,CreationTime,LastModifiedTime,Data) select NEWID() as fileguid, @newfullpath, '', GETDATE(), GETDATE(), data from DataPathFile where FileGUID = @originalFileguid + +delete from DataPathFile_History where FullPath = @newfullpath +insert into DataPathFile_History(FileGUID,FullPath,FileName,CreationTime,LastModifiedTime,Data) select NEWID() as fileguid, @newfullpath, '', GETDATE(), GETDATE(), data from DataPathFile_History where FileGUID = @originalFileguid + +delete from DataPathFile_Improv where FullPath = @newfullpath +insert into DataPathFile_Improv(FileGUID,FullPath,FileName,CreationTime,LastModifiedTime,Data) select NEWID() as fileguid, @newfullpath, '', GETDATE(), GETDATE(), data from DataPathFile_Improv where FileGUID = @originalFileguid + +delete from DataPathFile_ModelTemplate where FullPath = @newfullpath +insert into DataPathFile_ModelTemplate(FileGUID,FullPath,FileName,CreationTime,LastModifiedTime,Data) select NEWID() as fileguid, @newfullpath, '', GETDATE(), GETDATE(), data from DataPathFile_ModelTemplate where FileGUID = @originalFileguid + +delete from DataPathFile_Reporting where FullPath = @newfullpath +insert into DataPathFile_Reporting(FileGUID,FullPath,FileName,CreationTime,LastModifiedTime,Data) select NEWID() as fileguid, @newfullpath, '', GETDATE(), GETDATE(), data from DataPathFile_Reporting where FileGUID = @originalFileguid +GO + + +--------------------------------------------- + +-- dbo.procDataPathDeleteStale +CREATE proc [dbo].[procDataPathDeleteStale] as + + +delete dpf +from + DataPathFile_Improv dpf +where + FullPath like 'ImprovWorkbook%' + and not exists ( + select 1 + from + XPlan obj + where + cast(obj.PlanGUID as varchar(36)) = SUBSTRING(dpf.FullPath,LEN('ImprovWorkbook')+1,36) + ) + + + +delete dpf +from + DataPathFile_History dpf +where + FullPath like 'History\%' + and not exists ( + select 1 + from + HistoryItem hi + where + cast(hi.HISTORYITEMGUID as varchar(36)) = SUBSTRING(dpf.FullPath,LEN('History\')+1,36) + ) + +delete dpf +from + DataPathFile_ModelTemplate dpf +where + FullPath like 'ModelTemplateHistory\%' + and not exists ( + select 1 + from + EMFModelTemplate mt + where + cast(mt.ModelTemplateGUID as varchar(36)) = SUBSTRING(dpf.FullPath,LEN('ModelTemplateHistory\')+1,36) + ) + + +delete dpf +from + DataPathFile_ModelTemplate dpf +where + FullPath like 'ModelTemplates\%' + and not exists ( + select 1 + from + EMFModelTemplate mt + where + cast(mt.ModelTemplateGUID as varchar(36)) = SUBSTRING(dpf.FullPath,LEN('ModelTemplates\')+1,36) + ) +GO + + +--------------------------------------------- + +-- dbo.procDataPathObtainLock +CREATE procedure [dbo].[procDataPathObtainLock] ( + @FullPath varchar(max), + @MaxLockSeconds int = 30, -- by default, you can only hold a lock for 30 seconds before stolen + @OwnerID uniqueidentifier = '00000000-0000-0000-0000-000000000000' +) +AS +BEGIN + +declare @ObtainedLocked bit; + +if(@FullPath like 'History%') begin + update DataPathFile_History WITH (updlock, rowlock, readpast) set IsLocked = 1, LockTime = GETDATE(), LockOwner = @OwnerID + where + (FullPath = @FullPath AND IsLocked = 0) + OR + (FullPath = @FullPath AND IsLocked = 1 AND ABS(DATEDIFF(second, getdate(), LockTime)) > @MaxLockSeconds) + OR + (FullPath = @FullPath AND IsLocked = 1 AND LockOwner = @OwnerID); --same owner relocking +end else begin + if(@FullPath like 'Improv%') begin + update DataPathFile_Improv WITH (updlock, rowlock, readpast) set IsLocked = 1, LockTime = GETDATE() , LockOwner = @OwnerID + where + (FullPath = @FullPath AND IsLocked = 0) + OR + (FullPath = @FullPath AND IsLocked = 1 AND ABS(DATEDIFF(second, getdate(), LockTime)) > @MaxLockSeconds) + OR + (FullPath = @FullPath AND IsLocked = 1 AND LockOwner = @OwnerID); --same owner relocking + end else begin + if(@FullPath like 'ModelTemplate%') begin + update DataPathFile_ModelTemplate WITH (updlock, rowlock, readpast) set IsLocked = 1, LockTime = GETDATE() , LockOwner = @OwnerID + where + (FullPath = @FullPath AND IsLocked = 0) + OR + (FullPath = @FullPath AND IsLocked = 1 AND ABS(DATEDIFF(second, getdate(), LockTime)) > @MaxLockSeconds) + OR + (FullPath = @FullPath AND IsLocked = 1 AND LockOwner = @OwnerID); --same owner relocking + end else begin + if(@FullPath like 'Reporting%') begin + update DataPathFile_Reporting WITH (updlock, rowlock, readpast) set IsLocked = 1, LockTime = GETDATE(), LockOwner = @OwnerID + where + (FullPath = @FullPath AND IsLocked = 0) + OR + (FullPath = @FullPath AND IsLocked = 1 AND ABS(DATEDIFF(second, getdate(), LockTime)) > @MaxLockSeconds) + OR + (FullPath = @FullPath AND IsLocked = 1 AND LockOwner = @OwnerID); --same owner relocking + end else begin + update DataPathFile WITH (updlock, rowlock, readpast) set IsLocked = 1, LockTime = GETDATE(), LockOwner = @OwnerID + where + (FullPath = @FullPath AND IsLocked = 0) + OR + (FullPath = @FullPath AND IsLocked = 1 AND ABS(DATEDIFF(second, getdate(), LockTime)) > @MaxLockSeconds) + OR + (FullPath = @FullPath AND IsLocked = 1 AND LockOwner = @OwnerID); --same owner relocking + end + end + end +end + +declare @RowsAffected int; +select @RowsAffected = @@ROWCOUNT; + +if (@RowsAffected = 1) +begin + set @ObtainedLocked = 1 +end +else +begin + set @ObtainedLocked = 0 +end +select @ObtainedLocked; + +END +GO + + +--------------------------------------------- + +-- dbo.procDataPathReleaseLock +CREATE procedure [dbo].[procDataPathReleaseLock] ( + @FullPath varchar(max) +) +AS +BEGIN + update DataPathFile WITH (updlock, rowlock, readpast) set IsLocked = 0, LockOwner = dbo.ZeroGUID() where FullPath = @FullPath AND IsLocked = 1; + if(@FullPath like 'History%') begin update DataPathFile_History WITH (updlock, rowlock, readpast) set IsLocked = 0, LockOwner = dbo.ZeroGUID() where FullPath = @FullPath AND IsLocked = 1 end; + if(@FullPath like 'Improv%') begin update DataPathFile_Improv WITH (updlock, rowlock, readpast) set IsLocked = 0, LockOwner = dbo.ZeroGUID() where FullPath = @FullPath AND IsLocked = 1 end; + if(@FullPath like 'ModelTemplate%') begin update DataPathFile_ModelTemplate WITH (updlock, rowlock, readpast) set IsLocked = 0, LockOwner = dbo.ZeroGUID() where FullPath = @FullPath AND IsLocked = 1 end; + if(@FullPath like 'Reporting%') begin update DataPathFile_Reporting WITH (updlock, rowlock, readpast) set IsLocked = 0, LockOwner = dbo.ZeroGUID() where FullPath = @FullPath AND IsLocked = 1 end; +END +GO + + +--------------------------------------------- + +-- dbo.procDeactivateInactiveUsers +CREATE PROC [dbo].[procDeactivateInactiveUsers] +AS + SET NOCOUNT ON + + IF (EXISTS(SELECT 1 FROM [dbo].[DBSetting] WHERE Name = 'SECURITY_USERDEACTIVATEDAYS' AND Setting != '-1')) + BEGIN + DECLARE @expiredays INT + SELECT @expiredays = CAST(Setting AS INT) FROM [dbo].[DBSetting] WHERE Name = 'SECURITY_USERDEACTIVATEDAYS' + + UPDATE u SET u.IsDisabled = 1 + FROM [dbo].[UserProfile] u + WHERE @expiredays < DATEDIFF(day, ISNULL((SELECT MAX(LoginStamp) FROM [dbo].[LoginHistory] h WHERE h.UserGUID = u.UserGUID), u.LastChangedPasswordUtc AT TIME ZONE 'UTC' AT TIME ZONE 'Central Standard Time'), GETDATE()) + END +GO + + +--------------------------------------------- + +-- dbo.procDeleteUpdatedClinicalIndicatorEncounters +CREATE PROCEDURE [dbo].[procDeleteUpdatedClinicalIndicatorEncounters] + @transactionguid uniqueidentifier +AS + +CREATE TABLE #ClinicalIndicatorEncounters (EncounterID bigint primary key NOT NULL DEFAULT (0)) + +INSERT INTO #ClinicalIndicatorEncounters (EncounterID) +SELECT EncounterID +FROM [clientdss].[FactPatientEncounterSummary] +WHERE HistoryItemGUID = @transactionguid + +CREATE TABLE #Deleted (RowID int); + +WHILE (1 = 1) +BEGIN + + DELETE top (5000) dss.FactPatientEncounterClinicalIndicator + OUTPUT deleted.RowID into #Deleted + FROM dss.FactPatientEncounterClinicalIndicator + WHERE EncounterID IN (SELECT CIE.EncounterID FROM #ClinicalIndicatorEncounters CIE) + + if ((SELECT COUNT(*) FROM #Deleted) = 0) + BEGIN + BREAK; + END + + delete from #Deleted; + +END--ENDWHILE + +DROP TABLE #Deleted; + + + +RETURN +GO + + +--------------------------------------------- + +-- dbo.procDemoAssignRandomAuthor +create proc procDemoAssignRandomAuthor + @lootgroupid nvarchar(128) +as + +declare @randomUserGUID uniqueidentifier +declare @authorRoleID smallint +select @authorRoleID = roleid from userrole where type = 1 + +select top 1 @randomuserGUID= userguid from userprofile +where authid = '' +and namelast not like 'zstrata%' +order by newid() + +exec dbo.[procS3ClearAssignmentByLootGroupRole] @lootgroupid, @authorRoleID +exec dbo.procS3AssignIdentityToSpecialRole @randomUserGUID, 1, @lootgroupid +GO + + +--------------------------------------------- + +-- dbo.procDepreciate +CREATE proc procDepreciate + @amount money + ,@amountYear int + ,@usefulLife int + ,@inserviceYear int + ,@inserviceMonth int +as + +create table #out (year int, amount money) + +if @inserviceYear < @amountYear set @inserviceYear = @amountYear + +declare @resultYear int +set @resultYear = @inserviceYear + +while @resultYear <= @inserviceYear + @usefulLife begin + insert into #out (year, amount) + values (@resultYear, dbo.GetDepreciationPart(@amount,@amountYear,@usefulLife, @inserviceYear, @inserviceMonth, @resultYear)) + + set @resultYear = @resultYear + 1 +end + +select * from #out +GO + + +--------------------------------------------- + +-- dbo.procDirectoryAddEntry +CREATE PROCEDURE dbo.procDirectoryAddEntry +( +@planGUID AS UNIQUEIDENTIFIER, +@planTypeGUID AS UNIQUEIDENTIFIER, +@schemaName AS NVARCHAR(64) = 'data' +) +AS + --this procedure is obsolete given FE20, but still exists for backwards compatibility + RETURN +GO + + +--------------------------------------------- + +-- dbo.procDirectoryCacheClean +CREATE proc procDirectoryCacheClean + @clean bit = 0 +as + declare @name varchar(128) + + --old cache tables + declare crsCache cursor for select name from sys.tables where name like 'DirectoryCache%' + open crsCache + fetch next from crsCache into @name + while(@@FETCH_STATUS = 0) begin + if(@clean = 0) begin + print 'data.' + @name + end else begin + declare @sql varchar(4000) + set @sql = 'drop table data.' + @name + exec(@sql) + end + + fetch next from crsCache into @name + end + close crsCache + deallocate crsCache + + --old cache views + declare crsView cursor for select name from sys.views where name like 'viewDirectoryCache_%' + open crsView + fetch next from crsView into @name + while(@@FETCH_STATUS = 0) begin + if((select count(*) from PlanType where replace(replace(replace(replace(REPLACE(Name, ' ', ''), '.', ''), '(', ''), ')', ''), '-', '') = REPLACE(@name, 'viewDirectoryCache_', '')) = 0) begin + if(@clean = 0) begin + print 'data.' + @name + end else begin + declare @sql2 varchar(4000) + set @sql2 = 'drop view data.' + @name + exec(@sql2) + end + end + + fetch next from crsView into @name + end + close crsView + deallocate crsView +GO + + +--------------------------------------------- + +-- dbo.procDirectoryRefreshField +CREATE PROCEDURE [dbo].[procDirectoryRefreshField] + @planTypeGUID as uniqueidentifier, + @formFieldGUID uniqueidentifier, + @isForRebuild bit = 0, + @debug bit = 0, + @entityexpression nvarchar(max) = '' +AS + --this procedure is obsolete given FE20, but still exists for backwards compatibility + RETURN +GO + + +--------------------------------------------- + +-- dbo.procDirectoryRefreshFieldAll +CREATE PROCEDURE [dbo].[procDirectoryRefreshFieldAll] + @planTypeGUID as uniqueidentifier, + @isForRebuild bit = 0, + @debug bit = 0, + @entityexpression nvarchar(max) = '' +AS + --this procedure is obsolete given FE20, but still exists for backwards compatibility + RETURN +GO + + +--------------------------------------------- + +-- dbo.procDropCLRAssembly +CREATE PROCEDURE dbo.procDropCLRAssembly + @asmname NVARCHAR(1000) + -- Add the parameters for the stored procedure here +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + + --First we need to drop all the Wrapper objects that are dependent on the Assembly which include CLR { Aggregates, Scalars, Stored Procedures, Table Value Functions & Triggers } + DECLARE @d_sql NVARCHAR(MAX); + DECLARE @drop_type VARCHAR(100) + + + -- CURSOR VARIABLES -- + + DECLARE @wname NVARCHAR(1000); + DECLARE @wtype NVARCHAR(1000); + + -- CURSOR VARIABLES (END) -- + + DECLARE dCursor CURSOR FAST_FORWARD FOR + SELECT '[' + ss.name + '].[' + o.name + ']' AS wraper_name, o.type + FROM sys.assembly_modules am + JOIN sys.objects o ON am.object_id = o.object_id + JOIN sys.assemblies sas ON sas.assembly_id = am.assembly_id + JOIN sys.schemas ss ON ss.schema_id = o.schema_id + WHERE sas.name = @asmname + + OPEN dCursor + + FETCH NEXT FROM dCursor INTO @wname, @wtype + + WHILE @@FETCH_STATUS = 0 + BEGIN + + SET @drop_type = ''; + + IF @wtype IN ('PC', 'P') + SELECT @drop_type = 'PROCEDURE' + + IF @wtype IN ('FN', 'FS', 'FT', 'IF', 'TF') + SELECT @drop_type = 'FUNCTION' + + IF @wtype = 'AF' + SELECT @drop_type = 'AGGREGATE' + + IF @wtype = 'U' + SELECT @drop_type = 'TABLE' + + IF @wtype = 'V' + SELECT @drop_type = 'VIEW' + + IF @drop_type <> '' + BEGIN + SET @d_sql = 'DROP '+ @drop_type + ' ' + @wname + EXEC(@d_sql); + END + + FETCH NEXT FROM dCursor INTO @wname, @wtype + END + + CLOSE dCursor + DEALLOCATE dCursor + + --Finally drop the Assembly + SET @d_sql = N'IF EXISTS (SELECT * FROM sys.assemblies asms WHERE asms.name = ''' + @asmname + ''' AND is_user_defined = 1) DROP ASSEMBLY ['+ @asmname +']' + + EXEC(@d_sql) + +END +GO + + +--------------------------------------------- + +-- dbo.procDropIndexesByQuery +create proc [dbo].procDropIndexesByQuery + @tablename sysname, + @query nvarchar(max) +as + +-- name: sp_drop_constraints +-- author: douglas bass +-- date: 06/19/2000 + +-- sp_drop_constraints will drop all constraints on the specified table, +-- including CHECK, FOREIGN KEY, PRIMARY KEY, UNIQUE, and DEFAULT constraints. +-- Compile it in your master database and use it from any user database. + +set nocount on + +declare @constname sysname, + @cmd varchar(1024) + +declare curs_constraints cursor LOCAL FAST_FORWARD for + select name + from sys.indexes + where + type = 2 + and object_id = object_id(@tablename) + and name like @query + +open curs_constraints + +fetch next from curs_constraints into @constname +while (@@fetch_status = 0) +begin + select @cmd = 'DROP INDEX ' + @tablename + '.' + @constname + --print @cmd + exec(@cmd) + fetch next from curs_constraints into @constname +end + +close curs_constraints +deallocate curs_constraints + +return 0 +GO + + +--------------------------------------------- + +-- dbo.procDropzzFactTableIndex +CREATE PROCEDURE [dbo].[procDropzzFactTableIndex] +@zzTableName nvarchar(256) +AS +DECLARE @sql nvarchar(1204) +SET @sql =' + IF EXISTS (SELECT name FROM sys.indexes WHERE name = ''HistoryItemGUID'' + AND object_id = (SELECT object_id(''' + @zzTableName + ''') ) ) + BEGIN + DROP INDEX [HistoryItemGUID] ON ' + @zzTableName + ' WITH (ONLINE = OFF) + END +' +Exec sp_executesql @sql +GO + + +--------------------------------------------- + +-- dbo.procEMFBlastFormulas +CREATE proc procEMFBlastFormulas + @modelguid uniqueidentifier + ,@measureguid uniqueidentifier +as + +/* +exec procEMFBlastFormulas '00000000-0000-0000-0000-000000000000','00000000-0000-0000-0000-000000000000' +*/ + +declare @mtguid uniqueidentifier +select @mtguid = modeltemplateguid from xplan where planguid = @modelguid + +declare @mdcguid uniqueidentifier +declare @zztable varchar(max) +declare @sql varchar(max) + +DECLARE mdc CURSOR LOCAL FAST_FORWARD +FOR + select + distinct + case when parentmodeldataconfigguid = '00000000-0000-0000-0000-000000000000' then st.modeldataconfigguid + else parentmodeldataconfigguid + end as ModelDataConfigGUID + from + emfmodeltemplatelinksource ls + left join emfsubtable st on ls.parentsubtableguid = st.subtableguid + inner join emfmodeldatalink mls on ls.linksourceguid = mls.linksourceguid + where + modeltemplateguid = @mtguid + and mls.modelguid = mls.parentmodelguid --only self linked are valid + +OPEN mdc +FETCH NEXT FROM mdc INTO @mdcguid +WHILE @@FETCH_STATUS = 0 +BEGIN + + set @zztable = 'zzEMFModelData_' + replace(cast(@mdcguid as varchar(36)),'-','_') + + set @sql = 'UPDATE ' + @zztable + ' SET Formula = cast(Value as money), StringValue = cast(value as money) WHERE MeasureGUID = ''' + cast(@measureguid as varchar(36)) + ''' AND (formula <> cast(value as money) or stringvalue <> cast(value as money)) AND ModelGUID = ''' + cast(@modelguid as varchar(36)) + '''' + + exec(@sql) + + FETCH NEXT FROM mdc INTO @mdcguid +END +CLOSE mdc +DEALLOCATE mdc +GO + + +--------------------------------------------- + +-- dbo.procEMFClearOrphanedPlaceholderLabelMappings +create proc procEMFClearOrphanedPlaceholderLabelMappings as +delete plm from EMFModelTemplatePlaceholderLabelMapping plm +where not plm.PlaceholderMemberGUID in (select listmemberguid from SecureListMember slm where slm.ListGUID = plm.PlaceholderDimensionGUID) +GO + + +--------------------------------------------- + +-- dbo.procEMFCreatePlanEmptyFillins +create proc procEMFCreatePlanEmptyFillins as +insert into emffillin (modelguid, placeholdermemberguid, filledinmemberguid,issetbyuser) +select planguid, '00000000-0000-0000-0000-000000000000', '00000000-0000-0000-0000-000000000000', 1 from xplan +where not exists +(select 1 from emffillin where emffillin.modelguid = planguid and placeholdermemberguid = '00000000-0000-0000-0000-000000000000' and filledinmemberguid = '00000000-0000-0000-0000-000000000000') +GO + + +--------------------------------------------- + +-- dbo.procEMFFillInAdd +--CREATE FUNCTION [dbo].[GetFillinMembersMissing] +-- (@modelGUID uniqueidentifier, @placeholderDimensionGUID uniqueidentifier, @maxIndex int) +--RETURNS +-- @fillInMemberGUIDS TABLE ( guid uniqueidentifier) +--AS +--BEGIN +CREATE proc [dbo].[procEMFFillInAdd] + @modelGUID uniqueidentifier + ,@placeholderDimensionGUID as uniqueidentifier --ph + ,@maxIndex int +as + +/* + test 2 + set @placeholderDimensionGUID = '17FEAA4B-A2A2-4353-B081-03E3DFB5CB77' + set @modelGUID = '9C5BFBD1-4DF4-4223-B4C3-D013809261AC' + + declare @maxIndex int + set @maxIndex = 4 + --declare @minIndex int +*/ +--delete fillins past index @maxIndex + declare @firstMemberGUID uniqueidentifier + select @firstMemberGUID = dbo.getModelFirstFillIn(@modelGUID, @placeholderDimensionGUID) + + --get out of here if we dont have a base fillin, we cant know where to start + -- starting at the beginning is kind of dangerous + if @firstMemberGUID = '00000000-0000-0000-0000-000000000000' return + + select + --modelguid,dbo.getplanname(modelguid), + row_number() over (order by slm.sortorderfullpath) as RowNum, + listmemberguid + into #members + from + securelistmember slm + where + exists( + select 1 + from + securelistmember slm2 + where + slm2.listguid = slm.listguid + and slm2.parentlistmemberguid = slm.parentlistmemberguid + and slm2.listmemberguid = @firstMemberGUID + ) + + declare @firstRowNum int + select @firstRowNum = rownum from #members where listmemberguid = @firstmemberguid + + + DECLARE fillins CURSOR LOCAL FAST_FORWARD FOR + select + listmemberguid as FillInGUID + from + #members + where + rownum between @firstRowNum and (@firstRowNum + @maxIndex -1) + and not exists ( + select 1 + from + emffillin + where + filledinmemberguid = listmemberguid + and modelguid = @modelguid + ) + order by rownum + + declare @fillInMemberGUID uniqueidentifier + + OPEN fillins + FETCH NEXT FROM fillins INTO @fillInMemberGUID + WHILE @@FETCH_STATUS = 0 + BEGIN + --exec procEMFFillInSetByIndex @PHDimensionGUID, @ParentPHMemberGUID, @index, @FillInGUID, @ModelGUID + print @fillInMemberGUID + exec procEMFFillInAddToEnd @PlaceholderDimensionGUID, @FillInMemberGUID, @ModelGUID + + FETCH NEXT FROM fillins INTO @fillInMemberGUID + END + + CLOSE fillins + deallocate fillins + + + + + --exec procEMFFillInAddToEnd + + + drop table #members + + --PlaceholderMemberGUID in + -- ( select listmemberguid + -- from securelist + -- where listguid = @placeholderDimensionGUID + -- ) + --and ModelGUID = @modelGUID + --) FillIns +-- WHERE +-- RowNum > @MaxIndex + + + + +-- RETURN +--END +--GO +GO + + +--------------------------------------------- + +-- dbo.procEMFFillInAddToEnd +CREATE proc [dbo].[procEMFFillInAddToEnd] + @PlaceholderDimensionGUID uniqueidentifier + --,@PlaceholderParentMemberGUID uniqueidentifier isnt going to be used on a PH dimension with multi sections yet + ,@FillInMemberGUID uniqueidentifier + ,@ModelGUID uniqueidentifier +as + +/* +declare @PHDimGUID uniqueidentifier +declare @PlaceholderIndex int +declare @FillInMemberGUID uniqueidentifier +declare @ModelGUID uniqueidentifier + +set @modelguid = '7594B42B-AF3D-43B6-8A56-6CA6F84F836B' --scott 2.0 1 +set @PHDimGUID = '1A220CA5-182D-4EA8-AE70-1E6C1E7F8D2D' --staff ph +set @placeholderindex = 2 +set @fillinmemberguid = '37D0CF18-435E-4CEC-9C6F-1D56C6276883' --staff: tushar +*/ + +declare @placeholdermemberguid uniqueidentifier +declare @placeholderindex int + + +select @placeholderIndex = dbo.GetModelLastFillInIndex(@ModelGUID,@PlaceholderDimensionGUID) --next index + +set @placeholderIndex= @placeholderIndex + 1 + +select + @placeholdermemberguid = placeholdermemberguid +from + ( + select + row_number() over (order by PH.SortOrder) - 1 as PlaceholderIndex, --zero based + PH.PlaceholderMemberGUID + from + viewplaceholders PH + where + PH.PlaceholderDimensionGUID = @PlaceholderDimensionGUID + --and PH.PlaceholderParentMemberGUID = @PlaceholderParentMemberGUID + ) phnum +where + PlaceholderIndex = @placeholderindex + + +if @placeholdermemberguid is null return + +exec procEMFFillInSet @modelguid, @placeholdermemberguid, @fillinmemberguid +GO + + +--------------------------------------------- + +-- dbo.procEMFFillInAddToEndSection +CREATE proc [dbo].[procEMFFillInAddToEndSection] + @SectionGUID uniqueidentifier --isnt going to be used on a PH dimension with multi sections yet + ,@FillInMemberGUID uniqueidentifier + ,@ModelGUID uniqueidentifier +as + +/* +declare @PHDimGUID uniqueidentifier +declare @PlaceholderIndex int +declare @FillInMemberGUID uniqueidentifier +declare @ModelGUID uniqueidentifier + +set @modelguid = '7594B42B-AF3D-43B6-8A56-6CA6F84F836B' --scott 2.0 1 +set @PHDimGUID = '1A220CA5-182D-4EA8-AE70-1E6C1E7F8D2D' --staff ph +set @placeholderindex = 2 +set @fillinmemberguid = '37D0CF18-435E-4CEC-9C6F-1D56C6276883' --staff: tushar +*/ + +declare @placeholdermemberguid uniqueidentifier +declare @placeholderindex int + + +select @placeholderIndex = dbo.GetModelLastFillInIndexSection(@ModelGUID,@SectionGUID) --next index + +set @placeholderIndex= @placeholderIndex + 1 + +select + @placeholdermemberguid = placeholdermemberguid +from + ( + select + row_number() over (order by PH.SortOrder) - 1 as PlaceholderIndex, --zero based + PH.PlaceholderMemberGUID + from + viewplaceholders PH + where + PH.PlaceholderParentMemberGUID = @SectionGUID + + --and PH.PlaceholderParentMemberGUID = @PlaceholderParentMemberGUID + ) phnum +where + PlaceholderIndex = @placeholderindex + + +if @placeholdermemberguid is null return + +exec procEMFFillInSet @modelguid, @placeholdermemberguid, @fillinmemberguid +GO + + +--------------------------------------------- + +-- dbo.procEMFFillInCopy +create proc procEMFFillInCopy + @oldmodelguid uniqueidentifier, + @newmodelguid uniqueidentifier +as +insert into emffillin(modelguid, placeholdermemberguid, filledinmemberguid, issetbyuser) +select + @newmodelguid, placeholdermemberguid, filledinmemberguid, issetbyuser +from + emffillin +where + modelguid = @oldmodelguid + and not exists(select 1 from emffillin fi2 where fi2.modelguid = @newmodelguid and fi2.placeholdermemberguid = emffillin.placeholdermemberguid) +GO + + +--------------------------------------------- + +-- dbo.procEMFFillInSet +CREATE proc [dbo].[procEMFFillInSet] + @planguid uniqueidentifier, + @PlaceholderMemberGUID uniqueidentifier, + @FilledInMemberGUID uniqueidentifier +as + +if exists (select 1 from emffillin where ModelGUID = @planguid and placeholdermemberguid = @placeholdermemberguid) begin + update EMFFillIn + SET FilledInMemberGUID = @FilledInMemberGUID + WHERE + ModelGUID = @planguid + and PlaceholderMemberGUID = @PlaceholderMemberGUID + +end else begin + + INSERT INTO EMFFillIn (ModelGUID, PlaceHolderMemberGUID, FilledInMemberGUID) + VALUES (@PlanGUID, @PlaceHolderMemberGUID, @FilledInMemberGUID) + +end +GO + + +--------------------------------------------- + +-- dbo.procEMFFillInSetByIndex +CREATE proc [dbo].[procEMFFillInSetByIndex] + @PlaceholderDimensionGUID uniqueidentifier + ,@PlaceholderParentMemberGUID uniqueidentifier + ,@PlaceholderIndex int + ,@FillInMemberGUID uniqueidentifier + ,@ModelGUID uniqueidentifier +as + +/* +declare @PHDimGUID uniqueidentifier +declare @PlaceholderIndex int +declare @FillInMemberGUID uniqueidentifier +declare @ModelGUID uniqueidentifier + +set @modelguid = '7594B42B-AF3D-43B6-8A56-6CA6F84F836B' --scott 2.0 1 +set @PHDimGUID = '1A220CA5-182D-4EA8-AE70-1E6C1E7F8D2D' --staff ph +set @placeholderindex = 2 +set @fillinmemberguid = '37D0CF18-435E-4CEC-9C6F-1D56C6276883' --staff: tushar +*/ + +declare @placeholdermemberguid uniqueidentifier + +select + @placeholdermemberguid = placeholdermemberguid +from + ( + select + row_number() over (order by PH.SortOrder) - 1 as PlaceholderIndex, --zero based + PH.PlaceholderMemberGUID + from + viewplaceholders PH + where + PH.PlaceholderDimensionGUID = @PlaceholderDimensionGUID + and PH.PlaceholderParentMemberGUID = @PlaceholderParentMemberGUID + ) phnum +where + PlaceholderIndex = @placeholderindex + +if @placeholdermemberguid is null return + +exec procEMFFillInSet @modelguid, @placeholdermemberguid, @fillinmemberguid +GO + + +--------------------------------------------- + +-- dbo.procEMFFillInSetByTemplate +CREATE proc [dbo].[procEMFFillInSetByTemplate] + @modelguid uniqueidentifier + ,@placeholderdimensionGUID uniqueidentifier + ,@fitname varchar(max) + ,@isClearingOld bit = 1 +as + +declare @desc varchar(max) +declare @instanceGUID uniqueidentifier +set @instanceGUID = NEWID() + +begin try + begin transaction + + declare @fillInDimensionGUID uniqueidentifier + select @fillInDimensionGUID = fillInDimensionGUID from securelist where listguid = @placeholderdimensionGUID + + if @fillinDimensionguid is null + BEGIN + ROLLBACK TRANSACTION + set @desc = '[procEMFFillInSetByTemplate] Failed' + exec procLogScript @desc, null + RETURN + END + --SELECT DISTINCT PHDimensionGUID, MODELGUID, PARENTPHMEMBERGUID, FILLINGUID, SORTORDER INTO #fillinsDist + + if @isClearingOld = 1 begin + delete from EMFFillIn where + modelguid = @modelguid + and placeholderMemberGUID in (select listmemberguid from securelistmember where listguid = @placeholderDimensionGUID) + end + + + insert into EMFFillInSetManyStaging (InstanceGUID,PHDimensionGUID,ModelGUID,ParentPHMemberGUID,FillInGUID,SortOrder) + select + @instanceGUID, + @placeholderdimensionguid as PHDimensionGUID, + @modelguid as ModelGUID, + phsection.listmemberguid as ParentPHMemberGUID, + slmv.listmemberguid as FillInGUID, + coalesce(slmvdo.valuetext,slm.sortorderfullpath) as SortOrder + + from + securelistmember slm + inner join securelistmembervalue slmv on slm.listmemberguid = slmv.listmemberguid + inner join securelistmember phsection on + slmv.valuetext = phsection.name + and phsection.listguid = @placeholderDimensionGUID + left join securelistproperty slpdo on slm.listguid = slpdo.listguid and slpdo.name = 'Default Order' + left join securelistmembervalue slmvdo on slm.listguid = slmvdo.listguid and slmvdo.valueindex = slpdo.propertyindex and slmvdo.listmemberguid = slm.listmemberguid + where + slmv.listguid = @fillInDimensionGUID + and + exists ( + select 1 + from + securelistproperty slp + where + slp.propertytype= 9 + and slp.listguid = slmv.listguid + and slmv.valueindex = slp.propertyindex + and slp.name = @fitname + ) + + exec procEMFFillInSetMany @instanceguid + + delete from EMFFillInSetManyStaging where InstanceGUID = @instanceGUID + + set @desc = '[procEMFFillInSetByTemplate] Succeeded, InstanceGUID=' + cast(@instanceGUID as varchar(36)) + exec procLogScript @desc, null + + COMMIT TRANSACTION +END TRY + +BEGIN CATCH + ROLLBACK TRANSACTION + set @desc = '[procEMFFillInSetByTemplate] Failed, InstanceGUID=' + cast(@instanceGUID as varchar(36)) + ': ' + error_message() + exec procLogScript @desc, null + exec procSysRethrowError +END CATCH +GO + + +--------------------------------------------- + +-- dbo.procEMFFillInSetMany +CREATE proc [dbo].[procEMFFillInSetMany] + @InstanceGUID uniqueidentifier +as + +declare @desc varchar(max) + +BEGIN TRY + BEGIN TRANSACTION + + declare @PHDimensionGUID uniqueidentifier + declare @modelguid uniqueidentifier + declare @parentPHMemberGUID uniqueidentifier + declare @fillInGUID uniqueidentifier + declare @index int + + SELECT DISTINCT PHDimensionGUID, MODELGUID, PARENTPHMEMBERGUID, FILLINGUID, SORTORDER INTO #fillinsDist + FROM EMFFillInSetManyStaging + WHERE InstanceGUID = @InstanceGUID + + --clears out ALL (even those set by users) fillins for all combos of Plan-PlaceholderSection that are trying to be mass set + DELETE FROM EMFFillIn + where + exists + ( + select 1 --listmemberguid + from + #fillinsdist fid + inner join securelistmember slm on fid.parentphmemberguid = slm.parentlistmemberguid + where + fid.modelguid = emffillin.modelguid + and emffillin.placeholdermemberguid = slm.listmemberguid + ) + --and issetbyuser = 0 + + + DECLARE fillins CURSOR LOCAL FAST_FORWARD + FOR SELECT PHDimensionGUID, MODELGUID, PARENTPHMEMBERGUID, FILLINGUID, Row_Number() over (partition by modelguid, parentphmemberguid order by SORTORDER asc) -1 FROM #fillinsDist + WHERE + NOT MODELGUID IS NULL + AND NOT PARENTPHMEMBERGUID is null + AND NOT FILLINGUID is null + OPEN fillins + FETCH NEXT FROM fillins INTO @PHDimensionGUID,@modelGUID, @parentPHMemberGUID, @fillInGUID, @index + WHILE @@FETCH_STATUS = 0 + BEGIN + exec procEMFFillInSetByIndex @PHDimensionGUID, @ParentPHMemberGUID, @index, @FillInGUID, @ModelGUID + + FETCH NEXT FROM fillins INTO @PHDimensionGUID,@modelGUID, @parentPHMemberGUID, @fillInGUID, @index + END + + CLOSE fillins + deallocate fillins + drop table #fillinsDist + + set @desc = '[procEMFFillInSetMany] Succeeded, InstanceGUID=' + cast(@instanceGUID as varchar(36)) + exec procLogScript @desc, null + + COMMIT TRANSACTION +END TRY +BEGIN CATCH + ROLLBACK TRANSACTION + + set @desc = '[procEMFFillInSetMany] Failed, InstanceGUID=' + cast(@instanceGUID as varchar(36)) + ': ' + error_message() + exec procLogScript @desc, null + + exec procSysRethrowError +END CATCH +GO + + +--------------------------------------------- + +-- dbo.procEMFFillInSetManyClearThoseBeingSet +CREATE proc [dbo].[procEMFFillInSetManyClearThoseBeingSet] + @InstanceGUID uniqueidentifier +as +declare @desc varchar(36) +begin try + begin transaction + declare @PHDimensionGUID uniqueidentifier + declare @modelguid uniqueidentifier + declare @parentPHMemberGUID uniqueidentifier + declare @fillInGUID uniqueidentifier + declare @index int + + SELECT DISTINCT PHDimensionGUID, MODELGUID, PARENTPHMEMBERGUID, FILLINGUID, SORTORDER INTO #fillinsDist + FROM EMFFillInSetManyStaging + WHERE InstanceGUID = @InstanceGUID + + + --clears out ALL (even those set by users) fillins for all combos of Plan-PlaceholderSection that are trying to be mass set + DELETE FROM EMFFillIn + where + exists + ( + select 1 --listmemberguid + from + #fillinsdist fid + --inner join securelistmember slm on fid.parentphmemberguid = slm.parentlistmemberguid + where + fid.modelguid = emffillin.modelguid + and emffillin.filledinmemberguid = fid.fillinguid + ) + and (not FillInGUID = '00000000-0000-0000-0000-000000000000' and not PlaceholderMemberGUID = '00000000-0000-0000-0000-000000000000') + --and issetbyuser = 0 + + + DECLARE fillins CURSOR LOCAL FAST_FORWARD + FOR SELECT PHDimensionGUID, MODELGUID, PARENTPHMEMBERGUID, FILLINGUID, Row_Number() over (partition by modelguid, parentphmemberguid order by SORTORDER asc) -1 FROM #fillinsDist + WHERE + NOT MODELGUID IS NULL + AND NOT PARENTPHMEMBERGUID is null + AND NOT FILLINGUID is null + OPEN fillins + FETCH NEXT FROM fillins INTO @PHDimensionGUID,@modelGUID, @parentPHMemberGUID, @fillInGUID, @index + WHILE @@FETCH_STATUS = 0 + BEGIN + exec procEMFFillInSetByIndex @PHDimensionGUID, @ParentPHMemberGUID, @index, @FillInGUID, @ModelGUID + + FETCH NEXT FROM fillins INTO @PHDimensionGUID,@modelGUID, @parentPHMemberGUID, @fillInGUID, @index + END + + CLOSE fillins + deallocate fillins + drop table #fillinsDist + + set @desc = '[procEMFFillInSetManyClearThoseBeingSet] Succeeded, InstanceGUID=' + cast(@instanceGUID as varchar(36)) + exec procLogScript @desc, null + + COMMIT TRANSACTION +END TRY +BEGIN CATCH + ROLLBACK TRANSACTION + + set @desc = '[procEMFFillInSetManyClearThoseBeingSet] Failed, InstanceGUID=' + cast(@instanceGUID as varchar(36)) + ': ' + error_message() + exec procLogScript @desc, null + + exec procSysRethrowError +END CATCH +GO + + +--------------------------------------------- + +-- dbo.procEMFFillInSetManyClearThoseBeingSet_ReorderAtEnd +CREATE proc [dbo].[procEMFFillInSetManyClearThoseBeingSet_ReorderAtEnd] + @InstanceGUID uniqueidentifier +as +declare @desc varchar(max) + +begin try + begin transaction + + declare @PHDimensionGUID uniqueidentifier + declare @modelguid uniqueidentifier + declare @parentPHMemberGUID uniqueidentifier + declare @fillInGUID uniqueidentifier + declare @index int + + SELECT DISTINCT PHDimensionGUID, MODELGUID, PARENTPHMEMBERGUID, FILLINGUID, SORTORDER INTO #fillinsDist + FROM EMFFillInSetManyStaging + WHERE InstanceGUID = @InstanceGUID + + + --clears out ALL (even those set by users) fillins for all combos of Plan-PlaceholderSection that are trying to be mass set + delete FROM EMFFillIn + where + exists + ( + select 1 --listmemberguid + from + #fillinsdist fid + --inner join securelistmember slm on fid.parentphmemberguid = slm.parentlistmemberguid + where + fid.modelguid = emffillin.modelguid + and emffillin.filledinmemberguid = fid.fillinguid + ) + and (not FillInGUID = '00000000-0000-0000-0000-000000000000' and not PlaceholderMemberGUID = '00000000-0000-0000-0000-000000000000') + --and issetbyuser = 0 + +----If Any Remaining for Plan-Section Combos are out of order after removal - reorder-- + Update viewemffillinsoutoforder set placeholdermemberguid = sortedphmemberguid + where + exists + (select 1 + from + #fillinsdist fid + where + fid.modelguid = viewemffillinsoutoforder.modelguid + and viewemffillinsoutoforder.placeholdersectionguid = fid.PARENTPHMEMBERGUID + ) + + DECLARE fillins CURSOR LOCAL FAST_FORWARD + FOR SELECT PARENTPHMEMBERGUID, FILLINGUID,MODELGUID FROM #fillinsDist + WHERE + NOT MODELGUID IS NULL + AND NOT PARENTPHMEMBERGUID is null + AND NOT FILLINGUID is null + OPEN fillins + FETCH NEXT FROM fillins INTO @parentPHMemberGUID, @fillInGUID, @ModelGUID + --FETCH NEXT FROM fillins INTO @PHDimensionGUID,@modelGUID, @parentPHMemberGUID, @fillInGUID, @index + WHILE @@FETCH_STATUS = 0 + BEGIN + + exec procEMFFillInAddToEndSection @parentPHMemberGUID, @fillInGUID, @ModelGUID + --exec procEMFFillInSetByIndex @PHDimensionGUID, @ParentPHMemberGUID, @index, @FillInGUID, @ModelGUID + + FETCH NEXT FROM fillins INTO @parentPHMemberGUID, @fillInGUID, @ModelGUID + + END + + CLOSE fillins + deallocate fillins + + --Reorder Based on Dimension Sort After All Added To End of Section-- + Update viewemffillinsoutoforder set placeholdermemberguid = sortedphmemberguid + where + exists + (select 1 + from + #fillinsdist fid + where + fid.modelguid = viewemffillinsoutoforder.modelguid + and viewemffillinsoutoforder.placeholdersectionguid = fid.PARENTPHMEMBERGUID + ) + + drop table #fillinsDist + + set @desc = '[procEMFFillInSetManyClearThoseBeingSet_ReorderAtEnd] Succeeded, InstanceGUID=' + cast(@instanceGUID as varchar(36)) + exec procLogScript @desc, null + + COMMIT TRANSACTION +END TRY +BEGIN CATCH + ROLLBACK TRANSACTION + + set @desc = '[procEMFFillInSetManyClearThoseBeingSet_ReorderAtEnd] Failed, InstanceGUID=' + cast(@instanceGUID as varchar(36)) + ': ' + error_message() + exec procLogScript @desc, null + + exec procSysRethrowError +END CATCH +GO + + +--------------------------------------------- + +-- dbo.procEMFFillInSetManyNoClear +CREATE proc [dbo].[procEMFFillInSetManyNoClear] + @InstanceGUID uniqueidentifier +as + +/* +declare @PHDimGUID uniqueidentifier +declare @PlaceholderIndex int +declare @FillInMemberGUID uniqueidentifier +declare @ModelGUID uniqueidentifier + +set @modelguid = '7594B42B-AF3D-43B6-8A56-6CA6F84F836B' --scott 2.0 1 +set @PHDimGUID = '1A220CA5-182D-4EA8-AE70-1E6C1E7F8D2D' --staff ph +set @placeholderindex = 2 +set @fillinmemberguid = '37D0CF18-435E-4CEC-9C6F-1D56C6276883' --staff: tushar +*/ + + declare @PHDimensionGUID uniqueidentifier + declare @modelguid uniqueidentifier + declare @parentPHMemberGUID uniqueidentifier + declare @fillInGUID uniqueidentifier + declare @index int + + SELECT DISTINCT PHDimensionGUID, MODELGUID, PARENTPHMEMBERGUID, FILLINGUID, SORTORDER INTO #fillinsDist + FROM EMFFillInSetManyStaging + WHERE InstanceGUID = @InstanceGUID + + --clears out ALL (even those set by users) fillins for all combos of Plan-PlaceholderSection that are trying to be mass set + --DELETE FROM EMFFillIn + --where + -- exists + -- ( + -- select 1 --listmemberguid + -- from + -- #fillinsdist fid + -- inner join securelistmember slm on fid.parentphmemberguid = slm.parentlistmemberguid + -- where + -- fid.modelguid = emffillin.modelguid + -- and emffillin.placeholdermemberguid = slm.listmemberguid + -- ) + --and issetbyuser = 0 + + + DECLARE fillins CURSOR LOCAL FAST_FORWARD + FOR SELECT PHDimensionGUID, MODELGUID, PARENTPHMEMBERGUID, FILLINGUID, Row_Number() over (partition by modelguid, parentphmemberguid order by SORTORDER asc) -1 FROM #fillinsDist + WHERE + NOT MODELGUID IS NULL + AND NOT PARENTPHMEMBERGUID is null + AND NOT FILLINGUID is null + AND NOT EXISTS ( + SELECT 1 + FROM EMFFillIn exFI + inner join securelistmember phslm on exfi.placeholdermemberguid = phslm.listmemberguid + WHERE exFI.modelguid = #fillinsDist.modelguid + and exFI.filledinmemberguid = #fillinsDist.fillinguid + and phslm.parentlistmemberguid = #fillinsDist.parentphmemberguid + ) + + OPEN fillins + FETCH NEXT FROM fillins INTO @PHDimensionGUID,@modelGUID, @parentPHMemberGUID, @fillInGUID, @index + WHILE @@FETCH_STATUS = 0 + BEGIN + exec procEMFFillInAddtoendsection @ParentPHMemberGUID, @FillInGUID, @ModelGUID + + FETCH NEXT FROM fillins INTO @PHDimensionGUID,@modelGUID, @parentPHMemberGUID, @fillInGUID, @index + END + + CLOSE fillins + deallocate fillins + drop table #fillinsDist +--select +-- @placeholdermemberguid = placeholdermemberguid +--from +-- ( +-- select +-- row_number() over (order by PH.SortOrder) - 1 as PlaceholderIndex, --zero based +-- PH.PlaceholderMemberGUID +-- from +-- viewplaceholders PH +-- where +-- PH.PlaceholderDimensionGUID = @PlaceholderDimensionGUID +-- and PH.PlaceholderParentMemberGUID = @PlaceholderParentMemberGUID +-- ) phnum +--where +-- PlaceholderIndex = @placeholderindex + +--if @placeholdermemberguid is null return + +--exec procEMFFillInSet @modelguid, @placeholdermemberguid, @fillinmemberguid + + +--GO +GO + + +--------------------------------------------- + +-- dbo.procEMFGetModelDependencyTreesByModel +CREATE procedure [dbo].[procEMFGetModelDependencyTreesByModel]( + @ModelGUID uniqueidentifier +) +AS +BEGIN + + +DECLARE @submodelGUID uniqueidentifier; + +DECLARE @ModelTree TABLE ( ModelGUID uniqueidentifier, [Level] int) + +insert into @ModelTree select * from dbo.GetModelDependencyTree(@modelGUID, 100); +select * from @ModelTree --select for dataset + +DECLARE mCursor CURSOR FAST_FORWARD FOR + select ModelGUID from @ModelTree + +open mCursor + +FETCH NEXT FROM mCursor into @submodelGUID +WHILE(@@FETCH_STATUS = 0) +BEGIN + if (@submodelGUID <> @ModelGUID) + select * from dbo.GetModelDependencyTree(@submodelGUID, 100); + + FETCH NEXT FROM mCursor into @submodelGUID; +END +close mCursor; +DEALLOCATE mCursor; + + +END +GO + + +--------------------------------------------- + +-- dbo.procEMFGetModelDependencyTreesByModelList +CREATE Procedure [dbo].[procEMFGetModelDependencyTreesByModelList] +( + @ModelGUIDCSV nvarchar(max) +) +AS + +declare crsCursor CURSOR FAST_FORWARD FOR + select PlanGUID from XPlan + where PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(@ModelGUIDCSV, ',')) and IsDeletedPlan = 0 + +open crsCursor; + +DECLARE @UsedModels TABLE +( + ModelGUID uniqueidentifier primary key +) +DECLARE @modelGUID uniqueidentifier +DECLARE @submodelGUID uniqueidentifier; + +declare @ModelTree TABLE ( ModelGUID uniqueidentifier, [Level] int) + + +FETCH NEXT FROM crsCursor into @modelGUID +WHILE (@@FETCH_STATUS = 0) + BEGIN + + insert into @ModelTree select * from dbo.GetModelDependencyTree(@modelGUID, 100); + if (not exists (select 1 from @UsedModels where ModelGUID = @modelGUID)) + BEGIN + select * from @ModelTree --select for dataset + insert into @UsedModels (ModelGUID) VALUES (@modelGUID); + + DECLARE mCursor CURSOR FAST_FORWARD FOR + select ModelGUID from @ModelTree + + open mCursor + + FETCH NEXT FROM mCursor into @submodelGUID + WHILE(@@FETCH_STATUS = 0) + BEGIN + if (not exists (select 1 from @UsedModels where ModelGUID = @submodelGUID)) + BEGIN + select * from dbo.GetModelDependencyTree(@submodelGUID, 100); + insert into @UsedModels (ModelGUID) values (@submodelGUID); + END + + FETCH NEXT FROM mCursor into @submodelGUID; + END + close mCursor; + DEALLOCATE mCursor; + + delete from @ModelTree + END --if not exists + + FETCH NEXT FROM crsCursor into @modelGUID + END --while +close crsCursor; +DEALLOCATE crsCursor; +GO + + +--------------------------------------------- + +-- dbo.procEMFGetModelDependencyTreesByModelTemplate +--Author: gforeman +--Branch: Earwig +--Forward +CREATE Procedure [dbo].[procEMFGetModelDependencyTreesByModelTemplate] +( + @ModelTemplateGUID uniqueidentifier +) +AS + +declare crsCursor CURSOR FAST_FORWARD FOR + select PlanGUID from XPlan + where ModelTemplateGUID = @ModelTemplateGUID and IsDeletedPlan = 0 + +open crsCursor; + +DECLARE @UsedModels TABLE +( + ModelGUID uniqueidentifier primary key +) +DECLARE @modelGUID uniqueidentifier +DECLARE @submodelGUID uniqueidentifier; + +declare @ModelTree TABLE ( ModelGUID uniqueidentifier, [Level] int) + + +FETCH NEXT FROM crsCursor into @modelGUID +WHILE (@@FETCH_STATUS = 0) + BEGIN + + insert into @ModelTree select * from dbo.GetModelDependencyTree(@modelGUID, 100); + if (not exists (select 1 from @UsedModels where ModelGUID = @modelGUID)) + BEGIN + select * from @ModelTree --select for dataset + insert into @UsedModels (ModelGUID) VALUES (@modelGUID); + + DECLARE mCursor CURSOR FAST_FORWARD FOR + select ModelGUID from @ModelTree + + open mCursor + + FETCH NEXT FROM mCursor into @submodelGUID + WHILE(@@FETCH_STATUS = 0) + BEGIN + if (not exists (select 1 from @UsedModels where ModelGUID = @submodelGUID)) + BEGIN + select * from dbo.GetModelDependencyTree(@submodelGUID, 100); + insert into @UsedModels (ModelGUID) values (@submodelGUID); + END + + FETCH NEXT FROM mCursor into @submodelGUID; + END + close mCursor; + DEALLOCATE mCursor; + + delete from @ModelTree + END --if not exists + + FETCH NEXT FROM crsCursor into @modelGUID + END --while +close crsCursor; +DEALLOCATE crsCursor; +GO + + +--------------------------------------------- + +-- dbo.procEMFImprovInsertCopy +CREATE proc [dbo].[procEMFImprovInsertCopy] + @sourceplanguid uniqueidentifier + ,@newplanguid uniqueidentifier +as + +declare @sourceFileGuid uniqueidentifier +select @sourceFileGuid =FileGUID from DataPathFile_Improv where FullPath = 'ImprovWorkbook' + CAST(@sourceplanguid as varchar(36)) +'.xlsx' + +declare @fullpath varchar(max) +if not @sourceFileGuid is null begin + set @fullpath = 'ImprovWorkbook' + CAST(@newplanguid as varchar(36)) +'.xlsx' + exec dbo.procDataPathCopyFile @sourceFileGuid, @fullpath +end + +delete from MEImprovData where ModelGUID = @newplanguid +insert into MEImprovData(ModelGUID, WorksheetGUID, Row, Col, Formula, CellValue, OriginalComment) +select @newplanguid, WorksheetGUID, Row, Col, Formula, CellValue, OriginalComment +from + MEImprovData +where + modelguid = @sourceplanguid +GO + + +--------------------------------------------- + +-- dbo.procEMFListCacheCleanup +CREATE proc [dbo].[procEMFListCacheCleanup] + @isDeleting bit = 0 +as + declare @tblsql nvarchar(4000) + declare @tablename nvarchar(100) + declare crsTables cursor for + select + t.name + from + sys.tables t + left join SecureList l on cast(l.ListGUID as nvarchar(36)) = replace(RIGHT(t.name, 36), '_', '-') + where + t.name like 'zzlist%' + and l.ListGUID is null + + open crsTables + fetch next from crsTables into @tablename + + while(@@FETCH_STATUS = 0) begin + set @tblsql = 'drop table ' + @tablename + exec(@tblsql) + + fetch next from crsTables into @tablename + end + + close crsTables + deallocate crsTables + + declare @viewsql nvarchar(4000) + declare @viewname nvarchar(100) + declare crsViews cursor for + select + v.name + from + sys.views v + left join SecureList l on replace(l.Name, ' ', '') = replace(replace(v.name, 'zzviewlist_', ''), 'zzviewlistexport_', '') + where + v.name like 'zzviewlist%' + and l.ListGUID is null + + open crsViews + fetch next from crsViews into @viewname + + while(@@FETCH_STATUS = 0) begin + if(@isDeleting = 1) begin + set @viewsql = 'drop view ' + @viewname + exec(@viewsql) + end else begin + print @viewname + end + + fetch next from crsViews into @viewname + end + + close crsViews + deallocate crsViews +GO + + +--------------------------------------------- + +-- dbo.procEMFMDCViewCleanup +CREATE proc [dbo].[procEMFMDCViewCleanup] + @isDeleting bit = 0 +as + declare @viewsql nvarchar(4000) + declare @viewname nvarchar(100) + declare crsViews cursor for + select + v.name + from + sys.views v + left join EMFModelDataConfig mdc on replace(replace(replace(replace(replace(replace(replace(mdc.Name, ' ', ''), '-', ''), '&', ''), '(', ''), ')', ''), '/', ''), '\', '') in(replace(v.Name, 'zzviewModelTemplateMapping_', ''), replace(v.Name, 'zzviewModelTemplateMappingBasic_', ''), replace(v.Name, 'zzviewModelData_', ''), replace(v.Name, 'zzviewModelDataInner_', ''), replace(v.Name, 'zzviewModelDataBasic_', '')) + where + v.name like 'zzviewModel%' + and mdc.ModelDataConfigGUID is null + + open crsViews + fetch next from crsViews into @viewname + + while(@@FETCH_STATUS = 0) begin + if(@isDeleting = 1) begin + set @viewsql = 'drop view ' + @viewname + exec(@viewsql) + end else begin + print @viewname + end + + fetch next from crsViews into @viewname + end + + close crsViews + deallocate crsViews +GO + + +--------------------------------------------- + +-- dbo.procEMFMissingPHMembersCreate +CREATE proc [dbo].[procEMFMissingPHMembersCreate] + @sourcedb nvarchar(100) +as + declare @sql nvarchar(max) + + set @sql=' + insert into [dbo].[SecureListMember] ([ListMemberGUID],[ListGUID],[ParentListMemberGUID],[Name],[Description],[FullPath],[DisplayOrder],[OutlineLevel],[OperatorType],[IsIDLocked],[IsNameLocked],[IsDeleteLocked],[IsNewChildLocked],[IsParentAssociationLocked],[IsEditAttributeLocked],[ListMemberID],[SortOrderFullPath],[FillInConfigGUID],[FillInDimensionGUID],[DateCreated],[DateModified],[LootIDOverride]) + select LM.[ListMemberGUID],LM.[ListGUID],LM.[ParentListMemberGUID],LM.[Name],LM.[Description],LM.[FullPath],LM.[DisplayOrder],LM.[OutlineLevel],LM.[OperatorType],LM.[IsIDLocked],LM.[IsNameLocked],LM.[IsDeleteLocked],LM.[IsNewChildLocked],LM.[IsParentAssociationLocked],LM.[IsEditAttributeLocked],LM.[ListMemberID],LM.[SortOrderFullPath],LM.[FillInConfigGUID],LM.[FillInDimensionGUID],LM.[DateCreated],LM.[DateModified],LM.[LootIDOverride] + from + ' + @sourcedb + '.dbo.SecureListMember LM + inner join ' + @sourcedb + '.dbo.SecureList L on L.ListGUID = LM.ListGUID + left join SecureListMember ME on ME.Name = LM.Name and ME.ListGUID = LM.ListGUID + where + ME.ListMemberGUID is null + and L.Name like ''%ph''' + + exec(@sql) +GO + + +--------------------------------------------- + +-- dbo.procEMFModelTemplateMappingEnsureIndexes +create proc procEMFModelTemplateMappingEnsureIndexes +as + declare @mdcguid uniqueidentifier + declare @sql nvarchar(max) + declare crsScripts cursor for + select + MDC.ModelDataConfigGUID, + 'CREATE CLUSTERED INDEX [idx_zzEMFModelTemplateMapping_' + replace(CAST(MDC.ModelDataConfigGUID as nvarchar(36)), '-', '_') + '_ByTemplate] ON [dbo].[zzEMFModelTemplateMapping_' + replace(CAST(MDC.ModelDataConfigGUID as nvarchar(36)), '-', '_') + '] + ( + [MODELTEMPLATEGUID] ASC + )WITH (SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]' as IdxCreateSQL + from + EMFModelDataConfig MDC + where + not exists(select 1 from sys.indexes idx where idx.name = 'idx_zzEMFModelTemplateMapping_' + replace(CAST(MDC.ModelDataConfigGUID as nvarchar(36)), '-', '_') + '_ByTemplate') + + open crsScripts + fetch next from crsScripts into @mdcguid, @sql + + while (@@FETCH_STATUS = 0) begin + print @mdcguid + exec(@sql) + fetch next from crsScripts into @mdcguid, @sql + end + + close crsScripts + deallocate crsScripts +GO + + +--------------------------------------------- + +-- dbo.procEMFRemoveTemplateMappings +CREATE proc [dbo].[procEMFRemoveTemplateMappings] + @modeltemplateguid uniqueidentifier, + @includeprofiles bit = 1 +as + --EMF mapping tables + declare @execsql varchar(max) + set @execsql = ' + delete from zzemfmodeltemplatemapping_{mdcguidfriendly} where modeltemplateguid = ''' + cast(@modeltemplateguid as varchar(36)) + ''' + ' + declare @structurefiltersql varchar(max) + set @structurefiltersql = ' + WHERE + ModelDataConfigGUID IN ( + select + isnull(st.modeldataconfigguid, ls.parentmodeldataconfigguid) + from + emfmodeltemplatelinksource ls + left join emfsubtable st on ls.parentsubtableguid = st.subtableguid + where + modeltemplateguid = ''' + cast(@modeltemplateguid as varchar(36)) + ''' + )' + exec dbo.procEMFRunForManyStructures @execsql, @structurefiltersql, 1,0 + + --Expansions (EMF) + delete from EMFModelTemplateExpansion where ExpansionGUID in (select expansionguid from viewEMFModelTemplateExpansion where ModelTemplateGUID = @modeltemplateguid) + + --Form Field mappings (Score) + delete from EMFModelTemplateFormFieldMapping where cellguid in (select c.cellguid from viewmecell c where c.BookGUID = @modeltemplateguid) + + --Placeholder Labels (EMF) + delete from EMFModelTemplatePlaceholderLabelMapping where cellguid in (select c.cellguid from viewmecell c where c.BookGUID = @modeltemplateguid) + + --Form Field mappings (EMF) + delete from EMFModelTemplateFormFieldMapping where cellguid in (select ff.CellGUID from EMFModelTemplateFormFieldMapping ff left join MEExcelCell ce on ce.ExcelCellGUID = ff.CellGUID where ce.ExcelCellGUID is null) + + --Score mapping tables + set @execsql = ' + delete m + from + {schema}.{object} m + where + exists ( + select 1 + from + viewMECell c + where + c.CellGUID = m.CellGUID + and c.BookGUID = ''' + cast(@modeltemplateguid as varchar(36)) + ''' + ) + or not exists ( + select 1 + from + viewMECell c2 + where + c2.CellGUID = m.CellGUID + ) + ' + set @structurefiltersql = ' + where + ScoreDataTable.DataTableGUID in ( + select DataTableGUID1 + from ScoreComposite sc + inner join EMFModelTemplateLinkSource ls on ls.ParentScoreCompositeTableGUID = sc.CompositeGUID + where + ls.ModelTemplateGUID = ''' + cast(@modeltemplateguid as varchar(36)) + ''' + ) + ' + exec dbo.procScoreRunForManyStructures @execsql, @structurefiltersql, 1, 0 + + --Placeholder Labels (Score) + delete phl from [dbo].[MEScorePlaceholderLabel] phl where phl.CellGUID in (select cx.ExcelCellGUID from [dbo].[viewMECell] cx where cx.ModelTemplateGUID = @modeltemplateguid) + + --Expansions (Score) + delete scx from MEScoreExpansion scx where scx.ExcelCellGUID in (select cx.ExcelCellGUID from [dbo].[viewMECell] cx where cx.ModelTemplateGUID = @modeltemplateguid) + + --Template Cells (Score) + delete xc from [dbo].[MEExcelCell] xc inner join [dbo].[EMFModelTemplateWorksheet] ws on ws.WorksheetGUID = xc.ExcelSheetGUID where ws.ModelTemplateGUID = @modeltemplateguid; + + --Child Expansion Profiles + if (@includeprofiles = 1) begin + declare crsProfiles cursor fast_forward for select ChildModelTemplateGUID from [dbo].[MEScoreExpansionProfile] with (readuncommitted) where ParentModelTemplateGUID = @modeltemplateguid + declare @childmtguid uniqueidentifier + open crsProfiles + fetch next from crsProfiles into @childmtguid + while(@@fetch_status = 0) begin + exec [dbo].[procEMFRemoveTemplateMappings] @childmtguid, 0 + fetch next from crsProfiles into @childmtguid + end + close crsProfiles + deallocate crsProfiles + end +GO + + +--------------------------------------------- + +-- dbo.procEMFRemoveUnfilledData +create proc procEMFRemoveUnfilledData + @placeholderDimensionGUID uniqueidentifier + ,@isDeleting bit = 0 + ,@isRunning bit = 0 +as +--set @isRunning = 0 +--set @isDeleting = 1 +--set @placeholderDimensionGUID = '17FEAA4B-A2A2-4353-B081-03E3DFB5CB77' + + +declare @dimnameFriendly varchar(128) +select @dimnameFriendly = REPLACE(name,' ','') from securelist where ListGUID = @placeholderDimensionGUID + +--select * from SecureList where IsPlaceholder = 1 +declare @planDimGUID uniqueidentifier +select @planDimGUID = listguid from SecureList where ListType = 2 + +declare @wheresql varchar(max) +set @wheresql = ' +where modeldataconfigguid in ( +select + modeldataconfigguid +from + EMFModelDataConfigDimensionLink +where + DimensionGUID = ''' + cast(@placeholderDimensionGUID as varchar(36)) + ''' +intersect +select + modeldataconfigguid +from + EMFModelDataConfigDimensionLink +where + DimensionGUID = ''' + cast(@planDimGUID as varchar(36)) + ''' + ) +' + +declare @maybeBasic varchar(10) +if @isDeleting = 1 + set @maybeBasic = 'Basic' +else + set @maybeBasic = '' + +declare @sql varchar(max) + + +if @isDeleting = 1 + set @sql = 'delete data ' +else + set @sql = 'select ''{mdcname}'' as MDCName, * ' + + +set @sql = @sql + ' +from + zzviewModelData' + @maybebasic + '_{mdcnamefriendly} data +where + not exists ( + select 1 + from + EMFFillIn fi + where + fi.modelguid = data.PlansGUID --modelguid + and fi.FilledInMemberGUID = data.' + @dimnamefriendly + 'GUID -- g17FEAA4B_A2A2_4353_B081_03E3DFB5CB77 + ) +' + +exec procEMFRunForManyStructures @sql, @wheresql,@isRunning,0 +GO + + +--------------------------------------------- + +-- dbo.procEMFRunForManyStructures +CREATE proc [dbo].[procEMFRunForManyStructures] + @execsql varchar(max) + ,@structurefiltersql varchar(max) = '' + ,@exec bit = 0 + ,@allTogether bit = 0 +as + +--set @execsql = ' +-- select ''{mdcname}'', count(*) from zzemfmodeldata_{mdcguidfriendly} +--' +--set @structurefiltersql = ' +--where name like ''lrfp%'' +--' + +declare @structuresql varchar(max) + +set @structuresql = ' +select + modeldataconfigguid, name +from + emfmodeldataconfig +' + @structurefiltersql + +create table #mdcs (modeldataconfigguid uniqueidentifier, name nvarchar(64)) + +insert into #mdcs +exec (@structuresql) + +declare @mdcguid uniqueidentifier +declare @mdcguidfriendly varchar(36) +declare @mdcname nvarchar(64) +declare @mdcnamefriendly nvarchar(64) +declare @sql varchar(max) + + declare crsMDC CURSOR FOR + select modeldataconfigguid, name + from #mdcs + + open crsMDC; + + set @sql = '' + + FETCH NEXT FROM crsMDC into @mdcguid, @mdcname + WHILE (@@FETCH_STATUS = 0) + BEGIN + + set @mdcguidfriendly = replace(cast(@mdcguid as varchar(36)),'-','_') + set @mdcnamefriendly = REPLACE(@mdcname,' ','') + set @mdcnamefriendly = REPLACE(@mdcnamefriendly,'-','') + set @mdcnamefriendly = REPLACE(@mdcnamefriendly,'.','') + + if @allTogether = 1 begin + set @sql = @sql + replace(replace(replace(replace(@execsql,'{mdcguid}',cast(@mdcguid as varchar(36))), '{mdcname}',@mdcname),'{mdcguidfriendly}',@mdcguidfriendly),'{mdcnamefriendly}',@mdcnamefriendly) + end else begin + set @sql = replace(replace(replace(replace(@execsql,'{mdcguid}',cast(@mdcguid as varchar(36))), '{mdcname}',@mdcname),'{mdcguidfriendly}',@mdcguidfriendly),'{mdcnamefriendly}',@mdcnamefriendly) + if @exec = 1 begin + exec(@sql) + end else begin + print @sql + end + end + + + + + FETCH NEXT FROM crsMDC into @mdcguid, @mdcname + END + close crsMDC; + DEALLOCATE crsMDC; + + if @allTogether = 1 begin + if @exec = 1 begin + exec(@sql) + end else begin + print @sql + end + end + + + +drop table #mdcs +GO + + +--------------------------------------------- + +-- dbo.procEMFShowTemplateMappingCounts +CREATE proc [dbo].[procEMFShowTemplateMappingCounts] + @modeltemplateguid uniqueidentifier +as + + +declare @wheresql varchar(max) +set @wheresql = ' +where modeldataconfigguid in ( +select + ISNULL(st.MODELDATACONFIGGUID,ls.ParentModelDataConfigGUID) +from + EMFModelTemplateLinkSource ls + left join EMFSubtable st on ls.ParentSubtableGUID= st.SUBTABLEGUID +where + modeltemplateguid = ''' + cast(@modeltemplateguid as varchar(36)) + ''' + ) +' + +declare @sql varchar(max) +set @sql = ' +select + ''{mdcname}'' as Name, count(*) as TotalCnt, sum(case when isusermapped = 1 then 1 else 0 end) as UserMappedCount +from + zzEMFModelTemplateMapping_{mdcguidfriendly} map +where + modeltemplateguid = ''' + cast(@modeltemplateguid as varchar(36)) + ''' +' + +exec procEMFRunForManyStructures @sql, @wheresql,1 +GO + + +--------------------------------------------- + +-- dbo.procEMFViewTemplateMappingCount +CREATE proc [dbo].[procEMFViewTemplateMappingCount] + @modeltemplateguid uniqueidentifier +as + +declare @execsql varchar(max) +set @execsql = 'declare @cnt int + select @cnt = count(*) from zzemfmodeltemplatemapping_{mdcguidfriendly} with (readuncommitted) where modeltemplateguid = ''' + cast(@modeltemplateguid as varchar(36)) + ''' + print ''{mdcname} '' + cast(@cnt as varchar(36)) + ' + +declare @structurefiltersql varchar(max) +set @structurefiltersql = ' WHERE ModelDataConfigGUID IN ( +select + isnull(st.modeldataconfigguid, ls.parentmodeldataconfigguid) +from + emfmodeltemplatelinksource ls + left join emfsubtable st on ls.parentsubtableguid = st.subtableguid +where + modeltemplateguid = ''' + cast(@modeltemplateguid as varchar(36)) + ''' + )' + +exec dbo.procEMFRunForManyStructures @execsql, @structurefiltersql, 1,0 +GO + + +--------------------------------------------- + +-- dbo.procEnsureColumnInTable +CREATE proc [dbo].[procEnsureColumnInTable]( + @SchemaName NVARCHAR(128), + @TableName NVARCHAR(MAX), + @ColumnName NVARCHAR(128), + @Type NVARCHAR(128), @Default nvarchar(128), @DebugMode bit = 0) + +AS +BEGIN + +DECLARE @sql varchar(max) + +IF dbo.tableColumnExists(@SchemaName, @TableName, @ColumnName)=0 BEGIN + SET @SQL = 'ALTER TABLE ' + (select [dbo].[GetSQLTableExpression](@SchemaName, @TableName)) + SET @SQL = @SQL + ' ADD ' + @ColumnName + SET @SQL = @SQL + ' ' + @Type + IF LOWER(@Type) <> 'timestamp' + begin + SET @SQL = @SQL + ' NOT NULL CONSTRAINT DF_' + replace(@TableName,' ','_') + '_' + @ColumnName + SET @SQL = @SQL + ' DEFAULT ' + @default + end + + + IF @DebugMode = 0 BEGIN + EXEC (@SQL) + PRINT @ColumnName + ' added to ' + @TableName + END ELSE BEGIN + PRINT @SQL + END + +END + + +END +GO + + +--------------------------------------------- + +-- dbo.procEnsureColumnInTableCopyFromOther +CREATE proc [dbo].[procEnsureColumnInTableCopyFromOther]( + @SchemaName NVARCHAR(128), + @TableName NVARCHAR(MAX), + @ColumnName NVARCHAR(128), + @Type NVARCHAR(128), @Default nvarchar(128), @OldColumnName NVARCHAR(128), @DebugMode bit = 0) + +AS +BEGIN + +DECLARE @sql varchar(max) +DECLARE @sql2 varchar(max) + +IF dbo.ColumnExists(@SchemaName, @TableName, @ColumnName)=0 BEGIN + SET @SQL = 'ALTER TABLE ' + (select [dbo].[GetSQLTableExpression] (@SchemaName, @TableName)) + SET @SQL = @SQL + ' ADD ' + @ColumnName + SET @SQL = @SQL + ' ' + @Type + SET @SQL = @SQL + ' NOT NULL CONSTRAINT DF_' + Replace(@TableName,' ','_') + '_' + @ColumnName + SET @SQL = @SQL + ' DEFAULT ' + @default + + SET @SQL2 = ' UPDATE ' + (select [dbo].[GetSQLTableExpression] (@SchemaName, @TableName)) + SET @SQL2 = @SQL2 + ' SET ' + @ColumnName + SET @SQL2 = @SQL2 + ' = ' + @OldColumnName + + IF @DebugMode = 0 BEGIN + EXEC (@SQL) + PRINT @ColumnName + ' added to ' + @TableName + EXEC (@SQL2) + PRINT @OldColumnName + ' copied to ' + @ColumnName + ' for ' + @TableName + + END ELSE BEGIN + PRINT @SQL + PRINT 'GO' + PRINT @SQL2 + END + +END + + +END +GO + + +--------------------------------------------- + +-- dbo.procEnsureColumnNotInTable +CREATE proc [dbo].[procEnsureColumnNotInTable]( + @SchemaName NVARCHAR(128), + @TableName NVARCHAR(MAX), + @ColumnName NVARCHAR(128), + @DebugMode bit = 0 +) +AS +BEGIN + +DECLARE @sql varchar(max) + +IF dbo.ColumnExists(@SchemaName, @TableName, @ColumnName)=1 BEGIN + SET @SQL = 'ALTER TABLE ' + (select [dbo].[GetSQLTableExpression](@SchemaName, @TableName)) + SET @SQL = @SQL + ' DROP CONSTRAINT DF_' + @TableName + '_' + @ColumnName + + SET @SQL = @SQL + ' + ALTER TABLE ' + (select [dbo].[GetSQLTableExpression](@SchemaName, @TableName)) + SET @SQL = @SQL + ' DROP COLUMN ' + @ColumnName + + IF @DebugMode = 0 BEGIN + EXEC (@SQL) + PRINT @ColumnName + ' removed from ' + @TableName + END ELSE BEGIN + PRINT @SQL + END + +END + + +END +GO + + +--------------------------------------------- + +-- dbo.procEnsureDimensionColumnsInTable +CREATE proc [dbo].[procEnsureDimensionColumnsInTable] + @schemaname nvarchar(128), + @tableName nvarchar(128), + @mdcguid uniqueidentifier, + @debugmode bit, + @skipmodel bit +as + +DECLARE @dimensionName as nvarchar(256) +DECLARE @dimensionGUID as uniqueidentifier +DECLARE @listtype int +DECLARE @zzDIMcursor nvarchar(256) + + +DECLARE zzdimensions CURSOR LOCAL FAST_FORWARD +FOR SELECT SLM.LISTGUID, SLM.NAME, SLM.LISTTYPE, UPPER('G' + REPLACE(cast(SLM.LISTGUID as varchar(36)),'-','_')) FROM dbo.EMFModelDataConfigDimensionLink MDCDL JOIN SECURELIST SLM ON MDCDL.DIMENSIONGUID=SLM.LISTGUID WHERE MDCDL.MODELDATACONFIGGUID = @MDCGUID ORDER BY CASE WHEN SLM.LISTTYPE = 2 THEN 0 ELSE 1 END, CAST(SLM.LISTGUID as varchar(36)) ASC + +OPEN zzdimensions +FETCH NEXT FROM zzdimensions INTO @dimensionGUID, @dimensionName, @listtype, @zzDIMcursor +WHILE @@FETCH_STATUS = 0 +BEGIN + --SET @zzDIMcolumnname = @zzDIMcursor --+ 'GUID' + + IF @LISTTYPE = 2 BEGIN + IF @skipmodel = 0 BEGIN + exec procEnsureColumnInTable @schemaname, @tableName,'MODELGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode + END + END ELSE BEGIN + exec procEnsureColumnInTable @schemaname, @tableName,@zzDimCursor, 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode + END + + + FETCH NEXT FROM zzdimensions INTO @dimensionGUID, @dimensionName, @listtype, @zzDIMcursor +END +CLOSE zzdimensions +DEALLOCATE zzdimensions +GO + + +--------------------------------------------- + +-- dbo.procEnsureSchema +CREATE PROCEDURE dbo.procEnsureSchema( + @Schema nvarchar(128) +) +AS +BEGIN + + declare @count int; + select @count = count(*) from INFORMATION_SCHEMA.SCHEMATA where [SCHEMA_NAME] = @Schema; + + if (@count < 1) + begin + declare @sql varchar(max); + set @sql = 'CREATE SCHEMA [' + @Schema + '];'; + exec (@sql); + end + +END +GO + + +--------------------------------------------- + +-- dbo.procEnsureScoreDataTableSetup +CREATE proc [dbo].[procEnsureScoreDataTableSetup] + @dataTableGUID uniqueidentifier + ,@debugMode bit = 0 +as + +--set @dataTableGUID = 'BDD7EF92-5335-4FD1-9E0A-E22FF8A60CC8' +--set @debugMode = 0 +declare @mappingTableName nvarchar(max) +declare @SchemaName nvarchar(128) + +select + @mappingTableName = SQLObjectName, + @SchemaName = SQLSchemaName +from dbo.ScoreDataTable where DataTableGUID = @dataTableGUID + +exec procAddIdentityColumnToTable @SchemaName, @mappingTableName,'RowID', @DebugMode, '1', '1' +exec procEnsureColumnInTable @SchemaName, @mappingTableName,'HistoryItemGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode +exec procEnsureColumnInTable @SchemaName, @mappingTableName, 'Version', 'timestamp', '', @DebugMode +exec procEnsureColumnInTable @SchemaName, @mappingTableName, 'IsDeleted', 'bit', '0', @DebugMode +GO + + +--------------------------------------------- + +-- dbo.procEnsureScoreMappingTableSetup +CREATE proc [dbo].[procEnsureScoreMappingTableSetup] + @dataTableGUID uniqueidentifier + ,@debugMode bit = 0 + ,@isLegacy bit = 0 +as + +--set @dataTableGUID = 'BDD7EF92-5335-4FD1-9E0A-E22FF8A60CC8' +--set @debugMode = 0 +declare @mappingTableName nvarchar(max) +declare @SchemaName nvarchar(128) +select + @mappingTableName = SQLObjectName, + @SchemaName = SQLSchemaName +from dbo.ScoreDataTable where DataTableGUID = @dataTableGUID + +exec procEnsureScoreDataTableSetup @dataTableGUID, @debugMode +exec procEnsureColumnInTable @SchemaName, @mappingTableName,'RowExpanded', 'int', '0', @DebugMode +exec procEnsureColumnInTable @SchemaName, @mappingTableName,'CellGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode +exec procEnsureColumnInTable @SchemaName, @mappingTableName,'IsUserMapped', 'bit', '1', @DebugMode +exec procEnsureColumnInTable @SchemaName, @mappingTableName,'MeasureGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode + +exec procEnsureScoreMeasureExists @datatableguid,'RowExpanded',2,@debugmode +exec procEnsureScoreMeasureExists @datatableguid,'CellGUID',1,@debugmode +exec procEnsureScoreMeasureExists @datatableguid,'IsUserMapped',10,@debugmode +exec procEnsureScoreMeasureExists @datatableguid,'MeasureGUID',8,@debugmode + +if @isLegacy = 1 begin + exec procEnsureColumnInTable @SchemaName, @mappingTableName,'IsReadFromDB', 'bit', '0', @DebugMode + exec procEnsureColumnInTable @SchemaName, @mappingTableName,'IsWrittenToDB', 'bit', '0', @DebugMode + exec procEnsureColumnInTable @SchemaName, @mappingTableName,'IsLocked', 'bit', '0', @DebugMode + exec procEnsureColumnInTable @SchemaName, @mappingTableName,'IsAssumptionInput', 'bit', '0', @DebugMode + exec procEnsureColumnInTable @SchemaName, @mappingTableName,'IsAssumptionOutput', 'bit', '0', @DebugMode + exec procEnsureColumnInTable @SchemaName, @mappingTableName,'CompositeGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode + exec procEnsureScoreMeasureExists @datatableguid,'IsWrittenToDB',3,@debugmode + exec procEnsureScoreMeasureExists @datatableguid,'IsReadFromDB',4,@debugmode + exec procEnsureScoreMeasureExists @datatableguid,'IsLocked',5,@debugmode + exec procEnsureScoreMeasureExists @datatableguid,'IsAssumptionInput',6,@debugmode + exec procEnsureScoreMeasureExists @datatableguid,'IsAssumptionOutput',7,@debugmode + exec procEnsureScoreMeasureExists @datatableguid,'CompositeGUID',9,@debugmode +end + + + --CellGUID = 1 + --RowExpanded = 2 + --IsWrittenToDB = 3 + --IsReadFromDB = 4 + --IsLocked = 5 + --IsAssumptionInput = 6 + --IsAssumptionOutput = 7 + --MeasureGUID = 8 +--guid = 36 +--int = 52 +--bit = 104 +--go +--alter proc procEnsureScoreMeasureExists +-- @dataTableGUID uniqueidentifier +-- ,@columnName varchar(64) +-- ,@sqlDataType int +-- ,@specialMeasureIndex tinyint +-- ,@isDebug bit = 0 +--as + +--declare @cnt int +--select @cnt = COUNT(*) from dbo.ScoreMeasure sm where sm.DataTableGUID = @dataTableGUID and SQLColumnName = @columnName +--if @cnt = 0 begin + +-- if @isDebug = 1 begin +-- select @columnName, @datatableguid,1,1,@columnName, '{0}.' + @columnName, @sqlDataType,@specialMeasureIndex +-- end else begin +-- insert into dbo.ScoreMeasure (FriendlyName,DataTableGUID,IsReadFromDB,IsWrittenToDB,SQLColumnName, SQLColumnExpression, SQLDataType, SpecialMeasureIndex) +-- select @columnName, @datatableguid,1,1,@columnName, '{0}.' + @columnName, @sqlDataType,@specialMeasureIndex +-- end +--end +GO + + +--------------------------------------------- + +-- dbo.procEnsureScoreMeasureExists +CREATE proc [dbo].[procEnsureScoreMeasureExists] + @dataTableGUID uniqueidentifier + ,@columnName varchar(64) + ,@specialMeasureIndex tinyint + ,@isDebug bit = 0 +as + +declare @cnt int +select @cnt = COUNT(*) from dbo.ScoreMeasure sm where sm.DataTableGUID = @dataTableGUID and SQLColumnName = @columnName +if @cnt = 0 begin + --measure missing completely + if @isDebug = 1 begin + select @columnName, @datatableguid,1,1,@columnName, '{0}.' + @columnName, @specialMeasureIndex + end else begin + insert into dbo.ScoreMeasure (FriendlyName,DataTableGUID,IsReadFromDB,IsWrittenToDB,SQLColumnName, SpecialMeasureIndex) + select @columnName, @datatableguid,1,1,@columnName, @specialMeasureIndex + end +end else if @cnt = 1 begin + select @cnt = COUNT(*) from dbo.ScoreMeasure sm where sm.DataTableGUID = @dataTableGUID and SQLColumnName = @columnName and SpecialMeasureIndex = @specialMeasureIndex + if @cnt = 0 begin + --special measure index is wrong + if @isDebug = 1 begin + print 'Index not set correctly for ' + @columnname + end else begin + update dbo.ScoreMeasure set SpecialMeasureIndex = @specialMeasureIndex where DataTableGUID = @dataTableGUID and SQLColumnName = @columnName + end + end +end +GO + + +--------------------------------------------- + +-- dbo.procEnsureUserAppModeAccessLink +CREATE proc procEnsureUserAppModeAccessLink ( + @UserGUID uniqueidentifier, + @AccessLevel tinyint = 1 +) +AS +BEGIN +if ((select COUNT(*) from UserProfileAppModeAccessLink where UserGUID = @UserGUID and AccessLevel = @AccessLevel) = 0) + insert into UserProfileAppModeAccessLink (UserGUID, AccessLevel) VALUES (@UserGUID, @AccessLevel); +END +GO + + +--------------------------------------------- + +-- dbo.procEnsureUserAppModeAccessLinkAllUsers +create procedure procEnsureUserAppModeAccessLinkAllUsers +AS +BEGIN + +declare crsCursor CURSOR FAST_FORWARD FOR + select UserGUID from UserProfile + +open crsCursor; + +DECLARE @guid uniqueidentifier + +FETCH NEXT FROM crsCursor into @guid +WHILE (@@FETCH_STATUS = 0) + BEGIN + + exec procEnsureUserAppModeAccessLink @guid; + FETCH NEXT FROM crsCursor into @guid + END +close crsCursor; +DEALLOCATE crsCursor; + +END +GO + + +--------------------------------------------- + +-- dbo.procErrorPrint +-- Create procedure to retrieve error information. +create PROCEDURE procErrorPrint +AS +print ' +ERRORNUMBER: ' + cast(ERROR_NUMBER() as varchar(max)) + ' +ERROR_SEVERITY: ' + cast(ERROR_SEVERITY() as varchar(max)) + ' +ERROR_STATE: ' + cast(ERROR_STATE() as varchar(max)) + ' +ERROR_PROCEDURE: ' + cast(ERROR_PROCEDURE() as varchar(max)) + ' +ERROR_LINE: ' + cast(ERROR_LINE() as varchar(max)) + ' +ERROR_MESSAGE: ' + cast(ERROR_MESSAGE() as varchar(max)) +GO + + +--------------------------------------------- + +-- dbo.procEventUpdate +CREATE proc procEventUpdate + @eventname varchar(64) +as + +insert into Event (EventName) +select @eventname where not @eventname in (select eventname from Event) + +if @@ROWCOUNT = 0 begin + update + Event + set + EventName = EventName + where + EventName = @eventname +end +GO + + +--------------------------------------------- + +-- dbo.procExpansionDeleteInvalidMemberSelections +CREATE PROC procExpansionDeleteInvalidMemberSelections AS +DELETE xmem FROM + EMFModelTemplateExpansion Ex + INNER JOIN EMFModelTemplateExpansionLabel lab ON ex.EXPANSIONGUID = lab.EXPANSIONGUID + INNER JOIN EMFEntityExpansionMember xmem ON xmem.EXPANSIONGUID = ex.EXPANSIONGUID + INNER JOIN SecureListMember mem ON xmem.DIMENSIONMEMBERGUID = mem.listmemberguid +WHERE + ex.DIMENSIONLEVEL <> mem.OUTLINELEVEL +GO + + +--------------------------------------------- + +-- dbo.procFE2UpdateFormFieldSection +CREATE PROCEDURE [dbo].[procFE2UpdateFormFieldSection]( + @FormFieldGUID As UNIQUEIDENTIFIER, + @FormSectionGUID As UNIQUEIDENTIFIER, + @IgnoreColumn As BIT +) +AS +BEGIN + DECLARE + @Row INT, + @Col INT + + SELECT @Row=MAX(Row) + FROM [dbo].[FE2FormField] + WHERE FormSectionGUID = @FormSectionGUID + + IF @Row IS NULL + BEGIN + SET @Row = 0 + SET @Col = 0 + END + ELSE IF (@IgnoreColumn = 1 OR EXISTS (SELECT 1 FROM [dbo].[FE2FormField] WHERE FormSectionGUID = @FormSectionGUID and Row=@Row and Col=1)) + BEGIN + SET @Row += 1 + SET @Col = 0 + END + ELSE BEGIN + SET @Col = 1 + END + + UPDATE [dbo].[FE2FormField] + SET Col=@Col, Row=@Row, FormSectionGUID=@FormSectionGUID + WHERE FormFieldGUID=@FormFieldGUID AND FormSectionGUID != @FormSectionGUID + +END +GO + + +--------------------------------------------- + +-- dbo.procFindPerformanceFlaws +CREATE PROCEDURE [dbo].[procFindPerformanceFlaws] + @SchemaName NVARCHAR(10) = '', -- Provide the schema you wish to check + @SpecificObj NVARCHAR(1000) = '' -- If you are looking for a specific object, specify it here, otherwise the entire schema will be checked +AS +BEGIN + + /* + Script Owner: Mike Y. + + Script Notes: + - This is not a performant script, so ignore the amount of cursors, can always tweak it later + - There are false positives, will work on trying to narrow that down as we use this + - Will add more checks as time goes on. + + Left to do: + - Use Search Arguments ( will look /search for table scan at SQL level in Perf Env as a first step) + - Avoid using table variables, cursors or function calls that evaluate each row in where clause + + Change Log: + 07/12/2019 - Added table level checks + */ + + SET NOCOUNT ON; + IF OBJECT_ID('tempdb.dbo.#objects') IS NOT NULL + DROP TABLE #objects + + IF OBJECT_ID('tempdb.dbo.#Results') IS NOT NULL + DROP TABLE #Results + + CREATE TABLE #Results ( + Name NVARCHAR(MAX), + ObjectType NVARCHAR(MAX), + Severity SMALLINT, + Category NVARCHAR(MAX), + Description NVARCHAR(MAX) + ) + + SELECT * + INTO #objects + FROM [sys].[objects] + WHERE type IN ('U', 'P', 'V') -- https://docs.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-objects-transact-sql?view=sql-server-2017 + AND schema_id = SCHEMA_ID(@SchemaName) + AND (@SpecificObj = '' OR object_id = OBJECT_ID(@SchemaName + '.' + @SpecificObj)) + + IF ((SELECT COUNT(*) FROM #objects) = 0) + BEGIN + SELECT @SchemaName + '.' + @SpecificObj + ' was not found in this database' AS Error + RETURN; + END + + -- Use table compression if it will grow over 1,000 rows + CREATE TABLE #FactPageCompression ( + Name NVARCHAR(MAX), + ObjectType NVARCHAR(MAX) + ) + + -- Loop through any procs + DECLARE @ObjectId INT, + @SchemaId INT, + @Type NVARCHAR(MAX) + + DECLARE crsObjs CURSOR FAST_FORWARD FOR SELECT Object_Id, Schema_Id, Type_Desc FROM #objects WHERE Type != 'U' + OPEN crsObjs + FETCH NEXT FROM crsObjs INTO @ObjectId, @SchemaId, @Type + DECLARE @sql NVARCHAR(MAX) + WHILE (@@fetch_status = 0) + BEGIN + SELECT @sql = OBJECT_DEFINITION(@ObjectId) + + INSERT INTO #Results (Name, ObjectType, Category, Description, Severity) + SELECT SCHEMA_NAME(@SchemaId) + '.' + OBJECT_NAME(@ObjectId), @Type, Category, Description, Severity FROM [dbo].[funcFindTSQLPerformanceFlaws](@sql); + + FETCH next FROM crsObjs INTO @ObjectId, @SchemaId, @Type + + END + CLOSE crsObjs + DEALLOCATE crsObjs + + DECLARE @TableName NVARCHAR(MAX); + + -- Table Checks + DECLARE crsTbls cURSOR FAST_FORWARD FOR SELECT Object_Id, Schema_Id, Type_Desc FROM #objects WHERE Type = 'U' + OPEN crsTbls + FETCH NEXT FROM crsTbls INTO @ObjectId, @SchemaId, @Type + WHILE (@@fetch_status = 0) + BEGIN + SELECT @sql = OBJECT_DEFINITION(@ObjectId) + + IF (OBJECT_NAME(@ObjectId) LIKE ('%Fact%')) + BEGIN + + IF NOT EXISTS(SELECT 1 FROM sys.partitions SP LEFT OUTER JOIN sys.indexes IX ON sp.object_id = ix.object_id and sp.index_id = ix.index_id + WHERE sp.data_compression > 0 AND sp.object_id = @ObjectId) + BEGIN + INSERT INTO #FactPageCompression (Name, ObjectType) VALUES (SCHEMA_NAME(@SchemaId) + '.' + OBJECT_NAME(@ObjectId), @Type) + END + + END + + FETCH next FROM crsTbls INTO @ObjectId, @SchemaId, @Type + END + CLOSE crsTbls + DEALLOCATE crsTbls + + -- Check for tables that need page compression + SELECT + SCHEMA_NAME(sOBJ.Schema_Id) + '.' + sOBJ.name AS [Name], + sOBJ.Type_Desc AS ObjectType, + 'Table Compression' AS Category, + 'Use Page Compression on all Tables containing over 1000 rows' AS Description + INTO #TablesNeedingPageCompression + FROM + #objects AS sOBJ + INNER JOIN sys.partitions AS sPTN ON sOBJ.object_id = sPTN.object_id + WHERE + sOBJ.type = 'U' + AND sPTN.Rows >= 1000 + AND sPTN.data_compression = 0 + AND SCHEMA_NAME(sOBJ.schema_id) = @SchemaName + ORDER BY [Name] + + -- Clustered Index needed + SELECT SCHEMA_NAME(o.Schema_Id) + '.' + o.name AS [Name], + o.Type_Desc AS ObjectType, + 'Clustered Index' AS Category, + 'This table does not have a clustered index, verify if this needs a clustered index or not. This helps JOINs, WHERE operations and Order/Group By clauses' AS Description + INTO #ClusterIndex + FROM sys.indexes i + INNER JOIN #objects o ON i.object_id = o.object_id + WHERE o.type_desc = 'USER_TABLE' + AND i.type_desc = 'HEAP' -- determine which tables in our database are a 'heap', meaning they do not have a clustered index. https://www.mssqltips.com/sqlservertip/2510/sql-server-tables-without-a-clustered-index/ + AND SCHEMA_NAME(o.schema_id) = @SchemaName + AND OBJECT_NAME(o.Object_ID) NOT LIKE ('%Fact%') + ORDER BY o.name + + -- Check column size + SELECT SCHEMA_NAME(o.Schema_Id) + '.' + TABLE_NAME as Name, + o.Type_Desc AS ObjectType, + 'Column Size' AS Category, + 'Keep the columns short (data size), verify that the columns truly need to be MAX' AS Description + INTO #ColumnSize + FROM INFORMATION_SCHEMA.COLUMNS i + INNER JOIN #objects o ON i.TABLE_NAME = OBJECT_NAME(o.object_id) + WHERE TABLE_SCHEMA = @SchemaName AND CHARACTER_MAXIMUM_LENGTH = -1 + + -- Populate results tables + + -- Severity + -- 3 - High + -- 2 - Medium + -- 1 - Low + + IF ((SELECT COUNT(*) FROM #FactPageCompression) > 0) + BEGIN + INSERT INTO #Results (Name, ObjectType, Category, Description, Severity) + SELECT Name, ObjectType, 'Table Compression' AS Category, 'Use Page Compression on all Fact Tables' AS Description, 3 AS Severity FROM #FactPageCompression + END + + IF ((SELECT COUNT(*) FROM #TablesNeedingPageCompression) > 0) + BEGIN + INSERT INTO #Results (Name, ObjectType, Category, Description, Severity) + SELECT Name, ObjectType, Category, Description, 2 AS Severity FROM #TablesNeedingPageCompression + END + + IF ((SELECT COUNT(*) FROM #ClusterIndex) > 0) + BEGIN + INSERT INTO #Results (Name, ObjectType, Category, Description, Severity) + SELECT Name, ObjectType, Category, Description, 3 AS Severity FROM #ClusterIndex + END + + IF ((SELECT COUNT(*) FROM #ColumnSize) > 0) + BEGIN + INSERT INTO #Results (Name, ObjectType, Category, Description, Severity) + SELECT Name, ObjectType, Category, Description, 1 AS Severity FROM #ColumnSize + END + + SELECT Name, CASE WHEN Severity = 3 THEN 'High' + WHEN Severity = 2 THEN 'Medium' + WHEN Severity = 1 THEN 'Low' ELSE 'N/A' END AS Severity, + ObjectType, Category, Description + FROM #Results + ORDER BY Name, Category, ObjectType + +END +GO + + +--------------------------------------------- + +-- dbo.procFixSelfModelLinks +CREATE proc [dbo].[procFixSelfModelLinks] + @modelguid uniqueidentifier +as + +set nocount on + +--delete those for wrong tempaltes or dead plans +delete + emfmodeldatalink +from + emfmodeldatalink +where + not exists + ( select 1 + from + xplan p + left join emfmodeltemplatelinksource ls on p.modeltemplateguid = ls.modeltemplateguid + where + emfmodeldatalink.modelguid = p.planguid + and emfmodeldatalink.linksourceguid = ls.linksourceguid + and p.planguid = @modelguid + ) + and modelguid = @modelguid + + +--plan other than self for one marked self +update + emfmodeldatalink +set + parentmodelguid = modelguid +where + parentmodelguid <> modelguid + and linksourceguid in (select linksourceguid from emfmodeltemplatelinksource where isself = 1) + and modelguid = @modelguid + +--missing for correct template +insert into emfmodeldatalink (linksourceguid, modelguid, parentmodelguid) +select + ls.linksourceguid, p.planguid, p.planguid +from + xplan p + inner join emfmodeltemplatelinksource ls on p.modeltemplateguid = ls.modeltemplateguid and ls.isself = 1 +where + not exists( + select 1 + from + emfmodeldatalink mdl + where + mdl.modelguid = p.planguid + and mdl.linksourceguid = ls.linksourceguid + ) + and p.planguid = @modelguid +GO + + +--------------------------------------------- + +-- dbo.procFixSelfModelLinksAll +create proc [dbo].[procFixSelfModelLinksAll] + @debug bit = 0 +as + +if @debug = 0 + set nocount on + +--delete those for wrong tempaltes or dead plans +delete + emfmodeldatalink +from + emfmodeldatalink +where + not exists + ( select 1 + from + xplan p + left join emfmodeltemplatelinksource ls on p.modeltemplateguid = ls.modeltemplateguid + where + emfmodeldatalink.modelguid = p.planguid + and emfmodeldatalink.linksourceguid = ls.linksourceguid + ) + + +--plan other than self for one marked self +update + emfmodeldatalink +set + parentmodelguid = modelguid +where + parentmodelguid <> modelguid + and linksourceguid in (select linksourceguid from emfmodeltemplatelinksource where isself = 1) + +--missing for correct template +insert into emfmodeldatalink (linksourceguid, modelguid, parentmodelguid) +select + ls.linksourceguid, p.planguid, p.planguid +from + xplan p + inner join emfmodeltemplate mt on p.modeltemplateguid = mt.modeltemplateguid + inner join emfmodeltemplatelinksource ls on mt.modeltemplateguid = ls.modeltemplateguid and ls.isself = 1 + left join emfmodeldatalink mdl on mdl.linksourceguid = ls.linksourceguid and mdl.modelguid = p.planguid +where + mdl.modelguid is null +GO + + +--------------------------------------------- + +-- dbo.procFixSelfModelLinksAllIncludingNonSelf +create proc [dbo].[procFixSelfModelLinksAllIncludingNonSelf] + @debug bit = 0 +as + +if @debug = 0 + set nocount on + +--delete those for wrong tempaltes or dead plans +delete + emfmodeldatalink +from + emfmodeldatalink +where + not exists + ( select 1 + from + xplan p + left join emfmodeltemplatelinksource ls on p.modeltemplateguid = ls.modeltemplateguid + where + emfmodeldatalink.modelguid = p.planguid + and emfmodeldatalink.linksourceguid = ls.linksourceguid + ) + + +--plan other than self for one marked self +update + emfmodeldatalink +set + parentmodelguid = modelguid +where + parentmodelguid <> modelguid + and linksourceguid in (select linksourceguid from emfmodeltemplatelinksource ) + +--missing for correct template +insert into emfmodeldatalink (linksourceguid, modelguid, parentmodelguid) +select + ls.linksourceguid, p.planguid, p.planguid +from + xplan p + inner join emfmodeltemplate mt on p.modeltemplateguid = mt.modeltemplateguid + inner join emfmodeltemplatelinksource ls on mt.modeltemplateguid = ls.modeltemplateguid + left join emfmodeldatalink mdl on mdl.linksourceguid = ls.linksourceguid and mdl.modelguid = p.planguid +where + mdl.modelguid is null +GO + + +--------------------------------------------- + +-- dbo.procFixZZTables +CREATE PROCEDURE [dbo].[procFixZZTables] + @DebugMode bit = 0 +AS +BEGIN + SET NOCOUNT ON; + + DECLARE @zzMDCGUID uniqueidentifier + DECLARE @mdcName nvarchar(max) + DECLARE @zzMDCtablename nvarchar(36) +-- DECLARE @zzDIMcursor nvarchar(256) +-- DECLARE @zzDIMcolumnname nvarchar(256) + DECLARE @modelTemplateMappingTableName nvarchar(256) + DECLARE @modelDataTableName nvarchar(256) +-- DECLARE @dimensionName as nvarchar(256) +-- DECLARE @dimensionGUID as uniqueidentifier +-- DECLARE @fixSQL as nvarchar(max) + + DECLARE zztable CURSOR LOCAL FAST_FORWARD + FOR SELECT NAME, MODELDATACONFIGGUID FROM EMFMODELDATACONFIG + OPEN zztable + FETCH NEXT FROM zztable INTO @mdcName, @zzMDCGUID + WHILE @@FETCH_STATUS = 0 + BEGIN + + + --SET @zztable_query = 'ALTER TABLE ' + @zztable_name + ' ADD [MAPPINGTYPE] int NOT NULL Default(0) WITH VALUES' + --EXECUTE sp_executesql @zztable_query + SET @zzMDCtablename = REPLACE(@zzMDCGUID,'-','_') + + SET @modelTemplateMappingTableName = 'zzEMFModelTemplateMapping_' + @zzMDCtablename + if (select count(*) from sysobjects where xtype='u' and name like @modelTemplateMappingTableName) = 0 + PRINT @modelTemplateMappingTableName + ' table is not present' + else begin + exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'MODELTEMPLATEGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode + exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'CELLGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode + exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'SOURCEGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode + exec procEnsureDimensionColumnsInTable 'dbo', @modelTemplateMappingTableName, @zzMDCGUID, @DebugMode, 1 + exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'MEASUREGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode + exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'WORKSHEETGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode + exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'ROW', 'int', '0', @DebugMode + exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'COL', 'int', '0', @DebugMode + exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'ISREADONLY', 'bit', '0', @DebugMode + exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'IsLocked', 'bit', '0', @DebugMode + exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'IsReadFromDB', 'bit', '1', @DebugMode + exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'IsWrittenToDB', 'bit', '1', @DebugMode + exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'IsUserMapped', 'bit', '1', @DebugMode + exec procEnsureColumnInTableCopyFromOther 'dbo', @modelTemplateMappingTableName ,'RowDesigner', 'int', '0', 'Row', @DebugMode + exec procEnsureColumnInTable 'dbo', @modelTemplateMappingTableName ,'AssumptionType', 'int', '0', @DebugMode + exec procEnsureColumnNotInTable 'dbo', @modelTemplateMappingTableName, 'riskvariabletemplateguid', @DebugMode + end + + + SET @modelDataTableName = 'zzEMFModelData_' + @zzMDCtablename + if (select count(*) from sysobjects where xtype='u' and name like @modelDataTableName) = 0 + PRINT @modelDataTableName + ' table is not present' + else begin + --exec procEnsureColumnInTable @modelDataTableName ,'MODELGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode + exec procEnsureDimensionColumnsInTable 'dbo', @modelDataTableName, @zzMDCGUID, @DebugMode, 0 + exec procEnsureColumnInTable 'dbo', @modelDataTableName ,'MEASUREGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode + exec procEnsureColumnInTable 'dbo', @modelDataTableName ,'VALUE', 'float', '0', @DebugMode + exec procEnsureColumnInTable 'dbo', @modelDataTableName ,'FORMULA', 'varchar(1024)', '''''', @DebugMode + exec procEnsureColumnInTable 'dbo', @modelDataTableName ,'STRINGVALUE', 'varchar(1024)', '''''', @DebugMode + exec procEnsureColumnInTable 'dbo', @modelDataTableName ,'HISTORYITEMGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode + exec procEnsureColumnInTable 'dbo', @modelDataTableName ,'SUBTABLEROWGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode + exec procEnsureColumnInTable 'dbo', @modelDataTableName ,'DATAROWGUID', 'uniqueidentifier', 'newid()', @DebugMode + exec procEnsureColumnInTable 'dbo', @modelDataTableName ,'ISACTIVE', 'bit', '1', @DebugMode + exec procEnsureColumnNotInTable 'dbo', @modelDataTableName, 'riskvariableguid', @DebugMode + + end + + +-- DECLARE zzdimensions CURSOR LOCAL FAST_FORWARD +-- FOR SELECT SLM.LISTGUID, SLM.NAME, UPPER('G' + REPLACE(cast(SLM.LISTGUID as varchar(36)),'-','_')) FROM dbo.EMFModelDataConfigDimensionLink MDCDL JOIN SECURELIST SLM ON MDCDL.DIMENSIONGUID=SLM.LISTGUID WHERE MDCDL.MODELDATACONFIGGUID = @zzMDCGUID +-- OPEN zzdimensions +-- FETCH NEXT FROM zzdimensions INTO @dimensionGUID, @dimensionName, @zzDIMcursor +-- WHILE @@FETCH_STATUS = 0 +-- BEGIN +-- SET @zzDIMcolumnname = @zzDIMcursor --+ 'GUID' +-- SET @fixSQL = 'DELETE FROM emfmodeldataconfigdimensionlink WHERE DIMENSIONGUID = ''' + cast(@dimensionGUID as varchar(36)) + ''' and MODELDATACONFIGGUID = ''' + cast(@zzMDCGUID as varchar(36)) + '''' +-- IF (SELECT count(*) FROM sysobjects JOIN syscolumns ON sysobjects.id = syscolumns.id WHERE sysobjects.xtype='U' AND (sysobjects.name like @modelDataTableName or sysobjects.name like @modelMappingTableName or sysobjects.name like @modelTemplateMappingTableName)and syscolumns.name like @zzDIMcolumnname) <> 3 +-- --PRINT ' ' + @zzDIMcolumnname + ' is present' +-- --ELSE +-- PRINT @fixSQL + ' --' + cast(@zzMDCGUID as varchar(36)) + ' (' + @mdcName + ') - ' + @zzDIMcolumnname + ' (' + @dimensionName + ') is not present in both ModelData and ModelMapping' +-- +-- +-- FETCH NEXT FROM zzdimensions INTO @dimensionGUID, @dimensionName, @zzDIMcursor +-- END +-- CLOSE zzdimensions +-- DEALLOCATE zzdimensions +-- + FETCH NEXT FROM zztable INTO @mdcName, @zzMDCGUID + END + CLOSE zztable + DEALLOCATE zztable + +END +GO + + +--------------------------------------------- + +-- dbo.procFormDataCreateMissing +CREATE proc [dbo].[procFormDataCreateMissing] + @plantypeguid uniqueidentifier = '00000000-0000-0000-0000-000000000000', + @isdebug bit = 0 +as + --this proc exists for backwards compatibility only + return +GO + + +--------------------------------------------- + +-- dbo.procFormField10Delete +CREATE PROCEDURE [dbo].[procFormField10Delete] + @FormFieldGUID uniqueidentifier +AS +BEGIN + if((select count(*) from FEFormField where FormFieldGUID = @FormFieldGUID) = 0) begin + return + end + + --remove from forms + declare @placeholder varchar(128) + select @placeholder = '' from FEFormField where FormFieldGUID = @FormFieldGUID + update FEFormSection set HTMLDesign = replace(HTMLDesign, @placeholder, ''), HTML = replace(HTML, @placeholder, '') where HTMLDesign like '%' + @placeholder + '%' + + --remove data + delete from FEFormData where FormFieldGUID = @FormFieldGUID + + --remove form field mappings + delete from EMFModelTemplateFormFieldMapping where FormFieldGUID = @FormFieldGUID + + --remove custom script + delete from CustomScript where CustomScriptGUID=(select sourceguid from FEFormField where FormFieldGUID = @FormFieldGUID) + + --remove gridsettings + delete from GridSetting where ColumnID='G' + replace(cast(@FormFieldGUID as varchar(36)), '-', '_') + + --remove field + delete from FEFormField where FormFieldGUID = @FormFieldGUID +END +GO + + +--------------------------------------------- + +-- dbo.procFormFieldCalculationActionTask +CREATE PROC [dbo].[procFormFieldCalculationActionTask] + @isDebugOnly bit = 0 +AS + SET NOCOUNT ON + + DECLARE @sql varchar(max); + + SET @sql = ' + DECLARE @statusCode INT; + SET @statusCode = 0; + EXEC [dbo].[procCreateTask] + @taskTypeName = ''Strata.CS.Jazz.Biz.FormEngine20.ComputedFields.ComputedFieldControllerTask, Strata.CS.Jazz.Biz'', + @contextXML = ''1procFormFieldCalculationActionTask'', + @taskSource = ''procFormFieldCalculationActionTask'', + @statusCode = @statusCode OUTPUT; + IF @statusCode < 200 OR @statusCode > 299 + BEGIN + RAISERROR(''Failed to insert to Hangfire'',16,1); + END; + '; + + IF (@isDebugOnly = 0) BEGIN + EXEC (@sql) + END ELSE BEGIN + PRINT @sql + END +GO + + +--------------------------------------------- + +-- dbo.procFormFieldCalculationRefresh +CREATE PROCEDURE [dbo].[procFormFieldCalculationRefresh] + @formfieldguid uniqueidentifier, + @entityexpression nvarchar(max) = '', + @directoryrefresh bit = 0, + @refreshmodefilter int = 0 +AS + --for backwards compatibility, refresh all fields tied to this formfieldguid + declare @allfields nvarchar(max) + select @allfields = dbo.StrAggr(cast(FormFieldGUID as nvarchar(36)), ',', '') from [dbo].[FE2FormField] (readuncommitted) where FormFieldGUID = @formfieldguid or OldFormFieldGUID = @formfieldguid + + if(len(@allfields) > 0) begin + insert into [dbo].[FE2FormFieldRefreshRequest] (FormFieldGUIDCSV, PlanLookupSQL) values(@allfields, @entityexpression) + exec procFormFieldCalculationActionTask + end +GO + + +--------------------------------------------- + +-- dbo.procFormFieldCalculationRefreshAll +CREATE PROCEDURE [dbo].[procFormFieldCalculationRefreshAll] + @plantypeguid uniqueidentifier +AS + insert into [dbo].[FE2FormFieldRefreshRequest] (PlanTypeGUID) values(@plantypeguid) + exec procFormFieldCalculationActionTask +GO + + +--------------------------------------------- + +-- dbo.procFormFieldCalculationRefreshAllByEntity +CREATE PROCEDURE [dbo].[procFormFieldCalculationRefreshAllByEntity] + @entityexpression nvarchar(max), + @isdebug bit = 0 +AS + insert into [dbo].[FE2FormFieldRefreshRequest] (PlanLookupSQL) values(@entityexpression) + exec procFormFieldCalculationActionTask @isdebug +GO + + +--------------------------------------------- + +-- dbo.procFormFieldCalculationRefreshByPlanType +CREATE PROCEDURE [dbo].[procFormFieldCalculationRefreshByPlanType] + @formfieldguid uniqueidentifier, + @plantypeguid uniqueidentifier, + @entityexpression nvarchar(max) = '', + @createmissing bit = 1, + @isbulk bit = 0 +AS + insert into [dbo].[FE2FormFieldRefreshRequest] (FormFieldGUIDCSV, PlanTypeGUID, PlanLookupSQL) select cast(@formfieldguid as nvarchar(36)), @plantypeguid, @entityexpression + exec procFormFieldCalculationActionTask +GO + + +--------------------------------------------- + +-- dbo.procFormFieldCalculationRefreshMultiple +CREATE PROCEDURE [dbo].[procFormFieldCalculationRefreshMultiple] + @formfieldguidCSV nvarchar(max), + @entityexpression nvarchar(max) = '', + @directoryrefresh bit = 0, + @refreshmodefilter int = 0 +AS + if(len(@formfieldguidCSV) > 0) begin + insert into [dbo].[FE2FormFieldRefreshRequest] (FormFieldGUIDCSV, PlanLookupSQL) values(@formfieldguidCSV, @entityexpression) + exec procFormFieldCalculationActionTask + end +GO + + +--------------------------------------------- + +-- dbo.procFormFieldCalculationRefreshNoSync +CREATE proc [dbo].[procFormFieldCalculationRefreshNoSync] + @planGUIDList nvarchar(max), + @refreshMode int = 2 +as + --this procedure is obsolete given FE20, but still exists for backwards compatibility + RETURN +GO + + +--------------------------------------------- + +-- dbo.procFormFieldCalculationRefreshNoSyncAll +CREATE proc [dbo].[procFormFieldCalculationRefreshNoSyncAll] + @planTypeGUID uniqueidentifier, + @refreshMode int = 2 +as + --this procedure is obsolete given FE20, but still exists for backwards compatibility + RETURN +GO + + +--------------------------------------------- + +-- dbo.procFormFieldCalculationTest +create proc dbo.procFormFieldCalculationTest + @formfieldguid uniqueidentifier +as + declare @refreshsql nvarchar(max) + select @refreshsql = LastRefreshSQL from [dbo].[viewFE2FormFieldComputed] where FormFieldGUID = @formfieldguid + + if (@refreshsql is null) begin + print 'Field not found.' + return + end + + if (len(ltrim(rtrim(@refreshsql))) = 0) begin + print 'Refresh SQL not found. Please go to Admin Tools and refresh this field with test mode enabled, and then try again.' + return + end + + print @refreshsql + exec(@refreshsql) +GO + + +--------------------------------------------- + +-- dbo.procFormHTMLPrint +create procedure procFormHTMLPrint + @formdefguid uniqueidentifier +as + declare @html nvarchar(max) + declare crsSections cursor for select html from feformsection where formdefguid=@formdefguid order by parentformsectionguid, displayorder + open crsSections + fetch next from crsSections into @html + while(@@fetch_status = 0) begin + print @html + fetch next from crsSections into @html + end + close crsSections + deallocate crsSections +GO + + +--------------------------------------------- + +-- dbo.procGenerateDataMessages +CREATE PROCEDURE [dbo].[procGenerateDataMessages] + @MAXMESSAGESPERTOPIC int, + @IGNORETOPICGUID varchar(36) = '' + +AS +BEGIN + SET NOCOUNT ON + + declare @authorguid uniqueidentifier + declare @emptyguid varchar(36) + declare @nummessages int + declare @count int + declare @TOPICGUID uniqueidentifier + + set @emptyguid = '00000000-0000-0000-0000-000000000000' + + -- loop through all topics and create respective messages + DECLARE crsTopics cursor LOCAL FAST_FORWARD FOR select topicguid from msgtopic + OPEN crsTopics + FETCH NEXT FROM crsTopics into @TOPICGUID + + WHILE (@@FETCH_STATUS = 0) + BEGIN + + If (@IGNORETOPICGUID <> @TOPICGUID) + BEGIN + SET @nummessages = ROUND(@MAXMESSAGESPERTOPIC * rand(), 0) + If (@nummessages = 0) + BEGIN + SET @nummessages = 1 + END + + PRINT cast(@nummessages as varchar) + ' messages created for topicguid = ' --+ cast(@TOPICGUID as varchar) + + SET @count = 1 + WHILE (@count <= @nummessages) + BEGIN + SELECT @authorguid = userguid from userprofile order by newid() + + INSERT INTO MSGMESSAGE(messageguid, topicguid, messagetypeguid, replytomsgguid, subject, body, authorguid, datecreated, datesent, hasattachments) + SELECT top 1 newid(), @TOPICGUID, messagetypeguid, replytomsgguid, subject, body, @authorguid, dateadd(hour, @count * (24 - @count) * rand(), datecreated), datesent, hasattachments from msgmessage order by newid() + + SET @count = @count + 1 + END + + PRINT @TOPICGUID + END + FETCH NEXT FROM crsTopics into @TOPICGUID + END + + CLOSE crsTopics + DEALLOCATE crsTopics + + SET NOCOUNT OFF +END +GO + + +--------------------------------------------- + +-- dbo.procGenerateDataTopics +CREATE PROCEDURE [dbo].[procGenerateDataTopics] + @NUMTOPICS int, + @COPYTOPICGUID varchar(36) = '' + +AS +BEGIN + SET NOCOUNT ON + + declare @authorguid uniqueidentifier + declare @emptyguid varchar(36) + + set @emptyguid = '00000000-0000-0000-0000-000000000000' + + declare @i int + set @i = 0 + while (@i < @NUMTOPICS) begin + --copy an existing x number of times + if (@COPYTOPICGUID <> '') + BEGIN + SELECT @COPYTOPICGUID = topicguid from msgtopic where topicguid = @COPYTOPICGUID + if (@COPYTOPICGUID is not null) + BEGIN + SELECT @authorguid = userguid from userprofile order by newid() + insert into msgtopic (topicguid, forumguid, authorguid, [name], description, topictype, datecreated) + select newid(), forumguid, @authorguid, 'Copy of ' + [name] + cast(@i as varchar), description, topictype, dateadd(day, @i + 1, datecreated) from msgtopic where topicguid = @COPYTOPICGUID + + PRINT 'Topic created' + END + END + else + BEGIN + SELECT @authorguid = userguid from userprofile order by newid() + + --currently can only create private message topics + insert into msgtopic (topicguid, forumguid, authorguid, [name], description, topictype, datecreated) values(newid(), @emptyguid, @authorguid, newid(), newid(), 2, getdate()) + END + set @i = @i + 1 + end + + SET NOCOUNT OFF +END +GO + + +--------------------------------------------- + +-- dbo.procGetCompactedUserACL +CREATE PROCEDURE [dbo].[procGetCompactedUserACL] + @UserGUID uniqueidentifier +AS + IF (NOT EXISTS(SELECT 1 FROM UserProfile (readuncommitted) WHERE UserGUID = @UserGUID)) BEGIN RETURN END + + --everything user has access to + CREATE TABLE #UserACL(LootGroupPrefix nvarchar(100), LootID nvarchar(128), IsFullAccess bit, IsReadable bit, IsWritable bit, IsSecurable bit, IsDeletable bit, IsCreatable bit) + INSERT #UserACL + SELECT + LootGroupPrefix, + LootID, + CAST(0 as bit) as IsFullAccess, + IsReadable, + IsWritable, + IsSecurable, + IsDeletable, + IsCreatable + FROM + dbo.ufn_GetS3ACLByUserGuid(@UserGUID) + + --loot groups where the user has access to everything + CREATE TABLE #FullAccess(LootGroupPrefix nvarchar(100), LootID nvarchar(128), IsFullAccess bit, IsReadable bit, IsWritable bit, IsSecurable bit, IsDeletable bit, IsCreatable bit) + INSERT #FullAccess + SELECT + L.LootGroupPrefix, + '' as LootID, + CAST(1 as bit) as IsFullAccess, + CAST(1 as bit) as IsReadable, + CAST(1 as bit) as IsWritable, + CAST(1 as bit) as IsSecurable, + CAST(1 as bit) as IsDeletable, + CAST(1 as bit) as IsCreatable + FROM + S3Loot L (readuncommitted) + GROUP BY + L.LootGroupPrefix + HAVING + (select COUNT(*) from #UserACL acl where acl.LootGroupPrefix = L.LootGroupPrefix and acl.IsReadable = 1 and acl.IsWritable = 1 and acl.IsCreatable = 1 and acl.IsDeletable = 1 and acl.IsSecurable = 1) >= COUNT(*) + + --compact acl based on full access + DELETE FROM #UserACL where LootGroupPrefix in(select LootGroupPrefix from #FullAccess) + + --include items user has no access to + INSERT #UserACL + SELECT + L.LootGroupPrefix, + L.LootID as LootID, + CAST(0 as bit) as IsFullAccess, + CAST(0 as bit) as IsReadable, + CAST(0 as bit) as IsWritable, + CAST(0 as bit) as IsSecurable, + CAST(0 as bit) as IsDeletable, + CAST(0 as bit) as IsCreatable + FROM + S3Loot L (readuncommitted) + WHERE + not exists (select 1 from #UserACL acl where acl.LootID = L.LootID) + and not exists(select 1 from #FullAccess fa where fa.LootGroupPrefix = L.LootGroupPrefix) + + --return acl + full access groups + SELECT * FROM #UserACL + UNION ALL + SELECT * FROM #FullAccess + + --clean up + DROP TABLE #UserACL + DROP TABLE #FullAccess +GO + + +--------------------------------------------- + +-- dbo.procGetDimensionAttributesToReportRelationInfo +CREATE proc [dbo].[procGetDimensionAttributesToReportRelationInfo] +as + set nocount on +declare @departmentDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'Department') + +declare @capProjectDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'CAP Project') +declare @fundingReleaseDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'CAP Funding Release') +declare @requisitionDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'CAP Requisition') +declare @substitutionSourceDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'CAP Substitution') + +declare @longRangePlanDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'SP Long Range Plan') +declare @rollingForecastPlanDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'SP Rolling Forecast Plan') +declare @longRangeServiceLineDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'SP Long Range Service Line') +declare @rollingServiceLinePlanDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'SP Rolling Service Line Plan') + +declare @departmentalBudgetDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'OB Departmental Budget') + +declare @departmentMrDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'MR Department') + +declare @attributeGuids table (AttributeGUID uniqueidentifier) + +declare @departmentAttributeGuids table (AttributeGUID uniqueidentifier) +insert into @departmentAttributeGuids +select AttributeGUID from viewScoreAttribute where DimensionGUID = @departmentDimGuid + +--department attributes +insert into @attributeGuids +select AttributeGUID from @departmentAttributeGuids + +--department mr attributes +declare @departmentMrAttributeGuids table (AttributeGUID uniqueidentifier, DepartmentAttributeGUID uniqueidentifier) +insert into @departmentMrAttributeGuids +select distinct mr.AttributeGUID, d.AttributeGUID +from viewScoreAttribute mr +join viewScoreAttribute d on d.DimensionGUID = @departmentDimGuid + and d.SqlColumnName=mr.SqlColumnName +where mr.DimensionGUID = @departmentMrDimGuid + +insert into @attributeGuids +select AttributeGUID from @departmentMrAttributeGuids + +--ob departmental budget +declare @obAttributeGuids table (AttributeGUID uniqueidentifier, InferredAttributeGuid uniqueidentifier) +insert into @obAttributeGuids +select AttributeGUID, InferredAttributeGuid from viewScoreAttribute +where DimensionGUID = @departmentalBudgetDimGuid AND InferredAttributeGuid IN (select AttributeGUID from @departmentAttributeGuids) +insert into @attributeGuids +select AttributeGUID from @obAttributeGuids + +--sp long Range Plan +declare @splongRangeAttributeGuids table (AttributeGUID uniqueidentifier, InferredAttributeGuid uniqueidentifier) +insert into @splongRangeAttributeGuids +select AttributeGUID, InferredAttributeGuid from viewScoreAttribute +where DimensionGUID = @longRangePlanDimGuid AND InferredAttributeGuid IN (select AttributeGUID from @departmentAttributeGuids) +insert into @attributeGuids +select AttributeGUID from @splongRangeAttributeGuids + +--sp rolling Forecast Plan +declare @sprollingForecastAttributeGuids table (AttributeGUID uniqueidentifier, InferredAttributeGuid uniqueidentifier) +insert into @sprollingForecastAttributeGuids +select AttributeGUID, InferredAttributeGuid from viewScoreAttribute +where DimensionGUID = @rollingForecastPlanDimGuid AND InferredAttributeGuid IN (select AttributeGUID from @departmentAttributeGuids) +insert into @attributeGuids +select AttributeGUID from @sprollingForecastAttributeGuids + +--sp long Range Service Line +declare @splongRangeServiceLineAttributeGuids table (AttributeGUID uniqueidentifier, InferredAttributeGuid uniqueidentifier) +insert into @splongRangeServiceLineAttributeGuids +select AttributeGUID, InferredAttributeGuid from viewScoreAttribute +where DimensionGUID = @longRangeServiceLineDimGuid AND InferredAttributeGuid IN (select AttributeGUID from @departmentAttributeGuids) +insert into @attributeGuids +select AttributeGUID from @splongRangeServiceLineAttributeGuids + +--sp rolling Service Line Plan +declare @sprollingServiceLinePlanAttributeGuids table (AttributeGUID uniqueidentifier, InferredAttributeGuid uniqueidentifier) +insert into @sprollingServiceLinePlanAttributeGuids +select AttributeGUID, InferredAttributeGuid from viewScoreAttribute +where DimensionGUID = @rollingServiceLinePlanDimGuid AND InferredAttributeGuid IN (select AttributeGUID from @departmentAttributeGuids) +insert into @attributeGuids +select AttributeGUID from @sprollingServiceLinePlanAttributeGuids + +--cap Project +declare @capProjectAttributeGuids table (AttributeGUID uniqueidentifier, InferredAttributeGuid uniqueidentifier) +insert into @capProjectAttributeGuids +select AttributeGUID, InferredAttributeGuid from viewScoreAttribute +where DimensionGUID = @capProjectDimGuid AND InferredAttributeGuid IN (select AttributeGUID from @departmentAttributeGuids) +insert into @attributeGuids +select AttributeGUID from @capProjectAttributeGuids + +--cap funding Release +declare @capfundingReleaseAttributeGuids table (AttributeGUID uniqueidentifier, InferredAttributeGuid uniqueidentifier) +insert into @capfundingReleaseAttributeGuids +select attr.AttributeGUID, cattr.InferredAttributeGuid from viewScoreAttribute attr +join @capProjectAttributeGuids cattr on cattr.AttributeGUID = attr.InferredAttributeGuid +where DimensionGUID = @fundingReleaseDimGuid +insert into @attributeGuids +select AttributeGUID from @capfundingReleaseAttributeGuids + +--cap requisition +declare @caprequisitionAttributeGuids table (AttributeGUID uniqueidentifier, InferredAttributeGuid uniqueidentifier) +insert into @caprequisitionAttributeGuids +select attr.AttributeGUID, attr.InferredAttributeGuid from viewScoreAttribute attr +join @capProjectAttributeGuids cattr on cattr.AttributeGUID = attr.InferredAttributeGuid +where DimensionGUID = @requisitionDimGuid +insert into @attributeGuids +select AttributeGUID from @caprequisitionAttributeGuids + +--cap substitution +declare @capsubstitutionAttributeGuids table (AttributeGUID uniqueidentifier, InferredAttributeGuid uniqueidentifier) +insert into @capsubstitutionAttributeGuids +select attr.AttributeGUID, attr.InferredAttributeGuid from viewScoreAttribute attr +join @capProjectAttributeGuids cattr on cattr.AttributeGUID = attr.InferredAttributeGuid +where DimensionGUID = @substitutionSourceDimGuid +insert into @attributeGuids +select AttributeGUID from @capsubstitutionAttributeGuids + +-- Result table to return +declare @result table (AttributeGUID uniqueidentifier, ReportGUID uniqueidentifier, FrameworkID tinyint) + +declare @frameworkInfo table (FrameworkID tinyint, FrameworkName nvarchar(100), ReportFrameworkPrefix nvarchar(5)) +insert into @frameworkInfo select (select FrameworkID from fw.DimFramework where Name = 'Capital Management'), 'Capital Management', 'CAP' +insert into @frameworkInfo select (select FrameworkID from fw.DimFramework where Name = 'Operating Budgeting'), 'Operating Budgeting', 'OB' +insert into @frameworkInfo select (select FrameworkID from fw.DimFramework where Name = 'Management Reporting'), 'Management Reporting', 'MR' +insert into @frameworkInfo select (select FrameworkID from fw.DimFramework where Name = 'Strategic Planning'), 'Strategic Planning', 'SP' +insert into @frameworkInfo select (select FrameworkID from fw.DimFramework where Name = 'Productivity Reporting'), 'Productivity Reporting', 'PR' +insert into @frameworkInfo select (select FrameworkID from fw.DimFramework where Name = 'Decision Support'), 'Decision Support', 'DS' + +-- Cursor configuration +declare @frameworkId tinyInt +declare @frameworkName nvarchar(100) +declare @prefix nvarchar(5) +declare crsFrameworks cursor fast_forward for + select FrameworkID, FrameworkName, ReportFrameworkPrefix + from @frameworkInfo + +open crsFrameworks +fetch next from crsFrameworks into @frameworkId, @frameworkName, @prefix + +while (@@fetch_status = 0) + begin + insert into @result + --ad hoc reports using the attribute for this framework + select + cast(ra.AttributeID as uniqueidentifier), r.ReportGUID, @frameworkId + from + REClientReportSectionAttribute ra + inner join REClientReportSectionLink sl on sl.ClientReportSectionGUID = ra.ClientReportSectionGUID + inner join REReport r on r.ReportGUID = sl.ReportGUID + inner join REClientReportDataSourceLink rdsl on r.ReportGUID = rdsl.ReportGUID + inner join DataView dv on rdsl.DataSourceGUID = dv.DataViewGUID + inner join Folder f on f.FolderGUID = r.FolderGUID + left join Folder pf on pf.FolderGUID = f.ParentFolderGUID + where + ra.AttributeID in (select cast(AttributeGUID as nvarchar(36)) from @attributeGuids) + and + (dv.Name like (@prefix + '%') + or (f.Name = @frameworkname or isnull(pf.Name, '') = @frameworkname)) + + insert into @result + --ad hoc reports using the attribute for this framework as filter + select + cast(ra.AttributeID as uniqueidentifier), r.ReportGUID, @frameworkId + from + REClientReportParameter ra + inner join REReport r on r.ReportGUID = ra.ReportGUID + inner join REClientReportDataSourceLink rdsl on r.ReportGUID = rdsl.ReportGUID + inner join DataView dv on rdsl.DataSourceGUID = dv.DataViewGUID + inner join Folder f on f.FolderGUID = r.FolderGUID + left join Folder pf on pf.FolderGUID = f.ParentFolderGUID + where + ra.AttributeID in (select cast(AttributeGUID as nvarchar(36)) from @attributeGuids) + and + (dv.Name like (@prefix + '%') + or (f.Name = @frameworkname or isnull(pf.Name, '') = @frameworkname)) + + insert into @result + --tabular detail reports using the attribute for this framework + select + ra.AttributeGUID, r.ReportGUID, @frameworkId + from + RESQLReportDisplayColumn dc + inner join RESQLReportSetup rs on rs.SQLReportSetupGUID = dc.SQLReportSetupGUID + inner join REReport r on r.ReportGUID = rs.ReportGUID + inner join RESQLReportRegisteredDimension rd on rd.DataViewGUID = rs.DataViewGUID + inner join RESQLReportRegisteredAttribute ra on ra.RegisteredDimensionGUID = rd.RegisteredDimensionGUID + inner join dbo.ScoreAttribute a on a.AttributeGUID = ra.AttributeGUID + inner join DataView dv on rd.DataViewGUID = dv.DataViewGUID + inner join Folder f on f.FolderGUID = r.FolderGUID + left join Folder pf on pf.FolderGUID = f.ParentFolderGUID + where + ltrim(rtrim(dc.ColumnName)) = case when ltrim(rtrim(ra.ColumnAlias)) = '' then a.SQLColumnName else ltrim(rtrim(ra.ColumnAlias)) end + and ra.AttributeGUID in (select AttributeGUID from @attributeGuids) + and (dv.Name like (@prefix + '%') + or (f.Name = @frameworkname or isnull(pf.Name, '') = @frameworkname)) + + fetch next from crsFrameworks into @frameworkId, @frameworkName, @prefix + end +close crsFrameworks +deallocate crsFrameworks + +declare @resultFinal table (AttributeGUID uniqueidentifier, ReportGUID uniqueidentifier, FrameworkID tinyint) + +insert into @resultFinal +select distinct r.AttributeGUID, r.ReportGUID, r.FrameworkID +from @result r +join @departmentAttributeGuids d on d.AttributeGUID=r.AttributeGUID + +insert into @resultFinal +select distinct d.DepartmentAttributeGUID, r.ReportGUID, r.FrameworkID +from @result r +join @departmentMrAttributeGuids d on d.AttributeGUID=r.AttributeGUID + + +insert into @resultFinal +select distinct d.InferredAttributeGuid, r.ReportGUID, r.FrameworkID +from @result r +join @obAttributeGuids d on d.AttributeGUID=r.AttributeGUID + +insert into @resultFinal +select distinct d.InferredAttributeGuid, r.ReportGUID, r.FrameworkID +from @result r +join @splongRangeAttributeGuids d on d.AttributeGUID=r.AttributeGUID + +insert into @resultFinal +select distinct d.InferredAttributeGuid, r.ReportGUID, r.FrameworkID +from @result r +join @sprollingForecastAttributeGuids d on d.AttributeGUID=r.AttributeGUID + +insert into @resultFinal +select distinct d.InferredAttributeGuid, r.ReportGUID, r.FrameworkID +from @result r +join @splongRangeServiceLineAttributeGuids d on d.AttributeGUID=r.AttributeGUID + +insert into @resultFinal +select distinct d.InferredAttributeGuid, r.ReportGUID, r.FrameworkID +from @result r +join @sprollingServiceLinePlanAttributeGuids d on d.AttributeGUID=r.AttributeGUID + +insert into @resultFinal +select distinct d.InferredAttributeGuid, r.ReportGUID, r.FrameworkID +from @result r +join @capProjectAttributeGuids d on d.AttributeGUID=r.AttributeGUID + +insert into @resultFinal +select distinct p.InferredAttributeGuid, r.ReportGUID, r.FrameworkID +from @result r +join @capfundingReleaseAttributeGuids d on r.AttributeGUID=d.AttributeGUID +join @capProjectAttributeGuids p on d.InferredAttributeGuid=p.AttributeGUID + +insert into @resultFinal +select distinct p.InferredAttributeGuid, r.ReportGUID, r.FrameworkID +from @result r +join @caprequisitionAttributeGuids d on r.AttributeGUID=d.AttributeGUID +join @capProjectAttributeGuids p on d.InferredAttributeGuid=p.AttributeGUID + +insert into @resultFinal +select distinct p.InferredAttributeGuid, r.ReportGUID, r.FrameworkID +from @result r +join @capsubstitutionAttributeGuids d on r.AttributeGUID=d.AttributeGUID +join @capProjectAttributeGuids p on d.InferredAttributeGuid=p.AttributeGUID + +select distinct r.AttributeGUID, r.ReportGUID, r.FrameworkID +from @resultFinal r +order by AttributeGUID, FrameworkID +GO + + +--------------------------------------------- + +-- dbo.procGetInputDataByBatches +/* +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-08-17 HV JAZZ-41822 PR Metrics Definition - Select Standard Metrics - Productive Hours, UOS Staffing, Productive Hours per UOS +** 2 2022-10-13 KF JAZZ-44078 Charge Based Statistics Modals Performance Improvement +** 3 2023-10-10 KF JAZZ-61890 Technical - Convert pi.FactMetric and pi.FactMetricDaily Rowid and dependent objects to bigint +************************************************************ +*/ +CREATE PROCEDURE [dbo].[procGetInputDataByBatches] + @batchSize int = 10000, + @columnName nvarchar(100), + @tableAlias nvarchar(100), + @fromClause nvarchar(max), + @whereClause nvarchar(max), + @declareParameters nvarchar(max) = '', + @isDebug bit = 0 +AS + +DECLARE @columnNameWithAlias nvarchar(200) +set @columnNameWithAlias = @tableAlias + '.' + @columnName + +DECLARE @sql nvarchar(max) = '' + +IF @declareParameters IS NOT NULL AND @declareParameters != '' BEGIN + SET @sql = @sql + 'DECLARE +' + @declareParameters + ' +' +END + +SET @sql = @sql + ' +IF OBJECT_ID(''tempdb..#inputData'') IS NOT NULL DROP TABLE #inputData + +SELECT ' + @columnNameWithAlias + ', COUNT_BIG(*) AS RecordsCount, 0 AS BatchID INTO #inputData +FROM ' + @fromClause + +IF NOT( @whereClause is null or @whereClause = '') +BEGIN + SET @sql = @sql + ' + WHERE ' + @whereclause +END + +SET @sql = @sql + ' +GROUP BY ' + @columnNameWithAlias + ' + +-- Split data into batches +WHILE EXISTS (SELECT TOP 1 1 FROM #inputData WHERE BatchID = 0) +BEGIN + ;WITH infoTable AS + ( + SELECT + IPP.' + @columnName + ', + ROW_NUMBER() OVER (ORDER BY IPP.' + @columnName + ') AS RowNumber, + SUM(RecordsCount) OVER (ORDER BY IPP.' + @columnName + ') AS Total, + M.MaxBatchID+1 AS BatchID + FROM #inputData IPP + CROSS JOIN (SELECT MAX(BatchID) AS MaxBatchID FROM #inputData) M + WHERE IPP.BatchID = 0 + ) + UPDATE IPP + SET IPP.BatchID = MI.BatchID + FROM #inputData IPP + INNER JOIN infoTable MI ON MI.' + @columnName + ' = IPP.' + @columnName + ' + WHERE MI.Total <= ' + cast(@BatchSize as nvarchar(100)) + ' OR MI.RowNumber = 1 +END + +select * from #inputData' + +IF @isDebug = 1 +BEGIN + PRINT (cast(@sql as ntext)); +END +ElSE +BEGIN + EXEC (@sql); +END +GO + + +--------------------------------------------- + +-- dbo.procGetNextQueuedTask +CREATE PROCEDURE [dbo].[procGetNextQueuedTask] + @MinPriority int = 0, + @WhereClause varchar(MAX), + @WorkerID uniqueidentifier = '00000000-0000-0000-0000-000000000000' + AS +DECLARE @sql varchar(MAX) + +--SQL +SET @sql = 'BEGIN TRANSACTION;' +SET @sql = @sql + ' DECLARE @NEXTQUEUEDTASKGUID uniqueidentifier; ' +SET @sql = @sql + 'SELECT TOP 1 @NEXTQUEUEDTASKGUID = t.TaskGUID FROM TETASK t WITH (updlock, rowlock, readpast) left join TEDISABLEDDATABASE ddb on t.dbconnectionguid = ddb.disableddbconnectionguid where ddb.disableddbconnectionguid is null and t.status <> 1 and t.status <> 4 and GETDATE() > t.NextRunTime' + +IF (@WhereClause <> '') BEGIN + SET @sql = @sql + ' and ' + @WhereClause +END +SET @sql = @sql + ' and priority >= ' + cast(@MinPriority as varchar); +--Grouping +set @sql = @sql + ' and not exists ( select 1 from TETask T0 where T0.GroupingID <> '''' and T0.GroupingID = t.GroupingID and T0.GroupingIndex < t.GroupingIndex)'; +set @sql = @sql + ' order by t.priority DESC, t.creationtime;' +SET @sql = @sql + ' UPDATE TETASK WITH (updlock, rowlock, readpast) SET STATUS=1, STARTTIME = getDate(), WorkerID=''' + cast(@WorkerID as varchar(36)) + ''' where TaskGUID = @NEXTQUEUEDTASKGUID;' +SET @sql = @sql + ' SELECT * FROM TETASK WITH (updlock, rowlock, readpast) where TaskGUID = @NextQUEUEDTASKGUID;' +SET @sql = @sql + ' COMMIT TRANSACTION;' +print @sql; +exec (@sql) +GO + + +--------------------------------------------- + +-- dbo.procGetNextQueuedTaskByPriority +CREATE PROCEDURE [dbo].[procGetNextQueuedTaskByPriority] +@Priority int + AS + +DECLARE @TEMPTABLENAME varchar(38) +DECLARE @sql varchar(MAX) + +SET @TEMPTABLENAME = '#' + dbo.GetSQLColumnSafeGuid(newid()) + +--insert next queued item (all non-executing tasks) into temp table +SET @sql = 'BEGIN TRAN; SELECT TOP 1 t.* INTO ' + @TEMPTABLENAME + ' FROM TETASK t left join TEDISABLEDDATABASE ddb on t.dbconnectionguid = ddb.disableddbconnectionguid where ddb.disableddbconnectionguid is null and status <> 1 and priority < ' + cast(@Priority as varchar) + ' order by priority, creationtime;' + +-- if one task was entered into temp table, then +-- find taskguid from temp table and update real table with new status +-- return temp table +-- drop temp table +SET @sql = @sql + ' IF (SELECT COUNT(*) FROM ' + @TEMPTABLENAME + ') > 0 BEGIN ' +SET @sql = @sql + ' DECLARE @NEXTQUEUEDTASKGUID uniqueidentifier;' +SET @sql = @sql + ' SELECT @NEXTQUEUEDTASKGUID = TASKGUID FROM ' + @TEMPTABLENAME + ';' +SET @sql = @sql + ' UPDATE TETASK SET STATUS = 1, STARTTIME = getdate() WHERE TASKGUID = @NEXTQUEUEDTASKGUID; ' +SET @sql = @sql + ' SELECT * FROM ' + @TEMPTABLENAME + ';' +SET @sql = @sql + ' END' +SET @sql = @sql + ' DROP TABLE ' + @TEMPTABLENAME + ';' +SET @sql = @sql + ' COMMIT TRAN; ' + +exec (@sql) +GO + + +--------------------------------------------- + +-- dbo.procGetQueuedTaskCount +CREATE PROCEDURE [dbo].[procGetQueuedTaskCount] + @WhereClause varchar(4000) + AS + +DECLARE @sql varchar(MAX) +SET @sql = ' select count(*) from TETask t with (updlock, rowlock, readpast) where ' + @WhereClause + ' and Status=0 and GetDate() > t.NextRunTime;' +exec(@sql); +GO + + +--------------------------------------------- + +-- dbo.procGetRelatedPlans +CREATE PROCEDURE procGetRelatedPlans + @PlanGUID UNIQUEIDENTIFIER +AS +BEGIN + SET NOCOUNT ON + + DECLARE @keyAttributeGUID UNIQUEIDENTIFIER + DECLARE @keyColumnExpression NVARCHAR(MAX) + DECLARE @keyTableExpression NVARCHAR(MAX) + + SELECT TOP 1 + @keyAttributeGUID = sa.AttributeGUID, + @keyColumnExpression = sa.SQLColumnName, + @keyTableExpression = dbo.GetSQLTableExpression(dg.SchemaName, dg.ObjectName) + FROM XPlan p + JOIN PlanType pt ON pt.PlanTypeGUID = p.PlanTypeGUID + JOIN ScoreDimension d ON d.DimensionGUID = pt.DimensionGUID + JOIN ScoreDimensionGroup dg ON dg.DimensionGUID = d.DimensionGUID + JOIN ScoreAttribute sa ON sa.DimensionGroupGUID = dg.DimensionGroupGUID AND sa.AttributeGUID = d.DefaultKeyGUID + WHERE p.PlanGUID = @PlanGUID + + DECLARE @planId NVARCHAR(MAX) + DECLARE @getIdSql NVARCHAR(MAX) = + 'SELECT @planId = ' + @keyColumnExpression + ' FROM ' + @keyTableExpression + ' ' + + 'WHERE MemberGUID = ''' + CAST(@PlanGUID AS NVARCHAR(36)) + '''' + + EXEC sp_executesql @getIdSql, N'@planId NVARCHAR(MAX) OUTPUT', @planId = @planId OUTPUT + + DROP TABLE IF EXISTS #child_plan_queries + + SELECT + NEWID() AS QueryGUID, + dbo.GetSQLTableExpression(dg.SchemaName, dg.ObjectName) AS TableExpression, + sa.SQLColumnName AS ColumnExpression + INTO #child_plan_queries + FROM PlanType pt + JOIN ScoreDimension d ON d.DimensionGUID = pt.DimensionGUID + JOIN ScoreDimensionGroup dg ON dg.DimensionGUID = d.DimensionGUID + JOIN ScoreAttribute sa ON sa.DimensionGroupGUID = dg.DimensionGroupGUID + WHERE sa.ForeignKeyGUID = @keyAttributeGUID + + DECLARE @sql NVARCHAR(MAX) = '' + + WHILE (SELECT COUNT(1) FROM #child_plan_queries) > 0 + BEGIN + DECLARE @queryGUID UNIQUEIDENTIFIER + DECLARE @tableExpression NVARCHAR(MAX) = '' + DECLARE @columnExpression NVARCHAR(MAX) = '' + DECLARE @childMemberGUID UNIQUEIDENTIFIER = dbo.GetZeroGUID() + + SELECT TOP 1 + @queryGUID = QueryGUID, + @tableExpression = TableExpression, + @columnExpression = ColumnExpression + FROM #child_plan_queries + ORDER BY TableExpression, ColumnExpression + + DELETE #child_plan_queries WHERE QueryGUID = @queryGUID + + SET @sql = @sql + + 'SELECT MemberGUID AS PlanGUID ' + + 'FROM ' + @tableExpression + ' ' + + 'WHERE ' + @columnExpression + ' = ' + @planId + ' ' + + 'UNION ALL ' + END + + SET @sql = TRIM('UNION ALL ' FROM @sql) + EXEC sp_executesql @sql +END +GO + + +--------------------------------------------- + +-- dbo.procGetScoreDimensionMember +CREATE proc [dbo].[procGetScoreDimensionMember] + @MemberGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000' +AS + +declare @out table + ( + MemberGUID uniqueidentifier, + DefaultAttribute nvarchar(max), + AttributeValue nvarchar(max), + DimensionGUID uniqueidentifier, + DimensionName nvarchar(max), + DimensionTable nvarchar(max) + ) + +declare @DimensionGUID uniqueidentifier +declare @DimensionName nvarchar(max) +declare @TableExpression nvarchar(max) +declare @DefaultAttributeFriendlyName nvarchar(max) +declare @DefaultAttributeColumnExpression nvarchar(max) + +declare dimtables cursor local fast_forward for +select + SD.DimensionGUID, + SD.FriendlyName, + SD.SqlSchemaName + '.' + SD.SQLObjectName, + SA.FriendlyName, + SA.sqlcolumnname +from ScoreDimension SD + inner join ScoreAttribute SA on SA.AttributeGUID = SD.defaultlookupkeyguid + +open dimtables + fetch next from dimtables into @DimensionGUID, @DimensionName, @TableExpression, @DefaultAttributeFriendlyName, @DefaultAttributeColumnExpression + while @@fetch_status = 0 + begin + + declare @wc nvarchar(max) + set @wc = '' + if @MemberGUID <> '00000000-0000-0000-0000-000000000000' + set @wc = ' where MemberGUID = ''' + cast(@MemberGUID as nvarchar(max)) + '''' + + declare @sql nvarchar(max) + set @sql = 'select MemberGUID, ''' + @DefaultAttributeFriendlyName + ''' as DefaultAttribute, ' + @DefaultAttributeColumnExpression + ' as AttributeValue, ''' + cast(@DimensionGUID as nvarchar(max)) + ''', ''' + @DimensionName + ''' as DimensionName, ''' + @TableExpression + ''' as DimensionTable from ' + @TableExpression + @wc + + insert into @out + (MemberGUID, DefaultAttribute, AttributeValue,DimensionGUID, DimensionName, DimensionTable) + exec sp_executesql @sql + + fetch next from dimtables into @DimensionGUID, @DimensionName, @TableExpression, @DefaultAttributeFriendlyName, @DefaultAttributeColumnExpression + end +close dimtables +deallocate dimtables + +select * from @out +GO + + +--------------------------------------------- + +-- dbo.procGetSecuredMemberCount +CREATE PROCEDURE [dbo].[procGetSecuredMemberCount] + @LootGroupPrefix nvarchar(100) = '' +AS + IF (@LootGroupPrefix = '') + BEGIN + SELECT + COUNT(*) + FROM + S3Loot + WHERE + LootID NOT LIKE '%|%' + END + ELSE + BEGIN + SELECT + COUNT(*) + FROM + S3Loot + WHERE + LootID LIKE @LootGroupPrefix + '|%' + END +GO + + +--------------------------------------------- + +-- dbo.procGetSecurityDeniedMembersList +CREATE PROCEDURE [dbo].[procGetSecurityDeniedMembersList] + -- Add the parameters for the stored procedure here + @ListGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000', + @UserGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000' + AS + BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + + select cast(slm.ListMemberGUID as varchar(36)) + from SecureListMember slm + inner join SecureList sl on slm.ListGUID = sl.ListGUID and sl.IsSecured = 1 and sl.ListGUID = @ListGUID + left join viewS3ACL ACL on ACL.LootID = slm.LootIDOverride and ACL.UserGUID = @UserGUID + where ACL.IsReadable = 0 or ACL.IsReadable is null + + END +GO + + +--------------------------------------------- + +-- dbo.procGetTableReferencesInfo +CREATE PROCEDURE [dbo].[procGetTableReferencesInfo] + @tableSchema NVARCHAR(max), + @tableName NVARCHAR(max) +AS + +/* +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-09-14 BS JAZZ-42636 PR Metrics Definition: communication failure error when deleting many metrics with related pi.factmetric data +************************************************************ +*/ +SELECT DISTINCT U.COLUMN_NAME as ColumnName, R.COLUMN_NAME as RefColumnName, R.TABLE_SCHEMA as RefSchema, R.TABLE_NAME as RefName +FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE U +INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS FK on + U.CONSTRAINT_CATALOG = FK.UNIQUE_CONSTRAINT_CATALOG AND + U.CONSTRAINT_SCHEMA = FK.UNIQUE_CONSTRAINT_SCHEMA AND + U.CONSTRAINT_NAME = FK.UNIQUE_CONSTRAINT_NAME +INNER JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE R ON + R.CONSTRAINT_CATALOG = FK.CONSTRAINT_CATALOG AND + R.CONSTRAINT_SCHEMA = FK.CONSTRAINT_SCHEMA AND + R.CONSTRAINT_NAME = FK.CONSTRAINT_NAME +INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON + CU.CONSTRAINT_CATALOG = U.CONSTRAINT_CATALOG AND + CU.CONSTRAINT_SCHEMA = U.CONSTRAINT_SCHEMA AND + CU.CONSTRAINT_NAME = U.CONSTRAINT_NAME AND + CU.COLUMN_NAME = U.COLUMN_NAME AND + CU.TABLE_CATALOG = U.TABLE_CATALOG AND + CU.TABLE_SCHEMA = U.TABLE_SCHEMA AND + CU.TABLE_NAME = U.TABLE_NAME +INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE RC ON + RC.CONSTRAINT_CATALOG = R.CONSTRAINT_CATALOG AND + RC.CONSTRAINT_SCHEMA = R.CONSTRAINT_SCHEMA AND + RC.CONSTRAINT_NAME = R.CONSTRAINT_NAME AND + RC.COLUMN_NAME = R.COLUMN_NAME AND + RC.TABLE_CATALOG = R.TABLE_CATALOG AND + RC.TABLE_SCHEMA = R.TABLE_SCHEMA AND + RC.TABLE_NAME = R.TABLE_NAME AND + RC.ORDINAL_POSITION = CU.ORDINAL_POSITION +WHERE U.TABLE_SCHEMA = @tableSchema AND U.TABLE_NAME = @tableName +GO + + +--------------------------------------------- + +-- dbo.procGetTagCloud +CREATE procedure [dbo].[procGetTagCloud] ( + @MaxFontSize int, + @TagTable sysname, + @TagSchema sysname = 'dbo' +) +AS +BEGIN + +declare @sql varchar(max); + +set @sql = ' +declare @MaxFontSize int; +set @MaxFontSize = ' + cast(@MaxFontSize as nvarchar(max)) + ' +declare @Min int; +declare @Max int; + +WITH Tags (Tag, [Count]) +AS +( + select + T.Name as Tag, + COUNT(T.TagGUID) as [Count] + from [' + @TagSchema + '].[' + @TagTable + '] TI + inner join Tag T on T.TagGUID = TI.TagGUID + GROUP BY T.Name +) +SELECT @Min = MIN([Count]), @Max = MAX([Count]) from Tags + +select + T.TagGUID, + T.Name AS [Tag], + COUNT(TI.TagGUID) as [Count], + case when COUNT(TI.TagGUID) > @Min then (@MaxFontSize * (COUNT(TI.TagGUID) - @Min)) / (@Max - @Min) else 1 end as [FontSize] +from [' + @TagSchema + '].[' + @TagTable + '] TI + inner join Tag T on T.TagGUID = TI.TagGUID +group by T.Name, T.TagGUID + +'; + +print @sql; +exec (@sql); +END +GO + + +--------------------------------------------- + +-- dbo.procGetUniqueColumnValueForCopy +CREATE PROCEDURE [dbo].[procGetUniqueColumnValueForCopy] +( + @schema nvarchar(128), + @objectname nvarchar(128), + @column nvarchar(128), + @desiredvalue varchar(max) +) +AS +BEGIN + declare @retval varchar(max); + declare @sql nvarchar(max); + + SET @sql = N' + declare @index int; + set @index = 0; + set @testvalueOUT = @desiredvalue; + WHILE (1=1) + BEGIN + IF ((SELECT COUNT([' + @column + ']) FROM [' + @schema + '].[' + @objectname + '] WHERE [' + @column + '] = @testvalueOUT) > 0) + BEGIN + IF (@index = 0) + BEGIN + set @testvalueOUT = @desiredvalue + '' - Copy''; + END + ELSE + BEGIN + set @testvalueOUT = @desiredvalue + '' ('' + cast(@index as nvarchar(128)) + '') - Copy''; + END + + set @index = @index + 1; + END + ELSE + BEGIN + break; + END + END' + + exec sp_executesql + @sql, + N'@desiredvalue nvarchar(500), + @testvalueOUT nvarchar(500) OUTPUT + ', + @desiredvalue=@desiredvalue, + @testvalueOUT=@retval OUTPUT; + + + select @retval; + +END +GO + + +--------------------------------------------- + +-- dbo.procGetUnreadMessageCount +CREATE PROCEDURE [dbo].[procGetUnreadMessageCount] + @UserGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000' + AS + + select + count(*) + from + MsgTopic (readuncommitted) T + inner join MsgMessage (readuncommitted) M on T.TopicGUID = M.TopicGUID + inner join viewS3ACLSimple (readuncommitted) ACL on ACL.LootID = T.TopicGUID and ACl.IsReadable = 1 and acl.UserGUID = @UserGUID + where + not exists(select 1 from MsgTopicArchive (readuncommitted) ta where ta.UserGUID = @UserGUID and ta.TopicGUID = t.TopicGUID) + and not exists(select 1 from MsgMessageRead (readuncommitted) mr where mr.MessageGUID = m.MessageGUID and mr.UserGUID = @UserGUID and mr.IsRead = 1) +GO + + +--------------------------------------------- + +-- dbo.procGetUserSecurityLastModifiedDate +-- ============================================= +-- Author: +-- Create date: <6/24/2008> +-- Description: +-- ============================================= +CREATE PROCEDURE procGetUserSecurityLastModifiedDate + -- Add the parameters for the stored procedure here + @UserGUID uniqueidentifier +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + SELECT LastModifiedDate + FROM UserSecurityLastModifiedDate + WHERE UserGUID = @UserGUID + +END +GO + + +--------------------------------------------- + +-- dbo.procGetViewBaseTables +CREATE procedure [dbo].[procGetViewBaseTables] ( + @ViewSchema sysname, + @ViewName sysname +) +AS +BEGIN + + select + ViewSchema + ,ViewName + ,TableSchema + ,TableName + ,case when TableType = 'VIEW' then 1 else 0 end as [IsView] + ,[Level] + from viewSysViewBaseTables + where ViewName = @ViewName and ViewSchema = @ViewSchema + Order by [Level] + +END +GO + + +--------------------------------------------- + +-- dbo.procIRCCheckin +CREATE procedure [dbo].[procIRCCheckin] ( + @UserGUID uniqueidentifier, + @IRCChatGUID uniqueidentifier, + @LastMessageID bigint = -1 +) +AS +BEGIN + + BEGIN TRANSACTION + + --Determine last Checkin Time and Checkin + declare @LastCheckin datetime; + declare @Timestamp datetime; + declare @SQLTableName nvarchar(128) + + set @Timestamp = GETDATE(); + + select @LastCheckin = [LastCheckinTime] from dbo.IRCChatMembership WITH (READUNCOMMITTED) + where UserGUID = @UserGUID and IRCChatGUID = @IRCChatGUID; + + if (@LastCheckin is null) + begin + insert into dbo.IRCChatMembership (UserGUID, IRCChatGUID, LastCheckinTime) values (@UserGUID, @IRCChatGUID, @Timestamp); + end + else + begin + update dbo.IRCChatMembership set LastCheckinTime = @Timestamp where UserGUID = @UserGUID and IRCChatGUID = @IRCChatGUID; + end + + + --Clean up old users (haven't checked in for 15 seconds) + delete from dbo.IRCChatMembership where LastCheckinTime < DATEADD(SECOND,-15,GETDATE()) + + + --Find database table + select @SQLTableName = SQLTableName from dbo.IRCChat WITH (READUNCOMMITTED ) + where IRCChatGUID = @IRCChatGUID; + + + + --Begin Dataset Selects - read as dataset by code + + --Chat Membership + select UP.UserGUID, UP.NameFirst + ' ' + UP.NameLast as [NameFull], UP.UserName, ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0) AS IsSysAdmin from dbo.IRCChatMembership CM WITH (READUNCOMMITTED) + inner join UserProfile UP on UP.UserGUID = CM.UserGUID + left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = 'GEN - User Administrator') + where CM.IRCChatGUID = @IRCChatGUID + + --Last MessageID + declare @lSQL varchar(max); + set @lSQL = 'select COALESCE(MAX(MessageID),0) as [LastMessageID] from [irc].[' + @SQLTableName + ']'; + exec (@lSQL); + + + --New Messages + declare @sql varchar(max); + if (@LastMessageID = -1) + begin + set @sql = ' + select * from [irc].[' + @SQLTableName + '] where 1=0 + '; + -- set @sql = ' + -- select + -- C.[MessageID], + -- UP.[UserName], + -- UP.[UserGUID], + -- UP.[NameFirst] + '' '' + UP.NameLast as [FullName], + -- C.[Timestamp] as [Timestamp], + -- C.[MessageText] + -- from [irc].[' + @SQLTableName + '] C WITH (READUNCOMMITTED) + -- inner join dbo.UserProfile UP on UP.UserGUID = C.UserGUID + -- where C.[MessageID] > (select MAX(MessageID) - 50 from [irc].[' + @SQLTableName + ']) + -- order by C.[MessageID] + -- '; + end + else + begin + set @sql = ' + select + C.[MessageID], + UP.[UserName], + UP.[UserGUID], + UP.[NameFirst] + '' '' + UP.NameLast as [FullName], + C.[Timestamp] as [Timestamp], + C.[MessageText] + from [irc].[' + @SQLTableName + '] C WITH (READUNCOMMITTED) + inner join dbo.UserProfile UP on UP.UserGUID = C.UserGUID + where C.[MessageID] > ' + cast(@LastMessageID as nvarchar(128)) + ' + order by C.[MessageID] + '; + end + exec (@sql); + + COMMIT TRANSACTION + +END +GO + + +--------------------------------------------- + +-- dbo.procIRCClearOrphanedUsers +CREATE PROCEDURE dbo.procIRCClearOrphanedUsers +AS +BEGIN +--Clean up old users (haven't checked in for 15 seconds) + delete from dbo.IRCChatMembership where LastCheckinTime < DATEADD(SECOND,-15,GETDATE()) + END +GO + + +--------------------------------------------- + +-- dbo.procIRCCreateChatTable +CREATE procedure [dbo].[procIRCCreateChatTable] ( + @IRCChatGUID uniqueidentifier +) +AS +BEGIN + + BEGIN TRANSACTION + + declare @SQLTableName nvarchar(128); + --Find database table + select @SQLTableName = SQLTableName from dbo.IRCChat WITH (READUNCOMMITTED ) + where IRCChatGUID = @IRCChatGUID; + + + declare @sql varchar(max); + + set @sql = 'CREATE TABLE [irc].[' + @SQLTableName + '] ( + [MessageID] bigint not null primary key identity(1,1), + [Timestamp] datetime not null default getdate(), + [UserGUID] uniqueidentifier not null default dbo.ZeroGUID(), + [MessageText] nvarchar(max) not null default ''''); + ' + print @sql; + exec (@sql); + + COMMIT TRANSACTION + +END +GO + + +--------------------------------------------- + +-- dbo.procIRCDropChat +create procedure [dbo].[procIRCDropChat] ( + @IRCChatGUID uniqueidentifier +) +AS + + BEGIN TRANSACTION + + declare @SQLTableName nvarchar(128); + --Find database table + select @SQLTableName = SQLTableName from dbo.IRCChat WITH (READUNCOMMITTED ) + where IRCChatGUID = @IRCChatGUID; + + + declare @sql varchar(max); + + set @sql = 'DROP TABLE [irc].[' + @SQLTableName + '];' + + exec (@sql); + + COMMIT TRANSACTION +GO + + +--------------------------------------------- + +-- dbo.procIRCIsUserInChat +CREATE PROCEDURE [dbo].[procIRCIsUserInChat] ( + @IRCChatGUID uniqueidentifier, + @UserGUID uniqueidentifier +) +AS +BEGIN + + exec procIRCClearOrphanedUsers; + declare @IsUserInChat bit; + set @IsUserInChat = 0; + + declare @count int; + select @count = COUNT(M.IRCChatGUID) from dbo.IRCChatMembership M + where M.IRCChatGUID = @IRCChatGUID and M.UserGUID = @UserGUID; + + if (@count > 0) + set @IsUserInChat = 1; + + select @IsUserInChat; +END +GO + + +--------------------------------------------- + +-- dbo.procIRCLeaveChat +create procedure [dbo].[procIRCLeaveChat]( + @UserGUID uniqueidentifier, + @IRCChatGUID uniqueidentifier +) +AS +BEGIN + delete from dbo.IRCChatMembership where UserGUID = @UserGUID and IRCChatGUID = @IRCChatGUID +END +GO + + +--------------------------------------------- + +-- dbo.procIRCSendMessage +CREATE procedure [dbo].[procIRCSendMessage] ( + @UserGUID uniqueidentifier, + @IRCChatGUID uniqueidentifier, + @MessageText nvarchar(max) +) +AS +BEGIN + + BEGIN TRANSACTION + + set @MessageText = REPLACE(@MessageText, '''', '''''') + declare @SQLTableName nvarchar(128); + --Find database table + select @SQLTableName = SQLTableName from dbo.IRCChat WITH (READUNCOMMITTED ) + where IRCChatGUID = @IRCChatGUID; + + declare @sql varchar(max); + + set @sql = 'insert into [irc].[' + @SQLTableName + '] (MessageText, UserGUID) VALUES (''' + @MessageText + ''',''' + cast(@UserGUID as nvarchar(64)) + ''')' + + exec (@sql); + + COMMIT TRANSACTION + +END +GO + + +--------------------------------------------- + +-- dbo.procInitStandardReportSelector +CREATE PROCEDURE [dbo].[procInitStandardReportSelector] +AS +BEGIN +DECLARE @isExistRELootTypeTable bit; +DECLARE @isExistRESelectorTable bit; + +set @isExistRELootTypeTable = +(SELECT COUNT(NAME) +FROM SYS.TABLES +WHERE NAME = 'RELootType'); + +set @isExistRESelectorTable = +(SELECT COUNT(NAME) +FROM SYS.TABLES +WHERE NAME = 'RESelector'); + +print @isExistRELootTypeTable +print @isExistRESelectorTable + +IF @isExistRELootTypeTable = 0 +BEGIN + CREATE TABLE [dbo].[RELootType]( + [ID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_RELootType_ID] DEFAULT (newid()), + [LootType] [int] NOT NULL CONSTRAINT [DF_RELootType_LootType] DEFAULT ((0)), + [LootTypeName] [nvarchar](64) NOT NULL CONSTRAINT [DF_RELootType_LootTypeName] DEFAULT (''), + [VERSION] [timestamp] NOT NULL, + CONSTRAINT [PK_RELootType] PRIMARY KEY CLUSTERED + ( + [ID] 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 + +INSERT INTO RELootType +(ID, LootType, LootTypeName) +VALUES +( +'FC558834-7EA7-4A8C-94B7-111CAAAAE400', +0, +'Plan' +); + +INSERT INTO RELootType +(ID, LootType, LootTypeName) +VALUES +( +'891A6E54-5BC8-4088-85C8-323BCAA7C60E', +3, +'Report' +); + + + +INSERT INTO RELootType +(ID, LootType, LootTypeName) +VALUES +( +'d7927372-c3ad-4e3b-892d-d91de9fad1dc', +2, +'List' +); + +INSERT INTO RELootType +(ID, LootType, LootTypeName) +VALUES +( +'108a6a2a-0bf9-4d02-8e1d-cbe627eb12b5', +4, +'PlanType' +); + +INSERT INTO RELootType +(ID, LootType, LootTypeName) +VALUES +( +'85f7fe66-d6c9-4c9d-8136-c41f1f1eef8b', +8, +'FormField' +); + + + +INSERT INTO RELootType +(ID, LootType, LootTypeName) +VALUES +( +'45093B3D-35E3-48A2-B25E-756F4A1BC4CF', +7, +'System Section' +); + +INSERT INTO RELootType +(ID, LootType, LootTypeName) +VALUES +( +'6691EFEC-D8D9-4C99-ACF7-ACFCE80C9134', +99, +'All' +); + +INSERT INTO RELootType +(ID, LootType, LootTypeName) +VALUES +( +'29250C25-DBE4-4E7A-BFC9-E0CC32B501CC', +2, +'List Member' +); + +INSERT INTO RELootType +(ID, LootType, LootTypeName) +VALUES +( +'76BDE210-F4CD-4136-BC26-E50F9B6A56DA', +1, +'Folder' +); + +IF @isExistRESelectorTable = 0 +BEGIN + CREATE TABLE [dbo].[RESelector]( + [ID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_REBooleanSelector_ID] DEFAULT (newid()), + [Name] [nvarchar](64) NOT NULL, + [Value] [int] NOT NULL, + [Type] [nvarchar](64) NOT NULL, + [VERSION] [timestamp] NOT NULL + ) ON [PRIMARY] +END + + +INSERT INTO RESelector +(ID, Name, Value, Type) +VALUES +( +'72FFB9CB-BB88-4EF5-BD4F-B76D311CC2D9', +'Yes', +1, +'Boolean' +); + +INSERT INTO RESelector +(ID, Name, Value, Type) +VALUES +( +'A2D76819-7832-4078-AE5D-541A274195DB', +'No', +0, +'Boolean' +); + +END +GO + + +--------------------------------------------- + +-- dbo.procInsertStandardCodeTask +CREATE PROC dbo.procInsertStandardCodeTask +AS + +DECLARE @statusCode INT; +EXEC dbo.procCreateTask +@taskTypeName = 'Strata.CS.Jazz.Biz.StandardCodes.StandardCodesSyncTask, Strata.CS.Jazz.Biz', -- varchar(1000) +@contextXML = '', -- varchar(1000) +@userName = 'Migration', +@statusCode = @statusCode OUTPUT; +GO + + +--------------------------------------------- + +-- dbo.procIntDeleteInterfaceSectionTables +create procedure [dbo].[procIntDeleteInterfaceSectionTables] ( + @InterfaceSectionId uniqueidentifier, + @IntSchema nvarchar(128) = 'int' +) +AS +BEGIN + + declare @SectionName varchar(max); + select @SectionName = Name from dbo.IntDataInterfaceSection where DataInterfaceSectionID = @InterfaceSectionId + + declare @AcceptedTable sysname; + declare @RejectedTable sysname; + declare @AcceptedView sysname; + declare @RejectedView sysname; + + select @AcceptedTable = dbo.GetDataIntSectionAcceptedTableName(@InterfaceSectionId); + select @RejectedTable = dbo.GetDataIntSectionRejectedTableName(@InterfaceSectionId); + select @AcceptedView = dbo.GetDataIntSectionAcceptedViewName(@SectionName,@InterfaceSectionId); + select @RejectedView = dbo.GetDataIntSectionRejectedViewName(@SectionName,@InterfaceSectionId); + + if (dbo.TableExists(@IntSchema, @AcceptedTable) = 1) begin + exec procSysDropTable @IntSchema, @AcceptedTable; + end + if (dbo.TableExists(@IntSchema, @RejectedTable) = 1) begin + exec procSysDropTable @IntSchema, @RejectedTable; + end + if (dbo.ViewExists(@IntSchema, @AcceptedView) = 1) begin + exec procSysDropTable @IntSchema, @AcceptedView; + end + if (dbo.ViewExists(@IntSchema, @RejectedView) = 1) begin + exec procSysDropTable @IntSchema, @RejectedView; + end + +END +GO + + +--------------------------------------------- + +-- dbo.procIntTransactionCreate +CREATE procedure dbo.procIntTransactionCreate ( + @TransactionGUID uniqueidentifier, + @ConfigGUID uniqueidentifier, + @UserID uniqueidentifier, + @Comment nvarchar(800) +) +as +begin + insert into [dbo].[IntTransaction] + (TransactionGUID, ConfigID, UserID, StartTimeUtc, EndTimeUtc, IsSuccess, HasCompleted, Comment, Files, IsManualEntry) + values (@TransactionGUID, @ConfigGUID, @UserID, getutcdate(), getutcdate(), 1, 1, @Comment, 'T-SQL', 1) +end +GO + + +--------------------------------------------- + +-- dbo.procInvalidateModelWorkbookCache +CREATE PROC procInvalidateModelWorkbookCache + @entityguid uniqueidentifier, + @istemplate bit, + @isdebugonly bit = 0, + @source nvarchar(100) = 'Unknown' +AS + declare @whereClause nvarchar(max) + + IF @istemplate = 1 BEGIN + --clear models for this template, if caching enabled + if ((select count(*) from [dbo].[EMFModelTemplate] (readuncommitted) where ModelTemplateGUID = @entityguid and IsModelWorkbookCachable = 1) > 0) begin + if ((select count(*) from [dbo].[XPlan] (readuncommitted) where ModelTemplateGUID = @entityguid and IsModelWorkbookCached = 1) > 0) begin + --clear file cache + update XPlan Set IsModelWorkbookCached = 0, LastModelCacheInvalidateReason = @source, LastModelCacheInvalidateDate = getdate() WHERE ModelTemplateGUID = @entityguid and IsModelWorkbookCached = 1 + + --clear memory cache + if ((select count(*) from [dbo].[EMFModelTemplate] (readuncommitted) where ModelTemplateGUID = @entityguid and IsMemoryCachable = 1) > 0) begin + set @whereClause = ' in(select xp1.PlanGUID from XPlan xp1 (readuncommitted) where xp1.ModelTemplateGUID = ''' + cast(@entityguid as nvarchar(36)) + ''')' + exec procTEEvictModelCache @whereClause + end + end + end + END ELSE BEGIN + --clear just this model, if caching enabled + if ((select count(*) from [dbo].[EMFModelTemplate] mt (readuncommitted) inner join [dbo].[XPlan] p (readuncommitted) on p.ModelTemplateGUID = mt.ModelTemplateGUID and p.PlanGUID = @entityguid where mt.IsModelWorkbookCachable = 1) > 0) begin + if ((select count(*) from [dbo].[XPlan] (readuncommitted) where IsModelWorkbookCached = 1 and (PlanGUID = @entityguid or PlanGUID in(select ModelGUID from [dbo].[viewModelDependencies] where ParentModelGUID = @entityguid))) > 0) begin + --clear file cache + update [dbo].[XPlan] set IsModelWorkbookCached = 0, LastModelCacheInvalidateReason = @source, LastModelCacheInvalidateDate = getdate() where IsModelWorkbookCached = 1 and (PlanGUID = @entityguid or PlanGUID in(select ModelGUID from [dbo].[viewModelDependencies] where ParentModelGUID = @entityguid)) + + --clear memory cache + if ((select count(*) from [dbo].[EMFModelTemplate] mt (readuncommitted) inner join [dbo].[XPlan] p (readuncommitted) on p.ModelTemplateGUID = mt.ModelTemplateGUID and p.PlanGUID = @entityguid where mt.IsMemoryCachable = 1) > 0) begin + set @whereClause = ' in(select xp1.PlanGUID from XPlan xp1 (readuncommitted) where xp1.PlanGUID = ''' + cast(@entityguid as nvarchar(36)) + ''' union all select dep2.ModelGUID from [dbo].[viewModelDependencies] dep2 where dep2.ParentModelGUID = ''' + cast(@entityguid as nvarchar(36)) + ''')' + exec procTEEvictModelCache @whereClause, @isdebugonly + end + end + end + END +GO + + +--------------------------------------------- + +-- dbo.procInvalidateModelWorkbookCacheByDimension +CREATE proc [dbo].[procInvalidateModelWorkbookCacheByDimension] + @dimensionGUID uniqueidentifier, + @whereClause nvarchar(max) = '', + @isDebug bit = 0, + @source nvarchar(100) = 'Unknown' +as + set nocount on + + --cancel if this dimension is not a fillin dimension in modeling + if ((select count(*) from [dbo].[MEScorePlaceholderLabel] phl (readuncommitted) where phl.FillinDimensionGUID = @dimensionGUID) = 0) begin + return + end + + declare @dimSource nvarchar(100) + declare @fullWhereClause nvarchar(max) + declare @mcSQL nvarchar(max) + + select @dimSource = SQLSchemaName + '.' + SQLObjectName from [dbo].[ScoreDimension] (readuncommitted) where DimensionGUID = @dimensionGUID + + if((select count(*) from [dbo].[EMFModelTemplate] (readuncommitted) where IsModelWorkbookCachable = 1) > 0) begin + set @fullWhereClause = ' in( + select + FI.ModelGUID + from + ScoreFillin FI (readuncommitted) + inner join ' + @dimSource + ' C (readuncommitted) on C.MemberGUID = FI.FillinMemberGUID ' + if (@whereClause != '') begin + set @fullWhereClause = @fullWhereClause + ' where ' + @whereClause + end + set @fullWhereClause = @fullWhereClause + ')' + + set @mcSQL = ' + declare @cnt int + select @cnt = count(*) from XPlan P (readuncommitted) inner join EMFModelTemplate MT (readuncommitted) on MT.ModelTemplateGUID = P.ModelTemplateGUID where MT.IsModelWorkbookCachable = 1 and P.PlanGUID ' + @fullWhereClause + ' + if(@cnt > 0) begin + --clear cache + update XPlan set IsModelWorkbookCached = 0, LastModelCacheInvalidateReason = ''' + @source + ''', LastModelCacheInvalidateDate = getdate() where IsModelWorkbookCached = 1 and PlanGUID ' + @fullWhereClause + ' + + select @cnt = count(*) from XPlan P (readuncommitted) inner join EMFModelTemplate MT (readuncommitted) on MT.ModelTemplateGUID = P.ModelTemplateGUID where MT.IsMemoryCachable = 1 and P.PlanGUID ' + @fullWhereClause + ' + if(@cnt > 0) begin + exec procTEEvictModelCache ''' + replace(@fullWhereClause, '''', '''''') + ''' + end + end' + + if(@isDebug = 0) begin + exec(@mcSQL) + end else begin + print @mcSQL + end + end +GO + + +--------------------------------------------- + +-- dbo.procInvalidateModelWorkbookCacheByDimensionEMF +CREATE proc [dbo].[procInvalidateModelWorkbookCacheByDimensionEMF] + @dimensionGUID uniqueidentifier, + @whereClause nvarchar(max) = '', + @isDebug bit = 0, + @source nvarchar(100) = 'Unknown' +as + declare @mcSQL nvarchar(max) + declare @fullWhereClause nvarchar(max) + + if((select count(*) from [dbo].[EMFModelTemplate] where IsModelWorkbookCachable = 1) > 0) begin + set @fullWhereClause = ' in( + select + FI.ModelGUID + from + EMFFillin FI (readuncommitted) + inner join SecureListMember C (readuncommitted) on C.ListGUID = ''' + cast(@dimensionGUID as nvarchar(36)) + ''' and C.ListMemberGUID = FI.FilledInMemberGUID ' + if (@whereClause != '') begin + set @fullWhereClause = @fullWhereClause + ' where ' + @whereClause + end + set @fullWhereClause = @fullWhereClause + ')' + + set @mcSQL = 'update XPlan set IsModelWorkbookCached = 0, LastModelCacheInvalidateReason = ''' + @source + ''', LastModelCacheInvalidateDate = getdate() where IsModelWorkbookCached = 1 and PlanGUID ' + @fullWhereClause + + if(@isDebug = 0) begin + exec(@mcSQL) + end else begin + print @mcSQL + end + + --exec procTEEvictModelCache @fullWhereClause, @isDebug + end +GO + + +--------------------------------------------- + +-- dbo.procInvalidateModelWorkbookCacheByPlanType +CREATE PROC procInvalidateModelWorkbookCacheByPlanType + @planTypeGUID uniqueidentifier, + @source nvarchar(100) = 'Unknown' +AS + --see if this plan type has templates with caching enabled + if ((select count(*) from [dbo].[EMFModelTemplate] mt (readuncommitted) inner join [dbo].[PlanTypeModelTemplateLink] ptl (readuncommitted) on ptl.ModelTemplateGUID = mt.ModelTemplateGUID where ptl.PlanTypeGUID = @planTypeGUID and mt.IsModelWorkbookCachable = 1) > 0) begin + if ((select count(*) from [dbo].[XPlan] (readuncommitted) where PlanTypeGUID = @planTypeGUID and IsModelWorkbookCached = 1) > 0) begin + --clear file cache + update [dbo].[XPlan] set IsModelWorkbookCached = 0, LastModelCacheInvalidateReason = @source, LastModelCacheInvalidateDate = getdate() where PlanTypeGUID = @planTypeGUID and IsModelWorkbookCached = 1 + + --clear memory cache + if ((select count(*) from [dbo].[EMFModelTemplate] mt (readuncommitted) inner join [dbo].[PlanTypeModelTemplateLink] ptl (readuncommitted) on ptl.ModelTemplateGUID = mt.ModelTemplateGUID where ptl.PlanTypeGUID = @planTypeGUID and mt.IsMemoryCachable = 1) > 0) begin + declare @whereClause nvarchar(max) + set @whereClause = ' in(select x1.PlanGUID from XPlan x1 (readuncommitted) where x1.PlanTypeGUID = ''' + cast(@planTypeGUID as nvarchar(36)) + ''')' + exec procTEEvictModelCache @whereClause + end + end + end +GO + + +--------------------------------------------- + +-- dbo.procInvalidateModelWorkbookCacheByTemplate +CREATE PROC dbo.procInvalidateModelWorkbookCacheByTemplate + @modelTemplateGUID uniqueidentifier, + @source nvarchar(100) = 'Unknown', + @idlePlansOnly bit = 0 +AS + --see if this plan type has templates with caching enabled + if ((select count(*) from [dbo].[EMFModelTemplate] mt (readuncommitted) where mt.ModelTemplateGUID = @modelTemplateGUID and mt.IsModelWorkbookCachable = 1) > 0) begin + if ((select count(*) from [dbo].[XPlan] (readuncommitted) where ModelTemplateGUID = @modelTemplateGUID and IsModelWorkbookCached = 1) > 0) begin + if (@idlePlansOnly = 0) begin + --clear file cache + update [dbo].[XPlan] set IsModelWorkbookCached = 0, LastModelCacheInvalidateReason = @source, LastModelCacheInvalidateDate = getdate() where ModelTemplateGUID = @modelTemplateGUID and IsModelWorkbookCached = 1 + + --clear memory cache + if ((select count(*) from [dbo].[EMFModelTemplate] mt (readuncommitted) where mt.ModelTemplateGUID = @modelTemplateGUID and mt.IsMemoryCachable = 1) > 0) begin + declare @whereClause nvarchar(max) + set @whereClause = ' in(select x1.PlanGUID from XPlan x1 (readuncommitted) where x1.ModelTemplateGUID = ''' + cast(@modelTemplateGUID as nvarchar(36)) + ''')' + exec procTEEvictModelCache @whereClause + end + end else begin + --clear file cache for plans not in memory or refresh queue (this option is used to resolve a specific error where plans have invalid file cache) + update p set p.IsModelWorkbookCached = 0, p.LastModelCacheInvalidateReason = @source, p.LastModelCacheInvalidateDate = getdate() + from + XPlan p + inner join emfmodeltemplate t on p.modeltemplateguid = t.modeltemplateguid + where + t.modeltemplateguid = @modelTemplateGUID + and t.ismodelworkbookcachable = 1 + and t.ismemorycachable = 1 + and p.ismodelworkbookcached = 1 + and not exists(select 1 from modelcachelookup lu where lu.ModelGuid = p.PlanGUID) + and not exists(select 1 from MEModelRefreshQueue q where q.modelguid = p.planguid) + end + end + end +GO + + +--------------------------------------------- + +-- dbo.procInvalidateModelWorkbookCacheByWhereClause +CREATE PROC procInvalidateModelWorkbookCacheByWhereClause + @xplanWhereClause nvarchar(max), + @isDebugOnly bit = 0, + @source nvarchar(100) = 'Unknown' +AS + declare @sql nvarchar(max) + + declare @where nvarchar(max) + if (@xplanWhereClause != '') begin + set @where = @xplanWhereClause + end else begin + set @where = '(1 = 1)' + end + + declare @evictWhereClause nvarchar(max) + set @evictWhereClause = ' in(select x1.PlanGUID from XPlan x1 (readuncommitted) inner join EMFModelTemplate mt1 (readuncommitted) on mt1.ModelTemplateGUID = x1.ModelTemplateGUID where mt1.IsModelWorkbookCachable = 1' + if (@where != '(1 = 1)') begin + set @evictWhereClause = @evictWhereClause + ' and x1.' + ltrim(@where) + end + set @evictWhereClause = @evictWhereClause + ')' + + if ((select count(*) from [dbo].[EMFModelTemplate] (readuncommitted) where IsModelWorkbookCachable = 1) > 0) begin + set @sql = ' + if((select count(*) from XPlan p (readuncommitted) inner join EMFModelTemplate mt (readuncommitted) on p.ModelTemplateGUID = mt.ModelTemplateGUID where p.IsModelWorkbookCached = 1 and mt.IsModelWorkbookCachable = 1 and mt.IsMemoryCachable = 0 and ' + @where + ') > 0) begin + --clear file cache only + update [dbo].[XPlan] set IsModelWorkbookCached = 0, LastModelCacheInvalidateReason = ''' + @source + ''', LastModelCacheInvalidateDate = getdate() where IsModelWorkbookCached = 1 and ' + @where + ' + end + if((select count(*) from XPlan p (readuncommitted) inner join EMFModelTemplate mt (readuncommitted) on p.ModelTemplateGUID = mt.ModelTemplateGUID where p.IsModelWorkbookCached = 1 and mt.IsModelWorkbookCachable = 1 and mt.IsMemoryCachable = 1 and ' + @where + ') > 0) begin + --clear file cache + update [dbo].[XPlan] set IsModelWorkbookCached = 0, LastModelCacheInvalidateReason = ''' + @source + ''', LastModelCacheInvalidateDate = getdate() where IsModelWorkbookCached = 1 and ' + @where + ' + + --clear memory cache + exec procTEEvictModelCache ''' + replace(@evictWhereClause, '''', '''''') + ''' + end + ' + + if (@isDebugOnly = 0) begin + exec(@sql) + end else begin + print @sql + end + end +GO + + +--------------------------------------------- + +-- dbo.procIsModelDriverExceptionsTest +create proc [dbo].[procIsModelDriverExceptionsTest] +with recompile +as + exec dbo.procSysDropTempTable '##modelattrs' + + select * + into ##modelattrs + from viewScoreAttribute + where + (DimensionName = 'Account' and FriendlyName = 'Name') + or + (DimensionName = 'Account' and FriendlyName = 'OB Dollars Rollup Name') + or + (DimensionName = 'Account' and FriendlyName = 'OB Variability') + or + (DimensionName = 'Account' and FriendlyName = 'OB Staffing') + or + (DimensionName = 'Job Code' and FriendlyName = 'Name') + or + (DimensionName = 'Job Code' and FriendlyName = 'Variability') + or + (DimensionName = 'Pay Code Group' and FriendlyName = 'Name') + or + (DimensionName = 'Fiscal Year' and FriendlyName = 'Name') + or + (DimensionName = 'Charge Code' and FriendlyName = 'Name') + or + (DimensionName = 'Charge Code' and FriendlyName = 'Category') + or + (DimensionName = 'Charge Code' and FriendlyName = 'IsStatDriver') + or + (DimensionName = 'Charge Code' and FriendlyName = 'RVU Weight') + or + (DimensionName = 'Charge Code' and FriendlyName = 'Charge Increase') + or + (DimensionName = 'Employee' and FriendlyName = 'Name') + or + (DimensionName = 'Employee' and FriendlyName = 'Job Code') + or + (DimensionName = 'Employee' and FriendlyName = 'Next Review') + or + (DimensionName = 'Employee' and FriendlyName = 'Wage Rate') + or + (DimensionName = 'Account' and FriendlyName = 'OB Dollars Financial Reporting Name') + or + (DimensionName = 'Account' and FriendlyName = 'OB Dollars Financial Reporting Line Name') + or + (DimensionName = 'Account' and FriendlyName = 'OB Units Financial Reporting Name') + or + (DimensionName = 'Account' and FriendlyName = 'OB Units Financial Reporting Line Name') + or + (DimensionName = 'OB Financial Reporting' and FriendlyName = 'Name') + or + (DimensionName = 'OB Financial Reporting' and FriendlyName = 'Line Name') + or + (DimensionName = 'Account' and FriendlyName = 'Patient Type Rollup Name') + or + (DimensionName = 'Account' and FriendlyName = 'Patient Class') + or + (DimensionName = 'Pay Code Group' and FriendlyName = 'Wage Rate Multiplier') + or + (DimensionName = 'Provider' and FriendlyName = 'Base Pay') + or + (DimensionName = 'Provider' and FriendlyName = 'Name') + or + (DimensionName = 'Provider' and FriendlyName = 'Specialty') + or + (DimensionName = 'Provider' and FriendlyName = 'IsEmployee') + or + (DimensionName = 'OB Forecast Detail' and FriendlyName = 'Name') + or + (DimensionName = 'Provider' and FriendlyName = 'OB Tier 1 Threshold') + or + (DimensionName = 'Provider' and FriendlyName = 'OB Tier 2 Threshold') + or + (DimensionName = 'Provider' and FriendlyName = 'OB Tier 3 Threshold') + or + (DimensionName = 'Provider' and FriendlyName = 'OB Tier 4 Threshold') + or + (DimensionName = 'Provider' and FriendlyName = 'OB Tier 5 Threshold') + or + (DimensionName = 'Provider' and FriendlyName = 'OB Tier 6 Threshold') + or + (DimensionName = 'Provider' and FriendlyName = 'OB Tier 1 Rate') + or + (DimensionName = 'Provider' and FriendlyName = 'OB Tier 2 Rate') + or + (DimensionName = 'Provider' and FriendlyName = 'OB Tier 3 Rate') + or + (DimensionName = 'Provider' and FriendlyName = 'OB Tier 4 Rate') + or + (DimensionName = 'Provider' and FriendlyName = 'OB Tier 5 Rate') + or + (DimensionName = 'Provider' and FriendlyName = 'OB Tier 6 Rate') + or + (DimensionName = 'Provider' and FriendlyName = 'OB Volume Target 1') + or + (DimensionName = 'Provider' and FriendlyName = 'OB Volume Target 2') + or + (DimensionName = 'OB Financial Reporting' and FriendlyName = 'Section') + or + (DimensionName = 'OB Forecast Detail' and FriendlyName = 'Account') + or + (DimensionName = 'OB Financial Reporting' and FriendlyName = 'Is Expense') + or + (DimensionName = 'OB Forecast Detail' and FriendlyName = 'Secondary Account') + or + (DimensionName = 'Provider' and FriendlyName = 'IsPhysician') + or + (DimensionName = 'Account' and FriendlyName = 'Name') + or + (DimensionName = 'OB Departmental Budget' and FriendlyName = 'Is Variable') + or + (DimensionName = 'Pay Code Group' and FriendlyName = 'IsExcludedfromBenefits') + or + (DimensionName = 'OB Financial Reporting' and FriendlyName = 'Projection Method') + or + (DimensionName = 'OB Financial Reporting' and FriendlyName = 'Spread Method') + or + (DimensionName = 'Account' and FriendlyName = 'OB Is Expense') + or + (DimensionName = 'Account' and FriendlyName = 'Inversion') + or + (DimensionName = 'Account' and FriendlyName = 'AccountID') + or + (DimensionName = 'OB Departmental Budget' and FriendlyName = 'DepartmentalBudgetID') + or + (DimensionName = 'Work Week' and FriendlyName = 'Name') + or + (DimensionName = 'Work Week' and FriendlyName = 'WorkWeekID') + or + (DimensionName = 'Provider' and FriendlyName = 'WorkWeekOverrideID') + or + (DimensionName = 'Job Code' and FriendlyName = 'WorkWeekOverrideID') + or + (DimensionName = 'Employee' and FriendlyName = 'WorkWeekOverrideID') + or + (DimensionName = 'OB Departmental Budget' and FriendlyName = 'Entity Default Work WeekID') + or + (DimensionName = 'Provider' and FriendlyName = 'NPI') + or + (DimensionName = 'OB Departmental Budget' and FriendlyName = 'Hours per UOS Projection') + or + (DimensionName = 'OB Departmental Budget' and FriendlyName = 'Hours per UOS Budget') + or + (DimensionName = 'Employee' and FriendlyName = 'Employee Cohort Contract Date') + or + (DimensionName = 'Employee' and FriendlyName = 'Employee Cohort Merit Type') + or + (DimensionName = 'OB Forecast Detail' and FriendlyName = 'Volume Target') + or + (DimensionName = 'Fiscal Year' and FriendlyName = 'Name') + or + (DimensionName = 'OB Global Statistics' and FriendlyName = 'Account') + or + (DimensionName = 'OB Global Statistics' and FriendlyName = 'Department Code') + or + (DimensionName = 'OB Global Statistics' and FriendlyName = 'Name') + or + (DimensionName = 'OB Global Statistics' and FriendlyName = 'LOSLink') + or + (DimensionName = 'OB Global Statistics' and FriendlyName = 'OB Units Financial Reporting Name') + or + (DimensionName = 'OB Global Statistics' and FriendlyName = 'OB Units Financial Reporting Line Name') + or + (DimensionName = 'OB Global Statistics' and FriendlyName = 'Patient Class') + or + (DimensionName = 'OB Global Statistics' and FriendlyName = 'OB Payor Group') + or + (DimensionName = 'Account' and FriendlyName = 'Name') + or + (DimensionName = 'Fiscal Year' and FriendlyName = 'Name') + or + (DimensionName = 'OB Global Statistics' and FriendlyName = 'Name') + or + (DimensionName = 'OB Global Statistics' and FriendlyName = 'OB Units Financial Reporting Name') + or + (DimensionName = 'OB Global Statistics' and FriendlyName = 'OB Units Financial Reporting Line Name') + or + (DimensionName = 'Account' and FriendlyName = 'Name') + or + (DimensionName = 'OB Global Statistics' and FriendlyName = 'Account') + or + (DimensionName = 'OB Global Statistics' and FriendlyName = 'Department Code') + or + (DimensionName = 'OB Global Statistics' and FriendlyName = 'LOSLink') + or + (DimensionName = 'OB Global Statistics' and FriendlyName = 'Patient Class') + or + (DimensionName = 'OB Global Statistics' and FriendlyName = 'OB Payor Group') + or + (DimensionName = 'Account' and FriendlyName = 'Name') + or + (DimensionName = 'Account' and FriendlyName = 'Patient Class') + or + (DimensionName = 'Account' and FriendlyName = 'OB Payor Group') + or + (DimensionName = 'Account' and FriendlyName = 'OB Dollars Rollup Name') + or + (DimensionName = 'Account' and FriendlyName = 'OB Staffing') + or + (DimensionName = 'Account' and FriendlyName = 'Variability') + or + (DimensionName = 'Charge Code' and FriendlyName = 'Name') + or + (DimensionName = 'Charge Code' and FriendlyName = 'Category') + or + (DimensionName = 'Charge Code' and FriendlyName = 'Charge Increase') + or + (DimensionName = 'Charge Code' and FriendlyName = 'IsStatDriver') + or + (DimensionName = 'Charge Code' and FriendlyName = 'RVU Weight') + or + (DimensionName = 'Employee' and FriendlyName = 'Name') + or + (DimensionName = 'Employee' and FriendlyName = 'Next Review') + or + (DimensionName = 'Employee' and FriendlyName = 'Job Code') + or + (DimensionName = 'Employee' and FriendlyName = 'Wage Rate') + or + (DimensionName = 'Fiscal Year' and FriendlyName = 'Name') + or + (DimensionName = 'OB Forecast Detail' and FriendlyName = 'Name') + or + (DimensionName = 'OB Forecast Detail' and FriendlyName = 'Name') + or + (DimensionName = 'Job Code' and FriendlyName = 'Name') + or + (DimensionName = 'Job Code' and FriendlyName = 'Variability') + or + (DimensionName = 'Payor Group' and FriendlyName = 'Name') + or + (DimensionName = 'OB Provider' and FriendlyName = 'Name') + or + (DimensionName = 'OB Provider' and FriendlyName = 'RVU Budget Target') + or + (DimensionName = 'OB Provider' and FriendlyName = 'Provider Code') + or + (DimensionName = 'OB Provider' and FriendlyName = 'RVU Conversion Factor') + or + (DimensionName = 'OB Provider' and FriendlyName = 'RVU Current Target') + or + (DimensionName = 'OB Provider' and FriendlyName = 'isEmployee') + or + (DimensionName = 'OB Provider' and FriendlyName = 'Annual RVU Median') + or + (DimensionName = 'OB Provider' and FriendlyName = 'Provider Speciality') + or + (DimensionName = 'Account' and FriendlyName = 'Name') + or + (DimensionName = 'Account' and FriendlyName = 'OB Dollars Rollup Name') + or + (DimensionName = 'Charge Code' and FriendlyName = 'Name') + or + (DimensionName = 'Employee' and FriendlyName = 'Name') + or + (DimensionName = 'Fiscal Year' and FriendlyName = 'Name') + or + (DimensionName = 'OB Forecast Detail' and FriendlyName = 'Name') + or + (DimensionName = 'OB Forecast Detail' and FriendlyName = 'Name') + or + (DimensionName = 'Job Code' and FriendlyName = 'Name') + or + (DimensionName = 'Payor Group' and FriendlyName = 'Name') + or + (DimensionName = 'OB Provider' and FriendlyName = 'Name') + or + (DimensionName = 'Account' and FriendlyName = 'Patient Class') + or + (DimensionName = 'Account' and FriendlyName = 'OB Payor Group') + or + (DimensionName = 'Account' and FriendlyName = 'OB Staffing') + or + (DimensionName = 'Account' and FriendlyName = 'Variability') + or + (DimensionName = 'Charge Code' and FriendlyName = 'Category') + or + (DimensionName = 'Charge Code' and FriendlyName = 'Charge Increase') + or + (DimensionName = 'Charge Code' and FriendlyName = 'IsStatDriver') + or + (DimensionName = 'Charge Code' and FriendlyName = 'RVU Weight') + or + (DimensionName = 'Employee' and FriendlyName = 'Next Review') + or + (DimensionName = 'Employee' and FriendlyName = 'Job Code') + or + (DimensionName = 'Employee' and FriendlyName = 'Wage Rate') + or + (DimensionName = 'Job Code' and FriendlyName = 'Variability') + or + (DimensionName = 'OB Provider' and FriendlyName = 'RVU Budget Target') + or + (DimensionName = 'OB Provider' and FriendlyName = 'Provider Code') + or + (DimensionName = 'OB Provider' and FriendlyName = 'RVU Conversion Factor') + or + (DimensionName = 'OB Provider' and FriendlyName = 'RVU Current Target') + or + (DimensionName = 'OB Provider' and FriendlyName = 'isEmployee') + or + (DimensionName = 'OB Provider' and FriendlyName = 'Annual RVU Median') + or + (DimensionName = 'OB Provider' and FriendlyName = 'Provider Speciality') + or + (DimensionName = 'Fiscal Year' and FriendlyName = 'Name') + or + (DimensionName = 'Modeling Service Line' and FriendlyName = 'Name') + or + (DimensionName = 'Modeling Service Line' and FriendlyName = 'Age Cohort') + or + (DimensionName = 'Modeling Service Line' and FriendlyName = 'Medical Surgical') + or + (DimensionName = 'Modeling Service Line' and FriendlyName = 'Service Line') + or + (DimensionName = 'Modeling Service Line' and FriendlyName = 'Service Line Rollup') + or + (DimensionName = 'OB Forecast Detail' and FriendlyName = 'Name') + or + (DimensionName = 'Service Line Rollup' and FriendlyName = 'Name') + or + (DimensionName = 'Fiscal Year' and FriendlyName = 'Name') + or + (DimensionName = 'Modeling Service Line' and FriendlyName = 'Name') + or + (DimensionName = 'OB Forecast Detail' and FriendlyName = 'Name') + or + (DimensionName = 'Service Line Rollup' and FriendlyName = 'Name') + or + (DimensionName = 'Modeling Service Line' and FriendlyName = 'Age Cohort') + or + (DimensionName = 'Modeling Service Line' and FriendlyName = 'Medical Surgical') + or + (DimensionName = 'Modeling Service Line' and FriendlyName = 'Service Line') + or + (DimensionName = 'Modeling Service Line' and FriendlyName = 'Service Line Rollup') + + exec dbo.procSysDropTempTable '#failures' + + create table #failures ([Message] nvarchar(max), [DimensionName] [nvarchar](128), [FriendlyName] [nvarchar](200)) + + --attributes with IsModelDriver = 0 that should have = 1 + insert into #failures + select 'attribute with IsModelDriver = 0 that should have = 1' as Message, DimensionName, FriendlyName + from viewScoreAttribute where IsModelDriver = 0 and AttributeGUID in(select AttributeGUID from ##modelattrs) + + --attributes with IsModelDriver = 1 that should have = 0 + insert into #failures + select 'attribute with IsModelDriver = 1 that should have = 0', DimensionName, FriendlyName + from viewScoreAttribute where IsModelDriver = 1 and FriendlyName != 'Name' and AttributeGUID not in(select AttributeGUID from ##modelattrs) + + select * from #failures + + drop table #failures + drop table ##modelattrs +GO + + +--------------------------------------------- + +-- dbo.procLastModifiedSchema +CREATE proc procLastModifiedSchema as +select s.name,o.name, modify_date, +case when type_desc = 'USER_TABLE' then 'Table' +when type_desc = 'SQL_STORED_PROCEDURE' then 'Stored Procedure' +when type_desc in ('SQL_INLINE_TABLE_VALUED_FUNCTION', 'SQL_SCALAR_FUNCTION', 'SQL_TABLE_VALUED_FUNCTION') then 'Function' +end as type_desc +from sys.objects o + inner join sys.schemas s on o.schema_id = s.schema_id +where type in ('U', 'P', 'FN', 'IF', 'TF') +and is_ms_shipped = 0 +order by modify_date desc +GO + + +--------------------------------------------- + +-- dbo.procLinkedTransferDataBetweenTables +CREATE PROCEDURE [dbo].[procLinkedTransferDataBetweenTables] +( + + @SourceTableExpression varchar(max), + @TargetTableExpression varchar(max), + @aWhereClause varchar(max) = '', + @aSelectClause varchar(max) = '*' +) +AS + +declare @WhereClause varchar(max); +set @WhereClause = ''; +IF (@aWhereClause <> '') +BEGIN + SET @WhereClause = ' WHERE ' + @aWhereClause + ' '; +END + +declare @sql varchar(max); +set @sql = ' + + declare @TargetTableExpression varchar(max); + set @TargetTableExpression = ''' + @TargetTableExpression + '''; + + IF ([dbo].[TableExistsByTableExpression] (@TargetTableExpression) = 1) + BEGIN + SET IDENTITY_INSERT ' + @TargetTableExpression + ' ON ; + INSERT INTO ' + @TargetTableExpression + ' SELECT ' + @aSelectClause + ' FROM ' + @SourceTableExpression + ' ' + @WhereClause + '; + SET IDENTITY_INSERT ' + @TargetTableExpression + ' OFF ; + END + ELSE + BEGIN + SELECT ' + @aSelectClause + ' INTO ' + @TargetTableExpression + ' FROM ' + @SourceTableExpression + ' ' + @WhereClause + '; + END + +'; +print @sql; +exec (@sql); +GO + + +--------------------------------------------- + +-- dbo.procLogHistory +create proc [dbo].[procLogHistory] + @username nvarchar(128), + @desc nvarchar(4000), + @cnt int, + @higuid uniqueidentifier +as + + +INSERT INTO [dbo].[HistoryItem] + ( + OBJECTGUID + ,[HISTORYITEMGUID] + ,[CATEGORY] + ,[DESCRIPTION] + ,ITEMCOUNT + --,[ISCOMPARABLE] + --,[ISRECOVERABLE] + --,[ISVIEWABLE] + ,[METAXML] + ,[MODIFIERUSERNAME] + ) + VALUES + ( + dbo.ZeroGUID() + ,@higuid + ,'Script' --as Category + ,@desc --as Description + ,@cnt + --,0 + --,0 + --,0 + ,'' --as METAXML + ,@username + --, + ) +GO + + +--------------------------------------------- + +-- dbo.procLogLastSQL +CREATE proc [dbo].[procLogLastSQL] + @username nvarchar(128), + @desc nvarchar(4000), + @higuid uniqueidentifier + --@count int out +as + +declare @count int +set @count = @@rowcount + +INSERT INTO [dbo].[HistoryItem] + ([HISTORYITEMGUID] + ,[CATEGORY] + ,[DESCRIPTION] + + ,[METAXML] + ,[MODIFIERUSERNAME] + ,ITEMCOUNT + ) + VALUES + (@higuid + ,'Script' --as Category + ,@desc --as Description + ,'' --as METAXML + ,@username + ,@count + --, + ) +GO + + +--------------------------------------------- + +-- dbo.procLogLastSQLImport +CREATE proc [dbo].[procLogLastSQLImport] + @username nvarchar(128), + @desc nvarchar(4000), + @higuid uniqueidentifier , + @tablename nvarchar(64), + @category nvarchar(64) = 'Import' +as + +declare @count int +set @count = @@rowcount + + +INSERT INTO [dbo].[HistoryItem] + ([HISTORYITEMGUID] + ,[CATEGORY] + ,[DESCRIPTION] + ,[METAXML] + ,[MODIFIERUSERNAME] + ,ITEMCOUNT + ) + VALUES + (@higuid + ,@category --as Category + ,@desc --as Description + ,@tablename --as METAXML + ,@username + ,@count + --, + ) +GO + + +--------------------------------------------- + +-- dbo.procLogLastSQLImportWithComments +CREATE proc [dbo].[procLogLastSQLImportWithComments] + @username nvarchar(128), + @desc nvarchar(4000), + @higuid uniqueidentifier , + @tablename nvarchar(64), + @usercomments nvarchar(256), + @elapsedms int = 0, + @userguid uniqueidentifier = '00000000-0000-0000-0000-000000000000', + @category nvarchar(64) = 'Import' +as + +declare @count int +set @count = @@rowcount + + +INSERT INTO [dbo].[HistoryItem] + ([HISTORYITEMGUID] + ,[CATEGORY] + ,[DESCRIPTION] + ,[METAXML] + ,[MODIFIERUSERNAME] + ,[USERCOMMENTS] + ,ITEMCOUNT + ,ELAPSEDMS + ,MODIFIERUSERGUID + ) + VALUES + (@higuid + ,@category --as Category + ,@desc --as Description + ,@tablename --as METAXML + ,@username + ,@usercomments + ,@count + ,@elapsedms + ,@userguid + --, + ) +GO + + +--------------------------------------------- + +-- dbo.procLogObjectHistory +CREATE proc [dbo].[procLogObjectHistory] + @entityguid uniqueidentifier, + @desc nvarchar(4000), + @cnt int, + @higuid uniqueidentifier OUTPUT +as + +declare @username nvarchar(64) +set @username = left(system_user,64) + +set @higuid = newid() + +INSERT INTO [dbo].[HistoryItem] + ( + OBJECTGUID + ,[HISTORYITEMGUID] + ,[CATEGORY] + ,[DESCRIPTION] + ,ITEMCOUNT + --,[ISCOMPARABLE] + --,[ISRECOVERABLE] + --,[ISVIEWABLE] + ,[METAXML] + ,[MODIFIERUSERNAME] + ) + VALUES + ( + @entityguid + ,@higuid + ,'Script' --as Category + ,@desc --as Description + ,@cnt + --,0 + --,0 + --,0 + ,'' --as METAXML + ,@username + --, + ) +GO + + +--------------------------------------------- + +-- dbo.procLogObjectHistoryItemGUID +create proc [dbo].[procLogObjectHistoryItemGUID] + @entityguid uniqueidentifier, + @desc nvarchar(4000), + @cnt int, + @higuid uniqueidentifier +as + +declare @username nvarchar(64) +set @username = left(system_user,64) + +if @higuid is null begin + print 'Invalid higuid' + return +end + +INSERT INTO [dbo].[HistoryItem] + ( + OBJECTGUID + ,[HISTORYITEMGUID] + ,[CATEGORY] + ,[DESCRIPTION] + ,ITEMCOUNT + --,[ISCOMPARABLE] + --,[ISRECOVERABLE] + --,[ISVIEWABLE] + ,[METAXML] + ,[MODIFIERUSERNAME] + ) + VALUES + ( + @entityguid + ,@higuid + ,'Script' --as Category + ,@desc --as Description + ,@cnt + --,0 + --,0 + --,0 + ,'' --as METAXML + ,@username + --, + ) +GO + + +--------------------------------------------- + +-- dbo.procLogObjectHistoryItemGUIDObjectType +create proc [dbo].[procLogObjectHistoryItemGUIDObjectType] + @objecttype nvarchar(4000), + @entityguid uniqueidentifier, + @desc nvarchar(4000), + @cnt int, + @higuid uniqueidentifier + +as + +declare @username nvarchar(64) +set @username = left(system_user,64) + +if @higuid is null begin + print 'Invalid higuid' + return +end + +INSERT INTO [dbo].[HistoryItem] + ( + OBJECTGUID + ,[HISTORYITEMGUID] + ,[CATEGORY] + ,[DESCRIPTION] + ,ITEMCOUNT + --,[ISCOMPARABLE] + --,[ISRECOVERABLE] + --,[ISVIEWABLE] + ,[METAXML] + ,[MODIFIERUSERNAME] + ,OBJECTTYPE + ) + VALUES + ( + @entityguid + ,@higuid + ,'Script' --as Category + ,@desc --as Description + ,@cnt + --,0 + --,0 + --,0 + ,'' --as METAXML + ,@username + ,@objecttype + --, + ) +GO + + +--------------------------------------------- + +-- dbo.procLogScript +CREATE proc [dbo].[procLogScript] + @desc nvarchar(4000), + @higuid uniqueidentifier OUTPUT +as + set nocount on + + declare @username nvarchar(64) + set @username = left(system_user,64) + + if (@higuid is null or @higuid = dbo.ZeroGUID() or exists(select 1 from dbo.HistoryItem where HistoryItemGUID = @higuid)) begin + set @higuid = newid() + end + + INSERT INTO [dbo].[HistoryItem] + ([HISTORYITEMGUID] + ,[CATEGORY] + ,[DESCRIPTION] + ,[METAXML] + ,[MODIFIERUSERNAME] + ) + VALUES + (@higuid + ,'Script' --as Category + ,@desc --as Description + ,'' --as METAXML + ,@username + --, + ) +GO + + +--------------------------------------------- + +-- dbo.procLogin +CREATE procedure [dbo].[procLogin] + @username nvarchar(64), + @password nvarchar(64), + @orgpin nvarchar(6) = '', + @ipaddress varchar(15) = 'none', + @tokentype int = 0 +AS +SET NOCOUNT ON + +declare @userguid uniqueidentifier +declare @cnt int +declare @IsSysAdmin bit +SELECT + @userguid = UP.USERGUID, + @cnt = count(*), + @IsSysAdmin = ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0) +FROM + UserProfile UP + left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = 'GEN - User Administrator') +WHERE + UP.USERNAME = @USERNAME + AND (convert(varbinary, UP.HASHEDPASSWORD) = convert(varbinary, @PASSWORD)) + AND UP.IsDisabled = 0 +group by UP.userguid, IL.GroupingGUID + + +IF @cnt > 0 BEGIN + declare @TOKENGUID uniqueidentifier + SET @TOKENGUID = newid() + + INSERT INTO + CurrentUser (TOKENGUID, USERGUID, IPADDRESS, TokenType, UserName) + VALUES + (@TOKENGUID, @USERGUID, @IPADDRESS, @tokentype, @username) + + + SELECT @TOKENGUID AS TOKENGUID, @USERGUID as USERGUID, @USERNAME as USERNAME, @IsSysAdmin as ISSYSADMIN, @tokentype as TOKENTYPE +END +GO + + +--------------------------------------------- + +-- dbo.procLoginCheck +CREATE procedure [dbo].[procLoginCheck] + @username nvarchar(64), + @password nvarchar(64), + @orgpin nvarchar(6) = '', + @ipaddress varchar(15) = 'none' +AS +SET NOCOUNT ON + +SELECT + cast('00000000-0000-0000-0000-000000000000' as uniqueidentifier) as TOKENGUID, + UP.USERGUID, + UP.USERNAME, + ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0) AS IsSysAdmin, + 0 as 'TOKENTYPE' +FROM + UserProfile UP + left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = 'GEN - User Administrator') +WHERE + UP.USERNAME = @USERNAME + AND convert(varbinary, UP.HASHEDPASSWORD) = convert(varbinary, @PASSWORD) + AND UP.IsDisabled = 0 +GO + + +--------------------------------------------- + +-- dbo.procLoginCheckSSO +CREATE procedure [dbo].[procLoginCheckSSO] + @username nvarchar(64), + @authid nvarchar(128), + @ipaddress varchar(15) = 'None' +AS +SET NOCOUNT ON + +SELECT + cast('00000000-0000-0000-0000-000000000000' as uniqueidentifier) as TOKENGUID, + UP.USERGUID, + UP.USERNAME, + ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0) AS IsSysAdmin, + 0 as 'TOKENTYPE' +FROM + UserProfile UP + left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = 'GEN - User Administrator') +WHERE + UP.USERNAME = @USERNAME + AND UP.AUTHID = @AUTHID + AND UP.IsDisabled = 0 +GO + + +--------------------------------------------- + +-- dbo.procLoginGetUserGUID +create proc procLoginGetUserGUID + @username nvarchar(max) +as + select userguid from userprofile where username = @username +GO + + +--------------------------------------------- + +-- dbo.procLoginGetUserSalt +CREATE PROCEDURE [dbo].[procLoginGetUserSalt] +@username nvarchar(max) + AS + BEGIN + select salt from userprofile where username = @username + END +GO + + +--------------------------------------------- + +-- dbo.procLoginNewToken +CREATE procedure [dbo].[procLoginNewToken] + @tokenguid uniqueidentifier, + @ipaddress varchar(15), + @ttl integer = 0, + @updatelastactionstamp bit = 1, + @tokentype int = 0 +as + SET NOCOUNT ON + declare @userguid uniqueidentifier + declare @username nvarchar(64) + declare @cnt int + declare @IsSysAdmin bit + + if((select count(*) from [dbo].[CurrentUser] (readuncommitted) where TokenGUID = @tokenguid and UserGUID = '10101010-1111-0000-1111-101010101010') > 0) begin + select @username = UserName from [dbo].[CurrentUser] where TokenGUID = @tokenguid + set @userguid = '10101010-1111-0000-1111-101010101010' + set @cnt = 1 + set @IsSysAdmin = 1 + end else begin + SELECT + @userguid = CU.USERGUID, + @username = UP.USERNAME, + @cnt = count(*), + @IsSysAdmin = ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0) + FROM + CurrentUser CU (readuncommitted) + INNER JOIN UserProfile UP (readuncommitted) ON CU.UserGUID = UP.UserGUID + left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = 'GEN - User Administrator') + WHERE + TOKENGUID = @tokenguid + AND UP.IsDisabled = 0 + group by CU.userguid, UP.username, IL.GroupingGUID + end + + IF @cnt > 0 BEGIN + declare @NEWTOKENGUID uniqueidentifier + SET @NEWTOKENGUID = newid() + + INSERT INTO + CurrentUser (TOKENGUID, USERGUID, IPADDRESS, LASTACTIONSTAMPUTC, TokenType, UserName) + VALUES + (@NEWTOKENGUID, @USERGUID, @IPADDRESS, DATEADD(day,@ttl,getUTCDate()), @tokentype, @username) + + SELECT @NEWTOKENGUID AS TOKENGUID, @USERGUID as USERGUID, @USERNAME as USERNAME, @IsSysAdmin as ISSYSADMIN, @tokentype as TOKENTYPE + END +GO + + +--------------------------------------------- + +-- dbo.procLoginReauthenticate +CREATE PROC [dbo].[procLoginReauthenticate] + @tokenguid UNIQUEIDENTIFIER, + @ipaddress VARCHAR(15), + @ttl INTEGER = 0, + @updatelastactionstamp BIT = 1 +AS + SET NOCOUNT ON + + IF @updatelastactionstamp = 1 BEGIN + UPDATE CurrentUser + SET LastActionStampUtc = DATEADD(day, @ttl, GETUTCDATE()) + WHERE TOKENGUID = @tokenguid + END + + SELECT CU.TOKENGUID, CU.USERGUID, CU.USERNAME, + CAST((COALESCE((ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS BIT),0)), CASE WHEN CU.UserGUID = dbo.GetSuperUserGUID() THEN 1 ELSE 0 END)) AS BIT) AS [IsSysAdmin], + CU.TokenType + FROM CurrentUser CU + LEFT JOIN UserProfile UP ON CU.UserGUID = UP.UserGUID + LEFT JOIN [dbo].[S3IdentityLink] IL ON UP.UserGUID = IL.MemberGUID AND IL.GroupingGUID = (SELECT UserGroupGUID FROM [dbo].[UserGroup] WHERE GlobalID = 'GEN - User Administrator') + WHERE TOKENGUID = @tokenguid AND ISNULL(UP.IsDisabled, 0) = 0 +GO + + +--------------------------------------------- + +-- dbo.procLoginRecreate +CREATE PROC [dbo].[procLoginRecreate] + @tokenguid UNIQUEIDENTIFIER, + @username NVARCHAR(64), + @hashedpassword NVARCHAR(64), + @orgpin NVARCHAR(6) = '', + @ipaddress VARCHAR(15) = 'none', + @tokentype INT = 0, + @ttl INT = 0 +AS +SET NOCOUNT ON + +DECLARE @userguid UNIQUEIDENTIFIER +DECLARE @cnt INT +DECLARE @IsSysAdmin BIT + +SELECT + @userguid = USERGUID, + @cnt = COUNT(*), + @IsSysAdmin = ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS BIT), 0) +FROM + UserProfile UP + LEFT JOIN [dbo].[S3IdentityLink] IL ON UP.UserGUID = IL.MemberGUID AND IL.GroupingGUID = (SELECT UserGroupGUID FROM [dbo].[UserGroup] WHERE GlobalID = 'GEN - User Administrator') +WHERE + USERNAME = @USERNAME + AND (CONVERT(VARBINARY, HASHEDPASSWORD) = CONVERT(VARBINARY, @HashedPASSWORD)) + AND IsDisabled = 0 +GROUP BY userguid, IL.GroupingGUID + +IF @cnt > 0 BEGIN + DECLARE @LastActionStampUtc DATETIME + SET @LastActionStampUtc = DATEADD(d,@TTL, GETUTCDATE()) + IF NOT EXISTS(SELECT 1 FROM CurrentUser WHERE TokenGUID = @tokenguid) + BEGIN + INSERT INTO CurrentUser (TOKENGUID, USERGUID, IPADDRESS, TokenType, LastActionStampUtc, UserName) + VALUES(@TOKENGUID, @USERGUID, @IPADDRESS, @tokentype, @LastActionStampUtc, @username) + END + ELSE + BEGIN + UPDATE CurrentUser SET LastActionStampUtc = @LastActionStampUtc WHERE TokenGUID = @tokenguid + END + SELECT @TOKENGUID AS TOKENGUID, @USERGUID AS USERGUID, @USERNAME AS USERNAME, @IsSysAdmin AS ISSYSADMIN, @tokentype AS TOKENTYPE +END +GO + + +--------------------------------------------- + +-- dbo.procLoginSSO +CREATE procedure [dbo].[procLoginSSO] + @username nvarchar(64), + @authid nvarchar(128), + @ipaddress varchar(15) = 'none', + @tokentype int = 0 + +AS +SET NOCOUNT ON + +declare @userguid uniqueidentifier +declare @cnt int +declare @IsSysAdmin bit +SELECT + @userguid = USERGUID, + @cnt = count(*), + @IsSysAdmin = ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0) +FROM + UserProfile UP + left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = 'GEN - User Administrator') +WHERE + USERNAME = @USERNAME + AND AUTHID = @AUTHID + AND IsDisabled = 0 +group by userguid, IL.GroupingGUID + + +IF @cnt > 0 BEGIN + DECLARE @tokenguid uniqueidentifier + SET @TOKENGUID = newid() + + INSERT INTO + CurrentUser (TOKENGUID, USERGUID, IPADDRESS, TokenType, UserName) + VALUES + (@TOKENGUID, @USERGUID, @IPADDRESS, @tokentype, @username) + + SELECT @TOKENGUID AS TOKENGUID, @USERGUID as USERGUID, @USERNAME as USERNAME, @IsSysAdmin as ISSYSADMIN, @tokentype as TokenType +END +GO + + +--------------------------------------------- + +-- dbo.procLogoffInactiveUsers +CREATE PROC [dbo].[procLogoffInactiveUsers] +AS + SET NOCOUNT ON + DECLARE @timeoutMinutes INT + SET @timeoutMinutes = 360 --121 + INSERT INTO ActionLog(Action, SubAction, Details, Username, DateTimeStamp, Duration) + SELECT 'Logout', 'Inactivity Logout', CAST(USERGUID AS NVARCHAR(36)), 'procLogoffInactiveUsers', GETUTCDATE(), 0 FROM CurrentUser WHERE DATEDIFF(mi, lastactionstamputc, GETUTCDATE()) > @timeoutMinutes + DELETE FROM CurrentUser WHERE DATEDIFF(mi, lastactionstamputc, GETUTCDATE()) > @timeoutMinutes +GO + + +--------------------------------------------- + +-- dbo.procLogout +CREATE procedure [dbo].[procLogout] + @tokenguid uniqueidentifier, + @ipaddress varchar(15) = 'none' +as + SET NOCOUNT ON + + insert into ActionLog(Action, SubAction, Details, Username, DateTimeStamp, Duration) select 'Logout', 'DB Logout', 'procLogout', UserName, GETDATE(), 0 from [dbo].[CurrentUser] where TOKENGUID = @TOKENGUID + + DELETE FROM CurrentUser where TOKENGUID = @TOKENGUID --and IPADDRESS = @IPADDRESS +GO + + +--------------------------------------------- + +-- dbo.procLogoutAllUsers +CREATE procedure [dbo].[procLogoutAllUsers] +as + SET NOCOUNT ON + + insert into ActionLog(Action, SubAction, Details, Username, DateTimeStamp, Duration) select 'Logout', 'DB Logout', 'procLogoutAllUsers', UserName, GETDATE(), 0 from [dbo].[CurrentUser] + + DELETE FROM CurrentUser WHERE TokenType = 0; + EXEC dbo.procLogoffInactiveUsers; +GO + + +--------------------------------------------- + +-- dbo.procMEImprovDataRemoveDuplicates +CREATE proc dbo.procMEImprovDataRemoveDuplicates +as + --try to resolve duplicates by removing blank values + if (exists(select 1 from MEImprovData group by modelguid, row, col having count(*) > 1)) begin + delete from MEImprovData + where + Formula = '' and CellValue = '' and + ( + ImprovDataGUID in(select min(improvdataguid) from MEImprovData group by modelguid, row, col having count(*) > 1) + or ImprovDataGUID in(select max(improvdataguid) from MEImprovData group by modelguid, row, col having count(*) > 1) + ) + end + + --remove remaining duplicates with the same value + if (exists(select 1 from MEImprovData group by modelguid, row, col, formula, cellvalue having count(*) > 1)) begin + delete from MEImprovData + where + ImprovDataGUID in(select min(improvdataguid) from MEImprovData group by modelguid, row, col, formula, cellvalue having count(*) > 1) + end +GO + + +--------------------------------------------- + +-- dbo.procMEModelChangeDebug +CREATE proc dbo.procMEModelChangeDebug + @higuid uniqueidentifier, + @address nvarchar(max), + @lookbackDays int = 7 +as + --input related info + declare @modelguid uniqueidentifier + select @modelguid = ObjectGUID from HistoryItem where HistoryItemGUID = @higuid + declare @dtname nvarchar(max) + select + @dtname = dt.FriendlyName + from + ScoreTupleDataHistoryChangeItem ci + inner join ScoreDataTable dt on dt.DataTableGUID = ci.DataTableGUID + where + ci.HistoryItemGUID = @higuid; + + --determine lookback range: either since last touch to this cell, or X days + declare @enddate datetime + select @enddate = DateTimeStamp from HistoryItem where HISTORYITEMGUID = @higuid + declare @startdate datetime + select top 1 + @startdate = hi.DATETIMESTAMP + from + ScoreTupleDataHistoryChangeItem ci + inner join HistoryItem hi on hi.HISTORYITEMGUID = ci.HistoryItemGUID + where + hi.OBJECTGUID = @modelguid + and hi.HISTORYITEMGUID != @higuid + and ci.CellAddress = @address + and ci.BeforeValueString != ci.AfterValueString + and hi.DateTimeStamp < @enddate + order by + hi.DATETIMESTAMP desc; + if (@startdate is null) begin + set @startdate = @enddate - @lookbackDays + end + if (datediff(day, @startdate, @enddate) < @lookbackDays) begin + select @startdate = dateadd(day, -1 * @lookbackDays, @enddate) + end + + --other touches of this cell + select + hi.HistoryItemGUID, + hi.DateTimeStamp, + hi.ModifierUserGUID, + hi.ModifierUserName, + cast('Debug Cell Changed' as nvarchar(100)) as Category, + cast(@dtname + ': ' + ci.BeforeValueString + ' -> ' + ci.AfterValueString as nvarchar(max)) as Description + into ##modeldebug + from + ScoreTupleDataHistoryChangeItem ci + inner join HistoryItem hi on hi.HISTORYITEMGUID = ci.HistoryItemGUID + where + hi.OBJECTGUID = @modelguid + and ci.CellAddress = @address + and (hi.HISTORYITEMGUID = @higuid or hi.DATETIMESTAMP between @startdate and @enddate) + and ci.BeforeValueString != ci.AfterValueString; + + --fillin change details + insert into ##modeldebug + select + rli.HistoryItemGUID, + rli.DateTimeStamp, + hi.ModifierUserGUID, + hi.ModifierUserName, + 'Fillin Change' as Category, + rli.SectionName + ': ' + case when rli.Action = 0 then 'Add' when rli.Action = 1 then 'Move' when rli.Action = 2 then 'Delete' else 'Unknown' end + rli.FillinMemberName as Description + from + ScoreFillinRefreshLogItem rli + inner join HistoryItem hi on hi.HistoryItemGUID = rli.HistoryItemGUID + where + rli.ModelGUID = @modelguid + and rli.DateTimeStamp between @startdate and @enddate; + + --other system actions + insert into ##modeldebug + select + hi.HistoryItemGUID, + hi.DateTimeStamp, + hi.ModifierUserGUID, + hi.ModifierUserName, + hi.Category, + hi.Description + from + HistoryItem hi + where + (hi.HISTORYITEMGUID = @higuid or hi.DATETIMESTAMP between @startdate and @enddate) + and (hi.CATEGORY not in('Expansion Changes', 'Model Data Save') or hi.ObjectGUID = @modelguid) + and CATEGORY not in('', 'Contract Model', 'Excel Reporter', 'Form Data', 'Manual Unlock', 'Patient Population Definition', 'Report Action', 'Role Assignment', 'Service Line Definition', 'Service Line Definitions', 'Structure View', 'Workflow') + and Description not like '%Exceptions' + and Description not like 'insert template publish request%' + and Description not in('Sync Expansion Profiles'); + + --global model saves + if (exists(select 1 from XPlan p inner join EMFModelTemplate t on t.ModelTemplateGUID = p.ModelTemplateGUID where p.PlanGUID = @modelguid and t.Name like 'OB Departmental Budget%')) begin + insert into ##modeldebug + select + hi.HistoryItemGUID, + hi.DateTimeStamp, + hi.ModifierUserGUID, + hi.ModifierUserName, + 'Global Model ' + hi.Category as Category, + p.Name as Description + from + HistoryItem hi + inner join XPlan p on p.PlanGUID = hi.ObjectGUID + inner join EMFModelTemplate mt on mt.ModelTemplateGUID = p.ModelTemplateGUID + where + hi.DATETIMESTAMP between @startdate and @enddate + and hi.CATEGORY in('Expansion Changes', 'Model Data Save') + and mt.Name not like 'OB Departmental Budget%' + and mt.Name like 'OB %' + end + + --remove unrelated publishes + delete data + from + ##modeldebug data + inner join HistoryItem hi on hi.HistoryItemGUID = data.HistoryItemGUID + left join EMFModelTemplate mt on mt.ModelTemplateGUID = hi.ObjectGUID + where + hi.DESCRIPTION = 'Template Architect Publish' + and (mt.ModelTemplateGUID is null or not exists(select 1 from XPlan p where p.PlanGUID = @modelguid and p.ModelTemplateGUID = mt.ModelTemplateGUID)); + update data set data.Category = 'Template Publish', data.Description = mt.Name + from + ##modeldebug data + inner join HistoryItem hi on hi.HistoryItemGUID = data.HistoryItemGUID + inner join EMFModelTemplate mt on mt.ModelTemplateGUID = hi.ObjectGUID + where + hi.DESCRIPTION = 'Template Architect Publish'; + + --remove unrelated dimension saves + declare @frameworkID int + select @frameworkID = fw.FrameworkID from PlanType pt inner join Folder f on f.FolderGUID = pt.FolderGUID inner join fw.DimFramework fw on fw.Name = f.Name inner join XPlan p on p.PlanTypeGUID = pt.PlanTypeGUID where p.PlanGUID = @modelguid; + if (@frameworkID is null) begin + set @frameworkID = 0 + end + delete data + from + ##modeldebug data + inner join HistoryItem hi on hi.HistoryItemGUID = data.HistoryItemGUID + inner join ScoreDimension d on d.DimensionGUID = hi.ObjectGUID + where + hi.DESCRIPTION = 'Dimension Save' + and + (not exists(select 1 from ScoreDimensionFramework df where df.DimensionGUID = d.DimensionGUID and df.FrameworkID in(0, @frameworkID)) + or d.FriendlyName like 'Service Line%'); + update data set data.Category = 'Dimension Save', data.Description = d.FriendlyName + from + ##modeldebug data + inner join HistoryItem hi on hi.HistoryItemGUID = data.HistoryItemGUID + inner join ScoreDimension d on d.DimensionGUID = hi.ObjectGUID + where + hi.DESCRIPTION = 'Dimension Save'; + + --remove unrelated ds2 saves + delete data + from + ##modeldebug data + inner join HistoryItem hi on hi.HistoryItemGUID = data.HistoryItemGUID + inner join scoretableeditorconfig tec on tec.tableeditorconfigguid = hi.ObjectGUID + inner join folder f on f.folderguid = tec.folderguid + left join folder pf on pf.folderguid = f.parentfolderguid + left join folder ppf on ppf.folderguid = pf.parentfolderguid + left join folder pppf on pppf.folderguid = ppf.parentfolderguid + inner join fw.dimframework df on df.name = f.name or df.name = isnull(pf.name, 'Missing') or df.name = isnull(ppf.name, 'Missing') or df.name = isnull(pppf.name, 'Missing') + where + hi.Category = 'Data Studio 2.0' + and (df.FrameworkID != @frameworkID or hi.Description = 'SaveView') + update data set data.Category = 'Data Studio Save', data.Description = tec.FriendlyName + from + ##modeldebug data + inner join HistoryItem hi on hi.HistoryItemGUID = data.HistoryItemGUID + inner join scoretableeditorconfig tec on tec.tableeditorconfigguid = hi.ObjectGUID + where + hi.Category = 'Data Studio 2.0' + + --remove unrelated data imports + delete data + from + ##modeldebug data + inner join HistoryItem hi on hi.HistoryItemGUID = data.HistoryItemGUID + inner join IntTransaction t on t.TransactionGUID = hi.HistoryItemGUID + inner join IntConfig c on c.ConfigID = t.ConfigID + where + hi.Category = 'Data Integration' + and not exists(select 1 from dbo.IntConfigFramework cf where cf.ConfigID = c.ConfigID and cf.FrameworkID = @frameworkID); + update data set data.Description = c.Name + from + ##modeldebug data + inner join HistoryItem hi on hi.HistoryItemGUID = data.HistoryItemGUID + inner join IntTransaction t on t.TransactionGUID = hi.HistoryItemGUID + inner join IntConfig c on c.ConfigID = t.ConfigID + where + hi.Category = 'Data Integration'; + + select * from ##modeldebug data + order by + data.DATETIMESTAMP desc, + data.Category asc; + drop table ##modeldebug; +GO + + +--------------------------------------------- + +-- dbo.procMENativeModelingDisable +CREATE proc dbo.procMENativeModelingDisable +as + set nocount on + + update [ob].[SystemSetting] set Value = '0' where Name = 'Native Modeling Enabled' + update [cap].[SystemSetting] set Value = '0' where Name = 'Native Modeling Enabled' + + declare @templateGUID uniqueidentifier + declare crsTemplates cursor fast_forward for select ModelTemplateGUID from [dbo].[EMFModelTemplate] where IsMemoryCachable = 1 + + open crsTemplates + fetch next from crsTemplates into @templateGUID + + while (@@fetch_status = 0) begin + exec [dbo].[procInvalidateModelWorkbookCache] @templateGUID, 1, 0, 'procMENativeModelingDisable' + update [dbo].[EMFModelTemplate] set IsModelWorkbookCachable = 0, IsMemoryCachable = 0 where ModelTemplateGUID = @templateGUID + update [dbo].[XPlan] set IsModelWorkbookCached = 0 where ModelTemplateGUID = @templateGUID + + fetch next from crsTemplates into @templateGUID + end + + close crsTemplates + deallocate crsTemplates + + truncate table dbo.ModelCacheLookup + + update [dbo].[TEScheduledTask] set IsDisabled = 1 where Name = 'GM Prime Model Cache' + update ob.SystemSetting set Value = DefaultValue where Name = 'Native Modeling Priming Limit' + + print('NOTE: If you intend to leave Native Modeling permanently disabled, you will need to manually update plan and directory toolbars to fix the visibility of Edit Budget and Edit Expansion tools.'); +GO + + +--------------------------------------------- + +-- dbo.procMENativeModelingEnable +CREATE PROCEDURE dbo.procMENativeModelingEnable + @cacheServerName NVARCHAR(100) = 'default', + @enablePriming BIT = 1, + @domain NVARCHAR(100) = 'sdt.local', + @frameworkID SMALLINT = 2, --OB + @isMemoryCachePersisted BIT = 1, + @isForTraining BIT = 0 +AS +BEGIN + SET NOCOUNT ON + + IF @frameworkID = 2 + BEGIN + UPDATE ob.SystemSetting + SET Value = '1' + WHERE Name = 'Native Modeling Enabled' + END + + IF @frameworkID = 1 + BEGIN + UPDATE cap.SystemSetting + SET Value = '1' + WHERE Name = 'Native Modeling Enabled' + END + + DECLARE @frameworkName NVARCHAR(100) + DECLARE @frameworkAbbreviation NVARCHAR(10) + + SELECT @frameworkName = Name + FROM fw.DimFramework + WHERE FrameworkID = @frameworkID + + SELECT @frameworkAbbreviation = CASE + WHEN Abbreviation = 'CM' + THEN 'CAP' + ELSE Abbreviation + END + FROM fw.DimFramework + WHERE FrameworkID = @frameworkID + + DECLARE @jazzVersion NVARCHAR(6) + + SELECT @jazzVersion = replace(Setting, '.', '') + FROM dbo.DBSetting + WHERE Name = 'GENERAL_APPVERSION' + + IF @cacheServerName = 'default' + BEGIN + SELECT @cacheServerName = 'Setting' + FROM dbo.DBSetting + WHERE Name = 'MODELING_LOADBALANCED_CACHE_BASE_URL' + END + ELSE + BEGIN + SET @cacheServerName = 'http://' + @cacheServerName + '.' + @domain + END + + --dbsettings + EXEC dbo.procChangeDBSetting 'MODELING_LOADBALANCED_CACHE_BASE_URL', @cacheServerName + EXEC dbo.procChangeDBSetting 'MODELING_ISFILECACHECOMPRESSED', '0' + + --template settings + UPDATE dbo.EMFModelTemplate + SET IsModelWorkbookCachable = @isMemoryCachePersisted, + IsMemoryCachable = 1, + IsModelRefreshOnFillinChange = 0 + WHERE Name LIKE @frameworkAbbreviation + ' %' + + --do not clear HasModelDependents for CAP Advanced Project Pro Forma - it's required for Depreciation re-calculation + DECLARE @capProFormaTemplateGUID UNIQUEIDENTIFIER = '538EAAB2-22B1-41BA-882E-6EFB9C262062' + + UPDATE dbo.EMFModelTemplate + SET HasModelDependents = 0 + WHERE Name LIKE @frameworkAbbreviation + ' %' + AND ModelTemplateGUID <> @capProFormaTemplateGUID + + --plan settings + UPDATE dbo.XPlan + SET IsModelRefreshEnabled = 1, + IsModelWorkbookCached = 0 + WHERE ModelTemplateGUID IN ( + SELECT mt.ModelTemplateGUID + FROM dbo.EMFModelTemplate mt + WHERE mt.Name LIKE @frameworkAbbreviation + ' %' + ) + + --scheduled task + IF @enablePriming = 1 AND @isMemoryCachePersisted = 1 + BEGIN + UPDATE dbo.TEScheduledTask + SET IsDisabled = 0 + WHERE Name = 'GM Prime Model Cache' + END + + --hide edit expansions in form + UPDATE dbo.CustomMenuContent + SET ContentXML = replace(cast(ContentXML AS NVARCHAR(max)), '', '') + WHERE CustomMenuGUID IN ( + SELECT f.CustomMenuGUID + FROM dbo.FE2Form f + INNER JOIN dbo.PlanType pt + ON pt.PlanTypeGUID = f.PlanTypeGUID + INNER JOIN dbo.Folder ptf + ON ptf.FolderGuid = pt.FolderGUID + WHERE ptf.Name = @frameworkName + ) + AND cast(ContentXML AS NVARCHAR(max)) LIKE '%%' + + --limit priming for training + IF (@frameworkID = 2) + BEGIN --OB only + IF (@isForTraining = 1) + BEGIN + UPDATE ob.SystemSetting + SET Value = '10' + WHERE Name = 'Native Modeling Priming Limit' + END + ELSE + BEGIN + UPDATE ob.SystemSetting + SET Value = DefaultValue + WHERE Name = 'Native Modeling Priming Limit' + END + END + + PRINT ('Complete!'); + PRINT ('MANUAL POST STEPS'); + PRINT ('1) Clear Application Cache from Admin Tools'); + PRINT ('2) Ensure Edit Budget tool is visible in both the workspace (Custom Menus->OB Directory Toolbar) and on the form (Plan Type Setup->Edit Form->Edit Toolbar)'); + + IF (@enablePriming = 1) + BEGIN + PRINT ('3) Wait for tasks to finish and System Diagnostics to show no Modeling issues'); + PRINT ('4) Confirm you can launch a model and navigation looks ok'); + END +END +GO + + +--------------------------------------------- + +-- dbo.procMEPHSectionConfigDefaultInsert +CREATE proc [dbo].[procMEPHSectionConfigDefaultInsert] as +exec procScoreRebuildDimensionMemberView + +declare @sql nvarchar(max) + +set @sql = ' +insert into MEPHSectionConfig +(ModelTemplateGUID, PHSectionDimensionGUID, PHSectionMemberGUID, FriendlyName) +select distinct + mt.ModelTemplateGUID, k1.DimensionGUID, dm.MemberGUID, dm.MemberName +from + EMFModelTemplate mt + inner join EMFModelTemplateLinkSource ls on mt.ModelTemplateGUID = ls.ModelTemplateGUID + inner join ScoreComposite sc on ls.ParentScoreCompositeTableGUID = sc.CompositeGUID + inner join ScoreCompositeLink scl on sc.CompositeGUID = scl.CompositeGUID + inner join ScoreAttribute k1 on scl.Key1GUID = k1.AttributeGUID + inner join fw.viewScoreDimensionMember dm on k1.DimensionGUID = dm.DimensionGUID +where + scl.IsPlaceholder = 1 + and not exists ( + select 1 + from + MEPHSectionConfig phx + where + phx.PHSectionDimensionGUID = k1.DimensionGUID + and phx.PHSectionMemberGUID = dm.MemberGUID + )' + +--dynamic to remove dependency on fw schema +exec (@sql) +GO + + +--------------------------------------------- + +-- dbo.procMEPHSectionDuplicatesResolve +CREATE proc dbo.procMEPHSectionDuplicatesResolve + @isdebug bit = 0 +as + --always remove invalid phsections first to avoid false positives + delete from [dbo].[MEPHSection] where PHSectionGUID not in(select v.PHSectionGUID from [dbo].[viewMEPHSection] v) + + declare crsDupes cursor fast_forward for select distinct PlanTypeGUID, ModelTemplateGUID, PHSectionDimensionGUID, PHSectionMemberGUID from [dbo].[viewMEPHSectionDuplicates] where ModelTemplateGUID not in(select ChildModelTemplateGUID from [dbo].[MEScoreExpansionProfile]) + declare @ptguid uniqueidentifier + declare @mtguid uniqueidentifier + declare @dimguid uniqueidentifier + declare @memberguid uniqueidentifier + declare @debugsql nvarchar(max) + declare @phsectionguid uniqueidentifier + + open crsDupes + fetch next from crsDupes into @ptguid, @mtguid, @dimguid, @memberguid + + while(@@fetch_status = 0) begin + select top 1 @phsectionguid = PHSectionGUID from [dbo].[viewMEPHSection] where PlanTypeGUID = @ptguid and ModelTemplateGUID = @mtguid and PHSectionDimensionGUID = @dimguid and PHSectionMemberGUID = @memberguid + select @debugsql = 'select ''' + cast(@phsectionguid as nvarchar(36)) + ''' as Guess, * from dbo.viewMEPHSectionDuplicates where PlanTypeGUID = ''' + cast(@ptguid as nvarchar(36)) + ''' and ModelTemplateGUID = ''' + cast(@mtguid as nvarchar(36)) + ''' and PHSectionDimensionGUID = ''' + cast(@dimguid as nvarchar(36)) + ''' and PHSectionMemberGUID = ''' + cast(@memberguid as nvarchar(36)) + '''' + if (@isdebug = 1) begin + print @debugsql + end + + --if one of the dupes is not configured, delete that one + if ((select count(*) from [dbo].[MEPHSection] where PlanTypeGUID = @ptguid and ModelTemplateGUID = @mtguid and PHSectionDimensionGUID = @dimguid and PHSectionMemberGUID = @memberguid and RuleType != 0) = 1) begin + if (@isdebug = 1) begin + print 'AUTO: duplicates differ by type, delete ''none'' sections + ' + end else begin + delete from [dbo].[MEPHSection] where PlanTypeGUID = @ptguid and ModelTemplateGUID = @mtguid and PHSectionDimensionGUID = @dimguid and PHSectionMemberGUID = @memberguid and RuleType = 0 + end + end else begin + --if dupes are identical delete the one that is invisible in PSM + if((select count(*) from [dbo].[viewMEPHSectionDuplicates] d where d.PlanTypeGUID = @ptguid and d.ModelTemplateGUID = @mtguid and d.PHSectionDimensionGUID = @dimguid and d.PHSectionMemberGUID = @memberguid and not exists(select 1 from [dbo].[viewMEPHSectionDuplicates] f where f.PlanTypeGUID = @ptguid and f.ModelTemplateGUID = @mtguid and f.PHSectionDimensionGUID = @dimguid and f.PHSectionMemberGUID = @memberguid and f.FriendlyName = d.FriendlyName and f.SortType = d.SortType and f.IsConstantIndex = d.IsConstantIndex and f.RootHierarchyPath = d.RootHierarchyPath and f.DefaultHierarchyPath = d.DefaultHierarchyPath and f.IsAppend = d.IsAppend and f.IsHidden = d.IsHidden and f.IsReadOnly = d.IsReadOnly and f.IsExclusive = d.IsExclusive and f.RuleType = d.RuleType and f.IsOneTime = d.IsOneTime and f.IsClearOnRefresh = d.IsClearOnRefresh and f.ExclusivityGroup = d.ExclusivityGroup and f.IsOrderByName = d.IsOrderByName and f.PHSectionGUID != d.PHSectionGUID)) = 0) begin + if (@isdebug = 1) begin + print 'AUTO: duplicates are identical, delete extras + ' + end else begin + delete from [dbo].[MEPHSection] where PHSectionGUID = @phsectionguid + end + end else begin + --otherwise we will remove the first one listed in viewMEPHSection, as this should be the one that is invisible in PSM + if (@isdebug = 1) begin + print 'GUESS: duplicates differ by misc properties + ' + end else begin + delete from [dbo].[MEPHSection] where PHSectionGUID = @phsectionguid + end + end + end + + fetch next from crsDupes into @ptguid, @mtguid, @dimguid, @memberguid + end + + close crsDupes + deallocate crsDupes + + if (@isdebug = 0) begin + exec [dbo].[procMEScoreExpansionProfileSyncTemplatesAll] @isPreservingChildMappings = 1 + + if (exists(select 1 from [dbo].[viewMEPHSectionDuplicates])) begin + print 'FAILED: Some duplicate PH sections count not be auto-resolved.' + end else begin + print 'Success' + end + end +GO + + +--------------------------------------------- + +-- dbo.procMEScoreExpansionGetMaxCount +CREATE PROC [dbo].[procMEScoreExpansionGetMaxCount] + @templateGUID UNIQUEIDENTIFIER, + @phSectionName NVARCHAR(100), + @ignoreOverrides bit = 0 +AS + DECLARE @baseCount INT = NULL, + @ovrCount INT = NULL, + @baseTemplateGUID UNIQUEIDENTIFIER = @templateGUID; + + IF EXISTS (SELECT TOP 1 1 FROM [dbo].[MEScoreExpansionProfile] WHERE [ChildModelTemplateGUID] = @templateGUID) BEGIN + -- find base template guid + SELECT TOP 1 @baseTemplateGUID = [ParentModelTemplateGUID] FROM [dbo].[MEScoreExpansionProfile] WHERE [ChildModelTemplateGUID] = @templateGUID + END + + SELECT @baseCount = MAX(E.[Count]) + FROM [dbo].[MEScoreExpansion] AS E WITH (READUNCOMMITTED) + INNER JOIN [dbo].[viewMECell] AS XC ON E.[ExcelCellGUID] = XC.[CellGUID] + WHERE E.[GlobalID] = @phSectionName AND XC.[BookGUID] = @baseTemplateGUID + + SELECT @ovrCount = MAX(OVR.[CountOverride]) + FROM [dbo].[MEScoreExpansionOverride] AS OVR + INNER JOIN [dbo].[MEScoreExpansionProfile] AS P ON P.[ExpansionProfileGUID] = OVR.[ExpansionProfileGUID] + WHERE OVR.[ExpansionGlobalID] = @phSectionName AND P.[ChildModelTemplateGUID] = @templateGUID + + IF (@baseCount IS NULL) BEGIN + SELECT 0 + END ELSE BEGIN + IF (@ovrCount IS NOT NULL and @ignoreOverrides = 0) BEGIN + SELECT @ovrCount + END ELSE BEGIN + SELECT @baseCount + END + END +GO + + +--------------------------------------------- + +-- dbo.procMEScoreExpansionProfileApplyOverrides +create proc dbo.procMEScoreExpansionProfileApplyOverrides + @childMTGUID uniqueidentifier +as + set nocount on + + update SE set SE.Count = OVR.CountOverride + from + [dbo].[MEScoreExpansion] SE + inner join [dbo].[viewMECell] XC on XC.ExcelCellGUID = SE.ExcelCellGUID + inner join [dbo].[MEScoreExpansionProfile] EP on EP.ChildModelTemplateGUID = XC.ModelTemplateGUID + inner join [dbo].[MEScoreExpansionOverride] OVR on OVR.ExpansionGlobalID = SE.GlobalID and OVR.ExpansionProfileGUID = EP.ExpansionProfileGUID + where + XC.ModelTemplateGUID = @childMTGUID +GO + + +--------------------------------------------- + +-- dbo.procMEScoreExpansionProfileDelete +create proc dbo.procMEScoreExpansionProfileDelete + @profileGUID uniqueidentifier +as + declare @childMTGUID uniqueidentifier + select @childMTGUID = ChildModelTemplateGUID from [dbo].[MEScoreExpansionProfile] where ExpansionProfileGUID = @profileGUID + + exec [dbo].[procEMFRemoveTemplateMappings] @childMTGUID + + delete from [dbo].[S3SimplePermission] where LootID in(select MS.ModelSectionGUID from [dbo].[ModelSection] MS inner join [dbo].[EMFModelTemplateWorksheet] WS on WS.WorksheetGUID = MS.SheetGUID where WS.ModelTemplateGUID = @childMTGUID) + delete from [dbo].[ModelSection] where SheetGUID in(select WS.WorksheetGUID from [dbo].[EMFModelTemplateWorksheet] WS where WS.ModelTemplateGUID = @childMTGUID) + delete from [dbo].[MEPHSectionRuleValue] where PHSectionGUID in(select PHS.PHSectionGUID from [dbo].[MEPHSection] PHS where PHS.ModelTemplateGUID = @childMTGUID) + delete from [dbo].[MEPHSection] where ModelTemplateGUID = @childMTGUID + delete from [dbo].[MEFillinTemplate] where ModelTemplateGUID = @childMTGUID + delete from [dbo].[EMFModelTemplateWorksheet] where ModelTemplateGUID = @childMTGUID; + delete from [dbo].[EMFModelTemplateLinkSource] where ModelTemplateGUID = @childMTGUID; + delete from [dbo].[DataPathFile_ModelTemplate] where CAST(FullPath as nvarchar(51)) = 'ModelTemplates\' + CAST(@childMTGUID as nvarchar(36)); + delete from [dbo].[EMFModelTemplate] where ModelTemplateGUID = @childMTGUID + + delete from [dbo].[MEScoreExpansionProfile] where ExpansionProfileGUID = @profileGUID +GO + + +--------------------------------------------- + +-- dbo.procMEScoreExpansionProfileFitPlans +CREATE PROC [dbo].[procMEScoreExpansionProfileFitPlans] + @templateGUID UNIQUEIDENTIFIER, + @planGUIDList NVARCHAR(MAX) = NULL, + @expansionPadding TINYINT = 10 +AS + SET NOCOUNT ON + + IF EXISTS (SELECT TOP 1 1 FROM [dbo].[MEScoreExpansionProfile] WHERE [ChildModelTemplateGUID] = @templateGUID) + BEGIN + -- we are in the child profile, switch to main template + SELECT TOP 1 @templateGUID = [ParentModelTemplateGUID] FROM [dbo].[MEScoreExpansionProfile] WHERE [ChildModelTemplateGUID] = @templateGUID + END + + IF EXISTS (SELECT TOP 1 1 FROM [dbo].[MEScoreExpansionProfile] WHERE [ParentModelTemplateGUID] = @templateGUID) + BEGIN + + CREATE TABLE #PossiblePlanToTemplateMap ( + [PlanGUID] UNIQUEIDENTIFIER NOT NULL, + [ModelTemplateGUID] UNIQUEIDENTIFIER NOT NULL, + [UsageOrder] INT NOT NULL + ); + + CREATE TABLE #NewPlanToTemplateMap ( + [PlanGUID] UNIQUEIDENTIFIER NOT NULL, + [ModelTemplateGUID] UNIQUEIDENTIFIER NOT NULL + ); + + -- find all templates for each plan it would fit + INSERT INTO #PossiblePlanToTemplateMap([PlanGUID], [ModelTemplateGUID], [UsageOrder]) + SELECT + P.[PlanGUID], + M.[ModelTemplateGUID], + M.[UsageOrder] + FROM [dbo].[XPlan] AS P + CROSS APPLY + ( + SELECT [ChildModelTemplateGUID] AS [ModelTemplateGUID], [UsageOrder] FROM [dbo].[MEScoreExpansionProfile] AS SEP WHERE SEP.[ParentModelTemplateGUID] = @templateGUID + UNION + SELECT @templateGUID AS [ModelTemplateGUID], -1 AS [UsageOrder] + ) AS M + LEFT JOIN + ( -- plans that don't fit in at least one of any profile's overrides + SELECT + DISTINCT + FC.[PlanGUID] AS [PlanGUID], + SEP.[ChildModelTemplateGUID] AS [ModelTemplateGUID] + FROM [dbo].[MEScoreExpansionOverride] AS OVR + INNER JOIN [dbo].[MEScoreExpansionProfile] AS SEP ON SEP.[ExpansionProfileGUID] = OVR.[ExpansionProfileGUID] + INNER JOIN + ( + SELECT -- fillin counts + P.[PlanGUID], + PHS.[FriendlyName], + P.[ModelTemplateGUID], + SUM(CASE WHEN FI.[FillinGUID] IS NULL THEN 0 ELSE 1 END) AS [FillinCount] + FROM [dbo].[XPlan] AS P WITH (READUNCOMMITTED) + INNER JOIN [dbo].[MEPHSection] AS PHS WITH (READUNCOMMITTED) ON PHS.[ModelTemplateGUID] = P.[ModelTemplateGUID] + LEFT JOIN [dbo].[ScoreFillin] AS FI WITH (READUNCOMMITTED) ON FI.[ModelGUID] = P.[PlanGUID] AND FI.[PlaceholderSectionMemberGUID] = PHS.[PHSectionMemberGUID] + WHERE + ((P.[ModelTemplateGUID] = @templateGUID) OR (P.[ModelTemplateGUID] IN (SELECT [ChildModelTemplateGUID] FROM [dbo].[MEScoreExpansionProfile] WHERE [ParentModelTemplateGUID] = @templateGUID))) + GROUP BY + P.[PlanGUID], + PHS.[FriendlyName], + P.[ModelTemplateGUID] + ) AS FC ON OVR.[ExpansionGlobalID] = FC.[FriendlyName] + WHERE + ((FC.[FillinCount] + @expansionPadding) > OVR.[CountOverride]) + ) AS DNF ON DNF.[PlanGUID] = P.PlanGUID AND DNF.[ModelTemplateGUID] = M.[ModelTemplateGUID] + WHERE + ((P.[ModelTemplateGUID] = @templateGUID) OR (P.[ModelTemplateGUID] IN (SELECT [ChildModelTemplateGUID] FROM [dbo].[MEScoreExpansionProfile] WHERE [ParentModelTemplateGUID] = @templateGUID))) + AND (DNF.[PlanGUID] IS NULL) -- exclude invalid mapping + AND ((@planGUIDList IS NULL) OR (P.[PlanGUID] IN (SELECT [guid] FROM [dbo].ConvertCSGuidsToTable(@planGUIDList, ',')))); + + -- find the smallest template for each plan + INSERT INTO #NewPlanToTemplateMap([PlanGUID], [ModelTemplateGUID]) + SELECT + MAP.[PlanGUID], + MAP.[ModelTemplateGUID] + FROM #PossiblePlanToTemplateMap AS MAP + INNER JOIN + ( + SELECT + M.[PlanGUID], + MAX(M.[UsageOrder]) as [MaxUsageOrder] + FROM #PossiblePlanToTemplateMap AS M + GROUP BY M.[PlanGUID] + ) AS MAXMAP ON MAXMAP.[PlanGUID] = MAP.[PlanGUID] + INNER JOIN [dbo].[XPlan] AS EXISTINGPLAN ON EXISTINGPLAN.[PlanGUID] = MAP.[PlanGUID] + WHERE + MAP.[UsageOrder] = MAXMAP.[MaxUsageOrder] -- the smallest profile + AND EXISTINGPLAN.[ModelTemplateGUID] <> MAP.[ModelTemplateGUID] -- exclude plans that are already in correct profile + AND ((@planGUIDList IS NULL) OR (MAP.[PlanGUID] IN (SELECT [guid] FROM [dbo].ConvertCSGuidsToTable(@planGUIDList, ',')))); + + IF EXISTS (SELECT TOP 1 1 FROM #NewPlanToTemplateMap) + BEGIN + + -- move plans + UPDATE P + SET P.[ModelTemplateGUID] = NP.[ModelTemplateGUID] + FROM [dbo].[XPlan] AS P + INNER JOIN #NewPlanToTemplateMap AS NP ON NP.[PlanGUID] = P.[PlanGUID]; + + -- move workspace data + UPDATE IMPR + SET IMPR.[WorksheetGUID] = NWS.[WORKSHEETGUID] + FROM + [dbo].[MEImprovData] AS IMPR + INNER JOIN [dbo].[XPlan] AS P ON P.[PlanGUID] = IMPR.[ModelGUID] + INNER JOIN #NewPlanToTemplateMap AS NP ON NP.[PlanGUID] = P.[PlanGUID] + INNER JOIN [dbo].[EMFModelTemplateWorksheet] AS WS ON WS.WorksheetGUID = IMPR.WorksheetGUID + INNER JOIN [dbo].[EMFModelTemplateWorksheet] AS NWS ON NWS.[Name] = WS.[Name] AND NWS.[ModelTemplateGUID] = P.[ModelTemplateGUID] + WHERE + WS.[ModelTemplateGUID] <> P.[ModelTemplateGUID]; + + -- invalidate cache for the used plans + DECLARE @usedPlanGUIDList NVARCHAR(MAX) = NULL; + SELECT @usedPlanGUIDList = ISNULL(@usedPlanGUIDList + ',', '') + CAST([PlanGUID] AS VARCHAR(36)) FROM #NewPlanToTemplateMap + DECLARE @xplanWhereClause NVARCHAR(MAX) = 'PlanGUID in (SELECT [guid] FROM [dbo].ConvertCSGuidsToTable(''' + @usedPlanGUIDList + ''', '',''))'; + EXEC [dbo].[procInvalidateModelWorkbookCacheByWhereClause] @xplanWhereClause, 0, 'procMEScoreExpansionProfileFitPlans'; + + END + + -- cleanup + DROP TABLE #PossiblePlanToTemplateMap; + DROP TABLE #NewPlanToTemplateMap; + + END + + -- fix fillin templates + UPDATE X SET X.[FillinTemplateGUID] = CT.[FillinTemplateGUID] FROM [dbo].[XPlan] AS X INNER JOIN [dbo].[MEFillinTemplate] AS PT ON PT.[FillinTemplateGUID] = X.[FillinTemplateGUID] INNER JOIN [dbo].[MEFillinTemplate] AS CT ON CT.[ModelTemplateGUID] = X.[ModelTemplateGUID] AND CT.[ModelTemplateGUID] != PT.[ModelTemplateGUID] AND CT.[Name] = PT.[Name]; + UPDATE X SET X.[FillinTemplateGUID] = [dbo].ZeroGUID() FROM [dbo].[XPlan] AS X WHERE NOT EXISTS(SELECT 1 FROM [dbo].[MEFillinTemplate] AS FI WHERE FI.[FillinTemplateGUID] = X.[FillinTemplateGUID] AND FI.[ModelTemplateGUID] = X.[ModelTemplateGUID]); + UPDATE X SET X.[FillinTemplateGUID] = FI.[FillinTemplateGUID] FROM [dbo].[XPlan] AS X INNER JOIN [dbo].[MEFillinTemplate] AS FI ON FI.[ModelTemplateGUID] = X.[ModelTemplateGUID] AND FI.[IsDefault] = 1 WHERE X.[FillinTemplateGUID] = [dbo].ZeroGUID(); + +RETURN +GO + + +--------------------------------------------- + +-- dbo.procMEScoreExpansionProfileRecommend +CREATE PROC [dbo].[procMEScoreExpansionProfileRecommend] + @templateGUID UNIQUEIDENTIFIER +AS + SET NOCOUNT ON; + + IF EXISTS (SELECT TOP 1 1 FROM [dbo].[MEScoreExpansionProfile] WHERE [ChildModelTemplateGUID] = @templateGUID) + BEGIN + -- we are in the child template, switch to main template + SELECT TOP 1 @templateGUID = [ParentModelTemplateGUID] FROM [dbo].[MEScoreExpansionProfile] WHERE [ChildModelTemplateGUID] = @templateGUID; + END + + DECLARE @newProfileWasCreated BIT = 0; + CREATE TABLE #newScoreExpansionOverrides ( + [ExpansionGlobalID] NVARCHAR(100) NOT NULL, + [CountOverride] INT NOT NULL + ); + + -- find outlier sections and create overrides + INSERT INTO #newScoreExpansionOverrides ([ExpansionGlobalID], [CountOverride]) + SELECT + DISTINCT + RMC.[SectionName] AS [ExpansionGlobalID], + RMC.[RecommendedMaxCount] AS [CountOverride] + FROM [dbo].[TemplateSettings] AS TS + INNER JOIN [dbo].[MEScoreExpansionRecommendedMaxCount] AS RMC + ON RMC.[SectionName] = SUBSTRING(TS.[SettingID], 18, LEN(TS.[SettingID])) + WHERE 1=1 + AND TS.[TemplateGUID] = @templateGUID + AND TS.[SettingID] LIKE 'Section Counts%' + AND RMC.[RecommendedMaxCount] < COALESCE(TS.[Value], 0); + + -- outlier profile must have flag IsOutlier and be the first profile + DECLARE @outlierProfileGUID UNIQUEIDENTIFIER = (SELECT TOP 1 [ExpansionProfileGUID] FROM [dbo].[MEScoreExpansionProfile] WHERE ([ParentModelTemplateGUID] = @templateGUID) AND ([IsOutlier] = 1) AND ([UsageOrder] = 0)); + DECLARE @removeExistingProfiles BIT = 0; + + -- remove all existing profiles if + -- outlier profile does not exist and there are overrides + -- outlier profile exists and there no overrides + IF (@outlierProfileGUID IS NULL AND EXISTS(SELECT TOP 1 1 FROM #newScoreExpansionOverrides)) + OR (@outlierProfileGUID IS NOT NULL AND NOT EXISTS(SELECT TOP 1 1 FROM #newScoreExpansionOverrides)) + BEGIN + SET @removeExistingProfiles = 1; + END + + IF (@removeExistingProfiles = 1) + BEGIN + -- remove all existing profiles + -- there won't be more than 2-3 profiles + DECLARE profilesToRemoveCursor CURSOR FAST_FORWARD FOR + SELECT [ExpansionProfileGUID], [ChildModelTemplateGUID] + FROM [dbo].[MEScoreExpansionProfile] WITH (READUNCOMMITTED) + WHERE [ParentModelTemplateGUID] = @templateGUID + ORDER BY [UsageOrder] DESC; + + DECLARE @currentProfileGUID UNIQUEIDENTIFIER, @currentChildMTGUID UNIQUEIDENTIFIER; + + OPEN profilesToRemoveCursor; + FETCH NEXT FROM profilesToRemoveCursor INTO @currentProfileGUID, @currentChildMTGUID; + WHILE(@@FETCH_STATUS = 0) + BEGIN + + -- move workspace data to Parent template (must be done before removing model template) + UPDATE IMPR + SET IMPR.[WorksheetGUID] = NWS.[WORKSHEETGUID] + FROM [dbo].[MEImprovData] AS IMPR + INNER JOIN [dbo].[EMFModelTemplateWorksheet] AS WS + ON WS.[WorksheetGUID] = IMPR.[WorksheetGUID] AND WS.[ModelTemplateGUID] = @currentChildMTGUID + INNER JOIN [dbo].[EMFModelTemplateWorksheet] AS NWS + ON NWS.[Name] = WS.[Name] AND NWS.[ModelTemplateGUID] = @templateGUID; + + -- delete model template + EXEC [dbo].[procEMFRemoveTemplateMappings] @currentChildMTGUID, 0; + DELETE FROM [dbo].[PlanTypeModelTemplateLink] WHERE [ModelTemplateGUID] = @currentChildMTGUID; + DELETE FROM [dbo].[EMFModelTemplate] WHERE [ModelTemplateGUID] = @currentChildMTGUID; + DELETE FROM [dbo].[DataPathFile_ModelTemplate] WHERE [FullPath] LIKE ('%' + CAST(@currentChildMTGUID AS NVARCHAR(36)) + '%'); + + -- delete expansion profile and overrides + DELETE FROM [dbo].[MEScoreExpansionOverride] WHERE [ExpansionProfileGUID] = @currentProfileGUID; + DELETE FROM [dbo].[MEScoreExpansionProfile] WHERE [ExpansionProfileGUID] = @currentProfileGUID; + + -- move all plans to Parent template + UPDATE [dbo].[XPlan] SET [ModelTemplateGUID] = @templateGUID WHERE [ModelTemplateGUID] = @currentChildMTGUID; + + FETCH NEXT FROM profilesToRemoveCursor INTO @currentProfileGUID, @currentChildMTGUID; + END + CLOSE profilesToRemoveCursor; + DEALLOCATE profilesToRemoveCursor; + END + + -- create outlier profile + IF EXISTS(SELECT TOP 1 1 FROM #newScoreExpansionOverrides) + BEGIN + IF (@outlierProfileGUID IS NOT NULL) -- there is existing outlier profile: update existing overrides + BEGIN + -- remove existing overrides + DELETE FROM [dbo].[MEScoreExpansionOverride] WHERE [ExpansionProfileGUID] = @outlierProfileGUID; + + -- add new overrides + INSERT INTO [dbo].[MEScoreExpansionOverride] ([ExpansionProfileGUID], [ExpansionGlobalID], [CountOverride]) + SELECT @outlierProfileGUID, [ExpansionGlobalID], [CountOverride] FROM #newScoreExpansionOverrides; + + -- move all plans to Parent template + DECLARE @childMTGUID UNIQUEIDENTIFIER = (SELECT TOP 1 [ChildModelTemplateGUID] FROM [dbo].[MEScoreExpansionProfile] WHERE [ExpansionProfileGUID] = @outlierProfileGUID) + UPDATE [dbo].[XPlan] SET [ModelTemplateGUID] = @templateGUID WHERE [ModelTemplateGUID] = @childMTGUID; + + PRINT 'Outlier profile updated!'; + END + ELSE + BEGIN + -- create new outlier profile + SET @outlierProfileGUID = NEWID(); + + -- outlier profile is always Profile 1 + INSERT INTO [dbo].[MEScoreExpansionProfile] ([ExpansionProfileGUID], [ParentModelTemplateGUID], [Name], [UsageOrder], [IsOutlier]) + SELECT @outlierProfileGUID, @templateGUID, 'Profile 1', 0, 1; + + -- add overrides for outlier profile + INSERT INTO [dbo].[MEScoreExpansionOverride] ([ExpansionProfileGUID], [ExpansionGlobalID], [CountOverride]) + SELECT @outlierProfileGUID, [ExpansionGlobalID], [CountOverride] FROM #newScoreExpansionOverrides; + + SET @newProfileWasCreated = 1; + + PRINT 'Outlier profile created!'; + END + END + + -- disable/enable NM for parent template + DECLARE @isNativeModelingEnabled BIT = (SELECT TOP 1 [Value] FROM [ob].[SystemSetting] WHERE [Name] = 'Native Modeling Enabled') + + IF (@isNativeModelingEnabled = 1) + BEGIN + IF (((SELECT TOP 1 [ExpansionProfileGUID] FROM [dbo].[MEScoreExpansionProfile] WHERE ([ParentModelTemplateGUID] = @templateGUID) AND ([IsOutlier] = 1) AND ([UsageOrder] = 0)) IS NULL) OR exists(select 1 from [ob].[SystemSetting] where [Name] = 'Native Modeling Limits Enabled' and [Value] = '0')) + BEGIN + UPDATE [dbo].[EMFModelTemplate] SET [IsModelWorkbookCachable] = 1, [IsMemoryCachable] = 1 WHERE [ModelTemplateGUID] = @templateGUID; + END + ELSE + BEGIN + EXEC [dbo].[procInvalidateModelWorkbookCache] @templateGUID, 1, 0, 'procMENativeModelingDisable'; + UPDATE [dbo].[EMFModelTemplate] SET [IsModelWorkbookCachable] = 0, [IsMemoryCachable] = 0 WHERE [ModelTemplateGUID] = @templateGUID; + END + END + + -- create normal profile if needed + + -- clear temp table + DELETE FROM #newScoreExpansionOverrides; + + -- find overrides for new profile + INSERT INTO #newScoreExpansionOverrides ([ExpansionGlobalID], [CountOverride]) + SELECT + DISTINCT + [ExpansionGlobalID], + [CountOverride] + FROM + [dbo].[viewMEPHSectionAnalysisRecommendation] + WHERE + ModelTemplateGUID = @templateGUID; + + -- create profile + IF EXISTS(SELECT TOP 1 1 FROM #newScoreExpansionOverrides) + BEGIN + DECLARE @newProfileGUID UNIQUEIDENTIFIER = NEWID(); + DECLARE @newProfileUsageOrder INT = (SELECT COUNT(*) FROM [dbo].[MEScoreExpansionProfile] WHERE [ParentModelTemplateGUID] = @templateGUID); + + -- create profile + INSERT INTO [dbo].[MEScoreExpansionProfile] ([ExpansionProfileGUID], [ParentModelTemplateGUID], [Name], [UsageOrder], [IsOutlier]) + SELECT @newProfileGUID, @templateGUID, 'Profile ' + CAST((@newProfileUsageOrder + 1) AS NVARCHAR(2)), @newProfileUsageOrder, 0; + + -- create overrides + INSERT INTO [dbo].[MEScoreExpansionOverride] ([ExpansionProfileGUID], [ExpansionGlobalID], [CountOverride]) + SELECT @newProfileGUID, [ExpansionGlobalID], [CountOverride] FROM #newScoreExpansionOverrides; + + SET @newProfileWasCreated = 1; + + PRINT 'New profile created!'; + END + + -- drop temp table + DROP TABLE #newScoreExpansionOverrides; + + -- sync templates + IF (@newProfileWasCreated = 1) + BEGIN + -- build out the new template for this profile so we can apply plans to it + EXEC [dbo].[procMEScoreExpansionProfileSyncTemplates] @templateGUID, 0, 0; + END +GO + + +--------------------------------------------- + +-- dbo.procMEScoreExpansionProfileSyncTemplates +CREATE proc [dbo].[procMEScoreExpansionProfileSyncTemplates] + @parentMTGUID uniqueidentifier, + @isPreservingChildMappings bit = 1, + @isPreservingNavSections bit = 1 +as + set nocount on + + declare @profileGUID uniqueidentifier + declare @childMTGUID uniqueidentifier + declare @nativeModelingEnabled bit = (select top 1 [Value] from [ob].[SystemSetting] where Name = 'Native Modeling Enabled') + declare crsProfiles cursor fast_forward for select ExpansionProfileGUID, ChildModelTemplateGUID from [dbo].[MEScoreExpansionProfile] where ParentModelTemplateGUID = @parentMTGUID order by UsageOrder + + open crsProfiles + fetch next from crsProfiles into @profileGUID, @childMTGUID + + while(@@fetch_status = 0) begin + if (@childMTGUID = dbo.ZeroGUID()) begin + if (@isPreservingChildMappings = 1) begin + --template files incorrectly won't get created in this case, so skip + print 'Invalid parameter value: isPreservingChildMappings' + return + end + + --child template missing, add new + select @childMTGUID = newid() + update [dbo].[MEScoreExpansionProfile] set ChildModelTemplateGUID = @childMTGUID where ExpansionProfileGUID = @profileGUID + + --add template + insert into [dbo].[EMFModelTemplate] ([ModelTemplateGUID], [Name], [Description], [Type], [IsPublished], [IsExpanded], [IsSafeModeOn], [DefaultFormGUID], [IsNewLabelsOnly], [IsUsingHashJoin], [IsScoreFillinAdvancedMode], [IsModelWorkbookCachable], [HasModelDependents], [IsModelRefreshOnFillinChange], [IsReadUncommittedLoad], [IsReadUncommittedSave], [IsMemoryCachable], [PublishOrder], [EditExpansionsMode], [TemplateVersion], [IsUsingOpenWorkbookFormat], [IsHidden]) + select @childMTGUID, MT.Name + ' (' + EP.Name + ')', 'Expansion Profile of ' + MT.[Name], MT.[Type], MT.[IsPublished], MT.[IsExpanded], MT.[IsSafeModeOn], MT.[DefaultFormGUID], MT.[IsNewLabelsOnly], MT.[IsUsingHashJoin], MT.[IsScoreFillinAdvancedMode], @nativeModelingEnabled, MT.[HasModelDependents], MT.[IsModelRefreshOnFillinChange], MT.[IsReadUncommittedLoad], MT.[IsReadUncommittedSave], @nativeModelingEnabled, MT.[PublishOrder], MT.[EditExpansionsMode], MT.[TemplateVersion], MT.[IsUsingOpenWorkbookFormat], cast(1 as bit) + from [dbo].[EMFModelTemplate] MT inner join [dbo].[MEScoreExpansionProfile] EP on EP.ParentModelTemplateGUID = MT.ModelTemplateGUID and EP.ChildModelTemplateGUID = @childMTGUID + where ModelTemplateGUID = @parentMTGUID + + --link template to plantype + insert into [dbo].[PlanTypeModelTemplateLink] (PlanTypeGUID, ModelTemplateGUID) select PlanTypeGUID, @childMTGUID from [dbo].[PlanTypeModelTemplateLink] where ModelTemplateGUID = @parentMTGUID + + end else begin + --child template exists, first clear mappings + if (@isPreservingChildMappings = 0) begin + exec [dbo].[procEMFRemoveTemplateMappings] @childMTGUID, 0 + end + + --sync template + update CMT + set + CMT.Name = PMT.Name + ' (' + EP.Name + ')', + CMT.DefaultFormGUID = PMT.DefaultFormGUID, + CMT.IsScoreFillinAdvancedMode = PMT.IsScoreFillinAdvancedMode, + CMT.IsModelWorkbookCachable = @nativeModelingEnabled, + CMT.HasModelDependents = PMT.HasModelDependents, + CMT.IsModelRefreshOnFillinChange = PMT.IsModelRefreshOnFillinChange, + CMT.IsReadUncommittedLoad = PMT.IsReadUncommittedLoad, + CMT.IsReadUncommittedSave = PMT.IsReadUncommittedSave, + CMT.IsMemoryCachable = @nativeModelingEnabled, + CMT.EditExpansionsMode = PMT.EditExpansionsMode, + CMT.TemplateVersion = PMT.TemplateVersion, + CMT.IsUsingOpenWorkbookFormat = PMT.IsUsingOpenWorkbookFormat, + CMT.IsHidden = 1 + from + [dbo].[EMFModelTemplate] CMT + inner join [dbo].[MEScoreExpansionProfile] EP on EP.ChildModelTemplateGUID = CMT.ModelTemplateGUID + inner join [dbo].[EMFModelTemplate] PMT on PMT.ModelTemplateGUID = EP.ParentModelTemplateGUID + where + CMT.ModelTemplateGUID = @childMTGUID + + --remove deleted fillin templates from the child also + delete from [dbo].[MEFillinTemplate] where ModelTemplateGUID = @childMTGUID and Name not in(select pfit.Name from [dbo].[MEFillinTemplate] pfit where pfit.ModelTemplateGUID = @parentMTGUID); + + --remove other info so we can re-add latest from parent + if (@isPreservingNavSections = 0) begin + delete from [dbo].[S3SimplePermission] where LootID in(select MS.ModelSectionGUID from [dbo].[ModelSection] MS inner join [dbo].[EMFModelTemplateWorksheet] WS on WS.WorksheetGUID = MS.SheetGUID where WS.ModelTemplateGUID = @childMTGUID) + delete from [dbo].[S3SimplePermission] where LootID in(select WS.WorksheetGUID from [dbo].[EMFModelTemplateWorksheet] WS where WS.ModelTemplateGUID = @childMTGUID) + delete from [dbo].[ModelSection] where SheetGUID in(select WS.WorksheetGUID from [dbo].[EMFModelTemplateWorksheet] WS where WS.ModelTemplateGUID = @childMTGUID) + end + delete from [dbo].[ModelSection] where SheetGUID not in(select WS.WorksheetGUID from [dbo].[EMFModelTemplateWorksheet] WS) + delete from [dbo].[MEPHSectionRuleValue] where PHSectionGUID in(select PHS.PHSectionGUID from [dbo].[MEPHSection] PHS where PHS.ModelTemplateGUID = @childMTGUID) + delete from [dbo].[MEPHSection] where ModelTemplateGUID = @childMTGUID + if (@isPreservingChildMappings = 0) begin + delete from [dbo].[EMFModelTemplateWorksheet] where ModelTemplateGUID = @childMTGUID; + delete from [dbo].[EMFModelTemplateLinkSource] where ModelTemplateGUID = @childMTGUID; + delete from [dbo].[DataPathFile_ModelTemplate] where CAST(FullPath as nvarchar(51)) = 'ModelTemplates\' + CAST(@childMTGUID as nvarchar(36)); + end + end + + if (@isPreservingChildMappings = 0) begin + --add worksheets + insert into [dbo].[EMFModelTemplateWorksheet] ([WorksheetGUID], [ModelTemplateGUID], [Name], [DesignerMetaData], [TransformStateGUID], [IsImprov], [IsHiddenOnExpand], [HiddenRows], [HiddenColumns], [IsHeadingsHiddenOnExpand], [ZoomLevel], [IsChartsEnabled], [NameSourceAddress], [DefaultCellAddress], [FreezePanesCellAddress], [IsDefaultSheet], [CounterCellAddress], [CloneCount], [IsClearingByNameCell]) + select newid(), @childMTGUID, [Name], [DesignerMetaData], [TransformStateGUID], [IsImprov], [IsHiddenOnExpand], [HiddenRows], [HiddenColumns], [IsHeadingsHiddenOnExpand], [ZoomLevel], [IsChartsEnabled], [NameSourceAddress], [DefaultCellAddress], [FreezePanesCellAddress], [IsDefaultSheet], [CounterCellAddress], [CloneCount], [IsClearingByNameCell] + from [dbo].[EMFModelTemplateWorksheet] + where ModelTemplateGUID = @parentMTGUID + + --duplicate improv data cannot be handled, so remove it + delete i + from + MEImprovData i + inner join ob.viewDimDepartmentalBudget b on b.MemberGUID = i.ModelGUID + inner join dbo.XPlan p on p.PlanGUID = b.MemberGUID + where + p.ModelTemplateGUID in(@childMTGUID, @parentMTGUID) + and i.ModelGUID in(select sq.modelguid from (select distinct id.modelguid, id.worksheetguid from MEImprovData id group by id.modelguid, id.worksheetguid) sq group by sq.modelguid having count(*) > 1); + + --fix any remaining orphan improv data + update i set i.WorksheetGUID = ws.WorksheetGUID + from + MEImprovData i + inner join ob.viewDimDepartmentalBudget b on b.MemberGUID = i.ModelGUID + inner join dbo.XPlan p on p.PlanGUID = b.MemberGUID + inner join dbo.EMFModelTemplateWorksheet ws on ws.ModelTemplateGUID = p.ModelTemplateGUID and ws.Name = 'Workspace' + where + p.ModelTemplateGUID in(@childMTGUID, @parentMTGUID) + and i.WorksheetGUID != ws.WorksheetGUID; + + --add link sources + insert into [dbo].[EMFModelTemplateLinkSource] ([LinkSourceGUID], [Name], [ModelTemplateGUID], [ParentSubtableGUID], [ParentModelDataConfigGUID], [ParentScoreCompositeTableGUID], [IsSelf]) + select newid(), [Name], @childMTGUID, [ParentSubtableGUID], [ParentModelDataConfigGUID], [ParentScoreCompositeTableGUID], [IsSelf] + from [dbo].[EMFModelTemplateLinkSource] + where ModelTemplateGUID = @parentMTGUID + + --add template files + insert into [dbo].[DataPathFile_ModelTemplate] ([FileGUID], [FullPath], [FileName], [CreationTime], [LastModifiedTime], [Data], [IsLocked]) + select newid(), replace([FullPath], cast(@parentMTGUID as nvarchar(36)), cast(@childMTGUID as nvarchar(36))), replace([FileName], cast(@parentMTGUID as nvarchar(36)), cast(@childMTGUID as nvarchar(36))), getdate(), getdate(), [Data], 0 + from [dbo].[DataPathFile_ModelTemplate] + where FullPath like 'ModelTemplates\%' and CAST(FullPath as nvarchar(51)) = 'ModelTemplates\' + CAST(@parentMTGUID as nvarchar(36)) + end + + --add ph sections + insert into [dbo].[MEPHSection] ([PHSectionGUID], [ModelTemplateGUID], [PHSectionDimensionGUID], [PHSectionMemberGUID], [PlanTypeGUID], [FriendlyName], [SortType], [IsConstantIndex], [RootHierarchyPath], [DefaultHierarchyPath], [IsAppend], [IsHidden], [IsReadOnly], [IsExclusive], [RuleType], [IsOneTime], [IsClearOnRefresh], [ExclusivityGroup], [IsOrderByName], [IsOrderByNameSkippingCode]) + select newid(), @childMTGUID, [PHSectionDimensionGUID], [PHSectionMemberGUID], [PlanTypeGUID], [FriendlyName], [SortType], [IsConstantIndex], [RootHierarchyPath], [DefaultHierarchyPath], [IsAppend], [IsHidden], [IsReadOnly], [IsExclusive], [RuleType], [IsOneTime], [IsClearOnRefresh], [ExclusivityGroup], [IsOrderByName], [IsOrderByNameSkippingCode] + from [dbo].[MEPHSection] + where ModelTemplateGUID = @parentMTGUID + + --add new fillin templates + insert into [dbo].[MEFillinTemplate] ([FillinTemplateGUID], [Name], [ModelTemplateGUID], [IsDefault]) + select newid(), fit.[Name], @childMTGUID, fit.[IsDefault] + from [dbo].[MEFillinTemplate] fit + where fit.ModelTemplateGUID = @parentMTGUID + and not exists(select 1 from [dbo].[MEFillinTemplate] ex where ex.ModelTemplateGUID = @childMTGUID and ex.Name = fit.Name) + + --fix fillin template on existing plans + update XP set XP.FillinTemplateGUID = dbo.ZeroGUID() from [dbo].[XPlan] XP where XP.FillinTemplateGUID != dbo.ZeroGUID() and XP.FillinTemplateGUID not in(select FT.FillinTemplateGUID from [dbo].[MEFillinTemplate] FT where FT.ModelTemplateGUID = XP.ModelTemplateGUID); + update XP set XP.FillinTemplateGUID = FT.FillinTemplateGUID from [dbo].[XPlan] XP inner join [dbo].[MEFillinTemplate] FT on FT.ModelTemplateGUID = XP.ModelTemplateGUID and FT.IsDefault = 1 where XP.FillinTemplateGUID = dbo.ZeroGUID(); + + --add ph section rules + insert into [dbo].[MEPHSectionRuleValue] ([PHSectionRuleValueGUID], [PHSectionGUID], [RuleValueKey], [RuleValue], [SortOrder], [FillinTemplateGUID]) + select newid(), CPHS.[PHSectionGUID], RV.[RuleValueKey], RV.[RuleValue], RV.[SortOrder], isnull(CFT.[FillinTemplateGUID], dbo.ZeroGUID()) + from + [dbo].[MEPHSectionRuleValue] RV + inner join [dbo].[MEPHSection] PPHS on PPHS.PHSectionGUID = RV.PHSectionGUID + inner join [dbo].[MEPHSection] CPHS on PPHS.PHSectionMemberGUID = CPHS.PHSectionMemberGUID and PPHS.IsHidden = CPHS.IsHidden and CPHS.ModelTemplateGUID = @childMTGUID + left join [dbo].[MEFillinTemplate] PFT on PFT.FillinTemplateGUID = RV.FillinTemplateGUID + left join [dbo].[MEFillinTemplate] CFT on CFT.Name = PFT.Name and CFT.ModelTemplateGUID = @childMTGUID + where PPHS.ModelTemplateGUID = @parentMTGUID + + --fix ph section rule values (for rules that reference other ph sections, like union rule) + update CRV set CRV.RuleValue = cast(CPHS.PHSectionGUID as nvarchar(36)) + from + [dbo].[MEPHSectionRuleValue] CRV + inner join [dbo].[MEPHSection] PPHS on cast(PPHS.PHSectionGUID as nvarchar(36)) = CRV.RuleValue and PPHS.ModelTemplateGUID = @parentMTGUID + inner join [dbo].[MEPHSection] CPHS on PPHS.PHSectionMemberGUID = CPHS.PHSectionMemberGUID and PPHS.IsHidden = CPHS.IsHidden and CPHS.ModelTemplateGUID = @childMTGUID + where + exists (select 1 from [dbo].[MEPHSection] CP where CP.PHSectionGUID = CRV.PHSectionGUID and CP.ModelTemplateGUID = @childMTGUID) + + --add model sections + if ((@isPreservingNavSections = 0) or (not exists(select 1 from [dbo].[ModelSection] where SheetGUID in(select WS.WorksheetGUID from [dbo].[EMFModelTemplateWorksheet] WS where WS.ModelTemplateGUID = @childMTGUID)))) begin + insert into [dbo].[ModelSection] ([ModelSectionGUID], [Name], [Range], [Address], [SheetGUID], [ParentGUID], [SortOrder], [IsInherit], [IsHidden]) + select newid(), MS.[Name], MS.[Range], MS.[Address], CWS.WorksheetGUID, MS.[ParentGUID], MS.[SortOrder], MS.[IsInherit], MS.[IsHidden] + from + [dbo].[ModelSection] MS + inner join [dbo].[EMFModelTemplateWorksheet] PWS on PWS.WorksheetGUID = MS.SheetGUID + inner join [dbo].[EMFModelTemplateWorksheet] CWS on CWS.Name = PWS.Name and CWS.ModelTemplateGUID = @childMTGUID + where PWS.ModelTemplateGUID = @parentMTGUID + + --fix model section parents + update CMS set CMS.ParentGUID = CP.ModelSectionGUID + from + [dbo].[ModelSection] CMS + inner join [dbo].[EMFModelTemplateWorksheet] CWS on CWS.WorksheetGUID = CMS.SheetGUID + inner join [dbo].[ModelSection] PP on PP.ModelSectionGUID = CMS.ParentGUID + inner join [dbo].[ModelSection] CP on CP.Address = PP.Address and CP.SheetGUID = CMS.SheetGUID + where + CWS.ModelTemplateGUID = @childMTGUID; + update CMS set CMS.ParentGUID = CMS.SheetGUID + from + [dbo].[ModelSection] CMS + inner join [dbo].[EMFModelTemplateWorksheet] CWS on CWS.WorksheetGUID = CMS.SheetGUID + where + CWS.ModelTemplateGUID = @childMTGUID + and CMS.ParentGUID in(select PWS.WorksheetGUID from [dbo].[EMFModelTemplateWorksheet] PWS where PWS.ModelTemplateGUID = @parentMTGUID); + + --add model section security + insert into [dbo].[S3SimplePermission] (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) + select CMS.ModelSectionGUID, PSP.IdentityGUID, PSP.ReadValue, PSP.WriteValue, PSP.SecureValue + from + [dbo].[ModelSection] MS + inner join [dbo].[EMFModelTemplateWorksheet] PWS on PWS.WorksheetGUID = MS.SheetGUID + inner join [dbo].[EMFModelTemplateWorksheet] CWS on CWS.Name = PWS.Name and CWS.ModelTemplateGUID = @childMTGUID + inner join [dbo].[ModelSection] CMS on CMS.Address = MS.Address and CMS.SheetGUID = CWS.WorksheetGUID + inner join [dbo].[S3SimplePermission] PSP on PSP.LootID = MS.ModelSectionGUID + where PWS.ModelTemplateGUID = @parentMTGUID + + --add model sheet security + insert into [dbo].[S3SimplePermission] (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) + select CWS.WorksheetGUID, PSP.IdentityGUID, PSP.ReadValue, PSP.WriteValue, PSP.SecureValue + from + [dbo].[EMFModelTemplateWorksheet] PWS + inner join [dbo].[EMFModelTemplateWorksheet] CWS on CWS.Name = PWS.Name and CWS.ModelTemplateGUID = @childMTGUID + inner join [dbo].[S3SimplePermission] PSP on PSP.LootID = PWS.WorksheetGUID + where PWS.ModelTemplateGUID = @parentMTGUID + end + + fetch next from crsProfiles into @profileGUID, @childMTGUID + end + + close crsProfiles + deallocate crsProfiles + + declare @higuid uniqueidentifier + exec procLogScript 'Sync Expansion Profiles' , @higuid output +GO + + +--------------------------------------------- + +-- dbo.procMEScoreExpansionProfileSyncTemplatesAll +CREATE proc dbo.procMEScoreExpansionProfileSyncTemplatesAll + @isPreservingChildMappings bit = 1, + @isPreservingNavSections bit = 1 +as + declare @mtGUID uniqueidentifier + declare crsTemplates cursor fast_forward for select distinct ParentModelTemplateGUID from [dbo].[MEScoreExpansionProfile] + + open crsTemplates + fetch next from crsTemplates into @mtGUID + + while(@@fetch_status = 0) begin + exec [dbo].[procMEScoreExpansionProfileSyncTemplates] @mtGUID, @isPreservingChildMappings, @isPreservingNavSections + + fetch next from crsTemplates into @mtGUID + end + + close crsTemplates + deallocate crsTemplates +GO + + +--------------------------------------------- + +-- dbo.procMigrateScriptGet +CREATE proc [dbo].[procMigrateScriptGet] + @schema nvarchar(8), + @sourcedb nvarchar(100) +as + declare @tableName nvarchar(100) + declare crsTables cursor for select name from sys.tables where schema_id in(select schema_id from sys.schemas where name = @schema) + + open crsTables + fetch next from crsTables into @tableName + + declare @migratesql nvarchar(max) + + while(@@FETCH_STATUS = 0) begin + exec procMigrateScriptGetByTable @schema, @sourcedb, @tableName + + fetch next from crsTables into @tableName + end + + close crsTables + deallocate crsTables +GO + + +--------------------------------------------- + +-- dbo.procMigrateScriptGetByDimension +create proc [dbo].[procMigrateScriptGetByDimension] + @schema nvarchar(16), + @sourcedb nvarchar(100), + @tableName nvarchar(100), + @whereClause nvarchar(4000) = '', + @isExecuting bit = 0 +as + if((select count(*) from sys.tables where name = @tableName and schema_id in(select schema_id from sys.schemas where name = @schema)) = 0) begin + RAISERROR ('Destination table not found.', 18, 0) + return + end + + declare @tableId int + select @tableId = object_id from sys.tables where name = @tableName and schema_id in(select schema_id from sys.schemas where name = @schema) + + declare @migratesql nvarchar(max) + set @migratesql = '' + + declare @identName nvarchar(100) + select @identName = name from sys.identity_columns where object_id = @tableId + + declare @columnName nvarchar(100) + + set @migratesql = @migratesql + 'insert into [' + @schema + '].[' + @tableName + '] (MemberGUID,' + + declare crsColumns1 cursor for select name from sys.columns where object_id = @tableId and system_type_id != 189 and is_computed = 0 and name != @identName and name != 'MemberGUID' + open crsColumns1 + fetch next from crsColumns1 into @columnName + while(@@FETCH_STATUS = 0) begin + set @migratesql = @migratesql + '[' + @columnName + '],' + fetch next from crsColumns1 into @columnName + end + close crsColumns1 + deallocate crsColumns1 + + set @migratesql = LEFT(@migratesql, len(@migratesql) - 1) + ') +select (case when MemberGUID in(select ex.MemberGUID from [' + @schema + '].[' + @tableName + '] ex) then newid() else MemberGUID end) as MemberGUID, ' + + declare crsColumns2 cursor for select name from sys.columns where object_id = @tableId and system_type_id != 189 and is_computed = 0 and name != @identName and name != 'MemberGUID' + open crsColumns2 + fetch next from crsColumns2 into @columnName + while(@@FETCH_STATUS = 0) begin + set @migratesql = @migratesql + '[' + @columnName + '],' + fetch next from crsColumns2 into @columnName + end + close crsColumns2 + deallocate crsColumns2 + + set @migratesql = LEFT(@migratesql, len(@migratesql) - 1) + ' +from ' + @sourcedb + '.[' + @schema + '].[' + set @migratesql = @migratesql + @tableName + '] +' + + + --prevent dupes + if(@migratesql not like '%where %') begin + set @migratesql = @migratesql + 'where ' + end else begin + set @migratesql = @migratesql + ' and ' + end + set @migratesql = @migratesql + 'Name not in(select Name from [' + @schema + '].[' + @tableName + '])' + + --add optional where clause + if(@whereClause != '') begin + if(@migratesql not like '%where %') begin + set @migratesql = @migratesql + 'where ' + end else begin + set @migratesql = @migratesql + ' and ' + end + set @migratesql = @migratesql + @whereClause + ' +' + end else begin + set @migratesql = @migratesql + ' +' + end + + set @migratesql = @migratesql + ' +' + + if(@isExecuting = 1) begin + exec(@migratesql) + end else begin + print @migratesql + end +GO + + +--------------------------------------------- + +-- dbo.procMigrateScriptGetByTable +CREATE proc [dbo].[procMigrateScriptGetByTable] + @schema nvarchar(16), + @sourcedb nvarchar(100), + @tableName nvarchar(100), + @whereClause nvarchar(4000) = '', + @isExecuting bit = 0, + @isFromView bit = 0, + @isTestingIndexes bit = 1, + @isTestingPrimaryKeys bit = 1 +as + if((select count(*) from sys.tables where name = @tableName and schema_id in(select schema_id from sys.schemas where name = @schema)) = 0) begin + RAISERROR ('Destination table not found.', 18, 0) + return + end + + declare @tableId int + select @tableId = object_id from sys.tables where name = @tableName and schema_id in(select schema_id from sys.schemas where name = @schema) + + declare @migratesql nvarchar(max) + set @migratesql = '' + + declare @columnName nvarchar(100) + + --identity insert on if contains identity column + if((select COUNT(*) from sys.identity_columns where object_id = @tableId) > 0) begin + set @migratesql = @migratesql + 'set identity_insert [' + @schema + '].[' + @tableName + '] on +' + end + + --truncate fact tables + if(left(@tableName, 4) = 'Fact') begin + set @migratesql = @migratesql + 'truncate table [' + @schema + '].[' + @tableName + '] +' + end + + set @migratesql = @migratesql + 'insert into [' + @schema + '].[' + @tableName + '] (' + + declare crsColumns1 cursor for select name from sys.columns where object_id = @tableId and system_type_id != 189 and is_computed = 0 + open crsColumns1 + fetch next from crsColumns1 into @columnName + while(@@FETCH_STATUS = 0) begin + set @migratesql = @migratesql + '[' + @columnName + '],' + fetch next from crsColumns1 into @columnName + end + close crsColumns1 + deallocate crsColumns1 + + set @migratesql = LEFT(@migratesql, len(@migratesql) - 1) + ') +select ' + + declare crsColumns2 cursor for select name from sys.columns where object_id = @tableId and system_type_id != 189 and is_computed = 0 + open crsColumns2 + fetch next from crsColumns2 into @columnName + while(@@FETCH_STATUS = 0) begin + set @migratesql = @migratesql + '[' + @columnName + '],' + fetch next from crsColumns2 into @columnName + end + close crsColumns2 + deallocate crsColumns2 + + set @migratesql = LEFT(@migratesql, len(@migratesql) - 1) + ' +from ' + @sourcedb + '.[' + @schema + '].[' + if(@isFromView = 1) begin + set @migratesql = @migratesql + 'view' + end + set @migratesql = @migratesql + @tableName + '] +' + + --prevent dupes + declare @keyname nvarchar(64) + declare crsUniqueKeys cursor for + select + c.name + from + sys.columns c + inner join sys.index_columns ic on ic.object_id = c.object_id and ic.column_id = c.column_id + inner join sys.indexes i on i.index_id = ic.index_id and i.object_id = ic.object_id + inner join sys.key_constraints kc on kc.name = i.name + inner join sys.tables t on t.object_id = kc.parent_object_id + where + i.is_unique = 1 + and ((i.name like 'PK_%' and @isTestingPrimaryKeys = 1) or @isTestingIndexes = 1) + and t.object_id = @tableId + open crsUniqueKeys + fetch next from crsUniqueKeys into @keyname + while(@@FETCH_STATUS = 0) begin + if(@migratesql not like '%where %') begin + set @migratesql = @migratesql + 'where ' + end else begin + set @migratesql = @migratesql + ' and ' + end + set @migratesql = @migratesql + @keyname + ' not in(select ' + @keyname + ' from [' + @schema + '].[' + @tableName + '])' + + fetch next from crsUniqueKeys into @keyname + end + close crsUniqueKeys + deallocate crsUniqueKeys + + --add optional where clause + if(@whereClause != '') begin + if(@migratesql not like '%where %') begin + set @migratesql = @migratesql + 'where ' + end else begin + set @migratesql = @migratesql + ' and ' + end + set @migratesql = @migratesql + @whereClause + ' +' + end else begin + set @migratesql = @migratesql + ' +' + end + + --identity insert off + if((select COUNT(*) from sys.identity_columns where object_id = @tableId) > 0) begin + set @migratesql = @migratesql + 'set identity_insert [' + @schema + '].[' + @tableName + '] off +' + end + + set @migratesql = @migratesql + ' +' + + if(@isExecuting = 1) begin + exec(@migratesql) + end else begin + print @migratesql + end +GO + + +--------------------------------------------- + +-- dbo.procMigrateScriptGetByTableComparison +CREATE proc [dbo].[procMigrateScriptGetByTableComparison] + @schema nvarchar(16), + @sourcedb nvarchar(100), + @tableName nvarchar(100), + @whereClause nvarchar(4000) = '', + @isExecuting bit = 0, + @isFromView bit = 0, + @isTestingIndexes bit = 1, + @isTestingPrimaryKeys bit = 1 +as + +------------------------- + --Post Comparison of table copies across DBs + --Output: Target Count to bring over, Table, Resulting Count + --see [dbo].[procSyncEMFDimensionWithScore] for messaging stuff +------------------------- + + +declare @sourcecomparesql nvarchar(max) +set @sourcecomparesql = '' + if(@isFromView = 1) begin + set @sourcecomparesql = @sourcecomparesql + 'select count(*) as srccount from ' + @sourcedb + '.[' + @schema + '].[view' + @tablename + ']' + end else begin + set @sourcecomparesql = @sourcecomparesql + 'select count(*) as srccount from ' + @sourcedb + '.[' + @schema + '].[' + @tablename + ']' + end + + +--declare @targetcomparesql nvarchar(max) +--set @targetcomparesql = '' +-- if(@isFromView = 1) begin +-- set @targetcomparesql = @targetcomparesql + 'select count(*) as tgtcount from [' + @@servername + '].[' + DB_NAME() + '].[' + @schema + '].[view' + @tablename + ']' +-- end else begin +-- set @targetcomparesql = @targetcomparesql + 'select count(*) as tgtcount from [' + @@servername + '].[' + DB_NAME() + '].[' + @schema + '].[' + @tablename + ']' +-- end + + +declare @targetcomparesql nvarchar(max) +set @targetcomparesql = '' + if(@isFromView = 1) begin + set @targetcomparesql = @targetcomparesql + 'select count(*) as tgtcount from [' + @schema + '].[view' + @tablename + ']' + end else begin + set @targetcomparesql = @targetcomparesql + 'select count(*) as tgtcount from [' + @schema + '].[' + @tablename + ']' + end + + + + ----Handle Blank Where Clause - sourcesql + if(@whereClause != '') begin + set @sourcecomparesql = @sourcecomparesql + ' where ' + @whereclause + end else begin + set @sourcecomparesql = @sourcecomparesql +end + + ----Handle Blank Where Clause - targetsql + if(@whereClause != '') begin + set @targetcomparesql = @targetcomparesql + ' where ' + @whereclause + end else begin + set @targetcomparesql = @targetcomparesql +end + + +declare @comparisonsql nvarchar(max) +set @comparisonsql = '' +set @comparisonsql = 'select tgtcount - srccount from (' + + @sourcecomparesql + ') src left join (' + @targetcomparesql + ') tgt on 1 = 1' + + +--print @sourcecomparesql +--print @targetcomparesql +--print @comparisonsql + + + if(@isExecuting = 1) begin + exec(@comparisonsql) + end else begin + select @sourcecomparesql = REPLACE(@sourcecomparesql, 'count(*) as srccount', '*') + select @targetcomparesql = REPLACE(@targetcomparesql, 'count(*) as tgtcount', '*') + print @comparisonsql + print @sourcecomparesql + print @targetcomparesql + end +GO + + +--------------------------------------------- + +-- dbo.procMigrateScriptUpdateAttributeGUID +CREATE proc [dbo].[procMigrateScriptUpdateAttributeGUID] + @sourcedb nvarchar(500), + @attributeGuidNew uniqueidentifier, + @attributeGuidOld uniqueidentifier +as + DECLARE @resultTable table(Query nvarchar(max)) + + DECLARE @migratesqlDropFK table(query nvarchar(max)) + DECLARE @migratesqlCreateFK table(query nvarchar(max)) + DECLARE @migratesqlCreateFKTable table(query nvarchar(max)) + + DECLARE @fKName nvarchar(400), @tableName nvarchar(200), @colName nvarchar(200), @schemaName nvarchar(10); + + DECLARE fkCursor CURSOR FOR + SELECT + fk.name As FKName, + tp.name As ParentTable, + cp.name As ParentColumn, + s.name As SchemaName + FROM + sys.foreign_keys fk + INNER JOIN + sys.tables tp ON fk.parent_object_id = tp.object_id + INNER JOIN + sys.tables tr ON fk.referenced_object_id = tr.object_id + INNER JOIN + sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id + INNER JOIN + sys.columns cp ON fkc.parent_column_id = cp.column_id AND fkc.parent_object_id = cp.object_id + INNER JOIN + sys.columns cr ON fkc.referenced_column_id = cr.column_id AND fkc.referenced_object_id = cr.object_id + INNER JOIN + sys.schemas s on s.schema_id=tp.schema_id + where tr.name='ScoreAttribute' and cr.name = 'AttributeGUID' + ORDER BY + tp.name, cp.column_id + OPEN fkCursor + + FETCH NEXT FROM fkCursor + INTO @fKName, @tableName, @colName, @schemaName + + WHILE (@@FETCH_STATUS = 0) + BEGIN + INSERT INTO @migratesqlCreateFK + SELECT ' ALTER TABLE ' + '[' + @schemaName + '].[' + @tableName + '] ' + + 'ADD CONSTRAINT '+ @fKName + ' FOREIGN KEY (' + @colName + ') ' + + 'REFERENCES ' + '[dbo].[ScoreAttribute](AttributeGUID)' + + INSERT INTO @migratesqlDropFK + SELECT ' ALTER TABLE ' + '[' + @schemaName + '].[' + @tableName + '] ' + + 'DROP CONSTRAINT '+ @fKName + + INSERT INTO @migratesqlCreateFKTable + SELECT ' UPDATE ' + '[' + @schemaName + '].[' + @tableName + '] SET ' + @colName + ' = ''' + convert(varchar(38), @attributeGuidNew) + + ''' WHERE ' + @colName + ' = ''' +convert(varchar(38), @attributeGuidOld) + '''' + + FETCH NEXT FROM fkCursor + INTO @fKName, @tableName, @colName, @schemaName + END + + CLOSE fkCursor + DEALLOCATE fkCursor + + INSERT INTO @resultTable + SELECT * FROM @migratesqlDropFK + + INSERT INTO @resultTable + SELECT ' UPDATE ' + '[dbo].[ScoreAttribute] SET AttributeGUID=''' + convert(nvarchar(38), @attributeGuidNew) + + ''' WHERE AttributeGUID=''' + convert(nvarchar(38), @attributeGuidOld) + '''' + + INSERT INTO @resultTable + SELECT ' UPDATE ' + '[dbo].[ScoreDimension] SET DefaultKeyGUID=''' + convert(nvarchar(38), @attributeGuidNew) + + ''' WHERE DefaultKeyGUID=''' + convert(nvarchar(38), @attributeGuidOld) + '''' + + INSERT INTO @resultTable + SELECT ' UPDATE ' + '[dbo].[ScoreDimension] SET DefaultLookupKeyGUID=''' + convert(nvarchar(38), @attributeGuidNew) + + ''' WHERE DefaultLookupKeyGUID=''' + convert(nvarchar(38), @attributeGuidOld) + '''' + + INSERT INTO @resultTable + SELECT ' UPDATE ' + '[dbo].[ScoreAttribute] SET InferredSourceGUID=''' + convert(nvarchar(38), @attributeGuidNew) + + ''' WHERE InferredSourceGUID=''' + convert(nvarchar(38), @attributeGuidOld) + '''' + + INSERT INTO @resultTable + SELECT ' UPDATE ' + '[dbo].[ScoreAttribute] SET InferredAttributeGuid=''' + convert(nvarchar(38), @attributeGuidNew) + + ''' WHERE InferredAttributeGuid=''' + convert(nvarchar(38), @attributeGuidOld) + '''' + + INSERT INTO @resultTable + SELECT ' UPDATE [dbo].[IntDataInterfaceField] SET ScoreKeyGUID=''' + convert(nvarchar(38), @attributeGuidNew) + + ''' WHERE ScoreKeyGUID=''' + convert(nvarchar(38), @attributeGuidOld) + '''' + + INSERT INTO @resultTable + SELECT * FROM @migratesqlCreateFKTable + + DECLARE tablesCursor CURSOR FOR + SELECT c.name AS ColName, t.name AS TableName, s.name AS SchemaName + FROM sys.columns c + INNER JOIN + sys.tables t ON c.object_id = t.object_id + INNER JOIN + sys.schemas s on s.schema_id=t.schema_id + WHERE (c.name LIKE '%AttributeGUID' or c.name LIKE '%AttributeID') + and t.Name <> 'ScoreAttribute' + and c.Name <> 'ClientReportSectionAttributeGUID' and c.Name <> 'RuleEngineFilterAttributeGUID' and c.Name <> 'ScheduleIncludedAttributeGUID' + and s.name<>'bak' and s.name<>'data' + order by c.name + OPEN tablesCursor + + FETCH NEXT FROM tablesCursor + INTO @colName, @tableName, @schemaName + + WHILE (@@FETCH_STATUS = 0) + BEGIN + INSERT INTO @resultTable + SELECT ' UPDATE ' + '[' + @schemaName + '].[' + @tableName + '] SET ' + @colName + ' = ''' + convert(varchar(38), @attributeGuidNew) + + ''' WHERE ' + @colName + ' = ''' +convert(varchar(38), @attributeGuidOld) + '''' + + FETCH NEXT FROM tablesCursor + INTO @colName, @tableName, @schemaName + END + + CLOSE tablesCursor + DEALLOCATE tablesCursor + + INSERT INTO @resultTable + SELECT * FROM @migratesqlCreateFK + + SELECT * FROM @resultTable +GO + + +--------------------------------------------- + +-- dbo.procMigrateScriptUpdateDimensionGUID +CREATE proc [dbo].[procMigrateScriptUpdateDimensionGUID] + @sourcedb nvarchar(500), + @dimensionGuidNew uniqueidentifier, + @dimensionGuidOld uniqueidentifier +as + DECLARE @resultTable table(Query nvarchar(max)) + + DECLARE @migratesqlDropFK table(query nvarchar(max)) + DECLARE @migratesqlCreateFK table(query nvarchar(max)) + + DECLARE @fKName nvarchar(400), @tableName nvarchar(200), @colName nvarchar(200), @schemaName nvarchar(10); + + DECLARE fkCursor CURSOR FOR + SELECT + fk.name As FKName, + tp.name As ParentTable, + cp.name As ParentColumn, + s.name As SchemaName + FROM + sys.foreign_keys fk + INNER JOIN + sys.tables tp ON fk.parent_object_id = tp.object_id + INNER JOIN + sys.tables tr ON fk.referenced_object_id = tr.object_id + INNER JOIN + sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id + INNER JOIN + sys.columns cp ON fkc.parent_column_id = cp.column_id AND fkc.parent_object_id = cp.object_id + INNER JOIN + sys.columns cr ON fkc.referenced_column_id = cr.column_id AND fkc.referenced_object_id = cr.object_id + INNER JOIN + sys.schemas s on s.schema_id=tp.schema_id + where tr.name='ScoreDimension' and cr.name = 'DimensionGUID' + ORDER BY + tp.name, cp.column_id + OPEN fkCursor + + FETCH NEXT FROM fkCursor + INTO @fKName, @tableName, @colName, @schemaName + + WHILE (@@FETCH_STATUS = 0) + BEGIN + INSERT INTO @migratesqlCreateFK + SELECT ' ALTER TABLE ' + '[' + @schemaName + '].[' + @tableName + '] ' + + 'ADD CONSTRAINT '+ @fKName + ' FOREIGN KEY (' + @colName + ') ' + + 'REFERENCES ' + '[dbo].[ScoreDimension](DimensionGUID)' + + INSERT INTO @migratesqlDropFK + SELECT ' ALTER TABLE ' + '[' + @schemaName + '].[' + @tableName + '] ' + + 'DROP CONSTRAINT '+ @fKName + + FETCH NEXT FROM fkCursor + INTO @fKName, @tableName, @colName, @schemaName + END + + CLOSE fkCursor + DEALLOCATE fkCursor + + INSERT INTO @resultTable + SELECT * FROM @migratesqlDropFK + + INSERT INTO @resultTable + SELECT ' UPDATE ' + '[dbo].[ScoreDimension] SET DimensionGUID=''' + convert(nvarchar(38), @dimensionGuidNew) + + ''' WHERE DimensionGUID=''' + convert(nvarchar(38), @dimensionGuidOld) + '''' + + INSERT INTO @resultTable + SELECT ' UPDATE ' + '[dbo].[S3SimplePermission] SET LootID=''' + convert(nvarchar(38), @dimensionGuidNew) + + ''' WHERE LootID=''' + convert(nvarchar(38), @dimensionGuidOld) + '''' + + DECLARE tablesCursor CURSOR FOR + SELECT c.name AS ColName, t.name AS TableName, s.name AS SchemaName + FROM sys.columns c + INNER JOIN + sys.tables t ON c.object_id = t.object_id + INNER JOIN + sys.schemas s on s.schema_id=t.schema_id + WHERE (c.name LIKE '%DimensionGUID' or c.name LIKE '%DimensionID') + and t.Name<>'AMMultiEditGroup' and t.name<>'ScoreDimension' and t.Name<>'DimensionInfo' and not t.Name like ('EMF%') + and c.name<>'FWDimensionGUID' and c.name<>'RegisteredDimensionGUID' and c.name<>'PlaceholderDimensionGUID' and c.name<>'PoolDimensionGUID' + and s.name<>'bak' and s.name<>'data' + order by c.name + OPEN tablesCursor + + FETCH NEXT FROM tablesCursor + INTO @colName, @tableName, @schemaName + + WHILE (@@FETCH_STATUS = 0) + BEGIN + INSERT INTO @resultTable + SELECT ' UPDATE ' + '[' + @schemaName + '].[' + @tableName + '] SET ' + @colName + ' = ''' + convert(varchar(38), @dimensionGuidNew) + + ''' WHERE ' + @colName + ' = ''' +convert(varchar(38), @dimensionGuidOld) + '''' + + FETCH NEXT FROM tablesCursor + INTO @colName, @tableName, @schemaName + END + + CLOSE tablesCursor + DEALLOCATE tablesCursor + + INSERT INTO @resultTable + SELECT * FROM @migratesqlCreateFK + + SELECT * FROM @resultTable +GO + + +--------------------------------------------- + +-- dbo.procModelDataConfigReindex +CREATE proc [dbo].[procModelDataConfigReindex] + @mdcguid uniqueidentifier +as + /* + declare @guid uniqueidentifier + set @guid = newid() + exec procModelDataConfigReindex @guid + */ + declare @sql varchar(max) + set @sql = ' + DBCC DBREINDEX (''' + dbo.GetZZModelTemplateMappingTableName(@mdcguid) + ''', '' '', 80) + DBCC DBREINDEX (''' + dbo.GetZZModelDataTableName(@mdcguid) + ''', '' '', 80) + ' + print @sql + exec(@sql) +GO + + +--------------------------------------------- + +-- dbo.procModelSectionChildSecurityRefresh +CREATE PROCEDURE [dbo].[procModelSectionChildSecurityRefresh] +AS +BEGIN + WHILE EXISTS + ( + SELECT TOP 1 1 + FROM [dbo].[S3SimplePermission] sec1 + INNER JOIN [dbo].[ModelSection] ms ON sec1.[LootID] = ms.[ModelSectionGUID] + INNER JOIN [dbo].[S3SimplePermission] sec2 ON ms.[ParentGUID] = sec2.[LootID] AND sec1.[IdentityGUID] = sec2.[IdentityGUID] + WHERE 1=1 + AND ms.[IsInherit] = 1 + AND + ( + sec1.[ReadValue] <> sec2.[ReadValue] + OR sec1.[WriteValue] <> sec2.[WriteValue] + OR sec1.[SecureValue] <> sec2.[SecureValue] + ) + ) + BEGIN + UPDATE sec1 + SET sec1.[ReadValue] = sec2.[ReadValue], + sec1.[WriteValue] = sec2.[WriteValue], + sec1.[SecureValue] = sec2.[SecureValue] + FROM [dbo].[S3SimplePermission] sec1 + INNER JOIN [dbo].[ModelSection] ms ON sec1.[LootID] = ms.[ModelSectionGUID] + INNER JOIN [dbo].[S3SimplePermission] sec2 ON ms.[ParentGUID] = sec2.[LootID] AND sec1.[IdentityGUID] = sec2.[IdentityGUID] + WHERE 1 = 1 + AND ms.[IsInherit] = 1 + AND + ( + sec1.[ReadValue] <> sec2.[ReadValue] + OR sec1.[WriteValue] <> sec2.[WriteValue] + OR sec1.[SecureValue] <> sec2.[SecureValue] + ) + END +END +GO + + +--------------------------------------------- + +-- dbo.procMsgBatchReportUpgrade +CREATE proc dbo.procMsgBatchReportUpgrade + @reportGUID uniqueidentifier, + @messageGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000' +as + --copy this message over to the messaging 2.0 tables + --this is a hack due to the old MessageGenerator not being able to talk to messaging 2.0 directly + + insert into [dbo].[EmailThread] (EmailThreadGUID, Subject, DateTimeStamp, ItemGUID, IsForReporting) + select R.ReportGUID, 'Report Snapshots - ' + R.Name, min(T.DateCreated), dbo.ZeroGUID(), 1 from [dbo].[MsgTopic] T inner join [dbo].[REReport] R (readuncommitted) on R.Name = T.Tag + where R.ReportGUID = @reportGUID and not exists(select 1 from [dbo].[EmailThread] EX where EX.EmailThreadGUID = R.ReportGUID) and T.Tag != '' + group by R.ReportGUID, R.Name + + insert into [dbo].[EmailMessage] (EmailMessageGUID, EmailThreadGUID, Subject, DateTimeStamp, Body, SenderUserGUID) + select M.MessageGUID, cast(max(cast(R.ReportGUID as nvarchar(36))) as uniqueidentifier), M.Subject, M.DateCreated, M.Body, M.AuthorGUID from [dbo].[MsgMessage] M inner join [dbo].[MsgTopic] T on T.TopicGUID = M.TopicGUID inner join [dbo].[REReport] R (readuncommitted) on R.Name = T.Tag + where (@messageGUID = '00000000-0000-0000-0000-000000000000' or M.MessageGUID = @messageGUID) and not exists(select 1 from [dbo].[EmailMessage] EX where EX.EmailMessageGUID = M.MessageGUID) and T.Tag != '' + group by M.MessageGUID, M.Subject, M.DateCreated, M.Body, M.AuthorGUID + having exists(select 1 from [dbo].[EmailThread] EXT where EXT.EmailThreadGUID = cast(max(cast(R.ReportGUID as nvarchar(36))) as uniqueidentifier)) + + update EM set EM.SenderUserGUID = S.UserGUID + from + [dbo].[EmailMessage] EM + inner join [dbo].[EmailThread] EMT on EMT.EmailThreadGUID = EM.EmailThreadGUID + inner join [dbo].[MsgMessage] M on M.MessageGUID = EM.EmailMessageGUID + inner join [dbo].[MsgTopic] T on T.TopicGUID = M.TopicGUID + inner join [dbo].[viewS3ACLSimple] S on S.LootID = T.TopicGUID and IsReadable = 1 + where + EMT.EmailThreadGUID = @reportGUID + and (@messageGUID = '00000000-0000-0000-0000-000000000000' or M.MessageGUID = @messageGUID) +GO + + +--------------------------------------------- + +-- dbo.procMsgClearEmailActivity +CREATE proc [dbo].[procMsgClearEmailActivity] +( + @NumDaysToKeep int = 30 +) + as + +delete from MsgEmailActivity where Timestamp < DATEADD(DAY, -@NumDaysToKeep, GETDATE()) +GO + + +--------------------------------------------- + +-- dbo.procMsgMarkAllMessagesRead +CREATE proc [dbo].[procMsgMarkAllMessagesRead] as + +delete from msgmessageread + +CREATE TABLE #tempMessageRead( + [UserGUID] [uniqueidentifier] , + [MessageGUID] [uniqueidentifier], +) + +--add all users that are recipients of topics +insert into #tempMessageRead + select s.UserGUID, m.MessageGUID from MsgTopic T + inner join msgmessage m on t.topicguid = m.topicguid + inner join dbo.viewS3ACLSimple s on cast(t.TopicGUID as varchar(36)) = s.LootID + inner join userprofile u on u.userguid = s.userguid + where s.IsReadable = 1 and t.topicguid not in (select topicguid from msgtopicarchive where userguid = u.userguid) + + --add all user message combos for unsecured forums + insert into #tempMessageRead + select u.userguid, x.messageguid from userprofile u, +(select m.messageguid from msgmessage m +inner join msgtopic t on t.topicguid = m.topicguid +inner join msgforum f on t.forumguid = f.forumguid where f.ForumType = 0 ) x + +--add all user message combos for secured forums +insert into #tempMessageRead +select s.userguid,m.messageguid from msgmessage m inner join msgtopic t on t.topicguid = m.topicguid +inner join msgforum f on t.forumguid = f.forumguid and f.ForumType = 1 +inner join XPlan p on f.EntityGUID = p.PlanGUID +inner join viewS3ACL s on s.LootID = p.CachedLootID +inner join userprofile u on u.userguid = s.userguid +where s.IsReadable = 1 + +--update the message read table +insert into msgmessageread +select x.userguid, x.messageguid, 1, getdate() from +(select distinct userguid, messageguid from #tempMessageRead ) x + +drop table #tempMessageRead +GO + + +--------------------------------------------- + +-- dbo.procMsgMessageCreate +CREATE proc [dbo].[procMsgMessageCreate] +( + @FromUsername nvarchar(max), + @ToUsername nvarchar(max), + @MessageTypeGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000', + @ForumGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000', + @Subject nvarchar(max) = 'New Message', + @Body nvarchar(max) = '' +) + as + + if (@FromUsername = '' or @ToUsername = '') begin + print 'Message could not be created. Usernames were not specified' + return + end + + Declare @fromUserGUID uniqueidentifier + Declare @toUserGUID uniqueidentifier + + Set @fromUserGUID = (select userguid from UserProfile where UserName = @FromUsername) + Set @toUserGUID = (select userguid from UserProfile where UserName = @ToUsername) + + if (@fromUserGUID = dbo.ZeroGUID() or @fromUserGUID is null) begin + print 'Message could not be created. From user does not exist in the database.' + return + end + + if (@toUserGUID = dbo.ZeroGUID() or @toUserGUID is null) begin + print 'Message could not be created. To user does not exist in the database.' + return + end + + if (select COUNT(*) from MsgMessageType where MessageTypeGUID = @MessageTypeGUID) = 0 begin + print 'Message could not be created. Message type does not exist in the database.' + return + end + + Declare @newTopicGUID uniqueidentifier + Declare @newMessageGUID uniqueidentifier + Declare @topicType int + + Declare @messageTypeType int + Set @messageTypeType = (select [TYPE] from MsgMessageType where MessageTypeGUID = @MessageTypeGUID) + + if (@messageTypeType = 0) begin + --forum + + if (select COUNT(*) from MsgForum where ForumGUID = @ForumGUID) = 0 begin + print 'Message could not be created. Forum does not exist in the database.' + return + end + + Declare @forumType int + Set @forumType = (select forumtype from MsgForum where ForumGUID = @ForumGUID) + + if (@forumType = 0) begin + --general forum + Set @topicType = 0 + end else if (@forumType = 1) begin + --plan forum + Set @topicType = 1 + end else begin + print 'Message could not be created. Incorrect type specified for forum.' + return + end + + end else if (@messageTypeType = 1) begin + --notification + Set @topicType = 3 + Set @ForumGUID = dbo.ZeroGUID() + end else if (@messageTypeType = 2) begin + --private message + set @topicType = 2 + Set @ForumGUID = dbo.ZeroGUID() + end else begin + print 'Message could not be created. Incorrect type specified for message type.' + return + end + + Set @newTopicGUID = (select NEWID()) + insert into MsgTopic (TopicGUID, ForumGUID, AuthorGUID, Name, TopicType) values (@newTopicGUID, @ForumGUID, @fromUserGUID, @Subject, @topicType) + + Set @newMessageGUID = (select NEWID()) + insert into MsgMessage (MessageGUID, TopicGUID, MessageTypeGUID, ReplyToMsgGUID, [Subject], Body, AuthorGUID, DateSent) values (@newMessageGUID, @newTopicGUID, @MessageTypeGUID, dbo.ZeroGUID(), @Subject, @Body, @fromUserGUID, '1/1/1900') + + --add security for From & To user + insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) values (@newTopicGUID, @fromUserGUID, 1, 1, 1) + insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) values (@newTopicGUID, @toUserGUID, 1, 1, 1) + + print 'Message created successfully' +GO + + +--------------------------------------------- + +-- dbo.procMsgRemoveAll +CREATE PROC dbo.procMsgRemoveAll + +AS + +-- remove file attachments linked to messages +delete from FileAttachment where entityguid in (select messageguid from msgmessage) + +-- truncate tables +delete from MsgAttachment +delete from MsgBookmark +delete from MsgEmailActivity +delete from MsgMessage +delete from MsgMessagePlanLink +delete from MsgMessageRead +delete from MsgTopic +delete from MsgTopicArchive +delete from MsgForum +delete from MsgForumRead +delete from MsgForumViewed + + +delete from MsgEmailSummary + +delete from EmailRecipient +delete from EmailMessage +delete from EmailThread +GO + + +--------------------------------------------- + +-- dbo.procPlanCreate +CREATE proc [dbo].[procPlanCreate] + @PlanGuid UNIQUEIDENTIFIER + ,@PlanTypeName VARCHAR(450) + ,@PlanName VARCHAR(450) + ,@authorUserName VARCHAR(450) + ,@templateName VARCHAR(450) + ,@planDimensionFQN VARCHAR(450) = '' + ,@lootPrefix NVARCHAR(10) = 'P|' + ,@isSettingAuthor BIT = 1 + ,@isRefreshingSecurity BIT = 1 + ,@isRefreshDirectoryField BIT = 1 + ,@isRunningPlantypeScript BIT = 0 + ,@formDefGUID UNIQUEIDENTIFIER = '00000000-0000-0000-0000-000000000000' + ,@wfMapGUID UNIQUEIDENTIFIER = '00000000-0000-0000-0000-000000000000' + ,@isCreateMissingFormData BIT = 1 + ,@isFromPlanImporter BIT = 0 +as + +-- validation +if len(@templateName) = 0 begin print 'template name required' return end +if len(@lootPrefix) = 0 begin print 'loot prefix is required' return end + +declare @cnt int +select @cnt = COUNT(*) from xplan where PlanGUID = @PlanGuid +if @cnt > 0 begin + print 'plan already exists ' + cast(@PlanGuid as varchar(36)) + return +end + +-- initialization +select @PlanName = dbo.GetWebSafeString(@PlanName) + +declare @ptguid uniqueidentifier +declare @ptdimguid uniqueidentifier +select @ptguid = plantypeguid, @ptdimguid = DimensionGUID from PlanType where Name = @PlanTypeName + +declare @mtguid uniqueidentifier +if LEN(@templateName) = 0 begin + select top 1 @mtguid = ModelTemplateGUID from plantypemodeltemplatelink where plantypeguid = @ptguid +end else begin + select top 1 @mtguid = ModelTemplateGUID from emfmodeltemplate where Name like @templateName +end + +declare @formguid uniqueidentifier + + +IF @formDefGUID = '00000000-0000-0000-0000-000000000000' BEGIN +select top 1 @formguid = formguid from fe2form where plantypeguid = @ptguid +END ELSE BEGIN +select top 1 @formguid = formguid from fe2form where formguid = @formDefGUID +END + + +declare @authorRoleGUID uniqueidentifier +select @authorRoleGUID = userroleguid from UserRole where Type = 1 + +declare @authorUserGUID uniqueidentifier +select @authorUserGUID = userguid from UserProfile where UserName = @authorUserName +if (@authorUserGUID is null) select @authorUserGUID = usergroupguid from UserGroup where Name = @authorUserName +if (@authorUserGUID is null and (@authorUserName like 'sdt\%' or @authorUserName = 'System')) set @authorUserGUID = '10101010-1111-0000-1111-101010101010' + +declare @nameFFGUID uniqueidentifier +select @nameFFGUID = NameFormFieldGUID from PlanType where PlanTypeGUID = @ptguid + + +-- validation +if @PlanName is null begin print '@PlanName is null' return end +if @ptguid is null begin print '@ptguid is null' return end +if @authorUserGUID is null begin print '@authorUserGUID is null' return end +if @mtguid is null begin print '@mtguid is null' return end +if @formguid is null begin print '@formguid is null' return end + +PRINT 'Creating plan: ' + cast(@PlanGuid AS NVARCHAR(36)) + +declare @planid int + +insert into XPlan (planguid, DefaultFormDefGUID, ModelTemplateGUID, PlanTypeGUID) +select + @PlanGuid, + @formguid , + @mtguid, + @ptguid + +set @planid = @@IDENTITY + +-- insert dimension member, and add security +-- info: dimension attributes will be ignored by this procedure +-- need to insert into all non view backed secondary groups then insert into primary group last +-- because security trigger is on primary group and inner joins to secondary groups will filter out members if they dont exist in secondary group +declare @planMemberSql AS NVARCHAR(MAX) +if (len(@planDimensionFQN) > 0) begin + -- insert into secondary groups + declare @planMemberGroupName nvarchar(450) + declare crsDimGroups cursor fast_forward for + select DG.SchemaName + '.' + DG.ObjectName + from ScoreDimensionGroup DG + where + DG.DimensionGUID = @ptdimguid + and (DG.ObjectName not like 'view%' or (DG.SchemaName + '.' + DG.ObjectName like replace(replace(@planDimensionFQN, '[', ''), ']', '') + '%' and DG.ObjectName like '%_custom')) + and DG.DimensionGroupGUID not in (select primarygroupguid from scoredimension where dimensionguid = @ptdimguid) + open crsDimGroups + fetch next from crsDimGroups into @planMemberGroupName + while(@@FETCH_STATUS = 0) begin + SET @planMemberSql = 'INSERT INTO ' + @planMemberGroupName + ' (MemberGUID) VALUES (''' + cast(@PlanGuid AS NVARCHAR(36)) + ''')' + EXEC (@planMemberSql) + fetch next from crsDimGroups into @planMemberGroupName + end + close crsDimGroups + deallocate crsDimGroups + + -- insert into primary group + set @planMemberSql = 'If not exists (select * from ' + @planDimensionFQN + ' where MemberGUID = ''' + + cast(@PlanGuid AS NVARCHAR(36)) + ''')' + ' INSERT INTO ' + @planDimensionFQN + ' (MemberGUID) VALUES (''' + cast(@PlanGuid AS NVARCHAR(36)) + ''')' + EXEC (@planMemberSql) +end + +declare @plandimguid uniqueidentifier; +set @plandimguid = (select dimensionguid from PlanType where Name=@PlanTypeName) +EXEC [dbo].[procScoreDimensionCacheRefresh] @dimensionGUID = @plandimguid + +-- refresh security +if @isRefreshingSecurity = 1 begin + exec procScoreSetDimensionSecurity30 @ptdimguid +end + +-- set author +declare @lootid nvarchar(max) +if @isSettingAuthor = 1 begin + set @lootid = @lootPrefix + cast(@planid as varchar(max)) + exec dbo.procS3AssignIdentityToSpecialRole @authoruserguid, 1, @lootid +end + +-- add/update directory cache +EXEC procDirectoryAddEntry @PlanGuid, @ptguid + +-- add name to formdata - NO LONGER DONE + +-- add to workflow +IF @wfMapGUID = '00000000-0000-0000-0000-000000000000' BEGIN + IF @isFromPlanImporter = 0 BEGIN + insert into WFToken ( EntityGUID, WorkflowMapGUID, WorkflowStepGUID ) + select @PlanGuid, wf.WorkflowMapGUID,wfs.WorkflowStepGUID + from + PlanTypeWorkflowMapLink wf + inner join WFWorkflowStep wfs on wf.WorkflowMapGUID = wfs.WorkflowMapGUID + where PlanTypeGUID = @ptguid and IsRequiredWorkflow = 1 and IsStart = 1 + END +END ELSE BEGIN + insert into WFToken ( EntityGUID, WorkflowMapGUID, WorkflowStepGUID ) + select @PlanGuid, wf.WorkflowMapGUID,wfs.WorkflowStepGUID + from + PlanTypeWorkflowMapLink wf + inner join WFWorkflowStep wfs on wf.WorkflowMapGUID = wfs.WorkflowMapGUID + where PlanTypeGUID = @ptguid and wf.WorkflowMapGUID = @wfMapGUID +END + +-- fillin default +exec procScoreFillinSetByTemplateDefault @PlanGuid, 0 + + +-- (optional) @ptguid +if @isRunningPlantypeScript = 1 begin + + DECLARE @saveScriptGUID AS UNIQUEIDENTIFIER + DECLARE @saveScriptGUID2 AS UNIQUEIDENTIFIER + + DECLARE @saveScript AS VARCHAR(MAX) + DECLARE @saveScript2 AS VARCHAR(MAX) + + select @saveScriptGUID = OnSaveCustomScriptGUID from PlanType where PlanTypeGUID = @ptguid + select @saveScriptGUID2 = OnSaveCustomScript2GUID from PlanType where PlanTypeGUID = @ptguid + + IF @saveScriptGUID <> '00000000-0000-0000-0000-000000000000' BEGIN + select @saveScript = scripttext from CustomScript where CustomScriptGUID = @saveScriptGUID + set @saveScript = REPLACE(@saveScript, '@PlanGuidList', '''' + cast(@PlanGuid AS nvarchar(36)) + '''') + exec (@saveScript) + END + + IF @saveScriptGUID2 <> '00000000-0000-0000-0000-000000000000' BEGIN + select @saveScript2 = scripttext from CustomScript where CustomScriptGUID = @saveScriptGUID2 + set @saveScript2 = REPLACE(@saveScript2, '@PlanGuidList', '''' + cast(@PlanGuid AS nvarchar(36)) + '''') + exec (@saveScript2) + END + +end + +-- create missing form field +IF @isCreateMissingFormData = 1 BEGIN + exec procFormDataCreateMissing @ptguid +END + +-- refresh fields in directory cache +IF @isRefreshDirectoryField = 1 BEGIN + EXEC procDirectoryRefreshFieldAll @ptguid +END +GO + + +--------------------------------------------- + +-- dbo.procPlanDelete +CREATE PROCEDURE [dbo].[procPlanDelete] + @PlanGUID AS UNIQUEIDENTIFIER, + @PlanDimension AS NVARCHAR(128), + @LootPrefix AS NVARCHAR(16) = 'P|', + @IsDeletingData AS BIT = 0 +AS +-- assumptions +-- no score facts + +PRINT 'Deleting ' + CAST(@PlanGUID AS NVARCHAR(36)) + +DECLARE @LootGroupID NVARCHAR(128) +SELECT @LootGroupID = CachedLootID FROM XPlan WHERE PlanGUID = @PlanGUID + +DECLARE @ModelTemplateGUID AS UNIQUEIDENTIFIER +SET @ModelTemplateGUID = (SELECT ModelTemplateGUID FROM XPlan WHERE PlanGUID = @PlanGUID) + +IF @PlanGUID IS NULL BEGIN + Print 'Plan not found' + RETURN +END + +IF @ModelTemplateGUID IS NULL BEGIN + Print 'Template not found: ' + CAST(@ModelTemplateGUID AS NVARCHAR(36)) + RETURN +END + +--Cache +exec [dbo].[procInvalidateModelWorkbookCache] @PlanGUID, 0, 0, 'procPlanDelete' + +DECLARE @SharedSecurityCount int +select @SharedSecurityCount = count(*) from [dbo].[XPlan] P (readuncommitted) inner join [dbo].[PlanType] PT (readuncommitted) on PT.PlanTypeGUID = P.PlanTypeGUID inner join [dbo].[ScoreDimension] D (readuncommitted) on D.DimensionGUID = PT.DimensionGUID where P.PlanGUID = @PlanGUID and D.IsSharingSecurity = 1 + +--Plan Dimension +DECLARE @planDimensionDeleteSql AS NVARCHAR(MAX) +SET @planDimensionDeleteSql = 'DELETE ' + @PlanDimension + ' WHERE memberguid = ''' + CAST(@PlanGUID AS NVARCHAR(36)) + '''' +EXEC (@planDimensionDeleteSql) + +--XPlan +DELETE + XPlan +WHERE + PlanGUID = @PlanGUID + +--remove dependent history records +DELETE FROM dbo.WFHistory WHERE EntityGUID = @PlanGUID + +--S3 (loot and assignment), if the plan does not share security +if (@SharedSecurityCount = 0) begin + EXEC dbo.procS3ClearSecurityByLootGroup @LootGroupID +end + +--delete model data +if @IsDeletingData = 1 begin + + DECLARE @deleteSql AS NVARCHAR(MAX) + DECLARE @whereSql AS NVARCHAR(MAX) + + SET @deleteSql = 'delete data from zzviewModelDataBasic_{mdcnamefriendly} data where data.plansguid = ''' + CAST(@PlanGUID AS NVARCHAR(36)) + '''' + SET @whereSql = 'where modeldataconfigguid in (SELECT LS.ParentModelDataConfigGUID FROM EMFModelTemplateLinkSource LS WHERE LS.IsSelf = 1 AND LS.ModelTemplateGUID = ''' + CAST(@ModelTemplateGUID AS NVARCHAR(36)) + ''')' + + exec procEMFRunForManyStructures @deleteSql, @whereSql, 1, 1 + + --score (implementation incomplete) + delete from [dbo].[ScoreFillin] where ModelGUID = @PlanGUID + exec [dbo].[procScoreFillinTableRefresh] @PlanGUID +end +GO + + +--------------------------------------------- + +-- dbo.procPlanDeleteAll +CREATE PROCEDURE [dbo].[procPlanDeleteAll] + @PlanDimension AS NVARCHAR(128), + @IsExecuting as bit = 0 +AS + +declare @idattr nvarchar(100) +select @idattr = A.SQLColumnName +from [dbo].[ScoreAttribute] A inner join [dbo].[ScoreDimensionGroup] DG on DG.DimensionGroupGUID = A.DimensionGroupGUID inner join [dbo].[ScoreDimension] D on DG.DimensionGUID = D.DimensionGUID and A.AttributeGUID = D.DefaultKeyGUID +where (DG.SchemaName + '.' + DG.ObjectName) = @PlanDimension or (D.SQLSchemaName + '.' + D.SQLObjectName) = @PlanDimension + or ('[' + DG.SchemaName + '].[' + DG.ObjectName + ']') = @PlanDimension or ('[' + D.SQLSchemaName + '].[' + D.SQLObjectName + ']') = @PlanDimension + +declare @sql as nvarchar(max) = ' +declare plancursor CURSOR FAST_FORWARD FOR + select + dimp.memberguid, + p.name + from ' + @PlanDimension + ' dimp + left join xplan p on p.planguid = dimp.memberguid + where + ' + @idattr + ' != 0 + +open plancursor; + +declare @memberguid uniqueidentifier; +declare @planname nvarchar(100); + +FETCH NEXT FROM plancursor into @memberguid, @planname +WHILE (@@FETCH_STATUS = 0) + BEGIN + print (''Deleting Plan: '' + @planname); + exec procPlanDelete @memberguid, ''' + @PlanDimension + ''', default, 1 + FETCH NEXT FROM plancursor into @memberguid, @planname + END +close plancursor; +deallocate plancursor; + +delete from ' + @PlanDimension + ' where ' + @idattr + ' != 0 +' + +if (@IsExecuting=1) + begin + exec (@sql) + end +else + begin + print @sql + end + + +RETURN +GO + + +--------------------------------------------- + +-- dbo.procPlanHistoryInsert +create procedure procPlanHistoryInsert + @planGUIDList nvarchar(max), + @userGUID uniqueidentifier, + @category nvarchar(64), + @description nvarchar(4000) +as + insert into HistoryItem (HISTORYITEMGUID, OBJECTGUID, OBJECTTYPE, DATETIMESTAMP, MODIFIERUSERGUID, CATEGORY, DESCRIPTION, MODIFIERUSERNAME, ITEMCOUNT, METAXML) + select + NEWID(), + P.PlanGUID, + '', + GETDATE(), + @userGUID, + @category, + @description, + coalesce((select NameFull from UserProfile where UserGUID = @userGUID), ''), + 1, + '' + from + XPlan P + where + P.PlanGUID in(select [guid] from dbo.ConvertCSGuidsToTable(@planGUIDList, ',')) +GO + + +--------------------------------------------- + +-- dbo.procPlanMarkModelWorkbookAsCached +CREATE PROC procPlanMarkModelWorkbookAsCached + @planguid uniqueidentifier +AS + UPDATE XPlan SET IsModelWorkbookCached = 1 WHERE PlanGUID = @planguid +GO + + +--------------------------------------------- + +-- dbo.procPopulateCMFactsWithAllAccounts +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2020-11-13 KF JAZZ-8741 My Performance | Standard Metric - UOS Non Staffing +*************************************************************/ +CREATE PROCEDURE [dbo].[procPopulateCMFactsWithAllAccounts] +@MetricGUID uniqueidentifier +AS + +DECLARE @AccountDimensionGUID uniqueidentifier, @BucketGUID uniqueidentifier + +SELECT @BucketGUID = BucketGUID +FROM dbo.CMMetric +WHERE MetricGUID = @MetricGUID + +SELECT @AccountDimensionGUID = DimensionGUID +FROM dbo.ScoreDimension +WHERE GlobalID = 'Account' + +IF @BucketGUID IS NOT NULL +BEGIN + DELETE FROM dbo.CMFacts + WHERE BucketGUID = @BucketGUID + + INSERT INTO dbo.CMFacts (DimensionGUID, MemberGUID, BucketGUID) + SELECT @AccountDimensionGUID, MemberGUID, @BucketGUID + FROM fw.DimAccount +END +GO + + +--------------------------------------------- + +-- dbo.procPopulateDataDictionaryFieldsValueExamples +-- ============================================= +-- Author: Yaroslav Dembitskyi +-- Create date: 7/20/2017 +-- Description: Populates [dbo].[DataDictionaryFieldValueExample] based on existing data. Also provides possibility to update example value for specific scoreGuid +-- Change History: +-- 2/6/2019 yrhee Remove cursors and invalid keylink lookups +-- ============================================= + +CREATE PROC [dbo].[procPopulateDataDictionaryFieldsValueExamples] ( + @specificScoreGuidToUpdate UNIQUEIDENTIFIER = NULL +) +AS +BEGIN + + IF OBJECT_ID('tempdb..#tempDataDictionaryGUIDs') IS NOT NULL + BEGIN + DROP TABLE #tempDataDictionaryGUIDs; + END + + CREATE TABLE #tempDataDictionaryGUIDs (ScoreGUID UNIQUEIDENTIFIER) + + IF(@specificScoreGuidToUpdate IS NOT NULL) + BEGIN + INSERT INTO #tempDataDictionaryGUIDs + SELECT @specificScoreGuidToUpdate + END + ELSE + BEGIN + INSERT INTO #tempDataDictionaryGUIDs + SELECT DISTINCT GivenScoreAttributeGUID + FROM dbo.viewDataDictionary + END + + -- ============================================= + -- Get Attribute Values (incl KeyLinks) + -- ============================================= + DECLARE @sqlAttributes NVARCHAR(MAX) = + ( + SELECT dbo.STRAGGR( + ' SELECT TOP 1 ''' + AttributeGUIDAsText + ''' AttributeGUID, ' + + CASE WHEN ColumnTypeName = 'bit' + THEN ' ''True/False'' ExampleValue ' + WHEN ColumnTypeName LIKE '%datetime%' + THEN ' CONVERT(CHAR(10), ['+ SQLColumnName + '], 103) + SUBSTRING(CONVERT(varchar, [' + SQLColumnName + '], 0),12, 8) ExampleValue ' + + FromWhereClause + ELSE ' CONVERT(NVARCHAR(4000),['+ SQLColumnName + ']) ExampleValue ' + + FromWhereClause END + , ' UNION ALL ', '') + FROM + ( + SELECT DISTINCT + CONVERT(NVARCHAR(40), attr.AttributeGUID) AttributeGUIDAsText, + attr.SQLColumnName, + TYPE_NAME(attr.ColumnType) ColumnTypeName, + ' FROM [' + dim.SQLSchemaName + '].[' + dim.SQLObjectName + '] (NOLOCK) WHERE CONVERT(NVARCHAR(4000),[' + attr.SQLColumnName + ']) <> '''' ' + + CASE WHEN TYPE_NAME(attrKey.ColumnType) LIKE '%int' THEN ' and [' + attrKey.SQLColumnName + '] <> 0 ' ELSE '' END FromWhereClause + FROM #tempDataDictionaryGUIDs dd + INNER JOIN ScoreAttribute attr WITH (READUNCOMMITTED) ON dd.ScoreGUID = attr.AttributeGUID + INNER JOIN ScoreDimensionGroup gr WITH (READUNCOMMITTED) ON attr.DimensionGroupGUID = gr.DimensionGroupGUID + INNER JOIN ScoreDimension dim WITH (READUNCOMMITTED) ON gr.DimensionGUID = dim.DimensionGUID + INNER JOIN ScoreAttribute attrKey WITH (READUNCOMMITTED) ON dim.DefaultKeyGUID = attrKey.AttributeGUID + INNER JOIN dbo.viewSysColumns col WITH (READUNCOMMITTED) ON col.SchemaName = dim.SQLSchemaName AND col.ObjectName = dim.SQLObjectName AND col.ColumnName = attr.SQLColumnName + ) t1 + ); + + -- ============================================= + -- Get Measure Values + -- ============================================= + DECLARE @sqlMeasures NVARCHAR(MAX) = + ( + SELECT dbo.STRAGGR( + ' SELECT TOP 1 ''' + MeasureGUIDAsText + ''' MeasureGUID, ' + + CASE WHEN ColumnTypeName = 'bit' + THEN ' ''True/False'' ExampleValue ' + WHEN ColumnTypeName LIKE '%datetime%' + THEN ' CONVERT(CHAR(10), ['+ SQLColumnName + '], 103) + SUBSTRING(CONVERT(varchar, [' + SQLColumnName + '], 0),12, 8) ExampleValue ' + + FromWhereClause + ELSE ' CONVERT(NVARCHAR(4000),['+ SQLColumnName + ']) ExampleValue ' + + FromWhereClause END + , ' UNION ALL ', '') + FROM + ( + SELECT DISTINCT + CONVERT(NVARCHAR(40), m.MeasureGUID) MeasureGUIDAsText, + m.SQLColumnName, + TYPE_NAME(m.ColumnTypeValue) ColumnTypeName, + ' FROM [' + dt.SQLSchemaName + '].[' + dt.SQLObjectName + '] (NOLOCK) WHERE CONVERT(NVARCHAR(4000),[' + m.SQLColumnName + ']) <> '''' ' FromWhereClause + FROM #tempDataDictionaryGUIDs dd + INNER JOIN ScoreMeasure m WITH (READUNCOMMITTED) ON dd.ScoreGUID = m.MeasureGUID + INNER JOIN ScoreDataTable dt WITH (READUNCOMMITTED) ON m.DataTableGUID = dt.DataTableGUID + INNER JOIN dbo.viewSysColumns col WITH (READUNCOMMITTED) ON col.SchemaName = dt.SQLSchemaName AND col.ObjectName = dt.SQLObjectName AND col.ColumnName = m.SQLColumnName + ) t1 + ); + + -- ===================================================== + -- Final Updates to dbo.DataDictionaryFieldValueExample + -- ===================================================== + DECLARE @sqlFinal NVARCHAR(MAX) = + 'CREATE TABLE #ExampleValues (ScoreGUID UNIQUEIDENTIFIER, ExampleValue NVARCHAR(4000)) ' + + IF (@sqlMeasures IS NOT NULL) + BEGIN + SET @sqlFinal = @sqlFinal + + ' INSERT INTO #ExampleValues (ScoreGUID, ExampleValue) + SELECT MeasureGUID, ExampleValue + FROM (' + @sqlMeasures + ') tMeas ' + END + + IF (@sqlAttributes IS NOT NULL) + BEGIN + SET @sqlFinal = @sqlFinal + + ' INSERT INTO #ExampleValues (ScoreGUID, ExampleValue) + SELECT AttributeGUID, ExampleValue + FROM (' + @sqlAttributes + ') tAttr ' + END + + SET @sqlFinal = @sqlFinal + + ' UPDATE dd + SET dd.ExampleValue = ev.ExampleValue + FROM dbo.DataDictionaryFieldValueExample dd + INNER JOIN #ExampleValues ev ON dd.ScoreGUID = ev.ScoreGUID + WHERE dd.ExampleValue != ev.ExampleValue + + INSERT INTO dbo.DataDictionaryFieldValueExample (ScoreGUID, ExampleValue) + SELECT ev.ScoreGUID, ev.ExampleValue + FROM #ExampleValues ev + LEFT JOIN dbo.DataDictionaryFieldValueExample dd on ev.ScoreGUID = dd.ScoreGUID + WHERE dd.ScoreGUID IS NULL ' + + IF (@specificScoreGuidToUpdate IS NULL) -- DON'T DELETE IF SINGLE GUID + BEGIN + SET @sqlFinal = @sqlFinal + + ' DELETE FROM dbo.DataDictionaryFieldValueExample + WHERE ScoreGUID NOT IN (SELECT ScoreGUID FROM #ExampleValues) ' + END + + SET @sqlFinal = @sqlFinal + + ' DROP TABLE #ExampleValues '; + + EXEC(@sqlFinal); + + IF OBJECT_ID('tempdb..#tempDataDictionaryGUIDs') IS NOT NULL + BEGIN + DROP TABLE #tempDataDictionaryGUIDs; + END +END +GO + + +--------------------------------------------- + +-- dbo.procPrintLongText +create proc dbo.procPrintLongText + @String NVARCHAR(MAX) +as + DECLARE @CurrentEnd BIGINT; /* track the length of the next substring */ + DECLARE @offset tinyint; /*tracks the amount of offset needed */ + set @string = replace( replace(@string, char(13) + char(10), char(10)) , char(13), char(10)) + + WHILE LEN(@String) > 1 + BEGIN + IF CHARINDEX(CHAR(10), @String) between 1 AND 4000 + BEGIN + SET @CurrentEnd = CHARINDEX(char(10), @String) -1 + set @offset = 2 + END + ELSE + BEGIN + SET @CurrentEnd = 4000 + set @offset = 1 + END + PRINT SUBSTRING(@String, 1, @CurrentEnd) + set @string = SUBSTRING(@String, @CurrentEnd+@offset, LEN(@String)) + END +GO + + +--------------------------------------------- + +-- dbo.procRESQLReportRegisteredAttributeFixReferences +CREATE proc dbo.procRESQLReportRegisteredAttributeFixReferences + @reportGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000', + @attributeGUIDCSV nvarchar(max) = '', + @beforeColumnName nvarchar(100) = '', + @afterColumnName nvarchar(100) = '', + @dataViewGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000' +as + ------------------------------------------ + -- AD HOC REPORTS + ------------------------------------------ + + --fix broken ad hoc parameters - always works as long as the attribute is registered + update p set p.ColumnName = ra.ColumnName, p.Name = case when @afterColumnName = '' then p.Name else @afterColumnName end + from + viewREClientReportParameter_Broken bk + inner join REClientReportParameter p on p.ClientReportParameterGUID = bk.ClientReportParameterGUID + inner join viewRESQLReportRegisteredAttribute_ByReport ra on ra.ReportGUID = bk.ReportGUID and cast(ra.AttributeGUID as nvarchar(36)) = p.AttributeID + where + bk.ReportGUID = @reportGUID or @reportGUID = '00000000-0000-0000-0000-000000000000' + and (@dataViewGUID = '00000000-0000-0000-0000-000000000000' or exists(select 1 from REClientReportDataSourceLink l where l.ReportGUID = bk.ReportGUID and l.DataSourceGUID = @dataViewGUID)) + + --fix broken ad hoc section attributes - always works as long as the attribute is registered + update sa set sa.ColumnName = ra.ColumnName, sa.Name = case when @afterColumnName = '' then sa.Name else @afterColumnName end + from + viewREClientReportSectionAttribute_Broken bk + inner join REClientReportSectionAttribute sa on sa.ClientReportSectionAttributeGUID = bk.ClientReportSectionAttributeGUID + inner join viewRESQLReportRegisteredAttribute_ByReport ra on ra.ReportGUID = bk.ReportGUID and cast(ra.AttributeGUID as nvarchar(36)) = sa.AttributeID + where + bk.ReportGUID = @reportGUID or @reportGUID = '00000000-0000-0000-0000-000000000000' + and (@dataViewGUID = '00000000-0000-0000-0000-000000000000' or exists(select 1 from REClientReportDataSourceLink l where l.ReportGUID = bk.ReportGUID and l.DataSourceGUID = @dataViewGUID)) + + ------------------------------------------ + -- SQL REPORTS + ------------------------------------------ + + --NOTE: not fixing display names because this would break excel report references that cannot be updated via SQL + + --fix broken sql report display columns that match rename parameters + if (@attributeGUIDCSV != '' and @beforeColumnName != '' and @afterColumnName != '') begin + update dc set dc.ColumnName = ra.ColumnName + from + viewRESQLReportDisplayColumn_Broken bk + inner join RESQLReportSetup rs on rs.SQLReportSetupGUID = bk.SQLReportSetupGUID + inner join RESQLReportDisplayColumn dc on dc.DisplayColumnGUID = bk.DisplayColumnGUID + inner join viewRESQLReportRegisteredAttribute_ByReport ra on ra.ReportGUID = bk.ReportGUID and ra.ColumnName = @afterColumnName + inner join viewScoreAttribute a on a.AttributeGUID = ra.AttributeGUID + inner join (select guid as AttributeGUID from dbo.ConvertCSGuidsToTable(@attributeGUIDCSV, ',')) csv on csv.AttributeGUID = a.AttributeGUID or csv.AttributeGUID = a.ForeignKeyGUID or csv.AttributeGUID = a.InferredAttributeGUID + where + (dc.ColumnName = @beforeColumnName or @beforeColumnName like dc.ColumnName + ' Name') + and (bk.ReportGUID = @reportGUID or @reportGUID = '00000000-0000-0000-0000-000000000000') + and (@dataViewGUID = '00000000-0000-0000-0000-000000000000' or rs.DataViewGUID = @dataViewGUID) + end else begin + --fix broken sql report display columns - only works if column name mismatch is only due to extra/missing spaces + update dc set dc.ColumnName = ra.ColumnName + from + viewRESQLReportDisplayColumn_Broken bk + inner join RESQLReportSetup rs on rs.SQLReportSetupGUID = bk.SQLReportSetupGUID + inner join RESQLReportDisplayColumn dc on dc.DisplayColumnGUID = bk.DisplayColumnGUID + inner join viewRESQLReportRegisteredAttribute_ByReport ra on ra.ReportGUID = bk.ReportGUID and replace(ra.ColumnName, ' ', '') = replace(dc.ColumnName, ' ', '') + where + bk.ReportGUID = @reportGUID or @reportGUID = '00000000-0000-0000-0000-000000000000' + and (@dataViewGUID = '00000000-0000-0000-0000-000000000000' or rs.DataViewGUID = @dataViewGUID) + end + + --fix broken sql report filter columns that match rename parameters + if (@attributeGUIDCSV != '' and @beforeColumnName != '' and @afterColumnName != '') begin + update fc set fc.ColumnName = ra.ColumnName + from + viewRESQLReportFilterColumn_Broken bk + inner join RESQLReportSetup rs on rs.SQLReportSetupGUID = bk.SQLReportSetupGUID + inner join RESQLReportFilterColumn fc on fc.FilterColumnGUID = bk.FilterColumnGUID + inner join viewRESQLReportRegisteredAttribute_ByReport ra on ra.ReportGUID = bk.ReportGUID and ra.ColumnName = @afterColumnName + inner join viewScoreAttribute a on a.AttributeGUID = ra.AttributeGUID + inner join (select guid as AttributeGUID from dbo.ConvertCSGuidsToTable(@attributeGUIDCSV, ',')) csv on csv.AttributeGUID = a.AttributeGUID or csv.AttributeGUID = a.ForeignKeyGUID or csv.AttributeGUID = a.InferredAttributeGUID + where + (fc.ColumnName = @beforeColumnName or @beforeColumnName like fc.ColumnName + ' Name') + and (bk.ReportGUID = @reportGUID or @reportGUID = '00000000-0000-0000-0000-000000000000') + and (@dataViewGUID = '00000000-0000-0000-0000-000000000000' or rs.DataViewGUID = @dataViewGUID) + end else begin + --fix broken sql report filter columns - only works if column name mismatch is only due to extra/missing spaces + update fc set fc.ColumnName = ra.ColumnName + from + viewRESQLReportFilterColumn_Broken bk + inner join RESQLReportSetup rs on rs.SQLReportSetupGUID = bk.SQLReportSetupGUID + inner join RESQLReportFilterColumn fc on fc.FilterColumnGUID = bk.FilterColumnGUID + inner join viewRESQLReportRegisteredAttribute_ByReport ra on ra.ReportGUID = bk.ReportGUID and replace(ra.ColumnName, ' ', '') = replace(fc.ColumnName, ' ', '') + where + bk.ReportGUID = @reportGUID or @reportGUID = '00000000-0000-0000-0000-000000000000' + and (@dataViewGUID = '00000000-0000-0000-0000-000000000000' or rs.DataViewGUID = @dataViewGUID) + end + + ------------------------------------------ + -- EXCEL REPORTS + ------------------------------------------ + + --fix broken excel reporter sort columns that match rename parameters + if (@attributeGUIDCSV != '' and @beforeColumnName != '' and @afterColumnName != '') begin + update p set p.ColumnName = ra.ColumnName + from + viewRESortingParameter_Broken bk + inner join RESortingParameter p on p.ParameterGUID = bk.ParameterGUID + inner join viewRESQLReportRegisteredAttribute_ByReport ra on ra.ReportGUID = bk.ReportGUID and ra.ColumnName = @afterColumnName + inner join viewScoreAttribute a on a.AttributeGUID = ra.AttributeGUID + inner join (select guid as AttributeGUID from dbo.ConvertCSGuidsToTable(@attributeGUIDCSV, ',')) csv on csv.AttributeGUID = a.AttributeGUID or csv.AttributeGUID = a.ForeignKeyGUID or csv.AttributeGUID = a.InferredAttributeGUID + where + (p.ColumnName = @beforeColumnName or @beforeColumnName like p.ColumnName + ' Name') + and (bk.ReportGUID = @reportGUID or @reportGUID = '00000000-0000-0000-0000-000000000000') + and (@dataViewGUID = '00000000-0000-0000-0000-000000000000' or bk.DataViewGUID = @dataViewGUID) + end else begin + --fix broken excel reporter sort columns - only works if column name mismatch is only due to extra/missing spaces + update p set p.ColumnName = ra.ColumnName + from + viewRESortingParameter_Broken bk + inner join RESortingParameter p on p.ParameterGUID = bk.ParameterGUID + inner join viewRESQLReportRegisteredAttribute_ByReport ra on ra.ReportGUID = bk.ReportGUID and replace(ra.ColumnName, ' ', '') = replace(p.ColumnName, ' ', '') + where + bk.ReportGUID = @reportGUID or @reportGUID = '00000000-0000-0000-0000-000000000000' + and (@dataViewGUID = '00000000-0000-0000-0000-000000000000' or bk.DataViewGUID = @dataViewGUID) + end + + ------------------------------------------ + -- DASHBOARDS + ------------------------------------------ + if (@dataViewGUID = '00000000-0000-0000-0000-000000000000') begin + --fix broken desktop parameters + update bk set bk.ColumnName = ra.ColumnName, bk.Name = case when @afterColumnName = '' then bk.Name else @afterColumnName end + from + viewDesktopParameter_Broken bk + inner join ( + select + dp.DesktopParameterGUID, + max(ra.ColumnName) as ColumnName + from + DesktopParameter dp + inner join REReport r on dp.ReportGuidsCSV like '%' + cast(r.ReportGUID as nvarchar(36)) + '%' + inner join viewRESQLReportRegisteredAttribute_ByReport ra on ra.ReportGUID = r.ReportGUID and cast(ra.AttributeGUID as nvarchar(36)) = dp.AttributeID + group by + dp.DesktopParameterGUID + ) ra on ra.DesktopParameterGUID = bk.DesktopParameterGUID + end +GO + + +--------------------------------------------- + +-- dbo.procRESQLReportRegisteredAttributeRename +CREATE proc [dbo].[procRESQLReportRegisteredAttributeRename] + @attributeGUID uniqueidentifier, + @oldName nvarchar(100), + @newName nvarchar(100), + @DataViewGUID uniqueidentifier = null +as + --get all linked attributes + declare @refAttributes nvarchar(max) + select + @refAttributes = dbo.strAggr(cast(a.AttributeGUID as nvarchar(36)), ',', '') + from + viewScoreAttribute a + where + a.AttributeGUID = @attributeGUID + or a.ForeignKeyGUID = @attributeGUID + or a.InferredAttributeGUID = @attributeGUID + if (@refAttributes is null or @refAttributes = '') begin + return + end + + --include CAP attributes that are inferred through Project + declare @refAttributesCAP nvarchar(max) + select + @refAttributesCAP = dbo.strAggr(cast(a.AttributeGUID as nvarchar(36)), ',', '') + from + viewScoreAttribute a + where + a.ForeignKeyGUID in(select guid from dbo.ConvertCSGuidsToTable(@refAttributes, ',')) + or a.InferredAttributeGUID in(select guid from dbo.ConvertCSGuidsToTable(@refAttributes, ',')) + if (@refAttributesCAP is not null and @refAttributesCAP != '') begin + set @refAttributes = @refAttributes + ',' + @refAttributesCAP + end + + --include MR Department attributes if renaming a Department attribute + if (exists(select 1 from viewScoreAttribute where AttributeGUID = @attributeGUID and DimensionName = 'Department')) begin + declare @refAttributesMR nvarchar(max) + select + @refAttributesMR = dbo.strAggr(cast(mra.AttributeGUID as nvarchar(36)), ',', '') + from + viewScoreAttribute a + inner join viewScoreAttribute mra on mra.SQLColumnName = a.SQLColumnName + where + a.DimensionName = 'Department' + and mra.DimensionName = 'MR Department' + and ( + a.AttributeGUID = @attributeGUID + or a.ForeignKeyGUID = @attributeGUID + or a.InferredAttributeGUID = @attributeGUID + ) + if (@refAttributesMR is not null and @refAttributesMR != '') begin + set @refAttributes = @refAttributes + ',' + @refAttributesMR + end + end + + --update registered attribute alias + update ra set ra.ColumnAlias = @newName + from + RESQLReportRegisteredAttribute ra + inner join viewScoreAttribute a on a.AttributeGUID = ra.AttributeGUID + left JOIN RESQLReportRegisteredDimension d ON ra.RegisteredDimensionGUID = d.RegisteredDimensionGUID + + where + a.AttributeGUID in(select guid from dbo.ConvertCSGuidsToTable(@refAttributes, ',')) + and (ra.ColumnAlias = @oldName or @oldName like ra.ColumnAlias + ' Name') + and (d.DataViewGUID = @DataViewGUID or @DataViewGUID is NULL) + + --fix report dependencies + exec dbo.procRESQLReportRegisteredAttributeFixReferences '00000000-0000-0000-0000-000000000000', @refAttributes, @oldName, @newName, @DataViewGUID +GO + + +--------------------------------------------- + +-- dbo.procRefreshViews +CREATE procedure [dbo].[procRefreshViews] as + +DECLARE @tables NVARCHAR(4000) +DECLARE @view SYSNAME +DECLARE @sql NVARCHAR(500) + +SET @tables = NULL + + +SET @sql = N'EXEC sp_refreshView ' + +DECLARE viewCsr CURSOR READ_ONLY FAST_FORWARD FOR +SELECT + v.SchemaName + '.[' + v.ObjectName + ']' +FROM + dbo.viewSysViews v +WHERE + v.ObjectName NOT LIKE 'sys%' + and v.ObjectName not like 'viewS3%' + and v.ObjectName != 'viewPlaceholders' + and v.ObjectName != 'viewWFEntity' + and v.ObjectName not like 'viewWFReviewerAssignmentNoDelegates%' + and v.SchemaName != 'bak' +order by v.SchemaName, v.ObjectName + +--AND @tables IS NULL +--OR CHARINDEX(OBJECT_NAME(vtu.table_name), N',' + @tables + N',') > 0 + +OPEN viewCsr + +SELECT cast('' as varchar(255)) as viewName into #broken + +FETCH NEXT FROM viewCsr INTO @view +WHILE @@FETCH_STATUS = 0 +BEGIN + --PRINT @sql + @view + BEGIN TRY + EXEC(@sql + '''' + @view + '''') + END TRY + BEGIN CATCH + IF @@TRANCOUNT >= 1 ROLLBACK + INSERT INTO #broken (viewName) values (@view) + --print @@trancount + END CATCH + + FETCH NEXT FROM viewCsr INTO @view +END + +CLOSE viewCsr +DEALLOCATE viewCsr + +truncate table RefreshViewsLog; + +insert into RefreshViewsLog(BrokenViewName, BrokenViewDropSQL, BrokenViewSelectSQL) +select distinct + viewName as BrokenViewName, + 'drop view ' + viewname as BrokenViewDropSQL, + 'select top 1 * from ' + viewname as BrokenViewSelectSQL +from #broken where viewname <> '' + +drop table #broken +select * from RefreshViewsLog +GO + + +--------------------------------------------- + +-- dbo.procReinitializeApplicationModes +CREATE proc [dbo].[procReinitializeApplicationModes] +AS +BEGIN +truncate table ApplicationMode +set identity_insert ApplicationMode ON; +insert into ApplicationMode (ApplicationModeID,Name) VALUES (0, 'No Access'); +insert into ApplicationMode (ApplicationModeID,Name) VALUES (1, 'Simple Mode'); +insert into ApplicationMode (ApplicationModeID,Name) VALUES (2, 'Advanced Mode'); +insert into ApplicationMode (ApplicationModeID,Name) VALUES (3, 'Super User Mode'); +set identity_insert ApplicationMode OFF; +END +GO + + +--------------------------------------------- + +-- dbo.procRemoveController +CREATE PROCEDURE [dbo].[procRemoveController] +@ControllerID as uniqueidentifier + AS + +DELETE FROM dbo.ActiveControllers WHERE ControllerID=@ControllerID +GO + + +--------------------------------------------- + +-- dbo.procRemoveOrphanedMappingsAndDataByDimension +-- ================================================================================= +-- Author: Graydon Foreman +-- Create date: Oct 29, 2007 +-- Description: Removes mappings and data associated with deleted members +-- ================================================================================= +CREATE PROCEDURE [dbo].[procRemoveOrphanedMappingsAndDataByDimension] + @DIMENSIONGUID as uniqueidentifier, + @debug bit = 0 +AS +BEGIN + SET NOCOUNT ON; + + DECLARE @FillInDimensionGUID uniqueidentifier + SELECT @FillInDimensionGUID = FillInDimensionGUID FROM SecureList WHERE ListGUID = @DimensionGUID + + IF @FillInDimensionGUID = '00000000-0000-0000-0000-000000000000' BEGIN + SET @FillInDimensionGUID = @DimensionGUID + END + + + -------------------------- + -- Mapping Removal + -------------------------- + + DECLARE @MappingTable nvarchar(256) + DECLARE @mapsql nvarchar(4000) + + -- Find all dynamic mapping tables + DECLARE zzMapTable CURSOR LOCAL FAST_FORWARD + FOR SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME LIKE 'zzEMFModelTemplateMapping%' AND COLUMN_NAME = dbo.GetSQLColumnSafeGuid(@DIMENSIONGUID) + OPEN zzMapTable + FETCH NEXT FROM zzMapTable INTO @MappingTable + + -- Delete this member from mapping tables + WHILE @@FETCH_STATUS = 0 + BEGIN + IF @debug = 1 BEGIN + SET @mapsql = 'SELECT * FROM ' + END ELSE BEGIN + SET @mapsql = 'DELETE FROM ' + END + + SET @mapsql = @mapsql + @MappingTable + ' WHERE ' + dbo.GetSQLColumnSafeGuid(@DIMENSIONGUID) + ' != ''00000000-0000-0000-0000-000000000000'' AND ' + dbo.GetSQLColumnSafeGuid(@DIMENSIONGUID) + ' NOT IN(SELECT LISTMEMBERGUID FROM SecureListMember WHERE LISTGUID = ''' + cast(@DimensionGUID as nvarchar(36)) + ''')' + EXECUTE (@mapsql) + + FETCH NEXT FROM zzMapTable INTO @MappingTable + END + + CLOSE zzMapTable + DEALLOCATE zzMapTable + + -------------------------- + -- Data Removal + -------------------------- + + DECLARE @DataTable nvarchar(256) + DECLARE @datasql nvarchar(4000) + + -- Find all dynamic data tables + DECLARE zzDataTable CURSOR LOCAL FAST_FORWARD + FOR SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME LIKE 'zzEMFModelData%' AND COLUMN_NAME = dbo.GetSQLColumnSafeGuid(@DIMENSIONGUID) + OPEN zzDataTable + FETCH NEXT FROM zzDataTable INTO @DataTable + + -- Delete this member from data tables + WHILE @@FETCH_STATUS = 0 + BEGIN + IF @debug = 1 BEGIN + SET @datasql = 'SELECT * FROM ' + END ELSE BEGIN + SET @datasql = 'DELETE FROM ' + END + SET @datasql = @datasql + @DataTable + ' WHERE ' + dbo.GetSQLColumnSafeGuid(@DIMENSIONGUID) + ' != ''00000000-0000-0000-0000-000000000000'' AND ' + dbo.GetSQLColumnSafeGuid(@DIMENSIONGUID) + ' NOT IN(SELECT LISTMEMBERGUID FROM SecureListMember WHERE LISTGUID = ''' + cast(@FillInDimensionGUID as nvarchar(36)) + ''')' + EXECUTE (@datasql) + + FETCH NEXT FROM zzDataTable INTO @DataTable + END + + CLOSE zzDataTable + DEALLOCATE zzDataTable +END +GO + + +--------------------------------------------- + +-- dbo.procRemoveOrphanedZZTables +CREATE proc [dbo].[procRemoveOrphanedZZTables] as + +declare crsMDTables CURSOR FOR +select name from sysobjects where name like 'zzEMF%' order by name + +open crsMDTables; + +DECLARE @tableName as varchar(100) +DECLARE @mdcguid uniqueidentifier +DECLARE @guidstring varchar(36) +DECLARE @guidstart int +DECLARE @cnt int + +FETCH NEXT FROM crsMDTables into @tableName +WHILE (@@FETCH_STATUS = 0) BEGIN + + + SET @guidstart = charindex('_',@tableName) + SET @guidstring = replace(right(@tablename,len(@tablename) - @guidstart),'_','-') + SET @mdcguid = @guidstring + + SELECT @cnt = count(*) FROM EMFModelDataConfig where modeldataconfigguid = @mdcguid + + if @cnt = 0 begin + print 'drop table ' + @tableName + end + FETCH NEXT FROM crsMDTables into @tableName +END + +close crsMDTables +DEALLOCATE crsMDTables +GO + + +--------------------------------------------- + +-- dbo.procRemoveScoreDataTables +-- ============================================= +-- Author: +-- Create date: +-- Description: +-- ============================================= +CREATE PROCEDURE dbo.procRemoveScoreDataTables + @SchemaName varchar(64) +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + Declare @SQL varchar(8000) + Declare @tblname varchar(128) + + Declare crs_tblname Cursor LOCAL Forward_Only For SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @SchemaName + OPEN crs_tblname; + FETCH NEXT FROM crs_tblname into @tblname; + WHILE (@@FETCH_STATUS = 0) + BEGIN + Set @SQL = 'drop table ' + @schemaname + '.' + @tblname + print 'Dropping table ' + @schemaname + '.' + @tblname + exec (@sql) + exec (@sql) --drop again in case there are foreign keys that errored + FETCH NEXT FROM crs_tblname into @tblname; + END + CLOSE crs_tblname; + DEALLOCATE crs_tblname; + +END +GO + + +--------------------------------------------- + +-- dbo.procRemoveWorkerFromActiveController +CREATE PROCEDURE [dbo].[procRemoveWorkerFromActiveController] +@ControllerID as uniqueidentifier, +@WorkerID as uniqueidentifier + AS + +IF ((select count(*) from [dbo].[ActiveControllers] where ControllerID=@ControllerID AND WorkerID=@WorkerID) > 0) +BEGIN + DELETE FROM [dbo].[ActiveControllers] WHERE ControllerID=@ControllerID AND WorkerID=@WorkerID +END +GO + + +--------------------------------------------- + +-- dbo.procReportCopyClientReport +create proc [dbo].[procReportCopyClientReport] + @sourcedbname nvarchar(max), + @reportguid uniqueidentifier +as + set nocount on + exec procReportCopyClientReportXDB @sourcedbname, @reportguid +GO + + +--------------------------------------------- + +-- dbo.procReportCopyClientReportXDB +CREATE proc [dbo].[procReportCopyClientReportXDB] + @sourcedb nvarchar(100), + @reportGUID uniqueidentifier, + @toFolderGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000', + @debug bit = 0 +as + declare @reportGUIDStr nvarchar(36) = cast(@reportGUID as nvarchar(36)) + + if(@reportGUID = '00000000-0000-0000-0000-000000000000') begin + RAISERROR ('Report Name cannot be blank.', 18, 0) + return + end + + if (select COUNT(*) from REReport where ReportGUID=@reportGUID) = 1 begin + print 'Report ' + @reportGUIDStr + ' already exists.' + return + end + + declare @isExecuting bit + if(@debug = 1) begin + set @isExecuting = 0 + end else begin + set @isExecuting = 1 + end + + --put fields in root folder if no folder specified + declare @folderguid uniqueidentifier + if(@toFolderGUID = '00000000-0000-0000-0000-000000000000') begin + select @folderguid = RootFolderGUID from FolderSet where Type = 4 + end else begin + set @folderguid = @toFolderGUID + end + + declare @whereReport nvarchar(4000) = 'ReportGUID = ''' + @reportGUIDStr + '''' + declare @whereSection nvarchar(4000) = 'ClientReportSectionGUID in(select l.ClientReportSectionGUID from ' + @sourcedb + '.dbo.REClientReportSectionLink l where l.' + @whereReport + ')' + + --copy dataview + declare @whereDataView nvarchar(4000) = 'DataViewGUID in (select DataSourceGUID from ' + @sourcedb + '.dbo.REClientReportDataSourceLink s where s.reportguid = ''' + CAST(@reportGUID as nvarchar(36)) + ''')' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'DataView', @whereDataView, @isExecuting + + --setup default security for DataVie + insert into S3SimplePermission(PermissionGUID, LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) + select NEWID(), DataViewGUID, '00000000-0000-0000-0000-000000000001', cast(1 as bit), cast(1 as bit), cast(1 as bit) + from DataView where DataViewGUID not in(select sp.LootID from S3SimplePermission sp) + + + --copy registered dimensions + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'RESqlReportRegisteredDimension', @whereDataView, @isExecuting + + --copy registered attributes + declare @whereRegisteredAttribute nvarchar(4000) = 'RegisteredDimensionGUID in (select registereddimensionguid from ' + @sourcedb + '.dbo.resqlreportregistereddimension where ' + @whereDataView + ')' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'RESQLReportRegisteredAttribute', @whereRegisteredAttribute, @isExecuting + + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REReport', @whereReport, @isExecuting + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REClientReportSetup', @whereReport, @isExecuting + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REClientReportSection', @whereSection, @isExecuting + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REClientReportSectionLink', @whereReport, @isExecuting + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REClientReportConditionalFormat', @whereReport, @isExecuting + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REClientReportDataSourceLink', @whereReport, @isExecuting, 0, 0, 0 + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REClientReportParameter', @whereReport, @isExecuting + + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REClientReportCalculation', @whereSection, @isExecuting + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REClientReportSectionAttribute', @whereSection, @isExecuting + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REClientReportSectionMeasure', @whereSection, @isExecuting + + --for reports that now don't have a valid folder, move to specified folder + if(@isExecuting = 1) begin + update REReport set FolderGUID = @folderguid where FolderGUID not in(select f.FolderGUID from Folder f) + end else begin + print 'update REReport set FolderGUID = ''' + cast(@folderguid as nvarchar(36)) + ''' where FolderGUID not in(select f.FolderGUID from Folder f)' + end + + --setup default security + insert into S3SimplePermission(PermissionGUID, LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) + select NEWID(), ReportGUID, '00000000-0000-0000-0000-000000000001', cast(1 as bit), cast(1 as bit), cast(1 as bit) + from REReport where ReportGUID not in(select sp.LootID from S3SimplePermission sp) +GO + + +--------------------------------------------- + +-- dbo.procReportCopyCubeReport +-- ============================================= +-- Author: Mitch and Jacky +-- Create date: Now +-- Description: Copies Cube Reports from any database to this one +-- ============================================= +CREATE PROCEDURE [dbo].[procReportCopyCubeReport] + -- Add the parameters for the stored procedure here + @sourcedbname nvarchar(max), + @reportguid uniqueidentifier +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + +declare @sql as nvarchar(max) +set @sql = +' +declare @reportguid as uniqueidentifier +set @reportguid = ''' + cast(@reportGUID as nvarchar(128)) + ''' + +declare @reportSetupGUID as uniqueidentifier +set @reportsetupguid = (select top 1 Cubereportsetupguid from ' + @sourcedbname + '.[dbo].RECubeReportSetup where ReportGUID=@reportguid) + +if @reportguid <> dbo.ZeroGUID() and (select COUNT(*) from REReport where ReportGUID=@reportguid) = 0 begin + -- copy report + insert into REReport + select * from + ' + @sourcedbname + '.[dbo].REReport + where reportguid=@reportguid + + -- copy report setup + insert into RECubeReportSetup + select * from + ' + @sourcedbname + '.[dbo].RECubeReportSetup + where ReportGUID=@reportguid + + -- copy Dimension + insert into RECubeReportDimension + select * from + ' + @sourcedbname + '.[dbo].RECubeReportDimension + where CubeReportSetupGUID=@reportSetupGUID + + -- copy dimension Levels + insert into RECubeReportLevel + select * from + ' + @sourcedbname + '.[dbo].RECubeReportLevel + where CubeReportDimensionGUID in (Select cubereportdimensionguid from RECubeReportDimension where CubeReportSetupGUID = @reportSetupGUID) + + -- copy Measure + insert into RECubeReportMeasure + select * from + ' + @sourcedbname + '.[dbo].RECubeReportMeasure + where CubeReportSetupGUID=@reportSetupGUID + + -- copy Parameters + insert into RECubeReportParameter + select * from + ' + @sourcedbname + '.[dbo].RECubeReportParameter + where CubeReportSetupGUID=@reportSetupGUID + + -- set security + insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) values (@reportguid, ''00000000-0000-0000-0000-000000000001'', 1, 1, 1) +end' + +exec(@sql) + +END +GO + + +--------------------------------------------- + +-- dbo.procReportCopyDSCubeReport +Create proc [dbo].[procReportCopyDSCubeReport] + @sourcedb nvarchar(100), + @reportGUID uniqueidentifier, + @toFolderGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000', + @debug bit = 0 +as + declare @reportGUIDStr nvarchar(36) = cast(@reportGUID as nvarchar(36)) + + if(@reportGUID = '00000000-0000-0000-0000-000000000000') begin + RAISERROR ('Report Name cannot be blank.', 18, 0) + return + end + + if (select COUNT(*) from REReport where ReportGUID=@reportGUID) = 1 begin + print 'Report ' + @reportGUIDStr + ' already exists.' + return + end + + declare @isExecuting bit + if(@debug = 1) begin + set @isExecuting = 0 + end else begin + set @isExecuting = 1 + end + + --put fields in root folder if no folder specified + declare @folderguid uniqueidentifier + if(@toFolderGUID = '00000000-0000-0000-0000-000000000000') begin + select @folderguid = RootFolderGUID from FolderSet where Type = 4 + end else begin + set @folderguid = @toFolderGUID + end + + declare @whereReport nvarchar(4000) = 'ReportGUID = ''' + @reportGUIDStr + '''' + declare @whereSection nvarchar(4000) = 'DSCubeReportSectionGUID in(select l.DSCubeReportSectionGUID from ' + @sourcedb + '.dbo.REDSCubeReportSectionLink l where l.' + @whereReport + ')' + + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REReport', @whereReport, @isExecuting + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REDSCubeReportSetup', @whereReport, @isExecuting + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REDSCubeReportSection', @whereSection, @isExecuting + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REDSCubeReportSectionLink', @whereReport, @isExecuting + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REDSCubeReportConditionalFormat', @whereReport, @isExecuting + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REDSCubeReportDataSourceLink', @whereReport, @isExecuting, 0, 0, 0 + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REDSCubeReportParameter', @whereReport, @isExecuting + + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REDSCubeReportCalculation', @whereSection, @isExecuting + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REDSCubeReportSectionAttribute', @whereSection, @isExecuting + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REDSCubeReportSectionMeasure', @whereSection, @isExecuting + + --for reports that now don't have a valid folder, move to specified folder + if(@isExecuting = 1) begin + update REReport set FolderGUID = @folderguid where FolderGUID not in(select f.FolderGUID from Folder f) + end else begin + print 'update REReport set FolderGUID = ''' + cast(@folderguid as nvarchar(36)) + ''' where FolderGUID not in(select f.FolderGUID from Folder f)' + end + + --setup default security + insert into S3SimplePermission(PermissionGUID, LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) + select NEWID(), ReportGUID, '00000000-0000-0000-0000-000000000001', cast(1 as bit), cast(1 as bit), cast(1 as bit) + from REReport where ReportGUID not in(select sp.LootID from S3SimplePermission sp) +GO + + +--------------------------------------------- + +-- dbo.procReportCopyERReport +-- ============================================= +-- Author: Mitch and Jacky +-- Create date: Now +-- Description: Copies Cube Reports from any database to this one +-- ============================================= +CREATE PROCEDURE [dbo].[procReportCopyERReport] + -- Add the parameters for the stored procedure here + @sourcedbname nvarchar(max), + @reportguid uniqueidentifier +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + exec procReportCopyERXDB @sourcedbname, @reportguid + +END +GO + + +--------------------------------------------- + +-- dbo.procReportCopyERXDB +CREATE proc [dbo].[procReportCopyERXDB] + @sourcedb nvarchar(100), + @reportGUID uniqueidentifier, + @toFolderGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000', + @debug bit = 0 +as + declare @whereClause nvarchar(4000) + + if(@reportGUID = '00000000-0000-0000-0000-000000000000') begin + RAISERROR ('Report Name cannot be blank.', 18, 0) + return + end + + declare @isExecuting bit + if(@debug = 1) begin + set @isExecuting = 0 + end else begin + set @isExecuting = 1 + end + + --put fields in root folder if no folder specified + declare @folderguid uniqueidentifier + if(@toFolderGUID = '00000000-0000-0000-0000-000000000000') begin + select @folderguid = RootFolderGUID from FolderSet where Type = 4 + end else begin + set @folderguid = @toFolderGUID + end + + --copy report + set @whereClause = 'ReportGUID = ''' + cast(@reportGUID as nvarchar(36)) + '''' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REReport', @whereClause, @isExecuting + + -- Actual excel file + set @whereClause = 'fullpath = ''Reporting\VSTO Excel Reports\' + cast(@reportGUID as nvarchar(36)) + '.xls''' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'DataPathFile_Reporting', @whereClause, @isExecuting + + --copy the sheetconfigs + set @whereClause = 'ReportGUID = ''' + cast(@reportGUID as nvarchar(36)) + '''' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'resheetconfig', @whereClause, @isExecuting + + --copy the exconfigs from the sheet configs + set @whereClause = 'sheetguid in (select sheetguid from ' + @sourcedb + '.dbo.RESheetConfig where reportguid = ''' + cast(@reportGUID as nvarchar(36)) + ''')' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'reexconfig', @whereClause, @isExecuting + + --copy the exconfigfiltermembers from the sheet configs + set @whereClause = 'ExConfigGUID in (select ExConfigGUID from ' + @sourcedb + '.dbo.REExConfig ex inner join ' + @sourcedb + '.dbo.RESheetConfig sh on sh.SheetGUID = ex.SheetGUID where sh.reportguid = ''' + cast(@reportGUID as nvarchar(36)) + ''')' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REExConfigFilterMembers', @whereClause, @isExecuting, 0, 0, 0 + + if(@isExecuting = 1) begin + update REReport set FolderGUID = @folderguid where FolderGUID not in(select FolderGUID from Folder) + end else begin + print 'update REReport set FolderGUID = ''' + cast(@folderguid as nvarchar(36)) + ''' where FolderGUID not in(select FolderGUID from Folder)' + end + + --sql reports + declare @sql as nvarchar(max) + set @sql = ' + declare @reportguid as uniqueidentifier + set @reportguid = ''' + cast(@reportGUID as nvarchar(36)) + ''' + declare @csv nvarchar(max) + select @csv = coalesce(@csv + '','','''') + cast(sourceguid as nvarchar(128)) from ' + @sourcedb + '.[dbo].[redatasource] where reportguid = @reportguid and sourcetype = 6 + + declare @repsql as nvarchar(200) + set @repsql = ''procReportCopySQLXDB ''''' + @sourcedb + ''''', {guidq}, ''''00000000-0000-0000-0000-000000000000'''', ' + cast(@debug as nvarchar(1)) + ''' + + exec procRunForManyGUIDs @repsql, @csv, ' + cast(@isExecuting as nvarchar(1)) + print '' + exec(@sql) + print '' + + -- datasources + set @whereClause = 'ReportGUID = ''' + cast(@reportGUID as nvarchar(36)) + '''' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REDataSource', @whereClause, @isExecuting + + -- numbering parameter + set @whereClause = 'DatasourceGUID in (select datasourceguid from ' + @sourcedb + '.dbo.redatasource where reportguid = ''' + cast(@reportGUID as nvarchar(36)) + ''')' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'RENumberingParameter', @whereClause, @isExecuting + + -- query parameter + set @whereClause = 'DatasourceGUID in (select datasourceguid from ' + @sourcedb + '.dbo.redatasource where reportguid = ''' + cast(@reportGUID as nvarchar(36)) + ''')' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'requeryparameter', @whereClause, @isExecuting + + -- sorting parameter + set @whereClause = 'DatasourceGUID in (select datasourceguid from ' + @sourcedb + '.dbo.redatasource where reportguid = ''' + cast(@reportGUID as nvarchar(36)) + ''')' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'resortingparameter', @whereClause, @isExecuting + + -- grouping parameters + set @whereClause = 'ReportGUID = ''' + cast(@reportGUID as nvarchar(36)) + '''' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'regroupingparameter', @whereClause, @isExecuting + + -- grouping parameter links + set @whereClause = 'groupingparameterguid in (select groupingparameterguid from ' + @sourcedb + '.dbo.regroupingparameter where reportguid = ''' + cast(@reportGUID as nvarchar(36)) + ''')' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'regroupingparameterlink', @whereClause, @isExecuting + + --setup default security + insert into S3SimplePermission(PermissionGUID, LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) + select NEWID(), ReportGUID, '00000000-0000-0000-0000-000000000001', cast(1 as bit), cast(1 as bit), cast(1 as bit) + from REReport where ReportGUID not in(select LootID from S3SimplePermission) +GO + + +--------------------------------------------- + +-- dbo.procReportCopyExtractReport +CREATE proc [dbo].[procReportCopyExtractReport] + @sourcedbname nvarchar(max), + @reportguid uniqueidentifier +as + set nocount on + exec procReportCopyExtractReportXDB @sourcedbname, @reportguid +GO + + +--------------------------------------------- + +-- dbo.procReportCopyExtractReportXDB +CREATE proc [dbo].[procReportCopyExtractReportXDB] + @sourcedb nvarchar(100), + @reportGUID uniqueidentifier, + @toFolderGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000', + @debug bit = 0 +AS + declare @reportGUIDStr nvarchar(36) = cast(@reportGUID as nvarchar(36)) + + + if(@reportGUID = '00000000-0000-0000-0000-000000000000') begin + RAISERROR ('Report Name cannot be blank.', 18, 0) + return + end + + if (select COUNT(*) from REReport where ReportGUID=@reportGUID) = 1 begin + print 'Report ' + @reportGUIDStr + ' already exists.' + return + end + + exec procReportCopyClientReportXDB @sourcedb, @reportGUID, @toFolderGUID, @debug + + + declare @isExecuting bit + if(@debug = 1) begin + set @isExecuting = 0 + end else begin + set @isExecuting = 1 + end + + declare @whereReport nvarchar(4000) = 'ReportGUID = ''' + @reportGUIDStr + '''' + declare @whereSection nvarchar(4000) = 'ClientReportSetupGUID in (select l.ClientReportSetupGUID from ' + @sourcedb + '.dbo.REClientReportSetup l where l.' + @whereReport + ')' + + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REExtractReportOutputColumn', @whereSection, @isExecuting + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REExtractReportOutputFormat', @whereSection, @isExecuting +GO + + +--------------------------------------------- + +-- dbo.procReportCopyFileReport +CREATE proc [dbo].[procReportCopyFileReport] + @sourcedbname nvarchar(max), + @reportguid uniqueidentifier +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + exec procReportCopyFileXDB @sourcedbname, @reportguid +END +GO + + +--------------------------------------------- + +-- dbo.procReportCopyFileXDB +CREATE proc [dbo].[procReportCopyFileXDB] + @sourcedb nvarchar(100), + @reportGUID uniqueidentifier, + @toFolderGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000', + @debug bit = 0 +as + declare @whereClause nvarchar(4000) + + if(@reportGUID = '00000000-0000-0000-0000-000000000000') begin + RAISERROR ('Report GUID cannot be blank.', 18, 0) + return + end + + declare @isExecuting bit + if(@debug = 1) begin + set @isExecuting = 0 + end else begin + set @isExecuting = 1 + end + + --put fields in root folder if no folder specified + declare @folderguid uniqueidentifier + if(@toFolderGUID = '00000000-0000-0000-0000-000000000000') begin + select @folderguid = RootFolderGUID from FolderSet where Type = 4 + end else begin + set @folderguid = @toFolderGUID + end + + --copy report + set @whereClause = 'ReportGUID = ''' + cast(@reportGUID as nvarchar(36)) + '''' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REReport', @whereClause, @isExecuting + + --copy report setup + declare @whereReportSetup nvarchar(4000) = 'FileReportSetupGUID in (select rs.filereportsetupguid from ' + @sourcedb + '.dbo.REFileReportSetup rs where rs.reportguid = ''' + cast(@reportGUID as nvarchar(36)) + ''')' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REFileReportSetup', @whereReportSetup, @isExecuting + + --actual file + set @whereClause = 'FileName like ''%' + cast(@reportGUID as nvarchar(36)) + '%''' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'DataPathFile_Reporting', @whereClause, @isExecuting + + --for reports that now don't have a valid folder, move to specified folder + if(@isExecuting = 1) begin + update REReport set FolderGUID = @folderguid where FolderGUID not in(select sf.FolderGUID from Folder sf) + end else begin + print 'update REReport set FolderGUID = ''' + cast(@folderguid as nvarchar(36)) + ''' where FolderGUID not in(select sf.FolderGUID from Folder sf)' + end + + --setup default security + insert into S3SimplePermission(PermissionGUID, LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) + select NEWID(), ReportGUID, '00000000-0000-0000-0000-000000000001', cast(1 as bit), cast(1 as bit), cast(1 as bit) + from REReport where ReportGUID not in(select p.LootID from S3SimplePermission p) +GO + + +--------------------------------------------- + +-- dbo.procReportCopyMDReport +CREATE PROCEDURE [dbo].[procReportCopyMDReport] + -- Add the parameters for the stored procedure here + @sourcedbname nvarchar(max), + @reportguid uniqueidentifier +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + exec procReportCopyMDXDB @sourcedbname, @reportguid + +END +GO + + +--------------------------------------------- + +-- dbo.procReportCopyMDXDB +create PROCEDURE [dbo].[procReportCopyMDXDB] + @sourcedb nvarchar(100), + @reportGUID uniqueidentifier, + @toFolderGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000', + @debug bit = 0 +as + declare @reportGUIDStr nvarchar(36) = cast(@reportGUID as nvarchar(36)) + + if(@reportGUID = '00000000-0000-0000-0000-000000000000') begin + RAISERROR ('Report Name cannot be blank.', 18, 0) + return + end + + if (select COUNT(*) from REReport where ReportGUID=@reportGUID) = 1 begin + print 'Report ' + @reportGUIDStr + ' already exists.' + return + end + + declare @isExecuting bit + if(@debug = 1) begin + set @isExecuting = 0 + end else begin + set @isExecuting = 1 + end + + --put fields in root folder if no folder specified + declare @folderguid uniqueidentifier + if(@toFolderGUID = '00000000-0000-0000-0000-000000000000') begin + select @folderguid = RootFolderGUID from FolderSet where Type = 4 + end else begin + set @folderguid = @toFolderGUID + end + + --copy report + declare @whereReport nvarchar(4000) = 'ReportGUID = ''' + @reportGUIDStr + '''' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REReport', @whereReport, @isExecuting + + --copy report setup + declare @whereReportSetup nvarchar(4000) = 'ModelDataReportSetupGUID in (select rs.modeldatareportsetupguid from ' + @sourcedb + '.dbo.REModelDataReportSetup rs where rs.reportguid = ''' + cast(@reportGUID as nvarchar(36)) + ''')' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REModelDataReportSetup', @whereReportSetup, @isExecuting + + --setup default security + insert into S3SimplePermission(PermissionGUID, LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) + select NEWID(), ReportGUID, '00000000-0000-0000-0000-000000000001', cast(1 as bit), cast(1 as bit), cast(1 as bit) + from REReport where ReportGUID not in(select LootID from S3SimplePermission) +GO + + +--------------------------------------------- + +-- dbo.procReportCopyReport +CREATE PROCEDURE [dbo].[procReportCopyReport] + @ReportGUID as UniqueIdentifier, + @SourceDBName as nvarchar(max) +AS +BEGIN + SET NOCOUNT ON; + + declare @sql as nvarchar(max) + set @sql = ' + declare @reporttype nvarchar(max) + + select top 1 @reporttype = AssemblyQualifiedName from ' + @SourceDBName + '.[dbo].[rereport] where ReportGUID = ''' + Cast(@ReportGUID as Nvarchar(max)) + ''' + + if @reporttype like ''Strata.Reporting.ExcelReporter%'' + begin + exec [procReportCopyERReport] ''' + @SourceDBName + ''', ''' + Cast(@ReportGUID as Nvarchar(max)) + ''' + end + else if @reporttype like ''Strata.CubeReporter%'' + begin + exec [procReportCopyCubeReport] ''' + @SourceDBName + ''', ''' + Cast(@ReportGUID as Nvarchar(max)) + ''' + end + else if @reporttype like ''Strata.X.Biz.Reporting.SQLReport%'' + begin + exec [procReportCopySQLReport] ''' + @SourceDBName + ''', ''' + Cast(@ReportGUID as Nvarchar(max)) + ''' + end + else if @reporttype like ''Strata.X.Biz.Reporting.ModelDataReport%'' + begin + exec [procReportCopyMDReport] ''' + @SourceDBName + ''', ''' + Cast(@ReportGUID as Nvarchar(max)) + ''' + end + else if @reporttype like ''Strata.X.Biz.Reporting.FileReport%'' + begin + exec [procReportCopyFileReport] ''' + @SourceDBName + ''', ''' + Cast(@ReportGUID as Nvarchar(max)) + ''' + end + else if @reporttype like ''Strata.CS.Jazz.Biz.Reporting.ClientReport%'' + begin + exec [procReportCopyClientReport] ''' + @SourceDBName + ''', ''' + Cast(@ReportGUID as Nvarchar(max)) + ''' + end + else if @reporttype like ''Strata.CS.Jazz.Biz.Reporting.DSCubeReport%'' + begin + exec [procReportCopyDSCubeReport] ''' + @SourceDBName + ''', ''' + Cast(@ReportGUID as Nvarchar(max)) + ''' + end + ' + + exec (@sql) + end +GO + + +--------------------------------------------- + +-- dbo.procReportCopySQLReport +-- ============================================= +-- Author: Mitch and Jacky +-- Create date: Now +-- Description: Copies Cube Reports from any database to this one +-- ============================================= +CREATE PROCEDURE [dbo].[procReportCopySQLReport] + -- Add the parameters for the stored procedure here + @sourcedbname nvarchar(max), + @reportguid uniqueidentifier +AS +BEGIN + + exec procReportCopySQLXDB @sourcedbname, @reportguid + +END +GO + + +--------------------------------------------- + +-- dbo.procReportCopySQLXDB +--Author: jchau +--Branch: Earwig +--Forward + + +CREATE proc [dbo].[procReportCopySQLXDB] + @sourcedb nvarchar(100), + @reportGUID uniqueidentifier, + @toFolderGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000', + @debug bit = 0 +as + declare @reportGUIDStr nvarchar(36) = cast(@reportGUID as nvarchar(36)) + + if(@reportGUID = '00000000-0000-0000-0000-000000000000') begin + RAISERROR ('Report Name cannot be blank.', 18, 0) + return + end + + if (select COUNT(*) from REReport where ReportGUID=@reportGUID) = 1 begin + print 'Report ' + @reportGUIDStr + ' already exists.' + return + end + + declare @isExecuting bit + if(@debug = 1) begin + set @isExecuting = 0 + end else begin + set @isExecuting = 1 + end + + --put fields in root folder if no folder specified + declare @folderguid uniqueidentifier + if(@toFolderGUID = '00000000-0000-0000-0000-000000000000') begin + select @folderguid = RootFolderGUID from FolderSet where Type = 4 + end else begin + set @folderguid = @toFolderGUID + end + + --copy dataview + declare @whereDataView nvarchar(4000) = 'DataViewGUID in (select dataviewguid from ' + @sourcedb + '.dbo.resqlreportsetup s where s.reportguid = ''' + CAST(@reportGUID as nvarchar(36)) + ''')' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'DataView', @whereDataView, @isExecuting + + --copy registered dimensions + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'RESqlReportRegisteredDimension', @whereDataView, @isExecuting + + --copy registered attributes + declare @whereRegisteredAttribute nvarchar(4000) = 'RegisteredDimensionGUID in (select registereddimensionguid from ' + @sourcedb + '.dbo.resqlreportregistereddimension where ' + @whereDataView + ')' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'RESQLReportRegisteredAttribute', @whereRegisteredAttribute, @isExecuting + + --copy report + declare @whereReport nvarchar(4000) = 'ReportGUID = ''' + @reportGUIDStr + '''' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'REReport', @whereReport, @isExecuting + + --copy report setup + declare @whereReportSetup nvarchar(4000) = 'SQLReportSetupGUID in (select sqlreportsetupguid from ' + @sourcedb + '.dbo.resqlreportsetup where reportguid = ''' + @reportGUIDStr + ''')' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'RESQLReportSetup', @whereReportSetup, @isExecuting + + --copy display columns + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'RESQLReportDisplayColumn', @whereReportSetup, @isExecuting + + --copy filter columns + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'RESQLReportFilterColumn', @whereReportSetup, @isExecuting + + --copy pivot columns + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'RESQLReportPivotColumn', @whereReportSetup, @isExecuting + + --copy pivot column filters + declare @wherePivotColumnFilter nvarchar(4000) = 'PivotColumnGUID in (select PivotColumnGUID from ' + @sourcedb + '.dbo.RESQLReportPivotColumn where ' + @whereReportSetup + ')' + exec procMigrateScriptGetByTable 'dbo', @sourcedb, 'RESQLReportPivotColumnFilter', @wherePivotColumnFilter, @isExecuting + + --for reports that now don't have a valid folder, move to specified folder + if(@isExecuting = 1) begin + update REReport set FolderGUID = @folderguid where FolderGUID not in(select FolderGUID from Folder) + end else begin + print 'update REReport set FolderGUID = ''' + cast(@folderguid as nvarchar(36)) + ''' where FolderGUID not in(select FolderGUID from Folder)' + end + + --setup default security + insert into S3SimplePermission(PermissionGUID, LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) + select NEWID(), ReportGUID, '00000000-0000-0000-0000-000000000001', cast(1 as bit), cast(1 as bit), cast(1 as bit) + from REReport where ReportGUID not in(select LootID from S3SimplePermission) + + + +RETURN +GO + + +--------------------------------------------- + +-- dbo.procReportCopySystemReport +-- ============================================= +-- Author: Mitch and Jacky +-- Create date: Now +-- Description: Copies System Reports from any database to this one +-- ============================================= +CREATE PROCEDURE [dbo].[procReportCopySystemReport] + -- Add the parameters for the stored procedure here + @sourcedbname nvarchar(max), + @reportguid uniqueidentifier +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + declare @reportguidstring as nvarchar(128) + set @reportguidstring = cast(@reportGUID as nvarchar(128)) + declare @where as nvarchar(max) + set @where = 'REPORTGUID = ''' + @reportguidstring + '''' + exec procMigrateScriptGetByTable 'dbo', @sourcedbname, 'REReport', @where, 1, 0, 0 + + declare @reportfilename as varchar(64) + set @reportfilename = (select 'ExReports\' + REPLACE(Name,' ','') from rereport where reportguid = @reportguid) + + set @where = 'fullpath like (''' + @reportfilename + '%'')' + exec procMigrateScriptGetByTable 'dbo', @sourcedbname, 'datapathfile', @where, 1, 0, 0 + + set @where = 'reportguid = ''' + @reportguidstring + '''' + exec procMigrateScriptGetByTable 'dbo', @sourcedbname, 'REExReportSetup', @where, 1, 0, 0 + + insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) values (@reportguid, '00000000-0000-0000-0000-000000000001', 1, 1, 1) + + exec procReportValidateFolderGUID @reportguid + +END +GO + + +--------------------------------------------- + +-- dbo.procReportDebug +-- Fix Scripts + + +CREATE PROCEDURE [dbo].[procReportDebug] + @ReportGUID uniqueidentifier +AS +BEGIN + + select R.AuthorFullName, R.Name, R.ReportGUID, R.DateCreated, R.DateLastModified from [dbo].REReport R + where ReportGUID = @ReportGUID + + select Name, cast(parametervaluexml as xml) as [ParameterXML] from [dbo].regroupingparameter + where reportguid = @ReportGUID + + select ds.Name as DataSourceName, r.Name as SQLReportName, r.ReportGUID as SQLReportGUID, dv.SQLViewName from [dbo].REDataSource ds + inner join [dbo].REReport r on ds.SourceGUID=r.ReportGUID + inner join [dbo].RESQLReportSetup rs on rs.ReportGUID=r.ReportGUID + inner join [dbo].DataView dv on dv.DataViewGUID = rs.DataViewGUID + where ds.ReportGUID=@reportguid + order by ds.Name + +END +GO + + +--------------------------------------------- + +-- dbo.procReportDeleteERReport +CREATE PROCEDURE [dbo].[procReportDeleteERReport] + -- Add the parameters for the stored procedure here + @reportguid uniqueidentifier +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + -- Excel File + delete from datapathfile_reporting where fullpath = 'Reporting\VSTO Excel Reports\' + convert(varchar(max), @reportguid) + '.xls' + + -- ER Configs + delete from REExConfig where SheetGUID in (select SheetGUID from RESheetConfig where ReportGUID=@reportguid) + delete from RESheetConfig where ReportGUID=@reportguid + + -- Parameters + delete from RENumberingParameter where DataSourceGUID in (select DataSourceGUID from REDataSource where ReportGUID=@reportguid) + delete from REQueryParameter where DataSourceGUID in (select DataSourceGUID from REDataSource where ReportGUID=@reportguid) + delete from RESortingParameter where DataSourceGUID in (select DataSourceGUID from REDataSource where ReportGUID=@reportguid) + + delete from REGroupingParameterLink where GroupingParameterGUID in (select groupingparameterguid from regroupingparameter where reportguid = @reportguid) + delete from REGroupingParameter where ReportGUID=@reportguid + + -- Data Sources + delete from REDataSource where ReportGUID=@reportguid + + -- REReport + delete from REReport where ReportGUID=@reportguid + + -- Remove orphaned datasources + exec procReportRemoveOrphanedERDatasources + + print 'Success' + +END + +RETURN +GO + + +--------------------------------------------- + +-- dbo.procReportRemoveBatchReports +CREATE PROC dbo.[procReportRemoveBatchReports] + +as + +declare crsGUIDs_1 CURSOR FOR + select r.ReportGuid from REReport r where r.IsBatchReport = 1 + +open crsGUIDs_1; + +-- Delete ER reports +declare @reportGuid uniqueidentifier +FETCH NEXT FROM crsGUIDs_1 into @reportGuid +WHILE (@@FETCH_STATUS = 0) + BEGIN + exec dbo.procReportDeleteERReport @reportGuid + FETCH NEXT FROM crsGUIDs_1 into @reportGuid + END +close crsGUIDs_1; +DEALLOCATE crsGUIDs_1; +GO + + +--------------------------------------------- + +-- dbo.procReportRemoveCachedReportsByPlan +CREATE PROCEDURE [dbo].[procReportRemoveCachedReportsByPlan] + @planguid as uniqueidentifier +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + -- Remove any cached reports tied to that plan + delete from RECachedReport where Identifier like '%' + CAST(@planguid as varchar(36)) + '%' + +END + +RETURN +GO + + +--------------------------------------------- + +-- dbo.procReportRemoveCachedReportsByPlanType +CREATE PROCEDURE [dbo].[procReportRemoveCachedReportsByPlanType] + @plantypeguid as uniqueidentifier +AS +BEGIN + SET NOCOUNT ON + +--GET ALL THE PLANGUIDS from the plantype +declare crsGUIDs CURSOR FOR + select PLANGUID + from XPlan WHERE PlanTypeGUID = @plantypeguid + +open crsGUIDs; + +-- Loop through them and remove for each planguid with the +--Remove Cached reports by plan +declare @guid uniqueidentifier +FETCH NEXT FROM crsGUIDs into @guid +WHILE (@@FETCH_STATUS = 0) + BEGIN + exec procReportRemoveCachedReportsByPlan @guid + + FETCH NEXT FROM crsGUIDs into @guid + END +END + +Deallocate crsGUIDs +GO + + +--------------------------------------------- + +-- dbo.procReportRemoveCachedReportsByReport +-- ============================================= +-- Author: Jacky +-- Create date: Now +-- Description: Remove cached reports with missing reportguids and stale datapathfile for missing cached reports +-- ============================================= +CREATE PROCEDURE [dbo].[procReportRemoveCachedReportsByReport] + @reportguid as uniqueidentifier +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + -- Remove any cached reports tied to that plan + delete from RECachedReport where ReportGUID=@reportguid + + -- Remove any datapath file with missing cached reports + delete from DataPathFile where FullPath like 'Reporting\Cached Reports\%' and cast(LEFT(filename, 36) as uniqueidentifier) not in (select cachedreportguid from RECachedReport) + +END +GO + + +--------------------------------------------- + +-- dbo.procReportRemoveOrphanedCachedReports +-- ============================================= +-- Author: Jacky +-- Create date: Now +-- Description: Remove cached reports with missing reportguids and stale datapathfile for missing cached reports +-- ============================================= +CREATE PROCEDURE [dbo].[procReportRemoveOrphanedCachedReports] +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + -- Remove any cached reports with missing report guids + delete from RECachedReport where ReportGUID not in (select ReportGUID from REReport) + + -- rolling delete of datapath file + CREATE TABLE #LogDeleted (fileGUID uniqueidentifier); + + WHILE (1 = 1) + BEGIN + DELETE top (1000) DataPathFile_Reporting + OUTPUT deleted.FileGUID into #LogDeleted + FROM DataPathFile_Reporting TH + WHERE TH.FullPath like 'Reporting\Cached Reports\%' and cast(LEFT(TH.filename, 36) as uniqueidentifier) not in (select cachedreportguid from RECachedReport) + + if ((select COUNT(*) from #LogDeleted) = 0) + BEGIN + BREAK; + END + + delete from #LogDeleted; + + END + + DROP TABLE #LogDeleted; + +END + + +RETURN +GO + + +--------------------------------------------- + +-- dbo.procReportRemoveOrphanedDataPathFiles +CREATE PROC dbo.procReportRemoveOrphanedDataPathFiles + +AS + +delete from datapathfile_reporting +where FileName like '%.xls' and FileName not in (select CAST(reportguid as nvarchar(36)) + '.xls' from REReport) + +delete from datapathfile_reporting +where FileName like '%.pdf' and FileName not in (select CAST(reportguid as nvarchar(36)) + '.pdf' from REReport) + +exec dbo.procReportRemoveOrphanedCachedReports +GO + + +--------------------------------------------- + +-- dbo.procReportRemoveOrphanedERDatasources +-- ================================================================================= +-- Author: Jacky Chau +-- Create date: December 14, 2009 +-- Description: Removes orphaned ER datasource SQL reports +-- ================================================================================= +CREATE PROC [dbo].[procReportRemoveOrphanedERDatasources] AS + set nocount on; + + declare @count int + + select + distinct RE.ReportGUID as rguid + into #orphans + from + REReport RE + left join REDataSource DS on DS.SourceGUID=RE.ReportGUID + where + RE.IsDataSource=1 and DS.ReportGUID is null + + delete from REReport where ReportGUID in(select rguid from #orphans) + + select @count = count(*) from #orphans + + drop table #orphans + + print cast(@count as varchar(12)) + ' reports removed' +GO + + +--------------------------------------------- + +-- dbo.procReportValidateFolderGUID +-- ============================================= +-- Author: Mitch +-- checks to see if the reports folder guid exists if it does do nothing +-- if it doesnt place in the root reports folder '62D99FB1-12A2-4BE7-8D1D-92B60A181FA3' +-- ============================================= +CREATE PROCEDURE [dbo].[procReportValidateFolderGUID] + @reportguid AS uniqueidentifier +AS +BEGIN + + declare @folderguid as uniqueidentifier + select @folderguid = FolderGUID from REReport where ReportGUID = @reportguid + + if (select COUNT(*) from Folder where FolderGuid = @folderguid) = 0 + begin + update REReport SET FolderGUID = (SELECT TOP 1 RootFolderGUID from FolderSet where Type = 4) WHERE ReportGUID = @reportguid + end +END +GO + + +--------------------------------------------- + +-- dbo.procRollingDeleteNoTruncateOnTable +CREATE PROC [dbo].[procRollingDeleteNoTruncateOnTable] + @tableSchema nvarchar(128), + @tableName nvarchar(128), + @identityColumn nvarchar(128), --SHOULD Be RowID 95% of the time + @fromClause nvarchar(max), + @whereClause nvarchar(max), + @deleteRecordCount int, + @isPrintingStatement bit = 1, + @identityTableAlias nvarchar(128) = '' +AS +/**** The stored procedure is created based on dbo.procRollingDeleteOnTable ****/ +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-09-20 KF JAZZ-6746 JAZZ-36879 PR\\Metrics Definition: communication failure error when deleting many metrics with related pi.factmetric data +*************************************************************/ + + +IF (@fromClause is null or @fromClause = '') +BEGIN + raiserror( 'FROM CLAUSE IS EMPTY ', 0, 1) WITH NOWAIT; + RETURN +END + +IF (@deleteRecordCount <= 0) +BEGIN + raiserror( 'ERROR: Delete Record Count is Less than or equal to zero ', 0, 1) WITH NOWAIT; + RETURN +END + +-- GET THE IDENTITY TYPE +DECLARE @sqlType int, @maxlength int, @precision int, @scale int +select + @sqlType = c.system_type_id, @maxlength = c.max_length, @precision = c.precision, @scale = c.scale +from sys.columns c +inner join sys.objects o ON o.object_id = c.object_id +inner join sys.schemas s ON s.schema_id = o.schema_id +WHERE s.name = @tableSchema AND o.name = @tableName AND c.name = @identityColumn + +declare @sqlStringType nvarchar(128) +SET @sqlStringType = dbo.GetSQLFullyQualifiedType(@sqlType, @maxlength, @precision, @scale) + +DECLARE @idcol nvarchar(128) +SET @idcol = 'id' + REPLACE(CAST(newid() as NVARCHAR(120)), '-', '') --replace guid with no dashes and start the table name with a 'g' + +DECLARE @tempTable nvarchar(128) +SET @tempTable = '[data].RollingDelete' + @tableName + 'g' + REPLACE(CAST(newid() as NVARCHAR(120)), '-', '') --replace guid with no dashes and start the table name with a 'g' + +--CREATE THE SQL STATEMENT + +DECLARE @sql as NVARCHAR(MAX) +SET @sql = +' + +DECLARE @start BIGINT; +DECLARE @end BIGINT; +DECLARE @step BIGINT; +' + +IF @identityTableAlias <> '' +BEGIN + Set @identityTableAlias = @identityTableAlias + '.'; +END + + +SET @sql = @sql + ' + + CREATE TABLE ' + @tempTable + ' + ( + ' + @idcol + ' bigint identity(1,1), + ' + @identityColumn + ' ' + @sqlStringType + ' --lookup type + ) + WITH (DATA_COMPRESSION = PAGE) + + CREATE CLUSTERED INDEX IX_' + @idcol + '_ID_IDENTITY + ON '+ @tempTable + '(' + @idcol + ', ' + @identityColumn + '); + + + SELECT @start = MIN(' + @identityTableAlias + @identityColumn + '), @end = MAX(' + @identityTableAlias + @identityColumn + ') + FROM ' + @FROMCLAUSE + + IF NOT( @whereClause is null or @whereClause = '') + BEGIN + SET @sql = @sql + ' WHERE ' + @whereclause + END + +SET @sql = @sql + ' + + WHILE (@start <= @end) + BEGIN + SET @step = @start + 499999; + + If @step > @end + BEGIN + SET @step = @end; + END + INSERT INTO ' + @tempTable + ' + SELECT ' + @identityTableAlias + @identityColumn + ' + FROM ' + @FROMCLAUSE + + IF NOT( @whereClause is null or @whereClause = '') + BEGIN + SET @sql = @sql + ' WHERE ' + @whereclause + ' and ' + @identityTableAlias + @identityColumn + ' BETWEEN @start AND @step ' + END + ELSE + BEGIN + SET @sql = @sql + ' WHERE ' + @identityTableAlias + @identityColumn + ' BETWEEN @start AND @step ' + END + + SET @sql = @sql + ' + + SET @start = @start + 500000; + END +' + SET @sql = @sql + ' + + raiserror( ''Starting standard delete path on: ' + @tableSchema + '.' + @tableName + ''' , 0, 1) WITH NOWAIT; + DECLARE + @maxid AS BIGINT + ,@currentid BIGINT + ,@nowAsString varchar(30) + select @currentid = 1 + select @maxid=max(' + @idcol + ' ) FROM ' + @tempTable + ' + + while @currentid<=@maxid + begin + set @nowAsString = convert( varchar(30), getdate(), 121 ); + raiserror( ''@currentid %I64d at %s...'', 0, 1, @currentid, @nowAsString ) WITH NOWAIT ; + DELETE TN FROM ' + @tableSchema + '.' + @tableName + ' TN + INNER JOIN '+ @tempTable + ' DT ON DT.' + @identityColumn + ' = TN.' + @identityColumn + ' AND DT.' + @idcol + ' BETWEEN @currentid AND @currentid + ' + CAST(@deleteRecordCount AS NVARCHAR(10)) + ' + SET @currentid = @currentid + ' + CAST(@deleteRecordCount AS NVARCHAR(10)) + ' + 1 + END + raiserror( ''Finished delete on: ' + @tableSchema + '.' + @tableName + ''' , 0, 1) WITH NOWAIT; + + + DROP TABLE ' + @tempTable + ' +' + +IF @isPrintingStatement = 1 +BEGIN + PRINT (cast(@sql as ntext)); +END +ElSE +BEGIN + EXEC (@sql); +END +GO + + +--------------------------------------------- + +-- dbo.procRollingDeleteOnTable +CREATE PROC [dbo].[procRollingDeleteOnTable] + @tableSchema nvarchar(128), + @tableName nvarchar(128), + @identityColumn nvarchar(128), --SHOULD Be RowID 95% of the time + @fromClause nvarchar(max), + @whereClause nvarchar(max), + @deleteRecordCount int, + @truncateThreshold decimal(4, 3), + @isPrintingStatement bit = 1, + @identityTableAlias nvarchar(128) = '' +AS + +IF (@fromClause is null or @fromClause = '') +BEGIN + raiserror( 'FROM CLAUSE IS EMPTY ', 0, 1) WITH NOWAIT; + RETURN +END + +IF (@deleteRecordCount <= 0) +BEGIN + raiserror( 'ERROR: Delete Record Count is Less than or equal to zero ', 0, 1) WITH NOWAIT; + RETURN +END + +-- GET THE IDENTITY TYPE +DECLARE @sqlType int, @maxlength int, @precision int, @scale int +select + @sqlType = c.system_type_id, @maxlength = c.max_length, @precision = c.precision, @scale = c.scale +from sys.columns c +inner join sys.objects o ON o.object_id = c.object_id +inner join sys.schemas s ON s.schema_id = o.schema_id +WHERE s.name = @tableSchema AND o.name = @tableName AND c.name = @identityColumn + +declare @sqlStringType nvarchar(128) +SET @sqlStringType = dbo.GetSQLFullyQualifiedType(@sqlType, @maxlength, @precision, @scale) + +DECLARE @idcol nvarchar(128) +SET @idcol = 'id' + REPLACE(CAST(newid() as NVARCHAR(120)), '-', '') --replace guid with no dashes and start the table name with a 'g' + +DECLARE @tempTable nvarchar(128) +SET @tempTable = '[data].RollingDelete' + @tableName + 'g' + REPLACE(CAST(newid() as NVARCHAR(120)), '-', '') --replace guid with no dashes and start the table name with a 'g' + +--CREATE THE SQL STATEMENT + +DECLARE @sql as NVARCHAR(MAX) +SET @sql = +' + +DECLARE @start BIGINT; +DECLARE @end BIGINT; +DECLARE @step BIGINT; +DECLARE @filteredRecordCount FLOAT +SELECT @filteredRecordCount = COUNT(1) +FROM ' + @FROMCLAUSE + ' +' + +IF NOT( @whereClause is null or @whereClause = '') +BEGIN + SET @sql = @sql + 'WHERE ' + @whereclause +END + + +IF @identityTableAlias <> '' +BEGIN + Set @identityTableAlias = @identityTableAlias + '.'; +END + + +SET @sql = @sql + ' +DECLARE @unfilteredRecordCount bigint +SELECT @unfilteredRecordCount = row_count from sys.dm_db_partition_stats ps where ps.object_id=object_id(''' + @tableSchema + '.' + @tableName + ''') and ps.index_id < 2 +--Just TRUNCATE THE TABLE +IF (@filteredRecordCount = @unfilteredRecordCount) +BEGIN + raiserror( ''TRUNCATING TABLE ' + @tableName + ''', 0, 1) WITH NOWAIT; + TRUNCATE TABLE ' + @tableSchema + '.' + @tableName + ' +END +ELSE +BEGIN + CREATE TABLE ' + @tempTable + ' + ( + ' + @idcol + ' bigint identity(1,1), + ' + @identityColumn + ' ' + @sqlStringType + ' --lookup type + ) + WITH (DATA_COMPRESSION = PAGE) + + CREATE CLUSTERED INDEX IX_' + @idcol + '_ID_IDENTITY + ON '+ @tempTable + '(' + @idcol + ', ' + @identityColumn + '); + + +SELECT @start = MIN(' + @identityTableAlias + @identityColumn + '), @end = MAX(' + @identityTableAlias + @identityColumn + ') + FROM ' + @FROMCLAUSE + + IF NOT( @whereClause is null or @whereClause = '') + BEGIN + SET @sql = @sql + ' WHERE ' + @whereclause + END + +SET @sql = @sql + ' + +WHILE (@start <= @end) +BEGIN + SET @step = @start + 499999; + + If @step > @end + BEGIN + SET @step = @end; + END + INSERT INTO ' + @tempTable + ' + SELECT ' + @identityTableAlias + @identityColumn + ' + FROM ' + @FROMCLAUSE + + IF NOT( @whereClause is null or @whereClause = '') + BEGIN + SET @sql = @sql + ' WHERE ' + @whereclause + ' and ' + @identityTableAlias + @identityColumn + ' BETWEEN @start AND @step ' + END + ELSE + BEGIN + SET @sql = @sql + ' WHERE ' + @identityTableAlias + @identityColumn + ' BETWEEN @start AND @step ' + END + +SET @sql = @sql + ' + + SET @start = @start + 500000; +END +' + DECLARE @truncateTableName NVARCHAR(120); + SET @truncateTableName = 'tempRollingDelete' + @tableName + REPLACE(REPLACE(REPLACE(convert(varchar, getdate(), 113), '-', '_'), ':', '_'), ' ', '_'); + + SET @sql = @sql + ' + + --Just TRUNCATE THE TABLE + IF (@filteredRecordCount = @unfilteredRecordCount) + BEGIN + raiserror( ''TRUNCATING TABLE '+ @tableName + ''', 0, 1) WITH NOWAIT; + TRUNCATE TABLE ' + @tableSchema + '.' + @tableName + ' + END + ELSE + BEGIN + raiserror( ''Starting standard delete path on: ' + @tableSchema + '.' + @tableName + ''' , 0, 1) WITH NOWAIT; + DECLARE + @maxid AS BIGINT + ,@currentid BIGINT + ,@nowAsString varchar(30) + select @currentid = 1 + select @maxid=max(' + @idcol + ' ) FROM ' + @tempTable + ' + + while @currentid<=@maxid + begin + set @nowAsString = convert( varchar(30), getdate(), 121 ); + raiserror( ''@currentid %I64d at %s...'', 0, 1, @currentid, @nowAsString ) WITH NOWAIT ; + DELETE TN FROM ' + @tableSchema + '.' + @tableName + ' TN + INNER JOIN '+ @tempTable + ' DT ON DT.' + @identityColumn + ' = TN.' + @identityColumn + ' AND DT.' + @idcol + ' BETWEEN @currentid AND @currentid + ' + CAST(@deleteRecordCount AS NVARCHAR(10)) + ' + SET @currentid = @currentid + ' + CAST(@deleteRecordCount AS NVARCHAR(10)) + ' + 1 + END + raiserror( ''Finished delete on: ' + @tableSchema + '.' + @tableName + ''' , 0, 1) WITH NOWAIT; + END + + DROP TABLE ' + @tempTable + ' +END +' + +IF @isPrintingStatement = 1 +BEGIN + PRINT (cast(@sql as ntext)); +END +ElSE +BEGIN + EXEC (@sql); +END +GO + + +--------------------------------------------- + +-- dbo.procRollingUpdateOnTable +CREATE PROCEDURE dbo.procRollingUpdateOnTable + @tableSchema nvarchar(128), + @tableName nvarchar(128), + @identityColumn nvarchar(128), --SHOULD RowID 95% of the time + @updateStatement nvarchar(max), + @fromClause nvarchar(max), + @whereClause nvarchar(max), + @updateRecordCount int, + @isPrintingStatement bit = 0 +AS + +IF (@updateRecordCount <= 0) +BEGIN + raiserror( 'ERROR: Delete Record Count is Less than or equal to zero ', 0, 1) WITH NOWAIT; + RETURN +END + +-- GET THE IDENTITY TYPE +DECLARE @sqlType int, @maxlength int, @precision int, @scale int +select + @sqlType = c.system_type_id, @maxlength = c.max_length, @precision = c.precision, @scale = c.scale +from sys.columns c +inner join sys.objects o ON o.object_id = c.object_id +inner join sys.schemas s ON s.schema_id = o.schema_id +WHERE o.name = @tableName AND s.name = @tableSchema AND c.name = @identityColumn + +declare @sqlStringType nvarchar(128) +SET @sqlStringType = dbo.GetSQLFullyQualifiedType(@sqlType, @maxlength, @precision, @scale) +DECLARE @idcol nvarchar(128) +SET @idcol = 'id' + REPLACE(CAST(newid() as NVARCHAR(120)), '-', '') --replace guid with no dashes and start the table name with a 'g' + +--SET THE TEMP TABLE NAME +DECLARE @tempTable nvarchar(128) +SET @tempTable = '[data].' + [dbo].[GetSQLColumnSafeGuid](NEWID()) + +--CREATE THE SQL STATEMENT +DECLARE @sql as NVARCHAR(MAX) +SET @sql = +' +DECLARE @start BIGINT; +DECLARE @end BIGINT; +DECLARE @step BIGINT; + +CREATE TABLE ' + @tempTable + ' +( + ' + @idcol + ' bigint identity(1,1), + ' + @identityColumn + ' ' + @sqlStringType + ' --lookup type +) + WITH (DATA_COMPRESSION = PAGE) + + CREATE CLUSTERED INDEX IX_' + @idcol + '_ID_IDENTITY + ON '+ @tempTable + '(' + @idcol + ', ' + @identityColumn + '); + + +SELECT @start = MIN(' + @identityColumn + '), @end = MAX(' + @identityColumn + ') + FROM ' + @FROMCLAUSE + +IF NOT( @whereClause is null or @whereClause = '') +BEGIN + SET @sql = @sql + ' WHERE ' + @whereclause +END + +SET @sql = @sql + ' + +WHILE (@start <= @end) +BEGIN + SET @step = @start + 499999; + + If @step > @end + BEGIN + SET @step = @end; + END + INSERT INTO ' + @tempTable + ' + + + + SELECT ' + @identityColumn + ' + FROM ' + @FROMCLAUSE + + IF NOT( @whereClause is null or @whereClause = '') + BEGIN + SET @sql = @sql + ' WHERE ' + @whereclause + ' and ' + @identityColumn + ' BETWEEN @start AND @step ' + END + ELSE + BEGIN + SET @sql = @sql + ' WHERE ' + @identityColumn + ' BETWEEN @start AND @step ' + END + +SET @sql = @sql + ' + + SET @start = @start + 500000; +END +' +SET @sql = @sql + ' + +DECLARE @filteredRecordCount bigint +SELECT @filteredRecordCount = COUNT(1) FROM ' + @tempTable + ' +DECLARE @unfilteredRecordCount bigint +SELECT @unfilteredRecordCount = COUNT(1) FROM ' + @tableSchema + '.' + @tableName + ' (nolock) + +DECLARE + @maxid AS BIGINT + ,@currentid BIGINT + ,@nowAsString varchar(30) +select @currentid = 1 +select @maxid=max(' + @idcol + ') FROM ' + @tempTable + ' + +while @currentid<=@maxid +begin + set @nowAsString = convert( varchar(30), getdate(), 121 ); + raiserror( ''@currentid %I64d at %s...'', 0, 1, @currentid, @nowAsString ) WITH NOWAIT ; + UPDATE ' + @tableSchema + '.' + @tableName + ' SET ' + @updateStatement + ' FROM ' + @tableSchema + '.' + @tableName + ' TN + INNER JOIN '+ @tempTable + ' DT ON DT.' + @identityColumn + ' = TN.' + @identityColumn + ' AND DT.' + @idcol + ' BETWEEN @currentid AND @currentid + ' + CAST(@updateRecordCount AS NVARCHAR(10)) + ' + SET @currentid = @currentid + ' + CAST(@updateRecordCount AS NVARCHAR(10)) + ' + 1 +END + + +DROP TABLE ' + @tempTable + ' +' + +IF @isPrintingStatement = 1 +BEGIN + PRINT (@sql); +END +ElSE +BEGIN + EXEC (@sql); +END +GO + + +--------------------------------------------- + +-- dbo.procRollingUpdateOnTableWithEncounterID +CREATE PROC [dbo].[procRollingUpdateOnTableWithEncounterID] + @tableSchema nvarchar(128), + @tableName nvarchar(128), + @identityColumn nvarchar(128), --SHOULD RowID 95% of the time + @updateStatement nvarchar(max), + @fromClause nvarchar(max), + @whereClause nvarchar(max), + @tempTableAlias NVARCHAR(MAX), + @enounterIDTable NVARCHAR(MAX), + @updateRecordCount int, + @isPrintingStatement bit = 0, + @targetTableAlias NVARCHAR(100) = 'Target', + @encounterTableAlias NVARCHAR(100) = 'PE' +AS + +IF (@updateRecordCount <= 0) +BEGIN + raiserror( 'ERROR: Delete Record Count is Less than or equal to zero ', 0, 1) WITH NOWAIT; + RETURN +END + +-- GET THE IDENTITY TYPE +DECLARE @sqlType int, @maxlength int, @precision int, @scale int +select + @sqlType = c.system_type_id, @maxlength = c.max_length, @precision = c.precision, @scale = c.scale +from sys.columns c +inner join sys.objects o ON o.object_id = c.object_id +inner join sys.schemas s ON s.schema_id = o.schema_id +WHERE o.name = @tableName AND s.name = @tableSchema AND c.name = @identityColumn + +declare @sqlStringType nvarchar(128) +SET @sqlStringType = dbo.GetSQLFullyQualifiedType(@sqlType, @maxlength, @precision, @scale) +DECLARE @idcol nvarchar(128) +SET @idcol = 'id' + REPLACE(CAST(newid() as NVARCHAR(120)), '-', '') --replace guid with no dashes and start the table name with a 'g' + +--GET THE DATE +DECLARE @currDate datetime +SET @currDate = GETDATE() +DECLARE @currDateString nvarchar(60) +SET @currDateString = REPLACE(REPLACE(CAST(@currDate as NVARCHAR(50)), ' ', ''), ':', '') +DECLARE @tempTable nvarchar(128) +SET @tempTable = '[data].' + @currDateString + +--CREATE THE SQL STATEMENT +DECLARE @sql as NVARCHAR(MAX) +SET @sql = +' + +CREATE TABLE ' + @tempTable + ' +( + ' + @idcol + ' bigint identity(1,1), + ' + @identityColumn + ' ' + @sqlStringType + ', --lookup type + EncounterID BIGINT +) + WITH (DATA_COMPRESSION = PAGE) + + CREATE CLUSTERED INDEX IX_' + @idcol + '_ID_IDENTITY + ON '+ @tempTable + '(' + @idcol + ', ' + @identityColumn + '); + + +INSERT INTO ' + @tempTable + ' +SELECT '+@targetTableAlias+'.' + @identityColumn + ', ' + @encounterTableAlias + '.EncounterID +FROM ' + @FROMCLAUSE + ' +' +if NOT(@whereClause is null or @whereClause = '') +BEGIN + SET @sql = @sql + 'WHERE ' + @whereclause +END +SET @sql = @sql + ' + +DECLARE @filteredRecordCount bigint +SELECT @filteredRecordCount = COUNT(1) FROM ' + @tempTable + ' +DECLARE @unfilteredRecordCount bigint +SELECT @unfilteredRecordCount = COUNT(1) FROM ' + @tableSchema + '.' + @tableName + ' (nolock) + +DECLARE + @maxid AS BIGINT + ,@currentid BIGINT + ,@nowAsString varchar(30) +select @currentid = 1 +select @maxid=max(' + @idcol + ') FROM ' + @tempTable + ' + +while @currentid<=@maxid +begin + set @nowAsString = convert( varchar(30), getdate(), 121 ); + raiserror( ''@currentid %I64d at %s...'', 0, 1, @currentid, @nowAsString ) WITH NOWAIT ; + UPDATE ' + @tableSchema + '.' + @tableName + ' SET ' + @updateStatement + ' FROM ' + @tableSchema + '.' + @tableName + ' TN + INNER JOIN '+ @tempTable + ' '+ @tempTableAlias + ' ON '+ @tempTableAlias + '.' + @identityColumn + ' = TN.' + @identityColumn + ' AND '+ @tempTableAlias + '.' + @idcol + ' BETWEEN @currentid AND @currentid + ' + CAST(@updateRecordCount AS NVARCHAR(10)) + ' + SET @currentid = @currentid + ' + CAST(@updateRecordCount AS NVARCHAR(10)) + ' + 1 +END + + +DROP TABLE ' + @tempTable + ' +' + +IF @isPrintingStatement = 1 +BEGIN + PRINT (@sql); +END +ElSE +BEGIN + EXEC (@sql); +END +GO + + +--------------------------------------------- + +-- dbo.procRunForManyGUIDs +CREATE proc procRunForManyGUIDs + @sql varchar(max) + , @guids varchar(max) + , @isExecuting bit +as +--set @guids = '47413A00-1994-4606-8948-2BDFEDAC1FB9,63A2935D-EDB8-4DAF-863F-677831C6AC4E' +--set @sql = 'print {guidq}' +--set @isExecuting = 1 + +declare crsGUIDs CURSOR FOR + select guid + from dbo.CSVGuidsToTable(@guids) + +open crsGUIDs; + +declare @sqli varchar(max) +declare @guid uniqueidentifier +FETCH NEXT FROM crsGUIDs into @guid +WHILE (@@FETCH_STATUS = 0) + BEGIN + SET @sqli = replace( + replace(@sql,'{guidq}','''' + cast(@guid as varchar(36)) + '''') + ,'{guid}',cast(@guid as varchar(36))) + + if @isExecuting = 1 begin + exec(@sqli) + end else begin + print @sqli + end + + FETCH NEXT FROM crsGUIDs into @guid + END +close crsGUIDs; +DEALLOCATE crsGUIDs; +GO + + +--------------------------------------------- + +-- dbo.procRunForManyPlanGUIDsFromPlanType +CREATE proc [dbo].[procRunForManyPlanGUIDsFromPlanType] + @sql varchar(max) + , @plantypeguid uniqueidentifier + , @isExecuting bit +as + +declare crsGUIDs CURSOR FOR + select planguid + from xplan where plantypeguid = @plantypeguid + +open crsGUIDs; + +declare @sqli varchar(max) +declare @guid uniqueidentifier +FETCH NEXT FROM crsGUIDs into @guid +WHILE (@@FETCH_STATUS = 0) + BEGIN + SET @sqli = replace( + replace(@sql,'{guidq}','''' + cast(@guid as varchar(36)) + '''') + ,'{guid}',cast(@guid as varchar(36))) + + if @isExecuting = 1 begin + exec(@sqli) + end else begin + print @sqli + end + + FETCH NEXT FROM crsGUIDs into @guid + END +close crsGUIDs; +DEALLOCATE crsGUIDs; +GO + + +--------------------------------------------- + +-- dbo.procRunScheduledIntegrationTask +CREATE PROCEDURE [dbo].[procRunScheduledIntegrationTask] +( + @ConfigID uniqueidentifier, + @ConfigScheduleID uniqueidentifier, + @IsDebugOnly bit = 0 +) +AS +begin + +DECLARE @statusCode INT; + +DECLARE @contextXML VARCHAR(MAX) = '' + cast(@ConfigID as nvarchar(100)) + 'false' + cast(@ConfigScheduleID as nvarchar(100)) + ''; + + + if (@IsDebugOnly = 0) + begin + EXEC dbo.procCreateTask + @taskTypeName = 'Strata.CS.Jazz.Biz.DataIntegration.Tasks.ScheduledIntegrationTask, Strata.CS.Jazz.Biz', -- varchar(1000) + @contextXML = @contextXML, + @userName = 'Run Integration', + @statusCode = @statusCode OUTPUT, + @taskSource = 'procRunScheduledIntegrationTask' + END + +end +GO + + +--------------------------------------------- + +-- dbo.procS3AssignGroupToRole +CREATE procedure dbo.[procS3AssignGroupToRole] + @GroupName as nvarchar(128), + @RoleID smallint, + @LootGroupID nvarchar(128), + @HistoryItemGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000' +AS + + +DECLARE @userGUID AS UNIQUEIDENTIFIER + +DECLARE + userCursor CURSOR READ_ONLY +FOR + select + MU.UserGUID + from S3IdentityLink IL + inner join UserGroup G on G.UserGroupGUID = IL.GroupingGUID + left join UserGroup MG on MG.UserGroupGUID = IL.MemberGUID + left join UserProfile MU on MU.UserGUID = IL.MemberGUID + where G.Name = @GroupName and IL.Distance <> 0 + +OPEN + userCursor + +FETCH NEXT FROM userCursor +INTO @userGUID + +WHILE @@FETCH_STATUS = 0 +BEGIN + --PRINT @userGUID + + + DECLARE @script AS NVARCHAR(1024) + SET @script = '' + + + SET @script = 'EXEC procS3AssignIdentityToRole ''' + CAST(@userGUID AS NVARCHAR(36)) + ''', ' + CAST(@RoleID AS NVARCHAR(10)) + ', ''' + @LootGroupID + '''' + + PRINT @script + EXEC (@script) + + FETCH NEXT FROM userCursor + INTO @userGUID +END + +CLOSE userCursor +DEALLOCATE userCursor +GO + + +--------------------------------------------- + +-- dbo.procS3AssignIdentityToGroup +CREATE procedure [dbo].[procS3AssignIdentityToGroup] + @MEMBERGUID uniqueidentifier, + @GROUPINGGUID uniqueidentifier +as + +DECLARE @cnt int +declare @ucnt int +SELECT + @ucnt = COUNT(*) +FROM + USERPROFILE +WHERE + userguid = @MEMBERGUID + +declare @isuser bit +IF @ucnt = 0 + set @isuser = 0 +else + set @isuser = 1 + +select + @cnt = @ucnt + count(*) +from + usergroup +where + usergroupguid = @memberguid + and type = 0 + +IF @cnt = 0 BEGIN + PRINT cast(@MEMBERGUID as varchar(36)) + ' is invalid identity (not user or group)' + RETURN +END + +SELECT + @cnt = COUNT(*) +FROM + USERGROUP +WHERE + USERGROUP.USERGROUPGUID = @GROUPINGGUID + and USERGROUP.TYPE = 0 + +IF @cnt = 0 BEGIN + PRINT cast(@GROUPINGGUID as varchar(36)) + ' is invalid identity (group)' + RETURN +END + +SELECT + @cnt = count(*) +FROM + S3IdentityLink +WHERE + GroupingGUID = @GRoupingGUID + and MemberGUID = @memberguid + and distance = 1 + +IF @CNT > 0 begin + print 'member ' + cast(@memberguid as varchar(36)) + ' is already in group ' + cast(@groupingguid as varchar(36)) + return +end + +INSERT INTO + S3IdentityLink + (GroupingGUID, MemberGUID, Fullpath, Distance) +select + @GROUPINGGUID, @MEMBERGUID, '\' + cast(@GROUPINGGUID as varchar(36)) + '\' + cast(@MEMBERGUID as varchar(36)) + '\', 1 +GO + + +--------------------------------------------- + +-- dbo.procS3AssignIdentityToRole +CREATE procedure [dbo].[procS3AssignIdentityToRole] + @IdentityGUID uniqueidentifier, + @RoleID smallint, + @LootGroupID nvarchar(128), + @HistoryItemGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000' +as + +DECLARE @cnt int +declare @ucnt int +SELECT + @ucnt = COUNT(*) +FROM + USERPROFILE +WHERE + userguid = @IdentityGUID + +declare @isuser bit +IF @ucnt = 0 + set @isuser = 0 +else + set @isuser = 1 + +select + @cnt = @ucnt + count(*) +from + usergroup +where + usergroupguid = @IdentityGUID + and type = 0 + +IF @cnt = 0 BEGIN + PRINT cast(@IdentityGUID as varchar(36)) + ' is invalid identity (not user or group)' + RETURN +END + + +SELECT + @cnt = COUNT(*) +FROM + USERROLE +WHERE + USERROLE.RoleID = @RoleID + +IF @cnt = 0 BEGIN + PRINT cast(@RoleID as varchar(36)) + ' is invalid role' + RETURN +END + +SELECT + @cnt = COUNT(*) +FROM + S3LootGroup +WHERE + LootGroupID = @LootGroupID + +IF @cnt = 0 BEGIN + PRINT cast(@LootGroupID as varchar(36)) + ' is invalid loot' + RETURN +END + + + +SELECT + @CNT = COUNT(*) +from + S3RoleAssignment ra +where + ra.IdentityGUID = @IdentityGUID + and ra.LootGroupID = @LootGroupID + and ra.RoleID = @RoleID + +IF @cnt > 0 begin + PRINT cast(@IdentityGUID as varchar(36)) + ' already in role ' + cast(@RoleID as varchar(36)) + ' for loot ' + cast(@LootGroupID as nvarchar(128)) + return +end + +INSERT INTO + S3RoleAssignment ( IdentityGUID,LootGroupID, RoleID, HistoryItemGUID) +VALUES + (@IdentityGUID, @LootGroupID, @RoleID, @HistoryItemGUID) + + +-- +-- +--IF (@PARENTUSERGROUPGUID != @IDENTITYGUID) +--BEGIN +-- DECLARE @FULLPATH as varchar(800) +-- SET @FULLPATH = '\' + cast(@PARENTUSERGROUPGUID as varchar(36)) + '\' + cast(@IDENTITYGUID as varchar(36)) + '\' +-- +-- IF @USERGROUPCHILDTYPE = 0 +-- INSERT INTO S2IdentityLink (GroupingGUID, MemberGUID, Fullpath, Distance, GroupingIdentityGUID, GroupingLootGroupID, IsUser) VALUES(@PARENTUSERGROUPGUID, @IDENTITYGUID, @FULLPATH, 1, @GROUPINGIDENTITYGUID, @LootGroupID, 1) +-- +-- IF @USERGROUPCHILDTYPE = 1 +-- INSERT INTO S2IdentityLink (GroupingGUID, MemberGUID, Fullpath, Distance, GroupingIdentityGUID, GroupingLootGroupID, IsUser) VALUES(@PARENTUSERGROUPGUID, @IDENTITYGUID, @FULLPATH, 1, @GROUPINGIDENTITYGUID, @LootGroupID, 0) +--END +-- +-- +-- +GO + + +--------------------------------------------- + +-- dbo.procS3AssignIdentityToSpecialRole +CREATE procedure [dbo].[procS3AssignIdentityToSpecialRole] + @IdentityGUID uniqueidentifier, + @RoleTypeID int, + @LootGroupID nvarchar(128) +as + set nocount on + + INSERT INTO + S3RoleAssignment ( IdentityGUID,LootGroupID, RoleID) + SELECT + @IdentityGUID, + @LootGroupID, + r.RoleID + from + [dbo].[UserRole] r (readuncommitted) + where + r.Type = @RoleTypeID + and not exists(select 1 from [dbo].[S3RoleAssignment] ex (readuncommitted) where ex.IdentityGUID = @IdentityGUID and ex.LootGroupID = @LootGroupID and ex.RoleID = r.RoleID) +GO + + +--------------------------------------------- + +-- dbo.procS3AssignSecurityToButton +CREATE procedure [dbo].[procS3AssignSecurityToButton] + @lootId nvarchar(max), + @identityGuid uniqueidentifier +as + +declare @systemSectionRootLootId uniqueidentifier = '1F30ED4A-DFA5-4EA6-8457-20D23DB372C3' + +-- Get read access roleId +declare @readAccessRoleId int +select @readAccessRoleId = roleid from dbo.UserRole where Name = 'Access - Read Allow' + +-- Add to System Section Permission Set +declare @psetid int +select top 1 @psetid = PermissionSetID from [dbo].[S3PermissionSet] where Name in ('System Sections', 'SS - System') + +if (@psetid is null) +begin + print 'System Section permission set not found' + return +end + +if (@readAccessRoleId is null) +begin + print 'Access - Read Allow role not found' + return +end + +-- Recreate Loot to ensure it's in the right permission set +delete from S3Loot where LootID = @lootId and PermissionSetID != @psetid + +insert into [dbo].[S3Loot] (LootID, PermissionSetID) +select @lootId, @psetid where not exists (select 1 from [dbo].[S3Loot] inn where inn.LootID = @lootId) + +-- Set up relationship with root system section +insert into [dbo].[S3LootGroup] (LootID, LootGroupID) +select @lootId, @systemSectionRootLootId + where not exists (select 1 from [dbo].[S3LootGroup] inn where inn.LootID=@lootId and inn.LootGroupID=@systemSectionRootLootId) +union all +select @lootId, @lootId + where not exists (select 1 from [dbo].[S3LootGroup] inn where inn.LootID=@lootId and inn.LootGroupID=@lootId) + +-- Add role assignment +declare @roleAssignmentCount int +select @roleAssignmentCount = COUNT(*) from S3RoleAssignment where LootGroupID=@lootId and RoleId=@readAccessRoleId and IdentityGuid = @identityguid + +if (@roleAssignmentCount = 0) +begin + insert into dbo.S3RoleAssignment(IdentityGUID, RoleId, LootGroupID) + select @identityGuid,@readAccessRoleId, @lootId +end +GO + + +--------------------------------------------- + +-- dbo.procS3ClearAssignmentByLootGroupRole +-- ============================================= +-- Author: William Yuan +-- Create date: 8/28 +-- Description: Clears security based on entity and role combination. Security 2.0 +-- ============================================= + + + +CREATE PROCEDURE [dbo].[procS3ClearAssignmentByLootGroupRole] + -- Add the parameters for the stored procedure here + @LootGroupID nvarchar(128), + @RoleID smallint, + @HistoryItemGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000' +AS +BEGIN + SET NOCOUNT ON; + + + UPDATE + S3RoleAssignment + SET + IsMarkedDeleted = 1, + HistoryItemGUID = @HistoryItemGUID + WHERE + LootGroupID = @LootGroupID + AND RoleID = @RoleID + + +END +GO + + +--------------------------------------------- + +-- dbo.procS3ClearAssignmentByLootGroupRoleIdentity +-- ============================================= +-- Author: William Yuan +-- Create date: 8/28 +-- Description: Clears security based on entity and role combination. Security 2.0 +-- ============================================= + + + +CREATE PROCEDURE [dbo].[procS3ClearAssignmentByLootGroupRoleIdentity] + -- Add the parameters for the stored procedure here + @LootGroupID nvarchar(128), + @RoleID smallint, + @IDENTITYGUID uniqueidentifier, + @HistoryItemGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000' +AS +BEGIN + SET NOCOUNT ON; + + + UPDATE + S3RoleAssignment + SET + IsMarkedDeleted = 1, + HistoryItemGUID = @HistoryItemGUID + WHERE + LootGroupID = @LootGroupID + AND RoleID = @RoleID + AND IdentityGUID = @IdentityGUID + + +END +GO + + +--------------------------------------------- + +-- dbo.procS3ClearSecurityByLootGroup +CREATE PROCEDURE [dbo].[procS3ClearSecurityByLootGroup] + @LootGroupID nvarchar(128) +AS +BEGIN + SET NOCOUNT ON; + + DELETE + S3Loot + WHERE + LootId = @LootGroupID + + DELETE + S3RoleAssignment + WHERE + LootGroupID = @LootGroupID + + DELETE + S3LootGroup + WHERE + LootGroupID = @LootGroupID + +END +GO + + +--------------------------------------------- + +-- dbo.procS3CopyRoleAssignments +CREATE procedure [dbo].[procS3CopyRoleAssignments] + + @SRCLootGroupID nvarchar(128), + @DSTLootGroupID nvarchar(128) + +as + + +insert into S3RoleAssignment ( IdentityGUID, RoleID, LootGroupID) +select + IdentityGUID, RoleID, @DSTLootGroupID +from + S3RoleAssignment +where + LootGroupID = @SRCLootGroupID + and not exists ( + select 1 + from + S3RoleAssignment rax + where + rax.IdentityGUID = S3RoleAssignment.IdentityGUID + and rax.RoleID = S3RoleAssignment.RoleID + and rax.LootGroupID = @DSTLootGroupID + ) +GO + + +--------------------------------------------- + +-- dbo.procS3DebugLoot +CREATE proc [dbo].[procS3DebugLoot] + @lootID nvarchar(100), + @userNameOrGUID nvarchar(100) +as + --find the user + declare @userGUID uniqueidentifier + declare @userNameFull nvarchar(100) + declare @username nvarchar(100) + select @userGUID = UserGUID, @userNameFull = NameFull, @username = UserName from UserProfile where UserName = @userNameOrGUID or NameFull = @userNameOrGUID or CAST(UserGUID as nvarchar(36)) = @userNameOrGUID + if(@userGUID is null) begin + print 'User not found' + return + end + print 'User: ' + @userNameFull + ' (' + @username + ')' + print '' + + --verify the loot exists + if((select COUNT(*) from S3Loot where LootID = @lootID) = 0) begin + print 'Loot not found' + return + end + + --user access + declare @read nvarchar(10); declare @write nvarchar(10); declare @secure nvarchar(10); declare @delete nvarchar(10); declare @create nvarchar(10); + if((select COUNT(*) from viewS3ACL where LootID = @lootID and UserGUID = @userGUID) > 0) begin + select @read = case when coalesce(IsReadable, 0) = 1 then ' Read' else '' end, @write = case when coalesce(IsWritable, 0) = 1 then ' Write' else '' end, @secure = case when coalesce(IsSecurable, 0) = 1 then ' Secure' else '' end, @delete = case when coalesce(IsDeletable, 0) = 1 then ' Delete' else '' end, @create = case when coalesce(IsCreatable, 0) = 1 then ' Create' else '' end from viewS3ACL where LootID = @lootID and UserGUID = @userGUID + print 'User Access:' + @read + @write + @create + @delete + @secure + end else begin + print 'User Access: (none)' + end + + --role assignments + declare @roledetail nvarchar(max); declare @identname nvarchar(100); declare @roleassign nvarchar(100); declare @assigngroup nvarchar(100) + set @roledetail = '' + declare crsRoles cursor fast_forward for select distinct IdentityName, RoleName, LootGroupID from viewS3RoleAssignmentDetail where LootID = @lootID and UserGUID = @userGUID + open crsRoles + fetch next from crsRoles into @identname, @roleassign, @assigngroup + while(@@FETCH_STATUS = 0) begin + if(@roledetail != '') begin set @roledetail = @roledetail + ', ' end + set @roledetail = @roledetail + @identname + ' -> ' + @roleassign + ' (' + @assigngroup + ')' + fetch next from crsRoles into @identname, @roleassign, @assigngroup + end + close crsRoles + deallocate crsRoles + print 'User Assignments: ' + @roledetail + print '' + + --permission set + declare @pset nvarchar(100) + declare @psetid int + select @pset = PS.Name, @psetid = PS.PermissionSetID from S3Loot L inner join S3PermissionSet PS on PS.PermissionSetID = L.PermissionSetID where L.LootID = @lootID + print 'Permission Set: ' + @pset + + --parents + declare @parents nvarchar(max) + declare @parent nvarchar(100) + set @parents = '' + declare crsParents cursor fast_forward for select LootGroupID from S3LootGroup where LootID = @lootID and LootID != LootGroupID + open crsParents + fetch next from crsParents into @parent + while(@@FETCH_STATUS = 0) begin + if(@parents != '') begin set @parents = @parents + ', ' end + set @parents = @parents + @parent + fetch next from crsParents into @parent + end + close crsParents + deallocate crsParents + print 'Parents: ' + @parents + print '' + + --access detail + declare @readdetail nvarchar(max); declare @writedetail nvarchar(max); declare @securedetail nvarchar(max); declare @deletedetail nvarchar(max); declare @createdetail nvarchar(max); + set @readdetail = ''; set @writedetail = ''; set @securedetail = ''; set @deletedetail = ''; set @createdetail = ''; + declare @roleid int; declare @rolename nvarchar(100); declare @lootgroup nvarchar(100); declare @readallow int; declare @readdeny int; declare @writeallow int; declare @writedeny int; declare @secureallow int; declare @securedeny int; declare @deleteallow int; declare @deletedeny int; declare @createallow int; declare @createdeny int; + declare crsDetails cursor fast_forward for select distinct RoleID, RoleName, LootGroupID, ReadAllowPts, ReadDenyPts, WriteAllowPts, WriteDenyPts, SecureAllowPts, SecureDenyPts, DeleteAllowPts, DeleteDenyPts, CreateAllowPts, CreateDenyPts from viewS3ACLDetail where LootID = @lootID and UserGUID = @userGUID + open crsDetails + fetch next from crsDetails into @roleid, @rolename, @lootgroup, @readallow, @readdeny, @writeallow, @writedeny, @secureallow, @securedeny, @deleteallow, @deletedeny, @createallow, @createdeny + while(@@FETCH_STATUS = 0) begin + if(@readallow > 0) begin if(@readdetail != '') begin set @readdetail = @readdetail + ', ' end set @readdetail = @readdetail + @rolename + ' +' + cast(@readallow as nvarchar(16)) + ' (' + @lootgroup + ')' end + if(@readdeny > 0) begin if(@readdetail != '') begin set @readdetail = @readdetail + ', ' end set @readdetail = @readdetail + @rolename + ' -' + cast(@readdeny as nvarchar(16)) + ' (' + @lootgroup + ')' end + + if(@writeallow > 0) begin if(@writedetail != '') begin set @writedetail = @writedetail + ', ' end set @writedetail = @writedetail + @rolename + ' +' + cast(@writeallow as nvarchar(16)) + ' (' + @lootgroup + ')' end + if(@writedeny > 0) begin if(@writedetail != '') begin set @writedetail = @writedetail + ', ' end set @writedetail = @writedetail + @rolename + ' -' + cast(@writedeny as nvarchar(16)) + ' (' + @lootgroup + ')' end + + if(@createallow > 0) begin if(@createdetail != '') begin set @createdetail = @createdetail + ', ' end set @createdetail = @createdetail + @rolename + ' +' + cast(@createallow as nvarchar(16)) + ' (' + @lootgroup + ')' end + if(@createdeny > 0) begin if(@createdetail != '') begin set @createdetail = @createdetail + ', ' end set @createdetail = @createdetail + @rolename + ' -' + cast(@createdeny as nvarchar(16)) + ' (' + @lootgroup + ')' end + + if(@deleteallow > 0) begin if(@deletedetail != '') begin set @deletedetail = @deletedetail + ', ' end set @deletedetail = @deletedetail + @rolename + ' +' + cast(@deleteallow as nvarchar(16)) + ' (' + @lootgroup + ')' end + if(@deletedeny > 0) begin if(@deletedetail != '') begin set @deletedetail = @deletedetail + ', ' end set @deletedetail = @deletedetail + @rolename + ' -' + cast(@deletedeny as nvarchar(16)) + ' (' + @lootgroup + ')' end + + if(@secureallow > 0) begin if(@securedetail != '') begin set @securedetail = @securedetail + ', ' end set @securedetail = @securedetail + @rolename + ' +' + cast(@secureallow as nvarchar(16)) + ' (' + @lootgroup + ')' end + if(@securedeny > 0) begin if(@securedetail != '') begin set @securedetail = @securedetail + ', ' end set @securedetail = @securedetail + @rolename + ' -' + cast(@securedeny as nvarchar(16)) + ' (' + @lootgroup + ')' end + + fetch next from crsDetails into @roleid, @rolename, @lootgroup, @readallow, @readdeny, @writeallow, @writedeny, @secureallow, @securedeny, @deleteallow, @deletedeny, @createallow, @createdeny + end + close crsDetails + deallocate crsDetails + print 'Read Detail: ' + @readdetail + print 'Write Detail: ' + @writedetail + print 'Create Detail: ' + @createdetail + print 'Delete Detail: ' + @deletedetail + print 'Secure Detail: ' + @securedetail + print 'Detail Legend: +X => Allow Weight X, -Y => Deny Weight Y' + print '' + + --permission set detail + declare @psreadhowto nvarchar(max); declare @pswritehowto nvarchar(max); declare @pscreatehowto nvarchar(max); declare @psdeletehowto nvarchar(max); declare @pssecurehowto nvarchar(max); + set @psreadhowto = ''; set @pswritehowto = ''; set @pscreatehowto = ''; set @psdeletehowto = ''; set @pssecurehowto = ''; + declare @psrole nvarchar(100); declare @psread int; declare @pswrite int; declare @pssecure int; declare @pscreate int; declare @psdelete int; + declare crsPSDetail cursor fast_forward for select R.Name, P.ReadAllowPts, P.WriteAllowPts, P.SecureAllowPts, P.CreateAllowPts, P.DeleteAllowPts from S3Permission P inner join UserRole R on R.RoleID = P.RoleID where P.PermissionSetID = @psetid + open crsPSDetail + fetch next from crsPSDetail into @psrole, @psread, @pswrite, @pssecure, @pscreate, @psdelete + while(@@FETCH_STATUS = 0) begin + if(@psread > 0) begin if(@psreadhowto != '') begin set @psreadhowto = @psreadhowto + ', ' end set @psreadhowto = @psreadhowto + @psrole + ' (+' + CAST(@psread as nvarchar(16)) + ')' end + if(@pswrite > 0) begin if(@pswritehowto != '') begin set @pswritehowto = @pswritehowto + ', ' end set @pswritehowto = @pswritehowto + @psrole + ' (+' + CAST(@pswrite as nvarchar(16)) + ')' end + if(@pscreate > 0) begin if(@pscreatehowto != '') begin set @pscreatehowto = @pscreatehowto + ', ' end set @pscreatehowto = @pscreatehowto + @psrole + ' (+' + CAST(@pscreate as nvarchar(16)) + ')' end + if(@psdelete > 0) begin if(@psdeletehowto != '') begin set @psdeletehowto = @psdeletehowto + ', ' end set @psdeletehowto = @psdeletehowto + @psrole + ' (+' + CAST(@psdelete as nvarchar(16)) + ')' end + if(@pssecure > 0) begin if(@pssecurehowto != '') begin set @pssecurehowto = @pssecurehowto + ', ' end set @pssecurehowto = @pssecurehowto + @psrole + ' (+' + CAST(@pssecure as nvarchar(16)) + ')' end + + fetch next from crsPSDetail into @psrole, @psread, @pswrite, @pssecure, @pscreate, @psdelete + end + close crsPSDetail + deallocate crsPSDetail + print 'How To Get Read: ' + @psreadhowto + print 'How To Get Write: ' + @pswritehowto + print 'How To Get Create: ' + @pscreatehowto + print 'How To Get Delete: ' + @psdeletehowto + print 'How To Get Secure: ' + @pssecurehowto +GO + + +--------------------------------------------- + +-- dbo.procS3DebugMember +CREATE proc [dbo].[procS3DebugMember] + @dimensionNameOrGUID nvarchar(100), + @memberNameOrGUID nvarchar(100), + @userNameOrGUID nvarchar(100) +as + --find the dimension + declare @dimGUID uniqueidentifier + declare @dimName nvarchar(100) + declare @dimSQL nvarchar(100) + declare @issecure bit + select @dimGUID = DimensionGUID, @dimName = FriendlyName, @dimSQL = SQLSchemaName + '.' + SQLObjectName, @issecure = IsSecured from ScoreDimension where FriendlyName = @dimensionNameOrGUID or CAST(DimensionGUID as nvarchar(36)) = @dimensionNameOrGUID + if(@dimGUID is null) begin + print 'Dimension not found' + return + end + if(@issecure = 0) begin + print 'Dimension is not secured!' + return + end + print 'Dimension: ' + @dimName + + --get the loot prefix + declare @lootattr nvarchar(100) + declare @prefix nvarchar(50) + select @lootattr = A.SQLColumnName, @prefix = A.SecuredLootGroupPrefix from ScoreAttribute A + inner join ScoreDimensionGroup SG on SG.DimensionGroupGUID = A.DimensionGroupGUID + inner join ScoreDimension D on D.DimensionGUID = SG.DimensionGUID + where A.IsSecuredLootID = 1 and D.DimensionGUID = @dimGUID + if(@lootattr is null) begin + print 'Secure loot ID column not found' + return + end + if(@prefix != '') begin + set @prefix = @prefix + '|' + end + + declare @sql nvarchar(max) + set @sql = ' + --find the member loot + declare @lootID nvarchar(100) + declare @memberName nvarchar(450) + select @memberName = Name, @lootID = ''' + @prefix + ''' + cast(' + @lootattr + ' as nvarchar(100)) from ' + @dimSQL + ' where Name = ''' + @memberNameOrGUID + ''' or cast(MemberGUID as nvarchar(36)) = ''' + @memberNameOrGUID + ''' + if(@lootID is null) begin + print ''Member not found'' + return + end + print ''Member: '' + @memberName + '' ('' + @lootID + '')'' + + exec procS3DebugLoot @lootID, ''' + @userNameOrGUID + ''' + ' + exec(@sql) +GO + + +--------------------------------------------- + +-- dbo.procS3DebugPlan +CREATE proc [dbo].[procS3DebugPlan] + @planNameOrGUID nvarchar(450), + @userNameOrGUID nvarchar(100) +as + --check for dupes + if((select COUNT(*) from XPlan where Name = @planNameOrGUID) > 1) begin + print 'Plan name is not unique. Please provide the PlanGUID.' + return + end + + --find the plan loot + declare @lootID nvarchar(100) + declare @planName nvarchar(450) + select @planName = Name, @lootID = CachedLootID from XPlan where Name = @planNameOrGUID or CAST(PlanGUID as nvarchar(36)) = @planNameOrGUID + if(@lootID is null) begin + print 'Plan not found' + return + end + print 'Plan: ' + @planName + ' (' + @lootID + ')' + + exec procS3DebugLoot @lootID, @userNameOrGUID +GO + + +--------------------------------------------- + +-- dbo.procS3DeleteOrphans +CREATE proc [dbo].[procS3DeleteOrphans] + @lootGroupPrefix nvarchar(100) = null, + @isExecuting bit = 0 +as + IF @lootGroupPrefix='' + BEGIN + RAISERROR(N'LootGroupPrefix couldn''t be empty string', 1, 16) + RETURN + END + + CREATE TABLE #s3orphan( + [LootID] [nvarchar](128) NOT NULL, + [PermissionSetID] [smallint] NOT NULL) + + IF @lootGroupPrefix IS NULL OR @lootGroupPrefix = 'P' + BEGIN + insert into #s3orphan select LootID, PermissionSetID from S3Loot where LootGroupPrefix = 'P' and LootID not in(select CachedLootID from [dbo].[XPlan]) + END + + declare @sql nvarchar(max) + select @sql = dbo.straggr('insert into #s3orphan select LootID, PermissionSetID from S3Loot where LootGroupPrefix = ''' + SecuredLootGroupPrefix + ''' and LootID not in(select ''' + SecuredLootGroupPrefix + '|'' + cast(' + SQLColumnName + ' as nvarchar(16)) from ' + DimensionSQLObjectExpression + ')', ' + ', '') from viewScoreAttribute where IsSecuredLootID = 1 and ((SecuredLootGroupPrefix not in('', 'P') AND @lootGroupPrefix IS NULL) OR (SecuredLootGroupPrefix = @lootGroupPrefix AND @lootGroupPrefix IS NOT NULL)) + exec(@sql) + + if (@isExecuting = 1) begin + delete x + from S3LootGroup x + inner join #s3orphan y on x.LootID = y.LootID + + delete x + from S3RoleAssignment x + inner join #s3orphan y on x.LootGroupID = y.LootID + + delete x + from S3Loot x + inner join #s3orphan y on x.LootID = y.LootID + end + + select * from #s3orphan + drop table #s3orphan +GO + + +--------------------------------------------- + +-- dbo.procS3EnsureSimplePermissionDefaultForStrata +create proc procS3EnsureSimplePermissionDefaultForStrata +as + insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 1, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 1) + insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 3, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 3) + insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 4, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 4) + insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 6, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 6) + insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 8, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 8) + insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 9, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 9) + insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 10, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 10) + insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 11, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 11) + insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 12, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 12) + insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 13, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 13) + insert into S3SimplePermissionDefault (EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) select 14, UserGroupGUID, CAST(1 as bit), CAST(1 as bit), CAST(1 as bit) from UserGroup where Name = 'Strata Administrator' and UserGroupGUID not in(select IdentityGUID from S3SimplePermissionDefault where EntityType = 14) +GO + + +--------------------------------------------- + +-- dbo.procS3GetUserGUIDsAssignedToPRGroups +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2019-12-05 HV TK-80875 PR | Emails +*************************************************************/ +CREATE PROCEDURE dbo.procS3GetUserGUIDsAssignedToPRGroups + @PRCategory nvarchar(64) +AS + +SELECT DISTINCT MemberGUID FROM [dbo].[S3IdentityLink] il +INNER JOIN [dbo].[UserGroup] ug on ug.UserGroupGUID = il.GroupingGUID +WHERE ug.Category = @PRCategory +GO + + +--------------------------------------------- + +-- dbo.procS3GetUsersAssignedToMRDepartments +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2019-11-21 KF B-24581 PR | Emails - Responsibility / User Picker - Daily +** 2 2022-05-24 HV JAZZ-38243 PR Roles PR notifications emails +*************************************************************/ +CREATE PROCEDURE dbo.procS3GetUsersAssignedToMRDepartments + @RoleIDs nvarchar(max) +AS + +SELECT * FROM +( + -- Department level + SELECT S.RoleID, S.UserGUID, U.NameFull as UserNameFull FROM viewS3RoleAssignmentDetail S + INNER JOIN dbo.UserProfile U ON U.UserGUID = S.UserGUID + WHERE + U.IsDisabled = 0 + AND S.IsDirectAssignment = 1 + AND S.LootID Like 'MRDept|%' + AND S.RoleID IN (select val from ConvertCSValuesToTable(@RoleIDs, ',')) + + UNION + + -- Rollup levels + SELECT S.RoleID, S.UserGUID, U.NameFull as UserNameFull FROM viewS3RoleAssignmentDetail S + INNER JOIN dbo.UserProfile U ON U.UserGUID = S.UserGUID + WHERE + U.IsDisabled = 0 + AND S.LootID Like 'MRDept|%' + AND (S.LootGroupID Like 'SYS%' OR S.LootGroupID Like 'ENT%' OR S.LootGroupID Like 'DeptRollup%') + AND S.RoleID IN (select val from ConvertCSValuesToTable(@RoleIDs, ',')) +) as R +INNER JOIN +( + SELECT DISTINCT MemberGUID FROM [dbo].[S3IdentityLink] il + INNER JOIN [dbo].[UserGroup] ug on ug.UserGroupGUID = il.GroupingGUID + WHERE ug.Category = 'PR' +) as G +on R.UserGUID = G.MemberGUID +GO + + +--------------------------------------------- + +-- dbo.procS3GetUsersAssignedToMRDepartmentsForPR +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-06-02 KF JAZZ-38243 PR Roles PR notifications emails +*************************************************************/ +CREATE PROCEDURE [dbo].[procS3GetUsersAssignedToMRDepartmentsForPR] + @RoleIDs nvarchar(max) +AS + +IF OBJECT_ID('tempdb..#roleIDs') IS NOT NULL DROP TABLE #roleIDs; +CREATE TABLE #roleIDs (RoleID INT Primary Key) + +INSERT INTO #roleIDs (RoleID) +SELECT val FROM ConvertCSValuesToTable(@RoleIDs, ',') + +SELECT R.* FROM +( + -- Department level + SELECT S.RoleID, S.UserGUID, U.NameFull as UserNameFull FROM viewS3RoleAssignmentDetail S + INNER JOIN dbo.UserProfile U ON U.UserGUID = S.UserGUID + INNER JOIN #roleIDs R ON R.RoleID = S.RoleID + WHERE + U.IsDisabled = 0 + AND S.IsDirectAssignment = 1 + AND S.LootID Like 'MRDept|%' + + UNION + + -- Rollup levels + SELECT S.RoleID, S.UserGUID, U.NameFull as UserNameFull FROM viewS3RoleAssignmentDetail S + INNER JOIN dbo.UserProfile U ON U.UserGUID = S.UserGUID + INNER JOIN #roleIDs R ON R.RoleID = S.RoleID + WHERE + U.IsDisabled = 0 + AND S.LootID Like 'MRDept|%' + AND (S.LootGroupID Like 'SYS%' OR S.LootGroupID Like 'ENT%' OR S.LootGroupID Like 'DeptRollup%') +) as R +INNER JOIN UserRole UR ON UR.RoleID = R.RoleID +INNER JOIN +( + SELECT DISTINCT MemberGUID FROM [dbo].[S3IdentityLink] il + INNER JOIN [dbo].[UserGroup] ug on ug.UserGroupGUID = il.GroupingGUID + WHERE ug.Category = 'PR' +) as PG ON PG.MemberGUID = R.UserGUID +LEFT JOIN +( + SELECT DISTINCT MemberGUID FROM [dbo].[S3IdentityLink] il + INNER JOIN [dbo].[UserGroup] ug on ug.UserGroupGUID = il.GroupingGUID + WHERE ug.Category = 'MR' +) as MG ON MG.MemberGUID = R.UserGUID +WHERE UR.Category = 'PR' OR (UR.Category = 'MR' AND MG.MemberGUID IS NOT NULL) + +IF OBJECT_ID('tempdb..#roleIDs') IS NOT NULL DROP TABLE #roleIDs; +GO + + +--------------------------------------------- + +-- dbo.procS3IdentityLinkAddMissing +CREATE proc [dbo].[procS3IdentityLinkAddMissing] as + +INSERT INTO S3IdentityLink (GroupingGUID, MemberGUID, FullPath, Distance) +SELECT + Userguid, + UserGuid, + '\' + cast(userguid as varchar(36)) + '\', + 0 +FROM + UserProfile +WHERE + not exists (select 1 from S3IdentityLink il where il.GroupingGUID = UserGUID and il.MemberGUID = UserGUID) + +--distance 1 to everyone group +INSERT INTO S3IdentityLink (GroupingGUID, MemberGUID, FullPath, Distance) +SELECT + '00000000-0000-0000-0000-000000000001', + ins.UserGuid, + '\00000000-0000-0000-0000-000000000001\' + cast(ins.userguid as varchar(36)) + '\', + 1 +FROM + userprofile INS +WHERE + not exists (select 1 from S3IdentityLink il where il.GroupingGUID = '00000000-0000-0000-0000-000000000001' and il.MemberGUID = UserGUID) + +INSERT INTO S3IdentityLink (GroupingGUID, MemberGUID, FullPath, Distance) +SELECT + ins.UserGroupGUID, + ins.UserGroupGUID, + '\' + cast(ins.UserGroupGUID as varchar(36)) + '\', + 0 +FROM + UserGroup ins +WHERE + not exists ( + select 1 + from S3IdentityLink ilx + where ilx.MemberGUID = ins.UserGroupGUID and ilx.GroupingGUID = ins.UserGroupGUID + ) +GO + + +--------------------------------------------- + +-- dbo.procS3IdentityLinkFixFullpaths +CREATE proc procS3IdentityLinkFixFullpaths + @isDebugOnly bit = 0 +as + declare @fullpath nvarchar(400) + declare @fixed nvarchar(400) + declare @pos int + declare crsLinks cursor read_only fast_forward for select Fullpath from S3IdentityLink (readuncommitted) where Fullpath not like '\%' or ((len(Fullpath) - 1) / 37.0) != floor((len(Fullpath) - 1) / 37.0) + open crsLinks + fetch next from crsLinks into @fullpath + while(@@FETCH_STATUS = 0) begin + set @fixed = @fullpath + set @pos = 1 + while (@pos < LEN(@fixed)) begin + if (SUBSTRING(@fixed, @pos, 1) != '\') begin + if (@pos = 1) begin + set @fixed = '\' + @fixed + end else begin + set @fixed = SUBSTRING(@fixed, 1, @pos - 1) + '\' + SUBSTRING(@fixed, @pos, len(@fixed) - @pos + 1) + end + end + set @pos = @pos + 37 + end + + print @fullpath + ' -> ' + @fixed + if (@isDebugOnly = 0) begin + if((select count(*) from [dbo].[S3IdentityLink] where Fullpath = @fixed) > 0) begin + delete from [dbo].[S3IdentityLink] where Fullpath = @fullpath + end else begin + update [dbo].[S3IdentityLink] set Fullpath = @fixed where Fullpath = @fullpath + end + end + + fetch next from crsLinks into @fullpath + end + close crsLinks + deallocate crsLinks + + update il set il.Fullpath = il.Fullpath + '\' from S3IdentityLink il where il.Fullpath not like '%\' and not exists(select 1 from S3IdentityLink ex where ex.Fullpath = il.Fullpath + '\') +GO + + +--------------------------------------------- + +-- dbo.procS3LootGroupUpdateSystemSection +CREATE proc [dbo].[procS3LootGroupUpdateSystemSection] as + + +declare @psid int +select @psid = permissionsetid from S3PermissionSet where MetaForUpgrade = '1F30ED4A-DFA5-4EA6-8457-20D23DB372C3' + +if @psid is null begin + print 'This depends on the existence of a s3permissionset with metaforupgrade = 1F30ED4A-DFA5-4EA6-8457-20D23DB372C3' + return +end + +insert into S3Loot ( LootID, PermissionSetID) +select + ss.SYSTEMSECTIONGUID,@psid +from + SystemSection ss +where + not exists ( + select 1 + from + S3Loot l + where + l.LootID = CAST(ss.systemsectionguid as varchar(36)) + ) +--****************** +--****************** +--Create S3LootGroup for secured systemsections +--****************** +--****************** + +create table #S3LootGroup( LootID nvarchar(128), LootGroupID nvarchar(128)) + + +insert into #S3LootGroup( LootID,LootGroupID) +select CAST(ss1 as varchar(36)), CAST(ss1 as varchar(36)) from viewSystemSectionFlat +union all +select CAST(ss1 as varchar(36)), CAST(ss2 as varchar(36)) from viewSystemSectionFlat where ss2 is not null +union all +select CAST(ss1 as varchar(36)), CAST(ss3 as varchar(36)) from viewSystemSectionFlat where ss3 is not null +union all +select CAST(ss1 as varchar(36)), CAST(ss4 as varchar(36)) from viewSystemSectionFlat where ss4 is not null +union all +select CAST(ss1 as varchar(36)), CAST(ss5 as varchar(36)) from viewSystemSectionFlat where ss5 is not null +union all +select CAST(ss1 as varchar(36)), CAST(ss6 as varchar(36)) from viewSystemSectionFlat where ss6 is not null + + + +--delete invalid ones +DELETE lg FROM S3LootGroup lg WHERE + lg.LootID IN (select nlg.LootID from #S3LootGroup nlg) + and NOT EXISTS ( + SELECT 1 + FROM #S3LootGroup nlg + WHERE lg.lootid = nlg.LootID and lg.lootgroupid = nlg.lootgroupid + ) + +--add valid ones +INSERT INTO S3LootGroup (LootID, LootGroupID) +SELECT + lootid, lootgroupid +FROM + #S3LootGroup nlg +WHERE + NOT EXISTS ( + SELECT 1 + FROM S3LootGroup lg + WHERE lg.lootid = nlg.LootID and lg.lootgroupid = nlg.lootgroupid + ) + +drop table #s3lootgroup +GO + + +--------------------------------------------- + +-- dbo.procS3MenuSecurityAfterSave +create proc dbo.procS3MenuSecurityAfterSave +as + --replace user management system center security with latest menu item security + delete from S3simplepermission where lootid in('68E8430F-F3BC-4286-B73D-6CDEA144F7BC', 'BA346C79-C2D0-4CA2-8090-CC71719A1B5B'); + insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) + select s.sectionguid, p.identityguid, p.readvalue, p.writevalue, p.securevalue from S3simplepermission p cross join SystemCenterSection s where p.lootid = 'd62a6536-9bfb-4bde-b945-eda88ab0e19e' and s.sectionguid in('68E8430F-F3BC-4286-B73D-6CDEA144F7BC', 'BA346C79-C2D0-4CA2-8090-CC71719A1B5B'); +GO + + +--------------------------------------------- + +-- dbo.procS3PlanTypeLootExpressionSet +CREATE proc procS3PlanTypeLootExpressionSet + @planTypeGUID uniqueidentifier, + @lootIDSQLExpression nvarchar(100), + @defaultPermissionSetID smallint, + @isUpdatingExistingPlans bit = 0 +as + if((select COUNT(*) from PlanType where PlanTypeGUID = @planTypeGUID) = 0) begin + print 'Plan type not found' + return + end + + update PlanType set LootIDSQLExpression = @lootIDSQLExpression where PlanTypeGUID = @planTypeGUID + + if(@isUpdatingExistingPlans = 1) begin + select CachedLootID into ##oldloot from XPlan where PlanTypeGUID = @planTypeGUID + + declare @updateSQL nvarchar(4000) + set @updateSQL = @updateSQL + 'update XPlan set CachedLootID = ' + @lootIDSQLExpression + ' where PlanTypeGUID = ''' + cast(@planTypeGUID as nvarchar(36)) + ''';' + + delete from S3Loot where LootID in(select CachedLootID from ##oldloot) and LootID not in(select CachedLootID from XPlan) + + insert into S3Loot(LootID, PermissionSetID) select CachedLootID, @defaultPermissionSetID from XPlan where PlanTypeGUID = @planTypeGUID and CachedLootID not in(select LootID from S3Loot) + + drop table ##oldloot + end +GO + + +--------------------------------------------- + +-- dbo.procS3RebuildLootView +--/****** Object: StoredProcedure [dbo].[procScoreRunForManyStructures] Script Date: 10/16/2009 15:50:12 ******/ +--SET ANSI_NULLS ON +--GO + +--SET QUOTED_IDENTIFIER ON +--GO + +CREATE proc [dbo].[procS3RebuildLootView] +as + + +declare @dropSQL nvarchar(max) +set @dropsql = 'if dbo.ViewExists(''data'',''viewS3LootPossible'') = 1 begin + drop view data.viewS3LootPossible +end' +exec(@dropsql) + +declare @viewSQL varchar(max) + +--secured system sections +set @viewSQL = ' +create view data.viewS3LootPossible as +select lootid, ''SecureListMember'' as LootType, Name from securelistmember where listguid in (select listguid from securelist where issecured = 1) +' + +--secured dimensions +declare crsScoreDim CURSOR FOR + select ' +select + ''' + case when len(sa.securedlootgroupprefix) > 0 then sa.securedlootgroupprefix + '|' else '' end + + ''' + cast(' + sa.sqlcolumnname + ' as varchar(max)), + ''DimensionMember'', + cast(' + sadlk.sqlcolumnname + ' as varchar(max)) +from + [' + sd.sqlschemaname + '].[' + sd.sqlobjectname + ']' + from + ScoreDimension SD + inner join viewScoreAttribute SA on sd.dimensionguid = sa.dimensionguid + inner join viewScoreAttribute SADLK on sd.dimensionguid = sadlk.dimensionguid and sd.defaultlookupkeyguid = sadlk.attributeguid + where + sd.issecured = 1 + and sa.issecuredlootid = 1 + and + ( + dbo.viewexists(sd.sqlschemaname,sd.sqlobjectname) = 1 + or dbo.tableexists(sd.sqlschemaname,sd.sqlobjectname) = 1 + ) + +open crsScoreDim; + +declare @dimsql varchar(max) + +FETCH NEXT FROM crsScoreDim into @dimsql +WHILE (@@FETCH_STATUS = 0) BEGIN + set @viewSQL = @viewSQL + ' + UNION ALL + ' + @dimsql + FETCH NEXT FROM crsScoreDim into @dimsql +end + +close crsscoredim +deallocate crsscoredim + +exec(@viewsql) +GO + + +--------------------------------------------- + +-- dbo.procS3RebuildStatistics +create proc dbo.procS3RebuildStatistics +as + if (not exists(select 1 from fw.SystemSetting where Name = 'ACL Statistics Auto-Rebuild' and Value = '1')) begin + return + end + + UPDATE STATISTICS [dbo].[S3IdentityLink] with fullscan; + UPDATE STATISTICS [dbo].[S3Loot] with fullscan ; + UPDATE STATISTICS [dbo].[S3LootGroup] with fullscan ; + UPDATE STATISTICS [dbo].[S3LootRefreshLog] with fullscan ; + UPDATE STATISTICS [dbo].[S3Permission] with fullscan ; + UPDATE STATISTICS [dbo].[S3PermissionSet] with fullscan ; + UPDATE STATISTICS [dbo].[S3RoleAssignment] with fullscan ; + UPDATE STATISTICS [dbo].[S3SimplePermission] with fullscan ; + UPDATE STATISTICS [dbo].[S3SimplePermissionDefault] with fullscan ; + UPDATE STATISTICS [dbo].[S3UserACLRegenRequest] with fullscan ; +GO + + +--------------------------------------------- + +-- dbo.procS3RemoveIdentityFromRole +CREATE procedure [dbo].[procS3RemoveIdentityFromRole] + @IdentityGUID uniqueidentifier, + @RoleID smallint, + @LootGroupID nvarchar(128), + @HistoryItemGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000' +as + +DECLARE @cnt int +declare @ucnt int +SELECT + @ucnt = COUNT(*) +FROM + USERPROFILE +WHERE + userguid = @IdentityGUID + +declare @isuser bit +IF @ucnt = 0 + set @isuser = 0 +else + set @isuser = 1 + +select + @cnt = @ucnt + count(*) +from + usergroup +where + usergroupguid = @IdentityGUID + and type = 0 + +IF @cnt = 0 BEGIN + PRINT cast(@IdentityGUID as varchar(36)) + ' is invalid identity (not user or group)' + RETURN +END + +SELECT + @cnt = COUNT(*) +FROM + USERROLE +WHERE + USERROLE.RoleID = @RoleID + +IF @cnt = 0 BEGIN + PRINT cast(@RoleID as varchar(36)) + ' is invalid role' + RETURN +END + +SELECT + @cnt = COUNT(*) +FROM + S3LootGroup +WHERE + LootGroupID = @LootGroupID + +IF @cnt = 0 BEGIN + PRINT cast(@LootGroupID as varchar(36)) + ' is invalid loot' + RETURN +END + +SELECT + @CNT = COUNT(*) +from + S3RoleAssignment ra +where + ra.IdentityGUID = @IdentityGUID + and ra.LootGroupID = @LootGroupID + and ra.RoleID = @RoleID + +IF @cnt = 0 begin + PRINT cast(@IdentityGUID as varchar(36)) + ' is not in role ' + cast(@RoleID as varchar(36)) + ' for loot ' + cast(@LootGroupID as nvarchar(128)) + return +end + +DELETE FROM + S3RoleAssignment +WHERE + IdentityGUID = @IdentityGUID + and RoleID = @RoleID + and LootGroupID = @LootGroupID +GO + + +--------------------------------------------- + +-- dbo.procS3SetSimplePermissionDefault +CREATE PROCEDURE [dbo].[procS3SetSimplePermissionDefault] + @EntityType int, + @IdentityGUID uniqueidentifier, + @ReadValue bit = 1, + @WriteValue bit = 0, + @SecureValue bit = 0 +AS +BEGIN + SET NOCOUNT ON; + + -- EntityTypes + -- 1: Folder + -- 3: Report + -- 4: PlanType + -- 6: MessagingTopic + -- 8: FormField + -- 9: FormSection + -- 10: Pool + -- 11: ListInsertionPoint + -- 12: CustomAction + -- 13: UserGroup + -- 14: Workflow + + insert into S3SimplePermissionDefault(EntityType, IdentityGUID, ReadValue, WriteValue, SecureValue) + values(@EntityType, @IdentityGUID, @ReadValue, @WriteValue, @SecureValue) + +END +GO + + +--------------------------------------------- + +-- dbo.procS3SyncUserDirectRoleAssignments +CREATE proc [procS3SyncUserDirectRoleAssignments] ( + @SourceUserName nvarchar(64), + @TargetUserName nvarchar(64) + ) +AS +BEGIN + + declare @TargetUserGUID uniqueidentifier; + declare @SourceUserGUID uniqueidentifier; + select @TargetUserGUID = userguid from UserProfile where UserName = @TargetUserName; + select @SourceUserGUID = userguid from UserProfile where UserName = @SourceUserName; + + + if (@TargetUserGUID is null) + begin + print 'Couldn''t find target user: ' + @TargetUserName + return; + end + if (@SourceUserGUID is null) + begin + print 'Couldn''t find target user: ' + @SourceUserName + return; + end + + insert into S3RoleAssignment + (IdentityGUID, RoleID, LootGroupID) + select + @TargetUserGUID, + D.RoleID, + D.LootGroupID + from viewS3RoleAssignmentDirect D + left join viewS3RoleAssignmentDirect C + on C.LootGroupID = D.LootGroupID + and C.RoleID = D.RoleID + and C.IdentityGUID = @TargetUserGUID + where D.IdentityGUID = (select userguid from UserProfile where UserName = @SourceUserName) + and D.RoleID <> (select RoleID from UserRole where Name = 'Author') + and C.IdentityGUID is null; + + +END +GO + + +--------------------------------------------- + +-- dbo.procS3UserAdminEnsureAccess +CREATE proc dbo.procS3UserAdminEnsureAccess + @userGUID uniqueidentifier +as + declare @isAdmin bit + select @isAdmin = ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0) from dbo.UserProfile UP + left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = 'GEN - User Administrator') + where UP.UserGUID = @userGUID + + if (@isAdmin = 1) begin + --add user setup menu access if not already present from group assignments + insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) + select 'd62a6536-9bfb-4bde-b945-eda88ab0e19e', u.UserGUID, 1, 1, 0 + from dbo.UserProfile u + where u.UserGUID = @userGUID + and not exists(select 1 from viewS3AclSimple acl where acl.UserGUID = u.UserGUID and acl.LootID = 'd62a6536-9bfb-4bde-b945-eda88ab0e19e') + end else begin + --remove user setup menu access if directly assigned + delete from S3SimplePermission where LootID = 'd62a6536-9bfb-4bde-b945-eda88ab0e19e' and IdentityGUID = @userGUID; + end + + --sync security changes to system center + exec dbo.procS3MenuSecurityAfterSave +GO + + +--------------------------------------------- + +-- dbo.procSMCGetDatabaseGUID +CREATE PROCEDURE [dbo].[procSMCGetDatabaseGUID]( + @ReturnVal uniqueidentifier OUTPUT +) +AS +BEGIN + + declare @SMC_SERVER nvarchar(128); + declare @SMC_DB nvarchar(128); + declare @DatabaseGUID uniqueidentifier; + + select @SMC_SERVER = Setting from DBSetting where Name = 'SMC_PRIMARY_SERVER' + select @SMC_DB = setting from DBSetting where Name = 'SMC_PRIMARY_DATABASE' + if (@SMC_SERVER is null) + begin + print 'SMC_PRIMARY_SERVER NOT SET.'; + return; + end + if (@SMC_DB is null) + begin + print 'SMC_PRIMARY_DATABASE NOT SET.'; + return; + end + + declare @sql nvarchar(max); + set @sql = ' + select + @DBGUID_OUT = DatabaseGUID + from [' + @SMC_SERVER + '].[' + @SMC_DB + '].[dbo].[viewDatabaseInfo] + where (LinkedServerName = ''' + @@SERVERNAME + ''' OR LinkedServerName = ''' + @@SERVERNAME + '.sdt.local'' OR LinkedServerName = ''' + replace(@@SERVERNAME, '\', '.sdt.local\') + ''' OR replace(LinkedServerName, ''.sdt.local\'', ''\'') = ''' + @@SERVERNAME + ''') AND PhysicalName = ''' + DB_NAME() + ''' + ' + + EXECUTE sp_executesql + @sql, + N'@DBGUID_OUT uniqueidentifier OUTPUT', + @DBGUID_OUT=@DatabaseGUID OUTPUT; + + SELECT @ReturnVal = @DatabaseGUID; +END +GO + + +--------------------------------------------- + +-- dbo.procSR2EnsureBoundYearAlign +create proc dbo.procSR2EnsureBoundYearAlign +as + --make sure year on bounds data matches year on corresponding model data, in case model year structure changed + + declare @datatable nvarchar(100) + declare @boundstable nvarchar(100) + declare @sql nvarchar(max) + + declare crsTables cursor fast_forward for + select s.name + '.' + replace(t.name, 'Bounds', '') as DataTableName, s.name + '.' + t.name as BoundsTableName from sys.tables t inner join sys.schemas s on s.schema_id = t.schema_id where t.name like '%bounds' + + open crsTables + fetch next from crsTables into @datatable, @boundstable + + while(@@fetch_status = 0) begin + set @sql = ' + update b set b.FiscalYearID = f.FiscalYearID + from + ' + @boundstable + ' b + inner join ' + @datatable + ' f on f.RowID = b.RowID + where + b.FiscalYearID != f.FiscalYearID + ' + BEGIN TRY + exec(@sql) + END TRY + BEGIN CATCH + --LOL + END CATCH + + fetch next from crsTables into @datatable, @boundstable + end + + close crsTables + deallocate crsTables +GO + + +--------------------------------------------- + +-- dbo.procSR2EnsurePlanFillinCache +create proc dbo.procSR2EnsurePlanFillinCache + @planGUIDList nvarchar(max) = '' +as + if (@planguidList = '') begin + update fi set fi.FillinMemberName = p.Name + from + [dbo].[ScoreFillin] fi + inner join [dbo].[XPlan] p with (readuncommitted) on p.PlanGUID = fi.FillinMemberGUID + where + fi.FillinMemberName != p.Name + + exec [dbo].[procScoreFillinTableRefreshAll] + end else begin + if (exists(select 1 from [dbo].[ScoreFillin] fi with (readuncommitted) inner join [dbo].[XPlan] p with (readuncommitted) on p.PlanGUID = fi.FillinMemberGUID where p.PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(@planGUIDList, ',')) and fi.FillinMemberName != p.Name)) begin + update fi set fi.FillinMemberName = p.Name + from + [dbo].[ScoreFillin] fi + inner join [dbo].[XPlan] p with (readuncommitted) on p.PlanGUID = fi.FillinMemberGUID + where + p.PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(@planGUIDList, ',')) + and fi.FillinMemberName != p.Name + + exec [dbo].[procScoreFillinTableRefresh] @planGUIDList + end + end +GO + + +--------------------------------------------- + +-- dbo.procSR2RiskBinsCalculate +CREATE proc dbo.procSR2RiskBinsCalculate + @riskResultGUID uniqueidentifier, + @binCount int +as + set nocount on + + declare @min decimal(19, 8) + declare @max decimal(19, 8) + declare @step decimal(19, 8) + + select @min = coalesce((select MIN(Value) from [dbo].[SR2RiskResultDetail] where RiskResultGUID = @riskResultGUID), 0) + select @max = coalesce((select MAX(Value) from [dbo].[SR2RiskResultDetail] where RiskResultGUID = @riskResultGUID), 0) + set @step = ((@max - @min) / cast(@binCount as decimal(19, 8))) + + if (@min = @max) begin + update [dbo].[SR2RiskResultDetail] set BinNumber = 0 where RiskResultGUID = @riskResultGUID + end else begin + declare @binIndex as int = 0 + declare @binLowerBound as decimal(19, 8) = @min + + while (@binIndex < @binCount) begin + update [dbo].[SR2RiskResultDetail] set BinNumber = @binIndex where RiskResultGUID = @riskResultGUID and Value >= @binLowerBound + + set @binIndex = @binIndex + 1 + set @binLowerBound = @binLowerBound + @step + end + end +GO + + +--------------------------------------------- + +-- dbo.procScoreAttributeIsModelDriverRefresh +create proc dbo.procScoreAttributeIsModelDriverRefresh +as + update [dbo].[ScoreAttribute] set IsModelDriver = 0 + update [dbo].[ScoreAttribute] set IsModelDriver = 1 where exists(select 1 from [dbo].[MEScorePlaceholderLabel] phl (readuncommitted) where phl.FillinAttributeGUID = AttributeGUID) +GO + + +--------------------------------------------- + +-- dbo.procScoreAttributeSchemaUpdate +create proc procScoreAttributeSchemaUpdate + @attributeguid uniqueidentifier +as + +update + sa +set + sa.CachedInferredSQLColumnType =sac.CachedInferredSQLColumnType, + sa.ColumnType =sac.ColumnType, + sa.ComputedValueDefinition =sac.ComputedValueDefinition, + sa.DefaultValueDefinition =sac.DefaultValueDefinition, + --sa.DimensionGroupIsTable =sac.DimensionGroupIsTable, + sa.ForeignKeyColumn =sac.ForeignKeyColumn, + sa.ForeignKeyOnDelete =sac.ForeignKeyOnDelete, + sa.ForeignKeySchema =sac.ForeignKeySchema, + sa.ForeignKeyTable =sac.ForeignKeyTable, + sa.IdentityIncrement =sac.IdentityIncrement, + sa.IdentitySeed =sac.IdentitySeed, + sa.IsColumnExist =sac.IsColumnExist, + sa.IsComputed =sac.IsComputed, + sa.IsForeignKeyed =sac.IsForeignKeyed, + sa.IsIdentity =sac.IsIdentity, + sa.IsNullable =sac.IsNullable, + sa.MaxLength =sac.MaxLength, + sa.Precision =sac.Precision, + sa.Scale =sac.Scale +from + ScoreAttribute sa + inner join viewScoreAttributeSchemaInfo sac on sa.AttributeGUID = sac.AttributeGUID +where + sa.AttributeGUID = @attributeguid +GO + + +--------------------------------------------- + +-- dbo.procScoreAttributeSchemaUpdateAll +CREATE proc [dbo].[procScoreAttributeSchemaUpdateAll] ( + @DimensionGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000' +) as + +update + sa +set + sa.CachedInferredSQLColumnType =sac.CachedInferredSQLColumnType, + sa.ColumnType =sac.ColumnType, + sa.ComputedValueDefinition =sac.ComputedValueDefinition, + sa.DefaultValueDefinition =sac.DefaultValueDefinition, + --sa.DimensionGroupIsTable =sac.DimensionGroupIsTable, + sa.ForeignKeyColumn =sac.ForeignKeyColumn, + sa.ForeignKeyOnDelete =sac.ForeignKeyOnDelete, + sa.ForeignKeySchema =sac.ForeignKeySchema, + sa.ForeignKeyTable =sac.ForeignKeyTable, + sa.IdentityIncrement =sac.IdentityIncrement, + sa.IdentitySeed =sac.IdentitySeed, + sa.IsColumnExist =sac.IsColumnExist, + sa.IsComputed =sac.IsComputed, + sa.IsForeignKeyed =sac.IsForeignKeyed, + sa.IsIdentity =sac.IsIdentity, + sa.IsNullable =sac.IsNullable, + sa.MaxLength =sac.MaxLength, + sa.Precision =sac.Precision, + sa.Scale =sac.Scale +from + ScoreAttribute sa + inner join ScoreDimensionGroup g on g.DimensionGroupGUID = sa.DimensionGroupGUID + inner join ScoreDimension d on d.DimensionGUID = g.DimensionGUID + inner join viewScoreAttributeSchemaInfo sac on sa.AttributeGUID = sac.AttributeGUID +where + (d.DimensionGUID = @DimensionGUID or @DimensionGUID = '00000000-0000-0000-0000-000000000000') + and + (sa.CachedInferredSQLColumnType <>sac.CachedInferredSQLColumnType or + sa.ColumnType <>sac.ColumnType or + sa.ComputedValueDefinition <>sac.ComputedValueDefinition or + sa.DefaultValueDefinition <>sac.DefaultValueDefinition or + --sa.DimensionGroupIsTable <>sac.DimensionGroupIsTable or + sa.ForeignKeyColumn <>sac.ForeignKeyColumn or + sa.ForeignKeyOnDelete <>sac.ForeignKeyOnDelete or + sa.ForeignKeySchema <>sac.ForeignKeySchema or + sa.ForeignKeyTable <>sac.ForeignKeyTable or + sa.IdentityIncrement <>sac.IdentityIncrement or + sa.IdentitySeed <>sac.IdentitySeed or + sa.IsColumnExist <>sac.IsColumnExist or + sa.IsComputed <>sac.IsComputed or + sa.IsForeignKeyed <>sac.IsForeignKeyed or + sa.IsIdentity <>sac.IsIdentity or + sa.IsNullable <>sac.IsNullable or + sa.MaxLength <>sac.MaxLength or + sa.Precision <>sac.Precision or + sa.Scale <>sac.Scale ) +RETURN +GO + + +--------------------------------------------- + +-- dbo.procScoreAttributeSettingAddMissing +CREATE proc [dbo].[procScoreAttributeSettingAddMissing] +as + --non-inferred attributes default based on attribute-framework and dimension-framework linkages + insert into ScoreAttributeSetting (AttributeGUID, DimensionGUID, IsCustom, IsMarkedForDeletion, IsUsed, CAPIsUsed, DSSIsUsed, MRIsUsed, OBIsUsed, PRIsUsed, SPIsUsed) + select + a.AttributeGUID, + a.DimensionGUID, + 0 as IsCustom, + 0 as IsMarkedForDeletion, + (case when isnull(fw.FrameworkID, 0) != 0 then 1 when isnull(dss.FrameworkID, 0) != 0 then 1 when a.FriendlyName like 'DSS %' or a.FriendlyName like '% DSS' then 1 else 0 end) as IsUsed, + (case when isnull(fw.FrameworkID, 0) != 0 then 1 when isnull(cap.FrameworkID, 0) != 0 then 1 when a.FriendlyName like 'CAP %' or a.FriendlyName like '% CAP' or a.FriendlyName like 'Capital %' or a.FriendlyName like '% Capital' then 1 else 0 end) as CAPIsUsed, + (case when isnull(fw.FrameworkID, 0) != 0 then 1 when isnull(dss.FrameworkID, 0) != 0 then 1 when a.FriendlyName like 'DSS %' or a.FriendlyName like '% DSS' then 1 else 0 end) as DSSIsUsed, + (case when isnull(fw.FrameworkID, 0) != 0 then 1 when isnull(mr.FrameworkID, 0) != 0 then 1 when a.FriendlyName like 'MR %' or a.FriendlyName like '% MR' or a.FriendlyName like '% MR %' then 1 else 0 end) as MRIsUsed, + (case when isnull(ob.FrameworkID, 0) != 0 then 1 when a.FriendlyName like 'OB %' or a.FriendlyName like '% OB' then 1 else 0 end) as OBIsUsed, + (case when isnull(fw.FrameworkID, 0) != 0 then 1 when isnull(pr.FrameworkID, 0) != 0 then 1 when a.FriendlyName like 'PR %' or a.FriendlyName like '% PR' or a.FriendlyName like '% PR %' or a.FriendlyName like 'PI %' or a.FriendlyName like '% PI' or a.FriendlyName like '% PI %' then 1 else 0 end) as PRIsUsed, + (case when isnull(fw.FrameworkID, 0) != 0 then 1 when isnull(sp.FrameworkID, 0) != 0 then 1 when a.FriendlyName like 'SP %' or a.FriendlyName like '% SP' then 1 else 0 end) as SPIsUsed + from + viewScoreAttribute a + left join viewScoreAttributeFramework fw on fw.AttributeGUID = a.AttributeGUID and fw.FrameworkID = 0 + left join viewScoreAttributeFramework cap on cap.AttributeGUID = a.AttributeGUID and cap.FrameworkID = 1 + left join viewScoreAttributeFramework dss on dss.AttributeGUID = a.AttributeGUID and dss.FrameworkID = 6 + left join viewScoreAttributeFramework mr on mr.AttributeGUID = a.AttributeGUID and mr.FrameworkID = 3 + left join viewScoreAttributeFramework ob on ob.AttributeGUID = a.AttributeGUID and ob.FrameworkID = 2 + left join viewScoreAttributeFramework pr on pr.AttributeGUID = a.AttributeGUID and pr.FrameworkID = 5 + left join viewScoreAttributeFramework sp on sp.AttributeGUID = a.AttributeGUID and sp.FrameworkID = 4 + where + not exists(select 1 from ScoreAttributeSetting sa where sa.AttributeGUID = a.AttributeGUID) + and a.InferredAttributeGUID = '00000000-0000-0000-0000-000000000000' + + --inferred attributes just pull from their parent attribute, except for Department + insert into ScoreAttributeSetting (AttributeGUID, DimensionGUID, IsCustom, IsMarkedForDeletion, IsUsed, CAPIsUsed, DSSIsUsed, MRIsUsed, OBIsUsed, PRIsUsed, SPIsUsed) + select + a.AttributeGUID, + a.DimensionGUID, + pas.IsCustom, + 0 as IsMarkedForDeletion, + pas.IsUsed, + pas.CAPIsUsed, + pas.DSSIsUsed, + pas.MRIsUsed, + pas.OBIsUsed, + pas.PRIsUsed, + pas.SPIsUsed + from + viewScoreAttribute a + inner join ScoreAttributeSetting pas on pas.AttributeGUID = a.InferredAttributeGUID + where + not exists(select 1 from ScoreAttributeSetting sa where sa.AttributeGUID = a.AttributeGUID) + and a.InferredAttributeGUID != '00000000-0000-0000-0000-000000000000' + and a.DimensionName != 'Department' + update sas set + sas.IsCustom = pas.IsCustom, + sas.IsUsed = pas.IsUsed, + sas.CAPIsUsed = pas.CAPIsUsed, + sas.DSSIsUsed = pas.DSSIsUsed, + sas.MRIsUsed = pas.MRIsUsed, + sas.OBIsUsed = pas.OBIsUsed, + sas.PRIsUsed = pas.PRIsUsed, + sas.SPIsUsed = pas.SPIsUsed + from + viewScoreAttribute a + inner join ScoreAttributeSetting sas on sas.AttributeGUID = a.AttributeGUID + inner join ScoreAttributeSetting pas on pas.AttributeGUID = a.InferredAttributeGUID + where + a.InferredAttributeGUID != '00000000-0000-0000-0000-000000000000' + and a.DimensionName != 'Department' + and ( + sas.IsCustom != pas.IsCustom or + sas.IsUsed != pas.IsUsed or + sas.CAPIsUsed != pas.CAPIsUsed or + sas.DSSIsUsed != pas.DSSIsUsed or + sas.MRIsUsed != pas.MRIsUsed or + sas.OBIsUsed != pas.OBIsUsed or + sas.PRIsUsed != pas.PRIsUsed or + sas.SPIsUsed != pas.SPIsUsed + ) + + update sas + set sas.PRIsUsed=1, sas.MRIsUsed=1 + from + scoreattributesetting sas + join scoreattribute attr on sas.AttributeGUID = attr.AttributeGUID + join ScoreDimensionGroup gr on attr.DimensionGroupGUID = gr.DimensionGroupGUID + join ScoreDimension dim on dim.DimensionGUID = gr.DimensionGUID + where + dim.FriendlyName='MR Department' + and (sas.PRIsUsed=0 or sas.MRIsUsed=0) +GO + + +--------------------------------------------- + +-- dbo.procScoreAttributeSettingSetFromDI +CREATE proc dbo.procScoreAttributeSettingSetFromDI +as + with diUsage as ( + select + x.AttributeGUID + ,max(case when x.FrameworkID in(0, 1) then 1 else 0 end) as CAPIsUsed + ,max(case when x.FrameworkID in(0, 2) then 1 else 0 end) as OBIsUsed + ,max(case when x.FrameworkID in(0, 3) then 1 else 0 end) as MRIsUsed + ,max(case when x.FrameworkID in(0, 4) then 1 else 0 end) as SPIsUsed + ,max(case when x.FrameworkID in(0, 5) then 1 else 0 end) as PRIsUsed + ,max(case when x.FrameworkID in(0, 6) then 1 else 0 end) as DSSIsUsed + ,max(case when x.FrameworkID in(0, 6) then 1 else 0 end) as IsUsed + from ( + select + dif.ScoreKeyGUID as AttributeGUID, + c.FrameworkID + from + IntConfig c + inner join IntDataInterfaceSection dis on dis.DataInterfaceID = c.DataInterfaceID + inner join IntDataInterfaceField dif on dif.DataInterfaceSectionID = dis.DataInterfaceSectionID + where + datediff(day, c.LastRunAtUtc, getutcdate()) <= 120 + and dif.IsHidden = 0 + union all + select + dif.GivenScoreAttributeGUID as AttributeGUID, + c.FrameworkID + from + IntConfig c + inner join IntDataInterfaceSection dis on dis.DataInterfaceID = c.DataInterfaceID + inner join IntDataInterfaceField dif on dif.DataInterfaceSectionID = dis.DataInterfaceSectionID + where + datediff(day, c.LastRunAtUtc, getutcdate()) <= 120 + and dif.IsHidden = 0 + ) x + group by x.AttributeGUID + ) + update s set s.IsUsed = (case when di.IsUsed = 1 then 1 else s.IsUsed end), s.CAPIsUsed = (case when di.CAPIsUsed = 1 then 1 else s.CAPIsUsed end), s.OBIsUsed = (case when di.OBIsUsed = 1 then 1 else s.OBIsUsed end), s.MRIsUsed = (case when di.MRIsUsed = 1 then 1 else s.MRIsUsed end), s.SPIsUsed = (case when di.SPIsUsed = 1 then 1 else s.SPIsUsed end), s.PRIsUsed = (case when di.PRIsUsed = 1 then 1 else s.PRIsUsed end), s.DSSIsUsed = (case when di.DSSIsUsed = 1 then 1 else s.DSSIsUsed end) + from + ScoreAttributeSetting s + inner join diUsage di on di.AttributeGUID = s.AttributeGUID + + exec dbo.procScoreAttributeSettingAddMissing +GO + + +--------------------------------------------- + +-- dbo.procScoreClearLootRefreshTriggers +--Forward +create procedure [dbo].[procScoreClearLootRefreshTriggers]( + @DimensionGUID uniqueidentifier +) +AS +BEGIN + + declare crsCursor CURSOR LOCAL FAST_FORWARD FOR + select SchemaName, Name from ViewSysTriggers + where Name like '%' + [dbo].GetScoreLootRefreshTriggerName(@DimensionGUID) + '%' + + open crsCursor; + + declare @SchemaName sysname; + declare @TriggerName sysname; + + FETCH NEXT FROM crsCursor into @SchemaName, @TriggerName + WHILE (@@FETCH_STATUS = 0) + BEGIN + + exec procSysDropTrigger @SchemaName, @TriggerName + + FETCH NEXT FROM crsCursor into @SchemaName, @TriggerName + END + close crsCursor; + DEALLOCATE crsCursor; + +END + +RETURN +GO + + +--------------------------------------------- + +-- dbo.procScoreCompositeModifiedAt +--Author: gforeman +--Branch: Firefly +--Forward +CREATE proc [dbo].[procScoreCompositeModifiedAt] + @compositeguid uniqueidentifier +as +select coalesce((select MAX(ModifiedAt) from + ( + select sc.ModifiedAt from ScoreComposite sc where sc.CompositeGUID = @compositeguid + union all + select sl.ModifiedAt from ScoreCompositeLink sl where sl.CompositeGUID = @compositeguid + union all + select dt1.ModifiedAt from ScoreDataTable dt1 where dt1.DataTableGUID in(select sc.DataTableGUID1 from ScoreComposite sc where sc.CompositeGUID = @compositeguid) + union all + select sm1.ModifiedAt from ScoreMeasure sm1 where sm1.DataTableGUID in(select sc.DataTableGUID1 from ScoreComposite sc where sc.CompositeGUID = @compositeguid) + union all + select dtkl1.ModifiedAt from ScoreDataTableKeyLink dtkl1 where dtkl1.DataTableGUID in(select sc.DataTableGUID1 from ScoreComposite sc where sc.CompositeGUID = @compositeguid) + union all + select sa1.DateModified as ModifiedAt from ScoreAttribute sa1 where sa1.AttributeGUID in(select dtkl1.KeyGUID from ScoreDataTableKeyLink dtkl1 where dtkl1.DataTableGUID in(select sc.DataTableGUID1 from ScoreComposite sc where sc.CompositeGUID = @compositeguid)) + union all + select dt2.ModifiedAt from ScoreDataTable dt2 where dt2.DataTableGUID in(select sc.DataTableGUID2 from ScoreComposite sc where sc.CompositeGUID = @compositeguid) + union all + select sm2.ModifiedAt from ScoreMeasure sm2 where sm2.DataTableGUID in(select sc.DataTableGUID2 from ScoreComposite sc where sc.CompositeGUID = @compositeguid) + union all + select dtkl2.ModifiedAt from ScoreDataTableKeyLink dtkl2 where dtkl2.DataTableGUID in(select sc.DataTableGUID2 from ScoreComposite sc where sc.CompositeGUID = @compositeguid) + union all + select sa2.DateModified as ModifiedAt from ScoreAttribute sa2 where sa2.AttributeGUID in(select dtkl2.KeyGUID from ScoreDataTableKeyLink dtkl2 where dtkl2.DataTableGUID in(select sc.DataTableGUID2 from ScoreComposite sc where sc.CompositeGUID = @compositeguid)) + ) x +), getdate()) --return current date if invalid guid passed +GO + + +--------------------------------------------- + +-- dbo.procScoreCopyComposite +CREATE PROCEDURE [dbo].[procScoreCopyComposite] ( + @CompositeGUID uniqueidentifier, + @TargetDatabase varchar(4000), -- [Server].[Database] for example: [ittestserv01\sql2005].[TSMChampaign] + @IsIncludeData bit = 0, + @IsDebugOnly bit = 0 +) +AS + +--Copy Both DataTables (does not need dynamic sql) +declare @DataTable1GUID uniqueidentifier; +declare @DataTable2GUID uniqueidentifier; +select @DataTable1GUID = DataTableGUID1, @DataTable2GUID = DataTableGUID2 from ScoreComposite where CompositeGUID = @CompositeGUID; + +execute [dbo].procScoreCopyDataTable @DataTable1GUID, @TargetDatabase, @IsIncludeData, @IsDebugOnly; +execute [dbo].procScoreCopyDataTable @DataTable2GUID, @TargetDatabase, @IsIncludeData, @IsDebugOnly; + +---Now register the composite and copy composite links (requiring dynamic sql) +declare @sql varchar(max) +set @sql = ' + +declare @TargetDatabase varchar(4000); +declare @CompositeGUID uniqueidentifier; +declare @Source_FriendlyName nvarchar(max); +declare @Target_Count int; + +set @CompositeGUID = ''' + Cast(@CompositeGUID as varchar(64)) + '''; +set @TargetDatabase = ''' + @TargetDatabase + '''; + +--Check for Existence +select @Source_FriendlyName = FriendlyName from dbo.ScoreComposite + WHERE CompositeGUID = @CompositeGUID +SELECT @Target_Count = COUNT(*) from ' + @TargetDatabase + '.[dbo].[ScoreComposite] + WHERE CompositeGUID = @CompositeGUID Or FriendlyName = @Source_FriendlyName; + +if (@Target_Count > 0) +BEGIN + print ''Composite Exists in Target Database''; + RETURN; +END + +--Copy Composite into new table +INSERT INTO ' + @TargetDatabase + '.[dbo].[ScoreComposite] +(CompositeGUID,DataTableGUID1,DataTableGUID2,IsWrittenToDB,FriendlyName) +SELECT top 1 +CompositeGUID,DataTableGUID1,DataTableGUID2,IsWrittenToDB,FriendlyName +from dbo.ScoreComposite WHERE CompositeGUID = @CompositeGUID; + +--Copy CompositeLinks into new table (have to account for Identity..so do this custom columns +INSERT INTO ' + @TargetDatabase + '.[dbo].[ScoreCompositeLink] + (CompositeGUID,CompositeLinkGUID,IsFixedIndex,IsPlaceholder,Key1AttributeGUID,Key1GUID,Key2AttributeGUID,Key2GUID,PlaceholderIndexMeasureGUID,SQLCustomLinkExpression,Type) +SELECT + LINK.CompositeGUID,LINK.CompositeLinkGUID,LINK.IsFixedIndex,LINK.IsPlaceholder,LINK.Key1AttributeGUID,FK1.AttributeGUID,LINK.Key2AttributeGUID,FK2.AttributeGUID,LINK.PlaceholderIndexMeasureGUID,LINK.SQLCustomLinkExpression,LINK.Type + from + [dbo].[ScoreCompositeLink] LINK + inner join viewScoreAttribute K1 on K1.AttributeGUID = LINK.Key1GUID + inner join viewScoreAttribute K2 on K2.AttributeGUID = LINK.Key2GUID + left join ' + @TargetDatabase + '.[dbo].[viewScoreAttribute] FK1 on FK1.SQLColumnName = K1.SQLColumnName and FK1.DimensionName = K1.DimensionName + left join ' + @TargetDatabase + '.[dbo].[viewScoreAttribute] FK2 on FK2.SQLColumnName = K2.SQLColumnName and FK2.DimensionName = K2.DimensionName +where CompositeGUID=@CompositeGUID +' +print @sql; + +if @IsDebugOnly = 0 +BEGIN + exec (@sql); +END +GO + + +--------------------------------------------- + +-- dbo.procScoreCopyDataTable +CREATE PROCEDURE [dbo].[procScoreCopyDataTable] ( + @DataTableGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000', + @TargetDatabase varchar(4000), -- [Server].[Database] for example: [ittestserv01\sql2005].[TSMChampaign] + @IsIncludeData bit = 0, + @IsDebugOnly bit = 0, + @aFriendlyName varchar(max) = '' +) +AS + +if (@aFriendlyName <> '') +BEGIN + print 'Recursive Call'; + declare @DTGUID uniqueidentifier; + select @DTGUID=DatatableGUID from ScoreDatatable where FriendlyName = @aFriendlyName; + exec dbo.procScoreCopyDataTable @DTGUID, @TargetDatabase, @IsIncludeData, @IsDebugOnly; + RETURN; +END + +print ' Copying Dimensions ' +--First Must Copy all dimensions that are a part of this datatable (have keys) +-- this does not require dynamic sql +DECLARE DimensionCursor CURSOR FOR +SELECT Distinct(DimensionGUID), (select count(*) from [dbo].[viewScoreAttribute] A where A.DimensionGUID = D.DimensionGUID) as AttributeCount from ScoreDimension D where + D.DimensionGUID IN ( + --ALL DIMENSIONS IN DT + select DIM.DimensionGUID from ScoreDataTable DT + inner join ScoreDataTableKeyLink DTKEYLINK on DT.DataTableGUID = DTKEYLINK.DataTableGUID + inner join viewScoreAttribute ATT on ATT.AttributeGUID = DTKEYLINK.KeyGUID + inner join ScoreDimension DIM on DIM.DimensionGUID = ATT.DimensionGUID + where DT.DataTableGUID = @DataTableGUID + UNION + --INCLUDE FK_DIMENSIONS OF ANY ATTRIBUTES + select DIM_FK.DimensionGUID from ScoreDataTable DT + inner join ScoreDataTableKeyLink DTKEYLINK on DT.DataTableGUID = DTKEYLINK.DataTableGUID + inner join viewScoreAttribute ATT on ATT.AttributeGUID = DTKEYLINK.KeyGUID + inner join ScoreDimension DIM on DIM.DimensionGUID = ATT.DimensionGUID + inner join viewScoreAttribute ATT_FK on ATT.ForeignKeyGUID = ATT_FK.AttributeGUID + inner join ScoreDimension DIM_FK on ATT_FK.DimensionGUID = DIM_FK.DimensionGUID + where DT.DataTableGUID = @DataTableGUID) +order by AttributeCount asc -- do smaller dimensions first, as presumably the larger dimensions depend on them + + +Open DimensionCursor +declare @DimGUID uniqueidentifier +declare @AttrCount int +FETCH NEXT FROM DimensionCursor INTO @DimGUID, @AttrCount +WHILE (@@FETCH_STATUS = 0) +BEGIN + EXECUTE dbo.procScoreCopyDimension @DimGUID, @TargetDatabase, @IsIncludeData, @IsDebugOnly; + FETCH NEXT FROM DimensionCursor INTO @DimGUID, @AttrCount +END +CLOSE DimensionCursor +DEALLOCATE DimensionCursor + + +declare @SQLSchemaName varchar(max); +declare @SQLObjectName varchar(max); +select @SQLSchemaName = SQLSchemaName, + @SQLObjectName = SQLObjectName + from ScoreDataTable where DataTableGUID = @DataTableGUID; + +print ' Copying Datatable ' +declare @sql varchar(max) +set @sql = ' + +declare @TargetDatabase varchar(4000); +declare @DataTableGUID uniqueidentifier; +declare @Source_FriendlyName nvarchar(max); +declare @Target_Count int; +set @DataTableGUID = ''' + Cast(@DataTableGUID as varchar(64)) + '''; +set @TargetDatabase = ''' + @TargetDatabase + '''; + +--Check for Existence +select @Source_FriendlyName = FriendlyName from dbo.ScoreDataTable + WHERE DataTableGUID = @DataTableGUID +select @Target_Count = COUNT(*) from ' + @TargetDatabase + '.[dbo].[ScoreDataTable] + WHERE DataTableGUID = @DataTableGUID Or FriendlyName = @Source_FriendlyName; + +if (@Target_Count > 0) +BEGIN + print ''DataTable Exists in Target Database''; + RETURN; +END + +--Copy DataTable into new table +INSERT INTO ' + @TargetDatabase + '.[dbo].[ScoreDataTable] + (DataTableGUID,FriendlyName,Description,SQLSchemaName,SQLObjectName,SQLTableAlias,IsWrittenToDB,DisplayFormatAttributeGUID,GlobalID,IsCompositeMappingTable,IsCompositeBoundsTable,FrameworkID,IsWrittenIfZero) +SELECT top 1 + DataTableGUID,FriendlyName,Description,SQLSchemaName,SQLObjectName,SQLTableAlias,IsWrittenToDB,DisplayFormatAttributeGUID,GlobalID,IsCompositeMappingTable,IsCompositeBoundsTable,FrameworkID,IsWrittenIfZero + from dbo.ScoreDataTable WHERE DataTableGUID = @DataTableGUID; + +--Copy KeyLinks into new table +INSERT INTO ' + @TargetDatabase + '.[dbo].[ScoreDataTableKeyLink] + (DataTableKeyLinkGUID,DataTableGUID,KeyGUID) +SELECT + LINK.DataTableKeyLinkGUID,LINK.DataTableGUID,FK1.AttributeGUID +FROM dbo.ScoreDataTableKeyLink LINK + inner join viewScoreAttribute K1 on K1.AttributeGUID = LINK.KeyGUID + left join ' + @TargetDatabase + '.[dbo].[viewScoreAttribute] FK1 on FK1.SQLColumnName = K1.SQLColumnName and FK1.DimensionName = K1.DimensionName +WHERE DataTableGUID = @DataTableGUID; + + +--Copy Measures into new table +declare @measureWhere nvarchar(450) +set @measureWhere = ''DataTableGUID = '''''' + cast(@DataTableGUID as nvarchar(36)) + '''''''' +exec ' + @TargetDatabase + '.dbo.procMigrateScriptGetByTable ''dbo'', ''[' + cast(SERVERPROPERTY('SERVERNAME') as varchar(4000)) + '].[' + DB_NAME() + ']'', ''ScoreMeasure'', @measureWhere, 1 + +--Never Copy Data but always Copy the Schema +-- DONT DO THIS ANYMORE, SYNC FIRST +--EXEC ' + @TargetDatabase + '.[dbo].[procLinkedTransferDataBetweenTables] ''[' + cast(SERVERPROPERTY('SERVERNAME') as varchar(4000)) + '].[' + DB_NAME() + '].' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ''',''' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ''' +-- ,'' 1=0 ''; + +'; + +print @sql; + +if @IsDebugOnly = 0 +BEGIN + exec (@sql); +END +GO + + +--------------------------------------------- + +-- dbo.procScoreCopyDimension +CREATE PROCEDURE [dbo].[procScoreCopyDimension] ( + @DimensionGUID uniqueidentifier='00000000-0000-0000-0000-000000000000', + @TargetDatabase varchar(4000), -- [Server].[Database] for example: [ittestserv01\sql2005].[TSMChampaign] + @IsIncludeData bit = 0, + @IsDebugOnly bit = 0, + @IsIncludeForeignKeyDimensions bit = 0, + @IsBuildingTables bit = 0 +) +AS + + +if (@DimensionGUID = '00000000-0000-0000-0000-000000000000') +BEGIN + RETURN; +END + +--Dont want to framework transfer account ph if missing, as it conflicts with ob account ph - everyone will have one or the other already +if (exists (select 1 from [dbo].[ScoreDimension] (nolock) where DimensionGUID = @DimensionGUID and FriendlyName = 'Account PH')) begin return end + +print 'Copying Dimension'; +declare @SQLSchemaName nvarchar(128); +declare @SQLObjectName nvarchar(max); +select + @SQLSchemaName = SQLSchemaName, + @SQLObjectName = SQLObjectName +from [dbo].[ScoreDimension] where DimensionGUID = @DimensionGUID + + +--Check Foreign Key Dimensions +if (@IsIncludeForeignKeyDimensions = 1) +begin + declare crsCursor CURSOR FAST_FORWARD LOCAL FOR + select distinct FKD.DimensionGUID, FKD.FriendlyName from ScoreDimension D + inner join viewScoreAttribute A on A.DimensionGUID = D.DimensionGUID + inner join viewScoreAttribute FKA on FKA.AttributeGUID = A.ForeignKeyGUID + inner join ScoreDimension FKD on FKD.DimensionGUID = FKA.DimensionGUID + where D.DimensionGUID = @DimensionGUID + open crsCursor; + declare @fkDimGUID uniqueidentifier; + declare @fkName varchar(max); + FETCH NEXT FROM crsCursor into @fkDimGUID, @fkName; + + WHILE (@@FETCH_STATUS = 0) + BEGIN + print 'Copying Foreign Key Dimension: ' + @fkName; + exec procScoreCopyDimension @fkDimGUID, @TargetDatabase, @IsIncludeData, @IsDebugOnly, @IsBuildingTables; + FETCH NEXT FROM crsCursor into @fkDimGUID, @fkName + END + close crsCursor; + DEALLOCATE crsCursor; +end + + +if (@IsBuildingTables = 1 or @IsIncludeData = 1) begin + + declare @GroupSchema nvarchar(128); + declare @GroupObject nvarchar(128); + declare grpCursor CURSOR FAST_FORWARD LOCAL FOR + select G.SchemaName, G.ObjectName from ScoreDimension D + inner join ScoreDimensionGroup G on D.DimensionGUID = G.DimensionGUID + where D.DimensionGUID = @DimensionGUID + open grpCursor; + FETCH NEXT FROM grpCursor into @GroupSchema, @GroupObject; + + WHILE (@@FETCH_STATUS = 0) + BEGIN + declare @remoteSQL varchar(max); + set @remoteSQL = ''; + --disallow building a view + if (@IsBuildingTables = 1 and dbo.IsView(@GroupSchema,@GroupObject) = 0) begin + print 'Remotely Building Group Table: ' + '[' + @GroupSchema + '].[' + @GroupObject + ']'''; + set @remoteSQL = @remoteSQL + ' exec ' + @TargetDatabase + '.[sqlgen].procCopyRemoteTable ''[' + cast(SERVERPROPERTY('SERVERNAME') as varchar(4000)) + '].[' + DB_NAME() + ']'', ''' + @GroupSchema + ''', ''' + @GroupObject + '''; +' + end + --attempt to transfer regardless + if (@IsIncludeData = 1) begin + print 'Transfering Data to ' + '[' + @GroupSchema + '].[' + @GroupObject + ']'''; + set @remoteSQL = @remoteSQL + ' EXEC ' + @TargetDatabase + '.[dbo].[procLinkedTransferDataBetweenTables] ''[' + cast(SERVERPROPERTY('SERVERNAME') as varchar(4000)) + '].[' + DB_NAME() + '].' + (select [dbo].[GetSQLTableExpression](@GroupSchema, @GroupObject)) + ''',''' + (select [dbo].[GetSQLTableExpression](@GroupSchema, @GroupObject)) + ''''; + end + print @remoteSQL; + if (@IsDebugOnly = 0) begin + exec (@remoteSQL); + end + + FETCH NEXT FROM grpCursor into @GroupSchema, @GroupObject; + END + close grpCursor; + DEALLOCATE grpCursor; + + + +end + +declare @sql varchar(max) +set @sql = ' + +declare @DimensionGUID uniqueidentifier; +set @DimensionGUID = ''' + Cast(@DimensionGUID as varchar(64)) + '''; +declare @IsIncludeData bit; +set @IsIncludeData = ' + Cast(@IsIncludeData as varchar) + '; + +declare @Target_Count int; +declare @Source_FriendlyName nvarchar(max); + + +select @Source_FriendlyName = FriendlyName from [dbo].[ScoreDimension] where DimensionGUID = @DimensionGUID; + +select @Target_Count = Count(*) from ' + @TargetDatabase + '.[dbo].[ScoreDimension] +where DimensionGUID = @DimensionGUID OR FriendlyName = @Source_FriendlyName; + +if (@Target_Count > 0) +BEGIN + print ''Dimension Exists in Target Database'' + Return; +END + +--Copy Dimension into new table +INSERT INTO ' + @TargetDatabase + '.[dbo].[ScoreDimension] + ( DimensionGUID, + FriendlyName, + Description, + SQLTableAlias, + DefaultKeyGUID, + DefaultHierarchyGUID, + DefaultLookupKeyGUID, + IsSecured, + PermissionSetID, + SQLSchemaName, + SQLObjectName, + DefaultMemberGUID, + IsSysAdminOnly, + IsAllowMemberDelete, + IsAllowMemberAdd, + PrimaryGroupGUID, + IsStock, + DateModified, + PickerType, + IsSharingSecurity , + DimensionVersion +) + SELECT top 1 + DimensionGUID, + FriendlyName, + Description, + SQLTableAlias, + DefaultKeyGUID, + DefaultHierarchyGUID, + DefaultLookupKeyGUID, + IsSecured, + PermissionSetID, + SQLSchemaName, + SQLObjectName, + DefaultMemberGUID, + IsSysAdminOnly, + IsAllowMemberDelete, + IsAllowMemberAdd, + PrimaryGroupGUID, + IsStock, + DateModified, + PickerType, + IsSharingSecurity, + DimensionVersion + from dbo.ScoreDimension WHERE DimensionGUID = @DimensionGUID; + +-- Copy Dimension Groups +INSERT INTO ' + @TargetDatabase + '.[dbo].[ScoreDimensionGroup] +(DimensionGroupGUID, DimensionGUID, Name, Description, SchemaName, ObjectName, IsStock, DateModified) +SELECT + DimensionGroupGUID, DimensionGUID, Name, Description, SchemaName, ObjectName, IsStock, DateModified +from dbo.ScoreDimensionGroup WHERE DimensionGUID = @DimensionGUID; + +--Copy Attributes into new table +INSERT INTO ' + @TargetDatabase + '.[dbo].[ScoreAttribute] + (AttributeGUID, + DimensionGroupGUID, + FriendlyName, + IsWrittenToDB, + IsKey, + IsSecuredLootID, + IsSecuredLootGroupID, + SecuredLootGroupPrefix, + SQLColumnName, + DefaultSortAttributeGUID, + ForeignKeyGUID, + IsRequired, + SpecialAttributeIndex, + IsCopiedWithPlan, + DisplayOrder, + IsHidden, + DateModified, + AttributeType, + MetaXML, + InferredSourceGUID, + InferredColumnName, + InferredAttributeGUID, + HelpText, + ColumnType, + ComputedValueDefinition, + IsComputed, + IsIdentity, + IdentityIncrement, + IdentitySeed, + IsNullable, + DefaultValueDefinition, + Precision, + Scale, + MaxLength, + IsColumnExist, + IsForeignKeyed, + ForeignKeySchema, + ForeignKeyTable, + ForeignKeyColumn, + ForeignKeyOnDelete, + CachedInferredSQLColumnType, + IsFKAutoFilter, + JoinTypeVal + ) +SELECT + A.AttributeGUID, + A.DimensionGroupGUID, + A.FriendlyName, + A.IsWrittenToDB, + A.IsKey, + A.IsSecuredLootID, + A.IsSecuredLootGroupID, + A.SecuredLootGroupPrefix, + A.SQLColumnName, + A.DefaultSortAttributeGUID, + A.ForeignKeyGUID, + A.IsRequired, + A.SpecialAttributeIndex, + A.IsCopiedWithPlan, + A.DisplayOrder, + A.IsHidden, + A.DateModified, + A.AttributeType, + A.MetaXML, + A.InferredSourceGUID, + A.InferredColumnName, + A.InferredAttributeGUID, + A.HelpText, + A.ColumnType, + A.ComputedValueDefinition, + A.IsComputed, + A.IsIdentity, + A.IdentityIncrement, + A.IdentitySeed, + A.IsNullable, + A.DefaultValueDefinition, + A.Precision, + A.Scale, + A.MaxLength, + A.IsColumnExist, + A.IsForeignKeyed, + A.ForeignKeySchema, + A.ForeignKeyTable, + A.ForeignKeyColumn, + A.ForeignKeyOnDelete, + A.CachedInferredSQLColumnType, + A.IsFKAutoFilter, + A.JoinTypeVal + from dbo.viewScoreAttribute A + inner join ScoreDimensionGroup G on G.DimensionGroupGUID = A.DimensionGroupGUID + inner join ScoreDimension D on D.DimensionGUID = G.DimensionGUID +WHERE D.DimensionGUID = @DimensionGUID; + +--Copy Hierarchies +INSERT INTO ' + @TargetDatabase + '.[dbo].[ScoreHierarchy] + (HierarchyGUID, DimensionGUID, FriendlyName, PathAlias, DateModified) +SELECT + HierarchyGUID, DimensionGUID, FriendlyName, PathAlias, DateModified +from dbo.ScoreHierarchy WHERE DimensionGUID = @DimensionGUID; + + +--Copy Hierarchy Attribute Links +INSERT INTO ' + @TargetDatabase + '.[dbo].[ScoreHierarchyAttributeLink] +(HierarchyAttributeLinkGUID, + HierarchyGUID, + AttributeGUID, + DisplayAttributeGUID, + SortOrder, + IsDependentOnChild, + DateModified, + IsAttributeFiltered, + FilterAttributeGUID, + FilterString +) +SELECT + LINK.HierarchyAttributeLinkGUID, + LINK.HierarchyGUID, + LINK.AttributeGUID, + LINK.DisplayAttributeGUID, + LINK.SortOrder, + LINK.IsDependentOnChild, + LINK.DateModified, + LINK.IsAttributeFiltered, + LINK.FilterAttributeGUID, + LINK.FilterString + from ScoreHierarchyAttributeLink LINK + inner join viewScoreAttribute ATT on ATT.AttributeGUID = LINK.AttributeGUID + inner join ScoreDimension DIM on ATT.DimensionGUID = DIM.DimensionGUID + where DIM.DimensionGUID = @DimensionGUID; + +--Copy Dimension Framework +INSERT INTO ' + @TargetDatabase + '.[dbo].[ScoreDimensionFramework] +(DimensionGUID, + FrameworkID +) +SELECT + DFW.DimensionGUID, + DFW.FrameworkID +FROM ScoreDimensionFramework DFW + WHERE DFW.DimensionGUID = @DimensionGUID; + + + +--SIMPLE PERMISSIONS +if not exists (select 1 from ' + @TargetDatabase + '.[dbo].[S3SimplePermission] where LootID = @DimensionGUID and IdentityGUID = (select UserGroupGUID from ' + @TargetDatabase + '.[dbo].[UserGroup] where Name = ''Everyone'')) begin + insert into ' + @TargetDatabase + '.[dbo].[S3SimplePermission] (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) + VALUES (@DimensionGUID, (select UserGroupGUID from ' + @TargetDatabase + '.[dbo].[UserGroup] where Name = ''Everyone''), 1,1,1) +end + +'; +print @sql; + +if @IsDebugOnly = 0 +BEGIN + exec (@sql); +END +GO + + +--------------------------------------------- + +-- dbo.procScoreDataTableCreateParamTypes +create proc dbo.procScoreDataTableCreateParamTypes + @isDebug bit = 0 +as + declare @dtguid uniqueidentifier + declare @sql nvarchar(max) + declare crsTables cursor fast_forward for + select + dt.DataTableGUID, ' + if (exists(select 1 from sys.schemas s inner join sys.types t on t.schema_id = s.schema_id where s.name = ''' + dt.SQLSchemaName + ''' and t.name = ''' + dt.SQLObjectName + 'TableType'')) begin + drop type ' + dt.SQLSchemaName + '.' + dt.SQLObjectName + 'TableType; + end + create type ' + dt.SQLSchemaName + '.' + dt.SQLObjectName + 'TableType as table ( + [RowID] int{0} + );' + from + dbo.ScoreDataTable dt + where + dt.FriendlyName not like '% Aggregate' + and exists(select 1 from dbo.ScoreComposite c where c.DataTableGUID2 = dt.DataTableGUID and exists(select 1 from EMFModelTemplateLinkSource emf where emf.ParentScoreCompositeTableGUID = c.CompositeGUID)) + and exists(select 1 from dbo.ScoreMeasure m where m.DataTableGUID = dt.DataTableGUID and m.IsWrittenToDB = 1) + + open crsTables + fetch next from crsTables into @dtguid, @sql + + declare @measures nvarchar(max) + declare @measure nvarchar(max) + + while (@@fetch_status = 0) begin + declare crsMeasures cursor fast_forward for + select m.ColName from ( + select + ', [' + m.SQLColumnName + '] ' + t.name + case when t.name = 'varchar' then '(' + cast(m.MaxLength as nvarchar(8)) + ')' when t.name = 'nvarchar' and m.MaxLength <= 4000 then '(' + cast(m.MaxLength as nvarchar(8)) + ')' when t.name = 'nvarchar' and m.MaxLength > 4000 then '(4000)' when t.name = 'decimal' then '(' + cast(m.Precision as nvarchar(8)) + ',' + cast(m.Scale as nvarchar(8)) + ')' else '' end as ColName + from + dbo.ScoreMeasure m + inner join sys.types t on t.system_type_id = m.ColumnTypeValue + where + m.IsWrittenToDB = 1 + and m.DataTableGUID = @dtguid + and t.name != 'sysname' + union all + select + ', [' + m.SpecialFormulaSQLColumnName + '] nvarchar(max)' as ColName + from + dbo.ScoreMeasure m + inner join sys.types t on t.system_type_id = m.ColumnTypeValue + where + m.IsWrittenToDB = 1 + and m.DataTableGUID = @dtguid + and t.name != 'sysname' + and m.SpecialFormulaSQLColumnName != '' + union all + select + ', [' + m.SpecialCommentSQLColumnName + '] nvarchar(max)' as ColName + from + dbo.ScoreMeasure m + inner join sys.types t on t.system_type_id = m.ColumnTypeValue + where + m.IsWrittenToDB = 1 + and m.DataTableGUID = @dtguid + and t.name != 'sysname' + and m.SpecialCommentSQLColumnName != '' + ) m + order by m.ColName + + open crsMeasures + fetch next from crsMeasures into @measure + + set @measures = '' + + while (@@fetch_status = 0) begin + set @measures = @measures + @measure + + fetch next from crsMeasures into @measure + end + + close crsMeasures + deallocate crsMeasures + + set @sql = replace(@sql, '{0}', @measures) + + if (@isDebug = 0) begin + exec(@sql) + end else begin + print @sql + end + + fetch next from crsTables into @dtguid, @sql + end + + close crsTables + deallocate crsTables +GO + + +--------------------------------------------- + +-- dbo.procScoreDataTableEnsureDefaults +create proc procScoreDataTableEnsureDefaults +as + declare @sql nvarchar(max) + declare crsScripts cursor fast_forward for + select distinct + 'ALTER TABLE ' + s.name + '.' + t.name + ' ADD CONSTRAINT DF_' + t.name + '_' + c.name + ' DEFAULT 0 FOR ' + c.name + from + sys.columns c + inner join sys.tables t on t.object_id = c.object_id + inner join sys.schemas s on s.schema_id = t.schema_id + inner join ScoreDataTable dt on dt.SQLObjectName = t.name and dt.SQLSchemaName = s.name + where + c.name like '%ID' + and c.name != 'RowID' + and system_type_id in(48, 52, 56) + and default_object_id = 0 + open crsScripts + fetch next from crsScripts into @sql + while(@@FETCH_STATUS = 0) begin + exec(@sql) + fetch next from crsScripts into @sql + end + close crsScripts + deallocate crsScripts +GO + + +--------------------------------------------- + +-- dbo.procScoreDataTableKeyLinkSchemaUpdate +create proc [dbo].[procScoreDataTableKeyLinkSchemaUpdate] + @datatableguid uniqueidentifier = '00000000-0000-0000-0000-000000000000' +as + +update + obj +set + obj.ColumnID = objschema.ColumnID, + obj.ColumnName = objschema.ColumnName, + obj.ColumnTypeValue = objschema.ColumnTypeValue, + obj.ComputedValueDefinition = objschema.ComputedValueDefinition, + obj.DefaultValueDefinition = objschema.DefaultValueDefinition, + obj.ForeignKeyColumn = objschema.ForeignKeyColumn, + obj.ForeignKeyOnDelete = objschema.ForeignKeyOnDelete, + obj.ForeignKeySchema = objschema.ForeignKeySchema, + obj.ForeignKeyTable = objschema.ForeignKeyTable, + obj.IdentityIncrement = objschema.IdentityIncrement, + obj.IdentitySeed = objschema.IdentitySeed, + obj.IsComputed = objschema.IsComputed, + obj.IsForeignKeyed = objschema.IsForeignKeyed, + obj.IsIdentity = objschema.IsIdentity, + obj.IsNullable = objschema.IsNullable, + obj.IsPartOfPrimaryKey = objschema.IsPartOfPrimaryKey, + obj.IsPartOfUniqueIndex = objschema.IsPartOfUniqueIndex, + obj.IsPrimaryKey = objschema.IsPrimaryKey, + obj.IsUniqueIndex = objschema.IsUniqueIndex, + obj.MaxLength = objschema.MaxLength, + obj.ObjectID = objschema.ObjectID, + obj.ObjectName = objschema.ObjectName, + obj.ObjectType = objschema.ObjectType, + obj.Precision = objschema.Precision, + obj.Scale = objschema.Scale, + obj.SchemaName = objschema.SchemaName +from + ScoreDataTableKeyLink obj + inner join viewScoreDataTableKeyLinkSchemaInfo objschema on obj.DataTableKeyLinkGUID = objschema.DataTableKeyLinkGUID +where + @datatableguid in (obj.datatableguid, dbo.zeroguid()) + and ( + obj.ColumnID <> objschema.ColumnID or + obj.ColumnName <> objschema.ColumnName or + obj.ColumnTypeValue <> objschema.ColumnTypeValue or + obj.ComputedValueDefinition <> objschema.ComputedValueDefinition or + obj.DefaultValueDefinition <> objschema.DefaultValueDefinition or + obj.ForeignKeyColumn <> objschema.ForeignKeyColumn or + obj.ForeignKeyOnDelete <> objschema.ForeignKeyOnDelete or + obj.ForeignKeySchema <> objschema.ForeignKeySchema or + obj.ForeignKeyTable <> objschema.ForeignKeyTable or + obj.IdentityIncrement <> objschema.IdentityIncrement or + obj.IdentitySeed <> objschema.IdentitySeed or + obj.IsComputed <> objschema.IsComputed or + obj.IsForeignKeyed <> objschema.IsForeignKeyed or + obj.IsIdentity <> objschema.IsIdentity or + obj.IsNullable <> objschema.IsNullable or + obj.IsPartOfPrimaryKey <> objschema.IsPartOfPrimaryKey or + obj.IsPartOfUniqueIndex <> objschema.IsPartOfUniqueIndex or + obj.IsPrimaryKey <> objschema.IsPrimaryKey or + obj.IsUniqueIndex <> objschema.IsUniqueIndex or + obj.MaxLength <> objschema.MaxLength or + obj.ObjectID <> objschema.ObjectID or + obj.ObjectName <> objschema.ObjectName or + obj.ObjectType <> objschema.ObjectType or + obj.Precision <> objschema.Precision or + obj.Scale <> objschema.Scale or + obj.SchemaName <> objschema.SchemaName + ) +GO + + +--------------------------------------------- + +-- dbo.procScoreDataTableKeyLinkSchemaUpdateMissing +--Forward +create proc procScoreDataTableKeyLinkSchemaUpdateMissing +as + if ((select count(*) from [dbo].ScoreDataTableKeyLink where columnname = '') > 0) begin + declare @dtguid uniqueidentifier + declare crsTables cursor fast_forward for select DataTableGUID from [dbo].ScoreDataTableKeyLink where columnname = '' + + open crsTables + fetch next from crsTables into @dtguid + + while(@@fetch_status = 0) begin + exec [dbo].[procScoreDataTableKeyLinkSchemaUpdate] @dtguid + + fetch next from crsTables into @dtguid + end + + close crsTables + deallocate crsTables + end + +RETURN +GO + + +--------------------------------------------- + +-- dbo.procScoreDeleteComposite +CREATE Procedure [dbo].[procScoreDeleteComposite] +( + @CompositeGUID uniqueidentifier +) +AS + + print 'Deleting CompositeLinks'; + DELETE FROM ScoreCompositeLink where CompositeGUID = @CompositeGUID; + + print 'Deleting Composite'; + DELETE FROM ScoreComposite where CompositeGUID = @CompositeGUID +GO + + +--------------------------------------------- + +-- dbo.procScoreDeleteCompositeFull +CREATE proc procScoreDeleteCompositeFull + @compositeGUID uniqueidentifier +as + +begin try + begin transaction + declare @dt1g uniqueidentifier + declare @dt1schema sysname + declare @dt1name sysname + declare @dt2g uniqueidentifier + declare @dt2schema sysname + declare @dt2name sysname + + select + @dt1g = dt1.DataTableGUID, + @dt1schema = dt1.SQLSchemaName, + @dt1name = dt1.SQLObjectName, + @dt2g = dt2.DataTableGUID, + @dt2schema = dt2.SQLSchemaName, + @dt2name = dt2.SQLObjectName + from + ScoreComposite sc + left join ScoreDataTable dt1 on sc.DataTableGUID1 = dt1.DataTableGUID + left join ScoreDataTable dt2 on sc.DataTableGUID2 = dt2.DataTableGUID + where + sc.CompositeGUID = @compositeGUID + + --delete scorecomposite record + delete from ScoreComposite where CompositeGUID = @compositeGUID + print 'deleted composite reg' + + --delete dt1 if unused by any composites + delete from ScoreDataTable where DataTableGUID = @dt1g and not exists (select 1 from ScoreComposite sc where sc.DataTableGUID1 = @dt1g or sc.DataTableGUID2 = @dt1g) + print 'deleted dt1 reg' + + --delete dt2 if unused by any composites + delete from ScoreDataTable where DataTableGUID = @dt2g and not exists (select 1 from ScoreComposite sc where sc.DataTableGUID1 = @dt2g or sc.DataTableGUID2 = @dt2g) + print 'deleted dt2 reg' + + declare @sql varchar(max) + + --drop dt1 table if it exists + if dbo.TableExists(@dt1schema, @dt1name) = 1 begin + set @sql = 'drop table [' + @dt1schema + '].[' + @dt1name + ']' + exec (@sql) + print 'dropped dt1' + end + + --drop dt2 table if it exists + if dbo.TableExists(@dt2schema, @dt2name) = 1 begin + set @sql = 'drop table [' + @dt2schema + '].[' + @dt2name + ']' + exec (@sql) + print 'dropped dt2' + end + + commit +end try +begin catch + rollback + print 'error: ' + error_message() + exec procSysRethrowError +end catch +GO + + +--------------------------------------------- + +-- dbo.procScoreDeleteDataTable +CREATE Procedure [dbo].[procScoreDeleteDataTable] +( + @DataTableGUID uniqueidentifier, + @IsHardDelete bit = 0 , + @DeleteInUse bit = 0 +) +AS + declare @SchemaName nvarchar(128); + declare @ObjectName nvarchar(max); + select + @SchemaName = SQLSchemaName, + @ObjectName = SQLObjectName + from ScoreDataTable where DataTableGUID = @DataTableGUID; + + if @SchemaName is null RETURN + if @objectname is null RETURN + + IF ([dbo].[ScoreIsDataTableInUse](@DataTableGUID) = 1 AND @DeleteInUse = 0) + BEGIN + -- Do NOT allow this to happen under any circumstances + RAISERROR ('DataTable is in use. Cannot delete.',15,1); + RETURN + END + + IF @DeleteInUse = 1 begin + print 'Deleting composites that use this datatable'; + DELETE FROM ScoreComposite where DataTableGUID1 = @DataTableGUID + DELETE FROM ScoreComposite where DataTableGUID2 = @DataTableGUID + end + + print 'Deleting DataTableKeyLinks'; + DELETE FROM ScoreDataTableKeyLink where DataTableGUID = @DataTableGUID; + + print 'Deleting Measures'; + DELETE FROM ScoreMeasure where DataTableGUID = @DataTableGUID + + print ' Deleting DataTable'; + DELETE FROM ScoreDataTable where DataTableGUID = @DataTableGUID + + if (@IsHardDelete = 1) + BEGIN + + if ([dbo].[IsView](@SchemaName, @ObjectName) = 1) + BEGIN + print ' Cannot hard delete a view. Skipping. '; + END + ELSE + BEGIN + print ' Hard deleting datatable.'; + declare @sql varchar(max); + set @sql = ' + DELETE FROM ' + (select [dbo].[GetSQLTableExpression](@SchemaName, @ObjectName)) + '; + DROP TABLE ' + (select [dbo].[GetSQLTableExpression](@SchemaName, @ObjectName)) + '; + '; + print @sql + print @schemaname + print @objectname + exec (@sql); + END + END +GO + + +--------------------------------------------- + +-- dbo.procScoreDeleteDimension +CREATE Procedure [dbo].[procScoreDeleteDimension] +( + @DimensionGUID uniqueidentifier, + @IsHardDelete bit = 0, --Hard Delete will remove the table as well. + @DeleteInUse bit = 0 +) +AS + + declare @SQLSchemaName nvarchar(128); + declare @SQLObjectName nvarchar(max); + select + @SQLSchemaName = SQLSchemaName, + @SQLObjectName = SQLObjectName + from ScoreDimension where DimensionGUID = @DimensionGUID; + + IF ([dbo].[ScoreIsDimensionInUse](@DimensionGUID) = 1 and @DeleteInUse = 0) + BEGIN + -- Do NOT allow this to happen under any circumstances + RAISERROR ('Dimension is in use. Cannot delete.',15,1); + RETURN + END + + print ' Deleting Hierarchy Records '; + DELETE FROM ScoreHierarchy where DimensionGUID = @DimensionGUID; + + + + print ' Resetting FKs and DefaultSortAtts '; + --FKs and DefaultSortAttributeGUIDS + DECLARE AttributeCursor CURSOR FOR + SELECT A.AttributeGUID FROM ScoreAttribute A + inner join ScoreDimensionGroup G on G.DimensionGroupGUID = A.DimensionGroupGUID + inner join ScoreDimension D on D.DimensionGUID = G.DimensionGUID + where D.DimensionGUID = @DimensionGUID + + OPEN AttributeCursor + DECLARE @AttGuid_i uniqueidentifier + + FETCH NEXT FROM AttributeCursor INTO @AttGuid_i; + WHILE (@@FETCH_STATUS = 0) + BEGIN + UPDATE ScoreAttribute + SET DefaultSortAttributeGUID = '00000000-0000-0000-0000-000000000000' + WHERE DefaultSortAttributeGUID = @AttGuid_i; + UPDATE ScoreAttribute + SET ForeignKeyGUID = '00000000-0000-0000-0000-000000000000' + WHERE ForeignKeyGUID = @AttGuid_i; + FETCH NEXT FROM AttributeCursor INTO @AttGuid_i; + END + CLOSE AttributeCursor; + DEALLOCATE AttributeCursor; + + Print ' Deleting Attribute Records '; + --Note: Hierarchy Attribute links handled by Foreign Key delete in ScoreAttribute + DELETE A + FROM ScoreAttribute A + inner join ScoreDimensionGroup G on G.DimensionGroupGUID = A.DimensionGroupGUID + where G.DimensionGUID = @DimensionGUID; + --DELETE FROM ScoreAttribute where DimensionGUID = @DimensionGUID; + + + if (@IsHardDelete = 1) + begin + print 'Dropping Group Tables/Views'; + declare @GroupSchema nvarchar(128); + declare @GroupObject nvarchar(128); + declare GroupCursor CURSOR LOCAL FAST_FORWARD FOR + SELECT SchemaName, ObjectName from ScoreDimensionGroup where DimensionGUID = @DimensionGUID; + + OPEN GroupCursor + FETCH NEXT FROM GroupCursor INTO @GroupSchema,@GroupObject; + WHILE (@@FETCH_STATUS = 0) + BEGIN + if ([dbo].[IsView](@GroupSchema,@GroupObject) = 1) + begin + exec procSysDropView @GroupSchema, @GroupObject; + end + else + begin + exec procSysDropTable @GroupSchema, @GroupObject; + end + FETCH NEXT FROM GroupCursor INTO @GroupSchema,@GroupObject; + END + CLOSE GroupCursor; + DEALLOCATE GroupCursor; + end + + Print ' Deleting Group Records'; + DELETE FROM ScoreDimensionGroup where DimensionGUID = @DimensionGUID; + + if (@IsHardDelete = 1) + BEGIN + + if ([dbo].[IsView](@SQLSchemaName, @SQLObjectName) = 1) + BEGIN + print ' Hard Deleting Dimension View '; + exec procSysDropView @SQLSchemaName, @SQLObjectName; + END + ELSE + BEGIN + print ' Hard deleting dimension Table.'; + exec procSysDropTable @SQLSchemaName, @SQLObjectName; + END + END + + DELETE FROM dbo.ScoreDimensionFramework + WHERE DimensionGUID = @DimensionGUID; + + print 'Deleting Dimension Record'; + DELETE FROM ScoreDimension where DimensionGUID = @DimensionGUID; +GO + + +--------------------------------------------- + +-- dbo.procScoreDeleteOrphanedSecurityTriggers +create procedure [dbo].[procScoreDeleteOrphanedSecurityTriggers] ( + @IsDebugOnly bit = 0 +) +AS + +BEGIN + +--ORPHANED Triggers +declare crsCursor CURSOR FAST_FORWARD FOR + +select + T.Name, + T.SchemaName +from viewSysTriggers T + left join ScoreDimension D on SUBSTRING(T.Name, 20, 32) = REPLACE(D.DimensionGUID,'-','') +where + T.Name like 'trg_ScoreDimension_%_LootRefresh%' + and D.FriendlyName is null + +print 'The Following Score Loot Refresh Triggers are Orphaned (Dimension no longer exists): +'; + +open crsCursor; + +DECLARE @triggerName nvarchar(128); +DECLARE @schemaName nvarchar(128); + +declare @sql varchar(max); +set @sql = ''; +FETCH NEXT FROM crsCursor into @triggerName, @schemaName +WHILE (@@FETCH_STATUS = 0) + BEGIN + + PRINT ' [' + @schemaName + '].[' + @triggerName + ']'; + set @sql = @sql + 'DROP TRIGGER [' + @schemaName + '].[' + @triggerName + ']; +'; + FETCH NEXT FROM crsCursor into @triggerName, @schemaName; + END +close crsCursor; +DEALLOCATE crsCursor; + +print ''; +print @sql; + +if (@IsDebugOnly = 0) +BEGIN + exec (@sql); +END + +END +GO + + +--------------------------------------------- + +-- dbo.procScoreDimensionCacheRefresh +CREATE proc [dbo].[procScoreDimensionCacheRefresh] + @dimensionGUID uniqueidentifier, + @whereClause nvarchar(max) = '', + @isDebug bit = 0, + @isNoRecurse bit = 0, + @isSecurityDirty bit = 0 +AS + set nocount on + + --caching not used by v2 dimensions + IF (exists (SELECT 1 FROM ScoreDimension with (readuncommitted) WHERE DimensionGUID = @dimensionGUID AND DimensionVersion = 3)) BEGIN + --grab basic dimension info + declare @sourceSchema nvarchar(100) + declare @sourceName nvarchar(450) + declare @cacheSchema nvarchar(100) + declare @cacheName nvarchar(450) + declare @objectid int + declare @isSecured bit + select + @sourceSchema = D.SQLSchemaName, + @sourceName = D.SQLObjectName + '_source', + @cacheSchema = DG.SchemaName, + @cacheName = DG.ObjectName, + @objectid = T.object_id, + @isSecured = D.IsSecured + from + ScoreDimension D with (readuncommitted) + inner join ScoreDimensionGroup DG with (readuncommitted) on DG.DimensionGroupGUID = D.PrimaryGroupGUID + inner join sys.tables T with (readuncommitted) on T.name = DG.ObjectName + inner join sys.schemas S with (readuncommitted) on S.name = DG.SchemaName and S.schema_id = T.schema_id + where + D.DimensionGUID = @dimensionGUID + + declare @isUsingVersionColumn bit + if ((select COUNT(*) from sys.columns with (readuncommitted) where object_id = @objectid and name = 'Version') > 0) begin + set @isUsingVersionColumn = 1 + end else begin + set @isUsingVersionColumn = 0 + end + + --get column info + declare @colName nvarchar(100) + declare crsColumns cursor fast_forward for + select + C.name + from + sys.columns C with (readuncommitted) + inner join sys.tables T with (readuncommitted) on T.object_id = C.object_id + inner join sys.schemas S with (readuncommitted) on S.schema_id = T.schema_id + inner join viewScoreAttribute A on A.SQLColumnName = C.name + where + T.name = @cacheName + and S.name = @cacheSchema + and A.DimensionGUID = @dimensionGUID + and A.IsWrittenToDB = 0 + and A.AttributeType != 1 + and A.SQLColumnName not in('MemberGUID', 'HistoryItemGUID') + and C.is_computed = 0 + + declare @colCount int + set @colCount = 0 + + --build the update script to populate non-editable columns in the cache + declare @fillSQL nvarchar(max) = '' + if (@isSecured = 1) begin + set @fillSQL = 'update dbo.ScoreDimension set IsSecurityTriggersEnabled = 0 where DimensionGUID = ''' + cast(@dimensionGUID as nvarchar(36)) + '''; + ' + end + set @fillSQL = @fillSQL + 'update C set ' + open crsColumns + fetch next from crsColumns into @colName + while (@@FETCH_STATUS = 0) begin + set @fillSQL = @fillSQL + 'C.[' + @colName + '] = S.[' + @colName + '],' + set @colCount = @colCount + 1 + fetch next from crsColumns into @colName + end + close crsColumns + deallocate crsColumns + set @fillSQL = LEFT(@fillSQL, len(@fillSQL) - 1) + set @fillSQL = @fillSQL + ' + from + ' + @cacheSchema + '.' + @cacheName + ' C + inner join ' + @sourceSchema + '.' + @sourceName + ' S on S.MemberGUID = C.MemberGUID' + if (@whereClause != '') begin + set @fillSQL = @fillSQL + ' where ' + @whereClause + end + set @fillSQL = @fillSQL + '; + ' + declare @rollbackSQL nvarchar(1000) = '' + if (@isSecured = 1) begin + set @fillSQL = @fillSQL + 'update dbo.ScoreDimension set IsSecurityTriggersEnabled = 1 where DimensionGUID = ''' + cast(@dimensionGUID as nvarchar(36)) + ''';' + set @rollbackSQL = 'update dbo.ScoreDimension set IsSecurityTriggersEnabled = 1 where DimensionGUID = ''' + cast(@dimensionGUID as nvarchar(36)) + ''';' + end + + --fill the cache table + if (@colCount > 0) begin + if (@isDebug = 0) begin + begin try + exec(@fillSQL) + end try + begin catch + --don't leave triggers in a bad state + exec(@rollbackSQL) + end catch + end else begin + print @fillSQL + end + end + END + + --refresh dependent members, going up to 2 dependency levels deep + if (@isNoRecurse = 0) begin + declare @FKsql nvarchar(max) + set @FKsql = '' + declare @FKdimensionGUID uniqueidentifier + declare crsFKDimensions cursor fast_forward for + select distinct + d.ChildDimensionGUID + from + dbo.viewScoreDimensionDependency d + where + (d.ParentDimensionGUID = @dimensionGUID or d.ParentDimensionGUID in(select c.ChildDimensionGUID from dbo.viewScoreDimensionDependency c where c.ParentDimensionGUID = @dimensionGUID)) + and d.ChildDimensionGUID != @dimensionGUID + open crsFKDimensions + fetch next from crsFKDimensions into @FKdimensionGUID + while(@@FETCH_STATUS = 0) begin + --have to use dynamic sql because otherwise the recursion fails because we use the same cursor name + set @FKsql = @FKsql + 'exec procScoreDimensionCacheRefresh ''' + CAST(@FKdimensionGUID as nvarchar(36)) + ''', '''', ' + cast(@isDebug as nvarchar(1)) + ', 1, ' + cast(@isSecurityDirty as nvarchar(1)) + ' +' + fetch next from crsFKDimensions into @FKdimensionGUID + end + close crsFKDimensions + deallocate crsFKDimensions + exec(@FKsql) + end + + --refresh security if any inferred/calculated attributes drive security + if ((@isDebug = 0) and (@isSecured = 1) and (@isSecurityDirty = 1)) begin + INSERT INTO [dbo].[S3UserACLRegenRequest] ([RequestGUID], [IssuedAt]) VALUES (NEWID(), GETDATE()) + exec procScoreSetDimensionSecurity30 @dimensionGUID, @isDebug, @isUsingVersionColumn, 0, 'procScoreDimensionCacheRefresh' + end +GO + + +--------------------------------------------- + +-- dbo.procScoreDimensionCacheRefreshAll +--Forward +create proc procScoreDimensionCacheRefreshAll +as + set nocount on + + declare @dimensionGUID uniqueidentifier + declare crsDimensions cursor fast_forward for select DimensionGUID from ScoreDimension + + open crsDimensions + fetch next from crsDimensions into @dimensionGUID + + while(@@FETCH_STATUS = 0) begin + exec procScoreDimensionCacheRefresh @dimensionGUID + + fetch next from crsDimensions into @dimensionGUID + end + + close crsDimensions + deallocate crsDimensions +GO + + +--------------------------------------------- + +-- dbo.procScoreDimensionLastModified +CREATE proc [dbo].[procScoreDimensionLastModified] + @dimensionguid uniqueidentifier +as + +declare @datemodified datetime + +select coalesce((select MAX(datemodified) from + ( + select datemodified from ScoreDimension where DimensionGUID = @dimensionguid + union all select datemodified from ScoreAttribute where DimensionGroupGUID in (select dimensiongroupguid from scoredimensiongroup where dimensionguid = @dimensionguid) + union all select datemodified from ScoreDimensionGroup where DimensionGUID = @dimensionguid + union all select datemodified from ScoreHierarchy where DimensionGUID = @dimensionguid + union all select datemodified from ScoreHierarchyAttributeLink shal + where shal.HierarchyGUID in (select HierarchyGUID from ScoreHierarchy where DimensionGUID = @dimensionguid) + ) x +), getdate()) --return current date if invalid guid passedd +GO + + +--------------------------------------------- + +-- dbo.procScoreEnsureDefaultFramework +create proc dbo.procScoreEnsureDefaultFramework +AS +begin + + --ensure that fw.DimFramework contains the general framework + if not exists(select 1 from fw.DimFramework where FrameworkID = 0) begin + set identity_insert fw.DimFramework ON; + insert into fw.DimFramework (FrameworkID, Name) VALUES (0, 'General'); + set identity_insert fw.DimFramework OFF; + end + + --insert into ScoreDimensionFramework any dimensions that aren't tagged at all (linked to General) + insert into ScoreDimensionFramework (DimensionGUID, FrameworkID) + select D.DimensionGUID, 0 as [FrameworkID] from ScoreDimension D + left join ScoreDimensionFramework F on F.DimensionGUID = D.DimensionGUID + group by D.DimensionGUID + having SUM(case when F.FrameworkID is null then 0 else 1 end) = 0 + +end +GO + + +--------------------------------------------- + +-- dbo.procScoreEnsureDimensionTableSetup +CREATE proc [dbo].[procScoreEnsureDimensionTableSetup] ( + @DimensionGUID uniqueidentifier, + @DebugMode bit +) +AS + + declare @SchemaName nvarchar(128); + declare @ObjectName nvarchar(max); + select + @SchemaName = SQLSchemaName, + @ObjectName = SQLObjectName + from ScoreDimension where DimensionGUID = @DimensionGUID; + + if ([dbo].[IsView](@SchemaName, @ObjectName) = 1) + BEGIN + print ('Table is view-backed. Cannot add Columns. Exiting.'); + RETURN; + END + + exec procEnsureColumnInTable @SchemaName, @ObjectName, 'IsDeleted', 'bit', '0', @DebugMode; + exec procEnsureColumnInTable @SchemaName, @ObjectName, 'HistoryItemGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode + exec procEnsureColumnInTable @SchemaName, @ObjectName, 'MemberGUID', 'uniqueidentifier', 'newid()', @DebugMode +GO + + +--------------------------------------------- + +-- dbo.procScoreEnsureLootRefreshTrigger +--#notran# +CREATE PROC [dbo].[procScoreEnsureLootRefreshTrigger]( + @aDimensionGUID uniqueidentifier +) +AS + + --get schema and object + declare @Schema varchar(128); + declare @Object varchar(128); + select @Schema = Sqlschemaname, @Object = SQLObjectname from ScoreDimension where DimensionGUID = @aDimensionGUID; + if (exists(select 1 from scoredimension d where d.dimensionguid = @aDimensionGUID and d.dimensionversion = 3 and exists(select 1 from sys.views v where v.name = d.sqlobjectname + '_source'))) begin + set @Object = @Object + '_source' + end + + if ([dbo].[IsView](@Schema, @Object) = 1) + BEGIN + declare @TableSchema varchar(128); + declare @TableName varchar(128); + declare @TableTriggerName varchar(128); + print 'Adding Triggers to Underlying Tables'; + + DECLARE TableCursor CURSOR LOCAL FAST_FORWARD + FOR select TableName, TableSchema from viewSysViewBaseTables where ViewName = @Object and ViewSchema = @Schema and TableType = 'BASE TABLE' and TableName like 'Dim%' and TableSchema <> 'dbo' order by [Level] + --FOR select * from [dbo].GetViewUnderlyingTables(@Schema, @Object) + OPEN TableCursor; + Fetch Next from TableCursor INTO @TableName, @TableSchema; + WHILE (@@FETCH_STATUS = 0) + BEGIN + if (@TableSchema = 'dbo') + BEGIN + print 'Skipping dbo schema underlying table.'; + END + ELSE + BEGIN + set @TableTriggerName = Substring((select [dbo].GetScoreLootRefreshTriggerName(@aDimensionGUID)) + '_' + @TableName, 0, 128); + exec [dbo].procScoreEnsureLootRefreshTriggerHelper @aDimensionGUID, @TableSchema,@TableName,@TableTriggerName,0; + END + + Fetch Next from TableCursor INTO @TableName, @TableSchema; + END + CLOSE TableCursor; + DEALLOCATE TableCursor; + END + ELSE + BEGIN + --Add the Trigger directly to the Table + declare @triggerName varchar(max); + select @triggerName = (select [dbo].GetScoreLootRefreshTriggerName(@aDimensionGUID)); + exec [dbo].procScoreEnsureLootRefreshTriggerHelper @aDimensionGUID, @Schema, @Object, @triggerName,1; + END +GO + + +--------------------------------------------- + +-- dbo.procScoreEnsureLootRefreshTriggerHelper +CREATE PROC [dbo].[procScoreEnsureLootRefreshTriggerHelper]( + @aDimensionGUID uniqueidentifier, + @TargetSchemaName varchar(128), + @TargetObjectName varchar(128), + @TriggerName varchar(128), + @IsDirect bit +) +AS + +declare @isself bit = 0 +if(exists(select 1 from [dbo].[ScoreDimension] D inner join [dbo].[ScoreDimensionGroup] DG on DG.DimensionGroupGUID = D.PrimaryGroupGUID where D.DimensionGUID = @aDimensionGUID and DG.SchemaName = @TargetSchemaName and DG.ObjectName = @TargetObjectName)) begin + set @isself = 1 +end + +declare @targetDimensionGUID uniqueidentifier +select @targetDimensionGUID = D.DimensionGUID from [dbo].[ScoreDimension] D inner join [dbo].[ScoreDimensionGroup] DG on DG.DimensionGroupGUID = D.PrimaryGroupGUID where D.IsSecured = 1 and DG.SchemaName = @TargetSchemaName and DG.ObjectName = @TargetObjectName +if (@targetDimensionGUID is null) begin + return +end + +------IF THE TRIGGER EXISTS, THEN DROP IT, WE NEED TO RECREATE +if ([dbo].IsTriggerExist(@TriggerName)= 1) + BEGIN + declare @dropSQL varchar(max); + set @dropSQL = ' + DROP TRIGGER [' + @TargetSchemaName + '].[' + @TriggerName + ']; + '; + print @dropSQL; + exec(@dropSQL) + END + + -----SEE IF THERES A VERSION COLUMN , will be 1 OR 0 +declare @IsVersion int; +select + @IsVersion = COUNT(*) +from viewSysColumns COL +where + COL.ObjectName = @TargetObjectName + and COL.SchemaName = @TargetSchemaName + and COL.ColumnName = 'Version' + and COL.ColumnTypeValue = 189 --timestamp + +if (@IsDirect = 0) +begin + set @IsVersion = 0 --don't use version if we are not direct +end + +if (not exists(select 1 from sys.tables t inner join sys.schemas s on s.schema_id = t.schema_id where s.name = @TargetSchemaName and t.name = @TargetObjectName)) +begin + return +end + +declare @sql varchar(max); +set @sql = ' + + CREATE TRIGGER [' + @TargetSchemaName + '].[' + @TriggerName + '] + ON ' + (select [dbo].[GetSQLTableExpression](@TargetSchemaName, @TargetObjectName)) + ' + AFTER UPDATE, INSERT + AS + BEGIN + SET NOCOUNT ON; + + if (exists(select 1 from dbo.ScoreDimension with (readuncommitted) where DimensionGUID = ''' + cast(@targetDimensionGUID as nvarchar(36)) + ''' and IsSecurityTriggersEnabled = 0)) begin + return + end +' + +if (@isself = 1) begin + set @sql = @sql + ' + declare @memberguid uniqueidentifier + + --handle single member insert specially + if (((select count(MemberGUID) from inserted) = 1) and ((select count(MemberGUID) from deleted) = 0)) begin + select top 1 @memberguid = MemberGUID from inserted + EXEC procScoreSetDimensionSecurity30InsertNew ''' + cast(@aDimensionGUID as varchar(max)) + ''', @memberguid, 0, ' + CAST(@IsVersion as nvarchar(8)) + ' + return + end + + --handle single member update specially + if (((select count(MemberGUID) from inserted) = 1) and ((select count(MemberGUID) from deleted) = 1) and (isnull((select top 1 MemberGUID from inserted), ''00000000-0000-0000-0000-000000000000'') = isnull((select top 1 MemberGUID from deleted), ''00000000-0000-0000-0000-000000000000''))) begin + select top 1 @memberguid = MemberGUID from deleted + EXEC procScoreSetDimensionSecurity30UpdateSingle ''' + cast(@aDimensionGUID as varchar(max)) + ''', @memberguid, 0, ' + CAST(@IsVersion as nvarchar(8)) + ' + return + end' +end else begin + set @sql = @sql + ' + if ((exists(select 1 from inserted)) and (not exists(select 1 from deleted))) begin + --no dependents to refresh since this is a straight insert + return + end' +end + +set @sql = @sql + ' + + --handle all other cases + EXEC procScoreSetDimensionSecurity30 ''' + cast(@aDimensionGUID as varchar(max)) + ''', 0, ' + CAST(@IsVersion as nvarchar(8)) + ' + END +'; +print @sql; +exec (@sql); + +--hack: drop unwanted project->requisition trigger +declare @reqdimguid uniqueidentifier +select @reqdimguid = DimensionGUID from ScoreDimension where FriendlyName = 'CAP Requisition' +if (@reqdimguid is not null) begin + declare @reqdimsql nvarchar(max) + set @reqdimsql = ' + IF EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N''[cap].[trg_ScoreDimension_' + replace(cast(@reqdimguid as nvarchar(36)), '-', '') + '_LootRefresh_DimProject]'')) + DROP TRIGGER [cap].[trg_ScoreDimension_' + replace(cast(@reqdimguid as nvarchar(36)), '-', '') + '_LootRefresh_DimProject]' + exec(@reqdimsql) +end +GO + + +--------------------------------------------- + +-- dbo.procScoreEnsureLootRefreshTriggers +create procedure [dbo].[procScoreEnsureLootRefreshTriggers] +AS +BEGIN + + declare dimCursor CURSOR LOCAL FAST_FORWARD FOR + select DimensionGUID, IsSecured from ScoreDimension + + open dimCursor; + + DECLARE @DimGUID uniqueidentifier; + DECLARE @IsSecured bit; + + FETCH NEXT FROM dimCursor into @DimGUID, @IsSecured + WHILE (@@FETCH_STATUS = 0) + BEGIN + + if (@IsSecured = 1) + begin + exec procScoreEnsureLootRefreshTrigger @DimGUID; + end + + FETCH NEXT FROM dimCursor into @DimGUID, @IsSecured + END + close dimCursor; + DEALLOCATE dimCursor; + +END +GO + + +--------------------------------------------- + +-- dbo.procScoreEnsureSecurity +create procedure [dbo].[procScoreEnsureSecurity] +AS +BEGIN + + exec procScoreDeleteOrphanedSecurityTriggers; + exec procScoreEnsureLootRefreshTriggers; + +END +GO + + +--------------------------------------------- + +-- dbo.procScoreEnsureSystemSectionDimension +--/****** Object: StoredProcedure [dbo].[procScoreEnsureSystemSectionDimension] Script Date: 03/22/2011 11:25:58 ******/ +--SET ANSI_NULLS ON +--GO + +--SET QUOTED_IDENTIFIER ON +--GO + + + +CREATE proc [dbo].[procScoreEnsureSystemSectionDimension] ( + @IsForceRebuild bit = 0 +) +as + + +declare @DeletedDimensionGUID uniqueidentifier; + +-- check existing +declare @cnt int +select @cnt = count(*) from ScoreDimension where FriendlyName = 'System Sections' +if @cnt = 1 begin + + if @IsForceRebuild = 1 begin + print 'Forcing Rebuild...'; + select @DeletedDimensionGUID = DimensionGUID from ScoreDimension where FriendlyName = 'System Sections'; + exec procScoreDeleteDimension @DeletedDimensionGUID, 1,1; + end + else begin + print 'System Section dimension already exists.' + return + end + +end + +-- get schema +declare @schema varchar(10) +select @schema = name from sys.schemas where name = 'fw' +if @schema is null begin + select @schema = name from sys.schemas where name = 'data' + if @schema is null begin + set @schema = 'dbo' + end +end + +-- create view +declare @sql varchar(max) +set @sql = ' + create view [' + @schema + '].[viewDimSystemSection] + as + select + SS.SYSTEMSECTIONGUID as MemberGUID, + SS.Name, + SS.ImageName, + coalesce(nullif(replace(replace(replace(substring(replace(SS.FullPath, ''SYSTEM\'', ''''), 1, patindex(''%\%'', replace(SS.FullPath, ''SYSTEM\'', ''''))), ''\'', ''''), ''TOOLBAR_'', ''''), ''MENU_'', ''''), ''''), ''System'') as Area, + coalesce(nullif(replace(substring(replace(SS.FullPath, ''SYSTEM\'', ''''), 1, patindex(''%\%'', replace(SS.FullPath, ''SYSTEM\'', ''''))), ''\'', ''''), ''''), ''System'') as Section, + coalesce(nullif(replace(replace(replace(substring(replace(SS.FullPath, ''SYSTEM\'', ''''), 1, patindex(''%\%'', replace(SS.FullPath, ''SYSTEM\'', ''''))), ''\'', ''''), ''TOOLBAR_'', ''''), ''MENU_'', ''''), ''''), ''System'') + + '' - '' + + coalesce(nullif(replace(substring(replace(SS.FullPath, ''SYSTEM\'', ''''), 1, patindex(''%\%'', replace(SS.FullPath, ''SYSTEM\'', ''''))), ''\'', ''''), ''''), ''System'') + + '' - '' + SS.Name as [FullName], + SS.ID, + SS.LootID, + coalesce(PSS.Name, ''System'') as Parent, + coalesce(PSS.LootID, ''1F30ED4A-DFA5-4EA6-8457-20D23DB372C3'') as ParentLootID, + cast(0 as bit) as IsDeleted, + dbo.ZeroGUID() as HistoryItemGUID + from SystemSection SS + left join SystemSection PSS on PSS.SystemSectionGUID = SS.ParentGUID + --inner join S3Loot L on L.LootID = SS.LootID + --inner join S3PermissionSet PS on PS.PermissionSetID = L.PermissionSetID --why do we do this? AJK + --where PS.Name like ''%System%'' + ' +exec(@sql) + +-- get permissionsetid +declare @PermissionSetID int +select @PermissionSetID = PermissionSetID from S3PermissionSet where Name like '%System%' + +-- create dimension +insert into ScoreDimension +(FriendlyName, SQLTableAlias, DefaultKeyGUID, DefaultHierarchyGUID, DefaultLookupKeyGUID, IsSecured, PermissionSetID, SQLSchemaName, SQLObjectName, DefaultMemberGUID, IsSysAdminOnly) +values ( + 'System Sections', -- FriendlyName + 'SS', -- SQLTableAlias + dbo.ZeroGUID(), -- DefaultKeyGUID + dbo.ZeroGUID(), -- DefaultHierarchyGUID + dbo.ZeroGUID(), -- DefaultLookupKeyGUID + 1, -- IsSecured + @PermissionSetID, -- PermissionSetID + @schema, -- SQLSchemaName + 'viewDimSystemSection', -- SQLObjectName + dbo.ZeroGUID(), -- DefaultMemberGUID + 0 -- IsSysAdminOnly +) + +-- get dimensionguid +declare @DimensionGUID uniqueidentifier +select @DimensionGUID = DimensionGUID from ScoreDimension where FriendlyName = 'System Sections' + + + +-- create dimension group +insert into ScoreDimensionGroup +(DimensionGUID, Name, Description, IsStock, SchemaName, ObjectName, DateModified) +values ( + @DimensionGUID, --DimensionGUID + 'System Sections', --Name + '', --Description + 1, --IsStock + @schema, --SchemaName + 'viewDimSystemSection', --ObjectName + GETDATE() --DateModified +); + +declare @DimensionGroupGUID uniqueidentifier; +select @DimensionGroupGUID = G.DimensionGroupGUID from ScoreDimensionGroup G + inner join ScoreDimension D on D.DimensionGUID = G.DimensionGUID +where G.Name = 'System Sections' and D.DimensionGUID = @DimensionGUID + +--update primary group +UPDATE ScoreDimension Set PrimaryGroupGUID = @DimensionGroupGUID + where DimensionGUID = @DimensionGUID + +--get COLUMN attribute type +declare @ColumnType int; +select @ColumnType = T.ScoreAttributeTypeID from ScoreAttributeType T where T.Name = 'Column'; + +-- create memberguid attribute +insert into ScoreAttribute +(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, IsHidden, AttributeType) +values ( + @DimensionGroupGUID, -- DimensionGUID + 'MemberGUID', -- FriendlyName + 36, -- ColumnType + 0, -- IsWrittenToDB + 1, -- IsKey + 0, -- IsSecuredLootID + 0, -- IsSecuredLootConfigID + 0, -- IsSecuredLootGroupID + '', -- SecuredLootGroupPrefix + 'MemberGUID', -- SQLColumnName + dbo.ZeroGUID(), -- DefaultSortAttributeGUID + dbo.ZeroGUID(), -- ForeignKeyGUID + 1, -- IsRequired + 0, -- SpecialAttributeIndex + 1, -- IsCopiedWithPlan + 0, -- DisplayOrder + 0, -- isHidden + @ColumnType --AttributeType +) + +-- create fullname attribute +insert into ScoreAttribute +(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, IsHidden, AttributeType) +values ( + @DimensionGroupGUID, -- DimensionGUID + 'FullName', -- FriendlyName + 231, -- ColumnType + 0, -- IsWrittenToDB + 1, -- IsKey + 0, -- IsSecuredLootID + 0, -- IsSecuredLootConfigID + 0, -- IsSecuredLootGroupID + '', -- SecuredLootGroupPrefix + 'FullName', -- SQLColumnName + dbo.ZeroGUID(), -- DefaultSortAttributeGUID + dbo.ZeroGUID(), -- ForeignKeyGUID + 1, -- IsRequired + 0, -- SpecialAttributeIndex + 1, -- IsCopiedWithPlan + 0, -- DisplayOrder + 0, -- isHidden + @ColumnType --AttributeType +) + +-- create name attribute +insert into ScoreAttribute +(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, IsHidden, AttributeType) +values ( + @DimensionGroupGUID, -- DimensionGUID + 'Name', -- FriendlyName + 231, -- ColumnType + 0, -- IsWrittenToDB + 0, -- IsKey + 0, -- IsSecuredLootID + 0, -- IsSecuredLootConfigID + 0, -- IsSecuredLootGroupID + '', -- SecuredLootGroupPrefix + 'Name', -- SQLColumnName + dbo.ZeroGUID(), -- DefaultSortAttributeGUID + dbo.ZeroGUID(), -- ForeignKeyGUID + 1, -- IsRequired + 0, -- SpecialAttributeIndex + 1, -- IsCopiedWithPlan + 0, -- DisplayOrder + 0, -- isHidden + @ColumnType --AttributeType +) + +-- create imagename attribute +insert into ScoreAttribute +(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, IsHidden, AttributeType) +values ( + @DimensionGroupGUID, -- DimensionGUID + 'ImageName', -- FriendlyName + 231, -- ColumnType + 0, -- IsWrittenToDB + 0, -- IsKey + 0, -- IsSecuredLootID + 0, -- IsSecuredLootConfigID + 0, -- IsSecuredLootGroupID + '', -- SecuredLootGroupPrefix + 'ImageName', -- SQLColumnName + dbo.ZeroGUID(), -- DefaultSortAttributeGUID + dbo.ZeroGUID(), -- ForeignKeyGUID + 1, -- IsRequired + 0, -- SpecialAttributeIndex + 1, -- IsCopiedWithPlan + 0, -- DisplayOrder + 0, -- isHidden + @ColumnType --AttributeType +) + +-- create area attribute +insert into ScoreAttribute +(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, IsHidden, AttributeType) +values ( + @DimensionGroupGUID, -- DimensionGUID + 'Area', -- FriendlyName + 231, -- ColumnType + 0, -- IsWrittenToDB + 0, -- IsKey + 0, -- IsSecuredLootID + 0, -- IsSecuredLootConfigID + 1, -- IsSecuredLootGroupID + 'SS', -- SecuredLootGroupPrefix + 'Area', -- SQLColumnName + dbo.ZeroGUID(), -- DefaultSortAttributeGUID + dbo.ZeroGUID(), -- ForeignKeyGUID + 1, -- IsRequired + 0, -- SpecialAttributeIndex + 1, -- IsCopiedWithPlan + 0, -- DisplayOrder + 0, -- isHidden + @ColumnType --AttributeType +) + +-- create section attribute +insert into ScoreAttribute +(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, IsHidden, AttributeType) +values ( + @DimensionGroupGUID, -- DimensionGUID + 'Section', -- FriendlyName + 231, -- ColumnType + 0, -- IsWrittenToDB + 0, -- IsKey + 0, -- IsSecuredLootID + 0, -- IsSecuredLootConfigID + 1, -- IsSecuredLootGroupID + 'SS', -- SecuredLootGroupPrefix + 'Section', -- SQLColumnName + dbo.ZeroGUID(), -- DefaultSortAttributeGUID + dbo.ZeroGUID(), -- ForeignKeyGUID + 1, -- IsRequired + 0, -- SpecialAttributeIndex + 1, -- IsCopiedWithPlan + 0, -- DisplayOrder + 0, -- isHidden + @ColumnType --AttributeType +) + +-- create id attribute +insert into ScoreAttribute +(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, IsHidden, AttributeType) +values ( + @DimensionGroupGUID, -- DimensionGUID + 'ID', -- FriendlyName + 231, -- ColumnType + 0, -- IsWrittenToDB + 0, -- IsKey + 0, -- IsSecuredLootID + 0, -- IsSecuredLootConfigID + 0, -- IsSecuredLootGroupID + '', -- SecuredLootGroupPrefix + 'ID', -- SQLColumnName + dbo.ZeroGUID(), -- DefaultSortAttributeGUID + dbo.ZeroGUID(), -- ForeignKeyGUID + 1, -- IsRequired + 0, -- SpecialAttributeIndex + 1, -- IsCopiedWithPlan + 0, -- DisplayOrder + 0, -- isHidden + @ColumnType --AttributeType +) + +-- create lootid attribute +insert into ScoreAttribute +(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, IsHidden, AttributeType) +values ( + @DimensionGroupGUID, -- DimensionGUID + 'LootID', -- FriendlyName + 167, -- ColumnType + 0, -- IsWrittenToDB + 1, -- IsKey + 1, -- IsSecuredLootID + 0, -- IsSecuredLootConfigID + 1, -- IsSecuredLootGroupID + '', -- SecuredLootGroupPrefix + 'LootID', -- SQLColumnName + dbo.ZeroGUID(), -- DefaultSortAttributeGUID + dbo.ZeroGUID(), -- ForeignKeyGUID + 1, -- IsRequired + 0, -- SpecialAttributeIndex + 1, -- IsCopiedWithPlan + 0, -- DisplayOrder + 0, -- isHidden + @ColumnType --AttributeType +) + +-- create parent attribute +insert into ScoreAttribute +(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, IsHidden, AttributeType) +values ( + @DimensionGroupGUID, -- DimensionGUID + 'Parent', -- FriendlyName + 231, -- ColumnType + 0, -- IsWrittenToDB + 0, -- IsKey + 0, -- IsSecuredLootID + 0, -- IsSecuredLootConfigID + 0, -- IsSecuredLootGroupID + '', -- SecuredLootGroupPrefix + 'Parent', -- SQLColumnName + dbo.ZeroGUID(), -- DefaultSortAttributeGUID + dbo.ZeroGUID(), -- ForeignKeyGUID + 1, -- IsRequired + 0, -- SpecialAttributeIndex + 1, -- IsCopiedWithPlan + 0, -- DisplayOrder + 0, -- isHidden + @ColumnType --AttributeType +) + +-- create parentlootid attribute +insert into ScoreAttribute +(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, IsHidden, AttributeType) +values ( + @DimensionGroupGUID, -- DimensionGUID + 'ParentLootID', -- FriendlyName + 231, -- ColumnType + 0, -- IsWrittenToDB + 0, -- IsKey + 0, -- IsSecuredLootID + 0, -- IsSecuredLootConfigID + 1, -- IsSecuredLootGroupID + '', -- SecuredLootGroupPrefix + 'ParentLootID', -- SQLColumnName + dbo.ZeroGUID(), -- DefaultSortAttributeGUID + dbo.ZeroGUID(), -- ForeignKeyGUID + 1, -- IsRequired + 0, -- SpecialAttributeIndex + 1, -- IsCopiedWithPlan + 0, -- DisplayOrder + 0, -- isHidden + @ColumnType --AttributeType +) + +-- create hierarchy +insert into ScoreHierarchy +(DimensionGUID, FriendlyName, PathAlias) +values (@DimensionGUID, 'System Sections', 'SS') + +-- get hierarchyguid +declare @HierarchyGUID uniqueidentifier +select @HierarchyGUID = HierarchyGUID from ScoreHierarchy where FriendlyName = 'System Sections' + +-- create parentlootid hierarchyattributelink +insert into ScoreHierarchyAttributeLink +(HierarchyGUID, AttributeGUID, DisplayAttributeGUID, SortOrder, IsDependentOnChild) +select + @HierarchyGUID, -- HierarchyGUID + A.AttributeGUID, -- AttributeGUID + DA.AttributeGUID, -- DisplayAttributeGUID + 1, -- SortOrder + 0 -- IsDependentOnChild +from ScoreAttribute A +inner join ScoreAttribute DA on DA.DimensionGroupGUID = A.DimensionGroupGUID +where A.FriendlyName = 'ParentLootID' + and DA.FriendlyName = 'Parent' + and A.DimensionGroupGUID = @DimensionGroupGUID + +-- create area hierarchyattributelink +insert into ScoreHierarchyAttributeLink +(HierarchyGUID, AttributeGUID, DisplayAttributeGUID, SortOrder, IsDependentOnChild) +select + @HierarchyGUID, -- HierarchyGUID + A.AttributeGUID, -- AttributeGUID + A.AttributeGUID, -- DisplayAttributeGUID + 2, -- SortOrder + 0 -- IsDependentOnChild +from ScoreAttribute A +where A.FriendlyName = 'Area' + and A.DimensionGroupGUID = @DimensionGroupGUID + +-- create section hierarchyattributelink +insert into ScoreHierarchyAttributeLink +(HierarchyGUID, AttributeGUID, DisplayAttributeGUID, SortOrder, IsDependentOnChild) +select + @HierarchyGUID, -- HierarchyGUID + A.AttributeGUID, -- AttributeGUID + A.AttributeGUID, -- DisplayAttributeGUID + 3, -- SortOrder + 0 -- IsDependentOnChild +from ScoreAttribute A +where A.FriendlyName = 'Section' + and A.DimensionGroupGUID = @DimensionGroupGUID + +-- create lootid hierarchyattributelink +insert into ScoreHierarchyAttributeLink +(HierarchyGUID, AttributeGUID, DisplayAttributeGUID, SortOrder, IsDependentOnChild) +select + @HierarchyGUID, -- HierarchyGUID + A.AttributeGUID, -- AttributeGUID + DA.AttributeGUID, -- DisplayAttributeGUID + 4, -- SortOrder + 0 -- IsDependentOnChild +from ScoreAttribute A +inner join ScoreAttribute DA on DA.DimensionGroupGUID = A.DimensionGroupGUID +where A.FriendlyName = 'LootID' + and DA.FriendlyName = 'FullName' + and A.DimensionGroupGUID = @DimensionGroupGUID + +-- create default hierarchyguid +update D + set D.DefaultHierarchyGUID = @HierarchyGUID +from ScoreDimension D +where D.DimensionGUID = @DimensionGUID + +-- create default keyguid +update D + set D.DefaultKeyGUID = A.AttributeGUID +from ScoreDimension D +inner join ScoreDimensionGroup G on G.DimensionGUID = D.DimensionGUID +inner join ScoreAttribute A on A.DimensionGroupGUID = G.DimensionGroupGUID +where A.FriendlyName = 'MemberGUID' + and D.DimensionGUID = @DimensionGUID + +-- create default lookupkeyguid +update D + set D.DefaultLookupKeyGUID = A.AttributeGUID +from ScoreDimension D +inner join ScoreDimensionGroup G on D.DimensionGUID = G.DimensionGUID +inner join ScoreAttribute A on A.DimensionGroupGUID = G.DimensionGroupGUID +where A.FriendlyName = 'FullName' + and D.DimensionGUID = @DimensionGUID + +-- update loot +exec procScoreSetDimensionSecurity30 @DimensionGUID + +print 'System Section dimension created.' +print 'View: [' + @schema + '].[viewDimSystemSection]' +print 'Dimension: System Sections (' + cast(@DimensionGUID as varchar(36)) +')' +print 'PermissionSet: ' + cast(@PermissionSetID as varchar(10)) + + +-- If rebuilding, fix simple security +if @IsForceRebuild = 1 begin + update S3SimplePermission set LootID = @DimensionGUID where LootID = @DeletedDimensionGUID +end + +exec procScoreAttributeSchemaUpdateAll; +GO + + +--------------------------------------------- + +-- dbo.procScoreEnsureUserProfileDimension +--========================================================================================== + + +CREATE proc [dbo].[procScoreEnsureUserProfileDimension] ( + @IsForceRebuild bit = 0 +) +as + + +declare @DeletedDimensionGUID uniqueidentifier; + +-- check existing +declare @cnt int +select @cnt = count(*) from ScoreDimension where FriendlyName = 'User Profiles' +if @cnt = 1 begin + + if @IsForceRebuild = 1 begin + print 'Forcing Rebuild...'; + select @DeletedDimensionGUID = DimensionGUID from ScoreDimension where FriendlyName = 'User Profiles'; + exec procScoreDeleteDimension @DeletedDimensionGUID, 1,1; + end + else begin + print 'User Profile dimension already exists.' + return + end + +end + +-- get schema +declare @schema varchar(10) +select @schema = name from sys.schemas where name = 'fw' +if @schema is null begin + select @schema = name from sys.schemas where name = 'data' + if @schema is null begin + set @schema = 'dbo' + end +end + +-- create view +declare @sql varchar(max) +set @sql = ' + create view [' + @schema + '].[viewDimUserProfile] + as + select + up.UserGUID as MemberGUID, + up.UserGUID, + up.UserName, + up.NameFull, + ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0) AS IsSysAdmin, + CAST (0 as bit) as IsDeleted, + dbo.ZeroGUID() as HistoryItemGUID, + CAST(UserGUID as varchar(36)) as LootID + from UserProfile up + left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = ''GEN - User Administrator'') + where up.IsDisabled = 0 + ' +exec(@sql) + +---------------------------------------- + + +-- get permissionsetid +declare @PermissionSetExists int +declare @PermissionSetID int +select @PermissionSetExists = COUNT(*) from S3PermissionSet where MetaForUpgrade='090D3991-D019-48A9-B501-0AC52402EDFC' + +if (@PermissionSetExists = 0) +begin + insert into dbo.S3PermissionSet (Name, MetaForUpgrade) + values ( + 'UP - ReadOnly', + '090D3991-D019-48A9-B501-0AC52402EDFC' + ) + + select @PermissionSetID = PermissionSetID from S3PermissionSet where MetaForUpgrade='090D3991-D019-48A9-B501-0AC52402EDFC' + insert into dbo.S3Permission (PermissionSetID, RoleID, Weight, ReadValue) + select + @PermissionSetID, + ur.RoleID, + 0, + CAST (1 as bit) + from UserRole ur +end + +select @PermissionSetID = PermissionSetID from S3PermissionSet where MetaForUpgrade='090D3991-D019-48A9-B501-0AC52402EDFC' + + +-- create dimension +insert into ScoreDimension +(FriendlyName, SQLTableAlias, DefaultKeyGUID, DefaultHierarchyGUID, DefaultLookupKeyGUID, IsSecured, PermissionSetID, SQLSchemaName, SQLObjectName, DefaultMemberGUID, IsSysAdminOnly, IsAllowMemberAdd, IsAllowMemberDelete) +values ( + 'User Profiles', -- FriendlyName + 'USERPROF', -- SQLTableAlias + dbo.ZeroGUID(), -- DefaultKeyGUID + dbo.ZeroGUID(), -- DefaultHierarchyGUID + dbo.ZeroGUID(), -- DefaultLookupKeyGUID + 1, -- IsSecured + @PermissionSetID, -- PermissionSetID + @schema, -- SQLSchemaName + 'viewDimUserProfile', -- SQLObjectName + dbo.ZeroGUID(), -- DefaultMemberGUID + 0, -- IsSysAdminOnly + 0, -- IsAllowMemberAdd + 0 -- IsAllowMemberDelete +) + +-- get dimensionguid +declare @DimensionGUID uniqueidentifier +select @DimensionGUID = DimensionGUID from ScoreDimension where FriendlyName = 'User Profiles' + + + +-- create dimension group +insert into ScoreDimensionGroup +(DimensionGUID, Name, Description, IsStock, SchemaName, ObjectName, DateModified) +values ( + @DimensionGUID, --DimensionGUID + 'User Profiles', --Name + '', --Description + 1, --IsStock + @schema, --SchemaName + 'viewDimUserProfile', --ObjectName + GETDATE() --DateModified +); + +declare @DimensionGroupGUID uniqueidentifier; +select @DimensionGroupGUID = G.DimensionGroupGUID from ScoreDimensionGroup G + inner join ScoreDimension D on D.DimensionGUID = G.DimensionGUID +where G.Name = 'User Profiles' and D.DimensionGUID = @DimensionGUID + +--update primary group +UPDATE ScoreDimension Set PrimaryGroupGUID = @DimensionGroupGUID + where DimensionGUID = @DimensionGUID + +--get COLUMN attribute type +declare @ColumnType int; +select @ColumnType = T.ScoreAttributeTypeID from ScoreAttributeType T where T.Name = 'Column'; + +-- create memberguid attribute +insert into ScoreAttribute +(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, AttributeType) +values ( + @DimensionGroupGUID, -- DimensionGroupGUID + 'MemberGUID', -- FriendlyName + 36, -- ColumnType + 0, -- IsWrittenToDB + 1, -- IsKey + 0, -- IsSecuredLootID + 0, -- IsSecuredLootConfigID + 0, -- IsSecuredLootGroupID + '', -- SecuredLootGroupPrefix + 'MemberGUID', -- SQLColumnName + dbo.ZeroGUID(), -- DefaultSortAttributeGUID + dbo.ZeroGUID(), -- ForeignKeyGUID + 1, -- IsRequired + 0, -- SpecialAttributeIndex + 1, -- IsCopiedWithPlan + 0, -- DisplayOrder + @ColumnType --AttributeType +) + +-- create userguid attribute +insert into ScoreAttribute +(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, AttributeType) +values ( + @DimensionGroupGUID, -- DimensionGroupGUID + 'UserGUID', -- FriendlyName + 36, -- ColumnType + 0, -- IsWrittenToDB + 1, -- IsKey + 0, -- IsSecuredLootID + 0, -- IsSecuredLootConfigID + 0, -- IsSecuredLootGroupID + '', -- SecuredLootGroupPrefix + 'UserGUID', -- SQLColumnName + dbo.ZeroGUID(), -- DefaultSortAttributeGUID + dbo.ZeroGUID(), -- ForeignKeyGUID + 1, -- IsRequired + 0, -- SpecialAttributeIndex + 1, -- IsCopiedWithPlan + 0, -- DisplayOrder + @ColumnType --AttributeType +) + +-- create NameFull attribute +insert into ScoreAttribute +(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, AttributeType) +values ( + @DimensionGroupGUID, -- DimensionGUID + 'NameFull', -- FriendlyName + 231, -- ColumnType + 0, -- IsWrittenToDB + 1, -- IsKey + 0, -- IsSecuredLootID + 0, -- IsSecuredLootConfigID + 0, -- IsSecuredLootGroupID + '', -- SecuredLootGroupPrefix + 'NameFull', -- SQLColumnName + dbo.ZeroGUID(), -- DefaultSortAttributeGUID + dbo.ZeroGUID(), -- ForeignKeyGUID + 1, -- IsRequired + 0, -- SpecialAttributeIndex + 1, -- IsCopiedWithPlan + 0, -- DisplayOrder + @ColumnType --AttributeType +) + +-- create UserName attribute +insert into ScoreAttribute +(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, AttributeType) +values ( + @DimensionGroupGUID, -- DimensionGUID + 'UserName', -- FriendlyName + 231, -- ColumnType + 0, -- IsWrittenToDB + 0, -- IsKey + 0, -- IsSecuredLootID + 0, -- IsSecuredLootConfigID + 0, -- IsSecuredLootGroupID + '', -- SecuredLootGroupPrefix + 'UserName', -- SQLColumnName + dbo.ZeroGUID(), -- DefaultSortAttributeGUID + dbo.ZeroGUID(), -- ForeignKeyGUID + 1, -- IsRequired + 0, -- SpecialAttributeIndex + 1, -- IsCopiedWithPlan + 0, -- DisplayOrder + @ColumnType --AttributeType +) + +-- create lootid attribute +insert into ScoreAttribute +(DimensionGroupGUID, FriendlyName, ColumnType, IsWrittenToDB, IsKey, IsSecuredLootID, IsSecuredLootConfigID, IsSecuredLootGroupID, SecuredLootGroupPrefix, SQLColumnName, DefaultSortAttributeGUID, ForeignKeyGUID, IsRequired, SpecialAttributeIndex, IsCopiedWithPlan, DisplayOrder, AttributeType) +values ( + @DimensionGroupGUID, -- DimensionGUID + 'LootID', -- FriendlyName + 167, -- ColumnType + 0, -- IsWrittenToDB + 1, -- IsKey + 1, -- IsSecuredLootID + 0, -- IsSecuredLootConfigID + 1, -- IsSecuredLootGroupID + '', -- SecuredLootGroupPrefix + 'LootID', -- SQLColumnName + dbo.ZeroGUID(), -- DefaultSortAttributeGUID + dbo.ZeroGUID(), -- ForeignKeyGUID + 1, -- IsRequired + 0, -- SpecialAttributeIndex + 1, -- IsCopiedWithPlan + 0, -- DisplayOrder + @ColumnType --AttributeType +) + + +-- create hierarchy +insert into ScoreHierarchy +(DimensionGUID, FriendlyName, PathAlias) +values (@DimensionGUID, 'User Profiles', 'USERPROF') + +-- get hierarchyguid +declare @HierarchyGUID uniqueidentifier +select @HierarchyGUID = HierarchyGUID from ScoreHierarchy where FriendlyName = 'User Profiles' + +-- create lootid/namefull hierarchyattributelink +insert into ScoreHierarchyAttributeLink +(HierarchyGUID, AttributeGUID, DisplayAttributeGUID, SortOrder, IsDependentOnChild) +select + @HierarchyGUID, -- HierarchyGUID + A.AttributeGUID, -- AttributeGUID + DA.AttributeGUID, -- DisplayAttributeGUID + 4, -- SortOrder + 0 -- IsDependentOnChild +from ScoreAttribute A +inner join ScoreAttribute DA on DA.DimensionGroupGUID = A.DimensionGroupGUID +where A.FriendlyName = 'LootID' + and DA.FriendlyName = 'NameFull' + and A.DimensionGroupGUID = @DimensionGroupGUID + +-- create default hierarchyguid +update D + set D.DefaultHierarchyGUID = @HierarchyGUID +from ScoreDimension D +where D.DimensionGUID = @DimensionGUID + +-- create default keyguid +update D + set D.DefaultKeyGUID = A.AttributeGUID +from ScoreDimension D +inner join ScoreDimensionGroup G on G.DimensionGUID = D.DimensionGUID +inner join ScoreAttribute A on A.DimensionGroupGUID = G.DimensionGroupGUID +where A.FriendlyName = 'UserGUID' + and D.DimensionGUID = @DimensionGUID + +-- create default lookupkeyguid +update D + set D.DefaultLookupKeyGUID = A.AttributeGUID +from ScoreDimension D +inner join ScoreDimensionGroup G on D.DimensionGUID = G.DimensionGUID +inner join ScoreAttribute A on A.DimensionGroupGUID = G.DimensionGroupGUID +where A.FriendlyName = 'NameFull' + and D.DimensionGUID = @DimensionGUID + +-- update loot +exec procScoreSetDimensionSecurity30 @DimensionGUID + +print 'User Profile dimension created.' +print 'View: [' + @schema + '].[viewDimUserProfile]' +print 'Dimension: User Profiles (' + cast(@DimensionGUID as varchar(36)) +')' +print 'PermissionSet: ' + cast(@PermissionSetID as varchar(10)) + + +-- If rebuilding, fix simple security +if @IsForceRebuild = 1 begin + update S3SimplePermission set LootID = @DimensionGUID where LootID = @DeletedDimensionGUID +end + +exec procScoreAttributeSchemaUpdateAll; +GO + + +--------------------------------------------- + +-- dbo.procScoreFillInCopy +CREATE proc [dbo].[procScoreFillInCopy] + @oldmodelguid uniqueidentifier, + @newmodelguid uniqueidentifier +as + +declare @higuid uniqueidentifier +set @higuid = NEWID() + +declare @cnt int +set @cnt = 0 + +--UPDATE EVERYTHING THAT IS ALREADY THERE +UPDATE ScoreFillin + SET + --PlaceholderSectionMemberGUID = OLD.PlaceholderSectionMemberGUID, + --PlaceholderIndex = OLD.PlaceholderIndex, + FillinMemberGUID = OLD.FillinMemberGUID, + FillinMemberName = OLD.FillinMemberName, + HistoryItemGUID = @higuid, + IsSystemSet = OLD.IsSystemSet +FROM ScoreFillin + inner join ScoreFillin OLD + on + OLD.PlaceholderSectionMemberGUID = ScoreFillin.PlaceholderSectionMemberGUID + and + OLD.PlaceholderIndex = ScoreFillin.PlaceholderIndex +where + ScoreFillin.ModelGUID = @newmodelguid + and OLD.ModelGUID = @oldmodelguid + and ScoreFIllin.FillinMemberGUID <> OLD.FillinMemberGUID + +set @cnt = @cnt + @@ROWCOUNT + +--INSERT ANYTHING THAT ISNT +insert into ScoreFillin(FillinGUID, ModelGUID, PlaceholderSectionMemberGUID, PlaceholderIndex, FillinMemberGUID, FillinMemberName, HistoryItemGUID, IsSystemSet) +select + NewID() as FillinGUID, @newmodelguid, PlaceholderSectionMemberGUID, PlaceholderIndex, FillinMemberGUID, FillinMemberName, @higuid, IsSystemSet +from + ScoreFillin +where + modelguid = @oldmodelguid + AND NOT EXISTS ( + select 1 + from + ScoreFillin NEW + where + NEW.PlaceholderSectionMemberGUID = ScoreFillin.PlaceholderSectionMemberGUID + and NEW.PlaceholderIndex = ScoreFillin.PlaceholderIndex + and NEW.ModelGUID = @newmodelguid + ) + +set @cnt = @cnt + @@ROWCOUNT + +if @cnt > 0 begin + + exec [procLogObjectHistoryItemGUIDObjectType] 'Strata.EMF.Biz.Data.ScoreDataHistoryItem, Strata.EMF.Biz', @newmodelguid, 'Copied fillins', @cnt, @higuid +end + --AND FillinGUID NOT IN + -- (select OLD.FillinGUID from ScoreFillin NEW + -- inner join ScoreFillin OLD on + -- OLD.PlaceholderSectionMemberGUID = NEW.PlaceholderSectionMemberGUID + -- and + -- OLD.PlaceholderIndex = NEW.PlaceholderIndex + -- where + -- NEW.ModelGUID = @newmodelguid + -- and OLD.ModelGUID = @oldmodelguid) + + +--fix "self" fillins +exec procScoreFillinSetByTemplateDefault @newmodelguid, 1 + +--refresh cache +exec [dbo].[procScoreFillinTableRefresh] @newmodelguid +GO + + +--------------------------------------------- + +-- dbo.procScoreFillInDelete +create proc [dbo].[procScoreFillInDelete] + @modelguid uniqueidentifier, + @phSectionMemberGUID uniqueidentifier, + @fillInMemberGUID uniqueidentifier +as + +delete from ScoreFillin +where + ModelGUID = @modelguid + and PlaceholderSectionMemberGUID = @phSectionMemberGUID + and FillinMemberGUID = @fillInMemberGUID +GO + + +--------------------------------------------- + +-- dbo.procScoreFillInInsert +CREATE proc [dbo].[procScoreFillInInsert] + @modelguid uniqueidentifier, + @phSectionMemberGUID uniqueidentifier, + @fillInMemberGUID uniqueidentifier +as + +declare @cnt int +declare @maxIndex int + +select + @cnt = SUM(case when fi.FillinMemberGUID = @fillInMemberGUID then 1 else 0 end), + @maxIndex = MAX(fi.PlaceholderIndex) +from + ScoreFillin fi +where + fi.ModelGUID = @modelguid + and fi.PlaceholderSectionMemberGUID = @phSectionMemberGUID + +if @cnt = 0 begin + insert into ScoreFillin ( ModelGUID, PlaceholderSectionMemberGUID, PlaceholderIndex, FillinMemberGUID ) + values (@modelguid, @phSectionMemberGUID, @maxIndex + 1, @fillInMemberGUID) +end +GO + + +--------------------------------------------- + +-- dbo.procScoreFillInSetByTemplate +CREATE proc [dbo].[procScoreFillInSetByTemplate] + @modelGUID uniqueidentifier, + @fillInTemplateName nvarchar(100) +as +--FITGUID PlaceholderSectionMemberGUID Auto-Fillin-Method +--x {my department} use current planmemberguid +--x {accounts} query: all accounts where attribute x = y sort by attribute z +--x {payors} specific member: {bcbs} + +-- Fill in Current Model fit items +declare @modelName nvarchar(max) +select @modelName = name from xplan where planguid = @modelGUID + +declare @higuid uniqueidentifier +set @higuid = NEWID() +declare @cnt int +set @cnt = 0 + +insert into ScoreFillin ( ModelGUID, PlaceholderSectionMemberGUID, PlaceholderIndex, FillinMemberGUID, FillinMemberName, HistoryItemGUID) +select + @modelGUID, + PlaceholderSectionMemberGUID, + isnull((select max(placeholderindex) from scorefillin fi where fi.modelguid = @modelguid and fi.placeholdersectionmemberguid = fit.PlaceholderSectionMemberGUID),0) + + PlaceholderSectionIndex, + @modelGUID, + left(isnull(@modelName,'Current Model') ,50), + @higuid +from + ScoreFillInTemplateItem fit (readuncommitted) +where + fillInTemplateName = @fillInTemplateName + and IsCurrentModelGUID = 1 + and not exists (select 1 from ScoreFillin fi where fi.ModelGUID = @modelGUID and fi.PlaceholderSectionMemberGUID = fit.PlaceholderSectionMemberGUID and fi.FillinMemberGUID = @modelGUID) + +set @cnt = @@ROWCOUNT + +--Fill in constant fit items +insert into ScoreFillin ( ModelGUID, PlaceholderSectionMemberGUID, PlaceholderIndex, FillinMemberGUID, FillinMemberName, HistoryItemGUID) +select + @modelGUID, + PlaceholderSectionMemberGUID, + isnull((select max(placeholderindex) from scorefillin fi where fi.modelguid = @modelguid and fi.placeholdersectionmemberguid = fit.PlaceholderSectionMemberGUID),0) + + PlaceholderSectionIndex, + ConstantMemberGUID, + 'Constant Member', --isnull(sdm.MemberName,'Constant Member' ), + @higuid +from + ScoreFillInTemplateItem fit (readuncommitted) + --left join data.viewScoreDimensionMember sdm on fit.ConstantMemberGUID = sdm.MemberGUID +where + fillInTemplateName = @fillInTemplateName + and IsConstantMemberGUID = 1 + and not exists (select 1 from ScoreFillin fi where fi.ModelGUID = @modelGUID and fi.PlaceholderSectionMemberGUID = fit.PlaceholderSectionMemberGUID and fi.FillinMemberGUID = ConstantMemberGUID) + +set @cnt = @cnt + @@ROWCOUNT + +declare @PlaceholderSectionMemberGUID uniqueidentifier +declare @query varchar(max) + +declare crsFITQ CURSOR LOCAL READ_ONLY FAST_FORWARD FOR + select + PlaceholderSectionMemberGUID, + Query + from + ScoreFillInTemplateItem (readuncommitted) + where + fillInTemplateName = @fillInTemplateName + and isquery = 1 + + +open crsFITQ; + +declare @minrow int + +FETCH NEXT FROM crsFITQ into @PlaceholderSectionMemberGUID, @query +WHILE (@@FETCH_STATUS = 0) + BEGIN + create table #members (rownum int, memberguid uniqueidentifier, memberName nvarchar(max)) + + set @query = REPLACE(@query, '{modelguid}',@modelguid) + + insert into #members (rownum, memberguid, memberName) + exec (@query) + + select @minrow = MIN(rownum) from #members + if @minrow = 1 begin + update #members set rownum = rownum - 1 + end + + insert into ScoreFillin ( ModelGUID, PlaceholderSectionMemberGUID, PlaceholderIndex, FillinMemberGUID, FillinMemberName, HistoryItemGUID) + select + @modelGUID, + @PlaceholderSectionMemberGUID, + isnull((select max(placeholderindex) from scorefillin fi where fi.modelguid = @modelguid and fi.placeholdersectionmemberguid = @PlaceholderSectionMemberGUID),0) + + rownum, + memberguid, + left(memberName,50), + @higuid + from + #members fit + where + not exists (select 1 from ScoreFillin fi where fi.ModelGUID = @modelGUID and fi.PlaceholderSectionMemberGUID = @PlaceholderSectionMemberGUID and fi.FillinMemberGUID = fit.MemberGUID) + order by + rownum + + set @cnt = @cnt + @@ROWCOUNT + drop table #members + + FETCH NEXT FROM crsFITQ into @PlaceholderSectionMemberGUID, @query + END +close crsFITQ; +DEALLOCATE crsFITQ; + +declare @msg Nvarchar(max) +set @msg = 'Set Fillin Template ' + @fillInTemplateName + +if @cnt > 0 begin + exec [procLogObjectHistoryItemGUIDObjectType] 'Strata.EMF.Biz.Data.ScoreDataHistoryItem, Strata.EMF.Biz', @modelguid, @msg, @cnt, @higuid +end + +--select +-- @isQuery = IsQuery +--from +-- ScoreFillInTemplateItem +--where +-- FillInTemplateItemID = @fillInTemplateItemID + +exec [dbo].[procScoreFillinTableRefresh] @modelGUID +GO + + +--------------------------------------------- + +-- dbo.procScoreFillInSetByTemplateJustSelf +CREATE proc [dbo].[procScoreFillInSetByTemplateJustSelf] + @modelGUID uniqueidentifier, + @fillInTemplateName nvarchar(max) +as +--FITGUID PlaceholderSectionMemberGUID Auto-Fillin-Method +--x {my department} use current planmemberguid +--x {accounts} query: all accounts where attribute x = y sort by attribute z +--x {payors} specific member: {bcbs} + + +--delete existing iscurrentmodelguid = 1 fillins for this model +delete fi from ScoreFillin fi +where + ModelGUID = @modelGUID + and exists ( + select 1 + from + ScoreFillInTemplateItem fit + where + fit.IsCurrentModelGUID = 1 + and fit.PlaceholderSectionMemberGUID = fi.PlaceholderSectionMemberGUID + and fit.PlaceholderSectionIndex = fi.PlaceholderIndex + ) + +declare @modelName nvarchar(max) +select @modelName = left(name, 50) from Xplan where PlanGUID = @modelGUID + +declare @higuid uniqueidentifier +set @higuid = NEWID() + +declare @cnt int + +-- Fill in Current Model fit items +insert into ScoreFillin ( ModelGUID, PlaceholderSectionMemberGUID, PlaceholderIndex, FillinMemberGUID, FillinMemberName, HistoryItemGUID) +select + @modelGUID, + PlaceholderSectionMemberGUID, + isnull((select max(placeholderindex) from scorefillin fi where fi.modelguid = @modelguid and fi.placeholdersectionmemberguid = fit.PlaceholderSectionMemberGUID),0) + + PlaceholderSectionIndex, + @modelGUID, + isnull(@modelName,'Current Model'), + @higuid +from + ScoreFillInTemplateItem fit +where + fillInTemplateName = @fillInTemplateName + and IsCurrentModelGUID = 1 + and not exists (select 1 from ScoreFillin fi where fi.ModelGUID = @modelGUID and fi.PlaceholderSectionMemberGUID = fit.PlaceholderSectionMemberGUID and fi.FillinMemberGUID = @modelGUID) + +set @cnt = @@ROWCOUNT + +if @cnt > 0 begin + exec [procLogObjectHistoryItemGUIDObjectType] 'Strata.EMF.Biz.Data.ScoreDataHistoryItem, Strata.EMF.Biz', @modelguid,'Set Self Fillins',@cnt,@higuid +end + +exec [dbo].[procScoreFillinTableRefresh] @modelGUID +GO + + +--------------------------------------------- + +-- dbo.procScoreFillInSetManyClearThoseBeingSet +--Forward + + +CREATE proc [dbo].[procScoreFillInSetManyClearThoseBeingSet] + @iguid uniqueidentifier +as + DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20)); + + + WITH tgt (ModelGUID, + PlaceholderSectionMemberGUID, + PlaceholderIndex, + FillInMemberGUID, + FillinMemberName) + AS + ( + select + ModelGUID, + PlaceholderSectionMemberGUID , + PlaceholderIndex, + FillInMemberGUID, + FillinMemberName + from + ScoreFillin + where + ModelGUID in (select ModelGUID from ScoreFillinSetManyStaging where InstanceGUID = @iguid) + and PlaceholderSectionMemberGUID in (select PlaceholderSectionMemberGUID from ScoreFillinSetManyStaging where InstanceGUID=@iguid) --Changed + and IsDeleted = 0 + ) + MERGE tgt as target + USING( + select + ModelGUID, + PlaceholderSectionMemberGUID, + row_number() over (partition by modelguid, placeholdersectionmemberguid order by sortorder) - 1 as PlaceholderIndex, + FillInMemberGUID, + FillinMemberName + from + ( + select + modelguid, + placeholdersectionmemberguid, + min(sortorder)as SortOrder, + fillinmemberguid, + min(fillinmembername) as fillinmembername + from + ScoreFillinSetManyStaging + where InstanceGUID=@iguid -- Changed + group by + modelguid, + placeholdersectionmemberguid, + FillInMemberGUID, + MakeUnique + ) src + ) as source + ON ( + target.ModelGUID = source.ModelGUID + and target.PlaceholderSectionMemberGUID = source.PlaceholderSectionMemberGUID + and target.PlaceholderIndex = source.PlaceholderIndex + and target.FillInMemberGUID = source.FillInMemberGUID + ) + WHEN MATCHED AND target.FillinMemberName <> source.FillinMemberName THEN + UPDATE SET target.FillinMemberName = source.FillinMemberName + WHEN NOT MATCHED BY TARGET THEN + INSERT ( ModelGUID, + PlaceholderSectionMemberGUID, + PlaceholderIndex, + FillInMemberGUID, + FillinMemberName) + VALUES ( + ModelGUID, + PlaceholderSectionMemberGUID, + PlaceholderIndex, + FillInMemberGUID, + FillinMemberName) + WHEN NOT MATCHED BY SOURCE THEN + DELETE --UPDATE SET target.IsDeleted = 1 + OUTPUT $action INTO @SummaryOfChanges; + + select Change, COUNT(*) from @SummaryOfChanges group by change + +RETURN +GO + + +--------------------------------------------- + +-- dbo.procScoreFillInSetManyClearThoseBeingSetNoDeletes +create proc [dbo].[procScoreFillInSetManyClearThoseBeingSetNoDeletes] + @iguid uniqueidentifier +as + DECLARE @SummaryOfChanges TABLE(Change VARCHAR(20)); + + + WITH tgt (ModelGUID, + PlaceholderSectionMemberGUID, + PlaceholderIndex, + FillInMemberGUID, + FillinMemberName) + AS + ( + select + ModelGUID, + PlaceholderSectionMemberGUID , + PlaceholderIndex, + FillInMemberGUID, + FillinMemberName + from + ScoreFillin + where + ModelGUID in (select ModelGUID from ScoreFillinSetManyStaging where InstanceGUID = @iguid) + and PlaceholderSectionMemberGUID in (select PlaceholderSectionMemberGUID from ScoreFillinSetManyStaging where InstanceGUID=@iguid) --Changed + and IsDeleted = 0 + ) + MERGE tgt as target + USING( + select + ModelGUID, + PlaceholderSectionMemberGUID, + row_number() over (partition by modelguid, placeholdersectionmemberguid order by sortorder) - 1 as PlaceholderIndex, + FillInMemberGUID, + FillinMemberName + from + ( + select + modelguid, + placeholdersectionmemberguid, + min(sortorder)as SortOrder, + fillinmemberguid, + min(fillinmembername) as fillinmembername + from + ScoreFillinSetManyStaging + where InstanceGUID=@iguid -- Changed + group by + modelguid, + placeholdersectionmemberguid, + FillInMemberGUID, + MakeUnique + ) src + ) as source + ON ( + target.ModelGUID = source.ModelGUID + and target.PlaceholderSectionMemberGUID = source.PlaceholderSectionMemberGUID + and target.PlaceholderIndex = source.PlaceholderIndex + and target.FillInMemberGUID = source.FillInMemberGUID + ) + WHEN MATCHED AND target.FillinMemberName <> source.FillinMemberName THEN + UPDATE SET target.FillinMemberName = source.FillinMemberName + WHEN NOT MATCHED BY TARGET THEN + INSERT ( ModelGUID, + PlaceholderSectionMemberGUID, + PlaceholderIndex, + FillInMemberGUID, + FillinMemberName) + VALUES ( + ModelGUID, + PlaceholderSectionMemberGUID, + PlaceholderIndex, + FillInMemberGUID, + FillinMemberName) + OUTPUT $action INTO @SummaryOfChanges; + + select Change, COUNT(*) from @SummaryOfChanges group by change +GO + + +--------------------------------------------- + +-- dbo.procScoreFillinCompressIndices +CREATE proc [dbo].[procScoreFillinCompressIndices] + @modelguid uniqueidentifier +as +select + fi.FillinGUID, + ROW_NUMBER() over (partition by fi.modelguid, fi.placeholdersectionmemberguid order by fi.placeholderindex ) -1 as PlaceholderIndex + into #CompressedIndices +from + ScoreFillin fi +where + fi.ModelGUID = @modelguid + +declare @higuid uniqueidentifier +set @higuid = NEWID() + +declare @cnt int + +update + ScoreFillin +set + PlaceholderIndex = CI.PlaceholderIndex, + HistoryItemGUID = @higuid +from + ScoreFillin + inner join #CompressedIndices ci on ScoreFillin.FillinGUID = ci.fillInGUID +where + ScoreFillin.PlaceholderIndex <> ci.PlaceholderIndex + +set @cnt = @@ROWCOUNT + +drop table #CompressedIndices + +if @cnt > 0 begin + exec [procLogObjectHistoryItemGUIDObjectType] 'Strata.EMF.Biz.Data.ScoreDataHistoryItem, Strata.EMF.Biz', @modelguid, 'Compressed Fillin Indices', @cnt, @higuid +end +GO + + +--------------------------------------------- + +-- dbo.procScoreFillinExclusivityLogMemberNameRefresh +CREATE proc [dbo].[procScoreFillinExclusivityLogMemberNameRefresh] + @modelGuidCsv nvarchar(max), + @isDebug bit = 0 +AS + DECLARE @dimobj nvarchar(max) + DECLARE @keyname nvarchar(64) + DECLARE @sql nvarchar(max) + +DECLARE @DimensionsByModel TABLE(dimobj varchar(max), keyname nvarchar(64)) + +INSERT INTO @DimensionsByModel (dimobj, keyname) +SELECT DISTINCT sa.DimensionSQLObjectExpression, dk.SQLColumnName +FROM [dbo].[viewScoreAttribute] sa + INNER JOIN [dbo].[ScoreDimension] d on d.DimensionGUID = sa.DimensionGUID + INNER JOIN [dbo].[viewScoreAttribute] dk on dk.AttributeGUID = d.DefaultLookupKeyGUID and dk.SQLColumnName like '%Name' +WHERE EXISTS( + SELECT TOP 1 1 + FROM [dbo].[ScoreCompositeLink] cl WITH (readuncommitted) + INNER JOIN [dbo].[EMFModelTemplateLinkSource] ls WITH (readuncommitted) ON ls.ParentScoreCompositeTableGUID = cl.CompositeGUID + INNER JOIN [dbo].[XPlan] p WITH (readuncommitted) ON p.ModelTemplateGUID = ls.ModelTemplateGUID and p.PlanGUID in(SELECT GUID FROM dbo.ConvertCSGuidsToTable(@modelGuidCsv, ',')) + WHERE + cl.Key2GUID = sa.AttributeGUID + AND cl.IsPlaceholder = 1 + ) + +DECLARE @COUNT INT +SELECT @COUNT = COUNT(1) FROM @DimensionsByModel + +WHILE(@COUNT > 0) + BEGIN + SELECT TOP 1 @dimobj = dimobj, @keyname = keyname FROM @DimensionsByModel + + set @sql = ' + UPDATE SF + SET Message = REPLACE(SF.Message, SF.FillinMemberGUID, D.' + @keyname + ') + FROM ScoreFillinExclusivityLogItem SF + INNER JOIN '+ @dimobj + ' D ON D.MemberGUID = SF.FillinMemberGUID + WHERE + SF.ModelGUID IN (SELECT guid FROM dbo.ConvertCSGuidsToTable(''' + @modelGuidCsv + ''', '','')) + AND D.' + @keyname + ' != '''' + AND SF.Message LIKE ''%''+CAST(SF.FillinMemberGUID AS nvarchar(36))+''%'' +' + + IF (@isDebug = 0) BEGIN + EXEC(@sql) + END ELSE BEGIN + PRINT @sql + END + + SET @COUNT -= 1 + + DELETE FROM @DimensionsByModel + WHERE dimobj = @dimobj AND keyname = @keyname + END +GO + + +--------------------------------------------- + +-- dbo.procScoreFillinMemberNameRefresh +CREATE proc dbo.procScoreFillinMemberNameRefresh + @modelGuidCsv nvarchar(max) = '', + @isDebug bit = 0 +as + set nocount on + + declare @dimobj nvarchar(450) + declare @keyname nvarchar(450) + declare @sql nvarchar(max) + + if (@modelGuidCsv = '') begin + if(exists(select 1 from [dbo].[ScoreFillin] with (readuncommitted) where FillinMemberName in('', 'default'))) begin + declare crsDimensions cursor fast_forward for + select distinct + sa.DimensionSQLObjectExpression, + dk.SQLColumnName + from + [dbo].[viewScoreAttribute] sa + inner join [dbo].[ScoreDimension] d on d.DimensionGUID = sa.DimensionGUID + inner join [dbo].[viewScoreAttribute] dk on dk.AttributeGUID = d.DefaultLookupKeyGUID and dk.SQLColumnName like '%Name' + where + exists(select 1 from [dbo].[ScoreCompositeLink] cl with (readuncommitted) where cl.Key2GUID = sa.AttributeGUID and cl.IsPlaceholder = 1) + + open crsDimensions + fetch next from crsDimensions into @dimobj, @keyname + + while(@@fetch_status = 0) begin + set @sql = ' + update SF set SF.FillinMemberName = D.' + @keyname + ' + from + ScoreFillin SF + inner join ' + @dimobj + ' D on D.MemberGUID = SF.FillinMemberGUID + where + SF.FillinMemberName in('''', ''default'') + ' + if (@isDebug = 0) begin + exec(@sql) + end else begin + print @sql + end + + set @sql = ' + update SF set SF.FillinMemberName = D.' + @keyname + ' + from + ScoreFillinRefreshLogItem SF + inner join ' + @dimobj + ' D on D.MemberGUID = SF.FillinMemberGUID + where + SF.FillinMemberName in('''', ''default'') + ' + if (@isDebug = 0) begin + exec(@sql) + end else begin + print @sql + end + + fetch next from crsDimensions into @dimobj, @keyname + end + + close crsDimensions + deallocate crsDimensions + end + + --handle self fillins specially + if (@isDebug = 0) begin + update sf set sf.FillinMemberName = xp.Name + from + [dbo].[ScoreFillin] sf + inner join [dbo].[XPlan] xp with (readuncommitted) on xp.PlanGUID = sf.ModelGUID and sf.FillinMemberGUID = xp.PlanGUID + where + sf.FillinMemberName <> xp.Name + and xp.Name != '' + end else begin + print ' + update sf set sf.FillinMemberName = xp.Name + from + [dbo].[ScoreFillin] sf + inner join [dbo].[XPlan] xp with (readuncommitted) on xp.PlanGUID = sf.ModelGUID and sf.FillinMemberGUID = xp.PlanGUID + where + sf.FillinMemberName <> xp.Name + and xp.Name != ''''' + end + end else begin + if(exists(select 1 from [dbo].[ScoreFillin] with (readuncommitted) where FillinMemberName in ('', 'default') and ModelGUID in(select guid from dbo.ConvertCSGuidsToTable(@modelGuidCsv, ',')))) begin + declare crsDimensionsByModel cursor fast_forward for + select distinct + sa.DimensionSQLObjectExpression, + dk.SQLColumnName + from + [dbo].[viewScoreAttribute] sa + inner join [dbo].[ScoreDimension] d on d.DimensionGUID = sa.DimensionGUID + inner join [dbo].[viewScoreAttribute] dk on dk.AttributeGUID = d.DefaultLookupKeyGUID and dk.SQLColumnName like '%Name' + where + exists( + select 1 + from + [dbo].[ScoreCompositeLink] cl with (readuncommitted) + inner join [dbo].[EMFModelTemplateLinkSource] ls with (readuncommitted) on ls.ParentScoreCompositeTableGUID = cl.CompositeGUID + inner join [dbo].[XPlan] p with (readuncommitted) on p.ModelTemplateGUID = ls.ModelTemplateGUID and p.PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(@modelGuidCsv, ',')) + where + cl.Key2GUID = sa.AttributeGUID + and cl.IsPlaceholder = 1 + ) + + open crsDimensionsByModel + fetch next from crsDimensionsByModel into @dimobj, @keyname + + while(@@fetch_status = 0) begin + set @sql = ' + update SF set SF.FillinMemberName = D.' + @keyname + ' + from + ScoreFillin SF + inner join ' + @dimobj + ' D on D.MemberGUID = SF.FillinMemberGUID + where + SF.FillinMemberName in('''', ''default'') + and ModelGUID in(select guid from dbo.ConvertCSGuidsToTable(''' + @modelGuidCsv + ''', '','')) + ' + if (@isDebug = 0) begin + exec(@sql) + end else begin + print @sql + end + + set @sql = ' + update SF set SF.FillinMemberName = D.' + @keyname + ' + from + ScoreFillinRefreshLogItem SF + inner join ' + @dimobj + ' D on D.MemberGUID = SF.FillinMemberGUID + where + SF.FillinMemberName in('''', ''default'') + and ModelGUID in(select guid from dbo.ConvertCSGuidsToTable(''' + @modelGuidCsv + ''', '','')) + ' + if (@isDebug = 0) begin + exec(@sql) + end else begin + print @sql + end + + fetch next from crsDimensionsByModel into @dimobj, @keyname + end + + close crsDimensionsByModel + deallocate crsDimensionsByModel + end + + --handle self fillins specially + if (@isDebug = 0) begin + update sf set sf.FillinMemberName = xp.Name + from + [dbo].[ScoreFillin] sf + inner join [dbo].[XPlan] xp with (readuncommitted) on xp.PlanGUID = sf.ModelGUID and sf.FillinMemberGUID = xp.PlanGUID + where + sf.FillinMemberName <> xp.Name + and xp.Name != '' + and xp.PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(@modelGuidCsv, ',')) + end else begin + print ' + update sf set sf.FillinMemberName = xp.Name + from + [dbo].[ScoreFillin] sf + inner join [dbo].[XPlan] xp with (readuncommitted) on xp.PlanGUID = sf.ModelGUID and sf.FillinMemberGUID = xp.PlanGUID + where + sf.FillinMemberName <> xp.Name + and xp.Name != '''' + and xp.PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(@modelGuidCsv, '',''))' + end + end +GO + + +--------------------------------------------- + +-- dbo.procScoreFillinSetByTemplateDefault +CREATE proc [dbo].[procScoreFillinSetByTemplateDefault] + @planguid uniqueidentifier + ,@isCopy as bit = 0 +as + +declare @fillInTemplateName nvarchar(100) +select @fillInTemplateName = scoredefaultfillInTemplateName from PlanType +where PlanTypeGUID = (select PlanTypeGUID from XPlan where PlanGUID = @planguid) + +if @fillInTemplateName is null return +if @fillInTemplateName = '' return + +if @isCopy = 1 begin + exec procScoreFillInSetByTemplateJustSelf @planguid, @fillInTemplateName +end else begin + exec procScoreFillInSetByTemplate @planguid, @fillInTemplateName +end +GO + + +--------------------------------------------- + +-- dbo.procScoreFillinTableAudit +CREATE proc [dbo].[procScoreFillinTableAudit] + @modelGUID uniqueidentifier, + @isAutoFixing bit = 1 +as + set nocount on + + declare @rowid int = -1 + if((select count(*) from [data].[ScoreFillinCacheAudit] (readuncommitted)) > 0) begin + select @rowid = max(RowID) from [data].[ScoreFillinCacheAudit] (readuncommitted) + end + + declare @tableName nvarchar(150) + declare @phKeyName nvarchar(100) + declare @phDimTable nvarchar(450) + declare @fillinKeyName nvarchar(100) + declare @fillinDimTable nvarchar(450) + declare @fillinDimGUID uniqueidentifier + declare crsInfo cursor fast_forward for + select distinct + 'ScoreFillin_' + replace(A2.DimensionName, ' ', '') as TableName, + A1.SQLColumnName as PHKeyName, + A1.DimensionSQLObjectExpression as PHDimTable, + A2.SQLColumnName as FillinKeyName, + A2.DimensionSQLObjectExpression as FillinDimTable, + A2.DimensionGUID as FillinDimGUID + from + ScoreCompositeLink CL (readuncommitted) + inner join viewScoreAttribute A1 on A1.AttributeGUID = CL.Key1GUID + inner join viewScoreAttribute A2 on A2.AttributeGUID = CL.Key2GUID + inner join EMFModelTemplateLinkSource LS (readuncommitted) on LS.ParentScoreCompositeTableGUID = CL.CompositeGUID + inner join EMFModelTemplate MT (readuncommitted) on MT.ModelTemplateGUID = LS.ModelTemplateGUID + inner join sys.tables t on t.Name = 'ScoreFillin_' + replace(A2.DimensionName, ' ', '') + inner join dbo.XPlan p on p.ModelTemplateGUID = MT.ModelTemplateGUID + where + CL.IsPlaceholder = 1 + and MT.IsScoreFillinAdvancedMode = 1 + and p.PlanGUID = @modelGUID + + open crsInfo + fetch next from crsInfo into @tableName, @phKeyName, @phDimTable, @fillinKeyName, @fillinDimTable, @fillinDimGUID + + declare @sql nvarchar(max) + while(@@FETCH_STATUS = 0) begin + set @sql = ' + insert into data.ScoreFillinCacheAudit ([FillinGUID], [ModelGUID], [DimensionGUID], [Problem]) + select [FillinGUID], [ModelGUID], ''' + cast(@fillinDimGUID as nvarchar(36)) + ''', ''ScoreFillin exists, ' + @tableName + ' missing'' + from ScoreFillin (readuncommitted) + where FillinMemberGUID in (select fk.MemberGUID from ' + @fillinDimTable + ' fk) + and FillinGUID not in(select c.FillinGUID from [data].[' + @tableName + '] c (readuncommitted)) + and ModelGUID = ''' + cast(@modelGUID as nvarchar(36)) + '''; + + insert into data.ScoreFillinCacheAudit ([FillinGUID], [ModelGUID], [DimensionGUID], [Problem]) + select [FillinGUID], [ModelGUID], ''' + cast(@fillinDimGUID as nvarchar(36)) + ''', ''ScoreFillin missing, ' + @tableName + ' exists'' + from [data].[' + @tableName + '] (readuncommitted) + where FillinMemberGUID in (select fk.MemberGUID from ' + @fillinDimTable + ' fk) + and FillinGUID not in(select l.FillinGUID from ScoreFillin l (readuncommitted)) + and ModelGUID = ''' + cast(@modelGUID as nvarchar(36)) + '''; + + insert into data.ScoreFillinCacheAudit ([FillinGUID], [ModelGUID], [DimensionGUID], [Problem]) + select fi.[FillinGUID], fi.[ModelGUID], ''' + cast(@fillinDimGUID as nvarchar(36)) + ''', ''ScoreFillin order '' + cast(fi.PlaceholderIndex as nvarchar(8)) + '', ' + @tableName + ' '' + cast(c.PlaceholderIndex as nvarchar(8)) + from ScoreFillin fi (readuncommitted) + inner join [data].[' + @tableName + '] c (readuncommitted) on c.FillinGUID = fi.FillinGUID + where fi.PlaceholderIndex != c.PlaceholderIndex + and fi.ModelGUID = ''' + cast(@modelGUID as nvarchar(36)) + '''; +' + exec(@sql) + + fetch next from crsInfo into @tableName, @phKeyName, @phDimTable, @fillinKeyName, @fillinDimTable, @fillinDimGUID + end + + close crsInfo + deallocate crsInfo + + if ((@isAutoFixing = 1) and (exists(select 1 from [data].[ScoreFillinCacheAudit] (readuncommitted) where RowID > @rowid and ModelGUID = @modelGUID))) begin + exec [dbo].[procScoreFillinTableRefresh] @modelGUID + exec [dbo].[procInvalidateModelWorkbookCache] @modelGUID, 0, 0, 'procScoreFillinTableAudit' + end +GO + + +--------------------------------------------- + +-- dbo.procScoreFillinTableAuditAll +/************************************************************ +** Author: gforeman +** Create Date: 2012 +** Description: +** This proc serves as a safeguard against fillin +** cache tables getting out of sync with ScoreFillin. +** Theoretically, if all Jazz functions and custom scripts +** are setup and working correctly, this should be +** unnecessary. But if anything forgets to refresh +** cache after updating members, you have problems. +** Usage: +** Run and then inspect the returned contents of +** data.ScoreFillinCacheAudit for a listing of issues that +** were encountered. +*************************************************************/ +CREATE proc procScoreFillinTableAuditAll + @isAutoFixing bit = 0 +as + set nocount on + + declare @rowid int = -1 + if((select count(*) from [data].[ScoreFillinCacheAudit] (readuncommitted)) > 0) begin + select @rowid = max(RowID) from [data].[ScoreFillinCacheAudit] (readuncommitted) + end + + declare @tableName nvarchar(150) + declare @phKeyName nvarchar(100) + declare @phDimTable nvarchar(450) + declare @fillinKeyName nvarchar(100) + declare @fillinDimTable nvarchar(450) + declare @fillinDimGUID uniqueidentifier + declare crsInfo cursor fast_forward for + select distinct + 'ScoreFillin_' + replace(A2.DimensionName, ' ', '') as TableName, + A1.SQLColumnName as PHKeyName, + A1.DimensionSQLObjectExpression as PHDimTable, + A2.SQLColumnName as FillinKeyName, + A2.DimensionSQLObjectExpression as FillinDimTable, + A2.DimensionGUID as FillinDimGUID + from + ScoreCompositeLink CL (readuncommitted) + inner join viewScoreAttribute A1 on A1.AttributeGUID = CL.Key1GUID + inner join viewScoreAttribute A2 on A2.AttributeGUID = CL.Key2GUID + inner join EMFModelTemplateLinkSource LS (readuncommitted) on LS.ParentScoreCompositeTableGUID = CL.CompositeGUID + inner join EMFModelTemplate MT (readuncommitted) on MT.ModelTemplateGUID = LS.ModelTemplateGUID + inner join sys.tables t on t.Name = 'ScoreFillin_' + replace(A2.DimensionName, ' ', '') + where + CL.IsPlaceholder = 1 + and MT.IsScoreFillinAdvancedMode = 1 + + open crsInfo + fetch next from crsInfo into @tableName, @phKeyName, @phDimTable, @fillinKeyName, @fillinDimTable, @fillinDimGUID + + declare @sql nvarchar(max) + while(@@FETCH_STATUS = 0) begin + set @sql = ' + insert into data.ScoreFillinCacheAudit ([FillinGUID], [ModelGUID], [DimensionGUID], [Problem]) + select [FillinGUID], [ModelGUID], ''' + cast(@fillinDimGUID as nvarchar(36)) + ''', ''ScoreFillin exists, ' + @tableName + ' missing'' + from ScoreFillin (readuncommitted) + where FillinMemberGUID in (select fk.MemberGUID from ' + @fillinDimTable + ' fk) + and FillinGUID not in(select c.FillinGUID from [data].[' + @tableName + '] c (readuncommitted)) + and ModelGUID in(select p.PlanGUID from XPlan p (readuncommitted) inner join EMFModelTemplate t (readuncommitted) on t.ModelTemplateGUID = p.ModelTemplateGUID and t.IsScoreFillinAdvancedMode = 1); + + insert into data.ScoreFillinCacheAudit ([FillinGUID], [ModelGUID], [DimensionGUID], [Problem]) + select [FillinGUID], [ModelGUID], ''' + cast(@fillinDimGUID as nvarchar(36)) + ''', ''ScoreFillin missing, ' + @tableName + ' exists'' + from [data].[' + @tableName + '] (readuncommitted) + where FillinMemberGUID in (select fk.MemberGUID from ' + @fillinDimTable + ' fk) + and FillinGUID not in(select l.FillinGUID from ScoreFillin l (readuncommitted)) + and ModelGUID in(select p.PlanGUID from XPlan p (readuncommitted) inner join EMFModelTemplate t (readuncommitted) on t.ModelTemplateGUID = p.ModelTemplateGUID and t.IsScoreFillinAdvancedMode = 1); + + insert into data.ScoreFillinCacheAudit ([FillinGUID], [ModelGUID], [DimensionGUID], [Problem]) + select fi.[FillinGUID], fi.[ModelGUID], ''' + cast(@fillinDimGUID as nvarchar(36)) + ''', ''ScoreFillin order '' + cast(fi.PlaceholderIndex as nvarchar(8)) + '', ' + @tableName + ' '' + cast(c.PlaceholderIndex as nvarchar(8)) + from ScoreFillin fi (readuncommitted) + inner join [data].[' + @tableName + '] c (readuncommitted) on c.FillinGUID = fi.FillinGUID + where fi.PlaceholderIndex != c.PlaceholderIndex; +' + exec(@sql) + + fetch next from crsInfo into @tableName, @phKeyName, @phDimTable, @fillinKeyName, @fillinDimTable, @fillinDimGUID + end + + close crsInfo + deallocate crsInfo + + if (@isAutoFixing = 1) begin + declare @dimensionGUID uniqueidentifier + declare crsDimensions cursor fast_forward for select distinct DimensionGUID from [data].[ScoreFillinCacheAudit] (readuncommitted) where RowID > @rowid + open crsDimensions + fetch next from crsDimensions into @dimensionGUID + while(@@fetch_status = 0) begin + exec [dbo].[procScoreFillinTableRefreshByDimension] @dimensionGUID + fetch next from crsDimensions into @dimensionGUID + end + close crsDimensions + deallocate crsDimensions + + declare @invwhere nvarchar(max) + set @invwhere = 'PlanGUID in(select ModelGUID from [data].[ScoreFillinCacheAudit] (readuncommitted) where RowID > ' + cast(@rowid as nvarchar(16)) + ')' + exec [dbo].[procInvalidateModelWorkbookCacheByWhereClause] @invwhere, 0, 'procScoreFillinTableAuditAll' + end + + select * from [data].[ScoreFillinCacheAudit] where RowID > @rowid +GO + + +--------------------------------------------- + +-- dbo.procScoreFillinTableRebuild +CREATE proc [dbo].[procScoreFillinTableRebuild] + @phDimensionGUID uniqueidentifier, + @fillinDimensionGUID uniqueidentifier, + @isDebug bit = 0 +as + set nocount on + + declare @tableName nvarchar(150) + select @tableName = 'ScoreFillin_' + replace(FriendlyName, ' ', '') from ScoreDimension where DimensionGUID = @fillinDimensionGUID + + declare @phKeyName nvarchar(100) + declare @phKeyType int + select @phKeyName = A.SQLColumnName, @phKeyType = A.ColumnType from viewScoreAttribute A inner join ScoreDimension D on D.DimensionGUID = A.DimensionGUID and D.DefaultKeyGUID = A.AttributeGUID and D.DimensionGUID = @phDimensionGUID + + declare @fillinKeyName nvarchar(100) + declare @fillinKeyType int + select @fillinKeyName = A.SQLColumnName, @phKeyType = A.ColumnType from viewScoreAttribute A inner join ScoreDimension D on D.DimensionGUID = A.DimensionGUID and D.DefaultKeyGUID = A.AttributeGUID and D.DimensionGUID = @fillinDimensionGUID + + declare @error nvarchar(450) + if (@phKeyType != 48 and @phKeyType != 52 and @phKeyType != 56 and @phKeyType != 127) begin + set @error = 'Fillin table ' + @tableName + ' cannot be created because the placeholder dimension has a non-integer default key.' + RAISERROR (@error, 18, 0) + return + end + if (@fillinKeyType != 48 and @fillinKeyType != 52 and @fillinKeyType != 56 and @fillinKeyType != 127) begin + set @error = 'Fillin table ' + @tableName + ' cannot be created because the fillin dimension has a non-integer default key.' + RAISERROR (@error, 18, 0) + return + end + + declare @sql nvarchar(max) + + --drop any existing instance of the table + set @sql = ' + if ((select count(*) from sys.tables where name = ''' + @tableName + ''') > 0) begin + drop table data.' + @tableName + ' + end' + if (@isDebug = 1) begin print @sql end else begin exec(@sql) end + + --create the table + set @sql = ' + CREATE TABLE [data].[' + @tableName + '] ( + [RowID] [int] IDENTITY(1,1) NOT NULL, + [FillinGUID] [uniqueidentifier] NOT NULL, + [ModelGUID] [uniqueidentifier] NOT NULL, + [PlaceholderSectionMemberGUID] [uniqueidentifier] NOT NULL, + [PlaceholderIndex] [int] NOT NULL, + [FillinMemberGUID] [uniqueidentifier] NOT NULL, + [FillinMemberName] [nvarchar](max) NOT NULL, + [IsDeleted] [bit] NOT NULL, + [HistoryItemGUID] [uniqueidentifier] NOT NULL, + [' + @phKeyName + '] [int] NOT NULL, + [' + @fillinKeyName + '] [int] NOT NULL, + CONSTRAINT [PK_' + @tableName + '] PRIMARY KEY NONCLUSTERED + ( [RowID] ASC ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + ) ON [PRIMARY]' + if (@isDebug = 1) begin print @sql end else begin exec(@sql) end + + --add default values + set @sql = ' + ALTER TABLE [data].[' + @tableName + '] ADD CONSTRAINT [DF_' + @tableName + '_' + @phKeyName + '] DEFAULT ((0)) FOR [' + @phKeyName + '] + ALTER TABLE [data].[' + @tableName + '] ADD CONSTRAINT [DF_' + @tableName + '_' + @fillinKeyName + '] DEFAULT ((0)) FOR [' + @fillinKeyName + ']' + if (@isDebug = 1) begin print @sql end else begin exec(@sql) end + + --create clustered index + set @sql = ' + CREATE CLUSTERED INDEX [IX_' + @tableName + '_Cluster] ON [data].[' + @tableName + '] ( + [ModelGUID] ASC + ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]' + if (@isDebug = 1) begin print @sql end else begin exec(@sql) end + + --create index on ID columns + set @sql = ' + CREATE NONCLUSTERED INDEX [IX_' + @tableName + '_ByIDs] ON [data].[' + @tableName + '] ( + [ModelGUID] ASC, + [PlaceholderIndex] ASC, + [' + @phKeyName + '] ASC, + [' + @fillinKeyName + '] ASC + ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]' + if (@isDebug = 1) begin print @sql end else begin exec(@sql) end + + --prevent duplicate fillins + set @sql = ' + CREATE UNIQUE NONCLUSTERED INDEX IX_' + @tableName + '_ByFillinGUID ON [data].[' + @tableName + '] ( + FillinGUID + ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]' + if (@isDebug = 1) begin print @sql end else begin exec(@sql) end +GO + + +--------------------------------------------- + +-- dbo.procScoreFillinTableRebuildAll +--Author: gforeman +--Branch: Earwig +--Forward +create proc procScoreFillinTableRebuildAll + @isDebug bit = 0 +as + if ((select COUNT(*) from EMFModelTemplate where IsScoreFillinAdvancedMode = 1) = 0) begin return end + + declare @phDimensionGUID uniqueidentifier + declare @fillinDimensionGUID uniqueidentifier + declare crsDimensions cursor fast_forward for + select distinct + A1.DimensionGUID as PHDimensionGUID, + A2.DimensionGUID as FillinDimensionGUID + from + ScoreCompositeLink CL + inner join viewScoreAttribute A1 on A1.AttributeGUID = CL.Key1GUID + inner join viewScoreAttribute A2 on A2.AttributeGUID = CL.Key2GUID + inner join EMFModelTemplateLinkSource LS on LS.ParentScoreCompositeTableGUID = CL.CompositeGUID + inner join EMFModelTemplate MT on MT.ModelTemplateGUID = LS.ModelTemplateGUID + where + CL.IsPlaceholder = 1 + and MT.IsScoreFillinAdvancedMode = 1 + + open crsDimensions + fetch next from crsDimensions into @phDimensionGUID, @fillinDimensionGUID + + while(@@FETCH_STATUS = 0) begin + exec procScoreFillinTableRebuild @phDimensionGUID, @fillinDimensionGUID, @isDebug + + fetch next from crsDimensions into @phDimensionGUID, @fillinDimensionGUID + end + + close crsDimensions + deallocate crsDimensions + + exec procScoreFillinTableRefreshAll @isDebug +GO + + +--------------------------------------------- + +-- dbo.procScoreFillinTableRefresh +CREATE proc [dbo].[procScoreFillinTableRefresh] + @modelGUIDList nvarchar(max), + @isDebug bit = 0 +as + set nocount on + + declare @mtguid uniqueidentifier + declare @whereClause nvarchar(max) + + declare crsTemplates cursor fast_forward for select distinct MT.ModelTemplateGUID from [dbo].[EMFModelTemplate] MT (readuncommitted) inner join [dbo].[XPlan] P (readuncommitted) on P.ModelTemplateGUID = MT.ModelTemplateGUID where P.PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(@modelGUIDList, ',')) + open crsTemplates + fetch next from crsTemplates into @mtguid + + while(@@FETCH_STATUS = 0) begin + set @whereClause = 'in (select xp.PlanGUID from XPlan xp (readuncommitted) inner join dbo.ConvertCSGuidsToTable(''' + @modelGUIDList + ''', '','') cs on cs.guid = xp.PlanGUID where xp.ModelTemplateGUID = ''' + CAST(@mtguid as nvarchar(36)) + ''')' + exec procScoreFillinTableRefreshWorker @mtguid, @whereClause, @isDebug + + fetch next from crsTemplates into @mtguid + end + + close crsTemplates + deallocate crsTemplates +GO + + +--------------------------------------------- + +-- dbo.procScoreFillinTableRefreshAll +CREATE proc procScoreFillinTableRefreshAll + @isDebug bit = 0 +as + declare @ptguid uniqueidentifier + declare crsTypes cursor fast_forward for select PlanTypeGUID from [dbo].[PlanType] (readuncommitted) + + open crsTypes + fetch next from crsTypes into @ptguid + + while (@@FETCH_STATUS = 0) begin + exec procScoreFillinTableRefreshByPlanType @ptguid, @isDebug + fetch next from crsTypes into @ptguid + end + + close crsTypes + deallocate crsTypes +GO + + +--------------------------------------------- + +-- dbo.procScoreFillinTableRefreshByDimension +CREATE proc [dbo].[procScoreFillinTableRefreshByDimension] + @dimensionGUID uniqueidentifier, + @isDebug bit = 0, + @whereClause nvarchar(max) = '' +as + set nocount on + + declare @tableName nvarchar(150) + declare @phKeyName nvarchar(100) + declare @phDimTable nvarchar(450) + declare @fillinKeyName nvarchar(100) + declare @fillinDimTable nvarchar(450) + declare @fillinDimGUID uniqueidentifier + declare crsInfo cursor fast_forward for + select distinct + 'ScoreFillin_' + replace(A2.DimensionName, ' ', '') as TableName, + A1.SQLColumnName as PHKeyName, + A1.DimensionSQLObjectExpression as PHDimTable, + A2.SQLColumnName as FillinKeyName, + A2.DimensionSQLObjectExpression as FillinDimTable, + A2.DimensionGUID + from + ScoreCompositeLink CL (readuncommitted) + inner join viewScoreAttribute A1 on A1.AttributeGUID = CL.Key1GUID + inner join viewScoreAttribute A2 on A2.AttributeGUID = CL.Key2GUID + inner join EMFModelTemplateLinkSource LS (readuncommitted) on LS.ParentScoreCompositeTableGUID = CL.CompositeGUID + inner join EMFModelTemplate MT (readuncommitted) on MT.ModelTemplateGUID = LS.ModelTemplateGUID + where + CL.IsPlaceholder = 1 + and MT.IsScoreFillinAdvancedMode = 1 + and (A1.DimensionGUID = @dimensionGUID or A2.DimensionGUID = @dimensionguid) + + open crsInfo + fetch next from crsInfo into @tableName, @phKeyName, @phDimTable, @fillinKeyName, @fillinDimTable, @fillinDimGUID + + declare @sql nvarchar(max) + while(@@FETCH_STATUS = 0) begin + if ((@dimensionGUID = @fillinDimGUID) and (len(@whereClause) > 0)) begin + set @sql = ' + begin tran + + delete from data.' + @tableName + ' where FillinMemberGUID in(select C.MemberGUID from ' + @fillinDimTable + ' C where ' + @whereClause + '); + delete from data.' + @tableName + ' where FillinMemberGUID not in(select C.MemberGUID from ' + @fillinDimTable + ' C); + + insert into [data].[' + @tableName + '] ([FillinGUID], [ModelGUID], [PlaceholderSectionMemberGUID], [PlaceholderIndex], [FillinMemberGUID], [FillinMemberName], [IsDeleted], [HistoryItemGUID]) + select [FillinGUID], [ModelGUID], [PlaceholderSectionMemberGUID], [PlaceholderIndex], [FillinMemberGUID], [FillinMemberName], [IsDeleted], [HistoryItemGUID] + from ScoreFillin (readuncommitted) + where FillinMemberGUID in (select C.MemberGUID from ' + @fillinDimTable + ' C where ' + @whereClause + '); + + update FI set FI.' + @phKeyName + ' = PH.' + @phKeyName + ' from data.' + @tableName + ' FI inner join ' + @phDimTable + ' PH on PH.MemberGUID = FI.PlaceholderSectionMemberGUID where FI.FillinMemberGUID in (select C.MemberGUID from ' + @fillinDimTable + ' C where ' + @whereClause + '); + update FI set FI.' + @fillinKeyName + ' = PH.' + @fillinKeyName + ' from data.' + @tableName + ' FI inner join ' + @fillinDimTable + ' PH on PH.MemberGUID = FI.FillinMemberGUID where FI.FillinMemberGUID in (select C.MemberGUID from ' + @fillinDimTable + ' C where ' + @whereClause + '); + + commit tran +' + end else begin + set @sql = ' + begin tran + + truncate table data.' + @tableName + '; + + insert into [data].[' + @tableName + '] ([FillinGUID], [ModelGUID], [PlaceholderSectionMemberGUID], [PlaceholderIndex], [FillinMemberGUID], [FillinMemberName], [IsDeleted], [HistoryItemGUID]) + select [FillinGUID], [ModelGUID], [PlaceholderSectionMemberGUID], [PlaceholderIndex], [FillinMemberGUID], [FillinMemberName], [IsDeleted], [HistoryItemGUID] + from ScoreFillin (readuncommitted) + where FillinMemberGUID in (select fk.MemberGUID from ' + @fillinDimTable + ' fk); + + update FI set FI.' + @phKeyName + ' = PH.' + @phKeyName + ' from data.' + @tableName + ' FI inner join ' + @phDimTable + ' PH on PH.MemberGUID = FI.PlaceholderSectionMemberGUID; + update FI set FI.' + @fillinKeyName + ' = PH.' + @fillinKeyName + ' from data.' + @tableName + ' FI inner join ' + @fillinDimTable + ' PH on PH.MemberGUID = FI.FillinMemberGUID; + + commit tran +' + end + + if (@isDebug = 1) begin print @sql end else begin exec(@sql) end + + fetch next from crsInfo into @tableName, @phKeyName, @phDimTable, @fillinKeyName, @fillinDimTable, @fillinDimGUID + end + + close crsInfo + deallocate crsInfo +GO + + +--------------------------------------------- + +-- dbo.procScoreFillinTableRefreshByPlanType +CREATE proc procScoreFillinTableRefreshByPlanType + @planTypeGUID uniqueidentifier, + @isDebug bit = 0 +as + declare @templateGUID uniqueidentifier + declare crsTemplates cursor fast_forward for + select distinct + P.ModelTemplateGUID + from + XPlan P (readuncommitted) + where + P.PlanTypeGUID = @planTypeGUID + and exists(select 1 from EMFModelTemplateLinkSource LS (readuncommitted) inner join EMFModelTemplate MT (readuncommitted) on MT.ModelTemplateGUID = LS.ModelTemplateGUID where LS.ModelTemplateGUID = P.ModelTemplateGUID and LS.ParentScoreCompositeTableGUID != dbo.ZeroGUID() and MT.IsScoreFillinAdvancedMode = 1) + + open crsTemplates + fetch next from crsTemplates into @templateGUID + + declare @whereClause nvarchar(max) = '' + while (@@FETCH_STATUS = 0) begin + set @whereClause = ' in(select xp.PlanGUID from XPlan xp (readuncommitted) where xp.PlanTypeGUID = ''' + cast(@planTypeGUID as nvarchar(36)) + ''' and xp.ModelTemplateGUID = ''' + cast(@templateGUID as nvarchar(36)) + ''')' + exec [dbo].[procScoreFillinTableRefreshWorker] @templateGUID, @whereClause, @isDebug + + fetch next from crsTemplates into @templateGUID + end + + close crsTemplates + deallocate crsTemplates +GO + + +--------------------------------------------- + +-- dbo.procScoreFillinTableRefreshWorker +create proc [dbo].[procScoreFillinTableRefreshWorker] + @modelTemplateGUID uniqueidentifier, + @modelGUIDWhereClause nvarchar(max), + @isDebug bit = 0 +as + set nocount on + + declare @tableName nvarchar(150) + declare @phKeyName nvarchar(100) + declare @phDimTable nvarchar(450) + declare @fillinKeyName nvarchar(100) + declare @fillinDimTable nvarchar(450) + declare crsInfo cursor fast_forward for + select distinct + 'ScoreFillin_' + replace(A2.DimensionName, ' ', '') as TableName, + A1.SQLColumnName as PHKeyName, + A1.DimensionSQLObjectExpression as PHDimTable, + A2.SQLColumnName as FillinKeyName, + A2.DimensionSQLObjectExpression as FillinDimTable + from + ScoreCompositeLink CL (readuncommitted) + inner join viewScoreAttribute A1 on A1.AttributeGUID = CL.Key1GUID + inner join viewScoreAttribute A2 on A2.AttributeGUID = CL.Key2GUID + inner join EMFModelTemplateLinkSource LS (readuncommitted) on LS.ParentScoreCompositeTableGUID = CL.CompositeGUID + inner join EMFModelTemplate MT (readuncommitted) on MT.ModelTemplateGUID = LS.ModelTemplateGUID + where + MT.ModelTemplateGUID = @modelTemplateGUID + and CL.IsPlaceholder = 1 + and MT.IsScoreFillinAdvancedMode = 1 + + open crsInfo + fetch next from crsInfo into @tableName, @phKeyName, @phDimTable, @fillinKeyName, @fillinDimTable + + declare @sql nvarchar(max) + while(@@FETCH_STATUS = 0) begin + set @sql = ' + begin tran + + delete from data.' + @tableName + ' where ModelGUID ' + @modelGUIDWhereClause + '; + + insert into [data].[' + @tableName + '] ([FillinGUID], [ModelGUID], [PlaceholderSectionMemberGUID], [PlaceholderIndex], [FillinMemberGUID], [FillinMemberName], [IsDeleted], [HistoryItemGUID]) + select [FillinGUID], [ModelGUID], [PlaceholderSectionMemberGUID], [PlaceholderIndex], [FillinMemberGUID], [FillinMemberName], [IsDeleted], [HistoryItemGUID] + from ScoreFillin (readuncommitted) + where FillinMemberGUID in (select fk.MemberGUID from ' + @fillinDimTable + ' fk) and ModelGUID ' + @modelGUIDWhereClause + '; + + update FI set FI.' + @phKeyName + ' = PH.' + @phKeyName + ' from data.' + @tableName + ' FI inner join ' + @phDimTable + ' PH on PH.MemberGUID = FI.PlaceholderSectionMemberGUID where FI.ModelGUID ' + @modelGUIDWhereClause + '; + update FI set FI.' + @fillinKeyName + ' = PH.' + @fillinKeyName + ' from data.' + @tableName + ' FI inner join ' + @fillinDimTable + ' PH on PH.MemberGUID = FI.FillinMemberGUID where FI.ModelGUID ' + @modelGUIDWhereClause + '; + + commit tran +' + if (@isDebug = 1) begin print @sql end else begin exec(@sql) end + + fetch next from crsInfo into @tableName, @phKeyName, @phDimTable, @fillinKeyName, @fillinDimTable + end + + close crsInfo + deallocate crsInfo +GO + + +--------------------------------------------- + +-- dbo.procScoreFixMeasureAggTypes +CREATE proc [dbo].[procScoreFixMeasureAggTypes] +AS + +--AggType 1 = COUNT, safe for all score measures + +--Fix Sums = 0 +update ScoreMeasure set AggType = 1 + where AggType = 0 + AND (dbo.IsSQLNumericType((select ColumnTypeValue from viewScoreMeasure where MeasureGUID = ScoreMeasure.MeasureGUID)) = 0) + +--Fix Avg = 2 +update ScoreMeasure set AggType = 1 + where AggType = 2 + AND (dbo.IsSQLNumericType((select ColumnTypeValue from viewScoreMeasure where MeasureGUID = ScoreMeasure.MeasureGUID)) = 0) + +--Fix Min = 3 +update ScoreMeasure set AggType = 1 +where AggType = 3 + AND (dbo.IsSQLNumericType((select ColumnTypeValue from viewScoreMeasure where MeasureGUID = ScoreMeasure.MeasureGUID)) = 0) + AND (dbo.IsSQLCharacterType((select ColumnTypeValue from viewScoreMeasure where MeasureGUID = ScoreMeasure.MeasureGUID)) = 0) + AND (dbo.IsSQLDateTimeType((select ColumnTypeValue from viewScoreMeasure where MeasureGUID = ScoreMeasure.MeasureGUID)) = 0) + +--Fix Max = 4 +update ScoreMeasure set AggType = 1 +where AggType = 4 + AND (dbo.IsSQLNumericType((select ColumnTypeValue from viewScoreMeasure where MeasureGUID = ScoreMeasure.MeasureGUID)) = 0) + AND (dbo.IsSQLCharacterType((select ColumnTypeValue from viewScoreMeasure where MeasureGUID = ScoreMeasure.MeasureGUID)) = 0) + AND (dbo.IsSQLDateTimeType((select ColumnTypeValue from viewScoreMeasure where MeasureGUID = ScoreMeasure.MeasureGUID)) = 0) +GO + + +--------------------------------------------- + +-- dbo.procScoreGetDefaultAttributeValue +CREATE PROCEDURE [dbo].[procScoreGetDefaultAttributeValue]( + @AttributeGUID uniqueidentifier, + @MemberGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000' +) +AS + +--parameter(s) +--declare @AttributeGUID uniqueidentifier; +--set @AttributeGUID = 'A0965292-E374-4407-9C07-EE613A2F69D0'; + +---------------------------------------------------- +-- Get all necessary values and save to variables +---------------------------------------------------- +declare @DimensionExp varchar(256); +declare @KeyColumn varchar(128); +declare @AttColumn varchar(128); +declare @DefaultMemberGUID uniqueidentifier; + +select + @KeyColumn = K.SQLColumnName, + @AttColumn = Att.SQLColumnName, + @DimensionExp = [dbo].[GetSQLTableExpression](DIM.SQLSchemaName, DIM.SQLObjectName), + @DefaultMemberGUID = DIM.DefaultMemberGUID + from dbo.ScoreAttribute K + inner join ScoreDimensionGroup GK on GK.DimensionGroupGUID = K.DimensionGroupGUID + inner join ScoreDimension DIM on GK.DimensionGUID = DIM.DimensionGUID + inner join ScoreAttribute ATT on ATT.AttributeGUID = DIM.DefaultLookupKeyGUID + where K.AttributeGUID = @AttributeGUID + +print @DimensionExp; +print @AttColumn; + +if (@MemberGUID <> '00000000-0000-0000-0000-000000000000') begin + set @DefaultMemberGUID = @MemberGUID +end +---------------------------------------------------- +--BUILD SQL +-- Note: Ignoring Security for Default Members +---------------------------------------------------- +declare @sql varchar(max); +set @sql = ' + + select + DIM.[' + @KeyColumn + '] as KeyValue, + DIM.[' + @AttColumn + '] as AttributeValue + from ' + @DimensionExp + ' DIM + where + MemberGUID = ''' + CAST(@DefaultMemberGUID as nvarchar(64)) + ''' +'; +print @sql; +exec (@sql); +GO + + +--------------------------------------------- + +-- dbo.procScoreHierarchyPathGetQuery +create proc dbo.procScoreHierarchyPathGetQuery + @hpath nvarchar(max), + @isWhereOnly bit, + @sql nvarchar(max) OUT +as + select + @sql = dbo.straggr(a.SQLColumnName + ' = ''' + lvls.val + '''', ' AND ', '') + from + viewScoreHierarchy h + inner join ScoreDimension d on d.DimensionGUID = h.DimensionGUID + inner join viewScoreAttribute a on a.AttributeGUID = h.AttributeGUID + inner join (select parts.pos - 2 as pos, parts.val from dbo.ConvertCSValuesToTable(@hpath, '|') parts where parts.pos > 2) lvls on lvls.pos = h.SortOrder + where + d.SQLTableAlias in(select hn.val from dbo.ConvertCSValuesToTable(@hpath, '|') hn where hn.pos = 1) + and h.PathAlias in(select hn.val from dbo.ConvertCSValuesToTable(@hpath, '|') hn where hn.pos = 2) + + declare @filter nvarchar(max) + select + @filter = max(a.SQLColumnName + ' = ''' + al.FilterString + '''') + from + ScoreHierarchy h + inner join ScoreHierarchyAttributeLink al on al.HierarchyGUID = h.HierarchyGUID + inner join ScoreDimension d on d.DimensionGUID = h.DimensionGUID + inner join viewScoreAttribute a on a.AttributeGUID = al.FilterAttributeGUID + where + d.SQLTableAlias in(select hn.val from dbo.ConvertCSValuesToTable(@hpath, '|') hn where hn.pos = 1) + and h.PathAlias in(select hn.val from dbo.ConvertCSValuesToTable(@hpath, '|') hn where hn.pos = 2) + and al.IsAttributeFiltered = 1 + if (@filter is not null and @filter != '') begin + set @sql = @sql + ' AND ' + @filter + end + + if (@isWhereOnly = 0) begin + select + @sql = 'select ' + a.SQLColumnName + ' from ' + d.SQLSchemaName + '.' + d.SQLObjectName + ' where ' + @sql + from + ScoreDimension d + inner join viewScoreAttribute a on a.AttributeGUID = d.DefaultKeyGUID + where + d.SQLTableAlias in(select hn.val from dbo.ConvertCSValuesToTable(@hpath, '|') hn where hn.pos = 1) + end +GO + + +--------------------------------------------- + +-- dbo.procScoreLoadPlanGUIDForSecuredLootID +CREATE PROCEDURE [dbo].[procScoreLoadPlanGUIDForSecuredLootID]( + @SecuredID nvarchar(128) +) +AS +BEGIN + select coalesce((select top 1 PlanGUID from XPlan PLN where PLN.CachedLootID = @SecuredID), dbo.ZeroGUID()) +END +GO + + +--------------------------------------------- + +-- dbo.procScoreLoadSecuredConfigIDForPlan +CREATE PROC [dbo].[procScoreLoadSecuredConfigIDForPlan]( + @PlanGUID uniqueidentifier +) +AS + select CachedLootID from XPlan where PlanGUID = @PlanGUID + + --declare @SQLSchemaName nvarchar(128); + --declare @SQLObjectName nvarchar(max); + --declare @AttributeColumn nvarchar(4000); + --declare @Prefix nvarchar(128); + + --select top 1 + -- @SQLSchemaName = DIM.SQLSchemaName, + -- @SQLObjectName = DIM.SQLObjectName, + -- @AttributeColumn = coalesce(OATTR.SQLColumnName, ATTR.SQLColumnName), + -- @Prefix = coalesce(OATTR.SecuredLootGroupPrefix, ATTR.SecuredLootGroupPrefix) + --from XPLan PLN + -- inner join PlanType PLNTYPE on PLN.PlanTypeGUID = PLNTYPE.PlanTypeGUID + -- inner join ScoreDimension DIM on DIM.DimensionGUID = PLNTYPE.DimensionGUID + -- inner join ScoreAttribute ATTR on ATTR.DimensionGUID = DIM.DimensionGUID + -- left join ScoreAttribute OATTR on OATTR.DimensionGUID = DIM.DimensionGUID + -- and OATTR.IsSecuredLootConfigID = 1 + --where ATTR.IsSecuredLootID = 1 + -- and PLN.PlanGUID = @PlanGUID + + --declare @sql varchar(max); + --if(@Prefix = '') begin + -- set @sql = ' + -- select cast(' + @AttributeColumn + ' as nvarchar) as LootID from ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' + -- where MemberGUID = ''' + cast(@PlanGUID as nvarchar(36)) + ''' + + -- '; + --end else begin + -- set @sql = ' + -- select ''' + @Prefix + ''' + ''|'' + cast(' + @AttributeColumn + ' as nvarchar) as LootID from ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' + -- where MemberGUID = ''' + cast(@PlanGUID as nvarchar(36)) + ''' + + -- '; + --end + + --exec (@sql); +GO + + +--------------------------------------------- + +-- dbo.procScoreLoadSecuredLootIDForPlan +CREATE PROC [dbo].[procScoreLoadSecuredLootIDForPlan] ( + @PlanGUID uniqueidentifier +) +AS + +select CachedLootID from XPlan where PlanGUID = @PlanGUID + +--declare @SQLSchemaName nvarchar(128); +--declare @SQLObjectName nvarchar(max); +--declare @AttributeColumn nvarchar(4000); +--declare @Prefix nvarchar(128); + +--select top 1 +-- @SQLSchemaName = DIM.SQLSchemaName, +-- @SQLObjectName = DIM.SQLObjectName, +-- @AttributeColumn = ATTR.SQLColumnName, +-- @Prefix = ATTR.SecuredLootGroupPrefix +--from XPLan PLN +-- inner join PlanType PLNTYPE on PLN.PlanTypeGUID = PLNTYPE.PlanTypeGUID +-- inner join ScoreDimension DIM on DIM.DimensionGUID = PLNTYPE.DimensionGUID +-- inner join ScoreDimensionGroup DIMG on DIMG.DimensionGUID = DIM.DimensionGUID +-- inner join ScoreAttribute ATTR on ATTR.DimensionGroupGUID = DIMG.DimensionGroupGUID +--where PLN.PlanGUID = @PlanGUID and ATTR.IsSecuredLootID = 1 + + +--declare @sql varchar(max); + +--if(@Prefix = '') begin +-- set @sql = ' +-- select cast(' + @AttributeColumn + ' as nvarchar) as LootID from ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' +-- where MemberGUID = ''' + CAST(@PlanGUID as varchar(max)) + ''' + +-- '; +--end else begin +-- set @sql = ' +-- select ''' + @Prefix + ''' + ''|'' + cast(' + @AttributeColumn + ' as nvarchar) as LootID from ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' +-- where MemberGUID = ''' + CAST(@PlanGUID as varchar(max)) + ''' + +-- '; +--end + +--print @sql; +--exec (@sql); +GO + + +--------------------------------------------- + +-- dbo.procScoreLoadSecuredLootIDForPlanShortcut +CREATE PROC [dbo].[procScoreLoadSecuredLootIDForPlanShortcut]( + @EntityGUID UNIQUEIDENTIFIER +) +AS + --check xplan first because viewWFEntity filters out deleted plans + if (exists(select 1 from dbo.XPlan where PlanGUID = @EntityGUID)) begin + SELECT TOP 1 CachedLootID + FROM [dbo].[XPlan] + WHERE PlanGUID = @EntityGUID + end else begin + SELECT TOP 1 CachedLootID + FROM [dbo].[viewWFEntity] + WHERE EntityGUID = @EntityGUID + end +GO + + +--------------------------------------------- + +-- dbo.procScoreLoadSecuredLootIDForPlansShortcut +CREATE PROC [dbo].[procScoreLoadSecuredLootIDForPlansShortcut]( + @PlanGUIDListCSV varchar(max) +) +AS + select + PLN.PlanGUID as MemberGUID, + PLN.CachedLootID as LootID + from + XPLan PLN + where + PLN.PlanGUID in (select * from dbo.CSVGuidsToTable (@PlanGUIDListCSV)) +GO + + +--------------------------------------------- + +-- dbo.procScoreMeasureSchemaUpdate +create proc [dbo].[procScoreMeasureSchemaUpdate] + @datatableguid uniqueidentifier = '00000000-0000-0000-0000-000000000000' +as + +update + obj +set + obj.ColumnID = objschema.ColumnID, + obj.ColumnTypeValue = objschema.ColumnTypeValue, + obj.ColumnName = objschema.ColumnName, + obj.ComputedValueDefinition = objschema.ComputedValueDefinition, + obj.DefaultValueDefinition = objschema.DefaultValueDefinition, + obj.ForeignKeyColumn = objschema.ForeignKeyColumn, + obj.ForeignKeyOnDelete = objschema.ForeignKeyOnDelete, + obj.ForeignKeySchema = objschema.ForeignKeySchema, + obj.ForeignKeyTable = objschema.ForeignKeyTable, + obj.IdentityIncrement = objschema.IdentityIncrement, + obj.IdentitySeed = objschema.IdentitySeed, + obj.IsComputed = objschema.IsComputed, + obj.IsForeignKeyed = objschema.IsForeignKeyed, + obj.IsIdentity = objschema.IsIdentity, + obj.IsNullable = objschema.IsNullable, + obj.IsPartOfPrimaryKey = objschema.IsPartOfPrimaryKey, + obj.IsPartOfUniqueIndex = objschema.IsPartOfUniqueIndex, + obj.IsPrimaryKey = objschema.IsPrimaryKey, + obj.IsUniqueIndex = objschema.IsUniqueIndex, + obj.MaxLength = objschema.MaxLength, + obj.ObjectID = objschema.ObjectID, + obj.ObjectName = objschema.ObjectName, + obj.ObjectType = objschema.ObjectType, + obj.Precision = objschema.Precision, + obj.Scale = objschema.Scale, + obj.SchemaName = objschema.SchemaName +from + ScoreMeasure obj + inner join viewScoreMeasureSchemaInfo objschema on obj.MeasureGUID = objschema.MeasureGUID +where + @datatableguid in (obj.datatableguid, dbo.zeroguid()) + and ( + obj.ColumnID <> objschema.ColumnID or + obj.ColumnTypeValue <> objschema.ColumnTypeValue or + obj.ColumnName <> objschema.ColumnName or + obj.ComputedValueDefinition <> objschema.ComputedValueDefinition or + obj.DefaultValueDefinition <> objschema.DefaultValueDefinition or + obj.ForeignKeyColumn <> objschema.ForeignKeyColumn or + obj.ForeignKeyOnDelete <> objschema.ForeignKeyOnDelete or + obj.ForeignKeySchema <> objschema.ForeignKeySchema or + obj.ForeignKeyTable <> objschema.ForeignKeyTable or + obj.IdentityIncrement <> objschema.IdentityIncrement or + obj.IdentitySeed <> objschema.IdentitySeed or + obj.IsComputed <> objschema.IsComputed or + obj.IsForeignKeyed <> objschema.IsForeignKeyed or + obj.IsIdentity <> objschema.IsIdentity or + obj.IsNullable <> objschema.IsNullable or + obj.IsPartOfPrimaryKey <> objschema.IsPartOfPrimaryKey or + obj.IsPartOfUniqueIndex <> objschema.IsPartOfUniqueIndex or + obj.IsPrimaryKey <> objschema.IsPrimaryKey or + obj.IsUniqueIndex <> objschema.IsUniqueIndex or + obj.MaxLength <> objschema.MaxLength or + obj.ObjectID <> objschema.ObjectID or + obj.ObjectName <> objschema.ObjectName or + obj.ObjectType <> objschema.ObjectType or + obj.Precision <> objschema.Precision or + obj.Scale <> objschema.Scale or + obj.SchemaName <> objschema.SchemaName + ) +GO + + +--------------------------------------------- + +-- dbo.procScoreRebuildDimensionMemberView +--#notran# +CREATE proc [dbo].[procScoreRebuildDimensionMemberView] + @isDebugOnly bit = 0 +as +exec dbo.procRefreshViews --broken views will not be included in these debug views + +declare @viewSQL varchar(max) +set @viewSQL = '' + +declare @dropSql varchar(max) + +set @dropSql =' +if dbo.ViewExists(''data'',''viewScoreDimensionMember'') = 1 begin + drop view data.viewScoreDimensionMember +end + +if dbo.ViewExists(''data'',''viewScoreFillInDetail'') = 1 begin + drop view data.viewScoreFillInDetail +end + +if dbo.ViewExists(''data'',''viewScoreFillInTemplateItemDetail'') = 1 begin + drop view data.viewScoreFillInTemplateItemDetail +end + +' +if (@isDebugOnly = 0) begin exec (@dropsql) end else begin exec dbo.procPrintLongText @dropsql end + +--secured system sections +set @viewSQL = @viewSQL +' + +create view data.viewScoreDimensionMember as +' + +--secured dimensions +declare crsScoreDim CURSOR FOR + select ' +SELECT + cast(''' + cast(SD.DimensionGUID as varchar(36)) + ''' as uniqueidentifier) as DimensionGUID, + ''' + SD.FriendlyName + ''' as DimensionName, + MemberGUID, + cast([' + sadlk.sqlcolumnname + '] as varchar(max)) as MemberName, + cast([' + sadk.sqlcolumnname + '] as varchar(max)) as DefaultKey, + ''' + isnull(salid.securedlootgroupprefix,'Unsecure') + '|'' + cast([' + isnull(salid.sqlcolumnname, sadk.sqlcolumnname) + '] as varchar(max)) as LootID +FROM [' + sd.sqlschemaname + '].[' + sd.sqlobjectname + ']' + from + ScoreDimension SD + inner join viewSysColumns col on sd.sqlschemaname = col.schemaname and sd.sqlobjectname = col.objectname and col.columnname = 'memberguid' + + inner join viewScoreAttributeCore30 SADLK on sd.dimensionguid = sadlk.dimensionguid and sd.defaultlookupkeyguid = sadlk.attributeguid + inner join viewSysColumns SADLKcol on sd.sqlschemaname = SADLKcol.schemaname and sd.sqlobjectname = SADLKcol.objectname and SADLKcol.columnname = sadlk.sqlcolumnname + + inner join viewScoreAttributeCore30 SADK on sd.dimensionguid = sadk.dimensionguid and sd.defaultkeyguid = SADK.attributeguid + inner join viewSysColumns sadkcol on sd.sqlschemaname = sadkcol.schemaname and sd.sqlobjectname = sadkcol.objectname and sadkcol.columnname = sadk.sqlcolumnname + + left join viewScoreAttributeCore30 SALID on sd.dimensionguid = salid.dimensionguid and salid.issecuredlootid = 1 + where + (dbo.viewexists(sd.sqlschemaname,sd.sqlobjectname) = 1 + or dbo.tableexists(sd.sqlschemaname,sd.sqlobjectname) = 1) + and sd.sqlschemaname + '.' + sd.sqlobjectname not in(select replace(replace(brokenviewname, '[', ''), ']', '') from dbo.RefreshViewsLog) + +open crsScoreDim; + +declare @dimsql varchar(max) +declare @cnt int +set @cnt = 0 + +FETCH NEXT FROM crsScoreDim into @dimsql +WHILE (@@FETCH_STATUS = 0) BEGIN + + if @cnt > 0 begin + set @viewSQL = @viewSQL + ' + UNION ALL + ' + end + set @cnt = @cnt + 1 + set @viewSQL = @viewSQL + ' + ' + @dimsql + FETCH NEXT FROM crsScoreDim into @dimsql +end + +close crsscoredim +deallocate crsscoredim + +if @cnt > 0 begin + if (@isDebugOnly = 0) begin exec (@viewsql) end else begin exec dbo.procPrintLongText @viewsql end + + set @viewSQL = ' + +create view data.[viewScoreFillInTemplateItemDetail] as +select + fit.*, + secmem.DimensionName as SectionDimensionName, + secmem.MemberName as SectionMemberName, + conmem.DimensionName as ConstantDimensionName, + conmem.MemberName as ConstantMemberName +from + ScoreFillInTemplateItem fit + left join data.viewScoreDimensionMember secmem on fit.PlaceholderSectionMemberGUID = secmem.MemberGUID + left join data.viewScoreDimensionMember conmem on fit.ConstantMemberGUID = conmem.MemberGUID' + + if (@isDebugOnly = 0) begin exec (@viewsql) end else begin exec dbo.procPrintLongText @viewsql end + + set @viewSQL = ' +create view [data].[viewScoreFillinDetail] as +select + fi.ModelGUID, + sdmm.MemberName as ModelName, + fi.PlaceholderSectionMemberGUID, + sdmph.DimensionName as PlaceholderSectionDimensionName, + sdmph.DefaultKey as PlaceholderSectionDefaultKey, + sdmph.LootID as PlaceholderSectionLootID, + sdmph.MemberName as PlaceholderSectionMemberName, + fi.PlaceholderIndex, + fi.FillinMemberGUID, + sdmfi.DimensionName as FillInDimensionName, + sdmfi.DefaultKey as FillInDefaultKey, + sdmfi.LootID as FillInLootID, + sdmfi.MemberName as FillInMemberName +from + ScoreFillin fi + left join data.viewScoreDimensionMember sdmm on fi.ModelGUID = sdmm.MemberGUID + left join data.viewScoreDimensionMember sdmph on fi.PlaceholderSectionMemberGUID = sdmph.MemberGUID + left join data.viewScoreDimensionMember sdmfi on fi.FillinMemberGUID = sdmfi.MemberGUID + ' + if (@isDebugOnly = 0) begin exec (@viewsql) end else begin exec dbo.procPrintLongText @viewsql end +end +GO + + +--------------------------------------------- + +-- dbo.procScoreRemoveDeletedAll +CREATE proc procScoreRemoveDeletedAll +as +exec [procScoreRunForManyStructures] 'delete from [{schema}].[{object}] where isdeleted = 1', 'where iswrittentodb = 1', 1 +GO + + +--------------------------------------------- + +-- dbo.procScoreRemoveLootRefreshTrigger +CREATE proc [dbo].[procScoreRemoveLootRefreshTrigger]( + @aDimensionGUID uniqueidentifier +) +AS + + --get schema and object + declare @Schema varchar(128); + declare @Object varchar(128); + + select @Schema = Sqlschemaname, @Object = SQLObjectName from ScoreDimension where DimensionGUID = @aDimensionGUID; + + declare @triggerName varchar(max); + select @triggerName = (select [dbo].GetScoreLootRefreshTriggerName(@aDimensionGUID)); + + if ([dbo].[IsView](@Schema, @Object) = 1) + BEGIN + print 'Removing Triggers from Underlying Tables'; + declare @TableSchema varchar(128); + declare @TableName varchar(128); + declare @TableTriggerName varchar(128); + + DECLARE TableCursor CURSOR + FOR select * from [dbo].GetViewUnderlyingTables(@Schema, @Object) + + OPEN TableCursor; + Fetch Next from TableCursor INTO @TableName, @TableSchema; + WHILE (@@FETCH_STATUS = 0) + BEGIN + set @TableTriggerName = Substring((select [dbo].GetScoreLootRefreshTriggerName(@aDimensionGUID)) + '_' + @TableName, 0, 128); + if ([dbo].IsTriggerExist(@TableTriggerName) = 1) + BEGIN + declare @tablesql varchar(max); + set @tablesql = ' + DROP TRIGGER [' + @TableSchema + '].[' + @TableTriggerName + '] + '; + print @tablesql; + exec (@tablesql); + END + Fetch Next from TableCursor INTO @TableName, @TableSchema; + END + CLOSE TableCursor; + DEALLOCATE TableCursor; + END + + if ([dbo].IsTriggerExist(@triggerName)= 1) + BEGIN + + declare @sql varchar(max); + set @sql = ' + DROP TRIGGER [' + @Schema + '].[' + @triggerName + '] + '; + print @sql; + exec (@sql); + END + ELSE + print 'Trigger does not exist.' +GO + + +--------------------------------------------- + +-- dbo.procScoreRunForManyStructures +CREATE proc [dbo].[procScoreRunForManyStructures] + @execsql varchar(max) + ,@structurefiltersql varchar(max) = '' + ,@exec bit = 0 + ,@allTogether bit = 0 +as + +--set @execsql = ' +-- select ''{mdcname}'', count(*) from zzemfmodeldata_{mdcguidfriendly} +--' +--set @structurefiltersql = ' +--where friendlyname like ''lrfp%'' +--' + +declare @structuresql varchar(max) + +set @structuresql = ' +select + datatableguid, friendlyname, sqlschemaname, sqlobjectname, sqltablealias +from + scoredatatable +' + @structurefiltersql + +create table #mdcs (datatableguid uniqueidentifier, friendlyname nvarchar(64), sqlschemaname nvarchar(max), sqlobjectname nvarchar(max), sqltablealias nvarchar(max)) + +insert into #mdcs +exec (@structuresql) + +declare @sdtguid uniqueidentifier +declare @sdtguidfriendly varchar(36) +declare @sdtname nvarchar(64) +declare @sdtnamefriendly nvarchar(64) +declare @sqlschemaname nvarchar(max) +declare @sqlobjectname nvarchar(max) +declare @sqltablealias nvarchar(max) +declare @sql varchar(max) + + declare crsMDC CURSOR FOR + select * + from #mdcs + + open crsMDC; + + set @sql = '' + + FETCH NEXT FROM crsMDC into @sdtguid, @sdtname, @sqlschemaname, @sqlobjectname, @sqltablealias + WHILE (@@FETCH_STATUS = 0) + BEGIN + + set @sdtguidfriendly = replace(cast(@sdtguid as varchar(36)),'-','_') + set @sdtnamefriendly = REPLACE(@sdtname,' ','') + set @sdtnamefriendly = REPLACE(@sdtnamefriendly,'-','') + set @sdtnamefriendly = REPLACE(@sdtnamefriendly,'.','') + + if @allTogether = 1 begin + set @sql = @sql + replace(replace(replace(replace(replace(replace(replace(@execsql,'{mdcguid}',cast(@sdtguid as varchar(36))), '{mdcname}',@sdtname),'{mdcguidfriendly}',@sdtguidfriendly),'{mdcnamefriendly}',@sdtnamefriendly),'{schema}',@sqlschemaname),'{object}',@sqlobjectname),'{alias}',@sqltablealias) + end else begin + set @sql = replace(replace(replace(replace(replace(replace(replace(@execsql,'{mdcguid}',cast(@sdtguid as varchar(36))), '{mdcname}',@sdtname),'{mdcguidfriendly}',@sdtguidfriendly),'{mdcnamefriendly}',@sdtnamefriendly),'{schema}',@sqlschemaname),'{object}',@sqlobjectname),'{alias}',@sqltablealias) + if @exec = 1 begin + exec(@sql) + end else begin + print @sql + end + end + + + + + FETCH NEXT FROM crsMDC into @sdtguid, @sdtname, @sqlschemaname, @sqlobjectname, @sqltablealias + END + close crsMDC; + DEALLOCATE crsMDC; + + if @allTogether = 1 begin + if @exec = 1 begin + exec(@sql) + end else begin + print @sql + end + end + + + +drop table #mdcs +GO + + +--------------------------------------------- + +-- dbo.procScoreSecurityTriggersGet +create proc procScoreSecurityTriggersGet + @dimensionSchema nvarchar(10), + @dimensionTableName nvarchar(100) +as + select + d.FriendlyName as RefreshDimension, + 'exec procScoreSetDimensionSecurity30 ''' + cast(d.DimensionGUID as nvarchar(36)) + ''',0,0' as RefreshSQL, + 'drop trigger fw.' + tg.Name as DropSQL + from + sys.triggers tg + inner join [dbo].[ScoreDimension] d on tg.name like '%' + replace(cast(d.DimensionGUID as nvarchar(36)),'-', '') + '%' where tg.parent_id in(select t.object_id from sys.tables t inner join sys.schemas s on s.schema_id = t.schema_id where t.name = @dimensionTableName and s.name = @dimensionSchema) + and name like '%ScoreDimension%' +GO + + +--------------------------------------------- + +-- dbo.procScoreSetDimensionSecurity30 +CREATE proc [dbo].[procScoreSetDimensionSecurity30] +( + @aDimensionGUID UNIQUEIDENTIFIER, + @IsDebugOnly bit = 0, + @IsUsingVersionColumn bit = 0, + @IsOverrideSharedLoot bit = 0, + @source nvarchar(100) = 'procScoreSetDimensionSecurity30' +) +AS +BEGIN + set nocount on + IF ( + ( + SELECT + COUNT(*) + FROM + [dbo].[ScoreDimension] (READUNCOMMITTED) + WHERE + DimensionGUID = @aDimensionGUID AND + IsSecurityTriggersEnabled = 1 + ) = 0 + ) + BEGIN + RETURN; + END; + ELSE + BEGIN + + DECLARE @json VARCHAR(1000) = '{' + + '"DimensionGuid":"' + CAST(@aDimensionGUID AS VARCHAR(50)) + '"' + + ',"IsDebugOnly":' + CAST(@IsDebugOnly AS VARCHAR(1)) + + ',"IsUsingVersionColumn":' + CAST(@IsUsingVersionColumn AS VARCHAR(1)) + + ',"IsOverrideSharedLoot":' + CAST(@IsOverrideSharedLoot AS VARCHAR(1)) + + '}'; + + DECLARE @statusCode INT; + EXEC dbo.procCreateTask + @taskTypeName = 'Strata.CS.Jazz.Biz.Security.Tasks.ScoreSetDimensionSecurityTask, Strata.CS.Jazz.Biz', -- varchar(1000) + @contextXML = @json, -- varchar(1000) + @userName = 'Strata', + @statusCode = @statusCode OUTPUT, + @taskSource = @source; + + END; +END; +GO + + +--------------------------------------------- + +-- dbo.procScoreSetDimensionSecurity30InsertNew +CREATE proc [dbo].[procScoreSetDimensionSecurity30InsertNew] +( + @aDimensionGUID uniqueidentifier, + @aMemberGUID uniqueidentifier, + @IsDebugOnly bit = 0, + @IsUsingVersionColumn bit = 0, + @IsOverrideSharedLoot bit = 0 +) +AS + +declare @sql nvarchar(max); +set @sql = ''; + +declare @SQLSchemaName nvarchar(128); +declare @SQLObjectName nvarchar(max); +declare @IsSecured bit; +declare @IsSharingSecurity bit; +select + @SQLSchemaName = SQLSchemaName, + @SQLObjectName = SQLObjectName, + @IsSecured = IsSecured, + @IsSharingSecurity = IsSharingSecurity +from ScoreDimension (readuncommitted) where DimensionGUID = @aDimensionGUID; + + +if (@SQLObjectName is null) begin + --declare @err nvarchar(max); + --set @err = 'Dimension with GUID ' + cast(@aDimensionGUID as nvarchar(64)) + ' does not exist. Cannot set security on dimension.'; + --RAISERROR (@err,15,1); + RETURN; +end +if (@IsSecured = 0) +BEGIN + --NOT SECURED, DO NOTHING + RETURN; +END +if (@IsSharingSecurity = 1 and @IsOverrideSharedLoot = 0) +BEGIN + --LOOTS are handled from another dimension. No Need to refresh + RETURN; +END + +declare @lootIDColumn nvarchar(128) +declare @lootIDExpression nvarchar(128) +select @lootIDColumn = 'START.' + SQLColumnName, @lootIDExpression = SecuredLootGroupPrefix from viewScoreAttributeCore30 where DimensionGUID = @aDimensionGUID and IsSecuredLootID = 1 + +if @lootIDExpression = '' begin + set @lootIDExpression = 'cast(' + @lootIDColumn + ' as nvarchar(128))' +end +else begin + set @lootIDExpression = '''' + @lootIDExpression + '|'' + cast(' + @lootIDColumn + ' as nvarchar(128))' +end + +set @sql = @sql + ' + IF (SELECT COUNT(*) FROM ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' WHERE MemberGUID = ''' + CAST(@aMemberGUID as nvarchar(36)) + ''') = 0 BEGIN + RETURN + END + + --DELETE FROM S3Loot WHERE LootID IN (SELECT ' + @lootIDExpression + ' FROM ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' START) AND PermissionSetID <> (SELECT SD.PermissionSetID FROM ScoreDimension SD WHERE SD.DimensionGUID = ''' + cast(@aDimensionGUID as varchar(36)) + ''') + INSERT INTO S3Loot (LootID, PermissionSetID) + SELECT DISTINCT + ' + @lootIDExpression + ', SD.PermissionSetID + FROM + ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' START + CROSS JOIN ScoreDimension (readuncommitted) SD + WHERE + SD.DimensionGUID = ''' + cast(@aDimensionGUID as varchar(36)) + ''' + AND NOT EXISTS (SELECT 1 FROM S3Loot LX WHERE LX.LootID = ' + @lootIDExpression + ') + AND START.MemberGUID = ''' + CAST(@aMemberGUID as nvarchar(36)) + ''' +' + +set @sql = @sql + ' + CREATE TABLE #S3LootGroup (LootID nvarchar(128), LootGroupID nvarchar(128)) + + INSERT INTO #S3LootGroup (LootID, LootGroupID) + + +'; + +DECLARE AttributeCursor CURSOR +FOR select 'START.' + SQLColumnName as ColumnName, SecuredLootGroupPrefix + from viewScoreAttributeCore30 ATT + where ATT.IsSecuredLootGroupID = 1 and ATT.DimensionGUID = @aDimensionGUID; + +declare @ColName nvarchar(max); +declare @Prefix nvarchar(128); +declare @expression nvarchar(128); +declare @expressionWithPrefix nvarchar(128); + +declare @i int; +set @i = 0; +OPEN AttributeCursor; +Fetch Next from AttributeCursor INTO @ColName, @Prefix; +WHILE (@@FETCH_STATUS = 0) +BEGIN + if (@i <> 0) begin + set @sql = @sql + 'UNION ALL + '; + end + set @expression = 'ltrim(rtrim(cast(' + @ColName + ' as nvarchar(128))))' + if @Prefix = '' begin + set @expressionWithPrefix = @expression + end + else begin + set @expressionWithPrefix = '''' + @Prefix + '|'' + ' + @expression + end + + set @sql = @sql + ' + select ' + @lootIDExpression + ', ' + @expressionWithPrefix + ' from ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' START + WHERE + MemberGUID = ''' + CAST(@aMemberGUID as nvarchar(36)) + ''' AND + ' + @expression + ' <> '''' + ' + + --and not exists (select 1 from dbo.S3LootGroup LOOTGROUP + -- where LOOTGROUP.LootID = ' + @lootIDExpression + ' + -- and LOOTGROUP.LootGroupID = ' + @expressionWithPrefix + ' + -- ) + + + + set @i = @i + 1; + Fetch Next from AttributeCursor INTO @ColName, @Prefix; +END; +CLOSE AttributeCursor; +DEALLOCATE AttributeCursor; + +set @sql = @sql + ' +--create index idx_lootid on #s3lootgroup(lootid) + +--add valid ones +INSERT INTO S3LootGroup (LootID, LootGroupID) +SELECT DISTINCT + lootid, lootgroupid +FROM + #S3LootGroup nlg +WHERE + NOT EXISTS ( + SELECT 1 + FROM S3LootGroup lg + WHERE lg.lootid = nlg.LootID and lg.lootgroupid = nlg.lootgroupid + ) +' + +set @sql = @sql + ' +DROP TABLE #S3LootGroup +' + +if @IsDebugOnly = 0 begin + exec (@sql) +end else begin + print @sql +end +GO + + +--------------------------------------------- + +-- dbo.procScoreSetDimensionSecurity30Sync +CREATE proc [dbo].[procScoreSetDimensionSecurity30Sync] +( + @aDimensionGUID uniqueidentifier, + @IsDebugOnly bit = 0, + @IsUsingVersionColumn bit = 0, + @IsOverrideSharedLoot bit = 0 +) +AS +set nocount on + +declare @sql nvarchar(max); +set @sql = ''; + +declare @SQLSchemaName nvarchar(128); +declare @SQLObjectName nvarchar(max); +declare @IsSecured bit; +declare @IsSharingSecurity bit; +declare @IsSecurityReadOnly bit; +select + @SQLSchemaName = SQLSchemaName, + @SQLObjectName = SQLObjectName, + @IsSecured = IsSecured, + @IsSharingSecurity = IsSharingSecurity, + @IsSecurityReadOnly = IsSecurityReadOnly +from ScoreDimension (readuncommitted) where DimensionGUID = @aDimensionGUID; + +--if security is read only, we assume another dimension is maintaining the security for us +if (@IsSecurityReadOnly = 1) begin + return +end + +if (@SQLObjectName is null) begin + --declare @err nvarchar(max); + --set @err = 'Dimension with GUID ' + cast(@aDimensionGUID as nvarchar(64)) + ' does not exist. Cannot set security on dimension.'; + --RAISERROR (@err,15,1); + RETURN; +end +if (@IsSecured = 0) +BEGIN + --NOT SECURED, DO NOTHING + RETURN; +END +if (@IsSharingSecurity = 1 and @IsOverrideSharedLoot = 0) +BEGIN + --LOOTS are handled from another dimension. No Need to refresh + RETURN; +END + +declare @eventName varchar(64) +set @eventName = 'SBS' + CAST(@aDimensionGUID as varchar(36)) +declare @lastRunVersion timestamp +select @lastRunVersion = dbo.GetEventVersion(@eventName) + +declare @lootIDColumn nvarchar(128) +declare @lootIDExpression nvarchar(128) +select @lootIDColumn = 'START.' + SQLColumnName, @lootIDExpression = SecuredLootGroupPrefix from viewScoreAttributeCore30 where DimensionGUID = @aDimensionGUID and IsSecuredLootID = 1 + +if @lootIDExpression = '' begin + set @lootIDExpression = 'cast(' + @lootIDColumn + ' as nvarchar(128))' +end +else begin + set @lootIDExpression = '''' + @lootIDExpression + '|'' + cast(' + @lootIDColumn + ' as nvarchar(128))' +end + +set @sql = @sql + ' + --DELETE FROM S3Loot WHERE LootID IN (SELECT ' + @lootIDExpression + ' FROM ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' START) AND PermissionSetID <> (SELECT SD.PermissionSetID FROM ScoreDimension SD WHERE SD.DimensionGUID = ''' + cast(@aDimensionGUID as varchar(36)) + ''') + INSERT INTO S3Loot (LootID, PermissionSetID) + SELECT DISTINCT + ' + @lootIDExpression + ', SD.PermissionSetID + FROM + ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' START + CROSS JOIN ScoreDimension SD (readuncommitted) + WHERE + SD.DimensionGUID = ''' + cast(@aDimensionGUID as varchar(36)) + ''' + AND NOT EXISTS (SELECT 1 FROM S3Loot LX WHERE LX.LootID = ' + @lootIDExpression + ') +' +if @IsUsingVersionColumn = 1 begin + set @sql = @sql + ' AND START.Version > @lastRunVersion' +end + + +set @sql = @sql + ' + CREATE TABLE #S3LootGroup (LootID nvarchar(128), LootGroupID nvarchar(128)) + + INSERT INTO #S3LootGroup (LootID, LootGroupID) + + +'; + +DECLARE AttributeCursor CURSOR +FOR select 'START.' + SQLColumnName as ColumnName, SecuredLootGroupPrefix + from viewScoreAttributeCore30 ATT + where ATT.IsSecuredLootGroupID = 1 and ATT.DimensionGUID = @aDimensionGUID; + +declare @ColName nvarchar(max); +declare @Prefix nvarchar(128); +declare @expression nvarchar(128); +declare @expressionWithPrefix nvarchar(128); + +declare @i int; +set @i = 0; +OPEN AttributeCursor; +Fetch Next from AttributeCursor INTO @ColName, @Prefix; +WHILE (@@FETCH_STATUS = 0) +BEGIN + if (@i <> 0) begin + set @sql = @sql + 'UNION ALL + '; + end + set @expression = 'ltrim(rtrim(cast(' + @ColName + ' as nvarchar(128))))' + if @Prefix = '' begin + set @expressionWithPrefix = @expression + end + else begin + set @expressionWithPrefix = '''' + @Prefix + '|'' + ' + @expression + end + + set @sql = @sql + ' + select ' + @lootIDExpression + ', ' + @expressionWithPrefix + ' from ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' START + WHERE + ' + @expression + ' <> '''' + ' +if @IsUsingVersionColumn = 1 begin + set @sql = @sql + ' AND START.Version > @lastRunVersion + ' +end + + --and not exists (select 1 from dbo.S3LootGroup LOOTGROUP + -- where LOOTGROUP.LootID = ' + @lootIDExpression + ' + -- and LOOTGROUP.LootGroupID = ' + @expressionWithPrefix + ' + -- ) + + + + set @i = @i + 1; + Fetch Next from AttributeCursor INTO @ColName, @Prefix; +END; +CLOSE AttributeCursor; +DEALLOCATE AttributeCursor; + +set @sql = @sql + ' +create index idx_lootid on #s3lootgroup(lootid) + +--delete invalid ones +while (1 = 1) begin + DELETE top(1000) lg FROM S3LootGroup lg WHERE + lg.LootID IN (select nlg.LootID from #S3LootGroup nlg) + and NOT EXISTS ( + SELECT 1 + FROM #S3LootGroup nlg + WHERE lg.lootid = nlg.LootID and lg.lootgroupid = nlg.lootgroupid + ) + + if (@@rowcount = 0) break +end + +--add valid ones +CREATE TABLE #S3LootGroupInsert (RowID int primary key identity, LootID nvarchar(128), LootGroupID nvarchar(128)) +INSERT INTO #S3LootGroupInsert (LootID, LootGroupID) +SELECT DISTINCT + lootid, lootgroupid +FROM + #S3LootGroup nlg +WHERE + NOT EXISTS ( + SELECT 1 + FROM S3LootGroup lg + WHERE lg.lootid = nlg.LootID and lg.lootgroupid = nlg.lootgroupid + ) +declare @inscount int = 1 +declare @insmax int +select @insmax = max(RowID) from #S3LootGroupInsert +while(@inscount <= @insmax) begin + INSERT INTO S3LootGroup (LootID, LootGroupID) + select nlg.LootID, nlg.LootGroupID from #S3LootGroupInsert nlg where nlg.RowID >= @inscount and nlg.RowID < @inscount + 1000 + and NOT EXISTS ( + SELECT 1 + FROM S3LootGroup lg + WHERE lg.lootid = nlg.LootID and lg.lootgroupid = nlg.lootgroupid + ) + + set @inscount = @inscount + 1000 +end +' + +set @sql = @sql + ' +DROP TABLE #S3LootGroup +DROP TABLE #S3LootGroupInsert +' + +if @IsDebugOnly = 0 begin + --exec (@sql); + exec sp_executesql @sql,N'@lastRunVersion timestamp', @lastRunVersion = @lastRunVersion-- + + exec procEventupdate @eventName +end else begin + print @sql +end +GO + + +--------------------------------------------- + +-- dbo.procScoreSetDimensionSecurity30UpdateSingle +CREATE proc [dbo].[procScoreSetDimensionSecurity30UpdateSingle] +( + @aDimensionGUID uniqueidentifier, + @aMemberGUID uniqueidentifier, + @IsDebugOnly bit = 0, + @IsUsingVersionColumn bit = 0, + @IsOverrideSharedLoot bit = 0 +) +AS +set nocount on + +declare @sql nvarchar(max); +set @sql = ''; + +declare @SQLSchemaName nvarchar(128); +declare @SQLObjectName nvarchar(max); +declare @IsSecured bit; +declare @IsSharingSecurity bit; +declare @IsSecurityReadOnly bit; +select + @SQLSchemaName = SQLSchemaName, + @SQLObjectName = SQLObjectName, + @IsSecured = IsSecured, + @IsSharingSecurity = IsSharingSecurity, + @IsSecurityReadOnly = IsSecurityReadOnly +from ScoreDimension (readuncommitted) where DimensionGUID = @aDimensionGUID; + +--if security is read only, we assume another dimension is maintaining the security for us +if (@IsSecurityReadOnly = 1) begin + return +end + +if (@SQLObjectName is null) begin + --declare @err nvarchar(max); + --set @err = 'Dimension with GUID ' + cast(@aDimensionGUID as nvarchar(64)) + ' does not exist. Cannot set security on dimension.'; + --RAISERROR (@err,15,1); + RETURN; +end +if (@IsSecured = 0) +BEGIN + --NOT SECURED, DO NOTHING + RETURN; +END +if (@IsSharingSecurity = 1 and @IsOverrideSharedLoot = 0) +BEGIN + --LOOTS are handled from another dimension. No Need to refresh + RETURN; +END + +declare @lootIDColumn nvarchar(128) +declare @lootIDExpression nvarchar(128) +select @lootIDColumn = 'START.' + SQLColumnName, @lootIDExpression = SecuredLootGroupPrefix from viewScoreAttributeCore30 where DimensionGUID = @aDimensionGUID and IsSecuredLootID = 1 + +if @lootIDExpression = '' begin + set @lootIDExpression = 'cast(' + @lootIDColumn + ' as nvarchar(128))' +end +else begin + set @lootIDExpression = '''' + @lootIDExpression + '|'' + cast(' + @lootIDColumn + ' as nvarchar(128))' +end + +set @sql = @sql + ' + INSERT INTO S3Loot (LootID, PermissionSetID) + SELECT DISTINCT + ' + @lootIDExpression + ', SD.PermissionSetID + FROM + ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' START + CROSS JOIN ScoreDimension SD (readuncommitted) + WHERE + SD.DimensionGUID = ''' + cast(@aDimensionGUID as varchar(36)) + ''' + AND START.MemberGUID = ''' + cast(@aMemberGUID as varchar(36)) + ''' + AND NOT EXISTS (SELECT 1 FROM S3Loot LX WHERE LX.LootID = ' + @lootIDExpression + ') +' + +set @sql = @sql + ' + CREATE TABLE #S3LootGroup (LootID nvarchar(128), LootGroupID nvarchar(128)) + + INSERT INTO #S3LootGroup (LootID, LootGroupID) + + +'; + +DECLARE AttributeCursor CURSOR +FOR select 'START.' + SQLColumnName as ColumnName, SecuredLootGroupPrefix + from viewScoreAttributeCore30 ATT + where ATT.IsSecuredLootGroupID = 1 and ATT.DimensionGUID = @aDimensionGUID; + +declare @ColName nvarchar(max); +declare @Prefix nvarchar(128); +declare @expression nvarchar(128); +declare @expressionWithPrefix nvarchar(128); + +declare @i int; +set @i = 0; +OPEN AttributeCursor; +Fetch Next from AttributeCursor INTO @ColName, @Prefix; +WHILE (@@FETCH_STATUS = 0) +BEGIN + if (@i <> 0) begin + set @sql = @sql + 'UNION ALL + '; + end + set @expression = 'ltrim(rtrim(cast(' + @ColName + ' as nvarchar(128))))' + if @Prefix = '' begin + set @expressionWithPrefix = @expression + end + else begin + set @expressionWithPrefix = '''' + @Prefix + '|'' + ' + @expression + end + + set @sql = @sql + ' + select ' + @lootIDExpression + ', ' + @expressionWithPrefix + ' from ' + (select [dbo].[GetSQLTableExpression](@SQLSchemaName, @SQLObjectName)) + ' START + WHERE + ' + @expression + ' <> '''' + AND START.MemberGUID = ''' + cast(@aMemberGUID as varchar(36)) + ''' + ' + + --and not exists (select 1 from dbo.S3LootGroup LOOTGROUP + -- where LOOTGROUP.LootID = ' + @lootIDExpression + ' + -- and LOOTGROUP.LootGroupID = ' + @expressionWithPrefix + ' + -- ) + + + + set @i = @i + 1; + Fetch Next from AttributeCursor INTO @ColName, @Prefix; +END; +CLOSE AttributeCursor; +DEALLOCATE AttributeCursor; + +set @sql = @sql + ' +create index idx_lootid on #s3lootgroup(lootid) + +--delete invalid ones +while (1 = 1) begin + DELETE top(1000) lg FROM S3LootGroup lg WHERE + lg.LootID IN (select nlg.LootID from #S3LootGroup nlg) + and NOT EXISTS ( + SELECT 1 + FROM #S3LootGroup nlg + WHERE lg.lootid = nlg.LootID and lg.lootgroupid = nlg.lootgroupid + ) + + if (@@rowcount = 0) break +end + +--add valid ones +CREATE TABLE #S3LootGroupInsert (RowID int primary key identity, LootID nvarchar(128), LootGroupID nvarchar(128)) +INSERT INTO #S3LootGroupInsert (LootID, LootGroupID) +SELECT DISTINCT + lootid, lootgroupid +FROM + #S3LootGroup nlg +WHERE + NOT EXISTS ( + SELECT 1 + FROM S3LootGroup lg + WHERE lg.lootid = nlg.LootID and lg.lootgroupid = nlg.lootgroupid + ) +declare @inscount int = 1 +declare @insmax int +select @insmax = max(RowID) from #S3LootGroupInsert +while(@inscount <= @insmax) begin + INSERT INTO S3LootGroup (LootID, LootGroupID) + select LootID, LootGroupID from #S3LootGroupInsert where RowID >= @inscount and RowID < @inscount + 1000 + + set @inscount = @inscount + 1000 +end +' + +set @sql = @sql + ' +DROP TABLE #S3LootGroup +DROP TABLE #S3LootGroupInsert +' + +if @IsDebugOnly = 0 begin + exec (@sql) +end else begin + print @sql +end +GO + + +--------------------------------------------- + +-- dbo.procScoreSyncDimensionGroups +CREATE proc [dbo].[procScoreSyncDimensionGroups] ( + @DimensionGUID uniqueidentifier, + @IsDebugOnly bit = 0 +) +AS +BEGIN + + +declare @PrimarySchema sysname; +declare @PrimaryObject sysname; + +select + @PrimaryObject = DG.ObjectName, + @PrimarySchema = DG.SchemaName +from ScoreDimension D + inner join ScoreDimensionGroup DG on DG.DimensionGUID = D.DimensionGUID +where DG.DimensionGroupGUID = D.PrimaryGroupGUID and D.DimensionGUID = @DimensionGUID; + +if (@PrimarySchema is null or @PrimaryObject is null) +begin + print 'Unable to find Primary Group'; + return; +end + +--cursor over secondaries +declare @GroupSchema sysname; +declare @GroupObject sysname; + +declare crsCursor CURSOR LOCAL FAST_FORWARD FOR + select + DG.SchemaName, + DG.ObjectName + from ScoreDimension D + inner join ScoreDimensionGroup DG on DG.DimensionGUID = D.DimensionGUID + where DG.DimensionGroupGUID <> D.PrimaryGroupGUID and D.DimensionGUID = @DimensionGUID + and dbo.IsView(DG.SchemaName,DG.ObjectName) = 0; -- don't sync view-backed dimension groups + +open crsCursor; + +FETCH NEXT FROM crsCursor into @GroupSchema, @GroupObject +WHILE (@@FETCH_STATUS = 0) + BEGIN + + declare @sql varchar(max); + set @sql = ' + INSERT INTO [' + @GroupSchema + '].[' + @GroupObject + '] ([MemberGUID]) + select P.[MemberGUID] from [' + @PrimarySchema + '].[' + @PrimaryObject + '] P + left join [' + @GroupSchema + '].[' + @GroupObject + '] S on S.[MemberGUID] = P.[MemberGUID] + where S.[MemberGUID] is null; + + DELETE FROM [' + @GroupSchema + '].[' + @GroupObject + '] + where [MemberGUID] not in (Select [MemberGUID] from [' + @PrimarySchema + '].[' + @PrimaryObject + ']); + '; + if (@IsDebugOnly = 1) begin + print @sql; + end + else begin + exec (@sql); + end + + FETCH NEXT FROM crsCursor into @GroupSchema, @GroupObject + END +close crsCursor; +DEALLOCATE crsCursor; + + + + +END +GO + + +--------------------------------------------- + +-- dbo.procScoreTruncateDimension +CREATE proc [dbo].[procScoreTruncateDimension] ( + @DimensionGUID uniqueidentifier, + @IsDebugOnly bit = 0 +) +AS +BEGIN + + declare @sql varchar(max); + set @sql = ''; + declare @schema sysname; + declare @object sysname; + + + declare crsCursor CURSOR LOCAL FAST_FORWARD FOR + select G.SchemaName, G.ObjectName from ScoreDimension D + inner join ScoreDimensionGroup G on G.DimensionGUID = D.DimensionGUID + where D.DimensionGUID = @DimensionGUID + + + open crsCursor; + + set @sql = 'BEGIN TRANSACTION TRUNCATE_DIMENSION; +'; + FETCH NEXT FROM crsCursor into @schema, @object + WHILE (@@FETCH_STATUS = 0) + BEGIN + + set @sql = @sql + 'TRUNCATE TABLE [' + @schema + '].[' + @object + ']; +'; + + FETCH NEXT FROM crsCursor into @schema, @object + END + close crsCursor; + DEALLOCATE crsCursor; + set @sql = @sql + 'COMMIT TRANSACTION TRUNCATE_DIMENSION;'; + + if (@IsDebugOnly = 1) begin + print @sql; + end + else begin + exec (@sql); + end + + + +END +GO + + +--------------------------------------------- + +-- dbo.procScoreUpdateLootPermissionSets +CREATE procedure [dbo].[procScoreUpdateLootPermissionSets] ( + @DimensionGUID uniqueidentifier +) +AS +BEGIN + + if not exists (select top 1 DimensionGUID from ScoreDimension where DimensionGUID =@DimensionGUID and IsSecured=1) + begin + print 'Dimension doesn''t exist, or it isn''t secured!' + return; + end + + declare @SecuredColumn nvarchar(128); + declare @SecuredPrefix nvarchar(128); + declare @SQLSchema nvarchar(128); + declare @SQLObject nvarchar(128); + declare @PSetID smallint; + + select + @SQLSchema = SQLSchemaName, + @SQLObject = SQLObjectName, + @PSetID = PermissionSetID + from ScoreDimension + where DimensionGUID = @DimensionGUID + + + select @SecuredColumn = A.SQLColumnName, + @SecuredPrefix = A.SecuredLootGroupPrefix + from ScoreDimension D + inner join [dbo].[ScoreDimensionGroup] sdg on d.DimensionGuid = sdg.DimensionGUID + inner join ScoreAttribute A on a.DimensionGroupGuid = sdg.DimensionGroupGUID + where D.DimensionGUID = @DimensionGUID and A.IsSecuredLootID = 1 + if (@SecuredColumn is null) + begin + print 'SecuredLootID column doesn''t exist!' + return; + end + + declare @sql varchar(max); + set @sql = ' + + UPDATE LOOT + SET LOOT.PermissionSetID = ' + cast(@PSetID as nvarchar(128)) + ' + FROM S3Loot LOOT + INNER JOIN ' + dbo.GetSQLTableExpression(@SQLSchema, @SQLObject) + ' DIM + ON LOOT.[LootID] = ''' + @SecuredPrefix +'|'' + cast(DIM.[' + @SecuredColumn + '] as nvarchar(128)) + WHERE LOOT.PermissionSetID != ' + cast(@PSetID as nvarchar(128)) + ' + + '; + + print @sql; + exec (@sql); +END +GO + + +--------------------------------------------- + +-- dbo.procScoreValidateConfig +CREATE proc [dbo].[procScoreValidateConfig] + @commit bit = 0 +as + + +set nocount on +declare @cnt int +declare @results as table (Result varchar(max)) +declare @sql nvarchar(max) + +--these should be done no matter what +exec procScoreFixMeasureAggTypes +exec procScoreAttributeSchemaUpdateAll + +begin try + begin tran + + -- + + --INVALID MODELGUID IN SCOREFILLIN + insert into @results + select distinct 'Deleted fillins for invalid modelguid: ' + isnull(CAST(modelguid as varchar(36)),'') from ScoreFillin where not modelguid in (select planguid from xplan) + + delete from ScoreFillin where not modelguid in (select planguid from xplan) + + + ----secured dimension with invalid permissionset + --insert into @results + --select 'Updated secured score dimension to have a valid permissionsetid: ' + isnull(FriendlyName,'') + --from + -- ScoreDimension + --where + -- IsSecured = 1 + -- and not PermissionSetID in (select PermissionSetID from S3PermissionSet) + + --update + -- ScoreDimension + --set + -- PermissionSetID = (select top 1 PermissionSetID from S3PermissionSet) --gotta pick 1! + --where + -- IsSecured = 1 + -- and not PermissionSetID in (select PermissionSetID from S3PermissionSet) + + --insert into @results + --select + -- 'NO AUTOFIX: Invalid dimension (' + isnull(SD.FriendlyName,'Missing') + ') attribute (' + isnull(SA.FriendlyName,'Missing') + ') for plantype (' + isnull(PT.Name,'Null') + ') ' + -- + case when isnull(SA.SecuredLootGroupPrefix,'') <> 'P' then 'No P Prefix, ' else '' end + -- + case when isnull(SA.ColumnType,0) <> 56 then 'Not integer, ' else '' end + --from + -- PlanType PT + -- left join ScoreDimension SD on PT.DimensionGUID = SD.DimensionGUID + -- left join ScoreAttribute SA on SD.DimensionGUID = SA.DimensionGUID + --where + -- SA.IsSecuredLootID = 1 + -- and ( + -- SA.AttributeGUID is null + -- or SA.SecuredLootGroupPrefix <> 'P' + -- or SA.ColumnType <> 56 + -- ) + + + insert into @results + select + 'NO AUTOFIX: exec dbo.procScoreDeleteDimension ''' + isnull(cast(sd.dimensionguid as varchar(36)),'') + ''' --Dimension "' + isnull(sd.FriendlyName,'') + '" (' + isnull(cast(sd.DimensionGUID as varchar(36)),'') + ') is missing source object: [' + isnull(sd.SQLSchemaName,'') + '].[' + isnull(sd.SQLObjectName,'') + ']' + from + scoredimension sd + where not + ( + dbo.viewexists(sd.sqlschemaname,sd.sqlobjectname) = 1 + or dbo.tableexists(sd.sqlschemaname,sd.sqlobjectname) = 1 + ) + + + insert into @results + select + 'Deleted ScoreDimensionGroup (' + sd.FriendlyName + '.' + sdg.Name + ') (and its attributes) because its sql object does not exist [' + sdg.SchemaName + '].[' + sdg.ObjectName + ']' + from + ScoreDimensionGroup sdg + inner join ScoreDimension sd on sdg.DimensionGUID = sd.DimensionGUID + + where not + ( + dbo.ViewExists(SchemaName, ObjectName) = 1 + or dbo.TableExists(SchemaName, ObjectName) = 1 + ) + + delete from ScoreAttribute where DimensionGroupGUID in ( + select DimensionGroupGUID from ScoreDimensionGroup where not + ( + dbo.ViewExists(SchemaName, ObjectName) = 1 + or dbo.TableExists(SchemaName, ObjectName) = 1 + ) + ) + + delete from ScoreDimensionGroup where not + ( + dbo.ViewExists(SchemaName, ObjectName) = 1 + or dbo.TableExists(SchemaName, ObjectName) = 1 + ) + + insert into @results + select + 'NO AUTOFIX: exec dbo.procScoreDeleteDataTable ''' + isnull(cast(DataTableGUID as varchar(36)),'') + '''--,0,1 --DataTable "' + isnull(FriendlyName,'') + '" (' + isnull(cast(DataTableGUID as varchar(36)),'') + ') is missing source object: [' + isnull(SQLSchemaName,'') + '].[' + isnull(SQLObjectName,'') + ']' + from + ScoreDataTable dt + where not + ( + dbo.viewexists(sqlschemaname,sqlobjectname) = 1 + or dbo.tableexists(sqlschemaname,sqlobjectname) = 1 + ) + order by FriendlyName + + insert into @results + select + 'Deleted ScoreMeasure, MeasureGUID = ''' + isnull(cast(MeasureGUID as varchar(36)),'') + ''' -- Missing column: [' + isnull(SQLSchemaName,'') + '].[' + isnull(SQLObjectName,'') + '].[' + ISNULL(sqlcolumnname,'') + ']' + from + ScoreMeasure sm + inner join ScoreDataTable dt on sm.DataTableGUID = dt.DataTableGUID + where not + ( + dbo.ColumnExists(SQLSchemaName, SQLObjectName, SQLColumnName) = 1 + ) + order by + SQLSchemaName, SQLObjectName, SQLColumnName + + delete sm from ScoreMeasure sm + inner join ScoreDataTable dt on sm.DataTableGUID = dt.DataTableGUID + where not + ( + dbo.ColumnExists(SQLSchemaName, SQLObjectName, SQLColumnName) = 1 + ) + + insert into @results + select + 'Deleted Invalid attribute (and its CompositeLinks and DataTableKeyLinks) (not in viewScoreAttributeCore30): ' + isnull(cast(sa.AttributeGUID as varchar(36)),'') + ' ' + isnull(sa.FriendlyName,'') + from + ScoreAttribute sa + where not AttributeGUID in (select AttributeGUID from viewScoreAttributeCore30) + + delete from ScoreDataTableKeyLink + where not KeyGUID in (select AttributeGUID from viewScoreAttributeCore30) + + delete from ScoreCompositeLink + where not Key1GUID in (select AttributeGUID from viewScoreAttributeCore30) + + delete from ScoreCompositeLink + where not Key2GUID in (select AttributeGUID from viewScoreAttributeCore30) + + delete from ScoreAttribute + where not AttributeGUID in (select AttributeGUID from viewScoreAttributeCore30) + + insert into @results + select + 'Deleted Invalid attribute (and its CompositeLinks and DataTableKeyLinks) (column does not exist): ' + cast(sa.AttributeGUID as varchar(36)) + ' ' + sa.DimensionName + ' ' + isnull(sa.FriendlyName,'') + from + viewScoreAttributeCore30 sa + where + IsColumnExist = 0 + + delete from ScoreDataTableKeyLink + where KeyGUID in (select AttributeGUID from viewScoreAttributeCore30 where IsColumnExist = 0) + + delete from ScoreCompositeLink + where Key1GUID in (select AttributeGUID from viewScoreAttributeCore30 where IsColumnExist = 0) + + delete from ScoreCompositeLink + where Key2GUID in (select AttributeGUID from viewScoreAttributeCore30 where IsColumnExist = 0) + + delete from ScoreAttribute + where AttributeGUID in (select AttributeGUID from viewScoreAttributeCore30 where IsColumnExist = 0) + + insert into @results + select + 'Updated (' + isnull(SD.FriendlyName,'Missing') + ') to not be secured, since it has no SecuredLootID' + from + ScoreDimension sd + where + IsSecured = 1 and + not exists ( + select 1 from + ScoreDimensionGroup sdg + inner join ScoreAttribute sa on sdg.DimensionGroupGUID = sa.DimensionGroupGUID + where + sd.DimensionGUID = sdg.DimensionGUID + and sa.IsSecuredLootID = 1 + ) + + update ScoreDimension + set IsSecured = 0 + where + IsSecured = 1 and + not exists ( + select 1 from + ScoreDimensionGroup sdg + inner join ScoreAttribute sa on sdg.DimensionGroupGUID = sa.DimensionGroupGUID + where + ScoreDimension.DimensionGUID = sdg.DimensionGUID + and sa.IsSecuredLootID = 1 + ) + + declare @total int + select @total = COUNT(*) from @results + + if @commit = 1 begin + commit + insert into @results select 'Changes committed.' + end else begin + rollback + insert into @results select 'Changes rolled back.' + end + + select * + from @results + +end try +begin catch + rollback + print error_message() + print 'Rollback rolled back. No changes have been applied.' +end catch +GO + + +--------------------------------------------- + +-- dbo.procSetIdentityInsert +CREATE PROCEDURE [dbo].[procSetIdentityInsert] +( + @SQLTableExpression varchar(max), + @IsOn bit +) +AS + +declare @sql varchar(max); +declare @ONorOFF varchar(8); + +if (@IsOn = 1) +BEGIN + set @ONorOFF = 'ON'; +END +ELSE + set @ONorOFF = 'OFF'; + +set @sql = 'set Identity_insert ' + @SQLTableExpression + ' ' + @ONorOFF; +print @sql; +exec (@sql) +GO + + +--------------------------------------------- + +-- dbo.procSetUserSecurityLastModifiedDate +-- ============================================= +-- Author: +-- Create date: <6/24/2008> +-- Description: +-- ============================================= +CREATE PROCEDURE procSetUserSecurityLastModifiedDate + -- Add the parameters for the stored procedure here + @UserGUID uniqueidentifier, + @LastModifiedDate DateTime = NULL +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + -- Make sure date time is set + IF @LastModifiedDate IS NULL SET @LastModifiedDate = GetDate() + + -- Attempt update + UPDATE UserSecurityLastModifiedDate + SET LastModifiedDate = @LastModifiedDate + WHERE UserGUID = @UserGUID + + -- If userguid doesn't exist, insert + IF @@ROWCOUNT=0 + INSERT INTO UserSecurityLastModifiedDate VALUES (@UserGUID, @LastModifiedDate) + +END +GO + + +--------------------------------------------- + +-- dbo.procShowGUIDsMB +CREATE PROC procShowGUIDsMB AS + +CREATE table #space (name varchar(100), rows int, reserved varchar(50), + data varchar(50), index_size varchar(50), unused varchar(50)) + +exec sp_MSforeachtable 'insert into #space exec sp_spaceused ''?'';' + +-- +--SELECT +-- name, +-- rows, +-- cast(replace(reserved, ' KB', '') as int) / 1000 as reserved, +-- cast(replace(data, ' KB', '') as int) / 1000 as data, +-- cast(replace(index_size, ' KB', '') as int) / 1000 as index_size, +-- cast(replace(unused, ' KB', '') as int) / 1000 as unused +-- from #space order by reserved DESC + +DECLARE @val FLOAT + +SELECT + --sysobjects.name, syscolumns.name, #space.rows, + @val = sum(#space.rows * 16.0) / 1000000.0 +FROM sysobjects + INNER JOIN syscolumns ON sysobjects.id = syscolumns.id + INNER JOIN #space ON #space.name = sysobjects.name +WHERE sysobjects.xtype='U' AND syscolumns.xtype = 36 + +PRINT 'All: ' + cast(@val AS varchar(max)) + ' MB' + +SELECT + --sysobjects.name, syscolumns.name, #space.rows, + @val = sum(#space.rows * 16.0) / 1000000.0 +FROM sysobjects + INNER JOIN syscolumns ON sysobjects.id = syscolumns.id + INNER JOIN #space ON #space.name = sysobjects.name +WHERE sysobjects.xtype='U' AND syscolumns.xtype = 36 AND sysobjects.name LIKE 'zz%' + +PRINT 'zzTables: ' + cast(@val AS varchar(max)) + ' MB' + +DROP TABLE #space +GO + + +--------------------------------------------- + +-- dbo.procShowLargestModels +CREATE PROC [dbo].[procShowLargestModels] AS + SET NOCOUNT ON; + + DECLARE @zzMDCGUID uniqueidentifier + DECLARE @mdcName nvarchar(max) + DECLARE @zzMDCtablename nvarchar(36) +-- DECLARE @zzDIMcursor nvarchar(256) +-- DECLARE @zzDIMcolumnname nvarchar(256) + DECLARE @modelTemplateMappingTableName nvarchar(256) + DECLARE @modelDataTableName nvarchar(256) +-- DECLARE @dimensionName as nvarchar(256) +-- DECLARE @dimensionGUID as uniqueidentifier +-- DECLARE @fixSQL as nvarchar(max) + DECLARE @sql varchar(max) + + CREATE TABLE #Biggest (IsTemplate BIT , name varchar(max), rows int) + + DECLARE zztable CURSOR LOCAL FAST_FORWARD + FOR SELECT NAME, MODELDATACONFIGGUID FROM EMFModelDataConfig + OPEN zztable + FETCH NEXT FROM zztable INTO @mdcName, @zzMDCGUID + WHILE @@FETCH_STATUS = 0 + BEGIN + + + --SET @zztable_query = 'ALTER TABLE ' + @zztable_name + ' ADD [MAPPINGTYPE] int NOT NULL Default(0) WITH VALUES' + --EXECUTE sp_executesql @zztable_query + SET @zzMDCtablename = REPLACE(@zzMDCGUID,'-','_') + + SET @modelTemplateMappingTableName = 'zzEMFModelTemplateMapping_' + @zzMDCtablename + if (select count(*) from sysobjects where xtype='u' and name like @modelTemplateMappingTableName) <> 0 BEGIN + SET @sql = 'DECLARE @name varchar(max); DECLARE @cnt int; SELECT TOP 1 @name = MT.NAME, @cnt = COUNT(*) FROM ' + @modelTemplateMappingTableName + ' MAP INNER JOIN EMFMODELTEMPLATE MT ON MT.MODELTEMPLATEGUID = MAP.MODELTEMPLATEGUID GROUP BY MT.NAME ORDER BY COUNT(*) DESC + ; INSERT INTO #Biggest (IsTemplate, name, Rows) VALUES (1, @name, @cnt)' + EXEC (@sql) + END + + +-- SET @modelDataTableName = 'zzEMFModelData_' + @zzMDCtablename +-- if (select count(*) from sysobjects where xtype='u' and name like @modelDataTableName) = 0 +-- PRINT @modelDataTableName + ' table is not present' +-- else begin +-- --exec procEnsureColumnInTable @modelDataTableName ,'MODELGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode +-- exec procEnsureDimensionColumnsInTable @modelDataTableName, @zzMDCGUID, @DebugMode, 0 +-- exec procEnsureColumnInTable @modelDataTableName ,'MEASUREGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode +-- exec procEnsureColumnInTable @modelDataTableName ,'VALUE', 'float', '0', @DebugMode +-- exec procEnsureColumnInTable @modelDataTableName ,'FORMULA', 'varchar(1024)', '''''', @DebugMode +-- exec procEnsureColumnInTable @modelDataTableName ,'STRINGVALUE', 'varchar(1024)', '''''', @DebugMode +-- exec procEnsureColumnInTable @modelDataTableName ,'RISKVARIABLEGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode +-- exec procEnsureColumnInTable @modelDataTableName ,'HISTORYITEMGUID', 'uniqueidentifier', '''00000000-0000-0000-0000-000000000000''', @DebugMode +-- end + + +-- DECLARE zzdimensions CURSOR LOCAL FAST_FORWARD +-- FOR SELECT SLM.LISTGUID, SLM.NAME, UPPER('G' + REPLACE(cast(SLM.LISTGUID as varchar(36)),'-','_')) FROM dbo.EMFModelDataConfigDimensionLink MDCDL JOIN SECURELIST SLM ON MDCDL.DIMENSIONGUID=SLM.LISTGUID WHERE MDCDL.MODELDATACONFIGGUID = @zzMDCGUID +-- OPEN zzdimensions +-- FETCH NEXT FROM zzdimensions INTO @dimensionGUID, @dimensionName, @zzDIMcursor +-- WHILE @@FETCH_STATUS = 0 +-- BEGIN +-- SET @zzDIMcolumnname = @zzDIMcursor --+ 'GUID' +-- SET @fixSQL = 'DELETE FROM emfmodeldataconfigdimensionlink WHERE DIMENSIONGUID = ''' + cast(@dimensionGUID as varchar(36)) + ''' and MODELDATACONFIGGUID = ''' + cast(@zzMDCGUID as varchar(36)) + '''' +-- IF (SELECT count(*) FROM sysobjects JOIN syscolumns ON sysobjects.id = syscolumns.id WHERE sysobjects.xtype='U' AND (sysobjects.name like @modelDataTableName or sysobjects.name like @modelMappingTableName or sysobjects.name like @modelTemplateMappingTableName)and syscolumns.name like @zzDIMcolumnname) <> 3 +-- --PRINT ' ' + @zzDIMcolumnname + ' is present' +-- --ELSE +-- PRINT @fixSQL + ' --' + cast(@zzMDCGUID as varchar(36)) + ' (' + @mdcName + ') - ' + @zzDIMcolumnname + ' (' + @dimensionName + ') is not present in both ModelData and ModelMapping' +-- +-- +-- FETCH NEXT FROM zzdimensions INTO @dimensionGUID, @dimensionName, @zzDIMcursor +-- END +-- CLOSE zzdimensions +-- DEALLOCATE zzdimensions +-- + FETCH NEXT FROM zztable INTO @mdcName, @zzMDCGUID + END + CLOSE zztable + DEALLOCATE zztable + + + SELECT TOP 10 * FROM #Biggest ORDER BY rows DESC + DROP TABLE #Biggest +GO + + +--------------------------------------------- + +-- dbo.procShowTableSizes +CREATE procedure [dbo].[procShowTableSizes] + @orderByColumn varchar(max) = '' +as +create table #space (name varchar(100), rows int, reserved varchar(50), + data varchar(50), index_size varchar(50), unused varchar(50)) + +exec sp_MSforeachtable 'insert into #space exec sp_spaceused ''?'';' + +select + name, + rows, + cast(replace(reserved, ' KB', '') as int) / 1000 as reserved, + cast(replace(data, ' KB', '') as int) / 1000 as data, + cast(replace(index_size, ' KB', '') as int) / 1000 as index_size, + cast(replace(unused, ' KB', '') as int) / 1000 as unused, + round(case when rows = 0 then 0 else cast(replace(reserved, ' KB', '') as float) / rows end,2) as KBperrow +from #space +order by reserved desc + +drop table #space +GO + + +--------------------------------------------- + +-- dbo.procStrataCLRDrop +CREATE PROCEDURE dbo.procStrataCLRDrop + -- Add the parameters for the stored procedure here +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + + --First we need to drop all the Wrapper objects that are dependent on the Assembly which include CLR { Aggregates, Scalars, Stored Procedures, Table Value Functions & Triggers } + DECLARE @asmname NVARCHAR(1000); + DECLARE @d_sql NVARCHAR(MAX); + DECLARE @drop_type VARCHAR(100) + + --****Don't forget to set the correct *OLD* (NOT NEW) assembly name. + SET @asmname = N'StrataCLR'; + + -- CURSOR VARIABLES -- + + DECLARE @wname NVARCHAR(1000); + DECLARE @wtype NVARCHAR(1000); + + -- CURSOR VARIABLES (END) -- + + DECLARE dCursor CURSOR FAST_FORWARD FOR + SELECT '[' + ss.name + '].[' + o.name + ']' AS wraper_name, o.type + FROM sys.assembly_modules am + JOIN sys.objects o ON am.object_id = o.object_id + JOIN sys.assemblies sas ON sas.assembly_id = am.assembly_id + JOIN sys.schemas ss ON ss.schema_id = o.schema_id + WHERE sas.name = @asmname + + OPEN dCursor + + FETCH NEXT FROM dCursor INTO @wname, @wtype + + WHILE @@FETCH_STATUS = 0 + BEGIN + + SET @drop_type = ''; + + IF @wtype IN ('PC', 'P') + SELECT @drop_type = 'PROCEDURE' + + IF @wtype IN ('FN', 'FS', 'FT', 'IF', 'TF') + SELECT @drop_type = 'FUNCTION' + + IF @wtype = 'AF' + SELECT @drop_type = 'AGGREGATE' + + IF @wtype = 'U' + SELECT @drop_type = 'TABLE' + + IF @wtype = 'V' + SELECT @drop_type = 'VIEW' + + IF @drop_type <> '' + BEGIN + SET @d_sql = 'DROP '+ @drop_type + ' ' + @wname + EXEC(@d_sql); + END + + FETCH NEXT FROM dCursor INTO @wname, @wtype + END + + CLOSE dCursor + DEALLOCATE dCursor + + --Finally drop the Assembly + SET @d_sql = N'IF EXISTS (SELECT * FROM sys.assemblies asms WHERE asms.name = ''' + @asmname + ''' AND is_user_defined = 1) DROP ASSEMBLY [StrataCLR]' + + EXEC(@d_sql) + +END +GO + + +--------------------------------------------- + +-- dbo.procSyncEMFDimensionWithScore +CREATE procedure [dbo].[procSyncEMFDimensionWithScore] + @listGUID uniqueidentifier, + @dimGUID uniqueidentifier, + @updateMemberGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000', + @nameCol nvarchar(64) = 'Name', + @sortCol nvarchar(64) = 'Name', + @scoreWhereClause nvarchar(4000) = '(1 = 1)', + @isdebug bit = 0 +as + set nocount on + + --verify dimension integrity + if((select COUNT(*) from SecureList where ListGUID = @listGUID) = 0) begin + RAISERROR ('EMF dimension not found.', 18, 0) + return + end + if((select COUNT(*) from ScoreDimension where DimensionGUID = @dimGUID) = 0) begin + RAISERROR ('Score dimension not found.', 18, 0) + return + end + if((select COUNT(*) from SecureListProperty LP left join viewScoreAttributeCore30 SA on SA.FriendlyName = LP.Name and SA.DimensionGUID = @dimGUID where LP.ListGUID = @listGUID and SA.AttributeGUID is null) > 0) begin + RAISERROR ('Attribute names don''t match.', 18, 0) + return + end + if((select COUNT(*) from SecureListLevel where ListGUID = @listGUID) > 2) begin + RAISERROR ('Dimensions with more than 2 levels are not supported.', 18, 0) + return + end + if((select COUNT(*) from SecureListLevel where ListGUID = @listGUID) > 1) begin + if((select COUNT(*) from SecureListLevel LL left join viewScoreAttributeCore30 SA on SA.FriendlyName = LL.Name and SA.DimensionGUID = @dimGUID where LL.LevelIndex = 0 and LL.ListGUID = @listGUID and SA.AttributeGUID is null) > 0) begin + RAISERROR ('Level names don''t match.', 18, 0) + return + end + end + + + --get score dimension table name + declare @dimTable nvarchar(100) + select @dimTable = SQLSchemaName + '.' + SQLObjectName from ScoreDimension where DimensionGUID = @dimGUID + + --get emf cache table name + declare @cacheTable nvarchar(100) + set @cacheTable = 'zzList_' + REPLACE(cast(@listGUID as nvarchar(36)), '-', '_') + + --get emf levels + declare @levelLeaf uniqueidentifier + declare @levelCategory uniqueidentifier + if((select COUNT(*) from SecureListLevel where ListGUID = @listGUID) > 1) begin + select @levelLeaf = ListLevelGUID from SecureListLevel where ListGUID = @listGUID and LevelIndex = 1 + select @levelCategory = ListLevelGUID from SecureListLevel where ListGUID = @listGUID and LevelIndex = 0 + end else begin + select @levelLeaf = ListLevelGUID from SecureListLevel where ListGUID = @listGUID and LevelIndex = 0 + select @levelCategory = dbo.ZeroGUID() + end + declare @levelCategoryName nvarchar(100) + +select + @levelCategoryName = SA.SQLColumnName +from SecureListLevel LL +left join viewScoreAttributeCore30 SA on SA.FriendlyName = LL.Name and SA.DimensionGUID = @dimGUID +where + LL.ListLevelGUID = @levelCategory + --select @levelCategoryName = Name from SecureListLevel where ListLevelGUID = @levelCategory + + --get lootid info + declare @lootidPrefix nvarchar(100) + declare @lootidColName nvarchar(100) + set @lootidPrefix = coalesce((select SecuredLootGroupPrefix from viewScoreAttributeCore30 where IsSecuredLootID = 1 and DimensionGUID = @dimGUID), '') + set @lootidColName = coalesce((select SQLColumnName from viewScoreAttributeCore30 where IsSecuredLootID = 1 and DimensionGUID = @dimGUID), 'MemberGUID') + if(@lootidPrefix != '') begin + set @lootidPrefix = @lootidPrefix + '|' + end + + --delete missing emf members + declare @deletesql nvarchar(max) + set @deletesql = 'delete from SecureListMember where ListGUID = ''' + CAST(@listGUID as nvarchar(36)) + ''' and ListMemberGUID not in(select MemberGUID from ' + @dimTable + ' where ' + @scoreWhereClause + ')' + if(@levelCategory != dbo.ZeroGUID()) begin + --don't delete parent members + set @deletesql = @deletesql + ' and ParentListMemberGUID != dbo.ZeroGUID()' + end + if(@updateMemberGUID != dbo.ZeroGUID()) begin + --only delete specified member + set @deletesql = @deletesql + ' and ListMemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + '''' + end + + --delete from list cache also + set @deletesql = @deletesql + '; delete from ' + @cacheTable + ' where ListMemberGUID not in(select MemberGUID from ' + @dimTable + ' where ' + @scoreWhereClause + ')' + if(@levelCategory != dbo.ZeroGUID()) begin + --don't delete parent members + set @deletesql = @deletesql + ' and coalesce(L' + replace(CAST(@levelLeaf as nvarchar(36)), '-', '_') + ', dbo.ZeroGUID()) != dbo.ZeroGUID()' + end + if(@updateMemberGUID != dbo.ZeroGUID()) begin + --only delete specified member + set @deletesql = @deletesql + ' and ListMemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + '''' + end + + + --commit deletes + if(@isdebug = 1) begin + print @deletesql + end else begin + exec(@deletesql) + end + + --create missing members + declare @insertsql nvarchar(max) + set @insertsql = ' + INSERT INTO [SecureListMember] ([ListMemberGUID], [ListGUID], [ParentListMemberGUID], [Name], [Description], [FullPath], [DisplayOrder], [OutlineLevel], [ListMemberID], [SortOrderFullPath], [DateCreated], [DateModified], [LootIDOverride]) + select + MemberGUID, + ''' + cast(@listGUID as nvarchar(36)) + ''', + dbo.ZeroGUID(), + ' + @nameCol + ', + '''', + ''' + cast(@listGUID as nvarchar(36)) + '\'' + CAST(MemberGUID as nvarchar(36)) + ''\'', + 0, + 0, + cast(MemberGUID as nvarchar(36)), + ''00000000\'', + GETDATE(), + GETDATE(), + ''' + @lootidPrefix + ''' + cast(' + @lootidColName + ' as nvarchar(100)) + from + ' + @dimTable + ' + where + ' + @scoreWhereClause + ' + and MemberGUID not in(select ListMemberGUID from SecureListMember where ListGUID = ''' + CAST(@listGUID as nvarchar(36)) + ''')' + if(@updateMemberGUID != dbo.ZeroGUID()) begin + --only create specified member + set @insertsql = @insertsql + ' and MemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + '''' + end + + --create missing parents + if(@levelCategory != dbo.ZeroGUID()) begin + set @insertsql = @insertsql + '; + declare @parentName nvarchar(100) + declare crsParents cursor for select distinct ' + @levelCategoryName + ' from ' + @dimTable + ' where ' + @scoreWhereClause + ' and ' + @levelCategoryName + ' not in(select Name from SecureListMember where ParentListMemberGUID = dbo.ZeroGUID() and ListGUID = ''' + CAST(@listGUID as nvarchar(36)) + ''')' + if(@updateMemberGUID != dbo.ZeroGUID()) begin + --only create parent of specified member + set @insertsql = @insertsql + ' and MemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + '''' + end + + set @insertsql = @insertsql + ' + open crsParents + fetch next from crsParents into @parentName + + declare @parentGUID uniqueidentifier + while(@@fetch_status = 0) begin + select @parentGUID = newid() + + INSERT INTO [SecureListMember] ([ListMemberGUID], [ListGUID], [ParentListMemberGUID], [Name], [Description], [FullPath], [DisplayOrder], [OutlineLevel], [ListMemberID], [SortOrderFullPath], [DateCreated], [DateModified], [LootIDOverride]) + select + @parentGUID, + ''' + cast(@listGUID as nvarchar(36)) + ''', + dbo.ZeroGUID(), + @parentName, + '''', + ''' + cast(@listGUID as nvarchar(36)) + '\'' + CAST(@parentGUID as nvarchar(36)) + ''\'', + 0, + 0, + cast(@parentGUID as nvarchar(36)), + ''00000000\'', + GETDATE(), + GETDATE(), + '''' + + fetch next from crsParents into @parentName + end + + close crsParents + deallocate crsParents' + end + + --fix parents + if(@levelCategory != dbo.ZeroGUID()) begin + set @insertsql = @insertsql + '; + update LM set LM.ParentListMemberGUID = PLM.ListMemberGUID, LM.FullPath = PLM.FullPath + cast(LM.ListMemberGUID as nvarchar(36)) + ''\'', SortOrderFullPath = ''00000000\00000000\'', OutlineLevel=1 + from + SecureListMember LM + inner join ' + @dimTable + ' SD on SD.MemberGUID = LM.ListMemberGUID + inner join SecureListMember PLM on PLM.Name = SD.' + @levelCategoryName + ' and PLM.OutlineLevel = 0 + where + ' + @scoreWhereClause + ' + and LM.ListGUID = ''' + CAST(@listGUID as nvarchar(36)) + ''' + and LM.ParentListMemberGUID != PLM.ListMemberGUID + ' + if(@updateMemberGUID != dbo.ZeroGUID()) begin + --only fix specified member + set @insertsql = @insertsql + ' and LM.ListMemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + '''' + end + end + + --add missing parents in cache + if(@levelCategory != dbo.ZeroGUID()) begin + set @insertsql = @insertsql + '; + INSERT INTO ' + @cacheTable + ' (L' + replace(CAST(@levelCategory as nvarchar(36)), '-', '_') + ', Name, ListMemberGUID) + select ListMemberGUID, Name, ListMemberGUID + from SecureListMember + where OutlineLevel = 0 and ListGUID = ''' + CAST(@listGUID as nvarchar(36)) + ''' and ListMemberGUID not in(select ListMemberGUID from ' + @cacheTable + ')' + end + + --add other new members to list cache + set @insertsql = @insertsql + '; + INSERT INTO ' + @cacheTable + ' (L' + replace(CAST(@levelLeaf as nvarchar(36)), '-', '_') + ', Name, ListMemberGUID) + select ListMemberGUID, Name, ListMemberGUID + from SecureListMember + where ListGUID = ''' + CAST(@listGUID as nvarchar(36)) + ''' and ListMemberGUID not in(select ListMemberGUID from ' + @cacheTable + ')' + if(@updateMemberGUID != dbo.ZeroGUID()) begin + --only create specified member + set @insertsql = @insertsql + ' and ListMemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + '''' + end + + --fix parents of leaf members in cache + if(@levelCategory != dbo.ZeroGUID()) begin + set @insertsql = @insertsql + '; + update LC set LC.L' + replace(cast(@levelCategory as nvarchar(36)), '-', '_') + ' = LM.ParentListMemberGUID + from + ' + @cacheTable + ' LC + inner join SecureListMember LM on LC.ListMemberGUID = LM.ListMemberGUID + where + LM.ListGUID = ''' + CAST(@listGUID as nvarchar(36)) + ''' + and LM.OutlineLevel = 1 + and coalesce(LC.L' + replace(cast(@levelCategory as nvarchar(36)), '-', '_') + ', dbo.ZeroGUID()) != LM.ParentListMemberGUID + ' + if(@updateMemberGUID != dbo.ZeroGUID()) begin + --only fix specified member + set @insertsql = @insertsql + ' and LC.ListMemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + '''' + end + end + + --commit inserts + if(@isdebug = 1) begin + print @insertsql + end else begin + exec(@insertsql) + end + + --create missing membervalue records + declare @valsyncsql nvarchar(max) + set @valsyncsql = ' + insert into SecureListMemberValue(ListMemberValueGUID, ListMemberGUID, ListGUID, Type, ValueFloat, ValueText, ValueIndex) + select + NEWID(), + LM.ListMemberGUID, + LM.ListGUID, + case when LP.PropertyType = 1 then 1 else 0 end, + 0, + '''', + LP.PropertyIndex + from + SecureListMember LM + inner join SecureListProperty LP on LP.ListGUID = LM.ListGUID + left join SecureListMemberValue LMV on LMV.ListMemberGUID = LM.ListMemberGUID and LMV.ValueIndex = LP.PropertyIndex + where + LM.ListGUID = ''' + CAST(@listGUID as nvarchar(36)) + ''' + and LMV.ListMemberValueGUID is null' + if(@updateMemberGUID != dbo.ZeroGUID()) begin + --only create for specified member + set @valsyncsql = @valsyncsql + ' and LM.ListMemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + '''' + end + if(@isdebug = 1) begin + print @valsyncsql + end else begin + exec(@valsyncsql) + end + + --update member name + declare @updatesql nvarchar(max) + set @updatesql = ' + update LM set LM.Name = SD.' + @nameCol + ' + from + SecureListMember LM + inner join ' + @dimTable + ' SD on SD.MemberGUID = LM.ListMemberGUID + where + ' + @scoreWhereClause + ' + and LM.Name != SD.' + @nameCol + ' + and LM.ListGUID = ''' + CAST(@listGUID as nvarchar(36)) + '''' + if(@updateMemberGUID != dbo.ZeroGUID()) begin + --only update specified member + set @updatesql = @updatesql + ' and LM.ListMemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + '''' + end + + --iterate through properties + declare @emfpropGUID uniqueidentifier + declare @emfpropType int + declare @scorepropName nvarchar(100) + declare crsAttributes cursor for select LP.ListPropertyGUID, LP.PropertyType, '[' + SA.SQLColumnName + ']' from SecureListProperty LP left join viewScoreAttributeCore30 SA on SA.FriendlyName = LP.Name and SA.DimensionGUID = @dimGUID where LP.ListGUID = @listGUID + open crsAttributes + fetch next from crsAttributes into @emfpropGUID, @emfpropType, @scorepropName + + --update property values + while(@@FETCH_STATUS = 0) begin + --member value table updates + if(@emfpropType = 1) begin + --numeric property update + set @updatesql = @updatesql + '; + update LMV set LMV.ValueFloat = SD.' + @scorepropName + ', LMV.ValueText = '''' + from + SecureListMemberValue LMV + inner join SecureListProperty LP on LP.ListGUID = LMV.ListGUID and LP.PropertyIndex = LMV.ValueIndex + inner join ' + @dimTable + ' SD on SD.MemberGUID = LMV.ListMemberGUID + where + ' + @scoreWhereClause + ' + and LMV.ListGUID = ''' + cast(@listGUID as nvarchar(36)) + ''' + and LP.ListPropertyGUID = ''' + CAST(@emfpropGUID as nvarchar(36)) + ''' + and LMV.ValueFloat != SD.' + @scorepropName + end else begin + --text property update + set @updatesql = @updatesql + '; + update LMV set LMV.ValueFloat = 0, LMV.ValueText = SD.' + @scorepropName + ' + from + SecureListMemberValue LMV + inner join SecureListProperty LP on LP.ListGUID = LMV.ListGUID and LP.PropertyIndex = LMV.ValueIndex + inner join ' + @dimTable + ' SD on SD.MemberGUID = LMV.ListMemberGUID + where + ' + @scoreWhereClause + ' + and LMV.ListGUID = ''' + cast(@listGUID as nvarchar(36)) + ''' + and LP.ListPropertyGUID = ''' + CAST(@emfpropGUID as nvarchar(36)) + ''' + and LMV.ValueText != cast(SD.' + @scorepropName + ' as nvarchar(1000))' + end + if(@updateMemberGUID != dbo.ZeroGUID()) begin + --only update specified member + set @updatesql = @updatesql + ' and LMV.ListMemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + '''' + end + + --list cache (cheat and update name here too) + set @updatesql = @updatesql + '; + update LC set LC.Name = SD.' + @nameCol + ', LC.P' + replace(CAST(@emfpropguid as nvarchar(36)), '-', '_') + ' = SD.' + @scorepropName + ' + from + ' + @cacheTable + ' LC + inner join ' + @dimTable + ' SD on SD.MemberGUID = LC.ListMemberGUID + where + ' + @scoreWhereClause + ' + and (LC.Name != SD.' + @nameCol + ' or LC.P' + replace(CAST(@emfpropguid as nvarchar(36)), '-', '_') + ' is null or LC.P' + replace(CAST(@emfpropguid as nvarchar(36)), '-', '_') + ' != SD.' + @scorepropName + ')' + if(@updateMemberGUID != dbo.ZeroGUID()) begin + --only update specified member + set @updatesql = @updatesql + ' and LC.ListMemberGUID = ''' + CAST(@updateMemberGUID as nvarchar(36)) + '''' + end + + fetch next from crsAttributes into @emfpropGUID, @emfpropType, @scorepropName + end + + --update display orders for the whole dimension + declare @tmpname nvarchar(50) + select @tmpname = '##tmp' + replace(cast(newid() as nvarchar(36)), '-', '') + set @updatesql = @updatesql + '; + select MemberGUID, rank() over (order by ' + @sortCol + ') as [Rank] into ' + @tmpname + ' from ' + @dimTable + '; + + update SLM set SLM.DisplayOrder = O.Rank, SLM.SortOrderFullPath = (SUBSTRING(''00000000'', 1, 8 - len(O.Rank)) + CAST(O.Rank as nvarchar(8)) + ''\'') + from + SecureListMember SLM + inner join ' + @tmpname + ' O on O.MemberGUID = SLM.ListMemberGUID and SLM.DisplayOrder != O.Rank + where + SLM.ListGUID = ''' + cast(@listGUID as nvarchar(36)) + '''; + + drop table ' + @tmpname + + --commit updates + close crsAttributes + deallocate crsAttributes + if(@isdebug = 1) begin + print @updatesql + end else begin + exec(@updatesql) + end +GO + + +--------------------------------------------- + +-- dbo.procSyncEMFDimensionWithScoreCreate +CREATE procedure [dbo].[procSyncEMFDimensionWithScoreCreate] + @listGUID uniqueidentifier, + @dimGUID uniqueidentifier, + @dimTableSchema nvarchar(64), + @dimTableName nvarchar(64), + @nameCol nvarchar(64) = 'Name', + @sortCol nvarchar(64) = 'Name', + @tolerance int = 200, + @isdebug bit = 0 +as + declare @sql nvarchar(max) + + set @sql = ' + CREATE TRIGGER ' + @dimTableSchema + '.[' + replace(replace(@dimTableName, '[', ''), ']', '') + 'Sync] + ON ' + @dimTableSchema + '.[' + replace(replace(@dimTableName, '[', ''), ']', '') + '] + AFTER INSERT, DELETE, UPDATE + AS + BEGIN + SET NOCOUNT ON; + + declare @memberGUID uniqueidentifier + + --short-circuit and just refresh everything if there were a lot of updates + if(((select count(*) from INSERTED) + (select count(*) from DELETED)) > ' + CAST(@tolerance as nvarchar(8)) + ') begin + exec procSyncEMFDimensionWithScore ''' + cast(@listGUID as nvarchar(36)) + ''', ''' + cast(@dimGUID as nvarchar(36)) + ''', ''00000000-0000-0000-0000-000000000000'', ''' + @nameCol + ''', ''' + @sortCol + ''' + return + end + + --process deleted + declare crsDeleted cursor for select MemberGUID from DELETED where MemberGUID not in(select MemberGUID from INSERTED) + open crsDeleted + fetch next from crsDeleted into @memberGUID + while(@@fetch_status = 0) begin + exec procSyncEMFDimensionWithScore ''' + cast(@listGUID as nvarchar(36)) + ''', ''' + cast(@dimGUID as nvarchar(36)) + ''', @memberGUID, ''' + @nameCol + ''', ''' + @sortCol + ''' + fetch next from crsDeleted into @memberGUID + end + close crsDeleted + deallocate crsDeleted + + --process inserted + declare crsInserted cursor for select MemberGUID from INSERTED where MemberGUID not in(select MemberGUID from DELETED) + open crsInserted + fetch next from crsInserted into @memberGUID + while(@@fetch_status = 0) begin + exec procSyncEMFDimensionWithScore ''' + cast(@listGUID as nvarchar(36)) + ''', ''' + cast(@dimGUID as nvarchar(36)) + ''', @memberGUID, ''' + @nameCol + ''', ''' + @sortCol + ''' + fetch next from crsInserted into @memberGUID + end + close crsInserted + deallocate crsInserted + + --process updated + declare crsUpdated cursor for select MemberGUID from INSERTED where MemberGUID in(select MemberGUID from DELETED) + open crsUpdated + fetch next from crsUpdated into @memberGUID + while(@@fetch_status = 0) begin + exec procSyncEMFDimensionWithScore ''' + cast(@listGUID as nvarchar(36)) + ''', ''' + cast(@dimGUID as nvarchar(36)) + ''', @memberGUID, ''' + @nameCol + ''', ''' + @sortCol + ''' + fetch next from crsUpdated into @memberGUID + end + close crsUpdated + deallocate crsUpdated + END + ' + + if(@isdebug = 1) begin + print @sql + end else begin + exec(@sql) + end +GO + + +--------------------------------------------- + +-- dbo.procSyncEMFDimensionWithScoreDrop +CREATE procedure [dbo].[procSyncEMFDimensionWithScoreDrop] + @dimTableSchema nvarchar(64), + @dimTableName nvarchar(64), + @isdebug bit = 0 +as + declare @sql nvarchar(max) + + set @sql = 'DROP TRIGGER ' + @dimTableSchema + '.[' + REPLACE(REPLACE(@dimTableName, '[', ''), ']', '') + 'Sync]' + + if(@isdebug = 1) begin + print @sql + end else begin + exec(@sql) + end +GO + + +--------------------------------------------- + +-- dbo.procSysDisableChangeTrackingOnTable +CREATE PROCEDURE [dbo].[procSysDisableChangeTrackingOnTable] +( + @schemaName NVARCHAR(128), + @tableName NVARCHAR(128) +) +AS +BEGIN + DECLARE @fulltablename NVARCHAR(256) = @schemaName + '.' + @tableName; + DECLARE @SQL VARCHAR(MAX); + SET @SQL = 'IF EXISTS (SELECT 1 FROM sys.change_tracking_tables + WHERE object_id = OBJECT_ID(N''' + @fulltablename + ''')) + BEGIN + ALTER TABLE ' + @fulltablename + ' DISABLE CHANGE_TRACKING + END' + + Exec(@SQL); +END +GO + + +--------------------------------------------- + +-- dbo.procSysDropAllColumnConstraints +CREATE procedure [dbo].[procSysDropAllColumnConstraints] ( + @schema sysname, + @object sysname +) +AS +BEGIN + +declare @tableexpression sysname; +set @tableexpression = dbo.GetSQLTableExpression(@schema, @object); + + +declare colCursor CURSOR local FAST_FORWARD FOR + select ColumnName from viewSysColumns where ObjectID = OBJECT_ID(@tableexpression); + +open colCursor; + +DECLARE @column nvarchar(128); + +FETCH NEXT FROM colCursor into @column +WHILE (@@FETCH_STATUS = 0) + BEGIN + exec procSysDropColumnConstraints @schema, @object, @column; + --print 'exec procSysDropColumnConstraints @schema, @table, @column'; + FETCH NEXT FROM colCursor into @column + END +close colCursor; +DEALLOCATE colCursor; + + +END +GO + + +--------------------------------------------- + +-- dbo.procSysDropClusteredIndex +create procedure [dbo].[procSysDropClusteredIndex] (@schema sysname, @table sysname) +AS +BEGIN + + --DROP CLUSTERED INDEX + declare @tableexpression sysname; + set @tableexpression = dbo.GetSQLTableExpression(@schema, @table); + + declare @ClusteredIndexName varchar(200) + set @ClusteredIndexName = (select i.name from sys.indexes i + inner join sys.tables t on i.object_id=t.object_id + inner join sys.schemas s on t.schema_id=s.schema_id + where t.type = 'u' and t.name = @table and s.name = @schema and i.type = 1) + + declare @sql nvarchar(max); + set @sql = ' + IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N''[' + @schema + '].[' + @table + ']'') AND name = N''' + @ClusteredIndexName + ''' and is_primary_key = 1) + ALTER TABLE ' + @tableexpression + ' DROP CONSTRAINT [' + @ClusteredIndexName + '] + IF EXISTS (SELECT 1 FROM sys.indexes WHERE object_id = OBJECT_ID(N''[' + @schema + '].[' + @table + ']'') AND name = N''' + @ClusteredIndexName + ''' and is_primary_key = 0) + DROP INDEX ' + @ClusteredIndexName + ' ON ' + @tableexpression + ' WITH ( ONLINE = OFF )' + exec sp_executesql @sql; + +END + + +RETURN +GO + + +--------------------------------------------- + +-- dbo.procSysDropColumnAndDefault +CREATE PROC [dbo].[procSysDropColumnAndDefault] + @schema SYSNAME, + @table SYSNAME, + @column SYSNAME +AS + + DECLARE @sql VARCHAR(MAX) + SET @sql = ' + ALTER TABLE [{0}].[{1}] DROP COLUMN [{2}] + ' + + IF (dbo.ColumnExists(@schema, @table, @column) = 1) + BEGIN + SET @sql = REPLACE(@sql, '{0}', @schema) + SET @sql = REPLACE(@sql, '{1}', @table) + SET @sql = REPLACE(@sql, '{2}', @column) + + BEGIN TRY + EXEC procSysDropColumnConstraints @schema, @table, @column + EXEC (@sql) + END TRY + BEGIN CATCH + PRINT 'Column drop not successful: ' + @schema + '.' + @table + '.' + @column + EXEC procSysRethrowError + END CATCH + END +GO + + +--------------------------------------------- + +-- dbo.procSysDropColumnConstraints +CREATE proc [dbo].[procSysDropColumnConstraints] + @schemaName sysname, + @tableName sysname, + @columnName sysname, + @includeCheck bit = 1, + @includeFK bit = 1, + @includePK bit = 1, + @includeUnique bit = 1, + @includeDefault bit = 1 +as + + +declare crsCursor CURSOR local FAST_FORWARD FOR +select 'ALTER TABLE [' + @schemaName + '].[' +@tableName + '] DROP CONSTRAINT [' + so.name + ']' + from sysobjects so + inner join sys.sysconstraints sc on so.id = sc.constid + left join sys.key_constraints kc on kc.object_id = so.id + left join sys.syscolumns scol on sc.colid = scol.colid and scol.id = so.parent_obj + left join sys.indexes i on i.index_id = kc.unique_index_id and i.object_id = object_id( '[' + @schemaName + '].[' +@tableName + ']' ) + left join sys.index_columns ic on ic.index_id = i.index_id and ic.object_id = object_id( '[' + @schemaName + '].[' +@tableName + ']' ) + left join sys.columns icol on icol.column_id = ic.column_id and icol.object_id = object_id( '[' + @schemaName + '].[' +@tableName + ']' ) +where + ((@includeCheck = 1 and so.xtype = 'C') + or + (@includeFK = 1 and so.xtype = 'F') + or + (@includePK = 1 and so.xtype = 'PK') + or + (@includeUnique = 1 and so.xtype = 'UQ') + or + (@includeDefault = 1 and so.xtype = 'D')) + and (so.status & 64) = 0 + and parent_obj = object_id( '[' + @schemaName + '].[' +@tableName + ']' ) + and (scol.name = @columnName or icol.name = @columnName) + +open crsCursor; + +DECLARE @SQL NVARCHAR(MAX) + +FETCH NEXT FROM crsCursor into @sql +WHILE (@@FETCH_STATUS = 0) + BEGIN + + exec(@sql) + + FETCH NEXT FROM crsCursor into @sql + END +close crsCursor; +DEALLOCATE crsCursor; +GO + + +--------------------------------------------- + +-- dbo.procSysDropColumnDefault +CREATE proc [dbo].[procSysDropColumnDefault] + @schemaName sysname, + @tableName sysname, + @columnName sysname +as + + +exec dbo.procSysDropColumnConstraints @schemaName,@tableName,@columnName,0,0,0,0,1; +GO + + +--------------------------------------------- + +-- dbo.procSysDropForeignKeyConstraint +CREATE PROC dbo.procSysDropForeignKeyConstraint + @SchemaName NVARCHAR(10), + @TableName NVARCHAR(100), + @ColumnName NVARCHAR(256) +AS +BEGIN + DECLARE @command NVARCHAR(MAX) + select @Command = 'ALTER TABLE ' + @SchemaName + '.[' + @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 t.schema_id = schema_id(@SchemaName) + and c.name = @ColumnName; + EXEC sp_executesql @command +END +GO + + +--------------------------------------------- + +-- dbo.procSysDropIndex +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2021-12-16 KF JAZZ-31105 Created +** 2 2022-01-20 HV JAZZ-32256 Add possibility to drop index for views +*************************************************************/ +CREATE PROCEDURE dbo.procSysDropIndex (@schema sysname, @table sysname, @indexName sysname, @isView bit = 0) +AS + +DECLARE @indexExists bit + +IF @isView = 0 + BEGIN + SET @indexExists = + CASE WHEN EXISTS + (select 1 from sys.indexes i + inner join sys.tables t on t.object_id = i.object_id + inner join sys.schemas s on s.schema_id = t.schema_id + where s.name = @schema and t.name = @table and i.name = @indexName) + THEN 1 ELSE 0 + END + END +ELSE -- @isView = 1 + BEGIN + SET @indexExists = + CASE WHEN EXISTS + (select 1 from sys.indexes i + inner join sys.views t on t.object_id = i.object_id + inner join sys.schemas s on s.schema_id = t.schema_id + where s.name = @schema and t.name = @table and i.name = @indexName) + THEN 1 ELSE 0 + END + END + +IF (@indexExists = 1) + BEGIN + declare @sql nvarchar(max); + set @sql = N'DROP INDEX ['+@indexName+'] ON ['+@schema+'].['+@table+']' + + exec sp_executesql @sql + END +GO + + +--------------------------------------------- + +-- dbo.procSysDropPrimaryKeyConstraint +CREATE PROC dbo.procSysDropPrimaryKeyConstraint + @SchemaName NVARCHAR(10), + @TableName NVARCHAR(100) +AS +BEGIN + DECLARE @PKName NVARCHAR(MAX) + SELECT @PKName = k.name + FROM sys.key_constraints k + INNER JOIN sys.tables t ON k.parent_object_id = t.object_id + INNER JOIN sys.schemas s ON t.schema_id = s.schema_id + WHERE k.type = 'PK' AND t.name = @TableName and s.name = @SchemaName + + DECLARE @dropsql NVARCHAR(MAX) = 'ALTER TABLE ' + @SchemaName + '.' + @TableName + ' DROP CONSTRAINT ' + @PKName + EXEC sp_executesql @dropsql +END +GO + + +--------------------------------------------- + +-- dbo.procSysDropProc +CREATE PROCEDURE [dbo].[procSysDropProc]( + @schema SYSNAME, + @proc SYSNAME +) +AS + BEGIN + + DECLARE @tableexpression SYSNAME; + SET @tableexpression = dbo.GetSQLTableExpression(@schema, @proc); + DECLARE @sql VARCHAR(MAX); + SET @sql = 'DROP PROCEDURE ' + @tableexpression; + + -- NOW DROP THE VIEW --------------------------------------------------------------------- + IF EXISTS(SELECT * FROM sys.procedures WHERE name = @proc AND schema_name(schema_id) = @schema) + EXEC (@sql); + + END +GO + + +--------------------------------------------- + +-- dbo.procSysDropTable +CREATE procedure [dbo].[procSysDropTable] ( + @schema sysname, + @table sysname +) +AS +BEGIN + +declare @tableexpression sysname; +set @tableexpression = dbo.GetSQLTableExpression(@schema, @table); + +-- DROP CONSTRAINTS,TRIGGERS +exec procSysDropAllColumnConstraints @schema, @table +exec procSysDropTriggers @schema, @table; + +-- NOW DROP THE TABLE --------------------------------------------------------------------- +declare @sql varchar(max); +set @sql = ' + +IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[' + @schema + '].[' + @table + ']'') AND type in (N''U'')) + DROP TABLE ' + @tableexpression + '; +'; + +exec (@sql); + +END +GO + + +--------------------------------------------- + +-- dbo.procSysDropTempTable +CREATE PROCEDURE [dbo].[procSysDropTempTable] ( + @tempTable SYSNAME +) +AS + BEGIN + -- NOW DROP THE TEMP TABLE --------------------------------------------------------------------- + DECLARE @sql VARCHAR(MAX); + SET @sql = ' + IF OBJECT_ID(''tempdb..' + @tempTable + ''') IS NOT NULL + DROP TABLE ' + @tempTable + '; + '; + + EXEC (@sql); + END +GO + + +--------------------------------------------- + +-- dbo.procSysDropTrigger +CREATE procedure [dbo].[procSysDropTrigger] ( + @schema sysname, + @trigger sysname +) +AS +BEGIN + +declare @triggerexpression sysname; +set @triggerexpression = dbo.GetSQLTableExpression(@schema, @trigger); + +-- NOW DROP THE TABLE --------------------------------------------------------------------- +declare @sql varchar(max); +set @sql = ' + +if (OBJECT_ID(''[' + @schema + '].[' + @trigger + ']'', ''TRIGGER'') is not null) + DROP TRIGGER ' + @triggerexpression + '; +'; + +print @sql; +exec (@sql); + +END +GO + + +--------------------------------------------- + +-- dbo.procSysDropTriggers +CREATE procedure [dbo].[procSysDropTriggers] ( + @schema sysname, + @object sysname, + @IncludeAfter bit = 1, + @IncludeInsteadOf bit = 1 +) +AS +BEGIN + +declare @tableexpression sysname; +set @tableexpression = dbo.GetSQLTableExpression(@schema, @object); + + +declare tCursor CURSOR FAST_FORWARD FOR + select Name from sys.triggers T where T.parent_id = OBJECT_ID(@tableexpression) + and + ((@IncludeAfter=1 and T.is_instead_of_trigger = 0) OR (@IncludeInsteadOf=1 and T.is_instead_of_trigger=1)); + + +open tCursor; + +DECLARE @trigger nvarchar(128); + +FETCH NEXT FROM tCursor into @trigger +WHILE (@@FETCH_STATUS = 0) + BEGIN + declare @sql varchar(max); + set @sql = 'DROP TRIGGER [' + @schema + '].[' + @trigger + ']'; + exec (@sql); + FETCH NEXT FROM tCursor into @trigger + END +close tCursor; +DEALLOCATE tCursor; + + +END +GO + + +--------------------------------------------- + +-- dbo.procSysDropView +CREATE procedure [dbo].[procSysDropView] ( + @schema sysname, + @view sysname +) +AS +BEGIN + +declare @tableexpression sysname; +set @tableexpression = dbo.GetSQLTableExpression(@schema, @view); + +-- DROP TRIGGERS +exec procSysDropTriggers @schema, @view; + +-- NOW DROP THE VIEW --------------------------------------------------------------------- +declare @sql varchar(max); +set @sql = ' + +IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''[' + @schema + '].[' + @view + ']'') AND type in (N''V'')) + DROP VIEW ' + @tableexpression + '; +'; + +exec (@sql); + +END +GO + + +--------------------------------------------- + +-- dbo.procSysGetUniqueObjectName +create procedure procSysGetUniqueObjectName ( + @schema sysname, + @desiredName sysname +) +AS +BEGIN + declare @testname sysname; + declare @index int; + + set @testname = @desiredName; + set @index = 0; + + if ( 0 = (select COUNT(O.object_id) from sys.objects O inner join sys.schemas S on S.schema_id = O.schema_id where S.name = @schema and O.name = @desiredName)) + BEGIN + select @desiredName + return; + END + + WHILE (1=1) + BEGIN + set @testname = @desiredName + '_' + CAST(@index as nvarchar(max)); + + if ( 0 = (select COUNT(O.object_id) from sys.objects O inner join sys.schemas S on S.schema_id = O.schema_id where S.name = @schema and O.name = @testname)) + BEGIN + select @testname + return; + END + set @index = @index + 1; + END +END +GO + + +--------------------------------------------- + +-- dbo.procSysGetUniqueObjectNameForCopy +CREATE procedure [dbo].[procSysGetUniqueObjectNameForCopy] ( + @schema sysname, + @desiredName sysname +) +AS +BEGIN + declare @testname sysname; + declare @index int; + + set @testname = @desiredName; + set @index = 0; + + if ( 0 = (select COUNT(O.object_id) from sys.objects O inner join sys.schemas S on S.schema_id = O.schema_id where S.name = @schema and O.name = @desiredName)) + BEGIN + select @desiredName + return; + END + + WHILE (1=1) + BEGIN + set @testname = @desiredName + ' - Copy' + ISNULL( + (case when @index = 0 then null else ' (' + CAST(@index as nvarchar(max)) + ')' end), + ''); + + if ( 0 = (select COUNT(O.object_id) from sys.objects O inner join sys.schemas S on S.schema_id = O.schema_id where S.name = @schema and O.name = @testname)) + BEGIN + select @testname + return; + END + set @index = @index + 1; + END +END +GO + + +--------------------------------------------- + +-- dbo.procSysRefreshView +CREATE procedure [dbo].[procSysRefreshView] ( + @viewName nvarchar(256) +) +AS +BEGIN + + -- NOW REFRESH THE VIEW --------------------------------------------------------------------- + declare @sql varchar(max); + set @sql = ' + + IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N''' + @viewName + ''') AND type in (N''V'')) + EXEC sp_refreshview ''' + @viewName + '''; + '; + + EXEC (@sql); + +END +GO + + +--------------------------------------------- + +-- dbo.procSysRethrowError +-- Create the stored procedure to generate an error using +-- RAISERROR. The original error information is used to +-- construct the msg_str for RAISERROR. +CREATE PROCEDURE procSysRethrowError AS + -- Return if there is no error information to retrieve. + IF ERROR_NUMBER() IS NULL + RETURN; + + DECLARE + @ErrorMessage NVARCHAR(4000), + @ErrorNumber INT, + @ErrorSeverity INT, + @ErrorState INT, + @ErrorLine INT, + @ErrorProcedure NVARCHAR(200); + + -- Assign variables to error-handling functions that + -- capture information for RAISERROR. + SELECT + @ErrorNumber = ERROR_NUMBER(), + @ErrorSeverity = ERROR_SEVERITY(), + @ErrorState = ERROR_STATE(), + @ErrorLine = ERROR_LINE(), + @ErrorProcedure = ISNULL(ERROR_PROCEDURE(), '-'); + + -- Build the message string that will contain original + -- error information. + SELECT @ErrorMessage = + N'Error %d, Level %d, State %d, Procedure %s, Line %d, ' + + 'Message: '+ ERROR_MESSAGE(); + + -- Raise an error: msg_str parameter of RAISERROR will contain + -- the original error information. + RAISERROR + ( + @ErrorMessage, + @ErrorSeverity, + 1, + @ErrorNumber, -- parameter: original error number. + @ErrorSeverity, -- parameter: original error severity. + @ErrorState, -- parameter: original error state. + @ErrorProcedure, -- parameter: original error procedure name. + @ErrorLine -- parameter: original error line number. + ); +GO + + +--------------------------------------------- + +-- dbo.procSysSetColumnIdentity +CREATE proc [dbo].[procSysSetColumnIdentity] ( + @schema varchar(max), + @table varchar(max), + @column varchar(max), + @isDebug bit = 0) +as + + + +-- Helper Variables +declare @tempTable varchar(max) +declare @columnType varchar(max) +declare @source varchar(max) + +-- SQL +declare @backupSQL varchar(max) +declare @dropConstraintsSQL varchar(max) +declare @fixTableSQL varchar(max) +declare @reloadValuesSQL varchar(max) +declare @addConstraintsSQL varchar(max) + +set @tempTable = '#zzTemp' + @table + 'Fix' +set @source = '[' + @schema + '].[' + @table + ']' + + + +-- Validate Input +if ((select object_id from sys.tables t inner join sys.schemas s on s.schema_id = t.schema_id where s.name like @schema and t.name like @table) is null) begin + print 'Unable to find table: ' + @source + '.' + return +end + +if ((select c.object_id from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name like @schema and t.name like @table and c.name like @column) is null) begin + print 'Unable to find column: [' + @column + '] in table: ' + @source + '.' + return +end + +select @columnType = ty.name from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id inner join sys.types ty on ty.system_type_id = c.system_type_id where s.name like @schema and t.name + + + like @table and c.name like @column; +if (@columnType is null or @columnType not in ('tinyint', 'smallint', 'int', 'bigint')) begin + print 'Invalid column type: ''' + @columnType + '''. Expecting an integer.' + return +end + + + +declare @columns as varchar(max) +set @columns = '' +select @columns = @columns + ',[' + c.name + ']' +from sys.columns c +inner join sys.tables t on t.object_id = c.object_id +inner join sys.schemas s on s.schema_id = t.schema_id +inner join sys.types ct on ct.system_type_id = c.system_type_id and ct.user_type_id = c.user_type_id +where s.name = @schema and t.name = @table and ct.name not in ('timestamp') +if (LEN(@columns) > 0) set @columns = SUBSTRING(@columns, 2, len(@columns) - 1) + +-- Save the values SQL +set @backupSQL = ' +select ' + @columns + ' into ' + @tempTable + ' from ' + @source + '; +' + +-- Reload Values SQL +set @reloadValuesSQL = ' +set identity_insert ' + @source + ' ON; +truncate table ' + @source + '; +insert into ' + @source + '(' + @columns + ') select ' + @columns + ' from ' + @tempTable + '; +set identity_insert ' + @source + ' OFF; +drop table ' + @tempTable + '; +' + + +-- Fix Table +set @fixTableSQL = ' +alter table ' + @source + ' drop column [' + @column + ']; +alter table ' + @source + ' add [' + @column + '] ' + @columnType + ' not null identity(1,1); +' + +-- Constraints +declare @defvalueName varchar(max) +declare @defvalue varchar(max) + +select @defvalueName = d.name, @defvalue = d.definition +from sys.default_constraints d + +inner join sys.tables t on t.object_id = d.parent_object_id +inner join sys.schemas s on t.schema_id = t.schema_id +inner join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id + +where s.name like @schema and t.name like @table and c.name like @column + +if (@defvalue is not null and @defvalueName is not null) begin + set @dropConstraintsSQL = ' +alter table ' + @source + ' drop constraint ' + @defvalueName + ';' + -- Default cannot be re-added because it will be an identity +end + +set @dropConstraintsSQL = ISNULL(@dropConstraintsSQL, '') +set @addConstraintsSQL = ISNULL(@addConstraintsSQL, '') + + +declare @fkName varchar(max) +declare @deleteAction varchar(max) +declare @updateAction varchar(max) +declare @pSchema varchar(max) +declare @pTable varchar(max) +declare @pColumn varchar(max) + +declare @pSource varchar(max) + +declare fkCursor CURSOR LOCAL FAST_FORWARD FOR + select + fk.name, fk.delete_referential_action_desc, fk.update_referential_action_desc, psch.name as parent_schema, ptbl.name as parent_table, pcol.name as parent_table_column + from sys.foreign_keys fk + + inner join sys.foreign_key_columns fkc on fkc.constraint_object_id = fk.object_id + + inner join sys.tables fktbl on fktbl.object_id = fk.referenced_object_id + inner join sys.schemas fksch on fksch.schema_id = fktbl.schema_id + inner join sys.columns fkcol on fkcol.object_id = fktbl.object_id and fkcol.column_id = fkc.referenced_column_id + + inner join sys.tables ptbl on ptbl.object_id = fk.parent_object_id + inner join sys.schemas psch on psch.schema_id = ptbl.schema_id + inner join sys.columns pcol on pcol.object_id = fk.parent_object_id and pcol.column_id = fkc.parent_column_id + + where fksch.name like @schema and fktbl.name like @table and fkcol.name like @column + +open fkCursor; +fetch next from fkCursor into @fkName, @deleteAction, @updateAction, @pSchema, @pTable, @pColumn + +while (@@FETCH_STATUS <> -1) begin + + set @pSource = '[' + @pSchema + '].[' + @pTable + ']' + set @updateAction = REPLACE(@updateAction, '_', ' ') + set @deleteAction = REPLACE(@deleteAction, '_', ' ') + + set @dropConstraintsSQL = @dropConstraintsSQL + ' +alter table ' + @pSource + ' drop constraint ' + @fkName + ';' + set @addConstraintsSQL = @addConstraintsSQL + ' +alter table ' + @pSource + ' add constraint ' + @fkName + ' foreign key ([' + @pColumn + ']) + references ' + @source + '([' + @column + ']) + on update ' + @updateAction + ' + on delete ' + @deleteAction + '; +' + + fetch next from fkCursor into @fkName, @deleteAction, @updateAction, @pSchema, @pTable, @pColumn +end + +close fkCursor +deallocate fkCursor + + + + + + +declare @pkname varchar(max) +declare @pkcolumns varchar(max) + +select @pkname = c.CONSTRAINT_NAME +from INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc +inner join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE c on c.CONSTRAINT_NAME = tc.CONSTRAINT_NAME +where tc.TABLE_SCHEMA like @schema and tc.TABLE_NAME like @table and tc.CONSTRAINT_TYPE = 'PRIMARY KEY' + +if (@pkname is not null) begin + set @pkcolumns = '' + select @pkcolumns = @pkcolumns + ', [' + c.COLUMN_NAME + ']' from INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc + inner join INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE c on c.CONSTRAINT_NAME = tc.CONSTRAINT_NAME + where tc.TABLE_SCHEMA like @schema and tc.TABLE_NAME like @table and tc.CONSTRAINT_TYPE = 'PRIMARY KEY' + if (len(@pkcolumns) > 0) set @pkcolumns = SUBSTRING(@pkcolumns, 3, len(@pkcolumns) - 2) + + set @dropConstraintsSQL = @dropConstraintsSQL + ' +alter table ' + @source + ' drop constraint ' + @pkname + ';' + set @addConstraintsSQL = ' +alter table ' + @source + ' add constraint ' + @pkname + ' primary key (' + @pkcolumns + ');' + @addConstraintsSQL + +end + + + + +--- Print/Exec +if (@isDebug = 1) begin + + print 'begin transaction;' + print 'begin try +-- Backing up values: ' + @backupSQL + print ' +-- Dropping Constraints: ' + @dropConstraintsSQL + print ' +-- Fixing Table: ' + @fixTableSQL + print ' +-- Reloading values: ' + @reloadValuesSQL + print ' +-- Re-Adding Constraints: ' + @addConstraintsSQL + print ' +end try +begin catch + print cast(ERROR_NUMBER() as varchar(max)) + '' : '' + ERROR_MESSAGE() + if @@TRANCOUNT > 0 + rollback transaction; +end catch; +if @@TRANCOUNT > 0 + commit transaction;' +end +else begin + begin transaction; + begin try + exec (@backupSQL + @dropConstraintsSQL + @fixTableSQL + @reloadValuesSQL + @addConstraintsSQL) + end try + begin catch + print cast(ERROR_NUMBER() as varchar(max)) + ' : ' + ERROR_MESSAGE() + if @@TRANCOUNT > 0 + rollback transaction; + end catch; + if @@TRANCOUNT > 0 + commit transaction; +end +GO + + +--------------------------------------------- + +-- dbo.procSysUpdateColumnType +CREATE proc [dbo].[procSysUpdateColumnType] + @schema sysname, + @table sysname, + @column sysname, + @newtype varchar(100), + @meta varchar(100) = 'NOT NULL DEFAULT (0)' +as + + +begin try + exec (' + alter table ' + @schema + '.' + @table + ' add ' + @column + '__New ' + @newtype + ' ' + @meta+ ' + exec (''update ' + @schema + '.' + @table + ' set ' + @column + '__New = ' + @column + ''') + exec procSysDropColumnAndDefault ''' + @schema + ''', ''' + @table + ''', ''' + @column + ''' + exec sp_rename ''' + @schema + '.' + @table + '.' + @column + '__New'', ''' + @column + ''', ''COLUMN''; + ') +end try +begin catch + print 'Column type change failed.' + exec [dbo].[procSysRethrowError] +end catch +GO + + +--------------------------------------------- + +-- dbo.procTEEvictModelCache +CREATE PROCEDURE [dbo].[procTEEvictModelCache] +( + @PlanWhereClause nvarchar(max), + @IsDebugOnly bit = 0 +) +AS + DECLARE @json NVARCHAR(max) + + if (exists(select 1 from fw.systemsetting where name = 'Use TaskEngine' and value = '1')) begin + set @json = '{' + + '"PlanWhereClause":"' + replace(@PlanWhereClause, '''', '''''') + '"' + + '}'; + end else begin + set @json = '{' + + '"PlanWhereClause":"' + @PlanWhereClause + '"' + + '}'; + end + + if (@IsDebugOnly = 0) begin + DECLARE @statusCode INT; + EXEC dbo.procCreateTask + @taskTypeName = 'Strata.CS.Jazz.Biz.ModelEngine.Tasks.EvictModelCacheTask, Strata.CS.Jazz.Biz', + @contextXML = @json, + @taskSource = 'procTEEvictModelCache', + @statusCode = @statusCode OUTPUT; + + IF @statusCode < 200 OR @statusCode > 299 + BEGIN + RAISERROR('Failed to insert to Hangfire',16,1); + END; + end else begin + print 'DECLARE @statusCode INT; + EXEC dbo.procCreateTask + @taskTypeName = ''Strata.CS.Jazz.Biz.ModelEngine.Tasks.EvictModelCacheTask, Strata.CS.Jazz.Biz'', + @contextXML = ''' + @json + ''', + @taskSource = ''procTEEvictModelCache'', + @statusCode = @statusCode OUTPUT;' + end +GO + + +--------------------------------------------- + +-- dbo.procTEGetLinkedServerFullName +CREATE PROCEDURE dbo.procTEGetLinkedServerFullName( + @ReturnVal nvarchar(256) OUTPUT +) +AS +BEGIN + + declare @SMC_SERVER nvarchar(128); + declare @SMC_DB nvarchar(128); + declare @TE_GUID nvarchar(36); + + select @SMC_SERVER = Setting from DBSetting where Name = 'SMC_PRIMARY_SERVER' + select @SMC_DB = setting from DBSetting where Name = 'SMC_PRIMARY_DATABASE' + select @TE_GUID = setting from DBSetting where Name = 'TASKENGINE_CONNECTIONKEY' + DECLARE @TE_FULLNAME nvarchar(256); + + declare @sql nvarchar(max); + set @sql = ' + select + @TE_FULLNAMEOUT = LinkedServerFullName + from [' + @SMC_SERVER + '].[' + @SMC_DB + '].[dbo].[viewDatabaseInfo] + where DatabaseGUID = ''' + @TE_GUID + ''' + ' + + EXECUTE sp_executesql + @sql, + N'@TE_FULLNAMEOUT nvarchar(256) OUTPUT', + @TE_FULLNAMEOUT=@TE_FULLNAME OUTPUT; + + SELECT @ReturnVal = @TE_FULLNAME; +END +GO + + +--------------------------------------------- + +-- dbo.procTEPartialModelRefresh +CREATE PROCEDURE [dbo].[procTEPartialModelRefresh] +( + @compositeGUID uniqueidentifier, + @ModelGUIDList nvarchar(max), + @IsDebugOnly bit = 0 +) +AS +begin + if (@IsDebugOnly = 1) begin + print 'EXEC dbo.procCreateTask + @taskTypeName = ''Strata.CS.Jazz.Biz.ModelEngine.Tasks.RefreshModelTask, Strata.CS.Jazz.Biz'', + @contextXML = '''', + @taskSource = ''procTEPartialModelRefresh'';' + return + end + + --add to refresh queue, converting any requests that were already in queue into full refreshes + update q set q.CompositeGUID = dbo.ZeroGUID() from [dbo].[MEModelRefreshQueue] q inner join [dbo].[XPlan] P (readuncommitted) on P.PlanGUID = q.ModelGUID where P.PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(@ModelGUIDList, ',')) and q.CompositeGUID != dbo.ZeroGUID() and q.CompositeGUID != @compositeGUID; + insert into [dbo].[MEModelRefreshQueue] (ModelGUID, Source, CompositeGUID) + select + P.PlanGUID, + 'procTEPartialModelRefresh', + case when mt.IsMemoryCachable = 1 + then @compositeGUID + else dbo.ZeroGUID() + end + from [dbo].[XPlan] P (readuncommitted) + inner join [dbo].[EMFModelTemplate] mt on mt.ModelTemplateGUID = P.ModelTemplateGUID + where 1=1 + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45' --filter GM Blank template + and P.PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(@ModelGUIDList, ',')) + and not exists(select 1 from [dbo].[MEModelRefreshQueue] ex where ex.ModelGUID = P.PlanGUID); + + --invalidate cache for requests that turned into full refreshes + exec procInvalidateModelWorkbookCacheByWhereClause 'PlanGUID in(select ModelGUID from dbo.MEModelRefreshQueue where CompositeGUID = dbo.ZeroGUID())', 0, 'procTEPartialModelRefresh' + + --create task + DECLARE @statusCode INT; + EXEC dbo.procCreateTask + @taskTypeName = 'Strata.CS.Jazz.Biz.ModelEngine.Tasks.RefreshModelTask, Strata.CS.Jazz.Biz', + @contextXML = '', + @taskSource = 'procTEPartialModelRefresh', + @statusCode = @statusCode OUTPUT; + + IF @statusCode < 200 OR @statusCode > 299 + BEGIN + RAISERROR('Failed to insert to Hangfire',16,1); + END; +end +GO + + +--------------------------------------------- + +-- dbo.procTERefreshFillins +CREATE PROCEDURE [dbo].[procTERefreshFillins] +( + @planTypeGUID uniqueidentifier, + @modelTemplateGUID uniqueidentifier, + @placeholderSectionGUIDList nvarchar(max), + @IsDebugOnly bit = 0 +) +AS + if (@IsDebugOnly = 1) begin + print 'EXEC dbo.procCreateTask + @taskTypeName = ''Strata.CS.Jazz.Biz.ModelEngine.Fillins20.FillinRefreshTask, Strata.CS.Jazz.Biz'', + @contextXML = '''', + @taskSource = ''procTERefreshFillins'';' + return + end + + --insert refresh requests + if(@placeholderSectionGUIDList <> '') + begin + INSERT INTO [dbo].[FillinRefreshRequest] ([PlanTypeGUID], [ModelTemplateGUID], [PlaceHolderSectionGUID]) + SELECT @planTypeGUID, @modelTemplateGUID, guid FROM CSVGuidsToTable(@placeholderSectionGUIDList) + end + else + begin + if(@modelTemplateGUID <> '00000000-0000-0000-0000-000000000000') + begin + INSERT INTO [dbo].[FillinRefreshRequest] ([ModelTemplateGUID]) VALUES (@modelTemplateGUID) + end + else + begin + INSERT INTO [dbo].[FillinRefreshRequest] ([PlanTypeGUID]) VALUES (@planTypeGUID) + end + end + + --create task + DECLARE @statusCode INT; + EXEC dbo.procCreateTask + @taskTypeName = 'Strata.CS.Jazz.Biz.ModelEngine.Fillins20.FillinRefreshTask, Strata.CS.Jazz.Biz', + @contextXML = '', + @taskSource = 'procTERefreshFillins', + @statusCode = @statusCode OUTPUT; + + IF @statusCode < 200 OR @statusCode > 299 + BEGIN + RAISERROR('Failed to insert to Hangfire',16,1); + END; +GO + + +--------------------------------------------- + +-- dbo.procTERefreshFillinsByPlan +CREATE PROCEDURE [dbo].[procTERefreshFillinsByPlan] +( + @planGUIDList nvarchar(max), + @placeholderSectionGUIDList nvarchar(max), + @IsDebugOnly bit = 0 +) +AS + if (@IsDebugOnly = 1) begin + print 'EXEC dbo.procCreateTask + @taskTypeName = ''Strata.CS.Jazz.Biz.ModelEngine.Fillins20.FillinRefreshTask, Strata.CS.Jazz.Biz'', + @contextXML = '''', + @taskSource = ''procTERefreshFillinsByPlan'';' + return + end + + --insert refresh requests + if(@placeholderSectionGUIDList = '') + begin + INSERT INTO [dbo].[FillinRefreshRequest] ([PlanGUID]) + SELECT guid FROM CSVGuidsToTable(@planGUIDList) + end + else + begin + INSERT INTO [dbo].[FillinRefreshRequest] ([PlaceHolderSectionGUID], [PlanGUID]) + SELECT phs.guid, p.guid FROM CSVGuidsToTable(@planGUIDList) p cross apply CSVGuidsToTable(@placeholderSectionGUIDList) phs + end + + --create task + DECLARE @statusCode INT; + EXEC dbo.procCreateTask + @taskTypeName = 'Strata.CS.Jazz.Biz.ModelEngine.Fillins20.FillinRefreshTask, Strata.CS.Jazz.Biz', + @contextXML = '', + @taskSource = 'procTERefreshFillins', + @statusCode = @statusCode OUTPUT; + + IF @statusCode < 200 OR @statusCode > 299 + BEGIN + RAISERROR('Failed to insert to Hangfire',16,1); + END; +GO + + +--------------------------------------------- + +-- dbo.procTERefreshModel +CREATE PROCEDURE [dbo].[procTERefreshModel] +( + @ModelGUID uniqueidentifier, + @IsIgnoreLock bit = 0, --obsolete + @UseDependencies bit = 0, --obsolete + @IsDebugOnly bit = 0 +) +AS +begin + if (@IsDebugOnly = 1) begin + print 'EXEC dbo.procCreateTask + @taskTypeName = ''Strata.CS.Jazz.Biz.ModelEngine.Tasks.RefreshModelTask, Strata.CS.Jazz.Biz'', + @contextXML = '''', + @taskSource = ''procTERefreshModel'';' + return + end + + --add to refresh queue + insert into [dbo].[MEModelRefreshQueue] (ModelGUID, Source) + select + P.PlanGUID, + 'procTERefreshModel' + from [dbo].[XPlan] P (readuncommitted) + where 1=1 + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45' --filter GM Blank template + and P.PlanGUID = @ModelGUID + and not exists(select 1 from [dbo].[MEModelRefreshQueue] ex where ex.ModelGUID = P.PlanGUID) + + --invalidate cache + exec procInvalidateModelWorkbookCache @ModelGUID, 0, 0, 'procTERefreshModel' + + --create task + DECLARE @statusCode INT; + EXEC dbo.procCreateTask + @taskTypeName = 'Strata.CS.Jazz.Biz.ModelEngine.Tasks.RefreshModelTask, Strata.CS.Jazz.Biz', + @contextXML = '', + @taskSource = 'procTERefreshModel', + @statusCode = @statusCode OUTPUT; + + IF @statusCode < 200 OR @statusCode > 299 + BEGIN + RAISERROR('Failed to insert to Hangfire',16,1); + END; +end +GO + + +--------------------------------------------- + +-- dbo.procTERefreshModelList +CREATE PROCEDURE [dbo].[procTERefreshModelList] +( + @ModelGUIDList nvarchar(max), + @IsDebugOnly bit = 0 +) +AS +begin + if (@IsDebugOnly = 1) begin + print 'EXEC dbo.procCreateTask + @taskTypeName = ''Strata.CS.Jazz.Biz.ModelEngine.Tasks.RefreshModelTask, Strata.CS.Jazz.Biz'', + @contextXML = '''', + @taskSource = ''procTERefreshModelList'';' + return + end + + --add to refresh queue + insert into [dbo].[MEModelRefreshQueue] (ModelGUID, Source) + select + P.PlanGUID, + 'procTERefreshModelList' + from [dbo].[XPlan] P (readuncommitted) + where 1=1 + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45' --filter GM Blank template + and P.PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(@ModelGUIDList, ',')) + and not exists(select 1 from [dbo].[MEModelRefreshQueue] ex where ex.ModelGUID = P.PlanGUID) + + --invalidate cache + declare @invalidateWhere nvarchar(max) + set @invalidateWhere = 'PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(''' + @ModelGUIDList + ''', '',''))' + exec procInvalidateModelWorkbookCacheByWhereClause @invalidateWhere, 0, 'procTERefreshModelList' + + --create task + DECLARE @statusCode INT; + EXEC dbo.procCreateTask + @taskTypeName = 'Strata.CS.Jazz.Biz.ModelEngine.Tasks.RefreshModelTask, Strata.CS.Jazz.Biz', + @contextXML = '', + @taskSource = 'procTERefreshModelList', + @statusCode = @statusCode OUTPUT; + + IF @statusCode < 200 OR @statusCode > 299 + BEGIN + RAISERROR('Failed to insert to Hangfire',16,1); + END; +end +GO + + +--------------------------------------------- + +-- dbo.procTERefreshModelTemplate +CREATE PROCEDURE [dbo].[procTERefreshModelTemplate] +( + @ModelTemplateGUID uniqueidentifier, + @IsIgnoreLock bit = 0, --obsolete + @IsDebugOnly bit = 0 +) +AS +begin + if (@ModelTemplateGUID = '7F792F1F-F32A-4053-9907-534A2D736D45') return --filter GM Blank template + + if (@IsDebugOnly = 1) begin + print 'EXEC dbo.procCreateTask + @taskTypeName = ''Strata.CS.Jazz.Biz.ModelEngine.Tasks.RefreshModelTask, Strata.CS.Jazz.Biz'', + @contextXML = '''', + @taskSource = ''procTERefreshModelTemplate'';' + return + end + + --add to refresh queue + insert into [dbo].[MEModelRefreshQueue] (ModelGUID, Source) + select P.PlanGUID, 'procTERefreshModelTemplate' + from [dbo].[XPlan] P (readuncommitted) + where 1=1 + and P.ModelTemplateGUID = @ModelTemplateGUID + and not exists(select 1 from [dbo].[MEModelRefreshQueue] ex where ex.ModelGUID = P.PlanGUID) + + --invalidate cache + exec procInvalidateModelWorkbookCache @ModelTemplateGUID, 1, 0, 'procTERefreshModelTemplate' + + --create task + DECLARE @statusCode INT; + EXEC dbo.procCreateTask + @taskTypeName = 'Strata.CS.Jazz.Biz.ModelEngine.Tasks.RefreshModelTask, Strata.CS.Jazz.Biz', + @contextXML = '', + @taskSource = 'procTERefreshModelTemplate', + @statusCode = @statusCode OUTPUT; + + IF @statusCode < 200 OR @statusCode > 299 + BEGIN + RAISERROR('Failed to insert to Hangfire',16,1); + END; +end +GO + + +--------------------------------------------- + +-- dbo.procTableReseedIdentity +CREATE PROCEDURE dbo.procTableReseedIdentity +@schemaName VARCHAR(100), +@tableName VARCHAR(100), +@seedValue INT = null AS + +BEGIN + + DECLARE @tableNameWithSchema VARCHAR(200) + SET @tableNameWithSchema = @schemaName + '.' + @tableName + + IF OBJECTPROPERTY(OBJECT_ID(@tableNameWithSchema), 'TableHasIdentity') = 1 + BEGIN + SELECT @seedValue = ISNULL(@seedValue,IDENT_SEED(@tableNameWithSchema)) + + DBCC CHECKIDENT(@tableNameWithSchema,'RESEED', @seedValue) + END + +END +GO + + +--------------------------------------------- + +-- dbo.procTruncateTemplateMappingbyFramework +CREATE PROC [dbo].[procTruncateTemplateMappingbyFramework] + @FrameworkID Int +as + +DECLARE @SCHEMA nvarchar(256) +DECLARE @FactTableName nvarchar(256) +DECLARE @SQL nvarchar(1024) +DECLARE @SQL2 nvarchar(1024) +DECLARE @FrameworkSchemaName nvarchar(100) = (Select FrameworkSchemaName from [fw].[DimFramework] WHERE FrameworkID=@FrameworkID) +DECLARE @ClientSchemaName nvarchar(100) = (Select ClientSchemaName from [fw].[DimFramework]WHERE FrameworkID=@FrameworkID) +Declare @TemplateGUIDs nvarchar(max) + + +DECLARE FactTableCursor CURSOR FOR + + select + t.name + , (select name from sys.schemas where schema_id = t.schema_id) + from sys.tables t + where + 1=1 + and t.schema_id in(select schema_id from sys.schemas where name in(@FrameworkSchemaName, @ClientSchemaName) ) + and t.name like 'fact%' and t.name like '%map' and name not like '%FactWorkingHoursPerMonthMap' + order by t.name + +OPEN FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + set @SQL = 'truncate table ' + @SCHEMA + '.' + @FactTableName + set @SQL2='DBCC CHECKIDENT (''' + + @SCHEMA + '.' + @FactTableName + ''', RESEED, 1)' +-- print @SQL +-- print @SQL2 + EXECUTE sp_executesql @SQL + EXECUTE sp_executesql @SQL2 + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + +select @TemplateGUIDs = dbo.straggr(a.ID, ',', '') from ( + select distinct cast(db.ModelTemplateGUID as nvarchar(36)) as ID from [dbo].[EMFModelTemplateFramework] db where FrameworkID=@FrameworkID + ) a + +exec [dbo].[procRunForManyGUIDs] @sql = 'exec [dbo].[procEMFRemoveTemplateMappings] @modeltemplateguid ={guidq} ,@includeprofiles = 1', @guids = @TemplateGUIDs, @isExecuting = 1 + + + +RETURN +GO + + +--------------------------------------------- + +-- dbo.procUpdateDefaultMemberGuid +--Author: rreimer +--Branch: DSSAdvancedCostingNoKoz +--Forward +create proc procUpdateDefaultMemberGuid +as + set nocount on + + declare @dimGuid nvarchar(36) + declare @tableName nvarchar(max) + declare crsInfo cursor fast_forward for + select + cast(DG.DimensionGUID as nvarchar(36)), + DG.SchemaName + '.' + DG.ObjectName as SQLObjectName + from + [dbo].[ScoreDimension] D + inner join [dbo].[ScoreDimensionGroup] DG on DG.DimensionGroupGUID = D.PrimaryGroupGUID + inner join sys.tables T on T.Name = DG.ObjectName + inner join sys.schemas S on S.Name = DG.SchemaName and T.schema_id = S.schema_id + where + D.DefaultMemberGUID ='00000000-0000-0000-0000-000000000000' + and exists(select 1 from sys.columns C where C.object_id = T.object_id and Name = 'Name') + + open crsInfo + fetch next from crsInfo into @dimGuid,@tableName + declare @sql nvarchar(max) + while(@@FETCH_STATUS = 0) begin + set @sql = ' + update [dbo].[ScoreDimension] set DefaultMemberGUID = + coalesce((select top 1 M.MemberGUID from '+@tableName+' M where M.Name like ''%Not Specified%''), dbo.ZeroGUID()) + where DimensionGUID = ''' + @dimGuid +'''' + exec (@sql) + fetch next from crsInfo into @dimGuid, @tableName + end + close crsInfo + deallocate crsInfo +GO + + +--------------------------------------------- + +-- dbo.procUpdateDefaultMemberGuid2 +CREATE proc [dbo].[procUpdateDefaultMemberGuid2] +@dimGuid nvarchar(36), +@tableName nvarchar(max), +@nameColumn nvarchar(max) +as +declare @sql nvarchar(max) +set @sql = ' + update [dbo].[ScoreDimension] set DefaultMemberGUID = + coalesce((select top 1 M.MemberGUID from '+@tableName+' M where M.'+@nameColumn+' like ''%Not Specified%''), dbo.ZeroGUID()) + where DimensionGUID = ''' + @dimGuid +'''' + exec (@sql) + +RETURN +GO + + +--------------------------------------------- + +-- dbo.procUpdateScheduledTaskIsDisabled +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2019-12-16 KF B-24658 MR | Automatic Reminders +*************************************************************/ +CREATE PROCEDURE [dbo].[procUpdateScheduledTaskIsDisabled] +@ScheduledTaskGUID uniqueidentifier, +@IsDisabled BIT +AS + +UPDATE dbo.TEScheduledTask +SET IsDisabled = @IsDisabled +WHERE ScheduledTaskGUID = @ScheduledTaskGUID +GO + + +--------------------------------------------- + +-- dbo.procUserCheckPasswordHistory +-- ============================================= +-- Author: Eric Kretzer +-- Create date: 04/12/2011 +-- Description: Check to see if a password has been used in the last X iterations +-- ============================================= +CREATE PROCEDURE [dbo].[procUserCheckPasswordHistory] + @USERGUID as uniqueidentifier, + @HASHEDPASSWORD as nvarchar(64), + @ITERATIONS as tinyint +AS +BEGIN + select case when COUNT(*) > 0 then 1 else 0 end as [IsUsedPassword] from passwordhistory where UserGUID = @UserGUID and Iteration <= @Iterations and HashedPassword = @HashedPassword +END +GO + + +--------------------------------------------- + +-- dbo.procUserGroupDelete +CREATE procedure [dbo].[procUserGroupDelete] + @UserGroupGUID uniqueidentifier, + @Name nvarchar(64) = '', + @Type int = 0, + @Description nvarchar(4000) = '', + @Category nvarchar(64) = '', + @LootGUID uniqueidentifier = '00000000-0000-0000-0000-00000000000000', + @UserRoleGUID uniqueidentifier = '00000000-0000-0000-0000-00000000000000' +as + +--Role assignment groups should never be deleted manually +IF (@Type != 1) BEGIN + DELETE FROM UserGroup WHERE UserGroupGUID = @UserGroupGUID +END +GO + + +--------------------------------------------- + +-- dbo.procUserGroupInsert +CREATE procedure [dbo].[procUserGroupInsert] + @UserGroupGUID uniqueidentifier, + @Name nvarchar(64), + @Type int, + @Description nvarchar(4000), + @Category nvarchar(64), + @LootGUID uniqueidentifier, + @UserRoleGUID uniqueidentifier +as + +IF (@Type != 1) BEGIN + INSERT INTO UserGroup (UserGroupGUID, Name, Type, Description, Category) + VALUES (@UserGroupGUID, @Name, @Type, @Description, @Category) +END +GO + + +--------------------------------------------- + +-- dbo.procUserGroupUpdate +CREATE procedure [dbo].[procUserGroupUpdate] + @UserGroupGUID uniqueidentifier, + @Name nvarchar(64), + @Type int, + @Description nvarchar(4000), + @Category nvarchar(64), + @LootGUID uniqueidentifier, + @UserRoleGUID uniqueidentifier +as + +IF (@Type != 1) BEGIN + UPDATE UserGroup SET Name = @Name, Type = @Type, Description = @Description, Category = @Category WHERE UserGroupGUID = @UserGroupGUID +END +GO + + +--------------------------------------------- + +-- dbo.procUserSetPassword +-- ============================================= +-- Author: +-- Create date: +-- Description: +-- ============================================= +CREATE PROCEDURE [dbo].[procUserSetPassword] + @USERGUID as uniqueidentifier, + @HASHEDPASSWORD as nvarchar(64) +AS +BEGIN + UPDATE UserProfile + SET + HASHEDPASSWORD = @HASHEDPASSWORD + WHERE + USERGUID = @USERGUID +END +GO + + +--------------------------------------------- + +-- dbo.procUserSetPasswordAll +create proc dbo.procUserSetPasswordAll + @UnhashedPassword nvarchar(64) +as + set nocount on + + declare @userguid uniqueidentifier + declare crsUsers cursor fast_forward for select UserGUID from [dbo].[UserProfile] + + open crsUsers + fetch next from crsUsers into @userguid + + while (@@fetch_status = 0) begin + update [dbo].[UserProfile] set HashedPassword = dbo.GetHashedPassword(UserGUID, @UnhashedPassword) where UserGUID = @userguid + + fetch next from crsUsers into @userguid + end + + close crsUsers + deallocate crsUsers +GO + + +--------------------------------------------- + +-- dbo.procUserSetPasswordSandbox +CREATE proc dbo.procUserSetPasswordSandbox + @UnhashedPassword nvarchar(64) +as + set nocount on + + declare @userguid uniqueidentifier + declare crsUsers cursor fast_forward for select UserGUID from [dbo].[UserProfile] where UserName like 'sandbox%' or UserName like 'elearning%' + or userguid in (select UserGUID from [dbo].[DemoUser]) order by UserName + open crsUsers + fetch next from crsUsers into @userguid + + while (@@fetch_status = 0) begin + update [dbo].[UserProfile] set HashedPassword = dbo.GetHashedPassword(UserGUID, @UnhashedPassword) where UserGUID = @userguid + + fetch next from crsUsers into @userguid + end + + close crsUsers + deallocate crsUsers +GO + + +--------------------------------------------- + +-- dbo.procUsersEnsureSimpleMode +CREATE procedure [dbo].[procUsersEnsureSimpleMode] +as +begin + insert into UserProfileAppModeAccessLink (UserGUID, AccessLevel) + select + UP.UserGUID, 1 + from + UserProfile UP + where + not exists(select 1 from UserProfileAppModeAccessLink L where UP.UserGUID = L.UserGUID) +end +GO + + +--------------------------------------------- + +-- dbo.procValidateColumnsExists +create proc [dbo].[procValidateColumnsExists] + @schema nvarchar(max), + @object nvarchar(max), + @column nvarchar(max) +as + +if dbo.ColumnExists(@schema, @object, @column) = 0 + print @schema + '.' + @object + '.' + @column + ' is missing.' +GO + + +--------------------------------------------- + +-- dbo.procValidateDimensionProperty +CREATE proc [dbo].[procValidateDimensionProperty] + @DimensionName nvarchar(450), + @PropertyName nvarchar(450), + @MatchDimensionName nvarchar(450), + @MatchDimensionLevel int = -1 +AS + +DECLARE @DimensionGUID uniqueidentifier +DECLARE @PropertyIndex int +DECLARE @TargetDimensionGUID uniqueidentifier + +SET @DimensionGUID = '00000000-0000-0000-0000-000000000000' +SELECT @DimensionGUID = ListGUID FROM SecureList WHERE [Name] = @DimensionName +IF(@DimensionGUID = '00000000-0000-0000-0000-000000000000') BEGIN + PRINT 'Dimension not found.' + RETURN +END + +SET @PropertyIndex = -1 +SELECT @PropertyIndex = PropertyIndex FROM SecureListProperty WHERE ListGUID = @DimensionGUID AND [Name] = @PropertyName +IF(@PropertyIndex = -1) BEGIN + PRINT 'Property not found.' + RETURN +END + +SET @TargetDimensionGUID = '00000000-0000-0000-0000-000000000000' +SELECT @TargetDimensionGUID = ListGUID FROM SecureList WHERE [Name] = @MatchDimensionName +IF(@TargetDimensionGUID = '00000000-0000-0000-0000-000000000000') BEGIN + PRINT 'Target dimension not found.' + RETURN +END + +SELECT + SM.ListMemberGUID AS MemberGUID, + SM.[Name] AS Member, + SMV.ValueText AS MemberPropertyValue +FROM + SecureListMember SM + LEFT JOIN SecureListMemberValue SMV ON SM.ListMemberGUID = SMV.ListMemberGUID AND SMV.ValueIndex = @PropertyIndex + LEFT JOIN SecureListMember TM ON TM.ListGUID = @TargetDimensionGUID AND (SMV.ValueText = TM.[Name] OR CAST(SMV.ValueFloat AS NVARCHAR(64)) = TM.[Name]) AND (@MatchDimensionLevel = -1 OR TM.OutlineLevel = @MatchDimensionLevel) +WHERE + SM.ListGUID = @DimensionGUID + AND TM.ListMemberGUID IS NULL +ORDER BY + SM.SortOrderFullPath +GO + + +--------------------------------------------- + +-- dbo.procValidateModelStructures +-- ============================================= +-- Author: Eric Kretzer +-- Create date: Nov 21, 2006 +-- Description: Validates the Model Structure dynamic tables zzEMFModelMapping & zzEMFModelData +-- ============================================= +CREATE PROCEDURE [dbo].[procValidateModelStructures] +AS +BEGIN + SET NOCOUNT ON; + + DECLARE @zzMDCGUID uniqueidentifier + DECLARE @mdcName nvarchar(max) + DECLARE @zzMDCtablename nvarchar(36) + DECLARE @zzDIMcursor nvarchar(256) + DECLARE @zzDIMcolumnname nvarchar(256) + DECLARE @modelTemplateMappingTableName nvarchar(256) + DECLARE @modelDataTableName nvarchar(256) + DECLARE @dimensionName as nvarchar(256) + DECLARE @dimensionGUID as uniqueidentifier + DECLARE @fixSQL as nvarchar(max) + + DECLARE zztable CURSOR LOCAL FAST_FORWARD + FOR SELECT NAME, MODELDATACONFIGGUID FROM EMFMODELDATACONFIG + OPEN zztable + FETCH NEXT FROM zztable INTO @mdcName, @zzMDCGUID + WHILE @@FETCH_STATUS = 0 + BEGIN + + + --SET @zztable_query = 'ALTER TABLE ' + @zztable_name + ' ADD [MAPPINGTYPE] int NOT NULL Default(0) WITH VALUES' + --EXECUTE sp_executesql @zztable_query + SET @zzMDCtablename = REPLACE(@zzMDCGUID,'-','_') + --PRINT @zztablename + ' table is present' + --else + + SET @zzMDCtablename = REPLACE(@zzMDCGUID,'-','_') + SET @modelDataTableName = 'zzEMFModelData_' + @zzMDCtablename + if (select count(*) from sysobjects where xtype='u' and name like @modelDataTableName) = 0 + --PRINT @zztablename + ' table is present' + --else + PRINT @modelDataTableName + ' table is not present' + + SET @zzMDCtablename = REPLACE(@zzMDCGUID,'-','_') + SET @modelTemplateMappingTableName = 'zzEMFModelTemplateMapping_' + @zzMDCtablename + if (select count(*) from sysobjects where xtype='u' and name like @modelDataTableName) = 0 + --PRINT @zztablename + ' table is present' + --else + PRINT @modelTemplateMappingTableName + ' table is not present' + +--SELECT sysobjects.name, syscolumns.name,* FROM sysobjects JOIN syscolumns ON sysobjects.id = syscolumns.id WHERE sysobjects.xtype='U' order by sysobjects.name, syscolumns.name + DECLARE @type int + DECLARE zzdimensions CURSOR LOCAL FAST_FORWARD + FOR SELECT SLM.LISTGUID, SLM.NAME, UPPER('G' + REPLACE(cast(SLM.LISTGUID as varchar(36)),'-','_')) FROM dbo.EMFModelDataConfigDimensionLink MDCDL JOIN SECURELIST SLM ON MDCDL.DIMENSIONGUID=SLM.LISTGUID WHERE MDCDL.MODELDATACONFIGGUID = @zzMDCGUID + OPEN zzdimensions + FETCH NEXT FROM zzdimensions INTO @dimensionGUID, @dimensionName, @zzDIMcursor + WHILE @@FETCH_STATUS = 0 + BEGIN + SELECT @type = LISTTYPE FROM SECURELIST WHERE LISTGUID = @dimensionGUID + + IF @type = 0 or @type = 3 BEGIN + SET @zzDIMcolumnname = @zzDIMcursor --+ 'GUID' + SET @fixSQL = 'DELETE FROM emfmodeldataconfigdimensionlink WHERE DIMENSIONGUID = ''' + cast(@dimensionGUID as varchar(36)) + ''' and MODELDATACONFIGGUID = ''' + cast(@zzMDCGUID as varchar(36)) + '''' + IF (SELECT count(*) FROM sysobjects JOIN syscolumns ON sysobjects.id = syscolumns.id WHERE sysobjects.xtype='U' AND (sysobjects.name like @modelDataTableName or sysobjects.name like @modelTemplateMappingTableName)and syscolumns.name like @zzDIMcolumnname) <> 2 + --PRINT ' ' + @zzDIMcolumnname + ' is present' + --ELSE + PRINT @fixSQL + ' --' + cast(@zzMDCGUID as varchar(36)) + ' (' + @mdcName + ') - ' + @zzDIMcolumnname + ' (' + @dimensionName + ') is not present in both ModelData and ModelMapping' + END + + FETCH NEXT FROM zzdimensions INTO @dimensionGUID, @dimensionName, @zzDIMcursor + END + CLOSE zzdimensions + DEALLOCATE zzdimensions + + FETCH NEXT FROM zztable INTO @mdcName, @zzMDCGUID + END + CLOSE zztable + DEALLOCATE zztable + +END +GO + + +--------------------------------------------- + +-- dbo.procVerifyReportFolder +CREATE PROC [dbo].[procVerifyReportFolder] ( + @sourcedb nvarchar(100), + @folderGUID uniqueidentifier +) +AS +BEGIN + + IF EXISTS (SELECT 1 FROM [dbo].[Folder] WHERE FolderGuid = @folderGUID) + BEGIN + RETURN + END + + DECLARE @sql nvarchar(4000) = 'INSERT INTO [dbo].[Folder] ([FolderGuid], [FolderSetGUID], [ParentFolderGUID], [Name], [Description], [DateCreated], [DateModified], [OutlineLevel], [DisplayOrder], [ImageType], [FolderType], [QueryRootXML], [IsDeletedFolder], [BasedOnFolderGUID], [UpgradeHierarchyPath], [GlobalID]) + SELECT ''' + CAST(@folderGuid AS nvarchar(50)) + ''', [FolderSetGUID], [ParentFolderGUID], [Name], [Description], [DateCreated], [DateModified], [OutlineLevel], [DisplayOrder], [ImageType], [FolderType], [QueryRootXML], [IsDeletedFolder], ''00000000-0000-0000-0000-000000000000'', [UpgradeHierarchyPath], [GlobalID] + FROM ' + @sourceDB + '.[dbo].[Folder] + WHERE folderGUID = ''' + CAST(@folderGuid AS nvarchar(50)) + '''' + EXEC sp_executeSql @sql + + DECLARE @parentFolderGUID uniqueidentifier + SELECT @parentFolderGUID = ParentFolderGUID FROM [dbo].[Folder] WHERE FolderGuid = @folderGUID + + IF NOT EXISTS (SELECT 1 FROM [dbo].[Folder] WHERE FolderGuid = @parentFolderGUID) + BEGIN + EXEC [dbo].[procVerifyReportFolder] @sourcedb, @parentFolderGUID + END + +END +GO + + +--------------------------------------------- + +-- dbo.procWFBrokenConditionsFix +create proc [dbo].[procWFBrokenConditionsFix] +as + if((select COUNT(*) from wfeventplanstatement where type=1 and statementguid not in(select conditionsetguid from wfconditionset)) > 0) begin + declare crsStatements cursor for select statementguid from wfeventplanstatement where type=1 and statementguid not in(select conditionsetguid from wfconditionset) + declare @statementguid uniqueidentifier + declare @conditionguid uniqueidentifier + + open crsStatements + fetch next from crsStatements into @statementguid + + while(@@FETCH_STATUS = 0) begin + select @conditionguid = newid() + + insert into wfconditionset values(@statementguid, @conditionguid); + insert into wfcondition values(@conditionguid, @statementguid, 1, '00000000-0000-0000-0000-000000000000', '', '', 'Always', '', ''); + + fetch next from crsStatements into @statementguid + end + + close crsStatements + deallocate crsStatements + end +GO + + +--------------------------------------------- + +-- dbo.procWFHistoryReport +CREATE PROCEDURE [dbo].[procWFHistoryReport] + @workflowMapGUID uniqueidentifier, + @planGUIDList nvarchar(max) +AS + declare @tempTableName nvarchar(34) + select @tempTableName = '#T' + replace(CAST(NEWID() as nvarchar(36)), '-', '') + + declare @allsql nvarchar(max) + set @allsql = ' + declare @workflowMapGUID uniqueidentifier + declare @planGUIDList nvarchar(max) + + set @workflowMapGUID = ''' + CAST(@workflowMapGUID as nvarchar(36)) + ''' + set @planGUIDList = ''' + @planGUIDList + ''' + + --create empty records for all plan/step combinations + select distinct + e.EntityGUID, + s.WorkflowStepGUID, + CAST(''1900-01-01 12:00:00.000'' as datetime) as EnteredStep, + CAST(''1900-01-01 12:00:00.000'' as datetime) as ExitedStep, + 0 as DaysInStep + into ' + @tempTableName + ' + from + WFWorkflowStep s + cross join dbo.viewWFEntity e + where + s.WorkflowMapGUID = @workflowMapGUID + and e.EntityGUID in (select entityguid from WFToken where WorkflowMapGUID = @workflowMapGUID) + and e.EntityGUID in (select guid from dbo.ConvertCSGuidsToTable(@planGUIDList, '','')) + and s.IsHidden = 0 + and s.IsHiddenInRouting = 0 + + declare @planguid uniqueidentifier + declare @stepguid uniqueidentifier + declare crsPlan cursor for select EntityGUID, WorkflowStepGUID from ' + @tempTableName + ' + + open crsPlan + fetch next from crsPlan into @planguid, @stepguid + + declare @sql nvarchar(max) + + --fill in entered/exited step dates from history + while(@@FETCH_STATUS = 0) begin + set @sql = '' + update ' + @tempTableName + ' set EnteredStep = coalesce(h.DateTimeStamp, ''''1900-01-01 12:00:00.000'''') + from + ' + @tempTableName + ' wfh + inner join historyitem h on wfh.EntityGUID = h.ObjectGUID and h.Category=''''Workflow'''' and (h.MetaXML.exist(''''//WORKFLOWCHANGE[TYPE = 1 and ITEMGUID = "'' + lower(cast(@stepguid as nvarchar(36))) + ''"]'''') = 1) + where + wfh.EntityGUID = '''''' + cast(@planguid as nvarchar(36)) + '''''' and wfh.WorkflowStepGUID = '''''' + cast(@stepguid as nvarchar(36)) + ''''''; + + update ' + @tempTableName + ' set ExitedStep = coalesce(h.DateTimeStamp, ''''1900-01-01 12:00:00.000'''') + from + ' + @tempTableName + ' wfh + inner join historyitem h on wfh.EntityGUID = h.ObjectGUID and h.Category=''''Workflow'''' and (h.MetaXML.exist(''''//WORKFLOWCHANGE[(TYPE = 3 or TYPE = 10) and ITEMGUID = "'' + lower(cast(@stepguid as nvarchar(36))) + ''"]'''') = 1) + where + wfh.EntityGUID = '''''' + cast(@planguid as nvarchar(36)) + '''''' and wfh.WorkflowStepGUID = '''''' + cast(@stepguid as nvarchar(36)) + ''''''; + '' + exec(@sql) + + fetch next from crsPlan into @planguid, @stepguid + end + + close crsPlan + deallocate crsPlan + + --calculate time in step + update ' + @tempTableName + ' set DaysInStep = cast((GETDATE() - EnteredStep) as int) where EnteredStep != ''1900-01-01 12:00:00.000'' and ExitedStep = ''1900-01-01 12:00:00.000''; + update ' + @tempTableName + ' set DaysInStep = cast((ExitedStep - EnteredStep) as int) where EnteredStep != ''1900-01-01 12:00:00.000'' and ExitedStep != ''1900-01-01 12:00:00.000''; + + select * from ' + @tempTableName + ' + + drop table ' + @tempTableName + ' + ' + exec(@allsql) +GO + + +--------------------------------------------- + +-- dbo.procWFMergeWorkflows +create proc procWFMergeWorkflows + @sourceWorkflowGUID uniqueidentifier, + @targetWorkflowGUID uniqueidentifier +as + update WFComment set WorkflowMapGUID = @targetWorkflowGUID where WorkflowMapGUID = @sourceWorkflowGUID + update WFHistory set WorkflowMapGUID = @targetWorkflowGUID where WorkflowMapGUID = @sourceWorkflowGUID + update WFProcess set WorkflowMapGUID = @targetWorkflowGUID where WorkflowMapGUID = @sourceWorkflowGUID + update WFProcessStepLink set WorkflowMapGUID = @targetWorkflowGUID where WorkflowMapGUID = @sourceWorkflowGUID + update WFToken set WorkflowMapGUID = @targetWorkflowGUID where WorkflowMapGUID = @sourceWorkflowGUID + update WFTransition set WorkflowMapGUID = @targetWorkflowGUID where WorkflowMapGUID = @sourceWorkflowGUID + update WFWorkflowStep set WorkflowMapGUID = @targetWorkflowGUID where WorkflowMapGUID = @sourceWorkflowGUID + delete from WFToken where WorkflowMapGUID = @targetWorkflowGUID +GO + + +--------------------------------------------- + +-- dbo.procWFPlanStepCacheRefresh +CREATE proc dbo.procWFPlanStepCacheRefresh +as + set nocount on + + declare @currentPlanGUID uniqueidentifier + declare @lastPlanGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000' + declare @stepName nvarchar(64) + declare @stepGUID uniqueidentifier + declare @stepList nvarchar(max) = '' + declare @stepGUIDList nvarchar(max) = '' + + declare crsTokens cursor fast_forward for select distinct T.EntityGUID, S.WorkflowStepGUID, S.Name from [dbo].[WFToken] T (readuncommitted) inner join [dbo].[WFWorkflowStep] S on S.WorkflowStepGUID = T.WorkflowStepGUID where S.IsHidden = 0 and S.IsHiddenInRouting = 0 order by T.EntityGUID + + open crsTokens + fetch next from crsTokens into @currentPlanGUID, @stepGUID, @stepName + + while (@@fetch_status = 0) begin + if (@lastPlanGUID != @currentPlanGUID) begin + if (len(@stepList) > 0) begin + update [dbo].[XPlan] set CachedWorkflowStep = left(@stepList, 128), CachedWorkflowStepGUIDsCSV = left(@stepGUIDList, 400) where PlanGUID = @lastPlanGUID + end + + set @stepList = '' + set @stepGUIDList = '' + set @lastPlanGUID = @currentPlanGUID + end + + if (len(@stepList) > 0) begin + set @stepList = @stepList + ', ' + set @stepGUIDList = @stepGUIDList + ',' + end + set @stepList = @stepList + @stepName + set @stepGUIDList = @stepGUIDList + cast(@stepGUID as nvarchar(36)) + + fetch next from crsTokens into @currentPlanGUID, @stepGUID, @stepName + end + + if (@lastPlanGUID != '00000000-0000-0000-0000-000000000000') and (len(@stepList) > 0) begin + update [dbo].[XPlan] set CachedWorkflowStep = left(@stepList, 128), CachedWorkflowStepGUIDsCSV = left(@stepGUIDList, 400) where PlanGUID = @lastPlanGUID + end + + close crsTokens + deallocate crsTokens +GO + + +--------------------------------------------- + +-- dbo.procWFSecurityRemoveInvalid +create proc dbo.procWFSecurityRemoveInvalid + @entityGUID uniqueidentifier, + @wfStepGUID uniqueidentifier +as + delete ra + from + WFToken t + inner join viewWFEntity e on e.EntityGUID = t.EntityGUID + inner join WFWorkflowStep s on s.WorkflowStepGUID = t.WorkflowStepGUID + inner join UserRole r on r.Type = case when s.ReviewerAccess = 1 then 6 when s.ReviewerAccess = 2 then 8 else -1 end + inner join S3RoleAssignment ra on ra.LootGroupID = e.CachedLootID and ra.RoleID = r.RoleID + inner join UserProfile u on u.userGUID = ra.IdentityGUID --wf auto-security is always applied directly to users + where + s.ReviewerAccess in(1, 2) --read, write + and s.ReviewerExitAccess != s.ReviewerAccess + and not exists( --checks if assigned user is not a reviewer + select 1 + from + viewWFReviewerAssignmentIndexedAll ra + where + ra.WorkflowStepGUID = s.WorkflowStepGUID + and ra.PlanGUID = e.EntityGUID + and ra.UserGUID = u.UserGUID + ) + and e.EntityGUID = @entityGUID + and s.WorkflowStepGUID = @wfStepGUID +GO + + +--------------------------------------------- + +-- dbo.sp_alterdiagram +CREATE PROCEDURE dbo.sp_alterdiagram + ( + @diagramname sysname, + @owner_id int = null, + @version int, + @definition varbinary(max) + ) + WITH EXECUTE AS 'dbo' + AS + BEGIN + set nocount on + + declare @theId int + declare @retval int + declare @IsDbo int + + declare @UIDFound int + declare @DiagId int + declare @ShouldChangeUID int + + if(@diagramname is null) + begin + RAISERROR ('Invalid ARG', 16, 1) + return -1 + end + + execute as caller; + select @theId = DATABASE_PRINCIPAL_ID(); + select @IsDbo = IS_MEMBER(N'db_owner'); + if(@owner_id is null) + select @owner_id = @theId; + revert; + + select @ShouldChangeUID = 0 + select @DiagId = diagram_id, @UIDFound = principal_id from dbo.sysdiagrams where principal_id = @owner_id and name = @diagramname + + if(@DiagId IS NULL or (@IsDbo = 0 and @theId <> @UIDFound)) + begin + RAISERROR ('Diagram does not exist or you do not have permission.', 16, 1); + return -3 + end + + if(@IsDbo <> 0) + begin + if(@UIDFound is null or USER_NAME(@UIDFound) is null) -- invalid principal_id + begin + select @ShouldChangeUID = 1 ; + end + end + + -- update dds data + update dbo.sysdiagrams set definition = @definition where diagram_id = @DiagId ; + + -- change owner + if(@ShouldChangeUID = 1) + update dbo.sysdiagrams set principal_id = @theId where diagram_id = @DiagId ; + + -- update dds version + if(@version is not null) + update dbo.sysdiagrams set version = @version where diagram_id = @DiagId ; + + return 0 + END +GO + + +--------------------------------------------- + +-- dbo.sp_creatediagram +CREATE PROCEDURE dbo.sp_creatediagram + ( + @diagramname sysname, + @owner_id int = null, + @version int, + @definition varbinary(max) + ) + WITH EXECUTE AS 'dbo' + AS + BEGIN + set nocount on + + declare @theId int + declare @retval int + declare @IsDbo int + declare @userName sysname + if(@version is null or @diagramname is null) + begin + RAISERROR (N'E_INVALIDARG', 16, 1); + return -1 + end + + execute as caller; + select @theId = DATABASE_PRINCIPAL_ID(); + select @IsDbo = IS_MEMBER(N'db_owner'); + revert; + + if @owner_id is null + begin + select @owner_id = @theId; + end + else + begin + if @theId <> @owner_id + begin + if @IsDbo = 0 + begin + RAISERROR (N'E_INVALIDARG', 16, 1); + return -1 + end + select @theId = @owner_id + end + end + -- next 2 line only for test, will be removed after define name unique + if EXISTS(select diagram_id from dbo.sysdiagrams where principal_id = @theId and name = @diagramname) + begin + RAISERROR ('The name is already used.', 16, 1); + return -2 + end + + insert into dbo.sysdiagrams(name, principal_id , version, definition) + VALUES(@diagramname, @theId, @version, @definition) ; + + select @retval = @@IDENTITY + return @retval + END +GO + + +--------------------------------------------- + +-- dbo.sp_drop_constraints +CREATE proc [dbo].[sp_drop_constraints] + + @tablename sysname + +as + +-- name: sp_drop_constraints +-- author: douglas bass +-- date: 06/19/2000 + +-- sp_drop_constraints will drop all constraints on the specified table, +-- including CHECK, FOREIGN KEY, PRIMARY KEY, UNIQUE, and DEFAULT constraints. +-- Compile it in your master database and use it from any user database. + +set nocount on + +declare @constname sysname, + @cmd varchar(1024) + +declare curs_constraints cursor LOCAL FAST_FORWARD for + select name + from sysobjects + where xtype in ('C', 'F', 'PK', 'UQ', 'D') + and (status & 64) = 0 + and parent_obj = object_id(@tablename) + +open curs_constraints + +fetch next from curs_constraints into @constname +while (@@fetch_status = 0) +begin + select @cmd = 'ALTER TABLE ' + @tablename + ' DROP CONSTRAINT ' + @constname + exec(@cmd) + fetch next from curs_constraints into @constname +end + +close curs_constraints +deallocate curs_constraints + +return 0 +GO + + +--------------------------------------------- + +-- dbo.sp_dropdiagram +CREATE PROCEDURE dbo.sp_dropdiagram + ( + @diagramname sysname, + @owner_id int = null + ) + WITH EXECUTE AS 'dbo' + AS + BEGIN + set nocount on + declare @theId int + declare @IsDbo int + + declare @UIDFound int + declare @DiagId int + + if(@diagramname is null) + begin + RAISERROR ('Invalid value', 16, 1); + return -1 + end + + EXECUTE AS CALLER; + select @theId = DATABASE_PRINCIPAL_ID(); + select @IsDbo = IS_MEMBER(N'db_owner'); + if(@owner_id is null) + select @owner_id = @theId; + REVERT; + + select @DiagId = diagram_id, @UIDFound = principal_id from dbo.sysdiagrams where principal_id = @owner_id and name = @diagramname + if(@DiagId IS NULL or (@IsDbo = 0 and @UIDFound <> @theId)) + begin + RAISERROR ('Diagram does not exist or you do not have permission.', 16, 1) + return -3 + end + + delete from dbo.sysdiagrams where diagram_id = @DiagId; + + return 0; + END +GO + + +--------------------------------------------- + +-- dbo.sp_helpdiagramdefinition +CREATE PROCEDURE dbo.sp_helpdiagramdefinition + ( + @diagramname sysname, + @owner_id int = null + ) + WITH EXECUTE AS N'dbo' + AS + BEGIN + set nocount on + + declare @theId int + declare @IsDbo int + declare @DiagId int + declare @UIDFound int + + if(@diagramname is null) + begin + RAISERROR (N'E_INVALIDARG', 16, 1); + return -1 + end + + execute as caller; + select @theId = DATABASE_PRINCIPAL_ID(); + select @IsDbo = IS_MEMBER(N'db_owner'); + if(@owner_id is null) + select @owner_id = @theId; + revert; + + select @DiagId = diagram_id, @UIDFound = principal_id from dbo.sysdiagrams where principal_id = @owner_id and name = @diagramname; + if(@DiagId IS NULL or (@IsDbo = 0 and @UIDFound <> @theId )) + begin + RAISERROR ('Diagram does not exist or you do not have permission.', 16, 1); + return -3 + end + + select version, definition FROM dbo.sysdiagrams where diagram_id = @DiagId ; + return 0 + END +GO + + +--------------------------------------------- + +-- dbo.sp_helpdiagrams +CREATE PROCEDURE dbo.sp_helpdiagrams + ( + @diagramname sysname = NULL, + @owner_id int = NULL + ) + WITH EXECUTE AS N'dbo' + AS + BEGIN + DECLARE @user sysname + DECLARE @dboLogin bit + EXECUTE AS CALLER; + SET @user = USER_NAME(); + SET @dboLogin = CONVERT(bit,IS_MEMBER('db_owner')); + REVERT; + SELECT + [Database] = DB_NAME(), + [Name] = name, + [ID] = diagram_id, + [Owner] = USER_NAME(principal_id), + [OwnerID] = principal_id + FROM + sysdiagrams + WHERE + (@dboLogin = 1 OR USER_NAME(principal_id) = @user) AND + (@diagramname IS NULL OR name = @diagramname) AND + (@owner_id IS NULL OR principal_id = @owner_id) + ORDER BY + 4, 5, 1 + END +GO + + +--------------------------------------------- + +-- dbo.sp_renamediagram +CREATE PROCEDURE dbo.sp_renamediagram + ( + @diagramname sysname, + @owner_id int = null, + @new_diagramname sysname + + ) + WITH EXECUTE AS 'dbo' + AS + BEGIN + set nocount on + declare @theId int + declare @IsDbo int + + declare @UIDFound int + declare @DiagId int + declare @DiagIdTarg int + declare @u_name sysname + if((@diagramname is null) or (@new_diagramname is null)) + begin + RAISERROR ('Invalid value', 16, 1); + return -1 + end + + EXECUTE AS CALLER; + select @theId = DATABASE_PRINCIPAL_ID(); + select @IsDbo = IS_MEMBER(N'db_owner'); + if(@owner_id is null) + select @owner_id = @theId; + REVERT; + + select @u_name = USER_NAME(@owner_id) + + select @DiagId = diagram_id, @UIDFound = principal_id from dbo.sysdiagrams where principal_id = @owner_id and name = @diagramname + if(@DiagId IS NULL or (@IsDbo = 0 and @UIDFound <> @theId)) + begin + RAISERROR ('Diagram does not exist or you do not have permission.', 16, 1) + return -3 + end + + -- if((@u_name is not null) and (@new_diagramname = @diagramname)) -- nothing will change + -- return 0; + + if(@u_name is null) + select @DiagIdTarg = diagram_id from dbo.sysdiagrams where principal_id = @theId and name = @new_diagramname + else + select @DiagIdTarg = diagram_id from dbo.sysdiagrams where principal_id = @owner_id and name = @new_diagramname + + if((@DiagIdTarg is not null) and @DiagId <> @DiagIdTarg) + begin + RAISERROR ('The name is already used.', 16, 1); + return -2 + end + + if(@u_name is null) + update dbo.sysdiagrams set [name] = @new_diagramname, principal_id = @theId where diagram_id = @DiagId + else + update dbo.sysdiagrams set [name] = @new_diagramname where diagram_id = @DiagId + return 0 + END +GO + + +--------------------------------------------- + +-- dbo.sp_upgraddiagrams +CREATE PROCEDURE dbo.sp_upgraddiagrams + AS + BEGIN + IF OBJECT_ID(N'dbo.sysdiagrams') IS NOT NULL + return 0; + + CREATE TABLE dbo.sysdiagrams + ( + name sysname NOT NULL, + principal_id int NOT NULL, -- we may change it to varbinary(85) + diagram_id int PRIMARY KEY IDENTITY, + version int, + + definition varbinary(max) + CONSTRAINT UK_principal_name UNIQUE + ( + principal_id, + name + ) + ); + + + /* Add this if we need to have some form of extended properties for diagrams */ + /* + IF OBJECT_ID(N'dbo.sysdiagram_properties') IS NULL + BEGIN + CREATE TABLE dbo.sysdiagram_properties + ( + diagram_id int, + name sysname, + value varbinary(max) NOT NULL + ) + END + */ + + IF OBJECT_ID(N'dbo.dtproperties') IS NOT NULL + begin + insert into dbo.sysdiagrams + ( + [name], + [principal_id], + [version], + [definition] + ) + select + convert(sysname, dgnm.[uvalue]), + DATABASE_PRINCIPAL_ID(N'dbo'), -- will change to the sid of sa + 0, -- zero for old format, dgdef.[version], + dgdef.[lvalue] + from dbo.[dtproperties] dgnm + inner join dbo.[dtproperties] dggd on dggd.[property] = 'DtgSchemaGUID' and dggd.[objectid] = dgnm.[objectid] + inner join dbo.[dtproperties] dgdef on dgdef.[property] = 'DtgSchemaDATA' and dgdef.[objectid] = dgnm.[objectid] + + where dgnm.[property] = 'DtgSchemaNAME' and dggd.[uvalue] like N'_EA3E6268-D998-11CE-9454-00AA00A3F36E_' + return 2; + end + return 1; + END +GO + + +--------------------------------------------- + +--------------------------------------------- +-- FUNCTIONS +--------------------------------------------- + +-- dbo.CSVGuidsToTable +CREATE FUNCTION [dbo].[CSVGuidsToTable] + (@CSVList varchar(max) ) +RETURNS + @tPKList TABLE ( guid uniqueidentifier) +AS +BEGIN +/* + select * from dbo.[CSVGuidsToTable]('') + select * from dbo.[CSVGuidsToTable]('00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,') + select * from dbo.[CSVGuidsToTable]('00000000-0000-0000-0000-000000000000') + select * from dbo.[CSVGuidsToTable]('00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000') + DECLARE @list nvarchar(max) + SET @list = '00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,' + DECLARE @delimiter char(1) + SET @delimiter = ',' + DECLARE @tbl TABLE (pos int IDENTITY(1, 1) NOT NULL, guid uniqueidentifier) +*/ + + + DECLARE @CSVCte TABLE (startpos bigint, endpos bigint) + + + DECLARE @startpos bigint + SET @startpos = 1 + DECLARE @endpos bigint + SET @endpos = CHARINDEX(',' , @CSVList + ',') + + IF @endpos = 0 RETURN + + INSERT INTO @CSVCte (startpos, endpos) + SELECT @startpos, @endpos + + SET @startpos = @endpos + 1 + SET @endpos = CHARINDEX(',', @CSVList + ',', @endpos + 1) + + WHILE @endpos <> 0 BEGIN + INSERT INTO @CSVCte (startpos, endpos) + SELECT @startpos, @endpos + + SET @startpos = @endpos + 1 + SET @endpos = CHARINDEX(',', @CSVList + ',', @endpos + 1) + END + + INSERT INTO @tPKList + SELECT cast(rtrim(ltrim(SUBSTRING(@CSVList, StartPos,EndPos-StartPos))) as uniqueidentifier) FROM @CSVCte WHERE endpos - startpos >= 36 + + + + RETURN +END +GO + + +--------------------------------------------- + +-- dbo.CapitalizeEachWord +CREATE FUNCTION [dbo].[CapitalizeEachWord]( + @InputString varchar(8000) +) +RETURNS varchar(8000) +AS +BEGIN + +declare @CurrentString varchar(8000); +declare @ReturnString varchar(8000); +set @ReturnString = ''; + +DECLARE BUILD CURSOR + FOR select Component from [dbo].[Split](@InputString, ' ') + +Open BUILD +FETCH NEXT FROM BUILD INTO @CurrentString +WHILE (@@FETCH_STATUS <> - 1) +BEGIN + set @ReturnString = @ReturnString + upper(substring(@currentString,1,1)) + lower(substring(@currentString, 2, Len(@currentString))) + ' ' + FETCH NEXT FROM BUILD INTO @CurrentString +END + +set @ReturnString = RTRIM(@ReturnString) + +CLOSE BUILD +DEALLOCATE BUILD + + +RETURN @ReturnString +END +GO + + +--------------------------------------------- + +-- dbo.ColumnExists +CREATE FUNCTION [dbo].[ColumnExists]( + @SchemaName NVARCHAR(128), + @TableName NVARCHAR(MAX), + @ColumnName NVARCHAR(128) +) +RETURNS BIT--Returns 0 if column does not exist. Returns 1 if column exists. +AS +BEGIN +RETURN dbo.TableColumnExists(@SchemaName,@TableName,@columnname) +----See if the Table already contains the column. +--IF EXISTS +--(SELECT * FROM SysObjects O INNER JOIN SysColumns C ON O.ID=C.ID +--WHERE ObjectProperty(O.ID,'IsUserTable')=1 +--AND O.Name=@TableName +--AND C.Name=@ColumnName) +--RETURN cast(1 as bit) +----Table does not contain the column. +--RETURN cast(0 as bit) +END +GO + + +--------------------------------------------- + +-- dbo.ColumnExistsByTableExpression +CREATE FUNCTION [dbo].[ColumnExistsByTableExpression]( + @TableExpression NVARCHAR(MAX), + @ColumnName NVARCHAR(128) +) +RETURNS BIT--Returns 0 if column does not exist. Returns 1 if column exists. +AS +BEGIN +RETURN dbo.TableColumnExistsByTableExpression(@TableExpression,@columnname) +----See if the Table already contains the column. +--IF EXISTS +--(SELECT * FROM SysObjects O INNER JOIN SysColumns C ON O.ID=C.ID +--WHERE ObjectProperty(O.ID,'IsUserTable')=1 +--AND O.Name=@TableName +--AND C.Name=@ColumnName) +--RETURN cast(1 as bit) +----Table does not contain the column. +--RETURN cast(0 as bit) +END +GO + + +--------------------------------------------- + +-- dbo.ConstraintExists +create function dbo.ConstraintExists( + @ConstraintName sysname +) +returns bit +AS +BEGIN + declare @returnVal bit; + set @returnVal = 0; + + if (exists(select 1 from sys.sysconstraints sc where OBJECT_NAME(sc.constid) = @ConstraintName)) + begin + set @returnVal = 1 + end + return @returnVal; + +END +GO + + +--------------------------------------------- + +-- dbo.ConvertCSGuidsToTable +CREATE FUNCTION [dbo].[ConvertCSGuidsToTable] + (@CSVList varchar(max), @delimiter char(1) = N',' ) +RETURNS + @tPKList TABLE ( listpos int IDENTITY(1, 1) NOT NULL, guid uniqueidentifier) +AS +BEGIN +/* + select * from dbo.[ConvertCSGuidsToTable]('',',') + select * from dbo.[ConvertCSGuidsToTable]('00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,',',') + select * from dbo.[ConvertCSGuidsToTable]('00000000-0000-0000-0000-000000000000',',') + select * from dbo.[ConvertCSGuidsToTable]('00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000',',') + DECLARE @list nvarchar(max) + SET @list = '00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,' + DECLARE @delimiter char(1) + SET @delimiter = ',' + DECLARE @tbl TABLE (pos int IDENTITY(1, 1) NOT NULL, guid uniqueidentifier) +*/ + + + DECLARE @startpos bigint + SET @startpos = 1 + DECLARE @endpos bigint + SET @endpos = CHARINDEX(@delimiter , @CSVList + @delimiter) + + IF @endpos = 0 RETURN + + IF @endpos - @startpos >= 36 BEGIN + INSERT INTO @tPKList (guid) values (cast(rtrim(ltrim(SUBSTRING(@CSVList, @StartPos,@EndPos-@StartPos))) as uniqueidentifier)) + END + + SET @startpos = @endpos + 1 + SET @endpos = CHARINDEX(@delimiter, @CSVList + @delimiter, @endpos + 1) + + WHILE @endpos <> 0 BEGIN + IF @endpos - @startpos >= 36 BEGIN + INSERT INTO @tPKList (guid) values (cast(rtrim(ltrim(SUBSTRING(@CSVList, @StartPos,@EndPos-@StartPos))) as uniqueidentifier)) + END + + SET @startpos = @endpos + 1 + SET @endpos = CHARINDEX(@delimiter, @CSVList + @delimiter, @endpos + 1) + END + + + + + RETURN +END +GO + + +--------------------------------------------- + +-- dbo.ConvertCSValuesToTable +CREATE FUNCTION [dbo].[ConvertCSValuesToTable] + (@CSVList nvarchar(max), @delimiter char(1) = N',' ) +RETURNS + @tPKList TABLE ( pos int IDENTITY(1, 1) NOT NULL, val nvarchar(max)) +AS +BEGIN +/* + select * from dbo.[ConvertCSValuesToTable]('', ',') + select * from dbo.[ConvertCSValuesToTable]('00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,', ',') + select * from dbo.[ConvertCSValuesToTable]('00000000-0000-0000-0000-000000000000', ',') + select * from dbo.[ConvertCSValuesToTable]('00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000', ',') + DECLARE @list nvarchar(max) + SET @list = '00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,00000000-0000-0000-0000-000000000000,' + DECLARE @delimiter char(1) + SET @delimiter = ',' + DECLARE @tbl TABLE (pos int IDENTITY(1, 1) NOT NULL, guid uniqueidentifier) +*/ + + + DECLARE @startpos bigint + SET @startpos = 1 + DECLARE @endpos bigint + SET @endpos = CHARINDEX(@delimiter , @CSVList + @delimiter) + + IF @endpos = 0 RETURN + + IF @endpos - @startpos >= 0 BEGIN + INSERT INTO @tPKList (val) values ( rtrim(ltrim(SUBSTRING(@CSVList, @StartPos,@EndPos-@StartPos)))) + END + + SET @startpos = @endpos + 1 + SET @endpos = CHARINDEX(@delimiter, @CSVList + @delimiter, @endpos + 1) + + WHILE @endpos <> 0 BEGIN + --INSERT INTO @CSVCte (startpos, endpos) + --SELECT @startpos, @endpos + IF @endpos - @startpos >= 0 BEGIN + INSERT INTO @tPKList (val) values ( rtrim(ltrim(SUBSTRING(@CSVList, @StartPos,@EndPos-@StartPos)))) + END + + SET @startpos = @endpos + 1 + SET @endpos = CHARINDEX(@delimiter, @CSVList + @delimiter, @endpos + 1) + END + + + --SELECT rtrim(ltrim(SUBSTRING(@CSVList, StartPos,EndPos-StartPos))) FROM @CSVCte WHERE endpos - startpos >= 0 + + + + RETURN +END +GO + + +--------------------------------------------- + +-- dbo.ConvertEMFFormatToScore +CREATE function [dbo].[ConvertEMFFormatToScore](@EMFFormat as nvarchar(max)) + returns nvarchar(max) +as +begin + Return CASE @EMFFormat + WHEN 'Percent 2' then '0.00%;(0.00%)' + WHEN 'Dollars (Actual) 2' then '$#,##0.00;($#,##0.00)' + WHEN 'Dollars (Thousands)' then '$#,##0;($#,##0)' + WHEN 'Dollars (Thousands) 0' then '$#,##0;($#,##0)' + WHEN 'Number 0' then '#,##0;(#,##0)' + WHEN 'Number 1' then '#,##0.0;(#,##0.0)' + WHEN 'Number 2' then '#,##0.00;(#,##0.00)' + ELSE @EMFFormat + END +END +GO + + +--------------------------------------------- + +-- dbo.DataIntegrationSchema +create function dbo.DataIntegrationSchema() +RETURNS sysname +BEGIN + return 'int'; +END +GO + + +--------------------------------------------- + +-- dbo.Divide +CREATE function [dbo].[Divide] (@left float, @right decimal(38,15)) +returns decimal(38,15) +as +begin +return cast((@left / @right) as decimal(38,15)) +end +GO + + +--------------------------------------------- + +-- dbo.DivideSafely +Create FUNCTION [dbo].[DivideSafely](@numeratoramount float, @denominatoramount float, @isusingdenominator tinyint) +RETURNS float +AS +BEGIN + + if (@numeratoramount is null) begin + return 0 + end + + if (@isusingdenominator = 0) begin + return @numeratoramount + end + + if (@denominatoramount is null) or (@denominatoramount = 0) begin + return 0 + end + + return @numeratoramount / @denominatoramount + +END +GO + + +--------------------------------------------- + +-- dbo.GUIDLEN +create function [dbo].[GUIDLEN]() +returns int +AS +BEGIN + declare @len int; + select @len = LEN(dbo.ZeroGUID()); + return @len; +END +GO + + +--------------------------------------------- + +-- dbo.GetColumnDefaultValue +Create FUNCTION [dbo].[GetColumnDefaultValue]( + @SchemaName NVARCHAR(128), + @TableName NVARCHAR(1000), + @ColumnName NVARCHAR(128) +) +RETURNS nvarchar(4000) +AS +BEGIN + +DECLARE @DefaultValue AS NVARCHAR(4000) + +SET @DefaultValue = NULL + +SELECT @DefaultValue = COLUMN_DEFAULT +FROM INFORMATION_SCHEMA.COLUMNS +WHERE TABLE_SCHEMA = @SchemaName + AND TABLE_NAME = @TableName + AND COLUMN_NAME = @ColumnName + +IF @DefaultValue IS NOT NULL +BEGIN +--Trim out the leading '(' and trailing ')' +--Leading '(' +SET @DefaultValue = REPLACE(REPLACE(LTrim(RTrim(REPLACE(REPLACE(@DefaultValue,' ','~'),'(',' '))),' ','('),'~',' ') +--Trailing ')' +SET @DefaultValue = REPLACE(REPLACE(LTrim(RTrim(REPLACE(REPLACE(@DefaultValue,' ','~'),')',' '))),' ',')'),'~',' ') +END + +RETURN @DefaultValue + +END +GO + + +--------------------------------------------- + +-- dbo.GetCurrentFiscalYear +create function [dbo].[GetCurrentFiscalYear]() +RETURNS char(4) as begin + +DECLARE @RET AS CHAR(4) +SELECT @RET = CAST(YEAR(dbo.getfiscaldate(getdate())) AS CHAR(4)) + +return @RET +end +GO + + +--------------------------------------------- + +-- dbo.GetCurrentMonthAmount +create FUNCTION [dbo].GetCurrentMonthAmount +( + @currentMonthIndex tinyint, + @amount01 money, + @amount02 money, + @amount03 money, + @amount04 money, + @amount05 money, + @amount06 money, + @amount07 money, + @amount08 money, + @amount09 money, + @amount10 money, + @amount11 money, + @amount12 money +) +returns money with schemabinding +BEGIN + +declare @amount money + +if @currentMonthIndex = 1 set @amount = @amount01 +if @currentMonthIndex = 2 set @amount = @amount02; +if @currentMonthIndex = 3 set @amount = @amount03; +if @currentMonthIndex = 4 set @amount = @amount04; +if @currentMonthIndex = 5 set @amount = @amount05; +if @currentMonthIndex = 6 set @amount = @amount06; +if @currentMonthIndex = 7 set @amount = @amount07; +if @currentMonthIndex = 8 set @amount = @amount08; +if @currentMonthIndex = 9 set @amount = @amount09; +if @currentMonthIndex = 10 set @amount = @amount10; +if @currentMonthIndex = 11 set @amount = @amount11; +if @currentMonthIndex = 12 set @amount = @amount12; + + +return @amount + +END +GO + + +--------------------------------------------- + +-- dbo.GetDBSetting +CREATE FUNCTION [dbo].[GetDBSetting](@SettingName nvarchar(128)) + RETURNS nvarchar(4000) + AS + BEGIN + DECLARE @Value nvarchar(4000) + SET @Value = null + + if exists(select 1 from dbsetting where name = @SettingName) + set @Value = (select setting from DBSetting where Name = @SettingName) + + return @value + END +GO + + +--------------------------------------------- + +-- dbo.GetDataIntSectionAcceptedTableName +create function dbo.GetDataIntSectionAcceptedTableName( + @SectionId uniqueidentifier +) +returns varchar(max) +BEGIN + return dbo.SanitizeNonDelimitedIdentifier('Import_' + cast(@SectionId as nvarchar(36)) + '_Accepted'); +END +GO + + +--------------------------------------------- + +-- dbo.GetDataIntSectionAcceptedViewName +create function dbo.GetDataIntSectionAcceptedViewName( + @SectionName nvarchar(128), + @SectionId uniqueidentifier +) +returns varchar(max) +BEGIN + return dbo.SanitizeNonDelimitedIdentifier('viewImport_' + @SectionName + '_' + cast(@SectionId as nvarchar(36)) + '_Accepted'); +END +GO + + +--------------------------------------------- + +-- dbo.GetDataIntSectionRejectedTableName +create function dbo.GetDataIntSectionRejectedTableName( + @SectionId uniqueidentifier +) +returns varchar(max) +BEGIN + return dbo.SanitizeNonDelimitedIdentifier('Import_' + cast(@SectionId as nvarchar(36)) + '_Rejected'); +END +GO + + +--------------------------------------------- + +-- dbo.GetDataIntSectionRejectedViewName +CREATE function dbo.GetDataIntSectionRejectedViewName( + @SectionName nvarchar(128), + @SectionId uniqueidentifier +) +returns varchar(max) +BEGIN + return dbo.SanitizeNonDelimitedIdentifier('viewImport_' + @SectionName + '_' + cast(@SectionId as nvarchar(36)) + '_Rejected'); +END +GO + + +--------------------------------------------- + +-- dbo.GetDaysInMonth +CREATE FUNCTION [dbo].[GetDaysInMonth] ( @pDate DATETIME ) +RETURNS INT +with schemabinding +AS +BEGIN + + --SET @pDate = CONVERT(VARCHAR(10), @pDate, 101) + SET @pDate = dateadd(d, 1 - DAY(@pDate),@pdate) + + RETURN DATEDIFF(DD, @pDate, DATEADD(MM, 1, @pDate)) +END +GO + + +--------------------------------------------- + +-- dbo.GetDaysInMonthsLoaded +CREATE FUNCTION [dbo].[GetDaysInMonthsLoaded] (@fiscalYearID int) +RETURNS INT +AS + BEGIN + + RETURN + (SELECT SUM(VALUE) + FROM [client].[viewFactWorkingHoursPerMonthUnpivoted] wh + INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = wh.FiscalMonthID + WHERE FiscalYearID = @FiscalYearID + AND fm.SortOrder <= (SELECT CAST(Setting AS int) FROM [dbo].[DBSetting] WHERE Name = 'OB_Months_Loaded')) + + END +GO + + +--------------------------------------------- + +-- dbo.GetDefaultConstraintName +CREATE FUNCTION [dbo].[GetDefaultConstraintName]( + @SQLSchemaName nvarchar(128), + @SQLObjectName nvarchar(128), + @ColumnName NVARCHAR(128) +) +returns nvarchar(128) +AS +BEGIN + return [dbo].[GetDefaultConstraintNameByTableExpression](@SQLSchemaName + '.' + @SQLObjectName, @ColumnName); + +END +GO + + +--------------------------------------------- + +-- dbo.GetDefaultConstraintNameByTableExpression +CREATE FUNCTION [dbo].[GetDefaultConstraintNameByTableExpression]( + @SQLObjectExpression VARCHAR(MAX), + @ColumnName NVARCHAR(128) +) +returns nvarchar(128) +AS +BEGIN + declare @defConstraint nvarchar(128); + select top 1 @defConstraint = c.name from sys.default_constraints c + inner join sys.columns col on col.default_object_id = c.object_id + inner join sys.objects o on o.object_id = c.parent_object_id + inner join sys.schemas s on s.schema_id = o.schema_id + where ('[' + s.name + '].[' + o.name + ']') = @SQLObjectExpression + and col.name = @ColumnName + + if (@defConstraint is null) + begin + select top 1 @defConstraint = c.name from sys.default_constraints c + inner join sys.columns col on col.default_object_id = c.object_id + inner join sys.objects o on o.object_id = c.parent_object_id + inner join sys.schemas s on s.schema_id = o.schema_id + where (s.name + '.' + o.name) = @SQLObjectExpression + and col.name = @ColumnName + end + + return @defConstraint; + +END +GO + + +--------------------------------------------- + +-- dbo.GetDepreciationPart +CREATE FUNCTION [dbo].[GetDepreciationPart]( + @amount money + ,@amountYear int + ,@usefulLife int + ,@inserviceYear int + ,@inserviceMonth int + ,@resultYear int + ) +RETURNS Money +AS +BEGIN + +if @amountYear > @inserviceYear set @inserviceYear = @amountYear + +if @resultYear < @inserviceYear begin + return 0 +end + +if @resultYear > @inserviceYear + @usefulLife begin + return 0 +end + +declare @firstYearMonths int +set @firstYearMonths = 12 - @inserviceMonth + +declare @lastYearMonths int +set @lastYearMonths = 12 - @firstYearMonths + +declare @yearlyAmount money +set @yearlyAmount = @amount / @usefulLife + +if @resultYear = @inserviceYear begin + --handle first year + --set @result = (@firstYearMonths / 12.0) * @yearlyAmount + return (@firstYearMonths / 12.0) * @yearlyAmount +end + + +if @resultYear = @inserviceYear + @usefulLife begin + --handle last year + --set @result = (@lastYearMonths / 12.0) * @yearlyAmount + return (@lastYearMonths / 12.0) * @yearlyAmount +end + +return @yearlyAmount + +end +GO + + +--------------------------------------------- + +-- dbo.GetDirectoryCacheName +CREATE function [dbo].[GetDirectoryCacheName](@plantypeguid as uniqueidentifier) + returns nvarchar(max) +as +begin + declare @plantypename nvarchar(128) + declare @tablename nvarchar(max) + + set @plantypename = (select name from PlanType where PlanTypeGUID=@planTypeGUID) + set @tablename = 'data.DirectoryCache_' + replace(replace(replace(@plantypename, ' ', ''), '-', ''), '.', '') + + return @tablename +end +GO + + +--------------------------------------------- + +-- dbo.GetEscapedString +CREATE function [dbo].[GetEscapedString] ( + @expression varchar(max) + ) +returns varchar(max) +AS +BEGIN + declare @ret varchar(max); + set @ret = replace(replace(replace(replace(replace(@expression,'''',''),']',''),'[',''),'(',''),')',''); + return @ret; +END +GO + + +--------------------------------------------- + +-- dbo.GetEventVersion +create FUNCTION [dbo].[GetEventVersion]( + @EventName varchar(64) + ) +RETURNS varbinary(8) +AS +BEGIN + declare @ret timestamp + select @ret = version from event where eventname = @eventname + if @ret is null set @ret = 0 + return @ret +end +GO + + +--------------------------------------------- + +-- dbo.GetFillinMembersPastMaxIndex +CREATE FUNCTION [dbo].[GetFillinMembersPastMaxIndex] + (@modelGUID uniqueidentifier, @placeholderDimensionGUID uniqueidentifier, @maxIndex int) +RETURNS + @fillInMemberGUIDS TABLE ( guid uniqueidentifier) +AS +BEGIN + + --declare @modelGUID uniqueidentifier + --declare @structureDimensionGUID as uniqueidentifier --ph + + --declare @maxIndex int + --set @structureDimensionGUID = '17FEAA4B-A2A2-4353-B081-03E3DFB5CB77' + --set @modelGUID = '9C5BFBD1-4DF4-4223-B4C3-D013809261AC' + + ----select dbo.getModelFirstFillIn(@modelguid, @structuredimensionguid) + --set @maxIndex = 1 + --declare @minIndex int + +--delete fillins past index @maxIndex + + insert into @fillinMemberGUIDs + select + FilledInMemberGUID + FROM + ( + select + --modelguid,dbo.getplanname(modelguid), + row_number() over (order by slm.sortorderfullpath) as RowNum, + FilledInMemberGUID + from + EMFFillIn fi + inner join securelistmember slm on fi.PlaceholderMemberGUID = slm.listmemberguid + where + PlaceholderMemberGUID in + ( select slm.listmemberguid + from securelistmember slm + where slm.listguid = @placeholderDimensionGUID + ) + and ModelGUID = @modelGUID + ) FillIns + WHERE + RowNum > @MaxIndex + + + + + RETURN +END +GO + + +--------------------------------------------- + +-- dbo.GetFiscalDate +CREATE FUNCTION [dbo].[GetFiscalDate]( + @NonFiscalDate datetime + ) +RETURNS DATETIME--Returns 0 if column does not exist. Returns 1 if column exists. +AS +BEGIN +--See if the Table already contains the column. + + + declare @yeday varchar(2) + select @yeday = setting from dbsetting where name = 'GENERAL_FISCALYEARENDDAY' + declare @yemonth varchar(2) + select @yemonth = setting from dbsetting where name = 'GENERAL_FISCALYEARENDMONTH' + + --set @yemonth = '04' + --set @yeday = '30' + + declare @yedate datetime + set @yedate = @yemonth + '/' + @yeday + '/' + cast(year(@NonFiscalDate) as varchar(4)) + + + if datediff(dd, @yedate, @NonFiscalDate) > = 1 begin + return dateadd(yy,1,@NonFiscalDate) + end else begin + return @NonFiscalDate + end + + --needed because functions are weird + return @NonFiscalDate +end + +--Table does not contain the column. +GO + + +--------------------------------------------- + +-- dbo.GetFiscalDateNow +create function dbo.GetFiscalDateNow() +RETURNS DATETIME as begin +return dbo.getfiscaldate(getdate()) +end +GO + + +--------------------------------------------- + +-- dbo.GetFiscalStartMonth +CREATE FUNCTION dbo.GetFiscalStartMonth() +RETURNS int +AS +BEGIN + + DECLARE @fiscalYearEndMonth INT; + DECLARE @fiscalYearStartMonth INT; + + SET @fiscalYearEndMonth = CAST(dbo.GetDBSetting('GENERAL_FISCALYEARENDMONTH') AS INT); + + IF @fiscalYearEndMonth = 12 + BEGIN + SET @fiscalYearStartMonth = 1; + END + ELSE + BEGIN + SET @fiscalYearStartMonth = @fiscalYearEndMonth + 1; + END + + RETURN @fiscalYearStartMonth + +END; +GO + + +--------------------------------------------- + +-- dbo.GetFiscalYearEndDate +CREATE FUNCTION dbo.GetFiscalYearEndDate() + RETURNS Date +AS +BEGIN + + DECLARE @EndDate DATE; + + SET @EndDate = CONVERT(DATE, dbo.GetCurrentFiscalYear() + '/'+ dbo.GetDBSetting('GENERAL_FISCALYEARENDMONTH') + '/' +dbo.GetDBSetting('GENERAL_FISCALYEARENDDAY') ); + + RETURN @EndDate + +END; +GO + + +--------------------------------------------- + +-- dbo.GetFiscalYearForDate +CREATE FUNCTION [dbo].[GetFiscalYearForDate](@TestDate datetime) + +RETURNS int +AS +BEGIN + + declare @yeday varchar(2) + select @yeday = setting from dbsetting where name = 'GENERAL_FISCALYEARENDDAY' + declare @yemonth varchar(2) + select @yemonth = setting from dbsetting where name = 'GENERAL_FISCALYEARENDMONTH' + + declare @FiscalYear int + + set @FiscalYear = (Select + (CASE WHEN (DATEPART(month, @TestDate) = @yemonth) THEN + (CASE WHEN (DATEPART(day, @TestDate) > @yeday) + THEN (DATEPART(year, @TestDate) + 1) + ELSE (DATEPART(year, @TestDate)) END) + ELSE (CASE WHEN (DATEPART(month, @TestDate) + > @yemonth) THEN (DATEPART(year, @TestDate) + 1) ELSE (DATEPART(year, @TestDate)) END) END) AS FiscalYear) + + return @FiscalYear + +END +GO + + +--------------------------------------------- + +-- dbo.GetFiscalYearStartDate +CREATE FUNCTION dbo.GetFiscalYearStartDate() + RETURNS Date +AS +BEGIN + + DECLARE @StartDate DATE; + + SET @StartDate = DATEADD(DAY, 1, DATEADD(YEAR, -1, dbo.GetFiscalYearEndDate())); + + RETURN @StartDate + +END; +GO + + +--------------------------------------------- + +-- dbo.GetFolderFullPath +create function GetFolderFullPath(@folderguid as uniqueidentifier) + returns nvarchar(max) +as +begin + --declare @folderguid uniqueidentifier + --set @folderguid = '2DF3FEF0-A8BE-4975-95AE-8A88821D691B' + + declare @parentfolderguid uniqueidentifier + declare @folderfound bit + declare @fullpath nvarchar(max) + + select @fullpath = name, @folderfound = 1, @parentfolderguid = parentfolderguid from folder where folderguid = @folderguid + + declare @currentfoldername nvarchar(450) + + while @folderfound = 1 begin + set @folderfound = 0 + select @currentfoldername = name, @folderfound = 1, @parentfolderguid = parentfolderguid from folder where folderguid = @parentfolderguid + + if @folderfound = 1 begin + set @fullpath = @currentfoldername + '\' + @fullpath + end + end + + return @fullpath +end +GO + + +--------------------------------------------- + +-- dbo.GetFolderFullPathGUID +create function [dbo].[GetFolderFullPathGUID](@folderguid as uniqueidentifier) + returns nvarchar(max) +as +begin + --declare @folderguid uniqueidentifier + --set @folderguid = '2DF3FEF0-A8BE-4975-95AE-8A88821D691B' + + declare @parentfolderguid uniqueidentifier + declare @folderfound bit + declare @fullpath nvarchar(max) + + select @fullpath = cast(folderguid as varchar(36)), @folderfound = 1, @parentfolderguid = parentfolderguid from folder where folderguid = @folderguid + + declare @currentfoldername varchar(36) + + while @folderfound = 1 begin + set @folderfound = 0 + select @currentfoldername = cast(folderguid as varchar(36)), @folderfound = 1, @parentfolderguid = parentfolderguid from folder where folderguid = @parentfolderguid + + if @folderfound = 1 begin + set @fullpath = @currentfoldername + '\' + @fullpath + end + end + + return @fullpath +end +GO + + +--------------------------------------------- + +-- dbo.GetFolderGUID +CREATE function [dbo].[GetFolderGUID](@fullpath as nvarchar(max)) + returns uniqueidentifier +as +begin + + declare @folderguid As uniqueidentifier + + set @folderguid = (select folderguid from folder where dbo.getfolderfullpath(folderguid) = cast('CHW\' + Left(@fullpath,Len(@fullpath) - 1) as nvarchar(Max))) + + If (@folderguid is null) + set @folderguid = '00000000-0000-0000-0000-000000000000' + + return @folderguid + +end +GO + + +--------------------------------------------- + +-- dbo.GetFolderName +Create function [dbo].[GetFolderName](@folderguid as uniqueidentifier) + returns nvarchar(450) +as +begin + + declare @foldername As nvarchar(450) + + set @foldername = (select name from folder where folderguid = @folderguid) + + return @foldername + +end +GO + + +--------------------------------------------- + +-- dbo.GetFolderSortorderFullPath +CREATE function [dbo].[GetFolderSortorderFullPath](@folderguid as uniqueidentifier) + returns nvarchar(max) +as +begin +/* + select dbo.GetFolderSortorderFullPath(folderguid),* from folder where foldersetguid = 'BFB042E0-119C-4CFB-9C65-787275EEDB93' order by dbo.[GetFolderSortorderFullPath](folderguid) +*/ + --declare @folderguid uniqueidentifier + --set @folderguid = '2DF3FEF0-A8BE-4975-95AE-8A88821D691B' + + declare @parentfolderguid uniqueidentifier + declare @folderfound bit + declare @fullpath nvarchar(max) + + select @fullpath = replace(space(10 - len(cast(displayorder as varchar(max)))) + cast(displayorder as varchar(max)),' ','0'), @folderfound = 1, @parentfolderguid = parentfolderguid from folder where folderguid = @folderguid + + declare @currentfoldername nvarchar(450) + + while @folderfound = 1 begin + set @folderfound = 0 + select @currentfoldername = replace(space(10 - len(cast(displayorder as varchar(max)))) + cast(displayorder as varchar(max)),' ','0'), @folderfound = 1, @parentfolderguid = parentfolderguid from folder where folderguid = @parentfolderguid + + if @folderfound = 1 begin + set @fullpath = @currentfoldername + '\' + @fullpath + end + end + + return @fullpath +end + + +--select replace(space(5 - len(cast(displayorder as varchar(max)))) + cast(displayorder as varchar(max)),' ','0') from folder +GO + + +--------------------------------------------- + +-- dbo.GetFoldersRecursive +CREATE FUNCTION [dbo].[GetFoldersRecursive] + (@folderguid uniqueidentifier) +RETURNS + @folderguids TABLE ( guid uniqueidentifier) +AS +BEGIN +/* + select * from dbo.GetFoldersRecursive('2F4DEF7F-26F4-41AD-9A6E-8570A3AE78B9') +*/ + DECLARE @ISDELETED bit + SELECT @ISDELETED = COALESCE(ISDELETEDFOLDER, CAST(0 AS BIT)) FROM FOLDER WHERE FOLDERGUID = @folderguid + + INSERT INTO @folderguids + SELECT FOLDERGUID FROM FOLDER WHERE FOLDERGUID = @folderguid + + WHILE @@ROWCOUNT > 0 BEGIN + INSERT INTO @folderguids + SELECT FOLDERGUID FROM FOLDER WHERE ISDELETEDFOLDER = @ISDELETED AND PARENTFOLDERGUID IN (select guid from @folderguids) AND NOT FOLDERGUID IN (select guid from @folderguids) + END + + RETURN +END +GO + + +--------------------------------------------- + +-- dbo.GetFormFieldGUID +CREATE function [dbo].[GetFormFieldGUID](@aFormFieldName as nvarchar(64)) returns uniqueidentifier +as +BEGIN + declare @ret as uniqueidentifier + select top 1 @ret = formfieldguid from feformfield where name like @aFormFieldName + return @ret +END +GO + + +--------------------------------------------- + +-- dbo.GetFormFieldTypeColumn +CREATE function [dbo].[GetFormFieldTypeColumn](@aFormFieldType as int) returns varchar(64) +as +BEGIN + declare @ret as varchar(64) + + select @ret = case + when @aFormFieldType = 1 then 'ValueFloat' + when @aFormFieldType = 2 then 'ValueFloat' + when @aFormFieldType = 3 then 'ValueFloat' + when @aFormFieldType = 5 then 'ValueDate' + when @aFormFieldType = 12 then 'ValueBit' + when @aFormFieldType = 15 then 'ValueBit' + else 'ValueVarChar' end + + return @ret +END +GO + + +--------------------------------------------- + +-- dbo.GetFormFieldValue +CREATE function [dbo].[GetFormFieldValue](@aFormFieldGUID as uniqueidentifier, @aPlanGUID as uniqueidentifier) returns varchar(Max) +as +BEGIN + declare @ret as varchar(Max) + select top 1 @ret = valuevarchar from feformdata where feformdata.entityguid = @aPlanGUID AND formfieldguid = @aFormFieldGUID + return @ret +END +GO + + +--------------------------------------------- + +-- dbo.GetHangfireApiEndpoint +CREATE + + FUNCTION [dbo].[GetHangfireApiEndpoint]() + RETURNS varchar(200) + AS + BEGIN + + DECLARE @domain nvarchar(100); + + SELECT @domain = [ds].[Setting] + FROM [dbo].[DBSetting] AS [ds] + WHERE [ds].[Name] = 'SECURITY_TA_IMPERSONATE_DOMAIN'; + + + ------- Declare the return variable here + DECLARE @smc varchar(50), + @appVersion varchar(20); + + SELECT @smc = [Setting] + FROM [dbo].[DBSetting] + WHERE [Name] = 'SMC_PRIMARY_DATABASE'; + + SELECT @appVersion = REPLACE([ds].[Setting], '.', '') + FROM [dbo].[DBSetting] AS [ds] + WHERE [ds].[Name] = 'GENERAL_APPVERSION'; + + + IF @domain IS NOT NULL AND @domain = 'strataeudev' + BEGIN + RETURN 'https://deuw1websrv-01.ad.strataeudev.net/HangfireManagement' + @appVersion + '/api'; + END; + + + DECLARE @apiEnpoint varchar(100); + + SELECT @apiEnpoint = CASE @smc + WHEN 'smc dev' THEN 'https://hangfire-dev.sdt.local/HangfireManagement' + WHEN 'smc qa' THEN 'https://qoakwebsrv01.sdt.local/HangfireManagement' + WHEN 'smc training' THEN 'https://noakwebsrv01.sdt.local/HangfireManagement' + WHEN 'smc prod' THEN 'https://hangfire-prod.sdt.local/HangfireManagement' + WHEN 'smc dr' THEN 'https://hangfire-dr.sdt.local/HangfireManagement' + ELSE '' + END; + + RETURN @apiEnpoint + @appVersion + '/api'; + + END; +GO + + +--------------------------------------------- + +-- dbo.GetHashedPassword +CREATE function [dbo].[GetHashedPassword](@userguid as uniqueidentifier, @pw as varchar(max)) returns varchar(max) +as +BEGIN + declare @ret as varchar(max) + + declare @converter as xml + set @ret = @pw + lower(cast(@userguid as varchar(36))) + 'Strata Decision Technology SDT' + + + declare @i int + set @i = 0 + + while @i <100001 begin + set @converter = (SELECT HASHBYTES('SHA1',@ret) as "T" FOR XML RAW, BINARY BASE64, TYPE) + select @ret = @converter.value('row[1]/@T', 'varchar(max)') + set @i = @i + 1 + end + + + + + return @ret +END +GO + + +--------------------------------------------- + +-- dbo.GetImageColumnHTML +CREATE FUNCTION dbo.GetImageColumnHTML +( + @imgurl varchar(128), + @value varchar(64) +) +RETURNS varchar(400) +AS +BEGIN + declare @result varchar(400) + + select @result = '
' + @value + '
' + + return @result + +END +GO + + +--------------------------------------------- + +-- dbo.GetInsertCommandForDataDictionaryFieldValueExample +-- ============================================= +-- Author: Yaroslav Dembitskyi +-- Create date: 7/20/2017 +-- Description: Generates insert command for score item to populate DataDictionary +-- ============================================= +CREATE FUNCTION [dbo].[GetInsertCommandForDataDictionaryFieldValueExample] +( + @scoreGuid uniqueidentifier, + @columnName nvarchar(128), + @schemaName nvarchar(128), + @objectName nvarchar(128), + @columnType tinyint, + @idColumnName nvarchar(128) = null +) +RETURNS nvarchar(max) +AS +BEGIN + if([dbo].ColumnExists(@schemaName, @objectName, @columnName) = 0) + BEGIN + return '' + END + + declare @result nvarchar(max) + declare @fromWhereClause nvarchar(max) = ' from [' + @schemaName + '].[' + @objectName + '] where CONVERT(NVARCHAR(4000),[' + @columnName + ']) <> '''' ' + declare @scoreGuidAsText nvarchar(50) = CONVERT(NVARCHAR(50), @scoreGuid) + if(@idColumnName is not null AND [dbo].ColumnExists(@schemaName, @objectName, @idColumnName) = 1 AND + (select DATA_TYPE from INFORMATION_SCHEMA.COLUMNS IC where TABLE_NAME = @objectName and TABLE_SCHEMA=@schemaName and COLUMN_NAME = @idColumnName) like '%int') + BEGIN + set @fromWhereClause = @fromWhereClause + ' and [' + @idColumnName + '] <> 0 ' + END + IF(TYPE_NAME(@columnType) = 'bit') + BEGIN + set @result = 'insert into [dbo].[DataDictionaryFieldValueExample] (ScoreGUID, ExampleValue) values (''' + @scoreGuidAsText + ''', ''True/False'')' + END + ELSE IF (TYPE_NAME(@columnType) = 'datetime' OR TYPE_NAME(@columnType) = 'datetime2' OR TYPE_NAME(@columnType) = 'smalldatetime') + BEGIN + set @result = 'insert into [dbo].[DataDictionaryFieldValueExample] (ScoreGUID, ExampleValue) select top 1 ''' + @scoreGuidAsText + ''', + CONVERT(CHAR(10), ['+ @columnName + '], 103) + SUBSTRING(CONVERT(varchar, [' + @columnName + '], 0),12, 8) ' + @fromWhereClause + END + ELSE + BEGIN + set @result = 'insert into [dbo].[DataDictionaryFieldValueExample] (ScoreGUID, ExampleValue) select top 1 ''' + @scoreGuidAsText + ''', + CONVERT(NVARCHAR(4000),['+ @columnName + '])' + @fromWhereClause + END + return @result +END +GO + + +--------------------------------------------- + +-- dbo.GetLastFiscalYearEndDate +CREATE FUNCTION dbo.GetLastFiscalYearEndDate() + RETURNS Date +AS +BEGIN + + DECLARE @EndDate DATE; + DECLARE @CurrentFiscalYearEndDate DATE; + + SET @CurrentFiscalYearEndDate = CONVERT(DATE, dbo.GetCurrentFiscalYear() + '/'+ dbo.GetDBSetting('GENERAL_FISCALYEARENDMONTH') + '/' +dbo.GetDBSetting('GENERAL_FISCALYEARENDDAY') ); + SET @EndDate = DATEADD(YEAR, -1, @CurrentFiscalYearEndDate); + + RETURN @EndDate + +END; +GO + + +--------------------------------------------- + +-- dbo.GetLastFiscalYearStartDate +CREATE FUNCTION dbo.GetLastFiscalYearStartDate() + RETURNS Date +AS +BEGIN + + DECLARE @StartDate DATE; + + SET @StartDate = DATEADD(DAY, 1, DATEADD(YEAR, -1, dbo.GetLastFiscalYearEndDate())); + + RETURN @StartDate + +END; +GO + + +--------------------------------------------- + +-- dbo.GetLinkedServerDefinition +CREATE FUNCTION [dbo].[GetLinkedServerDefinition]() +returns nvarchar(512) +AS +BEGIN + + declare @retval nvarchar(512) + select @retval = '[' + @@ServerName + '].[' + db_Name() + ']' + return @retval +END +GO + + +--------------------------------------------- + +-- dbo.GetMainFolderSetGUID +create function GetMainFolderSetGUID() returns uniqueidentifier +as +BEGIN + declare @ret as uniqueidentifier + select @ret = foldersetguid from folderset where type = 1 + return @ret +END +GO + + +--------------------------------------------- + +-- dbo.GetModelDependencyTree +CREATE FUNCTION [dbo].[GetModelDependencyTree] + (@ModelGUID uniqueidentifier, @MaxRecursionLevel int) +RETURNS + @ModelTree TABLE ( [ModelGUID] uniqueidentifier, [Level] int) +AS +BEGIN + + declare @Level int; + declare @Counter int; + set @Level = 0; + set @Counter = 1; + + declare @Models TABLE + ( + ModelGUID uniqueidentifier, + ParentModelGUID uniqueidentifier, + [Level] int, + unique clustered (ModelGUID, ParentModelGUID, [Level]) + ) + declare @UsedParents TABLE + ( + ModelGUID uniqueidentifier primary key clustered + ) + + --Base Query + insert into @Models select @ModelGUID, @ModelGUID, @Level; + insert into @UsedParents select @ModelGUID + + set @Level=@Level+1; + + insert into @Models + select distinct ModelGUID, ParentModelGUID, @Level from dbo.viewModelDependencies + where ParentModelGUID = @ModelGUID and ModelGUID <> @ModelGUID + + -- Begin Recursion + WHILE @@ROWCOUNT > 0 + BEGIN + --handle max recursion + if (@Counter > @MaxRecursionLevel) + BEGIN + BREAK; + END + + --update state + set @Level = @Level + 1; + insert into @UsedParents + select distinct M.ModelGUID from @Models M + where not exists(select 1 from @UsedParents where ModelGUID = M.ModelGUID) and M.MODELGUID <> null + + --recursive query + insert into @Models + select DISTINCT NEW.ModelGUID, NEW.ParentModelGUID, @Level from viewModelDependencies NEW + left join @Models OLD on OLD.ModelGUID = NEW.ParentModelGUID + where not exists (select 1 from @UsedParents where ModelGUID = NEW.ParentModelGUID) + and NEW.ModelGUID <> NEW.ParentModelGUID and OLD.MODELGUID <> null + + set @Counter = @Counter + 1; + END + + insert into @ModelTree select distinct ModelGUID, [Level] from @Models order by [Level] DESC + + return +END +GO + + +--------------------------------------------- + +-- dbo.GetModelFirstFillIn +CREATE function [dbo].[GetModelFirstFillIn](@modelGUID as uniqueidentifier, @structureDimensionGUID as uniqueidentifier) + returns uniqueidentifier +as +begin + +/* +declare @modelGUID uniqueidentifier +declare @structureDimensionGUID as uniqueidentifier --ph + +declare @maxIndex int +set @structureDimensionGUID = '17FEAA4B-A2A2-4353-B081-03E3DFB5CB77' +set @modelGUID = '9C5BFBD1-4DF4-4223-B4C3-D013809261AC' + +select dbo.getModelFirstFillIn(@modelguid, @structuredimensionguid) +*/ + +--delete fillins past index @maxIndex + declare @out uniqueidentifier + select top 1 + @out = FilledInMemberGUID + FROM + ( + select + --modelguid,dbo.getplanname(modelguid), + row_number() over (order by slm.sortorderfullpath) as RowNum, + FilledInMemberGUID + from + EMFFillIn fi + inner join securelistmember slm on fi.PlaceholderMemberGUID = slm.listmemberguid + where + ( + PlaceholderMemberGUID in + ( select listmemberguid + from securelistmember + where listguid = @structureDimensionGUID + ) or + FilledInMemberGUID in + ( select listmemberguid + from securelistmember + where listguid = @structureDimensionGUID + ) + ) + and ModelGUID = @modelGUID + ) FillIns + ORDER BY RowNum + + if @out is null set @out = '00000000-0000-0000-0000-000000000000' + + return @out +end +GO + + +--------------------------------------------- + +-- dbo.GetModelFirstFillInSection +create function [dbo].[GetModelFirstFillInSection](@modelGUID as uniqueidentifier, @PHSectionGUID as uniqueidentifier) + returns uniqueidentifier +as +begin + +/* +declare @modelGUID uniqueidentifier +declare @structureDimensionGUID as uniqueidentifier --ph + +declare @maxIndex int +set @structureDimensionGUID = '17FEAA4B-A2A2-4353-B081-03E3DFB5CB77' +set @modelGUID = '9C5BFBD1-4DF4-4223-B4C3-D013809261AC' + +select dbo.getModelFirstFillIn(@modelguid, @structuredimensionguid) +*/ + +--delete fillins past index @maxIndex + declare @out uniqueidentifier + select top 1 + @out = FilledInMemberGUID + FROM + ( + select + --modelguid,dbo.getplanname(modelguid), + row_number() over (order by slm.sortorderfullpath) as RowNum, + FilledInMemberGUID + from + EMFFillIn fi + inner join securelistmember slm on fi.PlaceholderMemberGUID = slm.listmemberguid + where + ( + PlaceholderMemberGUID in + ( select listmemberguid + from securelistmember + where parentlistmemberguid = @PHSectionGUID + + ) + --FilledInMemberGUID in + -- ( select listmemberguid + -- from securelistmember + -- where listguid = @structureDimensionGUID + -- ) + ) + and ModelGUID = @modelGUID + ) FillIns + ORDER BY RowNum + + if @out is null set @out = '00000000-0000-0000-0000-000000000000' + + return @out +end +GO + + +--------------------------------------------- + +-- dbo.GetModelLastFillInIndex +CREATE function [dbo].[GetModelLastFillInIndex](@modelGUID as uniqueidentifier, @structureDimensionGUID as uniqueidentifier) + returns bigint +as +begin + +/* +declare @modelGUID uniqueidentifier +declare @structureDimensionGUID as uniqueidentifier --ph + +declare @maxIndex int +set @structureDimensionGUID = '17FEAA4B-A2A2-4353-B081-03E3DFB5CB77' +set @modelGUID = '9C5BFBD1-4DF4-4223-B4C3-D013809261AC' + +select dbo.getModelFirstFillIn(@modelguid, @structuredimensionguid) +*/ + +--delete fillins past index @maxIndex + declare @out bigint + select top 1 + @out = RowNum -1 + FROM + ( + select + --modelguid,dbo.getplanname(modelguid), + row_number() over (order by slm.sortorderfullpath) as RowNum, + FilledInMemberGUID + from + EMFFillIn fi + inner join securelistmember slm on fi.PlaceholderMemberGUID = slm.listmemberguid + where + PlaceholderMemberGUID in + ( select slm.listmemberguid + from securelistmember slm + where slm.listguid = @structureDimensionGUID + ) + and ModelGUID = @modelGUID + ) FillIns + ORDER BY RowNum desc + + if @out is null set @out = 0 + + return @out +end +GO + + +--------------------------------------------- + +-- dbo.GetModelLastFillInIndexSection +CREATE function [dbo].[GetModelLastFillInIndexSection](@modelGUID as uniqueidentifier, @SectionmemberGUID as uniqueidentifier) + returns bigint +as +begin + + +/* +declare @modelGUID uniqueidentifier +declare @structureDimensionGUID as uniqueidentifier --ph + +declare @maxIndex int +set @structureDimensionGUID = '17FEAA4B-A2A2-4353-B081-03E3DFB5CB77' +set @modelGUID = '9C5BFBD1-4DF4-4223-B4C3-D013809261AC' + +select dbo.getModelFirstFillIn(@modelguid, @structuredimensionguid) +*/ + +--delete fillins past index @maxIndex + declare @out bigint + + select + @out = count(*) -1 + from + EMFFillIn fi + inner join securelistmember slm on fi.PlaceholderMemberGUID = slm.listmemberguid + where + slm.parentlistmemberguid = @SectionmemberGUID + and ModelGUID = @modelGUID + + if @out is null set @out = 0 + + return @out +end +GO + + +--------------------------------------------- + +-- dbo.GetPlanGUID +CREATE function [dbo].[GetPlanGUID](@aPlanName as nvarchar(max)) returns uniqueidentifier +as +BEGIN + declare @ret as uniqueidentifier + select top 1 @ret = planguid from xplan where dbo.getplanname(planguid) like @aPlanName + return @ret +END +GO + + +--------------------------------------------- + +-- dbo.GetPlanLastModified +CREATE function [dbo].[GetPlanLastModified](@PLANGUID as uniqueidentifier) returns nvarchar(450) +as +BEGIN + declare @ret as nvarchar(450) + + SELECT @ret = CONVERT(VARCHAR(10), coalesce((select MAX(datetimestamp) from HistoryItem (readuncommitted) where OBJECTGUID = @planguid), '2000-01-01 12:00:00.000'), 101) + + if(@ret = '2000-01-01 12:00:00.000') begin + set @ret = '' + end + + return @ret +END +GO + + +--------------------------------------------- + +-- dbo.GetPlanName +CREATE function [dbo].[GetPlanName](@PLANGUID as uniqueidentifier) returns nvarchar(450) +as +BEGIN + declare @ret as nvarchar(450) + + SELECT @ret = Name FROM XPlan (readuncommitted) WHERE PlanGUID = @PLANGUID + + return @ret +END +GO + + +--------------------------------------------- + +-- dbo.GetSQLColumnFullType +CREATE FUNCTION [dbo].[GetSQLColumnFullType] +( + @type_id int, + @maxlength int, + @scale int, + @precision int +) +RETURNS nvarchar(128) +AS +BEGIN + DECLARE @typeToReturn nvarchar(128) = TYPE_NAME(@type_id) + IF @typeToReturn = 'char'OR @typeToReturn ='varchar' OR @typeToReturn = 'binary' OR @typeToReturn = 'varbinary' + BEGIN + SET @typeToReturn = @typeToReturn + '(' + case @maxlength when -1 then 'max' else cast(@maxlength as nvarchar(10)) end + ')' + END + ELSE IF @typeToReturn = 'nchar'OR @typeToReturn ='nvarchar' OR @typeToReturn = 'nbinary' OR @typeToReturn = 'nvarbinary' + BEGIN + SET @typeToReturn = @typeToReturn + '(' + case @maxlength when -1 then 'max' else cast(@maxlength / 2 as nvarchar(10)) end + ')' + END + ELSE IF @typeToReturn = 'decimal' or @typeToReturn = 'numeric' + BEGIN + SET @typeToReturn = @typeToReturn + '(' + cast(@scale as nvarchar(10)) + ', ' + cast(@precision as nvarchar(10)) + ')' + END + + RETURN @typeToReturn; +END +GO + + +--------------------------------------------- + +-- dbo.GetSQLColumnSafeGuid +CREATE FUNCTION [dbo].[GetSQLColumnSafeGuid] (@guid uniqueidentifier) RETURNS varchar(37) +AS +BEGIN + DECLARE @tmpstr varchar(37) + + SELECT @tmpstr = upper(cast(@guid as varchar(37))) + SELECT @tmpstr = replace(@tmpstr, '-', '_') + SELECT @tmpstr = 'G' + @tmpstr + + RETURN @tmpstr +END +GO + + +--------------------------------------------- + +-- dbo.GetSQLFullyQualifiedType +CREATE FUNCTION dbo.GetSQLFullyQualifiedType +( + @type_id int, + @maxlength int, + @scale int, + @precision int +) +RETURNS nvarchar(128) +AS +BEGIN + DECLARE @typeToReturn nvarchar(128); + select @typeToReturn = TYPE_NAME(@type_id); + + IF @typeToReturn like '%varchar%' + BEGIN + SET @typeToReturn = @typeToReturn + '(' + cast(@maxlength as nvarchar(10)) + ')' + END + ELSE IF @typeToReturn like '%decimal%' + BEGIN + SET @typeToReturn = @typeToReturn + '(' + cast(@scale as nvarchar(10)) + ',' + cast(@precision as nvarchar(10)) + ')' + END + + RETURN @typeToReturn; +END +GO + + +--------------------------------------------- + +-- dbo.GetSQLTableExpression +CREATE FUNCTION [dbo].[GetSQLTableExpression]( + @SchemaName nvarchar(128), + @ObjectName nvarchar(Max) +) +RETURNS varchar(max) +AS +BEGIN + + declare @SchemaExp varchar(max); + declare @ObjectExp varchar(max); + declare @returnval varchar(max) + + set @SchemaExp = ''; + set @ObjectExp = ''; + + --Build Schema Expression + if (SUBSTRING(@SchemaName,1,1) <> '[') + set @SchemaExp = '[' + + set @SchemaExp = @SchemaExp + @SchemaName; + + if (SUBSTRING(@SchemaName,LEN(@SchemaName),1) <> ']') + set @SchemaExp = @SchemaExp + ']'; + + --Build Object Expression + if (SUBSTRING(@ObjectName,1,1) <> '[') + set @ObjectExp = '[' + + set @ObjectExp = @ObjectExp + @ObjectName; + + if (SUBSTRING(@ObjectName,LEN(@ObjectName),1) <> ']') + set @ObjectExp = @ObjectExp + ']'; + + --Combine + select @returnval = @SchemaExp + '.' + @ObjectExp; + return @returnval; +END +GO + + +--------------------------------------------- + +-- dbo.GetScoreLootRefreshTriggerName +CREATE Function [dbo].[GetScoreLootRefreshTriggerName]( + @aDimensionGUID uniqueidentifier +) +returns varchar(max) +AS +BEGIN + declare @TriggerName varchar(max); + set @TriggerName = 'trg_ScoreDimension_' + Replace(cast(@aDimensionGUID as varchar(64)),'-','') + '_LootRefresh'; + return @TriggerName; +END +GO + + +--------------------------------------------- + +-- dbo.GetSecureListMemberFullPath +create function [dbo].[GetSecureListMemberFullPath](@listmemberguid as uniqueidentifier) + returns nvarchar(max) +as +begin + --declare @listmemberguid uniqueidentifier + --set @listmemberguid = '2DF3FEF0-A8BE-4975-95AE-8A88821D691B' + + declare @parentlistmemberguid uniqueidentifier declare @SecureListMemberfound bit + declare @fullpath nvarchar(max) + + select @fullpath = name, @SecureListMemberfound = 1, @parentlistmemberguid = parentlistmemberguid from SecureListMember where listmemberguid = @listmemberguid + + declare @currentSecureListMembername nvarchar(450) + + while @SecureListMemberfound = 1 begin + set @SecureListMemberfound = 0 + select @currentSecureListMembername = name, @SecureListMemberfound = 1, @parentlistmemberguid = parentlistmemberguid from SecureListMember where listmemberguid = @parentlistmemberguid + + if @SecureListMemberfound = 1 begin + set @fullpath = @currentSecureListMembername + '\' + @fullpath + end + end + + return @fullpath +end +GO + + +--------------------------------------------- + +-- dbo.GetSecureListOffsetMember +CREATE function [dbo].[GetSecureListOffsetMember](@oldmemberguid as uniqueidentifier, @offset int) + returns uniqueidentifier +as +begin + --select * from securelist where name = 'year 20' +/* declare @oldmemberguid uniqueidentifier + declare @offset int + set @offset = 3 + set @oldmemberguid = 'B95F36CB-970B-4E44-8382-81A12F1D3C06' +*/ + + declare @dimensionguid uniqueidentifier + + select @dimensionguid = listguid + from securelistmember + where listmemberguid = @oldmemberguid + + declare @ret as uniqueidentifier + select + @ret = cast(coalesce(slmnew.listmemberguid, '11111111-1111-1111-1111-111111111111') as uniqueidentifier) + from + securelistmember slmOld + left join SecureListMember slmNew on slmOld.listguid = slmNew.listguid + and slmNew.displayorder = slmOld.displayorder + @offset + and slmnew.ParentListMemberGUID = slmold.ParentListMemberGUID + where + slmold.listmemberguid = @oldmemberguid + + if @ret is null set @ret = '11111111-1111-1111-1111-111111111111' + return @ret +end +GO + + +--------------------------------------------- + +-- dbo.GetSecureListSortorderFullPath +create function [dbo].[GetSecureListSortorderFullPath](@listmemberguid as uniqueidentifier) + returns nvarchar(max) +as +begin +/* + select dbo.GetSecureListSortorderFullPath(listmemberguid),* from folder order by dbo.[GetFolderSortorderFullPath](listmemberguid) +*/ + --declare @listmemberguid uniqueidentifier + --set @listmemberguid = '2DF3FEF0-A8BE-4975-95AE-8A88821D691B' + + declare @parentlistmemberguid uniqueidentifier + declare @folderfound bit + declare @fullpath nvarchar(max) + + select @fullpath = replace(space(10 - len(cast(displayorder as varchar(max)))) + cast(displayorder as varchar(max)),' ','0'), @folderfound = 1, @parentlistmemberguid = parentlistmemberguid from securelistmember where listmemberguid = @listmemberguid + + declare @currentfoldername nvarchar(450) + + while @folderfound = 1 begin + set @folderfound = 0 + select @currentfoldername = replace(space(10 - len(cast(displayorder as varchar(max)))) + cast(displayorder as varchar(max)),' ','0'), @folderfound = 1, @parentlistmemberguid = parentlistmemberguid from securelistmember where listmemberguid = @parentlistmemberguid + + if @folderfound = 1 begin + set @fullpath = @currentfoldername + '\' + @fullpath + end + end + + return @fullpath +end + + +--select replace(space(5 - len(cast(displayorder as varchar(max)))) + cast(displayorder as varchar(max)),' ','0') from folder +GO + + +--------------------------------------------- + +-- dbo.GetSecureListVersion +CREATE function [dbo].[GetSecureListVersion](@LISTGUID as uniqueidentifier) returns binary(8) +AS +BEGIN + declare @maxversion as binary(8) + declare @tempversion as binary(8) + + select @maxversion = max(l.version) + from securelist l where l.listguid = @LISTGUID; + + select @tempversion = max(lm.version) + from securelistmember lm where lm.listguid = @LISTGUID; + if(@tempversion > @maxversion) begin + SET @maxversion = @tempversion + end + + select @tempversion = max(lmv.version) + from securelistmembervalue lmv where lmv.listguid = @LISTGUID; + if(@tempversion > @maxversion) begin + SET @maxversion = @tempversion + end + + select @tempversion = max(ll.version) + from securelistlevel ll where ll.listguid = @LISTGUID; + if(@tempversion > @maxversion) begin + SET @maxversion = @tempversion + end + + select @tempversion = max(lp.version) + from securelistproperty lp where lp.listguid = @LISTGUID; + if(@tempversion > @maxversion) begin + SET @maxversion = @tempversion + end + + return @maxversion +END +GO + + +--------------------------------------------- + +-- dbo.GetSuperUserGUID +create function [dbo].[GetSuperUserGUID]() +RETURNS uniqueidentifier +AS +BEGIN + declare @val uniqueidentifier; + set @val = '10101010-1111-0000-1111-101010101010' + + return @val; +END +GO + + +--------------------------------------------- + +-- dbo.GetSystemSectionFullPath +CREATE function [dbo].[GetSystemSectionFullPath](@SystemSectionguid as uniqueidentifier) + returns nvarchar(max) +as +begin + --declare @SystemSectionguid uniqueidentifier + --set @SystemSectionguid = '2DF3FEF0-A8BE-4975-95AE-8A88821D691B' + + declare @parentSystemSectionguid uniqueidentifier + declare @SystemSectionfound bit + declare @fullpath nvarchar(max) + + select @fullpath = name, + @SystemSectionfound = 1, + @parentSystemSectionguid = parentguid + from SystemSection where SystemSectionguid = @SystemSectionguid + + declare @currentSystemSectionname nvarchar(450) + + while @SystemSectionfound = 1 begin + set @SystemSectionfound = 0 + select @currentSystemSectionname = name, @SystemSectionfound = 1, @parentSystemSectionguid = parentguid from SystemSection where SystemSectionguid = @parentSystemSectionguid + + if @SystemSectionfound = 1 and @currentSystemSectionname <> 'System' begin + set @fullpath = @currentSystemSectionname + '\' + @fullpath + end + end + + set @fullpath = replace(@fullpath,'~Tool_','') + set @fullpath = replace(@fullpath,'~Title_','') + set @fullpath = replace(@fullpath,'~Group_','') + set @fullpath = replace(@fullpath,'~Main_Generic','') + return @fullpath +end +GO + + +--------------------------------------------- + +-- dbo.GetTrueFalseString +create Function dbo.GetTrueFalseString( + @Bit bit + ) + returns nvarchar(10) +AS +BEGIN +declare @returnval nvarchar(10) +if (@Bit = 1) + begin + set @returnval = 'True' + end + else + begin + set @returnval = 'False' + end + return @returnval +END +GO + + +--------------------------------------------- + +-- dbo.GetUpdateCommandForDataDictionaryFieldValueExample +-- ============================================= +-- Author: Yaroslav Dembitskyi +-- Create date: 7/20/2017 +-- Description: Generates update command for score item to populate DataDictionary +-- ============================================= +CREATE FUNCTION [dbo].[GetUpdateCommandForDataDictionaryFieldValueExample] +( + @scoreGuid uniqueidentifier, + @columnName nvarchar(128), + @schemaName nvarchar(128), + @objectName nvarchar(128), + @columnType tinyint, + @idColumnName nvarchar(128) = null +) +RETURNS nvarchar(max) +AS +BEGIN + if([dbo].ColumnExists(@schemaName, @objectName, @columnName) = 0) + BEGIN + return '' + END + + declare @result nvarchar(max) + declare @valueToUpdateSelectQuery nvarchar(max) + declare @fromWhereClause nvarchar(max) = ' from [' + @schemaName + '].[' + @objectName + '] where CONVERT(NVARCHAR(4000),[' + @columnName + ']) <> '''' ' + declare @scoreGuidAsText nvarchar(50) = CONVERT(NVARCHAR(50), @scoreGuid) + if(@idColumnName is not null AND [dbo].ColumnExists(@schemaName, @objectName, @idColumnName) = 1 AND + (select DATA_TYPE from INFORMATION_SCHEMA.COLUMNS IC where TABLE_NAME = @objectName and TABLE_SCHEMA=@schemaName and COLUMN_NAME = @idColumnName) like '%int') + BEGIN + set @fromWhereClause = @fromWhereClause + ' and [' + @idColumnName + '] <> 0 ' + END + IF(TYPE_NAME(@columnType) = 'bit') + BEGIN + set @valueToUpdateSelectQuery = 'select ''True/False''' + END + ELSE IF (TYPE_NAME(@columnType) = 'datetime' OR TYPE_NAME(@columnType) = 'datetime2' OR TYPE_NAME(@columnType) = 'smalldatetime') + BEGIN + set @valueToUpdateSelectQuery = 'select top 1 CONVERT(CHAR(10), ['+ @columnName + '], 103) + SUBSTRING(CONVERT(varchar, [' + @columnName + '], 0),12, 8) ' + @fromWhereClause + END + ELSE + BEGIN + set @valueToUpdateSelectQuery = 'select top 1 CONVERT(NVARCHAR(4000), ['+ @columnName + '])' + @fromWhereClause + END + + set @result = 'if(exists(' + @valueToUpdateSelectQuery + ')) + update [dbo].[DataDictionaryFieldValueExample] set ExampleValue = (' + @valueToUpdateSelectQuery + ') where ScoreGUID = ''' + @scoreGuidAsText + ''' + else + delete from [dbo].[DataDictionaryFieldValueExample] where ScoreGUID = ''' + @scoreGuidAsText + '''' + + return @result +END +GO + + +--------------------------------------------- + +-- dbo.GetUserGUID +CREATE function GetUserGUID(@aUsername as nvarchar(max)) returns uniqueidentifier +as +BEGIN + declare @ret as uniqueidentifier + select top 1 @ret = userguid from userprofile where username like @ausername + return @ret +END +GO + + +--------------------------------------------- + +-- dbo.GetUserGroupGUID +CREATE function [dbo].[GetUserGroupGUID](@agroupname as nvarchar(max)) returns uniqueidentifier +as +BEGIN + declare @ret as uniqueidentifier + select top 1 @ret = usergroupguid from usergroup where name like @agroupname + return @ret +END +GO + + +--------------------------------------------- + +-- dbo.GetUserRoleAssignmentCSV +CREATE FUNCTION [dbo].[GetUserRoleAssignmentCSV] ( + @ENTITYGUID uniqueidentifier, + @ALIASGUIDLIST text, + @IDENTITYNAMES bit = 0 + ) + RETURNS NVARCHAR(MAX) +AS +BEGIN + DECLARE @tbl TABLE ( MemberGUID uniqueidentifier ) + DECLARE @ALIASGUID uniqueidentifier + + DECLARE crsAliases CURSOR LOCAL FAST_FORWARD FOR + SELECT GUID FROM dbo.ConvertCSGuidsToTable(@ALIASGUIDLIST, ',') + OPEN crsAliases + + FETCH NEXT FROM crsAliases INTO @ALIASGUID + WHILE @@FETCH_STATUS = 0 BEGIN + INSERT @tbl + + SELECT DISTINCT + RA.UserGUID + FROM + viewS3RoleAssignmentDetail RA + inner join UserRole R on R.RoleID = RA.RoleID + inner join XPlan P on P.CachedLootID = RA.LootID + WHERE + R.UserRoleGUID = @ALIASGUID + AND P.PlanGUID = @EntityGUID + + +/* SELECT DISTINCT + IDENTITYGUID + FROM + IdentityAlias + WHERE + ALIASGUID = @ALIASGUID + AND IDENTITYGUID NOT IN (SELECT IDENTITYGUID FROM @tbl) + AND ((ENTITYGUID = @ENTITYGUID) OR (ENTITYGUID = '00000000-0000-0000-0000-000000000000')) +*/ + FETCH NEXT FROM crsAliases INTO @ALIASGUID + + END + + CLOSE crsAliases + DEALLOCATE crsAliases + + DECLARE @csv NVARCHAR(MAX) + SET @csv = '' + + IF (@IDENTITYNAMES = 1) BEGIN + select @csv = @csv + namelast + ', ' + namefirst + '; ' from userprofile where userguid in(select memberguid from @tbl) + IF (len(@csv) > 1) BEGIN + select @csv = left(@csv, len(@csv) - 1) + END + END ELSE BEGIN + select @csv = @csv + cast(memberguid as varchar(36)) + ',' from @tbl + IF (len(@csv) > 1) BEGIN + select @csv = left(@csv, len(@csv) - 1) + END + END + + RETURN @csv +END +GO + + +--------------------------------------------- + +-- dbo.GetValidDimensionTupleXML +create function GetValidDimensionTupleXML(@tuplexml xml, @mdcguid uniqueidentifier) + returns xml +as begin + declare @goodtuplexml xml + + set @goodtuplexml = (select lower(cast(dimensionguid as varchar(36))) as DIMENSIONGUID from emfmodeldataconfigdimensionlink DIMENSIONALITY where modeldataconfigguid = @mdcguid for xml auto, elements) + + declare @combinedxml xml + set @combinedxml = '
' + cast(@tuplexml as varchar(max)) + cast(@goodtuplexml as varchar(max)) + '
' + + declare @goodmembers xml + + select @goodmembers = @combinedxml.query('//DIMENSIONTUPLEMEMBER[DIMENSIONGUID = //DIMENSIONALITY/DIMENSIONGUID]') + + declare @ots xml + select @ots = @tuplexml.query('/DIMENSIONTUPLE/OBJECTTYPESTRATA') + + declare @mg xml + select @mg = @tuplexml.query('/DIMENSIONTUPLE/MEASUREGUID') + + declare @goodxml xml + set @goodxml = '' + cast(@ots as varchar(max)) + cast(@mg as varchar(max)) + cast(@goodmembers as varchar(max)) + '' + + return @goodxml +end +GO + + +--------------------------------------------- + +-- dbo.GetViewUnderlyingTables +CREATE function [dbo].[GetViewUnderlyingTables](@ViewSchema varchar(128), @ViewName varchar(128)) +Returns Table +AS + return (select distinct(TABLE_NAME) TableName, TABLE_SCHEMA as TableSchema from INFORMATION_SCHEMA.VIEW_COLUMN_USAGE + where VIEW_SCHEMA = @ViewSchema AND VIEW_NAME = @ViewName); +GO + + +--------------------------------------------- + +-- dbo.GetWebSafeString +CREATE function [dbo].[GetWebSafeString](@input as nvarchar(max)) returns nvarchar(max) +as +BEGIN + declare @ret as nvarchar(max) + select @ret = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@input, '<', ''), '>', ''), '''', ''), '&', ''), '"', ''), '\', ''), '/', '') + return @ret +END +GO + + +--------------------------------------------- + +-- dbo.GetWebSafeStringFullTrim +CREATE function [dbo].[GetWebSafeStringFullTrim](@input as nvarchar(max)) returns nvarchar(max) +as +BEGIN + declare @ret as nvarchar(max) + select @ret = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@input, '<', ''), '>', ''), '''', ''), '&', ''), '"', ''), '\', ''), '/', ''), ' ', ' '))) + return @ret +END +GO + + +--------------------------------------------- + +-- dbo.GetZZModelDataTableName +create function GetZZModelDataTableName(@mdcguid uniqueidentifier) +returns varchar(max) +as begin + + return 'zzEMFModelData_' + replace(cast(@mdcguid as varchar(36)), '-','_') +end +GO + + +--------------------------------------------- + +-- dbo.GetZZModelDataViewName +CREATE function [dbo].[GetZZModelDataViewName](@mdcguid uniqueidentifier) + returns varchar(max) +as begin + declare @mdcName as nvarchar(64) + declare @ret as nvarchar(max) + + SELECT + @mdcName = Name + FROM + EMFModelDataConfig + WHERE + ModelDataConfigGUID = @mdcguid + + set @ret = replace(@mdcName, ' ', '') + set @ret = replace(@ret, '(', '') + set @ret = replace(@ret, ')', '') + + set @ret = 'zzviewModelData_' + @ret + + return @ret +end +GO + + +--------------------------------------------- + +-- dbo.GetZZModelTemplateMappingTableName +create function GetZZModelTemplateMappingTableName(@mdcguid uniqueidentifier) +returns varchar(max) +as begin + + return 'zzEMFModelTemplateMapping_' + replace(cast(@mdcguid as varchar(36)), '-','_') +end +GO + + +--------------------------------------------- + +-- dbo.GetZeroGUID +-- ============================================= +-- Author: +-- Create date: +-- Description: +-- ============================================= +CREATE FUNCTION [dbo].[GetZeroGUID] () +RETURNS uniqueidentifier +AS +BEGIN + -- Declare the return variable here + DECLARE @ZEROGUID uniqueidentifier + select @ZEROGUID = [dbo].[ZeroGUID](); + RETURN @ZEROGUID + +END +GO + + +--------------------------------------------- + +-- dbo.IntToGUID +CREATE Function [dbo].[IntToGUID]( + @objectID int +) +returns UNIQUEIDENTIFIER +AS +BEGIN + declare @GUIDSTR nvarchar(36); + set @GUIDSTR = cast(dbo.ZeroGUID() as nvarchar(36)); + + declare @obj nvarchar(11); + if (@objectID >= 0) begin + set @obj = '0' + cast(@objectID as nvarchar(10)); + end + else begin + set @obj = '1' + substring(cast(@objectID as nvarchar(11)), 2,10); + end + return cast( + STUFF('00000000', 1, LEN(SUBSTRING(@obj,1,8)),SUBSTRING(@obj, 1,8)) + + '-' + + STUFF('0000',1, LEN(SUBSTRING(@obj,9,3)),SUBSTRING(@obj,9,3)) + + '-0000-0000-000000000000' as uniqueidentifier) +END +GO + + +--------------------------------------------- + +-- dbo.IsClusteredIndexExist +-- ============================================= +-- Author: AI +-- Create date: 8/03/2017 +-- Description: Checks if clustered index exist. +-- Parameters: +-- @schema: Table schema +-- @table: Table name +-- @isPrimaryKey: Optional parameter. Checks if it's has primary key index. If parameter has default value then checks for clustered indexes with primary key and not. +-- Example: +-- Check for indexes with primary key and not +-- select dbo.IsClusteredIndexExist(@schema, @table, DEFAULT) +-- Check only primary key indexes +-- select dbo.IsClusteredIndexExist(@schema, @table, 1) +-- ============================================= +CREATE FUNCTION [dbo].[IsClusteredIndexExist] ( + @schema SYSNAME + ,@table SYSNAME + ,@isPrimaryKey BIT = NULL + ) +RETURNS BIT +AS +BEGIN + DECLARE @result BIT + + SET @result = ( + SELECT CASE + WHEN count(*) > 0 + THEN 1 + ELSE 0 + END + FROM sys.indexes i + INNER JOIN sys.tables t ON i.object_id = t.object_id + INNER JOIN sys.schemas s ON t.schema_id = s.schema_id + WHERE t.type = 'u' + AND t.NAME = @table + AND s.NAME = @schema + AND i.type = 1 + AND ( + @isPrimaryKey IS NULL + OR i.is_primary_key = @isPrimaryKey + ) + ) + + RETURN @result +END +GO + + +--------------------------------------------- + +-- dbo.IsLetter +CREATE function dbo.IsLetter( + @char varchar +) +returns bit +BEGIN + + declare @returnVal bit; + declare @ascii int; + + select @ascii = ASCII(@char); + + if ((@ascii >= 65 and @ascii <= 90) or (@ascii >= 97 and @ascii <= 122)) begin + set @returnVal = 1; + end + else begin + set @returnVal = 0; + end + + return @returnVal; +END +GO + + +--------------------------------------------- + +-- dbo.IsLetterOrDigit +CREATE function [dbo].[IsLetterOrDigit]( + @char varchar +) +returns bit +BEGIN + + declare @returnVal bit; + declare @ascii int; + + select @ascii = ASCII(@char); + + if ( + (@ascii >= 48 and @ascii <= 57) + or (@ascii >= 65 and @ascii <= 90) + or (@ascii >= 97 and @ascii <= 122)) + begin + set @returnVal = 1; + end + else begin + set @returnVal = 0; + end + + return @returnVal; +END +GO + + +--------------------------------------------- + +-- dbo.IsSQLCharacterType +CREATE Function [dbo].[IsSQLCharacterType]( + @eSQLDataType int +) +RETURNS bit +AS +BEGIN + declare @returnval bit; + set @returnval = 0; + if (@eSQLDataType in (175,239,35,99,167,231)) + begin + set @returnval = 1; + end + + return @returnval; +END +GO + + +--------------------------------------------- + +-- dbo.IsSQLDateTimeType +CREATE Function [dbo].[IsSQLDateTimeType]( + @eSQLDataType int +) +RETURNS bit +AS +BEGIN + declare @returnval bit; + set @returnval = 0; + if (@eSQLDataType in (58,61)) + begin + set @returnval = 1; + end + + return @returnval; +END +GO + + +--------------------------------------------- + +-- dbo.IsSQLNumericType +CREATE Function [dbo].[IsSQLNumericType]( + @eSQLDataType int +) +RETURNS bit +AS +BEGIN + declare @returnval bit; + set @returnval = 0; + if (@eSQLDataType in (48,52,56,58,59,60,62,106,122,127)) + begin + set @returnval = 1; + end + + return @returnval; +END +GO + + +--------------------------------------------- + +-- dbo.IsScoreObjectSQLForeignKeyedToTarget +CREATE FUNCTION dbo.IsScoreObjectSQLForeignKeyedToTarget +( + @dimToCheckAgainst UNIQUEIDENTIFIER, + @fkDimGUID UNIQUEIDENTIFIER +) +RETURNS BIT +AS +BEGIN + DECLARE @tableToFKCheck nvarchar(400) + DECLARE @tableToCheckAgainst nvarchar(400) + SELECT + @tableToCheckAgainst = a.DimensionGroupSQLObjectName, -- we check against this one to see if this table has a FK + @tableToFKCheck = A2.DimensionGroupSQLObjectName --this is the table we check if it is foreign keyed from + from viewscoreattribute a + INNER JOIN viewscoreattribute a2 ON a2.AttributeGUID = a.CachedFKDefaultLookupKeyGUID + where a.DimensionGUID = @dimToCheckAgainst AND a.CachedFKDimensionGUID =@fkDimGUID + + DECLARE @result BIT + IF @tableToFKCheck is null OR @tableToCheckAgainst is null + BEGIN + SET @result = 0 + END + ELSE + BEGIN + SET @result = dbo.IsTableForeignKeyedToTarget(@tableToFKCheck, @tableToCheckAgainst) + END + + RETURN @RESULT +END +GO + + +--------------------------------------------- + +-- dbo.IsTableForeignKeyedToTarget +CREATE FUNCTION dbo.IsTableForeignKeyedToTarget ( + @tableToFKCheck nvarchar(400), + @tableToCheckAgainst nvarchar(400) +) +RETURNS BIT +AS +BEGIN + declare @returnval as bit + + IF ( + SELECT + COUNT(1) + FROM + sys.foreign_keys (nolock) AS f + INNER JOIN + sys.foreign_key_columns (nolock) AS fc + ON f.OBJECT_ID = fc.constraint_object_id + INNER JOIN + sys.tables (nolock) t + ON t.OBJECT_ID = fc.referenced_object_id + WHERE + OBJECT_NAME (f.referenced_object_id) = 'dimpatienttype' AND OBJECT_NAME(f.parent_object_id) = 'dimaccount' + ) > 0 + BEGIN + SET @returnval = 1 + END + ELSE + BEGIN + SET @returnval = 0 + END + + RETURN @returnval +END +GO + + +--------------------------------------------- + +-- dbo.IsTriggerExist +CREATE Function [dbo].[IsTriggerExist]( + @TriggerName varchar(128) +) +returns bit +BEGIN + + declare @retval bit; + declare @count int; + select @count = count(*) from ViewSysTriggers where + Name = @TriggerName + if (@count >= 1) + set @retval = 1 + ELSE + set @retval = 0 + return @retval; +END +GO + + +--------------------------------------------- + +-- dbo.IsTupleXMLValidForStructure +CREATE function IsTupleXMLValidForStructure (@tuplexml xml, @mdcguid uniqueidentifier) + returns bit +as begin + declare @cnt int + select + @cnt = count(*) + from + ( + (select + T.c.query('DIMENSIONGUID').value('.', 'uniqueidentifier') as dimensionguid + from + @tuplexml.nodes('//DIMENSIONTUPLEMEMBER') T(c)) + ) xmld + left join emfmodeldataconfigdimensionlink mdcd on mdcd.dimensionguid = xmld.dimensionguid and modeldataconfigguid = @mdcguid + where + mdcd.dimensionguid is null + + declare @retval bit + if @cnt = 0 + set @retval = 1 + else + set @retval = 0 + return @retval +end +GO + + +--------------------------------------------- + +-- dbo.IsUniqueIndexColumnExist +Create Function [dbo].[IsUniqueIndexColumnExist]( + @SchemaName nvarchar(128), + @ObjectName nvarchar(128), + @ColumnName nvarchar(128) +) +Returns bit +AS +BEGIN + +declare @Count int; + +select @Count = COUNT(IND0.Name) from sys.objects O0 + inner join sys.schemas S0 on S0.schema_id = O0.schema_id + inner join sys.indexes IND0 on O0.object_id = IND0.object_id + inner join sys.index_columns ICOL0 on ICOL0.object_id = O0.object_id and IND0.index_id = ICOL0.index_id + inner join sys.columns COL0 on COL0.object_id = O0.object_id and ICOL0.column_id = COL0.column_id +Group By IND0.name, S0.name, O0.name + +HAVING S0.name = @SchemaName and O0.name = @ObjectName and COUNT(IND0.Name) = 1 + +and +IND0.name in ( + +select IND.name from sys.objects O + inner join sys.schemas S on S.schema_id = O.schema_id + inner join sys.indexes IND on O.object_id = IND.object_id + inner join sys.index_columns ICOL on ICOL.object_id = O.object_id and IND.index_id = ICOL.index_id + inner join sys.columns COL on COL.object_id = O.object_id and ICOL.column_id = COL.column_id +where S.name = @SchemaName and O.name = @ObjectName and COL.name = @ColumnName + and IND.is_unique = 1 + ) + +declare @ReturnVal bit; +if (@Count >= 1) +BEGIN + set @ReturnVal = 1; +END +ELSE +BEGIN + set @ReturnVal = 0; +END + +return @ReturnVal; +END +GO + + +--------------------------------------------- + +-- dbo.IsView +CREATE FUNCTION [dbo].[IsView] +( + @SchemaName nvarchar(128), + @ObjectName nvarchar(max) +) +returns bit +BEGIN + +declare @TOTAL int; +select @TOTAL = COUNT(*) from sys.views V + inner join sys.schemas S on V.schema_id = S.schema_id +where + S.Name = @SchemaName and V.Name = @ObjectName + +return cast(@TOTAL as bit); +END +GO + + +--------------------------------------------- + +-- dbo.JSONEscaped +CREATE FUNCTION [dbo].[JSONEscaped] ( /* this is a simple utility function that takes a SQL String with all its clobber and outputs it as a sting with all the JSON escape sequences in it.*/ + @Unescaped NVARCHAR(MAX) --a string with maybe characters that will break json + ) +RETURNS NVARCHAR(MAX) +AS +BEGIN + SELECT @Unescaped = REPLACE(@Unescaped, FROMString, TOString) + FROM (SELECT '' AS FromString, '\' AS ToString + UNION ALL SELECT '"', '"' + UNION ALL SELECT '/', '/' + UNION ALL SELECT CHAR(08),'b' + UNION ALL SELECT CHAR(12),'f' + UNION ALL SELECT CHAR(10),'n' + UNION ALL SELECT CHAR(13),'r' + UNION ALL SELECT CHAR(09),'t' + ) substitutions +RETURN @Unescaped +END +GO + + +--------------------------------------------- + +-- dbo.Last12Months +Create FUNCTION [dbo].[Last12Months] +( + @Date DATETIME +) RETURNS @tbl TABLE (Start DATETIME, EndDate DATETIME) +AS +BEGIN + WITH T AS( + SELECT + DATEADD(month, DATEDIFF(month, 0, @Date), 0) AS Start, + DATEADD(d, -DAY(DATEADD(m,1,@date)),DATEADD(m,1,@date)) AS EndDate, + 12 Cnt + UNION ALL + SELECT + DATEADD(month, -1, Start), + DATEADD(d, -DAY(DATEADD(m,1,Start-1)),DATEADD(m,1,Start-1)), + Cnt-1 + FROM + T + WHERE + Cnt-1>0 + ) + INSERT INTO @tbl + (Start, EndDate) + SELECT + Start, EndDate + FROM T + + RETURN +END +GO + + +--------------------------------------------- + +-- dbo.MaxDateTime +create function dbo.MaxDateTime(@val1 datetime, @val2 datetime) +returns datetime +as +begin + if @val1 > @val2 + return @val1 + return isnull(@val2,@val1) +end +GO + + +--------------------------------------------- + +-- dbo.ParseFullPath +CREATE FUNCTION [dbo].[ParseFullPath] +( + @inText varchar(max), + @delim varchar(1) = '\', + @targetIndex int +) +RETURNS varchar(max) +AS +BEGIN + +IF @inText is null BEGIN + return '' +end + +IF len(@inText) = 0 BEGIN + return '' +end + +DECLARE @remainingText varchar(max) +DECLARE @currentValue varchar(max) +DECLARE @currentIndex int + +SET @remainingText = @inText +SET @currentIndex = 0 + +WHILE @currentIndex < @targetIndex +BEGIN + + SET @currentIndex = @currentIndex + 1 + + IF charindex('\', @remainingText) = 0 BEGIN + IF @currentIndex = @targetIndex + RETURN @remainingText + ELSE + return '' + end + SET @currentValue = left(@remainingText,charindex('\', @remainingText) -1) + SET @remainingText = right(@remainingText, len(@remainingText) - (len(@currentValue) + 1)) + +END + +RETURN @currentValue +END +GO + + +--------------------------------------------- + +-- dbo.ParseFullPathGUID +CREATE FUNCTION [dbo].[ParseFullPathGUID] +( + @inText varchar(max), + @delim varchar(1) = '\', + @targetIndex int +) +RETURNS uniqueidentifier +AS +BEGIN + +IF @inText is null BEGIN + return '00000000-0000-0000-0000-000000000000' +end + +IF len(@inText) = 0 BEGIN + return '00000000-0000-0000-0000-000000000000' +end + +DECLARE @remainingText varchar(max) +DECLARE @currentValue uniqueidentifier +DECLARE @currentIndex int + +SET @remainingText = @inText +SET @currentIndex = 0 + +WHILE @currentIndex < @targetIndex +BEGIN + + SET @currentIndex = @currentIndex + 1 + + IF charindex('\', @remainingText) = 0 BEGIN + IF @currentIndex = @targetIndex + RETURN @remainingText + ELSE + return '00000000-0000-0000-0000-000000000000' + end + SET @currentValue = left(@remainingText,charindex('\', @remainingText) -1) + SET @remainingText = right(@remainingText, len(@remainingText) - (len(@currentValue) + 1)) + +END + +RETURN @currentValue +END +GO + + +--------------------------------------------- + +-- dbo.ParseRecord +CREATE function [dbo].[ParseRecord]( + @test nvarchar(max) + ,@findBase nvarchar(max) +) returns nvarchar(max) +as +BEGIN + declare @ret as nvarchar(max) + + --declare @test nvarchar(max) + --set @test = 'Quantity=126|CostPerItem=1250.00' + + --declare @findBase nvarchar(max) + --set @findBase = 'Item' + + declare @recordStart char(1) + set @recordStart = ',' + declare @recordEqual char(1) + set @recordEqual = '=' + + declare @find nvarchar(max) + set @find = @recordStart + @findBase + @recordEqual + + declare @startPos int + set @startpos = charindex(@find,@test,0) + + if @startPos = 0 begin + --not found, try without recordStart + set @find = @findBase + @recordEqual + set @startpos = charindex(@find,@test,0) + + if @startPos = 0 begin + --still not found + return '' + end + + end + + set @startPos = @startPos + LEN(@find) + + declare @endPos int + set @endpos = CHARINDEX(@recordStart,@test,@startPos) + + if @endPos = 0 begin + set @endPos = LEN(@test) + 1 + end + + set @ret = SUBSTRING(@test,@startpos, @endPos - @startPos) + + return @ret +END +GO + + +--------------------------------------------- + +-- dbo.RandNumber +CREATE FUNCTION RandNumber() +RETURNS float +AS + BEGIN + RETURN (SELECT RandNumber FROM viewRandomNumber) + END +GO + + +--------------------------------------------- + +-- dbo.STRAGGR +-- Unable to retrieve definition for dbo.STRAGGR. +GO + + +--------------------------------------------- + +-- dbo.SanitizeNonDelimitedIdentifier +CREATE FUNCTION dbo.SanitizeNonDelimitedIdentifier( + @str varchar(max) +) +returns varchar(max) +BEGIN + + declare @index int; + declare @returnVal varchar(max); + declare @currentChar char; + + set @returnVal = ''; + set @index = 1; + + WHILE (@index <= LEN(@str)) + begin + select @currentChar = SUBSTRING(@str,@index,1); + if (@index = 1) begin + if (dbo.IsLetter(@currentChar) = 1 or @currentChar = '_' or @currentChar = '@' or @currentChar = '#') begin + set @returnVal = @returnVal + @currentChar; + end + else begin + set @returnVal = @returnVal + '_'; + end + end + else + begin + if (dbo.IsLetterOrDigit(@currentChar) = 1 or @currentChar = '_' or @currentChar = '@' or @currentChar = '#' or @currentChar = '$') begin + set @returnVal = @returnVal + @currentChar; + end + else begin + set @returnVal = @returnVal + '_'; + end + end + + set @index = @index + 1; + end + + return @returnVal; + +END +GO + + +--------------------------------------------- + +-- dbo.ScoreIsDataTableInUse +CREATE FUNCTION [dbo].[ScoreIsDataTableInUse] +( + @DataTableGUID uniqueidentifier +) +RETURNS Bit +As +BEGIN + + +--Is DataTable used by any composites +DECLARE @CompositeCount int; +select @CompositeCount = COUNT(*) from ScoreComposite COMP + inner join ScoreDataTable DT on DT.DataTableGUID = COMP.DataTableGUID1 OR DT.DataTableGUID = COMP.DataTableGuid2 +Where DT.DataTableGUID = @DataTableGUID; + +--Any other cases? I don't think so... +declare @retval bit; +set @retval = 0; + +if (@CompositeCount > 0) +BEGIN + set @retval = 1; +END + +RETURN @retval + +END +GO + + +--------------------------------------------- + +-- dbo.ScoreIsDimensionFKsActive +CREATE FUNCTION [dbo].[ScoreIsDimensionFKsActive] ( + @DimensionGUID uniqueidentifier +) +RETURNS BIT +AS +BEGIN + +--Does Given Dimension Contain an Attribute that is a foreign key to an in-use dimension? +declare @Total int; +select @Total = COUNT(*) from ScoreDataTable DT + inner join ScoreDataTableKeyLink DTLINK on DT.DataTableGUID = DTLINK.DataTableGUID + inner join ScoreAttribute INUSE_ATT on INUSE_ATT.AttributeGUID = DTLINK.KeyGUID + inner join ScoreAttribute OUR_ATT on OUR_ATT.AttributeGUID = INUSE_ATT.ForeignKeyGUID + inner join ScoreDimensionGroup OUR_DIMGROUP on OUR_DIMGROUP.DimensionGroupGUID = OUR_ATT.DimensionGroupGUID + inner join ScoreDimension OUR_DIM on OUR_DIM.DimensionGUID = OUR_DIMGROUP.DimensionGUID + Where OUR_DIM.DimensionGUID = @DimensionGUID + +DECLARE @retval BIT; +SET @retval = 0; +IF (@Total > 0) +BEGIN + set @retval = 1; +END + +return @retval; +END +GO + + +--------------------------------------------- + +-- dbo.ScoreIsDimensionInUse +CREATE FUNCTION [dbo].[ScoreIsDimensionInUse] +( + @DimensionGuid uniqueidentifier +) +RETURNS Bit +As +BEGIN + + +--Is Dimension used by any datatables +DECLARE @DTCount int; +select @DTCount = COUNT(*) from ScoreDataTable DT + inner join ScoreDataTableKeyLink KLINK on DT.DataTableGUID = KLINK.DataTableGUID + inner join ScoreAttribute ATT on ATT.AttributeGUID = KLINK.KeyGUID + inner join ScoreDimensionGroup G on ATT.DimensionGroupGUID = G.DimensionGroupGUID + inner join ScoreDimension DIM on DIM.DimensionGUID = G.DimensionGUID +Where DIM.DimensionGUID = @DimensionGUID; + +declare @retval bit; +set @retval = 0; + +--Does Dimension Contain an Attribute that is a foreign key to an in use dimension? +DECLARE @IsaForeignKeyForInUse bit; +set @IsaForeignKeyForInUse = [dbo].[ScoreIsDimensionFKsActive] (@DimensionGUID); +if (@IsaForeignKeyForInUse = 1) +BEGIN + set @retval = 1 +END + +if (@DTCount > 0) +BEGIN + set @retval = 1; +END + +RETURN @retval + +END +GO + + +--------------------------------------------- + +-- dbo.ScoreIsPlaceHolderDimension +CREATE FUNCTION [dbo].[ScoreIsPlaceHolderDimension] +( + @DimensionGuid uniqueidentifier +) +RETURNS Bit +As +BEGIN + + +--Is Dimension used by any datatables +DECLARE @DTCount int; +select @DTCount = COUNT(*) from ScoreComposite C + inner join ScoreCompositeLink CL on C.CompositeGUID = CL.CompositeGUID + inner join ScoreAttribute ATT on ATT.AttributeGUID = CL.Key1GUID + inner join ScoreDimensionGroup G on ATT.DimensionGroupGUID = G.DimensionGroupGUID + inner join ScoreDimension DIM on DIM.DimensionGUID = G.DimensionGUID +Where DIM.DimensionGUID = @DimensionGUID and CL.[Type] = 1 ; --direct placeholder + +declare @retval bit; +set @retval = 0; + +if (@DTCount > 0) +BEGIN + set @retval = 1; +END + +RETURN @retval + +END +GO + + +--------------------------------------------- + +-- dbo.Split +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-09-04 IP B-20335 Component varchar(50) --> varchar(500) to support spitting of History Viewer filter +** 2 2018-09-13 SD TK-63626 Change type from varchar(500) to varchar(max) + TK-63621 +*************************************************************/ +CREATE FUNCTION [dbo].[Split]( + @Input varchar(max), + @Delimeter char(1) +) +RETURNS @returnTable TABLE(Component varchar(max)) +AS +BEGIN + --Parse the string and insert each component into the @returnTable table + DECLARE @SubString varchar(max) + DECLARE @StartPos int, @Length int + WHILE LEN(@Input) > 0 + BEGIN + SET @StartPos = CHARINDEX(@Delimeter, @Input) + IF @StartPos < 0 SET @StartPos = 0 + SET @Length = LEN(@Input) - @StartPos - 1 + IF @Length < 0 SET @Length = 0 + IF @StartPos > 0 + BEGIN + SET @SubString = SUBSTRING(@Input, 1, @StartPos - 1) + SET @Input = SUBSTRING(@Input, @StartPos + 1, LEN(@Input) - @StartPos) + END + ELSE + BEGIN + SET @SubString = @Input + SET @Input = '' + END + INSERT @returnTable (Component) VALUES(@SubString) + END + + --Show all Components in the @returnTable table + RETURN +END +GO + + +--------------------------------------------- + +-- dbo.StripNewLine +CREATE function [dbo].[StripNewLine]( + @Input varchar(max) +) +returns varchar(max) +AS +BEGIN + declare @retval varchar(max); + set @retval = REPLACE(REPLACE(REPLACE(@Input, CHAR(13), ' '), CHAR(10), ' '), CHAR(13) + CHAR(10), ' '); + + return @retval; + + +END +GO + + +--------------------------------------------- + +-- dbo.TableColumnExists +CREATE FUNCTION [dbo].[TableColumnExists]( + @SchemaName NVARCHAR(128), + @TableName NVARCHAR(MAX), + @ColumnName nvarchar(128) +) +RETURNS BIT--Returns 0 if column does not exist. Returns 1 if column exists. +AS +BEGIN + +IF EXISTS + (SELECT 1 + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = @SchemaName AND TABLE_NAME = @tablename + AND COLUMN_NAME = @columnname + ) +RETURN cast(1 as bit) + +--Table does not contain the column. +RETURN cast(0 as bit) +END +GO + + +--------------------------------------------- + +-- dbo.TableColumnExistsByTableExpression +CREATE FUNCTION [dbo].[TableColumnExistsByTableExpression]( + @TableExpression NVARCHAR(MAX), + @ColumnName nvarchar(128) +) +RETURNS BIT--Returns 0 if column does not exist. Returns 1 if column exists. +AS +BEGIN + +IF EXISTS + (SELECT 1 + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA + '.' + TABLE_NAME = @TableExpression + AND COLUMN_NAME = @columnname + ) +RETURN cast(1 as bit) + + +IF EXISTS + (SELECT 1 + FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA + '.' + TABLE_NAME = @TableExpression + AND '[' + COLUMN_NAME + ']' = @columnname + ) +RETURN cast(1 as bit) + +IF EXISTS + (SELECT 1 + FROM INFORMATION_SCHEMA.COLUMNS + WHERE ('[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']') = @TableExpression + AND COLUMN_NAME = @columnname + ) +RETURN cast(1 as bit) + +IF EXISTS + (SELECT 1 + FROM INFORMATION_SCHEMA.COLUMNS + WHERE ('[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']') = @TableExpression + AND '[' + COLUMN_NAME + ']' = @columnname + ) +RETURN cast(1 as bit) + +--Table does not contain the column. +RETURN cast(0 as bit) +END +GO + + +--------------------------------------------- + +-- dbo.TableExists +CREATE FUNCTION [dbo].[TableExists]( + @SchemaName sysname, + @TableName sysname +) +RETURNS BIT--Returns 0 if table does not exist. Returns 1 if table exists. +AS +BEGIN + +IF EXISTS + (SELECT * FROM INFORMATION_SCHEMA.Tables + WHERE TABLE_SCHEMA = @SchemaName AND TABLE_NAME = @TableName and TABLE_TYPE = 'BASE TABLE') +RETURN cast(1 as bit) + +--Table does not contain the column. +RETURN cast(0 as bit) +END +GO + + +--------------------------------------------- + +-- dbo.TableExistsByTableExpression +CREATE FUNCTION [dbo].[TableExistsByTableExpression]( + @TableExpression NVARCHAR(MAX) +) +RETURNS BIT--Returns 0 if table does not exist. Returns 1 if table exists. +AS +BEGIN + +IF EXISTS + (SELECT * FROM INFORMATION_SCHEMA.Tables + WHERE TABLE_SCHEMA + '.' + TABLE_NAME = @TableExpression) +RETURN cast(1 as bit) + +IF EXISTS + (SELECT * FROM INFORMATION_SCHEMA.Tables + WHERE '[' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']' = @TableExpression) +RETURN cast(1 as bit) + +IF EXISTS + (SELECT * FROM INFORMATION_SCHEMA.Tables + WHERE TABLE_NAME = @TableExpression) +RETURN cast(1 as bit) + +--Table does not contain the column. +RETURN cast(0 as bit) +END +GO + + +--------------------------------------------- + +-- dbo.TitleCase +create function dbo.TitleCase(@Text as varchar(8000)) +returns varchar(8000) +as +begin + declare @Reset bit; + declare @Ret varchar(8000); + declare @i int; + declare @c char(1); + + select @Reset = 1, @i=1, @Ret = ''; + + while (@i <= len(@Text)) + select @c= substring(@Text,@i,1), + @Ret = @Ret + case when @Reset=1 then UPPER(@c) else LOWER(@c) end, + @Reset = case when @c like '[a-zA-Z]' then 0 else 1 end, + @i = @i +1 + return @Ret +end +GO + + +--------------------------------------------- + +-- dbo.ToValidCSV +create function dbo.ToValidCSV (@Text varchar(max)) +RETURNS varchar(max) +AS +BEGIN + + declare @RetVal varchar(max); + set @RetVal = @Text; + + -- if it contains " , replace with "" + if (CHARINDEX('"', @RetVal, 1) <> 0) begin + set @RetVal = REPLACE(@RetVal, '"', '""'); + end + -- if it contains a comma, seperate with quotes + if (CHARINDEX(',',@RetVal,1) <> 0) begin + set @RetVal = '"' + @RetVal + '"'; + end + + return @RetVal; +END +GO + + +--------------------------------------------- + +-- dbo.TrimChar +Create FUNCTION [dbo].[TrimChar]( + @String NVARCHAR(4000), + @c NCHAR(1) +) +RETURNS nvarchar(4000) +AS +BEGIN + +IF @String IS NOT NULL AND @c IS NOT NULL +BEGIN + SET @String = REPLACE(REPLACE(LTrim(RTrim(REPLACE(REPLACE(@String,' ','~'),@c,' '))),' ',@c),'~',' ') +END + +RETURN @String + +END +GO + + +--------------------------------------------- + +-- dbo.ViewExists +CREATE FUNCTION [dbo].[ViewExists](@SchemaName nvarchar(128), @ViewName NVARCHAR(128)) +RETURNS BIT--Returns 0 if column does not exist. Returns 1 if column exists. +AS +BEGIN +--See if the Table already contains the column. + + +IF EXISTS + (SELECT * FROM INFORMATION_SCHEMA.Views + WHERE TABLE_SCHEMA = @SchemaName AND TABLE_NAME = @ViewName) +RETURN cast(1 as bit) + +--Table does not contain the column. +RETURN cast(0 as bit) +END +GO + + +--------------------------------------------- + +-- dbo.YTD +CREATE FUNCTION [dbo].[YTD] +( + @currentMonthIndex tinyint, + @amount01 decimal(19, 4), + @amount02 decimal(19, 4), + @amount03 decimal(19, 4), + @amount04 decimal(19, 4), + @amount05 decimal(19, 4), + @amount06 decimal(19, 4), + @amount07 decimal(19, 4), + @amount08 decimal(19, 4), + @amount09 decimal(19, 4), + @amount10 decimal(19, 4), + @amount11 decimal(19, 4), + @amount12 decimal(19, 4) +) +returns decimal(19, 4) with schemabinding +BEGIN + +declare @amount decimal(19, 4) + +set @amount = @amount01 + +if @currentMonthIndex >= 2 begin set @amount = @amount + @amount02; +if @currentMonthIndex >= 3 begin set @amount = @amount + @amount03; +if @currentMonthIndex >= 4 begin set @amount = @amount + @amount04; +if @currentMonthIndex >= 5 begin set @amount = @amount + @amount05; +if @currentMonthIndex >= 6 begin set @amount = @amount + @amount06; +if @currentMonthIndex >= 7 begin set @amount = @amount + @amount07; +if @currentMonthIndex >= 8 begin set @amount = @amount + @amount08; +if @currentMonthIndex >= 9 begin set @amount = @amount + @amount09; +if @currentMonthIndex >= 10 begin set @amount = @amount + @amount10; +if @currentMonthIndex >= 11 begin set @amount = @amount + @amount11; +if @currentMonthIndex >= 12 begin set @amount = @amount + @amount12; +end end end end end end end end end end end + +return @amount + +END +GO + + +--------------------------------------------- + +-- dbo.ZeroGUID +-- ============================================= +-- Author: +-- Create date: +-- Description: +-- ============================================= +CREATE FUNCTION dbo.ZeroGUID () +RETURNS uniqueidentifier +AS +BEGIN + -- Declare the return variable here + DECLARE @ZEROGUID uniqueidentifier + SET @ZEROGUID = '00000000-0000-0000-0000-000000000000' + RETURN @ZEROGUID + +END +GO + + +--------------------------------------------- + +-- dbo.fnParseJSON +CREATE FUNCTION [dbo].[fnParseJSON]( @JSON NVARCHAR(MAX)) +/************************************************************** +** Change History +** CID Date Author WI Description +** 1 2019-06-03 IP D-07973 function that transforms JSON to element-list +*************************************************************/ +RETURNS @hierarchy TABLE + ( + element_id INT IDENTITY(1, 1) NOT NULL, /* internal surrogate primary key gives the order of parsing and the list order */ + sequenceNo [int] NULL, /* the place in the sequence for the element */ + parent_ID INT,/* if the element has a parent then it is in this column. The document is the ultimate parent, so you can get the structure from recursing from the document */ + Object_ID INT,/* each list or object has an object id. This ties all elements to a parent. Lists are treated as objects here */ + NAME NVARCHAR(2000),/* the name of the object */ + StringValue NVARCHAR(MAX) NOT NULL,/*the string representation of the value of the element. */ + ValueType VARCHAR(10) NOT null /* the declared type of the value represented as a string in StringValue*/ + ) +AS +BEGIN + DECLARE + @FirstObject INT, --the index of the first open bracket found in the JSON string + @OpenDelimiter INT,--the index of the next open bracket found in the JSON string + @NextOpenDelimiter INT,--the index of subsequent open bracket found in the JSON string + @NextCloseDelimiter INT,--the index of subsequent close bracket found in the JSON string + @Type NVARCHAR(10),--whether it denotes an object or an array + @NextCloseDelimiterChar CHAR(1),--either a '}' or a ']' + @Contents NVARCHAR(MAX), --the unparsed contents of the bracketed expression + @Start INT, --index of the start of the token that you are parsing + @end INT,--index of the end of the token that you are parsing + @param INT,--the parameter at the end of the next Object/Array token + @EndOfName INT,--the index of the start of the parameter at end of Object/Array token + @token NVARCHAR(200),--either a string or object + @value NVARCHAR(MAX), -- the value as a string + @SequenceNo int, -- the sequence number within a list + @name NVARCHAR(200), --the name as a string + @parent_ID INT,--the next parent ID to allocate + @lenJSON INT,--the current length of the JSON String + @characters NCHAR(36),--used to convert hex to decimal + @result BIGINT,--the value of the hex symbol being parsed + @index SMALLINT,--used for parsing the hex value + @Escape INT --the index of the next escape character + + + DECLARE @Strings TABLE /* in this temporary table we keep all strings, even the names of the elements, since they are 'escaped' in a different way, and may contain, unescaped, brackets denoting objects or lists. These are replaced in the JSON string by tokens representing the string */ + ( + String_ID INT IDENTITY(1, 1), + StringValue NVARCHAR(MAX) + ) + SELECT--initialise the characters to convert hex to ascii + @characters='0123456789abcdefghijklmnopqrstuvwxyz', + @SequenceNo=0, --set the sequence no. to something sensible. + /* firstly we process all strings. This is done because [{} and ] aren't escaped in strings, which complicates an iterative parse. */ + @parent_ID=0; + WHILE 1=1 --forever until there is nothing more to do + BEGIN + SELECT + @start=PATINDEX('%[^a-zA-Z]["]%', @json collate SQL_Latin1_General_CP850_Bin);--next delimited string + IF @start=0 BREAK --no more so drop through the WHILE loop + IF SUBSTRING(@json, @start+1, 1)='"' + BEGIN --Delimited Name + SET @start=@Start+1; + SET @end=PATINDEX('%[^\]["]%', RIGHT(@json, LEN(@json+'|')-@start) collate SQL_Latin1_General_CP850_Bin); + END + IF @end=0 --no end delimiter to last string + BREAK --no more + SELECT @token=SUBSTRING(@json, @start+1, @end-1) + --now put in the escaped control characters + SELECT @token=REPLACE(@token, FROMString, TOString) + FROM + (SELECT + '\"' AS FromString, '"' AS ToString + UNION ALL SELECT '\\', '\' + UNION ALL SELECT '\/', '/' + UNION ALL SELECT '\b', CHAR(08) + UNION ALL SELECT '\f', CHAR(12) + UNION ALL SELECT '\n', CHAR(10) + UNION ALL SELECT '\r', CHAR(13) + UNION ALL SELECT '\t', CHAR(09) + ) substitutions + SELECT @result=0, @escape=1 + --Begin to take out any hex escape codes + WHILE @escape>0 + BEGIN + SELECT @index=0, + --find the next hex escape sequence + @escape=PATINDEX('%\x[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%', @token collate SQL_Latin1_General_CP850_Bin) + IF @escape>0 --if there is one + BEGIN + WHILE @index<4 --there are always four digits to a \x sequence + BEGIN + SELECT --determine its value + @result=@result+POWER(16, @index) + *(CHARINDEX(SUBSTRING(@token, @escape+2+3-@index, 1), + @characters)-1), @index=@index+1 ; + + END + -- and replace the hex sequence by its unicode value + SELECT @token=STUFF(@token, @escape, 6, NCHAR(@result)) + END + END + --now store the string away + INSERT INTO @Strings (StringValue) SELECT @token + -- and replace the string with a token + SELECT @JSON=STUFF(@json, @start, @end+1, + '@string'+CONVERT(NVARCHAR(5), @@identity)) + END + -- all strings are now removed. Now we find the first leaf. + WHILE 1=1 --forever until there is nothing more to do + BEGIN + + SELECT @parent_ID=@parent_ID+1 + --find the first object or list by looking for the open bracket + SELECT @FirstObject=PATINDEX('%[{[[]%', @json collate SQL_Latin1_General_CP850_Bin)--object or array + IF @FirstObject = 0 BREAK + IF (SUBSTRING(@json, @FirstObject, 1)='{') + SELECT @NextCloseDelimiterChar='}', @type='object' + ELSE + SELECT @NextCloseDelimiterChar=']', @type='array' + SELECT @OpenDelimiter=@firstObject + + WHILE 1=1 --find the innermost object or list... + BEGIN + SELECT + @lenJSON=LEN(@JSON+'|')-1 + --find the matching close-delimiter proceeding after the open-delimiter + SELECT + @NextCloseDelimiter=CHARINDEX(@NextCloseDelimiterChar, @json, + @OpenDelimiter+1) + --is there an intervening open-delimiter of either type + SELECT @NextOpenDelimiter=PATINDEX('%[{[[]%', + RIGHT(@json, @lenJSON-@OpenDelimiter)collate SQL_Latin1_General_CP850_Bin)--object + IF @NextOpenDelimiter=0 + BREAK + SELECT @NextOpenDelimiter=@NextOpenDelimiter+@OpenDelimiter + IF @NextCloseDelimiter<@NextOpenDelimiter + BREAK + IF SUBSTRING(@json, @NextOpenDelimiter, 1)='{' + SELECT @NextCloseDelimiterChar='}', @type='object' + ELSE + SELECT @NextCloseDelimiterChar=']', @type='array' + SELECT @OpenDelimiter=@NextOpenDelimiter + END + ---and parse out the list or name/value pairs + SELECT + @contents=SUBSTRING(@json, @OpenDelimiter+1, + @NextCloseDelimiter-@OpenDelimiter-1) + SELECT + @JSON=STUFF(@json, @OpenDelimiter, + @NextCloseDelimiter-@OpenDelimiter+1, + '@'+@type+CONVERT(NVARCHAR(5), @parent_ID)) + WHILE (PATINDEX('%[A-Za-z0-9@+.e]%', @contents collate SQL_Latin1_General_CP850_Bin))<>0 + BEGIN + IF @Type='Object' --it will be a 0-n list containing a string followed by a string, number,boolean, or null + BEGIN + SELECT + @SequenceNo=0,@end=CHARINDEX(':', ' '+@contents)--if there is anything, it will be a string-based name. + SELECT @start=PATINDEX('%[^A-Za-z@][@]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin)--AAAAAAAA + SELECT @token=SUBSTRING(' '+@contents, @start+1, @End-@Start-1), + @endofname=PATINDEX('%[0-9]%', @token collate SQL_Latin1_General_CP850_Bin), + @param=RIGHT(@token, LEN(@token)-@endofname+1) + SELECT + @token=LEFT(@token, @endofname-1), + @Contents=RIGHT(' '+@contents, LEN(' '+@contents+'|')-@end-1) + SELECT @name=stringvalue FROM @strings + WHERE string_id=@param --fetch the name + END + ELSE + SELECT @Name=null,@SequenceNo=@SequenceNo+1 + SELECT + @end=CHARINDEX(',', @contents)-- a string-token, object-token, list-token, number,boolean, or null + IF @end=0 + SELECT @end=PATINDEX('%[A-Za-z0-9@+.e][^A-Za-z0-9@+.e]%', @Contents+' ' collate SQL_Latin1_General_CP850_Bin) + +1 + SELECT + @start=PATINDEX('%[^A-Za-z0-9@+.e][A-Za-z0-9@+.e][\-]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin) + -- Edited: add more condition [\-] in order to detect negative number 08-20-2014 + --select @start,@end, LEN(@contents+'|'), @contents + SELECT + @Value=RTRIM(SUBSTRING(@contents, @start, @End-@Start)), + @Contents=RIGHT(@contents+' ', LEN(@contents+'|')-@end) + IF SUBSTRING(@value, 1, 7)='@object' + INSERT INTO @hierarchy + (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType) + SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 8, 5), + SUBSTRING(@value, 8, 5), 'object' + ELSE + IF SUBSTRING(@value, 1, 6)='@array' + INSERT INTO @hierarchy + (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType) + SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 7, 5), + SUBSTRING(@value, 7, 5), 'array' + ELSE + IF SUBSTRING(@value, 1, 7)='@string' + INSERT INTO @hierarchy + (NAME, SequenceNo, parent_ID, StringValue, ValueType) + SELECT @name, @SequenceNo, @parent_ID, stringvalue, 'string' + FROM @strings + WHERE string_id=SUBSTRING(@value, 8, 5) + ELSE + IF @value IN ('true', 'false') + INSERT INTO @hierarchy + (NAME, SequenceNo, parent_ID, StringValue, ValueType) + SELECT @name, @SequenceNo, @parent_ID, @value, 'boolean' + ELSE + IF @value='null' + INSERT INTO @hierarchy + (NAME, SequenceNo, parent_ID, StringValue, ValueType) + SELECT @name, @SequenceNo, @parent_ID, @value, 'null' + ELSE + IF PATINDEX('%[^0-9]%', @value collate SQL_Latin1_General_CP850_Bin)>0 + INSERT INTO @hierarchy + (NAME, SequenceNo, parent_ID, StringValue, ValueType) + SELECT @name, @SequenceNo, @parent_ID, @value, 'real' + ELSE + INSERT INTO @hierarchy + (NAME, SequenceNo, parent_ID, StringValue, ValueType) + SELECT @name, @SequenceNo, @parent_ID, @value, 'int' + if @Contents=' ' Select @SequenceNo=0 + END + END +INSERT INTO @hierarchy (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType) + SELECT '-',1, NULL, '', @parent_id-1, @type +-- + RETURN +END +GO + + +--------------------------------------------- + +-- dbo.fn_diagramobjects +CREATE FUNCTION dbo.fn_diagramobjects() + RETURNS int + WITH EXECUTE AS N'dbo' + AS + BEGIN + declare @id_upgraddiagrams int + declare @id_sysdiagrams int + declare @id_helpdiagrams int + declare @id_helpdiagramdefinition int + declare @id_creatediagram int + declare @id_renamediagram int + declare @id_alterdiagram int + declare @id_dropdiagram int + declare @InstalledObjects int + + select @InstalledObjects = 0 + + select @id_upgraddiagrams = object_id(N'dbo.sp_upgraddiagrams'), + @id_sysdiagrams = object_id(N'dbo.sysdiagrams'), + @id_helpdiagrams = object_id(N'dbo.sp_helpdiagrams'), + @id_helpdiagramdefinition = object_id(N'dbo.sp_helpdiagramdefinition'), + @id_creatediagram = object_id(N'dbo.sp_creatediagram'), + @id_renamediagram = object_id(N'dbo.sp_renamediagram'), + @id_alterdiagram = object_id(N'dbo.sp_alterdiagram'), + @id_dropdiagram = object_id(N'dbo.sp_dropdiagram') + + if @id_upgraddiagrams is not null + select @InstalledObjects = @InstalledObjects + 1 + if @id_sysdiagrams is not null + select @InstalledObjects = @InstalledObjects + 2 + if @id_helpdiagrams is not null + select @InstalledObjects = @InstalledObjects + 4 + if @id_helpdiagramdefinition is not null + select @InstalledObjects = @InstalledObjects + 8 + if @id_creatediagram is not null + select @InstalledObjects = @InstalledObjects + 16 + if @id_renamediagram is not null + select @InstalledObjects = @InstalledObjects + 32 + if @id_alterdiagram is not null + select @InstalledObjects = @InstalledObjects + 64 + if @id_dropdiagram is not null + select @InstalledObjects = @InstalledObjects + 128 + + return @InstalledObjects + END +GO + + +--------------------------------------------- + +-- dbo.funcFindTSQLPerformanceFlaws +CREATE FUNCTION [dbo].[funcFindTSQLPerformanceFlaws] ( + @SqlText NVARCHAR(MAX) +) +RETURNS @Results TABLE ( + Severity SMALLINT, + Category NVARCHAR(MAX), + Description NVARCHAR(MAX) + ) +AS +BEGIN + + -- Rule 1 Avoid using Like ‘% %’ + IF (@SqlText LIKE '%''[%]%[%]''%') + BEGIN + INSERT INTO @Results (Category, Description, Severity) VALUES ('Contains Open Ended Like', 'Avoid using Like ‘% %’', 2) + END + + -- Rule 2 Avoid * ,Select only the required columns + IF (@SqlText LIKE '%SELECT%*,%FROM%' OR + @SqlText LIKE '%SELECT%,*%FROM%' OR + @SqlText LIKE '%SELECT%* ,%FROM%' OR + @SqlText LIKE '%SELECT%, *%FROM%' OR + @SqlText LIKE '%SELECT * FROM%') -- I'm sure there's a better way, but for now this will do, otherwise was getting too many false positives + BEGIN + INSERT INTO @Results (Category, Description, Severity) VALUES ('Select Star Used', 'Avoid * ,Select only the required columns', 2) + END + + -- Rule 3 Don't use DISTINCT unless you have to + IF (@SqlText LIKE '%DISTINCT%') + BEGIN + INSERT INTO @Results (Category, Description, Severity) VALUES ('Distinct Used', 'Don''t use DISTINCT unless you have to', 1) + END + + -- Rule 4 Think set based, instead of row by row (avoid cursor). + IF (@SqlText LIKE '%CURSOR%') + BEGIN + INSERT INTO @Results (Category, Description, Severity) VALUES('Cursor', 'Think set based, instead of row by row (avoid cursor).', 3) + END + + -- Rule 5 Avoid using table variables, cursors or function calls that evaluate each row in where clause + IF (@SqlText LIKE '%INNER JOIN @%') + BEGIN + INSERT INTO @Results (Category, Description, Severity) VALUES('Table Variables', 'Avoid using table variables, cursors or function calls that evaluate each row in where clause', 3) + END + + RETURN; +END +GO + + +--------------------------------------------- + +-- dbo.funcFindTSQLPerformanceFlawsForMigration +CREATE FUNCTION [dbo].[funcFindTSQLPerformanceFlawsForMigration] ( + @MigrationName NVARCHAR(MAX) +) +RETURNS @Results TABLE ( + Name NVARCHAR(MAX), + ObjectType NVARCHAR(MAX), + Severity NVARCHAR(MAX), + Category NVARCHAR(MAX), + Description NVARCHAR(MAX) + ) +AS +BEGIN + + DECLARE @Sql NVARCHAR(MAX) = (SELECT ForwardScript FROM [migration].[MigrationLog] WHERE Name = @MigrationName) + + INSERT INTO @Results(Name, Severity, ObjectType, Category, Description) + SELECT @MigrationName AS Name, CASE WHEN Severity = 3 THEN 'High' + WHEN Severity = 2 THEN 'Medium' + WHEN Severity = 1 THEN 'Low' ELSE 'N/A' END AS Severity, 'Migration' AS ObjectType, Category, Description + FROM [dbo].[funcFindTSQLPerformanceFlaws] (@Sql) + + RETURN; +END +GO + + +--------------------------------------------- + +-- dbo.getScoreDimensionGuid +Create Function [dbo].[getScoreDimensionGuid] +(@DimensionName nvarchar(128)) +Returns uniqueidentifier +AS +BEGIN +declare @DimGUID uniqueidentifier; +set @DimGUID = (select top 1 DimensionGUID from dbo.ScoreDimension where FriendlyName = @DimensionName) +return @DimGUID +End +GO + + +--------------------------------------------- + +-- dbo.intGetTransformationSourceField +CREATE FUNCTION [dbo].[intGetTransformationSourceField]( + @sourceColumnId uniqueidentifier +) +RETURNS varchar(1000) +BEGIN + DECLARE @SourceField TABLE + ( + RowNum int identity(1,1), + DataSourceID uniqueidentifier, + ColumnName nvarchar(1000), + Concatenator nvarchar(1000) default ' ' + ) + + --Get all info from current Source Field + insert into @SourceField + select distinct DataSourceID,ColumnName,' ' from IntSourceField where SourceColumnId=@sourceColumnId + + declare @transformationID uniqueidentifier + select @transformationID = DataSourceID from @SourceField + + DECLARE @ResultTable TABLE ( + TransformationID uniqueidentifier NOT NULL, + SourceDataSourceID uniqueidentifier NOT NULL, + Depth int NOT NULL + ) + + --Get all transformations from current Source Field + ;WITH cte (TransformationID, SourceDataSourceID, Depth) AS + ( + SELECT tl.TargetDataSourceID, tl.SourceDataSourceID, 1 as Depth + FROM + intTransformationLink tl + WHERE tl.TargetDataSourceID = @transformationID + + UNION ALL + + SELECT t.TargetDataSourceID, t.SourceDataSourceID, c.Depth + 1 + FROM intTransformationLink t + INNER JOIN cte c ON t.TargetDataSourceID = c.SourceDataSourceID + ) + + insert into @ResultTable + select * from cte + + DECLARE @SourceFields TABLE + ( + ColumnName nvarchar(1000) + ) + + insert into @SourceFields + select distinct ColumnName from IntSourceField + where DataSourceID=(select top 1 SourceDataSourceID from @ResultTable WHERE Depth = (SELECT top 1 MAX(Depth) FROM @ResultTable)) + + --If exists Source file field with the same name, return it + declare @result nvarchar(1000) + select @result = ColumnName + from( + select top 1 ColumnName from @SourceFields where ColumnName like (select ColumnName from @SourceField) + ) as r + + DECLARE @numrows int + SELECT @numrows = MAX(Depth) FROM @ResultTable + DECLARE @i int + SET @i = 1 + declare @xml XML + + DECLARE @TransactionXml TABLE + ( + NodeName nvarchar(1000), + NodeValue nvarchar(1000), + Alias nvarchar(1000) + ) + + --Go throw all transformations and look for Current Source Field + WHILE (@i <= @numrows) + BEGIN + select @xml = TRY_CONVERT(XML, (select TransformXml from IntTransformation where TransformationId = (select top 1 TransformationID from @ResultTable WHERE Depth = @i))) + If(@xml is null) + RETURN '' + + declare @xmlNode as varchar(1000) + select @xmlNode = @xml.value('local-name(/*[1])','varchar(1000)') + + delete from @TransactionXml + + --Parse TransactionXml for receiving transformation type name, used column and alias + insert into @TransactionXml + SELECT + NodeName = C.value('local-name(.)', 'nvarchar(1000)'), + NodeValue = C.value('(.)[1]', 'nvarchar(1000)'), + Alias = C.value('./@ALIAS','nvarchar(1000)') + FROM @xml.nodes('/*[local-name(.)=sql:variable("@xmlNode")]/*') AS T(C) + + DECLARE @numrowsFields int + SELECT @numrowsFields = count(1) FROM @SourceField + DECLARE @iFields int + SET @iFields = 1 + + DECLARE @firstSplit TABLE + ( + name nvarchar(1000) + ) + DECLARE @NewNames TABLE + ( + RowNum int identity(1,1), + name nvarchar(1000), + Concatenator nvarchar(1000) + ) + DECLARE @newName nvarchar(1000) + + --Go throw all result fields (handle case when source field use calculated column with several fields) + WHILE (@iFields <= @numrowsFields) + BEGIN + select @newName = NULL + --check if column was renamed + select @newName = NodeValue from @TransactionXml where Alias like (select ColumnName from @SourceField where RowNum = @iFields) + + IF @newName IS NOT NULL + BEGIN + update @SourceField set ColumnName = @newName where RowNum = @iFields + END + ELSE + BEGIN + --Handle calculated column + select @newName = NodeValue from @TransactionXml where NodeValue like (select ColumnName from @SourceField where RowNum = @iFields) AND NodeName like 'TARGETCOLUMN' + IF @newName IS NOT NULL + BEGIN + --parse calculated formula using [] + select @newName = NodeValue from @TransactionXml where NodeName like 'CALCULATION' + + delete from @firstSplit + insert into @firstSplit + select * from Split(@newName, '[') + + delete from @NewNames + insert into @NewNames + select Left(name,CHARINDEX(']',name)-1), case when CHARINDEX(']',name) <> len(name) then replace(name,Left(name,CHARINDEX(']',name)-1),'') else ' ' end + from @firstSplit where name like '%]%' + + DECLARE @iNewFields int + select @iNewFields = min(RowNum) from @NewNames + + --select * from @NewNames + + WHILE (@iNewFields <= (select max(RowNum) FROM @NewNames)) + BEGIN + declare @Concatenator varchar(1000) + set @Concatenator='' + select @Concatenator = Concatenator from @NewNames where RowNum = @iNewFields + + if(@Concatenator like '%||%||%') + begin + select @Concatenator = Component from Split(@Concatenator, '||') where (LTRIM(RTRIM(Component)) like '"%' or LTRIM(RTRIM(Component)) like '''%') + and (LTRIM(RTRIM(Component)) like '%"' or LTRIM(RTRIM(Component)) like '%''') + select @Concatenator = replace(@Concatenator, '"', '') + select @Concatenator = replace(@Concatenator, '''', '') + update @NewNames set Concatenator = @Concatenator where RowNum = @iNewFields + end + else + update @NewNames set Concatenator = ' ' where RowNum = @iNewFields + select @iNewFields = @iNewFields + 1 + END + + --update new name for Source Field + + IF (select count(1) from @NewNames) > 0 + BEGIN + update @SourceField set ColumnName = (select name from @NewNames where RowNum = (select min(RowNum) from @NewNames)) + where RowNum = @iFields + + update sf set sf.Concatenator = case when sf.Concatenator=' ' then nn.Concatenator else sf.Concatenator end + from @SourceField sf + join @NewNames nn on nn.name = sf.ColumnName + where sf.RowNum = @iFields and nn.Concatenator<>' ' + END + + --if calculated column contains more than one field, add it + IF (select count(1) from @NewNames) > 1 + BEGIN + insert into @SourceField(ColumnName, Concatenator) + select distinct name, Concatenator from @NewNames + where RowNum <> 1 and name not in (select ColumnName from @SourceField) + END + END + END + SET @iFields = @iFields + 1 + END + SET @i = @i + 1 + END + + IF(select count(*) from @SourceField) = 1 + BEGIN + update @SourceField set Concatenator='' + END + + --join all Source File fields that were used for current Source Field + select @result = STUFF(( + SELECT ColumnName + Concatenator + FROM @SourceField + order by RowNum + FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 0, '') + + RETURN @result +END +GO + + +--------------------------------------------- + +-- dbo.intGetTransformationSourceFileList +CREATE FUNCTION dbo.intGetTransformationSourceFileList( + @transformationID uniqueidentifier +) +RETURNS @ResultTable TABLE ( + SourceFileID uniqueidentifier NOT NULL +) +BEGIN + WITH cte (TransformationID, SourceDataSourceID, Depth) AS + ( + SELECT TargetDataSourceID, SourceDataSourceID, 1 as Depth + FROM intTransformationLink + WHERE TargetDataSourceID = @transformationID + + UNION ALL + + SELECT t.TargetDataSourceID, t.SourceDataSourceID, c.Depth + 1 + FROM intTransformationLink t + INNER JOIN cte c ON t.TargetDataSourceID = c.SourceDataSourceID + ) + INSERT INTO @ResultTable + SELECT DISTINCT SourceDataSourceID as SourceFileID from cte + WHERE Depth = (SELECT MAX(Depth) FROM cte) + + RETURN; +END +GO + + +--------------------------------------------- + +-- dbo.parseJSON +CREATE FUNCTION dbo.parseJSON( @JSON NVARCHAR(MAX)) +RETURNS @hierarchy TABLE + ( + element_id INT IDENTITY(1, 1) NOT NULL, /* internal surrogate primary key gives the order of parsing and the list order */ + sequenceNo [int] NULL, /* the place in the sequence for the element */ + parent_ID INT,/* if the element has a parent then it is in this column. The document is the ultimate parent, so you can get the structure from recursing from the document */ + Object_ID INT,/* each list or object has an object id. This ties all elements to a parent. Lists are treated as objects here */ + NAME NVARCHAR(2000),/* the name of the object */ + StringValue NVARCHAR(MAX) NOT NULL,/*the string representation of the value of the element. */ + ValueType VARCHAR(10) NOT null /* the declared type of the value represented as a string in StringValue*/ + ) +AS +BEGIN + DECLARE + @FirstObject INT, --the index of the first open bracket found in the JSON string + @OpenDelimiter INT,--the index of the next open bracket found in the JSON string + @NextOpenDelimiter INT,--the index of subsequent open bracket found in the JSON string + @NextCloseDelimiter INT,--the index of subsequent close bracket found in the JSON string + @Type NVARCHAR(10),--whether it denotes an object or an array + @NextCloseDelimiterChar CHAR(1),--either a '}' or a ']' + @Contents NVARCHAR(MAX), --the unparsed contents of the bracketed expression + @Start INT, --index of the start of the token that you are parsing + @end INT,--index of the end of the token that you are parsing + @param INT,--the parameter at the end of the next Object/Array token + @EndOfName INT,--the index of the start of the parameter at end of Object/Array token + @token NVARCHAR(200),--either a string or object + @value NVARCHAR(MAX), -- the value as a string + @SequenceNo int, -- the sequence number within a list + @name NVARCHAR(200), --the name as a string + @parent_ID INT,--the next parent ID to allocate + @lenJSON INT,--the current length of the JSON String + @characters NCHAR(36),--used to convert hex to decimal + @result BIGINT,--the value of the hex symbol being parsed + @index SMALLINT,--used for parsing the hex value + @Escape INT --the index of the next escape character + + + DECLARE @Strings TABLE /* in this temporary table we keep all strings, even the names of the elements, since they are 'escaped' in a different way, and may contain, unescaped, brackets denoting objects or lists. These are replaced in the JSON string by tokens representing the string */ + ( + String_ID INT IDENTITY(1, 1), + StringValue NVARCHAR(MAX) + ) + SELECT--initialise the characters to convert hex to ascii + @characters='0123456789abcdefghijklmnopqrstuvwxyz', + @SequenceNo=0, --set the sequence no. to something sensible. + /* firstly we process all strings. This is done because [{} and ] aren't escaped in strings, which complicates an iterative parse. */ + @parent_ID=0; + WHILE 1=1 --forever until there is nothing more to do + BEGIN + SELECT + @start=PATINDEX('%[^a-zA-Z]["]%', @json collate SQL_Latin1_General_CP850_Bin);--next delimited string + IF @start=0 BREAK --no more so drop through the WHILE loop + IF SUBSTRING(@json, @start+1, 1)='"' + BEGIN --Delimited Name + SET @start=@Start+1; + SET @end=PATINDEX('%[^\]["]%', RIGHT(@json, LEN(@json+'|')-@start) collate SQL_Latin1_General_CP850_Bin); + END + IF @end=0 --no end delimiter to last string + BREAK --no more + SELECT @token=SUBSTRING(@json, @start+1, @end-1) + --now put in the escaped control characters + SELECT @token=REPLACE(@token, FROMString, TOString) + FROM + (SELECT + '\"' AS FromString, '"' AS ToString + UNION ALL SELECT '\\', '\' + UNION ALL SELECT '\/', '/' + UNION ALL SELECT '\b', CHAR(08) + UNION ALL SELECT '\f', CHAR(12) + UNION ALL SELECT '\n', CHAR(10) + UNION ALL SELECT '\r', CHAR(13) + UNION ALL SELECT '\t', CHAR(09) + ) substitutions + SELECT @result=0, @escape=1 + --Begin to take out any hex escape codes + WHILE @escape>0 + BEGIN + SELECT @index=0, + --find the next hex escape sequence + @escape=PATINDEX('%\x[0-9a-f][0-9a-f][0-9a-f][0-9a-f]%', @token collate SQL_Latin1_General_CP850_Bin) + IF @escape>0 --if there is one + BEGIN + WHILE @index<4 --there are always four digits to a \x sequence + BEGIN + SELECT --determine its value + @result=@result+POWER(16, @index) + *(CHARINDEX(SUBSTRING(@token, @escape+2+3-@index, 1), + @characters)-1), @index=@index+1 ; + + END + -- and replace the hex sequence by its unicode value + SELECT @token=STUFF(@token, @escape, 6, NCHAR(@result)) + END + END + --now store the string away + INSERT INTO @Strings (StringValue) SELECT @token + -- and replace the string with a token + SELECT @JSON=STUFF(@json, @start, @end+1, + '@string'+CONVERT(NVARCHAR(5), @@identity)) + END + -- all strings are now removed. Now we find the first leaf. + WHILE 1=1 --forever until there is nothing more to do + BEGIN + + SELECT @parent_ID=@parent_ID+1 + --find the first object or list by looking for the open bracket + SELECT @FirstObject=PATINDEX('%[{[[]%', @json collate SQL_Latin1_General_CP850_Bin)--object or array + IF @FirstObject = 0 BREAK + IF (SUBSTRING(@json, @FirstObject, 1)='{') + SELECT @NextCloseDelimiterChar='}', @type='object' + ELSE + SELECT @NextCloseDelimiterChar=']', @type='array' + SELECT @OpenDelimiter=@firstObject + + WHILE 1=1 --find the innermost object or list... + BEGIN + SELECT + @lenJSON=LEN(@JSON+'|')-1 + --find the matching close-delimiter proceeding after the open-delimiter + SELECT + @NextCloseDelimiter=CHARINDEX(@NextCloseDelimiterChar, @json, + @OpenDelimiter+1) + --is there an intervening open-delimiter of either type + SELECT @NextOpenDelimiter=PATINDEX('%[{[[]%', + RIGHT(@json, @lenJSON-@OpenDelimiter)collate SQL_Latin1_General_CP850_Bin)--object + IF @NextOpenDelimiter=0 + BREAK + SELECT @NextOpenDelimiter=@NextOpenDelimiter+@OpenDelimiter + IF @NextCloseDelimiter<@NextOpenDelimiter + BREAK + IF SUBSTRING(@json, @NextOpenDelimiter, 1)='{' + SELECT @NextCloseDelimiterChar='}', @type='object' + ELSE + SELECT @NextCloseDelimiterChar=']', @type='array' + SELECT @OpenDelimiter=@NextOpenDelimiter + END + ---and parse out the list or name/value pairs + SELECT + @contents=SUBSTRING(@json, @OpenDelimiter+1, + @NextCloseDelimiter-@OpenDelimiter-1) + SELECT + @JSON=STUFF(@json, @OpenDelimiter, + @NextCloseDelimiter-@OpenDelimiter+1, + '@'+@type+CONVERT(NVARCHAR(5), @parent_ID)) + WHILE (PATINDEX('%[A-Za-z0-9@+.e]%', @contents collate SQL_Latin1_General_CP850_Bin))<>0 + BEGIN + IF @Type='Object' --it will be a 0-n list containing a string followed by a string, number,boolean, or null + BEGIN + SELECT + @SequenceNo=0,@end=CHARINDEX(':', ' '+@contents)--if there is anything, it will be a string-based name. + SELECT @start=PATINDEX('%[^A-Za-z@][@]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin)--AAAAAAAA + SELECT @token=SUBSTRING(' '+@contents, @start+1, @End-@Start-1), + @endofname=PATINDEX('%[0-9]%', @token collate SQL_Latin1_General_CP850_Bin), + @param=RIGHT(@token, LEN(@token)-@endofname+1) + SELECT + @token=LEFT(@token, @endofname-1), + @Contents=RIGHT(' '+@contents, LEN(' '+@contents+'|')-@end-1) + SELECT @name=stringvalue FROM @strings + WHERE string_id=@param --fetch the name + END + ELSE + SELECT @Name=null,@SequenceNo=@SequenceNo+1 + SELECT + @end=CHARINDEX(',', @contents)-- a string-token, object-token, list-token, number,boolean, or null + IF @end=0 + SELECT @end=PATINDEX('%[A-Za-z0-9@+.e][^A-Za-z0-9@+.e]%', @Contents+' ' collate SQL_Latin1_General_CP850_Bin) + +1 + SELECT + @start=PATINDEX('%[^A-Za-z0-9@+.e][A-Za-z0-9@+.e]%', ' '+@contents collate SQL_Latin1_General_CP850_Bin) + --select @start,@end, LEN(@contents+'|'), @contents + SELECT + @Value=RTRIM(SUBSTRING(@contents, @start, @End-@Start)), + @Contents=RIGHT(@contents+' ', LEN(@contents+'|')-@end) + IF SUBSTRING(@value, 1, 7)='@object' + INSERT INTO @hierarchy + (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType) + SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 8, 5), + SUBSTRING(@value, 8, 5), 'object' + ELSE + IF SUBSTRING(@value, 1, 6)='@array' + INSERT INTO @hierarchy + (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType) + SELECT @name, @SequenceNo, @parent_ID, SUBSTRING(@value, 7, 5), + SUBSTRING(@value, 7, 5), 'array' + ELSE + IF SUBSTRING(@value, 1, 7)='@string' + INSERT INTO @hierarchy + (NAME, SequenceNo, parent_ID, StringValue, ValueType) + SELECT @name, @SequenceNo, @parent_ID, stringvalue, 'string' + FROM @strings + WHERE string_id=SUBSTRING(@value, 8, 5) + ELSE + IF @value IN ('true', 'false') + INSERT INTO @hierarchy + (NAME, SequenceNo, parent_ID, StringValue, ValueType) + SELECT @name, @SequenceNo, @parent_ID, @value, 'boolean' + ELSE + IF @value='null' + INSERT INTO @hierarchy + (NAME, SequenceNo, parent_ID, StringValue, ValueType) + SELECT @name, @SequenceNo, @parent_ID, @value, 'null' + ELSE + IF PATINDEX('%[^0-9]%', @value collate SQL_Latin1_General_CP850_Bin)>0 + INSERT INTO @hierarchy + (NAME, SequenceNo, parent_ID, StringValue, ValueType) + SELECT @name, @SequenceNo, @parent_ID, @value, 'real' + ELSE + INSERT INTO @hierarchy + (NAME, SequenceNo, parent_ID, StringValue, ValueType) + SELECT @name, @SequenceNo, @parent_ID, @value, 'int' + if @Contents=' ' Select @SequenceNo=0 + END + END +INSERT INTO @hierarchy (NAME, SequenceNo, parent_ID, StringValue, Object_ID, ValueType) + SELECT '-',1, NULL, '', @parent_id-1, @type +-- + RETURN +END +GO + + +--------------------------------------------- + +-- dbo.ufn_GetS3ACLByUserGuid +CREATE FUNCTION dbo.ufn_GetS3ACLByUserGuid +( + @UserGuid UNIQUEIDENTIFIER +) +RETURNS TABLE +WITH SCHEMABINDING +AS +RETURN +( + SELECT + acl.LootID, + acl.LootGroupPrefix, + case when sum(acl.ReadAllowpts) > sum(acl.ReadDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsReadable, + case when sum(acl.WriteAllowpts) > sum(acl.WriteDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsWritable, + case when sum(acl.SecureAllowpts) > sum(acl.SecureDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsSecurable, + case when sum(acl.DeleteAllowpts) > sum(acl.DeleteDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsDeletable, + case when sum(acl.CreateAllowpts) > sum(acl.CreateDenypts) then CAST(1 as bit) else CAST(0 as bit) end as IsCreatable + FROM + ( + SELECT + L.LootID, + L.LootGroupPrefix, + ReadAllowPts, + ReadDenyPts, + WriteAllowPts, + WriteDenyPts, + SecureAllowPts, + SecureDenyPts, + DeleteAllowPts, + DeleteDenyPts, + CreateAllowPts, + CreateDenyPts + FROM + dbo.S3LootGroup LG WITH (READUNCOMMITTED) + INNER JOIN dbo.S3Loot L WITH (READUNCOMMITTED) ON L.LootID = LG.LootID + INNER JOIN dbo.S3RoleAssignment RA WITH (READUNCOMMITTED) ON LG.LootGroupID = RA.LootGroupID + INNER JOIN dbo.S3Permission P WITH (READUNCOMMITTED) ON RA.RoleID = P.RoleID and L.PermissionSetID = P.PermissionSetID + INNER JOIN dbo.S3IdentityLink il WITH (READUNCOMMITTED) ON RA.identityguid = il.GroupingGUID + WHERE il.MemberGUID = @UserGuid + ) AS acl + + + GROUP BY + acl.LootID, + acl.LootGroupPrefix +); +GO + + +--------------------------------------------- + +-- dbo.ufn_GetS3ACLSimpleReadable +CREATE FUNCTION dbo.ufn_GetS3ACLSimpleReadable +( + @UserGuid UNIQUEIDENTIFIER +) +RETURNS TABLE +AS +RETURN +( + SELECT DISTINCT P.LootID + FROM dbo.UserProfile U WITH (READUNCOMMITTED) + INNER JOIN dbo.S3IdentityLink IL WITH (READUNCOMMITTED) + ON U.UserGUID = IL.MemberGUID + INNER JOIN dbo.S3SimplePermission P WITH (READUNCOMMITTED) + ON P.IdentityGUID = IL.GroupingGUID + WHERE U.UserGUID = @UserGuid AND P.ReadValue = 1 +); +GO + + +--------------------------------------------- + diff --git a/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements_small.sql new file mode 100644 index 0000000..446b5a6 --- /dev/null +++ b/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements_small.sql @@ -0,0 +1,38 @@ +-- SCHEMA: dbo + +--------------------------------------------- +-- TABLES +--------------------------------------------- + + +--------------------------------------------- +-- dbo.AMAssumptionView ------------------ +--------------------------------------------- +CREATE TABLE [dbo].[AMAssumptionView] ( + [AssumptionViewGUID] uniqueidentifier NOT NULL, + [AssumptionGroupGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(450) NOT NULL, + [ColumnWidths] varchar(8000) NOT NULL, + [AssumptionJoinDataGUID] uniqueidentifier NOT NULL, + [FolderGUID] uniqueidentifier NOT NULL, + [IsDistributionModeActive] bit NOT NULL, + [DistributionInfo] xml(max) NOT NULL, + [ProviderGUID] uniqueidentifier NOT NULL, + [CreatedDate] datetime NOT NULL, + [CreatedBy] uniqueidentifier NOT NULL, + [LastUsedDate] datetime NOT NULL, + PRIMARY KEY ([AssumptionViewGUID]) +); +GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_CreatedBy] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CreatedBy]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_CreatedDate] DEFAULT (getdate()) FOR [CreatedDate]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_LastUsedDate] DEFAULT (getdate()) FOR [LastUsedDate]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_Table_1_AssumptionViewGUID] DEFAULT (newid()) FOR [AssumptionViewGUID]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_ASSUMPTIONGROUPGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssumptionGroupGUID]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_NAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_COLUMNWIDTHS] DEFAULT ('') FOR [ColumnWidths]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_ASSUMPTIONCUBEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssumptionJoinDataGUID]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_FOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_ISDISTRIBUTIONMODEACTIVE] DEFAULT ((0)) FOR [IsDistributionModeActive]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_DISTRIBUTIONINFOXML] DEFAULT ('') FOR [DistributionInfo]; GO +ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_PROVIDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ProviderGUID]; GO diff --git a/ef-migration/infrastructure/sql-server/schemas/fp_schema_database_statements.sql b/ef-migration/infrastructure/sql-server/schemas/fp_schema_database_statements.sql new file mode 100644 index 0000000..1deece3 --- /dev/null +++ b/ef-migration/infrastructure/sql-server/schemas/fp_schema_database_statements.sql @@ -0,0 +1,126102 @@ +-- SCHEMA: fp + +--------------------------------------------- +-- TABLES +--------------------------------------------- + + +--------------------------------------------- +-- fp.APAdminPerformanceTest ------------------ +--------------------------------------------- +CREATE TABLE [fp].[APAdminPerformanceTest] ( + [TestID] uniqueidentifier NOT NULL, + [SortOrder] int NOT NULL, + [TestTypeID] tinyint NOT NULL, + [TestName] nvarchar(100) NOT NULL, + [Description] nvarchar(3000) NOT NULL, + [BudgetConfigID] int NOT NULL, + [SourceDimensionalityJSON] nvarchar(max) NOT NULL, + [TestDetailJSON] nvarchar(max) NOT NULL, + [IsActive] bit NOT NULL, + [CreatedBy] nvarchar(1000) NOT NULL, + [Target] int NOT NULL, + [MaximumTheshold] int NOT NULL, + [PickableDepartments] nvarchar(max) NOT NULL, + PRIMARY KEY ([TestID]) +); +GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Targe__5375AD4D] DEFAULT ((0)) FOR [Target]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Maxim__5469D186] DEFAULT ((0)) FOR [MaximumTheshold]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Picka__565219F8] DEFAULT ('') FOR [PickableDepartments]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__TestI__6B4249E6] DEFAULT (newid()) FOR [TestID]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__SortO__6C366E1F] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__TestT__6D2A9258] DEFAULT ((0)) FOR [TestTypeID]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__TestN__6E1EB691] DEFAULT ('') FOR [TestName]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Descr__6F12DACA] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Budge__70FB233C] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Sourc__71EF4775] DEFAULT ('') FOR [SourceDimensionalityJSON]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__TestD__72E36BAE] DEFAULT ('') FOR [TestDetailJSON]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__IsAct__73D78FE7] DEFAULT ((0)) FOR [IsActive]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Creat__74CBB420] DEFAULT ('') FOR [CreatedBy]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.APAdminPerformanceTestResults ------------------ +--------------------------------------------- +CREATE TABLE [fp].[APAdminPerformanceTestResults] ( + [TestID] uniqueidentifier NOT NULL, + [StartDate] datetime NOT NULL, + [EndDate] datetime NOT NULL, + [Status] tinyint NOT NULL, + [ErrorDetails] nvarchar(max) NOT NULL +); +GO +ALTER TABLE [fp].[APAdminPerformanceTestResults] ADD CONSTRAINT [FK__APAdminPe__TestI__7B78B1AF] FOREIGN KEY ([TestID]) REFERENCES [fp].[APAdminPerformanceTest] ([TestID]); GO +ALTER TABLE [fp].[APAdminPerformanceTestResults] ADD CONSTRAINT [DF__APAdminPe__TestI__76B3FC92] DEFAULT (newid()) FOR [TestID]; GO +ALTER TABLE [fp].[APAdminPerformanceTestResults] ADD CONSTRAINT [DF__APAdminPe__Start__77A820CB] DEFAULT (getdate()) FOR [StartDate]; GO +ALTER TABLE [fp].[APAdminPerformanceTestResults] ADD CONSTRAINT [DF__APAdminPe__EndDa__789C4504] DEFAULT (getdate()) FOR [EndDate]; GO +ALTER TABLE [fp].[APAdminPerformanceTestResults] ADD CONSTRAINT [DF__APAdminPe__Statu__7990693D] DEFAULT ((0)) FOR [Status]; GO +ALTER TABLE [fp].[APAdminPerformanceTestResults] ADD CONSTRAINT [DF__APAdminPe__Error__7A848D76] DEFAULT ('') FOR [ErrorDetails]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.APEDepartmentWorkflowStatus ------------------ +--------------------------------------------- +CREATE TABLE [fp].[APEDepartmentWorkflowStatus] ( + [DepartmentWorkflowStatusID] int NOT NULL, + [WorkflowStepID] int NOT NULL, + [DepartmentID] int NOT NULL, + [Status] tinyint NOT NULL, + [EnteredStepDateTimeUtc] datetime NOT NULL, + PRIMARY KEY ([DepartmentWorkflowStatusID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [UC_APEDepartmentWorkflowStatus_DepartmentID_WorkflowStepID] ON [fp].[APEDepartmentWorkflowStatus] ([DepartmentID], [WorkflowStepID]); +GO +ALTER TABLE [fp].[APEDepartmentWorkflowStatus] ADD CONSTRAINT [FK__APEDepart__Workf__0232CC71] FOREIGN KEY ([WorkflowStepID]) REFERENCES [fp].[APEWorkflow] ([WorkflowStepID]); GO +ALTER TABLE [fp].[APEDepartmentWorkflowStatus] ADD CONSTRAINT [DF__APEDepart__Workf__013EA838] DEFAULT ((0)) FOR [WorkflowStepID]; GO +ALTER TABLE [fp].[APEDepartmentWorkflowStatus] ADD CONSTRAINT [DF__APEDepart__Depar__0326F0AA] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[APEDepartmentWorkflowStatus] ADD CONSTRAINT [DF__APEDepart__Enter__384D811C] DEFAULT (getutcdate()) FOR [EnteredStepDateTimeUtc]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.APEEntityGroupConfigSetting ------------------ +--------------------------------------------- +CREATE TABLE [fp].[APEEntityGroupConfigSetting] ( + [EntityGroupConfigID] int NOT NULL, + [IsSalaryWageRateHidden] bit NOT NULL, + [AdminRoleID] int NOT NULL, + PRIMARY KEY ([EntityGroupConfigID]) +); +GO +ALTER TABLE [fp].[APEEntityGroupConfigSetting] ADD CONSTRAINT [DF__APEEntity__Admin__191631C9] DEFAULT ((0)) FOR [AdminRoleID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.APESectionRoleAccess ------------------ +--------------------------------------------- +CREATE TABLE [fp].[APESectionRoleAccess] ( + [SectionRoleAccessID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [Section] nvarchar(100) NOT NULL, + [RoleID] int NOT NULL, + [AccessType] int NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + PRIMARY KEY ([SectionRoleAccessID]) +); +GO +ALTER TABLE [fp].[APESectionRoleAccess] ADD CONSTRAINT [DF__APESectio__Entit__135D5873] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[APESectionRoleAccess] ADD CONSTRAINT [DF__APESectio__Secti__14517CAC] DEFAULT ('') FOR [Section]; GO +ALTER TABLE [fp].[APESectionRoleAccess] ADD CONSTRAINT [DF__APESectio__RoleI__1545A0E5] DEFAULT ((0)) FOR [RoleID]; GO +ALTER TABLE [fp].[APESectionRoleAccess] ADD CONSTRAINT [DF__APESectio__Acces__1639C51E] DEFAULT ((0)) FOR [AccessType]; GO +ALTER TABLE [fp].[APESectionRoleAccess] ADD CONSTRAINT [DF_APESectionRoleAccess_BudgetPhaseID] DEFAULT ((3)) FOR [BudgetPhaseID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.APEViewConfig ------------------ +--------------------------------------------- +CREATE TABLE [fp].[APEViewConfig] ( + [RowID] bigint NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [ViewName] varchar(35) NOT NULL, + [PivotConfiguration] varchar(max) NOT NULL, + [MeasuresConfiguration] varchar(max) NOT NULL, + [HasFilters] bit NOT NULL, + [ModifiedDate] datetime NOT NULL, + [IsShareable] bit NULL, + [PlanSectionID] int NOT NULL, + [SubsectionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [FK_APEViewConfig_PlanSection] FOREIGN KEY ([PlanSectionID]) REFERENCES [fp].[PlanSection] ([PlanSectionID]); GO +ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [FK_APEViewConfig_PlanSubsection] FOREIGN KEY ([SubsectionID]) REFERENCES [fp].[PlanSubsection] ([SubsectionID]); GO +ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [DF__APEViewCo__UserG__0F14CAB1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [DF__APEViewCo__ViewN__10FD1323] DEFAULT ('') FOR [ViewName]; GO +ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [DF__APEViewCo__Pivot__11F1375C] DEFAULT ('') FOR [PivotConfiguration]; GO +ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [DF__APEViewCo__Measu__12E55B95] DEFAULT ('') FOR [MeasuresConfiguration]; GO +ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [DF__APEViewCo__HasFi__13D97FCE] DEFAULT ((0)) FOR [HasFilters]; GO +ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [DF__APEViewCo__PlanS__149AFBE2] DEFAULT ((0)) FOR [PlanSectionID]; GO +ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [DF__APEViewCo__Modif__14CDA407] DEFAULT (getdate()) FOR [ModifiedDate]; GO +ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [DF__APEViewCo__Subse__16834454] DEFAULT ((0)) FOR [SubsectionID]; GO +ALTER TABLE [fp].[APEViewConfig] ADD CONSTRAINT [DF__APEViewCo__IsSha__28770C06] DEFAULT ((1)) FOR [IsShareable]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.APEWorkflow ------------------ +--------------------------------------------- +CREATE TABLE [fp].[APEWorkflow] ( + [WorkflowStepID] int NOT NULL, + [Name] nvarchar(100) NOT NULL, + [RoleID] int NOT NULL, + [WorkflowStepOrder] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [IsEditable] bit NOT NULL, + [IsNotificationEnabled] bit NOT NULL, + PRIMARY KEY ([WorkflowStepID]) +); +GO +ALTER TABLE [fp].[APEWorkflow] ADD CONSTRAINT [DF__APEWorkfl__Entit__050F391C] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[APEWorkflow] ADD CONSTRAINT [DF__APEWorkfl__IsEdi__172DE957] DEFAULT ((0)) FOR [IsEditable]; GO +ALTER TABLE [fp].[APEWorkflow] ADD CONSTRAINT [DF__APEWorkfl__IsNot__53D8CD5C] DEFAULT ((0)) FOR [IsNotificationEnabled]; GO +ALTER TABLE [fp].[APEWorkflow] ADD CONSTRAINT [DF__APEWorkflo__Name__56544A33] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fp].[APEWorkflow] ADD CONSTRAINT [DF__APEWorkfl__RoleI__583C92A5] DEFAULT ((0)) FOR [RoleID]; GO +ALTER TABLE [fp].[APEWorkflow] ADD CONSTRAINT [DF__APEWorkfl__Workf__5930B6DE] DEFAULT ((0)) FOR [WorkflowStepOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.APEWorkflowReviewStatusLog ------------------ +--------------------------------------------- +CREATE TABLE [fp].[APEWorkflowReviewStatusLog] ( + [ReviewStatusLogID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [TargetWorkflowStepID] int NOT NULL, + [TargetWorkflowStepName] varchar(100) NOT NULL, + [Status] tinyint NOT NULL, + [Comment] nvarchar(4000) NOT NULL, + [SourceWorkflowStepID] int NOT NULL, + [SourceWorkflowStepName] varchar(100) NOT NULL, + [TimeStampUtc] datetime NOT NULL, + PRIMARY KEY ([ReviewStatusLogID]) +); +GO +ALTER TABLE [fp].[APEWorkflowReviewStatusLog] ADD CONSTRAINT [DF__APEWorkfl__Targe__07EBA5C7] DEFAULT ('') FOR [TargetWorkflowStepName]; GO +ALTER TABLE [fp].[APEWorkflowReviewStatusLog] ADD CONSTRAINT [DF__APEWorkfl__Comme__1BF29E74] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[APEWorkflowReviewStatusLog] ADD CONSTRAINT [DF__APEWorkfl__Sourc__1CE6C2AD] DEFAULT ((0)) FOR [SourceWorkflowStepID]; GO +ALTER TABLE [fp].[APEWorkflowReviewStatusLog] ADD CONSTRAINT [DF__APEWorkfl__Sourc__1DDAE6E6] DEFAULT ('') FOR [SourceWorkflowStepName]; GO +ALTER TABLE [fp].[APEWorkflowReviewStatusLog] ADD CONSTRAINT [DF__APEWorkfl__TimeS__37595CE3] DEFAULT (getutcdate()) FOR [TimeStampUtc]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.APEWorkflowRole ------------------ +--------------------------------------------- +CREATE TABLE [fp].[APEWorkflowRole] ( + [WorkflowRoleID] int NOT NULL, + [WorkflowStepID] int NOT NULL, + [RoleID] int NOT NULL, + PRIMARY KEY ([WorkflowRoleID]) +); +GO +ALTER TABLE [fp].[APEWorkflowRole] ADD CONSTRAINT [FK__APEWorkfl__Workf__7D6E1754] FOREIGN KEY ([WorkflowStepID]) REFERENCES [fp].[APEWorkflow] ([WorkflowStepID]); GO +ALTER TABLE [fp].[APEWorkflowRole] ADD CONSTRAINT [DF__APEWorkfl__Workf__7C79F31B] DEFAULT ((0)) FOR [WorkflowStepID]; GO +ALTER TABLE [fp].[APEWorkflowRole] ADD CONSTRAINT [DF__APEWorkfl__RoleI__7E623B8D] DEFAULT ((0)) FOR [RoleID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.AccountFlexConfig ------------------ +--------------------------------------------- +CREATE TABLE [fp].[AccountFlexConfig] ( + [FlexConfigGUID] uniqueidentifier NOT NULL, + [AccountID] int NOT NULL, + [FlexMethodClassName] nvarchar(100) NOT NULL, + [EntityGroupConfigGUID] uniqueidentifier NOT NULL, + [IsUsingTrailing12] bit NOT NULL, + PRIMARY KEY ([FlexConfigGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[AccountFlexConfig] ([AccountID], [EntityGroupConfigGUID]); +GO +ALTER TABLE [fp].[AccountFlexConfig] ADD CONSTRAINT [DF__AccountFl__IsUsi__2FAC82CC] DEFAULT ((0)) FOR [IsUsingTrailing12]; GO +ALTER TABLE [fp].[AccountFlexConfig] ADD CONSTRAINT [DF__AccountFl__FlexC__3E0D1CED] DEFAULT (newid()) FOR [FlexConfigGUID]; GO +ALTER TABLE [fp].[AccountFlexConfig] ADD CONSTRAINT [DF__AccountFl__Accou__3F014126] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[AccountFlexConfig] ADD CONSTRAINT [DF__AccountFl__FlexM__3FF5655F] DEFAULT ('') FOR [FlexMethodClassName]; GO +ALTER TABLE [fp].[AccountFlexConfig] ADD CONSTRAINT [df_AccountFlexConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.AccountFlexConfigAssignment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[AccountFlexConfigAssignment] ( + [FlexConfigAssignmentGUID] uniqueidentifier NOT NULL, + [FlexConfigGUID] uniqueidentifier NOT NULL, + [JobCodeAssignment] nvarchar(400) NOT NULL, + [PayCodeGroupAssignment] nvarchar(400) NOT NULL, + PRIMARY KEY ([FlexConfigAssignmentGUID]) +); +GO +ALTER TABLE [fp].[AccountFlexConfigAssignment] ADD CONSTRAINT [FK__AccountFl__FlexC__46A262EE] FOREIGN KEY ([FlexConfigGUID]) REFERENCES [fp].[AccountFlexConfig] ([FlexConfigGUID]); GO +ALTER TABLE [fp].[AccountFlexConfigAssignment] ADD CONSTRAINT [DF__AccountFl__FlexC__42D1D20A] DEFAULT (newid()) FOR [FlexConfigAssignmentGUID]; GO +ALTER TABLE [fp].[AccountFlexConfigAssignment] ADD CONSTRAINT [DF__AccountFl__FlexC__43C5F643] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FlexConfigGUID]; GO +ALTER TABLE [fp].[AccountFlexConfigAssignment] ADD CONSTRAINT [DF__AccountFl__JobCo__44BA1A7C] DEFAULT ('') FOR [JobCodeAssignment]; GO +ALTER TABLE [fp].[AccountFlexConfigAssignment] ADD CONSTRAINT [DF__AccountFl__PayCo__45AE3EB5] DEFAULT ('') FOR [PayCodeGroupAssignment]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.AccountOBForecastDetailMapping ------------------ +--------------------------------------------- +CREATE TABLE [fp].[AccountOBForecastDetailMapping] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [AccountID] int NOT NULL, + [OBForecastDetailID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [CLU_AcctOBForecastDetail_ndx] ON [fp].[AccountOBForecastDetailMapping] ([BudgetConfigID], [AccountID], [OBForecastDetailID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_ClusteredUnique] ON [fp].[AccountOBForecastDetailMapping] ([BudgetConfigID], [AccountID], [OBForecastDetailID]); +GO +ALTER TABLE [fp].[AccountOBForecastDetailMapping] ADD CONSTRAINT [DF__AccountOB__Budge__6E8D8EEF] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[AccountOBForecastDetailMapping] ADD CONSTRAINT [DF__AccountOB__Accou__6F81B328] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[AccountOBForecastDetailMapping] ADD CONSTRAINT [DF__AccountOB__OBFor__7075D761] DEFAULT ((0)) FOR [OBForecastDetailID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.AddProviderEncountersDataForCharges ------------------ +--------------------------------------------- +CREATE TABLE [fp].[AddProviderEncountersDataForCharges] ( + [AddProviderEncountersDataForChargesID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [PatientClassID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [UnitTypeID] int NOT NULL, + [ServiceEntityID] int NOT NULL, + [MSDRGID] int NOT NULL, + [UBRevCodeID] int NOT NULL, + [PrimaryCPTID] int NOT NULL, + [ServiceProviderID] int NOT NULL, + [ServiceProviderSpecialtyID] int NOT NULL, + [PerformingProviderID] int NOT NULL, + [PerformingProviderSpecialtyID] int NOT NULL, + [BillingCPTID] int NOT NULL, + [IsProcessed] bit NOT NULL, + PRIMARY KEY ([AddProviderEncountersDataForChargesID]) +); +GO +ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [FK__AddProvid__Adjus__6B6F9474] FOREIGN KEY ([AdjustmentGUID]) REFERENCES [fp].[DepartmentChargeVolumeAdjustment] ([AdjustmentGUID]); GO +ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Adjus__6A7B703B] DEFAULT (newid()) FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Budge__6C63B8AD] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Entit__6D57DCE6] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Depar__6E4C011F] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Servi__6F402558] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Patie__70344991] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Charg__71286DCA] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__AgeCo__721C9203] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Medic__7310B63C] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__UnitT__7404DA75] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Servi__74F8FEAE] DEFAULT ((0)) FOR [ServiceEntityID]; GO +ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__MSDRG__75ED22E7] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__UBRev__76E14720] DEFAULT ((0)) FOR [UBRevCodeID]; GO +ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Prima__77D56B59] DEFAULT ((0)) FOR [PrimaryCPTID]; GO +ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Servi__78C98F92] DEFAULT ((0)) FOR [ServiceProviderID]; GO +ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Servi__79BDB3CB] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO +ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Perfo__7AB1D804] DEFAULT ((0)) FOR [PerformingProviderID]; GO +ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Perfo__7BA5FC3D] DEFAULT ((0)) FOR [PerformingProviderSpecialtyID]; GO +ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__Billi__7E8268E8] DEFAULT ((0)) FOR [BillingCPTID]; GO +ALTER TABLE [fp].[AddProviderEncountersDataForCharges] ADD CONSTRAINT [DF__AddProvid__IsPro__7F768D21] DEFAULT ((0)) FOR [IsProcessed]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.AddProviderSummary ------------------ +--------------------------------------------- +CREATE TABLE [fp].[AddProviderSummary] ( + [SummaryID] int NOT NULL, + [SLEncounterAdjustmentGUID] uniqueidentifier NULL, + [DCVolumeAdjustmentGUID] uniqueidentifier NULL, + [EmployeeType] int NOT NULL, + [EmployeeID] int NULL, + [ProviderID] int NULL, + [ProviderType] int NOT NULL, + [Specialty] int NOT NULL, + [StartDateUTC] datetime NOT NULL, + [BenchmarkAverage] decimal NOT NULL, + [ProjectionTotal] decimal NOT NULL, + [BudgetTotal] decimal NOT NULL, + [BenchmarkProvidersJSON] nvarchar(max) NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [ClassificationGroupID] int NOT NULL, + [ClassificationCategoryID] int NOT NULL, + PRIMARY KEY ([SummaryID]) +); + +CREATE NONCLUSTERED INDEX [IX_AddProviderSummary_LinkedAdjustments] ON [fp].[AddProviderSummary] ([SLEncounterAdjustmentGUID], [DCVolumeAdjustmentGUID]); +GO +ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [FK__AddProvid__Emplo__0ADBBC27] FOREIGN KEY ([EmployeeID]) REFERENCES [fw].[DimEmployee] ([EmployeeID]); GO +ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [FK__AddProvid__Provi__0BCFE060] FOREIGN KEY ([ProviderID]) REFERENCES [dss].[DimPhysician] ([PhysicianID]); GO +ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [FK__AddProvid__SLEnc__07FF4F7C] FOREIGN KEY ([SLEncounterAdjustmentGUID]) REFERENCES [fp].[ServiceLineEncounterAdjustment] ([AdjustmentGUID]); GO +ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Emplo__09E797EE] DEFAULT ((0)) FOR [EmployeeType]; GO +ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Provi__0CC40499] DEFAULT ((0)) FOR [ProviderType]; GO +ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Speci__0DB828D2] DEFAULT ((0)) FOR [Specialty]; GO +ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Start__0EAC4D0B] DEFAULT (getdate()) FOR [StartDateUTC]; GO +ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Bench__0FA07144] DEFAULT ((0)) FOR [BenchmarkAverage]; GO +ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Proje__1094957D] DEFAULT ((0)) FOR [ProjectionTotal]; GO +ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Budge__1188B9B6] DEFAULT ((0)) FOR [BudgetTotal]; GO +ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Bench__127CDDEF] DEFAULT ('') FOR [BenchmarkProvidersJSON]; GO +ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Comme__13710228] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Class__14652661] DEFAULT ((0)) FOR [ClassificationGroupID]; GO +ALTER TABLE [fp].[AddProviderSummary] ADD CONSTRAINT [DF__AddProvid__Class__15594A9A] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.AdjustmentChunkingConfiguration ------------------ +--------------------------------------------- +CREATE TABLE [fp].[AdjustmentChunkingConfiguration] ( + [SectionID] int NOT NULL, + [Description] nvarchar(100) NOT NULL, + [IsChunkingEnabled] bit NOT NULL, + [MaxAdjustmentsPerChunk] int NOT NULL, + [MaxImportAdjustmentsPerChunk] int NOT NULL, + [MaxAdjustmentRecordCountForChunking] int NOT NULL, + PRIMARY KEY ([SectionID]) +); +GO +ALTER TABLE [fp].[AdjustmentChunkingConfiguration] ADD CONSTRAINT [DF__Adjustmen__Secti__154F28F9] DEFAULT ((0)) FOR [SectionID]; GO +ALTER TABLE [fp].[AdjustmentChunkingConfiguration] ADD CONSTRAINT [DF__Adjustmen__Descr__16434D32] DEFAULT ((0)) FOR [Description]; GO +ALTER TABLE [fp].[AdjustmentChunkingConfiguration] ADD CONSTRAINT [DF__Adjustmen__IsChu__1737716B] DEFAULT ((0)) FOR [IsChunkingEnabled]; GO +ALTER TABLE [fp].[AdjustmentChunkingConfiguration] ADD CONSTRAINT [DF__Adjustmen__MaxAd__182B95A4] DEFAULT ((0)) FOR [MaxAdjustmentsPerChunk]; GO +ALTER TABLE [fp].[AdjustmentChunkingConfiguration] ADD CONSTRAINT [DF__Adjustmen__MaxIm__191FB9DD] DEFAULT ((0)) FOR [MaxImportAdjustmentsPerChunk]; GO +ALTER TABLE [fp].[AdjustmentChunkingConfiguration] ADD CONSTRAINT [DF__Adjustmen__MaxAd__1A13DE16] DEFAULT ((0)) FOR [MaxAdjustmentRecordCountForChunking]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.AdjustmentClassificationCategory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[AdjustmentClassificationCategory] ( + [CategoryID] int NOT NULL, + [GroupID] int NOT NULL, + [Name] nvarchar(30) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([CategoryID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [UQ_FP_AdjustmentClassificationCategory_GroupID_Name] ON [fp].[AdjustmentClassificationCategory] ([GroupID], [Name]); +GO +ALTER TABLE [fp].[AdjustmentClassificationCategory] ADD CONSTRAINT [FK_AdjustmentClassificationCategory_GroupID] FOREIGN KEY ([GroupID]) REFERENCES [fp].[AdjustmentClassificationGroup] ([GroupID]); GO +ALTER TABLE [fp].[AdjustmentClassificationCategory] ADD CONSTRAINT [DF__Adjustmen__Group__48583505] DEFAULT ((0)) FOR [GroupID]; GO +ALTER TABLE [fp].[AdjustmentClassificationCategory] ADD CONSTRAINT [DF__Adjustment__Name__494C593E] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fp].[AdjustmentClassificationCategory] ADD CONSTRAINT [DF__Adjustmen__Membe__49E2ECC9] DEFAULT (newid()) FOR [MemberGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.AdjustmentClassificationGroup ------------------ +--------------------------------------------- +CREATE TABLE [fp].[AdjustmentClassificationGroup] ( + [GroupID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [Name] nvarchar(30) NOT NULL, + [IsEncounterVisible] bit NOT NULL, + [IsChargesVisible] bit NOT NULL, + [IsStatisticsVisible] bit NOT NULL, + [IsStaffingVisible] bit NOT NULL, + [IsBenefitsVisible] bit NOT NULL, + [IsGeneralLedgerVisible] bit NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [IsProviderCompensationVisible] bit NOT NULL, + PRIMARY KEY ([GroupID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [UQ_FP_AdjustmentClassificationGroup_BudgetConfigID_Name] ON [fp].[AdjustmentClassificationGroup] ([BudgetConfigID], [Name]); +GO +ALTER TABLE [fp].[AdjustmentClassificationGroup] ADD CONSTRAINT [DF__Adjustmen__isPro__67B41229] DEFAULT ((0)) FOR [IsProviderCompensationVisible]; GO +ALTER TABLE [fp].[AdjustmentClassificationGroup] ADD CONSTRAINT [DF__Adjustmen__Budge__3DDAA692] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[AdjustmentClassificationGroup] ADD CONSTRAINT [DF__Adjustment__Name__3ECECACB] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fp].[AdjustmentClassificationGroup] ADD CONSTRAINT [DF__Adjustmen__IsEnc__3FC2EF04] DEFAULT ((0)) FOR [IsEncounterVisible]; GO +ALTER TABLE [fp].[AdjustmentClassificationGroup] ADD CONSTRAINT [DF__Adjustmen__IsCha__40B7133D] DEFAULT ((0)) FOR [IsChargesVisible]; GO +ALTER TABLE [fp].[AdjustmentClassificationGroup] ADD CONSTRAINT [DF__Adjustmen__IsSta__41AB3776] DEFAULT ((0)) FOR [IsStatisticsVisible]; GO +ALTER TABLE [fp].[AdjustmentClassificationGroup] ADD CONSTRAINT [DF__Adjustmen__IsSta__429F5BAF] DEFAULT ((0)) FOR [IsStaffingVisible]; GO +ALTER TABLE [fp].[AdjustmentClassificationGroup] ADD CONSTRAINT [DF__Adjustmen__Membe__4335EF3A] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fp].[AdjustmentClassificationGroup] ADD CONSTRAINT [DF__Adjustmen__IsBen__43937FE8] DEFAULT ((0)) FOR [IsBenefitsVisible]; GO +ALTER TABLE [fp].[AdjustmentClassificationGroup] ADD CONSTRAINT [DF__Adjustmen__IsGen__4487A421] DEFAULT ((0)) FOR [IsGeneralLedgerVisible]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.AdjustmentGrouping ------------------ +--------------------------------------------- +CREATE TABLE [fp].[AdjustmentGrouping] ( + [GroupingGUID] uniqueidentifier NOT NULL, + [Description] nvarchar(max) NOT NULL, + [ExcelFile] varbinary(max) NULL, + [IsRecordDeleted] bit NOT NULL, + PRIMARY KEY ([GroupingGUID]) +); +GO +ALTER TABLE [fp].[AdjustmentGrouping] ADD CONSTRAINT [DF__Adjustmen__IsRec__0967A9AA] DEFAULT ((0)) FOR [IsRecordDeleted]; GO +ALTER TABLE [fp].[AdjustmentGrouping] ADD CONSTRAINT [DF__Adjustmen__Group__722CAAC8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[AdjustmentGrouping] ADD CONSTRAINT [DF__Adjustmen__Descr__7320CF01] DEFAULT ('') FOR [Description]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.AdjustmentImpactReportBatchConfiguration ------------------ +--------------------------------------------- +CREATE TABLE [fp].[AdjustmentImpactReportBatchConfiguration] ( + [BatchID] int NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [TotalRowCount] int NOT NULL, + PRIMARY KEY ([BatchID], [EntityID], [PatientClassID], [MedicalSurgicalID]) +); +GO +ALTER TABLE [fp].[AdjustmentImpactReportBatchConfiguration] ADD CONSTRAINT [DF__Adjustmen__Batch__37078484] DEFAULT ((0)) FOR [BatchID]; GO +ALTER TABLE [fp].[AdjustmentImpactReportBatchConfiguration] ADD CONSTRAINT [DF__Adjustmen__Entit__37FBA8BD] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[AdjustmentImpactReportBatchConfiguration] ADD CONSTRAINT [DF__Adjustmen__Patie__38EFCCF6] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[AdjustmentImpactReportBatchConfiguration] ADD CONSTRAINT [DF__Adjustmen__Medic__39E3F12F] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[AdjustmentImpactReportBatchConfiguration] ADD CONSTRAINT [DF__Adjustmen__Total__3AD81568] DEFAULT ((0)) FOR [TotalRowCount]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.AdjustmentImpactReportPendingAdjustments ------------------ +--------------------------------------------- +CREATE TABLE [fp].[AdjustmentImpactReportPendingAdjustments] ( + [AdjustmentGUID] uniqueidentifier NOT NULL +); +GO +ALTER TABLE [fp].[AdjustmentImpactReportPendingAdjustments] ADD CONSTRAINT [DF__Adjustmen__Adjus__052F6677] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.AdjustmentImpactReport_Batches ------------------ +--------------------------------------------- +CREATE TABLE [fp].[AdjustmentImpactReport_Batches] ( + [SortOrder] int NOT NULL, + [ReportExecutionGUID] uniqueidentifier NOT NULL, + [BatchID] int NOT NULL, + [IsInitial] bit NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [ServiceLineID] int NOT NULL +); +GO +ALTER TABLE [fp].[AdjustmentImpactReport_Batches] ADD CONSTRAINT [DF__Adjustmen__Repor__5A5A170B] DEFAULT (newid()) FOR [ReportExecutionGUID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_Batches] ADD CONSTRAINT [DF__Adjustmen__Batch__5B4E3B44] DEFAULT ((0)) FOR [BatchID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_Batches] ADD CONSTRAINT [DF__Adjustmen__IsIni__5C425F7D] DEFAULT ((0)) FOR [IsInitial]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_Batches] ADD CONSTRAINT [DF__Adjustmen__Entit__5D3683B6] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_Batches] ADD CONSTRAINT [DF__Adjustmen__Patie__5E2AA7EF] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_Batches] ADD CONSTRAINT [DF__Adjustmen__Servi__5F1ECC28] DEFAULT ((0)) FOR [ServiceLineID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.AdjustmentImpactReport_CombineChargeEncounterAndPrice ------------------ +--------------------------------------------- +CREATE TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ( + [ReportExecutionGUID] uniqueidentifier NOT NULL, + [BatchID] int NOT NULL, + [IsInitial] bit NOT NULL, + [Charge_ChargeVolumeID] int NOT NULL, + [Charge_BudgetConfigID] int NOT NULL, + [Charge_EntityGroupConfigID] int NOT NULL, + [Charge_EntityID] int NOT NULL, + [Charge_DepartmentID] int NOT NULL, + [Charge_ChargeCodeID] int NOT NULL, + [Charge_PatientClassID] int NOT NULL, + [Charge_ServiceProviderSpecialtyID] int NOT NULL, + [Charge_PerformingProviderID] int NOT NULL, + [Charge_PerformingProviderSpecialtyID] int NOT NULL, + [Charge_UBRevCodeID] int NOT NULL, + [Charge_ChargeImpact01] decimal NOT NULL, + [Charge_ChargeImpact02] decimal NOT NULL, + [Charge_ChargeImpact03] decimal NOT NULL, + [Charge_ChargeImpact04] decimal NOT NULL, + [Charge_ChargeImpact05] decimal NOT NULL, + [Charge_ChargeImpact06] decimal NOT NULL, + [Charge_ChargeImpact07] decimal NOT NULL, + [Charge_ChargeImpact08] decimal NOT NULL, + [Charge_ChargeImpact09] decimal NOT NULL, + [Charge_ChargeImpact10] decimal NOT NULL, + [Charge_ChargeImpact11] decimal NOT NULL, + [Charge_ChargeImpact12] decimal NOT NULL, + [Encounter_ServiceLineEncounterID] int NOT NULL, + [Encounter_BudgetConfigID] int NOT NULL, + [Encounter_EntityGroupConfigID] int NOT NULL, + [Encounter_EntityID] int NOT NULL, + [Encounter_PatientClassID] int NOT NULL, + [Encounter_ServiceLineID] int NOT NULL, + [Encounter_ServiceLineRollupID] int NOT NULL, + [Encounter_AgeCohortID] int NOT NULL, + [Encounter_MedicalSurgicalID] int NOT NULL, + [Encounter_DepartmentID] int NOT NULL, + [Encounter_PayorID] int NOT NULL, + [Encounter_PayorGroupID] int NOT NULL, + [Encounter_MSDRGID] int NOT NULL, + [Encounter_CPTID] int NOT NULL, + [Encounter_ProviderID] int NOT NULL, + [Encounter_PhysicianSpecialtyID] int NOT NULL, + [Encounter_ServiceEntityID] int NOT NULL, + [Encounter_PrimaryCPTID] int NOT NULL, + [Encounter_ServiceProviderID] int NOT NULL, + [Encounter_IsInitialValue] bit NOT NULL, + [Encounter_AdjustmentGUID] uniqueidentifier NOT NULL, + [Encounter_TimeClassID] int NOT NULL, + [Encounter_BudgetPhaseID] int NOT NULL, + [Encounter_EncounterImpact01] decimal NOT NULL, + [Encounter_EncounterImpact02] decimal NOT NULL, + [Encounter_EncounterImpact03] decimal NOT NULL, + [Encounter_EncounterImpact04] decimal NOT NULL, + [Encounter_EncounterImpact05] decimal NOT NULL, + [Encounter_EncounterImpact06] decimal NOT NULL, + [Encounter_EncounterImpact07] decimal NOT NULL, + [Encounter_EncounterImpact08] decimal NOT NULL, + [Encounter_EncounterImpact09] decimal NOT NULL, + [Encounter_EncounterImpact10] decimal NOT NULL, + [Encounter_EncounterImpact11] decimal NOT NULL, + [Encounter_EncounterImpact12] decimal NOT NULL, + [Price_BaselineChargeRate] decimal NOT NULL, + [DollarImpact_ChargeImpact01] decimal NOT NULL, + [DollarImpact_ChargeImpact02] decimal NOT NULL, + [DollarImpact_ChargeImpact03] decimal NOT NULL, + [DollarImpact_ChargeImpact04] decimal NOT NULL, + [DollarImpact_ChargeImpact05] decimal NOT NULL, + [DollarImpact_ChargeImpact06] decimal NOT NULL, + [DollarImpact_ChargeImpact07] decimal NOT NULL, + [DollarImpact_ChargeImpact08] decimal NOT NULL, + [DollarImpact_ChargeImpact09] decimal NOT NULL, + [DollarImpact_ChargeImpact10] decimal NOT NULL, + [DollarImpact_ChargeImpact11] decimal NOT NULL, + [DollarImpact_ChargeImpact12] decimal NOT NULL +); +GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__007FBFF3] DEFAULT ((0)) FOR [Encounter_AgeCohortID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__0173E42C] DEFAULT ((0)) FOR [Encounter_MedicalSurgicalID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__02680865] DEFAULT ((0)) FOR [Encounter_DepartmentID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__035C2C9E] DEFAULT ((0)) FOR [Encounter_PayorID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__045050D7] DEFAULT ((0)) FOR [Encounter_PayorGroupID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__05447510] DEFAULT ((0)) FOR [Encounter_MSDRGID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__06389949] DEFAULT ((0)) FOR [Encounter_CPTID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__072CBD82] DEFAULT ((0)) FOR [Encounter_ProviderID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__0820E1BB] DEFAULT ((0)) FOR [Encounter_PhysicianSpecialtyID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__091505F4] DEFAULT ((0)) FOR [Encounter_ServiceEntityID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__0A092A2D] DEFAULT ((0)) FOR [Encounter_PrimaryCPTID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__0AFD4E66] DEFAULT ((0)) FOR [Encounter_ServiceProviderID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__0BF1729F] DEFAULT ((0)) FOR [Encounter_IsInitialValue]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__0CE596D8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [Encounter_AdjustmentGUID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__0DD9BB11] DEFAULT ((0)) FOR [Encounter_TimeClassID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__0ECDDF4A] DEFAULT ((0)) FOR [Encounter_BudgetPhaseID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__0FC20383] DEFAULT ((0)) FOR [Encounter_EncounterImpact01]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__10B627BC] DEFAULT ((0)) FOR [Encounter_EncounterImpact02]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__11AA4BF5] DEFAULT ((0)) FOR [Encounter_EncounterImpact03]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__129E702E] DEFAULT ((0)) FOR [Encounter_EncounterImpact04]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__13929467] DEFAULT ((0)) FOR [Encounter_EncounterImpact05]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__1486B8A0] DEFAULT ((0)) FOR [Encounter_EncounterImpact06]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__157ADCD9] DEFAULT ((0)) FOR [Encounter_EncounterImpact07]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__166F0112] DEFAULT ((0)) FOR [Encounter_EncounterImpact08]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__1763254B] DEFAULT ((0)) FOR [Encounter_EncounterImpact09]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__18574984] DEFAULT ((0)) FOR [Encounter_EncounterImpact10]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__194B6DBD] DEFAULT ((0)) FOR [Encounter_EncounterImpact11]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__1A3F91F6] DEFAULT ((0)) FOR [Encounter_EncounterImpact12]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Price__1B33B62F] DEFAULT ((0)) FOR [Price_BaselineChargeRate]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__1C27DA68] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact01]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__1D1BFEA1] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact02]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__1E1022DA] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact03]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__1F044713] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact04]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__20EC8F85] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact05]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__21E0B3BE] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact06]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__22D4D7F7] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact07]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__23C8FC30] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact08]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__24BD2069] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact09]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__25B144A2] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact10]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__26A568DB] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact11]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Dolla__27998D14] DEFAULT ((0)) FOR [DollarImpact_ChargeImpact12]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Repor__6107149A] DEFAULT (newid()) FOR [ReportExecutionGUID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Batch__61FB38D3] DEFAULT ((0)) FOR [BatchID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__IsIni__62EF5D0C] DEFAULT ((0)) FOR [IsInitial]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__63E38145] DEFAULT ((0)) FOR [Charge_ChargeVolumeID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__64D7A57E] DEFAULT ((0)) FOR [Charge_BudgetConfigID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__65CBC9B7] DEFAULT ((0)) FOR [Charge_EntityGroupConfigID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__66BFEDF0] DEFAULT ((0)) FOR [Charge_EntityID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__67B41229] DEFAULT ((0)) FOR [Charge_DepartmentID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__68A83662] DEFAULT ((0)) FOR [Charge_ChargeCodeID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__699C5A9B] DEFAULT ((0)) FOR [Charge_PatientClassID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__6A907ED4] DEFAULT ((0)) FOR [Charge_ServiceProviderSpecialtyID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__6B84A30D] DEFAULT ((0)) FOR [Charge_PerformingProviderID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__6C78C746] DEFAULT ((0)) FOR [Charge_PerformingProviderSpecialtyID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__6D6CEB7F] DEFAULT ((0)) FOR [Charge_UBRevCodeID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__6E610FB8] DEFAULT ((0)) FOR [Charge_ChargeImpact01]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__6F5533F1] DEFAULT ((0)) FOR [Charge_ChargeImpact02]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__7049582A] DEFAULT ((0)) FOR [Charge_ChargeImpact03]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__713D7C63] DEFAULT ((0)) FOR [Charge_ChargeImpact04]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__7231A09C] DEFAULT ((0)) FOR [Charge_ChargeImpact05]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__7325C4D5] DEFAULT ((0)) FOR [Charge_ChargeImpact06]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__7419E90E] DEFAULT ((0)) FOR [Charge_ChargeImpact07]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__750E0D47] DEFAULT ((0)) FOR [Charge_ChargeImpact08]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__76023180] DEFAULT ((0)) FOR [Charge_ChargeImpact09]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__76F655B9] DEFAULT ((0)) FOR [Charge_ChargeImpact10]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__77EA79F2] DEFAULT ((0)) FOR [Charge_ChargeImpact11]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Charg__78DE9E2B] DEFAULT ((0)) FOR [Charge_ChargeImpact12]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__79D2C264] DEFAULT ((0)) FOR [Encounter_ServiceLineEncounterID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__7AC6E69D] DEFAULT ((0)) FOR [Encounter_BudgetConfigID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__7BBB0AD6] DEFAULT ((0)) FOR [Encounter_EntityGroupConfigID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__7CAF2F0F] DEFAULT ((0)) FOR [Encounter_EntityID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__7DA35348] DEFAULT ((0)) FOR [Encounter_PatientClassID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__7E977781] DEFAULT ((0)) FOR [Encounter_ServiceLineID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombineChargeEncounterAndPrice] ADD CONSTRAINT [DF__Adjustmen__Encou__7F8B9BBA] DEFAULT ((0)) FOR [Encounter_ServiceLineRollupID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.AdjustmentImpactReport_CombinedChargeVolumeAndStatistics ------------------ +--------------------------------------------- +CREATE TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ( + [ReportExecutionGUID] uniqueidentifier NOT NULL, + [BatchID] int NOT NULL, + [IsInitial] bit NOT NULL, + [Charge_ChargeVolumeID] int NOT NULL, + [Charge_BudgetConfigID] int NOT NULL, + [Charge_EntityGroupConfigID] int NOT NULL, + [Charge_EntityID] int NOT NULL, + [Charge_DepartmentID] int NOT NULL, + [Charge_ChargeCodeID] int NOT NULL, + [Charge_PatientClassID] int NOT NULL, + [Charge_ServiceProviderSpecialtyID] int NOT NULL, + [Charge_PerformingProviderID] int NOT NULL, + [Charge_PerformingProviderSpecialtyID] int NOT NULL, + [Charge_UBRevCodeID] int NOT NULL, + [Charge_ChargeImpact01] decimal NOT NULL, + [Charge_ChargeImpact02] decimal NOT NULL, + [Charge_ChargeImpact03] decimal NOT NULL, + [Charge_ChargeImpact04] decimal NOT NULL, + [Charge_ChargeImpact05] decimal NOT NULL, + [Charge_ChargeImpact06] decimal NOT NULL, + [Charge_ChargeImpact07] decimal NOT NULL, + [Charge_ChargeImpact08] decimal NOT NULL, + [Charge_ChargeImpact09] decimal NOT NULL, + [Charge_ChargeImpact10] decimal NOT NULL, + [Charge_ChargeImpact11] decimal NOT NULL, + [Charge_ChargeImpact12] decimal NOT NULL, + [Encounter_ServiceLineEncounterID] int NOT NULL, + [Encounter_BudgetConfigID] int NOT NULL, + [Encounter_EntityGroupConfigID] int NOT NULL, + [Encounter_EntityID] int NOT NULL, + [Encounter_PatientClassID] int NOT NULL, + [Encounter_ServiceLineID] int NOT NULL, + [Encounter_ServiceLineRollupID] int NOT NULL, + [Encounter_AgeCohortID] int NOT NULL, + [Encounter_MedicalSurgicalID] int NOT NULL, + [Encounter_DepartmentID] int NOT NULL, + [Encounter_PayorID] int NOT NULL, + [Encounter_PayorGroupID] int NOT NULL, + [Encounter_MSDRGID] int NOT NULL, + [Encounter_CPTID] int NOT NULL, + [Encounter_ProviderID] int NOT NULL, + [Encounter_PhysicianSpecialtyID] int NOT NULL, + [Encounter_ServiceEntityID] int NOT NULL, + [Encounter_PrimaryCPTID] int NOT NULL, + [Encounter_ServiceProviderID] int NOT NULL, + [Encounter_IsInitialValue] bit NOT NULL, + [Encounter_AdjustmentGUID] uniqueidentifier NOT NULL, + [Encounter_TimeClassID] int NOT NULL, + [Encounter_BudgetPhaseID] int NOT NULL, + [Encounter_EncounterImpact01] decimal NOT NULL, + [Encounter_EncounterImpact02] decimal NOT NULL, + [Encounter_EncounterImpact03] decimal NOT NULL, + [Encounter_EncounterImpact04] decimal NOT NULL, + [Encounter_EncounterImpact05] decimal NOT NULL, + [Encounter_EncounterImpact06] decimal NOT NULL, + [Encounter_EncounterImpact07] decimal NOT NULL, + [Encounter_EncounterImpact08] decimal NOT NULL, + [Encounter_EncounterImpact09] decimal NOT NULL, + [Encounter_EncounterImpact10] decimal NOT NULL, + [Encounter_EncounterImpact11] decimal NOT NULL, + [Encounter_EncounterImpact12] decimal NOT NULL, + [Crosswalk_EntityGroupConfigID] int NOT NULL, + [Crosswalk_DepartmentID] int NOT NULL, + [Crosswalk_ChargeCodeID] int NOT NULL, + [Crosswalk_PatientClassID] int NOT NULL, + [Crosswalk_AccountID] int NOT NULL, + [Crosswalk_RVUWeight] decimal NOT NULL, + [Stats_StatisticsID] int NOT NULL, + [Stats_BudgetConfigID] int NOT NULL, + [Stats_EntityID] int NOT NULL, + [Stats_DepartmentID] int NOT NULL, + [Stats_AccountID] int NOT NULL, + [Stats_FinancialReportingID] int NOT NULL, + [Stats_PayorID] int NOT NULL, + [Stats_PatientClassID] int NOT NULL, + [StatisticsImpact01] decimal NOT NULL, + [StatisticsImpact02] decimal NOT NULL, + [StatisticsImpact03] decimal NOT NULL, + [StatisticsImpact04] decimal NOT NULL, + [StatisticsImpact05] decimal NOT NULL, + [StatisticsImpact06] decimal NOT NULL, + [StatisticsImpact07] decimal NOT NULL, + [StatisticsImpact08] decimal NOT NULL, + [StatisticsImpact09] decimal NOT NULL, + [StatisticsImpact10] decimal NOT NULL, + [StatisticsImpact11] decimal NOT NULL, + [StatisticsImpact12] decimal NOT NULL +); +GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__004AB5C9] DEFAULT ((0)) FOR [Charge_ChargeImpact03]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__013EDA02] DEFAULT ((0)) FOR [Charge_ChargeImpact04]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__0232FE3B] DEFAULT ((0)) FOR [Charge_ChargeImpact05]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__03272274] DEFAULT ((0)) FOR [Charge_ChargeImpact06]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__041B46AD] DEFAULT ((0)) FOR [Charge_ChargeImpact07]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__050F6AE6] DEFAULT ((0)) FOR [Charge_ChargeImpact08]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__06038F1F] DEFAULT ((0)) FOR [Charge_ChargeImpact09]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__06F7B358] DEFAULT ((0)) FOR [Charge_ChargeImpact10]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__07EBD791] DEFAULT ((0)) FOR [Charge_ChargeImpact11]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__08DFFBCA] DEFAULT ((0)) FOR [Charge_ChargeImpact12]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__09D42003] DEFAULT ((0)) FOR [Encounter_ServiceLineEncounterID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__0AC8443C] DEFAULT ((0)) FOR [Encounter_BudgetConfigID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__0BBC6875] DEFAULT ((0)) FOR [Encounter_EntityGroupConfigID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__0CB08CAE] DEFAULT ((0)) FOR [Encounter_EntityID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__0DA4B0E7] DEFAULT ((0)) FOR [Encounter_PatientClassID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__0E98D520] DEFAULT ((0)) FOR [Encounter_ServiceLineID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__0F8CF959] DEFAULT ((0)) FOR [Encounter_ServiceLineRollupID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__10811D92] DEFAULT ((0)) FOR [Encounter_AgeCohortID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__117541CB] DEFAULT ((0)) FOR [Encounter_MedicalSurgicalID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__12696604] DEFAULT ((0)) FOR [Encounter_DepartmentID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__135D8A3D] DEFAULT ((0)) FOR [Encounter_PayorID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__1451AE76] DEFAULT ((0)) FOR [Encounter_PayorGroupID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__1545D2AF] DEFAULT ((0)) FOR [Encounter_MSDRGID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__1639F6E8] DEFAULT ((0)) FOR [Encounter_CPTID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__172E1B21] DEFAULT ((0)) FOR [Encounter_ProviderID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__18223F5A] DEFAULT ((0)) FOR [Encounter_PhysicianSpecialtyID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__19166393] DEFAULT ((0)) FOR [Encounter_ServiceEntityID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__1A0A87CC] DEFAULT ((0)) FOR [Encounter_PrimaryCPTID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__1AFEAC05] DEFAULT ((0)) FOR [Encounter_ServiceProviderID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__1BF2D03E] DEFAULT ((0)) FOR [Encounter_IsInitialValue]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__1CE6F477] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [Encounter_AdjustmentGUID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__1DDB18B0] DEFAULT ((0)) FOR [Encounter_TimeClassID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__1ECF3CE9] DEFAULT ((0)) FOR [Encounter_BudgetPhaseID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__1FC36122] DEFAULT ((0)) FOR [Encounter_EncounterImpact01]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__20B7855B] DEFAULT ((0)) FOR [Encounter_EncounterImpact02]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__21ABA994] DEFAULT ((0)) FOR [Encounter_EncounterImpact03]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__229FCDCD] DEFAULT ((0)) FOR [Encounter_EncounterImpact04]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__2393F206] DEFAULT ((0)) FOR [Encounter_EncounterImpact05]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__2488163F] DEFAULT ((0)) FOR [Encounter_EncounterImpact06]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__257C3A78] DEFAULT ((0)) FOR [Encounter_EncounterImpact07]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__26705EB1] DEFAULT ((0)) FOR [Encounter_EncounterImpact08]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__276482EA] DEFAULT ((0)) FOR [Encounter_EncounterImpact09]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__2858A723] DEFAULT ((0)) FOR [Encounter_EncounterImpact10]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__294CCB5C] DEFAULT ((0)) FOR [Encounter_EncounterImpact11]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Encou__2A40EF95] DEFAULT ((0)) FOR [Encounter_EncounterImpact12]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Cross__2B3513CE] DEFAULT ((0)) FOR [Crosswalk_EntityGroupConfigID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Cross__2C293807] DEFAULT ((0)) FOR [Crosswalk_DepartmentID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Cross__2D1D5C40] DEFAULT ((0)) FOR [Crosswalk_ChargeCodeID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Cross__2E118079] DEFAULT ((0)) FOR [Crosswalk_PatientClassID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Cross__2F05A4B2] DEFAULT ((0)) FOR [Crosswalk_AccountID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Cross__2FF9C8EB] DEFAULT ((0)) FOR [Crosswalk_RVUWeight]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stats__30EDED24] DEFAULT ((0)) FOR [Stats_StatisticsID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stats__31E2115D] DEFAULT ((0)) FOR [Stats_BudgetConfigID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stats__32D63596] DEFAULT ((0)) FOR [Stats_EntityID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stats__33CA59CF] DEFAULT ((0)) FOR [Stats_DepartmentID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stats__34BE7E08] DEFAULT ((0)) FOR [Stats_AccountID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stats__35B2A241] DEFAULT ((0)) FOR [Stats_FinancialReportingID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stats__36A6C67A] DEFAULT ((0)) FOR [Stats_PayorID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stats__379AEAB3] DEFAULT ((0)) FOR [Stats_PatientClassID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__388F0EEC] DEFAULT ((0)) FOR [StatisticsImpact01]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__39833325] DEFAULT ((0)) FOR [StatisticsImpact02]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__3A77575E] DEFAULT ((0)) FOR [StatisticsImpact03]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__3B6B7B97] DEFAULT ((0)) FOR [StatisticsImpact04]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__3C5F9FD0] DEFAULT ((0)) FOR [StatisticsImpact05]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__3D53C409] DEFAULT ((0)) FOR [StatisticsImpact06]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__3E47E842] DEFAULT ((0)) FOR [StatisticsImpact07]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__3F3C0C7B] DEFAULT ((0)) FOR [StatisticsImpact08]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__403030B4] DEFAULT ((0)) FOR [StatisticsImpact09]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__412454ED] DEFAULT ((0)) FOR [StatisticsImpact10]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__42187926] DEFAULT ((0)) FOR [StatisticsImpact11]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Stati__430C9D5F] DEFAULT ((0)) FOR [StatisticsImpact12]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Repor__71087239] DEFAULT (newid()) FOR [ReportExecutionGUID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Batch__71FC9672] DEFAULT ((0)) FOR [BatchID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__IsIni__72F0BAAB] DEFAULT ((0)) FOR [IsInitial]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__73E4DEE4] DEFAULT ((0)) FOR [Charge_ChargeVolumeID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__74D9031D] DEFAULT ((0)) FOR [Charge_BudgetConfigID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__75CD2756] DEFAULT ((0)) FOR [Charge_EntityGroupConfigID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__76C14B8F] DEFAULT ((0)) FOR [Charge_EntityID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__77B56FC8] DEFAULT ((0)) FOR [Charge_DepartmentID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__78A99401] DEFAULT ((0)) FOR [Charge_ChargeCodeID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__799DB83A] DEFAULT ((0)) FOR [Charge_PatientClassID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__7A91DC73] DEFAULT ((0)) FOR [Charge_ServiceProviderSpecialtyID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__7B8600AC] DEFAULT ((0)) FOR [Charge_PerformingProviderID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__7C7A24E5] DEFAULT ((0)) FOR [Charge_PerformingProviderSpecialtyID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__7D6E491E] DEFAULT ((0)) FOR [Charge_UBRevCodeID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__7E626D57] DEFAULT ((0)) FOR [Charge_ChargeImpact01]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedChargeVolumeAndStatistics] ADD CONSTRAINT [DF__Adjustmen__Charg__7F569190] DEFAULT ((0)) FOR [Charge_ChargeImpact02]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.AdjustmentImpactReport_CombinedData_DebugConfiguration ------------------ +--------------------------------------------- +CREATE TABLE [fp].[AdjustmentImpactReport_CombinedData_DebugConfiguration] ( + [Batch_EntityID] int NOT NULL, + [Batch_PatientClassID] int NOT NULL, + [Batch_ServiceLineID] int NOT NULL, + [DepartmentID] int NOT NULL +); +GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedData_DebugConfiguration] ADD CONSTRAINT [DF__Adjustmen__Batch__4BA1E360] DEFAULT ((0)) FOR [Batch_EntityID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedData_DebugConfiguration] ADD CONSTRAINT [DF__Adjustmen__Batch__4C960799] DEFAULT ((0)) FOR [Batch_PatientClassID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedData_DebugConfiguration] ADD CONSTRAINT [DF__Adjustmen__Batch__4D8A2BD2] DEFAULT ((0)) FOR [Batch_ServiceLineID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedData_DebugConfiguration] ADD CONSTRAINT [DF__Adjustmen__Depar__4E7E500B] DEFAULT ((0)) FOR [DepartmentID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.AdjustmentImpactReport_CombinedEncounterAndCharge ------------------ +--------------------------------------------- +CREATE TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ( + [ReportExecutionGUID] uniqueidentifier NOT NULL, + [BatchID] int NOT NULL, + [IsInitial] bit NOT NULL, + [Charge_ChargeVolumeID] int NOT NULL, + [Charge_BudgetConfigID] int NOT NULL, + [Charge_EntityGroupConfigID] int NOT NULL, + [Charge_EntityID] int NOT NULL, + [Charge_DepartmentID] int NOT NULL, + [Charge_ChargeCodeID] int NOT NULL, + [Charge_PatientClassID] int NOT NULL, + [Charge_ServiceProviderSpecialtyID] int NOT NULL, + [Charge_PerformingProviderID] int NOT NULL, + [Charge_PerformingProviderSpecialtyID] int NOT NULL, + [Charge_UBRevCodeID] int NOT NULL, + [Charge_ChargeImpact01] decimal NOT NULL, + [Charge_ChargeImpact02] decimal NOT NULL, + [Charge_ChargeImpact03] decimal NOT NULL, + [Charge_ChargeImpact04] decimal NOT NULL, + [Charge_ChargeImpact05] decimal NOT NULL, + [Charge_ChargeImpact06] decimal NOT NULL, + [Charge_ChargeImpact07] decimal NOT NULL, + [Charge_ChargeImpact08] decimal NOT NULL, + [Charge_ChargeImpact09] decimal NOT NULL, + [Charge_ChargeImpact10] decimal NOT NULL, + [Charge_ChargeImpact11] decimal NOT NULL, + [Charge_ChargeImpact12] decimal NOT NULL, + [Encounter_ServiceLineEncounterID] int NOT NULL, + [Encounter_BudgetConfigID] int NOT NULL, + [Encounter_EntityGroupConfigID] int NOT NULL, + [Encounter_EntityID] int NOT NULL, + [Encounter_PatientClassID] int NOT NULL, + [Encounter_ServiceLineID] int NOT NULL, + [Encounter_ServiceLineRollupID] int NOT NULL, + [Encounter_AgeCohortID] int NOT NULL, + [Encounter_MedicalSurgicalID] int NOT NULL, + [Encounter_DepartmentID] int NOT NULL, + [Encounter_PayorID] int NOT NULL, + [Encounter_PayorGroupID] int NOT NULL, + [Encounter_MSDRGID] int NOT NULL, + [Encounter_CPTID] int NOT NULL, + [Encounter_ProviderID] int NOT NULL, + [Encounter_PhysicianSpecialtyID] int NOT NULL, + [Encounter_ServiceEntityID] int NOT NULL, + [Encounter_PrimaryCPTID] int NOT NULL, + [Encounter_ServiceProviderID] int NOT NULL, + [Encounter_IsInitialValue] bit NOT NULL, + [Encounter_AdjustmentGUID] uniqueidentifier NOT NULL, + [Encounter_TimeClassID] int NOT NULL, + [Encounter_BudgetPhaseID] int NOT NULL, + [Encounter_EncounterImpact01] decimal NOT NULL, + [Encounter_EncounterImpact02] decimal NOT NULL, + [Encounter_EncounterImpact03] decimal NOT NULL, + [Encounter_EncounterImpact04] decimal NOT NULL, + [Encounter_EncounterImpact05] decimal NOT NULL, + [Encounter_EncounterImpact06] decimal NOT NULL, + [Encounter_EncounterImpact07] decimal NOT NULL, + [Encounter_EncounterImpact08] decimal NOT NULL, + [Encounter_EncounterImpact09] decimal NOT NULL, + [Encounter_EncounterImpact10] decimal NOT NULL, + [Encounter_EncounterImpact11] decimal NOT NULL, + [Encounter_EncounterImpact12] decimal NOT NULL, + [UnitImpact_ChargeImpact01] decimal NOT NULL, + [UnitImpact_ChargeImpact02] decimal NOT NULL, + [UnitImpact_ChargeImpact03] decimal NOT NULL, + [UnitImpact_ChargeImpact04] decimal NOT NULL, + [UnitImpact_ChargeImpact05] decimal NOT NULL, + [UnitImpact_ChargeImpact06] decimal NOT NULL, + [UnitImpact_ChargeImpact07] decimal NOT NULL, + [UnitImpact_ChargeImpact08] decimal NOT NULL, + [UnitImpact_ChargeImpact09] decimal NOT NULL, + [UnitImpact_ChargeImpact10] decimal NOT NULL, + [UnitImpact_ChargeImpact11] decimal NOT NULL, + [UnitImpact_ChargeImpact12] decimal NOT NULL +); +GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Repor__2A75F9BF] DEFAULT (newid()) FOR [ReportExecutionGUID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Batch__2B6A1DF8] DEFAULT ((0)) FOR [BatchID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__IsIni__2C5E4231] DEFAULT ((0)) FOR [IsInitial]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__2D52666A] DEFAULT ((0)) FOR [Charge_ChargeVolumeID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__2E468AA3] DEFAULT ((0)) FOR [Charge_BudgetConfigID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__2F3AAEDC] DEFAULT ((0)) FOR [Charge_EntityGroupConfigID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__302ED315] DEFAULT ((0)) FOR [Charge_EntityID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__3122F74E] DEFAULT ((0)) FOR [Charge_DepartmentID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__32171B87] DEFAULT ((0)) FOR [Charge_ChargeCodeID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__330B3FC0] DEFAULT ((0)) FOR [Charge_PatientClassID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__33FF63F9] DEFAULT ((0)) FOR [Charge_ServiceProviderSpecialtyID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__34F38832] DEFAULT ((0)) FOR [Charge_PerformingProviderID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__35E7AC6B] DEFAULT ((0)) FOR [Charge_PerformingProviderSpecialtyID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__36DBD0A4] DEFAULT ((0)) FOR [Charge_UBRevCodeID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__37CFF4DD] DEFAULT ((0)) FOR [Charge_ChargeImpact01]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__38C41916] DEFAULT ((0)) FOR [Charge_ChargeImpact02]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__39B83D4F] DEFAULT ((0)) FOR [Charge_ChargeImpact03]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__3AAC6188] DEFAULT ((0)) FOR [Charge_ChargeImpact04]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__3BA085C1] DEFAULT ((0)) FOR [Charge_ChargeImpact05]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__3C94A9FA] DEFAULT ((0)) FOR [Charge_ChargeImpact06]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__3D88CE33] DEFAULT ((0)) FOR [Charge_ChargeImpact07]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__3E7CF26C] DEFAULT ((0)) FOR [Charge_ChargeImpact08]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__3F7116A5] DEFAULT ((0)) FOR [Charge_ChargeImpact09]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__40653ADE] DEFAULT ((0)) FOR [Charge_ChargeImpact10]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__41595F17] DEFAULT ((0)) FOR [Charge_ChargeImpact11]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Charg__424D8350] DEFAULT ((0)) FOR [Charge_ChargeImpact12]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__4341A789] DEFAULT ((0)) FOR [Encounter_ServiceLineEncounterID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__4435CBC2] DEFAULT ((0)) FOR [Encounter_BudgetConfigID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__4529EFFB] DEFAULT ((0)) FOR [Encounter_EntityGroupConfigID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__461E1434] DEFAULT ((0)) FOR [Encounter_EntityID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__4712386D] DEFAULT ((0)) FOR [Encounter_PatientClassID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__48065CA6] DEFAULT ((0)) FOR [Encounter_ServiceLineID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__48FA80DF] DEFAULT ((0)) FOR [Encounter_ServiceLineRollupID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__49EEA518] DEFAULT ((0)) FOR [Encounter_AgeCohortID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__4AE2C951] DEFAULT ((0)) FOR [Encounter_MedicalSurgicalID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__4BD6ED8A] DEFAULT ((0)) FOR [Encounter_DepartmentID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__4CCB11C3] DEFAULT ((0)) FOR [Encounter_PayorID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__4DBF35FC] DEFAULT ((0)) FOR [Encounter_PayorGroupID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__4EB35A35] DEFAULT ((0)) FOR [Encounter_MSDRGID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__4FA77E6E] DEFAULT ((0)) FOR [Encounter_CPTID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__509BA2A7] DEFAULT ((0)) FOR [Encounter_ProviderID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__518FC6E0] DEFAULT ((0)) FOR [Encounter_PhysicianSpecialtyID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__5283EB19] DEFAULT ((0)) FOR [Encounter_ServiceEntityID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__53780F52] DEFAULT ((0)) FOR [Encounter_PrimaryCPTID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__546C338B] DEFAULT ((0)) FOR [Encounter_ServiceProviderID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__556057C4] DEFAULT ((0)) FOR [Encounter_IsInitialValue]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__56547BFD] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [Encounter_AdjustmentGUID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__5748A036] DEFAULT ((0)) FOR [Encounter_TimeClassID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__583CC46F] DEFAULT ((0)) FOR [Encounter_BudgetPhaseID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__5930E8A8] DEFAULT ((0)) FOR [Encounter_EncounterImpact01]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__5A250CE1] DEFAULT ((0)) FOR [Encounter_EncounterImpact02]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__5B19311A] DEFAULT ((0)) FOR [Encounter_EncounterImpact03]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__5C0D5553] DEFAULT ((0)) FOR [Encounter_EncounterImpact04]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__5D01798C] DEFAULT ((0)) FOR [Encounter_EncounterImpact05]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__5DF59DC5] DEFAULT ((0)) FOR [Encounter_EncounterImpact06]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__5EE9C1FE] DEFAULT ((0)) FOR [Encounter_EncounterImpact07]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__5FDDE637] DEFAULT ((0)) FOR [Encounter_EncounterImpact08]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__60D20A70] DEFAULT ((0)) FOR [Encounter_EncounterImpact09]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__61C62EA9] DEFAULT ((0)) FOR [Encounter_EncounterImpact10]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__62BA52E2] DEFAULT ((0)) FOR [Encounter_EncounterImpact11]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__Encou__63AE771B] DEFAULT ((0)) FOR [Encounter_EncounterImpact12]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__64A29B54] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact01]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__6596BF8D] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact02]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__668AE3C6] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact03]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__677F07FF] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact04]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__68732C38] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact05]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__69675071] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact06]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__6A5B74AA] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact07]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__6B4F98E3] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact08]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__6C43BD1C] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact09]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__6D37E155] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact10]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__6E2C058E] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact11]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_CombinedEncounterAndCharge] ADD CONSTRAINT [DF__Adjustmen__UnitI__6F2029C7] DEFAULT ((0)) FOR [UnitImpact_ChargeImpact12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.AdjustmentImpactReport_DebugInfo ------------------ +--------------------------------------------- +CREATE TABLE [fp].[AdjustmentImpactReport_DebugInfo] ( + [SortOrder] int NOT NULL, + [ReportExecutionGUID] uniqueidentifier NOT NULL, + [BatchID] int NOT NULL, + [IsInitial] bit NOT NULL, + [ReportName] nvarchar(100) NOT NULL, + [DateCreated] datetime NOT NULL, + [Message] nvarchar(max) NOT NULL, + [CorrespondingSql] nvarchar(max) NOT NULL +); +GO +ALTER TABLE [fp].[AdjustmentImpactReport_DebugInfo] ADD CONSTRAINT [DF__Adjustmen__Repor__52B8F543] DEFAULT (newid()) FOR [ReportExecutionGUID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_DebugInfo] ADD CONSTRAINT [DF__Adjustmen__Batch__53AD197C] DEFAULT ((0)) FOR [BatchID]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_DebugInfo] ADD CONSTRAINT [DF__Adjustmen__IsIni__54A13DB5] DEFAULT ((0)) FOR [IsInitial]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_DebugInfo] ADD CONSTRAINT [DF__Adjustmen__Repor__559561EE] DEFAULT ('') FOR [ReportName]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_DebugInfo] ADD CONSTRAINT [DF__Adjustmen__DateC__56898627] DEFAULT (getdate()) FOR [DateCreated]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_DebugInfo] ADD CONSTRAINT [DF__Adjustmen__Messa__577DAA60] DEFAULT ('') FOR [Message]; GO +ALTER TABLE [fp].[AdjustmentImpactReport_DebugInfo] ADD CONSTRAINT [DF__Adjustmen__Corre__5871CE99] DEFAULT ('') FOR [CorrespondingSql]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.AdjustmentLink ------------------ +--------------------------------------------- +CREATE TABLE [fp].[AdjustmentLink] ( + [RowID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [LinkedAdjustmentGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [IX_ClusteredUnique] ON [fp].[AdjustmentLink] ([AdjustmentGUID], [LinkedAdjustmentGUID]); +GO +ALTER TABLE [fp].[AdjustmentLink] ADD CONSTRAINT [DF__Adjustmen__Adjus__4FE5138B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[AdjustmentLink] ADD CONSTRAINT [DF__Adjustmen__Linke__50D937C4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [LinkedAdjustmentGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.AdjustmentRemovalHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[AdjustmentRemovalHistory] ( + [DateTimeCreated] datetime NOT NULL, + [Author] nvarchar(100) NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [Sections] nvarchar(1000) NOT NULL +); +GO +ALTER TABLE [fp].[AdjustmentRemovalHistory] ADD CONSTRAINT [DF__Adjustmen__DateT__7C726549] DEFAULT (getdate()) FOR [DateTimeCreated]; GO +ALTER TABLE [fp].[AdjustmentRemovalHistory] ADD CONSTRAINT [DF__Adjustmen__Autho__7D668982] DEFAULT ('') FOR [Author]; GO +ALTER TABLE [fp].[AdjustmentRemovalHistory] ADD CONSTRAINT [DF__Adjustmen__Budge__7E5AADBB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[AdjustmentRemovalHistory] ADD CONSTRAINT [DF__Adjustmen__Secti__7F4ED1F4] DEFAULT ('') FOR [Sections]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveBenefitsChangeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveBenefitsChangeHistory] ( + [RowID] bigint NOT NULL, + [BenefitsID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [SortOrder] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [OldValue] decimal NOT NULL, + [NewValue] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [FK_ArchiveBenefitsChangeHistory_BenefitsID] FOREIGN KEY ([BenefitsID]) REFERENCES [fp].[ArchiveFactBenefits] ([BenefitsID]); GO +ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [DF__ArchiveBe__Benef__09ECF585] DEFAULT ((0)) FOR [BenefitsID]; GO +ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [DF__ArchiveBe__Adjus__0AE119BE] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [DF__ArchiveBe__Adjus__0BD53DF7] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [DF__ArchiveBe__SortO__0CC96230] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [DF__ArchiveBe__Fisca__0DBD8669] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [DF__ArchiveBe__UnitT__0EB1AAA2] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [DF__ArchiveBe__TimeC__0FA5CEDB] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [DF__ArchiveBe__Budge__1099F314] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [DF__ArchiveBe__OldVa__118E174D] DEFAULT ((0)) FOR [OldValue]; GO +ALTER TABLE [fp].[ArchiveBenefitsChangeHistory] ADD CONSTRAINT [DF__ArchiveBe__NewVa__12823B86] DEFAULT ((0)) FOR [NewValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveChangeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveChangeHistory] ( + [RowID] int NOT NULL, + [ChangeHistoryGUID] uniqueidentifier NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [SortOrder] int NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [OldValue] decimal NOT NULL, + [NewValue] decimal NOT NULL, + [FiscalMonthID] int NOT NULL, + [AdjustedProperty] tinyint NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ArchiveChangeHistory] ADD CONSTRAINT [DF_ArchiveChangeHistory_ChangeHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ChangeHistoryGUID]; GO +ALTER TABLE [fp].[ArchiveChangeHistory] ADD CONSTRAINT [DF_ArchiveChangeHistory_AdjustmentGUID] DEFAULT (newid()) FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ArchiveChangeHistory] ADD CONSTRAINT [DF_ArchiveChangeHistory_SortOrder] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fp].[ArchiveChangeHistory] ADD CONSTRAINT [DF_ArchiveChangeHistory_AdjustmentType] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[ArchiveChangeHistory] ADD CONSTRAINT [DF_ArchiveChangeHistory_OldValue] DEFAULT ((0)) FOR [OldValue]; GO +ALTER TABLE [fp].[ArchiveChangeHistory] ADD CONSTRAINT [DF_ArchiveChangeHistory_NewValue] DEFAULT ((0)) FOR [NewValue]; GO +ALTER TABLE [fp].[ArchiveChangeHistory] ADD CONSTRAINT [DF_ArchiveChangeHistory_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[ArchiveChangeHistory] ADD CONSTRAINT [DF_ArchiveChangeHistory_AdjustedProperty] DEFAULT ((0)) FOR [AdjustedProperty]; GO +ALTER TABLE [fp].[ArchiveChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__Group__1DF3EE32] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveChargeVolumeChangeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveChargeVolumeChangeHistory] ( + [RowID] bigint NOT NULL, + [ChargeVolumeID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [SortOrder] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [OldValue] decimal NOT NULL, + [NewValue] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [FK_ArchiveChargeVolumeChangeHistory_ChargeVolumeID] FOREIGN KEY ([ChargeVolumeID]) REFERENCES [fp].[ArchiveFactChargeVolume] ([ChargeVolumeID]); GO +ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__Charg__20D05ADD] DEFAULT ((0)) FOR [ChargeVolumeID]; GO +ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__Adjus__21C47F16] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__Adjus__22B8A34F] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__SortO__23ACC788] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__Fisca__24A0EBC1] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__UnitT__25950FFA] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__TimeC__26893433] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__Budge__277D586C] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__OldVa__28717CA5] DEFAULT ((0)) FOR [OldValue]; GO +ALTER TABLE [fp].[ArchiveChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ArchiveCh__NewVa__2965A0DE] DEFAULT ((0)) FOR [NewValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactBenefits ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactBenefits] ( + [BenefitsID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [FlexMethodID] tinyint NOT NULL, + [AddDate] datetime NOT NULL, + [SampledBudget01] decimal NOT NULL, + [SampledBudget02] decimal NOT NULL, + [SampledBudget03] decimal NOT NULL, + [SampledBudget04] decimal NOT NULL, + [SampledBudget05] decimal NOT NULL, + [SampledBudget06] decimal NOT NULL, + [SampledBudget07] decimal NOT NULL, + [SampledBudget08] decimal NOT NULL, + [SampledBudget09] decimal NOT NULL, + [SampledBudget10] decimal NOT NULL, + [SampledBudget11] decimal NOT NULL, + [SampledBudget12] decimal NOT NULL, + [SampledBudgetTotal] decimal NOT NULL, + [SampledProjection01] decimal NOT NULL, + [SampledProjection02] decimal NOT NULL, + [SampledProjection03] decimal NOT NULL, + [SampledProjection04] decimal NOT NULL, + [SampledProjection05] decimal NOT NULL, + [SampledProjection06] decimal NOT NULL, + [SampledProjection07] decimal NOT NULL, + [SampledProjection08] decimal NOT NULL, + [SampledProjection09] decimal NOT NULL, + [SampledProjection10] decimal NOT NULL, + [SampledProjection11] decimal NOT NULL, + [SampledProjection12] decimal NOT NULL, + [SampledProjectionTotal] decimal NOT NULL, + [InitialBudget01] decimal NOT NULL, + [InitialBudget02] decimal NOT NULL, + [InitialBudget03] decimal NOT NULL, + [InitialBudget04] decimal NOT NULL, + [InitialBudget05] decimal NOT NULL, + [InitialBudget06] decimal NOT NULL, + [InitialBudget07] decimal NOT NULL, + [InitialBudget08] decimal NOT NULL, + [InitialBudget09] decimal NOT NULL, + [InitialBudget10] decimal NOT NULL, + [InitialBudget11] decimal NOT NULL, + [InitialBudget12] decimal NOT NULL, + [InitialBudgetTotal] decimal NOT NULL, + [InitialProjection01] decimal NOT NULL, + [InitialProjection02] decimal NOT NULL, + [InitialProjection03] decimal NOT NULL, + [InitialProjection04] decimal NOT NULL, + [InitialProjection05] decimal NOT NULL, + [InitialProjection06] decimal NOT NULL, + [InitialProjection07] decimal NOT NULL, + [InitialProjection08] decimal NOT NULL, + [InitialProjection09] decimal NOT NULL, + [InitialProjection10] decimal NOT NULL, + [InitialProjection11] decimal NOT NULL, + [InitialProjection12] decimal NOT NULL, + [InitialProjectionTotal] decimal NOT NULL, + PRIMARY KEY ([BenefitsID]) +); + +CREATE NONCLUSTERED INDEX [IX_ArchiveFactBenefits_Account] ON [fp].[ArchiveFactBenefits] ([AccountID]) INCLUDE ([BenefitsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [FinancialReportingID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactBenefits_BudgetConfig] ON [fp].[ArchiveFactBenefits] ([BudgetConfigID]) INCLUDE ([BenefitsID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactBenefits_Department] ON [fp].[ArchiveFactBenefits] ([DepartmentID]) INCLUDE ([BenefitsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [AccountID], [FinancialReportingID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactBenefits_Entity] ON [fp].[ArchiveFactBenefits] ([EntityID]) INCLUDE ([BenefitsID], [BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [AccountID], [FinancialReportingID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactBenefits_EntityGroupConfig] ON [fp].[ArchiveFactBenefits] ([EntityGroupConfigID]) INCLUDE ([BenefitsID], [BudgetConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [UnitTypeID]); +GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__00ECCFD9] DEFAULT ((0)) FOR [InitialProjection08]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__01E0F412] DEFAULT ((0)) FOR [InitialProjection09]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__02D5184B] DEFAULT ((0)) FOR [InitialProjection10]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__03C93C84] DEFAULT ((0)) FOR [InitialProjection11]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__04BD60BD] DEFAULT ((0)) FOR [InitialProjection12]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Budge__4F557445] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Entit__5049987E] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Entit__513DBCB7] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Depar__5231E0F0] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Accou__53260529] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Finan__541A2962] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__UnitT__550E4D9B] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__FlexM__560271D4] DEFAULT ((0)) FOR [FlexMethodID]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__AddDa__56F6960D] DEFAULT (getdate()) FOR [AddDate]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__57EABA46] DEFAULT ((0)) FOR [SampledBudget01]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__58DEDE7F] DEFAULT ((0)) FOR [SampledBudget02]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__59D302B8] DEFAULT ((0)) FOR [SampledBudget03]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__5AC726F1] DEFAULT ((0)) FOR [SampledBudget04]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__5BBB4B2A] DEFAULT ((0)) FOR [SampledBudget05]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__5CAF6F63] DEFAULT ((0)) FOR [SampledBudget06]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__5DA3939C] DEFAULT ((0)) FOR [SampledBudget07]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__5E97B7D5] DEFAULT ((0)) FOR [SampledBudget08]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__5F8BDC0E] DEFAULT ((0)) FOR [SampledBudget09]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__60800047] DEFAULT ((0)) FOR [SampledBudget10]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__61742480] DEFAULT ((0)) FOR [SampledBudget11]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__626848B9] DEFAULT ((0)) FOR [SampledBudget12]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__635C6CF2] DEFAULT ((0)) FOR [SampledProjection01]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6450912B] DEFAULT ((0)) FOR [SampledProjection02]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6544B564] DEFAULT ((0)) FOR [SampledProjection03]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6638D99D] DEFAULT ((0)) FOR [SampledProjection04]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__672CFDD6] DEFAULT ((0)) FOR [SampledProjection05]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6821220F] DEFAULT ((0)) FOR [SampledProjection06]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__69154648] DEFAULT ((0)) FOR [SampledProjection07]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6A096A81] DEFAULT ((0)) FOR [SampledProjection08]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6AFD8EBA] DEFAULT ((0)) FOR [SampledProjection09]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6BF1B2F3] DEFAULT ((0)) FOR [SampledProjection10]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6CE5D72C] DEFAULT ((0)) FOR [SampledProjection11]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6DD9FB65] DEFAULT ((0)) FOR [SampledProjection12]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__6ECE1F9E] DEFAULT ((0)) FOR [InitialBudget01]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__6FC243D7] DEFAULT ((0)) FOR [InitialBudget02]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__70B66810] DEFAULT ((0)) FOR [InitialBudget03]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__71AA8C49] DEFAULT ((0)) FOR [InitialBudget04]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__729EB082] DEFAULT ((0)) FOR [InitialBudget05]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__7392D4BB] DEFAULT ((0)) FOR [InitialBudget06]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__7486F8F4] DEFAULT ((0)) FOR [InitialBudget07]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__757B1D2D] DEFAULT ((0)) FOR [InitialBudget08]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__766F4166] DEFAULT ((0)) FOR [InitialBudget09]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__7763659F] DEFAULT ((0)) FOR [InitialBudget10]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__785789D8] DEFAULT ((0)) FOR [InitialBudget11]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__794BAE11] DEFAULT ((0)) FOR [InitialBudget12]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__7A3FD24A] DEFAULT ((0)) FOR [InitialProjection01]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__7B33F683] DEFAULT ((0)) FOR [InitialProjection02]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__7C281ABC] DEFAULT ((0)) FOR [InitialProjection03]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__7D1C3EF5] DEFAULT ((0)) FOR [InitialProjection04]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__7E10632E] DEFAULT ((0)) FOR [InitialProjection05]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__7F048767] DEFAULT ((0)) FOR [InitialProjection06]; GO +ALTER TABLE [fp].[ArchiveFactBenefits] ADD CONSTRAINT [DF__ArchiveFa__Initi__7FF8ABA0] DEFAULT ((0)) FOR [InitialProjection07]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactBenefitsBudget ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactBenefitsBudget] ( + [RowID] int NOT NULL, + [BenefitsID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedValue01] decimal NOT NULL, + [AdjustedValue02] decimal NOT NULL, + [AdjustedValue03] decimal NOT NULL, + [AdjustedValue04] decimal NOT NULL, + [AdjustedValue05] decimal NOT NULL, + [AdjustedValue06] decimal NOT NULL, + [AdjustedValue07] decimal NOT NULL, + [AdjustedValue08] decimal NOT NULL, + [AdjustedValue09] decimal NOT NULL, + [AdjustedValue10] decimal NOT NULL, + [AdjustedValue11] decimal NOT NULL, + [AdjustedValue12] decimal NOT NULL, + [AdjustedValueTotal] decimal NOT NULL, + [FlexedValue01] decimal NOT NULL, + [FlexedValue02] decimal NOT NULL, + [FlexedValue03] decimal NOT NULL, + [FlexedValue04] decimal NOT NULL, + [FlexedValue05] decimal NOT NULL, + [FlexedValue06] decimal NOT NULL, + [FlexedValue07] decimal NOT NULL, + [FlexedValue08] decimal NOT NULL, + [FlexedValue09] decimal NOT NULL, + [FlexedValue10] decimal NOT NULL, + [FlexedValue11] decimal NOT NULL, + [FlexedValue12] decimal NOT NULL, + [FlexedValueTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_ArchiveFactBenefitsBudget] ON [fp].[ArchiveFactBenefitsBudget] ([BenefitsID], [BudgetPhaseID]); +GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [FK_ArchiveFactBenefitsBudget_BenefitsID] FOREIGN KEY ([BenefitsID]) REFERENCES [fp].[ArchiveFactBenefits] ([BenefitsID]); GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Benef__0799CD68] DEFAULT ((0)) FOR [BenefitsID]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__LockT__088DF1A1] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__LockF__098215DA] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Budge__0A763A13] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0B6A5E4C] DEFAULT ((0)) FOR [AdjustedValue01]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0C5E8285] DEFAULT ((0)) FOR [AdjustedValue02]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0D52A6BE] DEFAULT ((0)) FOR [AdjustedValue03]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0E46CAF7] DEFAULT ((0)) FOR [AdjustedValue04]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0F3AEF30] DEFAULT ((0)) FOR [AdjustedValue05]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__102F1369] DEFAULT ((0)) FOR [AdjustedValue06]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__112337A2] DEFAULT ((0)) FOR [AdjustedValue07]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__12175BDB] DEFAULT ((0)) FOR [AdjustedValue08]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__130B8014] DEFAULT ((0)) FOR [AdjustedValue09]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__13FFA44D] DEFAULT ((0)) FOR [AdjustedValue10]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__14F3C886] DEFAULT ((0)) FOR [AdjustedValue11]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__15E7ECBF] DEFAULT ((0)) FOR [AdjustedValue12]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__16DC10F8] DEFAULT ((0)) FOR [FlexedValue01]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__17D03531] DEFAULT ((0)) FOR [FlexedValue02]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__18C4596A] DEFAULT ((0)) FOR [FlexedValue03]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__19B87DA3] DEFAULT ((0)) FOR [FlexedValue04]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1AACA1DC] DEFAULT ((0)) FOR [FlexedValue05]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1BA0C615] DEFAULT ((0)) FOR [FlexedValue06]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1C94EA4E] DEFAULT ((0)) FOR [FlexedValue07]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1D890E87] DEFAULT ((0)) FOR [FlexedValue08]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1E7D32C0] DEFAULT ((0)) FOR [FlexedValue09]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1F7156F9] DEFAULT ((0)) FOR [FlexedValue10]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__20657B32] DEFAULT ((0)) FOR [FlexedValue11]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__21599F6B] DEFAULT ((0)) FOR [FlexedValue12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactBenefitsHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactBenefitsHistory] ( + [RowID] int NOT NULL, + [BenefitsID] int NOT NULL, + [PriorYearActualValue01] decimal NOT NULL, + [PriorYearActualValue02] decimal NOT NULL, + [PriorYearActualValue03] decimal NOT NULL, + [PriorYearActualValue04] decimal NOT NULL, + [PriorYearActualValue05] decimal NOT NULL, + [PriorYearActualValue06] decimal NOT NULL, + [PriorYearActualValue07] decimal NOT NULL, + [PriorYearActualValue08] decimal NOT NULL, + [PriorYearActualValue09] decimal NOT NULL, + [PriorYearActualValue10] decimal NOT NULL, + [PriorYearActualValue11] decimal NOT NULL, + [PriorYearActualValue12] decimal NOT NULL, + [PriorYearActualValueTotal] decimal NOT NULL, + [ActualYTDValue01] decimal NOT NULL, + [ActualYTDValue02] decimal NOT NULL, + [ActualYTDValue03] decimal NOT NULL, + [ActualYTDValue04] decimal NOT NULL, + [ActualYTDValue05] decimal NOT NULL, + [ActualYTDValue06] decimal NOT NULL, + [ActualYTDValue07] decimal NOT NULL, + [ActualYTDValue08] decimal NOT NULL, + [ActualYTDValue09] decimal NOT NULL, + [ActualYTDValue10] decimal NOT NULL, + [ActualYTDValue11] decimal NOT NULL, + [ActualYTDValue12] decimal NOT NULL, + [ActualYTDValueTotal] decimal NOT NULL, + [CurrentYearBudget01] decimal NOT NULL, + [CurrentYearBudget02] decimal NOT NULL, + [CurrentYearBudget03] decimal NOT NULL, + [CurrentYearBudget04] decimal NOT NULL, + [CurrentYearBudget05] decimal NOT NULL, + [CurrentYearBudget06] decimal NOT NULL, + [CurrentYearBudget07] decimal NOT NULL, + [CurrentYearBudget08] decimal NOT NULL, + [CurrentYearBudget09] decimal NOT NULL, + [CurrentYearBudget10] decimal NOT NULL, + [CurrentYearBudget11] decimal NOT NULL, + [CurrentYearBudget12] decimal NOT NULL, + [CurrentYearBudgetTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [FK_ArchiveFactBenefitsHistory_BenefitsID] FOREIGN KEY ([BenefitsID]) REFERENCES [fp].[ArchiveFactBenefits] ([BenefitsID]); GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__00989575] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Benef__5E437D71] DEFAULT ((0)) FOR [BenefitsID]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5F37A1AA] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__602BC5E3] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__611FEA1C] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__62140E55] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__6308328E] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__63FC56C7] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__64F07B00] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__65E49F39] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__66D8C372] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__67CCE7AB] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__68C10BE4] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__69B5301D] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6AA95456] DEFAULT ((0)) FOR [ActualYTDValue01]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6B9D788F] DEFAULT ((0)) FOR [ActualYTDValue02]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6C919CC8] DEFAULT ((0)) FOR [ActualYTDValue03]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6D85C101] DEFAULT ((0)) FOR [ActualYTDValue04]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6E79E53A] DEFAULT ((0)) FOR [ActualYTDValue05]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6F6E0973] DEFAULT ((0)) FOR [ActualYTDValue06]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__70622DAC] DEFAULT ((0)) FOR [ActualYTDValue07]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__715651E5] DEFAULT ((0)) FOR [ActualYTDValue08]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__724A761E] DEFAULT ((0)) FOR [ActualYTDValue09]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__733E9A57] DEFAULT ((0)) FOR [ActualYTDValue10]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__7432BE90] DEFAULT ((0)) FOR [ActualYTDValue11]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__7526E2C9] DEFAULT ((0)) FOR [ActualYTDValue12]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__761B0702] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__770F2B3B] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__78034F74] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__78F773AD] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__79EB97E6] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7ADFBC1F] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7BD3E058] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7CC80491] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7DBC28CA] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7EB04D03] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7FA4713C] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactBenefitsProjection ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactBenefitsProjection] ( + [RowID] int NOT NULL, + [BenefitsID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedValue01] decimal NOT NULL, + [AdjustedValue02] decimal NOT NULL, + [AdjustedValue03] decimal NOT NULL, + [AdjustedValue04] decimal NOT NULL, + [AdjustedValue05] decimal NOT NULL, + [AdjustedValue06] decimal NOT NULL, + [AdjustedValue07] decimal NOT NULL, + [AdjustedValue08] decimal NOT NULL, + [AdjustedValue09] decimal NOT NULL, + [AdjustedValue10] decimal NOT NULL, + [AdjustedValue11] decimal NOT NULL, + [AdjustedValue12] decimal NOT NULL, + [AdjustedValueTotal] decimal NOT NULL, + [FlexedValue01] decimal NOT NULL, + [FlexedValue02] decimal NOT NULL, + [FlexedValue03] decimal NOT NULL, + [FlexedValue04] decimal NOT NULL, + [FlexedValue05] decimal NOT NULL, + [FlexedValue06] decimal NOT NULL, + [FlexedValue07] decimal NOT NULL, + [FlexedValue08] decimal NOT NULL, + [FlexedValue09] decimal NOT NULL, + [FlexedValue10] decimal NOT NULL, + [FlexedValue11] decimal NOT NULL, + [FlexedValue12] decimal NOT NULL, + [FlexedValueTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_ArchiveFactBenefitsProjection] ON [fp].[ArchiveFactBenefitsProjection] ([BenefitsID], [BudgetPhaseID]); +GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [FK_ArchiveFactBenefitsProjection_BenefitsID] FOREIGN KEY ([BenefitsID]) REFERENCES [fp].[ArchiveFactBenefits] ([BenefitsID]); GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Benef__252A304F] DEFAULT ((0)) FOR [BenefitsID]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__LockT__261E5488] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__LockF__271278C1] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Budge__28069CFA] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__28FAC133] DEFAULT ((0)) FOR [AdjustedValue01]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__29EEE56C] DEFAULT ((0)) FOR [AdjustedValue02]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2AE309A5] DEFAULT ((0)) FOR [AdjustedValue03]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2BD72DDE] DEFAULT ((0)) FOR [AdjustedValue04]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2CCB5217] DEFAULT ((0)) FOR [AdjustedValue05]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2DBF7650] DEFAULT ((0)) FOR [AdjustedValue06]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2EB39A89] DEFAULT ((0)) FOR [AdjustedValue07]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2FA7BEC2] DEFAULT ((0)) FOR [AdjustedValue08]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__309BE2FB] DEFAULT ((0)) FOR [AdjustedValue09]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__31900734] DEFAULT ((0)) FOR [AdjustedValue10]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__32842B6D] DEFAULT ((0)) FOR [AdjustedValue11]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__33784FA6] DEFAULT ((0)) FOR [AdjustedValue12]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__346C73DF] DEFAULT ((0)) FOR [FlexedValue01]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__35609818] DEFAULT ((0)) FOR [FlexedValue02]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3654BC51] DEFAULT ((0)) FOR [FlexedValue03]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3748E08A] DEFAULT ((0)) FOR [FlexedValue04]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__383D04C3] DEFAULT ((0)) FOR [FlexedValue05]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__393128FC] DEFAULT ((0)) FOR [FlexedValue06]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3A254D35] DEFAULT ((0)) FOR [FlexedValue07]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3B19716E] DEFAULT ((0)) FOR [FlexedValue08]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3C0D95A7] DEFAULT ((0)) FOR [FlexedValue09]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3D01B9E0] DEFAULT ((0)) FOR [FlexedValue10]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3DF5DE19] DEFAULT ((0)) FOR [FlexedValue11]; GO +ALTER TABLE [fp].[ArchiveFactBenefitsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3EEA0252] DEFAULT ((0)) FOR [FlexedValue12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactChargeVolume ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactChargeVolume] ( + [ChargeVolumeID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [PatientClassID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [AddDate] datetime NOT NULL, + [SampledBudget01] decimal NOT NULL, + [SampledBudget02] decimal NOT NULL, + [SampledBudget03] decimal NOT NULL, + [SampledBudget04] decimal NOT NULL, + [SampledBudget05] decimal NOT NULL, + [SampledBudget06] decimal NOT NULL, + [SampledBudget07] decimal NOT NULL, + [SampledBudget08] decimal NOT NULL, + [SampledBudget09] decimal NOT NULL, + [SampledBudget10] decimal NOT NULL, + [SampledBudget11] decimal NOT NULL, + [SampledBudget12] decimal NOT NULL, + [SampledBudgetTotal] decimal NULL, + [SampledProjection01] decimal NOT NULL, + [SampledProjection02] decimal NOT NULL, + [SampledProjection03] decimal NOT NULL, + [SampledProjection04] decimal NOT NULL, + [SampledProjection05] decimal NOT NULL, + [SampledProjection06] decimal NOT NULL, + [SampledProjection07] decimal NOT NULL, + [SampledProjection08] decimal NOT NULL, + [SampledProjection09] decimal NOT NULL, + [SampledProjection10] decimal NOT NULL, + [SampledProjection11] decimal NOT NULL, + [SampledProjection12] decimal NOT NULL, + [SampledProjectionTotal] decimal NULL, + [InitialBudget01] decimal NOT NULL, + [InitialBudget02] decimal NOT NULL, + [InitialBudget03] decimal NOT NULL, + [InitialBudget04] decimal NOT NULL, + [InitialBudget05] decimal NOT NULL, + [InitialBudget06] decimal NOT NULL, + [InitialBudget07] decimal NOT NULL, + [InitialBudget08] decimal NOT NULL, + [InitialBudget09] decimal NOT NULL, + [InitialBudget10] decimal NOT NULL, + [InitialBudget11] decimal NOT NULL, + [InitialBudget12] decimal NOT NULL, + [InitialBudgetTotal] decimal NULL, + [InitialProjection01] decimal NOT NULL, + [InitialProjection02] decimal NOT NULL, + [InitialProjection03] decimal NOT NULL, + [InitialProjection04] decimal NOT NULL, + [InitialProjection05] decimal NOT NULL, + [InitialProjection06] decimal NOT NULL, + [InitialProjection07] decimal NOT NULL, + [InitialProjection08] decimal NOT NULL, + [InitialProjection09] decimal NOT NULL, + [InitialProjection10] decimal NOT NULL, + [InitialProjection11] decimal NOT NULL, + [InitialProjection12] decimal NOT NULL, + [InitialProjectionTotal] decimal NULL, + [VariableDirectUnitCost] decimal NOT NULL, + [ChargeEntityID] int NOT NULL, + [MSDRGID] int NOT NULL, + [UBRevCodeID] int NOT NULL, + [CPTID] int NOT NULL, + [ServiceProviderID] int NOT NULL, + [ServiceProviderSpecialtyID] int NOT NULL, + [BillingProviderID] int NOT NULL, + [BillingProviderSpecialtyID] int NOT NULL, + PRIMARY KEY ([ChargeVolumeID]) +); + +CREATE CLUSTERED INDEX [IX_ArchiveFactChargeVolume] ON [fp].[ArchiveFactChargeVolume] ([ChargeVolumeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactChargeVolume_BudgetConfig] ON [fp].[ArchiveFactChargeVolume] ([BudgetConfigID]) INCLUDE ([ChargeVolumeID], [EntityGroupConfigID], [EntityID], [DepartmentID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactChargeVolume_Department] ON [fp].[ArchiveFactChargeVolume] ([DepartmentID]) INCLUDE ([ChargeVolumeID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactChargeVolume_Entity] ON [fp].[ArchiveFactChargeVolume] ([EntityID]) INCLUDE ([ChargeVolumeID], [BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactChargeVolume_EntityGroupConfig] ON [fp].[ArchiveFactChargeVolume] ([EntityGroupConfigID]) INCLUDE ([ChargeVolumeID], [BudgetConfigID], [EntityID], [DepartmentID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [UnitTypeID]); +GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Budge__02BF3E5B] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Entit__03B36294] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Entit__04A786CD] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Depar__059BAB06] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Servi__068FCF3F] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Patie__0783F378] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__AgeCo__087817B1] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Medic__096C3BEA] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Charg__0A606023] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__UnitT__0B54845C] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__AddDa__0C48A895] DEFAULT (getdate()) FOR [AddDate]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__0D3CCCCE] DEFAULT ((0)) FOR [SampledBudget01]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__0E30F107] DEFAULT ((0)) FOR [SampledBudget02]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__0F251540] DEFAULT ((0)) FOR [SampledBudget03]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__10193979] DEFAULT ((0)) FOR [SampledBudget04]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__110D5DB2] DEFAULT ((0)) FOR [SampledBudget05]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__120181EB] DEFAULT ((0)) FOR [SampledBudget06]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__12F5A624] DEFAULT ((0)) FOR [SampledBudget07]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__13E9CA5D] DEFAULT ((0)) FOR [SampledBudget08]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__14DDEE96] DEFAULT ((0)) FOR [SampledBudget09]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__15D212CF] DEFAULT ((0)) FOR [SampledBudget10]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__16C63708] DEFAULT ((0)) FOR [SampledBudget11]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__17BA5B41] DEFAULT ((0)) FOR [SampledBudget12]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__18AE7F7A] DEFAULT ((0)) FOR [SampledProjection01]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__19A2A3B3] DEFAULT ((0)) FOR [SampledProjection02]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__1A96C7EC] DEFAULT ((0)) FOR [SampledProjection03]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__1B8AEC25] DEFAULT ((0)) FOR [SampledProjection04]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__1C7F105E] DEFAULT ((0)) FOR [SampledProjection05]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__1D733497] DEFAULT ((0)) FOR [SampledProjection06]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__1E6758D0] DEFAULT ((0)) FOR [SampledProjection07]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__1F5B7D09] DEFAULT ((0)) FOR [SampledProjection08]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__204FA142] DEFAULT ((0)) FOR [SampledProjection09]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__2143C57B] DEFAULT ((0)) FOR [SampledProjection10]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__2237E9B4] DEFAULT ((0)) FOR [SampledProjection11]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Sampl__232C0DED] DEFAULT ((0)) FOR [SampledProjection12]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__24203226] DEFAULT ((0)) FOR [InitialBudget01]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__2514565F] DEFAULT ((0)) FOR [InitialBudget02]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__26087A98] DEFAULT ((0)) FOR [InitialBudget03]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__26FC9ED1] DEFAULT ((0)) FOR [InitialBudget04]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__27F0C30A] DEFAULT ((0)) FOR [InitialBudget05]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__28E4E743] DEFAULT ((0)) FOR [InitialBudget06]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__29D90B7C] DEFAULT ((0)) FOR [InitialBudget07]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__2ACD2FB5] DEFAULT ((0)) FOR [InitialBudget08]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__2BC153EE] DEFAULT ((0)) FOR [InitialBudget09]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__2CB57827] DEFAULT ((0)) FOR [InitialBudget10]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__2DA99C60] DEFAULT ((0)) FOR [InitialBudget11]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__2E9DC099] DEFAULT ((0)) FOR [InitialBudget12]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__2F91E4D2] DEFAULT ((0)) FOR [InitialProjection01]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__3086090B] DEFAULT ((0)) FOR [InitialProjection02]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__317A2D44] DEFAULT ((0)) FOR [InitialProjection03]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__326E517D] DEFAULT ((0)) FOR [InitialProjection04]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__336275B6] DEFAULT ((0)) FOR [InitialProjection05]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__345699EF] DEFAULT ((0)) FOR [InitialProjection06]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__354ABE28] DEFAULT ((0)) FOR [InitialProjection07]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__363EE261] DEFAULT ((0)) FOR [InitialProjection08]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__3733069A] DEFAULT ((0)) FOR [InitialProjection09]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__38272AD3] DEFAULT ((0)) FOR [InitialProjection10]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__391B4F0C] DEFAULT ((0)) FOR [InitialProjection11]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Initi__3A0F7345] DEFAULT ((0)) FOR [InitialProjection12]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Varia__3B03977E] DEFAULT ((0)) FOR [VariableDirectUnitCost]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Charg__4F05FDEB] DEFAULT ((0)) FOR [ChargeEntityID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__MSDRG__4FFA2224] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__UBRev__50EE465D] DEFAULT ((0)) FOR [UBRevCodeID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__CPTID__51E26A96] DEFAULT ((0)) FOR [CPTID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Servi__52D68ECF] DEFAULT ((0)) FOR [ServiceProviderID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Servi__53CAB308] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Billi__54BED741] DEFAULT ((0)) FOR [BillingProviderID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolume] ADD CONSTRAINT [DF__ArchiveFa__Billi__55B2FB7A] DEFAULT ((0)) FOR [BillingProviderSpecialtyID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactChargeVolumeBudget ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactChargeVolumeBudget] ( + [RowID] int NOT NULL, + [ChargeVolumeID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedValue01] decimal NOT NULL, + [AdjustedValue02] decimal NOT NULL, + [AdjustedValue03] decimal NOT NULL, + [AdjustedValue04] decimal NOT NULL, + [AdjustedValue05] decimal NOT NULL, + [AdjustedValue06] decimal NOT NULL, + [AdjustedValue07] decimal NOT NULL, + [AdjustedValue08] decimal NOT NULL, + [AdjustedValue09] decimal NOT NULL, + [AdjustedValue10] decimal NOT NULL, + [AdjustedValue11] decimal NOT NULL, + [AdjustedValue12] decimal NOT NULL, + [AdjustedValueTotal] decimal NULL, + [FlexedValue01] decimal NOT NULL, + [FlexedValue02] decimal NOT NULL, + [FlexedValue03] decimal NOT NULL, + [FlexedValue04] decimal NOT NULL, + [FlexedValue05] decimal NOT NULL, + [FlexedValue06] decimal NOT NULL, + [FlexedValue07] decimal NOT NULL, + [FlexedValue08] decimal NOT NULL, + [FlexedValue09] decimal NOT NULL, + [FlexedValue10] decimal NOT NULL, + [FlexedValue11] decimal NOT NULL, + [FlexedValue12] decimal NOT NULL, + [FlexedValueTotal] decimal NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_ArchiveFactChargeVolumeBudget] ON [fp].[ArchiveFactChargeVolumeBudget] ([ChargeVolumeID], [BudgetPhaseID]); +GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [FK_ArchiveFactChargeVolumeBudget_ChargeVolumeID] FOREIGN KEY ([ChargeVolumeID]) REFERENCES [fp].[ArchiveFactChargeVolume] ([ChargeVolumeID]); GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Charg__3DE00429] DEFAULT ((0)) FOR [ChargeVolumeID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__LockT__3ED42862] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__LockF__3FC84C9B] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Budge__40BC70D4] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__41B0950D] DEFAULT ((0)) FOR [AdjustedValue01]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__42A4B946] DEFAULT ((0)) FOR [AdjustedValue02]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4398DD7F] DEFAULT ((0)) FOR [AdjustedValue03]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__448D01B8] DEFAULT ((0)) FOR [AdjustedValue04]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__458125F1] DEFAULT ((0)) FOR [AdjustedValue05]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__46754A2A] DEFAULT ((0)) FOR [AdjustedValue06]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__47696E63] DEFAULT ((0)) FOR [AdjustedValue07]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__485D929C] DEFAULT ((0)) FOR [AdjustedValue08]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4951B6D5] DEFAULT ((0)) FOR [AdjustedValue09]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4A45DB0E] DEFAULT ((0)) FOR [AdjustedValue10]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4B39FF47] DEFAULT ((0)) FOR [AdjustedValue11]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4C2E2380] DEFAULT ((0)) FOR [AdjustedValue12]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__4D2247B9] DEFAULT ((0)) FOR [FlexedValue01]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__4E166BF2] DEFAULT ((0)) FOR [FlexedValue02]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__4F0A902B] DEFAULT ((0)) FOR [FlexedValue03]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__4FFEB464] DEFAULT ((0)) FOR [FlexedValue04]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__50F2D89D] DEFAULT ((0)) FOR [FlexedValue05]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__51E6FCD6] DEFAULT ((0)) FOR [FlexedValue06]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__52DB210F] DEFAULT ((0)) FOR [FlexedValue07]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__53CF4548] DEFAULT ((0)) FOR [FlexedValue08]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__54C36981] DEFAULT ((0)) FOR [FlexedValue09]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__55B78DBA] DEFAULT ((0)) FOR [FlexedValue10]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__56ABB1F3] DEFAULT ((0)) FOR [FlexedValue11]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__579FD62C] DEFAULT ((0)) FOR [FlexedValue12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactChargeVolumeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactChargeVolumeHistory] ( + [RowID] int NOT NULL, + [ChargeVolumeID] int NOT NULL, + [ActualYTDValue01] decimal NOT NULL, + [ActualYTDValue02] decimal NOT NULL, + [ActualYTDValue03] decimal NOT NULL, + [ActualYTDValue04] decimal NOT NULL, + [ActualYTDValue05] decimal NOT NULL, + [ActualYTDValue06] decimal NOT NULL, + [ActualYTDValue07] decimal NOT NULL, + [ActualYTDValue08] decimal NOT NULL, + [ActualYTDValue09] decimal NOT NULL, + [ActualYTDValue10] decimal NOT NULL, + [ActualYTDValue11] decimal NOT NULL, + [ActualYTDValue12] decimal NOT NULL, + [PriorYearActualValue01] decimal NOT NULL, + [PriorYearActualValue02] decimal NOT NULL, + [PriorYearActualValue03] decimal NOT NULL, + [PriorYearActualValue04] decimal NOT NULL, + [PriorYearActualValue05] decimal NOT NULL, + [PriorYearActualValue06] decimal NOT NULL, + [PriorYearActualValue07] decimal NOT NULL, + [PriorYearActualValue08] decimal NOT NULL, + [PriorYearActualValue09] decimal NOT NULL, + [PriorYearActualValue10] decimal NOT NULL, + [PriorYearActualValue11] decimal NOT NULL, + [PriorYearActualValue12] decimal NOT NULL, + [CurrentYearBudgetValue01] decimal NOT NULL, + [CurrentYearBudgetValue02] decimal NOT NULL, + [CurrentYearBudgetValue03] decimal NOT NULL, + [CurrentYearBudgetValue04] decimal NOT NULL, + [CurrentYearBudgetValue05] decimal NOT NULL, + [CurrentYearBudgetValue06] decimal NOT NULL, + [CurrentYearBudgetValue07] decimal NOT NULL, + [CurrentYearBudgetValue08] decimal NOT NULL, + [CurrentYearBudgetValue09] decimal NOT NULL, + [CurrentYearBudgetValue10] decimal NOT NULL, + [CurrentYearBudgetValue11] decimal NOT NULL, + [CurrentYearBudgetValue12] decimal NOT NULL, + [PriorYearActualValueTotal] decimal NOT NULL, + [ActualYTDValueTotal] decimal NOT NULL, + [CurrentYearBudgetValueTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [FK_ArchiveFactChargeVolumeHistory_ChargeVolumeID] FOREIGN KEY ([ChargeVolumeID]) REFERENCES [fp].[ArchiveFactChargeVolume] ([ChargeVolumeID]); GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Charg__04692659] DEFAULT ((0)) FOR [ChargeVolumeID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__055D4A92] DEFAULT ((0)) FOR [ActualYTDValue01]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__06516ECB] DEFAULT ((0)) FOR [ActualYTDValue02]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__07459304] DEFAULT ((0)) FOR [ActualYTDValue03]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0839B73D] DEFAULT ((0)) FOR [ActualYTDValue04]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__092DDB76] DEFAULT ((0)) FOR [ActualYTDValue05]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0A21FFAF] DEFAULT ((0)) FOR [ActualYTDValue06]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0B1623E8] DEFAULT ((0)) FOR [ActualYTDValue07]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0C0A4821] DEFAULT ((0)) FOR [ActualYTDValue08]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0CFE6C5A] DEFAULT ((0)) FOR [ActualYTDValue09]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0DF29093] DEFAULT ((0)) FOR [ActualYTDValue10]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0EE6B4CC] DEFAULT ((0)) FOR [ActualYTDValue11]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0FDAD905] DEFAULT ((0)) FOR [ActualYTDValue12]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__10CEFD3E] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__11C32177] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__12B745B0] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__13AB69E9] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__149F8E22] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__1593B25B] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__1687D694] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__177BFACD] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__18701F06] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__1964433F] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__1A586778] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__1B4C8BB1] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1C40AFEA] DEFAULT ((0)) FOR [CurrentYearBudgetValue01]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1D34D423] DEFAULT ((0)) FOR [CurrentYearBudgetValue02]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1E28F85C] DEFAULT ((0)) FOR [CurrentYearBudgetValue03]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1F1D1C95] DEFAULT ((0)) FOR [CurrentYearBudgetValue04]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__201140CE] DEFAULT ((0)) FOR [CurrentYearBudgetValue05]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__21056507] DEFAULT ((0)) FOR [CurrentYearBudgetValue06]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__21F98940] DEFAULT ((0)) FOR [CurrentYearBudgetValue07]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__22EDAD79] DEFAULT ((0)) FOR [CurrentYearBudgetValue08]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__23E1D1B2] DEFAULT ((0)) FOR [CurrentYearBudgetValue09]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__24D5F5EB] DEFAULT ((0)) FOR [CurrentYearBudgetValue10]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__25CA1A24] DEFAULT ((0)) FOR [CurrentYearBudgetValue11]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__26BE3E5D] DEFAULT ((0)) FOR [CurrentYearBudgetValue12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactChargeVolumeProjection ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactChargeVolumeProjection] ( + [RowID] int NOT NULL, + [ChargeVolumeID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedValue01] decimal NOT NULL, + [AdjustedValue02] decimal NOT NULL, + [AdjustedValue03] decimal NOT NULL, + [AdjustedValue04] decimal NOT NULL, + [AdjustedValue05] decimal NOT NULL, + [AdjustedValue06] decimal NOT NULL, + [AdjustedValue07] decimal NOT NULL, + [AdjustedValue08] decimal NOT NULL, + [AdjustedValue09] decimal NOT NULL, + [AdjustedValue10] decimal NOT NULL, + [AdjustedValue11] decimal NOT NULL, + [AdjustedValue12] decimal NOT NULL, + [AdjustedValueTotal] decimal NULL, + [FlexedValue01] decimal NOT NULL, + [FlexedValue02] decimal NOT NULL, + [FlexedValue03] decimal NOT NULL, + [FlexedValue04] decimal NOT NULL, + [FlexedValue05] decimal NOT NULL, + [FlexedValue06] decimal NOT NULL, + [FlexedValue07] decimal NOT NULL, + [FlexedValue08] decimal NOT NULL, + [FlexedValue09] decimal NOT NULL, + [FlexedValue10] decimal NOT NULL, + [FlexedValue11] decimal NOT NULL, + [FlexedValue12] decimal NOT NULL, + [FlexedValueTotal] decimal NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_ArchiveFactChargeVolumeProjection] ON [fp].[ArchiveFactChargeVolumeProjection] ([ChargeVolumeID], [BudgetPhaseID]); +GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [FK_ArchiveFactChargeVolumeProjection_ChargeVolumeID] FOREIGN KEY ([ChargeVolumeID]) REFERENCES [fp].[ArchiveFactChargeVolume] ([ChargeVolumeID]); GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Charg__5B706710] DEFAULT ((0)) FOR [ChargeVolumeID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__LockT__5C648B49] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__LockF__5D58AF82] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Budge__5E4CD3BB] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5F40F7F4] DEFAULT ((0)) FOR [AdjustedValue01]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__60351C2D] DEFAULT ((0)) FOR [AdjustedValue02]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__61294066] DEFAULT ((0)) FOR [AdjustedValue03]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__621D649F] DEFAULT ((0)) FOR [AdjustedValue04]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__631188D8] DEFAULT ((0)) FOR [AdjustedValue05]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6405AD11] DEFAULT ((0)) FOR [AdjustedValue06]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__64F9D14A] DEFAULT ((0)) FOR [AdjustedValue07]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__65EDF583] DEFAULT ((0)) FOR [AdjustedValue08]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__66E219BC] DEFAULT ((0)) FOR [AdjustedValue09]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__67D63DF5] DEFAULT ((0)) FOR [AdjustedValue10]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__68CA622E] DEFAULT ((0)) FOR [AdjustedValue11]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__69BE8667] DEFAULT ((0)) FOR [AdjustedValue12]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6AB2AAA0] DEFAULT ((0)) FOR [FlexedValue01]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6BA6CED9] DEFAULT ((0)) FOR [FlexedValue02]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6C9AF312] DEFAULT ((0)) FOR [FlexedValue03]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6D8F174B] DEFAULT ((0)) FOR [FlexedValue04]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6E833B84] DEFAULT ((0)) FOR [FlexedValue05]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6F775FBD] DEFAULT ((0)) FOR [FlexedValue06]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__706B83F6] DEFAULT ((0)) FOR [FlexedValue07]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__715FA82F] DEFAULT ((0)) FOR [FlexedValue08]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__7253CC68] DEFAULT ((0)) FOR [FlexedValue09]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__7347F0A1] DEFAULT ((0)) FOR [FlexedValue10]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__743C14DA] DEFAULT ((0)) FOR [FlexedValue11]; GO +ALTER TABLE [fp].[ArchiveFactChargeVolumeProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__75303913] DEFAULT ((0)) FOR [FlexedValue12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactGeneralLedger ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactGeneralLedger] ( + [GeneralLedgerID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [VariabilityID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [APEModelSectionID] tinyint NOT NULL, + [AddDate] datetime NOT NULL, + [SampledBudget01] decimal NOT NULL, + [SampledBudget02] decimal NOT NULL, + [SampledBudget03] decimal NOT NULL, + [SampledBudget04] decimal NOT NULL, + [SampledBudget05] decimal NOT NULL, + [SampledBudget06] decimal NOT NULL, + [SampledBudget07] decimal NOT NULL, + [SampledBudget08] decimal NOT NULL, + [SampledBudget09] decimal NOT NULL, + [SampledBudget10] decimal NOT NULL, + [SampledBudget11] decimal NOT NULL, + [SampledBudget12] decimal NOT NULL, + [SampledBudgetTotal] decimal NULL, + [SampledProjection01] decimal NOT NULL, + [SampledProjection02] decimal NOT NULL, + [SampledProjection03] decimal NOT NULL, + [SampledProjection04] decimal NOT NULL, + [SampledProjection05] decimal NOT NULL, + [SampledProjection06] decimal NOT NULL, + [SampledProjection07] decimal NOT NULL, + [SampledProjection08] decimal NOT NULL, + [SampledProjection09] decimal NOT NULL, + [SampledProjection10] decimal NOT NULL, + [SampledProjection11] decimal NOT NULL, + [SampledProjection12] decimal NOT NULL, + [SampledProjectionTotal] decimal NULL, + [InitialBudget01] decimal NOT NULL, + [InitialBudget02] decimal NOT NULL, + [InitialBudget03] decimal NOT NULL, + [InitialBudget04] decimal NOT NULL, + [InitialBudget05] decimal NOT NULL, + [InitialBudget06] decimal NOT NULL, + [InitialBudget07] decimal NOT NULL, + [InitialBudget08] decimal NOT NULL, + [InitialBudget09] decimal NOT NULL, + [InitialBudget10] decimal NOT NULL, + [InitialBudget11] decimal NOT NULL, + [InitialBudget12] decimal NOT NULL, + [InitialBudgetTotal] decimal NULL, + [InitialProjection01] decimal NOT NULL, + [InitialProjection02] decimal NOT NULL, + [InitialProjection03] decimal NOT NULL, + [InitialProjection04] decimal NOT NULL, + [InitialProjection05] decimal NOT NULL, + [InitialProjection06] decimal NOT NULL, + [InitialProjection07] decimal NOT NULL, + [InitialProjection08] decimal NOT NULL, + [InitialProjection09] decimal NOT NULL, + [InitialProjection10] decimal NOT NULL, + [InitialProjection11] decimal NOT NULL, + [InitialProjection12] decimal NOT NULL, + [InitialProjectionTotal] decimal NULL, + PRIMARY KEY ([GeneralLedgerID]) +); + +CREATE CLUSTERED INDEX [IX_ArchiveFactGeneralLedger] ON [fp].[ArchiveFactGeneralLedger] ([GeneralLedgerID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactGeneralLedger_Account] ON [fp].[ArchiveFactGeneralLedger] ([AccountID]) INCLUDE ([GeneralLedgerID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [FinancialReportingID], [VariabilityID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactGeneralLedger_BudgetConfig] ON [fp].[ArchiveFactGeneralLedger] ([BudgetConfigID]) INCLUDE ([GeneralLedgerID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [VariabilityID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactGeneralLedger_Department] ON [fp].[ArchiveFactGeneralLedger] ([DepartmentID]) INCLUDE ([GeneralLedgerID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [AccountID], [FinancialReportingID], [VariabilityID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactGeneralLedger_Entity] ON [fp].[ArchiveFactGeneralLedger] ([EntityID]) INCLUDE ([GeneralLedgerID], [BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [AccountID], [FinancialReportingID], [VariabilityID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactGeneralLedger_EntityGroupConfig] ON [fp].[ArchiveFactGeneralLedger] ([EntityGroupConfigID]) INCLUDE ([GeneralLedgerID], [BudgetConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [VariabilityID], [UnitTypeID]); +GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Budge__22A1FE08] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Entit__23962241] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Entit__248A467A] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Depar__257E6AB3] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Accou__26728EEC] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Finan__2766B325] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Varia__285AD75E] DEFAULT ((0)) FOR [VariabilityID]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__UnitT__294EFB97] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__APEMo__2A431FD0] DEFAULT ((0)) FOR [APEModelSectionID]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__AddDa__2B374409] DEFAULT (getdate()) FOR [AddDate]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__2C2B6842] DEFAULT ((0)) FOR [SampledBudget01]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__2D1F8C7B] DEFAULT ((0)) FOR [SampledBudget02]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__2E13B0B4] DEFAULT ((0)) FOR [SampledBudget03]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__2F07D4ED] DEFAULT ((0)) FOR [SampledBudget04]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__2FFBF926] DEFAULT ((0)) FOR [SampledBudget05]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__30F01D5F] DEFAULT ((0)) FOR [SampledBudget06]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__31E44198] DEFAULT ((0)) FOR [SampledBudget07]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__32D865D1] DEFAULT ((0)) FOR [SampledBudget08]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__33CC8A0A] DEFAULT ((0)) FOR [SampledBudget09]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__34C0AE43] DEFAULT ((0)) FOR [SampledBudget10]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__35B4D27C] DEFAULT ((0)) FOR [SampledBudget11]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__36A8F6B5] DEFAULT ((0)) FOR [SampledBudget12]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__379D1AEE] DEFAULT ((0)) FOR [SampledProjection01]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__38913F27] DEFAULT ((0)) FOR [SampledProjection02]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__39856360] DEFAULT ((0)) FOR [SampledProjection03]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3A798799] DEFAULT ((0)) FOR [SampledProjection04]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3B6DABD2] DEFAULT ((0)) FOR [SampledProjection05]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3C61D00B] DEFAULT ((0)) FOR [SampledProjection06]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3D55F444] DEFAULT ((0)) FOR [SampledProjection07]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3E4A187D] DEFAULT ((0)) FOR [SampledProjection08]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3F3E3CB6] DEFAULT ((0)) FOR [SampledProjection09]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__403260EF] DEFAULT ((0)) FOR [SampledProjection10]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__41268528] DEFAULT ((0)) FOR [SampledProjection11]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Sampl__421AA961] DEFAULT ((0)) FOR [SampledProjection12]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__430ECD9A] DEFAULT ((0)) FOR [InitialBudget01]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__4402F1D3] DEFAULT ((0)) FOR [InitialBudget02]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__44F7160C] DEFAULT ((0)) FOR [InitialBudget03]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__45EB3A45] DEFAULT ((0)) FOR [InitialBudget04]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__46DF5E7E] DEFAULT ((0)) FOR [InitialBudget05]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__47D382B7] DEFAULT ((0)) FOR [InitialBudget06]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__48C7A6F0] DEFAULT ((0)) FOR [InitialBudget07]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__49BBCB29] DEFAULT ((0)) FOR [InitialBudget08]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__4AAFEF62] DEFAULT ((0)) FOR [InitialBudget09]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__4BA4139B] DEFAULT ((0)) FOR [InitialBudget10]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__4C9837D4] DEFAULT ((0)) FOR [InitialBudget11]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__4D8C5C0D] DEFAULT ((0)) FOR [InitialBudget12]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__4E808046] DEFAULT ((0)) FOR [InitialProjection01]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__4F74A47F] DEFAULT ((0)) FOR [InitialProjection02]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__5068C8B8] DEFAULT ((0)) FOR [InitialProjection03]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__515CECF1] DEFAULT ((0)) FOR [InitialProjection04]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__5251112A] DEFAULT ((0)) FOR [InitialProjection05]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__53453563] DEFAULT ((0)) FOR [InitialProjection06]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__5439599C] DEFAULT ((0)) FOR [InitialProjection07]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__552D7DD5] DEFAULT ((0)) FOR [InitialProjection08]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__5621A20E] DEFAULT ((0)) FOR [InitialProjection09]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__5715C647] DEFAULT ((0)) FOR [InitialProjection10]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__5809EA80] DEFAULT ((0)) FOR [InitialProjection11]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedger] ADD CONSTRAINT [DF__ArchiveFa__Initi__58FE0EB9] DEFAULT ((0)) FOR [InitialProjection12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactGeneralLedgerBudget ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactGeneralLedgerBudget] ( + [RowID] int NOT NULL, + [GeneralLedgerID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedValue01] decimal NOT NULL, + [AdjustedValue02] decimal NOT NULL, + [AdjustedValue03] decimal NOT NULL, + [AdjustedValue04] decimal NOT NULL, + [AdjustedValue05] decimal NOT NULL, + [AdjustedValue06] decimal NOT NULL, + [AdjustedValue07] decimal NOT NULL, + [AdjustedValue08] decimal NOT NULL, + [AdjustedValue09] decimal NOT NULL, + [AdjustedValue10] decimal NOT NULL, + [AdjustedValue11] decimal NOT NULL, + [AdjustedValue12] decimal NOT NULL, + [AdjustedValueTotal] decimal NULL, + [FlexedValue01] decimal NOT NULL, + [FlexedValue02] decimal NOT NULL, + [FlexedValue03] decimal NOT NULL, + [FlexedValue04] decimal NOT NULL, + [FlexedValue05] decimal NOT NULL, + [FlexedValue06] decimal NOT NULL, + [FlexedValue07] decimal NOT NULL, + [FlexedValue08] decimal NOT NULL, + [FlexedValue09] decimal NOT NULL, + [FlexedValue10] decimal NOT NULL, + [FlexedValue11] decimal NOT NULL, + [FlexedValue12] decimal NOT NULL, + [FlexedValueTotal] decimal NULL, + [PercentAdjustmentFactor01] decimal NOT NULL, + [PercentAdjustmentFactor02] decimal NOT NULL, + [PercentAdjustmentFactor03] decimal NOT NULL, + [PercentAdjustmentFactor04] decimal NOT NULL, + [PercentAdjustmentFactor05] decimal NOT NULL, + [PercentAdjustmentFactor06] decimal NOT NULL, + [PercentAdjustmentFactor07] decimal NOT NULL, + [PercentAdjustmentFactor08] decimal NOT NULL, + [PercentAdjustmentFactor09] decimal NOT NULL, + [PercentAdjustmentFactor10] decimal NOT NULL, + [PercentAdjustmentFactor11] decimal NOT NULL, + [PercentAdjustmentFactor12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_ArchiveFactGeneralLedgerBudget] ON [fp].[ArchiveFactGeneralLedgerBudget] ([GeneralLedgerID], [BudgetPhaseID]); +GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [FK_ArchiveFactGeneralLedgerBudget_GeneralLedgerID] FOREIGN KEY ([GeneralLedgerID]) REFERENCES [fp].[ArchiveFactGeneralLedger] ([GeneralLedgerID]); GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Gener__55428C6E] DEFAULT ((0)) FOR [GeneralLedgerID]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__LockT__5636B0A7] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__LockF__572AD4E0] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Budge__581EF919] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__59131D52] DEFAULT ((0)) FOR [AdjustedValue01]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5A07418B] DEFAULT ((0)) FOR [AdjustedValue02]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5AFB65C4] DEFAULT ((0)) FOR [AdjustedValue03]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5BEF89FD] DEFAULT ((0)) FOR [AdjustedValue04]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5CE3AE36] DEFAULT ((0)) FOR [AdjustedValue05]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5DD7D26F] DEFAULT ((0)) FOR [AdjustedValue06]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5ECBF6A8] DEFAULT ((0)) FOR [AdjustedValue07]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5FC01AE1] DEFAULT ((0)) FOR [AdjustedValue08]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__60B43F1A] DEFAULT ((0)) FOR [AdjustedValue09]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__61A86353] DEFAULT ((0)) FOR [AdjustedValue10]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__629C878C] DEFAULT ((0)) FOR [AdjustedValue11]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6390ABC5] DEFAULT ((0)) FOR [AdjustedValue12]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6484CFFE] DEFAULT ((0)) FOR [FlexedValue01]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6578F437] DEFAULT ((0)) FOR [FlexedValue02]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__666D1870] DEFAULT ((0)) FOR [FlexedValue03]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__67613CA9] DEFAULT ((0)) FOR [FlexedValue04]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__685560E2] DEFAULT ((0)) FOR [FlexedValue05]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6949851B] DEFAULT ((0)) FOR [FlexedValue06]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6A3DA954] DEFAULT ((0)) FOR [FlexedValue07]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6B31CD8D] DEFAULT ((0)) FOR [FlexedValue08]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6C25F1C6] DEFAULT ((0)) FOR [FlexedValue09]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6D1A15FF] DEFAULT ((0)) FOR [FlexedValue10]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6E0E3A38] DEFAULT ((0)) FOR [FlexedValue11]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6F025E71] DEFAULT ((0)) FOR [FlexedValue12]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__6FF682AA] DEFAULT ((1)) FOR [PercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__70EAA6E3] DEFAULT ((1)) FOR [PercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__71DECB1C] DEFAULT ((1)) FOR [PercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__72D2EF55] DEFAULT ((1)) FOR [PercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__73C7138E] DEFAULT ((1)) FOR [PercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__74BB37C7] DEFAULT ((1)) FOR [PercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__75AF5C00] DEFAULT ((1)) FOR [PercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__76A38039] DEFAULT ((1)) FOR [PercentAdjustmentFactor08]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__7797A472] DEFAULT ((1)) FOR [PercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__788BC8AB] DEFAULT ((1)) FOR [PercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__797FECE4] DEFAULT ((1)) FOR [PercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__7A74111D] DEFAULT ((1)) FOR [PercentAdjustmentFactor12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactGeneralLedgerHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactGeneralLedgerHistory] ( + [RowID] int NOT NULL, + [GeneralLedgerID] int NOT NULL, + [PriorYearActualValue01] decimal NOT NULL, + [PriorYearActualValue02] decimal NOT NULL, + [PriorYearActualValue03] decimal NOT NULL, + [PriorYearActualValue04] decimal NOT NULL, + [PriorYearActualValue05] decimal NOT NULL, + [PriorYearActualValue06] decimal NOT NULL, + [PriorYearActualValue07] decimal NOT NULL, + [PriorYearActualValue08] decimal NOT NULL, + [PriorYearActualValue09] decimal NOT NULL, + [PriorYearActualValue10] decimal NOT NULL, + [PriorYearActualValue11] decimal NOT NULL, + [PriorYearActualValue12] decimal NOT NULL, + [ActualYTDValue01] decimal NOT NULL, + [ActualYTDValue02] decimal NOT NULL, + [ActualYTDValue03] decimal NOT NULL, + [ActualYTDValue04] decimal NOT NULL, + [ActualYTDValue05] decimal NOT NULL, + [ActualYTDValue06] decimal NOT NULL, + [ActualYTDValue07] decimal NOT NULL, + [ActualYTDValue08] decimal NOT NULL, + [ActualYTDValue09] decimal NOT NULL, + [ActualYTDValue10] decimal NOT NULL, + [ActualYTDValue11] decimal NOT NULL, + [ActualYTDValue12] decimal NOT NULL, + [CurrentYearBudget01] decimal NOT NULL, + [CurrentYearBudget02] decimal NOT NULL, + [CurrentYearBudget03] decimal NOT NULL, + [CurrentYearBudget04] decimal NOT NULL, + [CurrentYearBudget05] decimal NOT NULL, + [CurrentYearBudget06] decimal NOT NULL, + [CurrentYearBudget07] decimal NOT NULL, + [CurrentYearBudget08] decimal NOT NULL, + [CurrentYearBudget09] decimal NOT NULL, + [CurrentYearBudget10] decimal NOT NULL, + [CurrentYearBudget11] decimal NOT NULL, + [CurrentYearBudget12] decimal NOT NULL, + [PriorYearActualValueTotal] decimal NOT NULL, + [ActualYTDValueTotal] decimal NOT NULL, + [CurrentYearBudgetTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [FK_ArchiveFactGeneralLedgerHistory_GeneralLedgerID] FOREIGN KEY ([GeneralLedgerID]) REFERENCES [fp].[ArchiveFactGeneralLedger] ([GeneralLedgerID]); GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Gener__381DD489] DEFAULT ((0)) FOR [GeneralLedgerID]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3911F8C2] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3A061CFB] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3AFA4134] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3BEE656D] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3CE289A6] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3DD6ADDF] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3ECAD218] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3FBEF651] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__40B31A8A] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__41A73EC3] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__429B62FC] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__438F8735] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__4483AB6E] DEFAULT ((0)) FOR [ActualYTDValue01]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__4577CFA7] DEFAULT ((0)) FOR [ActualYTDValue02]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__466BF3E0] DEFAULT ((0)) FOR [ActualYTDValue03]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__47601819] DEFAULT ((0)) FOR [ActualYTDValue04]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__48543C52] DEFAULT ((0)) FOR [ActualYTDValue05]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__4948608B] DEFAULT ((0)) FOR [ActualYTDValue06]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__4A3C84C4] DEFAULT ((0)) FOR [ActualYTDValue07]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__4B30A8FD] DEFAULT ((0)) FOR [ActualYTDValue08]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__4C24CD36] DEFAULT ((0)) FOR [ActualYTDValue09]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__4D18F16F] DEFAULT ((0)) FOR [ActualYTDValue10]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__4E0D15A8] DEFAULT ((0)) FOR [ActualYTDValue11]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__4F0139E1] DEFAULT ((0)) FOR [ActualYTDValue12]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4FF55E1A] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__50E98253] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__51DDA68C] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__52D1CAC5] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__53C5EEFE] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__54BA1337] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__55AE3770] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__56A25BA9] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__57967FE2] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__588AA41B] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__597EC854] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__5A72EC8D] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactGeneralLedgerProjection ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactGeneralLedgerProjection] ( + [RowID] int NOT NULL, + [GeneralLedgerID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedValue01] decimal NOT NULL, + [AdjustedValue02] decimal NOT NULL, + [AdjustedValue03] decimal NOT NULL, + [AdjustedValue04] decimal NOT NULL, + [AdjustedValue05] decimal NOT NULL, + [AdjustedValue06] decimal NOT NULL, + [AdjustedValue07] decimal NOT NULL, + [AdjustedValue08] decimal NOT NULL, + [AdjustedValue09] decimal NOT NULL, + [AdjustedValue10] decimal NOT NULL, + [AdjustedValue11] decimal NOT NULL, + [AdjustedValue12] decimal NOT NULL, + [AdjustedValueTotal] decimal NULL, + [FlexedValue01] decimal NOT NULL, + [FlexedValue02] decimal NOT NULL, + [FlexedValue03] decimal NOT NULL, + [FlexedValue04] decimal NOT NULL, + [FlexedValue05] decimal NOT NULL, + [FlexedValue06] decimal NOT NULL, + [FlexedValue07] decimal NOT NULL, + [FlexedValue08] decimal NOT NULL, + [FlexedValue09] decimal NOT NULL, + [FlexedValue10] decimal NOT NULL, + [FlexedValue11] decimal NOT NULL, + [FlexedValue12] decimal NOT NULL, + [FlexedValueTotal] decimal NULL, + [PercentAdjustmentFactor01] decimal NOT NULL, + [PercentAdjustmentFactor02] decimal NOT NULL, + [PercentAdjustmentFactor03] decimal NOT NULL, + [PercentAdjustmentFactor04] decimal NOT NULL, + [PercentAdjustmentFactor05] decimal NOT NULL, + [PercentAdjustmentFactor06] decimal NOT NULL, + [PercentAdjustmentFactor07] decimal NOT NULL, + [PercentAdjustmentFactor08] decimal NOT NULL, + [PercentAdjustmentFactor09] decimal NOT NULL, + [PercentAdjustmentFactor10] decimal NOT NULL, + [PercentAdjustmentFactor11] decimal NOT NULL, + [PercentAdjustmentFactor12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_ArchiveFactGeneralLedgerProjection] ON [fp].[ArchiveFactGeneralLedgerProjection] ([GeneralLedgerID], [BudgetPhaseID]); +GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [FK_ArchiveFactGeneralLedgerProjection_GeneralLedgerID] FOREIGN KEY ([GeneralLedgerID]) REFERENCES [fp].[ArchiveFactGeneralLedger] ([GeneralLedgerID]); GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__LockF__002CEA73] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Budge__01210EAC] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__021532E5] DEFAULT ((0)) FOR [AdjustedValue01]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0309571E] DEFAULT ((0)) FOR [AdjustedValue02]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__03FD7B57] DEFAULT ((0)) FOR [AdjustedValue03]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__04F19F90] DEFAULT ((0)) FOR [AdjustedValue04]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__05E5C3C9] DEFAULT ((0)) FOR [AdjustedValue05]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__06D9E802] DEFAULT ((0)) FOR [AdjustedValue06]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__07CE0C3B] DEFAULT ((0)) FOR [AdjustedValue07]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__08C23074] DEFAULT ((0)) FOR [AdjustedValue08]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__09B654AD] DEFAULT ((0)) FOR [AdjustedValue09]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0AAA78E6] DEFAULT ((0)) FOR [AdjustedValue10]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0B9E9D1F] DEFAULT ((0)) FOR [AdjustedValue11]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0C92C158] DEFAULT ((0)) FOR [AdjustedValue12]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__0D86E591] DEFAULT ((0)) FOR [FlexedValue01]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__0E7B09CA] DEFAULT ((0)) FOR [FlexedValue02]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__0F6F2E03] DEFAULT ((0)) FOR [FlexedValue03]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1063523C] DEFAULT ((0)) FOR [FlexedValue04]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__11577675] DEFAULT ((0)) FOR [FlexedValue05]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__124B9AAE] DEFAULT ((0)) FOR [FlexedValue06]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__133FBEE7] DEFAULT ((0)) FOR [FlexedValue07]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1433E320] DEFAULT ((0)) FOR [FlexedValue08]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__15280759] DEFAULT ((0)) FOR [FlexedValue09]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__161C2B92] DEFAULT ((0)) FOR [FlexedValue10]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__17104FCB] DEFAULT ((0)) FOR [FlexedValue11]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__18047404] DEFAULT ((0)) FOR [FlexedValue12]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__18F8983D] DEFAULT ((1)) FOR [PercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__19ECBC76] DEFAULT ((1)) FOR [PercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__1AE0E0AF] DEFAULT ((1)) FOR [PercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__1BD504E8] DEFAULT ((1)) FOR [PercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__1CC92921] DEFAULT ((1)) FOR [PercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__1DBD4D5A] DEFAULT ((1)) FOR [PercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__1EB17193] DEFAULT ((1)) FOR [PercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__1FA595CC] DEFAULT ((1)) FOR [PercentAdjustmentFactor08]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__2099BA05] DEFAULT ((1)) FOR [PercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__218DDE3E] DEFAULT ((1)) FOR [PercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__22820277] DEFAULT ((1)) FOR [PercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__237626B0] DEFAULT ((1)) FOR [PercentAdjustmentFactor12]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__Gener__7E44A201] DEFAULT ((0)) FOR [GeneralLedgerID]; GO +ALTER TABLE [fp].[ArchiveFactGeneralLedgerProjection] ADD CONSTRAINT [DF__ArchiveFa__LockT__7F38C63A] DEFAULT ((0)) FOR [LockType]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactReimbursementCharges ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactReimbursementCharges] ( + [ReimbursementChargesID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [DepartmentID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [MSDRGID] int NOT NULL, + [PrimaryCPTID] int NOT NULL, + [UBRevCodeID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [AddDate] datetime NOT NULL, + [InitialBudgetChargeDollars01] decimal NOT NULL, + [InitialBudgetChargeDollars02] decimal NOT NULL, + [InitialBudgetChargeDollars03] decimal NOT NULL, + [InitialBudgetChargeDollars04] decimal NOT NULL, + [InitialBudgetChargeDollars05] decimal NOT NULL, + [InitialBudgetChargeDollars06] decimal NOT NULL, + [InitialBudgetChargeDollars07] decimal NOT NULL, + [InitialBudgetChargeDollars08] decimal NOT NULL, + [InitialBudgetChargeDollars09] decimal NOT NULL, + [InitialBudgetChargeDollars10] decimal NOT NULL, + [InitialBudgetChargeDollars11] decimal NOT NULL, + [InitialBudgetChargeDollars12] decimal NOT NULL, + [InitialBudgetChargeDollarsTotal] decimal NOT NULL, + [InitialBudgetChargeUnits01] decimal NOT NULL, + [InitialBudgetChargeUnits02] decimal NOT NULL, + [InitialBudgetChargeUnits03] decimal NOT NULL, + [InitialBudgetChargeUnits04] decimal NOT NULL, + [InitialBudgetChargeUnits05] decimal NOT NULL, + [InitialBudgetChargeUnits06] decimal NOT NULL, + [InitialBudgetChargeUnits07] decimal NOT NULL, + [InitialBudgetChargeUnits08] decimal NOT NULL, + [InitialBudgetChargeUnits09] decimal NOT NULL, + [InitialBudgetChargeUnits10] decimal NOT NULL, + [InitialBudgetChargeUnits11] decimal NOT NULL, + [InitialBudgetChargeUnits12] decimal NOT NULL, + [InitialBudgetChargeUnitsTotal] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge01] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge02] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge03] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge04] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge05] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge06] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge07] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge08] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge09] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge10] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge11] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge12] decimal NOT NULL, + [InitialBudgetNetPerDiem01] decimal NOT NULL, + [InitialBudgetNetPerDiem02] decimal NOT NULL, + [InitialBudgetNetPerDiem03] decimal NOT NULL, + [InitialBudgetNetPerDiem04] decimal NOT NULL, + [InitialBudgetNetPerDiem05] decimal NOT NULL, + [InitialBudgetNetPerDiem06] decimal NOT NULL, + [InitialBudgetNetPerDiem07] decimal NOT NULL, + [InitialBudgetNetPerDiem08] decimal NOT NULL, + [InitialBudgetNetPerDiem09] decimal NOT NULL, + [InitialBudgetNetPerDiem10] decimal NOT NULL, + [InitialBudgetNetPerDiem11] decimal NOT NULL, + [InitialBudgetNetPerDiem12] decimal NOT NULL, + [InitialProjectionChargeDollars01] decimal NOT NULL, + [InitialProjectionChargeDollars02] decimal NOT NULL, + [InitialProjectionChargeDollars03] decimal NOT NULL, + [InitialProjectionChargeDollars04] decimal NOT NULL, + [InitialProjectionChargeDollars05] decimal NOT NULL, + [InitialProjectionChargeDollars06] decimal NOT NULL, + [InitialProjectionChargeDollars07] decimal NOT NULL, + [InitialProjectionChargeDollars08] decimal NOT NULL, + [InitialProjectionChargeDollars09] decimal NOT NULL, + [InitialProjectionChargeDollars10] decimal NOT NULL, + [InitialProjectionChargeDollars11] decimal NOT NULL, + [InitialProjectionChargeDollars12] decimal NOT NULL, + [InitialProjectionChargeDollarsTotal] decimal NOT NULL, + [InitialProjectionChargeUnits01] decimal NOT NULL, + [InitialProjectionChargeUnits02] decimal NOT NULL, + [InitialProjectionChargeUnits03] decimal NOT NULL, + [InitialProjectionChargeUnits04] decimal NOT NULL, + [InitialProjectionChargeUnits05] decimal NOT NULL, + [InitialProjectionChargeUnits06] decimal NOT NULL, + [InitialProjectionChargeUnits07] decimal NOT NULL, + [InitialProjectionChargeUnits08] decimal NOT NULL, + [InitialProjectionChargeUnits09] decimal NOT NULL, + [InitialProjectionChargeUnits10] decimal NOT NULL, + [InitialProjectionChargeUnits11] decimal NOT NULL, + [InitialProjectionChargeUnits12] decimal NOT NULL, + [InitialProjectionChargeUnitsTotal] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge01] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge02] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge03] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge04] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge05] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge06] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge07] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge08] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge09] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge10] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge11] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge12] decimal NOT NULL, + [InitialProjectionNetPerDiem01] decimal NOT NULL, + [InitialProjectionNetPerDiem02] decimal NOT NULL, + [InitialProjectionNetPerDiem03] decimal NOT NULL, + [InitialProjectionNetPerDiem04] decimal NOT NULL, + [InitialProjectionNetPerDiem05] decimal NOT NULL, + [InitialProjectionNetPerDiem06] decimal NOT NULL, + [InitialProjectionNetPerDiem07] decimal NOT NULL, + [InitialProjectionNetPerDiem08] decimal NOT NULL, + [InitialProjectionNetPerDiem09] decimal NOT NULL, + [InitialProjectionNetPerDiem10] decimal NOT NULL, + [InitialProjectionNetPerDiem11] decimal NOT NULL, + [InitialProjectionNetPerDiem12] decimal NOT NULL, + [IsNew] bit NOT NULL, + PRIMARY KEY ([ReimbursementChargesID]) +); +GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [FK_ArchiveFactReimbursementCharges_CPT] FOREIGN KEY ([PrimaryCPTID]) REFERENCES [dss].[DimCPT] ([CPTID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [FK_ArchiveFactReimbursementCharges_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [FK_ArchiveFactReimbursementCharges_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [FK_ArchiveFactReimbursementCharges_MedicalSurgical] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [FK_ArchiveFactReimbursementCharges_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [FK_ArchiveFactReimbursementCharges_Payor] FOREIGN KEY ([PayorID]) REFERENCES [fw].[DimPayor] ([PayorID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [FK_ArchiveFactReimbursementCharges_PayorGroup] FOREIGN KEY ([PayorGroupID]) REFERENCES [fw].[DimPayorGroup] ([PayorGroupID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [FK_ArchiveFactReimbursementCharges_ServiceLine] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [FK_ArchiveFactReimbursementCharges_ServiceLineRollup] FOREIGN KEY ([ServiceLineRollupID]) REFERENCES [fw].[DimServiceLineRollup] ([ServiceLineRollupID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [FK_ArchiveFactReimbursementCharges_UnitType] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__00A9DD25] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__019E015E] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__02922597] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__038649D0] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__047A6E09] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__056E9242] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__0662B67B] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__IsNew__0756DAB4] DEFAULT ((0)) FOR [IsNew]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Budge__1D7B25FD] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Entit__1E6F4A36] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Entit__1F636E6F] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Patie__205792A8] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Servi__214BB6E1] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Servi__223FDB1A] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Medic__2333FF53] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Depar__2428238C] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Payor__251C47C5] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Payor__26106BFE] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__MSDRG__27049037] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Prima__27F8B470] DEFAULT ((0)) FOR [PrimaryCPTID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__UBRev__28ECD8A9] DEFAULT ((0)) FOR [UBRevCodeID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__UnitT__29E0FCE2] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF_ArchiveReimbursementCharges_AddDate] DEFAULT ('1900-01-01') FOR [AddDate]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__2BC94554] DEFAULT ((0)) FOR [InitialBudgetChargeDollars01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__2CBD698D] DEFAULT ((0)) FOR [InitialBudgetChargeDollars02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__2DB18DC6] DEFAULT ((0)) FOR [InitialBudgetChargeDollars03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__2EA5B1FF] DEFAULT ((0)) FOR [InitialBudgetChargeDollars04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__2F99D638] DEFAULT ((0)) FOR [InitialBudgetChargeDollars05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__308DFA71] DEFAULT ((0)) FOR [InitialBudgetChargeDollars06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__31821EAA] DEFAULT ((0)) FOR [InitialBudgetChargeDollars07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__327642E3] DEFAULT ((0)) FOR [InitialBudgetChargeDollars08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__336A671C] DEFAULT ((0)) FOR [InitialBudgetChargeDollars09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__345E8B55] DEFAULT ((0)) FOR [InitialBudgetChargeDollars10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__3552AF8E] DEFAULT ((0)) FOR [InitialBudgetChargeDollars11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__3646D3C7] DEFAULT ((0)) FOR [InitialBudgetChargeDollars12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__373AF800] DEFAULT ((0)) FOR [InitialBudgetChargeUnits01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__382F1C39] DEFAULT ((0)) FOR [InitialBudgetChargeUnits02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__39234072] DEFAULT ((0)) FOR [InitialBudgetChargeUnits03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__3A1764AB] DEFAULT ((0)) FOR [InitialBudgetChargeUnits04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__3B0B88E4] DEFAULT ((0)) FOR [InitialBudgetChargeUnits05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__3BFFAD1D] DEFAULT ((0)) FOR [InitialBudgetChargeUnits06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__3CF3D156] DEFAULT ((0)) FOR [InitialBudgetChargeUnits07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__3DE7F58F] DEFAULT ((0)) FOR [InitialBudgetChargeUnits08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__3EDC19C8] DEFAULT ((0)) FOR [InitialBudgetChargeUnits09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__3FD03E01] DEFAULT ((0)) FOR [InitialBudgetChargeUnits10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__40C4623A] DEFAULT ((0)) FOR [InitialBudgetChargeUnits11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__41B88673] DEFAULT ((0)) FOR [InitialBudgetChargeUnits12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__42ACAAAC] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__43A0CEE5] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__4494F31E] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__45891757] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__467D3B90] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__47715FC9] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__48658402] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__4959A83B] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__4A4DCC74] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__4B41F0AD] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__4C3614E6] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__4D2A391F] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__4E1E5D58] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__4F128191] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__5006A5CA] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__50FACA03] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__51EEEE3C] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__52E31275] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__53D736AE] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__54CB5AE7] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__55BF7F20] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__56B3A359] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__57A7C792] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__589BEBCB] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__59901004] DEFAULT ((0)) FOR [InitialProjectionChargeDollars01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__5A84343D] DEFAULT ((0)) FOR [InitialProjectionChargeDollars02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__5B785876] DEFAULT ((0)) FOR [InitialProjectionChargeDollars03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__5C6C7CAF] DEFAULT ((0)) FOR [InitialProjectionChargeDollars04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__5D60A0E8] DEFAULT ((0)) FOR [InitialProjectionChargeDollars05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__5E54C521] DEFAULT ((0)) FOR [InitialProjectionChargeDollars06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__5F48E95A] DEFAULT ((0)) FOR [InitialProjectionChargeDollars07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__603D0D93] DEFAULT ((0)) FOR [InitialProjectionChargeDollars08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__613131CC] DEFAULT ((0)) FOR [InitialProjectionChargeDollars09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__62255605] DEFAULT ((0)) FOR [InitialProjectionChargeDollars10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__63197A3E] DEFAULT ((0)) FOR [InitialProjectionChargeDollars11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__640D9E77] DEFAULT ((0)) FOR [InitialProjectionChargeDollars12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__6501C2B0] DEFAULT ((0)) FOR [InitialProjectionChargeUnits01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__65F5E6E9] DEFAULT ((0)) FOR [InitialProjectionChargeUnits02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__66EA0B22] DEFAULT ((0)) FOR [InitialProjectionChargeUnits03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__67DE2F5B] DEFAULT ((0)) FOR [InitialProjectionChargeUnits04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__68D25394] DEFAULT ((0)) FOR [InitialProjectionChargeUnits05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__69C677CD] DEFAULT ((0)) FOR [InitialProjectionChargeUnits06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__6ABA9C06] DEFAULT ((0)) FOR [InitialProjectionChargeUnits07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__6BAEC03F] DEFAULT ((0)) FOR [InitialProjectionChargeUnits08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__6CA2E478] DEFAULT ((0)) FOR [InitialProjectionChargeUnits09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__6D9708B1] DEFAULT ((0)) FOR [InitialProjectionChargeUnits10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__6E8B2CEA] DEFAULT ((0)) FOR [InitialProjectionChargeUnits11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__6F7F5123] DEFAULT ((0)) FOR [InitialProjectionChargeUnits12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__7073755C] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__71679995] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__725BBDCE] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__734FE207] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__74440640] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__75382A79] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__762C4EB2] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__772072EB] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__78149724] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__7908BB5D] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__79FCDF96] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__7AF103CF] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__7BE52808] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__7CD94C41] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__7DCD707A] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__7EC194B3] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementCharges] ADD CONSTRAINT [DF__ArchiveFa__Initi__7FB5B8EC] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem05]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactReimbursementChargesBudget ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactReimbursementChargesBudget] ( + [RowID] int NOT NULL, + [ReimbursementChargesID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedChargeDollars01] decimal NOT NULL, + [AdjustedChargeDollars02] decimal NOT NULL, + [AdjustedChargeDollars03] decimal NOT NULL, + [AdjustedChargeDollars04] decimal NOT NULL, + [AdjustedChargeDollars05] decimal NOT NULL, + [AdjustedChargeDollars06] decimal NOT NULL, + [AdjustedChargeDollars07] decimal NOT NULL, + [AdjustedChargeDollars08] decimal NOT NULL, + [AdjustedChargeDollars09] decimal NOT NULL, + [AdjustedChargeDollars10] decimal NOT NULL, + [AdjustedChargeDollars11] decimal NOT NULL, + [AdjustedChargeDollars12] decimal NOT NULL, + [AdjustedChargeDollarsTotal] decimal NOT NULL, + [AdjustedChargeUnits01] decimal NOT NULL, + [AdjustedChargeUnits02] decimal NOT NULL, + [AdjustedChargeUnits03] decimal NOT NULL, + [AdjustedChargeUnits04] decimal NOT NULL, + [AdjustedChargeUnits05] decimal NOT NULL, + [AdjustedChargeUnits06] decimal NOT NULL, + [AdjustedChargeUnits07] decimal NOT NULL, + [AdjustedChargeUnits08] decimal NOT NULL, + [AdjustedChargeUnits09] decimal NOT NULL, + [AdjustedChargeUnits10] decimal NOT NULL, + [AdjustedChargeUnits11] decimal NOT NULL, + [AdjustedChargeUnits12] decimal NOT NULL, + [AdjustedChargeUnitsTotal] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge01] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge02] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge03] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge04] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge05] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge06] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge07] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge08] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge09] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge10] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge11] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge12] decimal NOT NULL, + [AdjustedNetPerDiem01] decimal NOT NULL, + [AdjustedNetPerDiem02] decimal NOT NULL, + [AdjustedNetPerDiem03] decimal NOT NULL, + [AdjustedNetPerDiem04] decimal NOT NULL, + [AdjustedNetPerDiem05] decimal NOT NULL, + [AdjustedNetPerDiem06] decimal NOT NULL, + [AdjustedNetPerDiem07] decimal NOT NULL, + [AdjustedNetPerDiem08] decimal NOT NULL, + [AdjustedNetPerDiem09] decimal NOT NULL, + [AdjustedNetPerDiem10] decimal NOT NULL, + [AdjustedNetPerDiem11] decimal NOT NULL, + [AdjustedNetPerDiem12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [FK_ArchiveFactReimbursementChargesBudget_ReimbursementChargesID] FOREIGN KEY ([ReimbursementChargesID]) REFERENCES [fp].[FactReimbursementCharges] ([ReimbursementChargesID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__003FC8D1] DEFAULT ((0)) FOR [AdjustedNetPerDiem02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0133ED0A] DEFAULT ((0)) FOR [AdjustedNetPerDiem03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__02281143] DEFAULT ((0)) FOR [AdjustedNetPerDiem04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__031C357C] DEFAULT ((0)) FOR [AdjustedNetPerDiem05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__041059B5] DEFAULT ((0)) FOR [AdjustedNetPerDiem06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__05047DEE] DEFAULT ((0)) FOR [AdjustedNetPerDiem07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__05F8A227] DEFAULT ((0)) FOR [AdjustedNetPerDiem08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__06ECC660] DEFAULT ((0)) FOR [AdjustedNetPerDiem09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__07E0EA99] DEFAULT ((0)) FOR [AdjustedNetPerDiem10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__08D50ED2] DEFAULT ((0)) FOR [AdjustedNetPerDiem11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__09C9330B] DEFAULT ((0)) FOR [AdjustedNetPerDiem12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Reimb__5925FBB0] DEFAULT ((0)) FOR [ReimbursementChargesID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__LockT__5A1A1FE9] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__LockF__5B0E4422] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Budge__5C02685B] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5CF68C94] DEFAULT ((0)) FOR [AdjustedChargeDollars01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5DEAB0CD] DEFAULT ((0)) FOR [AdjustedChargeDollars02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5EDED506] DEFAULT ((0)) FOR [AdjustedChargeDollars03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5FD2F93F] DEFAULT ((0)) FOR [AdjustedChargeDollars04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__60C71D78] DEFAULT ((0)) FOR [AdjustedChargeDollars05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__61BB41B1] DEFAULT ((0)) FOR [AdjustedChargeDollars06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__62AF65EA] DEFAULT ((0)) FOR [AdjustedChargeDollars07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__63A38A23] DEFAULT ((0)) FOR [AdjustedChargeDollars08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6497AE5C] DEFAULT ((0)) FOR [AdjustedChargeDollars09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__658BD295] DEFAULT ((0)) FOR [AdjustedChargeDollars10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__667FF6CE] DEFAULT ((0)) FOR [AdjustedChargeDollars11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__67741B07] DEFAULT ((0)) FOR [AdjustedChargeDollars12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__68683F40] DEFAULT ((0)) FOR [AdjustedChargeUnits01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__695C6379] DEFAULT ((0)) FOR [AdjustedChargeUnits02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6A5087B2] DEFAULT ((0)) FOR [AdjustedChargeUnits03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6B44ABEB] DEFAULT ((0)) FOR [AdjustedChargeUnits04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6C38D024] DEFAULT ((0)) FOR [AdjustedChargeUnits05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6D2CF45D] DEFAULT ((0)) FOR [AdjustedChargeUnits06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6E211896] DEFAULT ((0)) FOR [AdjustedChargeUnits07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6F153CCF] DEFAULT ((0)) FOR [AdjustedChargeUnits08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__70096108] DEFAULT ((0)) FOR [AdjustedChargeUnits09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__70FD8541] DEFAULT ((0)) FOR [AdjustedChargeUnits10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__71F1A97A] DEFAULT ((0)) FOR [AdjustedChargeUnits11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__72E5CDB3] DEFAULT ((0)) FOR [AdjustedChargeUnits12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__73D9F1EC] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__74CE1625] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__75C23A5E] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__76B65E97] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__77AA82D0] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__789EA709] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__7992CB42] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__7A86EF7B] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__7B7B13B4] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__7C6F37ED] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__7D635C26] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__7E57805F] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__7F4BA498] DEFAULT ((0)) FOR [AdjustedNetPerDiem01]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactReimbursementChargesHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactReimbursementChargesHistory] ( + [RowID] int NOT NULL, + [ReimbursementChargesID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [PriorYearActualChargeDollars01] decimal NOT NULL, + [PriorYearActualChargeDollars02] decimal NOT NULL, + [PriorYearActualChargeDollars03] decimal NOT NULL, + [PriorYearActualChargeDollars04] decimal NOT NULL, + [PriorYearActualChargeDollars05] decimal NOT NULL, + [PriorYearActualChargeDollars06] decimal NOT NULL, + [PriorYearActualChargeDollars07] decimal NOT NULL, + [PriorYearActualChargeDollars08] decimal NOT NULL, + [PriorYearActualChargeDollars09] decimal NOT NULL, + [PriorYearActualChargeDollars10] decimal NOT NULL, + [PriorYearActualChargeDollars11] decimal NOT NULL, + [PriorYearActualChargeDollars12] decimal NOT NULL, + [PriorYearActualChargeDollarsTotal] decimal NOT NULL, + [ActualYTDChargeDollars01] decimal NOT NULL, + [ActualYTDChargeDollars02] decimal NOT NULL, + [ActualYTDChargeDollars03] decimal NOT NULL, + [ActualYTDChargeDollars04] decimal NOT NULL, + [ActualYTDChargeDollars05] decimal NOT NULL, + [ActualYTDChargeDollars06] decimal NOT NULL, + [ActualYTDChargeDollars07] decimal NOT NULL, + [ActualYTDChargeDollars08] decimal NOT NULL, + [ActualYTDChargeDollars09] decimal NOT NULL, + [ActualYTDChargeDollars10] decimal NOT NULL, + [ActualYTDChargeDollars11] decimal NOT NULL, + [ActualYTDChargeDollars12] decimal NOT NULL, + [ActualYTDChargeDollarsTotal] decimal NOT NULL, + [CurrentYearBudgetChargeDollars01] decimal NOT NULL, + [CurrentYearBudgetChargeDollars02] decimal NOT NULL, + [CurrentYearBudgetChargeDollars03] decimal NOT NULL, + [CurrentYearBudgetChargeDollars04] decimal NOT NULL, + [CurrentYearBudgetChargeDollars05] decimal NOT NULL, + [CurrentYearBudgetChargeDollars06] decimal NOT NULL, + [CurrentYearBudgetChargeDollars07] decimal NOT NULL, + [CurrentYearBudgetChargeDollars08] decimal NOT NULL, + [CurrentYearBudgetChargeDollars09] decimal NOT NULL, + [CurrentYearBudgetChargeDollars10] decimal NOT NULL, + [CurrentYearBudgetChargeDollars11] decimal NOT NULL, + [CurrentYearBudgetChargeDollars12] decimal NOT NULL, + [CurrentYearBudgetChargeDollarsTotal] decimal NOT NULL, + [PriorYearActualChargeUnits01] decimal NOT NULL, + [PriorYearActualChargeUnits02] decimal NOT NULL, + [PriorYearActualChargeUnits03] decimal NOT NULL, + [PriorYearActualChargeUnits04] decimal NOT NULL, + [PriorYearActualChargeUnits05] decimal NOT NULL, + [PriorYearActualChargeUnits06] decimal NOT NULL, + [PriorYearActualChargeUnits07] decimal NOT NULL, + [PriorYearActualChargeUnits08] decimal NOT NULL, + [PriorYearActualChargeUnits09] decimal NOT NULL, + [PriorYearActualChargeUnits10] decimal NOT NULL, + [PriorYearActualChargeUnits11] decimal NOT NULL, + [PriorYearActualChargeUnits12] decimal NOT NULL, + [PriorYearActualChargeUnitsTotal] decimal NOT NULL, + [ActualYTDChargeUnits01] decimal NOT NULL, + [ActualYTDChargeUnits02] decimal NOT NULL, + [ActualYTDChargeUnits03] decimal NOT NULL, + [ActualYTDChargeUnits04] decimal NOT NULL, + [ActualYTDChargeUnits05] decimal NOT NULL, + [ActualYTDChargeUnits06] decimal NOT NULL, + [ActualYTDChargeUnits07] decimal NOT NULL, + [ActualYTDChargeUnits08] decimal NOT NULL, + [ActualYTDChargeUnits09] decimal NOT NULL, + [ActualYTDChargeUnits10] decimal NOT NULL, + [ActualYTDChargeUnits11] decimal NOT NULL, + [ActualYTDChargeUnits12] decimal NOT NULL, + [ActualYTDChargeUnitsTotal] decimal NOT NULL, + [CurrentYearBudgetChargeUnits01] decimal NOT NULL, + [CurrentYearBudgetChargeUnits02] decimal NOT NULL, + [CurrentYearBudgetChargeUnits03] decimal NOT NULL, + [CurrentYearBudgetChargeUnits04] decimal NOT NULL, + [CurrentYearBudgetChargeUnits05] decimal NOT NULL, + [CurrentYearBudgetChargeUnits06] decimal NOT NULL, + [CurrentYearBudgetChargeUnits07] decimal NOT NULL, + [CurrentYearBudgetChargeUnits08] decimal NOT NULL, + [CurrentYearBudgetChargeUnits09] decimal NOT NULL, + [CurrentYearBudgetChargeUnits10] decimal NOT NULL, + [CurrentYearBudgetChargeUnits11] decimal NOT NULL, + [CurrentYearBudgetChargeUnits12] decimal NOT NULL, + [CurrentYearBudgetChargeUnitsTotal] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge01] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge02] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge03] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge04] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge05] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge06] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge07] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge08] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge09] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge10] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge11] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge12] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge01] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge02] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge03] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge04] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge05] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge06] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge07] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge08] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge09] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge10] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge11] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge12] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge01] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge02] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge03] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge04] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge05] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge06] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge07] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge08] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge09] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge10] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge11] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge12] decimal NOT NULL, + [PriorYearActualNetPerDiem01] decimal NOT NULL, + [PriorYearActualNetPerDiem02] decimal NOT NULL, + [PriorYearActualNetPerDiem03] decimal NOT NULL, + [PriorYearActualNetPerDiem04] decimal NOT NULL, + [PriorYearActualNetPerDiem05] decimal NOT NULL, + [PriorYearActualNetPerDiem06] decimal NOT NULL, + [PriorYearActualNetPerDiem07] decimal NOT NULL, + [PriorYearActualNetPerDiem08] decimal NOT NULL, + [PriorYearActualNetPerDiem09] decimal NOT NULL, + [PriorYearActualNetPerDiem10] decimal NOT NULL, + [PriorYearActualNetPerDiem11] decimal NOT NULL, + [PriorYearActualNetPerDiem12] decimal NOT NULL, + [ActualYTDNetPerDiem01] decimal NOT NULL, + [ActualYTDNetPerDiem02] decimal NOT NULL, + [ActualYTDNetPerDiem03] decimal NOT NULL, + [ActualYTDNetPerDiem04] decimal NOT NULL, + [ActualYTDNetPerDiem05] decimal NOT NULL, + [ActualYTDNetPerDiem06] decimal NOT NULL, + [ActualYTDNetPerDiem07] decimal NOT NULL, + [ActualYTDNetPerDiem08] decimal NOT NULL, + [ActualYTDNetPerDiem09] decimal NOT NULL, + [ActualYTDNetPerDiem10] decimal NOT NULL, + [ActualYTDNetPerDiem11] decimal NOT NULL, + [ActualYTDNetPerDiem12] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem01] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem02] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem03] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem04] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem05] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem06] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem07] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem08] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem09] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem10] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem11] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [FK_ArchiveFactReimbursementChargesHistory_ReimbursementChargesID] FOREIGN KEY ([ReimbursementChargesID]) REFERENCES [fp].[FactReimbursementCharges] ([ReimbursementChargesID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0094CE8C] DEFAULT ((0)) FOR [ActualYTDNetPerDiem05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0188F2C5] DEFAULT ((0)) FOR [ActualYTDNetPerDiem06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__027D16FE] DEFAULT ((0)) FOR [ActualYTDNetPerDiem07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__03713B37] DEFAULT ((0)) FOR [ActualYTDNetPerDiem08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__04655F70] DEFAULT ((0)) FOR [ActualYTDNetPerDiem09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__055983A9] DEFAULT ((0)) FOR [ActualYTDNetPerDiem10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__064DA7E2] DEFAULT ((0)) FOR [ActualYTDNetPerDiem11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Reimb__0682B20C] DEFAULT ((0)) FOR [ReimbursementChargesID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0741CC1B] DEFAULT ((0)) FOR [ActualYTDNetPerDiem12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__LockT__0776D645] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__0835F054] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__LockF__086AFA7E] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__092A148D] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Budge__095F1EB7] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__0A1E38C6] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__0A5342F0] DEFAULT ((0)) FOR [PriorYearActualChargeDollars01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__0B125CFF] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__0B476729] DEFAULT ((0)) FOR [PriorYearActualChargeDollars02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__0C068138] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__0C3B8B62] DEFAULT ((0)) FOR [PriorYearActualChargeDollars03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__0CFAA571] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__0D2FAF9B] DEFAULT ((0)) FOR [PriorYearActualChargeDollars04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__0DEEC9AA] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__0E23D3D4] DEFAULT ((0)) FOR [PriorYearActualChargeDollars05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__0EE2EDE3] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__0F17F80D] DEFAULT ((0)) FOR [PriorYearActualChargeDollars06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__0FD7121C] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__100C1C46] DEFAULT ((0)) FOR [PriorYearActualChargeDollars07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__10CB3655] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__1100407F] DEFAULT ((0)) FOR [PriorYearActualChargeDollars08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__11BF5A8E] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__11F464B8] DEFAULT ((0)) FOR [PriorYearActualChargeDollars09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__12B37EC7] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__12E888F1] DEFAULT ((0)) FOR [PriorYearActualChargeDollars10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__13DCAD2A] DEFAULT ((0)) FOR [PriorYearActualChargeDollars11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__14D0D163] DEFAULT ((0)) FOR [PriorYearActualChargeDollars12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__15C4F59C] DEFAULT ((0)) FOR [ActualYTDChargeDollars01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__16B919D5] DEFAULT ((0)) FOR [ActualYTDChargeDollars02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__17AD3E0E] DEFAULT ((0)) FOR [ActualYTDChargeDollars03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__18A16247] DEFAULT ((0)) FOR [ActualYTDChargeDollars04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__19958680] DEFAULT ((0)) FOR [ActualYTDChargeDollars05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__1A89AAB9] DEFAULT ((0)) FOR [ActualYTDChargeDollars06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__1B7DCEF2] DEFAULT ((0)) FOR [ActualYTDChargeDollars07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__1C71F32B] DEFAULT ((0)) FOR [ActualYTDChargeDollars08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__1D661764] DEFAULT ((0)) FOR [ActualYTDChargeDollars09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__1E5A3B9D] DEFAULT ((0)) FOR [ActualYTDChargeDollars10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__1F4E5FD6] DEFAULT ((0)) FOR [ActualYTDChargeDollars11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__2042840F] DEFAULT ((0)) FOR [ActualYTDChargeDollars12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__2136A848] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__222ACC81] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__231EF0BA] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__241314F3] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__2507392C] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__25FB5D65] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__26EF819E] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__27E3A5D7] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__28D7CA10] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__29CBEE49] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__2AC01282] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__2BB436BB] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__2CA85AF4] DEFAULT ((0)) FOR [PriorYearActualChargeUnits01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__2D9C7F2D] DEFAULT ((0)) FOR [PriorYearActualChargeUnits02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__2E90A366] DEFAULT ((0)) FOR [PriorYearActualChargeUnits03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__2F84C79F] DEFAULT ((0)) FOR [PriorYearActualChargeUnits04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3078EBD8] DEFAULT ((0)) FOR [PriorYearActualChargeUnits05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__316D1011] DEFAULT ((0)) FOR [PriorYearActualChargeUnits06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3261344A] DEFAULT ((0)) FOR [PriorYearActualChargeUnits07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__33555883] DEFAULT ((0)) FOR [PriorYearActualChargeUnits08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__34497CBC] DEFAULT ((0)) FOR [PriorYearActualChargeUnits09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__353DA0F5] DEFAULT ((0)) FOR [PriorYearActualChargeUnits10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3631C52E] DEFAULT ((0)) FOR [PriorYearActualChargeUnits11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3725E967] DEFAULT ((0)) FOR [PriorYearActualChargeUnits12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__381A0DA0] DEFAULT ((0)) FOR [ActualYTDChargeUnits01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__390E31D9] DEFAULT ((0)) FOR [ActualYTDChargeUnits02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3A025612] DEFAULT ((0)) FOR [ActualYTDChargeUnits03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3AF67A4B] DEFAULT ((0)) FOR [ActualYTDChargeUnits04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3BEA9E84] DEFAULT ((0)) FOR [ActualYTDChargeUnits05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3CDEC2BD] DEFAULT ((0)) FOR [ActualYTDChargeUnits06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3DD2E6F6] DEFAULT ((0)) FOR [ActualYTDChargeUnits07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3EC70B2F] DEFAULT ((0)) FOR [ActualYTDChargeUnits08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3FBB2F68] DEFAULT ((0)) FOR [ActualYTDChargeUnits09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__40AF53A1] DEFAULT ((0)) FOR [ActualYTDChargeUnits10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__41A377DA] DEFAULT ((0)) FOR [ActualYTDChargeUnits11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__42979C13] DEFAULT ((0)) FOR [ActualYTDChargeUnits12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__438BC04C] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__447FE485] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__457408BE] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__46682CF7] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__475C5130] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__48507569] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__494499A2] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4A38BDDB] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4B2CE214] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4C21064D] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4D152A86] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4E094EBF] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__4EFD72F8] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__4FF19731] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__50E5BB6A] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__51D9DFA3] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__52CE03DC] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__53C22815] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__54B64C4E] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__55AA7087] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__569E94C0] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5792B8F9] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5886DD32] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__597B016B] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__5A6F25A4] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__5B6349DD] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__5C576E16] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__5D4B924F] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__5E3FB688] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__5F33DAC1] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6027FEFA] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__611C2333] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6210476C] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__63046BA5] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__63F88FDE] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__64ECB417] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__65E0D850] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__66D4FC89] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__67C920C2] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__68BD44FB] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__69B16934] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6AA58D6D] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6B99B1A6] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6C8DD5DF] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6D81FA18] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6E761E51] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6F6A428A] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__705E66C3] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__71528AFC] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__7246AF35] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__733AD36E] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__742EF7A7] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__75231BE0] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__76174019] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__770B6452] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__77FF888B] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__78F3ACC4] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__79E7D0FD] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__7ADBF536] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__7BD0196F] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__7CC43DA8] DEFAULT ((0)) FOR [ActualYTDNetPerDiem01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__7DB861E1] DEFAULT ((0)) FOR [ActualYTDNetPerDiem02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__7EAC861A] DEFAULT ((0)) FOR [ActualYTDNetPerDiem03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__7FA0AA53] DEFAULT ((0)) FOR [ActualYTDNetPerDiem04]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactReimbursementChargesProjection ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactReimbursementChargesProjection] ( + [RowID] int NOT NULL, + [ReimbursementChargesID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedChargeDollars01] decimal NOT NULL, + [AdjustedChargeDollars02] decimal NOT NULL, + [AdjustedChargeDollars03] decimal NOT NULL, + [AdjustedChargeDollars04] decimal NOT NULL, + [AdjustedChargeDollars05] decimal NOT NULL, + [AdjustedChargeDollars06] decimal NOT NULL, + [AdjustedChargeDollars07] decimal NOT NULL, + [AdjustedChargeDollars08] decimal NOT NULL, + [AdjustedChargeDollars09] decimal NOT NULL, + [AdjustedChargeDollars10] decimal NOT NULL, + [AdjustedChargeDollars11] decimal NOT NULL, + [AdjustedChargeDollars12] decimal NOT NULL, + [AdjustedChargeDollarsTotal] decimal NOT NULL, + [AdjustedChargeUnits01] decimal NOT NULL, + [AdjustedChargeUnits02] decimal NOT NULL, + [AdjustedChargeUnits03] decimal NOT NULL, + [AdjustedChargeUnits04] decimal NOT NULL, + [AdjustedChargeUnits05] decimal NOT NULL, + [AdjustedChargeUnits06] decimal NOT NULL, + [AdjustedChargeUnits07] decimal NOT NULL, + [AdjustedChargeUnits08] decimal NOT NULL, + [AdjustedChargeUnits09] decimal NOT NULL, + [AdjustedChargeUnits10] decimal NOT NULL, + [AdjustedChargeUnits11] decimal NOT NULL, + [AdjustedChargeUnits12] decimal NOT NULL, + [AdjustedChargeUnitsTotal] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge01] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge02] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge03] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge04] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge05] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge06] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge07] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge08] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge09] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge10] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge11] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge12] decimal NOT NULL, + [AdjustedNetPerDiem01] decimal NOT NULL, + [AdjustedNetPerDiem02] decimal NOT NULL, + [AdjustedNetPerDiem03] decimal NOT NULL, + [AdjustedNetPerDiem04] decimal NOT NULL, + [AdjustedNetPerDiem05] decimal NOT NULL, + [AdjustedNetPerDiem06] decimal NOT NULL, + [AdjustedNetPerDiem07] decimal NOT NULL, + [AdjustedNetPerDiem08] decimal NOT NULL, + [AdjustedNetPerDiem09] decimal NOT NULL, + [AdjustedNetPerDiem10] decimal NOT NULL, + [AdjustedNetPerDiem11] decimal NOT NULL, + [AdjustedNetPerDiem12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [FK_ArchiveFactReimbursementChargesProjection_ReimbursementChargesID] FOREIGN KEY ([ReimbursementChargesID]) REFERENCES [fp].[FactReimbursementCharges] ([ReimbursementChargesID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Reimb__0D99C3EF] DEFAULT ((0)) FOR [ReimbursementChargesID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__LockT__0E8DE828] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__LockF__0F820C61] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Budge__1076309A] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__116A54D3] DEFAULT ((0)) FOR [AdjustedChargeDollars01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__125E790C] DEFAULT ((0)) FOR [AdjustedChargeDollars02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__13529D45] DEFAULT ((0)) FOR [AdjustedChargeDollars03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1446C17E] DEFAULT ((0)) FOR [AdjustedChargeDollars04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__153AE5B7] DEFAULT ((0)) FOR [AdjustedChargeDollars05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__162F09F0] DEFAULT ((0)) FOR [AdjustedChargeDollars06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__17232E29] DEFAULT ((0)) FOR [AdjustedChargeDollars07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__18175262] DEFAULT ((0)) FOR [AdjustedChargeDollars08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__190B769B] DEFAULT ((0)) FOR [AdjustedChargeDollars09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__19FF9AD4] DEFAULT ((0)) FOR [AdjustedChargeDollars10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1AF3BF0D] DEFAULT ((0)) FOR [AdjustedChargeDollars11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1BE7E346] DEFAULT ((0)) FOR [AdjustedChargeDollars12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1CDC077F] DEFAULT ((0)) FOR [AdjustedChargeUnits01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1DD02BB8] DEFAULT ((0)) FOR [AdjustedChargeUnits02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1EC44FF1] DEFAULT ((0)) FOR [AdjustedChargeUnits03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1FB8742A] DEFAULT ((0)) FOR [AdjustedChargeUnits04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__20AC9863] DEFAULT ((0)) FOR [AdjustedChargeUnits05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__21A0BC9C] DEFAULT ((0)) FOR [AdjustedChargeUnits06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2294E0D5] DEFAULT ((0)) FOR [AdjustedChargeUnits07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2389050E] DEFAULT ((0)) FOR [AdjustedChargeUnits08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__247D2947] DEFAULT ((0)) FOR [AdjustedChargeUnits09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__25714D80] DEFAULT ((0)) FOR [AdjustedChargeUnits10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__266571B9] DEFAULT ((0)) FOR [AdjustedChargeUnits11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__275995F2] DEFAULT ((0)) FOR [AdjustedChargeUnits12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__284DBA2B] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2941DE64] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2A36029D] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2B2A26D6] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2C1E4B0F] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2D126F48] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2E069381] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2EFAB7BA] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2FEEDBF3] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__30E3002C] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__31D72465] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__32CB489E] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__33BF6CD7] DEFAULT ((0)) FOR [AdjustedNetPerDiem01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__34B39110] DEFAULT ((0)) FOR [AdjustedNetPerDiem02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__35A7B549] DEFAULT ((0)) FOR [AdjustedNetPerDiem03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__369BD982] DEFAULT ((0)) FOR [AdjustedNetPerDiem04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__378FFDBB] DEFAULT ((0)) FOR [AdjustedNetPerDiem05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__388421F4] DEFAULT ((0)) FOR [AdjustedNetPerDiem06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3978462D] DEFAULT ((0)) FOR [AdjustedNetPerDiem07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3A6C6A66] DEFAULT ((0)) FOR [AdjustedNetPerDiem08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3B608E9F] DEFAULT ((0)) FOR [AdjustedNetPerDiem09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3C54B2D8] DEFAULT ((0)) FOR [AdjustedNetPerDiem10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3D48D711] DEFAULT ((0)) FOR [AdjustedNetPerDiem11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementChargesProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3E3CFB4A] DEFAULT ((0)) FOR [AdjustedNetPerDiem12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactReimbursementEncounter ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactReimbursementEncounter] ( + [ReimbursementEncounterID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [DepartmentID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [MSDRGID] int NOT NULL, + [CPTID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [AddDate] datetime NOT NULL, + [InitialBudget01] decimal NOT NULL, + [InitialBudget02] decimal NOT NULL, + [InitialBudget03] decimal NOT NULL, + [InitialBudget04] decimal NOT NULL, + [InitialBudget05] decimal NOT NULL, + [InitialBudget06] decimal NOT NULL, + [InitialBudget07] decimal NOT NULL, + [InitialBudget08] decimal NOT NULL, + [InitialBudget09] decimal NOT NULL, + [InitialBudget10] decimal NOT NULL, + [InitialBudget11] decimal NOT NULL, + [InitialBudget12] decimal NOT NULL, + [InitialBudgetNetPerEncounter01] decimal NOT NULL, + [InitialBudgetNetPerEncounter02] decimal NOT NULL, + [InitialBudgetNetPerEncounter03] decimal NOT NULL, + [InitialBudgetNetPerEncounter04] decimal NOT NULL, + [InitialBudgetNetPerEncounter05] decimal NOT NULL, + [InitialBudgetNetPerEncounter06] decimal NOT NULL, + [InitialBudgetNetPerEncounter07] decimal NOT NULL, + [InitialBudgetNetPerEncounter08] decimal NOT NULL, + [InitialBudgetNetPerEncounter09] decimal NOT NULL, + [InitialBudgetNetPerEncounter10] decimal NOT NULL, + [InitialBudgetNetPerEncounter11] decimal NOT NULL, + [InitialBudgetNetPerEncounter12] decimal NOT NULL, + [InitialBudgetNetReimbursement01] decimal NULL, + [InitialBudgetNetReimbursement02] decimal NULL, + [InitialBudgetNetReimbursement03] decimal NULL, + [InitialBudgetNetReimbursement04] decimal NULL, + [InitialBudgetNetReimbursement05] decimal NULL, + [InitialBudgetNetReimbursement06] decimal NULL, + [InitialBudgetNetReimbursement07] decimal NULL, + [InitialBudgetNetReimbursement08] decimal NULL, + [InitialBudgetNetReimbursement09] decimal NULL, + [InitialBudgetNetReimbursement10] decimal NULL, + [InitialBudgetNetReimbursement11] decimal NULL, + [InitialBudgetNetReimbursement12] decimal NULL, + [InitialProjection01] decimal NOT NULL, + [InitialProjection02] decimal NOT NULL, + [InitialProjection03] decimal NOT NULL, + [InitialProjection04] decimal NOT NULL, + [InitialProjection05] decimal NOT NULL, + [InitialProjection06] decimal NOT NULL, + [InitialProjection07] decimal NOT NULL, + [InitialProjection08] decimal NOT NULL, + [InitialProjection09] decimal NOT NULL, + [InitialProjection10] decimal NOT NULL, + [InitialProjection11] decimal NOT NULL, + [InitialProjection12] decimal NOT NULL, + [InitialProjectionNetPerEncounter01] decimal NOT NULL, + [InitialProjectionNetPerEncounter02] decimal NOT NULL, + [InitialProjectionNetPerEncounter03] decimal NOT NULL, + [InitialProjectionNetPerEncounter04] decimal NOT NULL, + [InitialProjectionNetPerEncounter05] decimal NOT NULL, + [InitialProjectionNetPerEncounter06] decimal NOT NULL, + [InitialProjectionNetPerEncounter07] decimal NOT NULL, + [InitialProjectionNetPerEncounter08] decimal NOT NULL, + [InitialProjectionNetPerEncounter09] decimal NOT NULL, + [InitialProjectionNetPerEncounter10] decimal NOT NULL, + [InitialProjectionNetPerEncounter11] decimal NOT NULL, + [InitialProjectionNetPerEncounter12] decimal NOT NULL, + [InitialProjectionNetReimbursement01] decimal NULL, + [InitialProjectionNetReimbursement02] decimal NULL, + [InitialProjectionNetReimbursement03] decimal NULL, + [InitialProjectionNetReimbursement04] decimal NULL, + [InitialProjectionNetReimbursement05] decimal NULL, + [InitialProjectionNetReimbursement06] decimal NULL, + [InitialProjectionNetReimbursement07] decimal NULL, + [InitialProjectionNetReimbursement08] decimal NULL, + [InitialProjectionNetReimbursement09] decimal NULL, + [InitialProjectionNetReimbursement10] decimal NULL, + [InitialProjectionNetReimbursement11] decimal NULL, + [InitialProjectionNetReimbursement12] decimal NULL, + [InitialBudgetTotal] decimal NOT NULL, + [InitialProjectionTotal] decimal NOT NULL, + [IsNew] bit NOT NULL, + PRIMARY KEY ([ReimbursementEncounterID]) +); +GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounter_CPT] FOREIGN KEY ([CPTID]) REFERENCES [dss].[DimCPT] ([CPTID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounter_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounter_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounter_MedicalSurgical] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounter_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounter_Payor] FOREIGN KEY ([PayorID]) REFERENCES [fw].[DimPayor] ([PayorID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounter_PayorGroup] FOREIGN KEY ([PayorGroupID]) REFERENCES [fw].[DimPayorGroup] ([PayorGroupID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounter_ServiceLine] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounter_ServiceLineRollup] FOREIGN KEY ([ServiceLineRollupID]) REFERENCES [fw].[DimServiceLineRollup] ([ServiceLineRollupID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounter_UnitType] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0054D76A] DEFAULT ((0)) FOR [InitialBudget11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0148FBA3] DEFAULT ((0)) FOR [InitialBudget12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__023D1FDC] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__03314415] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0425684E] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__05198C87] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__060DB0C0] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0701D4F9] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__07F5F932] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__08EA1D6B] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__09DE41A4] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0AD265DD] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0BC68A16] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0CBAAE4F] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0DAED288] DEFAULT ((0)) FOR [InitialProjection01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0EA2F6C1] DEFAULT ((0)) FOR [InitialProjection02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0F971AFA] DEFAULT ((0)) FOR [InitialProjection03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__108B3F33] DEFAULT ((0)) FOR [InitialProjection04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__117F636C] DEFAULT ((0)) FOR [InitialProjection05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__127387A5] DEFAULT ((0)) FOR [InitialProjection06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1367ABDE] DEFAULT ((0)) FOR [InitialProjection07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__145BD017] DEFAULT ((0)) FOR [InitialProjection08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__154FF450] DEFAULT ((0)) FOR [InitialProjection09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__16441889] DEFAULT ((0)) FOR [InitialProjection10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__17383CC2] DEFAULT ((0)) FOR [InitialProjection11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__182C60FB] DEFAULT ((0)) FOR [InitialProjection12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__19208534] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1A14A96D] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1B08CDA6] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1BFCF1DF] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1CF11618] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1DE53A51] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1ED95E8A] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1FCD82C3] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__20C1A6FC] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__21B5CB35] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__22A9EF6E] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__239E13A7] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__IsNew__249237E0] DEFAULT ((0)) FOR [IsNew]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Budge__69717212] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Entit__6A65964B] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Entit__6B59BA84] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Patie__6C4DDEBD] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Servi__6D4202F6] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Servi__6E36272F] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Medic__6F2A4B68] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Depar__701E6FA1] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Payor__711293DA] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Payor__7206B813] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__MSDRG__72FADC4C] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__CPTID__73EF0085] DEFAULT ((0)) FOR [CPTID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__UnitT__74E324BE] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF_ArchiveFactReimbursementEncounter_AddDate] DEFAULT ('1900-01-01') FOR [AddDate]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__76CB6D30] DEFAULT ((0)) FOR [InitialBudget01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__77BF9169] DEFAULT ((0)) FOR [InitialBudget02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__78B3B5A2] DEFAULT ((0)) FOR [InitialBudget03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__79A7D9DB] DEFAULT ((0)) FOR [InitialBudget04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__7A9BFE14] DEFAULT ((0)) FOR [InitialBudget05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__7B90224D] DEFAULT ((0)) FOR [InitialBudget06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__7C844686] DEFAULT ((0)) FOR [InitialBudget07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__7D786ABF] DEFAULT ((0)) FOR [InitialBudget08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__7E6C8EF8] DEFAULT ((0)) FOR [InitialBudget09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__7F60B331] DEFAULT ((0)) FOR [InitialBudget10]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactReimbursementEncounterBudget ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ( + [RowID] int NOT NULL, + [ReimbursementEncounterID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedValue01] decimal NOT NULL, + [AdjustedValue02] decimal NOT NULL, + [AdjustedValue03] decimal NOT NULL, + [AdjustedValue04] decimal NOT NULL, + [AdjustedValue05] decimal NOT NULL, + [AdjustedValue06] decimal NOT NULL, + [AdjustedValue07] decimal NOT NULL, + [AdjustedValue08] decimal NOT NULL, + [AdjustedValue09] decimal NOT NULL, + [AdjustedValue10] decimal NOT NULL, + [AdjustedValue11] decimal NOT NULL, + [AdjustedValue12] decimal NOT NULL, + [AdjustedValueTotal] decimal NOT NULL, + [AdjustedNetPerEncounterValue01] decimal NOT NULL, + [AdjustedNetPerEncounterValue02] decimal NOT NULL, + [AdjustedNetPerEncounterValue03] decimal NOT NULL, + [AdjustedNetPerEncounterValue04] decimal NOT NULL, + [AdjustedNetPerEncounterValue05] decimal NOT NULL, + [AdjustedNetPerEncounterValue06] decimal NOT NULL, + [AdjustedNetPerEncounterValue07] decimal NOT NULL, + [AdjustedNetPerEncounterValue08] decimal NOT NULL, + [AdjustedNetPerEncounterValue09] decimal NOT NULL, + [AdjustedNetPerEncounterValue10] decimal NOT NULL, + [AdjustedNetPerEncounterValue11] decimal NOT NULL, + [AdjustedNetPerEncounterValue12] decimal NOT NULL, + [AdjustedNetReimbursementValue01] decimal NULL, + [AdjustedNetReimbursementValue02] decimal NULL, + [AdjustedNetReimbursementValue03] decimal NULL, + [AdjustedNetReimbursementValue04] decimal NULL, + [AdjustedNetReimbursementValue05] decimal NULL, + [AdjustedNetReimbursementValue06] decimal NULL, + [AdjustedNetReimbursementValue07] decimal NULL, + [AdjustedNetReimbursementValue08] decimal NULL, + [AdjustedNetReimbursementValue09] decimal NULL, + [AdjustedNetReimbursementValue10] decimal NULL, + [AdjustedNetReimbursementValue11] decimal NULL, + [AdjustedNetReimbursementValue12] decimal NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounterBudget_ReimbursementEncounterID] FOREIGN KEY ([ReimbursementEncounterID]) REFERENCES [fp].[ArchiveFactReimbursementEncounter] ([ReimbursementEncounterID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Reimb__4E8871AC] DEFAULT ((0)) FOR [ReimbursementEncounterID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__LockT__4F7C95E5] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__LockF__5070BA1E] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Budge__5164DE57] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__52590290] DEFAULT ((0)) FOR [AdjustedValue01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__534D26C9] DEFAULT ((0)) FOR [AdjustedValue02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__54414B02] DEFAULT ((0)) FOR [AdjustedValue03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__55356F3B] DEFAULT ((0)) FOR [AdjustedValue04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__56299374] DEFAULT ((0)) FOR [AdjustedValue05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__571DB7AD] DEFAULT ((0)) FOR [AdjustedValue06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5811DBE6] DEFAULT ((0)) FOR [AdjustedValue07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5906001F] DEFAULT ((0)) FOR [AdjustedValue08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__59FA2458] DEFAULT ((0)) FOR [AdjustedValue09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5AEE4891] DEFAULT ((0)) FOR [AdjustedValue10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5BE26CCA] DEFAULT ((0)) FOR [AdjustedValue11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5CD69103] DEFAULT ((0)) FOR [AdjustedValue12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5DCAB53C] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5EBED975] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5FB2FDAE] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__60A721E7] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__619B4620] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__628F6A59] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__63838E92] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6477B2CB] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__656BD704] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__665FFB3D] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__67541F76] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__684843AF] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactReimbursementEncounterHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ( + [RowID] int NOT NULL, + [ReimbursementEncounterID] int NOT NULL, + [PriorYearActualValue01] decimal NOT NULL, + [PriorYearActualValue02] decimal NOT NULL, + [PriorYearActualValue03] decimal NOT NULL, + [PriorYearActualValue04] decimal NOT NULL, + [PriorYearActualValue05] decimal NOT NULL, + [PriorYearActualValue06] decimal NOT NULL, + [PriorYearActualValue07] decimal NOT NULL, + [PriorYearActualValue08] decimal NOT NULL, + [PriorYearActualValue09] decimal NOT NULL, + [PriorYearActualValue10] decimal NOT NULL, + [PriorYearActualValue11] decimal NOT NULL, + [PriorYearActualValue12] decimal NOT NULL, + [PriorYearActualValueTotal] decimal NULL, + [ActualYTDValue01] decimal NOT NULL, + [ActualYTDValue02] decimal NOT NULL, + [ActualYTDValue03] decimal NOT NULL, + [ActualYTDValue04] decimal NOT NULL, + [ActualYTDValue05] decimal NOT NULL, + [ActualYTDValue06] decimal NOT NULL, + [ActualYTDValue07] decimal NOT NULL, + [ActualYTDValue08] decimal NOT NULL, + [ActualYTDValue09] decimal NOT NULL, + [ActualYTDValue10] decimal NOT NULL, + [ActualYTDValue11] decimal NOT NULL, + [ActualYTDValue12] decimal NOT NULL, + [ActualYTDValueTotal] decimal NULL, + [CurrentYearBudget01] decimal NOT NULL, + [CurrentYearBudget02] decimal NOT NULL, + [CurrentYearBudget03] decimal NOT NULL, + [CurrentYearBudget04] decimal NOT NULL, + [CurrentYearBudget05] decimal NOT NULL, + [CurrentYearBudget06] decimal NOT NULL, + [CurrentYearBudget07] decimal NOT NULL, + [CurrentYearBudget08] decimal NOT NULL, + [CurrentYearBudget09] decimal NOT NULL, + [CurrentYearBudget10] decimal NOT NULL, + [CurrentYearBudget11] decimal NOT NULL, + [CurrentYearBudget12] decimal NOT NULL, + [CurrentYearBudgetTotal] decimal NULL, + [PriorYearActualNetPerEncounterValue01] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue02] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue03] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue04] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue05] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue06] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue07] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue08] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue09] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue10] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue11] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue12] decimal NOT NULL, + [ActualYTDNetPerEncounterValue01] decimal NOT NULL, + [ActualYTDNetPerEncounterValue02] decimal NOT NULL, + [ActualYTDNetPerEncounterValue03] decimal NOT NULL, + [ActualYTDNetPerEncounterValue04] decimal NOT NULL, + [ActualYTDNetPerEncounterValue05] decimal NOT NULL, + [ActualYTDNetPerEncounterValue06] decimal NOT NULL, + [ActualYTDNetPerEncounterValue07] decimal NOT NULL, + [ActualYTDNetPerEncounterValue08] decimal NOT NULL, + [ActualYTDNetPerEncounterValue09] decimal NOT NULL, + [ActualYTDNetPerEncounterValue10] decimal NOT NULL, + [ActualYTDNetPerEncounterValue11] decimal NOT NULL, + [ActualYTDNetPerEncounterValue12] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget01] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget02] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget03] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget04] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget05] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget06] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget07] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget08] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget09] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget10] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget11] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget12] decimal NOT NULL, + [PriorYearActualNetReimbursementValue01] decimal NULL, + [PriorYearActualNetReimbursementValue02] decimal NULL, + [PriorYearActualNetReimbursementValue03] decimal NULL, + [PriorYearActualNetReimbursementValue04] decimal NULL, + [PriorYearActualNetReimbursementValue05] decimal NULL, + [PriorYearActualNetReimbursementValue06] decimal NULL, + [PriorYearActualNetReimbursementValue07] decimal NULL, + [PriorYearActualNetReimbursementValue08] decimal NULL, + [PriorYearActualNetReimbursementValue09] decimal NULL, + [PriorYearActualNetReimbursementValue10] decimal NULL, + [PriorYearActualNetReimbursementValue11] decimal NULL, + [PriorYearActualNetReimbursementValue12] decimal NULL, + [ActualYTDNetReimbursementValue01] decimal NULL, + [ActualYTDNetReimbursementValue02] decimal NULL, + [ActualYTDNetReimbursementValue03] decimal NULL, + [ActualYTDNetReimbursementValue04] decimal NULL, + [ActualYTDNetReimbursementValue05] decimal NULL, + [ActualYTDNetReimbursementValue06] decimal NULL, + [ActualYTDNetReimbursementValue07] decimal NULL, + [ActualYTDNetReimbursementValue08] decimal NULL, + [ActualYTDNetReimbursementValue09] decimal NULL, + [ActualYTDNetReimbursementValue10] decimal NULL, + [ActualYTDNetReimbursementValue11] decimal NULL, + [ActualYTDNetReimbursementValue12] decimal NULL, + [CurrentYearNetReimbursementBudget01] decimal NULL, + [CurrentYearNetReimbursementBudget02] decimal NULL, + [CurrentYearNetReimbursementBudget03] decimal NULL, + [CurrentYearNetReimbursementBudget04] decimal NULL, + [CurrentYearNetReimbursementBudget05] decimal NULL, + [CurrentYearNetReimbursementBudget06] decimal NULL, + [CurrentYearNetReimbursementBudget07] decimal NULL, + [CurrentYearNetReimbursementBudget08] decimal NULL, + [CurrentYearNetReimbursementBudget09] decimal NULL, + [CurrentYearNetReimbursementBudget10] decimal NULL, + [CurrentYearNetReimbursementBudget11] decimal NULL, + [CurrentYearNetReimbursementBudget12] decimal NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounterHistory_ReimbursementEncounterID] FOREIGN KEY ([ReimbursementEncounterID]) REFERENCES [fp].[ArchiveFactReimbursementEncounter] ([ReimbursementEncounterID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__0074D2FB] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__0168F734] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__025D1B6D] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__03513FA6] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__044563DF] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__05398818] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__062DAC51] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__0721D08A] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__0815F4C3] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__090A18FC] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__09FE3D35] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0AF2616E] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0BE685A7] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0CDAA9E0] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0DCECE19] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0EC2F252] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__0FB7168B] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__10AB3AC4] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__119F5EFD] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__12938336] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__1387A76F] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__147BCBA8] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__156FEFE1] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1664141A] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__17583853] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__184C5C8C] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__194080C5] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1A34A4FE] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1B28C937] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1C1CED70] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1D1111A9] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1E0535E2] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1EF95A1B] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__1FED7E54] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__20E1A28D] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Reimb__5C377285] DEFAULT ((0)) FOR [ReimbursementEncounterID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5D2B96BE] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5E1FBAF7] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5F13DF30] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__60080369] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__60FC27A2] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__61F04BDB] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__62E47014] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__63D8944D] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__64CCB886] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__65C0DCBF] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__66B500F8] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__67A92531] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__689D496A] DEFAULT ((0)) FOR [ActualYTDValue01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__69916DA3] DEFAULT ((0)) FOR [ActualYTDValue02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6A8591DC] DEFAULT ((0)) FOR [ActualYTDValue03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6B79B615] DEFAULT ((0)) FOR [ActualYTDValue04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6C6DDA4E] DEFAULT ((0)) FOR [ActualYTDValue05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6D61FE87] DEFAULT ((0)) FOR [ActualYTDValue06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6E5622C0] DEFAULT ((0)) FOR [ActualYTDValue07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6F4A46F9] DEFAULT ((0)) FOR [ActualYTDValue08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__703E6B32] DEFAULT ((0)) FOR [ActualYTDValue09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__71328F6B] DEFAULT ((0)) FOR [ActualYTDValue10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__7226B3A4] DEFAULT ((0)) FOR [ActualYTDValue11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__731AD7DD] DEFAULT ((0)) FOR [ActualYTDValue12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__740EFC16] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7503204F] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__75F74488] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__76EB68C1] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__77DF8CFA] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__78D3B133] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__79C7D56C] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7ABBF9A5] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7BB01DDE] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7CA44217] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7D986650] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7E8C8A89] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__7F80AEC2] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue01]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactReimbursementEncounterProjection ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ( + [RowID] int NOT NULL, + [ReimbursementEncounterID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedValue01] decimal NOT NULL, + [AdjustedValue02] decimal NOT NULL, + [AdjustedValue03] decimal NOT NULL, + [AdjustedValue04] decimal NOT NULL, + [AdjustedValue05] decimal NOT NULL, + [AdjustedValue06] decimal NOT NULL, + [AdjustedValue07] decimal NOT NULL, + [AdjustedValue08] decimal NOT NULL, + [AdjustedValue09] decimal NOT NULL, + [AdjustedValue10] decimal NOT NULL, + [AdjustedValue11] decimal NOT NULL, + [AdjustedValue12] decimal NOT NULL, + [AdjustedValueTotal] decimal NOT NULL, + [AdjustedNetPerEncounterValue01] decimal NOT NULL, + [AdjustedNetPerEncounterValue02] decimal NOT NULL, + [AdjustedNetPerEncounterValue03] decimal NOT NULL, + [AdjustedNetPerEncounterValue04] decimal NOT NULL, + [AdjustedNetPerEncounterValue05] decimal NOT NULL, + [AdjustedNetPerEncounterValue06] decimal NOT NULL, + [AdjustedNetPerEncounterValue07] decimal NOT NULL, + [AdjustedNetPerEncounterValue08] decimal NOT NULL, + [AdjustedNetPerEncounterValue09] decimal NOT NULL, + [AdjustedNetPerEncounterValue10] decimal NOT NULL, + [AdjustedNetPerEncounterValue11] decimal NOT NULL, + [AdjustedNetPerEncounterValue12] decimal NOT NULL, + [AdjustedNetReimbursementValue01] decimal NULL, + [AdjustedNetReimbursementValue02] decimal NULL, + [AdjustedNetReimbursementValue03] decimal NULL, + [AdjustedNetReimbursementValue04] decimal NULL, + [AdjustedNetReimbursementValue05] decimal NULL, + [AdjustedNetReimbursementValue06] decimal NULL, + [AdjustedNetReimbursementValue07] decimal NULL, + [AdjustedNetReimbursementValue08] decimal NULL, + [AdjustedNetReimbursementValue09] decimal NULL, + [AdjustedNetReimbursementValue10] decimal NULL, + [AdjustedNetReimbursementValue11] decimal NULL, + [AdjustedNetReimbursementValue12] decimal NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [FK_ArchiveFactReimbursementEncounterProjection_ReimbursementEncounterID] FOREIGN KEY ([ReimbursementEncounterID]) REFERENCES [fp].[ArchiveFactReimbursementEncounter] ([ReimbursementEncounterID]); GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__LockT__00DEE74F] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__LockF__01D30B88] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Budge__02C72FC1] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__03BB53FA] DEFAULT ((0)) FOR [AdjustedValue01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__04AF7833] DEFAULT ((0)) FOR [AdjustedValue02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__05A39C6C] DEFAULT ((0)) FOR [AdjustedValue03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0697C0A5] DEFAULT ((0)) FOR [AdjustedValue04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__078BE4DE] DEFAULT ((0)) FOR [AdjustedValue05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__08800917] DEFAULT ((0)) FOR [AdjustedValue06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__09742D50] DEFAULT ((0)) FOR [AdjustedValue07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0A685189] DEFAULT ((0)) FOR [AdjustedValue08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0B5C75C2] DEFAULT ((0)) FOR [AdjustedValue09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0C5099FB] DEFAULT ((0)) FOR [AdjustedValue10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0D44BE34] DEFAULT ((0)) FOR [AdjustedValue11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0E38E26D] DEFAULT ((0)) FOR [AdjustedValue12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0F2D06A6] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue01]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__10212ADF] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue02]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__11154F18] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue03]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__12097351] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue04]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__12FD978A] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue05]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__13F1BBC3] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue06]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__14E5DFFC] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue07]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__15DA0435] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue08]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__16CE286E] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue09]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__17C24CA7] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue10]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__18B670E0] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue11]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__19AA9519] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue12]; GO +ALTER TABLE [fp].[ArchiveFactReimbursementEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Reimb__7FEAC316] DEFAULT ((0)) FOR [ReimbursementEncounterID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactServiceLineEncounter ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactServiceLineEncounter] ( + [ServiceLineEncounterID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [DepartmentID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [MSDRGID] int NOT NULL, + [CPTID] int NOT NULL, + [ProviderID] int NOT NULL, + [PhysicianSpecialtyID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [AddDate] datetime NOT NULL, + [SampledBudget01] decimal NOT NULL, + [SampledBudget02] decimal NOT NULL, + [SampledBudget03] decimal NOT NULL, + [SampledBudget04] decimal NOT NULL, + [SampledBudget05] decimal NOT NULL, + [SampledBudget06] decimal NOT NULL, + [SampledBudget07] decimal NOT NULL, + [SampledBudget08] decimal NOT NULL, + [SampledBudget09] decimal NOT NULL, + [SampledBudget10] decimal NOT NULL, + [SampledBudget11] decimal NOT NULL, + [SampledBudget12] decimal NOT NULL, + [SampledProjection01] decimal NOT NULL, + [SampledProjection02] decimal NOT NULL, + [SampledProjection03] decimal NOT NULL, + [SampledProjection04] decimal NOT NULL, + [SampledProjection05] decimal NOT NULL, + [SampledProjection06] decimal NOT NULL, + [SampledProjection07] decimal NOT NULL, + [SampledProjection08] decimal NOT NULL, + [SampledProjection09] decimal NOT NULL, + [SampledProjection10] decimal NOT NULL, + [SampledProjection11] decimal NOT NULL, + [SampledProjection12] decimal NOT NULL, + [InitialBudget01] decimal NOT NULL, + [InitialBudget02] decimal NOT NULL, + [InitialBudget03] decimal NOT NULL, + [InitialBudget04] decimal NOT NULL, + [InitialBudget05] decimal NOT NULL, + [InitialBudget06] decimal NOT NULL, + [InitialBudget07] decimal NOT NULL, + [InitialBudget08] decimal NOT NULL, + [InitialBudget09] decimal NOT NULL, + [InitialBudget10] decimal NOT NULL, + [InitialBudget11] decimal NOT NULL, + [InitialBudget12] decimal NOT NULL, + [InitialProjection01] decimal NOT NULL, + [InitialProjection02] decimal NOT NULL, + [InitialProjection03] decimal NOT NULL, + [InitialProjection04] decimal NOT NULL, + [InitialProjection05] decimal NOT NULL, + [InitialProjection06] decimal NOT NULL, + [InitialProjection07] decimal NOT NULL, + [InitialProjection08] decimal NOT NULL, + [InitialProjection09] decimal NOT NULL, + [InitialProjection10] decimal NOT NULL, + [InitialProjection11] decimal NOT NULL, + [InitialProjection12] decimal NOT NULL, + [SampledBudgetTotal] decimal NOT NULL, + [SampledProjectionTotal] decimal NOT NULL, + [InitialBudgetTotal] decimal NOT NULL, + [InitialProjectionTotal] decimal NOT NULL, + [IsNew] bit NOT NULL, + PRIMARY KEY ([ServiceLineEncounterID]) +); + +CREATE NONCLUSTERED INDEX [IX_ArchiveFactServiceLineEncounter_BudgetConfig] ON [fp].[ArchiveFactServiceLineEncounter] ([BudgetConfigID]) INCLUDE ([ServiceLineEncounterID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactServiceLineEncounter_Department] ON [fp].[ArchiveFactServiceLineEncounter] ([DepartmentID]) INCLUDE ([ServiceLineEncounterID], [BudgetConfigID], [EntityGroupConfigID], [PatientClassID], [EntityID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactServiceLineEncounter_Entity] ON [fp].[ArchiveFactServiceLineEncounter] ([EntityID]) INCLUDE ([ServiceLineEncounterID], [BudgetConfigID], [EntityGroupConfigID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactServiceLineEncounter_EntityGroupConfig] ON [fp].[ArchiveFactServiceLineEncounter] ([EntityGroupConfigID]) INCLUDE ([ServiceLineEncounterID], [BudgetConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactServiceLineEncounter_ServiceLine] ON [fp].[ArchiveFactServiceLineEncounter] ([ServiceLineID]) INCLUDE ([ServiceLineEncounterID], [BudgetConfigID], [EntityGroupConfigID], [PatientClassID], [EntityID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[ArchiveFactServiceLineEncounter] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]); +GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_AgeCohort] FOREIGN KEY ([AgeCohortID]) REFERENCES [fw].[DimAgeCohort] ([AgeCohortID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_CPT] FOREIGN KEY ([CPTID]) REFERENCES [dss].[DimCPT] ([CPTID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_MedicalSurgical] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_MSDRG] FOREIGN KEY ([MSDRGID]) REFERENCES [dss].[DimMSDRG] ([MSDRGID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_Payor] FOREIGN KEY ([PayorID]) REFERENCES [fw].[DimPayor] ([PayorID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_PayorGroup] FOREIGN KEY ([PayorGroupID]) REFERENCES [fw].[DimPayorGroup] ([PayorGroupID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_PhysicianSpecialty] FOREIGN KEY ([PhysicianSpecialtyID]) REFERENCES [fw].[DimPhysicianSpecialty] ([PhysicianSpecialtyID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_Provider] FOREIGN KEY ([ProviderID]) REFERENCES [fw].[DimProvider] ([ProviderID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_ServiceLine] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_ServiceLineRollup] FOREIGN KEY ([ServiceLineRollupID]) REFERENCES [fw].[DimServiceLineRollup] ([ServiceLineRollupID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounter_UnitType] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__006783FE] DEFAULT ((0)) FOR [SampledBudget12]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__015BA837] DEFAULT ((0)) FOR [SampledProjection01]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__024FCC70] DEFAULT ((0)) FOR [SampledProjection02]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__0343F0A9] DEFAULT ((0)) FOR [SampledProjection03]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__043814E2] DEFAULT ((0)) FOR [SampledProjection04]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__052C391B] DEFAULT ((0)) FOR [SampledProjection05]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__06205D54] DEFAULT ((0)) FOR [SampledProjection06]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__0714818D] DEFAULT ((0)) FOR [SampledProjection07]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__0808A5C6] DEFAULT ((0)) FOR [SampledProjection08]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__08FCC9FF] DEFAULT ((0)) FOR [SampledProjection09]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__09F0EE38] DEFAULT ((0)) FOR [SampledProjection10]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__0AE51271] DEFAULT ((0)) FOR [SampledProjection11]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__0BD936AA] DEFAULT ((0)) FOR [SampledProjection12]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0CCD5AE3] DEFAULT ((0)) FOR [InitialBudget01]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0DC17F1C] DEFAULT ((0)) FOR [InitialBudget02]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0EB5A355] DEFAULT ((0)) FOR [InitialBudget03]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__0FA9C78E] DEFAULT ((0)) FOR [InitialBudget04]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__109DEBC7] DEFAULT ((0)) FOR [InitialBudget05]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__11921000] DEFAULT ((0)) FOR [InitialBudget06]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__12863439] DEFAULT ((0)) FOR [InitialBudget07]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__137A5872] DEFAULT ((0)) FOR [InitialBudget08]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__146E7CAB] DEFAULT ((0)) FOR [InitialBudget09]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1562A0E4] DEFAULT ((0)) FOR [InitialBudget10]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1656C51D] DEFAULT ((0)) FOR [InitialBudget11]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__174AE956] DEFAULT ((0)) FOR [InitialBudget12]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__183F0D8F] DEFAULT ((0)) FOR [InitialProjection01]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__193331C8] DEFAULT ((0)) FOR [InitialProjection02]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1A275601] DEFAULT ((0)) FOR [InitialProjection03]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1B1B7A3A] DEFAULT ((0)) FOR [InitialProjection04]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1C0F9E73] DEFAULT ((0)) FOR [InitialProjection05]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1D03C2AC] DEFAULT ((0)) FOR [InitialProjection06]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1DF7E6E5] DEFAULT ((0)) FOR [InitialProjection07]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1EEC0B1E] DEFAULT ((0)) FOR [InitialProjection08]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__1FE02F57] DEFAULT ((0)) FOR [InitialProjection09]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__20D45390] DEFAULT ((0)) FOR [InitialProjection10]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__21C877C9] DEFAULT ((0)) FOR [InitialProjection11]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Initi__22BC9C02] DEFAULT ((0)) FOR [InitialProjection12]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__IsNew__23B0C03B] DEFAULT ((0)) FOR [IsNew]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Budge__65B38DC2] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Entit__66A7B1FB] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Entit__679BD634] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Patie__688FFA6D] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Servi__69841EA6] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Servi__6A7842DF] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__AgeCo__6B6C6718] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Medic__6C608B51] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Depar__6D54AF8A] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Payor__6E48D3C3] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Payor__6F3CF7FC] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__MSDRG__70311C35] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__CPTID__7125406E] DEFAULT ((0)) FOR [CPTID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Provi__721964A7] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Physi__730D88E0] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__UnitT__7401AD19] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF_ArchiveServiceLineEncounter_AddDate] DEFAULT ('1900-01-01') FOR [AddDate]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__75E9F58B] DEFAULT ((0)) FOR [SampledBudget01]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__76DE19C4] DEFAULT ((0)) FOR [SampledBudget02]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__77D23DFD] DEFAULT ((0)) FOR [SampledBudget03]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__78C66236] DEFAULT ((0)) FOR [SampledBudget04]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__79BA866F] DEFAULT ((0)) FOR [SampledBudget05]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__7AAEAAA8] DEFAULT ((0)) FOR [SampledBudget06]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__7BA2CEE1] DEFAULT ((0)) FOR [SampledBudget07]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__7C96F31A] DEFAULT ((0)) FOR [SampledBudget08]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__7D8B1753] DEFAULT ((0)) FOR [SampledBudget09]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__7E7F3B8C] DEFAULT ((0)) FOR [SampledBudget10]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounter] ADD CONSTRAINT [DF__ArchiveFa__Sampl__7F735FC5] DEFAULT ((0)) FOR [SampledBudget11]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactServiceLineEncounterBasis ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ( + [RowID] int NOT NULL, + [BudgetConfigID] smallint NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [ActualEncounters] decimal NOT NULL, + [YTDEncounters] decimal NOT NULL, + [BaseEncounters] decimal NOT NULL, + [ValueMonth01] decimal NOT NULL, + [ValueMonth02] decimal NOT NULL, + [ValueMonth03] decimal NOT NULL, + [ValueMonth04] decimal NOT NULL, + [ValueMonth05] decimal NOT NULL, + [ValueMonth06] decimal NOT NULL, + [ValueMonth07] decimal NOT NULL, + [ValueMonth08] decimal NOT NULL, + [ValueMonth09] decimal NOT NULL, + [ValueMonth10] decimal NOT NULL, + [ValueMonth11] decimal NOT NULL, + [ValueMonth12] decimal NOT NULL, + [ValueAnnualOriginal] decimal NOT NULL, + [ChangeHistoryGUID] uniqueidentifier NOT NULL, + [ServiceLineCasesTotal] decimal NULL +); +GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounterBasis_DimAgeCohort] FOREIGN KEY ([AgeCohortID]) REFERENCES [fw].[DimAgeCohort] ([AgeCohortID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounterBasis_DimEntity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounterBasis_DimMedicalSurgical] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounterBasis_DimPatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounterBasis_DimServiceLine] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth07] DEFAULT ((0)) FOR [ValueMonth07]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth08] DEFAULT ((0)) FOR [ValueMonth08]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth09] DEFAULT ((0)) FOR [ValueMonth09]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth10] DEFAULT ((0)) FOR [ValueMonth10]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth11] DEFAULT ((0)) FOR [ValueMonth11]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth12] DEFAULT ((0)) FOR [ValueMonth12]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueAnnualOriginal] DEFAULT ((0)) FOR [ValueAnnualOriginal]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ChangeHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ChangeHistoryGUID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_BudgetConfigID] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_EntityID] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_PatientClassID] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ServiceLineID] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_AgeCohortID] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_MedicalSurgicalID] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ActualEncounters] DEFAULT ((0)) FOR [ActualEncounters]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_YTDEncounters] DEFAULT ((0)) FOR [YTDEncounters]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_BaseEncounters] DEFAULT ((0)) FOR [BaseEncounters]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth01] DEFAULT ((0)) FOR [ValueMonth01]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth02] DEFAULT ((0)) FOR [ValueMonth02]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth03] DEFAULT ((0)) FOR [ValueMonth03]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth04] DEFAULT ((0)) FOR [ValueMonth04]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth05] DEFAULT ((0)) FOR [ValueMonth05]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBasis] ADD CONSTRAINT [DF_ArchiveFactServiceLineEncounterBasis_ValueMonth06] DEFAULT ((0)) FOR [ValueMonth06]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactServiceLineEncounterBudget ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ( + [RowID] int NOT NULL, + [ServiceLineEncounterID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedValue01] decimal NOT NULL, + [AdjustedValue02] decimal NOT NULL, + [AdjustedValue03] decimal NOT NULL, + [AdjustedValue04] decimal NOT NULL, + [AdjustedValue05] decimal NOT NULL, + [AdjustedValue06] decimal NOT NULL, + [AdjustedValue07] decimal NOT NULL, + [AdjustedValue08] decimal NOT NULL, + [AdjustedValue09] decimal NOT NULL, + [AdjustedValue10] decimal NOT NULL, + [AdjustedValue11] decimal NOT NULL, + [AdjustedValue12] decimal NOT NULL, + [AdjustedValueTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_ArchiveFactServiceLineEncounterBudget] ON [fp].[ArchiveFactServiceLineEncounterBudget] ([ServiceLineEncounterID], [BudgetPhaseID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactServiceLineEncounterBudget_BudgetPhaseID] ON [fp].[ArchiveFactServiceLineEncounterBudget] ([BudgetPhaseID], [ServiceLineEncounterID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[ArchiveFactServiceLineEncounterBudget] ([ServiceLineEncounterID], [BudgetPhaseID]); +GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounterBudget_ServiceLineEncounterID] FOREIGN KEY ([ServiceLineEncounterID]) REFERENCES [fp].[ArchiveFactServiceLineEncounter] ([ServiceLineEncounterID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Servi__33E72804] DEFAULT ((0)) FOR [ServiceLineEncounterID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__LockT__34DB4C3D] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__LockF__35CF7076] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Budge__36C394AF] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__37B7B8E8] DEFAULT ((0)) FOR [AdjustedValue01]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__38ABDD21] DEFAULT ((0)) FOR [AdjustedValue02]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__39A0015A] DEFAULT ((0)) FOR [AdjustedValue03]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3A942593] DEFAULT ((0)) FOR [AdjustedValue04]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3B8849CC] DEFAULT ((0)) FOR [AdjustedValue05]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3C7C6E05] DEFAULT ((0)) FOR [AdjustedValue06]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3D70923E] DEFAULT ((0)) FOR [AdjustedValue07]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3E64B677] DEFAULT ((0)) FOR [AdjustedValue08]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3F58DAB0] DEFAULT ((0)) FOR [AdjustedValue09]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__404CFEE9] DEFAULT ((0)) FOR [AdjustedValue10]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__41412322] DEFAULT ((0)) FOR [AdjustedValue11]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4235475B] DEFAULT ((0)) FOR [AdjustedValue12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactServiceLineEncounterHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ( + [RowID] int NOT NULL, + [ServiceLineEncounterID] int NOT NULL, + [PriorYearActualValue01] decimal NOT NULL, + [PriorYearActualValue02] decimal NOT NULL, + [PriorYearActualValue03] decimal NOT NULL, + [PriorYearActualValue04] decimal NOT NULL, + [PriorYearActualValue05] decimal NOT NULL, + [PriorYearActualValue06] decimal NOT NULL, + [PriorYearActualValue07] decimal NOT NULL, + [PriorYearActualValue08] decimal NOT NULL, + [PriorYearActualValue09] decimal NOT NULL, + [PriorYearActualValue10] decimal NOT NULL, + [PriorYearActualValue11] decimal NOT NULL, + [PriorYearActualValue12] decimal NOT NULL, + [ActualYTDValue01] decimal NOT NULL, + [ActualYTDValue02] decimal NOT NULL, + [ActualYTDValue03] decimal NOT NULL, + [ActualYTDValue04] decimal NOT NULL, + [ActualYTDValue05] decimal NOT NULL, + [ActualYTDValue06] decimal NOT NULL, + [ActualYTDValue07] decimal NOT NULL, + [ActualYTDValue08] decimal NOT NULL, + [ActualYTDValue09] decimal NOT NULL, + [ActualYTDValue10] decimal NOT NULL, + [ActualYTDValue11] decimal NOT NULL, + [ActualYTDValue12] decimal NOT NULL, + [CurrentYearBudget01] decimal NOT NULL, + [CurrentYearBudget02] decimal NOT NULL, + [CurrentYearBudget03] decimal NOT NULL, + [CurrentYearBudget04] decimal NOT NULL, + [CurrentYearBudget05] decimal NOT NULL, + [CurrentYearBudget06] decimal NOT NULL, + [CurrentYearBudget07] decimal NOT NULL, + [CurrentYearBudget08] decimal NOT NULL, + [CurrentYearBudget09] decimal NOT NULL, + [CurrentYearBudget10] decimal NOT NULL, + [CurrentYearBudget11] decimal NOT NULL, + [CurrentYearBudget12] decimal NOT NULL, + [PriorYearActualValueTotal] decimal NOT NULL, + [ActualYTDValueTotal] decimal NOT NULL, + [CurrentYearBudgetTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_ArchiveFactServiceLineEncounterHistory] ON [fp].[ArchiveFactServiceLineEncounterHistory] ([ServiceLineEncounterID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[ArchiveFactServiceLineEncounterHistory] ([ServiceLineEncounterID]); +GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounterHistory_ServiceLineEncounterID] FOREIGN KEY ([ServiceLineEncounterID]) REFERENCES [fp].[ArchiveFactServiceLineEncounter] ([ServiceLineEncounterID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Servi__5824887A] DEFAULT ((0)) FOR [ServiceLineEncounterID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5918ACB3] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5A0CD0EC] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5B00F525] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5BF5195E] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5CE93D97] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5DDD61D0] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5ED18609] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5FC5AA42] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__60B9CE7B] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__61ADF2B4] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__62A216ED] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__63963B26] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__648A5F5F] DEFAULT ((0)) FOR [ActualYTDValue01]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__657E8398] DEFAULT ((0)) FOR [ActualYTDValue02]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6672A7D1] DEFAULT ((0)) FOR [ActualYTDValue03]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6766CC0A] DEFAULT ((0)) FOR [ActualYTDValue04]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__685AF043] DEFAULT ((0)) FOR [ActualYTDValue05]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__694F147C] DEFAULT ((0)) FOR [ActualYTDValue06]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6A4338B5] DEFAULT ((0)) FOR [ActualYTDValue07]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6B375CEE] DEFAULT ((0)) FOR [ActualYTDValue08]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6C2B8127] DEFAULT ((0)) FOR [ActualYTDValue09]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6D1FA560] DEFAULT ((0)) FOR [ActualYTDValue10]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6E13C999] DEFAULT ((0)) FOR [ActualYTDValue11]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6F07EDD2] DEFAULT ((0)) FOR [ActualYTDValue12]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6FFC120B] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__70F03644] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__71E45A7D] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__72D87EB6] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__73CCA2EF] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__74C0C728] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__75B4EB61] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__76A90F9A] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__779D33D3] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7891580C] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__79857C45] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7A79A07E] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactServiceLineEncounterProjection ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ( + [RowID] int NOT NULL, + [ServiceLineEncounterID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedValue01] decimal NOT NULL, + [AdjustedValue02] decimal NOT NULL, + [AdjustedValue03] decimal NOT NULL, + [AdjustedValue04] decimal NOT NULL, + [AdjustedValue05] decimal NOT NULL, + [AdjustedValue06] decimal NOT NULL, + [AdjustedValue07] decimal NOT NULL, + [AdjustedValue08] decimal NOT NULL, + [AdjustedValue09] decimal NOT NULL, + [AdjustedValue10] decimal NOT NULL, + [AdjustedValue11] decimal NOT NULL, + [AdjustedValue12] decimal NOT NULL, + [AdjustedValueTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_ArchiveFactServiceLineEncounterProjection] ON [fp].[ArchiveFactServiceLineEncounterProjection] ([ServiceLineEncounterID], [BudgetPhaseID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactServiceLineEncounterProjection_BudgetPhaseID] ON [fp].[ArchiveFactServiceLineEncounterProjection] ([BudgetPhaseID], [ServiceLineEncounterID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[ArchiveFactServiceLineEncounterProjection] ([ServiceLineEncounterID], [BudgetPhaseID]); +GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [FK_ArchiveFactServiceLineEncounterProjection_ServiceLineEncounterID] FOREIGN KEY ([ServiceLineEncounterID]) REFERENCES [fp].[ArchiveFactServiceLineEncounter] ([ServiceLineEncounterID]); GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Servi__4605D83F] DEFAULT ((0)) FOR [ServiceLineEncounterID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__LockT__46F9FC78] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__LockF__47EE20B1] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Budge__48E244EA] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__49D66923] DEFAULT ((0)) FOR [AdjustedValue01]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4ACA8D5C] DEFAULT ((0)) FOR [AdjustedValue02]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4BBEB195] DEFAULT ((0)) FOR [AdjustedValue03]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4CB2D5CE] DEFAULT ((0)) FOR [AdjustedValue04]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4DA6FA07] DEFAULT ((0)) FOR [AdjustedValue05]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4E9B1E40] DEFAULT ((0)) FOR [AdjustedValue06]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__4F8F4279] DEFAULT ((0)) FOR [AdjustedValue07]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__508366B2] DEFAULT ((0)) FOR [AdjustedValue08]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__51778AEB] DEFAULT ((0)) FOR [AdjustedValue09]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__526BAF24] DEFAULT ((0)) FOR [AdjustedValue10]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__535FD35D] DEFAULT ((0)) FOR [AdjustedValue11]; GO +ALTER TABLE [fp].[ArchiveFactServiceLineEncounterProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__5453F796] DEFAULT ((0)) FOR [AdjustedValue12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactStaffing ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactStaffing] ( + [StaffingID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeGroupID] int NOT NULL, + [ProductiveClassID] int NOT NULL, + [VariabilityID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [AddDate] datetime NOT NULL, + [SampledBudget01] decimal NOT NULL, + [SampledBudget02] decimal NOT NULL, + [SampledBudget03] decimal NOT NULL, + [SampledBudget04] decimal NOT NULL, + [SampledBudget05] decimal NOT NULL, + [SampledBudget06] decimal NOT NULL, + [SampledBudget07] decimal NOT NULL, + [SampledBudget08] decimal NOT NULL, + [SampledBudget09] decimal NOT NULL, + [SampledBudget10] decimal NOT NULL, + [SampledBudget11] decimal NOT NULL, + [SampledBudget12] decimal NOT NULL, + [SampledBudgetTotal] decimal NOT NULL, + [SampledProjection01] decimal NOT NULL, + [SampledProjection02] decimal NOT NULL, + [SampledProjection03] decimal NOT NULL, + [SampledProjection04] decimal NOT NULL, + [SampledProjection05] decimal NOT NULL, + [SampledProjection06] decimal NOT NULL, + [SampledProjection07] decimal NOT NULL, + [SampledProjection08] decimal NOT NULL, + [SampledProjection09] decimal NOT NULL, + [SampledProjection10] decimal NOT NULL, + [SampledProjection11] decimal NOT NULL, + [SampledProjection12] decimal NOT NULL, + [SampledProjectionTotal] decimal NOT NULL, + [InitialBudget01] decimal NOT NULL, + [InitialBudget02] decimal NOT NULL, + [InitialBudget03] decimal NOT NULL, + [InitialBudget04] decimal NOT NULL, + [InitialBudget05] decimal NOT NULL, + [InitialBudget06] decimal NOT NULL, + [InitialBudget07] decimal NOT NULL, + [InitialBudget08] decimal NOT NULL, + [InitialBudget09] decimal NOT NULL, + [InitialBudget10] decimal NOT NULL, + [InitialBudget11] decimal NOT NULL, + [InitialBudget12] decimal NOT NULL, + [InitialBudgetTotal] decimal NOT NULL, + [InitialProjection01] decimal NOT NULL, + [InitialProjection02] decimal NOT NULL, + [InitialProjection03] decimal NOT NULL, + [InitialProjection04] decimal NOT NULL, + [InitialProjection05] decimal NOT NULL, + [InitialProjection06] decimal NOT NULL, + [InitialProjection07] decimal NOT NULL, + [InitialProjection08] decimal NOT NULL, + [InitialProjection09] decimal NOT NULL, + [InitialProjection10] decimal NOT NULL, + [InitialProjection11] decimal NOT NULL, + [InitialProjection12] decimal NOT NULL, + [InitialProjectionTotal] decimal NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [SubSectionID] int NOT NULL, + PRIMARY KEY ([StaffingID]) +); + +CREATE CLUSTERED INDEX [IX_ArchiveFactStaffing] ON [fp].[ArchiveFactStaffing] ([StaffingID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactStaffing_BudgetConfig] ON [fp].[ArchiveFactStaffing] ([BudgetConfigID]) INCLUDE ([StaffingID], [EntityGroupConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactStaffing_Department] ON [fp].[ArchiveFactStaffing] ([DepartmentID]) INCLUDE ([StaffingID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactStaffing_Entity] ON [fp].[ArchiveFactStaffing] ([EntityID]) INCLUDE ([StaffingID], [BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactStaffing_EntityGroupConfig] ON [fp].[ArchiveFactStaffing] ([EntityGroupConfigID]) INCLUDE ([StaffingID], [BudgetConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactStaffing_JobCode] ON [fp].[ArchiveFactStaffing] ([JobCodeID]) INCLUDE ([StaffingID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactStaffing_PayCodeGroup] ON [fp].[ArchiveFactStaffing] ([PayCodeGroupID]) INCLUDE ([StaffingID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [JobCodeID], [ProductiveClassID], [VariabilityID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveFactStaffing_ProductiveClass] ON [fp].[ArchiveFactStaffing] ([ProductiveClassID]) INCLUDE ([StaffingID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID], [UnitTypeID]); +GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Provi__225F0B54] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Provi__23532F8D] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Provi__244753C6] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Budge__24FF47C6] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Provi__253B77FF] DEFAULT ((0)) FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Entit__25F36BFF] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__SubSe__262F9C38] DEFAULT ((0)) FOR [SubSectionID]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Entit__26E79038] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Depar__27DBB471] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__JobCo__28CFD8AA] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__PayCo__29C3FCE3] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Produ__2AB8211C] DEFAULT ((0)) FOR [ProductiveClassID]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Varia__2BAC4555] DEFAULT ((0)) FOR [VariabilityID]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__UnitT__2CA0698E] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__AddDa__2D948DC7] DEFAULT (getdate()) FOR [AddDate]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__2E88B200] DEFAULT ((0)) FOR [SampledBudget01]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__2F7CD639] DEFAULT ((0)) FOR [SampledBudget02]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3070FA72] DEFAULT ((0)) FOR [SampledBudget03]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__31651EAB] DEFAULT ((0)) FOR [SampledBudget04]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__325942E4] DEFAULT ((0)) FOR [SampledBudget05]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__334D671D] DEFAULT ((0)) FOR [SampledBudget06]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__34418B56] DEFAULT ((0)) FOR [SampledBudget07]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3535AF8F] DEFAULT ((0)) FOR [SampledBudget08]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3629D3C8] DEFAULT ((0)) FOR [SampledBudget09]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__371DF801] DEFAULT ((0)) FOR [SampledBudget10]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__38121C3A] DEFAULT ((0)) FOR [SampledBudget11]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__39064073] DEFAULT ((0)) FOR [SampledBudget12]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__39FA64AC] DEFAULT ((0)) FOR [SampledProjection01]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3AEE88E5] DEFAULT ((0)) FOR [SampledProjection02]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3BE2AD1E] DEFAULT ((0)) FOR [SampledProjection03]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3CD6D157] DEFAULT ((0)) FOR [SampledProjection04]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3DCAF590] DEFAULT ((0)) FOR [SampledProjection05]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3EBF19C9] DEFAULT ((0)) FOR [SampledProjection06]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__3FB33E02] DEFAULT ((0)) FOR [SampledProjection07]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__40A7623B] DEFAULT ((0)) FOR [SampledProjection08]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__419B8674] DEFAULT ((0)) FOR [SampledProjection09]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__428FAAAD] DEFAULT ((0)) FOR [SampledProjection10]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__4383CEE6] DEFAULT ((0)) FOR [SampledProjection11]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Sampl__4477F31F] DEFAULT ((0)) FOR [SampledProjection12]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__456C1758] DEFAULT ((0)) FOR [InitialBudget01]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__46603B91] DEFAULT ((0)) FOR [InitialBudget02]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__47545FCA] DEFAULT ((0)) FOR [InitialBudget03]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__48488403] DEFAULT ((0)) FOR [InitialBudget04]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__493CA83C] DEFAULT ((0)) FOR [InitialBudget05]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__4A30CC75] DEFAULT ((0)) FOR [InitialBudget06]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__4B24F0AE] DEFAULT ((0)) FOR [InitialBudget07]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__4C1914E7] DEFAULT ((0)) FOR [InitialBudget08]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__4D0D3920] DEFAULT ((0)) FOR [InitialBudget09]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__4E015D59] DEFAULT ((0)) FOR [InitialBudget10]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__4EF58192] DEFAULT ((0)) FOR [InitialBudget11]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__4FE9A5CB] DEFAULT ((0)) FOR [InitialBudget12]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__50DDCA04] DEFAULT ((0)) FOR [InitialProjection01]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__51D1EE3D] DEFAULT ((0)) FOR [InitialProjection02]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__52C61276] DEFAULT ((0)) FOR [InitialProjection03]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__53BA36AF] DEFAULT ((0)) FOR [InitialProjection04]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__54AE5AE8] DEFAULT ((0)) FOR [InitialProjection05]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__55A27F21] DEFAULT ((0)) FOR [InitialProjection06]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__5696A35A] DEFAULT ((0)) FOR [InitialProjection07]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__578AC793] DEFAULT ((0)) FOR [InitialProjection08]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__587EEBCC] DEFAULT ((0)) FOR [InitialProjection09]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__59731005] DEFAULT ((0)) FOR [InitialProjection10]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__5A67343E] DEFAULT ((0)) FOR [InitialProjection11]; GO +ALTER TABLE [fp].[ArchiveFactStaffing] ADD CONSTRAINT [DF__ArchiveFa__Initi__5B5B5877] DEFAULT ((0)) FOR [InitialProjection12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactStaffingBudget ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactStaffingBudget] ( + [RowID] int NOT NULL, + [StaffingID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedValue01] decimal NOT NULL, + [AdjustedValue02] decimal NOT NULL, + [AdjustedValue03] decimal NOT NULL, + [AdjustedValue04] decimal NOT NULL, + [AdjustedValue05] decimal NOT NULL, + [AdjustedValue06] decimal NOT NULL, + [AdjustedValue07] decimal NOT NULL, + [AdjustedValue08] decimal NOT NULL, + [AdjustedValue09] decimal NOT NULL, + [AdjustedValue10] decimal NOT NULL, + [AdjustedValue11] decimal NOT NULL, + [AdjustedValue12] decimal NOT NULL, + [AdjustedValueTotal] decimal NOT NULL, + [FlexedValue01] decimal NOT NULL, + [FlexedValue02] decimal NOT NULL, + [FlexedValue03] decimal NOT NULL, + [FlexedValue04] decimal NOT NULL, + [FlexedValue05] decimal NOT NULL, + [FlexedValue06] decimal NOT NULL, + [FlexedValue07] decimal NOT NULL, + [FlexedValue08] decimal NOT NULL, + [FlexedValue09] decimal NOT NULL, + [FlexedValue10] decimal NOT NULL, + [FlexedValue11] decimal NOT NULL, + [FlexedValue12] decimal NOT NULL, + [FlexedValueTotal] decimal NOT NULL, + [PercentAdjustmentFactor01] decimal NOT NULL, + [PercentAdjustmentFactor02] decimal NOT NULL, + [PercentAdjustmentFactor03] decimal NOT NULL, + [PercentAdjustmentFactor04] decimal NOT NULL, + [PercentAdjustmentFactor05] decimal NOT NULL, + [PercentAdjustmentFactor06] decimal NOT NULL, + [PercentAdjustmentFactor07] decimal NOT NULL, + [PercentAdjustmentFactor08] decimal NOT NULL, + [PercentAdjustmentFactor09] decimal NOT NULL, + [PercentAdjustmentFactor10] decimal NOT NULL, + [PercentAdjustmentFactor11] decimal NOT NULL, + [PercentAdjustmentFactor12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_ArchiveFactStaffingBudget] ON [fp].[ArchiveFactStaffingBudget] ([StaffingID], [BudgetPhaseID]); +GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [FK_ArchiveFactStaffingBudget_StaffingID] FOREIGN KEY ([StaffingID]) REFERENCES [fp].[ArchiveFactStaffing] ([StaffingID]); GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__008CDD26] DEFAULT ((1)) FOR [PercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__0181015F] DEFAULT ((1)) FOR [PercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__02752598] DEFAULT ((1)) FOR [PercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__036949D1] DEFAULT ((1)) FOR [PercentAdjustmentFactor12]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Staff__5E37C522] DEFAULT ((0)) FOR [StaffingID]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__LockT__5F2BE95B] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__LockF__60200D94] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Budge__611431CD] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__62085606] DEFAULT ((0)) FOR [AdjustedValue01]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__62FC7A3F] DEFAULT ((0)) FOR [AdjustedValue02]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__63F09E78] DEFAULT ((0)) FOR [AdjustedValue03]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__64E4C2B1] DEFAULT ((0)) FOR [AdjustedValue04]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__65D8E6EA] DEFAULT ((0)) FOR [AdjustedValue05]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__66CD0B23] DEFAULT ((0)) FOR [AdjustedValue06]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__67C12F5C] DEFAULT ((0)) FOR [AdjustedValue07]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__68B55395] DEFAULT ((0)) FOR [AdjustedValue08]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__69A977CE] DEFAULT ((0)) FOR [AdjustedValue09]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6A9D9C07] DEFAULT ((0)) FOR [AdjustedValue10]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6B91C040] DEFAULT ((0)) FOR [AdjustedValue11]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__6C85E479] DEFAULT ((0)) FOR [AdjustedValue12]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6D7A08B2] DEFAULT ((0)) FOR [FlexedValue01]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6E6E2CEB] DEFAULT ((0)) FOR [FlexedValue02]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__6F625124] DEFAULT ((0)) FOR [FlexedValue03]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__7056755D] DEFAULT ((0)) FOR [FlexedValue04]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__714A9996] DEFAULT ((0)) FOR [FlexedValue05]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__723EBDCF] DEFAULT ((0)) FOR [FlexedValue06]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__7332E208] DEFAULT ((0)) FOR [FlexedValue07]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__74270641] DEFAULT ((0)) FOR [FlexedValue08]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__751B2A7A] DEFAULT ((0)) FOR [FlexedValue09]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__760F4EB3] DEFAULT ((0)) FOR [FlexedValue10]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__770372EC] DEFAULT ((0)) FOR [FlexedValue11]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__77F79725] DEFAULT ((0)) FOR [FlexedValue12]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__78EBBB5E] DEFAULT ((1)) FOR [PercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__79DFDF97] DEFAULT ((1)) FOR [PercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__7AD403D0] DEFAULT ((1)) FOR [PercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__7BC82809] DEFAULT ((1)) FOR [PercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__7CBC4C42] DEFAULT ((1)) FOR [PercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__7DB0707B] DEFAULT ((1)) FOR [PercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__7EA494B4] DEFAULT ((1)) FOR [PercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[ArchiveFactStaffingBudget] ADD CONSTRAINT [DF__ArchiveFa__Perce__7F98B8ED] DEFAULT ((1)) FOR [PercentAdjustmentFactor08]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactStaffingHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactStaffingHistory] ( + [RowID] int NOT NULL, + [StaffingID] int NOT NULL, + [PriorYearActualValue01] decimal NOT NULL, + [PriorYearActualValue02] decimal NOT NULL, + [PriorYearActualValue03] decimal NOT NULL, + [PriorYearActualValue04] decimal NOT NULL, + [PriorYearActualValue05] decimal NOT NULL, + [PriorYearActualValue06] decimal NOT NULL, + [PriorYearActualValue07] decimal NOT NULL, + [PriorYearActualValue08] decimal NOT NULL, + [PriorYearActualValue09] decimal NOT NULL, + [PriorYearActualValue10] decimal NOT NULL, + [PriorYearActualValue11] decimal NOT NULL, + [PriorYearActualValue12] decimal NOT NULL, + [PriorYearActualValueTotal] decimal NOT NULL, + [ActualYTDValue01] decimal NOT NULL, + [ActualYTDValue02] decimal NOT NULL, + [ActualYTDValue03] decimal NOT NULL, + [ActualYTDValue04] decimal NOT NULL, + [ActualYTDValue05] decimal NOT NULL, + [ActualYTDValue06] decimal NOT NULL, + [ActualYTDValue07] decimal NOT NULL, + [ActualYTDValue08] decimal NOT NULL, + [ActualYTDValue09] decimal NOT NULL, + [ActualYTDValue10] decimal NOT NULL, + [ActualYTDValue11] decimal NOT NULL, + [ActualYTDValue12] decimal NOT NULL, + [ActualYTDValueTotal] decimal NOT NULL, + [CurrentYearBudget01] decimal NOT NULL, + [CurrentYearBudget02] decimal NOT NULL, + [CurrentYearBudget03] decimal NOT NULL, + [CurrentYearBudget04] decimal NOT NULL, + [CurrentYearBudget05] decimal NOT NULL, + [CurrentYearBudget06] decimal NOT NULL, + [CurrentYearBudget07] decimal NOT NULL, + [CurrentYearBudget08] decimal NOT NULL, + [CurrentYearBudget09] decimal NOT NULL, + [CurrentYearBudget10] decimal NOT NULL, + [CurrentYearBudget11] decimal NOT NULL, + [CurrentYearBudget12] decimal NOT NULL, + [CurrentYearBudgetTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [FK_ArchiveFactStaffingHistory_StaffingID] FOREIGN KEY ([StaffingID]) REFERENCES [fp].[ArchiveFactStaffing] ([StaffingID]); GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Staff__2A8ECF41] DEFAULT ((0)) FOR [StaffingID]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__2B82F37A] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__2C7717B3] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__2D6B3BEC] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__2E5F6025] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__2F53845E] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3047A897] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__313BCCD0] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__322FF109] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__33241542] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__3418397B] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__350C5DB4] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__360081ED] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__36F4A626] DEFAULT ((0)) FOR [ActualYTDValue01]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__37E8CA5F] DEFAULT ((0)) FOR [ActualYTDValue02]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__38DCEE98] DEFAULT ((0)) FOR [ActualYTDValue03]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__39D112D1] DEFAULT ((0)) FOR [ActualYTDValue04]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3AC5370A] DEFAULT ((0)) FOR [ActualYTDValue05]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3BB95B43] DEFAULT ((0)) FOR [ActualYTDValue06]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3CAD7F7C] DEFAULT ((0)) FOR [ActualYTDValue07]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3DA1A3B5] DEFAULT ((0)) FOR [ActualYTDValue08]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3E95C7EE] DEFAULT ((0)) FOR [ActualYTDValue09]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__3F89EC27] DEFAULT ((0)) FOR [ActualYTDValue10]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__407E1060] DEFAULT ((0)) FOR [ActualYTDValue11]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__41723499] DEFAULT ((0)) FOR [ActualYTDValue12]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__426658D2] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__435A7D0B] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__444EA144] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4542C57D] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4636E9B6] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__472B0DEF] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__481F3228] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__49135661] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4A077A9A] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4AFB9ED3] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4BEFC30C] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__4CE3E745] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactStaffingHistoryFTETotals ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactStaffingHistoryFTETotals] ( + [RowID] int NOT NULL, + [StaffingID] int NOT NULL, + [PriorYearActualTotal] decimal NOT NULL, + [ActualYTDTotal] decimal NOT NULL, + [CurrentYearBudgetTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_ArchiveFactStaffingHistoryFTETotals] ON [fp].[ArchiveFactStaffingHistoryFTETotals] ([StaffingID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[ArchiveFactStaffingHistoryFTETotals] ([StaffingID]); +GO +ALTER TABLE [fp].[ArchiveFactStaffingHistoryFTETotals] ADD CONSTRAINT [DF__ArchiveFa__Staff__16EC8D51] DEFAULT ((0)) FOR [StaffingID]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistoryFTETotals] ADD CONSTRAINT [DF__ArchiveFa__Prior__17E0B18A] DEFAULT ((0)) FOR [PriorYearActualTotal]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistoryFTETotals] ADD CONSTRAINT [DF__ArchiveFa__Actua__18D4D5C3] DEFAULT ((0)) FOR [ActualYTDTotal]; GO +ALTER TABLE [fp].[ArchiveFactStaffingHistoryFTETotals] ADD CONSTRAINT [DF__ArchiveFa__Curre__19C8F9FC] DEFAULT ((0)) FOR [CurrentYearBudgetTotal]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactStaffingProjection ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactStaffingProjection] ( + [RowID] int NOT NULL, + [StaffingID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedValue01] decimal NOT NULL, + [AdjustedValue02] decimal NOT NULL, + [AdjustedValue03] decimal NOT NULL, + [AdjustedValue04] decimal NOT NULL, + [AdjustedValue05] decimal NOT NULL, + [AdjustedValue06] decimal NOT NULL, + [AdjustedValue07] decimal NOT NULL, + [AdjustedValue08] decimal NOT NULL, + [AdjustedValue09] decimal NOT NULL, + [AdjustedValue10] decimal NOT NULL, + [AdjustedValue11] decimal NOT NULL, + [AdjustedValue12] decimal NOT NULL, + [AdjustedValueTotal] decimal NOT NULL, + [FlexedValue01] decimal NOT NULL, + [FlexedValue02] decimal NOT NULL, + [FlexedValue03] decimal NOT NULL, + [FlexedValue04] decimal NOT NULL, + [FlexedValue05] decimal NOT NULL, + [FlexedValue06] decimal NOT NULL, + [FlexedValue07] decimal NOT NULL, + [FlexedValue08] decimal NOT NULL, + [FlexedValue09] decimal NOT NULL, + [FlexedValue10] decimal NOT NULL, + [FlexedValue11] decimal NOT NULL, + [FlexedValue12] decimal NOT NULL, + [FlexedValueTotal] decimal NOT NULL, + [PercentAdjustmentFactor01] decimal NOT NULL, + [PercentAdjustmentFactor02] decimal NOT NULL, + [PercentAdjustmentFactor03] decimal NOT NULL, + [PercentAdjustmentFactor04] decimal NOT NULL, + [PercentAdjustmentFactor05] decimal NOT NULL, + [PercentAdjustmentFactor06] decimal NOT NULL, + [PercentAdjustmentFactor07] decimal NOT NULL, + [PercentAdjustmentFactor08] decimal NOT NULL, + [PercentAdjustmentFactor09] decimal NOT NULL, + [PercentAdjustmentFactor10] decimal NOT NULL, + [PercentAdjustmentFactor11] decimal NOT NULL, + [PercentAdjustmentFactor12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_ArchiveFactStaffingProjection] ON [fp].[ArchiveFactStaffingProjection] ([StaffingID], [BudgetPhaseID]); +GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [FK_ArchiveFactStaffingProjection_StaffingID] FOREIGN KEY ([StaffingID]) REFERENCES [fp].[ArchiveFactStaffing] ([StaffingID]); GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Staff__0739DAB5] DEFAULT ((0)) FOR [StaffingID]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__LockT__082DFEEE] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__LockF__09222327] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Budge__0A164760] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0B0A6B99] DEFAULT ((0)) FOR [AdjustedValue01]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0BFE8FD2] DEFAULT ((0)) FOR [AdjustedValue02]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0CF2B40B] DEFAULT ((0)) FOR [AdjustedValue03]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0DE6D844] DEFAULT ((0)) FOR [AdjustedValue04]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0EDAFC7D] DEFAULT ((0)) FOR [AdjustedValue05]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__0FCF20B6] DEFAULT ((0)) FOR [AdjustedValue06]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__10C344EF] DEFAULT ((0)) FOR [AdjustedValue07]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__11B76928] DEFAULT ((0)) FOR [AdjustedValue08]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__12AB8D61] DEFAULT ((0)) FOR [AdjustedValue09]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__139FB19A] DEFAULT ((0)) FOR [AdjustedValue10]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1493D5D3] DEFAULT ((0)) FOR [AdjustedValue11]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1587FA0C] DEFAULT ((0)) FOR [AdjustedValue12]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__167C1E45] DEFAULT ((0)) FOR [FlexedValue01]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1770427E] DEFAULT ((0)) FOR [FlexedValue02]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__186466B7] DEFAULT ((0)) FOR [FlexedValue03]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__19588AF0] DEFAULT ((0)) FOR [FlexedValue04]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1A4CAF29] DEFAULT ((0)) FOR [FlexedValue05]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1B40D362] DEFAULT ((0)) FOR [FlexedValue06]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1C34F79B] DEFAULT ((0)) FOR [FlexedValue07]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1D291BD4] DEFAULT ((0)) FOR [FlexedValue08]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1E1D400D] DEFAULT ((0)) FOR [FlexedValue09]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1F116446] DEFAULT ((0)) FOR [FlexedValue10]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__2005887F] DEFAULT ((0)) FOR [FlexedValue11]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__20F9ACB8] DEFAULT ((0)) FOR [FlexedValue12]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__21EDD0F1] DEFAULT ((1)) FOR [PercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__22E1F52A] DEFAULT ((1)) FOR [PercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__23D61963] DEFAULT ((1)) FOR [PercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__24CA3D9C] DEFAULT ((1)) FOR [PercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__25BE61D5] DEFAULT ((1)) FOR [PercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__26B2860E] DEFAULT ((1)) FOR [PercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__27A6AA47] DEFAULT ((1)) FOR [PercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__289ACE80] DEFAULT ((1)) FOR [PercentAdjustmentFactor08]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__298EF2B9] DEFAULT ((1)) FOR [PercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__2A8316F2] DEFAULT ((1)) FOR [PercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__2B773B2B] DEFAULT ((1)) FOR [PercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[ArchiveFactStaffingProjection] ADD CONSTRAINT [DF__ArchiveFa__Perce__2C6B5F64] DEFAULT ((1)) FOR [PercentAdjustmentFactor12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactStatistics ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactStatistics] ( + [StatisticsID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [PayorID] int NOT NULL, + [PatientClassID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [AddDate] datetime NOT NULL, + [SampledBudget01] decimal NOT NULL, + [SampledBudget02] decimal NOT NULL, + [SampledBudget03] decimal NOT NULL, + [SampledBudget04] decimal NOT NULL, + [SampledBudget05] decimal NOT NULL, + [SampledBudget06] decimal NOT NULL, + [SampledBudget07] decimal NOT NULL, + [SampledBudget08] decimal NOT NULL, + [SampledBudget09] decimal NOT NULL, + [SampledBudget10] decimal NOT NULL, + [SampledBudget11] decimal NOT NULL, + [SampledBudget12] decimal NOT NULL, + [SampledBudgetTotal] decimal NULL, + [SampledProjection01] decimal NOT NULL, + [SampledProjection02] decimal NOT NULL, + [SampledProjection03] decimal NOT NULL, + [SampledProjection04] decimal NOT NULL, + [SampledProjection05] decimal NOT NULL, + [SampledProjection06] decimal NOT NULL, + [SampledProjection07] decimal NOT NULL, + [SampledProjection08] decimal NOT NULL, + [SampledProjection09] decimal NOT NULL, + [SampledProjection10] decimal NOT NULL, + [SampledProjection11] decimal NOT NULL, + [SampledProjection12] decimal NOT NULL, + [SampledProjectionTotal] decimal NULL, + [InitialBudget01] decimal NOT NULL, + [InitialBudget02] decimal NOT NULL, + [InitialBudget03] decimal NOT NULL, + [InitialBudget04] decimal NOT NULL, + [InitialBudget05] decimal NOT NULL, + [InitialBudget06] decimal NOT NULL, + [InitialBudget07] decimal NOT NULL, + [InitialBudget08] decimal NOT NULL, + [InitialBudget09] decimal NOT NULL, + [InitialBudget10] decimal NOT NULL, + [InitialBudget11] decimal NOT NULL, + [InitialBudget12] decimal NOT NULL, + [InitialBudgetTotal] decimal NULL, + [InitialProjection01] decimal NOT NULL, + [InitialProjection02] decimal NOT NULL, + [InitialProjection03] decimal NOT NULL, + [InitialProjection04] decimal NOT NULL, + [InitialProjection05] decimal NOT NULL, + [InitialProjection06] decimal NOT NULL, + [InitialProjection07] decimal NOT NULL, + [InitialProjection08] decimal NOT NULL, + [InitialProjection09] decimal NOT NULL, + [InitialProjection10] decimal NOT NULL, + [InitialProjection11] decimal NOT NULL, + [InitialProjection12] decimal NOT NULL, + [InitialProjectionTotal] decimal NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [SubSectionID] int NOT NULL, + PRIMARY KEY ([StatisticsID]) +); + +CREATE CLUSTERED INDEX [IX_ArchiveFactStatistics] ON [fp].[ArchiveFactStatistics] ([StatisticsID]); +GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__0037D76B] DEFAULT ((0)) FOR [InitialBudget12]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__012BFBA4] DEFAULT ((0)) FOR [InitialProjection01]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__02201FDD] DEFAULT ((0)) FOR [InitialProjection02]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__03144416] DEFAULT ((0)) FOR [InitialProjection03]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__0408684F] DEFAULT ((0)) FOR [InitialProjection04]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__04FC8C88] DEFAULT ((0)) FOR [InitialProjection05]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__05F0B0C1] DEFAULT ((0)) FOR [InitialProjection06]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__06E4D4FA] DEFAULT ((0)) FOR [InitialProjection07]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__07D8F933] DEFAULT ((0)) FOR [InitialProjection08]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__08CD1D6C] DEFAULT ((0)) FOR [InitialProjection09]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__09C141A5] DEFAULT ((0)) FOR [InitialProjection10]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__0AB565DE] DEFAULT ((0)) FOR [InitialProjection11]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__0BA98A17] DEFAULT ((0)) FOR [InitialProjection12]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Provi__1D9A5637] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Provi__1E8E7A70] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Provi__1F829EA9] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Provi__2076C2E2] DEFAULT ((0)) FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__SubSe__216AE71B] DEFAULT ((0)) FOR [SubSectionID]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Budge__554D7966] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Entit__56419D9F] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Entit__5735C1D8] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Depar__5829E611] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Accou__591E0A4A] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Finan__5A122E83] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Payor__5B0652BC] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Patie__5BFA76F5] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__UnitT__5CEE9B2E] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__AddDa__5DE2BF67] DEFAULT (getdate()) FOR [AddDate]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__5ED6E3A0] DEFAULT ((0)) FOR [SampledBudget01]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__5FCB07D9] DEFAULT ((0)) FOR [SampledBudget02]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__60BF2C12] DEFAULT ((0)) FOR [SampledBudget03]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__61B3504B] DEFAULT ((0)) FOR [SampledBudget04]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__62A77484] DEFAULT ((0)) FOR [SampledBudget05]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__639B98BD] DEFAULT ((0)) FOR [SampledBudget06]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__648FBCF6] DEFAULT ((0)) FOR [SampledBudget07]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6583E12F] DEFAULT ((0)) FOR [SampledBudget08]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__66780568] DEFAULT ((0)) FOR [SampledBudget09]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__676C29A1] DEFAULT ((0)) FOR [SampledBudget10]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__68604DDA] DEFAULT ((0)) FOR [SampledBudget11]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__69547213] DEFAULT ((0)) FOR [SampledBudget12]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6A48964C] DEFAULT ((0)) FOR [SampledProjection01]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6B3CBA85] DEFAULT ((0)) FOR [SampledProjection02]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6C30DEBE] DEFAULT ((0)) FOR [SampledProjection03]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6D2502F7] DEFAULT ((0)) FOR [SampledProjection04]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6E192730] DEFAULT ((0)) FOR [SampledProjection05]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__6F0D4B69] DEFAULT ((0)) FOR [SampledProjection06]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__70016FA2] DEFAULT ((0)) FOR [SampledProjection07]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__70F593DB] DEFAULT ((0)) FOR [SampledProjection08]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__71E9B814] DEFAULT ((0)) FOR [SampledProjection09]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__72DDDC4D] DEFAULT ((0)) FOR [SampledProjection10]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__73D20086] DEFAULT ((0)) FOR [SampledProjection11]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Sampl__74C624BF] DEFAULT ((0)) FOR [SampledProjection12]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__75BA48F8] DEFAULT ((0)) FOR [InitialBudget01]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__76AE6D31] DEFAULT ((0)) FOR [InitialBudget02]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__77A2916A] DEFAULT ((0)) FOR [InitialBudget03]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__7896B5A3] DEFAULT ((0)) FOR [InitialBudget04]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__798AD9DC] DEFAULT ((0)) FOR [InitialBudget05]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__7A7EFE15] DEFAULT ((0)) FOR [InitialBudget06]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__7B73224E] DEFAULT ((0)) FOR [InitialBudget07]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__7C674687] DEFAULT ((0)) FOR [InitialBudget08]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__7D5B6AC0] DEFAULT ((0)) FOR [InitialBudget09]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__7E4F8EF9] DEFAULT ((0)) FOR [InitialBudget10]; GO +ALTER TABLE [fp].[ArchiveFactStatistics] ADD CONSTRAINT [DF__ArchiveFa__Initi__7F43B332] DEFAULT ((0)) FOR [InitialBudget11]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactStatisticsBudget ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactStatisticsBudget] ( + [RowID] int NOT NULL, + [StatisticsID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedValue01] decimal NOT NULL, + [AdjustedValue02] decimal NOT NULL, + [AdjustedValue03] decimal NOT NULL, + [AdjustedValue04] decimal NOT NULL, + [AdjustedValue05] decimal NOT NULL, + [AdjustedValue06] decimal NOT NULL, + [AdjustedValue07] decimal NOT NULL, + [AdjustedValue08] decimal NOT NULL, + [AdjustedValue09] decimal NOT NULL, + [AdjustedValue10] decimal NOT NULL, + [AdjustedValue11] decimal NOT NULL, + [AdjustedValue12] decimal NOT NULL, + [AdjustedValueTotal] decimal NULL, + [FlexedValue01] decimal NOT NULL, + [FlexedValue02] decimal NOT NULL, + [FlexedValue03] decimal NOT NULL, + [FlexedValue04] decimal NOT NULL, + [FlexedValue05] decimal NOT NULL, + [FlexedValue06] decimal NOT NULL, + [FlexedValue07] decimal NOT NULL, + [FlexedValue08] decimal NOT NULL, + [FlexedValue09] decimal NOT NULL, + [FlexedValue10] decimal NOT NULL, + [FlexedValue11] decimal NOT NULL, + [FlexedValue12] decimal NOT NULL, + [FlexedValueTotal] decimal NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [FK_ArchiveFactStatisticsBudget_StatisticsID] FOREIGN KEY ([StatisticsID]) REFERENCES [fp].[ArchiveFactStatistics] ([StatisticsID]); GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Stati__0E85F6C2] DEFAULT ((0)) FOR [StatisticsID]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__LockT__0F7A1AFB] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__LockF__106E3F34] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Budge__1162636D] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__125687A6] DEFAULT ((0)) FOR [AdjustedValue01]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__134AABDF] DEFAULT ((0)) FOR [AdjustedValue02]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__143ED018] DEFAULT ((0)) FOR [AdjustedValue03]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1532F451] DEFAULT ((0)) FOR [AdjustedValue04]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1627188A] DEFAULT ((0)) FOR [AdjustedValue05]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__171B3CC3] DEFAULT ((0)) FOR [AdjustedValue06]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__180F60FC] DEFAULT ((0)) FOR [AdjustedValue07]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__19038535] DEFAULT ((0)) FOR [AdjustedValue08]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__19F7A96E] DEFAULT ((0)) FOR [AdjustedValue09]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1AEBCDA7] DEFAULT ((0)) FOR [AdjustedValue10]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1BDFF1E0] DEFAULT ((0)) FOR [AdjustedValue11]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Adjus__1CD41619] DEFAULT ((0)) FOR [AdjustedValue12]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1DC83A52] DEFAULT ((0)) FOR [FlexedValue01]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1EBC5E8B] DEFAULT ((0)) FOR [FlexedValue02]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__1FB082C4] DEFAULT ((0)) FOR [FlexedValue03]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__20A4A6FD] DEFAULT ((0)) FOR [FlexedValue04]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__2198CB36] DEFAULT ((0)) FOR [FlexedValue05]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__228CEF6F] DEFAULT ((0)) FOR [FlexedValue06]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__238113A8] DEFAULT ((0)) FOR [FlexedValue07]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__247537E1] DEFAULT ((0)) FOR [FlexedValue08]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__25695C1A] DEFAULT ((0)) FOR [FlexedValue09]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__265D8053] DEFAULT ((0)) FOR [FlexedValue10]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__2751A48C] DEFAULT ((0)) FOR [FlexedValue11]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsBudget] ADD CONSTRAINT [DF__ArchiveFa__Flexe__2845C8C5] DEFAULT ((0)) FOR [FlexedValue12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactStatisticsHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactStatisticsHistory] ( + [RowID] int NOT NULL, + [StatisticsID] int NOT NULL, + [PriorYearActualValue01] decimal NOT NULL, + [PriorYearActualValue02] decimal NOT NULL, + [PriorYearActualValue03] decimal NOT NULL, + [PriorYearActualValue04] decimal NOT NULL, + [PriorYearActualValue05] decimal NOT NULL, + [PriorYearActualValue06] decimal NOT NULL, + [PriorYearActualValue07] decimal NOT NULL, + [PriorYearActualValue08] decimal NOT NULL, + [PriorYearActualValue09] decimal NOT NULL, + [PriorYearActualValue10] decimal NOT NULL, + [PriorYearActualValue11] decimal NOT NULL, + [PriorYearActualValue12] decimal NOT NULL, + [ActualYTDValue01] decimal NOT NULL, + [ActualYTDValue02] decimal NOT NULL, + [ActualYTDValue03] decimal NOT NULL, + [ActualYTDValue04] decimal NOT NULL, + [ActualYTDValue05] decimal NOT NULL, + [ActualYTDValue06] decimal NOT NULL, + [ActualYTDValue07] decimal NOT NULL, + [ActualYTDValue08] decimal NOT NULL, + [ActualYTDValue09] decimal NOT NULL, + [ActualYTDValue10] decimal NOT NULL, + [ActualYTDValue11] decimal NOT NULL, + [ActualYTDValue12] decimal NOT NULL, + [CurrentYearBudget01] decimal NOT NULL, + [CurrentYearBudget02] decimal NOT NULL, + [CurrentYearBudget03] decimal NOT NULL, + [CurrentYearBudget04] decimal NOT NULL, + [CurrentYearBudget05] decimal NOT NULL, + [CurrentYearBudget06] decimal NOT NULL, + [CurrentYearBudget07] decimal NOT NULL, + [CurrentYearBudget08] decimal NOT NULL, + [CurrentYearBudget09] decimal NOT NULL, + [CurrentYearBudget10] decimal NOT NULL, + [CurrentYearBudget11] decimal NOT NULL, + [CurrentYearBudget12] decimal NOT NULL, + [PriorYearActualValueTotal] decimal NOT NULL, + [ActualYTDValueTotal] decimal NOT NULL, + [CurrentYearBudgetTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [FK_ArchiveFactStatisticsHistory_StatisticsID] FOREIGN KEY ([StatisticsID]) REFERENCES [fp].[ArchiveFactStatistics] ([StatisticsID]); GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Stati__50B47829] DEFAULT ((0)) FOR [StatisticsID]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__51A89C62] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__529CC09B] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5390E4D4] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5485090D] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__55792D46] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__566D517F] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__576175B8] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__585599F1] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5949BE2A] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5A3DE263] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5B32069C] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Prior__5C262AD5] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__5D1A4F0E] DEFAULT ((0)) FOR [ActualYTDValue01]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__5E0E7347] DEFAULT ((0)) FOR [ActualYTDValue02]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__5F029780] DEFAULT ((0)) FOR [ActualYTDValue03]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__5FF6BBB9] DEFAULT ((0)) FOR [ActualYTDValue04]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__60EADFF2] DEFAULT ((0)) FOR [ActualYTDValue05]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__61DF042B] DEFAULT ((0)) FOR [ActualYTDValue06]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__62D32864] DEFAULT ((0)) FOR [ActualYTDValue07]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__63C74C9D] DEFAULT ((0)) FOR [ActualYTDValue08]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__64BB70D6] DEFAULT ((0)) FOR [ActualYTDValue09]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__65AF950F] DEFAULT ((0)) FOR [ActualYTDValue10]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__66A3B948] DEFAULT ((0)) FOR [ActualYTDValue11]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Actua__6797DD81] DEFAULT ((0)) FOR [ActualYTDValue12]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__688C01BA] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__698025F3] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6A744A2C] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6B686E65] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6C5C929E] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6D50B6D7] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6E44DB10] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__6F38FF49] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__702D2382] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__712147BB] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__72156BF4] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsHistory] ADD CONSTRAINT [DF__ArchiveFa__Curre__7309902D] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveFactStatisticsProjection ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveFactStatisticsProjection] ( + [RowID] int NOT NULL, + [StatisticsID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedValue01] decimal NOT NULL, + [AdjustedValue02] decimal NOT NULL, + [AdjustedValue03] decimal NOT NULL, + [AdjustedValue04] decimal NOT NULL, + [AdjustedValue05] decimal NOT NULL, + [AdjustedValue06] decimal NOT NULL, + [AdjustedValue07] decimal NOT NULL, + [AdjustedValue08] decimal NOT NULL, + [AdjustedValue09] decimal NOT NULL, + [AdjustedValue10] decimal NOT NULL, + [AdjustedValue11] decimal NOT NULL, + [AdjustedValue12] decimal NOT NULL, + [AdjustedValueTotal] decimal NULL, + [FlexedValue01] decimal NOT NULL, + [FlexedValue02] decimal NOT NULL, + [FlexedValue03] decimal NOT NULL, + [FlexedValue04] decimal NOT NULL, + [FlexedValue05] decimal NOT NULL, + [FlexedValue06] decimal NOT NULL, + [FlexedValue07] decimal NOT NULL, + [FlexedValue08] decimal NOT NULL, + [FlexedValue09] decimal NOT NULL, + [FlexedValue10] decimal NOT NULL, + [FlexedValue11] decimal NOT NULL, + [FlexedValue12] decimal NOT NULL, + [FlexedValueTotal] decimal NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [FK_ArchiveFactStatisticsProjection_StatisticsID] FOREIGN KEY ([StatisticsID]) REFERENCES [fp].[ArchiveFactStatistics] ([StatisticsID]); GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Stati__2B223570] DEFAULT ((0)) FOR [StatisticsID]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__LockT__2C1659A9] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__LockF__2D0A7DE2] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Budge__2DFEA21B] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2EF2C654] DEFAULT ((0)) FOR [AdjustedValue01]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__2FE6EA8D] DEFAULT ((0)) FOR [AdjustedValue02]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__30DB0EC6] DEFAULT ((0)) FOR [AdjustedValue03]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__31CF32FF] DEFAULT ((0)) FOR [AdjustedValue04]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__32C35738] DEFAULT ((0)) FOR [AdjustedValue05]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__33B77B71] DEFAULT ((0)) FOR [AdjustedValue06]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__34AB9FAA] DEFAULT ((0)) FOR [AdjustedValue07]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__359FC3E3] DEFAULT ((0)) FOR [AdjustedValue08]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__3693E81C] DEFAULT ((0)) FOR [AdjustedValue09]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__37880C55] DEFAULT ((0)) FOR [AdjustedValue10]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__387C308E] DEFAULT ((0)) FOR [AdjustedValue11]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Adjus__397054C7] DEFAULT ((0)) FOR [AdjustedValue12]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3A647900] DEFAULT ((0)) FOR [FlexedValue01]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3B589D39] DEFAULT ((0)) FOR [FlexedValue02]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3C4CC172] DEFAULT ((0)) FOR [FlexedValue03]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3D40E5AB] DEFAULT ((0)) FOR [FlexedValue04]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3E3509E4] DEFAULT ((0)) FOR [FlexedValue05]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__3F292E1D] DEFAULT ((0)) FOR [FlexedValue06]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__401D5256] DEFAULT ((0)) FOR [FlexedValue07]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__4111768F] DEFAULT ((0)) FOR [FlexedValue08]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__42059AC8] DEFAULT ((0)) FOR [FlexedValue09]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__42F9BF01] DEFAULT ((0)) FOR [FlexedValue10]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__43EDE33A] DEFAULT ((0)) FOR [FlexedValue11]; GO +ALTER TABLE [fp].[ArchiveFactStatisticsProjection] ADD CONSTRAINT [DF__ArchiveFa__Flexe__44E20773] DEFAULT ((0)) FOR [FlexedValue12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveGeneralLedgerChangeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ( + [RowID] bigint NOT NULL, + [GeneralLedgerID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [SortOrder] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [OldValue] decimal NOT NULL, + [NewValue] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [FK_ArchiveGeneralLedgerChangeHistory_GeneralLedgerID] FOREIGN KEY ([GeneralLedgerID]) REFERENCES [fp].[ArchiveFactGeneralLedger] ([GeneralLedgerID]); GO +ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__Gener__2C420D89] DEFAULT ((0)) FOR [GeneralLedgerID]; GO +ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__Adjus__2D3631C2] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__Group__2E2A55FB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__Adjus__2F1E7A34] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__SortO__30129E6D] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__Fisca__3106C2A6] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__UnitT__31FAE6DF] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__TimeC__32EF0B18] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__Budge__33E32F51] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__OldVa__34D7538A] DEFAULT ((0)) FOR [OldValue]; GO +ALTER TABLE [fp].[ArchiveGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__ArchiveGe__NewVa__35CB77C3] DEFAULT ((0)) FOR [NewValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveServiceLineEncounterChangeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ( + [RowID] bigint NOT NULL, + [ServiceLineEncounterID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [SortOrder] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [OldValue] decimal NOT NULL, + [NewValue] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_ArchiveServiceLineEncounterChangeHistory] ON [fp].[ArchiveServiceLineEncounterChangeHistory] ([ServiceLineEncounterID]); +CREATE NONCLUSTERED INDEX [IX_ArchiveServiceLineEncounterChangeHistory_AdjustmentGuid] ON [fp].[ArchiveServiceLineEncounterChangeHistory] ([AdjustmentGUID]) INCLUDE ([ServiceLineEncounterID], [SortOrder], [FiscalMonthID], [UnitTypeID], [TimeClassID], [BudgetPhaseID]); +GO +ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [FK_ArchiveServiceLineEncounterChangeHistory_ServiceLineEncounterID] FOREIGN KEY ([ServiceLineEncounterID]) REFERENCES [fp].[ArchiveFactServiceLineEncounter] ([ServiceLineEncounterID]); GO +ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__Servi__0BA42C80] DEFAULT ((0)) FOR [ServiceLineEncounterID]; GO +ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__Adjus__0C9850B9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__Group__0D8C74F2] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__Adjus__0E80992B] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__SortO__0F74BD64] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__Fisca__1068E19D] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__UnitT__115D05D6] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__TimeC__12512A0F] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__Budge__13454E48] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__OldVa__14397281] DEFAULT ((0)) FOR [OldValue]; GO +ALTER TABLE [fp].[ArchiveServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ArchiveSe__NewVa__152D96BA] DEFAULT ((0)) FOR [NewValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveStaffingChangeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveStaffingChangeHistory] ( + [RowID] bigint NOT NULL, + [StaffingID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [SortOrder] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [OldValue] decimal NOT NULL, + [NewValue] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [FK_ArchiveStaffingChangeHistory_StaffingID] FOREIGN KEY ([StaffingID]) REFERENCES [fp].[ArchiveFactStaffing] ([StaffingID]); GO +ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Staff__38A7E46E] DEFAULT ((0)) FOR [StaffingID]; GO +ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Adjus__399C08A7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Group__3A902CE0] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Adjus__3B845119] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__SortO__3C787552] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Fisca__3D6C998B] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__UnitT__3E60BDC4] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__TimeC__3F54E1FD] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Budge__40490636] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__OldVa__413D2A6F] DEFAULT ((0)) FOR [OldValue]; GO +ALTER TABLE [fp].[ArchiveStaffingChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__NewVa__42314EA8] DEFAULT ((0)) FOR [NewValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ArchiveStatisticsChangeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ArchiveStatisticsChangeHistory] ( + [RowID] bigint NOT NULL, + [StatisticsID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [SortOrder] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [OldValue] decimal NOT NULL, + [NewValue] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [FK_ArchiveStatisticsChangeHistory_StatisticsID] FOREIGN KEY ([StatisticsID]) REFERENCES [fp].[ArchiveFactStatistics] ([StatisticsID]); GO +ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Stati__450DBB53] DEFAULT ((0)) FOR [StatisticsID]; GO +ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Adjus__4601DF8C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Group__46F603C5] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Adjus__47EA27FE] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__SortO__48DE4C37] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Fisca__49D27070] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__UnitT__4AC694A9] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__TimeC__4BBAB8E2] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__Budge__4CAEDD1B] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__OldVa__4DA30154] DEFAULT ((0)) FOR [OldValue]; GO +ALTER TABLE [fp].[ArchiveStatisticsChangeHistory] ADD CONSTRAINT [DF__ArchiveSt__NewVa__4E97258D] DEFAULT ((0)) FOR [NewValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.BenefitsAdjustment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[BenefitsAdjustment] ( + [AdjustmentGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [Value] decimal NOT NULL, + [AdjustmentFilterJSON] nvarchar(max) NOT NULL, + [GroupingHierarchyJSON] nvarchar(max) NOT NULL, + [AdjustedProperty] nvarchar(100) NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [ClassificationGroupID] int NOT NULL, + [ClassificationCategoryID] int NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + [LastModifiedDateUtc] datetime NOT NULL, + [DimensionMemberJson] nvarchar(max) NOT NULL, + [AdjustmentID] int NOT NULL, + [IsErrored] bit NOT NULL, + PRIMARY KEY ([AdjustmentGUID]) +); +GO +ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [FK__BenefitsA__Budge__3B5DFAD0] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF_BenefitsAdjustment_ClassificationGroupID] DEFAULT ((0)) FOR [ClassificationGroupID]; GO +ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF_BenefitsAdjustment_ClassificationCategoryID] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO +ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__Adjus__15DFFB59] DEFAULT (newid()) FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__Adjus__16D41F92] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__Value__17C843CB] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__Adjus__18BC6804] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO +ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__Group__19B08C3D] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO +ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__Adjus__1AA4B076] DEFAULT ('') FOR [AdjustedProperty]; GO +ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__Comme__1B98D4AF] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__Autho__1C8CF8E8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__Autho__1D811D21] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__Group__6F503E1D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__Benefits__UnitTypeID] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__BenefitsA__IsErr__4BED92D1] DEFAULT ((0)) FOR [IsErrored]; GO +ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__BenefitsA__Dimen__64D60ED0] DEFAULT ('') FOR [DimensionMemberJson]; GO +ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__BenefitsA__DateC__6634475D] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__BenefitsA__LastM__67286B96] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO +ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF_BenefitsAdjustment_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF__BenefitsA__IsRec__6CCB6AFC] DEFAULT ((0)) FOR [IsRecordDeleted]; GO +ALTER TABLE [fp].[BenefitsAdjustment] ADD CONSTRAINT [DF_BenefitsAdjustment_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.BenefitsAdjustmentImport ------------------ +--------------------------------------------- +CREATE TABLE [fp].[BenefitsAdjustmentImport] ( + [RowID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [EntityID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [Value] decimal NOT NULL, + [Version] timestamp NOT NULL, + [TimeClassID] tinyint NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [AdjustmentID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_AdjustmentID] ON [fp].[BenefitsAdjustmentImport] ([AdjustmentID]); +GO +ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF__BenefitsA__Adjus__22BE32B0] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF__BenefitsA__Adjus__3B7DF661] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF__BenefitsAdjImport__Depar__2B6F7FBE] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF__BenefitsAdjImport__AccountID__2D57C830] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF__BenefitsAdjImport__FinancialReportingID__2D57C830] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF__BenefitsAdjImport__Fisca__31285914] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF__BenefitsAdjImport__UnitT__34F8E9F8] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF__BenefitsAdjImport__Fisca__3CCC1A58] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF_INTBenefitsAdjImport_VALUE] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF__BenefitsA__Entit__431F1829] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF_BenefitsAdjustmentImport_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[BenefitsAdjustmentImport] ADD CONSTRAINT [DF__BenefitsA__IsRec__71902019] DEFAULT ((0)) FOR [IsRecordDeleted]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.BenefitsAdjustment_backup ------------------ +--------------------------------------------- +CREATE TABLE [fp].[BenefitsAdjustment_backup] ( + [AdjustmentGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [Value] decimal NOT NULL, + [AdjustmentFilterJSON] nvarchar(max) NOT NULL, + [GroupingHierarchyJSON] nvarchar(max) NOT NULL, + [AdjustedProperty] nvarchar(100) NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [LastModifiedDate] datetime NOT NULL, + [DateCreatedUTC] datetime NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + PRIMARY KEY ([AdjustmentGUID]) +); +GO +ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [FK__BenefitsA__Budge__4D7CAB0B] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__Adjus__4E70CF44] DEFAULT (newid()) FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__Adjus__4F64F37D] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__Value__505917B6] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__Adjus__514D3BEF] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO +ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__Group__52416028] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO +ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__Adjus__53358461] DEFAULT ('') FOR [AdjustedProperty]; GO +ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__Comme__5429A89A] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__Autho__551DCCD3] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__Autho__5611F10C] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__LastM__57061545] DEFAULT (getdate()) FOR [LastModifiedDate]; GO +ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__DateC__57FA397E] DEFAULT (getdate()) FOR [DateCreatedUTC]; GO +ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__Group__58EE5DB7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF__BenefitsA__UnitT__59E281F0] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[BenefitsAdjustment_backup] ADD CONSTRAINT [DF_BenefitsAdjustmentBackup_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.BenefitsChangeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[BenefitsChangeHistory] ( + [RowID] bigint NOT NULL, + [BenefitsID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [OldValue] decimal NOT NULL, + [NewValue] decimal NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [BudgetConfigID] int NOT NULL, + [DateCreatedUTC] datetime2 NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_BenefitsChangeHistory] ON [fp].[BenefitsChangeHistory] ([BenefitsID]); +GO +ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [FK_BenefitsChangeHistory_BenefitsID] FOREIGN KEY ([BenefitsID]) REFERENCES [fp].[FactBenefits] ([BenefitsID]); GO +ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__DateC__05C2014F] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO +ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__Group__07F2CBD6] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__Benef__40B24F33] DEFAULT ((0)) FOR [BenefitsID]; GO +ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__Adjus__41A6736C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__Adjus__429A97A5] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__Fisca__4482E017] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__UnitT__45770450] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__TimeC__466B2889] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__Budge__475F4CC2] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__OldVa__485370FB] DEFAULT ((0)) FOR [OldValue]; GO +ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__NewVa__49479534] DEFAULT ((0)) FOR [NewValue]; GO +ALTER TABLE [fp].[BenefitsChangeHistory] ADD CONSTRAINT [DF__BenefitsC__Budge__60FA90F4] DEFAULT ((0)) FOR [BudgetConfigID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.BenefitsSpreadUnlockData ------------------ +--------------------------------------------- +CREATE TABLE [fp].[BenefitsSpreadUnlockData] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [Version] timestamp NOT NULL, + [Value01] decimal NOT NULL, + [Value02] decimal NOT NULL, + [Value03] decimal NOT NULL, + [Value04] decimal NOT NULL, + [Value05] decimal NOT NULL, + [Value06] decimal NOT NULL, + [Value07] decimal NOT NULL, + [Value08] decimal NOT NULL, + [Value09] decimal NOT NULL, + [Value10] decimal NOT NULL, + [Value11] decimal NOT NULL, + [Value12] decimal NOT NULL, + [IsRecordDeleted] bit NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Budge__2E0E531D] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Entit__2FF69B8F] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Depar__30EABFC8] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Accou__31DEE401] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Finan__32D3083A] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__33C72C73] DEFAULT ((0)) FOR [Value01]; GO +ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__34BB50AC] DEFAULT ((0)) FOR [Value02]; GO +ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__35AF74E5] DEFAULT ((0)) FOR [Value03]; GO +ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__36A3991E] DEFAULT ((0)) FOR [Value04]; GO +ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__3797BD57] DEFAULT ((0)) FOR [Value05]; GO +ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__388BE190] DEFAULT ((0)) FOR [Value06]; GO +ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__398005C9] DEFAULT ((0)) FOR [Value07]; GO +ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__3A742A02] DEFAULT ((0)) FOR [Value08]; GO +ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__3B684E3B] DEFAULT ((0)) FOR [Value09]; GO +ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__3C5C7274] DEFAULT ((0)) FOR [Value10]; GO +ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__3D5096AD] DEFAULT ((0)) FOR [Value11]; GO +ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__Value__3E44BAE6] DEFAULT ((0)) FOR [Value12]; GO +ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [df_BenefitsSpreadUnlockData_AdjustmentGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[BenefitsSpreadUnlockData] ADD CONSTRAINT [DF__BenefitsS__IsRec__7FDE3F70] DEFAULT ((0)) FOR [IsRecordDeleted]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.BenefitsSpreads ------------------ +--------------------------------------------- +CREATE TABLE [fp].[BenefitsSpreads] ( + [BudgetConfigID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [IsInactive] bit NOT NULL, + [SpreadPercentage01] decimal NULL, + [SpreadPercentage02] decimal NULL, + [SpreadPercentage03] decimal NULL, + [SpreadPercentage04] decimal NULL, + [SpreadPercentage05] decimal NULL, + [SpreadPercentage06] decimal NULL, + [SpreadPercentage07] decimal NULL, + [SpreadPercentage08] decimal NULL, + [SpreadPercentage09] decimal NULL, + [SpreadPercentage10] decimal NULL, + [SpreadPercentage11] decimal NULL, + [SpreadPercentage12] decimal NULL, + [TotalImportedValue] decimal NULL, + [SpreadHistoryGUID] uniqueidentifier NOT NULL, + [GlobalSpreadID] int NOT NULL, + PRIMARY KEY ([BudgetConfigID], [DepartmentID], [AccountID]) +); +GO +ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [FK_FpBenefitsSpreads_History] FOREIGN KEY ([SpreadHistoryGUID]) REFERENCES [fp].[SpreadHistory] ([SpreadHistoryGUID]); GO +ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [df_BenefitsSpreads_SpreadHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SpreadHistoryGUID]; GO +ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Budge__36D8A348] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Depar__37CCC781] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Accou__38C0EBBA] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__IsIna__39B50FF3] DEFAULT ((0)) FOR [IsInactive]; GO +ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__3AA9342C] DEFAULT ((0)) FOR [SpreadPercentage01]; GO +ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__3B9D5865] DEFAULT ((0)) FOR [SpreadPercentage02]; GO +ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__3C917C9E] DEFAULT ((0)) FOR [SpreadPercentage03]; GO +ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__3D85A0D7] DEFAULT ((0)) FOR [SpreadPercentage04]; GO +ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__3E79C510] DEFAULT ((0)) FOR [SpreadPercentage05]; GO +ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__3F6DE949] DEFAULT ((0)) FOR [SpreadPercentage06]; GO +ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__40620D82] DEFAULT ((0)) FOR [SpreadPercentage07]; GO +ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__415631BB] DEFAULT ((0)) FOR [SpreadPercentage08]; GO +ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__424A55F4] DEFAULT ((0)) FOR [SpreadPercentage09]; GO +ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__433E7A2D] DEFAULT ((0)) FOR [SpreadPercentage10]; GO +ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__44329E66] DEFAULT ((0)) FOR [SpreadPercentage11]; GO +ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Sprea__4526C29F] DEFAULT ((0)) FOR [SpreadPercentage12]; GO +ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Total__461AE6D8] DEFAULT ((0)) FOR [TotalImportedValue]; GO +ALTER TABLE [fp].[BenefitsSpreads] ADD CONSTRAINT [DF__BenefitsS__Globa__48032F4A] DEFAULT ((1)) FOR [GlobalSpreadID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.BudgetAction ------------------ +--------------------------------------------- +CREATE TABLE [fp].[BudgetAction] ( + [ActionID] int NOT NULL, + [Name] nvarchar(max) NOT NULL, + [IsActive] bit NOT NULL, + [IsConfigurationAction] bit NOT NULL, + [IsReportAction] bit NOT NULL, + PRIMARY KEY ([ActionID]) +); +GO +ALTER TABLE [fp].[BudgetAction] ADD CONSTRAINT [DF__BudgetAct__Actio__68A901B9] DEFAULT ((0)) FOR [ActionID]; GO +ALTER TABLE [fp].[BudgetAction] ADD CONSTRAINT [DF__BudgetActi__Name__699D25F2] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fp].[BudgetAction] ADD CONSTRAINT [DF__BudgetAct__IsAct__6A914A2B] DEFAULT ((1)) FOR [IsActive]; GO +ALTER TABLE [fp].[BudgetAction] ADD CONSTRAINT [DF__BudgetAct__IsCon__6B856E64] DEFAULT ((0)) FOR [IsConfigurationAction]; GO +ALTER TABLE [fp].[BudgetAction] ADD CONSTRAINT [DF__BudgetAct__IsRep__6C79929D] DEFAULT ((0)) FOR [IsReportAction]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.BudgetConfig ------------------ +--------------------------------------------- +CREATE TABLE [fp].[BudgetConfig] ( + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [FiscalYearID] smallint NOT NULL, + [BudgetConfigID] smallint NOT NULL, + [ChargeMasterConfigJson] varchar(max) NOT NULL, + [DateModified] smalldatetime NOT NULL, + [DatePublished] smalldatetime NOT NULL, + [BudgetConfigName] nvarchar(100) NOT NULL, + [IsActive] bit NOT NULL, + [Comments] nvarchar(2000) NOT NULL, + [IsOverUnderFundedUsed] bit NOT NULL, + [IsFTEHidden] bit NOT NULL, + [IsProjectionHidden] bit NOT NULL, + [IsArchived] bit NOT NULL, + [IsProjectCurrentYear] bit NOT NULL, + [IsMRTracking] bit NOT NULL, + [ParentBudgetConfigID] smallint NOT NULL, + [MonthsLoaded] tinyint NOT NULL, + [CurrentBudgetPhaseID] tinyint NOT NULL, + [AdjustmentClassificationSetting] tinyint NOT NULL, + [IsEngineDisabled] bit NOT NULL, + [UseDSForSampling] bit NOT NULL, + [IsGLBudgetHistoryAvailable] bit NOT NULL, + [IsStaffingBudgetHistoryAvailable] bit NOT NULL, + [IsTempoNonStaffingPageAvailable] bit NOT NULL, + [IsAdjustmentClassificationEnabled] bit NOT NULL, + [IsRestrictDepartmentAccess] bit NOT NULL, + [IsChargeMasterRefreshedForDollarImpactReport] bit NOT NULL, + [DefaultReimbursementProjectionMethodID] int NOT NULL, + [IsProviderVolumesEnabled] bit NOT NULL, + [IsTempoOtherRevenuePageAvailable] bit NOT NULL, + [UseEmployeePlanning] bit NOT NULL, + [IsUsingSystemGeneratedHistoricalStats] bit NOT NULL, + [IsSubAccountCategoriesEnabled] bit NOT NULL, + [AreStatisticsAccountsEnabled] bit NOT NULL, + [IsProviderCompensationEnabled] bit NOT NULL, + [DisplayCategoryInMyBudgets] bit NOT NULL, + [IsLocalAdminReadOnly] bit NOT NULL, + [IsTargetingEmailEnabled] bit NOT NULL, + [AllowLocalAdminAddEmpAddFTEPlanEditor] bit NOT NULL, + [AllowLocalAdminAddEmpAddJobCodeMyBudgets] bit NOT NULL, + [AllowLocalAdminAddAccountPlanEditor] bit NOT NULL, + [AllowLocalAdminAddAccountMyBudgets] bit NOT NULL, + [IsBudgetClosed] bit NOT NULL, + [IsStatisticsBudgetHistoryAvailable] bit NOT NULL, + [IsImpactReportsEnabled] bit NOT NULL, + [DefaultReimbursementNetRevenueModelID] int NOT NULL, + [IsProviderPlanningEnabled] bit NOT NULL, + [IsUsedForReportComparison] bit NOT NULL, + [UseProviderSource] bit NOT NULL, + [IsProjectionLockedOnMyBudget] bit NOT NULL, + [IsBudgetLockedOnMyBudget] bit NOT NULL, + [EnableExceptionActionItems] bit NOT NULL, + [IsWorkWeekOverrideCheckIgnored] bit NOT NULL, + PRIMARY KEY ([BudgetConfigGUID]) +); + +CREATE NONCLUSTERED INDEX [NCNU_BudgetConfig_BudgetConfigID] ON [fp].[BudgetConfig] ([BudgetConfigID]); +CREATE NONCLUSTERED INDEX [NCNU_BudgetConfig_FiscalYearID] ON [fp].[BudgetConfig] ([FiscalYearID]); +GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsMRT__07C7E34D] DEFAULT ((0)) FOR [IsMRTracking]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF_BudgetConfig_IsUsingSystemGeneratedHistoricalStats] DEFAULT ((0)) FOR [IsUsingSystemGeneratedHistoricalStats]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Paren__08BC0786] DEFAULT ((0)) FOR [ParentBudgetConfigID]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Budge__09245362] DEFAULT (newid()) FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Fisca__0A18779B] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF_IsAdjustmentClassificationEnabled] DEFAULT ((0)) FOR [IsAdjustmentClassificationEnabled]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF_BudgetConfigComment] DEFAULT ('') FOR [Comments]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsPro__0FB02246] DEFAULT ((0)) FOR [IsProviderPlanningEnabled]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Allow__100DB2F4] DEFAULT ((1)) FOR [AllowLocalAdminAddEmpAddFTEPlanEditor]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF_IsRestrictDepartmentAccess] DEFAULT ((1)) FOR [IsRestrictDepartmentAccess]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsSta__13C79E91] DEFAULT ((0)) FOR [IsProviderVolumesEnabled]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Defau__1F918454] DEFAULT ((0)) FOR [DefaultReimbursementNetRevenueModelID]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__DateM__1F9F3B14] DEFAULT (getdate()) FOR [DateModified]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__DateP__20935F4D] DEFAULT (getdate()) FOR [DatePublished]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsGLB__20F51A78] DEFAULT ((1)) FOR [IsGLBudgetHistoryAvailable]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Budge__21878386] DEFAULT ('Default Budget') FOR [BudgetConfigName]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsSta__21E93EB1] DEFAULT ((1)) FOR [IsStaffingBudgetHistoryAvailable]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsAct__227BA7BF] DEFAULT ((0)) FOR [IsActive]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Adjus__2563FE83] DEFAULT ((0)) FOR [AdjustmentClassificationSetting]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsBud__26A6FF89] DEFAULT ((0)) FOR [IsBudgetClosed]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Charg__2967D119] DEFAULT ('') FOR [ChargeMasterConfigJson]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsSub__2B6AE94F] DEFAULT ((0)) FOR [IsSubAccountCategoriesEnabled]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsFTE__2B9BC8FC] DEFAULT ((0)) FOR [IsFTEHidden]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsPro__2C8FED35] DEFAULT ((0)) FOR [IsProjectionHidden]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsUse__334FFAEC] DEFAULT ((0)) FOR [IsUsedForReportComparison]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF_BudgetConfig_IsProjectCurrentYear] DEFAULT ((0)) FOR [IsProjectCurrentYear]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsPro__3A55F6E9] DEFAULT ((0)) FOR [IsProjectionLockedOnMyBudget]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsBud__3B4A1B22] DEFAULT ((0)) FOR [IsBudgetLockedOnMyBudget]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Allow__3CE0596B] DEFAULT ((1)) FOR [AllowLocalAdminAddEmpAddJobCodeMyBudgets]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsSta__46DEC4F1] DEFAULT ((0)) FOR [IsStatisticsBudgetHistoryAvailable]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Defau__47274706] DEFAULT ((1)) FOR [DefaultReimbursementProjectionMethodID]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsTem__49B99AEE] DEFAULT ((0)) FOR [IsTempoOtherRevenuePageAvailable]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__UseDS__4D08A6E0] DEFAULT ((0)) FOR [UseDSForSampling]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__UsePr__4DB2E420] DEFAULT ((0)) FOR [UseProviderSource]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__UseEm__55962D45] DEFAULT ((0)) FOR [UseEmployeePlanning]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsTem__561EA67C] DEFAULT ((0)) FOR [IsTempoNonStaffingPageAvailable]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsCha__5826EA7F] DEFAULT ((1)) FOR [IsChargeMasterRefreshedForDollarImpactReport]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Enabl__5DF50438] DEFAULT ((0)) FOR [EnableExceptionActionItems]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Curre__5FDAB8DB] DEFAULT ((2)) FOR [CurrentBudgetPhaseID]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Month__64699877] DEFAULT ((0)) FOR [MonthsLoaded]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsOve__693908C2] DEFAULT ((1)) FOR [IsOverUnderFundedUsed]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF_BudgetConfig_IsArchived] DEFAULT ((0)) FOR [IsArchived]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF_BudgetConfig_AreStatisticsAccountsEnabled] DEFAULT ((0)) FOR [AreStatisticsAccountsEnabled]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Allow__724845E3] DEFAULT ((1)) FOR [AllowLocalAdminAddAccountPlanEditor]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__Allow__733C6A1C] DEFAULT ((1)) FOR [AllowLocalAdminAddAccountMyBudgets]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsImp__74C58B32] DEFAULT ((0)) FOR [IsImpactReportsEnabled]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsTar__7559BCB8] DEFAULT ((1)) FOR [IsTargetingEmailEnabled]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsEng__773E0C77] DEFAULT ((0)) FOR [IsEngineDisabled]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF_BudgetConfig_IsLocalAdminReadOnly] DEFAULT ((0)) FOR [IsLocalAdminReadOnly]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF_BudgetConfig_IsProviderCompensationEnabled] DEFAULT ((0)) FOR [IsProviderCompensationEnabled]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF__BudgetCon__IsWor__7C798B58] DEFAULT ((0)) FOR [IsWorkWeekOverrideCheckIgnored]; GO +ALTER TABLE [fp].[BudgetConfig] ADD CONSTRAINT [DF_BudgetConfig_DisplayCategoryInMyBudgets] DEFAULT ((0)) FOR [DisplayCategoryInMyBudgets]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.BudgetConfigDefaultHoursMix ------------------ +--------------------------------------------- +CREATE TABLE [fp].[BudgetConfigDefaultHoursMix] ( + [BudgetConfigHoursMixGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [PayCodeGroupID] int NOT NULL, + [HoursMix] decimal NOT NULL, + PRIMARY KEY ([BudgetConfigHoursMixGUID]) +); +GO +ALTER TABLE [fp].[BudgetConfigDefaultHoursMix] ADD CONSTRAINT [FK__BudgetCon__Budge__774665A0] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[BudgetConfigDefaultHoursMix] ADD CONSTRAINT [FK__BudgetCon__PayCo__783A89D9] FOREIGN KEY ([PayCodeGroupID]) REFERENCES [fw].[DimPayCodeGroup] ([PayCodeGroupID]); GO +ALTER TABLE [fp].[BudgetConfigDefaultHoursMix] ADD CONSTRAINT [DF__BudgetCon__Hours__35439819] DEFAULT ((0)) FOR [HoursMix]; GO +ALTER TABLE [fp].[BudgetConfigDefaultHoursMix] ADD CONSTRAINT [DF__BudgetCon__Budge__76524167] DEFAULT (newid()) FOR [BudgetConfigHoursMixGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.BudgetConfigDefaultSetting ------------------ +--------------------------------------------- +CREATE TABLE [fp].[BudgetConfigDefaultSetting] ( + [SettingID] int NOT NULL, + [Name] nvarchar(max) NOT NULL, + [Description] nvarchar(max) NOT NULL, + [DefaultValue] bit NOT NULL, + [DateCreated] date NOT NULL, + PRIMARY KEY ([SettingID]) +); +GO +ALTER TABLE [fp].[BudgetConfigDefaultSetting] ADD CONSTRAINT [DF__BudgetCon__DateC__027F7903] DEFAULT (getdate()) FOR [DateCreated]; GO +ALTER TABLE [fp].[BudgetConfigDefaultSetting] ADD CONSTRAINT [DF__BudgetConf__Name__3626D836] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fp].[BudgetConfigDefaultSetting] ADD CONSTRAINT [DF__BudgetCon__Descr__371AFC6F] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fp].[BudgetConfigDefaultSetting] ADD CONSTRAINT [DF__BudgetCon__Defau__380F20A8] DEFAULT ((1)) FOR [DefaultValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.BudgetConfigSetting ------------------ +--------------------------------------------- +CREATE TABLE [fp].[BudgetConfigSetting] ( + [BudgetConfigID] int NOT NULL, + [SettingID] int NOT NULL, + [Value] bit NOT NULL +); +GO +ALTER TABLE [fp].[BudgetConfigSetting] ADD CONSTRAINT [FK__BudgetCon__Setti__3CD3D5C5] FOREIGN KEY ([SettingID]) REFERENCES [fp].[BudgetConfigDefaultSetting] ([SettingID]); GO +ALTER TABLE [fp].[BudgetConfigSetting] ADD CONSTRAINT [DF__BudgetCon__Budge__39F7691A] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[BudgetConfigSetting] ADD CONSTRAINT [DF__BudgetCon__Setti__3AEB8D53] DEFAULT ((0)) FOR [SettingID]; GO +ALTER TABLE [fp].[BudgetConfigSetting] ADD CONSTRAINT [DF__BudgetCon__Value__3BDFB18C] DEFAULT ((0)) FOR [Value]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.BudgetRefreshRequest ------------------ +--------------------------------------------- +CREATE TABLE [fp].[BudgetRefreshRequest] ( + [RequestGUID] uniqueidentifier NOT NULL, + [BudgetConfigID] smallint NOT NULL, + [DateTimeStamp] datetime NOT NULL, + [UserName] nvarchar(64) NOT NULL, + [SourceDimensionalityJSON] nvarchar(max) NOT NULL, + [DateStarted] datetime NOT NULL, + [DateEnded] datetime NOT NULL, + [Status] tinyint NOT NULL, + [ErrorMessage] nvarchar(max) NOT NULL, + [StackTrace] nvarchar(max) NOT NULL, + [CurrentDataRefreshMethod] nvarchar(max) NOT NULL, + [SourceActionID] smallint NOT NULL, + [AffectedDepartments] nvarchar(max) NOT NULL, + [IsIgnoreTargetingError] bit NOT NULL, + [Source] nvarchar(100) NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [SamplingJSON] nvarchar(max) NOT NULL, + [EmailAddress] nvarchar(2000) NOT NULL, + [InitialSamplingJSON] nvarchar(max) NOT NULL, + [InitialSourceDimensionalityJSON] nvarchar(max) NOT NULL, + [DateTimeStampUTC] datetime NOT NULL, + [DateStartedUTC] datetime NOT NULL, + [DateEndedUTC] datetime NOT NULL, + [PlanSectionID] int NOT NULL, + PRIMARY KEY ([RequestGUID]) +); +GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__DateT__0CFC6DE9] DEFAULT (getutcdate()) FOR [DateTimeStampUTC]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__DateS__0DF09222] DEFAULT ('1900-01-01T00:00:00') FOR [DateStartedUTC]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Entit__0EC226FB] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__DateE__0EE4B65B] DEFAULT ('1900-01-01T00:00:00') FOR [DateEndedUTC]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Sampl__0FB64B34] DEFAULT ('') FOR [SamplingJSON]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__PlanS__1CA99124] DEFAULT ((0)) FOR [PlanSectionID]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Affec__20E896D2] DEFAULT ('') FOR [AffectedDepartments]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Sourc__2A746311] DEFAULT ('') FOR [Source]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__DateS__33185CF3] DEFAULT ('1900-01-01T00:00:00') FOR [DateStarted]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__DateE__340C812C] DEFAULT ('1900-01-01T00:00:00') FOR [DateEnded]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Statu__3500A565] DEFAULT ((0)) FOR [Status]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Error__35F4C99E] DEFAULT ('') FOR [ErrorMessage]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Stack__36E8EDD7] DEFAULT ('') FOR [StackTrace]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Curre__37DD1210] DEFAULT ('') FOR [CurrentDataRefreshMethod]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Initi__489C24DA] DEFAULT ('') FOR [InitialSourceDimensionalityJSON]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF_BudgetRefreshRequest_RequestGUID] DEFAULT (newid()) FOR [RequestGUID]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF_BudgetRefreshRequest_BudgetConfigID] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF_BudgetRefreshRequest_DateTimeStamp] DEFAULT (getdate()) FOR [DateTimeStamp]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF_BudgetRefreshRequest_UserName] DEFAULT ('') FOR [UserName]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__IsIgn__56F203CD] DEFAULT ((0)) FOR [IsIgnoreTargetingError]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF_BudgetRefreshRequest_SourceDimensionalityJSON] DEFAULT ('') FOR [SourceDimensionalityJSON]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Sourc__602AFA8C] DEFAULT ((0)) FOR [SourceActionID]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Email__6E61DB0F] DEFAULT ('') FOR [EmailAddress]; GO +ALTER TABLE [fp].[BudgetRefreshRequest] ADD CONSTRAINT [DF__BudgetRef__Initi__7425A15D] DEFAULT ('') FOR [InitialSamplingJSON]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.BudgetRefreshRequestHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[BudgetRefreshRequestHistory] ( + [RequestGUID] uniqueidentifier NOT NULL, + [BudgetConfigID] smallint NOT NULL, + [DateTimeStamp] datetime NOT NULL, + [UserName] nvarchar(64) NOT NULL, + [SourceDimensionalityJSON] nvarchar(max) NOT NULL, + [DateStarted] datetime NOT NULL, + [DateEnded] datetime NOT NULL, + [Status] tinyint NOT NULL, + [ErrorMessage] nvarchar(max) NULL, + [StackTrace] nvarchar(max) NULL, + [SourceActionID] smallint NOT NULL, + [AffectedDepartments] nvarchar(max) NOT NULL, + [CollapsedRequestGUID] uniqueidentifier NOT NULL, + [IsIgnoreTargetingError] bit NOT NULL, + [Source] nvarchar(100) NOT NULL, + [JazzVersion] nvarchar(100) NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [SamplingJSON] nvarchar(max) NOT NULL, + [InitialSamplingJSON] nvarchar(max) NOT NULL, + [InitialSourceDimensionalityJSON] nvarchar(max) NOT NULL, + [CanceledBy] nvarchar(max) NOT NULL, + [DateTimeStampUTC] datetime NOT NULL, + [DateStartedUTC] datetime NOT NULL, + [DateEndedUTC] datetime NOT NULL, + [AffectedDepartmentCount] int NOT NULL, + [PlanSectionID] int NOT NULL +); +GO +ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__DateT__0FD8DA94] DEFAULT (getutcdate()) FOR [DateTimeStampUTC]; GO +ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__Entit__10AA6F6D] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__DateS__10CCFECD] DEFAULT ('1900-01-01T00:00:00') FOR [DateStartedUTC]; GO +ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__Sampl__119E93A6] DEFAULT ('') FOR [SamplingJSON]; GO +ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__DateE__11C12306] DEFAULT ('1900-01-01T00:00:00') FOR [DateEndedUTC]; GO +ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__PlanS__1D9DB55D] DEFAULT ((0)) FOR [PlanSectionID]; GO +ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__Affec__22D0DF44] DEFAULT ('') FOR [AffectedDepartments]; GO +ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__Sourc__2B68874A] DEFAULT ('') FOR [Source]; GO +ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__Initi__49904913] DEFAULT ('') FOR [InitialSourceDimensionalityJSON]; GO +ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__JazzV__4DBD9F4E] DEFAULT ('') FOR [JazzVersion]; GO +ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__Affec__53AEE1F4] DEFAULT ((0)) FOR [AffectedDepartmentCount]; GO +ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__IsIgn__57E62806] DEFAULT ((0)) FOR [IsIgnoreTargetingError]; GO +ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__Sourc__611F1EC5] DEFAULT ((0)) FOR [SourceActionID]; GO +ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__Cance__6EE294AA] DEFAULT ('') FOR [CanceledBy]; GO +ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__Initi__7519C596] DEFAULT ('') FOR [InitialSamplingJSON]; GO +ALTER TABLE [fp].[BudgetRefreshRequestHistory] ADD CONSTRAINT [DF__BudgetRef__Colla__7D2102FF] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CollapsedRequestGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.BudgetSnapshot ------------------ +--------------------------------------------- +CREATE TABLE [fp].[BudgetSnapshot] ( + [SnapshotID] int NOT NULL, + [Name] nvarchar(100) NOT NULL, + [BudgetConfigID] int NOT NULL, + [PlanSectionID] int NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorName] nvarchar(300) NOT NULL, + [AdjustmentsStampedOff] int NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [DateCreatedUTC] datetime NOT NULL, + [DateProcessedUTC] datetime NOT NULL, + [DateInvalidatedUTC] datetime NOT NULL, + [IsValid] bit NOT NULL, + [IsAutoDeleteEnabled] bit NOT NULL, + [InvalidReason] nvarchar(1000) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([SnapshotID]) +); +GO +ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSnap__Name__22626A7A] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__Budge__23568EB3] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__PlanS__244AB2EC] DEFAULT ((0)) FOR [PlanSectionID]; GO +ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__Autho__253ED725] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__Autho__2632FB5E] DEFAULT ('') FOR [AuthorName]; GO +ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__Adjus__27271F97] DEFAULT ((0)) FOR [AdjustmentsStampedOff]; GO +ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__Comme__281B43D0] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__DateC__290F6809] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO +ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__DateP__2A038C42] DEFAULT ('1/1/2000') FOR [DateProcessedUTC]; GO +ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__DateI__2AF7B07B] DEFAULT ('1/1/2000') FOR [DateInvalidatedUTC]; GO +ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__IsVal__2BEBD4B4] DEFAULT ((1)) FOR [IsValid]; GO +ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__IsAut__2CDFF8ED] DEFAULT ((1)) FOR [IsAutoDeleteEnabled]; GO +ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__Inval__2DD41D26] DEFAULT ('') FOR [InvalidReason]; GO +ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__Membe__2EC8415F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MemberGUID]; GO +ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__Histo__2FBC6598] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fp].[BudgetSnapshot] ADD CONSTRAINT [DF__BudgetSna__Trans__30B089D1] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.BudgetSnapshotSchedule ------------------ +--------------------------------------------- +CREATE TABLE [fp].[BudgetSnapshotSchedule] ( + [BudgetConfigID] int NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [DateCreatedUTC] datetime NOT NULL, + [Frequency] int NOT NULL, + [Recurring] int NOT NULL, + [StartOn] int NOT NULL, + [DayOfWeek] int NOT NULL, + [StartDate] datetime NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorName] nvarchar(300) NOT NULL +); +GO +ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSna__Budge__2F525144] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSnap__Name__3046757D] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSna__Comme__313A99B6] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSna__DateC__322EBDEF] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO +ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSna__Frequ__3322E228] DEFAULT ((0)) FOR [Frequency]; GO +ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSna__Recur__34170661] DEFAULT ((0)) FOR [Recurring]; GO +ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSna__Start__350B2A9A] DEFAULT ((0)) FOR [StartOn]; GO +ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSna__DayOf__35FF4ED3] DEFAULT ((0)) FOR [DayOfWeek]; GO +ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSna__Start__36F3730C] DEFAULT (getutcdate()) FOR [StartDate]; GO +ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSna__Autho__37E79745] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[BudgetSnapshotSchedule] ADD CONSTRAINT [DF__BudgetSna__Autho__38DBBB7E] DEFAULT ('') FOR [AuthorName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.BudgetTimeClassSecurity ------------------ +--------------------------------------------- +CREATE TABLE [fp].[BudgetTimeClassSecurity] ( + [BudgetTimeClassSecurityGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [IsProjectionLocked] bit NOT NULL, + [IsTargetLocked] bit NOT NULL, + [IsBudgetLocked] bit NOT NULL, + [PlanSectionID] int NOT NULL, + [SubsectionID] int NOT NULL, + PRIMARY KEY ([BudgetTimeClassSecurityGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [UC_BudgetTimeClassSecurity_SectionInfo] ON [fp].[BudgetTimeClassSecurity] ([BudgetConfigGUID], [PlanSectionID], [SubsectionID]); +GO +ALTER TABLE [fp].[BudgetTimeClassSecurity] ADD CONSTRAINT [FK_BudgetTimeClassSecurity_BudgetConfigGUID] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[BudgetTimeClassSecurity] ADD CONSTRAINT [FK_SectionId] FOREIGN KEY ([PlanSectionID]) REFERENCES [fp].[PlanSection] ([PlanSectionID]); GO +ALTER TABLE [fp].[BudgetTimeClassSecurity] ADD CONSTRAINT [FK_SubsectionId] FOREIGN KEY ([SubsectionID]) REFERENCES [fp].[PlanSubsection] ([SubsectionID]); GO +ALTER TABLE [fp].[BudgetTimeClassSecurity] ADD CONSTRAINT [DF_SectionId] DEFAULT ((0)) FOR [PlanSectionID]; GO +ALTER TABLE [fp].[BudgetTimeClassSecurity] ADD CONSTRAINT [DF_SubsectionId] DEFAULT ((0)) FOR [SubsectionID]; GO +ALTER TABLE [fp].[BudgetTimeClassSecurity] ADD CONSTRAINT [DF__BudgetTim__Budge__32FF8771] DEFAULT (newid()) FOR [BudgetTimeClassSecurityGUID]; GO +ALTER TABLE [fp].[BudgetTimeClassSecurity] ADD CONSTRAINT [DF__BudgetTim__IsPro__34E7CFE3] DEFAULT ((0)) FOR [IsProjectionLocked]; GO +ALTER TABLE [fp].[BudgetTimeClassSecurity] ADD CONSTRAINT [DF__BudgetTim__IsTar__35DBF41C] DEFAULT ((0)) FOR [IsTargetLocked]; GO +ALTER TABLE [fp].[BudgetTimeClassSecurity] ADD CONSTRAINT [DF__BudgetTim__IsBud__36D01855] DEFAULT ((0)) FOR [IsBudgetLocked]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.BudgetedCostPerRVU_Sampled ------------------ +--------------------------------------------- +CREATE TABLE [fp].[BudgetedCostPerRVU_Sampled] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeGroupID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [CostComponentID] int NOT NULL, + [BudgetConfigID] smallint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [VariableDirectUnitCostPerRVU] decimal NULL, + [TotalVariableDirectCost] decimal NULL, + [TotalCost] decimal NULL, + [PayCodeID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [VariableDirectCost] decimal NOT NULL, + [IsImportedFromFile] bit NOT NULL, + [ChargeCodeID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__IsImp__11ABE2A3] DEFAULT ((0)) FOR [IsImportedFromFile]; GO +ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__Depar__48C2178F] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__Accou__49B63BC8] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__JobCo__4AAA6001] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__PayCo__4B9E843A] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__Fisca__4C92A873] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__CostC__4D86CCAC] DEFAULT ((0)) FOR [CostComponentID]; GO +ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__Budge__4E7AF0E5] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__UnitT__4F6F151E] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__Varia__50633957] DEFAULT ((0)) FOR [VariableDirectUnitCostPerRVU]; GO +ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__Total__51575D90] DEFAULT ((0)) FOR [TotalVariableDirectCost]; GO +ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__Total__524B81C9] DEFAULT ((0)) FOR [TotalCost]; GO +ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF_BudgetedCostPerRVU_Sampled_PayCodeID] DEFAULT ((0)) FOR [PayCodeID]; GO +ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF_BudgetedCostPerRVU_Sampled_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__Varia__7742052A] DEFAULT ((0)) FOR [VariableDirectCost]; GO +ALTER TABLE [fp].[BudgetedCostPerRVU_Sampled] ADD CONSTRAINT [DF__BudgetedC__Charg__75991A4D] DEFAULT ((0)) FOR [ChargeCodeID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ChangeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ChangeHistory] ( + [RowID] int NOT NULL, + [ChangeHistoryGUID] uniqueidentifier NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [SortOrder] int NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [OldValue] decimal NOT NULL, + [NewValue] decimal NOT NULL, + [FiscalMonthID] int NOT NULL, + [AdjustedProperty] tinyint NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE NONCLUSTERED INDEX [IX_ChangeHistory] ON [fp].[ChangeHistory] ([ChangeHistoryGUID]); +CREATE NONCLUSTERED INDEX [NCNU_ChangeHistory] ON [fp].[ChangeHistory] ([AdjustedProperty]) INCLUDE ([ChangeHistoryGUID], [AdjustmentType]); +GO +ALTER TABLE [fp].[ChangeHistory] ADD CONSTRAINT [DF_ChangeHistory_AdjustmentGUID] DEFAULT (newid()) FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ChangeHistory] ADD CONSTRAINT [DF_ChangeHistory_ChangeHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ChangeHistoryGUID]; GO +ALTER TABLE [fp].[ChangeHistory] ADD CONSTRAINT [DF_ChangeHistory_SortOrder] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fp].[ChangeHistory] ADD CONSTRAINT [DF_ChangeHistory_AdjustmentType] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[ChangeHistory] ADD CONSTRAINT [DF_ChangeHistory_OldValue] DEFAULT ((0)) FOR [OldValue]; GO +ALTER TABLE [fp].[ChangeHistory] ADD CONSTRAINT [DF_ChangeHistory_NewValue] DEFAULT ((0)) FOR [NewValue]; GO +ALTER TABLE [fp].[ChangeHistory] ADD CONSTRAINT [DF_ChangeHistory_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[ChangeHistory] ADD CONSTRAINT [DF_ChangeHistory_AdjustedProperty] DEFAULT ((0)) FOR [AdjustedProperty]; GO +ALTER TABLE [fp].[ChangeHistory] ADD CONSTRAINT [DF__ChangeHis__Group__60489418] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ChargeToGeneralLedgerCrosswalkConfiguration ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] ( + [RowID] int NOT NULL, + [BudgetConfigID] smallint NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [PatientClassID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [AccountID] int NOT NULL, + [IsRecordDeleted] bit NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_fp_ChargeToGeneralLedgerCrosswalkConfiguration] ON [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] ([EntityGroupConfigID], [DepartmentID]); +CREATE UNIQUE NONCLUSTERED INDEX [CORE_ChargeToGeneralLedgerCrosswalkConfiguration_Unique] ON [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] ([BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [ChargeCodeID], [PatientClassID], [AccountID], [PayorGroupID]); +GO +ALTER TABLE [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToG__IsRec__0D314649] DEFAULT ((0)) FOR [IsRecordDeleted]; GO +ALTER TABLE [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToG__Budge__58FB1327] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToG__Entit__59EF3760] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToG__Depar__5AE35B99] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToG__Charg__5BD77FD2] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToG__Patie__5CCBA40B] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToG__Payor__5DBFC844] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToG__Accou__5EB3EC7D] DEFAULT ((0)) FOR [AccountID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ChargeToStatisticsCrosswalkConfiguration ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ChargeToStatisticsCrosswalkConfiguration] ( + [EntityGroupConfigID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [PatientClassID] int NOT NULL, + [AccountID] int NOT NULL, + [RVUWeight] decimal NOT NULL, + PRIMARY KEY ([EntityGroupConfigID], [DepartmentID], [ChargeCodeID], [PatientClassID], [AccountID]) +); +GO +ALTER TABLE [fp].[ChargeToStatisticsCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToS__Entit__246F0EF3] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[ChargeToStatisticsCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToS__Depar__2563332C] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ChargeToStatisticsCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToS__Charg__26575765] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fp].[ChargeToStatisticsCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToS__Patie__274B7B9E] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ChargeToStatisticsCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToS__Accou__283F9FD7] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[ChargeToStatisticsCrosswalkConfiguration] ADD CONSTRAINT [DF__ChargeToS__RVUWe__2933C410] DEFAULT ((0)) FOR [RVUWeight]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ChargeVolume ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ChargeVolume] ( + [ChargeVolumeID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [PatientClassID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [ServiceEntityID] int NOT NULL, + [MSDRGID] int NOT NULL, + [UBRevCodeID] int NOT NULL, + [PrimaryCPTID] int NOT NULL, + [ServiceProviderID] int NOT NULL, + [ServiceProviderSpecialtyID] int NOT NULL, + [PerformingProviderID] int NOT NULL, + [PerformingProviderSpecialtyID] int NOT NULL, + [BillingCPTID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [VariableDirectUnitCost] decimal NOT NULL, + [SampledBudgetTotal] decimal NOT NULL, + [SampledProjectionTotal] decimal NOT NULL, + [InitialBudgetTotal] decimal NOT NULL, + [InitialProjectionTotal] decimal NOT NULL, + [BudgetAdjustedTotal] decimal NOT NULL, + [TargetAdjustedTotal] decimal NOT NULL, + [ProjectionAdjustedTotal] decimal NOT NULL, + [InitialBudgetDollarsTotal] decimal NOT NULL, + [InitialProjectionDollarsTotal] decimal NOT NULL, + [BudgetDollarsAdjustedTotal] decimal NOT NULL, + [TargetDollarsAdjustedTotal] decimal NOT NULL, + [ProjectionDollarsAdjustedTotal] decimal NOT NULL, + [SampledBudget01] decimal NOT NULL, + [SampledBudget02] decimal NOT NULL, + [SampledBudget03] decimal NOT NULL, + [SampledBudget04] decimal NOT NULL, + [SampledBudget05] decimal NOT NULL, + [SampledBudget06] decimal NOT NULL, + [SampledBudget07] decimal NOT NULL, + [SampledBudget08] decimal NOT NULL, + [SampledBudget09] decimal NOT NULL, + [SampledBudget10] decimal NOT NULL, + [SampledBudget11] decimal NOT NULL, + [SampledBudget12] decimal NOT NULL, + [SampledProjection01] decimal NOT NULL, + [SampledProjection02] decimal NOT NULL, + [SampledProjection03] decimal NOT NULL, + [SampledProjection04] decimal NOT NULL, + [SampledProjection05] decimal NOT NULL, + [SampledProjection06] decimal NOT NULL, + [SampledProjection07] decimal NOT NULL, + [SampledProjection08] decimal NOT NULL, + [SampledProjection09] decimal NOT NULL, + [SampledProjection10] decimal NOT NULL, + [SampledProjection11] decimal NOT NULL, + [SampledProjection12] decimal NOT NULL, + [InitialBudget01] decimal NOT NULL, + [InitialBudget02] decimal NOT NULL, + [InitialBudget03] decimal NOT NULL, + [InitialBudget04] decimal NOT NULL, + [InitialBudget05] decimal NOT NULL, + [InitialBudget06] decimal NOT NULL, + [InitialBudget07] decimal NOT NULL, + [InitialBudget08] decimal NOT NULL, + [InitialBudget09] decimal NOT NULL, + [InitialBudget10] decimal NOT NULL, + [InitialBudget11] decimal NOT NULL, + [InitialBudget12] decimal NOT NULL, + [InitialProjection01] decimal NOT NULL, + [InitialProjection02] decimal NOT NULL, + [InitialProjection03] decimal NOT NULL, + [InitialProjection04] decimal NOT NULL, + [InitialProjection05] decimal NOT NULL, + [InitialProjection06] decimal NOT NULL, + [InitialProjection07] decimal NOT NULL, + [InitialProjection08] decimal NOT NULL, + [InitialProjection09] decimal NOT NULL, + [InitialProjection10] decimal NOT NULL, + [InitialProjection11] decimal NOT NULL, + [InitialProjection12] decimal NOT NULL, + [InitialBudgetUnitsPerEncounter01] decimal NOT NULL, + [InitialBudgetUnitsPerEncounter02] decimal NOT NULL, + [InitialBudgetUnitsPerEncounter03] decimal NOT NULL, + [InitialBudgetUnitsPerEncounter04] decimal NOT NULL, + [InitialBudgetUnitsPerEncounter05] decimal NOT NULL, + [InitialBudgetUnitsPerEncounter06] decimal NOT NULL, + [InitialBudgetUnitsPerEncounter07] decimal NOT NULL, + [InitialBudgetUnitsPerEncounter08] decimal NOT NULL, + [InitialBudgetUnitsPerEncounter09] decimal NOT NULL, + [InitialBudgetUnitsPerEncounter10] decimal NOT NULL, + [InitialBudgetUnitsPerEncounter11] decimal NOT NULL, + [InitialBudgetUnitsPerEncounter12] decimal NOT NULL, + [InitialProjectionUnitsPerEncounter01] decimal NOT NULL, + [InitialProjectionUnitsPerEncounter02] decimal NOT NULL, + [InitialProjectionUnitsPerEncounter03] decimal NOT NULL, + [InitialProjectionUnitsPerEncounter04] decimal NOT NULL, + [InitialProjectionUnitsPerEncounter05] decimal NOT NULL, + [InitialProjectionUnitsPerEncounter06] decimal NOT NULL, + [InitialProjectionUnitsPerEncounter07] decimal NOT NULL, + [InitialProjectionUnitsPerEncounter08] decimal NOT NULL, + [InitialProjectionUnitsPerEncounter09] decimal NOT NULL, + [InitialProjectionUnitsPerEncounter10] decimal NOT NULL, + [InitialProjectionUnitsPerEncounter11] decimal NOT NULL, + [InitialProjectionUnitsPerEncounter12] decimal NOT NULL, + [TargetAdjusted01] decimal NOT NULL, + [TargetAdjusted02] decimal NOT NULL, + [TargetAdjusted03] decimal NOT NULL, + [TargetAdjusted04] decimal NOT NULL, + [TargetAdjusted05] decimal NOT NULL, + [TargetAdjusted06] decimal NOT NULL, + [TargetAdjusted07] decimal NOT NULL, + [TargetAdjusted08] decimal NOT NULL, + [TargetAdjusted09] decimal NOT NULL, + [TargetAdjusted10] decimal NOT NULL, + [TargetAdjusted11] decimal NOT NULL, + [TargetAdjusted12] decimal NOT NULL, + [TargetUnitsPerEncounterAdjusted01] decimal NOT NULL, + [TargetUnitsPerEncounterAdjusted02] decimal NOT NULL, + [TargetUnitsPerEncounterAdjusted03] decimal NOT NULL, + [TargetUnitsPerEncounterAdjusted04] decimal NOT NULL, + [TargetUnitsPerEncounterAdjusted05] decimal NOT NULL, + [TargetUnitsPerEncounterAdjusted06] decimal NOT NULL, + [TargetUnitsPerEncounterAdjusted07] decimal NOT NULL, + [TargetUnitsPerEncounterAdjusted08] decimal NOT NULL, + [TargetUnitsPerEncounterAdjusted09] decimal NOT NULL, + [TargetUnitsPerEncounterAdjusted10] decimal NOT NULL, + [TargetUnitsPerEncounterAdjusted11] decimal NOT NULL, + [TargetUnitsPerEncounterAdjusted12] decimal NOT NULL, + [BudgetAdjusted01] decimal NOT NULL, + [BudgetAdjusted02] decimal NOT NULL, + [BudgetAdjusted03] decimal NOT NULL, + [BudgetAdjusted04] decimal NOT NULL, + [BudgetAdjusted05] decimal NOT NULL, + [BudgetAdjusted06] decimal NOT NULL, + [BudgetAdjusted07] decimal NOT NULL, + [BudgetAdjusted08] decimal NOT NULL, + [BudgetAdjusted09] decimal NOT NULL, + [BudgetAdjusted10] decimal NOT NULL, + [BudgetAdjusted11] decimal NOT NULL, + [BudgetAdjusted12] decimal NOT NULL, + [BudgetUnitsPerEncounterAdjusted01] decimal NOT NULL, + [BudgetUnitsPerEncounterAdjusted02] decimal NOT NULL, + [BudgetUnitsPerEncounterAdjusted03] decimal NOT NULL, + [BudgetUnitsPerEncounterAdjusted04] decimal NOT NULL, + [BudgetUnitsPerEncounterAdjusted05] decimal NOT NULL, + [BudgetUnitsPerEncounterAdjusted06] decimal NOT NULL, + [BudgetUnitsPerEncounterAdjusted07] decimal NOT NULL, + [BudgetUnitsPerEncounterAdjusted08] decimal NOT NULL, + [BudgetUnitsPerEncounterAdjusted09] decimal NOT NULL, + [BudgetUnitsPerEncounterAdjusted10] decimal NOT NULL, + [BudgetUnitsPerEncounterAdjusted11] decimal NOT NULL, + [BudgetUnitsPerEncounterAdjusted12] decimal NOT NULL, + [ProjectionAdjusted01] decimal NOT NULL, + [ProjectionAdjusted02] decimal NOT NULL, + [ProjectionAdjusted03] decimal NOT NULL, + [ProjectionAdjusted04] decimal NOT NULL, + [ProjectionAdjusted05] decimal NOT NULL, + [ProjectionAdjusted06] decimal NOT NULL, + [ProjectionAdjusted07] decimal NOT NULL, + [ProjectionAdjusted08] decimal NOT NULL, + [ProjectionAdjusted09] decimal NOT NULL, + [ProjectionAdjusted10] decimal NOT NULL, + [ProjectionAdjusted11] decimal NOT NULL, + [ProjectionAdjusted12] decimal NOT NULL, + [ProjectionUnitsPerEncounterAdjusted01] decimal NOT NULL, + [ProjectionUnitsPerEncounterAdjusted02] decimal NOT NULL, + [ProjectionUnitsPerEncounterAdjusted03] decimal NOT NULL, + [ProjectionUnitsPerEncounterAdjusted04] decimal NOT NULL, + [ProjectionUnitsPerEncounterAdjusted05] decimal NOT NULL, + [ProjectionUnitsPerEncounterAdjusted06] decimal NOT NULL, + [ProjectionUnitsPerEncounterAdjusted07] decimal NOT NULL, + [ProjectionUnitsPerEncounterAdjusted08] decimal NOT NULL, + [ProjectionUnitsPerEncounterAdjusted09] decimal NOT NULL, + [ProjectionUnitsPerEncounterAdjusted10] decimal NOT NULL, + [ProjectionUnitsPerEncounterAdjusted11] decimal NOT NULL, + [ProjectionUnitsPerEncounterAdjusted12] decimal NOT NULL, + [InitialBudgetDollars01] decimal NOT NULL, + [InitialBudgetDollars02] decimal NOT NULL, + [InitialBudgetDollars03] decimal NOT NULL, + [InitialBudgetDollars04] decimal NOT NULL, + [InitialBudgetDollars05] decimal NOT NULL, + [InitialBudgetDollars06] decimal NOT NULL, + [InitialBudgetDollars07] decimal NOT NULL, + [InitialBudgetDollars08] decimal NOT NULL, + [InitialBudgetDollars09] decimal NOT NULL, + [InitialBudgetDollars10] decimal NOT NULL, + [InitialBudgetDollars11] decimal NOT NULL, + [InitialBudgetDollars12] decimal NOT NULL, + [InitialProjectionDollars01] decimal NOT NULL, + [InitialProjectionDollars02] decimal NOT NULL, + [InitialProjectionDollars03] decimal NOT NULL, + [InitialProjectionDollars04] decimal NOT NULL, + [InitialProjectionDollars05] decimal NOT NULL, + [InitialProjectionDollars06] decimal NOT NULL, + [InitialProjectionDollars07] decimal NOT NULL, + [InitialProjectionDollars08] decimal NOT NULL, + [InitialProjectionDollars09] decimal NOT NULL, + [InitialProjectionDollars10] decimal NOT NULL, + [InitialProjectionDollars11] decimal NOT NULL, + [InitialProjectionDollars12] decimal NOT NULL, + [TargetPrice01] decimal NOT NULL, + [TargetPrice02] decimal NOT NULL, + [TargetPrice03] decimal NOT NULL, + [TargetPrice04] decimal NOT NULL, + [TargetPrice05] decimal NOT NULL, + [TargetPrice06] decimal NOT NULL, + [TargetPrice07] decimal NOT NULL, + [TargetPrice08] decimal NOT NULL, + [TargetPrice09] decimal NOT NULL, + [TargetPrice10] decimal NOT NULL, + [TargetPrice11] decimal NOT NULL, + [TargetPrice12] decimal NOT NULL, + [BudgetPrice01] decimal NOT NULL, + [BudgetPrice02] decimal NOT NULL, + [BudgetPrice03] decimal NOT NULL, + [BudgetPrice04] decimal NOT NULL, + [BudgetPrice05] decimal NOT NULL, + [BudgetPrice06] decimal NOT NULL, + [BudgetPrice07] decimal NOT NULL, + [BudgetPrice08] decimal NOT NULL, + [BudgetPrice09] decimal NOT NULL, + [BudgetPrice10] decimal NOT NULL, + [BudgetPrice11] decimal NOT NULL, + [BudgetPrice12] decimal NOT NULL, + [ProjectionPrice01] decimal NOT NULL, + [ProjectionPrice02] decimal NOT NULL, + [ProjectionPrice03] decimal NOT NULL, + [ProjectionPrice04] decimal NOT NULL, + [ProjectionPrice05] decimal NOT NULL, + [ProjectionPrice06] decimal NOT NULL, + [ProjectionPrice07] decimal NOT NULL, + [ProjectionPrice08] decimal NOT NULL, + [ProjectionPrice09] decimal NOT NULL, + [ProjectionPrice10] decimal NOT NULL, + [ProjectionPrice11] decimal NOT NULL, + [ProjectionPrice12] decimal NOT NULL, + [TargetDollarsAdjusted01] decimal NOT NULL, + [TargetDollarsAdjusted02] decimal NOT NULL, + [TargetDollarsAdjusted03] decimal NOT NULL, + [TargetDollarsAdjusted04] decimal NOT NULL, + [TargetDollarsAdjusted05] decimal NOT NULL, + [TargetDollarsAdjusted06] decimal NOT NULL, + [TargetDollarsAdjusted07] decimal NOT NULL, + [TargetDollarsAdjusted08] decimal NOT NULL, + [TargetDollarsAdjusted09] decimal NOT NULL, + [TargetDollarsAdjusted10] decimal NOT NULL, + [TargetDollarsAdjusted11] decimal NOT NULL, + [TargetDollarsAdjusted12] decimal NOT NULL, + [BudgetDollarsAdjusted01] decimal NOT NULL, + [BudgetDollarsAdjusted02] decimal NOT NULL, + [BudgetDollarsAdjusted03] decimal NOT NULL, + [BudgetDollarsAdjusted04] decimal NOT NULL, + [BudgetDollarsAdjusted05] decimal NOT NULL, + [BudgetDollarsAdjusted06] decimal NOT NULL, + [BudgetDollarsAdjusted07] decimal NOT NULL, + [BudgetDollarsAdjusted08] decimal NOT NULL, + [BudgetDollarsAdjusted09] decimal NOT NULL, + [BudgetDollarsAdjusted10] decimal NOT NULL, + [BudgetDollarsAdjusted11] decimal NOT NULL, + [BudgetDollarsAdjusted12] decimal NOT NULL, + [ProjectionDollarsAdjusted01] decimal NOT NULL, + [ProjectionDollarsAdjusted02] decimal NOT NULL, + [ProjectionDollarsAdjusted03] decimal NOT NULL, + [ProjectionDollarsAdjusted04] decimal NOT NULL, + [ProjectionDollarsAdjusted05] decimal NOT NULL, + [ProjectionDollarsAdjusted06] decimal NOT NULL, + [ProjectionDollarsAdjusted07] decimal NOT NULL, + [ProjectionDollarsAdjusted08] decimal NOT NULL, + [ProjectionDollarsAdjusted09] decimal NOT NULL, + [ProjectionDollarsAdjusted10] decimal NOT NULL, + [ProjectionDollarsAdjusted11] decimal NOT NULL, + [ProjectionDollarsAdjusted12] decimal NOT NULL, + [AddDate] datetime NOT NULL, + [IsNew] bit NOT NULL, + [BudgetLockType] tinyint NOT NULL, + [BudgetLockFlag] tinyint NOT NULL, + [TargetLockType] tinyint NOT NULL, + [TargetLockFlag] tinyint NOT NULL, + [ProjectionLockType] tinyint NOT NULL, + [ProjectionLockFlag] tinyint NOT NULL, + [IsCVReportRefreshRequired] bit NOT NULL, + PRIMARY KEY ([ChargeVolumeID]) +); + +CREATE CLUSTERED INDEX [IX_ChargeVolume] ON [fp].[ChargeVolume] ([BudgetConfigID], [EntityID], [DepartmentID], [ChargeCodeID]); +CREATE NONCLUSTERED INDEX [CORE_EntityGroupConfigID_inc] ON [fp].[ChargeVolume] ([EntityGroupConfigID], [BudgetConfigID], [UnitTypeID]) INCLUDE ([ChargeVolumeID], [EntityID], [DepartmentID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [IsNew]); +CREATE NONCLUSTERED INDEX [IX_ChargeVolume_BudgetConfig] ON [fp].[ChargeVolume] ([BudgetConfigID]) INCLUDE ([ChargeVolumeID], [EntityGroupConfigID], [EntityID], [DepartmentID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ChargeVolume_Department] ON [fp].[ChargeVolume] ([DepartmentID]) INCLUDE ([ChargeVolumeID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ChargeVolume_Entity] ON [fp].[ChargeVolume] ([EntityID]) INCLUDE ([ChargeVolumeID], [BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [UnitTypeID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[ChargeVolume] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [ServiceEntityID], [MSDRGID], [UBRevCodeID], [PrimaryCPTID], [ServiceProviderID], [ServiceProviderSpecialtyID], [PerformingProviderID], [PerformingProviderSpecialtyID], [BillingCPTID], [UnitTypeID]) INCLUDE ([IsNew]); +CREATE NONCLUSTERED INDEX [NCNU_SleCvFlexing] ON [fp].[ChargeVolume] ([BudgetConfigID], [UnitTypeID]) INCLUDE ([ChargeVolumeID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ServiceEntityID], [MSDRGID], [PrimaryCPTID], [ServiceProviderID]); +GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [FK_ChargeVolume_AgeCohort] FOREIGN KEY ([AgeCohortID]) REFERENCES [fw].[DimAgeCohort] ([AgeCohortID]); GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [FK_ChargeVolume_ChargeCode] FOREIGN KEY ([ChargeCodeID]) REFERENCES [fw].[DimChargeCode] ([ChargeCodeID]); GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [FK_ChargeVolume_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [FK_ChargeVolume_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [FK_ChargeVolume_MedicalSurgical] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [FK_ChargeVolume_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [FK_ChargeVolume_ServiceLine] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [FK_ChargeVolume_UnitType] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__0017424D] DEFAULT ((0)) FOR [SampledBudget06]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__00D65C5C] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted09]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__010B6686] DEFAULT ((0)) FOR [SampledBudget07]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__01CA8095] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted10]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__01FF8ABF] DEFAULT ((0)) FOR [SampledBudget08]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__02BEA4CE] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted11]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__02F3AEF8] DEFAULT ((0)) FOR [SampledBudget09]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__03B2C907] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted12]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__03E7D331] DEFAULT ((0)) FOR [SampledBudget10]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__04A6ED40] DEFAULT ((0)) FOR [InitialBudgetDollars01]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__04DBF76A] DEFAULT ((0)) FOR [SampledBudget11]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__059B1179] DEFAULT ((0)) FOR [InitialBudgetDollars02]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__05D01BA3] DEFAULT ((0)) FOR [SampledBudget12]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__068F35B2] DEFAULT ((0)) FOR [InitialBudgetDollars03]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__06C43FDC] DEFAULT ((0)) FOR [SampledProjection01]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__078359EB] DEFAULT ((0)) FOR [InitialBudgetDollars04]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__07B86415] DEFAULT ((0)) FOR [SampledProjection02]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__08777E24] DEFAULT ((0)) FOR [InitialBudgetDollars05]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__08AC884E] DEFAULT ((0)) FOR [SampledProjection03]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__096BA25D] DEFAULT ((0)) FOR [InitialBudgetDollars06]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__09A0AC87] DEFAULT ((0)) FOR [SampledProjection04]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__0A5FC696] DEFAULT ((0)) FOR [InitialBudgetDollars07]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__0A94D0C0] DEFAULT ((0)) FOR [SampledProjection05]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__0B53EACF] DEFAULT ((0)) FOR [InitialBudgetDollars08]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__0B88F4F9] DEFAULT ((0)) FOR [SampledProjection06]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__0C480F08] DEFAULT ((0)) FOR [InitialBudgetDollars09]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__0C7D1932] DEFAULT ((0)) FOR [SampledProjection07]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__0D3C3341] DEFAULT ((0)) FOR [InitialBudgetDollars10]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__0D713D6B] DEFAULT ((0)) FOR [SampledProjection08]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__0E30577A] DEFAULT ((0)) FOR [InitialBudgetDollars11]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__0E6561A4] DEFAULT ((0)) FOR [SampledProjection09]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__0F247BB3] DEFAULT ((0)) FOR [InitialBudgetDollars12]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__0F5985DD] DEFAULT ((0)) FOR [SampledProjection10]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__10189FEC] DEFAULT ((0)) FOR [InitialProjectionDollars01]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__104DAA16] DEFAULT ((0)) FOR [SampledProjection11]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__110CC425] DEFAULT ((0)) FOR [InitialProjectionDollars02]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__1141CE4F] DEFAULT ((0)) FOR [SampledProjection12]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__1200E85E] DEFAULT ((0)) FOR [InitialProjectionDollars03]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__1235F288] DEFAULT ((0)) FOR [InitialBudget01]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__12F50C97] DEFAULT ((0)) FOR [InitialProjectionDollars04]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__132A16C1] DEFAULT ((0)) FOR [InitialBudget02]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__13E930D0] DEFAULT ((0)) FOR [InitialProjectionDollars05]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__141E3AFA] DEFAULT ((0)) FOR [InitialBudget03]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__14DD5509] DEFAULT ((0)) FOR [InitialProjectionDollars06]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__15125F33] DEFAULT ((0)) FOR [InitialBudget04]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__15D17942] DEFAULT ((0)) FOR [InitialProjectionDollars07]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__1606836C] DEFAULT ((0)) FOR [InitialBudget05]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__16C59D7B] DEFAULT ((0)) FOR [InitialProjectionDollars08]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__16FAA7A5] DEFAULT ((0)) FOR [InitialBudget06]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__17B9C1B4] DEFAULT ((0)) FOR [InitialProjectionDollars09]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__17EECBDE] DEFAULT ((0)) FOR [InitialBudget07]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__18ADE5ED] DEFAULT ((0)) FOR [InitialProjectionDollars10]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__18E2F017] DEFAULT ((0)) FOR [InitialBudget08]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__19A20A26] DEFAULT ((0)) FOR [InitialProjectionDollars11]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__19D71450] DEFAULT ((0)) FOR [InitialBudget09]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__1A962E5F] DEFAULT ((0)) FOR [InitialProjectionDollars12]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__1ACB3889] DEFAULT ((0)) FOR [InitialBudget10]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__1B8A5298] DEFAULT ((0)) FOR [TargetPrice01]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__1BBF5CC2] DEFAULT ((0)) FOR [InitialBudget11]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__1C7E76D1] DEFAULT ((0)) FOR [TargetPrice02]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__1CB380FB] DEFAULT ((0)) FOR [InitialBudget12]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__1D729B0A] DEFAULT ((0)) FOR [TargetPrice03]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__1DA7A534] DEFAULT ((0)) FOR [InitialProjection01]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__1E66BF43] DEFAULT ((0)) FOR [TargetPrice04]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__1E9BC96D] DEFAULT ((0)) FOR [InitialProjection02]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__1F5AE37C] DEFAULT ((0)) FOR [TargetPrice05]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__1F8FEDA6] DEFAULT ((0)) FOR [InitialProjection03]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__204F07B5] DEFAULT ((0)) FOR [TargetPrice06]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__208411DF] DEFAULT ((0)) FOR [InitialProjection04]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__21432BEE] DEFAULT ((0)) FOR [TargetPrice07]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__21783618] DEFAULT ((0)) FOR [InitialProjection05]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__22375027] DEFAULT ((0)) FOR [TargetPrice08]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__226C5A51] DEFAULT ((0)) FOR [InitialProjection06]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__232B7460] DEFAULT ((0)) FOR [TargetPrice09]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__23607E8A] DEFAULT ((0)) FOR [InitialProjection07]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__241F9899] DEFAULT ((0)) FOR [TargetPrice10]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__2454A2C3] DEFAULT ((0)) FOR [InitialProjection08]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__2513BCD2] DEFAULT ((0)) FOR [TargetPrice11]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__2548C6FC] DEFAULT ((0)) FOR [InitialProjection09]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__2607E10B] DEFAULT ((0)) FOR [TargetPrice12]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__263CEB35] DEFAULT ((0)) FOR [InitialProjection10]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__26FC0544] DEFAULT ((0)) FOR [BudgetPrice01]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__27310F6E] DEFAULT ((0)) FOR [InitialProjection11]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__27F0297D] DEFAULT ((0)) FOR [BudgetPrice02]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__282533A7] DEFAULT ((0)) FOR [InitialProjection12]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__28E44DB6] DEFAULT ((0)) FOR [BudgetPrice03]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__291957E0] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter01]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__29D871EF] DEFAULT ((0)) FOR [BudgetPrice04]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__2A0D7C19] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter02]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__2ACC9628] DEFAULT ((0)) FOR [BudgetPrice05]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__2B01A052] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter03]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__2BC0BA61] DEFAULT ((0)) FOR [BudgetPrice06]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__2BF5C48B] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter04]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__2CB4DE9A] DEFAULT ((0)) FOR [BudgetPrice07]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__2CE9E8C4] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter05]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__2DA902D3] DEFAULT ((0)) FOR [BudgetPrice08]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__2DDE0CFD] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter06]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__2E9D270C] DEFAULT ((0)) FOR [BudgetPrice09]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__2ED23136] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter07]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__2F914B45] DEFAULT ((0)) FOR [BudgetPrice10]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__2FC6556F] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter08]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__30856F7E] DEFAULT ((0)) FOR [BudgetPrice11]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__30BA79A8] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter09]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__317993B7] DEFAULT ((0)) FOR [BudgetPrice12]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__31AE9DE1] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter10]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__326DB7F0] DEFAULT ((0)) FOR [ProjectionPrice01]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__32A2C21A] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter11]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__3361DC29] DEFAULT ((0)) FOR [ProjectionPrice02]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__3396E653] DEFAULT ((0)) FOR [InitialBudgetUnitsPerEncounter12]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__34560062] DEFAULT ((0)) FOR [ProjectionPrice03]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__348B0A8C] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter01]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__354A249B] DEFAULT ((0)) FOR [ProjectionPrice04]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__357F2EC5] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter02]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__363E48D4] DEFAULT ((0)) FOR [ProjectionPrice05]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__367352FE] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter03]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__37326D0D] DEFAULT ((0)) FOR [ProjectionPrice06]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__37677737] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter04]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__38269146] DEFAULT ((0)) FOR [ProjectionPrice07]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__385B9B70] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter05]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__391AB57F] DEFAULT ((0)) FOR [ProjectionPrice08]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__394FBFA9] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter06]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__3A0ED9B8] DEFAULT ((0)) FOR [ProjectionPrice09]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__3A43E3E2] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter07]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__3B02FDF1] DEFAULT ((0)) FOR [ProjectionPrice10]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__3B38081B] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter08]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__3BF7222A] DEFAULT ((0)) FOR [ProjectionPrice11]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__3C2C2C54] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter09]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__3CEB4663] DEFAULT ((0)) FOR [ProjectionPrice12]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__3D20508D] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter10]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__AddDa__3DDF6A9C] DEFAULT (getdate()) FOR [AddDate]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__3E1474C6] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter11]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__IsNew__3ED38ED5] DEFAULT ((0)) FOR [IsNew]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Initi__3F0898FF] DEFAULT ((0)) FOR [InitialProjectionUnitsPerEncounter12]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__3FC7B30E] DEFAULT ((0)) FOR [BudgetLockType]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__3FFCBD38] DEFAULT ((0)) FOR [TargetAdjusted01]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__40BBD747] DEFAULT ((0)) FOR [BudgetLockFlag]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__40F0E171] DEFAULT ((0)) FOR [TargetAdjusted02]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__41AFFB80] DEFAULT ((0)) FOR [TargetLockType]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__41E505AA] DEFAULT ((0)) FOR [TargetAdjusted03]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__42A41FB9] DEFAULT ((0)) FOR [TargetLockFlag]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__42D929E3] DEFAULT ((0)) FOR [TargetAdjusted04]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__439843F2] DEFAULT ((0)) FOR [ProjectionLockType]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__43CD4E1C] DEFAULT ((0)) FOR [TargetAdjusted05]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__448C682B] DEFAULT ((0)) FOR [ProjectionLockFlag]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__44C17255] DEFAULT ((0)) FOR [TargetAdjusted06]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__IsCVR__45808C64] DEFAULT ((0)) FOR [IsCVReportRefreshRequired]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__45B5968E] DEFAULT ((0)) FOR [TargetAdjusted07]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__46A9BAC7] DEFAULT ((0)) FOR [TargetAdjusted08]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__479DDF00] DEFAULT ((0)) FOR [TargetAdjusted09]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__48920339] DEFAULT ((0)) FOR [TargetAdjusted10]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__49862772] DEFAULT ((0)) FOR [TargetAdjusted11]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__4A7A4BAB] DEFAULT ((0)) FOR [TargetAdjusted12]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__4B6E6FE4] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted01]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__4C62941D] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted02]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__4D56B856] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted03]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__4E4ADC8F] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted04]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__4F3F00C8] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted05]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__50332501] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted06]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__5127493A] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted07]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__521B6D73] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted08]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__530F91AC] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted09]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__5403B5E5] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted10]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__54F7DA1E] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted11]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Targe__55EBFE57] DEFAULT ((0)) FOR [TargetUnitsPerEncounterAdjusted12]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__56E02290] DEFAULT ((0)) FOR [BudgetAdjusted01]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__57D446C9] DEFAULT ((0)) FOR [BudgetAdjusted02]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__58C86B02] DEFAULT ((0)) FOR [BudgetAdjusted03]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__59BC8F3B] DEFAULT ((0)) FOR [BudgetAdjusted04]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__5AB0B374] DEFAULT ((0)) FOR [BudgetAdjusted05]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__5BA4D7AD] DEFAULT ((0)) FOR [BudgetAdjusted06]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__5C98FBE6] DEFAULT ((0)) FOR [BudgetAdjusted07]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__5D8D201F] DEFAULT ((0)) FOR [BudgetAdjusted08]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__5E814458] DEFAULT ((0)) FOR [BudgetAdjusted09]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__5F756891] DEFAULT ((0)) FOR [BudgetAdjusted10]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__60698CCA] DEFAULT ((0)) FOR [BudgetAdjusted11]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__615DB103] DEFAULT ((0)) FOR [BudgetAdjusted12]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__6251D53C] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted01]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__6345F975] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted02]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__643A1DAE] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted03]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__652E41E7] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted04]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__66226620] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted05]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__67168A59] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted06]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__680AAE92] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted07]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__683FB8BC] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__68FED2CB] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted08]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Entit__6933DCF5] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__69F2F704] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted09]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Entit__6A28012E] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__6AE71B3D] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted10]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Depar__6B1C2567] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__6BDB3F76] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted11]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Servi__6C1049A0] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Budge__6CCF63AF] DEFAULT ((0)) FOR [BudgetUnitsPerEncounterAdjusted12]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Patie__6D046DD9] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__6DC387E8] DEFAULT ((0)) FOR [ProjectionAdjusted01]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__AgeCo__6DF89212] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__6EB7AC21] DEFAULT ((0)) FOR [ProjectionAdjusted02]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Medic__6EECB64B] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__6FABD05A] DEFAULT ((0)) FOR [ProjectionAdjusted03]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Charg__6FE0DA84] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__709FF493] DEFAULT ((0)) FOR [ProjectionAdjusted04]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Servi__70D4FEBD] DEFAULT ((0)) FOR [ServiceEntityID]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__719418CC] DEFAULT ((0)) FOR [ProjectionAdjusted05]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__MSDRG__71C922F6] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__72883D05] DEFAULT ((0)) FOR [ProjectionAdjusted06]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__UBRev__72BD472F] DEFAULT ((0)) FOR [UBRevCodeID]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__737C613E] DEFAULT ((0)) FOR [ProjectionAdjusted07]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Prima__73B16B68] DEFAULT ((0)) FOR [PrimaryCPTID]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__74708577] DEFAULT ((0)) FOR [ProjectionAdjusted08]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Servi__74A58FA1] DEFAULT ((0)) FOR [ServiceProviderID]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__7564A9B0] DEFAULT ((0)) FOR [ProjectionAdjusted09]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Servi__7599B3DA] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__7658CDE9] DEFAULT ((0)) FOR [ProjectionAdjusted10]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Perfo__768DD813] DEFAULT ((0)) FOR [PerformingProviderID]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__774CF222] DEFAULT ((0)) FOR [ProjectionAdjusted11]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Perfo__7781FC4C] DEFAULT ((0)) FOR [PerformingProviderSpecialtyID]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__7841165B] DEFAULT ((0)) FOR [ProjectionAdjusted12]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Billi__78762085] DEFAULT ((0)) FOR [BillingCPTID]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__79353A94] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted01]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__UnitT__796A44BE] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__7A295ECD] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted02]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Varia__7A5E68F7] DEFAULT ((0)) FOR [VariableDirectUnitCost]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__7B1D8306] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted03]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__7B528D30] DEFAULT ((0)) FOR [SampledBudget01]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__7C11A73F] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted04]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__7C46B169] DEFAULT ((0)) FOR [SampledBudget02]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__7D05CB78] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted05]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__7D3AD5A2] DEFAULT ((0)) FOR [SampledBudget03]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__7DF9EFB1] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted06]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__7E2EF9DB] DEFAULT ((0)) FOR [SampledBudget04]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__7EEE13EA] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted07]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Sampl__7F231E14] DEFAULT ((0)) FOR [SampledBudget05]; GO +ALTER TABLE [fp].[ChargeVolume] ADD CONSTRAINT [DF__ChargeVol__Proje__7FE23823] DEFAULT ((0)) FOR [ProjectionUnitsPerEncounterAdjusted08]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ChargeVolumeAddProviderAdjustment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ChargeVolumeAddProviderAdjustment] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [PatientClassID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [ServiceEntityID] int NOT NULL, + [MSDRGID] int NOT NULL, + [UBRevCodeID] int NOT NULL, + [PrimaryCPTID] int NOT NULL, + [BillingCPTID] int NOT NULL, + [ServiceProviderID] int NOT NULL, + [ServiceProviderSpecialtyID] int NOT NULL, + [PerformingProviderID] int NOT NULL, + [PerformingProviderSpecialtyID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [Value01] decimal NOT NULL, + [Value02] decimal NOT NULL, + [Value03] decimal NOT NULL, + [Value04] decimal NOT NULL, + [Value05] decimal NOT NULL, + [Value06] decimal NOT NULL, + [Value07] decimal NOT NULL, + [Value08] decimal NOT NULL, + [Value09] decimal NOT NULL, + [Value10] decimal NOT NULL, + [Value11] decimal NOT NULL, + [Value12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [CLU_CVAddProvider] ON [fp].[ChargeVolumeAddProviderAdjustment] ([BudgetConfigID], [DepartmentID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_ClusteredUnique] ON [fp].[ChargeVolumeAddProviderAdjustment] ([BudgetConfigID], [AdjustmentGUID], [EntityID], [DepartmentID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [ServiceEntityID], [MSDRGID], [UBRevCodeID], [PrimaryCPTID], [ServiceProviderID], [ServiceProviderSpecialtyID], [PerformingProviderID], [PerformingProviderSpecialtyID], [BillingCPTID], [TimeClassID], [BudgetPhaseID]); +GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Charg__009337DE] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Servi__01875C17] DEFAULT ((0)) FOR [ServiceEntityID]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__MSDRG__027B8050] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__UBRev__036FA489] DEFAULT ((0)) FOR [UBRevCodeID]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Prima__0463C8C2] DEFAULT ((0)) FOR [PrimaryCPTID]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Billi__0557ECFB] DEFAULT ((0)) FOR [BillingCPTID]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Servi__064C1134] DEFAULT ((0)) FOR [ServiceProviderID]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Servi__0740356D] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Perfo__083459A6] DEFAULT ((0)) FOR [PerformingProviderID]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Perfo__09287DDF] DEFAULT ((0)) FOR [PerformingProviderSpecialtyID]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__TimeC__0C04EA8A] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Budge__0CF90EC3] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__IsRec__0DED32FC] DEFAULT ((0)) FOR [IsRecordDeleted]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__0EE15735] DEFAULT ((0)) FOR [Value01]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__0FD57B6E] DEFAULT ((0)) FOR [Value02]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__10C99FA7] DEFAULT ((0)) FOR [Value03]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__11BDC3E0] DEFAULT ((0)) FOR [Value04]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__12B1E819] DEFAULT ((0)) FOR [Value05]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__13A60C52] DEFAULT ((0)) FOR [Value06]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__149A308B] DEFAULT ((0)) FOR [Value07]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__158E54C4] DEFAULT ((0)) FOR [Value08]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__168278FD] DEFAULT ((0)) FOR [Value09]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__17769D36] DEFAULT ((0)) FOR [Value10]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__186AC16F] DEFAULT ((0)) FOR [Value11]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Value__195EE5A8] DEFAULT ((0)) FOR [Value12]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Budge__78F21616] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Adjus__79E63A4F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Entit__7ADA5E88] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Depar__7BCE82C1] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Servi__7CC2A6FA] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Patie__7DB6CB33] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__AgeCo__7EAAEF6C] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[ChargeVolumeAddProviderAdjustment] ADD CONSTRAINT [DF__ChargeVol__Medic__7F9F13A5] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ChargeVolumeAdjustmentRate ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ChargeVolumeAdjustmentRate] ( + [RowID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [BudgetConfigID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [PatientClassID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [EntityID] int NOT NULL, + [ServiceEntityID] int NOT NULL, + [MSDRGID] int NOT NULL, + [UBRevCodeID] int NOT NULL, + [PrimaryCPTID] int NOT NULL, + [ServiceProviderID] int NOT NULL, + [ServiceProviderSpecialtyID] int NOT NULL, + [PerformingProviderID] int NOT NULL, + [PerformingProviderSpecialtyID] int NOT NULL, + [BillingCPTID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Value01] decimal NOT NULL, + [Value02] decimal NOT NULL, + [Value03] decimal NOT NULL, + [Value04] decimal NOT NULL, + [Value05] decimal NOT NULL, + [Value06] decimal NOT NULL, + [Value07] decimal NOT NULL, + [Value08] decimal NOT NULL, + [Value09] decimal NOT NULL, + [Value10] decimal NOT NULL, + [Value11] decimal NOT NULL, + [Value12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_Clustered_ChargeVolumeAdjustmentRate] ON [fp].[ChargeVolumeAdjustmentRate] ([BudgetConfigID]); +GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Adjus__3996AB10] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Budge__3A8ACF49] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Depar__3B7EF382] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Servi__3C7317BB] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Patie__3D673BF4] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__AgeCo__3E5B602D] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Medic__3F4F8466] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Charg__4043A89F] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Entit__4137CCD8] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Servi__422BF111] DEFAULT ((0)) FOR [ServiceEntityID]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__MSDRG__4320154A] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__UBRev__44143983] DEFAULT ((0)) FOR [UBRevCodeID]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Prima__45085DBC] DEFAULT ((0)) FOR [PrimaryCPTID]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Servi__45FC81F5] DEFAULT ((0)) FOR [ServiceProviderID]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Servi__46F0A62E] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Perfo__47E4CA67] DEFAULT ((0)) FOR [PerformingProviderID]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Perfo__48D8EEA0] DEFAULT ((0)) FOR [PerformingProviderSpecialtyID]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Billi__4BB55B4B] DEFAULT ((0)) FOR [BillingCPTID]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__TimeC__4CA97F84] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__4D9DA3BD] DEFAULT ((0)) FOR [Value01]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__4E91C7F6] DEFAULT ((0)) FOR [Value02]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__4F85EC2F] DEFAULT ((0)) FOR [Value03]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__507A1068] DEFAULT ((0)) FOR [Value04]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__516E34A1] DEFAULT ((0)) FOR [Value05]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__526258DA] DEFAULT ((0)) FOR [Value06]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__53567D13] DEFAULT ((0)) FOR [Value07]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__544AA14C] DEFAULT ((0)) FOR [Value08]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__553EC585] DEFAULT ((0)) FOR [Value09]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__5632E9BE] DEFAULT ((0)) FOR [Value10]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__57270DF7] DEFAULT ((0)) FOR [Value11]; GO +ALTER TABLE [fp].[ChargeVolumeAdjustmentRate] ADD CONSTRAINT [DF__ChargeVol__Value__581B3230] DEFAULT ((0)) FOR [Value12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ChargeVolumeChangeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ChargeVolumeChangeHistory] ( + [RowID] bigint NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [OldValue] decimal NOT NULL, + [NewValue] decimal NOT NULL, + [BudgetConfigID] int NOT NULL, + [DateCreatedUTC] datetime2 NOT NULL, + [ChargeVolumeID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE NONCLUSTERED INDEX [CORE_ChargeVolumeID] ON [fp].[ChargeVolumeChangeHistory] ([ChargeVolumeID]); +CREATE NONCLUSTERED INDEX [CORE_ChargeVolumeChangeHistory_ImpactReportLoads] ON [fp].[ChargeVolumeChangeHistory] ([AdjustmentGUID], [FiscalMonthID], [TimeClassID]) INCLUDE ([ChargeVolumeID], [AdjustmentType], [UnitTypeID], [BudgetPhaseID], [OldValue], [NewValue], [BudgetConfigID]); +GO +ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__DateC__02E594A4] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO +ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__Adjus__188E83E9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__Adjus__1982A822] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__Fisca__1B6AF094] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__UnitT__1C5F14CD] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__TimeC__1D533906] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__Budge__1E475D3F] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__OldVa__1F3B8178] DEFAULT ((0)) FOR [OldValue]; GO +ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__NewVa__202FA5B1] DEFAULT ((0)) FOR [NewValue]; GO +ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__Budge__5E1E2449] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ChargeVolumeChangeHistory] ADD CONSTRAINT [DF__ChargeVol__NewCh__7A9E6019] DEFAULT ((0)) FOR [ChargeVolumeID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ChargeVolumeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ChargeVolumeHistory] ( + [RowID] int NOT NULL, + [ChargeVolumeID] int NOT NULL, + [ActualYTDValue01] decimal NOT NULL, + [ActualYTDValue02] decimal NOT NULL, + [ActualYTDValue03] decimal NOT NULL, + [ActualYTDValue04] decimal NOT NULL, + [ActualYTDValue05] decimal NOT NULL, + [ActualYTDValue06] decimal NOT NULL, + [ActualYTDValue07] decimal NOT NULL, + [ActualYTDValue08] decimal NOT NULL, + [ActualYTDValue09] decimal NOT NULL, + [ActualYTDValue10] decimal NOT NULL, + [ActualYTDValue11] decimal NOT NULL, + [ActualYTDValue12] decimal NOT NULL, + [PriorYearActualValue01] decimal NOT NULL, + [PriorYearActualValue02] decimal NOT NULL, + [PriorYearActualValue03] decimal NOT NULL, + [PriorYearActualValue04] decimal NOT NULL, + [PriorYearActualValue05] decimal NOT NULL, + [PriorYearActualValue06] decimal NOT NULL, + [PriorYearActualValue07] decimal NOT NULL, + [PriorYearActualValue08] decimal NOT NULL, + [PriorYearActualValue09] decimal NOT NULL, + [PriorYearActualValue10] decimal NOT NULL, + [PriorYearActualValue11] decimal NOT NULL, + [PriorYearActualValue12] decimal NOT NULL, + [CurrentYearBudget01] decimal NOT NULL, + [CurrentYearBudget02] decimal NOT NULL, + [CurrentYearBudget03] decimal NOT NULL, + [CurrentYearBudget04] decimal NOT NULL, + [CurrentYearBudget05] decimal NOT NULL, + [CurrentYearBudget06] decimal NOT NULL, + [CurrentYearBudget07] decimal NOT NULL, + [CurrentYearBudget08] decimal NOT NULL, + [CurrentYearBudget09] decimal NOT NULL, + [CurrentYearBudget10] decimal NOT NULL, + [CurrentYearBudget11] decimal NOT NULL, + [CurrentYearBudget12] decimal NOT NULL, + [ActualYTDDollarValue01] decimal NOT NULL, + [ActualYTDDollarValue02] decimal NOT NULL, + [ActualYTDDollarValue03] decimal NOT NULL, + [ActualYTDDollarValue04] decimal NOT NULL, + [ActualYTDDollarValue05] decimal NOT NULL, + [ActualYTDDollarValue06] decimal NOT NULL, + [ActualYTDDollarValue07] decimal NOT NULL, + [ActualYTDDollarValue08] decimal NOT NULL, + [ActualYTDDollarValue09] decimal NOT NULL, + [ActualYTDDollarValue10] decimal NOT NULL, + [ActualYTDDollarValue11] decimal NOT NULL, + [ActualYTDDollarValue12] decimal NOT NULL, + [PriorYearActualDollarValue01] decimal NOT NULL, + [PriorYearActualDollarValue02] decimal NOT NULL, + [PriorYearActualDollarValue03] decimal NOT NULL, + [PriorYearActualDollarValue04] decimal NOT NULL, + [PriorYearActualDollarValue05] decimal NOT NULL, + [PriorYearActualDollarValue06] decimal NOT NULL, + [PriorYearActualDollarValue07] decimal NOT NULL, + [PriorYearActualDollarValue08] decimal NOT NULL, + [PriorYearActualDollarValue09] decimal NOT NULL, + [PriorYearActualDollarValue10] decimal NOT NULL, + [PriorYearActualDollarValue11] decimal NOT NULL, + [PriorYearActualDollarValue12] decimal NOT NULL, + [CurrentYearBudgetDollar01] decimal NOT NULL, + [CurrentYearBudgetDollar02] decimal NOT NULL, + [CurrentYearBudgetDollar03] decimal NOT NULL, + [CurrentYearBudgetDollar04] decimal NOT NULL, + [CurrentYearBudgetDollar05] decimal NOT NULL, + [CurrentYearBudgetDollar06] decimal NOT NULL, + [CurrentYearBudgetDollar07] decimal NOT NULL, + [CurrentYearBudgetDollar08] decimal NOT NULL, + [CurrentYearBudgetDollar09] decimal NOT NULL, + [CurrentYearBudgetDollar10] decimal NOT NULL, + [CurrentYearBudgetDollar11] decimal NOT NULL, + [CurrentYearBudgetDollar12] decimal NOT NULL, + [ActualYTDValueTotal] decimal NOT NULL, + [PriorYearActualValueTotal] decimal NOT NULL, + [CurrentYearBudgetTotal] decimal NOT NULL, + [ActualYTDDollarValueTotal] decimal NOT NULL, + [PriorYearActualDollarValueTotal] decimal NOT NULL, + [CurrentYearBudgetDollarTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_ChargeVolumeHistory] ON [fp].[ChargeVolumeHistory] ([ChargeVolumeID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[ChargeVolumeHistory] ([ChargeVolumeID]); +GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [FK_ChargeVolumeHistory_ChargeVolumeID] FOREIGN KEY ([ChargeVolumeID]) REFERENCES [fp].[ChargeVolume] ([ChargeVolumeID]); GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__006C4808] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__01606C41] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__0254907A] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__0348B4B3] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__043CD8EC] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__0530FD25] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__0625215E] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__07194597] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__080D69D0] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__09018E09] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__09F5B242] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__0AE9D67B] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__0BDDFAB4] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__0CD21EED] DEFAULT ((0)) FOR [ActualYTDDollarValue01]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__0DC64326] DEFAULT ((0)) FOR [ActualYTDDollarValue02]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__0EBA675F] DEFAULT ((0)) FOR [ActualYTDDollarValue03]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__0FAE8B98] DEFAULT ((0)) FOR [ActualYTDDollarValue04]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__10A2AFD1] DEFAULT ((0)) FOR [ActualYTDDollarValue05]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__1196D40A] DEFAULT ((0)) FOR [ActualYTDDollarValue06]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__128AF843] DEFAULT ((0)) FOR [ActualYTDDollarValue07]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__137F1C7C] DEFAULT ((0)) FOR [ActualYTDDollarValue08]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__147340B5] DEFAULT ((0)) FOR [ActualYTDDollarValue09]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__156764EE] DEFAULT ((0)) FOR [ActualYTDDollarValue10]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__165B8927] DEFAULT ((0)) FOR [ActualYTDDollarValue11]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__174FAD60] DEFAULT ((0)) FOR [ActualYTDDollarValue12]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__1843D199] DEFAULT ((0)) FOR [PriorYearActualDollarValue01]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__1937F5D2] DEFAULT ((0)) FOR [PriorYearActualDollarValue02]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__1A2C1A0B] DEFAULT ((0)) FOR [PriorYearActualDollarValue03]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__1B203E44] DEFAULT ((0)) FOR [PriorYearActualDollarValue04]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__1C14627D] DEFAULT ((0)) FOR [PriorYearActualDollarValue05]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__1D0886B6] DEFAULT ((0)) FOR [PriorYearActualDollarValue06]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__1DFCAAEF] DEFAULT ((0)) FOR [PriorYearActualDollarValue07]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__1EF0CF28] DEFAULT ((0)) FOR [PriorYearActualDollarValue08]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__1FE4F361] DEFAULT ((0)) FOR [PriorYearActualDollarValue09]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__20D9179A] DEFAULT ((0)) FOR [PriorYearActualDollarValue10]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__21CD3BD3] DEFAULT ((0)) FOR [PriorYearActualDollarValue11]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__22C1600C] DEFAULT ((0)) FOR [PriorYearActualDollarValue12]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__23B58445] DEFAULT ((0)) FOR [CurrentYearBudgetDollar01]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__24A9A87E] DEFAULT ((0)) FOR [CurrentYearBudgetDollar02]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__259DCCB7] DEFAULT ((0)) FOR [CurrentYearBudgetDollar03]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__2691F0F0] DEFAULT ((0)) FOR [CurrentYearBudgetDollar04]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__27861529] DEFAULT ((0)) FOR [CurrentYearBudgetDollar05]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__287A3962] DEFAULT ((0)) FOR [CurrentYearBudgetDollar06]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__296E5D9B] DEFAULT ((0)) FOR [CurrentYearBudgetDollar07]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__2A6281D4] DEFAULT ((0)) FOR [CurrentYearBudgetDollar08]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__2B56A60D] DEFAULT ((0)) FOR [CurrentYearBudgetDollar09]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__2C4ACA46] DEFAULT ((0)) FOR [CurrentYearBudgetDollar10]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__2D3EEE7F] DEFAULT ((0)) FOR [CurrentYearBudgetDollar11]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Curre__2E3312B8] DEFAULT ((0)) FOR [CurrentYearBudgetDollar12]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Charg__6988E2B0] DEFAULT ((0)) FOR [ChargeVolumeID]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__6A7D06E9] DEFAULT ((0)) FOR [ActualYTDValue01]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__6B712B22] DEFAULT ((0)) FOR [ActualYTDValue02]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__6C654F5B] DEFAULT ((0)) FOR [ActualYTDValue03]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__6D597394] DEFAULT ((0)) FOR [ActualYTDValue04]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__6E4D97CD] DEFAULT ((0)) FOR [ActualYTDValue05]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__6F41BC06] DEFAULT ((0)) FOR [ActualYTDValue06]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__7035E03F] DEFAULT ((0)) FOR [ActualYTDValue07]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__712A0478] DEFAULT ((0)) FOR [ActualYTDValue08]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__721E28B1] DEFAULT ((0)) FOR [ActualYTDValue09]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__73124CEA] DEFAULT ((0)) FOR [ActualYTDValue10]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__74067123] DEFAULT ((0)) FOR [ActualYTDValue11]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Actua__74FA955C] DEFAULT ((0)) FOR [ActualYTDValue12]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__75EEB995] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__76E2DDCE] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__77D70207] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__78CB2640] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__79BF4A79] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__7AB36EB2] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__7BA792EB] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__7C9BB724] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__7D8FDB5D] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__7E83FF96] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO +ALTER TABLE [fp].[ChargeVolumeHistory] ADD CONSTRAINT [DF__ChargeVol__Prior__7F7823CF] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ChargeVolumeSpreadUnlockData ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ChargeVolumeSpreadUnlockData] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [PatientClassID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [Version] timestamp NOT NULL, + [Value01] decimal NOT NULL, + [Value02] decimal NOT NULL, + [Value03] decimal NOT NULL, + [Value04] decimal NOT NULL, + [Value05] decimal NOT NULL, + [Value06] decimal NOT NULL, + [Value07] decimal NOT NULL, + [Value08] decimal NOT NULL, + [Value09] decimal NOT NULL, + [Value10] decimal NOT NULL, + [Value11] decimal NOT NULL, + [Value12] decimal NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [MSDRGID] int NOT NULL, + [UBRevCodeID] int NOT NULL, + [ServiceProviderID] int NOT NULL, + [ServiceProviderSpecialtyID] int NOT NULL, + [ServiceEntityID] int NOT NULL, + [PrimaryCPTID] int NOT NULL, + [BillingCPTID] int NOT NULL, + [PerformingProviderID] int NOT NULL, + [PerformingProviderSpecialtyID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__IsRec__00D263A9] DEFAULT ((0)) FOR [IsRecordDeleted]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Budge__0E95A7C4] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Entit__107DF036] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Depar__1172146F] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Patie__126638A8] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Servi__135A5CE1] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__AgeCo__144E811A] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Medic__1542A553] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Charg__1636C98C] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__172AEDC5] DEFAULT ((0)) FOR [Value01]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__181F11FE] DEFAULT ((0)) FOR [Value02]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__19133637] DEFAULT ((0)) FOR [Value03]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__1A075A70] DEFAULT ((0)) FOR [Value04]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__1AFB7EA9] DEFAULT ((0)) FOR [Value05]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__1BEFA2E2] DEFAULT ((0)) FOR [Value06]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__1CE3C71B] DEFAULT ((0)) FOR [Value07]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__1DD7EB54] DEFAULT ((0)) FOR [Value08]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__1ECC0F8D] DEFAULT ((0)) FOR [Value09]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__1FC033C6] DEFAULT ((0)) FOR [Value10]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__20B457FF] DEFAULT ((0)) FOR [Value11]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Value__21A87C38] DEFAULT ((0)) FOR [Value12]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Servi__27C21398] DEFAULT ((0)) FOR [ServiceEntityID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Prima__28B637D1] DEFAULT ((0)) FOR [PrimaryCPTID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Billi__29AA5C0A] DEFAULT ((0)) FOR [BillingCPTID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Perfo__2A9E8043] DEFAULT ((0)) FOR [PerformingProviderID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Perfo__2B92A47C] DEFAULT ((0)) FOR [PerformingProviderSpecialtyID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [df_ChargeVolumeSpreadUnlockData_AdjustmentGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__MSDRG__59838C5E] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__UBRev__5A77B097] DEFAULT ((0)) FOR [UBRevCodeID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Servi__5C5FF909] DEFAULT ((0)) FOR [ServiceProviderID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreadUnlockData] ADD CONSTRAINT [DF__ChargeVol__Servi__5D541D42] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ChargeVolumeSpreads ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ChargeVolumeSpreads] ( + [BudgetConfigID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [PatientClassID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [IsInactive] bit NOT NULL, + [SpreadPercentage01] decimal NULL, + [SpreadPercentage02] decimal NULL, + [SpreadPercentage03] decimal NULL, + [SpreadPercentage04] decimal NULL, + [SpreadPercentage05] decimal NULL, + [SpreadPercentage06] decimal NULL, + [SpreadPercentage07] decimal NULL, + [SpreadPercentage08] decimal NULL, + [SpreadPercentage09] decimal NULL, + [SpreadPercentage10] decimal NULL, + [SpreadPercentage11] decimal NULL, + [SpreadPercentage12] decimal NULL, + [TotalImportedValue] decimal NULL, + [SpreadHistoryGUID] uniqueidentifier NOT NULL, + [GlobalSpreadID] int NOT NULL, + [ChargeEntityID] int NOT NULL, + [MSDRGID] int NOT NULL, + [UBRevCodeID] int NOT NULL, + [CPTID] int NOT NULL, + [ServiceProviderID] int NOT NULL, + [ServiceProviderSpecialtyID] int NOT NULL, + [BillingProviderID] int NOT NULL, + [BillingProviderSpecialtyID] int NOT NULL, + PRIMARY KEY ([BudgetConfigID], [DepartmentID], [ServiceLineID], [ChargeCodeID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID]) +); +GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [FK_ChargeVolumeSpreads_History] FOREIGN KEY ([SpreadHistoryGUID]) REFERENCES [fp].[SpreadHistory] ([SpreadHistoryGUID]); GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [FK_FpChargeVolumeSpreads_AgeCohort] FOREIGN KEY ([AgeCohortID]) REFERENCES [fw].[DimAgeCohort] ([AgeCohortID]); GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [FK_FpChargeVolumeSpreads_ChargeCode] FOREIGN KEY ([ChargeCodeID]) REFERENCES [fw].[DimChargeCode] ([ChargeCodeID]); GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [FK_FpChargeVolumeSpreads_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [FK_FpChargeVolumeSpreads_MedicalSurgical] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [FK_FpChargeVolumeSpreads_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [FK_FpChargeVolumeSpreads_ServiceLine] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Budge__0FBED627] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Depar__10B2FA60] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Servi__129B42D2] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Charg__14838B44] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Patie__166BD3B6] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__AgeCo__18541C28] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Medic__1A3C649A] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__IsIna__1C24AD0C] DEFAULT ((0)) FOR [IsInactive]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__1D18D145] DEFAULT ((0)) FOR [SpreadPercentage01]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__1E0CF57E] DEFAULT ((0)) FOR [SpreadPercentage02]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__1F0119B7] DEFAULT ((0)) FOR [SpreadPercentage03]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__1FF53DF0] DEFAULT ((0)) FOR [SpreadPercentage04]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__20E96229] DEFAULT ((0)) FOR [SpreadPercentage05]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__21DD8662] DEFAULT ((0)) FOR [SpreadPercentage06]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__22D1AA9B] DEFAULT ((0)) FOR [SpreadPercentage07]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__23C5CED4] DEFAULT ((0)) FOR [SpreadPercentage08]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__24B9F30D] DEFAULT ((0)) FOR [SpreadPercentage09]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__25AE1746] DEFAULT ((0)) FOR [SpreadPercentage10]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__26A23B7F] DEFAULT ((0)) FOR [SpreadPercentage11]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Sprea__27965FB8] DEFAULT ((0)) FOR [SpreadPercentage12]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Total__288A83F1] DEFAULT ((0)) FOR [TotalImportedValue]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Globa__3A5F1B69] DEFAULT ((1)) FOR [GlobalSpreadID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Charg__457C93B1] DEFAULT ((0)) FOR [ChargeEntityID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__MSDRG__4670B7EA] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__UBRev__4764DC23] DEFAULT ((0)) FOR [UBRevCodeID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__CPTID__4859005C] DEFAULT ((0)) FOR [CPTID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Servi__494D2495] DEFAULT ((0)) FOR [ServiceProviderID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Servi__4A4148CE] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Billi__4B356D07] DEFAULT ((0)) FOR [BillingProviderID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [DF__ChargeVol__Billi__4C299140] DEFAULT ((0)) FOR [BillingProviderSpecialtyID]; GO +ALTER TABLE [fp].[ChargeVolumeSpreads] ADD CONSTRAINT [df_ChargeVolumeSpreads_SpreadHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SpreadHistoryGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.CustomReportLink ------------------ +--------------------------------------------- +CREATE TABLE [fp].[CustomReportLink] ( + [CustomReportLinkGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([CustomReportLinkGUID]) +); +GO +ALTER TABLE [fp].[CustomReportLink] ADD CONSTRAINT [FK_FpCustomReportLink_Report] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [fp].[CustomReportLink] ADD CONSTRAINT [DF__CustomRep__Custo__207E827E] DEFAULT (newid()) FOR [CustomReportLinkGUID]; GO +ALTER TABLE [fp].[CustomReportLink] ADD CONSTRAINT [df_CustomReportLink_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.DSSamplingMapping ------------------ +--------------------------------------------- +CREATE TABLE [fp].[DSSamplingMapping] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [FiscalYearTable] nvarchar(128) NOT NULL, + [FiscalYearColumn] nvarchar(128) NOT NULL, + [ExtractFiscalYearFromDate] bit NOT NULL, + [FiscalMonthTable] nvarchar(128) NOT NULL, + [FiscalMonthColumn] nvarchar(128) NOT NULL, + [ExtractFiscalMonthFromDate] bit NOT NULL, + [ServiceEntityTable] nvarchar(128) NOT NULL, + [ServiceEntityColumn] nvarchar(128) NOT NULL, + [ServiceLineTable] nvarchar(128) NOT NULL, + [ServiceLineColumn] nvarchar(128) NOT NULL, + [AgeCohortTable] nvarchar(128) NOT NULL, + [AgeCohortColumn] nvarchar(128) NOT NULL, + [ServiceLineDepartmentTable] nvarchar(128) NOT NULL, + [ServiceLineDepartmentColumn] nvarchar(128) NOT NULL, + [DepartmentTable] nvarchar(128) NOT NULL, + [DepartmentColumn] nvarchar(128) NOT NULL, + [UBRevCodeTable] nvarchar(128) NOT NULL, + [UBRevCodeColumn] nvarchar(128) NOT NULL, + [PrimaryCPTIDTable] nvarchar(128) NOT NULL, + [PrimaryCPTIDColumn] nvarchar(128) NOT NULL, + [BillingCPTIDTable] nvarchar(128) NOT NULL, + [BillingCPTIDColumn] nvarchar(128) NOT NULL, + [PrimaryPhysicianTable] nvarchar(128) NOT NULL, + [PrimaryPhysicianColumn] nvarchar(128) NOT NULL, + [PerformingPhysicianTable] nvarchar(128) NOT NULL, + [PerformingPhysicianColumn] nvarchar(128) NOT NULL, + [VolumeTable] nvarchar(128) NOT NULL, + [VolumeColumn] nvarchar(128) NOT NULL, + [MSDRGTable] nvarchar(128) NOT NULL, + [MSDRGColumn] nvarchar(128) NOT NULL, + [ServiceEntityIdentifierGuid] uniqueidentifier NOT NULL, + [ServiceLineIdentifierGuid] uniqueidentifier NOT NULL, + [AgeCohortIdentifierGuid] uniqueidentifier NOT NULL, + [ServiceLineDepartmentIdentifierGuid] uniqueidentifier NOT NULL, + [DepartmentIdentifierGuid] uniqueidentifier NOT NULL, + [UBRevCodeIdentifierGuid] uniqueidentifier NOT NULL, + [PrimaryCPTIDIdentifierGuid] uniqueidentifier NOT NULL, + [BillingCPTIDIdentifierGuid] uniqueidentifier NOT NULL, + [PrimaryPhysicianIdentifierGuid] uniqueidentifier NOT NULL, + [PerformingPhysicianIdentifierGuid] uniqueidentifier NOT NULL, + [MSDRGIdentifierGuid] uniqueidentifier NOT NULL, + [VolumeIdentifierGuid] uniqueidentifier NOT NULL, + [DateIdentifierGuid] uniqueidentifier NOT NULL, + [PatientClassTable] nvarchar(256) NOT NULL, + [PatientClassColumn] nvarchar(256) NOT NULL, + [PatientClassIdentifierGuid] uniqueidentifier NOT NULL, + [IsPatientClassConfigured] bit NOT NULL, + [MedSurgTable] nvarchar(256) NOT NULL, + [MedSurgColumn] nvarchar(256) NOT NULL, + [MedSurgIdentifierGuid] uniqueidentifier NOT NULL, + [IsMedSurgConfigured] bit NOT NULL, + [InsuranceTable] nvarchar(256) NOT NULL, + [InsuranceColumn] nvarchar(256) NOT NULL, + [InsuranceIdentifierGuid] uniqueidentifier NOT NULL, + [ClinicalIndicatorID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [IX_ClusteredUnique] ON [fp].[DSSamplingMapping] ([BudgetConfigID]); +GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF_DSSamplingMapping_ClinicalIndicatorID] DEFAULT ((0)) FOR [ClinicalIndicatorID]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Servi__1DAF64D0] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [ServiceEntityIdentifierGuid]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Servi__1EA38909] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [ServiceLineIdentifierGuid]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__AgeCo__1F97AD42] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [AgeCohortIdentifierGuid]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Servi__208BD17B] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [ServiceLineDepartmentIdentifierGuid]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Depar__217FF5B4] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [DepartmentIdentifierGuid]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__UBRev__227419ED] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [UBRevCodeIdentifierGuid]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Prima__23683E26] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [PrimaryCPTIDIdentifierGuid]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Billi__245C625F] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [BillingCPTIDIdentifierGuid]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Prima__25508698] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [PrimaryPhysicianIdentifierGuid]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Perfo__2644AAD1] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [PerformingPhysicianIdentifierGuid]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__MSDRG__2738CF0A] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [MSDRGIdentifierGuid]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Volum__282CF343] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [VolumeIdentifierGuid]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__DateI__2921177C] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [DateIdentifierGuid]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Fisca__306C6832] DEFAULT ('') FOR [FiscalYearTable]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Fisca__31608C6B] DEFAULT ('') FOR [FiscalYearColumn]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Extra__3254B0A4] DEFAULT ((0)) FOR [ExtractFiscalYearFromDate]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Fisca__3348D4DD] DEFAULT ('') FOR [FiscalMonthTable]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Fisca__343CF916] DEFAULT ('') FOR [FiscalMonthColumn]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Extra__35311D4F] DEFAULT ((0)) FOR [ExtractFiscalMonthFromDate]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Servi__36254188] DEFAULT ('') FOR [ServiceEntityTable]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Servi__371965C1] DEFAULT ('') FOR [ServiceEntityColumn]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Servi__380D89FA] DEFAULT ('') FOR [ServiceLineTable]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Servi__3901AE33] DEFAULT ('') FOR [ServiceLineColumn]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__AgeCo__39F5D26C] DEFAULT ('') FOR [AgeCohortTable]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__AgeCo__3AE9F6A5] DEFAULT ('') FOR [AgeCohortColumn]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Servi__3BDE1ADE] DEFAULT ('') FOR [ServiceLineDepartmentTable]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Servi__3CD23F17] DEFAULT ('') FOR [ServiceLineDepartmentColumn]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Depar__3DC66350] DEFAULT ('') FOR [DepartmentTable]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Depar__3EBA8789] DEFAULT ('') FOR [DepartmentColumn]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__UBRev__3FAEABC2] DEFAULT ('') FOR [UBRevCodeTable]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__UBRev__40A2CFFB] DEFAULT ('') FOR [UBRevCodeColumn]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Prima__4196F434] DEFAULT ('') FOR [PrimaryCPTIDTable]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Prima__428B186D] DEFAULT ('') FOR [PrimaryCPTIDColumn]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Billi__437F3CA6] DEFAULT ('') FOR [BillingCPTIDTable]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Billi__447360DF] DEFAULT ('') FOR [BillingCPTIDColumn]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Prima__45678518] DEFAULT ('') FOR [PrimaryPhysicianTable]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Prima__465BA951] DEFAULT ('') FOR [PrimaryPhysicianColumn]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Perfo__474FCD8A] DEFAULT ('') FOR [PerformingPhysicianTable]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Perfo__4843F1C3] DEFAULT ('') FOR [PerformingPhysicianColumn]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Volum__493815FC] DEFAULT ('') FOR [VolumeTable]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Volum__4A2C3A35] DEFAULT ('') FOR [VolumeColumn]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__MSDRG__4B205E6E] DEFAULT ('') FOR [MSDRGTable]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__MSDRG__4C1482A7] DEFAULT ('') FOR [MSDRGColumn]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Patie__63F7C487] DEFAULT ('') FOR [PatientClassTable]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Patie__64EBE8C0] DEFAULT ('') FOR [PatientClassColumn]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Patie__65E00CF9] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [PatientClassIdentifierGuid]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__IsPat__66D43132] DEFAULT ((0)) FOR [IsPatientClassConfigured]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__MedSu__67C8556B] DEFAULT ('') FOR [MedSurgTable]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__MedSu__68BC79A4] DEFAULT ('') FOR [MedSurgColumn]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__MedSu__69B09DDD] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [MedSurgIdentifierGuid]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__IsMed__6AA4C216] DEFAULT ((0)) FOR [IsMedSurgConfigured]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Insur__6DA12A52] DEFAULT ('') FOR [InsuranceTable]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Insur__6E954E8B] DEFAULT ('') FOR [InsuranceColumn]; GO +ALTER TABLE [fp].[DSSamplingMapping] ADD CONSTRAINT [DF__DSSamplin__Insur__6F8972C4] DEFAULT (CONVERT([uniqueidentifier],CONVERT([binary],(0)))) FOR [InsuranceIdentifierGuid]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.DataRefreshTargetThreshold ------------------ +--------------------------------------------- +CREATE TABLE [fp].[DataRefreshTargetThreshold] ( + [ClassName] nvarchar(300) NOT NULL, + [Threshold] int NOT NULL +); +GO +ALTER TABLE [fp].[DataRefreshTargetThreshold] ADD CONSTRAINT [DF__DataRefre__Class__178AE078] DEFAULT ('') FOR [ClassName]; GO +ALTER TABLE [fp].[DataRefreshTargetThreshold] ADD CONSTRAINT [DF__DataRefre__Thres__187F04B1] DEFAULT ((0)) FOR [Threshold]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.DataTransferConversionRates ------------------ +--------------------------------------------- +CREATE TABLE [fp].[DataTransferConversionRates] ( + [RowID] int NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [TimeClassID] tinyint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [Value] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[DataTransferConversionRates] ADD CONSTRAINT [FK_DataTransferConversionRates_BudgetConfigGUID] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[DataTransferConversionRates] ADD CONSTRAINT [FK_DataTransferConversionRates_FiscalMonthID] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO +ALTER TABLE [fp].[DataTransferConversionRates] ADD CONSTRAINT [FK_DataTransferConversionRates_TimeClassID] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [fp].[DataTransferConversionRates] ADD CONSTRAINT [DF__DataTrans__Budge__544C37FA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[DataTransferConversionRates] ADD CONSTRAINT [DF__DataTrans__TimeC__55405C33] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[DataTransferConversionRates] ADD CONSTRAINT [DF__DataTrans__Fisca__5634806C] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[DataTransferConversionRates] ADD CONSTRAINT [DF__DataTrans__Value__5728A4A5] DEFAULT ((0)) FOR [Value]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.DataTransferErrorLog ------------------ +--------------------------------------------- +CREATE TABLE [fp].[DataTransferErrorLog] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityCode] nvarchar(200) NOT NULL, + [DepartmentCode] nvarchar(100) NOT NULL, + [AccountCode] nvarchar(40) NOT NULL, + [PatientClassCode] nvarchar(100) NOT NULL, + [PayorCode] nvarchar(100) NOT NULL, + [FileTransferType] nvarchar(100) NOT NULL, + [ExecutionDate] datetime NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[DataTransferErrorLog] ADD CONSTRAINT [DF__DataTrans__Budge__78899870] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[DataTransferErrorLog] ADD CONSTRAINT [DF__DataTrans__Entit__797DBCA9] DEFAULT ('') FOR [EntityCode]; GO +ALTER TABLE [fp].[DataTransferErrorLog] ADD CONSTRAINT [DF__DataTrans__Depar__7A71E0E2] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [fp].[DataTransferErrorLog] ADD CONSTRAINT [DF__DataTrans__Accou__7B66051B] DEFAULT ('') FOR [AccountCode]; GO +ALTER TABLE [fp].[DataTransferErrorLog] ADD CONSTRAINT [DF__DataTrans__Patie__7C5A2954] DEFAULT ('') FOR [PatientClassCode]; GO +ALTER TABLE [fp].[DataTransferErrorLog] ADD CONSTRAINT [DF__DataTrans__Payor__7D4E4D8D] DEFAULT ('') FOR [PayorCode]; GO +ALTER TABLE [fp].[DataTransferErrorLog] ADD CONSTRAINT [DF__DataTrans__FileT__7E4271C6] DEFAULT ('') FOR [FileTransferType]; GO +ALTER TABLE [fp].[DataTransferErrorLog] ADD CONSTRAINT [DF__DataTrans__Execu__7F3695FF] DEFAULT ('1900-01-01T00:00:00') FOR [ExecutionDate]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.DeductionsFlexingConfig ------------------ +--------------------------------------------- +CREATE TABLE [fp].[DeductionsFlexingConfig] ( + [EntityGroupConfigGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [FlexMethodID] smallint NOT NULL, + PRIMARY KEY ([EntityGroupConfigGUID], [DepartmentID]) +); +GO +ALTER TABLE [fp].[DeductionsFlexingConfig] ADD CONSTRAINT [FK__Deduction__Depar__3DE4C833] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[DeductionsFlexingConfig] ADD CONSTRAINT [df_DeductionsFlexingConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO +ALTER TABLE [fp].[DeductionsFlexingConfig] ADD CONSTRAINT [DF__Deduction__Depar__3A008D9A] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[DeductionsFlexingConfig] ADD CONSTRAINT [DF__Deduction__FlexM__3AF4B1D3] DEFAULT ((0)) FOR [FlexMethodID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.DepartmentChargeAdjustmentImport ------------------ +--------------------------------------------- +CREATE TABLE [fp].[DepartmentChargeAdjustmentImport] ( + [RowID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [PatientClassID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [Value] decimal NOT NULL, + [Version] timestamp NOT NULL, + [EntityID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [ServiceEntityID] int NOT NULL, + [MSDRGID] int NOT NULL, + [UBRevCodeID] int NOT NULL, + [PrimaryCPTID] int NOT NULL, + [ServiceProviderID] int NOT NULL, + [ServiceProviderSpecialtyID] int NOT NULL, + [PerformingProviderID] int NOT NULL, + [PerformingProviderSpecialtyID] int NOT NULL, + [BillingCPTID] int NOT NULL, + [AdjustmentID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_AdjustmentID] ON [fp].[DepartmentChargeAdjustmentImport] ([AdjustmentID]); +GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__Servi__1D448525] DEFAULT ((0)) FOR [ServiceEntityID]; GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__MSDRG__1E38A95E] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__UBRev__1F2CCD97] DEFAULT ((0)) FOR [UBRevCodeID]; GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__Prima__2020F1D0] DEFAULT ((0)) FOR [PrimaryCPTID]; GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__Servi__21151609] DEFAULT ((0)) FOR [ServiceProviderID]; GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__Servi__22093A42] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__Perfo__22FD5E7B] DEFAULT ((0)) FOR [PerformingProviderID]; GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__Adjus__23B256E9] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__Perfo__23F182B4] DEFAULT ((0)) FOR [PerformingProviderSpecialtyID]; GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__Billi__26CDEF5F] DEFAULT ((0)) FOR [BillingCPTID]; GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__Adjus__2D04EE81] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__DepartmentChargeAdjImport__DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__DepartmentChargeAdjImport__ServiceLineID] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__DepartmentChargeAdjImport__PatientClassID] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__DepartmentChargeAdjImport__AgeCohortID] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__DepartmentChargeAdjImport__MedicalSurgicalID] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__DepartmentChargeAdjImport__ChargeCodeID] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__Entit__337CE1E6] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__DepartmentChargeAdjImport__BudgetChargeUnits] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__DepartmentChargeAdjImport_FiscalMonth] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF_DepartmentChargeAdjustmentImport_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[DepartmentChargeAdjustmentImport] ADD CONSTRAINT [DF__Departmen__IsRec__72844452] DEFAULT ((0)) FOR [IsRecordDeleted]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.DepartmentChargeVolumeAdjustment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[DepartmentChargeVolumeAdjustment] ( + [AdjustmentGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [Value] decimal NOT NULL, + [AdjustmentFilterJSON] nvarchar(max) NOT NULL, + [GroupingHierarchyJSON] nvarchar(max) NOT NULL, + [AdjustedProperty] nvarchar(100) NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [TimeClassID] tinyint NOT NULL, + [ClassificationGroupID] int NOT NULL, + [ClassificationCategoryID] int NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + [LastModifiedDateUtc] datetime NOT NULL, + [DimensionMemberJson] nvarchar(max) NOT NULL, + [AffectedDataCount] int NOT NULL, + [AdjustmentID] int NOT NULL, + [IsErrored] bit NOT NULL, + PRIMARY KEY ([AdjustmentGUID]) +); +GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [FK__Departmen__Budge__49A9B822] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF_DepartmentChargeVolumeAdjustment_ClassificationGroupID] DEFAULT ((0)) FOR [ClassificationGroupID]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF_DepartmentChargeVolumeAdjustment_ClassificationCategoryID] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Adjus__48B593E9] DEFAULT (newid()) FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__IsErr__4A054A5F] DEFAULT ((0)) FOR [IsErrored]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Adjus__4A9DDC5B] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Value__4B920094] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Adjus__4C8624CD] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Group__4D7A4906] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Adjus__4E6E6D3F] DEFAULT ('') FOR [AdjustedProperty]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Comme__4F629178] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Autho__5056B5B1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Group__5120BCB8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Autho__514AD9EA] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Dimen__61F9A225] DEFAULT ('') FOR [DimensionMemberJson]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__Affec__66BE5742] DEFAULT ((0)) FOR [AffectedDataCount]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__IsRec__6DBF8F35] DEFAULT ((0)) FOR [IsRecordDeleted]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__DateC__6DD56925] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF__Departmen__LastM__6EC98D5E] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment] ADD CONSTRAINT [DF_DepartmentChargeVolumeAdjustment_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.DepartmentChargeVolumeAdjustment_backup ------------------ +--------------------------------------------- +CREATE TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ( + [AdjustmentGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [Value] decimal NOT NULL, + [AdjustmentFilterJSON] nvarchar(max) NOT NULL, + [GroupingHierarchyJSON] nvarchar(max) NOT NULL, + [AdjustedProperty] nvarchar(100) NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [LastModifiedDate] datetime NOT NULL, + [DateCreatedUTC] datetime NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [TimeClassID] tinyint NOT NULL, + PRIMARY KEY ([AdjustmentGUID]) +); +GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [FK__Departmen__Budge__6E120121] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__Adjus__62A04E75] DEFAULT (newid()) FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__Adjus__639472AE] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__Value__648896E7] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__Adjus__657CBB20] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__Group__6670DF59] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__Adjus__67650392] DEFAULT ('') FOR [AdjustedProperty]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__Comme__685927CB] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__Autho__694D4C04] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__Autho__6A41703D] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__LastM__6B359476] DEFAULT (getdate()) FOR [LastModifiedDate]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__DateC__6C29B8AF] DEFAULT (getdate()) FOR [DateCreatedUTC]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF__Departmen__Group__6D1DDCE8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[DepartmentChargeVolumeAdjustment_backup] ADD CONSTRAINT [DF_DepartmentChargeVolumeAdjustmentBackup_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.DepartmentConfig ------------------ +--------------------------------------------- +CREATE TABLE [fp].[DepartmentConfig] ( + [DepartmentConfigGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [UpdatedDate] datetime NOT NULL, + [EntityGroupConfigGUID] uniqueidentifier NOT NULL, + [HasStatistics] bit NOT NULL, + [HasRevenueAndDeductions] bit NOT NULL, + [HasOtherRevenue] bit NOT NULL, + [HasRoster] bit NOT NULL, + [HasStaffing] bit NOT NULL, + [HasBenefits] bit NOT NULL, + [HasNonStaffingExpenses] bit NOT NULL, + [HasZeroBasedExpenses] bit NOT NULL, + PRIMARY KEY ([DepartmentConfigGUID]) +); + +CREATE NONCLUSTERED INDEX [NCNU_DepartmentConfig_DepartmentID] ON [fp].[DepartmentConfig] ([DepartmentID]); +CREATE NONCLUSTERED INDEX [NCNU_DepartmentConfig_EntityGroupConfigGUID] ON [fp].[DepartmentConfig] ([EntityGroupConfigGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [UC_FP_DepartmentConfig_DeptID_EGC] ON [fp].[DepartmentConfig] ([DepartmentID], [EntityGroupConfigGUID]); +GO +ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [FK__Departmen__Depar__2393C03C] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [FK__Departmen__Entit__3983015B] FOREIGN KEY ([EntityGroupConfigGUID]) REFERENCES [fp].[EntityGroupConfig] ([EntityGroupConfigGUID]); GO +ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [DF__Departmen__HasZe__1B47F971] DEFAULT ((0)) FOR [HasZeroBasedExpenses]; GO +ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [DF__Departmen__Depar__229F9C03] DEFAULT (newid()) FOR [DepartmentConfigGUID]; GO +ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [DF__Departmen__Updat__257C08AE] DEFAULT ('1900-01-01') FOR [UpdatedDate]; GO +ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [DF__Departmen__HasSt__3A772594] DEFAULT ((0)) FOR [HasStatistics]; GO +ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [DF__Departmen__HasRe__3B6B49CD] DEFAULT ((0)) FOR [HasRevenueAndDeductions]; GO +ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [DF__Departmen__HasOt__3C5F6E06] DEFAULT ((0)) FOR [HasOtherRevenue]; GO +ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [DF__Departmen__HasRo__3D53923F] DEFAULT ((0)) FOR [HasRoster]; GO +ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [DF__Departmen__HasSt__3E47B678] DEFAULT ((0)) FOR [HasStaffing]; GO +ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [DF__Departmen__HasBe__3F3BDAB1] DEFAULT ((0)) FOR [HasBenefits]; GO +ALTER TABLE [fp].[DepartmentConfig] ADD CONSTRAINT [DF__Departmen__HasNo__402FFEEA] DEFAULT ((0)) FOR [HasNonStaffingExpenses]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.DepartmentLevelConfiguration ------------------ +--------------------------------------------- +CREATE TABLE [fp].[DepartmentLevelConfiguration] ( + [BudgetConfigID] int NOT NULL, + [DepartmentID] int NOT NULL, + [IsUsingProviderStats] bit NOT NULL, + [IsUsingProviderStaffing] bit NOT NULL, + PRIMARY KEY ([BudgetConfigID], [DepartmentID]) +); +GO +ALTER TABLE [fp].[DepartmentLevelConfiguration] ADD CONSTRAINT [FK_DepartmentLevelConfiguration_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[DepartmentLevelConfiguration] ADD CONSTRAINT [DF__Departmen__Budge__7868D188] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[DepartmentLevelConfiguration] ADD CONSTRAINT [DF__Departmen__Depar__795CF5C1] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[DepartmentLevelConfiguration] ADD CONSTRAINT [DF__Departmen__IsUsi__7A5119FA] DEFAULT ((0)) FOR [IsUsingProviderStats]; GO +ALTER TABLE [fp].[DepartmentLevelConfiguration] ADD CONSTRAINT [DF__Departmen__IsUsi__7B453E33] DEFAULT ((0)) FOR [IsUsingProviderStaffing]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.DependentStatisticsAccount ------------------ +--------------------------------------------- +CREATE TABLE [fp].[DependentStatisticsAccount] ( + [BudgetConfigID] int NOT NULL, + [DependentAccountID] int NOT NULL, + [DriverAccountID] int NOT NULL, + [DependentStatisticsAccountID] int NOT NULL, + [SourceDepartmentID] int NOT NULL, + [SourceDepartmentPath] nvarchar(max) NOT NULL, + [IsNewRecord] bit NOT NULL, + PRIMARY KEY ([DependentStatisticsAccountID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[DependentStatisticsAccount] ([BudgetConfigID], [DependentAccountID], [DriverAccountID], [SourceDepartmentID]); +GO +ALTER TABLE [fp].[DependentStatisticsAccount] ADD CONSTRAINT [df_SourceDepartmentID] DEFAULT ((-1)) FOR [SourceDepartmentID]; GO +ALTER TABLE [fp].[DependentStatisticsAccount] ADD CONSTRAINT [DF__Dependent__Sourc__0FB97890] DEFAULT ('') FOR [SourceDepartmentPath]; GO +ALTER TABLE [fp].[DependentStatisticsAccount] ADD CONSTRAINT [DF__Dependent__IsNew__35DFECCF] DEFAULT ((0)) FOR [IsNewRecord]; GO +ALTER TABLE [fp].[DependentStatisticsAccount] ADD CONSTRAINT [DF__Dependent__Budge__611B57DC] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[DependentStatisticsAccount] ADD CONSTRAINT [DF__Dependent__Depen__620F7C15] DEFAULT ((0)) FOR [DependentAccountID]; GO +ALTER TABLE [fp].[DependentStatisticsAccount] ADD CONSTRAINT [DF__Dependent__Drive__6303A04E] DEFAULT ((0)) FOR [DriverAccountID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.DependentStatisticsAccountDepartment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[DependentStatisticsAccountDepartment] ( + [RowID] int NOT NULL, + [DependentStatisticsAccountID] int NOT NULL, + [DepartmentID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[DependentStatisticsAccountDepartment] ADD CONSTRAINT [FK_DependentStatisticsAccountDepartment_DependentStatisticsAccountID] FOREIGN KEY ([DependentStatisticsAccountID]) REFERENCES [fp].[DependentStatisticsAccount] ([DependentStatisticsAccountID]); GO +ALTER TABLE [fp].[DependentStatisticsAccountDepartment] ADD CONSTRAINT [DF__Dependent__Depen__1295E53B] DEFAULT ((0)) FOR [DependentStatisticsAccountID]; GO +ALTER TABLE [fp].[DependentStatisticsAccountDepartment] ADD CONSTRAINT [DF__Dependent__Depar__138A0974] DEFAULT ((0)) FOR [DepartmentID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.DependentStatisticsAccountScoreDepartment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[DependentStatisticsAccountScoreDepartment] ( + [RowID] int NOT NULL, + [DependentStatisticsAccountID] int NOT NULL, + [ScoreValue] nvarchar(max) NOT NULL, + [Name] nvarchar(1000) NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[DependentStatisticsAccountScoreDepartment] ADD CONSTRAINT [FK_DependentStatisticsAccountScoreDepartment_DependentStatisticsAccountID] FOREIGN KEY ([DependentStatisticsAccountID]) REFERENCES [fp].[DependentStatisticsAccount] ([DependentStatisticsAccountID]); GO +ALTER TABLE [fp].[DependentStatisticsAccountScoreDepartment] ADD CONSTRAINT [DF__Dependent__Depen__1B2B2B3C] DEFAULT ((0)) FOR [DependentStatisticsAccountID]; GO +ALTER TABLE [fp].[DependentStatisticsAccountScoreDepartment] ADD CONSTRAINT [DF__Dependent__Score__1C1F4F75] DEFAULT ('') FOR [ScoreValue]; GO +ALTER TABLE [fp].[DependentStatisticsAccountScoreDepartment] ADD CONSTRAINT [DF__DependentS__Name__1D1373AE] DEFAULT ('') FOR [Name]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.DimCategory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[DimCategory] ( + [CategoryID] int NOT NULL, + [Category] varchar(50) NOT NULL +); +GO +ALTER TABLE [fp].[DimCategory] ADD CONSTRAINT [DF__DimCatego__Categ__62BB1E39] DEFAULT ('') FOR [Category]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.DimItemizationDataType ------------------ +--------------------------------------------- +CREATE TABLE [fp].[DimItemizationDataType] ( + [ItemizationDataTypeID] int NOT NULL, + [Name] nvarchar(100) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([ItemizationDataTypeID]) +); +GO +ALTER TABLE [fp].[DimItemizationDataType] ADD CONSTRAINT [DF__DimItemiza__Name__50BAD2E1] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fp].[DimItemizationDataType] ADD CONSTRAINT [DF__DimItemiz__Membe__51AEF71A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MemberGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.DimSubAccountCategory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[DimSubAccountCategory] ( + [HistoryItemGUID] uniqueidentifier NOT NULL, + [SubAccountCategoryID] int NOT NULL, + [Description] nvarchar(200) NOT NULL, + [CategoryRollUp] nvarchar(200) NOT NULL, + [FullDescription] nvarchar(400) NOT NULL, + [TransactionID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([SubAccountCategoryID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [UQ_DimSubAccountCategory_Description] ON [fp].[DimSubAccountCategory] ([Description]); +GO +ALTER TABLE [fp].[DimSubAccountCategory] ADD CONSTRAINT [DF__DimSubAcc__Histo__302F9E6C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fp].[DimSubAccountCategory] ADD CONSTRAINT [DF__DimSubAcc__Descr__3217E6DE] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fp].[DimSubAccountCategory] ADD CONSTRAINT [DF__DimSubAcc__Categ__330C0B17] DEFAULT ('') FOR [CategoryRollUp]; GO +ALTER TABLE [fp].[DimSubAccountCategory] ADD CONSTRAINT [DF__DimSubAcc__FullD__34002F50] DEFAULT ('') FOR [FullDescription]; GO +ALTER TABLE [fp].[DimSubAccountCategory] ADD CONSTRAINT [DF__DimSubAcc__Trans__34F45389] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fp].[DimSubAccountCategory] ADD CONSTRAINT [DF__DimSubAcc__Membe__35E877C2] DEFAULT (newid()) FOR [MemberGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.EmployeeBudgetingNewEmployee ------------------ +--------------------------------------------- +CREATE TABLE [fp].[EmployeeBudgetingNewEmployee] ( + [RowID] int NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [EmployeeNumber] nvarchar(400) NOT NULL, + [FiscalYearID] smallint NULL, + [EmployeeID] int NOT NULL, + [JobCodeID] int NOT NULL, + [HireDateUTC] datetime NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[EmployeeBudgetingNewEmployee] ADD CONSTRAINT [DF__EmployeeB__Budge__3DF21730] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[EmployeeBudgetingNewEmployee] ADD CONSTRAINT [DF__EmployeeB__Fisca__3EE63B69] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[EmployeeBudgetingNewEmployee] ADD CONSTRAINT [DF__EmployeeB__Comme__3FDA5FA2] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[EmployeeBudgetingNewEmployee] ADD CONSTRAINT [DF__EmployeeB__Emplo__40CE83DB] DEFAULT ('') FOR [EmployeeNumber]; GO +ALTER TABLE [fp].[EmployeeBudgetingNewEmployee] ADD CONSTRAINT [DF__EmployeeB__Fisca__41C2A814] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[EmployeeBudgetingNewEmployee] ADD CONSTRAINT [DF__EmployeeB__Emplo__42B6CC4D] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[EmployeeBudgetingNewEmployee] ADD CONSTRAINT [DF__EmployeeB__JobCo__43AAF086] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[EmployeeBudgetingNewEmployee] ADD CONSTRAINT [DF__EmployeeB__HireD__449F14BF] DEFAULT (getutcdate()) FOR [HireDateUTC]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.EngineLog ------------------ +--------------------------------------------- +CREATE TABLE [fp].[EngineLog] ( + [RequestGUID] uniqueidentifier NOT NULL, + [StepID] int NOT NULL, + [AttemptID] int NOT NULL, + [StepName] nvarchar(300) NOT NULL, + [ClassName] nvarchar(300) NOT NULL, + [SourceDimensionalityJSON] nvarchar(max) NOT NULL, + [OptionsJSON] nvarchar(max) NOT NULL, + [DateStarted] datetime NOT NULL, + [DateEnded] datetime NOT NULL, + [Status] tinyint NOT NULL, + [ErrorMessage] nvarchar(max) NOT NULL, + [StackTrace] nvarchar(max) NOT NULL, + [AffectedDepartments] nvarchar(max) NOT NULL, + [AffectedDepartmentCount] int NOT NULL, + PRIMARY KEY ([RequestGUID], [AttemptID], [StepID]) +); +GO +ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__Affec__54A3062D] DEFAULT ((0)) FOR [AffectedDepartmentCount]; GO +ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__Reque__6F1DC7C2] DEFAULT (newid()) FOR [RequestGUID]; GO +ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__StepI__7011EBFB] DEFAULT ((0)) FOR [StepID]; GO +ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__Attem__71061034] DEFAULT ((0)) FOR [AttemptID]; GO +ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__StepN__71FA346D] DEFAULT ('') FOR [StepName]; GO +ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__Class__72EE58A6] DEFAULT ('') FOR [ClassName]; GO +ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__Sourc__73E27CDF] DEFAULT ('') FOR [SourceDimensionalityJSON]; GO +ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__Optio__74D6A118] DEFAULT ('') FOR [OptionsJSON]; GO +ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__DateS__75CAC551] DEFAULT ('1900-01-01T00:00:00') FOR [DateStarted]; GO +ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__DateE__76BEE98A] DEFAULT ('1900-01-01T00:00:00') FOR [DateEnded]; GO +ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__Statu__77B30DC3] DEFAULT ((0)) FOR [Status]; GO +ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__Error__78A731FC] DEFAULT ('') FOR [ErrorMessage]; GO +ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__Stack__799B5635] DEFAULT ('') FOR [StackTrace]; GO +ALTER TABLE [fp].[EngineLog] ADD CONSTRAINT [DF__EngineLog__Affec__7A8F7A6E] DEFAULT ('') FOR [AffectedDepartments]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.EntityGroupConfig ------------------ +--------------------------------------------- +CREATE TABLE [fp].[EntityGroupConfig] ( + [EntityGroupConfigGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NULL, + [Comments] nvarchar(1000) NULL, + [AccountTimeClassID] tinyint NOT NULL, + [AccountFiscalYearID] smallint NOT NULL, + [PayrollTimeClassID] tinyint NOT NULL, + [PayrollFiscalYearID] smallint NOT NULL, + [ServiceLineEncounterTimeClassID] tinyint NOT NULL, + [ServiceLineEncounterFiscalYearID] smallint NOT NULL, + [DepartmentChargeVolumeTimeClassID] tinyint NOT NULL, + [DepartmentChargeVolumeFiscalYearID] smallint NOT NULL, + [AccountLastSampled] datetime NOT NULL, + [PayrollLastSampled] datetime NOT NULL, + [ServiceLineEncounterLastSampled] datetime NOT NULL, + [DepartmentChargeVolumeLastSampled] datetime NOT NULL, + [CostingConfigGUID] uniqueidentifier NOT NULL, + [CostingConfigTimeClassID] tinyint NOT NULL, + [DateModified] smalldatetime NULL, + [DatePublished] smalldatetime NULL, + [BenefitsTimeClassID] tinyint NOT NULL, + [BenefitsFiscalYearID] smallint NOT NULL, + [BenefitsLastSampled] datetime NOT NULL, + [IsMarkedForDeletion] bit NOT NULL, + [StatisticsTimeClassID] tinyint NOT NULL, + [StatisticsFiscalYearID] smallint NOT NULL, + [StatisticsLastSampled] datetime NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [IsBudgetLockDown] bit NOT NULL, + [IsRosterUsed] bit NOT NULL, + [StatisticsModel] smallint NOT NULL, + [RevenueAndDeductionsTimeClassID] tinyint NOT NULL, + [RevenueAndDeductionsFiscalYearID] smallint NOT NULL, + [RevenueAndDeductionsLastSampled] datetime NOT NULL, + [IsPatientActivityFlexingForStaffing] bit NOT NULL, + [IsPatientActivityFlexingForNonStaffing] bit NOT NULL, + [ParentEntityGroupConfigGuid] uniqueidentifier NOT NULL, + [IsPayorGroupUsedForCrosswalk] bit NOT NULL, + PRIMARY KEY ([EntityGroupConfigGUID]) +); +GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__IsRos__05843A68] DEFAULT ((0)) FOR [IsRosterUsed]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__IsMar__302C3F46] DEFAULT ((0)) FOR [IsMarkedForDeletion]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Stati__321487B8] DEFAULT ((0)) FOR [StatisticsTimeClassID]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Stati__3308ABF1] DEFAULT ((0)) FOR [StatisticsFiscalYearID]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Stati__33FCD02A] DEFAULT ('1/1/2000') FOR [StatisticsLastSampled]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Entit__3530202E] DEFAULT (newid()) FOR [EntityGroupConfigGUID]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Benef__369945B3] DEFAULT ((0)) FOR [BenefitsTimeClassID]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGrou__Name__371868A0] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Benef__378D69EC] DEFAULT ((0)) FOR [BenefitsFiscalYearID]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Comme__380C8CD9] DEFAULT ('') FOR [Comments]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Benef__38818E25] DEFAULT ('1/1/2000') FOR [BenefitsLastSampled]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Accou__3900B112] DEFAULT ((0)) FOR [AccountTimeClassID]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Accou__39F4D54B] DEFAULT ((0)) FOR [AccountFiscalYearID]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Payro__3AE8F984] DEFAULT ((0)) FOR [PayrollTimeClassID]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Payro__3BDD1DBD] DEFAULT ((0)) FOR [PayrollFiscalYearID]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Servi__3CD141F6] DEFAULT ((0)) FOR [ServiceLineEncounterTimeClassID]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [df_EntityGroupConfig_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Servi__3DC5662F] DEFAULT ((0)) FOR [ServiceLineEncounterFiscalYearID]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [df_EntityGroupConfig_CostingConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CostingConfigGUID]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Depar__3EB98A68] DEFAULT ((0)) FOR [DepartmentChargeVolumeTimeClassID]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [df_EntityGroupConfig_ParentEntityGroupConfigGuid] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentEntityGroupConfigGuid]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Depar__3FADAEA1] DEFAULT ((0)) FOR [DepartmentChargeVolumeFiscalYearID]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Accou__40A1D2DA] DEFAULT ('1/1/2000') FOR [AccountLastSampled]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Payro__4195F713] DEFAULT ('1/1/2000') FOR [PayrollLastSampled]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Servi__428A1B4C] DEFAULT ('1/1/2000') FOR [ServiceLineEncounterLastSampled]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__IsBud__430C6B95] DEFAULT ((0)) FOR [IsBudgetLockDown]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Depar__437E3F85] DEFAULT ('1/1/2000') FOR [DepartmentChargeVolumeLastSampled]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__Costi__465AAC30] DEFAULT ((0)) FOR [CostingConfigTimeClassID]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__DateM__474ED069] DEFAULT (getdate()) FOR [DateModified]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__DateP__4842F4A2] DEFAULT (getdate()) FOR [DatePublished]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF_EntityGroupConfig_StatisticsModel] DEFAULT ((0)) FOR [StatisticsModel]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__IsPay__53430528] DEFAULT ((0)) FOR [IsPayorGroupUsedForCrosswalk]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF_EntityGroupConfig_RevenueAndDeductionsTimeClassID] DEFAULT ((0)) FOR [RevenueAndDeductionsTimeClassID]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF_EntityGroupConfig_RevenueAndDeductionsFiscalYearID] DEFAULT ((0)) FOR [RevenueAndDeductionsFiscalYearID]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF_EntityGroupConfig_RevenueAndDeductionsLastSampled] DEFAULT ('1/1/2000') FOR [RevenueAndDeductionsLastSampled]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__IsPat__68E03C1E] DEFAULT ((0)) FOR [IsPatientActivityFlexingForStaffing]; GO +ALTER TABLE [fp].[EntityGroupConfig] ADD CONSTRAINT [DF__EntityGro__IsPat__69D46057] DEFAULT ((0)) FOR [IsPatientActivityFlexingForNonStaffing]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.EntityGroupConfigMapping ------------------ +--------------------------------------------- +CREATE TABLE [fp].[EntityGroupConfigMapping] ( + [RowID] int NOT NULL, + [EntityGroupConfigGUID] uniqueidentifier NOT NULL, + [EntityID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[EntityGroupConfigMapping] ADD CONSTRAINT [df_EntityGroupConfigMapping_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO +ALTER TABLE [fp].[EntityGroupConfigMapping] ADD CONSTRAINT [DF__EntityGro__Entit__4C138586] DEFAULT ((0)) FOR [EntityID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ExecutiveSummary ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ExecutiveSummary] ( + [ExecutiveSummaryGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [SummaryType] smallint NOT NULL, + [DateModified] smalldatetime NOT NULL, + [LastAuthorGUID] uniqueidentifier NOT NULL, + [LastAuthorName] nvarchar(130) NOT NULL, + [Comments] nvarchar(max) NOT NULL, + PRIMARY KEY ([ExecutiveSummaryGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_ExecutiveSummary] ON [fp].[ExecutiveSummary] ([BudgetConfigGUID], [DepartmentID], [SummaryType]); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ExportHelpInfo ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ExportHelpInfo] ( + [ExportTypeID] smallint NOT NULL, + [ExportTypeName] varchar(50) NOT NULL, + [ColumnName] varchar(50) NOT NULL, + [ColumnDescription] varchar(200) NOT NULL, + [DataFormat] varchar(100) NOT NULL, + PRIMARY KEY ([ExportTypeID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FTERequest ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FTERequest] ( + [FTERequestGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [FTEAmount] decimal NOT NULL, + [StartFiscalMonthID] tinyint NOT NULL, + [WageRate] decimal NOT NULL, + [Comment] nvarchar(2000) NOT NULL, + [DateCreatedUTC] datetime NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([FTERequestGUID]) +); +GO +ALTER TABLE [fp].[FTERequest] ADD CONSTRAINT [FK__FTEReques__Budge__7EE78768] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[FTERequest] ADD CONSTRAINT [FK__FTEReques__Start__02B8184C] FOREIGN KEY ([StartFiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO +ALTER TABLE [fp].[FTERequest] ADD CONSTRAINT [FK_FTERequest_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[FTERequest] ADD CONSTRAINT [FK_FTERequest_JobCode] FOREIGN KEY ([JobCodeID]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO +ALTER TABLE [fp].[FTERequest] ADD CONSTRAINT [DF__FTEReques__FTEAm__01C3F413] DEFAULT ((0)) FOR [FTEAmount]; GO +ALTER TABLE [fp].[FTERequest] ADD CONSTRAINT [DF__FTEReques__WageR__03AC3C85] DEFAULT ((0)) FOR [WageRate]; GO +ALTER TABLE [fp].[FTERequest] ADD CONSTRAINT [DF__FTEReques__Group__04364C6A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[FTERequest] ADD CONSTRAINT [DF__FTEReques__Comme__04A060BE] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[FTERequest] ADD CONSTRAINT [DF__FTEReques__DateC__059484F7] DEFAULT ('1/1/1900') FOR [DateCreatedUTC]; GO +ALTER TABLE [fp].[FTERequest] ADD CONSTRAINT [DF__FTEReques__FTERe__7DF3632F] DEFAULT (newid()) FOR [FTERequestGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FTERequestDetail ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FTERequestDetail] ( + [FTERequestDetailGUID] uniqueidentifier NOT NULL, + [FTERequestGUID] uniqueidentifier NOT NULL, + [PayCodeGroupID] int NOT NULL, + [HoursMix] decimal NOT NULL, + PRIMARY KEY ([FTERequestDetailGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_UNIQUE] ON [fp].[FTERequestDetail] ([FTERequestGUID], [PayCodeGroupID]); +GO +ALTER TABLE [fp].[FTERequestDetail] ADD CONSTRAINT [FK__FTEReques__FTERe__16BF10F9] FOREIGN KEY ([FTERequestGUID]) REFERENCES [fp].[FTERequest] ([FTERequestGUID]); GO +ALTER TABLE [fp].[FTERequestDetail] ADD CONSTRAINT [FK__FTEReques__PayCo__17B33532] FOREIGN KEY ([PayCodeGroupID]) REFERENCES [fw].[DimPayCodeGroup] ([PayCodeGroupID]); GO +ALTER TABLE [fp].[FTERequestDetail] ADD CONSTRAINT [DF__FTEReques__FTERe__15CAECC0] DEFAULT (newid()) FOR [FTERequestDetailGUID]; GO +ALTER TABLE [fp].[FTERequestDetail] ADD CONSTRAINT [DF__FTEReques__Hours__344F73E0] DEFAULT ((0)) FOR [HoursMix]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactAccountVariability ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactAccountVariability] ( + [EntityGroupConfigGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FixedPercentage] decimal NOT NULL, + [RowID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [IX_FactAccountVariability] ON [fp].[FactAccountVariability] ([EntityGroupConfigGUID], [DepartmentID], [AccountID]); +GO +ALTER TABLE [fp].[FactAccountVariability] ADD CONSTRAINT [FK_FactAccountVariability_Account] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [fp].[FactAccountVariability] ADD CONSTRAINT [FK_FactAccountVariability_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[FactAccountVariability] ADD CONSTRAINT [DF_FactAccountVariability_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO +ALTER TABLE [fp].[FactAccountVariability] ADD CONSTRAINT [DF_FactAccountVariability_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactAccountVariability] ADD CONSTRAINT [DF_FactAccountVariability_AccountID] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[FactAccountVariability] ADD CONSTRAINT [DF_FactAccountVariability_FixedPercentage] DEFAULT ((0.0)) FOR [FixedPercentage]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactBenefits ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactBenefits] ( + [BenefitsID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [FlexMethodID] tinyint NOT NULL, + [AddDate] datetime NOT NULL, + [SampledBudget01] decimal NOT NULL, + [SampledBudget02] decimal NOT NULL, + [SampledBudget03] decimal NOT NULL, + [SampledBudget04] decimal NOT NULL, + [SampledBudget05] decimal NOT NULL, + [SampledBudget06] decimal NOT NULL, + [SampledBudget07] decimal NOT NULL, + [SampledBudget08] decimal NOT NULL, + [SampledBudget09] decimal NOT NULL, + [SampledBudget10] decimal NOT NULL, + [SampledBudget11] decimal NOT NULL, + [SampledBudget12] decimal NOT NULL, + [SampledBudgetTotal] decimal NOT NULL, + [SampledProjection01] decimal NOT NULL, + [SampledProjection02] decimal NOT NULL, + [SampledProjection03] decimal NOT NULL, + [SampledProjection04] decimal NOT NULL, + [SampledProjection05] decimal NOT NULL, + [SampledProjection06] decimal NOT NULL, + [SampledProjection07] decimal NOT NULL, + [SampledProjection08] decimal NOT NULL, + [SampledProjection09] decimal NOT NULL, + [SampledProjection10] decimal NOT NULL, + [SampledProjection11] decimal NOT NULL, + [SampledProjection12] decimal NOT NULL, + [SampledProjectionTotal] decimal NOT NULL, + [InitialBudget01] decimal NOT NULL, + [InitialBudget02] decimal NOT NULL, + [InitialBudget03] decimal NOT NULL, + [InitialBudget04] decimal NOT NULL, + [InitialBudget05] decimal NOT NULL, + [InitialBudget06] decimal NOT NULL, + [InitialBudget07] decimal NOT NULL, + [InitialBudget08] decimal NOT NULL, + [InitialBudget09] decimal NOT NULL, + [InitialBudget10] decimal NOT NULL, + [InitialBudget11] decimal NOT NULL, + [InitialBudget12] decimal NOT NULL, + [InitialBudgetTotal] decimal NOT NULL, + [InitialProjection01] decimal NOT NULL, + [InitialProjection02] decimal NOT NULL, + [InitialProjection03] decimal NOT NULL, + [InitialProjection04] decimal NOT NULL, + [InitialProjection05] decimal NOT NULL, + [InitialProjection06] decimal NOT NULL, + [InitialProjection07] decimal NOT NULL, + [InitialProjection08] decimal NOT NULL, + [InitialProjection09] decimal NOT NULL, + [InitialProjection10] decimal NOT NULL, + [InitialProjection11] decimal NOT NULL, + [InitialProjection12] decimal NOT NULL, + [InitialProjectionTotal] decimal NOT NULL, + [IsNew] bit NOT NULL, + [ChangeHistoryGroupingGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([BenefitsID]) +); + +CREATE UNIQUE CLUSTERED INDEX [IX_ClusteredUnique] ON [fp].[FactBenefits] ([BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [AccountID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_FactBenefits_Account] ON [fp].[FactBenefits] ([AccountID]) INCLUDE ([BenefitsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [FinancialReportingID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_FactBenefits_BudgetConfigID] ON [fp].[FactBenefits] ([BudgetConfigID]) INCLUDE ([EntityGroupConfigID], [EntityID], [DepartmentID], [FinancialReportingID], [AccountID], [UnitTypeID], [FlexMethodID], [InitialBudgetTotal], [InitialProjectionTotal]); +CREATE NONCLUSTERED INDEX [IX_FactBenefits_EntityGroupConfigID] ON [fp].[FactBenefits] ([EntityGroupConfigID]) INCLUDE ([BudgetConfigID], [EntityID], [DepartmentID], [FinancialReportingID], [AccountID], [UnitTypeID], [FlexMethodID], [InitialBudgetTotal], [InitialProjectionTotal]); +CREATE NONCLUSTERED INDEX [IX_FactBenefits_EntityID] ON [fp].[FactBenefits] ([EntityID]) INCLUDE ([BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [FinancialReportingID], [AccountID], [UnitTypeID], [FlexMethodID], [InitialBudgetTotal], [InitialProjectionTotal]); +CREATE NONCLUSTERED INDEX [IX_FactBenefits_DepartmentID] ON [fp].[FactBenefits] ([DepartmentID]) INCLUDE ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [FinancialReportingID], [AccountID], [UnitTypeID], [FlexMethodID], [InitialBudgetTotal], [InitialProjectionTotal]); +CREATE NONCLUSTERED INDEX [IX_FactBenefits_FinacialReportingID] ON [fp].[FactBenefits] ([FinancialReportingID]) INCLUDE ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [UnitTypeID], [FlexMethodID], [InitialBudgetTotal], [InitialProjectionTotal]); +CREATE NONCLUSTERED INDEX [IX_FactBenefits_AccountID] ON [fp].[FactBenefits] ([AccountID]) INCLUDE ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [FinancialReportingID], [UnitTypeID], [FlexMethodID], [InitialBudgetTotal], [InitialProjectionTotal]); +CREATE NONCLUSTERED INDEX [IX_FactBenefits_BudgetConfig] ON [fp].[FactBenefits] ([BudgetConfigID]) INCLUDE ([BenefitsID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_FactBenefits_Department] ON [fp].[FactBenefits] ([DepartmentID]) INCLUDE ([BenefitsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [AccountID], [FinancialReportingID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_FactBenefits_Entity] ON [fp].[FactBenefits] ([EntityID]) INCLUDE ([BenefitsID], [BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [AccountID], [FinancialReportingID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_FactBenefits_EntityGroupConfig] ON [fp].[FactBenefits] ([EntityGroupConfigID]) INCLUDE ([BenefitsID], [BudgetConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_FactBenefits_FinancialReporting] ON [fp].[FactBenefits] ([FinancialReportingID]) INCLUDE ([BenefitsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [UnitTypeID]); +GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [FK_FactBenefits_Account] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [FK_FactBenefits_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [FK_FactBenefits_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [FK_FactBenefits_FinancialReporting] FOREIGN KEY ([FinancialReportingID]) REFERENCES [ob].[DimFinancialReporting] ([FinancialReportingID]); GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [FK_FactBenefits_UnitType] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Budge__253F3EE8] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Entit__26336321] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Entit__2727875A] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Depar__281BAB93] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Accou__290FCFCC] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Finan__2A03F405] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__UnitT__2AF8183E] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__FlexM__2BEC3C77] DEFAULT ((0)) FOR [FlexMethodID]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__2DD484E9] DEFAULT ((0)) FOR [SampledBudget01]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__2EC8A922] DEFAULT ((0)) FOR [SampledBudget02]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__2FBCCD5B] DEFAULT ((0)) FOR [SampledBudget03]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__30B0F194] DEFAULT ((0)) FOR [SampledBudget04]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__IsNew__315AFD0A] DEFAULT ((0)) FOR [IsNew]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__31A515CD] DEFAULT ((0)) FOR [SampledBudget05]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__32993A06] DEFAULT ((0)) FOR [SampledBudget06]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__338D5E3F] DEFAULT ((0)) FOR [SampledBudget07]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__34818278] DEFAULT ((0)) FOR [SampledBudget08]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF_benefits_AddDate] DEFAULT ('1900-01-01') FOR [AddDate]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__3575A6B1] DEFAULT ((0)) FOR [SampledBudget09]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__3669CAEA] DEFAULT ((0)) FOR [SampledBudget10]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__375DEF23] DEFAULT ((0)) FOR [SampledBudget11]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__3852135C] DEFAULT ((0)) FOR [SampledBudget12]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__39463795] DEFAULT ((0)) FOR [SampledProjection01]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__3A3A5BCE] DEFAULT ((0)) FOR [SampledProjection02]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__3B2E8007] DEFAULT ((0)) FOR [SampledProjection03]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__3C22A440] DEFAULT ((0)) FOR [SampledProjection04]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Chang__3D123639] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ChangeHistoryGroupingGUID]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__3D16C879] DEFAULT ((0)) FOR [SampledProjection05]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__3E0AECB2] DEFAULT ((0)) FOR [SampledProjection06]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__3EFF10EB] DEFAULT ((0)) FOR [SampledProjection07]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__3FF33524] DEFAULT ((0)) FOR [SampledProjection08]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__40E7595D] DEFAULT ((0)) FOR [SampledProjection09]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__41DB7D96] DEFAULT ((0)) FOR [SampledProjection10]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__42CFA1CF] DEFAULT ((0)) FOR [SampledProjection11]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Sampl__43C3C608] DEFAULT ((0)) FOR [SampledProjection12]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__44B7EA41] DEFAULT ((0)) FOR [InitialBudget01]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__45AC0E7A] DEFAULT ((0)) FOR [InitialBudget02]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__46A032B3] DEFAULT ((0)) FOR [InitialBudget03]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__479456EC] DEFAULT ((0)) FOR [InitialBudget04]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__48887B25] DEFAULT ((0)) FOR [InitialBudget05]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__497C9F5E] DEFAULT ((0)) FOR [InitialBudget06]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__4A70C397] DEFAULT ((0)) FOR [InitialBudget07]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__4B64E7D0] DEFAULT ((0)) FOR [InitialBudget08]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__4C590C09] DEFAULT ((0)) FOR [InitialBudget09]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__4D4D3042] DEFAULT ((0)) FOR [InitialBudget10]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__4E41547B] DEFAULT ((0)) FOR [InitialBudget11]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__4F3578B4] DEFAULT ((0)) FOR [InitialBudget12]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__50299CED] DEFAULT ((0)) FOR [InitialProjection01]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__511DC126] DEFAULT ((0)) FOR [InitialProjection02]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__5211E55F] DEFAULT ((0)) FOR [InitialProjection03]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__53060998] DEFAULT ((0)) FOR [InitialProjection04]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__53FA2DD1] DEFAULT ((0)) FOR [InitialProjection05]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__54EE520A] DEFAULT ((0)) FOR [InitialProjection06]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__55E27643] DEFAULT ((0)) FOR [InitialProjection07]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__56D69A7C] DEFAULT ((0)) FOR [InitialProjection08]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__57CABEB5] DEFAULT ((0)) FOR [InitialProjection09]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__58BEE2EE] DEFAULT ((0)) FOR [InitialProjection10]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__59B30727] DEFAULT ((0)) FOR [InitialProjection11]; GO +ALTER TABLE [fp].[FactBenefits] ADD CONSTRAINT [DF__FactBenef__Initi__5AA72B60] DEFAULT ((0)) FOR [InitialProjection12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactBenefitsBudget ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactBenefitsBudget] ( + [RowID] int NOT NULL, + [BenefitsID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedValue01] decimal NOT NULL, + [AdjustedValue02] decimal NOT NULL, + [AdjustedValue03] decimal NOT NULL, + [AdjustedValue04] decimal NOT NULL, + [AdjustedValue05] decimal NOT NULL, + [AdjustedValue06] decimal NOT NULL, + [AdjustedValue07] decimal NOT NULL, + [AdjustedValue08] decimal NOT NULL, + [AdjustedValue09] decimal NOT NULL, + [AdjustedValue10] decimal NOT NULL, + [AdjustedValue11] decimal NOT NULL, + [AdjustedValue12] decimal NOT NULL, + [AdjustedValueTotal] decimal NOT NULL, + [FlexedValue01] decimal NOT NULL, + [FlexedValue02] decimal NOT NULL, + [FlexedValue03] decimal NOT NULL, + [FlexedValue04] decimal NOT NULL, + [FlexedValue05] decimal NOT NULL, + [FlexedValue06] decimal NOT NULL, + [FlexedValue07] decimal NOT NULL, + [FlexedValue08] decimal NOT NULL, + [FlexedValue09] decimal NOT NULL, + [FlexedValue10] decimal NOT NULL, + [FlexedValue11] decimal NOT NULL, + [FlexedValue12] decimal NOT NULL, + [FlexedValueTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_FactBenefitsBudget] ON [fp].[FactBenefitsBudget] ([BenefitsID], [BudgetPhaseID]); +CREATE NONCLUSTERED INDEX [IX_FactBenefitsBudget_BudgetPhaseID] ON [fp].[FactBenefitsBudget] ([BudgetPhaseID], [BenefitsID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[FactBenefitsBudget] ([BenefitsID], [BudgetPhaseID]); +GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [FK_FactBenefitsBudget_BenefitsID] FOREIGN KEY ([BenefitsID]) REFERENCES [fp].[FactBenefits] ([BenefitsID]); GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Benef__5D83980B] DEFAULT ((0)) FOR [BenefitsID]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__LockT__5E77BC44] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__LockF__5F6BE07D] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Budge__606004B6] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__615428EF] DEFAULT ((0)) FOR [AdjustedValue01]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__62484D28] DEFAULT ((0)) FOR [AdjustedValue02]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__633C7161] DEFAULT ((0)) FOR [AdjustedValue03]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__6430959A] DEFAULT ((0)) FOR [AdjustedValue04]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__6524B9D3] DEFAULT ((0)) FOR [AdjustedValue05]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__6618DE0C] DEFAULT ((0)) FOR [AdjustedValue06]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__670D0245] DEFAULT ((0)) FOR [AdjustedValue07]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__6801267E] DEFAULT ((0)) FOR [AdjustedValue08]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__68F54AB7] DEFAULT ((0)) FOR [AdjustedValue09]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__69E96EF0] DEFAULT ((0)) FOR [AdjustedValue10]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__6ADD9329] DEFAULT ((0)) FOR [AdjustedValue11]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Adjus__6BD1B762] DEFAULT ((0)) FOR [AdjustedValue12]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__6CC5DB9B] DEFAULT ((0)) FOR [FlexedValue01]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__6DB9FFD4] DEFAULT ((0)) FOR [FlexedValue02]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__6EAE240D] DEFAULT ((0)) FOR [FlexedValue03]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__6FA24846] DEFAULT ((0)) FOR [FlexedValue04]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__70966C7F] DEFAULT ((0)) FOR [FlexedValue05]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__718A90B8] DEFAULT ((0)) FOR [FlexedValue06]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__727EB4F1] DEFAULT ((0)) FOR [FlexedValue07]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__7372D92A] DEFAULT ((0)) FOR [FlexedValue08]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__7466FD63] DEFAULT ((0)) FOR [FlexedValue09]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__755B219C] DEFAULT ((0)) FOR [FlexedValue10]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__764F45D5] DEFAULT ((0)) FOR [FlexedValue11]; GO +ALTER TABLE [fp].[FactBenefitsBudget] ADD CONSTRAINT [DF__FactBenef__Flexe__77436A0E] DEFAULT ((0)) FOR [FlexedValue12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactBenefitsHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactBenefitsHistory] ( + [RowID] int NOT NULL, + [BenefitsID] int NOT NULL, + [PriorYearActualValue01] decimal NOT NULL, + [PriorYearActualValue02] decimal NOT NULL, + [PriorYearActualValue03] decimal NOT NULL, + [PriorYearActualValue04] decimal NOT NULL, + [PriorYearActualValue05] decimal NOT NULL, + [PriorYearActualValue06] decimal NOT NULL, + [PriorYearActualValue07] decimal NOT NULL, + [PriorYearActualValue08] decimal NOT NULL, + [PriorYearActualValue09] decimal NOT NULL, + [PriorYearActualValue10] decimal NOT NULL, + [PriorYearActualValue11] decimal NOT NULL, + [PriorYearActualValue12] decimal NOT NULL, + [PriorYearActualValueTotal] decimal NOT NULL, + [ActualYTDValue01] decimal NOT NULL, + [ActualYTDValue02] decimal NOT NULL, + [ActualYTDValue03] decimal NOT NULL, + [ActualYTDValue04] decimal NOT NULL, + [ActualYTDValue05] decimal NOT NULL, + [ActualYTDValue06] decimal NOT NULL, + [ActualYTDValue07] decimal NOT NULL, + [ActualYTDValue08] decimal NOT NULL, + [ActualYTDValue09] decimal NOT NULL, + [ActualYTDValue10] decimal NOT NULL, + [ActualYTDValue11] decimal NOT NULL, + [ActualYTDValue12] decimal NOT NULL, + [ActualYTDValueTotal] decimal NOT NULL, + [CurrentYearBudget01] decimal NOT NULL, + [CurrentYearBudget02] decimal NOT NULL, + [CurrentYearBudget03] decimal NOT NULL, + [CurrentYearBudget04] decimal NOT NULL, + [CurrentYearBudget05] decimal NOT NULL, + [CurrentYearBudget06] decimal NOT NULL, + [CurrentYearBudget07] decimal NOT NULL, + [CurrentYearBudget08] decimal NOT NULL, + [CurrentYearBudget09] decimal NOT NULL, + [CurrentYearBudget10] decimal NOT NULL, + [CurrentYearBudget11] decimal NOT NULL, + [CurrentYearBudget12] decimal NOT NULL, + [CurrentYearBudgetTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_FactBenefitsHistory] ON [fp].[FactBenefitsHistory] ([BenefitsID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[FactBenefitsHistory] ([BenefitsID]); +GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [FK_FactBenefitsHistory_BenefitsID] FOREIGN KEY ([BenefitsID]) REFERENCES [fp].[FactBenefits] ([BenefitsID]); GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Benef__1A8CA64B] DEFAULT ((0)) FOR [BenefitsID]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__1B80CA84] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__1C74EEBD] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__1D6912F6] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__1E5D372F] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__1F515B68] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__20457FA1] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__2139A3DA] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__222DC813] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__2321EC4C] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__24161085] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__250A34BE] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Prior__25FE58F7] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__26F27D30] DEFAULT ((0)) FOR [ActualYTDValue01]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__27E6A169] DEFAULT ((0)) FOR [ActualYTDValue02]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__28DAC5A2] DEFAULT ((0)) FOR [ActualYTDValue03]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__29CEE9DB] DEFAULT ((0)) FOR [ActualYTDValue04]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__2AC30E14] DEFAULT ((0)) FOR [ActualYTDValue05]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__2BB7324D] DEFAULT ((0)) FOR [ActualYTDValue06]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__2CAB5686] DEFAULT ((0)) FOR [ActualYTDValue07]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__2D9F7ABF] DEFAULT ((0)) FOR [ActualYTDValue08]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__2E939EF8] DEFAULT ((0)) FOR [ActualYTDValue09]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__2F87C331] DEFAULT ((0)) FOR [ActualYTDValue10]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__307BE76A] DEFAULT ((0)) FOR [ActualYTDValue11]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Actua__31700BA3] DEFAULT ((0)) FOR [ActualYTDValue12]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__32642FDC] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__33585415] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__344C784E] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__35409C87] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__3634C0C0] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__3728E4F9] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__381D0932] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__39112D6B] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__3A0551A4] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__3AF975DD] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__3BED9A16] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO +ALTER TABLE [fp].[FactBenefitsHistory] ADD CONSTRAINT [DF__FactBenef__Curre__3CE1BE4F] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactBenefitsProjection ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactBenefitsProjection] ( + [RowID] int NOT NULL, + [BenefitsID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedValue01] decimal NOT NULL, + [AdjustedValue02] decimal NOT NULL, + [AdjustedValue03] decimal NOT NULL, + [AdjustedValue04] decimal NOT NULL, + [AdjustedValue05] decimal NOT NULL, + [AdjustedValue06] decimal NOT NULL, + [AdjustedValue07] decimal NOT NULL, + [AdjustedValue08] decimal NOT NULL, + [AdjustedValue09] decimal NOT NULL, + [AdjustedValue10] decimal NOT NULL, + [AdjustedValue11] decimal NOT NULL, + [AdjustedValue12] decimal NOT NULL, + [AdjustedValueTotal] decimal NOT NULL, + [FlexedValue01] decimal NOT NULL, + [FlexedValue02] decimal NOT NULL, + [FlexedValue03] decimal NOT NULL, + [FlexedValue04] decimal NOT NULL, + [FlexedValue05] decimal NOT NULL, + [FlexedValue06] decimal NOT NULL, + [FlexedValue07] decimal NOT NULL, + [FlexedValue08] decimal NOT NULL, + [FlexedValue09] decimal NOT NULL, + [FlexedValue10] decimal NOT NULL, + [FlexedValue11] decimal NOT NULL, + [FlexedValue12] decimal NOT NULL, + [FlexedValueTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_FactBenefitsProjection] ON [fp].[FactBenefitsProjection] ([BenefitsID], [BudgetPhaseID]); +CREATE NONCLUSTERED INDEX [IX_FactBenefitsBudget_BudgetPhaseID] ON [fp].[FactBenefitsProjection] ([BudgetPhaseID], [BenefitsID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[FactBenefitsProjection] ([BenefitsID], [BudgetPhaseID]); +GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [FK_FactBenefitsProjection_BenefitsID] FOREIGN KEY ([BenefitsID]) REFERENCES [fp].[FactBenefits] ([BenefitsID]); GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__00CCD448] DEFAULT ((0)) FOR [AdjustedValue03]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__01C0F881] DEFAULT ((0)) FOR [AdjustedValue04]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__02B51CBA] DEFAULT ((0)) FOR [AdjustedValue05]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__03A940F3] DEFAULT ((0)) FOR [AdjustedValue06]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__049D652C] DEFAULT ((0)) FOR [AdjustedValue07]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__05918965] DEFAULT ((0)) FOR [AdjustedValue08]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__0685AD9E] DEFAULT ((0)) FOR [AdjustedValue09]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__0779D1D7] DEFAULT ((0)) FOR [AdjustedValue10]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__086DF610] DEFAULT ((0)) FOR [AdjustedValue11]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__09621A49] DEFAULT ((0)) FOR [AdjustedValue12]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__0A563E82] DEFAULT ((0)) FOR [FlexedValue01]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__0B4A62BB] DEFAULT ((0)) FOR [FlexedValue02]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__0C3E86F4] DEFAULT ((0)) FOR [FlexedValue03]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__0D32AB2D] DEFAULT ((0)) FOR [FlexedValue04]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__0E26CF66] DEFAULT ((0)) FOR [FlexedValue05]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__0F1AF39F] DEFAULT ((0)) FOR [FlexedValue06]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__100F17D8] DEFAULT ((0)) FOR [FlexedValue07]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__11033C11] DEFAULT ((0)) FOR [FlexedValue08]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__11F7604A] DEFAULT ((0)) FOR [FlexedValue09]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__12EB8483] DEFAULT ((0)) FOR [FlexedValue10]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__13DFA8BC] DEFAULT ((0)) FOR [FlexedValue11]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Flexe__14D3CCF5] DEFAULT ((0)) FOR [FlexedValue12]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Benef__7B13FAF2] DEFAULT ((0)) FOR [BenefitsID]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__LockT__7C081F2B] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__LockF__7CFC4364] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Budge__7DF0679D] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__7EE48BD6] DEFAULT ((0)) FOR [AdjustedValue01]; GO +ALTER TABLE [fp].[FactBenefitsProjection] ADD CONSTRAINT [DF__FactBenef__Adjus__7FD8B00F] DEFAULT ((0)) FOR [AdjustedValue02]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactChargeMaster ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactChargeMaster] ( + [RowID] int NOT NULL, + [BudgetConfigID] smallint NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [ChargeRate1] decimal NOT NULL, + [ChargeRate2] decimal NOT NULL, + [ChargeRate3] decimal NOT NULL, + [ChargeRate4] decimal NOT NULL, + [BaselineChargeRate] decimal NOT NULL, + [TimeClassID] tinyint NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE NONCLUSTERED INDEX [IX_FactChargeMaster_BudgetConfigID] ON [fp].[FactChargeMaster] ([BudgetConfigID]) INCLUDE ([ChargeCodeID], [ChargeRate1]); +CREATE NONCLUSTERED INDEX [IX_FactChargeMaster_BudgetConfigIDChargeCodeID] ON [fp].[FactChargeMaster] ([BudgetConfigID], [ChargeCodeID]) INCLUDE ([ChargeRate1]); +GO +ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [FK_ChargeMaster_ChargeCode] FOREIGN KEY ([ChargeCodeID]) REFERENCES [fw].[DimChargeCode] ([ChargeCodeID]); GO +ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [FK_ChargeMaster_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [FK_ChargeMaster_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO +ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [DF__FactCharg__Basel__07EA0F19] DEFAULT ((0)) FOR [BaselineChargeRate]; GO +ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [DF__FactCharg__Budge__1EEA42A6] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [df_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [DF__FactCharg__Entit__1FDE66DF] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [DF__FactCharg__Patie__21C6AF51] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [DF__FactCharg__Charg__23AEF7C3] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [DF__FactCharg__Charg__25974035] DEFAULT ((0)) FOR [ChargeRate1]; GO +ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [DF__FactCharg__Charg__268B646E] DEFAULT ((0)) FOR [ChargeRate2]; GO +ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [DF__FactCharg__Charg__277F88A7] DEFAULT ((0)) FOR [ChargeRate3]; GO +ALTER TABLE [fp].[FactChargeMaster] ADD CONSTRAINT [DF__FactCharg__Charg__2873ACE0] DEFAULT ((0)) FOR [ChargeRate4]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactGeneralLedgerInitiative ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactGeneralLedgerInitiative] ( + [RowID] int NOT NULL, + [GeneralLedgerID] int NOT NULL, + [InitiativeForecast01] decimal NOT NULL, + [InitiativeForecast02] decimal NOT NULL, + [InitiativeForecast03] decimal NOT NULL, + [InitiativeForecast04] decimal NOT NULL, + [InitiativeForecast05] decimal NOT NULL, + [InitiativeForecast06] decimal NOT NULL, + [InitiativeForecast07] decimal NOT NULL, + [InitiativeForecast08] decimal NOT NULL, + [InitiativeForecast09] decimal NOT NULL, + [InitiativeForecast10] decimal NOT NULL, + [InitiativeForecast11] decimal NOT NULL, + [InitiativeForecast12] decimal NOT NULL, + [InitiativeForecastTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [IX_FactGeneralLedgerInitiative_GeneralLedgerID] ON [fp].[FactGeneralLedgerInitiative] ([GeneralLedgerID]); +GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [FK_FactGeneralLedgerInitiative_GeneralLedgerID] FOREIGN KEY ([GeneralLedgerID]) REFERENCES [fp].[GeneralLedger] ([GeneralLedgerID]); GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Gener__15FC61CB] DEFAULT ((0)) FOR [GeneralLedgerID]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__16F08604] DEFAULT ((0)) FOR [InitiativeForecast01]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__17E4AA3D] DEFAULT ((0)) FOR [InitiativeForecast02]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__18D8CE76] DEFAULT ((0)) FOR [InitiativeForecast03]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__19CCF2AF] DEFAULT ((0)) FOR [InitiativeForecast04]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__1AC116E8] DEFAULT ((0)) FOR [InitiativeForecast05]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__1BB53B21] DEFAULT ((0)) FOR [InitiativeForecast06]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__1CA95F5A] DEFAULT ((0)) FOR [InitiativeForecast07]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__1D9D8393] DEFAULT ((0)) FOR [InitiativeForecast08]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__1E91A7CC] DEFAULT ((0)) FOR [InitiativeForecast09]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__1F85CC05] DEFAULT ((0)) FOR [InitiativeForecast10]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__2079F03E] DEFAULT ((0)) FOR [InitiativeForecast11]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative] ADD CONSTRAINT [DF__FactGener__Initi__216E1477] DEFAULT ((0)) FOR [InitiativeForecast12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactGeneralLedgerInitiative_OLD ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactGeneralLedgerInitiative_OLD] ( + [RowID] int NOT NULL, + [GeneralLedgerID] int NOT NULL, + [InitiativeForecast01] decimal NOT NULL, + [InitiativeForecast02] decimal NOT NULL, + [InitiativeForecast03] decimal NOT NULL, + [InitiativeForecast04] decimal NOT NULL, + [InitiativeForecast05] decimal NOT NULL, + [InitiativeForecast06] decimal NOT NULL, + [InitiativeForecast07] decimal NOT NULL, + [InitiativeForecast08] decimal NOT NULL, + [InitiativeForecast09] decimal NOT NULL, + [InitiativeForecast10] decimal NOT NULL, + [InitiativeForecast11] decimal NOT NULL, + [InitiativeForecast12] decimal NOT NULL, + [InitiativeForecastTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_GeneralLedgerID] DEFAULT ((0)) FOR [GeneralLedgerID]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast01] DEFAULT ((0)) FOR [InitiativeForecast01]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast02] DEFAULT ((0)) FOR [InitiativeForecast02]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast03] DEFAULT ((0)) FOR [InitiativeForecast03]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast04] DEFAULT ((0)) FOR [InitiativeForecast04]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast05] DEFAULT ((0)) FOR [InitiativeForecast05]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast06] DEFAULT ((0)) FOR [InitiativeForecast06]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast07] DEFAULT ((0)) FOR [InitiativeForecast07]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast08] DEFAULT ((0)) FOR [InitiativeForecast08]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast09] DEFAULT ((0)) FOR [InitiativeForecast09]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast10] DEFAULT ((0)) FOR [InitiativeForecast10]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast11] DEFAULT ((0)) FOR [InitiativeForecast11]; GO +ALTER TABLE [fp].[FactGeneralLedgerInitiative_OLD] ADD CONSTRAINT [DF_FactGeneralLedgerInitiative_InitiativeForecast12] DEFAULT ((0)) FOR [InitiativeForecast12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactISReportStatistics ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactISReportStatistics] ( + [BudgetConfigID] int NULL, + [DepartmentID] int NULL, + [AccountID] int NULL, + [FinancialReportingID] int NULL, + [FiscalYearID] int NULL, + [FiscalMonthID] int NULL, + [TimeClassID] int NULL, + [Amount] decimal NULL, + [YTD] decimal NULL, + [Yearly] decimal NULL, + [Total] decimal NULL +); + +CREATE CLUSTERED INDEX [idx_FactISReportStatistics] ON [fp].[FactISReportStatistics] ([FiscalYearID], [BudgetConfigID], [FiscalMonthID], [DepartmentID], [AccountID], [TimeClassID]); +CREATE NONCLUSTERED INDEX [NCNU_DepartmentID] ON [fp].[FactISReportStatistics] ([DepartmentID]); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReimbursementCharges ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReimbursementCharges] ( + [ReimbursementChargesID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [MSDRGID] int NOT NULL, + [PrimaryCPTID] int NOT NULL, + [UBRevCodeID] int NOT NULL, + [AddDate] datetime NOT NULL, + [InitialBudgetChargeDollars01] decimal NOT NULL, + [InitialBudgetChargeDollars02] decimal NOT NULL, + [InitialBudgetChargeDollars03] decimal NOT NULL, + [InitialBudgetChargeDollars04] decimal NOT NULL, + [InitialBudgetChargeDollars05] decimal NOT NULL, + [InitialBudgetChargeDollars06] decimal NOT NULL, + [InitialBudgetChargeDollars07] decimal NOT NULL, + [InitialBudgetChargeDollars08] decimal NOT NULL, + [InitialBudgetChargeDollars09] decimal NOT NULL, + [InitialBudgetChargeDollars10] decimal NOT NULL, + [InitialBudgetChargeDollars11] decimal NOT NULL, + [InitialBudgetChargeDollars12] decimal NOT NULL, + [InitialBudgetChargeDollarsTotal] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge01] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge02] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge03] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge04] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge05] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge06] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge07] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge08] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge09] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge10] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge11] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge12] decimal NOT NULL, + [InitialBudgetNetPerDiem01] decimal NOT NULL, + [InitialBudgetNetPerDiem02] decimal NOT NULL, + [InitialBudgetNetPerDiem03] decimal NOT NULL, + [InitialBudgetNetPerDiem04] decimal NOT NULL, + [InitialBudgetNetPerDiem05] decimal NOT NULL, + [InitialBudgetNetPerDiem06] decimal NOT NULL, + [InitialBudgetNetPerDiem07] decimal NOT NULL, + [InitialBudgetNetPerDiem08] decimal NOT NULL, + [InitialBudgetNetPerDiem09] decimal NOT NULL, + [InitialBudgetNetPerDiem10] decimal NOT NULL, + [InitialBudgetNetPerDiem11] decimal NOT NULL, + [InitialBudgetNetPerDiem12] decimal NOT NULL, + [InitialProjectionChargeDollars01] decimal NOT NULL, + [InitialProjectionChargeDollars02] decimal NOT NULL, + [InitialProjectionChargeDollars03] decimal NOT NULL, + [InitialProjectionChargeDollars04] decimal NOT NULL, + [InitialProjectionChargeDollars05] decimal NOT NULL, + [InitialProjectionChargeDollars06] decimal NOT NULL, + [InitialProjectionChargeDollars07] decimal NOT NULL, + [InitialProjectionChargeDollars08] decimal NOT NULL, + [InitialProjectionChargeDollars09] decimal NOT NULL, + [InitialProjectionChargeDollars10] decimal NOT NULL, + [InitialProjectionChargeDollars11] decimal NOT NULL, + [InitialProjectionChargeDollars12] decimal NOT NULL, + [InitialProjectionChargeDollarsTotal] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge01] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge02] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge03] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge04] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge05] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge06] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge07] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge08] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge09] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge10] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge11] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge12] decimal NOT NULL, + [InitialProjectionNetPerDiem01] decimal NOT NULL, + [InitialProjectionNetPerDiem02] decimal NOT NULL, + [InitialProjectionNetPerDiem03] decimal NOT NULL, + [InitialProjectionNetPerDiem04] decimal NOT NULL, + [InitialProjectionNetPerDiem05] decimal NOT NULL, + [InitialProjectionNetPerDiem06] decimal NOT NULL, + [InitialProjectionNetPerDiem07] decimal NOT NULL, + [InitialProjectionNetPerDiem08] decimal NOT NULL, + [InitialProjectionNetPerDiem09] decimal NOT NULL, + [InitialProjectionNetPerDiem10] decimal NOT NULL, + [InitialProjectionNetPerDiem11] decimal NOT NULL, + [InitialProjectionNetPerDiem12] decimal NOT NULL, + [IsNew] bit NOT NULL, + [InitialBudgetNetReimbursement01] decimal NOT NULL, + [InitialBudgetNetReimbursement02] decimal NOT NULL, + [InitialBudgetNetReimbursement03] decimal NOT NULL, + [InitialBudgetNetReimbursement04] decimal NOT NULL, + [InitialBudgetNetReimbursement05] decimal NOT NULL, + [InitialBudgetNetReimbursement06] decimal NOT NULL, + [InitialBudgetNetReimbursement07] decimal NOT NULL, + [InitialBudgetNetReimbursement08] decimal NOT NULL, + [InitialBudgetNetReimbursement09] decimal NOT NULL, + [InitialBudgetNetReimbursement10] decimal NOT NULL, + [InitialBudgetNetReimbursement11] decimal NOT NULL, + [InitialBudgetNetReimbursement12] decimal NOT NULL, + [InitialProjectionNetReimbursement01] decimal NOT NULL, + [InitialProjectionNetReimbursement02] decimal NOT NULL, + [InitialProjectionNetReimbursement03] decimal NOT NULL, + [InitialProjectionNetReimbursement04] decimal NOT NULL, + [InitialProjectionNetReimbursement05] decimal NOT NULL, + [InitialProjectionNetReimbursement06] decimal NOT NULL, + [InitialProjectionNetReimbursement07] decimal NOT NULL, + [InitialProjectionNetReimbursement08] decimal NOT NULL, + [InitialProjectionNetReimbursement09] decimal NOT NULL, + [InitialProjectionNetReimbursement10] decimal NOT NULL, + [InitialProjectionNetReimbursement11] decimal NOT NULL, + [InitialProjectionNetReimbursement12] decimal NOT NULL, + PRIMARY KEY ([ReimbursementChargesID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [CORE_FactReimbursementChargesUnique] ON [fp].[FactReimbursementCharges] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [MedicalSurgicalID], [PayorID], [PayorGroupID], [MSDRGID], [PrimaryCPTID], [UBRevCodeID]); +GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [FK_FactReimbursementCharges_CPT] FOREIGN KEY ([PrimaryCPTID]) REFERENCES [dss].[DimCPT] ([CPTID]); GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [FK_FactReimbursementCharges_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [FK_FactReimbursementCharges_MedicalSurgical] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [FK_FactReimbursementCharges_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [FK_FactReimbursementCharges_Payor] FOREIGN KEY ([PayorID]) REFERENCES [fw].[DimPayor] ([PayorID]); GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [FK_FactReimbursementCharges_PayorGroup] FOREIGN KEY ([PayorGroupID]) REFERENCES [fw].[DimPayorGroup] ([PayorGroupID]); GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [FK_FactReimbursementCharges_ServiceLine] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [FK_FactReimbursementCharges_ServiceLineRollup] FOREIGN KEY ([ServiceLineRollupID]) REFERENCES [fw].[DimServiceLineRollup] ([ServiceLineRollupID]); GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Budge__09A9377A] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Entit__0A9D5BB3] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Entit__0B917FEC] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Patie__0C85A425] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Servi__0D79C85E] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Servi__0E6DEC97] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Medic__0F6210D0] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Payor__114A5942] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Payor__123E7D7B] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__MSDRG__1332A1B4] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Prima__1426C5ED] DEFAULT ((0)) FOR [PrimaryCPTID]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__UBRev__151AEA26] DEFAULT ((0)) FOR [UBRevCodeID]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF_ReimbursementCharges_AddDate] DEFAULT ('1900-01-01') FOR [AddDate]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__17F756D1] DEFAULT ((0)) FOR [InitialBudgetChargeDollars01]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__18EB7B0A] DEFAULT ((0)) FOR [InitialBudgetChargeDollars02]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__19DF9F43] DEFAULT ((0)) FOR [InitialBudgetChargeDollars03]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__1AD3C37C] DEFAULT ((0)) FOR [InitialBudgetChargeDollars04]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__1BC7E7B5] DEFAULT ((0)) FOR [InitialBudgetChargeDollars05]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__1CBC0BEE] DEFAULT ((0)) FOR [InitialBudgetChargeDollars06]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__1DB03027] DEFAULT ((0)) FOR [InitialBudgetChargeDollars07]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__1EA45460] DEFAULT ((0)) FOR [InitialBudgetChargeDollars08]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__1F987899] DEFAULT ((0)) FOR [InitialBudgetChargeDollars09]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__208C9CD2] DEFAULT ((0)) FOR [InitialBudgetChargeDollars10]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__2180C10B] DEFAULT ((0)) FOR [InitialBudgetChargeDollars11]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__2274E544] DEFAULT ((0)) FOR [InitialBudgetChargeDollars12]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__2EDABC29] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge01]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__2FCEE062] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge02]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__30C3049B] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge03]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__31B728D4] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge04]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__32AB4D0D] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge05]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__339F7146] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge06]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__3493957F] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge07]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__3587B9B8] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge08]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__367BDDF1] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge09]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__3770022A] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge10]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__38642663] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge11]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__39584A9C] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge12]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__3A4C6ED5] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem01]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__3B40930E] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem02]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__3C34B747] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem03]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__3D28DB80] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem04]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__3E1CFFB9] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem05]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__3F1123F2] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem06]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__4005482B] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem07]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__40F96C64] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem08]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__41ED909D] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem09]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__42E1B4D6] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem10]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__43D5D90F] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem11]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__44C9FD48] DEFAULT ((0)) FOR [InitialBudgetNetPerDiem12]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__45BE2181] DEFAULT ((0)) FOR [InitialProjectionChargeDollars01]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__46B245BA] DEFAULT ((0)) FOR [InitialProjectionChargeDollars02]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__47A669F3] DEFAULT ((0)) FOR [InitialProjectionChargeDollars03]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__489A8E2C] DEFAULT ((0)) FOR [InitialProjectionChargeDollars04]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__498EB265] DEFAULT ((0)) FOR [InitialProjectionChargeDollars05]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__4A82D69E] DEFAULT ((0)) FOR [InitialProjectionChargeDollars06]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__4B76FAD7] DEFAULT ((0)) FOR [InitialProjectionChargeDollars07]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__4C6B1F10] DEFAULT ((0)) FOR [InitialProjectionChargeDollars08]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__4D5F4349] DEFAULT ((0)) FOR [InitialProjectionChargeDollars09]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__4E536782] DEFAULT ((0)) FOR [InitialProjectionChargeDollars10]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__4F478BBB] DEFAULT ((0)) FOR [InitialProjectionChargeDollars11]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__503BAFF4] DEFAULT ((0)) FOR [InitialProjectionChargeDollars12]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__5CA186D9] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge01]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__5D95AB12] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge02]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__5E89CF4B] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge03]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__5F7DF384] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge04]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__607217BD] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge05]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__61663BF6] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge06]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__625A602F] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge07]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__634E8468] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge08]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__6442A8A1] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge09]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__6536CCDA] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge10]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__662AF113] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge11]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__671F154C] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge12]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__68133985] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem01]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__69075DBE] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem02]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__69FB81F7] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem03]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__6AEFA630] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem04]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__6BE3CA69] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem05]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__6CD7EEA2] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem06]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__6DCC12DB] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem07]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__6EC03714] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem08]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__6FB45B4D] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem09]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__70A87F86] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem10]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__719CA3BF] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem11]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__Initi__7290C7F8] DEFAULT ((0)) FOR [InitialProjectionNetPerDiem12]; GO +ALTER TABLE [fp].[FactReimbursementCharges] ADD CONSTRAINT [DF__FactReimb__IsNew__7384EC31] DEFAULT ((0)) FOR [IsNew]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReimbursementChargesBudget ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReimbursementChargesBudget] ( + [RowID] int NOT NULL, + [ReimbursementChargesID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedChargeDollars01] decimal NOT NULL, + [AdjustedChargeDollars02] decimal NOT NULL, + [AdjustedChargeDollars03] decimal NOT NULL, + [AdjustedChargeDollars04] decimal NOT NULL, + [AdjustedChargeDollars05] decimal NOT NULL, + [AdjustedChargeDollars06] decimal NOT NULL, + [AdjustedChargeDollars07] decimal NOT NULL, + [AdjustedChargeDollars08] decimal NOT NULL, + [AdjustedChargeDollars09] decimal NOT NULL, + [AdjustedChargeDollars10] decimal NOT NULL, + [AdjustedChargeDollars11] decimal NOT NULL, + [AdjustedChargeDollars12] decimal NOT NULL, + [AdjustedChargeDollarsTotal] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge01] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge02] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge03] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge04] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge05] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge06] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge07] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge08] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge09] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge10] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge11] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge12] decimal NOT NULL, + [AdjustedNetPerDiem01] decimal NOT NULL, + [AdjustedNetPerDiem02] decimal NOT NULL, + [AdjustedNetPerDiem03] decimal NOT NULL, + [AdjustedNetPerDiem04] decimal NOT NULL, + [AdjustedNetPerDiem05] decimal NOT NULL, + [AdjustedNetPerDiem06] decimal NOT NULL, + [AdjustedNetPerDiem07] decimal NOT NULL, + [AdjustedNetPerDiem08] decimal NOT NULL, + [AdjustedNetPerDiem09] decimal NOT NULL, + [AdjustedNetPerDiem10] decimal NOT NULL, + [AdjustedNetPerDiem11] decimal NOT NULL, + [AdjustedNetPerDiem12] decimal NOT NULL, + [AdjustedNetReimbursementValue01] decimal NOT NULL, + [AdjustedNetReimbursementValue02] decimal NOT NULL, + [AdjustedNetReimbursementValue03] decimal NOT NULL, + [AdjustedNetReimbursementValue04] decimal NOT NULL, + [AdjustedNetReimbursementValue05] decimal NOT NULL, + [AdjustedNetReimbursementValue06] decimal NOT NULL, + [AdjustedNetReimbursementValue07] decimal NOT NULL, + [AdjustedNetReimbursementValue08] decimal NOT NULL, + [AdjustedNetReimbursementValue09] decimal NOT NULL, + [AdjustedNetReimbursementValue10] decimal NOT NULL, + [AdjustedNetReimbursementValue11] decimal NOT NULL, + [AdjustedNetReimbursementValue12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [FK_FactReimbursementChargesBudget_ReimbursementChargesID] FOREIGN KEY ([ReimbursementChargesID]) REFERENCES [fp].[FactReimbursementCharges] ([ReimbursementChargesID]); GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Reimb__24B23371] DEFAULT ((0)) FOR [ReimbursementChargesID]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__LockT__25A657AA] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__LockF__269A7BE3] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Budge__278EA01C] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__2882C455] DEFAULT ((0)) FOR [AdjustedChargeDollars01]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__2976E88E] DEFAULT ((0)) FOR [AdjustedChargeDollars02]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__2A6B0CC7] DEFAULT ((0)) FOR [AdjustedChargeDollars03]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__2B5F3100] DEFAULT ((0)) FOR [AdjustedChargeDollars04]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__2C535539] DEFAULT ((0)) FOR [AdjustedChargeDollars05]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__2D477972] DEFAULT ((0)) FOR [AdjustedChargeDollars06]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__2E3B9DAB] DEFAULT ((0)) FOR [AdjustedChargeDollars07]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__2F2FC1E4] DEFAULT ((0)) FOR [AdjustedChargeDollars08]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__3023E61D] DEFAULT ((0)) FOR [AdjustedChargeDollars09]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__31180A56] DEFAULT ((0)) FOR [AdjustedChargeDollars10]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__320C2E8F] DEFAULT ((0)) FOR [AdjustedChargeDollars11]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__330052C8] DEFAULT ((0)) FOR [AdjustedChargeDollars12]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__3F6629AD] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge01]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__405A4DE6] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge02]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__414E721F] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge03]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__42429658] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge04]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__4336BA91] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge05]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__442ADECA] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge06]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__451F0303] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge07]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__4613273C] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge08]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__47074B75] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge09]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__47FB6FAE] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge10]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__48EF93E7] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge11]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__49E3B820] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge12]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__4AD7DC59] DEFAULT ((0)) FOR [AdjustedNetPerDiem01]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__4BCC0092] DEFAULT ((0)) FOR [AdjustedNetPerDiem02]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__4CC024CB] DEFAULT ((0)) FOR [AdjustedNetPerDiem03]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__4DB44904] DEFAULT ((0)) FOR [AdjustedNetPerDiem04]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__4EA86D3D] DEFAULT ((0)) FOR [AdjustedNetPerDiem05]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__4F9C9176] DEFAULT ((0)) FOR [AdjustedNetPerDiem06]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__5090B5AF] DEFAULT ((0)) FOR [AdjustedNetPerDiem07]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__5184D9E8] DEFAULT ((0)) FOR [AdjustedNetPerDiem08]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__5278FE21] DEFAULT ((0)) FOR [AdjustedNetPerDiem09]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__536D225A] DEFAULT ((0)) FOR [AdjustedNetPerDiem10]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__54614693] DEFAULT ((0)) FOR [AdjustedNetPerDiem11]; GO +ALTER TABLE [fp].[FactReimbursementChargesBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__55556ACC] DEFAULT ((0)) FOR [AdjustedNetPerDiem12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReimbursementChargesHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReimbursementChargesHistory] ( + [RowID] int NOT NULL, + [ReimbursementChargesID] int NOT NULL, + [PriorYearActualChargeDollars01] decimal NOT NULL, + [PriorYearActualChargeDollars02] decimal NOT NULL, + [PriorYearActualChargeDollars03] decimal NOT NULL, + [PriorYearActualChargeDollars04] decimal NOT NULL, + [PriorYearActualChargeDollars05] decimal NOT NULL, + [PriorYearActualChargeDollars06] decimal NOT NULL, + [PriorYearActualChargeDollars07] decimal NOT NULL, + [PriorYearActualChargeDollars08] decimal NOT NULL, + [PriorYearActualChargeDollars09] decimal NOT NULL, + [PriorYearActualChargeDollars10] decimal NOT NULL, + [PriorYearActualChargeDollars11] decimal NOT NULL, + [PriorYearActualChargeDollars12] decimal NOT NULL, + [PriorYearActualChargeDollarsTotal] decimal NOT NULL, + [ActualYTDChargeDollars01] decimal NOT NULL, + [ActualYTDChargeDollars02] decimal NOT NULL, + [ActualYTDChargeDollars03] decimal NOT NULL, + [ActualYTDChargeDollars04] decimal NOT NULL, + [ActualYTDChargeDollars05] decimal NOT NULL, + [ActualYTDChargeDollars06] decimal NOT NULL, + [ActualYTDChargeDollars07] decimal NOT NULL, + [ActualYTDChargeDollars08] decimal NOT NULL, + [ActualYTDChargeDollars09] decimal NOT NULL, + [ActualYTDChargeDollars10] decimal NOT NULL, + [ActualYTDChargeDollars11] decimal NOT NULL, + [ActualYTDChargeDollars12] decimal NOT NULL, + [ActualYTDChargeDollarsTotal] decimal NOT NULL, + [CurrentYearBudgetChargeDollars01] decimal NOT NULL, + [CurrentYearBudgetChargeDollars02] decimal NOT NULL, + [CurrentYearBudgetChargeDollars03] decimal NOT NULL, + [CurrentYearBudgetChargeDollars04] decimal NOT NULL, + [CurrentYearBudgetChargeDollars05] decimal NOT NULL, + [CurrentYearBudgetChargeDollars06] decimal NOT NULL, + [CurrentYearBudgetChargeDollars07] decimal NOT NULL, + [CurrentYearBudgetChargeDollars08] decimal NOT NULL, + [CurrentYearBudgetChargeDollars09] decimal NOT NULL, + [CurrentYearBudgetChargeDollars10] decimal NOT NULL, + [CurrentYearBudgetChargeDollars11] decimal NOT NULL, + [CurrentYearBudgetChargeDollars12] decimal NOT NULL, + [CurrentYearBudgetChargeDollarsTotal] decimal NOT NULL, + [CurrentYearBudgetChargeUnits01] decimal NOT NULL, + [CurrentYearBudgetChargeUnits02] decimal NOT NULL, + [CurrentYearBudgetChargeUnits03] decimal NOT NULL, + [CurrentYearBudgetChargeUnits04] decimal NOT NULL, + [CurrentYearBudgetChargeUnits05] decimal NOT NULL, + [CurrentYearBudgetChargeUnits06] decimal NOT NULL, + [CurrentYearBudgetChargeUnits07] decimal NOT NULL, + [CurrentYearBudgetChargeUnits08] decimal NOT NULL, + [CurrentYearBudgetChargeUnits09] decimal NOT NULL, + [CurrentYearBudgetChargeUnits10] decimal NOT NULL, + [CurrentYearBudgetChargeUnits11] decimal NOT NULL, + [CurrentYearBudgetChargeUnits12] decimal NOT NULL, + [CurrentYearBudgetChargeUnitsTotal] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge01] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge02] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge03] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge04] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge05] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge06] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge07] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge08] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge09] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge10] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge11] decimal NOT NULL, + [PriorYearActualNetAsPercentOfCharge12] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge01] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge02] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge03] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge04] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge05] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge06] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge07] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge08] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge09] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge10] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge11] decimal NOT NULL, + [ActualYTDNetAsPercentOfCharge12] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge01] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge02] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge03] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge04] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge05] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge06] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge07] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge08] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge09] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge10] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge11] decimal NOT NULL, + [CurrentYearBudgetNetAsPercentOfCharge12] decimal NOT NULL, + [PriorYearActualNetPerDiem01] decimal NOT NULL, + [PriorYearActualNetPerDiem02] decimal NOT NULL, + [PriorYearActualNetPerDiem03] decimal NOT NULL, + [PriorYearActualNetPerDiem04] decimal NOT NULL, + [PriorYearActualNetPerDiem05] decimal NOT NULL, + [PriorYearActualNetPerDiem06] decimal NOT NULL, + [PriorYearActualNetPerDiem07] decimal NOT NULL, + [PriorYearActualNetPerDiem08] decimal NOT NULL, + [PriorYearActualNetPerDiem09] decimal NOT NULL, + [PriorYearActualNetPerDiem10] decimal NOT NULL, + [PriorYearActualNetPerDiem11] decimal NOT NULL, + [PriorYearActualNetPerDiem12] decimal NOT NULL, + [ActualYTDNetPerDiem01] decimal NOT NULL, + [ActualYTDNetPerDiem02] decimal NOT NULL, + [ActualYTDNetPerDiem03] decimal NOT NULL, + [ActualYTDNetPerDiem04] decimal NOT NULL, + [ActualYTDNetPerDiem05] decimal NOT NULL, + [ActualYTDNetPerDiem06] decimal NOT NULL, + [ActualYTDNetPerDiem07] decimal NOT NULL, + [ActualYTDNetPerDiem08] decimal NOT NULL, + [ActualYTDNetPerDiem09] decimal NOT NULL, + [ActualYTDNetPerDiem10] decimal NOT NULL, + [ActualYTDNetPerDiem11] decimal NOT NULL, + [ActualYTDNetPerDiem12] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem01] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem02] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem03] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem04] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem05] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem06] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem07] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem08] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem09] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem10] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem11] decimal NOT NULL, + [CurrentYearBudgetNetPerDiem12] decimal NOT NULL, + [PriorYearActualNetReimbursementValue01] decimal NOT NULL, + [PriorYearActualNetReimbursementValue02] decimal NOT NULL, + [PriorYearActualNetReimbursementValue03] decimal NOT NULL, + [PriorYearActualNetReimbursementValue04] decimal NOT NULL, + [PriorYearActualNetReimbursementValue05] decimal NOT NULL, + [PriorYearActualNetReimbursementValue06] decimal NOT NULL, + [PriorYearActualNetReimbursementValue07] decimal NOT NULL, + [PriorYearActualNetReimbursementValue08] decimal NOT NULL, + [PriorYearActualNetReimbursementValue09] decimal NOT NULL, + [PriorYearActualNetReimbursementValue10] decimal NOT NULL, + [PriorYearActualNetReimbursementValue11] decimal NOT NULL, + [PriorYearActualNetReimbursementValue12] decimal NOT NULL, + [ActualYTDNetReimbursementValue01] decimal NOT NULL, + [ActualYTDNetReimbursementValue02] decimal NOT NULL, + [ActualYTDNetReimbursementValue03] decimal NOT NULL, + [ActualYTDNetReimbursementValue04] decimal NOT NULL, + [ActualYTDNetReimbursementValue05] decimal NOT NULL, + [ActualYTDNetReimbursementValue06] decimal NOT NULL, + [ActualYTDNetReimbursementValue07] decimal NOT NULL, + [ActualYTDNetReimbursementValue08] decimal NOT NULL, + [ActualYTDNetReimbursementValue09] decimal NOT NULL, + [ActualYTDNetReimbursementValue10] decimal NOT NULL, + [ActualYTDNetReimbursementValue11] decimal NOT NULL, + [ActualYTDNetReimbursementValue12] decimal NOT NULL, + [CurrentYearNetReimbursementBudget01] decimal NOT NULL, + [CurrentYearNetReimbursementBudget02] decimal NOT NULL, + [CurrentYearNetReimbursementBudget03] decimal NOT NULL, + [CurrentYearNetReimbursementBudget04] decimal NOT NULL, + [CurrentYearNetReimbursementBudget05] decimal NOT NULL, + [CurrentYearNetReimbursementBudget06] decimal NOT NULL, + [CurrentYearNetReimbursementBudget07] decimal NOT NULL, + [CurrentYearNetReimbursementBudget08] decimal NOT NULL, + [CurrentYearNetReimbursementBudget09] decimal NOT NULL, + [CurrentYearNetReimbursementBudget10] decimal NOT NULL, + [CurrentYearNetReimbursementBudget11] decimal NOT NULL, + [CurrentYearNetReimbursementBudget12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [FK_FactReimbursementChargesHistory_ReimbursementChargesID] FOREIGN KEY ([ReimbursementChargesID]) REFERENCES [fp].[FactReimbursementCharges] ([ReimbursementChargesID]); GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__000ABEA7] DEFAULT ((0)) FOR [PriorYearActualChargeDollars07]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__00C9D8B6] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem10]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__00FEE2E0] DEFAULT ((0)) FOR [PriorYearActualChargeDollars08]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__01BDFCEF] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem11]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__01F30719] DEFAULT ((0)) FOR [PriorYearActualChargeDollars09]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__02B22128] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem12]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__02E72B52] DEFAULT ((0)) FOR [PriorYearActualChargeDollars10]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__03DB4F8B] DEFAULT ((0)) FOR [PriorYearActualChargeDollars11]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__04CF73C4] DEFAULT ((0)) FOR [PriorYearActualChargeDollars12]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__05C397FD] DEFAULT ((0)) FOR [ActualYTDChargeDollars01]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__06B7BC36] DEFAULT ((0)) FOR [ActualYTDChargeDollars02]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__07ABE06F] DEFAULT ((0)) FOR [ActualYTDChargeDollars03]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__08A004A8] DEFAULT ((0)) FOR [ActualYTDChargeDollars04]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__099428E1] DEFAULT ((0)) FOR [ActualYTDChargeDollars05]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__0A884D1A] DEFAULT ((0)) FOR [ActualYTDChargeDollars06]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__0B7C7153] DEFAULT ((0)) FOR [ActualYTDChargeDollars07]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__0C70958C] DEFAULT ((0)) FOR [ActualYTDChargeDollars08]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__0D64B9C5] DEFAULT ((0)) FOR [ActualYTDChargeDollars09]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__0E58DDFE] DEFAULT ((0)) FOR [ActualYTDChargeDollars10]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__0F4D0237] DEFAULT ((0)) FOR [ActualYTDChargeDollars11]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__10412670] DEFAULT ((0)) FOR [ActualYTDChargeDollars12]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__11354AA9] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars01]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__12296EE2] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars02]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__131D931B] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars03]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__1411B754] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars04]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__1505DB8D] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars05]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__15F9FFC6] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars06]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__16EE23FF] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars07]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__17E24838] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars08]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__18D66C71] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars09]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__19CA90AA] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars10]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__1ABEB4E3] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars11]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__1BB2D91C] DEFAULT ((0)) FOR [CurrentYearBudgetChargeDollars12]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__338A62AD] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits01]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__347E86E6] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits02]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__3572AB1F] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits03]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__3666CF58] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits04]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__375AF391] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits05]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__384F17CA] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits06]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__39433C03] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits07]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__3A37603C] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits08]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__3B2B8475] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits09]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__3C1FA8AE] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits10]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__3D13CCE7] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits11]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__3E07F120] DEFAULT ((0)) FOR [CurrentYearBudgetChargeUnits12]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__3EFC1559] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge01]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__3FF03992] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge02]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__40E45DCB] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge03]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__41D88204] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge04]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__42CCA63D] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge05]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__43C0CA76] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge06]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__44B4EEAF] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge07]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__45A912E8] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge08]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__469D3721] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge09]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__47915B5A] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge10]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__48857F93] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge11]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__4979A3CC] DEFAULT ((0)) FOR [PriorYearActualNetAsPercentOfCharge12]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4A6DC805] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge01]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4B61EC3E] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge02]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4C561077] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge03]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4D4A34B0] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge04]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4E3E58E9] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge05]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4F327D22] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge06]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__5026A15B] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge07]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__511AC594] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge08]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__520EE9CD] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge09]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__53030E06] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge10]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__53F7323F] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge11]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__54EB5678] DEFAULT ((0)) FOR [ActualYTDNetAsPercentOfCharge12]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__55DF7AB1] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge01]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__56D39EEA] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge02]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__57C7C323] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge03]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__58BBE75C] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge04]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__59B00B95] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge05]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__5AA42FCE] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge06]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__5B985407] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge07]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__5C8C7840] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge08]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__5D809C79] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge09]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__5E74C0B2] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge10]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__5F68E4EB] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge11]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__605D0924] DEFAULT ((0)) FOR [CurrentYearBudgetNetAsPercentOfCharge12]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__61512D5D] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem01]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__62455196] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem02]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__633975CF] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem03]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__642D9A08] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem04]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__6521BE41] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem05]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__6615E27A] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem06]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__670A06B3] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem07]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__67FE2AEC] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem08]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__68F24F25] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem09]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__69E6735E] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem10]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__6ADA9797] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem11]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__6BCEBBD0] DEFAULT ((0)) FOR [PriorYearActualNetPerDiem12]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__6CC2E009] DEFAULT ((0)) FOR [ActualYTDNetPerDiem01]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__6DB70442] DEFAULT ((0)) FOR [ActualYTDNetPerDiem02]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__6EAB287B] DEFAULT ((0)) FOR [ActualYTDNetPerDiem03]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__6F9F4CB4] DEFAULT ((0)) FOR [ActualYTDNetPerDiem04]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__709370ED] DEFAULT ((0)) FOR [ActualYTDNetPerDiem05]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__71879526] DEFAULT ((0)) FOR [ActualYTDNetPerDiem06]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__727BB95F] DEFAULT ((0)) FOR [ActualYTDNetPerDiem07]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__736FDD98] DEFAULT ((0)) FOR [ActualYTDNetPerDiem08]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__746401D1] DEFAULT ((0)) FOR [ActualYTDNetPerDiem09]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__7558260A] DEFAULT ((0)) FOR [ActualYTDNetPerDiem10]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__764C4A43] DEFAULT ((0)) FOR [ActualYTDNetPerDiem11]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Reimb__7681546D] DEFAULT ((0)) FOR [ReimbursementChargesID]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Actua__77406E7C] DEFAULT ((0)) FOR [ActualYTDNetPerDiem12]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__783492B5] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem01]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__7928B6EE] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem02]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__7A1CDB27] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem03]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__7A51E551] DEFAULT ((0)) FOR [PriorYearActualChargeDollars01]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__7B10FF60] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem04]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__7B46098A] DEFAULT ((0)) FOR [PriorYearActualChargeDollars02]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__7C052399] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem05]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__7C3A2DC3] DEFAULT ((0)) FOR [PriorYearActualChargeDollars03]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__7CF947D2] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem06]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__7D2E51FC] DEFAULT ((0)) FOR [PriorYearActualChargeDollars04]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__7DED6C0B] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem07]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__7E227635] DEFAULT ((0)) FOR [PriorYearActualChargeDollars05]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__7EE19044] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem08]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Prior__7F169A6E] DEFAULT ((0)) FOR [PriorYearActualChargeDollars06]; GO +ALTER TABLE [fp].[FactReimbursementChargesHistory] ADD CONSTRAINT [DF__FactReimb__Curre__7FD5B47D] DEFAULT ((0)) FOR [CurrentYearBudgetNetPerDiem09]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReimbursementChargesProjection ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReimbursementChargesProjection] ( + [RowID] int NOT NULL, + [ReimbursementChargesID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedChargeDollars01] decimal NOT NULL, + [AdjustedChargeDollars02] decimal NOT NULL, + [AdjustedChargeDollars03] decimal NOT NULL, + [AdjustedChargeDollars04] decimal NOT NULL, + [AdjustedChargeDollars05] decimal NOT NULL, + [AdjustedChargeDollars06] decimal NOT NULL, + [AdjustedChargeDollars07] decimal NOT NULL, + [AdjustedChargeDollars08] decimal NOT NULL, + [AdjustedChargeDollars09] decimal NOT NULL, + [AdjustedChargeDollars10] decimal NOT NULL, + [AdjustedChargeDollars11] decimal NOT NULL, + [AdjustedChargeDollars12] decimal NOT NULL, + [AdjustedChargeDollarsTotal] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge01] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge02] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge03] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge04] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge05] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge06] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge07] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge08] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge09] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge10] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge11] decimal NOT NULL, + [AdjustedNetAsPercentOfCharge12] decimal NOT NULL, + [AdjustedNetPerDiem01] decimal NOT NULL, + [AdjustedNetPerDiem02] decimal NOT NULL, + [AdjustedNetPerDiem03] decimal NOT NULL, + [AdjustedNetPerDiem04] decimal NOT NULL, + [AdjustedNetPerDiem05] decimal NOT NULL, + [AdjustedNetPerDiem06] decimal NOT NULL, + [AdjustedNetPerDiem07] decimal NOT NULL, + [AdjustedNetPerDiem08] decimal NOT NULL, + [AdjustedNetPerDiem09] decimal NOT NULL, + [AdjustedNetPerDiem10] decimal NOT NULL, + [AdjustedNetPerDiem11] decimal NOT NULL, + [AdjustedNetPerDiem12] decimal NOT NULL, + [AdjustedNetReimbursementValue01] decimal NOT NULL, + [AdjustedNetReimbursementValue02] decimal NOT NULL, + [AdjustedNetReimbursementValue03] decimal NOT NULL, + [AdjustedNetReimbursementValue04] decimal NOT NULL, + [AdjustedNetReimbursementValue05] decimal NOT NULL, + [AdjustedNetReimbursementValue06] decimal NOT NULL, + [AdjustedNetReimbursementValue07] decimal NOT NULL, + [AdjustedNetReimbursementValue08] decimal NOT NULL, + [AdjustedNetReimbursementValue09] decimal NOT NULL, + [AdjustedNetReimbursementValue10] decimal NOT NULL, + [AdjustedNetReimbursementValue11] decimal NOT NULL, + [AdjustedNetReimbursementValue12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [FK_FactReimbursementChargesProjection_ReimbursementChargesID] FOREIGN KEY ([ReimbursementChargesID]) REFERENCES [fp].[FactReimbursementCharges] ([ReimbursementChargesID]); GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Reimb__420D8C2E] DEFAULT ((0)) FOR [ReimbursementChargesID]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__LockT__4301B067] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__LockF__43F5D4A0] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Budge__44E9F8D9] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__45DE1D12] DEFAULT ((0)) FOR [AdjustedChargeDollars01]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__46D2414B] DEFAULT ((0)) FOR [AdjustedChargeDollars02]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__47C66584] DEFAULT ((0)) FOR [AdjustedChargeDollars03]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__48BA89BD] DEFAULT ((0)) FOR [AdjustedChargeDollars04]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__49AEADF6] DEFAULT ((0)) FOR [AdjustedChargeDollars05]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__4AA2D22F] DEFAULT ((0)) FOR [AdjustedChargeDollars06]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__4B96F668] DEFAULT ((0)) FOR [AdjustedChargeDollars07]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__4C8B1AA1] DEFAULT ((0)) FOR [AdjustedChargeDollars08]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__4D7F3EDA] DEFAULT ((0)) FOR [AdjustedChargeDollars09]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__4E736313] DEFAULT ((0)) FOR [AdjustedChargeDollars10]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__4F67874C] DEFAULT ((0)) FOR [AdjustedChargeDollars11]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__505BAB85] DEFAULT ((0)) FOR [AdjustedChargeDollars12]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__5CC1826A] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge01]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__5DB5A6A3] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge02]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__5EA9CADC] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge03]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__5F9DEF15] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge04]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6092134E] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge05]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__61863787] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge06]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__627A5BC0] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge07]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__636E7FF9] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge08]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6462A432] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge09]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6556C86B] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge10]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__664AECA4] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge11]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__673F10DD] DEFAULT ((0)) FOR [AdjustedNetAsPercentOfCharge12]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__68333516] DEFAULT ((0)) FOR [AdjustedNetPerDiem01]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6927594F] DEFAULT ((0)) FOR [AdjustedNetPerDiem02]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6A1B7D88] DEFAULT ((0)) FOR [AdjustedNetPerDiem03]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6B0FA1C1] DEFAULT ((0)) FOR [AdjustedNetPerDiem04]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6C03C5FA] DEFAULT ((0)) FOR [AdjustedNetPerDiem05]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6CF7EA33] DEFAULT ((0)) FOR [AdjustedNetPerDiem06]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6DEC0E6C] DEFAULT ((0)) FOR [AdjustedNetPerDiem07]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6EE032A5] DEFAULT ((0)) FOR [AdjustedNetPerDiem08]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6FD456DE] DEFAULT ((0)) FOR [AdjustedNetPerDiem09]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__70C87B17] DEFAULT ((0)) FOR [AdjustedNetPerDiem10]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__71BC9F50] DEFAULT ((0)) FOR [AdjustedNetPerDiem11]; GO +ALTER TABLE [fp].[FactReimbursementChargesProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__72B0C389] DEFAULT ((0)) FOR [AdjustedNetPerDiem12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReimbursementEncounter ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReimbursementEncounter] ( + [ReimbursementEncounterID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [MSDRGID] int NOT NULL, + [CPTID] int NOT NULL, + [AddDate] datetime NOT NULL, + [InitialBudgetEncounters01] decimal NOT NULL, + [InitialBudgetEncounters02] decimal NOT NULL, + [InitialBudgetEncounters03] decimal NOT NULL, + [InitialBudgetEncounters04] decimal NOT NULL, + [InitialBudgetEncounters05] decimal NOT NULL, + [InitialBudgetEncounters06] decimal NOT NULL, + [InitialBudgetEncounters07] decimal NOT NULL, + [InitialBudgetEncounters08] decimal NOT NULL, + [InitialBudgetEncounters09] decimal NOT NULL, + [InitialBudgetEncounters10] decimal NOT NULL, + [InitialBudgetEncounters11] decimal NOT NULL, + [InitialBudgetEncounters12] decimal NOT NULL, + [InitialBudgetNetPerEncounter01] decimal NOT NULL, + [InitialBudgetNetPerEncounter02] decimal NOT NULL, + [InitialBudgetNetPerEncounter03] decimal NOT NULL, + [InitialBudgetNetPerEncounter04] decimal NOT NULL, + [InitialBudgetNetPerEncounter05] decimal NOT NULL, + [InitialBudgetNetPerEncounter06] decimal NOT NULL, + [InitialBudgetNetPerEncounter07] decimal NOT NULL, + [InitialBudgetNetPerEncounter08] decimal NOT NULL, + [InitialBudgetNetPerEncounter09] decimal NOT NULL, + [InitialBudgetNetPerEncounter10] decimal NOT NULL, + [InitialBudgetNetPerEncounter11] decimal NOT NULL, + [InitialBudgetNetPerEncounter12] decimal NOT NULL, + [InitialProjectionEncounters01] decimal NOT NULL, + [InitialProjectionEncounters02] decimal NOT NULL, + [InitialProjectionEncounters03] decimal NOT NULL, + [InitialProjectionEncounters04] decimal NOT NULL, + [InitialProjectionEncounters05] decimal NOT NULL, + [InitialProjectionEncounters06] decimal NOT NULL, + [InitialProjectionEncounters07] decimal NOT NULL, + [InitialProjectionEncounters08] decimal NOT NULL, + [InitialProjectionEncounters09] decimal NOT NULL, + [InitialProjectionEncounters10] decimal NOT NULL, + [InitialProjectionEncounters11] decimal NOT NULL, + [InitialProjectionEncounters12] decimal NOT NULL, + [InitialProjectionNetPerEncounter01] decimal NOT NULL, + [InitialProjectionNetPerEncounter02] decimal NOT NULL, + [InitialProjectionNetPerEncounter03] decimal NOT NULL, + [InitialProjectionNetPerEncounter04] decimal NOT NULL, + [InitialProjectionNetPerEncounter05] decimal NOT NULL, + [InitialProjectionNetPerEncounter06] decimal NOT NULL, + [InitialProjectionNetPerEncounter07] decimal NOT NULL, + [InitialProjectionNetPerEncounter08] decimal NOT NULL, + [InitialProjectionNetPerEncounter09] decimal NOT NULL, + [InitialProjectionNetPerEncounter10] decimal NOT NULL, + [InitialProjectionNetPerEncounter11] decimal NOT NULL, + [InitialProjectionNetPerEncounter12] decimal NOT NULL, + [IsNew] bit NOT NULL, + [InitialBudgetEncountersTotal] decimal NOT NULL, + [InitialProjectionEncountersTotal] decimal NOT NULL, + [InitialBudgetNetReimbursement01] decimal NOT NULL, + [InitialBudgetNetReimbursement02] decimal NOT NULL, + [InitialBudgetNetReimbursement03] decimal NOT NULL, + [InitialBudgetNetReimbursement04] decimal NOT NULL, + [InitialBudgetNetReimbursement05] decimal NOT NULL, + [InitialBudgetNetReimbursement06] decimal NOT NULL, + [InitialBudgetNetReimbursement07] decimal NOT NULL, + [InitialBudgetNetReimbursement08] decimal NOT NULL, + [InitialBudgetNetReimbursement09] decimal NOT NULL, + [InitialBudgetNetReimbursement10] decimal NOT NULL, + [InitialBudgetNetReimbursement11] decimal NOT NULL, + [InitialBudgetNetReimbursement12] decimal NOT NULL, + [InitialProjectionNetReimbursement01] decimal NOT NULL, + [InitialProjectionNetReimbursement02] decimal NOT NULL, + [InitialProjectionNetReimbursement03] decimal NOT NULL, + [InitialProjectionNetReimbursement04] decimal NOT NULL, + [InitialProjectionNetReimbursement05] decimal NOT NULL, + [InitialProjectionNetReimbursement06] decimal NOT NULL, + [InitialProjectionNetReimbursement07] decimal NOT NULL, + [InitialProjectionNetReimbursement08] decimal NOT NULL, + [InitialProjectionNetReimbursement09] decimal NOT NULL, + [InitialProjectionNetReimbursement10] decimal NOT NULL, + [InitialProjectionNetReimbursement11] decimal NOT NULL, + [InitialProjectionNetReimbursement12] decimal NOT NULL, + PRIMARY KEY ([ReimbursementEncounterID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [CORE_FactReimbursementEncounterUnique] ON [fp].[FactReimbursementEncounter] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [MedicalSurgicalID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID]); +GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [FK_FactReimbursementEncounter_CPT] FOREIGN KEY ([CPTID]) REFERENCES [dss].[DimCPT] ([CPTID]); GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [FK_FactReimbursementEncounter_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [FK_FactReimbursementEncounter_MedicalSurgical] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [FK_FactReimbursementEncounter_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [FK_FactReimbursementEncounter_Payor] FOREIGN KEY ([PayorID]) REFERENCES [fw].[DimPayor] ([PayorID]); GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [FK_FactReimbursementEncounter_PayorGroup] FOREIGN KEY ([PayorGroupID]) REFERENCES [fw].[DimPayorGroup] ([PayorGroupID]); GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [FK_FactReimbursementEncounter_ServiceLine] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [FK_FactReimbursementEncounter_ServiceLineRollup] FOREIGN KEY ([ServiceLineRollupID]) REFERENCES [fw].[DimServiceLineRollup] ([ServiceLineRollupID]); GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Budge__017E05CD] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Entit__02722A06] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Entit__03664E3F] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Patie__045A7278] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Servi__054E96B1] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Servi__0642BAEA] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Medic__0736DF23] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Payor__091F2795] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Payor__0A134BCE] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__MSDRG__0B077007] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__CPTID__0BFB9440] DEFAULT ((0)) FOR [CPTID]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF_ReimbursementEncounter_AddDate] DEFAULT ('1900-01-01') FOR [AddDate]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__0ED800EB] DEFAULT ((0)) FOR [InitialBudgetEncounters01]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__0FCC2524] DEFAULT ((0)) FOR [InitialBudgetEncounters02]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__10C0495D] DEFAULT ((0)) FOR [InitialBudgetEncounters03]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__11B46D96] DEFAULT ((0)) FOR [InitialBudgetEncounters04]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__12A891CF] DEFAULT ((0)) FOR [InitialBudgetEncounters05]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__139CB608] DEFAULT ((0)) FOR [InitialBudgetEncounters06]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__1490DA41] DEFAULT ((0)) FOR [InitialBudgetEncounters07]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__1584FE7A] DEFAULT ((0)) FOR [InitialBudgetEncounters08]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__167922B3] DEFAULT ((0)) FOR [InitialBudgetEncounters09]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__176D46EC] DEFAULT ((0)) FOR [InitialBudgetEncounters10]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__18616B25] DEFAULT ((0)) FOR [InitialBudgetEncounters11]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__19558F5E] DEFAULT ((0)) FOR [InitialBudgetEncounters12]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__1A49B397] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter01]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__1B3DD7D0] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter02]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__1C31FC09] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter03]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__1D262042] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter04]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__1E1A447B] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter05]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__1F0E68B4] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter06]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__20028CED] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter07]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__20F6B126] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter08]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__21EAD55F] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter09]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__22DEF998] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter10]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__23D31DD1] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter11]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__24C7420A] DEFAULT ((0)) FOR [InitialBudgetNetPerEncounter12]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__25BB6643] DEFAULT ((0)) FOR [InitialProjectionEncounters01]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__26AF8A7C] DEFAULT ((0)) FOR [InitialProjectionEncounters02]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__27A3AEB5] DEFAULT ((0)) FOR [InitialProjectionEncounters03]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__2897D2EE] DEFAULT ((0)) FOR [InitialProjectionEncounters04]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__298BF727] DEFAULT ((0)) FOR [InitialProjectionEncounters05]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__2A801B60] DEFAULT ((0)) FOR [InitialProjectionEncounters06]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__2B743F99] DEFAULT ((0)) FOR [InitialProjectionEncounters07]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__2C6863D2] DEFAULT ((0)) FOR [InitialProjectionEncounters08]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__2D5C880B] DEFAULT ((0)) FOR [InitialProjectionEncounters09]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__2E50AC44] DEFAULT ((0)) FOR [InitialProjectionEncounters10]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__2F44D07D] DEFAULT ((0)) FOR [InitialProjectionEncounters11]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__3038F4B6] DEFAULT ((0)) FOR [InitialProjectionEncounters12]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__312D18EF] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter01]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__32213D28] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter02]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__33156161] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter03]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__3409859A] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter04]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__34FDA9D3] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter05]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__35F1CE0C] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter06]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__36E5F245] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter07]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__37DA167E] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter08]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__38CE3AB7] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter09]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__39C25EF0] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter10]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__3AB68329] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter11]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__Initi__3BAAA762] DEFAULT ((0)) FOR [InitialProjectionNetPerEncounter12]; GO +ALTER TABLE [fp].[FactReimbursementEncounter] ADD CONSTRAINT [DF__FactReimb__IsNew__3C9ECB9B] DEFAULT ((0)) FOR [IsNew]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReimbursementEncounterBudget ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReimbursementEncounterBudget] ( + [RowID] int NOT NULL, + [ReimbursementEncounterID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedEncounters01] decimal NOT NULL, + [AdjustedEncounters02] decimal NOT NULL, + [AdjustedEncounters03] decimal NOT NULL, + [AdjustedEncounters04] decimal NOT NULL, + [AdjustedEncounters05] decimal NOT NULL, + [AdjustedEncounters06] decimal NOT NULL, + [AdjustedEncounters07] decimal NOT NULL, + [AdjustedEncounters08] decimal NOT NULL, + [AdjustedEncounters09] decimal NOT NULL, + [AdjustedEncounters10] decimal NOT NULL, + [AdjustedEncounters11] decimal NOT NULL, + [AdjustedEncounters12] decimal NOT NULL, + [AdjustedNetPerEncounterValue01] decimal NOT NULL, + [AdjustedNetPerEncounterValue02] decimal NOT NULL, + [AdjustedNetPerEncounterValue03] decimal NOT NULL, + [AdjustedNetPerEncounterValue04] decimal NOT NULL, + [AdjustedNetPerEncounterValue05] decimal NOT NULL, + [AdjustedNetPerEncounterValue06] decimal NOT NULL, + [AdjustedNetPerEncounterValue07] decimal NOT NULL, + [AdjustedNetPerEncounterValue08] decimal NOT NULL, + [AdjustedNetPerEncounterValue09] decimal NOT NULL, + [AdjustedNetPerEncounterValue10] decimal NOT NULL, + [AdjustedNetPerEncounterValue11] decimal NOT NULL, + [AdjustedNetPerEncounterValue12] decimal NOT NULL, + [AdjustedEncountersTotal] decimal NOT NULL, + [AdjustedNetReimbursementValue01] decimal NOT NULL, + [AdjustedNetReimbursementValue02] decimal NOT NULL, + [AdjustedNetReimbursementValue03] decimal NOT NULL, + [AdjustedNetReimbursementValue04] decimal NOT NULL, + [AdjustedNetReimbursementValue05] decimal NOT NULL, + [AdjustedNetReimbursementValue06] decimal NOT NULL, + [AdjustedNetReimbursementValue07] decimal NOT NULL, + [AdjustedNetReimbursementValue08] decimal NOT NULL, + [AdjustedNetReimbursementValue09] decimal NOT NULL, + [AdjustedNetReimbursementValue10] decimal NOT NULL, + [AdjustedNetReimbursementValue11] decimal NOT NULL, + [AdjustedNetReimbursementValue12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [FK_FactReimbursementEncounterBudget_ReimbursementEncounterID] FOREIGN KEY ([ReimbursementEncounterID]) REFERENCES [fp].[FactReimbursementEncounter] ([ReimbursementEncounterID]); GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Reimb__30F80EC5] DEFAULT ((0)) FOR [ReimbursementEncounterID]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__LockT__31EC32FE] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__LockF__32E05737] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Budge__33D47B70] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__34C89FA9] DEFAULT ((0)) FOR [AdjustedEncounters01]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__35BCC3E2] DEFAULT ((0)) FOR [AdjustedEncounters02]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__36B0E81B] DEFAULT ((0)) FOR [AdjustedEncounters03]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__37A50C54] DEFAULT ((0)) FOR [AdjustedEncounters04]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__3899308D] DEFAULT ((0)) FOR [AdjustedEncounters05]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__398D54C6] DEFAULT ((0)) FOR [AdjustedEncounters06]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__3A8178FF] DEFAULT ((0)) FOR [AdjustedEncounters07]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__3B759D38] DEFAULT ((0)) FOR [AdjustedEncounters08]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__3C69C171] DEFAULT ((0)) FOR [AdjustedEncounters09]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__3D5DE5AA] DEFAULT ((0)) FOR [AdjustedEncounters10]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__3E5209E3] DEFAULT ((0)) FOR [AdjustedEncounters11]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__3F462E1C] DEFAULT ((0)) FOR [AdjustedEncounters12]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__403A5255] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue01]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__412E768E] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue02]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__42229AC7] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue03]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__4316BF00] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue04]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__440AE339] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue05]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__44FF0772] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue06]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__45F32BAB] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue07]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__46E74FE4] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue08]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__47DB741D] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue09]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__48CF9856] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue10]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__49C3BC8F] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue11]; GO +ALTER TABLE [fp].[FactReimbursementEncounterBudget] ADD CONSTRAINT [DF__FactReimb__Adjus__4AB7E0C8] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReimbursementEncounterHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReimbursementEncounterHistory] ( + [RowID] int NOT NULL, + [ReimbursementEncounterID] int NOT NULL, + [PriorYearActualEncounters01] decimal NOT NULL, + [PriorYearActualEncounters02] decimal NOT NULL, + [PriorYearActualEncounters03] decimal NOT NULL, + [PriorYearActualEncounters04] decimal NOT NULL, + [PriorYearActualEncounters05] decimal NOT NULL, + [PriorYearActualEncounters06] decimal NOT NULL, + [PriorYearActualEncounters07] decimal NOT NULL, + [PriorYearActualEncounters08] decimal NOT NULL, + [PriorYearActualEncounters09] decimal NOT NULL, + [PriorYearActualEncounters10] decimal NOT NULL, + [PriorYearActualEncounters11] decimal NOT NULL, + [PriorYearActualEncounters12] decimal NOT NULL, + [ActualYTDEncounters01] decimal NOT NULL, + [ActualYTDEncounters02] decimal NOT NULL, + [ActualYTDEncounters03] decimal NOT NULL, + [ActualYTDEncounters04] decimal NOT NULL, + [ActualYTDEncounters05] decimal NOT NULL, + [ActualYTDEncounters06] decimal NOT NULL, + [ActualYTDEncounters07] decimal NOT NULL, + [ActualYTDEncounters08] decimal NOT NULL, + [ActualYTDEncounters09] decimal NOT NULL, + [ActualYTDEncounters10] decimal NOT NULL, + [ActualYTDEncounters11] decimal NOT NULL, + [ActualYTDEncounters12] decimal NOT NULL, + [CurrentYearBudgetEncounters01] decimal NOT NULL, + [CurrentYearBudgetEncounters02] decimal NOT NULL, + [CurrentYearBudgetEncounters03] decimal NOT NULL, + [CurrentYearBudgetEncounters04] decimal NOT NULL, + [CurrentYearBudgetEncounters05] decimal NOT NULL, + [CurrentYearBudgetEncounters06] decimal NOT NULL, + [CurrentYearBudgetEncounters07] decimal NOT NULL, + [CurrentYearBudgetEncounters08] decimal NOT NULL, + [CurrentYearBudgetEncounters09] decimal NOT NULL, + [CurrentYearBudgetEncounters10] decimal NOT NULL, + [CurrentYearBudgetEncounters11] decimal NOT NULL, + [CurrentYearBudgetEncounters12] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue01] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue02] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue03] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue04] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue05] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue06] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue07] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue08] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue09] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue10] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue11] decimal NOT NULL, + [PriorYearActualNetPerEncounterValue12] decimal NOT NULL, + [ActualYTDNetPerEncounterValue01] decimal NOT NULL, + [ActualYTDNetPerEncounterValue02] decimal NOT NULL, + [ActualYTDNetPerEncounterValue03] decimal NOT NULL, + [ActualYTDNetPerEncounterValue04] decimal NOT NULL, + [ActualYTDNetPerEncounterValue05] decimal NOT NULL, + [ActualYTDNetPerEncounterValue06] decimal NOT NULL, + [ActualYTDNetPerEncounterValue07] decimal NOT NULL, + [ActualYTDNetPerEncounterValue08] decimal NOT NULL, + [ActualYTDNetPerEncounterValue09] decimal NOT NULL, + [ActualYTDNetPerEncounterValue10] decimal NOT NULL, + [ActualYTDNetPerEncounterValue11] decimal NOT NULL, + [ActualYTDNetPerEncounterValue12] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget01] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget02] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget03] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget04] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget05] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget06] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget07] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget08] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget09] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget10] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget11] decimal NOT NULL, + [CurrentYearNetPerEncounterBudget12] decimal NOT NULL, + [PriorYearActualEncountersTotal] decimal NOT NULL, + [ActualYTDEncountersTotal] decimal NOT NULL, + [CurrentYearBudgetEncountersTotal] decimal NOT NULL, + [PriorYearActualNetReimbursementValue01] decimal NOT NULL, + [PriorYearActualNetReimbursementValue02] decimal NOT NULL, + [PriorYearActualNetReimbursementValue03] decimal NOT NULL, + [PriorYearActualNetReimbursementValue04] decimal NOT NULL, + [PriorYearActualNetReimbursementValue05] decimal NOT NULL, + [PriorYearActualNetReimbursementValue06] decimal NOT NULL, + [PriorYearActualNetReimbursementValue07] decimal NOT NULL, + [PriorYearActualNetReimbursementValue08] decimal NOT NULL, + [PriorYearActualNetReimbursementValue09] decimal NOT NULL, + [PriorYearActualNetReimbursementValue10] decimal NOT NULL, + [PriorYearActualNetReimbursementValue11] decimal NOT NULL, + [PriorYearActualNetReimbursementValue12] decimal NOT NULL, + [ActualYTDNetReimbursementValue01] decimal NOT NULL, + [ActualYTDNetReimbursementValue02] decimal NOT NULL, + [ActualYTDNetReimbursementValue03] decimal NOT NULL, + [ActualYTDNetReimbursementValue04] decimal NOT NULL, + [ActualYTDNetReimbursementValue05] decimal NOT NULL, + [ActualYTDNetReimbursementValue06] decimal NOT NULL, + [ActualYTDNetReimbursementValue07] decimal NOT NULL, + [ActualYTDNetReimbursementValue08] decimal NOT NULL, + [ActualYTDNetReimbursementValue09] decimal NOT NULL, + [ActualYTDNetReimbursementValue10] decimal NOT NULL, + [ActualYTDNetReimbursementValue11] decimal NOT NULL, + [ActualYTDNetReimbursementValue12] decimal NOT NULL, + [CurrentYearNetReimbursementBudget01] decimal NOT NULL, + [CurrentYearNetReimbursementBudget02] decimal NOT NULL, + [CurrentYearNetReimbursementBudget03] decimal NOT NULL, + [CurrentYearNetReimbursementBudget04] decimal NOT NULL, + [CurrentYearNetReimbursementBudget05] decimal NOT NULL, + [CurrentYearNetReimbursementBudget06] decimal NOT NULL, + [CurrentYearNetReimbursementBudget07] decimal NOT NULL, + [CurrentYearNetReimbursementBudget08] decimal NOT NULL, + [CurrentYearNetReimbursementBudget09] decimal NOT NULL, + [CurrentYearNetReimbursementBudget10] decimal NOT NULL, + [CurrentYearNetReimbursementBudget11] decimal NOT NULL, + [CurrentYearNetReimbursementBudget12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [FK_FactReimbursementEncounterHistory_ReimbursementEncounterID] FOREIGN KEY ([ReimbursementEncounterID]) REFERENCES [fp].[FactReimbursementEncounter] ([ReimbursementEncounterID]); GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Reimb__13BCB199] DEFAULT ((0)) FOR [ReimbursementEncounterID]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__14B0D5D2] DEFAULT ((0)) FOR [PriorYearActualEncounters01]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__15A4FA0B] DEFAULT ((0)) FOR [PriorYearActualEncounters02]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__16991E44] DEFAULT ((0)) FOR [PriorYearActualEncounters03]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__178D427D] DEFAULT ((0)) FOR [PriorYearActualEncounters04]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__188166B6] DEFAULT ((0)) FOR [PriorYearActualEncounters05]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__19758AEF] DEFAULT ((0)) FOR [PriorYearActualEncounters06]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__1A69AF28] DEFAULT ((0)) FOR [PriorYearActualEncounters07]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__1B5DD361] DEFAULT ((0)) FOR [PriorYearActualEncounters08]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__1C51F79A] DEFAULT ((0)) FOR [PriorYearActualEncounters09]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__1D461BD3] DEFAULT ((0)) FOR [PriorYearActualEncounters10]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__1E3A400C] DEFAULT ((0)) FOR [PriorYearActualEncounters11]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__1F2E6445] DEFAULT ((0)) FOR [PriorYearActualEncounters12]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__2022887E] DEFAULT ((0)) FOR [ActualYTDEncounters01]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__2116ACB7] DEFAULT ((0)) FOR [ActualYTDEncounters02]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__220AD0F0] DEFAULT ((0)) FOR [ActualYTDEncounters03]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__22FEF529] DEFAULT ((0)) FOR [ActualYTDEncounters04]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__23F31962] DEFAULT ((0)) FOR [ActualYTDEncounters05]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__24E73D9B] DEFAULT ((0)) FOR [ActualYTDEncounters06]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__25DB61D4] DEFAULT ((0)) FOR [ActualYTDEncounters07]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__26CF860D] DEFAULT ((0)) FOR [ActualYTDEncounters08]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__27C3AA46] DEFAULT ((0)) FOR [ActualYTDEncounters09]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__28B7CE7F] DEFAULT ((0)) FOR [ActualYTDEncounters10]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__29ABF2B8] DEFAULT ((0)) FOR [ActualYTDEncounters11]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__2AA016F1] DEFAULT ((0)) FOR [ActualYTDEncounters12]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__2B943B2A] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters01]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__2C885F63] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters02]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__2D7C839C] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters03]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__2E70A7D5] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters04]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__2F64CC0E] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters05]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__3058F047] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters06]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__314D1480] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters07]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__324138B9] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters08]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__33355CF2] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters09]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__3429812B] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters10]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__351DA564] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters11]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__3611C99D] DEFAULT ((0)) FOR [CurrentYearBudgetEncounters12]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__3705EDD6] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue01]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__37FA120F] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue02]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__38EE3648] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue03]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__39E25A81] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue04]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__3AD67EBA] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue05]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__3BCAA2F3] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue06]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__3CBEC72C] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue07]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__3DB2EB65] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue08]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__3EA70F9E] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue09]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__3F9B33D7] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue10]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__408F5810] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue11]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Prior__41837C49] DEFAULT ((0)) FOR [PriorYearActualNetPerEncounterValue12]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4277A082] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue01]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__436BC4BB] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue02]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__445FE8F4] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue03]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__45540D2D] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue04]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__46483166] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue05]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__473C559F] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue06]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__483079D8] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue07]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__49249E11] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue08]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4A18C24A] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue09]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4B0CE683] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue10]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4C010ABC] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue11]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Actua__4CF52EF5] DEFAULT ((0)) FOR [ActualYTDNetPerEncounterValue12]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__4DE9532E] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget01]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__4EDD7767] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget02]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__4FD19BA0] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget03]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__50C5BFD9] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget04]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__51B9E412] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget05]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__52AE084B] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget06]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__53A22C84] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget07]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__549650BD] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget08]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__558A74F6] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget09]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__567E992F] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget10]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__5772BD68] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget11]; GO +ALTER TABLE [fp].[FactReimbursementEncounterHistory] ADD CONSTRAINT [DF__FactReimb__Curre__5866E1A1] DEFAULT ((0)) FOR [CurrentYearNetPerEncounterBudget12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReimbursementEncounterProjection ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReimbursementEncounterProjection] ( + [RowID] int NOT NULL, + [ReimbursementEncounterID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedEncounters01] decimal NOT NULL, + [AdjustedEncounters02] decimal NOT NULL, + [AdjustedEncounters03] decimal NOT NULL, + [AdjustedEncounters04] decimal NOT NULL, + [AdjustedEncounters05] decimal NOT NULL, + [AdjustedEncounters06] decimal NOT NULL, + [AdjustedEncounters07] decimal NOT NULL, + [AdjustedEncounters08] decimal NOT NULL, + [AdjustedEncounters09] decimal NOT NULL, + [AdjustedEncounters10] decimal NOT NULL, + [AdjustedEncounters11] decimal NOT NULL, + [AdjustedEncounters12] decimal NOT NULL, + [AdjustedNetPerEncounterValue01] decimal NOT NULL, + [AdjustedNetPerEncounterValue02] decimal NOT NULL, + [AdjustedNetPerEncounterValue03] decimal NOT NULL, + [AdjustedNetPerEncounterValue04] decimal NOT NULL, + [AdjustedNetPerEncounterValue05] decimal NOT NULL, + [AdjustedNetPerEncounterValue06] decimal NOT NULL, + [AdjustedNetPerEncounterValue07] decimal NOT NULL, + [AdjustedNetPerEncounterValue08] decimal NOT NULL, + [AdjustedNetPerEncounterValue09] decimal NOT NULL, + [AdjustedNetPerEncounterValue10] decimal NOT NULL, + [AdjustedNetPerEncounterValue11] decimal NOT NULL, + [AdjustedNetPerEncounterValue12] decimal NOT NULL, + [AdjustedEncountersTotal] decimal NOT NULL, + [AdjustedNetReimbursementValue01] decimal NOT NULL, + [AdjustedNetReimbursementValue02] decimal NOT NULL, + [AdjustedNetReimbursementValue03] decimal NOT NULL, + [AdjustedNetReimbursementValue04] decimal NOT NULL, + [AdjustedNetReimbursementValue05] decimal NOT NULL, + [AdjustedNetReimbursementValue06] decimal NOT NULL, + [AdjustedNetReimbursementValue07] decimal NOT NULL, + [AdjustedNetReimbursementValue08] decimal NOT NULL, + [AdjustedNetReimbursementValue09] decimal NOT NULL, + [AdjustedNetReimbursementValue10] decimal NOT NULL, + [AdjustedNetReimbursementValue11] decimal NOT NULL, + [AdjustedNetReimbursementValue12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [FK_FactReimbursementEncounterProjection_ReimbursementEncounterID] FOREIGN KEY ([ReimbursementEncounterID]) REFERENCES [fp].[FactReimbursementEncounter] ([ReimbursementEncounterID]); GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__001FCD40] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue06]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__0113F179] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue07]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__020815B2] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue08]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__02FC39EB] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue09]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__03F05E24] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue10]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__04E4825D] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue11]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__05D8A696] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue12]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Reimb__6C18D493] DEFAULT ((0)) FOR [ReimbursementEncounterID]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__LockT__6D0CF8CC] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__LockF__6E011D05] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Budge__6EF5413E] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__6FE96577] DEFAULT ((0)) FOR [AdjustedEncounters01]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__70DD89B0] DEFAULT ((0)) FOR [AdjustedEncounters02]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__71D1ADE9] DEFAULT ((0)) FOR [AdjustedEncounters03]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__72C5D222] DEFAULT ((0)) FOR [AdjustedEncounters04]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__73B9F65B] DEFAULT ((0)) FOR [AdjustedEncounters05]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__74AE1A94] DEFAULT ((0)) FOR [AdjustedEncounters06]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__75A23ECD] DEFAULT ((0)) FOR [AdjustedEncounters07]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__76966306] DEFAULT ((0)) FOR [AdjustedEncounters08]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__778A873F] DEFAULT ((0)) FOR [AdjustedEncounters09]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__787EAB78] DEFAULT ((0)) FOR [AdjustedEncounters10]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__7972CFB1] DEFAULT ((0)) FOR [AdjustedEncounters11]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__7A66F3EA] DEFAULT ((0)) FOR [AdjustedEncounters12]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__7B5B1823] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue01]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__7C4F3C5C] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue02]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__7D436095] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue03]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__7E3784CE] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue04]; GO +ALTER TABLE [fp].[FactReimbursementEncounterProjection] ADD CONSTRAINT [DF__FactReimb__Adjus__7F2BA907] DEFAULT ((0)) FOR [AdjustedNetPerEncounterValue05]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportAdjustmentHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportAdjustmentHistory] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [SectionID] int NOT NULL, + [AdjustmentID] int NOT NULL, + [AdjustmentType] int NOT NULL, + [Months] nvarchar(50) NOT NULL, + [AdjustmentValue] nvarchar(max) NOT NULL, + [AdjustedLevel] nvarchar(max) NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [LastModifiedDateUtc] datetime NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [ClassificationGroupID] int NOT NULL, + [ClassificationCategoryID] int NOT NULL, + [IsSetValue] bit NOT NULL, + [IsErrored] bit NOT NULL, + [IsRecordDeleted] bit NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE NONCLUSTERED INDEX [IX_FactReportAdjustmentHistory_BudgetConfigID] ON [fp].[FactReportAdjustmentHistory] ([BudgetConfigID], [SectionID], [AdjustmentID]); +GO +ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Budge__3B5900CD] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Secti__3C4D2506] DEFAULT ((0)) FOR [SectionID]; GO +ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Adjus__3D41493F] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Adjus__3E356D78] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Month__3F2991B1] DEFAULT ('') FOR [Months]; GO +ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Adjus__401DB5EA] DEFAULT ('') FOR [AdjustmentValue]; GO +ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Adjus__4111DA23] DEFAULT ('') FOR [AdjustedLevel]; GO +ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__UnitT__4205FE5C] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__TimeC__42FA2295] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__LastM__43EE46CE] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO +ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__DateC__44E26B07] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Comme__45D68F40] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Autho__46CAB379] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Class__47BED7B2] DEFAULT ((0)) FOR [ClassificationGroupID]; GO +ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__Class__48B2FBEB] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO +ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__IsSet__49A72024] DEFAULT ((0)) FOR [IsSetValue]; GO +ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__IsErr__4A9B445D] DEFAULT ((0)) FOR [IsErrored]; GO +ALTER TABLE [fp].[FactReportAdjustmentHistory] ADD CONSTRAINT [DF__FactRepor__IsRec__4B8F6896] DEFAULT ((0)) FOR [IsRecordDeleted]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportChargeToStatisticsCrosswalk ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ( + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [PatientClassID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalMonthID] tinyint NULL, + [FiscalYearID] smallint NOT NULL, + [RVUWeight] decimal NOT NULL, + [OriginalValue] decimal NOT NULL, + [Value] decimal NOT NULL, + [ManagerValue] decimal NOT NULL, + [AccountID] int NOT NULL +); + +CREATE CLUSTERED INDEX [IDX_FactReportChargeToStatisticsCrosswalk] ON [fp].[FactReportChargeToStatisticsCrosswalk] ([BudgetConfigID], [TimeClassID], [FiscalYearID], [EntityID], [DepartmentID], [ChargeCodeID], [ServiceLineID], [AgeCohortID], [MedicalSurgicalID], [PatientClassID], [UnitTypeID], [FiscalMonthID], [AccountID]); +CREATE NONCLUSTERED INDEX [NCNU_DepartmentID] ON [fp].[FactReportChargeToStatisticsCrosswalk] ([DepartmentID]); +GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Accou__1C538E48] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Budge__6D213C0E] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Entit__6E156047] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Depar__6F098480] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Charg__6FFDA8B9] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Servi__70F1CCF2] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__AgeCo__71E5F12B] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Medic__72DA1564] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Patie__73CE399D] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__UnitT__75B6820F] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__TimeC__76AAA648] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Fisca__779ECA81] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__RVUWe__798712F3] DEFAULT ((0)) FOR [RVUWeight]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Origi__7A7B372C] DEFAULT ((0)) FOR [OriginalValue]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Value__7B6F5B65] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk] ADD CONSTRAINT [DF__FactRepor__Manag__7C637F9E] DEFAULT ((0)) FOR [ManagerValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportChargeToStatisticsCrosswalkHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ( + [ChargeVolumeID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [PatientClassID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalYearID] int NULL, + [FiscalMonthID] tinyint NULL, + [RVUWeight] decimal NOT NULL, + [Value] decimal NOT NULL, + [AccountID] int NOT NULL +); + +CREATE CLUSTERED INDEX [IDX_FactReportChargeToStatisticsCrosswalkHistory] ON [fp].[FactReportChargeToStatisticsCrosswalkHistory] ([BudgetConfigID], [TimeClassID], [FiscalYearID], [UnitTypeID], [ChargeVolumeID], [EntityGroupConfigID], [EntityID], [DepartmentID], [ChargeCodeID], [ServiceLineID], [AgeCohortID], [MedicalSurgicalID], [PatientClassID], [FiscalMonthID], [AccountID]); +CREATE NONCLUSTERED INDEX [NCNU_DepartmentID] ON [fp].[FactReportChargeToStatisticsCrosswalkHistory] ([DepartmentID]); +GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Charg__0F765412] DEFAULT ((0)) FOR [ChargeVolumeID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Budge__106A784B] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Entit__115E9C84] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Entit__1252C0BD] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Depar__1346E4F6] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Charg__143B092F] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Servi__152F2D68] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__AgeCo__162351A1] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Medic__171775DA] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Patie__18FFBE4C] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__UnitT__19F3E285] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__TimeC__1AE806BE] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__RVUWe__1CD04F30] DEFAULT ((0)) FOR [RVUWeight]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Value__1DC47369] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory] ADD CONSTRAINT [DF__FactRepor__Accou__1E3BD6BA] DEFAULT ((0)) FOR [AccountID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportChargeToStatisticsCrosswalkHistory_archive ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ( + [ChargeVolumeID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [PayorID] int NOT NULL, + [PatientClassID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalYearID] int NULL, + [FiscalMonthID] tinyint NULL, + [RVUWeight] decimal NOT NULL, + [Value] decimal NOT NULL, + [AccountID] int NOT NULL +); +GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Accou__1F2FFAF3] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Charg__1FACBBDB] DEFAULT ((0)) FOR [ChargeVolumeID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Budge__20A0E014] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Entit__2195044D] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Entit__22892886] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Depar__237D4CBF] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Charg__247170F8] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Servi__25659531] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__AgeCo__2659B96A] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Medic__274DDDA3] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Payor__284201DC] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Patie__29362615] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__UnitT__2A2A4A4E] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__TimeC__2B1E6E87] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__RVUWe__2D06B6F9] DEFAULT ((0)) FOR [RVUWeight]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] ADD CONSTRAINT [DF__FactRepor__Value__2DFADB32] DEFAULT ((0)) FOR [Value]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportChargeToStatisticsCrosswalk_archive ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ( + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [PatientClassID] int NOT NULL, + [PayorID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalMonthID] tinyint NULL, + [FiscalYearID] smallint NOT NULL, + [RVUWeight] decimal NOT NULL, + [OriginalValue] decimal NOT NULL, + [Value] decimal NOT NULL, + [ManagerValue] decimal NOT NULL, + [AccountID] int NOT NULL +); +GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Depar__00341082] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Charg__012834BB] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Servi__021C58F4] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__AgeCo__03107D2D] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Medic__0404A166] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Patie__04F8C59F] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Payor__05ECE9D8] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__UnitT__06E10E11] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__TimeC__07D5324A] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Fisca__08C95683] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__RVUWe__0AB19EF5] DEFAULT ((0)) FOR [RVUWeight]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Origi__0BA5C32E] DEFAULT ((0)) FOR [OriginalValue]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Value__0C99E767] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Manag__0D8E0BA0] DEFAULT ((0)) FOR [ManagerValue]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Accou__1D47B281] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Budge__7E4BC810] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactReportChargeToStatisticsCrosswalk_archive] ADD CONSTRAINT [DF__FactRepor__Entit__7F3FEC49] DEFAULT ((0)) FOR [EntityID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportChargeVolume ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportChargeVolume] ( + [ChargeVolumeID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [PatientClassID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [ServiceEntityID] int NOT NULL, + [MSDRGID] int NOT NULL, + [UBRevCodeID] int NOT NULL, + [PrimaryCPTID] int NOT NULL, + [ServiceProviderID] int NOT NULL, + [ServiceProviderSpecialtyID] int NOT NULL, + [PerformingProviderID] int NOT NULL, + [PerformingProviderSpecialtyID] int NOT NULL, + [BillingCPTID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [InitialBudget01] decimal NOT NULL, + [InitialBudget02] decimal NOT NULL, + [InitialBudget03] decimal NOT NULL, + [InitialBudget04] decimal NOT NULL, + [InitialBudget05] decimal NOT NULL, + [InitialBudget06] decimal NOT NULL, + [InitialBudget07] decimal NOT NULL, + [InitialBudget08] decimal NOT NULL, + [InitialBudget09] decimal NOT NULL, + [InitialBudget10] decimal NOT NULL, + [InitialBudget11] decimal NOT NULL, + [InitialBudget12] decimal NOT NULL, + [InitialBudgetTotal] decimal NOT NULL, + [Target01] decimal NOT NULL, + [Target02] decimal NOT NULL, + [Target03] decimal NOT NULL, + [Target04] decimal NOT NULL, + [Target05] decimal NOT NULL, + [Target06] decimal NOT NULL, + [Target07] decimal NOT NULL, + [Target08] decimal NOT NULL, + [Target09] decimal NOT NULL, + [Target10] decimal NOT NULL, + [Target11] decimal NOT NULL, + [Target12] decimal NOT NULL, + [TargetTotal] decimal NOT NULL, + [Budget01] decimal NOT NULL, + [Budget02] decimal NOT NULL, + [Budget03] decimal NOT NULL, + [Budget04] decimal NOT NULL, + [Budget05] decimal NOT NULL, + [Budget06] decimal NOT NULL, + [Budget07] decimal NOT NULL, + [Budget08] decimal NOT NULL, + [Budget09] decimal NOT NULL, + [Budget10] decimal NOT NULL, + [Budget11] decimal NOT NULL, + [Budget12] decimal NOT NULL, + [BudgetTotal] decimal NOT NULL, + [Projection01] decimal NOT NULL, + [Projection02] decimal NOT NULL, + [Projection03] decimal NOT NULL, + [Projection04] decimal NOT NULL, + [Projection05] decimal NOT NULL, + [Projection06] decimal NOT NULL, + [Projection07] decimal NOT NULL, + [Projection08] decimal NOT NULL, + [Projection09] decimal NOT NULL, + [Projection10] decimal NOT NULL, + [Projection11] decimal NOT NULL, + [Projection12] decimal NOT NULL, + [ProjectionTotal] decimal NOT NULL +); +GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__0049EA72] DEFAULT ((0)) FOR [Target08]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__013E0EAB] DEFAULT ((0)) FOR [Target09]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__023232E4] DEFAULT ((0)) FOR [Target10]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__0326571D] DEFAULT ((0)) FOR [Target11]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__041A7B56] DEFAULT ((0)) FOR [Target12]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__047CD00E] DEFAULT ((0)) FOR [Projection01]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__050E9F8F] DEFAULT ((0)) FOR [TargetTotal]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__0570F447] DEFAULT ((0)) FOR [Projection02]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__0602C3C8] DEFAULT ((0)) FOR [Budget01]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__06651880] DEFAULT ((0)) FOR [Projection03]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__06F6E801] DEFAULT ((0)) FOR [Budget02]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__07593CB9] DEFAULT ((0)) FOR [Projection04]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__07EB0C3A] DEFAULT ((0)) FOR [Budget03]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__084D60F2] DEFAULT ((0)) FOR [Projection05]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__08DF3073] DEFAULT ((0)) FOR [Budget04]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__0941852B] DEFAULT ((0)) FOR [Projection06]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__09D354AC] DEFAULT ((0)) FOR [Budget05]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__0A35A964] DEFAULT ((0)) FOR [Projection07]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__0AC778E5] DEFAULT ((0)) FOR [Budget06]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__0B29CD9D] DEFAULT ((0)) FOR [Projection08]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__0BBB9D1E] DEFAULT ((0)) FOR [Budget07]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__0C1DF1D6] DEFAULT ((0)) FOR [Projection09]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__0CAFC157] DEFAULT ((0)) FOR [Budget08]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__0D12160F] DEFAULT ((0)) FOR [Projection10]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__0DA3E590] DEFAULT ((0)) FOR [Budget09]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__0E063A48] DEFAULT ((0)) FOR [Projection11]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__0E9809C9] DEFAULT ((0)) FOR [Budget10]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__0EFA5E81] DEFAULT ((0)) FOR [Projection12]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__0F8C2E02] DEFAULT ((0)) FOR [Budget11]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Proje__0FEE82BA] DEFAULT ((0)) FOR [ProjectionTotal]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__1080523B] DEFAULT ((0)) FOR [Budget12]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Manag__11747674] DEFAULT ((0)) FOR [BudgetTotal]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Charg__59301D51] DEFAULT ((0)) FOR [ChargeVolumeID]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Budge__5A24418A] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Entit__5B1865C3] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Depar__5C0C89FC] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Servi__5D00AE35] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Patie__5DF4D26E] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__AgeCo__5EE8F6A7] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Medic__5FDD1AE0] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Charg__60D13F19] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Servi__61C56352] DEFAULT ((0)) FOR [ServiceEntityID]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__MSDRG__62B9878B] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__UBRev__63ADABC4] DEFAULT ((0)) FOR [UBRevCodeID]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Prima__64A1CFFD] DEFAULT ((0)) FOR [PrimaryCPTID]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Servi__6595F436] DEFAULT ((0)) FOR [ServiceProviderID]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Servi__668A186F] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Perfo__677E3CA8] DEFAULT ((0)) FOR [PerformingProviderID]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Perfo__687260E1] DEFAULT ((0)) FOR [PerformingProviderSpecialtyID]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Billi__6966851A] DEFAULT ((0)) FOR [BillingCPTID]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__UnitT__6A5AA953] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__6D3715FE] DEFAULT ((0)) FOR [InitialBudget01]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__6E2B3A37] DEFAULT ((0)) FOR [InitialBudget02]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__6F1F5E70] DEFAULT ((0)) FOR [InitialBudget03]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__701382A9] DEFAULT ((0)) FOR [InitialBudget04]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__7107A6E2] DEFAULT ((0)) FOR [InitialBudget05]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__71FBCB1B] DEFAULT ((0)) FOR [InitialBudget06]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__72EFEF54] DEFAULT ((0)) FOR [InitialBudget07]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__73E4138D] DEFAULT ((0)) FOR [InitialBudget08]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__74D837C6] DEFAULT ((0)) FOR [InitialBudget09]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__75CC5BFF] DEFAULT ((0)) FOR [InitialBudget10]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__76C08038] DEFAULT ((0)) FOR [InitialBudget11]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__77B4A471] DEFAULT ((0)) FOR [InitialBudget12]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Origi__78A8C8AA] DEFAULT ((0)) FOR [InitialBudgetTotal]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__799CECE3] DEFAULT ((0)) FOR [Target01]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__7A91111C] DEFAULT ((0)) FOR [Target02]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__7B853555] DEFAULT ((0)) FOR [Target03]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__7C79598E] DEFAULT ((0)) FOR [Target04]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__7D6D7DC7] DEFAULT ((0)) FOR [Target05]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__7E61A200] DEFAULT ((0)) FOR [Target06]; GO +ALTER TABLE [fp].[FactReportChargeVolume] ADD CONSTRAINT [DF__FactRepor__Value__7F55C639] DEFAULT ((0)) FOR [Target07]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportChargeVolume_archive ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportChargeVolume_archive] ( + [ChargeVolumeID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [PatientClassID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [ServiceEntityID] int NOT NULL, + [MSDRGID] int NOT NULL, + [UBRevCodeID] int NOT NULL, + [PrimaryCPTID] int NOT NULL, + [ServiceProviderID] int NOT NULL, + [ServiceProviderSpecialtyID] int NOT NULL, + [PerformingProviderID] int NOT NULL, + [PerformingProviderSpecialtyID] int NOT NULL, + [BillingCPTID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [OriginalValue01] decimal NOT NULL, + [OriginalValue02] decimal NOT NULL, + [OriginalValue03] decimal NOT NULL, + [OriginalValue04] decimal NOT NULL, + [OriginalValue05] decimal NOT NULL, + [OriginalValue06] decimal NOT NULL, + [OriginalValue07] decimal NOT NULL, + [OriginalValue08] decimal NOT NULL, + [OriginalValue09] decimal NOT NULL, + [OriginalValue10] decimal NOT NULL, + [OriginalValue11] decimal NOT NULL, + [OriginalValue12] decimal NOT NULL, + [OriginalValueTotal] decimal NOT NULL, + [Value01] decimal NOT NULL, + [Value02] decimal NOT NULL, + [Value03] decimal NOT NULL, + [Value04] decimal NOT NULL, + [Value05] decimal NOT NULL, + [Value06] decimal NOT NULL, + [Value07] decimal NOT NULL, + [Value08] decimal NOT NULL, + [Value09] decimal NOT NULL, + [Value10] decimal NOT NULL, + [Value11] decimal NOT NULL, + [Value12] decimal NOT NULL, + [ValueTotal] decimal NOT NULL, + [ManagerValue01] decimal NOT NULL, + [ManagerValue02] decimal NOT NULL, + [ManagerValue03] decimal NOT NULL, + [ManagerValue04] decimal NOT NULL, + [ManagerValue05] decimal NOT NULL, + [ManagerValue06] decimal NOT NULL, + [ManagerValue07] decimal NOT NULL, + [ManagerValue08] decimal NOT NULL, + [ManagerValue09] decimal NOT NULL, + [ManagerValue10] decimal NOT NULL, + [ManagerValue11] decimal NOT NULL, + [ManagerValue12] decimal NOT NULL, + [ManagerValueTotal] decimal NOT NULL, + PRIMARY KEY ([ChargeVolumeID], [TimeClassID], [UnitTypeID]) +); +GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Charg__1450E31F] DEFAULT ((0)) FOR [ChargeVolumeID]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Budge__15450758] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Entit__16392B91] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Depar__172D4FCA] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Servi__18217403] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Patie__1915983C] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__AgeCo__1A09BC75] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Medic__1AFDE0AE] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Charg__1BF204E7] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Servi__1CE62920] DEFAULT ((0)) FOR [ServiceEntityID]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__MSDRG__1DDA4D59] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__UBRev__1ECE7192] DEFAULT ((0)) FOR [UBRevCodeID]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Prima__1FC295CB] DEFAULT ((0)) FOR [PrimaryCPTID]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Servi__20B6BA04] DEFAULT ((0)) FOR [ServiceProviderID]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Servi__21AADE3D] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Perfo__229F0276] DEFAULT ((0)) FOR [PerformingProviderID]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Perfo__239326AF] DEFAULT ((0)) FOR [PerformingProviderSpecialtyID]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Billi__24874AE8] DEFAULT ((0)) FOR [BillingCPTID]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__UnitT__257B6F21] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__TimeC__266F935A] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Fisca__2763B793] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__2857DBCC] DEFAULT ((0)) FOR [OriginalValue01]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__294C0005] DEFAULT ((0)) FOR [OriginalValue02]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__2A40243E] DEFAULT ((0)) FOR [OriginalValue03]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__2B344877] DEFAULT ((0)) FOR [OriginalValue04]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__2C286CB0] DEFAULT ((0)) FOR [OriginalValue05]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__2D1C90E9] DEFAULT ((0)) FOR [OriginalValue06]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__2E10B522] DEFAULT ((0)) FOR [OriginalValue07]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__2F04D95B] DEFAULT ((0)) FOR [OriginalValue08]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__2FF8FD94] DEFAULT ((0)) FOR [OriginalValue09]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__30ED21CD] DEFAULT ((0)) FOR [OriginalValue10]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__31E14606] DEFAULT ((0)) FOR [OriginalValue11]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__32D56A3F] DEFAULT ((0)) FOR [OriginalValue12]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Origi__33C98E78] DEFAULT ((0)) FOR [OriginalValueTotal]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__34BDB2B1] DEFAULT ((0)) FOR [Value01]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__35B1D6EA] DEFAULT ((0)) FOR [Value02]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__36A5FB23] DEFAULT ((0)) FOR [Value03]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__379A1F5C] DEFAULT ((0)) FOR [Value04]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__388E4395] DEFAULT ((0)) FOR [Value05]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__398267CE] DEFAULT ((0)) FOR [Value06]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__3A768C07] DEFAULT ((0)) FOR [Value07]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__3B6AB040] DEFAULT ((0)) FOR [Value08]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__3C5ED479] DEFAULT ((0)) FOR [Value09]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__3D52F8B2] DEFAULT ((0)) FOR [Value10]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__3E471CEB] DEFAULT ((0)) FOR [Value11]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__3F3B4124] DEFAULT ((0)) FOR [Value12]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Value__402F655D] DEFAULT ((0)) FOR [ValueTotal]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__41238996] DEFAULT ((0)) FOR [ManagerValue01]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__4217ADCF] DEFAULT ((0)) FOR [ManagerValue02]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__430BD208] DEFAULT ((0)) FOR [ManagerValue03]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__43FFF641] DEFAULT ((0)) FOR [ManagerValue04]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__44F41A7A] DEFAULT ((0)) FOR [ManagerValue05]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__45E83EB3] DEFAULT ((0)) FOR [ManagerValue06]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__46DC62EC] DEFAULT ((0)) FOR [ManagerValue07]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__47D08725] DEFAULT ((0)) FOR [ManagerValue08]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__48C4AB5E] DEFAULT ((0)) FOR [ManagerValue09]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__49B8CF97] DEFAULT ((0)) FOR [ManagerValue10]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__4AACF3D0] DEFAULT ((0)) FOR [ManagerValue11]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__4BA11809] DEFAULT ((0)) FOR [ManagerValue12]; GO +ALTER TABLE [fp].[FactReportChargeVolume_archive] ADD CONSTRAINT [DF__FactRepor__Manag__4C953C42] DEFAULT ((0)) FOR [ManagerValueTotal]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportChargesNotCrosswalkedData ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportChargesNotCrosswalkedData] ( + [DepartmentID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [PatientClassID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [ProjectionDollarsAdjustedTotal] decimal NOT NULL, + [TargetDollarsAdjustedTotal] decimal NOT NULL, + [BudgetDollarsAdjustedTotal] decimal NOT NULL, + [PayorGroupID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + PRIMARY KEY ([BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [PatientClassID], [ChargeCodeID], [PayorGroupID]) +); +GO +ALTER TABLE [fp].[FactReportChargesNotCrosswalkedData] ADD CONSTRAINT [DF__FactRepor__Depar__219831A9] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactReportChargesNotCrosswalkedData] ADD CONSTRAINT [DF__FactRepor__Charg__228C55E2] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fp].[FactReportChargesNotCrosswalkedData] ADD CONSTRAINT [DF__FactRepor__Patie__23807A1B] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactReportChargesNotCrosswalkedData] ADD CONSTRAINT [DF__FactRepor__Budge__24749E54] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactReportChargesNotCrosswalkedData] ADD CONSTRAINT [DF__FactRepor__Proje__2568C28D] DEFAULT ((0)) FOR [ProjectionDollarsAdjustedTotal]; GO +ALTER TABLE [fp].[FactReportChargesNotCrosswalkedData] ADD CONSTRAINT [DF__FactRepor__Targe__265CE6C6] DEFAULT ((0)) FOR [TargetDollarsAdjustedTotal]; GO +ALTER TABLE [fp].[FactReportChargesNotCrosswalkedData] ADD CONSTRAINT [DF__FactRepor__Budge__27510AFF] DEFAULT ((0)) FOR [BudgetDollarsAdjustedTotal]; GO +ALTER TABLE [fp].[FactReportChargesNotCrosswalkedData] ADD CONSTRAINT [DF__FactRepor__Payor__49E61A25] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[FactReportChargesNotCrosswalkedData] ADD CONSTRAINT [DF__FactRepor__Entit__4ADA3E5E] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportEncounter ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportEncounter] ( + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [PatientClassID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [DepartmentID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [MSDRGID] int NOT NULL, + [CPTID] int NOT NULL, + [ProviderID] int NOT NULL, + [PhysicianSpecialtyID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalMonthID] tinyint NULL, + [FiscalYearID] int NULL, + [OriginalValue] decimal NOT NULL, + [Value] decimal NOT NULL, + [ManagerValue] decimal NOT NULL +); +GO +ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Budge__532C5FE1] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Entit__5420841A] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Servi__5514A853] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Servi__5608CC8C] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO +ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Patie__56FCF0C5] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__AgeCo__57F114FE] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Medic__58E53937] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Depar__59D95D70] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Payor__5ACD81A9] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Payor__5BC1A5E2] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__MSDRG__5CB5CA1B] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__CPTID__5DA9EE54] DEFAULT ((0)) FOR [CPTID]; GO +ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Provi__5E9E128D] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Physi__5F9236C6] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO +ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__UnitT__60865AFF] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__TimeC__617A7F38] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Fisca__626EA371] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Fisca__6362C7AA] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Origi__6456EBE3] DEFAULT ((0)) FOR [OriginalValue]; GO +ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Value__654B101C] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[FactReportEncounter] ADD CONSTRAINT [DF__FactRepor__Manag__663F3455] DEFAULT ((0)) FOR [ManagerValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportEncounterHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportEncounterHistory] ( + [ServiceLineEncounterID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [PatientClassID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [DepartmentID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [MSDRGID] int NOT NULL, + [CPTID] int NOT NULL, + [ProviderID] int NOT NULL, + [PhysicianSpecialtyID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalMonthID] tinyint NULL, + [FiscalYearID] int NULL, + [Value] decimal NOT NULL +); +GO +ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Servi__00F32A91] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Servi__01E74ECA] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Patie__02DB7303] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__AgeCo__03CF973C] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Medic__04C3BB75] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Depar__05B7DFAE] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Payor__06AC03E7] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Payor__07A02820] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__MSDRG__08944C59] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__CPTID__09887092] DEFAULT ((0)) FOR [CPTID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Provi__0A7C94CB] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Physi__0B70B904] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__UnitT__0C64DD3D] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__TimeC__0D590176] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Fisca__0E4D25AF] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Fisca__0F4149E8] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Value__10356E21] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Servi__7D2299AD] DEFAULT ((0)) FOR [ServiceLineEncounterID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Budge__7E16BDE6] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Entit__7F0AE21F] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory] ADD CONSTRAINT [DF__FactRepor__Entit__7FFF0658] DEFAULT ((0)) FOR [EntityID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportEncounterHistory_archive ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportEncounterHistory_archive] ( + [ServiceLineEncounterID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [PatientClassID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [DepartmentID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [MSDRGID] int NOT NULL, + [CPTID] int NOT NULL, + [ProviderID] int NOT NULL, + [PhysicianSpecialtyID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalMonthID] tinyint NULL, + [FiscalYearID] int NULL, + [Value] decimal NOT NULL +); +GO +ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Servi__121DB693] DEFAULT ((0)) FOR [ServiceLineEncounterID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Budge__1311DACC] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Entit__1405FF05] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Entit__14FA233E] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Servi__15EE4777] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Servi__16E26BB0] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Patie__17D68FE9] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__AgeCo__18CAB422] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Medic__19BED85B] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Depar__1AB2FC94] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Payor__1BA720CD] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Payor__1C9B4506] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__MSDRG__1D8F693F] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__CPTID__1E838D78] DEFAULT ((0)) FOR [CPTID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Provi__1F77B1B1] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Physi__206BD5EA] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__UnitT__215FFA23] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__TimeC__22541E5C] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Fisca__23484295] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Fisca__243C66CE] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[FactReportEncounterHistory_archive] ADD CONSTRAINT [DF__FactRepor__Value__25308B07] DEFAULT ((0)) FOR [Value]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportEncounter_archive ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportEncounter_archive] ( + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [PatientClassID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [DepartmentID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [MSDRGID] int NOT NULL, + [CPTID] int NOT NULL, + [ProviderID] int NOT NULL, + [PhysicianSpecialtyID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalMonthID] tinyint NULL, + [FiscalYearID] int NULL, + [OriginalValue] decimal NOT NULL, + [Value] decimal NOT NULL, + [ManagerValue] decimal NOT NULL +); +GO +ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Budge__68277CC7] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Entit__691BA100] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Servi__6A0FC539] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Servi__6B03E972] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO +ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Patie__6BF80DAB] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__AgeCo__6CEC31E4] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Medic__6DE0561D] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Depar__6ED47A56] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Payor__6FC89E8F] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Payor__70BCC2C8] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__MSDRG__71B0E701] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__CPTID__72A50B3A] DEFAULT ((0)) FOR [CPTID]; GO +ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Provi__73992F73] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Physi__748D53AC] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO +ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__UnitT__758177E5] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__TimeC__76759C1E] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Fisca__7769C057] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Fisca__785DE490] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Origi__795208C9] DEFAULT ((0)) FOR [OriginalValue]; GO +ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Value__7A462D02] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[FactReportEncounter_archive] ADD CONSTRAINT [DF__FactRepor__Manag__7B3A513B] DEFAULT ((0)) FOR [ManagerValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportEncountersToChargeDollars ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportEncountersToChargeDollars] ( + [BudgetConfigID] int NOT NULL, + [ServiceEntityID] int NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [MSDRGID] int NOT NULL, + [PrimaryCPTID] int NOT NULL, + [ServiceProviderID] int NOT NULL, + [ServiceProviderSpecialtyID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [DepartmentID] int NOT NULL, + [UBRevCodeID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [TimeClassID] int NOT NULL, + [AdjustmentID] int NOT NULL, + [AdjustmentDate] datetime NOT NULL, + [AdjustmentAuthor] nvarchar(260) NOT NULL, + [AdjustmentClassificationCategoryID] int NOT NULL, + [AdjustmentClassificationGroupID] int NOT NULL, + [AdjustmentComment] nvarchar(max) NOT NULL, + [DollarImpact01] decimal NOT NULL, + [DollarImpact02] decimal NOT NULL, + [DollarImpact03] decimal NOT NULL, + [DollarImpact04] decimal NOT NULL, + [DollarImpact05] decimal NOT NULL, + [DollarImpact06] decimal NOT NULL, + [DollarImpact07] decimal NOT NULL, + [DollarImpact08] decimal NOT NULL, + [DollarImpact09] decimal NOT NULL, + [DollarImpact10] decimal NOT NULL, + [DollarImpact11] decimal NOT NULL, + [DollarImpact12] decimal NOT NULL, + [DollarImpactTotal] decimal NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL +); + +CREATE NONCLUSTERED INDEX [CORE_Dimensionality_FactReportEncountersToChargeDollars] ON [fp].[FactReportEncountersToChargeDollars] ([BudgetConfigID], [ServiceEntityID], [EntityID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [MSDRGID], [PrimaryCPTID], [ServiceProviderID], [ServiceProviderSpecialtyID], [ServiceLineID], [ServiceLineRollupID], [DepartmentID], [UBRevCodeID], [PayorID], [PayorGroupID], [TimeClassID], [AdjustmentID]); +GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Adjus__08FFF75B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF_FactReportEncountersToChargeDollars_AdjustmentComment] DEFAULT ('') FOR [AdjustmentComment]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Budge__36C5F6B4] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Servi__37BA1AED] DEFAULT ((0)) FOR [ServiceEntityID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Entit__38AE3F26] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Patie__39A2635F] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__AgeCo__3A968798] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Medic__3B8AABD1] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__MSDRG__3C7ED00A] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Prima__3D72F443] DEFAULT ((0)) FOR [PrimaryCPTID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Servi__3E67187C] DEFAULT ((0)) FOR [ServiceProviderID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Servi__3F5B3CB5] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Servi__404F60EE] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Servi__41438527] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Depar__4237A960] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__UBRev__432BCD99] DEFAULT ((0)) FOR [UBRevCodeID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Payor__441FF1D2] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Payor__4514160B] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__TimeC__46083A44] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Adjus__46FC5E7D] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Adjus__47F082B6] DEFAULT (getutcdate()) FOR [AdjustmentDate]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Adjus__48E4A6EF] DEFAULT ('') FOR [AdjustmentAuthor]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Adjus__49D8CB28] DEFAULT ((0)) FOR [AdjustmentClassificationCategoryID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Adjus__4ACCEF61] DEFAULT ((0)) FOR [AdjustmentClassificationGroupID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__4CB537D3] DEFAULT ((0)) FOR [DollarImpact01]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__4DA95C0C] DEFAULT ((0)) FOR [DollarImpact02]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__4E9D8045] DEFAULT ((0)) FOR [DollarImpact03]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__4F91A47E] DEFAULT ((0)) FOR [DollarImpact04]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__5085C8B7] DEFAULT ((0)) FOR [DollarImpact05]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__5179ECF0] DEFAULT ((0)) FOR [DollarImpact06]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__526E1129] DEFAULT ((0)) FOR [DollarImpact07]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__53623562] DEFAULT ((0)) FOR [DollarImpact08]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__5456599B] DEFAULT ((0)) FOR [DollarImpact09]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__554A7DD4] DEFAULT ((0)) FOR [DollarImpact10]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__563EA20D] DEFAULT ((0)) FOR [DollarImpact11]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars] ADD CONSTRAINT [DF__FactRepor__Dolla__5732C646] DEFAULT ((0)) FOR [DollarImpact12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportEncountersToChargeDollars_Initial ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ( + [BudgetConfigID] int NOT NULL, + [ServiceEntityID] int NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [MSDRGID] int NOT NULL, + [PrimaryCPTID] int NOT NULL, + [ServiceProviderID] int NOT NULL, + [ServiceProviderSpecialtyID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [DepartmentID] int NOT NULL, + [UBRevCodeID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [TimeClassID] int NOT NULL, + [AdjustmentID] int NOT NULL, + [AdjustmentDate] datetime NOT NULL, + [AdjustmentAuthor] nvarchar(260) NOT NULL, + [AdjustmentClassificationCategoryID] int NOT NULL, + [AdjustmentClassificationGroupID] int NOT NULL, + [AdjustmentComment] nvarchar(max) NOT NULL, + [DollarImpact01] decimal NOT NULL, + [DollarImpact02] decimal NOT NULL, + [DollarImpact03] decimal NOT NULL, + [DollarImpact04] decimal NOT NULL, + [DollarImpact05] decimal NOT NULL, + [DollarImpact06] decimal NOT NULL, + [DollarImpact07] decimal NOT NULL, + [DollarImpact08] decimal NOT NULL, + [DollarImpact09] decimal NOT NULL, + [DollarImpact10] decimal NOT NULL, + [DollarImpact11] decimal NOT NULL, + [DollarImpact12] decimal NOT NULL, + [DollarImpactTotal] decimal NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL +); + +CREATE NONCLUSTERED INDEX [CORE_Dimensionality_FactReportEncountersToChargeDollars_Initial] ON [fp].[FactReportEncountersToChargeDollars_Initial] ([BudgetConfigID], [ServiceEntityID], [EntityID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [MSDRGID], [PrimaryCPTID], [ServiceProviderID], [ServiceProviderSpecialtyID], [ServiceLineID], [ServiceLineRollupID], [DepartmentID], [UBRevCodeID], [PayorID], [PayorGroupID], [TimeClassID], [AdjustmentID]); +GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__0AE83FCD] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Budge__1470DEB0] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Servi__156502E9] DEFAULT ((0)) FOR [ServiceEntityID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Entit__16592722] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Patie__174D4B5B] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__AgeCo__18416F94] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Medic__193593CD] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__MSDRG__1A29B806] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Prima__1B1DDC3F] DEFAULT ((0)) FOR [PrimaryCPTID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Servi__1C120078] DEFAULT ((0)) FOR [ServiceProviderID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Servi__1D0624B1] DEFAULT ((0)) FOR [ServiceProviderSpecialtyID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Servi__1DFA48EA] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Servi__1EEE6D23] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Depar__1FE2915C] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__UBRev__20D6B595] DEFAULT ((0)) FOR [UBRevCodeID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Payor__21CAD9CE] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Payor__22BEFE07] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__TimeC__23B32240] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__24A74679] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__259B6AB2] DEFAULT (getutcdate()) FOR [AdjustmentDate]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__268F8EEB] DEFAULT ('') FOR [AdjustmentAuthor]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__2783B324] DEFAULT ((0)) FOR [AdjustmentClassificationCategoryID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__2877D75D] DEFAULT ((0)) FOR [AdjustmentClassificationGroupID]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__2A601FCF] DEFAULT ((0)) FOR [DollarImpact01]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__2B544408] DEFAULT ((0)) FOR [DollarImpact02]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__2C486841] DEFAULT ((0)) FOR [DollarImpact03]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF_FactReportEncountersToChargeDollars_Initial_AdjustmentComment] DEFAULT ('') FOR [AdjustmentComment]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__2D3C8C7A] DEFAULT ((0)) FOR [DollarImpact04]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__2E30B0B3] DEFAULT ((0)) FOR [DollarImpact05]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__2F24D4EC] DEFAULT ((0)) FOR [DollarImpact06]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__3018F925] DEFAULT ((0)) FOR [DollarImpact07]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__310D1D5E] DEFAULT ((0)) FOR [DollarImpact08]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__32014197] DEFAULT ((0)) FOR [DollarImpact09]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__32F565D0] DEFAULT ((0)) FOR [DollarImpact10]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__33E98A09] DEFAULT ((0)) FOR [DollarImpact11]; GO +ALTER TABLE [fp].[FactReportEncountersToChargeDollars_Initial] ADD CONSTRAINT [DF__FactRepor__Dolla__34DDAE42] DEFAULT ((0)) FOR [DollarImpact12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportEncountersToStats ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportEncountersToStats] ( + [BudgetConfigID] int NOT NULL, + [ServiceEntityID] int NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [MSDRGID] int NOT NULL, + [PrimaryCPTID] int NOT NULL, + [PerformingProviderID] int NOT NULL, + [ProviderID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [PayorID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalMonthID] int NOT NULL, + [AdjustmentID] int NOT NULL, + [AdjustmentDate] datetime NOT NULL, + [AdjustmentAuthor] nvarchar(260) NOT NULL, + [AdjustmentClassificationCategoryID] int NOT NULL, + [AdjustmentClassificationGroupID] int NOT NULL, + [AdjustmentComment] nvarchar(max) NOT NULL, + [StatisticsImpact] decimal NOT NULL, + [EncountersImpact] decimal NOT NULL, + [ChargeVolumeImpact] decimal NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL +); +GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Adjus__09F41B94] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF_FactReportEncountersToStats_AdjustmentComment] DEFAULT ('') FOR [AdjustmentComment]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Encou__2DD0BE00] DEFAULT ((0)) FOR [EncountersImpact]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Charg__2FB90672] DEFAULT ((0)) FOR [ChargeVolumeImpact]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Servi__54EA8B21] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Servi__56D2D393] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Budge__5E1EEFA0] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Servi__5F1313D9] DEFAULT ((0)) FOR [ServiceEntityID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Entit__60073812] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Patie__60FB5C4B] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__AgeCo__61EF8084] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Medic__62E3A4BD] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__MSDRG__63D7C8F6] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Prima__64CBED2F] DEFAULT ((0)) FOR [PrimaryCPTID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Perfo__65C01168] DEFAULT ((0)) FOR [PerformingProviderID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Provi__66B435A1] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Depar__67A859DA] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Accou__689C7E13] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Payor__6990A24C] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Finan__6A84C685] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__TimeC__6B78EABE] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Fisca__6C6D0EF7] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Adjus__6D613330] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Adjus__6E555769] DEFAULT (getutcdate()) FOR [AdjustmentDate]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Adjus__6F497BA2] DEFAULT ('') FOR [AdjustmentAuthor]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Adjus__703D9FDB] DEFAULT ((0)) FOR [AdjustmentClassificationCategoryID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Adjus__7131C414] DEFAULT ((0)) FOR [AdjustmentClassificationGroupID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats] ADD CONSTRAINT [DF__FactRepor__Stati__731A0C86] DEFAULT ((0)) FOR [StatisticsImpact]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportEncountersToStats_Initial ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportEncountersToStats_Initial] ( + [BudgetConfigID] int NOT NULL, + [ServiceEntityID] int NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [MSDRGID] int NOT NULL, + [PrimaryCPTID] int NOT NULL, + [PerformingProviderID] int NOT NULL, + [ProviderID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [PayorID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalMonthID] int NOT NULL, + [AdjustmentID] int NOT NULL, + [AdjustmentDate] datetime NOT NULL, + [AdjustmentAuthor] nvarchar(260) NOT NULL, + [AdjustmentClassificationCategoryID] int NOT NULL, + [AdjustmentClassificationGroupID] int NOT NULL, + [AdjustmentComment] nvarchar(max) NOT NULL, + [StatisticsImpact] decimal NOT NULL, + [EncountersImpact] decimal NOT NULL, + [ChargeVolumeImpact] decimal NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL +); +GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__0BDC6406] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Budge__1A33D9A7] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Servi__1B27FDE0] DEFAULT ((0)) FOR [ServiceEntityID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Entit__1C1C2219] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Patie__1D104652] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__AgeCo__1E046A8B] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Medic__1EF88EC4] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__MSDRG__1FECB2FD] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Prima__20E0D736] DEFAULT ((0)) FOR [PrimaryCPTID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Perfo__21D4FB6F] DEFAULT ((0)) FOR [PerformingProviderID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Provi__22C91FA8] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Depar__23BD43E1] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Accou__24B1681A] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Payor__25A58C53] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Finan__2699B08C] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__TimeC__278DD4C5] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Fisca__2881F8FE] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__29761D37] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__2A6A4170] DEFAULT (getutcdate()) FOR [AdjustmentDate]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__2B5E65A9] DEFAULT ('') FOR [AdjustmentAuthor]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__2C5289E2] DEFAULT ((0)) FOR [AdjustmentClassificationCategoryID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Adjus__2D46AE1B] DEFAULT ((0)) FOR [AdjustmentClassificationGroupID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF_FactReportEncountersToStats_Initial_AdjustmentComment] DEFAULT ('') FOR [AdjustmentComment]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Encou__2EC4E239] DEFAULT ((0)) FOR [EncountersImpact]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Stati__2F2EF68D] DEFAULT ((0)) FOR [StatisticsImpact]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Charg__30AD2AAB] DEFAULT ((0)) FOR [ChargeVolumeImpact]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Servi__55DEAF5A] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[FactReportEncountersToStats_Initial] ADD CONSTRAINT [DF__FactRepor__Servi__57C6F7CC] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportGeneralLedger ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportGeneralLedger] ( + [GeneralLedgerID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [APEModelSectionID] tinyint NOT NULL, + [VariabilityID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalYearID] int NULL, + [FiscalMonthID] tinyint NULL, + [LockType] int NULL, + [OriginalValue] decimal NULL, + [Value] decimal NULL, + [ManagerValue] decimal NULL, + [Rate] decimal NULL +); + +CREATE CLUSTERED INDEX [IDX_FactReportGeneralLedger] ON [fp].[FactReportGeneralLedger] ([BudgetConfigID], [TimeClassID], [FiscalYearID], [UnitTypeID], [GeneralLedgerID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [APEModelSectionID], [VariabilityID], [FiscalMonthID]); +CREATE NONCLUSTERED INDEX [NCNU_GeneralLedgerID] ON [fp].[FactReportGeneralLedger] ([GeneralLedgerID]); +CREATE NONCLUSTERED INDEX [NCNU_DepartmentID] ON [fp].[FactReportGeneralLedger] ([DepartmentID]); +GO +ALTER TABLE [fp].[FactReportGeneralLedger] ADD CONSTRAINT [df_FactReportGeneralLedger_OriginalValue] DEFAULT ((0)) FOR [OriginalValue]; GO +ALTER TABLE [fp].[FactReportGeneralLedger] ADD CONSTRAINT [df_FactReportGeneralLedger_Value] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[FactReportGeneralLedger] ADD CONSTRAINT [df_FactReportGeneralLedger_ManagerValue] DEFAULT ((0)) FOR [ManagerValue]; GO +ALTER TABLE [fp].[FactReportGeneralLedger] ADD CONSTRAINT [df_FactReportGeneralLedger_Rate] DEFAULT ((0)) FOR [Rate]; GO +ALTER TABLE [fp].[FactReportGeneralLedger] ADD CONSTRAINT [df_FactReportGeneralLedger_LockType] DEFAULT ((0)) FOR [LockType]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportGeneralLedgerDataTransfer ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportGeneralLedgerDataTransfer] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [VariabilityID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalYearID] int NULL, + [FiscalMonthID] tinyint NULL, + [OriginalValue] decimal NULL, + [Value] decimal NULL, + [ManagerValue] decimal NULL, + [Rate] decimal NULL, + PRIMARY KEY ([RowID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportGeneralLedgerDataTransferSnapshot ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportGeneralLedgerDataTransferSnapshot] ( + [RowID] int NOT NULL, + [SnapshotID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [VariabilityID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalYearID] int NULL, + [FiscalMonthID] tinyint NULL, + [OriginalValue] decimal NULL, + [Value] decimal NULL, + [ManagerValue] decimal NULL, + [Rate] decimal NULL, + PRIMARY KEY ([RowID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportGeneralLedgerHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportGeneralLedgerHistory] ( + [GeneralLedgerID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [APEModelSectionID] tinyint NOT NULL, + [VariabilityID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalYearID] int NULL, + [FiscalMonthID] tinyint NOT NULL, + [Value] decimal NOT NULL +); + +CREATE CLUSTERED INDEX [IDX_FactReportGeneralLedgerHistory] ON [fp].[FactReportGeneralLedgerHistory] ([BudgetConfigID], [TimeClassID], [FiscalYearID], [UnitTypeID], [GeneralLedgerID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [APEModelSectionID], [VariabilityID], [FiscalMonthID]); +CREATE NONCLUSTERED INDEX [NCNU_DepartmentID] ON [fp].[FactReportGeneralLedgerHistory] ([DepartmentID]); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportGeneralLedgerHistoryDataTransfer ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportGeneralLedgerHistoryDataTransfer] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [VariabilityID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalYearID] int NULL, + [FiscalMonthID] tinyint NOT NULL, + [Value] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportGeneralLedgerHistory_archive ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportGeneralLedgerHistory_archive] ( + [GeneralLedgerID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [APEModelSectionID] tinyint NOT NULL, + [VariabilityID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalYearID] int NULL, + [FiscalMonthID] tinyint NOT NULL, + [Value] decimal NOT NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportGeneralLedgerSnapshot ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportGeneralLedgerSnapshot] ( + [GeneralLedgerID] int NOT NULL, + [SnapshotID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [APEModelSectionID] tinyint NOT NULL, + [VariabilityID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalYearID] int NULL, + [FiscalMonthID] tinyint NULL, + [LockType] tinyint NULL, + [OriginalValue] decimal NULL, + [Value] decimal NULL, + [ManagerValue] decimal NULL, + [Rate] decimal NULL +); +GO +ALTER TABLE [fp].[FactReportGeneralLedgerSnapshot] ADD CONSTRAINT [DF__FactRepor__LockT__566C1E65] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[FactReportGeneralLedgerSnapshot] ADD CONSTRAINT [DF__FactRepor__Origi__5760429E] DEFAULT ((0)) FOR [OriginalValue]; GO +ALTER TABLE [fp].[FactReportGeneralLedgerSnapshot] ADD CONSTRAINT [DF__FactRepor__Value__585466D7] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[FactReportGeneralLedgerSnapshot] ADD CONSTRAINT [DF__FactRepor__Manag__59488B10] DEFAULT ((0)) FOR [ManagerValue]; GO +ALTER TABLE [fp].[FactReportGeneralLedgerSnapshot] ADD CONSTRAINT [DF__FactReport__Rate__5A3CAF49] DEFAULT ((0)) FOR [Rate]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportGeneralLedger_archive ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportGeneralLedger_archive] ( + [GeneralLedgerID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [APEModelSectionID] tinyint NOT NULL, + [VariabilityID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalYearID] int NULL, + [FiscalMonthID] tinyint NULL, + [LockType] tinyint NULL, + [OriginalValue] decimal NULL, + [Value] decimal NULL, + [ManagerValue] decimal NULL, + [Rate] decimal NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportReimbursement ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportReimbursement] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [MSDRGID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [PrimaryCPTID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalYearID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [Value] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE NONCLUSTERED INDEX [NCNU_FactReportReimbursement_RowID] ON [fp].[FactReportReimbursement] ([RowID]); +CREATE NONCLUSTERED INDEX [NCNU_FactReportReimbursement_EntityID] ON [fp].[FactReportReimbursement] ([EntityID], [PayorGroupID], [PatientClassID]); +GO +ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Budge__4E3FEF97] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Entit__4F3413D0] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Entit__50283809] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Patie__511C5C42] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Payor__5210807B] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Payor__5304A4B4] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Servi__53F8C8ED] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Servi__54ECED26] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO +ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__MSDRG__55E1115F] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Medic__56D53598] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Prima__57C959D1] DEFAULT ((0)) FOR [PrimaryCPTID]; GO +ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__UnitT__58BD7E0A] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__TimeC__59B1A243] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Fisca__5AA5C67C] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Fisca__5B99EAB5] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[FactReportReimbursement] ADD CONSTRAINT [DF__FactRepor__Value__5C8E0EEE] DEFAULT ((0)) FOR [Value]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportStaffing ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportStaffing] ( + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NULL, + [PayCodeGroupID] int NOT NULL, + [VariabilityID] int NOT NULL, + [ProductiveClassID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [OriginalValue] decimal NOT NULL, + [Value] decimal NOT NULL, + [ManagerValue] decimal NOT NULL, + [EmployeeID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL +); + +CREATE CLUSTERED INDEX [IDX_FactReportStaffing] ON [fp].[FactReportStaffing] ([BudgetConfigID], [UnitTypeID], [TimeClassID], [FiscalYearID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID], [ProductiveClassID], [FiscalMonthID], [EmployeeID]); +CREATE NONCLUSTERED INDEX [NCNU_DepartmentID] ON [fp].[FactReportStaffing] ([DepartmentID]); +GO +ALTER TABLE [fp].[FactReportStaffing] ADD CONSTRAINT [FK_FacReporttStaffing_Employee] FOREIGN KEY ([EmployeeID]) REFERENCES [fw].[DimEmployee] ([EmployeeID]); GO +ALTER TABLE [fp].[FactReportStaffing] ADD CONSTRAINT [DF__FactRepor__Emplo__0FEA8A07] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[FactReportStaffing] ADD CONSTRAINT [df_FactReportStaffing_OriginalValue] DEFAULT ((0)) FOR [OriginalValue]; GO +ALTER TABLE [fp].[FactReportStaffing] ADD CONSTRAINT [df_FactReportStaffing_Value] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[FactReportStaffing] ADD CONSTRAINT [df_FactReportStaffing_ManagerValue] DEFAULT ((0)) FOR [ManagerValue]; GO +ALTER TABLE [fp].[FactReportStaffing] ADD CONSTRAINT [DF__FactRepor__Provi__577E75B7] DEFAULT ('0') FOR [ProviderID]; GO +ALTER TABLE [fp].[FactReportStaffing] ADD CONSTRAINT [DF__FactRepor__Provi__587299F0] DEFAULT ('0') FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[FactReportStaffing] ADD CONSTRAINT [DF__FactRepor__Provi__5966BE29] DEFAULT ('0') FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[FactReportStaffing] ADD CONSTRAINT [DF__FactRepor__Provi__5A5AE262] DEFAULT ('0') FOR [ProviderSpecialtyID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportStaffingHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportStaffingHistory] ( + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NULL, + [PayCodeGroupID] int NOT NULL, + [ProductiveClassID] int NOT NULL, + [VariabilityID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalYearID] int NULL, + [FiscalMonthID] tinyint NULL, + [Value] decimal NOT NULL, + [EmployeeID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL +); + +CREATE CLUSTERED INDEX [IDX_FactReportStaffingHistory] ON [fp].[FactReportStaffingHistory] ([BudgetConfigID], [UnitTypeID], [TimeClassID], [FiscalYearID], [EntityGroupConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [FiscalMonthID], [EmployeeID]); +CREATE NONCLUSTERED INDEX [NCNU_DepartmentID] ON [fp].[FactReportStaffingHistory] ([DepartmentID]); +GO +ALTER TABLE [fp].[FactReportStaffingHistory] ADD CONSTRAINT [FK_FacReporttStaffingHistory_Employee] FOREIGN KEY ([EmployeeID]) REFERENCES [fw].[DimEmployee] ([EmployeeID]); GO +ALTER TABLE [fp].[FactReportStaffingHistory] ADD CONSTRAINT [DF__FactRepor__Emplo__11D2D279] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[FactReportStaffingHistory] ADD CONSTRAINT [DF__FactRepor__Provi__5F1F977F] DEFAULT ('0') FOR [ProviderID]; GO +ALTER TABLE [fp].[FactReportStaffingHistory] ADD CONSTRAINT [DF__FactRepor__Provi__6013BBB8] DEFAULT ('0') FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[FactReportStaffingHistory] ADD CONSTRAINT [DF__FactRepor__Provi__6107DFF1] DEFAULT ('0') FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[FactReportStaffingHistory] ADD CONSTRAINT [DF__FactRepor__Provi__61FC042A] DEFAULT ('0') FOR [ProviderSpecialtyID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportStaffingHistory_archive ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportStaffingHistory_archive] ( + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NULL, + [PayCodeGroupID] int NOT NULL, + [ProductiveClassID] int NOT NULL, + [VariabilityID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalYearID] int NULL, + [FiscalMonthID] tinyint NULL, + [Value] decimal NOT NULL, + [EmployeeID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL +); + +CREATE CLUSTERED INDEX [IDX_FactReportStaffingHistory_archive] ON [fp].[FactReportStaffingHistory_archive] ([BudgetConfigID], [UnitTypeID], [TimeClassID], [FiscalYearID], [EntityGroupConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [FiscalMonthID], [EmployeeID]); +GO +ALTER TABLE [fp].[FactReportStaffingHistory_archive] ADD CONSTRAINT [DF__FactRepor__Emplo__1741930C] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[FactReportStaffingHistory_archive] ADD CONSTRAINT [DF__FactRepor__Provi__62F02863] DEFAULT ('0') FOR [ProviderID]; GO +ALTER TABLE [fp].[FactReportStaffingHistory_archive] ADD CONSTRAINT [DF__FactRepor__Provi__63E44C9C] DEFAULT ('0') FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[FactReportStaffingHistory_archive] ADD CONSTRAINT [DF__FactRepor__Provi__64D870D5] DEFAULT ('0') FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[FactReportStaffingHistory_archive] ADD CONSTRAINT [DF__FactRepor__Provi__65CC950E] DEFAULT ('0') FOR [ProviderSpecialtyID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportStaffing_archive ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportStaffing_archive] ( + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NULL, + [PayCodeGroupID] int NOT NULL, + [VariabilityID] int NOT NULL, + [ProductiveClassID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [OriginalValue] decimal NOT NULL, + [Value] decimal NOT NULL, + [ManagerValue] decimal NOT NULL, + [EmployeeID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL +); +GO +ALTER TABLE [fp].[FactReportStaffing_archive] ADD CONSTRAINT [DF__FactRepor__Emplo__164D6ED3] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[FactReportStaffing_archive] ADD CONSTRAINT [DF__FactRepor__Provi__5B4F069B] DEFAULT ('0') FOR [ProviderID]; GO +ALTER TABLE [fp].[FactReportStaffing_archive] ADD CONSTRAINT [DF__FactRepor__Provi__5C432AD4] DEFAULT ('0') FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[FactReportStaffing_archive] ADD CONSTRAINT [DF__FactRepor__Provi__5D374F0D] DEFAULT ('0') FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[FactReportStaffing_archive] ADD CONSTRAINT [DF__FactRepor__Provi__5E2B7346] DEFAULT ('0') FOR [ProviderSpecialtyID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportStatistics ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportStatistics] ( + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [PatientClassID] int NOT NULL, + [PayorID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalMonthID] tinyint NULL, + [FiscalYearID] smallint NOT NULL, + [OriginalValue] decimal NOT NULL, + [Value] decimal NOT NULL, + [ManagerValue] decimal NOT NULL, + [ProviderID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL, + [ProviderTypeID] int NOT NULL +); + +CREATE CLUSTERED INDEX [IDX_FactReportStatistics] ON [fp].[FactReportStatistics] ([BudgetConfigID], [TimeClassID], [FiscalYearID], [EntityID], [DepartmentID], [AccountID], [PatientClassID], [PayorID], [FinancialReportingID], [UnitTypeID], [FiscalMonthID]); +CREATE NONCLUSTERED INDEX [NCNU_DepartmentID] ON [fp].[FactReportStatistics] ([DepartmentID]); +GO +ALTER TABLE [fp].[FactReportStatistics] ADD CONSTRAINT [DF__FactRepor__Provi__1C9C105D] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[FactReportStatistics] ADD CONSTRAINT [DF__FactRepor__Provi__1D903496] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[FactReportStatistics] ADD CONSTRAINT [DF__FactRepor__Provi__1E8458CF] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO +ALTER TABLE [fp].[FactReportStatistics] ADD CONSTRAINT [DF__FactRepor__Provi__1F787D08] DEFAULT ((0)) FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[FactReportStatistics] ADD CONSTRAINT [df_FactReportStatistics_OriginalValue] DEFAULT ((0)) FOR [OriginalValue]; GO +ALTER TABLE [fp].[FactReportStatistics] ADD CONSTRAINT [df_FactReportStatistics_Value] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[FactReportStatistics] ADD CONSTRAINT [df_FactReportStatistics_ManagerValue] DEFAULT ((0)) FOR [ManagerValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportStatisticsDataTransfer ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportStatisticsDataTransfer] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [PatientClassID] int NOT NULL, + [PayorID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalMonthID] tinyint NULL, + [FiscalYearID] smallint NOT NULL, + [OriginalValue] decimal NOT NULL, + [Value] decimal NOT NULL, + [ManagerValue] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportStatisticsHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportStatisticsHistory] ( + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [PayorID] int NOT NULL, + [PatientClassID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalYearID] int NULL, + [FiscalMonthID] tinyint NULL, + [Value] decimal NOT NULL, + [ProviderID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL, + [ProviderTypeID] int NOT NULL +); + +CREATE CLUSTERED INDEX [IDX_FactReportStatisticsHistory] ON [fp].[FactReportStatisticsHistory] ([BudgetConfigID], [TimeClassID], [FiscalYearID], [UnitTypeID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID], [FiscalMonthID]); +CREATE NONCLUSTERED INDEX [NCNU_DepartmentID] ON [fp].[FactReportStatisticsHistory] ([DepartmentID]); +GO +ALTER TABLE [fp].[FactReportStatisticsHistory] ADD CONSTRAINT [DF__FactRepor__Provi__243D3225] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[FactReportStatisticsHistory] ADD CONSTRAINT [DF__FactRepor__Provi__2531565E] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[FactReportStatisticsHistory] ADD CONSTRAINT [DF__FactRepor__Provi__26257A97] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO +ALTER TABLE [fp].[FactReportStatisticsHistory] ADD CONSTRAINT [DF__FactRepor__Provi__27199ED0] DEFAULT ((0)) FOR [ProviderTypeID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportStatisticsHistoryDataTransfer ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportStatisticsHistoryDataTransfer] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [PayorID] int NOT NULL, + [PatientClassID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalYearID] int NULL, + [FiscalMonthID] tinyint NULL, + [Value] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportStatisticsHistory_archive ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportStatisticsHistory_archive] ( + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [PayorID] int NOT NULL, + [PatientClassID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalYearID] int NULL, + [FiscalMonthID] tinyint NULL, + [Value] decimal NOT NULL, + [ProviderID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL, + [ProviderTypeID] int NOT NULL +); + +CREATE CLUSTERED INDEX [IDX_FactReportStatisticsHistory_archive] ON [fp].[FactReportStatisticsHistory_archive] ([BudgetConfigID], [TimeClassID], [FiscalYearID], [UnitTypeID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID], [FiscalMonthID]); +GO +ALTER TABLE [fp].[FactReportStatisticsHistory_archive] ADD CONSTRAINT [DF__FactRepor__Provi__280DC309] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[FactReportStatisticsHistory_archive] ADD CONSTRAINT [DF__FactRepor__Provi__2901E742] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[FactReportStatisticsHistory_archive] ADD CONSTRAINT [DF__FactRepor__Provi__29F60B7B] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO +ALTER TABLE [fp].[FactReportStatisticsHistory_archive] ADD CONSTRAINT [DF__FactRepor__Provi__2AEA2FB4] DEFAULT ((0)) FOR [ProviderTypeID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportStatistics_archive ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportStatistics_archive] ( + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [PatientClassID] int NOT NULL, + [PayorID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] int NOT NULL, + [FiscalMonthID] tinyint NULL, + [FiscalYearID] smallint NOT NULL, + [OriginalValue] decimal NOT NULL, + [Value] decimal NOT NULL, + [ManagerValue] decimal NOT NULL, + [ProviderID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL, + [ProviderTypeID] int NOT NULL +); +GO +ALTER TABLE [fp].[FactReportStatistics_archive] ADD CONSTRAINT [DF__FactRepor__Provi__206CA141] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[FactReportStatistics_archive] ADD CONSTRAINT [DF__FactRepor__Provi__2160C57A] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[FactReportStatistics_archive] ADD CONSTRAINT [DF__FactRepor__Provi__2254E9B3] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO +ALTER TABLE [fp].[FactReportStatistics_archive] ADD CONSTRAINT [DF__FactRepor__Provi__23490DEC] DEFAULT ((0)) FOR [ProviderTypeID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportingAP ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportingAP] ( + [RowID] bigint NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [EntityID] int NOT NULL, + [VariabilityID] int NOT NULL, + [FiscalYearID] int NOT NULL, + [FiscalMonthID] int NOT NULL, + [PatientClassID] int NOT NULL, + [PayorID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeGroupID] int NOT NULL, + [ProductiveClassID] int NOT NULL, + [EmployeeID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [CostComponentID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [ActualDollars] decimal NOT NULL, + [BudgetDollars] decimal NOT NULL, + [ProjectedDollars] decimal NOT NULL, + [TargetDollars] decimal NOT NULL, + [FlexDollars] decimal NOT NULL, + [ActualUnits] decimal NOT NULL, + [BudgetUnits] decimal NOT NULL, + [ProjectedUnits] decimal NOT NULL, + [TargetUnits] decimal NOT NULL, + [FlexUnits] decimal NOT NULL, + [ActualHours] decimal NOT NULL, + [BudgetHours] decimal NOT NULL, + [ProjectedHours] decimal NOT NULL, + [TargetHours] decimal NOT NULL, + [FlexHours] decimal NOT NULL, + [ActualFTEs] decimal NOT NULL, + [BudgetFTEs] decimal NOT NULL, + [ProjectedFTEs] decimal NOT NULL, + [TargetFTEs] decimal NOT NULL, + [FlexFTEs] decimal NOT NULL, + [ActualDollarsYTD] decimal NOT NULL, + [BudgetDollarsYTD] decimal NOT NULL, + [ProjectedDollarsYTD] decimal NOT NULL, + [TargetDollarsYTD] decimal NOT NULL, + [FlexDollarsYTD] decimal NOT NULL, + [ActualUnitsYTD] decimal NOT NULL, + [BudgetUnitsYTD] decimal NOT NULL, + [ProjectedUnitsYTD] decimal NOT NULL, + [TargetUnitsYTD] decimal NOT NULL, + [FlexUnitsYTD] decimal NOT NULL, + [ActualHoursYTD] decimal NOT NULL, + [BudgetHoursYTD] decimal NOT NULL, + [ProjectedHoursYTD] decimal NOT NULL, + [TargetHoursYTD] decimal NOT NULL, + [FlexHoursYTD] decimal NOT NULL, + [ActualFTEsYTD] decimal NOT NULL, + [BudgetFTEsYTD] decimal NOT NULL, + [ProjectedFTEsYTD] decimal NOT NULL, + [TargetFTEsYTD] decimal NOT NULL, + [FlexFTEsYTD] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] bit NOT NULL, + [IsPrimaryNonStaffingStatistic] bit NOT NULL, + [IsPrimaryRevenueStatistic] bit NOT NULL, + [IsPrimaryStaffingStatistic] bit NOT NULL, + [InitialUnits] decimal NOT NULL, + [InitialDollars] decimal NOT NULL, + [InitialHours] decimal NOT NULL, + [InitialFTEs] decimal NOT NULL, + [FiscalTimeID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE NONCLUSTERED INDEX [NCNU_FactReportingAP_FiscalYearFiscalMonth] ON [fp].[FactReportingAP] ([FiscalYearID], [FiscalMonthID]); +GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Budge__79DC18AE] DEFAULT ((0)) FOR [BudgetHoursYTD]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__IsPri__7A92A7CA] DEFAULT ((0)) FOR [IsPrimaryRevenueStatistic]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Proje__7AD03CE7] DEFAULT ((0)) FOR [ProjectedHoursYTD]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__IsPri__7B86CC03] DEFAULT ((0)) FOR [IsPrimaryStaffingStatistic]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Targe__7BC46120] DEFAULT ((0)) FOR [TargetHoursYTD]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__FlexH__7CB88559] DEFAULT ((0)) FOR [FlexHoursYTD]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Actua__7DACA992] DEFAULT ((0)) FOR [ActualFTEsYTD]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Budge__7EA0CDCB] DEFAULT ((0)) FOR [BudgetFTEsYTD]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Proje__7F94F204] DEFAULT ((0)) FOR [ProjectedFTEsYTD]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Fisca__37E69A24] DEFAULT ((0)) FOR [FiscalTimeID]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Targe__0089163D] DEFAULT ((0)) FOR [TargetFTEsYTD]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__FlexF__017D3A76] DEFAULT ((0)) FOR [FlexFTEsYTD]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Depar__4D097237] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Accou__4DFD9670] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Entit__4EF1BAA9] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Varia__4FE5DEE2] DEFAULT ((0)) FOR [VariabilityID]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Fisca__50DA031B] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Fisca__51CE2754] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Patie__52C24B8D] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Payor__53B66FC6] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__JobCo__54AA93FF] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__PayCo__559EB838] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Produ__5692DC71] DEFAULT ((0)) FOR [ProductiveClassID]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Emplo__578700AA] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Initi__5A85CAEB] DEFAULT ((0)) FOR [InitialUnits]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Charg__587B24E3] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Initi__5B79EF24] DEFAULT ((0)) FOR [InitialDollars]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Servi__596F491C] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Initi__5C6E135D] DEFAULT ((0)) FOR [InitialHours]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__CostC__5A636D55] DEFAULT ((0)) FOR [CostComponentID]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Initi__5D623796] DEFAULT ((0)) FOR [InitialFTEs]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Finan__5B57918E] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Actua__5C4BB5C7] DEFAULT ((0)) FOR [ActualDollars]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Budge__5D3FDA00] DEFAULT ((0)) FOR [BudgetDollars]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Proje__5E33FE39] DEFAULT ((0)) FOR [ProjectedDollars]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Targe__5F282272] DEFAULT ((0)) FOR [TargetDollars]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__FlexD__601C46AB] DEFAULT ((0)) FOR [FlexDollars]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Actua__61106AE4] DEFAULT ((0)) FOR [ActualUnits]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Budge__62048F1D] DEFAULT ((0)) FOR [BudgetUnits]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__IsDel__628E9F02] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Proje__62F8B356] DEFAULT ((0)) FOR [ProjectedUnits]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Histo__6382C33B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Targe__63ECD78F] DEFAULT ((0)) FOR [TargetUnits]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Trans__6476E774] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__FlexU__64E0FBC8] DEFAULT ((0)) FOR [FlexUnits]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Actua__65D52001] DEFAULT ((0)) FOR [ActualHours]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Budge__66C9443A] DEFAULT ((0)) FOR [BudgetHours]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Proje__67BD6873] DEFAULT ((0)) FOR [ProjectedHours]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Targe__68B18CAC] DEFAULT ((0)) FOR [TargetHours]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__FlexH__69A5B0E5] DEFAULT ((0)) FOR [FlexHours]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Actua__6A99D51E] DEFAULT ((0)) FOR [ActualFTEs]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Budge__6B8DF957] DEFAULT ((0)) FOR [BudgetFTEs]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Proje__6C821D90] DEFAULT ((0)) FOR [ProjectedFTEs]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Targe__6D7641C9] DEFAULT ((0)) FOR [TargetFTEs]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__FlexF__6E6A6602] DEFAULT ((0)) FOR [FlexFTEs]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Actua__6F5E8A3B] DEFAULT ((0)) FOR [ActualDollarsYTD]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Budge__7052AE74] DEFAULT ((0)) FOR [BudgetDollarsYTD]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Proje__7146D2AD] DEFAULT ((0)) FOR [ProjectedDollarsYTD]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Targe__723AF6E6] DEFAULT ((0)) FOR [TargetDollarsYTD]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__FlexD__732F1B1F] DEFAULT ((0)) FOR [FlexDollarsYTD]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Actua__74233F58] DEFAULT ((0)) FOR [ActualUnitsYTD]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Budge__75176391] DEFAULT ((0)) FOR [BudgetUnitsYTD]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Proje__760B87CA] DEFAULT ((0)) FOR [ProjectedUnitsYTD]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Targe__76FFAC03] DEFAULT ((0)) FOR [TargetUnitsYTD]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__FlexU__77F3D03C] DEFAULT ((0)) FOR [FlexUnitsYTD]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__Actua__78E7F475] DEFAULT ((0)) FOR [ActualHoursYTD]; GO +ALTER TABLE [fp].[FactReportingAP] ADD CONSTRAINT [DF__FactRepor__IsPri__799E8391] DEFAULT ((0)) FOR [IsPrimaryNonStaffingStatistic]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportingAPCharges ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportingAPCharges] ( + [RowID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [PatientClassID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [ServiceEntityID] int NOT NULL, + [UBRevenueCodeID] int NOT NULL, + [PrimaryCPTID] int NOT NULL, + [PhysicianID] int NOT NULL, + [PhysicianSpecialtyID] int NOT NULL, + [PerformingProviderID] int NOT NULL, + [PerformingPhysicianSpecialtyID] int NOT NULL, + [BilledCPTID] int NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [ActualUnits01] decimal NOT NULL, + [ActualUnits02] decimal NOT NULL, + [ActualUnits03] decimal NOT NULL, + [ActualUnits04] decimal NOT NULL, + [ActualUnits05] decimal NOT NULL, + [ActualUnits06] decimal NOT NULL, + [ActualUnits07] decimal NOT NULL, + [ActualUnits08] decimal NOT NULL, + [ActualUnits09] decimal NOT NULL, + [ActualUnits10] decimal NOT NULL, + [ActualUnits11] decimal NOT NULL, + [ActualUnits12] decimal NOT NULL, + [BudgetUnits01] decimal NOT NULL, + [BudgetUnits02] decimal NOT NULL, + [BudgetUnits03] decimal NOT NULL, + [BudgetUnits04] decimal NOT NULL, + [BudgetUnits05] decimal NOT NULL, + [BudgetUnits06] decimal NOT NULL, + [BudgetUnits07] decimal NOT NULL, + [BudgetUnits08] decimal NOT NULL, + [BudgetUnits09] decimal NOT NULL, + [BudgetUnits10] decimal NOT NULL, + [BudgetUnits11] decimal NOT NULL, + [BudgetUnits12] decimal NOT NULL, + [ProjectedUnits01] decimal NOT NULL, + [ProjectedUnits02] decimal NOT NULL, + [ProjectedUnits03] decimal NOT NULL, + [ProjectedUnits04] decimal NOT NULL, + [ProjectedUnits05] decimal NOT NULL, + [ProjectedUnits06] decimal NOT NULL, + [ProjectedUnits07] decimal NOT NULL, + [ProjectedUnits08] decimal NOT NULL, + [ProjectedUnits09] decimal NOT NULL, + [ProjectedUnits10] decimal NOT NULL, + [ProjectedUnits11] decimal NOT NULL, + [ProjectedUnits12] decimal NOT NULL, + [TargetUnits01] decimal NOT NULL, + [TargetUnits02] decimal NOT NULL, + [TargetUnits03] decimal NOT NULL, + [TargetUnits04] decimal NOT NULL, + [TargetUnits05] decimal NOT NULL, + [TargetUnits06] decimal NOT NULL, + [TargetUnits07] decimal NOT NULL, + [TargetUnits08] decimal NOT NULL, + [TargetUnits09] decimal NOT NULL, + [TargetUnits10] decimal NOT NULL, + [TargetUnits11] decimal NOT NULL, + [TargetUnits12] decimal NOT NULL, + [ActualDollars01] decimal NOT NULL, + [ActualDollars02] decimal NOT NULL, + [ActualDollars03] decimal NOT NULL, + [ActualDollars04] decimal NOT NULL, + [ActualDollars05] decimal NOT NULL, + [ActualDollars06] decimal NOT NULL, + [ActualDollars07] decimal NOT NULL, + [ActualDollars08] decimal NOT NULL, + [ActualDollars09] decimal NOT NULL, + [ActualDollars10] decimal NOT NULL, + [ActualDollars11] decimal NOT NULL, + [ActualDollars12] decimal NOT NULL, + [BudgetDollars01] decimal NOT NULL, + [BudgetDollars02] decimal NOT NULL, + [BudgetDollars03] decimal NOT NULL, + [BudgetDollars04] decimal NOT NULL, + [BudgetDollars05] decimal NOT NULL, + [BudgetDollars06] decimal NOT NULL, + [BudgetDollars07] decimal NOT NULL, + [BudgetDollars08] decimal NOT NULL, + [BudgetDollars09] decimal NOT NULL, + [BudgetDollars10] decimal NOT NULL, + [BudgetDollars11] decimal NOT NULL, + [BudgetDollars12] decimal NOT NULL, + [ProjectedDollars01] decimal NOT NULL, + [ProjectedDollars02] decimal NOT NULL, + [ProjectedDollars03] decimal NOT NULL, + [ProjectedDollars04] decimal NOT NULL, + [ProjectedDollars05] decimal NOT NULL, + [ProjectedDollars06] decimal NOT NULL, + [ProjectedDollars07] decimal NOT NULL, + [ProjectedDollars08] decimal NOT NULL, + [ProjectedDollars09] decimal NOT NULL, + [ProjectedDollars10] decimal NOT NULL, + [ProjectedDollars11] decimal NOT NULL, + [ProjectedDollars12] decimal NOT NULL, + [TargetDollars01] decimal NOT NULL, + [TargetDollars02] decimal NOT NULL, + [TargetDollars03] decimal NOT NULL, + [TargetDollars04] decimal NOT NULL, + [TargetDollars05] decimal NOT NULL, + [TargetDollars06] decimal NOT NULL, + [TargetDollars07] decimal NOT NULL, + [TargetDollars08] decimal NOT NULL, + [TargetDollars09] decimal NOT NULL, + [TargetDollars10] decimal NOT NULL, + [TargetDollars11] decimal NOT NULL, + [TargetDollars12] decimal NOT NULL, + [ActualUnitsTotal] decimal NOT NULL, + [BudgetUnitsTotal] decimal NOT NULL, + [ProjectedUnitsTotal] decimal NOT NULL, + [TargetUnitsTotal] decimal NOT NULL, + [ActualDollarsTotal] decimal NOT NULL, + [BudgetDollarsTotal] decimal NOT NULL, + [ProjectedDollarsTotal] decimal NOT NULL, + [TargetDollarsTotal] decimal NOT NULL, + [MSDRGRollupID] int NOT NULL, + [InitialUnits01] decimal NOT NULL, + [InitialUnits02] decimal NOT NULL, + [InitialUnits03] decimal NOT NULL, + [InitialUnits04] decimal NOT NULL, + [InitialUnits05] decimal NOT NULL, + [InitialUnits06] decimal NOT NULL, + [InitialUnits07] decimal NOT NULL, + [InitialUnits08] decimal NOT NULL, + [InitialUnits09] decimal NOT NULL, + [InitialUnits10] decimal NOT NULL, + [InitialUnits11] decimal NOT NULL, + [InitialUnits12] decimal NOT NULL, + [InitialDollars01] decimal NOT NULL, + [InitialDollars02] decimal NOT NULL, + [InitialDollars03] decimal NOT NULL, + [InitialDollars04] decimal NOT NULL, + [InitialDollars05] decimal NOT NULL, + [InitialDollars06] decimal NOT NULL, + [InitialDollars07] decimal NOT NULL, + [InitialDollars08] decimal NOT NULL, + [InitialDollars09] decimal NOT NULL, + [InitialDollars10] decimal NOT NULL, + [InitialDollars11] decimal NOT NULL, + [InitialDollars12] decimal NOT NULL, + [InitialUnitsTotal] decimal NOT NULL, + [InitialDollarsTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__AgeCo__257D05CF] FOREIGN KEY ([AgeCohortID]) REFERENCES [fw].[DimAgeCohort] ([AgeCohortID]); GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__Charg__294D96B3] FOREIGN KEY ([ChargeCodeID]) REFERENCES [fw].[DimChargeCode] ([ChargeCodeID]); GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__Depar__1FC42C79] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__Entit__1DDBE407] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__Fisca__2B35DF25] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__Medic__27654E41] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__MSDRG__57DE686A] FOREIGN KEY ([MSDRGRollupID]) REFERENCES [dss].[DimMSDRGRollup] ([MSDRGRollupID]); GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__Patie__2394BD5D] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__Physi__34BF495F] FOREIGN KEY ([PhysicianID]) REFERENCES [dss].[DimPhysician] ([PhysicianID]); GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__Physi__36A791D1] FOREIGN KEY ([PhysicianSpecialtyID]) REFERENCES [dss].[DimPhysicianSpecialty] ([PhysicianSpecialtyID]); GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__Servi__21AC74EB] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [FK__FactRepor__UBRev__31E2DCB4] FOREIGN KEY ([UBRevenueCodeID]) REFERENCES [dss].[DimUBRevenueCode] ([UBRevenueCodeID]); GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__002163EE] DEFAULT ((0)) FOR [BudgetUnits11]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__01158827] DEFAULT ((0)) FOR [BudgetUnits12]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__0209AC60] DEFAULT ((0)) FOR [ProjectedUnits01]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__02FDD099] DEFAULT ((0)) FOR [ProjectedUnits02]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__03F1F4D2] DEFAULT ((0)) FOR [ProjectedUnits03]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__04E6190B] DEFAULT ((0)) FOR [ProjectedUnits04]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__05DA3D44] DEFAULT ((0)) FOR [ProjectedUnits05]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__06CE617D] DEFAULT ((0)) FOR [ProjectedUnits06]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__07C285B6] DEFAULT ((0)) FOR [ProjectedUnits07]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__08B6A9EF] DEFAULT ((0)) FOR [ProjectedUnits08]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__09AACE28] DEFAULT ((0)) FOR [ProjectedUnits09]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__0A9EF261] DEFAULT ((0)) FOR [ProjectedUnits10]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__0B93169A] DEFAULT ((0)) FOR [ProjectedUnits11]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__0C873AD3] DEFAULT ((0)) FOR [ProjectedUnits12]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__0D7B5F0C] DEFAULT ((0)) FOR [TargetUnits01]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__0E6F8345] DEFAULT ((0)) FOR [TargetUnits02]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__0F63A77E] DEFAULT ((0)) FOR [TargetUnits03]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__1057CBB7] DEFAULT ((0)) FOR [TargetUnits04]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__114BEFF0] DEFAULT ((0)) FOR [TargetUnits05]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__12401429] DEFAULT ((0)) FOR [TargetUnits06]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__13343862] DEFAULT ((0)) FOR [TargetUnits07]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__14285C9B] DEFAULT ((0)) FOR [TargetUnits08]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__151C80D4] DEFAULT ((0)) FOR [TargetUnits09]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__1610A50D] DEFAULT ((0)) FOR [TargetUnits10]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__1704C946] DEFAULT ((0)) FOR [TargetUnits11]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__17F8ED7F] DEFAULT ((0)) FOR [TargetUnits12]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__18ED11B8] DEFAULT ((0)) FOR [ActualDollars01]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__19E135F1] DEFAULT ((0)) FOR [ActualDollars02]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__1AD55A2A] DEFAULT ((0)) FOR [ActualDollars03]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__1BC97E63] DEFAULT ((0)) FOR [ActualDollars04]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__1CBDA29C] DEFAULT ((0)) FOR [ActualDollars05]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Entit__1CE7BFCE] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__1DB1C6D5] DEFAULT ((0)) FOR [ActualDollars06]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__1EA5EB0E] DEFAULT ((0)) FOR [ActualDollars07]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Depar__1ED00840] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__1F9A0F47] DEFAULT ((0)) FOR [ActualDollars08]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__208E3380] DEFAULT ((0)) FOR [ActualDollars09]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Servi__20B850B2] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__218257B9] DEFAULT ((0)) FOR [ActualDollars10]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__22767BF2] DEFAULT ((0)) FOR [ActualDollars11]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Patie__22A09924] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__236AA02B] DEFAULT ((0)) FOR [ActualDollars12]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__245EC464] DEFAULT ((0)) FOR [BudgetDollars01]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__AgeCo__2488E196] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__2552E89D] DEFAULT ((0)) FOR [BudgetDollars02]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__26470CD6] DEFAULT ((0)) FOR [BudgetDollars03]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Medic__26712A08] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__273B310F] DEFAULT ((0)) FOR [BudgetDollars04]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__282F5548] DEFAULT ((0)) FOR [BudgetDollars05]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Charg__2859727A] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__29237981] DEFAULT ((0)) FOR [BudgetDollars06]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__2A179DBA] DEFAULT ((0)) FOR [BudgetDollars07]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Fisca__2A41BAEC] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__2B0BC1F3] DEFAULT ((0)) FOR [BudgetDollars08]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__2BFFE62C] DEFAULT ((0)) FOR [BudgetDollars09]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__2CF40A65] DEFAULT ((0)) FOR [BudgetDollars10]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__2DE82E9E] DEFAULT ((0)) FOR [BudgetDollars11]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Servi__2E124BD0] DEFAULT ((0)) FOR [ServiceEntityID]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__2EDC52D7] DEFAULT ((0)) FOR [BudgetDollars12]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__2FD07710] DEFAULT ((0)) FOR [ProjectedDollars01]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__30C49B49] DEFAULT ((0)) FOR [ProjectedDollars02]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__UBRev__30EEB87B] DEFAULT ((0)) FOR [UBRevenueCodeID]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__31B8BF82] DEFAULT ((0)) FOR [ProjectedDollars03]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__32ACE3BB] DEFAULT ((0)) FOR [ProjectedDollars04]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Prima__32D700ED] DEFAULT ((0)) FOR [PrimaryCPTID]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__33A107F4] DEFAULT ((0)) FOR [ProjectedDollars05]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Physi__33CB2526] DEFAULT ((0)) FOR [PhysicianID]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__34952C2D] DEFAULT ((0)) FOR [ProjectedDollars06]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__35895066] DEFAULT ((0)) FOR [ProjectedDollars07]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Physi__35B36D98] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__367D749F] DEFAULT ((0)) FOR [ProjectedDollars08]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__377198D8] DEFAULT ((0)) FOR [ProjectedDollars09]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Perfo__379BB60A] DEFAULT ((0)) FOR [PerformingProviderID]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__3865BD11] DEFAULT ((0)) FOR [ProjectedDollars10]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Perfo__388FDA43] DEFAULT ((0)) FOR [PerformingPhysicianSpecialtyID]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__3959E14A] DEFAULT ((0)) FOR [ProjectedDollars11]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Bille__3983FE7C] DEFAULT ((0)) FOR [BilledCPTID]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Proje__3A4E0583] DEFAULT ((0)) FOR [ProjectedDollars12]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__3B4229BC] DEFAULT ((0)) FOR [TargetDollars01]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__3C364DF5] DEFAULT ((0)) FOR [TargetDollars02]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__3D2A722E] DEFAULT ((0)) FOR [TargetDollars03]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__3E1E9667] DEFAULT ((0)) FOR [TargetDollars04]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__3F12BAA0] DEFAULT ((0)) FOR [TargetDollars05]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__4006DED9] DEFAULT ((0)) FOR [TargetDollars06]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__40FB0312] DEFAULT ((0)) FOR [TargetDollars07]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__41EF274B] DEFAULT ((0)) FOR [TargetDollars08]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__IsDel__4219447D] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__42E34B84] DEFAULT ((0)) FOR [TargetDollars09]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Histo__430D68B6] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__43D76FBD] DEFAULT ((0)) FOR [TargetDollars10]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Trans__44018CEF] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__44CB93F6] DEFAULT ((0)) FOR [TargetDollars11]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Targe__45BFB82F] DEFAULT ((0)) FOR [TargetDollars12]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__MSDRG__56EA4431] DEFAULT ((0)) FOR [MSDRGRollupID]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__5E565BCF] DEFAULT ((0)) FOR [InitialUnits01]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__5F4A8008] DEFAULT ((0)) FOR [InitialUnits02]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__603EA441] DEFAULT ((0)) FOR [InitialUnits03]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__6132C87A] DEFAULT ((0)) FOR [InitialUnits04]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__6226ECB3] DEFAULT ((0)) FOR [InitialUnits05]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__631B10EC] DEFAULT ((0)) FOR [InitialUnits06]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__640F3525] DEFAULT ((0)) FOR [InitialUnits07]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__6503595E] DEFAULT ((0)) FOR [InitialUnits08]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__65F77D97] DEFAULT ((0)) FOR [InitialUnits09]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__66EBA1D0] DEFAULT ((0)) FOR [InitialUnits10]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__67DFC609] DEFAULT ((0)) FOR [InitialUnits11]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__68D3EA42] DEFAULT ((0)) FOR [InitialUnits12]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__69C80E7B] DEFAULT ((0)) FOR [InitialDollars01]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__6ABC32B4] DEFAULT ((0)) FOR [InitialDollars02]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__6B264708] DEFAULT ((0)) FOR [ActualUnits01]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__6BB056ED] DEFAULT ((0)) FOR [InitialDollars03]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__6C1A6B41] DEFAULT ((0)) FOR [ActualUnits02]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__6CA47B26] DEFAULT ((0)) FOR [InitialDollars04]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__6D0E8F7A] DEFAULT ((0)) FOR [ActualUnits03]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__6D989F5F] DEFAULT ((0)) FOR [InitialDollars05]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__6E02B3B3] DEFAULT ((0)) FOR [ActualUnits04]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__6E8CC398] DEFAULT ((0)) FOR [InitialDollars06]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__6EF6D7EC] DEFAULT ((0)) FOR [ActualUnits05]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__6F80E7D1] DEFAULT ((0)) FOR [InitialDollars07]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__6FEAFC25] DEFAULT ((0)) FOR [ActualUnits06]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__70750C0A] DEFAULT ((0)) FOR [InitialDollars08]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__70DF205E] DEFAULT ((0)) FOR [ActualUnits07]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__71693043] DEFAULT ((0)) FOR [InitialDollars09]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__71D34497] DEFAULT ((0)) FOR [ActualUnits08]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__725D547C] DEFAULT ((0)) FOR [InitialDollars10]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__72C768D0] DEFAULT ((0)) FOR [ActualUnits09]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__735178B5] DEFAULT ((0)) FOR [InitialDollars11]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__73BB8D09] DEFAULT ((0)) FOR [ActualUnits10]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Initi__74459CEE] DEFAULT ((0)) FOR [InitialDollars12]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__74AFB142] DEFAULT ((0)) FOR [ActualUnits11]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Actua__75A3D57B] DEFAULT ((0)) FOR [ActualUnits12]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__7697F9B4] DEFAULT ((0)) FOR [BudgetUnits01]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__778C1DED] DEFAULT ((0)) FOR [BudgetUnits02]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__78804226] DEFAULT ((0)) FOR [BudgetUnits03]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__7974665F] DEFAULT ((0)) FOR [BudgetUnits04]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__7A688A98] DEFAULT ((0)) FOR [BudgetUnits05]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__7B5CAED1] DEFAULT ((0)) FOR [BudgetUnits06]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__7C50D30A] DEFAULT ((0)) FOR [BudgetUnits07]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__7D44F743] DEFAULT ((0)) FOR [BudgetUnits08]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__7E391B7C] DEFAULT ((0)) FOR [BudgetUnits09]; GO +ALTER TABLE [fp].[FactReportingAPCharges] ADD CONSTRAINT [DF__FactRepor__Budge__7F2D3FB5] DEFAULT ((0)) FOR [BudgetUnits10]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactReportingAPEncounters ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactReportingAPEncounters] ( + [RowID] int NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [DepartmentID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [CPTID] int NOT NULL, + [ProviderID] int NOT NULL, + [PhysicianSpecialtyID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [ActualEncounters] decimal NOT NULL, + [ActualEncountersYTD] decimal NOT NULL, + [BudgetEncounters] decimal NOT NULL, + [ProjectedEncounters] decimal NOT NULL, + [TargetEncounters] decimal NOT NULL, + [MSDRGRollupID] int NOT NULL, + [InitialEncounters] decimal NOT NULL, + [FiscalTimeID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__IsDel__0AFE19BD] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Histo__0BF23DF6] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Trans__0CE6622F] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Entit__0DDA8668] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Patie__0ECEAAA1] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Servi__0FC2CEDA] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Servi__10B6F313] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__AgeCo__11AB174C] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Medic__129F3B85] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Depar__13935FBE] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Payor__148783F7] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Payor__157BA830] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__CPTID__1763F0A2] DEFAULT ((0)) FOR [CPTID]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Provi__185814DB] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Physi__194C3914] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Fisca__1A405D4D] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Fisca__1B348186] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Actua__1C28A5BF] DEFAULT ((0)) FOR [ActualEncounters]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Actua__1D1CC9F8] DEFAULT ((0)) FOR [ActualEncountersYTD]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Budge__1E10EE31] DEFAULT ((0)) FOR [BudgetEncounters]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Proje__1F05126A] DEFAULT ((0)) FOR [ProjectedEncounters]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Targe__1FF936A3] DEFAULT ((0)) FOR [TargetEncounters]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Fisca__38DABE5D] DEFAULT ((0)) FOR [FiscalTimeID]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__MSDRG__58D28CA3] DEFAULT ((0)) FOR [MSDRGRollupID]; GO +ALTER TABLE [fp].[FactReportingAPEncounters] ADD CONSTRAINT [DF__FactRepor__Initi__7539C127] DEFAULT ((0)) FOR [InitialEncounters]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactStaffingVariabilityDetail ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactStaffingVariabilityDetail] ( + [EntityGroupConfigGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeID] int NOT NULL, + [FixedPercentage] decimal NOT NULL, + [RowID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [EmployeeID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [IX_FactPayrollVariabilityDetail] ON [fp].[FactStaffingVariabilityDetail] ([EntityGroupConfigGUID], [DepartmentID], [JobCodeID], [PayCodeID], [ProviderLineItemID]); +GO +ALTER TABLE [fp].[FactStaffingVariabilityDetail] ADD CONSTRAINT [FK_FactStaffingVariabilityDetail_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[FactStaffingVariabilityDetail] ADD CONSTRAINT [FK_FactStaffingVariabilityDetail_JobCode] FOREIGN KEY ([JobCodeID]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO +ALTER TABLE [fp].[FactStaffingVariabilityDetail] ADD CONSTRAINT [DF_FactPayrollVariabilityDetail_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO +ALTER TABLE [fp].[FactStaffingVariabilityDetail] ADD CONSTRAINT [DF_FactPayrollVariabilityDetail_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactStaffingVariabilityDetail] ADD CONSTRAINT [DF_FactPayrollVariabilityDetail_PayCodeID] DEFAULT ((0)) FOR [PayCodeID]; GO +ALTER TABLE [fp].[FactStaffingVariabilityDetail] ADD CONSTRAINT [DF_FactPayrollVariabilityDetail_FixedPercentage] DEFAULT ((0.0)) FOR [FixedPercentage]; GO +ALTER TABLE [fp].[FactStaffingVariabilityDetail] ADD CONSTRAINT [DF__FactStaff__Emplo__6ADC2E45] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[FactStaffingVariabilityDetail] ADD CONSTRAINT [DF__FactStaff__Provi__72CFF3C3] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[FactStaffingVariabilityDetail] ADD CONSTRAINT [DF_FactStaffingVariabilityDetail_JobCodeID] DEFAULT ((0)) FOR [JobCodeID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactStatistics ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactStatistics] ( + [StatisticsID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [PayorID] int NOT NULL, + [PatientClassID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [AddDate] datetime NOT NULL, + [SampledBudget01] decimal NOT NULL, + [SampledBudget02] decimal NOT NULL, + [SampledBudget03] decimal NOT NULL, + [SampledBudget04] decimal NOT NULL, + [SampledBudget05] decimal NOT NULL, + [SampledBudget06] decimal NOT NULL, + [SampledBudget07] decimal NOT NULL, + [SampledBudget08] decimal NOT NULL, + [SampledBudget09] decimal NOT NULL, + [SampledBudget10] decimal NOT NULL, + [SampledBudget11] decimal NOT NULL, + [SampledBudget12] decimal NOT NULL, + [SampledProjection01] decimal NOT NULL, + [SampledProjection02] decimal NOT NULL, + [SampledProjection03] decimal NOT NULL, + [SampledProjection04] decimal NOT NULL, + [SampledProjection05] decimal NOT NULL, + [SampledProjection06] decimal NOT NULL, + [SampledProjection07] decimal NOT NULL, + [SampledProjection08] decimal NOT NULL, + [SampledProjection09] decimal NOT NULL, + [SampledProjection10] decimal NOT NULL, + [SampledProjection11] decimal NOT NULL, + [SampledProjection12] decimal NOT NULL, + [InitialBudget01] decimal NOT NULL, + [InitialBudget02] decimal NOT NULL, + [InitialBudget03] decimal NOT NULL, + [InitialBudget04] decimal NOT NULL, + [InitialBudget05] decimal NOT NULL, + [InitialBudget06] decimal NOT NULL, + [InitialBudget07] decimal NOT NULL, + [InitialBudget08] decimal NOT NULL, + [InitialBudget09] decimal NOT NULL, + [InitialBudget10] decimal NOT NULL, + [InitialBudget11] decimal NOT NULL, + [InitialBudget12] decimal NOT NULL, + [InitialProjection01] decimal NOT NULL, + [InitialProjection02] decimal NOT NULL, + [InitialProjection03] decimal NOT NULL, + [InitialProjection04] decimal NOT NULL, + [InitialProjection05] decimal NOT NULL, + [InitialProjection06] decimal NOT NULL, + [InitialProjection07] decimal NOT NULL, + [InitialProjection08] decimal NOT NULL, + [InitialProjection09] decimal NOT NULL, + [InitialProjection10] decimal NOT NULL, + [InitialProjection11] decimal NOT NULL, + [InitialProjection12] decimal NOT NULL, + [SampledBudgetTotal] decimal NOT NULL, + [SampledProjectionTotal] decimal NOT NULL, + [InitialBudgetTotal] decimal NOT NULL, + [InitialProjectionTotal] decimal NOT NULL, + [IsNew] bit NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [SubsectionID] int NOT NULL, + [InitialBudgetRate01] decimal NOT NULL, + [InitialBudgetRate02] decimal NOT NULL, + [InitialBudgetRate03] decimal NOT NULL, + [InitialBudgetRate04] decimal NOT NULL, + [InitialBudgetRate05] decimal NOT NULL, + [InitialBudgetRate06] decimal NOT NULL, + [InitialBudgetRate07] decimal NOT NULL, + [InitialBudgetRate08] decimal NOT NULL, + [InitialBudgetRate09] decimal NOT NULL, + [InitialBudgetRate10] decimal NOT NULL, + [InitialBudgetRate11] decimal NOT NULL, + [InitialBudgetRate12] decimal NOT NULL, + [InitialProjectionRate01] decimal NOT NULL, + [InitialProjectionRate02] decimal NOT NULL, + [InitialProjectionRate03] decimal NOT NULL, + [InitialProjectionRate04] decimal NOT NULL, + [InitialProjectionRate05] decimal NOT NULL, + [InitialProjectionRate06] decimal NOT NULL, + [InitialProjectionRate07] decimal NOT NULL, + [InitialProjectionRate08] decimal NOT NULL, + [InitialProjectionRate09] decimal NOT NULL, + [InitialProjectionRate10] decimal NOT NULL, + [InitialProjectionRate11] decimal NOT NULL, + [InitialProjectionRate12] decimal NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([StatisticsID]) +); + +CREATE CLUSTERED INDEX [IX_FactStatistics] ON [fp].[FactStatistics] ([StatisticsID]); +CREATE NONCLUSTERED INDEX [IX_FactStatistics_Account] ON [fp].[FactStatistics] ([AccountID]) INCLUDE ([StatisticsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [FinancialReportingID], [PayorID], [PatientClassID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_FactStatistics_BudgetConfig] ON [fp].[FactStatistics] ([BudgetConfigID]) INCLUDE ([StatisticsID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_FactStatistics_Department] ON [fp].[FactStatistics] ([DepartmentID]) INCLUDE ([StatisticsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_FactStatistics_Entity] ON [fp].[FactStatistics] ([EntityID]) INCLUDE ([StatisticsID], [BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_FactStatistics_FinancialReporting] ON [fp].[FactStatistics] ([FinancialReportingID]) INCLUDE ([StatisticsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [PayorID], [PatientClassID], [UnitTypeID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[FactStatistics] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [PatientClassID], [PayorID], [UnitTypeID], [ProviderLineItemID], [ProviderID], [ProviderSpecialtyID], [ProviderTypeID]); +GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [FK_FactStatistics_Account] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [FK_FactStatistics_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [FK_FactStatistics_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [FK_FactStatistics_FinancialReporting] FOREIGN KEY ([FinancialReportingID]) REFERENCES [ob].[DimFinancialReporting] ([FinancialReportingID]); GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [FK_FactStatistics_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [FK_FactStatistics_Payor] FOREIGN KEY ([PayorID]) REFERENCES [fw].[DimPayor] ([PayorID]); GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [FK_FactStatistics_UnitType] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Provi__0009F350] DEFAULT ((0)) FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [df_Stat_SubsectionID] DEFAULT ('1') FOR [SubsectionID]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Budge__27D0C779] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Entit__28C4EBB2] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Entit__29B90FEB] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Depar__2AAD3424] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__2B495710] DEFAULT ((0)) FOR [InitialBudgetRate01]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Accou__2BA1585D] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__2C3D7B49] DEFAULT ((0)) FOR [InitialBudgetRate02]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Finan__2C957C96] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__2D319F82] DEFAULT ((0)) FOR [InitialBudgetRate03]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Payor__2D89A0CF] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__2E25C3BB] DEFAULT ((0)) FOR [InitialBudgetRate04]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Patie__2E7DC508] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__2F19E7F4] DEFAULT ((0)) FOR [InitialBudgetRate05]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__UnitT__2F71E941] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__300E0C2D] DEFAULT ((0)) FOR [InitialBudgetRate06]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__AddDa__30660D7A] DEFAULT (getdate()) FOR [AddDate]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__31023066] DEFAULT ((0)) FOR [InitialBudgetRate07]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__315A31B3] DEFAULT ((0)) FOR [SampledBudget01]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__31F6549F] DEFAULT ((0)) FOR [InitialBudgetRate08]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__324E55EC] DEFAULT ((0)) FOR [SampledBudget02]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__32EA78D8] DEFAULT ((0)) FOR [InitialBudgetRate09]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__33427A25] DEFAULT ((0)) FOR [SampledBudget03]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__IsNew__3343457C] DEFAULT ((0)) FOR [IsNew]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__33DE9D11] DEFAULT ((0)) FOR [InitialBudgetRate10]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__34369E5E] DEFAULT ((0)) FOR [SampledBudget04]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__34D2C14A] DEFAULT ((0)) FOR [InitialBudgetRate11]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__352AC297] DEFAULT ((0)) FOR [SampledBudget05]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__35C6E583] DEFAULT ((0)) FOR [InitialBudgetRate12]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__361EE6D0] DEFAULT ((0)) FOR [SampledBudget06]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__36BB09BC] DEFAULT ((0)) FOR [InitialProjectionRate01]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__37130B09] DEFAULT ((0)) FOR [SampledBudget07]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__37AF2DF5] DEFAULT ((0)) FOR [InitialProjectionRate02]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__38072F42] DEFAULT ((0)) FOR [SampledBudget08]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__38A3522E] DEFAULT ((0)) FOR [InitialProjectionRate03]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__38FB537B] DEFAULT ((0)) FOR [SampledBudget09]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__39977667] DEFAULT ((0)) FOR [InitialProjectionRate04]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__39EF77B4] DEFAULT ((0)) FOR [SampledBudget10]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__3A8B9AA0] DEFAULT ((0)) FOR [InitialProjectionRate05]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__3AE39BED] DEFAULT ((0)) FOR [SampledBudget11]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__3B7FBED9] DEFAULT ((0)) FOR [InitialProjectionRate06]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__3BD7C026] DEFAULT ((0)) FOR [SampledBudget12]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__3C73E312] DEFAULT ((0)) FOR [InitialProjectionRate07]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__3CCBE45F] DEFAULT ((0)) FOR [SampledProjection01]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__3D68074B] DEFAULT ((0)) FOR [InitialProjectionRate08]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__3DC00898] DEFAULT ((0)) FOR [SampledProjection02]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__3E5C2B84] DEFAULT ((0)) FOR [InitialProjectionRate09]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__3EB42CD1] DEFAULT ((0)) FOR [SampledProjection03]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__3F504FBD] DEFAULT ((0)) FOR [InitialProjectionRate10]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__3FA8510A] DEFAULT ((0)) FOR [SampledProjection04]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__404473F6] DEFAULT ((0)) FOR [InitialProjectionRate11]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__409C7543] DEFAULT ((0)) FOR [SampledProjection05]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__4138982F] DEFAULT ((0)) FOR [InitialProjectionRate12]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__4190997C] DEFAULT ((0)) FOR [SampledProjection06]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__4284BDB5] DEFAULT ((0)) FOR [SampledProjection07]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__4378E1EE] DEFAULT ((0)) FOR [SampledProjection08]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__446D0627] DEFAULT ((0)) FOR [SampledProjection09]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__45612A60] DEFAULT ((0)) FOR [SampledProjection10]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__46554E99] DEFAULT ((0)) FOR [SampledProjection11]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Sampl__474972D2] DEFAULT ((0)) FOR [SampledProjection12]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__483D970B] DEFAULT ((0)) FOR [InitialBudget01]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__4931BB44] DEFAULT ((0)) FOR [InitialBudget02]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__4A25DF7D] DEFAULT ((0)) FOR [InitialBudget03]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__4B1A03B6] DEFAULT ((0)) FOR [InitialBudget04]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__4C0E27EF] DEFAULT ((0)) FOR [InitialBudget05]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__4D024C28] DEFAULT ((0)) FOR [InitialBudget06]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__4DF67061] DEFAULT ((0)) FOR [InitialBudget07]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__4EEA949A] DEFAULT ((0)) FOR [InitialBudget08]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__4FDEB8D3] DEFAULT ((0)) FOR [InitialBudget09]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__50D2DD0C] DEFAULT ((0)) FOR [InitialBudget10]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__51C70145] DEFAULT ((0)) FOR [InitialBudget11]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__52BB257E] DEFAULT ((0)) FOR [InitialBudget12]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__53AF49B7] DEFAULT ((0)) FOR [InitialProjection01]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__54A36DF0] DEFAULT ((0)) FOR [InitialProjection02]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__55979229] DEFAULT ((0)) FOR [InitialProjection03]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__568BB662] DEFAULT ((0)) FOR [InitialProjection04]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__577FDA9B] DEFAULT ((0)) FOR [InitialProjection05]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__5873FED4] DEFAULT ((0)) FOR [InitialProjection06]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__5968230D] DEFAULT ((0)) FOR [InitialProjection07]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__5A5C4746] DEFAULT ((0)) FOR [InitialProjection08]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__5B506B7F] DEFAULT ((0)) FOR [InitialProjection09]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__5C448FB8] DEFAULT ((0)) FOR [InitialProjection10]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__5D38B3F1] DEFAULT ((0)) FOR [InitialProjection11]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Initi__5E2CD82A] DEFAULT ((0)) FOR [InitialProjection12]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Provi__7D2D86A5] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Provi__7E21AADE] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Group__7EA19922] DEFAULT (newid()) FOR [GroupingGUID]; GO +ALTER TABLE [fp].[FactStatistics] ADD CONSTRAINT [DF__FactStati__Provi__7F15CF17] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactStatisticsBudget ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactStatisticsBudget] ( + [RowID] int NOT NULL, + [StatisticsID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedValue01] decimal NOT NULL, + [AdjustedValue02] decimal NOT NULL, + [AdjustedValue03] decimal NOT NULL, + [AdjustedValue04] decimal NOT NULL, + [AdjustedValue05] decimal NOT NULL, + [AdjustedValue06] decimal NOT NULL, + [AdjustedValue07] decimal NOT NULL, + [AdjustedValue08] decimal NOT NULL, + [AdjustedValue09] decimal NOT NULL, + [AdjustedValue10] decimal NOT NULL, + [AdjustedValue11] decimal NOT NULL, + [AdjustedValue12] decimal NOT NULL, + [AdjustedValueTotal] decimal NOT NULL, + [RateAdjustedValue01] decimal NOT NULL, + [RateAdjustedValue02] decimal NOT NULL, + [RateAdjustedValue03] decimal NOT NULL, + [RateAdjustedValue04] decimal NOT NULL, + [RateAdjustedValue05] decimal NOT NULL, + [RateAdjustedValue06] decimal NOT NULL, + [RateAdjustedValue07] decimal NOT NULL, + [RateAdjustedValue08] decimal NOT NULL, + [RateAdjustedValue09] decimal NOT NULL, + [RateAdjustedValue10] decimal NOT NULL, + [RateAdjustedValue11] decimal NOT NULL, + [RateAdjustedValue12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_FactStatisticsBudget] ON [fp].[FactStatisticsBudget] ([StatisticsID], [BudgetPhaseID]); +CREATE NONCLUSTERED INDEX [IX_FactStatisticsBudget_BudgetPhaseID] ON [fp].[FactStatisticsBudget] ([BudgetPhaseID], [StatisticsID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[FactStatisticsBudget] ([StatisticsID], [BudgetPhaseID]); +GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [FK_FactStatisticsBudget_StatisticsID] FOREIGN KEY ([StatisticsID]) REFERENCES [fp].[FactStatistics] ([StatisticsID]); GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Stati__279BBD4F] DEFAULT ((0)) FOR [StatisticsID]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__LockT__288FE188] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__LockF__298405C1] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Budge__2A7829FA] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__2B6C4E33] DEFAULT ((0)) FOR [AdjustedValue01]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__2C60726C] DEFAULT ((0)) FOR [AdjustedValue02]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__2D5496A5] DEFAULT ((0)) FOR [AdjustedValue03]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__2E48BADE] DEFAULT ((0)) FOR [AdjustedValue04]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__2F3CDF17] DEFAULT ((0)) FOR [AdjustedValue05]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__30310350] DEFAULT ((0)) FOR [AdjustedValue06]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__31252789] DEFAULT ((0)) FOR [AdjustedValue07]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__32194BC2] DEFAULT ((0)) FOR [AdjustedValue08]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__330D6FFB] DEFAULT ((0)) FOR [AdjustedValue09]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__34019434] DEFAULT ((0)) FOR [AdjustedValue10]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__34F5B86D] DEFAULT ((0)) FOR [AdjustedValue11]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__Adjus__35E9DCA6] DEFAULT ((0)) FOR [AdjustedValue12]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__422CBC68] DEFAULT ((0)) FOR [RateAdjustedValue01]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__4320E0A1] DEFAULT ((0)) FOR [RateAdjustedValue02]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__441504DA] DEFAULT ((0)) FOR [RateAdjustedValue03]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__45092913] DEFAULT ((0)) FOR [RateAdjustedValue04]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__45FD4D4C] DEFAULT ((0)) FOR [RateAdjustedValue05]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__46F17185] DEFAULT ((0)) FOR [RateAdjustedValue06]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__47E595BE] DEFAULT ((0)) FOR [RateAdjustedValue07]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__48D9B9F7] DEFAULT ((0)) FOR [RateAdjustedValue08]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__49CDDE30] DEFAULT ((0)) FOR [RateAdjustedValue09]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__4AC20269] DEFAULT ((0)) FOR [RateAdjustedValue10]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__4BB626A2] DEFAULT ((0)) FOR [RateAdjustedValue11]; GO +ALTER TABLE [fp].[FactStatisticsBudget] ADD CONSTRAINT [DF__FactStati__RateA__4CAA4ADB] DEFAULT ((0)) FOR [RateAdjustedValue12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactStatisticsHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactStatisticsHistory] ( + [RowID] int NOT NULL, + [StatisticsID] int NOT NULL, + [PriorYearActualValue01] decimal NOT NULL, + [PriorYearActualValue02] decimal NOT NULL, + [PriorYearActualValue03] decimal NOT NULL, + [PriorYearActualValue04] decimal NOT NULL, + [PriorYearActualValue05] decimal NOT NULL, + [PriorYearActualValue06] decimal NOT NULL, + [PriorYearActualValue07] decimal NOT NULL, + [PriorYearActualValue08] decimal NOT NULL, + [PriorYearActualValue09] decimal NOT NULL, + [PriorYearActualValue10] decimal NOT NULL, + [PriorYearActualValue11] decimal NOT NULL, + [PriorYearActualValue12] decimal NOT NULL, + [ActualYTDValue01] decimal NOT NULL, + [ActualYTDValue02] decimal NOT NULL, + [ActualYTDValue03] decimal NOT NULL, + [ActualYTDValue04] decimal NOT NULL, + [ActualYTDValue05] decimal NOT NULL, + [ActualYTDValue06] decimal NOT NULL, + [ActualYTDValue07] decimal NOT NULL, + [ActualYTDValue08] decimal NOT NULL, + [ActualYTDValue09] decimal NOT NULL, + [ActualYTDValue10] decimal NOT NULL, + [ActualYTDValue11] decimal NOT NULL, + [ActualYTDValue12] decimal NOT NULL, + [CurrentYearBudget01] decimal NOT NULL, + [CurrentYearBudget02] decimal NOT NULL, + [CurrentYearBudget03] decimal NOT NULL, + [CurrentYearBudget04] decimal NOT NULL, + [CurrentYearBudget05] decimal NOT NULL, + [CurrentYearBudget06] decimal NOT NULL, + [CurrentYearBudget07] decimal NOT NULL, + [CurrentYearBudget08] decimal NOT NULL, + [CurrentYearBudget09] decimal NOT NULL, + [CurrentYearBudget10] decimal NOT NULL, + [CurrentYearBudget11] decimal NOT NULL, + [CurrentYearBudget12] decimal NOT NULL, + [PriorYearActualValueTotal] decimal NOT NULL, + [ActualYTDValueTotal] decimal NOT NULL, + [CurrentYearBudgetTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_FactStatisticsHistory] ON [fp].[FactStatisticsHistory] ([StatisticsID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[FactStatisticsHistory] ([StatisticsID]); +GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [FK_FactStatisticsHistory_StatisticsID] FOREIGN KEY ([StatisticsID]) REFERENCES [fp].[FactStatistics] ([StatisticsID]); GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__004CE604] DEFAULT ((0)) FOR [ActualYTDValue07]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__01410A3D] DEFAULT ((0)) FOR [ActualYTDValue08]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__02352E76] DEFAULT ((0)) FOR [ActualYTDValue09]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__032952AF] DEFAULT ((0)) FOR [ActualYTDValue10]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__041D76E8] DEFAULT ((0)) FOR [ActualYTDValue11]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__05119B21] DEFAULT ((0)) FOR [ActualYTDValue12]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__0605BF5A] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__06F9E393] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__07EE07CC] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__08E22C05] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__09D6503E] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__0ACA7477] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__0BBE98B0] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__0CB2BCE9] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__0DA6E122] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__0E9B055B] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__0F8F2994] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Curre__10834DCD] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Stati__6E2E35C9] DEFAULT ((0)) FOR [StatisticsID]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__6F225A02] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__70167E3B] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__710AA274] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__71FEC6AD] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__72F2EAE6] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__73E70F1F] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__74DB3358] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__75CF5791] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__76C37BCA] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__77B7A003] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__78ABC43C] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Prior__799FE875] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__7A940CAE] DEFAULT ((0)) FOR [ActualYTDValue01]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__7B8830E7] DEFAULT ((0)) FOR [ActualYTDValue02]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__7C7C5520] DEFAULT ((0)) FOR [ActualYTDValue03]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__7D707959] DEFAULT ((0)) FOR [ActualYTDValue04]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__7E649D92] DEFAULT ((0)) FOR [ActualYTDValue05]; GO +ALTER TABLE [fp].[FactStatisticsHistory] ADD CONSTRAINT [DF__FactStati__Actua__7F58C1CB] DEFAULT ((0)) FOR [ActualYTDValue06]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FactStatisticsProjection ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FactStatisticsProjection] ( + [RowID] int NOT NULL, + [StatisticsID] int NOT NULL, + [LockType] tinyint NOT NULL, + [LockFlag] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustedValue01] decimal NOT NULL, + [AdjustedValue02] decimal NOT NULL, + [AdjustedValue03] decimal NOT NULL, + [AdjustedValue04] decimal NOT NULL, + [AdjustedValue05] decimal NOT NULL, + [AdjustedValue06] decimal NOT NULL, + [AdjustedValue07] decimal NOT NULL, + [AdjustedValue08] decimal NOT NULL, + [AdjustedValue09] decimal NOT NULL, + [AdjustedValue10] decimal NOT NULL, + [AdjustedValue11] decimal NOT NULL, + [AdjustedValue12] decimal NOT NULL, + [AdjustedValueTotal] decimal NOT NULL, + [RateAdjustedValue01] decimal NOT NULL, + [RateAdjustedValue02] decimal NOT NULL, + [RateAdjustedValue03] decimal NOT NULL, + [RateAdjustedValue04] decimal NOT NULL, + [RateAdjustedValue05] decimal NOT NULL, + [RateAdjustedValue06] decimal NOT NULL, + [RateAdjustedValue07] decimal NOT NULL, + [RateAdjustedValue08] decimal NOT NULL, + [RateAdjustedValue09] decimal NOT NULL, + [RateAdjustedValue10] decimal NOT NULL, + [RateAdjustedValue11] decimal NOT NULL, + [RateAdjustedValue12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_FactStatisticsProjection] ON [fp].[FactStatisticsProjection] ([StatisticsID], [BudgetPhaseID]); +CREATE NONCLUSTERED INDEX [IX_FactStatisticsProjection_BudgetPhaseID] ON [fp].[FactStatisticsProjection] ([BudgetPhaseID], [StatisticsID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[FactStatisticsProjection] ([StatisticsID], [BudgetPhaseID]); +GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [FK_FactStatisticsProjection_StatisticsID] FOREIGN KEY ([StatisticsID]) REFERENCES [fp].[FactStatistics] ([StatisticsID]); GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Stati__452C2036] DEFAULT ((0)) FOR [StatisticsID]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__LockT__4620446F] DEFAULT ((0)) FOR [LockType]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__LockF__471468A8] DEFAULT ((0)) FOR [LockFlag]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Budge__48088CE1] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__48FCB11A] DEFAULT ((0)) FOR [AdjustedValue01]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__49F0D553] DEFAULT ((0)) FOR [AdjustedValue02]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__4AE4F98C] DEFAULT ((0)) FOR [AdjustedValue03]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__4BD91DC5] DEFAULT ((0)) FOR [AdjustedValue04]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__4CCD41FE] DEFAULT ((0)) FOR [AdjustedValue05]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__4D9E6F14] DEFAULT ((0)) FOR [RateAdjustedValue01]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__4DC16637] DEFAULT ((0)) FOR [AdjustedValue06]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__4E92934D] DEFAULT ((0)) FOR [RateAdjustedValue02]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__4EB58A70] DEFAULT ((0)) FOR [AdjustedValue07]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__4F86B786] DEFAULT ((0)) FOR [RateAdjustedValue03]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__4FA9AEA9] DEFAULT ((0)) FOR [AdjustedValue08]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__507ADBBF] DEFAULT ((0)) FOR [RateAdjustedValue04]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__509DD2E2] DEFAULT ((0)) FOR [AdjustedValue09]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__516EFFF8] DEFAULT ((0)) FOR [RateAdjustedValue05]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__5191F71B] DEFAULT ((0)) FOR [AdjustedValue10]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__52632431] DEFAULT ((0)) FOR [RateAdjustedValue06]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__52861B54] DEFAULT ((0)) FOR [AdjustedValue11]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__5357486A] DEFAULT ((0)) FOR [RateAdjustedValue07]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__Adjus__537A3F8D] DEFAULT ((0)) FOR [AdjustedValue12]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__544B6CA3] DEFAULT ((0)) FOR [RateAdjustedValue08]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__553F90DC] DEFAULT ((0)) FOR [RateAdjustedValue09]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__5633B515] DEFAULT ((0)) FOR [RateAdjustedValue10]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__5727D94E] DEFAULT ((0)) FOR [RateAdjustedValue11]; GO +ALTER TABLE [fp].[FactStatisticsProjection] ADD CONSTRAINT [DF__FactStati__RateA__581BFD87] DEFAULT ((0)) FOR [RateAdjustedValue12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FixChangeHistoryRequest ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FixChangeHistoryRequest] ( + [RequestGUID] uniqueidentifier NOT NULL, + [ChangeHistoryRecordType] tinyint NOT NULL, + [DateCreatedUTC] datetime NOT NULL, + [BasisID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [Value01] decimal NOT NULL, + [Value02] decimal NOT NULL, + [Value03] decimal NOT NULL, + [Value04] decimal NOT NULL, + [Value05] decimal NOT NULL, + [Value06] decimal NOT NULL, + [Value07] decimal NOT NULL, + [Value08] decimal NOT NULL, + [Value09] decimal NOT NULL, + [Value10] decimal NOT NULL, + [Value11] decimal NOT NULL, + [Value12] decimal NOT NULL, + PRIMARY KEY ([RequestGUID]) +); +GO +ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF_FixChangeHistoryRequest_RequestGUID] DEFAULT (newid()) FOR [RequestGUID]; GO +ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF_FixChangeHistoryRequest_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF_FixChangeHistoryRequest_DateCreatedUTC] DEFAULT (getdate()) FOR [DateCreatedUTC]; GO +ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__IsRec__35DE5621] DEFAULT ((0)) FOR [IsRecordDeleted]; GO +ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__37C69E93] DEFAULT ((0)) FOR [Value01]; GO +ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__38BAC2CC] DEFAULT ((0)) FOR [Value02]; GO +ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__39AEE705] DEFAULT ((0)) FOR [Value03]; GO +ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__3AA30B3E] DEFAULT ((0)) FOR [Value04]; GO +ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__3B972F77] DEFAULT ((0)) FOR [Value05]; GO +ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__3C8B53B0] DEFAULT ((0)) FOR [Value06]; GO +ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__3D7F77E9] DEFAULT ((0)) FOR [Value07]; GO +ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__3E739C22] DEFAULT ((0)) FOR [Value08]; GO +ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__3F67C05B] DEFAULT ((0)) FOR [Value09]; GO +ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__405BE494] DEFAULT ((0)) FOR [Value10]; GO +ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__415008CD] DEFAULT ((0)) FOR [Value11]; GO +ALTER TABLE [fp].[FixChangeHistoryRequest] ADD CONSTRAINT [DF__FixChange__Value__42442D06] DEFAULT ((0)) FOR [Value12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.FlexConfigMapping ------------------ +--------------------------------------------- +CREATE TABLE [fp].[FlexConfigMapping] ( + [EntityGroupConfigID] int NOT NULL, + [DepartmentID] int NOT NULL, + [GLAccountID] int NOT NULL, + [StatAccountID] int NOT NULL, + [FlexingTypeID] int NOT NULL, + [PRJobCodeID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [PatientClassID] int NOT NULL, + [DependentStatisticAccountID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [SourceDepartmentID] int NOT NULL, + PRIMARY KEY ([EntityGroupConfigID], [FlexingTypeID], [DepartmentID], [GLAccountID], [StatAccountID], [PRJobCodeID], [ChargeCodeID], [PatientClassID], [DependentStatisticAccountID], [ProviderLineItemID], [SourceDepartmentID]) +); +GO +ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__PRJob__03CE9A1B] DEFAULT ((0)) FOR [PRJobCodeID]; GO +ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__Patie__0B872C81] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__Sourc__172FB1CF] DEFAULT ((0)) FOR [SourceDepartmentID]; GO +ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__Depen__29610E9E] DEFAULT ((0)) FOR [DependentStatisticAccountID]; GO +ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__Provi__29EB1E83] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__Charg__44008FCE] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__Entit__76749EFD] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__Depar__7768C336] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__GLAcc__785CE76F] DEFAULT ((0)) FOR [GLAccountID]; GO +ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__StatA__79510BA8] DEFAULT ((0)) FOR [StatAccountID]; GO +ALTER TABLE [fp].[FlexConfigMapping] ADD CONSTRAINT [DF__FlexConfi__Flexi__7A452FE1] DEFAULT ((0)) FOR [FlexingTypeID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedger ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedger] ( + [GeneralLedgerID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [VariabilityID] int NOT NULL, + [APEModelSectionID] tinyint NOT NULL, + [AddDate] datetime NOT NULL, + [IsNew] bit NOT NULL, + [FlexingTypeID] smallint NOT NULL, + [ChangeHistoryGroupingGUID] uniqueidentifier NOT NULL, + [BudgetLockType] tinyint NOT NULL, + [BudgetLockFlag] tinyint NOT NULL, + [TargetLockType] tinyint NOT NULL, + [TargetLockFlag] tinyint NOT NULL, + [ProjectionLockType] tinyint NOT NULL, + [ProjectionLockFlag] tinyint NOT NULL, + [SampledBudgetTotal] decimal NOT NULL, + [SampledProjectionTotal] decimal NOT NULL, + [InitialBudgetTotal] decimal NOT NULL, + [InitialProjectionTotal] decimal NOT NULL, + [BudgetAdjustedTotal] decimal NOT NULL, + [TargetAdjustedTotal] decimal NOT NULL, + [ProjectionAdjustedTotal] decimal NOT NULL, + [SampledBudget01] decimal NOT NULL, + [SampledBudget02] decimal NOT NULL, + [SampledBudget03] decimal NOT NULL, + [SampledBudget04] decimal NOT NULL, + [SampledBudget05] decimal NOT NULL, + [SampledBudget06] decimal NOT NULL, + [SampledBudget07] decimal NOT NULL, + [SampledBudget08] decimal NOT NULL, + [SampledBudget09] decimal NOT NULL, + [SampledBudget10] decimal NOT NULL, + [SampledBudget11] decimal NOT NULL, + [SampledBudget12] decimal NOT NULL, + [SampledProjection01] decimal NOT NULL, + [SampledProjection02] decimal NOT NULL, + [SampledProjection03] decimal NOT NULL, + [SampledProjection04] decimal NOT NULL, + [SampledProjection05] decimal NOT NULL, + [SampledProjection06] decimal NOT NULL, + [SampledProjection07] decimal NOT NULL, + [SampledProjection08] decimal NOT NULL, + [SampledProjection09] decimal NOT NULL, + [SampledProjection10] decimal NOT NULL, + [SampledProjection11] decimal NOT NULL, + [SampledProjection12] decimal NOT NULL, + [InitialBudget01] decimal NOT NULL, + [InitialBudget02] decimal NOT NULL, + [InitialBudget03] decimal NOT NULL, + [InitialBudget04] decimal NOT NULL, + [InitialBudget05] decimal NOT NULL, + [InitialBudget06] decimal NOT NULL, + [InitialBudget07] decimal NOT NULL, + [InitialBudget08] decimal NOT NULL, + [InitialBudget09] decimal NOT NULL, + [InitialBudget10] decimal NOT NULL, + [InitialBudget11] decimal NOT NULL, + [InitialBudget12] decimal NOT NULL, + [InitialProjection01] decimal NOT NULL, + [InitialProjection02] decimal NOT NULL, + [InitialProjection03] decimal NOT NULL, + [InitialProjection04] decimal NOT NULL, + [InitialProjection05] decimal NOT NULL, + [InitialProjection06] decimal NOT NULL, + [InitialProjection07] decimal NOT NULL, + [InitialProjection08] decimal NOT NULL, + [InitialProjection09] decimal NOT NULL, + [InitialProjection10] decimal NOT NULL, + [InitialProjection11] decimal NOT NULL, + [InitialProjection12] decimal NOT NULL, + [TargetAdjusted01] decimal NOT NULL, + [TargetAdjusted02] decimal NOT NULL, + [TargetAdjusted03] decimal NOT NULL, + [TargetAdjusted04] decimal NOT NULL, + [TargetAdjusted05] decimal NOT NULL, + [TargetAdjusted06] decimal NOT NULL, + [TargetAdjusted07] decimal NOT NULL, + [TargetAdjusted08] decimal NOT NULL, + [TargetAdjusted09] decimal NOT NULL, + [TargetAdjusted10] decimal NOT NULL, + [TargetAdjusted11] decimal NOT NULL, + [TargetAdjusted12] decimal NOT NULL, + [BudgetAdjusted01] decimal NOT NULL, + [BudgetAdjusted02] decimal NOT NULL, + [BudgetAdjusted03] decimal NOT NULL, + [BudgetAdjusted04] decimal NOT NULL, + [BudgetAdjusted05] decimal NOT NULL, + [BudgetAdjusted06] decimal NOT NULL, + [BudgetAdjusted07] decimal NOT NULL, + [BudgetAdjusted08] decimal NOT NULL, + [BudgetAdjusted09] decimal NOT NULL, + [BudgetAdjusted10] decimal NOT NULL, + [BudgetAdjusted11] decimal NOT NULL, + [BudgetAdjusted12] decimal NOT NULL, + [ProjectionAdjusted01] decimal NOT NULL, + [ProjectionAdjusted02] decimal NOT NULL, + [ProjectionAdjusted03] decimal NOT NULL, + [ProjectionAdjusted04] decimal NOT NULL, + [ProjectionAdjusted05] decimal NOT NULL, + [ProjectionAdjusted06] decimal NOT NULL, + [ProjectionAdjusted07] decimal NOT NULL, + [ProjectionAdjusted08] decimal NOT NULL, + [ProjectionAdjusted09] decimal NOT NULL, + [ProjectionAdjusted10] decimal NOT NULL, + [ProjectionAdjusted11] decimal NOT NULL, + [ProjectionAdjusted12] decimal NOT NULL, + [InitialBudgetDollarsPerUOS01] decimal NOT NULL, + [InitialBudgetDollarsPerUOS02] decimal NOT NULL, + [InitialBudgetDollarsPerUOS03] decimal NOT NULL, + [InitialBudgetDollarsPerUOS04] decimal NOT NULL, + [InitialBudgetDollarsPerUOS05] decimal NOT NULL, + [InitialBudgetDollarsPerUOS06] decimal NOT NULL, + [InitialBudgetDollarsPerUOS07] decimal NOT NULL, + [InitialBudgetDollarsPerUOS08] decimal NOT NULL, + [InitialBudgetDollarsPerUOS09] decimal NOT NULL, + [InitialBudgetDollarsPerUOS10] decimal NOT NULL, + [InitialBudgetDollarsPerUOS11] decimal NOT NULL, + [InitialBudgetDollarsPerUOS12] decimal NOT NULL, + [InitialProjectionDollarsPerUOS01] decimal NOT NULL, + [InitialProjectionDollarsPerUOS02] decimal NOT NULL, + [InitialProjectionDollarsPerUOS03] decimal NOT NULL, + [InitialProjectionDollarsPerUOS04] decimal NOT NULL, + [InitialProjectionDollarsPerUOS05] decimal NOT NULL, + [InitialProjectionDollarsPerUOS06] decimal NOT NULL, + [InitialProjectionDollarsPerUOS07] decimal NOT NULL, + [InitialProjectionDollarsPerUOS08] decimal NOT NULL, + [InitialProjectionDollarsPerUOS09] decimal NOT NULL, + [InitialProjectionDollarsPerUOS10] decimal NOT NULL, + [InitialProjectionDollarsPerUOS11] decimal NOT NULL, + [InitialProjectionDollarsPerUOS12] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted01] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted02] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted03] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted04] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted05] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted06] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted07] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted08] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted09] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted10] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted11] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted12] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted01] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted02] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted03] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted04] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted05] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted06] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted07] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted08] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted09] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted10] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted11] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted12] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted01] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted02] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted03] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted04] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted05] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted06] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted07] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted08] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted09] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted10] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted11] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted12] decimal NOT NULL, + [InitialBudgetPercentOfCharge01] decimal NOT NULL, + [InitialBudgetPercentOfCharge02] decimal NOT NULL, + [InitialBudgetPercentOfCharge03] decimal NOT NULL, + [InitialBudgetPercentOfCharge04] decimal NOT NULL, + [InitialBudgetPercentOfCharge05] decimal NOT NULL, + [InitialBudgetPercentOfCharge06] decimal NOT NULL, + [InitialBudgetPercentOfCharge07] decimal NOT NULL, + [InitialBudgetPercentOfCharge08] decimal NOT NULL, + [InitialBudgetPercentOfCharge09] decimal NOT NULL, + [InitialBudgetPercentOfCharge10] decimal NOT NULL, + [InitialBudgetPercentOfCharge11] decimal NOT NULL, + [InitialBudgetPercentOfCharge12] decimal NOT NULL, + [InitialProjectionPercentOfCharge01] decimal NOT NULL, + [InitialProjectionPercentOfCharge02] decimal NOT NULL, + [InitialProjectionPercentOfCharge03] decimal NOT NULL, + [InitialProjectionPercentOfCharge04] decimal NOT NULL, + [InitialProjectionPercentOfCharge05] decimal NOT NULL, + [InitialProjectionPercentOfCharge06] decimal NOT NULL, + [InitialProjectionPercentOfCharge07] decimal NOT NULL, + [InitialProjectionPercentOfCharge08] decimal NOT NULL, + [InitialProjectionPercentOfCharge09] decimal NOT NULL, + [InitialProjectionPercentOfCharge10] decimal NOT NULL, + [InitialProjectionPercentOfCharge11] decimal NOT NULL, + [InitialProjectionPercentOfCharge12] decimal NOT NULL, + [TargetPercentOfChargeAdjusted01] decimal NOT NULL, + [TargetPercentOfChargeAdjusted02] decimal NOT NULL, + [TargetPercentOfChargeAdjusted03] decimal NOT NULL, + [TargetPercentOfChargeAdjusted04] decimal NOT NULL, + [TargetPercentOfChargeAdjusted05] decimal NOT NULL, + [TargetPercentOfChargeAdjusted06] decimal NOT NULL, + [TargetPercentOfChargeAdjusted07] decimal NOT NULL, + [TargetPercentOfChargeAdjusted08] decimal NOT NULL, + [TargetPercentOfChargeAdjusted09] decimal NOT NULL, + [TargetPercentOfChargeAdjusted10] decimal NOT NULL, + [TargetPercentOfChargeAdjusted11] decimal NOT NULL, + [TargetPercentOfChargeAdjusted12] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted01] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted02] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted03] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted04] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted05] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted06] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted07] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted08] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted09] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted10] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted11] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted12] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted01] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted02] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted03] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted04] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted05] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted06] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted07] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted08] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted09] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted10] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted11] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted12] decimal NOT NULL, + [TargetPercentAdjustmentFactor01] decimal NOT NULL, + [TargetPercentAdjustmentFactor02] decimal NOT NULL, + [TargetPercentAdjustmentFactor03] decimal NOT NULL, + [TargetPercentAdjustmentFactor04] decimal NOT NULL, + [TargetPercentAdjustmentFactor05] decimal NOT NULL, + [TargetPercentAdjustmentFactor06] decimal NOT NULL, + [TargetPercentAdjustmentFactor07] decimal NOT NULL, + [TargetPercentAdjustmentFactor08] decimal NOT NULL, + [TargetPercentAdjustmentFactor09] decimal NOT NULL, + [TargetPercentAdjustmentFactor10] decimal NOT NULL, + [TargetPercentAdjustmentFactor11] decimal NOT NULL, + [TargetPercentAdjustmentFactor12] decimal NOT NULL, + [BudgetPercentAdjustmentFactor01] decimal NOT NULL, + [BudgetPercentAdjustmentFactor02] decimal NOT NULL, + [BudgetPercentAdjustmentFactor03] decimal NOT NULL, + [BudgetPercentAdjustmentFactor04] decimal NOT NULL, + [BudgetPercentAdjustmentFactor05] decimal NOT NULL, + [BudgetPercentAdjustmentFactor06] decimal NOT NULL, + [BudgetPercentAdjustmentFactor07] decimal NOT NULL, + [BudgetPercentAdjustmentFactor08] decimal NOT NULL, + [BudgetPercentAdjustmentFactor09] decimal NOT NULL, + [BudgetPercentAdjustmentFactor10] decimal NOT NULL, + [BudgetPercentAdjustmentFactor11] decimal NOT NULL, + [BudgetPercentAdjustmentFactor12] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor01] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor02] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor03] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor04] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor05] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor06] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor07] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor08] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor09] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor10] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor11] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor12] decimal NOT NULL, + PRIMARY KEY ([GeneralLedgerID]) +); + +CREATE UNIQUE CLUSTERED INDEX [IX_Unique] ON [fp].[GeneralLedger] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [VariabilityID]); +CREATE NONCLUSTERED INDEX [IX_GeneralLedger_Account] ON [fp].[GeneralLedger] ([AccountID]) INCLUDE ([GeneralLedgerID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [FinancialReportingID], [VariabilityID]); +CREATE NONCLUSTERED INDEX [IX_GeneralLedger_BudgetDollarsConfig] ON [fp].[GeneralLedger] ([BudgetConfigID]) INCLUDE ([GeneralLedgerID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [VariabilityID]); +CREATE NONCLUSTERED INDEX [IX_GeneralLedger_Department] ON [fp].[GeneralLedger] ([DepartmentID]) INCLUDE ([GeneralLedgerID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [AccountID], [FinancialReportingID], [VariabilityID]); +CREATE NONCLUSTERED INDEX [IX_GeneralLedger_Entity] ON [fp].[GeneralLedger] ([EntityID]) INCLUDE ([GeneralLedgerID], [BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [AccountID], [FinancialReportingID], [VariabilityID]); +CREATE NONCLUSTERED INDEX [IX_GeneralLedger_EntityGroupConfig] ON [fp].[GeneralLedger] ([EntityGroupConfigID], [FlexingTypeID]) INCLUDE ([GeneralLedgerID], [BudgetConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [VariabilityID]); +GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [FK_GeneralLedger_Account] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [FK_GeneralLedger_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [FK_GeneralLedger_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [FK_GeneralLedger_FinancialReporting] FOREIGN KEY ([FinancialReportingID]) REFERENCES [ob].[DimFinancialReporting] ([FinancialReportingID]); GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [FK_GeneralLedger_Variability] FOREIGN KEY ([VariabilityID]) REFERENCES [fw].[DimVariability] ([VariabilityID]); GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__00222F45] DEFAULT ((0)) FOR [ProjectionAdjusted02]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__0116537E] DEFAULT ((0)) FOR [ProjectionAdjusted03]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__020A77B7] DEFAULT ((0)) FOR [ProjectionAdjusted04]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__02FE9BF0] DEFAULT ((0)) FOR [ProjectionAdjusted05]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__03F2C029] DEFAULT ((0)) FOR [ProjectionAdjusted06]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__04E6E462] DEFAULT ((0)) FOR [ProjectionAdjusted07]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__05DB089B] DEFAULT ((0)) FOR [ProjectionAdjusted08]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__06CF2CD4] DEFAULT ((0)) FOR [ProjectionAdjusted09]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__07C3510D] DEFAULT ((0)) FOR [ProjectionAdjusted10]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__08B77546] DEFAULT ((0)) FOR [ProjectionAdjusted11]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__09AB997F] DEFAULT ((0)) FOR [ProjectionAdjusted12]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__0A9FBDB8] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS01]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__0B93E1F1] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS02]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__0C88062A] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS03]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__0D7C2A63] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS04]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__0E704E9C] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS05]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__0F6472D5] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS06]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__1058970E] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS07]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__114CBB47] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS08]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__1240DF80] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS09]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__133503B9] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS10]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__142927F2] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS11]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__151D4C2B] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS12]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__16117064] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS01]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__1705949D] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS02]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__17F9B8D6] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS03]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__18EDDD0F] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS04]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__19E20148] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS05]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__1AD62581] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS06]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__1BCA49BA] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS07]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__1CBE6DF3] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS08]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__1DB2922C] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS09]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__1EA6B665] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS10]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__1F9ADA9E] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS11]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__208EFED7] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS12]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__21832310] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted01]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__22774749] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted02]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__236B6B82] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted03]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__245F8FBB] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted04]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__2553B3F4] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted05]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__2647D82D] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted06]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__273BFC66] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted07]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__2830209F] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted08]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__292444D8] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted09]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__29594F02] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__2A186911] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted10]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Entit__2A4D733B] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__2B0C8D4A] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted11]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Entit__2B419774] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__2C00B183] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted12]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Depar__2C35BBAD] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__2CF4D5BC] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted01]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Accou__2D29DFE6] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__2DE8F9F5] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted02]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Finan__2E1E041F] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__2EDD1E2E] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted03]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Varia__2F122858] DEFAULT ((0)) FOR [VariabilityID]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__2FD14267] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted04]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__APEMo__30064C91] DEFAULT ((0)) FOR [APEModelSectionID]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__30C566A0] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted05]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__AddDa__30FA70CA] DEFAULT ('1900-01-01') FOR [AddDate]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__31B98AD9] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted06]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__IsNew__31EE9503] DEFAULT ((0)) FOR [IsNew]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__32ADAF12] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted07]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Flexi__32E2B93C] DEFAULT ((0)) FOR [FlexingTypeID]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__33A1D34B] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted08]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Chang__33D6DD75] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ChangeHistoryGroupingGUID]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__3495F784] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted09]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__34CB01AE] DEFAULT ((0)) FOR [BudgetLockType]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__358A1BBD] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted10]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__35BF25E7] DEFAULT ((0)) FOR [BudgetLockFlag]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__367E3FF6] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted11]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__36B34A20] DEFAULT ((0)) FOR [TargetLockType]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__3772642F] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted12]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__37A76E59] DEFAULT ((0)) FOR [TargetLockFlag]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__38668868] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted01]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__389B9292] DEFAULT ((0)) FOR [ProjectionLockType]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__395AACA1] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted02]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__398FB6CB] DEFAULT ((0)) FOR [ProjectionLockFlag]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__3A4ED0DA] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted03]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__3A83DB04] DEFAULT ((0)) FOR [SampledBudget01]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__3B42F513] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted04]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__3B77FF3D] DEFAULT ((0)) FOR [SampledBudget02]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__3C37194C] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted05]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__3C6C2376] DEFAULT ((0)) FOR [SampledBudget03]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__3D2B3D85] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted06]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__3D6047AF] DEFAULT ((0)) FOR [SampledBudget04]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__3E1F61BE] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted07]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__3E546BE8] DEFAULT ((0)) FOR [SampledBudget05]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__3F1385F7] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted08]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__3F489021] DEFAULT ((0)) FOR [SampledBudget06]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__4007AA30] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted09]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__403CB45A] DEFAULT ((0)) FOR [SampledBudget07]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__40FBCE69] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted10]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__4130D893] DEFAULT ((0)) FOR [SampledBudget08]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__41EFF2A2] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted11]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__4224FCCC] DEFAULT ((0)) FOR [SampledBudget09]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__42E416DB] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted12]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__43192105] DEFAULT ((0)) FOR [SampledBudget10]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__43D83B14] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge01]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__440D453E] DEFAULT ((0)) FOR [SampledBudget11]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__44CC5F4D] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge02]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__45016977] DEFAULT ((0)) FOR [SampledBudget12]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__45C08386] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge03]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__45F58DB0] DEFAULT ((0)) FOR [SampledProjection01]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__46B4A7BF] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge04]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__46E9B1E9] DEFAULT ((0)) FOR [SampledProjection02]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__47A8CBF8] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge05]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__47DDD622] DEFAULT ((0)) FOR [SampledProjection03]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__489CF031] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge06]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__48D1FA5B] DEFAULT ((0)) FOR [SampledProjection04]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor01] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__4991146A] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge07]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__49C61E94] DEFAULT ((0)) FOR [SampledProjection05]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor02] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__4A8538A3] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge08]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__4ABA42CD] DEFAULT ((0)) FOR [SampledProjection06]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor03] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__4B795CDC] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge09]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__4BAE6706] DEFAULT ((0)) FOR [SampledProjection07]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor04] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__4C6D8115] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge10]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__4CA28B3F] DEFAULT ((0)) FOR [SampledProjection08]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor05] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__4D61A54E] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge11]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__4D96AF78] DEFAULT ((0)) FOR [SampledProjection09]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor06] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__4E55C987] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge12]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__4E8AD3B1] DEFAULT ((0)) FOR [SampledProjection10]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor07] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__4F49EDC0] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge01]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__4F7EF7EA] DEFAULT ((0)) FOR [SampledProjection11]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor08] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor08]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__503E11F9] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge02]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Sampl__50731C23] DEFAULT ((0)) FOR [SampledProjection12]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor09] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__51323632] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge03]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__5167405C] DEFAULT ((0)) FOR [InitialBudget01]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor10] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__52265A6B] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge04]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__525B6495] DEFAULT ((0)) FOR [InitialBudget02]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor11] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__531A7EA4] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge05]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__534F88CE] DEFAULT ((0)) FOR [InitialBudget03]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_TargetPercentAdjustmentFactor12] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor12]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__540EA2DD] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge06]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__5443AD07] DEFAULT ((0)) FOR [InitialBudget04]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor01] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__5502C716] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge07]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__5537D140] DEFAULT ((0)) FOR [InitialBudget05]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor02] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__55F6EB4F] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge08]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__562BF579] DEFAULT ((0)) FOR [InitialBudget06]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor03] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__56EB0F88] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge09]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__572019B2] DEFAULT ((0)) FOR [InitialBudget07]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor04] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__57DF33C1] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge10]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__58143DEB] DEFAULT ((0)) FOR [InitialBudget08]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor05] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__58D357FA] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge11]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__59086224] DEFAULT ((0)) FOR [InitialBudget09]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor06] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__59C77C33] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge12]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__59FC865D] DEFAULT ((0)) FOR [InitialBudget10]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor07] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__5ABBA06C] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted01]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__5AF0AA96] DEFAULT ((0)) FOR [InitialBudget11]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor08] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor08]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__5BAFC4A5] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted02]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__5BE4CECF] DEFAULT ((0)) FOR [InitialBudget12]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor09] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__5CA3E8DE] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted03]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__5CD8F308] DEFAULT ((0)) FOR [InitialProjection01]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor10] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__5D980D17] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted04]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__5DCD1741] DEFAULT ((0)) FOR [InitialProjection02]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor11] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__5E8C3150] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted05]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__5EC13B7A] DEFAULT ((0)) FOR [InitialProjection03]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_BudgetPercentAdjustmentFactor12] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor12]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__5F805589] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted06]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__5FB55FB3] DEFAULT ((0)) FOR [InitialProjection04]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor01] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__607479C2] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted07]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__60A983EC] DEFAULT ((0)) FOR [InitialProjection05]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor02] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__61689DFB] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted08]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__619DA825] DEFAULT ((0)) FOR [InitialProjection06]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor03] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__625CC234] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted09]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__6291CC5E] DEFAULT ((0)) FOR [InitialProjection07]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor04] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__6350E66D] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted10]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__6385F097] DEFAULT ((0)) FOR [InitialProjection08]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor05] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__64450AA6] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted11]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__647A14D0] DEFAULT ((0)) FOR [InitialProjection09]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor06] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__65392EDF] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted12]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__656E3909] DEFAULT ((0)) FOR [InitialProjection10]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor07] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__662D5318] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted01]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__66625D42] DEFAULT ((0)) FOR [InitialProjection11]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor08] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor08]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__67217751] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted02]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Initi__6756817B] DEFAULT ((0)) FOR [InitialProjection12]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor09] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__68159B8A] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted03]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__684AA5B4] DEFAULT ((0)) FOR [TargetAdjusted01]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor10] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__6909BFC3] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted04]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__693EC9ED] DEFAULT ((0)) FOR [TargetAdjusted02]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor11] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__69FDE3FC] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted05]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__6A32EE26] DEFAULT ((0)) FOR [TargetAdjusted03]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [df_GeneralLedger_ProjectionPercentAdjustmentFactor12] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor12]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__6AF20835] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted06]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__6B27125F] DEFAULT ((0)) FOR [TargetAdjusted04]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__6BE62C6E] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted07]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__6C1B3698] DEFAULT ((0)) FOR [TargetAdjusted05]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__6CDA50A7] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted08]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__6D0F5AD1] DEFAULT ((0)) FOR [TargetAdjusted06]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__6DCE74E0] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted09]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__6E037F0A] DEFAULT ((0)) FOR [TargetAdjusted07]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__6EC29919] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted10]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__6EF7A343] DEFAULT ((0)) FOR [TargetAdjusted08]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__6FB6BD52] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted11]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__6FEBC77C] DEFAULT ((0)) FOR [TargetAdjusted09]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__70AAE18B] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted12]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__70DFEBB5] DEFAULT ((0)) FOR [TargetAdjusted10]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__719F05C4] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted01]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__71D40FEE] DEFAULT ((0)) FOR [TargetAdjusted11]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__729329FD] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted02]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Targe__72C83427] DEFAULT ((0)) FOR [TargetAdjusted12]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__73874E36] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted03]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__73BC5860] DEFAULT ((0)) FOR [BudgetAdjusted01]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__747B726F] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted04]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__74B07C99] DEFAULT ((0)) FOR [BudgetAdjusted02]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__756F96A8] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted05]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__75A4A0D2] DEFAULT ((0)) FOR [BudgetAdjusted03]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__7663BAE1] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted06]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__7698C50B] DEFAULT ((0)) FOR [BudgetAdjusted04]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__7757DF1A] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted07]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__778CE944] DEFAULT ((0)) FOR [BudgetAdjusted05]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__784C0353] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted08]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__78810D7D] DEFAULT ((0)) FOR [BudgetAdjusted06]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__7940278C] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted09]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__797531B6] DEFAULT ((0)) FOR [BudgetAdjusted07]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__7A344BC5] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted10]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__7A6955EF] DEFAULT ((0)) FOR [BudgetAdjusted08]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__7B286FFE] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted11]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__7B5D7A28] DEFAULT ((0)) FOR [BudgetAdjusted09]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__7C1C9437] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted12]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__7C519E61] DEFAULT ((0)) FOR [BudgetAdjusted10]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__7D45C29A] DEFAULT ((0)) FOR [BudgetAdjusted11]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Budge__7E39E6D3] DEFAULT ((0)) FOR [BudgetAdjusted12]; GO +ALTER TABLE [fp].[GeneralLedger] ADD CONSTRAINT [DF__GeneralLe__Proje__7F2E0B0C] DEFAULT ((0)) FOR [ProjectionAdjusted01]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerAddAccountAdjustment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerAddAccountAdjustment] ( + [RowID] int NOT NULL, + [AdjustmentID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [Comment] nvarchar(1000) NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE NONCLUSTERED INDEX [NCNU_GeneralLedgerAddAccountAdjustment_RowID] ON [fp].[GeneralLedgerAddAccountAdjustment] ([RowID]); +GO +ALTER TABLE [fp].[GeneralLedgerAddAccountAdjustment] ADD CONSTRAINT [DF__GeneralLe__Adjus__7095079B] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[GeneralLedgerAddAccountAdjustment] ADD CONSTRAINT [DF__GeneralLe__Depar__71892BD4] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[GeneralLedgerAddAccountAdjustment] ADD CONSTRAINT [DF__GeneralLe__Accou__727D500D] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[GeneralLedgerAddAccountAdjustment] ADD CONSTRAINT [DF__GeneralLe__Comme__73717446] DEFAULT ('') FOR [Comment]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerAdjustment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerAdjustment] ( + [AdjustmentGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [Value] decimal NOT NULL, + [AdjustmentFilterJSON] nvarchar(max) NOT NULL, + [GroupingHierarchyJSON] nvarchar(max) NOT NULL, + [AdjustedProperty] nvarchar(100) NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [ClassificationGroupID] int NOT NULL, + [ClassificationCategoryID] int NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [LastModifiedDateUtc] datetime NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + [DimensionMemberJson] nvarchar(max) NOT NULL, + [AdjustmentID] int NOT NULL, + [IsErrored] bit NOT NULL, + PRIMARY KEY ([AdjustmentGUID]) +); +GO +ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [FK__GeneralLe__Budge__14EBD720] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Adjus__15DFFB59] DEFAULT (newid()) FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Adjus__16D41F92] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__17C843CB] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Adjus__18BC6804] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Group__19B08C3D] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Adjus__1AA4B076] DEFAULT ('') FOR [AdjustedProperty]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Comme__1B98D4AF] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Autho__1C8CF8E8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Autho__1D811D21] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF_GeneralLedgerAdjustment_ClassificationGroupID] DEFAULT ((0)) FOR [ClassificationGroupID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF_GeneralLedgerAdjustment_ClassificationCategoryID] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__UnitT__2339F677] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF_GeneralLedgerAdjustment_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__IsErr__4CE1B70A] DEFAULT ((0)) FOR [IsErrored]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__LastM__644BFEEB] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__DateC__65402324] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Dimen__65CA3309] DEFAULT ('') FOR [DimensionMemberJson]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__IsRec__661E6D6D] DEFAULT ((0)) FOR [IsRecordDeleted]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF_GeneralLedgerAdjustment_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment] ADD CONSTRAINT [DF__GeneralLe__Group__6F503E1D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerAdjustmentImport ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerAdjustmentImport] ( + [RowID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [Value] decimal NOT NULL, + [Version] timestamp NOT NULL, + [VariabilityID] int NOT NULL, + [EntityID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [AdjustmentID] int NOT NULL, + [OriginalUnitTypeID] tinyint NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_AdjustmentID] ON [fp].[GeneralLedgerAdjustmentImport] ([AdjustmentID]); +GO +ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLe__Varia__05B61736] DEFAULT ((0)) FOR [VariabilityID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLe__Adjus__24A67B22] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLe__Entit__3288BDAD] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLe__Adjus__368E58BB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLedgerAdjImport__Depar__2B6F7FBE] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLedgerAdjImport__AccountID__2D57C830] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLedgerAdjImport__FinancialReportingID__2D57C830] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLedgerAdjImport__Fisca__31285914] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLedgerAdjImport__UnitT__34F8E9F8] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLedgerAdjImport__Fisca__3CCC1A58] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF_INTGeneralLedgerAdjImport_VALUE] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__GeneralLe__IsRec__6806B5DF] DEFAULT ((0)) FOR [IsRecordDeleted]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF_GeneralLedgerAdjustmentImport_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF_GeneralLedgerAdjustmentImport_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerAdjustment_backup ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerAdjustment_backup] ( + [AdjustmentGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [Value] decimal NOT NULL, + [AdjustmentFilterJSON] nvarchar(max) NOT NULL, + [GroupingHierarchyJSON] nvarchar(max) NOT NULL, + [AdjustedProperty] nvarchar(100) NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [LastModifiedDate] datetime NOT NULL, + [DateCreatedUTC] datetime NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AdjustmentID] int NOT NULL, + PRIMARY KEY ([AdjustmentGUID]) +); +GO +ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [FK__GeneralLe__Budge__399E38E2] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF_GeneralLedgerAdjustmentBackup_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Adjus__2D3861FD] DEFAULT (newid()) FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Adjus__2E2C8636] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Value__2F20AA6F] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Adjus__3014CEA8] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Group__3108F2E1] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Adjus__31FD171A] DEFAULT ('') FOR [AdjustedProperty]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Comme__32F13B53] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Autho__33E55F8C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Autho__34D983C5] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__LastM__35CDA7FE] DEFAULT (getdate()) FOR [LastModifiedDate]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__DateC__36C1CC37] DEFAULT (getdate()) FOR [DateCreatedUTC]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__UnitT__37B5F070] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Group__38AA14A9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF__GeneralLe__Adjus__67809EAD] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[GeneralLedgerAdjustment_backup] ADD CONSTRAINT [DF_GeneralLedgerAdjustmentBackup_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerBasisFlexRate ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerBasisFlexRate] ( + [RowID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [FlexRate01] decimal NOT NULL, + [FlexRate02] decimal NOT NULL, + [FlexRate03] decimal NOT NULL, + [FlexRate04] decimal NOT NULL, + [FlexRate05] decimal NOT NULL, + [FlexRate06] decimal NOT NULL, + [FlexRate07] decimal NOT NULL, + [FlexRate08] decimal NOT NULL, + [FlexRate09] decimal NOT NULL, + [FlexRate10] decimal NOT NULL, + [FlexRate11] decimal NOT NULL, + [FlexRate12] decimal NOT NULL, + [BudgetConfigID] smallint NOT NULL, + [AdjustmentID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[GeneralLedgerBasisFlexRate] ([BudgetConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [FiscalYearID], [TimeClassID], [AdjustmentID]); +GO +ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__Entit__40A466A9] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__Depar__41988AE2] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__Accou__428CAF1B] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__Finan__4380D354] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__Fisca__4474F78D] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__TimeC__45691BC6] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__465D3FFF] DEFAULT ((0.0)) FOR [FlexRate01]; GO +ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__47516438] DEFAULT ((0.0)) FOR [FlexRate02]; GO +ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__48458871] DEFAULT ((0.0)) FOR [FlexRate03]; GO +ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__4939ACAA] DEFAULT ((0.0)) FOR [FlexRate04]; GO +ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__4A2DD0E3] DEFAULT ((0.0)) FOR [FlexRate05]; GO +ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__4B21F51C] DEFAULT ((0.0)) FOR [FlexRate06]; GO +ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__4C161955] DEFAULT ((0.0)) FOR [FlexRate07]; GO +ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__4D0A3D8E] DEFAULT ((0.0)) FOR [FlexRate08]; GO +ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__4DFE61C7] DEFAULT ((0.0)) FOR [FlexRate09]; GO +ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__4EF28600] DEFAULT ((0.0)) FOR [FlexRate10]; GO +ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__4FE6AA39] DEFAULT ((0.0)) FOR [FlexRate11]; GO +ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__FlexR__50DACE72] DEFAULT ((0.0)) FOR [FlexRate12]; GO +ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__Budge__51CEF2AB] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[GeneralLedgerBasisFlexRate] ADD CONSTRAINT [DF__GeneralLe__Adjus__52C316E4] DEFAULT ((0)) FOR [AdjustmentID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerChangeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerChangeHistory] ( + [RowID] bigint NOT NULL, + [GeneralLedgerID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [OldValue] decimal NOT NULL, + [NewValue] decimal NOT NULL, + [BudgetConfigID] int NOT NULL, + [DateCreatedUTC] datetime2 NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_GeneralLedgerChangeHistory] ON [fp].[GeneralLedgerChangeHistory] ([GeneralLedgerID]); +CREATE NONCLUSTERED INDEX [IX_GeneralLedgerChangeHistory_AdjustmentGuid] ON [fp].[GeneralLedgerChangeHistory] ([AdjustmentGUID]) INCLUDE ([GeneralLedgerID], [FiscalMonthID], [UnitTypeID], [TimeClassID], [BudgetPhaseID]); +GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [FK_GeneralLedgerChangeHistory_GeneralLedgerID] FOREIGN KEY ([GeneralLedgerID]) REFERENCES [fp].[GeneralLedger] ([GeneralLedgerID]); GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__Gener__06BA1E3B] DEFAULT ((0)) FOR [GeneralLedgerID]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__Adjus__07AE4274] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__Group__08A266AD] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__Adjus__09968AE6] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__Fisca__0A8AAF1F] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__UnitT__0B7ED358] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__TimeC__0C72F791] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__Budge__0D671BCA] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__0E5B4003] DEFAULT ((0)) FOR [OldValue]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__0F4F643C] DEFAULT ((0)) FOR [NewValue]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__Budge__10438875] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory] ADD CONSTRAINT [DF__GeneralLe__DateC__1137ACAE] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerChangeHistory_OLD ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerChangeHistory_OLD] ( + [RowID] bigint NOT NULL, + [GeneralLedgerID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [OldValue] decimal NOT NULL, + [NewValue] decimal NOT NULL, + [BudgetConfigID] int NOT NULL, + [DateCreatedUTC] datetime2 NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__DateC__06B62588] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__Budge__61EEB52D] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__Gener__766E760F] DEFAULT ((0)) FOR [GeneralLedgerID]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__Adjus__77629A48] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__Group__7856BE81] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__Adjus__794AE2BA] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__Fisca__7B332B2C] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__UnitT__7C274F65] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__TimeC__7D1B739E] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__Budge__7E0F97D7] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__OldVa__7F03BC10] DEFAULT ((0)) FOR [OldValue]; GO +ALTER TABLE [fp].[GeneralLedgerChangeHistory_OLD] ADD CONSTRAINT [DF__GeneralLe__NewVa__7FF7E049] DEFAULT ((0)) FOR [NewValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerFixedDetail ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerFixedDetail] ( + [CommentGUID] uniqueidentifier NOT NULL, + [AdjustmentID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [DepartmentID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [AccountID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [DollarsValue] decimal NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [SortOrder] int NOT NULL, + [SpreadID] int NOT NULL, + [IsMarkedForDeletion] bit NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [DateCreatedUTC] datetime NOT NULL, + [SpreadPercentage01] decimal NULL, + [SpreadPercentage02] decimal NULL, + [SpreadPercentage03] decimal NULL, + [SpreadPercentage04] decimal NULL, + [SpreadPercentage05] decimal NULL, + [SpreadPercentage06] decimal NULL, + [SpreadPercentage07] decimal NULL, + [SpreadPercentage08] decimal NULL, + [SpreadPercentage09] decimal NULL, + [SpreadPercentage10] decimal NULL, + [SpreadPercentage11] decimal NULL, + [SpreadPercentage12] decimal NULL, + [TotalImportedValue] decimal NULL, + [CategoryID] int NOT NULL, + [LastModifiedDateUtc] datetime NOT NULL, + [LastModifiedAuthorFullName] nvarchar(260) NOT NULL, + [LastModifiedAuthorGUID] uniqueidentifier NOT NULL, + [IsSetValue] bit NOT NULL, + PRIMARY KEY ([CommentGUID]) +); +GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__0B7BA5FC] DEFAULT ((0)) FOR [SpreadPercentage01]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__0C6FCA35] DEFAULT ((0)) FOR [SpreadPercentage02]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__0D63EE6E] DEFAULT ((0)) FOR [SpreadPercentage03]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__0E5812A7] DEFAULT ((0)) FOR [SpreadPercentage04]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__0F4C36E0] DEFAULT ((0)) FOR [SpreadPercentage05]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__10405B19] DEFAULT ((0)) FOR [SpreadPercentage06]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__11347F52] DEFAULT ((0)) FOR [SpreadPercentage07]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__1228A38B] DEFAULT ((0)) FOR [SpreadPercentage08]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__131CC7C4] DEFAULT ((0)) FOR [SpreadPercentage09]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__1410EBFD] DEFAULT ((0)) FOR [SpreadPercentage10]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__15051036] DEFAULT ((0)) FOR [SpreadPercentage11]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__15F9346F] DEFAULT ((0)) FOR [SpreadPercentage12]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Total__16ED58A8] DEFAULT ((0)) FOR [TotalImportedValue]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF_GeneralLedgerItemizationDetail_CategoryID] DEFAULT ((0)) FOR [CategoryID]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF_GeneralLedgerItemizationDetail_LastModifiedDateUtc] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF_GeneralLedgerItemizationDetail_LastModifiedAuthorFullName] DEFAULT ('') FOR [LastModifiedAuthorFullName]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF_GeneralLedgerItemizationDetail_LastModifiedAuthorGUID] DEFAULT (newid()) FOR [LastModifiedAuthorGUID]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Adjus__4182B0F2] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Budge__4276D52B] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Depar__436AF964] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Finan__445F1D9D] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Accou__455341D6] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__TimeC__4647660F] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Dolla__473B8A48] DEFAULT ((0)) FOR [DollarsValue]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Comme__482FAE81] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__SortO__4923D2BA] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Sprea__4A17F6F3] DEFAULT ((0)) FOR [SpreadID]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__IsDel__4B0C1B2C] DEFAULT ((0)) FOR [IsMarkedForDeletion]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__Autho__4CF4639E] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__DateC__4DE887D7] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF_GeneralLedgerI_Auth] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF_GeneralLedgerI_Comm] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CommentGUID]; GO +ALTER TABLE [fp].[GeneralLedgerFixedDetail] ADD CONSTRAINT [DF__GeneralLe__IsSet__6C87ACF1] DEFAULT ((0)) FOR [IsSetValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerHistory] ( + [RowID] int NOT NULL, + [GeneralLedgerID] int NOT NULL, + [PriorYearActualValue01] decimal NOT NULL, + [PriorYearActualValue02] decimal NOT NULL, + [PriorYearActualValue03] decimal NOT NULL, + [PriorYearActualValue04] decimal NOT NULL, + [PriorYearActualValue05] decimal NOT NULL, + [PriorYearActualValue06] decimal NOT NULL, + [PriorYearActualValue07] decimal NOT NULL, + [PriorYearActualValue08] decimal NOT NULL, + [PriorYearActualValue09] decimal NOT NULL, + [PriorYearActualValue10] decimal NOT NULL, + [PriorYearActualValue11] decimal NOT NULL, + [PriorYearActualValue12] decimal NOT NULL, + [ActualYTDValue01] decimal NOT NULL, + [ActualYTDValue02] decimal NOT NULL, + [ActualYTDValue03] decimal NOT NULL, + [ActualYTDValue04] decimal NOT NULL, + [ActualYTDValue05] decimal NOT NULL, + [ActualYTDValue06] decimal NOT NULL, + [ActualYTDValue07] decimal NOT NULL, + [ActualYTDValue08] decimal NOT NULL, + [ActualYTDValue09] decimal NOT NULL, + [ActualYTDValue10] decimal NOT NULL, + [ActualYTDValue11] decimal NOT NULL, + [ActualYTDValue12] decimal NOT NULL, + [CurrentYearBudget01] decimal NOT NULL, + [CurrentYearBudget02] decimal NOT NULL, + [CurrentYearBudget03] decimal NOT NULL, + [CurrentYearBudget04] decimal NOT NULL, + [CurrentYearBudget05] decimal NOT NULL, + [CurrentYearBudget06] decimal NOT NULL, + [CurrentYearBudget07] decimal NOT NULL, + [CurrentYearBudget08] decimal NOT NULL, + [CurrentYearBudget09] decimal NOT NULL, + [CurrentYearBudget10] decimal NOT NULL, + [CurrentYearBudget11] decimal NOT NULL, + [CurrentYearBudget12] decimal NOT NULL, + [PriorYearActualValueTotal] decimal NOT NULL, + [ActualYTDValueTotal] decimal NOT NULL, + [CurrentYearBudgetTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_GeneralLedgerHistory] ON [fp].[GeneralLedgerHistory] ([GeneralLedgerID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[GeneralLedgerHistory] ([GeneralLedgerID]); +GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [FK_GeneralLedgerHistory_GeneralLedgerID] FOREIGN KEY ([GeneralLedgerID]) REFERENCES [fp].[GeneralLedger] ([GeneralLedgerID]); GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__2612CE03] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__2706F23C] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__27FB1675] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__28EF3AAE] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__29E35EE7] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__2AD78320] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__2BCBA759] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__2CBFCB92] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__2DB3EFCB] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__2EA81404] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__2F9C383D] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Prior__30905C76] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__318480AF] DEFAULT ((0)) FOR [ActualYTDValue01]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__3278A4E8] DEFAULT ((0)) FOR [ActualYTDValue02]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__336CC921] DEFAULT ((0)) FOR [ActualYTDValue03]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__3460ED5A] DEFAULT ((0)) FOR [ActualYTDValue04]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__35551193] DEFAULT ((0)) FOR [ActualYTDValue05]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__364935CC] DEFAULT ((0)) FOR [ActualYTDValue06]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__373D5A05] DEFAULT ((0)) FOR [ActualYTDValue07]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__38317E3E] DEFAULT ((0)) FOR [ActualYTDValue08]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__3925A277] DEFAULT ((0)) FOR [ActualYTDValue09]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__3A19C6B0] DEFAULT ((0)) FOR [ActualYTDValue10]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__3B0DEAE9] DEFAULT ((0)) FOR [ActualYTDValue11]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Actua__3C020F22] DEFAULT ((0)) FOR [ActualYTDValue12]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__3CF6335B] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__3DEA5794] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__3EDE7BCD] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__3FD2A006] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__40C6C43F] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__41BAE878] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__42AF0CB1] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__43A330EA] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__44975523] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__458B795C] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__467F9D95] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO +ALTER TABLE [fp].[GeneralLedgerHistory] ADD CONSTRAINT [DF__GeneralLe__Curre__4773C1CE] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerInitialPlanConfigDetail ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ( + [RowID] int NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [BudgetConfigID] smallint NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [VariabilityID] int NOT NULL, + [APEModelSectionID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [ProjectionMethodID] int NOT NULL, + [TrailingMonths] tinyint NOT NULL, + [VersionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [FK__GeneralLe__Budge__34EBC896] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [FK__GeneralLe__Versi__6F6D6FE6] FOREIGN KEY ([VersionID]) REFERENCES [fp].[InitialPlanRuleVersion] ([VersionID]); GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__Budge__2A6E3A23] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__Budge__2B625E5C] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__Entit__2C568295] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__Depar__2D4AA6CE] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__Accou__2E3ECB07] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__Finan__2F32EF40] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__Varia__30271379] DEFAULT ((0)) FOR [VariabilityID]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__APEMo__311B37B2] DEFAULT ((0)) FOR [APEModelSectionID]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__TimeC__320F5BEB] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__Proje__33038024] DEFAULT ((0)) FOR [ProjectionMethodID]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__Trail__33F7A45D] DEFAULT ((0)) FOR [TrailingMonths]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetail] ADD CONSTRAINT [DF__GeneralLe__Versi__6E794BAD] DEFAULT ((0)) FOR [VersionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerInitialPlanConfigDetailHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ( + [RowID] int NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [BudgetConfigID] smallint NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [VariabilityID] int NOT NULL, + [APEModelSectionID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [ProjectionMethodID] int NOT NULL, + [TrailingMonths] tinyint NOT NULL, + [VersionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [FK__GeneralLe__Budge__7DBB8F3D] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [FK__GeneralLe__Versi__7EAFB376] FOREIGN KEY ([VersionID]) REFERENCES [fp].[InitialPlanRuleVersion] ([VersionID]); GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__Budge__7249DC91] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__Budge__733E00CA] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__Entit__74322503] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__Depar__7526493C] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__Accou__761A6D75] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__Finan__770E91AE] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__Varia__7802B5E7] DEFAULT ((0)) FOR [VariabilityID]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__APEMo__78F6DA20] DEFAULT ((0)) FOR [APEModelSectionID]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__TimeC__79EAFE59] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__Proje__7ADF2292] DEFAULT ((0)) FOR [ProjectionMethodID]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__Trail__7BD346CB] DEFAULT ((0)) FOR [TrailingMonths]; GO +ALTER TABLE [fp].[GeneralLedgerInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__GeneralLe__Versi__7CC76B04] DEFAULT ((0)) FOR [VersionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerItemizationDetailLink ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerItemizationDetailLink] ( + [OriginalAdjustmentCommentGUID] uniqueidentifier NOT NULL, + [InverseAdjustmentCommentGUID] uniqueidentifier NOT NULL +); +GO +ALTER TABLE [fp].[GeneralLedgerItemizationDetailLink] ADD CONSTRAINT [FK_InverseAdj_CommentGUID] FOREIGN KEY ([InverseAdjustmentCommentGUID]) REFERENCES [fp].[GeneralLedgerFixedDetail] ([CommentGUID]); GO +ALTER TABLE [fp].[GeneralLedgerItemizationDetailLink] ADD CONSTRAINT [FK_OriginalAdj_CommentGUID] FOREIGN KEY ([OriginalAdjustmentCommentGUID]) REFERENCES [fp].[GeneralLedgerFixedDetail] ([CommentGUID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerItemizationReportData ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerItemizationReportData] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [AccountID] int NOT NULL, + [TimeClassID] int NOT NULL, + [ItemizationDataTypeID] int NOT NULL, + [Month01] decimal NOT NULL, + [Month02] decimal NOT NULL, + [Month03] decimal NOT NULL, + [Month04] decimal NOT NULL, + [Month05] decimal NOT NULL, + [Month06] decimal NOT NULL, + [Month07] decimal NOT NULL, + [Month08] decimal NOT NULL, + [Month09] decimal NOT NULL, + [Month10] decimal NOT NULL, + [Month11] decimal NOT NULL, + [Month12] decimal NOT NULL, + [TotalValue] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [CORE_Unique_GLItemizationReportData] ON [fp].[GeneralLedgerItemizationReportData] ([BudgetConfigID], [EntityID], [DepartmentID], [FinancialReportingID], [AccountID], [ItemizationDataTypeID], [TimeClassID]); +GO +ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Budge__557F87FE] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Entit__5673AC37] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Depar__5767D070] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Finan__585BF4A9] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Accou__595018E2] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__TimeC__5A443D1B] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Itemi__5B386154] DEFAULT ((0)) FOR [ItemizationDataTypeID]; GO +ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__5C2C858D] DEFAULT ((0)) FOR [Month01]; GO +ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__5D20A9C6] DEFAULT ((0)) FOR [Month02]; GO +ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__5E14CDFF] DEFAULT ((0)) FOR [Month03]; GO +ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__5F08F238] DEFAULT ((0)) FOR [Month04]; GO +ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__5FFD1671] DEFAULT ((0)) FOR [Month05]; GO +ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__60F13AAA] DEFAULT ((0)) FOR [Month06]; GO +ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__61E55EE3] DEFAULT ((0)) FOR [Month07]; GO +ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__62D9831C] DEFAULT ((0)) FOR [Month08]; GO +ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__63CDA755] DEFAULT ((0)) FOR [Month09]; GO +ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__64C1CB8E] DEFAULT ((0)) FOR [Month10]; GO +ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__65B5EFC7] DEFAULT ((0)) FOR [Month11]; GO +ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Month__66AA1400] DEFAULT ((0)) FOR [Month12]; GO +ALTER TABLE [fp].[GeneralLedgerItemizationReportData] ADD CONSTRAINT [DF__GeneralLe__Total__679E3839] DEFAULT ((0)) FOR [TotalValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerManagerAdjustmentComment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ( + [CommentGUID] uniqueidentifier NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [InitialValue] decimal NOT NULL, + [DeltaValue] decimal NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [IsRollupLevel] int NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + [DateModifiedUtc] datetime NOT NULL, + PRIMARY KEY ([CommentGUID]) +); +GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__IsRol__2F8D5292] DEFAULT ((0)) FOR [IsRollupLevel]; GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [Default_GLManagerAdjComment_FinancialReportingID] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__DateC__3388CBFF] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__DateM__347CF038] DEFAULT (getutcdate()) FOR [DateModifiedUtc]; GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__Comme__57D27E51] DEFAULT (newid()) FOR [CommentGUID]; GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__Depar__5AAEEAFC] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__Accou__5BA30F35] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__Fisca__5D8B57A7] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__Comme__5E7F7BE0] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__Initi__5F73A019] DEFAULT ((0)) FOR [InitialValue]; GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__Updat__6067C452] DEFAULT ((0)) FOR [DeltaValue]; GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__Autho__62500CC4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentComment] ADD CONSTRAINT [DF__GeneralLe__Autho__634430FD] DEFAULT ('') FOR [AuthorFullName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerManagerAdjustmentData ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerManagerAdjustmentData] ( + [RowID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [EntityID] int NOT NULL, + [Value] decimal NULL, + [TimeClassID] tinyint NOT NULL +); + +CREATE NONCLUSTERED INDEX [NCNU_AdjustmentGUID] ON [fp].[GeneralLedgerManagerAdjustmentData] ([AdjustmentGUID]) INCLUDE ([DepartmentID], [AccountID], [FinancialReportingID], [FiscalYearID], [UnitTypeID], [FiscalMonthID], [EntityID], [Value], [TimeClassID]); +GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentData] ADD CONSTRAINT [Default_GLManagerAdj_TC] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentData] ADD CONSTRAINT [DF__GeneralLe__Adjus__394DF731] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentData] ADD CONSTRAINT [DF__GeneralLe__Depar__3A421B6A] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentData] ADD CONSTRAINT [DF__GeneralLe__Accou__3B363FA3] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentData] ADD CONSTRAINT [DF__GeneralLe__Finan__3C2A63DC] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentData] ADD CONSTRAINT [DF__GeneralLe__Fisca__3D1E8815] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentData] ADD CONSTRAINT [DF__GeneralLe__UnitT__3E12AC4E] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentData] ADD CONSTRAINT [DF__GeneralLe__Fisca__3F06D087] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentData] ADD CONSTRAINT [DF__GeneralLe__Entit__40EF18F9] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[GeneralLedgerManagerAdjustmentData] ADD CONSTRAINT [DF__GeneralLe__Value__41E33D32] DEFAULT ((0)) FOR [Value]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerMyBudgetAdjustment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ( + [RowID] int NOT NULL, + [AdjustmentID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [AccountID] int NOT NULL, + [VariabilityID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Value01] decimal NOT NULL, + [Value02] decimal NOT NULL, + [Value03] decimal NOT NULL, + [Value04] decimal NOT NULL, + [Value05] decimal NOT NULL, + [Value06] decimal NOT NULL, + [Value07] decimal NOT NULL, + [Value08] decimal NOT NULL, + [Value09] decimal NOT NULL, + [Value10] decimal NOT NULL, + [Value11] decimal NOT NULL, + [Value12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [CLU_GLAdjustmentItemization] ON [fp].[GeneralLedgerMyBudgetAdjustment] ([BudgetConfigID], [DepartmentID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_ClusteredUnique] ON [fp].[GeneralLedgerMyBudgetAdjustment] ([BudgetConfigID], [AdjustmentID], [EntityID], [DepartmentID], [FinancialReportingID], [AccountID], [VariabilityID], [UnitTypeID], [TimeClassID]); +GO +ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Adjus__07C023B1] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Budge__08B447EA] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Entit__09A86C23] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Depar__0A9C905C] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Finan__0B90B495] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Accou__0C84D8CE] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Varia__0D78FD07] DEFAULT ((0)) FOR [VariabilityID]; GO +ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__UnitT__0E6D2140] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__TimeC__0F614579] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__105569B2] DEFAULT ((0)) FOR [Value01]; GO +ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__11498DEB] DEFAULT ((0)) FOR [Value02]; GO +ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__123DB224] DEFAULT ((0)) FOR [Value03]; GO +ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__1331D65D] DEFAULT ((0)) FOR [Value04]; GO +ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__1425FA96] DEFAULT ((0)) FOR [Value05]; GO +ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__151A1ECF] DEFAULT ((0)) FOR [Value06]; GO +ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__160E4308] DEFAULT ((0)) FOR [Value07]; GO +ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__17026741] DEFAULT ((0)) FOR [Value08]; GO +ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__17F68B7A] DEFAULT ((0)) FOR [Value09]; GO +ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__18EAAFB3] DEFAULT ((0)) FOR [Value10]; GO +ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__19DED3EC] DEFAULT ((0)) FOR [Value11]; GO +ALTER TABLE [fp].[GeneralLedgerMyBudgetAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__1AD2F825] DEFAULT ((0)) FOR [Value12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerReimbursementExcludedDepartments ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerReimbursementExcludedDepartments] ( + [RowID] int NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [EntityID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[GeneralLedgerReimbursementExcludedDepartments] ADD CONSTRAINT [FK__GeneralLe__Budge__56B3D523] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[GeneralLedgerReimbursementExcludedDepartments] ADD CONSTRAINT [DF__GeneralLe__Budge__53D76878] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[GeneralLedgerReimbursementExcludedDepartments] ADD CONSTRAINT [DF__GeneralLe__Depar__54CB8CB1] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[GeneralLedgerReimbursementExcludedDepartments] ADD CONSTRAINT [DF__GeneralLe__Entit__55BFB0EA] DEFAULT ((0)) FOR [EntityID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerSnapshot ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerSnapshot] ( + [GeneralLedgerID] int NOT NULL, + [SnapshotID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [VariabilityID] int NOT NULL, + [APEModelSectionID] tinyint NOT NULL, + [AddDate] datetime NOT NULL, + [IsNew] bit NOT NULL, + [FlexingTypeID] smallint NOT NULL, + [ChangeHistoryGroupingGUID] uniqueidentifier NOT NULL, + [BudgetLockType] tinyint NOT NULL, + [BudgetLockFlag] tinyint NOT NULL, + [TargetLockType] tinyint NOT NULL, + [TargetLockFlag] tinyint NOT NULL, + [ProjectionLockType] tinyint NOT NULL, + [ProjectionLockFlag] tinyint NOT NULL, + [SampledBudget01] decimal NOT NULL, + [SampledBudget02] decimal NOT NULL, + [SampledBudget03] decimal NOT NULL, + [SampledBudget04] decimal NOT NULL, + [SampledBudget05] decimal NOT NULL, + [SampledBudget06] decimal NOT NULL, + [SampledBudget07] decimal NOT NULL, + [SampledBudget08] decimal NOT NULL, + [SampledBudget09] decimal NOT NULL, + [SampledBudget10] decimal NOT NULL, + [SampledBudget11] decimal NOT NULL, + [SampledBudget12] decimal NOT NULL, + [SampledProjection01] decimal NOT NULL, + [SampledProjection02] decimal NOT NULL, + [SampledProjection03] decimal NOT NULL, + [SampledProjection04] decimal NOT NULL, + [SampledProjection05] decimal NOT NULL, + [SampledProjection06] decimal NOT NULL, + [SampledProjection07] decimal NOT NULL, + [SampledProjection08] decimal NOT NULL, + [SampledProjection09] decimal NOT NULL, + [SampledProjection10] decimal NOT NULL, + [SampledProjection11] decimal NOT NULL, + [SampledProjection12] decimal NOT NULL, + [InitialBudget01] decimal NOT NULL, + [InitialBudget02] decimal NOT NULL, + [InitialBudget03] decimal NOT NULL, + [InitialBudget04] decimal NOT NULL, + [InitialBudget05] decimal NOT NULL, + [InitialBudget06] decimal NOT NULL, + [InitialBudget07] decimal NOT NULL, + [InitialBudget08] decimal NOT NULL, + [InitialBudget09] decimal NOT NULL, + [InitialBudget10] decimal NOT NULL, + [InitialBudget11] decimal NOT NULL, + [InitialBudget12] decimal NOT NULL, + [InitialProjection01] decimal NOT NULL, + [InitialProjection02] decimal NOT NULL, + [InitialProjection03] decimal NOT NULL, + [InitialProjection04] decimal NOT NULL, + [InitialProjection05] decimal NOT NULL, + [InitialProjection06] decimal NOT NULL, + [InitialProjection07] decimal NOT NULL, + [InitialProjection08] decimal NOT NULL, + [InitialProjection09] decimal NOT NULL, + [InitialProjection10] decimal NOT NULL, + [InitialProjection11] decimal NOT NULL, + [InitialProjection12] decimal NOT NULL, + [TargetAdjusted01] decimal NOT NULL, + [TargetAdjusted02] decimal NOT NULL, + [TargetAdjusted03] decimal NOT NULL, + [TargetAdjusted04] decimal NOT NULL, + [TargetAdjusted05] decimal NOT NULL, + [TargetAdjusted06] decimal NOT NULL, + [TargetAdjusted07] decimal NOT NULL, + [TargetAdjusted08] decimal NOT NULL, + [TargetAdjusted09] decimal NOT NULL, + [TargetAdjusted10] decimal NOT NULL, + [TargetAdjusted11] decimal NOT NULL, + [TargetAdjusted12] decimal NOT NULL, + [BudgetAdjusted01] decimal NOT NULL, + [BudgetAdjusted02] decimal NOT NULL, + [BudgetAdjusted03] decimal NOT NULL, + [BudgetAdjusted04] decimal NOT NULL, + [BudgetAdjusted05] decimal NOT NULL, + [BudgetAdjusted06] decimal NOT NULL, + [BudgetAdjusted07] decimal NOT NULL, + [BudgetAdjusted08] decimal NOT NULL, + [BudgetAdjusted09] decimal NOT NULL, + [BudgetAdjusted10] decimal NOT NULL, + [BudgetAdjusted11] decimal NOT NULL, + [BudgetAdjusted12] decimal NOT NULL, + [ProjectionAdjusted01] decimal NOT NULL, + [ProjectionAdjusted02] decimal NOT NULL, + [ProjectionAdjusted03] decimal NOT NULL, + [ProjectionAdjusted04] decimal NOT NULL, + [ProjectionAdjusted05] decimal NOT NULL, + [ProjectionAdjusted06] decimal NOT NULL, + [ProjectionAdjusted07] decimal NOT NULL, + [ProjectionAdjusted08] decimal NOT NULL, + [ProjectionAdjusted09] decimal NOT NULL, + [ProjectionAdjusted10] decimal NOT NULL, + [ProjectionAdjusted11] decimal NOT NULL, + [ProjectionAdjusted12] decimal NOT NULL, + [InitialBudgetDollarsPerUOS01] decimal NOT NULL, + [InitialBudgetDollarsPerUOS02] decimal NOT NULL, + [InitialBudgetDollarsPerUOS03] decimal NOT NULL, + [InitialBudgetDollarsPerUOS04] decimal NOT NULL, + [InitialBudgetDollarsPerUOS05] decimal NOT NULL, + [InitialBudgetDollarsPerUOS06] decimal NOT NULL, + [InitialBudgetDollarsPerUOS07] decimal NOT NULL, + [InitialBudgetDollarsPerUOS08] decimal NOT NULL, + [InitialBudgetDollarsPerUOS09] decimal NOT NULL, + [InitialBudgetDollarsPerUOS10] decimal NOT NULL, + [InitialBudgetDollarsPerUOS11] decimal NOT NULL, + [InitialBudgetDollarsPerUOS12] decimal NOT NULL, + [InitialProjectionDollarsPerUOS01] decimal NOT NULL, + [InitialProjectionDollarsPerUOS02] decimal NOT NULL, + [InitialProjectionDollarsPerUOS03] decimal NOT NULL, + [InitialProjectionDollarsPerUOS04] decimal NOT NULL, + [InitialProjectionDollarsPerUOS05] decimal NOT NULL, + [InitialProjectionDollarsPerUOS06] decimal NOT NULL, + [InitialProjectionDollarsPerUOS07] decimal NOT NULL, + [InitialProjectionDollarsPerUOS08] decimal NOT NULL, + [InitialProjectionDollarsPerUOS09] decimal NOT NULL, + [InitialProjectionDollarsPerUOS10] decimal NOT NULL, + [InitialProjectionDollarsPerUOS11] decimal NOT NULL, + [InitialProjectionDollarsPerUOS12] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted01] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted02] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted03] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted04] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted05] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted06] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted07] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted08] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted09] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted10] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted11] decimal NOT NULL, + [TargetDollarsPerUOSAdjusted12] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted01] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted02] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted03] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted04] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted05] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted06] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted07] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted08] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted09] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted10] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted11] decimal NOT NULL, + [BudgetDollarsPerUOSAdjusted12] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted01] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted02] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted03] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted04] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted05] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted06] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted07] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted08] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted09] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted10] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted11] decimal NOT NULL, + [ProjectionDollarsPerUOSAdjusted12] decimal NOT NULL, + [InitialBudgetPercentOfCharge01] decimal NOT NULL, + [InitialBudgetPercentOfCharge02] decimal NOT NULL, + [InitialBudgetPercentOfCharge03] decimal NOT NULL, + [InitialBudgetPercentOfCharge04] decimal NOT NULL, + [InitialBudgetPercentOfCharge05] decimal NOT NULL, + [InitialBudgetPercentOfCharge06] decimal NOT NULL, + [InitialBudgetPercentOfCharge07] decimal NOT NULL, + [InitialBudgetPercentOfCharge08] decimal NOT NULL, + [InitialBudgetPercentOfCharge09] decimal NOT NULL, + [InitialBudgetPercentOfCharge10] decimal NOT NULL, + [InitialBudgetPercentOfCharge11] decimal NOT NULL, + [InitialBudgetPercentOfCharge12] decimal NOT NULL, + [InitialProjectionPercentOfCharge01] decimal NOT NULL, + [InitialProjectionPercentOfCharge02] decimal NOT NULL, + [InitialProjectionPercentOfCharge03] decimal NOT NULL, + [InitialProjectionPercentOfCharge04] decimal NOT NULL, + [InitialProjectionPercentOfCharge05] decimal NOT NULL, + [InitialProjectionPercentOfCharge06] decimal NOT NULL, + [InitialProjectionPercentOfCharge07] decimal NOT NULL, + [InitialProjectionPercentOfCharge08] decimal NOT NULL, + [InitialProjectionPercentOfCharge09] decimal NOT NULL, + [InitialProjectionPercentOfCharge10] decimal NOT NULL, + [InitialProjectionPercentOfCharge11] decimal NOT NULL, + [InitialProjectionPercentOfCharge12] decimal NOT NULL, + [TargetPercentOfChargeAdjusted01] decimal NOT NULL, + [TargetPercentOfChargeAdjusted02] decimal NOT NULL, + [TargetPercentOfChargeAdjusted03] decimal NOT NULL, + [TargetPercentOfChargeAdjusted04] decimal NOT NULL, + [TargetPercentOfChargeAdjusted05] decimal NOT NULL, + [TargetPercentOfChargeAdjusted06] decimal NOT NULL, + [TargetPercentOfChargeAdjusted07] decimal NOT NULL, + [TargetPercentOfChargeAdjusted08] decimal NOT NULL, + [TargetPercentOfChargeAdjusted09] decimal NOT NULL, + [TargetPercentOfChargeAdjusted10] decimal NOT NULL, + [TargetPercentOfChargeAdjusted11] decimal NOT NULL, + [TargetPercentOfChargeAdjusted12] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted01] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted02] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted03] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted04] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted05] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted06] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted07] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted08] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted09] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted10] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted11] decimal NOT NULL, + [BudgetPercentOfChargeAdjusted12] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted01] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted02] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted03] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted04] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted05] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted06] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted07] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted08] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted09] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted10] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted11] decimal NOT NULL, + [ProjectionPercentOfChargeAdjusted12] decimal NOT NULL, + [TargetPercentAdjustmentFactor01] decimal NOT NULL, + [TargetPercentAdjustmentFactor02] decimal NOT NULL, + [TargetPercentAdjustmentFactor03] decimal NOT NULL, + [TargetPercentAdjustmentFactor04] decimal NOT NULL, + [TargetPercentAdjustmentFactor05] decimal NOT NULL, + [TargetPercentAdjustmentFactor06] decimal NOT NULL, + [TargetPercentAdjustmentFactor07] decimal NOT NULL, + [TargetPercentAdjustmentFactor08] decimal NOT NULL, + [TargetPercentAdjustmentFactor09] decimal NOT NULL, + [TargetPercentAdjustmentFactor10] decimal NOT NULL, + [TargetPercentAdjustmentFactor11] decimal NOT NULL, + [TargetPercentAdjustmentFactor12] decimal NOT NULL, + [BudgetPercentAdjustmentFactor01] decimal NOT NULL, + [BudgetPercentAdjustmentFactor02] decimal NOT NULL, + [BudgetPercentAdjustmentFactor03] decimal NOT NULL, + [BudgetPercentAdjustmentFactor04] decimal NOT NULL, + [BudgetPercentAdjustmentFactor05] decimal NOT NULL, + [BudgetPercentAdjustmentFactor06] decimal NOT NULL, + [BudgetPercentAdjustmentFactor07] decimal NOT NULL, + [BudgetPercentAdjustmentFactor08] decimal NOT NULL, + [BudgetPercentAdjustmentFactor09] decimal NOT NULL, + [BudgetPercentAdjustmentFactor10] decimal NOT NULL, + [BudgetPercentAdjustmentFactor11] decimal NOT NULL, + [BudgetPercentAdjustmentFactor12] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor01] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor02] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor03] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor04] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor05] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor06] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor07] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor08] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor09] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor10] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor11] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor12] decimal NOT NULL, + PRIMARY KEY ([GeneralLedgerID], [BudgetConfigID], [SnapshotID]) +); +GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__0097625B] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted05]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__00CC6C85] DEFAULT ((0)) FOR [BudgetAdjusted03]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__018B8694] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted06]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__01C090BE] DEFAULT ((0)) FOR [BudgetAdjusted04]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__027FAACD] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted07]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__02B4B4F7] DEFAULT ((0)) FOR [BudgetAdjusted05]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__0373CF06] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted08]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__03A8D930] DEFAULT ((0)) FOR [BudgetAdjusted06]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__0467F33F] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted09]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__049CFD69] DEFAULT ((0)) FOR [BudgetAdjusted07]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__055C1778] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted10]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__059121A2] DEFAULT ((0)) FOR [BudgetAdjusted08]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__06503BB1] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted11]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__068545DB] DEFAULT ((0)) FOR [BudgetAdjusted09]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__07445FEA] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted12]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__07796A14] DEFAULT ((0)) FOR [BudgetAdjusted10]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__08388423] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__086D8E4D] DEFAULT ((0)) FOR [BudgetAdjusted11]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__092CA85C] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__0961B286] DEFAULT ((0)) FOR [BudgetAdjusted12]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__0A20CC95] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__0A55D6BF] DEFAULT ((0)) FOR [ProjectionAdjusted01]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__0B14F0CE] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__0B49FAF8] DEFAULT ((0)) FOR [ProjectionAdjusted02]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__0C091507] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__0C3E1F31] DEFAULT ((0)) FOR [ProjectionAdjusted03]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__0CFD3940] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__0D32436A] DEFAULT ((0)) FOR [ProjectionAdjusted04]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__0DF15D79] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__0E2667A3] DEFAULT ((0)) FOR [ProjectionAdjusted05]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__0EE581B2] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor08]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__0F1A8BDC] DEFAULT ((0)) FOR [ProjectionAdjusted06]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__0FD9A5EB] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__100EB015] DEFAULT ((0)) FOR [ProjectionAdjusted07]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__10CDCA24] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__1102D44E] DEFAULT ((0)) FOR [ProjectionAdjusted08]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__11C1EE5D] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__11F6F887] DEFAULT ((0)) FOR [ProjectionAdjusted09]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__12B61296] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor12]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__12EB1CC0] DEFAULT ((0)) FOR [ProjectionAdjusted10]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__13AA36CF] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__13DF40F9] DEFAULT ((0)) FOR [ProjectionAdjusted11]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__149E5B08] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__14D36532] DEFAULT ((0)) FOR [ProjectionAdjusted12]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__15927F41] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__15C7896B] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS01]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__1686A37A] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__16BBADA4] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS02]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__177AC7B3] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__17AFD1DD] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS03]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__186EEBEC] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__18A3F616] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS04]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__19631025] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__19981A4F] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS05]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__1A57345E] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor08]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__1A8C3E88] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS06]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__1B4B5897] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__1B8062C1] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS07]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__1C3F7CD0] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__1C7486FA] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS08]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__1D33A109] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__1D68AB33] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS09]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__1E27C542] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor12]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__1E5CCF6C] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS10]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__1F1BE97B] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__1F50F3A5] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS11]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__20100DB4] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__204517DE] DEFAULT ((0)) FOR [InitialBudgetDollarsPerUOS12]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__210431ED] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__21393C17] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS01]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__21F85626] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__222D6050] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS02]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__22EC7A5F] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__23218489] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS03]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__23E09E98] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__2415A8C2] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS04]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__24D4C2D1] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__2509CCFB] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS05]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__25C8E70A] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor08]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__25FDF134] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS06]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__26BD0B43] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__26F2156D] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS07]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__27B12F7C] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__27E639A6] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS08]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__28A553B5] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__28DA5DDF] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS09]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__299977EE] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor12]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__29CE8218] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS10]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__2AC2A651] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS11]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__2BB6CA8A] DEFAULT ((0)) FOR [InitialProjectionDollarsPerUOS12]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__2CAAEEC3] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted01]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__2D9F12FC] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted02]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__2E933735] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted03]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__2F875B6E] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted04]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__307B7FA7] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted05]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__316FA3E0] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted06]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__3263C819] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted07]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Gener__3298D243] DEFAULT ((0)) FOR [GeneralLedgerID]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__3357EC52] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted08]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Snaps__338CF67C] DEFAULT ((0)) FOR [SnapshotID]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__344C108B] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted09]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__34811AB5] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__354034C4] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted10]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Entit__35753EEE] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__363458FD] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted11]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Entit__36696327] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__37287D36] DEFAULT ((0)) FOR [TargetDollarsPerUOSAdjusted12]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Depar__375D8760] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__381CA16F] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted01]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Accou__3851AB99] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__3910C5A8] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted02]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Finan__3945CFD2] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__3A04E9E1] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted03]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Varia__3A39F40B] DEFAULT ((0)) FOR [VariabilityID]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__3AF90E1A] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted04]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__APEMo__3B2E1844] DEFAULT ((0)) FOR [APEModelSectionID]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__3BED3253] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted05]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__AddDa__3C223C7D] DEFAULT ('1900-01-01') FOR [AddDate]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__3CE1568C] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted06]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__IsNew__3D1660B6] DEFAULT ((0)) FOR [IsNew]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__3DD57AC5] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted07]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Flexi__3E0A84EF] DEFAULT ((0)) FOR [FlexingTypeID]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__3EC99EFE] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted08]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Chang__3EFEA928] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ChangeHistoryGroupingGUID]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__3FBDC337] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted09]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__3FF2CD61] DEFAULT ((0)) FOR [BudgetLockType]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__40B1E770] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted10]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__40E6F19A] DEFAULT ((0)) FOR [BudgetLockFlag]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__41A60BA9] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted11]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__41DB15D3] DEFAULT ((0)) FOR [TargetLockType]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__429A2FE2] DEFAULT ((0)) FOR [BudgetDollarsPerUOSAdjusted12]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__42CF3A0C] DEFAULT ((0)) FOR [TargetLockFlag]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__438E541B] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted01]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__43C35E45] DEFAULT ((0)) FOR [ProjectionLockType]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__44827854] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted02]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__44B7827E] DEFAULT ((0)) FOR [ProjectionLockFlag]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__45769C8D] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted03]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__45ABA6B7] DEFAULT ((0)) FOR [SampledBudget01]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__466AC0C6] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted04]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__469FCAF0] DEFAULT ((0)) FOR [SampledBudget02]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__475EE4FF] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted05]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__4793EF29] DEFAULT ((0)) FOR [SampledBudget03]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__48530938] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted06]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__48881362] DEFAULT ((0)) FOR [SampledBudget04]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__49472D71] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted07]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__497C379B] DEFAULT ((0)) FOR [SampledBudget05]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__4A3B51AA] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted08]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__4A705BD4] DEFAULT ((0)) FOR [SampledBudget06]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__4B2F75E3] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted09]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__4B64800D] DEFAULT ((0)) FOR [SampledBudget07]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__4C239A1C] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted10]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__4C58A446] DEFAULT ((0)) FOR [SampledBudget08]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__4D17BE55] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted11]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__4D4CC87F] DEFAULT ((0)) FOR [SampledBudget09]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__4E0BE28E] DEFAULT ((0)) FOR [ProjectionDollarsPerUOSAdjusted12]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__4E40ECB8] DEFAULT ((0)) FOR [SampledBudget10]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__4F0006C7] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge01]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__4F3510F1] DEFAULT ((0)) FOR [SampledBudget11]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__4FF42B00] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge02]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__5029352A] DEFAULT ((0)) FOR [SampledBudget12]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__50E84F39] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge03]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__511D5963] DEFAULT ((0)) FOR [SampledProjection01]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__51DC7372] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge04]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__52117D9C] DEFAULT ((0)) FOR [SampledProjection02]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__52D097AB] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge05]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__5305A1D5] DEFAULT ((0)) FOR [SampledProjection03]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__53C4BBE4] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge06]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__53F9C60E] DEFAULT ((0)) FOR [SampledProjection04]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__54B8E01D] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge07]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__54EDEA47] DEFAULT ((0)) FOR [SampledProjection05]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__55AD0456] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge08]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__55E20E80] DEFAULT ((0)) FOR [SampledProjection06]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__56A1288F] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge09]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__56D632B9] DEFAULT ((0)) FOR [SampledProjection07]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__57954CC8] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge10]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__57CA56F2] DEFAULT ((0)) FOR [SampledProjection08]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__58897101] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge11]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__58BE7B2B] DEFAULT ((0)) FOR [SampledProjection09]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__597D953A] DEFAULT ((0)) FOR [InitialBudgetPercentOfCharge12]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__59B29F64] DEFAULT ((0)) FOR [SampledProjection10]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__5A71B973] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge01]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__5AA6C39D] DEFAULT ((0)) FOR [SampledProjection11]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__5B65DDAC] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge02]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Sampl__5B9AE7D6] DEFAULT ((0)) FOR [SampledProjection12]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__5C5A01E5] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge03]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__5C8F0C0F] DEFAULT ((0)) FOR [InitialBudget01]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__5D4E261E] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge04]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__5D833048] DEFAULT ((0)) FOR [InitialBudget02]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__5E424A57] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge05]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__5E775481] DEFAULT ((0)) FOR [InitialBudget03]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__5F366E90] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge06]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__5F6B78BA] DEFAULT ((0)) FOR [InitialBudget04]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__602A92C9] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge07]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__605F9CF3] DEFAULT ((0)) FOR [InitialBudget05]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__611EB702] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge08]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6153C12C] DEFAULT ((0)) FOR [InitialBudget06]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6212DB3B] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge09]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6247E565] DEFAULT ((0)) FOR [InitialBudget07]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6306FF74] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge10]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__633C099E] DEFAULT ((0)) FOR [InitialBudget08]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__63FB23AD] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge11]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__64302DD7] DEFAULT ((0)) FOR [InitialBudget09]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__64EF47E6] DEFAULT ((0)) FOR [InitialProjectionPercentOfCharge12]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__65245210] DEFAULT ((0)) FOR [InitialBudget10]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__65E36C1F] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted01]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__66187649] DEFAULT ((0)) FOR [InitialBudget11]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__66D79058] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted02]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__670C9A82] DEFAULT ((0)) FOR [InitialBudget12]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__67CBB491] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted03]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6800BEBB] DEFAULT ((0)) FOR [InitialProjection01]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__68BFD8CA] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted04]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__68F4E2F4] DEFAULT ((0)) FOR [InitialProjection02]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__69B3FD03] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted05]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__69E9072D] DEFAULT ((0)) FOR [InitialProjection03]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__6AA8213C] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted06]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6ADD2B66] DEFAULT ((0)) FOR [InitialProjection04]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__6B9C4575] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted07]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6BD14F9F] DEFAULT ((0)) FOR [InitialProjection05]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__6C9069AE] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted08]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6CC573D8] DEFAULT ((0)) FOR [InitialProjection06]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__6D848DE7] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted09]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6DB99811] DEFAULT ((0)) FOR [InitialProjection07]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__6E78B220] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted10]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6EADBC4A] DEFAULT ((0)) FOR [InitialProjection08]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__6F6CD659] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted11]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__6FA1E083] DEFAULT ((0)) FOR [InitialProjection09]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__7060FA92] DEFAULT ((0)) FOR [TargetPercentOfChargeAdjusted12]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__709604BC] DEFAULT ((0)) FOR [InitialProjection10]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__71551ECB] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted01]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__718A28F5] DEFAULT ((0)) FOR [InitialProjection11]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__72494304] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted02]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Initi__727E4D2E] DEFAULT ((0)) FOR [InitialProjection12]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__733D673D] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted03]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__73727167] DEFAULT ((0)) FOR [TargetAdjusted01]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__74318B76] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted04]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__746695A0] DEFAULT ((0)) FOR [TargetAdjusted02]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__7525AFAF] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted05]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__755AB9D9] DEFAULT ((0)) FOR [TargetAdjusted03]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__7619D3E8] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted06]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__764EDE12] DEFAULT ((0)) FOR [TargetAdjusted04]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__770DF821] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted07]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__7743024B] DEFAULT ((0)) FOR [TargetAdjusted05]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__78021C5A] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted08]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__78372684] DEFAULT ((0)) FOR [TargetAdjusted06]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__78F64093] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted09]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__792B4ABD] DEFAULT ((0)) FOR [TargetAdjusted07]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__79EA64CC] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted10]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__7A1F6EF6] DEFAULT ((0)) FOR [TargetAdjusted08]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__7ADE8905] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted11]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__7B13932F] DEFAULT ((0)) FOR [TargetAdjusted09]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__7BD2AD3E] DEFAULT ((0)) FOR [BudgetPercentOfChargeAdjusted12]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__7C07B768] DEFAULT ((0)) FOR [TargetAdjusted10]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__7CC6D177] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted01]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__7CFBDBA1] DEFAULT ((0)) FOR [TargetAdjusted11]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__7DBAF5B0] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted02]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Targe__7DEFFFDA] DEFAULT ((0)) FOR [TargetAdjusted12]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__7EAF19E9] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted03]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__7EE42413] DEFAULT ((0)) FOR [BudgetAdjusted01]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Proje__7FA33E22] DEFAULT ((0)) FOR [ProjectionPercentOfChargeAdjusted04]; GO +ALTER TABLE [fp].[GeneralLedgerSnapshot] ADD CONSTRAINT [DF__GeneralLe__Budge__7FD8484C] DEFAULT ((0)) FOR [BudgetAdjusted02]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerSpreadUnlockData ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerSpreadUnlockData] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [Version] timestamp NOT NULL, + [Value01] decimal NOT NULL, + [Value02] decimal NOT NULL, + [Value03] decimal NOT NULL, + [Value04] decimal NOT NULL, + [Value05] decimal NOT NULL, + [Value06] decimal NOT NULL, + [Value07] decimal NOT NULL, + [Value08] decimal NOT NULL, + [Value09] decimal NOT NULL, + [Value10] decimal NOT NULL, + [Value11] decimal NOT NULL, + [Value12] decimal NOT NULL, + [IsRecordDeleted] bit NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__0066B8A7] DEFAULT ((0)) FOR [Value05]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__015ADCE0] DEFAULT ((0)) FOR [Value06]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__IsRec__01C687E2] DEFAULT ((0)) FOR [IsRecordDeleted]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__024F0119] DEFAULT ((0)) FOR [Value07]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__03432552] DEFAULT ((0)) FOR [Value08]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__0437498B] DEFAULT ((0)) FOR [Value09]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__052B6DC4] DEFAULT ((0)) FOR [Value10]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__061F91FD] DEFAULT ((0)) FOR [Value11]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__0713B636] DEFAULT ((0)) FOR [Value12]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Budge__76DD4E6D] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Adjus__77D172A6] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Entit__78C596DF] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Depar__79B9BB18] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Accou__7AADDF51] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Finan__7BA2038A] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__7C9627C3] DEFAULT ((0)) FOR [Value01]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__7D8A4BFC] DEFAULT ((0)) FOR [Value02]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__7E7E7035] DEFAULT ((0)) FOR [Value03]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadUnlockData] ADD CONSTRAINT [DF__GeneralLe__Value__7F72946E] DEFAULT ((0)) FOR [Value04]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerSpreads ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerSpreads] ( + [BudgetConfigID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [IsInactive] bit NOT NULL, + [SpreadPercentage01] decimal NULL, + [SpreadPercentage02] decimal NULL, + [SpreadPercentage03] decimal NULL, + [SpreadPercentage04] decimal NULL, + [SpreadPercentage05] decimal NULL, + [SpreadPercentage06] decimal NULL, + [SpreadPercentage07] decimal NULL, + [SpreadPercentage08] decimal NULL, + [SpreadPercentage09] decimal NULL, + [SpreadPercentage10] decimal NULL, + [SpreadPercentage11] decimal NULL, + [SpreadPercentage12] decimal NULL, + [TotalImportedValue] decimal NULL, + [SpreadHistoryGUID] uniqueidentifier NOT NULL, + [GlobalSpreadID] int NOT NULL, + PRIMARY KEY ([BudgetConfigID], [DepartmentID], [AccountID]) +); +GO +ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [FK_FpGeneralLedgerSpreads_History] FOREIGN KEY ([SpreadHistoryGUID]) REFERENCES [fp].[SpreadHistory] ([SpreadHistoryGUID]); GO +ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Budge__313EFA2C] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Depar__32331E65] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Accou__3327429E] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__IsIna__341B66D7] DEFAULT ((0)) FOR [IsInactive]; GO +ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__350F8B10] DEFAULT ((0)) FOR [SpreadPercentage01]; GO +ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__3603AF49] DEFAULT ((0)) FOR [SpreadPercentage02]; GO +ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__36F7D382] DEFAULT ((0)) FOR [SpreadPercentage03]; GO +ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__37EBF7BB] DEFAULT ((0)) FOR [SpreadPercentage04]; GO +ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__38E01BF4] DEFAULT ((0)) FOR [SpreadPercentage05]; GO +ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__39D4402D] DEFAULT ((0)) FOR [SpreadPercentage06]; GO +ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__3AC86466] DEFAULT ((0)) FOR [SpreadPercentage07]; GO +ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__3BBC889F] DEFAULT ((0)) FOR [SpreadPercentage08]; GO +ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__3CB0ACD8] DEFAULT ((0)) FOR [SpreadPercentage09]; GO +ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__3DA4D111] DEFAULT ((0)) FOR [SpreadPercentage10]; GO +ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__3E98F54A] DEFAULT ((0)) FOR [SpreadPercentage11]; GO +ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Sprea__3F8D1983] DEFAULT ((0)) FOR [SpreadPercentage12]; GO +ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Total__40813DBC] DEFAULT ((0)) FOR [TotalImportedValue]; GO +ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [df_GeneralLedgerSpreads_SpreadHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SpreadHistoryGUID]; GO +ALTER TABLE [fp].[GeneralLedgerSpreads] ADD CONSTRAINT [DF__GeneralLe__Globa__6B2C6FF6] DEFAULT ((1)) FOR [GlobalSpreadID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerSpreadsChangeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ( + [RowID] bigint NOT NULL, + [GeneralLedgerID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + [OldValue01] decimal NOT NULL, + [OldValue02] decimal NOT NULL, + [OldValue03] decimal NOT NULL, + [OldValue04] decimal NOT NULL, + [OldValue05] decimal NOT NULL, + [OldValue06] decimal NOT NULL, + [OldValue07] decimal NOT NULL, + [OldValue08] decimal NOT NULL, + [OldValue09] decimal NOT NULL, + [OldValue10] decimal NOT NULL, + [OldValue11] decimal NOT NULL, + [OldValue12] decimal NOT NULL, + [NewValue01] decimal NOT NULL, + [NewValue02] decimal NOT NULL, + [NewValue03] decimal NOT NULL, + [NewValue04] decimal NOT NULL, + [NewValue05] decimal NOT NULL, + [NewValue06] decimal NOT NULL, + [NewValue07] decimal NOT NULL, + [NewValue08] decimal NOT NULL, + [NewValue09] decimal NOT NULL, + [NewValue10] decimal NOT NULL, + [NewValue11] decimal NOT NULL, + [NewValue12] decimal NOT NULL +); + +CREATE CLUSTERED INDEX [CORE_BudgetConfigID] ON [fp].[GeneralLedgerSpreadsChangeHistory] ([BudgetConfigID], [GeneralLedgerID], [RowID]); +GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__Gener__4F409776] DEFAULT ((0)) FOR [GeneralLedgerID]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__Budge__5034BBAF] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__DateC__5128DFE8] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__521D0421] DEFAULT ((0)) FOR [OldValue01]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__5311285A] DEFAULT ((0)) FOR [OldValue02]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__54054C93] DEFAULT ((0)) FOR [OldValue03]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__54F970CC] DEFAULT ((0)) FOR [OldValue04]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__55ED9505] DEFAULT ((0)) FOR [OldValue05]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__56E1B93E] DEFAULT ((0)) FOR [OldValue06]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__57D5DD77] DEFAULT ((0)) FOR [OldValue07]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__58CA01B0] DEFAULT ((0)) FOR [OldValue08]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__59BE25E9] DEFAULT ((0)) FOR [OldValue09]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__5AB24A22] DEFAULT ((0)) FOR [OldValue10]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__5BA66E5B] DEFAULT ((0)) FOR [OldValue11]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__OldVa__5C9A9294] DEFAULT ((0)) FOR [OldValue12]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__5D8EB6CD] DEFAULT ((0)) FOR [NewValue01]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__5E82DB06] DEFAULT ((0)) FOR [NewValue02]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__5F76FF3F] DEFAULT ((0)) FOR [NewValue03]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__606B2378] DEFAULT ((0)) FOR [NewValue04]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__615F47B1] DEFAULT ((0)) FOR [NewValue05]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__62536BEA] DEFAULT ((0)) FOR [NewValue06]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__63479023] DEFAULT ((0)) FOR [NewValue07]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__643BB45C] DEFAULT ((0)) FOR [NewValue08]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__652FD895] DEFAULT ((0)) FOR [NewValue09]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__6623FCCE] DEFAULT ((0)) FOR [NewValue10]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__67182107] DEFAULT ((0)) FOR [NewValue11]; GO +ALTER TABLE [fp].[GeneralLedgerSpreadsChangeHistory] ADD CONSTRAINT [DF__GeneralLe__NewVa__680C4540] DEFAULT ((0)) FOR [NewValue12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerSubAccountItemizedAdjustment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ( + [SubAccountItemizedID] int NOT NULL, + [AdjustmentID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [Itemized] bit NOT NULL, + [Value01] decimal NOT NULL, + [Value02] decimal NOT NULL, + [Value03] decimal NOT NULL, + [Value04] decimal NOT NULL, + [Value05] decimal NOT NULL, + [Value06] decimal NOT NULL, + [Value07] decimal NOT NULL, + [Value08] decimal NOT NULL, + [Value09] decimal NOT NULL, + [Value10] decimal NOT NULL, + [Value11] decimal NOT NULL, + [Value12] decimal NOT NULL, + PRIMARY KEY ([SubAccountItemizedID]) +); +GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Adjus__1C48A150] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Budge__1D3CC589] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Depar__1E30E9C2] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Accou__1F250DFB] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__UnitT__20193234] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__TimeC__210D566D] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Budge__22017AA6] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Itemi__22F59EDF] DEFAULT ((0)) FOR [Itemized]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__23E9C318] DEFAULT ((0)) FOR [Value01]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__24DDE751] DEFAULT ((0)) FOR [Value02]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__25D20B8A] DEFAULT ((0)) FOR [Value03]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__26C62FC3] DEFAULT ((0)) FOR [Value04]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__27BA53FC] DEFAULT ((0)) FOR [Value05]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__28AE7835] DEFAULT ((0)) FOR [Value06]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__29A29C6E] DEFAULT ((0)) FOR [Value07]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__2A96C0A7] DEFAULT ((0)) FOR [Value08]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__2B8AE4E0] DEFAULT ((0)) FOR [Value09]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__2C7F0919] DEFAULT ((0)) FOR [Value10]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__2D732D52] DEFAULT ((0)) FOR [Value11]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedAdjustment] ADD CONSTRAINT [DF__GeneralLe__Value__2E67518B] DEFAULT ((0)) FOR [Value12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerSubAccountItemizedDetail ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [AccountID] int NOT NULL, + [DepartmentID] int NOT NULL, + [Description] nvarchar(1000) NOT NULL, + [Value01] decimal NOT NULL, + [Value02] decimal NOT NULL, + [Value03] decimal NOT NULL, + [Value04] decimal NOT NULL, + [Value05] decimal NOT NULL, + [Value06] decimal NOT NULL, + [Value07] decimal NOT NULL, + [Value08] decimal NOT NULL, + [Value09] decimal NOT NULL, + [Value10] decimal NOT NULL, + [Value11] decimal NOT NULL, + [Value12] decimal NOT NULL, + [CategoryID] int NOT NULL, + [LastModifiedDateUtc] datetime NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + [CreatedAuthorFullName] nvarchar(260) NOT NULL, + [LastModifiedAuthorFullName] nvarchar(260) NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Categ__045C0926] DEFAULT ((0)) FOR [CategoryID]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Budge__2409BEA9] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__UnitT__24FDE2E2] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__TimeC__25F2071B] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Budge__26E62B54] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Accou__27DA4F8D] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Depar__28CE73C6] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Descr__2AB6BC38] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__2BAAE071] DEFAULT ((0)) FOR [Value01]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__2C9F04AA] DEFAULT ((0)) FOR [Value02]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__2D9328E3] DEFAULT ((0)) FOR [Value03]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__2E874D1C] DEFAULT ((0)) FOR [Value04]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__2F7B7155] DEFAULT ((0)) FOR [Value05]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__306F958E] DEFAULT ((0)) FOR [Value06]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__3163B9C7] DEFAULT ((0)) FOR [Value07]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__3257DE00] DEFAULT ((0)) FOR [Value08]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__334C0239] DEFAULT ((0)) FOR [Value09]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__34402672] DEFAULT ((0)) FOR [Value10]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__35344AAB] DEFAULT ((0)) FOR [Value11]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF__GeneralLe__Value__36286EE4] DEFAULT ((0)) FOR [Value12]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF_GeneralLedgerSubAccountItemizedDetail_LastModifiedDateUtc] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF_GeneralLedgerSubAccountItemizedDetail_DateCreatedUtc] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF_GeneralLedgerSubAccountItemizedDetail_CreatedAuthorFullName] DEFAULT ('') FOR [CreatedAuthorFullName]; GO +ALTER TABLE [fp].[GeneralLedgerSubAccountItemizedDetail] ADD CONSTRAINT [DF_GeneralLedgerSubAccountItemizedDetail_LastModifiedAuthorFullName] DEFAULT ('') FOR [LastModifiedAuthorFullName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GeneralLedgerVariableDetail ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GeneralLedgerVariableDetail] ( + [CommentGUID] uniqueidentifier NOT NULL, + [AdjustmentID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [DepartmentID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [AccountID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [DollarsValue] decimal NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [DateCreatedUTC] datetime NOT NULL, + PRIMARY KEY ([CommentGUID]) +); +GO +ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__Comme__50C4F482] DEFAULT (newid()) FOR [CommentGUID]; GO +ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__Adjus__51B918BB] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__Budge__52AD3CF4] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__Depar__53A1612D] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__Finan__54958566] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__Accou__5589A99F] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__TimeC__567DCDD8] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__Dolla__5771F211] DEFAULT ((0)) FOR [DollarsValue]; GO +ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__Comme__5866164A] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__Autho__595A3A83] DEFAULT ('') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__Autho__5A4E5EBC] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [fp].[GeneralLedgerVariableDetail] ADD CONSTRAINT [DF__GeneralLe__DateC__5B4282F5] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.GlobalSpread ------------------ +--------------------------------------------- +CREATE TABLE [fp].[GlobalSpread] ( + [GlobalSpreadID] int NOT NULL, + [BudgetConfigID] smallint NOT NULL, + [SpreadName] nvarchar(4000) NOT NULL, + [SortOrder] int NOT NULL, + [SpreadPercentage01] decimal NOT NULL, + [SpreadPercentage02] decimal NOT NULL, + [SpreadPercentage03] decimal NOT NULL, + [SpreadPercentage04] decimal NOT NULL, + [SpreadPercentage05] decimal NOT NULL, + [SpreadPercentage06] decimal NOT NULL, + [SpreadPercentage07] decimal NOT NULL, + [SpreadPercentage08] decimal NOT NULL, + [SpreadPercentage09] decimal NOT NULL, + [SpreadPercentage10] decimal NOT NULL, + [SpreadPercentage11] decimal NOT NULL, + [SpreadPercentage12] decimal NOT NULL, + [TotalSpreadValue] decimal NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([GlobalSpreadID]) +); +GO +ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [df_GlobalSpread_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Budge__5AF6082D] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__5BEA2C66] DEFAULT ('') FOR [SpreadName]; GO +ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__SortO__5CDE509F] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__5DD274D8] DEFAULT ((0)) FOR [SpreadPercentage01]; GO +ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__5EC69911] DEFAULT ((0)) FOR [SpreadPercentage02]; GO +ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__5FBABD4A] DEFAULT ((0)) FOR [SpreadPercentage03]; GO +ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__60AEE183] DEFAULT ((0)) FOR [SpreadPercentage04]; GO +ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__61A305BC] DEFAULT ((0)) FOR [SpreadPercentage05]; GO +ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__629729F5] DEFAULT ((0)) FOR [SpreadPercentage06]; GO +ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__638B4E2E] DEFAULT ((0)) FOR [SpreadPercentage07]; GO +ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__647F7267] DEFAULT ((0)) FOR [SpreadPercentage08]; GO +ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__657396A0] DEFAULT ((0)) FOR [SpreadPercentage09]; GO +ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__6667BAD9] DEFAULT ((0)) FOR [SpreadPercentage10]; GO +ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__675BDF12] DEFAULT ((0)) FOR [SpreadPercentage11]; GO +ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Sprea__6850034B] DEFAULT ((0)) FOR [SpreadPercentage12]; GO +ALTER TABLE [fp].[GlobalSpread] ADD CONSTRAINT [DF__GlobalSpr__Total__69442784] DEFAULT ((0)) FOR [TotalSpreadValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.InitialPlanRule ------------------ +--------------------------------------------- +CREATE TABLE [fp].[InitialPlanRule] ( + [RowID] int NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [BudgetConfigID] smallint NOT NULL, + [PlanSectionID] int NOT NULL, + [SubSectionID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [DimensionalityJSON] nvarchar(max) NOT NULL, + [ProjectionMethodID] int NOT NULL, + [TrailingMonths] tinyint NOT NULL, + [RulePriority] int NOT NULL, + [VersionID] int NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [FK__InitialPl__Budge__269DA93F] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [FK__InitialPl__Versi__344CAA18] FOREIGN KEY ([VersionID]) REFERENCES [fp].[InitialPlanRuleVersion] ([VersionID]); GO +ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [DF__InitialPl__Budge__1E08633E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [DF__InitialPl__Budge__1EFC8777] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [DF__InitialPl__PlanS__1FF0ABB0] DEFAULT ((0)) FOR [PlanSectionID]; GO +ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [DF__InitialPl__SubSe__20E4CFE9] DEFAULT ((0)) FOR [SubSectionID]; GO +ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [DF__InitialPl__TimeC__21D8F422] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [DF__InitialPl__Dimen__22CD185B] DEFAULT ('') FOR [DimensionalityJSON]; GO +ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [DF__InitialPl__Proje__23C13C94] DEFAULT ((0)) FOR [ProjectionMethodID]; GO +ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [DF__InitialPl__Trail__24B560CD] DEFAULT ((0)) FOR [TrailingMonths]; GO +ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [DF__InitialPl__RuleP__25A98506] DEFAULT ((0)) FOR [RulePriority]; GO +ALTER TABLE [fp].[InitialPlanRule] ADD CONSTRAINT [DF__InitialPl__Versi__335885DF] DEFAULT ((0)) FOR [VersionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.InitialPlanRuleHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[InitialPlanRuleHistory] ( + [RowID] int NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [BudgetConfigID] smallint NOT NULL, + [PlanSectionID] int NOT NULL, + [SubSectionID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [DimensionalityJSON] nvarchar(max) NOT NULL, + [ProjectionMethodID] int NOT NULL, + [TrailingMonths] tinyint NOT NULL, + [RulePriority] int NOT NULL, + [VersionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [FK__InitialPl__Budge__307C1934] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [FK__InitialPl__Versi__31703D6D] FOREIGN KEY ([VersionID]) REFERENCES [fp].[InitialPlanRuleVersion] ([VersionID]); GO +ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [DF__InitialPl__Budge__26F2AEFA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [DF__InitialPl__Budge__27E6D333] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [DF__InitialPl__PlanS__28DAF76C] DEFAULT ((0)) FOR [PlanSectionID]; GO +ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [DF__InitialPl__SubSe__29CF1BA5] DEFAULT ((0)) FOR [SubSectionID]; GO +ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [DF__InitialPl__TimeC__2AC33FDE] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [DF__InitialPl__Dimen__2BB76417] DEFAULT ('') FOR [DimensionalityJSON]; GO +ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [DF__InitialPl__Proje__2CAB8850] DEFAULT ((0)) FOR [ProjectionMethodID]; GO +ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [DF__InitialPl__Trail__2D9FAC89] DEFAULT ((0)) FOR [TrailingMonths]; GO +ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [DF__InitialPl__RuleP__2E93D0C2] DEFAULT ((0)) FOR [RulePriority]; GO +ALTER TABLE [fp].[InitialPlanRuleHistory] ADD CONSTRAINT [DF__InitialPl__Versi__2F87F4FB] DEFAULT ((0)) FOR [VersionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.InitialPlanRuleVersion ------------------ +--------------------------------------------- +CREATE TABLE [fp].[InitialPlanRuleVersion] ( + [VersionID] int NOT NULL, + [DateCreated] datetime NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [IsSampled] bit NOT NULL, + [IsConfigDetailDataReady] bit NOT NULL, + PRIMARY KEY ([VersionID]) +); +GO +ALTER TABLE [fp].[InitialPlanRuleVersion] ADD CONSTRAINT [DF__InitialPl__DateC__222DF9DD] DEFAULT (getdate()) FOR [DateCreated]; GO +ALTER TABLE [fp].[InitialPlanRuleVersion] ADD CONSTRAINT [DF__InitialPl__Autho__23221E16] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[InitialPlanRuleVersion] ADD CONSTRAINT [DF__InitialPl__Autho__2416424F] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [fp].[InitialPlanRuleVersion] ADD CONSTRAINT [DF__InitialPl__IsSam__2826CA55] DEFAULT ((0)) FOR [IsSampled]; GO +ALTER TABLE [fp].[InitialPlanRuleVersion] ADD CONSTRAINT [DF__InitialPl__IsCon__5736BEF9] DEFAULT ((0)) FOR [IsConfigDetailDataReady]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.LineItemJobCode ------------------ +--------------------------------------------- +CREATE TABLE [fp].[LineItemJobCode] ( + [RowID] int NOT NULL, + [FinancialLineItem] nvarchar(100) NOT NULL, + [JobCodeID] int NOT NULL, + [JobCode] nvarchar(100) NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [PreviousActualHours] decimal NOT NULL, + [YTDActualHours] decimal NOT NULL, + [CurrentBudgetHours] decimal NOT NULL, + [JanBudgetHours] decimal NOT NULL, + [FebBudgetHours] decimal NOT NULL, + [MarBudgetHours] decimal NOT NULL, + [AprBudgetHours] decimal NOT NULL, + [MayBudgetHours] decimal NOT NULL, + [JunBudgetHours] decimal NOT NULL, + [JulBudgetHours] decimal NOT NULL, + [AugBudgetHours] decimal NOT NULL, + [SepBudgetHours] decimal NOT NULL, + [OctBudgetHours] decimal NOT NULL, + [NovBudgetHours] decimal NOT NULL, + [DecBudgetHours] decimal NOT NULL, + [PreviousActualWorkingHours] decimal NOT NULL, + [YTDActualWorkingHours] decimal NOT NULL, + [CurrentBudgetWorkingHours] decimal NOT NULL, + [JanBudgetWorkingHours] decimal NOT NULL, + [FebBudgetWorkingHours] decimal NOT NULL, + [MarBudgetWorkingHours] decimal NOT NULL, + [AprBudgetWorkingHours] decimal NOT NULL, + [MayBudgetWorkingHours] decimal NOT NULL, + [JunBudgetWorkingHours] decimal NOT NULL, + [JulBudgetWorkingHours] decimal NOT NULL, + [AugBudgetWorkingHours] decimal NOT NULL, + [SepBudgetWorkingHours] decimal NOT NULL, + [OctBudgetWorkingHours] decimal NOT NULL, + [NovBudgetWorkingHours] decimal NOT NULL, + [DecBudgetWorkingHours] decimal NOT NULL, + [PreviousActualFTEs] decimal NOT NULL, + [YTDActualFTEs] decimal NOT NULL, + [CurrentBudgetFTEs] decimal NOT NULL, + [JanBudgetFTEs] decimal NOT NULL, + [FebBudgetFTEs] decimal NOT NULL, + [MarBudgetFTEs] decimal NOT NULL, + [AprBudgetFTEs] decimal NOT NULL, + [MayBudgetFTEs] decimal NOT NULL, + [JunBudgetFTEs] decimal NOT NULL, + [JulBudgetFTEs] decimal NOT NULL, + [AugBudgetFTEs] decimal NOT NULL, + [SepBudgetFTEs] decimal NOT NULL, + [OctBudgetFTEs] decimal NOT NULL, + [NovBudgetFTEs] decimal NOT NULL, + [DecBudgetFTEs] decimal NOT NULL, + [PreviousActualDollars] decimal NOT NULL, + [YTDActualDollars] decimal NOT NULL, + [CurrentBudgetDollars] decimal NOT NULL, + [JanBudgetDollars] decimal NOT NULL, + [FebBudgetDollars] decimal NOT NULL, + [MarBudgetDollars] decimal NOT NULL, + [AprBudgetDollars] decimal NOT NULL, + [MayBudgetDollars] decimal NOT NULL, + [JunBudgetDollars] decimal NOT NULL, + [JulBudgetDollars] decimal NOT NULL, + [AugBudgetDollars] decimal NOT NULL, + [SepBudgetDollars] decimal NOT NULL, + [OctBudgetDollars] decimal NOT NULL, + [NovBudgetDollars] decimal NOT NULL, + [DecBudgetDollars] decimal NOT NULL, + [PreviousActualWageRate] decimal NOT NULL, + [YTDActualWageRate] decimal NOT NULL, + [CurrentBudgetWageRate] decimal NOT NULL, + [CurrentBudgetWageRateMultiplier] decimal NOT NULL, + [JanBudgetWageRate] decimal NOT NULL, + [FebBudgetWageRate] decimal NOT NULL, + [MarBudgetWageRate] decimal NOT NULL, + [AprBudgetWageRate] decimal NOT NULL, + [MayBudgetWageRate] decimal NOT NULL, + [JunBudgetWageRate] decimal NOT NULL, + [JulBudgetWageRate] decimal NOT NULL, + [AugBudgetWageRate] decimal NOT NULL, + [SepBudgetWageRate] decimal NOT NULL, + [OctBudgetWageRate] decimal NOT NULL, + [NovBudgetWageRate] decimal NOT NULL, + [DecBudgetWageRate] decimal NOT NULL, + [OriginalBudgetHours] decimal NOT NULL, + [OriginalBudgetFTEs] decimal NOT NULL, + [OriginalBudgetDollars] decimal NOT NULL, + [OriginalBudgetWageRate] decimal NOT NULL, + [AnnualizedActualHours] decimal NOT NULL, + [AnnualizedActualWorkingHours] decimal NOT NULL, + [AnnualizedActualDollars] decimal NOT NULL, + [AnnualizedActualFTEs] decimal NOT NULL, + [AnnualizedActualWageRate] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF__LineItemJ__Annua__052A70A3] DEFAULT ((0)) FOR [AnnualizedActualHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF__LineItemJ__Annua__061E94DC] DEFAULT ((0)) FOR [AnnualizedActualWorkingHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF__LineItemJ__Annua__0712B915] DEFAULT ((0)) FOR [AnnualizedActualDollars]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF__LineItemJ__Annua__0806DD4E] DEFAULT ((0)) FOR [AnnualizedActualFTEs]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF__LineItemJ__Annua__08FB0187] DEFAULT ((0)) FOR [AnnualizedActualWageRate]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_FinancialLineItem] DEFAULT ('') FOR [FinancialLineItem]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JobCodeID] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JobCode] DEFAULT ('') FOR [JobCode]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_PreviousActualHours] DEFAULT ((0)) FOR [PreviousActualHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_YTDActualHours] DEFAULT ((0)) FOR [YTDActualHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_CurrentBudgetHours] DEFAULT ((0)) FOR [CurrentBudgetHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JanBudgetHours] DEFAULT ((0)) FOR [JanBudgetHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_FebBudgetHours] DEFAULT ((0)) FOR [FebBudgetHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_MarBudgetHours] DEFAULT ((0)) FOR [MarBudgetHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_AprBudgetHours] DEFAULT ((0)) FOR [AprBudgetHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_MayBudgetHours] DEFAULT ((0)) FOR [MayBudgetHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JunBudgetHours] DEFAULT ((0)) FOR [JunBudgetHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JulBudgetHours] DEFAULT ((0)) FOR [JulBudgetHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_AugBudgetHours] DEFAULT ((0)) FOR [AugBudgetHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_SepBudgetHours] DEFAULT ((0)) FOR [SepBudgetHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_OctBudgetHours] DEFAULT ((0)) FOR [OctBudgetHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_NovBudgetHours] DEFAULT ((0)) FOR [NovBudgetHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_DecBudgetHours] DEFAULT ((0)) FOR [DecBudgetHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_PreviousActualWorkingHours] DEFAULT ((0)) FOR [PreviousActualWorkingHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_YTDActualWorkingHours] DEFAULT ((0)) FOR [YTDActualWorkingHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_CurrentBudgetWorkingHours] DEFAULT ((0)) FOR [CurrentBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JanBudgetWorkingHours] DEFAULT ((0)) FOR [JanBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_FebBudgetWorkingHours] DEFAULT ((0)) FOR [FebBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_MarBudgetWorkingHours] DEFAULT ((0)) FOR [MarBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_AprBudgetWorkingHours] DEFAULT ((0)) FOR [AprBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_MayBudgetWorkingHours] DEFAULT ((0)) FOR [MayBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JunBudgetWorkingHours] DEFAULT ((0)) FOR [JunBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JulBudgetWorkingHours] DEFAULT ((0)) FOR [JulBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_AugBudgetWorkingHours] DEFAULT ((0)) FOR [AugBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_SepBudgetWorkingHours] DEFAULT ((0)) FOR [SepBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_OctBudgetWorkingHours] DEFAULT ((0)) FOR [OctBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_NovBudgetWorkingHours] DEFAULT ((0)) FOR [NovBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_DecBudgetWorkingHours] DEFAULT ((0)) FOR [DecBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_PreviousActualFTEs] DEFAULT ((0)) FOR [PreviousActualFTEs]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [df_LineItemJobCode_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_YTDActualFTEs] DEFAULT ((0)) FOR [YTDActualFTEs]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_CurrentBudgetFTEs] DEFAULT ((0)) FOR [CurrentBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JanBudgetFTEs] DEFAULT ((0)) FOR [JanBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_FebBudgetFTEs] DEFAULT ((0)) FOR [FebBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_MarBudgetFTEs] DEFAULT ((0)) FOR [MarBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_AprBudgetFTEs] DEFAULT ((0)) FOR [AprBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_MayBudgetFTEs] DEFAULT ((0)) FOR [MayBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JunBudgetFTEs] DEFAULT ((0)) FOR [JunBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JulBudgetFTEs] DEFAULT ((0)) FOR [JulBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_AugBudgetFTEs] DEFAULT ((0)) FOR [AugBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_SepBudgetFTEs] DEFAULT ((0)) FOR [SepBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_OctBudgetFTEs] DEFAULT ((0)) FOR [OctBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_NovBudgetFTEs] DEFAULT ((0)) FOR [NovBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_DecBudgetFTEs] DEFAULT ((0)) FOR [DecBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_PreviousActualDollars] DEFAULT ((0)) FOR [PreviousActualDollars]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_YTDActualDollars] DEFAULT ((0)) FOR [YTDActualDollars]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_CurrentBudgetDollars] DEFAULT ((0)) FOR [CurrentBudgetDollars]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JanBudgetDollars] DEFAULT ((0)) FOR [JanBudgetDollars]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_FebBudgetDollars] DEFAULT ((0)) FOR [FebBudgetDollars]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_MarBudgetDollars] DEFAULT ((0)) FOR [MarBudgetDollars]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_AprBudgetDollars] DEFAULT ((0)) FOR [AprBudgetDollars]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_MayBudgetDollars] DEFAULT ((0)) FOR [MayBudgetDollars]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JunBudgetDollars] DEFAULT ((0)) FOR [JunBudgetDollars]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JulBudgetDollars] DEFAULT ((0)) FOR [JulBudgetDollars]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_AugBudgetDollars] DEFAULT ((0)) FOR [AugBudgetDollars]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_SepBudgetDollars] DEFAULT ((0)) FOR [SepBudgetDollars]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_OctBudgetDollars] DEFAULT ((0)) FOR [OctBudgetDollars]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_NovBudgetDollars] DEFAULT ((0)) FOR [NovBudgetDollars]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_DecBudgetDollars] DEFAULT ((0)) FOR [DecBudgetDollars]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_PreviousActualWageRate] DEFAULT ((0)) FOR [PreviousActualWageRate]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_YTDActualWageRate] DEFAULT ((0)) FOR [YTDActualWageRate]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_CurrentBudgetWageRate] DEFAULT ((0)) FOR [CurrentBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_CurrentBudgetWageRateMultiplier] DEFAULT ((0)) FOR [CurrentBudgetWageRateMultiplier]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JanBudgetWageRate] DEFAULT ((0)) FOR [JanBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_FebBudgetWageRate] DEFAULT ((0)) FOR [FebBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_MarBudgetWageRate] DEFAULT ((0)) FOR [MarBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_AprBudgetWageRate] DEFAULT ((0)) FOR [AprBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_MayBudgetWageRate] DEFAULT ((0)) FOR [MayBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JunBudgetWageRate] DEFAULT ((0)) FOR [JunBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF__LineItemJ__Origi__4FC2842B] DEFAULT ((0)) FOR [OriginalBudgetHours]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_JulBudgetWageRate] DEFAULT ((0)) FOR [JulBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF__LineItemJ__Origi__50B6A864] DEFAULT ((0)) FOR [OriginalBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_AugBudgetWageRate] DEFAULT ((0)) FOR [AugBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF__LineItemJ__Origi__51AACC9D] DEFAULT ((0)) FOR [OriginalBudgetDollars]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_SepBudgetWageRate] DEFAULT ((0)) FOR [SepBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF__LineItemJ__Origi__529EF0D6] DEFAULT ((0)) FOR [OriginalBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_OctBudgetWageRate] DEFAULT ((0)) FOR [OctBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_NovBudgetWageRate] DEFAULT ((0)) FOR [NovBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemJobCode] ADD CONSTRAINT [DF_LineItemJobCode_DecBudgetWageRate] DEFAULT ((0)) FOR [DecBudgetWageRate]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.LineItemPayCodeGroup ------------------ +--------------------------------------------- +CREATE TABLE [fp].[LineItemPayCodeGroup] ( + [RowID] int NOT NULL, + [FinancialLineItem] nvarchar(100) NOT NULL, + [PayCodeGroupID] int NOT NULL, + [PayCodeGroup] nvarchar(100) NOT NULL, + [PayCodeGroupSortOrder] int NOT NULL, + [ProductiveClassID] int NOT NULL, + [ProductiveClass] nvarchar(100) NOT NULL, + [JobCodeID] int NOT NULL, + [JobCode] nvarchar(100) NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [PreviousActualHours] decimal NOT NULL, + [YTDActualHours] decimal NOT NULL, + [CurrentBudgetHours] decimal NOT NULL, + [JanBudgetHours] decimal NOT NULL, + [FebBudgetHours] decimal NOT NULL, + [MarBudgetHours] decimal NOT NULL, + [AprBudgetHours] decimal NOT NULL, + [MayBudgetHours] decimal NOT NULL, + [JunBudgetHours] decimal NOT NULL, + [JulBudgetHours] decimal NOT NULL, + [AugBudgetHours] decimal NOT NULL, + [SepBudgetHours] decimal NOT NULL, + [OctBudgetHours] decimal NOT NULL, + [NovBudgetHours] decimal NOT NULL, + [DecBudgetHours] decimal NOT NULL, + [PreviousActualWorkingHours] decimal NOT NULL, + [YTDActualWorkingHours] decimal NOT NULL, + [CurrentBudgetWorkingHours] decimal NOT NULL, + [JanBudgetWorkingHours] decimal NOT NULL, + [FebBudgetWorkingHours] decimal NOT NULL, + [MarBudgetWorkingHours] decimal NOT NULL, + [AprBudgetWorkingHours] decimal NOT NULL, + [MayBudgetWorkingHours] decimal NOT NULL, + [JunBudgetWorkingHours] decimal NOT NULL, + [JulBudgetWorkingHours] decimal NOT NULL, + [AugBudgetWorkingHours] decimal NOT NULL, + [SepBudgetWorkingHours] decimal NOT NULL, + [OctBudgetWorkingHours] decimal NOT NULL, + [NovBudgetWorkingHours] decimal NOT NULL, + [DecBudgetWorkingHours] decimal NOT NULL, + [PreviousActualFTEs] decimal NOT NULL, + [YTDActualFTEs] decimal NOT NULL, + [CurrentBudgetFTEs] decimal NOT NULL, + [JanBudgetFTEs] decimal NOT NULL, + [FebBudgetFTEs] decimal NOT NULL, + [MarBudgetFTEs] decimal NOT NULL, + [AprBudgetFTEs] decimal NOT NULL, + [MayBudgetFTEs] decimal NOT NULL, + [JunBudgetFTEs] decimal NOT NULL, + [JulBudgetFTEs] decimal NOT NULL, + [AugBudgetFTEs] decimal NOT NULL, + [SepBudgetFTEs] decimal NOT NULL, + [OctBudgetFTEs] decimal NOT NULL, + [NovBudgetFTEs] decimal NOT NULL, + [DecBudgetFTEs] decimal NOT NULL, + [PreviousActualDollars] decimal NOT NULL, + [YTDActualDollars] decimal NOT NULL, + [CurrentBudgetDollars] decimal NOT NULL, + [JanBudgetDollars] decimal NOT NULL, + [FebBudgetDollars] decimal NOT NULL, + [MarBudgetDollars] decimal NOT NULL, + [AprBudgetDollars] decimal NOT NULL, + [MayBudgetDollars] decimal NOT NULL, + [JunBudgetDollars] decimal NOT NULL, + [JulBudgetDollars] decimal NOT NULL, + [AugBudgetDollars] decimal NOT NULL, + [SepBudgetDollars] decimal NOT NULL, + [OctBudgetDollars] decimal NOT NULL, + [NovBudgetDollars] decimal NOT NULL, + [DecBudgetDollars] decimal NOT NULL, + [PreviousActualWageRate] decimal NOT NULL, + [YTDActualWageRate] decimal NOT NULL, + [CurrentBudgetWageRate] decimal NOT NULL, + [CurrentBudgetWageRateMultiplier] decimal NOT NULL, + [JanBudgetWageRate] decimal NOT NULL, + [FebBudgetWageRate] decimal NOT NULL, + [MarBudgetWageRate] decimal NOT NULL, + [AprBudgetWageRate] decimal NOT NULL, + [MayBudgetWageRate] decimal NOT NULL, + [JunBudgetWageRate] decimal NOT NULL, + [JulBudgetWageRate] decimal NOT NULL, + [AugBudgetWageRate] decimal NOT NULL, + [SepBudgetWageRate] decimal NOT NULL, + [OctBudgetWageRate] decimal NOT NULL, + [NovBudgetWageRate] decimal NOT NULL, + [DecBudgetWageRate] decimal NOT NULL, + [OriginalBudgetHours] decimal NOT NULL, + [OriginalBudgetFTEs] decimal NOT NULL, + [OriginalBudgetDollars] decimal NOT NULL, + [OriginalBudgetWageRate] decimal NOT NULL, + [AnnualizedActualHours] decimal NOT NULL, + [AnnualizedActualWorkingHours] decimal NOT NULL, + [AnnualizedActualDollars] decimal NOT NULL, + [AnnualizedActualFTEs] decimal NOT NULL, + [AnnualizedActualWageRate] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF__LineItemP__Annua__09EF25C0] DEFAULT ((0)) FOR [AnnualizedActualHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF__LineItemP__Annua__0AE349F9] DEFAULT ((0)) FOR [AnnualizedActualWorkingHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF__LineItemP__Annua__0BD76E32] DEFAULT ((0)) FOR [AnnualizedActualDollars]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF__LineItemP__Annua__0CCB926B] DEFAULT ((0)) FOR [AnnualizedActualFTEs]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF__LineItemP__Annua__0DBFB6A4] DEFAULT ((0)) FOR [AnnualizedActualWageRate]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_FinancialLineItem] DEFAULT ('') FOR [FinancialLineItem]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_PayCodeGroupID] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_PayCodeGroup] DEFAULT ('') FOR [PayCodeGroup]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_PayCodeGroupSortOrder] DEFAULT ((0)) FOR [PayCodeGroupSortOrder]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_ProductiveClassID] DEFAULT ((0)) FOR [ProductiveClassID]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_ProductiveClass] DEFAULT ('') FOR [ProductiveClass]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JobCodeID] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JobCode] DEFAULT ('') FOR [JobCode]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_PreviousActualHours] DEFAULT ((0)) FOR [PreviousActualHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_YTDActualHours] DEFAULT ((0)) FOR [YTDActualHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_CurrentBudgetHours] DEFAULT ((0)) FOR [CurrentBudgetHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JanBudgetHours] DEFAULT ((0)) FOR [JanBudgetHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_FebBudgetHours] DEFAULT ((0)) FOR [FebBudgetHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_MarBudgetHours] DEFAULT ((0)) FOR [MarBudgetHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_AprBudgetHours] DEFAULT ((0)) FOR [AprBudgetHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_MayBudgetHours] DEFAULT ((0)) FOR [MayBudgetHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [df_LineItemPayCodeGroup_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JunBudgetHours] DEFAULT ((0)) FOR [JunBudgetHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JulBudgetHours] DEFAULT ((0)) FOR [JulBudgetHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_AugBudgetHours] DEFAULT ((0)) FOR [AugBudgetHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_SepBudgetHours] DEFAULT ((0)) FOR [SepBudgetHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_OctBudgetHours] DEFAULT ((0)) FOR [OctBudgetHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_NovBudgetHours] DEFAULT ((0)) FOR [NovBudgetHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_DecBudgetHours] DEFAULT ((0)) FOR [DecBudgetHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_PreviousActualWorkingHours] DEFAULT ((0)) FOR [PreviousActualWorkingHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_YTDActualWorkingHours] DEFAULT ((0)) FOR [YTDActualWorkingHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_CurrentBudgetWorkingHours] DEFAULT ((0)) FOR [CurrentBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JanBudgetWorkingHours] DEFAULT ((0)) FOR [JanBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_FebBudgetWorkingHours] DEFAULT ((0)) FOR [FebBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_MarBudgetWorkingHours] DEFAULT ((0)) FOR [MarBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_AprBudgetWorkingHours] DEFAULT ((0)) FOR [AprBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_MayBudgetWorkingHours] DEFAULT ((0)) FOR [MayBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JunBudgetWorkingHours] DEFAULT ((0)) FOR [JunBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JulBudgetWorkingHours] DEFAULT ((0)) FOR [JulBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_AugBudgetWorkingHours] DEFAULT ((0)) FOR [AugBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_SepBudgetWorkingHours] DEFAULT ((0)) FOR [SepBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_OctBudgetWorkingHours] DEFAULT ((0)) FOR [OctBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_NovBudgetWorkingHours] DEFAULT ((0)) FOR [NovBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_DecBudgetWorkingHours] DEFAULT ((0)) FOR [DecBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_PreviousActualFTEs] DEFAULT ((0)) FOR [PreviousActualFTEs]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_YTDActualFTEs] DEFAULT ((0)) FOR [YTDActualFTEs]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_CurrentBudgetFTEs] DEFAULT ((0)) FOR [CurrentBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JanBudgetFTEs] DEFAULT ((0)) FOR [JanBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_FebBudgetFTEs] DEFAULT ((0)) FOR [FebBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_MarBudgetFTEs] DEFAULT ((0)) FOR [MarBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF__LineItemP__Origi__5393150F] DEFAULT ((0)) FOR [OriginalBudgetHours]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_AprBudgetFTEs] DEFAULT ((0)) FOR [AprBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF__LineItemP__Origi__54873948] DEFAULT ((0)) FOR [OriginalBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_MayBudgetFTEs] DEFAULT ((0)) FOR [MayBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF__LineItemP__Origi__557B5D81] DEFAULT ((0)) FOR [OriginalBudgetDollars]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JunBudgetFTEs] DEFAULT ((0)) FOR [JunBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF__LineItemP__Origi__566F81BA] DEFAULT ((0)) FOR [OriginalBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JulBudgetFTEs] DEFAULT ((0)) FOR [JulBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_AugBudgetFTEs] DEFAULT ((0)) FOR [AugBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_SepBudgetFTEs] DEFAULT ((0)) FOR [SepBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_OctBudgetFTEs] DEFAULT ((0)) FOR [OctBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_NovBudgetFTEs] DEFAULT ((0)) FOR [NovBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_DecBudgetFTEs] DEFAULT ((0)) FOR [DecBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_PreviousActualDollars] DEFAULT ((0)) FOR [PreviousActualDollars]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_YTDActualDollars] DEFAULT ((0)) FOR [YTDActualDollars]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_CurrentBudgetDollars] DEFAULT ((0)) FOR [CurrentBudgetDollars]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JanBudgetDollars] DEFAULT ((0)) FOR [JanBudgetDollars]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_FebBudgetDollars] DEFAULT ((0)) FOR [FebBudgetDollars]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_MarBudgetDollars] DEFAULT ((0)) FOR [MarBudgetDollars]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_AprBudgetDollars] DEFAULT ((0)) FOR [AprBudgetDollars]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_MayBudgetDollars] DEFAULT ((0)) FOR [MayBudgetDollars]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JunBudgetDollars] DEFAULT ((0)) FOR [JunBudgetDollars]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JulBudgetDollars] DEFAULT ((0)) FOR [JulBudgetDollars]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_AugBudgetDollars] DEFAULT ((0)) FOR [AugBudgetDollars]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_SepBudgetDollars] DEFAULT ((0)) FOR [SepBudgetDollars]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_OctBudgetDollars] DEFAULT ((0)) FOR [OctBudgetDollars]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_NovBudgetDollars] DEFAULT ((0)) FOR [NovBudgetDollars]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_DecBudgetDollars] DEFAULT ((0)) FOR [DecBudgetDollars]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_PreviousActualWageRate] DEFAULT ((0)) FOR [PreviousActualWageRate]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_YTDActualWageRate] DEFAULT ((0)) FOR [YTDActualWageRate]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_CurrentBudgetWageRate] DEFAULT ((0)) FOR [CurrentBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_CurrentBudgetWageRateMultiplier] DEFAULT ((0)) FOR [CurrentBudgetWageRateMultiplier]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JanBudgetWageRate] DEFAULT ((0)) FOR [JanBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_FebBudgetWageRate] DEFAULT ((0)) FOR [FebBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_MarBudgetWageRate] DEFAULT ((0)) FOR [MarBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_AprBudgetWageRate] DEFAULT ((0)) FOR [AprBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_MayBudgetWageRate] DEFAULT ((0)) FOR [MayBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JunBudgetWageRate] DEFAULT ((0)) FOR [JunBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_JulBudgetWageRate] DEFAULT ((0)) FOR [JulBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_AugBudgetWageRate] DEFAULT ((0)) FOR [AugBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_SepBudgetWageRate] DEFAULT ((0)) FOR [SepBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_OctBudgetWageRate] DEFAULT ((0)) FOR [OctBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_NovBudgetWageRate] DEFAULT ((0)) FOR [NovBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemPayCodeGroup] ADD CONSTRAINT [DF_LineItemPayCodeGroup_DecBudgetWageRate] DEFAULT ((0)) FOR [DecBudgetWageRate]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.LineItemProductiveClass ------------------ +--------------------------------------------- +CREATE TABLE [fp].[LineItemProductiveClass] ( + [RowID] int NOT NULL, + [FinancialLineItem] nvarchar(100) NOT NULL, + [ProductiveClassID] int NOT NULL, + [ProductiveClass] nvarchar(100) NOT NULL, + [ProductiveClassSortOrder] int NOT NULL, + [JobCodeID] int NOT NULL, + [JobCode] nvarchar(100) NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [PreviousActualHours] decimal NOT NULL, + [YTDActualHours] decimal NOT NULL, + [CurrentBudgetHours] decimal NOT NULL, + [JanBudgetHours] decimal NOT NULL, + [FebBudgetHours] decimal NOT NULL, + [MarBudgetHours] decimal NOT NULL, + [AprBudgetHours] decimal NOT NULL, + [MayBudgetHours] decimal NOT NULL, + [JunBudgetHours] decimal NOT NULL, + [JulBudgetHours] decimal NOT NULL, + [AugBudgetHours] decimal NOT NULL, + [SepBudgetHours] decimal NOT NULL, + [OctBudgetHours] decimal NOT NULL, + [NovBudgetHours] decimal NOT NULL, + [DecBudgetHours] decimal NOT NULL, + [PreviousActualWorkingHours] decimal NOT NULL, + [YTDActualWorkingHours] decimal NOT NULL, + [CurrentBudgetWorkingHours] decimal NOT NULL, + [JanBudgetWorkingHours] decimal NOT NULL, + [FebBudgetWorkingHours] decimal NOT NULL, + [MarBudgetWorkingHours] decimal NOT NULL, + [AprBudgetWorkingHours] decimal NOT NULL, + [MayBudgetWorkingHours] decimal NOT NULL, + [JunBudgetWorkingHours] decimal NOT NULL, + [JulBudgetWorkingHours] decimal NOT NULL, + [AugBudgetWorkingHours] decimal NOT NULL, + [SepBudgetWorkingHours] decimal NOT NULL, + [OctBudgetWorkingHours] decimal NOT NULL, + [NovBudgetWorkingHours] decimal NOT NULL, + [DecBudgetWorkingHours] decimal NOT NULL, + [PreviousActualFTEs] decimal NOT NULL, + [YTDActualFTEs] decimal NOT NULL, + [CurrentBudgetFTEs] decimal NOT NULL, + [JanBudgetFTEs] decimal NOT NULL, + [FebBudgetFTEs] decimal NOT NULL, + [MarBudgetFTEs] decimal NOT NULL, + [AprBudgetFTEs] decimal NOT NULL, + [MayBudgetFTEs] decimal NOT NULL, + [JunBudgetFTEs] decimal NOT NULL, + [JulBudgetFTEs] decimal NOT NULL, + [AugBudgetFTEs] decimal NOT NULL, + [SepBudgetFTEs] decimal NOT NULL, + [OctBudgetFTEs] decimal NOT NULL, + [NovBudgetFTEs] decimal NOT NULL, + [DecBudgetFTEs] decimal NOT NULL, + [PreviousActualDollars] decimal NOT NULL, + [YTDActualDollars] decimal NOT NULL, + [CurrentBudgetDollars] decimal NOT NULL, + [JanBudgetDollars] decimal NOT NULL, + [FebBudgetDollars] decimal NOT NULL, + [MarBudgetDollars] decimal NOT NULL, + [AprBudgetDollars] decimal NOT NULL, + [MayBudgetDollars] decimal NOT NULL, + [JunBudgetDollars] decimal NOT NULL, + [JulBudgetDollars] decimal NOT NULL, + [AugBudgetDollars] decimal NOT NULL, + [SepBudgetDollars] decimal NOT NULL, + [OctBudgetDollars] decimal NOT NULL, + [NovBudgetDollars] decimal NOT NULL, + [DecBudgetDollars] decimal NOT NULL, + [PreviousActualWageRate] decimal NOT NULL, + [YTDActualWageRate] decimal NOT NULL, + [CurrentBudgetWageRate] decimal NOT NULL, + [CurrentBudgetWageRateMultiplier] decimal NOT NULL, + [JanBudgetWageRate] decimal NOT NULL, + [FebBudgetWageRate] decimal NOT NULL, + [MarBudgetWageRate] decimal NOT NULL, + [AprBudgetWageRate] decimal NOT NULL, + [MayBudgetWageRate] decimal NOT NULL, + [JunBudgetWageRate] decimal NOT NULL, + [JulBudgetWageRate] decimal NOT NULL, + [AugBudgetWageRate] decimal NOT NULL, + [SepBudgetWageRate] decimal NOT NULL, + [OctBudgetWageRate] decimal NOT NULL, + [NovBudgetWageRate] decimal NOT NULL, + [DecBudgetWageRate] decimal NOT NULL, + [OriginalBudgetHours] decimal NOT NULL, + [OriginalBudgetFTEs] decimal NOT NULL, + [OriginalBudgetDollars] decimal NOT NULL, + [OriginalBudgetWageRate] decimal NOT NULL, + [AnnualizedActualHours] decimal NOT NULL, + [AnnualizedActualWorkingHours] decimal NOT NULL, + [AnnualizedActualDollars] decimal NOT NULL, + [AnnualizedActualFTEs] decimal NOT NULL, + [AnnualizedActualWageRate] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_MarBudgetFTEs] DEFAULT ((0)) FOR [MarBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_AprBudgetFTEs] DEFAULT ((0)) FOR [AprBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_MayBudgetFTEs] DEFAULT ((0)) FOR [MayBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JunBudgetFTEs] DEFAULT ((0)) FOR [JunBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JulBudgetFTEs] DEFAULT ((0)) FOR [JulBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_AugBudgetFTEs] DEFAULT ((0)) FOR [AugBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_SepBudgetFTEs] DEFAULT ((0)) FOR [SepBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_OctBudgetFTEs] DEFAULT ((0)) FOR [OctBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_NovBudgetFTEs] DEFAULT ((0)) FOR [NovBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_DecBudgetFTEs] DEFAULT ((0)) FOR [DecBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_PreviousActualDollars] DEFAULT ((0)) FOR [PreviousActualDollars]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_YTDActualDollars] DEFAULT ((0)) FOR [YTDActualDollars]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_CurrentBudgetDollars] DEFAULT ((0)) FOR [CurrentBudgetDollars]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JanBudgetDollars] DEFAULT ((0)) FOR [JanBudgetDollars]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_FebBudgetDollars] DEFAULT ((0)) FOR [FebBudgetDollars]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_MarBudgetDollars] DEFAULT ((0)) FOR [MarBudgetDollars]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF__LineItemP__Annua__0EB3DADD] DEFAULT ((0)) FOR [AnnualizedActualHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_AprBudgetDollars] DEFAULT ((0)) FOR [AprBudgetDollars]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF__LineItemP__Annua__0FA7FF16] DEFAULT ((0)) FOR [AnnualizedActualWorkingHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_MayBudgetDollars] DEFAULT ((0)) FOR [MayBudgetDollars]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF__LineItemP__Annua__109C234F] DEFAULT ((0)) FOR [AnnualizedActualDollars]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JunBudgetDollars] DEFAULT ((0)) FOR [JunBudgetDollars]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF__LineItemP__Annua__11904788] DEFAULT ((0)) FOR [AnnualizedActualFTEs]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JulBudgetDollars] DEFAULT ((0)) FOR [JulBudgetDollars]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF__LineItemP__Annua__12846BC1] DEFAULT ((0)) FOR [AnnualizedActualWageRate]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_AugBudgetDollars] DEFAULT ((0)) FOR [AugBudgetDollars]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_SepBudgetDollars] DEFAULT ((0)) FOR [SepBudgetDollars]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_OctBudgetDollars] DEFAULT ((0)) FOR [OctBudgetDollars]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_NovBudgetDollars] DEFAULT ((0)) FOR [NovBudgetDollars]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_DecBudgetDollars] DEFAULT ((0)) FOR [DecBudgetDollars]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_PreviousActualWageRate] DEFAULT ((0)) FOR [PreviousActualWageRate]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_YTDActualWageRate] DEFAULT ((0)) FOR [YTDActualWageRate]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_CurrentBudgetWageRate] DEFAULT ((0)) FOR [CurrentBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_CurrentBudgetWageRateMultiplier] DEFAULT ((0)) FOR [CurrentBudgetWageRateMultiplier]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JanBudgetWageRate] DEFAULT ((0)) FOR [JanBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_FebBudgetWageRate] DEFAULT ((0)) FOR [FebBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_MarBudgetWageRate] DEFAULT ((0)) FOR [MarBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_AprBudgetWageRate] DEFAULT ((0)) FOR [AprBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_MayBudgetWageRate] DEFAULT ((0)) FOR [MayBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JunBudgetWageRate] DEFAULT ((0)) FOR [JunBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JulBudgetWageRate] DEFAULT ((0)) FOR [JulBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_AugBudgetWageRate] DEFAULT ((0)) FOR [AugBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_SepBudgetWageRate] DEFAULT ((0)) FOR [SepBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_OctBudgetWageRate] DEFAULT ((0)) FOR [OctBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_NovBudgetWageRate] DEFAULT ((0)) FOR [NovBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_DecBudgetWageRate] DEFAULT ((0)) FOR [DecBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [df_LineItemProductiveClass_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF__LineItemP__Origi__5763A5F3] DEFAULT ((0)) FOR [OriginalBudgetHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF__LineItemP__Origi__5857CA2C] DEFAULT ((0)) FOR [OriginalBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_FinancialLineItem] DEFAULT ('') FOR [FinancialLineItem]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF__LineItemP__Origi__594BEE65] DEFAULT ((0)) FOR [OriginalBudgetDollars]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_ProductiveClassID] DEFAULT ((0)) FOR [ProductiveClassID]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF__LineItemP__Origi__5A40129E] DEFAULT ((0)) FOR [OriginalBudgetWageRate]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_ProductiveClass] DEFAULT ('') FOR [ProductiveClass]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_ProductiveClassSortOrder] DEFAULT ((0)) FOR [ProductiveClassSortOrder]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JobCodeID] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JobCode] DEFAULT ('') FOR [JobCode]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_PreviousActualHours] DEFAULT ((0)) FOR [PreviousActualHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_YTDActualHours] DEFAULT ((0)) FOR [YTDActualHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_CurrentBudgetHours] DEFAULT ((0)) FOR [CurrentBudgetHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JanBudgetHours] DEFAULT ((0)) FOR [JanBudgetHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_FebBudgetHours] DEFAULT ((0)) FOR [FebBudgetHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_MarBudgetHours] DEFAULT ((0)) FOR [MarBudgetHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_AprBudgetHours] DEFAULT ((0)) FOR [AprBudgetHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_MayBudgetHours] DEFAULT ((0)) FOR [MayBudgetHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JunBudgetHours] DEFAULT ((0)) FOR [JunBudgetHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JulBudgetHours] DEFAULT ((0)) FOR [JulBudgetHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_AugBudgetHours] DEFAULT ((0)) FOR [AugBudgetHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_SepBudgetHours] DEFAULT ((0)) FOR [SepBudgetHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_OctBudgetHours] DEFAULT ((0)) FOR [OctBudgetHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_NovBudgetHours] DEFAULT ((0)) FOR [NovBudgetHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_DecBudgetHours] DEFAULT ((0)) FOR [DecBudgetHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_PreviousActualWorkingHours] DEFAULT ((0)) FOR [PreviousActualWorkingHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_YTDActualWorkingHours] DEFAULT ((0)) FOR [YTDActualWorkingHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_CurrentBudgetWorkingHours] DEFAULT ((0)) FOR [CurrentBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JanBudgetWorkingHours] DEFAULT ((0)) FOR [JanBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_FebBudgetWorkingHours] DEFAULT ((0)) FOR [FebBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_MarBudgetWorkingHours] DEFAULT ((0)) FOR [MarBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_AprBudgetWorkingHours] DEFAULT ((0)) FOR [AprBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_MayBudgetWorkingHours] DEFAULT ((0)) FOR [MayBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JunBudgetWorkingHours] DEFAULT ((0)) FOR [JunBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JulBudgetWorkingHours] DEFAULT ((0)) FOR [JulBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_AugBudgetWorkingHours] DEFAULT ((0)) FOR [AugBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_SepBudgetWorkingHours] DEFAULT ((0)) FOR [SepBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_OctBudgetWorkingHours] DEFAULT ((0)) FOR [OctBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_NovBudgetWorkingHours] DEFAULT ((0)) FOR [NovBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_DecBudgetWorkingHours] DEFAULT ((0)) FOR [DecBudgetWorkingHours]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_PreviousActualFTEs] DEFAULT ((0)) FOR [PreviousActualFTEs]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_YTDActualFTEs] DEFAULT ((0)) FOR [YTDActualFTEs]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_CurrentBudgetFTEs] DEFAULT ((0)) FOR [CurrentBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_JanBudgetFTEs] DEFAULT ((0)) FOR [JanBudgetFTEs]; GO +ALTER TABLE [fp].[LineItemProductiveClass] ADD CONSTRAINT [DF_LineItemProductiveClass_FebBudgetFTEs] DEFAULT ((0)) FOR [FebBudgetFTEs]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ModelSectionMap ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ModelSectionMap] ( + [ModelSectionMapID] int NOT NULL, + [OBModelSectionName] nvarchar(200) NOT NULL, + [APEModelSectionID] tinyint NOT NULL, + [APEModelSectionName] nvarchar(200) NOT NULL, + PRIMARY KEY ([ModelSectionMapID]) +); +GO +ALTER TABLE [fp].[ModelSectionMap] ADD CONSTRAINT [DF__ModelSect__OBMod__03C8712D] DEFAULT ('') FOR [OBModelSectionName]; GO +ALTER TABLE [fp].[ModelSectionMap] ADD CONSTRAINT [DF__ModelSect__APEMo__04BC9566] DEFAULT ((0)) FOR [APEModelSectionID]; GO +ALTER TABLE [fp].[ModelSectionMap] ADD CONSTRAINT [DF__ModelSect__APEMo__05B0B99F] DEFAULT ('') FOR [APEModelSectionName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.NSOverrideFlexConfigAssignment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[NSOverrideFlexConfigAssignment] ( + [OverrideFlexConfigGUID] uniqueidentifier NOT NULL, + [AccountID] int NOT NULL, + [RowID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [Unique_NSOverrideFlexConfigAssignment_Account_FlexGUID] ON [fp].[NSOverrideFlexConfigAssignment] ([OverrideFlexConfigGUID], [AccountID]); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.NonStaffingExpenseFlexingConfig ------------------ +--------------------------------------------- +CREATE TABLE [fp].[NonStaffingExpenseFlexingConfig] ( + [EntityGroupConfigGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [FlexMethodID] smallint NOT NULL, + PRIMARY KEY ([EntityGroupConfigGUID], [DepartmentID]) +); +GO +ALTER TABLE [fp].[NonStaffingExpenseFlexingConfig] ADD CONSTRAINT [FK__NonStaffi__Depar__3ED8EC6C] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[NonStaffingExpenseFlexingConfig] ADD CONSTRAINT [df_NonStaffingExpenseFlexingConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO +ALTER TABLE [fp].[NonStaffingExpenseFlexingConfig] ADD CONSTRAINT [DF__NonStaffi__Depar__7891F199] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[NonStaffingExpenseFlexingConfig] ADD CONSTRAINT [DF__NonStaffi__FlexM__798615D2] DEFAULT ((0)) FOR [FlexMethodID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.NonStaffingExpenseFlexingOverrideConfig ------------------ +--------------------------------------------- +CREATE TABLE [fp].[NonStaffingExpenseFlexingOverrideConfig] ( + [EntityGroupConfigGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FlexMethodID] smallint NOT NULL, + [RowID] int NOT NULL, + [OverrideFlexConfigGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [Unique_NonStaffingExpenseFlexingOverrideConfig_EC_Dept_Account] ON [fp].[NonStaffingExpenseFlexingOverrideConfig] ([EntityGroupConfigGUID], [DepartmentID], [AccountID]); +CREATE UNIQUE NONCLUSTERED INDEX [UQ__NonStaff__173FA2A66EA0FA40] ON [fp].[NonStaffingExpenseFlexingOverrideConfig] ([OverrideFlexConfigGUID]); +GO +ALTER TABLE [fp].[NonStaffingExpenseFlexingOverrideConfig] ADD CONSTRAINT [FK__NonStaffi__Accou__4585E9FB] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [fp].[NonStaffingExpenseFlexingOverrideConfig] ADD CONSTRAINT [FK__NonStaffi__Depar__4491C5C2] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[NonStaffingExpenseFlexingOverrideConfig] ADD CONSTRAINT [df_NonStaffingExpenseFlexingOverrideConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO +ALTER TABLE [fp].[NonStaffingExpenseFlexingOverrideConfig] ADD CONSTRAINT [DF__NonStaffi__Depar__654A12FB] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[NonStaffingExpenseFlexingOverrideConfig] ADD CONSTRAINT [DF__NonStaffi__Accou__663E3734] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[NonStaffingExpenseFlexingOverrideConfig] ADD CONSTRAINT [DF__NonStaffi__FlexM__67325B6D] DEFAULT ((0)) FOR [FlexMethodID]; GO +ALTER TABLE [fp].[NonStaffingExpenseFlexingOverrideConfig] ADD CONSTRAINT [DF__NonStaffi__Overr__6FC7A16E] DEFAULT (newid()) FOR [OverrideFlexConfigGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.NonStaffingVariabilityConfig ------------------ +--------------------------------------------- +CREATE TABLE [fp].[NonStaffingVariabilityConfig] ( + [EntityGroupConfigGUID] uniqueidentifier NOT NULL, + [AccountID] int NOT NULL, + [Variability] decimal NOT NULL, + PRIMARY KEY ([EntityGroupConfigGUID], [AccountID]) +); +GO +ALTER TABLE [fp].[NonStaffingVariabilityConfig] ADD CONSTRAINT [DF__NonStaffi__Accou__0601C6A7] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[NonStaffingVariabilityConfig] ADD CONSTRAINT [DF__NonStaffi__Varia__06F5EAE0] DEFAULT ((0)) FOR [Variability]; GO +ALTER TABLE [fp].[NonStaffingVariabilityConfig] ADD CONSTRAINT [df_NonStaffingVariabilityConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.OldToNewChargeVolumeIDMapping ------------------ +--------------------------------------------- +CREATE TABLE [fp].[OldToNewChargeVolumeIDMapping] ( + [RowID] int NOT NULL, + [OldChargeVolumeID] int NOT NULL, + [NewChargeVolumeID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[OldToNewChargeVolumeIDMapping] ADD CONSTRAINT [DF__OldToNewC__OldCh__78B617A7] DEFAULT ((0)) FOR [OldChargeVolumeID]; GO +ALTER TABLE [fp].[OldToNewChargeVolumeIDMapping] ADD CONSTRAINT [DF__OldToNewC__NewCh__79AA3BE0] DEFAULT ((0)) FOR [NewChargeVolumeID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.OldToNewGeneralLedgerIDMapping ------------------ +--------------------------------------------- +CREATE TABLE [fp].[OldToNewGeneralLedgerIDMapping] ( + [RowID] int NOT NULL, + [OldGeneralLedgerID] int NOT NULL, + [NewGeneralLedgerID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[OldToNewGeneralLedgerIDMapping] ADD CONSTRAINT [DF__OldToNewG__OldGe__010144E5] DEFAULT ((0)) FOR [OldGeneralLedgerID]; GO +ALTER TABLE [fp].[OldToNewGeneralLedgerIDMapping] ADD CONSTRAINT [DF__OldToNewG__NewGe__01F5691E] DEFAULT ((0)) FOR [NewGeneralLedgerID]; GO +ALTER TABLE [fp].[OldToNewGeneralLedgerIDMapping] ADD CONSTRAINT [DF__OldToNewG__UnitT__02E98D57] DEFAULT ((0)) FOR [UnitTypeID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.OldToNewServiceLineEncounterIDMapping ------------------ +--------------------------------------------- +CREATE TABLE [fp].[OldToNewServiceLineEncounterIDMapping] ( + [RowID] int NOT NULL, + [OldServiceLineEncounterID] int NOT NULL, + [NewServiceLineEncounterID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[OldToNewServiceLineEncounterIDMapping] ADD CONSTRAINT [DF__OldToNewS__OldSe__74E586C3] DEFAULT ((0)) FOR [OldServiceLineEncounterID]; GO +ALTER TABLE [fp].[OldToNewServiceLineEncounterIDMapping] ADD CONSTRAINT [DF__OldToNewS__NewSe__75D9AAFC] DEFAULT ((0)) FOR [NewServiceLineEncounterID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.OldToNewStaffingIDMapping ------------------ +--------------------------------------------- +CREATE TABLE [fp].[OldToNewStaffingIDMapping] ( + [RowID] int NOT NULL, + [OldStaffingID] int NOT NULL, + [NewStaffingID] int NOT NULL, + [UnitTypeID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[OldToNewStaffingIDMapping] ADD CONSTRAINT [DF__OldToNewS__OldSt__5C307E40] DEFAULT ((0)) FOR [OldStaffingID]; GO +ALTER TABLE [fp].[OldToNewStaffingIDMapping] ADD CONSTRAINT [DF__OldToNewS__NewSt__5D24A279] DEFAULT ((0)) FOR [NewStaffingID]; GO +ALTER TABLE [fp].[OldToNewStaffingIDMapping] ADD CONSTRAINT [DF__OldToNewS__UnitT__5E18C6B2] DEFAULT ((0)) FOR [UnitTypeID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.OnePlanPerformanceTestValidationResult ------------------ +--------------------------------------------- +CREATE TABLE [fp].[OnePlanPerformanceTestValidationResult] ( + [TestResultID] int NOT NULL, + [PlanSectionID] int NOT NULL, + [BasisID] int NOT NULL, + [TableName] nvarchar(100) NOT NULL, + [ColumnName] nvarchar(100) NOT NULL, + [BeforeValue01] decimal NOT NULL, + [BeforeValue02] decimal NOT NULL, + [BeforeValue03] decimal NOT NULL, + [BeforeValue04] decimal NOT NULL, + [BeforeValue05] decimal NOT NULL, + [BeforeValue06] decimal NOT NULL, + [BeforeValue07] decimal NOT NULL, + [BeforeValue08] decimal NOT NULL, + [BeforeValue09] decimal NOT NULL, + [BeforeValue10] decimal NOT NULL, + [BeforeValue11] decimal NOT NULL, + [BeforeValue12] decimal NOT NULL, + [AfterValue01] decimal NOT NULL, + [AfterValue02] decimal NOT NULL, + [AfterValue03] decimal NOT NULL, + [AfterValue04] decimal NOT NULL, + [AfterValue05] decimal NOT NULL, + [AfterValue06] decimal NOT NULL, + [AfterValue07] decimal NOT NULL, + [AfterValue08] decimal NOT NULL, + [AfterValue09] decimal NOT NULL, + [AfterValue10] decimal NOT NULL, + [AfterValue11] decimal NOT NULL, + [AfterValue12] decimal NOT NULL, + [Variance01] decimal NULL, + [Variance02] decimal NULL, + [Variance03] decimal NULL, + [Variance04] decimal NULL, + [Variance05] decimal NULL, + [Variance06] decimal NULL, + [Variance07] decimal NULL, + [Variance08] decimal NULL, + [Variance09] decimal NULL, + [Variance10] decimal NULL, + [Variance11] decimal NULL, + [Variance12] decimal NULL +); +GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__TestR__000EB75A] DEFAULT ((0)) FOR [TestResultID]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__PlanS__0102DB93] DEFAULT ((0)) FOR [PlanSectionID]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Basis__01F6FFCC] DEFAULT ((0)) FOR [BasisID]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Table__02EB2405] DEFAULT ('') FOR [TableName]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Colum__03DF483E] DEFAULT ('') FOR [ColumnName]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__04D36C77] DEFAULT ((0)) FOR [BeforeValue01]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__05C790B0] DEFAULT ((0)) FOR [BeforeValue02]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__06BBB4E9] DEFAULT ((0)) FOR [BeforeValue03]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__07AFD922] DEFAULT ((0)) FOR [BeforeValue04]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__08A3FD5B] DEFAULT ((0)) FOR [BeforeValue05]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__09982194] DEFAULT ((0)) FOR [BeforeValue06]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__0A8C45CD] DEFAULT ((0)) FOR [BeforeValue07]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__0B806A06] DEFAULT ((0)) FOR [BeforeValue08]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__0C748E3F] DEFAULT ((0)) FOR [BeforeValue09]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__0D68B278] DEFAULT ((0)) FOR [BeforeValue10]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__0E5CD6B1] DEFAULT ((0)) FOR [BeforeValue11]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__Befor__0F50FAEA] DEFAULT ((0)) FOR [BeforeValue12]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__10451F23] DEFAULT ((0)) FOR [AfterValue01]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__1139435C] DEFAULT ((0)) FOR [AfterValue02]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__122D6795] DEFAULT ((0)) FOR [AfterValue03]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__13218BCE] DEFAULT ((0)) FOR [AfterValue04]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__1415B007] DEFAULT ((0)) FOR [AfterValue05]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__1509D440] DEFAULT ((0)) FOR [AfterValue06]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__15FDF879] DEFAULT ((0)) FOR [AfterValue07]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__16F21CB2] DEFAULT ((0)) FOR [AfterValue08]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__17E640EB] DEFAULT ((0)) FOR [AfterValue09]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__18DA6524] DEFAULT ((0)) FOR [AfterValue10]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__19CE895D] DEFAULT ((0)) FOR [AfterValue11]; GO +ALTER TABLE [fp].[OnePlanPerformanceTestValidationResult] ADD CONSTRAINT [DF__OnePlanPe__After__1AC2AD96] DEFAULT ((0)) FOR [AfterValue12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.PayrollVariabilityConfig ------------------ +--------------------------------------------- +CREATE TABLE [fp].[PayrollVariabilityConfig] ( + [EntityGroupConfigGUID] uniqueidentifier NOT NULL, + [JobCodeGroupID] int NOT NULL, + [JobCodeID] int NOT NULL, + [Variability] decimal NOT NULL, + PRIMARY KEY ([EntityGroupConfigGUID], [JobCodeGroupID], [JobCodeID]) +); + +CREATE NONCLUSTERED INDEX [NCNU_PayrollVariabilityConfig] ON [fp].[PayrollVariabilityConfig] ([EntityGroupConfigGUID], [JobCodeID]) INCLUDE ([Variability]); +GO +ALTER TABLE [fp].[PayrollVariabilityConfig] ADD CONSTRAINT [df_PayrollVariabilityConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO +ALTER TABLE [fp].[PayrollVariabilityConfig] ADD CONSTRAINT [DF__PayrollVa__JobCo__4C1F3DD5] DEFAULT ((0)) FOR [JobCodeGroupID]; GO +ALTER TABLE [fp].[PayrollVariabilityConfig] ADD CONSTRAINT [DF__PayrollVa__JobCo__4D13620E] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[PayrollVariabilityConfig] ADD CONSTRAINT [DF__PayrollVa__Varia__4E078647] DEFAULT ((0)) FOR [Variability]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.PercentageOfChargeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[PercentageOfChargeHistory] ( + [PercentageOfChargeHistoryGUID] uniqueidentifier NOT NULL, + [Date] datetime NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(max) NOT NULL, + [ExcelFile] varbinary(max) NULL, + PRIMARY KEY ([PercentageOfChargeHistoryGUID]) +); +GO +ALTER TABLE [fp].[PercentageOfChargeHistory] ADD CONSTRAINT [df_PercentageOfChargeHistory_PercentageOfChargeHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PercentageOfChargeHistoryGUID]; GO +ALTER TABLE [fp].[PercentageOfChargeHistory] ADD CONSTRAINT [df_PercentageOfChargeHistory_AuthorGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[PercentageOfChargeHistory] ADD CONSTRAINT [DF__Percentage__Date__39201316] DEFAULT (getdate()) FOR [Date]; GO +ALTER TABLE [fp].[PercentageOfChargeHistory] ADD CONSTRAINT [DF__Percentag__Autho__3B085B88] DEFAULT ('') FOR [AuthorFullName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.PercentageOfChargeImport ------------------ +--------------------------------------------- +CREATE TABLE [fp].[PercentageOfChargeImport] ( + [BudgetConfigID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Value01] decimal NOT NULL, + [Value02] decimal NOT NULL, + [Value03] decimal NOT NULL, + [Value04] decimal NOT NULL, + [Value05] decimal NOT NULL, + [Value06] decimal NOT NULL, + [Value07] decimal NOT NULL, + [Value08] decimal NOT NULL, + [Value09] decimal NOT NULL, + [Value10] decimal NOT NULL, + [Value11] decimal NOT NULL, + [Value12] decimal NOT NULL, + PRIMARY KEY ([BudgetConfigID], [TimeClassID], [DepartmentID], [AccountID]) +); +GO +ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [FK_PercentageOfChargeImport_Account] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [FK_PercentageOfChargeImport_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Budge__25191A69] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Depar__260D3EA2] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Accou__27F58714] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__TimeC__29DDCF86] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__2AD1F3BF] DEFAULT ((0)) FOR [Value01]; GO +ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__2BC617F8] DEFAULT ((0)) FOR [Value02]; GO +ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__2CBA3C31] DEFAULT ((0)) FOR [Value03]; GO +ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__2DAE606A] DEFAULT ((0)) FOR [Value04]; GO +ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__2EA284A3] DEFAULT ((0)) FOR [Value05]; GO +ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__2F96A8DC] DEFAULT ((0)) FOR [Value06]; GO +ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__308ACD15] DEFAULT ((0)) FOR [Value07]; GO +ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__317EF14E] DEFAULT ((0)) FOR [Value08]; GO +ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__32731587] DEFAULT ((0)) FOR [Value09]; GO +ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__336739C0] DEFAULT ((0)) FOR [Value10]; GO +ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__345B5DF9] DEFAULT ((0)) FOR [Value11]; GO +ALTER TABLE [fp].[PercentageOfChargeImport] ADD CONSTRAINT [DF__Percentag__Value__354F8232] DEFAULT ((0)) FOR [Value12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.PerformanceTestingSetting ------------------ +--------------------------------------------- +CREATE TABLE [fp].[PerformanceTestingSetting] ( + [SystemSettingID] int NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Description] nvarchar(400) NOT NULL, + [Value] nvarchar(max) NOT NULL, + [IsEditable] bit NOT NULL, + [ColumnType] int NOT NULL, + [DefaultValue] nvarchar(100) NOT NULL, + [IsEncrypted] bit NOT NULL, + [DateCreated] date NOT NULL, + PRIMARY KEY ([SystemSettingID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_PerformanceTestingSetting_Unique] ON [fp].[PerformanceTestingSetting] ([Name]); +GO +ALTER TABLE [fp].[PerformanceTestingSetting] ADD CONSTRAINT [DF__Performanc__Name__5247ECAA] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fp].[PerformanceTestingSetting] ADD CONSTRAINT [DF__Performan__Descr__533C10E3] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fp].[PerformanceTestingSetting] ADD CONSTRAINT [DF__Performan__Value__5430351C] DEFAULT ('') FOR [Value]; GO +ALTER TABLE [fp].[PerformanceTestingSetting] ADD CONSTRAINT [DF__Performan__IsEdi__55245955] DEFAULT ((0)) FOR [IsEditable]; GO +ALTER TABLE [fp].[PerformanceTestingSetting] ADD CONSTRAINT [DF__Performan__Colum__56187D8E] DEFAULT ((0)) FOR [ColumnType]; GO +ALTER TABLE [fp].[PerformanceTestingSetting] ADD CONSTRAINT [DF__Performan__Defau__570CA1C7] DEFAULT ('') FOR [DefaultValue]; GO +ALTER TABLE [fp].[PerformanceTestingSetting] ADD CONSTRAINT [DF__Performan__IsEnc__5800C600] DEFAULT ((0)) FOR [IsEncrypted]; GO +ALTER TABLE [fp].[PerformanceTestingSetting] ADD CONSTRAINT [DF__Performan__DateC__58F4EA39] DEFAULT (getdate()) FOR [DateCreated]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.PerformanceTestingSettingBySection ------------------ +--------------------------------------------- +CREATE TABLE [fp].[PerformanceTestingSettingBySection] ( + [SectionID] int NOT NULL, + [Description] nvarchar(100) NOT NULL, + [NumberOfRecordsInImport_LocalAdmin] int NOT NULL, + [NumberOfRecordsInImport_SysAdmin] int NOT NULL, + PRIMARY KEY ([SectionID]) +); +GO +ALTER TABLE [fp].[PerformanceTestingSettingBySection] ADD CONSTRAINT [DF__Performan__Numbe__053757DD] DEFAULT ((100)) FOR [NumberOfRecordsInImport_SysAdmin]; GO +ALTER TABLE [fp].[PerformanceTestingSettingBySection] ADD CONSTRAINT [DF__Performan__Secti__1D8BA256] DEFAULT ((0)) FOR [SectionID]; GO +ALTER TABLE [fp].[PerformanceTestingSettingBySection] ADD CONSTRAINT [DF__Performan__Descr__1E7FC68F] DEFAULT ((0)) FOR [Description]; GO +ALTER TABLE [fp].[PerformanceTestingSettingBySection] ADD CONSTRAINT [DF__Performan__Numbe__1F73EAC8] DEFAULT ((0)) FOR [NumberOfRecordsInImport_LocalAdmin]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.PlanEditorCustomReportLink ------------------ +--------------------------------------------- +CREATE TABLE [fp].[PlanEditorCustomReportLink] ( + [CustomReportLinkGUID] uniqueidentifier NOT NULL, + [ReportGUID] uniqueidentifier NOT NULL, + [SectionID] int NOT NULL, + PRIMARY KEY ([CustomReportLinkGUID]) +); +GO +ALTER TABLE [fp].[PlanEditorCustomReportLink] ADD CONSTRAINT [FK_FpPlanEditorCustomReportLink_Report] FOREIGN KEY ([ReportGUID]) REFERENCES [dbo].[REReport] ([ReportGUID]); GO +ALTER TABLE [fp].[PlanEditorCustomReportLink] ADD CONSTRAINT [DF__PlanEdito__Custo__35462BE8] DEFAULT (newid()) FOR [CustomReportLinkGUID]; GO +ALTER TABLE [fp].[PlanEditorCustomReportLink] ADD CONSTRAINT [DF__PlanEdito__Secti__372E745A] DEFAULT ((-1)) FOR [SectionID]; GO +ALTER TABLE [fp].[PlanEditorCustomReportLink] ADD CONSTRAINT [df_PlanEditorCustomReportLink_ReportGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ReportGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.PlanManagementHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[PlanManagementHistory] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [AuthorName] nvarchar(250) NOT NULL, + [DateTimeUTC] datetime NOT NULL, + [SourceTimeClassID] tinyint NOT NULL, + [IsEngineDisabled] bit NOT NULL, + [TargetTimeClassID] tinyint NOT NULL, + [IsMonthsLoadedIncluded] bit NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[PlanManagementHistory] ADD CONSTRAINT [DF__PlanManag__IsEng__03746893] DEFAULT ((0)) FOR [IsEngineDisabled]; GO +ALTER TABLE [fp].[PlanManagementHistory] ADD CONSTRAINT [DF__PlanManag__Targe__2085A88D] DEFAULT ((0)) FOR [TargetTimeClassID]; GO +ALTER TABLE [fp].[PlanManagementHistory] ADD CONSTRAINT [DF__PlanManag__IsMon__263E81E3] DEFAULT ((0)) FOR [IsMonthsLoadedIncluded]; GO +ALTER TABLE [fp].[PlanManagementHistory] ADD CONSTRAINT [DF__BudgetSta__Budge__29836C34] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[PlanManagementHistory] ADD CONSTRAINT [DF__BudgetSta__UserG__2A77906D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [fp].[PlanManagementHistory] ADD CONSTRAINT [DF__BudgetSta__Autho__2B6BB4A6] DEFAULT ('') FOR [AuthorName]; GO +ALTER TABLE [fp].[PlanManagementHistory] ADD CONSTRAINT [DF__BudgetSta__DateT__2C5FD8DF] DEFAULT (getutcdate()) FOR [DateTimeUTC]; GO +ALTER TABLE [fp].[PlanManagementHistory] ADD CONSTRAINT [DF__BudgetSta__TimeC__727EE6BB] DEFAULT ((0)) FOR [SourceTimeClassID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.PlanSection ------------------ +--------------------------------------------- +CREATE TABLE [fp].[PlanSection] ( + [HistoryItemGUID] uniqueidentifier NOT NULL, + [PlanSectionID] int NOT NULL, + [Description] nvarchar(200) NOT NULL, + [SortOrder] int NOT NULL, + [PlanSectionGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([PlanSectionID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [NCU_PlanSectionDescription] ON [fp].[PlanSection] ([Description]) INCLUDE ([PlanSectionID]); +GO +ALTER TABLE [fp].[PlanSection] ADD CONSTRAINT [DF__PlanSecti__Histo__3BFEE1C6] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fp].[PlanSection] ADD CONSTRAINT [DF__PlanSecti__Descr__3DE72A38] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fp].[PlanSection] ADD CONSTRAINT [DF__PlanSecti__SortO__3EDB4E71] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fp].[PlanSection] ADD CONSTRAINT [DF__PlanSecti__PlanS__3FCF72AA] DEFAULT (newid()) FOR [PlanSectionGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.PlanSectionSettings ------------------ +--------------------------------------------- +CREATE TABLE [fp].[PlanSectionSettings] ( + [PlanSectionID] int NOT NULL, + [AdjustmentRowLimit] int NOT NULL +); +GO +ALTER TABLE [fp].[PlanSectionSettings] ADD CONSTRAINT [FK__PlanSecti__PlanS__4BB6F1F9] FOREIGN KEY ([PlanSectionID]) REFERENCES [fp].[PlanSection] ([PlanSectionID]); GO +ALTER TABLE [fp].[PlanSectionSettings] ADD CONSTRAINT [DF__PlanSecti__PlanS__49CEA987] DEFAULT ((0)) FOR [PlanSectionID]; GO +ALTER TABLE [fp].[PlanSectionSettings] ADD CONSTRAINT [DF__PlanSecti__Adjus__4AC2CDC0] DEFAULT ((3000000)) FOR [AdjustmentRowLimit]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.PlanSubsection ------------------ +--------------------------------------------- +CREATE TABLE [fp].[PlanSubsection] ( + [SubsectionID] int NOT NULL, + [PlanSectionID] int NOT NULL, + [Subsection] varchar(100) NOT NULL, + PRIMARY KEY ([SubsectionID]) +); +GO +ALTER TABLE [fp].[PlanSubsection] ADD CONSTRAINT [FK_PlanSubsection] FOREIGN KEY ([PlanSectionID]) REFERENCES [fp].[PlanSection] ([PlanSectionID]); GO +ALTER TABLE [fp].[PlanSubsection] ADD CONSTRAINT [DF__PlanSubse__PlanS__19C9C553] DEFAULT ((0)) FOR [PlanSectionID]; GO +ALTER TABLE [fp].[PlanSubsection] ADD CONSTRAINT [DF__PlanSubse__Subse__1ABDE98C] DEFAULT ('') FOR [Subsection]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.PositionControl ------------------ +--------------------------------------------- +CREATE TABLE [fp].[PositionControl] ( + [PositionControlID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [DepartmentID] int NOT NULL, + [CostCenter] nvarchar(200) NOT NULL, + [PositionControlNumber] nvarchar(100) NOT NULL, + [EmployeeID] int NOT NULL, + [EmployeeCode] nvarchar(400) NOT NULL, + [EmployeeName] nvarchar(800) NOT NULL, + [JobCodeID] int NOT NULL, + [JobStatus] nvarchar(50) NOT NULL, + [HireDate] datetime NOT NULL, + [BiweeklyHours] decimal NOT NULL, + [AnnualFTE] decimal NOT NULL, + [HourlyRates] decimal NOT NULL, + [AnnualSalary] decimal NOT NULL +); +GO +ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__Budge__37F0BBC5] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__Depar__38E4DFFE] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__CostC__39D90437] DEFAULT ('') FOR [CostCenter]; GO +ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__Posit__3ACD2870] DEFAULT ('') FOR [PositionControlNumber]; GO +ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__Emplo__3BC14CA9] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__Emplo__3CB570E2] DEFAULT ('') FOR [EmployeeCode]; GO +ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__Emplo__3DA9951B] DEFAULT ('') FOR [EmployeeName]; GO +ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__JobCo__3E9DB954] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__JobSt__3F91DD8D] DEFAULT ((0)) FOR [JobStatus]; GO +ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__HireD__408601C6] DEFAULT (getdate()) FOR [HireDate]; GO +ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__Biwee__417A25FF] DEFAULT ((0)) FOR [BiweeklyHours]; GO +ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__Annua__426E4A38] DEFAULT ((0)) FOR [AnnualFTE]; GO +ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__Hourl__43626E71] DEFAULT ((0)) FOR [HourlyRates]; GO +ALTER TABLE [fp].[PositionControl] ADD CONSTRAINT [DF__PositionC__Annua__445692AA] DEFAULT ((0)) FOR [AnnualSalary]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.PrimaryStatisticsConfig ------------------ +--------------------------------------------- +CREATE TABLE [fp].[PrimaryStatisticsConfig] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [EntityGroupConfigGUID] uniqueidentifier NOT NULL, + [IsRevenue] bit NOT NULL, + [IsStaffing] bit NOT NULL, + [IsNonStaffing] bit NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[PrimaryStatisticsConfig] ADD CONSTRAINT [DF__FlexingSt__IsRev__6C2C1AB4] DEFAULT ((0)) FOR [IsRevenue]; GO +ALTER TABLE [fp].[PrimaryStatisticsConfig] ADD CONSTRAINT [DF__FlexingSt__IsSta__6D203EED] DEFAULT ((0)) FOR [IsStaffing]; GO +ALTER TABLE [fp].[PrimaryStatisticsConfig] ADD CONSTRAINT [DF__FlexingSt__IsNon__6E146326] DEFAULT ((0)) FOR [IsNonStaffing]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.PrimaryStatisticsConfigScoreSourceDepartments ------------------ +--------------------------------------------- +CREATE TABLE [fp].[PrimaryStatisticsConfigScoreSourceDepartments] ( + [ScoreSourceDepartmentGUID] uniqueidentifier NOT NULL, + [PrimaryStatisticsConfigID] int NOT NULL, + [ScoreValue] nvarchar(max) NOT NULL, + PRIMARY KEY ([ScoreSourceDepartmentGUID]) +); +GO +ALTER TABLE [fp].[PrimaryStatisticsConfigScoreSourceDepartments] ADD CONSTRAINT [DF__PrimarySt__Score__194D046B] DEFAULT (newid()) FOR [ScoreSourceDepartmentGUID]; GO +ALTER TABLE [fp].[PrimaryStatisticsConfigScoreSourceDepartments] ADD CONSTRAINT [DF__PrimarySt__Prima__1A4128A4] DEFAULT ((0)) FOR [PrimaryStatisticsConfigID]; GO +ALTER TABLE [fp].[PrimaryStatisticsConfigScoreSourceDepartments] ADD CONSTRAINT [DF__PrimarySt__Score__1B354CDD] DEFAULT ('') FOR [ScoreValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.PrimaryStatisticsConfigSourceDepartments ------------------ +--------------------------------------------- +CREATE TABLE [fp].[PrimaryStatisticsConfigSourceDepartments] ( + [SourceDepartmentGUID] uniqueidentifier NOT NULL, + [PrimaryStatisticsConfigID] int NOT NULL, + [DepartmentID] int NOT NULL, + PRIMARY KEY ([SourceDepartmentGUID]) +); +GO +ALTER TABLE [fp].[PrimaryStatisticsConfigSourceDepartments] ADD CONSTRAINT [DF__PrimarySt__Sourc__14884F4E] DEFAULT (newid()) FOR [SourceDepartmentGUID]; GO +ALTER TABLE [fp].[PrimaryStatisticsConfigSourceDepartments] ADD CONSTRAINT [DF__PrimarySt__Prima__157C7387] DEFAULT ((0)) FOR [PrimaryStatisticsConfigID]; GO +ALTER TABLE [fp].[PrimaryStatisticsConfigSourceDepartments] ADD CONSTRAINT [DF__PrimarySt__Depar__167097C0] DEFAULT ((0)) FOR [DepartmentID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ProvCompAddProviderAdjustment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ProvCompAddProviderAdjustment] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeGroupID] int NOT NULL, + [ProductiveClassID] int NOT NULL, + [EmployeeID] int NOT NULL, + [VariabilityID] int NOT NULL, + [UnitTypeID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [Value01] decimal NOT NULL, + [Value02] decimal NOT NULL, + [Value03] decimal NOT NULL, + [Value04] decimal NOT NULL, + [Value05] decimal NOT NULL, + [Value06] decimal NOT NULL, + [Value07] decimal NOT NULL, + [Value08] decimal NOT NULL, + [Value09] decimal NOT NULL, + [Value10] decimal NOT NULL, + [Value11] decimal NOT NULL, + [Value12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [FK_FpProvCompAddProviderAdjustment_AdjustmentGuid] FOREIGN KEY ([AdjustmentGUID]) REFERENCES [fp].[StaffingAdjustment] ([AdjustmentGUID]); GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Budge__63DA2AFB] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Adjus__64CE4F34] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Entit__65C2736D] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Depar__66B697A6] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Provi__67AABBDF] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Provi__689EE018] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Provi__69930451] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Provi__6A87288A] DEFAULT ((0)) FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__JobCo__6B7B4CC3] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__PayCo__6C6F70FC] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Produ__6D639535] DEFAULT ((0)) FOR [ProductiveClassID]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Emplo__6E57B96E] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__UnitT__6F4BDDA7] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Varia__704001E0] DEFAULT ((0)) FOR [VariabilityID]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__TimeC__71342619] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Budge__72284A52] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__IsRec__731C6E8B] DEFAULT ((0)) FOR [IsRecordDeleted]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__741092C4] DEFAULT ((0)) FOR [Value01]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__7504B6FD] DEFAULT ((0)) FOR [Value02]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__75F8DB36] DEFAULT ((0)) FOR [Value03]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__76ECFF6F] DEFAULT ((0)) FOR [Value04]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__77E123A8] DEFAULT ((0)) FOR [Value05]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__78D547E1] DEFAULT ((0)) FOR [Value06]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__79C96C1A] DEFAULT ((0)) FOR [Value07]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__7ABD9053] DEFAULT ((0)) FOR [Value08]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__7BB1B48C] DEFAULT ((0)) FOR [Value09]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__7CA5D8C5] DEFAULT ((0)) FOR [Value10]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__7D99FCFE] DEFAULT ((0)) FOR [Value11]; GO +ALTER TABLE [fp].[ProvCompAddProviderAdjustment] ADD CONSTRAINT [DF__ProvCompA__Value__7E8E2137] DEFAULT ((0)) FOR [Value12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ProvCompAddProviderSummaryDetails ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ProvCompAddProviderSummaryDetails] ( + [RowID] int NOT NULL, + [SummaryID] int NOT NULL, + [AnnualImpact] decimal NOT NULL, + [ProjectionImpact] decimal NOT NULL, + [BudgetImpact] decimal NOT NULL, + [UnitTypeID] int NOT NULL, + [TargetImpact] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ProvCompAddProviderSummaryDetails] ADD CONSTRAINT [FK_FP_ProvCompAddProviderSummaryDetails_SummaryID] FOREIGN KEY ([SummaryID]) REFERENCES [fp].[StatisticAddProviderSummary] ([SummaryID]); GO +ALTER TABLE [fp].[ProvCompAddProviderSummaryDetails] ADD CONSTRAINT [DF__ProvCompA__Summa__2D491020] DEFAULT ((0)) FOR [SummaryID]; GO +ALTER TABLE [fp].[ProvCompAddProviderSummaryDetails] ADD CONSTRAINT [DF__ProvCompA__Annua__2E3D3459] DEFAULT ((0)) FOR [AnnualImpact]; GO +ALTER TABLE [fp].[ProvCompAddProviderSummaryDetails] ADD CONSTRAINT [DF__ProvCompA__Proje__2F315892] DEFAULT ((0)) FOR [ProjectionImpact]; GO +ALTER TABLE [fp].[ProvCompAddProviderSummaryDetails] ADD CONSTRAINT [DF__ProvCompA__Budge__30257CCB] DEFAULT ((0)) FOR [BudgetImpact]; GO +ALTER TABLE [fp].[ProvCompAddProviderSummaryDetails] ADD CONSTRAINT [DF__ProvCompA__UnitT__3119A104] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ProvCompAddProviderSummaryDetails] ADD CONSTRAINT [DF_ProvCompAddProviderSummaryDetails_TargetImpact] DEFAULT ((0)) FOR [TargetImpact]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ProviderCompensationSpreads ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ProviderCompensationSpreads] ( + [BudgetConfigID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeGroupID] int NOT NULL, + [IsInactive] bit NOT NULL, + [SpreadPercentage01] decimal NULL, + [SpreadPercentage02] decimal NULL, + [SpreadPercentage03] decimal NULL, + [SpreadPercentage04] decimal NULL, + [SpreadPercentage05] decimal NULL, + [SpreadPercentage06] decimal NULL, + [SpreadPercentage07] decimal NULL, + [SpreadPercentage08] decimal NULL, + [SpreadPercentage09] decimal NULL, + [SpreadPercentage10] decimal NULL, + [SpreadPercentage11] decimal NULL, + [SpreadPercentage12] decimal NULL, + [TotalImportedValue] decimal NULL, + [SpreadHistoryGUID] uniqueidentifier NOT NULL, + [GlobalSpreadID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + PRIMARY KEY ([BudgetConfigID], [ProviderID], [ProviderLineItemID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [UnitTypeID]) +); +GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [FK_FpProviderCompensationSpreads_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [FK_FpProviderCompensationSpreads_JobCode] FOREIGN KEY ([JobCodeID]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [FK_FpProviderCompensationSpreads_PayCodeGroup] FOREIGN KEY ([PayCodeGroupID]) REFERENCES [fw].[DimPayCodeGroup] ([PayCodeGroupID]); GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [FK_FpProviderCompensationSpreads_Provider] FOREIGN KEY ([ProviderID]) REFERENCES [dss].[DimPhysician] ([PhysicianID]); GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [FK_FpProviderCompensationSpreads_ProviderLineItem] FOREIGN KEY ([ProviderLineItemID]) REFERENCES [fp].[ProviderLineItem] ([ProviderLineItemID]); GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [FK_ProviderCompensationSpreads_History] FOREIGN KEY ([SpreadHistoryGUID]) REFERENCES [fp].[SpreadHistory] ([SpreadHistoryGUID]); GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__00F3F5E8] DEFAULT ((0)) FOR [SpreadPercentage02]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__01E81A21] DEFAULT ((0)) FOR [SpreadPercentage03]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__02DC3E5A] DEFAULT ((0)) FOR [SpreadPercentage04]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__03D06293] DEFAULT ((0)) FOR [SpreadPercentage05]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__04C486CC] DEFAULT ((0)) FOR [SpreadPercentage06]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__05B8AB05] DEFAULT ((0)) FOR [SpreadPercentage07]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__06ACCF3E] DEFAULT ((0)) FOR [SpreadPercentage08]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__07A0F377] DEFAULT ((0)) FOR [SpreadPercentage09]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__089517B0] DEFAULT ((0)) FOR [SpreadPercentage10]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__09893BE9] DEFAULT ((0)) FOR [SpreadPercentage11]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__0A7D6022] DEFAULT ((0)) FOR [SpreadPercentage12]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Total__0B71845B] DEFAULT ((0)) FOR [TotalImportedValue]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__0C65A894] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SpreadHistoryGUID]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Globa__0E4DF106] DEFAULT ((1)) FOR [GlobalSpreadID]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__UnitT__458AAE05] DEFAULT ((34)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Budge__748E1F03] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Provi__7582433C] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Provi__776A8BAE] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Depar__7952D420] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__JobCo__7B3B1C92] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__PayCo__7D236504] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__IsIna__7F0BAD76] DEFAULT ((0)) FOR [IsInactive]; GO +ALTER TABLE [fp].[ProviderCompensationSpreads] ADD CONSTRAINT [DF__ProviderC__Sprea__7FFFD1AF] DEFAULT ((0)) FOR [SpreadPercentage01]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ProviderLineItem ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ProviderLineItem] ( + [HistoryItemGUID] uniqueidentifier NOT NULL, + [ProviderLineItemID] int NOT NULL, + [Description] nvarchar(200) NOT NULL, + [PlanSectionID] int NULL, + [TransactionID] int NULL, + [SortOrder] int NOT NULL, + [ProviderLineItemGUID] uniqueidentifier NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [PayCodeGroupID] int NOT NULL, + PRIMARY KEY ([ProviderLineItemID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [NCU_ProviderLineItemDescription] ON [fp].[ProviderLineItem] ([Description]) INCLUDE ([ProviderLineItemID]); +GO +ALTER TABLE [fp].[ProviderLineItem] ADD CONSTRAINT [DF__ProviderL__Histo__41B7BB1C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fp].[ProviderLineItem] ADD CONSTRAINT [DF__ProviderL__Descr__43A0038E] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fp].[ProviderLineItem] ADD CONSTRAINT [DF__ProviderL__PlanS__449427C7] DEFAULT ((0)) FOR [PlanSectionID]; GO +ALTER TABLE [fp].[ProviderLineItem] ADD CONSTRAINT [DF__ProviderL__Trans__45884C00] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fp].[ProviderLineItem] ADD CONSTRAINT [DF__ProviderL__SortO__467C7039] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fp].[ProviderLineItem] ADD CONSTRAINT [DF__ProviderL__Provi__47709472] DEFAULT (newid()) FOR [ProviderLineItemGUID]; GO +ALTER TABLE [fp].[ProviderLineItem] ADD CONSTRAINT [DF__ProviderL__PayCo__63A6B77F] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fp].[ProviderLineItem] ADD CONSTRAINT [DF__ProviderL__Membe__79CB02C8] DEFAULT (newid()) FOR [MemberGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ProviderLineItemOBForecastDetailMapping ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ProviderLineItemOBForecastDetailMapping] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [OBForecastDetailID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [CLU_ProviderLineItemOBForecastDetail_ndx] ON [fp].[ProviderLineItemOBForecastDetailMapping] ([BudgetConfigID], [ProviderLineItemID], [OBForecastDetailID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_ClusteredUnique] ON [fp].[ProviderLineItemOBForecastDetailMapping] ([BudgetConfigID], [ProviderLineItemID], [OBForecastDetailID]); +GO +ALTER TABLE [fp].[ProviderLineItemOBForecastDetailMapping] ADD CONSTRAINT [DF__ProviderL__Budge__7352440C] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ProviderLineItemOBForecastDetailMapping] ADD CONSTRAINT [DF__ProviderL__Provi__74466845] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[ProviderLineItemOBForecastDetailMapping] ADD CONSTRAINT [DF__ProviderL__OBFor__753A8C7E] DEFAULT ((0)) FOR [OBForecastDetailID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ProviderStaffingConfig ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ProviderStaffingConfig] ( + [ProviderStaffingConfigID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [IsEditByProviderType] bit NOT NULL, + [AccountID] int NOT NULL, + [VariabilityID] int NOT NULL, + PRIMARY KEY ([ProviderStaffingConfigID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [UC_ProviderStaffingConfig_BudgetProviderID] ON [fp].[ProviderStaffingConfig] ([BudgetConfigID], [ProviderLineItemID]); +GO +ALTER TABLE [fp].[ProviderStaffingConfig] ADD CONSTRAINT [FK_ProviderStaffingConfig_ProviderLineItemID] FOREIGN KEY ([ProviderLineItemID]) REFERENCES [fp].[ProviderLineItem] ([ProviderLineItemID]); GO +ALTER TABLE [fp].[ProviderStaffingConfig] ADD CONSTRAINT [DF__ProviderS__Budge__22E91B39] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ProviderStaffingConfig] ADD CONSTRAINT [DF__ProviderS__Provi__23DD3F72] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[ProviderStaffingConfig] ADD CONSTRAINT [DF__ProviderS__IsEdi__24D163AB] DEFAULT ((0)) FOR [IsEditByProviderType]; GO +ALTER TABLE [fp].[ProviderStaffingConfig] ADD CONSTRAINT [DF__ProviderS__Accou__25C587E4] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[ProviderStaffingConfig] ADD CONSTRAINT [DF__ProviderS__Varia__70E7AB51] DEFAULT ((0)) FOR [VariabilityID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ProviderStaffingConfigProviderType ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ProviderStaffingConfigProviderType] ( + [ProviderStaffingConfigTypeID] int NOT NULL, + [ProviderStaffingConfigID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [AccountID] int NOT NULL, + PRIMARY KEY ([ProviderStaffingConfigTypeID]) +); +GO +ALTER TABLE [fp].[ProviderStaffingConfigProviderType] ADD CONSTRAINT [FK_ProviderStaffConfType_AccountID] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [fp].[ProviderStaffingConfigProviderType] ADD CONSTRAINT [FK_ProviderStaffConfType_ProviderTypeID] FOREIGN KEY ([ProviderTypeID]) REFERENCES [clientdss].[DimProviderType] ([ProviderTypeID]); GO +ALTER TABLE [fp].[ProviderStaffingConfigProviderType] ADD CONSTRAINT [FK_ProviderStaffConfType_StaffConfigID] FOREIGN KEY ([ProviderStaffingConfigID]) REFERENCES [fp].[ProviderStaffingConfig] ([ProviderStaffingConfigID]); GO +ALTER TABLE [fp].[ProviderStaffingConfigProviderType] ADD CONSTRAINT [DF__ProviderS__Provi__62998BFA] DEFAULT ((0)) FOR [ProviderStaffingConfigID]; GO +ALTER TABLE [fp].[ProviderStaffingConfigProviderType] ADD CONSTRAINT [DF__ProviderS__Provi__638DB033] DEFAULT ((0)) FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[ProviderStaffingConfigProviderType] ADD CONSTRAINT [DF__ProviderS__Accou__6481D46C] DEFAULT ((0)) FOR [AccountID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ProviderStatisticsConfig ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ProviderStatisticsConfig] ( + [BudgetConfigID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [AccountID] int NOT NULL, + PRIMARY KEY ([BudgetConfigID], [ProviderLineItemID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[ProviderStatisticsConfig] ([BudgetConfigID], [ProviderLineItemID], [AccountID]); +GO +ALTER TABLE [fp].[ProviderStatisticsConfig] ADD CONSTRAINT [DF__ProviderS__Budge__73A41C6B] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ProviderStatisticsConfig] ADD CONSTRAINT [DF__ProviderS__Provi__749840A4] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[ProviderStatisticsConfig] ADD CONSTRAINT [DF__ProviderS__Accou__758C64DD] DEFAULT ((0)) FOR [AccountID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.RefreshDatabaseStatisticsConfiguration ------------------ +--------------------------------------------- +CREATE TABLE [fp].[RefreshDatabaseStatisticsConfiguration] ( + [SchemaName] nvarchar(2) NOT NULL, + [TableName] nvarchar(256) NOT NULL, + [IsActive] bit NOT NULL +); + +CREATE UNIQUE NONCLUSTERED INDEX [CORE_SchemaName_TableName] ON [fp].[RefreshDatabaseStatisticsConfiguration] ([SchemaName], [TableName]); +GO +ALTER TABLE [fp].[RefreshDatabaseStatisticsConfiguration] ADD CONSTRAINT [DF__RefreshDa__Schem__296CC6ED] DEFAULT ('') FOR [SchemaName]; GO +ALTER TABLE [fp].[RefreshDatabaseStatisticsConfiguration] ADD CONSTRAINT [DF__RefreshDa__Table__2A60EB26] DEFAULT ('') FOR [TableName]; GO +ALTER TABLE [fp].[RefreshDatabaseStatisticsConfiguration] ADD CONSTRAINT [DF__RefreshDa__IsAct__2B550F5F] DEFAULT ((1)) FOR [IsActive]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ReimbursementAdjustment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ReimbursementAdjustment] ( + [AdjustmentGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [Value] decimal NOT NULL, + [AdjustmentFilterJSON] nvarchar(max) NOT NULL, + [GroupingHierarchyJSON] nvarchar(max) NOT NULL, + [AdjustedProperty] nvarchar(100) NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [TimeClassID] tinyint NOT NULL, + [ClassificationGroupID] int NOT NULL, + [ClassificationCategoryID] int NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + [LastModifiedDateUtc] datetime NOT NULL, + [DimensionMemberJson] nvarchar(max) NOT NULL, + [AffectedDataCount] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [IsCarryForward] bit NOT NULL, + [AdjustmentID] int NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + PRIMARY KEY ([AdjustmentID]) +); +GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [FK__Reimburse__Budge__3C165264] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Budge__0FD97421] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Adjus__29037DF0] DEFAULT (newid()) FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Adjus__29F7A229] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Value__2AEBC662] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__IsCar__2BDFEA9B] DEFAULT ((0)) FOR [IsCarryForward]; GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Adjus__2CD40ED4] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Group__2DC8330D] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Adjus__2EBC5746] DEFAULT ('') FOR [AdjustedProperty]; GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Comme__2FB07B7F] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Autho__30A49FB8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Autho__3198C3F1] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Group__328CE82A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF_ReimbursementAdjustment_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF_ReimbursementAdjustment_ClassificationGroupID] DEFAULT ((0)) FOR [ClassificationGroupID]; GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF_ReimbursementAdjustment_ClassificationCategoryID] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__IsRec__365D790E] DEFAULT ((0)) FOR [IsRecordDeleted]; GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__DateC__37519D47] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__LastM__3845C180] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Dimen__3939E5B9] DEFAULT ('') FOR [DimensionMemberJson]; GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__Affec__3A2E09F2] DEFAULT ((0)) FOR [AffectedDataCount]; GO +ALTER TABLE [fp].[ReimbursementAdjustment] ADD CONSTRAINT [DF__Reimburse__UnitT__3B222E2B] DEFAULT ((0)) FOR [UnitTypeID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ReimbursementAdjustmentChargeImport ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ReimbursementAdjustmentChargeImport] ( + [RowID] int NOT NULL, + [AdjustmentID] int NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [MSDRGID] int NOT NULL, + [PrimaryCPTID] int NOT NULL, + [UBRevCodeID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Value01] decimal NULL, + [Value02] decimal NULL, + [Value03] decimal NULL, + [Value04] decimal NULL, + [Value05] decimal NULL, + [Value06] decimal NULL, + [Value07] decimal NULL, + [Value08] decimal NULL, + [Value09] decimal NULL, + [Value10] decimal NULL, + [Value11] decimal NULL, + [Value12] decimal NULL, + [BudgetPhaseID] tinyint NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__Budge__23CB5E35] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__Adjus__36928338] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__Entit__3786A771] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__Patie__387ACBAA] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__Payor__396EEFE3] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__Payor__3A63141C] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__Servi__3B573855] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__Servi__3C4B5C8E] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__Medic__3D3F80C7] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__MSDRG__3E33A500] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__Prima__3F27C939] DEFAULT ((0)) FOR [PrimaryCPTID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__UBRev__401BED72] DEFAULT ((0)) FOR [UBRevCodeID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__UnitT__411011AB] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentChargeImport] ADD CONSTRAINT [DF__Reimburse__TimeC__420435E4] DEFAULT ((0)) FOR [TimeClassID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ReimbursementAdjustmentEncounterImport ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ReimbursementAdjustmentEncounterImport] ( + [RowID] int NOT NULL, + [AdjustmentID] int NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [MSDRGID] int NOT NULL, + [CPTID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Value01] decimal NULL, + [Value02] decimal NULL, + [Value03] decimal NULL, + [Value04] decimal NULL, + [Value05] decimal NULL, + [Value06] decimal NULL, + [Value07] decimal NULL, + [Value08] decimal NULL, + [Value09] decimal NULL, + [Value10] decimal NULL, + [Value11] decimal NULL, + [Value12] decimal NULL, + [BudgetPhaseID] tinyint NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__Budge__22D739FC] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__Adjus__44E0A28F] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__Entit__45D4C6C8] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__Patie__46C8EB01] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__Payor__47BD0F3A] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__Payor__48B13373] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__Servi__49A557AC] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__Servi__4A997BE5] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__Medic__4B8DA01E] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__MSDRG__4C81C457] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__CPTID__4D75E890] DEFAULT ((0)) FOR [CPTID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__UnitT__4E6A0CC9] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentEncounterImport] ADD CONSTRAINT [DF__Reimburse__TimeC__4F5E3102] DEFAULT ((0)) FOR [TimeClassID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ReimbursementAdjustmentRate ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ReimbursementAdjustmentRate] ( + [RowID] int NOT NULL, + [AdjustmentID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [MSDRGID] int NOT NULL, + [CPTID] int NOT NULL, + [UBRevCodeID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [Value01] decimal NOT NULL, + [Value02] decimal NOT NULL, + [Value03] decimal NOT NULL, + [Value04] decimal NOT NULL, + [Value05] decimal NOT NULL, + [Value06] decimal NOT NULL, + [Value07] decimal NOT NULL, + [Value08] decimal NOT NULL, + [Value09] decimal NOT NULL, + [Value10] decimal NOT NULL, + [Value11] decimal NOT NULL, + [Value12] decimal NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_Clustered_ReimbursementAdjustmentRate] ON [fp].[ReimbursementAdjustmentRate] ([BudgetConfigID]); +GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Budge__10CD985A] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Adjus__3AED2401] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Budge__3BE1483A] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Entit__3CD56C73] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Patie__3DC990AC] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Servi__3EBDB4E5] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Servi__3FB1D91E] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Medic__40A5FD57] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Payor__419A2190] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Payor__428E45C9] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__MSDRG__43826A02] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__CPTID__44768E3B] DEFAULT ((0)) FOR [CPTID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__UBRev__456AB274] DEFAULT ((0)) FOR [UBRevCodeID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__TimeC__465ED6AD] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__UnitT__4752FAE6] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__48471F1F] DEFAULT ((0)) FOR [Value01]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__493B4358] DEFAULT ((0)) FOR [Value02]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__4A2F6791] DEFAULT ((0)) FOR [Value03]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__4B238BCA] DEFAULT ((0)) FOR [Value04]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__4C17B003] DEFAULT ((0)) FOR [Value05]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__4D0BD43C] DEFAULT ((0)) FOR [Value06]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__4DFFF875] DEFAULT ((0)) FOR [Value07]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__4EF41CAE] DEFAULT ((0)) FOR [Value08]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__4FE840E7] DEFAULT ((0)) FOR [Value09]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__50DC6520] DEFAULT ((0)) FOR [Value10]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__51D08959] DEFAULT ((0)) FOR [Value11]; GO +ALTER TABLE [fp].[ReimbursementAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__52C4AD92] DEFAULT ((0)) FOR [Value12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ReimbursementChangeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ReimbursementChangeHistory] ( + [RowID] bigint NOT NULL, + [ReimbursementID] int NOT NULL, + [SubsectionID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [OldValue] decimal NOT NULL, + [NewValue] decimal NOT NULL, + [BudgetConfigID] int NOT NULL, + [DateCreatedUTC] datetime2 NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__Reimb__5422E61F] DEFAULT ((0)) FOR [ReimbursementID]; GO +ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__Subse__55170A58] DEFAULT ((0)) FOR [SubsectionID]; GO +ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__Adjus__560B2E91] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__Adjus__56FF52CA] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__Fisca__57F37703] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__UnitT__58E79B3C] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__TimeC__59DBBF75] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__Budge__5ACFE3AE] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__OldVa__5BC407E7] DEFAULT ((0)) FOR [OldValue]; GO +ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__NewVa__5CB82C20] DEFAULT ((0)) FOR [NewValue]; GO +ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__Budge__5DAC5059] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ReimbursementChangeHistory] ADD CONSTRAINT [DF__Reimburse__DateC__5EA07492] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ReimbursementGeneralLedger ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ReimbursementGeneralLedger] ( + [ReimbursementGeneralLedgerID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [PatientClassID] int NOT NULL, + [BudgetLockType] tinyint NOT NULL, + [BudgetLockFlag] tinyint NOT NULL, + [TargetLockType] tinyint NOT NULL, + [TargetLockFlag] tinyint NOT NULL, + [ProjectionLockType] tinyint NOT NULL, + [ProjectionLockFlag] tinyint NOT NULL, + [AddDate] datetime NOT NULL, + [IsNew] bit NOT NULL, + [InitialBudgetTotal] decimal NOT NULL, + [InitialProjectionTotal] decimal NOT NULL, + [TargetAdjustedTotal] decimal NOT NULL, + [BudgetAdjustedTotal] decimal NOT NULL, + [ProjectionAdjustedTotal] decimal NOT NULL, + [InitialBudget01] decimal NOT NULL, + [InitialBudget02] decimal NOT NULL, + [InitialBudget03] decimal NOT NULL, + [InitialBudget04] decimal NOT NULL, + [InitialBudget05] decimal NOT NULL, + [InitialBudget06] decimal NOT NULL, + [InitialBudget07] decimal NOT NULL, + [InitialBudget08] decimal NOT NULL, + [InitialBudget09] decimal NOT NULL, + [InitialBudget10] decimal NOT NULL, + [InitialBudget11] decimal NOT NULL, + [InitialBudget12] decimal NOT NULL, + [InitialProjection01] decimal NOT NULL, + [InitialProjection02] decimal NOT NULL, + [InitialProjection03] decimal NOT NULL, + [InitialProjection04] decimal NOT NULL, + [InitialProjection05] decimal NOT NULL, + [InitialProjection06] decimal NOT NULL, + [InitialProjection07] decimal NOT NULL, + [InitialProjection08] decimal NOT NULL, + [InitialProjection09] decimal NOT NULL, + [InitialProjection10] decimal NOT NULL, + [InitialProjection11] decimal NOT NULL, + [InitialProjection12] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge01] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge02] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge03] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge04] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge05] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge06] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge07] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge08] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge09] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge10] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge11] decimal NOT NULL, + [InitialBudgetNetAsPercentOfCharge12] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge01] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge02] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge03] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge04] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge05] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge06] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge07] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge08] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge09] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge10] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge11] decimal NOT NULL, + [InitialProjectionNetAsPercentOfCharge12] decimal NOT NULL, + [InitialBudgetNetReimbursement01] decimal NOT NULL, + [InitialBudgetNetReimbursement02] decimal NOT NULL, + [InitialBudgetNetReimbursement03] decimal NOT NULL, + [InitialBudgetNetReimbursement04] decimal NOT NULL, + [InitialBudgetNetReimbursement05] decimal NOT NULL, + [InitialBudgetNetReimbursement06] decimal NOT NULL, + [InitialBudgetNetReimbursement07] decimal NOT NULL, + [InitialBudgetNetReimbursement08] decimal NOT NULL, + [InitialBudgetNetReimbursement09] decimal NOT NULL, + [InitialBudgetNetReimbursement10] decimal NOT NULL, + [InitialBudgetNetReimbursement11] decimal NOT NULL, + [InitialBudgetNetReimbursement12] decimal NOT NULL, + [InitialProjectionNetReimbursement01] decimal NOT NULL, + [InitialProjectionNetReimbursement02] decimal NOT NULL, + [InitialProjectionNetReimbursement03] decimal NOT NULL, + [InitialProjectionNetReimbursement04] decimal NOT NULL, + [InitialProjectionNetReimbursement05] decimal NOT NULL, + [InitialProjectionNetReimbursement06] decimal NOT NULL, + [InitialProjectionNetReimbursement07] decimal NOT NULL, + [InitialProjectionNetReimbursement08] decimal NOT NULL, + [InitialProjectionNetReimbursement09] decimal NOT NULL, + [InitialProjectionNetReimbursement10] decimal NOT NULL, + [InitialProjectionNetReimbursement11] decimal NOT NULL, + [InitialProjectionNetReimbursement12] decimal NOT NULL, + [TargetAdjusted01] decimal NOT NULL, + [TargetAdjusted02] decimal NOT NULL, + [TargetAdjusted03] decimal NOT NULL, + [TargetAdjusted04] decimal NOT NULL, + [TargetAdjusted05] decimal NOT NULL, + [TargetAdjusted06] decimal NOT NULL, + [TargetAdjusted07] decimal NOT NULL, + [TargetAdjusted08] decimal NOT NULL, + [TargetAdjusted09] decimal NOT NULL, + [TargetAdjusted10] decimal NOT NULL, + [TargetAdjusted11] decimal NOT NULL, + [TargetAdjusted12] decimal NOT NULL, + [TargetAdjustedNetAsPercentOfCharge01] decimal NOT NULL, + [TargetAdjustedNetAsPercentOfCharge02] decimal NOT NULL, + [TargetAdjustedNetAsPercentOfCharge03] decimal NOT NULL, + [TargetAdjustedNetAsPercentOfCharge04] decimal NOT NULL, + [TargetAdjustedNetAsPercentOfCharge05] decimal NOT NULL, + [TargetAdjustedNetAsPercentOfCharge06] decimal NOT NULL, + [TargetAdjustedNetAsPercentOfCharge07] decimal NOT NULL, + [TargetAdjustedNetAsPercentOfCharge08] decimal NOT NULL, + [TargetAdjustedNetAsPercentOfCharge09] decimal NOT NULL, + [TargetAdjustedNetAsPercentOfCharge10] decimal NOT NULL, + [TargetAdjustedNetAsPercentOfCharge11] decimal NOT NULL, + [TargetAdjustedNetAsPercentOfCharge12] decimal NOT NULL, + [TargetAdjustedNetReimbursement01] decimal NOT NULL, + [TargetAdjustedNetReimbursement02] decimal NOT NULL, + [TargetAdjustedNetReimbursement03] decimal NOT NULL, + [TargetAdjustedNetReimbursement04] decimal NOT NULL, + [TargetAdjustedNetReimbursement05] decimal NOT NULL, + [TargetAdjustedNetReimbursement06] decimal NOT NULL, + [TargetAdjustedNetReimbursement07] decimal NOT NULL, + [TargetAdjustedNetReimbursement08] decimal NOT NULL, + [TargetAdjustedNetReimbursement09] decimal NOT NULL, + [TargetAdjustedNetReimbursement10] decimal NOT NULL, + [TargetAdjustedNetReimbursement11] decimal NOT NULL, + [TargetAdjustedNetReimbursement12] decimal NOT NULL, + [BudgetAdjusted01] decimal NOT NULL, + [BudgetAdjusted02] decimal NOT NULL, + [BudgetAdjusted03] decimal NOT NULL, + [BudgetAdjusted04] decimal NOT NULL, + [BudgetAdjusted05] decimal NOT NULL, + [BudgetAdjusted06] decimal NOT NULL, + [BudgetAdjusted07] decimal NOT NULL, + [BudgetAdjusted08] decimal NOT NULL, + [BudgetAdjusted09] decimal NOT NULL, + [BudgetAdjusted10] decimal NOT NULL, + [BudgetAdjusted11] decimal NOT NULL, + [BudgetAdjusted12] decimal NOT NULL, + [BudgetAdjustedNetAsPercentOfCharge01] decimal NOT NULL, + [BudgetAdjustedNetAsPercentOfCharge02] decimal NOT NULL, + [BudgetAdjustedNetAsPercentOfCharge03] decimal NOT NULL, + [BudgetAdjustedNetAsPercentOfCharge04] decimal NOT NULL, + [BudgetAdjustedNetAsPercentOfCharge05] decimal NOT NULL, + [BudgetAdjustedNetAsPercentOfCharge06] decimal NOT NULL, + [BudgetAdjustedNetAsPercentOfCharge07] decimal NOT NULL, + [BudgetAdjustedNetAsPercentOfCharge08] decimal NOT NULL, + [BudgetAdjustedNetAsPercentOfCharge09] decimal NOT NULL, + [BudgetAdjustedNetAsPercentOfCharge10] decimal NOT NULL, + [BudgetAdjustedNetAsPercentOfCharge11] decimal NOT NULL, + [BudgetAdjustedNetAsPercentOfCharge12] decimal NOT NULL, + [BudgetAdjustedNetReimbursement01] decimal NOT NULL, + [BudgetAdjustedNetReimbursement02] decimal NOT NULL, + [BudgetAdjustedNetReimbursement03] decimal NOT NULL, + [BudgetAdjustedNetReimbursement04] decimal NOT NULL, + [BudgetAdjustedNetReimbursement05] decimal NOT NULL, + [BudgetAdjustedNetReimbursement06] decimal NOT NULL, + [BudgetAdjustedNetReimbursement07] decimal NOT NULL, + [BudgetAdjustedNetReimbursement08] decimal NOT NULL, + [BudgetAdjustedNetReimbursement09] decimal NOT NULL, + [BudgetAdjustedNetReimbursement10] decimal NOT NULL, + [BudgetAdjustedNetReimbursement11] decimal NOT NULL, + [BudgetAdjustedNetReimbursement12] decimal NOT NULL, + [ProjectionAdjusted01] decimal NOT NULL, + [ProjectionAdjusted02] decimal NOT NULL, + [ProjectionAdjusted03] decimal NOT NULL, + [ProjectionAdjusted04] decimal NOT NULL, + [ProjectionAdjusted05] decimal NOT NULL, + [ProjectionAdjusted06] decimal NOT NULL, + [ProjectionAdjusted07] decimal NOT NULL, + [ProjectionAdjusted08] decimal NOT NULL, + [ProjectionAdjusted09] decimal NOT NULL, + [ProjectionAdjusted10] decimal NOT NULL, + [ProjectionAdjusted11] decimal NOT NULL, + [ProjectionAdjusted12] decimal NOT NULL, + [ProjectionAdjustedNetAsPercentOfCharge01] decimal NOT NULL, + [ProjectionAdjustedNetAsPercentOfCharge02] decimal NOT NULL, + [ProjectionAdjustedNetAsPercentOfCharge03] decimal NOT NULL, + [ProjectionAdjustedNetAsPercentOfCharge04] decimal NOT NULL, + [ProjectionAdjustedNetAsPercentOfCharge05] decimal NOT NULL, + [ProjectionAdjustedNetAsPercentOfCharge06] decimal NOT NULL, + [ProjectionAdjustedNetAsPercentOfCharge07] decimal NOT NULL, + [ProjectionAdjustedNetAsPercentOfCharge08] decimal NOT NULL, + [ProjectionAdjustedNetAsPercentOfCharge09] decimal NOT NULL, + [ProjectionAdjustedNetAsPercentOfCharge10] decimal NOT NULL, + [ProjectionAdjustedNetAsPercentOfCharge11] decimal NOT NULL, + [ProjectionAdjustedNetAsPercentOfCharge12] decimal NOT NULL, + [ProjectionAdjustedNetReimbursement01] decimal NOT NULL, + [ProjectionAdjustedNetReimbursement02] decimal NOT NULL, + [ProjectionAdjustedNetReimbursement03] decimal NOT NULL, + [ProjectionAdjustedNetReimbursement04] decimal NOT NULL, + [ProjectionAdjustedNetReimbursement05] decimal NOT NULL, + [ProjectionAdjustedNetReimbursement06] decimal NOT NULL, + [ProjectionAdjustedNetReimbursement07] decimal NOT NULL, + [ProjectionAdjustedNetReimbursement08] decimal NOT NULL, + [ProjectionAdjustedNetReimbursement09] decimal NOT NULL, + [ProjectionAdjustedNetReimbursement10] decimal NOT NULL, + [ProjectionAdjustedNetReimbursement11] decimal NOT NULL, + [ProjectionAdjustedNetReimbursement12] decimal NOT NULL, + PRIMARY KEY ([ReimbursementGeneralLedgerID]) +); +GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [FK_ReimbursementGeneralLedger_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [FK_ReimbursementGeneralLedger_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [FK_ReimbursementGeneralLedger_PayorGroup] FOREIGN KEY ([PayorGroupID]) REFERENCES [fw].[DimPayorGroup] ([PayorGroupID]); GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__00CC3ABB] DEFAULT ((0)) FOR [BudgetAdjusted11]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__01C05EF4] DEFAULT ((0)) FOR [BudgetAdjusted12]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__02B4832D] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge01]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__03A8A766] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge02]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__049CCB9F] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge03]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__0590EFD8] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge04]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__06851411] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge05]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__0779384A] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge06]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__086D5C83] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge07]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__096180BC] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge08]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__0A55A4F5] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge09]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__0B49C92E] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge10]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__0C3DED67] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge11]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__0D3211A0] DEFAULT ((0)) FOR [BudgetAdjustedNetAsPercentOfCharge12]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__0E2635D9] DEFAULT ((0)) FOR [ProjectionAdjusted01]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__0F1A5A12] DEFAULT ((0)) FOR [ProjectionAdjusted02]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__100E7E4B] DEFAULT ((0)) FOR [ProjectionAdjusted03]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__1102A284] DEFAULT ((0)) FOR [ProjectionAdjusted04]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__11F6C6BD] DEFAULT ((0)) FOR [ProjectionAdjusted05]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__12EAEAF6] DEFAULT ((0)) FOR [ProjectionAdjusted06]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__13DF0F2F] DEFAULT ((0)) FOR [ProjectionAdjusted07]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__14D33368] DEFAULT ((0)) FOR [ProjectionAdjusted08]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__15C757A1] DEFAULT ((0)) FOR [ProjectionAdjusted09]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__16BB7BDA] DEFAULT ((0)) FOR [ProjectionAdjusted10]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__17AFA013] DEFAULT ((0)) FOR [ProjectionAdjusted11]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__18A3C44C] DEFAULT ((0)) FOR [ProjectionAdjusted12]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__1997E885] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge01]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__1A8C0CBE] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge02]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__1B8030F7] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge03]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__1C745530] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge04]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__1D687969] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge05]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__1E5C9DA2] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge06]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__1F50C1DB] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge07]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__2044E614] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge08]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__21390A4D] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge09]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__222D2E86] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge10]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__232152BF] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge11]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__241576F8] DEFAULT ((0)) FOR [ProjectionAdjustedNetAsPercentOfCharge12]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__2632C994] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Entit__2726EDCD] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Entit__281B1206] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Payor__290F363F] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Patie__2A035A78] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__2AF77EB1] DEFAULT ((0)) FOR [BudgetLockType]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__2BEBA2EA] DEFAULT ((0)) FOR [BudgetLockFlag]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__2CDFC723] DEFAULT ((0)) FOR [TargetLockType]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__2DD3EB5C] DEFAULT ((0)) FOR [TargetLockFlag]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__2EC80F95] DEFAULT ((0)) FOR [ProjectionLockType]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Proje__2FBC33CE] DEFAULT ((0)) FOR [ProjectionLockFlag]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__AddDa__30B05807] DEFAULT ('2800-01-01') FOR [AddDate]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__IsNew__31A47C40] DEFAULT ((0)) FOR [IsNew]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__3298A079] DEFAULT ((0)) FOR [InitialBudget01]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__338CC4B2] DEFAULT ((0)) FOR [InitialBudget02]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__3480E8EB] DEFAULT ((0)) FOR [InitialBudget03]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__35750D24] DEFAULT ((0)) FOR [InitialBudget04]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__3669315D] DEFAULT ((0)) FOR [InitialBudget05]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__375D5596] DEFAULT ((0)) FOR [InitialBudget06]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__385179CF] DEFAULT ((0)) FOR [InitialBudget07]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__39459E08] DEFAULT ((0)) FOR [InitialBudget08]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__3A39C241] DEFAULT ((0)) FOR [InitialBudget09]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__3B2DE67A] DEFAULT ((0)) FOR [InitialBudget10]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__3C220AB3] DEFAULT ((0)) FOR [InitialBudget11]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__3D162EEC] DEFAULT ((0)) FOR [InitialBudget12]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__3E0A5325] DEFAULT ((0)) FOR [InitialProjection01]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__3EFE775E] DEFAULT ((0)) FOR [InitialProjection02]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__3FF29B97] DEFAULT ((0)) FOR [InitialProjection03]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__40E6BFD0] DEFAULT ((0)) FOR [InitialProjection04]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__41DAE409] DEFAULT ((0)) FOR [InitialProjection05]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__42CF0842] DEFAULT ((0)) FOR [InitialProjection06]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__43C32C7B] DEFAULT ((0)) FOR [InitialProjection07]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__44B750B4] DEFAULT ((0)) FOR [InitialProjection08]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__45AB74ED] DEFAULT ((0)) FOR [InitialProjection09]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__469F9926] DEFAULT ((0)) FOR [InitialProjection10]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__4793BD5F] DEFAULT ((0)) FOR [InitialProjection11]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__4887E198] DEFAULT ((0)) FOR [InitialProjection12]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__497C05D1] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge01]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__4A702A0A] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge02]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__4B644E43] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge03]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__4C58727C] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge04]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__4D4C96B5] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge05]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__4E40BAEE] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge06]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__4F34DF27] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge07]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__50290360] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge08]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__511D2799] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge09]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__52114BD2] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge10]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__5305700B] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge11]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__53F99444] DEFAULT ((0)) FOR [InitialBudgetNetAsPercentOfCharge12]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__54EDB87D] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge01]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__55E1DCB6] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge02]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__56D600EF] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge03]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__57CA2528] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge04]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__58BE4961] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge05]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__59B26D9A] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge06]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__5AA691D3] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge07]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__5B9AB60C] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge08]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__5C8EDA45] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge09]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__5D82FE7E] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge10]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__5E7722B7] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge11]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Initi__5F6B46F0] DEFAULT ((0)) FOR [InitialProjectionNetAsPercentOfCharge12]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__605F6B29] DEFAULT ((0)) FOR [TargetAdjusted01]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__61538F62] DEFAULT ((0)) FOR [TargetAdjusted02]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__6247B39B] DEFAULT ((0)) FOR [TargetAdjusted03]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__633BD7D4] DEFAULT ((0)) FOR [TargetAdjusted04]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__642FFC0D] DEFAULT ((0)) FOR [TargetAdjusted05]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__65242046] DEFAULT ((0)) FOR [TargetAdjusted06]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__6618447F] DEFAULT ((0)) FOR [TargetAdjusted07]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__670C68B8] DEFAULT ((0)) FOR [TargetAdjusted08]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__68008CF1] DEFAULT ((0)) FOR [TargetAdjusted09]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__68F4B12A] DEFAULT ((0)) FOR [TargetAdjusted10]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__69E8D563] DEFAULT ((0)) FOR [TargetAdjusted11]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__6ADCF99C] DEFAULT ((0)) FOR [TargetAdjusted12]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__6BD11DD5] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge01]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__6CC5420E] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge02]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__6DB96647] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge03]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__6EAD8A80] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge04]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__6FA1AEB9] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge05]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__7095D2F2] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge06]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__7189F72B] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge07]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__727E1B64] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge08]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__73723F9D] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge09]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__746663D6] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge10]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__755A880F] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge11]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Targe__764EAC48] DEFAULT ((0)) FOR [TargetAdjustedNetAsPercentOfCharge12]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__7742D081] DEFAULT ((0)) FOR [BudgetAdjusted01]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__7836F4BA] DEFAULT ((0)) FOR [BudgetAdjusted02]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__792B18F3] DEFAULT ((0)) FOR [BudgetAdjusted03]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__7A1F3D2C] DEFAULT ((0)) FOR [BudgetAdjusted04]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__7B136165] DEFAULT ((0)) FOR [BudgetAdjusted05]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__7C07859E] DEFAULT ((0)) FOR [BudgetAdjusted06]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__7CFBA9D7] DEFAULT ((0)) FOR [BudgetAdjusted07]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__7DEFCE10] DEFAULT ((0)) FOR [BudgetAdjusted08]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__7EE3F249] DEFAULT ((0)) FOR [BudgetAdjusted09]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedger] ADD CONSTRAINT [DF__Reimburse__Budge__7FD81682] DEFAULT ((0)) FOR [BudgetAdjusted10]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ReimbursementGeneralLedgerAdjustment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ( + [AdjustmentGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [Value] decimal NOT NULL, + [AdjustmentFilterJSON] nvarchar(max) NOT NULL, + [GroupingHierarchyJSON] nvarchar(max) NOT NULL, + [AdjustedProperty] nvarchar(100) NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [ClassificationGroupID] int NOT NULL, + [ClassificationCategoryID] int NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [LastModifiedDateUtc] datetime NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + [DimensionMemberJson] nvarchar(max) NOT NULL, + [IsCarryForward] bit NOT NULL, + [AffectedDataCount] int NOT NULL, + [AdjustmentID] int NOT NULL, + [IsErrored] bit NOT NULL, + [UnitTypeID] tinyint NOT NULL, + PRIMARY KEY ([AdjustmentID]) +); +GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [FK__Reimburse__Budge__5D4DF454] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF_ReimbursementGeneralLedgerAdjustment_UnitTypeID] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Adjus__4946FBA7] DEFAULT (newid()) FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Adjus__4A3B1FE0] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Value__4B2F4419] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__IsCar__4C236852] DEFAULT ((0)) FOR [IsCarryForward]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Adjus__4D178C8B] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Group__4E0BB0C4] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Adjus__4EFFD4FD] DEFAULT ('') FOR [AdjustedProperty]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Comme__4FF3F936] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Autho__50E81D6F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Autho__51DC41A8] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Group__52D065E1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF_ReimbursementGeneralLedgerAdjustment_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF_ReimbursementGeneralLedgerAdjustment_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF_ReimbursementGeneralLedgerAdjustment_ClassificationGroupID] DEFAULT ((0)) FOR [ClassificationGroupID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF_ReimbursementGeneralLedgerAdjustment_ClassificationCategoryID] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__IsRec__57951AFE] DEFAULT ((0)) FOR [IsRecordDeleted]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__DateC__58893F37] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__LastM__597D6370] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Dimen__5A7187A9] DEFAULT ('') FOR [DimensionMemberJson]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__Affec__5B65ABE2] DEFAULT ((0)) FOR [AffectedDataCount]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustment] ADD CONSTRAINT [DF__Reimburse__IsErr__5C59D01B] DEFAULT ((0)) FOR [IsErrored]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ReimbursementGeneralLedgerAdjustmentImport ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ReimbursementGeneralLedgerAdjustmentImport] ( + [RowID] int NOT NULL, + [AdjustmentID] int NOT NULL, + [EntityID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [PatientClassID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [Value01] decimal NULL, + [Value02] decimal NULL, + [Value03] decimal NULL, + [Value04] decimal NULL, + [Value05] decimal NULL, + [Value06] decimal NULL, + [Value07] decimal NULL, + [Value08] decimal NULL, + [Value09] decimal NULL, + [Value10] decimal NULL, + [Value11] decimal NULL, + [Value12] decimal NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__Reimburse__Adjus__602A60FF] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__Reimburse__Entit__611E8538] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__Reimburse__Payor__6212A971] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__Reimburse__Patie__6306CDAA] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__Reimburse__TimeC__63FAF1E3] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentImport] ADD CONSTRAINT [DF__Reimburse__Budge__64EF161C] DEFAULT ((0)) FOR [BudgetPhaseID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ReimbursementGeneralLedgerAdjustmentRate ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ( + [RowID] int NOT NULL, + [AdjustmentID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [PatientClassID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [Value01] decimal NOT NULL, + [Value02] decimal NOT NULL, + [Value03] decimal NOT NULL, + [Value04] decimal NOT NULL, + [Value05] decimal NOT NULL, + [Value06] decimal NOT NULL, + [Value07] decimal NOT NULL, + [Value08] decimal NOT NULL, + [Value09] decimal NOT NULL, + [Value10] decimal NOT NULL, + [Value11] decimal NOT NULL, + [Value12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_Clustered_ReimbursementGeneralLedgerAdjustmentRate] ON [fp].[ReimbursementGeneralLedgerAdjustmentRate] ([BudgetConfigID]); +GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Patie__00780057] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__TimeC__016C2490] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__UnitT__026048C9] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__03546D02] DEFAULT ((0)) FOR [Value01]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__0448913B] DEFAULT ((0)) FOR [Value02]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__053CB574] DEFAULT ((0)) FOR [Value03]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__0630D9AD] DEFAULT ((0)) FOR [Value04]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__0724FDE6] DEFAULT ((0)) FOR [Value05]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__0819221F] DEFAULT ((0)) FOR [Value06]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__090D4658] DEFAULT ((0)) FOR [Value07]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__0A016A91] DEFAULT ((0)) FOR [Value08]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__0AF58ECA] DEFAULT ((0)) FOR [Value09]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__0BE9B303] DEFAULT ((0)) FOR [Value10]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__0CDDD73C] DEFAULT ((0)) FOR [Value11]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Value__0DD1FB75] DEFAULT ((0)) FOR [Value12]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [df_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Adjus__7CA76F73] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Budge__7D9B93AC] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Entit__7E8FB7E5] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerAdjustmentRate] ADD CONSTRAINT [DF__Reimburse__Payor__7F83DC1E] DEFAULT ((0)) FOR [PayorGroupID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ReimbursementGeneralLedgerChangeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ( + [RowID] bigint NOT NULL, + [ReimbursementGeneralLedgerID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [OldValue] decimal NOT NULL, + [NewValue] decimal NOT NULL, + [BudgetConfigID] int NOT NULL, + [DateCreatedUTC] datetime2 NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__Reimb__6AA7EF72] DEFAULT ((0)) FOR [ReimbursementGeneralLedgerID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__Adjus__6B9C13AB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__Adjus__6C9037E4] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__Fisca__6D845C1D] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__UnitT__6E788056] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__TimeC__6F6CA48F] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__Budge__7060C8C8] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__OldVa__7154ED01] DEFAULT ((0)) FOR [OldValue]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__NewVa__7249113A] DEFAULT ((0)) FOR [NewValue]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__Budge__733D3573] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerChangeHistory] ADD CONSTRAINT [DF__Reimburse__DateC__743159AC] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ReimbursementGeneralLedgerHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ReimbursementGeneralLedgerHistory] ( + [RowID] int NOT NULL, + [ReimbursementGeneralLedgerID] int NOT NULL, + [PriorYearActualValueTotal] decimal NOT NULL, + [PriorYearActualValue01] decimal NOT NULL, + [PriorYearActualValue02] decimal NOT NULL, + [PriorYearActualValue03] decimal NOT NULL, + [PriorYearActualValue04] decimal NOT NULL, + [PriorYearActualValue05] decimal NOT NULL, + [PriorYearActualValue06] decimal NOT NULL, + [PriorYearActualValue07] decimal NOT NULL, + [PriorYearActualValue08] decimal NOT NULL, + [PriorYearActualValue09] decimal NOT NULL, + [PriorYearActualValue10] decimal NOT NULL, + [PriorYearActualValue11] decimal NOT NULL, + [PriorYearActualValue12] decimal NOT NULL, + [PriorYearActualValueNetAsPercentOfCharge01] decimal NOT NULL, + [PriorYearActualValueNetAsPercentOfCharge02] decimal NOT NULL, + [PriorYearActualValueNetAsPercentOfCharge03] decimal NOT NULL, + [PriorYearActualValueNetAsPercentOfCharge04] decimal NOT NULL, + [PriorYearActualValueNetAsPercentOfCharge05] decimal NOT NULL, + [PriorYearActualValueNetAsPercentOfCharge06] decimal NOT NULL, + [PriorYearActualValueNetAsPercentOfCharge07] decimal NOT NULL, + [PriorYearActualValueNetAsPercentOfCharge08] decimal NOT NULL, + [PriorYearActualValueNetAsPercentOfCharge09] decimal NOT NULL, + [PriorYearActualValueNetAsPercentOfCharge10] decimal NOT NULL, + [PriorYearActualValueNetAsPercentOfCharge11] decimal NOT NULL, + [PriorYearActualValueNetAsPercentOfCharge12] decimal NOT NULL, + [PriorYearActualValueNetReimbursement01] decimal NOT NULL, + [PriorYearActualValueNetReimbursement02] decimal NOT NULL, + [PriorYearActualValueNetReimbursement03] decimal NOT NULL, + [PriorYearActualValueNetReimbursement04] decimal NOT NULL, + [PriorYearActualValueNetReimbursement05] decimal NOT NULL, + [PriorYearActualValueNetReimbursement06] decimal NOT NULL, + [PriorYearActualValueNetReimbursement07] decimal NOT NULL, + [PriorYearActualValueNetReimbursement08] decimal NOT NULL, + [PriorYearActualValueNetReimbursement09] decimal NOT NULL, + [PriorYearActualValueNetReimbursement10] decimal NOT NULL, + [PriorYearActualValueNetReimbursement11] decimal NOT NULL, + [PriorYearActualValueNetReimbursement12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [FK_ReimbursementGeneralLedgerHistory_ReimbursementGeneralLedgerID] FOREIGN KEY ([ReimbursementGeneralLedgerID]) REFERENCES [fp].[ReimbursementGeneralLedger] ([ReimbursementGeneralLedgerID]); GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Reimb__29CE504E] DEFAULT ((0)) FOR [ReimbursementGeneralLedgerID]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__2AC27487] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__2BB698C0] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__2CAABCF9] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__2D9EE132] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__2E93056B] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__2F8729A4] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__307B4DDD] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__316F7216] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__3263964F] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__3357BA88] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__344BDEC1] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__354002FA] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__36342733] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge01]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__37284B6C] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge02]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__381C6FA5] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge03]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__391093DE] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge04]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__3A04B817] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge05]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__3AF8DC50] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge06]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__3BED0089] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge07]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__3CE124C2] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge08]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__3DD548FB] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge09]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__3EC96D34] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge10]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__3FBD916D] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge11]; GO +ALTER TABLE [fp].[ReimbursementGeneralLedgerHistory] ADD CONSTRAINT [DF__Reimburse__Prior__40B1B5A6] DEFAULT ((0)) FOR [PriorYearActualValueNetAsPercentOfCharge12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ReimbursementImportLog ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ReimbursementImportLog] ( + [FileAttachmentGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [FileName] nvarchar(250) NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [UserName] nvarchar(64) NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + [FileData] varbinary(max) NOT NULL, + PRIMARY KEY ([FileAttachmentGUID]) +); +GO +ALTER TABLE [fp].[ReimbursementImportLog] ADD CONSTRAINT [DF__Reimburse__FileN__00D59105] DEFAULT ('') FOR [FileName]; GO +ALTER TABLE [fp].[ReimbursementImportLog] ADD CONSTRAINT [DF__Reimburse__UserG__01C9B53E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO +ALTER TABLE [fp].[ReimbursementImportLog] ADD CONSTRAINT [DF__Reimburse__UserN__02BDD977] DEFAULT ('') FOR [UserName]; GO +ALTER TABLE [fp].[ReimbursementImportLog] ADD CONSTRAINT [DF__Reimburse__DateC__03B1FDB0] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [fp].[ReimbursementImportLog] ADD CONSTRAINT [DF__Reimburse__FileA__7EED4893] DEFAULT (newid()) FOR [FileAttachmentGUID]; GO +ALTER TABLE [fp].[ReimbursementImportLog] ADD CONSTRAINT [DF__Reimburse__Budge__7FE16CCC] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ReimbursementNetRevenueModel ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ReimbursementNetRevenueModel] ( + [RowID] int NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [EntityID] int NOT NULL, + [NetRevenueModelID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ReimbursementNetRevenueModel] ADD CONSTRAINT [FK_ReimbursementNetRevenueModel_BudgetConfigGUID] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[ReimbursementNetRevenueModel] ADD CONSTRAINT [FK_ReimbursementNetRevenueModel_EntityID] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [fp].[ReimbursementNetRevenueModel] ADD CONSTRAINT [DF__Reimburse__Budge__1ACCCF37] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[ReimbursementNetRevenueModel] ADD CONSTRAINT [DF__Reimburse__Entit__1BC0F370] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ReimbursementNetRevenueModel] ADD CONSTRAINT [DF__Reimburse__NetRe__1CB517A9] DEFAULT ((0)) FOR [NetRevenueModelID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ReimbursementProjectionMethod ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ReimbursementProjectionMethod] ( + [RowID] int NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [PayorGroupID] int NOT NULL, + [ProjectionMethodID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ReimbursementProjectionMethod] ADD CONSTRAINT [FK_ReimbursementProjectionMethod_BudgetConfigGUID] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[ReimbursementProjectionMethod] ADD CONSTRAINT [FK_ReimbursementProjectionMethod_PayorGroupID] FOREIGN KEY ([PayorGroupID]) REFERENCES [fw].[DimPayorGroup] ([PayorGroupID]); GO +ALTER TABLE [fp].[ReimbursementProjectionMethod] ADD CONSTRAINT [DF__Reimburse__Budge__3BB5945A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[ReimbursementProjectionMethod] ADD CONSTRAINT [DF__Reimburse__Payor__3CA9B893] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[ReimbursementProjectionMethod] ADD CONSTRAINT [DF__Reimburse__Proje__3D9DDCCC] DEFAULT ((0)) FOR [ProjectionMethodID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ReimbursementToGeneralLedgerCrosswalkConfiguration ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ReimbursementToGeneralLedgerCrosswalkConfiguration] ( + [RowID] int NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [PayorGroupID] int NOT NULL, + [PatientClassID] int NOT NULL, + [AccountID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ProjectionAllocationPercent] decimal NOT NULL, + [BudgetAllocationPercent] decimal NOT NULL, + [EntityID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ReimbursementToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__Reimburse__Entit__23F4B010] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ReimbursementToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__Reimburse__Budge__62710576] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[ReimbursementToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__Reimburse__Payor__636529AF] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[ReimbursementToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__Reimburse__Patie__64594DE8] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ReimbursementToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__Reimburse__Accou__654D7221] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[ReimbursementToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__Reimburse__Depar__6641965A] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ReimbursementToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__Reimburse__Proje__6735BA93] DEFAULT ((1)) FOR [ProjectionAllocationPercent]; GO +ALTER TABLE [fp].[ReimbursementToGeneralLedgerCrosswalkConfiguration] ADD CONSTRAINT [DF__Reimburse__Budge__6829DECC] DEFAULT ((1)) FOR [BudgetAllocationPercent]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.RevenueExpenseFlexingConfig ------------------ +--------------------------------------------- +CREATE TABLE [fp].[RevenueExpenseFlexingConfig] ( + [EntityGroupConfigGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [FlexMethodID] smallint NOT NULL, + PRIMARY KEY ([EntityGroupConfigGUID], [DepartmentID]) +); +GO +ALTER TABLE [fp].[RevenueExpenseFlexingConfig] ADD CONSTRAINT [FK__RevenueEx__Depar__3FCD10A5] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[RevenueExpenseFlexingConfig] ADD CONSTRAINT [DF__RevenueEx__Depar__26EDB926] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[RevenueExpenseFlexingConfig] ADD CONSTRAINT [df_RevenueExpenseFlexingConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO +ALTER TABLE [fp].[RevenueExpenseFlexingConfig] ADD CONSTRAINT [DF__RevenueEx__FlexM__27E1DD5F] DEFAULT ((0)) FOR [FlexMethodID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.RevenueFlexingOverrideConfig ------------------ +--------------------------------------------- +CREATE TABLE [fp].[RevenueFlexingOverrideConfig] ( + [OverrideFlexConfigGUID] uniqueidentifier NOT NULL, + [EntityGroupConfigGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FlexMethodID] smallint NOT NULL, + PRIMARY KEY ([OverrideFlexConfigGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [Unique_RevenueFlexingOverrideConfig_EC_Dept_Account] ON [fp].[RevenueFlexingOverrideConfig] ([EntityGroupConfigGUID], [DepartmentID], [AccountID]); +GO +ALTER TABLE [fp].[RevenueFlexingOverrideConfig] ADD CONSTRAINT [FK__RevenueFl__Accou__439DA189] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [fp].[RevenueFlexingOverrideConfig] ADD CONSTRAINT [FK__RevenueFl__Depar__42A97D50] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[RevenueFlexingOverrideConfig] ADD CONSTRAINT [df_RevenueFlexingOverrideConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO +ALTER TABLE [fp].[RevenueFlexingOverrideConfig] ADD CONSTRAINT [DF__RevenueFl__Overr__2BB26E43] DEFAULT (newid()) FOR [OverrideFlexConfigGUID]; GO +ALTER TABLE [fp].[RevenueFlexingOverrideConfig] ADD CONSTRAINT [DF__RevenueFl__Depar__2D9AB6B5] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[RevenueFlexingOverrideConfig] ADD CONSTRAINT [DF__RevenueFl__Accou__2E8EDAEE] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[RevenueFlexingOverrideConfig] ADD CONSTRAINT [DF__RevenueFl__FlexM__2F82FF27] DEFAULT ((0)) FOR [FlexMethodID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.RevenueFlexingOverrideConfigAssignment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[RevenueFlexingOverrideConfigAssignment] ( + [OverrideFlexConfigGUID] uniqueidentifier NOT NULL, + [AccountID] int NOT NULL, + PRIMARY KEY ([OverrideFlexConfigGUID], [AccountID]) +); +GO +ALTER TABLE [fp].[RevenueFlexingOverrideConfigAssignment] ADD CONSTRAINT [FK_RevenueFlexingOverrideConfig_OverrideFlexConfigGUID] FOREIGN KEY ([OverrideFlexConfigGUID]) REFERENCES [fp].[RevenueFlexingOverrideConfig] ([OverrideFlexConfigGUID]); GO +ALTER TABLE [fp].[RevenueFlexingOverrideConfigAssignment] ADD CONSTRAINT [DF__RevenueFl__Overr__325F6BD2] DEFAULT (newid()) FOR [OverrideFlexConfigGUID]; GO +ALTER TABLE [fp].[RevenueFlexingOverrideConfigAssignment] ADD CONSTRAINT [DF__RevenueFl__Accou__3353900B] DEFAULT ((0)) FOR [AccountID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.RosterBudgetBasis ------------------ +--------------------------------------------- +CREATE TABLE [fp].[RosterBudgetBasis] ( + [RowID] int NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [InitialDollars] decimal NOT NULL, + [Dollars] decimal NOT NULL, + [FTEs] decimal NOT NULL, + [InitialFTEs] decimal NOT NULL, + [ProjectedDollars] decimal NOT NULL, + [ProjectedFTEs] decimal NOT NULL, + [EmployeeID] int NOT NULL, + [JobCodeID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [ActualYTDDollars] decimal NOT NULL, + [ActualYTDFTEs] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_RosterBudgetBasis] ON [fp].[RosterBudgetBasis] ([BudgetConfigGUID], [EmployeeID], [JobCodeID]); +GO +ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [df_RosterBudgetBasis_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [DF__RosterBud__Actua__61B0EE46] DEFAULT ((0)) FOR [ActualYTDDollars]; GO +ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [DF__RosterBud__Actua__639936B8] DEFAULT ((0)) FOR [ActualYTDFTEs]; GO +ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [DF__RosterBud__Emplo__6FAA07E2] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [DF__RosterBud__JobCo__709E2C1B] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [DF__RosterBud__Histo__71925054] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [Default_RosterBasis_InitialFTEs] DEFAULT ((0)) FOR [InitialFTEs]; GO +ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [Default_RosterBasis_FTEs] DEFAULT ((0)) FOR [FTEs]; GO +ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [Default_RosterBasis_ProjectedFTEs] DEFAULT ((0)) FOR [ProjectedFTEs]; GO +ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [Default_RosterBasis_InitialDollars] DEFAULT ((0)) FOR [InitialDollars]; GO +ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [Default_RosterBasis_Dollars] DEFAULT ((0)) FOR [Dollars]; GO +ALTER TABLE [fp].[RosterBudgetBasis] ADD CONSTRAINT [Default_RosterBasis_ProjectedDollars] DEFAULT ((0)) FOR [ProjectedDollars]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.RosterBudgetBasisHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[RosterBudgetBasisHistory] ( + [RowID] int NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [UserGuid] uniqueidentifier NOT NULL, + [Date] datetime NOT NULL, + [FTEs] decimal NOT NULL, + [DollarType] varchar(100) NULL, + [OriginalDollars] decimal NOT NULL, + [FinalDollars] decimal NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[RosterBudgetBasisHistory] ADD CONSTRAINT [DF__RosterBud__Histo__03B1008F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fp].[RosterBudgetBasisHistory] ADD CONSTRAINT [Default_RosterBasisHist_FTEs] DEFAULT ((0)) FOR [FTEs]; GO +ALTER TABLE [fp].[RosterBudgetBasisHistory] ADD CONSTRAINT [DF__RosterBud__UserG__0CE16C5B] DEFAULT (newid()) FOR [UserGuid]; GO +ALTER TABLE [fp].[RosterBudgetBasisHistory] ADD CONSTRAINT [DF__RosterBudg__Date__0DD59094] DEFAULT (CONVERT([datetime],(0))) FOR [Date]; GO +ALTER TABLE [fp].[RosterBudgetBasisHistory] ADD CONSTRAINT [df_RosterBudgetBasisHistory_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[RosterBudgetBasisHistory] ADD CONSTRAINT [DF__RosterBud__Dolla__5428DD43] DEFAULT ('Budget') FOR [DollarType]; GO +ALTER TABLE [fp].[RosterBudgetBasisHistory] ADD CONSTRAINT [DF__RosterBud__Origi__5488CFF6] DEFAULT ((0)) FOR [OriginalDollars]; GO +ALTER TABLE [fp].[RosterBudgetBasisHistory] ADD CONSTRAINT [DF__RosterBud__Final__557CF42F] DEFAULT ((0)) FOR [FinalDollars]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.RosterBudgetBasisResult ------------------ +--------------------------------------------- +CREATE TABLE [fp].[RosterBudgetBasisResult] ( + [RowID] int NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [Dollars] decimal NOT NULL, + [InitialDollars] decimal NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [FTEs] decimal NOT NULL, + [ProjectedDollars] decimal NOT NULL, + [ProjectedFTEs] decimal NOT NULL, + [EmployeeID] int NOT NULL, + [JobCodeID] int NOT NULL, + [DepartmentID] int NOT NULL, + [PayCodeGroupID] int NOT NULL, + [ActualYTDDollars] decimal NOT NULL, + [ActualYTDFTEs] decimal NOT NULL, + [InitialFTEs] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_RosterBudgetBasisResult] ON [fp].[RosterBudgetBasisResult] ([BudgetConfigGUID], [EmployeeID], [JobCodeID], [DepartmentID], [PayCodeGroupID]); +GO +ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [Default_RosterBasisResult_Dollars] DEFAULT ((0)) FOR [Dollars]; GO +ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [Default_RosterBasisResult_ProjectedDollars] DEFAULT ((0)) FOR [ProjectedDollars]; GO +ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [df_RosterBudgetBasisResult_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [DF__RosterBud__Actua__60BCCA0D] DEFAULT ((0)) FOR [ActualYTDDollars]; GO +ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [DF__RosterBud__Actua__62A5127F] DEFAULT ((0)) FOR [ActualYTDFTEs]; GO +ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [DF__RosterBud__Comme__6A0D316A] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [DF__RosterBud__Initi__73308003] DEFAULT ((0.0)) FOR [InitialFTEs]; GO +ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [DF__RosterBud__Emplo__7933721C] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [DF__RosterBud__JobCo__7A279655] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [DF__RosterBud__Depar__7B1BBA8E] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [DF__RosterBud__PayCo__7C0FDEC7] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [Default_RosterBasisResult_FTEs] DEFAULT ((0)) FOR [FTEs]; GO +ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [Default_RosterBasisResult_ProjectedFTEs] DEFAULT ((0)) FOR [ProjectedFTEs]; GO +ALTER TABLE [fp].[RosterBudgetBasisResult] ADD CONSTRAINT [Default_RosterBasisResult_InitialDollars] DEFAULT ((0)) FOR [InitialDollars]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.RosterBudgetBasisResultHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[RosterBudgetBasisResultHistory] ( + [RowID] int NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [UserGuid] uniqueidentifier NOT NULL, + [Date] datetime NOT NULL, + [DollarType] varchar(100) NULL, + [OriginalDollars] decimal NOT NULL, + [FinalDollars] decimal NOT NULL, + [EmployeeID] int NOT NULL, + [JobCodeID] int NOT NULL, + [DepartmentID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[RosterBudgetBasisResultHistory] ADD CONSTRAINT [DF__RosterBud__Emplo__0969D9E5] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[RosterBudgetBasisResultHistory] ADD CONSTRAINT [DF__RosterBud__JobCo__0A5DFE1E] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[RosterBudgetBasisResultHistory] ADD CONSTRAINT [DF__RosterBud__Depar__0B522257] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[RosterBudgetBasisResultHistory] ADD CONSTRAINT [DF__RosterBud__UserG__175EFACE] DEFAULT (newid()) FOR [UserGuid]; GO +ALTER TABLE [fp].[RosterBudgetBasisResultHistory] ADD CONSTRAINT [DF__RosterBudg__Date__18531F07] DEFAULT (CONVERT([datetime],(0))) FOR [Date]; GO +ALTER TABLE [fp].[RosterBudgetBasisResultHistory] ADD CONSTRAINT [df_RosterBudgetBasisResultHistory_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[RosterBudgetBasisResultHistory] ADD CONSTRAINT [DF__RosterBud__Dolla__551D017C] DEFAULT ('Budget') FOR [DollarType]; GO +ALTER TABLE [fp].[RosterBudgetBasisResultHistory] ADD CONSTRAINT [DF__RosterBud__Origi__56711868] DEFAULT ((0)) FOR [OriginalDollars]; GO +ALTER TABLE [fp].[RosterBudgetBasisResultHistory] ADD CONSTRAINT [DF__RosterBud__Final__57653CA1] DEFAULT ((0)) FOR [FinalDollars]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.RosterBudgetHoursMix ------------------ +--------------------------------------------- +CREATE TABLE [fp].[RosterBudgetHoursMix] ( + [RowID] int NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [Value] decimal NOT NULL, + [PayCodeGroupID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[RosterBudgetHoursMix] ADD CONSTRAINT [df_RosterBudgetHoursMix_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[RosterBudgetHoursMix] ADD CONSTRAINT [DF__RosterBud__Value__6063CB9F] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[RosterBudgetHoursMix] ADD CONSTRAINT [DF__RosterBud__PayCo__66209DA8] DEFAULT ((0)) FOR [PayCodeGroupID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.RosterBudgetNewEmployee ------------------ +--------------------------------------------- +CREATE TABLE [fp].[RosterBudgetNewEmployee] ( + [RowID] int NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [EmployeeNumber] nvarchar(400) NOT NULL, + [FiscalYearID] smallint NULL, + [EmployeeID] int NOT NULL, + [PositionNumber] nvarchar(100) NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_RosterBudgetNewEmployee] ON [fp].[RosterBudgetNewEmployee] ([BudgetConfigGUID], [EmployeeID]); +GO +ALTER TABLE [fp].[RosterBudgetNewEmployee] ADD CONSTRAINT [DF__RosterBud__Fisca__37C1A8BF] DEFAULT (datepart(year,getdate())) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[RosterBudgetNewEmployee] ADD CONSTRAINT [df_RosterBudgetNewEmployee_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[RosterBudgetNewEmployee] ADD CONSTRAINT [DF__RosterBud__Emplo__663CA086] DEFAULT ('') FOR [EmployeeNumber]; GO +ALTER TABLE [fp].[RosterBudgetNewEmployee] ADD CONSTRAINT [DF__RosterBud__Emplo__6808E61A] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[RosterBudgetNewEmployee] ADD CONSTRAINT [DF__RosterBud__Posit__754DD29F] DEFAULT ('') FOR [PositionNumber]; GO +ALTER TABLE [fp].[RosterBudgetNewEmployee] ADD CONSTRAINT [DF__RosterBud__Fisca__7A239DA2] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[RosterBudgetNewEmployee] ADD CONSTRAINT [DF__RosterBud__Comme__7B17C1DB] DEFAULT ('') FOR [Comment]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.RosterBudgetRequest ------------------ +--------------------------------------------- +CREATE TABLE [fp].[RosterBudgetRequest] ( + [RowID] int NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [UserGuid] uniqueidentifier NOT NULL, + [Status] tinyint NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [Date] datetime NOT NULL, + [Dollars] decimal NOT NULL, + [DollarType] varchar(100) NULL, + [JobCodeID] int NOT NULL, + [PayCodeGroupID] int NOT NULL, + [DepartmentID] int NOT NULL, + [EmployeeID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [DF__RosterBud__UserG__20E86508] DEFAULT (newid()) FOR [UserGuid]; GO +ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [DF__RosterBud__Statu__21DC8941] DEFAULT ((0)) FOR [Status]; GO +ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [DF__RosterBud__Comme__22D0AD7A] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [DF__RosterBudg__Date__23C4D1B3] DEFAULT (CONVERT([datetime],(0))) FOR [Date]; GO +ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [df_RosterBudgetRequest_BudgetConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [DF__RosterBud__Dolla__5334B90A] DEFAULT ('Budget') FOR [DollarType]; GO +ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [DF__RosterBud__JobCo__69F12E8C] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [DF__RosterBud__PayCo__6AE552C5] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [DF__RosterBud__Depar__6BD976FE] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [DF__RosterBud__Emplo__6CCD9B37] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[RosterBudgetRequest] ADD CONSTRAINT [Default_RosterBasisReq_Dollars] DEFAULT ((0)) FOR [Dollars]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.SamplingLog ------------------ +--------------------------------------------- +CREATE TABLE [fp].[SamplingLog] ( + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [PlanSectionID] int NOT NULL, + [PlanSectionDescription] nvarchar(300) NOT NULL, + [SourceDimensionalityJSON] nvarchar(max) NOT NULL, + [DateStartedUTC] datetime NOT NULL, + [DateEndedUTC] datetime NOT NULL, + [IsInitialPlanMethod] bit NOT NULL, + [IsDSSampling] bit NOT NULL, + [NumberOfRecordsSampled] int NOT NULL, + [JazzVersion] nvarchar(10) NOT NULL +); +GO +ALTER TABLE [fp].[SamplingLog] ADD CONSTRAINT [DF__SamplingL__Sourc__11220488] DEFAULT ('') FOR [SourceDimensionalityJSON]; GO +ALTER TABLE [fp].[SamplingLog] ADD CONSTRAINT [DF__SamplingL__DateS__121628C1] DEFAULT ('1900-01-01T00:00:00') FOR [DateStartedUTC]; GO +ALTER TABLE [fp].[SamplingLog] ADD CONSTRAINT [DF__SamplingL__DateE__130A4CFA] DEFAULT ('1900-01-01T00:00:00') FOR [DateEndedUTC]; GO +ALTER TABLE [fp].[SamplingLog] ADD CONSTRAINT [DF__SamplingL__IsIni__13FE7133] DEFAULT ((0)) FOR [IsInitialPlanMethod]; GO +ALTER TABLE [fp].[SamplingLog] ADD CONSTRAINT [DF__SamplingL__IsDSS__14F2956C] DEFAULT ((0)) FOR [IsDSSampling]; GO +ALTER TABLE [fp].[SamplingLog] ADD CONSTRAINT [DF__SamplingL__Numbe__15E6B9A5] DEFAULT ((0)) FOR [NumberOfRecordsSampled]; GO +ALTER TABLE [fp].[SamplingLog] ADD CONSTRAINT [DF__SamplingL__JazzV__52BABDBB] DEFAULT ('') FOR [JazzVersion]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ScheduledRefreshRequest ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ScheduledRefreshRequest] ( + [RequestGUID] uniqueidentifier NOT NULL, + [SourceDimensionalityJSON] nvarchar(max) NOT NULL, + [SourceActionID] smallint NOT NULL, + [IsIgnoreTargetingError] bit NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [SamplingJSON] nvarchar(max) NOT NULL, + [SortOrder] int NOT NULL, + [IsActive] bit NOT NULL, + PRIMARY KEY ([RequestGUID]) +); +GO +ALTER TABLE [fp].[ScheduledRefreshRequest] ADD CONSTRAINT [DF__Scheduled__Reque__394270AC] DEFAULT (newid()) FOR [RequestGUID]; GO +ALTER TABLE [fp].[ScheduledRefreshRequest] ADD CONSTRAINT [DF__Scheduled__Sourc__3A3694E5] DEFAULT ('') FOR [SourceDimensionalityJSON]; GO +ALTER TABLE [fp].[ScheduledRefreshRequest] ADD CONSTRAINT [DF__Scheduled__Sourc__3B2AB91E] DEFAULT ((0)) FOR [SourceActionID]; GO +ALTER TABLE [fp].[ScheduledRefreshRequest] ADD CONSTRAINT [DF__Scheduled__IsIgn__3C1EDD57] DEFAULT ((0)) FOR [IsIgnoreTargetingError]; GO +ALTER TABLE [fp].[ScheduledRefreshRequest] ADD CONSTRAINT [DF__Scheduled__Entit__3D130190] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[ScheduledRefreshRequest] ADD CONSTRAINT [DF__Scheduled__SortO__3EFB4A02] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fp].[ScheduledRefreshRequest] ADD CONSTRAINT [DF__Scheduled__IsAct__3FEF6E3B] DEFAULT ((0)) FOR [IsActive]; GO +ALTER TABLE [fp].[ScheduledRefreshRequest] ADD CONSTRAINT [df_SamplingJSON] DEFAULT ('') FOR [SamplingJSON]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.SectionSetup ------------------ +--------------------------------------------- +CREATE TABLE [fp].[SectionSetup] ( + [SectionSetupGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [PlanSectionID] int NOT NULL, + [SubSectionID] int NOT NULL, + [LevelID] varchar(50) NOT NULL, + [IsHidden] bit NOT NULL, + PRIMARY KEY ([SectionSetupGUID]) +); +GO +ALTER TABLE [fp].[SectionSetup] ADD CONSTRAINT [FK__SectionSe__Budge__0FD646C5] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[SectionSetup] ADD CONSTRAINT [FK__SectionSe__PlanS__10CA6AFE] FOREIGN KEY ([PlanSectionID]) REFERENCES [fp].[PlanSection] ([PlanSectionID]); GO +ALTER TABLE [fp].[SectionSetup] ADD CONSTRAINT [FK__SectionSe__SubSe__11BE8F37] FOREIGN KEY ([SubSectionID]) REFERENCES [fp].[PlanSubsection] ([SubsectionID]); GO +ALTER TABLE [fp].[SectionSetup] ADD CONSTRAINT [DF__SectionSe__PlanS__0C05B5E1] DEFAULT ((0)) FOR [PlanSectionID]; GO +ALTER TABLE [fp].[SectionSetup] ADD CONSTRAINT [DF__SectionSe__SubSe__0CF9DA1A] DEFAULT ((0)) FOR [SubSectionID]; GO +ALTER TABLE [fp].[SectionSetup] ADD CONSTRAINT [DF__SectionSe__Level__0DEDFE53] DEFAULT ('') FOR [LevelID]; GO +ALTER TABLE [fp].[SectionSetup] ADD CONSTRAINT [DF__SectionSe__IsHid__0EE2228C] DEFAULT ((0)) FOR [IsHidden]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ServiceLineEncounter ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ServiceLineEncounter] ( + [ServiceLineEncounterID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [DepartmentID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [MSDRGID] int NOT NULL, + [CPTID] int NOT NULL, + [ProviderID] int NOT NULL, + [PhysicianSpecialtyID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [AddDate] datetime NOT NULL, + [SampledBudgetTotal] decimal NOT NULL, + [SampledProjectionTotal] decimal NOT NULL, + [InitialBudgetTotal] decimal NOT NULL, + [InitialProjectionTotal] decimal NOT NULL, + [TargetAdjustedTotal] decimal NOT NULL, + [BudgetAdjustedTotal] decimal NOT NULL, + [ProjectionAdjustedTotal] decimal NOT NULL, + [SampledBudget01] decimal NOT NULL, + [SampledBudget02] decimal NOT NULL, + [SampledBudget03] decimal NOT NULL, + [SampledBudget04] decimal NOT NULL, + [SampledBudget05] decimal NOT NULL, + [SampledBudget06] decimal NOT NULL, + [SampledBudget07] decimal NOT NULL, + [SampledBudget08] decimal NOT NULL, + [SampledBudget09] decimal NOT NULL, + [SampledBudget10] decimal NOT NULL, + [SampledBudget11] decimal NOT NULL, + [SampledBudget12] decimal NOT NULL, + [SampledProjection01] decimal NOT NULL, + [SampledProjection02] decimal NOT NULL, + [SampledProjection03] decimal NOT NULL, + [SampledProjection04] decimal NOT NULL, + [SampledProjection05] decimal NOT NULL, + [SampledProjection06] decimal NOT NULL, + [SampledProjection07] decimal NOT NULL, + [SampledProjection08] decimal NOT NULL, + [SampledProjection09] decimal NOT NULL, + [SampledProjection10] decimal NOT NULL, + [SampledProjection11] decimal NOT NULL, + [SampledProjection12] decimal NOT NULL, + [InitialBudget01] decimal NOT NULL, + [InitialBudget02] decimal NOT NULL, + [InitialBudget03] decimal NOT NULL, + [InitialBudget04] decimal NOT NULL, + [InitialBudget05] decimal NOT NULL, + [InitialBudget06] decimal NOT NULL, + [InitialBudget07] decimal NOT NULL, + [InitialBudget08] decimal NOT NULL, + [InitialBudget09] decimal NOT NULL, + [InitialBudget10] decimal NOT NULL, + [InitialBudget11] decimal NOT NULL, + [InitialBudget12] decimal NOT NULL, + [InitialProjection01] decimal NOT NULL, + [InitialProjection02] decimal NOT NULL, + [InitialProjection03] decimal NOT NULL, + [InitialProjection04] decimal NOT NULL, + [InitialProjection05] decimal NOT NULL, + [InitialProjection06] decimal NOT NULL, + [InitialProjection07] decimal NOT NULL, + [InitialProjection08] decimal NOT NULL, + [InitialProjection09] decimal NOT NULL, + [InitialProjection10] decimal NOT NULL, + [InitialProjection11] decimal NOT NULL, + [InitialProjection12] decimal NOT NULL, + [TargetAdjusted01] decimal NOT NULL, + [TargetAdjusted02] decimal NOT NULL, + [TargetAdjusted03] decimal NOT NULL, + [TargetAdjusted04] decimal NOT NULL, + [TargetAdjusted05] decimal NOT NULL, + [TargetAdjusted06] decimal NOT NULL, + [TargetAdjusted07] decimal NOT NULL, + [TargetAdjusted08] decimal NOT NULL, + [TargetAdjusted09] decimal NOT NULL, + [TargetAdjusted10] decimal NOT NULL, + [TargetAdjusted11] decimal NOT NULL, + [TargetAdjusted12] decimal NOT NULL, + [BudgetAdjusted01] decimal NOT NULL, + [BudgetAdjusted02] decimal NOT NULL, + [BudgetAdjusted03] decimal NOT NULL, + [BudgetAdjusted04] decimal NOT NULL, + [BudgetAdjusted05] decimal NOT NULL, + [BudgetAdjusted06] decimal NOT NULL, + [BudgetAdjusted07] decimal NOT NULL, + [BudgetAdjusted08] decimal NOT NULL, + [BudgetAdjusted09] decimal NOT NULL, + [BudgetAdjusted10] decimal NOT NULL, + [BudgetAdjusted11] decimal NOT NULL, + [BudgetAdjusted12] decimal NOT NULL, + [ProjectionAdjusted01] decimal NOT NULL, + [ProjectionAdjusted02] decimal NOT NULL, + [ProjectionAdjusted03] decimal NOT NULL, + [ProjectionAdjusted04] decimal NOT NULL, + [ProjectionAdjusted05] decimal NOT NULL, + [ProjectionAdjusted06] decimal NOT NULL, + [ProjectionAdjusted07] decimal NOT NULL, + [ProjectionAdjusted08] decimal NOT NULL, + [ProjectionAdjusted09] decimal NOT NULL, + [ProjectionAdjusted10] decimal NOT NULL, + [ProjectionAdjusted11] decimal NOT NULL, + [ProjectionAdjusted12] decimal NOT NULL, + [IsNew] bit NOT NULL, + [BudgetLockType] tinyint NOT NULL, + [BudgetLockFlag] tinyint NOT NULL, + [TargetLockType] tinyint NOT NULL, + [TargetLockFlag] tinyint NOT NULL, + [ProjectionLockType] tinyint NOT NULL, + [ProjectionLockFlag] tinyint NOT NULL, + PRIMARY KEY ([ServiceLineEncounterID]) +); + +CREATE CLUSTERED INDEX [IX_ServiceLineEncounter_Clustered] ON [fp].[ServiceLineEncounter] ([BudgetConfigID], [EntityID], [PatientClassID], [ServiceLineRollupID], [ServiceLineID]); +CREATE NONCLUSTERED INDEX [IX_ServiceLineEncounter_BudgetConfig] ON [fp].[ServiceLineEncounter] ([BudgetConfigID]) INCLUDE ([ServiceLineEncounterID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ServiceLineEncounter_Department] ON [fp].[ServiceLineEncounter] ([DepartmentID]) INCLUDE ([ServiceLineEncounterID], [BudgetConfigID], [EntityGroupConfigID], [PatientClassID], [EntityID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ServiceLineEncounter_Entity] ON [fp].[ServiceLineEncounter] ([EntityID]) INCLUDE ([ServiceLineEncounterID], [BudgetConfigID], [EntityGroupConfigID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ServiceLineEncounter_EntityGroupConfig] ON [fp].[ServiceLineEncounter] ([EntityGroupConfigID]) INCLUDE ([ServiceLineEncounterID], [BudgetConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]); +CREATE NONCLUSTERED INDEX [IX_ServiceLineEncounter_ServiceLine] ON [fp].[ServiceLineEncounter] ([ServiceLineID]) INCLUDE ([ServiceLineEncounterID], [BudgetConfigID], [EntityGroupConfigID], [PatientClassID], [EntityID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_ServiceLineEncounterUnique] ON [fp].[ServiceLineEncounter] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID]); +GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_AgeCohort] FOREIGN KEY ([AgeCohortID]) REFERENCES [fw].[DimAgeCohort] ([AgeCohortID]); GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_CPT] FOREIGN KEY ([CPTID]) REFERENCES [dss].[DimCPT] ([CPTID]); GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_MedicalSurgical] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_Payor] FOREIGN KEY ([PayorID]) REFERENCES [fw].[DimPayor] ([PayorID]); GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_PayorGroup] FOREIGN KEY ([PayorGroupID]) REFERENCES [fw].[DimPayorGroup] ([PayorGroupID]); GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_ServiceLine] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_ServiceLineRollup] FOREIGN KEY ([ServiceLineRollupID]) REFERENCES [fw].[DimServiceLineRollup] ([ServiceLineRollupID]); GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [FK_ServiceLineEncounter_UnitType] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__00A15232] DEFAULT ((0)) FOR [InitialBudget11]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__0195766B] DEFAULT ((0)) FOR [InitialBudget12]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__02899AA4] DEFAULT ((0)) FOR [InitialProjection01]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__037DBEDD] DEFAULT ((0)) FOR [InitialProjection02]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__0471E316] DEFAULT ((0)) FOR [InitialProjection03]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__0566074F] DEFAULT ((0)) FOR [InitialProjection04]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__065A2B88] DEFAULT ((0)) FOR [InitialProjection05]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__074E4FC1] DEFAULT ((0)) FOR [InitialProjection06]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__084273FA] DEFAULT ((0)) FOR [InitialProjection07]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__09369833] DEFAULT ((0)) FOR [InitialProjection08]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__0A2ABC6C] DEFAULT ((0)) FOR [InitialProjection09]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__0B1EE0A5] DEFAULT ((0)) FOR [InitialProjection10]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__0C1304DE] DEFAULT ((0)) FOR [InitialProjection11]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__0D072917] DEFAULT ((0)) FOR [InitialProjection12]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__0DFB4D50] DEFAULT ((0)) FOR [TargetAdjusted01]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__0EEF7189] DEFAULT ((0)) FOR [TargetAdjusted02]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__0FE395C2] DEFAULT ((0)) FOR [TargetAdjusted03]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__10D7B9FB] DEFAULT ((0)) FOR [TargetAdjusted04]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__11CBDE34] DEFAULT ((0)) FOR [TargetAdjusted05]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__12C0026D] DEFAULT ((0)) FOR [TargetAdjusted06]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__13B426A6] DEFAULT ((0)) FOR [TargetAdjusted07]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__14A84ADF] DEFAULT ((0)) FOR [TargetAdjusted08]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__159C6F18] DEFAULT ((0)) FOR [TargetAdjusted09]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__16909351] DEFAULT ((0)) FOR [TargetAdjusted10]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__1784B78A] DEFAULT ((0)) FOR [TargetAdjusted11]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__1878DBC3] DEFAULT ((0)) FOR [TargetAdjusted12]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__196CFFFC] DEFAULT ((0)) FOR [BudgetAdjusted01]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__1A612435] DEFAULT ((0)) FOR [BudgetAdjusted02]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__1B55486E] DEFAULT ((0)) FOR [BudgetAdjusted03]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__1C496CA7] DEFAULT ((0)) FOR [BudgetAdjusted04]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__1D3D90E0] DEFAULT ((0)) FOR [BudgetAdjusted05]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__1E31B519] DEFAULT ((0)) FOR [BudgetAdjusted06]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__1F25D952] DEFAULT ((0)) FOR [BudgetAdjusted07]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__2019FD8B] DEFAULT ((0)) FOR [BudgetAdjusted08]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__210E21C4] DEFAULT ((0)) FOR [BudgetAdjusted09]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__220245FD] DEFAULT ((0)) FOR [BudgetAdjusted10]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__22F66A36] DEFAULT ((0)) FOR [BudgetAdjusted11]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__23EA8E6F] DEFAULT ((0)) FOR [BudgetAdjusted12]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__24DEB2A8] DEFAULT ((0)) FOR [ProjectionAdjusted01]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__25D2D6E1] DEFAULT ((0)) FOR [ProjectionAdjusted02]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__26C6FB1A] DEFAULT ((0)) FOR [ProjectionAdjusted03]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__27BB1F53] DEFAULT ((0)) FOR [ProjectionAdjusted04]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__28AF438C] DEFAULT ((0)) FOR [ProjectionAdjusted05]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__29A367C5] DEFAULT ((0)) FOR [ProjectionAdjusted06]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__2A978BFE] DEFAULT ((0)) FOR [ProjectionAdjusted07]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__2B8BB037] DEFAULT ((0)) FOR [ProjectionAdjusted08]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__2C7FD470] DEFAULT ((0)) FOR [ProjectionAdjusted09]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__2D73F8A9] DEFAULT ((0)) FOR [ProjectionAdjusted10]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__2E681CE2] DEFAULT ((0)) FOR [ProjectionAdjusted11]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__2F5C411B] DEFAULT ((0)) FOR [ProjectionAdjusted12]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__IsNew__30506554] DEFAULT ((0)) FOR [IsNew]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__3144898D] DEFAULT ((0)) FOR [BudgetLockType]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__3238ADC6] DEFAULT ((0)) FOR [BudgetLockFlag]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__332CD1FF] DEFAULT ((0)) FOR [TargetLockType]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Targe__3420F638] DEFAULT ((0)) FOR [TargetLockFlag]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__35151A71] DEFAULT ((0)) FOR [ProjectionLockType]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Proje__36093EAA] DEFAULT ((0)) FOR [ProjectionLockFlag]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Budge__4FFE1AD7] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Entit__50F23F10] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Entit__51E66349] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Patie__52DA8782] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Servi__53CEABBB] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Servi__54C2CFF4] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__AgeCo__55B6F42D] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Medic__56AB1866] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Depar__579F3C9F] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Payor__589360D8] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Payor__59878511] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__MSDRG__5A7BA94A] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__CPTID__5B6FCD83] DEFAULT ((0)) FOR [CPTID]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Provi__5C63F1BC] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Physi__5D5815F5] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__UnitT__5E4C3A2E] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__AddDa__5F405E67] DEFAULT (getdate()) FOR [AddDate]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__603482A0] DEFAULT ((0)) FOR [SampledBudget01]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__6128A6D9] DEFAULT ((0)) FOR [SampledBudget02]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__621CCB12] DEFAULT ((0)) FOR [SampledBudget03]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__6310EF4B] DEFAULT ((0)) FOR [SampledBudget04]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__64051384] DEFAULT ((0)) FOR [SampledBudget05]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__64F937BD] DEFAULT ((0)) FOR [SampledBudget06]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__65ED5BF6] DEFAULT ((0)) FOR [SampledBudget07]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__66E1802F] DEFAULT ((0)) FOR [SampledBudget08]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__67D5A468] DEFAULT ((0)) FOR [SampledBudget09]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__68C9C8A1] DEFAULT ((0)) FOR [SampledBudget10]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__69BDECDA] DEFAULT ((0)) FOR [SampledBudget11]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__6AB21113] DEFAULT ((0)) FOR [SampledBudget12]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__6BA6354C] DEFAULT ((0)) FOR [SampledProjection01]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__6C9A5985] DEFAULT ((0)) FOR [SampledProjection02]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__6D8E7DBE] DEFAULT ((0)) FOR [SampledProjection03]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__6E82A1F7] DEFAULT ((0)) FOR [SampledProjection04]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__6F76C630] DEFAULT ((0)) FOR [SampledProjection05]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__706AEA69] DEFAULT ((0)) FOR [SampledProjection06]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__715F0EA2] DEFAULT ((0)) FOR [SampledProjection07]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__725332DB] DEFAULT ((0)) FOR [SampledProjection08]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__73475714] DEFAULT ((0)) FOR [SampledProjection09]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__743B7B4D] DEFAULT ((0)) FOR [SampledProjection10]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__752F9F86] DEFAULT ((0)) FOR [SampledProjection11]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Sampl__7623C3BF] DEFAULT ((0)) FOR [SampledProjection12]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__7717E7F8] DEFAULT ((0)) FOR [InitialBudget01]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__780C0C31] DEFAULT ((0)) FOR [InitialBudget02]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__7900306A] DEFAULT ((0)) FOR [InitialBudget03]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__79F454A3] DEFAULT ((0)) FOR [InitialBudget04]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__7AE878DC] DEFAULT ((0)) FOR [InitialBudget05]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__7BDC9D15] DEFAULT ((0)) FOR [InitialBudget06]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__7CD0C14E] DEFAULT ((0)) FOR [InitialBudget07]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__7DC4E587] DEFAULT ((0)) FOR [InitialBudget08]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__7EB909C0] DEFAULT ((0)) FOR [InitialBudget09]; GO +ALTER TABLE [fp].[ServiceLineEncounter] ADD CONSTRAINT [DF__ServiceLi__Initi__7FAD2DF9] DEFAULT ((0)) FOR [InitialBudget10]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ServiceLineEncounterAddProviderAdjustment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [DepartmentID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [MSDRGID] int NOT NULL, + [CPTID] int NOT NULL, + [ProviderID] int NOT NULL, + [PhysicianSpecialtyID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [Value01] decimal NOT NULL, + [Value02] decimal NOT NULL, + [Value03] decimal NOT NULL, + [Value04] decimal NOT NULL, + [Value05] decimal NOT NULL, + [Value06] decimal NOT NULL, + [Value07] decimal NOT NULL, + [Value08] decimal NOT NULL, + [Value09] decimal NOT NULL, + [Value10] decimal NOT NULL, + [Value11] decimal NOT NULL, + [Value12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [CLU_SLEAddProvider] ON [fp].[ServiceLineEncounterAddProviderAdjustment] ([BudgetConfigID], [DepartmentID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_ClusteredUnique] ON [fp].[ServiceLineEncounterAddProviderAdjustment] ([BudgetConfigID], [AdjustmentGUID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [TimeClassID], [BudgetPhaseID]); +GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Budge__1C3B5253] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Adjus__1D2F768C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Entit__1E239AC5] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Patie__1F17BEFE] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Servi__200BE337] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Servi__21000770] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__AgeCo__21F42BA9] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Medic__22E84FE2] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Depar__23DC741B] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Payor__24D09854] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Payor__25C4BC8D] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__MSDRG__26B8E0C6] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__CPTID__27AD04FF] DEFAULT ((0)) FOR [CPTID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Provi__28A12938] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Physi__29954D71] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__TimeC__2A8971AA] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Budge__2B7D95E3] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__IsRec__2C71BA1C] DEFAULT ((0)) FOR [IsRecordDeleted]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__2D65DE55] DEFAULT ((0)) FOR [Value01]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__2E5A028E] DEFAULT ((0)) FOR [Value02]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__2F4E26C7] DEFAULT ((0)) FOR [Value03]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__30424B00] DEFAULT ((0)) FOR [Value04]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__31366F39] DEFAULT ((0)) FOR [Value05]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__322A9372] DEFAULT ((0)) FOR [Value06]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__331EB7AB] DEFAULT ((0)) FOR [Value07]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__3412DBE4] DEFAULT ((0)) FOR [Value08]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__3507001D] DEFAULT ((0)) FOR [Value09]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__35FB2456] DEFAULT ((0)) FOR [Value10]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__36EF488F] DEFAULT ((0)) FOR [Value11]; GO +ALTER TABLE [fp].[ServiceLineEncounterAddProviderAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__37E36CC8] DEFAULT ((0)) FOR [Value12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ServiceLineEncounterAdjustment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ServiceLineEncounterAdjustment] ( + [AdjustmentGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [Value] decimal NOT NULL, + [AdjustmentFilterJSON] nvarchar(max) NOT NULL, + [GroupingHierarchyJSON] nvarchar(max) NOT NULL, + [AdjustedProperty] nvarchar(100) NULL, + [Comment] nvarchar(max) NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [ClassificationGroupID] int NOT NULL, + [ClassificationCategoryID] int NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + [LastModifiedDateUtc] datetime NOT NULL, + [DimensionMemberJson] nvarchar(max) NOT NULL, + [AdjustmentID] int NOT NULL, + [IsErrored] bit NOT NULL, + PRIMARY KEY ([AdjustmentGUID]) +); +GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [FK__ServiceLi__Budge__5AD44424] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [df_AdjustedProperty] DEFAULT ('') FOR [AdjustedProperty]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__TimeC__1715DF2C] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Budge__180A0365] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF_ServiceLineEncounterAdjustment_ClassificationGroupID] DEFAULT ((0)) FOR [ClassificationGroupID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF_ServiceLineEncounterAdjustment_ClassificationCategoryID] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__IsErr__49112626] DEFAULT ((0)) FOR [IsErrored]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Group__502C987F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Adjus__59E01FEB] DEFAULT (newid()) FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Adjus__5BC8685D] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Value__5CBC8C96] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Adjus__5DB0B0CF] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Group__5EA4D508] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Comme__608D1D7A] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Dimen__61057DEC] DEFAULT ('') FOR [DimensionMemberJson]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Autho__618141B3] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__Autho__627565EC] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__DateC__6BED20B3] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__LastM__6CE144EC] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment] ADD CONSTRAINT [DF__ServiceLi__IsRec__6EB3B36E] DEFAULT ((0)) FOR [IsRecordDeleted]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ServiceLineEncounterAdjustmentImport ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ServiceLineEncounterAdjustmentImport] ( + [RowID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [DepartmentID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [MSDRGID] int NOT NULL, + [CPTID] int NOT NULL, + [ProviderID] int NOT NULL, + [PhysicianSpecialtyID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [Value] decimal NOT NULL, + [Version] timestamp NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [AdjustmentID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_AdjustmentID] ON [fp].[ServiceLineEncounterAdjustmentImport] ([AdjustmentID]); +CREATE NONCLUSTERED INDEX [CORE_AdjustmentGUID_EntityID_ServiceLineID] ON [fp].[ServiceLineEncounterAdjustmentImport] ([AdjustmentGUID], [EntityID], [ServiceLineID]); +GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Adjus__259A9F5B] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Adjus__3D866C2E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Entit__3E7A9067] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Patie__3F6EB4A0] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Servi__4062D8D9] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Servi__4156FD12] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__AgeCo__424B214B] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Medic__433F4584] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Depar__443369BD] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Payor__45278DF6] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Payor__461BB22F] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__MSDRG__470FD668] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__CPTID__4803FAA1] DEFAULT ((0)) FOR [CPTID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Provi__48F81EDA] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Physi__49EC4313] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF_SLEAdjImp_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF_SLEAdjImp_UnitTypeID] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF_SLEAdjImp_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF_SLEAdjImp_VALUE] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__TimeC__4EB0F830] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__Budge__4FA51C69] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustmentImport] ADD CONSTRAINT [DF__ServiceLi__IsRec__7560B0FD] DEFAULT ((0)) FOR [IsRecordDeleted]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ServiceLineEncounterAdjustment_backup ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ServiceLineEncounterAdjustment_backup] ( + [AdjustmentGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [Value] decimal NOT NULL, + [AdjustmentFilterJSON] nvarchar(max) NOT NULL, + [GroupingHierarchyJSON] nvarchar(max) NOT NULL, + [AdjustedProperty] nvarchar(100) NULL, + [Comment] nvarchar(max) NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [LastModifiedDate] datetime NOT NULL, + [DateCreatedUTC] datetime NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + PRIMARY KEY ([AdjustmentGUID]) +); +GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [FK__ServiceLi__Budge__5FC3E1CA] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [df_SlBackup_AdjustedProperty] DEFAULT ('') FOR [AdjustedProperty]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__TimeC__18FE279E] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__Budge__19F24BD7] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__Adjus__54522F1E] DEFAULT (newid()) FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__Adjus__55465357] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__Value__563A7790] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__Adjus__572E9BC9] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__Group__5822C002] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__Comme__5A0B0874] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__Autho__5AFF2CAD] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__Autho__5BF350E6] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__LastM__5CE7751F] DEFAULT (getdate()) FOR [LastModifiedDate]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__DateC__5DDB9958] DEFAULT (getdate()) FOR [DateCreatedUTC]; GO +ALTER TABLE [fp].[ServiceLineEncounterAdjustment_backup] ADD CONSTRAINT [DF__ServiceLi__Group__5ECFBD91] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ServiceLineEncounterChangeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ServiceLineEncounterChangeHistory] ( + [RowID] bigint NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [OldValue] decimal NOT NULL, + [NewValue] decimal NOT NULL, + [BudgetConfigID] int NOT NULL, + [DateCreatedUTC] datetime2 NOT NULL, + [ServiceLineEncounterID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_ServiceLineEncounterChangeHistory] ON [fp].[ServiceLineEncounterChangeHistory] ([ServiceLineEncounterID]); +CREATE NONCLUSTERED INDEX [IX_ServiceLineEncounterChangeHistory_AdjustmentGuid] ON [fp].[ServiceLineEncounterChangeHistory] ([AdjustmentGUID]) INCLUDE ([ServiceLineEncounterID], [FiscalMonthID], [UnitTypeID], [TimeClassID], [BudgetPhaseID]); +CREATE NONCLUSTERED INDEX [CORE_ServiceLineEncounterChangeHistory_ImpactReportLoads] ON [fp].[ServiceLineEncounterChangeHistory] ([AdjustmentGUID], [FiscalMonthID], [TimeClassID]) INCLUDE ([ServiceLineEncounterID], [AdjustmentType], [UnitTypeID], [BudgetPhaseID], [OldValue], [NewValue], [BudgetConfigID]); +GO +ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__Group__003279D4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__Adjus__01269E0D] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__DateC__01F1706B] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO +ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__Fisca__030EE67F] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__UnitT__04030AB8] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__TimeC__04F72EF1] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__Budge__05EB532A] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__06DF7763] DEFAULT ((0)) FOR [OldValue]; GO +ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__07D39B9C] DEFAULT ((0)) FOR [NewValue]; GO +ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__Budge__5D2A0010] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewSe__7B928452] DEFAULT ((0)) FOR [ServiceLineEncounterID]; GO +ALTER TABLE [fp].[ServiceLineEncounterChangeHistory] ADD CONSTRAINT [DF__ServiceLi__Adjus__7F3E559B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ServiceLineEncounterChargeVolumeMapping ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ServiceLineEncounterChargeVolumeMapping] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ProviderID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [CLU_SleCV_ndx] ON [fp].[ServiceLineEncounterChargeVolumeMapping] ([BudgetConfigID], [EntityID], [DepartmentID], [ServiceLineID], [ProviderID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_ClusteredUnique] ON [fp].[ServiceLineEncounterChargeVolumeMapping] ([BudgetConfigID], [EntityID], [DepartmentID], [ServiceLineID], [ProviderID]); +GO +ALTER TABLE [fp].[ServiceLineEncounterChargeVolumeMapping] ADD CONSTRAINT [DF__ServiceLi__Budge__2683D69C] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ServiceLineEncounterChargeVolumeMapping] ADD CONSTRAINT [DF__ServiceLi__Entit__2777FAD5] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ServiceLineEncounterChargeVolumeMapping] ADD CONSTRAINT [DF__ServiceLi__Depar__286C1F0E] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ServiceLineEncounterChargeVolumeMapping] ADD CONSTRAINT [DF__ServiceLi__Servi__29604347] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[ServiceLineEncounterChargeVolumeMapping] ADD CONSTRAINT [DF_ServiceLineEncounterChargeVolumeMapping_Provider] DEFAULT ((0)) FOR [ProviderID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ServiceLineEncounterHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ServiceLineEncounterHistory] ( + [RowID] int NOT NULL, + [ServiceLineEncounterID] int NOT NULL, + [ActualYTDValue01] decimal NOT NULL, + [ActualYTDValue02] decimal NOT NULL, + [ActualYTDValue03] decimal NOT NULL, + [ActualYTDValue04] decimal NOT NULL, + [ActualYTDValue05] decimal NOT NULL, + [ActualYTDValue06] decimal NOT NULL, + [ActualYTDValue07] decimal NOT NULL, + [ActualYTDValue08] decimal NOT NULL, + [ActualYTDValue09] decimal NOT NULL, + [ActualYTDValue10] decimal NOT NULL, + [ActualYTDValue11] decimal NOT NULL, + [ActualYTDValue12] decimal NOT NULL, + [PriorYearActualValue01] decimal NOT NULL, + [PriorYearActualValue02] decimal NOT NULL, + [PriorYearActualValue03] decimal NOT NULL, + [PriorYearActualValue04] decimal NOT NULL, + [PriorYearActualValue05] decimal NOT NULL, + [PriorYearActualValue06] decimal NOT NULL, + [PriorYearActualValue07] decimal NOT NULL, + [PriorYearActualValue08] decimal NOT NULL, + [PriorYearActualValue09] decimal NOT NULL, + [PriorYearActualValue10] decimal NOT NULL, + [PriorYearActualValue11] decimal NOT NULL, + [PriorYearActualValue12] decimal NOT NULL, + [CurrentYearBudget01] decimal NOT NULL, + [CurrentYearBudget02] decimal NOT NULL, + [CurrentYearBudget03] decimal NOT NULL, + [CurrentYearBudget04] decimal NOT NULL, + [CurrentYearBudget05] decimal NOT NULL, + [CurrentYearBudget06] decimal NOT NULL, + [CurrentYearBudget07] decimal NOT NULL, + [CurrentYearBudget08] decimal NOT NULL, + [CurrentYearBudget09] decimal NOT NULL, + [CurrentYearBudget10] decimal NOT NULL, + [CurrentYearBudget11] decimal NOT NULL, + [CurrentYearBudget12] decimal NOT NULL, + [PriorYearActualValueTotal] decimal NOT NULL, + [ActualYTDValueTotal] decimal NOT NULL, + [CurrentYearBudgetTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_ServiceLineEncounterHistory] ON [fp].[ServiceLineEncounterHistory] ([ServiceLineEncounterID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[ServiceLineEncounterHistory] ([ServiceLineEncounterID]); +GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [FK_ServiceLineEncounterHistory_ServiceLineEncounterID] FOREIGN KEY ([ServiceLineEncounterID]) REFERENCES [fp].[ServiceLineEncounter] ([ServiceLineEncounterID]); GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Servi__436339C8] DEFAULT ((0)) FOR [ServiceLineEncounterID]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__44575E01] DEFAULT ((0)) FOR [ActualYTDValue01]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__454B823A] DEFAULT ((0)) FOR [ActualYTDValue02]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__463FA673] DEFAULT ((0)) FOR [ActualYTDValue03]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__4733CAAC] DEFAULT ((0)) FOR [ActualYTDValue04]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__4827EEE5] DEFAULT ((0)) FOR [ActualYTDValue05]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__491C131E] DEFAULT ((0)) FOR [ActualYTDValue06]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__4A103757] DEFAULT ((0)) FOR [ActualYTDValue07]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__4B045B90] DEFAULT ((0)) FOR [ActualYTDValue08]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__4BF87FC9] DEFAULT ((0)) FOR [ActualYTDValue09]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__4CECA402] DEFAULT ((0)) FOR [ActualYTDValue10]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__4DE0C83B] DEFAULT ((0)) FOR [ActualYTDValue11]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Actua__4ED4EC74] DEFAULT ((0)) FOR [ActualYTDValue12]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__4FC910AD] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__50BD34E6] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__51B1591F] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__52A57D58] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__5399A191] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__548DC5CA] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__5581EA03] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__56760E3C] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__576A3275] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__585E56AE] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__59527AE7] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Prior__5A469F20] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__5B3AC359] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__5C2EE792] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__5D230BCB] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__5E173004] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__5F0B543D] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__5FFF7876] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__60F39CAF] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__61E7C0E8] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__62DBE521] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__63D0095A] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__64C42D93] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO +ALTER TABLE [fp].[ServiceLineEncounterHistory] ADD CONSTRAINT [DF__ServiceLi__Curre__65B851CC] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ServiceLineEncounterPayorGroupMix ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ServiceLineEncounterPayorGroupMix] ( + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [TimeClassID] int NOT NULL, + [MixPercentage] decimal NOT NULL, + [InitialMixPercentage] decimal NOT NULL, + [ServiceLineID] int NOT NULL +); + +CREATE UNIQUE NONCLUSTERED INDEX [CORE_MixUnique] ON [fp].[ServiceLineEncounterPayorGroupMix] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [PayorGroupID], [TimeClassID]); +GO +ALTER TABLE [fp].[ServiceLineEncounterPayorGroupMix] ADD CONSTRAINT [DF__ServiceLi__Servi__1B603566] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[ServiceLineEncounterPayorGroupMix] ADD CONSTRAINT [DF__ServiceLi__Budge__5D21751D] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ServiceLineEncounterPayorGroupMix] ADD CONSTRAINT [DF__ServiceLi__Entit__5E159956] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[ServiceLineEncounterPayorGroupMix] ADD CONSTRAINT [DF__ServiceLi__Entit__5F09BD8F] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ServiceLineEncounterPayorGroupMix] ADD CONSTRAINT [DF__ServiceLi__Patie__5FFDE1C8] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ServiceLineEncounterPayorGroupMix] ADD CONSTRAINT [DF__ServiceLi__Payor__60F20601] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[ServiceLineEncounterPayorGroupMix] ADD CONSTRAINT [DF__ServiceLi__TimeC__61E62A3A] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[ServiceLineEncounterPayorGroupMix] ADD CONSTRAINT [DF__ServiceLi__MixPe__62DA4E73] DEFAULT ((0)) FOR [MixPercentage]; GO +ALTER TABLE [fp].[ServiceLineEncounterPayorGroupMix] ADD CONSTRAINT [DF__ServiceLi__Initi__63CE72AC] DEFAULT ((0)) FOR [InitialMixPercentage]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ServiceLineEncounterSpreads ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ServiceLineEncounterSpreads] ( + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [PatientClassID] int NOT NULL, + [IsInactive] bit NOT NULL, + [SpreadPercentage01] decimal NULL, + [SpreadPercentage02] decimal NULL, + [SpreadPercentage03] decimal NULL, + [SpreadPercentage04] decimal NULL, + [SpreadPercentage05] decimal NULL, + [SpreadPercentage06] decimal NULL, + [SpreadPercentage07] decimal NULL, + [SpreadPercentage08] decimal NULL, + [SpreadPercentage09] decimal NULL, + [SpreadPercentage10] decimal NULL, + [SpreadPercentage11] decimal NULL, + [SpreadPercentage12] decimal NULL, + [TotalImportedValue] decimal NULL, + [SpreadHistoryGUID] uniqueidentifier NOT NULL, + [GlobalSpreadID] int NOT NULL, + PRIMARY KEY ([BudgetConfigID], [EntityID], [ServiceLineID], [PatientClassID]) +); +GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [FK_FpServiceLineEncounterSpreads_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [FK_FpServiceLineEncounterSpreads_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [FK_FpServiceLineEncounterSpreads_ServiceLine] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [FK_ServiceLineEncounterSpreads_History] FOREIGN KEY ([SpreadHistoryGUID]) REFERENCES [fp].[SpreadHistory] ([SpreadHistoryGUID]); GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Budge__65D5EB58] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Entit__66CA0F91] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Servi__67BE33CA] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Patie__68B25803] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__IsIna__69A67C3C] DEFAULT ((0)) FOR [IsInactive]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__6A9AA075] DEFAULT ((0)) FOR [SpreadPercentage01]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__6B8EC4AE] DEFAULT ((0)) FOR [SpreadPercentage02]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__6C82E8E7] DEFAULT ((0)) FOR [SpreadPercentage03]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__6D770D20] DEFAULT ((0)) FOR [SpreadPercentage04]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__6E6B3159] DEFAULT ((0)) FOR [SpreadPercentage06]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__6F5F5592] DEFAULT ((0)) FOR [SpreadPercentage07]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__705379CB] DEFAULT ((0)) FOR [SpreadPercentage08]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__71479E04] DEFAULT ((0)) FOR [SpreadPercentage09]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__723BC23D] DEFAULT ((0)) FOR [SpreadPercentage10]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__732FE676] DEFAULT ((0)) FOR [SpreadPercentage05]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__74240AAF] DEFAULT ((0)) FOR [SpreadPercentage11]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Sprea__75182EE8] DEFAULT ((0)) FOR [SpreadPercentage12]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Total__760C5321] DEFAULT ((0)) FOR [TotalImportedValue]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [df_ServiceLineEncounterSpreads_SpreadHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SpreadHistoryGUID]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreads] ADD CONSTRAINT [DF__ServiceLi__Globa__77F49B93] DEFAULT ((1)) FOR [GlobalSpreadID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ServiceLineEncounterSpreadsChangeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ( + [RowID] bigint NOT NULL, + [ServiceLineEncounterID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + [OldValue01] decimal NOT NULL, + [OldValue02] decimal NOT NULL, + [OldValue03] decimal NOT NULL, + [OldValue04] decimal NOT NULL, + [OldValue05] decimal NOT NULL, + [OldValue06] decimal NOT NULL, + [OldValue07] decimal NOT NULL, + [OldValue08] decimal NOT NULL, + [OldValue09] decimal NOT NULL, + [OldValue10] decimal NOT NULL, + [OldValue11] decimal NOT NULL, + [OldValue12] decimal NOT NULL, + [NewValue01] decimal NOT NULL, + [NewValue02] decimal NOT NULL, + [NewValue03] decimal NOT NULL, + [NewValue04] decimal NOT NULL, + [NewValue05] decimal NOT NULL, + [NewValue06] decimal NOT NULL, + [NewValue07] decimal NOT NULL, + [NewValue08] decimal NOT NULL, + [NewValue09] decimal NOT NULL, + [NewValue10] decimal NOT NULL, + [NewValue11] decimal NOT NULL, + [NewValue12] decimal NOT NULL +); + +CREATE CLUSTERED INDEX [CORE_BudgetConfigID] ON [fp].[ServiceLineEncounterSpreadsChangeHistory] ([BudgetConfigID], [ServiceLineEncounterID], [RowID]); +GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__00D7F30A] DEFAULT ((0)) FOR [NewValue10]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__01CC1743] DEFAULT ((0)) FOR [NewValue11]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__02C03B7C] DEFAULT ((0)) FOR [NewValue12]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__Servi__69F48DB2] DEFAULT ((0)) FOR [ServiceLineEncounterID]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__Budge__6AE8B1EB] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__DateC__6BDCD624] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__6CD0FA5D] DEFAULT ((0)) FOR [OldValue01]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__6DC51E96] DEFAULT ((0)) FOR [OldValue02]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__6EB942CF] DEFAULT ((0)) FOR [OldValue03]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__6FAD6708] DEFAULT ((0)) FOR [OldValue04]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__70A18B41] DEFAULT ((0)) FOR [OldValue05]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__7195AF7A] DEFAULT ((0)) FOR [OldValue06]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__7289D3B3] DEFAULT ((0)) FOR [OldValue07]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__737DF7EC] DEFAULT ((0)) FOR [OldValue08]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__74721C25] DEFAULT ((0)) FOR [OldValue09]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__7566405E] DEFAULT ((0)) FOR [OldValue10]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__765A6497] DEFAULT ((0)) FOR [OldValue11]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__OldVa__774E88D0] DEFAULT ((0)) FOR [OldValue12]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__7842AD09] DEFAULT ((0)) FOR [NewValue01]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__7936D142] DEFAULT ((0)) FOR [NewValue02]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__7A2AF57B] DEFAULT ((0)) FOR [NewValue03]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__7B1F19B4] DEFAULT ((0)) FOR [NewValue04]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__7C133DED] DEFAULT ((0)) FOR [NewValue05]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__7D076226] DEFAULT ((0)) FOR [NewValue06]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__7DFB865F] DEFAULT ((0)) FOR [NewValue07]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__7EEFAA98] DEFAULT ((0)) FOR [NewValue08]; GO +ALTER TABLE [fp].[ServiceLineEncounterSpreadsChangeHistory] ADD CONSTRAINT [DF__ServiceLi__NewVa__7FE3CED1] DEFAULT ((0)) FOR [NewValue09]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ServiceLineEncounterToChargePayorMix ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ServiceLineEncounterToChargePayorMix] ( + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [MSDRGID] int NOT NULL, + [CPTID] int NOT NULL, + [ProviderID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [InitialMixPercentage] decimal NOT NULL, + [ProjectionMixPercentage] decimal NOT NULL, + [BudgetMixPercentage] decimal NOT NULL, + [ActualYTDMixPercentage] decimal NOT NULL, + [PriorYearActualMixPercentage] decimal NOT NULL, + [CurrentYearBudgetMixPercentage] decimal NOT NULL, + [InitialProjectionMixPercentage] decimal NOT NULL +); + +CREATE UNIQUE NONCLUSTERED INDEX [CORE_MixUnique] ON [fp].[ServiceLineEncounterToChargePayorMix] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [AgeCohortID], [MedicalSurgicalID], [MSDRGID], [CPTID], [ProviderID], [PayorGroupID], [PayorID]); +GO +ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Initi__1D52D143] DEFAULT ((0)) FOR [InitialProjectionMixPercentage]; GO +ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Budge__4BA2AEB7] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Entit__4C96D2F0] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Entit__4D8AF729] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Patie__4E7F1B62] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Servi__4F733F9B] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__AgeCo__506763D4] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Medic__515B880D] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__MSDRG__524FAC46] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__CPTID__5343D07F] DEFAULT ((0)) FOR [CPTID]; GO +ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Provi__5437F4B8] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Payor__552C18F1] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Payor__56203D2A] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Initi__57146163] DEFAULT ((0)) FOR [InitialMixPercentage]; GO +ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Proje__5808859C] DEFAULT ((0)) FOR [ProjectionMixPercentage]; GO +ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Budge__58FCA9D5] DEFAULT ((0)) FOR [BudgetMixPercentage]; GO +ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Actua__59F0CE0E] DEFAULT ((0)) FOR [ActualYTDMixPercentage]; GO +ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Prior__5AE4F247] DEFAULT ((0)) FOR [PriorYearActualMixPercentage]; GO +ALTER TABLE [fp].[ServiceLineEncounterToChargePayorMix] ADD CONSTRAINT [DF__ServiceLi__Curre__5BD91680] DEFAULT ((0)) FOR [CurrentYearBudgetMixPercentage]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ServiceLineEncountersSpreadUnlockData ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [EntityID] int NOT NULL, + [PatientClassID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLineRollupID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [DepartmentID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [MSDRGID] int NOT NULL, + [CPTID] int NOT NULL, + [ProviderID] int NOT NULL, + [PhysicianSpecialtyID] int NOT NULL, + [Version] timestamp NOT NULL, + [Value01] decimal NOT NULL, + [Value02] decimal NOT NULL, + [Value03] decimal NOT NULL, + [Value04] decimal NOT NULL, + [Value05] decimal NOT NULL, + [Value06] decimal NOT NULL, + [Value07] decimal NOT NULL, + [Value08] decimal NOT NULL, + [Value09] decimal NOT NULL, + [Value10] decimal NOT NULL, + [Value11] decimal NOT NULL, + [Value12] decimal NOT NULL, + [IsRecordDeleted] bit NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Budge__4AECEAF2] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Adjus__4BE10F2B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Entit__4CD53364] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Patie__4DC9579D] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Servi__4EBD7BD6] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Servi__4FB1A00F] DEFAULT ((0)) FOR [ServiceLineRollupID]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__AgeCo__50A5C448] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Medic__5199E881] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Depar__528E0CBA] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Payor__538230F3] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Payor__5476552C] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__MSDRG__556A7965] DEFAULT ((0)) FOR [MSDRGID]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__CPTID__565E9D9E] DEFAULT ((0)) FOR [CPTID]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Provi__5752C1D7] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Physi__5846E610] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__593B0A49] DEFAULT ((0)) FOR [Value01]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__5A2F2E82] DEFAULT ((0)) FOR [Value02]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__5B2352BB] DEFAULT ((0)) FOR [Value03]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__5C1776F4] DEFAULT ((0)) FOR [Value04]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__5D0B9B2D] DEFAULT ((0)) FOR [Value05]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__5DFFBF66] DEFAULT ((0)) FOR [Value06]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__5EF3E39F] DEFAULT ((0)) FOR [Value07]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__5FE807D8] DEFAULT ((0)) FOR [Value08]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__60DC2C11] DEFAULT ((0)) FOR [Value09]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__61D0504A] DEFAULT ((0)) FOR [Value10]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__62C47483] DEFAULT ((0)) FOR [Value11]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__Value__63B898BC] DEFAULT ((0)) FOR [Value12]; GO +ALTER TABLE [fp].[ServiceLineEncountersSpreadUnlockData] ADD CONSTRAINT [DF__ServiceLi__IsRec__64ACBCF5] DEFAULT ((0)) FOR [IsRecordDeleted]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.SettingCategory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[SettingCategory] ( + [SettingCategoryID] int NOT NULL, + [CategoryID] int NOT NULL, + [SystemSettingID] int NOT NULL, + [BudgetConfigDefaultSettingID] int NOT NULL +); +GO +ALTER TABLE [fp].[SettingCategory] ADD CONSTRAINT [DF__SettingCa__Categ__64A366AB] DEFAULT ((0)) FOR [CategoryID]; GO +ALTER TABLE [fp].[SettingCategory] ADD CONSTRAINT [DF__SettingCa__Syste__65978AE4] DEFAULT ((0)) FOR [SystemSettingID]; GO +ALTER TABLE [fp].[SettingCategory] ADD CONSTRAINT [DF__SettingCa__Budge__668BAF1D] DEFAULT ((0)) FOR [BudgetConfigDefaultSettingID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.SpreadHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[SpreadHistory] ( + [SpreadHistoryGUID] uniqueidentifier NOT NULL, + [Date] datetime NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(max) NOT NULL, + [ExcelFile] varbinary(max) NULL, + PRIMARY KEY ([SpreadHistoryGUID]) +); +GO +ALTER TABLE [fp].[SpreadHistory] ADD CONSTRAINT [df_SpreadHistory_SpreadHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SpreadHistoryGUID]; GO +ALTER TABLE [fp].[SpreadHistory] ADD CONSTRAINT [df_SpreadHistory_AuthorGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[SpreadHistory] ADD CONSTRAINT [DF__SpreadHis__Autho__463A1712] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [fp].[SpreadHistory] ADD CONSTRAINT [DF__SpreadHist__Date__55B164CC] DEFAULT (getdate()) FOR [Date]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.Staffing ------------------ +--------------------------------------------- +CREATE TABLE [fp].[Staffing] ( + [StaffingID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [StaffingWageRateID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeGroupID] int NOT NULL, + [ProductiveClassID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL, + [EmployeeID] int NOT NULL, + [VariabilityID] int NOT NULL, + [AddDate] datetime NOT NULL, + [IsNew] bit NOT NULL, + [SubsectionID] int NOT NULL, + [FixedVariabilityPercentage] decimal NOT NULL, + [FlexingTypeID] smallint NOT NULL, + [ChangeHistoryGroupingGUID] uniqueidentifier NOT NULL, + [SampledBudgetDollarsTotal] decimal NULL, + [SampledProjectionDollarsTotal] decimal NULL, + [InitialBudgetDollarsTotal] decimal NULL, + [InitialProjectionDollarsTotal] decimal NULL, + [TargetAdjustedDollarsTotal] decimal NULL, + [BudgetAdjustedDollarsTotal] decimal NULL, + [ProjectionAdjustedDollarsTotal] decimal NULL, + [SampledBudgetHoursTotal] decimal NULL, + [SampledProjectionHoursTotal] decimal NULL, + [InitialBudgetHoursTotal] decimal NULL, + [InitialProjectionHoursTotal] decimal NULL, + [TargetAdjustedHoursTotal] decimal NULL, + [BudgetAdjustedHoursTotal] decimal NULL, + [ProjectionAdjustedHoursTotal] decimal NULL, + [SampledBudgetDollars01] decimal NOT NULL, + [SampledBudgetDollars02] decimal NOT NULL, + [SampledBudgetDollars03] decimal NOT NULL, + [SampledBudgetDollars04] decimal NOT NULL, + [SampledBudgetDollars05] decimal NOT NULL, + [SampledBudgetDollars06] decimal NOT NULL, + [SampledBudgetDollars07] decimal NOT NULL, + [SampledBudgetDollars08] decimal NOT NULL, + [SampledBudgetDollars09] decimal NOT NULL, + [SampledBudgetDollars10] decimal NOT NULL, + [SampledBudgetDollars11] decimal NOT NULL, + [SampledBudgetDollars12] decimal NOT NULL, + [SampledProjectionDollars01] decimal NOT NULL, + [SampledProjectionDollars02] decimal NOT NULL, + [SampledProjectionDollars03] decimal NOT NULL, + [SampledProjectionDollars04] decimal NOT NULL, + [SampledProjectionDollars05] decimal NOT NULL, + [SampledProjectionDollars06] decimal NOT NULL, + [SampledProjectionDollars07] decimal NOT NULL, + [SampledProjectionDollars08] decimal NOT NULL, + [SampledProjectionDollars09] decimal NOT NULL, + [SampledProjectionDollars10] decimal NOT NULL, + [SampledProjectionDollars11] decimal NOT NULL, + [SampledProjectionDollars12] decimal NOT NULL, + [InitialBudgetDollars01] decimal NOT NULL, + [InitialBudgetDollars02] decimal NOT NULL, + [InitialBudgetDollars03] decimal NOT NULL, + [InitialBudgetDollars04] decimal NOT NULL, + [InitialBudgetDollars05] decimal NOT NULL, + [InitialBudgetDollars06] decimal NOT NULL, + [InitialBudgetDollars07] decimal NOT NULL, + [InitialBudgetDollars08] decimal NOT NULL, + [InitialBudgetDollars09] decimal NOT NULL, + [InitialBudgetDollars10] decimal NOT NULL, + [InitialBudgetDollars11] decimal NOT NULL, + [InitialBudgetDollars12] decimal NOT NULL, + [InitialProjectionDollars01] decimal NOT NULL, + [InitialProjectionDollars02] decimal NOT NULL, + [InitialProjectionDollars03] decimal NOT NULL, + [InitialProjectionDollars04] decimal NOT NULL, + [InitialProjectionDollars05] decimal NOT NULL, + [InitialProjectionDollars06] decimal NOT NULL, + [InitialProjectionDollars07] decimal NOT NULL, + [InitialProjectionDollars08] decimal NOT NULL, + [InitialProjectionDollars09] decimal NOT NULL, + [InitialProjectionDollars10] decimal NOT NULL, + [InitialProjectionDollars11] decimal NOT NULL, + [InitialProjectionDollars12] decimal NOT NULL, + [TargetAdjustedDollars01] decimal NOT NULL, + [TargetAdjustedDollars02] decimal NOT NULL, + [TargetAdjustedDollars03] decimal NOT NULL, + [TargetAdjustedDollars04] decimal NOT NULL, + [TargetAdjustedDollars05] decimal NOT NULL, + [TargetAdjustedDollars06] decimal NOT NULL, + [TargetAdjustedDollars07] decimal NOT NULL, + [TargetAdjustedDollars08] decimal NOT NULL, + [TargetAdjustedDollars09] decimal NOT NULL, + [TargetAdjustedDollars10] decimal NOT NULL, + [TargetAdjustedDollars11] decimal NOT NULL, + [TargetAdjustedDollars12] decimal NOT NULL, + [BudgetAdjustedDollars01] decimal NOT NULL, + [BudgetAdjustedDollars02] decimal NOT NULL, + [BudgetAdjustedDollars03] decimal NOT NULL, + [BudgetAdjustedDollars04] decimal NOT NULL, + [BudgetAdjustedDollars05] decimal NOT NULL, + [BudgetAdjustedDollars06] decimal NOT NULL, + [BudgetAdjustedDollars07] decimal NOT NULL, + [BudgetAdjustedDollars08] decimal NOT NULL, + [BudgetAdjustedDollars09] decimal NOT NULL, + [BudgetAdjustedDollars10] decimal NOT NULL, + [BudgetAdjustedDollars11] decimal NOT NULL, + [BudgetAdjustedDollars12] decimal NOT NULL, + [ProjectionAdjustedDollars01] decimal NOT NULL, + [ProjectionAdjustedDollars02] decimal NOT NULL, + [ProjectionAdjustedDollars03] decimal NOT NULL, + [ProjectionAdjustedDollars04] decimal NOT NULL, + [ProjectionAdjustedDollars05] decimal NOT NULL, + [ProjectionAdjustedDollars06] decimal NOT NULL, + [ProjectionAdjustedDollars07] decimal NOT NULL, + [ProjectionAdjustedDollars08] decimal NOT NULL, + [ProjectionAdjustedDollars09] decimal NOT NULL, + [ProjectionAdjustedDollars10] decimal NOT NULL, + [ProjectionAdjustedDollars11] decimal NOT NULL, + [ProjectionAdjustedDollars12] decimal NOT NULL, + [TargetDollarsPercentAdjustmentFactor01] decimal NOT NULL, + [TargetDollarsPercentAdjustmentFactor02] decimal NOT NULL, + [TargetDollarsPercentAdjustmentFactor03] decimal NOT NULL, + [TargetDollarsPercentAdjustmentFactor04] decimal NOT NULL, + [TargetDollarsPercentAdjustmentFactor05] decimal NOT NULL, + [TargetDollarsPercentAdjustmentFactor06] decimal NOT NULL, + [TargetDollarsPercentAdjustmentFactor07] decimal NOT NULL, + [TargetDollarsPercentAdjustmentFactor08] decimal NOT NULL, + [TargetDollarsPercentAdjustmentFactor09] decimal NOT NULL, + [TargetDollarsPercentAdjustmentFactor10] decimal NOT NULL, + [TargetDollarsPercentAdjustmentFactor11] decimal NOT NULL, + [TargetDollarsPercentAdjustmentFactor12] decimal NOT NULL, + [BudgetDollarsPercentAdjustmentFactor01] decimal NOT NULL, + [BudgetDollarsPercentAdjustmentFactor02] decimal NOT NULL, + [BudgetDollarsPercentAdjustmentFactor03] decimal NOT NULL, + [BudgetDollarsPercentAdjustmentFactor04] decimal NOT NULL, + [BudgetDollarsPercentAdjustmentFactor05] decimal NOT NULL, + [BudgetDollarsPercentAdjustmentFactor06] decimal NOT NULL, + [BudgetDollarsPercentAdjustmentFactor07] decimal NOT NULL, + [BudgetDollarsPercentAdjustmentFactor08] decimal NOT NULL, + [BudgetDollarsPercentAdjustmentFactor09] decimal NOT NULL, + [BudgetDollarsPercentAdjustmentFactor10] decimal NOT NULL, + [BudgetDollarsPercentAdjustmentFactor11] decimal NOT NULL, + [BudgetDollarsPercentAdjustmentFactor12] decimal NOT NULL, + [ProjectionDollarsPercentAdjustmentFactor01] decimal NOT NULL, + [ProjectionDollarsPercentAdjustmentFactor02] decimal NOT NULL, + [ProjectionDollarsPercentAdjustmentFactor03] decimal NOT NULL, + [ProjectionDollarsPercentAdjustmentFactor04] decimal NOT NULL, + [ProjectionDollarsPercentAdjustmentFactor05] decimal NOT NULL, + [ProjectionDollarsPercentAdjustmentFactor06] decimal NOT NULL, + [ProjectionDollarsPercentAdjustmentFactor07] decimal NOT NULL, + [ProjectionDollarsPercentAdjustmentFactor08] decimal NOT NULL, + [ProjectionDollarsPercentAdjustmentFactor09] decimal NOT NULL, + [ProjectionDollarsPercentAdjustmentFactor10] decimal NOT NULL, + [ProjectionDollarsPercentAdjustmentFactor11] decimal NOT NULL, + [ProjectionDollarsPercentAdjustmentFactor12] decimal NOT NULL, + [SampledBudgetHours01] decimal NOT NULL, + [SampledBudgetHours02] decimal NOT NULL, + [SampledBudgetHours03] decimal NOT NULL, + [SampledBudgetHours04] decimal NOT NULL, + [SampledBudgetHours05] decimal NOT NULL, + [SampledBudgetHours06] decimal NOT NULL, + [SampledBudgetHours07] decimal NOT NULL, + [SampledBudgetHours08] decimal NOT NULL, + [SampledBudgetHours09] decimal NOT NULL, + [SampledBudgetHours10] decimal NOT NULL, + [SampledBudgetHours11] decimal NOT NULL, + [SampledBudgetHours12] decimal NOT NULL, + [SampledProjectionHours01] decimal NOT NULL, + [SampledProjectionHours02] decimal NOT NULL, + [SampledProjectionHours03] decimal NOT NULL, + [SampledProjectionHours04] decimal NOT NULL, + [SampledProjectionHours05] decimal NOT NULL, + [SampledProjectionHours06] decimal NOT NULL, + [SampledProjectionHours07] decimal NOT NULL, + [SampledProjectionHours08] decimal NOT NULL, + [SampledProjectionHours09] decimal NOT NULL, + [SampledProjectionHours10] decimal NOT NULL, + [SampledProjectionHours11] decimal NOT NULL, + [SampledProjectionHours12] decimal NOT NULL, + [InitialBudgetHours01] decimal NOT NULL, + [InitialBudgetHours02] decimal NOT NULL, + [InitialBudgetHours03] decimal NOT NULL, + [InitialBudgetHours04] decimal NOT NULL, + [InitialBudgetHours05] decimal NOT NULL, + [InitialBudgetHours06] decimal NOT NULL, + [InitialBudgetHours07] decimal NOT NULL, + [InitialBudgetHours08] decimal NOT NULL, + [InitialBudgetHours09] decimal NOT NULL, + [InitialBudgetHours10] decimal NOT NULL, + [InitialBudgetHours11] decimal NOT NULL, + [InitialBudgetHours12] decimal NOT NULL, + [InitialProjectionHours01] decimal NOT NULL, + [InitialProjectionHours02] decimal NOT NULL, + [InitialProjectionHours03] decimal NOT NULL, + [InitialProjectionHours04] decimal NOT NULL, + [InitialProjectionHours05] decimal NOT NULL, + [InitialProjectionHours06] decimal NOT NULL, + [InitialProjectionHours07] decimal NOT NULL, + [InitialProjectionHours08] decimal NOT NULL, + [InitialProjectionHours09] decimal NOT NULL, + [InitialProjectionHours10] decimal NOT NULL, + [InitialProjectionHours11] decimal NOT NULL, + [InitialProjectionHours12] decimal NOT NULL, + [TargetAdjustedHours01] decimal NOT NULL, + [TargetAdjustedHours02] decimal NOT NULL, + [TargetAdjustedHours03] decimal NOT NULL, + [TargetAdjustedHours04] decimal NOT NULL, + [TargetAdjustedHours05] decimal NOT NULL, + [TargetAdjustedHours06] decimal NOT NULL, + [TargetAdjustedHours07] decimal NOT NULL, + [TargetAdjustedHours08] decimal NOT NULL, + [TargetAdjustedHours09] decimal NOT NULL, + [TargetAdjustedHours10] decimal NOT NULL, + [TargetAdjustedHours11] decimal NOT NULL, + [TargetAdjustedHours12] decimal NOT NULL, + [BudgetAdjustedHours01] decimal NOT NULL, + [BudgetAdjustedHours02] decimal NOT NULL, + [BudgetAdjustedHours03] decimal NOT NULL, + [BudgetAdjustedHours04] decimal NOT NULL, + [BudgetAdjustedHours05] decimal NOT NULL, + [BudgetAdjustedHours06] decimal NOT NULL, + [BudgetAdjustedHours07] decimal NOT NULL, + [BudgetAdjustedHours08] decimal NOT NULL, + [BudgetAdjustedHours09] decimal NOT NULL, + [BudgetAdjustedHours10] decimal NOT NULL, + [BudgetAdjustedHours11] decimal NOT NULL, + [BudgetAdjustedHours12] decimal NOT NULL, + [ProjectionAdjustedHours01] decimal NOT NULL, + [ProjectionAdjustedHours02] decimal NOT NULL, + [ProjectionAdjustedHours03] decimal NOT NULL, + [ProjectionAdjustedHours04] decimal NOT NULL, + [ProjectionAdjustedHours05] decimal NOT NULL, + [ProjectionAdjustedHours06] decimal NOT NULL, + [ProjectionAdjustedHours07] decimal NOT NULL, + [ProjectionAdjustedHours08] decimal NOT NULL, + [ProjectionAdjustedHours09] decimal NOT NULL, + [ProjectionAdjustedHours10] decimal NOT NULL, + [ProjectionAdjustedHours11] decimal NOT NULL, + [ProjectionAdjustedHours12] decimal NOT NULL, + [TargetHoursPercentAdjustmentFactor01] decimal NOT NULL, + [TargetHoursPercentAdjustmentFactor02] decimal NOT NULL, + [TargetHoursPercentAdjustmentFactor03] decimal NOT NULL, + [TargetHoursPercentAdjustmentFactor04] decimal NOT NULL, + [TargetHoursPercentAdjustmentFactor05] decimal NOT NULL, + [TargetHoursPercentAdjustmentFactor06] decimal NOT NULL, + [TargetHoursPercentAdjustmentFactor07] decimal NOT NULL, + [TargetHoursPercentAdjustmentFactor08] decimal NOT NULL, + [TargetHoursPercentAdjustmentFactor09] decimal NOT NULL, + [TargetHoursPercentAdjustmentFactor10] decimal NOT NULL, + [TargetHoursPercentAdjustmentFactor11] decimal NOT NULL, + [TargetHoursPercentAdjustmentFactor12] decimal NOT NULL, + [BudgetHoursPercentAdjustmentFactor01] decimal NOT NULL, + [BudgetHoursPercentAdjustmentFactor02] decimal NOT NULL, + [BudgetHoursPercentAdjustmentFactor03] decimal NOT NULL, + [BudgetHoursPercentAdjustmentFactor04] decimal NOT NULL, + [BudgetHoursPercentAdjustmentFactor05] decimal NOT NULL, + [BudgetHoursPercentAdjustmentFactor06] decimal NOT NULL, + [BudgetHoursPercentAdjustmentFactor07] decimal NOT NULL, + [BudgetHoursPercentAdjustmentFactor08] decimal NOT NULL, + [BudgetHoursPercentAdjustmentFactor09] decimal NOT NULL, + [BudgetHoursPercentAdjustmentFactor10] decimal NOT NULL, + [BudgetHoursPercentAdjustmentFactor11] decimal NOT NULL, + [BudgetHoursPercentAdjustmentFactor12] decimal NOT NULL, + [ProjectionHoursPercentAdjustmentFactor01] decimal NOT NULL, + [ProjectionHoursPercentAdjustmentFactor02] decimal NOT NULL, + [ProjectionHoursPercentAdjustmentFactor03] decimal NOT NULL, + [ProjectionHoursPercentAdjustmentFactor04] decimal NOT NULL, + [ProjectionHoursPercentAdjustmentFactor05] decimal NOT NULL, + [ProjectionHoursPercentAdjustmentFactor06] decimal NOT NULL, + [ProjectionHoursPercentAdjustmentFactor07] decimal NOT NULL, + [ProjectionHoursPercentAdjustmentFactor08] decimal NOT NULL, + [ProjectionHoursPercentAdjustmentFactor09] decimal NOT NULL, + [ProjectionHoursPercentAdjustmentFactor10] decimal NOT NULL, + [ProjectionHoursPercentAdjustmentFactor11] decimal NOT NULL, + [ProjectionHoursPercentAdjustmentFactor12] decimal NOT NULL, + [SampledBudgetFTEs01] decimal NOT NULL, + [SampledBudgetFTEs02] decimal NOT NULL, + [SampledBudgetFTEs03] decimal NOT NULL, + [SampledBudgetFTEs04] decimal NOT NULL, + [SampledBudgetFTEs05] decimal NOT NULL, + [SampledBudgetFTEs06] decimal NOT NULL, + [SampledBudgetFTEs07] decimal NOT NULL, + [SampledBudgetFTEs08] decimal NOT NULL, + [SampledBudgetFTEs09] decimal NOT NULL, + [SampledBudgetFTEs10] decimal NOT NULL, + [SampledBudgetFTEs11] decimal NOT NULL, + [SampledBudgetFTEs12] decimal NOT NULL, + [SampledProjectionFTEs01] decimal NOT NULL, + [SampledProjectionFTEs02] decimal NOT NULL, + [SampledProjectionFTEs03] decimal NOT NULL, + [SampledProjectionFTEs04] decimal NOT NULL, + [SampledProjectionFTEs05] decimal NOT NULL, + [SampledProjectionFTEs06] decimal NOT NULL, + [SampledProjectionFTEs07] decimal NOT NULL, + [SampledProjectionFTEs08] decimal NOT NULL, + [SampledProjectionFTEs09] decimal NOT NULL, + [SampledProjectionFTEs10] decimal NOT NULL, + [SampledProjectionFTEs11] decimal NOT NULL, + [SampledProjectionFTEs12] decimal NOT NULL, + [InitialBudgetFTEs01] decimal NOT NULL, + [InitialBudgetFTEs02] decimal NOT NULL, + [InitialBudgetFTEs03] decimal NOT NULL, + [InitialBudgetFTEs04] decimal NOT NULL, + [InitialBudgetFTEs05] decimal NOT NULL, + [InitialBudgetFTEs06] decimal NOT NULL, + [InitialBudgetFTEs07] decimal NOT NULL, + [InitialBudgetFTEs08] decimal NOT NULL, + [InitialBudgetFTEs09] decimal NOT NULL, + [InitialBudgetFTEs10] decimal NOT NULL, + [InitialBudgetFTEs11] decimal NOT NULL, + [InitialBudgetFTEs12] decimal NOT NULL, + [InitialProjectionFTEs01] decimal NOT NULL, + [InitialProjectionFTEs02] decimal NOT NULL, + [InitialProjectionFTEs03] decimal NOT NULL, + [InitialProjectionFTEs04] decimal NOT NULL, + [InitialProjectionFTEs05] decimal NOT NULL, + [InitialProjectionFTEs06] decimal NOT NULL, + [InitialProjectionFTEs07] decimal NOT NULL, + [InitialProjectionFTEs08] decimal NOT NULL, + [InitialProjectionFTEs09] decimal NOT NULL, + [InitialProjectionFTEs10] decimal NOT NULL, + [InitialProjectionFTEs11] decimal NOT NULL, + [InitialProjectionFTEs12] decimal NOT NULL, + [TargetAdjustedFTEs01] decimal NOT NULL, + [TargetAdjustedFTEs02] decimal NOT NULL, + [TargetAdjustedFTEs03] decimal NOT NULL, + [TargetAdjustedFTEs04] decimal NOT NULL, + [TargetAdjustedFTEs05] decimal NOT NULL, + [TargetAdjustedFTEs06] decimal NOT NULL, + [TargetAdjustedFTEs07] decimal NOT NULL, + [TargetAdjustedFTEs08] decimal NOT NULL, + [TargetAdjustedFTEs09] decimal NOT NULL, + [TargetAdjustedFTEs10] decimal NOT NULL, + [TargetAdjustedFTEs11] decimal NOT NULL, + [TargetAdjustedFTEs12] decimal NOT NULL, + [BudgetAdjustedFTEs01] decimal NOT NULL, + [BudgetAdjustedFTEs02] decimal NOT NULL, + [BudgetAdjustedFTEs03] decimal NOT NULL, + [BudgetAdjustedFTEs04] decimal NOT NULL, + [BudgetAdjustedFTEs05] decimal NOT NULL, + [BudgetAdjustedFTEs06] decimal NOT NULL, + [BudgetAdjustedFTEs07] decimal NOT NULL, + [BudgetAdjustedFTEs08] decimal NOT NULL, + [BudgetAdjustedFTEs09] decimal NOT NULL, + [BudgetAdjustedFTEs10] decimal NOT NULL, + [BudgetAdjustedFTEs11] decimal NOT NULL, + [BudgetAdjustedFTEs12] decimal NOT NULL, + [ProjectionAdjustedFTEs01] decimal NOT NULL, + [ProjectionAdjustedFTEs02] decimal NOT NULL, + [ProjectionAdjustedFTEs03] decimal NOT NULL, + [ProjectionAdjustedFTEs04] decimal NOT NULL, + [ProjectionAdjustedFTEs05] decimal NOT NULL, + [ProjectionAdjustedFTEs06] decimal NOT NULL, + [ProjectionAdjustedFTEs07] decimal NOT NULL, + [ProjectionAdjustedFTEs08] decimal NOT NULL, + [ProjectionAdjustedFTEs09] decimal NOT NULL, + [ProjectionAdjustedFTEs10] decimal NOT NULL, + [ProjectionAdjustedFTEs11] decimal NOT NULL, + [ProjectionAdjustedFTEs12] decimal NOT NULL, + [TargetFTEsPercentAdjustmentFactor01] decimal NOT NULL, + [TargetFTEsPercentAdjustmentFactor02] decimal NOT NULL, + [TargetFTEsPercentAdjustmentFactor03] decimal NOT NULL, + [TargetFTEsPercentAdjustmentFactor04] decimal NOT NULL, + [TargetFTEsPercentAdjustmentFactor05] decimal NOT NULL, + [TargetFTEsPercentAdjustmentFactor06] decimal NOT NULL, + [TargetFTEsPercentAdjustmentFactor07] decimal NOT NULL, + [TargetFTEsPercentAdjustmentFactor08] decimal NOT NULL, + [TargetFTEsPercentAdjustmentFactor09] decimal NOT NULL, + [TargetFTEsPercentAdjustmentFactor10] decimal NOT NULL, + [TargetFTEsPercentAdjustmentFactor11] decimal NOT NULL, + [TargetFTEsPercentAdjustmentFactor12] decimal NOT NULL, + [BudgetFTEsPercentAdjustmentFactor01] decimal NOT NULL, + [BudgetFTEsPercentAdjustmentFactor02] decimal NOT NULL, + [BudgetFTEsPercentAdjustmentFactor03] decimal NOT NULL, + [BudgetFTEsPercentAdjustmentFactor04] decimal NOT NULL, + [BudgetFTEsPercentAdjustmentFactor05] decimal NOT NULL, + [BudgetFTEsPercentAdjustmentFactor06] decimal NOT NULL, + [BudgetFTEsPercentAdjustmentFactor07] decimal NOT NULL, + [BudgetFTEsPercentAdjustmentFactor08] decimal NOT NULL, + [BudgetFTEsPercentAdjustmentFactor09] decimal NOT NULL, + [BudgetFTEsPercentAdjustmentFactor10] decimal NOT NULL, + [BudgetFTEsPercentAdjustmentFactor11] decimal NOT NULL, + [BudgetFTEsPercentAdjustmentFactor12] decimal NOT NULL, + [ProjectionFTEsPercentAdjustmentFactor01] decimal NOT NULL, + [ProjectionFTEsPercentAdjustmentFactor02] decimal NOT NULL, + [ProjectionFTEsPercentAdjustmentFactor03] decimal NOT NULL, + [ProjectionFTEsPercentAdjustmentFactor04] decimal NOT NULL, + [ProjectionFTEsPercentAdjustmentFactor05] decimal NOT NULL, + [ProjectionFTEsPercentAdjustmentFactor06] decimal NOT NULL, + [ProjectionFTEsPercentAdjustmentFactor07] decimal NOT NULL, + [ProjectionFTEsPercentAdjustmentFactor08] decimal NOT NULL, + [ProjectionFTEsPercentAdjustmentFactor09] decimal NOT NULL, + [ProjectionFTEsPercentAdjustmentFactor10] decimal NOT NULL, + [ProjectionFTEsPercentAdjustmentFactor11] decimal NOT NULL, + [ProjectionFTEsPercentAdjustmentFactor12] decimal NOT NULL, + [InitialBudgetRate01] decimal NOT NULL, + [InitialBudgetRate02] decimal NOT NULL, + [InitialBudgetRate03] decimal NOT NULL, + [InitialBudgetRate04] decimal NOT NULL, + [InitialBudgetRate05] decimal NOT NULL, + [InitialBudgetRate06] decimal NOT NULL, + [InitialBudgetRate07] decimal NOT NULL, + [InitialBudgetRate08] decimal NOT NULL, + [InitialBudgetRate09] decimal NOT NULL, + [InitialBudgetRate10] decimal NOT NULL, + [InitialBudgetRate11] decimal NOT NULL, + [InitialBudgetRate12] decimal NOT NULL, + [InitialProjectionRate01] decimal NOT NULL, + [InitialProjectionRate02] decimal NOT NULL, + [InitialProjectionRate03] decimal NOT NULL, + [InitialProjectionRate04] decimal NOT NULL, + [InitialProjectionRate05] decimal NOT NULL, + [InitialProjectionRate06] decimal NOT NULL, + [InitialProjectionRate07] decimal NOT NULL, + [InitialProjectionRate08] decimal NOT NULL, + [InitialProjectionRate09] decimal NOT NULL, + [InitialProjectionRate10] decimal NOT NULL, + [InitialProjectionRate11] decimal NOT NULL, + [InitialProjectionRate12] decimal NOT NULL, + [TargetAdjustedRate01] decimal NOT NULL, + [TargetAdjustedRate02] decimal NOT NULL, + [TargetAdjustedRate03] decimal NOT NULL, + [TargetAdjustedRate04] decimal NOT NULL, + [TargetAdjustedRate05] decimal NOT NULL, + [TargetAdjustedRate06] decimal NOT NULL, + [TargetAdjustedRate07] decimal NOT NULL, + [TargetAdjustedRate08] decimal NOT NULL, + [TargetAdjustedRate09] decimal NOT NULL, + [TargetAdjustedRate10] decimal NOT NULL, + [TargetAdjustedRate11] decimal NOT NULL, + [TargetAdjustedRate12] decimal NOT NULL, + [BudgetAdjustedRate01] decimal NOT NULL, + [BudgetAdjustedRate02] decimal NOT NULL, + [BudgetAdjustedRate03] decimal NOT NULL, + [BudgetAdjustedRate04] decimal NOT NULL, + [BudgetAdjustedRate05] decimal NOT NULL, + [BudgetAdjustedRate06] decimal NOT NULL, + [BudgetAdjustedRate07] decimal NOT NULL, + [BudgetAdjustedRate08] decimal NOT NULL, + [BudgetAdjustedRate09] decimal NOT NULL, + [BudgetAdjustedRate10] decimal NOT NULL, + [BudgetAdjustedRate11] decimal NOT NULL, + [BudgetAdjustedRate12] decimal NOT NULL, + [ProjectionAdjustedRate01] decimal NOT NULL, + [ProjectionAdjustedRate02] decimal NOT NULL, + [ProjectionAdjustedRate03] decimal NOT NULL, + [ProjectionAdjustedRate04] decimal NOT NULL, + [ProjectionAdjustedRate05] decimal NOT NULL, + [ProjectionAdjustedRate06] decimal NOT NULL, + [ProjectionAdjustedRate07] decimal NOT NULL, + [ProjectionAdjustedRate08] decimal NOT NULL, + [ProjectionAdjustedRate09] decimal NOT NULL, + [ProjectionAdjustedRate10] decimal NOT NULL, + [ProjectionAdjustedRate11] decimal NOT NULL, + [ProjectionAdjustedRate12] decimal NOT NULL, + [BudgetDollarsLockType] tinyint NOT NULL, + [BudgetDollarsLockFlag] tinyint NOT NULL, + [TargetDollarsLockType] tinyint NOT NULL, + [TargetDollarsLockFlag] tinyint NOT NULL, + [ProjectionDollarsLockType] tinyint NOT NULL, + [ProjectionDollarsLockFlag] tinyint NOT NULL, + [BudgetHoursLockType] tinyint NOT NULL, + [BudgetHoursLockFlag] tinyint NOT NULL, + [TargetHoursLockType] tinyint NOT NULL, + [TargetHoursLockFlag] tinyint NOT NULL, + [ProjectionHoursLockType] tinyint NOT NULL, + [ProjectionHoursLockFlag] tinyint NOT NULL, + [BudgetFTEsLockType] tinyint NOT NULL, + [BudgetFTEsLockFlag] tinyint NOT NULL, + [TargetFTEsLockType] tinyint NOT NULL, + [TargetFTEsLockFlag] tinyint NOT NULL, + [ProjectionFTEsLockType] tinyint NOT NULL, + [ProjectionFTEsLockFlag] tinyint NOT NULL, + PRIMARY KEY ([StaffingID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[Staffing] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [EmployeeID], [VariabilityID], [ProviderID], [ProviderLineItemID], [ProviderTypeID], [ProviderSpecialtyID], [SubsectionID]) INCLUDE ([IsNew]); +CREATE NONCLUSTERED INDEX [IX_Staffing_JobCode] ON [fp].[Staffing] ([JobCodeID]) INCLUDE ([StaffingID], [BudgetConfigID], [DepartmentID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [ProviderID], [ProviderLineItemID], [ProviderTypeID], [ProviderSpecialtyID], [EmployeeID]); +CREATE NONCLUSTERED INDEX [IX_Staffing_Department] ON [fp].[Staffing] ([DepartmentID]) INCLUDE ([StaffingID], [BudgetConfigID], [EntityGroupConfigID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [ProviderID], [ProviderLineItemID], [ProviderTypeID], [ProviderSpecialtyID], [EmployeeID]); +CREATE NONCLUSTERED INDEX [IX_Staffing_Entity] ON [fp].[Staffing] ([EntityID]) INCLUDE ([StaffingID], [BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [ProviderID], [ProviderLineItemID], [ProviderTypeID], [ProviderSpecialtyID], [EmployeeID]); +CREATE NONCLUSTERED INDEX [IX_Staffing_EntityGroupConfig] ON [fp].[Staffing] ([EntityGroupConfigID]) INCLUDE ([StaffingID], [BudgetConfigID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [VariabilityID], [ProviderID], [ProviderLineItemID], [ProviderTypeID], [ProviderSpecialtyID], [EmployeeID]); +CREATE NONCLUSTERED INDEX [IX_ESC44532] ON [fp].[Staffing] ([FlexingTypeID], [EntityGroupConfigID], [JobCodeID]) INCLUDE ([DepartmentID]); +GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [FK_Staffing_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [FK_Staffing_Employee] FOREIGN KEY ([EmployeeID]) REFERENCES [fw].[DimEmployee] ([EmployeeID]); GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [FK_Staffing_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [FK_Staffing_PayCodeGroup] FOREIGN KEY ([PayCodeGroupID]) REFERENCES [fw].[DimPayCodeGroup] ([PayCodeGroupID]); GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [FK_Staffing_ProductiveClass] FOREIGN KEY ([ProductiveClassID]) REFERENCES [fw].[DimProductiveClass] ([ProductiveClassID]); GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [FK_Staffing_Variability] FOREIGN KEY ([VariabilityID]) REFERENCES [fw].[DimVariability] ([VariabilityID]); GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor03] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__00E214AB] DEFAULT ((0)) FOR [InitialBudgetRate08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor04] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__01D638E4] DEFAULT ((0)) FOR [InitialBudgetRate09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor05] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__02CA5D1D] DEFAULT ((0)) FOR [InitialBudgetRate10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor06] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__03BE8156] DEFAULT ((0)) FOR [InitialBudgetRate11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor07] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__04B2A58F] DEFAULT ((0)) FOR [InitialBudgetRate12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor08] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__05A6C9C8] DEFAULT ((0)) FOR [InitialProjectionRate01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor09] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__069AEE01] DEFAULT ((0)) FOR [InitialProjectionRate02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor10] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__078F123A] DEFAULT ((0)) FOR [InitialProjectionRate03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__07C41C64] DEFAULT ((0)) FOR [SampledBudgetFTEs01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor11] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__08833673] DEFAULT ((0)) FOR [InitialProjectionRate04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__08B8409D] DEFAULT ((0)) FOR [SampledBudgetFTEs02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor12] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__09775AAC] DEFAULT ((0)) FOR [InitialProjectionRate05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__09AC64D6] DEFAULT ((0)) FOR [SampledBudgetFTEs03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor01] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__0A6B7EE5] DEFAULT ((0)) FOR [InitialProjectionRate06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__0AA0890F] DEFAULT ((0)) FOR [SampledBudgetFTEs04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor02] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__0B5FA31E] DEFAULT ((0)) FOR [InitialProjectionRate07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__0B94AD48] DEFAULT ((0)) FOR [SampledBudgetFTEs05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor03] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__0C53C757] DEFAULT ((0)) FOR [InitialProjectionRate08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__0C88D181] DEFAULT ((0)) FOR [SampledBudgetFTEs06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor04] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__0D47EB90] DEFAULT ((0)) FOR [InitialProjectionRate09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__0D7CF5BA] DEFAULT ((0)) FOR [SampledBudgetFTEs07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor05] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__0E3C0FC9] DEFAULT ((0)) FOR [InitialProjectionRate10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__0E7119F3] DEFAULT ((0)) FOR [SampledBudgetFTEs08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor06] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__0F303402] DEFAULT ((0)) FOR [InitialProjectionRate11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__0F653E2C] DEFAULT ((0)) FOR [SampledBudgetFTEs09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__0FCF5280] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor07] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__1024583B] DEFAULT ((0)) FOR [InitialProjectionRate12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__10596265] DEFAULT ((0)) FOR [SampledBudgetFTEs10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Entity__10C376B9] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor08] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__11187C74] DEFAULT ((0)) FOR [TargetAdjustedRate01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__114D869E] DEFAULT ((0)) FOR [SampledBudgetFTEs11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Staffi__11B79AF2] DEFAULT ((0)) FOR [StaffingWageRateID]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor09] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__120CA0AD] DEFAULT ((0)) FOR [TargetAdjustedRate02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1241AAD7] DEFAULT ((0)) FOR [SampledBudgetFTEs12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Entity__12ABBF2B] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor10] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__1300C4E6] DEFAULT ((0)) FOR [TargetAdjustedRate03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1335CF10] DEFAULT ((0)) FOR [SampledProjectionFTEs01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Depart__139FE364] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor11] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__13F4E91F] DEFAULT ((0)) FOR [TargetAdjustedRate04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1429F349] DEFAULT ((0)) FOR [SampledProjectionFTEs02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetFTEsPercentAdjustmentFactor12] DEFAULT ((1)) FOR [BudgetFTEsPercentAdjustmentFactor12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__14E90D58] DEFAULT ((0)) FOR [TargetAdjustedRate05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__151E1782] DEFAULT ((0)) FOR [SampledProjectionFTEs03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__155321AC] DEFAULT ((0)) FOR [SampledBudgetHours01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__PayCod__15882BD6] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor01] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__15DD3191] DEFAULT ((0)) FOR [TargetAdjustedRate06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__16123BBB] DEFAULT ((0)) FOR [SampledProjectionFTEs04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__164745E5] DEFAULT ((0)) FOR [SampledBudgetHours02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Produc__167C500F] DEFAULT ((0)) FOR [ProductiveClassID]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor02] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__16D155CA] DEFAULT ((0)) FOR [TargetAdjustedRate07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__17065FF4] DEFAULT ((0)) FOR [SampledProjectionFTEs05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__173B6A1E] DEFAULT ((0)) FOR [SampledBudgetHours03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Provid__17707448] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor03] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__17C57A03] DEFAULT ((0)) FOR [TargetAdjustedRate08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__17FA842D] DEFAULT ((0)) FOR [SampledProjectionFTEs06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__182F8E57] DEFAULT ((0)) FOR [SampledBudgetHours04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Provid__18649881] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor04] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__18B99E3C] DEFAULT ((0)) FOR [TargetAdjustedRate09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__18EEA866] DEFAULT ((0)) FOR [SampledProjectionFTEs07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1923B290] DEFAULT ((0)) FOR [SampledBudgetHours05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Provid__1958BCBA] DEFAULT ((0)) FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor05] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__19ADC275] DEFAULT ((0)) FOR [TargetAdjustedRate10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__19E2CC9F] DEFAULT ((0)) FOR [SampledProjectionFTEs08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1A17D6C9] DEFAULT ((0)) FOR [SampledBudgetHours06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Provid__1A4CE0F3] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor06] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__1AA1E6AE] DEFAULT ((0)) FOR [TargetAdjustedRate11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1AD6F0D8] DEFAULT ((0)) FOR [SampledProjectionFTEs09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1B0BFB02] DEFAULT ((0)) FOR [SampledBudgetHours07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Employ__1B41052C] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor07] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__1B960AE7] DEFAULT ((0)) FOR [TargetAdjustedRate12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1BCB1511] DEFAULT ((0)) FOR [SampledProjectionFTEs10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1C001F3B] DEFAULT ((0)) FOR [SampledBudgetHours08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Variab__1C352965] DEFAULT ((0)) FOR [VariabilityID]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor08] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__1C8A2F20] DEFAULT ((0)) FOR [BudgetAdjustedRate01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1CBF394A] DEFAULT ((0)) FOR [SampledProjectionFTEs11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1CF44374] DEFAULT ((0)) FOR [SampledBudgetHours09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__AddDat__1D294D9E] DEFAULT ('1900-01-01') FOR [AddDate]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor09] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__1D7E5359] DEFAULT ((0)) FOR [BudgetAdjustedRate02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1DB35D83] DEFAULT ((0)) FOR [SampledProjectionFTEs12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1DE867AD] DEFAULT ((0)) FOR [SampledBudgetHours10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__IsNew__1E1D71D7] DEFAULT ((0)) FOR [IsNew]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor10] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__1E727792] DEFAULT ((0)) FOR [BudgetAdjustedRate03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__1EA781BC] DEFAULT ((0)) FOR [InitialBudgetFTEs01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1EDC8BE6] DEFAULT ((0)) FOR [SampledBudgetHours11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Subsec__1F119610] DEFAULT ('3') FOR [SubsectionID]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor11] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__1F669BCB] DEFAULT ((0)) FOR [BudgetAdjustedRate04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__1F9BA5F5] DEFAULT ((0)) FOR [InitialBudgetFTEs02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__1FD0B01F] DEFAULT ((0)) FOR [SampledBudgetHours12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__FixedV__2005BA49] DEFAULT ((1)) FOR [FixedVariabilityPercentage]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionDollarsPercentAdjustmentFactor12] DEFAULT ((1)) FOR [ProjectionDollarsPercentAdjustmentFactor12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__205AC004] DEFAULT ((0)) FOR [BudgetAdjustedRate05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__208FCA2E] DEFAULT ((0)) FOR [InitialBudgetFTEs03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__20C4D458] DEFAULT ((0)) FOR [SampledProjectionHours01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Flexin__20F9DE82] DEFAULT ((0)) FOR [FlexingTypeID]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor01] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__214EE43D] DEFAULT ((0)) FOR [BudgetAdjustedRate06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2183EE67] DEFAULT ((0)) FOR [InitialBudgetFTEs04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__21B8F891] DEFAULT ((0)) FOR [SampledProjectionHours02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Change__21EE02BB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ChangeHistoryGroupingGUID]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor02] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__22430876] DEFAULT ((0)) FOR [BudgetAdjustedRate07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__227812A0] DEFAULT ((0)) FOR [InitialBudgetFTEs05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__22AD1CCA] DEFAULT ((0)) FOR [SampledProjectionHours03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__22E226F4] DEFAULT ((0)) FOR [SampledBudgetDollars01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor03] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__23372CAF] DEFAULT ((0)) FOR [BudgetAdjustedRate08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__236C36D9] DEFAULT ((0)) FOR [InitialBudgetFTEs06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__23A14103] DEFAULT ((0)) FOR [SampledProjectionHours04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__23D64B2D] DEFAULT ((0)) FOR [SampledBudgetDollars02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor04] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__242B50E8] DEFAULT ((0)) FOR [BudgetAdjustedRate09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__24605B12] DEFAULT ((0)) FOR [InitialBudgetFTEs07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2495653C] DEFAULT ((0)) FOR [SampledProjectionHours05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__24CA6F66] DEFAULT ((0)) FOR [SampledBudgetDollars03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor05] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__251F7521] DEFAULT ((0)) FOR [BudgetAdjustedRate10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__25547F4B] DEFAULT ((0)) FOR [InitialBudgetFTEs08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__25898975] DEFAULT ((0)) FOR [SampledProjectionHours06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__25BE939F] DEFAULT ((0)) FOR [SampledBudgetDollars04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor06] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__2613995A] DEFAULT ((0)) FOR [BudgetAdjustedRate11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2648A384] DEFAULT ((0)) FOR [InitialBudgetFTEs09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__267DADAE] DEFAULT ((0)) FOR [SampledProjectionHours07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__26B2B7D8] DEFAULT ((0)) FOR [SampledBudgetDollars05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor07] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__2707BD93] DEFAULT ((0)) FOR [BudgetAdjustedRate12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__273CC7BD] DEFAULT ((0)) FOR [InitialBudgetFTEs10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2771D1E7] DEFAULT ((0)) FOR [SampledProjectionHours08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__27A6DC11] DEFAULT ((0)) FOR [SampledBudgetDollars06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor08] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__27FBE1CC] DEFAULT ((0)) FOR [ProjectionAdjustedRate01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2830EBF6] DEFAULT ((0)) FOR [InitialBudgetFTEs11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2865F620] DEFAULT ((0)) FOR [SampledProjectionHours09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__289B004A] DEFAULT ((0)) FOR [SampledBudgetDollars07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor09] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__28F00605] DEFAULT ((0)) FOR [ProjectionAdjustedRate02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2925102F] DEFAULT ((0)) FOR [InitialBudgetFTEs12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__295A1A59] DEFAULT ((0)) FOR [SampledProjectionHours10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__298F2483] DEFAULT ((0)) FOR [SampledBudgetDollars08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor10] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__29E42A3E] DEFAULT ((0)) FOR [ProjectionAdjustedRate03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2A193468] DEFAULT ((0)) FOR [InitialProjectionFTEs01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2A4E3E92] DEFAULT ((0)) FOR [SampledProjectionHours11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2A8348BC] DEFAULT ((0)) FOR [SampledBudgetDollars09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor11] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__2AD84E77] DEFAULT ((0)) FOR [ProjectionAdjustedRate04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2B0D58A1] DEFAULT ((0)) FOR [InitialProjectionFTEs02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2B4262CB] DEFAULT ((0)) FOR [SampledProjectionHours12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2B776CF5] DEFAULT ((0)) FOR [SampledBudgetDollars10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionHoursPercentAdjustmentFactor12] DEFAULT ((1)) FOR [ProjectionHoursPercentAdjustmentFactor12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__2BCC72B0] DEFAULT ((0)) FOR [ProjectionAdjustedRate05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2C017CDA] DEFAULT ((0)) FOR [InitialProjectionFTEs03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2C368704] DEFAULT ((0)) FOR [InitialBudgetHours01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2C6B912E] DEFAULT ((0)) FOR [SampledBudgetDollars11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor01] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__2CC096E9] DEFAULT ((0)) FOR [ProjectionAdjustedRate06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2CF5A113] DEFAULT ((0)) FOR [InitialProjectionFTEs04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2D2AAB3D] DEFAULT ((0)) FOR [InitialBudgetHours02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2D5FB567] DEFAULT ((0)) FOR [SampledBudgetDollars12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor02] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__2DB4BB22] DEFAULT ((0)) FOR [ProjectionAdjustedRate07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2DE9C54C] DEFAULT ((0)) FOR [InitialProjectionFTEs05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2E1ECF76] DEFAULT ((0)) FOR [InitialBudgetHours03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2E53D9A0] DEFAULT ((0)) FOR [SampledProjectionDollars01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor03] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__2EA8DF5B] DEFAULT ((0)) FOR [ProjectionAdjustedRate08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2EDDE985] DEFAULT ((0)) FOR [InitialProjectionFTEs06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2F12F3AF] DEFAULT ((0)) FOR [InitialBudgetHours04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__2F47FDD9] DEFAULT ((0)) FOR [SampledProjectionDollars02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor04] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__2F9D0394] DEFAULT ((0)) FOR [ProjectionAdjustedRate09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__2FD20DBE] DEFAULT ((0)) FOR [InitialProjectionFTEs07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__300717E8] DEFAULT ((0)) FOR [InitialBudgetHours05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__303C2212] DEFAULT ((0)) FOR [SampledProjectionDollars03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor05] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__309127CD] DEFAULT ((0)) FOR [ProjectionAdjustedRate10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__30C631F7] DEFAULT ((0)) FOR [InitialProjectionFTEs08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__30FB3C21] DEFAULT ((0)) FOR [InitialBudgetHours06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__3130464B] DEFAULT ((0)) FOR [SampledProjectionDollars04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor06] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__31854C06] DEFAULT ((0)) FOR [ProjectionAdjustedRate11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__31BA5630] DEFAULT ((0)) FOR [InitialProjectionFTEs09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__31EF605A] DEFAULT ((0)) FOR [InitialBudgetHours07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__32246A84] DEFAULT ((0)) FOR [SampledProjectionDollars05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor07] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__3279703F] DEFAULT ((0)) FOR [ProjectionAdjustedRate12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__32AE7A69] DEFAULT ((0)) FOR [InitialProjectionFTEs10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__32E38493] DEFAULT ((0)) FOR [InitialBudgetHours08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__33188EBD] DEFAULT ((0)) FOR [SampledProjectionDollars06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor08] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__336D9478] DEFAULT ((0)) FOR [BudgetDollarsLockType]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__33A29EA2] DEFAULT ((0)) FOR [InitialProjectionFTEs11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__33D7A8CC] DEFAULT ((0)) FOR [InitialBudgetHours09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__340CB2F6] DEFAULT ((0)) FOR [SampledProjectionDollars07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor09] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__3461B8B1] DEFAULT ((0)) FOR [BudgetDollarsLockFlag]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3496C2DB] DEFAULT ((0)) FOR [InitialProjectionFTEs12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__34CBCD05] DEFAULT ((0)) FOR [InitialBudgetHours10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__3500D72F] DEFAULT ((0)) FOR [SampledProjectionDollars08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor10] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__3555DCEA] DEFAULT ((0)) FOR [TargetDollarsLockType]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__358AE714] DEFAULT ((0)) FOR [TargetAdjustedFTEs01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__35BFF13E] DEFAULT ((0)) FOR [InitialBudgetHours11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__35F4FB68] DEFAULT ((0)) FOR [SampledProjectionDollars09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor11] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__364A0123] DEFAULT ((0)) FOR [TargetDollarsLockFlag]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__367F0B4D] DEFAULT ((0)) FOR [TargetAdjustedFTEs02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__36B41577] DEFAULT ((0)) FOR [InitialBudgetHours12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__36E91FA1] DEFAULT ((0)) FOR [SampledProjectionDollars10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_ProjectionFTEsPercentAdjustmentFactor12] DEFAULT ((1)) FOR [ProjectionFTEsPercentAdjustmentFactor12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__373E255C] DEFAULT ((0)) FOR [ProjectionDollarsLockType]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__37732F86] DEFAULT ((0)) FOR [TargetAdjustedFTEs03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__37A839B0] DEFAULT ((0)) FOR [InitialProjectionHours01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__37DD43DA] DEFAULT ((0)) FOR [SampledProjectionDollars11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__38324995] DEFAULT ((0)) FOR [ProjectionDollarsLockFlag]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__386753BF] DEFAULT ((0)) FOR [TargetAdjustedFTEs04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__389C5DE9] DEFAULT ((0)) FOR [InitialProjectionHours02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Sample__38D16813] DEFAULT ((0)) FOR [SampledProjectionDollars12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__39266DCE] DEFAULT ((0)) FOR [BudgetHoursLockType]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__395B77F8] DEFAULT ((0)) FOR [TargetAdjustedFTEs05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__39908222] DEFAULT ((0)) FOR [InitialProjectionHours03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__39C58C4C] DEFAULT ((0)) FOR [InitialBudgetDollars01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__3A1A9207] DEFAULT ((0)) FOR [BudgetHoursLockFlag]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__3A4F9C31] DEFAULT ((0)) FOR [TargetAdjustedFTEs06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3A84A65B] DEFAULT ((0)) FOR [InitialProjectionHours04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3AB9B085] DEFAULT ((0)) FOR [InitialBudgetDollars02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__3B0EB640] DEFAULT ((0)) FOR [TargetHoursLockType]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__3B43C06A] DEFAULT ((0)) FOR [TargetAdjustedFTEs07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3B78CA94] DEFAULT ((0)) FOR [InitialProjectionHours05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3BADD4BE] DEFAULT ((0)) FOR [InitialBudgetDollars03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__3C02DA79] DEFAULT ((0)) FOR [TargetHoursLockFlag]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__3C37E4A3] DEFAULT ((0)) FOR [TargetAdjustedFTEs08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3C6CEECD] DEFAULT ((0)) FOR [InitialProjectionHours06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3CA1F8F7] DEFAULT ((0)) FOR [InitialBudgetDollars04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__3CF6FEB2] DEFAULT ((0)) FOR [ProjectionHoursLockType]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__3D2C08DC] DEFAULT ((0)) FOR [TargetAdjustedFTEs09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3D611306] DEFAULT ((0)) FOR [InitialProjectionHours07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3D961D30] DEFAULT ((0)) FOR [InitialBudgetDollars05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__3DEB22EB] DEFAULT ((0)) FOR [ProjectionHoursLockFlag]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__3E202D15] DEFAULT ((0)) FOR [TargetAdjustedFTEs10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3E55373F] DEFAULT ((0)) FOR [InitialProjectionHours08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3E8A4169] DEFAULT ((0)) FOR [InitialBudgetDollars06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__3EDF4724] DEFAULT ((0)) FOR [BudgetFTEsLockType]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__3F14514E] DEFAULT ((0)) FOR [TargetAdjustedFTEs11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3F495B78] DEFAULT ((0)) FOR [InitialProjectionHours09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__3F7E65A2] DEFAULT ((0)) FOR [InitialBudgetDollars07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__3FD36B5D] DEFAULT ((0)) FOR [BudgetFTEsLockFlag]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__40087587] DEFAULT ((0)) FOR [TargetAdjustedFTEs12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__403D7FB1] DEFAULT ((0)) FOR [InitialProjectionHours10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__407289DB] DEFAULT ((0)) FOR [InitialBudgetDollars08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__40C78F96] DEFAULT ((0)) FOR [TargetFTEsLockType]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__40FC99C0] DEFAULT ((0)) FOR [BudgetAdjustedFTEs01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4131A3EA] DEFAULT ((0)) FOR [InitialProjectionHours11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4166AE14] DEFAULT ((0)) FOR [InitialBudgetDollars09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__41BBB3CF] DEFAULT ((0)) FOR [TargetFTEsLockFlag]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__41F0BDF9] DEFAULT ((0)) FOR [BudgetAdjustedFTEs02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4225C823] DEFAULT ((0)) FOR [InitialProjectionHours12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__425AD24D] DEFAULT ((0)) FOR [InitialBudgetDollars10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__42AFD808] DEFAULT ((0)) FOR [ProjectionFTEsLockType]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__42E4E232] DEFAULT ((0)) FOR [BudgetAdjustedFTEs03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__4319EC5C] DEFAULT ((0)) FOR [TargetAdjustedHours01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__434EF686] DEFAULT ((0)) FOR [InitialBudgetDollars11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__43A3FC41] DEFAULT ((0)) FOR [ProjectionFTEsLockFlag]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__43D9066B] DEFAULT ((0)) FOR [BudgetAdjustedFTEs04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__440E1095] DEFAULT ((0)) FOR [TargetAdjustedHours02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__44431ABF] DEFAULT ((0)) FOR [InitialBudgetDollars12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__44CD2AA4] DEFAULT ((0)) FOR [BudgetAdjustedFTEs05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__450234CE] DEFAULT ((0)) FOR [TargetAdjustedHours03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__45373EF8] DEFAULT ((0)) FOR [InitialProjectionDollars01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__45C14EDD] DEFAULT ((0)) FOR [BudgetAdjustedFTEs06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__45F65907] DEFAULT ((0)) FOR [TargetAdjustedHours04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__462B6331] DEFAULT ((0)) FOR [InitialProjectionDollars02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__46B57316] DEFAULT ((0)) FOR [BudgetAdjustedFTEs07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__46EA7D40] DEFAULT ((0)) FOR [TargetAdjustedHours05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__471F876A] DEFAULT ((0)) FOR [InitialProjectionDollars03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__47A9974F] DEFAULT ((0)) FOR [BudgetAdjustedFTEs08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__47DEA179] DEFAULT ((0)) FOR [TargetAdjustedHours06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4813ABA3] DEFAULT ((0)) FOR [InitialProjectionDollars04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__489DBB88] DEFAULT ((0)) FOR [BudgetAdjustedFTEs09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__48D2C5B2] DEFAULT ((0)) FOR [TargetAdjustedHours07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4907CFDC] DEFAULT ((0)) FOR [InitialProjectionDollars05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__4991DFC1] DEFAULT ((0)) FOR [BudgetAdjustedFTEs10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__49C6E9EB] DEFAULT ((0)) FOR [TargetAdjustedHours08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__49FBF415] DEFAULT ((0)) FOR [InitialProjectionDollars06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__4A8603FA] DEFAULT ((0)) FOR [BudgetAdjustedFTEs11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__4ABB0E24] DEFAULT ((0)) FOR [TargetAdjustedHours09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4AF0184E] DEFAULT ((0)) FOR [InitialProjectionDollars07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__4B7A2833] DEFAULT ((0)) FOR [BudgetAdjustedFTEs12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__4BAF325D] DEFAULT ((0)) FOR [TargetAdjustedHours10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4BE43C87] DEFAULT ((0)) FOR [InitialProjectionDollars08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__4C6E4C6C] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__4CA35696] DEFAULT ((0)) FOR [TargetAdjustedHours11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4CD860C0] DEFAULT ((0)) FOR [InitialProjectionDollars09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__4D6270A5] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__4D977ACF] DEFAULT ((0)) FOR [TargetAdjustedHours12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4DCC84F9] DEFAULT ((0)) FOR [InitialProjectionDollars10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__4E5694DE] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__4E8B9F08] DEFAULT ((0)) FOR [BudgetAdjustedHours01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4EC0A932] DEFAULT ((0)) FOR [InitialProjectionDollars11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__4F4AB917] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__4F7FC341] DEFAULT ((0)) FOR [BudgetAdjustedHours02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__4FB4CD6B] DEFAULT ((0)) FOR [InitialProjectionDollars12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__JobCod__4FFFB185] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__503EDD50] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__5073E77A] DEFAULT ((0)) FOR [BudgetAdjustedHours03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__50A8F1A4] DEFAULT ((0)) FOR [TargetAdjustedDollars01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor01] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__51330189] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__51680BB3] DEFAULT ((0)) FOR [BudgetAdjustedHours04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__519D15DD] DEFAULT ((0)) FOR [TargetAdjustedDollars02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor02] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__522725C2] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__525C2FEC] DEFAULT ((0)) FOR [BudgetAdjustedHours05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__52913A16] DEFAULT ((0)) FOR [TargetAdjustedDollars03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor03] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__531B49FB] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__53505425] DEFAULT ((0)) FOR [BudgetAdjustedHours06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__53855E4F] DEFAULT ((0)) FOR [TargetAdjustedDollars04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor04] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__540F6E34] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__5444785E] DEFAULT ((0)) FOR [BudgetAdjustedHours07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__54798288] DEFAULT ((0)) FOR [TargetAdjustedDollars05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor05] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__5503926D] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__55389C97] DEFAULT ((0)) FOR [BudgetAdjustedHours08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__556DA6C1] DEFAULT ((0)) FOR [TargetAdjustedDollars06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor06] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__55F7B6A6] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__562CC0D0] DEFAULT ((0)) FOR [BudgetAdjustedHours09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__5661CAFA] DEFAULT ((0)) FOR [TargetAdjustedDollars07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor07] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__56EBDADF] DEFAULT ((0)) FOR [ProjectionAdjustedFTEs12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__5720E509] DEFAULT ((0)) FOR [BudgetAdjustedHours10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__5755EF33] DEFAULT ((0)) FOR [TargetAdjustedDollars08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor08] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__58150942] DEFAULT ((0)) FOR [BudgetAdjustedHours11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__584A136C] DEFAULT ((0)) FOR [TargetAdjustedDollars09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor09] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__59092D7B] DEFAULT ((0)) FOR [BudgetAdjustedHours12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__593E37A5] DEFAULT ((0)) FOR [TargetAdjustedDollars10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor10] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__59FD51B4] DEFAULT ((0)) FOR [ProjectionAdjustedHours01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__5A325BDE] DEFAULT ((0)) FOR [TargetAdjustedDollars11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor11] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__5AF175ED] DEFAULT ((0)) FOR [ProjectionAdjustedHours02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Target__5B268017] DEFAULT ((0)) FOR [TargetAdjustedDollars12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetDollarsPercentAdjustmentFactor12] DEFAULT ((1)) FOR [TargetDollarsPercentAdjustmentFactor12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__5BE59A26] DEFAULT ((0)) FOR [ProjectionAdjustedHours03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__5C1AA450] DEFAULT ((0)) FOR [BudgetAdjustedDollars01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor01] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__5CD9BE5F] DEFAULT ((0)) FOR [ProjectionAdjustedHours04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__5D0EC889] DEFAULT ((0)) FOR [BudgetAdjustedDollars02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor02] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__5DCDE298] DEFAULT ((0)) FOR [ProjectionAdjustedHours05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__5E02ECC2] DEFAULT ((0)) FOR [BudgetAdjustedDollars03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor03] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__5EC206D1] DEFAULT ((0)) FOR [ProjectionAdjustedHours06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__5EF710FB] DEFAULT ((0)) FOR [BudgetAdjustedDollars04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor04] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__5FB62B0A] DEFAULT ((0)) FOR [ProjectionAdjustedHours07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__5FEB3534] DEFAULT ((0)) FOR [BudgetAdjustedDollars05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor05] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__60AA4F43] DEFAULT ((0)) FOR [ProjectionAdjustedHours08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__60DF596D] DEFAULT ((0)) FOR [BudgetAdjustedDollars06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor06] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__619E737C] DEFAULT ((0)) FOR [ProjectionAdjustedHours09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__61D37DA6] DEFAULT ((0)) FOR [BudgetAdjustedDollars07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor07] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__629297B5] DEFAULT ((0)) FOR [ProjectionAdjustedHours10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__62C7A1DF] DEFAULT ((0)) FOR [BudgetAdjustedDollars08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor08] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__6386BBEE] DEFAULT ((0)) FOR [ProjectionAdjustedHours11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__63BBC618] DEFAULT ((0)) FOR [BudgetAdjustedDollars09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor09] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__647AE027] DEFAULT ((0)) FOR [ProjectionAdjustedHours12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__64AFEA51] DEFAULT ((0)) FOR [BudgetAdjustedDollars10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor10] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__65A40E8A] DEFAULT ((0)) FOR [BudgetAdjustedDollars11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor11] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Budget__669832C3] DEFAULT ((0)) FOR [BudgetAdjustedDollars12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetHoursPercentAdjustmentFactor12] DEFAULT ((1)) FOR [TargetHoursPercentAdjustmentFactor12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__678C56FC] DEFAULT ((0)) FOR [ProjectionAdjustedDollars01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor01] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__68807B35] DEFAULT ((0)) FOR [ProjectionAdjustedDollars02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor02] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__69749F6E] DEFAULT ((0)) FOR [ProjectionAdjustedDollars03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor03] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__6A68C3A7] DEFAULT ((0)) FOR [ProjectionAdjustedDollars04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor04] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__6B5CE7E0] DEFAULT ((0)) FOR [ProjectionAdjustedDollars05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor05] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__6C510C19] DEFAULT ((0)) FOR [ProjectionAdjustedDollars06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor06] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__6D453052] DEFAULT ((0)) FOR [ProjectionAdjustedDollars07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor07] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__6E39548B] DEFAULT ((0)) FOR [ProjectionAdjustedDollars08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor08] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__6F2D78C4] DEFAULT ((0)) FOR [ProjectionAdjustedDollars09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor09] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__70219CFD] DEFAULT ((0)) FOR [ProjectionAdjustedDollars10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor10] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__7115C136] DEFAULT ((0)) FOR [ProjectionAdjustedDollars11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor11] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Projec__7209E56F] DEFAULT ((0)) FOR [ProjectionAdjustedDollars12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_TargetFTEsPercentAdjustmentFactor12] DEFAULT ((1)) FOR [TargetFTEsPercentAdjustmentFactor12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor01] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor02] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor03] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor04] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor05] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor06] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor07] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor08] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor08]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__7A35171C] DEFAULT ((0)) FOR [InitialBudgetRate01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor09] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__7B293B55] DEFAULT ((0)) FOR [InitialBudgetRate02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor10] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__7C1D5F8E] DEFAULT ((0)) FOR [InitialBudgetRate03]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor11] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__7D1183C7] DEFAULT ((0)) FOR [InitialBudgetRate04]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetDollarsPercentAdjustmentFactor12] DEFAULT ((1)) FOR [BudgetDollarsPercentAdjustmentFactor12]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__7E05A800] DEFAULT ((0)) FOR [InitialBudgetRate05]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor01] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__7EF9CC39] DEFAULT ((0)) FOR [InitialBudgetRate06]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [df_BudgetHoursPercentAdjustmentFactor02] DEFAULT ((1)) FOR [BudgetHoursPercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[Staffing] ADD CONSTRAINT [DF__Staffing__Initia__7FEDF072] DEFAULT ((0)) FOR [InitialBudgetRate07]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingAdjustment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingAdjustment] ( + [AdjustmentGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [Value] decimal NOT NULL, + [AdjustmentFilterJSON] nvarchar(max) NOT NULL, + [GroupingHierarchyJSON] nvarchar(max) NOT NULL, + [AdjustedProperty] nvarchar(100) NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [ParentFilterJSON] nvarchar(max) NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [ClassificationGroupID] int NOT NULL, + [ClassificationCategoryID] int NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + [LastModifiedDateUtc] datetime NOT NULL, + [DimensionMemberJson] nvarchar(max) NOT NULL, + [AdjustmentID] int NOT NULL, + [SubsectionID] int NOT NULL, + [IsErrored] bit NOT NULL, + PRIMARY KEY ([AdjustmentGUID]) +); + +CREATE NONCLUSTERED INDEX [JAZZ_7301_GroupingGUID] ON [fp].[StaffingAdjustment] ([GroupingGUID]) INCLUDE ([AdjustmentType], [AdjustmentFilterJSON], [GroupingHierarchyJSON], [AuthorGUID], [AuthorFullName], [TimeClassID], [BudgetPhaseID], [ClassificationGroupID], [ClassificationCategoryID], [IsRecordDeleted], [DateCreatedUtc], [LastModifiedDateUtc]); +GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [FK__PayrollBu__Budge__28348115] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [FK_StaffingAdjustment_SubsectionID] FOREIGN KEY ([SubsectionID]) REFERENCES [fp].[PlanSubsection] ([SubsectionID]); GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF_StaffingAdjustment_ClassificationGroupID] DEFAULT ((0)) FOR [ClassificationGroupID]; GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF_StaffingAdjustment_ClassificationCategoryID] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF_StaffingAdjustment_SubsectionID] DEFAULT ((0)) FOR [SubsectionID]; GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Adjus__2928A54E] DEFAULT (newid()) FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Adjus__2A1CC987] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Value__2B10EDC0] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Adjus__2C0511F9] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Group__2CF93632] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF_StaffingAdjustment_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Adjus__2DED5A6B] DEFAULT ('') FOR [AdjustedProperty]; GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Comme__2EE17EA4] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Autho__2FD5A2DD] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Autho__30C9C716] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__UnitT__33A633C1] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Group__349A57FA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__PayrollBu__Paren__4A20501C] DEFAULT ('{}') FOR [ParentFilterJSON]; GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__StaffingA__IsErr__4AF96E98] DEFAULT ((0)) FOR [IsErrored]; GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__StaffingA__Dimen__63E1EA97] DEFAULT ('') FOR [DimensionMemberJson]; GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__StaffingA__DateC__681C8FCF] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__StaffingA__LastM__6910B408] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__StaffingA__TimeC__6B169606] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[StaffingAdjustment] ADD CONSTRAINT [DF__StaffingA__IsRec__6FA7D7A7] DEFAULT ((0)) FOR [IsRecordDeleted]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingAdjustmentImport ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingAdjustmentImport] ( + [RowID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [Value] decimal NOT NULL, + [Version] timestamp NOT NULL, + [PayCodeGroupID] int NOT NULL, + [ProductiveClassID] int NOT NULL, + [VariabilityID] int NOT NULL, + [EntityID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [EmployeeID] int NOT NULL, + [AdjustmentID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL, + [OriginalUnitTypeID] tinyint NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_AdjustmentID] ON [fp].[StaffingAdjustmentImport] ([AdjustmentID]); +GO +ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF_StaffingAdjustmentImport_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__PayrollAdjImport__Fisca__3CCC1A58] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF_INTPayrollAdjImportINGVALUE] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF_PayrollAdjImport_PayCodeGroupID] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__PayrollAd__Produ__7712F224] DEFAULT ((0)) FOR [ProductiveClassID]; GO +ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__StaffingA__Emplo__0478D75B] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__PayrollAd__Varia__14F85AC6] DEFAULT ((0)) FOR [VariabilityID]; GO +ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__StaffingA__Adjus__268EC394] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__StaffingA__Provi__30981C12] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__StaffingA__Provi__318C404B] DEFAULT ((0)) FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__StaffingA__Provi__32806484] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__StaffingA__Provi__337488BD] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO +ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__PayrollAd__Entit__35652A58] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__PayrollAd__Adjus__6F71D05C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__PayrollAdjImport__Depar__2B6F7FBE] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__PayrollAdjImport__JobCo__2D57C830] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__PayrollAdjImport__Fisca__31285914] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF_StaffingAdjustmentImport_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__PayrollAdjImport__UnitT__34F8E9F8] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[StaffingAdjustmentImport] ADD CONSTRAINT [DF__StaffingA__IsRec__7378688B] DEFAULT ((0)) FOR [IsRecordDeleted]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingAdjustment_backup ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingAdjustment_backup] ( + [AdjustmentGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [Value] decimal NOT NULL, + [AdjustmentFilterJSON] nvarchar(max) NOT NULL, + [GroupingHierarchyJSON] nvarchar(max) NOT NULL, + [AdjustedProperty] nvarchar(100) NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [LastModifiedDate] datetime NOT NULL, + [DateCreatedUTC] datetime NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [ParentFilterJSON] nvarchar(max) NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + PRIMARY KEY ([AdjustmentGUID]) +); +GO +ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [FK__PayrollBu__Budge__0C575C76] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Adjus__00E5A9CA] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Value__01D9CE03] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Adjus__02CDF23C] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO +ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Group__03C21675] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO +ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Adjus__04B63AAE] DEFAULT ('') FOR [AdjustedProperty]; GO +ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Comme__05AA5EE7] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Autho__069E8320] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Autho__0792A759] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__LastM__0886CB92] DEFAULT (getdate()) FOR [LastModifiedDate]; GO +ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__DateC__097AEFCB] DEFAULT (getdate()) FOR [DateCreatedUTC]; GO +ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__UnitT__0A6F1404] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Group__0B63383D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Paren__0FFF66D6] DEFAULT ('') FOR [ParentFilterJSON]; GO +ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF_StaffingAdjustmentBackup_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__StaffingA__TimeC__6C0ABA3F] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[StaffingAdjustment_backup] ADD CONSTRAINT [DF__PayrollBu__Adjus__7FF18591] DEFAULT (newid()) FOR [AdjustmentGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingBasisFlexRate ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingBasisFlexRate] ( + [RowID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeGroupID] int NOT NULL, + [ProductiveClassID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetConfigID] smallint NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [EmployeeID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL, + [UnitTypeID] int NOT NULL, + [FlexRate01] decimal NOT NULL, + [FlexRate02] decimal NOT NULL, + [FlexRate03] decimal NOT NULL, + [FlexRate04] decimal NOT NULL, + [FlexRate05] decimal NOT NULL, + [FlexRate06] decimal NOT NULL, + [FlexRate07] decimal NOT NULL, + [FlexRate08] decimal NOT NULL, + [FlexRate09] decimal NOT NULL, + [FlexRate10] decimal NOT NULL, + [FlexRate11] decimal NOT NULL, + [FlexRate12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[StaffingBasisFlexRate] ([BudgetConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [ProviderID], [ProviderTypeID], [ProviderLineItemID], [ProviderSpecialtyID], [FiscalYearID], [TimeClassID], [AdjustmentGUID]); +GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [FK_StaffingBasisFlexRate_AdjustmentGUID] FOREIGN KEY ([AdjustmentGUID]) REFERENCES [fp].[StaffingAdjustment] ([AdjustmentGUID]); GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Entit__5971AB21] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Depar__5A65CF5A] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__JobCo__5B59F393] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__PayCo__5C4E17CC] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Produ__5D423C05] DEFAULT ((0)) FOR [ProductiveClassID]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Fisca__5E36603E] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__TimeC__5F2A8477] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Budge__601EA8B0] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Adjus__6112CCE9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Emplo__6206F122] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Provi__62FB155B] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Provi__63EF3994] DEFAULT ((0)) FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Provi__64E35DCD] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__Provi__65D78206] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__UnitT__66CBA63F] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__67BFCA78] DEFAULT ((0)) FOR [FlexRate01]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__68B3EEB1] DEFAULT ((0)) FOR [FlexRate02]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__69A812EA] DEFAULT ((0)) FOR [FlexRate03]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__6A9C3723] DEFAULT ((0)) FOR [FlexRate04]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__6B905B5C] DEFAULT ((0)) FOR [FlexRate05]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__6C847F95] DEFAULT ((0)) FOR [FlexRate06]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__6D78A3CE] DEFAULT ((0)) FOR [FlexRate07]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__6E6CC807] DEFAULT ((0)) FOR [FlexRate08]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__6F60EC40] DEFAULT ((0)) FOR [FlexRate09]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__70551079] DEFAULT ((0)) FOR [FlexRate10]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__714934B2] DEFAULT ((0)) FOR [FlexRate11]; GO +ALTER TABLE [fp].[StaffingBasisFlexRate] ADD CONSTRAINT [DF__TmpStaffi__FlexR__723D58EB] DEFAULT ((0)) FOR [FlexRate12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingChangeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingChangeHistory] ( + [RowID] bigint NOT NULL, + [StaffingID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [OldValue] decimal NOT NULL, + [NewValue] decimal NOT NULL, + [BudgetConfigID] int NOT NULL, + [DateCreatedUTC] datetime2 NOT NULL, + [SubsectionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_StaffingChangeHistory] ON [fp].[StaffingChangeHistory] ([StaffingID]); +CREATE NONCLUSTERED INDEX [IX_StaffingChangeHistory_AdjustmentGuid] ON [fp].[StaffingChangeHistory] ([AdjustmentGUID]) INCLUDE ([StaffingID], [FiscalMonthID], [UnitTypeID], [TimeClassID], [BudgetPhaseID]); +GO +ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [FK_StaffingChangeHistory_StaffingID] FOREIGN KEY ([StaffingID]) REFERENCES [fp].[Staffing] ([StaffingID]); GO +ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__Staff__61E95796] DEFAULT ((0)) FOR [StaffingID]; GO +ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__Adjus__62DD7BCF] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__Group__63D1A008] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__Adjus__64C5C441] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__Fisca__65B9E87A] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__UnitT__66AE0CB3] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__TimeC__67A230EC] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__Budge__68965525] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__OldVa__698A795E] DEFAULT ((0)) FOR [OldValue]; GO +ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__NewVa__6A7E9D97] DEFAULT ((0)) FOR [NewValue]; GO +ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__Budge__6B72C1D0] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__DateC__6C66E609] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO +ALTER TABLE [fp].[StaffingChangeHistory] ADD CONSTRAINT [DF__StaffingC__Subse__6D5B0A42] DEFAULT ((0)) FOR [SubsectionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingChangeHistory_OLD ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingChangeHistory_OLD] ( + [RowID] bigint NOT NULL, + [StaffingID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [OldValue] decimal NOT NULL, + [NewValue] decimal NOT NULL, + [BudgetConfigID] int NOT NULL, + [DateCreatedUTC] datetime2 NOT NULL, + [SubsectionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__DateC__04CDDD16] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO +ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__Staff__17A54CA8] DEFAULT ((0)) FOR [StaffingID]; GO +ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__Subse__17D75B40] DEFAULT ((3)) FOR [SubsectionID]; GO +ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__Adjus__189970E1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__Group__198D951A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__Adjus__1A81B953] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__Fisca__1C6A01C5] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__UnitT__1D5E25FE] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__TimeC__1E524A37] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__Budge__1F466E70] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__OldVa__203A92A9] DEFAULT ((0)) FOR [OldValue]; GO +ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__NewVa__212EB6E2] DEFAULT ((0)) FOR [NewValue]; GO +ALTER TABLE [fp].[StaffingChangeHistory_OLD] ADD CONSTRAINT [DF__StaffingC__Budge__60066CBB] DEFAULT ((0)) FOR [BudgetConfigID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingExpenseFlexingConfig ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingExpenseFlexingConfig] ( + [EntityGroupConfigGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [FlexMethodID] smallint NOT NULL, + [RowID] int NOT NULL, + [ProductivityTarget] decimal NOT NULL, + [IsUsingProductivityTarget] bit NOT NULL, + [IsUsingEmployeeBudgeting] bit NOT NULL, + [ProjectionProductivityTarget] decimal NOT NULL, + [IsUsingProjectionProductivityTarget] bit NOT NULL, + PRIMARY KEY ([EntityGroupConfigGUID], [DepartmentID]) +); +GO +ALTER TABLE [fp].[StaffingExpenseFlexingConfig] ADD CONSTRAINT [FK__StaffingE__Depar__40C134DE] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[StaffingExpenseFlexingConfig] ADD CONSTRAINT [DF__StaffingE__Produ__023135C3] DEFAULT ((0)) FOR [ProductivityTarget]; GO +ALTER TABLE [fp].[StaffingExpenseFlexingConfig] ADD CONSTRAINT [DF__StaffingE__IsUsi__0A930848] DEFAULT ((0)) FOR [IsUsingProductivityTarget]; GO +ALTER TABLE [fp].[StaffingExpenseFlexingConfig] ADD CONSTRAINT [df_StaffingExpenseFlexingConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO +ALTER TABLE [fp].[StaffingExpenseFlexingConfig] ADD CONSTRAINT [DF__StaffingE__Depar__3D071777] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StaffingExpenseFlexingConfig] ADD CONSTRAINT [DF__StaffingE__FlexM__3DFB3BB0] DEFAULT ((0)) FOR [FlexMethodID]; GO +ALTER TABLE [fp].[StaffingExpenseFlexingConfig] ADD CONSTRAINT [DF_StaffingExpenseFlexingConfig_ProjectionProductivityTarget] DEFAULT ((0)) FOR [ProjectionProductivityTarget]; GO +ALTER TABLE [fp].[StaffingExpenseFlexingConfig] ADD CONSTRAINT [DF_StaffingExpenseFlexingConfig_IsUsingProjectionProductivityTarget] DEFAULT ((0)) FOR [IsUsingProjectionProductivityTarget]; GO +ALTER TABLE [fp].[StaffingExpenseFlexingConfig] ADD CONSTRAINT [DF__StaffingE__IsUsi__727A22B1] DEFAULT ((0)) FOR [IsUsingEmployeeBudgeting]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingFlexingOverrideConfig ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingFlexingOverrideConfig] ( + [OverrideFlexConfigGUID] uniqueidentifier NOT NULL, + [EntityGroupConfigGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [FlexMethodID] smallint NOT NULL, + PRIMARY KEY ([OverrideFlexConfigGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [Unique_StaffingFlexingOverrideConfig_EC_Dept_Account] ON [fp].[StaffingFlexingOverrideConfig] ([EntityGroupConfigGUID], [DepartmentID], [JobCodeID]); +GO +ALTER TABLE [fp].[StaffingFlexingOverrideConfig] ADD CONSTRAINT [FK__StaffingF__Depar__486256A6] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[StaffingFlexingOverrideConfig] ADD CONSTRAINT [df_StaffingFlexingOverrideConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO +ALTER TABLE [fp].[StaffingFlexingOverrideConfig] ADD CONSTRAINT [DF__StaffingF__Overr__42BFF0CD] DEFAULT (newid()) FOR [OverrideFlexConfigGUID]; GO +ALTER TABLE [fp].[StaffingFlexingOverrideConfig] ADD CONSTRAINT [DF__StaffingF__Depar__44A8393F] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StaffingFlexingOverrideConfig] ADD CONSTRAINT [DF__StaffingF__JobCo__459C5D78] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[StaffingFlexingOverrideConfig] ADD CONSTRAINT [DF__StaffingF__FlexM__469081B1] DEFAULT ((0)) FOR [FlexMethodID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingFlexingOverrideConfigAssignment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingFlexingOverrideConfigAssignment] ( + [OverrideFlexConfigGUID] uniqueidentifier NOT NULL, + [AccountID] int NOT NULL, + PRIMARY KEY ([OverrideFlexConfigGUID], [AccountID]) +); +GO +ALTER TABLE [fp].[StaffingFlexingOverrideConfigAssignment] ADD CONSTRAINT [FK_OverrideFlexConfigGUID] FOREIGN KEY ([OverrideFlexConfigGUID]) REFERENCES [fp].[StaffingFlexingOverrideConfig] ([OverrideFlexConfigGUID]); GO +ALTER TABLE [fp].[StaffingFlexingOverrideConfigAssignment] ADD CONSTRAINT [DF__StaffingF__Overr__496CEE5C] DEFAULT (newid()) FOR [OverrideFlexConfigGUID]; GO +ALTER TABLE [fp].[StaffingFlexingOverrideConfigAssignment] ADD CONSTRAINT [DF__StaffingF__Accou__4A611295] DEFAULT ((0)) FOR [AccountID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingHistory] ( + [StaffingID] int NOT NULL, + [ActualYTDDollars01] decimal NOT NULL, + [ActualYTDDollars02] decimal NOT NULL, + [ActualYTDDollars03] decimal NOT NULL, + [ActualYTDDollars04] decimal NOT NULL, + [ActualYTDDollars05] decimal NOT NULL, + [ActualYTDDollars06] decimal NOT NULL, + [ActualYTDDollars07] decimal NOT NULL, + [ActualYTDDollars08] decimal NOT NULL, + [ActualYTDDollars09] decimal NOT NULL, + [ActualYTDDollars10] decimal NOT NULL, + [ActualYTDDollars11] decimal NOT NULL, + [ActualYTDDollars12] decimal NOT NULL, + [ActualYTDDollarsTotal] decimal NULL, + [PriorYearActualDollars01] decimal NOT NULL, + [PriorYearActualDollars02] decimal NOT NULL, + [PriorYearActualDollars03] decimal NOT NULL, + [PriorYearActualDollars04] decimal NOT NULL, + [PriorYearActualDollars05] decimal NOT NULL, + [PriorYearActualDollars06] decimal NOT NULL, + [PriorYearActualDollars07] decimal NOT NULL, + [PriorYearActualDollars08] decimal NOT NULL, + [PriorYearActualDollars09] decimal NOT NULL, + [PriorYearActualDollars10] decimal NOT NULL, + [PriorYearActualDollars11] decimal NOT NULL, + [PriorYearActualDollars12] decimal NOT NULL, + [PriorYearActualDollarsTotal] decimal NULL, + [CurrentYearBudgetDollars01] decimal NOT NULL, + [CurrentYearBudgetDollars02] decimal NOT NULL, + [CurrentYearBudgetDollars03] decimal NOT NULL, + [CurrentYearBudgetDollars04] decimal NOT NULL, + [CurrentYearBudgetDollars05] decimal NOT NULL, + [CurrentYearBudgetDollars06] decimal NOT NULL, + [CurrentYearBudgetDollars07] decimal NOT NULL, + [CurrentYearBudgetDollars08] decimal NOT NULL, + [CurrentYearBudgetDollars09] decimal NOT NULL, + [CurrentYearBudgetDollars10] decimal NOT NULL, + [CurrentYearBudgetDollars11] decimal NOT NULL, + [CurrentYearBudgetDollars12] decimal NOT NULL, + [CurrentYearBudgetDollarsTotal] decimal NULL, + [ActualYTDHours01] decimal NOT NULL, + [ActualYTDHours02] decimal NOT NULL, + [ActualYTDHours03] decimal NOT NULL, + [ActualYTDHours04] decimal NOT NULL, + [ActualYTDHours05] decimal NOT NULL, + [ActualYTDHours06] decimal NOT NULL, + [ActualYTDHours07] decimal NOT NULL, + [ActualYTDHours08] decimal NOT NULL, + [ActualYTDHours09] decimal NOT NULL, + [ActualYTDHours10] decimal NOT NULL, + [ActualYTDHours11] decimal NOT NULL, + [ActualYTDHours12] decimal NOT NULL, + [ActualYTDHoursTotal] decimal NULL, + [PriorYearActualHours01] decimal NOT NULL, + [PriorYearActualHours02] decimal NOT NULL, + [PriorYearActualHours03] decimal NOT NULL, + [PriorYearActualHours04] decimal NOT NULL, + [PriorYearActualHours05] decimal NOT NULL, + [PriorYearActualHours06] decimal NOT NULL, + [PriorYearActualHours07] decimal NOT NULL, + [PriorYearActualHours08] decimal NOT NULL, + [PriorYearActualHours09] decimal NOT NULL, + [PriorYearActualHours10] decimal NOT NULL, + [PriorYearActualHours11] decimal NOT NULL, + [PriorYearActualHours12] decimal NOT NULL, + [PriorYearActualHoursTotal] decimal NULL, + [CurrentYearBudgetHours01] decimal NOT NULL, + [CurrentYearBudgetHours02] decimal NOT NULL, + [CurrentYearBudgetHours03] decimal NOT NULL, + [CurrentYearBudgetHours04] decimal NOT NULL, + [CurrentYearBudgetHours05] decimal NOT NULL, + [CurrentYearBudgetHours06] decimal NOT NULL, + [CurrentYearBudgetHours07] decimal NOT NULL, + [CurrentYearBudgetHours08] decimal NOT NULL, + [CurrentYearBudgetHours09] decimal NOT NULL, + [CurrentYearBudgetHours10] decimal NOT NULL, + [CurrentYearBudgetHours11] decimal NOT NULL, + [CurrentYearBudgetHours12] decimal NOT NULL, + [CurrentYearBudgetHoursTotal] decimal NULL, + [ActualYTDFTEs01] decimal NOT NULL, + [ActualYTDFTEs02] decimal NOT NULL, + [ActualYTDFTEs03] decimal NOT NULL, + [ActualYTDFTEs04] decimal NOT NULL, + [ActualYTDFTEs05] decimal NOT NULL, + [ActualYTDFTEs06] decimal NOT NULL, + [ActualYTDFTEs07] decimal NOT NULL, + [ActualYTDFTEs08] decimal NOT NULL, + [ActualYTDFTEs09] decimal NOT NULL, + [ActualYTDFTEs10] decimal NOT NULL, + [ActualYTDFTEs11] decimal NOT NULL, + [ActualYTDFTEs12] decimal NOT NULL, + [ActualYTDFTEsTotal] decimal NOT NULL, + [PriorYearActualFTEs01] decimal NOT NULL, + [PriorYearActualFTEs02] decimal NOT NULL, + [PriorYearActualFTEs03] decimal NOT NULL, + [PriorYearActualFTEs04] decimal NOT NULL, + [PriorYearActualFTEs05] decimal NOT NULL, + [PriorYearActualFTEs06] decimal NOT NULL, + [PriorYearActualFTEs07] decimal NOT NULL, + [PriorYearActualFTEs08] decimal NOT NULL, + [PriorYearActualFTEs09] decimal NOT NULL, + [PriorYearActualFTEs10] decimal NOT NULL, + [PriorYearActualFTEs11] decimal NOT NULL, + [PriorYearActualFTEs12] decimal NOT NULL, + [PriorYearActualFTEsTotal] decimal NOT NULL, + [CurrentYearBudgetFTEs01] decimal NOT NULL, + [CurrentYearBudgetFTEs02] decimal NOT NULL, + [CurrentYearBudgetFTEs03] decimal NOT NULL, + [CurrentYearBudgetFTEs04] decimal NOT NULL, + [CurrentYearBudgetFTEs05] decimal NOT NULL, + [CurrentYearBudgetFTEs06] decimal NOT NULL, + [CurrentYearBudgetFTEs07] decimal NOT NULL, + [CurrentYearBudgetFTEs08] decimal NOT NULL, + [CurrentYearBudgetFTEs09] decimal NOT NULL, + [CurrentYearBudgetFTEs10] decimal NOT NULL, + [CurrentYearBudgetFTEs11] decimal NOT NULL, + [CurrentYearBudgetFTEs12] decimal NOT NULL, + [CurrentYearBudgetFTEsTotal] decimal NOT NULL, + PRIMARY KEY ([StaffingID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[StaffingHistory] ([StaffingID]); +GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__000DEC03] DEFAULT ((0)) FOR [ActualYTDDollars12]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__0102103C] DEFAULT ((0)) FOR [PriorYearActualDollars01]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__01F63475] DEFAULT ((0)) FOR [PriorYearActualDollars02]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__02EA58AE] DEFAULT ((0)) FOR [PriorYearActualDollars03]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__03DE7CE7] DEFAULT ((0)) FOR [PriorYearActualDollars04]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__04D2A120] DEFAULT ((0)) FOR [PriorYearActualDollars05]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__05C6C559] DEFAULT ((0)) FOR [PriorYearActualDollars06]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__06BAE992] DEFAULT ((0)) FOR [PriorYearActualDollars07]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__07AF0DCB] DEFAULT ((0)) FOR [PriorYearActualDollars08]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__08A33204] DEFAULT ((0)) FOR [PriorYearActualDollars09]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__0997563D] DEFAULT ((0)) FOR [PriorYearActualDollars10]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__0A8B7A76] DEFAULT ((0)) FOR [PriorYearActualDollars11]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__0B7F9EAF] DEFAULT ((0)) FOR [PriorYearActualDollars12]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__0C73C2E8] DEFAULT ((0)) FOR [CurrentYearBudgetDollars01]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__0D67E721] DEFAULT ((0)) FOR [CurrentYearBudgetDollars02]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__0E5C0B5A] DEFAULT ((0)) FOR [CurrentYearBudgetDollars03]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__0F502F93] DEFAULT ((0)) FOR [CurrentYearBudgetDollars04]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__104453CC] DEFAULT ((0)) FOR [CurrentYearBudgetDollars05]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__11387805] DEFAULT ((0)) FOR [CurrentYearBudgetDollars06]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__122C9C3E] DEFAULT ((0)) FOR [CurrentYearBudgetDollars07]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__1320C077] DEFAULT ((0)) FOR [CurrentYearBudgetDollars08]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__1414E4B0] DEFAULT ((0)) FOR [CurrentYearBudgetDollars09]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__150908E9] DEFAULT ((0)) FOR [CurrentYearBudgetDollars10]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__15FD2D22] DEFAULT ((0)) FOR [CurrentYearBudgetDollars11]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__16F1515B] DEFAULT ((0)) FOR [CurrentYearBudgetDollars12]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__17E57594] DEFAULT ((0)) FOR [ActualYTDHours01]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__18D999CD] DEFAULT ((0)) FOR [ActualYTDHours02]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__19CDBE06] DEFAULT ((0)) FOR [ActualYTDHours03]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__1AC1E23F] DEFAULT ((0)) FOR [ActualYTDHours04]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__1BB60678] DEFAULT ((0)) FOR [ActualYTDHours05]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__1CAA2AB1] DEFAULT ((0)) FOR [ActualYTDHours06]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__1D9E4EEA] DEFAULT ((0)) FOR [ActualYTDHours07]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__1E927323] DEFAULT ((0)) FOR [ActualYTDHours08]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__1F86975C] DEFAULT ((0)) FOR [ActualYTDHours09]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__207ABB95] DEFAULT ((0)) FOR [ActualYTDHours10]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__216EDFCE] DEFAULT ((0)) FOR [ActualYTDHours11]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__22630407] DEFAULT ((0)) FOR [ActualYTDHours12]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__23572840] DEFAULT ((0)) FOR [PriorYearActualHours01]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__244B4C79] DEFAULT ((0)) FOR [PriorYearActualHours02]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__253F70B2] DEFAULT ((0)) FOR [PriorYearActualHours03]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__263394EB] DEFAULT ((0)) FOR [PriorYearActualHours04]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__2727B924] DEFAULT ((0)) FOR [PriorYearActualHours05]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__281BDD5D] DEFAULT ((0)) FOR [PriorYearActualHours06]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__29100196] DEFAULT ((0)) FOR [PriorYearActualHours07]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__2A0425CF] DEFAULT ((0)) FOR [PriorYearActualHours08]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__2AF84A08] DEFAULT ((0)) FOR [PriorYearActualHours09]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__2BEC6E41] DEFAULT ((0)) FOR [PriorYearActualHours10]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__2CE0927A] DEFAULT ((0)) FOR [PriorYearActualHours11]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__2DD4B6B3] DEFAULT ((0)) FOR [PriorYearActualHours12]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__2EC8DAEC] DEFAULT ((0)) FOR [CurrentYearBudgetHours01]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__2FBCFF25] DEFAULT ((0)) FOR [CurrentYearBudgetHours02]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__30B1235E] DEFAULT ((0)) FOR [CurrentYearBudgetHours03]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__31A54797] DEFAULT ((0)) FOR [CurrentYearBudgetHours04]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__32996BD0] DEFAULT ((0)) FOR [CurrentYearBudgetHours05]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__338D9009] DEFAULT ((0)) FOR [CurrentYearBudgetHours06]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__3481B442] DEFAULT ((0)) FOR [CurrentYearBudgetHours07]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__3575D87B] DEFAULT ((0)) FOR [CurrentYearBudgetHours08]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__3669FCB4] DEFAULT ((0)) FOR [CurrentYearBudgetHours09]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__375E20ED] DEFAULT ((0)) FOR [CurrentYearBudgetHours10]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__38524526] DEFAULT ((0)) FOR [CurrentYearBudgetHours11]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__3946695F] DEFAULT ((0)) FOR [CurrentYearBudgetHours12]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__3A3A8D98] DEFAULT ((0)) FOR [ActualYTDFTEs01]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__3B2EB1D1] DEFAULT ((0)) FOR [ActualYTDFTEs02]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__3C22D60A] DEFAULT ((0)) FOR [ActualYTDFTEs03]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__3D16FA43] DEFAULT ((0)) FOR [ActualYTDFTEs04]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__3E0B1E7C] DEFAULT ((0)) FOR [ActualYTDFTEs05]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__3EFF42B5] DEFAULT ((0)) FOR [ActualYTDFTEs06]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__3FF366EE] DEFAULT ((0)) FOR [ActualYTDFTEs07]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__40E78B27] DEFAULT ((0)) FOR [ActualYTDFTEs08]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__41DBAF60] DEFAULT ((0)) FOR [ActualYTDFTEs09]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__42CFD399] DEFAULT ((0)) FOR [ActualYTDFTEs10]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__43C3F7D2] DEFAULT ((0)) FOR [ActualYTDFTEs11]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__44B81C0B] DEFAULT ((0)) FOR [ActualYTDFTEs12]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__45AC4044] DEFAULT ((0)) FOR [ActualYTDFTEsTotal]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__46A0647D] DEFAULT ((0)) FOR [PriorYearActualFTEs01]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__479488B6] DEFAULT ((0)) FOR [PriorYearActualFTEs02]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__4888ACEF] DEFAULT ((0)) FOR [PriorYearActualFTEs03]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__497CD128] DEFAULT ((0)) FOR [PriorYearActualFTEs04]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__4A70F561] DEFAULT ((0)) FOR [PriorYearActualFTEs05]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__4B65199A] DEFAULT ((0)) FOR [PriorYearActualFTEs06]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__4C593DD3] DEFAULT ((0)) FOR [PriorYearActualFTEs07]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__4D4D620C] DEFAULT ((0)) FOR [PriorYearActualFTEs08]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__4E418645] DEFAULT ((0)) FOR [PriorYearActualFTEs09]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__4F35AA7E] DEFAULT ((0)) FOR [PriorYearActualFTEs10]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__5029CEB7] DEFAULT ((0)) FOR [PriorYearActualFTEs11]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__511DF2F0] DEFAULT ((0)) FOR [PriorYearActualFTEs12]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Prior__52121729] DEFAULT ((0)) FOR [PriorYearActualFTEsTotal]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__53063B62] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs01]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__53FA5F9B] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs02]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__54EE83D4] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs03]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__55E2A80D] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs04]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__56D6CC46] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs05]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__57CAF07F] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs06]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__58BF14B8] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs07]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__59B338F1] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs08]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__5AA75D2A] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs09]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__5B9B8163] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs10]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__5C8FA59C] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs11]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__5D83C9D5] DEFAULT ((0)) FOR [CurrentYearBudgetFTEs12]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Curre__5E77EE0E] DEFAULT ((0)) FOR [CurrentYearBudgetFTEsTotal]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Staff__749C3957] DEFAULT ((0)) FOR [StaffingID]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__75905D90] DEFAULT ((0)) FOR [ActualYTDDollars01]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__768481C9] DEFAULT ((0)) FOR [ActualYTDDollars02]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__7778A602] DEFAULT ((0)) FOR [ActualYTDDollars03]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__786CCA3B] DEFAULT ((0)) FOR [ActualYTDDollars04]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__7960EE74] DEFAULT ((0)) FOR [ActualYTDDollars05]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__7A5512AD] DEFAULT ((0)) FOR [ActualYTDDollars06]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__7B4936E6] DEFAULT ((0)) FOR [ActualYTDDollars07]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__7C3D5B1F] DEFAULT ((0)) FOR [ActualYTDDollars08]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__7D317F58] DEFAULT ((0)) FOR [ActualYTDDollars09]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__7E25A391] DEFAULT ((0)) FOR [ActualYTDDollars10]; GO +ALTER TABLE [fp].[StaffingHistory] ADD CONSTRAINT [DF__StaffingH__Actua__7F19C7CA] DEFAULT ((0)) FOR [ActualYTDDollars11]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingInitialPlanConfigDetail ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingInitialPlanConfigDetail] ( + [RowID] int NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [BudgetConfigID] smallint NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [ProductiveClassID] int NOT NULL, + [PayCodeGroupID] int NOT NULL, + [VariabilityID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [EmployeeID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL, + [ProjectionMethodID] int NOT NULL, + [TrailingMonths] tinyint NOT NULL, + [VersionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [FK__StaffingI__Budge__77ADB02C] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [FK__StaffingI__Versi__4C8F1354] FOREIGN KEY ([VersionID]) REFERENCES [fp].[InitialPlanRuleVersion] ([VersionID]); GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Versi__4B9AEF1B] DEFAULT ((0)) FOR [VersionID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Budge__686B6C9C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Budge__695F90D5] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Depar__6A53B50E] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__JobCo__6B47D947] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Produ__6C3BFD80] DEFAULT ((0)) FOR [ProductiveClassID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__PayCo__6D3021B9] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Varia__6E2445F2] DEFAULT ((0)) FOR [VariabilityID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__TimeC__6F186A2B] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__UnitT__700C8E64] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Emplo__7100B29D] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Provi__71F4D6D6] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Provi__72E8FB0F] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Provi__73DD1F48] DEFAULT ((0)) FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Provi__74D14381] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Proje__75C567BA] DEFAULT ((0)) FOR [ProjectionMethodID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetail] ADD CONSTRAINT [DF__StaffingI__Trail__76B98BF3] DEFAULT ((0)) FOR [TrailingMonths]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingInitialPlanConfigDetailHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ( + [RowID] int NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [BudgetConfigID] smallint NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [ProductiveClassID] int NOT NULL, + [PayCodeGroupID] int NOT NULL, + [VariabilityID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [EmployeeID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL, + [ProjectionMethodID] int NOT NULL, + [TrailingMonths] tinyint NOT NULL, + [VersionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [FK_Staffing_Budget_Config] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Budge__1F8762B3] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Budge__207B86EC] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Depar__216FAB25] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__JobCo__2263CF5E] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Produ__2357F397] DEFAULT ((0)) FOR [ProductiveClassID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__PayCo__244C17D0] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Varia__25403C09] DEFAULT ((0)) FOR [VariabilityID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__TimeC__26346042] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__UnitT__2728847B] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Emplo__281CA8B4] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Provi__2910CCED] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Provi__2A04F126] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Provi__2AF9155F] DEFAULT ((0)) FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Provi__2BED3998] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Proje__2CE15DD1] DEFAULT ((0)) FOR [ProjectionMethodID]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Trail__2DD5820A] DEFAULT ((0)) FOR [TrailingMonths]; GO +ALTER TABLE [fp].[StaffingInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__StaffingI__Versi__2EC9A643] DEFAULT ((0)) FOR [VersionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingManagerAdjustmentComment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingManagerAdjustmentComment] ( + [CommentGUID] uniqueidentifier NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [UnitTypeID] int NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [InitialValue] decimal NOT NULL, + [DeltaValue] decimal NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [TimeClassID] tinyint NOT NULL, + [EmployeeID] int NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + [DateModifiedUtc] datetime NOT NULL, + PRIMARY KEY ([CommentGUID]) +); +GO +ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__Autho__00006B3C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__Autho__00F48F75] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Emplo__07554406] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__DateC__35711471] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__DateM__366538AA] DEFAULT (getutcdate()) FOR [DateModifiedUtc]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__TimeC__4017F4BF] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__Comme__739A9457] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CommentGUID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__Adjus__748EB890] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__Budge__7582DCC9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__Depar__76770102] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__JobCo__776B253B] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__Fisca__7A4791E6] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__UnitT__7B3BB61F] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__Comme__7C2FDA58] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__Initi__7D23FE91] DEFAULT ((0)) FOR [InitialValue]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentComment] ADD CONSTRAINT [DF__PayrollMa__Delta__7E1822CA] DEFAULT ((0)) FOR [DeltaValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingManagerAdjustmentData ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingManagerAdjustmentData] ( + [RowID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeGroupID] int NOT NULL, + [ProductiveClassID] int NOT NULL, + [EntityID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [FiscalYearID] int NOT NULL, + [FiscalMonthID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Value] decimal NULL, + [EmployeeID] int NOT NULL, + [IsSetZero] bit NOT NULL, + [VariabilityID] int NOT NULL +); + +CREATE NONCLUSTERED INDEX [NCNU_AdjustmentGUID] ON [fp].[StaffingManagerAdjustmentData] ([AdjustmentGUID]) INCLUDE ([DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [FiscalYearID], [UnitTypeID], [FiscalMonthID], [EntityID], [Value], [TimeClassID], [EmployeeID]); +GO +ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Emplo__06611FCD] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [Default_PRManagerAdj_UT] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [Default_PRManagerAdj_TC] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Varia__421184E1] DEFAULT ((0)) FOR [VariabilityID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__PayrollMa__Adjus__66409939] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__PayrollMa__Depar__6734BD72] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__PayrollMa__JobCo__6828E1AB] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__PayrollMa__PayCo__691D05E4] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__PayrollMa__Produ__6A112A1D] DEFAULT ((0)) FOR [ProductiveClassID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__PayrollMa__Entit__6B054E56] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__PayrollMa__Fisca__6DE1BB01] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__PayrollMa__Fisca__6ED5DF3A] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__PayrollMa__Value__70BE27AC] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[StaffingManagerAdjustmentData] ADD CONSTRAINT [DF__StaffingM__IsSet__7BE6BEB6] DEFAULT ((0)) FOR [IsSetZero]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingManagerSetAdjustmentComment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingManagerSetAdjustmentComment] ( + [CommentID] int NOT NULL, + [AdjustmentID] int NOT NULL, + [DepartmentID] int NOT NULL, + [VariabilityID] int NOT NULL, + [JobCodeID] int NOT NULL, + [EmployeeID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [FiscalYearID] int NOT NULL, + [InitialValue] decimal NOT NULL, + [Value] decimal NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + [DateModifiedUtc] datetime NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [AdjustedLevelInfoJSON] nvarchar(max) NOT NULL, + [BudgetConfigID] smallint NOT NULL, + [TabVariabilityID] int NOT NULL, + PRIMARY KEY ([CommentID]) +); +GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentComment_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentComment_Employee] FOREIGN KEY ([EmployeeID]) REFERENCES [fw].[DimEmployee] ([EmployeeID]); GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentComment_JobCode] FOREIGN KEY ([JobCodeID]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentComment_TimeClass] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentComment_UnitType] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentComment_Variability] FOREIGN KEY ([VariabilityID]) REFERENCES [fw].[DimVariability] ([VariabilityID]); GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Emplo__00373DDE] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__TimeC__012B6217] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__UnitT__021F8650] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Fisca__0313AA89] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Initi__0407CEC2] DEFAULT ((0)) FOR [InitialValue]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Value__04FBF2FB] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Autho__05F01734] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Autho__06E43B6D] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__DateC__07D85FA6] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__DateM__08CC83DF] DEFAULT (getutcdate()) FOR [DateModifiedUtc]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Comme__09C0A818] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Adjus__0AB4CC51] DEFAULT ('') FOR [AdjustedLevelInfoJSON]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Budge__3B5803AC] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__TabVa__3C4C27E5] DEFAULT ((0)) FOR [TabVariabilityID]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Adjus__7B7288C1] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Depar__7D5AD133] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__Varia__7E4EF56C] DEFAULT ((0)) FOR [VariabilityID]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__StaffingM__JobCo__7F4319A5] DEFAULT ((0)) FOR [JobCodeID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingManagerSetAdjustmentData ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingManagerSetAdjustmentData] ( + [RowID] int NOT NULL, + [AdjustmentID] int NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeGroupID] int NOT NULL, + [ProductiveClassID] int NOT NULL, + [EntityID] int NOT NULL, + [EmployeeID] int NOT NULL, + [VariabilityID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [FiscalYearID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Value01] decimal NOT NULL, + [Value02] decimal NOT NULL, + [Value03] decimal NOT NULL, + [Value04] decimal NOT NULL, + [Value05] decimal NOT NULL, + [Value06] decimal NOT NULL, + [Value07] decimal NOT NULL, + [Value08] decimal NOT NULL, + [Value09] decimal NOT NULL, + [Value10] decimal NOT NULL, + [Value11] decimal NOT NULL, + [Value12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentData_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentData_Employee] FOREIGN KEY ([EmployeeID]) REFERENCES [fw].[DimEmployee] ([EmployeeID]); GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentData_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentData_JobCode] FOREIGN KEY ([JobCodeID]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentData_PayCodeGroup] FOREIGN KEY ([PayCodeGroupID]) REFERENCES [fw].[DimPayCodeGroup] ([PayCodeGroupID]); GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentData_ProductiveClass] FOREIGN KEY ([ProductiveClassID]) REFERENCES [fw].[DimProductiveClass] ([ProductiveClassID]); GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentData_UnitType] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [FK_StaffingManagerSetAdjustmentData_Variability] FOREIGN KEY ([VariabilityID]) REFERENCES [fw].[DimVariability] ([VariabilityID]); GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Adjus__4051C2F3] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Depar__4145E72C] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__JobCo__423A0B65] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__PayCo__432E2F9E] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Produ__442253D7] DEFAULT ((0)) FOR [ProductiveClassID]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Entit__45167810] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Emplo__460A9C49] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Varia__46FEC082] DEFAULT ((0)) FOR [VariabilityID]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__UnitT__47F2E4BB] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Fisca__48E708F4] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__TimeC__49DB2D2D] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__4ACF5166] DEFAULT ((0)) FOR [Value01]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__4BC3759F] DEFAULT ((0)) FOR [Value02]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__4CB799D8] DEFAULT ((0)) FOR [Value03]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__4DABBE11] DEFAULT ((0)) FOR [Value04]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__4E9FE24A] DEFAULT ((0)) FOR [Value05]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__4F940683] DEFAULT ((0)) FOR [Value06]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__50882ABC] DEFAULT ((0)) FOR [Value07]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__517C4EF5] DEFAULT ((0)) FOR [Value08]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__5270732E] DEFAULT ((0)) FOR [Value09]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__53649767] DEFAULT ((0)) FOR [Value10]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__5458BBA0] DEFAULT ((0)) FOR [Value11]; GO +ALTER TABLE [fp].[StaffingManagerSetAdjustmentData] ADD CONSTRAINT [DF__StaffingM__Value__554CDFD9] DEFAULT ((0)) FOR [Value12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingMixAdjustment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingMixAdjustment] ( + [RowID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [BudgetConfigID] smallint NOT NULL, + [AdjustmentFilterJSON] nvarchar(max) NOT NULL, + [Value] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_BudgetConfig] ON [fp].[StaffingMixAdjustment] ([BudgetConfigID]); +GO +ALTER TABLE [fp].[StaffingMixAdjustment] ADD CONSTRAINT [DF__StaffingM__Adjus__2E64EF86] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[StaffingMixAdjustment] ADD CONSTRAINT [DF__StaffingM__Budge__2F5913BF] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[StaffingMixAdjustment] ADD CONSTRAINT [DF__StaffingM__Adjus__304D37F8] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO +ALTER TABLE [fp].[StaffingMixAdjustment] ADD CONSTRAINT [DF__StaffingM__Value__31415C31] DEFAULT ((0)) FOR [Value]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingSpreadUnlockData ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingSpreadUnlockData] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeGroupID] int NOT NULL, + [ProductiveClassID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [Version] timestamp NOT NULL, + [Value01] decimal NOT NULL, + [Value02] decimal NOT NULL, + [Value03] decimal NOT NULL, + [Value04] decimal NOT NULL, + [Value05] decimal NOT NULL, + [Value06] decimal NOT NULL, + [Value07] decimal NOT NULL, + [Value08] decimal NOT NULL, + [Value09] decimal NOT NULL, + [Value10] decimal NOT NULL, + [Value11] decimal NOT NULL, + [Value12] decimal NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [EmployeeID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__IsRec__02BAAC1B] DEFAULT ((0)) FOR [IsRecordDeleted]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Emplo__056CFB94] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Budge__115218DE] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Entit__133A6150] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Depar__142E8589] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__JobCo__1522A9C2] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__PayCo__1616CDFB] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Produ__170AF234] DEFAULT ((0)) FOR [ProductiveClassID]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__UnitT__17FF166D] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__18F33AA6] DEFAULT ((0)) FOR [Value01]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__19E75EDF] DEFAULT ((0)) FOR [Value02]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__1ADB8318] DEFAULT ((0)) FOR [Value03]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__1BCFA751] DEFAULT ((0)) FOR [Value04]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__1CC3CB8A] DEFAULT ((0)) FOR [Value05]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__1DB7EFC3] DEFAULT ((0)) FOR [Value06]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__1EAC13FC] DEFAULT ((0)) FOR [Value07]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__1FA03835] DEFAULT ((0)) FOR [Value08]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__20945C6E] DEFAULT ((0)) FOR [Value09]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__218880A7] DEFAULT ((0)) FOR [Value10]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__227CA4E0] DEFAULT ((0)) FOR [Value11]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Value__2370C919] DEFAULT ((0)) FOR [Value12]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Provi__3468ACF6] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Provi__355CD12F] DEFAULT ((0)) FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Provi__3650F568] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [DF__StaffingS__Provi__374519A1] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO +ALTER TABLE [fp].[StaffingSpreadUnlockData] ADD CONSTRAINT [df_StaffingSpreadUnlockData_AdjustmentGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingSpreads ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingSpreads] ( + [BudgetConfigID] int NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeGroupID] int NOT NULL, + [IsInactive] bit NOT NULL, + [SpreadPercentage01] decimal NULL, + [SpreadPercentage02] decimal NULL, + [SpreadPercentage03] decimal NULL, + [SpreadPercentage04] decimal NULL, + [SpreadPercentage05] decimal NULL, + [SpreadPercentage06] decimal NULL, + [SpreadPercentage07] decimal NULL, + [SpreadPercentage08] decimal NULL, + [SpreadPercentage09] decimal NULL, + [SpreadPercentage10] decimal NULL, + [SpreadPercentage11] decimal NULL, + [SpreadPercentage12] decimal NULL, + [TotalImportedValue] decimal NULL, + [SpreadHistoryGUID] uniqueidentifier NOT NULL, + [GlobalSpreadID] int NOT NULL, + PRIMARY KEY ([BudgetConfigID], [DepartmentID], [JobCodeID], [PayCodeGroupID]) +); +GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [FK_FpStaffingSpreads_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [FK_FpStaffingSpreads_JobCode] FOREIGN KEY ([JobCodeID]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [FK_FpStaffingSpreads_PayCodeGroup] FOREIGN KEY ([PayCodeGroupID]) REFERENCES [fw].[DimPayCodeGroup] ([PayCodeGroupID]); GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [FK_StaffingSpreads_History] FOREIGN KEY ([SpreadHistoryGUID]) REFERENCES [fp].[SpreadHistory] ([SpreadHistoryGUID]); GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__00C6AB5A] DEFAULT ((0)) FOR [SpreadPercentage03]; GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__01BACF93] DEFAULT ((0)) FOR [SpreadPercentage04]; GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__02AEF3CC] DEFAULT ((0)) FOR [SpreadPercentage05]; GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__03A31805] DEFAULT ((0)) FOR [SpreadPercentage06]; GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__04973C3E] DEFAULT ((0)) FOR [SpreadPercentage07]; GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__058B6077] DEFAULT ((0)) FOR [SpreadPercentage08]; GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__067F84B0] DEFAULT ((0)) FOR [SpreadPercentage09]; GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__0773A8E9] DEFAULT ((0)) FOR [SpreadPercentage10]; GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__0867CD22] DEFAULT ((0)) FOR [SpreadPercentage11]; GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__095BF15B] DEFAULT ((0)) FOR [SpreadPercentage12]; GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Total__0A501594] DEFAULT ((0)) FOR [TotalImportedValue]; GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Globa__17CA0C43] DEFAULT ((1)) FOR [GlobalSpreadID]; GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [df_StaffingSpreads_SpreadHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SpreadHistoryGUID]; GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Budge__773D4120] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Depar__78316559] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__JobCo__7A19ADCB] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__PayCo__7C01F63D] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__IsIna__7DEA3EAF] DEFAULT ((0)) FOR [IsInactive]; GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__7EDE62E8] DEFAULT ((0)) FOR [SpreadPercentage01]; GO +ALTER TABLE [fp].[StaffingSpreads] ADD CONSTRAINT [DF__StaffingS__Sprea__7FD28721] DEFAULT ((0)) FOR [SpreadPercentage02]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingSpreadsChangeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingSpreadsChangeHistory] ( + [RowID] bigint NOT NULL, + [StaffingID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [SubsectionID] int NOT NULL, + [UnitTypeID] smallint NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + [OldValue01] decimal NOT NULL, + [OldValue02] decimal NOT NULL, + [OldValue03] decimal NOT NULL, + [OldValue04] decimal NOT NULL, + [OldValue05] decimal NOT NULL, + [OldValue06] decimal NOT NULL, + [OldValue07] decimal NOT NULL, + [OldValue08] decimal NOT NULL, + [OldValue09] decimal NOT NULL, + [OldValue10] decimal NOT NULL, + [OldValue11] decimal NOT NULL, + [OldValue12] decimal NOT NULL, + [NewValue01] decimal NOT NULL, + [NewValue02] decimal NOT NULL, + [NewValue03] decimal NOT NULL, + [NewValue04] decimal NOT NULL, + [NewValue05] decimal NOT NULL, + [NewValue06] decimal NOT NULL, + [NewValue07] decimal NOT NULL, + [NewValue08] decimal NOT NULL, + [NewValue09] decimal NOT NULL, + [NewValue10] decimal NOT NULL, + [NewValue11] decimal NOT NULL, + [NewValue12] decimal NOT NULL +); + +CREATE CLUSTERED INDEX [CORE_BudgetConfigID] ON [fp].[StaffingSpreadsChangeHistory] ([BudgetConfigID], [SubsectionID], [StaffingID], [UnitTypeID], [RowID]); +GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__Staff__3BEDCBE0] DEFAULT ((0)) FOR [StaffingID]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__Budge__3CE1F019] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__Subse__3DD61452] DEFAULT ((3)) FOR [SubsectionID]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__UnitT__3ECA388B] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__DateC__3FBE5CC4] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__40B280FD] DEFAULT ((0)) FOR [OldValue01]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__41A6A536] DEFAULT ((0)) FOR [OldValue02]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__429AC96F] DEFAULT ((0)) FOR [OldValue03]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__438EEDA8] DEFAULT ((0)) FOR [OldValue04]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__448311E1] DEFAULT ((0)) FOR [OldValue05]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__4577361A] DEFAULT ((0)) FOR [OldValue06]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__466B5A53] DEFAULT ((0)) FOR [OldValue07]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__475F7E8C] DEFAULT ((0)) FOR [OldValue08]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__4853A2C5] DEFAULT ((0)) FOR [OldValue09]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__4947C6FE] DEFAULT ((0)) FOR [OldValue10]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__4A3BEB37] DEFAULT ((0)) FOR [OldValue11]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__OldVa__4B300F70] DEFAULT ((0)) FOR [OldValue12]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__4C2433A9] DEFAULT ((0)) FOR [NewValue01]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__4D1857E2] DEFAULT ((0)) FOR [NewValue02]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__4E0C7C1B] DEFAULT ((0)) FOR [NewValue03]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__4F00A054] DEFAULT ((0)) FOR [NewValue04]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__4FF4C48D] DEFAULT ((0)) FOR [NewValue05]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__50E8E8C6] DEFAULT ((0)) FOR [NewValue06]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__51DD0CFF] DEFAULT ((0)) FOR [NewValue07]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__52D13138] DEFAULT ((0)) FOR [NewValue08]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__53C55571] DEFAULT ((0)) FOR [NewValue09]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__54B979AA] DEFAULT ((0)) FOR [NewValue10]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__55AD9DE3] DEFAULT ((0)) FOR [NewValue11]; GO +ALTER TABLE [fp].[StaffingSpreadsChangeHistory] ADD CONSTRAINT [DF__StaffingS__NewVa__56A1C21C] DEFAULT ((0)) FOR [NewValue12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingVariabilityOverrideConfig ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingVariabilityOverrideConfig] ( + [RowID] int NOT NULL, + [EntityGroupConfigGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [Variability] decimal NOT NULL, + PRIMARY KEY ([EntityGroupConfigGUID], [DepartmentID], [JobCodeID]) +); +GO +ALTER TABLE [fp].[StaffingVariabilityOverrideConfig] ADD CONSTRAINT [FK_StaffingVariabilityOverrideConfig_JobCode] FOREIGN KEY ([JobCodeID]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO +ALTER TABLE [fp].[StaffingVariabilityOverrideConfig] ADD CONSTRAINT [DF__StaffingV__Depar__35B27077] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StaffingVariabilityOverrideConfig] ADD CONSTRAINT [DF__StaffingV__JobCo__36A694B0] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fp].[StaffingVariabilityOverrideConfig] ADD CONSTRAINT [DF__StaffingV__Varia__379AB8E9] DEFAULT ((0)) FOR [Variability]; GO +ALTER TABLE [fp].[StaffingVariabilityOverrideConfig] ADD CONSTRAINT [df_StaffingVariabilityOverrideConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StaffingWageRate ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StaffingWageRate] ( + [StaffingWageRateID] int NOT NULL, + [BudgetWageRateLockType] tinyint NOT NULL, + [BudgetWageRateLockFlag] tinyint NOT NULL, + [TargetWageRateLockType] tinyint NOT NULL, + [TargetWageRateLockFlag] tinyint NOT NULL, + [ProjectionWageRateLockType] tinyint NOT NULL, + [ProjectionWageRateLockFlag] tinyint NOT NULL, + [SampledBudget01] decimal NOT NULL, + [SampledBudget02] decimal NOT NULL, + [SampledBudget03] decimal NOT NULL, + [SampledBudget04] decimal NOT NULL, + [SampledBudget05] decimal NOT NULL, + [SampledBudget06] decimal NOT NULL, + [SampledBudget07] decimal NOT NULL, + [SampledBudget08] decimal NOT NULL, + [SampledBudget09] decimal NOT NULL, + [SampledBudget10] decimal NOT NULL, + [SampledBudget11] decimal NOT NULL, + [SampledBudget12] decimal NOT NULL, + [SampledProjection01] decimal NOT NULL, + [SampledProjection02] decimal NOT NULL, + [SampledProjection03] decimal NOT NULL, + [SampledProjection04] decimal NOT NULL, + [SampledProjection05] decimal NOT NULL, + [SampledProjection06] decimal NOT NULL, + [SampledProjection07] decimal NOT NULL, + [SampledProjection08] decimal NOT NULL, + [SampledProjection09] decimal NOT NULL, + [SampledProjection10] decimal NOT NULL, + [SampledProjection11] decimal NOT NULL, + [SampledProjection12] decimal NOT NULL, + [InitialBudget01] decimal NOT NULL, + [InitialBudget02] decimal NOT NULL, + [InitialBudget03] decimal NOT NULL, + [InitialBudget04] decimal NOT NULL, + [InitialBudget05] decimal NOT NULL, + [InitialBudget06] decimal NOT NULL, + [InitialBudget07] decimal NOT NULL, + [InitialBudget08] decimal NOT NULL, + [InitialBudget09] decimal NOT NULL, + [InitialBudget10] decimal NOT NULL, + [InitialBudget11] decimal NOT NULL, + [InitialBudget12] decimal NOT NULL, + [InitialProjection01] decimal NOT NULL, + [InitialProjection02] decimal NOT NULL, + [InitialProjection03] decimal NOT NULL, + [InitialProjection04] decimal NOT NULL, + [InitialProjection05] decimal NOT NULL, + [InitialProjection06] decimal NOT NULL, + [InitialProjection07] decimal NOT NULL, + [InitialProjection08] decimal NOT NULL, + [InitialProjection09] decimal NOT NULL, + [InitialProjection10] decimal NOT NULL, + [InitialProjection11] decimal NOT NULL, + [InitialProjection12] decimal NOT NULL, + [TargetAdjusted01] decimal NOT NULL, + [TargetAdjusted02] decimal NOT NULL, + [TargetAdjusted03] decimal NOT NULL, + [TargetAdjusted04] decimal NOT NULL, + [TargetAdjusted05] decimal NOT NULL, + [TargetAdjusted06] decimal NOT NULL, + [TargetAdjusted07] decimal NOT NULL, + [TargetAdjusted08] decimal NOT NULL, + [TargetAdjusted09] decimal NOT NULL, + [TargetAdjusted10] decimal NOT NULL, + [TargetAdjusted11] decimal NOT NULL, + [TargetAdjusted12] decimal NOT NULL, + [BudgetAdjusted01] decimal NOT NULL, + [BudgetAdjusted02] decimal NOT NULL, + [BudgetAdjusted03] decimal NOT NULL, + [BudgetAdjusted04] decimal NOT NULL, + [BudgetAdjusted05] decimal NOT NULL, + [BudgetAdjusted06] decimal NOT NULL, + [BudgetAdjusted07] decimal NOT NULL, + [BudgetAdjusted08] decimal NOT NULL, + [BudgetAdjusted09] decimal NOT NULL, + [BudgetAdjusted10] decimal NOT NULL, + [BudgetAdjusted11] decimal NOT NULL, + [BudgetAdjusted12] decimal NOT NULL, + [ProjectionAdjusted01] decimal NOT NULL, + [ProjectionAdjusted02] decimal NOT NULL, + [ProjectionAdjusted03] decimal NOT NULL, + [ProjectionAdjusted04] decimal NOT NULL, + [ProjectionAdjusted05] decimal NOT NULL, + [ProjectionAdjusted06] decimal NOT NULL, + [ProjectionAdjusted07] decimal NOT NULL, + [ProjectionAdjusted08] decimal NOT NULL, + [ProjectionAdjusted09] decimal NOT NULL, + [ProjectionAdjusted10] decimal NOT NULL, + [ProjectionAdjusted11] decimal NOT NULL, + [ProjectionAdjusted12] decimal NOT NULL, + [TargetPercentAdjustmentFactor01] decimal NOT NULL, + [TargetPercentAdjustmentFactor02] decimal NOT NULL, + [TargetPercentAdjustmentFactor03] decimal NOT NULL, + [TargetPercentAdjustmentFactor04] decimal NOT NULL, + [TargetPercentAdjustmentFactor05] decimal NOT NULL, + [TargetPercentAdjustmentFactor06] decimal NOT NULL, + [TargetPercentAdjustmentFactor07] decimal NOT NULL, + [TargetPercentAdjustmentFactor08] decimal NOT NULL, + [TargetPercentAdjustmentFactor09] decimal NOT NULL, + [TargetPercentAdjustmentFactor10] decimal NOT NULL, + [TargetPercentAdjustmentFactor11] decimal NOT NULL, + [TargetPercentAdjustmentFactor12] decimal NOT NULL, + [BudgetPercentAdjustmentFactor01] decimal NOT NULL, + [BudgetPercentAdjustmentFactor02] decimal NOT NULL, + [BudgetPercentAdjustmentFactor03] decimal NOT NULL, + [BudgetPercentAdjustmentFactor04] decimal NOT NULL, + [BudgetPercentAdjustmentFactor05] decimal NOT NULL, + [BudgetPercentAdjustmentFactor06] decimal NOT NULL, + [BudgetPercentAdjustmentFactor07] decimal NOT NULL, + [BudgetPercentAdjustmentFactor08] decimal NOT NULL, + [BudgetPercentAdjustmentFactor09] decimal NOT NULL, + [BudgetPercentAdjustmentFactor10] decimal NOT NULL, + [BudgetPercentAdjustmentFactor11] decimal NOT NULL, + [BudgetPercentAdjustmentFactor12] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor01] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor02] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor03] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor04] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor05] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor06] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor07] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor08] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor09] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor10] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor11] decimal NOT NULL, + [ProjectionPercentAdjustmentFactor12] decimal NOT NULL, + PRIMARY KEY ([StaffingWageRateID]) +); +GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__15BD3600] DEFAULT ((0)) FOR [BudgetWageRateLockType]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__16B15A39] DEFAULT ((0)) FOR [BudgetWageRateLockFlag]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__17A57E72] DEFAULT ((0)) FOR [TargetWageRateLockType]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__1899A2AB] DEFAULT ((0)) FOR [TargetWageRateLockFlag]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__198DC6E4] DEFAULT ((0)) FOR [ProjectionWageRateLockType]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__1A81EB1D] DEFAULT ((0)) FOR [ProjectionWageRateLockFlag]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__1B760F56] DEFAULT ((0)) FOR [SampledBudget01]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__1C6A338F] DEFAULT ((0)) FOR [SampledBudget02]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__1D5E57C8] DEFAULT ((0)) FOR [SampledBudget03]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__1E527C01] DEFAULT ((0)) FOR [SampledBudget04]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__1F46A03A] DEFAULT ((0)) FOR [SampledBudget05]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__203AC473] DEFAULT ((0)) FOR [SampledBudget06]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__212EE8AC] DEFAULT ((0)) FOR [SampledBudget07]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__22230CE5] DEFAULT ((0)) FOR [SampledBudget08]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__2317311E] DEFAULT ((0)) FOR [SampledBudget09]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__240B5557] DEFAULT ((0)) FOR [SampledBudget10]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__24FF7990] DEFAULT ((0)) FOR [SampledBudget11]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__25F39DC9] DEFAULT ((0)) FOR [SampledBudget12]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__26E7C202] DEFAULT ((0)) FOR [SampledProjection01]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__27DBE63B] DEFAULT ((0)) FOR [SampledProjection02]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__28D00A74] DEFAULT ((0)) FOR [SampledProjection03]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__29C42EAD] DEFAULT ((0)) FOR [SampledProjection04]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__2AB852E6] DEFAULT ((0)) FOR [SampledProjection05]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__2BAC771F] DEFAULT ((0)) FOR [SampledProjection06]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__2CA09B58] DEFAULT ((0)) FOR [SampledProjection07]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__2D94BF91] DEFAULT ((0)) FOR [SampledProjection08]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__2E88E3CA] DEFAULT ((0)) FOR [SampledProjection09]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__2F7D0803] DEFAULT ((0)) FOR [SampledProjection10]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__30712C3C] DEFAULT ((0)) FOR [SampledProjection11]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Sampl__31655075] DEFAULT ((0)) FOR [SampledProjection12]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__325974AE] DEFAULT ((0)) FOR [InitialBudget01]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__334D98E7] DEFAULT ((0)) FOR [InitialBudget02]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__3441BD20] DEFAULT ((0)) FOR [InitialBudget03]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__3535E159] DEFAULT ((0)) FOR [InitialBudget04]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__362A0592] DEFAULT ((0)) FOR [InitialBudget05]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__371E29CB] DEFAULT ((0)) FOR [InitialBudget06]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor01] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__38124E04] DEFAULT ((0)) FOR [InitialBudget07]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor02] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__3906723D] DEFAULT ((0)) FOR [InitialBudget08]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor03] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__39FA9676] DEFAULT ((0)) FOR [InitialBudget09]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor04] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__3AEEBAAF] DEFAULT ((0)) FOR [InitialBudget10]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor05] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__3BE2DEE8] DEFAULT ((0)) FOR [InitialBudget11]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor06] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__3CD70321] DEFAULT ((0)) FOR [InitialBudget12]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor07] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__3DCB275A] DEFAULT ((0)) FOR [InitialProjection01]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor08] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor08]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__3EBF4B93] DEFAULT ((0)) FOR [InitialProjection02]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor09] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__3FB36FCC] DEFAULT ((0)) FOR [InitialProjection03]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor10] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__40A79405] DEFAULT ((0)) FOR [InitialProjection04]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor11] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__419BB83E] DEFAULT ((0)) FOR [InitialProjection05]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_TargetPercentAdjustmentFactor12] DEFAULT ((1)) FOR [TargetPercentAdjustmentFactor12]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__428FDC77] DEFAULT ((0)) FOR [InitialProjection06]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor01] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__438400B0] DEFAULT ((0)) FOR [InitialProjection07]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor02] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__447824E9] DEFAULT ((0)) FOR [InitialProjection08]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor03] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__456C4922] DEFAULT ((0)) FOR [InitialProjection09]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor04] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__46606D5B] DEFAULT ((0)) FOR [InitialProjection10]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor05] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__47549194] DEFAULT ((0)) FOR [InitialProjection11]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor06] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Initi__4848B5CD] DEFAULT ((0)) FOR [InitialProjection12]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor07] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__493CDA06] DEFAULT ((0)) FOR [TargetAdjusted01]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor08] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor08]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__4A30FE3F] DEFAULT ((0)) FOR [TargetAdjusted02]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor09] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__4B252278] DEFAULT ((0)) FOR [TargetAdjusted03]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor10] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__4C1946B1] DEFAULT ((0)) FOR [TargetAdjusted04]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor11] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__4D0D6AEA] DEFAULT ((0)) FOR [TargetAdjusted05]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_BudgetPercentAdjustmentFactor12] DEFAULT ((1)) FOR [BudgetPercentAdjustmentFactor12]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__4E018F23] DEFAULT ((0)) FOR [TargetAdjusted06]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor01] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor01]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__4EF5B35C] DEFAULT ((0)) FOR [TargetAdjusted07]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor02] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor02]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__4FE9D795] DEFAULT ((0)) FOR [TargetAdjusted08]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor03] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor03]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__50DDFBCE] DEFAULT ((0)) FOR [TargetAdjusted09]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor04] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor04]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__51D22007] DEFAULT ((0)) FOR [TargetAdjusted10]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor05] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor05]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__52C64440] DEFAULT ((0)) FOR [TargetAdjusted11]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor06] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor06]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Targe__53BA6879] DEFAULT ((0)) FOR [TargetAdjusted12]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor07] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor07]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__54AE8CB2] DEFAULT ((0)) FOR [BudgetAdjusted01]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor08] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor08]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__55A2B0EB] DEFAULT ((0)) FOR [BudgetAdjusted02]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor09] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor09]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__5696D524] DEFAULT ((0)) FOR [BudgetAdjusted03]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor10] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor10]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__578AF95D] DEFAULT ((0)) FOR [BudgetAdjusted04]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor11] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor11]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__587F1D96] DEFAULT ((0)) FOR [BudgetAdjusted05]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [df_ProjectionPercentAdjustmentFactor12] DEFAULT ((1)) FOR [ProjectionPercentAdjustmentFactor12]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__597341CF] DEFAULT ((0)) FOR [BudgetAdjusted06]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__5A676608] DEFAULT ((0)) FOR [BudgetAdjusted07]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__5B5B8A41] DEFAULT ((0)) FOR [BudgetAdjusted08]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__5C4FAE7A] DEFAULT ((0)) FOR [BudgetAdjusted09]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__5D43D2B3] DEFAULT ((0)) FOR [BudgetAdjusted10]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__5E37F6EC] DEFAULT ((0)) FOR [BudgetAdjusted11]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Budge__5F2C1B25] DEFAULT ((0)) FOR [BudgetAdjusted12]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__60203F5E] DEFAULT ((0)) FOR [ProjectionAdjusted01]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__61146397] DEFAULT ((0)) FOR [ProjectionAdjusted02]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__620887D0] DEFAULT ((0)) FOR [ProjectionAdjusted03]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__62FCAC09] DEFAULT ((0)) FOR [ProjectionAdjusted04]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__63F0D042] DEFAULT ((0)) FOR [ProjectionAdjusted05]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__64E4F47B] DEFAULT ((0)) FOR [ProjectionAdjusted06]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__65D918B4] DEFAULT ((0)) FOR [ProjectionAdjusted07]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__66CD3CED] DEFAULT ((0)) FOR [ProjectionAdjusted08]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__67C16126] DEFAULT ((0)) FOR [ProjectionAdjusted09]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__68B5855F] DEFAULT ((0)) FOR [ProjectionAdjusted10]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__69A9A998] DEFAULT ((0)) FOR [ProjectionAdjusted11]; GO +ALTER TABLE [fp].[StaffingWageRate] ADD CONSTRAINT [DF__StaffingW__Proje__6A9DCDD1] DEFAULT ((0)) FOR [ProjectionAdjusted12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StatisticAddProviderAdjustment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StatisticAddProviderAdjustment] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [PayorID] int NOT NULL, + [PatientClassID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [SubsectionID] int NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [Value01] decimal NOT NULL, + [Value02] decimal NOT NULL, + [Value03] decimal NOT NULL, + [Value04] decimal NOT NULL, + [Value05] decimal NOT NULL, + [Value06] decimal NOT NULL, + [Value07] decimal NOT NULL, + [Value08] decimal NOT NULL, + [Value09] decimal NOT NULL, + [Value10] decimal NOT NULL, + [Value11] decimal NOT NULL, + [Value12] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [FK_FpStatisticAddProviderAdjustment_AdjustmentGuid] FOREIGN KEY ([AdjustmentGUID]) REFERENCES [fp].[StatisticsAdjustment] ([AdjustmentGUID]); GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Finan__009FBB84] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Payor__0193DFBD] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Patie__028803F6] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Provi__037C282F] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Provi__04704C68] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Provi__056470A1] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Provi__065894DA] DEFAULT ((0)) FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__TimeC__074CB913] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Budge__0840DD4C] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Subse__09350185] DEFAULT ((0)) FOR [SubsectionID]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__IsRec__0A2925BE] DEFAULT ((0)) FOR [IsRecordDeleted]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__0B1D49F7] DEFAULT ((0)) FOR [Value01]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__0C116E30] DEFAULT ((0)) FOR [Value02]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__0D059269] DEFAULT ((0)) FOR [Value03]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__0DF9B6A2] DEFAULT ((0)) FOR [Value04]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__0EEDDADB] DEFAULT ((0)) FOR [Value05]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__0FE1FF14] DEFAULT ((0)) FOR [Value06]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__10D6234D] DEFAULT ((0)) FOR [Value07]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__11CA4786] DEFAULT ((0)) FOR [Value08]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__12BE6BBF] DEFAULT ((0)) FOR [Value09]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__13B28FF8] DEFAULT ((0)) FOR [Value10]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__14A6B431] DEFAULT ((0)) FOR [Value11]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Value__159AD86A] DEFAULT ((0)) FOR [Value12]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Budge__7BDB0667] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Adjus__7CCF2AA0] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Entit__7DC34ED9] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Depar__7EB77312] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StatisticAddProviderAdjustment] ADD CONSTRAINT [DF__Statistic__Accou__7FAB974B] DEFAULT ((0)) FOR [AccountID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StatisticAddProviderSummary ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StatisticAddProviderSummary] ( + [SummaryID] int NOT NULL, + [DriverAdjustmentGUID] uniqueidentifier NOT NULL, + [DependentAdjustmentGUID] uniqueidentifier NOT NULL, + [EmployeeType] int NOT NULL, + [EmployeeID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [SpecialtyID] int NOT NULL, + [StartDate] datetime2 NOT NULL, + [BenchmarkProvidersJSON] varchar(1000) NOT NULL, + [Comment] varchar(1000) NOT NULL, + [ClassificationGroupID] int NOT NULL, + [ClassificationCategoryID] int NOT NULL, + [StaffingAdjustmentGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([SummaryID]) +); +GO +ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [FK_FP_StatAddProviderSummary_DriverAdjustmentGUID] FOREIGN KEY ([DriverAdjustmentGUID]) REFERENCES [fp].[StatisticsAdjustment] ([AdjustmentGUID]); GO +ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [FK_FP_StatAddProviderSummary_EmployeeID] FOREIGN KEY ([EmployeeID]) REFERENCES [fw].[DimEmployee] ([EmployeeID]); GO +ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [FK_FP_StatAddProviderSummary_ProviderID] FOREIGN KEY ([ProviderID]) REFERENCES [dss].[DimPhysician] ([PhysicianID]); GO +ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Staff__0CA73664] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [StaffingAdjustmentGUID]; GO +ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Drive__713E47BA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DriverAdjustmentGUID]; GO +ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Depen__72326BF3] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [DependentAdjustmentGUID]; GO +ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Emplo__7326902C] DEFAULT ((0)) FOR [EmployeeType]; GO +ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Emplo__741AB465] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Provi__750ED89E] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Provi__7602FCD7] DEFAULT ((0)) FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Speci__76F72110] DEFAULT ((0)) FOR [SpecialtyID]; GO +ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Start__77EB4549] DEFAULT (getdate()) FOR [StartDate]; GO +ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Bench__78DF6982] DEFAULT ('') FOR [BenchmarkProvidersJSON]; GO +ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Comme__79D38DBB] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Class__7AC7B1F4] DEFAULT ((0)) FOR [ClassificationGroupID]; GO +ALTER TABLE [fp].[StatisticAddProviderSummary] ADD CONSTRAINT [DF__Statistic__Class__7BBBD62D] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StatisticAddProviderSummaryDetails ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StatisticAddProviderSummaryDetails] ( + [RowID] int NOT NULL, + [SummaryID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ProjectionImpact] decimal NOT NULL, + [BudgetImpact] decimal NOT NULL, + [TargetImpact] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[StatisticAddProviderSummaryDetails] ADD CONSTRAINT [FK_FP_StatisticAddProviderSummaryDetails_SummaryID] FOREIGN KEY ([SummaryID]) REFERENCES [fp].[StatisticAddProviderSummary] ([SummaryID]); GO +ALTER TABLE [fp].[StatisticAddProviderSummaryDetails] ADD CONSTRAINT [DF__Statistic__Summa__0174AF83] DEFAULT ((0)) FOR [SummaryID]; GO +ALTER TABLE [fp].[StatisticAddProviderSummaryDetails] ADD CONSTRAINT [DF__Statistic__Provi__0268D3BC] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[StatisticAddProviderSummaryDetails] ADD CONSTRAINT [DF__Statistic__Depar__035CF7F5] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StatisticAddProviderSummaryDetails] ADD CONSTRAINT [DF__Statistic__Proje__04511C2E] DEFAULT ((0)) FOR [ProjectionImpact]; GO +ALTER TABLE [fp].[StatisticAddProviderSummaryDetails] ADD CONSTRAINT [DF__Statistic__Budge__05454067] DEFAULT ((0)) FOR [BudgetImpact]; GO +ALTER TABLE [fp].[StatisticAddProviderSummaryDetails] ADD CONSTRAINT [DF_StatisticAddProviderSummaryDetails_TargetImpact] DEFAULT ((0)) FOR [TargetImpact]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.Statistics ------------------ +--------------------------------------------- +CREATE TABLE [fp].[Statistics] ( + [StatisticsID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityGroupConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [PayorID] int NOT NULL, + [PatientClassID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [AddDate] datetime NOT NULL, + [IsNew] bit NOT NULL, + [SubsectionID] int NOT NULL, + [BudgetLockType] tinyint NOT NULL, + [BudgetLockFlag] tinyint NOT NULL, + [TargetLockType] tinyint NOT NULL, + [TargetLockFlag] tinyint NOT NULL, + [ProjectionLockType] tinyint NOT NULL, + [ProjectionLockFlag] tinyint NOT NULL, + [SampledBudgetTotal] decimal NOT NULL, + [SampledProjectionTotal] decimal NOT NULL, + [InitialBudgetTotal] decimal NOT NULL, + [InitialProjectionTotal] decimal NOT NULL, + [BudgetAdjustedTotal] decimal NOT NULL, + [TargetAdjustedTotal] decimal NOT NULL, + [ProjectionAdjustedTotal] decimal NOT NULL, + [SampledBudget01] decimal NOT NULL, + [SampledBudget02] decimal NOT NULL, + [SampledBudget03] decimal NOT NULL, + [SampledBudget04] decimal NOT NULL, + [SampledBudget05] decimal NOT NULL, + [SampledBudget06] decimal NOT NULL, + [SampledBudget07] decimal NOT NULL, + [SampledBudget08] decimal NOT NULL, + [SampledBudget09] decimal NOT NULL, + [SampledBudget10] decimal NOT NULL, + [SampledBudget11] decimal NOT NULL, + [SampledBudget12] decimal NOT NULL, + [SampledProjection01] decimal NOT NULL, + [SampledProjection02] decimal NOT NULL, + [SampledProjection03] decimal NOT NULL, + [SampledProjection04] decimal NOT NULL, + [SampledProjection05] decimal NOT NULL, + [SampledProjection06] decimal NOT NULL, + [SampledProjection07] decimal NOT NULL, + [SampledProjection08] decimal NOT NULL, + [SampledProjection09] decimal NOT NULL, + [SampledProjection10] decimal NOT NULL, + [SampledProjection11] decimal NOT NULL, + [SampledProjection12] decimal NOT NULL, + [InitialBudget01] decimal NOT NULL, + [InitialBudget02] decimal NOT NULL, + [InitialBudget03] decimal NOT NULL, + [InitialBudget04] decimal NOT NULL, + [InitialBudget05] decimal NOT NULL, + [InitialBudget06] decimal NOT NULL, + [InitialBudget07] decimal NOT NULL, + [InitialBudget08] decimal NOT NULL, + [InitialBudget09] decimal NOT NULL, + [InitialBudget10] decimal NOT NULL, + [InitialBudget11] decimal NOT NULL, + [InitialBudget12] decimal NOT NULL, + [InitialProjection01] decimal NOT NULL, + [InitialProjection02] decimal NOT NULL, + [InitialProjection03] decimal NOT NULL, + [InitialProjection04] decimal NOT NULL, + [InitialProjection05] decimal NOT NULL, + [InitialProjection06] decimal NOT NULL, + [InitialProjection07] decimal NOT NULL, + [InitialProjection08] decimal NOT NULL, + [InitialProjection09] decimal NOT NULL, + [InitialProjection10] decimal NOT NULL, + [InitialProjection11] decimal NOT NULL, + [InitialProjection12] decimal NOT NULL, + [InitialBudgetRate01] decimal NOT NULL, + [InitialBudgetRate02] decimal NOT NULL, + [InitialBudgetRate03] decimal NOT NULL, + [InitialBudgetRate04] decimal NOT NULL, + [InitialBudgetRate05] decimal NOT NULL, + [InitialBudgetRate06] decimal NOT NULL, + [InitialBudgetRate07] decimal NOT NULL, + [InitialBudgetRate08] decimal NOT NULL, + [InitialBudgetRate09] decimal NOT NULL, + [InitialBudgetRate10] decimal NOT NULL, + [InitialBudgetRate11] decimal NOT NULL, + [InitialBudgetRate12] decimal NOT NULL, + [InitialProjectionRate01] decimal NOT NULL, + [InitialProjectionRate02] decimal NOT NULL, + [InitialProjectionRate03] decimal NOT NULL, + [InitialProjectionRate04] decimal NOT NULL, + [InitialProjectionRate05] decimal NOT NULL, + [InitialProjectionRate06] decimal NOT NULL, + [InitialProjectionRate07] decimal NOT NULL, + [InitialProjectionRate08] decimal NOT NULL, + [InitialProjectionRate09] decimal NOT NULL, + [InitialProjectionRate10] decimal NOT NULL, + [InitialProjectionRate11] decimal NOT NULL, + [InitialProjectionRate12] decimal NOT NULL, + [BudgetAdjusted01] decimal NOT NULL, + [BudgetAdjusted02] decimal NOT NULL, + [BudgetAdjusted03] decimal NOT NULL, + [BudgetAdjusted04] decimal NOT NULL, + [BudgetAdjusted05] decimal NOT NULL, + [BudgetAdjusted06] decimal NOT NULL, + [BudgetAdjusted07] decimal NOT NULL, + [BudgetAdjusted08] decimal NOT NULL, + [BudgetAdjusted09] decimal NOT NULL, + [BudgetAdjusted10] decimal NOT NULL, + [BudgetAdjusted11] decimal NOT NULL, + [BudgetAdjusted12] decimal NOT NULL, + [TargetAdjusted01] decimal NOT NULL, + [TargetAdjusted02] decimal NOT NULL, + [TargetAdjusted03] decimal NOT NULL, + [TargetAdjusted04] decimal NOT NULL, + [TargetAdjusted05] decimal NOT NULL, + [TargetAdjusted06] decimal NOT NULL, + [TargetAdjusted07] decimal NOT NULL, + [TargetAdjusted08] decimal NOT NULL, + [TargetAdjusted09] decimal NOT NULL, + [TargetAdjusted10] decimal NOT NULL, + [TargetAdjusted11] decimal NOT NULL, + [TargetAdjusted12] decimal NOT NULL, + [BudgetRateAdjusted01] decimal NOT NULL, + [BudgetRateAdjusted02] decimal NOT NULL, + [BudgetRateAdjusted03] decimal NOT NULL, + [BudgetRateAdjusted04] decimal NOT NULL, + [BudgetRateAdjusted05] decimal NOT NULL, + [BudgetRateAdjusted06] decimal NOT NULL, + [BudgetRateAdjusted07] decimal NOT NULL, + [BudgetRateAdjusted08] decimal NOT NULL, + [BudgetRateAdjusted09] decimal NOT NULL, + [BudgetRateAdjusted10] decimal NOT NULL, + [BudgetRateAdjusted11] decimal NOT NULL, + [BudgetRateAdjusted12] decimal NOT NULL, + [TargetRateAdjusted01] decimal NOT NULL, + [TargetRateAdjusted02] decimal NOT NULL, + [TargetRateAdjusted03] decimal NOT NULL, + [TargetRateAdjusted04] decimal NOT NULL, + [TargetRateAdjusted05] decimal NOT NULL, + [TargetRateAdjusted06] decimal NOT NULL, + [TargetRateAdjusted07] decimal NOT NULL, + [TargetRateAdjusted08] decimal NOT NULL, + [TargetRateAdjusted09] decimal NOT NULL, + [TargetRateAdjusted10] decimal NOT NULL, + [TargetRateAdjusted11] decimal NOT NULL, + [TargetRateAdjusted12] decimal NOT NULL, + [ProjectionAdjusted01] decimal NOT NULL, + [ProjectionAdjusted02] decimal NOT NULL, + [ProjectionAdjusted03] decimal NOT NULL, + [ProjectionAdjusted04] decimal NOT NULL, + [ProjectionAdjusted05] decimal NOT NULL, + [ProjectionAdjusted06] decimal NOT NULL, + [ProjectionAdjusted07] decimal NOT NULL, + [ProjectionAdjusted08] decimal NOT NULL, + [ProjectionAdjusted09] decimal NOT NULL, + [ProjectionAdjusted10] decimal NOT NULL, + [ProjectionAdjusted11] decimal NOT NULL, + [ProjectionAdjusted12] decimal NOT NULL, + [ProjectionRateAdjusted01] decimal NOT NULL, + [ProjectionRateAdjusted02] decimal NOT NULL, + [ProjectionRateAdjusted03] decimal NOT NULL, + [ProjectionRateAdjusted04] decimal NOT NULL, + [ProjectionRateAdjusted05] decimal NOT NULL, + [ProjectionRateAdjusted06] decimal NOT NULL, + [ProjectionRateAdjusted07] decimal NOT NULL, + [ProjectionRateAdjusted08] decimal NOT NULL, + [ProjectionRateAdjusted09] decimal NOT NULL, + [ProjectionRateAdjusted10] decimal NOT NULL, + [ProjectionRateAdjusted11] decimal NOT NULL, + [ProjectionRateAdjusted12] decimal NOT NULL, + PRIMARY KEY ([StatisticsID]) +); + +CREATE NONCLUSTERED INDEX [IX_Statistics_Account] ON [fp].[Statistics] ([AccountID]) INCLUDE ([StatisticsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [FinancialReportingID], [PayorID], [PatientClassID]); +CREATE NONCLUSTERED INDEX [IX_Statistics_BudgetConfig] ON [fp].[Statistics] ([BudgetConfigID]) INCLUDE ([StatisticsID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID]); +CREATE NONCLUSTERED INDEX [IX_Statistics_Department] ON [fp].[Statistics] ([DepartmentID]) INCLUDE ([StatisticsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID]); +CREATE NONCLUSTERED INDEX [IX_Statistics_Entity] ON [fp].[Statistics] ([EntityID]) INCLUDE ([StatisticsID], [BudgetConfigID], [EntityGroupConfigID], [DepartmentID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID]); +CREATE NONCLUSTERED INDEX [IX_Statistics_FinancialReporting] ON [fp].[Statistics] ([FinancialReportingID]) INCLUDE ([StatisticsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [PayorID], [PatientClassID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_Unique] ON [fp].[Statistics] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [PatientClassID], [PayorID], [ProviderLineItemID], [ProviderID], [ProviderSpecialtyID], [ProviderTypeID]); +GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [FK_Statistics_Account] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [FK_Statistics_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [FK_Statistics_Entity] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [FK_Statistics_FinancialReporting] FOREIGN KEY ([FinancialReportingID]) REFERENCES [ob].[DimFinancialReporting] ([FinancialReportingID]); GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [FK_Statistics_PatientClass] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [FK_Statistics_Payor] FOREIGN KEY ([PayorID]) REFERENCES [fw].[DimPayor] ([PayorID]); GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__00425CA0] DEFAULT ((0)) FOR [ProjectionRateAdjusted07]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__007766CA] DEFAULT ((0)) FOR [SampledBudget05]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__013680D9] DEFAULT ((0)) FOR [ProjectionRateAdjusted08]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__016B8B03] DEFAULT ((0)) FOR [SampledBudget06]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__022AA512] DEFAULT ((0)) FOR [ProjectionRateAdjusted09]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__025FAF3C] DEFAULT ((0)) FOR [SampledBudget07]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__031EC94B] DEFAULT ((0)) FOR [ProjectionRateAdjusted10]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__0353D375] DEFAULT ((0)) FOR [SampledBudget08]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__0412ED84] DEFAULT ((0)) FOR [ProjectionRateAdjusted11]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__0447F7AE] DEFAULT ((0)) FOR [SampledBudget09]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__050711BD] DEFAULT ((0)) FOR [ProjectionRateAdjusted12]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__053C1BE7] DEFAULT ((0)) FOR [SampledBudget10]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__06304020] DEFAULT ((0)) FOR [SampledBudget11]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__07246459] DEFAULT ((0)) FOR [SampledBudget12]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__08188892] DEFAULT ((0)) FOR [SampledProjection01]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__090CACCB] DEFAULT ((0)) FOR [SampledProjection02]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__0A00D104] DEFAULT ((0)) FOR [SampledProjection03]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__0AF4F53D] DEFAULT ((0)) FOR [SampledProjection04]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__0BE91976] DEFAULT ((0)) FOR [SampledProjection05]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__0CDD3DAF] DEFAULT ((0)) FOR [SampledProjection06]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__0DD161E8] DEFAULT ((0)) FOR [SampledProjection07]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__0EC58621] DEFAULT ((0)) FOR [SampledProjection08]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__0FB9AA5A] DEFAULT ((0)) FOR [SampledProjection09]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__10ADCE93] DEFAULT ((0)) FOR [SampledProjection10]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__11A1F2CC] DEFAULT ((0)) FOR [SampledProjection11]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__12961705] DEFAULT ((0)) FOR [SampledProjection12]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__138A3B3E] DEFAULT ((0)) FOR [InitialBudget01]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__147E5F77] DEFAULT ((0)) FOR [InitialBudget02]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__157283B0] DEFAULT ((0)) FOR [InitialBudget03]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__1666A7E9] DEFAULT ((0)) FOR [InitialBudget04]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__175ACC22] DEFAULT ((0)) FOR [InitialBudget05]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__184EF05B] DEFAULT ((0)) FOR [InitialBudget06]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__19431494] DEFAULT ((0)) FOR [InitialBudget07]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__1A3738CD] DEFAULT ((0)) FOR [InitialBudget08]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__1B2B5D06] DEFAULT ((0)) FOR [InitialBudget09]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__1C1F813F] DEFAULT ((0)) FOR [InitialBudget10]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__1D13A578] DEFAULT ((0)) FOR [InitialBudget11]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__1E07C9B1] DEFAULT ((0)) FOR [InitialBudget12]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__1EFBEDEA] DEFAULT ((0)) FOR [InitialProjection01]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__1FF01223] DEFAULT ((0)) FOR [InitialProjection02]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__20E4365C] DEFAULT ((0)) FOR [InitialProjection03]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__21D85A95] DEFAULT ((0)) FOR [InitialProjection04]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__22CC7ECE] DEFAULT ((0)) FOR [InitialProjection05]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__23C0A307] DEFAULT ((0)) FOR [InitialProjection06]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__24B4C740] DEFAULT ((0)) FOR [InitialProjection07]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__25A8EB79] DEFAULT ((0)) FOR [InitialProjection08]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__269D0FB2] DEFAULT ((0)) FOR [InitialProjection09]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__279133EB] DEFAULT ((0)) FOR [InitialProjection10]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__28855824] DEFAULT ((0)) FOR [InitialProjection11]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__29797C5D] DEFAULT ((0)) FOR [InitialProjection12]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__2A6DA096] DEFAULT ((0)) FOR [InitialBudgetRate01]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__2B61C4CF] DEFAULT ((0)) FOR [InitialBudgetRate02]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__2C55E908] DEFAULT ((0)) FOR [InitialBudgetRate03]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__2D4A0D41] DEFAULT ((0)) FOR [InitialBudgetRate04]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__2E3E317A] DEFAULT ((0)) FOR [InitialBudgetRate05]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__2F3255B3] DEFAULT ((0)) FOR [InitialBudgetRate06]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__302679EC] DEFAULT ((0)) FOR [InitialBudgetRate07]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__311A9E25] DEFAULT ((0)) FOR [InitialBudgetRate08]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__320EC25E] DEFAULT ((0)) FOR [InitialBudgetRate09]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__3302E697] DEFAULT ((0)) FOR [InitialBudgetRate10]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__33F70AD0] DEFAULT ((0)) FOR [InitialBudgetRate11]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__34EB2F09] DEFAULT ((0)) FOR [InitialBudgetRate12]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__35DF5342] DEFAULT ((0)) FOR [InitialProjectionRate01]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__36D3777B] DEFAULT ((0)) FOR [InitialProjectionRate02]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__37C79BB4] DEFAULT ((0)) FOR [InitialProjectionRate03]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__38BBBFED] DEFAULT ((0)) FOR [InitialProjectionRate04]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__39AFE426] DEFAULT ((0)) FOR [InitialProjectionRate05]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__3AA4085F] DEFAULT ((0)) FOR [InitialProjectionRate06]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__3B982C98] DEFAULT ((0)) FOR [InitialProjectionRate07]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__3C8C50D1] DEFAULT ((0)) FOR [InitialProjectionRate08]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__3D80750A] DEFAULT ((0)) FOR [InitialProjectionRate09]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__3E749943] DEFAULT ((0)) FOR [InitialProjectionRate10]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__3F68BD7C] DEFAULT ((0)) FOR [InitialProjectionRate11]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Initi__405CE1B5] DEFAULT ((0)) FOR [InitialProjectionRate12]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__415105EE] DEFAULT ((0)) FOR [BudgetAdjusted01]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__42452A27] DEFAULT ((0)) FOR [BudgetAdjusted02]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__43394E60] DEFAULT ((0)) FOR [BudgetAdjusted03]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__442D7299] DEFAULT ((0)) FOR [BudgetAdjusted04]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__452196D2] DEFAULT ((0)) FOR [BudgetAdjusted05]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__4615BB0B] DEFAULT ((0)) FOR [BudgetAdjusted06]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__4709DF44] DEFAULT ((0)) FOR [BudgetAdjusted07]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__47FE037D] DEFAULT ((0)) FOR [BudgetAdjusted08]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__48F227B6] DEFAULT ((0)) FOR [BudgetAdjusted09]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__49E64BEF] DEFAULT ((0)) FOR [BudgetAdjusted10]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__4ADA7028] DEFAULT ((0)) FOR [BudgetAdjusted11]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__4BCE9461] DEFAULT ((0)) FOR [BudgetAdjusted12]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__4CC2B89A] DEFAULT ((0)) FOR [TargetAdjusted01]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__4DB6DCD3] DEFAULT ((0)) FOR [TargetAdjusted02]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__4EAB010C] DEFAULT ((0)) FOR [TargetAdjusted03]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__4F9F2545] DEFAULT ((0)) FOR [TargetAdjusted04]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__5093497E] DEFAULT ((0)) FOR [TargetAdjusted05]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__51876DB7] DEFAULT ((0)) FOR [TargetAdjusted06]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__527B91F0] DEFAULT ((0)) FOR [TargetAdjusted07]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__536FB629] DEFAULT ((0)) FOR [TargetAdjusted08]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__5463DA62] DEFAULT ((0)) FOR [TargetAdjusted09]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__5557FE9B] DEFAULT ((0)) FOR [TargetAdjusted10]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__564C22D4] DEFAULT ((0)) FOR [TargetAdjusted11]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__5740470D] DEFAULT ((0)) FOR [TargetAdjusted12]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__58346B46] DEFAULT ((0)) FOR [BudgetRateAdjusted01]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__59288F7F] DEFAULT ((0)) FOR [BudgetRateAdjusted02]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__5A1CB3B8] DEFAULT ((0)) FOR [BudgetRateAdjusted03]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__5B10D7F1] DEFAULT ((0)) FOR [BudgetRateAdjusted04]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__5C04FC2A] DEFAULT ((0)) FOR [BudgetRateAdjusted05]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__5CF92063] DEFAULT ((0)) FOR [BudgetRateAdjusted06]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__5DED449C] DEFAULT ((0)) FOR [BudgetRateAdjusted07]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__5EE168D5] DEFAULT ((0)) FOR [BudgetRateAdjusted08]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__5FD58D0E] DEFAULT ((0)) FOR [BudgetRateAdjusted09]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__60C9B147] DEFAULT ((0)) FOR [BudgetRateAdjusted10]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__61BDD580] DEFAULT ((0)) FOR [BudgetRateAdjusted11]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__62B1F9B9] DEFAULT ((0)) FOR [BudgetRateAdjusted12]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__63A61DF2] DEFAULT ((0)) FOR [TargetRateAdjusted01]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__649A422B] DEFAULT ((0)) FOR [TargetRateAdjusted02]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__658E6664] DEFAULT ((0)) FOR [TargetRateAdjusted03]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__66828A9D] DEFAULT ((0)) FOR [TargetRateAdjusted04]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__6776AED6] DEFAULT ((0)) FOR [TargetRateAdjusted05]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__686AD30F] DEFAULT ((0)) FOR [TargetRateAdjusted06]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__689FDD39] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__695EF748] DEFAULT ((0)) FOR [TargetRateAdjusted07]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Entit__69940172] DEFAULT ((0)) FOR [EntityGroupConfigID]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__6A531B81] DEFAULT ((0)) FOR [TargetRateAdjusted08]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Entit__6A8825AB] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__6B473FBA] DEFAULT ((0)) FOR [TargetRateAdjusted09]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Depar__6B7C49E4] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__6C3B63F3] DEFAULT ((0)) FOR [TargetRateAdjusted10]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Accou__6C706E1D] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__6D2F882C] DEFAULT ((0)) FOR [TargetRateAdjusted11]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Finan__6D649256] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__6E23AC65] DEFAULT ((0)) FOR [TargetRateAdjusted12]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Payor__6E58B68F] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__6F17D09E] DEFAULT ((0)) FOR [ProjectionAdjusted01]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Patie__6F4CDAC8] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__700BF4D7] DEFAULT ((0)) FOR [ProjectionAdjusted02]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Provi__7040FF01] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__71001910] DEFAULT ((0)) FOR [ProjectionAdjusted03]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Provi__7135233A] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__71F43D49] DEFAULT ((0)) FOR [ProjectionAdjusted04]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Provi__72294773] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__72E86182] DEFAULT ((0)) FOR [ProjectionAdjusted05]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Provi__731D6BAC] DEFAULT ((0)) FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__73DC85BB] DEFAULT ((0)) FOR [ProjectionAdjusted06]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__AddDa__74118FE5] DEFAULT (getdate()) FOR [AddDate]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__74D0A9F4] DEFAULT ((0)) FOR [ProjectionAdjusted07]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__IsNew__7505B41E] DEFAULT ((0)) FOR [IsNew]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__75C4CE2D] DEFAULT ((0)) FOR [ProjectionAdjusted08]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [df_Stats_SubsectionID] DEFAULT ('1') FOR [SubsectionID]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__76B8F266] DEFAULT ((0)) FOR [ProjectionAdjusted09]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__76EDFC90] DEFAULT ((0)) FOR [BudgetLockType]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__77AD169F] DEFAULT ((0)) FOR [ProjectionAdjusted10]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Budge__77E220C9] DEFAULT ((0)) FOR [BudgetLockFlag]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__78A13AD8] DEFAULT ((0)) FOR [ProjectionAdjusted11]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__78D64502] DEFAULT ((0)) FOR [TargetLockType]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__79955F11] DEFAULT ((0)) FOR [ProjectionAdjusted12]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Targe__79CA693B] DEFAULT ((0)) FOR [TargetLockFlag]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__7A89834A] DEFAULT ((0)) FOR [ProjectionRateAdjusted01]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__7ABE8D74] DEFAULT ((0)) FOR [ProjectionLockType]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__7B7DA783] DEFAULT ((0)) FOR [ProjectionRateAdjusted02]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__7BB2B1AD] DEFAULT ((0)) FOR [ProjectionLockFlag]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__7C71CBBC] DEFAULT ((0)) FOR [ProjectionRateAdjusted03]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__7CA6D5E6] DEFAULT ((0)) FOR [SampledBudget01]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__7D65EFF5] DEFAULT ((0)) FOR [ProjectionRateAdjusted04]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__7D9AFA1F] DEFAULT ((0)) FOR [SampledBudget02]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__7E5A142E] DEFAULT ((0)) FOR [ProjectionRateAdjusted05]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__7E8F1E58] DEFAULT ((0)) FOR [SampledBudget03]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Proje__7F4E3867] DEFAULT ((0)) FOR [ProjectionRateAdjusted06]; GO +ALTER TABLE [fp].[Statistics] ADD CONSTRAINT [DF__Statistic__Sampl__7F834291] DEFAULT ((0)) FOR [SampledBudget04]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StatisticsAdjustment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StatisticsAdjustment] ( + [AdjustmentGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [Value] decimal NOT NULL, + [AdjustmentFilterJSON] nvarchar(max) NOT NULL, + [GroupingHierarchyJSON] nvarchar(max) NOT NULL, + [AdjustedProperty] nvarchar(100) NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [ParentFilterJSON] nvarchar(max) NOT NULL, + [TimeClassID] tinyint NOT NULL, + [ClassificationGroupID] int NOT NULL, + [ClassificationCategoryID] int NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + [LastModifiedDateUtc] datetime NOT NULL, + [DimensionMemberJson] nvarchar(max) NOT NULL, + [AdjustmentID] int NOT NULL, + [SubsectionID] int NOT NULL, + [IsErrored] bit NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + PRIMARY KEY ([AdjustmentGUID]) +); +GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [FK__Statistic__Budge__6B17FAEA] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF_StatisticsAdjustment_ClassificationGroupID] DEFAULT ((0)) FOR [ClassificationGroupID]; GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF_StatisticsAdjustment_ClassificationCategoryID] DEFAULT ((0)) FOR [ClassificationCategoryID]; GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Subse__31422788] DEFAULT ((1)) FOR [SubsectionID]; GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Budge__3890A59A] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__IsErr__481D01ED] DEFAULT ((0)) FOR [IsErrored]; GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Dimen__62EDC65E] DEFAULT ('') FOR [DimensionMemberJson]; GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__DateC__6A04D841] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__LastM__6AF8FC7A] DEFAULT (getutcdate()) FOR [LastModifiedDateUtc]; GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Adjus__6C0C1F23] DEFAULT (newid()) FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF_StatisticsAdjustment] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Adjus__6D00435C] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Value__6DF46795] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Adjus__6EE88BCE] DEFAULT ('') FOR [AdjustmentFilterJSON]; GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Group__6FDCB007] DEFAULT ('') FOR [GroupingHierarchyJSON]; GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__IsRec__709BFBE0] DEFAULT ((0)) FOR [IsRecordDeleted]; GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Adjus__70D0D440] DEFAULT ('') FOR [AdjustedProperty]; GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Comme__71C4F879] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Autho__72B91CB2] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Autho__73AD40EB] DEFAULT ('') FOR [AuthorFullName]; GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Group__7689AD96] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[StatisticsAdjustment] ADD CONSTRAINT [DF__Statistic__Paren__777DD1CF] DEFAULT ('{}') FOR [ParentFilterJSON]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StatisticsAdjustmentImport ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StatisticsAdjustmentImport] ( + [RowID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [EntityID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [PayorID] int NOT NULL, + [PatientClassID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [Value] decimal NOT NULL, + [Version] timestamp NOT NULL, + [TimeClassID] tinyint NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [AdjustmentID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_AdjustmentID] ON [fp].[StatisticsAdjustmentImport] ([AdjustmentID]); +GO +ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Entit__001317D0] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Accou__01073C09] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Payor__01FB6042] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Patie__02EF847B] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Finan__03E3A8B4] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__TimeC__1016D774] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Adjus__2782E7CD] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF_StatisticsAdjustmentImport_BudgetPhaseID] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Provi__6C22F634] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Provi__6D171A6D] DEFAULT ((0)) FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Provi__6E0B3EA6] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Provi__6EFF62DF] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__IsRec__746C8CC4] DEFAULT ((0)) FOR [IsRecordDeleted]; GO +ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__Statistic__Adjus__7A5A3E7A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__StatisticsAdjImport__Depar__2B6F7FBE] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__StatisticsAdjImport__Fisca__31285914] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__StatisticsAdjImport__UnitT__34F8E9F8] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF__StatisticsAdjImport__Fisca__3CCC1A58] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentImport] ADD CONSTRAINT [DF_INTStatisticsAdjImportINGVALUE] DEFAULT ((0)) FOR [Value]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StatisticsAdjustmentRate ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StatisticsAdjustmentRate] ( + [RowID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [AdjustmentID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [PayorID] int NOT NULL, + [PatientClassID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [SubsectionID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Value01] decimal NOT NULL, + [Value02] decimal NOT NULL, + [Value03] decimal NOT NULL, + [Value04] decimal NOT NULL, + [Value05] decimal NOT NULL, + [Value06] decimal NOT NULL, + [Value07] decimal NOT NULL, + [Value08] decimal NOT NULL, + [Value09] decimal NOT NULL, + [Value10] decimal NOT NULL, + [Value11] decimal NOT NULL, + [Value12] decimal NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_Clustered_StatisticsAdjustmentRate] ON [fp].[StatisticsAdjustmentRate] ([BudgetConfigID]); +GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Adjus__16840FAB] DEFAULT ((0)) FOR [AdjustmentID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Budge__177833E4] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Entit__186C581D] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Depar__19607C56] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Accou__1A54A08F] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Finan__1B48C4C8] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Payor__1C3CE901] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Patie__1D310D3A] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Provi__1E253173] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Provi__1F1955AC] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Provi__200D79E5] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Provi__21019E1E] DEFAULT ((0)) FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Subse__21F5C257] DEFAULT ((0)) FOR [SubsectionID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__TimeC__22E9E690] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__23DE0AC9] DEFAULT ((0)) FOR [Value01]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__24D22F02] DEFAULT ((0)) FOR [Value02]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__25C6533B] DEFAULT ((0)) FOR [Value03]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__26BA7774] DEFAULT ((0)) FOR [Value04]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__27AE9BAD] DEFAULT ((0)) FOR [Value05]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__28A2BFE6] DEFAULT ((0)) FOR [Value06]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__2996E41F] DEFAULT ((0)) FOR [Value07]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__2A8B0858] DEFAULT ((0)) FOR [Value08]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__2B7F2C91] DEFAULT ((0)) FOR [Value09]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__2C7350CA] DEFAULT ((0)) FOR [Value10]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__2D677503] DEFAULT ((0)) FOR [Value11]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Value__2E5B993C] DEFAULT ((0)) FOR [Value12]; GO +ALTER TABLE [fp].[StatisticsAdjustmentRate] ADD CONSTRAINT [DF__Statistic__Budge__3984C9D3] DEFAULT ((0)) FOR [BudgetPhaseID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StatisticsAdjustment_backup ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StatisticsAdjustment_backup] ( + [AdjustmentGUID] uniqueidentifier NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [Value] decimal NOT NULL, + [AdjustmentFilterJSON] nvarchar(max) NOT NULL, + [GroupingHierarchyJSON] nvarchar(max) NOT NULL, + [AdjustedProperty] nvarchar(100) NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [AuthorFullName] nvarchar(260) NOT NULL, + [LastModifiedDate] datetime NOT NULL, + [DateCreatedUTC] datetime NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [ParentFilterJSON] nvarchar(max) NOT NULL, + [TimeClassID] tinyint NOT NULL, + PRIMARY KEY ([AdjustmentGUID]) +); +GO +ALTER TABLE [fp].[StatisticsAdjustment_backup] ADD CONSTRAINT [DF_StatisticsAdjustmentBackup_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StatisticsChangeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StatisticsChangeHistory] ( + [RowID] bigint NOT NULL, + [StatisticsID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [GroupingGUID] uniqueidentifier NOT NULL, + [AdjustmentType] tinyint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [BudgetPhaseID] tinyint NOT NULL, + [OldValue] decimal NOT NULL, + [NewValue] decimal NOT NULL, + [BudgetConfigID] int NOT NULL, + [DateCreatedUTC] datetime2 NOT NULL, + [SubsectionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_StatisticsChangeHistory] ON [fp].[StatisticsChangeHistory] ([StatisticsID]); +CREATE NONCLUSTERED INDEX [IX_StatisticsChangeHistory_AdjustmentGuid] ON [fp].[StatisticsChangeHistory] ([AdjustmentGUID]) INCLUDE ([StatisticsID], [FiscalMonthID], [UnitTypeID], [TimeClassID], [BudgetPhaseID]); +GO +ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [FK_StatisticsChangeHistory_StatisticsID] FOREIGN KEY ([StatisticsID]) REFERENCES [fp].[FactStatistics] ([StatisticsID]); GO +ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__DateC__03D9B8DD] DEFAULT (getutcdate()) FOR [DateCreatedUTC]; GO +ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__Stati__1453DEB1] DEFAULT ((0)) FOR [StatisticsID]; GO +ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__Adjus__154802EA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__Group__163C2723] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GroupingGUID]; GO +ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__Adjus__17304B5C] DEFAULT ((0)) FOR [AdjustmentType]; GO +ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__Subse__18CB7F79] DEFAULT ((1)) FOR [SubsectionID]; GO +ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__Fisca__191893CE] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__UnitT__1A0CB807] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__TimeC__1B00DC40] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__Budge__1BF50079] DEFAULT ((0)) FOR [BudgetPhaseID]; GO +ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__1CE924B2] DEFAULT ((0)) FOR [OldValue]; GO +ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__1DDD48EB] DEFAULT ((0)) FOR [NewValue]; GO +ALTER TABLE [fp].[StatisticsChangeHistory] ADD CONSTRAINT [DF__Statistic__Budge__5F124882] DEFAULT ((0)) FOR [BudgetConfigID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StatisticsFlexingConfig ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StatisticsFlexingConfig] ( + [EntityGroupConfigGUID] uniqueidentifier NOT NULL, + [AccountID] int NOT NULL, + [FlexMethodID] int NOT NULL, + PRIMARY KEY ([EntityGroupConfigGUID], [AccountID]) +); +GO +ALTER TABLE [fp].[StatisticsFlexingConfig] ADD CONSTRAINT [FK__Statistic__Accou__41B55917] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [fp].[StatisticsFlexingConfig] ADD CONSTRAINT [DF__Statistic__Accou__0DA2E86F] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[StatisticsFlexingConfig] ADD CONSTRAINT [DF__Statistic__FlexM__0E970CA8] DEFAULT ((6)) FOR [FlexMethodID]; GO +ALTER TABLE [fp].[StatisticsFlexingConfig] ADD CONSTRAINT [df_StatisticsFlexingConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StatisticsFlexingOverrideConfig ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StatisticsFlexingOverrideConfig] ( + [EntityGroupConfigGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FlexMethodID] smallint NOT NULL, + [RowID] int NOT NULL, + [OverrideFlexConfigGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [UQ__Statisti__173FA2A63EB2A0A8] ON [fp].[StatisticsFlexingOverrideConfig] ([OverrideFlexConfigGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [Unique_StatisticsFlexingOverrideConfig_EC_Dept_Account] ON [fp].[StatisticsFlexingOverrideConfig] ([EntityGroupConfigGUID], [DepartmentID], [AccountID]); +GO +ALTER TABLE [fp].[StatisticsFlexingOverrideConfig] ADD CONSTRAINT [FK__Statistic__Accou__476E326D] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [fp].[StatisticsFlexingOverrideConfig] ADD CONSTRAINT [FK__Statistic__Depar__467A0E34] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[StatisticsFlexingOverrideConfig] ADD CONSTRAINT [DF__Statistic__Depar__2F8DEC1F] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StatisticsFlexingOverrideConfig] ADD CONSTRAINT [DF__Statistic__Accou__30821058] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[StatisticsFlexingOverrideConfig] ADD CONSTRAINT [DF__Statistic__FlexM__31763491] DEFAULT ((6)) FOR [FlexMethodID]; GO +ALTER TABLE [fp].[StatisticsFlexingOverrideConfig] ADD CONSTRAINT [df_StatisticsFlexingOverrideConfig_EntityGroupConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [EntityGroupConfigGUID]; GO +ALTER TABLE [fp].[StatisticsFlexingOverrideConfig] ADD CONSTRAINT [df_StatisticsFlexingOverrideConfig_OverrideFlexConfigGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OverrideFlexConfigGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StatisticsFlexingOverrideConfigAssignment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StatisticsFlexingOverrideConfigAssignment] ( + [OverrideFlexConfigGUID] uniqueidentifier NOT NULL, + [ChargeCodeID] int NOT NULL, + [RowID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [Unique_StatisticsFlexingOverrideConfigAssignment_Account_FlexGUID] ON [fp].[StatisticsFlexingOverrideConfigAssignment] ([OverrideFlexConfigGUID], [ChargeCodeID]); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StatisticsHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StatisticsHistory] ( + [RowID] int NOT NULL, + [StatisticsID] int NOT NULL, + [PriorYearActualValue01] decimal NOT NULL, + [PriorYearActualValue02] decimal NOT NULL, + [PriorYearActualValue03] decimal NOT NULL, + [PriorYearActualValue04] decimal NOT NULL, + [PriorYearActualValue05] decimal NOT NULL, + [PriorYearActualValue06] decimal NOT NULL, + [PriorYearActualValue07] decimal NOT NULL, + [PriorYearActualValue08] decimal NOT NULL, + [PriorYearActualValue09] decimal NOT NULL, + [PriorYearActualValue10] decimal NOT NULL, + [PriorYearActualValue11] decimal NOT NULL, + [PriorYearActualValue12] decimal NOT NULL, + [ActualYTDValue01] decimal NOT NULL, + [ActualYTDValue02] decimal NOT NULL, + [ActualYTDValue03] decimal NOT NULL, + [ActualYTDValue04] decimal NOT NULL, + [ActualYTDValue05] decimal NOT NULL, + [ActualYTDValue06] decimal NOT NULL, + [ActualYTDValue07] decimal NOT NULL, + [ActualYTDValue08] decimal NOT NULL, + [ActualYTDValue09] decimal NOT NULL, + [ActualYTDValue10] decimal NOT NULL, + [ActualYTDValue11] decimal NOT NULL, + [ActualYTDValue12] decimal NOT NULL, + [CurrentYearBudget01] decimal NOT NULL, + [CurrentYearBudget02] decimal NOT NULL, + [CurrentYearBudget03] decimal NOT NULL, + [CurrentYearBudget04] decimal NOT NULL, + [CurrentYearBudget05] decimal NOT NULL, + [CurrentYearBudget06] decimal NOT NULL, + [CurrentYearBudget07] decimal NOT NULL, + [CurrentYearBudget08] decimal NOT NULL, + [CurrentYearBudget09] decimal NOT NULL, + [CurrentYearBudget10] decimal NOT NULL, + [CurrentYearBudget11] decimal NOT NULL, + [CurrentYearBudget12] decimal NOT NULL, + [PriorYearActualValueTotal] decimal NOT NULL, + [ActualYTDValueTotal] decimal NOT NULL, + [CurrentYearBudgetTotal] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [FK_StatisticsHistory_StatisticsID] FOREIGN KEY ([StatisticsID]) REFERENCES [fp].[Statistics] ([StatisticsID]); GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Stati__0D9C57BE] DEFAULT ((0)) FOR [StatisticsID]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__0E907BF7] DEFAULT ((0)) FOR [PriorYearActualValue01]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__0F84A030] DEFAULT ((0)) FOR [PriorYearActualValue02]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__1078C469] DEFAULT ((0)) FOR [PriorYearActualValue03]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__116CE8A2] DEFAULT ((0)) FOR [PriorYearActualValue04]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__12610CDB] DEFAULT ((0)) FOR [PriorYearActualValue05]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__13553114] DEFAULT ((0)) FOR [PriorYearActualValue06]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__1449554D] DEFAULT ((0)) FOR [PriorYearActualValue07]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__153D7986] DEFAULT ((0)) FOR [PriorYearActualValue08]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__16319DBF] DEFAULT ((0)) FOR [PriorYearActualValue09]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__1725C1F8] DEFAULT ((0)) FOR [PriorYearActualValue10]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__1819E631] DEFAULT ((0)) FOR [PriorYearActualValue11]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Prior__190E0A6A] DEFAULT ((0)) FOR [PriorYearActualValue12]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__1A022EA3] DEFAULT ((0)) FOR [ActualYTDValue01]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__1AF652DC] DEFAULT ((0)) FOR [ActualYTDValue02]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__1BEA7715] DEFAULT ((0)) FOR [ActualYTDValue03]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__1CDE9B4E] DEFAULT ((0)) FOR [ActualYTDValue04]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__1DD2BF87] DEFAULT ((0)) FOR [ActualYTDValue05]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__1EC6E3C0] DEFAULT ((0)) FOR [ActualYTDValue06]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__1FBB07F9] DEFAULT ((0)) FOR [ActualYTDValue07]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__20AF2C32] DEFAULT ((0)) FOR [ActualYTDValue08]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__21A3506B] DEFAULT ((0)) FOR [ActualYTDValue09]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__229774A4] DEFAULT ((0)) FOR [ActualYTDValue10]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__238B98DD] DEFAULT ((0)) FOR [ActualYTDValue11]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Actua__247FBD16] DEFAULT ((0)) FOR [ActualYTDValue12]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__2573E14F] DEFAULT ((0)) FOR [CurrentYearBudget01]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__26680588] DEFAULT ((0)) FOR [CurrentYearBudget02]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__275C29C1] DEFAULT ((0)) FOR [CurrentYearBudget03]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__28504DFA] DEFAULT ((0)) FOR [CurrentYearBudget04]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__29447233] DEFAULT ((0)) FOR [CurrentYearBudget05]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__2A38966C] DEFAULT ((0)) FOR [CurrentYearBudget06]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__2B2CBAA5] DEFAULT ((0)) FOR [CurrentYearBudget07]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__2C20DEDE] DEFAULT ((0)) FOR [CurrentYearBudget08]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__2D150317] DEFAULT ((0)) FOR [CurrentYearBudget09]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__2E092750] DEFAULT ((0)) FOR [CurrentYearBudget10]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__2EFD4B89] DEFAULT ((0)) FOR [CurrentYearBudget11]; GO +ALTER TABLE [fp].[StatisticsHistory] ADD CONSTRAINT [DF__Statistic__Curre__2FF16FC2] DEFAULT ((0)) FOR [CurrentYearBudget12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StatisticsInitialPlanConfigDetail ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StatisticsInitialPlanConfigDetail] ( + [RowID] int NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [BudgetConfigID] smallint NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [PatientClassID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [FinancialReportingID] int NOT NULL, + [PayorID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [VariabilityID] int NOT NULL, + [ProjectionMethodID] int NOT NULL, + [TrailingMonths] tinyint NOT NULL, + [VersionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [FK__Statistic__Budge__5E247F01] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [FK__Statistic__Versi__5F18A33A] FOREIGN KEY ([VersionID]) REFERENCES [fp].[InitialPlanRuleVersion] ([VersionID]); GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Budge__4DEE1738] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Budge__4EE23B71] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Entit__4FD65FAA] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Depar__50CA83E3] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Accou__51BEA81C] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Patie__52B2CC55] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__TimeC__53A6F08E] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Finan__549B14C7] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Payor__558F3900] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Provi__56835D39] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Provi__57778172] DEFAULT ((0)) FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Provi__586BA5AB] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Provi__595FC9E4] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Varia__5A53EE1D] DEFAULT ((0)) FOR [VariabilityID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Proje__5B481256] DEFAULT ((0)) FOR [ProjectionMethodID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Trail__5C3C368F] DEFAULT ((0)) FOR [TrailingMonths]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetail] ADD CONSTRAINT [DF__Statistic__Versi__5D305AC8] DEFAULT ((0)) FOR [VersionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StatisticsInitialPlanConfigDetailHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ( + [RowID] int NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [BudgetConfigID] smallint NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [PatientClassID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [FinancialReportingID] int NOT NULL, + [PayorID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [VariabilityID] int NOT NULL, + [ProjectionMethodID] int NOT NULL, + [TrailingMonths] tinyint NOT NULL, + [VersionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [FK__Statistic__Budge__722B77AE] FOREIGN KEY ([BudgetConfigGUID]) REFERENCES [fp].[BudgetConfig] ([BudgetConfigGUID]); GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [FK__Statistic__Versi__731F9BE7] FOREIGN KEY ([VersionID]) REFERENCES [fp].[InitialPlanRuleVersion] ([VersionID]); GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Budge__61F50FE5] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Budge__62E9341E] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Entit__63DD5857] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Depar__64D17C90] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Accou__65C5A0C9] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Patie__66B9C502] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__TimeC__67ADE93B] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Finan__68A20D74] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Payor__699631AD] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Provi__6A8A55E6] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Provi__6B7E7A1F] DEFAULT ((0)) FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Provi__6C729E58] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Provi__6D66C291] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Varia__6E5AE6CA] DEFAULT ((0)) FOR [VariabilityID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Proje__6F4F0B03] DEFAULT ((0)) FOR [ProjectionMethodID]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Trail__70432F3C] DEFAULT ((0)) FOR [TrailingMonths]; GO +ALTER TABLE [fp].[StatisticsInitialPlanConfigDetailHistory] ADD CONSTRAINT [DF__Statistic__Versi__71375375] DEFAULT ((0)) FOR [VersionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StatisticsSpreadUnlockData ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StatisticsSpreadUnlockData] ( + [RowID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [AdjustmentGUID] uniqueidentifier NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [PayorID] int NOT NULL, + [PatientClassID] int NOT NULL, + [Version] timestamp NOT NULL, + [Value01] decimal NOT NULL, + [Value02] decimal NOT NULL, + [Value03] decimal NOT NULL, + [Value04] decimal NOT NULL, + [Value05] decimal NOT NULL, + [Value06] decimal NOT NULL, + [Value07] decimal NOT NULL, + [Value08] decimal NOT NULL, + [Value09] decimal NOT NULL, + [Value10] decimal NOT NULL, + [Value11] decimal NOT NULL, + [Value12] decimal NOT NULL, + [IsRecordDeleted] bit NOT NULL, + [ProviderID] int NOT NULL, + [ProviderTypeID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [ProviderSpecialtyID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__IsRec__03AED054] DEFAULT ((0)) FOR [IsRecordDeleted]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [df_StatisticsSpreadUnlockData_AdjustmentGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AdjustmentGUID]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Budge__5D9D6AAE] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Entit__5F85B320] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Depar__6079D759] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Accou__616DFB92] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Finan__62621FCB] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Payor__63564404] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Patie__644A683D] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__653E8C76] DEFAULT ((0)) FOR [Value01]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__6632B0AF] DEFAULT ((0)) FOR [Value02]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__6726D4E8] DEFAULT ((0)) FOR [Value03]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__681AF921] DEFAULT ((0)) FOR [Value04]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__690F1D5A] DEFAULT ((0)) FOR [Value05]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__6A034193] DEFAULT ((0)) FOR [Value06]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__6AF765CC] DEFAULT ((0)) FOR [Value07]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Provi__6B6EC91D] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__6BEB8A05] DEFAULT ((0)) FOR [Value08]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Provi__6C62ED56] DEFAULT ((0)) FOR [ProviderTypeID]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__6CDFAE3E] DEFAULT ((0)) FOR [Value09]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Provi__6D57118F] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__6DD3D277] DEFAULT ((0)) FOR [Value10]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Provi__6E4B35C8] DEFAULT ((0)) FOR [ProviderSpecialtyID]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__6EC7F6B0] DEFAULT ((0)) FOR [Value11]; GO +ALTER TABLE [fp].[StatisticsSpreadUnlockData] ADD CONSTRAINT [DF__Statistic__Value__6FBC1AE9] DEFAULT ((0)) FOR [Value12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StatisticsSpreads ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StatisticsSpreads] ( + [BudgetConfigID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [IsInactive] bit NOT NULL, + [SpreadPercentage01] decimal NULL, + [SpreadPercentage02] decimal NULL, + [SpreadPercentage03] decimal NULL, + [SpreadPercentage04] decimal NULL, + [SpreadPercentage05] decimal NULL, + [SpreadPercentage06] decimal NULL, + [SpreadPercentage07] decimal NULL, + [SpreadPercentage08] decimal NULL, + [SpreadPercentage09] decimal NULL, + [SpreadPercentage10] decimal NULL, + [SpreadPercentage11] decimal NULL, + [SpreadPercentage12] decimal NULL, + [TotalImportedValue] decimal NULL, + [SpreadHistoryGUID] uniqueidentifier NOT NULL, + [GlobalSpreadID] int NOT NULL, + [ProviderID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + PRIMARY KEY ([BudgetConfigID], [DepartmentID], [AccountID], [ProviderID], [ProviderLineItemID]) +); +GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [FK_FpStatisticsSpreads_Account] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [FK_FpStatisticsSpreads_Department] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [FK_FpStatisticsSpreads_Provider] FOREIGN KEY ([ProviderID]) REFERENCES [dss].[DimPhysician] ([PhysicianID]); GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [FK_FpStatisticsSpreads_ProviderLineItem] FOREIGN KEY ([ProviderLineItemID]) REFERENCES [fp].[ProviderLineItem] ([ProviderLineItemID]); GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [FK_StatisticsSpreads_History] FOREIGN KEY ([SpreadHistoryGUID]) REFERENCES [fp].[SpreadHistory] ([SpreadHistoryGUID]); GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Provi__1BF466EC] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Provi__1CE88B25] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Globa__3B533FA2] DEFAULT ((1)) FOR [GlobalSpreadID]; GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Budge__43DD98AB] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Depar__44D1BCE4] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Accou__46BA0556] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__IsIna__48A24DC8] DEFAULT ((0)) FOR [IsInactive]; GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__49967201] DEFAULT ((0)) FOR [SpreadPercentage01]; GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__4A8A963A] DEFAULT ((0)) FOR [SpreadPercentage02]; GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__4B7EBA73] DEFAULT ((0)) FOR [SpreadPercentage03]; GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__4C72DEAC] DEFAULT ((0)) FOR [SpreadPercentage04]; GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__4D6702E5] DEFAULT ((0)) FOR [SpreadPercentage05]; GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__4E5B271E] DEFAULT ((0)) FOR [SpreadPercentage06]; GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [df_StatisticsSpreads_SpreadHistoryGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [SpreadHistoryGUID]; GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__4F4F4B57] DEFAULT ((0)) FOR [SpreadPercentage07]; GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__50436F90] DEFAULT ((0)) FOR [SpreadPercentage08]; GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__513793C9] DEFAULT ((0)) FOR [SpreadPercentage09]; GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__522BB802] DEFAULT ((0)) FOR [SpreadPercentage10]; GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__531FDC3B] DEFAULT ((0)) FOR [SpreadPercentage11]; GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Sprea__54140074] DEFAULT ((0)) FOR [SpreadPercentage12]; GO +ALTER TABLE [fp].[StatisticsSpreads] ADD CONSTRAINT [DF__Statistic__Total__550824AD] DEFAULT ((0)) FOR [TotalImportedValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.StatisticsSpreadsChangeHistory ------------------ +--------------------------------------------- +CREATE TABLE [fp].[StatisticsSpreadsChangeHistory] ( + [RowID] bigint NOT NULL, + [StatisticsID] int NOT NULL, + [BudgetConfigID] int NOT NULL, + [SubsectionID] int NOT NULL, + [DateCreatedUtc] datetime NOT NULL, + [OldValue01] decimal NOT NULL, + [OldValue02] decimal NOT NULL, + [OldValue03] decimal NOT NULL, + [OldValue04] decimal NOT NULL, + [OldValue05] decimal NOT NULL, + [OldValue06] decimal NOT NULL, + [OldValue07] decimal NOT NULL, + [OldValue08] decimal NOT NULL, + [OldValue09] decimal NOT NULL, + [OldValue10] decimal NOT NULL, + [OldValue11] decimal NOT NULL, + [OldValue12] decimal NOT NULL, + [NewValue01] decimal NOT NULL, + [NewValue02] decimal NOT NULL, + [NewValue03] decimal NOT NULL, + [NewValue04] decimal NOT NULL, + [NewValue05] decimal NOT NULL, + [NewValue06] decimal NOT NULL, + [NewValue07] decimal NOT NULL, + [NewValue08] decimal NOT NULL, + [NewValue09] decimal NOT NULL, + [NewValue10] decimal NOT NULL, + [NewValue11] decimal NOT NULL, + [NewValue12] decimal NOT NULL +); + +CREATE CLUSTERED INDEX [CORE_BudgetConfigID] ON [fp].[StatisticsSpreadsChangeHistory] ([BudgetConfigID], [SubsectionID], [StatisticsID], [RowID]); +GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__Stati__04A883EE] DEFAULT ((0)) FOR [StatisticsID]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__Budge__059CA827] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__Subse__0690CC60] DEFAULT ((1)) FOR [SubsectionID]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__DateC__0784F099] DEFAULT (getutcdate()) FOR [DateCreatedUtc]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__087914D2] DEFAULT ((0)) FOR [OldValue01]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__096D390B] DEFAULT ((0)) FOR [OldValue02]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__0A615D44] DEFAULT ((0)) FOR [OldValue03]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__0B55817D] DEFAULT ((0)) FOR [OldValue04]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__0C49A5B6] DEFAULT ((0)) FOR [OldValue05]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__0D3DC9EF] DEFAULT ((0)) FOR [OldValue06]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__0E31EE28] DEFAULT ((0)) FOR [OldValue07]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__0F261261] DEFAULT ((0)) FOR [OldValue08]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__101A369A] DEFAULT ((0)) FOR [OldValue09]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__110E5AD3] DEFAULT ((0)) FOR [OldValue10]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__12027F0C] DEFAULT ((0)) FOR [OldValue11]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__OldVa__12F6A345] DEFAULT ((0)) FOR [OldValue12]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__13EAC77E] DEFAULT ((0)) FOR [NewValue01]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__14DEEBB7] DEFAULT ((0)) FOR [NewValue02]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__15D30FF0] DEFAULT ((0)) FOR [NewValue03]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__16C73429] DEFAULT ((0)) FOR [NewValue04]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__17BB5862] DEFAULT ((0)) FOR [NewValue05]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__18AF7C9B] DEFAULT ((0)) FOR [NewValue06]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__19A3A0D4] DEFAULT ((0)) FOR [NewValue07]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__1A97C50D] DEFAULT ((0)) FOR [NewValue08]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__1B8BE946] DEFAULT ((0)) FOR [NewValue09]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__1C800D7F] DEFAULT ((0)) FOR [NewValue10]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__1D7431B8] DEFAULT ((0)) FOR [NewValue11]; GO +ALTER TABLE [fp].[StatisticsSpreadsChangeHistory] ADD CONSTRAINT [DF__Statistic__NewVa__1E6855F1] DEFAULT ((0)) FOR [NewValue12]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.SystemSetting ------------------ +--------------------------------------------- +CREATE TABLE [fp].[SystemSetting] ( + [SystemSettingID] int NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Description] nvarchar(400) NOT NULL, + [Value] nvarchar(max) NOT NULL, + [IsEditable] bit NOT NULL, + [ColumnType] int NOT NULL, + [DefaultValue] nvarchar(100) NOT NULL, + [IsEncrypted] bit NOT NULL, + [IsFeatureFlag] bit NOT NULL, + [DateCreated] date NOT NULL, + PRIMARY KEY ([SystemSettingID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_SystemSetting_Unique] ON [fp].[SystemSetting] ([Name]); +GO +ALTER TABLE [fp].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__DateC__03739D3C] DEFAULT (getdate()) FOR [DateCreated]; GO +ALTER TABLE [fp].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__IsFea__1127FBAC] DEFAULT ((0)) FOR [IsFeatureFlag]; GO +ALTER TABLE [fp].[SystemSetting] ADD CONSTRAINT [DF__SystemSett__Name__555D2A68] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fp].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__Descr__56514EA1] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fp].[SystemSetting] ADD CONSTRAINT [DF_SYSTEMSETTING_VALUE] DEFAULT ('') FOR [Value]; GO +ALTER TABLE [fp].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__IsEdi__58399713] DEFAULT ((0)) FOR [IsEditable]; GO +ALTER TABLE [fp].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__Colum__592DBB4C] DEFAULT ((0)) FOR [ColumnType]; GO +ALTER TABLE [fp].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__Defau__5A21DF85] DEFAULT ('') FOR [DefaultValue]; GO +ALTER TABLE [fp].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__IsEnc__5B1603BE] DEFAULT ((0)) FOR [IsEncrypted]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.TempProcTable ------------------ +--------------------------------------------- +CREATE TABLE [fp].[TempProcTable] ( + [ProcName] nvarchar(max) NULL, + [SchemaName] nvarchar(50) NULL, + [Schema_ID] int NULL, + [ProcText] nvarchar(max) NULL, + [type_desc] nvarchar(100) NULL, + [DateAdded] datetime NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ViewedGeneralLedgerItemizationComment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ViewedGeneralLedgerItemizationComment] ( + [RowID] int NOT NULL, + [CommentGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ViewedGeneralLedgerItemizationComment] ADD CONSTRAINT [DF__ViewedGen__Comme__705D9B6C] DEFAULT (newid()) FOR [CommentGUID]; GO +ALTER TABLE [fp].[ViewedGeneralLedgerItemizationComment] ADD CONSTRAINT [DF__ViewedGen__UserG__7151BFA5] DEFAULT (newid()) FOR [UserGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ViewedManagerAdjustmentComment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ViewedManagerAdjustmentComment] ( + [ViewedManagerAdjustmentCommentID] int NOT NULL, + [CommentGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([ViewedManagerAdjustmentCommentID]) +); +GO +ALTER TABLE [fp].[ViewedManagerAdjustmentComment] ADD CONSTRAINT [FK_ViewedManagerAdjustmentComment_GeneralLedgerManagerAdjustmentComment] FOREIGN KEY ([CommentGUID]) REFERENCES [fp].[GeneralLedgerManagerAdjustmentComment] ([CommentGUID]); GO +ALTER TABLE [fp].[ViewedManagerAdjustmentComment] ADD CONSTRAINT [df_ViewedManagerAdjustmentComment_CommentGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CommentGUID]; GO +ALTER TABLE [fp].[ViewedManagerAdjustmentComment] ADD CONSTRAINT [df_ViewedManagerAdjustmentComment_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ViewedStaffingManagerAdjustmentComment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ViewedStaffingManagerAdjustmentComment] ( + [ViewedStaffingManagerAdjustmentCommentID] int NOT NULL, + [CommentGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([ViewedStaffingManagerAdjustmentCommentID]) +); +GO +ALTER TABLE [fp].[ViewedStaffingManagerAdjustmentComment] ADD CONSTRAINT [FK_ViewedStaffingManagerAdjustmentComment_StaffingManagerAdjustmentComment] FOREIGN KEY ([CommentGUID]) REFERENCES [fp].[StaffingManagerAdjustmentComment] ([CommentGUID]); GO +ALTER TABLE [fp].[ViewedStaffingManagerAdjustmentComment] ADD CONSTRAINT [df_ViewedStaffingManagerAdjustmentComment_CommentGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CommentGUID]; GO +ALTER TABLE [fp].[ViewedStaffingManagerAdjustmentComment] ADD CONSTRAINT [df_ViewedStaffingManagerAdjustmentComment_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.ViewedStaffingManagerSetAdjustmentComment ------------------ +--------------------------------------------- +CREATE TABLE [fp].[ViewedStaffingManagerSetAdjustmentComment] ( + [RowID] int NOT NULL, + [CommentID] int NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fp].[ViewedStaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__ViewedSta__Comme__45E215C5] DEFAULT ((0)) FOR [CommentID]; GO +ALTER TABLE [fp].[ViewedStaffingManagerSetAdjustmentComment] ADD CONSTRAINT [DF__ViewedSta__UserG__46D639FE] DEFAULT (newid()) FOR [UserGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fp.WorkflowDepartmentMoveTaskInfo ------------------ +--------------------------------------------- +CREATE TABLE [fp].[WorkflowDepartmentMoveTaskInfo] ( + [MoveTaskInfoGUID] uniqueidentifier NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [StepName] nvarchar(200) NOT NULL, + [Comment] nvarchar(max) NOT NULL, + [DepartmentsForMove] nvarchar(max) NOT NULL, + PRIMARY KEY ([MoveTaskInfoGUID]) +); +GO + +--------------------------------------------- +--------------------------------------------- +-- VIEWS +--------------------------------------------- + +-- fp.viewABBDeptChargeVolumesByMonth +CREATE VIEW [fp].[viewABBDeptChargeVolumesByMonth] +as +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-10-06 JB JAZZ-44368 Remove PayorID and PayorGroupID +** 2 2023-03-22 BK JAZZ-52162 Update for new data structure +*************************************************************/ +SELECT + vol.BudgetConfigID, + vol.EntityGroupConfigID, + vol.EntityID, + vol.DepartmentID, + vol.ServiceLineID, + vol.PatientClassID, + vol.AgeCohortID, + vol.MedicalSurgicalID, + vol.ChargeCodeID, + vol.UnitTypeID, + vol.ServiceEntityID, + vol.MSDRGID, + vol.UBRevCodeID, + vol.PrimaryCPTID, + vol.BillingCPTID, + vol.ServiceProviderID, + vol.ServiceProviderSpecialtyID, + vol.PerformingProviderID, + vol.PerformingProviderSpecialtyID, + 2 as TimeClassID, + bc.FiscalYearID, + m.FiscalMonthID, + vol.Value as Volume +From + ( + SELECT + cv.ChargeVolumeID, + cv.BudgetConfigID, + cv.EntityGroupConfigID, + cv.EntityID, + cv.DepartmentID, + cv.ServiceLineID, + cv.PatientClassID, + cv.AgeCohortID, + cv.MedicalSurgicalID, + cv.ChargeCodeID, + cv.UnitTypeID, + cv.ServiceEntityID, + cv.MSDRGID, + cv.UBRevCodeID, + cv.PrimaryCPTID, + cv.BillingCPTID, + cv.ServiceProviderID, + cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, + cv.PerformingProviderSpecialtyID, + TargetLockType, + TargetAdjusted01 AS 'Month01', + TargetAdjusted02 AS 'Month02', + TargetAdjusted03 AS 'Month03', + TargetAdjusted04 AS 'Month04', + TargetAdjusted05 AS 'Month05', + TargetAdjusted06 AS 'Month06', + TargetAdjusted07 AS 'Month07', + TargetAdjusted08 AS 'Month08', + TargetAdjusted09 AS 'Month09', + TargetAdjusted10 AS 'Month10', + TargetAdjusted11 AS 'Month11', + TargetAdjusted12 AS 'Month12' + FROM + fp.ChargeVolume cv + WHERE cv.UnitTypeID = 145 -- We only want the units (aka volume) + ) cv + UNPIVOT (Value FOR FiscalMonth IN (Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12)) as vol +LEFT JOIN fw.DimFiscalMonth m ON + m.MonthColumnName = vol.FiscalMonth +INNER JOIN fp.BudgetConfig bc ON + vol.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewABBDeptChargeVolumesByMonth_Initials +CREATE VIEW [fp].[viewABBDeptChargeVolumesByMonth_Initials] +as +/********************************************************************* +** Change History +********************************************************************** +** CID Date Author WI Description +** 1 2022-07-12 MD JAZZ-38981 Initial +** 2 2022-10-06 JB JAZZ-44368 Remove PayorID and PayorGroupID +** 3 2023-03-22 BK JAZZ-52162 Update for new data structure +*********************************************************************/ +SELECT + vol.BudgetConfigID, + vol.EntityGroupConfigID, + vol.EntityID, + vol.DepartmentID, + vol.ServiceLineID, + vol.PatientClassID, + vol.AgeCohortID, + vol.MedicalSurgicalID, + vol.ChargeCodeID, + vol.UnitTypeID, + vol.ServiceEntityID, + vol.MSDRGID, + vol.UBRevCodeID, + vol.PrimaryCPTID, + vol.BillingCPTID, + vol.ServiceProviderID, + vol.ServiceProviderSpecialtyID, + vol.PerformingProviderID, + vol.PerformingProviderSpecialtyID, + TimeClassID, + bc.FiscalYearID, + m.FiscalMonthID, + vol.Value as Volume +From + ( + SELECT + cv.ChargeVolumeID, + cv.BudgetConfigID, + cv.EntityGroupConfigID, + cv.EntityID, + cv.DepartmentID, + cv.ServiceLineID, + cv.PatientClassID, + cv.AgeCohortID, + cv.MedicalSurgicalID, + cv.ChargeCodeID, + cv.UnitTypeID, + cv.ServiceEntityID, + cv.MSDRGID, + cv.UBRevCodeID, + cv.PrimaryCPTID, + cv.BillingCPTID, + cv.ServiceProviderID, + cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, + cv.PerformingProviderSpecialtyID, + CAST(2 AS TINYINT) AS TimeClassID, + cv.InitialBudget01 AS 'Month01', + cv.InitialBudget02 AS 'Month02', + cv.InitialBudget03 AS 'Month03', + cv.InitialBudget04 AS 'Month04', + cv.InitialBudget05 AS 'Month05', + cv.InitialBudget06 AS 'Month06', + cv.InitialBudget07 AS 'Month07', + cv.InitialBudget08 AS 'Month08', + cv.InitialBudget09 AS 'Month09', + cv.InitialBudget10 AS 'Month10', + cv.InitialBudget11 AS 'Month11', + cv.InitialBudget12 AS 'Month12' + FROM + fp.ChargeVolume cv + WHERE + cv.UnitTypeID = 145 -- We only want the units (aka volume) + ) cv + + UNPIVOT (Value FOR FiscalMonth IN (Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12)) as vol +LEFT JOIN fw.DimFiscalMonth m ON + m.MonthColumnName = vol.FiscalMonth +INNER JOIN fp.BudgetConfig bc +ON + vol.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewABBDeptChargeVolumesByMonth_Projection +/********************************************************************* +** Change History +********************************************************************** +** CID Date Author WI Description +** 1 2022-07-21 MD JAZZ-38981 Initial +** 2 2022-10-06 JB JAZZ-44368 Remove PayorID and PayorGroupID +** 3 2023-03-22 BK JAZZ-52162 Update for new data structure +** 4 2023-08-31 MY JAZZ-59674 Update Projection FiscalYear +*********************************************************************/ + +CREATE VIEW [fp].[viewABBDeptChargeVolumesByMonth_Projection] +as +SELECT + vol.BudgetConfigID, + vol.EntityGroupConfigID, + vol.EntityID, + vol.DepartmentID, + vol.ServiceLineID, + vol.PatientClassID, + vol.AgeCohortID, + vol.MedicalSurgicalID, + vol.ChargeCodeID, + vol.UnitTypeID, + vol.ServiceEntityID, + vol.MSDRGID, + vol.UBRevCodeID, + vol.PrimaryCPTID, + vol.BillingCPTID, + vol.ServiceProviderID, + vol.ServiceProviderSpecialtyID, + vol.PerformingProviderID, + vol.PerformingProviderSpecialtyID, + 12 as TimeClassID, + bc.FiscalYearID as FiscalYearID, -- Normally, we would want this to be FiscalYear - 1, but in this case we want to use the Budget Cost Per RVU + m.FiscalMonthID, + vol.Value as Volume +From + ( + SELECT + cv.ChargeVolumeID, + cv.BudgetConfigID, + cv.EntityGroupConfigID, + cv.EntityID, + cv.DepartmentID, + cv.ServiceLineID, + cv.PatientClassID, + cv.AgeCohortID, + cv.MedicalSurgicalID, + cv.ChargeCodeID, + cv.UnitTypeID, + cv.ServiceEntityID, + cv.MSDRGID, + cv.UBRevCodeID, + cv.PrimaryCPTID, + cv.BillingCPTID, + cv.ServiceProviderID, + cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, + cv.PerformingProviderSpecialtyID, + ProjectionLockType, + ProjectionAdjusted01 AS 'Month01', + ProjectionAdjusted02 AS 'Month02', + ProjectionAdjusted03 AS 'Month03', + ProjectionAdjusted04 AS 'Month04', + ProjectionAdjusted05 AS 'Month05', + ProjectionAdjusted06 AS 'Month06', + ProjectionAdjusted07 AS 'Month07', + ProjectionAdjusted08 AS 'Month08', + ProjectionAdjusted09 AS 'Month09', + ProjectionAdjusted10 AS 'Month10', + ProjectionAdjusted11 AS 'Month11', + ProjectionAdjusted12 AS 'Month12' + FROM + fp.ChargeVolume cv + WHERE cv.UnitTypeID = 145 -- We only want the units (aka volume) + ) cv + UNPIVOT (Value FOR FiscalMonth IN (Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12)) as vol +LEFT JOIN fw.DimFiscalMonth m ON + m.MonthColumnName = vol.FiscalMonth +INNER JOIN fp.BudgetConfig bc ON + vol.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewABBFlexingAuditGL +CREATE VIEW fp.viewABBFlexingAuditGL +as + SELECT + slv.EntityID, + slv.DepartmentID, + bc.FiscalYearID, + GL.TimeClassID, + bc.BudgetConfigID, + slv.ChargeCodeID, + GL.OriginalAccountID, + GL.CostComponentID, + cc.CostingConfigGuid, +-- COALESCE(BudgetChargeUnits / NULLIF(BudgetServiceLineCases, 0), 0) as Utilization, +0 as Utilization, + slv.Month01 as ChargeUnits_Month01, +slv.Month02 as ChargeUnits_Month02, +slv.Month03 as ChargeUnits_Month03, +slv.Month04 as ChargeUnits_Month04, +slv.Month05 as ChargeUnits_Month05, +slv.Month06 as ChargeUnits_Month06, +slv.Month07 as ChargeUnits_Month07, +slv.Month08 as ChargeUnits_Month08, +slv.Month09 as ChargeUnits_Month09, +slv.Month10 as ChargeUnits_Month10, +slv.Month11 as ChargeUnits_Month11, +slv.Month12 as ChargeUnits_Month12, +GL.VariableDirectUnitCost, + GL.FixedDirectUnitCost, + GL.Volume + FROM + [fp].[viewServiceLineChargeVolume_aggregate] slv + INNER JOIN [fp].[BudgetConfig] bc ON slv.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [fp].[EntityGroupConfig] ec ON ec.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN [dss].[CostingConfig] cc on ec.CostingConfigGUID=cc.CostingConfigGuid + INNER JOIN [dss].[CostingResult] cr on cc.CostingConfigGuid=cr.CostingConfigGuid + INNER JOIN [dss].[FactCostingOutDetailGL] GL ON 1=1 + AND gl.CostingResultID=cr.CostingResultID + AND gl.DepartmentID=slv.DepartmentID + AND gl.ChargeCodeID=slv.ChargeCodeID + AND GL.TimeClassID = ec.CostingConfigTimeClassID + WHERE + cr.CostingResultID in(select max(cr2.CostingResultID) from [dss].[CostingResult] cr2 where cr2.CostingConfigGuid = cc.CostingConfigGuid and cr2.IsActivityBasedDetail = 1 and cr2.IsMarkedForDeletion = 0) +GO + + +--------------------------------------------- + +-- fp.viewABBGLBudgetCostPerRVUbyMonth +CREATE VIEW [fp].[viewABBGLBudgetCostPerRVUbyMonth] AS + +SELECT + A.DepartmentID + ,B.AccountID + ,A.ChargeCodeID + ,A.CostComponentID + ,A.BudgetConfigID + ,A.FiscalMonthID + ,A.FiscalYearID + ,A.ChargeVolume + ,(A.ChargeVolume * A.RVU * B.VariableDirectUnitCostPerRVU) as ExtendedVariableDirectCost + ,B.TotalCost + ,B.TotalVariableDirectCost +FROM + (SELECT + b.DepartmentID + , b.ChargeCodeID + , ca.CostComponentID + , b.BudgetConfigID + , b.FiscalMonthID + , b.FiscalYearID + , MAX(ca.RVU) as RVU + , SUM(Volume) as ChargeVolume + FROM [fp].[viewABBDeptChargeVolumesByMonth] b + INNER JOIN [fp].[BudgetConfig] bc ON b.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [fp].[EntityGroupConfig] ec ON ec.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN [dss].[ChargeAllocation] ca + ON ca.CostingConfigGuid = ec.CostingConfigGUID + and ca.ChargeCodeID = b.ChargeCodeID + and ca.DepartmentID = b.DepartmentID + and AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0 + GROUP BY + b.DepartmentID, b.ChargeCodeID, ca.CostComponentID, b.BudgetConfigID, b.FiscalMonthID, b.FiscalYearID) A + +INNER JOIN + + (SELECT + OriginalAccountID as AccountID + , gl.DepartmentID + , gl.FiscalYearID + , gl.CostComponentID + , bc.BudgetConfigID + , SUM(gl.VariableDirectUnitCost)/SUM(ca.RVU) as VariableDirectUnitCostPerRVU + , SUM(gl.VariableDirectUnitCost * gl.Volume) as TotalVariableDirectCost + , SUM(gl.TotalCost) as TotalCost + FROM [dss].[FactCostingOutDetailGL] gl + INNER JOIN [dss].[CostingResult] cr on gl.CostingResultID = cr.CostingResultID + INNER JOIN [dss].[CostingConfig] con on cr.CostingConfigGuid = con.CostingConfigGuid + INNER JOIN [fp].[EntityGroupConfig] ec on con.CostingConfigGuid = ec.CostingConfigGUID + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigGUID = ec.BudgetConfigGUID + INNER JOIN [dss].[ChargeAllocation] ca on + ca.CostingConfigGuid = con.CostingConfigGUID + and ca.ChargeCodeID = gl.ChargeCodeID + and ca.DepartmentID = gl.DepartmentID + and ca.CostComponentID = gl.CostComponentID + and AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0 + WHERE + gl.CostingResultID in (select max(cr2.CostingResultID) from [dss].[CostingResult] cr2 where cr2.CostingConfigGuid = ec.CostingConfigGuid and cr2.IsActivityBasedDetail = 1 and cr2.IsMarkedForDeletion = 0 and cr2.IsFailure = 0) + and gl.TimeClassID = ec.CostingConfigTimeClassID + GROUP BY + gl.OriginalAccountID + , gl.DepartmentID + , bc.BudgetConfigID + , gl.FiscalYearID + , gl.CostComponentID) B +ON + A.DepartmentID = B.DepartmentID + and A.CostComponentID = B.CostComponentID; +GO + + +--------------------------------------------- + +-- fp.viewABBPayrollBudgetCostPerRVUbyMonth +CREATE VIEW [fp].[viewABBPayrollBudgetCostPerRVUbyMonth] AS + + SELECT + A.DepartmentID + ,B.JobCodeID + ,B.PayCodeGroupID + ,A.ChargeCodeID + ,A.CostComponentID + ,A.BudgetConfigID + ,A.FiscalMonthID + ,A.FiscalYearID + ,B.UnitTypeID + ,A.ChargeVolume + ,(A.ChargeVolume * A.RVU * B.VariableDirectUnitCostPerRVU) as ExtendedVariableDirectCost + ,B.TotalCost + ,B.TotalVariableDirectCost + FROM + (SELECT + b.DepartmentID + , b.ChargeCodeID + , ca.CostComponentID + , b.BudgetConfigID + , b.FiscalMonthID + , b.FiscalYearID + , MAX(ca.RVU) as RVU + , SUM(Volume) as ChargeVolume + FROM [fp].[viewABBDeptChargeVolumesByMonth] b + INNER JOIN [fp].[BudgetConfig] bc on b.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [fp].[EntityGroupConfig] ec on ec.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN [dss].[ChargeAllocation] ca + ON ca.CostingConfigGuid = ec.CostingConfigGUID + and ca.ChargeCodeID = b.ChargeCodeID + and ca.DepartmentID = b.DepartmentID + and AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0 + GROUP BY + b.DepartmentID, b.ChargeCodeID, ca.CostComponentID, b.BudgetConfigID, b.FiscalMonthID, b.FiscalYearID) A + + INNER JOIN + + (SELECT + OriginalJobCodeID as JobCodeID + , pc.PayCodeGroupID + , pay.DepartmentID + , pay.FiscalYearID + , pay.CostComponentID + , bc.BudgetConfigID + , pay.UnitTypeID + , SUM(pay.VariableDirectUnitCost)/SUM(ca.RVU) as VariableDirectUnitCostPerRVU + , SUM(pay.VariableDirectUnitCost * pay.Volume) as TotalVariableDirectCost + , SUM(pay.TotalCost) as TotalCost + FROM [dss].[FactCostingOutDetailPayroll] pay + INNER JOIN [dss].[CostingResult] cr on pay.CostingResultID = cr.CostingResultID + INNER JOIN [dss].[CostingConfig] con on cr.CostingConfigGuid = con.CostingConfigGuid + INNER JOIN [fp].[EntityGroupConfig] ec on con.CostingConfigGuid = ec.CostingConfigGUID + INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigGUID = ec.BudgetConfigGUID + INNER JOIN [dss].[ChargeAllocation] ca on + ca.CostingConfigGuid = con.CostingConfigGUID + and ca.ChargeCodeID = pay.ChargeCodeID + and ca.DepartmentID = pay.DepartmentID + and ca.CostComponentID = pay.CostComponentID + and AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0 + INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = pay.OriginalPayCodeID + WHERE + pay.CostingResultID in (select max(cr2.CostingResultID) from [dss].[CostingResult] cr2 where cr2.CostingConfigGuid = ec.CostingConfigGuid and cr2.IsActivityBasedDetail = 1 and cr2.IsMarkedForDeletion = 0 and cr2.IsFailure = 0) + and pay.TimeClassID = ec.CostingConfigTimeClassID + GROUP BY + pay.OriginalJobCodeID + , pc.PayCodeGroupID + , pay.DepartmentID + , bc.BudgetConfigID + , pay.UnitTypeID + , pay.FiscalYearID + , pay.CostComponentID) B + ON + A.DepartmentID = B.DepartmentID + and A.CostComponentID = B.CostComponentID +GO + + +--------------------------------------------- + +-- fp.viewAPEDepartmentWorkflowStatus +CREATE view fp.viewAPEDepartmentWorkflowStatus +as +select +bc.BudgetConfigID, +wk.EntityGroupConfigID, +dept.DepartmentWorkflowStatusID, +dept.DepartmentID, +dept.EnteredStepDateTimeUtc, +dept.Status, +wk.WorkflowStepID, +wk.Name, +wk.RoleID, +wk.WorkflowStepOrder, +wk.IsEditable +from fp.APEDepartmentWorkflowStatus as dept +inner join fp.APEWorkflow as wk on dept.WorkflowStepID = wk.WorkflowStepID +inner join fp.EntityGroupConfig as egc on wk.EntityGroupConfigID = egc.EntityGroupConfigID +inner join fp.BudgetConfig as bc on egc.BudgetConfigGUID = bc.BudgetConfigGUID +GO + + +--------------------------------------------- + +-- fp.viewAPESectionRoleAccessByUser +create view fp.viewAPESectionRoleAccessByUser +as + select + a.EntityGroupConfigID, + a.Section, + ra.IdentityGUID as UserGUID, + max(a.AccessType) as AccessType + from + fp.APESectionRoleAccess a + inner join dbo.viewS3RoleAssignment ra on ra.RoleID = a.RoleID + where + a.budgetphaseid = 2 + and ra.lootgroupid like 'DEPT|%' + group by + a.EntityGroupConfigID, + a.Section, + ra.IdentityGUID +GO + + +--------------------------------------------- + +-- fp.viewAPESectionRoleAccessByUserPerDepartment +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-10-12 MY JAZZ-61714 Import Tool Error for Local Admin (added TRY_CAST) +*************************************************************/ +CREATE VIEW fp.viewAPESectionRoleAccessByUserPerDepartment +AS + SELECT + a.EntityGroupConfigID, + a.Section, + ra.IdentityGUID as UserGUID, + TRY_CAST(REPLACE(ra.lootgroupid, 'DEPT|', '') AS INT) AS DepartmentID, + a.AccessType as AccessType + FROM fp.APESectionRoleAccess a + INNER JOIN dbo.viewS3RoleAssignment ra on ra.RoleID = a.RoleID + WHERE + a.budgetphaseid = 2 + AND ra.lootgroupid LIKE 'DEPT|%' +GO + + +--------------------------------------------- + +-- fp.viewAccountFlexConfig +CREATE VIEW fp.viewAccountFlexConfig +AS + SELECT bc.BudgetConfigID, egcm.EntityGroupConfigGUID, egcm.EntityID, afc.AccountID, afc.FlexMethodClassName + FROM [fp].[AccountFlexConfig] afc + INNER JOIN [fp].[EntityGroupConfig] egc ON afc.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egc.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID + INNER JOIN [fp].[BudgetConfig] bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID +GO + + +--------------------------------------------- + +-- fp.viewAddProviderSummary +CREATE view [fp].[viewAddProviderSummary] as + +SELECT + prov.SummaryID, + prov.SLEncounterAdjustmentGUID, + prov.DCVolumeAdjustmentGUID, + prov.EmployeeType, + emp.Number as EmployeeNumber, + emp.NameFirst, + emp.NameLast, + emp.NPI, + prov.StartDateUTC, + provtype.Name as ProviderType, + spec.Name Speciality, + prov.BenchmarkProvidersJSON, + prov.BenchmarkAverage, + prov.ProjectionTotal, + prov.BudgetTotal, + prov.ClassificationCategoryID, + prov.ClassificationGroupID, + prov.Comment +FROM fp.AddProviderSummary prov + LEFT JOIN [fw].[DimEmployee] emp ON prov.EmployeeID = emp.EmployeeID + LEFT JOIN [clientdss].[DimProviderType] provtype on provtype.ProviderTypeID = prov.ProviderType + LEFT JOIN [dss].[DimPhysicianSpecialty] spec on spec.PhysicianSpecialtyID = prov.Specialty +GO + + +--------------------------------------------- + +-- fp.viewAdjustmentClassificationCategory +--Last Modified 11/16/2020 3:28 PM +CREATE VIEW [fp].[viewAdjustmentClassificationCategory] +AS +SELECT + grp6BD697B47CED4B698C166B89FE895E9E.[CategoryID] + ,grp6BD697B47CED4B698C166B89FE895E9E.[Name] + ,grp6BD697B47CED4B698C166B89FE895E9E.[MemberGUID] + ,grp6BD697B47CED4B698C166B89FE895E9E.[GroupID] +FROM [fp].[AdjustmentClassificationCategory] grp6BD697B47CED4B698C166B89FE895E9E (readuncommitted) +GO + + +--------------------------------------------- + +-- fp.viewAdjustmentClassificationGroup +--Last Modified 11/16/2020 3:28 PM +CREATE VIEW [fp].[viewAdjustmentClassificationGroup] +AS +SELECT + grp67DF447E1BD04F1F8D5C73CDDF4B3EAC.[GroupID] + ,grp67DF447E1BD04F1F8D5C73CDDF4B3EAC.[Name] + ,grp67DF447E1BD04F1F8D5C73CDDF4B3EAC.[MemberGUID] + ,grp67DF447E1BD04F1F8D5C73CDDF4B3EAC.[BudgetConfigID] + ,grp67DF447E1BD04F1F8D5C73CDDF4B3EAC.[IsEncounterVisible] + ,grp67DF447E1BD04F1F8D5C73CDDF4B3EAC.[IsChargesVisible] + ,grp67DF447E1BD04F1F8D5C73CDDF4B3EAC.[IsStatisticsVisible] + ,grp67DF447E1BD04F1F8D5C73CDDF4B3EAC.[IsStaffingVisible] + ,grp67DF447E1BD04F1F8D5C73CDDF4B3EAC.[IsBenefitsVisible] + ,grp67DF447E1BD04F1F8D5C73CDDF4B3EAC.[IsGeneralLedgerVisible] +FROM [fp].[AdjustmentClassificationGroup] grp67DF447E1BD04F1F8D5C73CDDF4B3EAC (readuncommitted) +GO + + +--------------------------------------------- + +-- fp.viewAdjustmentGrouping +CREATE VIEW fp.viewAdjustmentGrouping +AS +SELECT [GroupingGUID] + ,[Description] + ,[ExcelFile] + ,[IsRecordDeleted] + FROM [fp].[AdjustmentGrouping] + WHERE IsRecordDeleted = 0 +GO + + +--------------------------------------------- + +-- fp.viewArchiveFactBenefits_HistoryViewer +CREATE VIEW fp.viewArchiveFactBenefits_HistoryViewer +AS +SELECT + ov.BenefitsID, + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.DepartmentID, + ov.AccountID, + ov.FinancialReportingID, + ov.UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + ov.FiscalMonthID, + LockType, + ov.InitialValue AS OriginalValue, + v.Value, + mgrv.ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT gl.* + FROM fp.ArchiveFactBenefits gl ) gl + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT gl.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.ArchiveFactBenefits gl + INNER JOIN fp.ArchiveFactBenefitsBudget bdgt ON gl.BenefitsID = bdgt.BenefitsID + WHERE bdgt.BudgetPhaseID = 2) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.DepartmentID = v.DepartmentID + AND ov.AccountID = v.AccountID + AND ov.BudgetConfigID = v.BudgetConfigID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN ( + -- Unpivot for ManagerValue + SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value AS ManagerValue + FROM ( + SELECT gl.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.ArchiveFactBenefits gl + INNER JOIN fp.ArchiveFactBenefitsBudget bdgt ON gl.BenefitsID = bdgt.BenefitsID + WHERE bdgt.BudgetPhaseID = 3) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON ov.DepartmentID = mgrv.DepartmentID + AND ov.AccountID = mgrv.AccountID + AND ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.UnitTypeID = mgrv.UnitTypeID + AND ov.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewArchiveFactBenefits_Pivoted +CREATE VIEW [fp].[viewArchiveFactBenefits_Pivoted] +AS +SELECT + fb.BenefitsID, + fb.BudgetConfigID, + fb.EntityGroupConfigID, + fb.EntityID, + fb.DepartmentID, + fb.AccountID, + fb.FinancialReportingID, + fb.UnitTypeID, + + CASE WHEN fb.FlexMethodID = 1 THEN 1 ELSE 0 END AS FlexByFTEs, + CASE WHEN fb.FlexMethodID = 2 THEN 1 ELSE 0 END AS FlexBySalaries, + + fbdgt.LockType as BudgetLockType, + fbdgt.LockFlag as BudgetLockFlag, + fproj.LockType as ProjectionLockType, + fproj.LockFlag as ProjectionLockFlag, + + dbdgt.LockType as FinalBudgetLockType, + dbdgt.LockFlag as FinalBudgetLockFlag, + dproj.LockType as FinalProjectionLockType, + dproj.LockFlag as FinalProjectionLockFlag, + + fbdgt.AdjustedValueTotal, + + dbdgt.AdjustedValueTotal as ManagerAdjustedValueTotal, + dproj.AdjustedValueTotal as ManagerAdjustedProjectionValueTotal, + + dproj.AdjustedValueTotal as AdjustedProjectionValueTotal, + + hist.ActualYTDValueTotal, + hist.CurrentYearBudgetTotal, + hist.PriorYearActualValueTotal, + + fb.InitialBudgetTotal, + fb.InitialProjectionTotal, + + fbdgt.AdjustedValue01, fbdgt.AdjustedValue02, fbdgt.AdjustedValue03, fbdgt.AdjustedValue04, fbdgt.AdjustedValue05, fbdgt.AdjustedValue06, fbdgt.AdjustedValue07, fbdgt.AdjustedValue08, fbdgt.AdjustedValue09, fbdgt.AdjustedValue10, fbdgt.AdjustedValue11, fbdgt.AdjustedValue12, + dbdgt.AdjustedValue01 AS ManagerAdjustedValue01, dbdgt.AdjustedValue02 AS ManagerAdjustedValue02, dbdgt.AdjustedValue03 AS ManagerAdjustedValue03, dbdgt.AdjustedValue04 AS ManagerAdjustedValue04, dbdgt.AdjustedValue05 AS ManagerAdjustedValue05, dbdgt.AdjustedValue06 AS ManagerAdjustedValue06, dbdgt.AdjustedValue07 AS ManagerAdjustedValue07, dbdgt.AdjustedValue08 AS ManagerAdjustedValue08, dbdgt.AdjustedValue09 AS ManagerAdjustedValue09, dbdgt.AdjustedValue10 AS ManagerAdjustedValue10, dbdgt.AdjustedValue11 AS ManagerAdjustedValue11, dbdgt.AdjustedValue12 AS ManagerAdjustedValue12, + dproj.AdjustedValue01 AS AdjustedProjectionValue01, dproj.AdjustedValue02 AS AdjustedProjectionValue02, dproj.AdjustedValue03 AS AdjustedProjectionValue03, dproj.AdjustedValue04 AS AdjustedProjectionValue04, dproj.AdjustedValue05 AS AdjustedProjectionValue05, dproj.AdjustedValue06 AS AdjustedProjectionValue06, dproj.AdjustedValue07 AS AdjustedProjectionValue07, dproj.AdjustedValue08 AS AdjustedProjectionValue08, dproj.AdjustedValue09 AS AdjustedProjectionValue09, dproj.AdjustedValue10 AS AdjustedProjectionValue10, dproj.AdjustedValue11 AS AdjustedProjectionValue11, dproj.AdjustedValue12 AS AdjustedProjectionValue12, + fb.InitialBudget01, fb.InitialBudget02, fb.InitialBudget03, fb.InitialBudget04, fb.InitialBudget05, fb.InitialBudget06, fb.InitialBudget07, fb.InitialBudget08, fb.InitialBudget09, fb.InitialBudget10, fb.InitialBudget11, fb.InitialBudget12, + hist.PriorYearActualValue01, hist.PriorYearActualValue02, hist.PriorYearActualValue03, hist.PriorYearActualValue04, hist.PriorYearActualValue05, hist.PriorYearActualValue06, hist.PriorYearActualValue07, hist.PriorYearActualValue08, hist.PriorYearActualValue09, hist.PriorYearActualValue10, hist.PriorYearActualValue11, hist.PriorYearActualValue12, + hist.ActualYTDValue01, hist.ActualYTDValue02, hist.ActualYTDValue03, hist.ActualYTDValue04, hist.ActualYTDValue05, hist.ActualYTDValue06, hist.ActualYTDValue07, hist.ActualYTDValue08, hist.ActualYTDValue09, hist.ActualYTDValue10, hist.ActualYTDValue11, hist.ActualYTDValue12, + hist.CurrentYearBudget01, hist.CurrentYearBudget02, hist.CurrentYearBudget03, hist.CurrentYearBudget04, hist.CurrentYearBudget05, hist.CurrentYearBudget06, hist.CurrentYearBudget07, hist.CurrentYearBudget08, hist.CurrentYearBudget09, hist.CurrentYearBudget10, hist.CurrentYearBudget11, hist.CurrentYearBudget12 +FROM [fp].[ArchiveFactBenefits] fb (READUNCOMMITTED) + INNER JOIN [fp].[ArchiveFactBenefitsBudget] (READUNCOMMITTED) fbdgt ON fb.BenefitsID = fbdgt.BenefitsID AND fbdgt.BudgetPhaseID = 2 + INNER JOIN [fp].[ArchiveFactBenefitsBudget] (READUNCOMMITTED) dbdgt ON fb.BenefitsID = dbdgt.BenefitsID AND dbdgt.BudgetPhaseID = 3 + INNER JOIN [fp].[ArchiveFactBenefitsProjection] (READUNCOMMITTED) fproj ON fb.BenefitsID = fproj.BenefitsID AND fproj.BudgetPhaseID = 2 + INNER JOIN [fp].[ArchiveFactBenefitsProjection] (READUNCOMMITTED) dproj ON fb.BenefitsID = dproj.BenefitsID AND dproj.BudgetPhaseID = 3 + INNER JOIN [fp].[ArchiveFactBenefitsHistory] hist (READUNCOMMITTED) ON fb.BenefitsID = hist.BenefitsID +GO + + +--------------------------------------------- + +-- fp.viewArchiveFactChargeVolume_Pivoted +CREATE VIEW fp.viewArchiveFactChargeVolume_Pivoted +AS + SELECT + fcv.ChargeVolumeID, + fcv.BudgetConfigID, + fcv.EntityGroupConfigID, + fcv.EntityID, + fcv.DepartmentID, + fcv.ServiceLineID, + fcv.PatientClassID, + fcv.AgeCohortID, + fcv.MedicalSurgicalID, + fcv.ChargeCodeID, + fcv.UnitTypeID, + + fbdgt.LockType as TargetLockType, + fbdgt.LockFlag as TargetLockFlag, + --dbdgt.LockType as BudgetLockType, + --dbdgt.LockFlag as BudgetLockFlag, + fproj.LockType as ProjectionLockType, + fproj.LockFlag as ProjectionLockFlag, + + fcv.VariableDirectUnitCost, + fcv.InitialBudgetTotal, + fcv.InitialProjectionTotal, + + fbdgt.AdjustedValueTotal, + + dbdgt.AdjustedValueTotal as ManagerAdjustedValueTotal, + fproj.AdjustedValueTotal as AdjustedProjectionValueTotal, + dproj.AdjustedValueTotal as ManagerAdjustedProjectionValueTotal, + + hist.ActualYTDValueTotal, + hist.PriorYearActualValueTotal, + hist.CurrentYearBudgetValueTotal AS CurrentYearBudgetTotal, + + fbdgt.AdjustedValue01, + fbdgt.AdjustedValue02, + fbdgt.AdjustedValue03, + fbdgt.AdjustedValue04, + fbdgt.AdjustedValue05, + fbdgt.AdjustedValue06, + fbdgt.AdjustedValue07, + fbdgt.AdjustedValue08, + fbdgt.AdjustedValue09, + fbdgt.AdjustedValue10, + fbdgt.AdjustedValue11, + fbdgt.AdjustedValue12, + + dbdgt.AdjustedValue01 AS ManagerAdjustedValue01, + dbdgt.AdjustedValue02 AS ManagerAdjustedValue02, + dbdgt.AdjustedValue03 AS ManagerAdjustedValue03, + dbdgt.AdjustedValue04 AS ManagerAdjustedValue04, + dbdgt.AdjustedValue05 AS ManagerAdjustedValue05, + dbdgt.AdjustedValue06 AS ManagerAdjustedValue06, + dbdgt.AdjustedValue07 AS ManagerAdjustedValue07, + dbdgt.AdjustedValue08 AS ManagerAdjustedValue08, + dbdgt.AdjustedValue09 AS ManagerAdjustedValue09, + dbdgt.AdjustedValue10 AS ManagerAdjustedValue10, + dbdgt.AdjustedValue11 AS ManagerAdjustedValue11, + dbdgt.AdjustedValue12 AS ManagerAdjustedValue12, + + fproj.AdjustedValue01 AS AdjustedProjectionValue01, + fproj.AdjustedValue02 AS AdjustedProjectionValue02, + fproj.AdjustedValue03 AS AdjustedProjectionValue03, + fproj.AdjustedValue04 AS AdjustedProjectionValue04, + fproj.AdjustedValue05 AS AdjustedProjectionValue05, + fproj.AdjustedValue06 AS AdjustedProjectionValue06, + fproj.AdjustedValue07 AS AdjustedProjectionValue07, + fproj.AdjustedValue08 AS AdjustedProjectionValue08, + fproj.AdjustedValue09 AS AdjustedProjectionValue09, + fproj.AdjustedValue10 AS AdjustedProjectionValue10, + fproj.AdjustedValue11 AS AdjustedProjectionValue11, + fproj.AdjustedValue12 AS AdjustedProjectionValue12 + FROM + [fp].[ArchiveFactChargeVolume] fcv with (readuncommitted) + INNER JOIN [fp].[ArchiveFactChargeVolumeBudget] fbdgt with (readuncommitted) ON fcv.ChargeVolumeID = fbdgt.ChargeVolumeID and fbdgt.BudgetPhaseID = 2 + INNER JOIN [fp].[ArchiveFactChargeVolumeBudget] dbdgt with (readuncommitted) ON fcv.ChargeVolumeID = dbdgt.ChargeVolumeID and dbdgt.BudgetPhaseID = 3 + INNER JOIN [fp].[ArchiveFactChargeVolumeProjection] fproj with (readuncommitted) ON fcv.ChargeVolumeID = fproj.ChargeVolumeID and fproj.BudgetPhaseID = 2 + INNER JOIN [fp].[ArchiveFactChargeVolumeProjection] dproj with (readuncommitted) ON fcv.ChargeVolumeID = dproj.ChargeVolumeID and dproj.BudgetPhaseID = 3 + INNER JOIN [fp].[ArchiveFactChargeVolumeHistory] hist with (readuncommitted) ON fcv.ChargeVolumeID = hist.ChargeVolumeID +GO + + +--------------------------------------------- + +-- fp.viewArchiveFactServiceLineEncounter_HistoryViewer +CREATE VIEW fp.viewArchiveFactServiceLineEncounter_HistoryViewer +AS +SELECT + ov.ServiceLineEncounterID, + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.PatientClassID, + ov.ServiceLineID, + ov.ServiceLineRollupID, + ov.AgeCohortID, + ov.MedicalSurgicalID, + ov.DepartmentID, + ov.PayorID, + ov.PayorGroupID, + ov.MSDRGID, + ov.CPTID, + ov.ProviderID, + ov.PhysicianSpecialtyID, + ov.UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + ov.FiscalMonthID, + LockType, + ov.InitialValue AS OriginalValue, + v.Value, + mgrv.ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT + ServiceLineEncounterID, + BudgetConfigID, + EntityGroupConfigID, + EntityID, + PatientClassID, + ServiceLineID, + ServiceLineRollupID, + AgeCohortID, + MedicalSurgicalID, + DepartmentID, + PayorID, + PayorGroupID, + MSDRGID, + CPTID, + ProviderID, + PhysicianSpecialtyID, + UnitTypeID, + m.FiscalMonthID, + f.InitialValue + FROM ( + SELECT sle.* + FROM fp.ArchiveFactServiceLineEncounter sle ) sle + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT + ServiceLineEncounterID, + BudgetConfigID, + EntityGroupConfigID, + EntityID, + PatientClassID, + ServiceLineID, + ServiceLineRollupID, + AgeCohortID, + MedicalSurgicalID, + DepartmentID, + PayorID, + PayorGroupID, + MSDRGID, + CPTID, + ProviderID, + PhysicianSpecialtyID, + UnitTypeID, + m.FiscalMonthID, + f.Value, + LockType + FROM ( + SELECT sle.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.ArchiveFactServiceLineEncounter sle + INNER JOIN fp.ArchiveFactServiceLineEncounterBudget bdgt ON sle.ServiceLineEncounterID = bdgt.ServiceLineEncounterID + WHERE bdgt.BudgetPhaseID = 2 + ) sle + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.BudgetConfigID = v.BudgetConfigID + AND ov.EntityGroupConfigID = v.EntityGroupConfigID + AND ov.EntityID = v.EntityID + AND ov.PatientClassID = v.PatientClassID + AND ov.ServiceLineID = v.ServiceLineID + AND ov.ServiceLineRollupID = v.ServiceLineRollupID + AND ov.AgeCohortID = v.AgeCohortID + AND ov.MedicalSurgicalID = v.MedicalSurgicalID + AND ov.DepartmentID = v.DepartmentID + AND ov.PayorID = v.PayorID + AND ov.PayorGroupID = v.PayorGroupID + AND ov.MSDRGID = v.MSDRGID + AND ov.CPTID = v.CPTID + AND ov.ProviderID = v.ProviderID + AND ov.PhysicianSpecialtyID = v.PhysicianSpecialtyID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN ( + -- Unpivot for ManagerValue + SELECT + ServiceLineEncounterID, + BudgetConfigID, + EntityGroupConfigID, + EntityID, + PatientClassID, + ServiceLineID, + ServiceLineRollupID, + AgeCohortID, + MedicalSurgicalID, + DepartmentID, + PayorID, + PayorGroupID, + MSDRGID, + CPTID, + ProviderID, + PhysicianSpecialtyID, + UnitTypeID, + m.FiscalMonthID, + f.Value AS ManagerValue + FROM ( + SELECT sle.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.ArchiveFactServiceLineEncounter sle + INNER JOIN fp.ArchiveFactServiceLineEncounterBudget bdgt ON sle.ServiceLineEncounterID = bdgt.ServiceLineEncounterID + WHERE bdgt.BudgetPhaseID = 3 + ) sle + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.EntityGroupConfigID = mgrv.EntityGroupConfigID + AND ov.EntityID = mgrv.EntityID + AND ov.PatientClassID = mgrv.PatientClassID + AND ov.ServiceLineID = mgrv.ServiceLineID + AND ov.ServiceLineRollupID = mgrv.ServiceLineRollupID + AND ov.AgeCohortID = mgrv.AgeCohortID + AND ov.MedicalSurgicalID = mgrv.MedicalSurgicalID + AND ov.DepartmentID = mgrv.DepartmentID + AND ov.PayorID = mgrv.PayorID + AND ov.PayorGroupID = mgrv.PayorGroupID + AND ov.MSDRGID = mgrv.MSDRGID + AND ov.CPTID = mgrv.CPTID + AND ov.ProviderID = mgrv.ProviderID + AND ov.PhysicianSpecialtyID = mgrv.PhysicianSpecialtyID + AND ov.UnitTypeID = mgrv.UnitTypeID + AND ov.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewArchiveFactServiceLineEncounter_Pivoted +CREATE VIEW fp.viewArchiveFactServiceLineEncounter_Pivoted +AS +SELECT + sl.ServiceLineEncounterID, + sl.BudgetConfigID, + sl.EntityGroupConfigID, + sl.EntityID, + sl.PatientClassID, + sl.ServiceLineID, + sl.ServiceLineRollupID, + sl.AgeCohortID, + sl.MedicalSurgicalID, + sl.DepartmentID, + sl.PayorID, + sl.PayorGroupID, + sl.MSDRGID, + sl.CPTID, + sl.ProviderID, + sl.PhysicianSpecialtyID, + sl.UnitTypeID, + + tbdgt.LockType as TargetLockType, + tbdgt.LockFlag as TargetLockFlag, + fbdgt.LockType as BudgetLockType, + fbdgt.LockFlag as BudgetLockFlag, + tproj.LockType as ProjectionLockType, + tproj.LockFlag as ProjectionLockFlag, + + tbdgt.AdjustedValueTotal, + fbdgt.AdjustedValueTotal as ManagerAdjustedValueTotal, + + tproj.AdjustedValueTotal as AdjustedProjectionValueTotal, + + hist.PriorYearActualValueTotal as PriorYearActualValueTotal, + hist.ActualYTDValueTotal as ActualYTDValueTotal, + hist.CurrentYearBudgetTotal as CurrentYearBudgetTotal, + + sl.SampledBudgetTotal, + sl.InitialBudgetTotal, + sl.InitialProjectionTotal, + + tbdgt.AdjustedValue01, tbdgt.AdjustedValue02, tbdgt.AdjustedValue03, tbdgt.AdjustedValue04, tbdgt.AdjustedValue05, tbdgt.AdjustedValue06, tbdgt.AdjustedValue07, tbdgt.AdjustedValue08, tbdgt.AdjustedValue09, tbdgt.AdjustedValue10, tbdgt.AdjustedValue11, tbdgt.AdjustedValue12, + fbdgt.AdjustedValue01 AS ManagerAdjustedValue01, fbdgt.AdjustedValue02 AS ManagerAdjustedValue02, fbdgt.AdjustedValue03 AS ManagerAdjustedValue03, fbdgt.AdjustedValue04 AS ManagerAdjustedValue04, fbdgt.AdjustedValue05 AS ManagerAdjustedValue05, fbdgt.AdjustedValue06 AS ManagerAdjustedValue06, fbdgt.AdjustedValue07 AS ManagerAdjustedValue07, fbdgt.AdjustedValue08 AS ManagerAdjustedValue08, fbdgt.AdjustedValue09 AS ManagerAdjustedValue09, fbdgt.AdjustedValue10 AS ManagerAdjustedValue10, fbdgt.AdjustedValue11 AS ManagerAdjustedValue11, fbdgt.AdjustedValue12 AS ManagerAdjustedValue12, + tproj.AdjustedValue01 AS AdjustedProjectionValue01, tproj.AdjustedValue02 AS AdjustedProjectionValue02, tproj.AdjustedValue03 AS AdjustedProjectionValue03, tproj.AdjustedValue04 AS AdjustedProjectionValue04, tproj.AdjustedValue05 AS AdjustedProjectionValue05, tproj.AdjustedValue06 AS AdjustedProjectionValue06, tproj.AdjustedValue07 AS AdjustedProjectionValue07, tproj.AdjustedValue08 AS AdjustedProjectionValue08, tproj.AdjustedValue09 AS AdjustedProjectionValue09, tproj.AdjustedValue10 AS AdjustedProjectionValue10, tproj.AdjustedValue11 AS AdjustedProjectionValue11, tproj.AdjustedValue12 AS AdjustedProjectionValue12 + +From fp.ArchiveFactServiceLineEncounter sl + INNER JOIN fp.ArchiveFactServiceLineEncounterBudget tbdgt ON sl.ServiceLineEncounterID = tbdgt.ServiceLineEncounterID AND tbdgt.BudgetPhaseID = 2 + INNER JOIN fp.ArchiveFactServiceLineEncounterBudget fbdgt ON sl.ServiceLineEncounterID = fbdgt.ServiceLineEncounterID AND fbdgt.BudgetPhaseID = 3 + INNER JOIN fp.ArchiveFactServiceLineEncounterProjection tproj ON sl.ServiceLineEncounterID = tproj.ServiceLineEncounterID AND tproj.BudgetPhaseID = 2 + INNER JOIN fp.ArchiveFactServiceLineEncounterHistory hist ON sl.ServiceLineEncounterID = hist.ServiceLineEncounterID +GO + + +--------------------------------------------- + +-- fp.viewArchiveFactStaffingBudget_HistoryViewer +CREATE VIEW fp.viewArchiveFactStaffing_HistoryViewer +AS +SELECT + ov.StaffingID, + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.DepartmentID, + ov.JobCodeID, + ov.PayCodeGroupID, + ov.ProductiveClassID, + ov.VariabilityID, + ov.ProviderID, ov.ProviderTypeID, ov.ProviderSpecialtyID, ov.ProviderLineItemID, ov.SubsectionID, + ov.UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + ov.FiscalMonthID, + LockType, + ov.InitialValue AS OriginalValue, + v.Value, + mgrv.ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT StaffingID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, VariabilityID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT fs.* + FROM fp.ArchiveFactStaffing fs ) fs + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT StaffingID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, VariabilityID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT fs.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.ArchiveFactStaffing fs + INNER JOIN fp.ArchiveFactStaffingBudget bdgt ON fs.StaffingID = bdgt.StaffingID + WHERE bdgt.BudgetPhaseID = 2) fs + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.DepartmentID = v.DepartmentID + AND ov.JobCodeID = v.JobCodeID + AND ov.BudgetConfigID = v.BudgetConfigID + AND ov.PayCodeGroupID = v.PayCodeGroupID + AND ov.ProductiveClassID = v.ProductiveClassID + AND ov.VariabilityID = v.VariabilityID + AND ov.ProviderID = v.ProviderID + AND ov.ProviderTypeID = v.ProviderTypeID + AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID + AND ov.ProviderLineItemID = v.ProviderLineItemID + AND ov.SubsectionID = v.SubsectionID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN ( + -- Unpivot for ManagerValue + SELECT StaffingID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, VariabilityID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.Value AS ManagerValue + FROM ( + SELECT fs.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.ArchiveFactStaffing fs + INNER JOIN fp.ArchiveFactStaffingBudget bdgt ON fs.StaffingID = bdgt.StaffingID + WHERE bdgt.BudgetPhaseID = 3) fs + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON ov.DepartmentID = mgrv.DepartmentID + AND ov.JobCodeID = mgrv.JobCodeID + AND ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.ProductiveClassID = mgrv.ProductiveClassID + AND ov.PayCodeGroupID = v.PayCodeGroupID + AND ov.VariabilityID = mgrv.VariabilityID + AND ov.ProviderID = v.ProviderID + AND ov.ProviderTypeID = v.ProviderTypeID + AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID + AND ov.ProviderLineItemID = v.ProviderLineItemID + AND ov.SubsectionID = v.SubsectionID + AND ov.UnitTypeID = mgrv.UnitTypeID + AND ov.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewArchiveFactStaffingProjection_HistoryViewer +CREATE VIEW [fp].[viewArchiveFactStaffingProjection_HistoryViewer] +AS +SELECT + ov.StaffingID, + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.DepartmentID, + ov.JobCodeID, + ov.PayCodeGroupID, + ov.ProductiveClassID, + ov.VariabilityID, + ov.ProviderID, ov.ProviderTypeID, ov.ProviderSpecialtyID, ov.ProviderLineItemID, ov.SubsectionID, + ov.UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID, + ov.FiscalMonthID, + LockType, + ov.InitialValue AS OriginalValue, + v.Value, + mgrv.ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT StaffingID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, VariabilityID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT fs.* + FROM fp.ArchiveFactStaffing fs ) fs + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT StaffingID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, VariabilityID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT fs.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.ArchiveFactStaffing fs + INNER JOIN fp.ArchiveFactStaffingProjection bdgt ON fs.StaffingID = bdgt.StaffingID + WHERE bdgt.BudgetPhaseID = 2) fs + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.DepartmentID = v.DepartmentID + AND ov.JobCodeID = v.JobCodeID + AND ov.BudgetConfigID = v.BudgetConfigID + AND ov.PayCodeGroupID = v.PayCodeGroupID + AND ov.ProductiveClassID = v.ProductiveClassID + AND ov.VariabilityID = v.VariabilityID + AND ov.ProviderID = v.ProviderID + AND ov.ProviderTypeID = v.ProviderTypeID + AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID + AND ov.ProviderLineItemID = v.ProviderLineItemID + AND ov.SubsectionID = v.SubsectionID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN ( + -- Unpivot for ManagerValue + SELECT StaffingID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, VariabilityID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.Value AS ManagerValue + FROM ( + SELECT fs.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.ArchiveFactStaffing fs + INNER JOIN fp.ArchiveFactStaffingProjection bdgt ON fs.StaffingID = bdgt.StaffingID + WHERE bdgt.BudgetPhaseID = 3) fs + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON ov.DepartmentID = mgrv.DepartmentID + AND ov.JobCodeID = mgrv.JobCodeID + AND ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.ProductiveClassID = mgrv.ProductiveClassID + AND ov.PayCodeGroupID = v.PayCodeGroupID + AND ov.VariabilityID = mgrv.VariabilityID + AND ov.ProviderID = v.ProviderID + AND ov.ProviderTypeID = v.ProviderTypeID + AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID + AND ov.ProviderLineItemID = v.ProviderLineItemID + AND ov.SubsectionID = v.SubsectionID + AND ov.UnitTypeID = mgrv.UnitTypeID + AND ov.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewArchiveFactStaffing_Pivoted +CREATE VIEW fp.viewArchiveFactStaffing_Pivoted +AS + +with WageRate as ( + SELECT + BudgetConfigID, EntityGroupConfigID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, + ProviderID, + ProviderTypeID, + ProviderSpecialtyID, + ProviderLineItemID, + SubsectionID, + bTarg.LockType as TargetLockType, + bTarg.LockFlag as TargetLockFlag, + bFinal.LockType as BudgetLockType, + bFinal.LockFlag as BudgetLockFlag, + pFinal.LockType as ProjectionLockType, + pFinal.LockFlag as ProjectionLockFlag + FROM [fp].[ArchiveFactStaffing] (READUNCOMMITTED) fs + INNER JOIN [fp].[ArchiveFactStaffingBudget] (READUNCOMMITTED) bTarg ON fs.StaffingID = bTarg.StaffingID AND bTarg.BudgetPhaseID = 2 + INNER JOIN [fp].[ArchiveFactStaffingBudget] (READUNCOMMITTED) bFinal ON fs.StaffingID = bFinal.StaffingID AND bFinal.BudgetPhaseID = 3 + INNER JOIN [fp].[ArchiveFactStaffingProjection] (READUNCOMMITTED) pTarg ON fs.StaffingID = pTarg.StaffingID AND pTarg.BudgetPhaseID = 2 + INNER JOIN [fp].[ArchiveFactStaffingProjection] (READUNCOMMITTED) pFinal ON fs.StaffingID = pFinal.StaffingID AND pFinal.BudgetPhaseID = 3 + WHERE fs.UnitTypeID = 159 +) +SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.ProductiveClassID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.SubsectionID, + fs.VariabilityID, + fs.UnitTypeID, + + bTarg.LockType as TargetLockType, + bTarg.LockFlag as TargetLockFlag, + bFinal.LockType as BudgetLockType, + bFinal.LockFlag as BudgetLockFlag, + pFinal.LockType as ProjectionLockType, + pFinal.LockFlag as ProjectionLockFlag, + + CASE WHEN bFinal.LockType = 6 THEN 1 ELSE 0 END AS BudgetSpreadsLockFlag, + + CASE WHEN bFinal.LockType = 7 THEN 1 ELSE 0 END AS BudgetAdjustmentLockFlag, + CASE WHEN bTarg.LockType = 7 THEN 1 ELSE 0 END AS TargetAdjustmentLockFlag, + CASE WHEN pFinal.LockType = 7 THEN 1 ELSE 0 END AS ProjectionAdjustmentLockFlag, + + wr.TargetLockType as WageRateTargetLockType, + wr.TargetLockFlag as WageRateTargetLockFlag, + wr.BudgetLockType as WageRateBudgetLockType, + wr.BudgetLockFlag as WageRateBudgetLockFlag, + wr.ProjectionLockType as WageRateProjectionLockType, + wr.ProjectionLockFlag as WageRateProjectionLockFlag, + + bTarg.AdjustedValueTotal, + + bFinal.AdjustedValueTotal as ManagerAdjustedValueTotal, + pFinal.AdjustedValueTotal as ManagerAdjustedProjectionValueTotal, + + pTarg.AdjustedValueTotal as AdjustedProjectionValueTotal, + + hist.ActualYTDValueTotal, + hist.CurrentYearBudgetTotal, + hist.PriorYearActualValueTotal, + + fs.InitialBudgetTotal, + fs.InitialProjectionTotal, + + -- Target Montly Values + bTarg.AdjustedValue01 AS AdjustedValue01, + bTarg.AdjustedValue02 AS AdjustedValue02, + bTarg.AdjustedValue03 AS AdjustedValue03, + bTarg.AdjustedValue04 AS AdjustedValue04, + bTarg.AdjustedValue05 AS AdjustedValue05, + bTarg.AdjustedValue06 AS AdjustedValue06, + bTarg.AdjustedValue07 AS AdjustedValue07, + bTarg.AdjustedValue08 AS AdjustedValue08, + bTarg.AdjustedValue09 AS AdjustedValue09, + bTarg.AdjustedValue10 AS AdjustedValue10, + bTarg.AdjustedValue11 AS AdjustedValue11, + bTarg.AdjustedValue12 AS AdjustedValue12, + + -- Budgeted Monthly Values + bFinal.AdjustedValue01 AS ManagerAdjustedValue01, + bFinal.AdjustedValue02 AS ManagerAdjustedValue02, + bFinal.AdjustedValue03 AS ManagerAdjustedValue03, + bFinal.AdjustedValue04 AS ManagerAdjustedValue04, + bFinal.AdjustedValue05 AS ManagerAdjustedValue05, + bFinal.AdjustedValue06 AS ManagerAdjustedValue06, + bFinal.AdjustedValue07 AS ManagerAdjustedValue07, + bFinal.AdjustedValue08 AS ManagerAdjustedValue08, + bFinal.AdjustedValue09 AS ManagerAdjustedValue09, + bFinal.AdjustedValue10 AS ManagerAdjustedValue10, + bFinal.AdjustedValue11 AS ManagerAdjustedValue11, + bFinal.AdjustedValue12 AS ManagerAdjustedValue12, + + -- Projected Monthly Values + pTarg.AdjustedValue01 AS AdjustedProjectionValue01, + pTarg.AdjustedValue02 AS AdjustedProjectionValue02, + pTarg.AdjustedValue03 AS AdjustedProjectionValue03, + pTarg.AdjustedValue04 AS AdjustedProjectionValue04, + pTarg.AdjustedValue05 AS AdjustedProjectionValue05, + pTarg.AdjustedValue06 AS AdjustedProjectionValue06, + pTarg.AdjustedValue07 AS AdjustedProjectionValue07, + pTarg.AdjustedValue08 AS AdjustedProjectionValue08, + pTarg.AdjustedValue09 AS AdjustedProjectionValue09, + pTarg.AdjustedValue10 AS AdjustedProjectionValue10, + pTarg.AdjustedValue11 AS AdjustedProjectionValue11, + pTarg.AdjustedValue12 AS AdjustedProjectionValue12, + + pFinal.AdjustedValue01 AS ManagerAdjustedProjectionValue01, + pFinal.AdjustedValue02 AS ManagerAdjustedProjectionValue02, + pFinal.AdjustedValue03 AS ManagerAdjustedProjectionValue03, + pFinal.AdjustedValue04 AS ManagerAdjustedProjectionValue04, + pFinal.AdjustedValue05 AS ManagerAdjustedProjectionValue05, + pFinal.AdjustedValue06 AS ManagerAdjustedProjectionValue06, + pFinal.AdjustedValue07 AS ManagerAdjustedProjectionValue07, + pFinal.AdjustedValue08 AS ManagerAdjustedProjectionValue08, + pFinal.AdjustedValue09 AS ManagerAdjustedProjectionValue09, + pFinal.AdjustedValue10 AS ManagerAdjustedProjectionValue10, + pFinal.AdjustedValue11 AS ManagerAdjustedProjectionValue11, + pFinal.AdjustedValue12 AS ManagerAdjustedProjectionValue12 +FROM [fp].[ArchiveFactStaffing] fs (READUNCOMMITTED) + INNER JOIN [fp].[ArchiveFactStaffingBudget] (READUNCOMMITTED) bTarg ON fs.StaffingID = bTarg.StaffingID AND bTarg.BudgetPhaseID = 2 + INNER JOIN [fp].[ArchiveFactStaffingBudget] (READUNCOMMITTED) bFinal ON fs.StaffingID = bFinal.StaffingID AND bFinal.BudgetPhaseID = 3 + INNER JOIN [fp].[ArchiveFactStaffingProjection] (READUNCOMMITTED) pTarg ON fs.StaffingID = pTarg.StaffingID AND pTarg.BudgetPhaseID = 2 + INNER JOIN [fp].[ArchiveFactStaffingProjection] (READUNCOMMITTED) pFinal ON fs.StaffingID = pFinal.StaffingID AND pFinal.BudgetPhaseID = 3 + INNER JOIN [fp].[ArchiveFactStaffingHistory] hist (READUNCOMMITTED) ON fs.StaffingID = hist.StaffingID + INNER JOIN WageRate wr + ON fs.BudgetConfigID = wr.BudgetConfigID + AND fs.EntityGroupConfigID = wr.EntityGroupConfigID + AND fs.DepartmentID = wr.DepartmentID + AND fs.JobCodeID = wr.JobCodeID + AND fs.PayCodeGroupID = wr.PayCodeGroupID + AND fs.ProductiveClassID = wr.ProductiveClassID + AND fs.ProviderID = wr.ProviderID + AND fs.ProviderTypeID = wr.ProviderTypeID + AND fs.ProviderSpecialtyID = wr.ProviderSpecialtyID + AND fs.ProviderLineItemID = wr.ProviderLineItemID + AND fs.SubsectionID = wr.SubsectionID +GO + + +--------------------------------------------- + +-- fp.viewArchiveFactStatisticsBudget_HistoryViewer +CREATE VIEW fp.viewArchiveFactStatistics_HistoryViewer +AS +SELECT + ov.StatisticsID, + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.DepartmentID, + ov.AccountID, + ov.FinancialReportingID, + ov.PatientClassID, + ov.PayorID, + ov.ProviderID, + ov.ProviderTypeID, + ov.ProviderSpecialtyID, + ov.ProviderLineItemID, + ov.SubsectionID, + ov.UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + ov.FiscalMonthID, + LockType, + ov.InitialValue AS OriginalValue, + v.Value, + mgrv.ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, UnitTypeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT gl.* + FROM fp.ArchiveFactStatistics gl ) gl + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, UnitTypeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT gl.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.ArchiveFactStatistics gl + INNER JOIN fp.ArchiveFactStatisticsBudget bdgt ON gl.StatisticsID = bdgt.StatisticsID + WHERE bdgt.BudgetPhaseID = 2) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.DepartmentID = v.DepartmentID + AND ov.AccountID = v.AccountID + AND ov.BudgetConfigID = v.BudgetConfigID + AND ov.PatientClassID = v.PatientClassID + AND ov.PayorID = v.PayorID + AND ov.ProviderID = v.ProviderID + AND ov.ProviderTypeID = v.ProviderTypeID + AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID + AND ov.ProviderLineItemID = v.ProviderLineItemID + AND ov.SubsectionID = v.SubsectionID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN ( + -- Unpivot for ManagerValue + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.Value AS ManagerValue + FROM ( + SELECT gl.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.ArchiveFactStatistics gl + INNER JOIN fp.ArchiveFactStatisticsBudget bdgt ON gl.StatisticsID = bdgt.StatisticsID + WHERE bdgt.BudgetPhaseID = 3) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON ov.DepartmentID = mgrv.DepartmentID + AND ov.AccountID = mgrv.AccountID + AND ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.PatientClassID = mgrv.PatientClassID + AND ov.PayorID = mgrv.PayorID + AND ov.ProviderID = v.ProviderID + AND ov.ProviderTypeID = v.ProviderTypeID + AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID + AND ov.ProviderLineItemID = v.ProviderLineItemID + AND ov.SubsectionID = v.SubsectionID + AND ov.UnitTypeID = mgrv.UnitTypeID + AND ov.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewArchiveFactStatisticsProjection_HistoryViewer +CREATE VIEW fp.viewArchiveFactStatisticsProjection_HistoryViewer +AS +SELECT + ov.StatisticsID, + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.DepartmentID, + ov.AccountID, + ov.FinancialReportingID, + ov.PatientClassID, + ov.PayorID, + ov.ProviderID, + ov.ProviderTypeID, + ov.ProviderSpecialtyID, + ov.ProviderLineItemID, + ov.SubsectionID, + ov.UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID, + ov.FiscalMonthID, + LockType, + ov.InitialValue AS OriginalValue, + v.Value, + mgrv.ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, UnitTypeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT gl.* + FROM fp.ArchiveFactStatistics gl ) gl + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, UnitTypeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT gl.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.ArchiveFactStatistics gl + INNER JOIN fp.ArchiveFactStatisticsProjection bdgt ON gl.StatisticsID = bdgt.StatisticsID + WHERE bdgt.BudgetPhaseID = 2) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.DepartmentID = v.DepartmentID + AND ov.AccountID = v.AccountID + AND ov.BudgetConfigID = v.BudgetConfigID + AND ov.PatientClassID = v.PatientClassID + AND ov.PayorID = v.PayorID + AND ov.ProviderID = v.ProviderID + AND ov.ProviderTypeID = v.ProviderTypeID + AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID + AND ov.ProviderLineItemID = v.ProviderLineItemID + AND ov.SubsectionID = v.SubsectionID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN ( + -- Unpivot for ManagerValue + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, m.FiscalMonthID, f.Value AS ManagerValue + FROM ( + SELECT gl.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.ArchiveFactStatistics gl + INNER JOIN fp.ArchiveFactStatisticsProjection bdgt ON gl.StatisticsID = bdgt.StatisticsID + WHERE bdgt.BudgetPhaseID = 3) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON ov.DepartmentID = mgrv.DepartmentID + AND ov.AccountID = mgrv.AccountID + AND ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.PatientClassID = mgrv.PatientClassID + AND ov.PayorID = mgrv.PayorID + AND ov.ProviderID = v.ProviderID + AND ov.ProviderTypeID = v.ProviderTypeID + AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID + AND ov.ProviderLineItemID = v.ProviderLineItemID + AND ov.SubsectionID = v.SubsectionID + AND ov.UnitTypeID = mgrv.UnitTypeID + AND ov.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewArchiveFactStatistics_Pivoted +CREATE VIEW [fp].[viewArchiveFactStatistics_Pivoted] +AS +SELECT + stat.StatisticsID, + stat.BudgetConfigID, + stat.EntityGroupConfigID, + stat.DepartmentID, + stat.FinancialReportingID, + stat.PayorID, + stat.PatientClassID, + stat.EntityID, + stat.AccountID, + bc.FiscalYearID, + stat.UnitTypeID, + stat.ProviderID, + stat.ProviderTypeID, + stat.ProviderSpecialtyID, + stat.ProviderLineItemID, + stat.SubsectionID, + fbdgt.LockType as BudgetLockType, + fbdgt.LockFlag as BudgetLockFlag, + fproj.LockType as ProjectionLockType, + fproj.LockFlag as ProjectionLockFlag, + + CASE WHEN dbdgt.LockType = 7 THEN 1 ELSE 0 END AS BudgetAdjustmentLockFlag, + CASE WHEN fbdgt.LockType = 7 THEN 1 ELSE 0 END AS TargetAdjustmentLockFlag, + CASE WHEN dproj.LockType = 7 THEN 1 ELSE 0 END AS ProjectionAdjustmentLockFlag, + + fbdgt.AdjustedValueTotal, + dbdgt.AdjustedValueTotal as ManagerAdjustedValueTotal, + + fproj.AdjustedValueTotal as AdjustedProjectionValueTotal, + dproj.AdjustedValueTotal as ManagerAdjustedProjectionValueTotal, + + hist.PriorYearActualValueTotal as PriorYearActualValueTotal, + hist.ActualYTDValueTotal as ActualYTDValueTotal, + hist.CurrentYearBudgetTotal as CurrentYearBudgetTotal, + + stat.InitialBudgetTotal, + stat.InitialProjectionTotal, + + dbdgt.AdjustedValue01 AS ManagerAdjustedValue01, dbdgt.AdjustedValue02 AS ManagerAdjustedValue02, dbdgt.AdjustedValue03 AS ManagerAdjustedValue03, dbdgt.AdjustedValue04 AS ManagerAdjustedValue04, dbdgt.AdjustedValue05 AS ManagerAdjustedValue05, dbdgt.AdjustedValue06 AS ManagerAdjustedValue06, dbdgt.AdjustedValue07 AS ManagerAdjustedValue07, dbdgt.AdjustedValue08 AS ManagerAdjustedValue08, dbdgt.AdjustedValue09 AS ManagerAdjustedValue09, dbdgt.AdjustedValue10 AS ManagerAdjustedValue10, dbdgt.AdjustedValue11 AS ManagerAdjustedValue11, dbdgt.AdjustedValue12 AS ManagerAdjustedValue12, + + fbdgt.AdjustedValue01, fbdgt.AdjustedValue02, fbdgt.AdjustedValue03, fbdgt.AdjustedValue04, fbdgt.AdjustedValue05, fbdgt.AdjustedValue06, fbdgt.AdjustedValue07, fbdgt.AdjustedValue08, fbdgt.AdjustedValue09, fbdgt.AdjustedValue10, fbdgt.AdjustedValue11, fbdgt.AdjustedValue12, + fproj.AdjustedValue01 as AdjustedProjectionValue01, fproj.AdjustedValue02 as AdjustedProjectionValue02, fproj.AdjustedValue03 as AdjustedProjectionValue03, fproj.AdjustedValue04 as AdjustedProjectionValue04, fproj.AdjustedValue05 as AdjustedProjectionValue05, fproj.AdjustedValue06 as AdjustedProjectionValue06, fproj.AdjustedValue07 as AdjustedProjectionValue07, fproj.AdjustedValue08 as AdjustedProjectionValue08, fproj.AdjustedValue09 as AdjustedProjectionValue09, fproj.AdjustedValue10 as AdjustedProjectionValue10, fproj.AdjustedValue11 as AdjustedProjectionValue11, fproj.AdjustedValue12 as AdjustedProjectionValue12, + dproj.AdjustedValue01 as ManagerAdjustedProjectionValue01, dproj.AdjustedValue02 as ManagerAdjustedProjectionValue02, dproj.AdjustedValue03 as ManagerAdjustedProjectionValue03, dproj.AdjustedValue04 as ManagerAdjustedProjectionValue04, dproj.AdjustedValue05 as ManagerAdjustedProjectionValue05, dproj.AdjustedValue06 as ManagerAdjustedProjectionValue06, dproj.AdjustedValue07 as ManagerAdjustedProjectionValue07, dproj.AdjustedValue08 as ManagerAdjustedProjectionValue08, dproj.AdjustedValue09 as ManagerAdjustedProjectionValue09, dproj.AdjustedValue10 as ManagerAdjustedProjectionValue10, dproj.AdjustedValue11 as ManagerAdjustedProjectionValue11, dproj.AdjustedValue12 as ManagerAdjustedProjectionValue12 +FROM + fp.ArchiveFactStatistics stat + INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON stat.BudgetConfigID = bc.BudgetConfigID + INNER JOIN fp.ArchiveFactStatisticsBudget fbdgt with (readuncommitted) ON stat.StatisticsID = fbdgt.StatisticsID and fbdgt.BudgetPhaseID = 2 + INNER JOIN fp.ArchiveFactStatisticsBudget dbdgt with (readuncommitted) ON stat.StatisticsID = dbdgt.StatisticsID and dbdgt.BudgetPhaseID = 3 + INNER JOIN fp.ArchiveFactStatisticsProjection fproj with (readuncommitted) ON stat.StatisticsID = fproj.StatisticsID and fproj.BudgetPhaseID = 2 + INNER JOIN fp.ArchiveFactStatisticsProjection dproj with (readuncommitted) ON stat.StatisticsID = dproj.StatisticsID and dproj.BudgetPhaseID = 3 + INNER JOIN fp.ArchiveFactStatisticsHistory hist with (readuncommitted) ON stat.StatisticsID = hist.StatisticsID +GO + + +--------------------------------------------- + +-- fp.viewBaseBudgetSnapshotWithNameConcat +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2024-12-04 MY JAZZ-80433 Initial +*************************************************************/ +-- This is needed because otherwise score blows up on trying to find the column +CREATE VIEW [fp].[viewBaseBudgetSnapshotWithNameConcat] +AS + SELECT + SnapshotID, + BudgetConfigID, + MemberGUID, + AuthorGUID, + AuthorName, + AdjustmentsStampedOff, + DateCreatedUTC, + DateProcessedUTC, + -- Only doing this because I know if we don't CCHS will complain about the date format in the EU + (Name + ' - ' + CASE WHEN ISNULL((SELECT Value FROM fw.SystemSetting WHERE Name = 'System Culture'), 'en-US') = 'en-US' + THEN FORMAT(DateCreatedUTC, 'MM-dd-yyyy HH:mm:ss') + ELSE FORMAT(DateCreatedUTC, 'yyyy-MM-dd HH:mm:ss') END) AS Name, + Comment, + '00000000-0000-0000-0000-000000000000' AS HistoryItemGUID, + TransactionID + FROM [fp].[BudgetSnapshot] +GO + + +--------------------------------------------- + +-- fp.viewBenefitsAccounts +CREATE VIEW [fp].[viewBenefitsAccounts] +AS + SELECT acc.* + FROM [fw].[DimAccount] acc + INNER JOIN [ob].[DimAccountPH] aph ON acc.OBAccountPHID = aph.AccountPHID + WHERE aph.Name LIKE '%Benefits%' +GO + + +--------------------------------------------- + +-- fp.viewBenefitsAdjustment +CREATE VIEW fp.viewBenefitsAdjustment +AS +SELECT [AdjustmentGUID] + ,[BudgetConfigGUID] + ,[AdjustmentType] + ,[Value] + ,[AdjustmentFilterJSON] + ,[GroupingHierarchyJSON] + ,[AdjustedProperty] + ,[Comment] + ,[AuthorGUID] + ,[AuthorFullName] + ,[LastModifiedDateUtc] + ,[DateCreatedUtc] + ,[GroupingGUID] + ,[UnitTypeID] + ,[TimeClassID] + ,[BudgetPhaseID] + ,[ClassificationGroupID] + ,[ClassificationCategoryID] + ,[IsRecordDeleted] + ,[DimensionMemberJson] + ,[AdjustmentID] + ,[IsErrored] +FROM [fp].[BenefitsAdjustment] +WHERE IsRecordDeleted = 0; +GO + + +--------------------------------------------- + +-- fp.viewBenefitsAdjustmentImport +CREATE VIEW fp.viewBenefitsAdjustmentImport +AS +SELECT [RowID] + ,[AdjustmentGUID] + ,[DepartmentID] + ,[AccountID] + ,[FinancialReportingID] + ,[EntityID] + ,[FiscalYearID] + ,[UnitTypeID] + ,[FiscalMonthID] + ,[Value] + ,[Version] + ,[TimeClassID] + ,[IsRecordDeleted] + ,[AdjustmentID] + FROM [fp].[BenefitsAdjustmentImport] + WHERE IsRecordDeleted = 0 +GO + + +--------------------------------------------- + +-- fp.viewBenefitsSpreadUnlockData +CREATE VIEW fp.viewBenefitsSpreadUnlockData +AS + +SELECT [RowID] + ,[BudgetConfigID] + ,[AdjustmentGUID] + ,[EntityID] + ,[DepartmentID] + ,[AccountID] + ,[FinancialReportingID] + ,[Version] + ,[Value01] + ,[Value02] + ,[Value03] + ,[Value04] + ,[Value05] + ,[Value06] + ,[Value07] + ,[Value08] + ,[Value09] + ,[Value10] + ,[Value11] + ,[Value12] + ,[IsRecordDeleted] + FROM [fp].[BenefitsSpreadUnlockData] + WHERE IsRecordDeleted = 0 +GO + + +--------------------------------------------- + +-- fp.viewBenefitsSpreads +CREATE VIEW fp.viewBenefitsSpreads +AS + SELECT [BudgetConfigID], [DepartmentID], [AccountID], [IsInactive], [SpreadPercentage01], [SpreadPercentage02], [SpreadPercentage03], [SpreadPercentage04], [SpreadPercentage05], [SpreadPercentage06], [SpreadPercentage07], [SpreadPercentage08], [SpreadPercentage09], [SpreadPercentage10], [SpreadPercentage11], [SpreadPercentage12], [TotalImportedValue] as TotalSpreadValue, [GlobalSpreadID] + FROM [fp].[BenefitsSpreads] with (readuncommitted) + WHERE GlobalSpreadID = 1 + + UNION ALL + + SELECT bs.[BudgetConfigID], [DepartmentID], [AccountID], [IsInactive], gs.[SpreadPercentage01], gs.[SpreadPercentage02], gs.[SpreadPercentage03], gs.[SpreadPercentage04], gs.[SpreadPercentage05], gs.[SpreadPercentage06], gs.[SpreadPercentage07], gs.[SpreadPercentage08], gs.[SpreadPercentage09], gs.[SpreadPercentage10], gs.[SpreadPercentage11], gs.[SpreadPercentage12], gs.TotalSpreadValue, bs.[GlobalSpreadID] + FROM [fp].[BenefitsSpreads] bs with (readuncommitted) + INNER JOIN [fp].[GlobalSpread] gs ON bs.GlobalSpreadID = gs.GlobalSpreadID + WHERE bs.GlobalSpreadID > 1 +GO + + +--------------------------------------------- + +-- fp.viewBudgetConfigSetting +CREATE VIEW fp.viewBudgetConfigSetting + AS + SELECT bc.BudgetConfigID, bc.BudgetConfigName, bc.IsActive AS BudgetConfigIsActive, def.Name, def.Description, sett.Value, def.DefaultValue + FROM [fp].[BudgetConfigSetting] sett + INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON sett.SettingID = def.SettingID + INNER JOIN [fp].[BudgetConfig] bc ON sett.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewBudgetConfig_DEBUG +CREATE VIEW fp.viewBudgetConfig_DEBUG + AS + SELECT bc.BudgetConfigGUID, bc.BudgetConfigID, bc.FiscalYearID AS BudgetConfigYear, bc.BudgetConfigName AS BCName, bc.IsActive, ec.EntityGroupConfigGUID, ec.EntityGroupConfigID, ec.Name AS ECName, ecm.Entities, + ServiceLineEncounterFiscalYearID AS SLCV_FY, ServiceLineEncounterTimeClassID AS SLCV_TC, DepartmentChargeVolumeFiscalYearID AS DCV_FY, DepartmentChargeVolumeTimeClassID AS DCV_TC, StatisticsFiscalYearID AS STAT_FY, StatisticsTimeClassID AS STAT_TC, + PayrollFiscalYearID AS PR_FY, PayrollTimeClassID AS PR_TC, BenefitsFiscalYearID AS BEN_FY, BenefitsTimeClassID AS BEN_TC, AccountFiscalYearID AS AC_FY, AccountTimeClassID AS AC_TC, CostingConfigGUID AS CostingGUID, CostingConfigTimeClassID AS Costing_TC, + ec.RevenueAndDeductionsFiscalYearID AS RANDD_FY, ec.RevenueAndDeductionsTimeClassID AS RANDD_TC, ec.IsRosterUsed, ec.IsBudgetLockDown, ec.ParentEntityGroupConfigGuid, ec.StatisticsModel, bc.MonthsLoaded + FROM [fp].[EntityGroupConfig] ec + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigGUID = ec.BudgetConfigGUID + INNER JOIN (SELECT DISTINCT EntityGroupConfigGUID, + ( + Select CAST(ecm1.EntityID AS VARCHAR(MAX)) + ',' AS [text()] + From [fp].[EntityGroupConfigMapping] ecm1 + Where ecm1.EntityGroupConfigGUID = ecm2.EntityGroupConfigGUID + ORDER BY ecm1.EntityGroupConfigGUID + For XML PATH ('') + ) Entities + From [fp].[EntityGroupConfigMapping] ecm2) ecm ON ec.EntityGroupConfigGUID = ecm.EntityGroupConfigGUID +GO + + +--------------------------------------------- + +-- fp.viewChargeVolumeAdjustmentImport_Pivoted +CREATE VIEW [fp].[viewChargeVolumeAdjustmentImport_Pivoted] + AS + SELECT + AdjustmentGUID, + DepartmentID, + ServiceLineID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + ChargeCodeID, + EntityID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + BillingCPTID, + TimeClassID, + IsRecordDeleted, + AdjustmentID, + [Month01], + [Month02], + [Month03], + [Month04], + [Month05], + [Month06], + [Month07], + [Month08], + [Month09], + [Month10], + [Month11], + [Month12] + FROM (SELECT + AdjustmentGUID, + DepartmentID, + ServiceLineID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + ChargeCodeID, + EntityID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + BillingCPTID, + TimeClassID, + IsRecordDeleted, + AdjustmentID, + m.MonthColumnName, + Value + FROM [fp].[DepartmentChargeAdjustmentImport] imp + INNER JOIN fw.DimFiscalMonth m ON m.FiscalMonthID = imp.FiscalMonthID + ) data + PIVOT (SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pvt +WHERE IsRecordDeleted = 0; +GO + + +--------------------------------------------- + +-- fp.viewChargeVolumeByPayorGroup +CREATE VIEW fp.viewChargeVolumeByPayorGroup +AS +SELECT + cv.ChargeVolumeID, + cv.BudgetConfigID, + cv.EntityGroupConfigID, + cv.EntityID, + cv.DepartmentID, + cv.ServiceLineID, + cv.PatientClassID, + cv.AgeCohortID, + cv.MedicalSurgicalID, + cv.ChargeCodeID, + cv.ServiceEntityID, + cv.MSDRGID, + cv.UBRevCodeID, + cv.PrimaryCPTID, + cv.ServiceProviderID, + cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, + cv.PerformingProviderSpecialtyID, + cv.BillingCPTID, + mix.PayorGroupID, + mix.BudgetMixPercentage, + cv.BudgetDollarsAdjustedTotal * BudgetMixPercentage AS BudgetTotal, + cv.TargetDollarsAdjustedTotal * BudgetMixPercentage AS TargetTotal, + cv.ProjectionDollarsAdjustedTotal * ProjectionMixPercentage AS ProjectionTotal +FROM fp.ChargeVolume cv + INNER JOIN fp.ServiceLineEncounterToChargePayorMix mix on + mix.BudgetConfigID = cv.BudgetConfigID + AND mix.EntityGroupConfigID = cv.EntityGroupConfigID + AND mix.PatientClassID = cv.PatientClassID + AND mix.EntityID = cv.ServiceEntityID + AND mix.ServiceLineID = cv.ServiceLineID + AND mix.AgeCohortID = cv.AgeCohortID + AND mix.MedicalSurgicalID = cv.MedicalSurgicalID + AND mix.MSDRGID = cv.MSDRGID + AND mix.CPTID = cv.PrimaryCPTID + AND mix.ProviderID = cv.ServiceProviderID +GO + + +--------------------------------------------- + +-- fp.viewChargeVolumeChangeHistoryGrouped +CREATE VIEW fp.viewChargeVolumeChangeHistoryGrouped + AS + SELECT + CAST(0 AS BIGINT) AS RowID, + ch.ChargeVolumeID, + ch.AdjustmentGUID, + ch.AdjustmentType, + ROW_NUMBER() OVER (PARTITION BY ch.ChargeVolumeID, ch.UnitTypeID, ch.TimeClassID, ch.BudgetPhaseID ORDER BY adj.DateCreatedUTC) - 1 AS SortOrder, + SUM(ch.OldValue) AS OldValue, + SUM(ch.NewValue) AS NewValue, + ch.UnitTypeID, + ch.TimeClassID, + ch.BudgetPhaseID + FROM [fp].[ChargeVolumeChangeHistory] ch + INNER JOIN [fp].[DepartmentChargeVolumeAdjustment] adj ON ch.AdjustmentGUID = adj.AdjustmentGUID + GROUP BY ch.ChargeVolumeID, + ch.UnitTypeID, + ch.TimeClassID, + ch.BudgetPhaseID, + ch.AdjustmentGUID, + ch.AdjustmentType, + adj.DateCreatedUTC +GO + + +--------------------------------------------- + +-- fp.viewChargeVolumeChangeHistoryWithRollUpDetail +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2-22-2023 MY JAZZ-46241 Removed 1000 row limit +*************************************************************/ +CREATE VIEW fp.viewChargeVolumeChangeHistoryWithRollUpDetail +AS + SELECT slech.RowID, slech.ChargeVolumeID, slech.AdjustmentGUID, slech.AdjustmentType, slech.FiscalMonthID, slech.UnitTypeID, slech.TimeClassID, slech.BudgetPhaseID, slech.OldValue, slech.NewValue, slech.BudgetConfigID, slech.DateCreatedUTC, slea.DateCreatedUTC AS AdjustmentDateCreatedUTC, + slea.GroupingGUID AS AdjustmentGroupingGUID, CASE WHEN slea.AdjustmentType IN (0, 2, 3) AND slea.GroupingGUID != '00000000-0000-0000-0000-000000000000' THEN slea2.AdjustmentGUID ELSE slea.AdjustmentGUID END ReportingAdjustmentGUID + FROM fp.ChargeVolumeChangeHistory slech + INNER JOIN fp.DepartmentChargeVolumeAdjustment slea ON slech.AdjustmentGUID = slea.AdjustmentGUID + LEFT JOIN fp.DepartmentChargeVolumeAdjustment slea2 ON slea.GroupingGUID = slea2.GroupingGUID AND slea.GroupingGUID != '00000000-0000-0000-0000-000000000000' AND slea2.AdjustmentType IN (12, 13, 14) +GO + + +--------------------------------------------- + +-- fp.viewChargeVolumeChangeHistory_Pivoted +CREATE VIEW fp.viewChargeVolumeChangeHistory_Pivoted + AS +WITH months AS +( + SELECT + FiscalMonthID, + REPLACE(MonthColumnName, 'Month', 'OldValue') AS OldMonthColumnName, + REPLACE(MonthColumnName, 'Month', 'NewValue') AS NewMonthColumnName + FROM fw.DimFiscalMonth +) +SELECT + ChargeVolumeID, + AdjustmentGUID, + UnitTypeID, + TimeClassID , + BudgetPhaseID , + BudgetConfigID , + AdjustmentType , + SUM(pvt2.OldValue01) AS OldValue01, + SUM(pvt2.OldValue02) AS OldValue02, + SUM(pvt2.OldValue03) AS OldValue03, + SUM(pvt2.OldValue04) AS OldValue04, + SUM(pvt2.OldValue05) AS OldValue05, + SUM(pvt2.OldValue06) AS OldValue06, + SUM(pvt2.OldValue07) AS OldValue07, + SUM(pvt2.OldValue08) AS OldValue08, + SUM(pvt2.OldValue09) AS OldValue09, + SUM(pvt2.OldValue10) AS OldValue10, + SUM(pvt2.OldValue11) AS OldValue11, + SUM(pvt2.OldValue12) AS OldValue12, + SUM(pvt2.NewValue01) AS NewValue01, + SUM(pvt2.NewValue02) AS NewValue02, + SUM(pvt2.NewValue03) AS NewValue03, + SUM(pvt2.NewValue04) AS NewValue04, + SUM(pvt2.NewValue05) AS NewValue05, + SUM(pvt2.NewValue06) AS NewValue06, + SUM(pvt2.NewValue07) AS NewValue07, + SUM(pvt2.NewValue08) AS NewValue08, + SUM(pvt2.NewValue09) AS NewValue09, + SUM(pvt2.NewValue10) AS NewValue10, + SUM(pvt2.NewValue11) AS NewValue11, + SUM(pvt2.NewValue12) AS NewValue12 +FROM + ( + SELECT + ChargeVolumeID, + AdjustmentGUID, + AdjustmentType, + UnitTypeID, + TimeClassID , + BudgetPhaseID , + BudgetConfigID , + m.OldMonthColumnName, + m.NewMonthColumnName, + OldValue, + NewValue + FROM [fp].[ChargeVolumeChangeHistory] ch + INNER JOIN months m ON m.FiscalMonthID = ch.FiscalMonthID + ) data + PIVOT (SUM(OldValue) for OldMonthColumnName in ([OldValue01],[OldValue02],[OldValue03],[OldValue04],[OldValue05],[OldValue06],[OldValue07],[OldValue08],[OldValue09],[OldValue10],[OldValue11],[OldValue12])) as pvt + PIVOT (SUM(NewValue) for NewMonthColumnName in ([NewValue01],[NewValue02],[NewValue03],[NewValue04],[NewValue05],[NewValue06],[NewValue07],[NewValue08],[NewValue09],[NewValue10],[NewValue11],[NewValue12])) as pvt2 +GROUP BY + ChargeVolumeID, + AdjustmentGUID, + UnitTypeID, + TimeClassID, + BudgetPhaseID, + BudgetConfigID, + AdjustmentType; +GO + + +--------------------------------------------- + +-- fp.viewChargeVolumeSpreadUnlockData +CREATE VIEW fp.viewChargeVolumeSpreadUnlockData +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-09-01 JB JAZZ-32095 Remove Payor and PayorGroupID from joins. + *************************************************************/ +SELECT [RowID] + ,[BudgetConfigID] + ,[AdjustmentGUID] + ,[EntityID] + ,[DepartmentID] + ,[PatientClassID] + ,[ServiceLineID] + ,[AgeCohortID] + ,[MedicalSurgicalID] + ,[ChargeCodeID] + ,[ServiceEntityID] + ,[MSDRGID] + ,[UBRevCodeID] + ,[PrimaryCPTID] + ,[ServiceProviderID] + ,[ServiceProviderSpecialtyID] + ,[PerformingProviderID] + ,[PerformingProviderSpecialtyID] + ,[BillingCPTID] + ,[Version] + ,[Value01] + ,[Value02] + ,[Value03] + ,[Value04] + ,[Value05] + ,[Value06] + ,[Value07] + ,[Value08] + ,[Value09] + ,[Value10] + ,[Value11] + ,[Value12] + ,[IsRecordDeleted] + FROM [fp].[ChargeVolumeSpreadUnlockData] + WHERE IsRecordDeleted = 0 +GO + + +--------------------------------------------- + +-- fp.viewChargeVolumeSpreads +CREATE VIEW [fp].[viewChargeVolumeSpreads] +AS + SELECT [BudgetConfigID], [DepartmentID], [ServiceLineID], [ChargeCodeID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [IsInactive], [SpreadPercentage01], [SpreadPercentage02], [SpreadPercentage03], [SpreadPercentage04], [SpreadPercentage05], [SpreadPercentage06], [SpreadPercentage07], [SpreadPercentage08], [SpreadPercentage09], [SpreadPercentage10], [SpreadPercentage11], [SpreadPercentage12], [TotalImportedValue] as TotalSpreadValue, [GlobalSpreadID] + FROM [fp].[ChargeVolumeSpreads] with (readuncommitted) + WHERE GlobalSpreadID = 1 + + UNION ALL + + SELECT bs.[BudgetConfigID], [DepartmentID], [ServiceLineID], [ChargeCodeID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [IsInactive], gs.[SpreadPercentage01], gs.[SpreadPercentage02], gs.[SpreadPercentage03], gs.[SpreadPercentage04], gs.[SpreadPercentage05], gs.[SpreadPercentage06], gs.[SpreadPercentage07], gs.[SpreadPercentage08], gs.[SpreadPercentage09], gs.[SpreadPercentage10], gs.[SpreadPercentage11], gs.[SpreadPercentage12], gs.TotalSpreadValue, bs.[GlobalSpreadID] + FROM [fp].[ChargeVolumeSpreads] bs with (readuncommitted) + INNER JOIN [fp].[GlobalSpread] gs ON bs.GlobalSpreadID = gs.GlobalSpreadID + WHERE bs.GlobalSpreadID > 1 +GO + + +--------------------------------------------- + +-- fp.viewChargeVolume_BudgetAdjusted +CREATE VIEW fp.viewChargeVolume_BudgetAdjusted + AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-02-13 NT JAZZ-48268 Create ChargeVolume view for Budget adjusted only + ** 2 2023-03-08 MY JAZZ-48307 Remove unnecessary history join + *************************************************************/ + SELECT cv.[ChargeVolumeID] + ,cv.[BudgetConfigID] + ,cv.[EntityGroupConfigID] + ,cv.[EntityID] + ,cv.[DepartmentID] + ,cv.[ServiceLineID] + ,cv.[PatientClassID] + ,cv.[AgeCohortID] + ,cv.[MedicalSurgicalID] + ,cv.[ChargeCodeID] + ,cv.[ServiceEntityID] + ,cv.[MSDRGID] + ,cv.[UBRevCodeID] + ,cv.[PrimaryCPTID] + ,cv.[ServiceProviderID] + ,cv.[ServiceProviderSpecialtyID] + ,cv.[PerformingProviderID] + ,cv.[PerformingProviderSpecialtyID] + ,cv.[BillingCPTID] + ,cv.[UnitTypeID] + + ,cv.[BudgetAdjustedTotal] + ,cv.[BudgetDollarsAdjustedTotal] + + ,cv.[BudgetAdjusted01] + ,cv.[BudgetAdjusted02] + ,cv.[BudgetAdjusted03] + ,cv.[BudgetAdjusted04] + ,cv.[BudgetAdjusted05] + ,cv.[BudgetAdjusted06] + ,cv.[BudgetAdjusted07] + ,cv.[BudgetAdjusted08] + ,cv.[BudgetAdjusted09] + ,cv.[BudgetAdjusted10] + ,cv.[BudgetAdjusted11] + ,cv.[BudgetAdjusted12] + + ,cv.[BudgetUnitsPerEncounterAdjusted01] + ,cv.[BudgetUnitsPerEncounterAdjusted02] + ,cv.[BudgetUnitsPerEncounterAdjusted03] + ,cv.[BudgetUnitsPerEncounterAdjusted04] + ,cv.[BudgetUnitsPerEncounterAdjusted05] + ,cv.[BudgetUnitsPerEncounterAdjusted06] + ,cv.[BudgetUnitsPerEncounterAdjusted07] + ,cv.[BudgetUnitsPerEncounterAdjusted08] + ,cv.[BudgetUnitsPerEncounterAdjusted09] + ,cv.[BudgetUnitsPerEncounterAdjusted10] + ,cv.[BudgetUnitsPerEncounterAdjusted11] + ,cv.[BudgetUnitsPerEncounterAdjusted12] + + ,cv.[BudgetPrice01] + ,cv.[BudgetPrice02] + ,cv.[BudgetPrice03] + ,cv.[BudgetPrice04] + ,cv.[BudgetPrice05] + ,cv.[BudgetPrice06] + ,cv.[BudgetPrice07] + ,cv.[BudgetPrice08] + ,cv.[BudgetPrice09] + ,cv.[BudgetPrice10] + ,cv.[BudgetPrice11] + ,cv.[BudgetPrice12] + + ,cv.[BudgetDollarsAdjusted01] + ,cv.[BudgetDollarsAdjusted02] + ,cv.[BudgetDollarsAdjusted03] + ,cv.[BudgetDollarsAdjusted04] + ,cv.[BudgetDollarsAdjusted05] + ,cv.[BudgetDollarsAdjusted06] + ,cv.[BudgetDollarsAdjusted07] + ,cv.[BudgetDollarsAdjusted08] + ,cv.[BudgetDollarsAdjusted09] + ,cv.[BudgetDollarsAdjusted10] + ,cv.[BudgetDollarsAdjusted11] + ,cv.[BudgetDollarsAdjusted12] +FROM fp.ChargeVolume cv +GO + + +--------------------------------------------- + +-- fp.viewChargeVolume_InitialBudget +CREATE VIEW fp.viewChargeVolume_InitialBudget + AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-02-13 NT JAZZ-48268 Create ChargeVolume view for inital budget only + ** 2 2023-03-08 MY JAZZ-48307 Remove unnecessary history join + *************************************************************/ + SELECT cv.[ChargeVolumeID] + ,cv.[BudgetConfigID] + ,cv.[EntityGroupConfigID] + ,cv.[EntityID] + ,cv.[DepartmentID] + ,cv.[ServiceLineID] + ,cv.[PatientClassID] + ,cv.[AgeCohortID] + ,cv.[MedicalSurgicalID] + ,cv.[ChargeCodeID] + ,cv.[ServiceEntityID] + ,cv.[MSDRGID] + ,cv.[UBRevCodeID] + ,cv.[PrimaryCPTID] + ,cv.[ServiceProviderID] + ,cv.[ServiceProviderSpecialtyID] + ,cv.[PerformingProviderID] + ,cv.[PerformingProviderSpecialtyID] + ,cv.[BillingCPTID] + ,cv.[UnitTypeID] + + ,cv.[InitialBudgetTotal] + ,cv.[InitialBudgetDollarsTotal] + + ,cv.[InitialBudget01] + ,cv.[InitialBudget02] + ,cv.[InitialBudget03] + ,cv.[InitialBudget04] + ,cv.[InitialBudget05] + ,cv.[InitialBudget06] + ,cv.[InitialBudget07] + ,cv.[InitialBudget08] + ,cv.[InitialBudget09] + ,cv.[InitialBudget10] + ,cv.[InitialBudget11] + ,cv.[InitialBudget12] + + ,cv.[InitialBudgetUnitsPerEncounter01] + ,cv.[InitialBudgetUnitsPerEncounter02] + ,cv.[InitialBudgetUnitsPerEncounter03] + ,cv.[InitialBudgetUnitsPerEncounter04] + ,cv.[InitialBudgetUnitsPerEncounter05] + ,cv.[InitialBudgetUnitsPerEncounter06] + ,cv.[InitialBudgetUnitsPerEncounter07] + ,cv.[InitialBudgetUnitsPerEncounter08] + ,cv.[InitialBudgetUnitsPerEncounter09] + ,cv.[InitialBudgetUnitsPerEncounter10] + ,cv.[InitialBudgetUnitsPerEncounter11] + ,cv.[InitialBudgetUnitsPerEncounter12] + + ,cv.[InitialBudgetDollars01] + ,cv.[InitialBudgetDollars02] + ,cv.[InitialBudgetDollars03] + ,cv.[InitialBudgetDollars04] + ,cv.[InitialBudgetDollars05] + ,cv.[InitialBudgetDollars06] + ,cv.[InitialBudgetDollars07] + ,cv.[InitialBudgetDollars08] + ,cv.[InitialBudgetDollars09] + ,cv.[InitialBudgetDollars10] + ,cv.[InitialBudgetDollars11] + ,cv.[InitialBudgetDollars12] +FROM fp.ChargeVolume cv +GO + + +--------------------------------------------- + +-- fp.viewChargeVolume_InitialProjection +CREATE VIEW fp.viewChargeVolume_InitialProjection + AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-02-13 NT JAZZ-48268 Create ChargeVolume view for inital projection only + ** 2 2023-03-08 MY JAZZ-48307 Remove unnecessary history join + *************************************************************/ + SELECT + cv.[ChargeVolumeID] + ,cv.[BudgetConfigID] + ,cv.[EntityGroupConfigID] + ,cv.[EntityID] + ,cv.[DepartmentID] + ,cv.[ServiceLineID] + ,cv.[PatientClassID] + ,cv.[AgeCohortID] + ,cv.[MedicalSurgicalID] + ,cv.[ChargeCodeID] + ,cv.[ServiceEntityID] + ,cv.[MSDRGID] + ,cv.[UBRevCodeID] + ,cv.[PrimaryCPTID] + ,cv.[ServiceProviderID] + ,cv.[ServiceProviderSpecialtyID] + ,cv.[PerformingProviderID] + ,cv.[PerformingProviderSpecialtyID] + ,cv.[BillingCPTID] + ,cv.[UnitTypeID] + + ,cv.[InitialProjectionTotal] + ,cv.[InitialProjectionDollarsTotal] + + ,cv.[InitialProjection01] + ,cv.[InitialProjection02] + ,cv.[InitialProjection03] + ,cv.[InitialProjection04] + ,cv.[InitialProjection05] + ,cv.[InitialProjection06] + ,cv.[InitialProjection07] + ,cv.[InitialProjection08] + ,cv.[InitialProjection09] + ,cv.[InitialProjection10] + ,cv.[InitialProjection11] + ,cv.[InitialProjection12] + + ,cv.[InitialProjectionUnitsPerEncounter01] + ,cv.[InitialProjectionUnitsPerEncounter02] + ,cv.[InitialProjectionUnitsPerEncounter03] + ,cv.[InitialProjectionUnitsPerEncounter04] + ,cv.[InitialProjectionUnitsPerEncounter05] + ,cv.[InitialProjectionUnitsPerEncounter06] + ,cv.[InitialProjectionUnitsPerEncounter07] + ,cv.[InitialProjectionUnitsPerEncounter08] + ,cv.[InitialProjectionUnitsPerEncounter09] + ,cv.[InitialProjectionUnitsPerEncounter10] + ,cv.[InitialProjectionUnitsPerEncounter11] + ,cv.[InitialProjectionUnitsPerEncounter12] + + ,cv.[InitialBudgetDollars01] + ,cv.[InitialBudgetDollars02] + ,cv.[InitialBudgetDollars03] + ,cv.[InitialBudgetDollars04] + ,cv.[InitialBudgetDollars05] + ,cv.[InitialBudgetDollars06] + ,cv.[InitialBudgetDollars07] + ,cv.[InitialBudgetDollars08] + ,cv.[InitialBudgetDollars09] + ,cv.[InitialBudgetDollars10] + ,cv.[InitialBudgetDollars11] + ,cv.[InitialBudgetDollars12] +FROM fp.ChargeVolume cv +GO + + +--------------------------------------------- + +-- fp.viewChargeVolume_Pivoted +CREATE VIEW [fp].[viewChargeVolume_Pivoted] +AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-02-21 MD JAZZ-50101 Initial + ** 2 2023-03-08 MY JAZZ-48307 Fix for missing Dollars Total + *************************************************************/ + SELECT + cv.ChargeVolumeID, + cv.BudgetConfigID, + cv.EntityGroupConfigID, + cv.EntityID, + cv.DepartmentID, + cv.ServiceLineID, + cv.PatientClassID, + cv.AgeCohortID, + cv.MedicalSurgicalID, + cv.ChargeCodeID, + cv.UnitTypeID, + cv.ServiceEntityID, + cv.MSDRGID, + cv.UBRevCodeID, + cv.PrimaryCPTID, + cv.BillingCPTID, + cv.ServiceProviderID, + cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, + cv.PerformingProviderSpecialtyID, + + cv.TargetLockType, + cv.TargetLockFlag, + cv.ProjectionLockType, + cv.ProjectionLockFlag, + + cv.VariableDirectUnitCost, + cv.InitialBudgetTotal, + cv.InitialProjectionTotal, + + cv.TargetAdjustedTotal, + cv.BudgetAdjustedTotal, + cv.ProjectionAdjustedTotal, + + cv.TargetDollarsAdjustedTotal, + cv.BudgetDollarsAdjustedTotal, + cv.ProjectionDollarsAdjustedTotal, + cv.InitialBudgetDollarsTotal, + cv.InitialProjectionDollarsTotal, + + hist.ActualYTDValueTotal, + hist.PriorYearActualValueTotal, + hist.CurrentYearBudgetTotal, + hist.ActualYTDDollarValueTotal, + hist.PriorYearActualDollarValueTotal, + hist.CurrentYearBudgetDollarTotal, + + cv.TargetAdjusted01, + cv.TargetAdjusted02, + cv.TargetAdjusted03, + cv.TargetAdjusted04, + cv.TargetAdjusted05, + cv.TargetAdjusted06, + cv.TargetAdjusted07, + cv.TargetAdjusted08, + cv.TargetAdjusted09, + cv.TargetAdjusted10, + cv.TargetAdjusted11, + cv.TargetAdjusted12, + + cv.BudgetAdjusted01, + cv.BudgetAdjusted02, + cv.BudgetAdjusted03, + cv.BudgetAdjusted04, + cv.BudgetAdjusted05, + cv.BudgetAdjusted06, + cv.BudgetAdjusted07, + cv.BudgetAdjusted08, + cv.BudgetAdjusted09, + cv.BudgetAdjusted10, + cv.BudgetAdjusted11, + cv.BudgetAdjusted12, + + cv.ProjectionAdjusted01, + cv.ProjectionAdjusted02, + cv.ProjectionAdjusted03, + cv.ProjectionAdjusted04, + cv.ProjectionAdjusted05, + cv.ProjectionAdjusted06, + cv.ProjectionAdjusted07, + cv.ProjectionAdjusted08, + cv.ProjectionAdjusted09, + cv.ProjectionAdjusted10, + cv.ProjectionAdjusted11, + cv.ProjectionAdjusted12, + + cv.TargetDollarsAdjusted01, + cv.TargetDollarsAdjusted02, + cv.TargetDollarsAdjusted03, + cv.TargetDollarsAdjusted04, + cv.TargetDollarsAdjusted05, + cv.TargetDollarsAdjusted06, + cv.TargetDollarsAdjusted07, + cv.TargetDollarsAdjusted08, + cv.TargetDollarsAdjusted09, + cv.TargetDollarsAdjusted10, + cv.TargetDollarsAdjusted11, + cv.TargetDollarsAdjusted12, + + cv.BudgetDollarsAdjusted01, + cv.BudgetDollarsAdjusted02, + cv.BudgetDollarsAdjusted03, + cv.BudgetDollarsAdjusted04, + cv.BudgetDollarsAdjusted05, + cv.BudgetDollarsAdjusted06, + cv.BudgetDollarsAdjusted07, + cv.BudgetDollarsAdjusted08, + cv.BudgetDollarsAdjusted09, + cv.BudgetDollarsAdjusted10, + cv.BudgetDollarsAdjusted11, + cv.BudgetDollarsAdjusted12, + + cv.ProjectionDollarsAdjusted01, + cv.ProjectionDollarsAdjusted02, + cv.ProjectionDollarsAdjusted03, + cv.ProjectionDollarsAdjusted04, + cv.ProjectionDollarsAdjusted05, + cv.ProjectionDollarsAdjusted06, + cv.ProjectionDollarsAdjusted07, + cv.ProjectionDollarsAdjusted08, + cv.ProjectionDollarsAdjusted09, + cv.ProjectionDollarsAdjusted10, + cv.ProjectionDollarsAdjusted11, + cv.ProjectionDollarsAdjusted12 + FROM + [fp].[ChargeVolume] cv WITH (READUNCOMMITTED) + INNER JOIN [fp].[ChargeVolumeHistory] hist WITH (READUNCOMMITTED) ON cv.ChargeVolumeID = hist.ChargeVolumeID +GO + + +--------------------------------------------- + +-- fp.viewChargeVolume_ProjectionAdjusted +CREATE VIEW fp.viewChargeVolume_ProjectionAdjusted + AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-02-13 NT JAZZ-48268 Create ChargeVolume view for Projection adjusted only + ** 2 2023-03-08 MY JAZZ-48307 Remove unnecessary history join + *************************************************************/ + SELECT cv.[ChargeVolumeID] + ,cv.[BudgetConfigID] + ,cv.[EntityGroupConfigID] + ,cv.[EntityID] + ,cv.[DepartmentID] + ,cv.[ServiceLineID] + ,cv.[PatientClassID] + ,cv.[AgeCohortID] + ,cv.[MedicalSurgicalID] + ,cv.[ChargeCodeID] + ,cv.[ServiceEntityID] + ,cv.[MSDRGID] + ,cv.[UBRevCodeID] + ,cv.[PrimaryCPTID] + ,cv.[ServiceProviderID] + ,cv.[ServiceProviderSpecialtyID] + ,cv.[PerformingProviderID] + ,cv.[PerformingProviderSpecialtyID] + ,cv.[BillingCPTID] + ,cv.[UnitTypeID] + + ,cv.[ProjectionAdjustedTotal] + ,cv.[ProjectionDollarsAdjustedTotal] + + ,cv.[ProjectionAdjusted01] + ,cv.[ProjectionAdjusted02] + ,cv.[ProjectionAdjusted03] + ,cv.[ProjectionAdjusted04] + ,cv.[ProjectionAdjusted05] + ,cv.[ProjectionAdjusted06] + ,cv.[ProjectionAdjusted07] + ,cv.[ProjectionAdjusted08] + ,cv.[ProjectionAdjusted09] + ,cv.[ProjectionAdjusted10] + ,cv.[ProjectionAdjusted11] + ,cv.[ProjectionAdjusted12] + + ,cv.[ProjectionUnitsPerEncounterAdjusted01] + ,cv.[ProjectionUnitsPerEncounterAdjusted02] + ,cv.[ProjectionUnitsPerEncounterAdjusted03] + ,cv.[ProjectionUnitsPerEncounterAdjusted04] + ,cv.[ProjectionUnitsPerEncounterAdjusted05] + ,cv.[ProjectionUnitsPerEncounterAdjusted06] + ,cv.[ProjectionUnitsPerEncounterAdjusted07] + ,cv.[ProjectionUnitsPerEncounterAdjusted08] + ,cv.[ProjectionUnitsPerEncounterAdjusted09] + ,cv.[ProjectionUnitsPerEncounterAdjusted10] + ,cv.[ProjectionUnitsPerEncounterAdjusted11] + ,cv.[ProjectionUnitsPerEncounterAdjusted12] + + ,cv.[ProjectionPrice01] + ,cv.[ProjectionPrice02] + ,cv.[ProjectionPrice03] + ,cv.[ProjectionPrice04] + ,cv.[ProjectionPrice05] + ,cv.[ProjectionPrice06] + ,cv.[ProjectionPrice07] + ,cv.[ProjectionPrice08] + ,cv.[ProjectionPrice09] + ,cv.[ProjectionPrice10] + ,cv.[ProjectionPrice11] + ,cv.[ProjectionPrice12] + + ,cv.[ProjectionDollarsAdjusted01] + ,cv.[ProjectionDollarsAdjusted02] + ,cv.[ProjectionDollarsAdjusted03] + ,cv.[ProjectionDollarsAdjusted04] + ,cv.[ProjectionDollarsAdjusted05] + ,cv.[ProjectionDollarsAdjusted06] + ,cv.[ProjectionDollarsAdjusted07] + ,cv.[ProjectionDollarsAdjusted08] + ,cv.[ProjectionDollarsAdjusted09] + ,cv.[ProjectionDollarsAdjusted10] + ,cv.[ProjectionDollarsAdjusted11] + ,cv.[ProjectionDollarsAdjusted12] +FROM fp.ChargeVolume cv +GO + + +--------------------------------------------- + +-- fp.viewChargeVolume_TargetAdjusted +CREATE VIEW fp.viewChargeVolume_TargetAdjusted + AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-02-13 NT JAZZ-48268 Create ChargeVolume view for Target adjusted only + ** 2 2023-03-08 MY JAZZ-48307 Remove unnecessary history join + *************************************************************/ + SELECT cv.[ChargeVolumeID] + ,cv.[BudgetConfigID] + ,cv.[EntityGroupConfigID] + ,cv.[EntityID] + ,cv.[DepartmentID] + ,cv.[ServiceLineID] + ,cv.[PatientClassID] + ,cv.[AgeCohortID] + ,cv.[MedicalSurgicalID] + ,cv.[ChargeCodeID] + ,cv.[ServiceEntityID] + ,cv.[MSDRGID] + ,cv.[UBRevCodeID] + ,cv.[PrimaryCPTID] + ,cv.[ServiceProviderID] + ,cv.[ServiceProviderSpecialtyID] + ,cv.[PerformingProviderID] + ,cv.[PerformingProviderSpecialtyID] + ,cv.[BillingCPTID] + ,cv.[UnitTypeID] + + ,cv.[TargetAdjustedTotal] + ,cv.[TargetDollarsAdjustedTotal] + + ,cv.[TargetAdjusted01] + ,cv.[TargetAdjusted02] + ,cv.[TargetAdjusted03] + ,cv.[TargetAdjusted04] + ,cv.[TargetAdjusted05] + ,cv.[TargetAdjusted06] + ,cv.[TargetAdjusted07] + ,cv.[TargetAdjusted08] + ,cv.[TargetAdjusted09] + ,cv.[TargetAdjusted10] + ,cv.[TargetAdjusted11] + ,cv.[TargetAdjusted12] + + ,cv.[TargetUnitsPerEncounterAdjusted01] + ,cv.[TargetUnitsPerEncounterAdjusted02] + ,cv.[TargetUnitsPerEncounterAdjusted03] + ,cv.[TargetUnitsPerEncounterAdjusted04] + ,cv.[TargetUnitsPerEncounterAdjusted05] + ,cv.[TargetUnitsPerEncounterAdjusted06] + ,cv.[TargetUnitsPerEncounterAdjusted07] + ,cv.[TargetUnitsPerEncounterAdjusted08] + ,cv.[TargetUnitsPerEncounterAdjusted09] + ,cv.[TargetUnitsPerEncounterAdjusted10] + ,cv.[TargetUnitsPerEncounterAdjusted11] + ,cv.[TargetUnitsPerEncounterAdjusted12] + + ,cv.[TargetPrice01] + ,cv.[TargetPrice02] + ,cv.[TargetPrice03] + ,cv.[TargetPrice04] + ,cv.[TargetPrice05] + ,cv.[TargetPrice06] + ,cv.[TargetPrice07] + ,cv.[TargetPrice08] + ,cv.[TargetPrice09] + ,cv.[TargetPrice10] + ,cv.[TargetPrice11] + ,cv.[TargetPrice12] + + ,cv.[TargetDollarsAdjusted01] + ,cv.[TargetDollarsAdjusted02] + ,cv.[TargetDollarsAdjusted03] + ,cv.[TargetDollarsAdjusted04] + ,cv.[TargetDollarsAdjusted05] + ,cv.[TargetDollarsAdjusted06] + ,cv.[TargetDollarsAdjusted07] + ,cv.[TargetDollarsAdjusted08] + ,cv.[TargetDollarsAdjusted09] + ,cv.[TargetDollarsAdjusted10] + ,cv.[TargetDollarsAdjusted11] + ,cv.[TargetDollarsAdjusted12] +FROM fp.ChargeVolume cv +GO + + +--------------------------------------------- + +-- fp.viewDeductionsAccounts +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 8-9-2023 MY JAZZ-58777 1Plan - Deductions flexing does not work for Fixed departments even when set to use Total Gross Charges in setup +*************************************************************/ +CREATE VIEW [fp].[viewDeductionsAccounts] +AS + SELECT acc.* + FROM [fw].[DimAccount] acc + INNER JOIN [ob].[DimAccountPH] aph ON acc.OBAccountPHID = aph.AccountPHID + WHERE aph.Name IN ('Deductions', 'Deductions - Charity and Bad Debt', 'Deductions - Reimbursement') -- Do not update this list unless you're adding to it. This view is used by multiple places to find all of the Deduction accounts in the system. Removing a value can lead to unexpected errors. +GO + + +--------------------------------------------- + +-- fp.viewDeductionsFlexingConfig +CREATE VIEW [fp].[viewDeductionsFlexingConfig] +AS +SELECT + fc.EntityGroupConfigGUID, + fc.DepartmentID, + acct.AccountID, + fc.FlexMethodID + FROM [fp].[DeductionsFlexingConfig] fc + CROSS APPLY (SELECT AccountID FROM [fp].[viewDeductionsAccounts]) acct +GO + + +--------------------------------------------- + +-- fp.viewDepartmentAccessByUser +CREATE view fp.viewDepartmentAccessByUser +as + select + a.EntityGroupConfigID, + a.Section, + ra.IdentityGUID as UserGUID, + REPLACE(ra.LootGroupID, 'DEPT|', '') as DepartmentID, + MAX(a.AccessType) as AccessType + from + [fp].[APESectionRoleAccess] a + LEFT JOIN [dbo].[viewS3RoleAssignment] ra on ra.RoleID = a.RoleID + INNER JOIN [fw].[DimDepartment] dept on 'DEPT|' + CAST(dept.DepartmentID as nvarchar(10)) = ra.LootGroupID + where + a.budgetphaseid = 2 + and ra.lootgroupid like 'DEPT|%' + group by + a.EntityGroupConfigID, + a.Section, + ra.IdentityGUID, + ra.LootGroupID +GO + + +--------------------------------------------- + +-- fp.viewDepartmentChargeVolumeAdjustment +CREATE VIEW fp.viewDepartmentChargeVolumeAdjustment +AS + +SELECT [AdjustmentGUID] + ,[BudgetConfigGUID] + ,[AdjustmentType] + ,[Value] + ,[AdjustmentFilterJSON] + ,[GroupingHierarchyJSON] + ,[AdjustedProperty] + ,[Comment] + ,[AuthorGUID] + ,[AuthorFullName] + ,[LastModifiedDateUtc] + ,[DateCreatedUtc] + ,[GroupingGUID] + ,[TimeClassID] + ,[ClassificationGroupID] + ,[ClassificationCategoryID] + ,[IsRecordDeleted] + ,[AffectedDataCount] + ,[DimensionMemberJson] + ,[AdjustmentID] + ,[IsErrored] + FROM [fp].[DepartmentChargeVolumeAdjustment] + WHERE IsRecordDeleted = 0; +GO + + +--------------------------------------------- + +-- fp.viewDepartmentChargeVolumeAdjustmentImport +CREATE VIEW fp.viewDepartmentChargeVolumeAdjustmentImport +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-09-01 JB JAZZ-32095 Remove Payor and PayorGroupID from joins. + *************************************************************/ +SELECT [RowID] + ,[AdjustmentGUID] + ,[DepartmentID] + ,[ServiceLineID] + ,[PatientClassID] + ,[AgeCohortID] + ,[MedicalSurgicalID] + ,[ChargeCodeID] + ,[ServiceEntityID] + ,[MSDRGID] + ,[UBRevCodeID] + ,[PrimaryCPTID] + ,[ServiceProviderID] + ,[ServiceProviderSpecialtyID] + ,[PerformingProviderID] + ,[PerformingProviderSpecialtyID] + ,[BillingCPTID] + ,[Value] + ,[Version] + ,[EntityID] + ,[TimeClassID] + ,[FiscalMonthID] + ,[IsRecordDeleted] + ,[AdjustmentID] + FROM [fp].[DepartmentChargeAdjustmentImport] + WHERE IsRecordDeleted = 0 +GO + + +--------------------------------------------- + +-- fp.viewDependentByDriverStatisticsFlexConfigMapping +CREATE VIEW fp.viewDependentByDriverStatisticsFlexConfigMapping +AS +SELECT + EntityGroupConfigID, + DepartmentID AS DependentDepartmentID, + DependentStatisticAccountID AS DependentAccountID, + SourceDepartmentID AS DriverDepartmentID, + StatAccountID AS DriverAccountID +FROM fp.FlexConfigMapping +WHERE FlexingTypeID = 8 -- FlexDependentStatisticsByDriverStatistics +GO + + +--------------------------------------------- + +-- fp.viewDimBudgetConfig +CREATE VIEW [fp].[viewDimBudgetConfig] +AS + SELECT + BudgetConfigID, + BudgetConfigGUID AS MemberGUID, + FiscalYearID, + DateModified, + DatePublished, + BudgetConfigName AS Name, + IsActive, + Comments, + '00000000-0000-0000-0000-000000000000' AS HistoryItemGUID, + 0 AS TransactionID + FROM [fp].[BudgetConfig] +GO + + +--------------------------------------------- + +-- fp.viewDimBudgetConfig_auto +--Last Modified 2/5/2018 7:18 PM +CREATE VIEW [fp].[viewDimBudgetConfig_auto] +AS +SELECT + grpE945519B243042599E20EC7624B3FF68.[BudgetConfigID] + ,grpE945519B243042599E20EC7624B3FF68.[Name] + ,grpE945519B243042599E20EC7624B3FF68.[TransactionID] + ,grpE945519B243042599E20EC7624B3FF68.[MemberGUID] + ,grpE945519B243042599E20EC7624B3FF68.[HistoryItemGUID] +FROM [fp].[ViewDimBudgetConfig] grpE945519B243042599E20EC7624B3FF68 +GO + + +--------------------------------------------- + +-- fp.viewDimBudgetSnapshot +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2024-12-04 MY JAZZ-80433 Update Name to Concat Date and Time +*************************************************************/ +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2024-12-04 MY JAZZ-80433 Update Name to Concat Date and Time +*************************************************************/ +CREATE VIEW [fp].[viewDimBudgetSnapshot] +AS + SELECT + SnapshotID, + BudgetConfigID, + MemberGUID, + AuthorGUID, + AuthorName, + AdjustmentsStampedOff, + DateCreatedUTC, + DateProcessedUTC, + Name, + Comment, + '00000000-0000-0000-0000-000000000000' AS HistoryItemGUID, + TransactionID + FROM [fp].[viewBaseBudgetSnapshotWithNameConcat] +GO + + +--------------------------------------------- + +-- fp.viewDimBudgetSnapshot_auto +--Last Modified 12/9/2024 11:54 AM +CREATE VIEW [fp].[viewDimBudgetSnapshot_auto] +AS +SELECT + grp9B2D0CB6369242248B72E41D9D831413.[SnapshotID] + ,grp9B2D0CB6369242248B72E41D9D831413.[Name] + ,grp9B2D0CB6369242248B72E41D9D831413.[TransactionID] + ,grp9B2D0CB6369242248B72E41D9D831413.[MemberGUID] + ,coalesce(grp9B2D0CB6369242248B72E41D9D831413.[HistoryItemGUID],'') as [HistoryItemGUID] + ,coalesce(grp9B2D0CB6369242248B72E41D9D831413.[Comment],'') as [Comment] + ,grp9B2D0CB6369242248B72E41D9D831413.[AdjustmentsStampedOff] + ,grp9B2D0CB6369242248B72E41D9D831413.[DateCreatedUTC] +FROM [fp].[ViewDimBudgetSnapshot] grp9B2D0CB6369242248B72E41D9D831413 +GO + + +--------------------------------------------- + +-- fp.viewDimItemizationDataType +--Last Modified 5/26/2021 3:28 PM +CREATE VIEW [fp].[viewDimItemizationDataType] +AS +SELECT + grp46FF9613EEC34DE4B2B4F9DFA90D18B5.[ItemizationDataTypeID] + ,grp46FF9613EEC34DE4B2B4F9DFA90D18B5.[Name] + ,grp46FF9613EEC34DE4B2B4F9DFA90D18B5.[MemberGUID] +FROM [fp].[DimItemizationDataType] grp46FF9613EEC34DE4B2B4F9DFA90D18B5 (readuncommitted) +GO + + +--------------------------------------------- + +-- fp.viewDimPerformingProvider +CREATE VIEW [fp].[viewDimPerformingProvider] +AS + SELECT + PhysicianID AS [PerformingProviderID] + ,TransactionID + ,Physician + ,PhysicianCode AS [PhysicianCode] + ,FullName + ,PhysicianSpecialtyID + ,StateLicenseNumber + ,GroupAffiliation + ,NPI + ,MemberGUID + ,ProviderTypeID + ,HistoryItemGUID + ,Title + ,IsActive + ,ACOFlag + ,InMedicalGroup + ,FirstName + ,IsProvider + ,ProviderGroup + ,PhysicianGroupAffiliationID + ,EmployeeID + ,PhysicianTaxonomyID + ,IsFP + ,IsDS + ,EmailAddress + ,NPIPhysician + + ,[EmployeeCode] [EmployeeCode] + ,[PhysicianGroupAffiliation] [PhysicianGroupAffiliation] +FROM [dss].[DimPhysician]; +GO + + +--------------------------------------------- + +-- fp.viewDimPerformingProvider_auto +--Last Modified 11/16/2020 3:28 PM +CREATE VIEW [fp].[viewDimPerformingProvider_auto] +AS +SELECT + grp6E30837FBA9B4380BB0834CE2978DBE1.[PerformingProviderID] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[TransactionID] + ,coalesce(grp6E30837FBA9B4380BB0834CE2978DBE1.[Physician],'') as [Physician] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[PhysicianCode] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[FullName] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[PhysicianSpecialtyID] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[StateLicenseNumber] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[GroupAffiliation] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[NPI] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[MemberGUID] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[ProviderTypeID] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[HistoryItemGUID] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[Title] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[IsActive] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[ACOFlag] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[InMedicalGroup] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[FirstName] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[IsProvider] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[ProviderGroup] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[PhysicianGroupAffiliationID] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[EmployeeID] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[PhysicianTaxonomyID] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[IsFP] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[IsDS] + ,grp6E30837FBA9B4380BB0834CE2978DBE1.[EmailAddress] + ,coalesce(grp6E30837FBA9B4380BB0834CE2978DBE1.[NPIPhysician],'') as [NPIPhysician] + ,ISNULL([PHYSSPECIALTY].[Name], 'Not Specified') as [PhysicianSpecialty] + ,ISNULL([PHYSSPECIALTY].[PhysicianSpecialtyCode], 'Not Specified') as [PhysicianSpecialtyCode] + ,ISNULL([PHYSSPECIALTY].[Description], 'Not Specified') as [PhysicianSpecialtyDescription] + ,ISNULL([PHYSSPECIALTY].[SpecialtyGroup], 'Not Specified') as [PhysicianSpecialtyGroup] + ,ISNULL([PROVTYPE].[Name], 'Not Specified') as [ProviderTypeName] + ,ISNULL([PROVTYPE].[ProviderTypeCode], 'Not Specified') as [ProviderTypeCode] + ,ISNULL([PROVTYPE].[Description], 'Not Specified') as [ProviderTypeDescription] + ,ISNULL([PHYSICIANGROUPAFFILIATION].[Name], 'Not Specified') as [PhysicianGroupAffiliation] + ,ISNULL([PHYSICIANGROUPAFFILIATION].[PhysicianGroupAffiliationCode], 'Not Specified') as [PhysicianGroupAffiliationCode] + ,ISNULL([PHYSICIANGROUPAFFILIATION].[Description], 'Not Specified') as [PhysicianGroupAffiliationDescription] + ,ISNULL([EMP].[Code], 'Not Specified') as [EmployeeCode] + ,ISNULL([PHYSTAX].[Name], 'Not Specified') as [PhysicianTaxonomy] +FROM [fp].[viewDimPerformingProvider] grp6E30837FBA9B4380BB0834CE2978DBE1 + LEFT JOIN [dss].[viewDimPhysicianSpecialty] [PHYSSPECIALTY] on [PHYSSPECIALTY].[PhysicianSpecialtyID] = [grp6E30837FBA9B4380BB0834CE2978DBE1].[PhysicianSpecialtyID] + LEFT JOIN [clientdss].[viewDimProviderType] [PROVTYPE] on [PROVTYPE].[ProviderTypeID] = [grp6E30837FBA9B4380BB0834CE2978DBE1].[ProviderTypeID] + LEFT JOIN [dss].[viewDimPhysicianGroupAffiliation] [PHYSICIANGROUPAFFILIATION] on [PHYSICIANGROUPAFFILIATION].[PhysicianGroupAffiliationID] = [grp6E30837FBA9B4380BB0834CE2978DBE1].[PhysicianGroupAffiliationID] + INNER JOIN [fw].[viewDimEmployee] [EMP] on [EMP].[EmployeeID] = [grp6E30837FBA9B4380BB0834CE2978DBE1].[EmployeeID] + LEFT JOIN [clientdss].[viewDimPhysicianTaxonomy] [PHYSTAX] on [PHYSTAX].[PhysicianTaxonomyID] = [grp6E30837FBA9B4380BB0834CE2978DBE1].[PhysicianTaxonomyID] +GO + + +--------------------------------------------- + +-- fp.viewDimPhysician +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 09-19-2023 MD JAZZ-59502 Add physician column +*************************************************************/ +CREATE VIEW [fp].[viewDimPhysician] +AS +SELECT + PhysicianID as ProviderID, + PhysicianSpecialtyID, + MemberGUID, + FullName as Name, + PhysicianCode as ProviderCode, + ProviderTypeID, + Physician +FROM dss.DimPhysician +GO + + +--------------------------------------------- + +-- fp.viewDimSection +CREATE VIEW fp.viewDimSection + AS + SELECT CONVERT(INT, ROW_NUMBER() OVER (ORDER BY ps.SortOrder, SubsectionID)) -1 AS SectionID, + CASE WHEN ps.PlanSectionID = 2 THEN 'Charges' + WHEN ps.PlanSectionID = 3 AND SubsectionID = 2 THEN 'Dependent Statistics' + WHEN ps.PlanSectionID = 4 AND SubsectionID = 4 THEN 'Provider Compensation' + WHEN ps.PlanSectionID = 7 AND SubSectionID = 5 THEN 'Reimbursement - Service Line' + WHEN ps.PlanSectionID = 7 AND SubSectionID = 7 THEN 'Reimbursement - General Ledger' + ELSE Description + END AS Description, + PlanSectionGUID AS MemberGUID, + HistoryItemGUID + FROM fp.PlanSection ps + LEFT JOIN fp.PlanSubSection pss on ps.PlanSectionID = pss.PlanSectionID + WHERE ISNULL(SubSectionID, '') <> 6 -- Exluding Reimbursement Charges +GO + + +--------------------------------------------- + +-- fp.viewDimSection_auto +--Last Modified 12/23/2024 10:16 AM +CREATE VIEW [fp].[viewDimSection_auto] +AS +SELECT + grpAE25CD3C290A48A697B5C97D7FBE44E2.[SectionID] + ,coalesce(grpAE25CD3C290A48A697B5C97D7FBE44E2.[Description],'') as [Description] + ,grpAE25CD3C290A48A697B5C97D7FBE44E2.[MemberGUID] +, [grpAE25CD3C290A48A697B5C97D7FBE44E2].[HistoryItemGUID]FROM [fp].[viewDimSection] grpAE25CD3C290A48A697B5C97D7FBE44E2 +GO + + +--------------------------------------------- + +-- fp.viewDimServiceEntity +CREATE VIEW [fp].[viewDimServiceEntity] +AS + SELECT + EntityID AS [ServiceEntityID] + ,Name + ,Code AS [Code] + ,Description + ,SortOrder + ,EntityType + ,IsActive + ,CAPIsDefined + ,DSSIsDefined + ,OBIsDefined + ,OBBenefitsDepartmentID + ,OBHasGlobalStatisticsPlan + ,OBHasReimbursementPlan + ,OBHasServiceLinePlan + ,OBIsUsingProviderComp + ,SPIsDefined + ,SPGrossChargesPatientTypeRollup + ,SPGrossChargesPayorGroup + ,SPContractualsPatientTypeRollup + ,SPContractualsPayorGroup + ,SPIPVolumesPatientTypeRollup + ,SPIPVolumesPayorGroup + ,SPIPDaysPatientTypeRollup + ,SPIPDaysPayorGroup + ,SPOPVolumesPatientTypeRollup + ,SPOPVolumesPayorGroup + ,SPFTEsJobCodeGroup + ,SPSalariesJobCodeGroup + ,SPClinicGrossChargesPayorGroup + ,SPClinicContractualsPayorGroup + ,SPClinicPrimaryVolumePhysicianGroup + ,SPClinicSecondaryVolumePhysicianGroup + ,SPClinicFTEsPhysicianGroup + ,SPClinicSalariesPhysicianGroup + ,SPOperationsSLDrivenModelID + ,SPRollingForecastSLDrivenModelID + ,SPServiceLineForecastType + ,SecureGroupID + ,WorkWeekID + ,TransactionID + ,PayCycleID + ,HistoryItemGUID + ,MemberGUID + ,CAPDefaultSalesTax + ,FWIsDefined + ,EliminationsDepartmentID + + ,[OBBenefitsDepartment] [OBBenefitsDepartment] +FROM [fw].[DimEntity]; +GO + + +--------------------------------------------- + +-- fp.viewDimServiceEntity_auto +--Last Modified 11/16/2020 3:28 PM +CREATE VIEW [fp].[viewDimServiceEntity_auto] +AS +SELECT + grp5666302E7CA94A6685CFFA1BBE6A261F.[ServiceEntityID] + ,coalesce(grp5666302E7CA94A6685CFFA1BBE6A261F.[Name],'') as [Name] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[Code] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[Description] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SortOrder] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[EntityType] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[IsActive] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[CAPIsDefined] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[DSSIsDefined] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[OBIsDefined] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[OBBenefitsDepartmentID] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[OBHasGlobalStatisticsPlan] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[OBHasReimbursementPlan] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[OBHasServiceLinePlan] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[OBIsUsingProviderComp] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPIsDefined] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPGrossChargesPatientTypeRollup] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPGrossChargesPayorGroup] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPContractualsPatientTypeRollup] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPContractualsPayorGroup] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPIPVolumesPatientTypeRollup] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPIPVolumesPayorGroup] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPIPDaysPatientTypeRollup] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPIPDaysPayorGroup] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPOPVolumesPatientTypeRollup] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPOPVolumesPayorGroup] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPFTEsJobCodeGroup] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPSalariesJobCodeGroup] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPClinicGrossChargesPayorGroup] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPClinicContractualsPayorGroup] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPClinicPrimaryVolumePhysicianGroup] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPClinicSecondaryVolumePhysicianGroup] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPClinicFTEsPhysicianGroup] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPClinicSalariesPhysicianGroup] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPOperationsSLDrivenModelID] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPRollingForecastSLDrivenModelID] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SPServiceLineForecastType] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[WorkWeekID] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[SecureGroupID] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[TransactionID] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[PayCycleID] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[HistoryItemGUID] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[MemberGUID] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[CAPDefaultSalesTax] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[FWIsDefined] + ,grp5666302E7CA94A6685CFFA1BBE6A261F.[EliminationsDepartmentID] + ,ISNULL([DEPT].[Name], 'Not Specified') as [OBBenefitsDepartment] +FROM [fp].[viewDimServiceEntity] grp5666302E7CA94A6685CFFA1BBE6A261F + INNER JOIN [fw].[viewDimDepartment] [DEPT] on [DEPT].[DepartmentID] = [grp5666302E7CA94A6685CFFA1BBE6A261F].[OBBenefitsDepartmentID] +GO + + +--------------------------------------------- + +-- fp.viewDimSubAccountCategory +--Last Modified 2/22/2022 10:18 AM +CREATE VIEW [fp].[viewDimSubAccountCategory] +AS +SELECT + grp335A2DAAD2584078A30A81CA9B64823B.[SubAccountCategoryID] + ,grp335A2DAAD2584078A30A81CA9B64823B.[Description] + ,grp335A2DAAD2584078A30A81CA9B64823B.[CategoryRollUp] + ,grp335A2DAAD2584078A30A81CA9B64823B.[FullDescription] + ,grp335A2DAAD2584078A30A81CA9B64823B.[TransactionID] + ,grp335A2DAAD2584078A30A81CA9B64823B.[MemberGUID] + ,grp335A2DAAD2584078A30A81CA9B64823B.[HistoryItemGUID] +FROM [fp].[DimSubAccountCategory] grp335A2DAAD2584078A30A81CA9B64823B (readuncommitted) +GO + + +--------------------------------------------- + +-- fp.viewEntityAccessByUser +CREATE VIEW [fp].[viewEntityAccessByUser] +AS + SELECT + a.EntityGroupConfigID, + a.Section, + ra.IdentityGUID as UserGUID, + REPLACE(ra.LootGroupID, 'DEPT|', '') as DepartmentID, + MAX(a.AccessType) as AccessType + FROM + [fp].[APESectionRoleAccess] a + LEFT JOIN [dbo].[viewS3RoleAssignment] ra ON ra.RoleID = a.RoleID + INNER JOIN [fw].[DimDepartment] dept ON 'DEPT|' + CAST(dept.DepartmentID as nvarchar(10)) = ra.LootGroupID + INNER JOIN fp.EntityGroupConfig egc ON a.EntityGroupConfigID = egc.EntityGroupConfigID + INNER JOIN fp.EntityGroupConfigMapping egcm + ON egc.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID + AND dept.EntityID = egcm.EntityID + WHERE + a.budgetphaseid = 2 + AND ra.lootgroupid like 'DEPT|%' + GROUP BY + a.EntityGroupConfigID, + a.Section, + ra.IdentityGUID, + ra.LootGroupID + HAVING + MAX(a.AccessType) > 0 +GO + + +--------------------------------------------- + +-- fp.viewExceptionDepartmentsWithoutBudget +CREATE VIEW fp.viewExceptionDepartmentsWithoutBudget +AS +/******************************************************************************* +** Change History +******************************************************************************** +** CID Date Author WI Description +** 1 04-24-2024 VZ JAZZ-69354 Initial Creation +** 2 05-17-2024 NH JAZZ-71771 Update report messages +*******************************************************************************/ +-- Has YTD data but no budgeted data +SELECT DISTINCT + dep.DepartmentID , + acc.AccountID , + 'Department has ' + CAST(CAST(SUM(glh.ActualYTDValueTotal) AS DECIMAL(16,2)) AS NVARCHAR(100)) + ' current year for account ' + ACC.[Name] + ' but does not have a budget.' AS [Detail] +FROM fp.GeneralLedger gl + INNER JOIN fp.GeneralLedgerHistory glh ON glh.GeneralLedgerID = gl.GeneralLedgerID + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = gl.BudgetConfigID + INNER JOIN fw.DimDepartment dep ON dep.DepartmentID = gl.DepartmentID + INNER JOIN fw.DimAccount acc ON acc.AccountID = gl.AccountID +WHERE bc.IsActive =1 and ActualYTDValueTotal <> 0 and BudgetAdjustedTotal = 0 +GROUP BY +dep.DepartmentID, +acc.AccountID, +Acc.Name +GO + + +--------------------------------------------- + +-- fp.viewExceptionDeptMissingPrimaryStatsConfig +CREATE VIEW [fp].[viewExceptionDeptMissingPrimaryStatsConfig] +AS +/******************************************************************************* +** Change History +******************************************************************************** +** CID Date Author WI Description +** 1 04-24-2024 VZ JAZZ-69354 Initial Creation +** 2 05-17-2024 NH JAZZ-71771 Update report messages +** 3 07-04-2024 VZ JAZZ-69920 Added EntityGroupConfig +*******************************************************************************/ +-- Missing Primary Statistics Mappings + + +-- Set as driver but no values to drive +SELECT DISTINCT + dep.DepartmentID, + acc.AccountID, + 'Driver statistics exist but no data exists for the mapped department/account.' AS Detail, + ec.EntityGroupConfigGuid, + ec.Name +FROM fp.PrimaryStatisticsConfig ps +INNER JOIN fp.EntityGroupConfig EC ON EC.EntityGroupConfigGUID = ps.EntityGroupConfigGUID +INNER JOIN fp.BudgetConfig BC ON BC.BudgetConfigGUID = EC.BudgetConfigGUID +INNER JOIN fw.DimDepartment Dep ON dep.DepartmentID = ps.DepartmentID +INNER JOIN fw.DimAccount acc ON acc.accountID = ps.AccountID +WHERE bc.IsActive =1 +AND Cast(IsRevenue AS INT) + Cast(IsStaffing AS INT) + Cast(IsNonStaffing AS INT) <>0 -- has driver set +AND -- Stat YTD data does not exist + + ( + SELECT SUM(SampledProjectionTotal) FROM fp.FactStatistics FS + WHERE FS.DepartmentID = ps.DepartmentID + AND fs.AccountID = ps.AccountID + AND BC.BudgetConfigID = FS.BudgetConfigID + ) <> 0 + +UNION ALL + +-- Has Stat data but not in primary stats driver table + +SELECT DISTINCT + dep.DepartmentID, + acc.AccountID, + 'Statisitics data is mapped to a department/account but you must configure a driver statistic.' AS Detail, + ec.EntityGroupConfigGuid, + ec.Name +FROM fp.FactStatistics fs +INNER JOIN fw.DimDepartment dep ON dep.DepartmentID = fs.DepartmentID +INNER JOIN fw.DimAccount acc ON acc.accountID = fs.AccountID +INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = fs.BudgetConfigID +INNER JOIN fp.EntityGroupConfig EC ON EC.BudgetConfigGUID = bc.BudgetConfigGUID +WHERE SampledProjectionTotal <> 0 -- NOn -zero stats data +AND dep.OBIsDefined = 1 AND dep.IsVariable = 1 +AND bc.IsActive = 1 -- Active Configuration +AND EXISTS + ( + SELECT * FROM fp.PrimaryStatisticsConfig ps + WHERE ps.DepartmentID = fs.DepartmentID + AND ps.AccountID = acc.accountID + AND ps.EntityGroupConfigGUID = EC.EntityGroupConfigGUID + AND Cast(IsRevenue AS Int) + Cast(IsStaffing AS Int) + Cast(IsNonStaffing AS Int) = 0 + ) +GO + + +--------------------------------------------- + +-- fp.viewExceptionDeptMissingProductivityStandard +CREATE VIEW [fp].[viewExceptionDeptMissingProductivityStandard] +AS +/******************************************************************************* +** Change History +******************************************************************************** +** CID Date Author WI Description +** 1 04-24-2024 VZ JAZZ-69354 Initial Creation +** 2 05-17-2024 NH JAZZ-71771 Update report messages +** 3 07-05-2024 VZ JAZZ-69920 Added EntityGroupConfigGuid +*******************************************************************************/ +----Missing Productivity Standards --- +SELECT DISTINCT + bc.BudgetConfigID, + EC.Name AS EntityGroupConfig, + dep.departmentID, + 'Department has variable job codes but you must specify productivity standards for flexing.' AS Detail, + EC.EntityGroupConfigGUID, + EC.Name +FROM fp.StaffingExpenseFlexingConfig fc + INNER JOIN fp.EntityGroupConfig EC ON EC.EntityGroupConfigGUID = fc.EntityGroupConfigGUID + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = EC.BudgetConfigGUID + INNER JOIN fw.DimDepartment dep ON dep.departmentID = fc.DepartmentID + INNER JOIN fp.PayrollVariabilityConfig pc ON pc.EntityGroupConfigGUID = EC.EntityGroupConfigGUID + INNER JOIN fp.Staffing fs ON fs.BudgetConfigID = bc.BudgetConfigID AND fs.departmentID = fc.departmentID AND fs.jobcodeID = pc.jobcodeid -- Data Check +WHERE bc.IsActive = 1 --- Active Configuration + AND EC.IsPatientActivityFlexingForStaffing = 0 -- Non PAF Clients + AND fc.FlexMethodID = 1 --- Flex Method = Stat Accounts + AND NOT EXISTS (SELECT 1 FROM fp.StaffingVariabilityOverrideConfig varovr WHERE varovr.entityGroupConfigGUID = fc.EntityGroupConfigGUID AND fc.departmentID = varovr.DepartmentID AND pc.Jobcodeid = varovr.JobCodeID AND varovr.Variability = 0) -- JC variability Override check + AND NOT EXISTS (SELECT 1 FROM fp.StaffingFlexingOverrideConfig stovr WHERE stovr.EntityGroupConfigGUID = EC.EntityGroupConfigGUID AND stovr.DepartmentID = fc.DepartmentID AND stovr.JobCodeID = pc.JobCodeID AND stovr.FlexMethodID = 6 )-- Flexing Override Check + AND fc.IsUsingProductivityTarget = 1 -- Set to use target + AND fc.ProductivityTarget = 0 + AND pc.Variability != 0 -- Only Variable jobcodes" +GO + + +--------------------------------------------- + +-- fp.viewExceptionInvalidDeductionsFlexingSetup +CREATE VIEW [fp].[viewExceptionInvalidDeductionsFlexingSetup] +AS + +/******************************************************************************* +** Change History +******************************************************************************** +** CID Date Author WI Description +** 1 04-24-2024 VZ JAZZ-69354 Initial Creation +** 2 05-17-2024 NH JAZZ-71771 Update report messages +** 3 07-05-2024 VZ JAZZ-69920 Added EntityGroupConfig +*******************************************************************************/ + +-- UseCase#1 : No underlying charge data for depts set to flex on charges -- +-- Dept setup for deductions flexing-- +SELECT DISTINCT + dep.DepartmentID, + 'No revenue data exists for the selected fiscal year/time class from the deductions baseline in [int].[FactGL].' AS Detail, + egc.EntityGroupConfigGUID, + egc.Name +FROM fp.deductionsflexingConfig fc +INNER JOIN fp.entitygroupConfig egc ON egc.entityGroupConfigGUID= fc.entityGroupConfiggUID +INNER JOIN fp.budgetconfig bc ON bc.budgetconfigGUID = egc.BudgetConfigGUID +INNER JOIN fw.dimdepartment dep ON dep.departmentID = fc.departmentID +WHERE bc.isactive =1 AND fc.flexmethodID =8 -- Total Gross Charges +-- There was no revenue data found for the selected fiscal year/time class from the deduction baseline in [int].[FactGL] +AND NOT EXISTS (SELECT * FROM [int].[FactGL] gl + WHERE gl.FiscalYearID = egc.RevenueAndDeductionsFiscalYearID AND gl.TimeClassID = egc.RevenueAndDeductionsTimeClassID + AND gl.DepartmentID = dep.DepartmentID + AND + gl.AccountID IN ( + SELECT accountID FROM fw.DimAccount acc WHERE + acc.OBModelSectionName LIKE '%Charge%')) + +UNION ALL + +-- UseCase #2: No historical deductions data to establish base rate for flexing +SELECT DISTINCT + dep.DepartmentID, + 'No general ledger data exists for the selected fiscal year/time class from the deductions baseline in [int].[FactGL].' AS Detail, + egc.EntityGroupConfigGUID, + egc.Name +FROM fp.deductionsflexingConfig fc +INNER JOIN fp.entitygroupConfig egc ON egc.entityGroupConfigGUID= fc.entityGroupConfiggUID +INNER JOIN fp.budgetconfig bc ON bc.budgetconfigGUID = egc.BudgetConfigGUID +INNER JOIN fw.dimdepartment dep ON dep.departmentID = fc.departmentID +WHERE bc.isactive =1 AND fc.flexmethodID =8 -- Total Gross Charges + +-- There was no revenue data found for the selected fiscal year/time class from the deduction baseline in [int].[FactGL] +AND NOT EXISTS (SELECT * FROM [int].[FactGL] gl + WHERE gl.FiscalYearID = egc.RevenueAndDeductionsFiscalYearID AND gl.TimeClassID = egc.RevenueAndDeductionsTimeClassID + AND gl.DepartmentID = dep.DepartmentID + AND + gl.AccountID IN ( + SELECT accountID FROM fw.DimAccount acc WHERE + acc.OBModelSectionName LIKE '%Deductions%')) +GO + + +--------------------------------------------- + +-- fp.viewExceptionInvalidRevenueFlexingSetup +CREATE VIEW [fp].[viewExceptionInvalidRevenueFlexingSetup] +AS + +/******************************************************************************* +** Change History +******************************************************************************** +** CID Date Author WI Description +** 1 04-24-2024 VZ JAZZ-69354 Initial Creation +** 2 05-17-2024 NH JAZZ-71771 Update report messages +** 3 07-05-2024 VZ JAZZ-69920 Added EntityGroupConfig +*******************************************************************************/ + +-- Revenue Flexing (Invalid Setup) +-- Dept flex driver set as Stats +-- No overrides +-- YTD revenue data +-- revenue driver set for primary stats +-- NO Stats data available + +--<<<<<<<<<<<<<<<< Flex Method = ID =3 --> Statistics Accounts By PatientClass --<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< +SELECT DISTINCT + dep.DepartmentID , + acc.AccountID , + flex.FlexMethodID , + 'Statistics Accounts By Patient Class' AS FlexMethod, + 'Department is set up for flexing but has no statistics data for statistics accounts by patient class.' AS Detail, + ec.EntityGroupConfigGUID, + ec.Name +FROM fp.GeneralLedger gl + INNER JOIN fp.GeneralLedgerHistory hi ON hi.GeneralLedgerID = gl.generalledgerID + INNER JOIN fw.dimdepartment dep ON dep.departmentID = gl.departmentID + INNER JOIN fw.dimaccount acc ON acc.accountID = gl.accountID + INNER join fp.BudgetConfig bc ON bc.budgetconfigID = gl.BudgetConfigID + INNER JOIN fp.EntityGroupConfig ec ON ec.budgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.ModelSectionMap map ON map.APEModelSectionID = gl.APEModelSectionID AND map.OBModelSectionName = acc.OBModelSectionName + INNER JOIN fp.RevenueExpenseFlexingConfig flex ON flex.departmentID = gl.departmentID AND flex.EntityGroupConfigGUID = ec.EntityGroupConfigGUID +WHERE bc.IsActive =1 AND ec.IsPatientActivityFlexingForNonStaffing <> 1 -- NON ABB/PAF client + AND map.APEModelSectionName ='Revenue' + AND hi.ActualYTDValueTotal <> 0 -- has YTD data + AND gl.VariabilityID <> 1 -- Revenues are always 100% variable unless for fixed dept or set overrides + AND flex.flexMethodID = 3 -- Stats by patient Class + AND NOT EXISTS -- No Overrides + ( + SELECT 1 + FROM fp.RevenueFlexingOverrideConfig ovr + WHERE ovr.DepartmentID = gl.DepartmentID + AND ovr.AccountID = gl.AccountID + AND ovr.EntityGroupConfigGUID = ec.EntityGroupConfigGUID + AND ovr.FlexMethodID = 6 -- Override as "Fixed" + ) --- Missing Flexmapping probably due to mismatch patient class + AND NOT EXISTS + ( + SELECT 1 + FROM fp.FlexConfigMapping map + INNER JOIN fp.FactStatistics fstat ON fstat.DepartmentID = map.DepartmentID AND fstat.AccountID = map.StatAccountID + WHERE map.GLAccountID = acc.AccountID + AND map.EntityGroupConfigID = ec.entitygroupConfigID + ) + + --- Primary Stats drivers Exists ---- + AND EXISTS + ( + SELECT 1 + FROM fp.PrimaryStatisticsConfig ps + WHERE ps.DepartmentID = gl.DepartmentID + AND ps.EntityGroupConfigGUID = ec.EntityGroupConfigGUID + AND ps.IsRevenue =1 + + -- No Data + AND NOT EXISTS + ( + SELECT * + FROM fp.FactStatistics fs + WHERE fs.departmentID = ps.departmentID + AND fs.accountID = ps.accountid + AND Fs.PatientClassID = acc.patientclassID + AND fs.EntityGroupConfigID = ec.EntityGroupConfigID + AND SampledProjectionTotal <> 0 -- Non Zero volume data for driver statistics + ) + ) + +UNION ALL + +--<<<<<<<<<<<<<<<< Flex Method = ID =4 --> Total Statistics Accounts--<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< +SELECT DISTINCT + dep.DepartmentID , + acc.AccountID , + flex.FlexMethodID, + 'Total Statistics Accounts' AS FlexMethod, + 'Department is set up for flexing but has no statistics data for total statistics accounts.' AS Detail, + ec.EntityGroupConfigGUID, + ec.Name +FROM fp.GeneralLedger gl + INNER JOIN fp.GeneralLedgerHistory hi ON hi.GeneralLedgerID = gl.GeneralLedgerID + INNER JOIN fw.DimDepartment dep ON dep.DepartmentID = gl.DepartmentID + INNER JOIN fw.DimAccount acc ON acc.AccountID = gl.AccountID + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = gl.BudgetConfigID + INNER JOIN fp.EntityGroupConfig ec ON ec.budgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.ModelSectionMap map ON map.APEModelSectionID = gl.APEModelSectionID + INNER JOIN fp.RevenueExpenseFlexingConfig flex ON flex.departmentID = gl.departmentID AND flex.EntityGroupConfigGUID = ec.EntityGroupConfigGUID +WHERE BC.IsActive =1 AND EC.IsPatientActivityFlexingForNonStaffing <> 1 -- NON ABB/PAF client + AND map.APEModelSectionName ='Revenue' + AND hi.ActualYTDValueTotal <> 0 -- has YTD data + AND gl.VariabilityID <> 1 -- Revenues are always 100% variable unless for fixed dept or set overrides + AND flex.flexMethodID = 4 -- Total Statistics Accounts + AND NOT EXISTS -- No Overrides + ( + SELECT 1 + FROM fp.RevenueFlexingOverrideConfig ovr + WHERE ovr.DepartmentID = gl.DepartmentID + AND ovr.AccountID = gl.AccountID + AND ovr.FlexMethodID = 6 -- Override as "Fixed" + ) --- Primary Stats drivers Exists ---- + AND EXISTS + ( + SELECT 1 + FROM fp.PrimaryStatisticsConfig ps + WHERE ps.DepartmentID = gl.DepartmentID + AND ps.EntityGroupConfigGUID = ec.EntityGroupConfigGUID + AND ps.IsRevenue =1 + + AND NOT EXISTS + ( + SELECT * + FROM fp.FactStatistics fs + INNER JOIN fw.DimAccount acc2 ON acc2.accountID = fs.AccountID + INNER JOIN fp.entitygroupconfig ecc ON ecc.entitygroupconfigID = fs.entitygroupconfigID + WHERE fs.departmentID = ps.departmentID + AND fs.accountID = ps.accountid + AND ps.EntityGroupConfigGUID = ecc.EntityGroupConfigGUID + AND SampledProjectionTotal <>0 -- Non Zero volume data for driver statistics + ) + ) +GO + + +--------------------------------------------- + +-- fp.viewExceptionVariableDeptNoFlexDrivers +CREATE VIEW [fp].[viewExceptionVariableDeptNoFlexDrivers] +AS +/******************************************************************************* +** Change History +******************************************************************************** +** CID Date Author WI Description +** 1 04-24-2024 VZ JAZZ-69354 Initial Creation +** 2 05-17-2024 NH JAZZ-71771 Update report messages +** 3 07-05-2024 VZ JAZZ-69920 Added EntityGroupConfig +*******************************************************************************/ +SELECT DISTINCT + Dd.DepartmentID, + 'Department has variable expense accounts but you must configure statistics accounts to drive expense accounts.' AS Detail, + egc.EntityGroupConfigGuid, + egc.Name +FROM [fp].[GeneralLedger] SF1 WITH (readuncommitted) + INNER JOIN [fw].[DimDepartment] DD WITH (readuncommitted) ON SF1.DepartmentID=DD.DepartmentID --CID 2 + INNER JOIN [fw].[DimAccount] DA ON SF1.AccountID=DA.AccountID + LEFT JOIN [fp].[ModelSectionMap] msm ON msm.OBModelSectionName = DA.OBModelSectionName + INNER join [fp].[BudgetConfig] bc1 ON bc1.BudgetConfigID=SF1.BudgetConfigID + INNER JOIN [fp].EntityGroupConfig egc ON SF1.EntityGroupConfigID = egc.EntityGroupConfigID +WHERE + 1=1 + AND bc1.IsActive='1' + AND MSM.ModelSectionMapID='6' --Expenses - Non-Staffing + AND DD.IsVariable=1 + AND DA.Variability=1 + AND SF1.InitialProjectionTotal<>0 + AND NOT EXISTS + ( + SELECT TOP 1 1 FROM [fp].[PrimaryStatisticsConfig] psc + INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID=psc.EntityGroupConfigGUID + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigGUID=egc.BudgetConfigGUID + WHERE bc.IsActive='1' AND psc.DepartmentID=dd.DepartmentID AND psc.IsNonStaffing='1' + ) + +UNION ALL + +SELECT DISTINCT + dd.DepartmentID, + 'Department has variable job codes but you must configure statistics accounts to drive staffing.' AS Detail, + egc.EntityGroupConfigGuid, + egc.Name +FROM [fp].[Staffing] SF1 WITH (readuncommitted) + INNER JOIN [fw].[DimDepartment] DD WITH (readuncommitted) ON SF1.DepartmentID=DD.DepartmentID --CID 2 + INNER JOIN [fw].[DimJobCode] JJ WITH (readuncommitted) ON SF1.JobCodeID=jj.JobCodeID + INNER join [fp].[BudgetConfig] bc1 ON bc1.BudgetConfigID=SF1.BudgetConfigID + INNER JOIN [fp].EntityGroupConfig egc ON SF1.EntityGroupConfigID = egc.EntityGroupConfigID +WHERE + 1=1 + AND bc1.IsActive='1' + AND DD.IsVariable=1 + AND JJ.IsVariable=1 + AND NOT EXISTS + ( + SELECT TOP 1 1 FROM [fp].[PrimaryStatisticsConfig] psc + INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID=psc.EntityGroupConfigGUID + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigGUID=egc.BudgetConfigGUID + WHERE bc.IsActive='1' AND psc.DepartmentID=dd.DepartmentID AND psc.IsStaffing='1' + ) +GO + + +--------------------------------------------- + +-- fp.viewExceptionsDepsWithRegularPCGNOHoursNODollars +CREATE VIEW fp.viewExceptionsDepsWithRegularPCGNOHoursNODollars +AS +/******************************************************************************* +** Change History +******************************************************************************** +** CID Date Author WI Description +** 1 04-24-2024 VZ JAZZ-69354 Initial Creation +** 2 05-17-2024 NH JAZZ-71771 Update report messages +*******************************************************************************/ +SELECT DISTINCT + dep.DepartmentID, + JC.JobCodeID, + 'Department has only non-regular hours/dollars for job code '+JC.name+' and cannot project non-regular dollars.' AS 'Detail' +FROM ( + SELECT + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.budgetconfigID, + fs.variabilityID + FROM fp.staffing fs + INNER JOIN fw.DimPayCodeGroup PCG ON PCG.paycodegroupID = fs.paycodegroupID + INNER JOIN fw.dimproductiveClass PC ON pCG.ProductiveClassID = PC.ProductiveClassID + WHERE PC.ProductiveClassID NOT IN (3, 4) -- Productive , Dollars Only + AND sampledProjectionDollarsTotal <> 0 AND SampledProjectionHoursTotal <> 0 -- Non Zero Non-Regular Dollars +) Other +INNER JOIN ( + SELECT -- Zero YTD Dollars + fs.departmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.budgetConfigID, + fs.variabilityID + FROM fp.staffing fs + INNER JOIN fw.DimPayCodeGroup PCG ON PCG.paycodegroupID = fs.paycodegroupID + INNER JOIN fw.dimproductiveClass PC ON pCG.ProductiveClassID = PC.ProductiveClassID + WHERE PC.Name ='Productive' AND fs.paycodegroupID = 1048 -- Regular + AND sampledProjectionDollarsTotal = 0 AND SampledProjectionHoursTotal = 0 -- Zero YTD Dollars +) Regular ON Other.DepartmentID = Regular.DepartmentID + AND other.JobCodeID = Regular.JobCodeID + AND Other.BudgetConfigID = Regular.BUdgetConfigID + AND other.VariabilityID = Regular.VariabilityID + INNER JOIN fw.dimdepartment dep ON dep.departmentID = Regular.departmentID + INNER JOIN fw.DimJobCode JC ON JC.jobcodeid = Regular.Jobcodeid + INNER JOIN fp.budgetcOnfig bc ON bc.budgetConfigID = Regular.budgetconfigID + INNER JOIN fp.EntityGroupConfig ec ON ec.budgetConfigGUID = bc.BudgetConfigGUID +WHERE bc.IsActive =1 -- Active Config +GO + + +--------------------------------------------- + +-- fp.viewExceptionsDeptProjectionEqualsYTD +CREATE VIEW fp.viewExceptionsDeptProjectionEqualsYTD +AS + +/******************************************************************************* +** Change History +******************************************************************************** +** CID Date Author WI Description +** 1 04-24-2024 VZ JAZZ-69354 Initial Creation +** 2 05-17-2024 NH JAZZ-71771 Update report messages +*******************************************************************************/ + +SELECT DISTINCT +dep.DepartmentID , +acc.AccountID , +'Department has projection equal to YTD for account ' + acc.Name + '.' AS Detail +FROM fp.generalledger gl + INNER JOIN fp.generalledgerHistory glh ON glh.generalledgerID = gl.generalledgerID + INNER JOIN fp.budgetconfig bc ON bc.budgetconfigid = gl.budgetconfigID + INNER JOIN fw.DimDepartment dep ON dep.departmentID = gl.departmentID + INNER JOIN fw.dimaccount acc ON acc.accountID = gl.accountID +WHERE bc.IsActive =1 AND ActualYTDValueTotal <>0 -- Final +AND glh.ActualYTDValueTotal = InitialProjectionTotal AND + bc.MonthsLoaded <> 12 +GO + + +--------------------------------------------- + +-- fp.viewExceptionsJobCodePayCodeGroupMissingPayrollToAccountCrosswalkConfigurations +CREATE VIEW [fp].[viewExceptionsJobCodePayCodeGroupMissingPayrollToAccountCrosswalkConfigurations] +AS + +/******************************************************************************* +** Change History +******************************************************************************** +** CID Date Author WI Description +** 1 04-24-2024 VZ JAZZ-69354 Initial Creation +** 2 05-17-2024 NH JAZZ-71771 Update report messages +** 3 07-02-2024 VZ JAZZ-73527 Update script to better performance +** 4 08-15-2024 MZ JAZZ-75111 Cleaned up the View & removed DepartmentID +** 5 08-27-2024 MZ JAZZ-76012 Fix checking cw.PayCodeGroupID instead of Staffing +*******************************************************************************/ + +SELECT DISTINCT + s.JobCodeID, + s.PayCodeGroupID, + pcg.Name +' dollars budgeted to ' + jc.Name + ' but you must map the payroll combination to a GL account.' AS 'Detail' +FROM [fp].[Staffing] s + INNER JOIN [fw].[DimPayCodeGroup] pcg WITH (readuncommitted) + ON s.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN [fw].[DimJobCode] jc WITH (readuncommitted) + ON s.JobCodeID = jc.JobCodeID + INNER JOIN [fp].[BudgetConfig] bc + ON s.BudgetConfigID = bc.BudgetConfigID +WHERE + s.BudgetAdjustedDollarsTotal <> 0 + AND bc.IsActive = 1 + AND s.SubsectionID = 3 + AND NOT EXISTS ( + SELECT 1 + FROM [clientob].[FactPayrollToAccountCrosswalk] cw WITH (readuncommitted) + WHERE + ( + (cw.JobCodeID = s.JobCodeID AND cw.PayCodeGroupID = s.PayCodeGroupID) --pay code group and job code specific + OR (cw.JobCodeID = s.JobCodeID AND cw.PayCodeGroupID = 0) --job code specific + OR (cw.JobCodeID = 0 AND cw.PayCodeGroupID = s.PayCodeGroupID) --pay code group specific + ) + AND cw.UnitTypeID = 34 --dollars + AND cw.IsDeleted = 0 + ) +GO + + +--------------------------------------------- + +-- fp.viewExceptionsJobCodesWithHoursButNODollars +CREATE View [fp].[viewExceptionsJobCodesWithHoursButNODollars] +AS +/******************************************************************************* +** Change History +******************************************************************************** +** CID Date Author WI Description +** 1 04-24-2024 VZ JAZZ-69354 Initial Creation +** 2 05-17-2024 NH JAZZ-71771 Update report messages +*******************************************************************************/ + SELECT DISTINCT + + dep.DepartmentID, + Jc.JobCodeID, + 'Department has hours in pay code group ' + + pcg.name + + ' but no dollars for job code ' + + jc.name + + '.' + + AS Detail + + FROM fp.staffing fs + INNER JOIN fw.dimdepartment dep ON dep.departmentid = fs.departmentid + INNER JOIN fw.dimjobcode jc ON jc.jobcodeid = fs.jobcodeid + INNER JOIN fw.DimPayCodeGroup pcg ON pcg.paycodegroupID = fs.paycodegroupID + INNER JOIN fp.budgetconfig bc ON bc.budgetconfigid = fs.budgetconfigid + INNER JOIN fp.EntityGroupConfig ec ON ec.budgetConfigGUID = bc.budgetConfigGUID +WHERE bc.IsActive =1 +AND fs.ProductiveClassID NOT IN (4,5,6) --Productive Non-FTE', 'Differential', 'Dollars-Only' EXCLUDED from FTE Calcs +AND jc.jobcodeid <>0 + AND fs.InitialProjectionDollarsTotal <>0 + + AND NOT EXISTS + ( + SELECT 1 + FROM fp.Staffing fs2 + WHERE + fs2.BudgetConfigID = fs.BudgetConfigID + AND fs2.departmentid = fs.departmentid + AND fs2.jobcodeid = fs.jobcodeid + AND fs2.paycodegroupid = fs.paycodegroupid + AND fs2.InitialProjectionDollarsTotal <>0 + ) +GO + + +--------------------------------------------- + +-- fp.viewExceptionsJobCodewithDollarsButNOHours +CREATE View [fp].[viewExceptionsJobCodewithDollarsButNOHours] +AS + +/******************************************************************************* +** Change History +******************************************************************************** +** CID Date Author WI Description +** 1 04-24-2024 VZ JAZZ-69354 Initial Creation +** 2 05-17-2024 NH JAZZ-71771 Update report messages +*******************************************************************************/ + +-- ************ JObCode with Dollars but NO Hours +--- ** Description: Checks for job code/pay code group combos that have dollars but not hours in historic time periods + +SELECT DISTINCT + DB.DepartmentID AS DepartmentID, + Jc.jobCodeID, + 'Department has dollars in pay code group ' + PCG.[Name] + ' but no hours for job code ' + JC.[Name] + '.' AS [Detail] + FROM fp.staffing AS ST WITH (READUNCOMMITTED) + INNER JOIN fw.dimdepartment AS DB WITH (READUNCOMMITTED) + ON DB.departmentID = ST.departmentID + INNER JOIN [fw].[DimJobCode] AS JC WITH (READUNCOMMITTED) + ON JC.[JobCodeID] = ST.[JobCodeID] + INNER JOIN [fw].[DimPayCodeGroup] AS PCG WITH (READUNCOMMITTED) + ON PCG.[PayCodeGroupID] = ST.[PayCodeGroupID] + INNER JOIN fp.Budgetconfig bc ON bc.BudgetConfigID = ST.budgetconfigID + INNER JOIN fp.entityGroupConfig EC ON EC.budgetConfigGUID = bc.BudgetConfigGUID +WHERE 1=1 +AND bc.IsActive =1 -- Active COnfig +AND PCG.[ProductiveClassID] NOT IN (4,6) --Productive Non-FTE', 'Dollars-Only' EXCLUDED from FTE Calcs +AND ST.InitialProjectionDollarsTotal != 0 +AND NOT EXISTS( + SELECT 1 + FROM fp.Staffing AS H WITH (READUNCOMMITTED) + WHERE 1=1 + AND H.DepartmentID = ST.DepartmentID + AND H.[JobCodeID] = ST.[JobCodeID] + AND H.[PayCodeGroupID] = ST.[PayCodeGroupID] + AND H.BudgetConfigID = ST.BudgetConfigID + AND H.InitialProjectionHoursTotal <>0 +) +GO + + +--------------------------------------------- + +-- fp.viewExceptionsNonStaffingExpenseInValidFlexingSetup +CREATE VIEW [fp].[viewExceptionsNonStaffingExpenseInValidFlexingSetup] +AS + +/******************************************************************************* +** Change History +******************************************************************************** +** CID Date Author WI Description +** 1 04-24-2024 VZ JAZZ-69354 Initial Creation +** 2 05-17-2024 NH JAZZ-71771 Update report messages +** 3 07-05-2024 VZ JAZZ-69920 Added EntityGroupConfig +*******************************************************************************/ + +-- Expense Flexing (Invalid Setup) +-- Dept flex driver set as Stats +-- No overrides +-- YTD Expense data +-- Expense driver set for primary stats +-- NO Stats data available + +--<<<<<<<<<<<<<<<< Flex Method = ID =1 --> Statistics Accounts --<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< + +SELECT DISTINCT + dep.DepartmentID , + acc.AccountID , + flex.FlexMethodID, + 'Statistics Accounts' AS FlexMethod, + 'Department is set up for flexing but has no statistics data for statistics accounts.' AS Detail, + EC.EntityGroupConfigGUID, + EC.Name +FROM [fp].[GeneralLedger] GL + INNER JOIN [fp].[GeneralLedgerHistory] hi ON hi.GeneralLedgerID = GL.GeneralLedgerID + INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = GL.DepartmentID + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = GL.AccountID + INNER join [fp].[BudgetConfig] BC ON BC.BudgetConfigID = GL.BudgetConfigID + INNER JOIN [fp].[EntityGroupConfig] EC ON EC.budgetConfigGUID = BC.BudgetConfigGUID + INNER JOIN [fp].[ModelSectionMap] map ON map.APEModelSectionID = GL.APEModelSectionID + INNER JOIN [fp].[NonStaffingExpenseFlexingConfig] flex ON flex.departmentID = GL.departmentID AND flex.EntityGroupConfigGUID = EC.EntityGroupConfigGUID +WHERE BC.IsActive =1 AND EC.IsPatientActivityFlexingForNonStaffing <> 1 -- NON ABB/PAF client + AND map.APEModelSectionName ='Non-Staffing' + AND hi.ActualYTDValueTotal <> 0 -- has YTD data + AND GL.VariabilityID <> 1 -- + AND flex.flexMethodID = 1 -- Statistic Accounts + AND NOT Exists -- No Overrides + ( + SELECT 1 + FROM [fp].[NonStaffingExpenseFlexingOverrideConfig] ovr + WHERE ovr.DepartmentID = GL.DepartmentID + AND ovr.AccountID = GL.AccountID + AND ovr.FlexMethodID = 6 -- Override as "Fixed" + ) + --- Primary Stats drivers Exists ---- + AND EXISTS + ( + SELECT 1 FROM [fp].[PrimaryStatisticsConfig] ps + WHERE ps.DepartmentID = gl.DepartmentID + AND ps.EntityGroupConfigGUID = ec.EntityGroupConfigGUID + AND ps.IsNonStaffing =1 + AND NOT EXISTS + ( + SELECT * + FROM [fp].[FactStatistics] fs + INNER JOIN fw.DimAccount acc2 ON acc2.AccountID = fs.AccountID + INNER JOIN fp.EntityGroupConfig ecc ON ecc.EntityGroupConfigID = fs.EntityGroupConfigID + WHERE fs.DepartmentID = ps.departmentID + --and fs.accountID = ps.accountid + AND ps.EntityGroupConfigGUID = ecc.EntityGroupConfigGUID + AND SampledProjectionTotal <>0 -- Non Zero volume data for driver statistics + ) + ) +GO + + +--------------------------------------------- + +-- fp.viewExcludedProductiveClassesForFTE +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-08-22 BK JAZZ-59251 Use ProductiveClassID = 4 instead of Dollars-Only to accommodate internationalization +************************************************************** +*/ +CREATE VIEW fp.viewExcludedProductiveClassesForFTE +AS + +SELECT PayCodeGroupID FROM [fw].[DimPayCodeGroup] pcg INNER JOIN [fw].[DimProductiveClass] pc on pcg.ProductiveClassID = pc.ProductiveClassID +WHERE pc.ProductiveClassID IN (4,5,6) +GO + + +--------------------------------------------- + +-- fp.viewExecutiveSummary +CREATE VIEW [fp].[viewExecutiveSummary] +AS + +select + [bc].[BudgetConfigID], + [ex].[DepartmentID], + Case + When [ex].[SummaryType] = '0' Then 'Statistics' + When [ex].[SummaryType] = '1' Then 'Revenue and Reductions' + When [ex].[SummaryType] = '2' Then 'Other Revenue' + When [ex].[SummaryType] = '3' Then 'Roster' + When [ex].[SummaryType] = '4' Then 'Staffing' + When [ex].[SummaryType] = '5' Then 'Benefits' + When [ex].[SummaryType] = '6' Then 'Non-Staffing Expense' + When [ex].[SummaryType] = '7' Then 'Staffing' + When [ex].[SummaryType] = '8' Then 'Provider Compensation' + Else 'Not implemented' End as SummaryTypeName, + [ex].[DateModified], + [ex].[LastAuthorGUID] as UserGUID, + [ex].[LastAuthorName], + [ex].[Comments] +from [fp].[ExecutiveSummary] ex + inner join [fp].[BudgetConfig] bc on bc.BudgetConfigGUID=ex.BudgetConfigGUID +GO + + +--------------------------------------------- + +-- fp.viewFactBenefits +CREATE VIEW fp.viewFactBenefits +AS +SELECT + b.BenefitsID, + b.BudgetConfigID, + b.EntityGroupConfigID, + b.DepartmentID, + b.FinancialReportingID, + b.EntityID, + b.AccountID, + b.UnitTypeID, + b.FlexMethodID, + bdgt.LockType as BudgetLockType, + bdgt.LockFlag as BudgetLockFlag, + bdgt.BudgetPhaseID as BudgetPhaseID, + proj.LockType as ProjectionLockType, + proj.LockFlag as ProjectionLockFlag, + b.InitialBudget01, b.InitialBudget02, b.InitialBudget03, b.InitialBudget04, b.InitialBudget05, b.InitialBudget06, b.InitialBudget07, b.InitialBudget08, b.InitialBudget09, b.InitialBudget10, b.InitialBudget11, b.InitialBudget12, b.InitialBudgetTotal, + b.InitialProjection01, b.InitialProjection02, b.InitialProjection03, b.InitialProjection04, b.InitialProjection05, b.InitialProjection06, b.InitialProjection07, b.InitialProjection08, b.InitialProjection09, b.InitialProjection10, b.InitialProjection11, b.InitialProjection12, b.InitialProjectionTotal, + bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12, bdgt.AdjustedValueTotal, + bdgt.FlexedValue01, bdgt.FlexedValue02, bdgt.FlexedValue03, bdgt.FlexedValue04, bdgt.FlexedValue05, bdgt.FlexedValue06, bdgt.FlexedValue07, bdgt.FlexedValue08, bdgt.FlexedValue09, bdgt.FlexedValue10, bdgt.FlexedValue11, bdgt.FlexedValue12, bdgt.FlexedValueTotal, + proj.AdjustedValue01 AS AdjustedProjectionValue01, proj.AdjustedValue02 AS AdjustedProjectionValue02, proj.AdjustedValue03 AS AdjustedProjectionValue03, proj.AdjustedValue04 AS AdjustedProjectionValue04, proj.AdjustedValue05 AS AdjustedProjectionValue05, proj.AdjustedValue06 AS AdjustedProjectionValue06, proj.AdjustedValue07 AS AdjustedProjectionValue07, proj.AdjustedValue08 AS AdjustedProjectionValue08, proj.AdjustedValue09 AS AdjustedProjectionValue09, proj.AdjustedValue10 AS AdjustedProjectionValue10, proj.AdjustedValue11 AS AdjustedProjectionValue11, proj.AdjustedValue12 AS AdjustedProjectionValue12, proj.AdjustedValueTotal AS AdjustedProjectionValueTotal, + proj.FlexedValue01 AS FlexedProjectionValue01, proj.FlexedValue02 AS FlexedProjectionValue02, proj.FlexedValue03 AS FlexedProjectionValue03, proj.FlexedValue04 AS FlexedProjectionValue04, proj.FlexedValue05 AS FlexedProjectionValue05, proj.FlexedValue06 AS FlexedProjectionValue06, proj.FlexedValue07 AS FlexedProjectionValue07, proj.FlexedValue08 AS FlexedProjectionValue08, proj.FlexedValue09 AS FlexedProjectionValue09, proj.FlexedValue10 AS FlexedProjectionValue10, proj.FlexedValue11 AS FlexedProjectionValue11, proj.FlexedValue12 AS FlexedProjectionValue12, proj.FlexedValueTotal AS FlexedProjectionValueTotal +FROM fp.FactBenefits b + INNER JOIN fp.FactBenefitsBudget bdgt ON b.BenefitsID = bdgt.BenefitsID + INNER JOIN fp.FactBenefitsProjection proj ON b.BenefitsID = proj.BenefitsID AND proj.BudgetPhaseID = bdgt.BudgetPhaseID +GO + + +--------------------------------------------- + +-- fp.viewFactBenefitsForHistoryViewer +CREATE VIEW [fp].[viewFactBenefitsForHistoryViewer] +AS +SELECT + ov.BenefitsID, + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.DepartmentID, + ov.AccountID, + ov.FinancialReportingID, + ov.UnitTypeID, + ov.FiscalMonthID, + ov.OriginalValue, + ov.FlexMethodID, + v.Value, + fv.FlexedValue, + ISNULL(ch.HistoryCount, 0) as HistoryCount +FROM ( + -- Unpivot for Value + SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT gl.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactBenefits gl + INNER JOIN fp.FactBenefitsBudget bdgt ON gl.BenefitsID = bdgt.BenefitsID + WHERE bdgt.BudgetPhaseID = 2) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v +INNER JOIN + -- Unpivot for OriginalValue + (SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.OriginalValue, FlexMethodID + FROM ( + SELECT gl.* + FROM fp.FactBenefits gl ) gl + UNPIVOT ( OriginalValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov + ON ov.DepartmentID = v.DepartmentID + AND ov.AccountID = v.AccountID + AND ov.BudgetConfigID = v.BudgetConfigID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN + -- Unpivot for OriginalValue + (SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.FlexedValue + FROM ( + SELECT gl.*, bdgt.LockType, bdgt.FlexedValue01, bdgt.FlexedValue02, bdgt.FlexedValue03, bdgt.FlexedValue04, bdgt.FlexedValue05, bdgt.FlexedValue06, bdgt.FlexedValue07, bdgt.FlexedValue08, bdgt.FlexedValue09, bdgt.FlexedValue10, bdgt.FlexedValue11, bdgt.FlexedValue12 + FROM fp.FactBenefits gl + INNER JOIN fp.FactBenefitsBudget bdgt ON gl.BenefitsID = bdgt.BenefitsID + WHERE bdgt.BudgetPhaseID = 2) gl + UNPIVOT ( FlexedValue FOR FiscalMonth IN (FlexedValue01, FlexedValue02, FlexedValue03, FlexedValue04, FlexedValue05, FlexedValue06, FlexedValue07, FlexedValue08, FlexedValue09, FlexedValue10, FlexedValue11, FlexedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'FlexedValue', 'Month')) fv + ON fv.DepartmentID = v.DepartmentID + AND fv.AccountID = v.AccountID + AND fv.BudgetConfigID = v.BudgetConfigID + AND fv.UnitTypeID = v.UnitTypeID + AND fv.FiscalMonthID = v.FiscalMonthID +LEFT JOIN + (SELECT BenefitsID, FiscalMonthID, count(*) as HistoryCount FROM [fp].[BenefitsChangeHistory] WHERE BudgetPhaseID = 2 AND TimeClassID = 2 GROUP BY BenefitsID, FiscalMonthID) ch + ON ch.BenefitsID = v.BenefitsID + AND ch.FiscalMonthID = v.FiscalMonthID +GO + + +--------------------------------------------- + +-- fp.viewFactBenefitsHistory_Unpivoted +CREATE VIEW fp.viewFactBenefitsHistory_Unpivoted +AS +-- Unpivot for PriorYearActual +SELECT data.BenefitsID, data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.AccountID, data.FinancialReportingID, data.UnitTypeID, 1 as TimeClassID, bc.FiscalYearID - 2 as FiscalYearID, data.FiscalMonthID, data.Value +FROM ( + SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT gl.*, hist.PriorYearActualValue01, hist.PriorYearActualValue02, hist.PriorYearActualValue03, hist.PriorYearActualValue04, hist.PriorYearActualValue05, hist.PriorYearActualValue06, hist.PriorYearActualValue07, hist.PriorYearActualValue08, hist.PriorYearActualValue09, hist.PriorYearActualValue10, hist.PriorYearActualValue11, hist.PriorYearActualValue12 + FROM fp.FactBenefits gl (READUNCOMMITTED) + INNER JOIN fp.FactBenefitsHistory hist (READUNCOMMITTED) + ON gl.BenefitsID = hist.BenefitsID ) gl + UNPIVOT ( Value FOR FiscalMonth IN (PriorYearActualValue01, PriorYearActualValue02, PriorYearActualValue03, PriorYearActualValue04, PriorYearActualValue05, PriorYearActualValue06, PriorYearActualValue07, PriorYearActualValue08, PriorYearActualValue09, PriorYearActualValue10, PriorYearActualValue11, PriorYearActualValue12)) as f + INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'PriorYearActualValue', 'Month')) data + INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID + +UNION ALL + +-- Unpivot for ActualYTD +SELECT data.BenefitsID, data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.AccountID, data.FinancialReportingID, data.UnitTypeID, 1 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value +FROM ( + SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT gl.*, hist.ActualYTDValue01, hist.ActualYTDValue02, hist.ActualYTDValue03, hist.ActualYTDValue04, hist.ActualYTDValue05, hist.ActualYTDValue06, hist.ActualYTDValue07, hist.ActualYTDValue08, hist.ActualYTDValue09, hist.ActualYTDValue10, hist.ActualYTDValue11, hist.ActualYTDValue12 + FROM fp.FactBenefits gl (READUNCOMMITTED) + INNER JOIN fp.FactBenefitsHistory hist (READUNCOMMITTED) + ON gl.BenefitsID = hist.BenefitsID ) gl + UNPIVOT ( Value FOR FiscalMonth IN (ActualYTDValue01, ActualYTDValue02, ActualYTDValue03, ActualYTDValue04, ActualYTDValue05, ActualYTDValue06, ActualYTDValue07, ActualYTDValue08, ActualYTDValue09, ActualYTDValue10, ActualYTDValue11, ActualYTDValue12)) as f + INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ActualYTDValue', 'Month')) data + INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID + +UNION ALL + +-- Unpivot for CurrentYearBudget +SELECT data.BenefitsID, data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.AccountID, data.FinancialReportingID, data.UnitTypeID, 2 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value +FROM ( + SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT gl.*, hist.CurrentYearBudget01, hist.CurrentYearBudget02, hist.CurrentYearBudget03, hist.CurrentYearBudget04, hist.CurrentYearBudget05, hist.CurrentYearBudget06, hist.CurrentYearBudget07, hist.CurrentYearBudget08, hist.CurrentYearBudget09, hist.CurrentYearBudget10, hist.CurrentYearBudget11, hist.CurrentYearBudget12 + FROM fp.FactBenefits gl (READUNCOMMITTED) + INNER JOIN fp.FactBenefitsHistory hist (READUNCOMMITTED) + ON gl.BenefitsID = hist.BenefitsID ) gl + UNPIVOT ( Value FOR FiscalMonth IN (CurrentYearBudget01, CurrentYearBudget02, CurrentYearBudget03, CurrentYearBudget04, CurrentYearBudget05, CurrentYearBudget06, CurrentYearBudget07, CurrentYearBudget08, CurrentYearBudget09, CurrentYearBudget10, CurrentYearBudget11, CurrentYearBudget12)) as f + INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'CurrentYearBudget', 'Month')) data + INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFactBenefits_HistoryViewer +CREATE VIEW fp.viewFactBenefits_HistoryViewer +AS +SELECT + ov.BenefitsID, + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.DepartmentID, + ov.AccountID, + ov.FinancialReportingID, + ov.UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + ov.FiscalMonthID, + LockType, + ov.InitialValue AS OriginalValue, + v.Value, + mgrv.ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT gl.* + FROM fp.FactBenefits gl ) gl + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT gl.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactBenefits gl + INNER JOIN fp.FactBenefitsBudget bdgt ON gl.BenefitsID = bdgt.BenefitsID + WHERE bdgt.BudgetPhaseID = 2) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.DepartmentID = v.DepartmentID + AND ov.AccountID = v.AccountID + AND ov.BudgetConfigID = v.BudgetConfigID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN ( + -- Unpivot for ManagerValue + SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value AS ManagerValue + FROM ( + SELECT gl.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactBenefits gl + INNER JOIN fp.FactBenefitsBudget bdgt ON gl.BenefitsID = bdgt.BenefitsID + WHERE bdgt.BudgetPhaseID = 3) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON ov.DepartmentID = mgrv.DepartmentID + AND ov.AccountID = mgrv.AccountID + AND ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.UnitTypeID = mgrv.UnitTypeID + AND ov.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFactBenefits_Pivoted +CREATE VIEW [fp].[viewFactBenefits_Pivoted] +AS +SELECT + fb.BenefitsID, + fb.BudgetConfigID, + fb.EntityGroupConfigID, + fb.EntityID, + fb.DepartmentID, + fb.AccountID, + fb.FinancialReportingID, + fb.UnitTypeID, + + CASE WHEN fb.FlexMethodID = 1 THEN 1 ELSE 0 END AS FlexByFTEs, + CASE WHEN fb.FlexMethodID = 2 THEN 1 ELSE 0 END AS FlexBySalaries, + + fbdgt.LockType as BudgetLockType, + fbdgt.LockFlag as BudgetLockFlag, + fproj.LockType as ProjectionLockType, + fproj.LockFlag as ProjectionLockFlag, + + dbdgt.LockType as FinalBudgetLockType, + dbdgt.LockFlag as FinalBudgetLockFlag, + dproj.LockType as FinalProjectionLockType, + dproj.LockFlag as FinalProjectionLockFlag, + + fbdgt.AdjustedValueTotal, + + dbdgt.AdjustedValueTotal as ManagerAdjustedValueTotal, + dproj.AdjustedValueTotal as ManagerAdjustedProjectionValueTotal, + + dproj.AdjustedValueTotal as AdjustedProjectionValueTotal, + + hist.ActualYTDValueTotal, + hist.CurrentYearBudgetTotal, + hist.PriorYearActualValueTotal, + + fb.InitialBudgetTotal, + fb.InitialProjectionTotal, + + fbdgt.AdjustedValue01, fbdgt.AdjustedValue02, fbdgt.AdjustedValue03, fbdgt.AdjustedValue04, fbdgt.AdjustedValue05, fbdgt.AdjustedValue06, fbdgt.AdjustedValue07, fbdgt.AdjustedValue08, fbdgt.AdjustedValue09, fbdgt.AdjustedValue10, fbdgt.AdjustedValue11, fbdgt.AdjustedValue12, + dbdgt.AdjustedValue01 AS ManagerAdjustedValue01, dbdgt.AdjustedValue02 AS ManagerAdjustedValue02, dbdgt.AdjustedValue03 AS ManagerAdjustedValue03, dbdgt.AdjustedValue04 AS ManagerAdjustedValue04, dbdgt.AdjustedValue05 AS ManagerAdjustedValue05, dbdgt.AdjustedValue06 AS ManagerAdjustedValue06, dbdgt.AdjustedValue07 AS ManagerAdjustedValue07, dbdgt.AdjustedValue08 AS ManagerAdjustedValue08, dbdgt.AdjustedValue09 AS ManagerAdjustedValue09, dbdgt.AdjustedValue10 AS ManagerAdjustedValue10, dbdgt.AdjustedValue11 AS ManagerAdjustedValue11, dbdgt.AdjustedValue12 AS ManagerAdjustedValue12, + dproj.AdjustedValue01 AS AdjustedProjectionValue01, dproj.AdjustedValue02 AS AdjustedProjectionValue02, dproj.AdjustedValue03 AS AdjustedProjectionValue03, dproj.AdjustedValue04 AS AdjustedProjectionValue04, dproj.AdjustedValue05 AS AdjustedProjectionValue05, dproj.AdjustedValue06 AS AdjustedProjectionValue06, dproj.AdjustedValue07 AS AdjustedProjectionValue07, dproj.AdjustedValue08 AS AdjustedProjectionValue08, dproj.AdjustedValue09 AS AdjustedProjectionValue09, dproj.AdjustedValue10 AS AdjustedProjectionValue10, dproj.AdjustedValue11 AS AdjustedProjectionValue11, dproj.AdjustedValue12 AS AdjustedProjectionValue12, + fb.InitialBudget01, fb.InitialBudget02, fb.InitialBudget03, fb.InitialBudget04, fb.InitialBudget05, fb.InitialBudget06, fb.InitialBudget07, fb.InitialBudget08, fb.InitialBudget09, fb.InitialBudget10, fb.InitialBudget11, fb.InitialBudget12, + hist.PriorYearActualValue01, hist.PriorYearActualValue02, hist.PriorYearActualValue03, hist.PriorYearActualValue04, hist.PriorYearActualValue05, hist.PriorYearActualValue06, hist.PriorYearActualValue07, hist.PriorYearActualValue08, hist.PriorYearActualValue09, hist.PriorYearActualValue10, hist.PriorYearActualValue11, hist.PriorYearActualValue12, + hist.ActualYTDValue01, hist.ActualYTDValue02, hist.ActualYTDValue03, hist.ActualYTDValue04, hist.ActualYTDValue05, hist.ActualYTDValue06, hist.ActualYTDValue07, hist.ActualYTDValue08, hist.ActualYTDValue09, hist.ActualYTDValue10, hist.ActualYTDValue11, hist.ActualYTDValue12, + hist.CurrentYearBudget01, hist.CurrentYearBudget02, hist.CurrentYearBudget03, hist.CurrentYearBudget04, hist.CurrentYearBudget05, hist.CurrentYearBudget06, hist.CurrentYearBudget07, hist.CurrentYearBudget08, hist.CurrentYearBudget09, hist.CurrentYearBudget10, hist.CurrentYearBudget11, hist.CurrentYearBudget12 +FROM [fp].[FactBenefits] fb (READUNCOMMITTED) + INNER JOIN [fp].[FactBenefitsBudget] (READUNCOMMITTED) fbdgt ON fb.BenefitsID = fbdgt.BenefitsID AND fbdgt.BudgetPhaseID = 2 + INNER JOIN [fp].[FactBenefitsBudget] (READUNCOMMITTED) dbdgt ON fb.BenefitsID = dbdgt.BenefitsID AND dbdgt.BudgetPhaseID = 3 + INNER JOIN [fp].[FactBenefitsProjection] (READUNCOMMITTED) fproj ON fb.BenefitsID = fproj.BenefitsID AND fproj.BudgetPhaseID = 2 + INNER JOIN [fp].[FactBenefitsProjection] (READUNCOMMITTED) dproj ON fb.BenefitsID = dproj.BenefitsID AND dproj.BudgetPhaseID = 3 + INNER JOIN [fp].[FactBenefitsHistory] hist (READUNCOMMITTED) ON fb.BenefitsID = hist.BenefitsID +GO + + +--------------------------------------------- + +-- fp.viewFactBenefits_Unpivoted +CREATE VIEW fp.viewFactBenefits_Unpivoted +AS +SELECT + ov.BenefitsID, + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.DepartmentID, + ov.AccountID, + ov.FinancialReportingID, + ov.UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + ov.FiscalMonthID, + LockType, + ov.InitialValue as OriginalValue, + v.Value, + mgrv.ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT gl.* + FROM fp.FactBenefits gl ) gl + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT gl.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactBenefits gl + INNER JOIN fp.FactBenefitsBudget bdgt ON gl.BenefitsID = bdgt.BenefitsID + WHERE bdgt.BudgetPhaseID = 2) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.DepartmentID = v.DepartmentID + AND ov.AccountID = v.AccountID + AND ov.BudgetConfigID = v.BudgetConfigID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN ( + -- Unpivot for ManagerValue + SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value AS ManagerValue + FROM ( + SELECT gl.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactBenefits gl + INNER JOIN fp.FactBenefitsBudget bdgt ON gl.BenefitsID = bdgt.BenefitsID + WHERE bdgt.BudgetPhaseID = 3) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON ov.DepartmentID = mgrv.DepartmentID + AND ov.AccountID = mgrv.AccountID + AND ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.UnitTypeID = mgrv.UnitTypeID + AND ov.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID + + +UNION ALL + +SELECT + ov.BenefitsID, + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.DepartmentID, + ov.AccountID, + ov.FinancialReportingID, + ov.UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID - 1 as FiscalYearID, + ov.FiscalMonthID, + LockType, + ov.InitialValue as OriginalValue, + v.Value, + mgrv.ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT gl.* + FROM fp.FactBenefits gl ) gl + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT gl.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactBenefits gl + INNER JOIN fp.FactBenefitsProjection bdgt ON gl.BenefitsID = bdgt.BenefitsID + WHERE bdgt.BudgetPhaseID = 2) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.DepartmentID = v.DepartmentID + AND ov.AccountID = v.AccountID + AND ov.BudgetConfigID = v.BudgetConfigID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN ( + -- Unpivot for ManagerValue + SELECT BenefitsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value AS ManagerValue + FROM ( + SELECT gl.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactBenefits gl + INNER JOIN fp.FactBenefitsProjection bdgt ON gl.BenefitsID = bdgt.BenefitsID + WHERE bdgt.BudgetPhaseID = 3) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON ov.DepartmentID = mgrv.DepartmentID + AND ov.AccountID = mgrv.AccountID + AND ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.UnitTypeID = mgrv.UnitTypeID + AND ov.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFactChargeDollarsToStatisticsCrosswalkHistory_Unpivoted_source +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2021-11-17 MD JAZZ-27519 Initial +** 2 2022-09-01 JB JAZZ-32095 Remove Payor and PayorGroupID from joins. +** 3 2023-03-21 MY JAZZ-49993 Update reporting to support new data model +*************************************************************/ +CREATE VIEW [fp].[viewFactChargeDollarsToStatisticsCrosswalkHistory_Unpivoted_source] + AS + -- The report source does not use data at the lowest level, so we're going to roll them up here so there is less data to pivot later. Pivoting is slow + WITH chargevolume AS ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, + cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, 34 as UnitTypeID, + SUM(hist.PriorYearActualDollarValue01) AS PriorYearActualValue01, + SUM(hist.PriorYearActualDollarValue02) AS PriorYearActualValue02, + SUM(hist.PriorYearActualDollarValue03) AS PriorYearActualValue03, + SUM(hist.PriorYearActualDollarValue04) AS PriorYearActualValue04, + SUM(hist.PriorYearActualDollarValue05) AS PriorYearActualValue05, + SUM(hist.PriorYearActualDollarValue06) AS PriorYearActualValue06, + SUM(hist.PriorYearActualDollarValue07) AS PriorYearActualValue07, + SUM(hist.PriorYearActualDollarValue08) AS PriorYearActualValue08, + SUM(hist.PriorYearActualDollarValue09) AS PriorYearActualValue09, + SUM(hist.PriorYearActualDollarValue10) AS PriorYearActualValue10, + SUM(hist.PriorYearActualDollarValue11) AS PriorYearActualValue11, + SUM(hist.PriorYearActualDollarValue12) AS PriorYearActualValue12, + SUM(hist.ActualYTDDollarValue01) AS ActualYTDValue01, + SUM(hist.ActualYTDDollarValue02) AS ActualYTDValue02, + SUM(hist.ActualYTDDollarValue03) AS ActualYTDValue03, + SUM(hist.ActualYTDDollarValue04) AS ActualYTDValue04, + SUM(hist.ActualYTDDollarValue05) AS ActualYTDValue05, + SUM(hist.ActualYTDDollarValue06) AS ActualYTDValue06, + SUM(hist.ActualYTDDollarValue07) AS ActualYTDValue07, + SUM(hist.ActualYTDDollarValue08) AS ActualYTDValue08, + SUM(hist.ActualYTDDollarValue09) AS ActualYTDValue09, + SUM(hist.ActualYTDDollarValue10) AS ActualYTDValue10, + SUM(hist.ActualYTDDollarValue11) AS ActualYTDValue11, + SUM(hist.ActualYTDDollarValue12) AS ActualYTDValue12, + SUM(hist.CurrentYearBudgetDollar01) AS CurrentYearBudgetValue01, + SUM(hist.CurrentYearBudgetDollar02) AS CurrentYearBudgetValue02, + SUM(hist.CurrentYearBudgetDollar03) AS CurrentYearBudgetValue03, + SUM(hist.CurrentYearBudgetDollar04) AS CurrentYearBudgetValue04, + SUM(hist.CurrentYearBudgetDollar05) AS CurrentYearBudgetValue05, + SUM(hist.CurrentYearBudgetDollar06) AS CurrentYearBudgetValue06, + SUM(hist.CurrentYearBudgetDollar07) AS CurrentYearBudgetValue07, + SUM(hist.CurrentYearBudgetDollar08) AS CurrentYearBudgetValue08, + SUM(hist.CurrentYearBudgetDollar09) AS CurrentYearBudgetValue09, + SUM(hist.CurrentYearBudgetDollar10) AS CurrentYearBudgetValue10, + SUM(hist.CurrentYearBudgetDollar11) AS CurrentYearBudgetValue11, + SUM(hist.CurrentYearBudgetDollar12) AS CurrentYearBudgetValue12 + FROM fp.ChargeVolume cv + INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigID = cv.BudgetConfigID + INNER JOIN fp.ChargeVolumeHistory hist ON cv.ChargeVolumeID = hist.ChargeVolumeID + INNER JOIN [fp].[EntityGroupConfig] e ON e.BudgetConfigGUID = bc.BudgetConfigGUID AND e.EntityGroupConfigID = cv.EntityGroupConfigID + INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] cc ON cc.EntityGroupConfigID = e.EntityGroupConfigID + AND cc.DepartmentID = cv.DepartmentID + AND cc.PatientClassID = cv.PatientClassID + AND cc.ChargeCodeID = cv.ChargeCodeID + AND cc.EntityGroupConfigID = cv.EntityGroupConfigID + WHERE bc.IsActive = 1 + GROUP BY cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, + cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID + ) + SELECT + BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + PatientClassID, + UnitTypeID, + TimeClassID, + FiscalYearID, + FiscalMonthID, + Value + FROM ( + SELECT data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.ChargeCodeID, data.ServiceLineID, data.AgeCohortID, data.MedicalSurgicalID, data.PatientClassID, data.UnitTypeID, 1 as TimeClassID, bc.FiscalYearID - 2 as FiscalYearID, data.FiscalMonthID, data.Value + FROM ( + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, PatientClassID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT fcv.BudgetConfigID, fcv.EntityGroupConfigID, fcv.EntityID, fcv.DepartmentID, fcv.ServiceLineID, fcv.PatientClassID, fcv.AgeCohortID, fcv.MedicalSurgicalID, fcv.ChargeCodeID, fcv.UnitTypeID, + fcv.PriorYearActualValue01, fcv.PriorYearActualValue02, fcv.PriorYearActualValue03, fcv.PriorYearActualValue04, fcv.PriorYearActualValue05, fcv.PriorYearActualValue06, fcv.PriorYearActualValue07, fcv.PriorYearActualValue08, fcv.PriorYearActualValue09, fcv.PriorYearActualValue10, fcv.PriorYearActualValue11, fcv.PriorYearActualValue12 + FROM chargevolume fcv ) fcv + UNPIVOT ( Value FOR FiscalMonth IN (PriorYearActualValue01, PriorYearActualValue02, PriorYearActualValue03, PriorYearActualValue04, PriorYearActualValue05, PriorYearActualValue06, PriorYearActualValue07, PriorYearActualValue08, PriorYearActualValue09, PriorYearActualValue10, PriorYearActualValue11, PriorYearActualValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'PriorYearActualValue', 'Month')) data + INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID + + UNION ALL + + -- Unpivot for ActualYTD + SELECT data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.ChargeCodeID, data.ServiceLineID, data.AgeCohortID, data.MedicalSurgicalID, data.PatientClassID, data.UnitTypeID, 1 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value + FROM ( + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, PatientClassID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT fcv.BudgetConfigID, fcv.EntityGroupConfigID, fcv.EntityID, fcv.DepartmentID, fcv.ServiceLineID, fcv.PatientClassID, fcv.AgeCohortID, fcv.MedicalSurgicalID, fcv.ChargeCodeID, fcv.UnitTypeID, + fcv.ActualYTDValue01, fcv.ActualYTDValue02, fcv.ActualYTDValue03, fcv.ActualYTDValue04, fcv.ActualYTDValue05, fcv.ActualYTDValue06, fcv.ActualYTDValue07, fcv.ActualYTDValue08, fcv.ActualYTDValue09, fcv.ActualYTDValue10, fcv.ActualYTDValue11, fcv.ActualYTDValue12 + FROM chargevolume fcv ) fcv + UNPIVOT ( Value FOR FiscalMonth IN (ActualYTDValue01, ActualYTDValue02, ActualYTDValue03, ActualYTDValue04, ActualYTDValue05, ActualYTDValue06, ActualYTDValue07, ActualYTDValue08, ActualYTDValue09, ActualYTDValue10, ActualYTDValue11, ActualYTDValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ActualYTDValue', 'Month')) data + INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID + + UNION ALL + + -- Unpivot for CurrentYearBudgetValue + SELECT data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.ChargeCodeID, data.ServiceLineID, data.AgeCohortID, data.MedicalSurgicalID, data.PatientClassID, data.UnitTypeID, 2 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value + FROM ( + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, PatientClassID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT fcv.BudgetConfigID, fcv.EntityGroupConfigID, fcv.EntityID, fcv.DepartmentID, fcv.ServiceLineID, fcv.PatientClassID, fcv.AgeCohortID, fcv.MedicalSurgicalID, fcv.ChargeCodeID, fcv.UnitTypeID, + fcv.CurrentYearBudgetValue01, fcv.CurrentYearBudgetValue02, fcv.CurrentYearBudgetValue03, fcv.CurrentYearBudgetValue04, fcv.CurrentYearBudgetValue05, fcv.CurrentYearBudgetValue06, fcv.CurrentYearBudgetValue07, fcv.CurrentYearBudgetValue08, fcv.CurrentYearBudgetValue09, fcv.CurrentYearBudgetValue10, fcv.CurrentYearBudgetValue11, fcv.CurrentYearBudgetValue12 + FROM chargevolume fcv ) fcv + UNPIVOT ( Value FOR FiscalMonth IN (CurrentYearBudgetValue01, CurrentYearBudgetValue02, CurrentYearBudgetValue03, CurrentYearBudgetValue04, CurrentYearBudgetValue05, CurrentYearBudgetValue06, CurrentYearBudgetValue07, CurrentYearBudgetValue08, CurrentYearBudgetValue09, CurrentYearBudgetValue10, CurrentYearBudgetValue11, CurrentYearBudgetValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'CurrentYearBudgetValue', 'Month')) data + INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID + + ) data +GO + + +--------------------------------------------- + +-- fp.viewFactChargeDollarsToStatisticsCrosswalk_Unpivoted_source +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2020-05-08 LR JAZZ-20 Initial +** 2 2020-13-08 MY JAZZ-4098 Performance tuning +** 3 2022-09-01 JB JAZZ-32095 Remove Payor and PayorGroupID from joins. +** 4 2023-03-21 MY JAZZ-49993 Update reporting to support new data model +*************************************************************/ +CREATE VIEW [fp].[viewFactChargeDollarsToStatisticsCrosswalk_Unpivoted_source] +AS + WITH chargevolume AS ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, + cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, 34 as UnitTypeID, + SUM(cv.InitialBudgetDollars01) AS InitialBudget01, + SUM(cv.InitialBudgetDollars02) AS InitialBudget02, + SUM(cv.InitialBudgetDollars03) AS InitialBudget03, + SUM(cv.InitialBudgetDollars04) AS InitialBudget04, + SUM(cv.InitialBudgetDollars05) AS InitialBudget05, + SUM(cv.InitialBudgetDollars06) AS InitialBudget06, + SUM(cv.InitialBudgetDollars07) AS InitialBudget07, + SUM(cv.InitialBudgetDollars08) AS InitialBudget08, + SUM(cv.InitialBudgetDollars09) AS InitialBudget09, + SUM(cv.InitialBudgetDollars10) AS InitialBudget10, + SUM(cv.InitialBudgetDollars11) AS InitialBudget11, + SUM(cv.InitialBudgetDollars12) AS InitialBudget12, + SUM(cv.InitialProjectionDollars01) AS InitialProjection01, + SUM(cv.InitialProjectionDollars02) AS InitialProjection02, + SUM(cv.InitialProjectionDollars03) AS InitialProjection03, + SUM(cv.InitialProjectionDollars04) AS InitialProjection04, + SUM(cv.InitialProjectionDollars05) AS InitialProjection05, + SUM(cv.InitialProjectionDollars06) AS InitialProjection06, + SUM(cv.InitialProjectionDollars07) AS InitialProjection07, + SUM(cv.InitialProjectionDollars08) AS InitialProjection08, + SUM(cv.InitialProjectionDollars09) AS InitialProjection09, + SUM(cv.InitialProjectionDollars10) AS InitialProjection10, + SUM(cv.InitialProjectionDollars11) AS InitialProjection11, + SUM(cv.InitialProjectionDollars12) AS InitialProjection12, + SUM(cv.TargetDollarsAdjusted01) AS TargetValue01, + SUM(cv.TargetDollarsAdjusted02) AS TargetValue02, + SUM(cv.TargetDollarsAdjusted03) AS TargetValue03, + SUM(cv.TargetDollarsAdjusted04) AS TargetValue04, + SUM(cv.TargetDollarsAdjusted05) AS TargetValue05, + SUM(cv.TargetDollarsAdjusted06) AS TargetValue06, + SUM(cv.TargetDollarsAdjusted07) AS TargetValue07, + SUM(cv.TargetDollarsAdjusted08) AS TargetValue08, + SUM(cv.TargetDollarsAdjusted09) AS TargetValue09, + SUM(cv.TargetDollarsAdjusted10) AS TargetValue10, + SUM(cv.TargetDollarsAdjusted11) AS TargetValue11, + SUM(cv.TargetDollarsAdjusted12) AS TargetValue12, + SUM(cv.BudgetDollarsAdjusted01) AS ManagerValue01, + SUM(cv.BudgetDollarsAdjusted02) AS ManagerValue02, + SUM(cv.BudgetDollarsAdjusted03) AS ManagerValue03, + SUM(cv.BudgetDollarsAdjusted04) AS ManagerValue04, + SUM(cv.BudgetDollarsAdjusted05) AS ManagerValue05, + SUM(cv.BudgetDollarsAdjusted06) AS ManagerValue06, + SUM(cv.BudgetDollarsAdjusted07) AS ManagerValue07, + SUM(cv.BudgetDollarsAdjusted08) AS ManagerValue08, + SUM(cv.BudgetDollarsAdjusted09) AS ManagerValue09, + SUM(cv.BudgetDollarsAdjusted10) AS ManagerValue10, + SUM(cv.BudgetDollarsAdjusted11) AS ManagerValue11, + SUM(cv.BudgetDollarsAdjusted12) AS ManagerValue12, + SUM(cv.ProjectionDollarsAdjusted01) AS ProjectedValue01, + SUM(cv.ProjectionDollarsAdjusted02) AS ProjectedValue02, + SUM(cv.ProjectionDollarsAdjusted03) AS ProjectedValue03, + SUM(cv.ProjectionDollarsAdjusted04) AS ProjectedValue04, + SUM(cv.ProjectionDollarsAdjusted05) AS ProjectedValue05, + SUM(cv.ProjectionDollarsAdjusted06) AS ProjectedValue06, + SUM(cv.ProjectionDollarsAdjusted07) AS ProjectedValue07, + SUM(cv.ProjectionDollarsAdjusted08) AS ProjectedValue08, + SUM(cv.ProjectionDollarsAdjusted09) AS ProjectedValue09, + SUM(cv.ProjectionDollarsAdjusted10) AS ProjectedValue10, + SUM(cv.ProjectionDollarsAdjusted11) AS ProjectedValue11, + SUM(cv.ProjectionDollarsAdjusted12) AS ProjectedValue12 + FROM fp.ChargeVolume cv + INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigID = cv.BudgetConfigID + INNER JOIN [fp].[EntityGroupConfig] e ON e.BudgetConfigGUID = bc.BudgetConfigGUID AND e.EntityGroupConfigID = cv.EntityGroupConfigID + INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] cc ON cc.EntityGroupConfigID = e.EntityGroupConfigID + AND cc.DepartmentID = cv.DepartmentID + AND cc.PatientClassID = cv.PatientClassID + AND cc.ChargeCodeID = cv.ChargeCodeID + WHERE bc.IsActive = 1 + AND cv.UnitTypeID = 145 + GROUP BY cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, + cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID + ) + SELECT + BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + PatientClassID, + UnitTypeID, + TimeClassID, + FiscalMonthID, + FiscalYearID, + OriginalValue, + Value, + ManagerValue + FROM ( + SELECT + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.DepartmentID, + ov.ChargeCodeID, + ov.ServiceLineID, + ov.AgeCohortID, + ov.MedicalSurgicalID, + ov.PatientClassID, + ov.UnitTypeID, + 2 as TimeClassID, + ov.FiscalMonthID, + bc.FiscalYearID, + ov.InitialValue as OriginalValue, + v.Value, + mgr.Value as ManagerValue + FROM ( + -- Unpivot for OriginalValue + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, ChargeCodeID, DepartmentID, PatientClassID,ServiceLineID, AgeCohortID, MedicalSurgicalID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, + cv.InitialBudget01, cv.InitialBudget02, cv.InitialBudget03, cv.InitialBudget04, cv.InitialBudget05, cv.InitialBudget06, cv.InitialBudget07, cv.InitialBudget08, cv.InitialBudget09, cv.InitialBudget10, cv.InitialBudget11, cv.InitialBudget12 + FROM chargevolume cv + ) cv + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov + INNER JOIN ( + -- Unpivot for Value + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, ChargeCodeID, DepartmentID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, + cv.TargetValue01, cv.TargetValue02, cv.TargetValue03, cv.TargetValue04, cv.TargetValue05, cv.TargetValue06, cv.TargetValue07, cv.TargetValue08, cv.TargetValue09, cv.TargetValue10, cv.TargetValue11, cv.TargetValue12 + FROM chargevolume cv + ) cv + UNPIVOT ( Value FOR FiscalMonth IN (TargetValue01, TargetValue02, TargetValue03, TargetValue04, TargetValue05, TargetValue06, TargetValue07, TargetValue08, TargetValue09, TargetValue10, TargetValue11, TargetValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'TargetValue', 'Month')) v + ON ov.BudgetConfigID = v.BudgetConfigID + AND ov.EntityGroupConfigID = v.EntityGroupConfigID + AND ov.EntityID = v.EntityID + AND ov.DepartmentID = v.DepartmentID + AND ov.ChargeCodeID = v.ChargeCodeID + AND ov.ServiceLineID = v.ServiceLineID + AND ov.AgeCohortID = v.AgeCohortID + AND ov.MedicalSurgicalID = v.MedicalSurgicalID + AND ov.PatientClassID = v.PatientClassID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID + INNER JOIN ( + -- Unpivot for ManagerValue + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, ChargeCodeID, DepartmentID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, + cv.ManagerValue01, cv.ManagerValue02, cv.ManagerValue03, cv.ManagerValue04, cv.ManagerValue05, cv.ManagerValue06, cv.ManagerValue07, cv.ManagerValue08, cv.ManagerValue09, cv.ManagerValue10, cv.ManagerValue11, cv.ManagerValue12 + FROM chargevolume cv + ) cv + UNPIVOT ( Value FOR FiscalMonth IN (ManagerValue01, ManagerValue02, ManagerValue03, ManagerValue04, ManagerValue05, ManagerValue06, ManagerValue07, ManagerValue08, ManagerValue09, ManagerValue10, ManagerValue11, ManagerValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ManagerValue', 'Month')) mgr + ON ov.BudgetConfigID = mgr.BudgetConfigID + AND ov.EntityGroupConfigID = mgr.EntityGroupConfigID + AND ov.EntityID = mgr.EntityID + AND ov.DepartmentID = mgr.DepartmentID + AND ov.ChargeCodeID = mgr.ChargeCodeID + AND ov.ServiceLineID = mgr.ServiceLineID + AND ov.AgeCohortID = mgr.AgeCohortID + AND ov.MedicalSurgicalID = mgr.MedicalSurgicalID + AND ov.PatientClassID = mgr.PatientClassID + AND ov.UnitTypeID = mgr.UnitTypeID + AND ov.FiscalMonthID = mgr.FiscalMonthID + INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID + + + UNION ALL + + SELECT + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.DepartmentID, + ov.ChargeCodeID, + ov.ServiceLineID, + ov.AgeCohortID, + ov.MedicalSurgicalID, + ov.PatientClassID, + ov.UnitTypeID, + 12 as TimeClassID, + ov.FiscalMonthID, + bc.FiscalYearID - 1, + ov.InitialValue as OriginalValue, + v.Value, + v.Value as ManagerValue -- Manager value is not different in CV for Projection + FROM ( + -- Unpivot for OriginalValue + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, ChargeCodeID, DepartmentID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, + cv.InitialProjection01,cv.InitialProjection02, cv.InitialProjection03, cv.InitialProjection04, cv.InitialProjection05, cv.InitialProjection06, cv.InitialProjection07, cv.InitialProjection08, cv.InitialProjection09, cv.InitialProjection10, cv.InitialProjection11, cv.InitialProjection12 + FROM chargevolume cv + ) cv + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov + INNER JOIN ( + -- Unpivot for Value + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, ChargeCodeID, DepartmentID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, + cv.ProjectedValue01, cv.ProjectedValue02, cv.ProjectedValue03, cv.ProjectedValue04, cv.ProjectedValue05, cv.ProjectedValue06, cv.ProjectedValue07, cv.ProjectedValue08, cv.ProjectedValue09, cv.ProjectedValue10, cv.ProjectedValue11, cv.ProjectedValue12 + FROM chargevolume cv + ) cv + UNPIVOT ( Value FOR FiscalMonth IN (ProjectedValue01, ProjectedValue02, ProjectedValue03, ProjectedValue04, ProjectedValue05, ProjectedValue06, ProjectedValue07, ProjectedValue08, ProjectedValue09, ProjectedValue10, ProjectedValue11, ProjectedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectedValue', 'Month')) v + ON ov.BudgetConfigID = v.BudgetConfigID + AND ov.EntityGroupConfigID = v.EntityGroupConfigID + AND ov.EntityID = v.EntityID + AND ov.DepartmentID = v.DepartmentID + AND ov.ChargeCodeID = v.ChargeCodeID + AND ov.ServiceLineID = v.ServiceLineID + AND ov.AgeCohortID = v.AgeCohortID + AND ov.MedicalSurgicalID = v.MedicalSurgicalID + AND ov.PatientClassID = v.PatientClassID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID + INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID + ) cvData +GO + + +--------------------------------------------- + +-- fp.viewFactChargeToStatisticsCrosswalkHistory_Unpivoted +/************************************************************** + ** CID Date Author WI Description + ** 1 2022-09-01 JB JAZZ-32095 Remove Payor and PayorGroupID from joins. +*************************************************************/ + +CREATE VIEW fp.viewFactChargeToStatisticsCrosswalkHistory_Unpivoted + AS +SELECT ChargeVolumeID, + BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + PatientClassID, + UnitTypeID, + TimeClassID, + FiscalYearID, + FiscalMonthID, + AccountID, + RVUWeight, + Value FROM fp.FactReportChargeToStatisticsCrosswalkHistory +GO + + +--------------------------------------------- + +-- fp.viewFactChargeToStatisticsCrosswalkHistory_Unpivoted_source +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2020-05-08 LR JAZZ-20 Initial +** 2 2020-13-08 MY JAZZ-4098 Performance tuning +** 3 2022-09-22 JB JAZZ-32095 Remove Payor and PayorGroupID +** 4 2023-03-21 MY JAZZ-49993 Update reporting to support new data model +*************************************************************/ +CREATE VIEW fp.viewFactChargeToStatisticsCrosswalkHistory_Unpivoted_source + AS + -- The report source does not use data at the lowest level, so we're going to roll them up here so there is less data to pivot later. Pivoting is slow + WITH chargevolume AS ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, + cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, + SUM(hist.PriorYearActualValue01) AS PriorYearActualValue01, + SUM(hist.PriorYearActualValue02) AS PriorYearActualValue02, + SUM(hist.PriorYearActualValue03) AS PriorYearActualValue03, + SUM(hist.PriorYearActualValue04) AS PriorYearActualValue04, + SUM(hist.PriorYearActualValue05) AS PriorYearActualValue05, + SUM(hist.PriorYearActualValue06) AS PriorYearActualValue06, + SUM(hist.PriorYearActualValue07) AS PriorYearActualValue07, + SUM(hist.PriorYearActualValue08) AS PriorYearActualValue08, + SUM(hist.PriorYearActualValue09) AS PriorYearActualValue09, + SUM(hist.PriorYearActualValue10) AS PriorYearActualValue10, + SUM(hist.PriorYearActualValue11) AS PriorYearActualValue11, + SUM(hist.PriorYearActualValue12) AS PriorYearActualValue12, + SUM(hist.ActualYTDValue01) AS ActualYTDValue01, + SUM(hist.ActualYTDValue02) AS ActualYTDValue02, + SUM(hist.ActualYTDValue03) AS ActualYTDValue03, + SUM(hist.ActualYTDValue04) AS ActualYTDValue04, + SUM(hist.ActualYTDValue05) AS ActualYTDValue05, + SUM(hist.ActualYTDValue06) AS ActualYTDValue06, + SUM(hist.ActualYTDValue07) AS ActualYTDValue07, + SUM(hist.ActualYTDValue08) AS ActualYTDValue08, + SUM(hist.ActualYTDValue09) AS ActualYTDValue09, + SUM(hist.ActualYTDValue10) AS ActualYTDValue10, + SUM(hist.ActualYTDValue11) AS ActualYTDValue11, + SUM(hist.ActualYTDValue12) AS ActualYTDValue12, + SUM(hist.CurrentYearBudget01) AS CurrentYearBudgetValue01, + SUM(hist.CurrentYearBudget02) AS CurrentYearBudgetValue02, + SUM(hist.CurrentYearBudget03) AS CurrentYearBudgetValue03, + SUM(hist.CurrentYearBudget04) AS CurrentYearBudgetValue04, + SUM(hist.CurrentYearBudget05) AS CurrentYearBudgetValue05, + SUM(hist.CurrentYearBudget06) AS CurrentYearBudgetValue06, + SUM(hist.CurrentYearBudget07) AS CurrentYearBudgetValue07, + SUM(hist.CurrentYearBudget08) AS CurrentYearBudgetValue08, + SUM(hist.CurrentYearBudget09) AS CurrentYearBudgetValue09, + SUM(hist.CurrentYearBudget10) AS CurrentYearBudgetValue10, + SUM(hist.CurrentYearBudget11) AS CurrentYearBudgetValue11, + SUM(hist.CurrentYearBudget12) AS CurrentYearBudgetValue12 + FROM fp.ChargeVolume cv + INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigID = cv.BudgetConfigID + INNER JOIN fp.ChargeVolumeHistory hist ON cv.ChargeVolumeID = hist.ChargeVolumeID + INNER JOIN [fp].[EntityGroupConfig] e ON e.BudgetConfigGUID = bc.BudgetConfigGUID AND e.EntityGroupConfigID = cv.EntityGroupConfigID + INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] cc ON cc.EntityGroupConfigID = e.EntityGroupConfigID + AND cc.DepartmentID = cv.DepartmentID + AND cc.PatientClassID = cv.PatientClassID + AND cc.ChargeCodeID = cv.ChargeCodeID + AND cc.EntityGroupConfigID = cv.EntityGroupConfigID + WHERE bc.IsActive = 1 + GROUP BY cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, + cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID + ) + SELECT + BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + PatientClassID, + UnitTypeID, + TimeClassID, + FiscalYearID, + FiscalMonthID, + Value + FROM ( + SELECT data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.ChargeCodeID, data.ServiceLineID, data.AgeCohortID, data.MedicalSurgicalID, data.PatientClassID, data.UnitTypeID, 1 as TimeClassID, bc.FiscalYearID - 2 as FiscalYearID, data.FiscalMonthID, data.Value + FROM ( + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, PatientClassID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT fcv.BudgetConfigID, fcv.EntityGroupConfigID, fcv.EntityID, fcv.DepartmentID, fcv.ServiceLineID, fcv.PatientClassID, fcv.AgeCohortID, fcv.MedicalSurgicalID, fcv.ChargeCodeID, fcv.UnitTypeID, + fcv.PriorYearActualValue01, fcv.PriorYearActualValue02, fcv.PriorYearActualValue03, fcv.PriorYearActualValue04, fcv.PriorYearActualValue05, fcv.PriorYearActualValue06, fcv.PriorYearActualValue07, fcv.PriorYearActualValue08, fcv.PriorYearActualValue09, fcv.PriorYearActualValue10, fcv.PriorYearActualValue11, fcv.PriorYearActualValue12 + FROM chargevolume fcv ) fcv + UNPIVOT ( Value FOR FiscalMonth IN (PriorYearActualValue01, PriorYearActualValue02, PriorYearActualValue03, PriorYearActualValue04, PriorYearActualValue05, PriorYearActualValue06, PriorYearActualValue07, PriorYearActualValue08, PriorYearActualValue09, PriorYearActualValue10, PriorYearActualValue11, PriorYearActualValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'PriorYearActualValue', 'Month')) data + INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID + + UNION ALL + + -- Unpivot for ActualYTD + SELECT data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.ChargeCodeID, data.ServiceLineID, data.AgeCohortID, data.MedicalSurgicalID, data.PatientClassID, data.UnitTypeID, 1 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value + FROM ( + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, PatientClassID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT fcv.BudgetConfigID, fcv.EntityGroupConfigID, fcv.EntityID, fcv.DepartmentID, fcv.ServiceLineID, fcv.PatientClassID, fcv.AgeCohortID, fcv.MedicalSurgicalID, fcv.ChargeCodeID, fcv.UnitTypeID, + fcv.ActualYTDValue01, fcv.ActualYTDValue02, fcv.ActualYTDValue03, fcv.ActualYTDValue04, fcv.ActualYTDValue05, fcv.ActualYTDValue06, fcv.ActualYTDValue07, fcv.ActualYTDValue08, fcv.ActualYTDValue09, fcv.ActualYTDValue10, fcv.ActualYTDValue11, fcv.ActualYTDValue12 + FROM chargevolume fcv ) fcv + UNPIVOT ( Value FOR FiscalMonth IN (ActualYTDValue01, ActualYTDValue02, ActualYTDValue03, ActualYTDValue04, ActualYTDValue05, ActualYTDValue06, ActualYTDValue07, ActualYTDValue08, ActualYTDValue09, ActualYTDValue10, ActualYTDValue11, ActualYTDValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ActualYTDValue', 'Month')) data + INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID + + UNION ALL + + -- Unpivot for CurrentYearBudgetValue + SELECT data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.ChargeCodeID, data.ServiceLineID, data.AgeCohortID, data.MedicalSurgicalID, data.PatientClassID, data.UnitTypeID, 2 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value + FROM ( + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, PatientClassID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT fcv.BudgetConfigID, fcv.EntityGroupConfigID, fcv.EntityID, fcv.DepartmentID, fcv.ServiceLineID, fcv.PatientClassID, fcv.AgeCohortID, fcv.MedicalSurgicalID, fcv.ChargeCodeID, fcv.UnitTypeID, + fcv.CurrentYearBudgetValue01, fcv.CurrentYearBudgetValue02, fcv.CurrentYearBudgetValue03, fcv.CurrentYearBudgetValue04, fcv.CurrentYearBudgetValue05, fcv.CurrentYearBudgetValue06, fcv.CurrentYearBudgetValue07, fcv.CurrentYearBudgetValue08, fcv.CurrentYearBudgetValue09, fcv.CurrentYearBudgetValue10, fcv.CurrentYearBudgetValue11, fcv.CurrentYearBudgetValue12 + FROM chargevolume fcv ) fcv + UNPIVOT ( Value FOR FiscalMonth IN (CurrentYearBudgetValue01, CurrentYearBudgetValue02, CurrentYearBudgetValue03, CurrentYearBudgetValue04, CurrentYearBudgetValue05, CurrentYearBudgetValue06, CurrentYearBudgetValue07, CurrentYearBudgetValue08, CurrentYearBudgetValue09, CurrentYearBudgetValue10, CurrentYearBudgetValue11, CurrentYearBudgetValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'CurrentYearBudgetValue', 'Month')) data + INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID + + ) data +GO + + +--------------------------------------------- + +-- fp.viewFactChargeToStatisticsCrosswalk_Unpivoted_source +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2020-05-08 LR JAZZ-20 Initial +** 2 2020-13-08 MY JAZZ-4098 Performance tuning +** 3 2022-09-01 JB JAZZ-32095 Remove Payor and PayorGroupID from joins. +** 4 2023-03-21 MY JAZZ-49993 Update reporting to support new data model +*************************************************************/ +CREATE VIEW fp.viewFactChargeToStatisticsCrosswalk_Unpivoted_source +AS + WITH chargevolume AS ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, + cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, + SUM(InitialBudget01) AS InitialBudget01, + SUM(InitialBudget02) AS InitialBudget02, + SUM(InitialBudget03) AS InitialBudget03, + SUM(InitialBudget04) AS InitialBudget04, + SUM(InitialBudget05) AS InitialBudget05, + SUM(InitialBudget06) AS InitialBudget06, + SUM(InitialBudget07) AS InitialBudget07, + SUM(InitialBudget08) AS InitialBudget08, + SUM(InitialBudget09) AS InitialBudget09, + SUM(InitialBudget10) AS InitialBudget10, + SUM(InitialBudget11) AS InitialBudget11, + SUM(InitialBudget12) AS InitialBudget12, + SUM(InitialProjection01) AS InitialProjection01, + SUM(InitialProjection02) AS InitialProjection02, + SUM(InitialProjection03) AS InitialProjection03, + SUM(InitialProjection04) AS InitialProjection04, + SUM(InitialProjection05) AS InitialProjection05, + SUM(InitialProjection06) AS InitialProjection06, + SUM(InitialProjection07) AS InitialProjection07, + SUM(InitialProjection08) AS InitialProjection08, + SUM(InitialProjection09) AS InitialProjection09, + SUM(InitialProjection10) AS InitialProjection10, + SUM(InitialProjection11) AS InitialProjection11, + SUM(InitialProjection12) AS InitialProjection12, + SUM(TargetAdjusted01) AS TargetValue01, + SUM(TargetAdjusted02) AS TargetValue02, + SUM(TargetAdjusted03) AS TargetValue03, + SUM(TargetAdjusted04) AS TargetValue04, + SUM(TargetAdjusted05) AS TargetValue05, + SUM(TargetAdjusted06) AS TargetValue06, + SUM(TargetAdjusted07) AS TargetValue07, + SUM(TargetAdjusted08) AS TargetValue08, + SUM(TargetAdjusted09) AS TargetValue09, + SUM(TargetAdjusted10) AS TargetValue10, + SUM(TargetAdjusted11) AS TargetValue11, + SUM(TargetAdjusted12) AS TargetValue12, + SUM(BudgetAdjusted01) AS ManagerValue01, + SUM(BudgetAdjusted02) AS ManagerValue02, + SUM(BudgetAdjusted03) AS ManagerValue03, + SUM(BudgetAdjusted04) AS ManagerValue04, + SUM(BudgetAdjusted05) AS ManagerValue05, + SUM(BudgetAdjusted06) AS ManagerValue06, + SUM(BudgetAdjusted07) AS ManagerValue07, + SUM(BudgetAdjusted08) AS ManagerValue08, + SUM(BudgetAdjusted09) AS ManagerValue09, + SUM(BudgetAdjusted10) AS ManagerValue10, + SUM(BudgetAdjusted11) AS ManagerValue11, + SUM(BudgetAdjusted12) AS ManagerValue12, + SUM(ProjectionAdjusted01) AS ProjectedValue01, + SUM(ProjectionAdjusted02) AS ProjectedValue02, + SUM(ProjectionAdjusted03) AS ProjectedValue03, + SUM(ProjectionAdjusted04) AS ProjectedValue04, + SUM(ProjectionAdjusted05) AS ProjectedValue05, + SUM(ProjectionAdjusted06) AS ProjectedValue06, + SUM(ProjectionAdjusted07) AS ProjectedValue07, + SUM(ProjectionAdjusted08) AS ProjectedValue08, + SUM(ProjectionAdjusted09) AS ProjectedValue09, + SUM(ProjectionAdjusted10) AS ProjectedValue10, + SUM(ProjectionAdjusted11) AS ProjectedValue11, + SUM(ProjectionAdjusted12) AS ProjectedValue12 + FROM fp.ChargeVolume cv + INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigID = cv.BudgetConfigID + INNER JOIN [fp].[EntityGroupConfig] e ON e.BudgetConfigGUID = bc.BudgetConfigGUID AND e.EntityGroupConfigID = cv.EntityGroupConfigID + INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] cc ON cc.EntityGroupConfigID = e.EntityGroupConfigID + AND cc.DepartmentID = cv.DepartmentID + AND cc.PatientClassID = cv.PatientClassID + AND cc.ChargeCodeID = cv.ChargeCodeID + WHERE bc.IsActive = 1 + GROUP BY cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, + cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID + ) + SELECT + BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + PatientClassID, + UnitTypeID, + TimeClassID, + FiscalMonthID, + FiscalYearID, + OriginalValue, + Value, + ManagerValue + FROM ( + SELECT + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.DepartmentID, + ov.ChargeCodeID, + ov.ServiceLineID, + ov.AgeCohortID, + ov.MedicalSurgicalID, + ov.PatientClassID, + ov.UnitTypeID, + 2 as TimeClassID, + ov.FiscalMonthID, + bc.FiscalYearID, + ov.InitialValue as OriginalValue, + v.Value, + mgr.Value as ManagerValue + FROM ( + -- Unpivot for OriginalValue + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, ChargeCodeID, DepartmentID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, + cv.InitialBudget01, cv.InitialBudget02, cv.InitialBudget03, cv.InitialBudget04, cv.InitialBudget05, cv.InitialBudget06, cv.InitialBudget07, cv.InitialBudget08, cv.InitialBudget09, cv.InitialBudget10, cv.InitialBudget11, cv.InitialBudget12 + FROM chargevolume cv + ) cv + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov + INNER JOIN ( + -- Unpivot for Value + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, ChargeCodeID, DepartmentID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, + cv.TargetValue01, cv.TargetValue02, cv.TargetValue03, cv.TargetValue04, cv.TargetValue05, cv.TargetValue06, cv.TargetValue07, cv.TargetValue08, cv.TargetValue09, cv.TargetValue10, cv.TargetValue11, cv.TargetValue12 + FROM chargevolume cv + ) cv + UNPIVOT ( Value FOR FiscalMonth IN (TargetValue01, TargetValue02, TargetValue03, TargetValue04, TargetValue05, TargetValue06, TargetValue07, TargetValue08, TargetValue09, TargetValue10, TargetValue11, TargetValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'TargetValue', 'Month')) v + ON ov.BudgetConfigID = v.BudgetConfigID + AND ov.EntityGroupConfigID = v.EntityGroupConfigID + AND ov.EntityID = v.EntityID + AND ov.DepartmentID = v.DepartmentID + AND ov.ChargeCodeID = v.ChargeCodeID + AND ov.ServiceLineID = v.ServiceLineID + AND ov.AgeCohortID = v.AgeCohortID + AND ov.MedicalSurgicalID = v.MedicalSurgicalID + AND ov.PatientClassID = v.PatientClassID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID + INNER JOIN ( + -- Unpivot for ManagerValue + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, ChargeCodeID, DepartmentID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, + cv.ManagerValue01, cv.ManagerValue02, cv.ManagerValue03, cv.ManagerValue04, cv.ManagerValue05, cv.ManagerValue06, cv.ManagerValue07, cv.ManagerValue08, cv.ManagerValue09, cv.ManagerValue10, cv.ManagerValue11, cv.ManagerValue12 + FROM chargevolume cv + ) cv + UNPIVOT ( Value FOR FiscalMonth IN (ManagerValue01, ManagerValue02, ManagerValue03, ManagerValue04, ManagerValue05, ManagerValue06, ManagerValue07, ManagerValue08, ManagerValue09, ManagerValue10, ManagerValue11, ManagerValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ManagerValue', 'Month')) mgr + ON ov.BudgetConfigID = mgr.BudgetConfigID + AND ov.EntityGroupConfigID = mgr.EntityGroupConfigID + AND ov.EntityID = mgr.EntityID + AND ov.DepartmentID = mgr.DepartmentID + AND ov.ChargeCodeID = mgr.ChargeCodeID + AND ov.ServiceLineID = mgr.ServiceLineID + AND ov.AgeCohortID = mgr.AgeCohortID + AND ov.MedicalSurgicalID = mgr.MedicalSurgicalID + AND ov.PatientClassID = mgr.PatientClassID + AND ov.UnitTypeID = mgr.UnitTypeID + AND ov.FiscalMonthID = mgr.FiscalMonthID + INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID + + + UNION ALL + + SELECT + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.DepartmentID, + ov.ChargeCodeID, + ov.ServiceLineID, + ov.AgeCohortID, + ov.MedicalSurgicalID, + ov.PatientClassID, + ov.UnitTypeID, + 12 as TimeClassID, + ov.FiscalMonthID, + bc.FiscalYearID - 1, + ov.InitialValue as OriginalValue, + v.Value, + v.Value as ManagerValue -- Manager value is not different in CV for Projection + FROM ( + -- Unpivot for OriginalValue + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, ChargeCodeID, DepartmentID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, + cv.InitialProjection01,cv.InitialProjection02, cv.InitialProjection03, cv.InitialProjection04, cv.InitialProjection05, cv.InitialProjection06, cv.InitialProjection07, cv.InitialProjection08, cv.InitialProjection09, cv.InitialProjection10, cv.InitialProjection11, cv.InitialProjection12 + FROM chargevolume cv + ) cv + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov + INNER JOIN ( + -- Unpivot for Value + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, ChargeCodeID, DepartmentID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, + cv.ProjectedValue01, cv.ProjectedValue02, cv.ProjectedValue03, cv.ProjectedValue04, cv.ProjectedValue05, cv.ProjectedValue06, cv.ProjectedValue07, cv.ProjectedValue08, cv.ProjectedValue09, cv.ProjectedValue10, cv.ProjectedValue11, cv.ProjectedValue12 + FROM chargevolume cv + ) cv + UNPIVOT ( Value FOR FiscalMonth IN (ProjectedValue01, ProjectedValue02, ProjectedValue03, ProjectedValue04, ProjectedValue05, ProjectedValue06, ProjectedValue07, ProjectedValue08, ProjectedValue09, ProjectedValue10, ProjectedValue11, ProjectedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectedValue', 'Month')) v + ON ov.BudgetConfigID = v.BudgetConfigID + AND ov.EntityGroupConfigID = v.EntityGroupConfigID + AND ov.EntityID = v.EntityID + AND ov.DepartmentID = v.DepartmentID + AND ov.ChargeCodeID = v.ChargeCodeID + AND ov.ServiceLineID = v.ServiceLineID + AND ov.AgeCohortID = v.AgeCohortID + AND ov.MedicalSurgicalID = v.MedicalSurgicalID + AND ov.PatientClassID = v.PatientClassID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID + INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID + ) cvData +GO + + +--------------------------------------------- + +-- fp.viewFactChargeVolume +CREATE VIEW fp.viewFactChargeVolume +AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-09-01 JB JAZZ-32095 Remove Payor and PayorGroupID from joins. + ** 2 2023-05-18 MY JAZZ-55153 Update to new structure + *************************************************************/ +SELECT + fcv.BudgetConfigID, + fcv.EntityGroupConfigID, + fcv.EntityID, + fcv.DepartmentID, + fcv.ServiceLineID, + fcv.PatientClassID, + fcv.AgeCohortID, + fcv.MedicalSurgicalID, + fcv.ChargeCodeID, + fcv.UnitTypeID, + fcv.ServiceEntityID, + fcv.MSDRGID, + fcv.UBRevCodeID, + fcv.PrimaryCPTID, + fcv.BillingCPTID, + fcv.ServiceProviderID, + fcv.ServiceProviderSpecialtyID, + fcv.PerformingProviderID, + fcv.PerformingProviderSpecialtyID, + 2 AS BudgetPhaseID, + fcv.BudgetLockType as BudgetLockType, + fcv.BudgetLockFlag as BudgetLockFlag, + fcv.ProjectionLockType as ProjectionLockType, + fcv.ProjectionLockFlag as ProjectionLockFlag, + fcv.TargetAdjusted01 AS AdjustedValue01, fcv.TargetAdjusted02 AS AdjustedValue02, fcv.TargetAdjusted03 AS AdjustedValue03, fcv.TargetAdjusted04 AS AdjustedValue04, fcv.TargetAdjusted05 AS AdjustedValue05, fcv.TargetAdjusted06 AS AdjustedValue06, + fcv.TargetAdjusted07 AS AdjustedValue07, fcv.TargetAdjusted08 AS AdjustedValue08, fcv.TargetAdjusted09 AS AdjustedValue09, fcv.TargetAdjusted10 AS AdjustedValue10, fcv.TargetAdjusted11 AS AdjustedValue11, fcv.TargetAdjusted12 AS AdjustedValue12, + fcv.TargetAdjustedTotal AS AdjustedValueTotal, + + fcv.TargetAdjusted01 AS FlexedValue01, fcv.TargetAdjusted02 AS FlexedValue02, fcv.TargetAdjusted03 AS FlexedValue03, fcv.TargetAdjusted04 AS FlexedValue04, fcv.TargetAdjusted05 AS FlexedValue05, fcv.TargetAdjusted06 AS FlexedValue06, + fcv.TargetAdjusted07 AS FlexedValue07, fcv.TargetAdjusted08 AS FlexedValue08, fcv.TargetAdjusted09 AS FlexedValue09, fcv.TargetAdjusted10 AS FlexedValue10, fcv.TargetAdjusted11 AS FlexedValue11, fcv.TargetAdjusted12 AS FlexedValue12, + fcv.TargetAdjustedTotal AS FlexedValueTotal, + + fcv.ProjectionAdjusted01 AS AdjustedProjectionValue01, fcv.ProjectionAdjusted02 AS AdjustedProjectionValue02, fcv.ProjectionAdjusted03 AS AdjustedProjectionValue03, fcv.ProjectionAdjusted04 AS AdjustedProjectionValue04, fcv.ProjectionAdjusted05 AS AdjustedProjectionValue05, fcv.ProjectionAdjusted06 AS AdjustedProjectionValue06, + fcv.ProjectionAdjusted07 AS AdjustedProjectionValue07, fcv.ProjectionAdjusted08 AS AdjustedProjectionValue08, fcv.ProjectionAdjusted09 AS AdjustedProjectionValue09, fcv.ProjectionAdjusted10 AS AdjustedProjectionValue10, fcv.ProjectionAdjusted11 AS AdjustedProjectionValue11, fcv.ProjectionAdjusted12 AS AdjustedProjectionValue12, + fcv.ProjectionAdjustedTotal AS AdjustedProjectionValueTotal, + + fcv.ProjectionAdjusted01 AS FlexedProjectionValue01, fcv.ProjectionAdjusted02 AS FlexedProjectionValue02, fcv.ProjectionAdjusted03 AS FlexedProjectionValue03, fcv.ProjectionAdjusted04 AS FlexedProjectionValue04, fcv.ProjectionAdjusted05 AS FlexedProjectionValue05, fcv.ProjectionAdjusted06 AS FlexedProjectionValue06, + fcv.ProjectionAdjusted07 AS FlexedProjectionValue07, fcv.ProjectionAdjusted08 AS FlexedProjectionValue08, fcv.ProjectionAdjusted09 AS FlexedProjectionValue09, fcv.ProjectionAdjusted10 AS FlexedProjectionValue10, fcv.ProjectionAdjusted11 AS FlexedProjectionValue11, fcv.ProjectionAdjusted12 AS FlexedProjectionValue12, + fcv.ProjectionAdjustedTotal AS FlexedProjectionValueTotal, + + fcv.VariableDirectUnitCost +FROM fp.ChargeVolume fcv +UNION ALL +SELECT + fcv.BudgetConfigID, + fcv.EntityGroupConfigID, + fcv.EntityID, + fcv.DepartmentID, + fcv.ServiceLineID, + fcv.PatientClassID, + fcv.AgeCohortID, + fcv.MedicalSurgicalID, + fcv.ChargeCodeID, + fcv.UnitTypeID, + fcv.ServiceEntityID, + fcv.MSDRGID, + fcv.UBRevCodeID, + fcv.PrimaryCPTID, + fcv.BillingCPTID, + fcv.ServiceProviderID, + fcv.ServiceProviderSpecialtyID, + fcv.PerformingProviderID, + fcv.PerformingProviderSpecialtyID, + 3 AS BudgetPhaseID, + fcv.BudgetLockType as BudgetLockType, + fcv.BudgetLockFlag as BudgetLockFlag, + fcv.ProjectionLockType as ProjectionLockType, + fcv.ProjectionLockFlag as ProjectionLockFlag, + fcv.BudgetAdjusted01 AS AdjustedValue01, fcv.BudgetAdjusted02 AS AdjustedValue02, fcv.BudgetAdjusted03 AS AdjustedValue03, fcv.BudgetAdjusted04 AS AdjustedValue04, fcv.BudgetAdjusted05 AS AdjustedValue05, fcv.BudgetAdjusted06 AS AdjustedValue06, + fcv.BudgetAdjusted07 AS AdjustedValue07, fcv.BudgetAdjusted08 AS AdjustedValue08, fcv.BudgetAdjusted09 AS AdjustedValue09, fcv.BudgetAdjusted10 AS AdjustedValue10, fcv.BudgetAdjusted11 AS AdjustedValue11, fcv.BudgetAdjusted12 AS AdjustedValue12, + fcv.BudgetAdjustedTotal AS AdjustedValueTotal, + + fcv.BudgetAdjusted01 AS FlexedValue01, fcv.BudgetAdjusted02 AS FlexedValue02, fcv.BudgetAdjusted03 AS FlexedValue03, fcv.BudgetAdjusted04 AS FlexedValue04, fcv.BudgetAdjusted05 AS FlexedValue05, fcv.BudgetAdjusted06 AS FlexedValue06, + fcv.BudgetAdjusted07 AS FlexedValue07, fcv.BudgetAdjusted08 AS FlexedValue08, fcv.BudgetAdjusted09 AS FlexedValue09, fcv.BudgetAdjusted10 AS FlexedValue10, fcv.BudgetAdjusted11 AS FlexedValue11, fcv.BudgetAdjusted12 AS FlexedValue12, + fcv.BudgetAdjustedTotal AS FlexedValueTotal, + + fcv.ProjectionAdjusted01 AS AdjustedProjectionValue01, fcv.ProjectionAdjusted02 AS AdjustedProjectionValue02, fcv.ProjectionAdjusted03 AS AdjustedProjectionValue03, fcv.ProjectionAdjusted04 AS AdjustedProjectionValue04, fcv.ProjectionAdjusted05 AS AdjustedProjectionValue05, fcv.ProjectionAdjusted06 AS AdjustedProjectionValue06, + fcv.ProjectionAdjusted07 AS AdjustedProjectionValue07, fcv.ProjectionAdjusted08 AS AdjustedProjectionValue08, fcv.ProjectionAdjusted09 AS AdjustedProjectionValue09, fcv.ProjectionAdjusted10 AS AdjustedProjectionValue10, fcv.ProjectionAdjusted11 AS AdjustedProjectionValue11, fcv.ProjectionAdjusted12 AS AdjustedProjectionValue12, + fcv.ProjectionAdjustedTotal AS AdjustedProjectionValueTotal, + + fcv.ProjectionAdjusted01 AS FlexedProjectionValue01, fcv.ProjectionAdjusted02 AS FlexedProjectionValue02, fcv.ProjectionAdjusted03 AS FlexedProjectionValue03, fcv.ProjectionAdjusted04 AS FlexedProjectionValue04, fcv.ProjectionAdjusted05 AS FlexedProjectionValue05, fcv.ProjectionAdjusted06 AS FlexedProjectionValue06, + fcv.ProjectionAdjusted07 AS FlexedProjectionValue07, fcv.ProjectionAdjusted08 AS FlexedProjectionValue08, fcv.ProjectionAdjusted09 AS FlexedProjectionValue09, fcv.ProjectionAdjusted10 AS FlexedProjectionValue10, fcv.ProjectionAdjusted11 AS FlexedProjectionValue11, fcv.ProjectionAdjusted12 AS FlexedProjectionValue12, + fcv.ProjectionAdjustedTotal AS FlexedProjectionValueTotal, + + fcv.VariableDirectUnitCost +FROM fp.ChargeVolume fcv +GO + + +--------------------------------------------- + +-- fp.viewFactChargeVolumeDollarsHistory_Unpivoted_source +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-01-03 MD JAZZ-29138 Initial +** 2 2023-05-18 MY JAZZ-55153 Update to new structure +*************************************************************/ +CREATE VIEW [fp].[viewFactChargeVolumeDollarsHistory_Unpivoted_source] +AS + +-- Unpivot for PriorYearActual +SELECT + data.BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, 34 as UnitTypeID, + 1 as TimeClassID, bc.FiscalYearID - 2 as FiscalYearID, data.FiscalMonthID, data.Value +FROM ( + SELECT + BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT + cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, + cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, + hist.PriorYearActualDollarValue01, hist.PriorYearActualDollarValue02, hist.PriorYearActualDollarValue03, hist.PriorYearActualDollarValue04, hist.PriorYearActualDollarValue05, hist.PriorYearActualDollarValue06, + hist.PriorYearActualDollarValue07, hist.PriorYearActualDollarValue08, hist.PriorYearActualDollarValue09, hist.PriorYearActualDollarValue10, hist.PriorYearActualDollarValue11, hist.PriorYearActualDollarValue12 + FROM [fp].[ChargeVolume] cv + INNER JOIN [fp].[ChargeVolumeHistory] hist ON cv.ChargeVolumeID = hist.ChargeVolumeID + WHERE cv.UnitTypeID = 145) cv + UNPIVOT ( Value FOR FiscalMonth IN (PriorYearActualDollarValue01, PriorYearActualDollarValue02, PriorYearActualDollarValue03, PriorYearActualDollarValue04, PriorYearActualDollarValue05, PriorYearActualDollarValue06, + PriorYearActualDollarValue07, PriorYearActualDollarValue08, PriorYearActualDollarValue09, PriorYearActualDollarValue10, PriorYearActualDollarValue11, PriorYearActualDollarValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'PriorYearActualValue', 'Month')) data + INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID + +UNION ALL + +-- Unpivot for ActualYTD +SELECT + data.BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, 34 as UnitTypeID, + 1 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value +FROM ( + SELECT + BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT + cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, + cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, + hist.ActualYTDDollarValue01, hist.ActualYTDDollarValue02, hist.ActualYTDDollarValue03, hist.ActualYTDDollarValue04, hist.ActualYTDDollarValue05, hist.ActualYTDDollarValue06, + hist.ActualYTDDollarValue07, hist.ActualYTDDollarValue08, hist.ActualYTDDollarValue09, hist.ActualYTDDollarValue10, hist.ActualYTDDollarValue11, hist.ActualYTDDollarValue12 + FROM [fp].[ChargeVolume] cv + INNER JOIN [fp].[ChargeVolumeHistory] hist ON cv.ChargeVolumeID = hist.ChargeVolumeID + WHERE cv.UnitTypeID = 145) cv + UNPIVOT ( Value FOR FiscalMonth IN (ActualYTDDollarValue01, ActualYTDDollarValue02, ActualYTDDollarValue03, ActualYTDDollarValue04, ActualYTDDollarValue05, ActualYTDDollarValue06, ActualYTDDollarValue07, ActualYTDDollarValue08, + ActualYTDDollarValue09, ActualYTDDollarValue10, ActualYTDDollarValue11, ActualYTDDollarValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ActualYTDValue', 'Month')) data + INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID + +UNION ALL + +-- Unpivot for CurrentYearBudget +SELECT + data.BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, 34 as UnitTypeID, + 2 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value +FROM ( + SELECT + BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT + cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, + cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, + hist.CurrentYearBudgetDollar01, hist.CurrentYearBudgetDollar02, hist.CurrentYearBudgetDollar03, hist.CurrentYearBudgetDollar04, hist.CurrentYearBudgetDollar05, hist.CurrentYearBudgetDollar06, + hist.CurrentYearBudgetDollar07, hist.CurrentYearBudgetDollar08, hist.CurrentYearBudgetDollar09, hist.CurrentYearBudgetDollar10, hist.CurrentYearBudgetDollar11, hist.CurrentYearBudgetDollar12 + FROM [fp].[ChargeVolume] cv + INNER JOIN [fp].[ChargeVolumeHistory] hist ON cv.ChargeVolumeID = hist.ChargeVolumeID + WHERE cv.UnitTypeID = 145) cv + UNPIVOT ( Value FOR FiscalMonth IN (CurrentYearBudgetDollar01, CurrentYearBudgetDollar02, CurrentYearBudgetDollar03, CurrentYearBudgetDollar04, CurrentYearBudgetDollar05, CurrentYearBudgetDollar06, + CurrentYearBudgetDollar07, CurrentYearBudgetDollar08, CurrentYearBudgetDollar09, CurrentYearBudgetDollar10, CurrentYearBudgetDollar11, CurrentYearBudgetDollar12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'CurrentYearBudgetValue', 'Month')) data + INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFactChargeVolumeDollars_Unpivoted_source +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2020-12-28 MD JAZZ-29138 Initial +** 2 2023-05-18 MY JAZZ-55153 Update to new structure +*************************************************************/ +CREATE VIEW [fp].[viewFactChargeVolumeDollars_Unpivoted_source] +AS + WITH chargevolume AS ( + SELECT + cv.BudgetConfigID, + cv.EntityGroupConfigID, + cv.EntityID, + cv.DepartmentID, + cv.ServiceLineID, + cv.PatientClassID, + cv.AgeCohortID, + cv.MedicalSurgicalID, + cv.ChargeCodeID, + cv.ServiceEntityID, + cv.MSDRGID, + cv.UBRevCodeID, + cv.PrimaryCPTID, + cv.ServiceProviderID, + cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, + cv.PerformingProviderSpecialtyID, + cv.BillingCPTID, + 34 as UnitTypeID, + SUM(cv.InitialBudgetDollars01) AS InitialBudget01, + SUM(cv.InitialBudgetDollars02) AS InitialBudget02, + SUM(cv.InitialBudgetDollars03) AS InitialBudget03, + SUM(cv.InitialBudgetDollars04) AS InitialBudget04, + SUM(cv.InitialBudgetDollars05) AS InitialBudget05, + SUM(cv.InitialBudgetDollars06) AS InitialBudget06, + SUM(cv.InitialBudgetDollars07) AS InitialBudget07, + SUM(cv.InitialBudgetDollars08) AS InitialBudget08, + SUM(cv.InitialBudgetDollars09) AS InitialBudget09, + SUM(cv.InitialBudgetDollars10) AS InitialBudget10, + SUM(cv.InitialBudgetDollars11) AS InitialBudget11, + SUM(cv.InitialBudgetDollars12) AS InitialBudget12, + SUM(cv.InitialProjectionDollars01) AS InitialProjection01, + SUM(cv.InitialProjectionDollars02) AS InitialProjection02, + SUM(cv.InitialProjectionDollars03) AS InitialProjection03, + SUM(cv.InitialProjectionDollars04) AS InitialProjection04, + SUM(cv.InitialProjectionDollars05) AS InitialProjection05, + SUM(cv.InitialProjectionDollars06) AS InitialProjection06, + SUM(cv.InitialProjectionDollars07) AS InitialProjection07, + SUM(cv.InitialProjectionDollars08) AS InitialProjection08, + SUM(cv.InitialProjectionDollars09) AS InitialProjection09, + SUM(cv.InitialProjectionDollars10) AS InitialProjection10, + SUM(cv.InitialProjectionDollars11) AS InitialProjection11, + SUM(cv.InitialProjectionDollars12) AS InitialProjection12, + SUM(cv.TargetDollarsAdjusted01) AS TargetValue01, + SUM(cv.TargetDollarsAdjusted02) AS TargetValue02, + SUM(cv.TargetDollarsAdjusted03) AS TargetValue03, + SUM(cv.TargetDollarsAdjusted04) AS TargetValue04, + SUM(cv.TargetDollarsAdjusted05) AS TargetValue05, + SUM(cv.TargetDollarsAdjusted06) AS TargetValue06, + SUM(cv.TargetDollarsAdjusted07) AS TargetValue07, + SUM(cv.TargetDollarsAdjusted08) AS TargetValue08, + SUM(cv.TargetDollarsAdjusted09) AS TargetValue09, + SUM(cv.TargetDollarsAdjusted10) AS TargetValue10, + SUM(cv.TargetDollarsAdjusted11) AS TargetValue11, + SUM(cv.TargetDollarsAdjusted12) AS TargetValue12, + SUM(cv.BudgetDollarsAdjusted01) AS ManagerValue01, + SUM(cv.BudgetDollarsAdjusted02) AS ManagerValue02, + SUM(cv.BudgetDollarsAdjusted03) AS ManagerValue03, + SUM(cv.BudgetDollarsAdjusted04) AS ManagerValue04, + SUM(cv.BudgetDollarsAdjusted05) AS ManagerValue05, + SUM(cv.BudgetDollarsAdjusted06) AS ManagerValue06, + SUM(cv.BudgetDollarsAdjusted07) AS ManagerValue07, + SUM(cv.BudgetDollarsAdjusted08) AS ManagerValue08, + SUM(cv.BudgetDollarsAdjusted09) AS ManagerValue09, + SUM(cv.BudgetDollarsAdjusted10) AS ManagerValue10, + SUM(cv.BudgetDollarsAdjusted11) AS ManagerValue11, + SUM(cv.BudgetDollarsAdjusted12) AS ManagerValue12, + SUM(cv.ProjectionDollarsAdjusted01) AS ProjectedValue01, + SUM(cv.ProjectionDollarsAdjusted02) AS ProjectedValue02, + SUM(cv.ProjectionDollarsAdjusted03) AS ProjectedValue03, + SUM(cv.ProjectionDollarsAdjusted04) AS ProjectedValue04, + SUM(cv.ProjectionDollarsAdjusted05) AS ProjectedValue05, + SUM(cv.ProjectionDollarsAdjusted06) AS ProjectedValue06, + SUM(cv.ProjectionDollarsAdjusted07) AS ProjectedValue07, + SUM(cv.ProjectionDollarsAdjusted08) AS ProjectedValue08, + SUM(cv.ProjectionDollarsAdjusted09) AS ProjectedValue09, + SUM(cv.ProjectionDollarsAdjusted10) AS ProjectedValue10, + SUM(cv.ProjectionDollarsAdjusted11) AS ProjectedValue11, + SUM(cv.ProjectionDollarsAdjusted12) AS ProjectedValue12 + FROM fp.ChargeVolume cv + INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigID = cv.BudgetConfigID + INNER JOIN [fp].[EntityGroupConfig] e ON e.BudgetConfigGUID = bc.BudgetConfigGUID AND e.EntityGroupConfigID = cv.EntityGroupConfigID + WHERE + bc.IsActive = 1 + AND cv.UnitTypeID = 145 + GROUP BY + cv.BudgetConfigID, + cv.EntityGroupConfigID, + cv.EntityID, + cv.DepartmentID, + cv.ServiceLineID, + cv.PatientClassID, + cv.AgeCohortID, + cv.MedicalSurgicalID, + cv.ChargeCodeID, + cv.ServiceEntityID, + cv.MSDRGID, + cv.UBRevCodeID, + cv.PrimaryCPTID, + cv.ServiceProviderID, + cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, + cv.PerformingProviderSpecialtyID, + cv.BillingCPTID, + cv.UnitTypeID + ) + SELECT + BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + ServiceLineID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + ChargeCodeID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + BillingCPTID, + UnitTypeID, + TimeClassID, + FiscalMonthID, + FiscalYearID, + OriginalValue, + Value, + ManagerValue + FROM ( + SELECT + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.DepartmentID, + ov.ServiceLineID, + ov.PatientClassID, + ov.AgeCohortID, + ov.MedicalSurgicalID, + ov.ChargeCodeID, + ov.ServiceEntityID, + ov.MSDRGID, + ov.UBRevCodeID, + ov.PrimaryCPTID, + ov.ServiceProviderID, + ov.ServiceProviderSpecialtyID, + ov.PerformingProviderID, + ov.PerformingProviderSpecialtyID, + ov.BillingCPTID, + ov.UnitTypeID, + 2 as TimeClassID, + ov.FiscalMonthID, + bc.FiscalYearID, + ov.InitialValue as OriginalValue, + v.Value, + mgr.Value as ManagerValue + FROM ( + -- Unpivot for OriginalValue + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, + cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, + cv.InitialBudget01, cv.InitialBudget02, cv.InitialBudget03, cv.InitialBudget04, cv.InitialBudget05, cv.InitialBudget06, cv.InitialBudget07, cv.InitialBudget08, cv.InitialBudget09, cv.InitialBudget10, cv.InitialBudget11, cv.InitialBudget12 + FROM chargevolume cv + ) cv + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov + INNER JOIN ( + -- Unpivot for Value + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, + cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, + cv.TargetValue01, cv.TargetValue02, cv.TargetValue03, cv.TargetValue04, cv.TargetValue05, cv.TargetValue06, cv.TargetValue07, cv.TargetValue08, cv.TargetValue09, cv.TargetValue10, cv.TargetValue11, cv.TargetValue12 + FROM chargevolume cv + ) cv + UNPIVOT ( Value FOR FiscalMonth IN (TargetValue01, TargetValue02, TargetValue03, TargetValue04, TargetValue05, TargetValue06, TargetValue07, TargetValue08, TargetValue09, TargetValue10, TargetValue11, TargetValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'TargetValue', 'Month')) v + ON + ov.BudgetConfigID = v.BudgetConfigID + AND ov.EntityGroupConfigID = v.EntityGroupConfigID + AND ov.EntityID = v.EntityID + AND ov.DepartmentID = v.DepartmentID + AND ov.ServiceLineID = v.ServiceLineID + AND ov.PatientClassID = v.PatientClassID + AND ov.AgeCohortID = v.AgeCohortID + AND ov.MedicalSurgicalID = v.MedicalSurgicalID + AND ov.ChargeCodeID = v.ChargeCodeID + AND ov.ServiceEntityID = v.ServiceEntityID + AND ov.MSDRGID = v.MSDRGID + AND ov.UBRevCodeID = v.UBRevCodeID + AND ov.PrimaryCPTID = v.PrimaryCPTID + AND ov.ServiceProviderID = v.ServiceProviderID + AND ov.ServiceProviderSpecialtyID = v.ServiceProviderSpecialtyID + AND ov.PerformingProviderID = v.PerformingProviderID + AND ov.PerformingProviderSpecialtyID = v.PerformingProviderSpecialtyID + AND ov.BillingCPTID = v.BillingCPTID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID + INNER JOIN ( + -- Unpivot for ManagerValue + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, + cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, + cv.ManagerValue01, cv.ManagerValue02, cv.ManagerValue03, cv.ManagerValue04, cv.ManagerValue05, cv.ManagerValue06, cv.ManagerValue07, cv.ManagerValue08, cv.ManagerValue09, cv.ManagerValue10, cv.ManagerValue11, cv.ManagerValue12 + FROM chargevolume cv + ) cv + UNPIVOT ( Value FOR FiscalMonth IN (ManagerValue01, ManagerValue02, ManagerValue03, ManagerValue04, ManagerValue05, ManagerValue06, ManagerValue07, ManagerValue08, ManagerValue09, ManagerValue10, ManagerValue11, ManagerValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ManagerValue', 'Month')) mgr + ON + ov.BudgetConfigID = mgr.BudgetConfigID + AND ov.EntityGroupConfigID = mgr.EntityGroupConfigID + AND ov.EntityID = mgr.EntityID + AND ov.DepartmentID = mgr.DepartmentID + AND ov.ServiceLineID = mgr.ServiceLineID + AND ov.PatientClassID = mgr.PatientClassID + AND ov.AgeCohortID = mgr.AgeCohortID + AND ov.MedicalSurgicalID = mgr.MedicalSurgicalID + AND ov.ChargeCodeID = mgr.ChargeCodeID + AND ov.ServiceEntityID = mgr.ServiceEntityID + AND ov.MSDRGID = mgr.MSDRGID + AND ov.UBRevCodeID = mgr.UBRevCodeID + AND ov.PrimaryCPTID = mgr.PrimaryCPTID + AND ov.ServiceProviderID = mgr.ServiceProviderID + AND ov.ServiceProviderSpecialtyID = mgr.ServiceProviderSpecialtyID + AND ov.PerformingProviderID = mgr.PerformingProviderID + AND ov.PerformingProviderSpecialtyID = mgr.PerformingProviderSpecialtyID + AND ov.BillingCPTID = mgr.BillingCPTID + AND ov.UnitTypeID = mgr.UnitTypeID + AND ov.FiscalMonthID = mgr.FiscalMonthID + INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID + + + UNION ALL + + SELECT + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.DepartmentID, + ov.ServiceLineID, + ov.PatientClassID, + ov.AgeCohortID, + ov.MedicalSurgicalID, + ov.ChargeCodeID, + ov.ServiceEntityID, + ov.MSDRGID, + ov.UBRevCodeID, + ov.PrimaryCPTID, + ov.ServiceProviderID, + ov.ServiceProviderSpecialtyID, + ov.PerformingProviderID, + ov.PerformingProviderSpecialtyID, + ov.BillingCPTID, + ov.UnitTypeID, + 12 as TimeClassID, + ov.FiscalMonthID, + bc.FiscalYearID - 1, + ov.InitialValue as OriginalValue, + v.Value, + v.Value as ManagerValue -- Manager value is not different in CV for Projection + FROM ( + -- Unpivot for OriginalValue + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, + cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, + cv.InitialProjection01,cv.InitialProjection02, cv.InitialProjection03, cv.InitialProjection04, cv.InitialProjection05, cv.InitialProjection06, cv.InitialProjection07, cv.InitialProjection08, cv.InitialProjection09, cv.InitialProjection10, cv.InitialProjection11, cv.InitialProjection12 + FROM chargevolume cv + ) cv + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov + INNER JOIN ( + -- Unpivot for Value + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, + cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, + cv.ProjectedValue01, cv.ProjectedValue02, cv.ProjectedValue03, cv.ProjectedValue04, cv.ProjectedValue05, cv.ProjectedValue06, cv.ProjectedValue07, cv.ProjectedValue08, cv.ProjectedValue09, cv.ProjectedValue10, cv.ProjectedValue11, cv.ProjectedValue12 + FROM chargevolume cv + ) cv + UNPIVOT ( Value FOR FiscalMonth IN (ProjectedValue01, ProjectedValue02, ProjectedValue03, ProjectedValue04, ProjectedValue05, ProjectedValue06, ProjectedValue07, ProjectedValue08, ProjectedValue09, ProjectedValue10, ProjectedValue11, ProjectedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectedValue', 'Month')) v + ON + ov.BudgetConfigID = v.BudgetConfigID + AND ov.EntityGroupConfigID = v.EntityGroupConfigID + AND ov.EntityID = v.EntityID + AND ov.DepartmentID = v.DepartmentID + AND ov.ServiceLineID = v.ServiceLineID + AND ov.PatientClassID = v.PatientClassID + AND ov.AgeCohortID = v.AgeCohortID + AND ov.MedicalSurgicalID = v.MedicalSurgicalID + AND ov.ChargeCodeID = v.ChargeCodeID + AND ov.ServiceEntityID = v.ServiceEntityID + AND ov.MSDRGID = v.MSDRGID + AND ov.UBRevCodeID = v.UBRevCodeID + AND ov.PrimaryCPTID = v.PrimaryCPTID + AND ov.ServiceProviderID = v.ServiceProviderID + AND ov.ServiceProviderSpecialtyID = v.ServiceProviderSpecialtyID + AND ov.PerformingProviderID = v.PerformingProviderID + AND ov.PerformingProviderSpecialtyID = v.PerformingProviderSpecialtyID + AND ov.BillingCPTID = v.BillingCPTID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID + INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID + ) cvData +GO + + +--------------------------------------------- + +-- fp.viewFactChargeVolumeHistory_Unpivoted +CREATE VIEW fp.viewFactChargeVolumeHistory_Unpivoted +AS +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-09-01 JB JAZZ-32095 Remove Payor and PayorGroupID from joins. +** 2 2023-05-18 MY JAZZ-55153 Update to new structure +*************************************************************/ + +-- Unpivot for PriorYearActual +SELECT data.ChargeVolumeID, data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.ServiceLineID, data.PatientClassID, data.AgeCohortID, data.MedicalSurgicalID, ChargeCodeID, data.UnitTypeID, +data.ServiceEntityID, +MSDRGID, +UBRevCodeID, +PrimaryCPTID, +BillingCPTID, +ServiceProviderID, +ServiceProviderSpecialtyID, +PerformingProviderID, +PerformingProviderSpecialtyID, +1 as TimeClassID, bc.FiscalYearID - 2 as FiscalYearID, data.FiscalMonthID, data.Value +FROM ( +SELECT ChargeVolumeID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, +ServiceEntityID, +MSDRGID, +UBRevCodeID, +PrimaryCPTID, +BillingCPTID, +ServiceProviderID, +ServiceProviderSpecialtyID, +PerformingProviderID, +PerformingProviderSpecialtyID, +UnitTypeID, m.FiscalMonthID, f.Value +FROM ( +SELECT fs.*, hist.PriorYearActualValue01, hist.PriorYearActualValue02, hist.PriorYearActualValue03, hist.PriorYearActualValue04, hist.PriorYearActualValue05, hist.PriorYearActualValue06, hist.PriorYearActualValue07, hist.PriorYearActualValue08, hist.PriorYearActualValue09, hist.PriorYearActualValue10, hist.PriorYearActualValue11, hist.PriorYearActualValue12 +FROM fp.ChargeVolume fs +INNER JOIN fp.ChargeVolumeHistory hist ON fs.ChargeVolumeID = hist.ChargeVolumeID ) fs +UNPIVOT ( Value FOR FiscalMonth IN (PriorYearActualValue01, PriorYearActualValue02, PriorYearActualValue03, PriorYearActualValue04, PriorYearActualValue05, PriorYearActualValue06, PriorYearActualValue07, PriorYearActualValue08, PriorYearActualValue09, PriorYearActualValue10, PriorYearActualValue11, PriorYearActualValue12)) as f +LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'PriorYearActualValue', 'Month')) data +INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID + +UNION ALL + +-- Unpivot for ActualYTD +SELECT data.ChargeVolumeID, data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.ServiceLineID, data.PatientClassID, data.AgeCohortID, data.MedicalSurgicalID, ChargeCodeID, data.UnitTypeID, +ServiceEntityID, +MSDRGID, +UBRevCodeID, +PrimaryCPTID, +BillingCPTID, +ServiceProviderID, +ServiceProviderSpecialtyID, +PerformingProviderID, +PerformingProviderSpecialtyID, +1 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value +FROM ( +SELECT ChargeVolumeID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, +ServiceEntityID, +MSDRGID, +UBRevCodeID, +PrimaryCPTID, +BillingCPTID, +ServiceProviderID, +ServiceProviderSpecialtyID, +PerformingProviderID, +PerformingProviderSpecialtyID, + UnitTypeID, m.FiscalMonthID, f.Value +FROM ( +SELECT fs.*, hist.ActualYTDValue01, hist.ActualYTDValue02, hist.ActualYTDValue03, hist.ActualYTDValue04, hist.ActualYTDValue05, hist.ActualYTDValue06, hist.ActualYTDValue07, hist.ActualYTDValue08, hist.ActualYTDValue09, hist.ActualYTDValue10, hist.ActualYTDValue11, hist.ActualYTDValue12 +FROM fp.ChargeVolume fs +INNER JOIN fp.ChargeVolumeHistory hist ON fs.ChargeVolumeID = hist.ChargeVolumeID ) fs +UNPIVOT ( Value FOR FiscalMonth IN (ActualYTDValue01, ActualYTDValue02, ActualYTDValue03, ActualYTDValue04, ActualYTDValue05, ActualYTDValue06, ActualYTDValue07, ActualYTDValue08, ActualYTDValue09, ActualYTDValue10, ActualYTDValue11, ActualYTDValue12)) as f +LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ActualYTDValue', 'Month')) data +INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID + +UNION ALL + +-- Unpivot for CurrentYearBudgetValue +SELECT data.ChargeVolumeID, data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.ServiceLineID, data.PatientClassID, data.AgeCohortID, data.MedicalSurgicalID, ChargeCodeID, data.UnitTypeID, +ServiceEntityID, +MSDRGID, +UBRevCodeID, +PrimaryCPTID, +BillingCPTID, +ServiceProviderID, +ServiceProviderSpecialtyID, +PerformingProviderID, +PerformingProviderSpecialtyID, +2 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value +FROM ( +SELECT ChargeVolumeID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, +ServiceEntityID, +MSDRGID, +UBRevCodeID, +PrimaryCPTID, +BillingCPTID, +ServiceProviderID, +ServiceProviderSpecialtyID, +PerformingProviderID, +PerformingProviderSpecialtyID, + UnitTypeID, m.FiscalMonthID, f.Value +FROM ( +SELECT fs.*, hist.CurrentYearBudget01, hist.CurrentYearBudget02, hist.CurrentYearBudget03, hist.CurrentYearBudget04, hist.CurrentYearBudget05, hist.CurrentYearBudget06, hist.CurrentYearBudget07, hist.CurrentYearBudget08, hist.CurrentYearBudget09, hist.CurrentYearBudget10, hist.CurrentYearBudget11, hist.CurrentYearBudget12 +FROM fp.ChargeVolume fs +INNER JOIN fp.ChargeVolumeHistory hist ON fs.ChargeVolumeID = hist.ChargeVolumeID ) fs +UNPIVOT ( Value FOR FiscalMonth IN (CurrentYearBudget01, CurrentYearBudget02, CurrentYearBudget03, CurrentYearBudget04, CurrentYearBudget05, CurrentYearBudget06, CurrentYearBudget07, CurrentYearBudget08, CurrentYearBudget09, CurrentYearBudget10, CurrentYearBudget11, CurrentYearBudget12)) as f +LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'CurrentYearBudgetValue', 'Month')) data +INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFactChargeVolumeHistory_Unpivoted_source +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-01-03 MD JAZZ-29138 Initial +** 2 2023-05-18 MY JAZZ-55153 Update to new structure +*************************************************************/ +CREATE VIEW [fp].[viewFactChargeVolumeHistory_Unpivoted_source] +AS + +-- Unpivot for PriorYearActual +SELECT + data.BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, + 1 as TimeClassID, bc.FiscalYearID - 2 as FiscalYearID, data.FiscalMonthID, data.Value +FROM ( + SELECT + BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT + cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, + cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, + hist.PriorYearActualValue01, hist.PriorYearActualValue02, hist.PriorYearActualValue03, hist.PriorYearActualValue04, hist.PriorYearActualValue05, hist.PriorYearActualValue06, + hist.PriorYearActualValue07, hist.PriorYearActualValue08, hist.PriorYearActualValue09, hist.PriorYearActualValue10, hist.PriorYearActualValue11, hist.PriorYearActualValue12 + FROM [fp].[ChargeVolume] cv + INNER JOIN [fp].[ChargeVolumeHistory] hist ON cv.ChargeVolumeID = hist.ChargeVolumeID + WHERE cv.UnitTypeID = 145) cv + UNPIVOT ( Value FOR FiscalMonth IN (PriorYearActualValue01, PriorYearActualValue02, PriorYearActualValue03, PriorYearActualValue04, PriorYearActualValue05, PriorYearActualValue06, + PriorYearActualValue07, PriorYearActualValue08, PriorYearActualValue09, PriorYearActualValue10, PriorYearActualValue11, PriorYearActualValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'PriorYearActualValue', 'Month')) data + INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID + +UNION ALL + +-- Unpivot for ActualYTD +SELECT + data.BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, + 1 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value +FROM ( + SELECT + BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT + cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, + cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, + hist.ActualYTDValue01, hist.ActualYTDValue02, hist.ActualYTDValue03, hist.ActualYTDValue04, hist.ActualYTDValue05, hist.ActualYTDValue06, + hist.ActualYTDValue07, hist.ActualYTDValue08, hist.ActualYTDValue09, hist.ActualYTDValue10, hist.ActualYTDValue11, hist.ActualYTDValue12 + FROM [fp].[ChargeVolume] cv + INNER JOIN [fp].[ChargeVolumeHistory] hist ON cv.ChargeVolumeID = hist.ChargeVolumeID + WHERE cv.UnitTypeID = 145) cv + UNPIVOT ( Value FOR FiscalMonth IN (ActualYTDValue01, ActualYTDValue02, ActualYTDValue03, ActualYTDValue04, ActualYTDValue05, ActualYTDValue06, ActualYTDValue07, ActualYTDValue08, + ActualYTDValue09, ActualYTDValue10, ActualYTDValue11, ActualYTDValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ActualYTDValue', 'Month')) data + INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID + +UNION ALL + +-- Unpivot for CurrentYearBudget +SELECT + data.BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, + 2 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value +FROM ( + SELECT + BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT + cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, + cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, + hist.CurrentYearBudget01, hist.CurrentYearBudget02, hist.CurrentYearBudget03, hist.CurrentYearBudget04, hist.CurrentYearBudget05, hist.CurrentYearBudget06, + hist.CurrentYearBudget07, hist.CurrentYearBudget08, hist.CurrentYearBudget09, hist.CurrentYearBudget10, hist.CurrentYearBudget11, hist.CurrentYearBudget12 + FROM [fp].[ChargeVolume] cv + INNER JOIN [fp].[ChargeVolumeHistory] hist ON cv.ChargeVolumeID = hist.ChargeVolumeID + WHERE cv.UnitTypeID = 145) cv + UNPIVOT ( Value FOR FiscalMonth IN (CurrentYearBudget01, CurrentYearBudget02, CurrentYearBudget03, CurrentYearBudget04, CurrentYearBudget05, CurrentYearBudget06, + CurrentYearBudget07, CurrentYearBudget08, CurrentYearBudget09, CurrentYearBudget10, CurrentYearBudget11, CurrentYearBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'CurrentYearBudgetValue', 'Month')) data + INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFactChargeVolume_Totals +CREATE VIEW fp.viewFactChargeVolume_Totals +AS +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-09-01 JB JAZZ-32095 Remove Payor and PayorGroupID from joins. +** 2 2023-05-18 MY JAZZ-55153 Update to new structure +*************************************************************/ +SELECT + fcv.BudgetConfigID, + fcv.EntityGroupConfigID, + fcv.EntityID, + fcv.DepartmentID, + fcv.ServiceLineID, + fcv.PatientClassID, + fcv.AgeCohortID, + fcv.MedicalSurgicalID, + fcv.ChargeCodeID, + fcv.UnitTypeID, + fcv.ServiceEntityID, + fcv.MSDRGID, + fcv.UBRevCodeID, + fcv.PrimaryCPTID, + fcv.BillingCPTID, + fcv.ServiceProviderID, + fcv.ServiceProviderSpecialtyID, + fcv.PerformingProviderID, + fcv.PerformingProviderSpecialtyID, + 2 AS BudgetPhaseID, + fcv.BudgetLockType as BudgetLockType, + fcv.BudgetLockFlag as BudgetLockFlag, + fcv.ProjectionLockType as ProjectionLockType, + fcv.ProjectionLockFlag as ProjectionLockFlag, + fcv.TargetAdjustedTotal AS AdjustedValueTotal, + fcv.TargetAdjustedTotal AS FlexedValueTotal, + fcv.ProjectionAdjustedTotal AS AdjustedProjectionValueTotal, + fcv.ProjectionAdjustedTotal AS FlexedProjectionValueTotal, + fcv.VariableDirectUnitCost +FROM fp.ChargeVolume fcv +UNION ALL +SELECT + fcv.BudgetConfigID, + fcv.EntityGroupConfigID, + fcv.EntityID, + fcv.DepartmentID, + fcv.ServiceLineID, + fcv.PatientClassID, + fcv.AgeCohortID, + fcv.MedicalSurgicalID, + fcv.ChargeCodeID, + fcv.UnitTypeID, + fcv.ServiceEntityID, + fcv.MSDRGID, + fcv.UBRevCodeID, + fcv.PrimaryCPTID, + fcv.BillingCPTID, + fcv.ServiceProviderID, + fcv.ServiceProviderSpecialtyID, + fcv.PerformingProviderID, + fcv.PerformingProviderSpecialtyID, + 3 AS BudgetPhaseID, + fcv.BudgetLockType as BudgetLockType, + fcv.BudgetLockFlag as BudgetLockFlag, + fcv.ProjectionLockType as ProjectionLockType, + fcv.ProjectionLockFlag as ProjectionLockFlag, + fcv.BudgetAdjustedTotal AS AdjustedValueTotal, + fcv.BudgetAdjustedTotal AS FlexedValueTotal, + fcv.ProjectionAdjustedTotal AS AdjustedProjectionValueTotal, + fcv.ProjectionAdjustedTotal AS FlexedProjectionValueTotal, + fcv.VariableDirectUnitCost +FROM fp.ChargeVolume fcv +GO + + +--------------------------------------------- + +-- fp.viewFactChargeVolume_Unpivoted +CREATE VIEW fp.viewFactChargeVolume_Unpivoted +AS +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-09-01 JB JAZZ-32095 Remove Payor and PayorGroupID from joins. +** 2 2023-05-18 MY JAZZ-55153 Update to new structure +*************************************************************/ +SELECT + ov.ChargeVolumeID, + ov.BudgetConfigID, + ov.EntityID, + ov.DepartmentID, + ov.ServiceLineID, + ov.PatientClassID, + ov.AgeCohortID, + ov.MedicalSurgicalID, + ov.ChargeCodeID, + ov.UnitTypeID, + ov.ServiceEntityID, + ov.MSDRGID, + ov.UBRevCodeID, + ov.PrimaryCPTID, + ov.BillingCPTID, + ov.ServiceProviderID, + ov.ServiceProviderSpecialtyID, + ov.PerformingProviderID, + ov.PerformingProviderSpecialtyID, + 2 as TimeClassID, + ov.FiscalMonthID, + ov.InitialValue as OriginalValue, + v.Value, + mgrv.Value as ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT ChargeVolumeID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, UnitTypeID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + BillingCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + m.FiscalMonthID, + f.InitialValue + FROM ( + SELECT cv.* + FROM fp.ChargeVolume cv ) cv + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT ChargeVolumeID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, UnitTypeID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + BillingCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + m.FiscalMonthID, + f.Value, + LockType + FROM ( + SELECT fcv.*, fcv.TargetLockType AS LockType, + fcv.TargetAdjusted01 AS AdjustedValue01, fcv.TargetAdjusted02 AS AdjustedValue02, fcv.TargetAdjusted03 AS AdjustedValue03, fcv.TargetAdjusted04 AS AdjustedValue04, fcv.TargetAdjusted05 AS AdjustedValue05, + fcv.TargetAdjusted06 AS AdjustedValue06, fcv.TargetAdjusted07 AS AdjustedValue07, fcv.TargetAdjusted08 AS AdjustedValue08, fcv.TargetAdjusted09 AS AdjustedValue09, fcv.TargetAdjusted10 AS AdjustedValue10, + fcv.TargetAdjusted11 AS AdjustedValue11, fcv.TargetAdjusted12 AS AdjustedValue12 + FROM fp.ChargeVolume fcv) cv + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.BudgetConfigID = v.BudgetConfigID + AND ov.EntityID = v.EntityID + AND ov.DepartmentID = v.DepartmentID + AND ov.ServiceLineID = v.ServiceLineID + AND ov.PatientClassID = v.PatientClassID + AND ov.AgeCohortID = v.AgeCohortID + AND ov.MedicalSurgicalID = v.MedicalSurgicalID + AND ov.ChargeCodeID = v.ChargeCodeID + AND ov.ServiceEntityID = v.ServiceEntityID + AND ov.MSDRGID = v.MSDRGID + AND ov.UBRevCodeID = v.UBRevCodeID + AND ov.PrimaryCPTID = v.PrimaryCPTID + AND ov.BillingCPTID = v.BillingCPTID + AND ov.ServiceProviderID = v.ServiceProviderID + AND ov.ServiceProviderSpecialtyID = v.ServiceProviderSpecialtyID + AND ov.PerformingProviderID = v.PerformingProviderID + AND ov.PerformingProviderSpecialtyID = v.PerformingProviderSpecialtyID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN ( + -- Unpivot for Manager Value + SELECT ChargeVolumeID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, UnitTypeID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + BillingCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + m.FiscalMonthID, + f.Value, + LockType + FROM ( + SELECT fcv.*, fcv.BudgetLockType AS LockType, + fcv.BudgetAdjusted01 AS AdjustedValue01, fcv.BudgetAdjusted02 AS AdjustedValue02, fcv.BudgetAdjusted03 AS AdjustedValue03, fcv.BudgetAdjusted04 AS AdjustedValue04, fcv.BudgetAdjusted05 AS AdjustedValue05, + fcv.BudgetAdjusted06 AS AdjustedValue06, fcv.BudgetAdjusted07 AS AdjustedValue07, fcv.BudgetAdjusted08 AS AdjustedValue08, fcv.BudgetAdjusted09 AS AdjustedValue09, fcv.BudgetAdjusted10 AS AdjustedValue10, + fcv.BudgetAdjusted11 AS AdjustedValue11, fcv.BudgetAdjusted12 AS AdjustedValue12 + FROM fp.ChargeVolume fcv) cv + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.EntityID = mgrv.EntityID + AND ov.DepartmentID = mgrv.DepartmentID + AND ov.ServiceLineID = mgrv.ServiceLineID + AND ov.PatientClassID = mgrv.PatientClassID + AND ov.AgeCohortID = mgrv.AgeCohortID + AND ov.MedicalSurgicalID = mgrv.MedicalSurgicalID + AND ov.ChargeCodeID = mgrv.ChargeCodeID + AND ov.ChargeCodeID = v.ChargeCodeID + AND ov.ServiceEntityID = v.ServiceEntityID + AND ov.MSDRGID = v.MSDRGID + AND ov.UBRevCodeID = v.UBRevCodeID + AND ov.PrimaryCPTID = v.PrimaryCPTID + AND ov.BillingCPTID = v.BillingCPTID + AND ov.ServiceProviderID = v.ServiceProviderID + AND ov.ServiceProviderSpecialtyID = v.ServiceProviderSpecialtyID + AND ov.PerformingProviderID = v.PerformingProviderID + AND ov.PerformingProviderSpecialtyID = v.PerformingProviderSpecialtyID + AND ov.UnitTypeID = mgrv.UnitTypeID + AND ov.FiscalMonthID = mgrv.FiscalMonthID + +UNION ALL + + SELECT + ov.ChargeVolumeID, + ov.BudgetConfigID, + ov.EntityID, + ov.DepartmentID, + ov.ServiceLineID, + ov.PatientClassID, + ov.AgeCohortID, + ov.MedicalSurgicalID, + ov.ChargeCodeID, + ov.UnitTypeID, + ov.ServiceEntityID, + ov.MSDRGID, + ov.UBRevCodeID, + ov.PrimaryCPTID, + ov.BillingCPTID, + ov.ServiceProviderID, + ov.ServiceProviderSpecialtyID, + ov.PerformingProviderID, + ov.PerformingProviderSpecialtyID, + 12 as TimeClassID, + ov.FiscalMonthID, + ov.InitialValue as OriginalValue, + v.Value, + mgrv.Value as ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT ChargeVolumeID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, UnitTypeID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + BillingCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + m.FiscalMonthID, + f.InitialValue + FROM ( + SELECT cv.* + FROM fp.ChargeVolume cv ) cv + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT ChargeVolumeID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, UnitTypeID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + BillingCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + m.FiscalMonthID, + f.Value, + LockType + FROM ( + SELECT fcv.*, fcv.ProjectionLockType AS LockType, + fcv.ProjectionAdjusted01 AS AdjustedValue01, fcv.ProjectionAdjusted02 AS AdjustedValue02, fcv.ProjectionAdjusted03 AS AdjustedValue03, fcv.ProjectionAdjusted04 AS AdjustedValue04, fcv.ProjectionAdjusted05 AS AdjustedValue05, + fcv.ProjectionAdjusted06 AS AdjustedValue06, fcv.ProjectionAdjusted07 AS AdjustedValue07, fcv.ProjectionAdjusted08 AS AdjustedValue08, fcv.ProjectionAdjusted09 AS AdjustedValue09, fcv.ProjectionAdjusted10 AS AdjustedValue10, + fcv.ProjectionAdjusted11 AS AdjustedValue11, fcv.ProjectionAdjusted12 AS AdjustedValue12 + FROM fp.ChargeVolume fcv) cv + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.BudgetConfigID = v.BudgetConfigID + AND ov.EntityID = v.EntityID + AND ov.DepartmentID = v.DepartmentID + AND ov.ServiceLineID = v.ServiceLineID + AND ov.PatientClassID = v.PatientClassID + AND ov.AgeCohortID = v.AgeCohortID + AND ov.MedicalSurgicalID = v.MedicalSurgicalID + AND ov.ChargeCodeID = v.ChargeCodeID + AND ov.ServiceEntityID = v.ServiceEntityID + AND ov.MSDRGID = v.MSDRGID + AND ov.UBRevCodeID = v.UBRevCodeID + AND ov.PrimaryCPTID = v.PrimaryCPTID + AND ov.BillingCPTID = v.BillingCPTID + AND ov.ServiceProviderID = v.ServiceProviderID + AND ov.ServiceProviderSpecialtyID = v.ServiceProviderSpecialtyID + AND ov.PerformingProviderID = v.PerformingProviderID + AND ov.PerformingProviderSpecialtyID = v.PerformingProviderSpecialtyID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN ( + -- Unpivot for Manager Value + SELECT ChargeVolumeID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, UnitTypeID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + BillingCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + m.FiscalMonthID, + f.Value, + LockType + FROM ( + SELECT fcv.*, fcv.ProjectionLockType AS LockType, + fcv.ProjectionAdjusted01 AS AdjustedValue01, fcv.ProjectionAdjusted02 AS AdjustedValue02, fcv.ProjectionAdjusted03 AS AdjustedValue03, fcv.ProjectionAdjusted04 AS AdjustedValue04, fcv.ProjectionAdjusted05 AS AdjustedValue05, + fcv.ProjectionAdjusted06 AS AdjustedValue06, fcv.ProjectionAdjusted07 AS AdjustedValue07, fcv.ProjectionAdjusted08 AS AdjustedValue08, fcv.ProjectionAdjusted09 AS AdjustedValue09, fcv.ProjectionAdjusted10 AS AdjustedValue10, + fcv.ProjectionAdjusted11 AS AdjustedValue11, fcv.ProjectionAdjusted12 AS AdjustedValue12 + FROM fp.ChargeVolume fcv) cv + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.EntityID = mgrv.EntityID + AND ov.DepartmentID = mgrv.DepartmentID + AND ov.ServiceLineID = mgrv.ServiceLineID + AND ov.PatientClassID = mgrv.PatientClassID + AND ov.AgeCohortID = mgrv.AgeCohortID + AND ov.MedicalSurgicalID = mgrv.MedicalSurgicalID + AND ov.ChargeCodeID = mgrv.ChargeCodeID + AND ov.ServiceEntityID = v.ServiceEntityID + AND ov.MSDRGID = v.MSDRGID + AND ov.UBRevCodeID = v.UBRevCodeID + AND ov.PrimaryCPTID = v.PrimaryCPTID + AND ov.BillingCPTID = v.BillingCPTID + AND ov.ServiceProviderID = v.ServiceProviderID + AND ov.ServiceProviderSpecialtyID = v.ServiceProviderSpecialtyID + AND ov.PerformingProviderID = v.PerformingProviderID + AND ov.PerformingProviderSpecialtyID = v.PerformingProviderSpecialtyID + AND ov.UnitTypeID = mgrv.UnitTypeID + AND ov.FiscalMonthID = mgrv.FiscalMonthID +GO + + +--------------------------------------------- + +-- fp.viewFactChargeVolume_Unpivoted_source +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2020-12-28 MD JAZZ-29138 Initial +** 2 2023-05-18 MY JAZZ-55153 Update to new structure +*************************************************************/ +CREATE VIEW [fp].[viewFactChargeVolume_Unpivoted_source] +AS + WITH chargevolume AS ( + SELECT + cv.BudgetConfigID, + cv.EntityGroupConfigID, + cv.EntityID, + cv.DepartmentID, + cv.ServiceLineID, + cv.PatientClassID, + cv.AgeCohortID, + cv.MedicalSurgicalID, + cv.ChargeCodeID, + cv.ServiceEntityID, + cv.MSDRGID, + cv.UBRevCodeID, + cv.PrimaryCPTID, + cv.ServiceProviderID, + cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, + cv.PerformingProviderSpecialtyID, + cv.BillingCPTID, + cv.UnitTypeID, + + SUM(cv.InitialBudget01) AS InitialBudget01, + SUM(cv.InitialBudget02) AS InitialBudget02, + SUM(cv.InitialBudget03) AS InitialBudget03, + SUM(cv.InitialBudget04) AS InitialBudget04, + SUM(cv.InitialBudget05) AS InitialBudget05, + SUM(cv.InitialBudget06) AS InitialBudget06, + SUM(cv.InitialBudget07) AS InitialBudget07, + SUM(cv.InitialBudget08) AS InitialBudget08, + SUM(cv.InitialBudget09) AS InitialBudget09, + SUM(cv.InitialBudget10) AS InitialBudget10, + SUM(cv.InitialBudget11) AS InitialBudget11, + SUM(cv.InitialBudget12) AS InitialBudget12, + SUM(cv.InitialProjection01) AS InitialProjection01, + SUM(cv.InitialProjection02) AS InitialProjection02, + SUM(cv.InitialProjection03) AS InitialProjection03, + SUM(cv.InitialProjection04) AS InitialProjection04, + SUM(cv.InitialProjection05) AS InitialProjection05, + SUM(cv.InitialProjection06) AS InitialProjection06, + SUM(cv.InitialProjection07) AS InitialProjection07, + SUM(cv.InitialProjection08) AS InitialProjection08, + SUM(cv.InitialProjection09) AS InitialProjection09, + SUM(cv.InitialProjection10) AS InitialProjection10, + SUM(cv.InitialProjection11) AS InitialProjection11, + SUM(cv.InitialProjection12) AS InitialProjection12, + SUM(cv.TargetAdjusted01) AS TargetValue01, + SUM(cv.TargetAdjusted02) AS TargetValue02, + SUM(cv.TargetAdjusted03) AS TargetValue03, + SUM(cv.TargetAdjusted04) AS TargetValue04, + SUM(cv.TargetAdjusted05) AS TargetValue05, + SUM(cv.TargetAdjusted06) AS TargetValue06, + SUM(cv.TargetAdjusted07) AS TargetValue07, + SUM(cv.TargetAdjusted08) AS TargetValue08, + SUM(cv.TargetAdjusted09) AS TargetValue09, + SUM(cv.TargetAdjusted10) AS TargetValue10, + SUM(cv.TargetAdjusted11) AS TargetValue11, + SUM(cv.TargetAdjusted12) AS TargetValue12, + SUM(cv.BudgetAdjusted01) AS ManagerValue01, + SUM(cv.BudgetAdjusted02) AS ManagerValue02, + SUM(cv.BudgetAdjusted03) AS ManagerValue03, + SUM(cv.BudgetAdjusted04) AS ManagerValue04, + SUM(cv.BudgetAdjusted05) AS ManagerValue05, + SUM(cv.BudgetAdjusted06) AS ManagerValue06, + SUM(cv.BudgetAdjusted07) AS ManagerValue07, + SUM(cv.BudgetAdjusted08) AS ManagerValue08, + SUM(cv.BudgetAdjusted09) AS ManagerValue09, + SUM(cv.BudgetAdjusted10) AS ManagerValue10, + SUM(cv.BudgetAdjusted11) AS ManagerValue11, + SUM(cv.BudgetAdjusted12) AS ManagerValue12, + SUM(cv.ProjectionAdjusted01) AS ProjectedValue01, + SUM(cv.ProjectionAdjusted02) AS ProjectedValue02, + SUM(cv.ProjectionAdjusted03) AS ProjectedValue03, + SUM(cv.ProjectionAdjusted04) AS ProjectedValue04, + SUM(cv.ProjectionAdjusted05) AS ProjectedValue05, + SUM(cv.ProjectionAdjusted06) AS ProjectedValue06, + SUM(cv.ProjectionAdjusted07) AS ProjectedValue07, + SUM(cv.ProjectionAdjusted08) AS ProjectedValue08, + SUM(cv.ProjectionAdjusted09) AS ProjectedValue09, + SUM(cv.ProjectionAdjusted10) AS ProjectedValue10, + SUM(cv.ProjectionAdjusted11) AS ProjectedValue11, + SUM(cv.ProjectionAdjusted12) AS ProjectedValue12 + FROM fp.ChargeVolume cv + INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigID = cv.BudgetConfigID + INNER JOIN [fp].[EntityGroupConfig] e ON e.BudgetConfigGUID = bc.BudgetConfigGUID AND e.EntityGroupConfigID = cv.EntityGroupConfigID + WHERE + bc.IsActive = 1 + AND cv.UnitTypeID = 145 + GROUP BY + cv.BudgetConfigID, + cv.EntityGroupConfigID, + cv.EntityID, + cv.DepartmentID, + cv.ServiceLineID, + cv.PatientClassID, + cv.AgeCohortID, + cv.MedicalSurgicalID, + cv.ChargeCodeID, + cv.ServiceEntityID, + cv.MSDRGID, + cv.UBRevCodeID, + cv.PrimaryCPTID, + cv.ServiceProviderID, + cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, + cv.PerformingProviderSpecialtyID, + cv.BillingCPTID, + cv.UnitTypeID + ) + SELECT + BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + ServiceLineID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + ChargeCodeID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + BillingCPTID, + UnitTypeID, + TimeClassID, + FiscalMonthID, + FiscalYearID, + OriginalValue, + Value, + ManagerValue + FROM ( + SELECT + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.DepartmentID, + ov.ServiceLineID, + ov.PatientClassID, + ov.AgeCohortID, + ov.MedicalSurgicalID, + ov.ChargeCodeID, + ov.ServiceEntityID, + ov.MSDRGID, + ov.UBRevCodeID, + ov.PrimaryCPTID, + ov.ServiceProviderID, + ov.ServiceProviderSpecialtyID, + ov.PerformingProviderID, + ov.PerformingProviderSpecialtyID, + ov.BillingCPTID, + ov.UnitTypeID, + 2 as TimeClassID, + ov.FiscalMonthID, + bc.FiscalYearID, + ov.InitialValue as OriginalValue, + v.Value, + mgr.Value as ManagerValue + FROM ( + -- Unpivot for OriginalValue + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT + cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, + cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, + cv.InitialBudget01, cv.InitialBudget02, cv.InitialBudget03, cv.InitialBudget04, cv.InitialBudget05, cv.InitialBudget06, cv.InitialBudget07, cv.InitialBudget08, cv.InitialBudget09, cv.InitialBudget10, cv.InitialBudget11, cv.InitialBudget12 + FROM chargevolume cv + ) cv + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov + INNER JOIN ( + -- Unpivot for Value + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, + cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, + cv.TargetValue01, cv.TargetValue02, cv.TargetValue03, cv.TargetValue04, cv.TargetValue05, cv.TargetValue06, cv.TargetValue07, cv.TargetValue08, cv.TargetValue09, cv.TargetValue10, cv.TargetValue11, cv.TargetValue12 + FROM chargevolume cv + ) cv + UNPIVOT ( Value FOR FiscalMonth IN (TargetValue01, TargetValue02, TargetValue03, TargetValue04, TargetValue05, TargetValue06, TargetValue07, TargetValue08, TargetValue09, TargetValue10, TargetValue11, TargetValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'TargetValue', 'Month')) v + ON + ov.BudgetConfigID = v.BudgetConfigID + AND ov.EntityGroupConfigID = v.EntityGroupConfigID + AND ov.EntityID = v.EntityID + AND ov.DepartmentID = v.DepartmentID + AND ov.ServiceLineID = v.ServiceLineID + AND ov.PatientClassID = v.PatientClassID + AND ov.AgeCohortID = v.AgeCohortID + AND ov.MedicalSurgicalID = v.MedicalSurgicalID + AND ov.ChargeCodeID = v.ChargeCodeID + AND ov.ServiceEntityID = v.ServiceEntityID + AND ov.MSDRGID = v.MSDRGID + AND ov.UBRevCodeID = v.UBRevCodeID + AND ov.PrimaryCPTID = v.PrimaryCPTID + AND ov.ServiceProviderID = v.ServiceProviderID + AND ov.ServiceProviderSpecialtyID = v.ServiceProviderSpecialtyID + AND ov.PerformingProviderID = v.PerformingProviderID + AND ov.PerformingProviderSpecialtyID = v.PerformingProviderSpecialtyID + AND ov.BillingCPTID = v.BillingCPTID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID + INNER JOIN ( + -- Unpivot for ManagerValue + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, + cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, + cv.ManagerValue01, cv.ManagerValue02, cv.ManagerValue03, cv.ManagerValue04, cv.ManagerValue05, cv.ManagerValue06, cv.ManagerValue07, cv.ManagerValue08, cv.ManagerValue09, cv.ManagerValue10, cv.ManagerValue11, cv.ManagerValue12 + FROM chargevolume cv + ) cv + UNPIVOT ( Value FOR FiscalMonth IN (ManagerValue01, ManagerValue02, ManagerValue03, ManagerValue04, ManagerValue05, ManagerValue06, ManagerValue07, ManagerValue08, ManagerValue09, ManagerValue10, ManagerValue11, ManagerValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ManagerValue', 'Month')) mgr + ON + ov.BudgetConfigID = mgr.BudgetConfigID + AND ov.EntityGroupConfigID = mgr.EntityGroupConfigID + AND ov.EntityID = mgr.EntityID + AND ov.DepartmentID = mgr.DepartmentID + AND ov.ServiceLineID = mgr.ServiceLineID + AND ov.PatientClassID = mgr.PatientClassID + AND ov.AgeCohortID = mgr.AgeCohortID + AND ov.MedicalSurgicalID = mgr.MedicalSurgicalID + AND ov.ChargeCodeID = mgr.ChargeCodeID + AND ov.ServiceEntityID = mgr.ServiceEntityID + AND ov.MSDRGID = mgr.MSDRGID + AND ov.UBRevCodeID = mgr.UBRevCodeID + AND ov.PrimaryCPTID = mgr.PrimaryCPTID + AND ov.ServiceProviderID = mgr.ServiceProviderID + AND ov.ServiceProviderSpecialtyID = mgr.ServiceProviderSpecialtyID + AND ov.PerformingProviderID = mgr.PerformingProviderID + AND ov.PerformingProviderSpecialtyID = mgr.PerformingProviderSpecialtyID + AND ov.BillingCPTID = mgr.BillingCPTID + AND ov.UnitTypeID = mgr.UnitTypeID + AND ov.FiscalMonthID = mgr.FiscalMonthID + INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID + + + UNION ALL + + SELECT + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.DepartmentID, + ov.ServiceLineID, + ov.PatientClassID, + ov.AgeCohortID, + ov.MedicalSurgicalID, + ov.ChargeCodeID, + ov.ServiceEntityID, + ov.MSDRGID, + ov.UBRevCodeID, + ov.PrimaryCPTID, + ov.ServiceProviderID, + ov.ServiceProviderSpecialtyID, + ov.PerformingProviderID, + ov.PerformingProviderSpecialtyID, + ov.BillingCPTID, + ov.UnitTypeID, + 12 as TimeClassID, + ov.FiscalMonthID, + bc.FiscalYearID - 1, + ov.InitialValue as OriginalValue, + v.Value, + v.Value as ManagerValue -- Manager value is not different in CV for Projection + FROM ( + -- Unpivot for OriginalValue + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, + cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, + cv.InitialProjection01,cv.InitialProjection02, cv.InitialProjection03, cv.InitialProjection04, cv.InitialProjection05, cv.InitialProjection06, cv.InitialProjection07, cv.InitialProjection08, cv.InitialProjection09, cv.InitialProjection10, cv.InitialProjection11, cv.InitialProjection12 + FROM chargevolume cv + ) cv + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov + INNER JOIN ( + -- Unpivot for Value + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, + ChargeCodeID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, + PerformingProviderID, PerformingProviderSpecialtyID, BillingCPTID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, + cv.ChargeCodeID, cv.ServiceEntityID, cv.MSDRGID, cv.UBRevCodeID, cv.PrimaryCPTID, cv.ServiceProviderID, cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, cv.PerformingProviderSpecialtyID, cv.BillingCPTID, cv.UnitTypeID, + cv.ProjectedValue01, cv.ProjectedValue02, cv.ProjectedValue03, cv.ProjectedValue04, cv.ProjectedValue05, cv.ProjectedValue06, cv.ProjectedValue07, cv.ProjectedValue08, cv.ProjectedValue09, cv.ProjectedValue10, cv.ProjectedValue11, cv.ProjectedValue12 + FROM chargevolume cv + ) cv + UNPIVOT ( Value FOR FiscalMonth IN (ProjectedValue01, ProjectedValue02, ProjectedValue03, ProjectedValue04, ProjectedValue05, ProjectedValue06, ProjectedValue07, ProjectedValue08, ProjectedValue09, ProjectedValue10, ProjectedValue11, ProjectedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectedValue', 'Month')) v + ON + ov.BudgetConfigID = v.BudgetConfigID + AND ov.EntityGroupConfigID = v.EntityGroupConfigID + AND ov.EntityID = v.EntityID + AND ov.DepartmentID = v.DepartmentID + AND ov.ServiceLineID = v.ServiceLineID + AND ov.PatientClassID = v.PatientClassID + AND ov.AgeCohortID = v.AgeCohortID + AND ov.MedicalSurgicalID = v.MedicalSurgicalID + AND ov.ChargeCodeID = v.ChargeCodeID + AND ov.ServiceEntityID = v.ServiceEntityID + AND ov.MSDRGID = v.MSDRGID + AND ov.UBRevCodeID = v.UBRevCodeID + AND ov.PrimaryCPTID = v.PrimaryCPTID + AND ov.ServiceProviderID = v.ServiceProviderID + AND ov.ServiceProviderSpecialtyID = v.ServiceProviderSpecialtyID + AND ov.PerformingProviderID = v.PerformingProviderID + AND ov.PerformingProviderSpecialtyID = v.PerformingProviderSpecialtyID + AND ov.BillingCPTID = v.BillingCPTID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID + INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID + ) cvData +GO + + +--------------------------------------------- + +-- fp.viewFactEncounterHistory_Unpivoted_source +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-02-28 BW JAZZ-49992 Updated for new data model, use [fp].[ServiceLineEncounter] +*************************************************************/ + +CREATE VIEW [fp].[viewFactEncounterHistory_Unpivoted_source] +AS +-- Unpivot for PriorYearActual +SELECT data.ServiceLineEncounterID, data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.PatientClassID, data.ServiceLineID, data.ServiceLineRollupID, +data.AgeCohortID, data.MedicalSurgicalID, data.PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, data.UnitTypeID, +1 as TimeClassID, bc.FiscalYearID - 2 as FiscalYearID, data.FiscalMonthID, data.Value +FROM ( + SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, PatientClassID, ServiceLineID, ServiceLineRollupID, AgeCohortID, MedicalSurgicalID, PayorID, + PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT fe.*, hist.PriorYearActualValue01, hist.PriorYearActualValue02, hist.PriorYearActualValue03, hist.PriorYearActualValue04, hist.PriorYearActualValue05, hist.PriorYearActualValue06, + hist.PriorYearActualValue07, hist.PriorYearActualValue08, hist.PriorYearActualValue09, hist.PriorYearActualValue10, hist.PriorYearActualValue11, hist.PriorYearActualValue12 + FROM [fp].[ServiceLineEncounter] fe + INNER JOIN [fp].[ServiceLineEncounterHistory] hist ON fe.ServiceLineEncounterID = hist.ServiceLineEncounterID ) fe + UNPIVOT ( Value FOR FiscalMonth IN (PriorYearActualValue01, PriorYearActualValue02, PriorYearActualValue03, PriorYearActualValue04, PriorYearActualValue05, PriorYearActualValue06, + PriorYearActualValue07, PriorYearActualValue08, PriorYearActualValue09, PriorYearActualValue10, PriorYearActualValue11, PriorYearActualValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'PriorYearActualValue', 'Month')) data + INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID + +UNION ALL + +-- Unpivot for ActualYTD +SELECT data.ServiceLineEncounterID, data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.PatientClassID, data.ServiceLineID, data.ServiceLineRollupID, +data.AgeCohortID, data.MedicalSurgicalID, data.PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, data.UnitTypeID, +1 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value +FROM ( + SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, PatientClassID, ServiceLineID, ServiceLineRollupID, AgeCohortID, MedicalSurgicalID, PayorID, + PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT fe.*, hist.ActualYTDValue01, hist.ActualYTDValue02, hist.ActualYTDValue03, hist.ActualYTDValue04, hist.ActualYTDValue05, hist.ActualYTDValue06, hist.ActualYTDValue07, + hist.ActualYTDValue08, hist.ActualYTDValue09, hist.ActualYTDValue10, hist.ActualYTDValue11, hist.ActualYTDValue12 + FROM [fp].[ServiceLineEncounter] fe + INNER JOIN [fp].[ServiceLineEncounterHistory] hist ON fe.ServiceLineEncounterID = hist.ServiceLineEncounterID ) fe + UNPIVOT ( Value FOR FiscalMonth IN (ActualYTDValue01, ActualYTDValue02, ActualYTDValue03, ActualYTDValue04, ActualYTDValue05, ActualYTDValue06, ActualYTDValue07, ActualYTDValue08, + ActualYTDValue09, ActualYTDValue10, ActualYTDValue11, ActualYTDValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ActualYTDValue', 'Month')) data + INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID + +UNION ALL + +-- Unpivot for CurrentYearBudget +SELECT data.ServiceLineEncounterID, data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.PatientClassID, data.ServiceLineID, data.ServiceLineRollupID, +data.AgeCohortID, data.MedicalSurgicalID, data.PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, data.UnitTypeID, 2 as TimeClassID, +bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value +FROM ( + SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, PatientClassID, ServiceLineID, ServiceLineRollupID, AgeCohortID, MedicalSurgicalID, PayorID, + PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT fe.*, hist.CurrentYearBudget01, hist.CurrentYearBudget02, hist.CurrentYearBudget03, hist.CurrentYearBudget04, hist.CurrentYearBudget05, hist.CurrentYearBudget06, + hist.CurrentYearBudget07, hist.CurrentYearBudget08, hist.CurrentYearBudget09, hist.CurrentYearBudget10, hist.CurrentYearBudget11, hist.CurrentYearBudget12 + FROM [fp].[ServiceLineEncounter] fe + INNER JOIN [fp].[ServiceLineEncounterHistory] hist ON fe.ServiceLineEncounterID = hist.ServiceLineEncounterID ) fe + UNPIVOT ( Value FOR FiscalMonth IN (CurrentYearBudget01, CurrentYearBudget02, CurrentYearBudget03, CurrentYearBudget04, CurrentYearBudget05, CurrentYearBudget06, CurrentYearBudget07, + CurrentYearBudget08, CurrentYearBudget09, CurrentYearBudget10, CurrentYearBudget11, CurrentYearBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'CurrentYearBudget', 'Month')) data + INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFactEncounter_Unpivoted_BaselineOnly +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-07-18 MY JAZZ-37944 Initial +** 2 2023-02-28 BW JAZZ-49992 Updated for new data model, use [fp].[ServiceLineEncounter] +** 3 2023-05-22 BW JAZZ-55391 Just a reapply +*************************************************************/ +CREATE VIEW [fp].[viewFactEncounter_Unpivoted_BaselineOnly] +AS +SELECT + ov.ServiceLineEncounterID, + ov.BudgetConfigID, + ov.EntityID, + ov.DepartmentID, + ov.ServiceLineID, + ov.ServiceLineRollupID, + ov.PatientClassID, + ov.AgeCohortID, + ov.MedicalSurgicalID, + ov.PayorID, + ov.PayorGroupID, + ov.MSDRGID, + ov.CPTID, + ov.ProviderID, + ov.PhysicianSpecialtyID, + ov.UnitTypeID, + 2 as TimeClassID, + ov.FiscalMonthID, + bc.FiscalYearID, + ov.InitialValue as OriginalValue +FROM ( + -- Unpivot for OriginalValue + SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, PatientClassID, ServiceLineID, ServiceLineRollupID, AgeCohortID, MedicalSurgicalID, PayorID, + PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT cv.ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, PatientClassID, ServiceLineID, ServiceLineRollupID, AgeCohortID, MedicalSurgicalID, PayorID, + PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, + InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12 + FROM [fp].[ServiceLineEncounter] cv + ) cv + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov +INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFactEncounter_Unpivoted_source +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-12-14 MD JAZZ-47250 Remove projection inner join on budget phase ID 3 +** 2 2023-02-28 BW JAZZ-49992 Updated for new data model, use [fp].[ServiceLineEncounter] +*************************************************************/ + +CREATE VIEW [fp].[viewFactEncounter_Unpivoted_source] +AS +SELECT + ov.ServiceLineEncounterID, + ov.BudgetConfigID, + ov.EntityID, + ov.DepartmentID, + ov.ServiceLineID, + ov.ServiceLineRollupID, + ov.PatientClassID, + ov.AgeCohortID, + ov.MedicalSurgicalID, + ov.PayorID, + ov.PayorGroupID, + ov.MSDRGID, + ov.CPTID, + ov.ProviderID, + ov.PhysicianSpecialtyID, + ov.UnitTypeID, + 2 as TimeClassID, + ov.FiscalMonthID, + bc.FiscalYearID, + ov.InitialValue as OriginalValue, + v.Value, + mgrv.Value as ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, PatientClassID, ServiceLineID, ServiceLineRollupID, AgeCohortID, MedicalSurgicalID, PayorID, + PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT cv.* + FROM [fp].[ServiceLineEncounter] cv ) cv + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f + + + + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, PatientClassID, ServiceLineID, ServiceLineRollupID, AgeCohortID, MedicalSurgicalID, PayorID, + PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT cv.*, cv.TargetLockType AS LockType, cv.TargetAdjusted01 AS AdjustedValue01, cv.TargetAdjusted02 AS AdjustedValue02, cv.TargetAdjusted03 AS AdjustedValue03, cv.TargetAdjusted04 AS AdjustedValue04, cv.TargetAdjusted05 AS AdjustedValue05, cv.TargetAdjusted06 AS AdjustedValue06, cv.TargetAdjusted07 AS AdjustedValue07, + cv.TargetAdjusted08 AS AdjustedValue08, cv.TargetAdjusted09 AS AdjustedValue09, cv.TargetAdjusted10 AS AdjustedValue10, cv.TargetAdjusted11 AS AdjustedValue11, cv.TargetAdjusted12 AS AdjustedValue12 + FROM [fp].[ServiceLineEncounter] cv + ) cv + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, + AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.BudgetConfigID = v.BudgetConfigID + AND ov.EntityID = v.EntityID + AND ov.DepartmentID = v.DepartmentID + AND ov.ServiceLineID = v.ServiceLineID + AND ov.ServiceLineRollupID = v.ServiceLineRollupID + AND ov.PatientClassID = v.PatientClassID + AND ov.AgeCohortID = v.AgeCohortID + AND ov.MedicalSurgicalID = v.MedicalSurgicalID + AND ov.PayorID = v.PayorID + AND ov.PayorGroupID = v.PayorGroupID + AND ov.MSDRGID = v.MSDRGID + AND ov.CPTID = v.CPTID + AND ov.ProviderID = v.ProviderID + AND ov.PhysicianSpecialtyID = v.PhysicianSpecialtyID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN ( + -- Unpivot for Manager Value + SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, PatientClassID, ServiceLineID, ServiceLineRollupID, AgeCohortID, MedicalSurgicalID, PayorID, + PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT cv.*, cv.BudgetLockType AS LockType, cv.BudgetAdjusted01 AS AdjustedValue01, cv.BudgetAdjusted02 AS AdjustedValue02, cv.BudgetAdjusted03 AS AdjustedValue03, cv.BudgetAdjusted04 AS AdjustedValue04, cv.BudgetAdjusted05 AS AdjustedValue05, cv.BudgetAdjusted06 AS AdjustedValue06, cv.BudgetAdjusted07 AS AdjustedValue07, + cv.BudgetAdjusted08 AS AdjustedValue08, cv.BudgetAdjusted09 AS AdjustedValue09, cv.BudgetAdjusted10 AS AdjustedValue10, cv.BudgetAdjusted11 AS AdjustedValue11, cv.BudgetAdjusted12 AS AdjustedValue12 + FROM [fp].[ServiceLineEncounter] cv + ) sle + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.EntityID = mgrv.EntityID + AND ov.DepartmentID = mgrv.DepartmentID + AND ov.ServiceLineID = mgrv.ServiceLineID + AND ov.ServiceLineRollupID = mgrv.ServiceLineRollupID + AND ov.PatientClassID = mgrv.PatientClassID + AND ov.AgeCohortID = mgrv.AgeCohortID + AND ov.MedicalSurgicalID = mgrv.MedicalSurgicalID + AND ov.PayorID = mgrv.PayorID + AND ov.PayorGroupID = mgrv.PayorGroupID + AND ov.MSDRGID = mgrv.MSDRGID + AND ov.CPTID = mgrv.CPTID + AND ov.ProviderID = mgrv.ProviderID + AND ov.PhysicianSpecialtyID = mgrv.PhysicianSpecialtyID + AND ov.UnitTypeID = mgrv.UnitTypeID + AND ov.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID + +UNION ALL + +SELECT + ov.ServiceLineEncounterID, + ov.BudgetConfigID, + ov.EntityID, + ov.DepartmentID, + ov.ServiceLineID, + ov.ServiceLineRollupID, + ov.PatientClassID, + ov.AgeCohortID, + ov.MedicalSurgicalID, + ov.PayorID, + ov.PayorGroupID, + ov.MSDRGID, + ov.CPTID, + ov.ProviderID, + ov.PhysicianSpecialtyID, + ov.UnitTypeID, + 12 as TimeClassID, + ov.FiscalMonthID, + bc.FiscalYearID - 1, + ov.InitialValue as OriginalValue, + v.Value, + 0 as ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, PatientClassID, ServiceLineID, ServiceLineRollupID, AgeCohortID, MedicalSurgicalID, PayorID, + PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT cv.* + FROM [fp].[ServiceLineEncounter] cv ) cv + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, + InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, PatientClassID, ServiceLineID, ServiceLineRollupID, AgeCohortID, MedicalSurgicalID, PayorID, + PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT cv.*, cv.ProjectionLockType AS LockType, cv.ProjectionAdjusted01 AS AdjustedValue01, cv.ProjectionAdjusted02 AS AdjustedValue02, cv.ProjectionAdjusted03 AS AdjustedValue03, cv.ProjectionAdjusted04 AS AdjustedValue04, cv.ProjectionAdjusted05 AS AdjustedValue05, cv.ProjectionAdjusted06 AS AdjustedValue06, cv.ProjectionAdjusted07 AS AdjustedValue07, + cv.ProjectionAdjusted08 AS AdjustedValue08, cv.ProjectionAdjusted09 AS AdjustedValue09, cv.ProjectionAdjusted10 AS AdjustedValue10, cv.ProjectionAdjusted11 AS AdjustedValue11, cv.ProjectionAdjusted12 AS AdjustedValue12 + FROM [fp].[ServiceLineEncounter] cv + ) cv + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, + AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.BudgetConfigID = v.BudgetConfigID + AND ov.EntityID = v.EntityID + AND ov.DepartmentID = v.DepartmentID + AND ov.ServiceLineID = v.ServiceLineID + AND ov.ServiceLineRollupID = v.ServiceLineRollupID + AND ov.PatientClassID = v.PatientClassID + AND ov.AgeCohortID = v.AgeCohortID + AND ov.MedicalSurgicalID = v.MedicalSurgicalID + AND ov.PayorID = v.PayorID + AND ov.PayorGroupID = v.PayorGroupID + AND ov.MSDRGID = v.MSDRGID + AND ov.CPTID = v.CPTID + AND ov.ProviderID = v.ProviderID + AND ov.PhysicianSpecialtyID = v.PhysicianSpecialtyID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFactGeneralLedgerBudget_HistoryViewer +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 7-20-2023 MY JAZZ-54785 Update to new structure +*************************************************************/ +CREATE VIEW fp.viewFactGeneralLedgerBudget_HistoryViewer +AS +SELECT + ov.GeneralLedgerID, + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.DepartmentID, + ov.AccountID, + ov.FinancialReportingID, + ov.APEModelSectionID, + ov.VariabilityID, + 34 AS UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + ov.FiscalMonthID, + LockType, + ov.InitialValue AS OriginalValue, + v.Value, + mgrv.ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, + InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12 + FROM fp.GeneralLedger gl ) gl + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, + TargetLockType AS LockType, + TargetAdjusted01 AS AdjustedValue01, + TargetAdjusted02 AS AdjustedValue02, + TargetAdjusted03 AS AdjustedValue03, + TargetAdjusted04 AS AdjustedValue04, + TargetAdjusted05 AS AdjustedValue05, + TargetAdjusted06 AS AdjustedValue06, + TargetAdjusted07 AS AdjustedValue07, + TargetAdjusted08 AS AdjustedValue08, + TargetAdjusted09 AS AdjustedValue09, + TargetAdjusted10 AS AdjustedValue10, + TargetAdjusted11 AS AdjustedValue11, + TargetAdjusted12 AS AdjustedValue12 + FROM fp.GeneralLedger gl) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.DepartmentID = v.DepartmentID + AND ov.AccountID = v.AccountID + AND ov.BudgetConfigID = v.BudgetConfigID + AND ov.VariabilityID = v.VariabilityID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN ( + -- Unpivot for ManagerValue + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, m.FiscalMonthID, f.Value AS ManagerValue + FROM ( + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, + BudgetLockType AS LockType, + BudgetAdjusted01 AS AdjustedValue01, + BudgetAdjusted02 AS AdjustedValue02, + BudgetAdjusted03 AS AdjustedValue03, + BudgetAdjusted04 AS AdjustedValue04, + BudgetAdjusted05 AS AdjustedValue05, + BudgetAdjusted06 AS AdjustedValue06, + BudgetAdjusted07 AS AdjustedValue07, + BudgetAdjusted08 AS AdjustedValue08, + BudgetAdjusted09 AS AdjustedValue09, + BudgetAdjusted10 AS AdjustedValue10, + BudgetAdjusted11 AS AdjustedValue11, + BudgetAdjusted12 AS AdjustedValue12 + FROM fp.GeneralLedger gl) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON ov.DepartmentID = mgrv.DepartmentID + AND ov.AccountID = mgrv.AccountID + AND ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.VariabilityID = mgrv.VariabilityID + AND ov.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFactGeneralLedgerHistory_Unpivoted +CREATE VIEW fp.viewFactGeneralLedgerHistory_Unpivoted +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-10-26 MD JAZZ-JAZZ-28803 Adding union all for data transfer table +*************************************************************/ +SELECT + rgl.GeneralLedgerID, + rgl.BudgetConfigID, + rgl.EntityGroupConfigID, + rgl.EntityID, + rgl.DepartmentID, + rgl.AccountID, + rgl.FinancialReportingID, + rgl.APEModelSectionID, + rgl.VariabilityID, + rgl.UnitTypeID, + rgl.TimeClassID, + rgl.FiscalYearID, + rgl.FiscalMonthID, + rgl.Value +FROM fp.FactReportGeneralLedgerHistory rgl +WHERE rgl.UnitTypeID = 34 + +UNION ALL + +-- Prior Year Actual and Current Year Budget - data transfer +SELECT + 0 as GeneralLedgerID, + dth.BudgetConfigID, + 0 as EntityGroupConfigID, + dth.EntityID, + dth.DepartmentID, + dth.AccountID, + dth.FinancialReportingID, + 2 as APEModelSectionID, + dth.VariabilityID, + dth.UnitTypeID, + dth.TimeClassID, + dth.FiscalYearID, + dth.FiscalMonthID, + dth.Value +FROM [fp].[FactReportGeneralLedgerHistoryDataTransfer] dth +WHERE dth.TimeClassID in(1, 2) +GO + + +--------------------------------------------- + +-- fp.viewFactGeneralLedgerHistory_Unpivoted_archive +CREATE VIEW fp.viewFactGeneralLedgerHistory_Unpivoted_archive AS SELECT * FROM fp.FactReportGeneralLedgerHistory_archive WHERE UnitTypeID = 34 +GO + + +--------------------------------------------- + +-- fp.viewFactGeneralLedgerHistory_Unpivoted_source +CREATE VIEW [fp].[viewFactGeneralLedgerHistory_Unpivoted_source] +AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-08-11 BK JAZZ-58752 Update for new gl data structure + *************************************************************/ + +SELECT + gl.GeneralLedgerID + ,gl.BudgetConfigID + ,gl.EntityGroupConfigID + ,gl.EntityID + ,gl.DepartmentID + ,gl.AccountID + ,gl.FinancialReportingID + ,gl.APEModelSectionID + ,gl.VariabilityID + ,34 as UnitTypeID + ,TimeClassID + ,bc.FiscalYearID - CASE WHEN IsPriorYear = 1 THEN 2 ELSE 1 END AS FiscalYearID + ,m.FiscalMonthID + ,hist.Value +FROM ( + SELECT hist.GeneralLedgerID, 1 AS TimeClassID, Value, FiscalMonth, CAST(0 as bit) As IsPriorYear + FROM fp.GeneralLedgerHistory hist (READUNCOMMITTED) + CROSS APPLY + (VALUES + (1, ActualYTDValue01), + (2, ActualYTDValue02), + (3, ActualYTDValue03), + (4, ActualYTDValue04), + (5, ActualYTDValue05), + (6, ActualYTDValue06), + (7, ActualYTDValue07), + (8, ActualYTDValue08), + (9, ActualYTDValue09), + (10,ActualYTDValue10), + (11,ActualYTDValue11), + (12,ActualYTDValue12)) X (FiscalMonth,Value) +UNION +SELECT hist.GeneralLedgerID, 2 AS TimeClassID, Value, FiscalMonth, CAST(0 as bit) As IsPriorYear + FROM fp.GeneralLedgerHistory hist (READUNCOMMITTED) + CROSS APPLY + (VALUES + (1, CurrentYearBudget01), + (2, CurrentYearBudget02), + (3, CurrentYearBudget03), + (4, CurrentYearBudget04), + (5, CurrentYearBudget05), + (6, CurrentYearBudget06), + (7, CurrentYearBudget07), + (8, CurrentYearBudget08), + (9, CurrentYearBudget09), + (10,CurrentYearBudget10), + (11,CurrentYearBudget11), + (12,CurrentYearBudget12)) X (FiscalMonth,Value) +UNION +SELECT hist.GeneralLedgerID, 1 AS TimeClassID, Value, FiscalMonth, CAST(1 as bit) As IsPriorYear + FROM fp.GeneralLedgerHistory hist (READUNCOMMITTED) + CROSS APPLY + (VALUES + (1, PriorYearActualValue01), + (2, PriorYearActualValue02), + (3, PriorYearActualValue03), + (4, PriorYearActualValue04), + (5, PriorYearActualValue05), + (6, PriorYearActualValue06), + (7, PriorYearActualValue07), + (8, PriorYearActualValue08), + (9, PriorYearActualValue09), + (10,PriorYearActualValue10), + (11,PriorYearActualValue11), + (12,PriorYearActualValue12)) X (FiscalMonth,Value) ) hist +INNER JOIN fp.GeneralLedger gl (READUNCOMMITTED) ON gl.GeneralLedgerID = hist.GeneralLedgerID + INNER JOIN fw.DimFiscalMonth m ON m.SortOrder = FiscalMonth + INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFactGeneralLedgerProjection_HistoryViewer +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 7-20-2023 MY JAZZ-54785 Update to new structure +*************************************************************/ +CREATE VIEW fp.viewFactGeneralLedgerProjection_HistoryViewer +AS +SELECT + ov.GeneralLedgerID, + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.DepartmentID, + ov.AccountID, + ov.FinancialReportingID, + ov.APEModelSectionID, + ov.VariabilityID, + 34 AS UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID, + ov.FiscalMonthID, + LockType, + ov.InitialValue AS OriginalValue, + v.Value, + v.Value AS ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, + InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12 + FROM fp.GeneralLedger gl ) gl + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, + ProjectionLockType AS LockType, + ProjectionAdjusted01 AS AdjustedValue01, + ProjectionAdjusted02 AS AdjustedValue02, + ProjectionAdjusted03 AS AdjustedValue03, + ProjectionAdjusted04 AS AdjustedValue04, + ProjectionAdjusted05 AS AdjustedValue05, + ProjectionAdjusted06 AS AdjustedValue06, + ProjectionAdjusted07 AS AdjustedValue07, + ProjectionAdjusted08 AS AdjustedValue08, + ProjectionAdjusted09 AS AdjustedValue09, + ProjectionAdjusted10 AS AdjustedValue10, + ProjectionAdjusted11 AS AdjustedValue11, + ProjectionAdjusted12 AS AdjustedValue12 + FROM fp.GeneralLedger gl) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.DepartmentID = v.DepartmentID + AND ov.AccountID = v.AccountID + AND ov.BudgetConfigID = v.BudgetConfigID + AND ov.VariabilityID = v.VariabilityID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFactGeneralLedgerSnapshot_Unpivoted +CREATE VIEW [fp].[viewFactGeneralLedgerSnapshot_Unpivoted] +AS +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2024-11-04 MY JAZZ-77737 Initial +***************************************************************/ + +------------------------------------ +-- This is a copy of fp.viewReportGeneralLedger essentially except cleaned up and adopted for Snapshots. +-- Note: Excluded here is the Data Transfer stuff, +------------------------------------ + +SELECT + rgl.GeneralLedgerID, + rgl.SnapshotID, + rgl.BudgetConfigID, + rgl.EntityGroupConfigID, + rgl.EntityID, + rgl.DepartmentID, + rgl.AccountID, + rgl.FinancialReportingID, + rgl.APEModelSectionID, + rgl.VariabilityID, + rgl.UnitTypeID, + rgl.TimeClassID, + rgl.FiscalYearID, + rgl.FiscalMonthID, + rgl.LockType, + rgl.OriginalValue, + rgl.Value, + rgl.ManagerValue, + rgl.Rate +FROM fp.FactReportGeneralLedgerSnapshot rgl +WHERE rgl.UnitTypeID = 34 + +UNION ALL + +-- UK to US Data transfer queries start here -- + +-- Manager Projection - data transfer +SELECT + 0 as GeneralLedgerID, + dt.SnapshotID, + bc.BudgetConfigID, + 0 as EntityGroupConfigID, + dt.EntityID, + dt.DepartmentID, + dt.AccountID, + dt.FinancialReportingID, + 2 as APEModelSectionID, + dt.VariabilityID, + dt.UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID-1 as FiscalYearID, + dt.FiscalMonthID, + 0 as LockType, + dt.OriginalValue, + dt.Value, + dt.ManagerValue, + dt.Rate +FROM [fp].[FactReportGeneralLedgerDataTransferSnapshot] dt + INNER JOIN fp.BudgetConfig bc on dt.BudgetConfigID = bc.BudgetConfigID +WHERE dt.TimeClassID = 12 + +UNION ALL + +-- Initial Budget - data transfer +SELECT + 0 as GeneralLedgerID, + dt.SnapshotID, + dt.BudgetConfigID, + 0 as EntityGroupConfigID, + dt.EntityID, + dt.DepartmentID, + dt.AccountID, + dt.FinancialReportingID, + 2 as APEModelSectionID, + dt.VariabilityID, + dt.UnitTypeID, + 21 as TimeClassID, + dt.FiscalYearID, + dt.FiscalMonthID, + 0 as LockType, + dt.OriginalValue, + dt.Value, + dt.ManagerValue, + dt.Rate +FROM [fp].[FactReportGeneralLedgerDataTransferSnapshot] dt +WHERE dt.TimeClassID = 2 + +UNION ALL + +-- Manager Budget - data transfer +SELECT + 0 as GeneralLedgerID, + dt.SnapshotID, + dt.BudgetConfigID, + 0 as EntityGroupConfigID, + dt.EntityID, + dt.DepartmentID, + dt.AccountID, + dt.FinancialReportingID, + 2 as APEModelSectionID, + dt.VariabilityID, + dt.UnitTypeID, + 2 as TimeClassID, + dt.FiscalYearID, + dt.FiscalMonthID, + 0 as LockType, + dt.OriginalValue, + dt.Value, + dt.ManagerValue, + dt.Rate +FROM [fp].[FactReportGeneralLedgerDataTransferSnapshot] dt +WHERE dt.TimeClassID = 2 + +UNION ALL + +-- Baseline Budget - data transfer +SELECT + 0 as GeneralLedgerID, + dt.SnapshotID, + dt.BudgetConfigID, + 0 as EntityGroupConfigID, + dt.EntityID, + dt.DepartmentID, + dt.AccountID, + dt.FinancialReportingID, + 2 as APEModelSectionID, + dt.VariabilityID, + dt.UnitTypeID, + 22 as TimeClassID, + dt.FiscalYearID, + dt.FiscalMonthID, + 0 as LockType, + dt.OriginalValue, + dt.Value, + dt.ManagerValue, + dt.Rate +FROM [fp].[FactReportGeneralLedgerDataTransferSnapshot] dt +WHERE dt.TimeClassID = 2 +GO + + +--------------------------------------------- + +-- fp.viewFactGeneralLedger_Snapshot +CREATE VIEW [fp].[viewFactGeneralLedger_Snapshot] +AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2024-10-22 MY JAZZ-77735 Initial Creation + *************************************************************/ + + SELECT + SnapshotID, + GeneralLedgerID, + gl.BudgetConfigID, + gl.EntityGroupConfigID, + gl.EntityID, + gl.DepartmentID, + gl.AccountID, + gl.FinancialReportingID, + gl.APEModelSectionID, + gl.VariabilityID, + 34 as UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + m.FiscalMonthID, + gl.TargetLockType AS LockType, + OriginalValue, Value, ManagerValue, Rate + FROM fp.GeneralLedgerSnapshot gl + CROSS APPLY ( + VALUES + (1,InitialBudget01,TargetAdjusted01,TargetPercentAdjustmentFactor01,BudgetAdjusted01), + (2,InitialBudget02,TargetAdjusted02,TargetPercentAdjustmentFactor02,BudgetAdjusted02), + (3,InitialBudget03,TargetAdjusted03,TargetPercentAdjustmentFactor03,BudgetAdjusted03), + (4,InitialBudget04,TargetAdjusted04,TargetPercentAdjustmentFactor04,BudgetAdjusted04), + (5,InitialBudget05,TargetAdjusted05,TargetPercentAdjustmentFactor05,BudgetAdjusted05), + (6,InitialBudget06,TargetAdjusted06,TargetPercentAdjustmentFactor06,BudgetAdjusted06), + (7,InitialBudget07,TargetAdjusted07,TargetPercentAdjustmentFactor07,BudgetAdjusted07), + (8,InitialBudget08,TargetAdjusted08,TargetPercentAdjustmentFactor08,BudgetAdjusted08), + (9,InitialBudget09,TargetAdjusted09,TargetPercentAdjustmentFactor09,BudgetAdjusted09), + (10,InitialBudget10,TargetAdjusted10,TargetPercentAdjustmentFactor10,BudgetAdjusted10), + (11,InitialBudget11,TargetAdjusted11,TargetPercentAdjustmentFactor11,BudgetAdjusted11), + (12,InitialBudget12,TargetAdjusted12,TargetPercentAdjustmentFactor12,BudgetAdjusted12)) glx (FiscalMonth, OriginalValue,Value, Rate, ManagerValue) +LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = glx.FiscalMonth +INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID + +UNION ALL + SELECT + SnapshotID, + GeneralLedgerID, + gl.BudgetConfigID, + gl.EntityGroupConfigID, + gl.EntityID, + gl.DepartmentID, + gl.AccountID, + gl.FinancialReportingID, + gl.APEModelSectionID, + gl.VariabilityID, + 33 as UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + m.FiscalMonthID, + gl.TargetLockType AS LockType, + OriginalValue, Value, ManagerValue, Rate + FROM fp.GeneralLedgerSnapshot gl + CROSS APPLY ( + VALUES + (1, InitialBudgetDollarsPerUOS01,TargetDollarsPerUOSAdjusted01,BudgetDollarsPerUOSAdjusted01,ProjectionPercentAdjustmentFactor01), + (2, InitialBudgetDollarsPerUOS02,TargetDollarsPerUOSAdjusted02,BudgetDollarsPerUOSAdjusted02,ProjectionPercentAdjustmentFactor02), + (3, InitialBudgetDollarsPerUOS03,TargetDollarsPerUOSAdjusted03,BudgetDollarsPerUOSAdjusted03,ProjectionPercentAdjustmentFactor03), + (4, InitialBudgetDollarsPerUOS04,TargetDollarsPerUOSAdjusted04,BudgetDollarsPerUOSAdjusted04,ProjectionPercentAdjustmentFactor04), + (5, InitialBudgetDollarsPerUOS05,TargetDollarsPerUOSAdjusted05,BudgetDollarsPerUOSAdjusted05,ProjectionPercentAdjustmentFactor05), + (6, InitialBudgetDollarsPerUOS06,TargetDollarsPerUOSAdjusted06,BudgetDollarsPerUOSAdjusted06,ProjectionPercentAdjustmentFactor06), + (7, InitialBudgetDollarsPerUOS07,TargetDollarsPerUOSAdjusted07,BudgetDollarsPerUOSAdjusted07,ProjectionPercentAdjustmentFactor07), + (8, InitialBudgetDollarsPerUOS08,TargetDollarsPerUOSAdjusted08,BudgetDollarsPerUOSAdjusted08,ProjectionPercentAdjustmentFactor08), + (9, InitialBudgetDollarsPerUOS09,TargetDollarsPerUOSAdjusted09,BudgetDollarsPerUOSAdjusted09,ProjectionPercentAdjustmentFactor09), + (10,InitialBudgetDollarsPerUOS10,TargetDollarsPerUOSAdjusted10,BudgetDollarsPerUOSAdjusted10,ProjectionPercentAdjustmentFactor10), + (11,InitialBudgetDollarsPerUOS11,TargetDollarsPerUOSAdjusted11,BudgetDollarsPerUOSAdjusted11,ProjectionPercentAdjustmentFactor11), + (12,InitialBudgetDollarsPerUOS12,TargetDollarsPerUOSAdjusted12,BudgetDollarsPerUOSAdjusted12,ProjectionPercentAdjustmentFactor12)) glx (FiscalMonth, OriginalValue, Value, ManagerValue, Rate) +LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = glx.FiscalMonth +INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID + WHERE gl.VariabilityID = 2 + +UNION ALL + SELECT + SnapshotID, + GeneralLedgerID, + gl.BudgetConfigID, + gl.EntityGroupConfigID, + gl.EntityID, + gl.DepartmentID, + gl.AccountID, + gl.FinancialReportingID, + gl.APEModelSectionID, + gl.VariabilityID, + 34 as UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID-1, + m.FiscalMonthID, + gl.ProjectionLockType AS LockType, + OriginalValue, Value, Value as ManagerValue, Rate + FROM fp.GeneralLedgerSnapshot gl + CROSS APPLY ( + VALUES + (1,InitialProjection01,ProjectionAdjusted01,ProjectionPercentAdjustmentFactor01), + (2,InitialProjection02,ProjectionAdjusted02,ProjectionPercentAdjustmentFactor02), + (3,InitialProjection03,ProjectionAdjusted03,ProjectionPercentAdjustmentFactor03), + (4,InitialProjection04,ProjectionAdjusted04,ProjectionPercentAdjustmentFactor04), + (5,InitialProjection05,ProjectionAdjusted05,ProjectionPercentAdjustmentFactor05), + (6,InitialProjection06,ProjectionAdjusted06,ProjectionPercentAdjustmentFactor06), + (7,InitialProjection07,ProjectionAdjusted07,ProjectionPercentAdjustmentFactor07), + (8,InitialProjection08,ProjectionAdjusted08,ProjectionPercentAdjustmentFactor08), + (9,InitialProjection09,ProjectionAdjusted09,ProjectionPercentAdjustmentFactor09), + (10,InitialProjection10,ProjectionAdjusted10,ProjectionPercentAdjustmentFactor10), + (11,InitialProjection11,ProjectionAdjusted11,ProjectionPercentAdjustmentFactor11), + (12,InitialProjection12,ProjectionAdjusted12,ProjectionPercentAdjustmentFactor12)) glx (FiscalMonth, OriginalValue,Value, Rate) + +LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = glx.FiscalMonth +INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID +UNION ALL + SELECT + SnapshotID, + GeneralLedgerID, + gl.BudgetConfigID, + gl.EntityGroupConfigID, + gl.EntityID, + gl.DepartmentID, + gl.AccountID, + gl.FinancialReportingID, + gl.APEModelSectionID, + gl.VariabilityID, + 33 as UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID-1, + m.FiscalMonthID, + gl.ProjectionLockType AS LockType, + OriginalValue, Value, Value as ManagerValue, Rate + FROM fp.GeneralLedgerSnapshot gl + CROSS APPLY ( + VALUES + (1, InitialProjectionDollarsPerUOS01,ProjectionDollarsPerUOSAdjusted01,ProjectionPercentAdjustmentFactor01), + (2, InitialProjectionDollarsPerUOS02,ProjectionDollarsPerUOSAdjusted02,ProjectionPercentAdjustmentFactor02), + (3, InitialProjectionDollarsPerUOS03,ProjectionDollarsPerUOSAdjusted03,ProjectionPercentAdjustmentFactor03), + (4, InitialProjectionDollarsPerUOS04,ProjectionDollarsPerUOSAdjusted04,ProjectionPercentAdjustmentFactor04), + (5, InitialProjectionDollarsPerUOS05,ProjectionDollarsPerUOSAdjusted05,ProjectionPercentAdjustmentFactor05), + (6, InitialProjectionDollarsPerUOS06,ProjectionDollarsPerUOSAdjusted06,ProjectionPercentAdjustmentFactor06), + (7, InitialProjectionDollarsPerUOS07,ProjectionDollarsPerUOSAdjusted07,ProjectionPercentAdjustmentFactor07), + (8, InitialProjectionDollarsPerUOS08,ProjectionDollarsPerUOSAdjusted08,ProjectionPercentAdjustmentFactor08), + (9, InitialProjectionDollarsPerUOS09,ProjectionDollarsPerUOSAdjusted09,ProjectionPercentAdjustmentFactor09), + (10,InitialProjectionDollarsPerUOS10,ProjectionDollarsPerUOSAdjusted10,ProjectionPercentAdjustmentFactor10), + (11,InitialProjectionDollarsPerUOS11,ProjectionDollarsPerUOSAdjusted11,ProjectionPercentAdjustmentFactor11), + (12,InitialProjectionDollarsPerUOS12,ProjectionDollarsPerUOSAdjusted12,ProjectionPercentAdjustmentFactor12)) glx (FiscalMonth, OriginalValue,Value, Rate) + + LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = glx.FiscalMonth +INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID + WHERE gl.VariabilityID = 2 +GO + + +--------------------------------------------- + +-- fp.viewFactGeneralLedger_Unpivoted +CREATE VIEW [fp].[viewFactGeneralLedger_Unpivoted] +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-10-26 MD JAZZ-JAZZ-28803 Adding union all for data transfer table +*************************************************************/ + +SELECT + rgl.GeneralLedgerID, + rgl.BudgetConfigID, + rgl.EntityGroupConfigID, + rgl.EntityID, + rgl.DepartmentID, + rgl.AccountID, + rgl.FinancialReportingID, + rgl.APEModelSectionID, + rgl.VariabilityID, + rgl.UnitTypeID, + rgl.TimeClassID, + rgl.FiscalYearID, + rgl.FiscalMonthID, + rgl.LockType, + rgl.OriginalValue, + rgl.Value, + rgl.ManagerValue, + rgl.Rate +FROM fp.FactReportGeneralLedger rgl +WHERE rgl.UnitTypeID = 34 + +UNION ALL + +-- Data transfer queries start here -- + +-- Manager Projection - data transfer +SELECT + 0 as GeneralLedgerID, + bc.BudgetConfigID, + 0 as EntityGroupConfigID, + dt.EntityID, + dt.DepartmentID, + dt.AccountID, + dt.FinancialReportingID, + 2 as APEModelSectionID, + dt.VariabilityID, + dt.UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID-1 as FiscalYearID, + dt.FiscalMonthID, + 0 as LockType, + dt.OriginalValue, + dt.Value, + dt.ManagerValue, + dt.Rate +FROM [fp].[FactReportGeneralLedgerDataTransfer] dt +INNER JOIN fp.BudgetConfig bc on dt.BudgetConfigID = bc.BudgetConfigID +WHERE dt.TimeClassID=12 + +UNION ALL + +-- Initial Budget - data transfer +SELECT + 0 as GeneralLedgerID, + dt.BudgetConfigID, + 0 as EntityGroupConfigID, + dt.EntityID, + dt.DepartmentID, + dt.AccountID, + dt.FinancialReportingID, + 2 as APEModelSectionID, + dt.VariabilityID, + dt.UnitTypeID, + 21 as TimeClassID, + dt.FiscalYearID, + dt.FiscalMonthID, + 0 as LockType, + dt.OriginalValue, + dt.Value, + dt.ManagerValue, + dt.Rate +FROM [fp].[FactReportGeneralLedgerDataTransfer] dt +WHERE dt.TimeClassID=2 + +UNION ALL + +-- Manager Budget - data transfer +SELECT + 0 as GeneralLedgerID, + dt.BudgetConfigID, + 0 as EntityGroupConfigID, + dt.EntityID, + dt.DepartmentID, + dt.AccountID, + dt.FinancialReportingID, + 2 as APEModelSectionID, + dt.VariabilityID, + dt.UnitTypeID, + 2 as TimeClassID, + dt.FiscalYearID, + dt.FiscalMonthID, + 0 as LockType, + dt.OriginalValue, + dt.Value, + dt.ManagerValue, + dt.Rate +FROM [fp].[FactReportGeneralLedgerDataTransfer] dt +WHERE dt.TimeClassID=2 + +UNION ALL + +-- Baseline Budget - data transfer +SELECT + 0 as GeneralLedgerID, + dt.BudgetConfigID, + 0 as EntityGroupConfigID, + dt.EntityID, + dt.DepartmentID, + dt.AccountID, + dt.FinancialReportingID, + 2 as APEModelSectionID, + dt.VariabilityID, + dt.UnitTypeID, + 22 as TimeClassID, + dt.FiscalYearID, + dt.FiscalMonthID, + 0 as LockType, + dt.OriginalValue, + dt.Value, + dt.ManagerValue, + dt.Rate +FROM [fp].[FactReportGeneralLedgerDataTransfer] dt +WHERE dt.TimeClassID=2 +GO + + +--------------------------------------------- + +-- fp.viewFactGeneralLedger_Unpivoted_archive +CREATE VIEW fp.viewFactGeneralLedger_Unpivoted_archive AS SELECT * FROM fp.FactReportGeneralLedger_archive WHERE UnitTypeID = 34 +GO + + +--------------------------------------------- + +-- fp.viewFactGeneralLedger_Unpivoted_source +CREATE VIEW [fp].[viewFactGeneralLedger_Unpivoted_source] +AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-08-11 BK JAZZ-58752 Update for new gl data structure + *************************************************************/ + + SELECT GeneralLedgerID, + gl.BudgetConfigID, + gl.EntityGroupConfigID, + gl.EntityID, + gl.DepartmentID, + gl.AccountID, + gl.FinancialReportingID, + gl.APEModelSectionID, + gl.VariabilityID, + 34 as UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + m.FiscalMonthID, + gl.TargetLockType AS LockType, + OriginalValue, Value, ManagerValue, Rate + FROM fp.GeneralLedger gl + CROSS APPLY ( + VALUES + (1,InitialBudget01,TargetAdjusted01,TargetPercentAdjustmentFactor01,BudgetAdjusted01), + (2,InitialBudget02,TargetAdjusted02,TargetPercentAdjustmentFactor02,BudgetAdjusted02), + (3,InitialBudget03,TargetAdjusted03,TargetPercentAdjustmentFactor03,BudgetAdjusted03), + (4,InitialBudget04,TargetAdjusted04,TargetPercentAdjustmentFactor04,BudgetAdjusted04), + (5,InitialBudget05,TargetAdjusted05,TargetPercentAdjustmentFactor05,BudgetAdjusted05), + (6,InitialBudget06,TargetAdjusted06,TargetPercentAdjustmentFactor06,BudgetAdjusted06), + (7,InitialBudget07,TargetAdjusted07,TargetPercentAdjustmentFactor07,BudgetAdjusted07), + (8,InitialBudget08,TargetAdjusted08,TargetPercentAdjustmentFactor08,BudgetAdjusted08), + (9,InitialBudget09,TargetAdjusted09,TargetPercentAdjustmentFactor09,BudgetAdjusted09), + (10,InitialBudget10,TargetAdjusted10,TargetPercentAdjustmentFactor10,BudgetAdjusted10), + (11,InitialBudget11,TargetAdjusted11,TargetPercentAdjustmentFactor11,BudgetAdjusted11), + (12,InitialBudget12,TargetAdjusted12,TargetPercentAdjustmentFactor12,BudgetAdjusted12)) glx (FiscalMonth, OriginalValue,Value, Rate, ManagerValue) +LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = glx.FiscalMonth +INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID + +UNION ALL + SELECT GeneralLedgerID, + gl.BudgetConfigID, + gl.EntityGroupConfigID, + gl.EntityID, + gl.DepartmentID, + gl.AccountID, + gl.FinancialReportingID, + gl.APEModelSectionID, + gl.VariabilityID, + 33 as UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + m.FiscalMonthID, + gl.TargetLockType AS LockType, + OriginalValue, Value, ManagerValue, Rate + FROM fp.GeneralLedger gl + CROSS APPLY ( + VALUES + (1, InitialBudgetDollarsPerUOS01,TargetDollarsPerUOSAdjusted01,BudgetDollarsPerUOSAdjusted01,ProjectionPercentAdjustmentFactor01), + (2, InitialBudgetDollarsPerUOS02,TargetDollarsPerUOSAdjusted02,BudgetDollarsPerUOSAdjusted02,ProjectionPercentAdjustmentFactor02), + (3, InitialBudgetDollarsPerUOS03,TargetDollarsPerUOSAdjusted03,BudgetDollarsPerUOSAdjusted03,ProjectionPercentAdjustmentFactor03), + (4, InitialBudgetDollarsPerUOS04,TargetDollarsPerUOSAdjusted04,BudgetDollarsPerUOSAdjusted04,ProjectionPercentAdjustmentFactor04), + (5, InitialBudgetDollarsPerUOS05,TargetDollarsPerUOSAdjusted05,BudgetDollarsPerUOSAdjusted05,ProjectionPercentAdjustmentFactor05), + (6, InitialBudgetDollarsPerUOS06,TargetDollarsPerUOSAdjusted06,BudgetDollarsPerUOSAdjusted06,ProjectionPercentAdjustmentFactor06), + (7, InitialBudgetDollarsPerUOS07,TargetDollarsPerUOSAdjusted07,BudgetDollarsPerUOSAdjusted07,ProjectionPercentAdjustmentFactor07), + (8, InitialBudgetDollarsPerUOS08,TargetDollarsPerUOSAdjusted08,BudgetDollarsPerUOSAdjusted08,ProjectionPercentAdjustmentFactor08), + (9, InitialBudgetDollarsPerUOS09,TargetDollarsPerUOSAdjusted09,BudgetDollarsPerUOSAdjusted09,ProjectionPercentAdjustmentFactor09), + (10,InitialBudgetDollarsPerUOS10,TargetDollarsPerUOSAdjusted10,BudgetDollarsPerUOSAdjusted10,ProjectionPercentAdjustmentFactor10), + (11,InitialBudgetDollarsPerUOS11,TargetDollarsPerUOSAdjusted11,BudgetDollarsPerUOSAdjusted11,ProjectionPercentAdjustmentFactor11), + (12,InitialBudgetDollarsPerUOS12,TargetDollarsPerUOSAdjusted12,BudgetDollarsPerUOSAdjusted12,ProjectionPercentAdjustmentFactor12)) glx (FiscalMonth, OriginalValue, Value, ManagerValue, Rate) +LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = glx.FiscalMonth +INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID + WHERE gl.VariabilityID = 2 + +UNION ALL + SELECT GeneralLedgerID, + gl.BudgetConfigID, + gl.EntityGroupConfigID, + gl.EntityID, + gl.DepartmentID, + gl.AccountID, + gl.FinancialReportingID, + gl.APEModelSectionID, + gl.VariabilityID, + 34 as UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID-1, + m.FiscalMonthID, + gl.ProjectionLockType AS LockType, + OriginalValue, Value, Value as ManagerValue, Rate + FROM fp.GeneralLedger gl + CROSS APPLY ( + VALUES + (1,InitialProjection01,ProjectionAdjusted01,ProjectionPercentAdjustmentFactor01), + (2,InitialProjection02,ProjectionAdjusted02,ProjectionPercentAdjustmentFactor02), + (3,InitialProjection03,ProjectionAdjusted03,ProjectionPercentAdjustmentFactor03), + (4,InitialProjection04,ProjectionAdjusted04,ProjectionPercentAdjustmentFactor04), + (5,InitialProjection05,ProjectionAdjusted05,ProjectionPercentAdjustmentFactor05), + (6,InitialProjection06,ProjectionAdjusted06,ProjectionPercentAdjustmentFactor06), + (7,InitialProjection07,ProjectionAdjusted07,ProjectionPercentAdjustmentFactor07), + (8,InitialProjection08,ProjectionAdjusted08,ProjectionPercentAdjustmentFactor08), + (9,InitialProjection09,ProjectionAdjusted09,ProjectionPercentAdjustmentFactor09), + (10,InitialProjection10,ProjectionAdjusted10,ProjectionPercentAdjustmentFactor10), + (11,InitialProjection11,ProjectionAdjusted11,ProjectionPercentAdjustmentFactor11), + (12,InitialProjection12,ProjectionAdjusted12,ProjectionPercentAdjustmentFactor12)) glx (FiscalMonth, OriginalValue,Value, Rate) + +LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = glx.FiscalMonth +INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID +UNION ALL + SELECT GeneralLedgerID, + gl.BudgetConfigID, + gl.EntityGroupConfigID, + gl.EntityID, + gl.DepartmentID, + gl.AccountID, + gl.FinancialReportingID, + gl.APEModelSectionID, + gl.VariabilityID, + 33 as UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID-1, + m.FiscalMonthID, + gl.ProjectionLockType AS LockType, + OriginalValue, Value, Value as ManagerValue, Rate + FROM fp.GeneralLedger gl + CROSS APPLY ( + VALUES + (1, InitialProjectionDollarsPerUOS01,ProjectionDollarsPerUOSAdjusted01,ProjectionPercentAdjustmentFactor01), + (2, InitialProjectionDollarsPerUOS02,ProjectionDollarsPerUOSAdjusted02,ProjectionPercentAdjustmentFactor02), + (3, InitialProjectionDollarsPerUOS03,ProjectionDollarsPerUOSAdjusted03,ProjectionPercentAdjustmentFactor03), + (4, InitialProjectionDollarsPerUOS04,ProjectionDollarsPerUOSAdjusted04,ProjectionPercentAdjustmentFactor04), + (5, InitialProjectionDollarsPerUOS05,ProjectionDollarsPerUOSAdjusted05,ProjectionPercentAdjustmentFactor05), + (6, InitialProjectionDollarsPerUOS06,ProjectionDollarsPerUOSAdjusted06,ProjectionPercentAdjustmentFactor06), + (7, InitialProjectionDollarsPerUOS07,ProjectionDollarsPerUOSAdjusted07,ProjectionPercentAdjustmentFactor07), + (8, InitialProjectionDollarsPerUOS08,ProjectionDollarsPerUOSAdjusted08,ProjectionPercentAdjustmentFactor08), + (9, InitialProjectionDollarsPerUOS09,ProjectionDollarsPerUOSAdjusted09,ProjectionPercentAdjustmentFactor09), + (10,InitialProjectionDollarsPerUOS10,ProjectionDollarsPerUOSAdjusted10,ProjectionPercentAdjustmentFactor10), + (11,InitialProjectionDollarsPerUOS11,ProjectionDollarsPerUOSAdjusted11,ProjectionPercentAdjustmentFactor11), + (12,InitialProjectionDollarsPerUOS12,ProjectionDollarsPerUOSAdjusted12,ProjectionPercentAdjustmentFactor12)) glx (FiscalMonth, OriginalValue,Value, Rate) + + LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = glx.FiscalMonth +INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID + WHERE gl.VariabilityID = 2 +GO + + +--------------------------------------------- + +-- fp.viewFactReimbursementBudget_HistoryViewer +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-16-50 MY JAZZ-32944 Initial +*************************************************************/ +CREATE VIEW fp.viewFactReimbursementBudget_HistoryViewer +AS + SELECT + ov.ReimbursementChargesID AS ReimbursementID, + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.PatientClassID, + ov.ServiceLineID, + ov.ServiceLineRollupID, + ov.MedicalSurgicalID, + ov.PayorID, + ov.PayorGroupID, + ov.MSDRGID, + ov.PrimaryCPTID, + ov.UBRevCodeID, + 6 AS SubsectionID, + 34 as UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + ov.FiscalMonthID, + ov.InitialValue AS OriginalValue, + mgrv.ManagerValue + FROM ( + -- Unpivot for OriginalValue + SELECT ReimbursementChargesID, BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, UBRevCodeID, 34 AS UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT gl.* + FROM [fp].[FactReimbursementCharges] gl ) gl + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudgetNetReimbursement01, InitialBudgetNetReimbursement02, InitialBudgetNetReimbursement03, InitialBudgetNetReimbursement04, InitialBudgetNetReimbursement05, InitialBudgetNetReimbursement06, + InitialBudgetNetReimbursement07, InitialBudgetNetReimbursement08, InitialBudgetNetReimbursement09, InitialBudgetNetReimbursement10, InitialBudgetNetReimbursement11, InitialBudgetNetReimbursement12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudgetNetReimbursement', 'Month')) ov + INNER JOIN ( + -- Unpivot for ManagerValue + SELECT ReimbursementChargesID, BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, UBRevCodeID, 34 AS UnitTypeID, m.FiscalMonthID, f.NetReimbursementValue AS ManagerValue + FROM ( + SELECT gl.*, bdgt.AdjustedNetReimbursementValue01, bdgt.AdjustedNetReimbursementValue02, bdgt.AdjustedNetReimbursementValue03, bdgt.AdjustedNetReimbursementValue04, bdgt.AdjustedNetReimbursementValue05, bdgt.AdjustedNetReimbursementValue06, + bdgt.AdjustedNetReimbursementValue07, bdgt.AdjustedNetReimbursementValue08, bdgt.AdjustedNetReimbursementValue09, bdgt.AdjustedNetReimbursementValue10, bdgt.AdjustedNetReimbursementValue11, bdgt.AdjustedNetReimbursementValue12 + FROM [fp].[FactReimbursementCharges] gl + INNER JOIN [fp].[FactReimbursementChargesBudget] bdgt ON gl.ReimbursementChargesID = bdgt.ReimbursementChargesID + WHERE bdgt.BudgetPhaseID = 3 + ) gl + UNPIVOT ( NetReimbursementValue FOR FiscalMonth IN (AdjustedNetReimbursementValue01, AdjustedNetReimbursementValue02, AdjustedNetReimbursementValue03, AdjustedNetReimbursementValue04, AdjustedNetReimbursementValue05, AdjustedNetReimbursementValue06, + AdjustedNetReimbursementValue07, AdjustedNetReimbursementValue08, AdjustedNetReimbursementValue09, AdjustedNetReimbursementValue10, AdjustedNetReimbursementValue11, AdjustedNetReimbursementValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedNetReimbursementValue', 'Month')) mgrv + ON ov.EntityID = mgrv.EntityID + AND ov.PatientClassID = mgrv.PatientClassID + AND ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.ServiceLineID = mgrv.ServiceLineID + AND ov.ServiceLineRollupID = mgrv.ServiceLineRollupID + AND ov.MedicalSurgicalID = mgrv.MedicalSurgicalID + AND ov.PayorID = mgrv.PayorID + AND ov.PayorGroupID = mgrv.PayorGroupID + AND ov.MSDRGID = mgrv.MSDRGID + AND ov.PrimaryCPTID = mgrv.PrimaryCPTID + AND ov.UBRevCodeID = mgrv.UBRevCodeID + AND ov.UnitTypeID = mgrv.UnitTypeID + AND ov.FiscalMonthID = mgrv.FiscalMonthID + INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID + UNION ALL + SELECT + ov.ReimbursementEncounterID AS ReimbursementID, + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.PatientClassID, + ov.ServiceLineID, + ov.ServiceLineRollupID, + ov.MedicalSurgicalID, + ov.PayorID, + ov.PayorGroupID, + ov.MSDRGID, + ov.PrimaryCPTID, + ov.UBRevCodeID, + 5 AS SubsectionID, + 34 as UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + ov.FiscalMonthID, + ov.InitialValue AS OriginalValue, + mgrv.ManagerValue + FROM ( + -- Unpivot for OriginalValue + SELECT ReimbursementEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID AS PrimaryCPTID, 0 AS UBRevCodeID, 34 AS UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT gl.* + FROM [fp].[FactReimbursementEncounter] gl ) gl + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudgetNetReimbursement01, InitialBudgetNetReimbursement02, InitialBudgetNetReimbursement03, InitialBudgetNetReimbursement04, InitialBudgetNetReimbursement05, InitialBudgetNetReimbursement06, + InitialBudgetNetReimbursement07, InitialBudgetNetReimbursement08, InitialBudgetNetReimbursement09, InitialBudgetNetReimbursement10, InitialBudgetNetReimbursement11, InitialBudgetNetReimbursement12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudgetNetReimbursement', 'Month')) ov + INNER JOIN ( + -- Unpivot for ManagerValue + SELECT ReimbursementEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID AS PrimaryCPTID, 0 AS UBRevCodeID, 34 AS UnitTypeID, m.FiscalMonthID, f.NetReimbursementValue AS ManagerValue + FROM ( + SELECT gl.*, bdgt.AdjustedNetReimbursementValue01, bdgt.AdjustedNetReimbursementValue02, bdgt.AdjustedNetReimbursementValue03, bdgt.AdjustedNetReimbursementValue04, bdgt.AdjustedNetReimbursementValue05, bdgt.AdjustedNetReimbursementValue06, + bdgt.AdjustedNetReimbursementValue07, bdgt.AdjustedNetReimbursementValue08, bdgt.AdjustedNetReimbursementValue09, bdgt.AdjustedNetReimbursementValue10, bdgt.AdjustedNetReimbursementValue11, bdgt.AdjustedNetReimbursementValue12 + FROM [fp].[FactReimbursementEncounter] gl + INNER JOIN [fp].[FactReimbursementEncounterBudget] bdgt ON gl.ReimbursementEncounterID = bdgt.ReimbursementEncounterID + WHERE bdgt.BudgetPhaseID = 3 + ) gl + UNPIVOT ( NetReimbursementValue FOR FiscalMonth IN (AdjustedNetReimbursementValue01, AdjustedNetReimbursementValue02, AdjustedNetReimbursementValue03, AdjustedNetReimbursementValue04, AdjustedNetReimbursementValue05, AdjustedNetReimbursementValue06, + AdjustedNetReimbursementValue07, AdjustedNetReimbursementValue08, AdjustedNetReimbursementValue09, AdjustedNetReimbursementValue10, AdjustedNetReimbursementValue11, AdjustedNetReimbursementValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedNetReimbursementValue', 'Month')) mgrv + ON ov.EntityID = mgrv.EntityID + AND ov.PatientClassID = mgrv.PatientClassID + AND ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.ServiceLineID = mgrv.ServiceLineID + AND ov.ServiceLineRollupID = mgrv.ServiceLineRollupID + AND ov.MedicalSurgicalID = mgrv.MedicalSurgicalID + AND ov.PayorID = mgrv.PayorID + AND ov.PayorGroupID = mgrv.PayorGroupID + AND ov.MSDRGID = mgrv.MSDRGID + AND ov.PrimaryCPTID = mgrv.PrimaryCPTID + AND ov.UBRevCodeID = mgrv.UBRevCodeID + AND ov.UnitTypeID = mgrv.UnitTypeID + AND ov.FiscalMonthID = mgrv.FiscalMonthID + INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFactReimbursementBudget_repo +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-08-31 MD JAZZ-59398 Remove filter to only pull budget + *******************************************************/ +CREATE VIEW [fp].[viewFactReimbursementBudget_repo] +AS + SELECT + budg.RowID, + budg.ReimbursementChargesID AS ReimbursementID, + budg.BudgetPhaseID, + frc.BudgetConfigID, + frc.EntityID, + frc.PatientClassID, + frc.ServiceLineID, + frc.ServiceLineRollupID, + frc.PayorID, + frc.PayorGroupID, + frc.MedicalSurgicalID, + frc.MSDRGID, + frc.PrimaryCPTID AS CPTID, + frc.UBRevCodeID, + budg.LockFlag, + budg.LockType, + CAST(2 AS TINYINT) AS TimeClassID, + 6 AS SubsectionID, -- Charges + + budg.AdjustedNetAsPercentOfCharge01 AS RateAdjustedValue01, + budg.AdjustedNetAsPercentOfCharge02 AS RateAdjustedValue02, + budg.AdjustedNetAsPercentOfCharge03 AS RateAdjustedValue03, + budg.AdjustedNetAsPercentOfCharge04 AS RateAdjustedValue04, + budg.AdjustedNetAsPercentOfCharge05 AS RateAdjustedValue05, + budg.AdjustedNetAsPercentOfCharge06 AS RateAdjustedValue06, + budg.AdjustedNetAsPercentOfCharge07 AS RateAdjustedValue07, + budg.AdjustedNetAsPercentOfCharge08 AS RateAdjustedValue08, + budg.AdjustedNetAsPercentOfCharge09 AS RateAdjustedValue09, + budg.AdjustedNetAsPercentOfCharge10 AS RateAdjustedValue10, + budg.AdjustedNetAsPercentOfCharge11 AS RateAdjustedValue11, + budg.AdjustedNetAsPercentOfCharge12 AS RateAdjustedValue12, + + budg.AdjustedChargeDollars01 AS VolumeAdjustedValue01, + budg.AdjustedChargeDollars02 AS VolumeAdjustedValue02, + budg.AdjustedChargeDollars03 AS VolumeAdjustedValue03, + budg.AdjustedChargeDollars04 AS VolumeAdjustedValue04, + budg.AdjustedChargeDollars05 AS VolumeAdjustedValue05, + budg.AdjustedChargeDollars06 AS VolumeAdjustedValue06, + budg.AdjustedChargeDollars07 AS VolumeAdjustedValue07, + budg.AdjustedChargeDollars08 AS VolumeAdjustedValue08, + budg.AdjustedChargeDollars09 AS VolumeAdjustedValue09, + budg.AdjustedChargeDollars10 AS VolumeAdjustedValue10, + budg.AdjustedChargeDollars11 AS VolumeAdjustedValue11, + budg.AdjustedChargeDollars12 AS VolumeAdjustedValue12, + + budg.AdjustedNetReimbursementValue01 AS NetReimbursementValue01, + budg.AdjustedNetReimbursementValue02 AS NetReimbursementValue02, + budg.AdjustedNetReimbursementValue03 AS NetReimbursementValue03, + budg.AdjustedNetReimbursementValue04 AS NetReimbursementValue04, + budg.AdjustedNetReimbursementValue05 AS NetReimbursementValue05, + budg.AdjustedNetReimbursementValue06 AS NetReimbursementValue06, + budg.AdjustedNetReimbursementValue07 AS NetReimbursementValue07, + budg.AdjustedNetReimbursementValue08 AS NetReimbursementValue08, + budg.AdjustedNetReimbursementValue09 AS NetReimbursementValue09, + budg.AdjustedNetReimbursementValue10 AS NetReimbursementValue10, + budg.AdjustedNetReimbursementValue11 AS NetReimbursementValue11, + budg.AdjustedNetReimbursementValue12 AS NetReimbursementValue12 + FROM fp.FactReimbursementCharges frc + INNER JOIN fp.FactReimbursementChargesBudget budg ON frc.ReimbursementChargesID = budg.ReimbursementChargesID + UNION ALL + SELECT + budg.RowID, + budg.ReimbursementEncounterID AS ReimbursementID, + budg.BudgetPhaseID, + frc.BudgetConfigID, + frc.EntityID, + frc.PatientClassID, + frc.ServiceLineID, + frc.ServiceLineRollupID, + frc.PayorID, + frc.PayorGroupID, + frc.MedicalSurgicalID, + frc.MSDRGID, + frc.CPTID, + 0 AS UBRevCodeID, + budg.LockFlag, + budg.LockType, + CAST(2 AS TINYINT) AS TimeClassID, + 5 AS SubsectionID, -- Encounters + + budg.AdjustedNetPerEncounterValue01 AS RateAdjustedValue01, + budg.AdjustedNetPerEncounterValue02 AS RateAdjustedValue02, + budg.AdjustedNetPerEncounterValue03 AS RateAdjustedValue03, + budg.AdjustedNetPerEncounterValue04 AS RateAdjustedValue04, + budg.AdjustedNetPerEncounterValue05 AS RateAdjustedValue05, + budg.AdjustedNetPerEncounterValue06 AS RateAdjustedValue06, + budg.AdjustedNetPerEncounterValue07 AS RateAdjustedValue07, + budg.AdjustedNetPerEncounterValue08 AS RateAdjustedValue08, + budg.AdjustedNetPerEncounterValue09 AS RateAdjustedValue09, + budg.AdjustedNetPerEncounterValue10 AS RateAdjustedValue10, + budg.AdjustedNetPerEncounterValue11 AS RateAdjustedValue11, + budg.AdjustedNetPerEncounterValue12 AS RateAdjustedValue12, + + budg.AdjustedEncounters01 AS VolumeAdjustedValue01, + budg.AdjustedEncounters02 AS VolumeAdjustedValue02, + budg.AdjustedEncounters03 AS VolumeAdjustedValue03, + budg.AdjustedEncounters04 AS VolumeAdjustedValue04, + budg.AdjustedEncounters05 AS VolumeAdjustedValue05, + budg.AdjustedEncounters06 AS VolumeAdjustedValue06, + budg.AdjustedEncounters07 AS VolumeAdjustedValue07, + budg.AdjustedEncounters08 AS VolumeAdjustedValue08, + budg.AdjustedEncounters09 AS VolumeAdjustedValue09, + budg.AdjustedEncounters10 AS VolumeAdjustedValue10, + budg.AdjustedEncounters11 AS VolumeAdjustedValue11, + budg.AdjustedEncounters12 AS VolumeAdjustedValue12, + + budg.AdjustedNetReimbursementValue01 AS NetReimbursementValue01, + budg.AdjustedNetReimbursementValue02 AS NetReimbursementValue02, + budg.AdjustedNetReimbursementValue03 AS NetReimbursementValue03, + budg.AdjustedNetReimbursementValue04 AS NetReimbursementValue04, + budg.AdjustedNetReimbursementValue05 AS NetReimbursementValue05, + budg.AdjustedNetReimbursementValue06 AS NetReimbursementValue06, + budg.AdjustedNetReimbursementValue07 AS NetReimbursementValue07, + budg.AdjustedNetReimbursementValue08 AS NetReimbursementValue08, + budg.AdjustedNetReimbursementValue09 AS NetReimbursementValue09, + budg.AdjustedNetReimbursementValue10 AS NetReimbursementValue10, + budg.AdjustedNetReimbursementValue11 AS NetReimbursementValue11, + budg.AdjustedNetReimbursementValue12 AS NetReimbursementValue12 + FROM fp.FactReimbursementEncounter frc + INNER JOIN fp.FactReimbursementEncounterBudget budg ON frc.ReimbursementEncounterID = budg.ReimbursementEncounterID +GO + + +--------------------------------------------- + +-- fp.viewFactReimbursementChargesHistory_Unpivoted_source +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-10-13 MD JAZZ-32897 Adding union all for data transfer table +*************************************************************/ +CREATE VIEW fp.viewFactReimbursementChargesHistory_Unpivoted_source +AS +SELECT + frc.BudgetConfigID, + frc.EntityGroupConfigID, + frc.EntityID, + frc.PatientClassID, + frc.ServiceLineID, + frc.ServiceLineRollupID, + frc.MedicalSurgicalID, + frc.PayorID, + frc.PayorGroupID, + frc.MSDRGID, + frc.PrimaryCPTID, + 1 AS TimeClassID, + bc.FiscalYearID - 2 AS FiscalYearID, + sum(frch.PriorYearActualNetReimbursementValue01) AS NetReimbursementValue01, + sum(frch.PriorYearActualNetReimbursementValue02) AS NetReimbursementValue02, + sum(frch.PriorYearActualNetReimbursementValue03) AS NetReimbursementValue03, + sum(frch.PriorYearActualNetReimbursementValue04) AS NetReimbursementValue04, + sum(frch.PriorYearActualNetReimbursementValue05) AS NetReimbursementValue05, + sum(frch.PriorYearActualNetReimbursementValue06) AS NetReimbursementValue06, + sum(frch.PriorYearActualNetReimbursementValue07) AS NetReimbursementValue07, + sum(frch.PriorYearActualNetReimbursementValue08) AS NetReimbursementValue08, + sum(frch.PriorYearActualNetReimbursementValue09) AS NetReimbursementValue09, + sum(frch.PriorYearActualNetReimbursementValue10) AS NetReimbursementValue10, + sum(frch.PriorYearActualNetReimbursementValue11) AS NetReimbursementValue11, + sum(frch.PriorYearActualNetReimbursementValue12) AS NetReimbursementValue12, + sum(frch.PriorYearActualChargeDollars01) AS ChargeDollarsValue01, + sum(frch.PriorYearActualChargeDollars02) AS ChargeDollarsValue02, + sum(frch.PriorYearActualChargeDollars03) AS ChargeDollarsValue03, + sum(frch.PriorYearActualChargeDollars04) AS ChargeDollarsValue04, + sum(frch.PriorYearActualChargeDollars05) AS ChargeDollarsValue05, + sum(frch.PriorYearActualChargeDollars06) AS ChargeDollarsValue06, + sum(frch.PriorYearActualChargeDollars07) AS ChargeDollarsValue07, + sum(frch.PriorYearActualChargeDollars08) AS ChargeDollarsValue08, + sum(frch.PriorYearActualChargeDollars09) AS ChargeDollarsValue09, + sum(frch.PriorYearActualChargeDollars10) AS ChargeDollarsValue10, + sum(frch.PriorYearActualChargeDollars11) AS ChargeDollarsValue11, + sum(frch.PriorYearActualChargeDollars12) AS ChargeDollarsValue12 +FROM fp.FactReimbursementCharges frc +JOIN fp.FactReimbursementChargesHistory frch + ON frc.ReimbursementChargesID = frch.ReimbursementChargesID +JOIN fp.BudgetConfig bc on frc.BudgetConfigID = bc.BudgetConfigID +GROUP BY + frc.BudgetConfigID, + frc.EntityGroupConfigID, + frc.EntityID, + frc.PatientClassID, + frc.ServiceLineID, + frc.ServiceLineRollupID, + frc.MedicalSurgicalID, + frc.PayorID, + frc.PayorGroupID, + frc.MSDRGID, + frc.PrimaryCPTID, + bc.FiscalYearID +GO + + +--------------------------------------------- + +-- fp.viewFactReimbursementCharges_Pivoted +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-03-01 BW JAZZ-33273 Adding net reimbursement calc'd columns for PriorYearActual, Budget, and Projection. + ** 2 2022-03-15 BW JAZZ-33273 Adding rate columns +*************************************************************/ + + +CREATE VIEW [fp].[viewFactReimbursementCharges_Pivoted] +AS +SELECT + frc.ReimbursementChargesID, + frc.BudgetConfigID, + frc.EntityGroupConfigID, + frc.EntityID, + frc.PatientClassID, + frc.ServiceLineID, + frc.ServiceLineRollupID, + frc.MedicalSurgicalID, + frc.PayorID, + frc.PayorGroupID, + frc.MSDRGID, + frc.PrimaryCPTID, + frc.UBRevCodeID, + + fbdgt.LockType as BudgetLockType, + fbdgt.LockFlag as BudgetLockFlag, + fproj.LockType as ProjectionLockType, + fproj.LockFlag as ProjectionLockFlag, + + CASE WHEN dbdgt.LockType = 7 THEN 1 ELSE 0 END AS BudgetAdjustmentLockFlag, + CASE WHEN fbdgt.LockType = 7 THEN 1 ELSE 0 END AS TargetAdjustmentLockFlag, + CASE WHEN dproj.LockType = 7 THEN 1 ELSE 0 END AS ProjectionAdjustmentLockFlag, + + fbdgt.AdjustedChargeDollarsTotal, + dbdgt.AdjustedChargeDollarsTotal as ManagerAdjustedChargeDollarsTotal, + + fproj.AdjustedChargeDollarsTotal as AdjustedProjectionValueTotal, + dproj.AdjustedChargeDollarsTotal as ManagerAdjustedChargeDollarsProjectionTotal, + + hist.PriorYearActualChargeDollarsTotal as PriorYearActualChargeDollarsTotal, + hist.ActualYTDChargeDollarsTotal as ActualYTDValueTotal, + hist.CurrentYearBudgetChargeDollarsTotal as CurrentYearBudgetTotal, + + frc.InitialBudgetChargeDollarsTotal, + frc.InitialProjectionChargeDollarsTotal, + + dbdgt.AdjustedChargeDollars01 AS ManagerAdjustedChargeDollars01, dbdgt.AdjustedChargeDollars02 AS ManagerAdjustedChargeDollars02, + dbdgt.AdjustedChargeDollars03 AS ManagerAdjustedChargeDollars03, dbdgt.AdjustedChargeDollars04 AS ManagerAdjustedChargeDollars04, + dbdgt.AdjustedChargeDollars05 AS ManagerAdjustedChargeDollars05, dbdgt.AdjustedChargeDollars06 AS ManagerAdjustedChargeDollars06, + dbdgt.AdjustedChargeDollars07 AS ManagerAdjustedChargeDollars07, dbdgt.AdjustedChargeDollars08 AS ManagerAdjustedChargeDollars08, + dbdgt.AdjustedChargeDollars09 AS ManagerAdjustedChargeDollars09, dbdgt.AdjustedChargeDollars10 AS ManagerAdjustedChargeDollars10, + dbdgt.AdjustedChargeDollars11 AS ManagerAdjustedChargeDollars11, dbdgt.AdjustedChargeDollars12 AS ManagerAdjustedChargeDollars12, + + fbdgt.AdjustedChargeDollars01, fbdgt.AdjustedChargeDollars02, fbdgt.AdjustedChargeDollars03, fbdgt.AdjustedChargeDollars04, + fbdgt.AdjustedChargeDollars05, fbdgt.AdjustedChargeDollars06, fbdgt.AdjustedChargeDollars07, fbdgt.AdjustedChargeDollars08, + fbdgt.AdjustedChargeDollars09, fbdgt.AdjustedChargeDollars10, fbdgt.AdjustedChargeDollars11, fbdgt.AdjustedChargeDollars12, + + fproj.AdjustedChargeDollars01 as AdjustedProjectionValue01, fproj.AdjustedChargeDollars02 as AdjustedProjectionValue02, + fproj.AdjustedChargeDollars03 as AdjustedProjectionValue03, fproj.AdjustedChargeDollars04 as AdjustedProjectionValue04, + fproj.AdjustedChargeDollars05 as AdjustedProjectionValue05, fproj.AdjustedChargeDollars06 as AdjustedProjectionValue06, + fproj.AdjustedChargeDollars07 as AdjustedProjectionValue07, fproj.AdjustedChargeDollars08 as AdjustedProjectionValue08, + fproj.AdjustedChargeDollars09 as AdjustedProjectionValue09, fproj.AdjustedChargeDollars10 as AdjustedProjectionValue10, + fproj.AdjustedChargeDollars11 as AdjustedProjectionValue11, fproj.AdjustedChargeDollars12 as AdjustedProjectionValue12, + + dproj.AdjustedChargeDollars01 as ManagerAdjustedProjectionValue01, dproj.AdjustedChargeDollars02 as ManagerAdjustedProjectionValue02, + dproj.AdjustedChargeDollars03 as ManagerAdjustedProjectionValue03, dproj.AdjustedChargeDollars04 as ManagerAdjustedProjectionValue04, + dproj.AdjustedChargeDollars05 as ManagerAdjustedProjectionValue05, dproj.AdjustedChargeDollars06 as ManagerAdjustedProjectionValue06, + dproj.AdjustedChargeDollars07 as ManagerAdjustedProjectionValue07, dproj.AdjustedChargeDollars08 as ManagerAdjustedProjectionValue08, + dproj.AdjustedChargeDollars09 as ManagerAdjustedProjectionValue09, dproj.AdjustedChargeDollars10 as ManagerAdjustedProjectionValue10, + dproj.AdjustedChargeDollars11 as ManagerAdjustedProjectionValue11, dproj.AdjustedChargeDollars12 as ManagerAdjustedProjectionValue12, + + frc.InitialBudgetNetReimbursement01, frc.InitialBudgetNetReimbursement02, frc.InitialBudgetNetReimbursement03, frc.InitialBudgetNetReimbursement04, + frc.InitialBudgetNetReimbursement05, frc.InitialBudgetNetReimbursement06, frc.InitialBudgetNetReimbursement07, frc.InitialBudgetNetReimbursement08, + frc.InitialBudgetNetReimbursement09, frc.InitialBudgetNetReimbursement10, frc.InitialBudgetNetReimbursement11, frc.InitialBudgetNetReimbursement12, + + frc.InitialProjectionNetReimbursement01, frc.InitialProjectionNetReimbursement02, frc.InitialProjectionNetReimbursement03, + frc.InitialProjectionNetReimbursement04, frc.InitialProjectionNetReimbursement05, frc.InitialProjectionNetReimbursement06, + frc.InitialProjectionNetReimbursement07, frc.InitialProjectionNetReimbursement08, frc.InitialProjectionNetReimbursement09, + frc.InitialProjectionNetReimbursement10, frc.InitialProjectionNetReimbursement11, frc.InitialProjectionNetReimbursement12, + + fbdgt.AdjustedNetReimbursementValue01, fbdgt.AdjustedNetReimbursementValue02, fbdgt.AdjustedNetReimbursementValue03, + fbdgt.AdjustedNetReimbursementValue04, fbdgt.AdjustedNetReimbursementValue05, fbdgt.AdjustedNetReimbursementValue06, + fbdgt.AdjustedNetReimbursementValue07, fbdgt.AdjustedNetReimbursementValue08, fbdgt.AdjustedNetReimbursementValue09, + fbdgt.AdjustedNetReimbursementValue10, fbdgt.AdjustedNetReimbursementValue11, fbdgt.AdjustedNetReimbursementValue12, + + dbdgt.AdjustedNetReimbursementValue01 AS ManagerAdjustedNetReimbursementValue01, dbdgt.AdjustedNetReimbursementValue02 AS ManagerAdjustedNetReimbursementValue02, + dbdgt.AdjustedNetReimbursementValue03 AS ManagerAdjustedNetReimbursementValue03, dbdgt.AdjustedNetReimbursementValue04 AS ManagerAdjustedNetReimbursementValue04, + dbdgt.AdjustedNetReimbursementValue05 AS ManagerAdjustedNetReimbursementValue05, dbdgt.AdjustedNetReimbursementValue06 AS ManagerAdjustedNetReimbursementValue06, + dbdgt.AdjustedNetReimbursementValue07 AS ManagerAdjustedNetReimbursementValue07, dbdgt.AdjustedNetReimbursementValue08 AS ManagerAdjustedNetReimbursementValue08, + dbdgt.AdjustedNetReimbursementValue09 AS ManagerAdjustedNetReimbursementValue09, dbdgt.AdjustedNetReimbursementValue10 AS ManagerAdjustedNetReimbursementValue10, + dbdgt.AdjustedNetReimbursementValue11 AS ManagerAdjustedNetReimbursementValue11, dbdgt.AdjustedNetReimbursementValue12 AS ManagerAdjustedNetReimbursementValue12, + + fproj.AdjustedNetReimbursementValue01 AS AdjustedProjectionNetReimbursementValue01, fproj.AdjustedNetReimbursementValue02 AS AdjustedProjectionNetReimbursementValue02, + fproj.AdjustedNetReimbursementValue03 AS AdjustedProjectionNetReimbursementValue03, fproj.AdjustedNetReimbursementValue04 AS AdjustedProjectionNetReimbursementValue04, + fproj.AdjustedNetReimbursementValue05 AS AdjustedProjectionNetReimbursementValue05, fproj.AdjustedNetReimbursementValue06 AS AdjustedProjectionNetReimbursementValue06, + fproj.AdjustedNetReimbursementValue07 AS AdjustedProjectionNetReimbursementValue07, fproj.AdjustedNetReimbursementValue08 AS AdjustedProjectionNetReimbursementValue08, + fproj.AdjustedNetReimbursementValue09 AS AdjustedProjectionNetReimbursementValue09, fproj.AdjustedNetReimbursementValue10 AS AdjustedProjectionNetReimbursementValue10, + fproj.AdjustedNetReimbursementValue11 AS AdjustedProjectionNetReimbursementValue11, fproj.AdjustedNetReimbursementValue12 AS AdjustedProjectionNetReimbursementValue12, + + dproj.AdjustedNetReimbursementValue01 AS ManagerAdjustedProjectionNetReimbursementValue01, dproj.AdjustedNetReimbursementValue02 AS ManagerAdjustedProjectionNetReimbursementValue02, + dproj.AdjustedNetReimbursementValue03 AS ManagerAdjustedProjectionNetReimbursementValue03, dproj.AdjustedNetReimbursementValue04 AS ManagerAdjustedProjectionNetReimbursementValue04, + dproj.AdjustedNetReimbursementValue05 AS ManagerAdjustedProjectionNetReimbursementValue05, dproj.AdjustedNetReimbursementValue06 AS ManagerAdjustedProjectionNetReimbursementValue06, + dproj.AdjustedNetReimbursementValue07 AS ManagerAdjustedProjectionNetReimbursementValue07, dproj.AdjustedNetReimbursementValue08 AS ManagerAdjustedProjectionNetReimbursementValue08, + dproj.AdjustedNetReimbursementValue09 AS ManagerAdjustedProjectionNetReimbursementValue09, dproj.AdjustedNetReimbursementValue10 AS ManagerAdjustedProjectionNetReimbursementValue10, + dproj.AdjustedNetReimbursementValue11 AS ManagerAdjustedProjectionNetReimbursementValue11, dproj.AdjustedNetReimbursementValue12 AS ManagerAdjustedProjectionNetReimbursementValue12, + + dbdgt.AdjustedNetAsPercentOfCharge01 AS ManagerAdjustedNetAsPercentOfCharge01, dbdgt.AdjustedNetAsPercentOfCharge02 AS ManagerAdjustedNetAsPercentOfCharge02, + dbdgt.AdjustedNetAsPercentOfCharge03 AS ManagerAdjustedNetAsPercentOfCharge03, dbdgt.AdjustedNetAsPercentOfCharge04 AS ManagerAdjustedNetAsPercentOfCharge04, + dbdgt.AdjustedNetAsPercentOfCharge05 AS ManagerAdjustedNetAsPercentOfCharge05, dbdgt.AdjustedNetAsPercentOfCharge06 AS ManagerAdjustedNetAsPercentOfCharge06, + dbdgt.AdjustedNetAsPercentOfCharge07 AS ManagerAdjustedNetAsPercentOfCharge07, dbdgt.AdjustedNetAsPercentOfCharge08 AS ManagerAdjustedNetAsPercentOfCharge08, + dbdgt.AdjustedNetAsPercentOfCharge09 AS ManagerAdjustedNetAsPercentOfCharge09, dbdgt.AdjustedNetAsPercentOfCharge10 AS ManagerAdjustedNetAsPercentOfCharge10, + dbdgt.AdjustedNetAsPercentOfCharge11 AS ManagerAdjustedNetAsPercentOfCharge11, dbdgt.AdjustedNetAsPercentOfCharge12 AS ManagerAdjustedNetAsPercentOfCharge12, + + fbdgt.AdjustedNetAsPercentOfCharge01, fbdgt.AdjustedNetAsPercentOfCharge02, fbdgt.AdjustedNetAsPercentOfCharge03, + fbdgt.AdjustedNetAsPercentOfCharge04, fbdgt.AdjustedNetAsPercentOfCharge05, fbdgt.AdjustedNetAsPercentOfCharge06, + fbdgt.AdjustedNetAsPercentOfCharge07, fbdgt.AdjustedNetAsPercentOfCharge08, fbdgt.AdjustedNetAsPercentOfCharge09, + fbdgt.AdjustedNetAsPercentOfCharge10, fbdgt.AdjustedNetAsPercentOfCharge11, fbdgt.AdjustedNetAsPercentOfCharge12, + + fproj.AdjustedNetAsPercentOfCharge01 AS AdjustedProjectionNetAsPercentOfCharge01, fproj.AdjustedNetAsPercentOfCharge02 AS AdjustedProjectionNetAsPercentOfCharge02, + fproj.AdjustedNetAsPercentOfCharge03 AS AdjustedProjectionNetAsPercentOfCharge03, fproj.AdjustedNetAsPercentOfCharge04 AS AdjustedProjectionNetAsPercentOfCharge04, + fproj.AdjustedNetAsPercentOfCharge05 AS AdjustedProjectionNetAsPercentOfCharge05, fproj.AdjustedNetAsPercentOfCharge06 AS AdjustedProjectionNetAsPercentOfCharge06, + fproj.AdjustedNetAsPercentOfCharge07 AS AdjustedProjectionNetAsPercentOfCharge07, fproj.AdjustedNetAsPercentOfCharge08 AS AdjustedProjectionNetAsPercentOfCharge08, + fproj.AdjustedNetAsPercentOfCharge09 AS AdjustedProjectionNetAsPercentOfCharge09, fproj.AdjustedNetAsPercentOfCharge10 AS AdjustedProjectionNetAsPercentOfCharge10, + fproj.AdjustedNetAsPercentOfCharge11 AS AdjustedProjectionNetAsPercentOfCharge11, fproj.AdjustedNetAsPercentOfCharge12 AS AdjustedProjectionNetAsPercentOfCharge12, + + dproj.AdjustedNetAsPercentOfCharge01 AS ManagerAdjustedProjectionNetAsPercentOfCharge01, dproj.AdjustedNetAsPercentOfCharge02 AS ManagerAdjustedProjectionNetAsPercentOfCharge02, + dproj.AdjustedNetAsPercentOfCharge03 AS ManagerAdjustedProjectionNetAsPercentOfCharge03, dproj.AdjustedNetAsPercentOfCharge04 AS ManagerAdjustedProjectionNetAsPercentOfCharge04, + dproj.AdjustedNetAsPercentOfCharge05 AS ManagerAdjustedProjectionNetAsPercentOfCharge05, dproj.AdjustedNetAsPercentOfCharge06 AS ManagerAdjustedProjectionNetAsPercentOfCharge06, + dproj.AdjustedNetAsPercentOfCharge07 AS ManagerAdjustedProjectionNetAsPercentOfCharge07, dproj.AdjustedNetAsPercentOfCharge08 AS ManagerAdjustedProjectionNetAsPercentOfCharge08, + dproj.AdjustedNetAsPercentOfCharge09 AS ManagerAdjustedProjectionNetAsPercentOfCharge09, dproj.AdjustedNetAsPercentOfCharge10 AS ManagerAdjustedProjectionNetAsPercentOfCharge10, + dproj.AdjustedNetAsPercentOfCharge11 AS ManagerAdjustedProjectionNetAsPercentOfCharge11, dproj.AdjustedNetAsPercentOfCharge12 AS ManagerAdjustedProjectionNetAsPercentOfCharge12, + + hist.PriorYearActualNetReimbursementValue01, hist.PriorYearActualNetReimbursementValue02, hist.PriorYearActualNetReimbursementValue03, hist.PriorYearActualNetReimbursementValue04, + hist.PriorYearActualNetReimbursementValue05, hist.PriorYearActualNetReimbursementValue06, hist.PriorYearActualNetReimbursementValue07, hist.PriorYearActualNetReimbursementValue08, + hist.PriorYearActualNetReimbursementValue09, hist.PriorYearActualNetReimbursementValue10, hist.PriorYearActualNetReimbursementValue11, hist.PriorYearActualNetReimbursementValue12, + + hist.ActualYTDNetReimbursementValue01, hist.ActualYTDNetReimbursementValue02, hist.ActualYTDNetReimbursementValue03, hist.ActualYTDNetReimbursementValue04, + hist.ActualYTDNetReimbursementValue05, hist.ActualYTDNetReimbursementValue06, hist.ActualYTDNetReimbursementValue07, hist.ActualYTDNetReimbursementValue08, + hist.ActualYTDNetReimbursementValue09, hist.ActualYTDNetReimbursementValue10, hist.ActualYTDNetReimbursementValue11, hist.ActualYTDNetReimbursementValue12, + + hist.CurrentYearNetReimbursementBudget01, hist.CurrentYearNetReimbursementBudget02, hist.CurrentYearNetReimbursementBudget03, hist.CurrentYearNetReimbursementBudget04, + hist.CurrentYearNetReimbursementBudget05, hist.CurrentYearNetReimbursementBudget06, hist.CurrentYearNetReimbursementBudget07, hist.CurrentYearNetReimbursementBudget08, + hist.CurrentYearNetReimbursementBudget09, hist.CurrentYearNetReimbursementBudget10, hist.CurrentYearNetReimbursementBudget11, hist.CurrentYearNetReimbursementBudget12 + +FROM + fp.FactReimbursementCharges frc + INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON frc.BudgetConfigID = bc.BudgetConfigID + INNER JOIN fp.FactReimbursementChargesBudget fbdgt with (readuncommitted) ON frc.ReimbursementChargesID = fbdgt.ReimbursementChargesID and fbdgt.BudgetPhaseID = 2 + INNER JOIN fp.FactReimbursementChargesBudget dbdgt with (readuncommitted) ON frc.ReimbursementChargesID = dbdgt.ReimbursementChargesID and dbdgt.BudgetPhaseID = 3 + INNER JOIN fp.FactReimbursementChargesProjection fproj with (readuncommitted) ON frc.ReimbursementChargesID = fproj.ReimbursementChargesID and fproj.BudgetPhaseID = 2 + INNER JOIN fp.FactReimbursementChargesProjection dproj with (readuncommitted) ON frc.ReimbursementChargesID = dproj.ReimbursementChargesID and dproj.BudgetPhaseID = 3 + INNER JOIN fp.FactReimbursementChargesHistory hist with (readuncommitted) ON frc.ReimbursementChargesID = hist.ReimbursementChargesID +GO + + +--------------------------------------------- + +-- fp.viewFactReimbursementCharges_Unpivoted_source +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-10-13 MD JAZZ-32897 Adding union all for data transfer table +*************************************************************/ +CREATE VIEW fp.viewFactReimbursementCharges_Unpivoted_source +AS + SELECT + frc.BudgetConfigID, + frc.EntityGroupConfigID, + frc.EntityID, + frc.PatientClassID, + frc.ServiceLineID, + frc.ServiceLineRollupID, + frc.MedicalSurgicalID, + frc.PayorID, + frc.PayorGroupID, + frc.MSDRGID, + frc.PrimaryCPTID, + 2 AS TimeClassID, + bc.FiscalYearID AS FiscalYearID, + sum(frcb.AdjustedNetReimbursementValue01) AS NetReimbursementValue01, + sum(frcb.AdjustedNetReimbursementValue02) AS NetReimbursementValue02, + sum(frcb.AdjustedNetReimbursementValue03) AS NetReimbursementValue03, + sum(frcb.AdjustedNetReimbursementValue04) AS NetReimbursementValue04, + sum(frcb.AdjustedNetReimbursementValue05) AS NetReimbursementValue05, + sum(frcb.AdjustedNetReimbursementValue06) AS NetReimbursementValue06, + sum(frcb.AdjustedNetReimbursementValue07) AS NetReimbursementValue07, + sum(frcb.AdjustedNetReimbursementValue08) AS NetReimbursementValue08, + sum(frcb.AdjustedNetReimbursementValue09) AS NetReimbursementValue09, + sum(frcb.AdjustedNetReimbursementValue10) AS NetReimbursementValue10, + sum(frcb.AdjustedNetReimbursementValue11) AS NetReimbursementValue11, + sum(frcb.AdjustedNetReimbursementValue12) AS NetReimbursementValue12, + sum(frcb.AdjustedChargeDollars01) AS ChargeDollarsValue01, + sum(frcb.AdjustedChargeDollars02) AS ChargeDollarsValue02, + sum(frcb.AdjustedChargeDollars03) AS ChargeDollarsValue03, + sum(frcb.AdjustedChargeDollars04) AS ChargeDollarsValue04, + sum(frcb.AdjustedChargeDollars05) AS ChargeDollarsValue05, + sum(frcb.AdjustedChargeDollars06) AS ChargeDollarsValue06, + sum(frcb.AdjustedChargeDollars07) AS ChargeDollarsValue07, + sum(frcb.AdjustedChargeDollars08) AS ChargeDollarsValue08, + sum(frcb.AdjustedChargeDollars09) AS ChargeDollarsValue09, + sum(frcb.AdjustedChargeDollars10) AS ChargeDollarsValue10, + sum(frcb.AdjustedChargeDollars11) AS ChargeDollarsValue11, + sum(frcb.AdjustedChargeDollars12) AS ChargeDollarsValue12 + FROM fp.FactReimbursementCharges frc + JOIN fp.FactReimbursementChargesBudget frcb + ON frc.ReimbursementChargesID = frcb.ReimbursementChargesID + JOIN fp.BudgetConfig bc on frc.BudgetConfigID = bc.BudgetConfigID + WHERE frcb.BudgetPhaseID = 3 + GROUP BY + frc.BudgetConfigID, + frc.EntityGroupConfigID, + frc.EntityID, + frc.PatientClassID, + frc.ServiceLineID, + frc.ServiceLineRollupID, + frc.MedicalSurgicalID, + frc.PayorID, + frc.PayorGroupID, + frc.MSDRGID, + frc.PrimaryCPTID, + bc.FiscalYearID + + UNION ALL + + SELECT + frc.BudgetConfigID, + frc.EntityGroupConfigID, + frc.EntityID, + frc.PatientClassID, + frc.ServiceLineID, + frc.ServiceLineRollupID, + frc.MedicalSurgicalID, + frc.PayorID, + frc.PayorGroupID, + frc.MSDRGID, + frc.PrimaryCPTID, + 12 AS TimeClassID, + bc.FiscalYearID - 1 AS FiscalYearID, + sum(frcp.AdjustedNetReimbursementValue01) AS NetReimbursementValue01, + sum(frcp.AdjustedNetReimbursementValue02) AS NetReimbursementValue02, + sum(frcp.AdjustedNetReimbursementValue03) AS NetReimbursementValue03, + sum(frcp.AdjustedNetReimbursementValue04) AS NetReimbursementValue04, + sum(frcp.AdjustedNetReimbursementValue05) AS NetReimbursementValue05, + sum(frcp.AdjustedNetReimbursementValue06) AS NetReimbursementValue06, + sum(frcp.AdjustedNetReimbursementValue07) AS NetReimbursementValue07, + sum(frcp.AdjustedNetReimbursementValue08) AS NetReimbursementValue08, + sum(frcp.AdjustedNetReimbursementValue09) AS NetReimbursementValue09, + sum(frcp.AdjustedNetReimbursementValue10) AS NetReimbursementValue10, + sum(frcp.AdjustedNetReimbursementValue11) AS NetReimbursementValue11, + sum(frcp.AdjustedNetReimbursementValue12) AS NetReimbursementValue12, + sum(frcp.AdjustedChargeDollars01) AS ChargeDollarsValue01, + sum(frcp.AdjustedChargeDollars02) AS ChargeDollarsValue02, + sum(frcp.AdjustedChargeDollars03) AS ChargeDollarsValue03, + sum(frcp.AdjustedChargeDollars04) AS ChargeDollarsValue04, + sum(frcp.AdjustedChargeDollars05) AS ChargeDollarsValue05, + sum(frcp.AdjustedChargeDollars06) AS ChargeDollarsValue06, + sum(frcp.AdjustedChargeDollars07) AS ChargeDollarsValue07, + sum(frcp.AdjustedChargeDollars08) AS ChargeDollarsValue08, + sum(frcp.AdjustedChargeDollars09) AS ChargeDollarsValue09, + sum(frcp.AdjustedChargeDollars10) AS ChargeDollarsValue10, + sum(frcp.AdjustedChargeDollars11) AS ChargeDollarsValue11, + sum(frcp.AdjustedChargeDollars12) AS ChargeDollarsValue12 + FROM fp.FactReimbursementCharges frc + JOIN fp.FactReimbursementChargesProjection frcp + ON frc.ReimbursementChargesID = frcp.ReimbursementChargesID + JOIN fp.BudgetConfig bc on frc.BudgetConfigID = bc.BudgetConfigID + WHERE frcp.BudgetPhaseID = 3 + GROUP BY + frc.BudgetConfigID, + frc.EntityGroupConfigID, + frc.EntityID, + frc.PatientClassID, + frc.ServiceLineID, + frc.ServiceLineRollupID, + frc.MedicalSurgicalID, + frc.PayorID, + frc.PayorGroupID, + frc.MSDRGID, + frc.PrimaryCPTID, + bc.FiscalYearID +GO + + +--------------------------------------------- + +-- fp.viewFactReimbursementEncounter_Pivoted +CREATE VIEW [fp].[viewFactReimbursementEncounter_Pivoted] +AS +SELECT + fre.ReimbursementEncounterID, + fre.BudgetConfigID, + fre.EntityGroupConfigID, + fre.EntityID, + fre.PatientClassID, + fre.ServiceLineID, + fre.ServiceLineRollupID, + fre.MedicalSurgicalID, + fre.PayorID, + fre.PayorGroupID, + fre.MSDRGID, + fre.CPTID, + + fbdgt.LockType as BudgetLockType, + fbdgt.LockFlag as BudgetLockFlag, + fproj.LockType as ProjectionLockType, + fproj.LockFlag as ProjectionLockFlag, + + CASE WHEN dbdgt.LockType = 7 THEN 1 ELSE 0 END AS BudgetAdjustmentLockFlag, + CASE WHEN fbdgt.LockType = 7 THEN 1 ELSE 0 END AS TargetAdjustmentLockFlag, + CASE WHEN dproj.LockType = 7 THEN 1 ELSE 0 END AS ProjectionAdjustmentLockFlag, + + fbdgt.AdjustedEncountersTotal, + dbdgt.AdjustedEncountersTotal as ManagerAdjustedEncountersTotal, + + fproj.AdjustedEncountersTotal as AdjustedProjectionEncountersTotal, + dproj.AdjustedEncountersTotal as ManagerAdjustedProjectionEncountersTotal, + + hist.PriorYearActualEncountersTotal as PriorYearActualEncountersTotal, + hist.ActualYTDEncountersTotal as ActualYTDEncountersTotal, + hist.CurrentYearBudgetEncountersTotal as CurrentYearBudgetEncountersTotal, + + fre.InitialBudgetEncountersTotal, + fre.InitialProjectionEncountersTotal, + + dbdgt.AdjustedEncounters01 AS ManagerAdjustedEncounters01, dbdgt.AdjustedEncounters02 AS ManagerAdjustedEncounters02, dbdgt.AdjustedEncounters03 AS ManagerAdjustedEncounters03, + dbdgt.AdjustedEncounters04 AS ManagerAdjustedEncounters04, dbdgt.AdjustedEncounters05 AS ManagerAdjustedEncounters05, dbdgt.AdjustedEncounters06 AS ManagerAdjustedEncounters06, + dbdgt.AdjustedEncounters07 AS ManagerAdjustedEncounters07, dbdgt.AdjustedEncounters08 AS ManagerAdjustedEncounters08, dbdgt.AdjustedEncounters09 AS ManagerAdjustedEncounters09, + dbdgt.AdjustedEncounters10 AS ManagerAdjustedEncounters10, dbdgt.AdjustedEncounters11 AS ManagerAdjustedEncounters11, dbdgt.AdjustedEncounters12 AS ManagerAdjustedEncounters12, + + fbdgt.AdjustedEncounters01, fbdgt.AdjustedEncounters02, fbdgt.AdjustedEncounters03, fbdgt.AdjustedEncounters04, fbdgt.AdjustedEncounters05, fbdgt.AdjustedEncounters06, + fbdgt.AdjustedEncounters07, fbdgt.AdjustedEncounters08, fbdgt.AdjustedEncounters09, fbdgt.AdjustedEncounters10, fbdgt.AdjustedEncounters11, fbdgt.AdjustedEncounters12, + + fproj.AdjustedEncounters01 as AdjustedProjectionEncounters01, fproj.AdjustedEncounters02 as AdjustedProjectionEncounters02, fproj.AdjustedEncounters03 as AdjustedProjectionEncounters03, + fproj.AdjustedEncounters04 as AdjustedProjectionEncounters04, fproj.AdjustedEncounters05 as AdjustedProjectionEncounters05, fproj.AdjustedEncounters06 as AdjustedProjectionEncounters06, + fproj.AdjustedEncounters07 as AdjustedProjectionEncounters07, fproj.AdjustedEncounters08 as AdjustedProjectionEncounters08, fproj.AdjustedEncounters09 as AdjustedProjectionEncounters09, + fproj.AdjustedEncounters10 as AdjustedProjectionEncounters10, fproj.AdjustedEncounters11 as AdjustedProjectionEncounters11, fproj.AdjustedEncounters12 as AdjustedProjectionEncounters12, + + dproj.AdjustedEncounters01 as ManagerAdjustedProjectionEncounters01, dproj.AdjustedEncounters02 as ManagerAdjustedProjectionEncounters02, dproj.AdjustedEncounters03 as ManagerAdjustedProjectionEncounters03, + dproj.AdjustedEncounters04 as ManagerAdjustedProjectionEncounters04, dproj.AdjustedEncounters05 as ManagerAdjustedProjectionEncounters05, dproj.AdjustedEncounters06 as ManagerAdjustedProjectionEncounters06, + dproj.AdjustedEncounters07 as ManagerAdjustedProjectionEncounters07, dproj.AdjustedEncounters08 as ManagerAdjustedProjectionEncounters08, dproj.AdjustedEncounters09 as ManagerAdjustedProjectionEncounters09, + dproj.AdjustedEncounters10 as ManagerAdjustedProjectionEncounters10, dproj.AdjustedEncounters11 as ManagerAdjustedProjectionEncounters11, dproj.AdjustedEncounters12 as ManagerAdjustedProjectionEncounters12, + + fre.InitialBudgetNetReimbursement01, fre.InitialBudgetNetReimbursement02, fre.InitialBudgetNetReimbursement03, fre.InitialBudgetNetReimbursement04, + fre.InitialBudgetNetReimbursement05, fre.InitialBudgetNetReimbursement06, fre.InitialBudgetNetReimbursement07, fre.InitialBudgetNetReimbursement08, + fre.InitialBudgetNetReimbursement09, fre.InitialBudgetNetReimbursement10, fre.InitialBudgetNetReimbursement11, fre.InitialBudgetNetReimbursement12, + + fre.InitialProjectionNetReimbursement01, fre.InitialProjectionNetReimbursement02, fre.InitialProjectionNetReimbursement03, fre.InitialProjectionNetReimbursement04, + fre.InitialProjectionNetReimbursement05, fre.InitialProjectionNetReimbursement06, fre.InitialProjectionNetReimbursement07, fre.InitialProjectionNetReimbursement08, + fre.InitialProjectionNetReimbursement09, fre.InitialProjectionNetReimbursement10, fre.InitialProjectionNetReimbursement11, fre.InitialProjectionNetReimbursement12, + + fbdgt.AdjustedNetReimbursementValue01, fbdgt.AdjustedNetReimbursementValue02, fbdgt.AdjustedNetReimbursementValue03, fbdgt.AdjustedNetReimbursementValue04, + fbdgt.AdjustedNetReimbursementValue05, fbdgt.AdjustedNetReimbursementValue06, fbdgt.AdjustedNetReimbursementValue07, fbdgt.AdjustedNetReimbursementValue08, + fbdgt.AdjustedNetReimbursementValue09, fbdgt.AdjustedNetReimbursementValue10, fbdgt.AdjustedNetReimbursementValue11, fbdgt.AdjustedNetReimbursementValue12, + + dbdgt.AdjustedNetReimbursementValue01 AS ManagerAdjustedNetReimbursementValue01, dbdgt.AdjustedNetReimbursementValue02 AS ManagerAdjustedNetReimbursementValue02, + dbdgt.AdjustedNetReimbursementValue03 AS ManagerAdjustedNetReimbursementValue03, dbdgt.AdjustedNetReimbursementValue04 AS ManagerAdjustedNetReimbursementValue04, + dbdgt.AdjustedNetReimbursementValue05 AS ManagerAdjustedNetReimbursementValue05, dbdgt.AdjustedNetReimbursementValue06 AS ManagerAdjustedNetReimbursementValue06, + dbdgt.AdjustedNetReimbursementValue07 AS ManagerAdjustedNetReimbursementValue07, dbdgt.AdjustedNetReimbursementValue08 AS ManagerAdjustedNetReimbursementValue08, + dbdgt.AdjustedNetReimbursementValue09 AS ManagerAdjustedNetReimbursementValue09, dbdgt.AdjustedNetReimbursementValue10 AS ManagerAdjustedNetReimbursementValue10, + dbdgt.AdjustedNetReimbursementValue11 AS ManagerAdjustedNetReimbursementValue11, dbdgt.AdjustedNetReimbursementValue12 AS ManagerAdjustedNetReimbursementValue12, + + fproj.AdjustedNetReimbursementValue01 AS AdjustedProjectionNetReimbursementValue01, fproj.AdjustedNetReimbursementValue02 AS AdjustedProjectionNetReimbursementValue02, + fproj.AdjustedNetReimbursementValue03 AS AdjustedProjectionNetReimbursementValue03, fproj.AdjustedNetReimbursementValue04 AS AdjustedProjectionNetReimbursementValue04, + fproj.AdjustedNetReimbursementValue05 AS AdjustedProjectionNetReimbursementValue05, fproj.AdjustedNetReimbursementValue06 AS AdjustedProjectionNetReimbursementValue06, + fproj.AdjustedNetReimbursementValue07 AS AdjustedProjectionNetReimbursementValue07, fproj.AdjustedNetReimbursementValue08 AS AdjustedProjectionNetReimbursementValue08, + fproj.AdjustedNetReimbursementValue09 AS AdjustedProjectionNetReimbursementValue09, fproj.AdjustedNetReimbursementValue10 AS AdjustedProjectionNetReimbursementValue10, + fproj.AdjustedNetReimbursementValue11 AS AdjustedProjectionNetReimbursementValue11, fproj.AdjustedNetReimbursementValue12 AS AdjustedProjectionNetReimbursementValue12, + + dproj.AdjustedNetReimbursementValue01 AS ManagerAdjustedProjectionNetReimbursementValue01, dproj.AdjustedNetReimbursementValue02 AS ManagerAdjustedProjectionNetReimbursementValue02, + dproj.AdjustedNetReimbursementValue03 AS ManagerAdjustedProjectionNetReimbursementValue03, dproj.AdjustedNetReimbursementValue04 AS ManagerAdjustedProjectionNetReimbursementValue04, + dproj.AdjustedNetReimbursementValue05 AS ManagerAdjustedProjectionNetReimbursementValue05, dproj.AdjustedNetReimbursementValue06 AS ManagerAdjustedProjectionNetReimbursementValue06, + dproj.AdjustedNetReimbursementValue07 AS ManagerAdjustedProjectionNetReimbursementValue07, dproj.AdjustedNetReimbursementValue08 AS ManagerAdjustedProjectionNetReimbursementValue08, + dproj.AdjustedNetReimbursementValue09 AS ManagerAdjustedProjectionNetReimbursementValue09, dproj.AdjustedNetReimbursementValue10 AS ManagerAdjustedProjectionNetReimbursementValue10, + dproj.AdjustedNetReimbursementValue11 AS ManagerAdjustedProjectionNetReimbursementValue11, dproj.AdjustedNetReimbursementValue12 AS ManagerAdjustedProjectionNetReimbursementValue12, + + fbdgt.AdjustedNetPerEncounterValue01, fbdgt.AdjustedNetPerEncounterValue02, fbdgt.AdjustedNetPerEncounterValue03, fbdgt.AdjustedNetPerEncounterValue04, + fbdgt.AdjustedNetPerEncounterValue05, fbdgt.AdjustedNetPerEncounterValue06, fbdgt.AdjustedNetPerEncounterValue07, fbdgt.AdjustedNetPerEncounterValue08, + fbdgt.AdjustedNetPerEncounterValue09, fbdgt.AdjustedNetPerEncounterValue10, fbdgt.AdjustedNetPerEncounterValue11, fbdgt.AdjustedNetPerEncounterValue12, + + dbdgt.AdjustedNetPerEncounterValue01 AS ManagerAdjustedNetPerEncounterValue01, dbdgt.AdjustedNetPerEncounterValue02 AS ManagerAdjustedNetPerEncounterValue02, + dbdgt.AdjustedNetPerEncounterValue03 AS ManagerAdjustedNetPerEncounterValue03, dbdgt.AdjustedNetPerEncounterValue04 AS ManagerAdjustedNetPerEncounterValue04, + dbdgt.AdjustedNetPerEncounterValue05 AS ManagerAdjustedNetPerEncounterValue05, dbdgt.AdjustedNetPerEncounterValue06 AS ManagerAdjustedNetPerEncounterValue06, + dbdgt.AdjustedNetPerEncounterValue07 AS ManagerAdjustedNetPerEncounterValue07, dbdgt.AdjustedNetPerEncounterValue08 AS ManagerAdjustedNetPerEncounterValue08, + dbdgt.AdjustedNetPerEncounterValue09 AS ManagerAdjustedNetPerEncounterValue09, dbdgt.AdjustedNetPerEncounterValue10 AS ManagerAdjustedNetPerEncounterValue10, + dbdgt.AdjustedNetPerEncounterValue11 AS ManagerAdjustedNetPerEncounterValue11, dbdgt.AdjustedNetPerEncounterValue12 AS ManagerAdjustedNetPerEncounterValue12, + + fproj.AdjustedNetPerEncounterValue01 AS AdjustedProjectionNetPerEncounterValue01, fproj.AdjustedNetPerEncounterValue02 AS AdjustedProjectionNetPerEncounterValue02, + fproj.AdjustedNetPerEncounterValue03 AS AdjustedProjectionNetPerEncounterValue03, fproj.AdjustedNetPerEncounterValue04 AS AdjustedProjectionNetPerEncounterValue04, + fproj.AdjustedNetPerEncounterValue05 AS AdjustedProjectionNetPerEncounterValue05, fproj.AdjustedNetPerEncounterValue06 AS AdjustedProjectionNetPerEncounterValue06, + fproj.AdjustedNetPerEncounterValue07 AS AdjustedProjectionNetPerEncounterValue07, fproj.AdjustedNetPerEncounterValue08 AS AdjustedProjectionNetPerEncounterValue08, + fproj.AdjustedNetPerEncounterValue09 AS AdjustedProjectionNetPerEncounterValue09, fproj.AdjustedNetPerEncounterValue10 AS AdjustedProjectionNetPerEncounterValue10, + fproj.AdjustedNetPerEncounterValue11 AS AdjustedProjectionNetPerEncounterValue11, fproj.AdjustedNetPerEncounterValue12 AS AdjustedProjectionNetPerEncounterValue12, + + dproj.AdjustedNetPerEncounterValue01 AS ManagerAdjustedProjectionNetPerEncounterValue01, dproj.AdjustedNetPerEncounterValue02 AS ManagerAdjustedProjectionNetPerEncounterValue02, + dproj.AdjustedNetPerEncounterValue03 AS ManagerAdjustedProjectionNetPerEncounterValue03, dproj.AdjustedNetPerEncounterValue04 AS ManagerAdjustedProjectionNetPerEncounterValue04, + dproj.AdjustedNetPerEncounterValue05 AS ManagerAdjustedProjectionNetPerEncounterValue05, dproj.AdjustedNetPerEncounterValue06 AS ManagerAdjustedProjectionNetPerEncounterValue06, + dproj.AdjustedNetPerEncounterValue07 AS ManagerAdjustedProjectionNetPerEncounterValue07, dproj.AdjustedNetPerEncounterValue08 AS ManagerAdjustedProjectionNetPerEncounterValue08, + dproj.AdjustedNetPerEncounterValue09 AS ManagerAdjustedProjectionNetPerEncounterValue09, dproj.AdjustedNetPerEncounterValue10 AS ManagerAdjustedProjectionNetPerEncounterValue10, + dproj.AdjustedNetPerEncounterValue11 AS ManagerAdjustedProjectionNetPerEncounterValue11, dproj.AdjustedNetPerEncounterValue12 AS ManagerAdjustedProjectionNetPerEncounterValue12, + + hist.PriorYearActualNetReimbursementValue01, hist.PriorYearActualNetReimbursementValue02, hist.PriorYearActualNetReimbursementValue03, hist.PriorYearActualNetReimbursementValue04, + hist.PriorYearActualNetReimbursementValue05, hist.PriorYearActualNetReimbursementValue06, hist.PriorYearActualNetReimbursementValue07, hist.PriorYearActualNetReimbursementValue08, + hist.PriorYearActualNetReimbursementValue09, hist.PriorYearActualNetReimbursementValue10, hist.PriorYearActualNetReimbursementValue11, hist.PriorYearActualNetReimbursementValue12, + + hist.ActualYTDNetReimbursementValue01, hist.ActualYTDNetReimbursementValue02, hist.ActualYTDNetReimbursementValue03, hist.ActualYTDNetReimbursementValue04, + hist.ActualYTDNetReimbursementValue05, hist.ActualYTDNetReimbursementValue06, hist.ActualYTDNetReimbursementValue07, hist.ActualYTDNetReimbursementValue08, + hist.ActualYTDNetReimbursementValue09, hist.ActualYTDNetReimbursementValue10, hist.ActualYTDNetReimbursementValue11, hist.ActualYTDNetReimbursementValue12, + + hist.CurrentYearNetReimbursementBudget01, hist.CurrentYearNetReimbursementBudget02, hist.CurrentYearNetReimbursementBudget03, hist.CurrentYearNetReimbursementBudget04, + hist.CurrentYearNetReimbursementBudget05, hist.CurrentYearNetReimbursementBudget06, hist.CurrentYearNetReimbursementBudget07, hist.CurrentYearNetReimbursementBudget08, + hist.CurrentYearNetReimbursementBudget09, hist.CurrentYearNetReimbursementBudget10, hist.CurrentYearNetReimbursementBudget11, hist.CurrentYearNetReimbursementBudget12 + + + +FROM + fp.FactReimbursementEncounter fre + INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fre.BudgetConfigID = bc.BudgetConfigID + INNER JOIN fp.FactReimbursementEncounterBudget fbdgt with (readuncommitted) ON fre.ReimbursementEncounterID = fbdgt.ReimbursementEncounterID and fbdgt.BudgetPhaseID = 2 + INNER JOIN fp.FactReimbursementEncounterBudget dbdgt with (readuncommitted) ON fre.ReimbursementEncounterID = dbdgt.ReimbursementEncounterID and dbdgt.BudgetPhaseID = 3 + INNER JOIN fp.FactReimbursementEncounterProjection fproj with (readuncommitted) ON fre.ReimbursementEncounterID = fproj.ReimbursementEncounterID and fproj.BudgetPhaseID = 2 + INNER JOIN fp.FactReimbursementEncounterProjection dproj with (readuncommitted) ON fre.ReimbursementEncounterID = dproj.ReimbursementEncounterID and dproj.BudgetPhaseID = 3 + INNER JOIN fp.FactReimbursementEncounterHistory hist with (readuncommitted) ON fre.ReimbursementEncounterID = hist.ReimbursementEncounterID +GO + + +--------------------------------------------- + +-- fp.viewFactReimbursementEncountersHistory_Unpivoted_source +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-10-13 MD JAZZ-32897 Adding union all for data transfer table +*************************************************************/ +CREATE VIEW fp.viewFactReimbursementEncountersHistory_Unpivoted_source +AS +SELECT + fre.BudgetConfigID, + fre.EntityGroupConfigID, + fre.EntityID, + fre.PatientClassID, + fre.ServiceLineID, + fre.ServiceLineRollupID, + fre.MedicalSurgicalID, + fre.PayorID, + fre.PayorGroupID, + fre.MSDRGID, + fre.CPTID, + 1 AS TimeClassID, + bc.FiscalYearID - 2 AS FiscalYearID, + sum(freh.PriorYearActualNetReimbursementValue01) AS NetReimbursementValue01, + sum(freh.PriorYearActualNetReimbursementValue02) AS NetReimbursementValue02, + sum(freh.PriorYearActualNetReimbursementValue03) AS NetReimbursementValue03, + sum(freh.PriorYearActualNetReimbursementValue04) AS NetReimbursementValue04, + sum(freh.PriorYearActualNetReimbursementValue05) AS NetReimbursementValue05, + sum(freh.PriorYearActualNetReimbursementValue06) AS NetReimbursementValue06, + sum(freh.PriorYearActualNetReimbursementValue07) AS NetReimbursementValue07, + sum(freh.PriorYearActualNetReimbursementValue08) AS NetReimbursementValue08, + sum(freh.PriorYearActualNetReimbursementValue09) AS NetReimbursementValue09, + sum(freh.PriorYearActualNetReimbursementValue10) AS NetReimbursementValue10, + sum(freh.PriorYearActualNetReimbursementValue11) AS NetReimbursementValue11, + sum(freh.PriorYearActualNetReimbursementValue12) AS NetReimbursementValue12 +FROM fp.FactReimbursementEncounter fre +JOIN fp.FactReimbursementEncounterHistory freh + ON fre.ReimbursementEncounterID = freh.ReimbursementEncounterID +JOIN fp.BudgetConfig bc on fre.BudgetConfigID = bc.BudgetConfigID +GROUP BY + fre.BudgetConfigID, + fre.EntityGroupConfigID, + fre.EntityID, + fre.PatientClassID, + fre.ServiceLineID, + fre.ServiceLineRollupID, + fre.MedicalSurgicalID, + fre.PayorID, + fre.PayorGroupID, + fre.MSDRGID, + fre.CPTID, + bc.FiscalYearID +GO + + +--------------------------------------------- + +-- fp.viewFactReimbursementEncounters_Unpivoted_source +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-10-13 MD JAZZ-32897 Adding union all for data transfer table +*************************************************************/ +CREATE VIEW fp.viewFactReimbursementEncounters_Unpivoted_source +AS + SELECT + fre.BudgetConfigID, + fre.EntityGroupConfigID, + fre.EntityID, + fre.PatientClassID, + fre.ServiceLineID, + fre.ServiceLineRollupID, + fre.MedicalSurgicalID, + fre.PayorID, + fre.PayorGroupID, + fre.MSDRGID, + fre.CPTID, + 2 AS TimeClassID, + bc.FiscalYearID AS FiscalYearID, + sum(freb.AdjustedNetReimbursementValue01) AS NetReimbursementValue01, + sum(freb.AdjustedNetReimbursementValue02) AS NetReimbursementValue02, + sum(freb.AdjustedNetReimbursementValue03) AS NetReimbursementValue03, + sum(freb.AdjustedNetReimbursementValue04) AS NetReimbursementValue04, + sum(freb.AdjustedNetReimbursementValue05) AS NetReimbursementValue05, + sum(freb.AdjustedNetReimbursementValue06) AS NetReimbursementValue06, + sum(freb.AdjustedNetReimbursementValue07) AS NetReimbursementValue07, + sum(freb.AdjustedNetReimbursementValue08) AS NetReimbursementValue08, + sum(freb.AdjustedNetReimbursementValue09) AS NetReimbursementValue09, + sum(freb.AdjustedNetReimbursementValue10) AS NetReimbursementValue10, + sum(freb.AdjustedNetReimbursementValue11) AS NetReimbursementValue11, + sum(freb.AdjustedNetReimbursementValue12) AS NetReimbursementValue12 + FROM fp.FactReimbursementEncounter fre + JOIN fp.FactReimbursementEncounterBudget freb + ON fre.ReimbursementEncounterID = freb.ReimbursementEncounterID + JOIN fp.BudgetConfig bc on fre.BudgetConfigID = bc.BudgetConfigID + WHERE freb.BudgetPhaseID = 3 + GROUP BY + fre.BudgetConfigID, + fre.EntityGroupConfigID, + fre.EntityID, + fre.PatientClassID, + fre.ServiceLineID, + fre.ServiceLineRollupID, + fre.MedicalSurgicalID, + fre.PayorID, + fre.PayorGroupID, + fre.MSDRGID, + fre.CPTID, + bc.FiscalYearID + + UNION ALL + + SELECT + fre.BudgetConfigID, + fre.EntityGroupConfigID, + fre.EntityID, + fre.PatientClassID, + fre.ServiceLineID, + fre.ServiceLineRollupID, + fre.MedicalSurgicalID, + fre.PayorID, + fre.PayorGroupID, + fre.MSDRGID, + fre.CPTID, + 12 AS TimeClassID, + bc.FiscalYearID - 1 AS FiscalYearID, + sum(frep.AdjustedNetReimbursementValue01) AS NetReimbursementValue01, + sum(frep.AdjustedNetReimbursementValue02) AS NetReimbursementValue02, + sum(frep.AdjustedNetReimbursementValue03) AS NetReimbursementValue03, + sum(frep.AdjustedNetReimbursementValue04) AS NetReimbursementValue04, + sum(frep.AdjustedNetReimbursementValue05) AS NetReimbursementValue05, + sum(frep.AdjustedNetReimbursementValue06) AS NetReimbursementValue06, + sum(frep.AdjustedNetReimbursementValue07) AS NetReimbursementValue07, + sum(frep.AdjustedNetReimbursementValue08) AS NetReimbursementValue08, + sum(frep.AdjustedNetReimbursementValue09) AS NetReimbursementValue09, + sum(frep.AdjustedNetReimbursementValue10) AS NetReimbursementValue10, + sum(frep.AdjustedNetReimbursementValue11) AS NetReimbursementValue11, + sum(frep.AdjustedNetReimbursementValue12) AS NetReimbursementValue12 + FROM fp.FactReimbursementEncounter fre + JOIN fp.FactReimbursementEncounterProjection frep + ON fre.ReimbursementEncounterID = frep.ReimbursementEncounterID + JOIN fp.BudgetConfig bc on fre.BudgetConfigID = bc.BudgetConfigID + WHERE frep.BudgetPhaseID = 3 + GROUP BY + fre.BudgetConfigID, + fre.EntityGroupConfigID, + fre.EntityID, + fre.PatientClassID, + fre.ServiceLineID, + fre.ServiceLineRollupID, + fre.MedicalSurgicalID, + fre.PayorID, + fre.PayorGroupID, + fre.MSDRGID, + fre.CPTID, + bc.FiscalYearID +GO + + +--------------------------------------------- + +-- fp.viewFactReimbursementProjection_repo +CREATE VIEW fp.viewFactReimbursementProjection_repo +AS + SELECT + budg.RowID, + budg.ReimbursementChargesID AS ReimbursementID, + budg.BudgetPhaseID, + frc.BudgetConfigID, + frc.EntityID, + frc.PatientClassID, + frc.ServiceLineID, + frc.ServiceLineRollupID, + frc.PayorID, + frc.PayorGroupID, + frc.MedicalSurgicalID, + frc.MSDRGID, + frc.PrimaryCPTID AS CPTID, + frc.UBRevCodeID, + budg.LockFlag, + budg.LockType, + CAST(12 AS TINYINT) AS TimeClassID, + 6 AS SubsectionID, -- Charges + + budg.AdjustedNetAsPercentOfCharge01 AS RateAdjustedValue01, + budg.AdjustedNetAsPercentOfCharge02 AS RateAdjustedValue02, + budg.AdjustedNetAsPercentOfCharge03 AS RateAdjustedValue03, + budg.AdjustedNetAsPercentOfCharge04 AS RateAdjustedValue04, + budg.AdjustedNetAsPercentOfCharge05 AS RateAdjustedValue05, + budg.AdjustedNetAsPercentOfCharge06 AS RateAdjustedValue06, + budg.AdjustedNetAsPercentOfCharge07 AS RateAdjustedValue07, + budg.AdjustedNetAsPercentOfCharge08 AS RateAdjustedValue08, + budg.AdjustedNetAsPercentOfCharge09 AS RateAdjustedValue09, + budg.AdjustedNetAsPercentOfCharge10 AS RateAdjustedValue10, + budg.AdjustedNetAsPercentOfCharge11 AS RateAdjustedValue11, + budg.AdjustedNetAsPercentOfCharge12 AS RateAdjustedValue12, + + budg.AdjustedChargeDollars01 AS VolumeAdjustedValue01, + budg.AdjustedChargeDollars02 AS VolumeAdjustedValue02, + budg.AdjustedChargeDollars03 AS VolumeAdjustedValue03, + budg.AdjustedChargeDollars04 AS VolumeAdjustedValue04, + budg.AdjustedChargeDollars05 AS VolumeAdjustedValue05, + budg.AdjustedChargeDollars06 AS VolumeAdjustedValue06, + budg.AdjustedChargeDollars07 AS VolumeAdjustedValue07, + budg.AdjustedChargeDollars08 AS VolumeAdjustedValue08, + budg.AdjustedChargeDollars09 AS VolumeAdjustedValue09, + budg.AdjustedChargeDollars10 AS VolumeAdjustedValue10, + budg.AdjustedChargeDollars11 AS VolumeAdjustedValue11, + budg.AdjustedChargeDollars12 AS VolumeAdjustedValue12, + + budg.AdjustedNetReimbursementValue01 AS NetReimbursementValue01, + budg.AdjustedNetReimbursementValue02 AS NetReimbursementValue02, + budg.AdjustedNetReimbursementValue03 AS NetReimbursementValue03, + budg.AdjustedNetReimbursementValue04 AS NetReimbursementValue04, + budg.AdjustedNetReimbursementValue05 AS NetReimbursementValue05, + budg.AdjustedNetReimbursementValue06 AS NetReimbursementValue06, + budg.AdjustedNetReimbursementValue07 AS NetReimbursementValue07, + budg.AdjustedNetReimbursementValue08 AS NetReimbursementValue08, + budg.AdjustedNetReimbursementValue09 AS NetReimbursementValue09, + budg.AdjustedNetReimbursementValue10 AS NetReimbursementValue10, + budg.AdjustedNetReimbursementValue11 AS NetReimbursementValue11, + budg.AdjustedNetReimbursementValue12 AS NetReimbursementValue12 + FROM fp.FactReimbursementCharges frc + INNER JOIN fp.FactReimbursementChargesProjection budg ON frc.ReimbursementChargesID = budg.ReimbursementChargesID + WHERE budg.BudgetPhaseID = 3 + UNION ALL + SELECT + budg.RowID, + budg.ReimbursementEncounterID AS ReimbursementID, + budg.BudgetPhaseID, + frc.BudgetConfigID, + frc.EntityID, + frc.PatientClassID, + frc.ServiceLineID, + frc.ServiceLineRollupID, + frc.PayorID, + frc.PayorGroupID, + frc.MedicalSurgicalID, + frc.MSDRGID, + frc.CPTID, + 0 AS UBRevCodeID, + budg.LockFlag, + budg.LockType, + CAST(12 AS TINYINT) AS TimeClassID, + 5 AS SubsectionID, -- Encounters + + budg.AdjustedNetPerEncounterValue01 AS RateAdjustedValue01, + budg.AdjustedNetPerEncounterValue02 AS RateAdjustedValue02, + budg.AdjustedNetPerEncounterValue03 AS RateAdjustedValue03, + budg.AdjustedNetPerEncounterValue04 AS RateAdjustedValue04, + budg.AdjustedNetPerEncounterValue05 AS RateAdjustedValue05, + budg.AdjustedNetPerEncounterValue06 AS RateAdjustedValue06, + budg.AdjustedNetPerEncounterValue07 AS RateAdjustedValue07, + budg.AdjustedNetPerEncounterValue08 AS RateAdjustedValue08, + budg.AdjustedNetPerEncounterValue09 AS RateAdjustedValue09, + budg.AdjustedNetPerEncounterValue10 AS RateAdjustedValue10, + budg.AdjustedNetPerEncounterValue11 AS RateAdjustedValue11, + budg.AdjustedNetPerEncounterValue12 AS RateAdjustedValue12, + + budg.AdjustedEncounters01 AS VolumeAdjustedValue01, + budg.AdjustedEncounters02 AS VolumeAdjustedValue02, + budg.AdjustedEncounters03 AS VolumeAdjustedValue03, + budg.AdjustedEncounters04 AS VolumeAdjustedValue04, + budg.AdjustedEncounters05 AS VolumeAdjustedValue05, + budg.AdjustedEncounters06 AS VolumeAdjustedValue06, + budg.AdjustedEncounters07 AS VolumeAdjustedValue07, + budg.AdjustedEncounters08 AS VolumeAdjustedValue08, + budg.AdjustedEncounters09 AS VolumeAdjustedValue09, + budg.AdjustedEncounters10 AS VolumeAdjustedValue10, + budg.AdjustedEncounters11 AS VolumeAdjustedValue11, + budg.AdjustedEncounters12 AS VolumeAdjustedValue12, + + budg.AdjustedNetReimbursementValue01 AS NetReimbursementValue01, + budg.AdjustedNetReimbursementValue02 AS NetReimbursementValue02, + budg.AdjustedNetReimbursementValue03 AS NetReimbursementValue03, + budg.AdjustedNetReimbursementValue04 AS NetReimbursementValue04, + budg.AdjustedNetReimbursementValue05 AS NetReimbursementValue05, + budg.AdjustedNetReimbursementValue06 AS NetReimbursementValue06, + budg.AdjustedNetReimbursementValue07 AS NetReimbursementValue07, + budg.AdjustedNetReimbursementValue08 AS NetReimbursementValue08, + budg.AdjustedNetReimbursementValue09 AS NetReimbursementValue09, + budg.AdjustedNetReimbursementValue10 AS NetReimbursementValue10, + budg.AdjustedNetReimbursementValue11 AS NetReimbursementValue11, + budg.AdjustedNetReimbursementValue12 AS NetReimbursementValue12 + FROM fp.FactReimbursementEncounter frc + INNER JOIN fp.FactReimbursementEncounterProjection budg ON frc.ReimbursementEncounterID = budg.ReimbursementEncounterID + WHERE budg.BudgetPhaseID = 3 +GO + + +--------------------------------------------- + +-- fp.viewFactReimbursement_Unpivoted +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-10-13 MD JAZZ-32897 Adding union all for data transfer table +*************************************************************/ +CREATE VIEW fp.viewFactReimbursement_Unpivoted +AS + SELECT + fr.BudgetConfigID, + fr.EntityID, + fr.PatientClassID, + fr.PayorID, + fr.PayorGroupID, + fr.ServiceLineID, + fr.ServiceLineRollupID, + fr.MSDRGID, + fr.MedicalSurgicalID, + fr.PrimaryCPTID, + fr.UnitTypeID, + fr.TimeClassID, + fr.FiscalYearID, + fr.FiscalMonthID, + fr.Value as Total + FROM fp.FactReportReimbursement fr +GO + + +--------------------------------------------- + +-- fp.viewFactReportAdjustmentsHistory +CREATE VIEW [fp].[viewFactReportAdjustmentsHistory] +AS +SELECT + RowID, + SectionID, + CASE WHEN AdjustmentType = 0 THEN 'Incremental' + WHEN AdjustmentType = 1 THEN 'Percent' + WHEN AdjustmentType = 2 THEN 'Set Value' + WHEN AdjustmentType = 3 THEN 'Final' + WHEN AdjustmentType = 4 THEN 'Import' + WHEN AdjustmentType = 5 THEN 'Mix' + WHEN AdjustmentType = 6 THEN 'Add FTE' + WHEN AdjustmentType = 7 THEN 'My Budgets' + WHEN AdjustmentType = 8 THEN 'Set Value' + WHEN AdjustmentType = 9 THEN 'Spread Unlock' + WHEN AdjustmentType = 10 THEN 'Lock' + WHEN AdjustmentType = 11 THEN 'Unlock' + WHEN AdjustmentType = 12 THEN 'Set Value' + WHEN AdjustmentType = 13 THEN 'Final Value' + WHEN AdjustmentType = 14 THEN 'Incremental' + WHEN AdjustmentType = 15 THEN 'Add Provider' + WHEN AdjustmentType = 16 AND IsSetValue = 0 THEN 'My Budgets Itemized' + WHEN AdjustmentType = 16 AND IsSetValue = 1 THEN 'My Budgets' + WHEN AdjustmentType = 17 THEN 'Add Employee' + WHEN AdjustmentType = 18 THEN 'Sub-Account Detail' + WHEN AdjustmentType = 19 THEN 'Add Account' + WHEN AdjustmentType = 20 THEN 'My Budgets' + ELSE '' + END AS [Adjustment Type], + Months, + AdjustmentValue AS [Adjustment Value], + AdjustedLevel AS [Adjustment Level], + UnitTypeID, + TimeClassID, + CAST(LastModifiedDateUtc at time zone 'UTC' at time zone 'CENTRAL STANDARD TIME' AS DateTime) AS [Date/time last edited], + CAST(DateCreatedUtc at time zone 'UTC' at time zone 'CENTRAL STANDARD TIME' AS DateTime) AS [Date/time created], + Comment, + AuthorFullName AS [Author Full Name], + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted AS IsDeleted +FROM fp.FactReportAdjustmentHistory +GO + + +--------------------------------------------- + +-- fp.viewFactReportChargeVolume +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 6-12-2023 MY JAZZ-54952 Projection data for charges data source not populating +*************************************************************/ +CREATE VIEW fp.viewFactReportChargeVolume +AS + SELECT + [BudgetConfigID], + [EntityID], + [DepartmentID], + [ServiceLineID], + [PatientClassID], + [AgeCohortID], + [MedicalSurgicalID], + [ChargeCodeID], + [ServiceEntityID], + [MSDRGID], + [UBRevCodeID], + [PrimaryCPTID], + [ServiceProviderID], + [ServiceProviderSpecialtyID], + [PerformingProviderID], + [PerformingProviderSpecialtyID], + [BillingCPTID], + [UnitTypeID], + [InitialBudget01] AS [Initial Month 01], + [InitialBudget02] AS [Initial Month 02], + [InitialBudget03] AS [Initial Month 03], + [InitialBudget04] AS [Initial Month 04], + [InitialBudget05] AS [Initial Month 05], + [InitialBudget06] AS [Initial Month 06], + [InitialBudget07] AS [Initial Month 07], + [InitialBudget08] AS [Initial Month 08], + [InitialBudget09] AS [Initial Month 09], + [InitialBudget10] AS [Initial Month 10], + [InitialBudget11] AS [Initial Month 11], + [InitialBudget12] AS [Initial Month 12], + [InitialBudgetTotal] AS [Initial Total], + [Target01] AS [Target Month 01], + [Target02] AS [Target Month 02], + [Target03] AS [Target Month 03], + [Target04] AS [Target Month 04], + [Target05] AS [Target Month 05], + [Target06] AS [Target Month 06], + [Target07] AS [Target Month 07], + [Target08] AS [Target Month 08], + [Target09] AS [Target Month 09], + [Target10] AS [Target Month 10], + [Target11] AS [Target Month 11], + [Target12] AS [Target Month 12], + [TargetTotal] AS [Target Total], + [Budget01] AS [Budget Month 01], + [Budget02] AS [Budget Month 02], + [Budget03] AS [Budget Month 03], + [Budget04] AS [Budget Month 04], + [Budget05] AS [Budget Month 05], + [Budget06] AS [Budget Month 06], + [Budget07] AS [Budget Month 07], + [Budget08] AS [Budget Month 08], + [Budget09] AS [Budget Month 09], + [Budget10] AS [Budget Month 10], + [Budget11] AS [Budget Month 11], + [Budget12] AS [Budget Month 12], + [BudgetTotal] AS [Budget Total], + [Projection01] AS [Projection Month 01], + [Projection02] AS [Projection Month 02], + [Projection03] AS [Projection Month 03], + [Projection04] AS [Projection Month 04], + [Projection05] AS [Projection Month 05], + [Projection06] AS [Projection Month 06], + [Projection07] AS [Projection Month 07], + [Projection08] AS [Projection Month 08], + [Projection09] AS [Projection Month 09], + [Projection10] AS [Projection Month 10], + [Projection11] AS [Projection Month 11], + [Projection12] AS [Projection Month 12], + [ProjectionTotal] AS [Projection Total] + FROM [fp].[FactReportChargeVolume] +GO + + +--------------------------------------------- + +-- fp.viewFactReportChargesNotCrosswalkedData +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 05-19-2023 MY JAZZ-54654 Initial +** 2 07-11-2023 MY JAZZ-57364 Add PayorGroupID +*************************************************************/ +CREATE VIEW fp.viewFactReportChargesNotCrosswalkedData +AS + SELECT + DepartmentID, + ChargeCodeID, + PatientClassID, + BudgetConfigID, + PayorGroupID, + ProjectionDollarsAdjustedTotal AS 'Projection Total', + TargetDollarsAdjustedTotal AS 'Target Total', + BudgetDollarsAdjustedTotal AS 'Budget Total' + FROM fp.FactReportChargesNotCrosswalkedData +GO + + +--------------------------------------------- + +-- fp.viewFactReportEncountersToChargeDollars +CREATE VIEW fp.viewFactReportEncountersToChargeDollars +AS +SELECT + BudgetConfigID, + ServiceEntityID, + EntityID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + MSDRGID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + ServiceLineID, + ServiceLineRollupID, + DepartmentID, + UBRevCodeID, + PayorID, + PayorGroupID, + TimeClassID, + AdjustmentID, + AdjustmentDate, + AdjustmentAuthor, + AdjustmentClassificationCategoryID, + AdjustmentClassificationGroupID, + AdjustmentComment, + dc.CalendarDateTime as AdjustmentCreatedDate, + DollarImpact01 AS [Dollar Impact Month01], + DollarImpact02 AS [Dollar Impact Month02], + DollarImpact03 AS [Dollar Impact Month03], + DollarImpact04 AS [Dollar Impact Month04], + DollarImpact05 AS [Dollar Impact Month05], + DollarImpact06 AS [Dollar Impact Month06], + DollarImpact07 AS [Dollar Impact Month07], + DollarImpact08 AS [Dollar Impact Month08], + DollarImpact09 AS [Dollar Impact Month09], + DollarImpact10 AS [Dollar Impact Month10], + DollarImpact11 AS [Dollar Impact Month11], + DollarImpact12 AS [Dollar Impact Month12], + DollarImpactTotal AS [Dollar Impact Total] +FROM fp.FactReportEncountersToChargeDollars ec + INNER JOIN [fw].[DimDate] as dc on CAST(ec.AdjustmentDate AS DATE) = dc.CalendarDateTime +UNION ALL +SELECT + BudgetConfigID, + ServiceEntityID, + EntityID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + MSDRGID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + ServiceLineID, + ServiceLineRollupID, + DepartmentID, + UBRevCodeID, + PayorID, + PayorGroupID, + TimeClassID, + AdjustmentID, + AdjustmentDate, + AdjustmentAuthor, + AdjustmentClassificationCategoryID, + AdjustmentClassificationGroupID, + AdjustmentComment, + dc.CalendarDateTime as AdjustmentCreatedDate, + DollarImpact01 AS [Dollar Impact Month01], + DollarImpact02 AS [Dollar Impact Month02], + DollarImpact03 AS [Dollar Impact Month03], + DollarImpact04 AS [Dollar Impact Month04], + DollarImpact05 AS [Dollar Impact Month05], + DollarImpact06 AS [Dollar Impact Month06], + DollarImpact07 AS [Dollar Impact Month07], + DollarImpact08 AS [Dollar Impact Month08], + DollarImpact09 AS [Dollar Impact Month09], + DollarImpact10 AS [Dollar Impact Month10], + DollarImpact11 AS [Dollar Impact Month11], + DollarImpact12 AS [Dollar Impact Month12], + DollarImpactTotal AS [Dollar Impact Total] +FROM fp.FactReportEncountersToChargeDollars_Initial ec + INNER JOIN [fw].[DimDate] as dc on CAST(ec.AdjustmentDate AS DATE) = dc.CalendarDateTime +GO + + +--------------------------------------------- + +-- fp.viewFactReportEncountersToStats +CREATE VIEW [fp].[viewFactReportEncountersToStats] +AS +SELECT BudgetConfigID, + ServiceEntityID, + EntityID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + MSDRGID, + PrimaryCPTID, + PerformingProviderID, + ProviderID, + DepartmentID, + AccountID, + PayorID, + FinancialReportingID, + TimeClassID, + FiscalMonthID, + AdjustmentID, + AdjustmentDate, + AdjustmentAuthor, + AdjustmentClassificationCategoryID, + AdjustmentClassificationGroupID, + AdjustmentComment, + StatisticsImpact, + EncountersImpact, + ChargeVolumeImpact, + dc.CalendarDateTime as AdjustmentCreatedDate, + ServiceLineID, + ServiceLineRollupID +FROM fp.FactReportEncountersToStats ec +INNER JOIN [fw].[DimDate] as dc on CAST(ec.AdjustmentDate AS DATE) = dc.CalendarDateTime +UNION ALL +SELECT BudgetConfigID, + ServiceEntityID, + EntityID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + MSDRGID, + PrimaryCPTID, + PerformingProviderID, + ProviderID, + DepartmentID, + AccountID, + PayorID, + FinancialReportingID, + TimeClassID, + FiscalMonthID, + AdjustmentID, + AdjustmentDate, + AdjustmentAuthor, + AdjustmentClassificationCategoryID, + AdjustmentClassificationGroupID, + AdjustmentComment, + StatisticsImpact, + EncountersImpact, + ChargeVolumeImpact, + dc.CalendarDateTime as AdjustmentCreatedDate, + ServiceLineID, + ServiceLineRollupID +FROM fp.FactReportEncountersToStats_Initial ec +INNER JOIN [fw].[DimDate] as dc on CAST(ec.AdjustmentDate AS DATE) = dc.CalendarDateTime +GO + + +--------------------------------------------- + +-- fp.viewFactServiceLineEncounterInitialValue_Unpivoted +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 10-19-2020 MY JAZZ-6489 Created Initial Value view to retrieve the initial value unpivoted from FactServiceLineEncounters +** 2 05-18-2023 MY JAZZ-55153 Update to new structure +*************************************************************/ +CREATE VIEW fp.viewFactServiceLineEncounterInitialValue_Unpivoted +AS +SELECT + initial.ServiceLineEncounterID, + initial.BudgetConfigID, + initial.EntityGroupConfigID, + initial.EntityID, + initial.PatientClassID, + initial.ServiceLineID, + initial.ServiceLineRollupID, + initial.AgeCohortID, + initial.MedicalSurgicalID, + initial.DepartmentID, + initial.PayorID, + initial.PayorGroupID, + initial.MSDRGID, + initial.CPTID, + initial.ProviderID, + initial.PhysicianSpecialtyID, + initial.UnitTypeID, + 2 as TimeClassID, + initial.FiscalMonthID, + initial.InitialValue AS InitialValue +FROM ( + SELECT + ServiceLineEncounterID, + BudgetConfigID, + EntityGroupConfigID, + EntityID, + PatientClassID, + ServiceLineID, + ServiceLineRollupID, + AgeCohortID, + MedicalSurgicalID, + DepartmentID, + PayorID, + PayorGroupID, + MSDRGID, + CPTID, + ProviderID, + PhysicianSpecialtyID, + UnitTypeID, + m.FiscalMonthID, + f.InitialValue + FROM ( + SELECT + sle.ServiceLineEncounterID, + sle.BudgetConfigID, + sle.EntityGroupConfigID, + sle.EntityID, + sle.PatientClassID, + sle.ServiceLineID, + sle.ServiceLineRollupID, + sle.AgeCohortID, + sle.MedicalSurgicalID, + sle.DepartmentID, + sle.PayorID, + sle.PayorGroupID, + sle.MSDRGID, + sle.CPTID, + sle.ProviderID, + sle.PhysicianSpecialtyID, + sle.UnitTypeID, + sle.InitialBudget01, + sle.InitialBudget02, + sle.InitialBudget03, + sle.InitialBudget04, + sle.InitialBudget05, + sle.InitialBudget06, + sle.InitialBudget07, + sle.InitialBudget08, + sle.InitialBudget09, + sle.InitialBudget10, + sle.InitialBudget11, + sle.InitialBudget12 + FROM fp.ServiceLineEncounter sle + ) sle + UNPIVOT ( + InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12) + ) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month') + ) initial +GO + + +--------------------------------------------- + +-- fp.viewFactServiceLineEncounter_HistoryViewer +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 5-18-2023 MY JAZZ-55153 Updated view to restructure +*************************************************************/ +CREATE VIEW fp.viewFactServiceLineEncounter_HistoryViewer +AS +SELECT + ov.ServiceLineEncounterID, + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.PatientClassID, + ov.ServiceLineID, + ov.ServiceLineRollupID, + ov.AgeCohortID, + ov.MedicalSurgicalID, + ov.DepartmentID, + ov.PayorID, + ov.PayorGroupID, + ov.MSDRGID, + ov.CPTID, + ov.ProviderID, + ov.PhysicianSpecialtyID, + ov.UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + ov.FiscalMonthID, + LockType, + ov.InitialValue AS OriginalValue, + v.Value, + mgrv.ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT + ServiceLineEncounterID, + BudgetConfigID, + EntityGroupConfigID, + EntityID, + PatientClassID, + ServiceLineID, + ServiceLineRollupID, + AgeCohortID, + MedicalSurgicalID, + DepartmentID, + PayorID, + PayorGroupID, + MSDRGID, + CPTID, + ProviderID, + PhysicianSpecialtyID, + UnitTypeID, + m.FiscalMonthID, + f.InitialValue + FROM ( + SELECT sle.* + FROM fp.ServiceLineEncounter sle ) sle + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT + ServiceLineEncounterID, + BudgetConfigID, + EntityGroupConfigID, + EntityID, + PatientClassID, + ServiceLineID, + ServiceLineRollupID, + AgeCohortID, + MedicalSurgicalID, + DepartmentID, + PayorID, + PayorGroupID, + MSDRGID, + CPTID, + ProviderID, + PhysicianSpecialtyID, + UnitTypeID, + m.FiscalMonthID, + f.Value, + LockType + FROM ( + SELECT sle.*, TargetLockType AS LockType, + sle.TargetAdjusted01 AS AdjustedValue01, sle.TargetAdjusted02 AS AdjustedValue02, sle.TargetAdjusted03 AS AdjustedValue03, sle.TargetAdjusted04 AS AdjustedValue04, + sle.TargetAdjusted05 AS AdjustedValue05, sle.TargetAdjusted06 AS AdjustedValue06, sle.TargetAdjusted07 AS AdjustedValue07, sle.TargetAdjusted08 AS AdjustedValue08, + sle.TargetAdjusted09 AS AdjustedValue09, sle.TargetAdjusted10 AS AdjustedValue10, sle.TargetAdjusted11 AS AdjustedValue11, sle.TargetAdjusted12 AS AdjustedValue12 + FROM fp.ServiceLineEncounter sle + ) sle + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.BudgetConfigID = v.BudgetConfigID + AND ov.EntityGroupConfigID = v.EntityGroupConfigID + AND ov.EntityID = v.EntityID + AND ov.PatientClassID = v.PatientClassID + AND ov.ServiceLineID = v.ServiceLineID + AND ov.ServiceLineRollupID = v.ServiceLineRollupID + AND ov.AgeCohortID = v.AgeCohortID + AND ov.MedicalSurgicalID = v.MedicalSurgicalID + AND ov.DepartmentID = v.DepartmentID + AND ov.PayorID = v.PayorID + AND ov.PayorGroupID = v.PayorGroupID + AND ov.MSDRGID = v.MSDRGID + AND ov.CPTID = v.CPTID + AND ov.ProviderID = v.ProviderID + AND ov.PhysicianSpecialtyID = v.PhysicianSpecialtyID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN ( + -- Unpivot for ManagerValue + SELECT + ServiceLineEncounterID, + BudgetConfigID, + EntityGroupConfigID, + EntityID, + PatientClassID, + ServiceLineID, + ServiceLineRollupID, + AgeCohortID, + MedicalSurgicalID, + DepartmentID, + PayorID, + PayorGroupID, + MSDRGID, + CPTID, + ProviderID, + PhysicianSpecialtyID, + UnitTypeID, + m.FiscalMonthID, + f.Value AS ManagerValue + FROM ( + SELECT sle.*, BudgetLockType AS LockType, + sle.BudgetAdjusted01 AS AdjustedValue01, sle.BudgetAdjusted02 AS AdjustedValue02, sle.BudgetAdjusted03 AS AdjustedValue03, sle.BudgetAdjusted04 AS AdjustedValue04, + sle.BudgetAdjusted05 AS AdjustedValue05, sle.BudgetAdjusted06 AS AdjustedValue06, sle.BudgetAdjusted07 AS AdjustedValue07, sle.BudgetAdjusted08 AS AdjustedValue08, + sle.BudgetAdjusted09 AS AdjustedValue09, sle.BudgetAdjusted10 AS AdjustedValue10, sle.BudgetAdjusted11 AS AdjustedValue11, sle.BudgetAdjusted12 AS AdjustedValue12 + FROM fp.ServiceLineEncounter sle + ) sle + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.EntityGroupConfigID = mgrv.EntityGroupConfigID + AND ov.EntityID = mgrv.EntityID + AND ov.PatientClassID = mgrv.PatientClassID + AND ov.ServiceLineID = mgrv.ServiceLineID + AND ov.ServiceLineRollupID = mgrv.ServiceLineRollupID + AND ov.AgeCohortID = mgrv.AgeCohortID + AND ov.MedicalSurgicalID = mgrv.MedicalSurgicalID + AND ov.DepartmentID = mgrv.DepartmentID + AND ov.PayorID = mgrv.PayorID + AND ov.PayorGroupID = mgrv.PayorGroupID + AND ov.MSDRGID = mgrv.MSDRGID + AND ov.CPTID = mgrv.CPTID + AND ov.ProviderID = mgrv.ProviderID + AND ov.PhysicianSpecialtyID = mgrv.PhysicianSpecialtyID + AND ov.UnitTypeID = mgrv.UnitTypeID + AND ov.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFactServiceLineEncounter_Pivoted +CREATE VIEW [fp].[viewFactServiceLineEncounter_Pivoted] +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-04-25 MD JAZZ-20817 Remove Budget Phase 3 from projection in SLE + ** 2 2023-05-19 MY JAZZ-55153 Update to restructure + *************************************************************/ +SELECT + sl.ServiceLineEncounterID, + sl.BudgetConfigID, + sl.EntityGroupConfigID, + sl.EntityID, + sl.PatientClassID, + sl.ServiceLineID, + sl.ServiceLineRollupID, + sl.AgeCohortID, + sl.MedicalSurgicalID, + sl.DepartmentID, + sl.PayorID, + sl.PayorGroupID, + sl.MSDRGID, + sl.CPTID, + sl.ProviderID, + sl.PhysicianSpecialtyID, + sl.UnitTypeID, + + sl.TargetLockType as TargetLockType, + sl.TargetLockFlag as TargetLockFlag, + sl.BudgetLockType as BudgetLockType, + sl.BudgetLockFlag as BudgetLockFlag, + sl.ProjectionLockType AS ProjectionLockType, + sl.ProjectionLockFlag AS ProjectionLockFlag, + + CASE WHEN sl.TargetLockType = 6 THEN 1 ELSE 0 END AS TargetSpreadsLockFlag, + + sl.TargetAdjustedTotal AS AdjustedValueTotal, + sl.BudgetAdjustedTotal as ManagerAdjustedValueTotal, + sl.ProjectionAdjustedTotal as AdjustedProjectionValueTotal, + + hist.PriorYearActualValueTotal as PriorYearActualValueTotal, + hist.ActualYTDValueTotal as ActualYTDValueTotal, + hist.CurrentYearBudgetTotal as CurrentYearBudgetTotal, + + sl.SampledBudgetTotal, + sl.InitialBudgetTotal, + sl.InitialProjectionTotal, + + sl.TargetAdjusted01 AS AdjustedValue01, sl.TargetAdjusted02 AS AdjustedValue02, sl.TargetAdjusted03 AS AdjustedValue03, + sl.TargetAdjusted04 AS AdjustedValue04, sl.TargetAdjusted05 AS AdjustedValue05, sl.TargetAdjusted06 AS AdjustedValue06, + sl.TargetAdjusted07 AS AdjustedValue07, sl.TargetAdjusted08 AS AdjustedValue08, sl.TargetAdjusted09 AS AdjustedValue09, + sl.TargetAdjusted10 AS AdjustedValue10, sl.TargetAdjusted11 AS AdjustedValue11, sl.TargetAdjusted12 AS AdjustedValue12, + + sl.BudgetAdjusted01 AS ManagerAdjustedValue01, sl.BudgetAdjusted02 AS ManagerAdjustedValue02, sl.BudgetAdjusted03 AS ManagerAdjustedValue03, + sl.BudgetAdjusted04 AS ManagerAdjustedValue04, sl.BudgetAdjusted05 AS ManagerAdjustedValue05, sl.BudgetAdjusted06 AS ManagerAdjustedValue06, + sl.BudgetAdjusted07 AS ManagerAdjustedValue07, sl.BudgetAdjusted08 AS ManagerAdjustedValue08, sl.BudgetAdjusted09 AS ManagerAdjustedValue09, + sl.BudgetAdjusted10 AS ManagerAdjustedValue10, sl.BudgetAdjusted11 AS ManagerAdjustedValue11, sl.BudgetAdjusted12 AS ManagerAdjustedValue12, + + sl.ProjectionAdjusted01 AS AdjustedProjectionValue01, sl.ProjectionAdjusted02 AS AdjustedProjectionValue02, sl.ProjectionAdjusted03 AS AdjustedProjectionValue03, + sl.ProjectionAdjusted04 AS AdjustedProjectionValue04, sl.ProjectionAdjusted05 AS AdjustedProjectionValue05, sl.ProjectionAdjusted06 AS AdjustedProjectionValue06, + sl.ProjectionAdjusted07 AS AdjustedProjectionValue07, sl.ProjectionAdjusted08 AS AdjustedProjectionValue08, sl.ProjectionAdjusted09 AS AdjustedProjectionValue09, + sl.ProjectionAdjusted10 AS AdjustedProjectionValue10, sl.ProjectionAdjusted11 AS AdjustedProjectionValue11, sl.ProjectionAdjusted12 AS AdjustedProjectionValue12 + +From fp.ServiceLineEncounter sl + INNER JOIN fp.ServiceLineEncounterHistory hist with (readuncommitted) ON sl.ServiceLineEncounterID = hist.ServiceLineEncounterID +GO + + +--------------------------------------------- + +-- fp.viewFactStaffingHistory +CREATE VIEW [fp].[viewFactStaffingHistory] +AS + -- Dollars + SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.ProductiveClassID, + fs.VariabilityID, + 34 AS UnitTypeID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderSpecialtyID, + fs.ProviderTypeID, + fs.ProviderLineItemID, + fs.SubsectionID, + fs.AddDate, + fs.SampledBudgetDollars01, + fs.SampledBudgetDollars02, + fs.SampledBudgetDollars03, + fs.SampledBudgetDollars04, + fs.SampledBudgetDollars05, + fs.SampledBudgetDollars06, + fs.SampledBudgetDollars07, + fs.SampledBudgetDollars08, + fs.SampledBudgetDollars09, + fs.SampledBudgetDollars10, + fs.SampledBudgetDollars11, + fs.SampledBudgetDollars12, + fs.SampledBudgetDollarsTotal, + fs.SampledProjectionDollars01, + fs.SampledProjectionDollars02, + fs.SampledProjectionDollars03, + fs.SampledProjectionDollars04, + fs.SampledProjectionDollars05, + fs.SampledProjectionDollars06, + fs.SampledProjectionDollars07, + fs.SampledProjectionDollars08, + fs.SampledProjectionDollars09, + fs.SampledProjectionDollars10, + fs.SampledProjectionDollars11, + fs.SampledProjectionDollars12, + fs.SampledProjectionDollarsTotal, + fs.InitialBudgetDollars01, + fs.InitialBudgetDollars02, + fs.InitialBudgetDollars03, + fs.InitialBudgetDollars04, + fs.InitialBudgetDollars05, + fs.InitialBudgetDollars06, + fs.InitialBudgetDollars07, + fs.InitialBudgetDollars08, + fs.InitialBudgetDollars09, + fs.InitialBudgetDollars10, + fs.InitialBudgetDollars11, + fs.InitialBudgetDollars12, + fs.InitialBudgetDollarsTotal, + fs.InitialProjectionDollars01, + fs.InitialProjectionDollars02, + fs.InitialProjectionDollars03, + fs.InitialProjectionDollars04, + fs.InitialProjectionDollars05, + fs.InitialProjectionDollars06, + fs.InitialProjectionDollars07, + fs.InitialProjectionDollars08, + fs.InitialProjectionDollars09, + fs.InitialProjectionDollars10, + fs.InitialProjectionDollars11, + fs.InitialProjectionDollars12, + fs.InitialProjectionDollarsTotal, + hist.PriorYearActualDollars01, + hist.PriorYearActualDollars02, + hist.PriorYearActualDollars03, + hist.PriorYearActualDollars04, + hist.PriorYearActualDollars05, + hist.PriorYearActualDollars06, + hist.PriorYearActualDollars07, + hist.PriorYearActualDollars08, + hist.PriorYearActualDollars09, + hist.PriorYearActualDollars10, + hist.PriorYearActualDollars11, + hist.PriorYearActualDollars12, + hist.PriorYearActualDollarsTotal, + hist.ActualYTDDollars01, + hist.ActualYTDDollars02, + hist.ActualYTDDollars03, + hist.ActualYTDDollars04, + hist.ActualYTDDollars05, + hist.ActualYTDDollars06, + hist.ActualYTDDollars07, + hist.ActualYTDDollars08, + hist.ActualYTDDollars09, + hist.ActualYTDDollars10, + hist.ActualYTDDollars11, + hist.ActualYTDDollars12, + hist.ActualYTDDollarsTotal, + hist.CurrentYearBudgetDollars01, + hist.CurrentYearBudgetDollars02, + hist.CurrentYearBudgetDollars03, + hist.CurrentYearBudgetDollars04, + hist.CurrentYearBudgetDollars05, + hist.CurrentYearBudgetDollars06, + hist.CurrentYearBudgetDollars07, + hist.CurrentYearBudgetDollars08, + hist.CurrentYearBudgetDollars09, + hist.CurrentYearBudgetDollars10, + hist.CurrentYearBudgetDollars11, + hist.CurrentYearBudgetDollars12, + hist.CurrentYearBudgetDollarsTotal + FROM [fp].[Staffing] fs + INNER JOIN [fp].[StaffingHistory] hist ON fs.StaffingID = hist.StaffingID + + UNION + + -- Hours + SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.ProductiveClassID, + fs.VariabilityID, + 34 AS UnitTypeID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderSpecialtyID, + fs.ProviderTypeID, + fs.ProviderLineItemID, + fs.SubsectionID, + fs.AddDate, + fs.SampledBudgetHours01, + fs.SampledBudgetHours02, + fs.SampledBudgetHours03, + fs.SampledBudgetHours04, + fs.SampledBudgetHours05, + fs.SampledBudgetHours06, + fs.SampledBudgetHours07, + fs.SampledBudgetHours08, + fs.SampledBudgetHours09, + fs.SampledBudgetHours10, + fs.SampledBudgetHours11, + fs.SampledBudgetHours12, + fs.SampledBudgetHoursTotal, + fs.SampledProjectionHours01, + fs.SampledProjectionHours02, + fs.SampledProjectionHours03, + fs.SampledProjectionHours04, + fs.SampledProjectionHours05, + fs.SampledProjectionHours06, + fs.SampledProjectionHours07, + fs.SampledProjectionHours08, + fs.SampledProjectionHours09, + fs.SampledProjectionHours10, + fs.SampledProjectionHours11, + fs.SampledProjectionHours12, + fs.SampledProjectionHoursTotal, + fs.InitialBudgetHours01, + fs.InitialBudgetHours02, + fs.InitialBudgetHours03, + fs.InitialBudgetHours04, + fs.InitialBudgetHours05, + fs.InitialBudgetHours06, + fs.InitialBudgetHours07, + fs.InitialBudgetHours08, + fs.InitialBudgetHours09, + fs.InitialBudgetHours10, + fs.InitialBudgetHours11, + fs.InitialBudgetHours12, + fs.InitialBudgetHoursTotal, + fs.InitialProjectionHours01, + fs.InitialProjectionHours02, + fs.InitialProjectionHours03, + fs.InitialProjectionHours04, + fs.InitialProjectionHours05, + fs.InitialProjectionHours06, + fs.InitialProjectionHours07, + fs.InitialProjectionHours08, + fs.InitialProjectionHours09, + fs.InitialProjectionHours10, + fs.InitialProjectionHours11, + fs.InitialProjectionHours12, + fs.InitialProjectionHoursTotal, + hist.PriorYearActualHours01, + hist.PriorYearActualHours02, + hist.PriorYearActualHours03, + hist.PriorYearActualHours04, + hist.PriorYearActualHours05, + hist.PriorYearActualHours06, + hist.PriorYearActualHours07, + hist.PriorYearActualHours08, + hist.PriorYearActualHours09, + hist.PriorYearActualHours10, + hist.PriorYearActualHours11, + hist.PriorYearActualHours12, + hist.PriorYearActualHoursTotal, + hist.ActualYTDHours01, + hist.ActualYTDHours02, + hist.ActualYTDHours03, + hist.ActualYTDHours04, + hist.ActualYTDHours05, + hist.ActualYTDHours06, + hist.ActualYTDHours07, + hist.ActualYTDHours08, + hist.ActualYTDHours09, + hist.ActualYTDHours10, + hist.ActualYTDHours11, + hist.ActualYTDHours12, + hist.ActualYTDHoursTotal, + hist.CurrentYearBudgetHours01, + hist.CurrentYearBudgetHours02, + hist.CurrentYearBudgetHours03, + hist.CurrentYearBudgetHours04, + hist.CurrentYearBudgetHours05, + hist.CurrentYearBudgetHours06, + hist.CurrentYearBudgetHours07, + hist.CurrentYearBudgetHours08, + hist.CurrentYearBudgetHours09, + hist.CurrentYearBudgetHours10, + hist.CurrentYearBudgetHours11, + hist.CurrentYearBudgetHours12, + hist.CurrentYearBudgetHoursTotal + FROM [fp].[Staffing] fs + INNER JOIN [fp].[StaffingHistory] hist ON fs.StaffingID = hist.StaffingID + + UNION + + SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.ProductiveClassID, + fs.VariabilityID, + 144 as UnitTypeID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderSpecialtyID, + fs.ProviderTypeID, + fs.ProviderLineItemID, + fs.SubsectionID, + fs.AddDate, + fs.SampledBudgetFTEs01, + fs.SampledBudgetFTEs02, + fs.SampledBudgetFTEs03, + fs.SampledBudgetFTEs04, + fs.SampledBudgetFTEs05, + fs.SampledBudgetFTEs06, + fs.SampledBudgetFTEs07, + fs.SampledBudgetFTEs08, + fs.SampledBudgetFTEs09, + fs.SampledBudgetFTEs10, + fs.SampledBudgetFTEs11, + fs.SampledBudgetFTEs12, + fs.SampledBudgetHoursTotal / whBudg.MonthYearly as SampledBudgetTotal, + fs.SampledProjectionFTEs01, + fs.SampledProjectionFTEs02, + fs.SampledProjectionFTEs03, + fs.SampledProjectionFTEs04, + fs.SampledProjectionFTEs05, + fs.SampledProjectionFTEs06, + fs.SampledProjectionFTEs07, + fs.SampledProjectionFTEs08, + fs.SampledProjectionFTEs09, + fs.SampledProjectionFTEs10, + fs.SampledProjectionFTEs11, + fs.SampledProjectionFTEs12, + fs.SampledProjectionHoursTotal / whBudg.MonthYearly as SampledProjectionTotal, + fs.InitialBudgetFTEs01, + fs.InitialBudgetFTEs02, + fs.InitialBudgetFTEs03, + fs.InitialBudgetFTEs04, + fs.InitialBudgetFTEs05, + fs.InitialBudgetFTEs06, + fs.InitialBudgetFTEs07, + fs.InitialBudgetFTEs08, + fs.InitialBudgetFTEs09, + fs.InitialBudgetFTEs10, + fs.InitialBudgetFTEs11, + fs.InitialBudgetFTEs12, + fs.InitialBudgetHoursTotal / whBudg.MonthYearly as InitialBudgetTotal, + fs.InitialProjectionFTEs01, + fs.InitialProjectionFTEs02, + fs.InitialProjectionFTEs03, + fs.InitialProjectionFTEs04, + fs.InitialProjectionFTEs05, + fs.InitialProjectionFTEs06, + fs.InitialProjectionFTEs07, + fs.InitialProjectionFTEs08, + fs.InitialProjectionFTEs09, + fs.InitialProjectionFTEs10, + fs.InitialProjectionFTEs11, + fs.InitialProjectionFTEs12, + fs.InitialProjectionHoursTotal / whBudg.MonthYearly as InitialProjectionTotal, + hist.PriorYearActualFTEs01, + hist.PriorYearActualFTEs02, + hist.PriorYearActualFTEs03, + hist.PriorYearActualFTEs04, + hist.PriorYearActualFTEs05, + hist.PriorYearActualFTEs06, + hist.PriorYearActualFTEs07, + hist.PriorYearActualFTEs08, + hist.PriorYearActualFTEs09, + hist.PriorYearActualFTEs10, + hist.PriorYearActualFTEs11, + hist.PriorYearActualFTEs12, + hist.PriorYearActualHoursTotal / whPrior.MonthYearly as PriorYearActualValueTotal, + hist.ActualYTDFTEs01, + hist.ActualYTDFTEs02, + hist.ActualYTDFTEs03, + hist.ActualYTDFTEs04, + hist.ActualYTDFTEs05, + hist.ActualYTDFTEs06, + hist.ActualYTDFTEs07, + hist.ActualYTDFTEs08, + hist.ActualYTDFTEs09, + hist.ActualYTDFTEs10, + hist.ActualYTDFTEs11, + hist.ActualYTDFTEs12, + hist.ActualYTDHoursTotal / [dbo].[GetDaysInMonthsLoaded](bc.FiscalYearID - 2) as ActualYTDValueTotal, + hist.CurrentYearBudgetFTEs01, + hist.CurrentYearBudgetFTEs02, + hist.CurrentYearBudgetFTEs03, + hist.CurrentYearBudgetFTEs04, + hist.CurrentYearBudgetFTEs05, + hist.CurrentYearBudgetFTEs06, + hist.CurrentYearBudgetFTEs07, + hist.CurrentYearBudgetFTEs08, + hist.CurrentYearBudgetFTEs09, + hist.CurrentYearBudgetFTEs10, + hist.CurrentYearBudgetFTEs11, + hist.CurrentYearBudgetFTEs12, + hist.CurrentYearBudgetHoursTotal / whCurr.MonthYearly as CurrentYearBudgetTotal + FROM [fp].[Staffing] fs + INNER JOIN [fp].[StaffingHistory] hist ON fs.StaffingID = hist.StaffingID + INNER JOIN [fp].[BudgetConfig] bc ON fs.BudgetConfigID = bc.BudgetConfigID + LEFT JOIN [client].[FactWorkingHoursPerMonth] whBudg ON whBudg.FiscalYearID = bc.FiscalYearID + LEFT JOIN [client].[FactWorkingHoursPerMonth] whCurr ON whCurr.FiscalYearID = bc.FiscalYearID - 1 + LEFT JOIN [client].[FactWorkingHoursPerMonth] whPrior ON whPrior.FiscalYearID = bc.FiscalYearID - 2 +GO + + +--------------------------------------------- + +-- fp.viewFactStaffingHistory_Unpivoted +CREATE VIEW [fp].[viewFactStaffingHistory_Unpivoted] +AS + SELECT + BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + JobCodeID, + PayCodeGroupID, + ProductiveClassID, + VariabilityID, + UnitTypeID, + TimeClassID, + FiscalYearID, + FiscalMonthID, + Value, + EmployeeID, + ProviderID, + ProviderLineItemID, + ProviderTypeID, + ProviderSpecialtyID + FROM fp.FactReportStaffingHistory +GO + + +--------------------------------------------- + +-- fp.viewFactStaffingHistory_Unpivoted_archive +CREATE VIEW fp.viewFactStaffingHistory_Unpivoted_archive AS SELECT * FROM fp.FactReportStaffingHistory_archive +GO + + +--------------------------------------------- + +-- fp.viewFactStaffingHistory_Unpivoted_source +CREATE VIEW [fp].[viewFactStaffingHistory_Unpivoted_source] +AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-11-14 BW JAZZ-62798 New data model update + *************************************************************/ + +SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.VariabilityID, + fs.ProductiveClassID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + 34 as UnitTypeID, + TimeClassID, + bc.FiscalYearID - CASE WHEN IsPriorYear = 1 THEN 2 ELSE 1 END AS FiscalYearID, + m.FiscalMonthID, + hist.Value +FROM ( + SELECT hist.StaffingID, 1 AS TimeClassID, Value, FiscalMonth, CAST(0 as bit) As IsPriorYear + FROM fp.StaffingHistory hist (READUNCOMMITTED) + CROSS APPLY + (VALUES + (1, ActualYTDDollars01), + (2, ActualYTDDollars02), + (3, ActualYTDDollars03), + (4, ActualYTDDollars04), + (5, ActualYTDDollars05), + (6, ActualYTDDollars06), + (7, ActualYTDDollars07), + (8, ActualYTDDollars08), + (9, ActualYTDDollars09), + (10,ActualYTDDollars10), + (11,ActualYTDDollars11), + (12,ActualYTDDollars12)) X (FiscalMonth,Value) +UNION +SELECT hist.StaffingID, 2 AS TimeClassID, Value, FiscalMonth, CAST(0 as bit) As IsPriorYear + FROM fp.StaffingHistory hist (READUNCOMMITTED) + CROSS APPLY + (VALUES + (1, CurrentYearBudgetDollars01), + (2, CurrentYearBudgetDollars02), + (3, CurrentYearBudgetDollars03), + (4, CurrentYearBudgetDollars04), + (5, CurrentYearBudgetDollars05), + (6, CurrentYearBudgetDollars06), + (7, CurrentYearBudgetDollars07), + (8, CurrentYearBudgetDollars08), + (9, CurrentYearBudgetDollars09), + (10,CurrentYearBudgetDollars10), + (11,CurrentYearBudgetDollars11), + (12,CurrentYearBudgetDollars12)) X (FiscalMonth,Value) +UNION +SELECT hist.StaffingID, 1 AS TimeClassID, Value, FiscalMonth, CAST(1 as bit) As IsPriorYear + FROM fp.StaffingHistory hist (READUNCOMMITTED) + CROSS APPLY + (VALUES + (1, PriorYearActualDollars01), + (2, PriorYearActualDollars02), + (3, PriorYearActualDollars03), + (4, PriorYearActualDollars04), + (5, PriorYearActualDollars05), + (6, PriorYearActualDollars06), + (7, PriorYearActualDollars07), + (8, PriorYearActualDollars08), + (9, PriorYearActualDollars09), + (10,PriorYearActualDollars10), + (11,PriorYearActualDollars11), + (12,PriorYearActualDollars12)) X (FiscalMonth,Value) ) hist +INNER JOIN fp.Staffing fs (READUNCOMMITTED) ON fs.StaffingID = hist.StaffingID + INNER JOIN fw.DimFiscalMonth m ON m.SortOrder = FiscalMonth + INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID + +UNION ALL + +SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.VariabilityID, + fs.ProductiveClassID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + 51 as UnitTypeID, + TimeClassID, + bc.FiscalYearID - CASE WHEN IsPriorYear = 1 THEN 2 ELSE 1 END AS FiscalYearID, + m.FiscalMonthID, + hist.Value +FROM ( + SELECT hist.StaffingID, 1 AS TimeClassID, Value, FiscalMonth, CAST(0 as bit) As IsPriorYear + FROM fp.StaffingHistory hist (READUNCOMMITTED) + CROSS APPLY + (VALUES + (1, ActualYTDHours01), + (2, ActualYTDHours02), + (3, ActualYTDHours03), + (4, ActualYTDHours04), + (5, ActualYTDHours05), + (6, ActualYTDHours06), + (7, ActualYTDHours07), + (8, ActualYTDHours08), + (9, ActualYTDHours09), + (10,ActualYTDHours10), + (11,ActualYTDHours11), + (12,ActualYTDHours12)) X (FiscalMonth,Value) +UNION +SELECT hist.StaffingID, 2 AS TimeClassID, Value, FiscalMonth, CAST(0 as bit) As IsPriorYear + FROM fp.StaffingHistory hist (READUNCOMMITTED) + CROSS APPLY + (VALUES + (1, CurrentYearBudgetHours01), + (2, CurrentYearBudgetHours02), + (3, CurrentYearBudgetHours03), + (4, CurrentYearBudgetHours04), + (5, CurrentYearBudgetHours05), + (6, CurrentYearBudgetHours06), + (7, CurrentYearBudgetHours07), + (8, CurrentYearBudgetHours08), + (9, CurrentYearBudgetHours09), + (10,CurrentYearBudgetHours10), + (11,CurrentYearBudgetHours11), + (12,CurrentYearBudgetHours12)) X (FiscalMonth,Value) +UNION +SELECT hist.StaffingID, 1 AS TimeClassID, Value, FiscalMonth, CAST(1 as bit) As IsPriorYear + FROM fp.StaffingHistory hist (READUNCOMMITTED) + CROSS APPLY + (VALUES + (1, PriorYearActualHours01), + (2, PriorYearActualHours02), + (3, PriorYearActualHours03), + (4, PriorYearActualHours04), + (5, PriorYearActualHours05), + (6, PriorYearActualHours06), + (7, PriorYearActualHours07), + (8, PriorYearActualHours08), + (9, PriorYearActualHours09), + (10,PriorYearActualHours10), + (11,PriorYearActualHours11), + (12,PriorYearActualHours12)) X (FiscalMonth,Value) ) hist +INNER JOIN fp.Staffing fs (READUNCOMMITTED) ON fs.StaffingID = hist.StaffingID + INNER JOIN fw.DimFiscalMonth m ON m.SortOrder = FiscalMonth + INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID + +UNION ALL + +SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.VariabilityID, + fs.ProductiveClassID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + 144 as UnitTypeID, + TimeClassID, + bc.FiscalYearID - CASE WHEN IsPriorYear = 1 THEN 2 ELSE 1 END AS FiscalYearID, + m.FiscalMonthID, + hist.Value +FROM ( + SELECT hist.StaffingID, 1 AS TimeClassID, Value, FiscalMonth, CAST(0 as bit) As IsPriorYear + FROM fp.StaffingHistory hist (READUNCOMMITTED) + CROSS APPLY + (VALUES + (1, ActualYTDFTEs01), + (2, ActualYTDFTEs02), + (3, ActualYTDFTEs03), + (4, ActualYTDFTEs04), + (5, ActualYTDFTEs05), + (6, ActualYTDFTEs06), + (7, ActualYTDFTEs07), + (8, ActualYTDFTEs08), + (9, ActualYTDFTEs09), + (10,ActualYTDFTEs10), + (11,ActualYTDFTEs11), + (12,ActualYTDFTEs12)) X (FiscalMonth,Value) +UNION +SELECT hist.StaffingID, 2 AS TimeClassID, Value, FiscalMonth, CAST(0 as bit) As IsPriorYear + FROM fp.StaffingHistory hist (READUNCOMMITTED) + CROSS APPLY + (VALUES + (1, CurrentYearBudgetFTEs01), + (2, CurrentYearBudgetFTEs02), + (3, CurrentYearBudgetFTEs03), + (4, CurrentYearBudgetFTEs04), + (5, CurrentYearBudgetFTEs05), + (6, CurrentYearBudgetFTEs06), + (7, CurrentYearBudgetFTEs07), + (8, CurrentYearBudgetFTEs08), + (9, CurrentYearBudgetFTEs09), + (10,CurrentYearBudgetFTEs10), + (11,CurrentYearBudgetFTEs11), + (12,CurrentYearBudgetFTEs12)) X (FiscalMonth,Value) +UNION +SELECT hist.StaffingID, 1 AS TimeClassID, Value, FiscalMonth, CAST(1 as bit) As IsPriorYear + FROM fp.StaffingHistory hist (READUNCOMMITTED) + CROSS APPLY + (VALUES + (1, PriorYearActualFTEs01), + (2, PriorYearActualFTEs02), + (3, PriorYearActualFTEs03), + (4, PriorYearActualFTEs04), + (5, PriorYearActualFTEs05), + (6, PriorYearActualFTEs06), + (7, PriorYearActualFTEs07), + (8, PriorYearActualFTEs08), + (9, PriorYearActualFTEs09), + (10,PriorYearActualFTEs10), + (11,PriorYearActualFTEs11), + (12,PriorYearActualFTEs12)) X (FiscalMonth,Value) ) hist +INNER JOIN fp.Staffing fs (READUNCOMMITTED) ON fs.StaffingID = hist.StaffingID + INNER JOIN fw.DimFiscalMonth m ON m.SortOrder = FiscalMonth + INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFactStaffingVariability +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-04-28 MY JAZZ-28395 Cache Variability Percentage on FactStaffing +** 2 2022-10-18 MD JAZZ-44889 Add EGC ID to view +** 3 2022-11-07 MY JAZZ-35951 Add EmployeeID to FactStaffingVariabilityDetail +** 4 2023-09-20 BK JAZZ-60973 Update for new data structure +*************************************************************/ +CREATE VIEW [fp].[viewFactStaffingVariability] +AS +SELECT DISTINCT + pv.BudgetConfigID, + egc.EntityGroupConfigGUID, + dd.EntityID, + pv.SubsectionID, + pv.DepartmentID, + pv.ProviderLineItemID, + pv.JobCodeID, + pv.PayCodeGroupID, + pv.EmployeeID, + pv.EntityGroupConfigID, + ISNULL(MAX(pv.FixedVariabilityPercentage), 0) AS FixedPercentage +FROM [fp].[Staffing] pv + INNER JOIN [fp].[EntityGroupConfig] egc ON pv.EntityGroupConfigID = egc.EntityGroupConfigID + INNER JOIN [fw].[DimDepartment] dd ON dd.DepartmentID = pv.DepartmentID +WHERE pv.VariabilityID = 2 +GROUP BY pv.BudgetConfigID, + pv.EntityGroupConfigID, + egc.EntityGroupConfigGUID, + dd.EntityID, + pv.SubsectionID, + pv.DepartmentID, + pv.JobCodeID, + pv.ProviderLineItemID, + pv.PayCodeGroupID, + pv.EmployeeID +GO + + +--------------------------------------------- + +-- fp.viewFactStaffingVariabilityForAdjustments +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 11-07-2022 MY JAZZ-35951 Add EmployeeID to FactStaffingVariabilityDetail +** 2 01-03-2023 MY JAZZ-63564 Final Pass Of Fact References (SQL) +*************************************************************/ +CREATE VIEW [fp].[viewFactStaffingVariabilityForAdjustments] +AS +SELECT DISTINCT + bc.BudgetConfigID, + egc.EntityGroupConfigGUID, + dd.EntityID, + pv.DepartmentID, + pv.JobCodeID, -- Eventually need to add PayCodeGroup level here for when ABB clients use this. + ISNULL(MAX(pv.FixedVariabilityPercentage), 0) AS FixedPercentage +FROM [fp].[Staffing] pv + INNER JOIN [fp].[EntityGroupConfig] egc ON pv.EntityGroupConfigID = egc.EntityGroupConfigID + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID + INNER JOIN [fw].[DimDepartment] dd ON dd.DepartmentID = pv.DepartmentID +WHERE pv.ProviderLineItemID = 0 -- Filtering out Provider Line Item lvl variability because they don't have manager adjustments. + AND pv.VariabilityID = 2 + AND pv.ProductiveClassID != 4 -- Exclude Dollars as these are always fixed + AND pv.EmployeeID = 0 -- Variable records are always EmployeeID = 0 +GROUP BY bc.BudgetConfigID, + pv.EntityGroupConfigID, + egc.EntityGroupConfigGUID, + dd.EntityID, + pv.DepartmentID, + pv.JobCodeID +GO + + +--------------------------------------------- + +-- fp.viewFactStaffing_Unpivoted +CREATE VIEW fp.viewFactStaffing_Unpivoted AS SELECT * FROM fp.FactReportStaffing +GO + + +--------------------------------------------- + +-- fp.viewFactStaffing_Unpivoted_BaselineOnly +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-07-18 MY JAZZ-37944 Initial +** 2 2023-12-07 BW JAZZ-63600 Data model restructure +*************************************************************/ +CREATE VIEW [fp].[viewFactStaffing_Unpivoted_BaselineOnly] +AS + SELECT staff.StaffingID, + staff.BudgetConfigID, + staff.EntityGroupConfigID, + staff.EntityID, + staff.DepartmentID, + staff.JobCodeID, + staff.PayCodeGroupID, + staff.VariabilityID, + staff.ProductiveClassID, + staff.EmployeeID, + staff.ProviderID, + staff.ProviderTypeID, + staff.ProviderSpecialtyID, + staff.ProviderLineItemID, + staff.SubsectionID, + UT.UnitTypeID, + TimeClassID = 2, + m.FiscalMonthID, + bc.FiscalYearID, + Value as OriginalValue + FROM [fp].[Staffing] staff (READUNCOMMITTED) + CROSS APPLY ( + VALUES + (1, 34, InitialBudgetDollars01), + (2, 34, InitialBudgetDollars02), + (3, 34, InitialBudgetDollars03), + (4, 34, InitialBudgetDollars04), + (5, 34, InitialBudgetDollars05), + (6, 34, InitialBudgetDollars06), + (7, 34, InitialBudgetDollars07), + (8, 34, InitialBudgetDollars08), + (9, 34, InitialBudgetDollars09), + (10, 34, InitialBudgetDollars10), + (11, 34, InitialBudgetDollars11), + (12, 34, InitialBudgetDollars12), + (1, 51, InitialBudgetHours01), + (2, 51, InitialBudgetHours02), + (3, 51, InitialBudgetHours03), + (4, 51, InitialBudgetHours04), + (5, 51, InitialBudgetHours05), + (6, 51, InitialBudgetHours06), + (7, 51, InitialBudgetHours07), + (8, 51, InitialBudgetHours08), + (9, 51, InitialBudgetHours09), + (10, 51, InitialBudgetHours10), + (11, 51, InitialBudgetHours11), + (12, 51, InitialBudgetHours12), + (1, 144, InitialBudgetFTEs01), + (2, 144, InitialBudgetFTEs02), + (3, 144, InitialBudgetFTEs03), + (4, 144, InitialBudgetFTEs04), + (5, 144, InitialBudgetFTEs05), + (6, 144, InitialBudgetFTEs06), + (7, 144, InitialBudgetFTEs07), + (8, 144, InitialBudgetFTEs08), + (9, 144, InitialBudgetFTEs09), + (10, 144, InitialBudgetFTEs10), + (11, 144, InitialBudgetFTEs11), + (12, 144, InitialBudgetFTEs12) + ) AS CrossApplied (FiscalMonth, UnitTypeID, Value) + LEFT JOIN [fw].[DimUnitType] ut ON ut.UnitTypeID = CrossApplied.UnitTypeID + LEFT JOIN [fw].[DimFiscalMonth] m ON m.SortOrder = CrossApplied.FiscalMonth + INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID + UNION ALL + SELECT staff.StaffingID, + staff.BudgetConfigID, + staff.EntityGroupConfigID, + staff.EntityID, + staff.DepartmentID, + staff.JobCodeID, + staff.PayCodeGroupID, + staff.VariabilityID, + staff.ProductiveClassID, + staff.EmployeeID, + staff.ProviderID, + staff.ProviderTypeID, + staff.ProviderSpecialtyID, + staff.ProviderLineItemID, + staff.SubsectionID, + UT.UnitTypeID, + TimeClassID = 2, + m.FiscalMonthID, + bc.FiscalYearID, + Value as OriginalValue + FROM [fp].[Staffing] staff (READUNCOMMITTED) + INNER JOIN [fp].[StaffingWageRate] wr (READUNCOMMITTED) ON staff.StaffingWageRateID = wr.StaffingWageRateID + AND staff.VariabilityID = 1 + CROSS APPLY ( + VALUES + (1, 159, InitialBudget01), + (2, 159, InitialBudget02), + (3, 159, InitialBudget03), + (4, 159, InitialBudget04), + (5, 159, InitialBudget05), + (6, 159, InitialBudget06), + (7, 159, InitialBudget07), + (8, 159, InitialBudget08), + (9, 159, InitialBudget09), + (10, 159, InitialBudget10), + (11, 159, InitialBudget11), + (12, 159, InitialBudget12) + ) AS CrossApplied (FiscalMonth, UnitTypeID, Value) + LEFT JOIN [fw].[DimUnitType] ut ON ut.UnitTypeID = CrossApplied.UnitTypeID + LEFT JOIN [fw].[DimFiscalMonth] m ON m.SortOrder = CrossApplied.FiscalMonth + INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFactStaffing_Unpivoted_archive +CREATE VIEW fp.viewFactStaffing_Unpivoted_archive AS SELECT * FROM fp.FactReportStaffing_archive +GO + + +--------------------------------------------- + +-- fp.viewFactStaffing_Unpivoted_source +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2020-08-07 MY JAZZ-2849 Added Entity Group Config to view for Snowflake reporting +** 2 2021-02-18 MY JAZZ-15374 Added Provider to view +** 3 2023-11-01 BW JAZZ-62798 New data model update +*************************************************************/ +CREATE VIEW [fp].[viewFactStaffing_Unpivoted_source] +AS +SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.VariabilityID, + fs.ProductiveClassID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.SubsectionID, + 34 as UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + m.FiscalMonthID, + OriginalValue, Value, ManagerValue + FROM fp.Staffing fs + CROSS APPLY ( + VALUES + (1,InitialBudgetDollars01, TargetAdjustedDollars01, BudgetAdjustedDollars01), + (2,InitialBudgetDollars02, TargetAdjustedDollars02, BudgetAdjustedDollars02), + (3,InitialBudgetDollars03, TargetAdjustedDollars03, BudgetAdjustedDollars03), + (4,InitialBudgetDollars04, TargetAdjustedDollars04, BudgetAdjustedDollars04), + (5,InitialBudgetDollars05, TargetAdjustedDollars05, BudgetAdjustedDollars05), + (6,InitialBudgetDollars06, TargetAdjustedDollars06, BudgetAdjustedDollars06), + (7,InitialBudgetDollars07, TargetAdjustedDollars07, BudgetAdjustedDollars07), + (8,InitialBudgetDollars08, TargetAdjustedDollars08, BudgetAdjustedDollars08), + (9,InitialBudgetDollars09, TargetAdjustedDollars09, BudgetAdjustedDollars09), + (10,InitialBudgetDollars10, TargetAdjustedDollars10, BudgetAdjustedDollars10), + (11,InitialBudgetDollars11, TargetAdjustedDollars11, BudgetAdjustedDollars11), + (12,InitialBudgetDollars12, TargetAdjustedDollars12, BudgetAdjustedDollars12)) fsx (FiscalMonth, OriginalValue, Value, ManagerValue) +LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = fsx.FiscalMonth +INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID + +UNION ALL +SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.VariabilityID, + fs.ProductiveClassID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.SubsectionID, + 34 as UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID - 1, + m.FiscalMonthID, + OriginalValue, Value, ManagerValue + FROM fp.Staffing fs + CROSS APPLY ( + VALUES + (1,InitialProjectionDollars01, ProjectionAdjustedDollars01, ProjectionAdjustedDollars01), + (2,InitialProjectionDollars02, ProjectionAdjustedDollars02, ProjectionAdjustedDollars02), + (3,InitialProjectionDollars03, ProjectionAdjustedDollars03, ProjectionAdjustedDollars03), + (4,InitialProjectionDollars04, ProjectionAdjustedDollars04, ProjectionAdjustedDollars04), + (5,InitialProjectionDollars05, ProjectionAdjustedDollars05, ProjectionAdjustedDollars05), + (6,InitialProjectionDollars06, ProjectionAdjustedDollars06, ProjectionAdjustedDollars06), + (7,InitialProjectionDollars07, ProjectionAdjustedDollars07, ProjectionAdjustedDollars07), + (8,InitialProjectionDollars08, ProjectionAdjustedDollars08, ProjectionAdjustedDollars08), + (9,InitialProjectionDollars09, ProjectionAdjustedDollars09, ProjectionAdjustedDollars09), + (10,InitialProjectionDollars10, ProjectionAdjustedDollars10, ProjectionAdjustedDollars10), + (11,InitialProjectionDollars11, ProjectionAdjustedDollars11, ProjectionAdjustedDollars11), + (12,InitialProjectionDollars12, ProjectionAdjustedDollars12, ProjectionAdjustedDollars12)) fsx (FiscalMonth, OriginalValue, Value, ManagerValue) +LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = fsx.FiscalMonth +INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID + +UNION ALL + +SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.VariabilityID, + fs.ProductiveClassID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.SubsectionID, + 51 as UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + m.FiscalMonthID, + OriginalValue, Value, ManagerValue + FROM fp.Staffing fs + CROSS APPLY ( + VALUES + (1,InitialBudgetHours01, TargetAdjustedHours01, BudgetAdjustedHours01), + (2,InitialBudgetHours02, TargetAdjustedHours02, BudgetAdjustedHours02), + (3,InitialBudgetHours03, TargetAdjustedHours03, BudgetAdjustedHours03), + (4,InitialBudgetHours04, TargetAdjustedHours04, BudgetAdjustedHours04), + (5,InitialBudgetHours05, TargetAdjustedHours05, BudgetAdjustedHours05), + (6,InitialBudgetHours06, TargetAdjustedHours06, BudgetAdjustedHours06), + (7,InitialBudgetHours07, TargetAdjustedHours07, BudgetAdjustedHours07), + (8,InitialBudgetHours08, TargetAdjustedHours08, BudgetAdjustedHours08), + (9,InitialBudgetHours09, TargetAdjustedHours09, BudgetAdjustedHours09), + (10,InitialBudgetHours10, TargetAdjustedHours10, BudgetAdjustedHours10), + (11,InitialBudgetHours11, TargetAdjustedHours11, BudgetAdjustedHours11), + (12,InitialBudgetHours12, TargetAdjustedHours12, BudgetAdjustedHours12)) fsx (FiscalMonth, OriginalValue, Value, ManagerValue) +LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = fsx.FiscalMonth +INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID + +UNION ALL +SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.VariabilityID, + fs.ProductiveClassID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.SubsectionID, + 51 as UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID - 1, + m.FiscalMonthID, + OriginalValue, Value, ManagerValue + FROM fp.Staffing fs + CROSS APPLY ( + VALUES + (1,InitialProjectionHours01, ProjectionAdjustedHours01, ProjectionAdjustedHours01), + (2,InitialProjectionHours02, ProjectionAdjustedHours02, ProjectionAdjustedHours02), + (3,InitialProjectionHours03, ProjectionAdjustedHours03, ProjectionAdjustedHours03), + (4,InitialProjectionHours04, ProjectionAdjustedHours04, ProjectionAdjustedHours04), + (5,InitialProjectionHours05, ProjectionAdjustedHours05, ProjectionAdjustedHours05), + (6,InitialProjectionHours06, ProjectionAdjustedHours06, ProjectionAdjustedHours06), + (7,InitialProjectionHours07, ProjectionAdjustedHours07, ProjectionAdjustedHours07), + (8,InitialProjectionHours08, ProjectionAdjustedHours08, ProjectionAdjustedHours08), + (9,InitialProjectionHours09, ProjectionAdjustedHours09, ProjectionAdjustedHours09), + (10,InitialProjectionHours10, ProjectionAdjustedHours10, ProjectionAdjustedHours10), + (11,InitialProjectionHours11, ProjectionAdjustedHours11, ProjectionAdjustedHours11), + (12,InitialProjectionHours12, ProjectionAdjustedHours12, ProjectionAdjustedHours12)) fsx (FiscalMonth, OriginalValue, Value, ManagerValue) +LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = fsx.FiscalMonth +INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID + +UNION ALL + +SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.VariabilityID, + fs.ProductiveClassID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.SubsectionID, + 144 as UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + m.FiscalMonthID, + OriginalValue, Value, ManagerValue + FROM fp.Staffing fs + CROSS APPLY ( + VALUES + (1,InitialBudgetFTEs01, TargetAdjustedFTEs01, BudgetAdjustedFTEs01), + (2,InitialBudgetFTEs02, TargetAdjustedFTEs02, BudgetAdjustedFTEs02), + (3,InitialBudgetFTEs03, TargetAdjustedFTEs03, BudgetAdjustedFTEs03), + (4,InitialBudgetFTEs04, TargetAdjustedFTEs04, BudgetAdjustedFTEs04), + (5,InitialBudgetFTEs05, TargetAdjustedFTEs05, BudgetAdjustedFTEs05), + (6,InitialBudgetFTEs06, TargetAdjustedFTEs06, BudgetAdjustedFTEs06), + (7,InitialBudgetFTEs07, TargetAdjustedFTEs07, BudgetAdjustedFTEs07), + (8,InitialBudgetFTEs08, TargetAdjustedFTEs08, BudgetAdjustedFTEs08), + (9,InitialBudgetFTEs09, TargetAdjustedFTEs09, BudgetAdjustedFTEs09), + (10,InitialBudgetFTEs10, TargetAdjustedFTEs10, BudgetAdjustedFTEs10), + (11,InitialBudgetFTEs11, TargetAdjustedFTEs11, BudgetAdjustedFTEs11), + (12,InitialBudgetFTEs12, TargetAdjustedFTEs12, BudgetAdjustedFTEs12)) fsx (FiscalMonth, OriginalValue, Value, ManagerValue) +LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = fsx.FiscalMonth +INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID + +UNION ALL +SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.VariabilityID, + fs.ProductiveClassID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.SubsectionID, + 144 as UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID - 1, + m.FiscalMonthID, + OriginalValue, Value, ManagerValue + FROM fp.Staffing fs + CROSS APPLY ( + VALUES + (1,InitialProjectionFTEs01, ProjectionAdjustedFTEs01, ProjectionAdjustedFTEs01), + (2,InitialProjectionFTEs02, ProjectionAdjustedFTEs02, ProjectionAdjustedFTEs02), + (3,InitialProjectionFTEs03, ProjectionAdjustedFTEs03, ProjectionAdjustedFTEs03), + (4,InitialProjectionFTEs04, ProjectionAdjustedFTEs04, ProjectionAdjustedFTEs04), + (5,InitialProjectionFTEs05, ProjectionAdjustedFTEs05, ProjectionAdjustedFTEs05), + (6,InitialProjectionFTEs06, ProjectionAdjustedFTEs06, ProjectionAdjustedFTEs06), + (7,InitialProjectionFTEs07, ProjectionAdjustedFTEs07, ProjectionAdjustedFTEs07), + (8,InitialProjectionFTEs08, ProjectionAdjustedFTEs08, ProjectionAdjustedFTEs08), + (9,InitialProjectionFTEs09, ProjectionAdjustedFTEs09, ProjectionAdjustedFTEs09), + (10,InitialProjectionFTEs10, ProjectionAdjustedFTEs10, ProjectionAdjustedFTEs10), + (11,InitialProjectionFTEs11, ProjectionAdjustedFTEs11, ProjectionAdjustedFTEs11), + (12,InitialProjectionFTEs12, ProjectionAdjustedFTEs12, ProjectionAdjustedFTEs12)) fsx (FiscalMonth, OriginalValue, Value, ManagerValue) +LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = fsx.FiscalMonth +INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID + +-- Wage Rate +UNION ALL + +SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + 3 AS VariabilityID, + fs.ProductiveClassID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.SubsectionID, + 159 as UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + m.FiscalMonthID, + OriginalValue, Value, ManagerValue + FROM fp.Staffing fs + INNER JOIN fp.StaffingWageRate wr ON fs.StaffingWageRateID = wr.StaffingWageRateID + CROSS APPLY ( + VALUES + (1,InitialBudget01, TargetAdjusted01, BudgetAdjusted01), + (2,InitialBudget02, TargetAdjusted02, BudgetAdjusted02), + (3,InitialBudget03, TargetAdjusted03, BudgetAdjusted03), + (4,InitialBudget04, TargetAdjusted04, BudgetAdjusted04), + (5,InitialBudget05, TargetAdjusted05, BudgetAdjusted05), + (6,InitialBudget06, TargetAdjusted06, BudgetAdjusted06), + (7,InitialBudget07, TargetAdjusted07, BudgetAdjusted07), + (8,InitialBudget08, TargetAdjusted08, BudgetAdjusted08), + (9,InitialBudget09, TargetAdjusted09, BudgetAdjusted09), + (10,InitialBudget10, TargetAdjusted10, BudgetAdjusted10), + (11,InitialBudget11, TargetAdjusted11, BudgetAdjusted11), + (12,InitialBudget12, TargetAdjusted12, BudgetAdjusted12)) fsx (FiscalMonth, OriginalValue, Value, ManagerValue) +LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = fsx.FiscalMonth +INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID +WHERE fs.VariabilityID = 1 + +UNION ALL +SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + 3 AS VariabilityID, + fs.ProductiveClassID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.SubsectionID, + 159 as UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID - 1, + m.FiscalMonthID, + OriginalValue, Value, ManagerValue + FROM fp.Staffing fs + INNER JOIN fp.StaffingWageRate wr ON fs.StaffingWageRateID = wr.StaffingWageRateID + CROSS APPLY ( + VALUES + (1,InitialProjection01, ProjectionAdjusted01, ProjectionAdjusted01), + (2,InitialProjection02, ProjectionAdjusted02, ProjectionAdjusted02), + (3,InitialProjection03, ProjectionAdjusted03, ProjectionAdjusted03), + (4,InitialProjection04, ProjectionAdjusted04, ProjectionAdjusted04), + (5,InitialProjection05, ProjectionAdjusted05, ProjectionAdjusted05), + (6,InitialProjection06, ProjectionAdjusted06, ProjectionAdjusted06), + (7,InitialProjection07, ProjectionAdjusted07, ProjectionAdjusted07), + (8,InitialProjection08, ProjectionAdjusted08, ProjectionAdjusted08), + (9,InitialProjection09, ProjectionAdjusted09, ProjectionAdjusted09), + (10,InitialProjection10, ProjectionAdjusted10, ProjectionAdjusted10), + (11,InitialProjection11, ProjectionAdjusted11, ProjectionAdjusted11), + (12,InitialProjection12, ProjectionAdjusted12, ProjectionAdjusted12)) fsx (FiscalMonth, OriginalValue, Value, ManagerValue) +LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = fsx.FiscalMonth +INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID +WHERE fs.VariabilityID = 1 + +UNION ALL + +SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.VariabilityID, + fs.ProductiveClassID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.SubsectionID, + 172 as UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + m.FiscalMonthID, + OriginalValue, Value, ManagerValue + FROM fp.Staffing fs + CROSS APPLY ( + VALUES + (1,InitialBudgetRate01, TargetAdjustedRate01, BudgetAdjustedRate01), + (2,InitialBudgetRate02, TargetAdjustedRate02, BudgetAdjustedRate02), + (3,InitialBudgetRate03, TargetAdjustedRate03, BudgetAdjustedRate03), + (4,InitialBudgetRate04, TargetAdjustedRate04, BudgetAdjustedRate04), + (5,InitialBudgetRate05, TargetAdjustedRate05, BudgetAdjustedRate05), + (6,InitialBudgetRate06, TargetAdjustedRate06, BudgetAdjustedRate06), + (7,InitialBudgetRate07, TargetAdjustedRate07, BudgetAdjustedRate07), + (8,InitialBudgetRate08, TargetAdjustedRate08, BudgetAdjustedRate08), + (9,InitialBudgetRate09, TargetAdjustedRate09, BudgetAdjustedRate09), + (10,InitialBudgetRate10, TargetAdjustedRate10, BudgetAdjustedRate10), + (11,InitialBudgetRate11, TargetAdjustedRate11, BudgetAdjustedRate11), + (12,InitialBudgetRate12, TargetAdjustedRate12, BudgetAdjustedRate12)) fsx (FiscalMonth, OriginalValue, Value, ManagerValue) +LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = fsx.FiscalMonth +INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID +WHERE fs.VariabilityID = 2 + +UNION ALL +SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.VariabilityID, + fs.ProductiveClassID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.SubsectionID, + 172 as UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID - 1, + m.FiscalMonthID, + OriginalValue, Value, ManagerValue + FROM fp.Staffing fs + CROSS APPLY ( + VALUES + (1,InitialProjectionRate01, ProjectionAdjustedRate01, ProjectionAdjustedRate01), + (2,InitialProjectionRate02, ProjectionAdjustedRate02, ProjectionAdjustedRate02), + (3,InitialProjectionRate03, ProjectionAdjustedRate03, ProjectionAdjustedRate03), + (4,InitialProjectionRate04, ProjectionAdjustedRate04, ProjectionAdjustedRate04), + (5,InitialProjectionRate05, ProjectionAdjustedRate05, ProjectionAdjustedRate05), + (6,InitialProjectionRate06, ProjectionAdjustedRate06, ProjectionAdjustedRate06), + (7,InitialProjectionRate07, ProjectionAdjustedRate07, ProjectionAdjustedRate07), + (8,InitialProjectionRate08, ProjectionAdjustedRate08, ProjectionAdjustedRate08), + (9,InitialProjectionRate09, ProjectionAdjustedRate09, ProjectionAdjustedRate09), + (10,InitialProjectionRate10, ProjectionAdjustedRate10, ProjectionAdjustedRate10), + (11,InitialProjectionRate11, ProjectionAdjustedRate11, ProjectionAdjustedRate11), + (12,InitialProjectionRate12, ProjectionAdjustedRate12, ProjectionAdjustedRate12)) fsx (FiscalMonth, OriginalValue, Value, ManagerValue) +LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = fsx.FiscalMonth +INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID +WHERE fs.VariabilityID = 2 +GO + + +--------------------------------------------- + +-- fp.viewFactStatistics +CREATE VIEW fp.viewFactStatistics +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-10-04 JB JAZZ-43489 Remove FlexedValue references + *************************************************************/ +SELECT + stat.StatisticsID, + stat.BudgetConfigID, + stat.EntityGroupConfigID, + stat.DepartmentID, + stat.FinancialReportingID, + stat.EntityID, + stat.AccountID, + stat.ProviderID, + stat.ProviderSpecialtyID, + stat.ProviderTypeID, + stat.ProviderLineItemID, + bc.FiscalYearID, + stat.UnitTypeID, + bdgt.LockType as BudgetLockType, + bdgt.LockFlag as BudgetLockFlag, + bdgt.BudgetPhaseID as BudgetPhaseID, + proj.LockType as ProjectionLockType, + proj.LockFlag as ProjectionLockFlag, + stat.SampledBudget01, stat.SampledBudget02, stat.SampledBudget03, stat.SampledBudget04, stat.SampledBudget05, stat.SampledBudget06, stat.SampledBudget07, stat.SampledBudget08, stat.SampledBudget09, stat.SampledBudget10, stat.SampledBudget11, stat.SampledBudget12, stat.SampledBudgetTotal, + stat.InitialBudget01, stat.InitialBudget02, stat.InitialBudget03, stat.InitialBudget04, stat.InitialBudget05, stat.InitialBudget06, stat.InitialBudget07, stat.InitialBudget08, stat.InitialBudget09, stat.InitialBudget10, stat.InitialBudget11, stat.InitialBudget12, stat.InitialBudgetTotal, + stat.SampledProjection01, stat.SampledProjection02, stat.SampledProjection03, stat.SampledProjection04, stat.SampledProjection05, stat.SampledProjection06, stat.SampledProjection07, stat.SampledProjection08, stat.SampledProjection09, stat.SampledProjection10, stat.SampledProjection11, stat.SampledProjection12, stat.SampledProjectionTotal, + stat.InitialProjection01, stat.InitialProjection02, stat.InitialProjection03, stat.InitialProjection04, stat.InitialProjection05, stat.InitialProjection06, stat.InitialProjection07, stat.InitialProjection08, stat.InitialProjection09, stat.InitialProjection10, stat.InitialProjection11, stat.InitialProjection12, stat.InitialProjectionTotal,bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12, bdgt.AdjustedValueTotal, + proj.AdjustedValue01 AS AdjustedProjectionValue01, proj.AdjustedValue02 AS AdjustedProjectionValue02, proj.AdjustedValue03 AS AdjustedProjectionValue03, proj.AdjustedValue04 AS AdjustedProjectionValue04, proj.AdjustedValue05 AS AdjustedProjectionValue05, proj.AdjustedValue06 AS AdjustedProjectionValue06, proj.AdjustedValue07 AS AdjustedProjectionValue07, proj.AdjustedValue08 AS AdjustedProjectionValue08, proj.AdjustedValue09 AS AdjustedProjectionValue09, proj.AdjustedValue10 AS AdjustedProjectionValue10, proj.AdjustedValue11 AS AdjustedProjectionValue11, proj.AdjustedValue12 AS AdjustedProjectionValue12, proj.AdjustedValueTotal AS AdjustedProjectionValueTotal +FROM fp.FactStatistics stat + INNER JOIN [fp].[BudgetConfig] bc ON stat.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [fp].[FactStatisticsBudget] bdgt ON stat.StatisticsID = bdgt.StatisticsID + INNER JOIN [fp].[FactStatisticsProjection] proj ON stat.StatisticsID = proj.StatisticsID AND proj.BudgetPhaseID = bdgt.BudgetPhaseID +GO + + +--------------------------------------------- + +-- fp.viewFactStatisticsBudget_HistoryViewer +CREATE VIEW [fp].[viewFactStatistics_HistoryViewer] +AS +SELECT + ov.StatisticsID, + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.DepartmentID, + ov.AccountID, + ov.FinancialReportingID, + ov.PatientClassID, + ov.PayorID, + ov.ProviderID, + ov.ProviderTypeID, + ov.ProviderLineItemID, + ov.ProviderSpecialtyID, + ov.SubSectionID, + ov.UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + ov.FiscalMonthID, + LockType, + ov.InitialValue AS OriginalValue, + v.Value, + mgrv.ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, ProviderID, ProviderTypeID, ProviderLineItemID, ProviderSpecialtyID, SubSectionID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT gl.* + FROM fp.FactStatistics gl ) gl + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, ProviderID, ProviderTypeID, ProviderLineItemID, ProviderSpecialtyID, SubSectionID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT gl.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactStatistics gl + INNER JOIN fp.FactStatisticsBudget bdgt ON gl.StatisticsID = bdgt.StatisticsID + WHERE bdgt.BudgetPhaseID = 2) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.DepartmentID = v.DepartmentID + AND ov.AccountID = v.AccountID + AND ov.BudgetConfigID = v.BudgetConfigID + AND ov.PatientClassID = v.PatientClassID + AND ov.PayorID = v.PayorID + AND ov.ProviderID = v.ProviderID + AND ov.ProviderTypeID = v.ProviderTypeID + AND ov.ProviderLineItemID = v.ProviderLineItemID + AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID + AND ov.SubSectionID = v.SubSectionID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN ( + -- Unpivot for ManagerValue + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, ProviderID, ProviderTypeID, ProviderLineItemID, ProviderSpecialtyID, SubSectionID, UnitTypeID, m.FiscalMonthID, f.Value AS ManagerValue + FROM ( + SELECT gl.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactStatistics gl + INNER JOIN fp.FactStatisticsBudget bdgt ON gl.StatisticsID = bdgt.StatisticsID + WHERE bdgt.BudgetPhaseID = 3) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON ov.DepartmentID = mgrv.DepartmentID + AND ov.AccountID = mgrv.AccountID + AND ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.PatientClassID = mgrv.PatientClassID + AND ov.PayorID = mgrv.PayorID + AND ov.ProviderID = mgrv.ProviderID + AND ov.ProviderTypeID = mgrv.ProviderTypeID + AND ov.ProviderLineItemID = mgrv.ProviderLineItemID + AND ov.ProviderSpecialtyID = mgrv.ProviderSpecialtyID + AND ov.SubSectionID = mgrv.SubSectionID + AND ov.UnitTypeID = mgrv.UnitTypeID + AND ov.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFactStatisticsBudget_repo +CREATE VIEW fp.viewFactStatisticsBudget_repo +AS +SELECT + fsb.RowID, + stat.StatisticsID, + stat.BudgetConfigID, + stat.EntityGroupConfigID, + fsb.BudgetPhaseID, + stat.EntityID, + stat.DepartmentID, + stat.AccountID, + stat.FinancialReportingID, + stat.PayorID, + stat.PatientClassID, + stat.UnitTypeID, + stat.ProviderID, + stat.ProviderSpecialtyID, + stat.ProviderTypeID, + stat.ProviderLineItemID, + fsb.LockFlag, + fsb.LockType, + CAST(2 AS TINYINT) AS TimeClassID, + fsb.AdjustedValue01, fsb.AdjustedValue02, fsb.AdjustedValue03, fsb.AdjustedValue04, fsb.AdjustedValue05, fsb.AdjustedValue06, fsb.AdjustedValue07, fsb.AdjustedValue08, fsb.AdjustedValue09, fsb.AdjustedValue10, fsb.AdjustedValue11, fsb.AdjustedValue12, + fsb.RateAdjustedValue01, fsb.RateAdjustedValue02, fsb.RateAdjustedValue03, fsb.RateAdjustedValue04, fsb.RateAdjustedValue05, fsb.RateAdjustedValue06, fsb.RateAdjustedValue07, fsb.RateAdjustedValue08, fsb.RateAdjustedValue09, fsb.RateAdjustedValue10, fsb.RateAdjustedValue11, fsb.RateAdjustedValue12, + stat.SubsectionID, + stat.GroupingGuid +FROM fp.FactStatistics stat + INNER JOIN fp.FactStatisticsBudget fsb ON stat.StatisticsID = fsb.StatisticsID; +GO + + +--------------------------------------------- + +-- fp.viewFactStatisticsByGeneralLedgerID +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 08-25-2023 MY JAZZ-59500 Updated view to restructure +*************************************************************/ +CREATE VIEW fp.viewFactStatisticsByGeneralLedgerID +AS +SELECT + gl.GeneralLedgerID, + gl.BudgetConfigID, + gl.EntityGroupConfigID, + gl.FlexingTypeID, + SUM(tgt.AdjustedValue01) AS TargetStats01, + SUM(tgt.AdjustedValue02) AS TargetStats02, + SUM(tgt.AdjustedValue03) AS TargetStats03, + SUM(tgt.AdjustedValue04) AS TargetStats04, + SUM(tgt.AdjustedValue05) AS TargetStats05, + SUM(tgt.AdjustedValue06) AS TargetStats06, + SUM(tgt.AdjustedValue07) AS TargetStats07, + SUM(tgt.AdjustedValue08) AS TargetStats08, + SUM(tgt.AdjustedValue09) AS TargetStats09, + SUM(tgt.AdjustedValue10) AS TargetStats10, + SUM(tgt.AdjustedValue11) AS TargetStats11, + SUM(tgt.AdjustedValue12) AS TargetStats12, + SUM(bdgt.AdjustedValue01) AS BudgetStats01, + SUM(bdgt.AdjustedValue02) AS BudgetStats02, + SUM(bdgt.AdjustedValue03) AS BudgetStats03, + SUM(bdgt.AdjustedValue04) AS BudgetStats04, + SUM(bdgt.AdjustedValue05) AS BudgetStats05, + SUM(bdgt.AdjustedValue06) AS BudgetStats06, + SUM(bdgt.AdjustedValue07) AS BudgetStats07, + SUM(bdgt.AdjustedValue08) AS BudgetStats08, + SUM(bdgt.AdjustedValue09) AS BudgetStats09, + SUM(bdgt.AdjustedValue10) AS BudgetStats10, + SUM(bdgt.AdjustedValue11) AS BudgetStats11, + SUM(bdgt.AdjustedValue12) AS BudgetStats12, + SUM(proj.AdjustedValue01) AS ProjectionStats01, + SUM(proj.AdjustedValue02) AS ProjectionStats02, + SUM(proj.AdjustedValue03) AS ProjectionStats03, + SUM(proj.AdjustedValue04) AS ProjectionStats04, + SUM(proj.AdjustedValue05) AS ProjectionStats05, + SUM(proj.AdjustedValue06) AS ProjectionStats06, + SUM(proj.AdjustedValue07) AS ProjectionStats07, + SUM(proj.AdjustedValue08) AS ProjectionStats08, + SUM(proj.AdjustedValue09) AS ProjectionStats09, + SUM(proj.AdjustedValue10) AS ProjectionStats10, + SUM(proj.AdjustedValue11) AS ProjectionStats11, + SUM(proj.AdjustedValue12) AS ProjectionStats12, + SUM(tgt.AdjustedValueTotal) AS TargetStatsTotal, + SUM(bdgt.AdjustedValueTotal) AS BudgetStatsTotal, + SUM(proj.AdjustedValueTotal) AS ProjectionStatsTotal +FROM [fp].FactStatistics sb WITH(NOLOCK) + INNER JOIN [fp].[FactStatisticsBudget] tgt ON sb.StatisticsID = tgt.StatisticsID AND tgt.BudgetPhaseID = 2 + INNER JOIN [fp].[FactStatisticsBudget] bdgt ON sb.StatisticsID = bdgt.StatisticsID AND bdgt.BudgetPhaseID = 3 + INNER JOIN [fp].[FactStatisticsProjection] proj ON sb.StatisticsID = proj.StatisticsID AND proj.BudgetPhaseID = bdgt.BudgetPhaseID + INNER JOIN [fp].[BudgetConfig] bc ON sb.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [fp].[EntityGroupConfig] egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN ( + SELECT DISTINCT EntityGroupConfigID, FlexingTypeID, DepartmentID, StatAccountID, GLAccountID + FROM [fp].[FlexConfigMapping] WITH(NOLOCK) + WHERE FlexingTypeID IN (1, 2) -- Non-Staffing (1) and Revenue (2) + ) fcm ON sb.DepartmentID = fcm.DepartmentID + AND sb.AccountID = fcm.StatAccountID + AND fcm.EntityGroupConfigID = egc.EntityGroupConfigID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egc.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID + AND sb.EntityID = egcm.EntityID + INNER JOIN fp.GeneralLedger gl ON sb.BudgetConfigID = gl.BudgetConfigID + AND sb.EntityGroupConfigID = gl.EntityGroupConfigID + AND sb.DepartmentID = gl.DepartmentID + AND fcm.GLAccountID = gl.AccountID + AND fcm.FlexingTypeID = gl.FlexingTypeID -- Essentially exclude anything that isn't flexing +WHERE 1 = 1 + AND gl.VariabilityID = 2 -- Filter to Variable records to avoid multiple rows +GROUP BY gl.GeneralLedgerID, gl.FlexingTypeID, gl.BudgetConfigID, gl.EntityGroupConfigID +HAVING SUM(tgt.AdjustedValueTotal) > 0 -- Exclude records that are all 0's, we can just assume it's 0 if it's missing from this + OR SUM(bdgt.AdjustedValueTotal) > 0 + OR SUM(proj.AdjustedValueTotal) > 0 +GO + + +--------------------------------------------- + +-- fp.viewFactStatisticsForAdjustments_Unpivoted +CREATE VIEW [fp].[viewFactStatisticsForAdjustments_Unpivoted] +AS +SELECT + ov.BudgetConfigID, + ov.EntityID, + ov.DepartmentID, + ov.AccountID, + ov.PatientClassID, + ov.PayorID, + ov.FinancialReportingID, + ov.UnitTypeID, + 2 as TimeClassID, + ov.FiscalMonthID, + bc.FiscalYearID, + ov.InitialValue as OriginalValue, + v.Value, + mgrv.Value as ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT cv.* + FROM fp.FactStatistics cv ) cv + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT cv.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactStatistics cv + INNER JOIN fp.FactStatisticsBudget bdgt ON cv.StatisticsID = bdgt.StatisticsID + WHERE bdgt.BudgetPhaseID = 2) cv + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.BudgetConfigID = v.BudgetConfigID + AND ov.EntityID = v.EntityID + AND ov.DepartmentID = v.DepartmentID + AND ov.AccountID = v.AccountID + AND ov.PatientClassID = v.PatientClassID + AND ov.PayorID = v.PayorID + AND ov.FinancialReportingID = v.FinancialReportingID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN ( + -- Unpivot for Manager Value + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT cv.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactStatistics cv + INNER JOIN fp.FactStatisticsBudget bdgt ON cv.StatisticsID = bdgt.StatisticsID + WHERE bdgt.BudgetPhaseID = 3) cv + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.EntityID = mgrv.EntityID + AND ov.DepartmentID = mgrv.DepartmentID + AND ov.AccountID = mgrv.AccountID + AND ov.PatientClassID = mgrv.PatientClassID + AND ov.PayorID = mgrv.PayorID + AND ov.FinancialReportingID = mgrv.FinancialReportingID + AND ov.UnitTypeID = mgrv.UnitTypeID + AND ov.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID + +UNION + + SELECT + ov.BudgetConfigID, + ov.EntityID, + ov.DepartmentID, + ov.AccountID, + ov.PatientClassID, + ov.PayorID, + ov.FinancialReportingID, + ov.UnitTypeID, + 12 as TimeClassID, + ov.FiscalMonthID, + bc.FiscalYearID, + ov.InitialValue as OriginalValue, + v.Value, + mgrv.Value as ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT cv.* + FROM fp.FactStatistics cv ) cv + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT cv.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactStatistics cv + INNER JOIN fp.FactStatisticsProjection bdgt ON cv.StatisticsID = bdgt.StatisticsID + WHERE bdgt.BudgetPhaseID = 2) cv + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.BudgetConfigID = v.BudgetConfigID + AND ov.EntityID = v.EntityID + AND ov.DepartmentID = v.DepartmentID + AND ov.AccountID = v.AccountID + AND ov.PatientClassID = v.PatientClassID + AND ov.PayorID = v.PayorID + AND ov.FinancialReportingID = v.FinancialReportingID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN ( + -- Unpivot for Manager Value + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT cv.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactStatistics cv + INNER JOIN fp.FactStatisticsProjection bdgt ON cv.StatisticsID = bdgt.StatisticsID + WHERE bdgt.BudgetPhaseID = 3) cv + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.EntityID = mgrv.EntityID + AND ov.DepartmentID = mgrv.DepartmentID + AND ov.AccountID = mgrv.AccountID + AND ov.PatientClassID = mgrv.PatientClassID + AND ov.PayorID = mgrv.PayorID + AND ov.FinancialReportingID = mgrv.FinancialReportingID + AND ov.UnitTypeID = mgrv.UnitTypeID + AND ov.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFactStatisticsHistory_Unpivoted +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-07-20 MD JAZZ-23237 Adding union all for data transfer table +*************************************************************/ + +CREATE VIEW [fp].[viewFactStatisticsHistory_Unpivoted] +AS + SELECT + BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + AccountID, + FinancialReportingID, + PayorID, + PatientClassID, + UnitTypeID, + TimeClassID, + FiscalYearID, + FiscalMonthID, + Value + FROM fp.FactReportStatisticsHistory + + UNION ALL + + SELECT + BudgetConfigID, + 0 as EntityGroupConfigID, + EntityID, + DepartmentID, + AccountID, + FinancialReportingID, + PayorID, + PatientClassID, + UnitTypeID, + TimeClassID, + FiscalYearID, + FiscalMonthID, + Value + FROM fp.FactReportStatisticsHistoryDataTransfer +GO + + +--------------------------------------------- + +-- fp.viewFactStatisticsHistory_Unpivoted_archive +CREATE VIEW fp.viewFactStatisticsHistory_Unpivoted_archive AS SELECT * FROM fp.FactReportStatisticsHistory_archive +GO + + +--------------------------------------------- + +-- fp.viewFactStatisticsHistory_Unpivoted_source +CREATE VIEW [fp].[viewFactStatisticsHistory_Unpivoted_source] +AS +-- Unpivot for PriorYearActual +SELECT data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.AccountID, data.FinancialReportingID, data.PayorID, data.PatientClassID, data.ProviderID, data.ProviderTypeID, data.ProviderSpecialtyID, data.ProviderLineItemID, data.SubsectionID, data.UnitTypeID, 1 as TimeClassID, bc.FiscalYearID - 2 as FiscalYearID, data.FiscalMonthID, data.Value +FROM ( + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PayorID, + PatientClassID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT fs.*, hist.PriorYearActualValue01, hist.PriorYearActualValue02, hist.PriorYearActualValue03, hist.PriorYearActualValue04, hist.PriorYearActualValue05, hist.PriorYearActualValue06, hist.PriorYearActualValue07, hist.PriorYearActualValue08, hist.PriorYearActualValue09, hist.PriorYearActualValue10, hist.PriorYearActualValue11, hist.PriorYearActualValue12 + FROM fp.FactStatistics fs + INNER JOIN fp.FactStatisticsHistory hist ON fs.StatisticsID = hist.StatisticsID ) fs + UNPIVOT ( Value FOR FiscalMonth IN (PriorYearActualValue01, PriorYearActualValue02, PriorYearActualValue03, PriorYearActualValue04, PriorYearActualValue05, PriorYearActualValue06, PriorYearActualValue07, PriorYearActualValue08, PriorYearActualValue09, PriorYearActualValue10, PriorYearActualValue11, PriorYearActualValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'PriorYearActualValue', 'Month')) data + INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID + +UNION ALL + +-- Unpivot for ActualYTD +SELECT data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.AccountID, data.FinancialReportingID, data.PayorID, data.PatientClassID, data.ProviderID, data.ProviderTypeID, data.ProviderSpecialtyID, data.ProviderLineItemID, data.SubsectionID, data.UnitTypeID, 1 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value +FROM ( + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PayorID, + PatientClassID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT fs.*, hist.ActualYTDValue01, hist.ActualYTDValue02, hist.ActualYTDValue03, hist.ActualYTDValue04, hist.ActualYTDValue05, hist.ActualYTDValue06, hist.ActualYTDValue07, hist.ActualYTDValue08, hist.ActualYTDValue09, hist.ActualYTDValue10, hist.ActualYTDValue11, hist.ActualYTDValue12 + FROM fp.FactStatistics fs + INNER JOIN fp.FactStatisticsHistory hist ON fs.StatisticsID = hist.StatisticsID ) fs + UNPIVOT ( Value FOR FiscalMonth IN (ActualYTDValue01, ActualYTDValue02, ActualYTDValue03, ActualYTDValue04, ActualYTDValue05, ActualYTDValue06, ActualYTDValue07, ActualYTDValue08, ActualYTDValue09, ActualYTDValue10, ActualYTDValue11, ActualYTDValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ActualYTDValue', 'Month')) data + INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID + +UNION ALL + +-- Unpivot for CurrentYearBudget +SELECT data.BudgetConfigID, data.EntityGroupConfigID, data.EntityID, data.DepartmentID, data.AccountID, data.FinancialReportingID, data.PayorID, data.PatientClassID, data.ProviderID, data.ProviderTypeID, data.ProviderSpecialtyID, data.ProviderLineItemID, data.SubsectionID, data.UnitTypeID, 2 as TimeClassID, bc.FiscalYearID - 1 as FiscalYearID, data.FiscalMonthID, data.Value +FROM ( + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PayorID, + PatientClassID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT fs.*, hist.CurrentYearBudget01, hist.CurrentYearBudget02, hist.CurrentYearBudget03, hist.CurrentYearBudget04, hist.CurrentYearBudget05, hist.CurrentYearBudget06, hist.CurrentYearBudget07, hist.CurrentYearBudget08, hist.CurrentYearBudget09, hist.CurrentYearBudget10, hist.CurrentYearBudget11, hist.CurrentYearBudget12 + FROM fp.FactStatistics fs + INNER JOIN fp.FactStatisticsHistory hist ON fs.StatisticsID = hist.StatisticsID ) fs + UNPIVOT ( Value FOR FiscalMonth IN (CurrentYearBudget01, CurrentYearBudget02, CurrentYearBudget03, CurrentYearBudget04, CurrentYearBudget05, CurrentYearBudget06, CurrentYearBudget07, CurrentYearBudget08, CurrentYearBudget09, CurrentYearBudget10, CurrentYearBudget11, CurrentYearBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'CurrentYearBudget', 'Month')) data + INNER JOIN fp.BudgetConfig bc ON data.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFactStatisticsProjection_HistoryViewer +CREATE VIEW [fp].[viewFactStatisticsProjection_HistoryViewer] +AS +SELECT + ov.StatisticsID, + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.DepartmentID, + ov.AccountID, + ov.FinancialReportingID, + ov.PatientClassID, + ov.PayorID, + ov.ProviderID, + ov.ProviderTypeID, + ov.ProviderLineItemID, + ov.ProviderSpecialtyID, + ov.SubSectionID, + ov.UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID, + ov.FiscalMonthID, + LockType, + ov.InitialValue AS OriginalValue, + v.Value, + mgrv.ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, ProviderID, ProviderTypeID, ProviderLineItemID, ProviderSpecialtyID, SubSectionID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT gl.* + FROM fp.FactStatistics gl ) gl + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, ProviderID, ProviderTypeID, ProviderLineItemID, ProviderSpecialtyID, SubSectionID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT gl.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactStatistics gl + INNER JOIN fp.FactStatisticsProjection bdgt ON gl.StatisticsID = bdgt.StatisticsID + WHERE bdgt.BudgetPhaseID = 2) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.DepartmentID = v.DepartmentID + AND ov.AccountID = v.AccountID + AND ov.BudgetConfigID = v.BudgetConfigID + AND ov.PatientClassID = v.PatientClassID + AND ov.PayorID = v.PayorID + AND ov.ProviderID = v.ProviderID + AND ov.ProviderTypeID = v.ProviderTypeID + AND ov.ProviderLineItemID = v.ProviderLineItemID + AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID + AND ov.SubSectionID = v.SubSectionID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN ( + -- Unpivot for ManagerValue + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, ProviderID, ProviderTypeID, ProviderLineItemID, ProviderSpecialtyID, SubSectionID, UnitTypeID, m.FiscalMonthID, f.Value AS ManagerValue + FROM ( + SELECT gl.*, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactStatistics gl + INNER JOIN fp.FactStatisticsProjection bdgt ON gl.StatisticsID = bdgt.StatisticsID + WHERE bdgt.BudgetPhaseID = 3) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON ov.DepartmentID = mgrv.DepartmentID + AND ov.AccountID = mgrv.AccountID + AND ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.PatientClassID = mgrv.PatientClassID + AND ov.PayorID = mgrv.PayorID + AND ov.ProviderID = mgrv.ProviderID + AND ov.ProviderTypeID = mgrv.ProviderTypeID + AND ov.ProviderLineItemID = mgrv.ProviderLineItemID + AND ov.ProviderSpecialtyID = mgrv.ProviderSpecialtyID + AND ov.SubSectionID = mgrv.SubSectionID + AND ov.UnitTypeID = mgrv.UnitTypeID + AND ov.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFactStatisticsProjection_repo +CREATE VIEW fp.viewFactStatisticsProjection_repo +AS +SELECT + fsp.RowID, + stat.StatisticsID, + stat.BudgetConfigID, + stat.EntityGroupConfigID, + fsp.BudgetPhaseID, + stat.EntityID, + stat.DepartmentID, + stat.AccountID, + stat.FinancialReportingID, + stat.PayorID, + stat.PatientClassID, + stat.UnitTypeID, + stat.ProviderID, + stat.ProviderSpecialtyID, + stat.ProviderTypeID, + stat.ProviderLineItemID, + fsp.LockFlag, + fsp.LockType, + CAST(12 AS TINYINT) AS TimeClassID, + fsp.AdjustedValue01, fsp.AdjustedValue02, fsp.AdjustedValue03, fsp.AdjustedValue04, fsp.AdjustedValue05, fsp.AdjustedValue06, fsp.AdjustedValue07, fsp.AdjustedValue08, fsp.AdjustedValue09, fsp.AdjustedValue10, fsp.AdjustedValue11, fsp.AdjustedValue12, + fsp.RateAdjustedValue01, fsp.RateAdjustedValue02, fsp.RateAdjustedValue03, fsp.RateAdjustedValue04, fsp.RateAdjustedValue05, fsp.RateAdjustedValue06, fsp.RateAdjustedValue07, fsp.RateAdjustedValue08, fsp.RateAdjustedValue09, fsp.RateAdjustedValue10, fsp.RateAdjustedValue11, fsp.RateAdjustedValue12, + stat.SubsectionID, + stat.GroupingGuid +FROM fp.FactStatistics stat + INNER JOIN fp.FactStatisticsProjection fsp ON stat.StatisticsID = fsp.StatisticsID; +GO + + +--------------------------------------------- + +-- fp.viewFactStatisticsTotals +CREATE VIEW fp.viewFactStatisticsTotals + AS + SELECT obj.StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PatientClassID, PayorID, UnitTypeID, + obj.ProviderID, obj.ProviderSpecialtyID, obj.ProviderTypeID, obj.ProviderLineItemID, + SampledBudgetTotal, SampledProjectionTotal, InitialBudgetTotal, InitialProjectionTotal, adminProj.AdjustedValueTotal AS ProjectionAdminTotal, mgrProj.AdjustedValueTotal AS ProjectionManagerTotal, + adminBudg.AdjustedValueTotal AS BudgetAdminTotal, mgrBudg.AdjustedValueTotal AS BudgetManagerTotal, hist.ActualYTDValueTotal, hist.PriorYearActualValueTotal, hist.CurrentYearBudgetTotal + FROM [fp].[FactStatistics] obj + INNER JOIN [fp].[FactStatisticsProjection] adminProj ON obj.StatisticsID = adminProj.StatisticsID + INNER JOIN [fp].[FactStatisticsProjection] mgrProj ON obj.StatisticsID = mgrProj.StatisticsID + INNER JOIN [fp].[FactStatisticsBudget] adminBudg ON obj.StatisticsID = adminBudg.StatisticsID + INNER JOIN [fp].[FactStatisticsBudget] mgrBudg ON obj.StatisticsID = mgrBudg.StatisticsID + INNER JOIN [fp].[FactStatisticsHistory] hist ON obj.StatisticsID = hist.StatisticsID + WHERE + adminProj.BudgetPhaseID = 2 + AND mgrProj.BudgetPhaseID = 3 + AND adminBudg.BudgetPhaseID = 2 + AND mgrBudg.BudgetPhaseID = 3 +GO + + +--------------------------------------------- + +-- fp.viewFactStatistics_Pivoted +CREATE VIEW [fp].[viewFactStatistics_Pivoted] +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-01-31 AO JAZZ-48807 Added BudgetSpreadsLockFlag + ** 2 2023-02-01 NH JAZZ-47035 Added TargetLockType, TargetLockFlag +*************************************************************/ + +SELECT + stat.StatisticsID, + stat.BudgetConfigID, + stat.EntityGroupConfigID, + stat.DepartmentID, + stat.FinancialReportingID, + stat.PayorID, + stat.PatientClassID, + stat.EntityID, + stat.AccountID, + bc.FiscalYearID, + stat.UnitTypeID, + stat.ProviderID, + stat.ProviderSpecialtyID, + stat.ProviderTypeID, + stat.ProviderLineItemID, + stat.SubsectionID, + stat.GroupingGuid, + fbdgt.LockType as TargetLockType, + fbdgt.LockFlag as TargetLockFlag, + dbdgt.LockType as BudgetLockType, + dbdgt.LockFlag as BudgetLockFlag, + dproj.LockType as ProjectionLockType, + dproj.LockFlag as ProjectionLockFlag, + + CASE WHEN dbdgt.LockType = 6 THEN 1 ELSE 0 END AS BudgetSpreadsLockFlag, + + CASE WHEN dbdgt.LockType = 7 THEN 1 ELSE 0 END AS BudgetAdjustmentLockFlag, + CASE WHEN fbdgt.LockType = 7 THEN 1 ELSE 0 END AS TargetAdjustmentLockFlag, + CASE WHEN dproj.LockType = 7 THEN 1 ELSE 0 END AS ProjectionAdjustmentLockFlag, + + fbdgt.AdjustedValueTotal, + dbdgt.AdjustedValueTotal as ManagerAdjustedValueTotal, + + fproj.AdjustedValueTotal as AdjustedProjectionValueTotal, + dproj.AdjustedValueTotal as ManagerAdjustedProjectionValueTotal, + + hist.PriorYearActualValueTotal as PriorYearActualValueTotal, + hist.ActualYTDValueTotal as ActualYTDValueTotal, + hist.CurrentYearBudgetTotal as CurrentYearBudgetTotal, + + stat.InitialBudgetTotal, + stat.InitialProjectionTotal, + + dbdgt.AdjustedValue01 AS ManagerAdjustedValue01, dbdgt.AdjustedValue02 AS ManagerAdjustedValue02, dbdgt.AdjustedValue03 AS ManagerAdjustedValue03, dbdgt.AdjustedValue04 AS ManagerAdjustedValue04, dbdgt.AdjustedValue05 AS ManagerAdjustedValue05, dbdgt.AdjustedValue06 AS ManagerAdjustedValue06, dbdgt.AdjustedValue07 AS ManagerAdjustedValue07, dbdgt.AdjustedValue08 AS ManagerAdjustedValue08, dbdgt.AdjustedValue09 AS ManagerAdjustedValue09, dbdgt.AdjustedValue10 AS ManagerAdjustedValue10, dbdgt.AdjustedValue11 AS ManagerAdjustedValue11, dbdgt.AdjustedValue12 AS ManagerAdjustedValue12, + + fbdgt.AdjustedValue01, fbdgt.AdjustedValue02, fbdgt.AdjustedValue03, fbdgt.AdjustedValue04, fbdgt.AdjustedValue05, fbdgt.AdjustedValue06, fbdgt.AdjustedValue07, fbdgt.AdjustedValue08, fbdgt.AdjustedValue09, fbdgt.AdjustedValue10, fbdgt.AdjustedValue11, fbdgt.AdjustedValue12, + fproj.AdjustedValue01 as AdjustedProjectionValue01, fproj.AdjustedValue02 as AdjustedProjectionValue02, fproj.AdjustedValue03 as AdjustedProjectionValue03, fproj.AdjustedValue04 as AdjustedProjectionValue04, fproj.AdjustedValue05 as AdjustedProjectionValue05, fproj.AdjustedValue06 as AdjustedProjectionValue06, fproj.AdjustedValue07 as AdjustedProjectionValue07, fproj.AdjustedValue08 as AdjustedProjectionValue08, fproj.AdjustedValue09 as AdjustedProjectionValue09, fproj.AdjustedValue10 as AdjustedProjectionValue10, fproj.AdjustedValue11 as AdjustedProjectionValue11, fproj.AdjustedValue12 as AdjustedProjectionValue12, + dproj.AdjustedValue01 as ManagerAdjustedProjectionValue01, dproj.AdjustedValue02 as ManagerAdjustedProjectionValue02, dproj.AdjustedValue03 as ManagerAdjustedProjectionValue03, dproj.AdjustedValue04 as ManagerAdjustedProjectionValue04, dproj.AdjustedValue05 as ManagerAdjustedProjectionValue05, dproj.AdjustedValue06 as ManagerAdjustedProjectionValue06, dproj.AdjustedValue07 as ManagerAdjustedProjectionValue07, dproj.AdjustedValue08 as ManagerAdjustedProjectionValue08, dproj.AdjustedValue09 as ManagerAdjustedProjectionValue09, dproj.AdjustedValue10 as ManagerAdjustedProjectionValue10, dproj.AdjustedValue11 as ManagerAdjustedProjectionValue11, dproj.AdjustedValue12 as ManagerAdjustedProjectionValue12 +FROM + fp.FactStatistics stat + INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON stat.BudgetConfigID = bc.BudgetConfigID + INNER JOIN fp.FactStatisticsBudget fbdgt with (readuncommitted) ON stat.StatisticsID = fbdgt.StatisticsID and fbdgt.BudgetPhaseID = 2 + INNER JOIN fp.FactStatisticsBudget dbdgt with (readuncommitted) ON stat.StatisticsID = dbdgt.StatisticsID and dbdgt.BudgetPhaseID = 3 + INNER JOIN fp.FactStatisticsProjection fproj with (readuncommitted) ON stat.StatisticsID = fproj.StatisticsID and fproj.BudgetPhaseID = 2 + INNER JOIN fp.FactStatisticsProjection dproj with (readuncommitted) ON stat.StatisticsID = dproj.StatisticsID and dproj.BudgetPhaseID = 3 + INNER JOIN fp.FactStatisticsHistory hist with (readuncommitted) ON stat.StatisticsID = hist.StatisticsID +GO + + +--------------------------------------------- + +-- fp.viewFactStatistics_Unpivoted +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-07-20 MD JAZZ-23237 Adding union all for data transfer table +*************************************************************/ + +CREATE VIEW [fp].[viewFactStatistics_Unpivoted] AS +SELECT + BudgetConfigID, + EntityID, + DepartmentID, + AccountID, + PatientClassID, + PayorID, + FinancialReportingID, + UnitTypeID, + TimeClassID, + FiscalMonthID, + FiscalYearID, + OriginalValue, + Value, + ManagerValue, + ProviderID, + ProviderLineItemID, + ProviderSpecialtyID, + ProviderTypeID +FROM fp.FactReportStatistics + +UNION ALL + +SELECT + BudgetConfigID, + EntityID, + DepartmentID, + AccountID, + PatientClassID, + PayorID, + FinancialReportingID, + UnitTypeID, + TimeClassID, + FiscalMonthID, + FiscalYearID, + OriginalValue, + Value, + ManagerValue, + 0 AS ProviderID, + 0 AS ProviderLineItemID, + 0 AS ProviderSpecialtyID, + 0 AS ProviderTypeID +FROM fp.FactReportStatisticsDataTransfer +GO + + +--------------------------------------------- + +-- fp.viewFactStatistics_Unpivoted_BaselineOnly +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-07-18 MY JAZZ-37944 Initial +*************************************************************/ +CREATE VIEW [fp].[viewFactStatistics_Unpivoted_BaselineOnly] +AS +SELECT + ov.StatisticsID, + ov.BudgetConfigID, + ov.EntityID, + ov.DepartmentID, + ov.AccountID, + ov.PatientClassID, + ov.PayorID, + ov.FinancialReportingID, + ov.ProviderID, + ov.ProviderTypeID, + ov.ProviderSpecialtyID, + ov.ProviderLineItemID, + ov.SubsectionID, + ov.UnitTypeID, + 2 as TimeClassID, + ov.FiscalMonthID, + bc.FiscalYearID, + ov.InitialValue as OriginalValue +FROM ( + -- Unpivot for OriginalValue + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, + FinancialReportingID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT cv.* + FROM fp.FactStatistics cv ) cv + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov +INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFactStatistics_Unpivoted_archive +CREATE VIEW fp.viewFactStatistics_Unpivoted_archive AS SELECT * FROM fp.FactReportStatistics_archive +GO + + +--------------------------------------------- + +-- fp.viewFactStatistics_Unpivoted_source +CREATE VIEW fp.viewFactStatistics_Unpivoted_source +AS +SELECT + ov.StatisticsID, + ov.BudgetConfigID, + ov.EntityID, + ov.DepartmentID, + ov.AccountID, + ov.PatientClassID, + ov.PayorID, + ov.FinancialReportingID, + ov.ProviderID, + ov.ProviderTypeID, + ov.ProviderSpecialtyID, + ov.ProviderLineItemID, + ov.SubsectionID, + ov.UnitTypeID, + 2 as TimeClassID, + ov.FiscalMonthID, + bc.FiscalYearID, + ov.InitialValue as OriginalValue, + v.Value, + mgrv.Value as ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, + FinancialReportingID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT cv.* + FROM fp.FactStatistics cv ) cv + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudget', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, + FinancialReportingID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT cv.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactStatistics cv + INNER JOIN fp.FactStatisticsBudget bdgt ON cv.StatisticsID = bdgt.StatisticsID + WHERE bdgt.BudgetPhaseID = 2) cv + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.BudgetConfigID = v.BudgetConfigID + AND ov.EntityID = v.EntityID + AND ov.DepartmentID = v.DepartmentID + AND ov.AccountID = v.AccountID + AND ov.PatientClassID = v.PatientClassID + AND ov.PayorID = v.PayorID + AND ov.FinancialReportingID = v.FinancialReportingID + AND ov.ProviderID = v.ProviderID + AND ov.ProviderTypeID = v.ProviderTypeID + AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID + AND ov.ProviderLineItemID = v.ProviderLineItemID + AND ov.SubsectionID = v.SubsectionID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN ( + -- Unpivot for Manager Value + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, + FinancialReportingID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT cv.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactStatistics cv + INNER JOIN fp.FactStatisticsBudget bdgt ON cv.StatisticsID = bdgt.StatisticsID + WHERE bdgt.BudgetPhaseID = 3) cv + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.EntityID = mgrv.EntityID + AND ov.DepartmentID = mgrv.DepartmentID + AND ov.AccountID = mgrv.AccountID + AND ov.PatientClassID = mgrv.PatientClassID + AND ov.PayorID = mgrv.PayorID + AND ov.FinancialReportingID = mgrv.FinancialReportingID + AND ov.ProviderID = mgrv.ProviderID + AND ov.ProviderTypeID = mgrv.ProviderTypeID + AND ov.ProviderSpecialtyID = mgrv.ProviderSpecialtyID + AND ov.ProviderLineItemID = mgrv.ProviderLineItemID + AND ov.SubsectionID = mgrv.SubsectionID + AND ov.UnitTypeID = mgrv.UnitTypeID + AND ov.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID + +UNION ALL + +SELECT + ov.StatisticsID, + ov.BudgetConfigID, + ov.EntityID, + ov.DepartmentID, + ov.AccountID, + ov.PatientClassID, + ov.PayorID, + ov.FinancialReportingID, + ov.ProviderID, + ov.ProviderTypeID, + ov.ProviderSpecialtyID, + ov.ProviderLineItemID, + ov.SubsectionID, + ov.UnitTypeID, + 12 as TimeClassID, + ov.FiscalMonthID, + bc.FiscalYearID - 1, + ov.InitialValue as OriginalValue, + v.Value, + mgrv.Value as ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, + FinancialReportingID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, UnitTypeID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT cv.* + FROM fp.FactStatistics cv ) cv + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjection', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, + FinancialReportingID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT cv.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactStatistics cv + INNER JOIN fp.FactStatisticsProjection bdgt ON cv.StatisticsID = bdgt.StatisticsID + WHERE bdgt.BudgetPhaseID = 2) cv + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON ov.BudgetConfigID = v.BudgetConfigID + AND ov.EntityID = v.EntityID + AND ov.DepartmentID = v.DepartmentID + AND ov.AccountID = v.AccountID + AND ov.PatientClassID = v.PatientClassID + AND ov.PayorID = v.PayorID + AND ov.FinancialReportingID = v.FinancialReportingID + AND ov.ProviderID = v.ProviderID + AND ov.ProviderTypeID = v.ProviderTypeID + AND ov.ProviderSpecialtyID = v.ProviderSpecialtyID + AND ov.ProviderLineItemID = v.ProviderLineItemID + AND ov.SubsectionID = v.SubsectionID + AND ov.UnitTypeID = v.UnitTypeID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN ( + -- Unpivot for Manager Value + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, + FinancialReportingID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT cv.*, bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactStatistics cv + INNER JOIN fp.FactStatisticsProjection bdgt ON cv.StatisticsID = bdgt.StatisticsID + WHERE bdgt.BudgetPhaseID = 3) cv + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.EntityID = mgrv.EntityID + AND ov.DepartmentID = mgrv.DepartmentID + AND ov.AccountID = mgrv.AccountID + AND ov.PatientClassID = mgrv.PatientClassID + AND ov.PayorID = mgrv.PayorID + AND ov.FinancialReportingID = mgrv.FinancialReportingID + AND ov.ProviderID = mgrv.ProviderID + AND ov.ProviderTypeID = mgrv.ProviderTypeID + AND ov.ProviderSpecialtyID = mgrv.ProviderSpecialtyID + AND ov.ProviderLineItemID = mgrv.ProviderLineItemID + AND ov.SubsectionID = mgrv.SubsectionID + AND ov.UnitTypeID = mgrv.UnitTypeID + AND ov.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN [fp].[BudgetConfig] bc ON ov.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewFlexConfigMapping +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 4-27-2023 MY JAZZ-54239 Add SourceDepartment to view +*************************************************************/ +CREATE VIEW fp.viewFlexConfigMapping +AS +SELECT bc.BudgetConfigID, fcm.EntityGroupConfigID, fcm.SourceDepartmentID, fcm.DepartmentID, fcm.GLAccountID, fcm.StatAccountID, fcm.FlexingTypeID, fcm.PRJobCodeID, fcm.ChargeCodeID, fcm.PatientClassID, fcm.DependentStatisticAccountID +FROM [fp].[FlexConfigMapping] fcm + INNER JOIN [fp].[EntityGroupConfig] egc ON fcm.EntityGroupConfigID = egc.EntityGroupConfigID + INNER JOIN [fp].[BudgetConfig] bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID +GO + + +--------------------------------------------- + +-- fp.viewGeneralLedger +CREATE VIEW fp.viewGeneralLedger + AS + SELECT + gl.GeneralLedgerID, + gl.BudgetConfigID, + gl.EntityGroupConfigID, + gl.DepartmentID, + gl.FinancialReportingID, + gl.VariabilityID, + gl.EntityID, + gl.AccountID, + gl.APEModelSectionID, + msm.APEModelSectionName, + + TargetLockType, + TargetLockFlag, + BudgetLockType, + BudgetLockFlag, + ProjectionLockType, + ProjectionLockFlag, + + gl.InitialBudgetTotal, + gl.InitialProjectionTotal, + TargetAdjustedTotal, + BudgetAdjustedTotal, + ProjectionAdjustedTotal AS AdjustedProjectionValueTotal, + + gl.InitialBudget01, + gl.InitialBudget02, + gl.InitialBudget03, + gl.InitialBudget04, + gl.InitialBudget05, + gl.InitialBudget06, + gl.InitialBudget07, + gl.InitialBudget08, + gl.InitialBudget09, + gl.InitialBudget10, + gl.InitialBudget11, + gl.InitialBudget12, + + gl.InitialProjection01, + gl.InitialProjection02, + gl.InitialProjection03, + gl.InitialProjection04, + gl.InitialProjection05, + gl.InitialProjection06, + gl.InitialProjection07, + gl.InitialProjection08, + gl.InitialProjection09, + gl.InitialProjection10, + gl.InitialProjection11, + gl.InitialProjection12, + + TargetAdjusted01, + TargetAdjusted02, + TargetAdjusted03, + TargetAdjusted04, + TargetAdjusted05, + TargetAdjusted06, + TargetAdjusted07, + TargetAdjusted08, + TargetAdjusted09, + TargetAdjusted10, + TargetAdjusted11, + TargetAdjusted12, + + BudgetAdjusted01, + BudgetAdjusted02, + BudgetAdjusted03, + BudgetAdjusted04, + BudgetAdjusted05, + BudgetAdjusted06, + BudgetAdjusted07, + BudgetAdjusted08, + BudgetAdjusted09, + BudgetAdjusted10, + BudgetAdjusted11, + BudgetAdjusted12, + + ProjectionAdjusted01 AS AdjustedProjectionValue01, + ProjectionAdjusted02 AS AdjustedProjectionValue02, + ProjectionAdjusted03 AS AdjustedProjectionValue03, + ProjectionAdjusted04 AS AdjustedProjectionValue04, + ProjectionAdjusted05 AS AdjustedProjectionValue05, + ProjectionAdjusted06 AS AdjustedProjectionValue06, + ProjectionAdjusted07 AS AdjustedProjectionValue07, + ProjectionAdjusted08 AS AdjustedProjectionValue08, + ProjectionAdjusted09 AS AdjustedProjectionValue09, + ProjectionAdjusted10 AS AdjustedProjectionValue10, + ProjectionAdjusted11 AS AdjustedProjectionValue11, + ProjectionAdjusted12 AS AdjustedProjectionValue12 + +FROM fp.GeneralLedger gl +INNER JOIN (SELECT DISTINCT APEModelSEctionID, APEModelSectionName FROM fp.ModelSectionMap) msm ON gl.APEModelSectionID = msm.APEModelSectionID +GO + + +--------------------------------------------- + +-- fp.viewGeneralLedgerAdjustment +CREATE VIEW fp.viewGeneralLedgerAdjustment +AS +SELECT AdjustmentGUID, + BudgetConfigGUID, + AdjustmentType, + Value, + AdjustmentFilterJSON, + GroupingHierarchyJSON, + AdjustedProperty, + Comment, + AuthorGUID, + AuthorFullName, + LastModifiedDateUtc, + DateCreatedUtc, + UnitTypeID, + GroupingGUID, + TimeClassID, + BudgetPhaseID, + ClassificationGroupID, + ClassificationCategoryID, + IsRecordDeleted, + DimensionMemberJson, + AdjustmentID, + IsErrored +FROM [fp].[GeneralLedgerAdjustment] +WHERE IsRecordDeleted = 0; +GO + + +--------------------------------------------- + +-- fp.viewGeneralLedgerAdjustmentAdjustmentJsonBreakdown +CREATE VIEW fp.viewGeneralLedgerAdjustmentAdjustmentJsonBreakdown +AS +SELECT + BudgetConfigGUID, + AdjustmentID, + AdjustmentGUID, + AdjustmentType, + GroupingGUID, + CASE WHEN AdjustmentType IN (12, 13, 14) THEN 1 WHEN AdjustmentType IN (0, 2) AND GroupingGUID != '00000000-0000-0000-0000-000000000000' THEN 1 ELSE 0 END IsRollUp, + IsRecordDeleted, + IsErrored, + DepartmentID, + DepartmentName, + AccountID, + AccountName, + FinancialReportingID, + FinancialReportingName, + EntityID, + EntityName, + AdjustmentFilterJSON, + AdjJson.DepartmentJSON, + AdjJson.AccountJSON, + AdjJson.FinancialReportingJSON, + AdjJson.EntityJSON +FROM fp.GeneralLedgerAdjustment +CROSS APPLY OPENJSON(AdjustmentFilterJSON) +WITH ( + DepartmentJSON NVARCHAR(MAX) '$.Department' AS JSON, + AccountJSON NVARCHAR(MAX) '$.Account' AS JSON, + FinancialReportingJSON NVARCHAR(MAX) '$.FinancialReporting' AS JSON, + EntityJSON NVARCHAR(MAX) '$.Entity' AS JSON +) AS AdjJson +OUTER APPLY OPENJSON(DepartmentJSON) WITH ( + DepartmentID VARCHAR(200) '$.ID', + DepartmentName NVARCHAR(100) '$.Name', + DepartmentCode NVARCHAR(100) '$.Code', + DepartmentPathID NVARCHAR(100) '$.PathID' +) +OUTER APPLY OPENJSON(AccountJSON) WITH ( + AccountID VARCHAR(200) '$.ID', + AccountName NVARCHAR(100) '$.Name', + AccountCode NVARCHAR(100) '$.Code', + AccountPathID NVARCHAR(100) '$.PathID' +) +OUTER APPLY OPENJSON(FinancialReportingJSON) WITH ( + FinancialReportingID VARCHAR(200) '$.ID', + FinancialReportingName NVARCHAR(100) '$.Name', + FinancialReportingCode NVARCHAR(100) '$.Code', + FinancialReportingPathID NVARCHAR(100) '$.PathID' +) +OUTER APPLY OPENJSON(EntityJSON) WITH ( + EntityID VARCHAR(200) '$.ID', + EntityName NVARCHAR(100) '$.Name', + EntityCode NVARCHAR(100) '$.Code', + EntityPathID NVARCHAR(100) '$.PathID' +) +GO + + +--------------------------------------------- + +-- fp.viewGeneralLedgerAdjustmentImport +CREATE VIEW [fp].[viewGeneralLedgerAdjustmentImport] +AS +SELECT [RowID] + ,[AdjustmentGUID] + ,[DepartmentID] + ,[AccountID] + ,[FinancialReportingID] + ,[FiscalYearID] + ,[UnitTypeID] + ,[FiscalMonthID] + ,[Value] + ,[Version] + ,[VariabilityID] + ,[EntityID] + ,[TimeClassID] + ,[BudgetPhaseID] + ,[IsRecordDeleted] + ,[AdjustmentID] + ,[OriginalUnitTypeID] +FROM [fp].[GeneralLedgerAdjustmentImport] +WHERE IsRecordDeleted = 0 +GO + + +--------------------------------------------- + +-- fp.viewGeneralLedgerDataForStatsToNonStaffing +CREATE VIEW fp.viewGeneralLedgerDataForStatsToNonStaffing AS + +SELECT GeneralLedgerID, EntityGroupConfigID, DepartmentID, AccountID, FlexingTypeID, + TargetAdjusted01, + TargetAdjusted02, + TargetAdjusted03, + TargetAdjusted04, + TargetAdjusted05, + TargetAdjusted06, + TargetAdjusted07, + TargetAdjusted08, + TargetAdjusted09, + TargetAdjusted10, + TargetAdjusted11, + TargetAdjusted12, + BudgetAdjusted01, + BudgetAdjusted02, + BudgetAdjusted03, + BudgetAdjusted04, + BudgetAdjusted05, + BudgetAdjusted06, + BudgetAdjusted07, + BudgetAdjusted08, + BudgetAdjusted09, + BudgetAdjusted10, + BudgetAdjusted11, + BudgetAdjusted12, + ProjectionAdjusted01, + ProjectionAdjusted02, + ProjectionAdjusted03, + ProjectionAdjusted04, + ProjectionAdjusted05, + ProjectionAdjusted06, + ProjectionAdjusted07, + ProjectionAdjusted08, + ProjectionAdjusted09, + ProjectionAdjusted10, + ProjectionAdjusted11, + ProjectionAdjusted12,TargetDollarsPerUOSAdjusted01, + TargetDollarsPerUOSAdjusted02, + TargetDollarsPerUOSAdjusted03, + TargetDollarsPerUOSAdjusted04, + TargetDollarsPerUOSAdjusted05, + TargetDollarsPerUOSAdjusted06, + TargetDollarsPerUOSAdjusted07, + TargetDollarsPerUOSAdjusted08, + TargetDollarsPerUOSAdjusted09, + TargetDollarsPerUOSAdjusted10, + TargetDollarsPerUOSAdjusted11, + TargetDollarsPerUOSAdjusted12, + BudgetDollarsPerUOSAdjusted01, + BudgetDollarsPerUOSAdjusted02, + BudgetDollarsPerUOSAdjusted03, + BudgetDollarsPerUOSAdjusted04, + BudgetDollarsPerUOSAdjusted05, + BudgetDollarsPerUOSAdjusted06, + BudgetDollarsPerUOSAdjusted07, + BudgetDollarsPerUOSAdjusted08, + BudgetDollarsPerUOSAdjusted09, + BudgetDollarsPerUOSAdjusted10, + BudgetDollarsPerUOSAdjusted11, + BudgetDollarsPerUOSAdjusted12, + ProjectionDollarsPerUOSAdjusted01, + ProjectionDollarsPerUOSAdjusted02, + ProjectionDollarsPerUOSAdjusted03, + ProjectionDollarsPerUOSAdjusted04, + ProjectionDollarsPerUOSAdjusted05, + ProjectionDollarsPerUOSAdjusted06, + ProjectionDollarsPerUOSAdjusted07, + ProjectionDollarsPerUOSAdjusted08, + ProjectionDollarsPerUOSAdjusted09, + ProjectionDollarsPerUOSAdjusted10, + ProjectionDollarsPerUOSAdjusted11, + ProjectionDollarsPerUOSAdjusted12 + FROM [fp].[GeneralLedger] WHERE VariabilityID = 2 +GO + + +--------------------------------------------- + +-- fp.viewGeneralLedgerFlexConfig +CREATE VIEW fp.viewGeneralLedgerFlexConfig +AS +SELECT EntityGroupConfigGUID, DepartmentID, AccountID, FlexMethodID +FROM [fp].[viewNonStaffingExpenseFlexingConfig] + +UNION ALL + +SELECT EntityGroupConfigGUID, DepartmentID, AccountID, FlexMethodID +FROM [fp].[viewRevenueExpenseFlexingConfig] + +UNION ALL + +SELECT EntityGroupConfigGUID, DepartmentID, AccountID, FlexMethodID +FROM [fp].[viewDeductionsFlexingConfig] +GO + + +--------------------------------------------- + +-- fp.viewGeneralLedgerInitialPlanConfigDetailLogs +CREATE VIEW fp.viewGeneralLedgerInitialPlanConfigDetailLogs AS + +SELECT RowID, + BudgetConfigGUID, + BudgetConfigID, + EntityID, + DepartmentID, + AccountID, + FinancialReportingID, + VariabilityID, + APEModelSectionID, + TimeClassID, + ProjectionMethodID, + TrailingMonths, + VersionID + FROM [fp].[GeneralLedgerInitialPlanConfigDetailHistory] + UNION + SELECT RowID, + BudgetConfigGUID, + BudgetConfigID, + EntityID, + DepartmentID, + AccountID, + FinancialReportingID, + VariabilityID, + APEModelSectionID, + TimeClassID, + ProjectionMethodID, + TrailingMonths, + VersionID + FROM [fp].[GeneralLedgerInitialPlanConfigDetail] +GO + + +--------------------------------------------- + +-- fp.viewGeneralLedgerItemizationDetail +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-08-05 YR JAZZ-39315 Added column 'CategoryID' +** 2 2022-08-16 DM JAZZ-35820 Added LastModified columns +** 3 2024-03-15 AO JAZZ-65797 Table rename +** 4 2024-06-12 NH JAZZ-69119 Added IsSetValue field +*************************************************************/ +CREATE VIEW [fp].[viewGeneralLedgerItemizationDetail] +AS +WITH deletedAdjustments(CommentGUID) AS (SELECT OriginalAdjustmentCommentGUID AS CommentGUID + FROM fp.GeneralLedgerItemizationDetailLink + UNION ALL + SELECT InverseAdjustmentCommentGUID AS CommentGUID + FROM fp.GeneralLedgerItemizationDetailLink) + SELECT glid.CommentGUID, glid.AdjustmentID, glid.BudgetConfigID, glid.DepartmentID, glid.FinancialReportingID, glid.AccountID, glid.TimeClassID, glid.DollarsValue, glid.Comment, glid.CategoryID, glid.SortOrder, glid.SpreadID, glid.IsMarkedForDeletion, + glid.AuthorGUID, glid.AuthorFullName, glid.DateCreatedUTC, glid.LastModifiedAuthorFullName, glid.LastModifiedDateUtc, glid.LastModifiedAuthorGUID, glid.SpreadPercentage01, glid.SpreadPercentage02, glid.SpreadPercentage03, glid.SpreadPercentage04, glid.SpreadPercentage05, glid.SpreadPercentage06, + glid.SpreadPercentage07, glid.SpreadPercentage08, glid.SpreadPercentage09, glid.SpreadPercentage10, glid.SpreadPercentage11, glid.SpreadPercentage12, glid.TotalImportedValue, glid.IsSetValue + FROM fp.GeneralLedgerFixedDetail AS glid LEFT OUTER JOIN + deletedAdjustments AS del ON glid.CommentGUID = del.CommentGUID + WHERE (del.CommentGUID IS NULL) +GO + + +--------------------------------------------- + +-- fp.viewGeneralLedgerManagerComments +CREATE view [fp].[viewGeneralLedgerManagerComments] +as +select + ROW_NUMBER() OVER(ORDER BY DepartmentID ASC) AS RowID, + bc.BudgetConfigID, + glc.DepartmentID, + glc.AccountID, + glc.FiscalYearID, + glc.Comment, + glc.InitialValue, + glc.DeltaValue as Adjustment, + glc.InitialValue + glc.DeltaValue as FinalValue, + glc.DateCreatedUtc, + glc.AuthorFullName, + glc.DateModifiedUtc, + CAST(glc.DateCreatedUtc at time zone 'UTC' at time zone 'CENTRAL STANDARD TIME' as DateTime) as DateCreated, + CAST(glc.DateModifiedUtc at time zone 'UTC' at time zone 'CENTRAL STANDARD TIME' as DateTime) as DateModified, + dc.CalendarDateTime as DateCreatedDate +from + fp.GeneralLedgerManagerAdjustmentComment as glc + inner join fp.BudgetConfig as bc on bc.BudgetConfigGUID = glc.BudgetConfigGUID + inner join [fw].[DimDate] as dc on CAST(glc.DateCreatedUtc AS DATE) = dc.CalendarDateTime +GO + + +--------------------------------------------- + +-- fp.viewGeneralLedgerMyBudgetReportData +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2021-09-03 MY JAZZ-23920 Filter out deleted itemized adjustments from report +** 2 2022-06-08 DM JAZZ-37699 Added sub-account detail adjustments for new data type +** 3 2022-06-28 YR JAZZ-36123 Rename 'Comment' to 'Description' +** 4 2022-07-07 MV JAZZ-39283 Add Sub Account Detail CategoryID +** 5 2022-07-20 SD JAZZ-35821 Add variable adjustments +** 6 2022-08-05 YR JAZZ-39315 Add CategoryID for viewGeneralLedgerItemizationDetail +** 7 2022-08-17 DM JAZZ-35820 Added LastModified columns for viewGeneralLedgerItemizationDetail +** 8 2022-08-22 SD JAZZ-42351 Added grouping stats data by budgetConfig +** 9 2023-08-25 MY JAZZ-58152 Update to new structure +** 10 2024-05-03 MZ JAZZ-69734 Renamed GeneralLedgerAdjustmentItemization to GeneralLedgerMyBudgetAdjustment +** 11 2024-06-12 NH JAZZ-69119 My Budgets Non-Staffing redesign: Update Itemization Report to show Set Value adjustments +** 12 2024-07-09 NH JAZZ-73268 Non-Staffing and Other Revenue Non-itemized: update Description to be a Comment +** 13 2024-07-21 NH JAZZ-73268 Non-Staffing and Other Revenue Non-itemized: updated Description/Comment +*************************************************************/ +CREATE VIEW [fp].[viewGeneralLedgerMyBudgetReportData] +AS + + -- TODO: The formatting of this view is attorciious and needs to be cleaned up the next time someone works on this view for a fix. + +WITH distinctVariableDetails AS ( + SELECT + f.BudgetConfigID, f.AccountID, f.DepartmentID, f.FinancialReportingID, f.TimeClassID, f.AdjustmentID, f.DollarsValue, a.Comment_All as Comment, a.AuthorFullName_All as AuthorFullName , a.DateCreated, + ROW_NUMBER() OVER(PARTITION BY f.BudgetConfigID, f.AccountID, f.DepartmentID, f.FinancialReportingID, f.TimeClassID ORDER BY f.DateCreatedUTC DESC) AS row_number + FROM [fp].[GeneralLedgerVariableDetail] f + INNER JOIN + ( + select t.BudgetConfigID, t.AccountID, t.DepartmentID, t.FinancialReportingID, t.TimeClassID, + STRING_AGG(CAST(t.AuthorFullName AS NVARCHAR(MAX)), '; ') Within GROUP (order by t.DateCreatedUTC DESC) As AuthorFullName_All, + STRING_AGG(CAST(t.Comment AS NVARCHAR(MAX)), '; ') Within GROUP (order by t.DateCreatedUTC DESC) As Comment_All, + STRING_AGG(CONVERT(VARCHAR, CAST(t.DateCreatedUtc AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DateTime)), '; ') Within GROUP (order by t.DateCreatedUTC DESC) as DateCreated + From [fp].[GeneralLedgerVariableDetail] t + LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone' + Group By BudgetConfigID, AccountID, DepartmentID, FinancialReportingID, TimeClassID + ) a on f.BudgetConfigID = a.BudgetConfigID + and f.AccountID = a.AccountID + and f.DepartmentID = a.DepartmentID + and f.FinancialReportingID = a.FinancialReportingID + and f.TimeClassID = a.TimeClassID + ), + distinctFixedDetails AS ( + SELECT + f.BudgetConfigID, + f.AccountID, + f.DepartmentID, + f.FinancialReportingID, + f.TimeClassID, + f.AdjustmentID, + f.DollarsValue, + a.Comment_All as Comment, + a.AuthorFullName_All as AuthorFullName, + a.DateCreated, + f.SpreadID, + f.SpreadPercentage01, + f.SpreadPercentage02, + f.SpreadPercentage03, + f.SpreadPercentage04, + f.SpreadPercentage05, + f.SpreadPercentage06, + f.SpreadPercentage07, + f.SpreadPercentage08, + f.SpreadPercentage09, + f.SpreadPercentage10, + f.SpreadPercentage11, + f.SpreadPercentage12, + ROW_NUMBER() OVER(PARTITION BY f.BudgetConfigID, f.AccountID, f.DepartmentID, f.FinancialReportingID, f.TimeClassID ORDER BY f.DateCreatedUTC DESC) AS row_number + FROM [fp].GeneralLedgerFixedDetail f + INNER JOIN + ( + select t.BudgetConfigID, t.AccountID, t.DepartmentID, t.FinancialReportingID, t.TimeClassID, + STRING_AGG(CAST(t.AuthorFullName AS NVARCHAR(MAX)), '; ') Within GROUP (order by t.DateCreatedUTC DESC) As AuthorFullName_All, + STRING_AGG(CAST(t.Comment AS NVARCHAR(MAX)), '; ') Within GROUP (order by t.DateCreatedUTC DESC) As Comment_All, + STRING_AGG(CONVERT(VARCHAR, CAST(t.DateCreatedUtc AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DateTime)), '; ') Within GROUP (order by t.DateCreatedUTC DESC) as DateCreated + From [fp].GeneralLedgerFixedDetail t + LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone' + Group By BudgetConfigID, AccountID, DepartmentID, FinancialReportingID, TimeClassID + ) a on f.BudgetConfigID = a.BudgetConfigID + and f.AccountID = a.AccountID + and f.DepartmentID = a.DepartmentID + and f.FinancialReportingID = a.FinancialReportingID + and f.TimeClassID = a.TimeClassID + WHERE IsSetValue = 1 + ), + + distinctGLAdjItemized AS (select DISTINCT AccountID, DepartmentID, BudgetConfigID, EntityID, FinancialReportingID, TimeClassID, VariabilityID from + fp.GeneralLedgerMyBudgetAdjustment), + + projectionGLData AS ( + select gl.AccountID, gl.DepartmentID, gl.EntityID, gl.FinancialReportingID, gl.BudgetConfigID, + gl.ProjectionAdjusted01 AS AdjustedValue01, gl.ProjectionAdjusted02 AS AdjustedValue02, gl.ProjectionAdjusted03 AS AdjustedValue03, + gl.ProjectionAdjusted04 AS AdjustedValue04, gl.ProjectionAdjusted05 AS AdjustedValue05, gl.ProjectionAdjusted06 AS AdjustedValue06, + gl.ProjectionAdjusted07 AS AdjustedValue07, gl.ProjectionAdjusted08 AS AdjustedValue08, gl.ProjectionAdjusted09 AS AdjustedValue09, + gl.ProjectionAdjusted10 AS AdjustedValue10, gl.ProjectionAdjusted11 AS AdjustedValue11, gl.ProjectionAdjusted12 AS AdjustedValue12, + gl.ProjectionAdjustedTotal AS AdjustedValueTotal + from + fp.GeneralLedger gl + INNER JOIN distinctGLAdjItemized gli + on + gli.AccountID = gl.AccountID and + gli.DepartmentID = gl.DepartmentID and + gli.BudgetConfigID = gl.BudgetConfigID and + gli.EntityID = gl.EntityID and + gli.FinancialReportingID = gl.FinancialReportingID and + gl.VariabilityID = gli.VariabilityID and + gli.TimeClassID = 12 and + gl.VariabilityID = 2 + ), + + projectionGLFixedData AS ( + select gl.AccountID, gl.DepartmentID, gl.EntityID, gl.FinancialReportingID, gl.BudgetConfigID, + gl.ProjectionAdjusted01 AS AdjustedValue01, gl.ProjectionAdjusted02 AS AdjustedValue02, gl.ProjectionAdjusted03 AS AdjustedValue03, + gl.ProjectionAdjusted04 AS AdjustedValue04, gl.ProjectionAdjusted05 AS AdjustedValue05, gl.ProjectionAdjusted06 AS AdjustedValue06, + gl.ProjectionAdjusted07 AS AdjustedValue07, gl.ProjectionAdjusted08 AS AdjustedValue08, gl.ProjectionAdjusted09 AS AdjustedValue09, + gl.ProjectionAdjusted10 AS AdjustedValue10, gl.ProjectionAdjusted11 AS AdjustedValue11, gl.ProjectionAdjusted12 AS AdjustedValue12, + gl.ProjectionAdjustedTotal AS AdjustedValueTotal + from + fp.GeneralLedger gl + INNER JOIN distinctGLAdjItemized gli + on + gli.AccountID = gl.AccountID and + gli.DepartmentID = gl.DepartmentID and + gli.BudgetConfigID = gl.BudgetConfigID and + gli.EntityID = gl.EntityID and + gli.FinancialReportingID = gl.FinancialReportingID and + gl.VariabilityID = gli.VariabilityID and + gli.TimeClassID = 12 and + gl.VariabilityID = 1 + ), + + statsData AS (SELECT + glai.AccountID, + glai.DepartmentID, + s.BudgetConfigID, + ISNULL(SUM(s.ManagerAdjustedValue01),0) AS ManagerAdjustedValue01, + ISNULL(SUM(s.ManagerAdjustedValue02),0) AS ManagerAdjustedValue02, + ISNULL(SUM(s.ManagerAdjustedValue03),0) AS ManagerAdjustedValue03, + ISNULL(SUM(s.ManagerAdjustedValue04),0) AS ManagerAdjustedValue04, + ISNULL(SUM(s.ManagerAdjustedValue05),0) AS ManagerAdjustedValue05, + ISNULL(SUM(s.ManagerAdjustedValue06),0) AS ManagerAdjustedValue06, + ISNULL(SUM(s.ManagerAdjustedValue07),0) AS ManagerAdjustedValue07, + ISNULL(SUM(s.ManagerAdjustedValue08),0) AS ManagerAdjustedValue08, + ISNULL(SUM(s.ManagerAdjustedValue09),0) AS ManagerAdjustedValue09, + ISNULL(SUM(s.ManagerAdjustedValue10),0) AS ManagerAdjustedValue10, + ISNULL(SUM(s.ManagerAdjustedValue11),0) AS ManagerAdjustedValue11, + ISNULL(SUM(s.ManagerAdjustedValue12),0) AS ManagerAdjustedValue12, + ISNULL(SUM(s.ManagerAdjustedValueTotal),0) AS ManagerAdjustedValueTotal, + ISNULL(SUM(s.ManagerAdjustedProjectionValue01),0) AS ManagerAdjustedProjectionValue01, + ISNULL(SUM(s.ManagerAdjustedProjectionValue02),0) AS ManagerAdjustedProjectionValue02, + ISNULL(SUM(s.ManagerAdjustedProjectionValue03),0) AS ManagerAdjustedProjectionValue03, + ISNULL(SUM(s.ManagerAdjustedProjectionValue04),0) AS ManagerAdjustedProjectionValue04, + ISNULL(SUM(s.ManagerAdjustedProjectionValue05),0) AS ManagerAdjustedProjectionValue05, + ISNULL(SUM(s.ManagerAdjustedProjectionValue06),0) AS ManagerAdjustedProjectionValue06, + ISNULL(SUM(s.ManagerAdjustedProjectionValue07),0) AS ManagerAdjustedProjectionValue07, + ISNULL(SUM(s.ManagerAdjustedProjectionValue08),0) AS ManagerAdjustedProjectionValue08, + ISNULL(SUM(s.ManagerAdjustedProjectionValue09),0) AS ManagerAdjustedProjectionValue09, + ISNULL(SUM(s.ManagerAdjustedProjectionValue10),0) AS ManagerAdjustedProjectionValue10, + ISNULL(SUM(s.ManagerAdjustedProjectionValue11),0) AS ManagerAdjustedProjectionValue11, + ISNULL(SUM(s.ManagerAdjustedProjectionValue12),0) AS ManagerAdjustedProjectionValue12, + ISNULL(SUM(s.ManagerAdjustedProjectionValueTotal),0) AS ManagerAdjustedProjectionValueTotal, + glai.TimeClassID + From [fp].[viewFactStatistics_Pivoted] s + INNER JOIN distinctGLAdjItemized as glai + on glai.DepartmentID = s.DepartmentID + AND glai.BudgetConfigID = s.BudgetConfigID + AND glai.VariabilityID = 2 + INNER JOIN fp.BudgetConfig bc on bc.BudgetConfigID = glai.BudgetConfigID + INNER JOIN fp.EntityGroupConfig egc on egc.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN ( + SELECT DISTINCT DepartmentID, GLAccountID, StatAccountID, EntityGroupConfigID + FROM [fp].[FlexConfigMapping] + ) As fcm + ON glai.DepartmentID = fcm.DepartmentID + AND glai.AccountID = fcm.GLAccountID + AND egc.EntityGroupConfigID = fcm.EntityGroupConfigID + AND s.AccountID = fcm.StatAccountID + Group By glai.AccountID, glai.DepartmentID, glai.TimeClassID, s.BudgetConfigID) + +SELECT a.BudgetConfigID, + a.EntityID, + a.DepartmentID, + a.AccountID, + a.TimeClassID, + a.DateCreated, + a.AuthorFullName, + a.Comment AS 'Description/Comment', + a.CategoryID, + a.ItemizationDataTypeID, + a.Month01, + a.Month02, + a.Month03, + a.Month04, + a.Month05, + a.Month06, + a.Month07, + a.Month08, + a.Month09, + a.Month10, + a.Month11, + a.Month12, + a.TotalValue, ROW_NUMBER() OVER(ORDER BY BUDGETCONFIGID) AS RowID +FROM ( + SELECT + rd.BudgetConfigID, + rd.EntityID, + rd.DepartmentID, + rd.AccountID, + rd.TimeClassID, + '' AS DateCreated, + '' AS AuthorFullName, + '' AS Comment, + 0 AS CategoryID, + rd.ItemizationDataTypeID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + TotalValue + FROM fp.GeneralLedgerItemizationReportData rd + + UNION ALL + + -- select variable admin projection adj +Select + m.BudgetConfigID, + m.EntityID, + m.DepartmentID, + m.AccountID, + m.TimeClassID, + m.DateCreated, + m.AuthorFullName, + m.Comment, + m.CategoryID, + m.ItemizationDataTypeID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + m.AdjustedValueTotal - (m.ManagerAdjMonth01 + m.ManagerAdjMonth02 + m.ManagerAdjMonth03 + m.ManagerAdjMonth04 + m.ManagerAdjMonth05 + m.ManagerAdjMonth06 + m.ManagerAdjMonth07 + m.ManagerAdjMonth08 + m.ManagerAdjMonth09 + m.ManagerAdjMonth10 + m.ManagerAdjMonth11 + m.ManagerAdjMonth12) AS TotalValue + from ( + SELECT + gli.BudgetConfigID, + gli.EntityID, + gli.DepartmentID, + gli.AccountID, + gli.TimeClassID, + '' AS DateCreated, + '' AS AuthorFullName, + '' AS Comment, + 0 AS CategoryID, + 6 AS ItemizationDataTypeID, + CASE WHEN bc.MonthsLoaded >= 1 THEN 0 ELSE phd.AdjustedValue01 - gli.Value01 * sd.ManagerAdjustedProjectionValue01 END AS Month01, + CASE WHEN bc.MonthsLoaded >= 2 THEN 0 ELSE phd.AdjustedValue02 - gli.Value02 * sd.ManagerAdjustedProjectionValue02 END AS Month02, + CASE WHEN bc.MonthsLoaded >= 3 THEN 0 ELSE phd.AdjustedValue03 - gli.Value03 * sd.ManagerAdjustedProjectionValue03 END AS Month03, + CASE WHEN bc.MonthsLoaded >= 4 THEN 0 ELSE phd.AdjustedValue04 - gli.Value04 * sd.ManagerAdjustedProjectionValue04 END AS Month04, + CASE WHEN bc.MonthsLoaded >= 5 THEN 0 ELSE phd.AdjustedValue05 - gli.Value05 * sd.ManagerAdjustedProjectionValue05 END AS Month05, + CASE WHEN bc.MonthsLoaded >= 6 THEN 0 ELSE phd.AdjustedValue06 - gli.Value06 * sd.ManagerAdjustedProjectionValue06 END AS Month06, + CASE WHEN bc.MonthsLoaded >= 7 THEN 0 ELSE phd.AdjustedValue07 - gli.Value07 * sd.ManagerAdjustedProjectionValue07 END AS Month07, + CASE WHEN bc.MonthsLoaded >= 8 THEN 0 ELSE phd.AdjustedValue08 - gli.Value08 * sd.ManagerAdjustedProjectionValue08 END AS Month08, + CASE WHEN bc.MonthsLoaded >= 9 THEN 0 ELSE phd.AdjustedValue09 - gli.Value09 * sd.ManagerAdjustedProjectionValue09 END AS Month09, + CASE WHEN bc.MonthsLoaded >= 10 THEN 0 ELSE phd.AdjustedValue10 - gli.Value10 * sd.ManagerAdjustedProjectionValue10 END AS Month10, + CASE WHEN bc.MonthsLoaded >= 11 THEN 0 ELSE phd.AdjustedValue11 - gli.Value11 * sd.ManagerAdjustedProjectionValue11 END AS Month11, + CASE WHEN bc.MonthsLoaded >= 12 THEN 0 ELSE phd.AdjustedValue12 - gli.Value12 * sd.ManagerAdjustedProjectionValue12 END AS Month12, + + CASE WHEN bc.MonthsLoaded >= 1 THEN phd.AdjustedValue01 ELSE gli.Value01 * sd.ManagerAdjustedProjectionValue01 END AS ManagerAdjMonth01, + CASE WHEN bc.MonthsLoaded >= 2 THEN phd.AdjustedValue02 ELSE gli.Value02 * sd.ManagerAdjustedProjectionValue02 END AS ManagerAdjMonth02, + CASE WHEN bc.MonthsLoaded >= 3 THEN phd.AdjustedValue03 ELSE gli.Value03 * sd.ManagerAdjustedProjectionValue03 END AS ManagerAdjMonth03, + CASE WHEN bc.MonthsLoaded >= 4 THEN phd.AdjustedValue04 ELSE gli.Value04 * sd.ManagerAdjustedProjectionValue04 END AS ManagerAdjMonth04, + CASE WHEN bc.MonthsLoaded >= 5 THEN phd.AdjustedValue05 ELSE gli.Value05 * sd.ManagerAdjustedProjectionValue05 END AS ManagerAdjMonth05, + CASE WHEN bc.MonthsLoaded >= 6 THEN phd.AdjustedValue06 ELSE gli.Value06 * sd.ManagerAdjustedProjectionValue06 END AS ManagerAdjMonth06, + CASE WHEN bc.MonthsLoaded >= 7 THEN phd.AdjustedValue07 ELSE gli.Value07 * sd.ManagerAdjustedProjectionValue07 END AS ManagerAdjMonth07, + CASE WHEN bc.MonthsLoaded >= 8 THEN phd.AdjustedValue08 ELSE gli.Value08 * sd.ManagerAdjustedProjectionValue08 END AS ManagerAdjMonth08, + CASE WHEN bc.MonthsLoaded >= 9 THEN phd.AdjustedValue09 ELSE gli.Value09 * sd.ManagerAdjustedProjectionValue09 END AS ManagerAdjMonth09, + CASE WHEN bc.MonthsLoaded >= 10 THEN phd.AdjustedValue10 ELSE gli.Value10 * sd.ManagerAdjustedProjectionValue10 END AS ManagerAdjMonth10, + CASE WHEN bc.MonthsLoaded >= 11 THEN phd.AdjustedValue11 ELSE gli.Value11 * sd.ManagerAdjustedProjectionValue11 END AS ManagerAdjMonth11, + CASE WHEN bc.MonthsLoaded >= 12 THEN phd.AdjustedValue12 ELSE gli.Value12 * sd.ManagerAdjustedProjectionValue12 END AS ManagerAdjMonth12, + phd.AdjustedValueTotal + FROM fp.GeneralLedgerMyBudgetAdjustment gli + INNER JOIN projectionGLData phd on + gli.BudgetConfigID = phd.BudgetConfigID + AND gli.DepartmentID = phd.DepartmentID + AND gli.FinancialReportingID = phd.FinancialReportingID + AND gli.AccountID = phd.AccountID + AND gli.EntityID = phd.EntityID + AND gli.FinancialReportingID = phd.FinancialReportingID + INNER JOIN distinctVariableDetails glvd on + gli.AdjustmentID = glvd.AdjustmentID + AND gli.BudgetConfigID = glvd.BudgetConfigID + AND gli.DepartmentID = glvd.DepartmentID + AND gli.FinancialReportingID = glvd.FinancialReportingID + AND gli.AccountID = glvd.AccountID + AND gli.FinancialReportingID = glvd.FinancialReportingID + AND gli.TimeClassID = glvd.TimeClassID + JOIN fp.BudgetConfig bc ON gli.BudgetConfigID = bc.BudgetConfigID + LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone' + INNER JOIN statsData sd on gli.AccountID = sd.AccountID and gli.DepartmentID = sd.DepartmentID and sd.TimeClassID = gli.TimeClassID and gli.BudgetConfigID = sd.BudgetConfigID + WHERE + gli.TimeClassID = 12 + AND gli.VariabilityID = 2 + and glvd.row_number = 1 ) m + where ( + Month01 <> 0 OR + Month02 <> 0 OR + Month03 <> 0 OR + Month04 <> 0 OR + Month05 <> 0 OR + Month06 <> 0 OR + Month07 <> 0 OR + Month08 <> 0 OR + Month09 <> 0 OR + Month10 <> 0 OR + Month11 <> 0 OR + Month12 <> 0 ) + + UNION ALL + + -- select variable admin budget adj + select + gli.BudgetConfigID, + gli.EntityID, + gli.DepartmentID, + gli.AccountID, + gli.TimeClassID, + '' AS DateCreated, + '' AS AuthorFullName, + '' as Comment, + 0 AS CategoryID, + 6 AS ItemizationDataTypeID, + gl.BudgetAdjusted01 - gli.Value01 * sd.ManagerAdjustedValue01 AS Month01, + gl.BudgetAdjusted02 - gli.Value02 * sd.ManagerAdjustedValue02 AS Month02, + gl.BudgetAdjusted03 - gli.Value03 * sd.ManagerAdjustedValue03 AS Month03, + gl.BudgetAdjusted04 - gli.Value04 * sd.ManagerAdjustedValue04 AS Month04, + gl.BudgetAdjusted05 - gli.Value05 * sd.ManagerAdjustedValue05 AS Month05, + gl.BudgetAdjusted06 - gli.Value06 * sd.ManagerAdjustedValue06 AS Month06, + gl.BudgetAdjusted07 - gli.Value07 * sd.ManagerAdjustedValue07 AS Month07, + gl.BudgetAdjusted08 - gli.Value08 * sd.ManagerAdjustedValue08 AS Month08, + gl.BudgetAdjusted09 - gli.Value09 * sd.ManagerAdjustedValue09 AS Month09, + gl.BudgetAdjusted10 - gli.Value10 * sd.ManagerAdjustedValue10 AS Month10, + gl.BudgetAdjusted11 - gli.Value11 * sd.ManagerAdjustedValue11 AS Month11, + gl.BudgetAdjusted12 - gli.Value12 * sd.ManagerAdjustedValue12 AS Month12, + gl.BudgetAdjustedTotal - glvd.DollarsValue * sd.ManagerAdjustedValueTotal AS TotalValue + from fp.GeneralLedger gl + Inner join fp.GeneralLedgerMyBudgetAdjustment gli on + gli.BudgetConfigID = gl.BudgetConfigID + AND gli.DepartmentID = gl.DepartmentID + AND gli.FinancialReportingID = gl.FinancialReportingID + AND gli.AccountID = gl.AccountID + AND gli.TimeClassID = 2 + INNER JOIN distinctVariableDetails glvd on gli.AdjustmentID = glvd.AdjustmentID + AND gli.BudgetConfigID = glvd.BudgetConfigID + AND gli.DepartmentID = glvd.DepartmentID + AND gli.FinancialReportingID = glvd.FinancialReportingID + AND gli.AccountID = glvd.AccountID + AND gli.TimeClassID = glvd.TimeClassID + JOIN fp.BudgetConfig bc ON gli.BudgetConfigID = bc.BudgetConfigID + LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone' + INNER JOIN statsData sd on gli.AccountID = sd.AccountID and gli.DepartmentID = sd.DepartmentID and sd.TimeClassID = 2 and gli.BudgetConfigID = sd.BudgetConfigID + Where + gl.VariabilityID = 2 and + glvd.row_number = 1 and + ( gl.BudgetAdjusted01 - gli.Value01 * sd.ManagerAdjustedValue01 <> 0 OR + gl.BudgetAdjusted02 - gli.Value02 * sd.ManagerAdjustedValue02 <> 0 OR + gl.BudgetAdjusted03 - gli.Value03 * sd.ManagerAdjustedValue03 <> 0 OR + gl.BudgetAdjusted04 - gli.Value04 * sd.ManagerAdjustedValue04 <> 0 OR + gl.BudgetAdjusted05 - gli.Value05 * sd.ManagerAdjustedValue05 <> 0 OR + gl.BudgetAdjusted06 - gli.Value06 * sd.ManagerAdjustedValue06 <> 0 OR + gl.BudgetAdjusted07 - gli.Value07 * sd.ManagerAdjustedValue07 <> 0 OR + gl.BudgetAdjusted08 - gli.Value08 * sd.ManagerAdjustedValue08 <> 0 OR + gl.BudgetAdjusted09 - gli.Value09 * sd.ManagerAdjustedValue09 <> 0 OR + gl.BudgetAdjusted10 - gli.Value10 * sd.ManagerAdjustedValue10 <> 0 OR + gl.BudgetAdjusted11 - gli.Value11 * sd.ManagerAdjustedValue11 <> 0 OR + gl.BudgetAdjusted12 - gli.Value12 * sd.ManagerAdjustedValue12 <> 0 ) + + + UNION ALL + + SELECT + gli.BudgetConfigID, + gli.EntityID, + gli.DepartmentID, + gli.AccountID, + gli.TimeClassID, + CASE WHEN DATEDIFF(ss, glid.DateCreatedUTC, glid.LastModifiedDateUtc) = 0 THEN CONVERT(varchar, CAST(glid.DateCreatedUtc AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DateTime)) + ELSE CONCAT(CONVERT(varchar, CAST(glid.DateCreatedUtc AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DATETIME)), ', ', + CONVERT(varchar, CAST(glid.LastModifiedDateUtc AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DATETIME))) END AS DateCreated, + CASE WHEN DATEDIFF(ss, glid.DateCreatedUTC, glid.LastModifiedDateUtc) = 0 THEN glid.AuthorFullName ELSE glid.AuthorFullName + ', ' + glid.LastModifiedAuthorFullName END AS AuthorFullName, + glid.Comment, + glid.CategoryID, + 3 AS ItemizationDataTypeID, + CASE WHEN glid.SpreadID = 0 + THEN glid.DollarsValue / 12 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage01 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage01 as decimal(19,8)) + END AS Month01, + CASE WHEN glid.SpreadID = 0 + THEN glid.DollarsValue / 12 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage02 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage02 as decimal(19,8)) + END AS Month02, + CASE WHEN glid.SpreadID = 0 + THEN glid.DollarsValue / 12 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage03 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage03 as decimal(19,8)) + END AS Month03, + CASE WHEN glid.SpreadID = 0 + THEN glid.DollarsValue / 12 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage04 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage04 as decimal(19,8)) + END AS Month04, + CASE WHEN glid.SpreadID = 0 + THEN glid.DollarsValue / 12 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage05 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage05 as decimal(19,8)) + END AS Month05, + CASE WHEN glid.SpreadID = 0 + THEN glid.DollarsValue / 12 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage06 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage06 as decimal(19,8)) + END AS Month06, + CASE WHEN glid.SpreadID = 0 + THEN glid.DollarsValue / 12 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage07 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage07 as decimal(19,8)) + END AS Month07, + CASE WHEN glid.SpreadID = 0 + THEN glid.DollarsValue / 12 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage08 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage08 as decimal(19,8)) + END AS Month08, + CASE WHEN glid.SpreadID = 0 + THEN glid.DollarsValue / 12 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage09 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage09 as decimal(19,8)) + END AS Month09, + CASE WHEN glid.SpreadID = 0 + THEN glid.DollarsValue / 12 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage10 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage10 as decimal(19,8)) + END AS Month10, + CASE WHEN glid.SpreadID = 0 + THEN glid.DollarsValue / 12 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage11 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage11 as decimal(19,8)) + END AS Month11, + CASE WHEN glid.SpreadID = 0 + THEN glid.DollarsValue / 12 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage12 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage12 as decimal(19,8)) + END AS Month12, + glid.DollarsValue as TotalValue + FROM fp.GeneralLedgerMyBudgetAdjustment gli + JOIN fp.viewGeneralLedgerItemizationDetail glid ON gli.AdjustmentID = glid.AdjustmentID + AND gli.BudgetConfigID = glid.BudgetConfigID + AND gli.DepartmentID = glid.DepartmentID + AND gli.FinancialReportingID = glid.FinancialReportingID + AND gli.AccountID = glid.AccountID + AND gli.TimeClassID = glid.TimeClassID + JOIN fp.GlobalSpread gs on glid.SpreadID = gs.GlobalSpreadID + JOIN fp.BudgetConfig bc ON gli.BudgetConfigID = bc.BudgetConfigID + LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone' + WHERE + glid.TimeClassID = 2 + AND gli.VariabilityID = 1 + AND glid.IsSetValue = 0 + + UNION ALL + + SELECT + gli.BudgetConfigID, + gli.EntityID, + gli.DepartmentID, + gli.AccountID, + gli.TimeClassID, + CASE WHEN DATEDIFF(ss, glid.DateCreatedUTC, glid.LastModifiedDateUtc) = 0 THEN CONVERT(varchar, CAST(glid.DateCreatedUtc AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DateTime)) + ELSE CONCAT(CONVERT(varchar, CAST(glid.DateCreatedUtc AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DATETIME)), ', ', + CONVERT(varchar, CAST(glid.LastModifiedDateUtc AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DATETIME))) END AS DateCreated, + CASE WHEN DATEDIFF(ss, glid.DateCreatedUTC, glid.LastModifiedDateUtc) = 0 THEN glid.AuthorFullName ELSE glid.AuthorFullName + ', ' + glid.LastModifiedAuthorFullName END AS AuthorFullName, + glid.Comment, + glid.CategoryID, + 3 AS ItemizationDataTypeID, + CASE WHEN bc.MonthsLoaded < 1 THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month01, + CASE WHEN bc.MonthsLoaded < 2 THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month02, + CASE WHEN bc.MonthsLoaded < 3 THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month03, + CASE WHEN bc.MonthsLoaded < 4 THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month04, + CASE WHEN bc.MonthsLoaded < 5 THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month05, + CASE WHEN bc.MonthsLoaded < 6 THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month06, + CASE WHEN bc.MonthsLoaded < 7 THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month07, + CASE WHEN bc.MonthsLoaded < 8 THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month08, + CASE WHEN bc.MonthsLoaded < 9 THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month09, + CASE WHEN bc.MonthsLoaded < 10 THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month10, + CASE WHEN bc.MonthsLoaded < 11 THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month11, + CASE WHEN bc.MonthsLoaded < 12 THEN glid.DollarsValue / (12 - bc.MonthsLoaded) ELSE 0 END AS Month12, + glid.DollarsValue as TotalValue + FROM fp.GeneralLedgerMyBudgetAdjustment gli + JOIN fp.viewGeneralLedgerItemizationDetail glid ON gli.AdjustmentID = glid.AdjustmentID + AND gli.BudgetConfigID = glid.BudgetConfigID + AND gli.DepartmentID = glid.DepartmentID + AND gli.FinancialReportingID = glid.FinancialReportingID + AND gli.AccountID = glid.AccountID + AND gli.TimeClassID = glid.TimeClassID + JOIN fp.GlobalSpread gs on glid.SpreadID = gs.GlobalSpreadID + JOIN fp.BudgetConfig bc ON gli.BudgetConfigID = bc.BudgetConfigID + LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone' + WHERE + glid.TimeClassID = 12 + and gli.VariabilityID = 1 + AND glid.IsSetValue = 0 + +UNION ALL + +SELECT + gli.BudgetConfigID, + gli.EntityID, + gli.DepartmentID, + gli.AccountID, + gli.TimeClassID, + glvd.DateCreated, + glvd.AuthorFullName AS AuthorFullName, + glvd.Comment, + 0 AS CategoryID, + 3 AS ItemizationDataTypeID, + CASE WHEN bc.MonthsLoaded < 1 THEN gli.Value01 ELSE 0 END AS Month01, + CASE WHEN bc.MonthsLoaded < 2 THEN gli.Value02 ELSE 0 END AS Month02, + CASE WHEN bc.MonthsLoaded < 3 THEN gli.Value03 ELSE 0 END AS Month03, + CASE WHEN bc.MonthsLoaded < 4 THEN gli.Value04 ELSE 0 END AS Month04, + CASE WHEN bc.MonthsLoaded < 5 THEN gli.Value05 ELSE 0 END AS Month05, + CASE WHEN bc.MonthsLoaded < 6 THEN gli.Value06 ELSE 0 END AS Month06, + CASE WHEN bc.MonthsLoaded < 7 THEN gli.Value07 ELSE 0 END AS Month07, + CASE WHEN bc.MonthsLoaded < 8 THEN gli.Value08 ELSE 0 END AS Month08, + CASE WHEN bc.MonthsLoaded < 9 THEN gli.Value09 ELSE 0 END AS Month09, + CASE WHEN bc.MonthsLoaded < 10 THEN gli.Value10 ELSE 0 END AS Month10, + CASE WHEN bc.MonthsLoaded < 11 THEN gli.Value11 ELSE 0 END AS Month11, + CASE WHEN bc.MonthsLoaded < 12 THEN gli.Value12 ELSE 0 END AS Month12, + glvd.DollarsValue as TotalValue + FROM fp.GeneralLedgerMyBudgetAdjustment gli + JOIN distinctFixedDetails glvd ON gli.AdjustmentID = glvd.AdjustmentID + AND gli.BudgetConfigID = glvd.BudgetConfigID + AND gli.DepartmentID = glvd.DepartmentID + AND gli.FinancialReportingID = glvd.FinancialReportingID + AND gli.AccountID = glvd.AccountID + AND gli.TimeClassID = glvd.TimeClassID + JOIN fp.BudgetConfig bc ON gli.BudgetConfigID = bc.BudgetConfigID + LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone' + WHERE + glvd.TimeClassID = 12 + AND gli.VariabilityID = 1 + AND glvd.row_number = 1 + + UNION ALL + + Select + m.BudgetConfigID, + m.EntityID, + m.DepartmentID, + m.AccountID, + m.TimeClassID, + m.DateCreated, + m.AuthorFullName, + m.Comment, + m.CategoryID, + m.ItemizationDataTypeID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + m.AdjustedValueTotal - (m.ManagerAdjMonth01 + m.ManagerAdjMonth02 + m.ManagerAdjMonth03 + m.ManagerAdjMonth04 + m.ManagerAdjMonth05 + m.ManagerAdjMonth06 + m.ManagerAdjMonth07 + m.ManagerAdjMonth08 + m.ManagerAdjMonth09 + m.ManagerAdjMonth10 + m.ManagerAdjMonth11 + m.ManagerAdjMonth12) AS TotalValue + from (SELECT + gli.BudgetConfigID, + gli.EntityID, + gli.DepartmentID, + gli.AccountID, + gli.TimeClassID, + '' AS DateCreated, + '' AS AuthorFullName, + '' AS Comment, + 0 AS CategoryID, + 2 AS ItemizationDataTypeID, + CASE WHEN bc.MonthsLoaded < 1 THEN phd.AdjustedValue01 - gli.Value01 ELSE 0 END AS Month01, + CASE WHEN bc.MonthsLoaded < 2 THEN phd.AdjustedValue02 - gli.Value02 ELSE 0 END AS Month02, + CASE WHEN bc.MonthsLoaded < 3 THEN phd.AdjustedValue03 - gli.Value03 ELSE 0 END AS Month03, + CASE WHEN bc.MonthsLoaded < 4 THEN phd.AdjustedValue04 - gli.Value04 ELSE 0 END AS Month04, + CASE WHEN bc.MonthsLoaded < 5 THEN phd.AdjustedValue05 - gli.Value05 ELSE 0 END AS Month05, + CASE WHEN bc.MonthsLoaded < 6 THEN phd.AdjustedValue06 - gli.Value06 ELSE 0 END AS Month06, + CASE WHEN bc.MonthsLoaded < 7 THEN phd.AdjustedValue07 - gli.Value07 ELSE 0 END AS Month07, + CASE WHEN bc.MonthsLoaded < 8 THEN phd.AdjustedValue08 - gli.Value08 ELSE 0 END AS Month08, + CASE WHEN bc.MonthsLoaded < 9 THEN phd.AdjustedValue09 - gli.Value09 ELSE 0 END AS Month09, + CASE WHEN bc.MonthsLoaded < 10 THEN phd.AdjustedValue10 - gli.Value10 ELSE 0 END AS Month10, + CASE WHEN bc.MonthsLoaded < 11 THEN phd.AdjustedValue11 - gli.Value11 ELSE 0 END AS Month11, + CASE WHEN bc.MonthsLoaded < 12 THEN phd.AdjustedValue12 - gli.Value12 ELSE 0 END AS Month12, + CASE WHEN bc.MonthsLoaded < 1 THEN gli.Value01 ELSE 0 END AS ManagerAdjMonth01, + CASE WHEN bc.MonthsLoaded < 2 THEN gli.Value02 ELSE 0 END AS ManagerAdjMonth02, + CASE WHEN bc.MonthsLoaded < 3 THEN gli.Value03 ELSE 0 END AS ManagerAdjMonth03, + CASE WHEN bc.MonthsLoaded < 4 THEN gli.Value04 ELSE 0 END AS ManagerAdjMonth04, + CASE WHEN bc.MonthsLoaded < 5 THEN gli.Value05 ELSE 0 END AS ManagerAdjMonth05, + CASE WHEN bc.MonthsLoaded < 6 THEN gli.Value06 ELSE 0 END AS ManagerAdjMonth06, + CASE WHEN bc.MonthsLoaded < 7 THEN gli.Value07 ELSE 0 END AS ManagerAdjMonth07, + CASE WHEN bc.MonthsLoaded < 8 THEN gli.Value08 ELSE 0 END AS ManagerAdjMonth08, + CASE WHEN bc.MonthsLoaded < 9 THEN gli.Value09 ELSE 0 END AS ManagerAdjMonth09, + CASE WHEN bc.MonthsLoaded < 10 THEN gli.Value10 ELSE 0 END AS ManagerAdjMonth10, + CASE WHEN bc.MonthsLoaded < 11 THEN gli.Value11 ELSE 0 END AS ManagerAdjMonth11, + CASE WHEN bc.MonthsLoaded < 12 THEN gli.Value12 ELSE 0 END AS ManagerAdjMonth12, + phd.AdjustedValueTotal, + glvd.DollarsValue as TotalValue + FROM fp.GeneralLedgerMyBudgetAdjustment gli + INNER JOIN projectionGLFixedData phd on + gli.BudgetConfigID = phd.BudgetConfigID + AND gli.DepartmentID = phd.DepartmentID + AND gli.FinancialReportingID = phd.FinancialReportingID + AND gli.AccountID = phd.AccountID + AND gli.EntityID = phd.EntityID + AND gli.FinancialReportingID = phd.FinancialReportingID + JOIN distinctFixedDetails glvd ON gli.AdjustmentID = glvd.AdjustmentID + AND gli.BudgetConfigID = glvd.BudgetConfigID + AND gli.DepartmentID = glvd.DepartmentID + AND gli.FinancialReportingID = glvd.FinancialReportingID + AND gli.AccountID = glvd.AccountID + AND gli.TimeClassID = glvd.TimeClassID + JOIN fp.BudgetConfig bc ON gli.BudgetConfigID = bc.BudgetConfigID + LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone' + WHERE + glvd.TimeClassID = 12 + and gli.VariabilityID = 1 + AND glvd.row_number = 1 ) m + where ( + Month01 <> 0 OR + Month02 <> 0 OR + Month03 <> 0 OR + Month04 <> 0 OR + Month05 <> 0 OR + Month06 <> 0 OR + Month07 <> 0 OR + Month08 <> 0 OR + Month09 <> 0 OR + Month10 <> 0 OR + Month11 <> 0 OR + Month12 <> 0 ) + + UNION ALL + + SELECT + gli.BudgetConfigID, + gli.EntityID, + gli.DepartmentID, + gli.AccountID, + gli.TimeClassID, + glid.DateCreated, + glid.AuthorFullName, + glid.Comment, + 0 as CategoryID, + 3 AS ItemizationDataTypeID, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value01 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage01 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage01 as decimal(19,8)) + END AS Month01, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value02 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage02 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage02 as decimal(19,8)) + END AS Month02, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value03 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage03 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage03 as decimal(19,8)) + END AS Month03, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value04 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage04 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage04 as decimal(19,8)) + END AS Month04, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value05 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage05 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage05 as decimal(19,8)) + END AS Month05, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value06 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage06 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage06 as decimal(19,8)) + END AS Month06, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value07 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage07 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage07 as decimal(19,8)) + END AS Month07, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value08 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage08 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage08 as decimal(19,8)) + END AS Month08, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value09 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage09 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage09 as decimal(19,8)) + END AS Month09, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value10 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage10 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage10 as decimal(19,8)) + END AS Month10, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value11 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage11 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage11 as decimal(19,8)) + END AS Month11, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value12 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage12 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage12 as decimal(19,8)) + END AS Month12, + glid.DollarsValue as TotalValue + FROM fp.GeneralLedgerMyBudgetAdjustment gli + JOIN distinctFixedDetails glid ON gli.AdjustmentID = glid.AdjustmentID + AND gli.BudgetConfigID = glid.BudgetConfigID + AND gli.DepartmentID = glid.DepartmentID + AND gli.FinancialReportingID = glid.FinancialReportingID + AND gli.AccountID = glid.AccountID + AND gli.TimeClassID = glid.TimeClassID + JOIN fp.GlobalSpread gs on glid.SpreadID = gs.GlobalSpreadID + JOIN fp.BudgetConfig bc ON gli.BudgetConfigID = bc.BudgetConfigID + WHERE + glid.TimeClassID = 2 + AND gli.VariabilityID = 1 + AND glid.row_number = 1 + + UNION ALL + + + Select + m.BudgetConfigID, + m.EntityID, + m.DepartmentID, + m.AccountID, + m.TimeClassID, + m.DateCreated, + m.AuthorFullName, + m.Comment, + m.CategoryID, + m.ItemizationDataTypeID, + glMonth01 - ManagerAdjustmentMonth01 AS Month01, + glMonth02 - ManagerAdjustmentMonth02 AS Month02, + glMonth03 - ManagerAdjustmentMonth03 AS Month03, + glMonth04 - ManagerAdjustmentMonth04 AS Month04, + glMonth05 - ManagerAdjustmentMonth05 AS Month05, + glMonth06 - ManagerAdjustmentMonth06 AS Month06, + glMonth07 - ManagerAdjustmentMonth07 AS Month07, + glMonth08 - ManagerAdjustmentMonth08 AS Month08, + glMonth09 - ManagerAdjustmentMonth09 AS Month09, + glMonth10 - ManagerAdjustmentMonth10 AS Month10, + glMonth11 - ManagerAdjustmentMonth11 AS Month11, + glMonth12 - ManagerAdjustmentMonth12 AS Month12, + glTotal - m.TotalValue AS TotalValue + from ( + SELECT + gli.BudgetConfigID, + gli.EntityID, + gli.DepartmentID, + gli.AccountID, + gli.TimeClassID, + '' AS DateCreated, + '' AS AuthorFullName, + '' AS Comment, + 0 as CategoryID, + 2 AS ItemizationDataTypeID, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value01 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage01 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage01 as decimal(19,8)) + END AS ManagerAdjustmentMonth01, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value02 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage02 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage02 as decimal(19,8)) + END AS ManagerAdjustmentMonth02, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value03 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage03 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage03 as decimal(19,8)) + END AS ManagerAdjustmentMonth03, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value04 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage04 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage04 as decimal(19,8)) + END AS ManagerAdjustmentMonth04, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value05 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage05 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage05 as decimal(19,8)) + END AS ManagerAdjustmentMonth05, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value06 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage06 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage06 as decimal(19,8)) + END AS ManagerAdjustmentMonth06, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value07 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage07 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage07 as decimal(19,8)) + END AS ManagerAdjustmentMonth07, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value08 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage08 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage08 as decimal(19,8)) + END AS ManagerAdjustmentMonth08, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value09 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage09 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage09 as decimal(19,8)) + END AS ManagerAdjustmentMonth09, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value10 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage10 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage10 as decimal(19,8)) + END AS ManagerAdjustmentMonth10, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value11 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage11 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage11 as decimal(19,8)) + END AS ManagerAdjustmentMonth11, + CASE WHEN glid.SpreadID = 0 + THEN gli.Value12 + WHEN glid.SpreadID = 1 + THEN cast(glid.DollarsValue * glid.SpreadPercentage12 as decimal(19,8)) + ELSE cast(glid.DollarsValue * gs.SpreadPercentage12 as decimal(19,8)) + END AS ManagerAdjustmentMonth12, + gl.BudgetAdjusted01 as glMonth01, + gl.BudgetAdjusted02 as glMonth02, + gl.BudgetAdjusted03 as glMonth03, + gl.BudgetAdjusted04 as glMonth04, + gl.BudgetAdjusted05 as glMonth05, + gl.BudgetAdjusted06 as glMonth06, + gl.BudgetAdjusted07 as glMonth07, + gl.BudgetAdjusted08 as glMonth08, + gl.BudgetAdjusted09 as glMonth09, + gl.BudgetAdjusted10 as glMonth10, + gl.BudgetAdjusted11 as glMonth11, + gl.BudgetAdjusted12 as glMonth12, + gl.BudgetAdjustedTotal as glTotal, + glid.DollarsValue as TotalValue + FROM fp.GeneralLedger gl + INNER JOIN fp.GeneralLedgerMyBudgetAdjustment gli ON + gli.BudgetConfigID = gl.BudgetConfigID + AND gli.DepartmentID = gl.DepartmentID + AND gli.FinancialReportingID = gl.FinancialReportingID + AND gli.AccountID = gl.AccountID + AND gli.TimeClassID = 2 + AND gli.VariabilityID = gl.VariabilityID + JOIN distinctFixedDetails glid ON gli.AdjustmentID = glid.AdjustmentID + AND gli.BudgetConfigID = glid.BudgetConfigID + AND gli.DepartmentID = glid.DepartmentID + AND gli.FinancialReportingID = glid.FinancialReportingID + AND gli.AccountID = glid.AccountID + AND gli.TimeClassID = glid.TimeClassID + JOIN fp.GlobalSpread gs on glid.SpreadID = gs.GlobalSpreadID + JOIN fp.BudgetConfig bc ON gli.BudgetConfigID = bc.BudgetConfigID + LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone' + WHERE + glid.TimeClassID = 2 + AND gli.VariabilityID = 1 + AND glid.row_number = 1 ) m + where ( + ABS(glMonth01 - ManagerAdjustmentMonth01) > 0.001 OR + ABS(glMonth02 - ManagerAdjustmentMonth02) > 0.001 OR + ABS(glMonth03 - ManagerAdjustmentMonth03) > 0.001 OR + ABS(glMonth04 - ManagerAdjustmentMonth04) > 0.001 OR + ABS(glMonth05 - ManagerAdjustmentMonth05) > 0.001 OR + ABS(glMonth06 - ManagerAdjustmentMonth06) > 0.001 OR + ABS(glMonth07 - ManagerAdjustmentMonth07) > 0.001 OR + ABS(glMonth08 - ManagerAdjustmentMonth08) > 0.001 OR + ABS(glMonth09 - ManagerAdjustmentMonth09) > 0.001 OR + ABS(glMonth10 - ManagerAdjustmentMonth10) > 0.001 OR + ABS(glMonth11 - ManagerAdjustmentMonth11) > 0.001 OR + ABS(glMonth12 - ManagerAdjustmentMonth12) > 0.001 ) + + UNION ALL + + -- for manager variable projection + Select *, + m.Month01 + m.Month02 + m.Month03 + m.Month04 + m.Month05 + m.Month05 + m.Month07 + m.Month08 + m.Month09 + m.Month10 + m.Month11 + m.Month12 AS TotalValue + from ( + SELECT + gli.BudgetConfigID, + gli.EntityID, + gli.DepartmentID, + gli.AccountID, + gli.TimeClassID, + glvd.DateCreated, + glvd.AuthorFullName, + glvd.Comment, + 0 AS CategoryID, + 5 AS ItemizationDataTypeID, + CASE WHEN bc.MonthsLoaded >= 1 THEN phd.AdjustedValue01 ELSE gli.Value01 * sd.ManagerAdjustedProjectionValue01 END AS Month01, + CASE WHEN bc.MonthsLoaded >= 2 THEN phd.AdjustedValue02 ELSE gli.Value02 * sd.ManagerAdjustedProjectionValue02 END AS Month02, + CASE WHEN bc.MonthsLoaded >= 3 THEN phd.AdjustedValue03 ELSE gli.Value03 * sd.ManagerAdjustedProjectionValue03 END AS Month03, + CASE WHEN bc.MonthsLoaded >= 4 THEN phd.AdjustedValue04 ELSE gli.Value04 * sd.ManagerAdjustedProjectionValue04 END AS Month04, + CASE WHEN bc.MonthsLoaded >= 5 THEN phd.AdjustedValue05 ELSE gli.Value05 * sd.ManagerAdjustedProjectionValue05 END AS Month05, + CASE WHEN bc.MonthsLoaded >= 6 THEN phd.AdjustedValue06 ELSE gli.Value06 * sd.ManagerAdjustedProjectionValue06 END AS Month06, + CASE WHEN bc.MonthsLoaded >= 7 THEN phd.AdjustedValue07 ELSE gli.Value07 * sd.ManagerAdjustedProjectionValue07 END AS Month07, + CASE WHEN bc.MonthsLoaded >= 8 THEN phd.AdjustedValue08 ELSE gli.Value08 * sd.ManagerAdjustedProjectionValue08 END AS Month08, + CASE WHEN bc.MonthsLoaded >= 9 THEN phd.AdjustedValue09 ELSE gli.Value09 * sd.ManagerAdjustedProjectionValue09 END AS Month09, + CASE WHEN bc.MonthsLoaded >= 10 THEN phd.AdjustedValue10 ELSE gli.Value10 * sd.ManagerAdjustedProjectionValue10 END AS Month10, + CASE WHEN bc.MonthsLoaded >= 11 THEN phd.AdjustedValue11 ELSE gli.Value11 * sd.ManagerAdjustedProjectionValue11 END AS Month11, + CASE WHEN bc.MonthsLoaded >= 12 THEN phd.AdjustedValue12 ELSE gli.Value12 * sd.ManagerAdjustedProjectionValue12 END AS Month12 + FROM fp.GeneralLedgerMyBudgetAdjustment gli + INNER JOIN projectionGLData phd on + gli.BudgetConfigID = phd.BudgetConfigID + AND gli.DepartmentID = phd.DepartmentID + AND gli.FinancialReportingID = phd.FinancialReportingID + AND gli.AccountID = phd.AccountID + AND gli.EntityID = phd.EntityID + AND gli.FinancialReportingID = phd.FinancialReportingID + INNER JOIN distinctVariableDetails glvd on + gli.AdjustmentID = glvd.AdjustmentID + AND gli.BudgetConfigID = glvd.BudgetConfigID + AND gli.DepartmentID = glvd.DepartmentID + AND gli.FinancialReportingID = glvd.FinancialReportingID + AND gli.AccountID = glvd.AccountID + AND gli.FinancialReportingID = glvd.FinancialReportingID + AND gli.TimeClassID = glvd.TimeClassID + JOIN fp.BudgetConfig bc ON gli.BudgetConfigID = bc.BudgetConfigID + LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone' + INNER JOIN statsData sd on gli.AccountID = sd.AccountID and gli.DepartmentID = sd.DepartmentID and sd.TimeClassID = gli.TimeClassID and gli.BudgetConfigID = sd.BudgetConfigID + WHERE + gli.TimeClassID = 12 + AND gli.VariabilityID = 2 + and glvd.row_number = 1 ) m + + UNION ALL + + + SELECT + gli.BudgetConfigID, + gli.EntityID, + gli.DepartmentID, + gli.AccountID, + gli.TimeClassID, + glvd.DateCreated, + glvd.AuthorFullName, + glvd.Comment, + 0 AS CategoryID, + 5 AS ItemizationDataTypeID, + gli.Value01 * sd.ManagerAdjustedValue01 AS Month01, + gli.Value02 * sd.ManagerAdjustedValue02 AS Month02, + gli.Value03 * sd.ManagerAdjustedValue03 AS Month03, + gli.Value04 * sd.ManagerAdjustedValue04 AS Month04, + gli.Value05 * sd.ManagerAdjustedValue05 AS Month05, + gli.Value06 * sd.ManagerAdjustedValue06 AS Month06, + gli.Value07 * sd.ManagerAdjustedValue07 AS Month07, + gli.Value08 * sd.ManagerAdjustedValue08 AS Month08, + gli.Value09 * sd.ManagerAdjustedValue09 AS Month09, + gli.Value10 * sd.ManagerAdjustedValue10 AS Month10, + gli.Value11 * sd.ManagerAdjustedValue11 AS Month11, + gli.Value12 * sd.ManagerAdjustedValue12 AS Month12, + glvd.DollarsValue * sd.ManagerAdjustedValueTotal AS TotalValue + FROM fp.GeneralLedgerMyBudgetAdjustment gli + INNER JOIN distinctVariableDetails glvd on gli.AdjustmentID = glvd.AdjustmentID + AND gli.BudgetConfigID = glvd.BudgetConfigID + AND gli.DepartmentID = glvd.DepartmentID + AND gli.FinancialReportingID = glvd.FinancialReportingID + AND gli.AccountID = glvd.AccountID + AND gli.TimeClassID = glvd.TimeClassID + JOIN fp.BudgetConfig bc ON gli.BudgetConfigID = bc.BudgetConfigID + LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone' + INNER JOIN statsData sd on gli.AccountID = sd.AccountID and gli.DepartmentID = sd.DepartmentID and sd.TimeClassID = gli.TimeClassID and gli.BudgetConfigID = sd.BudgetConfigID + WHERE + gli.TimeClassID = 2 + AND gli.VariabilityID = 2 + and glvd.row_number = 1 + + UNION ALL + + SELECT + DISTINCT + glsai.BudgetConfigID, + dep.EntityID, + glsai.DepartmentID, + glsai.AccountID, + CASE WHEN glsai.TimeClassID = 12 THEN glsai.TimeClassID ELSE CASE WHEN glsaid.BudgetPhaseID = 2 THEN 20 ELSE 2 END END AS TimeClassID , + CASE WHEN glsaid.LastModifiedAuthorFullName = '' THEN CONVERT(varchar, CAST(glsaid.DateCreatedUtc AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DateTime)) + ELSE CONCAT(CONVERT(varchar, CAST(glsaid.DateCreatedUtc AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DATETIME), 121), ', ', + CONVERT(varchar, CAST(glsaid.LastModifiedDateUtc AT TIME ZONE 'UTC' AT TIME ZONE ss.Value AS DATETIME), 121)) END AS DateCreated, + CASE WHEN glsaid.LastModifiedAuthorFullName = '' THEN glsaid.CreatedAuthorFullName ELSE glsaid.CreatedAuthorFullName + ', ' + glsaid.LastModifiedAuthorFullName END AS AuthorFullName, + glsaid.Description AS Comment, + glsaid.CategoryID, + 4 AS ItemizationDataTypeID, + glsaid.Value01 AS Month01, + glsaid.Value02 AS Month02, + glsaid.Value03 AS Month03, + glsaid.Value04 AS Month04, + glsaid.Value05 AS Month05, + glsaid.Value06 AS Month06, + glsaid.Value07 AS Month07, + glsaid.Value08 AS Month08, + glsaid.Value09 AS Month09, + glsaid.Value10 AS Month10, + glsaid.Value11 AS Month11, + glsaid.Value12 AS Month12, + glsaid.Value01 + glsaid.Value02 + glsaid.Value03 + glsaid.Value04 + glsaid.Value05 + glsaid.Value06 + glsaid.Value07 + glsaid.Value08 + glsaid.Value09 + glsaid.Value10 + glsaid.Value11 + glsaid.Value12 as TotalValue + FROM fp.GeneralLedgerSubAccountItemizedAdjustment glsai + JOIN fp.GeneralLedgerSubAccountItemizedDetail glsaid ON glsai.BudgetConfigID = glsaid.BudgetConfigID + AND glsai.DepartmentID = glsaid.DepartmentID + AND glsai.AccountID = glsaid.AccountID + AND glsai.TimeClassID = glsaid.TimeClassID + AND glsai.BudgetPhaseID = glsaid.BudgetPhaseID + JOIN fp.BudgetConfig bc ON glsai.BudgetConfigID = bc.BudgetConfigID + JOIN fw.DimDepartment dep ON dep.DepartmentId = glsai.DepartmentId + LEFT JOIN fw.SystemSetting ss on ss.Name = 'System Timezone' + WHERE glsai.Itemized = 1 + ) a; +GO + + +--------------------------------------------- + +-- fp.viewGeneralLedgerSpreadUnlockData +CREATE VIEW fp.viewGeneralLedgerSpreadUnlockData +AS + +SELECT [RowID] + ,[BudgetConfigID] + ,[AdjustmentGUID] + ,[EntityID] + ,[DepartmentID] + ,[AccountID] + ,[FinancialReportingID] + ,[Version] + ,[Value01] + ,[Value02] + ,[Value03] + ,[Value04] + ,[Value05] + ,[Value06] + ,[Value07] + ,[Value08] + ,[Value09] + ,[Value10] + ,[Value11] + ,[Value12] + ,[IsRecordDeleted] + FROM [fp].[GeneralLedgerSpreadUnlockData] + WHERE IsRecordDeleted = 0 +GO + + +--------------------------------------------- + +-- fp.viewGeneralLedgerSpreads +CREATE VIEW fp.viewGeneralLedgerSpreads +AS + SELECT [BudgetConfigID], [DepartmentID], [AccountID], [IsInactive], [SpreadPercentage01], [SpreadPercentage02], [SpreadPercentage03], [SpreadPercentage04], [SpreadPercentage05], [SpreadPercentage06], [SpreadPercentage07], [SpreadPercentage08], [SpreadPercentage09], [SpreadPercentage10], [SpreadPercentage11], [SpreadPercentage12], [TotalImportedValue] as TotalSpreadValue, [GlobalSpreadID] + FROM [fp].[GeneralLedgerSpreads] gls with (readuncommitted) + WHERE GlobalSpreadID = 1 + + UNION ALL + + SELECT gls.[BudgetConfigID], [DepartmentID], [AccountID], [IsInactive], gs.[SpreadPercentage01], gs.[SpreadPercentage02], gs.[SpreadPercentage03], gs.[SpreadPercentage04], gs.[SpreadPercentage05], gs.[SpreadPercentage06], gs.[SpreadPercentage07], gs.[SpreadPercentage08], gs.[SpreadPercentage09], gs.[SpreadPercentage10], gs.[SpreadPercentage11], gs.[SpreadPercentage12], gs.TotalSpreadValue, gls.[GlobalSpreadID] + FROM [fp].[GeneralLedgerSpreads] gls with (readuncommitted) + INNER JOIN [fp].[GlobalSpread] gs + ON gls.GlobalSpreadID = gs.GlobalSpreadID + WHERE gls.GlobalSpreadID > 1 +GO + + +--------------------------------------------- + +-- fp.viewGeneralLedgerUOSData +CREATE VIEW [fp].[viewGeneralLedgerUOSData] +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-03-06 NT JAZZ-49040 Cross Department Flexing change +** 2 2024-02-05 MY JAZZ-67147 Adjustments made to variable GL accounts for Depts using source depts as primary stats driver wipes out budgeted data +*************************************************************/ +AS +SELECT + sb.BudgetConfigID, fcm.EntityGroupConfigID, dept.EntityID, fcm.DepartmentID, fcm.GLAccountID AS AccountID, acct.OBDollarsFinancialReportingID AS FinancialReportingID, sb.UnitTypeID, sb.BudgetPhaseID, + SUM(AdjustedValue01) AS AdjustedValue01, SUM(AdjustedValue02) AS AdjustedValue02, SUM(AdjustedValue03) AS AdjustedValue03, SUM(AdjustedValue04) AS AdjustedValue04, SUM(AdjustedValue05) AS AdjustedValue05, SUM(AdjustedValue06) AS AdjustedValue06, SUM(AdjustedValue07) AS AdjustedValue07, SUM(AdjustedValue08) AS AdjustedValue08, SUM(AdjustedValue09) AS AdjustedValue09, SUM(AdjustedValue10) AS AdjustedValue10, SUM(AdjustedValue11) AS AdjustedValue11, SUM(AdjustedValue12) AS AdjustedValue12, SUM(AdjustedValueTotal) AS AdjustedValueTotal, + SUM(AdjustedProjectionValue01) AS AdjustedProjectionValue01, SUM(AdjustedProjectionValue02) AS AdjustedProjectionValue02, SUM(AdjustedProjectionValue03) AS AdjustedProjectionValue03, SUM(AdjustedProjectionValue04) AS AdjustedProjectionValue04, SUM(AdjustedProjectionValue05) AS AdjustedProjectionValue05, SUM(AdjustedProjectionValue06) AS AdjustedProjectionValue06, SUM(AdjustedProjectionValue07) AS AdjustedProjectionValue07, SUM(AdjustedProjectionValue08) AS AdjustedProjectionValue08, SUM(AdjustedProjectionValue09) AS AdjustedProjectionValue09, SUM(AdjustedProjectionValue10) AS AdjustedProjectionValue10, SUM(AdjustedProjectionValue11) AS AdjustedProjectionValue11, SUM(AdjustedProjectionValue12) AS AdjustedProjectionValue12, SUM(AdjustedProjectionValueTotal) AS AdjustedProjectionValueTotal +FROM [fp].[viewFactStatistics] sb + INNER JOIN ( + SELECT DISTINCT bc.BudgetConfigID, fcm.EntityGroupConfigID, DepartmentID, StatAccountID, GLAccountID, SourceDepartmentID + FROM [fp].[FlexConfigMapping] fcm + INNER JOIN fp.EntityGroupConfig egc ON egc.EntityGroupConfigID = fcm.EntityGroupConfigID + INNER JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE FlexingTypeID IN (1, 2) + ) fcm + ON sb.DepartmentID = fcm.SourceDepartmentID + AND sb.AccountID = fcm.StatAccountID + AND sb.BudgetConfigID = fcm.BudgetConfigID + INNER JOIN [fw].[DimAccount] acct ON fcm.GLAccountID = acct.AccountID + INNER JOIN fw.DimDepartment dept ON fcm.DepartmentID = dept.DepartmentID +GROUP BY + sb.BudgetConfigID, fcm.EntityGroupConfigID, dept.EntityID, fcm.DepartmentID, fcm.GLAccountID, acct.OBDollarsFinancialReportingID, sb.UnitTypeID, sb.BudgetPhaseID +GO + + +--------------------------------------------- + +-- fp.viewGeneralLedgerUOSData_Unpivoted +CREATE VIEW fp.viewGeneralLedgerUOSData_Unpivoted +AS +SELECT + v.BudgetConfigID, + v.EntityID, + v.DepartmentID, + v.AccountID, + v.FinancialReportingID, + 2 as TimeClassID, + v.FiscalMonthID, + v.Value, + mgrv.ManagerValue +FROM ( + -- Unpivot for value + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT fs.*, sb.AdjustedValue01, sb.AdjustedValue02, sb.AdjustedValue03, sb.AdjustedValue04, sb.AdjustedValue05, sb.AdjustedValue06, sb.AdjustedValue07, sb.AdjustedValue08, sb.AdjustedValue09, sb.AdjustedValue10, sb.AdjustedValue11, sb.AdjustedValue12 + FROM [fp].[FactStatistics] fs + INNER JOIN [fp].[FactStatisticsBudget] sb ON fs.StatisticsID = sb.StatisticsID + WHERE sb.BudgetPhaseID = 2) sb + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + -- Unpivot for ManagerValue +INNER JOIN ( + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.ManagerValue + FROM ( + SELECT fs.*, sb.AdjustedValue01, sb.AdjustedValue02, sb.AdjustedValue03, sb.AdjustedValue04, sb.AdjustedValue05, sb.AdjustedValue06, sb.AdjustedValue07, sb.AdjustedValue08, sb.AdjustedValue09, sb.AdjustedValue10, sb.AdjustedValue11, sb.AdjustedValue12 + FROM [fp].[FactStatistics] fs + INNER JOIN [fp].[FactStatisticsBudget] sb ON fs.StatisticsID = sb.StatisticsID + WHERE sb.BudgetPhaseID = 3) sb + UNPIVOT ( ManagerValue FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON v.BudgetConfigID = mgrv.BudgetConfigID + AND v.DepartmentID = mgrv.DepartmentID + AND v.AccountID = mgrv.AccountID + AND v.UnitTypeID = mgrv.UnitTypeID + AND v.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN ( + SELECT DISTINCT EntityGroupConfigID, DepartmentID, StatAccountID, GLAccountID + FROM [fp].[FlexConfigMapping] + WHERE FlexingTypeID IN (1, 2) + ) fcm ON v.DepartmentID = fcm.DepartmentID AND v.AccountID = fcm.StatAccountID AND v.EntityGroupConfigID = fcm.EntityGroupConfigID + +UNION ALL + +SELECT + v.BudgetConfigID, + v.EntityID, + v.DepartmentID, + v.AccountID, + v.FinancialReportingID, + 12 as TimeClassID, + v.FiscalMonthID, + v.Value, + mgrv.ManagerValue +FROM ( + -- Unpivot for value + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT fs.*, sb.AdjustedValue01, sb.AdjustedValue02, sb.AdjustedValue03, sb.AdjustedValue04, sb.AdjustedValue05, sb.AdjustedValue06, sb.AdjustedValue07, sb.AdjustedValue08, sb.AdjustedValue09, sb.AdjustedValue10, sb.AdjustedValue11, sb.AdjustedValue12 + FROM [fp].[FactStatistics] fs + INNER JOIN [fp].[FactStatisticsProjection] sb ON fs.StatisticsID = sb.StatisticsID + WHERE sb.BudgetPhaseID = 2) sb + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + -- Unpivot for ManagerValue +INNER JOIN ( + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.ManagerValue + FROM ( + SELECT fs.*, sb.AdjustedValue01, sb.AdjustedValue02, sb.AdjustedValue03, sb.AdjustedValue04, sb.AdjustedValue05, sb.AdjustedValue06, sb.AdjustedValue07, sb.AdjustedValue08, sb.AdjustedValue09, sb.AdjustedValue10, sb.AdjustedValue11, sb.AdjustedValue12 + FROM [fp].[FactStatistics] fs + INNER JOIN [fp].[FactStatisticsProjection] sb ON fs.StatisticsID = sb.StatisticsID + WHERE sb.BudgetPhaseID = 3) sb + UNPIVOT ( ManagerValue FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON v.BudgetConfigID = mgrv.BudgetConfigID + AND v.DepartmentID = mgrv.DepartmentID + AND v.AccountID = mgrv.AccountID + AND v.UnitTypeID = mgrv.UnitTypeID + AND v.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN ( + SELECT DISTINCT EntityGroupConfigID, DepartmentID, StatAccountID, GLAccountID + FROM [fp].[FlexConfigMapping] + WHERE FlexingTypeID IN (1, 2) + ) fcm ON v.DepartmentID = fcm.DepartmentID AND v.AccountID = fcm.StatAccountID AND v.EntityGroupConfigID = fcm.EntityGroupConfigID +GO + + +--------------------------------------------- + +-- fp.viewGeneralLedgerUOSHistoricalData +CREATE VIEW fp.viewGeneralLedgerUOSHistoricalData + AS +SELECT + base.BudgetConfigID, base.EntityID, base.DepartmentID, fcm.GLAccountID As AccountID, acct.OBDollarsFinancialReportingID As FinancialReportingID, 1 As TimeClassID, bc.FiscalYearID - 2 As FiscalYearID, + SUM(ISNULL(basis.PriorYearActualValueTotal, 0)) As Value +FROM [fp].[FactStatistics] As base + INNER JOIN [fp].[BudgetConfig] As bc ON base.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [fp].[FactStatisticsHistory] As basis ON base.StatisticsID = basis.StatisticsID + INNER JOIN [fp].[FlexConfigMapping] As fcm ON base.DepartmentID = fcm.DepartmentID AND base.AccountID = fcm.StatAccountID AND fcm.EntityGroupConfigID = base.EntityGroupConfigID + INNER JOIN [fw].[DimAccount] As acct ON fcm.GLAccountID = acct.AccountID +WHERE FlexingTypeID In (1, 2) +GROUP BY FiscalYearID,base.BudgetConfigID, + base.EntityID, + base.DepartmentID, + fcm.GLAccountID, + acct.OBDollarsFinancialReportingID +UNION ALL +SELECT + base.BudgetConfigID, base.EntityID, base.DepartmentID, fcm.GLAccountID As AccountID, acct.OBDollarsFinancialReportingID As FinancialReportingID, 1 As TimeClassID, bc.FiscalYearID - 1 As FiscalYearID, + SUM(ISNULL(basis.ActualYTDValueTotal, 0)) As Value +FROM [fp].[FactStatistics] As base + INNER JOIN [fp].[BudgetConfig] As bc ON base.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [fp].[FactStatisticsHistory] As basis ON base.StatisticsID = basis.StatisticsID + INNER JOIN [fp].[FlexConfigMapping] As fcm ON base.DepartmentID = fcm.DepartmentID AND base.AccountID = fcm.StatAccountID AND fcm.EntityGroupConfigID = base.EntityGroupConfigID + INNER JOIN [fw].[DimAccount] As acct ON fcm.GLAccountID = acct.AccountID +WHERE FlexingTypeID In (1, 2) +GROUP BY FiscalYearID,base.BudgetConfigID, + base.EntityID, + base.DepartmentID, + fcm.GLAccountID, + acct.OBDollarsFinancialReportingID +UNION ALL +SELECT + base.BudgetConfigID, base.EntityID, base.DepartmentID, fcm.GLAccountID As AccountID, acct.OBDollarsFinancialReportingID As FinancialReportingID, 2 As TimeClassID, bc.FiscalYearID - 1 As FiscalYearID, + SUM(ISNULL(basis.CurrentYearBudgetTotal, 0)) As Value +FROM [fp].[FactStatistics] As base + INNER JOIN [fp].[BudgetConfig] As bc ON base.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [fp].[FactStatisticsHistory] As basis ON base.StatisticsID = basis.StatisticsID + INNER JOIN [fp].[FlexConfigMapping] As fcm ON base.DepartmentID = fcm.DepartmentID AND base.AccountID = fcm.StatAccountID AND fcm.EntityGroupConfigID = base.EntityGroupConfigID + INNER JOIN [fw].[DimAccount] As acct ON fcm.GLAccountID = acct.AccountID +WHERE FlexingTypeID In (1, 2) +GROUP BY FiscalYearID,base.BudgetConfigID, + base.EntityID, + base.DepartmentID, + fcm.GLAccountID, + acct.OBDollarsFinancialReportingID; +GO + + +--------------------------------------------- + +-- fp.viewGeneralLedgerVariability +CREATE VIEW [fp].[viewGeneralLedgerVariability] +AS +SELECT + bc.BudgetConfigID, + av.EntityGroupConfigGUID, + dd.EntityID, + av.DepartmentID, + av.AccountID, + av.FixedPercentage +FROM [fp].[FactAccountVariability] av +INNER JOIN [fp].[EntityGroupConfig] egc +ON av.EntityGroupConfigGUID = egc.EntityGroupConfigGUID +INNER JOIN [fp].[BudgetConfig] bc +ON bc.BudgetConfigGUID = egc.BudgetConfigGUID +INNER JOIN [fw].[DimDepartment] dd +ON dd.DepartmentID = av.DepartmentID +GO + + +--------------------------------------------- + +-- fp.viewGeneralLedger_DepartmentManager +CREATE VIEW fp.viewGeneralLedger_DepartmentManager + AS +WITH targetDollarsPerUOS AS ( +SELECT + GeneralLedgerID, + BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + AccountID, + FinancialReportingID, + APEModelSectionID, + VariabilityID, + TargetLockFlag, + TargetLockType, + m.FiscalMonthID, + 33 As UnitTypeID, + f.Value As TargetValue +FROM + fp.GeneralLedger gl +UNPIVOT (Value For FiscalMonth IN (TargetDollarsPerUOSAdjusted01, TargetDollarsPerUOSAdjusted02, TargetDollarsPerUOSAdjusted03, TargetDollarsPerUOSAdjusted04, TargetDollarsPerUOSAdjusted05, TargetDollarsPerUOSAdjusted06, TargetDollarsPerUOSAdjusted07, TargetDollarsPerUOSAdjusted08, TargetDollarsPerUOSAdjusted09, TargetDollarsPerUOSAdjusted10, TargetDollarsPerUOSAdjusted11, TargetDollarsPerUOSAdjusted12)) f +LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'TargetDollarsPerUOSAdjusted', 'Month') +), +budgetDollarsPerUOS AS +(SELECT + GeneralLedgerID, + BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + AccountID, + FinancialReportingID, + APEModelSectionID, + VariabilityID, + BudgetLockFlag, + BudgetLockType, + m.FiscalMonthID, + 33 As UnitTypeID, + f.Value As BudgetValue +FROM + fp.GeneralLedger gl +UNPIVOT (Value For FiscalMonth IN (BudgetDollarsPerUOSAdjusted01, BudgetDollarsPerUOSAdjusted02, BudgetDollarsPerUOSAdjusted03, BudgetDollarsPerUOSAdjusted04, BudgetDollarsPerUOSAdjusted05, BudgetDollarsPerUOSAdjusted06, BudgetDollarsPerUOSAdjusted07, BudgetDollarsPerUOSAdjusted08, BudgetDollarsPerUOSAdjusted09, BudgetDollarsPerUOSAdjusted10, BudgetDollarsPerUOSAdjusted11, BudgetDollarsPerUOSAdjusted12)) f +LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'BudgetDollarsPerUOSAdjusted', 'Month') +) +SELECT b.GeneralLedgerID, + b.BudgetConfigID, + b.EntityGroupConfigID, + b.EntityID, + b.DepartmentID, + b.AccountID, + b.FinancialReportingID, + b.APEModelSectionID, + b.VariabilityID, + CAST(33 AS TINYINT) AS UnitTypeID, + 2 AS TimeClassID, + bc.FiscalYearID, + t.FiscalMonthID, + CASE WHEN b.BudgetLockFlag = 1 AND b.BudgetLockType = 6 THEN 0 ELSE b.BudgetLockFlag END As HasFinalValueAdjustment, + TargetValue AS Value, + BudgetValue AS ManagerValue +FROM targetDollarsPerUOS t INNER JOIN budgetDollarsPerUOS b ON t.GeneralLedgerID = b.GeneralLedgerID AND t.FiscalMonthID = b.FiscalMonthID +INNER JOIN fp.BudgetConfig bc ON t.BudgetConfigID = bc.BudgetConfigID +UNION +SELECT b.GeneralLedgerID, + b.BudgetConfigID, + b.EntityGroupConfigID, + b.EntityID, + b.DepartmentID, + b.AccountID, + b.FinancialReportingID, + b.APEModelSectionID, + b.VariabilityID, + CAST(34 AS TINYINT) AS UnitTypeID, + 2 AS TimeClassID, + bc.FiscalYearID, + t.FiscalMonthID, + CASE WHEN b.BudgetLockFlag = 1 AND b.BudgetLockType = 6 THEN 0 ELSE b.BudgetLockFlag END As HasFinalValueAdjustment, + TargetValue AS Value, + BudgetValue AS ManagerValue +FROM (SELECT + GeneralLedgerID, + BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + AccountID, + FinancialReportingID, + APEModelSectionID, + VariabilityID, + TargetLockFlag, + TargetLockType, + m.FiscalMonthID, + f.Value As TargetValue + FROM + fp.GeneralLedger gl + UNPIVOT (Value For FiscalMonth IN (TargetAdjusted01, TargetAdjusted02, TargetAdjusted03, TargetAdjusted04, TargetAdjusted05, TargetAdjusted06, TargetAdjusted07, TargetAdjusted08, TargetAdjusted09, TargetAdjusted10, TargetAdjusted11, TargetAdjusted12)) f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'TargetAdjusted', 'Month') + ) t +INNER JOIN + (SELECT + GeneralLedgerID, + BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + AccountID, + FinancialReportingID, + APEModelSectionID, + VariabilityID, + BudgetLockFlag, + BudgetLockType, + m.FiscalMonthID, + f.Value As BudgetValue + FROM + fp.GeneralLedger gl + UNPIVOT (Value For FiscalMonth IN (BudgetAdjusted01, BudgetAdjusted02, BudgetAdjusted03, BudgetAdjusted04, BudgetAdjusted05, BudgetAdjusted06, BudgetAdjusted07, BudgetAdjusted08, BudgetAdjusted09, BudgetAdjusted10, BudgetAdjusted11, BudgetAdjusted12)) f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'BudgetAdjusted', 'Month') + ) b + ON t.GeneralLedgerID = b.GeneralLedgerID + AND t.FiscalMonthID = b.FiscalMonthID +INNER JOIN fp.BudgetConfig bc ON t.BudgetConfigID = bc.BudgetConfigID +UNION +SELECT + GeneralLedgerID, + bc.BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + AccountID, + FinancialReportingID, + APEModelSectionID, + VariabilityID, + CAST(34 AS TINYINT) As UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID - 1 as FiscalYearID, + m.FiscalMonthID, + CASE WHEN ProjectionLockFlag = 1 AND ProjectionLockType = 6 THEN 0 ELSE ProjectionLockFlag END As HasFinalValueAdjustment, + 0 as Value, + f.Value As ManagerValue +FROM + fp.GeneralLedger gl +UNPIVOT (Value For FiscalMonth IN (ProjectionAdjusted01, ProjectionAdjusted02, ProjectionAdjusted03, ProjectionAdjusted04, ProjectionAdjusted05, ProjectionAdjusted06, ProjectionAdjusted07, + ProjectionAdjusted08, ProjectionAdjusted09, ProjectionAdjusted10, ProjectionAdjusted11, ProjectionAdjusted12)) f +LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectionAdjusted', 'Month') +INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = f.BudgetConfigID +UNION +SELECT + GeneralLedgerID, + bc.BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + AccountID, + FinancialReportingID, + APEModelSectionID, + VariabilityID, + 12 as TimeClassID, + bc.FiscalYearID - 1 as FiscalYearID, + m.FiscalMonthID, + CAST(33 AS TINYINT) As UnitTypeID, + 0 as Value, + f.Value As ManagerValue, + CASE WHEN ProjectionLockFlag = 1 AND ProjectionLockType = 6 THEN 0 ELSE ProjectionLockFlag END As HasFinalValueAdjustment +FROM + fp.GeneralLedger gl +UNPIVOT (Value For FiscalMonth IN (ProjectionDollarsPerUOSAdjusted01, ProjectionDollarsPerUOSAdjusted02, ProjectionDollarsPerUOSAdjusted03, ProjectionDollarsPerUOSAdjusted04, ProjectionDollarsPerUOSAdjusted05, ProjectionDollarsPerUOSAdjusted06, ProjectionDollarsPerUOSAdjusted07, + ProjectionDollarsPerUOSAdjusted08, ProjectionDollarsPerUOSAdjusted09, ProjectionDollarsPerUOSAdjusted10, ProjectionDollarsPerUOSAdjusted11, ProjectionDollarsPerUOSAdjusted12)) f +LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectionDollarsPerUOSAdjusted', 'Month') +INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = f.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewGeneralLedger_Pivoted +CREATE VIEW [fp].[viewGeneralLedger_Pivoted] + AS + SELECT + gl.GeneralLedgerID, + gl.BudgetConfigID, + gl.EntityGroupConfigID, + gl.DepartmentID, + gl.FinancialReportingID, + gl.VariabilityID, + gl.EntityID, + gl.AccountID, + bc.FiscalYearID, + 34 AS UnitTypeID, + gl.APEModelSectionID, + + gl.TargetLockType, + gl.TargetLockFlag, + gl.BudgetLockType, + gl.BudgetLockFlag, + gl.ProjectionLockType, + gl.ProjectionLockFlag, + + CASE WHEN gl.BudgetLockType = 6 THEN 1 ELSE 0 END AS BudgetSpreadsLockFlag, + CASE WHEN gl.BudgetLockType = 7 THEN 1 ELSE 0 END AS BudgetAdjustmentLockFlag, + CASE WHEN gl.TargetLockType = 7 THEN 1 ELSE 0 END AS TargetAdjustmentLockFlag, + CASE WHEN gl.ProjectionLockType = 7 THEN 1 ELSE 0 END AS ProjectionAdjustmentLockFlag, + + gl.TargetAdjustedTotal, + gl.BudgetAdjustedTotal, + gl.ProjectionAdjustedTotal, + + hist.PriorYearActualValueTotal as PriorYearActualValueTotal, + hist.ActualYTDValueTotal as ActualYTDValueTotal, + hist.CurrentYearBudgetTotal as CurrentYearBudgetTotal, + + gl.InitialBudgetTotal, + gl.InitialProjectionTotal, + + ISNULL(fgli.InitiativeForecastTotal, 0) as InitiativeForecastTotal, + ISNULL(fgli.InitiativeForecastTotal + gl.BudgetAdjustedTotal, 0) as IntiativeBudgetTotal, + + gl.TargetAdjusted01, gl.TargetAdjusted02, gl.TargetAdjusted03, gl.TargetAdjusted04, + gl.TargetAdjusted05, gl.TargetAdjusted06, gl.TargetAdjusted07, gl.TargetAdjusted08, + gl.TargetAdjusted09, gl.TargetAdjusted10, gl.TargetAdjusted11, gl.TargetAdjusted12, + + gl.BudgetAdjusted01, gl.BudgetAdjusted02, gl.BudgetAdjusted03, gl.BudgetAdjusted04, + gl.BudgetAdjusted05, gl.BudgetAdjusted06, gl.BudgetAdjusted07, gl.BudgetAdjusted08, + gl.BudgetAdjusted09, gl.BudgetAdjusted10, gl.BudgetAdjusted11, gl.BudgetAdjusted12, + + gl.ProjectionAdjusted01, gl.ProjectionAdjusted02, gl.ProjectionAdjusted03, gl.ProjectionAdjusted04, + gl.ProjectionAdjusted05, gl.ProjectionAdjusted06, gl.ProjectionAdjusted07, gl.ProjectionAdjusted08, + gl.ProjectionAdjusted09, gl.ProjectionAdjusted10, gl.ProjectionAdjusted11, gl.ProjectionAdjusted12, + + + gl.TargetDollarsPerUOSAdjusted01, gl.TargetDollarsPerUOSAdjusted02, gl.TargetDollarsPerUOSAdjusted03, gl.TargetDollarsPerUOSAdjusted04, + gl.TargetDollarsPerUOSAdjusted05, gl.TargetDollarsPerUOSAdjusted06, gl.TargetDollarsPerUOSAdjusted07, gl.TargetDollarsPerUOSAdjusted08, + gl.TargetDollarsPerUOSAdjusted09, gl.TargetDollarsPerUOSAdjusted10, gl.TargetDollarsPerUOSAdjusted11, gl.TargetDollarsPerUOSAdjusted12, + + gl.BudgetDollarsPerUOSAdjusted01, gl.BudgetDollarsPerUOSAdjusted02, gl.BudgetDollarsPerUOSAdjusted03, gl.BudgetDollarsPerUOSAdjusted04, + gl.BudgetDollarsPerUOSAdjusted05, gl.BudgetDollarsPerUOSAdjusted06, gl.BudgetDollarsPerUOSAdjusted07, gl.BudgetDollarsPerUOSAdjusted08, + gl.BudgetDollarsPerUOSAdjusted09, gl.BudgetDollarsPerUOSAdjusted10, gl.BudgetDollarsPerUOSAdjusted11, gl.BudgetDollarsPerUOSAdjusted12, + + gl.ProjectionDollarsPerUOSAdjusted01, gl.ProjectionDollarsPerUOSAdjusted02, gl.ProjectionDollarsPerUOSAdjusted03, gl.ProjectionDollarsPerUOSAdjusted04, + gl.ProjectionDollarsPerUOSAdjusted05, gl.ProjectionDollarsPerUOSAdjusted06, gl.ProjectionDollarsPerUOSAdjusted07, gl.ProjectionDollarsPerUOSAdjusted08, + gl.ProjectionDollarsPerUOSAdjusted09, gl.ProjectionDollarsPerUOSAdjusted10, gl.ProjectionDollarsPerUOSAdjusted11, gl.ProjectionDollarsPerUOSAdjusted12, + + ISNULL(fgli.InitiativeForecast01, 0) as InitiativeForecast01, ISNULL(fgli.InitiativeForecast02, 0) as InitiativeForecast02, + ISNULL(fgli.InitiativeForecast03, 0) as InitiativeForecast03, ISNULL(fgli.InitiativeForecast04, 0) as InitiativeForecast04, + ISNULL(fgli.InitiativeForecast05, 0) as InitiativeForecast05, ISNULL(fgli.InitiativeForecast06, 0) as InitiativeForecast06, + ISNULL(fgli.InitiativeForecast07, 0) as InitiativeForecast07, ISNULL(fgli.InitiativeForecast08, 0) as InitiativeForecast08, + ISNULL(fgli.InitiativeForecast09, 0) as InitiativeForecast09, ISNULL(fgli.InitiativeForecast10, 0) as InitiativeForecast10, + ISNULL(fgli.InitiativeForecast11, 0) as InitiativeForecast11, ISNULL(fgli.InitiativeForecast12, 0) as InitiativeForecast12 + FROM + fp.GeneralLedger gl with (readuncommitted) + INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON gl.BudgetConfigID = bc.BudgetConfigID + INNER JOIN fp.GeneralLedgerHistory hist with (readuncommitted) ON gl.GeneralLedgerID = hist.GeneralLedgerID + LEFT JOIN fp.FactGeneralLedgerInitiative fgli with (readuncommitted) ON gl.GeneralLedgerID = fgli.GeneralLedgerID +GO + + +--------------------------------------------- + +-- fp.viewGeneralLedger_Totals +CREATE VIEW fp.viewGeneralLedger_Totals +AS +SELECT + gl.GeneralLedgerID, + gl.BudgetConfigID, + gl.EntityGroupConfigID, + gl.DepartmentID, + gl.FinancialReportingID, + gl.VariabilityID, + gl.EntityID, + gl.AccountID, + gl.APEModelSectionID, + + TargetLockType, + TargetLockFlag, + BudgetLockType, + BudgetLockFlag, + ProjectionLockType, + ProjectionLockFlag, + + gl.InitialBudgetTotal, + gl.InitialProjectionTotal, + TargetAdjustedTotal, + BudgetAdjustedTotal AS ManagerAdjustedTotal, + ProjectionAdjustedTotal As ManagerAdjustedProjectionTotal, + + hist.PriorYearActualValueTotal, + hist.ActualYTDValueTotal, + hist.CurrentYearBudgetTotal +FROM fp.GeneralLedger gl +INNER JOIN fp.GeneralLedgerHistory hist ON gl.GeneralLedgerID = hist.GeneralLedgerID +GO + + +--------------------------------------------- + +-- fp.viewHistoryViewerAccountFlexAssignments +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-09-05 GF B-20335 Created - this view needs refactoring, it hardcodes assumptions about default hierarchies +*************************************************************/ +CREATE VIEW fp.viewHistoryViewerAccountFlexAssignments +AS + with AccFlexConfigAssign as ( + SELECT distinct + JobCodeGroupID = LTRIM(RTRIM(REPLACE(LEFT(JobCodes, LEN(JobCodes) - charindex('|', JobCodes)), '|', ''))), + JobCodeID = CASE + WHEN charindex('|', JobCodes) > 0 + THEN RIGHT(JobCodes, LEN(JobCodes) - charindex('|', JobCodes)) + ELSE NULL + END, + PayCodeGroupID, + ProductiveClassID, + AccountID + ,EntityGroupConfigID + FROM ( + SELECT EntityGroupConfigID, + REPLACE(REPLACE(JobCodeAssignment, 'JOBCODE|JC|', ''),'All','') AS JobCodes + ,CASE + WHEN CHARINDEX('PCG|OBPCG|',PayCodeGroupAssignment) >= 1 + THEN REPLACE(PayCodeGroupAssignment, 'PCG|OBPCG|', '') + ELSE NULL + END AS ProductiveClassID + ,CASE + WHEN CHARINDEX('PCG|OBPCG|',PayCodeGroupAssignment) = 0 + THEN REPLACE(PayCodeGroupAssignment,'All','') + ELSE NULL + END AS PayCodeGroupID + ,AccountID + ,PayCodeGroupAssignment + ,JobCodeAssignment + FROM fp.AccountFlexConfigAssignment afca + inner join fp.AccountFlexConfig afc on afc.FlexConfigGUID = afca.FlexConfigGUID + INNER JOIN [fp].[EntityGroupConfig] EGC on EGC.EntityGroupConfigGUID = afc.EntityGroupConfigGUID + ) SEL1 + ) + SELECT jc.JobCodeID, pcg.PayCodeGroupID,AFCA.EntityGroupConfigID,AFCA.AccountID + FROM AccFlexConfigAssign AFCA + INNER JOIN [fw].[DimJobCode] jc + ON ( + (jc.JobCodeID = AFCA.JobCodeID or AFCA.JobCodeID is null) + and + (jc.JobCodeGroupID = AFCA.JobCodeGroupID or AFCA.JobCodeGroupID is null) + ) + + INNER JOIN fw.DimPayCodeGroup pcg on ( + (pcg.PayCodeGroupID = AFCA.PayCodeGroupID or AFCA.PayCodeGroupID is null) + and + (pcg.ProductiveClassID = AFCA.ProductiveClassID or AFCA.ProductiveClassID is null) + ) +GO + + +--------------------------------------------- + +-- fp.viewInitialPlanRuleLogs +CREATE VIEW fp.viewInitialPlanRuleLogs AS + +SELECT RowID, + BudgetConfigGUID, + BudgetConfigID, + PlanSectionID, + TimeClassID, + SubSectionID, + DimensionalityJSON, + ProjectionMethodID, + TrailingMonths, + RulePriority, + VersionID + FROM [fp].[InitialPlanRuleHistory] + UNION + SELECT RowID, + BudgetConfigGUID, + BudgetConfigID, + PlanSectionID, + TimeClassID, + SubSectionID, + DimensionalityJSON, + ProjectionMethodID, + TrailingMonths, + RulePriority, + VersionID + FROM [fp].[InitialPlanRule] +GO + + +--------------------------------------------- + +-- fp.viewNonStaffingExpenseAccounts +CREATE VIEW [fp].[viewNonStaffingExpenseAccounts] +AS + SELECT acc.* + FROM [fw].[DimAccount] acc + INNER JOIN [ob].[DimAccountPH] aph ON acc.OBAccountPHID = aph.AccountPHID + WHERE aph.Name = 'Expenses - Non-Staffing' +GO + + +--------------------------------------------- + +-- fp.viewNonStaffingExpenseFlexingConfig +CREATE VIEW [fp].[viewNonStaffingExpenseFlexingConfig] +AS + +SELECT + b.EntityGroupConfigGUID, + b.DepartmentID, + b.AccountID, + CASE WHEN b.FlexMethodID = 6 THEN 6 + ELSE COALESCE(ovr.FlexMethodID, b.FlexMethodID) END AS FlexMethodID +FROM ( + SELECT + fc.EntityGroupConfigGUID, + fc.DepartmentID, + acct.AccountID, + fc.FlexMethodID + FROM [fp].[NonStaffingExpenseFlexingConfig] fc + CROSS APPLY (SELECT AccountID FROM [fp].[viewNonStaffingExpenseAccounts]) acct +) b +LEFT JOIN [fp].[NonStaffingExpenseFlexingOverrideConfig] ovr + ON b.DepartmentID = ovr.DepartmentID + AND b.AccountID = ovr.AccountID + AND b.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID +GO + + +--------------------------------------------- + +-- fp.viewPayrollUOSData +CREATE VIEW fp.viewPayrollUOSData + AS + SELECT + sb.BudgetConfigID, + sb.EntityID, sb.DepartmentID, + fcm.PRJobCodeID AS JobCodeID, + ISNULL(CAST(TimeClassID AS TINYINT), 0) AS TimeClassID, + ISNULL(FiscalMonthID, 0) AS FiscalMonthID, + ISNULL(SUM(Value), 0) AS Value, + ISNULL(SUM(ManagerValue), 0) AS ManagerValue +FROM [fp].[viewFactStatistics_Unpivoted] sb WITH(NOLOCK) + INNER JOIN [fp].[BudgetConfig] bc ON sb.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [fp].[EntityGroupConfig] egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN ( + SELECT DISTINCT EntityGroupConfigID, DepartmentID, StatAccountID, PRJobCodeID + FROM [fp].[FlexConfigMapping] WITH(NOLOCK) + WHERE FlexingTypeID IN (3) + ) fcm ON sb.DepartmentID = fcm.DepartmentID AND sb.AccountID = fcm.StatAccountID AND fcm.EntityGroupConfigID = egc.EntityGroupConfigID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egc.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID + AND sb.EntityID = egcm.EntityID +GROUP BY sb.BudgetConfigID, sb.EntityID, sb.DepartmentID, fcm.PRJobCodeID, TimeClassID, FiscalMonthID +GO + + +--------------------------------------------- + +-- fp.viewPayrollUOSDataForAdjustments +CREATE VIEW fp.viewPayrollUOSDataForAdjustments AS +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 3-06-2023 NT JAZZ-49040 Cross Department Flexing change +** 2 1-18-2024 YR JAZZ-64847 Variable FTE import to Projection wipes out Projected Months +** 3 2-18-2024 NH JAZZ-58389 Provider Compensation: support new contextual adjustment window +*************************************************************/ +SELECT sb.BudgetConfigID, fcm.EntityID, fcm.DepartmentID, fcm.PRJobCodeID AS JobCodeID, fcm.ProviderLineItemID, sb.ProviderID, fcm.FlexingTypeID, sb.BudgetPhaseID, ISNULL(SUM(sb.AdjustedValue01), 0) AS AdjustedValue01, ISNULL(SUM(sb.AdjustedValue02), 0) + AS AdjustedValue02, ISNULL(SUM(sb.AdjustedValue03), 0) AS AdjustedValue03, ISNULL(SUM(sb.AdjustedValue04), 0) AS AdjustedValue04, ISNULL(SUM(sb.AdjustedValue05), 0) AS AdjustedValue05, ISNULL(SUM(sb.AdjustedValue06), 0) + AS AdjustedValue06, ISNULL(SUM(sb.AdjustedValue07), 0) AS AdjustedValue07, ISNULL(SUM(sb.AdjustedValue08), 0) AS AdjustedValue08, ISNULL(SUM(sb.AdjustedValue09), 0) AS AdjustedValue09, ISNULL(SUM(sb.AdjustedValue10), 0) + AS AdjustedValue10, ISNULL(SUM(sb.AdjustedValue11), 0) AS AdjustedValue11, ISNULL(SUM(sb.AdjustedValue12), 0) AS AdjustedValue12, ISNULL(SUM(sb.AdjustedValueTotal), 0) AS AdjustedValueTotal, + ISNULL(SUM(sb.AdjustedProjectionValue01), 0) AS AdjustedProjectionValue01, ISNULL(SUM(sb.AdjustedProjectionValue02), 0) AS AdjustedProjectionValue02, ISNULL(SUM(sb.AdjustedProjectionValue03), 0) AS AdjustedProjectionValue03, + ISNULL(SUM(sb.AdjustedProjectionValue04), 0) AS AdjustedProjectionValue04, ISNULL(SUM(sb.AdjustedProjectionValue05), 0) AS AdjustedProjectionValue05, ISNULL(SUM(sb.AdjustedProjectionValue06), 0) AS AdjustedProjectionValue06, + ISNULL(SUM(sb.AdjustedProjectionValue07), 0) AS AdjustedProjectionValue07, ISNULL(SUM(sb.AdjustedProjectionValue08), 0) AS AdjustedProjectionValue08, ISNULL(SUM(sb.AdjustedProjectionValue09), 0) AS AdjustedProjectionValue09, + ISNULL(SUM(sb.AdjustedProjectionValue10), 0) AS AdjustedProjectionValue10, ISNULL(SUM(sb.AdjustedProjectionValue11), 0) AS AdjustedProjectionValue11, ISNULL(SUM(sb.AdjustedProjectionValue12), 0) AS AdjustedProjectionValue12, + ISNULL(SUM(sb.AdjustedProjectionValueTotal), 0) AS AdjustedProjectionValueTotal +FROM fp.viewFactStatistics AS sb WITH (NOLOCK) INNER JOIN + fp.BudgetConfig AS bc ON sb.BudgetConfigID = bc.BudgetConfigID INNER JOIN + fp.EntityGroupConfig AS egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID INNER JOIN + (SELECT DISTINCT fcm.EntityGroupConfigID, d.EntityID, fcm.DepartmentID, fcm.StatAccountID, fcm.PRJobCodeID, ProviderLineItemID, fcm.FlexingTypeID, fcm.SourceDepartmentID + FROM fp.FlexConfigMapping AS fcm WITH (NOLOCK) INNER JOIN fw.DimDepartment d ON d.DepartmentID = fcm.DepartmentID + WHERE (FlexingTypeID IN (3, 9))) AS fcm ON fcm.EntityGroupConfigID = egc.EntityGroupConfigID AND sb.AccountID = fcm.StatAccountID AND sb.DepartmentID = fcm.SourceDepartmentID INNER JOIN + fp.EntityGroupConfigMapping AS egcm ON egc.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID AND sb.EntityID = egcm.EntityID +GROUP BY sb.BudgetConfigID, fcm.EntityID, fcm.DepartmentID, fcm.PRJobCodeID, sb.ProviderID, fcm.ProviderLineItemID, fcm.FlexingTypeID, sb.BudgetPhaseID +GO + + +--------------------------------------------- + +-- fp.viewPayrollVariabilityConfig +CREATE VIEW [fp].[viewPayrollVariabilityConfig] +AS +SELECT + OBJ.*, jg.Name as JCGName, jc.Name as JCName + FROM + + [fp].[PayrollVariabilityConfig] OBJ + LEFT JOIN [fw].[DimJobCodeGroup] jg ON OBJ.JobCodeGroupID = jg.JobCodeGroupID + LEFT JOIN [fw].[DimJobCode] jc ON OBJ.JobCodeID = jc.JobCodeID +GO + + +--------------------------------------------- + +-- fp.viewPlanSection +CREATE VIEW [fp].[viewPlanSection] +AS + + SELECT + PlanSectionID, + PlanSectionGUID as MemberGUID, + Description, + SortOrder, + 0 AS TransactionID, + '00000000-0000-0000-0000-000000000000' AS HistoryItemGUID + FROM [fp].[PlanSection] +GO + + +--------------------------------------------- + +-- fp.viewPlanSection_auto +--Last Modified 11/16/2020 3:28 PM +CREATE VIEW [fp].[viewPlanSection_auto] +AS +SELECT + grpA26FDA3A669C47BCA67539B1DA857199.[PlanSectionID] + ,grpA26FDA3A669C47BCA67539B1DA857199.[Description] + ,grpA26FDA3A669C47BCA67539B1DA857199.[TransactionID] + ,grpA26FDA3A669C47BCA67539B1DA857199.[SortOrder] + ,grpA26FDA3A669C47BCA67539B1DA857199.[MemberGUID] + ,grpA26FDA3A669C47BCA67539B1DA857199.[HistoryItemGUID] +FROM [fp].[viewPlanSection] grpA26FDA3A669C47BCA67539B1DA857199 +GO + + +--------------------------------------------- + +-- fp.viewProviderCompensationSpreads +CREATE VIEW [fp].[viewProviderCompensationSpreads] +AS + SELECT [BudgetConfigID], [ProviderID], [ProviderLineItemID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [IsInactive], [SpreadPercentage01], [SpreadPercentage02], [SpreadPercentage03], [SpreadPercentage04], [SpreadPercentage05], [SpreadPercentage06], [SpreadPercentage07], [SpreadPercentage08], [SpreadPercentage09], [SpreadPercentage10], [SpreadPercentage11], [SpreadPercentage12], [TotalImportedValue] as TotalSpreadValue, [GlobalSpreadID], [UnitTypeID] + FROM [fp].[ProviderCompensationSpreads] gls with (readuncommitted) + WHERE GlobalSpreadID = 1 + + UNION ALL + + SELECT gls.[BudgetConfigID], [ProviderID], [ProviderLineItemID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [IsInactive], gs.[SpreadPercentage01], gs.[SpreadPercentage02], gs.[SpreadPercentage03], gs.[SpreadPercentage04], gs.[SpreadPercentage05], gs.[SpreadPercentage06], gs.[SpreadPercentage07], gs.[SpreadPercentage08], gs.[SpreadPercentage09], gs.[SpreadPercentage10], gs.[SpreadPercentage11], gs.[SpreadPercentage12], gs.TotalSpreadValue, gls.[GlobalSpreadID], [UnitTypeID] + FROM [fp].[ProviderCompensationSpreads] gls with (readuncommitted) + INNER JOIN [fp].[GlobalSpread] gs + ON gls.GlobalSpreadID = gs.GlobalSpreadID + WHERE gls.GlobalSpreadID > 1 +GO + + +--------------------------------------------- + +-- fp.viewProviderCompensationVariability +CREATE VIEW [fp].[viewProviderCompensationVariability] AS +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2024-02-18 NH JAZZ-65991 Provider Compensation: support new contextual adjustment window +*************************************************************/ +SELECT DISTINCT + bc.BudgetConfigID, + egc.EntityGroupConfigGUID, + dd.EntityID, + pv.DepartmentID, + pv.ProviderLineItemID, + ISNULL(MAX(pv.FixedVariabilityPercentage), 0) AS FixedPercentage +FROM [fp].[Staffing] pv + INNER JOIN [fp].[EntityGroupConfig] egc ON pv.EntityGroupConfigID = egc.EntityGroupConfigID + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID + INNER JOIN [fw].[DimDepartment] dd ON dd.DepartmentID = pv.DepartmentID + WHERE SubsectionID = 4 + AND pv.VariabilityID = 2 + GROUP BY bc.BudgetConfigID, + pv.EntityGroupConfigID, + egc.EntityGroupConfigGUID, + dd.EntityID, + pv.DepartmentID, + pv.ProviderLineItemID +GO + + +--------------------------------------------- + +-- fp.viewProviderLineItem +CREATE VIEW [fp].[viewProviderLineItem] +AS + + SELECT + pli.ProviderLineItemID, + pli.ProviderLineItemGUID as MemberGUID, + pli.Description, + pli.PlanSectionID, + pli.SortOrder, + pli.HistoryItemGUID, + pli.TransactionID + FROM [fp].[ProviderLineItem] pli +GO + + +--------------------------------------------- + +-- fp.viewProviderLineItem_auto +--Last Modified 11/15/2023 3:56 PM +CREATE VIEW [fp].[viewProviderLineItem_auto] +AS +SELECT + grpC441C263E43548A5AE8DFE1AC0E8958C.[ProviderLineItemID] + ,grpC441C263E43548A5AE8DFE1AC0E8958C.[Description] + ,grpC441C263E43548A5AE8DFE1AC0E8958C.[PlanSectionID] + ,grpC441C263E43548A5AE8DFE1AC0E8958C.[PayCodeGroupID] + ,grpC441C263E43548A5AE8DFE1AC0E8958C.[SortOrder] + ,grpC441C263E43548A5AE8DFE1AC0E8958C.[TransactionID] + ,grpC441C263E43548A5AE8DFE1AC0E8958C.[MemberGUID] + ,grpC441C263E43548A5AE8DFE1AC0E8958C.[HistoryItemGUID] + ,ISNULL([PLANSECTION].[Description], 'Not Specified') as [PlanSectionName] + ,ISNULL([PCG].[Name], 'Not Specified') as [PayCodeGroupName] +FROM [fp].[ProviderLineItem] grpC441C263E43548A5AE8DFE1AC0E8958C (readuncommitted) + LEFT JOIN [fp].[viewPlanSection_auto] [PLANSECTION] on [PLANSECTION].[PlanSectionID] = [grpC441C263E43548A5AE8DFE1AC0E8958C].[PlanSectionID] + LEFT JOIN [fw].[viewDimPayCodeGroup] [PCG] on [PCG].[PayCodeGroupID] = [grpC441C263E43548A5AE8DFE1AC0E8958C].[PayCodeGroupID] +GO + + +--------------------------------------------- + +-- fp.viewReimbursementAdjustment +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-16-50 MY JAZZ-32944 Initial +** 1 2023-09-04 MD JAZZ-59398 Add BudgetPhaseID +*************************************************************/ +CREATE VIEW [fp].[viewReimbursementAdjustment] +AS + SELECT [AdjustmentGUID] + ,[BudgetConfigGUID] + ,[AdjustmentType] + ,[Value] + ,[AdjustmentFilterJSON] + ,[GroupingHierarchyJSON] + ,[AdjustedProperty] + ,[Comment] + ,[AuthorGUID] + ,[AuthorFullName] + ,[GroupingGUID] + ,[TimeClassID] + ,[ClassificationGroupID] + ,[ClassificationCategoryID] + ,[IsRecordDeleted] + ,[DateCreatedUtc] + ,[LastModifiedDateUtc] + ,[DimensionMemberJson] + ,[AffectedDataCount] + ,[UnitTypeID] + ,[IsCarryForward] + ,[AdjustmentID] + ,[BudgetPhaseID] + FROM [fp].[ReimbursementAdjustment] + WHERE IsRecordDeleted = 0 +GO + + +--------------------------------------------- + +-- fp.viewReimbursementAdjustmentImport +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-09-13 MD JAZZ-59398 Add BudgetPhaseID column +*******************************************************/ + +CREATE VIEW [fp].[viewReimbursementAdjustmentImport] +AS +SELECT + [AdjustmentID] + ,[EntityID] + ,[PatientClassID] + ,[PayorID] + ,[PayorGroupID] + ,[ServiceLineID] + ,[ServiceLineRollupID] + ,[MedicalSurgicalID] + ,[MSDRGID] + ,[PrimaryCPTID] AS CPTID + ,[UBRevCodeID] + ,[UnitTypeID] + ,[TimeClassID] + ,[BudgetPhaseID] + ,[Value01] + ,[Value02] + ,[Value03] + ,[Value04] + ,[Value05] + ,[Value06] + ,[Value07] + ,[Value08] + ,[Value09] + ,[Value10] + ,[Value11] + ,[Value12] + ,6 AS SubsectionID -- Charges +FROM fp.ReimbursementAdjustmentChargeImport +UNION ALL +SELECT + [AdjustmentID] + ,[EntityID] + ,[PatientClassID] + ,[PayorID] + ,[PayorGroupID] + ,[ServiceLineID] + ,[ServiceLineRollupID] + ,[MedicalSurgicalID] + ,[MSDRGID] + ,[CPTID] + ,0 AS [UBRevCodeID] + ,[UnitTypeID] + ,[TimeClassID] + ,[BudgetPhaseID] + ,[Value01] + ,[Value02] + ,[Value03] + ,[Value04] + ,[Value05] + ,[Value06] + ,[Value07] + ,[Value08] + ,[Value09] + ,[Value10] + ,[Value11] + ,[Value12] + ,5 AS SubsectionID -- Encounters +FROM fp.ReimbursementAdjustmentEncounterImport +GO + + +--------------------------------------------- + +-- fp.viewReimbursementDeductionsAccounts +CREATE VIEW [fp].[viewReimbursementDeductionsAccounts] +AS + SELECT acc.* + FROM [fw].[DimAccount] acc + INNER JOIN [ob].[DimAccountPH] aph ON acc.OBAccountPHID = aph.AccountPHID + WHERE aph.Name = 'Deductions - Reimbursement' +GO + + +--------------------------------------------- + +-- fp.viewReimbursementGeneralLedgerAdjustment +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 06-19-2023 MZ JAZZ-56218 Initial +** 2 10-05-2023 NH JAZZ-61719 Added UnitTypeID +*************************************************************/ +CREATE VIEW fp.viewReimbursementGeneralLedgerAdjustment +AS + SELECT [AdjustmentGUID] + ,[BudgetConfigGUID] + ,[AdjustmentType] + ,[Value] + ,[AdjustmentFilterJSON] + ,[GroupingHierarchyJSON] + ,[AdjustedProperty] + ,[Comment] + ,[AuthorGUID] + ,[AuthorFullName] + ,[GroupingGUID] + ,[TimeClassID] + ,[BudgetPhaseID] + ,[UnitTypeID] + ,[ClassificationGroupID] + ,[ClassificationCategoryID] + ,[IsRecordDeleted] + ,[DateCreatedUtc] + ,[LastModifiedDateUtc] + ,[DimensionMemberJson] + ,[AffectedDataCount] + ,[IsCarryForward] + ,[AdjustmentID] + ,[IsErrored] + FROM [fp].[ReimbursementGeneralLedgerAdjustment] + WHERE IsRecordDeleted = 0 +GO + + +--------------------------------------------- + +-- fp.viewReimbursementGeneralLedgerBudget_HistoryViewer +CREATE VIEW [fp].[viewReimbursementGeneralLedgerBudget_HistoryViewer] +AS +SELECT + ov.ReimbursementGeneralLedgerID, + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.PayorGroupID, + ov.PatientClassID, + 34 AS UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + ov.FiscalMonthID, + LockType, + ov.InitialValue AS OriginalValue, + v.Value, + mgrv.ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT ReimbursementGeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT ReimbursementGeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, + InitialBudgetNetReimbursement01, InitialBudgetNetReimbursement02, InitialBudgetNetReimbursement03, InitialBudgetNetReimbursement04, InitialBudgetNetReimbursement05, InitialBudgetNetReimbursement06, InitialBudgetNetReimbursement07, InitialBudgetNetReimbursement08, InitialBudgetNetReimbursement09, InitialBudgetNetReimbursement10, InitialBudgetNetReimbursement11, InitialBudgetNetReimbursement12 + FROM fp.ReimbursementGeneralLedger gl ) gl + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialBudgetNetReimbursement01, InitialBudgetNetReimbursement02, InitialBudgetNetReimbursement03, InitialBudgetNetReimbursement04, InitialBudgetNetReimbursement05, InitialBudgetNetReimbursement06, InitialBudgetNetReimbursement07, InitialBudgetNetReimbursement08, InitialBudgetNetReimbursement09, InitialBudgetNetReimbursement10, InitialBudgetNetReimbursement11, InitialBudgetNetReimbursement12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialBudgetNetReimbursement', 'Month')) ov +INNER JOIN ( + -- Unpivot for Value + SELECT ReimbursementGeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT ReimbursementGeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, + TargetLockType AS LockType, + TargetAdjustedNetReimbursement01 AS AdjustedValue01, + TargetAdjustedNetReimbursement02 AS AdjustedValue02, + TargetAdjustedNetReimbursement03 AS AdjustedValue03, + TargetAdjustedNetReimbursement04 AS AdjustedValue04, + TargetAdjustedNetReimbursement05 AS AdjustedValue05, + TargetAdjustedNetReimbursement06 AS AdjustedValue06, + TargetAdjustedNetReimbursement07 AS AdjustedValue07, + TargetAdjustedNetReimbursement08 AS AdjustedValue08, + TargetAdjustedNetReimbursement09 AS AdjustedValue09, + TargetAdjustedNetReimbursement10 AS AdjustedValue10, + TargetAdjustedNetReimbursement11 AS AdjustedValue11, + TargetAdjustedNetReimbursement12 AS AdjustedValue12 + FROM fp.ReimbursementGeneralLedger gl) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) v + ON + ov.BudgetConfigID = v.BudgetConfigID + AND ov.EntityID = v.EntityID + AND ov.PayorGroupID = v.PayorGroupID + AND ov.PatientClassID = v.PatientClassID + AND ov.FiscalMonthID = v.FiscalMonthID +INNER JOIN ( + -- Unpivot for ManagerValue + SELECT ReimbursementGeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, m.FiscalMonthID, f.Value AS ManagerValue + FROM ( + SELECT ReimbursementGeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, + BudgetLockType AS LockType, + BudgetAdjustedNetReimbursement01 AS AdjustedValue01, + BudgetAdjustedNetReimbursement02 AS AdjustedValue02, + BudgetAdjustedNetReimbursement03 AS AdjustedValue03, + BudgetAdjustedNetReimbursement04 AS AdjustedValue04, + BudgetAdjustedNetReimbursement05 AS AdjustedValue05, + BudgetAdjustedNetReimbursement06 AS AdjustedValue06, + BudgetAdjustedNetReimbursement07 AS AdjustedValue07, + BudgetAdjustedNetReimbursement08 AS AdjustedValue08, + BudgetAdjustedNetReimbursement09 AS AdjustedValue09, + BudgetAdjustedNetReimbursement10 AS AdjustedValue10, + BudgetAdjustedNetReimbursement11 AS AdjustedValue11, + BudgetAdjustedNetReimbursement12 AS AdjustedValue12 + FROM fp.ReimbursementGeneralLedger gl) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON + v.BudgetConfigID = mgrv.BudgetConfigID + AND v.EntityID = mgrv.EntityID + AND v.PayorGroupID = mgrv.PayorGroupID + AND v.PatientClassID = mgrv.PatientClassID + AND v.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewReimbursementGeneralLedgerProjection_HistoryViewer +CREATE VIEW [fp].[viewReimbursementGeneralLedgerProjection_HistoryViewer] +AS +SELECT + ov.ReimbursementGeneralLedgerID, + ov.BudgetConfigID, + ov.EntityGroupConfigID, + ov.EntityID, + ov.PayorGroupID, + ov.PatientClassID, + 34 AS UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID, + ov.FiscalMonthID, + LockType, + ov.InitialValue AS OriginalValue, + mgrv.ManagerValue +FROM ( + -- Unpivot for OriginalValue + SELECT ReimbursementGeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, m.FiscalMonthID, f.InitialValue + FROM ( + SELECT ReimbursementGeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, + InitialProjectionNetReimbursement01, InitialProjectionNetReimbursement02, InitialProjectionNetReimbursement03, InitialProjectionNetReimbursement04, InitialProjectionNetReimbursement05, InitialProjectionNetReimbursement06, InitialProjectionNetReimbursement07, InitialProjectionNetReimbursement08, InitialProjectionNetReimbursement09, InitialProjectionNetReimbursement10, InitialProjectionNetReimbursement11, InitialProjectionNetReimbursement12 + FROM fp.ReimbursementGeneralLedger gl ) gl + UNPIVOT ( InitialValue FOR FiscalMonth IN (InitialProjectionNetReimbursement01, InitialProjectionNetReimbursement02, InitialProjectionNetReimbursement03, InitialProjectionNetReimbursement04, InitialProjectionNetReimbursement05, InitialProjectionNetReimbursement06, InitialProjectionNetReimbursement07, InitialProjectionNetReimbursement08, InitialProjectionNetReimbursement09, InitialProjectionNetReimbursement10, InitialProjectionNetReimbursement11, InitialProjectionNetReimbursement12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'InitialProjectionNetReimbursement', 'Month')) ov +INNER JOIN ( + -- Unpivot for ManagerValue + SELECT ReimbursementGeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, m.FiscalMonthID, f.Value AS ManagerValue, LockType + FROM ( + SELECT ReimbursementGeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, + ProjectionLockType AS LockType, + ProjectionAdjustedNetReimbursement01 AS AdjustedValue01, + ProjectionAdjustedNetReimbursement02 AS AdjustedValue02, + ProjectionAdjustedNetReimbursement03 AS AdjustedValue03, + ProjectionAdjustedNetReimbursement04 AS AdjustedValue04, + ProjectionAdjustedNetReimbursement05 AS AdjustedValue05, + ProjectionAdjustedNetReimbursement06 AS AdjustedValue06, + ProjectionAdjustedNetReimbursement07 AS AdjustedValue07, + ProjectionAdjustedNetReimbursement08 AS AdjustedValue08, + ProjectionAdjustedNetReimbursement09 AS AdjustedValue09, + ProjectionAdjustedNetReimbursement10 AS AdjustedValue10, + ProjectionAdjustedNetReimbursement11 AS AdjustedValue11, + ProjectionAdjustedNetReimbursement12 AS AdjustedValue12 + FROM fp.ReimbursementGeneralLedger gl) gl + UNPIVOT ( Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month')) mgrv + ON + ov.BudgetConfigID = mgrv.BudgetConfigID + AND ov.EntityID = mgrv.EntityID + AND ov.PayorGroupID = mgrv.PayorGroupID + AND ov.PatientClassID = mgrv.PatientClassID + AND ov.FiscalMonthID = mgrv.FiscalMonthID +INNER JOIN fp.BudgetConfig bc ON ov.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewReimbursementGeneralLedger_Pivoted +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-06-22 AO JAZZ-56124 Inital +*************************************************************/ + + +CREATE VIEW [fp].[viewReimbursementGeneralLedger_Pivoted] +AS + SELECT + rgl.ReimbursementGeneralLedgerID, + rgl.BudgetConfigID, + rgl.EntityGroupConfigID, + rgl.EntityID, + rgl.PatientClassID, + rgl.PayorGroupID, + + rgl.TargetLockType, + rgl.BudgetLockType, + rgl.ProjectionLockType, + + rgl.TargetLockFlag, + rgl.BudgetLockFlag, + rgl.ProjectionLockFlag, + + CASE WHEN rgl.TargetLockType = 7 THEN 1 ELSE 0 END AS TargetAdjustmentLockFlag, + CASE WHEN rgl.BudgetLockType = 7 THEN 1 ELSE 0 END AS BudgetAdjustmentLockFlag, + CASE WHEN rgl.ProjectionLockType = 7 THEN 1 ELSE 0 END AS ProjectionAdjustmentLockFlag, + + rgl.TargetAdjustedTotal, + rgl.BudgetAdjustedTotal, + rgl.ProjectionAdjustedTotal, + + hist.PriorYearActualValueTotal, + + rgl.InitialBudgetTotal, + rgl.InitialProjectionTotal, + + rgl.TargetAdjusted01, + rgl.TargetAdjusted02, + rgl.TargetAdjusted03, + rgl.TargetAdjusted04, + rgl.TargetAdjusted05, + rgl.TargetAdjusted06, + rgl.TargetAdjusted07, + rgl.TargetAdjusted08, + rgl.TargetAdjusted09, + rgl.TargetAdjusted10, + rgl.TargetAdjusted11, + rgl.TargetAdjusted12, + + rgl.BudgetAdjusted01, + rgl.BudgetAdjusted02, + rgl.BudgetAdjusted03, + rgl.BudgetAdjusted04, + rgl.BudgetAdjusted05, + rgl.BudgetAdjusted06, + rgl.BudgetAdjusted07, + rgl.BudgetAdjusted08, + rgl.BudgetAdjusted09, + rgl.BudgetAdjusted10, + rgl.BudgetAdjusted11, + rgl.BudgetAdjusted12, + + rgl.ProjectionAdjusted01, + rgl.ProjectionAdjusted02, + rgl.ProjectionAdjusted03, + rgl.ProjectionAdjusted04, + rgl.ProjectionAdjusted05, + rgl.ProjectionAdjusted06, + rgl.ProjectionAdjusted07, + rgl.ProjectionAdjusted08, + rgl.ProjectionAdjusted09, + rgl.ProjectionAdjusted10, + rgl.ProjectionAdjusted11, + rgl.ProjectionAdjusted12, + + hist.PriorYearActualValue01, + hist.PriorYearActualValue02, + hist.PriorYearActualValue03, + hist.PriorYearActualValue04, + hist.PriorYearActualValue05, + hist.PriorYearActualValue06, + hist.PriorYearActualValue07, + hist.PriorYearActualValue08, + hist.PriorYearActualValue09, + hist.PriorYearActualValue10, + hist.PriorYearActualValue11, + hist.PriorYearActualValue12, + + rgl.TargetAdjustedNetReimbursement01, + rgl.TargetAdjustedNetReimbursement02, + rgl.TargetAdjustedNetReimbursement03, + rgl.TargetAdjustedNetReimbursement04, + rgl.TargetAdjustedNetReimbursement05, + rgl.TargetAdjustedNetReimbursement06, + rgl.TargetAdjustedNetReimbursement07, + rgl.TargetAdjustedNetReimbursement08, + rgl.TargetAdjustedNetReimbursement09, + rgl.TargetAdjustedNetReimbursement10, + rgl.TargetAdjustedNetReimbursement11, + rgl.TargetAdjustedNetReimbursement12, + + rgl.BudgetAdjustedNetReimbursement01, + rgl.BudgetAdjustedNetReimbursement02, + rgl.BudgetAdjustedNetReimbursement03, + rgl.BudgetAdjustedNetReimbursement04, + rgl.BudgetAdjustedNetReimbursement05, + rgl.BudgetAdjustedNetReimbursement06, + rgl.BudgetAdjustedNetReimbursement07, + rgl.BudgetAdjustedNetReimbursement08, + rgl.BudgetAdjustedNetReimbursement09, + rgl.BudgetAdjustedNetReimbursement10, + rgl.BudgetAdjustedNetReimbursement11, + rgl.BudgetAdjustedNetReimbursement12, + + rgl.ProjectionAdjustedNetReimbursement01, + rgl.ProjectionAdjustedNetReimbursement02, + rgl.ProjectionAdjustedNetReimbursement03, + rgl.ProjectionAdjustedNetReimbursement04, + rgl.ProjectionAdjustedNetReimbursement05, + rgl.ProjectionAdjustedNetReimbursement06, + rgl.ProjectionAdjustedNetReimbursement07, + rgl.ProjectionAdjustedNetReimbursement08, + rgl.ProjectionAdjustedNetReimbursement09, + rgl.ProjectionAdjustedNetReimbursement10, + rgl.ProjectionAdjustedNetReimbursement11, + rgl.ProjectionAdjustedNetReimbursement12, + + hist.PriorYearActualValueNetReimbursement01, + hist.PriorYearActualValueNetReimbursement02, + hist.PriorYearActualValueNetReimbursement03, + hist.PriorYearActualValueNetReimbursement04, + hist.PriorYearActualValueNetReimbursement05, + hist.PriorYearActualValueNetReimbursement06, + hist.PriorYearActualValueNetReimbursement07, + hist.PriorYearActualValueNetReimbursement08, + hist.PriorYearActualValueNetReimbursement09, + hist.PriorYearActualValueNetReimbursement10, + hist.PriorYearActualValueNetReimbursement11, + hist.PriorYearActualValueNetReimbursement12, + + rgl.TargetAdjustedNetAsPercentOfCharge01, + rgl.TargetAdjustedNetAsPercentOfCharge02, + rgl.TargetAdjustedNetAsPercentOfCharge03, + rgl.TargetAdjustedNetAsPercentOfCharge04, + rgl.TargetAdjustedNetAsPercentOfCharge05, + rgl.TargetAdjustedNetAsPercentOfCharge06, + rgl.TargetAdjustedNetAsPercentOfCharge07, + rgl.TargetAdjustedNetAsPercentOfCharge08, + rgl.TargetAdjustedNetAsPercentOfCharge09, + rgl.TargetAdjustedNetAsPercentOfCharge10, + rgl.TargetAdjustedNetAsPercentOfCharge11, + rgl.TargetAdjustedNetAsPercentOfCharge12, + + rgl.BudgetAdjustedNetAsPercentOfCharge01, + rgl.BudgetAdjustedNetAsPercentOfCharge02, + rgl.BudgetAdjustedNetAsPercentOfCharge03, + rgl.BudgetAdjustedNetAsPercentOfCharge04, + rgl.BudgetAdjustedNetAsPercentOfCharge05, + rgl.BudgetAdjustedNetAsPercentOfCharge06, + rgl.BudgetAdjustedNetAsPercentOfCharge07, + rgl.BudgetAdjustedNetAsPercentOfCharge08, + rgl.BudgetAdjustedNetAsPercentOfCharge09, + rgl.BudgetAdjustedNetAsPercentOfCharge10, + rgl.BudgetAdjustedNetAsPercentOfCharge11, + rgl.BudgetAdjustedNetAsPercentOfCharge12, + + rgl.ProjectionAdjustedNetAsPercentOfCharge01, + rgl.ProjectionAdjustedNetAsPercentOfCharge02, + rgl.ProjectionAdjustedNetAsPercentOfCharge03, + rgl.ProjectionAdjustedNetAsPercentOfCharge04, + rgl.ProjectionAdjustedNetAsPercentOfCharge05, + rgl.ProjectionAdjustedNetAsPercentOfCharge06, + rgl.ProjectionAdjustedNetAsPercentOfCharge07, + rgl.ProjectionAdjustedNetAsPercentOfCharge08, + rgl.ProjectionAdjustedNetAsPercentOfCharge09, + rgl.ProjectionAdjustedNetAsPercentOfCharge10, + rgl.ProjectionAdjustedNetAsPercentOfCharge11, + rgl.ProjectionAdjustedNetAsPercentOfCharge12, + + hist.PriorYearActualValueNetAsPercentOfCharge01, + hist.PriorYearActualValueNetAsPercentOfCharge02, + hist.PriorYearActualValueNetAsPercentOfCharge03, + hist.PriorYearActualValueNetAsPercentOfCharge04, + hist.PriorYearActualValueNetAsPercentOfCharge05, + hist.PriorYearActualValueNetAsPercentOfCharge06, + hist.PriorYearActualValueNetAsPercentOfCharge07, + hist.PriorYearActualValueNetAsPercentOfCharge08, + hist.PriorYearActualValueNetAsPercentOfCharge09, + hist.PriorYearActualValueNetAsPercentOfCharge10, + hist.PriorYearActualValueNetAsPercentOfCharge11, + hist.PriorYearActualValueNetAsPercentOfCharge12 + + FROM + [fp].[ReimbursementGeneralLedger] rgl + INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON rgl.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [fp].[ReimbursementGeneralLedgerHistory] hist with (readuncommitted) ON rgl.ReimbursementGeneralLedgerID = hist.ReimbursementGeneralLedgerID +GO + + +--------------------------------------------- + +-- fp.viewReportChargeToStatisticsCrosswalk_MonthsWithValues +CREATE VIEW fp.viewReportChargeToStatisticsCrosswalk_MonthsWithValues +AS +/********************************************************************* +** Change History +********************************************************************** +** CID Date Author WI Description +** 2 2022-11-01 JB JAZZ-45621 Remove PayorID +*********************************************************************/ + WITH ChargeToStat AS ( + select BudgetConfigID, + EntityID, + DepartmentID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + PatientClassID, + UnitTypeID, + TimeClassID, + FiscalYearID, + FiscalMonthID, + AccountID, + RVUWeight, + OriginalValue, + Value, + ManagerValue + from [fp].[FactReportChargeToStatisticsCrosswalk] + union all + select BudgetConfigID, + EntityID, + DepartmentID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + PatientClassID, + UnitTypeID, + TimeClassID, + FiscalYearID, + FiscalMonthID, + AccountID, + RVUWeight, + OriginalValue, + Value, + ManagerValue + from [fp].[FactReportChargeToStatisticsCrosswalk_archive] + ), + ChargeToStatHistory AS ( + select ChargeVolumeID, + BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + PatientClassID, + UnitTypeID, + TimeClassID, + FiscalYearID, + FiscalMonthID, + AccountID, + RVUWeight, + Value + from [fp].[FactReportChargeToStatisticsCrosswalkHistory] + union all + select ChargeVolumeID, + BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + PatientClassID, + UnitTypeID, + TimeClassID, + FiscalYearID, + FiscalMonthID, + AccountID, + RVUWeight, + Value + from [fp].[FactReportChargeToStatisticsCrosswalkHistory_archive] + ) + + -- Manager Projection + SELECT + bc.BudgetConfigID, + st.EntityID, + st.DepartmentID, + st.AccountID, + bc.FiscalYearID-1 as FiscalYearID, + TimeClassID, + ManagerValue as Value, + UnitTypeID, + st.PatientClassID, + st.ChargeCodeID, + st.ServiceLineID, + st.AgeCohortID, + st.MedicalSurgicalID, + st.RVUWeight, + FiscalMonthID + from ChargeToStat st + INNER JOIN fp.BudgetConfig bc on st.BudgetConfigID = bc.BudgetConfigID + WHERE TimeClassID=12 + + union all + + -- Initial Budget + SELECT + BudgetConfigID, + st.EntityID, + st.DepartmentID, + st.AccountID, + FiscalYearID, + 21 as TimeClassID, + OriginalValue as Value, + UnitTypeID, + st.PatientClassID, + st.ChargeCodeID, + st.ServiceLineID, + st.AgeCohortID, + st.MedicalSurgicalID, + st.RVUWeight, + FiscalMonthID + from ChargeToStat st + WHERE TimeClassID=2 + + union all + + -- Manager Budget + select + BudgetConfigID, + st.EntityID, + st.DepartmentID, + st.AccountID, + FiscalYearID, + TimeClassID, + ManagerValue as Value, + UnitTypeID, + st.PatientClassID, + st.ChargeCodeID, + st.ServiceLineID, + st.AgeCohortID, + st.MedicalSurgicalID, + st.RVUWeight, + FiscalMonthID + from ChargeToStat st + WHERE TimeClassID=2 + + union all + + -- Baseline Budget + select + BudgetConfigID, + st.EntityID, + st.DepartmentID, + st.AccountID, + FiscalYearID, + 22 as TimeClassID, + Value, + UnitTypeID, + st.PatientClassID, + st.ChargeCodeID, + st.ServiceLineID, + st.AgeCohortID, + st.MedicalSurgicalID, + st.RVUWeight, + FiscalMonthID + from ChargeToStat st + WHERE TimeClassID=2 + + union all + + -- Prior Year Actual and Current Year Budget + select + bc.BudgetConfigID, + st.EntityID, + st.DepartmentID, + st.AccountID, + st.FiscalYearID, + TimeClassID, + Value, + UnitTypeID, + st.PatientClassID, + st.ChargeCodeID, + st.ServiceLineID, + st.AgeCohortID, + st.MedicalSurgicalID, + st.RVUWeight, + FiscalMonthID + from ChargeToStatHistory st + INNER JOIN fp.BudgetConfig bc on st.BudgetConfigID = bc.BudgetConfigID + WHERE TimeClassID in(1, 2) +GO + + +--------------------------------------------- + +-- fp.viewReportChargeToStatisticsCrosswalk_Unpivoted +CREATE VIEW fp.viewReportChargeToStatisticsCrosswalk_Unpivoted +AS +/********************************************************************* +** Change History +********************************************************************** +** CID Date Author WI Description +** 2 2022-11-01 JB JAZZ-45621 Remove PayorID +*********************************************************************/ + -- Making sure final projection has all months included + SELECT cvToStat.[BudgetConfigID], + cvToStat.[EntityID], + cvToStat.[DepartmentID], + cvToStat.[AccountID], + cvToStat.[PatientClassID], + cvToStat.[UnitTypeID], + cvToStat.[TimeClassID], + cvToStat.[FiscalMonthID], + cvToStat.[FiscalYearID], + cvToStat.ChargeCodeID, + cvToStat.ServiceLineID, + cvToStat.AgeCohortID, + cvToStat.MedicalSurgicalID, + --cvToStat.RVUWeight, -- Disabling this for now because the value is wrong + COALESCE(frs.Value, cvToStat.Value) as Value + FROM ( + SELECT DISTINCT [BudgetConfigID], [EntityID], [DepartmentID], [AccountID], [PatientClassID], + [ChargeCodeID], [ServiceLineID], [AgeCohortID], [MedicalSurgicalID], [UnitTypeID], [TimeClassID], + ca.[FiscalMonthID], [FiscalYearID], [RVUWeight], 0 as Value, 0 as OriginalValue, 0 as ManagerValue + FROM fp.viewReportChargeToStatisticsCrosswalk_MonthsWithValues + CROSS APPLY ( + select FiscalMonthID + from [fw].[DimFiscalMonth] + WHERE FiscalMonthID != 0 + ) ca + WHERE TimeClassID IN (1, 2, 12, 21, 22) + ) cvToStat + + LEFT JOIN (select * from fp.viewReportChargeToStatisticsCrosswalk_MonthsWithValues) frs + ON cvToStat.BudgetConfigID = frs.BudgetConfigID + and cvToStat.DepartmentID = frs.DepartmentID + and cvToStat.AccountID = frs.AccountID + and cvToStat.FiscalYearID = frs.FiscalYearID + and cvToStat.TimeClassID = frs.TimeClassID + and cvToStat.FiscalMonthID = frs.FiscalMonthID + and cvToStat.PatientClassID = frs.PatientClassID + and cvToStat.UnitTypeID = frs.UnitTypeID + and cvToStat.ChargeCodeID = frs.ChargeCodeID + and cvToStat.AgeCohortID = frs.AgeCohortID + and cvToStat.ServiceLineID = frs.ServiceLineID + and cvToStat.MedicalSurgicalID = frs.MedicalSurgicalID +GO + + +--------------------------------------------- + +-- fp.viewReportEncounter_MonthsWithValues +CREATE VIEW [fp].[viewReportEncounter_MonthsWithValues] AS + WITH Enc AS ( + select BudgetConfigID, EntityID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, DepartmentID, PayorID, PayorGroupID, + MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue, Value, ManagerValue + from [fp].[FactReportEncounter] + union all + select BudgetConfigID, EntityID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, DepartmentID, PayorID, PayorGroupID, + MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue, Value, ManagerValue + from [fp].[FactReportEncounter_archive] + ), + EncHistory AS ( + select ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, + DepartmentID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, Value + from [fp].[FactReportEncounterHistory] + union all + select ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, + DepartmentID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, Value + from [fp].[FactReportEncounterHistory_archive] + ) + + -- Manager Projection + SELECT + bc.BudgetConfigID, + ec.EntityID, + ec.DepartmentID, + bc.FiscalYearID-1 as FiscalYearID, + TimeClassID, + Value as Value, + UnitTypeID, + ec.ServiceLineID, + ec.ServiceLineRollupID, + ec.PatientClassID, + ec.AgeCohortID, + ec.MedicalSurgicalID, + ec.PayorID, + ec.PayorGroupID, + ec.MSDRGID, + ec.CPTID, + ec.ProviderID, + ec.PhysicianSpecialtyID, + ec.FiscalMonthID + from Enc ec + INNER JOIN fp.BudgetConfig bc on ec.BudgetConfigID = bc.BudgetConfigID + WHERE TimeClassID=12 + + union all + + -- Initial Budget + SELECT + BudgetConfigID, + ec.EntityID, + ec.DepartmentID, + ec.FiscalYearID, + 21 as TimeClassID, + OriginalValue as Value, + UnitTypeID, + ec.ServiceLineID, + ec.ServiceLineRollupID, + ec.PatientClassID, + ec.AgeCohortID, + ec.MedicalSurgicalID, + ec.PayorID, + ec.PayorGroupID, + ec.MSDRGID, + ec.CPTID, + ec.ProviderID, + ec.PhysicianSpecialtyID, + ec.FiscalMonthID + from Enc ec + WHERE TimeClassID=2 + + union all + + -- Manager Budget + select + BudgetConfigID, + ec.EntityID, + ec.DepartmentID, + ec.FiscalYearID, + TimeClassID, + ManagerValue as Value, + UnitTypeID, + ec.ServiceLineID, + ec.ServiceLineRollupID, + ec.PatientClassID, + ec.AgeCohortID, + ec.MedicalSurgicalID, + ec.PayorID, + ec.PayorGroupID, + ec.MSDRGID, + ec.CPTID, + ec.ProviderID, + ec.PhysicianSpecialtyID, + ec.FiscalMonthID + from Enc ec + WHERE TimeClassID=2 + + union all + + -- Baseline Budget + select + BudgetConfigID, + ec.EntityID, + ec.DepartmentID, + ec.FiscalYearID, + 22 as TimeClassID, + Value, + UnitTypeID, + ec.ServiceLineID, + ec.ServiceLineRollupID, + ec.PatientClassID, + ec.AgeCohortID, + ec.MedicalSurgicalID, + ec.PayorID, + ec.PayorGroupID, + ec.MSDRGID, + ec.CPTID, + ec.ProviderID, + ec.PhysicianSpecialtyID, + ec.FiscalMonthID + from Enc ec + WHERE TimeClassID=2 + + union all + + -- Prior Year Actual and Current Year Budget + select + bc.BudgetConfigID, + ec.EntityID, + ec.DepartmentID, + ec.FiscalYearID, + TimeClassID, + Value, + UnitTypeID, + ec.ServiceLineID, + ec.ServiceLineRollupID, + ec.PatientClassID, + ec.AgeCohortID, + ec.MedicalSurgicalID, + ec.PayorID, + ec.PayorGroupID, + ec.MSDRGID, + ec.CPTID, + ec.ProviderID, + ec.PhysicianSpecialtyID, + ec.FiscalMonthID + from EncHistory ec + INNER JOIN fp.BudgetConfig bc on ec.BudgetConfigID = bc.BudgetConfigID + WHERE TimeClassID in(1, 2) +GO + + +--------------------------------------------- + +-- fp.viewReportEncounter_Unpivoted +CREATE VIEW [fp].[viewReportEncounter_Unpivoted] +AS + -- Making sure final projection has all months included + SELECT fre_allmths.[BudgetConfigID], fre_allmths.[EntityID], + fre_allmths.[DepartmentID], fre_allmths.[ServiceLineID], + fre_allmths.[ServiceLineRollupID], fre_allmths.[PatientClassID], + fre_allmths.[AgeCohortID], fre_allmths.[MedicalSurgicalID], + fre_allmths.[PayorID], fre_allmths.[PayorGroupID], + fre_allmths.[MSDRGID], fre_allmths.[CPTID], + fre_allmths.[ProviderID], fre_allmths.[PhysicianSpecialtyID], + fre_allmths.[UnitTypeID], fre_allmths.[TimeClassID], + fre_allmths.[FiscalMonthID], fre_allmths.[FiscalYearID], + COALESCE(fre.Value, fre_allmths.Value) as Value + FROM ( + SELECT distinct [BudgetConfigID], [EntityID], [DepartmentID], [ServiceLineID], [ServiceLineRollupID], [PatientClassID], [AgeCohortID], + [MedicalSurgicalID],[PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], + [UnitTypeID], [TimeClassID], ca.[FiscalMonthID], [FiscalYearID], 0 as Value, 0 as OriginalValue, 0 as ManagerValue + FROM fp.viewReportEncounter_MonthsWithValues + CROSS APPLY ( + select FiscalMonthID + from [fw].[DimFiscalMonth] + WHERE FiscalMonthID != 0 + ) ca + WHERE TimeClassID IN (1, 2, 12, 21, 22) + ) fre_allmths + + LEFT JOIN (select * from fp.viewReportEncounter_MonthsWithValues) fre + ON fre_allmths.BudgetConfigID = fre.BudgetConfigID + and fre_allmths.DepartmentID = fre.DepartmentID + and fre_allmths.FiscalYearID = fre.FiscalYearID + and fre_allmths.TimeClassID = fre.TimeClassID + and fre_allmths.FiscalMonthID = fre.FiscalMonthID + and fre_allmths.ServiceLineID = fre.ServiceLineID + and fre_allmths.ServiceLineRollupID = fre.ServiceLineRollupID + and fre_allmths.PatientClassID = fre.PatientClassID + and fre_allmths.AgeCohortID = fre.AgeCohortID + and fre_allmths.MedicalSurgicalID = fre.MedicalSurgicalID + and fre_allmths.PayorID = fre.PayorID + and fre_allmths.PayorGroupID = fre.PayorGroupID + and fre_allmths.MSDRGID = fre.MSDRGID + and fre_allmths.CPTID = fre.CPTID + and fre_allmths.ProviderID = fre.ProviderID + and fre_allmths.PhysicianSpecialtyID = fre.PhysicianSpecialtyID + and fre_allmths.UnitTypeID = fre.UnitTypeID + and fre_allmths.EntityID = fre.EntityID +GO + + +--------------------------------------------- + +-- fp.viewReportFinancialStatements +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2019-04-16 IP B-22841 AP Income Statement Issues - Statistics +** 2 2020-05-04 LR D-09648 Data in wrong FinancialStatement ID +** 3 2023-06-26 MD JAZZ-54581 Simulate annualized time class +** 4 2024-07-18 DM JAZZ-72142 Included IsUsedForReportComparison budget config data +** 5 2024-10-17 MY JAZZ-78043 Annualized 2024 Time Class is not Calculating Correctly in IS + *************************************************************/ +CREATE VIEW [fp].[viewReportFinancialStatements] +as + -- GL Dollars, Projection + select + data.BudgetConfigID, + data.DepartmentID, + data.AccountID, + data.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID, + data.ManagerValue as Amount, + case when fm.SortOrder <= bc.MonthsLoaded then data.ManagerValue else 0 end as YTD, + data.ManagerValue as Yearly, + data.ManagerValue as Total + from + fp.viewFactGeneralLedger_UnPivoted data with (readuncommitted) + inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID + where + data.TimeClassID = 12 + and data.UnitTypeID = 34 + and (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1) + + union all + + -- GL Dollars, Target/Budget + select + data.BudgetConfigID, + data.DepartmentID, + data.AccountID, + data.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + tc.TimeClassID, + case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Amount, + case when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 2 then data.ManagerValue when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 20 then data.Value else 0 end as YTD, + case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Yearly, + case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Total + from + fp.viewFactGeneralLedger_UnPivoted data with (readuncommitted) + inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID + cross join fw.DimTimeClass tc with (readuncommitted) + where + data.TimeClassID = 2 + and data.UnitTypeID = 34 + and tc.TimeClassID in(2, 20) + and (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1) + + union all + + -- GL Dollars, Actual + select + data.BudgetConfigID, + data.DepartmentID, + data.AccountID, + data.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID, + data.Value as Amount, + case when fm.SortOrder <= bc.MonthsLoaded then data.Value else 0 end as YTD, + data.Value as Yearly, + data.Value as Total + from + [fp].[viewFactGeneralLedgerHistory_Unpivoted] data with (readuncommitted) + inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID + where + data.UnitTypeID = 34 + and (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1) + + union all + + -- GL Dollars, Annualized + -- --------------------JAZZ-54581--------------------------------------------------- + -- We are adding in the annualized time class as a valid time class for AP Income Statement + -- All data that is not generated by procReportFactStatisticsISBackup is pulled from the source tables in this view. + -- Timeclass 19 (annualized) is the annualized version of current year actuals. The below case statements are annualizing + -- current year actual data, taking into account leap year. The leap year logic has been pulled + -- directly from procReportFactStatisticsISBackup + -- BTB + -- --------------------JAZZ-54581--------------------------------------------------- + select + data.BudgetConfigID, + data.DepartmentID, + data.AccountID, + data.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + 19 TimeClassID, + (CASE WHEN + ((bc.FiscalYearID - 1) % 4 = 0) AND ((bc.FiscalYearID - 1) % 100 <> 0) OR ((bc.FiscalYearID - 1) % 400 = 0) + THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) + ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END) as Amount, + CASE WHEN fm.SortOrder <= bc.MonthsLoaded + THEN (CASE WHEN ((bc.FiscalYearID - 1) % 4 = 0) AND ((bc.FiscalYearID - 1) % 100 <> 0) OR ((bc.FiscalYearID - 1) % 400 = 0) + THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) + ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END) + ELSE 0 END as YTD, + (CASE WHEN ((bc.FiscalYearID - 1) % 4 = 0) AND ((bc.FiscalYearID - 1) % 100 <> 0) OR ((bc.FiscalYearID - 1) % 400 = 0) + THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) + ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END) as Yearly, + (CASE WHEN ((bc.FiscalYearID - 1) % 4 = 0) AND ((bc.FiscalYearID - 1) % 100 <> 0) OR ((bc.FiscalYearID - 1) % 400 = 0) + THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) + ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END) as Total + from + [fp].[viewFactGeneralLedgerHistory_Unpivoted] data with (readuncommitted) + inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID + inner join fw.DimFiscalMonth fm2 on bc.MonthsLoaded = fm2.SortOrder --To get YTD days in month + inner join fw.DimFiscalMonth fm3 on fm3.SortOrder = 12 --To get YTD days in full year + where + data.UnitTypeID = 34 + and (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1) + and data.TimeClassID = 1 + and data.FiscalYearID = bc.FiscalYearID - 1 + + union all + + -- Statistics, Projection + select + data.BudgetConfigID, + data.DepartmentID, + data.AccountID, + data.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID, + data.ManagerValue as Amount, + case when fm.SortOrder <= bc.MonthsLoaded then data.ManagerValue else 0 end as YTD, + data.ManagerValue as Yearly, + data.ManagerValue as Total + from + fp.viewFactStatistics_UnPivoted data with (readuncommitted) + inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID + where + data.TimeClassID = 12 + and (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1) + + union all + + -- Statistics, Target/Budget + select + data.BudgetConfigID, + data.DepartmentID, + data.AccountID, + data.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + tc.TimeClassID, + case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Amount, + case when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 2 then data.ManagerValue when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 20 then data.Value else 0 end as YTD, + case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Yearly, + case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Total + from + fp.viewFactStatistics_UnPivoted data with (readuncommitted) + inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID + cross join fw.DimTimeClass tc with (readuncommitted) + where + data.TimeClassID = 2 + and tc.TimeClassID in(2, 20) + and (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1) + + union all + + -- Statistics, Actual + select + data.BudgetConfigID, + data.DepartmentID, + data.AccountID, + data.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID, + data.Value as Amount, + case when fm.SortOrder <= bc.MonthsLoaded then data.Value else 0 end as YTD, + data.Value as Yearly, + data.Value as Total + from + [fp].[viewFactStatisticsHistory_Unpivoted] data with (readuncommitted) + inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID + WHERE bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1 + + union all + + -- Statistics, Annualized + -- --------------------JAZZ-54581--------------------------------------------------- + -- We are adding in the annualized time class as a valid time class for AP Income Statement + -- All data that is not generated by procReportFactStatisticsISBackup is pulled from the source tables in this view. + -- Timeclass 19 (annualized) is the annualized version of current year actuals. The below case statements are annualizing + -- current year actual data, taking into account leap year. The leap year logic has been pulled + -- directly from procReportFactStatisticsISBackup + -- BTB + -- --------------------JAZZ-54581--------------------------------------------------- + select + data.BudgetConfigID, + data.DepartmentID, + data.AccountID, + data.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + 19 as TimeClassID, + (CASE WHEN ((bc.FiscalYearID) - 1 % 4 = 0 AND (bc.FiscalYearID) - 1 % 100 <> 0) OR (bc.FiscalYearID) - 1 % 400 = 0 + THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) + ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END) as Amount, + CASE WHEN fm.SortOrder <= bc.MonthsLoaded + THEN (CASE WHEN ((bc.FiscalYearID) - 1 % 4 = 0 AND (bc.FiscalYearID) - 1 % 100 <> 0) OR (bc.FiscalYearID) - 1 % 400 = 0 + THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) + ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END) + ELSE 0 END as YTD, + (CASE WHEN ((bc.FiscalYearID) - 1 % 4 = 0 AND (bc.FiscalYearID) - 1 % 100 <> 0) OR (bc.FiscalYearID) - 1 % 400 = 0 + THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) + ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END) as Yearly, + (CASE WHEN ((bc.FiscalYearID) - 1 % 4 = 0 AND (bc.FiscalYearID) - 1 % 100 <> 0) OR (bc.FiscalYearID) - 1 % 400 = 0 + THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) + ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END) as Total + from + [fp].[viewFactStatisticsHistory_Unpivoted] data with (readuncommitted) + inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID + inner join fw.DimFiscalMonth fm2 on bc.MonthsLoaded = fm2.SortOrder --To get YTD days in month + inner join fw.DimFiscalMonth fm3 on fm3.SortOrder = 12 --To get YTD days in full year + WHERE (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1) + and data.TimeClassID = 1 + and data.FiscalYearID = bc.FiscalYearID - 1 + + union all + + -- Staffing Hours, Projection + select + data.BudgetConfigID, + data.DepartmentID, + 0 as AccountID, + CASE + WHEN data.ProductiveClassID = 2 AND data.UnitTypeID = 51 THEN 576 + WHEN data.ProductiveClassID = 3 AND data.UnitTypeID = 51 THEN 575 + ELSE 0 + END AS FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID, + data.ManagerValue as Amount, + case when fm.SortOrder <= bc.MonthsLoaded then data.ManagerValue else 0 end as YTD, + data.ManagerValue as Yearly, + data.ManagerValue as Total + from + fp.viewFactStaffing_UnPivoted data with (readuncommitted) + inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID + where + data.UnitTypeID = 51 + and data.TimeClassID = 12 + and (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1) + + union all + + -- Staffing Hours, Target/Budget + select + data.BudgetConfigID, + data.DepartmentID, + 0 as AccountID, + CASE + WHEN data.ProductiveClassID = 2 AND data.UnitTypeID = 51 THEN 576 + WHEN data.ProductiveClassID = 3 AND data.UnitTypeID = 51 THEN 575 + ELSE 0 + END AS FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + tc.TimeClassID, + case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Amount, + case when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 2 then data.ManagerValue when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 20 then data.Value else 0 end as YTD, + case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Yearly, + case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Total + from + fp.viewFactStaffing_UnPivoted data with (readuncommitted) + inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID + cross join fw.DimTimeClass tc with (readuncommitted) + where + data.UnitTypeID = 51 + and data.TimeClassID = 2 + and tc.TimeClassID in(2, 20) + and (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1) + + union all + + -- Staffing, Actual + select + data.BudgetConfigID, + data.DepartmentID, + 0 as AccountID, + CASE + WHEN data.ProductiveClassID = 2 AND data.UnitTypeID = 51 THEN 576 + WHEN data.ProductiveClassID = 3 AND data.UnitTypeID = 51 THEN 575 + ELSE 0 + END AS FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID, + data.Value as Amount, + case when fm.SortOrder <= bc.MonthsLoaded then data.Value else 0 end as YTD, + data.Value as Yearly, + data.Value as Total + from + [fp].[viewFactStaffingHistory_Unpivoted] data with (readuncommitted) + inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID + where + data.UnitTypeID = 51 + and (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1) + + union all + + -- Staffing, Annualized + -- --------------------JAZZ-54581--------------------------------------------------- + -- We are adding in the annualized time class as a valid time class for AP Income Statement + -- All data that is not generated by procReportFactStatisticsISBackup is pulled from the source tables in this view. + -- Timeclass 19 (annualized) is the annualized version of current year actuals. The below case statements are annualizing + -- current year actual data, taking into account leap year. The leap year logic has been pulled + -- directly from procReportFactStatisticsISBackup + -- BTB + -- --------------------JAZZ-54581--------------------------------------------------- + select + data.BudgetConfigID, + data.DepartmentID, + 0 as AccountID, + CASE + WHEN data.ProductiveClassID = 2 AND data.UnitTypeID = 51 THEN 576 + WHEN data.ProductiveClassID = 3 AND data.UnitTypeID = 51 THEN 575 + ELSE 0 + END AS FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + 19 as TimeClassID, + (CASE WHEN ((bc.FiscalYearID) - 1 % 4 = 0 AND (bc.FiscalYearID) - 1 % 100 <> 0) OR (bc.FiscalYearID) - 1 % 400 = 0 + THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) + ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END) as Amount, + CASE WHEN fm.SortOrder <= bc.MonthsLoaded + THEN (CASE WHEN ((bc.FiscalYearID) - 1 % 4 = 0 AND (bc.FiscalYearID) - 1 % 100 <> 0) OR (bc.FiscalYearID) - 1 % 400 = 0 + THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) + ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END) + ELSE 0 END as YTD, + (CASE WHEN ((bc.FiscalYearID) - 1 % 4 = 0 AND (bc.FiscalYearID) - 1 % 100 <> 0) OR (bc.FiscalYearID) - 1 % 400 = 0 + THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) + ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END) as Yearly, + (CASE WHEN ((bc.FiscalYearID) - 1 % 4 = 0 AND (bc.FiscalYearID) - 1 % 100 <> 0) OR (bc.FiscalYearID) - 1 % 400 = 0 + THEN ((data.Value / fm2.YTDDaysInLeapYearMonth) * fm3.YTDDaysInLeapYearMonth) + ELSE ((data.Value / fm2.YTDDaysInMonth) * fm3.YTDDaysInMonth) END) as Total + from + [fp].[viewFactStaffingHistory_Unpivoted] data with (readuncommitted) + inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID + inner join fw.DimFiscalMonth fm2 on bc.MonthsLoaded = fm2.SortOrder --To get YTD days in month + inner join fw.DimFiscalMonth fm3 on fm3.SortOrder = 12 --To get YTD days in full year + where + data.UnitTypeID = 51 + and (bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1) + and data.TimeClassID = 1 + and data.FiscalYearID = bc.FiscalYearID - 1 + + union all + + select + data.BudgetConfigID, + data.DepartmentID, + data.AccountID, + data.FinancialReportingID, --Stats - Other - Working Hours + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID, + data.Amount, + data.YTD, + data.Yearly, + data.Total + FROM fp.FactISReportStatistics data + INNER JOIN fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + WHERE bc.IsActive = 1 OR bc.IsUsedForReportComparison = 1 +GO + + +--------------------------------------------- + +-- fp.viewReportFinancialStatements_archive +CREATE view [fp].[viewReportFinancialStatements_archive] +as + -- GL Dollars, Projection + select + data.BudgetConfigID, + data.DepartmentID, + data.AccountID, + data.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID, + data.Value as Amount, + case when fm.SortOrder <= bc.MonthsLoaded then data.Value else 0 end as YTD, + data.Value as Yearly, + data.Value as Total + from + fp.viewFactGeneralLedger_UnPivoted_archive data with (readuncommitted) + inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID + where + data.TimeClassID = 12 + and data.UnitTypeID = 34 + + union all + + -- GL Dollars, Target/Budget + select + data.BudgetConfigID, + data.DepartmentID, + data.AccountID, + data.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + tc.TimeClassID, + case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Amount, + case when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 2 then data.ManagerValue when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 20 then data.Value else 0 end as YTD, + case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Yearly, + case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Total + from + fp.viewFactGeneralLedger_UnPivoted_archive data with (readuncommitted) + inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID + cross join fw.DimTimeClass tc with (readuncommitted) + where + data.TimeClassID = 2 + and data.UnitTypeID = 34 + and tc.TimeClassID in(2, 20) + + union all + + -- GL Dollars, Actual + select + data.BudgetConfigID, + data.DepartmentID, + data.AccountID, + data.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID, + data.Value as Amount, + case when fm.SortOrder <= bc.MonthsLoaded then data.Value else 0 end as YTD, + data.Value as Yearly, + data.Value as Total + from + [fp].[viewFactGeneralLedgerHistory_Unpivoted_archive] data with (readuncommitted) + inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID + where + data.UnitTypeID = 34 + + union all + + -- Statistics, Projection + select + data.BudgetConfigID, + data.DepartmentID, + data.AccountID, + data.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID, + data.Value as Amount, + case when fm.SortOrder <= bc.MonthsLoaded then data.Value else 0 end as YTD, + data.Value as Yearly, + data.Value as Total + from + fp.viewFactStatistics_UnPivoted_archive data with (readuncommitted) + inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID + where + data.TimeClassID = 12 + + union all + + -- Statistics, Target/Budget + select + data.BudgetConfigID, + data.DepartmentID, + data.AccountID, + data.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + tc.TimeClassID, + case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Amount, + case when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 2 then data.ManagerValue when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 20 then data.Value else 0 end as YTD, + case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Yearly, + case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Total + from + fp.viewFactStatistics_UnPivoted_archive data with (readuncommitted) + inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID + cross join fw.DimTimeClass tc with (readuncommitted) + where + data.TimeClassID = 2 + and tc.TimeClassID in(2, 20) + + union all + + -- Statistics, Actual + select + data.BudgetConfigID, + data.DepartmentID, + data.AccountID, + data.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID, + data.Value as Amount, + case when fm.SortOrder <= bc.MonthsLoaded then data.Value else 0 end as YTD, + data.Value as Yearly, + data.Value as Total + from + [fp].[viewFactStatisticsHistory_Unpivoted_archive] data with (readuncommitted) + inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID + + union all + + -- Staffing Hours, Projection + select + data.BudgetConfigID, + data.DepartmentID, + 0 as AccountID, + CASE + WHEN data.ProductiveClassID = 2 AND data.UnitTypeID = 51 THEN 576 + WHEN data.ProductiveClassID = 3 AND data.UnitTypeID = 51 THEN 575 + WHEN data.ProductiveClassID = 0 AND data.UnitTypeID = 51 THEN 4029 + ELSE 0 + END AS FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID, + data.Value as Amount, + case when fm.SortOrder <= bc.MonthsLoaded then data.Value else 0 end as YTD, + data.Value as Yearly, + data.Value as Total + from + fp.viewFactStaffing_UnPivoted_archive data with (readuncommitted) + inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID + where + data.UnitTypeID = 51 + and data.TimeClassID = 12 + + union all + + -- Staffing Hours, Target/Budget + select + data.BudgetConfigID, + data.DepartmentID, + 0 as AccountID, + CASE + WHEN data.ProductiveClassID = 2 AND data.UnitTypeID = 51 THEN 576 + WHEN data.ProductiveClassID = 3 AND data.UnitTypeID = 51 THEN 575 + WHEN data.ProductiveClassID = 0 AND data.UnitTypeID = 51 THEN 4029 + ELSE 0 + END AS FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + tc.TimeClassID, + case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Amount, + case when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 2 then data.ManagerValue when fm.SortOrder <= bc.MonthsLoaded and tc.TimeClassID = 20 then data.Value else 0 end as YTD, + case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Yearly, + case when tc.TimeClassID = 2 then data.ManagerValue else data.Value end as Total + from + fp.viewFactStaffing_UnPivoted_archive data with (readuncommitted) + inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID + cross join fw.DimTimeClass tc with (readuncommitted) + where + data.UnitTypeID = 51 + and data.TimeClassID = 2 + and tc.TimeClassID in(2, 20) + + union all + + -- Staffing, Actual + select + data.BudgetConfigID, + data.DepartmentID, + 0 as AccountID, + CASE + WHEN data.ProductiveClassID = 2 AND data.UnitTypeID = 51 THEN 576 + WHEN data.ProductiveClassID = 3 AND data.UnitTypeID = 51 THEN 575 + WHEN data.ProductiveClassID = 0 AND data.UnitTypeID = 51 THEN 4029 + ELSE 0 + END AS FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID, + data.Value as Amount, + case when fm.SortOrder <= bc.MonthsLoaded then data.Value else 0 end as YTD, + data.Value as Yearly, + data.Value as Total + from + [fp].[viewFactStaffingHistory_Unpivoted_archive] data with (readuncommitted) + inner join fp.BudgetConfig bc with (readuncommitted) on bc.BudgetConfigID = data.BudgetConfigID + inner join [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = data.FiscalMonthID + where + data.UnitTypeID = 51 + + union all + + -- Working Hours - Monthly + select + bc.BudgetConfigID, + d.DepartmentID, + 0 as AccountID, + 1015 as FinancialReportingID, --Stats - Other - Working Hours + WH.FiscalYearID, + WH.FiscalMonthID, + tc.TimeClassID, + WH.Hours as Amount, + WH.YTDHours as AmountYTD, + WH.Hours as Yearly, + WH.Hours as Total + FROM + [fw].[DimDepartment] d with (readuncommitted) + INNER JOIN [fw].[DimWorkWeek] ww WITH (READUNCOMMITTED) ON ww.WorkWeekID = d.WorkWeekID + INNER JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] WH ON ww.WorkWeekID = WH.WorkWeekID + INNER JOIN fp.BudgetConfig bc with (readuncommitted) ON bc.FiscalYearID = WH.FiscalYearID or bc.FiscalYearID - 1 = WH.FiscalYearID or bc.FiscalYearID - 2 = WH.FiscalYearID + CROSS JOIN [fw].[DimTimeClass] tc with (readuncommitted) + WHERE + tc.TimeClassID in(1, 2, 12, 20) + and bc.IsActive = 0 + + union all + + -- Working Hours - Annual + select + bc.BudgetConfigID, + d.DepartmentID, + 0 as AccountID, + 1015 as FinancialReportingID, --Stats - Other - Working Hours + WH.FiscalYearID, + 0 as FiscalMonthID, + tc.TimeClassID, + SUM(WH.Hours) as Amount, + SUM(WH.Hours) as AmountYTD, + SUM(WH.Hours) as Yearly, + SUM(WH.Hours) as Total + FROM + [fw].[DimDepartment] d with (readuncommitted) + INNER JOIN [fw].[DimWorkWeek] ww WITH (READUNCOMMITTED) ON ww.WorkWeekID = d.WorkWeekID + INNER JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] WH ON ww.WorkWeekID = WH.WorkWeekID + INNER JOIN fp.BudgetConfig bc with (readuncommitted) ON bc.FiscalYearID = WH.FiscalYearID or bc.FiscalYearID - 1 = WH.FiscalYearID or bc.FiscalYearID - 2 = WH.FiscalYearID + CROSS JOIN [fw].[DimTimeClass] tc with (readuncommitted) + WHERE + tc.TimeClassID in(1, 2, 12, 20) + and bc.IsActive = 0 + GROUP BY + bc.BudgetConfigID, + d.DepartmentID, + WH.FiscalYearID, + tc.TimeClassID +GO + + +--------------------------------------------- + +-- fp.viewReportGeneralLedger +CREATE VIEW [fp].[viewReportGeneralLedger] +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2020-04-22 LR D-09178 Including months with value zero on projection, so that reports wont have null values. + ** 2 2020-04-23 LR D-09151 Breaking down results by TimeCLassID, so that labels are displayed correctly in report. + *************************************************************/ +SELECT + factReportGL_AllMonths.[BudgetConfigID], + factReportGL_AllMonths.[DepartmentID], + factReportGL_AllMonths.[EntityID], + factReportGL_AllMonths.[AccountID], + factReportGL_AllMonths.[FiscalYearID], + factReportGL_AllMonths.[FiscalMonthID], + factReportGL_AllMonths.[TimeClassID], + factReportGL_AllMonths.VariabilityID, + acc.PatientClassID, + COALESCE(vrgl.Value, factReportGL_AllMonths.Value) as Value +FROM ( + SELECT distinct budgetconfigID, DepartmentID, EntityID, AccountID, FiscalYearID, TimeClassID, VariabilityID, ca.FiscalMonthID, 0 as value + FROM fp.viewReportGeneralLedger_MonthsWithValues + CROSS APPLY ( + select FiscalMonthID + from [fw].[DimFiscalMonth] + WHERE FiscalMonthID != 0 + ) ca + ) factReportGL_AllMonths + +LEFT JOIN (select * from fp.viewReportGeneralLedger_MonthsWithValues) vrgl + ON factReportGL_AllMonths.BudgetConfigID = vrgl.BudgetConfigID + and factReportGL_AllMonths.DepartmentID = vrgl.DepartmentID + and factReportGL_AllMonths.AccountID = vrgl.AccountID + and factReportGL_AllMonths.FiscalYearID = vrgl.FiscalYearID + and factReportGL_AllMonths.TimeClassID = vrgl.TimeClassID + and factReportGL_AllMonths.VariabilityID = vrgl.VariabilityID + and factReportGL_AllMonths.FiscalMonthID = vrgl.FiscalMonthID + +INNER JOIN [fw].[DimAccount] acc (READUNCOMMITTED) ON acc.AccountID = factReportGL_AllMonths.AccountID +INNER JOIN [fp].[BudgetConfig] bc (READUNCOMMITTED) ON bc.BudgetConfigID = factReportGL_AllMonths.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewReportGeneralLedgerInitiatives +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 8-17-2023 MY JAZZ-58792 Update to new structure +*************************************************************/ +CREATE VIEW fp.viewReportGeneralLedgerInitiatives +AS +SELECT + gl.BudgetConfigID, + gl.DepartmentID, + gl.EntityID, + gl.AccountID, + bc.FiscalYearID, + acc.PatientClassID, + gli.FiscalMonthID, + gli.InitiativeForecast +FROM fp.GeneralLedger gl +JOIN fw.DimAccount acc (READUNCOMMITTED) ON acc.AccountID = gl.AccountID +JOIN fp.BudgetConfig bc (READUNCOMMITTED) ON bc.BudgetConfigID = gl.BudgetConfigID +JOIN ( + SELECT + GeneralLedgerID, + InitiativeForecast, + CASE + WHEN FiscalMonthID = 'InitiativeForecast01' THEN 1 + WHEN FiscalMonthID = 'InitiativeForecast02' THEN 2 + WHEN FiscalMonthID = 'InitiativeForecast03' THEN 3 + WHEN FiscalMonthID = 'InitiativeForecast04' THEN 4 + WHEN FiscalMonthID = 'InitiativeForecast05' THEN 5 + WHEN FiscalMonthID = 'InitiativeForecast06' THEN 6 + WHEN FiscalMonthID = 'InitiativeForecast07' THEN 7 + WHEN FiscalMonthID = 'InitiativeForecast08' THEN 8 + WHEN FiscalMonthID = 'InitiativeForecast09' THEN 9 + WHEN FiscalMonthID = 'InitiativeForecast10' THEN 10 + WHEN FiscalMonthID = 'InitiativeForecast11' THEN 11 + WHEN FiscalMonthID = 'InitiativeForecast12' THEN 12 + END AS FiscalMonthID + FROM fp.FactGeneralLedgerInitiative + UNPIVOT (InitiativeForecast FOR FiscalMonthID IN ( + InitiativeForecast01, + InitiativeForecast02, + InitiativeForecast03, + InitiativeForecast04, + InitiativeForecast05, + InitiativeForecast06, + InitiativeForecast07, + InitiativeForecast08, + InitiativeForecast09, + InitiativeForecast10, + InitiativeForecast11, + InitiativeForecast12 + )) unpivoted +) gli on gl.GeneralLedgerID = gli.GeneralLedgerID +GO + + +--------------------------------------------- + +-- fp.viewReportGeneralLedgerSnapshot +CREATE VIEW [fp].[viewReportGeneralLedgerSnapshot] +AS +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2024-11-04 MY JAZZ-77737 Initial +***************************************************************/ + +------------------------------------ +-- This is a copy of fp.viewReportGeneralLedger essentially except cleaned up and adopted for Snapshots. +------------------------------------ + +WITH GL AS ( + SELECT * FROM [fp].[viewFactGeneralLedgerSnapshot_UnPivoted] +), +viewReportGeneralLedger_MonthsWithValues AS ( + -- Manager Projection + SELECT + SnapshotID, + bc.BudgetConfigID, + st.EntityID, + st.DepartmentID, + st.AccountID, + bc.FiscalYearID - 1 as FiscalYearID, + 12 as TimeClassID, + ManagerValue as Value, + IsStat, + UnitTypeID, + st.FinancialReportingID, + acc.PatientClassID, + VariabilityID, + FiscalMonthID + FROM GL st + INNER JOIN fp.BudgetConfig bc on st.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = st.AccountID + WHERE TimeClassID = 12 + + UNION ALL + + -- Initial Budget + SELECT + SnapshotID, + BudgetConfigID, + st.EntityID, + st.DepartmentID, + st.AccountID, + FiscalYearID, + 21 as TimeClassID, + OriginalValue as Value, + IsStat, + UnitTypeID, + st.FinancialReportingID, + acc.PatientClassID, + VariabilityID, + FiscalMonthID + FROM GL st + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = st.AccountID + WHERE TimeClassID = 2 + + UNION ALL + + -- Manager Budget + SELECT + SnapshotID, + BudgetConfigID, + st.EntityID, + st.DepartmentID, + st.AccountID, + FiscalYearID, + 2 as TimeClassID, + ManagerValue as Value, + IsStat, + UnitTypeID, + st.FinancialReportingID, + acc.PatientClassID, + VariabilityID, + FiscalMonthID + FROM GL st + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = st.AccountID + WHERE TimeClassID = 2 + + UNION ALL + + -- Baseline Budget + SELECT + SnapshotID, + BudgetConfigID, + st.EntityID, + st.DepartmentID, + st.AccountID, + FiscalYearID, + 22 as TimeClassID, + Value, + IsStat, + UnitTypeID, + st.FinancialReportingID, + acc.PatientClassID, + VariabilityID, + FiscalMonthID + FROM GL st + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = st.AccountID + WHERE TimeClassID = 2 + +) +SELECT + factReportGL_AllMonths.[SnapshotID], + factReportGL_AllMonths.[BudgetConfigID], + factReportGL_AllMonths.[DepartmentID], + factReportGL_AllMonths.[EntityID], + factReportGL_AllMonths.[AccountID], + factReportGL_AllMonths.[FiscalYearID], + factReportGL_AllMonths.[FiscalMonthID], + factReportGL_AllMonths.[TimeClassID], + factReportGL_AllMonths.VariabilityID, + acc.PatientClassID, + COALESCE(vrgl.Value, factReportGL_AllMonths.Value) AS Value +FROM ( + SELECT DISTINCT SnapshotID, budgetconfigID, DepartmentID, EntityID, AccountID, FiscalYearID, TimeClassID, VariabilityID, ca.FiscalMonthID, 0 as value + FROM viewReportGeneralLedger_MonthsWithValues + CROSS APPLY ( + select FiscalMonthID + from [fw].[DimFiscalMonth] + WHERE FiscalMonthID != 0 + ) ca + ) factReportGL_AllMonths + -- Not a fan of this, but the original is doing this too and I don't know the reason so I am leaving it. + LEFT JOIN ( + SELECT * FROM viewReportGeneralLedger_MonthsWithValues + ) vrgl + ON factReportGL_AllMonths.BudgetConfigID = vrgl.BudgetConfigID + and factReportGL_AllMonths.SnapshotID = vrgl.SnapshotID + and factReportGL_AllMonths.DepartmentID = vrgl.DepartmentID + and factReportGL_AllMonths.AccountID = vrgl.AccountID + and factReportGL_AllMonths.FiscalYearID = vrgl.FiscalYearID + and factReportGL_AllMonths.TimeClassID = vrgl.TimeClassID + and factReportGL_AllMonths.VariabilityID = vrgl.VariabilityID + and factReportGL_AllMonths.FiscalMonthID = vrgl.FiscalMonthID + INNER JOIN [fw].[DimAccount] acc (READUNCOMMITTED) ON acc.AccountID = factReportGL_AllMonths.AccountID + INNER JOIN [fp].[BudgetConfig] bc (READUNCOMMITTED) ON bc.BudgetConfigID = factReportGL_AllMonths.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewReportGeneralLedger_MonthsWithValues +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2021-07-20 MattD JAZZ-23237 Added unions in for data transfer tables for CCHS +** 2 2021-11-21 MattD JAZZ-29894 Removed unions in for data transfer tables for CCHS +***************************************************************/ + + CREATE VIEW fp.viewReportGeneralLedger_MonthsWithValues + AS + WITH GL AS ( + select * from [fp].[viewFactGeneralLedger_UnPivoted] + ), + GLHistory AS ( + select * from [fp].[viewFactGeneralLedgerHistory_UnPivoted] + ) + + -- Manager Projection + SELECT + bc.BudgetConfigID, + st.EntityID, + st.DepartmentID, + st.AccountID, + bc.FiscalYearID-1 as FiscalYearID, + 12 as TimeClassID, + ManagerValue as Value, + IsStat, + UnitTypeID, + st.FinancialReportingID, + acc.PatientClassID, + VariabilityID, + FiscalMonthID + from GL st + INNER JOIN fp.BudgetConfig bc on st.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = st.AccountID + WHERE TimeClassID=12 + + union all + + -- Initial Budget + SELECT + BudgetConfigID, + st.EntityID, + st.DepartmentID, + st.AccountID, + FiscalYearID, + 21 as TimeClassID, + OriginalValue as Value, + IsStat, + UnitTypeID, + st.FinancialReportingID, + acc.PatientClassID, + VariabilityID, + FiscalMonthID + from GL st + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = st.AccountID + WHERE TimeClassID=2 + + union all + + -- Manager Budget + select + BudgetConfigID, + st.EntityID, + st.DepartmentID, + st.AccountID, + FiscalYearID, + 2 as TimeClassID, + ManagerValue as Value, + IsStat, + UnitTypeID, + st.FinancialReportingID, + acc.PatientClassID, + VariabilityID, + FiscalMonthID + from GL st + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = st.AccountID + WHERE TimeClassID=2 + + union all + + -- Baseline Budget + select + BudgetConfigID, + st.EntityID, + st.DepartmentID, + st.AccountID, + FiscalYearID, + 22 as TimeClassID, + Value, + IsStat, + UnitTypeID, + st.FinancialReportingID, + acc.PatientClassID, + VariabilityID, + FiscalMonthID + from GL st + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = st.AccountID + WHERE TimeClassID=2 + + union all + + -- Prior Year Actual and Current Year Budget + select + bc.BudgetConfigID, + st.EntityID, + st.DepartmentID, + st.AccountID, + st.FiscalYearID, + TimeClassID, + Value, + IsStat, + UnitTypeID, + st.FinancialReportingID, + acc.PatientClassID, + VariabilityID, + FiscalMonthID + from GLHistory st + INNER JOIN fp.BudgetConfig bc on st.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = st.AccountID + WHERE TimeClassID in(1, 2) +GO + + +--------------------------------------------- + +-- fp.viewReportGeneralLedger_WithFlex +/***** *********************************************************** +****** Author: lcunningham +****** Create Date: 2021-08-19 +****** Description: GL reporting view having Flex originating from Demo 3. +****** Last Modified: 2022-03-24 +****** GM Release: 2022.22 +****** *********************************************************** +****** Change History +****** *********************************************************** +****** CID Date Author WI Description +****** xx 2021-08-19 ljc xxxx-xxxxxxx Custom report view request +****** 1 2022-03-24 ljc JAZZ-28731 Pulling in Flex total instead of Flex impact and view name change +****** **********************************************************/ + +CREATE + + VIEW [fp].[viewReportGeneralLedger_WithFlex] + AS +SELECT [BudgetConfigID], + [DepartmentID], + [EntityID], + [AccountID], + [FiscalYearID], + [TimeClassID], + [VariabilityID], + [PatientClassID], + SUM([Value]) AS [Value] + + FROM [fp].[viewReportGeneralLedger] + + GROUP BY + [BudgetConfigID], + [DepartmentID], + [EntityID], + [AccountID], + [FiscalYearID], + [TimeClassID], + [VariabilityID], + [PatientClassID] + + UNION ALL + +SELECT [gl].[BudgetConfigID], + [gl].[DepartmentID], + [gl].[EntityID], + [gl].[AccountID], + [bc].[FiscalYearID], + '4' AS [TimeClassID], + [gl].[VariabilityID], + [acc].[PatientClassID], + SUM([glb].[FlexedValueTotal]) AS [Value] + + FROM [fp].[FactGeneralLedger] AS [gl] + INNER JOIN [fp].[FactGeneralLedgerBudget] AS [glb] + ON [gl].[GeneralLedgerID] = [glb].[GeneralLedgerID] + AND [glb].[BudgetPhaseID] = 2 -- Target + + INNER JOIN [fp].[BudgetConfig] AS [bc] + ON [bc].[BudgetConfigID] = [gl].[BudgetConfigID] + + INNER JOIN [fw].[DimAccount] AS [acc] + ON [acc].[AccountID] = [gl].[AccountID] + + WHERE [bc].[IsActive] = 1 + AND [gl].[UnitTypeID] = 34 + AND [glb].[FlexedValueTotal] != 0 + + GROUP BY + [gl].[BudgetConfigID], + [gl].[DepartmentID], + [gl].[EntityID], + [gl].[AccountID], + [bc].[FiscalYearID], + [gl].[VariabilityID], + [acc].[PatientClassID] + + UNION ALL + +SELECT [gl].[BudgetConfigID], + [gl].[DepartmentID], + [gl].[EntityID], + [gl].[AccountID], + [bc].[FiscalYearID] - 1 AS [FiscalYearID], + '4' AS [TimeClassID], + [gl].[VariabilityID], + [acc].[PatientClassID], + SUM([glb].[FlexedValueTotal]) AS [Value] + + FROM [fp].[FactGeneralLedger] AS [gl] + INNER JOIN [fp].[FactGeneralLedgerProjection] AS [glb] + ON [gl].[GeneralLedgerID] = [glb].[GeneralLedgerID] + AND [glb].[BudgetPhaseID] = 2 -- Target + + INNER JOIN [fp].[BudgetConfig] AS [bc] + ON [bc].[BudgetConfigID] = [gl].[BudgetConfigID] + + INNER JOIN [fw].[DimAccount] AS [acc] + ON [acc].[AccountID] = [gl].[AccountID] + + WHERE [bc].[IsActive] = 1 + AND [gl].[UnitTypeID] = 34 + AND [glb].[FlexedValueTotal] != 0 + + GROUP BY + [gl].[BudgetConfigID], + [gl].[DepartmentID], + [gl].[EntityID], + [gl].[AccountID], + [bc].[FiscalYearID], + [gl].[VariabilityID], + [acc].[PatientClassID]; +GO + + +--------------------------------------------- + +-- fp.viewReportStaffing +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2021-05-24 BW JAZZ-20170 Added missing EmployeeID in select statements; switch from MAX to SUM +*************************************************************/ + +CREATE VIEW [fp].[viewReportStaffing] +AS +WITH PivoUnpivo AS ( + SELECT BudgetConfigID + ,EntityID + ,DepartmentID + ,JobCodeID + ,PayCodeGroupID + ,VariabilityID + ,ProductiveClassID + ,UnitTypeID + ,TimeClassID + ,FiscalYearID + ,EmployeeID + ,SUM([01]) as OriginalValue01 + ,SUM([02]) as OriginalValue02 + ,SUM([03]) as OriginalValue03 + ,SUM([04]) as OriginalValue04 + ,SUM([05]) as OriginalValue05 + ,SUM([06]) as OriginalValue06 + ,SUM([07]) as OriginalValue07 + ,SUM([08]) as OriginalValue08 + ,SUM([09]) as OriginalValue09 + ,SUM([10]) as OriginalValue10 + ,SUM([11]) as OriginalValue11 + ,SUM([12]) as OriginalValue12 + ,SUM([01_2]) as Value01 + ,SUM([02_2]) as Value02 + ,SUM([03_2]) as Value03 + ,SUM([04_2]) as Value04 + ,SUM([05_2]) as Value05 + ,SUM([06_2]) as Value06 + ,SUM([07_2]) as Value07 + ,SUM([08_2]) as Value08 + ,SUM([09_2]) as Value09 + ,SUM([10_2]) as Value10 + ,SUM([11_2]) as Value11 + ,SUM([12_2]) as Value12 + ,SUM([01_3]) as ManagerValue01 + ,SUM([02_3]) as ManagerValue02 + ,SUM([03_3]) as ManagerValue03 + ,SUM([04_3]) as ManagerValue04 + ,SUM([05_3]) as ManagerValue05 + ,SUM([06_3]) as ManagerValue06 + ,SUM([07_3]) as ManagerValue07 + ,SUM([08_3]) as ManagerValue08 + ,SUM([09_3]) as ManagerValue09 + ,SUM([10_3]) as ManagerValue10 + ,SUM([11_3]) as ManagerValue11 + ,SUM([12_3]) as ManagerValue12 + FROM ( + SELECT BudgetConfigID,EntityID,DepartmentID,JobCodeID,PayCodeGroupID,VariabilityID,ProductiveClassID,UnitTypeID,TimeClassID,RIGHT(fm.MonthColumnName,2) as FiscalMonthID,FiscalYearID,EmployeeID,OriginalValue,Value,ManagerValue,RIGHT(fm.MonthColumnName,2)+'_2' as FiscalMonthID_2,RIGHT(fm.MonthColumnName,2)+'_3' as FiscalMonthID_3 + FROM [fp].[FactReportStaffing] f with (readuncommitted) + INNER JOIN [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = f.FiscalMonthID + UNION ALL + SELECT BudgetConfigID,EntityID,DepartmentID,JobCodeID,PayCodeGroupID,VariabilityID,ProductiveClassID,UnitTypeID,TimeClassID,RIGHT(fm.MonthColumnName,2) as FiscalMonthID,FiscalYearID,EmployeeID,OriginalValue,Value,ManagerValue,RIGHT(fm.MonthColumnName,2)+'_2' as FiscalMonthID_2,RIGHT(fm.MonthColumnName,2)+'_3' as FiscalMonthID_3 + FROM [fp].[FactReportStaffing_archive] f with (readuncommitted) + INNER JOIN [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = f.FiscalMonthID + ) X + PIVOT (SUM(OriginalValue) FOR FiscalMonthID IN ([01],[02],[03],[04],[05],[06],[07],[08],[09],[10],[11],[12])) AS Pivot1 + PIVOT (SUM(Value) FOR FiscalMonthID_2 IN ([01_2],[02_2],[03_2],[04_2],[05_2],[06_2],[07_2],[08_2],[09_2],[10_2],[11_2],[12_2])) AS Pivot2 + PIVOT (SUM(ManagerValue) FOR FiscalMonthID_3 IN ([01_3],[02_3],[03_3],[04_3],[05_3],[06_3],[07_3],[08_3],[09_3],[10_3],[11_3],[12_3])) AS Pivot1 + GROUP BY + BudgetConfigID + ,EntityID + ,DepartmentID + ,JobCodeID + ,PayCodeGroupID + ,VariabilityID + ,ProductiveClassID + ,UnitTypeID + ,TimeClassID + ,FiscalYearID + ,EmployeeID +), +PivoUnpivoHistory AS ( + SELECT BudgetConfigID + ,EntityID + ,DepartmentID + ,JobCodeID + ,PayCodeGroupID + ,VariabilityID + ,ProductiveClassID + ,UnitTypeID + ,TimeClassID + ,FiscalYearID + ,EmployeeID + ,SUM([01]) as Value01 + ,SUM([02]) as Value02 + ,SUM([03]) as Value03 + ,SUM([04]) as Value04 + ,SUM([05]) as Value05 + ,SUM([06]) as Value06 + ,SUM([07]) as Value07 + ,SUM([08]) as Value08 + ,SUM([09]) as Value09 + ,SUM([10]) as Value10 + ,SUM([11]) as Value11 + ,SUM([12]) as Value12 + FROM ( + SELECT BudgetConfigID,EntityID,DepartmentID,JobCodeID,PayCodeGroupID,VariabilityID,ProductiveClassID,UnitTypeID,TimeClassID,RIGHT(fm.MonthColumnName,2) as FiscalMonthID,FiscalYearID,EmployeeID,Value + FROM [fp].[FactReportStaffingHistory] f with (readuncommitted) + INNER JOIN [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = f.FiscalMonthID + UNION ALL + SELECT BudgetConfigID,EntityID,DepartmentID,JobCodeID,PayCodeGroupID,VariabilityID,ProductiveClassID,UnitTypeID,TimeClassID,RIGHT(fm.MonthColumnName,2) as FiscalMonthID,FiscalYearID,EmployeeID,Value + FROM [fp].[FactReportStaffingHistory_archive] f with (readuncommitted) + INNER JOIN [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = f.FiscalMonthID + ) X + PIVOT (SUM(Value) FOR FiscalMonthID IN ([01],[02],[03],[04],[05],[06],[07],[08],[09],[10],[11],[12])) AS Pivot2 + GROUP BY BudgetConfigID + ,EntityID + ,DepartmentID + ,JobCodeID + ,PayCodeGroupID + ,VariabilityID + ,ProductiveClassID + ,UnitTypeID + ,TimeClassID + ,FiscalYearID + ,EmployeeID +) + +-- Manager Budget +SELECT + fs.DepartmentID, + fs.BudgetConfigID, + fs.JobCodeID, + fs.PayCodeGroupID, + bc.FiscalYearID, + fs.VariabilityID, + fs.TimeClassID, + fs.UnitTypeID, + fs.EmployeeID, + ISNULL(fs.ManagerValue01, 0.0) as Month01, + ISNULL(fs.ManagerValue02, 0.0) as Month02, + ISNULL(fs.ManagerValue03, 0.0) as Month03, + ISNULL(fs.ManagerValue04, 0.0) as Month04, + ISNULL(fs.ManagerValue05, 0.0) as Month05, + ISNULL(fs.ManagerValue06, 0.0) as Month06, + ISNULL(fs.ManagerValue07, 0.0) as Month07, + ISNULL(fs.ManagerValue08, 0.0) as Month08, + ISNULL(fs.ManagerValue09, 0.0) as Month09, + ISNULL(fs.ManagerValue10, 0.0) as Month10, + ISNULL(fs.ManagerValue11, 0.0) as Month11, + ISNULL(fs.ManagerValue12, 0.0) as Month12, + CASE + WHEN fs.UnitTypeID = 144 THEN ( + case when bc.MonthsLoaded >= 1 then (ISNULL(fs.ManagerValue01, 0.0) * fwh.Month01) else 0.0 end + + case when bc.MonthsLoaded >= 2 then (ISNULL(fs.ManagerValue02, 0.0) * fwh.Month02) else 0.0 end + + case when bc.MonthsLoaded >= 3 then (ISNULL(fs.ManagerValue03, 0.0) * fwh.Month03) else 0.0 end + + case when bc.MonthsLoaded >= 4 then (ISNULL(fs.ManagerValue04, 0.0) * fwh.Month04) else 0.0 end + + case when bc.MonthsLoaded >= 5 then (ISNULL(fs.ManagerValue05, 0.0) * fwh.Month05) else 0.0 end + + case when bc.MonthsLoaded >= 6 then (ISNULL(fs.ManagerValue06, 0.0) * fwh.Month06) else 0.0 end + + case when bc.MonthsLoaded >= 7 then (ISNULL(fs.ManagerValue07, 0.0) * fwh.Month07) else 0.0 end + + case when bc.MonthsLoaded >= 8 then (ISNULL(fs.ManagerValue08, 0.0) * fwh.Month08) else 0.0 end + + case when bc.MonthsLoaded >= 9 then (ISNULL(fs.ManagerValue09, 0.0) * fwh.Month09) else 0.0 end + + case when bc.MonthsLoaded >= 10 then (ISNULL(fs.ManagerValue10, 0.0) * fwh.Month10) else 0.0 end + + case when bc.MonthsLoaded >= 11 then (ISNULL(fs.ManagerValue11, 0.0) * fwh.Month11) else 0.0 end + + case when bc.MonthsLoaded >= 12 then (ISNULL(fs.ManagerValue12, 0.0) * fwh.Month12) else 0.0 end + ) / ( + case when bc.MonthsLoaded >= 1 then fwh.Month01 else 0.0 end + + case when bc.MonthsLoaded >= 2 then fwh.Month02 else 0.0 end + + case when bc.MonthsLoaded >= 3 then fwh.Month03 else 0.0 end + + case when bc.MonthsLoaded >= 4 then fwh.Month04 else 0.0 end + + case when bc.MonthsLoaded >= 5 then fwh.Month05 else 0.0 end + + case when bc.MonthsLoaded >= 6 then fwh.Month06 else 0.0 end + + case when bc.MonthsLoaded >= 7 then fwh.Month07 else 0.0 end + + case when bc.MonthsLoaded >= 8 then fwh.Month08 else 0.0 end + + case when bc.MonthsLoaded >= 9 then fwh.Month09 else 0.0 end + + case when bc.MonthsLoaded >= 10 then fwh.Month10 else 0.0 end + + case when bc.MonthsLoaded >= 11 then fwh.Month11 else 0.0 end + + case when bc.MonthsLoaded >= 12 then fwh.Month12 else 0.0 end + ) + ELSE ( + case when bc.MonthsLoaded >= 1 then ISNULL(fs.ManagerValue01, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 2 then ISNULL(fs.ManagerValue02, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 3 then ISNULL(fs.ManagerValue03, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 4 then ISNULL(fs.ManagerValue04, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 5 then ISNULL(fs.ManagerValue05, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 6 then ISNULL(fs.ManagerValue06, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 7 then ISNULL(fs.ManagerValue07, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 8 then ISNULL(fs.ManagerValue08, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 9 then ISNULL(fs.ManagerValue09, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 10 then ISNULL(fs.ManagerValue10, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 11 then ISNULL(fs.ManagerValue11, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 12 then ISNULL(fs.ManagerValue12, 0.0) else 0.0 end + ) + END AS YTD, + CASE + WHEN fs.UnitTypeID = 144 THEN ( + (ISNULL(fs.ManagerValue01, 0.0) * fwh.Month01) + + (ISNULL(fs.ManagerValue02, 0.0) * fwh.Month02) + + (ISNULL(fs.ManagerValue03, 0.0) * fwh.Month03) + + (ISNULL(fs.ManagerValue04, 0.0) * fwh.Month04) + + (ISNULL(fs.ManagerValue05, 0.0) * fwh.Month05) + + (ISNULL(fs.ManagerValue06, 0.0) * fwh.Month06) + + (ISNULL(fs.ManagerValue07, 0.0) * fwh.Month07) + + (ISNULL(fs.ManagerValue08, 0.0) * fwh.Month08) + + (ISNULL(fs.ManagerValue09, 0.0) * fwh.Month09) + + (ISNULL(fs.ManagerValue10, 0.0) * fwh.Month10) + + (ISNULL(fs.ManagerValue11, 0.0) * fwh.Month11) + + (ISNULL(fs.ManagerValue12, 0.0) * fwh.Month12) + ) / fwh.MonthYearly + ELSE ( + ISNULL(fs.ManagerValue01, 0.0) + + ISNULL(fs.ManagerValue02, 0.0) + + ISNULL(fs.ManagerValue03, 0.0) + + ISNULL(fs.ManagerValue04, 0.0) + + ISNULL(fs.ManagerValue05, 0.0) + + ISNULL(fs.ManagerValue06, 0.0) + + ISNULL(fs.ManagerValue07, 0.0) + + ISNULL(fs.ManagerValue08, 0.0) + + ISNULL(fs.ManagerValue09, 0.0) + + ISNULL(fs.ManagerValue10, 0.0) + + ISNULL(fs.ManagerValue11, 0.0) + + ISNULL(fs.ManagerValue12, 0.0) + ) + END AS Total +FROM + PivoUnpivo fs + INNER JOIN [fw].[DimDepartment] d with (readuncommitted) on d.DepartmentID = fs.DepartmentID + INNER JOIN [fw].[DimEntity] e with (readuncommitted) on e.EntityID = d.EntityID + INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID = fs.JobCodeID + INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [client].[FactWorkingHoursPerMonth] fwh with (readuncommitted) ON fwh.FiscalYearID = bc.FiscalYearID and fwh.WorkWeekID = case when jc.WorkWeekOverrideID > 0 then jc.WorkWeekOverrideID when d.WorkWeekID > 0 then d.WorkWeekID else e.WorkWeekID end + INNER JOIN [fw].[DimEmployee] emp with (readuncommitted) on emp.EmployeeID = fs.EmployeeID +WHERE + fs.TimeClassID=2 + +UNION ALL + +-- Initial Budget +SELECT + fs.DepartmentID, + fs.BudgetConfigID, + fs.JobCodeID, + fs.PayCodeGroupID, + bc.FiscalYearID, + fs.VariabilityID, + 21 AS TimeClassID, + fs.UnitTypeID, + fs.EmployeeID, + ISNULL(fs.OriginalValue01, 0.0) as Month01, + ISNULL(fs.OriginalValue02, 0.0) as Month02, + ISNULL(fs.OriginalValue03, 0.0) as Month03, + ISNULL(fs.OriginalValue04, 0.0) as Month04, + ISNULL(fs.OriginalValue05, 0.0) as Month05, + ISNULL(fs.OriginalValue06, 0.0) as Month06, + ISNULL(fs.OriginalValue07, 0.0) as Month07, + ISNULL(fs.OriginalValue08, 0.0) as Month08, + ISNULL(fs.OriginalValue09, 0.0) as Month09, + ISNULL(fs.OriginalValue10, 0.0) as Month10, + ISNULL(fs.OriginalValue11, 0.0) as Month11, + ISNULL(fs.OriginalValue12, 0.0) as Month12, + CASE + WHEN fs.UnitTypeID = 144 THEN ( + case when bc.MonthsLoaded >= 1 then (ISNULL(fs.OriginalValue01, 0.0) * fwh.Month01) else 0.0 end + + case when bc.MonthsLoaded >= 2 then (ISNULL(fs.OriginalValue02, 0.0) * fwh.Month02) else 0.0 end + + case when bc.MonthsLoaded >= 3 then (ISNULL(fs.OriginalValue03, 0.0) * fwh.Month03) else 0.0 end + + case when bc.MonthsLoaded >= 4 then (ISNULL(fs.OriginalValue04, 0.0) * fwh.Month04) else 0.0 end + + case when bc.MonthsLoaded >= 5 then (ISNULL(fs.OriginalValue05, 0.0) * fwh.Month05) else 0.0 end + + case when bc.MonthsLoaded >= 6 then (ISNULL(fs.OriginalValue06, 0.0) * fwh.Month06) else 0.0 end + + case when bc.MonthsLoaded >= 7 then (ISNULL(fs.OriginalValue07, 0.0) * fwh.Month07) else 0.0 end + + case when bc.MonthsLoaded >= 8 then (ISNULL(fs.OriginalValue08, 0.0) * fwh.Month08) else 0.0 end + + case when bc.MonthsLoaded >= 9 then (ISNULL(fs.OriginalValue09, 0.0) * fwh.Month09) else 0.0 end + + case when bc.MonthsLoaded >= 10 then (ISNULL(fs.OriginalValue10, 0.0) * fwh.Month10) else 0.0 end + + case when bc.MonthsLoaded >= 11 then (ISNULL(fs.OriginalValue11, 0.0) * fwh.Month11) else 0.0 end + + case when bc.MonthsLoaded >= 12 then (ISNULL(fs.OriginalValue12, 0.0) * fwh.Month12) else 0.0 end + ) / ( + case when bc.MonthsLoaded >= 1 then fwh.Month01 else 0.0 end + + case when bc.MonthsLoaded >= 2 then fwh.Month02 else 0.0 end + + case when bc.MonthsLoaded >= 3 then fwh.Month03 else 0.0 end + + case when bc.MonthsLoaded >= 4 then fwh.Month04 else 0.0 end + + case when bc.MonthsLoaded >= 5 then fwh.Month05 else 0.0 end + + case when bc.MonthsLoaded >= 6 then fwh.Month06 else 0.0 end + + case when bc.MonthsLoaded >= 7 then fwh.Month07 else 0.0 end + + case when bc.MonthsLoaded >= 8 then fwh.Month08 else 0.0 end + + case when bc.MonthsLoaded >= 9 then fwh.Month09 else 0.0 end + + case when bc.MonthsLoaded >= 10 then fwh.Month10 else 0.0 end + + case when bc.MonthsLoaded >= 11 then fwh.Month11 else 0.0 end + + case when bc.MonthsLoaded >= 12 then fwh.Month12 else 0.0 end + ) + ELSE ( + case when bc.MonthsLoaded >= 1 then ISNULL(fs.OriginalValue01, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 2 then ISNULL(fs.OriginalValue02, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 3 then ISNULL(fs.OriginalValue03, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 4 then ISNULL(fs.OriginalValue04, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 5 then ISNULL(fs.OriginalValue05, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 6 then ISNULL(fs.OriginalValue06, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 7 then ISNULL(fs.OriginalValue07, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 8 then ISNULL(fs.OriginalValue08, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 9 then ISNULL(fs.OriginalValue09, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 10 then ISNULL(fs.OriginalValue10, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 11 then ISNULL(fs.OriginalValue11, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 12 then ISNULL(fs.OriginalValue12, 0.0) else 0.0 end + ) + END AS YTD, + CASE + WHEN fs.UnitTypeID = 144 THEN ( + (ISNULL(fs.OriginalValue01, 0.0) * fwh.Month01) + + (ISNULL(fs.OriginalValue02, 0.0) * fwh.Month02) + + (ISNULL(fs.OriginalValue03, 0.0) * fwh.Month03) + + (ISNULL(fs.OriginalValue04, 0.0) * fwh.Month04) + + (ISNULL(fs.OriginalValue05, 0.0) * fwh.Month05) + + (ISNULL(fs.OriginalValue06, 0.0) * fwh.Month06) + + (ISNULL(fs.OriginalValue07, 0.0) * fwh.Month07) + + (ISNULL(fs.OriginalValue08, 0.0) * fwh.Month08) + + (ISNULL(fs.OriginalValue09, 0.0) * fwh.Month09) + + (ISNULL(fs.OriginalValue10, 0.0) * fwh.Month10) + + (ISNULL(fs.OriginalValue11, 0.0) * fwh.Month11) + + (ISNULL(fs.OriginalValue12, 0.0) * fwh.Month12) + ) / fwh.MonthYearly + ELSE ( + ISNULL(fs.OriginalValue01, 0.0) + + ISNULL(fs.OriginalValue02, 0.0) + + ISNULL(fs.OriginalValue03, 0.0) + + ISNULL(fs.OriginalValue04, 0.0) + + ISNULL(fs.OriginalValue05, 0.0) + + ISNULL(fs.OriginalValue06, 0.0) + + ISNULL(fs.OriginalValue07, 0.0) + + ISNULL(fs.OriginalValue08, 0.0) + + ISNULL(fs.OriginalValue09, 0.0) + + ISNULL(fs.OriginalValue10, 0.0) + + ISNULL(fs.OriginalValue11, 0.0) + + ISNULL(fs.OriginalValue12, 0.0) + ) + END AS Total +FROM + PivoUnpivo fs + INNER JOIN [fw].[DimDepartment] d with (readuncommitted) on d.DepartmentID = fs.DepartmentID + INNER JOIN [fw].[DimEntity] e with (readuncommitted) on e.EntityID = d.EntityID + INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID = fs.JobCodeID + INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [client].[FactWorkingHoursPerMonth] fwh with (readuncommitted) ON fwh.FiscalYearID = bc.FiscalYearID and fwh.WorkWeekID = case when jc.WorkWeekOverrideID > 0 then jc.WorkWeekOverrideID when d.WorkWeekID > 0 then d.WorkWeekID else e.WorkWeekID end + INNER JOIN [fw].[DimEmployee] emp with (readuncommitted) on emp.EmployeeID = fs.EmployeeID +WHERE + fs.TimeClassID=2 + +UNION ALL + +-- Baseline Budget +SELECT + fs.DepartmentID, + fs.BudgetConfigID, + fs.JobCodeID, + fs.PayCodeGroupID, + bc.FiscalYearID, + fs.VariabilityID, + 18 AS TimeClassID, + fs.UnitTypeID, + fs.EmployeeID, + ISNULL(fs.Value01, 0.0) as Month01, + ISNULL(fs.Value02, 0.0) as Month02, + ISNULL(fs.Value03, 0.0) as Month03, + ISNULL(fs.Value04, 0.0) as Month04, + ISNULL(fs.Value05, 0.0) as Month05, + ISNULL(fs.Value06, 0.0) as Month06, + ISNULL(fs.Value07, 0.0) as Month07, + ISNULL(fs.Value08, 0.0) as Month08, + ISNULL(fs.Value09, 0.0) as Month09, + ISNULL(fs.Value10, 0.0) as Month10, + ISNULL(fs.Value11, 0.0) as Month11, + ISNULL(fs.Value12, 0.0) as Month12, + CASE + WHEN fs.UnitTypeID = 144 THEN ( + case when bc.MonthsLoaded >= 1 then (ISNULL(fs.Value01, 0.0) * fwh.Month01) else 0.0 end + + case when bc.MonthsLoaded >= 2 then (ISNULL(fs.Value02, 0.0) * fwh.Month02) else 0.0 end + + case when bc.MonthsLoaded >= 3 then (ISNULL(fs.Value03, 0.0) * fwh.Month03) else 0.0 end + + case when bc.MonthsLoaded >= 4 then (ISNULL(fs.Value04, 0.0) * fwh.Month04) else 0.0 end + + case when bc.MonthsLoaded >= 5 then (ISNULL(fs.Value05, 0.0) * fwh.Month05) else 0.0 end + + case when bc.MonthsLoaded >= 6 then (ISNULL(fs.Value06, 0.0) * fwh.Month06) else 0.0 end + + case when bc.MonthsLoaded >= 7 then (ISNULL(fs.Value07, 0.0) * fwh.Month07) else 0.0 end + + case when bc.MonthsLoaded >= 8 then (ISNULL(fs.Value08, 0.0) * fwh.Month08) else 0.0 end + + case when bc.MonthsLoaded >= 9 then (ISNULL(fs.Value09, 0.0) * fwh.Month09) else 0.0 end + + case when bc.MonthsLoaded >= 10 then (ISNULL(fs.Value10, 0.0) * fwh.Month10) else 0.0 end + + case when bc.MonthsLoaded >= 11 then (ISNULL(fs.Value11, 0.0) * fwh.Month11) else 0.0 end + + case when bc.MonthsLoaded >= 12 then (ISNULL(fs.Value12, 0.0) * fwh.Month12) else 0.0 end + ) / ( + case when bc.MonthsLoaded >= 1 then fwh.Month01 else 0.0 end + + case when bc.MonthsLoaded >= 2 then fwh.Month02 else 0.0 end + + case when bc.MonthsLoaded >= 3 then fwh.Month03 else 0.0 end + + case when bc.MonthsLoaded >= 4 then fwh.Month04 else 0.0 end + + case when bc.MonthsLoaded >= 5 then fwh.Month05 else 0.0 end + + case when bc.MonthsLoaded >= 6 then fwh.Month06 else 0.0 end + + case when bc.MonthsLoaded >= 7 then fwh.Month07 else 0.0 end + + case when bc.MonthsLoaded >= 8 then fwh.Month08 else 0.0 end + + case when bc.MonthsLoaded >= 9 then fwh.Month09 else 0.0 end + + case when bc.MonthsLoaded >= 10 then fwh.Month10 else 0.0 end + + case when bc.MonthsLoaded >= 11 then fwh.Month11 else 0.0 end + + case when bc.MonthsLoaded >= 12 then fwh.Month12 else 0.0 end + ) + ELSE ( + case when bc.MonthsLoaded >= 1 then ISNULL(fs.Value01, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 2 then ISNULL(fs.Value02, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 3 then ISNULL(fs.Value03, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 4 then ISNULL(fs.Value04, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 5 then ISNULL(fs.Value05, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 6 then ISNULL(fs.Value06, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 7 then ISNULL(fs.Value07, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 8 then ISNULL(fs.Value08, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 9 then ISNULL(fs.Value09, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 10 then ISNULL(fs.Value10, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 11 then ISNULL(fs.Value11, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 12 then ISNULL(fs.Value12, 0.0) else 0.0 end + ) + END AS YTD, + CASE + WHEN fs.UnitTypeID = 144 THEN ( + (ISNULL(fs.Value01, 0.0) * fwh.Month01) + + (ISNULL(fs.Value02, 0.0) * fwh.Month02) + + (ISNULL(fs.Value03, 0.0) * fwh.Month03) + + (ISNULL(fs.Value04, 0.0) * fwh.Month04) + + (ISNULL(fs.Value05, 0.0) * fwh.Month05) + + (ISNULL(fs.Value06, 0.0) * fwh.Month06) + + (ISNULL(fs.Value07, 0.0) * fwh.Month07) + + (ISNULL(fs.Value08, 0.0) * fwh.Month08) + + (ISNULL(fs.Value09, 0.0) * fwh.Month09) + + (ISNULL(fs.Value10, 0.0) * fwh.Month10) + + (ISNULL(fs.Value11, 0.0) * fwh.Month11) + + (ISNULL(fs.Value12, 0.0) * fwh.Month12) + ) / fwh.MonthYearly + ELSE ( + ISNULL(fs.Value01, 0.0) + + ISNULL(fs.Value02, 0.0) + + ISNULL(fs.Value03, 0.0) + + ISNULL(fs.Value04, 0.0) + + ISNULL(fs.Value05, 0.0) + + ISNULL(fs.Value06, 0.0) + + ISNULL(fs.Value07, 0.0) + + ISNULL(fs.Value08, 0.0) + + ISNULL(fs.Value09, 0.0) + + ISNULL(fs.Value10, 0.0) + + ISNULL(fs.Value11, 0.0) + + ISNULL(fs.Value12, 0.0) + ) + END AS Total +FROM + PivoUnpivo fs + INNER JOIN [fw].[DimDepartment] d with (readuncommitted) on d.DepartmentID = fs.DepartmentID + INNER JOIN [fw].[DimEntity] e with (readuncommitted) on e.EntityID = d.EntityID + INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID = fs.JobCodeID + INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [client].[FactWorkingHoursPerMonth] fwh with (readuncommitted) ON fwh.FiscalYearID = bc.FiscalYearID and fwh.WorkWeekID = case when jc.WorkWeekOverrideID > 0 then jc.WorkWeekOverrideID when d.WorkWeekID > 0 then d.WorkWeekID else e.WorkWeekID end + INNER JOIN [fw].[DimEmployee] emp with (readuncommitted) on emp.EmployeeID = fs.EmployeeID +WHERE + fs.TimeClassID=2 + +UNION ALL + +-- Manager Projection +SELECT + fs.DepartmentID, + fs.BudgetConfigID, + fs.JobCodeID, + fs.PayCodeGroupID, + bc.FiscalYearID - 1 as FiscalYearID, + fs.VariabilityID, + 12 AS TimeClassID, + fs.UnitTypeID, + fs.EmployeeID, + ISNULL(fs.ManagerValue01, 0.0) as Month01, + ISNULL(fs.ManagerValue02, 0.0) as Month02, + ISNULL(fs.ManagerValue03, 0.0) as Month03, + ISNULL(fs.ManagerValue04, 0.0) as Month04, + ISNULL(fs.ManagerValue05, 0.0) as Month05, + ISNULL(fs.ManagerValue06, 0.0) as Month06, + ISNULL(fs.ManagerValue07, 0.0) as Month07, + ISNULL(fs.ManagerValue08, 0.0) as Month08, + ISNULL(fs.ManagerValue09, 0.0) as Month09, + ISNULL(fs.ManagerValue10, 0.0) as Month10, + ISNULL(fs.ManagerValue11, 0.0) as Month11, + ISNULL(fs.ManagerValue12, 0.0) as Month12, + CASE + WHEN fs.UnitTypeID = 144 THEN ( + case when bc.MonthsLoaded >= 1 then (ISNULL(fs.ManagerValue01, 0.0) * fwh.Month01) else 0.0 end + + case when bc.MonthsLoaded >= 2 then (ISNULL(fs.ManagerValue02, 0.0) * fwh.Month02) else 0.0 end + + case when bc.MonthsLoaded >= 3 then (ISNULL(fs.ManagerValue03, 0.0) * fwh.Month03) else 0.0 end + + case when bc.MonthsLoaded >= 4 then (ISNULL(fs.ManagerValue04, 0.0) * fwh.Month04) else 0.0 end + + case when bc.MonthsLoaded >= 5 then (ISNULL(fs.ManagerValue05, 0.0) * fwh.Month05) else 0.0 end + + case when bc.MonthsLoaded >= 6 then (ISNULL(fs.ManagerValue06, 0.0) * fwh.Month06) else 0.0 end + + case when bc.MonthsLoaded >= 7 then (ISNULL(fs.ManagerValue07, 0.0) * fwh.Month07) else 0.0 end + + case when bc.MonthsLoaded >= 8 then (ISNULL(fs.ManagerValue08, 0.0) * fwh.Month08) else 0.0 end + + case when bc.MonthsLoaded >= 9 then (ISNULL(fs.ManagerValue09, 0.0) * fwh.Month09) else 0.0 end + + case when bc.MonthsLoaded >= 10 then (ISNULL(fs.ManagerValue10, 0.0) * fwh.Month10) else 0.0 end + + case when bc.MonthsLoaded >= 11 then (ISNULL(fs.ManagerValue11, 0.0) * fwh.Month11) else 0.0 end + + case when bc.MonthsLoaded >= 12 then (ISNULL(fs.ManagerValue12, 0.0) * fwh.Month12) else 0.0 end + ) / ( + case when bc.MonthsLoaded >= 1 then fwh.Month01 else 0.0 end + + case when bc.MonthsLoaded >= 2 then fwh.Month02 else 0.0 end + + case when bc.MonthsLoaded >= 3 then fwh.Month03 else 0.0 end + + case when bc.MonthsLoaded >= 4 then fwh.Month04 else 0.0 end + + case when bc.MonthsLoaded >= 5 then fwh.Month05 else 0.0 end + + case when bc.MonthsLoaded >= 6 then fwh.Month06 else 0.0 end + + case when bc.MonthsLoaded >= 7 then fwh.Month07 else 0.0 end + + case when bc.MonthsLoaded >= 8 then fwh.Month08 else 0.0 end + + case when bc.MonthsLoaded >= 9 then fwh.Month09 else 0.0 end + + case when bc.MonthsLoaded >= 10 then fwh.Month10 else 0.0 end + + case when bc.MonthsLoaded >= 11 then fwh.Month11 else 0.0 end + + case when bc.MonthsLoaded >= 12 then fwh.Month12 else 0.0 end + ) + ELSE ( + case when bc.MonthsLoaded >= 1 then ISNULL(fs.ManagerValue01, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 2 then ISNULL(fs.ManagerValue02, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 3 then ISNULL(fs.ManagerValue03, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 4 then ISNULL(fs.ManagerValue04, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 5 then ISNULL(fs.ManagerValue05, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 6 then ISNULL(fs.ManagerValue06, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 7 then ISNULL(fs.ManagerValue07, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 8 then ISNULL(fs.ManagerValue08, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 9 then ISNULL(fs.ManagerValue09, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 10 then ISNULL(fs.ManagerValue10, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 11 then ISNULL(fs.ManagerValue11, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 12 then ISNULL(fs.ManagerValue12, 0.0) else 0.0 end + ) + END AS YTD, + CASE + WHEN fs.UnitTypeID = 144 THEN ( + (ISNULL(fs.ManagerValue01, 0.0) * fwh.Month01) + + (ISNULL(fs.ManagerValue02, 0.0) * fwh.Month02) + + (ISNULL(fs.ManagerValue03, 0.0) * fwh.Month03) + + (ISNULL(fs.ManagerValue04, 0.0) * fwh.Month04) + + (ISNULL(fs.ManagerValue05, 0.0) * fwh.Month05) + + (ISNULL(fs.ManagerValue06, 0.0) * fwh.Month06) + + (ISNULL(fs.ManagerValue07, 0.0) * fwh.Month07) + + (ISNULL(fs.ManagerValue08, 0.0) * fwh.Month08) + + (ISNULL(fs.ManagerValue09, 0.0) * fwh.Month09) + + (ISNULL(fs.ManagerValue10, 0.0) * fwh.Month10) + + (ISNULL(fs.ManagerValue11, 0.0) * fwh.Month11) + + (ISNULL(fs.ManagerValue12, 0.0) * fwh.Month12) + ) / fwh.MonthYearly + ELSE ( + ISNULL(fs.ManagerValue01, 0.0) + + ISNULL(fs.ManagerValue02, 0.0) + + ISNULL(fs.ManagerValue03, 0.0) + + ISNULL(fs.ManagerValue04, 0.0) + + ISNULL(fs.ManagerValue05, 0.0) + + ISNULL(fs.ManagerValue06, 0.0) + + ISNULL(fs.ManagerValue07, 0.0) + + ISNULL(fs.ManagerValue08, 0.0) + + ISNULL(fs.ManagerValue09, 0.0) + + ISNULL(fs.ManagerValue10, 0.0) + + ISNULL(fs.ManagerValue11, 0.0) + + ISNULL(fs.ManagerValue12, 0.0) + ) + END AS Total +FROM + PivoUnpivo fs + INNER JOIN [fw].[DimDepartment] d with (readuncommitted) on d.DepartmentID = fs.DepartmentID + INNER JOIN [fw].[DimEntity] e with (readuncommitted) on e.EntityID = d.EntityID + INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID = fs.JobCodeID + INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [client].[FactWorkingHoursPerMonth] fwh with (readuncommitted) ON fwh.FiscalYearID = bc.FiscalYearID - 1 and fwh.WorkWeekID = case when jc.WorkWeekOverrideID > 0 then jc.WorkWeekOverrideID when d.WorkWeekID > 0 then d.WorkWeekID else e.WorkWeekID end + INNER JOIN [fw].[DimEmployee] emp with (readuncommitted) on emp.EmployeeID = fs.EmployeeID +WHERE + fs.TimeClassID = 12 + +UNION ALL + +-- PriorYearActual and CurrentYearBudget +SELECT + fs.DepartmentID, + fs.BudgetConfigID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.FiscalYearID, + fs.VariabilityID, + fs.TimeClassID, + fs.UnitTypeID, + fs.EmployeeID, + ISNULL(fs.Value01, 0.0) AS Month01, + ISNULL(fs.Value02, 0.0) AS Month02, + ISNULL(fs.Value03, 0.0) AS Month03, + ISNULL(fs.Value04, 0.0) AS Month04, + ISNULL(fs.Value05, 0.0) AS Month05, + ISNULL(fs.Value06, 0.0) AS Month06, + ISNULL(fs.Value07, 0.0) AS Month07, + ISNULL(fs.Value08, 0.0) AS Month08, + ISNULL(fs.Value09, 0.0) AS Month09, + ISNULL(fs.Value10, 0.0) AS Month10, + ISNULL(fs.Value11, 0.0) AS Month11, + ISNULL(fs.Value12, 0.0) AS Month12, + CASE + WHEN fs.UnitTypeID = 144 THEN ( + case when bc.MonthsLoaded >= 1 then (ISNULL(fs.Value01, 0.0) * fwh.Month01) else 0.0 end + + case when bc.MonthsLoaded >= 2 then (ISNULL(fs.Value02, 0.0) * fwh.Month02) else 0.0 end + + case when bc.MonthsLoaded >= 3 then (ISNULL(fs.Value03, 0.0) * fwh.Month03) else 0.0 end + + case when bc.MonthsLoaded >= 4 then (ISNULL(fs.Value04, 0.0) * fwh.Month04) else 0.0 end + + case when bc.MonthsLoaded >= 5 then (ISNULL(fs.Value05, 0.0) * fwh.Month05) else 0.0 end + + case when bc.MonthsLoaded >= 6 then (ISNULL(fs.Value06, 0.0) * fwh.Month06) else 0.0 end + + case when bc.MonthsLoaded >= 7 then (ISNULL(fs.Value07, 0.0) * fwh.Month07) else 0.0 end + + case when bc.MonthsLoaded >= 8 then (ISNULL(fs.Value08, 0.0) * fwh.Month08) else 0.0 end + + case when bc.MonthsLoaded >= 9 then (ISNULL(fs.Value09, 0.0) * fwh.Month09) else 0.0 end + + case when bc.MonthsLoaded >= 10 then (ISNULL(fs.Value10, 0.0) * fwh.Month10) else 0.0 end + + case when bc.MonthsLoaded >= 11 then (ISNULL(fs.Value11, 0.0) * fwh.Month11) else 0.0 end + + case when bc.MonthsLoaded >= 12 then (ISNULL(fs.Value12, 0.0) * fwh.Month12) else 0.0 end + ) / ( + case when bc.MonthsLoaded >= 1 then fwh.Month01 else 0.0 end + + case when bc.MonthsLoaded >= 2 then fwh.Month02 else 0.0 end + + case when bc.MonthsLoaded >= 3 then fwh.Month03 else 0.0 end + + case when bc.MonthsLoaded >= 4 then fwh.Month04 else 0.0 end + + case when bc.MonthsLoaded >= 5 then fwh.Month05 else 0.0 end + + case when bc.MonthsLoaded >= 6 then fwh.Month06 else 0.0 end + + case when bc.MonthsLoaded >= 7 then fwh.Month07 else 0.0 end + + case when bc.MonthsLoaded >= 8 then fwh.Month08 else 0.0 end + + case when bc.MonthsLoaded >= 9 then fwh.Month09 else 0.0 end + + case when bc.MonthsLoaded >= 10 then fwh.Month10 else 0.0 end + + case when bc.MonthsLoaded >= 11 then fwh.Month11 else 0.0 end + + case when bc.MonthsLoaded >= 12 then fwh.Month12 else 0.0 end + ) + ELSE ( + case when bc.MonthsLoaded >= 1 then ISNULL(fs.Value01, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 2 then ISNULL(fs.Value02, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 3 then ISNULL(fs.Value03, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 4 then ISNULL(fs.Value04, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 5 then ISNULL(fs.Value05, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 6 then ISNULL(fs.Value06, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 7 then ISNULL(fs.Value07, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 8 then ISNULL(fs.Value08, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 9 then ISNULL(fs.Value09, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 10 then ISNULL(fs.Value10, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 11 then ISNULL(fs.Value11, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 12 then ISNULL(fs.Value12, 0.0) else 0.0 end + ) + END AS YTD, + CASE + WHEN fs.UnitTypeID = 144 THEN ( + (ISNULL(fs.Value01, 0.0) * fwh.Month01) + + (ISNULL(fs.Value02, 0.0) * fwh.Month02) + + (ISNULL(fs.Value03, 0.0) * fwh.Month03) + + (ISNULL(fs.Value04, 0.0) * fwh.Month04) + + (ISNULL(fs.Value05, 0.0) * fwh.Month05) + + (ISNULL(fs.Value06, 0.0) * fwh.Month06) + + (ISNULL(fs.Value07, 0.0) * fwh.Month07) + + (ISNULL(fs.Value08, 0.0) * fwh.Month08) + + (ISNULL(fs.Value09, 0.0) * fwh.Month09) + + (ISNULL(fs.Value10, 0.0) * fwh.Month10) + + (ISNULL(fs.Value11, 0.0) * fwh.Month11) + + (ISNULL(fs.Value12, 0.0) * fwh.Month12) + ) / fwh.MonthYearly + ELSE ( + ISNULL(fs.Value01, 0.0) + + ISNULL(fs.Value02, 0.0) + + ISNULL(fs.Value03, 0.0) + + ISNULL(fs.Value04, 0.0) + + ISNULL(fs.Value05, 0.0) + + ISNULL(fs.Value06, 0.0) + + ISNULL(fs.Value07, 0.0) + + ISNULL(fs.Value08, 0.0) + + ISNULL(fs.Value09, 0.0) + + ISNULL(fs.Value10, 0.0) + + ISNULL(fs.Value11, 0.0) + + ISNULL(fs.Value12, 0.0) + ) + END AS Total +FROM + PivoUnpivoHistory fs + INNER JOIN [fw].[DimDepartment] d with (readuncommitted) on d.DepartmentID = fs.DepartmentID + INNER JOIN [fw].[DimEntity] e with (readuncommitted) on e.EntityID = d.EntityID + INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID = fs.JobCodeID + INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [client].[FactWorkingHoursPerMonth] fwh with (readuncommitted) ON fwh.FiscalYearID = fs.FiscalYearID and fwh.WorkWeekID = case when jc.WorkWeekOverrideID > 0 then jc.WorkWeekOverrideID when d.WorkWeekID > 0 then d.WorkWeekID else e.WorkWeekID end + INNER JOIN [fw].[DimEmployee] emp with (readuncommitted) on emp.EmployeeID = fs.EmployeeID +WHERE + fs.TimeClassID IN (1, 2) +GO + + +--------------------------------------------- + +-- fp.viewReportStaffingForEmployeeAndProvider +CREATE VIEW [fp].[viewReportStaffingForEmployeeAndProvider] +AS +WITH PivoUnpivo AS ( + SELECT BudgetConfigID + ,EntityID + ,DepartmentID + ,JobCodeID + ,PayCodeGroupID + ,VariabilityID + ,ProductiveClassID + ,UnitTypeID + ,TimeClassID + ,FiscalYearID + ,EmployeeID + ,ProviderID + ,ProviderLineItemID + ,ProviderTypeID + ,ProviderSpecialtyID + ,SUM([01]) as OriginalValue01 + ,SUM([02]) as OriginalValue02 + ,SUM([03]) as OriginalValue03 + ,SUM([04]) as OriginalValue04 + ,SUM([05]) as OriginalValue05 + ,SUM([06]) as OriginalValue06 + ,SUM([07]) as OriginalValue07 + ,SUM([08]) as OriginalValue08 + ,SUM([09]) as OriginalValue09 + ,SUM([10]) as OriginalValue10 + ,SUM([11]) as OriginalValue11 + ,SUM([12]) as OriginalValue12 + ,SUM([01_2]) as Value01 + ,SUM([02_2]) as Value02 + ,SUM([03_2]) as Value03 + ,SUM([04_2]) as Value04 + ,SUM([05_2]) as Value05 + ,SUM([06_2]) as Value06 + ,SUM([07_2]) as Value07 + ,SUM([08_2]) as Value08 + ,SUM([09_2]) as Value09 + ,SUM([10_2]) as Value10 + ,SUM([11_2]) as Value11 + ,SUM([12_2]) as Value12 + ,SUM([01_3]) as ManagerValue01 + ,SUM([02_3]) as ManagerValue02 + ,SUM([03_3]) as ManagerValue03 + ,SUM([04_3]) as ManagerValue04 + ,SUM([05_3]) as ManagerValue05 + ,SUM([06_3]) as ManagerValue06 + ,SUM([07_3]) as ManagerValue07 + ,SUM([08_3]) as ManagerValue08 + ,SUM([09_3]) as ManagerValue09 + ,SUM([10_3]) as ManagerValue10 + ,SUM([11_3]) as ManagerValue11 + ,SUM([12_3]) as ManagerValue12 + FROM ( + SELECT BudgetConfigID,EntityID,DepartmentID,JobCodeID,PayCodeGroupID,VariabilityID,ProductiveClassID,UnitTypeID,TimeClassID,RIGHT(fm.MonthColumnName,2) as FiscalMonthID,FiscalYearID,EmployeeID, + ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, OriginalValue,Value,ManagerValue,RIGHT(fm.MonthColumnName,2)+'_2' as FiscalMonthID_2,RIGHT(fm.MonthColumnName,2)+'_3' as FiscalMonthID_3 + FROM [fp].[FactReportStaffing] f with (readuncommitted) + INNER JOIN [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = f.FiscalMonthID + UNION ALL + SELECT BudgetConfigID,EntityID,DepartmentID,JobCodeID,PayCodeGroupID,VariabilityID,ProductiveClassID,UnitTypeID,TimeClassID,RIGHT(fm.MonthColumnName,2) as FiscalMonthID,FiscalYearID,EmployeeID, + ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, OriginalValue,Value,ManagerValue,RIGHT(fm.MonthColumnName,2)+'_2' as FiscalMonthID_2,RIGHT(fm.MonthColumnName,2)+'_3' as FiscalMonthID_3 + FROM [fp].[FactReportStaffing_archive] f with (readuncommitted) + INNER JOIN [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = f.FiscalMonthID + ) X + PIVOT (SUM(OriginalValue) FOR FiscalMonthID IN ([01],[02],[03],[04],[05],[06],[07],[08],[09],[10],[11],[12])) AS Pivot1 + PIVOT (SUM(Value) FOR FiscalMonthID_2 IN ([01_2],[02_2],[03_2],[04_2],[05_2],[06_2],[07_2],[08_2],[09_2],[10_2],[11_2],[12_2])) AS Pivot2 + PIVOT (SUM(ManagerValue) FOR FiscalMonthID_3 IN ([01_3],[02_3],[03_3],[04_3],[05_3],[06_3],[07_3],[08_3],[09_3],[10_3],[11_3],[12_3])) AS Pivot1 + GROUP BY + BudgetConfigID + ,EntityID + ,DepartmentID + ,JobCodeID + ,PayCodeGroupID + ,VariabilityID + ,ProductiveClassID + ,UnitTypeID + ,TimeClassID + ,FiscalYearID + ,EmployeeID + ,ProviderID + ,ProviderLineItemID + ,ProviderTypeID + ,ProviderSpecialtyID +), +PivoUnpivoHistory AS ( + SELECT BudgetConfigID + ,EntityID + ,DepartmentID + ,JobCodeID + ,PayCodeGroupID + ,VariabilityID + ,ProductiveClassID + ,UnitTypeID + ,TimeClassID + ,FiscalYearID + ,EmployeeID + ,ProviderID + ,ProviderLineItemID + ,ProviderTypeID + ,ProviderSpecialtyID + ,SUM([01]) as Value01 + ,SUM([02]) as Value02 + ,SUM([03]) as Value03 + ,SUM([04]) as Value04 + ,SUM([05]) as Value05 + ,SUM([06]) as Value06 + ,SUM([07]) as Value07 + ,SUM([08]) as Value08 + ,SUM([09]) as Value09 + ,SUM([10]) as Value10 + ,SUM([11]) as Value11 + ,SUM([12]) as Value12 + FROM ( + SELECT BudgetConfigID,EntityID,DepartmentID,JobCodeID,PayCodeGroupID,VariabilityID,ProductiveClassID,UnitTypeID,TimeClassID,RIGHT(fm.MonthColumnName,2) as FiscalMonthID,FiscalYearID,EmployeeID, + ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, Value + FROM [fp].[FactReportStaffingHistory] f with (readuncommitted) + INNER JOIN [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = f.FiscalMonthID + UNION ALL + SELECT BudgetConfigID,EntityID,DepartmentID,JobCodeID,PayCodeGroupID,VariabilityID,ProductiveClassID,UnitTypeID,TimeClassID,RIGHT(fm.MonthColumnName,2) as FiscalMonthID,FiscalYearID,EmployeeID, + ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, Value + FROM [fp].[FactReportStaffingHistory_archive] f with (readuncommitted) + INNER JOIN [fw].[DimFiscalMonth] fm with (readuncommitted) on fm.FiscalMonthID = f.FiscalMonthID + ) X + PIVOT (SUM(Value) FOR FiscalMonthID IN ([01],[02],[03],[04],[05],[06],[07],[08],[09],[10],[11],[12])) AS Pivot2 + GROUP BY BudgetConfigID + ,EntityID + ,DepartmentID + ,JobCodeID + ,PayCodeGroupID + ,VariabilityID + ,ProductiveClassID + ,UnitTypeID + ,TimeClassID + ,FiscalYearID + ,EmployeeID + ,ProviderID + ,ProviderLineItemID + ,ProviderTypeID + ,ProviderSpecialtyID +) + +-- Manager Budget +SELECT + fs.DepartmentID, + fs.BudgetConfigID, + fs.JobCodeID, + fs.PayCodeGroupID, + bc.FiscalYearID, + fs.VariabilityID, + fs.TimeClassID, + fs.UnitTypeID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderLineItemID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + ISNULL(fs.ManagerValue01, 0.0) as Month01, + ISNULL(fs.ManagerValue02, 0.0) as Month02, + ISNULL(fs.ManagerValue03, 0.0) as Month03, + ISNULL(fs.ManagerValue04, 0.0) as Month04, + ISNULL(fs.ManagerValue05, 0.0) as Month05, + ISNULL(fs.ManagerValue06, 0.0) as Month06, + ISNULL(fs.ManagerValue07, 0.0) as Month07, + ISNULL(fs.ManagerValue08, 0.0) as Month08, + ISNULL(fs.ManagerValue09, 0.0) as Month09, + ISNULL(fs.ManagerValue10, 0.0) as Month10, + ISNULL(fs.ManagerValue11, 0.0) as Month11, + ISNULL(fs.ManagerValue12, 0.0) as Month12, + CASE + WHEN fs.UnitTypeID = 144 THEN ( + case when bc.MonthsLoaded >= 1 then (ISNULL(fs.ManagerValue01, 0.0) * fwh.Month01) else 0.0 end + + case when bc.MonthsLoaded >= 2 then (ISNULL(fs.ManagerValue02, 0.0) * fwh.Month02) else 0.0 end + + case when bc.MonthsLoaded >= 3 then (ISNULL(fs.ManagerValue03, 0.0) * fwh.Month03) else 0.0 end + + case when bc.MonthsLoaded >= 4 then (ISNULL(fs.ManagerValue04, 0.0) * fwh.Month04) else 0.0 end + + case when bc.MonthsLoaded >= 5 then (ISNULL(fs.ManagerValue05, 0.0) * fwh.Month05) else 0.0 end + + case when bc.MonthsLoaded >= 6 then (ISNULL(fs.ManagerValue06, 0.0) * fwh.Month06) else 0.0 end + + case when bc.MonthsLoaded >= 7 then (ISNULL(fs.ManagerValue07, 0.0) * fwh.Month07) else 0.0 end + + case when bc.MonthsLoaded >= 8 then (ISNULL(fs.ManagerValue08, 0.0) * fwh.Month08) else 0.0 end + + case when bc.MonthsLoaded >= 9 then (ISNULL(fs.ManagerValue09, 0.0) * fwh.Month09) else 0.0 end + + case when bc.MonthsLoaded >= 10 then (ISNULL(fs.ManagerValue10, 0.0) * fwh.Month10) else 0.0 end + + case when bc.MonthsLoaded >= 11 then (ISNULL(fs.ManagerValue11, 0.0) * fwh.Month11) else 0.0 end + + case when bc.MonthsLoaded >= 12 then (ISNULL(fs.ManagerValue12, 0.0) * fwh.Month12) else 0.0 end + ) / ( + case when bc.MonthsLoaded >= 1 then fwh.Month01 else 0.0 end + + case when bc.MonthsLoaded >= 2 then fwh.Month02 else 0.0 end + + case when bc.MonthsLoaded >= 3 then fwh.Month03 else 0.0 end + + case when bc.MonthsLoaded >= 4 then fwh.Month04 else 0.0 end + + case when bc.MonthsLoaded >= 5 then fwh.Month05 else 0.0 end + + case when bc.MonthsLoaded >= 6 then fwh.Month06 else 0.0 end + + case when bc.MonthsLoaded >= 7 then fwh.Month07 else 0.0 end + + case when bc.MonthsLoaded >= 8 then fwh.Month08 else 0.0 end + + case when bc.MonthsLoaded >= 9 then fwh.Month09 else 0.0 end + + case when bc.MonthsLoaded >= 10 then fwh.Month10 else 0.0 end + + case when bc.MonthsLoaded >= 11 then fwh.Month11 else 0.0 end + + case when bc.MonthsLoaded >= 12 then fwh.Month12 else 0.0 end + ) + ELSE ( + case when bc.MonthsLoaded >= 1 then ISNULL(fs.ManagerValue01, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 2 then ISNULL(fs.ManagerValue02, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 3 then ISNULL(fs.ManagerValue03, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 4 then ISNULL(fs.ManagerValue04, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 5 then ISNULL(fs.ManagerValue05, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 6 then ISNULL(fs.ManagerValue06, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 7 then ISNULL(fs.ManagerValue07, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 8 then ISNULL(fs.ManagerValue08, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 9 then ISNULL(fs.ManagerValue09, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 10 then ISNULL(fs.ManagerValue10, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 11 then ISNULL(fs.ManagerValue11, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 12 then ISNULL(fs.ManagerValue12, 0.0) else 0.0 end + ) + END AS YTD, + CASE + WHEN fs.UnitTypeID = 144 THEN ( + (ISNULL(fs.ManagerValue01, 0.0) * fwh.Month01) + + (ISNULL(fs.ManagerValue02, 0.0) * fwh.Month02) + + (ISNULL(fs.ManagerValue03, 0.0) * fwh.Month03) + + (ISNULL(fs.ManagerValue04, 0.0) * fwh.Month04) + + (ISNULL(fs.ManagerValue05, 0.0) * fwh.Month05) + + (ISNULL(fs.ManagerValue06, 0.0) * fwh.Month06) + + (ISNULL(fs.ManagerValue07, 0.0) * fwh.Month07) + + (ISNULL(fs.ManagerValue08, 0.0) * fwh.Month08) + + (ISNULL(fs.ManagerValue09, 0.0) * fwh.Month09) + + (ISNULL(fs.ManagerValue10, 0.0) * fwh.Month10) + + (ISNULL(fs.ManagerValue11, 0.0) * fwh.Month11) + + (ISNULL(fs.ManagerValue12, 0.0) * fwh.Month12) + ) / fwh.MonthYearly + ELSE ( + ISNULL(fs.ManagerValue01, 0.0) + + ISNULL(fs.ManagerValue02, 0.0) + + ISNULL(fs.ManagerValue03, 0.0) + + ISNULL(fs.ManagerValue04, 0.0) + + ISNULL(fs.ManagerValue05, 0.0) + + ISNULL(fs.ManagerValue06, 0.0) + + ISNULL(fs.ManagerValue07, 0.0) + + ISNULL(fs.ManagerValue08, 0.0) + + ISNULL(fs.ManagerValue09, 0.0) + + ISNULL(fs.ManagerValue10, 0.0) + + ISNULL(fs.ManagerValue11, 0.0) + + ISNULL(fs.ManagerValue12, 0.0) + ) + END AS Total +FROM + PivoUnpivo fs + INNER JOIN [fw].[DimDepartment] d with (readuncommitted) on d.DepartmentID = fs.DepartmentID + INNER JOIN [fw].[DimEntity] e with (readuncommitted) on e.EntityID = d.EntityID + INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID = fs.JobCodeID + INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [client].[FactWorkingHoursPerMonth] fwh with (readuncommitted) ON fwh.FiscalYearID = bc.FiscalYearID and fwh.WorkWeekID = case when jc.WorkWeekOverrideID > 0 then jc.WorkWeekOverrideID when d.WorkWeekID > 0 then d.WorkWeekID else e.WorkWeekID end + INNER JOIN [fw].[DimEmployee] emp with (readuncommitted) on emp.EmployeeID = fs.EmployeeID + INNER JOIN [fp].[viewDimPhysician] pr with (readuncommitted) on pr.ProviderID = fs.ProviderID + INNER JOIN [fp].[viewProviderLineItem] prli with (readuncommitted) on prli.ProviderLineItemID = fs.ProviderLineItemID + INNER JOIN [clientdss].[DimProviderType] pt with (readuncommitted) on pt.ProviderTypeID = fs.ProviderTypeID + INNER JOIN [dss].[DimPhysicianSpecialty] ps with (readuncommitted) on ps.PhysicianSpecialtyID = fs.ProviderSpecialtyID +WHERE + fs.TimeClassID=2 + +UNION ALL + +-- Initial Budget +SELECT + fs.DepartmentID, + fs.BudgetConfigID, + fs.JobCodeID, + fs.PayCodeGroupID, + bc.FiscalYearID, + fs.VariabilityID, + 21 AS TimeClassID, + fs.UnitTypeID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderLineItemID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + ISNULL(fs.OriginalValue01, 0.0) as Month01, + ISNULL(fs.OriginalValue02, 0.0) as Month02, + ISNULL(fs.OriginalValue03, 0.0) as Month03, + ISNULL(fs.OriginalValue04, 0.0) as Month04, + ISNULL(fs.OriginalValue05, 0.0) as Month05, + ISNULL(fs.OriginalValue06, 0.0) as Month06, + ISNULL(fs.OriginalValue07, 0.0) as Month07, + ISNULL(fs.OriginalValue08, 0.0) as Month08, + ISNULL(fs.OriginalValue09, 0.0) as Month09, + ISNULL(fs.OriginalValue10, 0.0) as Month10, + ISNULL(fs.OriginalValue11, 0.0) as Month11, + ISNULL(fs.OriginalValue12, 0.0) as Month12, + CASE + WHEN fs.UnitTypeID = 144 THEN ( + case when bc.MonthsLoaded >= 1 then (ISNULL(fs.OriginalValue01, 0.0) * fwh.Month01) else 0.0 end + + case when bc.MonthsLoaded >= 2 then (ISNULL(fs.OriginalValue02, 0.0) * fwh.Month02) else 0.0 end + + case when bc.MonthsLoaded >= 3 then (ISNULL(fs.OriginalValue03, 0.0) * fwh.Month03) else 0.0 end + + case when bc.MonthsLoaded >= 4 then (ISNULL(fs.OriginalValue04, 0.0) * fwh.Month04) else 0.0 end + + case when bc.MonthsLoaded >= 5 then (ISNULL(fs.OriginalValue05, 0.0) * fwh.Month05) else 0.0 end + + case when bc.MonthsLoaded >= 6 then (ISNULL(fs.OriginalValue06, 0.0) * fwh.Month06) else 0.0 end + + case when bc.MonthsLoaded >= 7 then (ISNULL(fs.OriginalValue07, 0.0) * fwh.Month07) else 0.0 end + + case when bc.MonthsLoaded >= 8 then (ISNULL(fs.OriginalValue08, 0.0) * fwh.Month08) else 0.0 end + + case when bc.MonthsLoaded >= 9 then (ISNULL(fs.OriginalValue09, 0.0) * fwh.Month09) else 0.0 end + + case when bc.MonthsLoaded >= 10 then (ISNULL(fs.OriginalValue10, 0.0) * fwh.Month10) else 0.0 end + + case when bc.MonthsLoaded >= 11 then (ISNULL(fs.OriginalValue11, 0.0) * fwh.Month11) else 0.0 end + + case when bc.MonthsLoaded >= 12 then (ISNULL(fs.OriginalValue12, 0.0) * fwh.Month12) else 0.0 end + ) / ( + case when bc.MonthsLoaded >= 1 then fwh.Month01 else 0.0 end + + case when bc.MonthsLoaded >= 2 then fwh.Month02 else 0.0 end + + case when bc.MonthsLoaded >= 3 then fwh.Month03 else 0.0 end + + case when bc.MonthsLoaded >= 4 then fwh.Month04 else 0.0 end + + case when bc.MonthsLoaded >= 5 then fwh.Month05 else 0.0 end + + case when bc.MonthsLoaded >= 6 then fwh.Month06 else 0.0 end + + case when bc.MonthsLoaded >= 7 then fwh.Month07 else 0.0 end + + case when bc.MonthsLoaded >= 8 then fwh.Month08 else 0.0 end + + case when bc.MonthsLoaded >= 9 then fwh.Month09 else 0.0 end + + case when bc.MonthsLoaded >= 10 then fwh.Month10 else 0.0 end + + case when bc.MonthsLoaded >= 11 then fwh.Month11 else 0.0 end + + case when bc.MonthsLoaded >= 12 then fwh.Month12 else 0.0 end + ) + ELSE ( + case when bc.MonthsLoaded >= 1 then ISNULL(fs.OriginalValue01, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 2 then ISNULL(fs.OriginalValue02, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 3 then ISNULL(fs.OriginalValue03, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 4 then ISNULL(fs.OriginalValue04, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 5 then ISNULL(fs.OriginalValue05, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 6 then ISNULL(fs.OriginalValue06, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 7 then ISNULL(fs.OriginalValue07, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 8 then ISNULL(fs.OriginalValue08, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 9 then ISNULL(fs.OriginalValue09, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 10 then ISNULL(fs.OriginalValue10, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 11 then ISNULL(fs.OriginalValue11, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 12 then ISNULL(fs.OriginalValue12, 0.0) else 0.0 end + ) + END AS YTD, + CASE + WHEN fs.UnitTypeID = 144 THEN ( + (ISNULL(fs.OriginalValue01, 0.0) * fwh.Month01) + + (ISNULL(fs.OriginalValue02, 0.0) * fwh.Month02) + + (ISNULL(fs.OriginalValue03, 0.0) * fwh.Month03) + + (ISNULL(fs.OriginalValue04, 0.0) * fwh.Month04) + + (ISNULL(fs.OriginalValue05, 0.0) * fwh.Month05) + + (ISNULL(fs.OriginalValue06, 0.0) * fwh.Month06) + + (ISNULL(fs.OriginalValue07, 0.0) * fwh.Month07) + + (ISNULL(fs.OriginalValue08, 0.0) * fwh.Month08) + + (ISNULL(fs.OriginalValue09, 0.0) * fwh.Month09) + + (ISNULL(fs.OriginalValue10, 0.0) * fwh.Month10) + + (ISNULL(fs.OriginalValue11, 0.0) * fwh.Month11) + + (ISNULL(fs.OriginalValue12, 0.0) * fwh.Month12) + ) / fwh.MonthYearly + ELSE ( + ISNULL(fs.OriginalValue01, 0.0) + + ISNULL(fs.OriginalValue02, 0.0) + + ISNULL(fs.OriginalValue03, 0.0) + + ISNULL(fs.OriginalValue04, 0.0) + + ISNULL(fs.OriginalValue05, 0.0) + + ISNULL(fs.OriginalValue06, 0.0) + + ISNULL(fs.OriginalValue07, 0.0) + + ISNULL(fs.OriginalValue08, 0.0) + + ISNULL(fs.OriginalValue09, 0.0) + + ISNULL(fs.OriginalValue10, 0.0) + + ISNULL(fs.OriginalValue11, 0.0) + + ISNULL(fs.OriginalValue12, 0.0) + ) + END AS Total +FROM + PivoUnpivo fs + INNER JOIN [fw].[DimDepartment] d with (readuncommitted) on d.DepartmentID = fs.DepartmentID + INNER JOIN [fw].[DimEntity] e with (readuncommitted) on e.EntityID = d.EntityID + INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID = fs.JobCodeID + INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [client].[FactWorkingHoursPerMonth] fwh with (readuncommitted) ON fwh.FiscalYearID = bc.FiscalYearID and fwh.WorkWeekID = case when jc.WorkWeekOverrideID > 0 then jc.WorkWeekOverrideID when d.WorkWeekID > 0 then d.WorkWeekID else e.WorkWeekID end + INNER JOIN [fw].[DimEmployee] emp with (readuncommitted) on emp.EmployeeID = fs.EmployeeID + INNER JOIN [fp].[viewDimPhysician] pr with (readuncommitted) on pr.ProviderID = fs.ProviderID + INNER JOIN [fp].[viewProviderLineItem] prli with (readuncommitted) on prli.ProviderLineItemID = fs.ProviderLineItemID + INNER JOIN [clientdss].[DimProviderType] pt with (readuncommitted) on pt.ProviderTypeID = fs.ProviderTypeID + INNER JOIN [dss].[DimPhysicianSpecialty] ps with (readuncommitted) on ps.PhysicianSpecialtyID = fs.ProviderSpecialtyID +WHERE + fs.TimeClassID=2 + +UNION ALL + +-- Baseline Budget +SELECT + fs.DepartmentID, + fs.BudgetConfigID, + fs.JobCodeID, + fs.PayCodeGroupID, + bc.FiscalYearID, + fs.VariabilityID, + 18 AS TimeClassID, + fs.UnitTypeID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderLineItemID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + ISNULL(fs.Value01, 0.0) as Month01, + ISNULL(fs.Value02, 0.0) as Month02, + ISNULL(fs.Value03, 0.0) as Month03, + ISNULL(fs.Value04, 0.0) as Month04, + ISNULL(fs.Value05, 0.0) as Month05, + ISNULL(fs.Value06, 0.0) as Month06, + ISNULL(fs.Value07, 0.0) as Month07, + ISNULL(fs.Value08, 0.0) as Month08, + ISNULL(fs.Value09, 0.0) as Month09, + ISNULL(fs.Value10, 0.0) as Month10, + ISNULL(fs.Value11, 0.0) as Month11, + ISNULL(fs.Value12, 0.0) as Month12, + CASE + WHEN fs.UnitTypeID = 144 THEN ( + case when bc.MonthsLoaded >= 1 then (ISNULL(fs.Value01, 0.0) * fwh.Month01) else 0.0 end + + case when bc.MonthsLoaded >= 2 then (ISNULL(fs.Value02, 0.0) * fwh.Month02) else 0.0 end + + case when bc.MonthsLoaded >= 3 then (ISNULL(fs.Value03, 0.0) * fwh.Month03) else 0.0 end + + case when bc.MonthsLoaded >= 4 then (ISNULL(fs.Value04, 0.0) * fwh.Month04) else 0.0 end + + case when bc.MonthsLoaded >= 5 then (ISNULL(fs.Value05, 0.0) * fwh.Month05) else 0.0 end + + case when bc.MonthsLoaded >= 6 then (ISNULL(fs.Value06, 0.0) * fwh.Month06) else 0.0 end + + case when bc.MonthsLoaded >= 7 then (ISNULL(fs.Value07, 0.0) * fwh.Month07) else 0.0 end + + case when bc.MonthsLoaded >= 8 then (ISNULL(fs.Value08, 0.0) * fwh.Month08) else 0.0 end + + case when bc.MonthsLoaded >= 9 then (ISNULL(fs.Value09, 0.0) * fwh.Month09) else 0.0 end + + case when bc.MonthsLoaded >= 10 then (ISNULL(fs.Value10, 0.0) * fwh.Month10) else 0.0 end + + case when bc.MonthsLoaded >= 11 then (ISNULL(fs.Value11, 0.0) * fwh.Month11) else 0.0 end + + case when bc.MonthsLoaded >= 12 then (ISNULL(fs.Value12, 0.0) * fwh.Month12) else 0.0 end + ) / ( + case when bc.MonthsLoaded >= 1 then fwh.Month01 else 0.0 end + + case when bc.MonthsLoaded >= 2 then fwh.Month02 else 0.0 end + + case when bc.MonthsLoaded >= 3 then fwh.Month03 else 0.0 end + + case when bc.MonthsLoaded >= 4 then fwh.Month04 else 0.0 end + + case when bc.MonthsLoaded >= 5 then fwh.Month05 else 0.0 end + + case when bc.MonthsLoaded >= 6 then fwh.Month06 else 0.0 end + + case when bc.MonthsLoaded >= 7 then fwh.Month07 else 0.0 end + + case when bc.MonthsLoaded >= 8 then fwh.Month08 else 0.0 end + + case when bc.MonthsLoaded >= 9 then fwh.Month09 else 0.0 end + + case when bc.MonthsLoaded >= 10 then fwh.Month10 else 0.0 end + + case when bc.MonthsLoaded >= 11 then fwh.Month11 else 0.0 end + + case when bc.MonthsLoaded >= 12 then fwh.Month12 else 0.0 end + ) + ELSE ( + case when bc.MonthsLoaded >= 1 then ISNULL(fs.Value01, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 2 then ISNULL(fs.Value02, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 3 then ISNULL(fs.Value03, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 4 then ISNULL(fs.Value04, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 5 then ISNULL(fs.Value05, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 6 then ISNULL(fs.Value06, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 7 then ISNULL(fs.Value07, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 8 then ISNULL(fs.Value08, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 9 then ISNULL(fs.Value09, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 10 then ISNULL(fs.Value10, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 11 then ISNULL(fs.Value11, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 12 then ISNULL(fs.Value12, 0.0) else 0.0 end + ) + END AS YTD, + CASE + WHEN fs.UnitTypeID = 144 THEN ( + (ISNULL(fs.Value01, 0.0) * fwh.Month01) + + (ISNULL(fs.Value02, 0.0) * fwh.Month02) + + (ISNULL(fs.Value03, 0.0) * fwh.Month03) + + (ISNULL(fs.Value04, 0.0) * fwh.Month04) + + (ISNULL(fs.Value05, 0.0) * fwh.Month05) + + (ISNULL(fs.Value06, 0.0) * fwh.Month06) + + (ISNULL(fs.Value07, 0.0) * fwh.Month07) + + (ISNULL(fs.Value08, 0.0) * fwh.Month08) + + (ISNULL(fs.Value09, 0.0) * fwh.Month09) + + (ISNULL(fs.Value10, 0.0) * fwh.Month10) + + (ISNULL(fs.Value11, 0.0) * fwh.Month11) + + (ISNULL(fs.Value12, 0.0) * fwh.Month12) + ) / fwh.MonthYearly + ELSE ( + ISNULL(fs.Value01, 0.0) + + ISNULL(fs.Value02, 0.0) + + ISNULL(fs.Value03, 0.0) + + ISNULL(fs.Value04, 0.0) + + ISNULL(fs.Value05, 0.0) + + ISNULL(fs.Value06, 0.0) + + ISNULL(fs.Value07, 0.0) + + ISNULL(fs.Value08, 0.0) + + ISNULL(fs.Value09, 0.0) + + ISNULL(fs.Value10, 0.0) + + ISNULL(fs.Value11, 0.0) + + ISNULL(fs.Value12, 0.0) + ) + END AS Total +FROM + PivoUnpivo fs + INNER JOIN [fw].[DimDepartment] d with (readuncommitted) on d.DepartmentID = fs.DepartmentID + INNER JOIN [fw].[DimEntity] e with (readuncommitted) on e.EntityID = d.EntityID + INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID = fs.JobCodeID + INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [client].[FactWorkingHoursPerMonth] fwh with (readuncommitted) ON fwh.FiscalYearID = bc.FiscalYearID and fwh.WorkWeekID = case when jc.WorkWeekOverrideID > 0 then jc.WorkWeekOverrideID when d.WorkWeekID > 0 then d.WorkWeekID else e.WorkWeekID end + INNER JOIN [fw].[DimEmployee] emp with (readuncommitted) on emp.EmployeeID = fs.EmployeeID + INNER JOIN [fp].[viewDimPhysician] pr with (readuncommitted) on pr.ProviderID = fs.ProviderID + INNER JOIN [fp].[viewProviderLineItem] prli with (readuncommitted) on prli.ProviderLineItemID = fs.ProviderLineItemID + INNER JOIN [clientdss].[DimProviderType] pt with (readuncommitted) on pt.ProviderTypeID = fs.ProviderTypeID + INNER JOIN [dss].[DimPhysicianSpecialty] ps with (readuncommitted) on ps.PhysicianSpecialtyID = fs.ProviderSpecialtyID +WHERE + fs.TimeClassID=2 + +UNION ALL + +-- Manager Projection +SELECT + fs.DepartmentID, + fs.BudgetConfigID, + fs.JobCodeID, + fs.PayCodeGroupID, + bc.FiscalYearID - 1 as FiscalYearID, + fs.VariabilityID, + 12 AS TimeClassID, + fs.UnitTypeID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderLineItemID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + ISNULL(fs.ManagerValue01, 0.0) as Month01, + ISNULL(fs.ManagerValue02, 0.0) as Month02, + ISNULL(fs.ManagerValue03, 0.0) as Month03, + ISNULL(fs.ManagerValue04, 0.0) as Month04, + ISNULL(fs.ManagerValue05, 0.0) as Month05, + ISNULL(fs.ManagerValue06, 0.0) as Month06, + ISNULL(fs.ManagerValue07, 0.0) as Month07, + ISNULL(fs.ManagerValue08, 0.0) as Month08, + ISNULL(fs.ManagerValue09, 0.0) as Month09, + ISNULL(fs.ManagerValue10, 0.0) as Month10, + ISNULL(fs.ManagerValue11, 0.0) as Month11, + ISNULL(fs.ManagerValue12, 0.0) as Month12, + CASE + WHEN fs.UnitTypeID = 144 THEN ( + case when bc.MonthsLoaded >= 1 then (ISNULL(fs.ManagerValue01, 0.0) * fwh.Month01) else 0.0 end + + case when bc.MonthsLoaded >= 2 then (ISNULL(fs.ManagerValue02, 0.0) * fwh.Month02) else 0.0 end + + case when bc.MonthsLoaded >= 3 then (ISNULL(fs.ManagerValue03, 0.0) * fwh.Month03) else 0.0 end + + case when bc.MonthsLoaded >= 4 then (ISNULL(fs.ManagerValue04, 0.0) * fwh.Month04) else 0.0 end + + case when bc.MonthsLoaded >= 5 then (ISNULL(fs.ManagerValue05, 0.0) * fwh.Month05) else 0.0 end + + case when bc.MonthsLoaded >= 6 then (ISNULL(fs.ManagerValue06, 0.0) * fwh.Month06) else 0.0 end + + case when bc.MonthsLoaded >= 7 then (ISNULL(fs.ManagerValue07, 0.0) * fwh.Month07) else 0.0 end + + case when bc.MonthsLoaded >= 8 then (ISNULL(fs.ManagerValue08, 0.0) * fwh.Month08) else 0.0 end + + case when bc.MonthsLoaded >= 9 then (ISNULL(fs.ManagerValue09, 0.0) * fwh.Month09) else 0.0 end + + case when bc.MonthsLoaded >= 10 then (ISNULL(fs.ManagerValue10, 0.0) * fwh.Month10) else 0.0 end + + case when bc.MonthsLoaded >= 11 then (ISNULL(fs.ManagerValue11, 0.0) * fwh.Month11) else 0.0 end + + case when bc.MonthsLoaded >= 12 then (ISNULL(fs.ManagerValue12, 0.0) * fwh.Month12) else 0.0 end + ) / ( + case when bc.MonthsLoaded >= 1 then fwh.Month01 else 0.0 end + + case when bc.MonthsLoaded >= 2 then fwh.Month02 else 0.0 end + + case when bc.MonthsLoaded >= 3 then fwh.Month03 else 0.0 end + + case when bc.MonthsLoaded >= 4 then fwh.Month04 else 0.0 end + + case when bc.MonthsLoaded >= 5 then fwh.Month05 else 0.0 end + + case when bc.MonthsLoaded >= 6 then fwh.Month06 else 0.0 end + + case when bc.MonthsLoaded >= 7 then fwh.Month07 else 0.0 end + + case when bc.MonthsLoaded >= 8 then fwh.Month08 else 0.0 end + + case when bc.MonthsLoaded >= 9 then fwh.Month09 else 0.0 end + + case when bc.MonthsLoaded >= 10 then fwh.Month10 else 0.0 end + + case when bc.MonthsLoaded >= 11 then fwh.Month11 else 0.0 end + + case when bc.MonthsLoaded >= 12 then fwh.Month12 else 0.0 end + ) + ELSE ( + case when bc.MonthsLoaded >= 1 then ISNULL(fs.ManagerValue01, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 2 then ISNULL(fs.ManagerValue02, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 3 then ISNULL(fs.ManagerValue03, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 4 then ISNULL(fs.ManagerValue04, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 5 then ISNULL(fs.ManagerValue05, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 6 then ISNULL(fs.ManagerValue06, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 7 then ISNULL(fs.ManagerValue07, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 8 then ISNULL(fs.ManagerValue08, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 9 then ISNULL(fs.ManagerValue09, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 10 then ISNULL(fs.ManagerValue10, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 11 then ISNULL(fs.ManagerValue11, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 12 then ISNULL(fs.ManagerValue12, 0.0) else 0.0 end + ) + END AS YTD, + CASE + WHEN fs.UnitTypeID = 144 THEN ( + (ISNULL(fs.ManagerValue01, 0.0) * fwh.Month01) + + (ISNULL(fs.ManagerValue02, 0.0) * fwh.Month02) + + (ISNULL(fs.ManagerValue03, 0.0) * fwh.Month03) + + (ISNULL(fs.ManagerValue04, 0.0) * fwh.Month04) + + (ISNULL(fs.ManagerValue05, 0.0) * fwh.Month05) + + (ISNULL(fs.ManagerValue06, 0.0) * fwh.Month06) + + (ISNULL(fs.ManagerValue07, 0.0) * fwh.Month07) + + (ISNULL(fs.ManagerValue08, 0.0) * fwh.Month08) + + (ISNULL(fs.ManagerValue09, 0.0) * fwh.Month09) + + (ISNULL(fs.ManagerValue10, 0.0) * fwh.Month10) + + (ISNULL(fs.ManagerValue11, 0.0) * fwh.Month11) + + (ISNULL(fs.ManagerValue12, 0.0) * fwh.Month12) + ) / fwh.MonthYearly + ELSE ( + ISNULL(fs.ManagerValue01, 0.0) + + ISNULL(fs.ManagerValue02, 0.0) + + ISNULL(fs.ManagerValue03, 0.0) + + ISNULL(fs.ManagerValue04, 0.0) + + ISNULL(fs.ManagerValue05, 0.0) + + ISNULL(fs.ManagerValue06, 0.0) + + ISNULL(fs.ManagerValue07, 0.0) + + ISNULL(fs.ManagerValue08, 0.0) + + ISNULL(fs.ManagerValue09, 0.0) + + ISNULL(fs.ManagerValue10, 0.0) + + ISNULL(fs.ManagerValue11, 0.0) + + ISNULL(fs.ManagerValue12, 0.0) + ) + END AS Total +FROM + PivoUnpivo fs + INNER JOIN [fw].[DimDepartment] d with (readuncommitted) on d.DepartmentID = fs.DepartmentID + INNER JOIN [fw].[DimEntity] e with (readuncommitted) on e.EntityID = d.EntityID + INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID = fs.JobCodeID + INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [client].[FactWorkingHoursPerMonth] fwh with (readuncommitted) ON fwh.FiscalYearID = bc.FiscalYearID - 1 and fwh.WorkWeekID = case when jc.WorkWeekOverrideID > 0 then jc.WorkWeekOverrideID when d.WorkWeekID > 0 then d.WorkWeekID else e.WorkWeekID end + INNER JOIN [fw].[DimEmployee] emp with (readuncommitted) on emp.EmployeeID = fs.EmployeeID + INNER JOIN [fp].[viewDimPhysician] pr with (readuncommitted) on pr.ProviderID = fs.ProviderID + INNER JOIN [fp].[viewProviderLineItem] prli with (readuncommitted) on prli.ProviderLineItemID = fs.ProviderLineItemID + INNER JOIN [clientdss].[DimProviderType] pt with (readuncommitted) on pt.ProviderTypeID = fs.ProviderTypeID + INNER JOIN [dss].[DimPhysicianSpecialty] ps with (readuncommitted) on ps.PhysicianSpecialtyID = fs.ProviderSpecialtyID +WHERE + fs.TimeClassID = 12 + +UNION ALL + +-- PriorYearActual and CurrentYearBudget +SELECT + fs.DepartmentID, + fs.BudgetConfigID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.FiscalYearID, + fs.VariabilityID, + fs.TimeClassID, + fs.UnitTypeID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderLineItemID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + ISNULL(fs.Value01, 0.0) AS Month01, + ISNULL(fs.Value02, 0.0) AS Month02, + ISNULL(fs.Value03, 0.0) AS Month03, + ISNULL(fs.Value04, 0.0) AS Month04, + ISNULL(fs.Value05, 0.0) AS Month05, + ISNULL(fs.Value06, 0.0) AS Month06, + ISNULL(fs.Value07, 0.0) AS Month07, + ISNULL(fs.Value08, 0.0) AS Month08, + ISNULL(fs.Value09, 0.0) AS Month09, + ISNULL(fs.Value10, 0.0) AS Month10, + ISNULL(fs.Value11, 0.0) AS Month11, + ISNULL(fs.Value12, 0.0) AS Month12, + CASE + WHEN fs.UnitTypeID = 144 THEN ( + case when bc.MonthsLoaded >= 1 then (ISNULL(fs.Value01, 0.0) * fwh.Month01) else 0.0 end + + case when bc.MonthsLoaded >= 2 then (ISNULL(fs.Value02, 0.0) * fwh.Month02) else 0.0 end + + case when bc.MonthsLoaded >= 3 then (ISNULL(fs.Value03, 0.0) * fwh.Month03) else 0.0 end + + case when bc.MonthsLoaded >= 4 then (ISNULL(fs.Value04, 0.0) * fwh.Month04) else 0.0 end + + case when bc.MonthsLoaded >= 5 then (ISNULL(fs.Value05, 0.0) * fwh.Month05) else 0.0 end + + case when bc.MonthsLoaded >= 6 then (ISNULL(fs.Value06, 0.0) * fwh.Month06) else 0.0 end + + case when bc.MonthsLoaded >= 7 then (ISNULL(fs.Value07, 0.0) * fwh.Month07) else 0.0 end + + case when bc.MonthsLoaded >= 8 then (ISNULL(fs.Value08, 0.0) * fwh.Month08) else 0.0 end + + case when bc.MonthsLoaded >= 9 then (ISNULL(fs.Value09, 0.0) * fwh.Month09) else 0.0 end + + case when bc.MonthsLoaded >= 10 then (ISNULL(fs.Value10, 0.0) * fwh.Month10) else 0.0 end + + case when bc.MonthsLoaded >= 11 then (ISNULL(fs.Value11, 0.0) * fwh.Month11) else 0.0 end + + case when bc.MonthsLoaded >= 12 then (ISNULL(fs.Value12, 0.0) * fwh.Month12) else 0.0 end + ) / ( + case when bc.MonthsLoaded >= 1 then fwh.Month01 else 0.0 end + + case when bc.MonthsLoaded >= 2 then fwh.Month02 else 0.0 end + + case when bc.MonthsLoaded >= 3 then fwh.Month03 else 0.0 end + + case when bc.MonthsLoaded >= 4 then fwh.Month04 else 0.0 end + + case when bc.MonthsLoaded >= 5 then fwh.Month05 else 0.0 end + + case when bc.MonthsLoaded >= 6 then fwh.Month06 else 0.0 end + + case when bc.MonthsLoaded >= 7 then fwh.Month07 else 0.0 end + + case when bc.MonthsLoaded >= 8 then fwh.Month08 else 0.0 end + + case when bc.MonthsLoaded >= 9 then fwh.Month09 else 0.0 end + + case when bc.MonthsLoaded >= 10 then fwh.Month10 else 0.0 end + + case when bc.MonthsLoaded >= 11 then fwh.Month11 else 0.0 end + + case when bc.MonthsLoaded >= 12 then fwh.Month12 else 0.0 end + ) + ELSE ( + case when bc.MonthsLoaded >= 1 then ISNULL(fs.Value01, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 2 then ISNULL(fs.Value02, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 3 then ISNULL(fs.Value03, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 4 then ISNULL(fs.Value04, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 5 then ISNULL(fs.Value05, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 6 then ISNULL(fs.Value06, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 7 then ISNULL(fs.Value07, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 8 then ISNULL(fs.Value08, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 9 then ISNULL(fs.Value09, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 10 then ISNULL(fs.Value10, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 11 then ISNULL(fs.Value11, 0.0) else 0.0 end + + case when bc.MonthsLoaded >= 12 then ISNULL(fs.Value12, 0.0) else 0.0 end + ) + END AS YTD, + CASE + WHEN fs.UnitTypeID = 144 THEN ( + (ISNULL(fs.Value01, 0.0) * fwh.Month01) + + (ISNULL(fs.Value02, 0.0) * fwh.Month02) + + (ISNULL(fs.Value03, 0.0) * fwh.Month03) + + (ISNULL(fs.Value04, 0.0) * fwh.Month04) + + (ISNULL(fs.Value05, 0.0) * fwh.Month05) + + (ISNULL(fs.Value06, 0.0) * fwh.Month06) + + (ISNULL(fs.Value07, 0.0) * fwh.Month07) + + (ISNULL(fs.Value08, 0.0) * fwh.Month08) + + (ISNULL(fs.Value09, 0.0) * fwh.Month09) + + (ISNULL(fs.Value10, 0.0) * fwh.Month10) + + (ISNULL(fs.Value11, 0.0) * fwh.Month11) + + (ISNULL(fs.Value12, 0.0) * fwh.Month12) + ) / fwh.MonthYearly + ELSE ( + ISNULL(fs.Value01, 0.0) + + ISNULL(fs.Value02, 0.0) + + ISNULL(fs.Value03, 0.0) + + ISNULL(fs.Value04, 0.0) + + ISNULL(fs.Value05, 0.0) + + ISNULL(fs.Value06, 0.0) + + ISNULL(fs.Value07, 0.0) + + ISNULL(fs.Value08, 0.0) + + ISNULL(fs.Value09, 0.0) + + ISNULL(fs.Value10, 0.0) + + ISNULL(fs.Value11, 0.0) + + ISNULL(fs.Value12, 0.0) + ) + END AS Total +FROM + PivoUnpivoHistory fs + INNER JOIN [fw].[DimDepartment] d with (readuncommitted) on d.DepartmentID = fs.DepartmentID + INNER JOIN [fw].[DimEntity] e with (readuncommitted) on e.EntityID = d.EntityID + INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID = fs.JobCodeID + INNER JOIN [fp].[BudgetConfig] bc with (readuncommitted) ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [client].[FactWorkingHoursPerMonth] fwh with (readuncommitted) ON fwh.FiscalYearID = fs.FiscalYearID and fwh.WorkWeekID = case when jc.WorkWeekOverrideID > 0 then jc.WorkWeekOverrideID when d.WorkWeekID > 0 then d.WorkWeekID else e.WorkWeekID end + INNER JOIN [fw].[DimEmployee] emp with (readuncommitted) on emp.EmployeeID = fs.EmployeeID + INNER JOIN [fp].[viewDimPhysician] pr with (readuncommitted) on pr.ProviderID = fs.ProviderID + INNER JOIN [fp].[viewProviderLineItem] prli with (readuncommitted) on prli.ProviderLineItemID = fs.ProviderLineItemID + INNER JOIN [clientdss].[DimProviderType] pt with (readuncommitted) on pt.ProviderTypeID = fs.ProviderTypeID + INNER JOIN [dss].[DimPhysicianSpecialty] ps with (readuncommitted) on ps.PhysicianSpecialtyID = fs.ProviderSpecialtyID +WHERE + fs.TimeClassID IN (1, 2) +GO + + +--------------------------------------------- + +-- fp.viewReportStaffingForEmployeeAndProvider_Unpivoted +CREATE VIEW [fp].[viewReportStaffingForEmployeeAndProvider_Unpivoted] +AS + WITH Staffing AS ( + select * from [fp].[FactReportStaffing] + union all + select * from [fp].[FactReportStaffing_archive] + ), + StaffingHistory AS ( + select * from [fp].[FactReportStaffingHistory] + union all + select * from [fp].[FactReportStaffingHistory_archive] + ) + + -- Making sure final projection has all months included + SELECT factReportStaffing_AllMonths.[BudgetConfigID], factReportStaffing_AllMonths.[EntityID], + factReportStaffing_AllMonths.[DepartmentID], factReportStaffing_AllMonths.[JobCodeID], + factReportStaffing_AllMonths.[PayCodeGroupID], factReportStaffing_AllMonths.[VariabilityID], + factReportStaffing_AllMonths.[ProductiveClassID], factReportStaffing_AllMonths.[UnitTypeID], + factReportStaffing_AllMonths.[TimeClassID], factReportStaffing_AllMonths.[FiscalMonthID], + factReportStaffing_AllMonths.[FiscalYearID], factReportStaffing_AllMonths.[EmployeeID], + factReportStaffing_AllMonths.[ProviderID],factReportStaffing_AllMonths.[ProviderLineItemID], + factReportStaffing_AllMonths.[ProviderTypeID],factReportStaffing_AllMonths.[ProviderSpecialtyID], + COALESCE(frs.Value, factReportStaffing_AllMonths.Value) as Value + FROM ( + SELECT distinct [BudgetConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID], + [ProductiveClassID], [UnitTypeID], [TimeClassID], ca.[FiscalMonthID], [FiscalYearID], [EmployeeID], + [ProviderID], [ProviderLineItemID], [ProviderTypeID], [ProviderSpecialtyID], 0 as Value + FROM fp.viewReportStaffing_MonthsWithValues + CROSS APPLY ( + select FiscalMonthID + from [fw].[DimFiscalMonth] + WHERE FiscalMonthID != 0 + ) ca + WHERE TimeClassID IN (1, 2, 12, 21, 22) + ) factReportStaffing_AllMonths + + LEFT JOIN (select * from fp.viewReportStaffing_MonthsWithValues) frs + ON factReportStaffing_AllMonths.BudgetConfigID = frs.BudgetConfigID + and factReportStaffing_AllMonths.DepartmentID = frs.DepartmentID + and factReportStaffing_AllMonths.FiscalYearID = frs.FiscalYearID + and factReportStaffing_AllMonths.TimeClassID = frs.TimeClassID + and factReportStaffing_AllMonths.VariabilityID = frs.VariabilityID + and factReportStaffing_AllMonths.FiscalMonthID = frs.FiscalMonthID + and factReportStaffing_AllMonths.JobCodeID = frs.JobCodeID + and factReportStaffing_AllMonths.PayCodeGroupID = frs.PayCodeGroupID + and factReportStaffing_AllMonths.UnitTypeID = frs.UnitTypeID + and factReportStaffing_AllMonths.EmployeeID = frs.EmployeeID + and factReportStaffing_AllMonths.ProviderID = frs.ProviderID + and factReportStaffing_AllMonths.ProviderLineItemID = frs.ProviderLineItemID + and factReportStaffing_AllMonths.ProviderTypeID = frs.ProviderTypeID + and factReportStaffing_AllMonths.ProviderSpecialtyID = frs.ProviderSpecialtyID +GO + + +--------------------------------------------- + +-- fp.viewReportStaffing_MonthsWithValues +CREATE VIEW [fp].[viewReportStaffing_MonthsWithValues] AS + WITH Staffing AS ( + select * from [fp].[FactReportStaffing] + union all + select * from [fp].[FactReportStaffing_archive] + ), + StaffingHistory AS ( + select * from [fp].[FactReportStaffingHistory] + union all + select * from [fp].[FactReportStaffingHistory_archive] + ) + -- Manager Budget + SELECT + EntityID, + DepartmentID, + fs.BudgetConfigID, + JobCodeID, + PayCodeGroupID, + bc.FiscalYearID, + VariabilityID, + TimeClassID, + UnitTypeID, + FiscalMonthID, + ProductiveClassID, + EmployeeID, + ProviderID, + ProviderLineItemID, + ProviderTypeID, + ProviderSpecialtyID, + ManagerValue as Value + FROM Staffing fs + INNER JOIN [fp].[BudgetConfig] bc ON fs.BudgetConfigID = bc.BudgetConfigID + WHERE + TimeClassID=2 + + UNION ALL + + -- Initial Budget + SELECT + EntityID, + DepartmentID, + fs.BudgetConfigID, + JobCodeID, + PayCodeGroupID, + bc.FiscalYearID, + VariabilityID, + 21 AS TimeClassID, + UnitTypeID, + FiscalMonthID, + ProductiveClassID, + EmployeeID, + ProviderID, + ProviderLineItemID, + ProviderTypeID, + ProviderSpecialtyID, + OriginalValue as Value + FROM Staffing fs + INNER JOIN [fp].[BudgetConfig] bc ON fs.BudgetConfigID = bc.BudgetConfigID + WHERE + TimeClassID=2 + + UNION ALL + + -- Baseline Budget + SELECT + EntityID, + DepartmentID, + fs.BudgetConfigID, + JobCodeID, + PayCodeGroupID, + bc.FiscalYearID, + VariabilityID, + 22 AS TimeClassID, + UnitTypeID, + FiscalMonthID, + ProductiveClassID, + EmployeeID, + ProviderID, + ProviderLineItemID, + ProviderTypeID, + ProviderSpecialtyID, + Value + FROM Staffing fs + INNER JOIN [fp].[BudgetConfig] bc ON fs.BudgetConfigID = bc.BudgetConfigID + WHERE + TimeClassID=2 + + UNION ALL + + -- Manager Projection + SELECT + EntityID, + DepartmentID, + fs.BudgetConfigID, + JobCodeID, + PayCodeGroupID, + bc.FiscalYearID - 1 as FiscalYearID, + VariabilityID, + 12 AS TimeClassID, + UnitTypeID, + FiscalMonthID, + ProductiveClassID, + EmployeeID, + ProviderID, + ProviderLineItemID, + ProviderTypeID, + ProviderSpecialtyID, + ManagerValue as Value + FROM Staffing fs + INNER JOIN [fp].[BudgetConfig] bc ON fs.BudgetConfigID = bc.BudgetConfigID + WHERE + TimeClassID = 12 + + UNION ALL + + -- Prior Year Actual and Current Year Budget + SELECT + EntityID, + fs.DepartmentID, + fs.BudgetConfigID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.FiscalYearID, + fs.VariabilityID, + fs.TimeClassID, + fs.UnitTypeID, + fs.FiscalMonthID, + ProductiveClassID, + EmployeeID, + ProviderID, + ProviderLineItemID, + ProviderTypeID, + ProviderSpecialtyID, + fs.Value + FROM StaffingHistory fs + INNER JOIN [fp].[BudgetConfig] bc ON fs.BudgetConfigID = bc.BudgetConfigID + WHERE + fs.TimeClassID IN (1, 2) +GO + + +--------------------------------------------- + +-- fp.viewReportStaffing_Unpivoted +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2020-04-22 LR D-09178 Including months with value zero on projection, so that reports wont have null values. + ** 2 2021-04-13 MW JAZZ-18056 Adding missing join on EmployeeID to fix overstated data +*************************************************************/ +CREATE VIEW [fp].[viewReportStaffing_Unpivoted] +AS + WITH Staffing AS ( + select * from [fp].[FactReportStaffing] + union all + select * from [fp].[FactReportStaffing_archive] + ), + StaffingHistory AS ( + select * from [fp].[FactReportStaffingHistory] + union all + select * from [fp].[FactReportStaffingHistory_archive] + ) + + -- Making sure final projection has all months included + SELECT factReportStaffing_AllMonths.[BudgetConfigID], factReportStaffing_AllMonths.[EntityID], + factReportStaffing_AllMonths.[DepartmentID], factReportStaffing_AllMonths.[JobCodeID], + factReportStaffing_AllMonths.[PayCodeGroupID], factReportStaffing_AllMonths.[VariabilityID], + factReportStaffing_AllMonths.[ProductiveClassID], factReportStaffing_AllMonths.[UnitTypeID], + factReportStaffing_AllMonths.[TimeClassID], factReportStaffing_AllMonths.[FiscalMonthID], + factReportStaffing_AllMonths.[FiscalYearID], factReportStaffing_AllMonths.[EmployeeID], + COALESCE(frs.Value, factReportStaffing_AllMonths.Value) as Value + FROM ( + SELECT distinct [BudgetConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID], + [ProductiveClassID], [UnitTypeID], [TimeClassID], ca.[FiscalMonthID], [FiscalYearID], [EmployeeID], 0 as Value + FROM fp.viewReportStaffing_MonthsWithValues + CROSS APPLY ( + select FiscalMonthID + from [fw].[DimFiscalMonth] + WHERE FiscalMonthID != 0 + ) ca + WHERE TimeClassID IN (1, 2, 12, 21, 22) + ) factReportStaffing_AllMonths + + LEFT JOIN (select * from fp.viewReportStaffing_MonthsWithValues) frs + ON factReportStaffing_AllMonths.BudgetConfigID = frs.BudgetConfigID + and factReportStaffing_AllMonths.DepartmentID = frs.DepartmentID + and factReportStaffing_AllMonths.FiscalYearID = frs.FiscalYearID + and factReportStaffing_AllMonths.TimeClassID = frs.TimeClassID + and factReportStaffing_AllMonths.VariabilityID = frs.VariabilityID + and factReportStaffing_AllMonths.FiscalMonthID = frs.FiscalMonthID + and factReportStaffing_AllMonths.JobCodeID = frs.JobCodeID + and factReportStaffing_AllMonths.PayCodeGroupID = frs.PayCodeGroupID + and factReportStaffing_AllMonths.UnitTypeID = frs.UnitTypeID + and factReportStaffing_AllMonths.EmployeeID = frs.EmployeeID +GO + + +--------------------------------------------- + +-- fp.viewReportStatistics +CREATE VIEW [fp].[viewReportStatistics] +AS +WITH PivoUnpivo AS ( +SELECT BudgetConfigID + ,EntityID + ,DepartmentID + ,AccountID + ,PatientClassID + ,PayorID + ,FinancialReportingID + ,UnitTypeID + ,TimeClassID + ,FiscalYearID + ,IsStat + ,ProviderID + ,ProviderTypeID + ,ProviderSpecialtyID + ,ProviderLineItemID + ,ISNULL(MAX([01]) ,0.0) as OriginalValue01 + ,ISNULL(MAX([02]) ,0.0) as OriginalValue02 + ,ISNULL(MAX([03]) ,0.0) as OriginalValue03 + ,ISNULL(MAX([04]) ,0.0) as OriginalValue04 + ,ISNULL(MAX([05]) ,0.0) as OriginalValue05 + ,ISNULL(MAX([06]) ,0.0) as OriginalValue06 + ,ISNULL(MAX([07]) ,0.0) as OriginalValue07 + ,ISNULL(MAX([08]) ,0.0) as OriginalValue08 + ,ISNULL(MAX([09]) ,0.0) as OriginalValue09 + ,ISNULL(MAX([10]) ,0.0) as OriginalValue10 + ,ISNULL(MAX([11]) ,0.0) as OriginalValue11 + ,ISNULL(MAX([12]) ,0.0) as OriginalValue12 + ,ISNULL(MAX([01_2]) ,0.0) as Value01 + ,ISNULL(MAX([02_2]) ,0.0) as Value02 + ,ISNULL(MAX([03_2]) ,0.0) as Value03 + ,ISNULL(MAX([04_2]) ,0.0) as Value04 + ,ISNULL(MAX([05_2]) ,0.0) as Value05 + ,ISNULL(MAX([06_2]) ,0.0) as Value06 + ,ISNULL(MAX([07_2]) ,0.0) as Value07 + ,ISNULL(MAX([08_2]) ,0.0) as Value08 + ,ISNULL(MAX([09_2]) ,0.0) as Value09 + ,ISNULL(MAX([10_2]) ,0.0) as Value10 + ,ISNULL(MAX([11_2]) ,0.0) as Value11 + ,ISNULL(MAX([12_2]) ,0.0) as Value12 + ,ISNULL(MAX([01_3]) ,0.0) as ManagerValue01 + ,ISNULL(MAX([02_3]) ,0.0) as ManagerValue02 + ,ISNULL(MAX([03_3]) ,0.0) as ManagerValue03 + ,ISNULL(MAX([04_3]) ,0.0) as ManagerValue04 + ,ISNULL(MAX([05_3]) ,0.0) as ManagerValue05 + ,ISNULL(MAX([06_3]) ,0.0) as ManagerValue06 + ,ISNULL(MAX([07_3]) ,0.0) as ManagerValue07 + ,ISNULL(MAX([08_3]) ,0.0) as ManagerValue08 + ,ISNULL(MAX([09_3]) ,0.0) as ManagerValue09 + ,ISNULL(MAX([10_3]) ,0.0) as ManagerValue10 + ,ISNULL(MAX([11_3]) ,0.0) as ManagerValue11 + ,ISNULL(MAX([12_3]) ,0.0) as ManagerValue12 +FROM ( +SELECT +BudgetConfigID, +EntityID, +DepartmentID, +s.AccountID, +s.PatientClassID, +IsStat, +PayorID, +FinancialReportingID, +UnitTypeID, +TimeClassID, +FiscalYearID, +ProviderID, +ProviderTypeID, +ProviderSpecialtyID, +ProviderLineItemID, +RIGHT('00'+CAST(dfm.SortOrder as varchar(2)),2) as FiscalMonthID, +OriginalValue, +Value, +ManagerValue, +RIGHT('00'+CAST(dfm.SortOrder as varchar(2)),2)+'_2' as FiscalMonthID_2, +RIGHT('00'+CAST(dfm.SortOrder as varchar(2)),2)+'_3' as FiscalMonthID_3 +FROM [fp].[FactReportStatistics] s +INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = S.AccountID +inner join fw.DimFiscalMonth dfm on dfm.FiscalMonthID = s.FiscalMonthID +UNION ALL +SELECT +BudgetConfigID, +EntityID, +DepartmentID, +s.AccountID, +s.PatientClassID, +IsStat, +PayorID, +FinancialReportingID, +UnitTypeID, +TimeClassID, +FiscalYearID, +ProviderID, +ProviderTypeID, +ProviderSpecialtyID, +ProviderLineItemID, +RIGHT('00'+CAST(dfm.SortOrder as varchar(2)),2) as FiscalMonthID, +OriginalValue, +Value, +ManagerValue, +RIGHT('00'+CAST(dfm.SortOrder as varchar(2)),2)+'_2' as FiscalMonthID_2, +RIGHT('00'+CAST(dfm.SortOrder as varchar(2)),2)+'_3' as FiscalMonthID_3 +FROM [fp].[FactReportStatistics_archive] s +INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = S.AccountID +inner join fw.DimFiscalMonth dfm on dfm.FiscalMonthID = s.FiscalMonthID +--WHERE BudgetConfigID = 4 and EntityID = 1 and DepartmentID = 12238 and JobCodeID = 706 and PayCodeGroupID = 1038 and VariabilityID = 1 and ProductiveClassID = 3 and UnitTypeID = 34 and TimeClassID = 2 +) X + PIVOT (MAX(OriginalValue) + FOR FiscalMonthID IN ([01],[02],[03],[04],[05],[06],[07],[08],[09],[10],[11],[12])) AS Pivot1 +PIVOT (MAX(Value) + FOR FiscalMonthID_2 IN ([01_2],[02_2],[03_2],[04_2],[05_2],[06_2],[07_2],[08_2],[09_2],[10_2],[11_2],[12_2])) AS Pivot2 +PIVOT (MAX(ManagerValue) + FOR FiscalMonthID_3 IN ([01_3],[02_3],[03_3],[04_3],[05_3],[06_3],[07_3],[08_3],[09_3],[10_3],[11_3],[12_3])) AS Pivot1 +GROUP BY BudgetConfigID + ,EntityID + ,DepartmentID + ,AccountID + ,PatientClassID + ,PayorID + ,FinancialReportingID + ,UnitTypeID + ,TimeClassID + ,FiscalYearID + ,IsStat + ,ProviderID + ,ProviderTypeID + ,ProviderSpecialtyID + ,ProviderLineItemID +), +PivoUnpivoHistory AS ( +SELECT BudgetConfigID + ,EntityID + ,DepartmentID + ,AccountID + ,PatientClassID + ,PayorID + ,FinancialReportingID + ,UnitTypeID + ,TimeClassID + ,FiscalYearID + ,IsStat + ,ProviderID + ,ProviderTypeID + ,ProviderSpecialtyID + ,ProviderLineItemID + ,ISNULL(MAX([01]),0.0) as Value01 + ,ISNULL(MAX([02]),0.0) as Value02 + ,ISNULL(MAX([03]),0.0) as Value03 + ,ISNULL(MAX([04]),0.0) as Value04 + ,ISNULL(MAX([05]),0.0) as Value05 + ,ISNULL(MAX([06]),0.0) as Value06 + ,ISNULL(MAX([07]),0.0) as Value07 + ,ISNULL(MAX([08]),0.0) as Value08 + ,ISNULL(MAX([09]),0.0) as Value09 + ,ISNULL(MAX([10]),0.0) as Value10 + ,ISNULL(MAX([11]),0.0) as Value11 + ,ISNULL(MAX([12]),0.0) as Value12 +FROM ( +SELECT +BudgetConfigID, +EntityID, +DepartmentID, +s.AccountID, +s.PatientClassID, +IsStat, +PayorID, +FinancialReportingID, +UnitTypeID, +TimeClassID, +FiscalYearID, +ProviderID, +ProviderTypeID, +ProviderSpecialtyID, +ProviderLineItemID, +RIGHT('00'+CAST(dfm.SortOrder as varchar(2)),2) as FiscalMonthID, +Value +FROM [fp].[FactReportStatisticsHistory] s +INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = S.AccountID +inner join fw.DimFiscalMonth dfm on dfm.FiscalMonthID = s.FiscalMonthID +UNION ALL +SELECT +BudgetConfigID, +EntityID, +DepartmentID, +s.AccountID, +s.PatientClassID, +IsStat, +PayorID, +FinancialReportingID, +UnitTypeID, +TimeClassID, +FiscalYearID, +ProviderID, +ProviderTypeID, +ProviderSpecialtyID, +ProviderLineItemID, +RIGHT('00'+CAST(dfm.SortOrder as varchar(2)),2) as FiscalMonthID, +Value +FROM [fp].[FactReportStatisticsHistory_archive] s +INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = S.AccountID +inner join fw.DimFiscalMonth dfm on dfm.FiscalMonthID = s.FiscalMonthID +--WHERE BudgetConfigID = 4 and EntityID = 1 and DepartmentID = 12238 and JobCodeID = 706 and PayCodeGroupID = 1038 and VariabilityID = 1 and ProductiveClassID = 3 and UnitTypeID = 34 and TimeClassID = 2 +) X +PIVOT (MAX(Value) + FOR FiscalMonthID IN ([01],[02],[03],[04],[05],[06],[07],[08],[09],[10],[11],[12])) AS Pivot1 +GROUP BY BudgetConfigID + ,EntityID + ,DepartmentID + ,AccountID + ,PatientClassID + ,PayorID + ,FinancialReportingID + ,UnitTypeID + ,TimeClassID + ,FiscalYearID + ,IsStat + ,ProviderID + ,ProviderTypeID + ,ProviderSpecialtyID + ,ProviderLineItemID +) + +SELECT + bc.[BudgetConfigID], + st.[DepartmentID], + st.[AccountID], + bc.[FiscalYearID]-1 as [FiscalYearID], + [TimeClassID], + ManagerValue01 as Month01, + ManagerValue02 as Month02, + ManagerValue03 as Month03, + ManagerValue04 as Month04, + ManagerValue05 as Month05, + ManagerValue06 as Month06, + ManagerValue07 as Month07, + ManagerValue08 as Month08, + ManagerValue09 as Month09, + ManagerValue10 as Month10, + ManagerValue11 as Month11, + ManagerValue12 as Month12, + IsStat, + [UnitTypeID], + [PatientClassID], + [ProviderID], + [ProviderTypeID], + [ProviderSpecialtyID], + [ProviderLineItemID], + ManagerValue01+ ManagerValue02+ ManagerValue03+ ManagerValue04+ ManagerValue05+ ManagerValue06+ ManagerValue07+ ManagerValue08+ ManagerValue09+ManagerValue10+ ManagerValue11+ ManagerValue12 as Total, + ManagerValue01+ ManagerValue02+ ManagerValue03+ ManagerValue04+ ManagerValue05+ ManagerValue06+ ManagerValue07+ ManagerValue08+ ManagerValue09+ManagerValue10+ ManagerValue11+ ManagerValue12 as YTD +from PivoUnpivo st +INNER JOIN [fp].[BudgetConfig] bc on st.BudgetConfigID = bc.BudgetConfigID +WHERE TimeClassID=12 + +union all +SELECT + [BudgetConfigID], + st.[DepartmentID], + st.[AccountID], + [FiscalYearID], + 21 as [TimeClassID], + OriginalValue01 as Month01, + OriginalValue02 as Month02, + OriginalValue03 as Month03, + OriginalValue04 as Month04, + OriginalValue05 as Month05, + OriginalValue06 as Month06, + OriginalValue07 as Month07, + OriginalValue08 as Month08, + OriginalValue09 as Month09, + OriginalValue10 as Month10, + OriginalValue11 as Month11, + OriginalValue12 as Month12, + IsStat, + [UnitTypeID], + [PatientClassID], + [ProviderID], + [ProviderTypeID], + [ProviderSpecialtyID], + [ProviderLineItemID], + (OriginalValue01+OriginalValue02+OriginalValue03+OriginalValue04+OriginalValue05+OriginalValue06+OriginalValue07+OriginalValue08+OriginalValue09+OriginalValue10+OriginalValue11+OriginalValue12) as Total, + (OriginalValue01+OriginalValue02+OriginalValue03+OriginalValue04+OriginalValue05+OriginalValue06+OriginalValue07+OriginalValue08+OriginalValue09+OriginalValue10+OriginalValue11+OriginalValue12) AS YTD +from PivoUnpivo st +WHERE TimeClassID=2 + +union all +select + [BudgetConfigID], + st.[DepartmentID], + st.[AccountID], + [FiscalYearID], + [TimeClassID], + ManagerValue01 as Month01, + ManagerValue02 as Month02, + ManagerValue03 as Month03, + ManagerValue04 as Month04, + ManagerValue05 as Month05, + ManagerValue06 as Month06, + ManagerValue07 as Month07, + ManagerValue08 as Month08, + ManagerValue09 as Month09, + ManagerValue10 as Month10, + ManagerValue11 as Month11, + ManagerValue12 as Month12, + IsStat, + [UnitTypeID], + [PatientClassID], + [ProviderID], + [ProviderTypeID], + [ProviderSpecialtyID], + [ProviderLineItemID], + (ManagerValue01+ManagerValue02 +ManagerValue03+ManagerValue04 + ManagerValue05+ManagerValue06+ManagerValue07+ManagerValue08+ManagerValue09+ManagerValue10+ManagerValue11+ManagerValue12) as Total, + (ManagerValue01+ManagerValue02 +ManagerValue03+ManagerValue04 + ManagerValue05+ManagerValue06+ManagerValue07+ManagerValue08+ManagerValue09+ManagerValue10+ManagerValue11+ManagerValue12) as YTD +from PivoUnpivo st +WHERE TimeClassID=2 + +union all +select + [BudgetConfigID], + st.[DepartmentID], + st.[AccountID], + [FiscalYearID], + 18 as [TimeClassID], + Value01 as Month01, + Value02 as Month02, + Value03 as Month03, + Value04 as Month04, + Value05 as Month05, + Value06 as Month06, + Value07 as Month07, + Value08 as Month08, + Value09 as Month09, + Value10 as Month10, + Value11 as Month11, + Value12 as Month12, + IsStat, + [UnitTypeID], + [PatientClassID], + [ProviderID], + [ProviderTypeID], + [ProviderSpecialtyID], + [ProviderLineItemID], + (Value01+Value02+Value03+Value04+Value05+Value06+Value07+Value08+Value09+Value10+Value11+Value12) as Total, + (Value01+Value02+Value03+Value04+Value05+Value06+Value07+Value08+Value09+Value10+Value11+Value12) AS YTD + from PivoUnpivo st +WHERE TimeClassID=2 + +union all +select + bc.[BudgetConfigID], + st.[DepartmentID], + st.[AccountID], + st.FiscalYearID, + [TimeClassID], + Value01 as Month01, + Value02 as Month02, + Value03 as Month03, + Value04 as Month04, + Value05 as Month05, + Value06 as Month06, + Value07 as Month07, + Value08 as Month08, + Value09 as Month09, + Value10 as Month10, + Value11 as Month11, + Value12 as Month12, + IsStat, + [UnitTypeID], + [PatientClassID], + [ProviderID], + [ProviderTypeID], + [ProviderSpecialtyID], + [ProviderLineItemID], + CASE + WHEN (SELECT clientob.GetMonthsLoaded()) = 1 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + WHEN (SELECT clientob.GetMonthsLoaded()) = 2 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + WHEN (SELECT clientob.GetMonthsLoaded()) = 3 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + WHEN (SELECT clientob.GetMonthsLoaded()) = 4 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + WHEN (SELECT clientob.GetMonthsLoaded()) = 5 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + WHEN (SELECT clientob.GetMonthsLoaded()) = 6 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + WHEN (SELECT clientob.GetMonthsLoaded()) = 7 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + WHEN (SELECT clientob.GetMonthsLoaded()) = 8 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + Value08 + WHEN (SELECT clientob.GetMonthsLoaded()) = 9 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + Value08 + Value09 + WHEN (SELECT clientob.GetMonthsLoaded()) = 10 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + Value08 + Value09 + Value10 + WHEN (SELECT clientob.GetMonthsLoaded()) = 11 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + Value08 + Value09 + Value10 + Value11 + ELSE (Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + Value08 + Value09 + Value10 + Value11 + Value12) END + AS Total, + CASE + WHEN (SELECT clientob.GetMonthsLoaded()) = 1 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + WHEN (SELECT clientob.GetMonthsLoaded()) = 2 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + WHEN (SELECT clientob.GetMonthsLoaded()) = 3 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + WHEN (SELECT clientob.GetMonthsLoaded()) = 4 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + WHEN (SELECT clientob.GetMonthsLoaded()) = 5 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + WHEN (SELECT clientob.GetMonthsLoaded()) = 6 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + WHEN (SELECT clientob.GetMonthsLoaded()) = 7 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + WHEN (SELECT clientob.GetMonthsLoaded()) = 8 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + Value08 + WHEN (SELECT clientob.GetMonthsLoaded()) = 9 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + Value08 + Value09 + WHEN (SELECT clientob.GetMonthsLoaded()) = 10 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + Value08 + Value09 + Value10 + WHEN (SELECT clientob.GetMonthsLoaded()) = 11 AND bc.[FiscalYearID] - 2= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + Value08 + Value09 + Value10 + Value11 + ELSE (Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + Value08 + Value09 + Value10 + Value11+ Value12) END + AS YTD +from PivoUnpivoHistory st +INNER JOIN [fp].[BudgetConfig] bc on st.BudgetConfigID = bc.BudgetConfigID +WHERE TimeClassID=1 + +union all +select + bc.[BudgetConfigID], + st.[DepartmentID], + st.[AccountID], + bc.[FiscalYearID] - 1 as FiscalYearID, + 2 AS [TimeClassID], + Value01 as Month01, + Value02 as Month02, + Value03 as Month03, + Value04 as Month04, + Value05 as Month05, + Value06 as Month06, + Value07 as Month07, + Value08 as Month08, + Value09 as Month09, + Value10 as Month10, + Value11 as Month11, + Value12 as Month12, + IsStat, + [UnitTypeID], + [PatientClassID], + [ProviderID], + [ProviderTypeID], + [ProviderSpecialtyID], + [ProviderLineItemID], + CASE + WHEN (SELECT clientob.GetMonthsLoaded()) = 1 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + WHEN (SELECT clientob.GetMonthsLoaded()) = 2 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + WHEN (SELECT clientob.GetMonthsLoaded()) = 3 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + WHEN (SELECT clientob.GetMonthsLoaded()) = 4 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + WHEN (SELECT clientob.GetMonthsLoaded()) = 5 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + WHEN (SELECT clientob.GetMonthsLoaded()) = 6 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + WHEN (SELECT clientob.GetMonthsLoaded()) = 7 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + WHEN (SELECT clientob.GetMonthsLoaded()) = 8 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + Value08 + WHEN (SELECT clientob.GetMonthsLoaded()) = 9 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + Value08 + Value09 + WHEN (SELECT clientob.GetMonthsLoaded()) = 10 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + Value08 + Value09 + Value10 + WHEN (SELECT clientob.GetMonthsLoaded()) = 11 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + Value08 + Value09 + Value10 + Value11 + ELSE (Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + Value08 + Value09 + Value10 + Value11+ Value12) END + AS Total, + CASE + WHEN (SELECT clientob.GetMonthsLoaded()) = 1 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + WHEN (SELECT clientob.GetMonthsLoaded()) = 2 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + WHEN (SELECT clientob.GetMonthsLoaded()) = 3 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + WHEN (SELECT clientob.GetMonthsLoaded()) = 4 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + WHEN (SELECT clientob.GetMonthsLoaded()) = 5 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + WHEN (SELECT clientob.GetMonthsLoaded()) = 6 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + WHEN (SELECT clientob.GetMonthsLoaded()) = 7 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + WHEN (SELECT clientob.GetMonthsLoaded()) = 8 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + Value08 + WHEN (SELECT clientob.GetMonthsLoaded()) = 9 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + Value08 + Value09 + WHEN (SELECT clientob.GetMonthsLoaded()) = 10 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + Value08 + Value09 + Value10 + WHEN (SELECT clientob.GetMonthsLoaded()) = 11 AND bc.[FiscalYearID] - 1= bc.FiscalYearID-1 AND [TimeClassID]=1 then Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + Value08 + Value09 + Value10 + Value11 + ELSE (Value01 + Value02 + Value03 + Value04 + Value05 + Value06 + Value07 + Value08 + Value09 + Value10 + Value11+ Value12) END + AS YTD +from PivoUnpivoHistory st +INNER JOIN [fp].[BudgetConfig] bc on st.BudgetConfigID = bc.BudgetConfigID +WHERE TimeClassID=2 +GO + + +--------------------------------------------- + +-- fp.viewReportStatistics_AccountHistory +CREATE VIEW fp.viewReportStatistics_AccountHistory +AS + +SELECT + fs.[BudgetConfigID], + fs.[DepartmentID], + fs.[AccountID], + bc.[FiscalYearID] - 2 as FiscalYearID, + 1 AS [TimeClassID], + fh.PriorYearActualValue01 as Month01, + fh.PriorYearActualValue02 as Month02, + fh.PriorYearActualValue03 as Month03, + fh.PriorYearActualValue04 as Month04, + fh.PriorYearActualValue05 as Month05, + fh.PriorYearActualValue06 as Month06, + fh.PriorYearActualValue07 as Month07, + fh.PriorYearActualValue08 as Month08, + fh.PriorYearActualValue09 as Month09, + fh.PriorYearActualValue10 as Month10, + fh.PriorYearActualValue11 as Month11, + fh.PriorYearActualValue12 as Month12, + acc.IsStat, + fs.UnitTypeID, + acc.PatientClassID, + fh.PriorYearActualValueTotal AS Total, + 0 AS YTD, + bc.FiscalYearID AS BudgetFiscalYearID + FROM [fp].[FactStatistics] fs INNER JOIN [fp].[FactStatisticsHistory] fh on fs.StatisticsID = fh.StatisticsID + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = fs.AccountID + INNER JOIN [fp].[BudgetConfig] bc on fs.BudgetConfigID = bc.BudgetConfigID + UNION +SELECT + fs.[BudgetConfigID], + fs.[DepartmentID], + fs.[AccountID], + bc.[FiscalYearID] - 1 as FiscalYearID, + 1 AS [TimeClassID], + fh.ActualYTDValue01 as Month01, + fh.ActualYTDValue02 as Month02, + fh.ActualYTDValue03 as Month03, + fh.ActualYTDValue04 as Month04, + fh.ActualYTDValue05 as Month05, + fh.ActualYTDValue06 as Month06, + fh.ActualYTDValue07 as Month07, + fh.ActualYTDValue08 as Month08, + fh.ActualYTDValue09 as Month09, + fh.ActualYTDValue10 as Month10, + fh.ActualYTDValue11 as Month11, + fh.ActualYTDValue12 as Month12, + acc.IsStat, + fs.UnitTypeID, + acc.PatientClassID, + fh.ActualYTDValueTotal AS Total, + 0 AS YTD, + bc.FiscalYearID AS BudgetFiscalYearID + FROM [fp].[FactStatistics] fs INNER JOIN [fp].[FactStatisticsHistory] fh on fs.StatisticsID = fh.StatisticsID + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = fs.AccountID + INNER JOIN [fp].[BudgetConfig] bc on fs.BudgetConfigID = bc.BudgetConfigID +UNION +SELECT + fs.[BudgetConfigID], + fs.[DepartmentID], + fs.[AccountID], + bc.[FiscalYearID] - 1 as FiscalYearID, + 2 AS [TimeClassID], + fh.CurrentYearBudget01 as Month01, + fh.CurrentYearBudget02 as Month02, + fh.CurrentYearBudget03 as Month03, + fh.CurrentYearBudget04 as Month04, + fh.CurrentYearBudget05 as Month05, + fh.CurrentYearBudget06 as Month06, + fh.CurrentYearBudget07 as Month07, + fh.CurrentYearBudget08 as Month08, + fh.CurrentYearBudget09 as Month09, + fh.CurrentYearBudget10 as Month10, + fh.CurrentYearBudget11 as Month11, + fh.CurrentYearBudget12 as Month12, + acc.IsStat, + fs.UnitTypeID, + acc.PatientClassID, + fh.CurrentYearBudgetTotal AS Total, + 0 AS YTD, + bc.FiscalYearID AS BudgetFiscalYearID + FROM [fp].[FactStatistics] fs INNER JOIN [fp].[FactStatisticsHistory] fh on fs.StatisticsID = fh.StatisticsID + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = fs.AccountID + INNER JOIN [fp].[BudgetConfig] bc on fs.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewReportStatistics_BaselineBudget +CREATE VIEW fp.viewReportStatistics_BaselineBudget +AS + +SELECT + fs.[BudgetConfigID], + fs.[DepartmentID], + fs.[AccountID], + bc.[FiscalYearID], + 18 AS [TimeClassID], + fp.AdjustedValue01 as Month01, + fp.AdjustedValue02 as Month02, + fp.AdjustedValue03 as Month03, + fp.AdjustedValue04 as Month04, + fp.AdjustedValue05 as Month05, + fp.AdjustedValue06 as Month06, + fp.AdjustedValue07 as Month07, + fp.AdjustedValue08 as Month08, + fp.AdjustedValue09 as Month09, + fp.AdjustedValue10 as Month10, + fp.AdjustedValue11 as Month11, + fp.AdjustedValue12 as Month12, + acc.IsStat, + fs.UnitTypeID, + acc.PatientClassID, + fp.AdjustedValueTotal AS Total, + 0 AS YTD + FROM [fp].[FactStatistics] fs INNER JOIN [fp].[FactStatisticsBudget] fp on fs.StatisticsID = fp.StatisticsID + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = fs.AccountID + INNER JOIN [fp].[BudgetConfig] bc on fs.BudgetConfigID = bc.BudgetConfigID + WHERE BudgetPhaseID = 2 +GO + + +--------------------------------------------- + +-- fp.viewReportStatistics_Budget +CREATE VIEW fp.viewReportStatistics_Budget +AS + + +SELECT + fs.[BudgetConfigID], + fs.[DepartmentID], + fs.[AccountID], + bc.[FiscalYearID], + 2 AS [TimeClassID], + fp.AdjustedValue01 as Month01, + fp.AdjustedValue02 as Month02, + fp.AdjustedValue03 as Month03, + fp.AdjustedValue04 as Month04, + fp.AdjustedValue05 as Month05, + fp.AdjustedValue06 as Month06, + fp.AdjustedValue07 as Month07, + fp.AdjustedValue08 as Month08, + fp.AdjustedValue09 as Month09, + fp.AdjustedValue10 as Month10, + fp.AdjustedValue11 as Month11, + fp.AdjustedValue12 as Month12, + acc.IsStat, + fs.UnitTypeID, + acc.PatientClassID, + fp.AdjustedValueTotal AS Total, + 0 AS YTD + FROM [fp].[FactStatistics] fs INNER JOIN [fp].[FactStatisticsBudget] fp on fs.StatisticsID = fp.StatisticsID + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = fs.AccountID + INNER JOIN [fp].[BudgetConfig] bc on fs.BudgetConfigID = bc.BudgetConfigID + WHERE BudgetPhaseID = 3 +GO + + +--------------------------------------------- + +-- fp.viewReportStatistics_InitialBudget +CREATE VIEW fp.viewReportStatistics_InitialBudget +AS + +SELECT + fs.[BudgetConfigID], + fs.[DepartmentID], + fs.[AccountID], + bc.[FiscalYearID], + 21 AS [TimeClassID], + fs.InitialBudget01 as Month01, + fs.InitialBudget02 as Month02, + fs.InitialBudget03 as Month03, + fs.InitialBudget04 as Month04, + fs.InitialBudget05 as Month05, + fs.InitialBudget06 as Month06, + fs.InitialBudget07 as Month07, + fs.InitialBudget08 as Month08, + fs.InitialBudget09 as Month09, + fs.InitialBudget10 as Month10, + fs.InitialBudget11 as Month11, + fs.InitialBudget12 as Month12, + acc.IsStat, + fs.UnitTypeID, + acc.PatientClassID, + fs.InitialBudgetTotal AS Total, + 0 AS YTD + FROM [fp].[FactStatistics] fs + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = fs.AccountID + INNER JOIN [fp].[BudgetConfig] bc on fs.BudgetConfigID = bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewReportStatistics_MonthsWithValues +CREATE VIEW [fp].[viewReportStatistics_MonthsWithValues] AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2024-03-25 MZ JAZZ-68120 Removed join on [fw].[DimAccount] + *************************************************************/ + WITH Stat AS ( + select * from [fp].[FactReportStatistics] + union all + select * from [fp].[FactReportStatistics_archive] + ), + StatHistory AS ( + select * from [fp].[FactReportStatisticsHistory] + union all + select * from [fp].[FactReportStatisticsHistory_archive] + ) + + -- Manager Projection + SELECT + bc.BudgetConfigID, + st.EntityID, + st.DepartmentID, + st.AccountID, + bc.FiscalYearID-1 as FiscalYearID, + TimeClassID, + ManagerValue as Value, + UnitTypeID, + st.PayorID, + st.FinancialReportingID, + st.PatientClassID, + FiscalMonthID, + st.ProviderID, + st.ProviderLineItemID, + st.ProviderSpecialtyID, + st.ProviderTypeID + from Stat st + INNER JOIN fp.BudgetConfig bc on st.BudgetConfigID = bc.BudgetConfigID + WHERE TimeClassID=12 + + union all + + -- Initial Budget + SELECT + BudgetConfigID, + st.EntityID, + st.DepartmentID, + st.AccountID, + FiscalYearID, + 21 as TimeClassID, + OriginalValue as Value, + UnitTypeID, + st.PayorID, + st.FinancialReportingID, + st.PatientClassID, + FiscalMonthID, + st.ProviderID, + st.ProviderLineItemID, + st.ProviderSpecialtyID, + st.ProviderTypeID + from Stat st + WHERE TimeClassID=2 + + union all + + -- Manager Budget + select + BudgetConfigID, + st.EntityID, + st.DepartmentID, + st.AccountID, + FiscalYearID, + TimeClassID, + ManagerValue as Value, + UnitTypeID, + st.PayorID, + st.FinancialReportingID, + st.PatientClassID, + FiscalMonthID, + st.ProviderID, + st.ProviderLineItemID, + st.ProviderSpecialtyID, + st.ProviderTypeID + from Stat st + WHERE TimeClassID=2 + + union all + + -- Baseline Budget + select + BudgetConfigID, + st.EntityID, + st.DepartmentID, + st.AccountID, + FiscalYearID, + 22 as TimeClassID, + Value, + UnitTypeID, + st.PayorID, + st.FinancialReportingID, + st.PatientClassID, + FiscalMonthID, + st.ProviderID, + st.ProviderLineItemID, + st.ProviderSpecialtyID, + st.ProviderTypeID + from Stat st + WHERE TimeClassID=2 + + union all + + -- Prior Year Actual and Current Year Budget + select + BudgetConfigID, + st.EntityID, + st.DepartmentID, + st.AccountID, + st.FiscalYearID, + TimeClassID, + Value, + UnitTypeID, + st.PayorID, + st.FinancialReportingID, + st.PatientClassID, + FiscalMonthID, + st.ProviderID, + st.ProviderLineItemID, + st.ProviderSpecialtyID, + st.ProviderTypeID + from StatHistory st + WHERE TimeClassID in(1, 2) +GO + + +--------------------------------------------- + +-- fp.viewReportStatistics_Projection +CREATE VIEW fp.viewReportStatistics_Projection +AS + +SELECT + fs.[BudgetConfigID], + fs.[DepartmentID], + fs.[AccountID], + bc.[FiscalYearID] - 1 AS FiscalYearID, + 12 AS [TimeClassID], + fp.AdjustedValue01 as Month01, + fp.AdjustedValue02 as Month02, + fp.AdjustedValue03 as Month03, + fp.AdjustedValue04 as Month04, + fp.AdjustedValue05 as Month05, + fp.AdjustedValue06 as Month06, + fp.AdjustedValue07 as Month07, + fp.AdjustedValue08 as Month08, + fp.AdjustedValue09 as Month09, + fp.AdjustedValue10 as Month10, + fp.AdjustedValue11 as Month11, + fp.AdjustedValue12 as Month12, + acc.IsStat, + fs.UnitTypeID, + acc.PatientClassID, + fp.AdjustedValueTotal AS Total, + 0 AS YTD + FROM [fp].[FactStatistics] fs INNER JOIN [fp].[FactStatisticsProjection] fp on fs.StatisticsID = fp.StatisticsID + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = fs.AccountID + INNER JOIN [fp].[BudgetConfig] bc on fs.BudgetConfigID = bc.BudgetConfigID + WHERE BudgetPhaseID = 3 +GO + + +--------------------------------------------- + +-- fp.viewReportStatistics_Unpivoted +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2020-04-22 LR D-09178 Including months with value zero on projection, so that reports wont have null values. + ** 2 2021-05-07 MD JAZZ-15686 Adding Provider fields + ** 2 2021-07-20 MD JAZZ-23237 Adding union alls for data transfer tables +*************************************************************/ +CREATE VIEW [fp].[viewReportStatistics_Unpivoted] +AS + WITH Stat AS ( + select * from [fp].[FactReportStatistics] + union all + select * from [fp].[FactReportStatistics_archive] + ), + StatHistory AS ( + select * from [fp].[FactReportStatisticsHistory] + union all + select * from [fp].[FactReportStatisticsHistory_archive] + ), + StatDataTransfer AS ( + select * from [fp].[FactReportStatisticsDataTransfer] + ), + StatHistoryDataTransfer AS ( + select * from [fp].[FactReportStatisticsHistoryDataTransfer] + ) + + -- Making sure final projection has all months included + SELECT factReportStatistics_AllMonths.[BudgetConfigID], factReportStatistics_AllMonths.[EntityID], + factReportStatistics_AllMonths.[DepartmentID], factReportStatistics_AllMonths.[AccountID], + factReportStatistics_AllMonths.[PatientClassID], factReportStatistics_AllMonths.[PayorID], + factReportStatistics_AllMonths.[FinancialReportingID], factReportStatistics_AllMonths.[UnitTypeID], + factReportStatistics_AllMonths.[TimeClassID], factReportStatistics_AllMonths.[FiscalMonthID], + factReportStatistics_AllMonths.[FiscalYearID], factReportStatistics_AllMonths.[ProviderID], + factReportStatistics_AllMonths.[ProviderTypeID], factReportStatistics_AllMonths.[ProviderSpecialtyID], + factReportStatistics_AllMonths.[ProviderLineItemID], + COALESCE(frs.Value, factReportStatistics_AllMonths.Value) as Value + FROM ( + SELECT distinct [BudgetConfigID], [EntityID], [DepartmentID], [AccountID], [PatientClassID], [PayorID], + [FinancialReportingID], [UnitTypeID], [TimeClassID], ca.[FiscalMonthID], [FiscalYearID], + [ProviderID], [ProviderTypeID], [ProviderSpecialtyID], [ProviderLineItemID], + 0 as Value, 0 as OriginalValue, 0 as ManagerValue + FROM fp.viewReportStatistics_MonthsWithValues + CROSS APPLY ( + select FiscalMonthID + from [fw].[DimFiscalMonth] + WHERE FiscalMonthID != 0 + ) ca + WHERE TimeClassID IN (1, 2, 12, 21, 22) + ) factReportStatistics_AllMonths + + LEFT JOIN (select * from fp.viewReportStatistics_MonthsWithValues) frs + ON factReportStatistics_AllMonths.BudgetConfigID = frs.BudgetConfigID + and factReportStatistics_AllMonths.DepartmentID = frs.DepartmentID + and factReportStatistics_AllMonths.AccountID = frs.AccountID + and factReportStatistics_AllMonths.FiscalYearID = frs.FiscalYearID + and factReportStatistics_AllMonths.TimeClassID = frs.TimeClassID + and factReportStatistics_AllMonths.FiscalMonthID = frs.FiscalMonthID + and factReportStatistics_AllMonths.PatientClassID = frs.PatientClassID + and factReportStatistics_AllMonths.UnitTypeID = frs.UnitTypeID + and factReportStatistics_AllMonths.ProviderID = frs.ProviderID + and factReportStatistics_AllMonths.ProviderTypeID = frs.ProviderTypeID + and factReportStatistics_AllMonths.ProviderSpecialtyID = frs.ProviderSpecialtyID + and factReportStatistics_AllMonths.ProviderLineItemID = frs.ProviderLineItemID + + UNION ALL + + SELECT + sdt.BudgetConfigID, + sdt.EntityID, + sdt.DepartmentID, + sdt.AccountID, + sdt.PatientClassID, + sdt.PayorID, + FinancialReportingID, + sdt.UnitTypeID, + sdt.TimeClassID, + sdt.FiscalMonthID, + sdt.FiscalYearID, + 0 as ProviderID, + 0 as ProviderTypeID, + 0 as ProviderSpecialityID, + 0 as ProviderLineItemID, + --OriginalValue, + sdt.Value + --ManagerValue + FROM StatDataTransfer sdt + + UNION ALL + + SELECT + shdt.BudgetConfigID, + shdt.EntityID, + shdt.DepartmentID, + shdt.AccountID, + shdt.PatientClassID, + shdt.PayorID, + FinancialReportingID, + shdt.UnitTypeID, + shdt.TimeClassID, + shdt.FiscalMonthID, + shdt.FiscalYearID, + 0 as ProviderID, + 0 as ProviderTypeID, + 0 as ProviderSpecialityID, + 0 as ProviderLineItemID, + --OriginalValue, + shdt.Value + --ManagerValue + FROM StatHistoryDataTransfer shdt +GO + + +--------------------------------------------- + +-- fp.viewRevenueAccounts +CREATE VIEW [fp].[viewRevenueAccounts] +AS + SELECT acc.* + FROM [fw].[DimAccount] acc + INNER JOIN [ob].[DimAccountPH] aph ON acc.OBAccountPHID = aph.AccountPHID + WHERE aph.Name IN ('Gross Charges - Clinic','Gross Charges - ED','Gross Charges - Inpatient','Gross Charges - Observation','Gross Charges - Other','Gross Charges - Outpatient') +GO + + +--------------------------------------------- + +-- fp.viewRevenueExpenseFlexingConfig +CREATE VIEW [fp].[viewRevenueExpenseFlexingConfig] +AS +SELECT + b.EntityGroupConfigGUID, + b.DepartmentID, + b.AccountID, + CASE WHEN b.FlexMethodID = 6 THEN 6 + ELSE COALESCE(ovr.FlexMethodID, b.FlexMethodID) END AS FlexMethodID +FROM ( + SELECT + fc.EntityGroupConfigGUID, + fc.DepartmentID, + acct.AccountID, + fc.FlexMethodID + FROM [fp].[RevenueExpenseFlexingConfig] fc + CROSS APPLY (SELECT AccountID FROM [fp].[viewRevenueAccounts]) acct +) b +LEFT JOIN [fp].[RevenueFlexingOverrideConfig] ovr + ON b.DepartmentID = ovr.DepartmentID + AND b.AccountID = ovr.AccountID + AND b.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID +GO + + +--------------------------------------------- + +-- fp.viewRosterBudgetBasisResult +CREATE VIEW [fp].[viewRosterBudgetBasisResult] +/**************************************************************************************************** +** Author: srk +** Create Date: 2017.01.25 +** Description: Reporting view for the 'OB Roster Budgeting Data' data source +** Last Modified: 2018.02.09 +** GM Release: 2017.1.3 +**************************************************************************************************** +** Change History +**************************************************************************************************** +** CID Date Author WI Description +** 1 2017.04.17 srk D-05867 Making sure view pulls in newly added employees +** 2 2017.05.16 srk D-05867 Pulling in start month for new employees +** 3 2017.11.16 my B-17923 Replacing Codes with IDs and removing new employees because new employees are now in the employee dim +** 4 2018.02.09 srk B-18879 Adding position number, fiscalyearid and comment to view +** 5 2023.03.24 MY JAZZ-51675 Add IsActive so it only pulls active config +****************************************************************************************************/ +AS + SELECT + DB.DepartmentalBudgetID, + DB.DepartmentCode, + ISNULL(BR.EmployeeID,0) as EmployeeID, + coalesce(DE.Code, 'Not Specified') as EmployeeCode, + DE.Number, + Coalesce(NE.PositionNumber, 'Not Specified') as PositionNumber, + ISNULL(BR.JobCodeID,0) as JobCodeID, + DE.JobCode, + BR.PayCodeGroupID, + PCG.PayCodeGroupCode, + coalesce(NE.FiscalYearID,0) as NewEmployeeStartYear, + coalesce(NE.FiscalMonthID,0) as NewEmployeeStartMonth, + coalesce(NE.Comment, 'Not Specified') as NewEmployeeComments, + BR.InitialDollars, + BR.ProjectedDollars, + BR.Dollars, + BR.ProjectedFTEs, + BR.FTEs, + BR.Comment + FROM [fp].[RosterBudgetBasisResult] BR + INNER JOIN fp.BudgetConfig bc ON BR.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN [fw].[DimEmployee] DE ON BR.EmployeeID = DE.EmployeeID + INNER JOIN [ob].[DimDepartmentalBudget] DB ON BR.DepartmentID = DB.DepartmentID + INNER JOIN [fw].[DimPayCodeGroup] PCG ON BR.PayCodeGroupID = PCG.PayCodeGroupID + LEFT JOIN [fp].[RosterBudgetNewEmployee] NE on DE.EmployeeID = NE.EmployeeID + WHERE bc.IsActive = 1 +GO + + +--------------------------------------------- + +-- fp.viewRosterBudgetRequest +CREATE VIEW [fp].[viewRosterBudgetRequest] +/**************************************************************************************************** +** Author: srk +** Create Date: 2018.02.09 +** Description: Reporting view for the 'OB Roster Budgeting Approval Requests' data source +** Last Modified: 2018.02.09 +** GM Release: 2018.2.1 +**************************************************************************************************** +** Change History +**************************************************************************************************** +** CID Date Author WI Description +** +****************************************************************************************************/ +AS + +SELECT + BC.BudgetConfigID, + RBR.UserGuid, + CASE + WHEN RBR.STATUS = 0 THEN 'Pending Approval' + WHEN RBR.STATUS = 1 THEN 'Approved' + WHEN RBR.STATUS = 2 THEN 'Denied' END AS Status, + RBR.Comment, + RBR.JobCodeID, + RBR.PayCodeGroupID, + RBR.DepartmentID, + RBR.EmployeeID, + COALESCE(NE.PositionNumber, 'Not Specified') as PositionNumber, + RBR.dollartype as DollarType, + RBR.Dollars +FROM [fp].[RosterBudgetRequest] RBR + INNER JOIN [fp].[BudgetConfig] BC on RBR.BudgetConfigGUID = BC.BudgetConfigGUID + LEFT JOIN [fp].[RosterBudgetNewEmployee] NE on RBR.EmployeeID = NE.EmployeeID +GO + + +--------------------------------------------- + +-- fp.viewRosterBudgetToStaffingPC +CREATE view [fp].[viewRosterBudgetToStaffingPC] +/**************************************************************************************************** +** Author: cbb +** Create Date: 2016.10.11 +** Description: roster budget data formatted for insertion into department budget models +** Last Modified: 2017.02.06 +** GM Release: 2017.1.0 +**************************************************************************************************** +** Change History +**************************************************************************************************** +** CID Date Author WI Description +** 1 2017.02.06 cbb d05500 filter out inactive plans +****************************************************************************************************/ +as + +select + [DepartmentalBudgetID] = ob.[DepartmentalBudgetID], + [PayCodeGroupID] = pcg.[PayCodeGroupID], + [PayCodeID] = 0, + [JobCodeID] = jc.[JobCodeID], + [EmployeeID] = 0, + [FiscalYearID] = case + when app.MeasureName like 'Projected%' + then (bc.[FiscalYearID]-1) + else bc.[FiscalYearID] + end, + [TimeClassID] = case + when app.MeasureName like 'Projected%' + then 12 + else 2 + end, + [UnitTypeID] = case + when app.MeasureName like '%FTEs' + then + case pcg.ProductiveClassID + when 2 then 146 -- Non-Productive + when 3 then 148 -- Productive + when 5 then 147 -- Differential + when 6 then 52 -- Productive Non-FTE + else 51 + end + else 34 + end, + [DataTypeID] = 3, + [Month01] = app.Amount * whpm.Month01 * + case when rem.StartMonthID > 1 then 0 + else + case + when app.MeasureName like '%FTEs' + then 1 + else 1/rem.RemainingHours + end + end, + [Month02] = app.Amount * whpm.Month02 * + case when rem.StartMonthID > 2 then 0 + else + case + when app.MeasureName like '%FTEs' + then 1 + else 1/rem.RemainingHours + end + end, + [Month03] = app.Amount * whpm.Month03 * + case when rem.StartMonthID > 3 then 0 + else + case + when app.MeasureName like '%FTEs' + then 1 + else 1/rem.RemainingHours + end + end, + [Month04] = app.Amount * whpm.Month04 * + case when rem.StartMonthID > 4 then 0 + else + case + when app.MeasureName like '%FTEs' + then 1 + else 1/rem.RemainingHours + end + end, + [Month05] = app.Amount * whpm.Month05 * + case when rem.StartMonthID > 5 then 0 + else + case + when app.MeasureName like '%FTEs' + then 1 + else 1/rem.RemainingHours + end + end, + [Month06] = app.Amount * whpm.Month06 * + case when rem.StartMonthID > 6 then 0 + else + case + when app.MeasureName like '%FTEs' + then 1 + else 1/rem.RemainingHours + end + end, + [Month07] = app.Amount * whpm.Month07 * + case when rem.StartMonthID > 7 then 0 + else + case + when app.MeasureName like '%FTEs' + then 1 + else 1/rem.RemainingHours + end + end, + [Month08] = app.Amount * whpm.Month08 * + case when rem.StartMonthID > 8 then 0 + else + case + when app.MeasureName like '%FTEs' + then 1 + else 1/rem.RemainingHours + end + end, + [Month09] = app.Amount * whpm.Month09 * + case when rem.StartMonthID > 9 then 0 + else + case + when app.MeasureName like '%FTEs' + then 1 + else 1/rem.RemainingHours + end + end, + [Month10] = app.Amount * whpm.Month10 * + case when rem.StartMonthID > 10 then 0 + else + case + when app.MeasureName like '%FTEs' + then 1 + else 1/rem.RemainingHours + end + end, + [Month11] = app.Amount * whpm.Month11 * + case when rem.StartMonthID > 11 then 0 + else + case + when app.MeasureName like '%FTEs' + then 1 + else 1/rem.RemainingHours + end + end, + [Month12] = app.Amount * whpm.Month12 * + case when rem.StartMonthID > 12 then 0 + else + case + when app.MeasureName like '%FTEs' + then 1 + else 1/rem.RemainingHours + end + end +FROM [fp].[RosterBudgetBasisResult] data + cross apply + ( + values + ('Dollars', data.Dollars), + ('FTEs', data.FTEs), + ('ProjectedDollars', data.ProjectedDollars), + ('ProjectedFTEs', data.ProjectedFTEs) + ) app (MeasureName, Amount) + inner join [fp].[BudgetConfig] bc + on bc.BudgetConfigGUID=data.BudgetConfigGUID + inner join [fw].[DimDepartment] md + on md.DepartmentID=data.DepartmentID + inner join [fw].[DimJobCode] jc + on jc.JobCodeID=data.JobCodeID + inner join [ob].[DimDepartmentalBudget] ob + on ob.DepartmentID=md.DepartmentID + inner join [fw].[DimPayCodeGroup] pcg + on pcg.PayCodeGroupID=data.PayCodeGroupID + inner join [client].[FactWorkingHoursPerMonth] whpm + on case + when jc.WorkWeekOverrideID=-1 + then ob.EntityDefaultWorkWeekID + else + jc.WorkWeekOverrideID + end = whpm.WorkWeekID + and case + when app.MeasureName like 'Projected%' + then (bc.[FiscalYearID]-1) + else bc.[FiscalYearID] + end = whpm.FiscalYearID + left join [fp].[RosterBudgetNewEmployee] new + on data.BudgetConfigGUID = new.BudgetConfigGUID + and data.EmployeeID = new.EmployeeID + cross apply + ( + select + StartMonthID = case + when app.MeasureName like 'Projected%' + then case when new.FiscalMonthID <= ob.MonthsLoaded then (ob.MonthsLoaded+1) else new.FiscalMonthID end + else 1 + end, + RemainingHours = case + when app.MeasureName like 'Projected%' + then + case coalesce(new.FiscalMonthID, 1) + when 1 then wh.MonthYearly + when 2 then wh.Month02 + wh.Month03 + wh.Month04 + wh.Month05 + wh.Month06 + wh.Month07 + wh.Month08 + wh.Month09 + wh.Month10 + wh.Month11 + wh.Month12 + when 3 then wh.Month03 + wh.Month04 + wh.Month05 + wh.Month06 + wh.Month07 + wh.Month08 + wh.Month09 + wh.Month10 + wh.Month11 + wh.Month12 + when 4 then wh.Month04 + wh.Month05 + wh.Month06 + wh.Month07 + wh.Month08 + wh.Month09 + wh.Month10 + wh.Month11 + wh.Month12 + when 5 then wh.Month05 + wh.Month06 + wh.Month07 + wh.Month08 + wh.Month09 + wh.Month10 + wh.Month11 + wh.Month12 + when 6 then wh.Month06 + wh.Month07 + wh.Month08 + wh.Month09 + wh.Month10 + wh.Month11 + wh.Month12 + when 7 then wh.Month07 + wh.Month08 + wh.Month09 + wh.Month10 + wh.Month11 + wh.Month12 + when 8 then wh.Month08 + wh.Month09 + wh.Month10 + wh.Month11 + wh.Month12 + when 9 then wh.Month09 + wh.Month10 + wh.Month11 + wh.Month12 + when 10 then wh.Month10 + wh.Month11 + wh.Month12 + when 11 then wh.Month11 + wh.Month12 + when 12 then wh.Month12 + else wh.MonthYearly + end + else wh.MonthYearly + end + from [client].[FactWorkingHoursPerMonth] wh + where wh.WorkWeekID = whpm.WorkWeekID + and wh.FiscalYearID = whpm.FiscalYearID + ) rem +where 1=1 + and bc.IsActive=1 +-- CID 1 begin + and ob.OBActivePlans=1 +-- CID 2 end + and + ( + ( + bc.IsProjectionHidden = 1 + and app.MeasureName not like 'Projected%' + ) + or + bc.IsProjectionHidden = 0 + ) +GO + + +--------------------------------------------- + +-- fp.viewServiceLineAdjustmentImport +CREATE VIEW fp.viewServiceLineAdjustmentImport +AS + +SELECT [RowID] + ,[AdjustmentGUID] + ,[EntityID] + ,[PatientClassID] + ,[ServiceLineID] + ,[ServiceLineRollupID] + ,[AgeCohortID] + ,[MedicalSurgicalID] + ,[DepartmentID] + ,[PayorID] + ,[PayorGroupID] + ,[MSDRGID] + ,[CPTID] + ,[ProviderID] + ,[PhysicianSpecialtyID] + ,[FiscalYearID] + ,[FiscalMonthID] + ,[UnitTypeID] + ,[Value] + ,[Version] + ,[TimeClassID] + ,[BudgetPhaseID] + ,[IsRecordDeleted] + ,[AdjustmentID] + FROM [fp].[ServiceLineEncounterAdjustmentImport] + WHERE IsRecordDeleted = 0 +GO + + +--------------------------------------------- + +-- fp.viewServiceLineChargeVolume_aggregate +CREATE VIEW fp.viewServiceLineChargeVolume_aggregate +as + SELECT + sl.EntityID, + dv.DepartmentID, + dv.ChargeCodeID, + --dv.ServiceLineID, + bc.FiscalYearID, + bc.BudgetConfigID, + SUM(sl.TargetAdjusted01 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month01], + SUM(sl.TargetAdjusted02 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month02], + SUM(sl.TargetAdjusted03 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month03], + SUM(sl.TargetAdjusted04 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month04], + SUM(sl.TargetAdjusted05 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month05], + SUM(sl.TargetAdjusted06 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month06], + SUM(sl.TargetAdjusted07 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month07], + SUM(sl.TargetAdjusted08 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month08], + SUM(sl.TargetAdjusted09 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month09], + SUM(sl.TargetAdjusted10 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month10], + SUM(sl.TargetAdjusted11 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month11], + SUM(sl.TargetAdjusted12 * COALESCE(dv.TargetAdjustedTotal / NULLIF(sl.TargetAdjustedTotal, 0), 0)) as [Month12] + FROM + [fp].[ChargeVolume] dv + INNER JOIN [fw].[DimDepartment] dept on dv.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[ServiceLineEncounter] sl + ON dv.BudgetConfigID = sl.BudgetConfigID + AND dv.ServiceLineID = sl.ServiceLineID + AND dv.AgeCohortID = sl.AgeCohortID + AND dv.MedicalSurgicalID = sl.MedicalSurgicalID + AND dv.PatientClassID = sl.PatientClassID + AND dept.EntityID = sl.EntityID + INNER JOIN [fp].[BudgetConfig] bc + ON dv.BudgetConfigID = bc.BudgetConfigID + GROUP BY + sl.EntityID, + dv.DepartmentID, + dv.ChargeCodeID, + --dv.ServiceLineID, + bc.FiscalYearID, + bc.BudgetConfigID +GO + + +--------------------------------------------- + +-- fp.viewServiceLineEncounterAdjustment +CREATE VIEW fp.viewServiceLineEncounterAdjustment +AS + +SELECT [AdjustmentGUID] + ,[BudgetConfigGUID] + ,[AdjustmentType] + ,[Value] + ,[AdjustmentFilterJSON] + ,[GroupingHierarchyJSON] + ,[AdjustedProperty] + ,[Comment] + ,[AuthorGUID] + ,[AuthorFullName] + ,[LastModifiedDateUtc] + ,[DateCreatedUtc] + ,[GroupingGUID] + ,[TimeClassID] + ,[BudgetPhaseID] + ,[ClassificationGroupID] + ,[ClassificationCategoryID] + ,[IsRecordDeleted] + ,[DimensionMemberJson] + ,[AdjustmentID] + ,[IsErrored] + FROM [fp].[ServiceLineEncounterAdjustment] + WHERE IsRecordDeleted = 0; +GO + + +--------------------------------------------- + +-- fp.viewServiceLineEncounterAdjustmentImport_Pivoted +CREATE VIEW fp.viewServiceLineEncounterAdjustmentImport_Pivoted +AS +SELECT + AdjustmentGUID, + DepartmentID, + EntityID, + PatientClassID, + ServiceLineID, + ServiceLineRollupID, + AgeCohortID, + MedicalSurgicalID, + PayorID, + PayorGroupID, + MSDRGID, + CPTID, + ProviderID, + PhysicianSpecialtyID, + UnitTypeID, + TimeClassID, + BudgetPhaseID, + IsRecordDeleted, + AdjustmentID, + [Month01], + [Month02], + [Month03], + [Month04], + [Month05], + [Month06], + [Month07], + [Month08], + [Month09], + [Month10], + [Month11], + [Month12] +FROM + ( + SELECT + AdjustmentGUID, + DepartmentID, + EntityID, + PatientClassID, + ServiceLineID, + ServiceLineRollupID, + AgeCohortID, + MedicalSurgicalID, + PayorID, + PayorGroupID, + MSDRGID, + CPTID, + ProviderID, + PhysicianSpecialtyID, + UnitTypeID, + TimeClassID, + BudgetPhaseID, + IsRecordDeleted, + AdjustmentID, + m.MonthColumnName, + Value + FROM fp.ServiceLineEncounterAdjustmentImport imp + INNER JOIN fw.DimFiscalMonth m ON m.FiscalMonthID = imp.FiscalMonthID + ) data + PIVOT (SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pvt +WHERE IsRecordDeleted = 0 +GO + + +--------------------------------------------- + +-- fp.viewServiceLineEncounterChangeHistoryWithRollUpDetail +CREATE VIEW fp.viewServiceLineEncounterChangeHistoryWithRollUpDetail +AS + SELECT slech.RowID, slech.ServiceLineEncounterID, slech.AdjustmentGUID, slech.GroupingGUID, slech.AdjustmentType, slech.FiscalMonthID, slech.UnitTypeID, slech.TimeClassID, slech.BudgetPhaseID, slech.OldValue, slech.NewValue, slech.BudgetConfigID, slech.DateCreatedUTC, slea.DateCreatedUTC AS AdjustmentDateCreatedUTC, + slea.GroupingGUID AS AdjustmentGroupingGUID, CASE WHEN slea.AdjustmentType IN (0, 2, 3) AND slea.GroupingGUID != '00000000-0000-0000-0000-000000000000' THEN slea2.AdjustmentGUID ELSE slea.AdjustmentGUID END ReportingAdjustmentGUID + FROM fp.ServiceLineEncounterChangeHistory slech + INNER JOIN fp.ServiceLineEncounterAdjustment slea ON slech.AdjustmentGUID = slea.AdjustmentGUID + LEFT JOIN fp.ServiceLineEncounterAdjustment slea2 ON slea.GroupingGUID = slea2.GroupingGUID AND slea.GroupingGUID != '00000000-0000-0000-0000-000000000000' AND slea2.AdjustmentType IN (12, 13, 14) +GO + + +--------------------------------------------- + +-- fp.viewServiceLineEncounterChangeHistory_Pivoted +CREATE VIEW fp.viewServiceLineEncounterChangeHistory_Pivoted + AS +WITH months AS +( + SELECT + FiscalMonthID, + REPLACE(MonthColumnName, 'Month', 'OldValue') AS OldMonthColumnName, + REPLACE(MonthColumnName, 'Month', 'NewValue') AS NewMonthColumnName + FROM fw.DimFiscalMonth +) +SELECT + ServiceLineEncounterID, + AdjustmentGUID, + UnitTypeID, + TimeClassID , + BudgetPhaseID , + BudgetConfigID , + AdjustmentType , + SUM(pvt2.OldValue01) AS OldValue01, + SUM(pvt2.OldValue02) AS OldValue02, + SUM(pvt2.OldValue03) AS OldValue03, + SUM(pvt2.OldValue04) AS OldValue04, + SUM(pvt2.OldValue05) AS OldValue05, + SUM(pvt2.OldValue06) AS OldValue06, + SUM(pvt2.OldValue07) AS OldValue07, + SUM(pvt2.OldValue08) AS OldValue08, + SUM(pvt2.OldValue09) AS OldValue09, + SUM(pvt2.OldValue10) AS OldValue10, + SUM(pvt2.OldValue11) AS OldValue11, + SUM(pvt2.OldValue12) AS OldValue12, + SUM(pvt2.NewValue01) AS NewValue01, + SUM(pvt2.NewValue02) AS NewValue02, + SUM(pvt2.NewValue03) AS NewValue03, + SUM(pvt2.NewValue04) AS NewValue04, + SUM(pvt2.NewValue05) AS NewValue05, + SUM(pvt2.NewValue06) AS NewValue06, + SUM(pvt2.NewValue07) AS NewValue07, + SUM(pvt2.NewValue08) AS NewValue08, + SUM(pvt2.NewValue09) AS NewValue09, + SUM(pvt2.NewValue10) AS NewValue10, + SUM(pvt2.NewValue11) AS NewValue11, + SUM(pvt2.NewValue12) AS NewValue12 +FROM + ( + SELECT + ServiceLineEncounterID, + AdjustmentGUID, + AdjustmentType, + UnitTypeID, + TimeClassID , + BudgetPhaseID , + BudgetConfigID , + m.OldMonthColumnName, + m.NewMonthColumnName, + OldValue, + NewValue + FROM fp.ServiceLineEncounterChangeHistory ch + INNER JOIN months m ON m.FiscalMonthID = ch.FiscalMonthID + ) data + PIVOT (SUM(OldValue) for OldMonthColumnName in ([OldValue01],[OldValue02],[OldValue03],[OldValue04],[OldValue05],[OldValue06],[OldValue07],[OldValue08],[OldValue09],[OldValue10],[OldValue11],[OldValue12])) as pvt + PIVOT (SUM(NewValue) for NewMonthColumnName in ([NewValue01],[NewValue02],[NewValue03],[NewValue04],[NewValue05],[NewValue06],[NewValue07],[NewValue08],[NewValue09],[NewValue10],[NewValue11],[NewValue12])) as pvt2 +GROUP BY + ServiceLineEncounterID, + AdjustmentGUID, + UnitTypeID, + TimeClassID, + BudgetPhaseID, + BudgetConfigID, + AdjustmentType; +GO + + +--------------------------------------------- + +-- fp.viewServiceLineEncounterPayorGroupMix_Pivoted +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 6-27-2023 MY JAZZ-56923 Adding Service Line into the SLE to Charge payor mix calc +*************************************************************/ +CREATE VIEW fp.viewServiceLineEncounterPayorGroupMix_Pivoted + AS + SELECT budg.BudgetConfigID, budg.EntityGroupConfigID, budg.EntityID, budg.PatientClassID, budg.ServiceLineID, budg.PayorGroupID, + budg.MixPercentage AS BudgetMixPercentage, + proj.MixPercentage AS ProjectionMixPercentage, + budg.InitialMixPercentage AS InitialBudgetMixPercentage, + proj.InitialMixPercentage AS InitialProjectionMixPercentage + FROM fp.ServiceLineEncounterPayorGroupMix budg + INNER JOIN fp.ServiceLineEncounterPayorGroupMix proj ON + budg.BudgetConfigID = proj.BudgetConfigID + AND budg.EntityGroupConfigID = proj.EntityGroupConfigID + AND budg.EntityID = proj.EntityID + AND budg.PatientClassID = proj.PatientClassID + AND budg.ServiceLineID = proj.ServiceLineID + AND budg.PayorGroupID = proj.PayorGroupID + WHERE budg.TimeClassID = 2 + AND proj.TimeClassID = 12 +GO + + +--------------------------------------------- + +-- fp.viewServiceLineEncounterSpreads +CREATE VIEW [fp].[viewServiceLineEncounterSpreads] +AS + SELECT [BudgetConfigID], [EntityID], [ServiceLineID], [PatientClassID], [IsInactive], [SpreadPercentage01], [SpreadPercentage02], [SpreadPercentage03], [SpreadPercentage04], [SpreadPercentage05], [SpreadPercentage06], [SpreadPercentage07], [SpreadPercentage08], [SpreadPercentage09], [SpreadPercentage10], [SpreadPercentage11], [SpreadPercentage12], [TotalImportedValue] as TotalSpreadValue, [GlobalSpreadID] + FROM [fp].[ServiceLineEncounterSpreads] with (readuncommitted) + WHERE GlobalSpreadID = 1 + + UNION ALL + + SELECT bs.[BudgetConfigID], [EntityID], [ServiceLineID], [PatientClassID], [IsInactive], gs.[SpreadPercentage01], gs.[SpreadPercentage02], gs.[SpreadPercentage03], gs.[SpreadPercentage04], gs.[SpreadPercentage05], gs.[SpreadPercentage06], gs.[SpreadPercentage07], gs.[SpreadPercentage08], gs.[SpreadPercentage09], gs.[SpreadPercentage10], gs.[SpreadPercentage11], gs.[SpreadPercentage12], gs.TotalSpreadValue, bs.[GlobalSpreadID] + FROM [fp].[ServiceLineEncounterSpreads] bs with (readuncommitted) + INNER JOIN [fp].[GlobalSpread] gs ON bs.GlobalSpreadID = gs.GlobalSpreadID + WHERE bs.GlobalSpreadID > 1 +GO + + +--------------------------------------------- + +-- fp.viewServiceLineEncounter_AllTotals +CREATE VIEW [fp].[viewServiceLineEncounter_AllTotals] +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-01-16 BK JAZZ-48267 Create view for totals only + *************************************************************/ +SELECT + sl.ServiceLineEncounterID, + sl.BudgetConfigID, + sl.EntityGroupConfigID, + sl.EntityID, + sl.PatientClassID, + sl.ServiceLineID, + sl.ServiceLineRollupID, + sl.AgeCohortID, + sl.MedicalSurgicalID, + sl.DepartmentID, + sl.PayorID, + sl.PayorGroupID, + sl.MSDRGID, + sl.CPTID, + sl.ProviderID, + sl.PhysicianSpecialtyID, + sl.UnitTypeID, + + sl.TargetLockType as TargetLockType, + sl.TargetLockFlag as TargetLockFlag, + sl.BudgetLockType as BudgetLockType, + sl.BudgetLockFlag as BudgetLockFlag, + sl.ProjectionLockType AS ProjectionLockType, + sl.ProjectionLockFlag AS ProjectionLockFlag, + + CASE WHEN sl.TargetLockType = 6 THEN 1 ELSE 0 END AS TargetSpreadsLockFlag, + + sl.TargetAdjustedTotal as AdjustedTotal, + sl.BudgetAdjustedTotal as ManagerAdjustedTotal, + sl.ProjectionAdjustedTotal as AdjustedProjectionTotal, + + hist.PriorYearActualValueTotal as PriorYearActualValueTotal, + hist.ActualYTDValueTotal as ActualYTDValueTotal, + hist.CurrentYearBudgetTotal as CurrentYearBudgetTotal, + + sl.SampledBudgetTotal, + sl.InitialBudgetTotal, + sl.InitialProjectionTotal, + + sl.TargetAdjusted01 as Adjusted01, + sl.TargetAdjusted02 as Adjusted02, + sl.TargetAdjusted03 as Adjusted03, + sl.TargetAdjusted04 as Adjusted04, + sl.TargetAdjusted05 as Adjusted05, + sl.TargetAdjusted06 as Adjusted06, + sl.TargetAdjusted07 as Adjusted07, + sl.TargetAdjusted08 as Adjusted08, + sl.TargetAdjusted09 as Adjusted09, + sl.TargetAdjusted10 as Adjusted10, + sl.TargetAdjusted11 as Adjusted11, + sl.TargetAdjusted12 as Adjusted12, + + sl.BudgetAdjusted01 AS ManagerAdjusted01, + sl.BudgetAdjusted02 AS ManagerAdjusted02, + sl.BudgetAdjusted03 AS ManagerAdjusted03, + sl.BudgetAdjusted04 AS ManagerAdjusted04, + sl.BudgetAdjusted05 AS ManagerAdjusted05, + sl.BudgetAdjusted06 AS ManagerAdjusted06, + sl.BudgetAdjusted07 AS ManagerAdjusted07, + sl.BudgetAdjusted08 AS ManagerAdjusted08, + sl.BudgetAdjusted09 AS ManagerAdjusted09, + sl.BudgetAdjusted10 AS ManagerAdjusted10, + sl.BudgetAdjusted11 AS ManagerAdjusted11, + sl.BudgetAdjusted12 AS ManagerAdjusted12, + + sl.ProjectionAdjusted01 AS AdjustedProjection01, + sl.ProjectionAdjusted02 AS AdjustedProjection02, + sl.ProjectionAdjusted03 AS AdjustedProjection03, + sl.ProjectionAdjusted04 AS AdjustedProjection04, + sl.ProjectionAdjusted05 AS AdjustedProjection05, + sl.ProjectionAdjusted06 AS AdjustedProjection06, + sl.ProjectionAdjusted07 AS AdjustedProjection07, + sl.ProjectionAdjusted08 AS AdjustedProjection08, + sl.ProjectionAdjusted09 AS AdjustedProjection09, + sl.ProjectionAdjusted10 AS AdjustedProjection10, + sl.ProjectionAdjusted11 AS AdjustedProjection11, + sl.ProjectionAdjusted12 AS AdjustedProjection12 + +From fp.ServiceLineEncounter sl + INNER JOIN fp.ServiceLineEncounterHistory hist with (readuncommitted) ON sl.ServiceLineEncounterID = hist.ServiceLineEncounterID +GO + + +--------------------------------------------- + +-- fp.viewServiceLineEncounter_BudgetAdjusted +CREATE VIEW [fp].[viewServiceLineEncounter_BudgetAdjusted] +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-01-16 BK JAZZ-48267 Create view for budget adjusted only + *************************************************************/ +SELECT + sl.ServiceLineEncounterID, + sl.BudgetConfigID, + sl.EntityGroupConfigID, + sl.EntityID, + sl.PatientClassID, + sl.ServiceLineID, + sl.ServiceLineRollupID, + sl.AgeCohortID, + sl.MedicalSurgicalID, + sl.DepartmentID, + sl.PayorID, + sl.PayorGroupID, + sl.MSDRGID, + sl.CPTID, + sl.ProviderID, + sl.PhysicianSpecialtyID, + sl.UnitTypeID, + + sl.BudgetAdjustedTotal, + sl.BudgetAdjusted01, + sl.BudgetAdjusted02, + sl.BudgetAdjusted03, + sl.BudgetAdjusted04, + sl.BudgetAdjusted05, + sl.BudgetAdjusted06, + sl.BudgetAdjusted07, + sl.BudgetAdjusted08, + sl.BudgetAdjusted09, + sl.BudgetAdjusted10, + sl.BudgetAdjusted11, + sl.BudgetAdjusted12 + + +From fp.ServiceLineEncounter sl + INNER JOIN fp.ServiceLineEncounterHistory hist with (readuncommitted) ON sl.ServiceLineEncounterID = hist.ServiceLineEncounterID +GO + + +--------------------------------------------- + +-- fp.viewServiceLineEncounter_InitialBudget +CREATE VIEW [fp].[viewServiceLineEncounter_InitialBudget] +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-01-16 BK JAZZ-48267 Create view for inital budget only + *************************************************************/ +SELECT + sl.ServiceLineEncounterID, + sl.BudgetConfigID, + sl.EntityGroupConfigID, + sl.EntityID, + sl.PatientClassID, + sl.ServiceLineID, + sl.ServiceLineRollupID, + sl.AgeCohortID, + sl.MedicalSurgicalID, + sl.DepartmentID, + sl.PayorID, + sl.PayorGroupID, + sl.MSDRGID, + sl.CPTID, + sl.ProviderID, + sl.PhysicianSpecialtyID, + sl.UnitTypeID, + + sl.InitialBudgetTotal, + + sl.InitialBudget01, + sl.InitialBudget02, + sl.InitialBudget03, + sl.InitialBudget04, + sl.InitialBudget05, + sl.InitialBudget06, + sl.InitialBudget07, + sl.InitialBudget08, + sl.InitialBudget09, + sl.InitialBudget10, + sl.InitialBudget11, + sl.InitialBudget12 + + +From fp.ServiceLineEncounter sl + INNER JOIN fp.ServiceLineEncounterHistory hist with (readuncommitted) ON sl.ServiceLineEncounterID = hist.ServiceLineEncounterID +GO + + +--------------------------------------------- + +-- fp.viewServiceLineEncounter_InitialProjection +CREATE VIEW [fp].[viewServiceLineEncounter_InitialProjection] +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-01-16 BK JAZZ-48267 Create view for inital projection only + *************************************************************/ +SELECT + sl.ServiceLineEncounterID, + sl.BudgetConfigID, + sl.EntityGroupConfigID, + sl.EntityID, + sl.PatientClassID, + sl.ServiceLineID, + sl.ServiceLineRollupID, + sl.AgeCohortID, + sl.MedicalSurgicalID, + sl.DepartmentID, + sl.PayorID, + sl.PayorGroupID, + sl.MSDRGID, + sl.CPTID, + sl.ProviderID, + sl.PhysicianSpecialtyID, + sl.UnitTypeID, + + sl.InitialProjectionTotal, + + sl.InitialProjection01, + sl.InitialProjection02, + sl.InitialProjection03, + sl.InitialProjection04, + sl.InitialProjection05, + sl.InitialProjection06, + sl.InitialProjection07, + sl.InitialProjection08, + sl.InitialProjection09, + sl.InitialProjection10, + sl.InitialProjection11, + sl.InitialProjection12 + + +From fp.ServiceLineEncounter sl + INNER JOIN fp.ServiceLineEncounterHistory hist with (readuncommitted) ON sl.ServiceLineEncounterID = hist.ServiceLineEncounterID +GO + + +--------------------------------------------- + +-- fp.viewServiceLineEncounter_ProjectionAdjusted +CREATE VIEW [fp].[viewServiceLineEncounter_ProjectionAdjusted] +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-01-16 BK JAZZ-48267 Create view for projection adjusted only + *************************************************************/ +SELECT + sl.ServiceLineEncounterID, + sl.BudgetConfigID, + sl.EntityGroupConfigID, + sl.EntityID, + sl.PatientClassID, + sl.ServiceLineID, + sl.ServiceLineRollupID, + sl.AgeCohortID, + sl.MedicalSurgicalID, + sl.DepartmentID, + sl.PayorID, + sl.PayorGroupID, + sl.MSDRGID, + sl.CPTID, + sl.ProviderID, + sl.PhysicianSpecialtyID, + sl.UnitTypeID, + + sl.ProjectionAdjustedTotal, + sl.ProjectionAdjusted01, + sl.ProjectionAdjusted02, + sl.ProjectionAdjusted03, + sl.ProjectionAdjusted04, + sl.ProjectionAdjusted05, + sl.ProjectionAdjusted06, + sl.ProjectionAdjusted07, + sl.ProjectionAdjusted08, + sl.ProjectionAdjusted09, + sl.ProjectionAdjusted10, + sl.ProjectionAdjusted11, + sl.ProjectionAdjusted12 + + +FROM fp.ServiceLineEncounter sl + INNER JOIN fp.ServiceLineEncounterHistory hist with (readuncommitted) ON sl.ServiceLineEncounterID = hist.ServiceLineEncounterID +GO + + +--------------------------------------------- + +-- fp.viewServiceLineEncounter_TargetAdjusted +CREATE VIEW [fp].[viewServiceLineEncounter_TargetAdjusted] +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-01-16 BK JAZZ-48267 Create view for target adjusted only + *************************************************************/ +SELECT + sl.ServiceLineEncounterID, + sl.BudgetConfigID, + sl.EntityGroupConfigID, + sl.EntityID, + sl.PatientClassID, + sl.ServiceLineID, + sl.ServiceLineRollupID, + sl.AgeCohortID, + sl.MedicalSurgicalID, + sl.DepartmentID, + sl.PayorID, + sl.PayorGroupID, + sl.MSDRGID, + sl.CPTID, + sl.ProviderID, + sl.PhysicianSpecialtyID, + sl.UnitTypeID, + + sl.TargetAdjustedTotal, + + sl.TargetAdjusted01, + sl.TargetAdjusted02, + sl.TargetAdjusted03, + sl.TargetAdjusted04, + sl.TargetAdjusted05, + sl.TargetAdjusted06, + sl.TargetAdjusted07, + sl.TargetAdjusted08, + sl.TargetAdjusted09, + sl.TargetAdjusted10, + sl.TargetAdjusted11, + sl.TargetAdjusted12 + + +From fp.ServiceLineEncounter sl + INNER JOIN fp.ServiceLineEncounterHistory hist with (readuncommitted) ON sl.ServiceLineEncounterID = hist.ServiceLineEncounterID +GO + + +--------------------------------------------- + +-- fp.viewServiceLineEncountersSpreadUnlockData +CREATE VIEW [fp].[viewServiceLineEncountersSpreadUnlockData] +AS +SELECT sud.[RowID] + ,sud.[BudgetConfigID] + ,sud.[AdjustmentGUID] + ,sud.[EntityID] + ,sud.[PatientClassID] + ,sud.[ServiceLineID] + ,sud.[ServiceLineRollupID] + ,sud.[AgeCohortID] + ,sud.[MedicalSurgicalID] + ,sud.[DepartmentID] + ,sud.[PayorID] + ,sud.[PayorGroupID] + ,sud.[MSDRGID] + ,sud.[CPTID] + ,sud.[ProviderID] + ,sud.[PhysicianSpecialtyID] + ,sud.[Version] + ,sud.[Value01] + ,sud.[Value02] + ,sud.[Value03] + ,sud.[Value04] + ,sud.[Value05] + ,sud.[Value06] + ,sud.[Value07] + ,sud.[Value08] + ,sud.[Value09] + ,sud.[Value10] + ,sud.[Value11] + ,sud.[Value12] + ,sud.[IsRecordDeleted] + ,adj.[BudgetPhaseID] + FROM [fp].[ServiceLineEncountersSpreadUnlockData] sud + INNER JOIN [fp].[ServiceLineEncounterAdjustment] adj ON adj.[AdjustmentGUID] = sud.[AdjustmentGUID] + WHERE sud.IsRecordDeleted = 0 +GO + + +--------------------------------------------- + +-- fp.viewSpreadsStatsFlexedByChargeVolume +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 5-18-2023 MY JAZZ-54812 Updated view to restructure +*************************************************************/ +CREATE VIEW fp.viewSpreadsStatsFlexedByChargeVolume +AS +SELECT + BudgetConfigID, + EntityGroupConfigID, + DepartmentID, + AccountID, + SpreadPercentage01, + SpreadPercentage02, + SpreadPercentage03, + SpreadPercentage04, + SpreadPercentage05, + SpreadPercentage06, + SpreadPercentage07, + SpreadPercentage08, + SpreadPercentage09, + SpreadPercentage10, + SpreadPercentage11, + 1 - (SpreadPercentage01 + SpreadPercentage02 + SpreadPercentage03 + SpreadPercentage04 + SpreadPercentage05 + SpreadPercentage06 + SpreadPercentage07 + SpreadPercentage08 + SpreadPercentage09 + SpreadPercentage10 + SpreadPercentage11) AS SpreadPercentage12 +FROM ( + SELECT + cv.BudgetConfigID, + cts.EntityGroupConfigID, + cts.DepartmentID, + cts.AccountID, + CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted01) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage01, + CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted02) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage02, + CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted03) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage03, + CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted04) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage04, + CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted05) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage05, + CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted06) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage06, + CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted07) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage07, + CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted08) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage08, + CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted09) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage09, + CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted10) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage10, + CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted11) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage11, + CASE WHEN SUM(cv.BudgetAdjustedTotal) = 0 THEN 0 ELSE CAST(SUM(cv.BudgetAdjusted12) AS DECIMAL(19, 8)) / CAST(SUM(cv.BudgetAdjustedTotal) AS DECIMAL(19, 8)) END as SpreadPercentage12 + FROM fp.ChargeVolume cv + INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] cts + ON cv.EntityGroupConfigID = cts.EntityGroupConfigID + AND cv.DepartmentID = cts.DepartmentID + AND cv.ChargeCodeID = cts.ChargeCodeID + AND cv.PatientClassID = cts.PatientClassID + WHERE + cv.UnitTypeID = 145 + GROUP BY + cv.BudgetConfigID, + cts.EntityGroupConfigID, + cts.DepartmentID, + cts.AccountID + ) data +GO + + +--------------------------------------------- + +-- fp.viewStaffing +CREATE VIEW [fp].[viewStaffing] +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-09-23 BW JAZZ-60740 Replacement for [fp].[viewFactStaffing_Pivoted], new data structure + *************************************************************/ + + SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.ProductiveClassID, + fs.VariabilityID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.SubsectionID, + fs.FlexingTypeID, + +-- Dollars + fs.TargetDollarsLockType, + fs.TargetDollarsLockFlag, + fs.BudgetDollarsLockType, + fs.BudgetDollarsLockFlag, + fs.ProjectionDollarsLockType, + fs.ProjectionDollarsLockFlag, + + CASE WHEN fs.BudgetDollarsLockType = 6 THEN 1 ELSE 0 END AS BudgetDollarsSpreadsLockFlag, + + CASE WHEN fs.BudgetDollarsLockType = 7 THEN 1 ELSE 0 END AS BudgetDollarsAdjustmentLockFlag, + CASE WHEN fs.TargetDollarsLockType = 7 THEN 1 ELSE 0 END AS TargetDollarsAdjustmentLockFlag, + CASE WHEN fs.ProjectionDollarsLockType = 7 THEN 1 ELSE 0 END AS ProjectionDollarsAdjustmentLockFlag, + + fs.TargetAdjustedDollarsTotal, + fs.BudgetAdjustedDollarsTotal, + fs.ProjectionAdjustedDollarsTotal, + + hist.ActualYTDDollarsTotal, + hist.CurrentYearBudgetDollarsTotal, + hist.PriorYearActualDollarsTotal, + + fs.InitialBudgetDollarsTotal, + fs.InitialBudgetDollars01, + fs.InitialBudgetDollars02, + fs.InitialBudgetDollars03, + fs.InitialBudgetDollars04, + fs.InitialBudgetDollars05, + fs.InitialBudgetDollars06, + fs.InitialBudgetDollars07, + fs.InitialBudgetDollars08, + fs.InitialBudgetDollars09, + fs.InitialBudgetDollars10, + fs.InitialBudgetDollars11, + fs.InitialBudgetDollars12, + + fs.InitialProjectionDollarsTotal, + + CASE WHEN fs.FlexingTypeID IN (3, 9) THEN 1 ELSE 0 END AS IsFlexedByStats, + + -- Target Montly Values + fs.TargetAdjustedDollars01, + fs.TargetAdjustedDollars02, + fs.TargetAdjustedDollars03, + fs.TargetAdjustedDollars04, + fs.TargetAdjustedDollars05, + fs.TargetAdjustedDollars06, + fs.TargetAdjustedDollars07, + fs.TargetAdjustedDollars08, + fs.TargetAdjustedDollars09, + fs.TargetAdjustedDollars10, + fs.TargetAdjustedDollars11, + fs.TargetAdjustedDollars12, + + -- Budgeted Monthly Values + fs.BudgetAdjustedDollars01, + fs.BudgetAdjustedDollars02, + fs.BudgetAdjustedDollars03, + fs.BudgetAdjustedDollars04, + fs.BudgetAdjustedDollars05, + fs.BudgetAdjustedDollars06, + fs.BudgetAdjustedDollars07, + fs.BudgetAdjustedDollars08, + fs.BudgetAdjustedDollars09, + fs.BudgetAdjustedDollars10, + fs.BudgetAdjustedDollars11, + fs.BudgetAdjustedDollars12, + + -- Projected Monthly Values + fs.ProjectionAdjustedDollars01, + fs.ProjectionAdjustedDollars02, + fs.ProjectionAdjustedDollars03, + fs.ProjectionAdjustedDollars04, + fs.ProjectionAdjustedDollars05, + fs.ProjectionAdjustedDollars06, + fs.ProjectionAdjustedDollars07, + fs.ProjectionAdjustedDollars08, + fs.ProjectionAdjustedDollars09, + fs.ProjectionAdjustedDollars10, + fs.ProjectionAdjustedDollars11, + fs.ProjectionAdjustedDollars12, + +-- Hours + fs.TargetHoursLockType, + fs.TargetHoursLockFlag, + fs.BudgetHoursLockType, + fs.BudgetHoursLockFlag, + fs.ProjectionHoursLockType, + fs.ProjectionHoursLockFlag, + + CASE WHEN fs.BudgetHoursLockType = 6 THEN 1 ELSE 0 END AS BudgetHoursSpreadsLockFlag, + + CASE WHEN fs.BudgetHoursLockType = 7 THEN 1 ELSE 0 END AS BudgetHoursAdjustmentLockFlag, + CASE WHEN fs.TargetHoursLockType = 7 THEN 1 ELSE 0 END AS TargetHoursAdjustmentLockFlag, + CASE WHEN fs.ProjectionHoursLockType = 7 THEN 1 ELSE 0 END AS ProjectionHoursAdjustmentLockFlag, + + fs.TargetAdjustedHoursTotal, + fs.BudgetAdjustedHoursTotal, + fs.ProjectionAdjustedHoursTotal, + + hist.ActualYTDHoursTotal, + hist.CurrentYearBudgetHoursTotal, + hist.PriorYearActualHoursTotal, + + fs.InitialBudgetHoursTotal, + fs.InitialBudgetHours01, + fs.InitialBudgetHours02, + fs.InitialBudgetHours03, + fs.InitialBudgetHours04, + fs.InitialBudgetHours05, + fs.InitialBudgetHours06, + fs.InitialBudgetHours07, + fs.InitialBudgetHours08, + fs.InitialBudgetHours09, + fs.InitialBudgetHours10, + fs.InitialBudgetHours11, + fs.InitialBudgetHours12, + + fs.InitialProjectionHoursTotal, + + -- Target Montly Values + fs.TargetAdjustedHours01, + fs.TargetAdjustedHours02, + fs.TargetAdjustedHours03, + fs.TargetAdjustedHours04, + fs.TargetAdjustedHours05, + fs.TargetAdjustedHours06, + fs.TargetAdjustedHours07, + fs.TargetAdjustedHours08, + fs.TargetAdjustedHours09, + fs.TargetAdjustedHours10, + fs.TargetAdjustedHours11, + fs.TargetAdjustedHours12, + + -- Budgeted Monthly Values + fs.BudgetAdjustedHours01, + fs.BudgetAdjustedHours02, + fs.BudgetAdjustedHours03, + fs.BudgetAdjustedHours04, + fs.BudgetAdjustedHours05, + fs.BudgetAdjustedHours06, + fs.BudgetAdjustedHours07, + fs.BudgetAdjustedHours08, + fs.BudgetAdjustedHours09, + fs.BudgetAdjustedHours10, + fs.BudgetAdjustedHours11, + fs.BudgetAdjustedHours12, + + -- Projected Monthly Values + fs.ProjectionAdjustedHours01, + fs.ProjectionAdjustedHours02, + fs.ProjectionAdjustedHours03, + fs.ProjectionAdjustedHours04, + fs.ProjectionAdjustedHours05, + fs.ProjectionAdjustedHours06, + fs.ProjectionAdjustedHours07, + fs.ProjectionAdjustedHours08, + fs.ProjectionAdjustedHours09, + fs.ProjectionAdjustedHours10, + fs.ProjectionAdjustedHours11, + fs.ProjectionAdjustedHours12, + +-- FTEs + fs.TargetFTEsLockType, + fs.TargetFTEsLockFlag, + fs.BudgetFTEsLockType, + fs.BudgetFTEsLockFlag, + fs.ProjectionFTEsLockType, + fs.ProjectionFTEsLockFlag, + + CASE WHEN fs.BudgetFTEsLockType = 6 THEN 1 ELSE 0 END AS BudgetFTEsSpreadsLockFlag, + + CASE WHEN fs.BudgetFTEsLockType = 7 THEN 1 ELSE 0 END AS BudgetFTEsAdjustmentLockFlag, + CASE WHEN fs.TargetFTEsLockType = 7 THEN 1 ELSE 0 END AS TargetFTEsAdjustmentLockFlag, + CASE WHEN fs.ProjectionFTEsLockType = 7 THEN 1 ELSE 0 END AS ProjectionFTEsAdjustmentLockFlag, + + hist.ActualYTDFTEsTotal, + hist.CurrentYearBudgetFTEsTotal, + hist.PriorYearActualFTEsTotal, + + fs.InitialBudgetFTEs01, + fs.InitialBudgetFTEs02, + fs.InitialBudgetFTEs03, + fs.InitialBudgetFTEs04, + fs.InitialBudgetFTEs05, + fs.InitialBudgetFTEs06, + fs.InitialBudgetFTEs07, + fs.InitialBudgetFTEs08, + fs.InitialBudgetFTEs09, + fs.InitialBudgetFTEs10, + fs.InitialBudgetFTEs11, + fs.InitialBudgetFTEs12, + + -- Target Montly Values + fs.TargetAdjustedFTEs01, + fs.TargetAdjustedFTEs02, + fs.TargetAdjustedFTEs03, + fs.TargetAdjustedFTEs04, + fs.TargetAdjustedFTEs05, + fs.TargetAdjustedFTEs06, + fs.TargetAdjustedFTEs07, + fs.TargetAdjustedFTEs08, + fs.TargetAdjustedFTEs09, + fs.TargetAdjustedFTEs10, + fs.TargetAdjustedFTEs11, + fs.TargetAdjustedFTEs12, + + -- Budgeted Monthly Values + fs.BudgetAdjustedFTEs01, + fs.BudgetAdjustedFTEs02, + fs.BudgetAdjustedFTEs03, + fs.BudgetAdjustedFTEs04, + fs.BudgetAdjustedFTEs05, + fs.BudgetAdjustedFTEs06, + fs.BudgetAdjustedFTEs07, + fs.BudgetAdjustedFTEs08, + fs.BudgetAdjustedFTEs09, + fs.BudgetAdjustedFTEs10, + fs.BudgetAdjustedFTEs11, + fs.BudgetAdjustedFTEs12, + + -- Projected Monthly Values + fs.ProjectionAdjustedFTEs01, + fs.ProjectionAdjustedFTEs02, + fs.ProjectionAdjustedFTEs03, + fs.ProjectionAdjustedFTEs04, + fs.ProjectionAdjustedFTEs05, + fs.ProjectionAdjustedFTEs06, + fs.ProjectionAdjustedFTEs07, + fs.ProjectionAdjustedFTEs08, + fs.ProjectionAdjustedFTEs09, + fs.ProjectionAdjustedFTEs10, + fs.ProjectionAdjustedFTEs11, + fs.ProjectionAdjustedFTEs12, + +-- Rates + fs.InitialBudgetRate01, + fs.InitialBudgetRate02, + fs.InitialBudgetRate03, + fs.InitialBudgetRate04, + fs.InitialBudgetRate05, + fs.InitialBudgetRate06, + fs.InitialBudgetRate07, + fs.InitialBudgetRate08, + fs.InitialBudgetRate09, + fs.InitialBudgetRate10, + fs.InitialBudgetRate11, + fs.InitialBudgetRate12, + + -- Target Montly Values + fs.TargetAdjustedRate01, + fs.TargetAdjustedRate02, + fs.TargetAdjustedRate03, + fs.TargetAdjustedRate04, + fs.TargetAdjustedRate05, + fs.TargetAdjustedRate06, + fs.TargetAdjustedRate07, + fs.TargetAdjustedRate08, + fs.TargetAdjustedRate09, + fs.TargetAdjustedRate10, + fs.TargetAdjustedRate11, + fs.TargetAdjustedRate12, + + -- Budgeted Monthly Values + fs.BudgetAdjustedRate01, + fs.BudgetAdjustedRate02, + fs.BudgetAdjustedRate03, + fs.BudgetAdjustedRate04, + fs.BudgetAdjustedRate05, + fs.BudgetAdjustedRate06, + fs.BudgetAdjustedRate07, + fs.BudgetAdjustedRate08, + fs.BudgetAdjustedRate09, + fs.BudgetAdjustedRate10, + fs.BudgetAdjustedRate11, + fs.BudgetAdjustedRate12, + + -- Projected Monthly Values + fs.ProjectionAdjustedRate01, + fs.ProjectionAdjustedRate02, + fs.ProjectionAdjustedRate03, + fs.ProjectionAdjustedRate04, + fs.ProjectionAdjustedRate05, + fs.ProjectionAdjustedRate06, + fs.ProjectionAdjustedRate07, + fs.ProjectionAdjustedRate08, + fs.ProjectionAdjustedRate09, + fs.ProjectionAdjustedRate10, + fs.ProjectionAdjustedRate11, + fs.ProjectionAdjustedRate12, + +-- Wage Rate + wr.TargetWageRateLockType, + wr.TargetWageRateLockFlag, + wr.BudgetWageRateLockType, + wr.BudgetWageRateLockFlag, + wr.ProjectionWageRateLockType, + wr.ProjectionWageRateLockFlag, + + wr.InitialBudget01 AS InitialBudgetWageRate01, + wr.InitialBudget02 AS InitialBudgetWageRate02, + wr.InitialBudget03 AS InitialBudgetWageRate03, + wr.InitialBudget04 AS InitialBudgetWageRate04, + wr.InitialBudget05 AS InitialBudgetWageRate05, + wr.InitialBudget06 AS InitialBudgetWageRate06, + wr.InitialBudget07 AS InitialBudgetWageRate07, + wr.InitialBudget08 AS InitialBudgetWageRate08, + wr.InitialBudget09 AS InitialBudgetWageRate09, + wr.InitialBudget10 AS InitialBudgetWageRate10, + wr.InitialBudget11 AS InitialBudgetWageRate11, + wr.InitialBudget12 AS InitialBudgetWageRate12, + + -- Target Montly Values + wr.TargetAdjusted01 AS TargetAdjustedWageRate01, + wr.TargetAdjusted02 AS TargetAdjustedWageRate02, + wr.TargetAdjusted03 AS TargetAdjustedWageRate03, + wr.TargetAdjusted04 AS TargetAdjustedWageRate04, + wr.TargetAdjusted05 AS TargetAdjustedWageRate05, + wr.TargetAdjusted06 AS TargetAdjustedWageRate06, + wr.TargetAdjusted07 AS TargetAdjustedWageRate07, + wr.TargetAdjusted08 AS TargetAdjustedWageRate08, + wr.TargetAdjusted09 AS TargetAdjustedWageRate09, + wr.TargetAdjusted10 AS TargetAdjustedWageRate10, + wr.TargetAdjusted11 AS TargetAdjustedWageRate11, + wr.TargetAdjusted12 AS TargetAdjustedWageRate12, + + -- Budgeted Monthly Values + wr.BudgetAdjusted01 AS BudgetAdjustedWageRate01, + wr.BudgetAdjusted02 AS BudgetAdjustedWageRate02, + wr.BudgetAdjusted03 AS BudgetAdjustedWageRate03, + wr.BudgetAdjusted04 AS BudgetAdjustedWageRate04, + wr.BudgetAdjusted05 AS BudgetAdjustedWageRate05, + wr.BudgetAdjusted06 AS BudgetAdjustedWageRate06, + wr.BudgetAdjusted07 AS BudgetAdjustedWageRate07, + wr.BudgetAdjusted08 AS BudgetAdjustedWageRate08, + wr.BudgetAdjusted09 AS BudgetAdjustedWageRate09, + wr.BudgetAdjusted10 AS BudgetAdjustedWageRate10, + wr.BudgetAdjusted11 AS BudgetAdjustedWageRate11, + wr.BudgetAdjusted12 AS BudgetAdjustedWageRate12, + + -- Projected Monthly Values + wr.ProjectionAdjusted01 AS ProjectionAdjustedWageRate01, + wr.ProjectionAdjusted02 AS ProjectionAdjustedWageRate02, + wr.ProjectionAdjusted03 AS ProjectionAdjustedWageRate03, + wr.ProjectionAdjusted04 AS ProjectionAdjustedWageRate04, + wr.ProjectionAdjusted05 AS ProjectionAdjustedWageRate05, + wr.ProjectionAdjusted06 AS ProjectionAdjustedWageRate06, + wr.ProjectionAdjusted07 AS ProjectionAdjustedWageRate07, + wr.ProjectionAdjusted08 AS ProjectionAdjustedWageRate08, + wr.ProjectionAdjusted09 AS ProjectionAdjustedWageRate09, + wr.ProjectionAdjusted10 AS ProjectionAdjustedWageRate10, + wr.ProjectionAdjusted11 AS ProjectionAdjustedWageRate11, + wr.ProjectionAdjusted12 AS ProjectionAdjustedWageRate12 + + FROM [fp].[Staffing] fs (READUNCOMMITTED) + INNER JOIN [fp].[StaffingHistory] hist (READUNCOMMITTED) ON fs.StaffingID = hist.StaffingID + INNER JOIN [fp].[StaffingWageRate] wr (READUNCOMMITTED) ON fs.StaffingWageRateID = wr.StaffingWageRateID +GO + + +--------------------------------------------- + +-- fp.viewStaffingAdjustment +CREATE VIEW [fp].[viewStaffingAdjustment] +AS + +SELECT [AdjustmentGUID] + ,[BudgetConfigGUID] + ,[AdjustmentType] + ,[Value] + ,[AdjustmentFilterJSON] + ,[GroupingHierarchyJSON] + ,[AdjustedProperty] + ,[Comment] + ,[AuthorGUID] + ,[AuthorFullName] + ,[LastModifiedDateUtc] + ,[DateCreatedUtc] + ,[UnitTypeID] + ,[GroupingGUID] + ,[ParentFilterJSON] + ,[TimeClassID] + ,[BudgetPhaseID] + ,[ClassificationGroupID] + ,[ClassificationCategoryID] + ,[IsRecordDeleted] + ,[DimensionMemberJson] + ,[AdjustmentID] + ,[SubsectionID] + ,[IsErrored] + FROM [fp].[StaffingAdjustment] + WHERE IsRecordDeleted = 0; +GO + + +--------------------------------------------- + +-- fp.viewStaffingAdjustmentImport +CREATE VIEW [fp].[viewStaffingAdjustmentImport] +AS + +SELECT [RowID] + ,[AdjustmentGUID] + ,[DepartmentID] + ,[JobCodeID] + ,[FiscalYearID] + ,[UnitTypeID] + ,[FiscalMonthID] + ,[Value] + ,[Version] + ,[PayCodeGroupID] + ,[ProductiveClassID] + ,[VariabilityID] + ,[EntityID] + ,[TimeClassID] + ,[BudgetPhaseID] + ,[IsRecordDeleted] + ,[AdjustmentID] + ,[EmployeeID] + ,[ProviderID] + ,[ProviderTypeID] + ,[ProviderSpecialtyID] + ,[ProviderLineItemID] + ,[OriginalUnitTypeID] + FROM [fp].[StaffingAdjustmentImport] + WHERE IsRecordDeleted = 0 +GO + + +--------------------------------------------- + +-- fp.viewStaffingDollars +CREATE VIEW [fp].[viewStaffingDollars] +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-02-21 MY JAZZ-XXX Initial + *************************************************************/ + + SELECT + fs.StaffingID, + fs.StaffingWageRateID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.ProductiveClassID, + fs.VariabilityID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.SubsectionID, + fs.FlexingTypeID, + fs.FixedVariabilityPercentage, + fs.IsNew, + fs.AddDate, + + fs.TargetDollarsLockType, + fs.TargetDollarsLockFlag, + fs.BudgetDollarsLockType, + fs.BudgetDollarsLockFlag, + fs.ProjectionDollarsLockType, + fs.ProjectionDollarsLockFlag, + + fs.TargetAdjustedDollarsTotal, + fs.BudgetAdjustedDollarsTotal, + fs.ProjectionAdjustedDollarsTotal, + + fs.InitialBudgetDollarsTotal, + fs.SampledBudgetDollarsTotal, + fs.SampledProjectionDollarsTotal, + + hist.ActualYTDDollarsTotal, + hist.CurrentYearBudgetDollarsTotal, + hist.PriorYearActualDollarsTotal, + + -- Target Montly Values + fs.TargetAdjustedDollars01, + fs.TargetAdjustedDollars02, + fs.TargetAdjustedDollars03, + fs.TargetAdjustedDollars04, + fs.TargetAdjustedDollars05, + fs.TargetAdjustedDollars06, + fs.TargetAdjustedDollars07, + fs.TargetAdjustedDollars08, + fs.TargetAdjustedDollars09, + fs.TargetAdjustedDollars10, + fs.TargetAdjustedDollars11, + fs.TargetAdjustedDollars12, + + -- Budgeted Monthly Values + fs.BudgetAdjustedDollars01, + fs.BudgetAdjustedDollars02, + fs.BudgetAdjustedDollars03, + fs.BudgetAdjustedDollars04, + fs.BudgetAdjustedDollars05, + fs.BudgetAdjustedDollars06, + fs.BudgetAdjustedDollars07, + fs.BudgetAdjustedDollars08, + fs.BudgetAdjustedDollars09, + fs.BudgetAdjustedDollars10, + fs.BudgetAdjustedDollars11, + fs.BudgetAdjustedDollars12, + + -- Projected Monthly Values + fs.ProjectionAdjustedDollars01, + fs.ProjectionAdjustedDollars02, + fs.ProjectionAdjustedDollars03, + fs.ProjectionAdjustedDollars04, + fs.ProjectionAdjustedDollars05, + fs.ProjectionAdjustedDollars06, + fs.ProjectionAdjustedDollars07, + fs.ProjectionAdjustedDollars08, + fs.ProjectionAdjustedDollars09, + fs.ProjectionAdjustedDollars10, + fs.ProjectionAdjustedDollars11, + fs.ProjectionAdjustedDollars12, + + -- Initial Dollars + fs.InitialBudgetDollars01, + fs.InitialBudgetDollars02, + fs.InitialBudgetDollars03, + fs.InitialBudgetDollars04, + fs.InitialBudgetDollars05, + fs.InitialBudgetDollars06, + fs.InitialBudgetDollars07, + fs.InitialBudgetDollars08, + fs.InitialBudgetDollars09, + fs.InitialBudgetDollars10, + fs.InitialBudgetDollars11, + fs.InitialBudgetDollars12, + + -- Sampled Dollars + fs.SampledBudgetDollars01, + fs.SampledBudgetDollars02, + fs.SampledBudgetDollars03, + fs.SampledBudgetDollars04, + fs.SampledBudgetDollars05, + fs.SampledBudgetDollars06, + fs.SampledBudgetDollars07, + fs.SampledBudgetDollars08, + fs.SampledBudgetDollars09, + fs.SampledBudgetDollars10, + fs.SampledBudgetDollars11, + fs.SampledBudgetDollars12, + + -- Sampled Projection Dollars + fs.SampledProjectionDollars01, + fs.SampledProjectionDollars02, + fs.SampledProjectionDollars03, + fs.SampledProjectionDollars04, + fs.SampledProjectionDollars05, + fs.SampledProjectionDollars06, + fs.SampledProjectionDollars07, + fs.SampledProjectionDollars08, + fs.SampledProjectionDollars09, + fs.SampledProjectionDollars10, + fs.SampledProjectionDollars11, + fs.SampledProjectionDollars12, + + -- ActualYTD Dollars + hist.ActualYTDDollars01, + hist.ActualYTDDollars02, + hist.ActualYTDDollars03, + hist.ActualYTDDollars04, + hist.ActualYTDDollars05, + hist.ActualYTDDollars06, + hist.ActualYTDDollars07, + hist.ActualYTDDollars08, + hist.ActualYTDDollars09, + hist.ActualYTDDollars10, + hist.ActualYTDDollars11, + hist.ActualYTDDollars12, + + -- CurrentYearBudget Dollars + hist.CurrentYearBudgetDollars01, + hist.CurrentYearBudgetDollars02, + hist.CurrentYearBudgetDollars03, + hist.CurrentYearBudgetDollars04, + hist.CurrentYearBudgetDollars05, + hist.CurrentYearBudgetDollars06, + hist.CurrentYearBudgetDollars07, + hist.CurrentYearBudgetDollars08, + hist.CurrentYearBudgetDollars09, + hist.CurrentYearBudgetDollars10, + hist.CurrentYearBudgetDollars11, + hist.CurrentYearBudgetDollars12, + + -- PriorYearActual Dollars + hist.PriorYearActualDollars01, + hist.PriorYearActualDollars02, + hist.PriorYearActualDollars03, + hist.PriorYearActualDollars04, + hist.PriorYearActualDollars05, + hist.PriorYearActualDollars06, + hist.PriorYearActualDollars07, + hist.PriorYearActualDollars08, + hist.PriorYearActualDollars09, + hist.PriorYearActualDollars10, + hist.PriorYearActualDollars11, + hist.PriorYearActualDollars12, + + -- Target Percent Adjustment Factor Values + fs.TargetDollarsPercentAdjustmentFactor01, + fs.TargetDollarsPercentAdjustmentFactor02, + fs.TargetDollarsPercentAdjustmentFactor03, + fs.TargetDollarsPercentAdjustmentFactor04, + fs.TargetDollarsPercentAdjustmentFactor05, + fs.TargetDollarsPercentAdjustmentFactor06, + fs.TargetDollarsPercentAdjustmentFactor07, + fs.TargetDollarsPercentAdjustmentFactor08, + fs.TargetDollarsPercentAdjustmentFactor09, + fs.TargetDollarsPercentAdjustmentFactor10, + fs.TargetDollarsPercentAdjustmentFactor11, + fs.TargetDollarsPercentAdjustmentFactor12, + + -- Budgeted Percent Adjustment Factor Values + fs.BudgetDollarsPercentAdjustmentFactor01, + fs.BudgetDollarsPercentAdjustmentFactor02, + fs.BudgetDollarsPercentAdjustmentFactor03, + fs.BudgetDollarsPercentAdjustmentFactor04, + fs.BudgetDollarsPercentAdjustmentFactor05, + fs.BudgetDollarsPercentAdjustmentFactor06, + fs.BudgetDollarsPercentAdjustmentFactor07, + fs.BudgetDollarsPercentAdjustmentFactor08, + fs.BudgetDollarsPercentAdjustmentFactor09, + fs.BudgetDollarsPercentAdjustmentFactor10, + fs.BudgetDollarsPercentAdjustmentFactor11, + fs.BudgetDollarsPercentAdjustmentFactor12, + + -- Projected Percent Adjustment Factor Values + fs.ProjectionDollarsPercentAdjustmentFactor01, + fs.ProjectionDollarsPercentAdjustmentFactor02, + fs.ProjectionDollarsPercentAdjustmentFactor03, + fs.ProjectionDollarsPercentAdjustmentFactor04, + fs.ProjectionDollarsPercentAdjustmentFactor05, + fs.ProjectionDollarsPercentAdjustmentFactor06, + fs.ProjectionDollarsPercentAdjustmentFactor07, + fs.ProjectionDollarsPercentAdjustmentFactor08, + fs.ProjectionDollarsPercentAdjustmentFactor09, + fs.ProjectionDollarsPercentAdjustmentFactor10, + fs.ProjectionDollarsPercentAdjustmentFactor11, + fs.ProjectionDollarsPercentAdjustmentFactor12 + FROM [fp].[Staffing] fs (READUNCOMMITTED) + INNER JOIN [fp].[StaffingHistory] hist (READUNCOMMITTED) ON fs.StaffingID = hist.StaffingID +GO + + +--------------------------------------------- + +-- fp.viewStaffingExpenseFlexingConfig +CREATE VIEW [fp].[viewStaffingExpenseFlexingConfig] +AS +SELECT + b.EntityGroupConfigGUID, + b.DepartmentID, + b.JobCodeID, + CASE WHEN b.FlexMethodID = 6 THEN 6 + ELSE COALESCE(ovr.FlexMethodID, b.FlexMethodID) END As FlexMethodID +FROM ( + SELECT + fc.EntityGroupConfigGUID, + fc.DepartmentID, + jc.JobCodeID, + fc.FlexMethodID + FROM [fp].[StaffingExpenseFlexingConfig] fc + CROSS APPLY (SELECT JobCodeID FROM [fw].[DimJobCode] WHERE JobCodeID > 0) jc +)b +LEFT JOIN [fp].[StaffingFlexingOverrideConfig] ovr + ON b.DepartmentID = ovr.DepartmentID + AND b.JobCodeID = ovr.JobCodeID + AND b.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID +GO + + +--------------------------------------------- + +-- fp.viewStaffingExpenseFlexingConfigWithDepartmentInfo +CREATE view fp.viewStaffingExpenseFlexingConfigWithDepartmentInfo +AS +SELECT OBJ.*, d.Name +FROM [fp].[StaffingExpenseFlexingConfig] OBJ + INNER JOIN [fw].[dimDepartment] d ON OBJ.DepartmentID = d.DepartmentID +GO + + +--------------------------------------------- + +-- fp.viewStaffingFTEs +CREATE VIEW [fp].[viewStaffingFTEs] +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-02-21 MY JAZZ-XXX Initial + *************************************************************/ + + SELECT + fs.StaffingID, + fs.StaffingWageRateID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.ProductiveClassID, + fs.VariabilityID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.SubsectionID, + fs.FlexingTypeID, + fs.FixedVariabilityPercentage, + fs.IsNew, + fs.AddDate, + + fs.TargetFTEsLockType, + fs.TargetFTEsLockFlag, + fs.BudgetFTEsLockType, + fs.BudgetFTEsLockFlag, + fs.ProjectionFTEsLockType, + fs.ProjectionFTEsLockFlag, + + -- Target Montly Values + fs.TargetAdjustedFTEs01, + fs.TargetAdjustedFTEs02, + fs.TargetAdjustedFTEs03, + fs.TargetAdjustedFTEs04, + fs.TargetAdjustedFTEs05, + fs.TargetAdjustedFTEs06, + fs.TargetAdjustedFTEs07, + fs.TargetAdjustedFTEs08, + fs.TargetAdjustedFTEs09, + fs.TargetAdjustedFTEs10, + fs.TargetAdjustedFTEs11, + fs.TargetAdjustedFTEs12, + + -- Budgeted Monthly Values + fs.BudgetAdjustedFTEs01, + fs.BudgetAdjustedFTEs02, + fs.BudgetAdjustedFTEs03, + fs.BudgetAdjustedFTEs04, + fs.BudgetAdjustedFTEs05, + fs.BudgetAdjustedFTEs06, + fs.BudgetAdjustedFTEs07, + fs.BudgetAdjustedFTEs08, + fs.BudgetAdjustedFTEs09, + fs.BudgetAdjustedFTEs10, + fs.BudgetAdjustedFTEs11, + fs.BudgetAdjustedFTEs12, + + -- Projected Monthly Values + fs.ProjectionAdjustedFTEs01, + fs.ProjectionAdjustedFTEs02, + fs.ProjectionAdjustedFTEs03, + fs.ProjectionAdjustedFTEs04, + fs.ProjectionAdjustedFTEs05, + fs.ProjectionAdjustedFTEs06, + fs.ProjectionAdjustedFTEs07, + fs.ProjectionAdjustedFTEs08, + fs.ProjectionAdjustedFTEs09, + fs.ProjectionAdjustedFTEs10, + fs.ProjectionAdjustedFTEs11, + fs.ProjectionAdjustedFTEs12, + + -- Initial FTEs + fs.InitialBudgetFTEs01, + fs.InitialBudgetFTEs02, + fs.InitialBudgetFTEs03, + fs.InitialBudgetFTEs04, + fs.InitialBudgetFTEs05, + fs.InitialBudgetFTEs06, + fs.InitialBudgetFTEs07, + fs.InitialBudgetFTEs08, + fs.InitialBudgetFTEs09, + fs.InitialBudgetFTEs10, + fs.InitialBudgetFTEs11, + fs.InitialBudgetFTEs12, + + -- Sampled FTEs + fs.SampledBudgetFTEs01, + fs.SampledBudgetFTEs02, + fs.SampledBudgetFTEs03, + fs.SampledBudgetFTEs04, + fs.SampledBudgetFTEs05, + fs.SampledBudgetFTEs06, + fs.SampledBudgetFTEs07, + fs.SampledBudgetFTEs08, + fs.SampledBudgetFTEs09, + fs.SampledBudgetFTEs10, + fs.SampledBudgetFTEs11, + fs.SampledBudgetFTEs12, + + -- Sampled Projection FTEs + fs.SampledProjectionFTEs01, + fs.SampledProjectionFTEs02, + fs.SampledProjectionFTEs03, + fs.SampledProjectionFTEs04, + fs.SampledProjectionFTEs05, + fs.SampledProjectionFTEs06, + fs.SampledProjectionFTEs07, + fs.SampledProjectionFTEs08, + fs.SampledProjectionFTEs09, + fs.SampledProjectionFTEs10, + fs.SampledProjectionFTEs11, + fs.SampledProjectionFTEs12, + + -- ActualYTD FTEs + hist.ActualYTDFTEs01, + hist.ActualYTDFTEs02, + hist.ActualYTDFTEs03, + hist.ActualYTDFTEs04, + hist.ActualYTDFTEs05, + hist.ActualYTDFTEs06, + hist.ActualYTDFTEs07, + hist.ActualYTDFTEs08, + hist.ActualYTDFTEs09, + hist.ActualYTDFTEs10, + hist.ActualYTDFTEs11, + hist.ActualYTDFTEs12, + + -- CurrentYearBudget FTEs + hist.CurrentYearBudgetFTEs01, + hist.CurrentYearBudgetFTEs02, + hist.CurrentYearBudgetFTEs03, + hist.CurrentYearBudgetFTEs04, + hist.CurrentYearBudgetFTEs05, + hist.CurrentYearBudgetFTEs06, + hist.CurrentYearBudgetFTEs07, + hist.CurrentYearBudgetFTEs08, + hist.CurrentYearBudgetFTEs09, + hist.CurrentYearBudgetFTEs10, + hist.CurrentYearBudgetFTEs11, + hist.CurrentYearBudgetFTEs12, + + -- PriorYearActual FTEs + hist.PriorYearActualFTEs01, + hist.PriorYearActualFTEs02, + hist.PriorYearActualFTEs03, + hist.PriorYearActualFTEs04, + hist.PriorYearActualFTEs05, + hist.PriorYearActualFTEs06, + hist.PriorYearActualFTEs07, + hist.PriorYearActualFTEs08, + hist.PriorYearActualFTEs09, + hist.PriorYearActualFTEs10, + hist.PriorYearActualFTEs11, + hist.PriorYearActualFTEs12, + + -- Target Percent Adjustment Factor Values + fs.TargetFTEsPercentAdjustmentFactor01, + fs.TargetFTEsPercentAdjustmentFactor02, + fs.TargetFTEsPercentAdjustmentFactor03, + fs.TargetFTEsPercentAdjustmentFactor04, + fs.TargetFTEsPercentAdjustmentFactor05, + fs.TargetFTEsPercentAdjustmentFactor06, + fs.TargetFTEsPercentAdjustmentFactor07, + fs.TargetFTEsPercentAdjustmentFactor08, + fs.TargetFTEsPercentAdjustmentFactor09, + fs.TargetFTEsPercentAdjustmentFactor10, + fs.TargetFTEsPercentAdjustmentFactor11, + fs.TargetFTEsPercentAdjustmentFactor12, + + -- Budgeted Percent Adjustment Factor Values + fs.BudgetFTEsPercentAdjustmentFactor01, + fs.BudgetFTEsPercentAdjustmentFactor02, + fs.BudgetFTEsPercentAdjustmentFactor03, + fs.BudgetFTEsPercentAdjustmentFactor04, + fs.BudgetFTEsPercentAdjustmentFactor05, + fs.BudgetFTEsPercentAdjustmentFactor06, + fs.BudgetFTEsPercentAdjustmentFactor07, + fs.BudgetFTEsPercentAdjustmentFactor08, + fs.BudgetFTEsPercentAdjustmentFactor09, + fs.BudgetFTEsPercentAdjustmentFactor10, + fs.BudgetFTEsPercentAdjustmentFactor11, + fs.BudgetFTEsPercentAdjustmentFactor12, + + -- Projected Percent Adjustment Factor Values + fs.ProjectionFTEsPercentAdjustmentFactor01, + fs.ProjectionFTEsPercentAdjustmentFactor02, + fs.ProjectionFTEsPercentAdjustmentFactor03, + fs.ProjectionFTEsPercentAdjustmentFactor04, + fs.ProjectionFTEsPercentAdjustmentFactor05, + fs.ProjectionFTEsPercentAdjustmentFactor06, + fs.ProjectionFTEsPercentAdjustmentFactor07, + fs.ProjectionFTEsPercentAdjustmentFactor08, + fs.ProjectionFTEsPercentAdjustmentFactor09, + fs.ProjectionFTEsPercentAdjustmentFactor10, + fs.ProjectionFTEsPercentAdjustmentFactor11, + fs.ProjectionFTEsPercentAdjustmentFactor12 + FROM [fp].[Staffing] fs (READUNCOMMITTED) + INNER JOIN [fp].[StaffingHistory] hist (READUNCOMMITTED) ON fs.StaffingID = hist.StaffingID +GO + + +--------------------------------------------- + +-- fp.viewStaffingHours +CREATE VIEW [fp].[viewStaffingHours] +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-02-21 MY JAZZ-XXX Initial + *************************************************************/ + + SELECT + fs.StaffingID, + fs.StaffingWageRateID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.ProductiveClassID, + fs.VariabilityID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.SubsectionID, + fs.FlexingTypeID, + fs.FixedVariabilityPercentage, + fs.IsNew, + fs.AddDate, + + fs.TargetHoursLockType, + fs.TargetHoursLockFlag, + fs.BudgetHoursLockType, + fs.BudgetHoursLockFlag, + fs.ProjectionHoursLockType, + fs.ProjectionHoursLockFlag, + + fs.TargetAdjustedHoursTotal, + fs.BudgetAdjustedHoursTotal, + fs.ProjectionAdjustedHoursTotal, + + fs.InitialBudgetHoursTotal, + fs.SampledBudgetHoursTotal, + fs.SampledProjectionHoursTotal, + + hist.ActualYTDHoursTotal, + hist.CurrentYearBudgetHoursTotal, + hist.PriorYearActualHoursTotal, + + -- Target Montly Values + fs.TargetAdjustedHours01, + fs.TargetAdjustedHours02, + fs.TargetAdjustedHours03, + fs.TargetAdjustedHours04, + fs.TargetAdjustedHours05, + fs.TargetAdjustedHours06, + fs.TargetAdjustedHours07, + fs.TargetAdjustedHours08, + fs.TargetAdjustedHours09, + fs.TargetAdjustedHours10, + fs.TargetAdjustedHours11, + fs.TargetAdjustedHours12, + + -- Budgeted Monthly Values + fs.BudgetAdjustedHours01, + fs.BudgetAdjustedHours02, + fs.BudgetAdjustedHours03, + fs.BudgetAdjustedHours04, + fs.BudgetAdjustedHours05, + fs.BudgetAdjustedHours06, + fs.BudgetAdjustedHours07, + fs.BudgetAdjustedHours08, + fs.BudgetAdjustedHours09, + fs.BudgetAdjustedHours10, + fs.BudgetAdjustedHours11, + fs.BudgetAdjustedHours12, + + -- Projected Monthly Values + fs.ProjectionAdjustedHours01, + fs.ProjectionAdjustedHours02, + fs.ProjectionAdjustedHours03, + fs.ProjectionAdjustedHours04, + fs.ProjectionAdjustedHours05, + fs.ProjectionAdjustedHours06, + fs.ProjectionAdjustedHours07, + fs.ProjectionAdjustedHours08, + fs.ProjectionAdjustedHours09, + fs.ProjectionAdjustedHours10, + fs.ProjectionAdjustedHours11, + fs.ProjectionAdjustedHours12, + + -- Initial Hours + fs.InitialBudgetHours01, + fs.InitialBudgetHours02, + fs.InitialBudgetHours03, + fs.InitialBudgetHours04, + fs.InitialBudgetHours05, + fs.InitialBudgetHours06, + fs.InitialBudgetHours07, + fs.InitialBudgetHours08, + fs.InitialBudgetHours09, + fs.InitialBudgetHours10, + fs.InitialBudgetHours11, + fs.InitialBudgetHours12, + + -- Sampled Hours + fs.SampledBudgetHours01, + fs.SampledBudgetHours02, + fs.SampledBudgetHours03, + fs.SampledBudgetHours04, + fs.SampledBudgetHours05, + fs.SampledBudgetHours06, + fs.SampledBudgetHours07, + fs.SampledBudgetHours08, + fs.SampledBudgetHours09, + fs.SampledBudgetHours10, + fs.SampledBudgetHours11, + fs.SampledBudgetHours12, + + -- Sampled Projection Hours + fs.SampledProjectionHours01, + fs.SampledProjectionHours02, + fs.SampledProjectionHours03, + fs.SampledProjectionHours04, + fs.SampledProjectionHours05, + fs.SampledProjectionHours06, + fs.SampledProjectionHours07, + fs.SampledProjectionHours08, + fs.SampledProjectionHours09, + fs.SampledProjectionHours10, + fs.SampledProjectionHours11, + fs.SampledProjectionHours12, + + -- ActualYTD Hours + hist.ActualYTDHours01, + hist.ActualYTDHours02, + hist.ActualYTDHours03, + hist.ActualYTDHours04, + hist.ActualYTDHours05, + hist.ActualYTDHours06, + hist.ActualYTDHours07, + hist.ActualYTDHours08, + hist.ActualYTDHours09, + hist.ActualYTDHours10, + hist.ActualYTDHours11, + hist.ActualYTDHours12, + + -- CurrentYearBudget Hours + hist.CurrentYearBudgetHours01, + hist.CurrentYearBudgetHours02, + hist.CurrentYearBudgetHours03, + hist.CurrentYearBudgetHours04, + hist.CurrentYearBudgetHours05, + hist.CurrentYearBudgetHours06, + hist.CurrentYearBudgetHours07, + hist.CurrentYearBudgetHours08, + hist.CurrentYearBudgetHours09, + hist.CurrentYearBudgetHours10, + hist.CurrentYearBudgetHours11, + hist.CurrentYearBudgetHours12, + + -- PriorYearActual Hours + hist.PriorYearActualHours01, + hist.PriorYearActualHours02, + hist.PriorYearActualHours03, + hist.PriorYearActualHours04, + hist.PriorYearActualHours05, + hist.PriorYearActualHours06, + hist.PriorYearActualHours07, + hist.PriorYearActualHours08, + hist.PriorYearActualHours09, + hist.PriorYearActualHours10, + hist.PriorYearActualHours11, + hist.PriorYearActualHours12, + + -- Target Percent Adjustment Factor Values + fs.TargetHoursPercentAdjustmentFactor01, + fs.TargetHoursPercentAdjustmentFactor02, + fs.TargetHoursPercentAdjustmentFactor03, + fs.TargetHoursPercentAdjustmentFactor04, + fs.TargetHoursPercentAdjustmentFactor05, + fs.TargetHoursPercentAdjustmentFactor06, + fs.TargetHoursPercentAdjustmentFactor07, + fs.TargetHoursPercentAdjustmentFactor08, + fs.TargetHoursPercentAdjustmentFactor09, + fs.TargetHoursPercentAdjustmentFactor10, + fs.TargetHoursPercentAdjustmentFactor11, + fs.TargetHoursPercentAdjustmentFactor12, + + -- Budgeted Percent Adjustment Factor Values + fs.BudgetHoursPercentAdjustmentFactor01, + fs.BudgetHoursPercentAdjustmentFactor02, + fs.BudgetHoursPercentAdjustmentFactor03, + fs.BudgetHoursPercentAdjustmentFactor04, + fs.BudgetHoursPercentAdjustmentFactor05, + fs.BudgetHoursPercentAdjustmentFactor06, + fs.BudgetHoursPercentAdjustmentFactor07, + fs.BudgetHoursPercentAdjustmentFactor08, + fs.BudgetHoursPercentAdjustmentFactor09, + fs.BudgetHoursPercentAdjustmentFactor10, + fs.BudgetHoursPercentAdjustmentFactor11, + fs.BudgetHoursPercentAdjustmentFactor12, + + -- Projected Percent Adjustment Factor Values + fs.ProjectionHoursPercentAdjustmentFactor01, + fs.ProjectionHoursPercentAdjustmentFactor02, + fs.ProjectionHoursPercentAdjustmentFactor03, + fs.ProjectionHoursPercentAdjustmentFactor04, + fs.ProjectionHoursPercentAdjustmentFactor05, + fs.ProjectionHoursPercentAdjustmentFactor06, + fs.ProjectionHoursPercentAdjustmentFactor07, + fs.ProjectionHoursPercentAdjustmentFactor08, + fs.ProjectionHoursPercentAdjustmentFactor09, + fs.ProjectionHoursPercentAdjustmentFactor10, + fs.ProjectionHoursPercentAdjustmentFactor11, + fs.ProjectionHoursPercentAdjustmentFactor12 + FROM [fp].[Staffing] fs (READUNCOMMITTED) + INNER JOIN [fp].[StaffingHistory] hist (READUNCOMMITTED) ON fs.StaffingID = hist.StaffingID +GO + + +--------------------------------------------- + +-- fp.viewStaffingInitialPlanConfigDetailLogs +CREATE VIEW [fp].[viewStaffingInitialPlanConfigDetailLogs] + AS +/******************************************************************************* + ** Change History + ******************************************************************************** + ** CID Date Author WI Description + ** 1 04-03-2024 NT JAZZ-61357 Initial Creation +*******************************************************************************/ + + SELECT + RowID, + BudgetConfigGUID, + BudgetConfigID, + DepartmentID, + JobCodeID, + ProductiveClassID, + PayCodeGroupID, + VariabilityID, + TimeClassID, + UnitTypeID, + EmployeeID, + ProviderID, + ProviderLineItemID, + ProviderTypeID, + ProviderSpecialtyID, + ProjectionMethodID, + TrailingMonths, + VersionID +FROM + [fp].[StaffingInitialPlanConfigDetail] +UNION + SELECT + RowID, + BudgetConfigGUID, + BudgetConfigID, + DepartmentID, + JobCodeID, + ProductiveClassID, + PayCodeGroupID, + VariabilityID, + TimeClassID, + UnitTypeID, + EmployeeID, + ProviderID, + ProviderLineItemID, + ProviderTypeID, + ProviderSpecialtyID, + ProjectionMethodID, + TrailingMonths, + VersionID +FROM + [fp].[StaffingInitialPlanConfigDetailHistory] +GO + + +--------------------------------------------- + +-- fp.viewStaffingManagerAdjustmentComments +CREATE VIEW [fp].[viewStaffingManagerAdjustmentComments] +AS +SELECT +ROW_NUMBER() OVER(ORDER BY DepartmentID ASC) AS RowID, +bc.BudgetConfigID, +sc.DepartmentID, +sc.JobCodeID, +sc.FiscalYearID, +sc.UnitTypeID, +sc.Comment, +sc.InitialValue, +sc.DeltaValue AS Adjustment, +sc.InitialValue + sc.DeltaValue AS FinalValue, +sc.DateCreatedUtc, +sc.AuthorFullName, +sc.DateModifiedUtc, +0 AS VariabilityID, +'Not Specified' AS AdjustedLevel, +CAST(sc.DateCreatedUtc AT TIME ZONE 'UTC' AT TIME ZONE 'CENTRAL STANDARD TIME' AS DATETIME) AS DateCreated, +CAST(sc.DateModifiedUtc AT TIME ZONE 'UTC' AT TIME ZONE 'CENTRAL STANDARD TIME' AS DATETIME) AS DateModified, +dc.CalendarDateTime AS DateCreatedDate +FROM fp.StaffingManagerAdjustmentComment AS sc +INNER JOIN fp.BudgetConfig AS bc ON bc.BudgetConfigGUID = sc.BudgetConfigGUID +INNER JOIN [fw].[DimDate] AS dc ON CAST(sc.DateCreatedUtc AS DATE) = dc.CalendarDateTime + +UNION ALL + +SELECT +ROW_NUMBER() OVER(ORDER BY DepartmentID ASC) AS RowID, +bc.BudgetConfigID, +sc.DepartmentID, +sc.JobCodeID, +sc.FiscalYearID, +sc.UnitTypeID, +sc.Comment, +sc.InitialValue, +sc.Value - sc.InitialValue AS Adjustment, +sc.Value AS FinalValue, +sc.DateCreatedUtc, +sc.AuthorFullName, +sc.DateModifiedUtc, +sc.VariabilityID, +(SELECT ISNULL(STRING_AGG(AdjustedLevel, ', '), '') FROM OPENJSON(AdjustedLevelInfoJSON) WITH ( AdjustedLevel NVARCHAR(MAX) '$.Text')) AS AdjustedLevel, +CAST(sc.DateCreatedUtc AT TIME ZONE 'UTC' AT TIME ZONE 'CENTRAL STANDARD TIME' AS DATETIME) AS DateCreated, +CAST(sc.DateModifiedUtc AT TIME ZONE 'UTC' AT TIME ZONE 'CENTRAL STANDARD TIME' AS DATETIME) AS DateModified, +dc.CalendarDateTime AS DateCreatedDate +FROM fp.StaffingManagerSetAdjustmentComment AS sc +INNER JOIN fp.BudgetConfig AS bc ON bc.BudgetConfigID = sc.BudgetConfigID +INNER JOIN [fw].[DimDate] AS dc ON CAST(sc.DateCreatedUtc AS DATE) = dc.CalendarDateTime +GO + + +--------------------------------------------- + +-- fp.viewStaffingRate +CREATE VIEW [fp].[viewStaffingRate] +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-02-21 MY JAZZ-XXX Initial + *************************************************************/ + + SELECT + fs.StaffingID, + fs.StaffingWageRateID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.ProductiveClassID, + fs.VariabilityID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.SubsectionID, + fs.FlexingTypeID, + fs.FixedVariabilityPercentage, + fs.IsNew, + fs.AddDate, + + -- Target Montly Values + fs.TargetAdjustedRate01, + fs.TargetAdjustedRate02, + fs.TargetAdjustedRate03, + fs.TargetAdjustedRate04, + fs.TargetAdjustedRate05, + fs.TargetAdjustedRate06, + fs.TargetAdjustedRate07, + fs.TargetAdjustedRate08, + fs.TargetAdjustedRate09, + fs.TargetAdjustedRate10, + fs.TargetAdjustedRate11, + fs.TargetAdjustedRate12, + + -- Budgeted Monthly Values + fs.BudgetAdjustedRate01, + fs.BudgetAdjustedRate02, + fs.BudgetAdjustedRate03, + fs.BudgetAdjustedRate04, + fs.BudgetAdjustedRate05, + fs.BudgetAdjustedRate06, + fs.BudgetAdjustedRate07, + fs.BudgetAdjustedRate08, + fs.BudgetAdjustedRate09, + fs.BudgetAdjustedRate10, + fs.BudgetAdjustedRate11, + fs.BudgetAdjustedRate12, + + -- Projected Monthly Values + fs.ProjectionAdjustedRate01, + fs.ProjectionAdjustedRate02, + fs.ProjectionAdjustedRate03, + fs.ProjectionAdjustedRate04, + fs.ProjectionAdjustedRate05, + fs.ProjectionAdjustedRate06, + fs.ProjectionAdjustedRate07, + fs.ProjectionAdjustedRate08, + fs.ProjectionAdjustedRate09, + fs.ProjectionAdjustedRate10, + fs.ProjectionAdjustedRate11, + fs.ProjectionAdjustedRate12, + + -- Initial Rate + fs.InitialBudgetRate01, + fs.InitialBudgetRate02, + fs.InitialBudgetRate03, + fs.InitialBudgetRate04, + fs.InitialBudgetRate05, + fs.InitialBudgetRate06, + fs.InitialBudgetRate07, + fs.InitialBudgetRate08, + fs.InitialBudgetRate09, + fs.InitialBudgetRate10, + fs.InitialBudgetRate11, + fs.InitialBudgetRate12 + FROM [fp].[Staffing] fs (READUNCOMMITTED) +GO + + +--------------------------------------------- + +-- fp.viewStaffingSpreadUnlockData +CREATE VIEW fp.viewStaffingSpreadUnlockData +AS + +SELECT [RowID] + ,[BudgetConfigID] + ,[AdjustmentGUID] + ,[EntityID] + ,[DepartmentID] + ,[JobCodeID] + ,[PayCodeGroupID] + ,[ProductiveClassID] + ,[UnitTypeID] + ,[Version] + ,[Value01] + ,[Value02] + ,[Value03] + ,[Value04] + ,[Value05] + ,[Value06] + ,[Value07] + ,[Value08] + ,[Value09] + ,[Value10] + ,[Value11] + ,[Value12] + ,[IsRecordDeleted] + ,[EmployeeID] + ,[ProviderID] + ,[ProviderTypeID] + ,[ProviderSpecialtyID] + ,[ProviderLineItemID] +FROM [fp].[StaffingSpreadUnlockData] +WHERE IsRecordDeleted = 0 +GO + + +--------------------------------------------- + +-- fp.viewStaffingSpreads +CREATE VIEW fp.viewStaffingSpreads +AS + SELECT [BudgetConfigID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [IsInactive], [SpreadPercentage01], [SpreadPercentage02], [SpreadPercentage03], [SpreadPercentage04], [SpreadPercentage05], [SpreadPercentage06], [SpreadPercentage07], [SpreadPercentage08], [SpreadPercentage09], [SpreadPercentage10], [SpreadPercentage11], [SpreadPercentage12], [TotalImportedValue] as TotalSpreadValue, [GlobalSpreadID] + FROM [fp].[StaffingSpreads] gls with (readuncommitted) + WHERE GlobalSpreadID = 1 + + UNION ALL + + SELECT gls.[BudgetConfigID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [IsInactive], gs.[SpreadPercentage01], gs.[SpreadPercentage02], gs.[SpreadPercentage03], gs.[SpreadPercentage04], gs.[SpreadPercentage05], gs.[SpreadPercentage06], gs.[SpreadPercentage07], gs.[SpreadPercentage08], gs.[SpreadPercentage09], gs.[SpreadPercentage10], gs.[SpreadPercentage11], gs.[SpreadPercentage12], gs.TotalSpreadValue, gls.[GlobalSpreadID] + FROM [fp].[StaffingSpreads] gls with (readuncommitted) + INNER JOIN [fp].[GlobalSpread] gs + ON gls.GlobalSpreadID = gs.GlobalSpreadID + WHERE gls.GlobalSpreadID > 1 +GO + + +--------------------------------------------- + +-- fp.viewStaffingTotals +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 10-9-2023 MY JAZZ-61365 Restructure Update +*************************************************************/ +CREATE VIEW [fp].[viewStaffingTotals] +AS + SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.ProductiveClassID, + fs.VariabilityID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.SubsectionID, + 34 AS UnitTypeID, + 3 AS BudgetPhaseID, -- Not sure why this is on here when we then break it out by phase??? Will look later + BudgetDollarsLockType as BudgetLockType, + BudgetDollarsLockFlag as BudgetLockFlag, + ProjectionDollarsLockType as ProjectionLockType, + ProjectionDollarsLockFlag as ProjectionLockFlag, + fs.SampledBudgetDollarsTotal AS SampledBudgetTotal, + fs.InitialBudgetDollarsTotal AS InitialBudgetTotal, + fs.SampledProjectionDollarsTotal AS SampledProjectionTotal, + fs.InitialProjectionDollarsTotal AS InitialProjectionTotal, + fs.TargetAdjustedDollarsTotal AS AdjustedValueTotal, + fs.TargetAdjustedDollarsTotal AS FlexedValueTotal, + fs.ProjectionAdjustedDollarsTotal AS AdjustedProjectionValueTotal, + fs.ProjectionAdjustedDollarsTotal AS FlexedProjectionValueTotal, + fs.BudgetAdjustedDollarsTotal as ManagerAdjustedValueTotal, + fs.BudgetAdjustedDollarsTotal as ManagerFlexedValueTotal, + fs.ProjectionAdjustedDollarsTotal as ManagerAdjustedProjectionValueTotal, + fs.ProjectionAdjustedDollarsTotal as ManagerFlexedProjectionValueTotal, + COALESCE(hist.PriorYearActualDollarsTotal, 0) as PriorYearActualValueTotal, + COALESCE(hist.ActualYTDDollarsTotal, 0) as ActualYTDValueTotal, + COALESCE(hist.CurrentYearBudgetDollarsTotal, 0) as CurrentYearBudgetTotal, + wh.MonthYearly as WorkingHours, + histHours.MonthYearly as HistoricalWorkingHours, + fs.FixedVariabilityPercentage + FROM [fp].[Staffing] fs + INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimEmployee] e on fs.EmployeeID = e.EmployeeID + INNER JOIN [fw].[DimDepartment] d on fs.DepartmentID = d.DepartmentID + INNER JOIN [fp].[BudgetConfig] bc on fs.BudgetConfigID = bc.BudgetConfigID + LEFT JOIN [fp].[StaffingHistory] hist ON fs.StaffingID = hist.StaffingID + LEFT JOIN [client].[FactWorkingHoursPerMonth] wh ON wh.FiscalYearID = bc.FiscalYearID + AND wh.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END) + LEFT JOIN [client].[FactWorkingHoursPerMonth] histHours ON histHours.FiscalYearID = (bc.FiscalYearID - 1) + AND histHours.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END) + UNION ALL + SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.ProductiveClassID, + fs.VariabilityID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.SubsectionID, + 51 AS UnitTypeID, + 3 AS BudgetPhaseID, -- Not sure why this is on here when we then break it out by phase??? Will look later + BudgetHoursLockType as BudgetLockType, + BudgetHoursLockFlag as BudgetLockFlag, + ProjectionHoursLockType as ProjectionLockType, + ProjectionHoursLockFlag as ProjectionLockFlag, + fs.SampledBudgetHoursTotal AS SampledBudgetTotal, + fs.InitialBudgetHoursTotal AS InitialBudgetTotal, + fs.SampledProjectionHoursTotal AS SampledProjectionTotal, + fs.InitialProjectionHoursTotal AS InitialProjectionTotal, + fs.TargetAdjustedHoursTotal AS AdjustedValueTotal, + fs.TargetAdjustedHoursTotal AS FlexedValueTotal, + fs.ProjectionAdjustedHoursTotal AS AdjustedProjectionValueTotal, + fs.ProjectionAdjustedHoursTotal AS FlexedProjectionValueTotal, + fs.BudgetAdjustedHoursTotal as ManagerAdjustedValueTotal, + fs.BudgetAdjustedHoursTotal as ManagerFlexedValueTotal, + fs.ProjectionAdjustedHoursTotal as ManagerAdjustedProjectionValueTotal, + fs.ProjectionAdjustedHoursTotal as ManagerFlexedProjectionValueTotal, + COALESCE(hist.PriorYearActualHoursTotal, 0) as PriorYearActualValueTotal, + COALESCE(hist.ActualYTDHoursTotal, 0) as ActualYTDValueTotal, + COALESCE(hist.CurrentYearBudgetHoursTotal, 0) as CurrentYearBudgetTotal, + wh.MonthYearly as WorkingHours, + histHours.MonthYearly as HistoricalWorkingHours, + fs.FixedVariabilityPercentage + FROM [fp].[Staffing] fs + INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimEmployee] e on fs.EmployeeID = e.EmployeeID + INNER JOIN [fw].[DimDepartment] d on fs.DepartmentID = d.DepartmentID + INNER JOIN [fp].[BudgetConfig] bc on fs.BudgetConfigID = bc.BudgetConfigID + LEFT JOIN [fp].[StaffingHistory] hist ON fs.StaffingID = hist.StaffingID + LEFT JOIN [client].[FactWorkingHoursPerMonth] wh ON wh.FiscalYearID = bc.FiscalYearID + AND wh.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END) + LEFT JOIN [client].[FactWorkingHoursPerMonth] histHours ON histHours.FiscalYearID = (bc.FiscalYearID - 1) + AND histHours.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END) + -- Excluding FTEs and Wage Rate, because they cannot be summed up across months and must be calculated, if we need to end up pulling them in I can + -- however, the values coming in before the restructure were wrong so I'm guessing they weren't used +GO + + +--------------------------------------------- + +-- fp.viewStaffingTotalsFixed_FromStaffing +CREATE VIEW [fp].[viewStaffingTotalsFixed_FromStaffing] + AS + /************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-10-23 NT JAZZ-61396 This is a replacement for viewFactStaffingTotalsFixed_FromFactStaffing as part of + Staffing Restructure +*************************************************************/ +SELECT + [StaffingID], + [BudgetConfigID], + fs.[EntityGroupConfigID], + [EntityID], + [DepartmentID], + [JobCodeID], + [PayCodeGroupID], + [ProductiveClassID], + [VariabilityID], + [EmployeeID], + [ProviderID], + [ProviderTypeID], + [ProviderSpecialtyID], + [ProviderLineItemID], + [SubsectionID], + [UnitTypeID], + [BudgetPhaseID], + [BudgetLockType], + [BudgetLockFlag], + [ProjectionLockType], + [ProjectionLockFlag], + [SampledBudgetTotal], + [InitialBudgetTotal], + [SampledProjectionTotal], + [InitialProjectionTotal], + [AdjustedValueTotal], + [FlexedValueTotal], + [AdjustedProjectionValueTotal], + [FlexedProjectionValueTotal], + [ManagerAdjustedValueTotal], + [ManagerFlexedValueTotal], + [ManagerAdjustedProjectionValueTotal], + [ManagerFlexedProjectionValueTotal], + [PriorYearActualValueTotal], + [ActualYTDValueTotal], + [CurrentYearBudgetTotal], + [WorkingHours], + [HistoricalWorkingHours], + [FixedVariabilityPercentage] +FROM + fp.viewStaffingTotals fs +INNER JOIN [fp].[EntityGroupConfig] AS egc ON + egc.EntityGroupConfigID = fs.EntityGroupConfigID +WHERE + fs.FixedVariabilityPercentage = 1 +GO + + +--------------------------------------------- + +-- fp.viewStaffingVariability +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-04-28 MY JAZZ-28395 Cache Variability Percentage on FactStaffing +** 2 2022-10-18 MD JAZZ-44889 Add EGC ID to view +** 3 2022-11-07 MY JAZZ-35951 Add EmployeeID to FactStaffingVariabilityDetail +** 4 2023-10-09 MY JAZZ-61365 Upgrade to new structure +*************************************************************/ +CREATE VIEW [fp].[viewStaffingVariability] +AS +SELECT DISTINCT + pv.BudgetConfigID, + egc.EntityGroupConfigGUID, + dd.EntityID, + pv.SubsectionID, + pv.DepartmentID, + pv.ProviderLineItemID, + pv.JobCodeID, + pv.PayCodeGroupID, + pv.EmployeeID, + pv.EntityGroupConfigID, + ISNULL(MAX(pv.FixedVariabilityPercentage), 0) AS FixedPercentage +FROM [fp].[Staffing] pv + INNER JOIN [fp].[EntityGroupConfig] egc ON pv.EntityGroupConfigID = egc.EntityGroupConfigID + INNER JOIN [fw].[DimDepartment] dd ON dd.DepartmentID = pv.DepartmentID +WHERE pv.VariabilityID = 2 +GROUP BY pv.BudgetConfigID, + pv.EntityGroupConfigID, + egc.EntityGroupConfigGUID, + dd.EntityID, + pv.SubsectionID, + pv.DepartmentID, + pv.JobCodeID, + pv.ProviderLineItemID, + pv.PayCodeGroupID, + pv.EmployeeID +GO + + +--------------------------------------------- + +-- fp.viewStaffingVariabilityWithoutPayCodeGroup +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-04-28 MY JAZZ-28395 Cache Variability Percentage on FactStaffing +** 2 2022-08-22 MY JAZZ-40590 Exclude Dollars Only PCG +** 3 11-7-2022 MY JAZZ-35951 Add EmployeeID to FactStaffingVariabilityDetail +** 4 10-10-2023 MY JAZZ-61397 Update Staffing/Provider Comp adjustments to support data model changes +*************************************************************/ +CREATE VIEW [fp].[viewStaffingVariabilityWithoutPayCodeGroup] +AS +SELECT DISTINCT + bc.BudgetConfigID, + egc.EntityGroupConfigGUID, + dd.EntityID, + pv.DepartmentID, + pv.JobCodeID, -- Eventually need to add PayCodeGroup level here for when ABB clients use this. + pv.EmployeeID, + ISNULL(MAX(pv.FixedVariabilityPercentage), 0) AS FixedPercentage +FROM [fp].[Staffing] pv + INNER JOIN [fp].[EntityGroupConfig] egc ON pv.EntityGroupConfigID = egc.EntityGroupConfigID + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID + INNER JOIN [fw].[DimDepartment] dd ON dd.DepartmentID = pv.DepartmentID +WHERE pv.ProviderLineItemID = 0 -- Filtering out Provider Line Item lvl variability because they don't have manager adjustments. + AND pv.VariabilityID = 2 + AND pv.ProductiveClassID != 4 -- Exclude Dollars as these are always fixed +GROUP BY bc.BudgetConfigID, + pv.EntityGroupConfigID, + egc.EntityGroupConfigGUID, + dd.EntityID, + pv.DepartmentID, + pv.JobCodeID, + pv.EmployeeID +GO + + +--------------------------------------------- + +-- fp.viewStaffingWageRate +CREATE VIEW [fp].[viewStaffingWageRate] +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-02-21 MY JAZZ-XXX Initial + *************************************************************/ + + SELECT + fs.StaffingID, + fs.StaffingWageRateID, + fs.BudgetConfigID, + fs.EntityGroupConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.ProductiveClassID, + 3 AS VariabilityID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.SubsectionID, + fs.FlexingTypeID, + fs.FixedVariabilityPercentage, + fs.IsNew, + fs.AddDate, + + wr.TargetWageRateLockType, + wr.TargetWageRateLockFlag, + wr.BudgetWageRateLockType, + wr.BudgetWageRateLockFlag, + wr.ProjectionWageRateLockType, + wr.ProjectionWageRateLockFlag, + + -- Target Montly Values + wr.TargetAdjusted01, + wr.TargetAdjusted02, + wr.TargetAdjusted03, + wr.TargetAdjusted04, + wr.TargetAdjusted05, + wr.TargetAdjusted06, + wr.TargetAdjusted07, + wr.TargetAdjusted08, + wr.TargetAdjusted09, + wr.TargetAdjusted10, + wr.TargetAdjusted11, + wr.TargetAdjusted12, + + -- Budgeted Monthly Values + wr.BudgetAdjusted01, + wr.BudgetAdjusted02, + wr.BudgetAdjusted03, + wr.BudgetAdjusted04, + wr.BudgetAdjusted05, + wr.BudgetAdjusted06, + wr.BudgetAdjusted07, + wr.BudgetAdjusted08, + wr.BudgetAdjusted09, + wr.BudgetAdjusted10, + wr.BudgetAdjusted11, + wr.BudgetAdjusted12, + + -- Projected Monthly Values + wr.ProjectionAdjusted01, + wr.ProjectionAdjusted02, + wr.ProjectionAdjusted03, + wr.ProjectionAdjusted04, + wr.ProjectionAdjusted05, + wr.ProjectionAdjusted06, + wr.ProjectionAdjusted07, + wr.ProjectionAdjusted08, + wr.ProjectionAdjusted09, + wr.ProjectionAdjusted10, + wr.ProjectionAdjusted11, + wr.ProjectionAdjusted12, + + -- Initial + wr.InitialBudget01, + wr.InitialBudget02, + wr.InitialBudget03, + wr.InitialBudget04, + wr.InitialBudget05, + wr.InitialBudget06, + wr.InitialBudget07, + wr.InitialBudget08, + wr.InitialBudget09, + wr.InitialBudget10, + wr.InitialBudget11, + wr.InitialBudget12, + + -- Sampled + wr.SampledBudget01, + wr.SampledBudget02, + wr.SampledBudget03, + wr.SampledBudget04, + wr.SampledBudget05, + wr.SampledBudget06, + wr.SampledBudget07, + wr.SampledBudget08, + wr.SampledBudget09, + wr.SampledBudget10, + wr.SampledBudget11, + wr.SampledBudget12, + + -- Sampled Projection + wr.SampledProjection01, + wr.SampledProjection02, + wr.SampledProjection03, + wr.SampledProjection04, + wr.SampledProjection05, + wr.SampledProjection06, + wr.SampledProjection07, + wr.SampledProjection08, + wr.SampledProjection09, + wr.SampledProjection10, + wr.SampledProjection11, + wr.SampledProjection12, + + -- Target Percent Adjustment Factor Values + wr.TargetPercentAdjustmentFactor01, + wr.TargetPercentAdjustmentFactor02, + wr.TargetPercentAdjustmentFactor03, + wr.TargetPercentAdjustmentFactor04, + wr.TargetPercentAdjustmentFactor05, + wr.TargetPercentAdjustmentFactor06, + wr.TargetPercentAdjustmentFactor07, + wr.TargetPercentAdjustmentFactor08, + wr.TargetPercentAdjustmentFactor09, + wr.TargetPercentAdjustmentFactor10, + wr.TargetPercentAdjustmentFactor11, + wr.TargetPercentAdjustmentFactor12, + + -- Budgeted Percent Adjustment Factor Values + wr.BudgetPercentAdjustmentFactor01, + wr.BudgetPercentAdjustmentFactor02, + wr.BudgetPercentAdjustmentFactor03, + wr.BudgetPercentAdjustmentFactor04, + wr.BudgetPercentAdjustmentFactor05, + wr.BudgetPercentAdjustmentFactor06, + wr.BudgetPercentAdjustmentFactor07, + wr.BudgetPercentAdjustmentFactor08, + wr.BudgetPercentAdjustmentFactor09, + wr.BudgetPercentAdjustmentFactor10, + wr.BudgetPercentAdjustmentFactor11, + wr.BudgetPercentAdjustmentFactor12, + + -- Projected Percent Adjustment Factor Values + wr.ProjectionPercentAdjustmentFactor01, + wr.ProjectionPercentAdjustmentFactor02, + wr.ProjectionPercentAdjustmentFactor03, + wr.ProjectionPercentAdjustmentFactor04, + wr.ProjectionPercentAdjustmentFactor05, + wr.ProjectionPercentAdjustmentFactor06, + wr.ProjectionPercentAdjustmentFactor07, + wr.ProjectionPercentAdjustmentFactor08, + wr.ProjectionPercentAdjustmentFactor09, + wr.ProjectionPercentAdjustmentFactor10, + wr.ProjectionPercentAdjustmentFactor11, + wr.ProjectionPercentAdjustmentFactor12 + FROM [fp].[Staffing] fs (READUNCOMMITTED) + INNER JOIN [fp].[StaffingWageRate] wr (READUNCOMMITTED) ON fs.StaffingWageRateID = wr.StaffingWageRateID + WHERE fs.VariabilityID = 1 -- Filtering so we only get 1 row +GO + + +--------------------------------------------- + +-- fp.viewStaffing_DepartmentManager +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-10-10 MY JAZZ-61397 Update Staffing/Provider Comp adjustments to support data model changes +** 2 2024-02-16 BK JAZZ-67683 Change WageRate VariabilityID to 3 instead of 1 +*************************************************************/ +CREATE VIEW [fp].[viewStaffing_DepartmentManager] +AS + SELECT + staff.StaffingID, + staff.BudgetConfigID, + staff.EntityGroupConfigID, + staff.EntityID, + staff.DepartmentID, + staff.JobCodeID, + staff.PayCodeGroupID, + staff.ProductiveClassID, + staff.VariabilityID, + staff.EmployeeID, + staff.ProviderID, + staff.ProviderTypeID, + staff.ProviderSpecialtyID, + staff.ProviderLineItemID, + staff.SubsectionID, + 34 AS UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + m.FiscalMonthID, + staff.TargetDollarsLockFlag AS HasFinalValueAdjustment, + Target AS Value, + Budget AS ManagerValue + FROM fp.Staffing staff + INNER JOIN fp.BudgetConfig bc ON staff.BudgetConfigID = bc.BudgetConfigID + CROSS APPLY ( + VALUES + (01, TargetAdjustedDollars01, BudgetAdjustedDollars01), + (02, TargetAdjustedDollars02, BudgetAdjustedDollars02), + (03, TargetAdjustedDollars03, BudgetAdjustedDollars03), + (04, TargetAdjustedDollars04, BudgetAdjustedDollars04), + (05, TargetAdjustedDollars05, BudgetAdjustedDollars05), + (06, TargetAdjustedDollars06, BudgetAdjustedDollars06), + (07, TargetAdjustedDollars07, BudgetAdjustedDollars07), + (08, TargetAdjustedDollars08, BudgetAdjustedDollars08), + (09, TargetAdjustedDollars09, BudgetAdjustedDollars09), + (10, TargetAdjustedDollars10, BudgetAdjustedDollars10), + (11, TargetAdjustedDollars11, BudgetAdjustedDollars11), + (12, TargetAdjustedDollars12, BudgetAdjustedDollars12) + ) AS CrossApplied (MonthSortOrder, Target, Budget) + LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder + UNION ALL + SELECT + staff.StaffingID, + staff.BudgetConfigID, + staff.EntityGroupConfigID, + staff.EntityID, + staff.DepartmentID, + staff.JobCodeID, + staff.PayCodeGroupID, + staff.ProductiveClassID, + staff.VariabilityID, + staff.EmployeeID, + staff.ProviderID, + staff.ProviderTypeID, + staff.ProviderSpecialtyID, + staff.ProviderLineItemID, + staff.SubsectionID, + 51 AS UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + m.FiscalMonthID, + staff.TargetHoursLockFlag AS HasFinalValueAdjustment, + Target AS Value, + Budget AS ManagerValue + FROM fp.Staffing staff + INNER JOIN fp.BudgetConfig bc ON staff.BudgetConfigID = bc.BudgetConfigID + CROSS APPLY ( + VALUES + (01, TargetAdjustedHours01, BudgetAdjustedHours01), + (02, TargetAdjustedHours02, BudgetAdjustedHours02), + (03, TargetAdjustedHours03, BudgetAdjustedHours03), + (04, TargetAdjustedHours04, BudgetAdjustedHours04), + (05, TargetAdjustedHours05, BudgetAdjustedHours05), + (06, TargetAdjustedHours06, BudgetAdjustedHours06), + (07, TargetAdjustedHours07, BudgetAdjustedHours07), + (08, TargetAdjustedHours08, BudgetAdjustedHours08), + (09, TargetAdjustedHours09, BudgetAdjustedHours09), + (10, TargetAdjustedHours10, BudgetAdjustedHours10), + (11, TargetAdjustedHours11, BudgetAdjustedHours11), + (12, TargetAdjustedHours12, BudgetAdjustedHours12) + ) AS CrossApplied (MonthSortOrder, Target, Budget) + LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder + UNION ALL + SELECT + staff.StaffingID, + staff.BudgetConfigID, + staff.EntityGroupConfigID, + staff.EntityID, + staff.DepartmentID, + staff.JobCodeID, + staff.PayCodeGroupID, + staff.ProductiveClassID, + staff.VariabilityID, + staff.EmployeeID, + staff.ProviderID, + staff.ProviderTypeID, + staff.ProviderSpecialtyID, + staff.ProviderLineItemID, + staff.SubsectionID, + 144 AS UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + m.FiscalMonthID, + staff.TargetFTEsLockFlag AS HasFinalValueAdjustment, + Target AS Value, + Budget AS ManagerValue + FROM fp.Staffing staff + INNER JOIN fp.BudgetConfig bc ON staff.BudgetConfigID = bc.BudgetConfigID + CROSS APPLY ( + VALUES + (01, TargetAdjustedFTEs01, BudgetAdjustedFTEs01), + (02, TargetAdjustedFTEs02, BudgetAdjustedFTEs02), + (03, TargetAdjustedFTEs03, BudgetAdjustedFTEs03), + (04, TargetAdjustedFTEs04, BudgetAdjustedFTEs04), + (05, TargetAdjustedFTEs05, BudgetAdjustedFTEs05), + (06, TargetAdjustedFTEs06, BudgetAdjustedFTEs06), + (07, TargetAdjustedFTEs07, BudgetAdjustedFTEs07), + (08, TargetAdjustedFTEs08, BudgetAdjustedFTEs08), + (09, TargetAdjustedFTEs09, BudgetAdjustedFTEs09), + (10, TargetAdjustedFTEs10, BudgetAdjustedFTEs10), + (11, TargetAdjustedFTEs11, BudgetAdjustedFTEs11), + (12, TargetAdjustedFTEs12, BudgetAdjustedFTEs12) + ) AS CrossApplied (MonthSortOrder, Target, Budget) + LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder + UNION ALL + SELECT + staff.StaffingID, + staff.BudgetConfigID, + staff.EntityGroupConfigID, + staff.EntityID, + staff.DepartmentID, + staff.JobCodeID, + staff.PayCodeGroupID, + staff.ProductiveClassID, + staff.VariabilityID, + staff.EmployeeID, + staff.ProviderID, + staff.ProviderTypeID, + staff.ProviderSpecialtyID, + staff.ProviderLineItemID, + staff.SubsectionID, + CASE WHEN staff.SubsectionID = 3 THEN 172 ELSE 33 END AS UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + m.FiscalMonthID, + 0 AS HasFinalValueAdjustment, + Target AS Value, + Budget AS ManagerValue + FROM fp.Staffing staff + INNER JOIN fp.BudgetConfig bc ON staff.BudgetConfigID = bc.BudgetConfigID + CROSS APPLY ( + VALUES + (01, TargetAdjustedRate01, BudgetAdjustedRate01), + (02, TargetAdjustedRate02, BudgetAdjustedRate02), + (03, TargetAdjustedRate03, BudgetAdjustedRate03), + (04, TargetAdjustedRate04, BudgetAdjustedRate04), + (05, TargetAdjustedRate05, BudgetAdjustedRate05), + (06, TargetAdjustedRate06, BudgetAdjustedRate06), + (07, TargetAdjustedRate07, BudgetAdjustedRate07), + (08, TargetAdjustedRate08, BudgetAdjustedRate08), + (09, TargetAdjustedRate09, BudgetAdjustedRate09), + (10, TargetAdjustedRate10, BudgetAdjustedRate10), + (11, TargetAdjustedRate11, BudgetAdjustedRate11), + (12, TargetAdjustedRate12, BudgetAdjustedRate12) + ) AS CrossApplied (MonthSortOrder, Target, Budget) + LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder + UNION ALL + SELECT + staff.StaffingID, + staff.BudgetConfigID, + staff.EntityGroupConfigID, + staff.EntityID, + staff.DepartmentID, + staff.JobCodeID, + staff.PayCodeGroupID, + staff.ProductiveClassID, + staff.VariabilityID, + staff.EmployeeID, + staff.ProviderID, + staff.ProviderTypeID, + staff.ProviderSpecialtyID, + staff.ProviderLineItemID, + staff.SubsectionID, + 34 AS UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID - 1AS FiscalYearID, + m.FiscalMonthID, + staff.ProjectionDollarsLockFlag AS HasFinalValueAdjustment, + Projection AS Value, + Projection AS ManagerValue + FROM fp.Staffing staff + INNER JOIN fp.BudgetConfig bc ON staff.BudgetConfigID = bc.BudgetConfigID + CROSS APPLY ( + VALUES + (01, ProjectionAdjustedDollars01), + (02, ProjectionAdjustedDollars02), + (03, ProjectionAdjustedDollars03), + (04, ProjectionAdjustedDollars04), + (05, ProjectionAdjustedDollars05), + (06, ProjectionAdjustedDollars06), + (07, ProjectionAdjustedDollars07), + (08, ProjectionAdjustedDollars08), + (09, ProjectionAdjustedDollars09), + (10, ProjectionAdjustedDollars10), + (11, ProjectionAdjustedDollars11), + (12, ProjectionAdjustedDollars12) + ) AS CrossApplied (MonthSortOrder, Projection) + LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder + UNION ALL + SELECT + staff.StaffingID, + staff.BudgetConfigID, + staff.EntityGroupConfigID, + staff.EntityID, + staff.DepartmentID, + staff.JobCodeID, + staff.PayCodeGroupID, + staff.ProductiveClassID, + staff.VariabilityID, + staff.EmployeeID, + staff.ProviderID, + staff.ProviderTypeID, + staff.ProviderSpecialtyID, + staff.ProviderLineItemID, + staff.SubsectionID, + 51 AS UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID - 1 AS FiscalYearID, + m.FiscalMonthID, + staff.ProjectionHoursLockFlag AS HasFinalValueAdjustment, + Projection AS Value, + Projection AS ManagerValue + FROM fp.Staffing staff + INNER JOIN fp.BudgetConfig bc ON staff.BudgetConfigID = bc.BudgetConfigID + CROSS APPLY ( + VALUES + (01, ProjectionAdjustedHours01), + (02, ProjectionAdjustedHours02), + (03, ProjectionAdjustedHours03), + (04, ProjectionAdjustedHours04), + (05, ProjectionAdjustedHours05), + (06, ProjectionAdjustedHours06), + (07, ProjectionAdjustedHours07), + (08, ProjectionAdjustedHours08), + (09, ProjectionAdjustedHours09), + (10, ProjectionAdjustedHours10), + (11, ProjectionAdjustedHours11), + (12, ProjectionAdjustedHours12) + ) AS CrossApplied (MonthSortOrder, Projection) + LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder + UNION ALL + SELECT + staff.StaffingID, + staff.BudgetConfigID, + staff.EntityGroupConfigID, + staff.EntityID, + staff.DepartmentID, + staff.JobCodeID, + staff.PayCodeGroupID, + staff.ProductiveClassID, + staff.VariabilityID, + staff.EmployeeID, + staff.ProviderID, + staff.ProviderTypeID, + staff.ProviderSpecialtyID, + staff.ProviderLineItemID, + staff.SubsectionID, + 144 AS UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID - 1 AS FiscalYearID, + m.FiscalMonthID, + staff.ProjectionFTEsLockFlag AS HasFinalValueAdjustment, + Projection AS Value, + Projection AS ManagerValue + FROM fp.Staffing staff + INNER JOIN fp.BudgetConfig bc ON staff.BudgetConfigID = bc.BudgetConfigID + CROSS APPLY ( + VALUES + (01, ProjectionAdjustedFTEs01), + (02, ProjectionAdjustedFTEs02), + (03, ProjectionAdjustedFTEs03), + (04, ProjectionAdjustedFTEs04), + (05, ProjectionAdjustedFTEs05), + (06, ProjectionAdjustedFTEs06), + (07, ProjectionAdjustedFTEs07), + (08, ProjectionAdjustedFTEs08), + (09, ProjectionAdjustedFTEs09), + (10, ProjectionAdjustedFTEs10), + (11, ProjectionAdjustedFTEs11), + (12, ProjectionAdjustedFTEs12) + ) AS CrossApplied (MonthSortOrder, Projection) + LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder + UNION ALL + SELECT + staff.StaffingID, + staff.BudgetConfigID, + staff.EntityGroupConfigID, + staff.EntityID, + staff.DepartmentID, + staff.JobCodeID, + staff.PayCodeGroupID, + staff.ProductiveClassID, + staff.VariabilityID, + staff.EmployeeID, + staff.ProviderID, + staff.ProviderTypeID, + staff.ProviderSpecialtyID, + staff.ProviderLineItemID, + staff.SubsectionID, + CASE WHEN staff.SubsectionID = 3 THEN 172 ELSE 33 END AS UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID - 1 AS FiscalYearID, + m.FiscalMonthID, + 0 AS HasFinalValueAdjustment, + Projection AS Value, + Projection AS ManagerValue + FROM fp.Staffing staff + INNER JOIN fp.BudgetConfig bc ON staff.BudgetConfigID = bc.BudgetConfigID + CROSS APPLY ( + VALUES + (01, ProjectionAdjustedRate01), + (02, ProjectionAdjustedRate02), + (03, ProjectionAdjustedRate03), + (04, ProjectionAdjustedRate04), + (05, ProjectionAdjustedRate05), + (06, ProjectionAdjustedRate06), + (07, ProjectionAdjustedRate07), + (08, ProjectionAdjustedRate08), + (09, ProjectionAdjustedRate09), + (10, ProjectionAdjustedRate10), + (11, ProjectionAdjustedRate11), + (12, ProjectionAdjustedRate12) + ) AS CrossApplied (MonthSortOrder, Projection) + LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder + UNION ALL + SELECT + staff.StaffingID, + staff.BudgetConfigID, + staff.EntityGroupConfigID, + staff.EntityID, + staff.DepartmentID, + staff.JobCodeID, + staff.PayCodeGroupID, + staff.ProductiveClassID, + 3 as VariabilityID, + staff.EmployeeID, + staff.ProviderID, + staff.ProviderTypeID, + staff.ProviderSpecialtyID, + staff.ProviderLineItemID, + staff.SubsectionID, + 159 AS UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID AS FiscalYearID, + m.FiscalMonthID, + swr.TargetWageRateLockFlag AS HasFinalValueAdjustment, + Target AS Value, + Budget AS ManagerValue + FROM fp.StaffingWageRate swr + INNER JOIN fp.Staffing staff ON swr.StaffingWageRateID = staff.StaffingWageRateID AND staff.VariabilityID = 1 -- Just doing this for 1 row since it'll be the same for both Fixed/Variable + INNER JOIN fp.BudgetConfig bc ON staff.BudgetConfigID = bc.BudgetConfigID + CROSS APPLY ( + VALUES + (01, TargetAdjusted01, BudgetAdjusted01), + (02, TargetAdjusted02, BudgetAdjusted02), + (03, TargetAdjusted03, BudgetAdjusted03), + (04, TargetAdjusted04, BudgetAdjusted04), + (05, TargetAdjusted05, BudgetAdjusted05), + (06, TargetAdjusted06, BudgetAdjusted06), + (07, TargetAdjusted07, BudgetAdjusted07), + (08, TargetAdjusted08, BudgetAdjusted08), + (09, TargetAdjusted09, BudgetAdjusted09), + (10, TargetAdjusted10, BudgetAdjusted10), + (11, TargetAdjusted11, BudgetAdjusted11), + (12, TargetAdjusted12, BudgetAdjusted12) + ) AS CrossApplied (MonthSortOrder, Target, Budget) + LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder + UNION ALL + SELECT + staff.StaffingID, + staff.BudgetConfigID, + staff.EntityGroupConfigID, + staff.EntityID, + staff.DepartmentID, + staff.JobCodeID, + staff.PayCodeGroupID, + staff.ProductiveClassID, + 3 as VariabilityID, + staff.EmployeeID, + staff.ProviderID, + staff.ProviderTypeID, + staff.ProviderSpecialtyID, + staff.ProviderLineItemID, + staff.SubsectionID, + 159 AS UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID - 1AS FiscalYearID, + m.FiscalMonthID, + swr.ProjectionWageRateLockFlag AS HasFinalValueAdjustment, + Projection AS Value, + Projection AS ManagerValue + FROM fp.StaffingWageRate swr + INNER JOIN fp.Staffing staff ON swr.StaffingWageRateID = staff.StaffingWageRateID AND staff.VariabilityID = 1 -- Just doing this for 1 row since it'll be the same for both Fixed/Variable + INNER JOIN fp.BudgetConfig bc ON staff.BudgetConfigID = bc.BudgetConfigID + CROSS APPLY ( + VALUES + (01, ProjectionAdjusted01), + (02, ProjectionAdjusted02), + (03, ProjectionAdjusted03), + (04, ProjectionAdjusted04), + (05, ProjectionAdjusted05), + (06, ProjectionAdjusted06), + (07, ProjectionAdjusted07), + (08, ProjectionAdjusted08), + (09, ProjectionAdjusted09), + (10, ProjectionAdjusted10), + (11, ProjectionAdjusted11), + (12, ProjectionAdjusted12) + ) AS CrossApplied (MonthSortOrder, Projection) + LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder +GO + + +--------------------------------------------- + +-- fp.viewStaffing_Unpivoted +CREATE VIEW [fp].[viewStaffing_Unpivoted] +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-11-16 BW JAZZ-60740 Data model restructure + *************************************************************/ + +SELECT staff.StaffingID, + staff.BudgetConfigID, + staff.EntityGroupConfigID, + staff.EntityID, + staff.DepartmentID, + staff.JobCodeID, + staff.PayCodeGroupID, + staff.ProductiveClassID, + staff.VariabilityID, + staff.EmployeeID, + staff.ProviderID, + staff.ProviderTypeID, + staff.ProviderSpecialtyID, + staff.ProviderLineItemID, + staff.SubsectionID, + staff.FlexingTypeID, + ut.UnitTypeID, + TargetLockType, + TargetLockFlag, + BudgetLockType, + BudgetLockFlag, + ProjectionLockType, + ProjectionLockFlag, + BudgetSpreadsLockFlag, + BudgetAdjustmentLockFlag, + TargetAdjustmentLockFlag, + ProjectionAdjustmentLockFlag, + WageRateTargetLockType, + WageRateTargetLockFlag, + WageRateBudgetLockType, + WageRateBudgetLockFlag, + WageRateProjectionLockType, + WageRateProjectionLockFlag, + AdjustedValueTotal, + ManagerAdjustedValueTotal, + ManagerAdjustedProjectionValueTotal, + AdjustedProjectionValueTotal, + ActualYTDValueTotal, + CurrentYearBudgetTotal, + PriorYearActualValueTotal, + InitialBudgetTotal, + InitialBudget01, + InitialBudget02, + InitialBudget03, + InitialBudget04, + InitialBudget05, + InitialBudget06, + InitialBudget07, + InitialBudget08, + InitialBudget09, + InitialBudget10, + InitialBudget11, + InitialBudget12, + InitialProjectionTotal, + IsFlexedByStats, + AdjustedValue01, + AdjustedValue02, + AdjustedValue03, + AdjustedValue04, + AdjustedValue05, + AdjustedValue06, + AdjustedValue07, + AdjustedValue08, + AdjustedValue09, + AdjustedValue10, + AdjustedValue11, + AdjustedValue12, + ManagerAdjustedValue01, + ManagerAdjustedValue02, + ManagerAdjustedValue03, + ManagerAdjustedValue04, + ManagerAdjustedValue05, + ManagerAdjustedValue06, + ManagerAdjustedValue07, + ManagerAdjustedValue08, + ManagerAdjustedValue09, + ManagerAdjustedValue10, + ManagerAdjustedValue11, + ManagerAdjustedValue12, + AdjustedProjectionValue01, + AdjustedProjectionValue02, + AdjustedProjectionValue03, + AdjustedProjectionValue04, + AdjustedProjectionValue05, + AdjustedProjectionValue06, + AdjustedProjectionValue07, + AdjustedProjectionValue08, + AdjustedProjectionValue09, + AdjustedProjectionValue10, + AdjustedProjectionValue11, + AdjustedProjectionValue12, + ManagerAdjustedProjectionValue01, + ManagerAdjustedProjectionValue02, + ManagerAdjustedProjectionValue03, + ManagerAdjustedProjectionValue04, + ManagerAdjustedProjectionValue05, + ManagerAdjustedProjectionValue06, + ManagerAdjustedProjectionValue07, + ManagerAdjustedProjectionValue08, + ManagerAdjustedProjectionValue09, + ManagerAdjustedProjectionValue10, + ManagerAdjustedProjectionValue11, + ManagerAdjustedProjectionValue12 +FROM fp.Staffing staff (READUNCOMMITTED) + INNER JOIN [fp].[StaffingHistory] hist (READUNCOMMITTED) ON staff.StaffingID = hist.StaffingID + CROSS APPLY ( + VALUES + ( 34, TargetDollarsLockType, TargetDollarsLockFlag, BudgetDollarsLockType, BudgetDollarsLockFlag, + ProjectionDollarsLockType, ProjectionDollarsLockFlag, + CASE WHEN BudgetDollarsLockType = 6 THEN 1 ELSE 0 END, + CASE WHEN BudgetDollarsLockType = 7 THEN 1 ELSE 0 END, + CASE WHEN TargetDollarsLockType = 7 THEN 1 ELSE 0 END, + CASE WHEN ProjectionDollarsLockType = 7 THEN 1 ELSE 0 END, 0, 0, 0, 0, 0, 0, TargetAdjustedDollarsTotal, BudgetAdjustedDollarsTotal, + ProjectionAdjustedDollarsTotal, ProjectionAdjustedDollarsTotal, hist.ActualYTDDollarsTotal, + hist.CurrentYearBudgetDollarsTotal, hist.PriorYearActualDollarsTotal, InitialBudgetDollarsTotal, + InitialBudgetDollars01, InitialBudgetDollars02, InitialBudgetDollars03, InitialBudgetDollars04, + InitialBudgetDollars05, InitialBudgetDollars06, InitialBudgetDollars07, InitialBudgetDollars08, + InitialBudgetDollars09, InitialBudgetDollars10, InitialBudgetDollars11, InitialBudgetDollars12, + InitialProjectionDollarsTotal, CASE WHEN FlexingTypeID IN ( 3, 9 ) THEN 1 ELSE 0 END, TargetAdjustedDollars01, TargetAdjustedDollars02, + TargetAdjustedDollars03, TargetAdjustedDollars04, TargetAdjustedDollars05, TargetAdjustedDollars06, + TargetAdjustedDollars07, TargetAdjustedDollars08, TargetAdjustedDollars09, TargetAdjustedDollars10, + TargetAdjustedDollars11, TargetAdjustedDollars12, BudgetAdjustedDollars01, BudgetAdjustedDollars02, + BudgetAdjustedDollars03, BudgetAdjustedDollars04, BudgetAdjustedDollars05, BudgetAdjustedDollars06, + BudgetAdjustedDollars07, BudgetAdjustedDollars08, BudgetAdjustedDollars09, BudgetAdjustedDollars10, + BudgetAdjustedDollars11, BudgetAdjustedDollars12, ProjectionAdjustedDollars01, ProjectionAdjustedDollars02, + ProjectionAdjustedDollars03, ProjectionAdjustedDollars04, ProjectionAdjustedDollars05, + ProjectionAdjustedDollars06, ProjectionAdjustedDollars07, ProjectionAdjustedDollars08, + ProjectionAdjustedDollars09, ProjectionAdjustedDollars10, ProjectionAdjustedDollars11, + ProjectionAdjustedDollars12, ProjectionAdjustedDollars01, ProjectionAdjustedDollars02, + ProjectionAdjustedDollars03, ProjectionAdjustedDollars04, ProjectionAdjustedDollars05, + ProjectionAdjustedDollars06, ProjectionAdjustedDollars07, ProjectionAdjustedDollars08, + ProjectionAdjustedDollars09, ProjectionAdjustedDollars10, ProjectionAdjustedDollars11, + ProjectionAdjustedDollars12 + ), + ( 51, TargetHoursLockType, TargetHoursLockFlag, BudgetHoursLockType, BudgetHoursLockFlag, + ProjectionHoursLockType, ProjectionHoursLockFlag, + CASE WHEN BudgetHoursLockType = 6 THEN 1 ELSE 0 END, + CASE WHEN BudgetHoursLockType = 7 THEN 1 ELSE 0 END, + CASE WHEN TargetHoursLockType = 7 THEN 1 ELSE 0 END, + CASE WHEN ProjectionHoursLockType = 7 THEN 1 ELSE 0 END, 0, 0, 0, 0, 0, 0, + TargetAdjustedHoursTotal, BudgetAdjustedHoursTotal, ProjectionAdjustedHoursTotal, + ProjectionAdjustedHoursTotal, hist.ActualYTDHoursTotal, hist.CurrentYearBudgetHoursTotal, + hist.PriorYearActualHoursTotal, InitialBudgetHoursTotal, InitialBudgetHours01, InitialBudgetHours02, + InitialBudgetHours03, InitialBudgetHours04, InitialBudgetHours05, InitialBudgetHours06, + InitialBudgetHours07, InitialBudgetHours08, InitialBudgetHours09, InitialBudgetHours10, + InitialBudgetHours11, InitialBudgetHours12, InitialProjectionHoursTotal, + CASE WHEN FlexingTypeID IN ( 3, 9 ) THEN 1 ELSE 0 END, TargetAdjustedHours01, TargetAdjustedHours02, TargetAdjustedHours03, TargetAdjustedHours04, + TargetAdjustedHours05, TargetAdjustedHours06, TargetAdjustedHours07, TargetAdjustedHours08, + TargetAdjustedHours09, TargetAdjustedHours10, TargetAdjustedHours11, TargetAdjustedHours12, + BudgetAdjustedHours01, BudgetAdjustedHours02, BudgetAdjustedHours03, BudgetAdjustedHours04, + BudgetAdjustedHours05, BudgetAdjustedHours06, BudgetAdjustedHours07, BudgetAdjustedHours08, + BudgetAdjustedHours09, BudgetAdjustedHours10, BudgetAdjustedHours11, BudgetAdjustedHours12, + ProjectionAdjustedHours01, ProjectionAdjustedHours02, ProjectionAdjustedHours03, ProjectionAdjustedHours04, + ProjectionAdjustedHours05, ProjectionAdjustedHours06, ProjectionAdjustedHours07, ProjectionAdjustedHours08, + ProjectionAdjustedHours09, ProjectionAdjustedHours10, ProjectionAdjustedHours11, ProjectionAdjustedHours12, + ProjectionAdjustedHours01, ProjectionAdjustedHours02, ProjectionAdjustedHours03, ProjectionAdjustedHours04, + ProjectionAdjustedHours05, ProjectionAdjustedHours06, ProjectionAdjustedHours07, ProjectionAdjustedHours08, + ProjectionAdjustedHours09, ProjectionAdjustedHours10, ProjectionAdjustedHours11, ProjectionAdjustedHours12 + ), + ( 144, TargetFTEsLockType, TargetFTEsLockFlag, BudgetFTEsLockType, BudgetFTEsLockFlag, + ProjectionFTEsLockType, ProjectionFTEsLockFlag, CASE WHEN BudgetFTEsLockType = 6 THEN 1 ELSE 0 END, + CASE WHEN BudgetFTEsLockType = 7 THEN 1 ELSE 0 END, + CASE WHEN TargetFTEsLockType = 7 THEN 1 ELSE 0 END, + CASE WHEN ProjectionFTEsLockType = 7 THEN 1 ELSE 0 END, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + hist.ActualYTDFTEsTotal, hist.CurrentYearBudgetFTEsTotal, hist.PriorYearActualFTEsTotal, 0, + InitialBudgetFTEs01, InitialBudgetFTEs02, InitialBudgetFTEs03, InitialBudgetFTEs04, InitialBudgetFTEs05, + InitialBudgetFTEs06, InitialBudgetFTEs07, InitialBudgetFTEs08, InitialBudgetFTEs09, InitialBudgetFTEs10, + InitialBudgetFTEs11, InitialBudgetFTEs12, 0, CASE WHEN FlexingTypeID IN ( 3, 9 ) THEN 1 ELSE 0 END, TargetAdjustedFTEs01, TargetAdjustedFTEs02, + TargetAdjustedFTEs03, TargetAdjustedFTEs04, TargetAdjustedFTEs05, TargetAdjustedFTEs06, + TargetAdjustedFTEs07, TargetAdjustedFTEs08, TargetAdjustedFTEs09, TargetAdjustedFTEs10, + TargetAdjustedFTEs11, TargetAdjustedFTEs12, BudgetAdjustedFTEs01, BudgetAdjustedFTEs02, + BudgetAdjustedFTEs03, BudgetAdjustedFTEs04, BudgetAdjustedFTEs05, BudgetAdjustedFTEs06, + BudgetAdjustedFTEs07, BudgetAdjustedFTEs08, BudgetAdjustedFTEs09, BudgetAdjustedFTEs10, + BudgetAdjustedFTEs11, BudgetAdjustedFTEs12, ProjectionAdjustedFTEs01, ProjectionAdjustedFTEs02, + ProjectionAdjustedFTEs03, ProjectionAdjustedFTEs04, ProjectionAdjustedFTEs05, ProjectionAdjustedFTEs06, + ProjectionAdjustedFTEs07, ProjectionAdjustedFTEs08, ProjectionAdjustedFTEs09, ProjectionAdjustedFTEs10, + ProjectionAdjustedFTEs11, ProjectionAdjustedFTEs12, ProjectionAdjustedFTEs01, ProjectionAdjustedFTEs02, + ProjectionAdjustedFTEs03, ProjectionAdjustedFTEs04, ProjectionAdjustedFTEs05, ProjectionAdjustedFTEs06, + ProjectionAdjustedFTEs07, ProjectionAdjustedFTEs08, ProjectionAdjustedFTEs09, ProjectionAdjustedFTEs10, + ProjectionAdjustedFTEs11, ProjectionAdjustedFTEs12 + ), + ( 172, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, InitialBudgetRate01, + InitialBudgetRate02, InitialBudgetRate03, InitialBudgetRate04, InitialBudgetRate05, InitialBudgetRate06, + InitialBudgetRate07, InitialBudgetRate08, InitialBudgetRate09, InitialBudgetRate10, InitialBudgetRate11, + InitialBudgetRate12, 0, CASE WHEN FlexingTypeID IN ( 3, 9 ) THEN 1 ELSE 0 END, TargetAdjustedRate01, TargetAdjustedRate02, TargetAdjustedRate03, + TargetAdjustedRate04, TargetAdjustedRate05, TargetAdjustedRate06, TargetAdjustedRate07, + TargetAdjustedRate08, TargetAdjustedRate09, TargetAdjustedRate10, TargetAdjustedRate11, + TargetAdjustedRate12, BudgetAdjustedRate01, BudgetAdjustedRate02, BudgetAdjustedRate03, + BudgetAdjustedRate04, BudgetAdjustedRate05, BudgetAdjustedRate06, BudgetAdjustedRate07, + BudgetAdjustedRate08, BudgetAdjustedRate09, BudgetAdjustedRate10, BudgetAdjustedRate11, + BudgetAdjustedRate12, ProjectionAdjustedRate01, ProjectionAdjustedRate02, ProjectionAdjustedRate03, + ProjectionAdjustedRate04, ProjectionAdjustedRate05, ProjectionAdjustedRate06, ProjectionAdjustedRate07, + ProjectionAdjustedRate08, ProjectionAdjustedRate09, ProjectionAdjustedRate10, ProjectionAdjustedRate11, + ProjectionAdjustedRate12, ProjectionAdjustedRate01, ProjectionAdjustedRate02, ProjectionAdjustedRate03, + ProjectionAdjustedRate04, ProjectionAdjustedRate05, ProjectionAdjustedRate06, ProjectionAdjustedRate07, + ProjectionAdjustedRate08, ProjectionAdjustedRate09, ProjectionAdjustedRate10, ProjectionAdjustedRate11, + ProjectionAdjustedRate12 + ) +) AS CrossApplied (UnitTypeID, TargetLockType, TargetLockFlag, BudgetLockType, BudgetLockFlag, ProjectionLockType, + ProjectionLockFlag, BudgetSpreadsLockFlag, BudgetAdjustmentLockFlag, TargetAdjustmentLockFlag, + ProjectionAdjustmentLockFlag, WageRateTargetLockType, WageRateTargetLockFlag, + WageRateBudgetLockType, WageRateBudgetLockFlag, WageRateProjectionLockType, + WageRateProjectionLockFlag, AdjustedValueTotal, ManagerAdjustedValueTotal, + ManagerAdjustedProjectionValueTotal, AdjustedProjectionValueTotal, ActualYTDValueTotal, + CurrentYearBudgetTotal, PriorYearActualValueTotal, InitialBudgetTotal, InitialBudget01, + InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, + InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, + InitialBudget12, InitialProjectionTotal, IsFlexedByStats, AdjustedValue01, AdjustedValue02, + AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, + AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12, + ManagerAdjustedValue01, ManagerAdjustedValue02, ManagerAdjustedValue03, ManagerAdjustedValue04, + ManagerAdjustedValue05, ManagerAdjustedValue06, ManagerAdjustedValue07, ManagerAdjustedValue08, + ManagerAdjustedValue09, ManagerAdjustedValue10, ManagerAdjustedValue11, ManagerAdjustedValue12, + AdjustedProjectionValue01, AdjustedProjectionValue02, AdjustedProjectionValue03, + AdjustedProjectionValue04, AdjustedProjectionValue05, AdjustedProjectionValue06, + AdjustedProjectionValue07, AdjustedProjectionValue08, AdjustedProjectionValue09, + AdjustedProjectionValue10, AdjustedProjectionValue11, AdjustedProjectionValue12, + ManagerAdjustedProjectionValue01, ManagerAdjustedProjectionValue02, + ManagerAdjustedProjectionValue03, ManagerAdjustedProjectionValue04, + ManagerAdjustedProjectionValue05, ManagerAdjustedProjectionValue06, + ManagerAdjustedProjectionValue07, ManagerAdjustedProjectionValue08, + ManagerAdjustedProjectionValue09, ManagerAdjustedProjectionValue10, + ManagerAdjustedProjectionValue11, ManagerAdjustedProjectionValue12 + ) + LEFT JOIN fw.DimUnitType ut ON ut.UnitTypeID = CrossApplied.UnitTypeID + +UNION ALL + +-- Wage Rate +SELECT staff.StaffingID, + staff.BudgetConfigID, + staff.EntityGroupConfigID, + staff.EntityID, + staff.DepartmentID, + staff.JobCodeID, + staff.PayCodeGroupID, + staff.ProductiveClassID, + 3 AS VariabilityID, + staff.EmployeeID, + staff.ProviderID, + staff.ProviderTypeID, + staff.ProviderSpecialtyID, + staff.ProviderLineItemID, + staff.SubsectionID, + staff.FlexingTypeID, + 159 AS UnitTypeID, + 0 as TargetLockType, + 0 as TargetLockFlag, + 0 as BudgetLockType, + 0 as BudgetLockFlag, + 0 as ProjectionLockType, + 0 as ProjectionLockFlag, + 0 AS BudgetSpreadsLockFlag, + 0 AS BudgetAdjustmentLockFlag, + 0 AS TargetAdjustmentLockFlag, + 0 AS ProjectionAdjustmentLockFlag, + wr.TargetWageRateLockType as WageRateTargetLockType, + wr.TargetWageRateLockFlag as WageRateTargetLockFlag, + wr.BudgetWageRateLockType as WageRateBudgetLockType, + wr.BudgetWageRateLockFlag as WageRateBudgetLockFlag, + wr.ProjectionWageRateLockType as WageRateProjectionLockType, + wr.ProjectionWageRateLockFlag as WageRateProjectionLockFlag, + 0 as AdjustedValueTotal, + 0 as ManagerAdjustedValueTotal, + 0 as ManagerAdjustedProjectionValueTotal, + 0 as AdjustedProjectionValueTotal, + 0 as ActualYTDValueTotal, + 0 as CurrentYearBudgetTotal, + 0 as PriorYearActualValueTotal, + 0 as InitialBudgetTotal, + wr.InitialBudget01 AS InitialBudget01, + wr.InitialBudget02 AS InitialBudget02, + wr.InitialBudget03 AS InitialBudget03, + wr.InitialBudget04 AS InitialBudget04, + wr.InitialBudget05 AS InitialBudget05, + wr.InitialBudget06 AS InitialBudget06, + wr.InitialBudget07 AS InitialBudget07, + wr.InitialBudget08 AS InitialBudget08, + wr.InitialBudget09 AS InitialBudget09, + wr.InitialBudget10 AS InitialBudget10, + wr.InitialBudget11 AS InitialBudget11, + wr.InitialBudget12 AS InitialBudget12, + 0 as InitialProjectionTotal, + 0 AS IsFlexedByStats, + wr.TargetAdjusted01 AS AdjustedValue01, + wr.TargetAdjusted02 AS AdjustedValue02, + wr.TargetAdjusted03 AS AdjustedValue03, + wr.TargetAdjusted04 AS AdjustedValue04, + wr.TargetAdjusted05 AS AdjustedValue05, + wr.TargetAdjusted06 AS AdjustedValue06, + wr.TargetAdjusted07 AS AdjustedValue07, + wr.TargetAdjusted08 AS AdjustedValue08, + wr.TargetAdjusted09 AS AdjustedValue09, + wr.TargetAdjusted10 AS AdjustedValue10, + wr.TargetAdjusted11 AS AdjustedValue11, + wr.TargetAdjusted12 AS AdjustedValue12, + wr.BudgetAdjusted01 AS ManagerAdjustedValue01, + wr.BudgetAdjusted02 AS ManagerAdjustedValue02, + wr.BudgetAdjusted03 AS ManagerAdjustedValue03, + wr.BudgetAdjusted04 AS ManagerAdjustedValue04, + wr.BudgetAdjusted05 AS ManagerAdjustedValue05, + wr.BudgetAdjusted06 AS ManagerAdjustedValue06, + wr.BudgetAdjusted07 AS ManagerAdjustedValue07, + wr.BudgetAdjusted08 AS ManagerAdjustedValue08, + wr.BudgetAdjusted09 AS ManagerAdjustedValue09, + wr.BudgetAdjusted10 AS ManagerAdjustedValue10, + wr.BudgetAdjusted11 AS ManagerAdjustedValue11, + wr.BudgetAdjusted12 AS ManagerAdjustedValue12, + wr.ProjectionAdjusted01 AS AdjustedProjectionValue01, + wr.ProjectionAdjusted02 AS AdjustedProjectionValue02, + wr.ProjectionAdjusted03 AS AdjustedProjectionValue03, + wr.ProjectionAdjusted04 AS AdjustedProjectionValue04, + wr.ProjectionAdjusted05 AS AdjustedProjectionValue05, + wr.ProjectionAdjusted06 AS AdjustedProjectionValue06, + wr.ProjectionAdjusted07 AS AdjustedProjectionValue07, + wr.ProjectionAdjusted08 AS AdjustedProjectionValue08, + wr.ProjectionAdjusted09 AS AdjustedProjectionValue09, + wr.ProjectionAdjusted10 AS AdjustedProjectionValue10, + wr.ProjectionAdjusted11 AS AdjustedProjectionValue11, + wr.ProjectionAdjusted12 AS AdjustedProjectionValue12, + wr.ProjectionAdjusted01 AS ManagerAdjustedProjectionValue01, + wr.ProjectionAdjusted02 AS ManagerAdjustedProjectionValue02, + wr.ProjectionAdjusted03 AS ManagerAdjustedProjectionValue03, + wr.ProjectionAdjusted04 AS ManagerAdjustedProjectionValue04, + wr.ProjectionAdjusted05 AS ManagerAdjustedProjectionValue05, + wr.ProjectionAdjusted06 AS ManagerAdjustedProjectionValue06, + wr.ProjectionAdjusted07 AS ManagerAdjustedProjectionValue07, + wr.ProjectionAdjusted08 AS ManagerAdjustedProjectionValue08, + wr.ProjectionAdjusted09 AS ManagerAdjustedProjectionValue09, + wr.ProjectionAdjusted10 AS ManagerAdjustedProjectionValue10, + wr.ProjectionAdjusted11 AS ManagerAdjustedProjectionValue11, + wr.ProjectionAdjusted12 AS ManagerAdjustedProjectionValue12 +FROM [fp].[Staffing] staff (READUNCOMMITTED) + INNER JOIN [fp].[StaffingWageRate] wr (READUNCOMMITTED) + ON staff.StaffingWageRateID = wr.StaffingWageRateID +WHERE staff.VariabilityID = 1 +GO + + +--------------------------------------------- + +-- fp.viewStaffing_WorkingHours +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-10-31 MD JAZZ-62448 Updated for staffing restructure +*************************************************************/ +CREATE VIEW [fp].[viewStaffing_WorkingHours] AS +SELECT + b.BudgetConfigID, + b.EntityGroupConfigID, + b.EntityID, + b.DepartmentID, + b.JobCodeID, + b.PayCodeGroupID, + b.ProductiveClassID, + b.SubsectionID, + b.VariabilityID, + b.EmployeeID, + b.InitialBudgetHours01, + b.InitialBudgetHours02, + b.InitialBudgetHours03, + b.InitialBudgetHours04, + b.InitialBudgetHours05, + b.InitialBudgetHours06, + b.InitialBudgetHours07, + b.InitialBudgetHours08, + b.InitialBudgetHours09, + b.InitialBudgetHours10, + b.InitialBudgetHours11, + b.InitialBudgetHours12, + b.InitialProjectionHours01, + b.InitialProjectionHours02, + b.InitialProjectionHours03, + b.InitialProjectionHours04, + b.InitialProjectionHours05, + b.InitialProjectionHours06, + b.InitialProjectionHours07, + b.InitialProjectionHours08, + b.InitialProjectionHours09, + b.InitialProjectionHours10, + b.InitialProjectionHours11, + b.InitialProjectionHours12, + b.BudgetAdjustedHours01, + b.BudgetAdjustedHours02, + b.BudgetAdjustedHours03, + b.BudgetAdjustedHours04, + b.BudgetAdjustedHours05, + b.BudgetAdjustedHours06, + b.BudgetAdjustedHours07, + b.BudgetAdjustedHours08, + b.BudgetAdjustedHours09, + b.BudgetAdjustedHours10, + b.BudgetAdjustedHours11, + b.BudgetAdjustedHours12, + b.TargetAdjustedHours01, + b.TargetAdjustedHours02, + b.TargetAdjustedHours03, + b.TargetAdjustedHours04, + b.TargetAdjustedHours05, + b.TargetAdjustedHours06, + b.TargetAdjustedHours07, + b.TargetAdjustedHours08, + b.TargetAdjustedHours09, + b.TargetAdjustedHours10, + b.TargetAdjustedHours11, + b.TargetAdjustedHours12, + b.ProjectionAdjustedHours01, + b.ProjectionAdjustedHours02, + b.ProjectionAdjustedHours03, + b.ProjectionAdjustedHours04, + b.ProjectionAdjustedHours05, + b.ProjectionAdjustedHours06, + b.ProjectionAdjustedHours07, + b.ProjectionAdjustedHours08, + b.ProjectionAdjustedHours09, + b.ProjectionAdjustedHours10, + b.ProjectionAdjustedHours11, + b.ProjectionAdjustedHours12, + whBudget.Month01 As BudgetWorkingHours01, + whBudget.Month02 As BudgetWorkingHours02, + whBudget.Month03 As BudgetWorkingHours03, + whBudget.Month04 As BudgetWorkingHours04, + whBudget.Month05 As BudgetWorkingHours05, + whBudget.Month06 As BudgetWorkingHours06, + whBudget.Month07 As BudgetWorkingHours07, + whBudget.Month08 As BudgetWorkingHours08, + whBudget.Month09 As BudgetWorkingHours09, + whBudget.Month10 As BudgetWorkingHours10, + whBudget.Month11 As BudgetWorkingHours11, + whBudget.Month12 As BudgetWorkingHours12, + whProjection.Month01 As ProjectionWorkingHours01, + whProjection.Month02 As ProjectionWorkingHours02, + whProjection.Month03 As ProjectionWorkingHours03, + whProjection.Month04 As ProjectionWorkingHours04, + whProjection.Month05 As ProjectionWorkingHours05, + whProjection.Month06 As ProjectionWorkingHours06, + whProjection.Month07 As ProjectionWorkingHours07, + whProjection.Month08 As ProjectionWorkingHours08, + whProjection.Month09 As ProjectionWorkingHours09, + whProjection.Month10 As ProjectionWorkingHours10, + whProjection.Month11 As ProjectionWorkingHours11, + whProjection.Month12 As ProjectionWorkingHours12 +FROM + [fp].[Staffing] b +INNER JOIN [fp].[BudgetConfig] bc (READUNCOMMITTED) ON + b.BudgetConfigID = bc.BudgetConfigID +INNER JOIN [fw].[DimDepartment] d (READUNCOMMITTED) ON + d.DepartmentID = b.DepartmentID +INNER JOIN [fw].[DimJobCode] jc (READUNCOMMITTED) ON + jc.JobCodeID = b.JobCodeID +INNER JOIN [client].[FactWorkingHoursPerMonth] whBudget (READUNCOMMITTED) ON + whBudget.FiscalYearID = bc.FiscalYearID + AND whBudget.WorkWeekID = + (CASE + WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID + ELSE d.WorkWeekID + END) +INNER JOIN [client].[FactWorkingHoursPerMonth] whProjection (READUNCOMMITTED) ON + whProjection.FiscalYearID = bc.FiscalYearID - 1 + AND whProjection.WorkWeekID = + (CASE + WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID + ELSE d.WorkWeekID + END) +INNER JOIN [fw].[DimEmployee] e (READUNCOMMITTED) ON + e.EmployeeID = b.EmployeeID; +GO + + +--------------------------------------------- + +-- fp.viewStatisticsAdjustment +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-01-04 MZ JAZZ-47034 Added BudgetPhaseID + *************************************************************/ + +CREATE VIEW [fp].[viewStatisticsAdjustment] +AS + +SELECT [AdjustmentGUID] + ,[BudgetConfigGUID] + ,[AdjustmentType] + ,[Value] + ,[AdjustmentFilterJSON] + ,[GroupingHierarchyJSON] + ,[AdjustedProperty] + ,[Comment] + ,[AuthorGUID] + ,[AuthorFullName] + ,[LastModifiedDateUtc] + ,[DateCreatedUtc] + ,[GroupingGUID] + ,[ParentFilterJSON] + ,[TimeClassID] + ,[BudgetPhaseID] + ,[ClassificationGroupID] + ,[ClassificationCategoryID] + ,[IsRecordDeleted] + ,[DimensionMemberJson] + ,[AdjustmentID] + ,[SubsectionID] + ,[IsErrored] + FROM [fp].[StatisticsAdjustment] + WHERE IsRecordDeleted = 0 +GO + + +--------------------------------------------- + +-- fp.viewStatisticsAdjustmentImport +CREATE VIEW [fp].[viewStatisticsAdjustmentImport] +AS +SELECT [RowID] + ,[AdjustmentGUID] + ,[DepartmentID] + ,[EntityID] + ,[AccountID] + ,[FinancialReportingID] + ,[PayorID] + ,[PatientClassID] + ,[ProviderID] + ,[ProviderTypeID] + ,[ProviderLineItemID] + ,[ProviderSpecialtyID] + ,[FiscalYearID] + ,[FiscalMonthID] + ,[UnitTypeID] + ,[Value] + ,[Version] + ,[TimeClassID] + ,[BudgetPhaseID] + ,[IsRecordDeleted] + ,[AdjustmentID] + FROM [fp].[StatisticsAdjustmentImport] + WHERE IsRecordDeleted = 0 +GO + + +--------------------------------------------- + +-- fp.viewStatisticsInitialPlanConfigDetailLogs +CREATE VIEW fp.viewStatisticsInitialPlanConfigDetailLogs AS + +SELECT RowID, + BudgetConfigGUID, + BudgetConfigID, + EntityID, + DepartmentID, + AccountID, + PatientClassID, + TimeClassID, + FinancialReportingID, + PayorID, + ProviderSpecialtyID, + ProviderTypeID, + ProviderID, + ProviderLineItemID, + VariabilityID, + ProjectionMethodID, + TrailingMonths, + VersionID + FROM [fp].[StatisticsInitialPlanConfigDetailHistory] + UNION + SELECT RowID, + BudgetConfigGUID, + BudgetConfigID, + EntityID, + DepartmentID, + AccountID, + PatientClassID, + TimeClassID, + FinancialReportingID, + PayorID, + ProviderSpecialtyID, + ProviderTypeID, + ProviderID, + ProviderLineItemID, + VariabilityID, + ProjectionMethodID, + TrailingMonths, + VersionID + FROM [fp].[StatisticsInitialPlanConfigDetail] +GO + + +--------------------------------------------- + +-- fp.viewStatisticsSpreadUnlockData +CREATE VIEW fp.viewStatisticsSpreadUnlockData +AS + +SELECT [RowID] + ,[BudgetConfigID] + ,[AdjustmentGUID] + ,[EntityID] + ,[DepartmentID] + ,[AccountID] + ,[FinancialReportingID] + ,[PayorID] + ,[PatientClassID] + ,[ProviderID] + ,[ProviderTypeID] + ,[ProviderLineItemID] + ,[ProviderSpecialtyID] + ,[Version] + ,[Value01] + ,[Value02] + ,[Value03] + ,[Value04] + ,[Value05] + ,[Value06] + ,[Value07] + ,[Value08] + ,[Value09] + ,[Value10] + ,[Value11] + ,[Value12] + ,[IsRecordDeleted] + FROM [fp].[StatisticsSpreadUnlockData] + WHERE IsRecordDeleted = 0 +GO + + +--------------------------------------------- + +-- fp.viewStatisticsSpreads +CREATE VIEW [fp].[viewStatisticsSpreads] +AS + SELECT [BudgetConfigID], [DepartmentID], [AccountID], [ProviderID], [ProviderLineItemID], [IsInactive], [SpreadPercentage01], [SpreadPercentage02], [SpreadPercentage03], [SpreadPercentage04], [SpreadPercentage05], [SpreadPercentage06], [SpreadPercentage07], [SpreadPercentage08], [SpreadPercentage09], [SpreadPercentage10], [SpreadPercentage11], [SpreadPercentage12], [TotalImportedValue] as TotalSpreadValue, [GlobalSpreadID] + FROM [fp].[StatisticsSpreads] with (readuncommitted) + WHERE GlobalSpreadID = 1 + + UNION ALL + + SELECT bs.[BudgetConfigID], [DepartmentID], [AccountID], [ProviderID], [ProviderLineItemID], [IsInactive], gs.[SpreadPercentage01], gs.[SpreadPercentage02], gs.[SpreadPercentage03], gs.[SpreadPercentage04], gs.[SpreadPercentage05], gs.[SpreadPercentage06], gs.[SpreadPercentage07], gs.[SpreadPercentage08], gs.[SpreadPercentage09], gs.[SpreadPercentage10], gs.[SpreadPercentage11], gs.[SpreadPercentage12], gs.TotalSpreadValue, bs.[GlobalSpreadID] + FROM [fp].[StatisticsSpreads] bs with (readuncommitted) + INNER JOIN [fp].[GlobalSpread] gs ON bs.GlobalSpreadID = gs.GlobalSpreadID + WHERE bs.GlobalSpreadID > 1 +GO + + +--------------------------------------------- + +-- fp.viewUserViewGeneralLedgerAdjustments +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2024-10-22 MY JAZZ-77735 Initial + *************************************************************/ +CREATE VIEW [fp].[viewUserViewGeneralLedgerAdjustments] +AS + + -- WAIT, STOP WHAT YOU ARE DOING. What are you using this for? If you are using this to get back adjustments + -- from the user perspective, then you are in the right place. If you are looking at it in any other way look elsewhere. + -- This translates the GeneralLedgerAdjustment table to what the user sees. So for exmaple, when you make a roll up adjustment, + -- it creates X amount of adjustments, where X is the number of departments underneath it. From the user perspective, this creates 1 adjustment. + -- This for that roll up adjustment will return back 1, not X. + + WITH glAdjustments AS ( + SELECT AdjustmentGUID, BudgetConfigGUID, AdjustmentFilterJSON, GroupingHierarchyJSON, AdjustmentType, AdjustedProperty, GroupingGUID + FROM fp.GeneralLedgerAdjustment WHERE IsRecordDeleted = 0 + ), + -- These are all rollup adjustments (aka the parent adjustment) + rollUpAdjustments AS ( + SELECT AdjustmentGUID, BudgetConfigGUID, AdjustmentFilterJSON, GroupingHierarchyJSON, AdjustmentType, AdjustedProperty, GroupingGUID + FROM glAdjustments WHERE AdjustmentType IN (12, 13, 14) + ), + -- These are all adjustments that are not part of a roll up + planEditorAdjustments AS ( + SELECT AdjustmentGUID, BudgetConfigGUID, AdjustmentFilterJSON, GroupingHierarchyJSON, AdjustmentType, AdjustedProperty, GroupingGUID + FROM glAdjustments WHERE AdjustmentType IN (0, 2, 3) AND GroupingGUID = '00000000-0000-0000-0000-000000000000' + ), + -- GL Adjustments does not have FTE adjustments so we can avoid extra processing + -- Exclude Incrementals, Sets, and Final, as well as their roll up counterparts + -- because these are included in the above queries + otherAdjustments AS ( + SELECT AdjustmentGUID, BudgetConfigGUID, AdjustmentFilterJSON, GroupingHierarchyJSON, AdjustmentType, AdjustedProperty, GroupingGUID + FROM glAdjustments WHERE AdjustmentType NOT IN (0, 2, 3, 12, 13, 14) + ) + + SELECT * FROM otherAdjustments + UNION ALL + SELECT * FROM planEditorAdjustments + UNION ALL + SELECT * FROM rollUpAdjustments +GO + + +--------------------------------------------- + +-- fp.viewWorkingHours +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 10-9-2023 MY JAZZ-61397 Update Staffing/Provider Comp adjustments to support data model changes +*************************************************************/ +CREATE VIEW fp.viewWorkingHours + AS + SELECT + b.StaffingID, b.BudgetConfigID, b.EntityGroupConfigID, b.EntityID, b.DepartmentID, b.JobCodeID, b.PayCodeGroupID, + b.ProductiveClassID, b.VariabilityID, b.EmployeeID, b.ProviderID, b.ProviderTypeID, b.ProviderSpecialtyID, + b.ProviderLineItemID, b.SubsectionID, b.AddDate, b.IsNew, + + whBudget.Month01 As BudgetWorkingHours01, whBudget.Month02 As BudgetWorkingHours02, whBudget.Month03 As BudgetWorkingHours03, + whBudget.Month04 As BudgetWorkingHours04, whBudget.Month05 As BudgetWorkingHours05, whBudget.Month06 As BudgetWorkingHours06, + whBudget.Month07 As BudgetWorkingHours07, whBudget.Month08 As BudgetWorkingHours08, whBudget.Month09 As BudgetWorkingHours09, + whBudget.Month10 As BudgetWorkingHours10, whBudget.Month11 As BudgetWorkingHours11, whBudget.Month12 As BudgetWorkingHours12, + + whProjection.Month01 As ProjectionWorkingHours01, whProjection.Month02 As ProjectionWorkingHours02, whProjection.Month03 As ProjectionWorkingHours03, whProjection.Month04 As ProjectionWorkingHours04, + whProjection.Month05 As ProjectionWorkingHours05, whProjection.Month06 As ProjectionWorkingHours06, whProjection.Month07 As ProjectionWorkingHours07, whProjection.Month08 As ProjectionWorkingHours08, + whProjection.Month09 As ProjectionWorkingHours09, whProjection.Month10 As ProjectionWorkingHours10, whProjection.Month11 As ProjectionWorkingHours11, whProjection.Month12 As ProjectionWorkingHours12, + + b.FlexingTypeID, + b.ChangeHistoryGroupingGUID + FROM [fp].[Staffing] b + INNER JOIN [fp].[BudgetConfig] bc (READUNCOMMITTED) ON b.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [fw].[DimDepartment] d (READUNCOMMITTED) ON d.DepartmentID = b.DepartmentID + INNER JOIN [fw].[DimJobCode] jc (READUNCOMMITTED) ON jc.JobCodeID = b.JobCodeID + INNER JOIN [client].[FactWorkingHoursPerMonth] whBudget (READUNCOMMITTED) ON whBudget.FiscalYearID = bc.FiscalYearID + AND whBudget.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END) + INNER JOIN [client].[FactWorkingHoursPerMonth] whProjection (READUNCOMMITTED) ON whProjection.FiscalYearID = bc.FiscalYearID - 1 + AND whProjection.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END) +GO + + +--------------------------------------------- + +-- fp.viewWorkingHoursPerMonthWithBreakdown +CREATE VIEW fp.viewWorkingHoursPerMonthWithBreakdown + AS + SELECT base.FiscalYearID, base.FiscalMonthID, base.WorkWeekID, base.AnnualHours, base.YTDHours, ISNULL(base.AnnualHours - base.PreviousMonthsYTDHours, base.AnnualHours) AS RemainingAnnualHours + FROM + ( + SELECT base.FiscalYearID, base.FiscalMonthID, base.WorkWeekID, whpm.MonthYearly AS AnnualHours, base.YTDHours, + LAG(base.YTDHours) OVER (PARTITION BY base.FiscalYearID, base.WorkWeekID ORDER BY base.FiscalYearID, fm.SortOrder) AS PreviousMonthsYTDHours + FROM [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] base + INNER JOIN [fw].[DimFiscalMonth] fm ON base.FiscalMonthID = fm.FiscalMonthID + INNER JOIN [client].[FactWorkingHoursPerMonth] whpm ON base.FiscalYearID = whpm.FiscalYearID + AND base.WorkWeekID = whpm.WorkWeekID + ) base +GO + + +--------------------------------------------- + +--------------------------------------------- +-- PROCEDURES +--------------------------------------------- + +-- fp.BenefitsAdjustment_SEL_LIST +CREATE PROCEDURE [fp].[BenefitsAdjustment_SEL_LIST] + @budgetGUID UNIQUEIDENTIFIER, + @start INT, + @end INT, + @search VARCHAR(MAX), + @filter VARCHAR(MAX), + @userGUID UNIQUEIDENTIFIER, + @isDataSecured BIT, + @dateTimeFormat VARCHAR(30), + @userTimeZone VARCHAR(50) +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2020-06-03 LR JAZZ-134 Now including deleted items to be displayed in the activity pane + ** 2 2020-07-01 OP JAZZ-635 Added AP Entity Config roles support + ** 3 2020-08-20 OP JAZZ-4123 Fixed import comment + ** 4 2023-01-10 NT JAZZ-45457 Include new IsErrored field in order to display "DELETED - ADJUSTMENT FAILED" in the activity card + ** 5 2024-02-22 MY JAZZ-67143 Filters acting unexpectedly post-adjustment - Issue #2 + *************************************************************/ + BEGIN + + CREATE TABLE #departmentsSecurity ( + DepartmentID INT NULL, + EntityID INT NULL + ) + + CREATE TABLE #securedAdjustments ( + AdjustmentGUID UNIQUEIDENTIFIER + ) + + DECLARE @guidEmpty UNIQUEIDENTIFIER = [dbo].[ZeroGUID]() + DECLARE @pageSize INT = @end - @start; + + SET @search = LOWER(NULLIF('%' + @search+ '%', '%\%')) + SET @filter = LOWER(NULLIF(@filter, '')) + + SELECT AdjustmentGUID + ,GroupingHierarchyJSON + ,JSON_VALUE(AdjustmentFilterJSON, '$.Entity.ID') AS EntityID + ,JSON_VALUE(AdjustmentFilterJSON, '$.Department.ID') AS DepartmentID + ,AdjustmentType + ,GroupingGUID + INTO #adjustments + FROM fp.BenefitsAdjustment AS slea WITH (NOLOCK) + WHERE slea.AdjustmentType IN (0, 2, 1, 4, 3, 10, 11, 12, 13, 14) -- Supported Adjustment types for Benefits Adjustments + AND slea.BudgetConfigGUID = @budgetGUID + + IF @isDataSecured = 1 + BEGIN + INSERT INTO #departmentsSecurity + EXEC fp.DepartmentsSecurity_SEL + @userGUID = @userGUID, + @pageName = 'Benefits' + + CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #departmentsSecurity (DepartmentID, EntityID) + + SELECT AdjustmentGUID + ,ahd.ID AS DepartmentID + INTO #adjustmentGroupingHierarchyDepartments + FROM ( + SELECT adj.AdjustmentGUID + ,adj.GroupingHierarchyJSON + FROM #adjustments AS adj + WHERE adj.EntityID IS NULL + AND adj.DepartmentID IS NULL) AS slea + OUTER APPLY fp.GetAdjustmentHierarchyIDs(slea.GroupingHierarchyJSON, 'Department') AS ahd + GROUP BY AdjustmentGUID + ,ahd.ID + + SELECT adj.AdjustmentGUID, + ahe.ID AS EntityID + INTO #adjustmentGroupingHierarchyEntities + FROM #adjustments AS adj + JOIN #adjustmentGroupingHierarchyDepartments AS adhd ON adhd.AdjustmentGUID = adj.AdjustmentGUID + AND adhd.DepartmentID IS NULL + OUTER APPLY fp.GetAdjustmentHierarchyIDs(adj.GroupingHierarchyJSON, 'Entity') AS ahe + GROUP BY adj.AdjustmentGUID + ,ahe.ID + + INSERT INTO #securedAdjustments + SELECT res.AdjustmentGUID + FROM ( + SELECT slea.AdjustmentGUID + FROM #adjustments AS slea + JOIN #departmentsSecurity AS ds ON ds.DepartmentID = slea.DepartmentID + GROUP BY slea.AdjustmentGUID + + UNION ALL + + SELECT slea.AdjustmentGUID + FROM #adjustments AS slea + JOIN #departmentsSecurity AS dse ON dse.EntityID = slea.EntityID + WHERE slea.DepartmentID IS NULL + GROUP BY slea.AdjustmentGUID + + UNION ALL + + SELECT aghd.AdjustmentGUID + FROM #adjustmentGroupingHierarchyDepartments AS aghd + JOIN #departmentsSecurity AS dshd ON dshd.DepartmentID = aghd.DepartmentID + WHERE dshd.DepartmentID IS NOT NULL + GROUP BY aghd.AdjustmentGUID + + UNION ALL + + SELECT aghe.AdjustmentGUID + FROM #adjustmentGroupingHierarchyEntities AS aghe + JOIN #departmentsSecurity AS dshd ON dshd.EntityID = aghe.EntityID + GROUP BY aghe.AdjustmentGUID + + UNION ALL + + SELECT adj.AdjustmentGUID + FROM #adjustments AS adj + JOIN #adjustmentGroupingHierarchyDepartments AS aghd ON aghd.AdjustmentGUID = adj.AdjustmentGUID + JOIN #adjustmentGroupingHierarchyEntities AS aghe ON aghe.AdjustmentGUID = adj.AdjustmentGUID + WHERE adj.DepartmentID IS NULL + AND adj.EntityID IS NULL + AND aghd.DepartmentID IS NULL + AND aghe.EntityID IS NULL + GROUP BY adj.AdjustmentGUID + ) AS res + + -- JAZZ-67143: Filters acting unexpectedly post-adjustment (Issue #2) + -- Essentially we had cases where a custom roll up would cause local admins to make an adjustment and the + -- adjustment would not show up in the pane. This is due to roll up adjustments as everything else seems to be fine. + -- Essentially what we are doing here is using the child adjustments to find if they fall in security. + -- In the event we have a child, populate the parent adjustment in the list. + -- Find all the GroupingGuid's for any child adjustments that fall into security. + + SELECT DISTINCT adj.GroupingGUID + INTO #groupingAdjustments + FROM #securedAdjustments secured + INNER JOIN #adjustments adj ON secured.AdjustmentGUID = adj.AdjustmentGUID + WHERE adj.GroupingGUID != '00000000-0000-0000-0000-000000000000' -- Only care about roll up adjustments. + + -- Once we have the GroupingGUIDs based on the security, we can insert the parent adjustment. + INSERT INTO #securedAdjustments + SELECT adj.AdjustmentGUID + FROM #adjustments adj + INNER JOIN #groupingAdjustments grp ON adj.GroupingGUID = grp.GroupingGUID + LEFT JOIN #securedAdjustments secured ON adj.AdjustmentGUID = secured.AdjustmentGUID + WHERE adj.AdjustmentType IN (12, 13, 14) -- Roll Up Adjustments + AND secured.AdjustmentGUID IS NULL + + END + ELSE + BEGIN + + INSERT INTO #securedAdjustments + SELECT AdjustmentGUID + FROM #adjustments + + END + + CREATE CLUSTERED INDEX PK_SecuredAdjustmnets ON #securedAdjustments (AdjustmentGUID) + + SELECT iadj.AdjustmentGuid, + iadj.UnitTypeID + INTO #importAdjustments + FROM fp.BenefitsAdjustmentImport AS iadj WITH (NOLOCK) + JOIN #securedAdjustments AS sadj ON sadj.AdjustmentGUID = iadj.AdjustmentGUID + LEFT JOIN #departmentsSecurity AS ds ON ds.DepartmentID = iadj.DepartmentID + WHERE ds.DepartmentID IS NOT NULL + OR @isDataSecured = 0 + GROUP BY iadj.AdjustmentGuid, + iadj.UnitTypeID + + CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentGUID, UnitTypeID) + + SELECT res.TotalRowsCount + ,res.AdjustmentGUID + ,res.BudgetConfigGUID + ,res.AdjustmentType + ,res.[Value] + ,res.AdjustmentFilterJSON + ,res.GroupingHierarchyJSON + ,res.AdjustedProperty + ,res.Comment + ,res.AuthorGUID + ,res.AuthorFullName + ,res.LastModifiedDateUtc + ,res.DateCreatedUtc + ,res.GroupingGUID + ,res.TimeClassID + ,res.BudgetPhaseID + ,res.ClassificationGroupID + ,res.ClassificationCategoryID + ,res.JobCode + ,res.JobCodeCount + ,res.DepartmentCode + ,res.DepartmentCount + ,res.UnitTypeID + ,res.ImportUnitTypeIDs + ,res.IsRecordDeleted + ,res.IsErrored + FROM ( + SELECT COUNT(res_inner.AdjustmentGUID) OVER () AS TotalRowsCount, + * + FROM ( + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber + , slea.AdjustmentGUID + ,slea.BudgetConfigGUID + ,slea.AdjustmentType + ,slea.[Value] + ,slea.AdjustmentFilterJSON + ,slea.GroupingHierarchyJSON + ,slea.AdjustedProperty + ,ISNULL(ag.Description, slea.Comment) AS Comment + ,slea.AuthorGUID + ,slea.AuthorFullName + ,slea.LastModifiedDateUtc + ,slea.DateCreatedUtc + ,slea.GroupingGUID + ,slea.TimeClassID + ,slea.BudgetPhaseID + ,slea.ClassificationGroupID + ,slea.ClassificationCategoryID + ,slea.UnitTypeID + ,NULL AS JobCode + ,NULL AS JobCodeCount + ,NULL AS DepartmentCode + ,NULL AS DepartmentCount + ,sai.ImportUnitTypeIDs + ,slea.IsRecordDeleted + ,slea.IsErrored + FROM fp.BenefitsAdjustment AS slea WITH (NOLOCK) + JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID + LEFT JOIN ( + SELECT p.AdjustmentGUID, + ImportUnitTypeIDs = + TRIM(STUFF( + (SELECT N' ' + CAST(p2.UnitTypeID AS VARCHAR(5)) + FROM #importAdjustments AS p2 + WHERE p2.AdjustmentGUID = p.AdjustmentGUID + GROUP BY p2.AdjustmentGUID, + p2.UnitTypeID + FOR XML PATH(N'')) + , 1, 0, N'')) + FROM #importAdjustments AS p + GROUP BY p.AdjustmentGUID + ) AS sai ON sai.AdjustmentGUID = slea.AdjustmentGUID + LEFT JOIN fp.viewAdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID + LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID + LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acg.GroupID = acg.GroupID + AND slea.ClassificationCategoryID = acc.CategoryID + LEFT JOIN ( + SELECT nsa.GroupingGUID + FROM fp.BenefitsAdjustment as nsa WITH (NOLOCK) + WHERE nsa.AdjustmentType IN (12, 13, 14) -- Currently not supported types + AND nsa.BudgetConfigGUID = @budgetGUID + GROUP BY nsa.GroupingGUID + ) AS ra ON ra.GroupingGUID = slea.GroupingGUID + WHERE (slea.AdjustmentType <> 4 + OR sai.ImportUnitTypeIDs <> '') -- Check department security for import adjustment + AND slea.AdjustmentType IN (0, 2, 1, 4, 3, 10, 11, 12, 13, 14) -- Supported Adjustment types for Benefits Adjustments + AND (ra.GroupingGUID IS NULL + OR slea.AdjustmentType IN (12, 13, 14)) + AND (@search IS NULL + OR ( + LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\' + OR LOWER(ISNULL(ag.Description, slea.Comment)) LIKE @search ESCAPE '\' + OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR acc.[Name] LIKE @search ESCAPE '\' + OR acg.[Name] LIKE @search ESCAPE '\' + OR fp.SearchHierarchyLevel(slea.AdjustmentFilterJSON, @search) = 1 + OR LOWER(fp.GetAdjustmentMeasure(slea.AdjustmentType, slea.UnitTypeID)) LIKE @search ESCAPE '\' + OR fp.SearchAdjustmentMeasureForImport(slea.AdjustmentType, sai.ImportUnitTypeIDs, @search) = 1 + ) + ) + AND (@filter IS NULL + OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, slea.BudgetPhaseID) IN ( + SELECT [value] + FROM STRING_SPLIT(@filter, ' ') + ) + ) + ) AS res_inner + WHERE res_inner.RowNumber = 1 ) AS res + WHERE res.RowNumber = 1 + ORDER BY res.DateCreatedUtc DESC + OFFSET @start ROWS + FETCH NEXT @pageSize ROWS ONLY; +END; +GO + + +--------------------------------------------- + +-- fp.ChargeVolumeADDProviderRateCalculations +/************************************************************** +** CID Date Author WI Description +** 1 2022-09-01 JB JAZZ-32095 Remove Payor and PayorGroupID from joins. +** 2 2022-11-10 AO JAZZ-45578 Remove PayorID and PayorGroupID from main select. +** 3 2023-05-18 MY JAZZ-55153 Update to restructure +*************************************************************/ +CREATE PROCEDURE [fp].[ChargeVolumeADDProviderRateCalculations] + @BudgetConfigID INT, + @MonthsLoaded TINYINT, + @NewProviderID INT, + @BenchProvidersList [dbo].[SqlInt32ListTableType] READONLY, + @IsDataSecured BIT, + @DeptList [dbo].[SqlInt32ListTableType] READONLY + + + AS + BEGIN + + IF OBJECT_ID('tempdb..#BenchProviders') IS NOT NULL + DROP TABLE #BenchProviders + + IF OBJECT_ID('tempdb..#DepartmentsSecurity') IS NOT NULL + DROP TABLE #DepartmentsSecurity + + IF OBJECT_ID('tempdb..#FactChargeVolumeTemp') IS NOT NULL + DROP TABLE #FactChargeVolumeTemp + + IF OBJECT_ID('tempdb..#FactChargeVolumeTempUnits') IS NOT NULL + DROP TABLE #FactChargeVolumeTempUnits + + IF OBJECT_ID('tempdb..#FactServiceLineTempUnits') IS NOT NULL + DROP TABLE #FactServiceLineTempUnits + + CREATE TABLE #BenchProviders ( + ProviderID INT + ) + + INSERT INTO #BenchProviders (ProviderID) + SELECT value + FROM @BenchProvidersList + + DECLARE @NumBenchProviders int + SELECT @NumBenchProviders = COUNT(*) FROM #BenchProviders + + CREATE TABLE #FactChargeVolumeTemp( + ChargeVolumeID INT, + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + DepartmentID INT, + ServiceLineID INT, + PatientClassID INT, + AgeCohortID INT, + MedicalSurgicalID INT, + ChargeCodeID INT, + UnitTypeID INT , + ServiceEntityID INT, + MSDRGID INT, + UBRevCodeID INT, + PrimaryCPTID INT, + ServiceProviderID INT, + ServiceProviderSpecialtyID INT, + PerformingProviderID INT, + PerformingProviderSpecialtyID INT, + BillingCPTID INT + ) + + -- select into temporary table data with changed PerformingProviderID to new if this provider is matched to selected benchmark providers + IF( @IsDataSecured = 1) + BEGIN + CREATE TABLE #DepartmentsSecurity ( + DepartmentID INT ) + + INSERT INTO #DepartmentsSecurity (DepartmentID) + SELECT value + FROM @DeptList + + INSERT INTO #FactChargeVolumeTemp + SELECT + fcv.ChargeVolumeID, + fcv.BudgetConfigID, + fcv.EntityGroupConfigID , + fcv.EntityID, + fcv.DepartmentID, + fcv.ServiceLineID , + fcv.PatientClassID, + fcv.AgeCohortID, + fcv.MedicalSurgicalID, + fcv.ChargeCodeID, + fcv.UnitTypeID , + fcv.ServiceEntityID, + fcv.MSDRGID, + fcv.UBRevCodeID, + fcv.PrimaryCPTID, + fcv.ServiceProviderID, + fcv.ServiceProviderSpecialtyID, + case when fcv.PerformingProviderID IN (select ProviderID from #BenchProviders) then @NewProviderID + else fcv.PerformingProviderID + end as PerformingProviderID, + fcv.PerformingProviderSpecialtyID, + fcv.BillingCPTID + FROM fp.ChargeVolume fcv + INNER JOIN #DepartmentsSecurity ds on ds.DepartmentID = fcv.DepartmentID + WHERE BudgetConfigID = @BudgetConfigID + and UnitTypeID = 145 + and ServiceProviderID in (SELECT ProviderID FROM #BenchProviders) + END +ELSE + BEGIN + INSERT INTO #FactChargeVolumeTemp + SELECT + ChargeVolumeID, + BudgetConfigID, + EntityGroupConfigID , + EntityID, + DepartmentID, + ServiceLineID , + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + ChargeCodeID, + UnitTypeID , + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + case when PerformingProviderID IN (select ProviderID from #BenchProviders) then @NewProviderID + else PerformingProviderID + end as PerformingProviderID, + PerformingProviderSpecialtyID, + BillingCPTID + FROM fp.ChargeVolume + WHERE BudgetConfigID = @BudgetConfigID + and UnitTypeID = 145 + and ServiceProviderID in (SELECT ProviderID FROM #BenchProviders) +END + +----------- select chargeVolume units ------------------- + Select + BudgetConfigID, + EntityGroupConfigID , + EntityID, + DepartmentID, + ServiceLineID , + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + ChargeCodeID, + UnitTypeID , + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + @NewProviderID as ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID , + PerformingProviderSpecialtyID, + BillingCPTID, + --Charge Units + case @Monthsloaded + when 1 then SUM(fcvh.ActualYTDValue01+fcvh.PriorYearActualValue02+fcvh.PriorYearActualValue03+fcvh.PriorYearActualValue04+fcvh.PriorYearActualValue05+fcvh.PriorYearActualValue06+fcvh.PriorYearActualValue07+fcvh.PriorYearActualValue08+fcvh.PriorYearActualValue09+fcvh.PriorYearActualValue10+fcvh.PriorYearActualValue11+fcvh.PriorYearActualValue12) + when 2 then SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.PriorYearActualValue03+fcvh.PriorYearActualValue04+fcvh.PriorYearActualValue05+fcvh.PriorYearActualValue06+fcvh.PriorYearActualValue07+fcvh.PriorYearActualValue08+fcvh.PriorYearActualValue09+fcvh.PriorYearActualValue10+fcvh.PriorYearActualValue11+fcvh.PriorYearActualValue12) + when 3 then SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.ActualYTDValue03+fcvh.PriorYearActualValue04+fcvh.PriorYearActualValue05+fcvh.PriorYearActualValue06+fcvh.PriorYearActualValue07+fcvh.PriorYearActualValue08+fcvh.PriorYearActualValue09+fcvh.PriorYearActualValue10+fcvh.PriorYearActualValue11+fcvh.PriorYearActualValue12) + when 4 then SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.ActualYTDValue03+fcvh.ActualYTDValue04+fcvh.PriorYearActualValue05+fcvh.PriorYearActualValue06+fcvh.PriorYearActualValue07+fcvh.PriorYearActualValue08+fcvh.PriorYearActualValue09+fcvh.PriorYearActualValue10+fcvh.PriorYearActualValue11+fcvh.PriorYearActualValue12) + when 5 then SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.ActualYTDValue03+fcvh.ActualYTDValue04+fcvh.ActualYTDValue05+fcvh.PriorYearActualValue06+fcvh.PriorYearActualValue07+fcvh.PriorYearActualValue08+fcvh.PriorYearActualValue09+fcvh.PriorYearActualValue10+fcvh.PriorYearActualValue11+fcvh.PriorYearActualValue12) + when 6 then SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.ActualYTDValue03+fcvh.ActualYTDValue04+fcvh.ActualYTDValue05+fcvh.ActualYTDValue06+fcvh.PriorYearActualValue07+fcvh.PriorYearActualValue08+fcvh.PriorYearActualValue09+fcvh.PriorYearActualValue10+fcvh.PriorYearActualValue11+fcvh.PriorYearActualValue12) + when 7 then SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.ActualYTDValue03+fcvh.ActualYTDValue04+fcvh.ActualYTDValue05+fcvh.ActualYTDValue06+fcvh.ActualYTDValue07+fcvh.PriorYearActualValue08+fcvh.PriorYearActualValue09+fcvh.PriorYearActualValue10+fcvh.PriorYearActualValue11+fcvh.PriorYearActualValue12) + when 8 then SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.ActualYTDValue03+fcvh.ActualYTDValue04+fcvh.ActualYTDValue05+fcvh.ActualYTDValue06+fcvh.ActualYTDValue07+fcvh.ActualYTDValue08+fcvh.PriorYearActualValue09+fcvh.PriorYearActualValue10+fcvh.PriorYearActualValue11+fcvh.PriorYearActualValue12) + when 9 then SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.ActualYTDValue03+fcvh.ActualYTDValue04+fcvh.ActualYTDValue05+fcvh.ActualYTDValue06+fcvh.ActualYTDValue07+fcvh.ActualYTDValue08+fcvh.ActualYTDValue09+fcvh.PriorYearActualValue10+fcvh.PriorYearActualValue11+fcvh.PriorYearActualValue12) + when 10 then SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.ActualYTDValue03+fcvh.ActualYTDValue04+fcvh.ActualYTDValue05+fcvh.ActualYTDValue06+fcvh.ActualYTDValue07+fcvh.ActualYTDValue08+fcvh.ActualYTDValue09+fcvh.ActualYTDValue10+fcvh.PriorYearActualValue11+fcvh.PriorYearActualValue12) + when 11 then SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.ActualYTDValue03+fcvh.ActualYTDValue04+fcvh.ActualYTDValue05+fcvh.ActualYTDValue06+fcvh.ActualYTDValue07+fcvh.ActualYTDValue08+fcvh.ActualYTDValue09+fcvh.ActualYTDValue10+fcvh.ActualYTDValue11+fcvh.PriorYearActualValue12) + else SUM(fcvh.ActualYTDValue01+fcvh.ActualYTDValue02+fcvh.ActualYTDValue03+fcvh.ActualYTDValue04+fcvh.ActualYTDValue05+fcvh.ActualYTDValue06+fcvh.ActualYTDValue07+fcvh.ActualYTDValue08+fcvh.ActualYTDValue09+fcvh.ActualYTDValue10+fcvh.ActualYTDValue11+fcvh.ActualYTDValue12) + end/@NumBenchProviders as CV_Units --needs to be devided by number of selected benchmark providers + into #FactChargeVolumeTempUnits + from #FactChargeVolumeTemp fcv + INNER JOIN [fp].[ChargeVolumeHistory] fcvh on fcv.ChargeVolumeID = fcvh.ChargeVolumeID + GROUP BY + BudgetConfigID, + EntityGroupConfigID , + EntityID, + DepartmentID, + ServiceLineID , + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + ChargeCodeID, + UnitTypeID , + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderSpecialtyID, + PerformingProviderID , + PerformingProviderSpecialtyID, + BillingCPTID + + +-------- select ServiceLineUnits ------------- + + SELECT + sd.BudgetConfigID, + sd.EntityGroupConfigID, + sd.EntityID, + sd.PatientClassID, + sd.ServiceLineID, + sd.ServiceLineRollupID, + sd.AgeCohortID, + sd.MedicalSurgicalID, + sd.DepartmentID, + sd.PayorID, + sd.PayorGroupID, + sd.MSDRGID, + sd.CPTID, + @NewProviderID as ProviderID, + sd.PhysicianSpecialtyID, + case @Monthsloaded + when 1 then SUM(sdh.ActualYTDValue01+sdh.PriorYearActualValue02+sdh.PriorYearActualValue03+sdh.PriorYearActualValue04+sdh.PriorYearActualValue05+sdh.PriorYearActualValue06+sdh.PriorYearActualValue07+sdh.PriorYearActualValue08+sdh.PriorYearActualValue09+sdh.PriorYearActualValue10+sdh.PriorYearActualValue11+sdh.PriorYearActualValue12) + when 2 then SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.PriorYearActualValue03+sdh.PriorYearActualValue04+sdh.PriorYearActualValue05+sdh.PriorYearActualValue06+sdh.PriorYearActualValue07+sdh.PriorYearActualValue08+sdh.PriorYearActualValue09+sdh.PriorYearActualValue10+sdh.PriorYearActualValue11+sdh.PriorYearActualValue12) + when 3 then SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.ActualYTDValue03+sdh.PriorYearActualValue04+sdh.PriorYearActualValue05+sdh.PriorYearActualValue06+sdh.PriorYearActualValue07+sdh.PriorYearActualValue08+sdh.PriorYearActualValue09+sdh.PriorYearActualValue10+sdh.PriorYearActualValue11+sdh.PriorYearActualValue12) + when 4 then SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.ActualYTDValue03+sdh.ActualYTDValue04+sdh.PriorYearActualValue05+sdh.PriorYearActualValue06+sdh.PriorYearActualValue07+sdh.PriorYearActualValue08+sdh.PriorYearActualValue09+sdh.PriorYearActualValue10+sdh.PriorYearActualValue11+sdh.PriorYearActualValue12) + when 5 then SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.ActualYTDValue03+sdh.ActualYTDValue04+sdh.ActualYTDValue05+sdh.PriorYearActualValue06+sdh.PriorYearActualValue07+sdh.PriorYearActualValue08+sdh.PriorYearActualValue09+sdh.PriorYearActualValue10+sdh.PriorYearActualValue11+sdh.PriorYearActualValue12) + when 6 then SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.ActualYTDValue03+sdh.ActualYTDValue04+sdh.ActualYTDValue05+sdh.ActualYTDValue06+sdh.PriorYearActualValue07+sdh.PriorYearActualValue08+sdh.PriorYearActualValue09+sdh.PriorYearActualValue10+sdh.PriorYearActualValue11+sdh.PriorYearActualValue12) + when 7 then SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.ActualYTDValue03+sdh.ActualYTDValue04+sdh.ActualYTDValue05+sdh.ActualYTDValue06+sdh.ActualYTDValue07+sdh.PriorYearActualValue08+sdh.PriorYearActualValue09+sdh.PriorYearActualValue10+sdh.PriorYearActualValue11+sdh.PriorYearActualValue12) + when 8 then SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.ActualYTDValue03+sdh.ActualYTDValue04+sdh.ActualYTDValue05+sdh.ActualYTDValue06+sdh.ActualYTDValue07+sdh.ActualYTDValue08+sdh.PriorYearActualValue09+sdh.PriorYearActualValue10+sdh.PriorYearActualValue11+sdh.PriorYearActualValue12) + when 9 then SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.ActualYTDValue03+sdh.ActualYTDValue04+sdh.ActualYTDValue05+sdh.ActualYTDValue06+sdh.ActualYTDValue07+sdh.ActualYTDValue08+sdh.ActualYTDValue09+sdh.PriorYearActualValue10+sdh.PriorYearActualValue11+sdh.PriorYearActualValue12) + when 10 then SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.ActualYTDValue03+sdh.ActualYTDValue04+sdh.ActualYTDValue05+sdh.ActualYTDValue06+sdh.ActualYTDValue07+sdh.ActualYTDValue08+sdh.ActualYTDValue09+sdh.ActualYTDValue10+sdh.PriorYearActualValue11+sdh.PriorYearActualValue12) + when 11 then SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.ActualYTDValue03+sdh.ActualYTDValue04+sdh.ActualYTDValue05+sdh.ActualYTDValue06+sdh.ActualYTDValue07+sdh.ActualYTDValue08+sdh.ActualYTDValue09+sdh.ActualYTDValue10+sdh.ActualYTDValue11+sdh.PriorYearActualValue12) + else SUM(sdh.ActualYTDValue01+sdh.ActualYTDValue02+sdh.ActualYTDValue03+sdh.ActualYTDValue04+sdh.ActualYTDValue05+sdh.ActualYTDValue06+sdh.ActualYTDValue07+sdh.ActualYTDValue08+sdh.ActualYTDValue09+sdh.ActualYTDValue10+sdh.ActualYTDValue11+sdh.ActualYTDValue12) + end/@NumBenchProviders as SL_Encounters --needs to be devided by number of selected benchmark providers + into #FactServiceLineTempUnits + from [fp].[ServiceLineEncounter] sd + INNER JOIN [fp].[ServiceLineEncounterHistory] sdh on sd.ServiceLineEncounterID = sdh.ServiceLineEncounterID + WHERE sd.ProviderID in (SELECT ProviderID FROM #BenchProviders) + group by + sd.BudgetConfigID, + sd.EntityID, + sd.EntityGroupConfigID, + sd.PatientClassID, + sd.ServiceLineID, + sd.ServiceLineRollupID, + sd.AgeCohortID, + sd.MedicalSurgicalID, + sd.DepartmentID, + sd.PayorID, + sd.PayorGroupID, + sd.MSDRGID, + sd.CPTID, + sd.PhysicianSpecialtyID + + ---- main select for calculate charge volume rate + SELECT sub.*, ISNULL(sub.CV_Units/nullif (sub.SL_EncountersSum,0),0) AS Charge_Rate + FROM + ( + SELECT + fcv.ServiceLineID, + fcv.PatientClassID, + fcv.AgeCohortID, + fcv.MedicalSurgicalID, + fcv.ServiceEntityID, + fcv.MSDRGID, + fcv.PrimaryCPTID, + fcv.ServiceProviderID, + fcv.ServiceProviderSpecialtyID, + fcv.DepartmentID, + fcv.UBRevCodeID, + fcv.ChargeCodeID, + fcv.PerformingProviderID, + fcv.PerformingProviderSpecialtyID, + fcv.BillingCPTID, + fcv.EntityID, + fcv.CV_Units, + Sum(sd.SL_Encounters) as SL_EncountersSum + FROM #FactChargeVolumeTempUnits fcv + INNER JOIN #FactServiceLineTempUnits sd + ON fcv.AgeCohortID = sd.AgeCohortID + AND fcv.MedicalSurgicalID = sd.MedicalSurgicalID + AND fcv.PatientClassID = sd.PatientClassID + AND fcv.ServiceLineID = sd.ServiceLineID + AND fcv.ServiceEntityID = sd.EntityID + AND fcv.MSDRGID = sd.MSDRGID + AND fcv.PrimaryCPTID = sd.CPTID + AND fcv.ServiceProviderID = sd.ProviderID + AND fcv.BudgetConfigID = sd.BudgetConfigID + AND fcv.EntityGroupConfigID = sd.EntityGroupConfigID + GROUP BY + fcv.ServiceLineID, + fcv.PatientClassID, + fcv.AgeCohortID, + fcv.MedicalSurgicalID, + fcv.ServiceEntityID, + fcv.MSDRGID, + fcv.PrimaryCPTID, + fcv.ServiceProviderSpecialtyID, + fcv.DepartmentID, + fcv.UBRevCodeID, + fcv.ChargeCodeID, + fcv.PerformingProviderID, + fcv.PerformingProviderSpecialtyID, + fcv.BillingCPTID, + fcv.EntityID, + fcv.CV_Units, + fcv.ServiceProviderID + + ) sub --End subquery +END +GO + + +--------------------------------------------- + +-- fp.DepartmentChargeVolumeAdjustment_SEL_LIST +CREATE PROCEDURE [fp].[DepartmentChargeVolumeAdjustment_SEL_LIST] + @budgetGUID UNIQUEIDENTIFIER, + @start INT, + @end INT, + @search VARCHAR(MAX), + @filter VARCHAR(MAX), + @userGUID UNIQUEIDENTIFIER, + @isDataSecured BIT, + @dateTimeFormat VARCHAR(30), + @userTimeZone VARCHAR(50) +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2020-06-03 LR JAZZ-134 Now including deleted items to be displayed in the activity pane + ** 2 2020-07-01 OP JAZZ-635 Added AP Entity Config roles support + ** 3 2020-08-20 OP JAZZ-4123 Fixed import comment + ** 4 2023-01-10 NT JAZZ-45457 Include new IsErrored field in order to display "DELETED - ADJUSTMENT FAILED" in the activity card + ** 5 2024-02-22 MY JAZZ-67143 Filters acting unexpectedly post-adjustment - Issue #2 + *************************************************************/ +BEGIN + CREATE TABLE #departmentsSecurity ( + DepartmentID INT NULL, + EntityID INT NULL + ) + + CREATE TABLE #securedAdjustments ( + AdjustmentGUID UNIQUEIDENTIFIER + ) + + DECLARE @guidEmpty UNIQUEIDENTIFIER = [dbo].[ZeroGUID]() + DECLARE @pageSize INT = @end - @start; + + SET @search = LOWER(NULLIF('%' + @search+ '%', '%\%')) + SET @filter = LOWER(NULLIF(@filter, '')) + + SELECT AdjustmentGUID + ,GroupingHierarchyJSON + ,JSON_VALUE(AdjustmentFilterJSON, '$.Entity.ID') AS EntityID + ,JSON_VALUE(AdjustmentFilterJSON, '$.Department.ID') AS DepartmentID + ,AdjustmentType + ,GroupingGUID + INTO #adjustments + FROM fp.DepartmentChargeVolumeAdjustment AS slea WITH (NOLOCK) + WHERE slea.AdjustmentType IN (0, 1, 2, 3, 4, 12, 13, 14) -- Supported Adjustment types for Charges Adjustments + AND slea.BudgetConfigGUID = @budgetGUID + + IF @isDataSecured = 1 + BEGIN + INSERT INTO #departmentsSecurity + EXEC fp.DepartmentsSecurity_SEL + @userGUID = @userGUID, + @pageName = 'Charge Volumes' + + CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #departmentsSecurity (DepartmentID, EntityID) + + SELECT AdjustmentGUID + ,ahd.ID AS DepartmentID + INTO #adjustmentGroupingHierarchyDepartments + FROM ( + SELECT adj.AdjustmentGUID + ,adj.GroupingHierarchyJSON + FROM #adjustments AS adj + WHERE adj.EntityID IS NULL + AND adj.DepartmentID IS NULL) AS slea + OUTER APPLY fp.GetAdjustmentHierarchyIDs(slea.GroupingHierarchyJSON, 'Department') AS ahd + GROUP BY AdjustmentGUID + ,ahd.ID + + SELECT adj.AdjustmentGUID, + ahe.ID AS EntityID + INTO #adjustmentGroupingHierarchyEntities + FROM #adjustments AS adj + JOIN #adjustmentGroupingHierarchyDepartments AS adhd ON adhd.AdjustmentGUID = adj.AdjustmentGUID + AND adhd.DepartmentID IS NULL + OUTER APPLY fp.GetAdjustmentHierarchyIDs(adj.GroupingHierarchyJSON, 'Entity') AS ahe + GROUP BY adj.AdjustmentGUID + ,ahe.ID + + INSERT INTO #securedAdjustments + SELECT res.AdjustmentGUID + FROM ( + SELECT slea.AdjustmentGUID + FROM #adjustments AS slea + JOIN #departmentsSecurity AS ds ON ds.DepartmentID = slea.DepartmentID + GROUP BY slea.AdjustmentGUID + + UNION ALL + + SELECT slea.AdjustmentGUID + FROM #adjustments AS slea + JOIN #departmentsSecurity AS dse ON dse.EntityID = slea.EntityID + WHERE slea.DepartmentID IS NULL + GROUP BY slea.AdjustmentGUID + + UNION ALL + + SELECT aghd.AdjustmentGUID + FROM #adjustmentGroupingHierarchyDepartments AS aghd + JOIN #departmentsSecurity AS dshd ON dshd.DepartmentID = aghd.DepartmentID + WHERE dshd.DepartmentID IS NOT NULL + GROUP BY aghd.AdjustmentGUID + + UNION ALL + + SELECT aghe.AdjustmentGUID + FROM #adjustmentGroupingHierarchyEntities AS aghe + JOIN #departmentsSecurity AS dshd ON dshd.EntityID = aghe.EntityID + GROUP BY aghe.AdjustmentGUID + + UNION ALL + + SELECT adj.AdjustmentGUID + FROM #adjustments AS adj + JOIN #adjustmentGroupingHierarchyDepartments AS aghd ON aghd.AdjustmentGUID = adj.AdjustmentGUID + JOIN #adjustmentGroupingHierarchyEntities AS aghe ON aghe.AdjustmentGUID = adj.AdjustmentGUID + WHERE adj.DepartmentID IS NULL + AND adj.EntityID IS NULL + AND aghd.DepartmentID IS NULL + AND aghe.EntityID IS NULL + GROUP BY adj.AdjustmentGUID + ) AS res + + -- JAZZ-67143: Filters acting unexpectedly post-adjustment (Issue #2) + -- Essentially we had cases where a custom roll up would cause local admins to make an adjustment and the + -- adjustment would not show up in the pane. This is due to roll up adjustments as everything else seems to be fine. + -- Essentially what we are doing here is using the child adjustments to find if they fall in security. + -- In the event we have a child, populate the parent adjustment in the list. + -- Find all the GroupingGuid's for any child adjustments that fall into security. + + SELECT DISTINCT adj.GroupingGUID + INTO #groupingAdjustments + FROM #securedAdjustments secured + INNER JOIN #adjustments adj ON secured.AdjustmentGUID = adj.AdjustmentGUID + WHERE adj.GroupingGUID != '00000000-0000-0000-0000-000000000000' -- Only care about roll up adjustments. + + -- Once we have the GroupingGUIDs based on the security, we can insert the parent adjustment. + INSERT INTO #securedAdjustments + SELECT adj.AdjustmentGUID + FROM #adjustments adj + INNER JOIN #groupingAdjustments grp ON adj.GroupingGUID = grp.GroupingGUID + LEFT JOIN #securedAdjustments secured ON adj.AdjustmentGUID = secured.AdjustmentGUID + WHERE adj.AdjustmentType IN (12, 13, 14) -- Roll Up Adjustments + AND secured.AdjustmentGUID IS NULL + + END + ELSE + BEGIN + + INSERT INTO #securedAdjustments + SELECT AdjustmentGUID + FROM #adjustments + + END + + CREATE CLUSTERED INDEX PK_SecuredAdjustmnets ON #securedAdjustments (AdjustmentGUID) + + SELECT iadj.AdjustmentGuid + INTO #importAdjustments + FROM fp.DepartmentChargeAdjustmentImport AS iadj WITH (NOLOCK) + JOIN #securedAdjustments AS sadj ON sadj.AdjustmentGUID = iadj.AdjustmentGUID + LEFT JOIN #departmentsSecurity AS ds ON ds.DepartmentID = iadj.DepartmentID + WHERE ds.DepartmentID IS NOT NULL + OR @isDataSecured = 0 + GROUP BY iadj.AdjustmentGuid + + CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentGUID) + + SELECT res.TotalRowsCount + ,res.AdjustmentGUID + ,res.BudgetConfigGUID + ,res.AdjustmentType + ,res.[Value] + ,res.AdjustmentFilterJSON + ,res.GroupingHierarchyJSON + ,res.AdjustedProperty + ,res.Comment + ,res.AuthorGUID + ,res.AuthorFullName + ,res.LastModifiedDateUtc + ,res.DateCreatedUtc + ,res.GroupingGUID + ,res.TimeClassID + ,res.BudgetPhaseID + ,res.ClassificationGroupID + ,res.ClassificationCategoryID + ,res.JobCode + ,res.JobCodeCount + ,res.DepartmentCode + ,res.DepartmentCount + ,res.UnitTypeID + ,res.IsRecordDeleted + ,res.IsErrored + ,CAST(res.UnitTypeID AS VARCHAR(5)) AS ImportUnitTypeIDs + FROM ( + SELECT COUNT(res_inner.AdjustmentGUID) OVER () AS TotalRowsCount, + * + FROM ( + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber + ,slea.AdjustmentGUID + ,slea.BudgetConfigGUID + ,slea.AdjustmentType + ,slea.[Value] + ,slea.AdjustmentFilterJSON + ,slea.GroupingHierarchyJSON + ,slea.AdjustedProperty + ,ISNULL(ag.Description, slea.Comment) AS Comment + ,slea.AuthorGUID + ,slea.AuthorFullName + ,slea.LastModifiedDateUtc + ,slea.DateCreatedUtc + ,slea.GroupingGUID + ,slea.TimeClassID + ,slea.BudgetPhaseID + ,slea.ClassificationGroupID + ,slea.ClassificationCategoryID + ,slea.UnitTypeId + ,NULL AS JobCode + ,NULL AS JobCodeCount + ,NULL AS DepartmentCode + ,NULL AS DepartmentCount + ,slea.IsRecordDeleted + ,slea.IsErrored + FROM ( SELECT adj.* + ,CAST(145 AS TINYINT) AS UnitTypeId -- UNITS + ,CASE WHEN (AdjustmentType = 7 -- Manager + OR AdjustmentType = 9) -- SpreadUnlock + THEN CAST(3 AS TINYINT) -- Departments + ELSE CAST(2 AS TINYINT) -- Admin + END AS BudgetPhaseID + FROM fp.DepartmentChargeVolumeAdjustment AS adj WITH (NOLOCK) + JOIN #securedAdjustments AS sadj ON sadj.AdjustmentGUID = adj.AdjustmentGUID) AS slea + LEFT JOIN ( + SELECT p.AdjustmentGuid, + ImportUnitTypeIDs = '145' + FROM #importAdjustments AS p + GROUP BY p.AdjustmentGuid + ) AS sai ON sai.AdjustmentGUID = slea.AdjustmentGUID + LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID + LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acg.GroupID = acg.GroupID + AND slea.ClassificationCategoryID = acc.CategoryID + LEFT JOIN fp.AdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID + LEFT JOIN ( + SELECT nsa.GroupingGUID + FROM fp.DepartmentChargeVolumeAdjustment as nsa WITH (NOLOCK) + WHERE nsa.AdjustmentType IN (12, 13, 14) -- Rollups, keep this so we have a way to filter out the dept adj for the rollups + AND nsa.BudgetConfigGUID = @budgetGUID + GROUP BY nsa.GroupingGUID + ) AS ra ON ra.GroupingGUID = slea.GroupingGUID + WHERE (slea.AdjustmentType <> 4 + OR sai.ImportUnitTypeIDs <> '') -- Check department security for import adjustment + AND (ra.GroupingGUID IS NULL + OR slea.AdjustmentType IN (12, 13, 14)) + AND (@search IS NULL + OR ( + LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\' + OR LOWER(ISNULL(ag.Description, slea.Comment)) LIKE @search ESCAPE '\' + OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR acc.[Name] LIKE @search ESCAPE '\' + OR acg.[Name] LIKE @search ESCAPE '\' + OR fp.SearchHierarchyLevel(slea.AdjustmentFilterJSON, @search) = 1 + OR LOWER(fp.GetAdjustmentMeasure(slea.AdjustmentType, slea.UnitTypeID)) LIKE @search ESCAPE '\' + ) + ) + AND (@filter IS NULL + OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, slea.BudgetPhaseID) IN ( + SELECT [value] + FROM STRING_SPLIT(@filter, ' ' ) + ) + ) + ) AS res_inner + WHERE res_inner.RowNumber = 1 ) AS res + ORDER BY res.DateCreatedUtc DESC + OFFSET @start ROWS + FETCH NEXT @pageSize ROWS ONLY; +END +GO + + +--------------------------------------------- + +-- fp.DepartmentsSecurity_SEL +CREATE PROCEDURE [fp].[DepartmentsSecurity_SEL] ( + @userGUID UNIQUEIDENTIFIER, + @pageName VARCHAR(30) +) +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2020-07-01 OP JAZZ-635 Added AP Entity Config roles support + ** 2 2020-07-31 OP JAZZ-3423 Applied entity config roles + ** 3 2021-03-21 OP JAZZ-1144 Removed #FullAccess temp table + ** 4 2022-06-02 YR JAZZ-37924 Added distinct to result + *************************************************************/ +BEGIN + IF NOT EXISTS( + SELECT 1 + FROM UserProfile (readuncommitted) + WHERE UserGUID = @UserGUID) + BEGIN + RETURN + END + + --everything user has access to + CREATE TABLE #UserACL(LootGroupPrefix nvarchar(100), LootID nvarchar(128), IsFullAccess bit, IsReadable bit, IsWritable bit, IsSecurable bit, IsDeletable bit, IsCreatable bit) + INSERT #UserACL + SELECT + LootGroupPrefix, + LootID, + CAST(0 as bit) as IsFullAccess, + IsReadable, + IsWritable, + IsSecurable, + IsDeletable, + IsCreatable + FROM + dbo.ufn_GetS3ACLByUserGuid(@UserGUID) + + --include items user has no access to + INSERT #UserACL + SELECT + L.LootGroupPrefix, + L.LootID as LootID, + CAST(0 as bit) as IsFullAccess, + CAST(0 as bit) as IsReadable, + CAST(0 as bit) as IsWritable, + CAST(0 as bit) as IsSecurable, + CAST(0 as bit) as IsDeletable, + CAST(0 as bit) as IsCreatable + FROM + S3Loot L (readuncommitted) + WHERE + not exists (select 1 from #UserACL acl where acl.LootID = L.LootID) + + SELECT DISTINCT res.DepartmentID, + d.EntityID + FROM ( + SELECT CAST(REPLACE(allAccess.LootID, 'DEPT|', '') AS INT) AS DepartmentID + FROM #UserACL AS allAccess + WHERE (allAccess.IsFullAccess = 1 + OR allAccess.IsReadable = 1) + AND allAccess.LootGroupPrefix = 'DEPT' + ) as res + JOIN fw.DimDepartment AS d ON d.DepartmentID = res.DepartmentID + JOIN fp.viewDepartmentAccessByUser AS dabu ON dabu.DepartmentID = res.DepartmentID + JOIN fp.EntityGroupConfig AS ecg ON ecg.EntityGroupConfigID = dabu.EntityGroupConfigID + JOIN fp.EntityGroupConfigMapping AS ecgm ON ecgm.EntityGroupConfigGuid = ecg.EntityGroupConfigGuid + WHERE dabu.AccessType > 0 -- Has Read or Write access + AND dabu.Section = @pageName + AND dabu.UserGUID = @UserGUID + AND d.EntityID = ecgm.EntityID +END +GO + + +--------------------------------------------- + +-- fp.FactStatisticsProviderLineItemGetEstimatedVolumes +CREATE PROCEDURE [fp].[FactStatisticsProviderLineItemGetEstimatedVolumes] + @BudgetConfigID tinyint, + @ProviderIds [dbo].[SqlInt32ListTableType] readonly, + @NumBenchProviders smallint, + @MonthsLoaded tinyint, + @DepartmentIds [dbo].[SqlInt32ListTableType] readonly, + @SubsectionID int = 1, + @UnitTypeID tinyint = 140 + AS + +/************************************************************** + +Change History +************************************************************** +CID Date Author WI Description +1 2021-11-12 AO JAZZ-26991 Not specified ProviderLineItems shouldn't return +2 2023-04-25 VZ JAZZ-36898 Removed CheckDepartment parameter +*************************************************************/ + + BEGIN + +-- TEST CALL +--DECLARE @BudgetConfigId smallint +--DECLARE @ProviderIds dbo.SqlInt32ListTableType +--DECLARE @NumBenchProviders int +--DECLARE @MonthsLoaded tinyint +--DECLARE @DepartmentIds dbo.SqlInt32ListTableType + +--SET @BudgetConfigId = 4 +--SET @NumBenchProviders = 2 +--SET @MonthsLoaded = 5 + +--INSERT INTO @ProviderIds values(45272) +--INSERT INTO @ProviderIds values(45393) + +--INSERT INTO @DepartmentIds values(0) + +--EXEC [fp].[FactStatisticsProviderLineItemGetEstimatedVolumes] @BudgetConfigId, @ProviderIds, @NumBenchProviders, @MonthsLoaded, @DepartmentIds +--END TEST CALL + + SELECT main.*, pli.[Description] as ProviderLineItemDescription from + (SELECT + fs.ProviderLineItemID, + fs.AccountID, + fs.PayorID, + fs.PatientClassID, + case @Monthsloaded + when 1 then SUM(fsh.ActualYTDValue01+fsh.PriorYearActualValue02+fsh.PriorYearActualValue03+fsh.PriorYearActualValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 2 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.PriorYearActualValue03+fsh.PriorYearActualValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 3 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.PriorYearActualValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 4 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 5 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 6 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 7 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 8 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 9 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 10 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.ActualYTDValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 11 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.ActualYTDValue10+fsh.ActualYTDValue11+fsh.PriorYearActualValue12) + else SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.ActualYTDValue10+fsh.ActualYTDValue11+fsh.ActualYTDValue12) + end/@NumBenchProviders as EstimatedVolume + FROM [fp].[FactStatistics] fs + INNER JOIN [fp].[FactStatisticsHistory] fsh on fsh.StatisticsID = fs.StatisticsID + WHERE fs.BudgetConfigID = @BudgetConfigID + AND fs.SubsectionID = @SubsectionID + AND fs.UnitTypeID = @UnitTypeID + AND fs.ProviderID IN (SELECT [value] from @ProviderIds) + AND fs.DepartmentID IN (SELECT [value] from @DepartmentIds) + AND fs.ProviderLineItemID <> 0 + GROUP BY + fs.ProviderLineItemID, + fs.AccountID, + fs.PayorID, + fs.PatientClassID) as main + INNER JOIN [fp].[ProviderLineItem] pli ON main.ProviderLineItemID = pli.ProviderLineItemID + +END +GO + + +--------------------------------------------- + +-- fp.GeneralLedgerAdjustment_SEL_LIST +CREATE PROCEDURE [fp].[GeneralLedgerAdjustment_SEL_LIST] + @budgetGUID UNIQUEIDENTIFIER, + @start INT, + @end INT, + @search VARCHAR(MAX), + @filter VARCHAR(MAX), + @userGUID UNIQUEIDENTIFIER, + @isDataSecured BIT, + @dateTimeFormat VARCHAR(30), + @userTimeZone VARCHAR(50) +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2020-06-03 LR JAZZ-134 Now including deleted items to be displayed in the activity pane + ** 2 2020-07-01 OP JAZZ-635 Added AP Entity Config roles support + ** 3 2020-08-20 OP JAZZ-4123 Fixed import comment + ** 4 2020-11-23 BW JAZZ-9982 Now including non-staffing (My Budgets) adjustments (AdjustmentType 16) to be displayed in the activity pane + ** 5 2020-03-10 MD JAZZ-10331 Updating manager adjustment pull to bring back distinct accounts and not count of rows + ** 6 2021-05-14 ZH JAZZ-18180 Adding view more details for projection time class activity cards + ** 7 2021-07-09 OP JAZZ-22930 Fixed search by Projection for Manager Cards (Adjustment Type 16) + ** 8 2021-11-19 MY JAZZ-28801 Added Variable Reset to Acceptable Types + ** 9 2021-11-19 YR JAZZ-34640 Added SubAccountItemized adjustment type + ** 10 2022-05-26 YR JAZZ-38119 Fixed search SubAccountItemized adjustment type by comment + ** 11 2022-06-02 YR JAZZ-37924 Hide restricted SubAccountItemized cards for user + ** 12 2022-06-30 AO JAZZ-37651 Hide restricted Manager Adjustment cards for local user + ** 13 2022-07-04 DM JAZZ-40016 Fixed an issue with STRING_AGG + ** 14 2022-11-25 YR JAZZ-46173 Added AddAccount adjustment type + ** 15 2022-12-06 YR JAZZ-42980 Return AdjustmentID + ** 16 2023-01-10 NT JAZZ-45457 Include new IsErrored field in order to display "DELETED - ADJUSTMENT FAILED" in the activity card + ** 17 2023-01-26 DM JAZZ-48779 Changed table for old my budgets adjustments retrievement + ** 18 2023-11-08 DM JAZZ-61425 Changed import adjustments unit type selection to support dollars per uos + ** 19 2024-02-22 MY JAZZ-67143 Filters acting unexpectedly post-adjustment - Issue #2 + ** 20 2024-05-03 MZ JAZZ-69734 Renamed GeneralLedgerAdjustmentItemization to GeneralLedgerMyBudgetAdjustment +*************************************************************/ +BEGIN + + EXEC [dbo].[procSysDropTempTable] '#departmentsSecurity' + EXEC [dbo].[procSysDropTempTable] '#securedAdjustments' + EXEC [dbo].[procSysDropTempTable] '#adjustments' + EXEC [dbo].[procSysDropTempTable] '#adjustmentGroupingHierarchyDepartments' + EXEC [dbo].[procSysDropTempTable] '#adjustmentGroupingHierarchyEntities' + EXEC [dbo].[procSysDropTempTable] '#groupingAdjustments' + + CREATE TABLE #departmentsSecurity ( + DepartmentID INT NULL, + EntityID INT NULL + ) + + CREATE TABLE #securedAdjustments ( + AdjustmentGUID UNIQUEIDENTIFIER + ) + + DECLARE @guidEmpty UNIQUEIDENTIFIER = [dbo].[ZeroGUID]() + DECLARE @pageSize INT = @end - @start; + + SET @search = LOWER(NULLIF('%' + @search+ '%', '%\%')) + SET @filter = LOWER(NULLIF(@filter, '')) + + SELECT + AdjustmentGUID, + GroupingHierarchyJSON, + JSON_VALUE(AdjustmentFilterJSON, '$.Entity.ID') AS EntityID, + JSON_VALUE(AdjustmentFilterJSON, '$.Department.ID') AS DepartmentID, + AdjustmentType, + GroupingGUID + INTO #adjustments + FROM fp.GeneralLedgerAdjustment AS slea WITH (NOLOCK) + WHERE slea.AdjustmentType IN (0, 1, 2, 3, 4, 7, 8, 10, 11, 12, 13, 14, 16, 18, 19) -- Supported Adjustment types for GL Adjustments. MY: Need to look to see if this necessary. I don't think we really need to be filtering out types. + AND slea.BudgetConfigGUID = @budgetGUID + + IF @isDataSecured = 1 + BEGIN + INSERT INTO #departmentsSecurity + EXEC fp.DepartmentsSecurity_SEL + @userGUID = @userGUID, + @pageName = 'General Ledger' + + CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #departmentsSecurity (DepartmentID, EntityID) + + SELECT AdjustmentGUID + ,ahd.ID AS DepartmentID + INTO #adjustmentGroupingHierarchyDepartments + FROM ( + SELECT adj.AdjustmentGUID + ,adj.GroupingHierarchyJSON + FROM #adjustments AS adj + WHERE adj.EntityID IS NULL + AND adj.DepartmentID IS NULL) AS slea + OUTER APPLY fp.GetAdjustmentHierarchyIDs(slea.GroupingHierarchyJSON, 'Department') AS ahd + GROUP BY AdjustmentGUID + ,ahd.ID + + SELECT adj.AdjustmentGUID, + ahe.ID AS EntityID + INTO #adjustmentGroupingHierarchyEntities + FROM #adjustments AS adj + JOIN #adjustmentGroupingHierarchyDepartments AS adhd ON adhd.AdjustmentGUID = adj.AdjustmentGUID + AND adhd.DepartmentID IS NULL + OUTER APPLY fp.GetAdjustmentHierarchyIDs(adj.GroupingHierarchyJSON, 'Entity') AS ahe + GROUP BY adj.AdjustmentGUID + ,ahe.ID + + INSERT INTO #securedAdjustments + SELECT res.AdjustmentGUID + FROM ( + SELECT slea.AdjustmentGUID + FROM #adjustments AS slea + JOIN #departmentsSecurity AS ds ON ds.DepartmentID = slea.DepartmentID + GROUP BY slea.AdjustmentGUID + + UNION ALL + + SELECT slea.AdjustmentGUID + FROM #adjustments AS slea + JOIN #departmentsSecurity AS dse ON dse.EntityID = slea.EntityID + WHERE slea.DepartmentID IS NULL + GROUP BY slea.AdjustmentGUID + + UNION ALL + + SELECT aghd.AdjustmentGUID + FROM #adjustmentGroupingHierarchyDepartments AS aghd + JOIN #departmentsSecurity AS dshd ON dshd.DepartmentID = aghd.DepartmentID + WHERE dshd.DepartmentID IS NOT NULL + GROUP BY aghd.AdjustmentGUID + + UNION ALL + + SELECT aghe.AdjustmentGUID + FROM #adjustmentGroupingHierarchyEntities AS aghe + JOIN #departmentsSecurity AS dshd ON dshd.EntityID = aghe.EntityID + GROUP BY aghe.AdjustmentGUID + + UNION ALL + + SELECT adj.AdjustmentGUID + FROM #adjustments AS adj + JOIN #adjustmentGroupingHierarchyDepartments AS aghd ON aghd.AdjustmentGUID = adj.AdjustmentGUID + JOIN #adjustmentGroupingHierarchyEntities AS aghe ON aghe.AdjustmentGUID = adj.AdjustmentGUID + WHERE adj.DepartmentID IS NULL + AND adj.EntityID IS NULL + AND aghd.DepartmentID IS NULL + AND aghe.EntityID IS NULL + GROUP BY adj.AdjustmentGUID + ) AS res + + -- JAZZ-67143: Filters acting unexpectedly post-adjustment (Issue #2) + -- Essentially we had cases where a custom roll up would cause local admins to make an adjustment and the + -- adjustment would not show up in the pane. This is due to roll up adjustments as everything else seems to be fine. + -- Essentially what we are doing here is using the child adjustments to find if they fall in security. + -- In the event we have a child, populate the parent adjustment in the list. + + -- Find all the GroupingGuid's for any child adjustments that fall into security. + SELECT DISTINCT adj.GroupingGUID + INTO #groupingAdjustments + FROM #securedAdjustments secured + INNER JOIN #adjustments adj ON secured.AdjustmentGUID = adj.AdjustmentGUID + WHERE adj.GroupingGUID != '00000000-0000-0000-0000-000000000000' -- Only care about roll up adjustments. + + -- Once we have the GroupingGUIDs based on the security, we can insert the parent adjustment. + INSERT INTO #securedAdjustments + SELECT adj.AdjustmentGUID + FROM #adjustments adj + INNER JOIN #groupingAdjustments grp ON adj.GroupingGUID = grp.GroupingGUID + LEFT JOIN #securedAdjustments secured ON adj.AdjustmentGUID = secured.AdjustmentGUID + WHERE adj.AdjustmentType IN (12, 13, 14) -- Roll Up Adjustments + AND secured.AdjustmentGUID IS NULL + + END + ELSE + BEGIN + INSERT INTO #securedAdjustments + SELECT AdjustmentGUID + FROM #adjustments + END + + CREATE CLUSTERED INDEX PK_SecuredAdjustmnets ON #securedAdjustments (AdjustmentGUID) + + SELECT iadj.AdjustmentGuid, + iadj.UnitTypeID, + iadj.OriginalUnitTypeID + INTO #importAdjustments + FROM fp.GeneralLedgerAdjustmentImport AS iadj WITH (NOLOCK) + JOIN #securedAdjustments AS sadj ON sadj.AdjustmentGUID = iadj.AdjustmentGUID + LEFT JOIN #departmentsSecurity AS ds ON ds.DepartmentID = iadj.DepartmentID + WHERE ds.DepartmentID IS NOT NULL + OR @isDataSecured = 0 + GROUP BY iadj.AdjustmentGuid, + iadj.UnitTypeID, + iadj.OriginalUnitTypeID + + CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentGUID, UnitTypeID) + + SELECT res.TotalRowsCount + ,res.AdjustmentGUID + ,res.AdjustmentID + ,res.BudgetConfigGUID + ,res.AdjustmentType + ,res.[Value] + ,res.AdjustmentFilterJSON + ,res.GroupingHierarchyJSON + ,res.AdjustedProperty + ,res.Comment + ,res.AuthorGUID + ,res.AuthorFullName + ,res.LastModifiedDateUtc + ,res.DateCreatedUtc + ,res.GroupingGUID + ,res.TimeClassID + ,res.BudgetPhaseID + ,res.ClassificationGroupID + ,res.ClassificationCategoryID + ,res.JobCode + ,res.JobCodeCount + ,res.DepartmentCode + ,res.DepartmentName + ,res.DepartmentCount + ,res.AccountCount + ,res.AccountName + ,res.UnitTypeID + ,res.ImportUnitTypeIDs + ,res.IsRecordDeleted + ,res.IsErrored + FROM ( + SELECT COUNT(res_inner.AdjustmentGUID) OVER () AS TotalRowsCount, + * + FROM ( + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber + ,slea.AdjustmentGUID + ,slea.AdjustmentID + ,slea.BudgetConfigGUID + ,slea.AdjustmentType + ,slea.[Value] + ,slea.AdjustmentFilterJSON + ,slea.GroupingHierarchyJSON + ,slea.AdjustedProperty + ,ISNULL(ag.Description, slea.Comment) AS Comment + ,slea.AuthorGUID + ,slea.AuthorFullName + ,slea.LastModifiedDateUtc + ,slea.DateCreatedUtc + ,slea.GroupingGUID + ,slea.TimeClassID + ,slea.BudgetPhaseID + ,slea.ClassificationGroupID + ,slea.ClassificationCategoryID + ,slea.UnitTypeId + ,NULL AS JobCode + ,NULL AS JobCodeCount + ,NULL AS DepartmentCode + ,NULL AS DepartmentName + ,NULL AS DepartmentCount + ,NULL AS AccountCount + ,NULL AS AccountName + ,sai.ImportUnitTypeIDs + ,slea.IsRecordDeleted + ,slea.IsErrored + FROM fp.GeneralLedgerAdjustment AS slea WITH (NOLOCK) + JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID + LEFT JOIN ( + SELECT p.AdjustmentGUID, + ImportUnitTypeIDs = + TRIM(STUFF( + (SELECT N' ' + CAST(ISNULL(p2.OriginalUnitTypeID, p2.UnitTypeID) AS VARCHAR(5)) + FROM #importAdjustments AS p2 + WHERE p2.AdjustmentGUID = p.AdjustmentGUID + GROUP BY p2.AdjustmentGUID, + p2.UnitTypeID, + p2.OriginalUnitTypeID + FOR XML PATH(N'')) + , 1, 0, N'')) + FROM #importAdjustments AS p + GROUP BY p.AdjustmentGUID + ) AS sai ON sai.AdjustmentGUID = slea.AdjustmentGUID + LEFT JOIN fp.viewAdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID + LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID + LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acg.GroupID = acg.GroupID + AND slea.ClassificationCategoryID = acc.CategoryID + LEFT JOIN ( + SELECT nsa.GroupingGUID + FROM fp.GeneralLedgerAdjustment as nsa WITH (NOLOCK) + WHERE nsa.AdjustmentType IN (12, 13, 14) -- Currently not supported types + AND nsa.BudgetConfigGUID = @budgetGUID + GROUP BY nsa.GroupingGUID + ) AS ra ON ra.GroupingGUID = slea.GroupingGUID + WHERE (slea.AdjustmentType <> 4 + OR sai.ImportUnitTypeIDs <> '') -- Check department security for import adjustment + AND slea.AdjustmentType NOT IN (7, 16, 18, 19) + AND (ra.GroupingGUID IS NULL + OR slea.AdjustmentType IN (12, 13, 14)) + AND (@search IS NULL + OR ( + LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\' + OR LOWER(ISNULL(ag.Description, slea.Comment)) LIKE @search ESCAPE '\' + OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR acc.[Name] LIKE @search ESCAPE '\' + OR acg.[Name] LIKE @search ESCAPE '\' + OR fp.SearchHierarchyLevel(slea.AdjustmentFilterJSON, @search) = 1 + OR LOWER(fp.GetAdjustmentMeasure(slea.AdjustmentType, slea.UnitTypeID)) LIKE @search ESCAPE '\' + OR fp.SearchAdjustmentMeasureForImport(slea.AdjustmentType, sai.ImportUnitTypeIDs, @search) = 1 + ) + ) + AND (@filter IS NULL + OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, slea.BudgetPhaseID) IN ( + SELECT [value] + FROM STRING_SPLIT(@filter, ' ' ) + ) + ) + UNION ALL + + -- Manager Adjustments + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID, adjComment.TimeClassID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber + ,slea.AdjustmentGUID + ,slea.AdjustmentID + ,slea.BudgetConfigGUID + ,slea.AdjustmentType + ,NULL AS [Value] + ,slea.AdjustmentFilterJSON + ,slea.GroupingHierarchyJSON + ,slea.AdjustedProperty + ,NULL AS Comment + ,slea.AuthorGUID + ,slea.AuthorFullName + ,slea.LastModifiedDateUtc + ,slea.DateCreatedUtc + ,slea.GroupingGUID + ,adjComment.TimeClassID + ,slea.BudgetPhaseID + ,slea.ClassificationGroupID + ,slea.ClassificationCategoryID + ,slea.UnitTypeId + ,NULL AS JobCode + ,NULL AS JobCodeCount + ,NULL AS DepartmentCode + ,adjComment.DepartmentName + ,adjComment.DepartmentCount + ,NULL AS AccountCount + ,adjComment.AccountName + ,NULL AS ImportUnitTypeIDs + ,slea.IsRecordDeleted + ,slea.IsErrored + FROM fp.GeneralLedgerAdjustment AS slea WITH (NOLOCK) + JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID + LEFT JOIN ( + SELECT + oldMyBudg.AdjustmentGUID + ,oldMyBudg.TimeClassID + ,dept.Name AS DepartmentName + ,STRING_AGG(CAST(acc.Name AS NVARCHAR(MAX)), ';') AS AccountName + ,COUNT(dept.DepartmentID) AS DepartmentCount + FROM ( + SELECT + OBJ.AdjustmentGUID + ,OBJ.TimeClassID + ,OBJ.DepartmentID + ,OBJ.AccountID + FROM fp.GeneralLedgerManagerAdjustmentData AS OBJ WITH (NOLOCK) + GROUP BY OBJ.AdjustmentGUID, OBJ.DepartmentID, OBJ.AccountID, OBJ.TimeClassID + ) oldMyBudg + JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = oldMyBudg.DepartmentID + JOIN fw.DimAccount AS acc WITH (NOLOCK) ON acc.AccountID = oldMyBudg.AccountID + LEFT JOIN #departmentsSecurity AS ds WITH (NOLOCK) ON ds.DepartmentID = oldMyBudg.DepartmentID + WHERE @isDataSecured = 0 OR ds.DepartmentID IS NOT NULL + GROUP BY oldMyBudg.AdjustmentGUID, dept.Name, oldMyBudg.TimeClassID + ) AS adjComment ON adjComment.AdjustmentGUID = slea.AdjustmentGUID + LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID + LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON slea.ClassificationGroupID = acc.GroupID + AND slea.ClassificationCategoryID = acc.CategoryID + WHERE slea.AdjustmentType = 7 + AND (@search IS NULL + OR ( + LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\' + OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR acc.[Name] LIKE @search ESCAPE '\' + OR acg.[Name] LIKE @search ESCAPE '\' + OR 'my budgets' LIKE @search ESCAPE '\' + OR LOWER(adjComment.DepartmentName) LIKE @search ESCAPE '\' + OR LOWER(adjComment.AccountName) LIKE @search ESCAPE '\' + ) + ) + AND (@filter IS NULL + OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, adjComment.TimeClassID, slea.BudgetPhaseID) IN (SELECT [value] FROM STRING_SPLIT(@filter, ' ' ) ) + ) + AND adjComment.DepartmentName IS NOT NULL + UNION ALL + + + + -- SubAccount Adjustments + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber + ,slea.AdjustmentGUID + ,slea.AdjustmentID + ,slea.BudgetConfigGUID + ,slea.AdjustmentType + ,NULL AS [Value] + ,slea.AdjustmentFilterJSON + ,slea.GroupingHierarchyJSON + ,slea.AdjustedProperty + ,slea.Comment + ,slea.AuthorGUID + ,slea.AuthorFullName + ,slea.LastModifiedDateUtc + ,slea.DateCreatedUtc + ,slea.GroupingGUID + ,TimeClassID + ,slea.BudgetPhaseID + ,slea.ClassificationGroupID + ,slea.ClassificationCategoryID + ,slea.UnitTypeId + ,NULL AS JobCode + ,NULL AS JobCodeCount + ,NULL AS DepartmentCode + ,subAccountAdj.DepartmentName + ,subAccountAdj.DepartmentCount + ,subAccountAdj.AccountCount + ,subAccountAdj.AccountName + ,NULL AS ImportUnitTypeIDs + ,slea.IsRecordDeleted + ,slea.IsErrored + FROM fp.GeneralLedgerAdjustment AS slea WITH (NOLOCK) + JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID + LEFT JOIN ( + SELECT + OBJ.AdjustmentID AS AdjustmentID + ,STRING_AGG(CAST(dept.Name AS NVARCHAR(MAX)), ';') AS DepartmentName + ,STRING_AGG(CAST(acc.Name AS NVARCHAR(MAX)), ';') AS AccountName + ,COUNT(distinct acc.AccountID) AS AccountCount + ,COUNT(distinct dept.DepartmentID) AS DepartmentCount + FROM fp.GeneralLedgerSubAccountItemizedAdjustment AS OBJ WITH (NOLOCK) + JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = OBJ.DepartmentID + JOIN fw.DimAccount AS acc WITH (NOLOCK) ON acc.AccountID = OBJ.AccountID + LEFT JOIN #departmentsSecurity AS ds WITH (NOLOCK) ON ds.DepartmentID = OBJ.DepartmentID + WHERE @isDataSecured = 0 OR ds.DepartmentID IS NOT NULL + GROUP BY OBJ.AdjustmentID + ) AS subAccountAdj ON subAccountAdj.AdjustmentID = slea.AdjustmentID + LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID + LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON slea.ClassificationGroupID = acc.GroupID + AND slea.ClassificationCategoryID = acc.CategoryID + WHERE slea.AdjustmentType = 18 + AND (@search IS NULL + OR ( + LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(slea.Comment) LIKE @search ESCAPE '\' + OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\' + OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR acc.[Name] LIKE @search ESCAPE '\' + OR acg.[Name] LIKE @search ESCAPE '\' + OR 'sub-account detail' LIKE @search ESCAPE '\' + OR LOWER(subAccountAdj.DepartmentName) LIKE @search ESCAPE '\' + OR LOWER(subAccountAdj.AccountName) LIKE @search ESCAPE '\' + ) + ) + AND (@filter IS NULL + OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, slea.BudgetPhaseID) IN (SELECT [value] FROM STRING_SPLIT(@filter, ' ' ) ) + ) + AND subAccountAdj.DepartmentName IS NOT NULL + + UNION ALL + + + -- AddAccount Adj + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber + ,slea.AdjustmentGUID + ,slea.AdjustmentID + ,slea.BudgetConfigGUID + ,slea.AdjustmentType + ,NULL AS [Value] + ,slea.AdjustmentFilterJSON + ,slea.GroupingHierarchyJSON + ,slea.AdjustedProperty + ,slea.Comment + ,slea.AuthorGUID + ,slea.AuthorFullName + ,slea.LastModifiedDateUtc + ,slea.DateCreatedUtc + ,slea.GroupingGUID + ,TimeClassID + ,slea.BudgetPhaseID + ,NULL AS ClassificationGroupID + ,NULL AS ClassificationCategoryID + ,slea.UnitTypeId + ,NULL AS JobCode + ,NULL AS JobCodeCount + ,NULL AS DepartmentCode + ,addAccountAdj.DepartmentName + ,addAccountAdj.DepartmentCount + ,addAccountAdj.AccountCount + ,addAccountAdj.AccountName + ,NULL AS ImportUnitTypeIDs + ,slea.IsRecordDeleted + ,slea.IsErrored + FROM fp.GeneralLedgerAdjustment AS slea WITH (NOLOCK) + JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID + LEFT JOIN ( + SELECT + OBJ.AdjustmentID AS AdjustmentID + ,STRING_AGG(CAST(dept.Name AS NVARCHAR(MAX)), ';') AS DepartmentName + ,STRING_AGG(CAST(acc.Name AS NVARCHAR(MAX)), ';') AS AccountName + ,STRING_AGG(CAST(OBJ.Comment AS NVARCHAR(MAX)), ';') AS Comment + ,COUNT(distinct acc.AccountID) AS AccountCount + ,COUNT(distinct dept.DepartmentID) AS DepartmentCount + FROM fp.GeneralLedgerAddAccountAdjustment AS OBJ WITH (NOLOCK) + JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = OBJ.DepartmentID + JOIN fw.DimAccount AS acc WITH (NOLOCK) ON acc.AccountID = OBJ.AccountID + LEFT JOIN #departmentsSecurity AS ds WITH (NOLOCK) ON ds.DepartmentID = OBJ.DepartmentID + WHERE @isDataSecured = 0 OR ds.DepartmentID IS NOT NULL + GROUP BY OBJ.AdjustmentID + ) AS addAccountAdj ON addAccountAdj.AdjustmentID = slea.AdjustmentID + WHERE slea.AdjustmentType = 19 + AND (@search IS NULL + OR ( + LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(addAccountAdj.Comment) LIKE @search ESCAPE '\' + OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\' + OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR 'add account' LIKE @search ESCAPE '\' + OR LOWER(addAccountAdj.DepartmentName) LIKE @search ESCAPE '\' + OR LOWER(addAccountAdj.AccountName) LIKE @search ESCAPE '\' + ) + ) + AND addAccountAdj.DepartmentName IS NOT NULL + + UNION ALL + -- Manager Adjustments - non-staffing adj type 16 + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID, glai.TimeClassID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber + ,slea.AdjustmentGUID + ,slea.AdjustmentID + ,slea.BudgetConfigGUID + ,slea.AdjustmentType + ,NULL AS [Value] + ,slea.AdjustmentFilterJSON + ,slea.GroupingHierarchyJSON + ,slea.AdjustedProperty + ,NULL AS Comment + ,slea.AuthorGUID + ,slea.AuthorFullName + ,slea.LastModifiedDateUtc + ,slea.DateCreatedUtc + ,slea.GroupingGUID + ,glai.TimeClassID + ,slea.BudgetPhaseID + ,slea.ClassificationGroupID + ,slea.ClassificationCategoryID + ,slea.UnitTypeId + ,NULL AS JobCode + ,NULL AS JobCodeCount + ,NULL AS DepartmentCode + ,adjComment.DepartmentName + ,adjComment.DepartmentCount + ,NULL AS AccountCount + ,adjComment.AccountName + ,NULL AS ImportUnitTypeIDs + ,slea.IsRecordDeleted + ,slea.IsErrored + FROM fp.GeneralLedgerAdjustment AS slea WITH (NOLOCK) + JOIN fp.GeneralLedgerMyBudgetAdjustment glai on slea.AdjustmentID = glai.AdjustmentID + JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID + LEFT JOIN ( + SELECT + OBJ.AdjustmentID + ,OBJ.TimeClassID + ,dept.Name AS DepartmentName + ,STRING_AGG(CAST(acc.Name AS NVARCHAR(MAX)), ';') AS AccountName + --JAZZ-10331 + ,COUNT(DISTINCT acc.AccountID) AS DepartmentCount + FROM fp.GeneralLedgerMyBudgetAdjustment AS OBJ WITH (NOLOCK) + JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = OBJ.DepartmentID + JOIN fw.DimAccount AS acc WITH (NOLOCK) ON acc.AccountID = OBJ.AccountID + -- JAZZ-18180 adding time class to group by + GROUP BY OBJ.AdjustmentID, OBJ.TimeClassID, dept.Name + ) AS adjComment ON adjComment.AdjustmentID = slea.AdjustmentID and adjComment.TimeClassID = glai.TimeClassID + LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID + LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON slea.ClassificationGroupID = acc.GroupID + AND slea.ClassificationCategoryID = acc.CategoryID + WHERE slea.AdjustmentType = 16 + AND (@search IS NULL + OR ( + LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\' + OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR acc.[Name] LIKE @search ESCAPE '\' + OR acg.[Name] LIKE @search ESCAPE '\' + OR 'my budgets' LIKE @search ESCAPE '\' + OR LOWER(adjComment.DepartmentName) LIKE @search ESCAPE '\' + OR LOWER(adjComment.AccountName) LIKE @search ESCAPE '\' + ) + ) + AND (@filter IS NULL + OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, glai.TimeClassID, slea.BudgetPhaseID) IN (SELECT [value] FROM STRING_SPLIT(@filter, ' ' ) ) + ) + ) AS res_inner + WHERE res_inner.RowNumber = 1 ) AS res + ORDER BY res.DateCreatedUtc DESC + OFFSET @start ROWS + FETCH NEXT @pageSize ROWS ONLY +END +GO + + +--------------------------------------------- + +-- fp.GetAllDepartmentsAccessInfo +CREATE PROCEDURE fp.GetAllDepartmentsAccessInfo (@entityGroupConfigIds [dbo].[SqlInt32ListTableType] READONLY, @userGUID UNIQUEIDENTIFIER) + WITH RECOMPILE + AS + BEGIN + IF OBJECT_ID('tempdb..#entityGroupConfigIds') IS NOT NULL drop table #entityGroupConfigIds + IF OBJECT_ID('tempdb..#deptAccess') IS NOT NULL drop table #deptAccess + IF OBJECT_ID('tempdb..#workflows') IS NOT NULL drop table #workflows + IF OBJECT_ID('tempdb..#DistinctRoleID') IS NOT NULL drop table #DistinctRoleID + IF OBJECT_ID('tempdb..#validRoleIDs') IS NOT NULL drop table #validRoleIDs + IF OBJECT_ID('tempdb..#workflowSecurityItems') IS NOT NULL drop table #workflowSecurityItems + IF OBJECT_ID('tempdb..#APEDepartmentWorkflowStatus') IS NOT NULL drop table #APEDepartmentWorkflowStatus + IF OBJECT_ID('tempdb..#possibleRoleIds') IS NOT NULL drop table #possibleRoleIds + + DECLARE @MONET_USERGUID UNIQUEIDENTIFIER = '10101010-1111-0000-1111-101010101010' + DECLARE @DEPT_SECURITY_LOOT_PREFIX VARCHAR(50) = 'DEPT'; + + CREATE TABLE #entityGroupConfigIds (EntityGroupConfigId INT PRIMARY KEY CLUSTERED) + + INSERT INTO #entityGroupConfigIds (EntityGroupConfigId) + SELECT value + FROM @entityGroupConfigIds + + CREATE TABLE #deptAccess ( + DepartmentID INT PRIMARY KEY CLUSTERED, + CanAccess BIT, + CanEdit BIT, + STATUS INT +, + CanReject BIT, + CanSubmit BIT, + CurrentStepID BIT, + CurrentStepName VARCHAR(max) + ) + + CREATE TABLE #workflows ( + WorkflowStepID INT, + NAME VARCHAR(max), + WorkflowStepOrder INT, + EntityGroupConfigID INT, + RoleID INT, + IsEditable BIT, + IsDeleted BIT + ) + + CREATE UNIQUE CLUSTERED INDEX IX_tmpWorkflow ON #workflows + ( + EntityGroupConfigID, + WorkflowStepID, + RoleID + ) + + INSERT INTO #workflows + SELECT apwf.WorkflowStepID, + apwf.NAME, + apwf.WorkflowStepOrder, + apwf.EntityGroupConfigID, + apwfr.RoleID, + apwf.IsEditable, + 0 AS isDeleted + FROM fp.APEWorkflow apwf with (readuncommitted) + INNER JOIN fp.APEWorkflowRole apwfr with (readuncommitted) ON apwf.WorkflowStepID = apwfr.WorkflowStepID + INNER JOIN #entityGroupConfigIds egc ON apwf.EntityGroupConfigID = egc.EntityGroupConfigId + + CREATE TABLE #DistinctRoleID + ( + RoleID INT, + WorkflowStepID INT + ) + + CREATE UNIQUE CLUSTERED INDEX IX_tmpDistinctRoleID ON #DistinctRoleID + ( + RoleID, + WorkflowStepID + ) + + INSERT INTO #DistinctRoleID (RoleID, WorkflowStepID) + SELECT DISTINCT RoleID, WorkflowStepID + FROM #workflows + + CREATE TABLE #possibleRoleIds (RoleID INT,WorkflowStepID INT) + + CREATE UNIQUE CLUSTERED INDEX IX_tmpPossibleRoleID ON #possibleRoleIds + ( + RoleID, + WorkflowStepID + ) + + INSERT INTO #possibleRoleIds + SELECT RoleID, WorkflowStepID + FROM #DistinctRoleID + UNION + SELECT AdminRoleID, WorkflowStepID + FROM [fp].[APEEntityGroupConfigSetting] AEGC with (readuncommitted) + inner join #workflows wf on wf.EntityGroupConfigId = AEGC.EntityGroupConfigID + INNER JOIN #entityGroupConfigIds egc ON AEGC.EntityGroupConfigID = egc.EntityGroupConfigId + + CREATE TABLE #workflowSecurityItems ( + DepartmentID INT, + UserGUID UNIQUEIDENTIFIER, + RoleID INT, + LootID NVARCHAR(128) + ) + CREATE UNIQUE CLUSTERED INDEX IX_tmpWorkflowSecurityItems ON #workflowSecurityItems + ( + DepartmentID, + UserGUID, + RoleID + ) + + + CREATE TABLE #validRoleIds (RoleID INT PRIMARY KEY CLUSTERED) + INSERT INTO #validRoleIds + SELECT DISTINCT DR.RoleID + FROM + dbo.S3LootGroup LG with (readuncommitted) + INNER JOIN dbo.S3RoleAssignment RA with (readuncommitted) on LG.LootGroupID = RA.LootGroupID + INNER JOIN #DistinctRoleID dr ON dr.RoleID = RA.RoleID and Ra.IdentityGUID = @userGUID and @userGuid <> @MONET_USERGUID + WHERE LootID LIKE 'Dept|%' + + declare @validRoleIdsCount int = (select count(*) from #validRoleIds) + + INSERT INTO #workflowSecurityItems + SELECT DepartmentID = Replace(LootID, 'Dept|', ''), + UserGUID, + RoleID, + LootID + FROM [dbo].[viewS3ACLDetail] acl where UserGUID = @userGuid and @userGuid <> @MONET_USERGUID + and LootID LIKE 'Dept|%' and CASE WHEN acl.WriteAllowpts > acl.WriteDenypts then CAST(1 as bit) else CAST(0 as bit) end = 1 -- IsWritable + and (acl.RoleID in (select distinct RoleID from #validRoleIds) or @validRoleIdsCount = 0) + + UNION + + SELECT DepartmentID, + UserGUID = @userGUID, + R.RoleID, + LootID = @DEPT_SECURITY_LOOT_PREFIX + '|' + CAST(DepartmentID AS VARCHAR(20)) + FROM #DistinctRoleID R + CROSS JOIN fw.viewDimDepartment_Real vw + WHERE @userGUID = @MONET_USERGUID + + CREATE TABLE #APEDepartmentWorkflowStatus ( + DepartmentWorkflowStatusID INT, + WorkflowStepID INT, + WorkflowStepOrder INT, + DepartmentID INT, + EnteredStepDateTimeUtc DATETIME, + STATUS TINYINT, + NAME VARCHAR(250), + RoleID INT, + CanAccess BIT, + + RN int + ) + CREATE UNIQUE CLUSTERED INDEX IX_tmpAPEDepartmentWorkflowStatus ON #APEDepartmentWorkflowStatus + ( + DepartmentWorkflowStatusID, + WorkflowStepID, + DepartmentID, + RoleID, + RN + ) + + INSERT INTO #APEDepartmentWorkflowStatus + SELECT wfs.DepartmentWorkflowStatusID, + wfs.WorkflowStepID, + wf.WorkflowStepOrder, + wfs.DepartmentID, + wfs.EnteredStepDateTimeUtc, + wfs.STATUS, + wf.NAME, + wfsi.RoleID, + CanAccess = MAX(isnull(wfsi.RoleID / wfsi.RoleID, 0)) over (partition by wfs.DepartmentID), + RN = Row_number() over (partition by wfs.DepartmentID,wf.[EntityGroupConfigID] order BY wfs.EnteredStepDateTimeUtc desc) + FROM #entityGroupConfigIds egc + INNER JOIN [fp].[APEWorkflow] wf ON wf.[EntityGroupConfigID] = egc.[EntityGroupConfigID] + INNER JOIN fp.APEWorkflowRole wfr on wfr.WorkflowStepID = wf.WorkflowStepID + inner JOIN fp.APEDepartmentWorkflowStatus wfs ON wf.WorkflowStepID = wfs.WorkflowStepID + inner JOIN #workflowSecurityItems wfsi ON wfsi.DepartmentID = wfs.DepartmentID + WHERE wfs.DepartmentID IS NOT NULL + + CREATE TABLE #AccessRules + ( + DepartmentID INT, + WorkflowStepID INT + ) + + CREATE UNIQUE CLUSTERED INDEX IX_tmpAccessRules ON #AccessRules + ( + DepartmentID, + WorkflowStepID + ) + + INSERT INTO #AccessRules + SELECT Distinct DepartmentID,dws.WorkflowStepID + FROM #possibleRoleIds pri + INNER JOIN #APEDepartmentWorkflowStatus dws ON dws.RoleID = pri.RoleID AND dws.[WorkflowStepID] = pri.WorkflowStepID + + + SELECT dws.DepartmentID, + dws.STATUS, + CAST(dws.CanAccess as BIT) as CanAccess, + CanEdit = CAST(CASE WHEN canAccess = 0 OR NOT EXISTS (SELECT 1 FROM #DistinctRoleID) THEN 0 + WHEN EXISTS (SELECT 1 FROM #AccessRules VR WHERE VR.DepartmentID = dws.DepartmentID and VR.WorkflowStepID = dws.WorkflowStepID) THEN 1 + ELSE 0 + END as BIT), + CanReject = CAST(CASE WHEN (WorkflowStepOrder > 1 AND WorkflowStepOrder < 1000) + AND CASE WHEN canAccess = 0 OR NOT EXISTS (SELECT 1 FROM #DistinctRoleID) THEN 0 + WHEN EXISTS (SELECT 1 FROM #AccessRules VR WHERE VR.DepartmentID = dws.DepartmentID and VR.WorkflowStepID = dws.WorkflowStepID) THEN 1 + ELSE 0 + END = 1 THEN 1 + ELSE 0 + END as BIT), + CanSubmit = CAST(CASE WHEN canAccess = 0 AND NOT EXISTS (SELECT 1 FROM #DistinctRoleID) THEN 0 + WHEN EXISTS (SELECT 1 FROM #AccessRules VR WHERE VR.DepartmentID = dws.DepartmentID and VR.WorkflowStepID = dws.WorkflowStepID) THEN 1 + ELSE 0 + END as BIT), + CurrentStepID = WorkflowStepID, + CurrentStepName = dws.NAME + FROM #APEDepartmentWorkflowStatus dws + JOIN FW.DimDepartment as dd + ON dws.DepartmentID = dd.DepartmentID + JOIN FW.DimEntity as de + ON dd.EntityID = de.EntityID + JOIN fp.EntityGroupConfigMapping as egcm + ON egcm.EntityID = de.EntityID + JOIN fp.EntityGroupConfig as EGC + on egcm.EntityGroupConfigGUID = EGC.EntityGroupConfigGUID + JOIN #entityGroupConfigIds AS GC + on EGC.EntityGroupConfigID = GC.EntityGroupConfigId + WHERE RN = 1 +END +GO + + +--------------------------------------------- + +-- fp.ProcReportFactChargeToStatisticsCrosswalkBackup +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2020-05-08 LR JAZZ-20 Initial +** 2 2020-13-08 MY JAZZ-4079 Adding feature flag to short circuit the proc +** 3 2020-13-08 MY JAZZ-4098 Performance tuning +** 4 2020-01-02 MY JAZZ-14421 Remove old FF call that is no longer needed +** 5 2021-11-10 BW JAZZ-1358 Add dept to the filter when untargeted, to remove orphans +** 6 2021-11-16 MD JAZZ-27519 Update charge data pull based on IsChargeDollarsRemoved on budget config +** 7 2021-12-16 BW JAZZ-31087 Filter source data for IsChargeDollarsRemoved dupes via the union to avoid merge error +** 8 2022-09-01 JB JAZZ-32095 Remove Payor and PayorGroupID from joins. +** 9 2023-03-15 MY JAZZ-51265 1Plan RefreshChargeToStatCrosswalkDataSource fails more often than not due to bad query plan +** 10 2023-03-21 MY JAZZ-49993 Update reporting to support new data model +** 11 2023-08-08 MY JAZZ-58719 Budget Process Times Out During Refresh Charge To Stat Crosswalk Data Source Action +*************************************************************/ +CREATE PROCEDURE [fp].[procReportFactChargeToStatisticsCrosswalkBackup] ( + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +) +WITH RECOMPILE +AS +BEGIN + + EXEC [dbo].[procSysDropTempTable] '#SRC' + EXEC [dbo].[procSysDropTempTable] '#SourceDimensionality' + EXEC [dbo].[procSysDropTempTable] '#departments' + EXEC [dbo].[procSysDropTempTable] '#charges' + + DECLARE @FiscalYearID INT, + @ProjectedFiscalYearID INT; + + SET @FiscalYearID = (SELECT FiscalYearID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID); + SET @ProjectedFiscalYearID = (SELECT FiscalYearID - 1 FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID); + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + + SELECT DISTINCT DepartmentID INTO #SourceDimensionality from fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #SourceDimensionality (DepartmentID) + SELECT DISTINCT DepartmentID FROM fp.ChargeVolume + WHERE BudgetConfigID = @BudgetConfigID + END + + CREATE TABLE #SRC ( + BudgetConfigID INT, + EntityID INT, + DepartmentID INT, + AccountID INT, + PatientClassID INT, + ChargeCodeID INT, + ServiceLineID INT, + AgeCohortID INT, + MedicalSurgicalID INT, + RVUWeight DECIMAL(12, 4), + UnitTypeID SMALLINT, + TimeClassID TINYINT, + FiscalMonthID TINYINT, + FiscalYearID SMALLINT, + OriginalValue DECIMAL(19, 8), + Value DECIMAL(19, 8), + ManagerValue DECIMAL(19, 8) + ) + + -- IF THERE ARE PERFORMANCE PROBLEMS WITH THIS PROC PLEASE READ + -- IF THERE ARE PERFORMANCE PROBLEMS WITH THIS PROC PLEASE READ + -- IF THERE ARE PERFORMANCE PROBLEMS WITH THIS PROC PLEASE READ + + -- JAZZ-51265 AND JAZZ-58719: Important note, I was not able to determine the root cause of JAZZ-51265/JAZZ-58719 and merely attempted to simply the logic as I think + -- this can sometimes cause query plan issues. If the problem still occurs we need more information and exactly what is causing the problem per the DBAs. + -- Previously we were just told to simplify the logic and thus are kind of trying to fix it blind as this has not been repeatable in Dev. + -- What I did this second time was combine everything before pivoting it out into months on rows. + -- We have to unpivot the data, so if the DBAs have better recommenedations for that, it would be appreciated. + + -- Initial Projection is not included because it not necessary as it's never shown to the user + SELECT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, + cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cc.AccountID, cc.RVUWeight, cv.UnitTypeID, + SUM(InitialBudget01) AS InitialBudget01, SUM(InitialBudget02) AS InitialBudget02, SUM(InitialBudget03) AS InitialBudget03, + SUM(InitialBudget04) AS InitialBudget04, SUM(InitialBudget05) AS InitialBudget05, SUM(InitialBudget06) AS InitialBudget06, + SUM(InitialBudget07) AS InitialBudget07, SUM(InitialBudget08) AS InitialBudget08, SUM(InitialBudget09) AS InitialBudget09, + SUM(InitialBudget10) AS InitialBudget10, SUM(InitialBudget11) AS InitialBudget11, SUM(InitialBudget12) AS InitialBudget12, + SUM(TargetAdjusted01) AS TargetValue01, SUM(TargetAdjusted02) AS TargetValue02, SUM(TargetAdjusted03) AS TargetValue03, + SUM(TargetAdjusted04) AS TargetValue04, SUM(TargetAdjusted05) AS TargetValue05, SUM(TargetAdjusted06) AS TargetValue06, + SUM(TargetAdjusted07) AS TargetValue07, SUM(TargetAdjusted08) AS TargetValue08, SUM(TargetAdjusted09) AS TargetValue09, + SUM(TargetAdjusted10) AS TargetValue10, SUM(TargetAdjusted11) AS TargetValue11, SUM(TargetAdjusted12) AS TargetValue12, + SUM(BudgetAdjusted01) AS ManagerValue01, SUM(BudgetAdjusted02) AS ManagerValue02, SUM(BudgetAdjusted03) AS ManagerValue03, + SUM(BudgetAdjusted04) AS ManagerValue04, SUM(BudgetAdjusted05) AS ManagerValue05, SUM(BudgetAdjusted06) AS ManagerValue06, + SUM(BudgetAdjusted07) AS ManagerValue07, SUM(BudgetAdjusted08) AS ManagerValue08, SUM(BudgetAdjusted09) AS ManagerValue09, + SUM(BudgetAdjusted10) AS ManagerValue10, SUM(BudgetAdjusted11) AS ManagerValue11, SUM(BudgetAdjusted12) AS ManagerValue12, + SUM(ProjectionAdjusted01) AS ProjectedValue01, SUM(ProjectionAdjusted02) AS ProjectedValue02, SUM(ProjectionAdjusted03) AS ProjectedValue03, + SUM(ProjectionAdjusted04) AS ProjectedValue04, SUM(ProjectionAdjusted05) AS ProjectedValue05, SUM(ProjectionAdjusted06) AS ProjectedValue06, + SUM(ProjectionAdjusted07) AS ProjectedValue07, SUM(ProjectionAdjusted08) AS ProjectedValue08, SUM(ProjectionAdjusted09) AS ProjectedValue09, + SUM(ProjectionAdjusted10) AS ProjectedValue10, SUM(ProjectionAdjusted11) AS ProjectedValue11, SUM(ProjectionAdjusted12) AS ProjectedValue12, + + SUM(InitialBudgetDollars01) AS InitialBudgetDollars01, SUM(InitialBudgetDollars02) AS InitialBudgetDollars02, SUM(InitialBudgetDollars03) AS InitialBudgetDollars03, + SUM(InitialBudgetDollars04) AS InitialBudgetDollars04, SUM(InitialBudgetDollars05) AS InitialBudgetDollars05, SUM(InitialBudgetDollars06) AS InitialBudgetDollars06, + SUM(InitialBudgetDollars07) AS InitialBudgetDollars07, SUM(InitialBudgetDollars08) AS InitialBudgetDollars08, SUM(InitialBudgetDollars09) AS InitialBudgetDollars09, + SUM(InitialBudgetDollars10) AS InitialBudgetDollars10, SUM(InitialBudgetDollars11) AS InitialBudgetDollars11, SUM(InitialBudgetDollars12) AS InitialBudgetDollars12, + SUM(TargetDollarsAdjusted01) AS TargetValueDollars01, SUM(TargetDollarsAdjusted02) AS TargetValueDollars02, SUM(TargetDollarsAdjusted03) AS TargetValueDollars03, + SUM(TargetDollarsAdjusted04) AS TargetValueDollars04, SUM(TargetDollarsAdjusted05) AS TargetValueDollars05, SUM(TargetDollarsAdjusted06) AS TargetValueDollars06, + SUM(TargetDollarsAdjusted07) AS TargetValueDollars07, SUM(TargetDollarsAdjusted08) AS TargetValueDollars08, SUM(TargetDollarsAdjusted09) AS TargetValueDollars09, + SUM(TargetDollarsAdjusted10) AS TargetValueDollars10, SUM(TargetDollarsAdjusted11) AS TargetValueDollars11, SUM(TargetDollarsAdjusted12) AS TargetValueDollars12, + SUM(BudgetDollarsAdjusted01) AS ManagerValueDollars01, SUM(BudgetDollarsAdjusted02) AS ManagerValueDollars02, SUM(BudgetDollarsAdjusted03) AS ManagerValueDollars03, + SUM(BudgetDollarsAdjusted04) AS ManagerValueDollars04, SUM(BudgetDollarsAdjusted05) AS ManagerValueDollars05, SUM(BudgetDollarsAdjusted06) AS ManagerValueDollars06, + SUM(BudgetDollarsAdjusted07) AS ManagerValueDollars07, SUM(BudgetDollarsAdjusted08) AS ManagerValueDollars08, SUM(BudgetDollarsAdjusted09) AS ManagerValueDollars09, + SUM(BudgetDollarsAdjusted10) AS ManagerValueDollars10, SUM(BudgetDollarsAdjusted11) AS ManagerValueDollars11, SUM(BudgetDollarsAdjusted12) AS ManagerValueDollars12, + SUM(ProjectionDollarsAdjusted01) AS ProjectedValueDollars01, SUM(ProjectionDollarsAdjusted02) AS ProjectedValueDollars02, SUM(ProjectionDollarsAdjusted03) AS ProjectedValueDollars03, + SUM(ProjectionDollarsAdjusted04) AS ProjectedValueDollars04, SUM(ProjectionDollarsAdjusted05) AS ProjectedValueDollars05, SUM(ProjectionDollarsAdjusted06) AS ProjectedValueDollars06, + SUM(ProjectionDollarsAdjusted07) AS ProjectedValueDollars07, SUM(ProjectionDollarsAdjusted08) AS ProjectedValueDollars08, SUM(ProjectionDollarsAdjusted09) AS ProjectedValueDollars09, + SUM(ProjectionDollarsAdjusted10) AS ProjectedValueDollars10, SUM(ProjectionDollarsAdjusted11) AS ProjectedValueDollars11, SUM(ProjectionDollarsAdjusted12) AS ProjectedValueDollars12 + INTO #charges + FROM fp.ChargeVolume cv + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = cv.DepartmentID + INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] cc ON cc.EntityGroupConfigID = cv.EntityGroupConfigID + AND cc.DepartmentID = cv.DepartmentID + AND cc.PatientClassID = cv.PatientClassID + AND cc.ChargeCodeID = cv.ChargeCodeID + WHERE cv.BudgetConfigID = @BudgetConfigID + AND 1 = 1 + -- Only checking units because there are never going to be cases where Dollars aren't 0 but units are 0 + AND ( + cv.InitialBudgetTotal != 0 OR + cv.TargetAdjustedTotal != 0 OR + cv.BudgetAdjustedTotal != 0 OR + cv.ProjectionAdjustedTotal != 0 + ) + GROUP BY cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.ServiceLineID, + cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, cc.AccountID, cc.RVUWeight + + SELECT + cv.BudgetConfigID, + cv.EntityGroupConfigID, + cv.EntityID, + cv.DepartmentID, + cv.ServiceLineID, + cv.PatientClassID, + cv.AgeCohortID, + cv.MedicalSurgicalID, + cv.ChargeCodeID, + cv.AccountID, + cv.RVUWeight, + MonthSortOrder, + m.FiscalMonthID, + InitialBudgetValue, + TargetValue, + ManagerValue, + ProjectedValue, + InitialBudgetDollars, + TargetDollars, + ManagerDollars, + ProjectedDollars + INTO #chargesPivoted + FROM #charges cv + CROSS APPLY ( + VALUES + (01, InitialBudget01, TargetValue01, ManagerValue01, ProjectedValue01, InitialBudgetDollars01, TargetValueDollars01, ManagerValueDollars01, ProjectedValueDollars01), + (02, InitialBudget02, TargetValue02, ManagerValue02, ProjectedValue02, InitialBudgetDollars02, TargetValueDollars02, ManagerValueDollars02, ProjectedValueDollars02), + (03, InitialBudget03, TargetValue03, ManagerValue03, ProjectedValue03, InitialBudgetDollars03, TargetValueDollars03, ManagerValueDollars03, ProjectedValueDollars03), + (04, InitialBudget04, TargetValue04, ManagerValue04, ProjectedValue04, InitialBudgetDollars04, TargetValueDollars04, ManagerValueDollars04, ProjectedValueDollars04), + (05, InitialBudget05, TargetValue05, ManagerValue05, ProjectedValue05, InitialBudgetDollars05, TargetValueDollars05, ManagerValueDollars05, ProjectedValueDollars05), + (06, InitialBudget06, TargetValue06, ManagerValue06, ProjectedValue06, InitialBudgetDollars06, TargetValueDollars06, ManagerValueDollars06, ProjectedValueDollars06), + (07, InitialBudget07, TargetValue07, ManagerValue07, ProjectedValue07, InitialBudgetDollars07, TargetValueDollars07, ManagerValueDollars07, ProjectedValueDollars07), + (08, InitialBudget08, TargetValue08, ManagerValue08, ProjectedValue08, InitialBudgetDollars08, TargetValueDollars08, ManagerValueDollars08, ProjectedValueDollars08), + (09, InitialBudget09, TargetValue09, ManagerValue09, ProjectedValue09, InitialBudgetDollars09, TargetValueDollars09, ManagerValueDollars09, ProjectedValueDollars09), + (10, InitialBudget10, TargetValue10, ManagerValue10, ProjectedValue10, InitialBudgetDollars10, TargetValueDollars10, ManagerValueDollars10, ProjectedValueDollars10), + (11, InitialBudget11, TargetValue11, ManagerValue11, ProjectedValue11, InitialBudgetDollars11, TargetValueDollars11, ManagerValueDollars11, ProjectedValueDollars11), + (12, InitialBudget12, TargetValue12, ManagerValue12, ProjectedValue12, InitialBudgetDollars12, TargetValueDollars12, ManagerValueDollars12, ProjectedValueDollars12) + ) AS CrossApplied (MonthSortOrder, InitialBudgetValue, TargetValue, ManagerValue, ProjectedValue, InitialBudgetDollars, TargetDollars, ManagerDollars, ProjectedDollars) + LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder + + INSERT INTO #SRC (BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, ChargeCodeID, ServiceLineID, + AgeCohortID, MedicalSurgicalID, FiscalMonthID, FiscalYearID, RVUWeight, UnitTypeID, TimeClassID, OriginalValue, + Value, ManagerValue) + SELECT + BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, + FiscalMonthID, + @FiscalYearID AS FiscalYearID, + RVUWeight, + 145 AS UnitTypeID, + 2 AS TimeClassID, + InitialBudgetValue, + TargetValue, + ManagerValue + FROM #chargesPivoted + WHERE InitialBudgetValue != 0 + OR TargetValue != 0 + OR ManagerValue != 0 + + INSERT INTO #SRC (BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, ChargeCodeID, ServiceLineID, + AgeCohortID, MedicalSurgicalID, FiscalMonthID, FiscalYearID, RVUWeight, UnitTypeID, TimeClassID, OriginalValue, + Value, ManagerValue) + SELECT + BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, + FiscalMonthID, + @FiscalYearID AS FiscalYearID, + RVUWeight, + 34 AS UnitTypeID, + 2 AS TimeClassID, + InitialBudgetDollars, + TargetDollars, + ManagerDollars + FROM #chargesPivoted + WHERE InitialBudgetDollars != 0 + OR TargetDollars != 0 + OR ManagerDollars != 0 + + INSERT INTO #SRC (BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, ChargeCodeID, ServiceLineID, + AgeCohortID, MedicalSurgicalID, FiscalMonthID, FiscalYearID, RVUWeight, UnitTypeID, TimeClassID, OriginalValue, + Value, ManagerValue) + SELECT + BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, + FiscalMonthID, + @ProjectedFiscalYearID AS FiscalYearID, + RVUWeight, + 145 AS UnitTypeID, + 12 AS TimeClassID, + 0 AS OriginalValue, + ProjectedValue, + ProjectedValue + FROM #chargesPivoted + WHERE ProjectedValue != 0 + + INSERT INTO #SRC (BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, ChargeCodeID, ServiceLineID, + AgeCohortID, MedicalSurgicalID, FiscalMonthID, FiscalYearID, RVUWeight, UnitTypeID, TimeClassID, OriginalValue, + Value, ManagerValue) + SELECT + BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, + FiscalMonthID, + @ProjectedFiscalYearID AS FiscalYearID, + RVUWeight, + 34 AS UnitTypeID, + 12 AS TimeClassID, + 0 AS OriginalValue, + ProjectedDollars, + ProjectedDollars + FROM #chargesPivoted + WHERE ProjectedDollars != 0 + + CREATE CLUSTERED INDEX inx_src ON #SRC ( + BudgetConfigID, + EntityID, + DepartmentID, + AccountID, + PatientClassID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + UnitTypeID, + TimeClassID, + FiscalMonthID, + FiscalYearID + ) + + -- Get all of the departments in that could be affected. We need to get this list to eliminate + -- the null check in the join in the with statement. + SELECT DISTINCT DepartmentID INTO #departments + FROM ( + SELECT DISTINCT DepartmentID FROM #SRC + UNION ALL + SELECT DISTINCT DepartmentID FROM #SourceDimensionality + ) data + + ;WITH TGT AS + ( + SELECT BudgetConfigID, EntityID, FRS.DepartmentID, AccountID, PatientClassID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, RVUWeight, UnitTypeID, + TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue, Value, ManagerValue + FROM fp.FactReportChargeToStatisticsCrosswalk FRS + INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID + WHERE FRS.BudgetConfigID = @BudgetConfigID + ) + MERGE TGT AS target + USING #SRC AS source + ON ( + target.BudgetConfigID = source.BudgetConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.AccountID = source.AccountID + AND target.PatientClassID = source.PatientClassID + AND target.ChargeCodeID = source.ChargeCodeID + AND target.ServiceLineID = source.ServiceLineID + AND target.AgeCohortID = source.AgeCohortID + AND target.MedicalSurgicalID = source.MedicalSurgicalID + AND target.UnitTypeID = source.UnitTypeID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + + ) + WHEN MATCHED AND (target.OriginalValue <> source.OriginalValue + OR target.Value <> source.Value + OR target.ManagerValue <> source.ManagerValue + OR target.RVUWeight <> source.RVUWeight) + THEN + UPDATE SET + target.OriginalValue = ISNULL(source.OriginalValue, 0), + target.Value = ISNULL(source.Value, 0), + target.ManagerValue = ISNULL(source.ManagerValue, 0), + target.RVUWeight = ISNULL(source.RVUWeight, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + BudgetConfigID + ,EntityID + ,DepartmentID + ,AccountID + ,PatientClassID + ,ChargeCodeID + ,ServiceLineID + ,AgeCohortID + ,MedicalSurgicalID + ,RVUWeight + ,UnitTypeID + ,TimeClassID + ,FiscalMonthID + ,FiscalYearID + ,OriginalValue + ,Value + ,ManagerValue + ) + VALUES ( + source. BudgetConfigID + ,source.EntityID + ,source.DepartmentID + ,source.AccountID + ,source.PatientClassID + ,source.ChargeCodeID + ,source.ServiceLineID + ,source.AgeCohortID + ,source.MedicalSurgicalID + ,ISNULL(source.RVUWeight, 0) + ,source.UnitTypeID + ,source.TimeClassID + ,source.FiscalMonthID + ,source.FiscalYearID + ,ISNULL(source.OriginalValue, 0) + ,ISNULL(source.Value, 0) + ,ISNULL(source.ManagerValue, 0) + ) + WHEN NOT MATCHED BY Source + THEN + DELETE; + + ------------------------------------------------------------------------------------------------------- + -- D-09168 : CCF: Data not flowing through into reports + -- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the + -- targeting above. This is a short term solution until we can get a more performant solution. + ------------------------------------------------------------------------------------------------------- + + -- Check if targeting exists, if it doesn't for this part, wipe it and populate all departments + -- We can't rely on the existing departments because of the check for the padded rows. + IF NOT EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL) + BEGIN + + TRUNCATE TABLE #departments; + + INSERT INTO #departments (DepartmentID) + SELECT DepartmentID + FROM [fw].[DimDepartment] dept + + END + + -- Get all records that were adjusted + SELECT DISTINCT + fcv.BudgetConfigID, + fcv.EntityID, + fcv.DepartmentID, + fcv.ChargeCodeID, + fcv.ServiceLineID, + fcv.AgeCohortID, + fcv.MedicalSurgicalID, + fcv.PatientClassID, + fcv.UnitTypeID, + chg.TimeClassID, + chg.FiscalMonthID + INTO #adjustedRecords + FROM [fp].[ChargeVolumeChangeHistory] chg + INNER JOIN [fp].[ChargeVolume] fcv ON chg.ChargeVolumeID = fcv.ChargeVolumeID + INNER JOIN [fp].[DepartmentChargeVolumeAdjustment] adj ON chg.AdjustmentGUID = adj.AdjustmentGUID + INNER JOIN #departments ft on ft.DepartmentID = fcv.DepartmentID + INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] cc ON cc.EntityGroupConfigID = fcv.EntityGroupConfigID + AND cc.DepartmentID = fcv.DepartmentID + AND cc.PatientClassID = fcv.PatientClassID + AND cc.ChargeCodeID = fcv.ChargeCodeID + AND fcv.EntityGroupConfigID = cc.EntityGroupConfigID + WHERE chg.BudgetConfigID = @BudgetConfigID + + -- Get the records that have 0's in them that might have been filtered out from the previous logic + SELECT + src.BudgetConfigID, + src.EntityID, + src.DepartmentID, + src.ChargeCodeID, + src.ServiceLineID, + src.AgeCohortID, + src.MedicalSurgicalID, + src.PatientClassID, + 145 AS UnitTypeID, + 2 AS TimeClassID, + src.FiscalMonthID, + @FiscalYearID AS FiscalYearID, + src.InitialBudgetValue AS OriginalValue, + src.TargetValue AS Value, + src.ManagerValue + INTO #tempUnpivoted + FROM #adjustedRecords adj + INNER JOIN #chargesPivoted src ON + adj.BudgetConfigID = src.BudgetConfigID + AND adj.EntityID = src.EntityID + AND adj.DepartmentID = src.DepartmentID + AND adj.PatientClassID = src.PatientClassID + AND adj.ChargeCodeID = src.ChargeCodeID + AND adj.ServiceLineID = src.ServiceLineID + AND adj.AgeCohortID = src.AgeCohortID + AND adj.MedicalSurgicalID = src.MedicalSurgicalID + AND adj.FiscalMonthID = src.FiscalMonthID + WHERE src.BudgetConfigID = @BudgetConfigID + AND (src.InitialBudgetValue = 0 OR src.TargetValue = 0 OR src.ManagerValue = 0) + + INSERT INTO #tempUnpivoted (BudgetConfigID, EntityID, DepartmentID, ChargeCodeID, ServiceLineID, AgeCohortID, + MedicalSurgicalID, PatientClassID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue, + Value, ManagerValue) + SELECT + src.BudgetConfigID, + src.EntityID, + src.DepartmentID, + src.ChargeCodeID, + src.ServiceLineID, + src.AgeCohortID, + src.MedicalSurgicalID, + src.PatientClassID, + 34 AS UnitTypeID, + 2 AS TimeClassID, + src.FiscalMonthID, + @FiscalYearID AS FiscalYearID, + src.InitialBudgetDollars, + src.TargetDollars, + src.ManagerDollars + FROM #adjustedRecords adj + INNER JOIN #chargesPivoted src ON + adj.BudgetConfigID = src.BudgetConfigID + AND adj.EntityID = src.EntityID + AND adj.DepartmentID = src.DepartmentID + AND adj.PatientClassID = src.PatientClassID + AND adj.ChargeCodeID = src.ChargeCodeID + AND adj.ServiceLineID = src.ServiceLineID + AND adj.AgeCohortID = src.AgeCohortID + AND adj.MedicalSurgicalID = src.MedicalSurgicalID + AND adj.FiscalMonthID = src.FiscalMonthID + WHERE src.BudgetConfigID = @BudgetConfigID + AND (src.InitialBudgetDollars = 0 OR src.TargetDollars = 0 OR src.ManagerDollars = 0) + + INSERT INTO #tempUnpivoted (BudgetConfigID, EntityID, DepartmentID, ChargeCodeID, ServiceLineID, AgeCohortID, + MedicalSurgicalID, PatientClassID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue, + Value, ManagerValue) + SELECT + src.BudgetConfigID, + src.EntityID, + src.DepartmentID, + src.ChargeCodeID, + src.ServiceLineID, + src.AgeCohortID, + src.MedicalSurgicalID, + src.PatientClassID, + 145 AS UnitTypeID, + 12 AS TimeClassID, + src.FiscalMonthID, + @ProjectedFiscalYearID AS FiscalYearID, + 0 AS OriginalValue, + src.ProjectedValue, + src.ProjectedValue + FROM #adjustedRecords adj + INNER JOIN #chargesPivoted src ON + adj.BudgetConfigID = src.BudgetConfigID + AND adj.EntityID = src.EntityID + AND adj.DepartmentID = src.DepartmentID + AND adj.PatientClassID = src.PatientClassID + AND adj.ChargeCodeID = src.ChargeCodeID + AND adj.ServiceLineID = src.ServiceLineID + AND adj.AgeCohortID = src.AgeCohortID + AND adj.MedicalSurgicalID = src.MedicalSurgicalID + AND adj.FiscalMonthID = src.FiscalMonthID + WHERE src.BudgetConfigID = @BudgetConfigID + AND src.ProjectedValue = 0 + + INSERT INTO #tempUnpivoted (BudgetConfigID, EntityID, DepartmentID, ChargeCodeID, ServiceLineID, AgeCohortID, + MedicalSurgicalID, PatientClassID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue, + Value, ManagerValue) + SELECT + src.BudgetConfigID, + src.EntityID, + src.DepartmentID, + src.ChargeCodeID, + src.ServiceLineID, + src.AgeCohortID, + src.MedicalSurgicalID, + src.PatientClassID, + 34 AS UnitTypeID, + 12 AS TimeClassID, + src.FiscalMonthID, + @ProjectedFiscalYearID AS FiscalYearID, + 0 AS OriginalValue, + src.ProjectedDollars, + src.ProjectedDollars + FROM #adjustedRecords adj + INNER JOIN #chargesPivoted src ON + adj.BudgetConfigID = src.BudgetConfigID + AND adj.EntityID = src.EntityID + AND adj.DepartmentID = src.DepartmentID + AND adj.PatientClassID = src.PatientClassID + AND adj.ChargeCodeID = src.ChargeCodeID + AND adj.ServiceLineID = src.ServiceLineID + AND adj.AgeCohortID = src.AgeCohortID + AND adj.MedicalSurgicalID = src.MedicalSurgicalID + AND adj.FiscalMonthID = src.FiscalMonthID + WHERE src.BudgetConfigID = @BudgetConfigID + AND src.ProjectedDollars = 0 + + -- Find the records that need to be updated by comparing the source to the reporting table + SELECT + target.BudgetConfigID, + target.EntityID, + target.DepartmentID, + target.ChargeCodeID, + target.ServiceLineID, + target.AgeCohortID, + target.MedicalSurgicalID, + target.PatientClassID, + target.UnitTypeID, + target.TimeClassID, + target.FiscalMonthID, + target.FiscalYearID, + target.OriginalValue, + target.Value, + target.ManagerValue + INTO #dataToUpdate + FROM [fp].[FactReportChargeToStatisticsCrosswalk] source + INNER JOIN #departments ft on ft.DepartmentID = source.DepartmentID + INNER JOIN #tempUnpivoted target ON target.BudgetConfigID = source.BudgetConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.PatientClassID = source.PatientClassID + AND target.ChargeCodeID = source.ChargeCodeID + AND target.ServiceLineID = source.ServiceLineID + AND target.AgeCohortID = source.AgeCohortID + AND target.MedicalSurgicalID = source.MedicalSurgicalID + AND target.UnitTypeID = source.UnitTypeID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + WHERE source.BudgetConfigID = @BudgetConfigID + AND (target.OriginalValue != source.OriginalValue OR target.Value != source.Value OR target.ManagerValue != source.ManagerValue) + + -- Update the records + UPDATE source + SET source.OriginalValue = ISNULL(target.OriginalValue, 0), + source.Value = ISNULL(target.Value, 0), + source.ManagerValue = ISNULL(target.ManagerValue, 0) + FROM [fp].[FactReportChargeToStatisticsCrosswalk] source + INNER JOIN #departments ft on ft.DepartmentID = source.DepartmentID + INNER JOIN #dataToUpdate target ON target.BudgetConfigID = source.BudgetConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.PatientClassID = source.PatientClassID + AND target.ChargeCodeID = source.ChargeCodeID + AND target.ServiceLineID = source.ServiceLineID + AND target.AgeCohortID = source.AgeCohortID + AND target.MedicalSurgicalID = source.MedicalSurgicalID + AND target.UnitTypeID = source.UnitTypeID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + +END +GO + + +--------------------------------------------- + +-- fp.ProcReportFactChargeToStatisticsCrosswalkHistoryBackup +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2020-05-08 LR JAZZ-20 Initial +** 2 2020-13-08 MY JAZZ-4079 Adding feature flag to short circuit the proc +** 3 2020-13-08 MY JAZZ-4098 Performance tuning +** 4 2020-01-02 MY JAZZ-14421 Remove old FF call that is no longer needed +** 5 2021-11-10 BW JAZZ-1358 Add dept to the filter when untargeted, to remove orphans +** 6 2021-11-16 MD JAZZ-27519 Update charge data pull based on IsChargeDollarsRemoved on budget config +** 7 2022-09-01 JB JAZZ-32095 Remove Payor and PayorGroupID from joins. +** 8 2023-03-15 MY JAZZ-51265 1Plan RefreshChargeToStatCrosswalkDataSource fails more often than not due to bad query plan +** 9 2023-03-21 MY JAZZ-49993 Update reporting to support new data model +** 10 2023-04-13 BW JAZZ-51383 Remove IsDollarsRemovedFromCharges +*************************************************************/ + CREATE PROCEDURE [fp].[procReportFactChargeToStatisticsCrosswalkHistoryBackup] ( + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY) + AS + BEGIN + + exec [dbo].[procSysDropTempTable] '#SRC' + exec [dbo].[procSysDropTempTable] '#SourceDimensionality' + exec [dbo].[procSysDropTempTable] '#departments' + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + + SELECT DISTINCT DepartmentID INTO #SourceDimensionality FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #SourceDimensionality (DepartmentID) + SELECT DISTINCT DepartmentID FROM fp.FactReportChargeToStatisticsCrosswalkHistory + WHERE BudgetConfigID = @BudgetConfigID + END + + CREATE TABLE #SRC ( + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + DepartmentID INT, + AccountID INT, + PatientClassID INT, + ChargeCodeID INT, + ServiceLineID INT, + AgeCohortID INT, + MedicalSurgicalID INT, + RVUWeight DECIMAL(12, 4), + UnitTypeID SMALLINT, + TimeClassID TINYINT, + FiscalMonthID TINYINT, + FiscalYearID SMALLINT, + Value DECIMAL(19, 8) + ) + + INSERT INTO #SRC (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, + AccountID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, RVUWeight, + PatientClassID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value) + SELECT VW.BudgetConfigID, VW.EntityGroupConfigID, EntityID, VW.DepartmentID, + cc.AccountID, VW.ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, cc.RVUWeight, + VW.PatientClassID, UnitTypeID, TimeClassID, VW.FiscalYearID, FiscalMonthID, Value + FROM [fp].viewFactChargeToStatisticsCrosswalkHistory_Unpivoted_source VW + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = VW.DepartmentID + INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigID = VW.BudgetConfigID + INNER JOIN [fp].[EntityGroupConfig] e ON e.BudgetConfigGUID=bc.BudgetConfigGUID + INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] cc ON cc.EntityGroupConfigID = e.EntityGroupConfigID + AND cc.DepartmentID = VW.DepartmentID + AND cc.PatientClassID = VW.PatientClassID + AND cc.ChargeCodeID = VW.ChargeCodeID + AND cc.EntityGroupConfigID = VW.EntityGroupConfigID + WHERE VW.BudgetConfigID = @BudgetConfigID + AND Value != 0 + + INSERT INTO #SRC (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, + AccountID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, RVUWeight, + PatientClassID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value) + SELECT VW.BudgetConfigID, VW.EntityGroupConfigID, EntityID, VW.DepartmentID, + cc.AccountID, VW.ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, cc.RVUWeight, + VW.PatientClassID, 34 as UnitTypeID, TimeClassID, VW.FiscalYearID, FiscalMonthID, Value + FROM [fp].viewFactChargeDollarsToStatisticsCrosswalkHistory_Unpivoted_source VW + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = VW.DepartmentID + INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigID = VW.BudgetConfigID + INNER JOIN [fp].[EntityGroupConfig] e ON e.BudgetConfigGUID=bc.BudgetConfigGUID + INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] cc ON cc.EntityGroupConfigID = e.EntityGroupConfigID + AND cc.DepartmentID = VW.DepartmentID + AND cc.PatientClassID = VW.PatientClassID + AND cc.ChargeCodeID = VW.ChargeCodeID + AND cc.EntityGroupConfigID = VW.EntityGroupConfigID + WHERE VW.BudgetConfigID = @BudgetConfigID + AND Value != 0 + + CREATE CLUSTERED INDEX inx_src ON #SRC ( + BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + AccountID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + PatientClassID, + UnitTypeID, + TimeClassID, + FiscalYearID, + FiscalMonthID + ) + + -- Get all of the departments in that could be affected. We need to get this list to eliminate + -- the null check in the join in the with statement. + SELECT DISTINCT DepartmentID INTO #departments + FROM ( + SELECT DISTINCT DepartmentID FROM #SRC + UNION ALL + SELECT DISTINCT DepartmentID FROM #SourceDimensionality + ) data + + ;WITH TGT AS + ( + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, FRS.DepartmentID, AccountID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, RVUWeight, + PatientClassID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value + FROM fp.FactReportChargeToStatisticsCrosswalkHistory FRS + INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID + WHERE FRS.BudgetConfigID = @BudgetConfigID + ) + MERGE TGT AS target + USING #SRC AS source + ON ( + target.BudgetConfigID = source.BudgetConfigID + AND target.EntityGroupConfigID = source.EntityGroupConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.AccountID = source.AccountID + AND target.ChargeCodeID = source.ChargeCodeID + AND target.ServiceLineID = source.ServiceLineID + AND target.AgeCohortID = source.AgeCohortID + AND target.MedicalSurgicalID = source.MedicalSurgicalID + AND target.PatientClassID = source.PatientClassID + AND target.UnitTypeID = source.UnitTypeID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalYearID = source.FiscalYearID + AND target.FiscalMonthID = source.FiscalMonthID) + WHEN MATCHED AND (target.Value <> source.Value OR target.RVUWeight <> source.RVUWeight) + THEN + UPDATE SET + target.Value = source.Value, + target.RVUWeight = source.RVUWeight + WHEN NOT MATCHED BY TARGET + THEN + INSERT (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, ChargeCodeID, ServiceLineID, + AgeCohortID, MedicalSurgicalID, RVUWeight, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value) + VALUES ( + source.BudgetConfigID + ,source.EntityGroupConfigID + ,source.EntityID + ,source.DepartmentID + ,source.AccountID + ,source.PatientClassID + ,source.ChargeCodeID + ,source.ServiceLineID + ,source.AgeCohortID + ,source.MedicalSurgicalID + ,source.RVUWeight + ,source.UnitTypeID + ,source.TimeClassID + ,source.FiscalYearID + ,source.FiscalMonthID + ,source.Value + ) + WHEN NOT MATCHED BY Source + THEN + DELETE; +END +GO + + +--------------------------------------------- + +-- fp.ProcReportFactEncounterBackup +CREATE PROCEDURE fp.ProcReportFactEncounterBackup ( + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +) +WITH RECOMPILE +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-07-23 NN JAZZ-21 Create proc + ** 2 2020-13-08 MY JAZZ-4079 Adding feature flag to short circuit the proc + ** 3 2020-01-02 MY JAZZ-14421 Remove old FF call that is no longer needed + ** 4 2021-11-10 BW JAZZ-1358 Add dept to the filter when untargeted, to remove orphans + *************************************************************/ + + EXEC [dbo].[procSysDropTempTable] '#SRC' + EXEC [dbo].[procSysDropTempTable] '#SourceDimensionality' + EXEC [dbo].[procSysDropTempTable] '#departments' + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + + SELECT DISTINCT DepartmentID INTO #SourceDimensionality from fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #SourceDimensionality (DepartmentID) + SELECT DISTINCT DepartmentID FROM [fp].[ServiceLineEncounter] + WHERE BudgetConfigID = @BudgetConfigID + END + + CREATE TABLE #SRC ( + BudgetConfigID INT, + EntityID INT, + DepartmentID INT, + ServiceLineID INT, + ServiceLineRollupID INT, + PatientClassID INT, + AgeCohortID INT, + MedicalSurgicalID INT, + PayorID INT, + PayorGroupID INT, + MSDRGID INT, + CPTID INT, + ProviderID INT, + PhysicianSpecialtyID INT, + UnitTypeID SMALLINT, + TimeClassID TINYINT, + FiscalMonthID TINYINT, + FiscalYearID SMALLINT, + OriginalValue DECIMAL(19, 8), + Value DECIMAL(19, 8), + ManagerValue DECIMAL(19, 8) + ) + + IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #SRC (BudgetConfigID, EntityID, VW.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, + PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue, Value, ManagerValue) + SELECT BudgetConfigID, EntityID, VW.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, + PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue, Value, ManagerValue + FROM [fp].[viewFactEncounter_Unpivoted_source] VW + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = VW.DepartmentID + WHERE VW.BudgetConfigID = @BudgetConfigID + AND (OriginalValue != 0 or Value != 0 or ManagerValue != 0) + END ELSE BEGIN + INSERT INTO #SRC (BudgetConfigID, EntityID, VW.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, + PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue, Value, ManagerValue) + SELECT BudgetConfigID, EntityID, VW.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, + PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue, Value, ManagerValue + FROM [fp].[viewFactEncounter_Unpivoted_source] VW + WHERE VW.BudgetConfigID = @BudgetConfigID + AND (OriginalValue != 0 or Value != 0 or ManagerValue != 0) + END + + CREATE CLUSTERED INDEX inx_src ON #SRC ( + BudgetConfigID + ,EntityID + ,DepartmentID + ,ServiceLineID + ,ServiceLineRollupID + ,PatientClassID + ,AgeCohortID + ,MedicalSurgicalID + ,PayorID + ,PayorGroupID + ,MSDRGID + ,CPTID + ,ProviderID + ,PhysicianSpecialtyID + ,UnitTypeID + ,TimeClassID + ,FiscalMonthID + ,FiscalYearID + ) + + -- Get all of the departments in that could be affected. We need to get this list to eliminate + -- the null check in the join in the with statement. + SELECT DISTINCT DepartmentID INTO #departments + FROM ( + SELECT DISTINCT DepartmentID FROM #SRC + UNION ALL + SELECT DISTINCT DepartmentID FROM #SourceDimensionality + ) data + + ;WITH TGT AS + ( + SELECT BudgetConfigID, EntityID, FRE.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, + PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue, Value, ManagerValue + FROM [fp].[FactReportEncounter] FRE + INNER JOIN #departments ft on ft.DepartmentID = FRE.DepartmentID + WHERE FRE.BudgetConfigID = @BudgetConfigID + ) + MERGE TGT AS target + USING #SRC AS source + ON ( + target.BudgetConfigID = source.BudgetConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.ServiceLineID = source.ServiceLineID + AND target.ServiceLineRollupID = source.ServiceLineRollupID + AND target.PatientClassID = source.PatientClassID + AND target.AgeCohortID = source.AgeCohortID + AND target.MedicalSurgicalID = source.MedicalSurgicalID + AND target.PayorID = source.PayorID + AND target.PayorGroupID = source.PayorGroupID + AND target.MSDRGID = source.MSDRGID + AND target.CPTID = source.CPTID + AND target.ProviderID = source.ProviderID + AND target.PhysicianSpecialtyID= source.PhysicianSpecialtyID + AND target.UnitTypeID = source.UnitTypeID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + + ) + WHEN MATCHED AND (target.OriginalValue <> source.OriginalValue + OR target.Value <> source.Value + OR target.ManagerValue <> source.ManagerValue) + THEN + UPDATE SET + target.OriginalValue = ISNULL(source.OriginalValue, 0), + target.Value = ISNULL(source.Value, 0), + target.ManagerValue = ISNULL(source.ManagerValue, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + BudgetConfigID + ,EntityID + ,DepartmentID + ,ServiceLineID + ,ServiceLineRollupID + ,PatientClassID + ,AgeCohortID + ,MedicalSurgicalID + ,PayorID + ,PayorGroupID + ,MSDRGID + ,CPTID + ,ProviderID + ,PhysicianSpecialtyID + ,UnitTypeID + ,TimeClassID + ,FiscalMonthID + ,FiscalYearID + ,OriginalValue + ,Value + ,ManagerValue + ) + VALUES ( + source.BudgetConfigID + ,source.EntityID + ,source.DepartmentID + ,source.ServiceLineID + ,source.ServiceLineRollupID + ,source.PatientClassID + ,source.AgeCohortID + ,source.MedicalSurgicalID + ,source.PayorID + ,source.PayorGroupID + ,source.MSDRGID + ,source.CPTID + ,source.ProviderID + ,source.PhysicianSpecialtyID + ,source.UnitTypeID + ,source.TimeClassID + ,source.FiscalMonthID + ,source.FiscalYearID + ,ISNULL(source.OriginalValue, 0) + ,ISNULL(source.Value, 0) + ,ISNULL(source.ManagerValue, 0) + ) + WHEN NOT MATCHED BY Source + THEN + DELETE; + + ------------------------------------------------------------------------------------------------------- + -- D-09168 : CCF: Data not flowing through into reports + -- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the + -- targeting above. This is a short term solution until we can get a more performant solution. + ------------------------------------------------------------------------------------------------------- + + -- Check if targeting exists, if it doesn't for this part, wipe it and populate all departments + -- We can't rely on the existing departments because of the check for the padded rows. + IF NOT EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL) + BEGIN + + TRUNCATE TABLE #departments; + + INSERT INTO #departments (DepartmentID) + SELECT DepartmentID + FROM [fw].[DimDepartment] dept + + END + + -- Get all records that were adjusted + SELECT DISTINCT chg.ServiceLineEncounterID + INTO #adjustedRecords + FROM [fp].[ServiceLineEncounterChangeHistory] chg + INNER JOIN [fp].[ServiceLineEncounter] fse ON chg.ServiceLineEncounterID = fse.ServiceLineEncounterID + INNER JOIN [fp].[ServiceLineEncounterAdjustment] adj ON chg.AdjustmentGUID = adj.AdjustmentGUID + INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN #departments ft on ft.DepartmentID = fse.DepartmentID + WHERE bc.BudgetConfigID = @BudgetConfigID + + -- Get the records that have 0's in them that might have been filtered out from the previous logic + SELECT src.ServiceLineEncounterID, src.BudgetConfigID, src.EntityID, src.DepartmentID, src.ServiceLineID, src.ServiceLineRollupID, src.PatientClassID, + src.AgeCohortID, src.MedicalSurgicalID, src.PayorID, src.PayorGroupID, src.MSDRGID, src.CPTID, src.ProviderID, src.PhysicianSpecialtyID, src.UnitTypeID, + src.TimeClassID, src.FiscalMonthID, src.FiscalYearID, src.OriginalValue, src.Value, src.ManagerValue + INTO #tempUnpivoted + FROM #adjustedRecords adj + INNER JOIN [fp].[viewFactEncounter_Unpivoted_source] src ON src.ServiceLineEncounterID = adj.ServiceLineEncounterID + WHERE src.BudgetConfigID = @BudgetConfigID + AND (src.OriginalValue = 0 OR src.Value = 0 OR src.ManagerValue = 0) + + -- Find the records that need to be updated by comparing the source to the reporting table + SELECT target.ServiceLineEncounterID, target.BudgetConfigID, target.EntityID, target.DepartmentID, target.ServiceLineID, target.ServiceLineRollupID, target.PatientClassID, + target.AgeCohortID, target.MedicalSurgicalID, target.PayorID, target.PayorGroupID, target.MSDRGID, target.CPTID, target.ProviderID, target.PhysicianSpecialtyID, + target.UnitTypeID, target.TimeClassID, target.FiscalMonthID, target.FiscalYearID, target.OriginalValue, target.Value, target.ManagerValue + INTO #dataToUpdate + FROM [fp].[FactReportEncounter] source + INNER JOIN #departments ft on ft.DepartmentID = source.DepartmentID + INNER JOIN #tempUnpivoted target ON target.BudgetConfigID = source.BudgetConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.ServiceLineID = source.ServiceLineID + AND target.ServiceLineRollupID = source.ServiceLineRollupID + AND target.PatientClassID = source.PatientClassID + AND target.AgeCohortID = source.AgeCohortID + AND target.MedicalSurgicalID = source.MedicalSurgicalID + AND target.PayorGroupID = source.PayorGroupID + AND target.PayorID = source.PayorID + AND target.MSDRGID = source.MSDRGID + AND target.CPTID = source.CPTID + AND target.ProviderID = source.ProviderID + AND target.PhysicianSpecialtyID = source.PhysicianSpecialtyID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + WHERE source.BudgetConfigID = @BudgetConfigID + AND (target.OriginalValue != source.OriginalValue OR target.Value != source.Value OR target.ManagerValue != source.ManagerValue) + + -- Update the records + UPDATE source + SET source.OriginalValue = ISNULL(target.OriginalValue, 0), + source.Value = ISNULL(target.Value, 0), + source.ManagerValue = ISNULL(target.ManagerValue, 0) + FROM [fp].[FactReportEncounter] source + INNER JOIN #departments ft on ft.DepartmentID = source.DepartmentID + INNER JOIN #dataToUpdate target ON target.BudgetConfigID = source.BudgetConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.ServiceLineID = source.ServiceLineID + AND target.ServiceLineRollupID = source.ServiceLineRollupID + AND target.PatientClassID = source.PatientClassID + AND target.AgeCohortID = source.AgeCohortID + AND target.MedicalSurgicalID = source.MedicalSurgicalID + AND target.PayorGroupID = source.PayorGroupID + AND target.PayorID = source.PayorID + AND target.MSDRGID = source.MSDRGID + AND target.CPTID = source.CPTID + AND target.ProviderID = source.ProviderID + AND target.PhysicianSpecialtyID = source.PhysicianSpecialtyID + AND target.UnitTypeID = source.UnitTypeID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + +END +GO + + +--------------------------------------------- + +-- fp.ProcReportFactEncounterHistoryBackup +CREATE PROCEDURE fp.ProcReportFactEncounterHistoryBackup ( + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY) +WITH RECOMPILE +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-07-23 NN JAZZ-21 Create proc + ** 2 2020-13-08 MY JAZZ-4079 Adding feature flag to short circuit the proc + ** 3 2020-01-02 MY JAZZ-14421 Remove old FF call that is no longer needed + ** 4 2021-11-10 BW JAZZ-1358 Add dept to the filter when untargeted, to remove orphans + ** 5 2023-05-19 BY JAZZ-55153 Update to restructure + *************************************************************/ + + exec [dbo].[procSysDropTempTable] '#SRC' + exec [dbo].[procSysDropTempTable] '#SourceDimensionality' + exec [dbo].[procSysDropTempTable] '#departments' + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + + SELECT DISTINCT DepartmentID INTO #SourceDimensionality FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #SourceDimensionality (DepartmentID) + SELECT DISTINCT DepartmentID FROM [fp].[ServiceLineEncounter] + WHERE BudgetConfigID = @BudgetConfigID + END + + CREATE TABLE #SRC ( + ServiceLineEncounterID INT, + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + DepartmentID INT, + ServiceLineID INT, + ServiceLineRollupID INT, + PatientClassID INT, + AgeCohortID INT, + MedicalSurgicalID INT, + PayorID INT, + PayorGroupID INT, + MSDRGID INT, + CPTID INT, + ProviderID INT, + PhysicianSpecialtyID INT, + UnitTypeID SMALLINT, + TimeClassID TINYINT, + FiscalYearID SMALLINT, + FiscalMonthID TINYINT, + Value DECIMAL(19, 8) + ) + + IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #SRC (ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, + AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value) + SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, + AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value + FROM [fp].viewFactEncounterHistory_Unpivoted_source VW + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = VW.DepartmentID + WHERE VW.BudgetConfigID = @BudgetConfigID + AND Value != 0 + END ELSE BEGIN + INSERT INTO #SRC (ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, + AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value) + SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, + AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value + FROM [fp].viewFactEncounterHistory_Unpivoted_source VW + WHERE VW.BudgetConfigID = @BudgetConfigID + AND Value != 0 + END + + CREATE CLUSTERED INDEX inx_src ON #SRC ( + ServiceLineEncounterID, + BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + ServiceLineID, + ServiceLineRollupID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + PayorID, + PayorGroupID, + MSDRGID, + CPTID, + ProviderID, + PhysicianSpecialtyID, + UnitTypeID, + TimeClassID, + FiscalYearID, + FiscalMonthID + ) + + -- Get all of the departments in that could be affected. We need to get this list to eliminate + -- the null check in the join in the with statement. + SELECT DISTINCT DepartmentID INTO #departments + FROM ( + SELECT DISTINCT DepartmentID FROM #SRC + UNION ALL + SELECT DISTINCT DepartmentID FROM #SourceDimensionality + ) data + + ;WITH TGT AS + ( + SELECT ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, FRE.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, + MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value + FROM [fp].[FactReportEncounterHistory] FRE + INNER JOIN #departments ft on ft.DepartmentID = FRE.DepartmentID + WHERE FRE.BudgetConfigID = @BudgetConfigID + ) + + MERGE TGT AS target + USING #SRC AS source + ON ( + target.ServiceLineEncounterID = source.ServiceLineEncounterID + AND target.BudgetConfigID = source.BudgetConfigID + AND target.EntityGroupConfigID = source.EntityGroupConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.ServiceLineID = source.ServiceLineID + AND target.ServiceLineRollupID = source.ServiceLineRollupID + AND target.PatientClassID = source.PatientClassID + AND target.AgeCohortID = source.AgeCohortID + AND target.MedicalSurgicalID = source.MedicalSurgicalID + AND target.PayorID = source.PayorID + AND target.PayorGroupID = source.PayorGroupID + AND target.MSDRGID = source.MSDRGID + AND target.CPTID = source.CPTID + AND target.ProviderID = source.ProviderID + AND target.PhysicianSpecialtyID = source.PhysicianSpecialtyID + AND target.UnitTypeID = source.UnitTypeID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalYearID = source.FiscalYearID + AND target.FiscalMonthID = source.FiscalMonthID) + + + WHEN MATCHED AND target.Value <> source.Value + THEN + UPDATE SET + target.Value = source.Value + WHEN NOT MATCHED BY TARGET + THEN + INSERT (ServiceLineEncounterID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, + MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value) + VALUES ( + source.ServiceLineEncounterID + ,source.BudgetConfigID + ,source.EntityGroupConfigID + ,source.EntityID + ,source.DepartmentID + ,source.ServiceLineID + ,source.ServiceLineRollupID + ,source.PatientClassID + ,source.AgeCohortID + ,source.MedicalSurgicalID + ,source.PayorID + ,source.PayorGroupID + ,source.MSDRGID + ,source.CPTID + ,source.ProviderID + ,source.PhysicianSpecialtyID + ,source.UnitTypeID + ,source.TimeClassID + ,source.FiscalYearID + ,source.FiscalMonthID + ,source.Value + ) + WHEN NOT MATCHED BY Source + THEN + DELETE; + END +GO + + +--------------------------------------------- + +-- fp.ProcReportFactGeneralLedgerHistoryBackup +CREATE PROCEDURE [fp].[ProcReportFactGeneralLedgerHistoryBackup] ( +@BudgetConfigID INT, +@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY) +WITH RECOMPILE +AS +BEGIN +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-12-24 IP B-21543 Added temp table to index source as well +** 2 2018-12-25 IP B-21543 Optimized refreshment of tables (refactored joining to @SourceDimensionality) +** 3 2019-01-09 GF B-21715 Optimize full config refresh case +** 4 2019-01-11 GF B-21715 Optimize targeted refresh case +** 5 2019-05-02 GF Remove special handling of all case to make concurrency work +** 6 2019-07-22 MY Performance updates +** 7 2021-11-10 BW JAZZ-1358 Add dept to the filter when untargeted, to remove orphans +** 8 2023-08-11 BK JAZZ-58752 Update for new gl data structure +** 9 2024-04-11 DM JAZZ-70189 Budget Config used for Report comparison is processed as well +*************************************************************/ + +exec [dbo].[procSysDropTempTable] '#SRC' +exec [dbo].[procSysDropTempTable] '#SourceDimensionality' +exec [dbo].[procSysDropTempTable] '#departments' + +--only the active config is supported currently +IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE (IsActive = 1 OR IsUsedForReportComparison = 1) AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + +SELECT DISTINCT DepartmentID INTO #SourceDimensionality FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + +IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL) +BEGIN + INSERT INTO #SourceDimensionality (DepartmentID) + SELECT DISTINCT DepartmentID FROM fp.GeneralLedger + WHERE BudgetConfigID = @BudgetConfigID +END + +CREATE TABLE #SRC( + GeneralLedgerID INT + ,BudgetConfigID INT + ,EntityGroupConfigID INT + ,EntityID INT + ,DepartmentID INT + ,AccountID INT + ,FinancialReportingID INT + ,APEModelSectionID INT + ,VariabilityID INT + ,UnitTypeID TINYINT + ,TimeClassID TINYINT + ,FiscalYearID SMALLINT + ,FiscalMonthID TINYINT + ,Value DECIMAL(19, 8) +) + +IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL) +BEGIN + INSERT INTO #SRC(GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value) + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value + FROM [fp].[viewFactGeneralLedgerHistory_Unpivoted_source] VW + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = VW.DepartmentID + WHERE VW.BudgetConfigID = @BudgetConfigID + AND Value != 0 +END ELSE BEGIN + INSERT INTO #SRC(GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value) + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value + FROM [fp].[viewFactGeneralLedgerHistory_Unpivoted_source] VW + WHERE VW.BudgetConfigID = @BudgetConfigID + AND Value != 0 +END + +CREATE CLUSTERED INDEX inx_src ON #SRC ( + GeneralLedgerID + ,BudgetConfigID + ,EntityGroupConfigID + ,EntityID + ,DepartmentID + ,AccountID + ,FinancialReportingID + ,APEModelSectionID + ,VariabilityID + ,UnitTypeID + ,TimeClassID + ,FiscalYearID + ,FiscalMonthID) + +-- Get all of the departments in that could be affected. We need to get this list to eliminate +-- the null check in the join in the with statement. +SELECT DISTINCT DepartmentID INTO #departments +FROM ( + SELECT DISTINCT DepartmentID FROM #SRC + UNION ALL + SELECT DISTINCT DepartmentID FROM #SourceDimensionality +) data + +;WITH TGT AS +( + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, FRS.DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value + FROM fp.FactReportGeneralLedgerHistory FRS + INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID + WHERE FRS.BudgetConfigID = @BudgetConfigID +) + MERGE TGT AS target + USING #SRC AS source + ON ( + target.GeneralLedgerID = source.GeneralLedgerID + AND target.BudgetConfigID = source.BudgetConfigID + AND target.EntityGroupConfigID = source.EntityGroupConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.AccountID = source.AccountID + AND target.FinancialReportingID = source.FinancialReportingID + AND target.APEModelSectionID = source.APEModelSectionID + AND target.VariabilityID = source.VariabilityID + AND target.UnitTypeID = source.UnitTypeID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalYearID = source.FiscalYearID + AND target.FiscalMonthID = source.FiscalMonthID + ) + WHEN MATCHED AND target.Value <> source.Value + THEN + UPDATE + SET + target.Value = source.Value + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + GeneralLedgerID + ,BudgetConfigID + ,EntityGroupConfigID + ,EntityID + ,DepartmentID + ,AccountID + ,FinancialReportingID + ,APEModelSectionID + ,VariabilityID + ,UnitTypeID + ,TimeClassID + ,FiscalYearID + ,FiscalMonthID + ,Value + ) + VALUES ( + source.GeneralLedgerID + ,source.BudgetConfigID + ,source.EntityGroupConfigID + ,source.EntityID + ,source.DepartmentID + ,source.AccountID + ,source.FinancialReportingID + ,source.APEModelSectionID + ,source.VariabilityID + ,source.UnitTypeID + ,source.TimeClassID + ,source.FiscalYearID + ,source.FiscalMonthID + ,source.Value + ) + WHEN NOT MATCHED BY Source + THEN + DELETE; +END +GO + + +--------------------------------------------- + +-- fp.ProcReportFactStaffingHistoryBackup +CREATE PROCEDURE [fp].[ProcReportFactStaffingHistoryBackup] ( + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY) +WITH RECOMPILE +AS +BEGIN +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-12-24 IP B-21543 Added temp table to index source as well +** 2 2019-01-09 GF B-21715 Optimize full config refresh case +** 3 2019-01-11 GF B-21715 Optimize targeted refresh case +** 4 2019-05-02 GF Remove special handling of all case to make concurrency work +** 6 2019-07-22 MY Performance updates to reports +** 7 2019-11-13 MD B-24632 Add EmployeeID to staffing sampling +** 6 2020-02-18 MY JAZZ-15375 Roll-up data above Provider for Report +** 9 2021-11-30 SD JAZZ-30301 add provider dimensions to Staffing reporting data sources +** 10 2024-07-04 DM JAZZ-70314 Budget Config used for Report comparison is processed as well +*************************************************************/ +exec [dbo].[procSysDropTempTable] '#SRC' +exec [dbo].[procSysDropTempTable] '#SourceDimensionality' +exec [dbo].[procSysDropTempTable] '#departments' + +--only the active config is supported currently +IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE (IsActive = 1 OR IsUsedForReportComparison = 1) AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + +SELECT DISTINCT DepartmentID INTO #SourceDimensionality FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + +CREATE TABLE #SRC ( + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + DepartmentID INT, + JobCodeID INT, + PayCodeGroupID INT, + ProductiveClassID INT, + VariabilityID INT, + UnitTypeID SMALLINT, + TimeClassID TINYINT, + FiscalYearID SMALLINT, + FiscalMonthID TINYINT, + Value DECIMAL(19, 8), + EmployeeID INT, + ProviderID INT, + ProviderLineItemID INT, + ProviderTypeID INT, + ProviderSpecialtyID INT +) + +IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL) +BEGIN + INSERT INTO #SRC (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value, EmployeeID, ProviderID, ProviderLineItemID, + ProviderTypeID, ProviderSpecialtyID) + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, SUM(Value), EmployeeID, ProviderID, ProviderLineItemID, + ProviderTypeID, ProviderSpecialtyID + FROM [fp].viewFactStaffingHistory_Unpivoted_source VW + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = VW.DepartmentID + WHERE VW.BudgetConfigID = @BudgetConfigID + AND Value != 0 + GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, EmployeeID, ProviderID, ProviderLineItemID, + ProviderTypeID, ProviderSpecialtyID +END ELSE BEGIN + INSERT INTO #SRC (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value, EmployeeID, ProviderID, ProviderLineItemID, + ProviderTypeID, ProviderSpecialtyID) + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, SUM(Value), EmployeeID, ProviderID, ProviderLineItemID, + ProviderTypeID, ProviderSpecialtyID + FROM [fp].viewFactStaffingHistory_Unpivoted_source VW + WHERE VW.BudgetConfigID = @BudgetConfigID + AND Value != 0 + GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, EmployeeID, ProviderID, ProviderLineItemID, + ProviderTypeID, ProviderSpecialtyID +END + +CREATE CLUSTERED INDEX inx_src ON #SRC ( + BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + JobCodeID, + PayCodeGroupID, + ProductiveClassID, + VariabilityID, + UnitTypeID, + TimeClassID, + FiscalYearID, + FiscalMonthID, + EmployeeID, + ProviderID, + ProviderLineItemID, + ProviderTypeID, + ProviderSpecialtyID +) + +-- Get all of the departments in that could be affected. We need to get this list to eliminate +-- the null check in the join in the with statement. +SELECT DISTINCT DepartmentID INTO #departments +FROM ( + SELECT DISTINCT DepartmentID FROM #SRC + UNION ALL + SELECT DISTINCT DepartmentID FROM #SourceDimensionality +) data + +;WITH TGT AS +( + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, FRS.DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, Value, EmployeeID, ProviderID, ProviderLineItemID, + ProviderTypeID, ProviderSpecialtyID + FROM fp.FactReportStaffingHistory FRS + INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID + WHERE FRS.BudgetConfigID = @BudgetConfigID +) + + MERGE TGT AS target + USING #SRC AS source + ON ( + target.BudgetConfigID=source.BudgetConfigID + and target.EntityGroupConfigID=source.EntityGroupConfigID + and target.EntityID=source.EntityID + and target.DepartmentID=source.DepartmentID + and target.JobCodeID=source.JobCodeID + and target.PayCodeGroupID=source.PayCodeGroupID + and target.ProductiveClassID=source.ProductiveClassID + and target.VariabilityID=source.VariabilityID + and target.UnitTypeID=source.UnitTypeID + and target.TimeClassID=source.TimeClassID + and target.FiscalYearID=source.FiscalYearID + and target.FiscalMonthID=source.FiscalMonthID + and target.EmployeeID=source.EmployeeID + AND target.ProviderID= source.ProviderID + AND target.ProviderLineItemID= source.ProviderLineItemID + AND target.ProviderTypeID= source.ProviderTypeID + AND target.ProviderSpecialtyID= source.ProviderSpecialtyID + ) + + WHEN MATCHED AND target.Value <> source.Value + THEN + UPDATE SET + target.Value = source.Value + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + BudgetConfigID + ,EntityGroupConfigID + ,EntityID + ,DepartmentID + ,JobCodeID + ,PayCodeGroupID + ,ProductiveClassID + ,VariabilityID + ,UnitTypeID + ,TimeClassID + ,FiscalYearID + ,FiscalMonthID + ,Value + ,EmployeeID + ,ProviderID + ,ProviderLineItemID + ,ProviderTypeID + ,ProviderSpecialtyID + ) + VALUES ( + source.BudgetConfigID + ,source.EntityGroupConfigID + ,source.EntityID + ,source.DepartmentID + ,source.JobCodeID + ,source.PayCodeGroupID + ,source.ProductiveClassID + ,source.VariabilityID + ,source.UnitTypeID + ,source.TimeClassID + ,source.FiscalYearID + ,source.FiscalMonthID + ,source.Value + ,source.EmployeeID + ,source.ProviderID + ,source.ProviderLineItemID + ,source.ProviderTypeID + ,source.ProviderSpecialtyID + ) + WHEN NOT MATCHED BY Source + THEN + DELETE; +END +GO + + +--------------------------------------------- + +-- fp.ProcReportFactStatisticsHistoryBackup +CREATE PROCEDURE [fp].[ProcReportFactStatisticsHistoryBackup] ( +@BudgetConfigID INT, +@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY) +WITH RECOMPILE +AS +BEGIN +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-12-24 IP B-21543 Added temp table to index source as well +** 2 2019-01-09 GF B-21715 Optimize full config refresh case +** 3 2019-01-11 GF B-21715 Optimize targeted refresh case +** 4 2019-05-02 GF Remove special handling of all case to make concurrency work +** 5 2019-07-22 MY Performance updates +** 6 2020-02-18 MY JAZZ-15375 Roll-up data above Provider for Report +** 7 2021-05-10 MD JAZZ-15686 Add Provider dimensions to Stats data sources +** 8 2021-11-10 BW JAZZ-1358 Add dept to the filter when untargeted, to remove orphans +** 9 2024-07-16 YR JAZZ-70315 Budget Config used for Report comparison is processed as well +*************************************************************/ +exec [dbo].[procSysDropTempTable] '#SRC' +exec [dbo].[procSysDropTempTable] '#SourceDimensionality' +exec [dbo].[procSysDropTempTable] '#departments' + +--only the active config is supported currently +IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE (IsActive = 1 OR IsUsedForReportComparison = 1) AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + +SELECT DISTINCT DepartmentID INTO #SourceDimensionality FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + +IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL) +BEGIN + INSERT INTO #SourceDimensionality (DepartmentID) + SELECT DISTINCT DepartmentID FROM fp.FactStatistics + WHERE BudgetConfigID = @BudgetConfigID +END + +CREATE TABLE #SRC ( + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + DepartmentID INT, + AccountID INT, + FinancialReportingID INT, + PayorID INT, + PatientClassID INT, + UnitTypeID SMALLINT, + TimeClassID TINYINT, + FiscalYearID SMALLINT, + FiscalMonthID TINYINT, + ProviderID INT, + ProviderTypeID INT, + ProviderSpecialtyID INT, + ProviderLineItemID INT, + Value DECIMAL(19, 8) +) + +IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL) +BEGIN + INSERT INTO #SRC (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PayorID, + PatientClassID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, Value) + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, AccountID, FinancialReportingID, PayorID, + PatientClassID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SUM(Value) + FROM [fp].viewFactStatisticsHistory_Unpivoted_source VW + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = VW.DepartmentID + WHERE VW.BudgetConfigID = @BudgetConfigID + AND Value != 0 + GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, AccountID, FinancialReportingID, PayorID, + PatientClassID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID +END ELSE BEGIN + INSERT INTO #SRC (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PayorID, + PatientClassID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, Value) + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, AccountID, FinancialReportingID, PayorID, + PatientClassID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SUM(Value) + FROM [fp].viewFactStatisticsHistory_Unpivoted_source VW + WHERE VW.BudgetConfigID = @BudgetConfigID + AND Value != 0 + GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, AccountID, FinancialReportingID, PayorID, + PatientClassID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID +END + +CREATE CLUSTERED INDEX inx_src ON #SRC ( + BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + AccountID, + FinancialReportingID, + PayorID, + PatientClassID, + UnitTypeID, + TimeClassID, + FiscalYearID, + FiscalMonthID, + ProviderID, + ProviderTypeID, + ProviderSpecialtyID, + ProviderLineItemID +) WITH (DATA_COMPRESSION = PAGE) + +-- Get all of the departments in that could be affected. We need to get this list to eliminate +-- the null check in the join in the with statement. +SELECT DISTINCT DepartmentID INTO #departments +FROM ( + SELECT DISTINCT DepartmentID FROM #SRC + UNION ALL + SELECT DISTINCT DepartmentID FROM #SourceDimensionality +) data + +;WITH TGT AS +( + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, FRS.DepartmentID, AccountID, FinancialReportingID, PayorID, + PatientClassID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, Value + FROM fp.FactReportStatisticsHistory FRS + INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID + WHERE FRS.BudgetConfigID = @BudgetConfigID +) + + MERGE TGT AS target + USING #SRC AS source + ON ( + target.BudgetConfigID = source.BudgetConfigID + AND target.EntityGroupConfigID = source.EntityGroupConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.AccountID = source.AccountID + AND target.FinancialReportingID = source.FinancialReportingID + AND target.PayorID = source.PayorID + AND target.PatientClassID = source.PatientClassID + AND target.UnitTypeID = source.UnitTypeID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalYearID = source.FiscalYearID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.ProviderID = source.ProviderID + AND target.ProviderTypeID = source.ProviderTypeID + AND target.ProviderSpecialtyID = source.ProviderSpecialtyID + AND target.ProviderLineItemID = source.ProviderLineItemID) + WHEN MATCHED AND target.Value <> source.Value + THEN + UPDATE SET + target.Value = source.Value + WHEN NOT MATCHED BY TARGET + THEN + INSERT (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, PayorID, + PatientClassID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, Value) + VALUES ( + source.BudgetConfigID + ,source.EntityGroupConfigID + ,source.EntityID + ,source.DepartmentID + ,source.AccountID + ,source.FinancialReportingID + ,source.PayorID + ,source.PatientClassID + ,source.UnitTypeID + ,source.TimeClassID + ,source.FiscalYearID + ,source.FiscalMonthID + ,source.ProviderID + ,source.ProviderTypeID + ,source.ProviderSpecialtyID + ,source.ProviderLineItemID + ,source.Value + ) + WHEN NOT MATCHED BY Source + THEN + DELETE; +END +GO + + +--------------------------------------------- + +-- fp.ProviderCompensationAdjustment_SEL_LIST +CREATE PROCEDURE [fp].[ProviderCompensationAdjustment_SEL_LIST] + @budgetGUID UNIQUEIDENTIFIER, + @start INT, + @end INT, + @search VARCHAR(MAX), + @filter VARCHAR(MAX), + @userGUID UNIQUEIDENTIFIER, + @isDataSecured BIT, + @dateTimeFormat VARCHAR(30), + @userTimeZone VARCHAR(50) +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-02-02 OP JAZZ-14151 Created SP + ** 2 2021-10-13 VZ JAZZ-40848 Added Add Provider Adjustments + ** 3 2024-02-22 MY JAZZ-67143 Filters acting unexpectedly post-adjustment - Issue #2 + *************************************************************/ +BEGIN + + -- Contains all DepartmnetID with correspond EntityID that are allowed for current user + CREATE TABLE #departmentsSecurity ( + DepartmentID INT NULL, + EntityID INT NULL + ) + + -- Adjustments that passes security check + CREATE TABLE #securedAdjustments ( + AdjustmentGUID UNIQUEIDENTIFIER + ) + + DECLARE @guidEmpty UNIQUEIDENTIFIER = [dbo].[ZeroGUID]() + DECLARE @pageSize INT = @end - @start; + + SET @search = LOWER(NULLIF('%' + @search+ '%', '%\%')) + SET @filter = LOWER(NULLIF(@filter, '')) + + -- Select all possible to display adjustments + SELECT AdjustmentGUID + ,GroupingHierarchyJSON + ,JSON_VALUE(AdjustmentFilterJSON, '$.Entity.ID') AS EntityID + ,JSON_VALUE(AdjustmentFilterJSON, '$.Department.ID') AS DepartmentID + ,AdjustmentType + ,GroupingGUID + INTO #adjustments + FROM [fp].[StaffingAdjustment] AS slea WITH (NOLOCK) + WHERE slea.AdjustmentType IN (0, 2, 1, 4, 5, 6, 7, 8, 3, 10, 11, 12, 13, 14, 15) -- Supported Adjustment types for Staffing Provider Adjustments + AND slea.BudgetConfigGUID = @budgetGUID + + IF @isDataSecured = 1 + BEGIN + -- Get all departments that are allowed for current user + INSERT INTO #departmentsSecurity + EXEC fp.DepartmentsSecurity_SEL + @userGUID = @userGUID, + @pageName = 'Staffing' + + -- Creating index for faster selects + CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #departmentsSecurity (DepartmentID, EntityID) + + -- Select adjustments that have no Department/Entity on filters, but have DepartmentID + -- on grouping hierarchy level + SELECT AdjustmentGUID + ,ahd.ID AS DepartmentID + INTO #adjustmentGroupingHierarchyDepartments + FROM ( + SELECT adj.AdjustmentGUID + ,adj.GroupingHierarchyJSON + FROM #adjustments AS adj + -- Ignore departments that have DepartmentID and EntityID + WHERE adj.EntityID IS NULL + AND adj.DepartmentID IS NULL) AS slea + OUTER APPLY fp.GetAdjustmentHierarchyIDs(slea.GroupingHierarchyJSON, 'Department') AS ahd + GROUP BY AdjustmentGUID + ,ahd.ID + + -- Select adjustments that don't have DepartmentID on grouping hierarchy level + -- but have EntityID on grouping hierarchy level + SELECT adj.AdjustmentGUID, + ahe.ID AS EntityID + INTO #adjustmentGroupingHierarchyEntities + FROM #adjustments AS adj + JOIN #adjustmentGroupingHierarchyDepartments AS adhd ON adhd.AdjustmentGUID = adj.AdjustmentGUID + AND adhd.DepartmentID IS NULL + OUTER APPLY fp.GetAdjustmentHierarchyIDs(adj.GroupingHierarchyJSON, 'Entity') AS ahe + GROUP BY adj.AdjustmentGUID + ,ahe.ID + + INSERT INTO #securedAdjustments + SELECT res.AdjustmentGUID + FROM ( + -- Adjustmnets that passes Department security by DepartmentID + SELECT slea.AdjustmentGUID + FROM #adjustments AS slea + JOIN #departmentsSecurity AS ds ON ds.DepartmentID = slea.DepartmentID + GROUP BY slea.AdjustmentGUID + + UNION ALL + + -- Adjustmnets that passes Department security by EntityID + SELECT slea.AdjustmentGUID + FROM #adjustments AS slea + JOIN #departmentsSecurity AS dse ON dse.EntityID = slea.EntityID + WHERE slea.DepartmentID IS NULL + GROUP BY slea.AdjustmentGUID + + UNION ALL + + -- Insert adjustments that have allowed DepartmentID on their grouping hierarchy + SELECT aghd.AdjustmentGUID + FROM #adjustmentGroupingHierarchyDepartments AS aghd + JOIN #departmentsSecurity AS dshd ON dshd.DepartmentID = aghd.DepartmentID + WHERE dshd.DepartmentID IS NOT NULL + GROUP BY aghd.AdjustmentGUID + + UNION ALL + + -- Insert adjustments that have allowed EntityID on their grouping hierarchy + SELECT aghe.AdjustmentGUID + FROM #adjustmentGroupingHierarchyEntities AS aghe + JOIN #departmentsSecurity AS dshd ON dshd.EntityID = aghe.EntityID + GROUP BY aghe.AdjustmentGUID + + UNION ALL + + -- Insert all adjustments that have no connection to department or entity + SELECT adj.AdjustmentGUID + FROM #adjustments AS adj + JOIN #adjustmentGroupingHierarchyDepartments AS aghd ON aghd.AdjustmentGUID = adj.AdjustmentGUID + JOIN #adjustmentGroupingHierarchyEntities AS aghe ON aghe.AdjustmentGUID = adj.AdjustmentGUID + WHERE adj.DepartmentID IS NULL + AND adj.EntityID IS NULL + AND aghd.DepartmentID IS NULL + AND aghe.EntityID IS NULL + AND adj.AdjustmentType <> 15 -- Add provider adjustment, that has no grouping hierarchy, but has security + GROUP BY adj.AdjustmentGUID + + UNION ALL + + SELECT adj.AdjustmentGUID + FROM #adjustments AS adj + JOIN fp.ProvCompAddProviderAdjustment AS pcapa ON adj.AdjustmentGUID = pcapa.AdjustmentGUID + JOIN #departmentsSecurity AS ds ON ds.DepartmentID = pcapa.DepartmentID + GROUP BY adj.AdjustmentGUID + ) AS res + + -- JAZZ-67143: Filters acting unexpectedly post-adjustment (Issue #2) + -- Essentially we had cases where a custom roll up would cause local admins to make an adjustment and the + -- adjustment would not show up in the pane. This is due to roll up adjustments as everything else seems to be fine. + -- Essentially what we are doing here is using the child adjustments to find if they fall in security. + -- In the event we have a child, populate the parent adjustment in the list. + -- Find all the GroupingGuid's for any child adjustments that fall into security. + + SELECT DISTINCT adj.GroupingGUID + INTO #groupingAdjustments + FROM #securedAdjustments secured + INNER JOIN #adjustments adj ON secured.AdjustmentGUID = adj.AdjustmentGUID + WHERE adj.GroupingGUID != '00000000-0000-0000-0000-000000000000' -- Only care about roll up adjustments. + + -- Once we have the GroupingGUIDs based on the security, we can insert the parent adjustment. + INSERT INTO #securedAdjustments + SELECT adj.AdjustmentGUID + FROM #adjustments adj + INNER JOIN #groupingAdjustments grp ON adj.GroupingGUID = grp.GroupingGUID + LEFT JOIN #securedAdjustments secured ON adj.AdjustmentGUID = secured.AdjustmentGUID + WHERE adj.AdjustmentType IN (12, 13, 14) -- Roll Up Adjustments + AND secured.AdjustmentGUID IS NULL + + END + ELSE + BEGIN + + -- In case there security is not applied just insert all adjustments + INSERT INTO #securedAdjustments + SELECT AdjustmentGUID + FROM #adjustments + + END + + CREATE CLUSTERED INDEX PK_SecuredAdjustmnets ON #securedAdjustments (AdjustmentGUID) + + -- Select import adjustments that are allowed by security + -- with UnitTypeID + SELECT iadj.AdjustmentGuid, + iadj.UnitTypeID, + iadj.DepartmentID + INTO #importAdjustments + FROM fp.StaffingAdjustmentImport AS iadj WITH (NOLOCK) + JOIN #securedAdjustments AS sadj ON sadj.AdjustmentGUID = iadj.AdjustmentGUID + LEFT JOIN #departmentsSecurity AS ds ON ds.DepartmentID = iadj.DepartmentID + WHERE ds.DepartmentID IS NOT NULL OR @isDataSecured = 0 + GROUP BY iadj.AdjustmentGuid, + iadj.UnitTypeID, + iadj.DepartmentID + + -- Creating indexes for faster selection + CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentGUID, UnitTypeID) + + SELECT res.TotalRowsCount + ,res.AdjustmentGUID + ,res.BudgetConfigGUID + ,res.AdjustmentType + ,res.[Value] + ,res.AdjustmentFilterJSON + ,res.GroupingHierarchyJSON + ,res.AdjustedProperty + ,res.Comment + ,res.AuthorGUID + ,res.AuthorFullName + ,res.LastModifiedDateUtc + ,res.DateCreatedUtc + ,res.GroupingGUID + ,res.TimeClassID + ,res.BudgetPhaseID + ,res.ClassificationGroupID + ,res.ClassificationCategoryID + ,res.JobCode + ,res.JobCodeCount + ,res.DepartmentCode + ,res.DepartmentCount + ,res.UnitTypeID + ,res.ImportUnitTypeIDs + ,res.AddProviderFirstName + ,res.AddProviderLastName + ,res.AddProviderType + ,res.IsRecordDeleted + FROM ( + -- Selecting total rows count, for paging to work correctly + SELECT COUNT(res_inner.AdjustmentGUID) OVER () AS TotalRowsCount, + * + FROM ( + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber + ,slea.AdjustmentGUID + ,slea.BudgetConfigGUID + ,slea.AdjustmentType + ,slea.[Value] + ,slea.AdjustmentFilterJSON + ,slea.GroupingHierarchyJSON + ,slea.AdjustedProperty + ,ISNULL(ag.[Description], slea.Comment) AS Comment + ,slea.AuthorGUID + ,slea.AuthorFullName + ,slea.LastModifiedDateUtc + ,slea.DateCreatedUtc + ,slea.GroupingGUID + ,slea.TimeClassID + ,slea.BudgetPhaseID + ,slea.ClassificationGroupID + ,slea.ClassificationCategoryID + ,slea.UnitTypeID + ,NULL AS JobCode + ,NULL AS JobCodeCount + ,NULL AS DepartmentCode + ,NULL AS DepartmentCount + ,sai.ImportUnitTypeIDs + ,NULL AS AddProviderFirstName + ,NULL AS AddProviderLastName + ,NULL AS AddProviderType + ,slea.IsRecordDeleted + FROM fp.StaffingAdjustment AS slea WITH (NOLOCK) + JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID + LEFT JOIN ( + SELECT p.AdjustmentGUID, + ImportUnitTypeIDs = + TRIM(STUFF( + (SELECT N' ' + CAST(p2.UnitTypeID AS VARCHAR(5)) + FROM #importAdjustments AS p2 + LEFT JOIN #departmentsSecurity AS ds ON ds.DepartmentID = p2.DepartmentID + WHERE (ds.DepartmentID IS NOT NULL + OR @isDataSecured = 0) + AND p2.AdjustmentGUID = p.AdjustmentGUID + GROUP BY p2.AdjustmentGUID, + p2.UnitTypeID + FOR XML PATH(N'')) + , 1, 0, N'')) + FROM #importAdjustments AS p + GROUP BY p.AdjustmentGUID + ) AS sai ON sai.AdjustmentGUID = slea.AdjustmentGUID + LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID + LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acg.GroupID = acg.GroupID + AND slea.ClassificationCategoryID = acc.CategoryID + LEFT JOIN fp.AdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID + LEFT JOIN ( + SELECT nsa.GroupingGUID + FROM fp.StaffingAdjustment as nsa WITH (NOLOCK) + WHERE nsa.AdjustmentType IN (12, 13, 14) + AND nsa.BudgetConfigGUID = @budgetGUID + GROUP BY nsa.GroupingGUID + ) AS ra ON ra.GroupingGUID = slea.GroupingGUID + WHERE (slea.AdjustmentType <> 4 + OR sai.ImportUnitTypeIDs <> '') + AND slea.SubsectionID = 4 -- Provider + AND (ra.GroupingGUID IS NULL + OR slea.AdjustmentType IN (12, 13, 14)) + AND slea.AdjustmentType <> 6 AND slea.AdjustmentType <> 7 AND slea.AdjustmentType <> 15 + AND (@search IS NULL + OR ( + LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\' + OR LOWER(ISNULL(ag.[Description], slea.Comment)) LIKE @search ESCAPE '\' + OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR ISNULL(acc.[Name], acg.[Name]) LIKE @search ESCAPE '\' + OR fp.SearchHierarchyLevel(slea.AdjustmentFilterJSON, @search) = 1 + OR LOWER(fp.GetAdjustmentMeasure(slea.AdjustmentType, slea.UnitTypeID)) LIKE @search ESCAPE '\' + OR fp.SearchAdjustmentMeasureForImport(slea.AdjustmentType, sai.ImportUnitTypeIDs, @search) = 1 + ) + ) + AND (@filter IS NULL + OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, slea.BudgetPhaseID) IN ( + SELECT [value] + FROM STRING_SPLIT(@filter, ' ' ) + ) + ) + -- Add Provider adjustment + UNION ALL + + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber + ,slea.AdjustmentGUID + ,slea.BudgetConfigGUID + ,slea.AdjustmentType + ,slea.[Value] + ,slea.AdjustmentFilterJSON + ,slea.GroupingHierarchyJSON + ,slea.AdjustedProperty + ,aps.Comment + ,slea.AuthorGUID + ,slea.AuthorFullName + ,slea.LastModifiedDateUtc + ,slea.DateCreatedUtc + ,slea.GroupingGUID + ,slea.TimeClassID + ,2 AS BudgetPhaseID + ,aps.ClassificationGroupID + ,aps.ClassificationCategoryID + ,NULL AS UnitTypeID + ,NULL AS JobCode + ,NULL AS JobCodeCount + ,NULL AS DepartmentCode + ,NULL AS DepartmentCount + ,NULL AS ImportUnitTypeIDs + ,de.NameFirst AS AddProviderFirstName + ,de.NameLast AS AddProviderLastName + ,aps.EmployeeType AS AddProviderType + ,slea.IsRecordDeleted + FROM fp.StaffingAdjustment AS slea WITH (NOLOCK) + JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID + JOIN fp.StatisticAddProviderSummary AS aps ON aps.StaffingAdjustmentGUID = slea.AdjustmentGUID + JOIN fw.DimEmployee AS de ON de.EmployeeID = aps.EmployeeID + LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = aps.ClassificationGroupID + LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acc.GroupID = acg.GroupID AND aps.ClassificationCategoryID = acc.CategoryID + WHERE slea.AdjustmentType = 15 -- add provider adjustments + AND (@search IS NULL + OR ( + LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\' + OR LOWER(aps.Comment) LIKE @search ESCAPE '\' + OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR acc.[Name] LIKE @search ESCAPE '\' + OR acg.[Name] LIKE @search ESCAPE '\' + OR de.NameFull LIKE @search ESCAPE '\' + ) + ) + AND (@filter IS NULL OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, 2) IN ( SELECT [value] FROM STRING_SPLIT(@filter, ' '))) + ) AS res_inner + WHERE res_inner.RowNumber = 1) AS res + ORDER BY res.DateCreatedUtc DESC + OFFSET @start ROWS + FETCH NEXT @pageSize ROWS ONLY + option (recompile) --!!! + ; + +END +GO + + +--------------------------------------------- + +-- fp.ResetFactStaffingTables +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-10-04 IP B-20922 Added using source dimensionality +** 2 2022-08-09 JB JAZZ-23177 Remove commented union for clean up purposes +*************************************************************/ +CREATE PROCEDURE [fp].[ResetFactStaffingTables] + @EntityGroupConfigID INT, + @UnitTypeIds dbo.SqlInt32ListTableType READONLY, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + SET NOCOUNT ON + + CREATE TABLE #FilteringTable ( + DepartmentID INT + ,INDEX ix_1 NONCLUSTERED (DepartmentID) + ) + + INSERT INTO #FilteringTable (DepartmentID) + SELECT DepartmentID + FROM @SourceDimensionality + + DECLARE @isFilterPresent INT = (SELECT COUNT(*) FROM #FilteringTable) + + IF (@isFilterPresent=0) BEGIN + UPDATE tbl + SET + tbl.AdjustedValue01 = fs.InitialBudget01, tbl.AdjustedValue02 = fs.InitialBudget02, tbl.AdjustedValue03 = fs.InitialBudget03, tbl.AdjustedValue04 = fs.InitialBudget04, tbl.AdjustedValue05 = fs.InitialBudget05, tbl.AdjustedValue06 = fs.InitialBudget06, tbl.AdjustedValue07 = fs.InitialBudget07, tbl.AdjustedValue08 = fs.InitialBudget08, tbl.AdjustedValue09 = fs.InitialBudget09, tbl.AdjustedValue10 = fs.InitialBudget10, tbl.AdjustedValue11 = fs.InitialBudget11, tbl.AdjustedValue12 = fs.InitialBudget12, + tbl.FlexedValue01 = fs.InitialBudget01, tbl.FlexedValue02 = fs.InitialBudget02, tbl.FlexedValue03 = fs.InitialBudget03, tbl.FlexedValue04 = fs.InitialBudget04, tbl.FlexedValue05 = fs.InitialBudget05, tbl.FlexedValue06 = fs.InitialBudget06, tbl.FlexedValue07 = fs.InitialBudget07, tbl.FlexedValue08 = fs.InitialBudget08, tbl.FlexedValue09 = fs.InitialBudget09, tbl.FlexedValue10 = fs.InitialBudget10, tbl.FlexedValue11 = fs.InitialBudget11, tbl.FlexedValue12 = fs.InitialBudget12, + tbl.PercentAdjustmentFactor01 = 1.000, tbl.PercentAdjustmentFactor02 = 1.000, tbl.PercentAdjustmentFactor03 = 1.000, tbl.PercentAdjustmentFactor04 = 1.000, tbl.PercentAdjustmentFactor05 = 1.000, tbl.PercentAdjustmentFactor06 = 1.000, tbl.PercentAdjustmentFactor07 = 1.000, tbl.PercentAdjustmentFactor08 = 1.000, tbl.PercentAdjustmentFactor09 = 1.000, tbl.PercentAdjustmentFactor10 = 1.000, tbl.PercentAdjustmentFactor11 = 1.000, tbl.PercentAdjustmentFactor12 = 1.000, + tbl.LockType = 0, + tbl.LockFlag = 0 + FROM [fp].[FactStaffingBudget] tbl + INNER JOIN [fp].[FactStaffing] fs ON tbl.StaffingID = fs.StaffingID + INNER JOIN @UnitTypeIds ut ON ut.value = fs.UnitTypeID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + + + -- reset the data in the projection table + UPDATE tbl + SET + tbl.AdjustedValue01 = fs.InitialProjection01, tbl.AdjustedValue02 = fs.InitialProjection02, tbl.AdjustedValue03 = fs.InitialProjection03, tbl.AdjustedValue04 = fs.InitialProjection04, tbl.AdjustedValue05 = fs.InitialProjection05, tbl.AdjustedValue06 = fs.InitialProjection06, tbl.AdjustedValue07 = fs.InitialProjection07, tbl.AdjustedValue08 = fs.InitialProjection08, tbl.AdjustedValue09 = fs.InitialProjection09, tbl.AdjustedValue10 = fs.InitialProjection10, tbl.AdjustedValue11 = fs.InitialProjection11, tbl.AdjustedValue12 = fs.InitialProjection12, + tbl.FlexedValue01 = fs.InitialProjection01, tbl.FlexedValue02 = fs.InitialProjection02, tbl.FlexedValue03 = fs.InitialProjection03, tbl.FlexedValue04 = fs.InitialProjection04, tbl.FlexedValue05 = fs.InitialProjection05, tbl.FlexedValue06 = fs.InitialProjection06, tbl.FlexedValue07 = fs.InitialProjection07, tbl.FlexedValue08 = fs.InitialProjection08, tbl.FlexedValue09 = fs.InitialProjection09, tbl.FlexedValue10 = fs.InitialProjection10, tbl.FlexedValue11 = fs.InitialProjection11, tbl.FlexedValue12 = fs.InitialProjection12, + tbl.PercentAdjustmentFactor01 = 1.000, tbl.PercentAdjustmentFactor02 = 1.000, tbl.PercentAdjustmentFactor03 = 1.000, tbl.PercentAdjustmentFactor04 = 1.000, tbl.PercentAdjustmentFactor05 = 1.000, tbl.PercentAdjustmentFactor06 = 1.000, tbl.PercentAdjustmentFactor07 = 1.000, tbl.PercentAdjustmentFactor08 = 1.000, tbl.PercentAdjustmentFactor09 = 1.000, tbl.PercentAdjustmentFactor10 = 1.000, tbl.PercentAdjustmentFactor11 = 1.000, tbl.PercentAdjustmentFactor12 = 1.000, + tbl.LockType = 0, + tbl.LockFlag = 0 + FROM [fp].[FactStaffingProjection] tbl + INNER JOIN [fp].[FactStaffing] fs ON tbl.StaffingID = fs.StaffingID + INNER JOIN @UnitTypeIds ut ON ut.value = fs.UnitTypeID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + + END ELSE BEGIN + -- reset the data in the budget table + UPDATE tbl + SET + tbl.AdjustedValue01 = fs.InitialBudget01, tbl.AdjustedValue02 = fs.InitialBudget02, tbl.AdjustedValue03 = fs.InitialBudget03, tbl.AdjustedValue04 = fs.InitialBudget04, tbl.AdjustedValue05 = fs.InitialBudget05, tbl.AdjustedValue06 = fs.InitialBudget06, tbl.AdjustedValue07 = fs.InitialBudget07, tbl.AdjustedValue08 = fs.InitialBudget08, tbl.AdjustedValue09 = fs.InitialBudget09, tbl.AdjustedValue10 = fs.InitialBudget10, tbl.AdjustedValue11 = fs.InitialBudget11, tbl.AdjustedValue12 = fs.InitialBudget12, + tbl.FlexedValue01 = fs.InitialBudget01, tbl.FlexedValue02 = fs.InitialBudget02, tbl.FlexedValue03 = fs.InitialBudget03, tbl.FlexedValue04 = fs.InitialBudget04, tbl.FlexedValue05 = fs.InitialBudget05, tbl.FlexedValue06 = fs.InitialBudget06, tbl.FlexedValue07 = fs.InitialBudget07, tbl.FlexedValue08 = fs.InitialBudget08, tbl.FlexedValue09 = fs.InitialBudget09, tbl.FlexedValue10 = fs.InitialBudget10, tbl.FlexedValue11 = fs.InitialBudget11, tbl.FlexedValue12 = fs.InitialBudget12, + tbl.PercentAdjustmentFactor01 = 1.000, tbl.PercentAdjustmentFactor02 = 1.000, tbl.PercentAdjustmentFactor03 = 1.000, tbl.PercentAdjustmentFactor04 = 1.000, tbl.PercentAdjustmentFactor05 = 1.000, tbl.PercentAdjustmentFactor06 = 1.000, tbl.PercentAdjustmentFactor07 = 1.000, tbl.PercentAdjustmentFactor08 = 1.000, tbl.PercentAdjustmentFactor09 = 1.000, tbl.PercentAdjustmentFactor10 = 1.000, tbl.PercentAdjustmentFactor11 = 1.000, tbl.PercentAdjustmentFactor12 = 1.000, + tbl.LockType = 0, + tbl.LockFlag = 0 + FROM [fp].[FactStaffingBudget] tbl + INNER JOIN [fp].[FactStaffing] fs ON tbl.StaffingID = fs.StaffingID + INNER JOIN #FilteringTable ft ON ft.DepartmentID = fs.DepartmentID + INNER JOIN @UnitTypeIds ut ON ut.value = fs.UnitTypeID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + + + -- reset the data in the projection table + UPDATE tbl + SET + tbl.AdjustedValue01 = fs.InitialProjection01, tbl.AdjustedValue02 = fs.InitialProjection02, tbl.AdjustedValue03 = fs.InitialProjection03, tbl.AdjustedValue04 = fs.InitialProjection04, tbl.AdjustedValue05 = fs.InitialProjection05, tbl.AdjustedValue06 = fs.InitialProjection06, tbl.AdjustedValue07 = fs.InitialProjection07, tbl.AdjustedValue08 = fs.InitialProjection08, tbl.AdjustedValue09 = fs.InitialProjection09, tbl.AdjustedValue10 = fs.InitialProjection10, tbl.AdjustedValue11 = fs.InitialProjection11, tbl.AdjustedValue12 = fs.InitialProjection12, + tbl.FlexedValue01 = fs.InitialProjection01, tbl.FlexedValue02 = fs.InitialProjection02, tbl.FlexedValue03 = fs.InitialProjection03, tbl.FlexedValue04 = fs.InitialProjection04, tbl.FlexedValue05 = fs.InitialProjection05, tbl.FlexedValue06 = fs.InitialProjection06, tbl.FlexedValue07 = fs.InitialProjection07, tbl.FlexedValue08 = fs.InitialProjection08, tbl.FlexedValue09 = fs.InitialProjection09, tbl.FlexedValue10 = fs.InitialProjection10, tbl.FlexedValue11 = fs.InitialProjection11, tbl.FlexedValue12 = fs.InitialProjection12, + tbl.PercentAdjustmentFactor01 = 1.000, tbl.PercentAdjustmentFactor02 = 1.000, tbl.PercentAdjustmentFactor03 = 1.000, tbl.PercentAdjustmentFactor04 = 1.000, tbl.PercentAdjustmentFactor05 = 1.000, tbl.PercentAdjustmentFactor06 = 1.000, tbl.PercentAdjustmentFactor07 = 1.000, tbl.PercentAdjustmentFactor08 = 1.000, tbl.PercentAdjustmentFactor09 = 1.000, tbl.PercentAdjustmentFactor10 = 1.000, tbl.PercentAdjustmentFactor11 = 1.000, tbl.PercentAdjustmentFactor12 = 1.000, + tbl.LockType = 0, + tbl.LockFlag = 0 + FROM [fp].[FactStaffingProjection] tbl + INNER JOIN [fp].[FactStaffing] fs ON tbl.StaffingID = fs.StaffingID + INNER JOIN #FilteringTable ft ON ft.DepartmentID = fs.DepartmentID + INNER JOIN @UnitTypeIds ut ON ut.value = fs.UnitTypeID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + END +END +GO + + +--------------------------------------------- + +-- fp.ResetFactStatisticsTables +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-10-04 IP B-20922 Added using source dimensionality +** 2 2020-14-12 MY JAZZ-11324 Added rate reset +** 3 2022-08-09 JB JAZZ-23177 Commented out union in #FilteringTable +** 4 2022-10-04 JB JAZZ-43489 Remove FlexedValue references +*************************************************************/ + CREATE PROCEDURE [fp].[ResetFactStatisticsTables] + @EntityGroupConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + AS + BEGIN + CREATE TABLE #FilteringTable ( + DepartmentID INT + ,INDEX ix_1 NONCLUSTERED (DepartmentID) + ) + + INSERT INTO #FilteringTable (DepartmentID) + SELECT DepartmentID + FROM @SourceDimensionality + +/* -- This was commented out in ResetFactStaffingTables so we commented it out here as well. -JB/BK 08/09/2022 @mtw + UNION + + SELECT d.DepartmentID + FROM fw.DimDepartment d + INNER JOIN @SourceDimensionality sd + ON sd.EntityID = d.EntityID + WHERE sd.DepartmentID IS NULL -- filter rows, where particular DepartmentID is set as specification of EntityID + + */ + + DECLARE @isFilterPresent int = (SELECT COUNT(*) FROM #FilteringTable) + + IF (@isFilterPresent=0) + INSERT INTO #FilteringTable (DepartmentID) VALUES (NULL) + + + UPDATE tbl + SET + tbl.AdjustedValue01 = fgl.InitialBudget01, tbl.AdjustedValue02 = fgl.InitialBudget02, tbl.AdjustedValue03 = fgl.InitialBudget03, tbl.AdjustedValue04 = fgl.InitialBudget04, tbl.AdjustedValue05 = fgl.InitialBudget05, tbl.AdjustedValue06 = fgl.InitialBudget06, tbl.AdjustedValue07 = fgl.InitialBudget07, tbl.AdjustedValue08 = fgl.InitialBudget08, tbl.AdjustedValue09 = fgl.InitialBudget09, tbl.AdjustedValue10 = fgl.InitialBudget10, tbl.AdjustedValue11 = fgl.InitialBudget11, tbl.AdjustedValue12 = fgl.InitialBudget12, + tbl.RateAdjustedValue01 = fgl.InitialBudgetRate01, tbl.RateAdjustedValue02 = fgl.InitialBudgetRate02, tbl.RateAdjustedValue03 = fgl.InitialBudgetRate03, tbl.RateAdjustedValue04 = fgl.InitialBudgetRate04, tbl.RateAdjustedValue05 = fgl.InitialBudgetRate05, tbl.RateAdjustedValue06 = fgl.InitialBudgetRate06, tbl.RateAdjustedValue07 = fgl.InitialBudgetRate07, tbl.RateAdjustedValue08 = fgl.InitialBudgetRate08, tbl.RateAdjustedValue09 = fgl.InitialBudgetRate09, tbl.RateAdjustedValue10 = fgl.InitialBudgetRate10, tbl.RateAdjustedValue11 = fgl.InitialBudgetRate11, tbl.RateAdjustedValue12 = fgl.InitialBudgetRate12, + tbl.LockType = 0, + tbl.LockFlag = 0 + FROM [fp].[FactStatisticsBudget] tbl + INNER JOIN [fp].[FactStatistics] fgl ON tbl.StatisticsID = fgl.StatisticsID + INNER JOIN #FilteringTable ft on (ft.DepartmentID = fgl.DepartmentID or @isFilterPresent = 0) + WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID + + UPDATE tbl + SET + tbl.AdjustedValue01 = fgl.InitialProjection01, tbl.AdjustedValue02 = fgl.InitialProjection02, tbl.AdjustedValue03 = fgl.InitialProjection03, tbl.AdjustedValue04 = fgl.InitialProjection04, tbl.AdjustedValue05 = fgl.InitialProjection05, tbl.AdjustedValue06 = fgl.InitialProjection06, tbl.AdjustedValue07 = fgl.InitialProjection07, tbl.AdjustedValue08 = fgl.InitialProjection08, tbl.AdjustedValue09 = fgl.InitialProjection09, tbl.AdjustedValue10 = fgl.InitialProjection10, tbl.AdjustedValue11 = fgl.InitialProjection11, tbl.AdjustedValue12 = fgl.InitialProjection12, + tbl.RateAdjustedValue01 = fgl.InitialProjectionRate01, tbl.RateAdjustedValue02 = fgl.InitialProjectionRate02, tbl.RateAdjustedValue03 = fgl.InitialProjectionRate03, tbl.RateAdjustedValue04 = fgl.InitialProjectionRate04, tbl.RateAdjustedValue05 = fgl.InitialProjectionRate05, tbl.RateAdjustedValue06 = fgl.InitialProjectionRate06, tbl.RateAdjustedValue07 = fgl.InitialProjectionRate07, tbl.RateAdjustedValue08 = fgl.InitialProjectionRate08, tbl.RateAdjustedValue09 = fgl.InitialProjectionRate09, tbl.RateAdjustedValue10 = fgl.InitialProjectionRate10, tbl.RateAdjustedValue11 = fgl.InitialProjectionRate11, tbl.RateAdjustedValue12 = fgl.InitialProjectionRate12, + tbl.LockType = 0, + tbl.LockFlag = 0 + FROM [fp].[FactStatisticsProjection] tbl + INNER JOIN [fp].[FactStatistics] fgl ON tbl.StatisticsID = fgl.StatisticsID + INNER JOIN #FilteringTable ft on (ft.DepartmentID = fgl.DepartmentID or @isFilterPresent = 0) + WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID + + END +GO + + +--------------------------------------------- + +-- fp.ResetServiceLineTables +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-09-19 BK JAZZ-42503 Add ProviderID to targeting +** 2 2023-02-24 BW JAZZ-48306 Updated for new data model, use [fp].[ServiceLineEncounter] +** 3 2023-05-24 MY JAZZ-55524 Included Target in the reset +*************************************************************/ +CREATE PROCEDURE [fp].[ResetServiceLineTables] + @EntityGroupConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + AS + BEGIN + + IF OBJECT_ID('tempdb..#FilteringTable') IS NOT NULL DROP TABLE #FilteringTable; + IF OBJECT_ID('tempdb..#filterTable') IS NOT NULL DROP TABLE #filterTable; + + CREATE TABLE #FilteringTable ( + DepartmentID INT + ,INDEX ix_1 NONCLUSTERED (DepartmentID) + ) + + INSERT INTO #FilteringTable (DepartmentID) + SELECT DepartmentID + FROM @SourceDimensionality sd WHERE sd.DepartmentID IS NOT NULL + + UNION + + SELECT d.DepartmentID + FROM fw.DimDepartment d + INNER JOIN @SourceDimensionality sd + ON sd.EntityID = d.EntityID + WHERE sd.DepartmentID IS NULL -- filter rows, where particular DepartmentID is set as specification of EntityID + + -- table to use to populate Entity and ServiceLines that correspond to the departments passed in + -- DepartmentID on fp.FactServiceLineEncounter DOES NOT correspond to DepartmentID on the other fp tables, it is for security purposes only + CREATE TABLE #filterTable (EntityID INT, ServiceLineID INT, ProviderID INT) + + DECLARE @BudgetConfigID SMALLINT + SELECT @BudgetConfigID = BudgetConfigID FROM fp.BudgetConfig a INNER JOIN fp.EntityGroupConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE b.EntityGroupConfigID = @EntityGroupConfigID + + -- use mapping table to populate filter table + INSERT INTO #filterTable (EntityID, ServiceLineID, ProviderID) + SELECT DISTINCT EntityID, ServiceLineID, map.ProviderID + FROM fp.ServiceLineEncounterChargeVolumeMapping map + INNER JOIN #FilteringTable ft on map.DepartmentID = ft.DepartmentID + WHERE map.BudgetConfigID = @BudgetConfigID + + IF EXISTS(SELECT 1 FROM #filterTable WHERE EntityID IS NULL) OR NOT EXISTS (SELECT 1 FROM #filterTable) + BEGIN + INSERT INTO #filterTable (EntityID, ServiceLineID, ProviderID) + SELECT DISTINCT EntityID, ServiceLineID, ProviderID + FROM fp.ServiceLineEncounter + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + UPDATE sle + SET + sle.TargetAdjusted01 = sle.InitialBudget01, + sle.TargetAdjusted02 = sle.InitialBudget02, + sle.TargetAdjusted03 = sle.InitialBudget03, + sle.TargetAdjusted04 = sle.InitialBudget04, + sle.TargetAdjusted05 = sle.InitialBudget05, + sle.TargetAdjusted06 = sle.InitialBudget06, + sle.TargetAdjusted07 = sle.InitialBudget07, + sle.TargetAdjusted08 = sle.InitialBudget08, + sle.TargetAdjusted09 = sle.InitialBudget09, + sle.TargetAdjusted10 = sle.InitialBudget10, + sle.TargetAdjusted11 = sle.InitialBudget11, + sle.TargetAdjusted12 = sle.InitialBudget12, + sle.TargetLockType = 0, + sle.TargetLockFlag = 0, + sle.BudgetAdjusted01 = sle.InitialBudget01, + sle.BudgetAdjusted02 = sle.InitialBudget02, + sle.BudgetAdjusted03 = sle.InitialBudget03, + sle.BudgetAdjusted04 = sle.InitialBudget04, + sle.BudgetAdjusted05 = sle.InitialBudget05, + sle.BudgetAdjusted06 = sle.InitialBudget06, + sle.BudgetAdjusted07 = sle.InitialBudget07, + sle.BudgetAdjusted08 = sle.InitialBudget08, + sle.BudgetAdjusted09 = sle.InitialBudget09, + sle.BudgetAdjusted10 = sle.InitialBudget10, + sle.BudgetAdjusted11 = sle.InitialBudget11, + sle.BudgetAdjusted12 = sle.InitialBudget12, + sle.BudgetLockType = 0, + sle.BudgetLockFlag = 0, + sle.ProjectionAdjusted01 = sle.InitialProjection01, + sle.ProjectionAdjusted02 = sle.InitialProjection02, + sle.ProjectionAdjusted03 = sle.InitialProjection03, + sle.ProjectionAdjusted04 = sle.InitialProjection04, + sle.ProjectionAdjusted05 = sle.InitialProjection05, + sle.ProjectionAdjusted06 = sle.InitialProjection06, + sle.ProjectionAdjusted07 = sle.InitialProjection07, + sle.ProjectionAdjusted08 = sle.InitialProjection08, + sle.ProjectionAdjusted09 = sle.InitialProjection09, + sle.ProjectionAdjusted10 = sle.InitialProjection10, + sle.ProjectionAdjusted11 = sle.InitialProjection11, + sle.ProjectionAdjusted12 = sle.InitialProjection12, + sle.ProjectionLockType = 0, + sle.ProjectionLockFlag = 0 + FROM [fp].[ServiceLineEncounter] sle + INNER JOIN #filterTable ft on ft.EntityID = sle.EntityID AND ft.ServiceLineID = sle.ServiceLineID AND ft.ProviderID = sle.ProviderID + WHERE sle.EntityGroupConfigID = @EntityGroupConfigID + + END +GO + + +--------------------------------------------- + +-- fp.ServiceLineEncounterAdjustment_SEL_LIST +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2020-06-03 LR JAZZ-134 Now including deleted items to be displayed in the activity pane + ** 2 2020-07-01 OP JAZZ-635 Added AP Entity Config roles support + ** 3 2020-08-20 OP JAZZ-4123 Fixed import comment + ** 4 2022-09-02 AO JAZZ-42931 Fixed search by Adjustment Type + ** 5 2022-01-06 NT JAZZ-45457 Include new IsErrored field in order to display "DELETED - ADJUSTMENT FAILED" in the activity card + ** 6 2024-02-22 MY JAZZ-67143 Filters acting unexpectedly post-adjustment - Issue #2 + *************************************************************/ +CREATE PROCEDURE [fp].[ServiceLineEncounterAdjustment_SEL_LIST] + @budgetGUID UNIQUEIDENTIFIER, + @start INT, + @end INT, + @search VARCHAR(MAX), + @filter VARCHAR(MAX), + @userGUID UNIQUEIDENTIFIER, + @isDataSecured BIT, + @dateTimeFormat VARCHAR(30), + @userTimeZone VARCHAR(50) +AS + +BEGIN + + CREATE TABLE #departmentsSecurity ( + DepartmentID INT NULL, + EntityID INT NULL + ) + + CREATE TABLE #securedAdjustments ( + AdjustmentGUID UNIQUEIDENTIFIER + ) + + DECLARE @guidEmpty UNIQUEIDENTIFIER = [dbo].[ZeroGUID]() + DECLARE @pageSize INT = @end - @start; + + SET @search = LOWER(NULLIF('%' + @search+ '%', '%\%')) + SET @filter = LOWER(NULLIF(@filter, '')) + + SELECT AdjustmentGUID + ,GroupingHierarchyJSON + ,JSON_VALUE(AdjustmentFilterJSON, '$.Entity.ID') AS EntityID + ,JSON_VALUE(AdjustmentFilterJSON, '$.Department.ID') AS DepartmentID + ,AdjustmentType + ,GroupingGUID + INTO #adjustments + FROM fp.ServiceLineEncounterAdjustment AS slea WITH (NOLOCK) + WHERE slea.AdjustmentType IN (0, 1, 2, 3, 4, 10, 11, 12, 13, 14, 15) -- Supported Adjustment types for SLE Adjustments + AND slea.BudgetConfigGUID = @budgetGUID + + IF @isDataSecured = 1 + BEGIN + INSERT INTO #departmentsSecurity + EXEC fp.DepartmentsSecurity_SEL + @userGUID = @userGUID, + @pageName = 'Encounters' + + CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #departmentsSecurity (DepartmentID, EntityID) + + SELECT AdjustmentGUID + ,ahd.ID AS DepartmentID + INTO #adjustmentGroupingHierarchyDepartments + FROM ( + SELECT adj.AdjustmentGUID + ,adj.GroupingHierarchyJSON + FROM #adjustments AS adj + WHERE adj.EntityID IS NULL + AND adj.DepartmentID IS NULL) AS slea + OUTER APPLY fp.GetAdjustmentHierarchyIDs(slea.GroupingHierarchyJSON, 'Department') AS ahd + GROUP BY AdjustmentGUID + ,ahd.ID + + SELECT adj.AdjustmentGUID, + ahe.ID AS EntityID + INTO #adjustmentGroupingHierarchyEntities + FROM #adjustments AS adj + JOIN #adjustmentGroupingHierarchyDepartments AS adhd ON adhd.AdjustmentGUID = adj.AdjustmentGUID + AND adhd.DepartmentID IS NULL + OUTER APPLY fp.GetAdjustmentHierarchyIDs(adj.GroupingHierarchyJSON, 'Entity') AS ahe + GROUP BY adj.AdjustmentGUID + ,ahe.ID + + INSERT INTO #securedAdjustments + SELECT res.AdjustmentGUID + FROM ( + SELECT slea.AdjustmentGUID + FROM #adjustments AS slea + JOIN #departmentsSecurity AS ds ON ds.DepartmentID = slea.DepartmentID + GROUP BY slea.AdjustmentGUID + + UNION ALL + + SELECT slea.AdjustmentGUID + FROM #adjustments AS slea + JOIN #departmentsSecurity AS dse ON dse.EntityID = slea.EntityID + WHERE slea.DepartmentID IS NULL + GROUP BY slea.AdjustmentGUID + + UNION ALL + + SELECT aghd.AdjustmentGUID + FROM #adjustmentGroupingHierarchyDepartments AS aghd + JOIN #departmentsSecurity AS dshd ON dshd.DepartmentID = aghd.DepartmentID + WHERE dshd.DepartmentID IS NOT NULL + GROUP BY aghd.AdjustmentGUID + + UNION ALL + + SELECT aghe.AdjustmentGUID + FROM #adjustmentGroupingHierarchyEntities AS aghe + JOIN #departmentsSecurity AS dshd ON dshd.EntityID = aghe.EntityID + GROUP BY aghe.AdjustmentGUID + + UNION ALL + + SELECT adj.AdjustmentGUID + FROM #adjustments AS adj + JOIN #adjustmentGroupingHierarchyDepartments AS aghd ON aghd.AdjustmentGUID = adj.AdjustmentGUID + JOIN #adjustmentGroupingHierarchyEntities AS aghe ON aghe.AdjustmentGUID = adj.AdjustmentGUID + WHERE adj.DepartmentID IS NULL + AND adj.EntityID IS NULL + AND aghd.DepartmentID IS NULL + AND aghe.EntityID IS NULL + AND adj.AdjustmentType <> 15 -- Add provider adjustment, that has no grouping hierarchy, but has security + GROUP BY adj.AdjustmentGUID + + UNION ALL + + SELECT adj.AdjustmentGUID + FROM #adjustments AS adj + JOIN fp.ServiceLineEncounterAddProviderAdjustment AS sleapa ON adj.AdjustmentGUID = sleapa.AdjustmentGUID + JOIN #departmentsSecurity AS ds ON ds.DepartmentID = sleapa.DepartmentID + GROUP BY adj.AdjustmentGUID + ) AS res + + -- JAZZ-67143: Filters acting unexpectedly post-adjustment (Issue #2) + -- Essentially we had cases where a custom roll up would cause local admins to make an adjustment and the + -- adjustment would not show up in the pane. This is due to roll up adjustments as everything else seems to be fine. + -- Essentially what we are doing here is using the child adjustments to find if they fall in security. + -- In the event we have a child, populate the parent adjustment in the list. + -- Find all the GroupingGuid's for any child adjustments that fall into security. + + SELECT DISTINCT adj.GroupingGUID + INTO #groupingAdjustments + FROM #securedAdjustments secured + INNER JOIN #adjustments adj ON secured.AdjustmentGUID = adj.AdjustmentGUID + WHERE adj.GroupingGUID != '00000000-0000-0000-0000-000000000000' -- Only care about roll up adjustments. + + -- Once we have the GroupingGUIDs based on the security, we can insert the parent adjustment. + INSERT INTO #securedAdjustments + SELECT adj.AdjustmentGUID + FROM #adjustments adj + INNER JOIN #groupingAdjustments grp ON adj.GroupingGUID = grp.GroupingGUID + LEFT JOIN #securedAdjustments secured ON adj.AdjustmentGUID = secured.AdjustmentGUID + WHERE adj.AdjustmentType IN (12, 13, 14) -- Roll Up Adjustments + AND secured.AdjustmentGUID IS NULL + + END + ELSE + BEGIN + + INSERT INTO #securedAdjustments + SELECT AdjustmentGUID + FROM #adjustments + + END + + CREATE CLUSTERED INDEX PK_SecuredAdjustmnets ON #securedAdjustments (AdjustmentGUID) + + SELECT iadj.AdjustmentGuid, + iadj.EntityID + INTO #importAdjustments + FROM fp.ServiceLineEncounterAdjustmentImport AS iadj + JOIN #securedAdjustments AS sadj ON sadj.AdjustmentGUID = iadj.AdjustmentGUID + GROUP BY iadj.AdjustmentGuid, + iadj.EntityID + + CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentGUID, EntityID) + + SELECT res.TotalRowsCount + ,res.AdjustmentGUID + ,res.BudgetConfigGUID + ,res.AdjustmentType + ,res.[Value] + ,res.AdjustmentFilterJSON + ,res.GroupingHierarchyJSON + ,res.AdjustedProperty + ,res.Comment + ,res.AuthorGUID + ,res.AuthorFullName + ,res.LastModifiedDateUtc + ,res.DateCreatedUtc + ,res.GroupingGUID + ,res.TimeClassID + ,res.BudgetPhaseID + ,res.ClassificationGroupID + ,res.ClassificationCategoryID + ,res.UnitTypeID + ,res.ImportUnitTypeIDs + ,res.AddProviderFirstName + ,res.AddProviderLastName + ,res.AddProviderType + ,res.IsRecordDeleted + ,res.IsErrored + FROM ( + SELECT COUNT(res_inner.AdjustmentGUID) OVER () AS TotalRowsCount, + * + FROM ( + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber + ,slea.AdjustmentGUID + ,slea.BudgetConfigGUID + ,slea.AdjustmentType + ,slea.[Value] + ,slea.AdjustmentFilterJSON + ,slea.GroupingHierarchyJSON + ,slea.AdjustedProperty + ,ISNULL(ag.Description, slea.Comment) AS Comment + ,slea.AuthorGUID + ,slea.AuthorFullName + ,slea.LastModifiedDateUtc + ,slea.DateCreatedUtc + ,slea.GroupingGUID + ,slea.TimeClassID + ,slea.BudgetPhaseID + ,slea.ClassificationGroupID + ,slea.ClassificationCategoryID + ,CAST(140 AS TINYINT) AS UnitTypeID + ,sai.ImportUnitTypeIDs + ,NULL AS AddProviderFirstName + ,NULL AS AddProviderLastName + ,NULL AS AddProviderType + ,slea.IsRecordDeleted + ,slea.IsErrored + FROM fp.ServiceLineEncounterAdjustment AS slea WITH (NOLOCK) + JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID + LEFT JOIN ( + SELECT p.AdjustmentGUID, + ImportUnitTypeIDs = '140' + FROM #importAdjustments AS p + LEFT JOIN #departmentsSecurity AS ds ON ds.EntityID = p.EntityID + GROUP BY p.AdjustmentGUID + ) AS sai ON sai.AdjustmentGUID = slea.AdjustmentGUID + LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID + LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acg.GroupID = acg.GroupID + AND slea.ClassificationCategoryID = acc.CategoryID + LEFT JOIN fp.AdjustmentGrouping AS ag ON ag.GroupingGUID = slea.GroupingGUID + LEFT JOIN ( + SELECT nsa.GroupingGUID + FROM fp.ServiceLineEncounterAdjustment as nsa WITH (NOLOCK) + WHERE nsa.AdjustmentType IN (12, 13, 14) -- Currently not supported types + AND nsa.BudgetConfigGUID = @budgetGUID + GROUP BY nsa.GroupingGUID + ) AS ra ON ra.GroupingGUID = slea.GroupingGUID + WHERE (slea.AdjustmentType <> 4 + OR sai.ImportUnitTypeIDs <> '') -- Check department security for import adjustment + AND (ra.GroupingGUID IS NULL + OR slea.AdjustmentType IN (12, 13, 14)) + AND slea.AdjustmentType <> 15 -- add provider adjustments + AND (@search IS NULL + OR ( + LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\' + OR LOWER(ISNULL(ag.Description, slea.Comment)) LIKE @search ESCAPE '\' + OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR acc.[Name] LIKE @search ESCAPE '\' + OR acg.[Name] LIKE @search ESCAPE '\' + OR ('encounters' LIKE @search ESCAPE '\') -- because no other Measures are supported for ServiceLineEncounterAdjustment + OR fp.SearchHierarchyLevel(slea.AdjustmentFilterJSON, @search) = 1 + ) + ) + AND (@filter IS NULL + OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, slea.BudgetPhaseID) IN ( + SELECT [value] + FROM STRING_SPLIT(@filter, ' ' ) + ) + ) + + -- Add Provider adjustments + UNION ALL + + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUTC DESC) AS RowNumber + ,slea.AdjustmentGUID + ,slea.BudgetConfigGUID + ,slea.AdjustmentType + ,slea.[Value] + ,slea.AdjustmentFilterJSON + ,slea.GroupingHierarchyJSON + ,slea.AdjustedProperty + ,aps.Comment + ,slea.AuthorGUID + ,slea.AuthorFullName + ,slea.LastModifiedDateUtc + ,slea.DateCreatedUTC + ,slea.GroupingGUID + ,slea.TimeClassID + ,slea.BudgetPhaseID + ,aps.ClassificationGroupID + ,aps.ClassificationCategoryID + ,NULL AS UnitTypeID + ,NULL AS ImportUnitTypeIDs + ,de.NameFirst AS AddProviderFirstName + ,de.NameLast AS AddProviderLastName + ,aps.EmployeeType AS AddProviderType + ,slea.IsRecordDeleted + ,slea.IsErrored + FROM fp.ServiceLineEncounterAdjustment AS slea WITH (NOLOCK) + JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID + JOIN fp.AddProviderSummary AS aps ON aps.SLEncounterAdjustmentGUID = slea.AdjustmentGUID + JOIN fw.DimEmployee AS de ON de.EmployeeID = aps.EmployeeID + LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = aps.ClassificationGroupID + LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acc.GroupID = acg.GroupID + AND aps.ClassificationCategoryID = acc.CategoryID + WHERE slea.AdjustmentType = 15 -- add provider adjustments + AND (@search IS NULL + OR ( + LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\' + OR LOWER(aps.Comment) LIKE @search ESCAPE '\' + OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR acc.[Name] LIKE @search ESCAPE '\' + OR acg.[Name] LIKE @search ESCAPE '\' + OR de.NameFull LIKE @search ESCAPE '\' + ) + ) + AND (@filter IS NULL + OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, slea.BudgetPhaseID) IN ( + SELECT [value] + FROM STRING_SPLIT(@filter, ' ' ) + ) + ) + ) AS res_inner + WHERE res_inner.RowNumber = 1 ) AS res + ORDER BY res.DateCreatedUtc DESC + OFFSET @start ROWS + FETCH NEXT @pageSize ROWS ONLY; +END +GO + + +--------------------------------------------- + +-- fp.StaffingAdjustment_SEL_LIST +CREATE PROCEDURE [fp].[StaffingAdjustment_SEL_LIST] + @budgetGUID UNIQUEIDENTIFIER, + @start INT, + @end INT, + @search VARCHAR(MAX), + @filter VARCHAR(MAX), + @userGUID UNIQUEIDENTIFIER, + @isDataSecured BIT, + @dateTimeFormat VARCHAR(30), + @userTimeZone VARCHAR(50) +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2020-06-03 LR JAZZ-134 Now including deleted items to be displayed in the activity pane + ** 2 2020-06-22 OP JAZZ-380 Added mix adjustment type + ** 3 2020-07-01 OP JAZZ-635 Added AP Entity Config roles support + ** 4 2020-08-20 OP JAZZ-4123 Fixed import comment + ** 5 2020-11-03 OP JAZZ-7301 Fixed FTE block performance + ** 6 2021-01-12 OP JAZZ-5417 Removed JobCodeName from query - it wasn't used anywhere in app + ** 7 2021-03-03 MD JAZZ-15738 Joined onto fp.StaffingManagerAdjustmentData to pull adjustments by time class + ** 8 2021-03-18 OP JAZZ-16325 Filtered adjustments by Staff sub-section + ** 9 2022-02-02 NT JAZZ-31672 Add filter & search logic when getting Employee Adjustments + ** 10 2022-06-30 AO JAZZ-37651 Hide restricted Manager Adjustment cards for local user + ** 11 2023-01-06 NT JAZZ-45457 Include new IsErrored field in order to display "DELETED - ADJUSTMENT FAILED" in the activity card + ** 12 2023-01-06 NT JAZZ-45457 Fix the sequence the new IsErrored field in the last unionized SQL as it is bombing #ntw + ** 13 2023-07-03 DM JAZZ-54979 Display new My Budgets ManagerSet adjustments + ** 14 2023-08-31 DM JAZZ-58746 Staffing Import adjsutment are handled to show fte unit type when variable is edited + ** 15 2024-02-22 MY JAZZ-67143 Filters acting unexpectedly post-adjustment - Issue #2 + *************************************************************/ +BEGIN + + -- Contains all DepartmnetID with correspond EntityID that are allowed for current user + CREATE TABLE #departmentsSecurity ( + DepartmentID INT NULL, + EntityID INT NULL + ) + + -- Adjustments that passes security check + CREATE TABLE #securedAdjustments ( + AdjustmentGUID UNIQUEIDENTIFIER + ) + + DECLARE @guidEmpty UNIQUEIDENTIFIER = [dbo].[ZeroGUID]() + DECLARE @pageSize INT = @end - @start; + + SET @search = LOWER(NULLIF('%' + @search+ '%', '%\%')) + SET @filter = LOWER(NULLIF(@filter, '')) + + -- Select all possible to display adjustments + SELECT AdjustmentGUID + ,GroupingHierarchyJSON + ,JSON_VALUE(AdjustmentFilterJSON, '$.Entity.ID') AS EntityID + ,JSON_VALUE(AdjustmentFilterJSON, '$.Department.ID') AS DepartmentID + ,AdjustmentType + ,GroupingGUID + INTO #adjustments + FROM [fp].[StaffingAdjustment] AS slea WITH (NOLOCK) + WHERE slea.AdjustmentType IN (0, 2, 1, 4, 5, 6, 7, 8, 3, 10, 11, 12, 13, 14, 17, 20) -- Supported Adjustment types for Staffing Adjustments + AND slea.BudgetConfigGUID = @budgetGUID + + IF @isDataSecured = 1 + BEGIN + -- Get all departments that are allowed for current user + INSERT INTO #departmentsSecurity + EXEC fp.DepartmentsSecurity_SEL + @userGUID = @userGUID, + @pageName = 'Staffing' + + -- Creating index for faster selects + CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #departmentsSecurity (DepartmentID, EntityID) + + -- Select adjustments that have no Department/Entity on filters, but have DepartmentID + -- on grouping hierarchy level + SELECT AdjustmentGUID + ,ahd.ID AS DepartmentID + INTO #adjustmentGroupingHierarchyDepartments + FROM ( + SELECT adj.AdjustmentGUID + ,adj.GroupingHierarchyJSON + FROM #adjustments AS adj + -- Ignore departments that have DepartmentID and EntityID + WHERE adj.EntityID IS NULL + AND adj.DepartmentID IS NULL) AS slea + OUTER APPLY fp.GetAdjustmentHierarchyIDs(slea.GroupingHierarchyJSON, 'Department') AS ahd + GROUP BY AdjustmentGUID + ,ahd.ID + + -- Select adjustments that don't have DepartmentID on grouping hierarchy level + -- but have EntityID on grouping hierarchy level + SELECT adj.AdjustmentGUID, + ahe.ID AS EntityID + INTO #adjustmentGroupingHierarchyEntities + FROM #adjustments AS adj + JOIN #adjustmentGroupingHierarchyDepartments AS adhd ON adhd.AdjustmentGUID = adj.AdjustmentGUID + AND adhd.DepartmentID IS NULL + OUTER APPLY fp.GetAdjustmentHierarchyIDs(adj.GroupingHierarchyJSON, 'Entity') AS ahe + GROUP BY adj.AdjustmentGUID + ,ahe.ID + + INSERT INTO #securedAdjustments + SELECT res.AdjustmentGUID + FROM ( + -- Adjustmnets that passes Department security by DepartmentID + SELECT slea.AdjustmentGUID + FROM #adjustments AS slea + JOIN #departmentsSecurity AS ds ON ds.DepartmentID = slea.DepartmentID + GROUP BY slea.AdjustmentGUID + + UNION ALL + + -- Adjustmnets that passes Department security by EntityID + SELECT slea.AdjustmentGUID + FROM #adjustments AS slea + JOIN #departmentsSecurity AS dse ON dse.EntityID = slea.EntityID + WHERE slea.DepartmentID IS NULL + GROUP BY slea.AdjustmentGUID + + UNION ALL + + -- Insert adjustments that have allowed DepartmentID on their grouping hierarchy + SELECT aghd.AdjustmentGUID + FROM #adjustmentGroupingHierarchyDepartments AS aghd + JOIN #departmentsSecurity AS dshd ON dshd.DepartmentID = aghd.DepartmentID + WHERE dshd.DepartmentID IS NOT NULL + GROUP BY aghd.AdjustmentGUID + + UNION ALL + + -- Insert adjustments that have allowed EntityID on their grouping hierarchy + SELECT aghe.AdjustmentGUID + FROM #adjustmentGroupingHierarchyEntities AS aghe + JOIN #departmentsSecurity AS dshd ON dshd.EntityID = aghe.EntityID + GROUP BY aghe.AdjustmentGUID + + UNION ALL + + -- Insert all adjustments that have no connection to department or entity + SELECT adj.AdjustmentGUID + FROM #adjustments AS adj + JOIN #adjustmentGroupingHierarchyDepartments AS aghd ON aghd.AdjustmentGUID = adj.AdjustmentGUID + JOIN #adjustmentGroupingHierarchyEntities AS aghe ON aghe.AdjustmentGUID = adj.AdjustmentGUID + WHERE adj.DepartmentID IS NULL + AND adj.EntityID IS NULL + AND aghd.DepartmentID IS NULL + AND aghe.EntityID IS NULL + GROUP BY adj.AdjustmentGUID + ) AS res + + -- JAZZ-67143: Filters acting unexpectedly post-adjustment (Issue #2) + -- Essentially we had cases where a custom roll up would cause local admins to make an adjustment and the + -- adjustment would not show up in the pane. This is due to roll up adjustments as everything else seems to be fine. + -- Essentially what we are doing here is using the child adjustments to find if they fall in security. + -- In the event we have a child, populate the parent adjustment in the list. + -- Find all the GroupingGuid's for any child adjustments that fall into security. + + SELECT DISTINCT adj.GroupingGUID + INTO #groupingAdjustments + FROM #securedAdjustments secured + INNER JOIN #adjustments adj ON secured.AdjustmentGUID = adj.AdjustmentGUID + WHERE adj.GroupingGUID != '00000000-0000-0000-0000-000000000000' -- Only care about roll up adjustments. + + -- Once we have the GroupingGUIDs based on the security, we can insert the parent adjustment. + INSERT INTO #securedAdjustments + SELECT adj.AdjustmentGUID + FROM #adjustments adj + INNER JOIN #groupingAdjustments grp ON adj.GroupingGUID = grp.GroupingGUID + LEFT JOIN #securedAdjustments secured ON adj.AdjustmentGUID = secured.AdjustmentGUID + WHERE adj.AdjustmentType IN (12, 13, 14) -- Roll Up Adjustments + AND secured.AdjustmentGUID IS NULL + + END + ELSE + BEGIN + + -- In case there security is not applied just insert all adjustments + INSERT INTO #securedAdjustments + SELECT AdjustmentGUID + FROM #adjustments + + END + + CREATE CLUSTERED INDEX PK_SecuredAdjustmnets ON #securedAdjustments (AdjustmentGUID) + + -- Select import adjustments that are allowed by security + -- with UnitTypeID + SELECT iadj.AdjustmentGuid, + iadj.UnitTypeID, + iadj.OriginalUnitTypeID, + iadj.DepartmentID + INTO #importAdjustments + FROM fp.StaffingAdjustmentImport AS iadj + JOIN #securedAdjustments AS sadj ON sadj.AdjustmentGUID = iadj.AdjustmentGUID + GROUP BY iadj.AdjustmentGuid, + iadj.UnitTypeID, + iadj.OriginalUnitTypeID, + iadj.DepartmentID + + -- Creating indexes for faster selection + CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentGUID, UnitTypeID) + + SELECT res.TotalRowsCount + ,res.AdjustmentGUID + ,res.BudgetConfigGUID + ,res.AdjustmentType + ,res.[Value] + ,res.AdjustmentFilterJSON + ,res.GroupingHierarchyJSON + ,res.AdjustedProperty + ,res.Comment + ,res.AuthorGUID + ,res.AuthorFullName + ,res.LastModifiedDateUtc + ,res.DateCreatedUtc + ,res.GroupingGUID + ,res.TimeClassID + ,res.BudgetPhaseID + ,res.ClassificationGroupID + ,res.ClassificationCategoryID + ,res.JobCodeName + ,res.JobCodeCount + ,res.DepartmentName + ,res.DepartmentCount + ,res.UnitTypeID + ,res.ImportUnitTypeIDs + ,res.IsRecordDeleted + ,res.EmployeeName + ,res.IsErrored + FROM ( + -- Selecting total rows count, for paging to work correctly + SELECT COUNT(res_inner.AdjustmentGUID) OVER () AS TotalRowsCount, + * + FROM ( + -- ROW_NUMBER calcutes result query row numbers using the given condition + -- Here, it calculated row numbers for each unique AdjustmentGUID + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber + ,slea.AdjustmentGUID + ,slea.BudgetConfigGUID + ,slea.AdjustmentType + ,slea.[Value] + ,slea.AdjustmentFilterJSON + ,slea.GroupingHierarchyJSON + ,slea.AdjustedProperty + ,ISNULL(ag.[Description], slea.Comment) AS Comment + ,slea.AuthorGUID + ,slea.AuthorFullName + ,slea.LastModifiedDateUtc + ,slea.DateCreatedUtc + ,slea.GroupingGUID + ,slea.TimeClassID + ,slea.BudgetPhaseID + ,slea.ClassificationGroupID + ,slea.ClassificationCategoryID + ,slea.UnitTypeID + ,NULL AS JobCodeName + ,NULL AS JobCodeCount + ,NULL AS DepartmentName + ,NULL AS DepartmentCount + ,sai.ImportUnitTypeIDs + ,slea.IsRecordDeleted + ,NULL AS EmployeeName + ,slea.IsErrored + FROM fp.StaffingAdjustment AS slea WITH (NOLOCK) + JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID + -- Getting the row of the import UnitTypeIDs + -- Adjustment can have multiple UnitTypeIDs in scope of one import, + -- so not to multiply all the data just to get all the types, + -- they are concated into one string, with space separator. + -- Backend logic should parse this string + + LEFT JOIN ( + SELECT p.AdjustmentGUID, + ImportUnitTypeIDs = + -- According to this source: https://sqlperformance.com/2014/08/t-sql-queries/sql-server-grouped-concatenation, + -- STUFF FOR XML PATH is the best way to do this + TRIM(STUFF( + (SELECT N' ' + CAST(ISNULL(p2.OriginalUnitTypeID, p2.UnitTypeID) AS VARCHAR(5)) + FROM #importAdjustments AS p2 + LEFT JOIN #departmentsSecurity AS ds ON ds.DepartmentID = p2.DepartmentID + WHERE (ds.DepartmentID IS NOT NULL + OR @isDataSecured = 0) + AND p2.AdjustmentGUID = p.AdjustmentGUID + GROUP BY p2.AdjustmentGUID, + p2.UnitTypeID, + p2.OriginalUnitTypeID + FOR XML PATH(N'')) + , 1, 0, N'')) + FROM #importAdjustments AS p + GROUP BY p.AdjustmentGUID + ) AS sai ON sai.AdjustmentGUID = slea.AdjustmentGUID + LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID + LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acg.GroupID = acg.GroupID + AND slea.ClassificationCategoryID = acc.CategoryID + LEFT JOIN fp.AdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID + -- Selecting all the adjustments that should not be displayed + -- This adjustment are currently no supported, and this code will be removed in future + LEFT JOIN ( + SELECT nsa.GroupingGUID + FROM fp.StaffingAdjustment as nsa WITH (NOLOCK) + WHERE nsa.AdjustmentType IN (12, 13, 14) -- Currently not supported types + AND nsa.BudgetConfigGUID = @budgetGUID + GROUP BY nsa.GroupingGUID + ) AS ra ON ra.GroupingGUID = slea.GroupingGUID + WHERE (slea.AdjustmentType <> 4 + -- ImportUnitTypeIDs contains list of the all unit from adjustments for departments that are allowed + -- In case AdjustmentType is 4 (Import), and the ImportUnitTypeIDs contains no IDs, + -- Then all adjustments that was imported are for the departments that are not allowed + OR sai.ImportUnitTypeIDs <> '') -- Check department security for import adjustment + AND slea.SubsectionID = 3 -- Staffing-Stuff + -- Restrict currently not allowed departments + AND (ra.GroupingGUID IS NULL + OR slea.AdjustmentType IN (12, 13, 14)) + -- Ignore FTE adjustments in this select + AND slea.AdjustmentType <> 6 AND slea.AdjustmentType <> 7 AND slea.AdjustmentType <> 17 AND slea.AdjustmentType <> 20 + -- Apply search, if needed + AND (@search IS NULL + OR ( + LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\' + OR LOWER(ISNULL(ag.[Description], slea.Comment)) LIKE @search ESCAPE '\' + OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR ISNULL(acc.[Name], acg.[Name]) LIKE @search ESCAPE '\' + OR fp.SearchHierarchyLevel(slea.AdjustmentFilterJSON, @search) = 1 + OR LOWER(fp.GetAdjustmentMeasure(slea.AdjustmentType, slea.UnitTypeID)) LIKE @search ESCAPE '\' + OR fp.SearchAdjustmentMeasureForImport(slea.AdjustmentType, sai.ImportUnitTypeIDs, @search) = 1 + ) + ) + -- Apply filter, if needed + AND (@filter IS NULL + OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, slea.BudgetPhaseID) IN ( + SELECT [value] + FROM STRING_SPLIT(@filter, ' ' ) + ) + ) + + UNION ALL + + -- FTE Adjustments were moved into UNION block + SELECT ROW_NUMBER() OVER (PARTITION BY slea.GroupingGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber + ,slea.GroupingGUID AS AdjustmentGUID + ,@budgetGUID AS BudgetConfigGUID + ,slea.AdjustmentType + ,fte.FTEAmount AS [Value] + ,slea.AdjustmentFilterJSON + ,slea.GroupingHierarchyJSON + ,'' AS AdjustedProperty + ,CASE WHEN FTECount = 1 + THEN fte.FTEComment + ELSE '' + END AS Comment + ,slea.AuthorGUID + ,slea.AuthorFullName + ,slea.LastModifiedDateUtc + ,slea.DateCreatedUtc + ,slea.GroupingGUID + ,slea.TimeClassID + ,slea.BudgetPhaseID + ,slea.ClassificationGroupID + ,slea.ClassificationCategoryID + ,NULL AS UnitTypeID + ,fte.JobCodeName + ,fte.JobCodeCount + ,fte.DepartmentName + ,fte.DepartmentCount + ,NULL AS ImportUnitTypeIDs + ,slea.IsRecordDeleted + ,NULL AS EmployeeName + ,slea.IsErrored + FROM ( + SELECT + slea_inner.GroupingGUID AS AdjustmentGUID + ,slea_inner.AdjustmentType + ,MIN(slea_inner.AdjustmentFilterJSON) AS AdjustmentFilterJSON + ,slea_inner.GroupingHierarchyJSON + ,slea_inner.AuthorGUID + ,slea_inner.AuthorFullName + ,MAX(slea_inner.LastModifiedDateUtc) AS LastModifiedDateUtc + ,slea_inner.DateCreatedUtc + ,slea_inner.GroupingGUID + ,slea_inner.TimeClassID + ,slea_inner.BudgetPhaseID + ,slea_inner.ClassificationGroupID + ,slea_inner.ClassificationCategoryID + ,slea_inner.IsRecordDeleted + ,slea_inner.IsErrored + FROM fp.StaffingAdjustment AS slea_inner WITH (NOLOCK) + JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea_inner.AdjustmentGUID + WHERE AdjustmentType = 6 + AND slea_inner.SubsectionID = 3 -- Staffing-Stuff + GROUP BY + slea_inner.GroupingGUID + ,slea_inner.AdjustmentType + ,slea_inner.GroupingHierarchyJSON + ,slea_inner.AuthorGUID + ,slea_inner.AuthorFullName + ,slea_inner.DateCreatedUtc + ,slea_inner.GroupingGUID + ,slea_inner.TimeClassID + ,slea_inner.BudgetPhaseID + ,slea_inner.ClassificationGroupID + ,slea_inner.ClassificationCategoryID + ,slea_inner.IsRecordDeleted + ,slea_inner.IsErrored + ) AS slea + JOIN ( + SELECT + MIN(dept.[Name]) AS DepartmentName + ,MIN(jc.[Name]) AS JobCodeName + ,OBJ.GroupingGUID + ,COUNT(OBJ.GroupingGUID) AS JobCodeCount + ,COUNT(OBJ.GroupingGUID) AS DepartmentCount + ,COUNT(OBJ.GroupingGUID) AS FTECount + ,CAST(SUM(OBJ.FTEAmount) AS DECIMAL(19,4)) AS FTEAmount + ,MAX(OBJ.Comment) AS FTEComment + FROM fp.FTERequest AS OBJ WITH (NOLOCK) + JOIN fw.DimJobCode AS jc WITH (NOLOCK) ON jc.JobCodeID = OBJ.JobCodeID + JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = OBJ.DepartmentID + GROUP BY + OBJ.GroupingGUID + ) AS fte ON fte.GroupingGUID = slea.GroupingGUID + WHERE (@search IS NULL + OR ( + LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(fp.GetAdjustmentValue(fte.FTEAmount, slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\' + OR (fte.FTECount = 1 + AND LOWER(fte.FTEComment) LIKE @search ESCAPE '\') + OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR (fte.FTECount = 1 + AND LOWER(fte.DepartmentName) LIKE @search ESCAPE '\') + OR (fte.FTECount = 1 + AND LOWER(fte.JobCodeName) LIKE @search ESCAPE '\') + ) + ) + AND (@filter IS NULL + OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, slea.BudgetPhaseID) IN ( + SELECT [value] + FROM STRING_SPLIT(@filter, ' ' ) + ) + ) + + UNION ALL + + -- Manager Adjustments + -- JAZZ-15738 - Partition by smad.TimeClassID as well + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID, smad.TimeClassID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber + ,slea.AdjustmentGUID + ,slea.BudgetConfigGUID + ,slea.AdjustmentType + ,NULL AS [Value] + ,slea.AdjustmentFilterJSON + ,slea.GroupingHierarchyJSON + ,slea.AdjustedProperty + ,NULL AS Comment + ,slea.AuthorGUID + ,slea.AuthorFullName + ,slea.LastModifiedDateUtc + ,slea.DateCreatedUtc + ,slea.GroupingGUID + ,smad.TimeClassID + ,slea.BudgetPhaseID + ,slea.ClassificationGroupID + ,slea.ClassificationCategoryID + ,slea.UnitTypeId + ,adjComment.JobCodeName + ,adjComment.JobCodeCount + ,adjComment.DepartmentName + ,adjComment.DepartmentCount + ,NULL AS ImportUnitTypeIDs + ,slea.IsRecordDeleted + ,NULL AS EmployeeName + ,slea.IsErrored + FROM fp.StaffingAdjustment AS slea WITH (NOLOCK) + JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID + --JAZZ-15738 + LEFT JOIN fp.StaffingManagerAdjustmentData smad on slea.AdjustmentGUID = smad.AdjustmentGUID + LEFT JOIN ( + SELECT + OBJ.AdjustmentGUID + ,dept.Name AS DepartmentName + ,NULL AS JobCodeName + ,COUNT(dept.DepartmentID) AS DepartmentCount + ,COUNT(DISTINCT job.JobCodeID) AS JobCodeCount + FROM fp.StaffingManagerAdjustmentComment AS OBJ WITH (NOLOCK) + JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = OBJ.DepartmentID + LEFT JOIN fw.DimJobCode AS job WITH (NOLOCK) ON job.JobCodeID = OBJ.JobCodeID + LEFT JOIN #departmentsSecurity AS ds WITH (NOLOCK) ON ds.DepartmentID = OBJ.DepartmentID + WHERE @isDataSecured = 0 OR ds.DepartmentID IS NOT NULL + GROUP BY OBJ.AdjustmentGUID, dept.Name + ) AS adjComment ON adjComment.AdjustmentGUID = slea.AdjustmentGUID + LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID + LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON slea.ClassificationGroupID = acc.GroupID + AND slea.ClassificationCategoryID = acc.CategoryID + WHERE slea.AdjustmentType = 7 + AND slea.SubsectionID = 3 -- Staffing-Stuff + AND (@search IS NULL + OR ( + LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\' + OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR acc.[Name] LIKE @search ESCAPE '\' + OR acg.[Name] LIKE @search ESCAPE '\' + OR 'my budgets' LIKE @search ESCAPE '\' + OR LOWER(adjComment.DepartmentName) LIKE @search ESCAPE '\' + ) + ) + AND (@filter IS NULL + OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, smad.TimeClassID, slea.BudgetPhaseID) IN ( + SELECT [value] + FROM STRING_SPLIT(@filter, ' ' ) + ) + ) + AND adjComment.DepartmentName IS NOT NULL + + UNION ALL + + -- ManagerSet (new My Budgets) Adjustments + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID, adjComment.TimeClassID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber + ,slea.AdjustmentGUID + ,slea.BudgetConfigGUID + ,slea.AdjustmentType + ,NULL AS [Value] + ,slea.AdjustmentFilterJSON + ,slea.GroupingHierarchyJSON + ,slea.AdjustedProperty + ,NULL AS Comment + ,slea.AuthorGUID + ,slea.AuthorFullName + ,slea.LastModifiedDateUtc + ,slea.DateCreatedUtc + ,slea.GroupingGUID + ,adjComment.TimeClassID + ,slea.BudgetPhaseID + ,slea.ClassificationGroupID + ,slea.ClassificationCategoryID + ,slea.UnitTypeId + ,adjComment.JobCodeName + ,adjComment.JobCodeCount + ,adjComment.DepartmentName + ,adjComment.DepartmentCount + ,NULL AS ImportUnitTypeIDs + ,slea.IsRecordDeleted + ,NULL AS EmployeeName + ,slea.IsErrored + FROM fp.StaffingAdjustment AS slea WITH (NOLOCK) + JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID + LEFT JOIN ( + SELECT + OBJ.AdjustmentID + ,dept.Name AS DepartmentName + ,NULL AS JobCodeName + ,STRING_AGG(CAST(job.Name AS NVARCHAR(MAX)), ';') AS JobCodeNames + ,STRING_AGG(CAST(OBJ.Comment AS NVARCHAR(MAX)), ';') AS Comments + ,COUNT(dept.DepartmentID) AS DepartmentCount + ,COUNT(DISTINCT job.JobCodeID) AS JobCodeCount + ,OBJ.TimeClassID + FROM fp.StaffingManagerSetAdjustmentComment AS OBJ WITH (NOLOCK) + JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = OBJ.DepartmentID + LEFT JOIN fw.DimJobCode AS job WITH (NOLOCK) ON job.JobCodeID = OBJ.JobCodeID + LEFT JOIN #departmentsSecurity AS ds WITH (NOLOCK) ON ds.DepartmentID = OBJ.DepartmentID + WHERE @isDataSecured = 0 OR ds.DepartmentID IS NOT NULL + GROUP BY OBJ.AdjustmentID, dept.Name, OBJ.TimeClassID + ) AS adjComment ON adjComment.AdjustmentID = slea.AdjustmentID + LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID + LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON slea.ClassificationGroupID = acc.GroupID + AND slea.ClassificationCategoryID = acc.CategoryID + WHERE slea.AdjustmentType = 20 + AND slea.SubsectionID = 3 + AND (@search IS NULL + OR ( + LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\' + OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR acc.[Name] LIKE @search ESCAPE '\' + OR acg.[Name] LIKE @search ESCAPE '\' + OR adjComment.JobCodeNames LIKE @search ESCAPE '\' + OR adjComment.Comments LIKE @search ESCAPE '\' + OR 'my budgets' LIKE @search ESCAPE '\' + OR LOWER(adjComment.DepartmentName) LIKE @search ESCAPE '\' + ) + ) + AND (@filter IS NULL + OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, adjComment.TimeClassID, slea.BudgetPhaseID) IN ( + SELECT [value] + FROM STRING_SPLIT(@filter, ' ' ) + ) + ) + AND adjComment.DepartmentName IS NOT NULL + + UNION ALL + + -- NPE Add Employee Adjustments + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID, smad.TimeClassID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber + ,slea.AdjustmentGUID + ,slea.BudgetConfigGUID + ,slea.AdjustmentType + ,NULL AS [Value] + ,slea.AdjustmentFilterJSON + ,slea.GroupingHierarchyJSON + ,slea.AdjustedProperty + ,ebne.Comment AS Comment + ,slea.AuthorGUID + ,slea.AuthorFullName + ,slea.LastModifiedDateUtc + ,slea.DateCreatedUtc + ,slea.GroupingGUID + ,smad.TimeClassID + ,slea.BudgetPhaseID + ,slea.ClassificationGroupID + ,slea.ClassificationCategoryID + ,slea.UnitTypeId + ,job.Name AS JobCodeName + ,NULL AS JobCodeCount + ,dept.Name AS DepartmentName + ,NULL AS DepartmentCount + ,NULL AS ImportUnitTypeIDs + ,slea.IsRecordDeleted + ,emp.NameLast + ', ' + emp.NameFirst AS EmployeeName + ,slea.IsErrored + FROM fp.StaffingAdjustment AS slea WITH (NOLOCK) + JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID + LEFT JOIN fp.StaffingManagerAdjustmentData smad on slea.AdjustmentGUID = smad.AdjustmentGUID + JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = smad.DepartmentID + LEFT JOIN fw.DimJobCode AS job WITH (NOLOCK) ON job.JobCodeID = smad.JobCodeID + LEFT JOIN fp.EmployeeBudgetingNewEmployee AS ebne WITH (NOLOCK) ON smad.EmployeeID = ebne.EmployeeID + LEFT JOIN fw.DimEmployee AS emp WITH (NOLOCK) ON smad.EmployeeID = emp.EmployeeID + LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID + LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON slea.ClassificationGroupID = acc.GroupID + AND slea.ClassificationCategoryID = acc.CategoryID + WHERE slea.AdjustmentType = 17 + AND slea.SubsectionID = 3 -- Staffing-Stuff + -- Apply search, if needed + AND (@search IS NULL + OR ( + LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\' + OR LOWER(ebne.Comment) LIKE @search ESCAPE '\' + OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR ISNULL(acc.[Name], acg.[Name]) LIKE @search ESCAPE '\' + OR fp.SearchHierarchyLevel(slea.AdjustmentFilterJSON, @search) = 1 + OR LOWER(fp.GetAdjustmentMeasure(slea.AdjustmentType, slea.UnitTypeID)) LIKE @search ESCAPE '\' + + ) + ) + -- Apply filter, if needed + AND (@filter IS NULL + OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, smad.TimeClassID, slea.BudgetPhaseID) IN ( + SELECT [value] + FROM STRING_SPLIT(@filter, ' ' ) + ) + ) + -- GROUP BY slea.AdjustmentGUID, smad.TimeClassID, slea.BudgetPhaseID + + ) AS res_inner + -- Selecting only unique adjustments + WHERE res_inner.RowNumber = 1) AS res + ORDER BY res.DateCreatedUtc DESC + OFFSET @start ROWS + FETCH NEXT @pageSize ROWS ONLY + option (recompile) --!!! + ; + +END; +GO + + +--------------------------------------------- + +-- fp.StatisticsAddProviderRateCalculations +CREATE PROCEDURE [fp].[StatisticsAddProviderRateCalculations] + @BudgetConfigID INT, + @MonthsLoaded TINYINT, + @SelectedProviders [dbo].[SqlInt32ListTableType] READONLY, + @DepartmentIds [dbo].[SqlInt32ListTableType] READONLY + AS + BEGIN + + SELECT [value] AS ProviderID + INTO #BenchProviders + FROM @SelectedProviders + + SELECT [value] AS DepartmentID + INTO #DepartmentSecurity + FROM @DepartmentIds + + SELECT dsa.DriverAccountID, + dsa.DependentAccountID, + [dependent].Units / driver.Units AS Rate + FROM ( + SELECT fs.AccountID, + case @Monthsloaded + when 1 then SUM(fsh.ActualYTDValue01+fsh.PriorYearActualValue02+fsh.PriorYearActualValue03+fsh.PriorYearActualValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 2 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.PriorYearActualValue03+fsh.PriorYearActualValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 3 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.PriorYearActualValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 4 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 5 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 6 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 7 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 8 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 9 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 10 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.ActualYTDValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 11 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.ActualYTDValue10+fsh.ActualYTDValue11+fsh.PriorYearActualValue12) + else SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.ActualYTDValue10+fsh.ActualYTDValue11+fsh.ActualYTDValue12) + end AS Units + FROM fp.FactStatistics AS fs + JOIN fp.FactStatisticsHistory AS fsh ON fsh.StatisticsID = fs.StatisticsID + JOIN #BenchProviders AS p ON p.ProviderID = fs.ProviderID + JOIN #DepartmentSecurity AS ds ON ds.DepartmentID = fs.DepartmentID + WHERE fs.BudgetConfigID = @BudgetConfigID + AND SubsectionID = 1 + AND UnitTypeID = 140 + GROUP BY fs.AccountID ) as driver + JOIN fp.DependentStatisticsAccount AS dsa ON dsa.DriverAccountID = driver.AccountID + JOIN ( + SELECT fs.AccountID, + case @Monthsloaded + when 1 then SUM(fsh.ActualYTDValue01+fsh.PriorYearActualValue02+fsh.PriorYearActualValue03+fsh.PriorYearActualValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 2 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.PriorYearActualValue03+fsh.PriorYearActualValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 3 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.PriorYearActualValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 4 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.PriorYearActualValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 5 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.PriorYearActualValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 6 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.PriorYearActualValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 7 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.PriorYearActualValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 8 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.PriorYearActualValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 9 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.PriorYearActualValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 10 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.ActualYTDValue10+fsh.PriorYearActualValue11+fsh.PriorYearActualValue12) + when 11 then SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.ActualYTDValue10+fsh.ActualYTDValue11+fsh.PriorYearActualValue12) + else SUM(fsh.ActualYTDValue01+fsh.ActualYTDValue02+fsh.ActualYTDValue03+fsh.ActualYTDValue04+fsh.ActualYTDValue05+fsh.ActualYTDValue06+fsh.ActualYTDValue07+fsh.ActualYTDValue08+fsh.ActualYTDValue09+fsh.ActualYTDValue10+fsh.ActualYTDValue11+fsh.ActualYTDValue12) + end AS Units + FROM fp.FactStatistics AS fs + JOIN fp.FactStatisticsHistory AS fsh ON fsh.StatisticsID = fs.StatisticsID + JOIN #BenchProviders AS p ON p.ProviderID = fs.ProviderID + JOIN #DepartmentSecurity AS ds ON ds.DepartmentID = fs.DepartmentID + WHERE fs.BudgetConfigID = @BudgetConfigID + AND SubsectionID = 2 + AND UnitTypeID = 140 + GROUP BY fs.AccountID + ) as [dependent] ON [dependent].AccountID = dsa.DependentAccountID + WHERE dsa.BudgetConfigID = @BudgetConfigID + AND driver.Units <> 0 + AND [dependent].Units <> 0 +END +GO + + +--------------------------------------------- + +-- fp.procABBFlexRecalcFTEs +/* ************************************************************************************************************************ +** Author: Nathan LeRoy +** Create Date: 2015-12-15 +** Description: Recalc payroll FTEs based on hours recalc +************************************************************************************************************************** +** Change History +************************************************************************************************************************** +** CID Date Author Workitem Description +** 1 12/16/15 NL changed to update instead of insert +** 2 03/25/16 NL payroll pivoting fix +** 3 02/27/17 NL fixing arithmetic overflow error +** 4 03/25/17 NL updating to use entity config +** 5 07/29/18 MY update to use new structure +** 6 11/01/18 AI added source dimensionality filter +** 7 02/06/18 BK B-21763 Exclude designated Productive Classes from FTE calc +** 8 04/04/19 NL Adding budget phase filter +** 9 04/15/19 MY Adding return data so that adjustments can be re-applied +** 10 07/30/19 NL D-08399 changing FTE calc to use working hours instead of existing ratio +** 10 04/08/21 MY JAZZ-17545 Cleaning up targeting and making proc more readable/Updated the proc to not update too much +** 11 10/31/23 MY JAZZ-61705 Support PAF for the new data model - Staffing +** 12 07/02/24 DM JAZZ-72920 Removed dependency for PercentAdjustmentFactor +*************************************************************************************************************************/ +CREATE PROC [fp].[procABBFlexRecalcFTEs] + @EntityGroupConfigID INT, + @FiscalYearID SMALLINT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#flexHours') IS NOT NULL DROP TABLE #flexHours + IF OBJECT_ID('tempdb..#basisIDs') IS NOT NULL DROP TABLE #basisIDs + CREATE TABLE #basisIDs (StaffingID INT); + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[Staffing] d WITH (READUNCOMMITTED) + where d.EntityGroupConfigID = @EntityGroupConfigID + END + + SELECT base.DepartmentID, base.EntityID, base.JobCodeID, base.PayCodeGroupID, base.EntityGroupConfigID, base.VariabilityID, + base.TargetAdjustedHours01, + base.TargetAdjustedHours02, + base.TargetAdjustedHours03, + base.TargetAdjustedHours04, + base.TargetAdjustedHours05, + base.TargetAdjustedHours06, + base.TargetAdjustedHours07, + base.TargetAdjustedHours08, + base.TargetAdjustedHours09, + base.TargetAdjustedHours10, + base.TargetAdjustedHours11, + base.TargetAdjustedHours12, + + base.BudgetAdjustedHours01, + base.BudgetAdjustedHours02, + base.BudgetAdjustedHours03, + base.BudgetAdjustedHours04, + base.BudgetAdjustedHours05, + base.BudgetAdjustedHours06, + base.BudgetAdjustedHours07, + base.BudgetAdjustedHours08, + base.BudgetAdjustedHours09, + base.BudgetAdjustedHours10, + base.BudgetAdjustedHours11, + base.BudgetAdjustedHours12 + INTO #flexHours + FROM [fp].[Staffing] base + INNER JOIN #FilterByDepartment s ON s.DepartmentID = base.DepartmentID + WHERE base.VariabilityID = 2 + AND base.EntityGroupConfigID = @EntityGroupConfigID + + UPDATE fs + SET + fs.TargetAdjustedFTEs01 = COALESCE((flexHours.TargetAdjustedHours01 / NULLIF(wh.Month01, 0)), 0), + fs.TargetAdjustedFTEs02 = COALESCE((flexHours.TargetAdjustedHours02 / NULLIF(wh.Month02, 0)), 0), + fs.TargetAdjustedFTEs03 = COALESCE((flexHours.TargetAdjustedHours03 / NULLIF(wh.Month03, 0)), 0), + fs.TargetAdjustedFTEs04 = COALESCE((flexHours.TargetAdjustedHours04 / NULLIF(wh.Month04, 0)), 0), + fs.TargetAdjustedFTEs05 = COALESCE((flexHours.TargetAdjustedHours05 / NULLIF(wh.Month05, 0)), 0), + fs.TargetAdjustedFTEs06 = COALESCE((flexHours.TargetAdjustedHours06 / NULLIF(wh.Month06, 0)), 0), + fs.TargetAdjustedFTEs07 = COALESCE((flexHours.TargetAdjustedHours07 / NULLIF(wh.Month07, 0)), 0), + fs.TargetAdjustedFTEs08 = COALESCE((flexHours.TargetAdjustedHours08 / NULLIF(wh.Month08, 0)), 0), + fs.TargetAdjustedFTEs09 = COALESCE((flexHours.TargetAdjustedHours09 / NULLIF(wh.Month09, 0)), 0), + fs.TargetAdjustedFTEs10 = COALESCE((flexHours.TargetAdjustedHours10 / NULLIF(wh.Month10, 0)), 0), + fs.TargetAdjustedFTEs11 = COALESCE((flexHours.TargetAdjustedHours11 / NULLIF(wh.Month11, 0)), 0), + fs.TargetAdjustedFTEs12 = COALESCE((flexHours.TargetAdjustedHours12 / NULLIF(wh.Month12, 0)), 0), + + fs.BudgetAdjustedFTEs01 = COALESCE((flexHours.BudgetAdjustedHours01 / NULLIF(wh.Month01, 0)), 0), + fs.BudgetAdjustedFTEs02 = COALESCE((flexHours.BudgetAdjustedHours02 / NULLIF(wh.Month02, 0)), 0), + fs.BudgetAdjustedFTEs03 = COALESCE((flexHours.BudgetAdjustedHours03 / NULLIF(wh.Month03, 0)), 0), + fs.BudgetAdjustedFTEs04 = COALESCE((flexHours.BudgetAdjustedHours04 / NULLIF(wh.Month04, 0)), 0), + fs.BudgetAdjustedFTEs05 = COALESCE((flexHours.BudgetAdjustedHours05 / NULLIF(wh.Month05, 0)), 0), + fs.BudgetAdjustedFTEs06 = COALESCE((flexHours.BudgetAdjustedHours06 / NULLIF(wh.Month06, 0)), 0), + fs.BudgetAdjustedFTEs07 = COALESCE((flexHours.BudgetAdjustedHours07 / NULLIF(wh.Month07, 0)), 0), + fs.BudgetAdjustedFTEs08 = COALESCE((flexHours.BudgetAdjustedHours08 / NULLIF(wh.Month08, 0)), 0), + fs.BudgetAdjustedFTEs09 = COALESCE((flexHours.BudgetAdjustedHours09 / NULLIF(wh.Month09, 0)), 0), + fs.BudgetAdjustedFTEs10 = COALESCE((flexHours.BudgetAdjustedHours10 / NULLIF(wh.Month10, 0)), 0), + fs.BudgetAdjustedFTEs11 = COALESCE((flexHours.BudgetAdjustedHours11 / NULLIF(wh.Month11, 0)), 0), + fs.BudgetAdjustedFTEs12 = COALESCE((flexHours.BudgetAdjustedHours12 / NULLIF(wh.Month12, 0)), 0) + OUTPUT + INSERTED.StaffingID + INTO + #basisIDs (StaffingID) + FROM [fp].[Staffing] fs + INNER JOIN #FilterByDepartment s ON s.DepartmentID = fs.DepartmentID + INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @FiscalYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fs.PayCodeGroupID = exc.PayCodeGroupID + LEFT JOIN #flexHours flexHours + ON flexHours.DepartmentID = fs.DepartmentID + AND flexHours.EntityID = fs.EntityID + AND flexHours.JobCodeID = fs.JobCodeID + AND flexHours.PayCodeGroupID = fs.PayCodeGroupID + AND flexHours.EntityGroupConfigID = fs.EntityGroupConfigID + AND flexHours.VariabilityID = fs.VariabilityID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.VariabilityID = 2 + AND exc.PayCodeGroupID IS NULL + AND fs.FlexingTypeID = 7 -- Patient Activity + + -- Return the data back so we can re-apply any percent adjustments and refresh the change history + SELECT StaffingID, m.FiscalMonthID, CAST(2 AS TINYINT) AS BudgetPhaseID, CAST(2 AS TINYINT) AS TimeClassID, CAST(144 AS TINYINT) AS UnitTypeID, f.Value + FROM ( + SELECT bdgt.StaffingID, bdgt.TargetAdjustedFTEs01, bdgt.TargetAdjustedFTEs02, bdgt.TargetAdjustedFTEs03, bdgt.TargetAdjustedFTEs04, bdgt.TargetAdjustedFTEs05, bdgt.TargetAdjustedFTEs06, + bdgt.TargetAdjustedFTEs07, bdgt.TargetAdjustedFTEs08, bdgt.TargetAdjustedFTEs09, bdgt.TargetAdjustedFTEs10, bdgt.TargetAdjustedFTEs11, bdgt.TargetAdjustedFTEs12 + FROM #basisIDs ids + INNER JOIN [fp].[Staffing] bdgt ON ids.StaffingID = bdgt.StaffingID + ) gl + UNPIVOT ( Value FOR FiscalMonth IN (TargetAdjustedFTEs01, TargetAdjustedFTEs02, TargetAdjustedFTEs03, TargetAdjustedFTEs04, TargetAdjustedFTEs05, TargetAdjustedFTEs06, TargetAdjustedFTEs07, TargetAdjustedFTEs08, TargetAdjustedFTEs09, TargetAdjustedFTEs10, TargetAdjustedFTEs11, TargetAdjustedFTEs12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'TargetAdjustedFTEs', 'Month') + UNION ALL + SELECT StaffingID, m.FiscalMonthID, CAST(3 AS TINYINT) AS BudgetPhaseID, CAST(2 AS TINYINT) AS TimeClassID, CAST(144 AS TINYINT) AS UnitTypeID, f.Value + FROM ( + SELECT bdgt.StaffingID, bdgt.BudgetAdjustedFTEs01, bdgt.BudgetAdjustedFTEs02, bdgt.BudgetAdjustedFTEs03, bdgt.BudgetAdjustedFTEs04, bdgt.BudgetAdjustedFTEs05, bdgt.BudgetAdjustedFTEs06, + bdgt.BudgetAdjustedFTEs07, bdgt.BudgetAdjustedFTEs08, bdgt.BudgetAdjustedFTEs09, bdgt.BudgetAdjustedFTEs10, bdgt.BudgetAdjustedFTEs11, bdgt.BudgetAdjustedFTEs12 + FROM #basisIDs ids + INNER JOIN [fp].[Staffing] bdgt ON ids.StaffingID = bdgt.StaffingID + ) gl + UNPIVOT ( Value FOR FiscalMonth IN (BudgetAdjustedFTEs01, BudgetAdjustedFTEs02, BudgetAdjustedFTEs03, BudgetAdjustedFTEs04, BudgetAdjustedFTEs05, BudgetAdjustedFTEs06, BudgetAdjustedFTEs07, BudgetAdjustedFTEs08, BudgetAdjustedFTEs09, BudgetAdjustedFTEs10, BudgetAdjustedFTEs11, BudgetAdjustedFTEs12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'BudgetAdjustedFTEs', 'Month') +GO + + +--------------------------------------------- + +-- fp.procABBFlexRecalcFTEs_Initial +CREATE PROC [fp].[procABBFlexRecalcFTEs_Initial] + @EntityGroupConfigID INT, + @FiscalYearID SMALLINT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-07-13 MD JAZZ-28981 Initial + ** 2 2023-10-31 MY JAZZ-61705 Support PAF for the new data model - Staffing + *************************************************************/ + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#flexHours') IS NOT NULL DROP TABLE #flexHours + IF OBJECT_ID('tempdb..#basisIDs') IS NOT NULL DROP TABLE #basisIDs + CREATE TABLE #basisIDs (StaffingID INT); + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[Staffing] d WITH (READUNCOMMITTED) + WHERE d.EntityGroupConfigID = @EntityGroupConfigID + AND SubsectionID = 3 + AND FlexingTypeID = 7 -- Patient Activity + END + + SELECT + base.DepartmentID, base.EntityID, base.JobCodeID, base.PayCodeGroupID, base.EntityGroupConfigID, base.VariabilityID, + base.InitialBudgetHours01, base.InitialBudgetHours02, base.InitialBudgetHours03, base.InitialBudgetHours04, + base.InitialBudgetHours05, base.InitialBudgetHours06, base.InitialBudgetHours07, base.InitialBudgetHours08, + base.InitialBudgetHours09, base.InitialBudgetHours10, base.InitialBudgetHours11, base.InitialBudgetHours12 + INTO #flexHours + FROM [fp].[Staffing] base + INNER JOIN #FilterByDepartment s ON s.DepartmentID = base.DepartmentID + WHERE base.VariabilityID = 2 + AND base.EntityGroupConfigID = @EntityGroupConfigID + AND base.SubsectionID = 3 + + UPDATE + baseFtes + SET + InitialBudgetFTEs01 = COALESCE((flexHours.InitialBudgetHours01 / NULLIF(wh.Month01, 0)), 0), + InitialBudgetFTEs02 = COALESCE((flexHours.InitialBudgetHours02 / NULLIF(wh.Month02, 0)), 0), + InitialBudgetFTEs03 = COALESCE((flexHours.InitialBudgetHours03 / NULLIF(wh.Month03, 0)), 0), + InitialBudgetFTEs04 = COALESCE((flexHours.InitialBudgetHours04 / NULLIF(wh.Month04, 0)), 0), + InitialBudgetFTEs05 = COALESCE((flexHours.InitialBudgetHours05 / NULLIF(wh.Month05, 0)), 0), + InitialBudgetFTEs06 = COALESCE((flexHours.InitialBudgetHours06 / NULLIF(wh.Month06, 0)), 0), + InitialBudgetFTEs07 = COALESCE((flexHours.InitialBudgetHours07 / NULLIF(wh.Month07, 0)), 0), + InitialBudgetFTEs08 = COALESCE((flexHours.InitialBudgetHours08 / NULLIF(wh.Month08, 0)), 0), + InitialBudgetFTEs09 = COALESCE((flexHours.InitialBudgetHours09 / NULLIF(wh.Month09, 0)), 0), + InitialBudgetFTEs10 = COALESCE((flexHours.InitialBudgetHours10 / NULLIF(wh.Month10, 0)), 0), + InitialBudgetFTEs11 = COALESCE((flexHours.InitialBudgetHours11 / NULLIF(wh.Month11, 0)), 0), + InitialBudgetFTEs12 = COALESCE((flexHours.InitialBudgetHours12 / NULLIF(wh.Month12, 0)), 0) + OUTPUT + INSERTED.StaffingID + INTO + #basisIDs (StaffingID) + FROM [fp].[Staffing] baseFtes + INNER JOIN #FilterByDepartment s ON s.DepartmentID = baseFtes.DepartmentID + INNER JOIN [fw].[DimJobCode] jc on baseFtes.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on baseFtes.DepartmentID = dept.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh + on wh.FiscalYearID = @FiscalYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc + on baseFtes.PayCodeGroupID = exc.PayCodeGroupID + LEFT JOIN #flexHours flexHours + ON flexHours.DepartmentID = baseFtes.DepartmentID + AND flexHours.EntityID = baseFtes.EntityID + AND flexHours.JobCodeID = baseFtes.JobCodeID + AND flexHours.PayCodeGroupID = baseFtes.PayCodeGroupID + AND flexHours.EntityGroupConfigID = baseFtes.EntityGroupConfigID + AND flexHours.VariabilityID = baseFtes.VariabilityID + WHERE baseFtes.EntityGroupConfigID = @EntityGroupConfigID + AND baseFtes.VariabilityID = 2 + AND exc.PayCodeGroupID IS NULL + AND baseFtes.FlexingTypeID = 7 -- Patient Activity + AND baseFtes.SubsectionID = 3 + + SELECT StaffingID as BasisID from #basisIDs +GO + + +--------------------------------------------- + +-- fp.procABBFlexRecalcFTEs_Projection +/************************************************************************************************************************** +** Change History +************************************************************************************************************************** +** CID Date Author Workitem Description +** 1 07/22/22 MD JAZZ-38981 Initial +** 2 2023-10-31 MY JAZZ-61705 Support PAF for the new data model - Staffing +** 3 07/02/24 DM JAZZ-72920 Removed dependency for PercentAdjustmentFactor +*************************************************************************************************************************/ +CREATE PROC [fp].[procABBFlexRecalcFTEs_Projection] + @EntityGroupConfigID INT, + @FiscalYearID SMALLINT, + @MonthsLoaded INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#flexHours') IS NOT NULL DROP TABLE #flexHours + IF OBJECT_ID('tempdb..#basisIDs') IS NOT NULL DROP TABLE #basisIDs + CREATE TABLE #basisIDs (StaffingID INT); + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[Staffing] d WITH (READUNCOMMITTED) + where d.EntityGroupConfigID = @EntityGroupConfigID + END + + SELECT + base.DepartmentID, base.EntityID, base.JobCodeID, base.PayCodeGroupID, base.EntityGroupConfigID, base.VariabilityID, + base.ProjectionAdjustedHours01, + base.ProjectionAdjustedHours02, + base.ProjectionAdjustedHours03, + base.ProjectionAdjustedHours04, + base.ProjectionAdjustedHours05, + base.ProjectionAdjustedHours06, + base.ProjectionAdjustedHours07, + base.ProjectionAdjustedHours08, + base.ProjectionAdjustedHours09, + base.ProjectionAdjustedHours10, + base.ProjectionAdjustedHours11, + base.ProjectionAdjustedHours12 + INTO #flexHours + FROM [fp].[Staffing] base + INNER JOIN #FilterByDepartment s ON s.DepartmentID = base.DepartmentID + WHERE base.VariabilityID = 2 + AND base.EntityGroupConfigID = @EntityGroupConfigID + + UPDATE fs + SET + fs.ProjectionAdjustedFTEs01 = CASE WHEN @MonthsLoaded < 1 THEN COALESCE((flexHours.ProjectionAdjustedHours01 / NULLIF(wh.Month01, 0)), 0) ELSE fs.ProjectionAdjustedFTEs01 END, + fs.ProjectionAdjustedFTEs02 = CASE WHEN @MonthsLoaded < 2 THEN COALESCE((flexHours.ProjectionAdjustedHours02 / NULLIF(wh.Month02, 0)), 0) ELSE fs.ProjectionAdjustedFTEs02 END, + fs.ProjectionAdjustedFTEs03 = CASE WHEN @MonthsLoaded < 3 THEN COALESCE((flexHours.ProjectionAdjustedHours03 / NULLIF(wh.Month03, 0)), 0) ELSE fs.ProjectionAdjustedFTEs03 END, + fs.ProjectionAdjustedFTEs04 = CASE WHEN @MonthsLoaded < 4 THEN COALESCE((flexHours.ProjectionAdjustedHours04 / NULLIF(wh.Month04, 0)), 0) ELSE fs.ProjectionAdjustedFTEs04 END, + fs.ProjectionAdjustedFTEs05 = CASE WHEN @MonthsLoaded < 5 THEN COALESCE((flexHours.ProjectionAdjustedHours05 / NULLIF(wh.Month05, 0)), 0) ELSE fs.ProjectionAdjustedFTEs05 END, + fs.ProjectionAdjustedFTEs06 = CASE WHEN @MonthsLoaded < 6 THEN COALESCE((flexHours.ProjectionAdjustedHours06 / NULLIF(wh.Month06, 0)), 0) ELSE fs.ProjectionAdjustedFTEs06 END, + fs.ProjectionAdjustedFTEs07 = CASE WHEN @MonthsLoaded < 7 THEN COALESCE((flexHours.ProjectionAdjustedHours07 / NULLIF(wh.Month07, 0)), 0) ELSE fs.ProjectionAdjustedFTEs07 END, + fs.ProjectionAdjustedFTEs08 = CASE WHEN @MonthsLoaded < 8 THEN COALESCE((flexHours.ProjectionAdjustedHours08 / NULLIF(wh.Month08, 0)), 0) ELSE fs.ProjectionAdjustedFTEs08 END, + fs.ProjectionAdjustedFTEs09 = CASE WHEN @MonthsLoaded < 9 THEN COALESCE((flexHours.ProjectionAdjustedHours09 / NULLIF(wh.Month09, 0)), 0) ELSE fs.ProjectionAdjustedFTEs09 END, + fs.ProjectionAdjustedFTEs10 = CASE WHEN @MonthsLoaded < 10 THEN COALESCE((flexHours.ProjectionAdjustedHours10 / NULLIF(wh.Month10, 0)), 0) ELSE fs.ProjectionAdjustedFTEs10 END, + fs.ProjectionAdjustedFTEs11 = CASE WHEN @MonthsLoaded < 11 THEN COALESCE((flexHours.ProjectionAdjustedHours11 / NULLIF(wh.Month11, 0)), 0) ELSE fs.ProjectionAdjustedFTEs11 END, + fs.ProjectionAdjustedFTEs12 = CASE WHEN @MonthsLoaded < 12 THEN COALESCE((flexHours.ProjectionAdjustedHours12 / NULLIF(wh.Month12, 0)), 0) ELSE fs.ProjectionAdjustedFTEs12 END + OUTPUT INSERTED.StaffingID + INTO #basisIDs (StaffingID) + FROM [fp].[Staffing] fs + INNER JOIN #FilterByDepartment s ON s.DepartmentID = fs.DepartmentID + INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @FiscalYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fs.PayCodeGroupID = exc.PayCodeGroupID + LEFT JOIN #flexHours flexHours + ON flexHours.DepartmentID = fs.DepartmentID + AND flexHours.EntityID = fs.EntityID + AND flexHours.JobCodeID = fs.JobCodeID + AND flexHours.PayCodeGroupID = fs.PayCodeGroupID + AND flexHours.EntityGroupConfigID = fs.EntityGroupConfigID + AND flexHours.VariabilityID = fs.VariabilityID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.VariabilityID = 2 + AND exc.PayCodeGroupID IS NULL + AND fs.FlexingTypeID = 7 -- Patient Activity + + -- Return the data back so we can re-apply any percent adjustments and refresh the change history + SELECT StaffingID, m.FiscalMonthID, CAST(3 AS TINYINT) AS BudgetPhaseID, CAST(12 AS TINYINT) AS TimeClassID, CAST(144 AS TINYINT) AS UnitTypeID, f.Value + FROM ( + SELECT + proj.StaffingID, + proj.ProjectionAdjustedFTEs01, proj.ProjectionAdjustedFTEs02, proj.ProjectionAdjustedFTEs03, proj.ProjectionAdjustedFTEs04, + proj.ProjectionAdjustedFTEs05, proj.ProjectionAdjustedFTEs06, proj.ProjectionAdjustedFTEs07, proj.ProjectionAdjustedFTEs08, + proj.ProjectionAdjustedFTEs09, proj.ProjectionAdjustedFTEs10, proj.ProjectionAdjustedFTEs11, proj.ProjectionAdjustedFTEs12 + FROM #basisIDs ids + INNER JOIN [fp].[Staffing] proj ON ids.StaffingID = proj.StaffingID + ) gl + UNPIVOT ( Value FOR FiscalMonth IN (ProjectionAdjustedFTEs01, ProjectionAdjustedFTEs02, ProjectionAdjustedFTEs03, ProjectionAdjustedFTEs04, ProjectionAdjustedFTEs05, ProjectionAdjustedFTEs06, ProjectionAdjustedFTEs07, ProjectionAdjustedFTEs08, ProjectionAdjustedFTEs09, ProjectionAdjustedFTEs10, ProjectionAdjustedFTEs11, ProjectionAdjustedFTEs12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectionAdjustedFTEs', 'Month') +GO + + +--------------------------------------------- + +-- fp.procABBFlexRecalcHours +/************************************************************************************************************************* +** Author: Nathan LeRoy +** Create Date: 2015-12-15 +** Description: Recalc payroll hours based on dollars flexing +** Last Modified: 2018-11-01 +************************************************************************************************************************** +** Change History +************************************************************************************************************************** +** CID Date Author WI Description +** 1 12/16/15 NL changed to update instead of insert +** 2 03/25/16 NL payroll pivoting fix +** 3 12/07/16 NL added variabilityID +** 4 03/25/17 NL updating to use entity config +** 5 07/29/18 MY update to use new structure +** 6 11/01/18 AI add source dimensionality +** 7 04/04/19 NL fixing join on wage rate +** 8 04/15/19 MY adding return data so that adjustments can be re-applied +** 9 01/18/21 BW removing inner join on UserDefinedTableType [fp].[BudgetRefreshSourceDimensionality]; use temp table instead +** 10 04/08/21 MY JAZZ-17545 Cleaning up targeting and making proc more readable/Updated the proc to not update too much +** 11 2023-10-31 MY JAZZ-61705 Support PAF for the new data model - Staffing +** 12 07/02/24 DM JAZZ-72920 Removed dependency for PercentAdjustmentFactor +*************************************************************************************************************************/ +CREATE PROC [fp].[procABBFlexRecalcHours] + @EntityGroupConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#basisIDs') IS NOT NULL DROP TABLE #basisIDs + IF OBJECT_ID('tempdb..#flexDollars') IS NOT NULL DROP TABLE #flexDollars + IF OBJECT_ID('tempdb..#origWageRate') IS NOT NULL DROP TABLE #origWageRate + + CREATE TABLE #basisIDs (StaffingID INT); + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[Staffing] d WITH (READUNCOMMITTED) + where d.EntityGroupConfigID = @EntityGroupConfigID + END + + -- For the purposes of recalculating the hours, we need to pre-adjusted value + SELECT base.DepartmentID, base.EntityID, base.JobCodeID, base.PayCodeGroupID, base.EntityGroupConfigID, base.VariabilityID, + base.TargetAdjustedDollars01, + base.TargetAdjustedDollars02, + base.TargetAdjustedDollars03, + base.TargetAdjustedDollars04, + base.TargetAdjustedDollars05, + base.TargetAdjustedDollars06, + base.TargetAdjustedDollars07, + base.TargetAdjustedDollars08, + base.TargetAdjustedDollars09, + base.TargetAdjustedDollars10, + base.TargetAdjustedDollars11, + base.TargetAdjustedDollars12, + + base.BudgetAdjustedDollars01, + base.BudgetAdjustedDollars02, + base.BudgetAdjustedDollars03, + base.BudgetAdjustedDollars04, + base.BudgetAdjustedDollars05, + base.BudgetAdjustedDollars06, + base.BudgetAdjustedDollars07, + base.BudgetAdjustedDollars08, + base.BudgetAdjustedDollars09, + base.BudgetAdjustedDollars10, + base.BudgetAdjustedDollars11, + base.BudgetAdjustedDollars12 + INTO #flexDollars + FROM [fp].[Staffing] base + INNER JOIN #FilterByDepartment s ON s.DepartmentID = base.DepartmentID + WHERE base.VariabilityID = 2 + AND base.EntityGroupConfigID = @EntityGroupConfigID + + SELECT base.DepartmentID, base.EntityID, base.JobCodeID, base.PayCodeGroupID, base.EntityGroupConfigID, base.VariabilityID, + wr.TargetAdjusted01, wr.TargetAdjusted02, wr.TargetAdjusted03, wr.TargetAdjusted04, wr.TargetAdjusted05, wr.TargetAdjusted06, + wr.TargetAdjusted07, wr.TargetAdjusted08, wr.TargetAdjusted09, wr.TargetAdjusted10, wr.TargetAdjusted11, wr.TargetAdjusted12, + wr.BudgetAdjusted01, wr.BudgetAdjusted02, wr.BudgetAdjusted03, wr.BudgetAdjusted04, wr.BudgetAdjusted05, wr.BudgetAdjusted06, + wr.BudgetAdjusted07, wr.BudgetAdjusted08, wr.BudgetAdjusted09, wr.BudgetAdjusted10, wr.BudgetAdjusted11, wr.BudgetAdjusted12 + INTO #origWageRate + FROM [fp].[Staffing] base + INNER JOIN #FilterByDepartment s ON s.DepartmentID = base.DepartmentID + INNER JOIN [fp].[StaffingWageRate] wr ON base.StaffingWageRateID = wr.StaffingWageRateID + WHERE base.VariabilityID = 2 + AND base.EntityGroupConfigID = @EntityGroupConfigID + + UPDATE + hours + SET + hours.TargetAdjustedHours01 = COALESCE(flexDollars.TargetAdjustedDollars01 / NULLIF(origWageRate.TargetAdjusted01, 0), 0), + hours.TargetAdjustedHours02 = COALESCE(flexDollars.TargetAdjustedDollars02 / NULLIF(origWageRate.TargetAdjusted02, 0), 0), + hours.TargetAdjustedHours03 = COALESCE(flexDollars.TargetAdjustedDollars03 / NULLIF(origWageRate.TargetAdjusted03, 0), 0), + hours.TargetAdjustedHours04 = COALESCE(flexDollars.TargetAdjustedDollars04 / NULLIF(origWageRate.TargetAdjusted04, 0), 0), + hours.TargetAdjustedHours05 = COALESCE(flexDollars.TargetAdjustedDollars05 / NULLIF(origWageRate.TargetAdjusted05, 0), 0), + hours.TargetAdjustedHours06 = COALESCE(flexDollars.TargetAdjustedDollars06 / NULLIF(origWageRate.TargetAdjusted06, 0), 0), + hours.TargetAdjustedHours07 = COALESCE(flexDollars.TargetAdjustedDollars07 / NULLIF(origWageRate.TargetAdjusted07, 0), 0), + hours.TargetAdjustedHours08 = COALESCE(flexDollars.TargetAdjustedDollars08 / NULLIF(origWageRate.TargetAdjusted08, 0), 0), + hours.TargetAdjustedHours09 = COALESCE(flexDollars.TargetAdjustedDollars09 / NULLIF(origWageRate.TargetAdjusted09, 0), 0), + hours.TargetAdjustedHours10 = COALESCE(flexDollars.TargetAdjustedDollars10 / NULLIF(origWageRate.TargetAdjusted10, 0), 0), + hours.TargetAdjustedHours11 = COALESCE(flexDollars.TargetAdjustedDollars11 / NULLIF(origWageRate.TargetAdjusted11, 0), 0), + hours.TargetAdjustedHours12 = COALESCE(flexDollars.TargetAdjustedDollars12 / NULLIF(origWageRate.TargetAdjusted12, 0), 0), + hours.BudgetAdjustedHours01 = COALESCE(flexDollars.BudgetAdjustedDollars01 / NULLIF(origWageRate.BudgetAdjusted01, 0), 0), + hours.BudgetAdjustedHours02 = COALESCE(flexDollars.BudgetAdjustedDollars02 / NULLIF(origWageRate.BudgetAdjusted02, 0), 0), + hours.BudgetAdjustedHours03 = COALESCE(flexDollars.BudgetAdjustedDollars03 / NULLIF(origWageRate.BudgetAdjusted03, 0), 0), + hours.BudgetAdjustedHours04 = COALESCE(flexDollars.BudgetAdjustedDollars04 / NULLIF(origWageRate.BudgetAdjusted04, 0), 0), + hours.BudgetAdjustedHours05 = COALESCE(flexDollars.BudgetAdjustedDollars05 / NULLIF(origWageRate.BudgetAdjusted05, 0), 0), + hours.BudgetAdjustedHours06 = COALESCE(flexDollars.BudgetAdjustedDollars06 / NULLIF(origWageRate.BudgetAdjusted06, 0), 0), + hours.BudgetAdjustedHours07 = COALESCE(flexDollars.BudgetAdjustedDollars07 / NULLIF(origWageRate.BudgetAdjusted07, 0), 0), + hours.BudgetAdjustedHours08 = COALESCE(flexDollars.BudgetAdjustedDollars08 / NULLIF(origWageRate.BudgetAdjusted08, 0), 0), + hours.BudgetAdjustedHours09 = COALESCE(flexDollars.BudgetAdjustedDollars09 / NULLIF(origWageRate.BudgetAdjusted09, 0), 0), + hours.BudgetAdjustedHours10 = COALESCE(flexDollars.BudgetAdjustedDollars10 / NULLIF(origWageRate.BudgetAdjusted10, 0), 0), + hours.BudgetAdjustedHours11 = COALESCE(flexDollars.BudgetAdjustedDollars11 / NULLIF(origWageRate.BudgetAdjusted11, 0), 0), + hours.BudgetAdjustedHours12 = COALESCE(flexDollars.BudgetAdjustedDollars12 / NULLIF(origWageRate.BudgetAdjusted12, 0), 0) + OUTPUT + INSERTED.StaffingID + INTO + #basisIDs (StaffingID) + FROM [fp].[Staffing] hours + INNER JOIN #FilterByDepartment s ON s.DepartmentID = hours.DepartmentID + LEFT JOIN #flexDollars flexDollars ON flexDollars.DepartmentID = hours.DepartmentID + AND flexDollars.EntityID = hours.EntityID + AND flexDollars.JobCodeID = hours.JobCodeID + AND flexDollars.PayCodeGroupID = hours.PayCodeGroupID + AND flexDollars.EntityGroupConfigID = hours.EntityGroupConfigID + LEFT JOIN #origWageRate origWageRate ON flexDollars.DepartmentID = origWageRate.DepartmentID + AND flexDollars.EntityID = origWageRate.EntityID + AND flexDollars.JobCodeID = origWageRate.JobCodeID + AND flexDollars.PayCodeGroupID = origWageRate.PayCodeGroupID + AND flexDollars.EntityGroupConfigID = origWageRate.EntityGroupConfigID + WHERE hours.EntityGroupConfigID = @EntityGroupConfigID + AND hours.VariabilityID = 2 + AND hours.FlexingTypeID = 7 -- Patient Activity + + -- Return the data back so we can re-apply any percent adjustments and refresh the change history + SELECT StaffingID, m.FiscalMonthID, cast(2 as tinyint) AS BudgetPhaseID, cast(2 as tinyint) AS TimeClassID, CAST(51 AS TINYINT) AS UnitTypeID, f.Value + FROM ( + SELECT bdgt.StaffingID, + bdgt.TargetAdjustedHours01, bdgt.TargetAdjustedHours02, bdgt.TargetAdjustedHours03, bdgt.TargetAdjustedHours04, bdgt.TargetAdjustedHours05, bdgt.TargetAdjustedHours06, + bdgt.TargetAdjustedHours07, bdgt.TargetAdjustedHours08, bdgt.TargetAdjustedHours09, bdgt.TargetAdjustedHours10, bdgt.TargetAdjustedHours11, bdgt.TargetAdjustedHours12 + FROM #basisIDs ids + INNER JOIN [fp].[Staffing] bdgt ON ids.StaffingID = bdgt.StaffingID + ) gl + UNPIVOT ( Value FOR FiscalMonth IN (TargetAdjustedHours01, TargetAdjustedHours02, TargetAdjustedHours03, TargetAdjustedHours04, TargetAdjustedHours05, TargetAdjustedHours06, + TargetAdjustedHours07, TargetAdjustedHours08, TargetAdjustedHours09, TargetAdjustedHours10, TargetAdjustedHours11, TargetAdjustedHours12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'TargetAdjustedHours', 'Month') + UNION ALL + SELECT StaffingID, m.FiscalMonthID, CAST(3 AS TINYINT) AS BudgetPhaseID, CAST(2 AS TINYINT) AS TimeClassID, CAST(51 AS TINYINT) AS UnitTypeID, f.Value + FROM ( + SELECT bdgt.StaffingID, + bdgt.BudgetAdjustedHours01, bdgt.BudgetAdjustedHours02, bdgt.BudgetAdjustedHours03, bdgt.BudgetAdjustedHours04, bdgt.BudgetAdjustedHours05, bdgt.BudgetAdjustedHours06, + bdgt.BudgetAdjustedHours07, bdgt.BudgetAdjustedHours08, bdgt.BudgetAdjustedHours09, bdgt.BudgetAdjustedHours10, bdgt.BudgetAdjustedHours11, bdgt.BudgetAdjustedHours12 + FROM #basisIDs ids + INNER JOIN [fp].[Staffing] bdgt ON ids.StaffingID = bdgt.StaffingID + ) gl + UNPIVOT ( Value FOR FiscalMonth IN (BudgetAdjustedHours01, BudgetAdjustedHours02, BudgetAdjustedHours03, BudgetAdjustedHours04, BudgetAdjustedHours05, BudgetAdjustedHours06, + BudgetAdjustedHours07, BudgetAdjustedHours08, BudgetAdjustedHours09, BudgetAdjustedHours10, BudgetAdjustedHours11, BudgetAdjustedHours12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'BudgetAdjustedHours', 'Month'); +GO + + +--------------------------------------------- + +-- fp.procABBFlexRecalcHours_Initial +CREATE PROC [fp].[procABBFlexRecalcHours_Initial] + @EntityGroupConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-07-13 MD JAZZ-28981 Initial + ** 2 2023-10-31 MY JAZZ-61705 Support PAF for the new data model - Staffing + *************************************************************/ + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#basisIDs') IS NOT NULL DROP TABLE #basisIDs + IF OBJECT_ID('tempdb..#flexDollars') IS NOT NULL DROP TABLE #flexDollars + IF OBJECT_ID('tempdb..#origWageRate') IS NOT NULL DROP TABLE #origWageRate + + CREATE TABLE #basisIDs (StaffingID INT); + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[Staffing] d WITH (READUNCOMMITTED) + WHERE d.EntityGroupConfigID = @EntityGroupConfigID + AND SubsectionID = 3 + AND FlexingTypeID = 7 -- Patient Activity + END + + SELECT + base.DepartmentID, base.EntityID, base.JobCodeID, base.PayCodeGroupID, base.EntityGroupConfigID, base.VariabilityID, + base.InitialBudgetDollars01, base.InitialBudgetDollars02, base.InitialBudgetDollars03, base.InitialBudgetDollars04, + base.InitialBudgetDollars05, base.InitialBudgetDollars06, base.InitialBudgetDollars07, base.InitialBudgetDollars08, + base.InitialBudgetDollars09, base.InitialBudgetDollars10, base.InitialBudgetDollars11, base.InitialBudgetDollars12 + INTO #flexDollars + FROM [fp].[Staffing] base + INNER JOIN #FilterByDepartment s ON s.DepartmentID = base.DepartmentID + WHERE base.VariabilityID = 2 + AND base.EntityGroupConfigID = @EntityGroupConfigID + AND base.SubsectionID = 3 + + SELECT + base.DepartmentID, base.EntityID, base.JobCodeID, base.PayCodeGroupID, base.EntityGroupConfigID, base.VariabilityID, + wr.InitialBudget01, wr.InitialBudget02, wr.InitialBudget03, wr.InitialBudget04, + wr.InitialBudget05, wr.InitialBudget06, wr.InitialBudget07, wr.InitialBudget08, + wr.InitialBudget09, wr.InitialBudget10, wr.InitialBudget11, wr.InitialBudget12 + INTO #origWageRate + FROM [fp].[Staffing] base + INNER JOIN #FilterByDepartment s ON s.DepartmentID = base.DepartmentID + INNER JOIN [fp].[StaffingWageRate] wr ON wr.StaffingWageRateID = base.StaffingWageRateID + WHERE base.VariabilityID = 2 + AND base.EntityGroupConfigID = @EntityGroupConfigID + AND base.SubsectionID = 3 + + UPDATE baseHours + SET + InitialBudgetHours01 = COALESCE(flexDollars.InitialBudgetDollars01 / NULLIF(origWageRate.InitialBudget01, 0), 0), + InitialBudgetHours02 = COALESCE(flexDollars.InitialBudgetDollars02 / NULLIF(origWageRate.InitialBudget02, 0), 0), + InitialBudgetHours03 = COALESCE(flexDollars.InitialBudgetDollars03 / NULLIF(origWageRate.InitialBudget03, 0), 0), + InitialBudgetHours04 = COALESCE(flexDollars.InitialBudgetDollars04 / NULLIF(origWageRate.InitialBudget04, 0), 0), + InitialBudgetHours05 = COALESCE(flexDollars.InitialBudgetDollars05 / NULLIF(origWageRate.InitialBudget05, 0), 0), + InitialBudgetHours06 = COALESCE(flexDollars.InitialBudgetDollars06 / NULLIF(origWageRate.InitialBudget06, 0), 0), + InitialBudgetHours07 = COALESCE(flexDollars.InitialBudgetDollars07 / NULLIF(origWageRate.InitialBudget07, 0), 0), + InitialBudgetHours08 = COALESCE(flexDollars.InitialBudgetDollars08 / NULLIF(origWageRate.InitialBudget08, 0), 0), + InitialBudgetHours09 = COALESCE(flexDollars.InitialBudgetDollars09 / NULLIF(origWageRate.InitialBudget09, 0), 0), + InitialBudgetHours10 = COALESCE(flexDollars.InitialBudgetDollars10 / NULLIF(origWageRate.InitialBudget10, 0), 0), + InitialBudgetHours11 = COALESCE(flexDollars.InitialBudgetDollars11 / NULLIF(origWageRate.InitialBudget11, 0), 0), + InitialBudgetHours12 = COALESCE(flexDollars.InitialBudgetDollars12 / NULLIF(origWageRate.InitialBudget12, 0), 0) + OUTPUT + INSERTED.StaffingID + INTO + #basisIDs (StaffingID) + FROM [fp].[Staffing] baseHours + INNER JOIN #FilterByDepartment s ON s.DepartmentID = baseHours.DepartmentID + LEFT JOIN #flexDollars flexDollars + ON flexDollars.DepartmentID = baseHours.DepartmentID + AND flexDollars.EntityID = baseHours.EntityID + AND flexDollars.JobCodeID = baseHours.JobCodeID + AND flexDollars.PayCodeGroupID = baseHours.PayCodeGroupID + AND flexDollars.EntityGroupConfigID = baseHours.EntityGroupConfigID + LEFT JOIN #origWageRate origWageRate + ON flexDollars.DepartmentID = origWageRate.DepartmentID + AND flexDollars.EntityID = origWageRate.EntityID + AND flexDollars.JobCodeID = origWageRate.JobCodeID + AND flexDollars.PayCodeGroupID = origWageRate.PayCodeGroupID + AND flexDollars.EntityGroupConfigID = origWageRate.EntityGroupConfigID + WHERE baseHours.EntityGroupConfigID = @EntityGroupConfigID + AND baseHours.VariabilityID = 2 + AND baseHours.FlexingTypeID = 7 -- Patient Activity + AND baseHours.SubsectionID = 3 + + SELECT StaffingID as BasisID from #basisIDs +GO + + +--------------------------------------------- + +-- fp.procABBFlexRecalcHours_Projection +/************************************************************************************************************************** +** Change History +************************************************************************************************************************** +** CID Date Author WI Description +** 1 07/22/22 MD JAZZ-38981 Initial +** 2 2023-10-31 MY JAZZ-61705 Support PAF for the new data model - Staffing +** 3 07/02/24 DM JAZZ-72920 Removed dependency for PercentAdjustmentFactor +*************************************************************************************************************************/ +CREATE PROC [fp].[procABBFlexRecalcHours_Projection] + @EntityGroupConfigID INT, + @MonthsLoaded INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#basisIDs') IS NOT NULL DROP TABLE #basisIDs + IF OBJECT_ID('tempdb..#flexDollars') IS NOT NULL DROP TABLE #flexDollars + IF OBJECT_ID('tempdb..#origWageRate') IS NOT NULL DROP TABLE #origWageRate + + CREATE TABLE #basisIDs (StaffingID INT); + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[Staffing] d WITH (READUNCOMMITTED) + where d.EntityGroupConfigID = @EntityGroupConfigID + END + + SELECT + base.DepartmentID, base.EntityID, base.JobCodeID, base.PayCodeGroupID, base.EntityGroupConfigID, base.VariabilityID, + base.ProjectionAdjustedDollars01, + base.ProjectionAdjustedDollars02, + base.ProjectionAdjustedDollars03, + base.ProjectionAdjustedDollars04, + base.ProjectionAdjustedDollars05, + base.ProjectionAdjustedDollars06, + base.ProjectionAdjustedDollars07, + base.ProjectionAdjustedDollars08, + base.ProjectionAdjustedDollars09, + base.ProjectionAdjustedDollars10, + base.ProjectionAdjustedDollars11, + base.ProjectionAdjustedDollars12 + INTO #flexDollars + FROM [fp].[Staffing] base + INNER JOIN #FilterByDepartment s ON s.DepartmentID = base.DepartmentID + WHERE base.VariabilityID = 2 + AND base.EntityGroupConfigID = @EntityGroupConfigID + + SELECT + base.DepartmentID, base.EntityID, base.JobCodeID, base.PayCodeGroupID, base.EntityGroupConfigID, base.VariabilityID, + wr.ProjectionAdjusted01, wr.ProjectionAdjusted02, wr.ProjectionAdjusted03, wr.ProjectionAdjusted04, + wr.ProjectionAdjusted05, wr.ProjectionAdjusted06, wr.ProjectionAdjusted07, wr.ProjectionAdjusted08, + wr.ProjectionAdjusted09, wr.ProjectionAdjusted10, wr.ProjectionAdjusted11, wr.ProjectionAdjusted12 + INTO #origWageRate + FROM [fp].[Staffing] base + INNER JOIN #FilterByDepartment s ON s.DepartmentID = base.DepartmentID + INNER JOIN [fp].[StaffingWageRate] wr ON base.StaffingWageRateID = wr.StaffingWageRateID + WHERE base.EntityGroupConfigID = @EntityGroupConfigID + AND base.VariabilityID = 2 + + UPDATE hours + SET + hours.ProjectionAdjustedHours01 = CASE WHEN @MonthsLoaded < 1 THEN COALESCE(flexDollars.ProjectionAdjustedDollars01 / NULLIF(origWageRate.ProjectionAdjusted01, 0), 0) ELSE hours.ProjectionAdjustedHours01 END, + hours.ProjectionAdjustedHours02 = CASE WHEN @MonthsLoaded < 2 THEN COALESCE(flexDollars.ProjectionAdjustedDollars02 / NULLIF(origWageRate.ProjectionAdjusted02, 0), 0) ELSE hours.ProjectionAdjustedHours02 END, + hours.ProjectionAdjustedHours03 = CASE WHEN @MonthsLoaded < 3 THEN COALESCE(flexDollars.ProjectionAdjustedDollars03 / NULLIF(origWageRate.ProjectionAdjusted03, 0), 0) ELSE hours.ProjectionAdjustedHours03 END, + hours.ProjectionAdjustedHours04 = CASE WHEN @MonthsLoaded < 4 THEN COALESCE(flexDollars.ProjectionAdjustedDollars04 / NULLIF(origWageRate.ProjectionAdjusted04, 0), 0) ELSE hours.ProjectionAdjustedHours04 END, + hours.ProjectionAdjustedHours05 = CASE WHEN @MonthsLoaded < 5 THEN COALESCE(flexDollars.ProjectionAdjustedDollars05 / NULLIF(origWageRate.ProjectionAdjusted05, 0), 0) ELSE hours.ProjectionAdjustedHours05 END, + hours.ProjectionAdjustedHours06 = CASE WHEN @MonthsLoaded < 6 THEN COALESCE(flexDollars.ProjectionAdjustedDollars06 / NULLIF(origWageRate.ProjectionAdjusted06, 0), 0) ELSE hours.ProjectionAdjustedHours06 END, + hours.ProjectionAdjustedHours07 = CASE WHEN @MonthsLoaded < 7 THEN COALESCE(flexDollars.ProjectionAdjustedDollars07 / NULLIF(origWageRate.ProjectionAdjusted07, 0), 0) ELSE hours.ProjectionAdjustedHours07 END, + hours.ProjectionAdjustedHours08 = CASE WHEN @MonthsLoaded < 8 THEN COALESCE(flexDollars.ProjectionAdjustedDollars08 / NULLIF(origWageRate.ProjectionAdjusted08, 0), 0) ELSE hours.ProjectionAdjustedHours08 END, + hours.ProjectionAdjustedHours09 = CASE WHEN @MonthsLoaded < 9 THEN COALESCE(flexDollars.ProjectionAdjustedDollars09 / NULLIF(origWageRate.ProjectionAdjusted09, 0), 0) ELSE hours.ProjectionAdjustedHours09 END, + hours.ProjectionAdjustedHours10 = CASE WHEN @MonthsLoaded < 10 THEN COALESCE(flexDollars.ProjectionAdjustedDollars10 / NULLIF(origWageRate.ProjectionAdjusted10, 0), 0) ELSE hours.ProjectionAdjustedHours10 END, + hours.ProjectionAdjustedHours11 = CASE WHEN @MonthsLoaded < 11 THEN COALESCE(flexDollars.ProjectionAdjustedDollars11 / NULLIF(origWageRate.ProjectionAdjusted11, 0), 0) ELSE hours.ProjectionAdjustedHours11 END, + hours.ProjectionAdjustedHours12 = CASE WHEN @MonthsLoaded < 12 THEN COALESCE(flexDollars.ProjectionAdjustedDollars12 / NULLIF(origWageRate.ProjectionAdjusted12, 0), 0) ELSE hours.ProjectionAdjustedHours12 END + OUTPUT + INSERTED.StaffingID + INTO + #basisIDs (StaffingID) + FROM [fp].[Staffing] hours + INNER JOIN #FilterByDepartment s ON s.DepartmentID = hours.DepartmentID + LEFT JOIN #flexDollars flexDollars + ON flexDollars.DepartmentID = hours.DepartmentID + AND flexDollars.EntityID = hours.EntityID + AND flexDollars.JobCodeID = hours.JobCodeID + AND flexDollars.PayCodeGroupID = hours.PayCodeGroupID + AND flexDollars.EntityGroupConfigID = hours.EntityGroupConfigID + LEFT JOIN #origWageRate origWageRate + ON flexDollars.DepartmentID = origWageRate.DepartmentID + AND flexDollars.EntityID = origWageRate.EntityID + AND flexDollars.JobCodeID = origWageRate.JobCodeID + AND flexDollars.PayCodeGroupID = origWageRate.PayCodeGroupID + AND flexDollars.EntityGroupConfigID = origWageRate.EntityGroupConfigID + WHERE hours.EntityGroupConfigID = @EntityGroupConfigID + AND hours.VariabilityID = 2 + AND hours.FlexingTypeID = 7 -- Patient Activity + + -- Return the data back so we can re-apply any percent adjustments and refresh the change history + SELECT StaffingID, m.FiscalMonthID, CAST(3 AS TINYINT) AS BudgetPhaseID, CAST(12 AS TINYINT) AS TimeClassID, CAST(51 AS TINYINT) AS UnitTypeID, f.Value + FROM ( + SELECT + proj.StaffingID, + proj.ProjectionAdjustedHours01, proj.ProjectionAdjustedHours02, proj.ProjectionAdjustedHours03, proj.ProjectionAdjustedHours04, + proj.ProjectionAdjustedHours05, proj.ProjectionAdjustedHours06, proj.ProjectionAdjustedHours07, proj.ProjectionAdjustedHours08, + proj.ProjectionAdjustedHours09, proj.ProjectionAdjustedHours10, proj.ProjectionAdjustedHours11, proj.ProjectionAdjustedHours12 + FROM #basisIDs ids + INNER JOIN [fp].[Staffing] proj ON ids.StaffingID = proj.StaffingID + ) gl + UNPIVOT ( Value FOR FiscalMonth IN (ProjectionAdjustedHours01, ProjectionAdjustedHours02, ProjectionAdjustedHours03, ProjectionAdjustedHours04, ProjectionAdjustedHours05, ProjectionAdjustedHours06, ProjectionAdjustedHours07, ProjectionAdjustedHours08, ProjectionAdjustedHours09, ProjectionAdjustedHours10, ProjectionAdjustedHours11, ProjectionAdjustedHours12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectionAdjustedHours', 'Month'); +GO + + +--------------------------------------------- + +-- fp.procABBMRFlexPostActions +CREATE PROCEDURE fp.procABBMRFlexPostActions + @MRYear int +AS +BEGIN + PRINT 'Running for FY' + CAST(@MRYear AS VARCHAR(1000)) +END +GO + + +--------------------------------------------- + +-- fp.procAPEngineTaskPreProcessingActions +CREATE PROCEDURE fp.procAPEngineTaskPreProcessingActions + AS + BEGIN + + SET NOCOUNT ON; + + /******************* PLEASE READ BEFORE UPDATING THIS PROC ****************** + + When adding to the proc, please do the following: + - Create a defect + - Create a migration updating this proc with the workaround + - When updating this migration, include the defect number and breif summary + + ****************************************************************************/ + + + END +GO + + +--------------------------------------------- + +-- fp.procAPIncomeStatementReportTurnOnFTECalculations +create proc [fp].[procAPIncomeStatementReportTurnOnFTECalculations] +as +BEGIN + if ((select VALUE from [fp].[SystemSetting] WHERE Name = 'Is APE Enabled') = 1) + begin + update frlineitem + SET Calculation = '[' + + (SELECT CAST(LineItemGUID as varchar(50)) FROM frlineitem WHERE FinancialReportingID = 589 and Statement = 'Stats') --Productive Hours + + ']/[' + + (SELECT CAST(LineItemGUID as varchar(50)) FROM frlineitem WHERE FinancialReportingID = 1015 and Statement = 'Stats')-- Stats - Other - Working Hours + + ']', + Type = 2 + WHERE FinancialReportingID = 591 and Statement = 'Stats' -- Stats - FTEs - Productive FTEs + + update frlineitem + SET Calculation = '[' + + (SELECT CAST(LineItemGUID as varchar(50)) FROM frlineitem WHERE FinancialReportingID = 590 and Statement = 'Stats') -- Stats- Hours + + ']/[' + + (SELECT CAST(LineItemGUID as varchar(50)) FROM frlineitem WHERE FinancialReportingID = 1015 and Statement = 'Stats')-- Stats - Other - Working Hours + + ']', + Type = 2 + + WHERE FinancialReportingID = 592 and Statement = 'Stats' -- Stats - FTEs - Non-Productive FTEs + + update frlineitem + SET Calculation = '[' + + (SELECT CAST(LineItemGUID as varchar(50)) FROM frlineitem WHERE FinancialReportingID = 2591 and Statement = 'Stats') -- Stats - Hours - GL Physician Hours + + ']/[' + + (SELECT CAST(LineItemGUID as varchar(50)) FROM frlineitem WHERE FinancialReportingID = 1015 and Statement = 'Stats')-- Stats - Other - Working Hours + + ']', + Type = 2 + WHERE FinancialReportingID = 1 and Statement = 'Stats' --Physician FTEs + + + update frlineitem + SET Calculation = '[' + + (SELECT CAST(LineItemGUID as varchar(50)) FROM frlineitem WHERE FinancialReportingID = 2590 and Statement = 'Stats') -- Stats - GL Hours + + ']/[' + + (SELECT CAST(LineItemGUID as varchar(50)) FROM frlineitem WHERE FinancialReportingID = 1015 and Statement = 'Stats')-- Stats - Other - Working Hours + + ']', + Type = 2 + WHERE FinancialReportingID = 2 and Statement = 'Stats'--Non-Physician Provider FTEs + end + ELSE + begin + update frlineitem + SET Calculation = '', + Type = 0 + WHERE FinancialReportingID = 592 and Statement = 'Stats'-- Stats - FTEs - Non-Productive FTEs + + update frlineitem + SET Calculation = '', + Type = 0 + WHERE FinancialReportingID = 591 and Statement = 'Stats' -- Stats - FTEs - Productive FTEs + + update frlineitem + SET Calculation = '', + Type = 0 + WHERE FinancialReportingID = 1 and Statement = 'Stats'--Physician FTEs + + + update frlineitem + SET Calculation = '', + Type = 0 + WHERE FinancialReportingID = 2 and Statement = 'Stats'--Non-Physician Provider FTEs + end +END +GO + + +--------------------------------------------- + +-- fp.procAPTempTableCleanupTask +CREATE PROCEDURE [fp].[procAPTempTableCleanupTask] +AS +BEGIN + +DECLARE @MyCursor CURSOR; +DECLARE @Name NVARCHAR(MAX); +BEGIN + SET @MyCursor = CURSOR FOR + SELECT CONCAT( 'DROP TABLE ','[tmp].[', name, ']') AS TempName FROM sys.tables + WHERE (name LIKE 'Staffing[_]%' OR name LIKE 'GeneralLedger[_]%') + AND SCHEMA_ID = SCHEMA_ID('tmp') + AND create_date <= GETDATE() - 1 + + OPEN @MyCursor + FETCH NEXT FROM @MyCursor + INTO @Name + + WHILE @@FETCH_STATUS = 0 + BEGIN + + + EXECUTE sp_executesql @Name; + + FETCH NEXT FROM @MyCursor + INTO @Name + END; + + CLOSE @MyCursor; + DEALLOCATE @MyCursor; +END; +END; +GO + + +--------------------------------------------- + +-- fp.procAddCategoryForSetting +CREATE PROCEDURE [fp].[procAddCategoryForSetting] + @CategoryName NVARCHAR(100), + @SettingName NVARCHAR(100) +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 10-18-2022 MY Felt Like it Initial Creation + *************************************************************/ + + DECLARE @CategoryID INT = (SELECT CategoryID FROM fp.DimCategory WHERE Category = @CategoryName) + + DECLARE @SystemSettingID INT = (SELECT SystemSettingID FROM fp.SystemSetting WHERE Name = @SettingName) + IF @SystemSettingID IS NOT NULL AND NOT EXISTS (SELECT 1 FROM [fp].[SettingCategory] WHERE SystemSettingID = @SystemSettingID AND CategoryID = @CategoryID) + BEGIN + INSERT INTO fp.SettingCategory (CategoryID, SystemSettingID) VALUES (@CategoryID, @SystemSettingID) + END + + SET @SystemSettingID = (SELECT SettingID FROM fp.BudgetConfigDefaultSetting WHERE Name = @SettingName) + IF @SystemSettingID IS NOT NULL AND NOT EXISTS (SELECT 1 FROM [fp].[SettingCategory] WHERE BudgetConfigDefaultSettingID = @SystemSettingID AND CategoryID = @CategoryID) + BEGIN + INSERT INTO fp.SettingCategory (CategoryID, BudgetConfigDefaultSettingID) VALUES (@CategoryID, @SystemSettingID) + END + +END +GO + + +--------------------------------------------- + +-- fp.procAddRosterEmployee +/************************************************************************************************************************* +** Change History +************************************************************************************************************************** +** CID Date Author WI Description +** 1 11/13/17 MY B-17923 Creates a Dummy Proc for Roster Changes +*************************************************************************************************************************/ +CREATE PROCEDURE fp.procAddRosterEmployee + @DepartmentID INT, + @JobCodeID INT, + @FTE DECIMAL(19,4), + @Salary DECIMAL(19,4), + @FiscalMonthID INT, + @FiscalYearID INT, + @Comment NVARCHAR(MAX) +AS +BEGIN + -- Enter Any Logic that is needed for after saving a Roster Adjustment + PRINT '' +END +GO + + +--------------------------------------------- + +-- fp.procAdjustmentImpactBatchCalculation +CREATE PROCEDURE [fp].[procAdjustmentImpactBatchCalculation] +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 08-17-2022 MY JAZZ-41983 Initial Creation + ** 2 03-20-2023 MY JAZZ-52181 New Structure + *************************************************************/ + + DECLARE @BudgetConfigID INT = (SELECT TOP 1 BudgetConfigID FROM fp.BudgetConfig WHERE IsActive = 1); -- Only the active config is used for these reports + DECLARE @RowLimit INT = ISNULL((SELECT Value FROM fp.SystemSetting WHERE Name = 'Row Limit for Adjustment Impact Report Batch'), 5000000); + + IF OBJECT_ID('tempdb..#mappingsByRowCount') IS NOT NULL DROP TABLE #mappingsByRowCount; + IF OBJECT_ID('tempdb..#currentBatch') IS NOT NULL DROP TABLE #currentBatch; + + SELECT EntityID, PatientClassID, MedicalSurgicalID, SUM(TotalRowCount) AS TotalRowCount + INTO #mappingsByRowCount + FROM ( + SELECT fcv.ServiceEntityID AS EntityID, fcv.PatientClassID, fcv.MedicalSurgicalID, COUNT(*) AS TotalRowCount + FROM fp.ChargeVolume fcv + WHERE BudgetConfigID = @BudgetConfigID + GROUP BY fcv.ServiceEntityID, fcv.PatientClassID, fcv.MedicalSurgicalID + UNION ALL + SELECT sle.EntityID, sle.PatientClassID, sle.MedicalSurgicalID, COUNT(*) AS TotalRowCount + FROM fp.ServiceLineEncounter sle + WHERE BudgetConfigID = @BudgetConfigID + GROUP BY sle.EntityID, sle.PatientClassID, sle.MedicalSurgicalID + ) dimensionality + GROUP BY EntityID, PatientClassID, MedicalSurgicalID + + CREATE TABLE #currentBatch ( + EntityID INT NOT NULL DEFAULT(0), + PatientClassID INT NOT NULL DEFAULT(0), + MedicalSurgicalID INT NOT NULL DEFAULT(0), + TotalRowCount INT NOT NULL DEFAULT(0) + ) + + TRUNCATE TABLE [fp].[AdjustmentImpactReportBatchConfiguration]; + + -- Yes it's cursor, I know it's bad, but I don't know how else to do it in SQL other than bringing it in code and doing it there, but + -- that seems silly just to avoid a cursor. This proc should only be run a handeful of times at best. Once initially and then anytime the batching + -- may need to be re-calc'd + DECLARE + @EntityID INT, + @PatientClassID INT, + @MedicalSurgicalID INT, + @RowCount INT, + @BatchNumber INT = 1, + @CurrentBatchRowCount INT = 0; + + DECLARE cursor_batches CURSOR + FOR SELECT EntityID, PatientClassID, MedicalSurgicalID, TotalRowCount FROM #mappingsByRowCount ORDER BY TotalRowCount; + + OPEN cursor_batches; + FETCH NEXT FROM cursor_batches INTO + @EntityID, + @PatientClassID, + @MedicalSurgicalID, + @RowCount; + + WHILE @@FETCH_STATUS = 0 + BEGIN + + IF (@CurrentBatchRowCount = 0) + BEGIN + + -- Add current batch to existing batch + INSERT INTO #currentBatch (EntityID, PatientClassID, MedicalSurgicalID, TotalRowCount) + SELECT @EntityID, @PatientClassID, @MedicalSurgicalID, @RowCount + + SET @CurrentBatchRowCount = @CurrentBatchRowCount + @RowCount; + + END ELSE BEGIN + + -- Need to cut off the current batch and start a new one + IF (@CurrentBatchRowCount > @RowLimit OR @CurrentBatchRowCount + @RowCount > @RowLimit) + BEGIN + INSERT INTO [fp].[AdjustmentImpactReportBatchConfiguration] (BatchID, EntityID, PatientClassID, MedicalSurgicalID, TotalRowCount) + SELECT @BatchNumber, EntityID, PatientClassID, MedicalSurgicalID, TotalRowCount + FROM #currentBatch + + TRUNCATE TABLE #currentBatch; + SET @BatchNumber = @BatchNumber + 1; + SET @CurrentBatchRowCount = 0; + END + + -- Add current batch to existing batch + INSERT INTO #currentBatch (EntityID, PatientClassID, MedicalSurgicalID, TotalRowCount) + SELECT @EntityID, @PatientClassID, @MedicalSurgicalID, @RowCount + + SET @CurrentBatchRowCount = @CurrentBatchRowCount + @RowCount; + + END + + FETCH NEXT FROM cursor_batches INTO + @EntityID, + @PatientClassID, + @MedicalSurgicalID, + @RowCount; + END; + + CLOSE cursor_batches; + DEALLOCATE cursor_batches; + + INSERT INTO [fp].[AdjustmentImpactReportBatchConfiguration] (BatchID, EntityID, PatientClassID, MedicalSurgicalID, TotalRowCount) + SELECT @BatchNumber, EntityID, PatientClassID, MedicalSurgicalID, TotalRowCount + FROM #currentBatch + +END +GO + + +--------------------------------------------- + +-- fp.procApplyVariabilityToStaffing +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-10-04 IP B-20922 Added using source dimensionality +** 2 2018-11-06 NL B-21035 Adding spreading (and renaming proc) +** 3 2018-12-12 NL D-07904 Removing FTEs from the Fix/Var apply, recalc after instead +** 4 2019-01-09 IP B-21757 Change Initial Projection Calculation - remaining testing and bugs fixing +** 5 2019-02-06 BK B-21763 Exclude designated productive classes from FTE calculation +** 6 2019-06-13 BK D-08548 Modify to use hours instead of days in year and exclude Dollars-Only hours +** 7 2019-08-12 BK D-08697 Performance enhancements +** 8 2019-08-13 MY X-XXXXX Update FTE calculation to calculate average, not / 12 +** 9 2019-08-19 BK B-24026 Performance enhancements +** 10 2019-10-21 BK X-XXXXX Fix issue when fiscal year <> projection year +** 11 2019-11-12 MY B-24221 Remove feature flag for wage rate stuff +** 12 2020-07-08 BK JAZZ-1796 Fix leap year average +** 13 2020-07-20 BK JAZZ-2117 Add Employee joins for EB +** 14 2020-08-05 LR JAZZ-1226 Added clean up for variable hours and FTEs with Fixed override +** 15 2020-11-02 BK JAZZ-8379 Add support for provider fields and update filtering logic +** 16 2021-02-17 MD JAZZ-14996 Added missing EmployeeID join on FTE update +** 17 2021-02-17 LR JAZZ-9006 Added missing variability IDs to UPDATE statement +** 18 2021-08-16 BK JAZZ-21272 Use cached variability table for cleaning up variable records +** 19 2022-04-29 MY JAZZ-28395 Cache Variability Percentage on FactStaffing +** 20 2022-10-04 MY JAZZ-37262 Remove Feature Flag 'Use Variability From FactStaffing Table' +** 21 2022-11-07 MY JAZZ-35951 Add EmployeeID to FactStaffingVariabilityDetail +** 22 2023-09-20 BK JAZZ-60973 Update for data restructure +** 23 2024-01-24 MY JAZZ-65733 Fix issue where the data wasn't getting rolled up above variability causing the data to not be re-split +** 24 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config +** 25 2024-02-08 MD JAZZ-66903 Add code changes from JAZZ-66611 - Fix projection months loaded being recalculated. Do not overwrite values +** 26 2024-02-20 BW JAZZ-66903 fix for provider InitialRate for variable is zeroed out +** 27 2024-06-14 SM JAZZ-71536 change JobCodeID from smallint to int +*************************************************************/ +CREATE PROCEDURE [fp].[procApplyVariabilityToStaffing] + @EntityGroupConfigID INT, + @FiscalYearID INT, + @MonthsLoaded INT, + @ProjectionFiscalYearID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + WITH RECOMPILE + AS + BEGIN + + SET NOCOUNT ON + + IF OBJECT_ID('tempdb..#FilteringTable') IS NOT NULL DROP TABLE #FilteringTable + IF OBJECT_ID('tempdb..#BudgetWorkingHours') IS NOT NULL DROP TABLE #BudgetWorkingHours + IF OBJECT_ID('tempdb..#preSpreadFixedVar') IS NOT NULL DROP TABLE #preSpreadFixedVar + IF OBJECT_ID('tempdb..#preSpreadFixedVarDollars') IS NOT NULL DROP TABLE #preSpreadFixedVarDollars + IF OBJECT_ID('tempdb..#spreadFixedVar') IS NOT NULL DROP TABLE #spreadFixedVar + IF OBJECT_ID('tempdb..#Totals') IS NOT NULL DROP TABLE #Totals + IF OBJECT_ID('tempdb..#fteTemp') IS NOT NULL DROP TABLE #fteTemp + IF OBJECT_ID('tempdb..#flatFteTemp') IS NOT NULL DROP TABLE #flatFteTemp + IF OBJECT_ID('tempdb..#MonthsLoadedTotal') IS NOT NULL DROP TABLE #MonthsLoadedTotal + IF OBJECT_ID('tempdb..#ProjectionWorkingHours') IS NOT NULL DROP TABLE #ProjectionWorkingHours + IF OBJECT_ID('tempdb..#ProjectionYTD') IS NOT NULL DROP TABLE #ProjectionYTD + IF OBJECT_ID('tempdb..#HoursAndWorkingHours') IS NOT NULL DROP TABLE #HoursAndWorkingHours + IF OBJECT_ID('tempdb..#DollarTotals') IS NOT NULL DROP TABLE #DollarTotals + IF OBJECT_ID('tempdb..#HoursForFteUpdate') IS NOT NULL DROP TABLE #HoursForFteUpdate + IF OBJECT_ID('tempdb..#Variability') IS NOT NULL DROP TABLE #Variability + IF OBJECT_ID('tempdb..#variableStaffingRecordsToCleanUp') IS NOT NULL DROP TABLE #variableStaffingRecordsToCleanUp + IF OBJECT_ID('tempdb..#combinedStaffingHoursAboveVariability') IS NOT NULL DROP TABLE #combinedStaffingHoursAboveVariability + IF OBJECT_ID('tempdb..#combinedStaffingDollarsAboveVariability') IS NOT NULL DROP TABLE #combinedStaffingDollarsAboveVariability + + CREATE TABLE #FilteringTable ( + DepartmentID INT + ,INDEX ix_1 NONCLUSTERED (DepartmentID) + ) + + INSERT INTO #FilteringTable (DepartmentID) + SELECT DepartmentID + FROM @SourceDimensionality + + DECLARE @EntityGroupConfigGUID UNIQUEIDENTIFIER; + SET @EntityGroupConfigGUID = (SELECT EntityGroupConfigGUID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID) + + DECLARE @isFilterPresent int = (SELECT COUNT(*) FROM #FilteringTable) + + IF (@isFilterPresent=0) BEGIN + INSERT INTO #FilteringTable (DepartmentID) + SELECT DISTINCT DepartmentID FROM fp.Staffing WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + DECLARE @IsProviderPlanningEnabled BIT + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled + FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID + WHERE EntityGroupConfigID = @EntityGroupConfigID; + + DECLARE @ProviderSubsectionID INT = 4; + DECLARE @StaffingSubsectionID INT = 3; + + DECLARE @SourceFiscalYearID int + DECLARE @SourceTimeClassID int + SELECT @SourceTimeClassID = PayrollTimeClassID, @SourceFiscalYearID = PayrollFiscalYearID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID + DECLARE @IsAnnualized BIT = (CASE WHEN @SourceFiscalYearID = @ProjectionFiscalYearID AND @SourceTimeClassID = 1 AND @MonthsLoaded < 12 THEN 1 ELSE 0 END) + + CREATE TABLE #Variability (DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, ProviderLineItemID INT, EmployeeID INT, FixedPercentage DECIMAL(38, 6)) + + INSERT INTO #Variability (DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID, FixedPercentage) + SELECT v.DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID, MAX(FixedPercentage) AS FixedPercentage + FROM [fp].[viewFactStaffingVariability] v + INNER JOIN #FilteringTable f ON v.DepartmentID = f.DepartmentID + WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID + GROUP BY v.DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID + + -- Pre spread values. Basically we need the fixed/variable split before we spread it evenly + CREATE TABLE #preSpreadFixedVar ( StaffingID int, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, EmployeeID INT, VariabilityID INT, ProductiveClassID INT, EntityGroupConfigID INT, + ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int, + InitialBudget01 DECIMAL(19,8), InitialBudget02 DECIMAL(19,8), InitialBudget03 DECIMAL(19,8), InitialBudget04 DECIMAL(19,8), + InitialBudget05 DECIMAL(19,8), InitialBudget06 DECIMAL(19,8), InitialBudget07 DECIMAL(19,8), InitialBudget08 DECIMAL(19,8), + InitialBudget09 DECIMAL(19,8), InitialBudget10 DECIMAL(19,8), InitialBudget11 DECIMAL(19,8), InitialBudget12 DECIMAL(19,8), + InitialBudgetTotal DECIMAL(19,8), + InitialProjection01 DECIMAL(19,8), InitialProjection02 DECIMAL(19,8), InitialProjection03 DECIMAL(19,8), InitialProjection04 DECIMAL(19,8), + InitialProjection05 DECIMAL(19,8), InitialProjection06 DECIMAL(19,8), InitialProjection07 DECIMAL(19,8), InitialProjection08 DECIMAL(19,8), + InitialProjection09 DECIMAL(19,8), InitialProjection10 DECIMAL(19,8), InitialProjection11 DECIMAL(19,8), InitialProjection12 DECIMAL(19,8), + InitialProjectionTotal DECIMAL(19,8), + INDEX ix_sfv_1 NONCLUSTERED (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID) + ) + -- we need this for projection dollars months loaded to be allocated to fixed/variable properly for when no hours exist but dollars do (jazz-66611) + CREATE TABLE #preSpreadFixedVarDollars ( StaffingID int, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, EmployeeID INT, VariabilityID INT, ProductiveClassID INT, EntityGroupConfigID INT, + ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int, + InitialProjection01 DECIMAL(19,8), InitialProjection02 DECIMAL(19,8), InitialProjection03 DECIMAL(19,8), InitialProjection04 DECIMAL(19,8), + InitialProjection05 DECIMAL(19,8), InitialProjection06 DECIMAL(19,8), InitialProjection07 DECIMAL(19,8), InitialProjection08 DECIMAL(19,8), + InitialProjection09 DECIMAL(19,8), InitialProjection10 DECIMAL(19,8), InitialProjection11 DECIMAL(19,8), InitialProjection12 DECIMAL(19,8) + INDEX ix_sfv_1 NONCLUSTERED (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID) + ) + + CREATE TABLE #spreadFixedVar ( StaffingID int, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, EmployeeID INT, VariabilityID INT, ProductiveClassID INT, EntityGroupConfigID INT, + ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int, + InitialBudget01 DECIMAL(19,8), InitialBudget02 DECIMAL(19,8), InitialBudget03 DECIMAL(19,8), InitialBudget04 DECIMAL(19,8), + InitialBudget05 DECIMAL(19,8), InitialBudget06 DECIMAL(19,8), InitialBudget07 DECIMAL(19,8), InitialBudget08 DECIMAL(19,8), + InitialBudget09 DECIMAL(19,8), InitialBudget10 DECIMAL(19,8), InitialBudget11 DECIMAL(19,8), InitialBudget12 DECIMAL(19,8), + InitialBudgetTotal DECIMAL(19,8), + InitialProjection01 DECIMAL(19,8), InitialProjection02 DECIMAL(19,8), InitialProjection03 DECIMAL(19,8), InitialProjection04 DECIMAL(19,8), + InitialProjection05 DECIMAL(19,8), InitialProjection06 DECIMAL(19,8), InitialProjection07 DECIMAL(19,8), InitialProjection08 DECIMAL(19,8), + InitialProjection09 DECIMAL(19,8), InitialProjection10 DECIMAL(19,8), InitialProjection11 DECIMAL(19,8), InitialProjection12 DECIMAL(19,8), + InitialProjectionTotal DECIMAL(19,8), + INDEX ix_sfv_1 NONCLUSTERED (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID) + ) + + -- We need to find the totals above Variability so we can resplit the data. + SELECT + fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, + SUM(fs.SampledBudgetHours01) AS SampledBudgetHours01, + SUM(fs.SampledBudgetHours02) AS SampledBudgetHours02, + SUM(fs.SampledBudgetHours03) AS SampledBudgetHours03, + SUM(fs.SampledBudgetHours04) AS SampledBudgetHours04, + SUM(fs.SampledBudgetHours05) AS SampledBudgetHours05, + SUM(fs.SampledBudgetHours06) AS SampledBudgetHours06, + SUM(fs.SampledBudgetHours07) AS SampledBudgetHours07, + SUM(fs.SampledBudgetHours08) AS SampledBudgetHours08, + SUM(fs.SampledBudgetHours09) AS SampledBudgetHours09, + SUM(fs.SampledBudgetHours10) AS SampledBudgetHours10, + SUM(fs.SampledBudgetHours11) AS SampledBudgetHours11, + SUM(fs.SampledBudgetHours12) AS SampledBudgetHours12, + SUM(fs.SampledBudgetHoursTotal) AS SampledBudgetHoursTotal, + SUM(fs.SampledProjectionHours01) AS SampledProjectionHours01, + SUM(fs.SampledProjectionHours02) AS SampledProjectionHours02, + SUM(fs.SampledProjectionHours03) AS SampledProjectionHours03, + SUM(fs.SampledProjectionHours04) AS SampledProjectionHours04, + SUM(fs.SampledProjectionHours05) AS SampledProjectionHours05, + SUM(fs.SampledProjectionHours06) AS SampledProjectionHours06, + SUM(fs.SampledProjectionHours07) AS SampledProjectionHours07, + SUM(fs.SampledProjectionHours08) AS SampledProjectionHours08, + SUM(fs.SampledProjectionHours09) AS SampledProjectionHours09, + SUM(fs.SampledProjectionHours10) AS SampledProjectionHours10, + SUM(fs.SampledProjectionHours11) AS SampledProjectionHours11, + SUM(fs.SampledProjectionHours12) AS SampledProjectionHours12 + INTO #combinedStaffingHoursAboveVariability + FROM [fp].[Staffing] fs + INNER JOIN #FilteringTable ft on (ft.DepartmentID = fs.DepartmentID ) + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND (@IsProviderPlanningEnabled = 0 OR SubsectionID <> @ProviderSubsectionID) -- exclude provider + GROUP BY fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, + fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID + + -- We need to find the totals above Variability so we can resplit the data. + SELECT + fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, + SUM(fs.SampledBudgetDollars01) AS SampledBudgetDollars01, + SUM(fs.SampledBudgetDollars02) AS SampledBudgetDollars02, + SUM(fs.SampledBudgetDollars03) AS SampledBudgetDollars03, + SUM(fs.SampledBudgetDollars04) AS SampledBudgetDollars04, + SUM(fs.SampledBudgetDollars05) AS SampledBudgetDollars05, + SUM(fs.SampledBudgetDollars06) AS SampledBudgetDollars06, + SUM(fs.SampledBudgetDollars07) AS SampledBudgetDollars07, + SUM(fs.SampledBudgetDollars08) AS SampledBudgetDollars08, + SUM(fs.SampledBudgetDollars09) AS SampledBudgetDollars09, + SUM(fs.SampledBudgetDollars10) AS SampledBudgetDollars10, + SUM(fs.SampledBudgetDollars11) AS SampledBudgetDollars11, + SUM(fs.SampledBudgetDollars12) AS SampledBudgetDollars12, + SUM(fs.SampledBudgetDollarsTotal) AS SampledBudgetDollarsTotal, + SUM(fs.SampledProjectionDollars01) AS SampledProjectionDollars01, + SUM(fs.SampledProjectionDollars02) AS SampledProjectionDollars02, + SUM(fs.SampledProjectionDollars03) AS SampledProjectionDollars03, + SUM(fs.SampledProjectionDollars04) AS SampledProjectionDollars04, + SUM(fs.SampledProjectionDollars05) AS SampledProjectionDollars05, + SUM(fs.SampledProjectionDollars06) AS SampledProjectionDollars06, + SUM(fs.SampledProjectionDollars07) AS SampledProjectionDollars07, + SUM(fs.SampledProjectionDollars08) AS SampledProjectionDollars08, + SUM(fs.SampledProjectionDollars09) AS SampledProjectionDollars09, + SUM(fs.SampledProjectionDollars10) AS SampledProjectionDollars10, + SUM(fs.SampledProjectionDollars11) AS SampledProjectionDollars11, + SUM(fs.SampledProjectionDollars12) AS SampledProjectionDollars12 + INTO #combinedStaffingDollarsAboveVariability + FROM [fp].[Staffing] fs + INNER JOIN #FilteringTable ft on (ft.DepartmentID = fs.DepartmentID ) + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND (@IsProviderPlanningEnabled = 0 OR SubsectionID <> @ProviderSubsectionID) -- exclude provider + GROUP BY fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, + fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID + + INSERT INTO #preSpreadFixedVar (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, VariabilityID, ProductiveClassID, EntityGroupConfigID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, + InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, InitialBudgetTotal, + InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12) + SELECT + fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.VariabilityID, fs.ProductiveClassID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours01) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours01) END as InitialBudgetHours01, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours02) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours02) END as InitialBudgetHours02, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours03) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours03) END as InitialBudgetHours03, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours04) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours04) END as InitialBudgetHours04, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours05) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours05) END as InitialBudgetHours05, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours06) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours06) END as InitialBudgetHours06, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours07) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours07) END as InitialBudgetHours07, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours08) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours08) END as InitialBudgetHours08, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours09) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours09) END as InitialBudgetHours09, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours10) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours10) END as InitialBudgetHours10, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours11) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours11) END as InitialBudgetHours11, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours12) END as InitialBudgetHours12, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHoursTotal) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHoursTotal) END as InitialBudgetHoursTotal, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours01 END SampledProjectionHours01, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours02 END SampledProjectionHours02, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours03 END SampledProjectionHours03, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours04 END SampledProjectionHours04, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours05 END SampledProjectionHours05, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours06 END SampledProjectionHours06, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours07 END SampledProjectionHours07, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours08 END SampledProjectionHours08, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours09 END SampledProjectionHours09, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours10 END SampledProjectionHours10, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours11 END SampledProjectionHours11, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours12 END SampledProjectionHours12 + FROM [fp].[Staffing] fs + INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID + INNER JOIN #combinedStaffingHoursAboveVariability total ON + fs.DepartmentID = total.DepartmentID + AND fs.JobCodeID = total.JobCodeID + AND fs.PayCodeGroupID = total.PayCodeGroupID + AND fs.EmployeeID = total.EmployeeID + AND fs.ProductiveClassID = total.ProductiveClassID + AND fs.EntityGroupConfigID = total.EntityGroupConfigID + AND fs.ProviderID = total.ProviderID + AND fs.ProviderTypeID = total.ProviderTypeID + AND fs.ProviderSpecialtyID = total.ProviderSpecialtyID + AND fs.ProviderLineItemID = total.ProviderLineItemID + AND fs.SubsectionID = total.SubsectionID + LEFT JOIN #Variability fv + ON fv.DepartmentID = fs.DepartmentID + AND fv.JobCodeID = fs.JobCodeID + AND fv.PayCodeGroupID = fs.PayCodeGroupID + AND fv.ProviderLineItemID = fs.ProviderLineItemID + AND fv.EmployeeID = fs.EmployeeID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID <> @ProviderSubsectionID) -- exclude provider + + INSERT INTO #preSpreadFixedVarDollars (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, VariabilityID, ProductiveClassID, EntityGroupConfigID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, + InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12) + SELECT + fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.VariabilityID, fs.ProductiveClassID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars01 END SampledProjectionDollars01, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars02 END SampledProjectionDollars02, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars03 END SampledProjectionDollars03, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars04 END SampledProjectionDollars04, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars05 END SampledProjectionDollars05, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars06 END SampledProjectionDollars06, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars07 END SampledProjectionDollars07, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars08 END SampledProjectionDollars08, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars09 END SampledProjectionDollars09, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars10 END SampledProjectionDollars10, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars11 END SampledProjectionDollars11, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars12 END SampledProjectionDollars12 + FROM [fp].[Staffing] fs + INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID + INNER JOIN #combinedStaffingDollarsAboveVariability total ON + fs.DepartmentID = total.DepartmentID + AND fs.JobCodeID = total.JobCodeID + AND fs.PayCodeGroupID = total.PayCodeGroupID + AND fs.EmployeeID = total.EmployeeID + AND fs.ProductiveClassID = total.ProductiveClassID + AND fs.EntityGroupConfigID = total.EntityGroupConfigID + AND fs.ProviderID = total.ProviderID + AND fs.ProviderTypeID = total.ProviderTypeID + AND fs.ProviderSpecialtyID = total.ProviderSpecialtyID + AND fs.ProviderLineItemID = total.ProviderLineItemID + AND fs.SubsectionID = total.SubsectionID + LEFT JOIN #Variability fv + ON fv.DepartmentID = fs.DepartmentID + AND fv.JobCodeID = fs.JobCodeID + AND fv.PayCodeGroupID = fs.PayCodeGroupID + AND fv.ProviderLineItemID = fs.ProviderLineItemID + AND fv.EmployeeID = fs.EmployeeID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID <> @ProviderSubsectionID) -- exclude provider + + -- We no longer need this after splitting out the hours + IF OBJECT_ID('tempdb..#combinedStaffingHoursAboveVariability') IS NOT NULL DROP TABLE #combinedStaffingHoursAboveVariability + + INSERT INTO #spreadFixedVar (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, VariabilityID, ProductiveClassID, EntityGroupConfigID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, + InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, + InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12) + SELECT + StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, VariabilityID, ProductiveClassID, EntityGroupConfigID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, + InitialBudget01 / 12, + InitialBudget02 / 12, + InitialBudget03 / 12, + InitialBudget04 / 12, + InitialBudget05 / 12, + InitialBudget06 / 12, + InitialBudget07 / 12, + InitialBudget08 / 12, + InitialBudget09 / 12, + InitialBudget10 / 12, + InitialBudget11 / 12, + InitialBudgetTotal = InitialBudgetTotal - (InitialBudget01 / 12 + InitialBudget02 / 12 + InitialBudget03 / 12 + InitialBudget04 / 12 + InitialBudget05 / 12 + InitialBudget06 / 12 + + InitialBudget07 / 12 + InitialBudget08 / 12 + InitialBudget09 / 12 + InitialBudget10 / 12 + InitialBudget11 / 12), + InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12 + FROM #preSpreadFixedVar + + UPDATE a + SET + InitialBudgetTotal = InitialBudget01 + InitialBudget02 + InitialBudget03 + InitialBudget04 + InitialBudget05 + InitialBudget06 + InitialBudget07 + InitialBudget08 + InitialBudget09 + InitialBudget10 + InitialBudget11 + InitialBudget12, + InitialProjectionTotal = InitialProjection01 + InitialProjection02 + InitialProjection03 + InitialProjection04 + InitialProjection05 + InitialProjection06 + InitialProjection07 + InitialProjection08 + InitialProjection09 + InitialProjection10 + InitialProjection11 + InitialProjection12 + FROM #spreadFixedVar a + + SELECT fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, fs.VariabilityID, + Month01, Month02, Month03, Month04, + Month05, Month06, Month07, Month08, + Month09, Month10, Month11, Month12, MonthYearly -- Jazz-1796 + INTO #BudgetWorkingHours + FROM [fp].[Staffing] fs + INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID + INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @FiscalYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND (@IsProviderPlanningEnabled = 0 OR SubsectionID <> @ProviderSubsectionID) -- exclude provider + + + SELECT fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, fs.VariabilityID, + pwh.Month01, pwh.Month02, pwh.Month03, pwh.Month04, + pwh.Month05, pwh.Month06, pwh.Month07, pwh.Month08, + pwh.Month09, pwh.Month10, pwh.Month11, pwh.Month12, pwh.MonthYearly -- Jazz-1796 + INTO #ProjectionWorkingHours + FROM #BudgetWorkingHours fs + INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] pwh on pwh.FiscalYearID = @ProjectionFiscalYearID and pwh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + + + SELECT fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, ytd.YTDHours + INTO #ProjectionYTD + FROM #ProjectionWorkingHours fs + INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID + INNER JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] ytd on ytd.FiscalYearID = @ProjectionFiscalYearID and ytd.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.SortOrder = @MonthsLoaded AND ytd.FiscalMonthID = fm.FiscalMonthID + + CREATE TABLE #HoursAndWorkingHours ( StaffingID INT, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, EmployeeID INT, EntityGroupConfigID INT, VariabilityID INT, + ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int, + InitialBudget01 DECIMAL(19,8), InitialBudget02 DECIMAL(19,8), InitialBudget03 DECIMAL(19,8), InitialBudget04 DECIMAL(19,8), + InitialBudget05 DECIMAL(19,8), InitialBudget06 DECIMAL(19,8), InitialBudget07 DECIMAL(19,8), InitialBudget08 DECIMAL(19,8), + InitialBudget09 DECIMAL(19,8), InitialBudget10 DECIMAL(19,8), InitialBudget11 DECIMAL(19,8), InitialBudget12 DECIMAL(19,8), + InitialBudgetTotal DECIMAL(19,8), + Month01 DECIMAL(19,8), Month02 DECIMAL(19,8), Month03 DECIMAL(19,8), Month04 DECIMAL(19,8), + Month05 DECIMAL(19,8), Month06 DECIMAL(19,8), Month07 DECIMAL(19,8), Month08 DECIMAL(19,8), + Month09 DECIMAL(19,8), Month10 DECIMAL(19,8), Month11 DECIMAL(19,8), Month12 DECIMAL(19,8), TotalWorkingHours DECIMAL(19,8), -- Jazz-1796 + INDEX ix_sfv_1 NONCLUSTERED (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID) + ) + + INSERT INTO #HoursAndWorkingHours (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, EntityGroupConfigID, VariabilityID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, + InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, + InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, + InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, + InitialBudgetTotal, + Month01, Month02, Month03, Month04, + Month05, Month06, Month07, Month08, + Month09, Month10, Month11, Month12, TotalWorkingHours) + SELECT h.StaffingID, h.DepartmentID, h.JobCodeID, h.PayCodeGroupID, h.EmployeeID, h.EntityGroupConfigID, h.VariabilityID, h.ProviderID, h.ProviderTypeID, h.ProviderSpecialtyID, h.ProviderLineItemID, h.SubsectionID, + h.InitialBudget01, h.InitialBudget02, h.InitialBudget03, h.InitialBudget04, h.InitialBudget05, h.InitialBudget06, h.InitialBudget07, h.InitialBudget08, h.InitialBudget09, h.InitialBudget10, h.InitialBudget11 , h.InitialBudget12, + h.InitialBudgetTotal, + wh.Month01, wh.Month02, wh.Month03, wh.Month04, wh.Month05, wh.Month06, wh.Month07, wh.Month08, wh.Month09, wh.Month10, wh.Month11 , wh.Month12, wh.MonthYearly -- Jazz-1796 + FROM #preSpreadFixedVar h -- We need the pre-spread here because we'll use the YTD hours later + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on h.PayCodeGroupID = exc.PayCodeGroupID + INNER JOIN #BudgetWorkingHours wh on h.StaffingID = wh.StaffingID + WHERE h.EntityGroupConfigID = @EntityGroupConfigID AND (h.VariabilityID = 1 OR exc.PayCodeGroupID IS NOT NULL) + + CREATE TABLE #flatFteTemp (StaffingID INT, AverageFTE DECIMAL(19,8)) + + -- budget ------------------------------------------------------------------------------------------------ + -- spread hours so that FTEs remain flat for fixed job codes + -- figure out ftes... + + INSERT INTO #flatFteTemp + SELECT h.StaffingID, + (h.InitialBudget01 / h.TotalWorkingHours) + + (h.InitialBudget02 / h.TotalWorkingHours) + + (h.InitialBudget03 / h.TotalWorkingHours) + + (h.InitialBudget04 / h.TotalWorkingHours) + + (h.InitialBudget05 / h.TotalWorkingHours) + + (h.InitialBudget06 / h.TotalWorkingHours) + + (h.InitialBudget07 / h.TotalWorkingHours) + + (h.InitialBudget08 / h.TotalWorkingHours) + + (h.InitialBudget09 / h.TotalWorkingHours) + + (h.InitialBudget10 / h.TotalWorkingHours) + + (h.InitialBudget11 / h.TotalWorkingHours) + + (h.InitialBudget12 / h.TotalWorkingHours) AS AverageFTE --Use a weighted average, not a straight average + FROM #HoursAndWorkingHours h + + + -- now back into hours + UPDATE + fs + SET + InitialBudgetHours01 = AverageFTE * wh.Month01, + InitialBudgetHours02 = AverageFTE * wh.Month02, + InitialBudgetHours03 = AverageFTE * wh.Month03, + InitialBudgetHours04 = AverageFTE * wh.Month04, + InitialBudgetHours05 = AverageFTE * wh.Month05, + InitialBudgetHours06 = AverageFTE * wh.Month06, + InitialBudgetHours07 = AverageFTE * wh.Month07, + InitialBudgetHours08 = AverageFTE * wh.Month08, + InitialBudgetHours09 = AverageFTE * wh.Month09, + InitialBudgetHours10 = AverageFTE * wh.Month10, + InitialBudgetHours11 = AverageFTE * wh.Month11, + InitialBudgetHours12 = AverageFTE * wh.Month12 + FROM [fp].[Staffing] fs + INNER JOIN #flatFteTemp fte ON fs.StaffingID = fte.StaffingID + INNER JOIN #BudgetWorkingHours wh on fs.StaffingID = wh.StaffingID + + -- update the initial values to be equal to the sampled values for variable job codes + UPDATE + fs + SET + fs.InitialBudgetHours01 = fv.InitialBudgetTotal / 12, + fs.InitialBudgetHours02 = fv.InitialBudgetTotal / 12, + fs.InitialBudgetHours03 = fv.InitialBudgetTotal / 12, + fs.InitialBudgetHours04 = fv.InitialBudgetTotal / 12, + fs.InitialBudgetHours05 = fv.InitialBudgetTotal / 12, + fs.InitialBudgetHours06 = fv.InitialBudgetTotal / 12, + fs.InitialBudgetHours07 = fv.InitialBudgetTotal / 12, + fs.InitialBudgetHours08 = fv.InitialBudgetTotal / 12, + fs.InitialBudgetHours09 = fv.InitialBudgetTotal / 12, + fs.InitialBudgetHours10 = fv.InitialBudgetTotal / 12, + fs.InitialBudgetHours11 = fv.InitialBudgetTotal / 12, + fs.InitialBudgetHours12 = fv.InitialBudgetTotal / 12 + FROM [fp].[Staffing] fs + INNER JOIN #spreadFixedVar fv on fs.StaffingID = fv.StaffingID + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fs.PayCodeGroupID = exc.PayCodeGroupID + WHERE fs.VariabilityID = 2 + AND exc.PayCodeGroupID IS NULL + + -- projection hours and FTEs ------------------------------------------------------------------------------------------------ + SELECT fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.EmployeeID, fs.VariabilityID, + CASE + WHEN @MonthsLoaded = 12 THEN InitialProjection01 + InitialProjection02 + InitialProjection03 + InitialProjection04 + InitialProjection05 + InitialProjection06 + InitialProjection07 + InitialProjection08 + InitialProjection09 + InitialProjection10 + InitialProjection11 + InitialProjection12 + WHEN @MonthsLoaded >= 11 THEN InitialProjection01 + InitialProjection02 + InitialProjection03 + InitialProjection04 + InitialProjection05 + InitialProjection06 + InitialProjection07 + InitialProjection08 + InitialProjection09 + InitialProjection10 + InitialProjection11 + WHEN @MonthsLoaded >= 10 THEN InitialProjection01 + InitialProjection02 + InitialProjection03 + InitialProjection04 + InitialProjection05 + InitialProjection06 + InitialProjection07 + InitialProjection08 + InitialProjection09 + InitialProjection10 + WHEN @MonthsLoaded >= 9 THEN InitialProjection01 + InitialProjection02 + InitialProjection03 + InitialProjection04 + InitialProjection05 + InitialProjection06 + InitialProjection07 + InitialProjection08 + InitialProjection09 + WHEN @MonthsLoaded >= 8 THEN InitialProjection01 + InitialProjection02 + InitialProjection03 + InitialProjection04 + InitialProjection05 + InitialProjection06 + InitialProjection07 + InitialProjection08 + WHEN @MonthsLoaded >= 7 THEN InitialProjection01 + InitialProjection02 + InitialProjection03 + InitialProjection04 + InitialProjection05 + InitialProjection06 + InitialProjection07 + WHEN @MonthsLoaded >= 6 THEN InitialProjection01 + InitialProjection02 + InitialProjection03 + InitialProjection04 + InitialProjection05 + InitialProjection06 + WHEN @MonthsLoaded >= 5 THEN InitialProjection01 + InitialProjection02 + InitialProjection03 + InitialProjection04 + InitialProjection05 + WHEN @MonthsLoaded >= 4 THEN InitialProjection01 + InitialProjection02 + InitialProjection03 + InitialProjection04 + WHEN @MonthsLoaded >= 3 THEN InitialProjection01 + InitialProjection02 + InitialProjection03 + WHEN @MonthsLoaded >= 2 THEN InitialProjection01 + InitialProjection02 + ELSE InitialProjection01 + END AS SampledProjectionTotal + INTO #MonthsLoadedTotal + FROM #spreadFixedVar fs + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + + -- spread hours so that FTEs remain flat for fixed job codes + -- figure out ftes... + SELECT h.StaffingID, + mnlt.SampledProjectionTotal / ytd.YTDHours AS AverageFTE + INTO #fteTemp + FROM [fp].[Staffing] h + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on h.PayCodeGroupID = exc.PayCodeGroupID + INNER JOIN #MonthsLoadedTotal mnlt on h.StaffingID = mnlt.StaffingID + INNER JOIN #ProjectionYTD ytd on ytd.StaffingID = h.StaffingID + WHERE h.EntityGroupConfigID = @EntityGroupConfigID AND (exc.PayCodeGroupID IS NOT NULL OR h.VariabilityID = 1) + + -- Projected hours should vary by working hours for fixed JobCodes + UPDATE + fs + SET + InitialProjectionHours01 = CASE WHEN @MonthsLoaded >= 1 THEN psfv.InitialProjection01 ELSE AverageFTE * wh.Month01 END, + InitialProjectionHours02 = CASE WHEN @MonthsLoaded >= 2 THEN psfv.InitialProjection02 ELSE AverageFTE * wh.Month02 END, + InitialProjectionHours03 = CASE WHEN @MonthsLoaded >= 3 THEN psfv.InitialProjection03 ELSE AverageFTE * wh.Month03 END, + InitialProjectionHours04 = CASE WHEN @MonthsLoaded >= 4 THEN psfv.InitialProjection04 ELSE AverageFTE * wh.Month04 END, + InitialProjectionHours05 = CASE WHEN @MonthsLoaded >= 5 THEN psfv.InitialProjection05 ELSE AverageFTE * wh.Month05 END, + InitialProjectionHours06 = CASE WHEN @MonthsLoaded >= 6 THEN psfv.InitialProjection06 ELSE AverageFTE * wh.Month06 END, + InitialProjectionHours07 = CASE WHEN @MonthsLoaded >= 7 THEN psfv.InitialProjection07 ELSE AverageFTE * wh.Month07 END, + InitialProjectionHours08 = CASE WHEN @MonthsLoaded >= 8 THEN psfv.InitialProjection08 ELSE AverageFTE * wh.Month08 END, + InitialProjectionHours09 = CASE WHEN @MonthsLoaded >= 9 THEN psfv.InitialProjection09 ELSE AverageFTE * wh.Month09 END, + InitialProjectionHours10 = CASE WHEN @MonthsLoaded >= 10 THEN psfv.InitialProjection10 ELSE AverageFTE * wh.Month10 END, + InitialProjectionHours11 = CASE WHEN @MonthsLoaded >= 11 THEN psfv.InitialProjection11 ELSE AverageFTE * wh.Month11 END, + InitialProjectionHours12 = CASE WHEN @MonthsLoaded >= 12 THEN psfv.InitialProjection12 ELSE AverageFTE * wh.Month12 END + FROM [fp].[Staffing] fs + INNER JOIN #spreadFixedVar sfv on fs.StaffingID = sfv.StaffingID + INNER JOIN #preSpreadFixedVar psfv on fs.StaffingID = psfv.StaffingID -- we need this because we need the actual values for months loaded projection unfortunately + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fs.PayCodeGroupID = exc.PayCodeGroupID + INNER JOIN #fteTemp fte ON fte.StaffingID = fs.StaffingID + INNER JOIN #ProjectionWorkingHours wh on wh.StaffingID = fs.StaffingID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND (exc.PayCodeGroupID IS NOT NULL OR fs.VariabilityID = 1) + + -- Projected hours should be flat for variable Job Codes or PayCodeGroups that have ProductiveClass that is excluded from FTE calcs + UPDATE + fs + SET + InitialProjectionHours01 = CASE WHEN @MonthsLoaded >= 1 THEN psfv.InitialProjection01 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours02 = CASE WHEN @MonthsLoaded >= 2 THEN psfv.InitialProjection02 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours03 = CASE WHEN @MonthsLoaded >= 3 THEN psfv.InitialProjection03 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours04 = CASE WHEN @MonthsLoaded >= 4 THEN psfv.InitialProjection04 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours05 = CASE WHEN @MonthsLoaded >= 5 THEN psfv.InitialProjection05 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours06 = CASE WHEN @MonthsLoaded >= 6 THEN psfv.InitialProjection06 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours07 = CASE WHEN @MonthsLoaded >= 7 THEN psfv.InitialProjection07 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours08 = CASE WHEN @MonthsLoaded >= 8 THEN psfv.InitialProjection08 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours09 = CASE WHEN @MonthsLoaded >= 9 THEN psfv.InitialProjection09 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours10 = CASE WHEN @MonthsLoaded >= 10 THEN psfv.InitialProjection10 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours11 = CASE WHEN @MonthsLoaded >= 11 THEN psfv.InitialProjection11 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours12 = CASE WHEN @MonthsLoaded >= 12 THEN psfv.InitialProjection12 ELSE (sfv.InitialProjectionTotal - t.SampledProjectionTotal) / (12.0 - @MonthsLoaded) END + FROM [fp].[Staffing] fs INNER JOIN #MonthsLoadedTotal t on fs.StaffingID = t.StaffingID + INNER JOIN #spreadFixedVar sfv on fs.StaffingID = sfv.StaffingID + INNER JOIN #preSpreadFixedVar psfv on fs.StaffingID = psfv.StaffingID -- we need this because we need the actual values for months loaded projection unfortunately + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fs.PayCodeGroupID = exc.PayCodeGroupID + WHERE fs.VariabilityID = 2 + AND exc.PayCodeGroupID IS NULL + + -- update FTEs -- all hours should have been spread properly now, so FTEs should be simply hours / working hours + -- JAZZ-14996 - Added missing EmployeeID join on FTE update + UPDATE fte SET + fte.InitialBudgetFTEs01 = fte.InitialBudgetHours01 / h.Month01, + fte.InitialBudgetFTEs02 = fte.InitialBudgetHours02 / h.Month02, + fte.InitialBudgetFTEs03 = fte.InitialBudgetHours03 / h.Month03, + fte.InitialBudgetFTEs04 = fte.InitialBudgetHours04 / h.Month04, + fte.InitialBudgetFTEs05 = fte.InitialBudgetHours05 / h.Month05, + fte.InitialBudgetFTEs06 = fte.InitialBudgetHours06 / h.Month06, + fte.InitialBudgetFTEs07 = fte.InitialBudgetHours07 / h.Month07, + fte.InitialBudgetFTEs08 = fte.InitialBudgetHours08 / h.Month08, + fte.InitialBudgetFTEs09 = fte.InitialBudgetHours09 / h.Month09, + fte.InitialBudgetFTEs10 = fte.InitialBudgetHours10 / h.Month10, + fte.InitialBudgetFTEs11 = fte.InitialBudgetHours11 / h.Month11, + fte.InitialBudgetFTEs12 = fte.InitialBudgetHours12 / h.Month12, + fte.InitialProjectionFTEs01 = fte.InitialProjectionHours01 / pwh.Month01, + fte.InitialProjectionFTEs02 = fte.InitialProjectionHours02 / pwh.Month02, + fte.InitialProjectionFTEs03 = fte.InitialProjectionHours03 / pwh.Month03, + fte.InitialProjectionFTEs04 = fte.InitialProjectionHours04 / pwh.Month04, + fte.InitialProjectionFTEs05 = fte.InitialProjectionHours05 / pwh.Month05, + fte.InitialProjectionFTEs06 = fte.InitialProjectionHours06 / pwh.Month06, + fte.InitialProjectionFTEs07 = fte.InitialProjectionHours07 / pwh.Month07, + fte.InitialProjectionFTEs08 = fte.InitialProjectionHours08 / pwh.Month08, + fte.InitialProjectionFTEs09 = fte.InitialProjectionHours09 / pwh.Month09, + fte.InitialProjectionFTEs10 = fte.InitialProjectionHours10 / pwh.Month10, + fte.InitialProjectionFTEs11 = fte.InitialProjectionHours11 / pwh.Month11, + fte.InitialProjectionFTEs12 = fte.InitialProjectionHours12 / pwh.Month12 + FROM [fp].[Staffing] fte + INNER JOIN #BudgetWorkingHours h ON h.StaffingID = fte.StaffingID -- we can use StaffingID now instead of all the dimensionality since it's the same row + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc ON h.PayCodeGroupID = exc.PayCodeGroupID + INNER JOIN #ProjectionWorkingHours pwh ON pwh.StaffingID = fte.StaffingID + WHERE fte.EntityGroupConfigID = @EntityGroupConfigID + AND exc.PayCodeGroupID IS NULL + + + ------ Dollars ---------------------------------------------------- + UPDATE + fs + SET + fs.InitialBudgetDollars01 = fs.InitialBudgetHours01 * wr.InitialBudget01, + fs.InitialBudgetDollars02 = fs.InitialBudgetHours02 * wr.InitialBudget02, + fs.InitialBudgetDollars03 = fs.InitialBudgetHours03 * wr.InitialBudget03, + fs.InitialBudgetDollars04 = fs.InitialBudgetHours04 * wr.InitialBudget04, + fs.InitialBudgetDollars05 = fs.InitialBudgetHours05 * wr.InitialBudget05, + fs.InitialBudgetDollars06 = fs.InitialBudgetHours06 * wr.InitialBudget06, + fs.InitialBudgetDollars07 = fs.InitialBudgetHours07 * wr.InitialBudget07, + fs.InitialBudgetDollars08 = fs.InitialBudgetHours08 * wr.InitialBudget08, + fs.InitialBudgetDollars09 = fs.InitialBudgetHours09 * wr.InitialBudget09, + fs.InitialBudgetDollars10 = fs.InitialBudgetHours10 * wr.InitialBudget10, + fs.InitialBudgetDollars11 = fs.InitialBudgetHours11 * wr.InitialBudget11, + fs.InitialBudgetDollars12 = fs.InitialBudgetHours12 * wr.InitialBudget12, + fs.InitialProjectionDollars01 = CASE WHEN @MonthsLoaded >= 1 THEN psfv.InitialProjection01 ELSE fs.InitialProjectionHours01 * wr.InitialProjection01 END, + fs.InitialProjectionDollars02 = CASE WHEN @MonthsLoaded >= 2 THEN psfv.InitialProjection02 ELSE fs.InitialProjectionHours02 * wr.InitialProjection02 END, + fs.InitialProjectionDollars03 = CASE WHEN @MonthsLoaded >= 3 THEN psfv.InitialProjection03 ELSE fs.InitialProjectionHours03 * wr.InitialProjection03 END, + fs.InitialProjectionDollars04 = CASE WHEN @MonthsLoaded >= 4 THEN psfv.InitialProjection04 ELSE fs.InitialProjectionHours04 * wr.InitialProjection04 END, + fs.InitialProjectionDollars05 = CASE WHEN @MonthsLoaded >= 5 THEN psfv.InitialProjection05 ELSE fs.InitialProjectionHours05 * wr.InitialProjection05 END, + fs.InitialProjectionDollars06 = CASE WHEN @MonthsLoaded >= 6 THEN psfv.InitialProjection06 ELSE fs.InitialProjectionHours06 * wr.InitialProjection06 END, + fs.InitialProjectionDollars07 = CASE WHEN @MonthsLoaded >= 7 THEN psfv.InitialProjection07 ELSE fs.InitialProjectionHours07 * wr.InitialProjection07 END, + fs.InitialProjectionDollars08 = CASE WHEN @MonthsLoaded >= 8 THEN psfv.InitialProjection08 ELSE fs.InitialProjectionHours08 * wr.InitialProjection08 END, + fs.InitialProjectionDollars09 = CASE WHEN @MonthsLoaded >= 9 THEN psfv.InitialProjection09 ELSE fs.InitialProjectionHours09 * wr.InitialProjection09 END, + fs.InitialProjectionDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN psfv.InitialProjection10 ELSE fs.InitialProjectionHours10 * wr.InitialProjection10 END, + fs.InitialProjectionDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN psfv.InitialProjection11 ELSE fs.InitialProjectionHours11 * wr.InitialProjection11 END, + fs.InitialProjectionDollars12 = CASE WHEN @MonthsLoaded >= 12 THEN psfv.InitialProjection12 ELSE fs.InitialProjectionHours12 * wr.InitialProjection12 END + FROM [fp].[Staffing] fs + INNER JOIN fp.StaffingWageRate wr on fs.StaffingWageRateID = wr.StaffingWageRateID + INNER JOIN #preSpreadFixedVarDollars psfv -- we need this unfortunately because we need the actual values for months loaded projection + ON psfv.StaffingID = fs.StaffingID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.ProductiveClassID <> 4 -- exclude 'Dollars-Only' + AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID <> @ProviderSubsectionID) -- exclude provider + + + -- now update dollars-only productive class + DELETE FROM #spreadFixedVar + + INSERT INTO #combinedStaffingDollarsAboveVariability (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProductiveClassID, EntityGroupConfigID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, SampledBudgetDollarsTotal, + SampledProjectionDollars01, SampledProjectionDollars02, SampledProjectionDollars03, SampledProjectionDollars04, SampledProjectionDollars05, SampledProjectionDollars06, + SampledProjectionDollars07, SampledProjectionDollars08, SampledProjectionDollars09, SampledProjectionDollars10, SampledProjectionDollars11, SampledProjectionDollars12) + SELECT + fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, + fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, + SUM(fs.SampledBudgetDollarsTotal) AS SampledBudgetDollarsTotal, + SUM(fs.SampledProjectionDollars01) AS SampledProjectionDollars01, + SUM(fs.SampledProjectionDollars02) AS SampledProjectionDollars02, + SUM(fs.SampledProjectionDollars03) AS SampledProjectionDollars03, + SUM(fs.SampledProjectionDollars04) AS SampledProjectionDollars04, + SUM(fs.SampledProjectionDollars05) AS SampledProjectionDollars05, + SUM(fs.SampledProjectionDollars06) AS SampledProjectionDollars06, + SUM(fs.SampledProjectionDollars07) AS SampledProjectionDollars07, + SUM(fs.SampledProjectionDollars08) AS SampledProjectionDollars08, + SUM(fs.SampledProjectionDollars09) AS SampledProjectionDollars09, + SUM(fs.SampledProjectionDollars10) AS SampledProjectionDollars10, + SUM(fs.SampledProjectionDollars11) AS SampledProjectionDollars11, + SUM(fs.SampledProjectionDollars12) AS SampledProjectionDollars12 + FROM [fp].[Staffing] fs + INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.ProductiveClassID = 4 -- 'Dollars-Only' + AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID <> @ProviderSubsectionID) -- exclude provider + GROUP BY fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, + fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID + + INSERT INTO #spreadFixedVar (StaffingID, + InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, + InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12) + SELECT + fs.StaffingID, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars01, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars02, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars03, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars04, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars05, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars06, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars07, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars08, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars09, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars10, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars11, + CASE WHEN fs.VariabilityID = 1 + THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal - ((total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) )) + ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal - ((total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) )) + END as InitialBudgetDollars12, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars01 END SampledProjectionDollars01, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars02 END SampledProjectionDollars02, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars03 END SampledProjectionDollars03, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars04 END SampledProjectionDollars04, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars05 END SampledProjectionDollars05, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars06 END SampledProjectionDollars06, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars07 END SampledProjectionDollars07, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars08 END SampledProjectionDollars08, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars09 END SampledProjectionDollars09, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars10 END SampledProjectionDollars10, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars11 END SampledProjectionDollars11, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars12 END SampledProjectionDollars12 + FROM [fp].[Staffing] fs + INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID + INNER JOIN #combinedStaffingDollarsAboveVariability total ON + fs.DepartmentID = total.DepartmentID + AND fs.JobCodeID = total.JobCodeID + AND fs.PayCodeGroupID = total.PayCodeGroupID + AND fs.EmployeeID = total.EmployeeID + AND fs.ProductiveClassID = total.ProductiveClassID + AND fs.EntityGroupConfigID = total.EntityGroupConfigID + AND fs.ProviderID = total.ProviderID + AND fs.ProviderTypeID = total.ProviderTypeID + AND fs.ProviderSpecialtyID = total.ProviderSpecialtyID + AND fs.ProviderLineItemID = total.ProviderLineItemID + AND fs.SubsectionID = total.SubsectionID + LEFT JOIN #Variability fv ON + fv.DepartmentID = fs.DepartmentID + AND fv.JobCodeID = fs.JobCodeID + AND fv.PayCodeGroupID = fs.PayCodeGroupID + AND fv.EmployeeID = fs.EmployeeID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.ProductiveClassID = 4 -- 'Dollars-Only' + AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID <> @ProviderSubsectionID) -- exclude provider + + TRUNCATE TABLE #combinedStaffingDollarsAboveVariability; + + --------------------------- Provider Line Item variability --------------------------- + + INSERT INTO #combinedStaffingDollarsAboveVariability (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProductiveClassID, EntityGroupConfigID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, SampledBudgetDollarsTotal, + SampledProjectionDollars01, SampledProjectionDollars02, SampledProjectionDollars03, SampledProjectionDollars04, SampledProjectionDollars05, SampledProjectionDollars06, + SampledProjectionDollars07, SampledProjectionDollars08, SampledProjectionDollars09, SampledProjectionDollars10, SampledProjectionDollars11, SampledProjectionDollars12) + SELECT + fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, + fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, + SUM(fs.SampledBudgetDollarsTotal) AS SampledBudgetDollarsTotal, + SUM(fs.SampledProjectionDollars01) AS SampledProjectionDollars01, + SUM(fs.SampledProjectionDollars02) AS SampledProjectionDollars02, + SUM(fs.SampledProjectionDollars03) AS SampledProjectionDollars03, + SUM(fs.SampledProjectionDollars04) AS SampledProjectionDollars04, + SUM(fs.SampledProjectionDollars05) AS SampledProjectionDollars05, + SUM(fs.SampledProjectionDollars06) AS SampledProjectionDollars06, + SUM(fs.SampledProjectionDollars07) AS SampledProjectionDollars07, + SUM(fs.SampledProjectionDollars08) AS SampledProjectionDollars08, + SUM(fs.SampledProjectionDollars09) AS SampledProjectionDollars09, + SUM(fs.SampledProjectionDollars10) AS SampledProjectionDollars10, + SUM(fs.SampledProjectionDollars11) AS SampledProjectionDollars11, + SUM(fs.SampledProjectionDollars12) AS SampledProjectionDollars12 + FROM [fp].[Staffing] fs + INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND (@IsProviderPlanningEnabled = 1 AND fs.SubsectionID = @ProviderSubsectionID) -- provider + GROUP BY fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, + fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID + + INSERT INTO #spreadFixedVar (StaffingID, + InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, + InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12) + SELECT + fs.StaffingID, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars01, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars02, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars03, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars04, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars05, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars06, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars07, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars08, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars09, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars10, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars11, + CASE WHEN fs.VariabilityID = 1 + THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal - ((total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) )) + ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal - ((total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) )) + END as InitialBudgetDollars12, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars01 END SampledProjectionDollars01, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars02 END SampledProjectionDollars02, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars03 END SampledProjectionDollars03, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars04 END SampledProjectionDollars04, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars05 END SampledProjectionDollars05, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars06 END SampledProjectionDollars06, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars07 END SampledProjectionDollars07, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars08 END SampledProjectionDollars08, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars09 END SampledProjectionDollars09, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars10 END SampledProjectionDollars10, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars11 END SampledProjectionDollars11, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars12 END SampledProjectionDollars12 + + FROM [fp].[Staffing] fs + INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID + INNER JOIN #combinedStaffingDollarsAboveVariability total ON + fs.DepartmentID = total.DepartmentID + AND fs.JobCodeID = total.JobCodeID + AND fs.PayCodeGroupID = total.PayCodeGroupID + AND fs.EmployeeID = total.EmployeeID + AND fs.ProductiveClassID = total.ProductiveClassID + AND fs.EntityGroupConfigID = total.EntityGroupConfigID + AND fs.ProviderID = total.ProviderID + AND fs.ProviderTypeID = total.ProviderTypeID + AND fs.ProviderSpecialtyID = total.ProviderSpecialtyID + AND fs.ProviderLineItemID = total.ProviderLineItemID + AND fs.SubsectionID = total.SubsectionID + LEFT JOIN #Variability fv -- if this is a filtered call, filtering was done here + ON fv.DepartmentID = fs.DepartmentID + AND fv.JobCodeID = fs.JobCodeID + AND fv.PayCodeGroupID = fs.PayCodeGroupID + AND fv.ProviderLineItemID = fs.ProviderLineItemID + AND fv.EmployeeID = fs.EmployeeID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID + AND (@IsProviderPlanningEnabled = 1 AND fs.SubsectionID = @ProviderSubsectionID) -- provider + + + -- update initial budget for dollars + UPDATE fs + SET + fs.InitialBudgetDollars01 = sfv.InitialBudget01, + fs.InitialBudgetDollars02 = sfv.InitialBudget02, + fs.InitialBudgetDollars03 = sfv.InitialBudget03, + fs.InitialBudgetDollars04 = sfv.InitialBudget04, + fs.InitialBudgetDollars05 = sfv.InitialBudget05, + fs.InitialBudgetDollars06 = sfv.InitialBudget06, + fs.InitialBudgetDollars07 = sfv.InitialBudget07, + fs.InitialBudgetDollars08 = sfv.InitialBudget08, + fs.InitialBudgetDollars09 = sfv.InitialBudget09, + fs.InitialBudgetDollars10 = sfv.InitialBudget10, + fs.InitialBudgetDollars11 = sfv.InitialBudget11, + fs.InitialBudgetDollars12 = sfv.InitialBudget12 + FROM + [fp].[Staffing] fs + INNER JOIN #spreadFixedVar sfv ON fs.StaffingID = sfv.StaffingID + + + CREATE TABLE #DollarTotals (StaffingID INT, ProjectionTotal DECIMAL(19,8), NewValue DECIMAL(19,8), + INDEX ix_dol_1 NONCLUSTERED (StaffingID) + ) + INSERT INTO #DollarTotals (StaffingID, ProjectionTotal) + SELECT StaffingID, + CASE WHEN @MonthsLoaded = 11 THEN staff.InitialProjection12 + WHEN @MonthsLoaded = 10 THEN staff.InitialProjection11 + staff.InitialProjection12 + WHEN @MonthsLoaded = 9 THEN staff.InitialProjection10 + staff.InitialProjection11 + staff.InitialProjection12 + WHEN @MonthsLoaded = 8 THEN staff.InitialProjection09 + staff.InitialProjection10 + staff.InitialProjection11 + staff.InitialProjection12 + WHEN @MonthsLoaded = 7 THEN staff.InitialProjection08 + staff.InitialProjection09 + staff.InitialProjection10 + staff.InitialProjection11 + staff.InitialProjection12 + WHEN @MonthsLoaded = 6 THEN staff.InitialProjection07 + staff.InitialProjection08 + staff.InitialProjection09 + staff.InitialProjection10 + staff.InitialProjection11 + staff.InitialProjection12 + WHEN @MonthsLoaded = 5 THEN staff.InitialProjection06 + staff.InitialProjection07 + staff.InitialProjection08 + staff.InitialProjection09 + staff.InitialProjection10 + staff.InitialProjection11 + staff.InitialProjection12 + WHEN @MonthsLoaded = 4 THEN staff.InitialProjection05 + staff.InitialProjection06 + staff.InitialProjection07 + staff.InitialProjection08 + staff.InitialProjection09 + staff.InitialProjection10 + staff.InitialProjection11 + staff.InitialProjection12 + WHEN @MonthsLoaded = 3 THEN staff.InitialProjection04 + staff.InitialProjection05 + staff.InitialProjection06 + staff.InitialProjection07 + staff.InitialProjection08 + staff.InitialProjection09 + staff.InitialProjection10 + staff.InitialProjection11 + staff.InitialProjection12 + WHEN @MonthsLoaded = 2 THEN staff.InitialProjection03 + staff.InitialProjection04 + staff.InitialProjection05 + staff.InitialProjection06 + staff.InitialProjection07 + staff.InitialProjection08 + staff.InitialProjection09 + staff.InitialProjection10 + staff.InitialProjection11 + staff.InitialProjection12 + WHEN @MonthsLoaded = 1 THEN staff.InitialProjection02 + staff.InitialProjection03 + staff.InitialProjection04 + staff.InitialProjection05 + staff.InitialProjection06 + staff.InitialProjection07 + staff.InitialProjection08 + staff.InitialProjection09 + staff.InitialProjection10 + staff.InitialProjection11 + staff.InitialProjection12 + ELSE 0 + END + FROM #spreadFixedVar staff + + UPDATE a + SET NewValue = ProjectionTotal / (12.0 - @MonthsLoaded) + FROM #DollarTotals a + + + -- update initial projection for dollars and hours + UPDATE fs + SET + fs.InitialProjectionDollars01 = CASE WHEN @MonthsLoaded >= 1 THEN sfv.InitialProjection01 ELSE t.NewValue END, + fs.InitialProjectionDollars02 = CASE WHEN @MonthsLoaded >= 2 THEN sfv.InitialProjection02 ELSE t.NewValue END, + fs.InitialProjectionDollars03 = CASE WHEN @MonthsLoaded >= 3 THEN sfv.InitialProjection03 ELSE t.NewValue END, + fs.InitialProjectionDollars04 = CASE WHEN @MonthsLoaded >= 4 THEN sfv.InitialProjection04 ELSE t.NewValue END, + fs.InitialProjectionDollars05 = CASE WHEN @MonthsLoaded >= 5 THEN sfv.InitialProjection05 ELSE t.NewValue END, + fs.InitialProjectionDollars06 = CASE WHEN @MonthsLoaded >= 6 THEN sfv.InitialProjection06 ELSE t.NewValue END, + fs.InitialProjectionDollars07 = CASE WHEN @MonthsLoaded >= 7 THEN sfv.InitialProjection07 ELSE t.NewValue END, + fs.InitialProjectionDollars08 = CASE WHEN @MonthsLoaded >= 8 THEN sfv.InitialProjection08 ELSE t.NewValue END, + fs.InitialProjectionDollars09 = CASE WHEN @MonthsLoaded >= 9 THEN sfv.InitialProjection09 ELSE t.NewValue END, + fs.InitialProjectionDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN sfv.InitialProjection10 ELSE t.NewValue END, + fs.InitialProjectionDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN sfv.InitialProjection11 ELSE t.NewValue END, + fs.InitialProjectionDollars12 = CASE WHEN @MonthsLoaded >= 12 THEN sfv.InitialProjection12 ELSE t.NewValue END + FROM [fp].[Staffing] fs + INNER JOIN #DollarTotals t on fs.StaffingID = t.StaffingID + INNER JOIN #spreadFixedVar sfv ON fs.StaffingID = sfv.StaffingID + + -- Cleaning up records where flexMethod = 6 (Fixed) AND variabilityID = 2 (Variable) + + UPDATE fs SET + fs.InitialBudgetFTEs01 = 0, + fs.InitialBudgetFTEs02 = 0, + fs.InitialBudgetFTEs03 = 0, + fs.InitialBudgetFTEs04 = 0, + fs.InitialBudgetFTEs05 = 0, + fs.InitialBudgetFTEs06 = 0, + fs.InitialBudgetFTEs07 = 0, + fs.InitialBudgetFTEs08 = 0, + fs.InitialBudgetFTEs09 = 0, + fs.InitialBudgetFTEs10 = 0, + fs.InitialBudgetFTEs11 = 0, + fs.InitialBudgetFTEs12 = 0, + fs.InitialProjectionFTEs01 = 0, + fs.InitialProjectionFTEs02 = 0, + fs.InitialProjectionFTEs03 = 0, + fs.InitialProjectionFTEs04 = 0, + fs.InitialProjectionFTEs05 = 0, + fs.InitialProjectionFTEs06 = 0, + fs.InitialProjectionFTEs07 = 0, + fs.InitialProjectionFTEs08 = 0, + fs.InitialProjectionFTEs09 = 0, + fs.InitialProjectionFTEs10 = 0, + fs.InitialProjectionFTEs11 = 0, + fs.InitialProjectionFTEs12 = 0, + + fs.TargetAdjustedFTEs01 = 0, + fs.TargetAdjustedFTEs02 = 0, + fs.TargetAdjustedFTEs03 = 0, + fs.TargetAdjustedFTEs04 = 0, + fs.TargetAdjustedFTEs05 = 0, + fs.TargetAdjustedFTEs06 = 0, + fs.TargetAdjustedFTEs07 = 0, + fs.TargetAdjustedFTEs08 = 0, + fs.TargetAdjustedFTEs09 = 0, + fs.TargetAdjustedFTEs10 = 0, + fs.TargetAdjustedFTEs11 = 0, + fs.TargetAdjustedFTEs12 = 0, + fs.BudgetAdjustedFTEs01 = 0, + fs.BudgetAdjustedFTEs02 = 0, + fs.BudgetAdjustedFTEs03 = 0, + fs.BudgetAdjustedFTEs04 = 0, + fs.BudgetAdjustedFTEs05 = 0, + fs.BudgetAdjustedFTEs06 = 0, + fs.BudgetAdjustedFTEs07 = 0, + fs.BudgetAdjustedFTEs08 = 0, + fs.BudgetAdjustedFTEs09 = 0, + fs.BudgetAdjustedFTEs10 = 0, + fs.BudgetAdjustedFTEs11 = 0, + fs.BudgetAdjustedFTEs12 = 0, + + fs.ProjectionAdjustedFTEs01 = 0, + fs.ProjectionAdjustedFTEs02 = 0, + fs.ProjectionAdjustedFTEs03 = 0, + fs.ProjectionAdjustedFTEs04 = 0, + fs.ProjectionAdjustedFTEs05 = 0, + fs.ProjectionAdjustedFTEs06 = 0, + fs.ProjectionAdjustedFTEs07 = 0, + fs.ProjectionAdjustedFTEs08 = 0, + fs.ProjectionAdjustedFTEs09 = 0, + fs.ProjectionAdjustedFTEs10 = 0, + fs.ProjectionAdjustedFTEs11 = 0, + fs.ProjectionAdjustedFTEs12 = 0, + fs.TargetFTEsPercentAdjustmentFactor01 = 0, + fs.TargetFTEsPercentAdjustmentFactor02 = 0, + fs.TargetFTEsPercentAdjustmentFactor03 = 0, + fs.TargetFTEsPercentAdjustmentFactor04 = 0, + fs.TargetFTEsPercentAdjustmentFactor05 = 0, + fs.TargetFTEsPercentAdjustmentFactor06 = 0, + fs.TargetFTEsPercentAdjustmentFactor07 = 0, + fs.TargetFTEsPercentAdjustmentFactor08 = 0, + fs.TargetFTEsPercentAdjustmentFactor09 = 0, + fs.TargetFTEsPercentAdjustmentFactor10 = 0, + fs.TargetFTEsPercentAdjustmentFactor11 = 0, + fs.TargetFTEsPercentAdjustmentFactor12 = 0, + fs.BudgetFTEsPercentAdjustmentFactor01 = 0, + fs.BudgetFTEsPercentAdjustmentFactor02 = 0, + fs.BudgetFTEsPercentAdjustmentFactor03 = 0, + fs.BudgetFTEsPercentAdjustmentFactor04 = 0, + fs.BudgetFTEsPercentAdjustmentFactor05 = 0, + fs.BudgetFTEsPercentAdjustmentFactor06 = 0, + fs.BudgetFTEsPercentAdjustmentFactor07 = 0, + fs.BudgetFTEsPercentAdjustmentFactor08 = 0, + fs.BudgetFTEsPercentAdjustmentFactor09 = 0, + fs.BudgetFTEsPercentAdjustmentFactor10 = 0, + fs.BudgetFTEsPercentAdjustmentFactor11 = 0, + fs.BudgetFTEsPercentAdjustmentFactor12 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor01 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor02 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor03 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor04 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor05 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor06 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor07 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor08 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor09 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor10 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor11 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor12 = 0, + + fs.InitialBudgetRate01 = 0, + fs.InitialBudgetRate02 = 0, + fs.InitialBudgetRate03 = 0, + fs.InitialBudgetRate04 = 0, + fs.InitialBudgetRate05 = 0, + fs.InitialBudgetRate06 = 0, + fs.InitialBudgetRate07 = 0, + fs.InitialBudgetRate08 = 0, + fs.InitialBudgetRate09 = 0, + fs.InitialBudgetRate10 = 0, + fs.InitialBudgetRate11 = 0, + fs.InitialBudgetRate12 = 0, + fs.InitialProjectionRate01 = 0, + fs.InitialProjectionRate02 = 0, + fs.InitialProjectionRate03 = 0, + fs.InitialProjectionRate04 = 0, + fs.InitialProjectionRate05 = 0, + fs.InitialProjectionRate06 = 0, + fs.InitialProjectionRate07 = 0, + fs.InitialProjectionRate08 = 0, + fs.InitialProjectionRate09 = 0, + fs.InitialProjectionRate10 = 0, + fs.InitialProjectionRate11 = 0, + fs.InitialProjectionRate12 = 0, + fs.TargetAdjustedRate01 = 0, + fs.TargetAdjustedRate02 = 0, + fs.TargetAdjustedRate03 = 0, + fs.TargetAdjustedRate04 = 0, + fs.TargetAdjustedRate05 = 0, + fs.TargetAdjustedRate06 = 0, + fs.TargetAdjustedRate07 = 0, + fs.TargetAdjustedRate08 = 0, + fs.TargetAdjustedRate09 = 0, + fs.TargetAdjustedRate10 = 0, + fs.TargetAdjustedRate11 = 0, + fs.TargetAdjustedRate12 = 0, + fs.BudgetAdjustedRate01 = 0, + fs.BudgetAdjustedRate02 = 0, + fs.BudgetAdjustedRate03 = 0, + fs.BudgetAdjustedRate04 = 0, + fs.BudgetAdjustedRate05 = 0, + fs.BudgetAdjustedRate06 = 0, + fs.BudgetAdjustedRate07 = 0, + fs.BudgetAdjustedRate08 = 0, + fs.BudgetAdjustedRate09 = 0, + fs.BudgetAdjustedRate10 = 0, + fs.BudgetAdjustedRate11 = 0, + fs.BudgetAdjustedRate12 = 0, + fs.ProjectionAdjustedRate01 = 0, + fs.ProjectionAdjustedRate02 = 0, + fs.ProjectionAdjustedRate03 = 0, + fs.ProjectionAdjustedRate04 = 0, + fs.ProjectionAdjustedRate05 = 0, + fs.ProjectionAdjustedRate06 = 0, + fs.ProjectionAdjustedRate07 = 0, + fs.ProjectionAdjustedRate08 = 0, + fs.ProjectionAdjustedRate09 = 0, + fs.ProjectionAdjustedRate10 = 0, + fs.ProjectionAdjustedRate11 = 0, + fs.ProjectionAdjustedRate12 = 0 + FROM [fp].[Staffing] fs + INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID + LEFT JOIN #Variability v on fs.DepartmentID = v.DepartmentID + AND fs.JobCodeID = v.JobCodeID + AND fs.PayCodeGroupID = v.PayCodeGroupID + AND v.ProviderLineItemID = fs.ProviderLineItemID + AND v.EmployeeID = fs.EmployeeID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND (v.FixedPercentage = 1 OR v.FixedPercentage is NULL) + AND fs.VariabilityID = 2 + + + END; +GO + + +--------------------------------------------- + +-- fp.procApplyVariabilityToStaffingHistory +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-10-04 IP B-20922 Added using source dimensionality +** 2 2019-08-19 BK B-24026 Performance updates +** 3 2020-07-20 MW JAZZ-2212 Add EmployeeID for EB +** 4 2020-08-05 LR JAZZ-1226 Added clean up for variable hours and FTEs with Fixed override +** 5 2020-10-27 LR JAZZ-6178 Alter ApplyVariabilityToStaffingHistory to fix migration override +** 6 2020-11-04 BK JAZZ-8379 Add provider fields to proc and clean up filtering +** 7 2021-08-16 BK JAZZ-21272 Use cached variability table for cleaning up variable records +** 8 2022-04-12 OP JAZZ-36116 Sampled all hours as fixed for provider compensation +** 9 2022-04-29 MY JAZZ-28395 Cache Variability Percentage on FactStaffing +** 10 2022-10-04 MY JAZZ-37262 Remove Feature Flag 'Use Variability From FactStaffing Table' +** 11 2022-11-07 MY JAZZ-35951 Add EmployeeID to FactStaffingVariabilityDetail +** 12 2023-09-20 BK JAZZ-60973 Update for new data structure +** 13 2023-12-26 NH/NT JAZZ-64324 Remove 'Use Hours and FTE on Provider Compensation (doing this in restructure branch on behalf of Softserve) +** 14 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config +*************************************************************/ +CREATE PROCEDURE [fp].[procApplyVariabilityToStaffingHistory] + @EntityGroupConfigID INT, + @FiscalYearID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + AS + BEGIN + + IF OBJECT_ID('tempdb..#Totals') IS NOT NULL DROP TABLE #Totals + IF OBJECT_ID('tempdb..#FilteredTotals') IS NOT NULL DROP TABLE #FilteredTotals + IF OBJECT_ID('tempdb..#Variability') IS NOT NULL DROP TABLE #Variability + + DECLARE @IsProviderPlanningEnabled BIT; + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID; + + CREATE TABLE #FilteringTable ( + DepartmentID INT + ,INDEX ix_1 NONCLUSTERED (DepartmentID) + ) + + INSERT INTO #FilteringTable (DepartmentID) + SELECT DepartmentID + FROM @SourceDimensionality + + DECLARE @EntityGroupConfigGUID UNIQUEIDENTIFIER; + SET @EntityGroupConfigGUID = (SELECT EntityGroupConfigGUID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID) + + CREATE TABLE #Variability ( DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, ProviderLineItemID INT, EmployeeID INT, FixedPercentage DECIMAL(19,8), + INDEX ix_totals_1 NONCLUSTERED ( DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID) + ) + + DECLARE @isFilterPresent int = (SELECT COUNT(*) FROM #FilteringTable) + + IF (@isFilterPresent=0) BEGIN + INSERT INTO #FilteringTable (DepartmentID) + SELECT DISTINCT DepartmentID FROM fp.Staffing WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + INSERT INTO #Variability (DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID, FixedPercentage) + SELECT v.DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID, MAX(FixedPercentage) AS FixedPercentage + FROM [fp].[viewFactStaffingVariability] v + INNER JOIN #FilteringTable f ON v.DepartmentID = f.DepartmentID + WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID + GROUP BY v.DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID + + + SELECT + fs.DepartmentID, + fs.JobCodeID, + fs.EmployeeID, + fs.PayCodeGroupID, + fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, + SUM(b.PriorYearActualHours01) AS PriorYearActualHours01, + SUM(b.PriorYearActualHours02) AS PriorYearActualHours02, + SUM(b.PriorYearActualHours03) AS PriorYearActualHours03, + SUM(b.PriorYearActualHours04) AS PriorYearActualHours04, + SUM(b.PriorYearActualHours05) AS PriorYearActualHours05, + SUM(b.PriorYearActualHours06) AS PriorYearActualHours06, + SUM(b.PriorYearActualHours07) AS PriorYearActualHours07, + SUM(b.PriorYearActualHours08) AS PriorYearActualHours08, + SUM(b.PriorYearActualHours09) AS PriorYearActualHours09, + SUM(b.PriorYearActualHours10) AS PriorYearActualHours10, + SUM(b.PriorYearActualHours11) AS PriorYearActualHours11, + SUM(b.PriorYearActualHours12) AS PriorYearActualHours12, + SUM(b.ActualYTDHours01) AS ActualYTDHours01, + SUM(b.ActualYTDHours02) AS ActualYTDHours02, + SUM(b.ActualYTDHours03) AS ActualYTDHours03, + SUM(b.ActualYTDHours04) AS ActualYTDHours04, + SUM(b.ActualYTDHours05) AS ActualYTDHours05, + SUM(b.ActualYTDHours06) AS ActualYTDHours06, + SUM(b.ActualYTDHours07) AS ActualYTDHours07, + SUM(b.ActualYTDHours08) AS ActualYTDHours08, + SUM(b.ActualYTDHours09) AS ActualYTDHours09, + SUM(b.ActualYTDHours10) AS ActualYTDHours10, + SUM(b.ActualYTDHours11) AS ActualYTDHours11, + SUM(b.ActualYTDHours12) AS ActualYTDHours12, + SUM(b.CurrentYearBudgetHours01) AS CurrentYearBudgetHours01, + SUM(b.CurrentYearBudgetHours02) AS CurrentYearBudgetHours02, + SUM(b.CurrentYearBudgetHours03) AS CurrentYearBudgetHours03, + SUM(b.CurrentYearBudgetHours04) AS CurrentYearBudgetHours04, + SUM(b.CurrentYearBudgetHours05) AS CurrentYearBudgetHours05, + SUM(b.CurrentYearBudgetHours06) AS CurrentYearBudgetHours06, + SUM(b.CurrentYearBudgetHours07) AS CurrentYearBudgetHours07, + SUM(b.CurrentYearBudgetHours08) AS CurrentYearBudgetHours08, + SUM(b.CurrentYearBudgetHours09) AS CurrentYearBudgetHours09, + SUM(b.CurrentYearBudgetHours10) AS CurrentYearBudgetHours10, + SUM(b.CurrentYearBudgetHours11) AS CurrentYearBudgetHours11, + SUM(b.CurrentYearBudgetHours12) AS CurrentYearBudgetHours12, + SUM(b.PriorYearActualDollars01) AS PriorYearActualDollars01, + SUM(b.PriorYearActualDollars02) AS PriorYearActualDollars02, + SUM(b.PriorYearActualDollars03) AS PriorYearActualDollars03, + SUM(b.PriorYearActualDollars04) AS PriorYearActualDollars04, + SUM(b.PriorYearActualDollars05) AS PriorYearActualDollars05, + SUM(b.PriorYearActualDollars06) AS PriorYearActualDollars06, + SUM(b.PriorYearActualDollars07) AS PriorYearActualDollars07, + SUM(b.PriorYearActualDollars08) AS PriorYearActualDollars08, + SUM(b.PriorYearActualDollars09) AS PriorYearActualDollars09, + SUM(b.PriorYearActualDollars10) AS PriorYearActualDollars10, + SUM(b.PriorYearActualDollars11) AS PriorYearActualDollars11, + SUM(b.PriorYearActualDollars12) AS PriorYearActualDollars12, + SUM(b.ActualYTDDollars01) AS ActualYTDDollars01, + SUM(b.ActualYTDDollars02) AS ActualYTDDollars02, + SUM(b.ActualYTDDollars03) AS ActualYTDDollars03, + SUM(b.ActualYTDDollars04) AS ActualYTDDollars04, + SUM(b.ActualYTDDollars05) AS ActualYTDDollars05, + SUM(b.ActualYTDDollars06) AS ActualYTDDollars06, + SUM(b.ActualYTDDollars07) AS ActualYTDDollars07, + SUM(b.ActualYTDDollars08) AS ActualYTDDollars08, + SUM(b.ActualYTDDollars09) AS ActualYTDDollars09, + SUM(b.ActualYTDDollars10) AS ActualYTDDollars10, + SUM(b.ActualYTDDollars11) AS ActualYTDDollars11, + SUM(b.ActualYTDDollars12) AS ActualYTDDollars12, + SUM(b.CurrentYearBudgetDollars01) AS CurrentYearBudgetDollars01, + SUM(b.CurrentYearBudgetDollars02) AS CurrentYearBudgetDollars02, + SUM(b.CurrentYearBudgetDollars03) AS CurrentYearBudgetDollars03, + SUM(b.CurrentYearBudgetDollars04) AS CurrentYearBudgetDollars04, + SUM(b.CurrentYearBudgetDollars05) AS CurrentYearBudgetDollars05, + SUM(b.CurrentYearBudgetDollars06) AS CurrentYearBudgetDollars06, + SUM(b.CurrentYearBudgetDollars07) AS CurrentYearBudgetDollars07, + SUM(b.CurrentYearBudgetDollars08) AS CurrentYearBudgetDollars08, + SUM(b.CurrentYearBudgetDollars09) AS CurrentYearBudgetDollars09, + SUM(b.CurrentYearBudgetDollars10) AS CurrentYearBudgetDollars10, + SUM(b.CurrentYearBudgetDollars11) AS CurrentYearBudgetDollars11, + SUM(b.CurrentYearBudgetDollars12) AS CurrentYearBudgetDollars12, + SUM(b.PriorYearActualFTEs01) AS PriorYearActualFTEs01, + SUM(b.PriorYearActualFTEs02) AS PriorYearActualFTEs02, + SUM(b.PriorYearActualFTEs03) AS PriorYearActualFTEs03, + SUM(b.PriorYearActualFTEs04) AS PriorYearActualFTEs04, + SUM(b.PriorYearActualFTEs05) AS PriorYearActualFTEs05, + SUM(b.PriorYearActualFTEs06) AS PriorYearActualFTEs06, + SUM(b.PriorYearActualFTEs07) AS PriorYearActualFTEs07, + SUM(b.PriorYearActualFTEs08) AS PriorYearActualFTEs08, + SUM(b.PriorYearActualFTEs09) AS PriorYearActualFTEs09, + SUM(b.PriorYearActualFTEs10) AS PriorYearActualFTEs10, + SUM(b.PriorYearActualFTEs11) AS PriorYearActualFTEs11, + SUM(b.PriorYearActualFTEs12) AS PriorYearActualFTEs12, + SUM(b.ActualYTDFTEs01) AS ActualYTDFTEs01, + SUM(b.ActualYTDFTEs02) AS ActualYTDFTEs02, + SUM(b.ActualYTDFTEs03) AS ActualYTDFTEs03, + SUM(b.ActualYTDFTEs04) AS ActualYTDFTEs04, + SUM(b.ActualYTDFTEs05) AS ActualYTDFTEs05, + SUM(b.ActualYTDFTEs06) AS ActualYTDFTEs06, + SUM(b.ActualYTDFTEs07) AS ActualYTDFTEs07, + SUM(b.ActualYTDFTEs08) AS ActualYTDFTEs08, + SUM(b.ActualYTDFTEs09) AS ActualYTDFTEs09, + SUM(b.ActualYTDFTEs10) AS ActualYTDFTEs10, + SUM(b.ActualYTDFTEs11) AS ActualYTDFTEs11, + SUM(b.ActualYTDFTEs12) AS ActualYTDFTEs12, + SUM(b.CurrentYearBudgetFTEs01) AS CurrentYearBudgetFTEs01, + SUM(b.CurrentYearBudgetFTEs02) AS CurrentYearBudgetFTEs02, + SUM(b.CurrentYearBudgetFTEs03) AS CurrentYearBudgetFTEs03, + SUM(b.CurrentYearBudgetFTEs04) AS CurrentYearBudgetFTEs04, + SUM(b.CurrentYearBudgetFTEs05) AS CurrentYearBudgetFTEs05, + SUM(b.CurrentYearBudgetFTEs06) AS CurrentYearBudgetFTEs06, + SUM(b.CurrentYearBudgetFTEs07) AS CurrentYearBudgetFTEs07, + SUM(b.CurrentYearBudgetFTEs08) AS CurrentYearBudgetFTEs08, + SUM(b.CurrentYearBudgetFTEs09) AS CurrentYearBudgetFTEs09, + SUM(b.CurrentYearBudgetFTEs10) AS CurrentYearBudgetFTEs10, + SUM(b.CurrentYearBudgetFTEs11) AS CurrentYearBudgetFTEs11, + SUM(b.CurrentYearBudgetFTEs12) AS CurrentYearBudgetFTEs12 + INTO #FilteredTotals + FROM + [fp].[StaffingHistory] b INNER JOIN [fp].[Staffing] fs ON b.StaffingID = fs.StaffingID + INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID + GROUP BY + fs.DepartmentID, + fs.JobCodeID, + fs.EmployeeID, + fs.PayCodeGroupID, + fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID + + -- dollars and ftes should be updated no matter what + UPDATE basis + SET + + basis.PriorYearActualDollars01 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars01 END, + basis.PriorYearActualDollars02 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars02 END, + basis.PriorYearActualDollars03 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars03 END, + basis.PriorYearActualDollars04 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars04 END, + basis.PriorYearActualDollars05 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars05 END, + basis.PriorYearActualDollars06 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars06 END, + basis.PriorYearActualDollars07 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars07 END, + basis.PriorYearActualDollars08 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars08 END, + basis.PriorYearActualDollars09 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars09 END, + basis.PriorYearActualDollars10 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars10 END, + basis.PriorYearActualDollars11 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars11 END, + basis.PriorYearActualDollars12 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualDollars12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualDollars12 END, + + basis.ActualYTDDollars01 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars01 END, + basis.ActualYTDDollars02 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars02 END, + basis.ActualYTDDollars03 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars03 END, + basis.ActualYTDDollars04 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars04 END, + basis.ActualYTDDollars05 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars05 END, + basis.ActualYTDDollars06 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars06 END, + basis.ActualYTDDollars07 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars07 END, + basis.ActualYTDDollars08 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars08 END, + basis.ActualYTDDollars09 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars09 END, + basis.ActualYTDDollars10 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars10 END, + basis.ActualYTDDollars11 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars11 END, + basis.ActualYTDDollars12 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDDollars12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDDollars12 END, + + basis.CurrentYearBudgetDollars01 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars01 END, + basis.CurrentYearBudgetDollars02 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars02 END, + basis.CurrentYearBudgetDollars03 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars03 END, + basis.CurrentYearBudgetDollars04 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars04 END, + basis.CurrentYearBudgetDollars05 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars05 END, + basis.CurrentYearBudgetDollars06 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars06 END, + basis.CurrentYearBudgetDollars07 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars07 END, + basis.CurrentYearBudgetDollars08 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars08 END, + basis.CurrentYearBudgetDollars09 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars09 END, + basis.CurrentYearBudgetDollars10 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars10 END, + basis.CurrentYearBudgetDollars11 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars11 END, + basis.CurrentYearBudgetDollars12 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetDollars12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetDollars12 END, + + basis.PriorYearActualFTEs01 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs01 END, + basis.PriorYearActualFTEs02 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs02 END, + basis.PriorYearActualFTEs03 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs03 END, + basis.PriorYearActualFTEs04 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs04 END, + basis.PriorYearActualFTEs05 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs05 END, + basis.PriorYearActualFTEs06 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs06 END, + basis.PriorYearActualFTEs07 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs07 END, + basis.PriorYearActualFTEs08 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs08 END, + basis.PriorYearActualFTEs09 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs09 END, + basis.PriorYearActualFTEs10 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs10 END, + basis.PriorYearActualFTEs11 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs11 END, + basis.PriorYearActualFTEs12 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualFTEs12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualFTEs12 END, + + basis.ActualYTDFTEs01 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs01 END, + basis.ActualYTDFTEs02 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs02 END, + basis.ActualYTDFTEs03 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs03 END, + basis.ActualYTDFTEs04 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs04 END, + basis.ActualYTDFTEs05 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs05 END, + basis.ActualYTDFTEs06 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs06 END, + basis.ActualYTDFTEs07 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs07 END, + basis.ActualYTDFTEs08 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs08 END, + basis.ActualYTDFTEs09 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs09 END, + basis.ActualYTDFTEs10 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs10 END, + basis.ActualYTDFTEs11 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs11 END, + basis.ActualYTDFTEs12 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDFTEs12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDFTEs12 END, + + basis.CurrentYearBudgetFTEs01 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs01 END, + basis.CurrentYearBudgetFTEs02 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs02 END, + basis.CurrentYearBudgetFTEs03 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs03 END, + basis.CurrentYearBudgetFTEs04 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs04 END, + basis.CurrentYearBudgetFTEs05 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs05 END, + basis.CurrentYearBudgetFTEs06 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs06 END, + basis.CurrentYearBudgetFTEs07 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs07 END, + basis.CurrentYearBudgetFTEs08 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs08 END, + basis.CurrentYearBudgetFTEs09 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs09 END, + basis.CurrentYearBudgetFTEs10 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs10 END, + basis.CurrentYearBudgetFTEs11 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs11 END, + basis.CurrentYearBudgetFTEs12 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetFTEs12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetFTEs12 END + FROM + [fp].[StaffingHistory] basis + INNER JOIN [fp].[Staffing] fs ON basis.StaffingID = fs.StaffingID + INNER JOIN #FilteredTotals total + ON total.DepartmentID = fs.DepartmentID + AND total.JobCodeID = fs.JobCodeID + AND total.PayCodeGroupID = fs.PayCodeGroupID + AND total.EmployeeID = fs.EmployeeID + LEFT JOIN #Variability fv + ON fv.DepartmentID = fs.DepartmentID + AND fv.JobCodeID = fs.JobCodeID + AND fv.PayCodeGroupID = fs.PayCodeGroupID + AND fv.EmployeeID = fs.EmployeeID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + + UPDATE basis + SET + basis.PriorYearActualHours01 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours01 END, + basis.PriorYearActualHours02 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours02 END, + basis.PriorYearActualHours03 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours03 END, + basis.PriorYearActualHours04 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours04 END, + basis.PriorYearActualHours05 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours05 END, + basis.PriorYearActualHours06 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours06 END, + basis.PriorYearActualHours07 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours07 END, + basis.PriorYearActualHours08 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours08 END, + basis.PriorYearActualHours09 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours09 END, + basis.PriorYearActualHours10 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours10 END, + basis.PriorYearActualHours11 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours11 END, + basis.PriorYearActualHours12 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.PriorYearActualHours12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.PriorYearActualHours12 END, + + basis.ActualYTDHours01 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours01 END, + basis.ActualYTDHours02 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours02 END, + basis.ActualYTDHours03 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours03 END, + basis.ActualYTDHours04 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours04 END, + basis.ActualYTDHours05 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours05 END, + basis.ActualYTDHours06 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours06 END, + basis.ActualYTDHours07 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours07 END, + basis.ActualYTDHours08 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours08 END, + basis.ActualYTDHours09 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours09 END, + basis.ActualYTDHours10 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours10 END, + basis.ActualYTDHours11 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours11 END, + basis.ActualYTDHours12 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.ActualYTDHours12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.ActualYTDHours12 END, + + basis.CurrentYearBudgetHours01 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours01 END, + basis.CurrentYearBudgetHours02 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours02 END, + basis.CurrentYearBudgetHours03 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours03 END, + basis.CurrentYearBudgetHours04 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours04 END, + basis.CurrentYearBudgetHours05 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours05 END, + basis.CurrentYearBudgetHours06 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours06 END, + basis.CurrentYearBudgetHours07 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours07 END, + basis.CurrentYearBudgetHours08 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours08 END, + basis.CurrentYearBudgetHours09 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours09 END, + basis.CurrentYearBudgetHours10 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours10 END, + basis.CurrentYearBudgetHours11 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours11 END, + basis.CurrentYearBudgetHours12 = CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.CurrentYearBudgetHours12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.CurrentYearBudgetHours12 END + + FROM + [fp].[StaffingHistory] basis + INNER JOIN [fp].[Staffing] fs ON basis.StaffingID = fs.StaffingID + INNER JOIN #FilteredTotals total + ON total.DepartmentID = fs.DepartmentID + AND total.JobCodeID = fs.JobCodeID + AND total.PayCodeGroupID = fs.PayCodeGroupID + AND total.EmployeeID = fs.EmployeeID + LEFT JOIN #Variability fv + ON fv.DepartmentID = fs.DepartmentID + AND fv.JobCodeID = fs.JobCodeID + AND fv.PayCodeGroupID = fs.PayCodeGroupID + AND fv.EmployeeID = fs.EmployeeID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND (fs.SubsectionID = 3 OR @IsProviderPlanningEnabled = 0) + + IF(@IsProviderPlanningEnabled = 1) BEGIN + + UPDATE basis + SET + basis.PriorYearActualHours01 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours01 ELSE 0 END, + basis.PriorYearActualHours02 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours02 ELSE 0 END, + basis.PriorYearActualHours03 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours03 ELSE 0 END, + basis.PriorYearActualHours04 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours04 ELSE 0 END, + basis.PriorYearActualHours05 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours05 ELSE 0 END, + basis.PriorYearActualHours06 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours06 ELSE 0 END, + basis.PriorYearActualHours07 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours07 ELSE 0 END, + basis.PriorYearActualHours08 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours08 ELSE 0 END, + basis.PriorYearActualHours09 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours09 ELSE 0 END, + basis.PriorYearActualHours10 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours10 ELSE 0 END, + basis.PriorYearActualHours11 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours11 ELSE 0 END, + basis.PriorYearActualHours12 = CASE WHEN fs.VariabilityID = 1 THEN total.PriorYearActualHours12 ELSE 0 END, + + basis.ActualYTDHours01 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours01 ELSE 0 END, + basis.ActualYTDHours02 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours02 ELSE 0 END, + basis.ActualYTDHours03 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours03 ELSE 0 END, + basis.ActualYTDHours04 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours04 ELSE 0 END, + basis.ActualYTDHours05 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours05 ELSE 0 END, + basis.ActualYTDHours06 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours06 ELSE 0 END, + basis.ActualYTDHours07 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours07 ELSE 0 END, + basis.ActualYTDHours08 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours08 ELSE 0 END, + basis.ActualYTDHours09 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours09 ELSE 0 END, + basis.ActualYTDHours10 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours10 ELSE 0 END, + basis.ActualYTDHours11 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours11 ELSE 0 END, + basis.ActualYTDHours12 = CASE WHEN fs.VariabilityID = 1 THEN total.ActualYTDHours12 ELSE 0 END, + + basis.CurrentYearBudgetHours01 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours01 ELSE 0 END, + basis.CurrentYearBudgetHours02 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours02 ELSE 0 END, + basis.CurrentYearBudgetHours03 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours03 ELSE 0 END, + basis.CurrentYearBudgetHours04 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours04 ELSE 0 END, + basis.CurrentYearBudgetHours05 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours05 ELSE 0 END, + basis.CurrentYearBudgetHours06 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours06 ELSE 0 END, + basis.CurrentYearBudgetHours07 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours07 ELSE 0 END, + basis.CurrentYearBudgetHours08 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours08 ELSE 0 END, + basis.CurrentYearBudgetHours09 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours09 ELSE 0 END, + basis.CurrentYearBudgetHours10 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours10 ELSE 0 END, + basis.CurrentYearBudgetHours11 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours11 ELSE 0 END, + basis.CurrentYearBudgetHours12 = CASE WHEN fs.VariabilityID = 1 THEN total.CurrentYearBudgetHours12 ELSE 0 END + FROM + [fp].[StaffingHistory] basis + INNER JOIN [fp].[Staffing] fs ON basis.StaffingID = fs.StaffingID + INNER JOIN #FilteredTotals total + ON total.DepartmentID = fs.DepartmentID + AND total.JobCodeID = fs.JobCodeID + AND total.PayCodeGroupID = fs.PayCodeGroupID + AND total.EmployeeID = fs.EmployeeID + LEFT JOIN #Variability fv + ON fv.DepartmentID = fs.DepartmentID + AND fv.JobCodeID = fs.JobCodeID + AND fv.PayCodeGroupID = fs.PayCodeGroupID + AND fv.EmployeeID = fs.EmployeeID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.SubsectionID = 4 + + END + + -- Cleaning up variable records where flexMethod = 6 (Fixed) AND variabilityID = 2 (Variable) AND unitTypeID = 144 or 172 (Hours Per UOS or FTEs) + CREATE TABLE #variableStaffingRecordsToCleanUp ( StaffingID int ) + + IF @isFilterPresent = 0 BEGIN + INSERT INTO #variableStaffingRecordsToCleanUp + SELECT fs.StaffingID + FROM [fp].[Staffing] fs + INNER JOIN [fp].[EntityGroupConfig] egc ON fs.EntityGroupConfigID = egc.EntityGroupConfigID + LEFT JOIN #Variability v on fs.DepartmentID = v.DepartmentID + AND fs.JobCodeID = v.JobCodeID + AND fs.PayCodeGroupID = v.PayCodeGroupID + AND fs.EmployeeID = v.EmployeeID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND (v.FixedPercentage = 1 OR v.FixedPercentage is NULL) + AND fs.VariabilityID = 2 --AND (fs.UnitTypeID = 144 OR fs.UnitTypeID = 172) + END ELSE BEGIN + INSERT INTO #variableStaffingRecordsToCleanUp + SELECT fs.StaffingID + FROM [fp].[Staffing] fs + INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID + INNER JOIN [fp].[EntityGroupConfig] egc ON fs.EntityGroupConfigID = egc.EntityGroupConfigID + LEFT JOIN #Variability v on fs.DepartmentID = v.DepartmentID + and fs.JobCodeID = v.JobCodeID + AND fs.PayCodeGroupID = v.PayCodeGroupID + AND fs.EmployeeID = v.EmployeeID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND (v.FixedPercentage = 1 OR v.FixedPercentage is NULL) + AND fs.VariabilityID = 2 --AND (fs.UnitTypeID = 144 OR fs.UnitTypeID = 172) + END + + UPDATE fs SET + fs.PriorYearActualFTEs01 = 0, + fs.PriorYearActualFTEs02 = 0, + fs.PriorYearActualFTEs03 = 0, + fs.PriorYearActualFTEs04 = 0, + fs.PriorYearActualFTEs05 = 0, + fs.PriorYearActualFTEs06 = 0, + fs.PriorYearActualFTEs07 = 0, + fs.PriorYearActualFTEs08 = 0, + fs.PriorYearActualFTEs09 = 0, + fs.PriorYearActualFTEs10 = 0, + fs.PriorYearActualFTEs11 = 0, + fs.PriorYearActualFTEs12 = 0, + fs.ActualYTDFTEs01 = 0, + fs.ActualYTDFTEs02 = 0, + fs.ActualYTDFTEs03 = 0, + fs.ActualYTDFTEs04 = 0, + fs.ActualYTDFTEs05 = 0, + fs.ActualYTDFTEs06 = 0, + fs.ActualYTDFTEs07 = 0, + fs.ActualYTDFTEs08 = 0, + fs.ActualYTDFTEs09 = 0, + fs.ActualYTDFTEs10 = 0, + fs.ActualYTDFTEs11 = 0, + fs.ActualYTDFTEs12 = 0, + fs.CurrentYearBudgetFTEs01 = 0, + fs.CurrentYearBudgetFTEs02 = 0, + fs.CurrentYearBudgetFTEs03 = 0, + fs.CurrentYearBudgetFTEs04 = 0, + fs.CurrentYearBudgetFTEs05 = 0, + fs.CurrentYearBudgetFTEs06 = 0, + fs.CurrentYearBudgetFTEs07 = 0, + fs.CurrentYearBudgetFTEs08 = 0, + fs.CurrentYearBudgetFTEs09 = 0, + fs.CurrentYearBudgetFTEs10 = 0, + fs.CurrentYearBudgetFTEs11 = 0, + fs.CurrentYearBudgetFTEs12 = 0 + FROM [fp].[StaffingHistory] fs + INNER JOIN #variableStaffingRecordsToCleanUp c ON c.StaffingID = fs.StaffingID + + END +GO + + +--------------------------------------------- + +-- fp.procApplyVariabilityToStaffing_InitialPlan +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2024-10-24 MY JAZZ-78967 Initial Creation +*************************************************************/ +CREATE PROCEDURE [fp].[procApplyVariabilityToStaffing_InitialPlan] + @EntityGroupConfigID INT, + @FiscalYearID INT, + @MonthsLoaded INT, + @ProjectionFiscalYearID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 -- WARNING: This will still update records, this just gives you a bit on insight on the temp tables. +WITH RECOMPILE +AS +BEGIN + + SET NOCOUNT ON + + IF OBJECT_ID('tempdb..#FilteringTable') IS NOT NULL DROP TABLE #FilteringTable + IF OBJECT_ID('tempdb..#BudgetWorkingHours') IS NOT NULL DROP TABLE #BudgetWorkingHours + IF OBJECT_ID('tempdb..#preSpreadFixedVar') IS NOT NULL DROP TABLE #preSpreadFixedVar + IF OBJECT_ID('tempdb..#preSpreadFixedVarDollars') IS NOT NULL DROP TABLE #preSpreadFixedVarDollars + IF OBJECT_ID('tempdb..#spreadFixedVar') IS NOT NULL DROP TABLE #spreadFixedVar + IF OBJECT_ID('tempdb..#Totals') IS NOT NULL DROP TABLE #Totals + IF OBJECT_ID('tempdb..#fteTemp') IS NOT NULL DROP TABLE #fteTemp + IF OBJECT_ID('tempdb..#flatFteTemp') IS NOT NULL DROP TABLE #flatFteTemp + IF OBJECT_ID('tempdb..#MonthsLoadedTotal') IS NOT NULL DROP TABLE #MonthsLoadedTotal + IF OBJECT_ID('tempdb..#ProjectionWorkingHours') IS NOT NULL DROP TABLE #ProjectionWorkingHours + IF OBJECT_ID('tempdb..#ProjectionYTD') IS NOT NULL DROP TABLE #ProjectionYTD + IF OBJECT_ID('tempdb..#HoursAndWorkingHours') IS NOT NULL DROP TABLE #HoursAndWorkingHours + IF OBJECT_ID('tempdb..#DollarTotals') IS NOT NULL DROP TABLE #DollarTotals + IF OBJECT_ID('tempdb..#HoursForFteUpdate') IS NOT NULL DROP TABLE #HoursForFteUpdate + IF OBJECT_ID('tempdb..#Variability') IS NOT NULL DROP TABLE #Variability + IF OBJECT_ID('tempdb..#variableStaffingRecordsToCleanUp') IS NOT NULL DROP TABLE #variableStaffingRecordsToCleanUp + IF OBJECT_ID('tempdb..#combinedStaffingHoursAboveVariability') IS NOT NULL DROP TABLE #combinedStaffingHoursAboveVariability + IF OBJECT_ID('tempdb..#combinedStaffingDollarsAboveVariability') IS NOT NULL DROP TABLE #combinedStaffingDollarsAboveVariability + + CREATE TABLE #FilteringTable ( + DepartmentID INT + ,INDEX ix_1 NONCLUSTERED (DepartmentID) + ) + + INSERT INTO #FilteringTable (DepartmentID) + SELECT DepartmentID + FROM @SourceDimensionality + + DECLARE @EntityGroupConfigGUID UNIQUEIDENTIFIER; + SET @EntityGroupConfigGUID = (SELECT EntityGroupConfigGUID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID) + + DECLARE @isFilterPresent int = (SELECT COUNT(*) FROM #FilteringTable) + + IF (@isFilterPresent=0) BEGIN + INSERT INTO #FilteringTable (DepartmentID) + SELECT DISTINCT DepartmentID FROM fp.Staffing WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + DECLARE @IsProviderPlanningEnabled BIT + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled + FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID + WHERE EntityGroupConfigID = @EntityGroupConfigID; + + DECLARE @ProviderSubsectionID INT = 4; + DECLARE @StaffingSubsectionID INT = 3; + + DECLARE @SourceFiscalYearID int + DECLARE @SourceTimeClassID int + SELECT @SourceTimeClassID = PayrollTimeClassID, @SourceFiscalYearID = PayrollFiscalYearID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID + DECLARE @IsAnnualized BIT = (CASE WHEN @SourceFiscalYearID = @ProjectionFiscalYearID AND @SourceTimeClassID = 1 AND @MonthsLoaded < 12 THEN 1 ELSE 0 END) + + CREATE TABLE #Variability (DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, ProviderLineItemID INT, EmployeeID INT, FixedPercentage DECIMAL(38, 6)) + + INSERT INTO #Variability (DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID, FixedPercentage) + SELECT v.DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID, MAX(FixedPercentage) AS FixedPercentage + FROM [fp].[viewFactStaffingVariability] v + INNER JOIN #FilteringTable f ON v.DepartmentID = f.DepartmentID + WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID + GROUP BY v.DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID + + -- Pre spread values. Basically we need the fixed/variable split before we spread it evenly + CREATE TABLE #preSpreadFixedVar ( StaffingID int, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, EmployeeID INT, VariabilityID INT, ProductiveClassID INT, EntityGroupConfigID INT, + ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int, + InitialBudget01 DECIMAL(19,8), InitialBudget02 DECIMAL(19,8), InitialBudget03 DECIMAL(19,8), InitialBudget04 DECIMAL(19,8), + InitialBudget05 DECIMAL(19,8), InitialBudget06 DECIMAL(19,8), InitialBudget07 DECIMAL(19,8), InitialBudget08 DECIMAL(19,8), + InitialBudget09 DECIMAL(19,8), InitialBudget10 DECIMAL(19,8), InitialBudget11 DECIMAL(19,8), InitialBudget12 DECIMAL(19,8), + InitialBudgetTotal DECIMAL(19,8), + InitialProjection01 DECIMAL(19,8), InitialProjection02 DECIMAL(19,8), InitialProjection03 DECIMAL(19,8), InitialProjection04 DECIMAL(19,8), + InitialProjection05 DECIMAL(19,8), InitialProjection06 DECIMAL(19,8), InitialProjection07 DECIMAL(19,8), InitialProjection08 DECIMAL(19,8), + InitialProjection09 DECIMAL(19,8), InitialProjection10 DECIMAL(19,8), InitialProjection11 DECIMAL(19,8), InitialProjection12 DECIMAL(19,8), + InitialProjectionTotal DECIMAL(19,8), + INDEX ix_sfv_1 NONCLUSTERED (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID) + ) + -- we need this for projection dollars months loaded to be allocated to fixed/variable properly for when no hours exist but dollars do (jazz-66611) + CREATE TABLE #preSpreadFixedVarDollars ( StaffingID int, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, EmployeeID INT, VariabilityID INT, ProductiveClassID INT, EntityGroupConfigID INT, + ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int, + InitialProjection01 DECIMAL(19,8), InitialProjection02 DECIMAL(19,8), InitialProjection03 DECIMAL(19,8), InitialProjection04 DECIMAL(19,8), + InitialProjection05 DECIMAL(19,8), InitialProjection06 DECIMAL(19,8), InitialProjection07 DECIMAL(19,8), InitialProjection08 DECIMAL(19,8), + InitialProjection09 DECIMAL(19,8), InitialProjection10 DECIMAL(19,8), InitialProjection11 DECIMAL(19,8), InitialProjection12 DECIMAL(19,8) + INDEX ix_sfv_1 NONCLUSTERED (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID) + ) + + CREATE TABLE #spreadFixedVar ( StaffingID int, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, EmployeeID INT, VariabilityID INT, ProductiveClassID INT, EntityGroupConfigID INT, + ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int, + InitialBudget01 DECIMAL(19,8), InitialBudget02 DECIMAL(19,8), InitialBudget03 DECIMAL(19,8), InitialBudget04 DECIMAL(19,8), + InitialBudget05 DECIMAL(19,8), InitialBudget06 DECIMAL(19,8), InitialBudget07 DECIMAL(19,8), InitialBudget08 DECIMAL(19,8), + InitialBudget09 DECIMAL(19,8), InitialBudget10 DECIMAL(19,8), InitialBudget11 DECIMAL(19,8), InitialBudget12 DECIMAL(19,8), + InitialBudgetTotal DECIMAL(19,8), + InitialProjection01 DECIMAL(19,8), InitialProjection02 DECIMAL(19,8), InitialProjection03 DECIMAL(19,8), InitialProjection04 DECIMAL(19,8), + InitialProjection05 DECIMAL(19,8), InitialProjection06 DECIMAL(19,8), InitialProjection07 DECIMAL(19,8), InitialProjection08 DECIMAL(19,8), + InitialProjection09 DECIMAL(19,8), InitialProjection10 DECIMAL(19,8), InitialProjection11 DECIMAL(19,8), InitialProjection12 DECIMAL(19,8), + InitialProjectionTotal DECIMAL(19,8), + INDEX ix_sfv_1 NONCLUSTERED (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID) + ) + + -- We need to find the totals above Variability so we can resplit the data. + SELECT + fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, + SUM(fs.SampledBudgetHours01) AS SampledBudgetHours01, + SUM(fs.SampledBudgetHours02) AS SampledBudgetHours02, + SUM(fs.SampledBudgetHours03) AS SampledBudgetHours03, + SUM(fs.SampledBudgetHours04) AS SampledBudgetHours04, + SUM(fs.SampledBudgetHours05) AS SampledBudgetHours05, + SUM(fs.SampledBudgetHours06) AS SampledBudgetHours06, + SUM(fs.SampledBudgetHours07) AS SampledBudgetHours07, + SUM(fs.SampledBudgetHours08) AS SampledBudgetHours08, + SUM(fs.SampledBudgetHours09) AS SampledBudgetHours09, + SUM(fs.SampledBudgetHours10) AS SampledBudgetHours10, + SUM(fs.SampledBudgetHours11) AS SampledBudgetHours11, + SUM(fs.SampledBudgetHours12) AS SampledBudgetHours12, + SUM(fs.SampledBudgetHoursTotal) AS SampledBudgetHoursTotal, + SUM(fs.SampledProjectionHours01) AS SampledProjectionHours01, + SUM(fs.SampledProjectionHours02) AS SampledProjectionHours02, + SUM(fs.SampledProjectionHours03) AS SampledProjectionHours03, + SUM(fs.SampledProjectionHours04) AS SampledProjectionHours04, + SUM(fs.SampledProjectionHours05) AS SampledProjectionHours05, + SUM(fs.SampledProjectionHours06) AS SampledProjectionHours06, + SUM(fs.SampledProjectionHours07) AS SampledProjectionHours07, + SUM(fs.SampledProjectionHours08) AS SampledProjectionHours08, + SUM(fs.SampledProjectionHours09) AS SampledProjectionHours09, + SUM(fs.SampledProjectionHours10) AS SampledProjectionHours10, + SUM(fs.SampledProjectionHours11) AS SampledProjectionHours11, + SUM(fs.SampledProjectionHours12) AS SampledProjectionHours12 + INTO #combinedStaffingHoursAboveVariability + FROM [fp].[Staffing] fs + INNER JOIN #FilteringTable ft on (ft.DepartmentID = fs.DepartmentID ) + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND (@IsProviderPlanningEnabled = 0 OR SubsectionID <> @ProviderSubsectionID) -- exclude provider + GROUP BY fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, + fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID + + IF @IsDebug = 1 + BEGIN + SELECT '#combinedStaffingHoursAboveVariability', * FROM #combinedStaffingHoursAboveVariability + END + + -- We need to find the totals above Variability so we can resplit the data. + SELECT + fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, + SUM(fs.SampledBudgetDollars01) AS SampledBudgetDollars01, + SUM(fs.SampledBudgetDollars02) AS SampledBudgetDollars02, + SUM(fs.SampledBudgetDollars03) AS SampledBudgetDollars03, + SUM(fs.SampledBudgetDollars04) AS SampledBudgetDollars04, + SUM(fs.SampledBudgetDollars05) AS SampledBudgetDollars05, + SUM(fs.SampledBudgetDollars06) AS SampledBudgetDollars06, + SUM(fs.SampledBudgetDollars07) AS SampledBudgetDollars07, + SUM(fs.SampledBudgetDollars08) AS SampledBudgetDollars08, + SUM(fs.SampledBudgetDollars09) AS SampledBudgetDollars09, + SUM(fs.SampledBudgetDollars10) AS SampledBudgetDollars10, + SUM(fs.SampledBudgetDollars11) AS SampledBudgetDollars11, + SUM(fs.SampledBudgetDollars12) AS SampledBudgetDollars12, + SUM(fs.SampledBudgetDollarsTotal) AS SampledBudgetDollarsTotal, + SUM(fs.SampledProjectionDollars01) AS SampledProjectionDollars01, + SUM(fs.SampledProjectionDollars02) AS SampledProjectionDollars02, + SUM(fs.SampledProjectionDollars03) AS SampledProjectionDollars03, + SUM(fs.SampledProjectionDollars04) AS SampledProjectionDollars04, + SUM(fs.SampledProjectionDollars05) AS SampledProjectionDollars05, + SUM(fs.SampledProjectionDollars06) AS SampledProjectionDollars06, + SUM(fs.SampledProjectionDollars07) AS SampledProjectionDollars07, + SUM(fs.SampledProjectionDollars08) AS SampledProjectionDollars08, + SUM(fs.SampledProjectionDollars09) AS SampledProjectionDollars09, + SUM(fs.SampledProjectionDollars10) AS SampledProjectionDollars10, + SUM(fs.SampledProjectionDollars11) AS SampledProjectionDollars11, + SUM(fs.SampledProjectionDollars12) AS SampledProjectionDollars12 + INTO #combinedStaffingDollarsAboveVariability + FROM [fp].[Staffing] fs + INNER JOIN #FilteringTable ft on (ft.DepartmentID = fs.DepartmentID ) + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND (@IsProviderPlanningEnabled = 0 OR SubsectionID <> @ProviderSubsectionID) -- exclude provider + GROUP BY fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, + fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID + + IF @IsDebug = 1 + BEGIN + SELECT '#combinedStaffingDollarsAboveVariability', * FROM #combinedStaffingDollarsAboveVariability + END + + INSERT INTO #preSpreadFixedVar (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, VariabilityID, ProductiveClassID, EntityGroupConfigID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, + InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, InitialBudgetTotal, + InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12) + SELECT + fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.VariabilityID, fs.ProductiveClassID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours01) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours01) END as InitialBudgetHours01, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours02) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours02) END as InitialBudgetHours02, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours03) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours03) END as InitialBudgetHours03, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours04) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours04) END as InitialBudgetHours04, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours05) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours05) END as InitialBudgetHours05, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours06) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours06) END as InitialBudgetHours06, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours07) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours07) END as InitialBudgetHours07, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours08) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours08) END as InitialBudgetHours08, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours09) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours09) END as InitialBudgetHours09, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours10) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours10) END as InitialBudgetHours10, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours11) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours11) END as InitialBudgetHours11, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHours12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHours12) END as InitialBudgetHours12, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetHoursTotal) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetHoursTotal) END as InitialBudgetHoursTotal, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours01 END SampledProjectionHours01, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours02 END SampledProjectionHours02, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours03 END SampledProjectionHours03, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours04 END SampledProjectionHours04, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours05 END SampledProjectionHours05, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours06 END SampledProjectionHours06, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours07 END SampledProjectionHours07, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours08 END SampledProjectionHours08, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours09 END SampledProjectionHours09, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours10 END SampledProjectionHours10, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours11 END SampledProjectionHours11, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionHours12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionHours12 END SampledProjectionHours12 + FROM [fp].[Staffing] fs + INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID + INNER JOIN #combinedStaffingHoursAboveVariability total ON + fs.DepartmentID = total.DepartmentID + AND fs.JobCodeID = total.JobCodeID + AND fs.PayCodeGroupID = total.PayCodeGroupID + AND fs.EmployeeID = total.EmployeeID + AND fs.ProductiveClassID = total.ProductiveClassID + AND fs.EntityGroupConfigID = total.EntityGroupConfigID + AND fs.ProviderID = total.ProviderID + AND fs.ProviderTypeID = total.ProviderTypeID + AND fs.ProviderSpecialtyID = total.ProviderSpecialtyID + AND fs.ProviderLineItemID = total.ProviderLineItemID + AND fs.SubsectionID = total.SubsectionID + LEFT JOIN #Variability fv + ON fv.DepartmentID = fs.DepartmentID + AND fv.JobCodeID = fs.JobCodeID + AND fv.PayCodeGroupID = fs.PayCodeGroupID + AND fv.ProviderLineItemID = fs.ProviderLineItemID + AND fv.EmployeeID = fs.EmployeeID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID <> @ProviderSubsectionID) -- exclude provider + + INSERT INTO #preSpreadFixedVarDollars (StaffingID, DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, VariabilityID, ProductiveClassID, EntityGroupConfigID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, + InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12) + SELECT + fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.VariabilityID, fs.ProductiveClassID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars01 END SampledProjectionDollars01, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars02 END SampledProjectionDollars02, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars03 END SampledProjectionDollars03, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars04 END SampledProjectionDollars04, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars05 END SampledProjectionDollars05, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars06 END SampledProjectionDollars06, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars07 END SampledProjectionDollars07, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars08 END SampledProjectionDollars08, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars09 END SampledProjectionDollars09, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars10 END SampledProjectionDollars10, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars11 END SampledProjectionDollars11, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars12 END SampledProjectionDollars12 + FROM [fp].[Staffing] fs + INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID + INNER JOIN #combinedStaffingDollarsAboveVariability total ON + fs.DepartmentID = total.DepartmentID + AND fs.JobCodeID = total.JobCodeID + AND fs.PayCodeGroupID = total.PayCodeGroupID + AND fs.EmployeeID = total.EmployeeID + AND fs.ProductiveClassID = total.ProductiveClassID + AND fs.EntityGroupConfigID = total.EntityGroupConfigID + AND fs.ProviderID = total.ProviderID + AND fs.ProviderTypeID = total.ProviderTypeID + AND fs.ProviderSpecialtyID = total.ProviderSpecialtyID + AND fs.ProviderLineItemID = total.ProviderLineItemID + AND fs.SubsectionID = total.SubsectionID + LEFT JOIN #Variability fv + ON fv.DepartmentID = fs.DepartmentID + AND fv.JobCodeID = fs.JobCodeID + AND fv.PayCodeGroupID = fs.PayCodeGroupID + AND fv.ProviderLineItemID = fs.ProviderLineItemID + AND fv.EmployeeID = fs.EmployeeID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID <> @ProviderSubsectionID) -- exclude provider + + IF @IsDebug = 1 + BEGIN + SELECT '#preSpreadFixedVar', * FROM #preSpreadFixedVar + END + + -- We no longer need this after splitting out the hours + IF OBJECT_ID('tempdb..#combinedStaffingHoursAboveVariability') IS NOT NULL DROP TABLE #combinedStaffingHoursAboveVariability + + SELECT fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, fs.VariabilityID, + Month01, Month02, Month03, Month04, + Month05, Month06, Month07, Month08, + Month09, Month10, Month11, Month12, MonthYearly -- Jazz-1796 + INTO #BudgetWorkingHours + FROM [fp].[Staffing] fs + INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID + INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @FiscalYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND (@IsProviderPlanningEnabled = 0 OR SubsectionID <> @ProviderSubsectionID) -- exclude provider + + + SELECT fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.EntityGroupConfigID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, fs.VariabilityID, + pwh.Month01, pwh.Month02, pwh.Month03, pwh.Month04, + pwh.Month05, pwh.Month06, pwh.Month07, pwh.Month08, + pwh.Month09, pwh.Month10, pwh.Month11, pwh.Month12, pwh.MonthYearly -- Jazz-1796 + INTO #ProjectionWorkingHours + FROM #BudgetWorkingHours fs + INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] pwh on pwh.FiscalYearID = @ProjectionFiscalYearID and pwh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + + IF @IsDebug = 1 + BEGIN + SELECT '#BudgetWorkingHours', * FROM #BudgetWorkingHours ORDER BY DepartmentID, JobCodeID, PayCodeGroupID + SELECT '#ProjectionWorkingHours', * FROM #ProjectionWorkingHours ORDER BY DepartmentID, JobCodeID, PayCodeGroupID + END + + -- Projected hours should vary by working hours for fixed JobCodes + UPDATE + fs + SET + InitialBudgetHours01 = psfv.InitialBudget01, + InitialBudgetHours02 = psfv.InitialBudget02, + InitialBudgetHours03 = psfv.InitialBudget03, + InitialBudgetHours04 = psfv.InitialBudget04, + InitialBudgetHours05 = psfv.InitialBudget05, + InitialBudgetHours06 = psfv.InitialBudget06, + InitialBudgetHours07 = psfv.InitialBudget07, + InitialBudgetHours08 = psfv.InitialBudget08, + InitialBudgetHours09 = psfv.InitialBudget09, + InitialBudgetHours10 = psfv.InitialBudget10, + InitialBudgetHours11 = psfv.InitialBudget11, + InitialBudgetHours12 = psfv.InitialBudget12, + InitialProjectionHours01 = psfv.InitialProjection01, + InitialProjectionHours02 = psfv.InitialProjection02, + InitialProjectionHours03 = psfv.InitialProjection03, + InitialProjectionHours04 = psfv.InitialProjection04, + InitialProjectionHours05 = psfv.InitialProjection05, + InitialProjectionHours06 = psfv.InitialProjection06, + InitialProjectionHours07 = psfv.InitialProjection07, + InitialProjectionHours08 = psfv.InitialProjection08, + InitialProjectionHours09 = psfv.InitialProjection09, + InitialProjectionHours10 = psfv.InitialProjection10, + InitialProjectionHours11 = psfv.InitialProjection11, + InitialProjectionHours12 = psfv.InitialProjection12 + FROM [fp].[Staffing] fs + INNER JOIN #preSpreadFixedVar psfv on fs.StaffingID = psfv.StaffingID -- we need this because we need the actual values for months loaded projection unfortunately + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.ProductiveClassID != 4 -- Ignore Dollars Only + + UPDATE fte SET + fte.InitialBudgetFTEs01 = fte.InitialBudgetHours01 / h.Month01, + fte.InitialBudgetFTEs02 = fte.InitialBudgetHours02 / h.Month02, + fte.InitialBudgetFTEs03 = fte.InitialBudgetHours03 / h.Month03, + fte.InitialBudgetFTEs04 = fte.InitialBudgetHours04 / h.Month04, + fte.InitialBudgetFTEs05 = fte.InitialBudgetHours05 / h.Month05, + fte.InitialBudgetFTEs06 = fte.InitialBudgetHours06 / h.Month06, + fte.InitialBudgetFTEs07 = fte.InitialBudgetHours07 / h.Month07, + fte.InitialBudgetFTEs08 = fte.InitialBudgetHours08 / h.Month08, + fte.InitialBudgetFTEs09 = fte.InitialBudgetHours09 / h.Month09, + fte.InitialBudgetFTEs10 = fte.InitialBudgetHours10 / h.Month10, + fte.InitialBudgetFTEs11 = fte.InitialBudgetHours11 / h.Month11, + fte.InitialBudgetFTEs12 = fte.InitialBudgetHours12 / h.Month12, + fte.InitialProjectionFTEs01 = fte.InitialProjectionHours01 / pwh.Month01, + fte.InitialProjectionFTEs02 = fte.InitialProjectionHours02 / pwh.Month02, + fte.InitialProjectionFTEs03 = fte.InitialProjectionHours03 / pwh.Month03, + fte.InitialProjectionFTEs04 = fte.InitialProjectionHours04 / pwh.Month04, + fte.InitialProjectionFTEs05 = fte.InitialProjectionHours05 / pwh.Month05, + fte.InitialProjectionFTEs06 = fte.InitialProjectionHours06 / pwh.Month06, + fte.InitialProjectionFTEs07 = fte.InitialProjectionHours07 / pwh.Month07, + fte.InitialProjectionFTEs08 = fte.InitialProjectionHours08 / pwh.Month08, + fte.InitialProjectionFTEs09 = fte.InitialProjectionHours09 / pwh.Month09, + fte.InitialProjectionFTEs10 = fte.InitialProjectionHours10 / pwh.Month10, + fte.InitialProjectionFTEs11 = fte.InitialProjectionHours11 / pwh.Month11, + fte.InitialProjectionFTEs12 = fte.InitialProjectionHours12 / pwh.Month12 + FROM [fp].[Staffing] fte + INNER JOIN #BudgetWorkingHours h ON h.StaffingID = fte.StaffingID -- we can use StaffingID now instead of all the dimensionality since it's the same row + INNER JOIN #ProjectionWorkingHours pwh ON pwh.StaffingID = fte.StaffingID + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc ON h.PayCodeGroupID = exc.PayCodeGroupID + WHERE fte.EntityGroupConfigID = @EntityGroupConfigID + AND exc.PayCodeGroupID IS NULL + + ------ Dollars ---------------------------------------------------- + UPDATE + fs + SET + fs.InitialBudgetDollars01 = fs.InitialBudgetHours01 * wr.InitialBudget01, + fs.InitialBudgetDollars02 = fs.InitialBudgetHours02 * wr.InitialBudget02, + fs.InitialBudgetDollars03 = fs.InitialBudgetHours03 * wr.InitialBudget03, + fs.InitialBudgetDollars04 = fs.InitialBudgetHours04 * wr.InitialBudget04, + fs.InitialBudgetDollars05 = fs.InitialBudgetHours05 * wr.InitialBudget05, + fs.InitialBudgetDollars06 = fs.InitialBudgetHours06 * wr.InitialBudget06, + fs.InitialBudgetDollars07 = fs.InitialBudgetHours07 * wr.InitialBudget07, + fs.InitialBudgetDollars08 = fs.InitialBudgetHours08 * wr.InitialBudget08, + fs.InitialBudgetDollars09 = fs.InitialBudgetHours09 * wr.InitialBudget09, + fs.InitialBudgetDollars10 = fs.InitialBudgetHours10 * wr.InitialBudget10, + fs.InitialBudgetDollars11 = fs.InitialBudgetHours11 * wr.InitialBudget11, + fs.InitialBudgetDollars12 = fs.InitialBudgetHours12 * wr.InitialBudget12, + fs.InitialProjectionDollars01 = CASE WHEN @MonthsLoaded >= 1 THEN psfv.InitialProjection01 ELSE fs.InitialProjectionHours01 * wr.InitialProjection01 END, + fs.InitialProjectionDollars02 = CASE WHEN @MonthsLoaded >= 2 THEN psfv.InitialProjection02 ELSE fs.InitialProjectionHours02 * wr.InitialProjection02 END, + fs.InitialProjectionDollars03 = CASE WHEN @MonthsLoaded >= 3 THEN psfv.InitialProjection03 ELSE fs.InitialProjectionHours03 * wr.InitialProjection03 END, + fs.InitialProjectionDollars04 = CASE WHEN @MonthsLoaded >= 4 THEN psfv.InitialProjection04 ELSE fs.InitialProjectionHours04 * wr.InitialProjection04 END, + fs.InitialProjectionDollars05 = CASE WHEN @MonthsLoaded >= 5 THEN psfv.InitialProjection05 ELSE fs.InitialProjectionHours05 * wr.InitialProjection05 END, + fs.InitialProjectionDollars06 = CASE WHEN @MonthsLoaded >= 6 THEN psfv.InitialProjection06 ELSE fs.InitialProjectionHours06 * wr.InitialProjection06 END, + fs.InitialProjectionDollars07 = CASE WHEN @MonthsLoaded >= 7 THEN psfv.InitialProjection07 ELSE fs.InitialProjectionHours07 * wr.InitialProjection07 END, + fs.InitialProjectionDollars08 = CASE WHEN @MonthsLoaded >= 8 THEN psfv.InitialProjection08 ELSE fs.InitialProjectionHours08 * wr.InitialProjection08 END, + fs.InitialProjectionDollars09 = CASE WHEN @MonthsLoaded >= 9 THEN psfv.InitialProjection09 ELSE fs.InitialProjectionHours09 * wr.InitialProjection09 END, + fs.InitialProjectionDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN psfv.InitialProjection10 ELSE fs.InitialProjectionHours10 * wr.InitialProjection10 END, + fs.InitialProjectionDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN psfv.InitialProjection11 ELSE fs.InitialProjectionHours11 * wr.InitialProjection11 END, + fs.InitialProjectionDollars12 = CASE WHEN @MonthsLoaded >= 12 THEN psfv.InitialProjection12 ELSE fs.InitialProjectionHours12 * wr.InitialProjection12 END + FROM [fp].[Staffing] fs + INNER JOIN fp.StaffingWageRate wr on fs.StaffingWageRateID = wr.StaffingWageRateID + INNER JOIN #preSpreadFixedVarDollars psfv -- we need this unfortunately because we need the actual values for months loaded projection + ON psfv.StaffingID = fs.StaffingID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.ProductiveClassID <> 4 -- exclude 'Dollars-Only' + AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID <> @ProviderSubsectionID) -- exclude provider + + -- now update dollars-only productive class + DELETE FROM #spreadFixedVar + + INSERT INTO #combinedStaffingDollarsAboveVariability (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProductiveClassID, EntityGroupConfigID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, SampledBudgetDollarsTotal, + SampledProjectionDollars01, SampledProjectionDollars02, SampledProjectionDollars03, SampledProjectionDollars04, SampledProjectionDollars05, SampledProjectionDollars06, + SampledProjectionDollars07, SampledProjectionDollars08, SampledProjectionDollars09, SampledProjectionDollars10, SampledProjectionDollars11, SampledProjectionDollars12) + SELECT + fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, + fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, + SUM(fs.SampledBudgetDollarsTotal) AS SampledBudgetDollarsTotal, + SUM(fs.SampledProjectionDollars01) AS SampledProjectionDollars01, + SUM(fs.SampledProjectionDollars02) AS SampledProjectionDollars02, + SUM(fs.SampledProjectionDollars03) AS SampledProjectionDollars03, + SUM(fs.SampledProjectionDollars04) AS SampledProjectionDollars04, + SUM(fs.SampledProjectionDollars05) AS SampledProjectionDollars05, + SUM(fs.SampledProjectionDollars06) AS SampledProjectionDollars06, + SUM(fs.SampledProjectionDollars07) AS SampledProjectionDollars07, + SUM(fs.SampledProjectionDollars08) AS SampledProjectionDollars08, + SUM(fs.SampledProjectionDollars09) AS SampledProjectionDollars09, + SUM(fs.SampledProjectionDollars10) AS SampledProjectionDollars10, + SUM(fs.SampledProjectionDollars11) AS SampledProjectionDollars11, + SUM(fs.SampledProjectionDollars12) AS SampledProjectionDollars12 + FROM [fp].[Staffing] fs + INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.ProductiveClassID = 4 -- 'Dollars-Only' + AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID <> @ProviderSubsectionID) -- exclude provider + GROUP BY fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, + fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID + + INSERT INTO #spreadFixedVar (StaffingID, + InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, + InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12) + SELECT + fs.StaffingID, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars01, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars02, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars03, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars04, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars05, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars06, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars07, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars08, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars09, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars10, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars11, + CASE WHEN fs.VariabilityID = 1 + THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal - ((total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) )) + ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal - ((total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) )) + END as InitialBudgetDollars12, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars01 END SampledProjectionDollars01, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars02 END SampledProjectionDollars02, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars03 END SampledProjectionDollars03, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars04 END SampledProjectionDollars04, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars05 END SampledProjectionDollars05, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars06 END SampledProjectionDollars06, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars07 END SampledProjectionDollars07, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars08 END SampledProjectionDollars08, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars09 END SampledProjectionDollars09, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars10 END SampledProjectionDollars10, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars11 END SampledProjectionDollars11, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars12 END SampledProjectionDollars12 + FROM [fp].[Staffing] fs + INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID + INNER JOIN #combinedStaffingDollarsAboveVariability total ON + fs.DepartmentID = total.DepartmentID + AND fs.JobCodeID = total.JobCodeID + AND fs.PayCodeGroupID = total.PayCodeGroupID + AND fs.EmployeeID = total.EmployeeID + AND fs.ProductiveClassID = total.ProductiveClassID + AND fs.EntityGroupConfigID = total.EntityGroupConfigID + AND fs.ProviderID = total.ProviderID + AND fs.ProviderTypeID = total.ProviderTypeID + AND fs.ProviderSpecialtyID = total.ProviderSpecialtyID + AND fs.ProviderLineItemID = total.ProviderLineItemID + AND fs.SubsectionID = total.SubsectionID + LEFT JOIN #Variability fv ON + fv.DepartmentID = fs.DepartmentID + AND fv.JobCodeID = fs.JobCodeID + AND fv.PayCodeGroupID = fs.PayCodeGroupID + AND fv.EmployeeID = fs.EmployeeID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.ProductiveClassID = 4 -- 'Dollars-Only' + AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID <> @ProviderSubsectionID) -- exclude provider + + IF @IsDebug = 1 + BEGIN + SELECT '#combinedStaffingDollarsAboveVariability', * FROM #combinedStaffingDollarsAboveVariability + SELECT '#spreadFixedVar - Dollars', * FROM #spreadFixedVar + END + + TRUNCATE TABLE #combinedStaffingDollarsAboveVariability; + + --------------------------- Provider Line Item variability --------------------------- + + INSERT INTO #combinedStaffingDollarsAboveVariability (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProductiveClassID, EntityGroupConfigID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, SampledBudgetDollarsTotal, + SampledProjectionDollars01, SampledProjectionDollars02, SampledProjectionDollars03, SampledProjectionDollars04, SampledProjectionDollars05, SampledProjectionDollars06, + SampledProjectionDollars07, SampledProjectionDollars08, SampledProjectionDollars09, SampledProjectionDollars10, SampledProjectionDollars11, SampledProjectionDollars12) + SELECT + fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, + fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, + SUM(fs.SampledBudgetDollarsTotal) AS SampledBudgetDollarsTotal, + SUM(fs.SampledProjectionDollars01) AS SampledProjectionDollars01, + SUM(fs.SampledProjectionDollars02) AS SampledProjectionDollars02, + SUM(fs.SampledProjectionDollars03) AS SampledProjectionDollars03, + SUM(fs.SampledProjectionDollars04) AS SampledProjectionDollars04, + SUM(fs.SampledProjectionDollars05) AS SampledProjectionDollars05, + SUM(fs.SampledProjectionDollars06) AS SampledProjectionDollars06, + SUM(fs.SampledProjectionDollars07) AS SampledProjectionDollars07, + SUM(fs.SampledProjectionDollars08) AS SampledProjectionDollars08, + SUM(fs.SampledProjectionDollars09) AS SampledProjectionDollars09, + SUM(fs.SampledProjectionDollars10) AS SampledProjectionDollars10, + SUM(fs.SampledProjectionDollars11) AS SampledProjectionDollars11, + SUM(fs.SampledProjectionDollars12) AS SampledProjectionDollars12 + FROM [fp].[Staffing] fs + INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND (@IsProviderPlanningEnabled = 1 AND fs.SubsectionID = @ProviderSubsectionID) -- provider + GROUP BY fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.EmployeeID, fs.ProductiveClassID, fs.EntityGroupConfigID, + fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID + + INSERT INTO #spreadFixedVar (StaffingID, + InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, + InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12) + SELECT + fs.StaffingID, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars01, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars02, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars03, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars04, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars05, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars06, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars07, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars08, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars09, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars10, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal/12) ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal/12) END as InitialBudgetDollars11, + CASE WHEN fs.VariabilityID = 1 + THEN COALESCE(fv.FixedPercentage, 1.0) * (total.SampledBudgetDollarsTotal - ((total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) )) + ELSE COALESCE(1 - fv.FixedPercentage, 0) * (total.SampledBudgetDollarsTotal - ((total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) + (total.SampledBudgetDollarsTotal / 12) )) + END as InitialBudgetDollars12, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars01 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars01 END SampledProjectionDollars01, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars02 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars02 END SampledProjectionDollars02, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars03 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars03 END SampledProjectionDollars03, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars04 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars04 END SampledProjectionDollars04, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars05 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars05 END SampledProjectionDollars05, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars06 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars06 END SampledProjectionDollars06, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars07 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars07 END SampledProjectionDollars07, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars08 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars08 END SampledProjectionDollars08, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars09 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars09 END SampledProjectionDollars09, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars10 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars10 END SampledProjectionDollars10, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars11 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars11 END SampledProjectionDollars11, + CASE WHEN fs.VariabilityID = 1 THEN COALESCE(fv.FixedPercentage, 1.0) * total.SampledProjectionDollars12 ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionDollars12 END SampledProjectionDollars12 + FROM [fp].[Staffing] fs + INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID + INNER JOIN #combinedStaffingDollarsAboveVariability total ON + fs.DepartmentID = total.DepartmentID + AND fs.JobCodeID = total.JobCodeID + AND fs.PayCodeGroupID = total.PayCodeGroupID + AND fs.EmployeeID = total.EmployeeID + AND fs.ProductiveClassID = total.ProductiveClassID + AND fs.EntityGroupConfigID = total.EntityGroupConfigID + AND fs.ProviderID = total.ProviderID + AND fs.ProviderTypeID = total.ProviderTypeID + AND fs.ProviderSpecialtyID = total.ProviderSpecialtyID + AND fs.ProviderLineItemID = total.ProviderLineItemID + AND fs.SubsectionID = total.SubsectionID + LEFT JOIN #Variability fv -- if this is a filtered call, filtering was done here + ON fv.DepartmentID = fs.DepartmentID + AND fv.JobCodeID = fs.JobCodeID + AND fv.PayCodeGroupID = fs.PayCodeGroupID + AND fv.ProviderLineItemID = fs.ProviderLineItemID + AND fv.EmployeeID = fs.EmployeeID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID + AND (@IsProviderPlanningEnabled = 1 AND fs.SubsectionID = @ProviderSubsectionID) -- provider + + IF @IsDebug = 1 + BEGIN + SELECT '#combinedStaffingDollarsAboveVariability - Provider Line Item variability', * FROM #combinedStaffingDollarsAboveVariability + SELECT '#spreadFixedVar - Provider Line Item variability', * FROM #spreadFixedVar + END + + -- update initial budget for dollars + UPDATE fs + SET + fs.InitialBudgetDollars01 = sfv.InitialBudget01, + fs.InitialBudgetDollars02 = sfv.InitialBudget02, + fs.InitialBudgetDollars03 = sfv.InitialBudget03, + fs.InitialBudgetDollars04 = sfv.InitialBudget04, + fs.InitialBudgetDollars05 = sfv.InitialBudget05, + fs.InitialBudgetDollars06 = sfv.InitialBudget06, + fs.InitialBudgetDollars07 = sfv.InitialBudget07, + fs.InitialBudgetDollars08 = sfv.InitialBudget08, + fs.InitialBudgetDollars09 = sfv.InitialBudget09, + fs.InitialBudgetDollars10 = sfv.InitialBudget10, + fs.InitialBudgetDollars11 = sfv.InitialBudget11, + fs.InitialBudgetDollars12 = sfv.InitialBudget12 + FROM [fp].[Staffing] fs + INNER JOIN #spreadFixedVar sfv ON fs.StaffingID = sfv.StaffingID + + -- update initial projection for dollars + UPDATE fs + SET + fs.InitialProjectionDollars01 = sfv.InitialProjection01, + fs.InitialProjectionDollars02 = sfv.InitialProjection02, + fs.InitialProjectionDollars03 = sfv.InitialProjection03, + fs.InitialProjectionDollars04 = sfv.InitialProjection04, + fs.InitialProjectionDollars05 = sfv.InitialProjection05, + fs.InitialProjectionDollars06 = sfv.InitialProjection06, + fs.InitialProjectionDollars07 = sfv.InitialProjection07, + fs.InitialProjectionDollars08 = sfv.InitialProjection08, + fs.InitialProjectionDollars09 = sfv.InitialProjection09, + fs.InitialProjectionDollars10 = sfv.InitialProjection10, + fs.InitialProjectionDollars11 = sfv.InitialProjection11, + fs.InitialProjectionDollars12 = sfv.InitialProjection12 + FROM [fp].[Staffing] fs + INNER JOIN #spreadFixedVar sfv ON fs.StaffingID = sfv.StaffingID + + -- Cleaning up records where flexMethod = 6 (Fixed) AND variabilityID = 2 (Variable) + UPDATE fs SET + fs.InitialBudgetFTEs01 = 0, + fs.InitialBudgetFTEs02 = 0, + fs.InitialBudgetFTEs03 = 0, + fs.InitialBudgetFTEs04 = 0, + fs.InitialBudgetFTEs05 = 0, + fs.InitialBudgetFTEs06 = 0, + fs.InitialBudgetFTEs07 = 0, + fs.InitialBudgetFTEs08 = 0, + fs.InitialBudgetFTEs09 = 0, + fs.InitialBudgetFTEs10 = 0, + fs.InitialBudgetFTEs11 = 0, + fs.InitialBudgetFTEs12 = 0, + fs.InitialProjectionFTEs01 = 0, + fs.InitialProjectionFTEs02 = 0, + fs.InitialProjectionFTEs03 = 0, + fs.InitialProjectionFTEs04 = 0, + fs.InitialProjectionFTEs05 = 0, + fs.InitialProjectionFTEs06 = 0, + fs.InitialProjectionFTEs07 = 0, + fs.InitialProjectionFTEs08 = 0, + fs.InitialProjectionFTEs09 = 0, + fs.InitialProjectionFTEs10 = 0, + fs.InitialProjectionFTEs11 = 0, + fs.InitialProjectionFTEs12 = 0, + + fs.TargetAdjustedFTEs01 = 0, + fs.TargetAdjustedFTEs02 = 0, + fs.TargetAdjustedFTEs03 = 0, + fs.TargetAdjustedFTEs04 = 0, + fs.TargetAdjustedFTEs05 = 0, + fs.TargetAdjustedFTEs06 = 0, + fs.TargetAdjustedFTEs07 = 0, + fs.TargetAdjustedFTEs08 = 0, + fs.TargetAdjustedFTEs09 = 0, + fs.TargetAdjustedFTEs10 = 0, + fs.TargetAdjustedFTEs11 = 0, + fs.TargetAdjustedFTEs12 = 0, + fs.BudgetAdjustedFTEs01 = 0, + fs.BudgetAdjustedFTEs02 = 0, + fs.BudgetAdjustedFTEs03 = 0, + fs.BudgetAdjustedFTEs04 = 0, + fs.BudgetAdjustedFTEs05 = 0, + fs.BudgetAdjustedFTEs06 = 0, + fs.BudgetAdjustedFTEs07 = 0, + fs.BudgetAdjustedFTEs08 = 0, + fs.BudgetAdjustedFTEs09 = 0, + fs.BudgetAdjustedFTEs10 = 0, + fs.BudgetAdjustedFTEs11 = 0, + fs.BudgetAdjustedFTEs12 = 0, + + fs.ProjectionAdjustedFTEs01 = 0, + fs.ProjectionAdjustedFTEs02 = 0, + fs.ProjectionAdjustedFTEs03 = 0, + fs.ProjectionAdjustedFTEs04 = 0, + fs.ProjectionAdjustedFTEs05 = 0, + fs.ProjectionAdjustedFTEs06 = 0, + fs.ProjectionAdjustedFTEs07 = 0, + fs.ProjectionAdjustedFTEs08 = 0, + fs.ProjectionAdjustedFTEs09 = 0, + fs.ProjectionAdjustedFTEs10 = 0, + fs.ProjectionAdjustedFTEs11 = 0, + fs.ProjectionAdjustedFTEs12 = 0, + fs.TargetFTEsPercentAdjustmentFactor01 = 0, + fs.TargetFTEsPercentAdjustmentFactor02 = 0, + fs.TargetFTEsPercentAdjustmentFactor03 = 0, + fs.TargetFTEsPercentAdjustmentFactor04 = 0, + fs.TargetFTEsPercentAdjustmentFactor05 = 0, + fs.TargetFTEsPercentAdjustmentFactor06 = 0, + fs.TargetFTEsPercentAdjustmentFactor07 = 0, + fs.TargetFTEsPercentAdjustmentFactor08 = 0, + fs.TargetFTEsPercentAdjustmentFactor09 = 0, + fs.TargetFTEsPercentAdjustmentFactor10 = 0, + fs.TargetFTEsPercentAdjustmentFactor11 = 0, + fs.TargetFTEsPercentAdjustmentFactor12 = 0, + fs.BudgetFTEsPercentAdjustmentFactor01 = 0, + fs.BudgetFTEsPercentAdjustmentFactor02 = 0, + fs.BudgetFTEsPercentAdjustmentFactor03 = 0, + fs.BudgetFTEsPercentAdjustmentFactor04 = 0, + fs.BudgetFTEsPercentAdjustmentFactor05 = 0, + fs.BudgetFTEsPercentAdjustmentFactor06 = 0, + fs.BudgetFTEsPercentAdjustmentFactor07 = 0, + fs.BudgetFTEsPercentAdjustmentFactor08 = 0, + fs.BudgetFTEsPercentAdjustmentFactor09 = 0, + fs.BudgetFTEsPercentAdjustmentFactor10 = 0, + fs.BudgetFTEsPercentAdjustmentFactor11 = 0, + fs.BudgetFTEsPercentAdjustmentFactor12 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor01 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor02 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor03 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor04 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor05 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor06 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor07 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor08 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor09 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor10 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor11 = 0, + fs.ProjectionFTEsPercentAdjustmentFactor12 = 0, + + fs.InitialBudgetRate01 = 0, + fs.InitialBudgetRate02 = 0, + fs.InitialBudgetRate03 = 0, + fs.InitialBudgetRate04 = 0, + fs.InitialBudgetRate05 = 0, + fs.InitialBudgetRate06 = 0, + fs.InitialBudgetRate07 = 0, + fs.InitialBudgetRate08 = 0, + fs.InitialBudgetRate09 = 0, + fs.InitialBudgetRate10 = 0, + fs.InitialBudgetRate11 = 0, + fs.InitialBudgetRate12 = 0, + fs.InitialProjectionRate01 = 0, + fs.InitialProjectionRate02 = 0, + fs.InitialProjectionRate03 = 0, + fs.InitialProjectionRate04 = 0, + fs.InitialProjectionRate05 = 0, + fs.InitialProjectionRate06 = 0, + fs.InitialProjectionRate07 = 0, + fs.InitialProjectionRate08 = 0, + fs.InitialProjectionRate09 = 0, + fs.InitialProjectionRate10 = 0, + fs.InitialProjectionRate11 = 0, + fs.InitialProjectionRate12 = 0, + fs.TargetAdjustedRate01 = 0, + fs.TargetAdjustedRate02 = 0, + fs.TargetAdjustedRate03 = 0, + fs.TargetAdjustedRate04 = 0, + fs.TargetAdjustedRate05 = 0, + fs.TargetAdjustedRate06 = 0, + fs.TargetAdjustedRate07 = 0, + fs.TargetAdjustedRate08 = 0, + fs.TargetAdjustedRate09 = 0, + fs.TargetAdjustedRate10 = 0, + fs.TargetAdjustedRate11 = 0, + fs.TargetAdjustedRate12 = 0, + fs.BudgetAdjustedRate01 = 0, + fs.BudgetAdjustedRate02 = 0, + fs.BudgetAdjustedRate03 = 0, + fs.BudgetAdjustedRate04 = 0, + fs.BudgetAdjustedRate05 = 0, + fs.BudgetAdjustedRate06 = 0, + fs.BudgetAdjustedRate07 = 0, + fs.BudgetAdjustedRate08 = 0, + fs.BudgetAdjustedRate09 = 0, + fs.BudgetAdjustedRate10 = 0, + fs.BudgetAdjustedRate11 = 0, + fs.BudgetAdjustedRate12 = 0, + fs.ProjectionAdjustedRate01 = 0, + fs.ProjectionAdjustedRate02 = 0, + fs.ProjectionAdjustedRate03 = 0, + fs.ProjectionAdjustedRate04 = 0, + fs.ProjectionAdjustedRate05 = 0, + fs.ProjectionAdjustedRate06 = 0, + fs.ProjectionAdjustedRate07 = 0, + fs.ProjectionAdjustedRate08 = 0, + fs.ProjectionAdjustedRate09 = 0, + fs.ProjectionAdjustedRate10 = 0, + fs.ProjectionAdjustedRate11 = 0, + fs.ProjectionAdjustedRate12 = 0 + FROM [fp].[Staffing] fs + INNER JOIN #FilteringTable ft on ft.DepartmentID = fs.DepartmentID + LEFT JOIN #Variability v on fs.DepartmentID = v.DepartmentID + AND fs.JobCodeID = v.JobCodeID + AND fs.PayCodeGroupID = v.PayCodeGroupID + AND v.ProviderLineItemID = fs.ProviderLineItemID + AND v.EmployeeID = fs.EmployeeID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND (v.FixedPercentage = 1 OR v.FixedPercentage is NULL) + AND fs.VariabilityID = 2 + + END; +GO + + +--------------------------------------------- + +-- fp.procArchiveBenefitsData +CREATE PROCEDURE [fp].[procArchiveBenefitsData] + @budgetConfigID SMALLINT +AS +BEGIN + SET NOCOUNT ON; + +-- BEGIN TRANSACTION ArchiveBenefitsData; +-- +-- BEGIN TRY +-- +---- copy FactBenefits table +-- +-- -- copy records +-- SET IDENTITY_INSERT [fp].[ArchiveFactBenefits] ON +-- INSERT INTO [fp].[ArchiveFactBenefits] ([BenefitsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [UnitTypeID], [AddDate], [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12]) +-- SElECT [BenefitsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [UnitTypeID], [AddDate], [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12] FROM [fp].[FactBenefits] WHERE [BudgetConfigID] = @budgetConfigID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactAccountBasisRecords INT = (SELECT COUNT(*) FROM [fp].[ArchiveFactBenefits] WHERE [BudgetConfigID] = @budgetConfigID); +-- DECLARE @numberOfOriginalFactAccountBasisRecords INT = (SELECT COUNT(*) FROM [fp].[FactBenefits] WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactAccountBasisRecords <> @numberOfOriginalFactAccountBasisRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactBenefits] table.', 15, 1); +-- +-- +---- copy FactBenefitsBudget table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveFactBenefitsBudget] ([BenefitsID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12]) +-- SELECT bdgt.[BenefitsID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12] +-- FROM [fp].[FactBenefitsBudget] bdgt +-- INNER JOIN [fp].[ArchiveFactBenefits] gl ON bdgt.BenefitsID = gl.BenefitsID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactAccountBasisResultRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveFactBenefitsBudget] bdgt +-- INNER JOIN [fp].[ArchiveFactBenefits] gl ON bdgt.BenefitsID = gl.BenefitsID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalFactAccountBasisResultRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[FactBenefitsBudget] bdgt +-- INNER JOIN [fp].[FactBenefits] gl ON bdgt.BenefitsID = gl.BenefitsID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactAccountBasisResultRecords <> @numberOfOriginalFactAccountBasisResultRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactBenefitsBudget] table.', 15, 1); +-- +-- +-- +---- copy FactBenefitsProjection table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveFactBenefitsProjection] ([BenefitsID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12]) +-- SELECT proj.[BenefitsID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12] +-- FROM [fp].[FactBenefitsProjection] proj +-- INNER JOIN [fp].[ArchiveFactBenefits] gl ON proj.BenefitsID = gl.BenefitsID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactAccountBasisProjectionRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveFactBenefitsProjection] proj +-- INNER JOIN [fp].[ArchiveFactBenefits] gl ON proj.BenefitsID = gl.BenefitsID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalFactAccountBasisProjectionRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[FactBenefitsProjection] proj +-- INNER JOIN [fp].[FactBenefits] gl ON proj.BenefitsID = gl.BenefitsID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactAccountBasisProjectionRecords <> @numberOfOriginalFactAccountBasisProjectionRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactBenefitsProjection] table.', 15, 1); +-- +-- +---- copy FactBenefitsHistory table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveFactBenefitsHistory]([BenefitsID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12], +-- [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12], +-- [CurrentYearBudget01],[CurrentYearBudget02],[CurrentYearBudget03],[CurrentYearBudget04],[CurrentYearBudget05],[CurrentYearBudget06],[CurrentYearBudget07],[CurrentYearBudget08],[CurrentYearBudget09],[CurrentYearBudget10],[CurrentYearBudget11],[CurrentYearBudget12]) +-- SELECT +-- hist.[BenefitsID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12], +-- [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12], +-- [CurrentYearBudget01],[CurrentYearBudget02],[CurrentYearBudget03],[CurrentYearBudget04],[CurrentYearBudget05],[CurrentYearBudget06],[CurrentYearBudget07],[CurrentYearBudget08],[CurrentYearBudget09],[CurrentYearBudget10],[CurrentYearBudget11],[CurrentYearBudget12] +-- FROM [fp].[FactBenefitsHistory] hist +-- INNER JOIN [fp].[ArchiveFactBenefits] b ON hist.BenefitsID = b.BenefitsID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactBenefitsHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveFactBenefitsHistory] hist +-- INNER JOIN [fp].[ArchiveFactBenefits] b ON hist.BenefitsID = b.BenefitsID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalFactBenefitsHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[FactBenefitsHistory] hist +-- INNER JOIN [fp].[FactBenefits] b ON hist.BenefitsID = b.BenefitsID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactBenefitsHistoryRecords <> @numberOfOriginalFactBenefitsHistoryRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactBenefitsHistory] table.', 15, 1); +-- +---- copy BenefitsChangeHistory table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveBenefitsChangeHistory]([BenefitsID],[AdjustmentGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue]) +-- SELECT +-- hist.[BenefitsID],[AdjustmentGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],hist.[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue] +-- FROM [fp].[BenefitsChangeHistory] hist +-- INNER JOIN [fp].[ArchiveFactBenefits] b ON hist.BenefitsID = b.BenefitsID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedBenefitsChangeHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveBenefitsChangeHistory] hist +-- INNER JOIN [fp].[ArchiveFactBenefits] b ON hist.BenefitsID = b.BenefitsID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalBenefitsChangeHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[BenefitsChangeHistory] hist +-- INNER JOIN [fp].[FactBenefits] b ON hist.BenefitsID = b.BenefitsID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedBenefitsChangeHistoryRecords <> @numberOfOriginalBenefitsChangeHistoryRecords) +-- RAISERROR ('Not all records were archived from [fp].[BenefitsChangeHistory] table.', 15, 1); +-- +-- +---- remove original data (FK will cascade deletes) +-- DELETE FROM [fp].[FactBenefits] WHERE [BudgetConfigID] = @budgetConfigID; +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactBenefits] WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactBenefits] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactBenefitsBudget] bdgt INNER JOIN [fp].[FactBenefits] b ON bdgt.BenefitsID = b.BenefitsID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactBenefitsBudget] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactBenefitsProjection] proj INNER JOIN [fp].[FactBenefits] b ON proj.BenefitsID = b.BenefitsID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactBenefitsProjection] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactBenefitsHistory] hist INNER JOIN [fp].[FactBenefits] b ON hist.BenefitsID = b.BenefitsID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactBenefitsHistory] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[BenefitsChangeHistory] hist INNER JOIN [fp].[FactBenefits] b ON hist.BenefitsID = b.BenefitsID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[BenefitsChangeHistory] table.', 15, 2); +-- +-- +-- COMMIT TRANSACTION ArchiveBenefitsData; +-- END TRY +-- BEGIN CATCH +-- ROLLBACK TRANSACTION ArchiveBenefitsData; +-- +-- DECLARE @errorMessage NVARCHAR(MAX) = ERROR_MESSAGE(); +-- DECLARE @errorSeverity INT = ERROR_SEVERITY(); +-- DECLARE @errorState INT = ERROR_STATE(); +-- +-- RAISERROR (@errorMessage, @errorSeverity, @errorState); +-- END CATCH +-- +--RETURN; +END +GO + + +--------------------------------------------- + +-- fp.procArchiveChargeVolumeData +CREATE PROCEDURE [fp].[procArchiveChargeVolumeData] + @budgetConfigID SMALLINT +AS +BEGIN + SET NOCOUNT ON; +-- +-- BEGIN TRANSACTION ArchiveChargeVolumeData; +-- +-- BEGIN TRY +-- +-- -- copy FactChargeVolume table +-- +-- -- copy records +-- SET IDENTITY_INSERT [fp].[ArchiveFactChargeVolume] ON +-- INSERT INTO [fp].[ArchiveFactChargeVolume] ([ChargeVolumeID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [PatientClassID], [ServiceLineID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [UnitTypeID], [AddDate], [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12], [SampledBudget01], [SampledBudget02], [SampledBudget03], [SampledBudget04], [SampledBudget05], [SampledBudget06], [SampledBudget07], [SampledBudget08], [SampledBudget09], [SampledBudget10], [SampledBudget11], [SampledBudget12], [SampledProjection01], [SampledProjection02], [SampledProjection03], [SampledProjection04], [SampledProjection05], [SampledProjection06], [SampledProjection07], [SampledProjection08], [SampledProjection09], [SampledProjection10], [SampledProjection11], [SampledProjection12]) +-- SElECT [ChargeVolumeID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [PatientClassID], [ServiceLineID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [UnitTypeID], [AddDate], [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12], [SampledBudget01], [SampledBudget02], [SampledBudget03], [SampledBudget04], [SampledBudget05], [SampledBudget06], [SampledBudget07], [SampledBudget08], [SampledBudget09], [SampledBudget10], [SampledBudget11], [SampledBudget12], [SampledProjection01], [SampledProjection02], [SampledProjection03], [SampledProjection04], [SampledProjection05], [SampledProjection06], [SampledProjection07], [SampledProjection08], [SampledProjection09], [SampledProjection10], [SampledProjection11], [SampledProjection12] +-- FROM [fp].[FactChargeVolume] WHERE [BudgetConfigID] = @budgetConfigID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactAccountBasisRecords INT = (SELECT COUNT(*) FROM [fp].[ArchiveFactChargeVolume] WHERE [BudgetConfigID] = @budgetConfigID); +-- DECLARE @numberOfOriginalFactAccountBasisRecords INT = (SELECT COUNT(*) FROM [fp].[FactChargeVolume] WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactAccountBasisRecords <> @numberOfOriginalFactAccountBasisRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactChargeVolume] table.', 15, 1); +-- +-- +-- -- copy FactChargeVolumeBudget table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveFactChargeVolumeBudget] ([ChargeVolumeID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12]) +-- SELECT bdgt.[ChargeVolumeID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12] +-- FROM [fp].[FactChargeVolumeBudget] bdgt +-- INNER JOIN [fp].[ArchiveFactChargeVolume] cv ON bdgt.ChargeVolumeID = cv.ChargeVolumeID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactAccountBasisResultRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveFactChargeVolumeBudget] bdgt +-- INNER JOIN [fp].[ArchiveFactChargeVolume] cv ON bdgt.ChargeVolumeID = cv.ChargeVolumeID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalFactAccountBasisResultRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[FactChargeVolumeBudget] bdgt +-- INNER JOIN [fp].[FactChargeVolume] cv ON bdgt.ChargeVolumeID = cv.ChargeVolumeID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactAccountBasisResultRecords <> @numberOfOriginalFactAccountBasisResultRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactChargeVolumeBudget] table.', 15, 1); +-- +-- +-- +-- -- copy FactChargeVolumeProjection table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveFactChargeVolumeProjection] ([ChargeVolumeID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12]) +-- SELECT proj.[ChargeVolumeID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12] +-- FROM [fp].[FactChargeVolumeProjection] proj +-- INNER JOIN [fp].[ArchiveFactChargeVolume] cv ON proj.ChargeVolumeID = cv.ChargeVolumeID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactAccountBasisProjectionRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveFactChargeVolumeProjection] proj +-- INNER JOIN [fp].[ArchiveFactChargeVolume] cv ON proj.ChargeVolumeID = cv.ChargeVolumeID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalFactAccountBasisProjectionRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[FactChargeVolumeProjection] proj +-- INNER JOIN [fp].[FactChargeVolume] cv ON proj.ChargeVolumeID = cv.ChargeVolumeID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactAccountBasisProjectionRecords <> @numberOfOriginalFactAccountBasisProjectionRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactChargeVolumeProjection] table.', 15, 1); +-- +---- copy FactChargeVolumeHistory table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveFactChargeVolumeHistory]([ChargeVolumeID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12], +-- [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12], +-- [CurrentYearBudgetValue01],[CurrentYearBudgetValue02],[CurrentYearBudgetValue03],[CurrentYearBudgetValue04],[CurrentYearBudgetValue05],[CurrentYearBudgetValue06],[CurrentYearBudgetValue07],[CurrentYearBudgetValue08],[CurrentYearBudgetValue09],[CurrentYearBudgetValue10],[CurrentYearBudgetValue11],[CurrentYearBudgetValue12]) +-- SELECT +-- hist.[ChargeVolumeID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12], +-- [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12], +-- [CurrentYearBudgetValue01],[CurrentYearBudgetValue02],[CurrentYearBudgetValue03],[CurrentYearBudgetValue04],[CurrentYearBudgetValue05],[CurrentYearBudgetValue06],[CurrentYearBudgetValue07],[CurrentYearBudgetValue08],[CurrentYearBudgetValue09],[CurrentYearBudgetValue10],[CurrentYearBudgetValue11],[CurrentYearBudgetValue12] +-- FROM [fp].[FactChargeVolumeHistory] hist +-- INNER JOIN [fp].[ArchiveFactChargeVolume] cv ON hist.ChargeVolumeID = cv.ChargeVolumeID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactChargeVolumeHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveFactChargeVolumeHistory] hist +-- INNER JOIN [fp].[ArchiveFactChargeVolume] cv ON hist.ChargeVolumeID = cv.ChargeVolumeID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalFactChargeVolumeHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[FactChargeVolumeHistory] hist +-- INNER JOIN [fp].[FactChargeVolume] cv ON hist.ChargeVolumeID = cv.ChargeVolumeID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactChargeVolumeHistoryRecords <> @numberOfOriginalFactChargeVolumeHistoryRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactChargeVolumeHistory] table.', 15, 1); +-- +---- copy ChargeVolumeChangeHistory table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveChargeVolumeChangeHistory]([ChargeVolumeID],[AdjustmentGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue]) +-- SELECT +-- hist.[ChargeVolumeID],[AdjustmentGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],hist.[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue] +-- FROM [fp].[ChargeVolumeChangeHistory] hist +-- INNER JOIN [fp].[ArchiveFactChargeVolume] cv ON hist.ChargeVolumeID = cv.ChargeVolumeID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedChargeVolumeChangeHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveChargeVolumeChangeHistory] hist +-- INNER JOIN [fp].[ArchiveFactChargeVolume] cv ON hist.ChargeVolumeID = cv.ChargeVolumeID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalChargeVolumeChangeHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ChargeVolumeChangeHistory] hist +-- INNER JOIN [fp].[FactChargeVolume] cv ON hist.ChargeVolumeID = cv.ChargeVolumeID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedChargeVolumeChangeHistoryRecords <> @numberOfOriginalChargeVolumeChangeHistoryRecords) +-- RAISERROR ('Not all records were archived from [fp].[ChargeVolumeChangeHistory] table.', 15, 1); +-- +-- +-- -- remove original data (FK will cascade deletes) +-- DELETE FROM [fp].[FactChargeVolume] WHERE [BudgetConfigID] = @budgetConfigID; +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactChargeVolume] WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactChargeVolume] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactChargeVolumeBudget] bdgt INNER JOIN [fp].[FactChargeVolume] cv ON bdgt.ChargeVolumeID = cv.ChargeVolumeID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactChargeVolumeBudget] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactChargeVolumeProjection] proj INNER JOIN [fp].[FactChargeVolume] cv ON proj.ChargeVolumeID = cv.ChargeVolumeID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactChargeVolumeProjection] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactChargeVolumeHistory] hist INNER JOIN [fp].[FactChargeVolume] cv ON hist.ChargeVolumeID = cv.ChargeVolumeID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactChargeVolumeHistory] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[ChargeVolumeChangeHistory] hist INNER JOIN [fp].[FactChargeVolume] cv ON hist.ChargeVolumeID = cv.ChargeVolumeID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[ChargeVolumeChangeHistory] table.', 15, 2); +-- +-- COMMIT TRANSACTION ArchiveChargeVolumeData; +-- END TRY +-- BEGIN CATCH +-- ROLLBACK TRANSACTION ArchiveChargeVolumeData; +-- +-- DECLARE @errorMessage NVARCHAR(MAX) = ERROR_MESSAGE(); +-- DECLARE @errorSeverity INT = ERROR_SEVERITY(); +-- DECLARE @errorState INT = ERROR_STATE(); +-- +-- RAISERROR (@errorMessage, @errorSeverity, @errorState); +-- END CATCH +-- +--RETURN; +END +GO + + +--------------------------------------------- + +-- fp.procArchiveFactServiceLineData +CREATE PROCEDURE [fp].[procArchiveFactServiceLineData] + @budgetConfigID SMALLINT +AS +BEGIN + SET NOCOUNT ON; +-- +-- BEGIN TRANSACTION ArchiveServiceLineData; +-- +-- BEGIN TRY +-- +---- copy FactServiceLineEncounter table +-- +-- -- copy records +-- SET IDENTITY_INSERT [fp].[ArchiveFactServiceLineEncounter] ON +-- INSERT INTO [fp].[ArchiveFactServiceLineEncounter] ([ServiceLineEncounterID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], +-- [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID], [AddDate], +-- [SampledBudget01], [SampledBudget02], [SampledBudget03], [SampledBudget04], [SampledBudget05], [SampledBudget06], [SampledBudget07], [SampledBudget08], [SampledBudget09], +-- [SampledBudget10], [SampledBudget11], [SampledBudget12], [SampledProjection01], [SampledProjection02], [SampledProjection03], [SampledProjection04], [SampledProjection05], +-- [SampledProjection06], [SampledProjection07], [SampledProjection08], [SampledProjection09], [SampledProjection10], [SampledProjection11], [SampledProjection12], [InitialBudget01], +-- [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], +-- [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], +-- [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12]) +-- SElECT [ServiceLineEncounterID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], +-- [AgeCohortID], [MedicalSurgicalID], [DepartmentID], [PayorID], [PayorGroupID], [MSDRGID], [CPTID], [ProviderID], [PhysicianSpecialtyID], [UnitTypeID], [AddDate], +-- [SampledBudget01], [SampledBudget02], [SampledBudget03], [SampledBudget04], [SampledBudget05], [SampledBudget06], [SampledBudget07], [SampledBudget08], [SampledBudget09], +-- [SampledBudget10], [SampledBudget11], [SampledBudget12], [SampledProjection01], [SampledProjection02], [SampledProjection03], [SampledProjection04], [SampledProjection05], +-- [SampledProjection06], [SampledProjection07], [SampledProjection08], [SampledProjection09], [SampledProjection10], [SampledProjection11], [SampledProjection12], [InitialBudget01], +-- [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], +-- [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], +-- [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12] +-- FROM [fp].[FactServiceLineEncounter] WHERE [BudgetConfigID] = @budgetConfigID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactAccountBasisRecords INT = (SELECT COUNT(*) FROM [fp].[ArchiveFactServiceLineEncounter] WHERE [BudgetConfigID] = @budgetConfigID); +-- DECLARE @numberOfOriginalFactAccountBasisRecords INT = (SELECT COUNT(*) FROM [fp].[FactServiceLineEncounter] WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactAccountBasisRecords <> @numberOfOriginalFactAccountBasisRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactServiceLineEncounter] table.', 15, 1); +-- +-- +---- copy FactServiceLineEncounterBudget table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveFactServiceLineEncounterBudget] ([ServiceLineEncounterID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12]) +-- SELECT bdgt.[ServiceLineEncounterID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12] +-- FROM [fp].[FactServiceLineEncounterBudget] bdgt +-- INNER JOIN [fp].[ArchiveFactServiceLineEncounter] stat ON bdgt.ServiceLineEncounterID = stat.ServiceLineEncounterID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactAccountBasisResultRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveFactServiceLineEncounterBudget] bdgt +-- INNER JOIN [fp].[ArchiveFactServiceLineEncounter] stat ON bdgt.ServiceLineEncounterID = stat.ServiceLineEncounterID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalFactAccountBasisResultRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[FactServiceLineEncounterBudget] bdgt +-- INNER JOIN [fp].[FactServiceLineEncounter] stat ON bdgt.ServiceLineEncounterID = stat.ServiceLineEncounterID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactAccountBasisResultRecords <> @numberOfOriginalFactAccountBasisResultRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactServiceLineEncounterBudget] table.', 15, 1); +-- +-- +-- +---- copy FactServiceLineEncounterProjection table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveFactServiceLineEncounterProjection] ([ServiceLineEncounterID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12]) +-- SELECT proj.[ServiceLineEncounterID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12] +-- FROM [fp].[FactServiceLineEncounterProjection] proj +-- INNER JOIN [fp].[ArchiveFactServiceLineEncounter] stat ON proj.ServiceLineEncounterID = stat.ServiceLineEncounterID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactAccountBasisProjectionRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveFactServiceLineEncounterProjection] proj +-- INNER JOIN [fp].[ArchiveFactServiceLineEncounter] stat ON proj.ServiceLineEncounterID = stat.ServiceLineEncounterID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalFactAccountBasisProjectionRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[FactServiceLineEncounterProjection] proj +-- INNER JOIN [fp].[FactServiceLineEncounter] stat ON proj.ServiceLineEncounterID = stat.ServiceLineEncounterID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactAccountBasisProjectionRecords <> @numberOfOriginalFactAccountBasisProjectionRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactServiceLineEncounterProjection] table.', 15, 1); +-- +---- copy FactServiceLineEncounterHistory table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveFactServiceLineEncounterHistory]([ServiceLineEncounterID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12], +-- [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12], +-- [CurrentYearBudget01],[CurrentYearBudget02],[CurrentYearBudget03],[CurrentYearBudget04],[CurrentYearBudget05],[CurrentYearBudget06],[CurrentYearBudget07],[CurrentYearBudget08],[CurrentYearBudget09],[CurrentYearBudget10],[CurrentYearBudget11],[CurrentYearBudget12]) +-- SELECT +-- hist.[ServiceLineEncounterID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12], +-- [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12], +-- [CurrentYearBudget01],[CurrentYearBudget02],[CurrentYearBudget03],[CurrentYearBudget04],[CurrentYearBudget05],[CurrentYearBudget06],[CurrentYearBudget07],[CurrentYearBudget08],[CurrentYearBudget09],[CurrentYearBudget10],[CurrentYearBudget11],[CurrentYearBudget12] +-- FROM [fp].[FactServiceLineEncounterHistory] hist +-- INNER JOIN [fp].[ArchiveFactServiceLineEncounter] stat ON hist.ServiceLineEncounterID = stat.ServiceLineEncounterID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactServiceLineEncounterHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveFactServiceLineEncounterHistory] hist +-- INNER JOIN [fp].[ArchiveFactServiceLineEncounter] stat ON hist.ServiceLineEncounterID = stat.ServiceLineEncounterID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalFactServiceLineEncounterHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[FactServiceLineEncounterHistory] hist +-- INNER JOIN [fp].[FactServiceLineEncounter] stat ON hist.ServiceLineEncounterID = stat.ServiceLineEncounterID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactServiceLineEncounterHistoryRecords <> @numberOfOriginalFactServiceLineEncounterHistoryRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactServiceLineEncounterHistory] table.', 15, 1); +-- +---- copy ServiceLineEncounterChangeHistory table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveServiceLineEncounterChangeHistory]([ServiceLineEncounterID],[AdjustmentGUID],[GroupingGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue]) +-- SELECT +-- hist.[ServiceLineEncounterID],[AdjustmentGUID],[GroupingGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],hist.[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue] +-- FROM [fp].[ServiceLineEncounterChangeHistory] hist +-- INNER JOIN [fp].[ArchiveFactServiceLineEncounter] stat ON hist.ServiceLineEncounterID = stat.ServiceLineEncounterID; +-- +-- -- ensure all records were copied +-- DECLARE @numberOfArchivedServiceLineEncounterChangeHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveServiceLineEncounterChangeHistory] hist +-- INNER JOIN [fp].[ArchiveFactServiceLineEncounter] stat ON hist.ServiceLineEncounterID = stat.ServiceLineEncounterID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalServiceLineEncounterChangeHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ServiceLineEncounterChangeHistory] hist +-- INNER JOIN [fp].[FactServiceLineEncounter] stat ON hist.ServiceLineEncounterID = stat.ServiceLineEncounterID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedServiceLineEncounterChangeHistoryRecords <> @numberOfOriginalServiceLineEncounterChangeHistoryRecords) +-- RAISERROR ('Not all records were archived from [fp].[ServiceLineEncounterChangeHistory] table.', 15, 1); +-- +-- -- remove original data (FK will cascade deletes) +-- DELETE FROM [fp].[FactServiceLineEncounter] WHERE [BudgetConfigID] = @budgetConfigID; +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactServiceLineEncounter] WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactServiceLineEncounter] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactServiceLineEncounterBudget] bdgt INNER JOIN [fp].[FactServiceLineEncounter] stat ON bdgt.ServiceLineEncounterID = stat.ServiceLineEncounterID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactServiceLineEncounterBudget] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactServiceLineEncounterProjection] proj INNER JOIN [fp].[FactServiceLineEncounter] stat ON proj.ServiceLineEncounterID = stat.ServiceLineEncounterID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactServiceLineEncounterProjection] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactServiceLineEncounterHistory] hist INNER JOIN [fp].[FactServiceLineEncounter] stat ON hist.ServiceLineEncounterID = stat.ServiceLineEncounterID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactServiceLineEncounterHistory] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[ServiceLineEncounterChangeHistory] hist INNER JOIN [fp].[FactServiceLineEncounter] stat ON hist.ServiceLineEncounterID = stat.ServiceLineEncounterID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[ServiceLineEncounterChangeHistory] table.', 15, 2); +-- +-- COMMIT TRANSACTION ArchiveServiceLineData; +-- END TRY +-- BEGIN CATCH +-- ROLLBACK TRANSACTION ArchiveServiceLineData; +-- +-- DECLARE @errorMessage NVARCHAR(MAX) = ERROR_MESSAGE(); +-- DECLARE @errorSeverity INT = ERROR_SEVERITY(); +-- DECLARE @errorState INT = ERROR_STATE(); +-- +-- RAISERROR (@errorMessage, @errorSeverity, @errorState); +-- END CATCH +-- +--RETURN; +END +GO + + +--------------------------------------------- + +-- fp.procArchiveGeneralLedgerData +CREATE PROCEDURE [fp].[procArchiveGeneralLedgerData] + @budgetConfigID SMALLINT +AS +BEGIN + SET NOCOUNT ON; +-- +-- BEGIN TRANSACTION ArchiveGeneralLedgerData; +-- +-- BEGIN TRY +-- +---- copy FactGeneralLedger table +-- +-- -- copy records +-- SET IDENTITY_INSERT [fp].[ArchiveFactGeneralLedger] ON +-- INSERT INTO [fp].[ArchiveFactGeneralLedger] ([GeneralLedgerID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [VariabilityID], [UnitTypeID], [APEModelSectionID], [AddDate], [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12]) +-- SElECT [GeneralLedgerID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [VariabilityID], [UnitTypeID], [APEModelSectionID], [AddDate], [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12] FROM [fp].[FactGeneralLedger] WHERE [BudgetConfigID] = @budgetConfigID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactAccountBasisRecords INT = (SELECT COUNT(*) FROM [fp].[ArchiveFactGeneralLedger] WHERE [BudgetConfigID] = @budgetConfigID); +-- DECLARE @numberOfOriginalFactAccountBasisRecords INT = (SELECT COUNT(*) FROM [fp].[FactGeneralLedger] WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactAccountBasisRecords <> @numberOfOriginalFactAccountBasisRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactGeneralLedger] table.', 15, 1); +-- +-- +---- copy FactGeneralLedgerBudget table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveFactGeneralLedgerBudget] ([GeneralLedgerID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12], [PercentAdjustmentFactor01], [PercentAdjustmentFactor02], [PercentAdjustmentFactor03], [PercentAdjustmentFactor04], [PercentAdjustmentFactor05], [PercentAdjustmentFactor06], [PercentAdjustmentFactor07], [PercentAdjustmentFactor08], [PercentAdjustmentFactor09], [PercentAdjustmentFactor10], [PercentAdjustmentFactor11], [PercentAdjustmentFactor12]) +-- SELECT bdgt.[GeneralLedgerID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12], [PercentAdjustmentFactor01], [PercentAdjustmentFactor02], [PercentAdjustmentFactor03], [PercentAdjustmentFactor04], [PercentAdjustmentFactor05], [PercentAdjustmentFactor06], [PercentAdjustmentFactor07], [PercentAdjustmentFactor08], [PercentAdjustmentFactor09], [PercentAdjustmentFactor10], [PercentAdjustmentFactor11], [PercentAdjustmentFactor12] +-- FROM [fp].[FactGeneralLedgerBudget] bdgt +-- INNER JOIN [fp].[ArchiveFactGeneralLedger] gl ON bdgt.GeneralLedgerID = gl.GeneralLedgerID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactAccountBasisResultRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveFactGeneralLedgerBudget] bdgt +-- INNER JOIN [fp].[ArchiveFactGeneralLedger] gl ON bdgt.GeneralLedgerID = gl.GeneralLedgerID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalFactAccountBasisResultRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[FactGeneralLedgerBudget] bdgt +-- INNER JOIN [fp].[FactGeneralLedger] gl ON bdgt.GeneralLedgerID = gl.GeneralLedgerID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactAccountBasisResultRecords <> @numberOfOriginalFactAccountBasisResultRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactGeneralLedgerBudget] table.', 15, 1); +-- +-- +-- +---- copy FactGeneralLedgerProjection table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveFactGeneralLedgerProjection] ([GeneralLedgerID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12], [PercentAdjustmentFactor01], [PercentAdjustmentFactor02], [PercentAdjustmentFactor03], [PercentAdjustmentFactor04], [PercentAdjustmentFactor05], [PercentAdjustmentFactor06], [PercentAdjustmentFactor07], [PercentAdjustmentFactor08], [PercentAdjustmentFactor09], [PercentAdjustmentFactor10], [PercentAdjustmentFactor11], [PercentAdjustmentFactor12]) +-- SELECT proj.[GeneralLedgerID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12], [PercentAdjustmentFactor01], [PercentAdjustmentFactor02], [PercentAdjustmentFactor03], [PercentAdjustmentFactor04], [PercentAdjustmentFactor05], [PercentAdjustmentFactor06], [PercentAdjustmentFactor07], [PercentAdjustmentFactor08], [PercentAdjustmentFactor09], [PercentAdjustmentFactor10], [PercentAdjustmentFactor11], [PercentAdjustmentFactor12] +-- FROM [fp].[FactGeneralLedgerProjection] proj +-- INNER JOIN [fp].[ArchiveFactGeneralLedger] gl ON proj.GeneralLedgerID = gl.GeneralLedgerID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactAccountBasisProjectionRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveFactGeneralLedgerProjection] proj +-- INNER JOIN [fp].[ArchiveFactGeneralLedger] gl ON proj.GeneralLedgerID = gl.GeneralLedgerID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalFactAccountBasisProjectionRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[FactGeneralLedgerProjection] proj +-- INNER JOIN [fp].[FactGeneralLedger] gl ON proj.GeneralLedgerID = gl.GeneralLedgerID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactAccountBasisProjectionRecords <> @numberOfOriginalFactAccountBasisProjectionRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactGeneralLedgerProjection] table.', 15, 1); +-- +---- copy FactGeneralLedgerHistory table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveFactGeneralLedgerHistory]([GeneralLedgerID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12], +-- [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12], +-- [CurrentYearBudget01],[CurrentYearBudget02],[CurrentYearBudget03],[CurrentYearBudget04],[CurrentYearBudget05],[CurrentYearBudget06],[CurrentYearBudget07],[CurrentYearBudget08],[CurrentYearBudget09],[CurrentYearBudget10],[CurrentYearBudget11],[CurrentYearBudget12]) +-- SELECT +-- hist.[GeneralLedgerID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12], +-- [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12], +-- [CurrentYearBudget01],[CurrentYearBudget02],[CurrentYearBudget03],[CurrentYearBudget04],[CurrentYearBudget05],[CurrentYearBudget06],[CurrentYearBudget07],[CurrentYearBudget08],[CurrentYearBudget09],[CurrentYearBudget10],[CurrentYearBudget11],[CurrentYearBudget12] +-- FROM [fp].[FactGeneralLedgerHistory] hist +-- INNER JOIN [fp].[ArchiveFactGeneralLedger] gl ON hist.GeneralLedgerID = gl.GeneralLedgerID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactGeneralLedgerHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveFactGeneralLedgerHistory] hist +-- INNER JOIN [fp].[ArchiveFactGeneralLedger] gl ON hist.GeneralLedgerID = gl.GeneralLedgerID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalFactGeneralLedgerHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[FactGeneralLedgerHistory] hist +-- INNER JOIN [fp].[FactGeneralLedger] gl ON hist.GeneralLedgerID = gl.GeneralLedgerID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactGeneralLedgerHistoryRecords <> @numberOfOriginalFactGeneralLedgerHistoryRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactGeneralLedgerHistory] table.', 15, 1); +-- +---- copy GeneralLedgerChangeHistory table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveGeneralLedgerChangeHistory]([GeneralLedgerID],[AdjustmentGUID],[GroupingGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue]) +-- SELECT +-- hist.[GeneralLedgerID],[AdjustmentGUID],[GroupingGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],hist.[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue] +-- FROM [fp].[GeneralLedgerChangeHistory] hist +-- INNER JOIN [fp].[ArchiveFactGeneralLedger] gl ON hist.GeneralLedgerID = gl.GeneralLedgerID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedGeneralLedgerChangeHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveGeneralLedgerChangeHistory] hist +-- INNER JOIN [fp].[ArchiveFactGeneralLedger] gl ON hist.GeneralLedgerID = gl.GeneralLedgerID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalGeneralLedgerChangeHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[GeneralLedgerChangeHistory] hist +-- INNER JOIN [fp].[FactGeneralLedger] gl ON hist.GeneralLedgerID = gl.GeneralLedgerID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedGeneralLedgerChangeHistoryRecords <> @numberOfOriginalGeneralLedgerChangeHistoryRecords) +-- RAISERROR ('Not all records were archived from [fp].[GeneralLedgerChangeHistory] table.', 15, 1); +-- +-- +---- remove original data (FK will cascade deletes) +-- DELETE FROM [fp].[FactGeneralLedger] WHERE [BudgetConfigID] = @budgetConfigID; +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactGeneralLedger] WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactGeneralLedger] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactGeneralLedgerBudget] bdgt INNER JOIN [fp].[FactGeneralLedger] gl ON bdgt.GeneralLedgerID = gl.GeneralLedgerID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactGeneralLedgerBudget] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactGeneralLedgerProjection] proj INNER JOIN [fp].[FactGeneralLedger] gl ON proj.GeneralLedgerID = gl.GeneralLedgerID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactGeneralLedgerProjection] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactGeneralLedgerHistory] hist INNER JOIN [fp].[FactGeneralLedger] gl ON hist.GeneralLedgerID = gl.GeneralLedgerID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactGeneralLedgerHistory] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[GeneralLedgerChangeHistory] hist INNER JOIN [fp].[FactGeneralLedger] gl ON hist.GeneralLedgerID = gl.GeneralLedgerID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[GeneralLedgerChangeHistory] table.', 15, 2); +-- +-- COMMIT TRANSACTION ArchiveGeneralLedgerData; +-- END TRY +-- BEGIN CATCH +-- ROLLBACK TRANSACTION ArchiveGeneralLedgerData; +-- +-- DECLARE @errorMessage NVARCHAR(MAX) = ERROR_MESSAGE(); +-- DECLARE @errorSeverity INT = ERROR_SEVERITY(); +-- DECLARE @errorState INT = ERROR_STATE(); +-- +-- RAISERROR (@errorMessage, @errorSeverity, @errorState); +-- END CATCH +-- +--RETURN; +END +GO + + +--------------------------------------------- + +-- fp.procArchiveServiceLineData +CREATE PROCEDURE [fp].[procArchiveServiceLineData] + @budgetConfigID SMALLINT +AS +BEGIN + SET NOCOUNT ON; + + BEGIN TRANSACTION ArchiveServiceLineData; + + BEGIN TRY + +-- copy FactServiceLineEncounterBasis table + + -- copy records + INSERT INTO [fp].[ArchiveFactServiceLineEncounterBasis] ([BudgetConfigID], [EntityID], [PatientClassID], [ServiceLineID], [AgeCohortID], [MedicalSurgicalID], [ActualEncounters], [YTDEncounters], [BaseEncounters], [ValueMonth01], [ValueMonth02], [ValueMonth03], [ValueMonth04], [ValueMonth05], [ValueMonth06], [ValueMonth07], [ValueMonth08], [ValueMonth09], [ValueMonth10], [ValueMonth11], [ValueMonth12], [ValueAnnualOriginal], [ChangeHistoryGUID]) + SELECT [BudgetConfigID], [EntityID], [PatientClassID], [ServiceLineID], [AgeCohortID], [MedicalSurgicalID], [ActualEncounters], [YTDEncounters], [BaseEncounters], [ValueMonth01], [ValueMonth02], [ValueMonth03], [ValueMonth04], [ValueMonth05], [ValueMonth06], [ValueMonth07], [ValueMonth08], [ValueMonth09], [ValueMonth10], [ValueMonth11], [ValueMonth12], [ValueAnnualOriginal], [ChangeHistoryGUID] FROM [fp].[FactServiceLineEncounterBasis] WHERE [BudgetConfigID] = @budgetConfigID; + + -- ensure all record were copied + DECLARE @numberOfArchivedServiceLineEncounterBasisRecords INT = (SELECT COUNT(*) FROM [fp].[ArchiveFactServiceLineEncounterBasis] WHERE [BudgetConfigID] = @budgetConfigID); + DECLARE @numberOfOriginalServiceLineEncounterBasisRecords INT = (SELECT COUNT(*) FROM [fp].[FactServiceLineEncounterBasis] WHERE [BudgetConfigID] = @budgetConfigID); + + IF (@numberOfArchivedServiceLineEncounterBasisRecords <> @numberOfOriginalServiceLineEncounterBasisRecords) + RAISERROR ('Not all records were archived from [fp].[FactServiceLineEncounterBasis] table.', 15, 1); + + -- remove original data + DELETE FROM [fp].[FactServiceLineEncounterBasis] WHERE [BudgetConfigID] = @budgetConfigID; + + IF EXISTS(SELECT 1 FROM [fp].[FactServiceLineEncounterBasis] WHERE [BudgetConfigID] = @budgetConfigID) + RAISERROR ('Not all records were removed from [fp].[FactServiceLineEncounterBasis] table.', 15, 2); + + COMMIT TRANSACTION ArchiveServiceLineData; + END TRY + BEGIN CATCH + ROLLBACK TRANSACTION ArchiveServiceLineData; + + DECLARE @errorMessage NVARCHAR(MAX) = ERROR_MESSAGE(); + DECLARE @errorSeverity INT = ERROR_SEVERITY(); + DECLARE @errorState INT = ERROR_STATE(); + + RAISERROR (@errorMessage, @errorSeverity, @errorState); + END CATCH + +RETURN; +END +GO + + +--------------------------------------------- + +-- fp.procArchiveStaffingData +CREATE PROCEDURE [fp].[procArchiveStaffingData] + @budgetConfigID SMALLINT +AS +BEGIN + SET NOCOUNT ON; +-- BEGIN TRANSACTION ArchiveStaffingData; +-- +-- BEGIN TRY +-- +-- -- copy FactStaffing table +-- +-- -- copy records +-- SET IDENTITY_INSERT [fp].[ArchiveFactStaffing] ON +-- INSERT INTO [fp].[ArchiveFactStaffing] ([StaffingID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [UnitTypeID], [AddDate], [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12], [SampledBudget01], [SampledBudget02], [SampledBudget03], [SampledBudget04], [SampledBudget05], [SampledBudget06], [SampledBudget07], [SampledBudget08], [SampledBudget09], [SampledBudget10], [SampledBudget11], [SampledBudget12], [SampledProjection01], [SampledProjection02], [SampledProjection03], [SampledProjection04], [SampledProjection05], [SampledProjection06], [SampledProjection07], [SampledProjection08], [SampledProjection09], [SampledProjection10], [SampledProjection11], [SampledProjection12]) +-- SElECT [StaffingID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [UnitTypeID], [AddDate], [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12], [SampledBudget01], [SampledBudget02], [SampledBudget03], [SampledBudget04], [SampledBudget05], [SampledBudget06], [SampledBudget07], [SampledBudget08], [SampledBudget09], [SampledBudget10], [SampledBudget11], [SampledBudget12], [SampledProjection01], [SampledProjection02], [SampledProjection03], [SampledProjection04], [SampledProjection05], [SampledProjection06], [SampledProjection07], [SampledProjection08], [SampledProjection09], [SampledProjection10], [SampledProjection11], [SampledProjection12] +-- FROM [fp].[FactStaffing] WHERE [BudgetConfigID] = @budgetConfigID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactStaffingBasisRecords INT = (SELECT COUNT(*) FROM [fp].[ArchiveFactStaffing] WHERE [BudgetConfigID] = @budgetConfigID); +-- DECLARE @numberOfOriginalFactStaffingBasisRecords INT = (SELECT COUNT(*) FROM [fp].[FactStaffing] WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactStaffingBasisRecords <> @numberOfOriginalFactStaffingBasisRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactStaffing] table.', 15, 1); +-- +-- +-- -- copy FactStaffingBudget table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveFactStaffingBudget] ([StaffingID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12]) +-- SELECT bdgt.[StaffingID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12] +-- FROM [fp].[FactStaffingBudget] bdgt +-- INNER JOIN [fp].[ArchiveFactStaffing] st ON bdgt.StaffingID = st.StaffingID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactStaffingBasisResultRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveFactStaffingBudget] bdgt +-- INNER JOIN [fp].[ArchiveFactStaffing] st ON bdgt.StaffingID = st.StaffingID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalFactStaffingBasisResultRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[FactStaffingBudget] bdgt +-- INNER JOIN [fp].[FactStaffing] st ON bdgt.StaffingID = st.StaffingID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactStaffingBasisResultRecords <> @numberOfOriginalFactStaffingBasisResultRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactStaffingBudget] table.', 15, 1); +-- +-- +-- +-- -- copy FactStaffingProjection table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveFactStaffingProjection] ([StaffingID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12]) +-- SELECT proj.[StaffingID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12] +-- FROM [fp].[FactStaffingProjection] proj +-- INNER JOIN [fp].[ArchiveFactStaffing] st ON proj.StaffingID = st.StaffingID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactStaffingBasisProjectionRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveFactStaffingProjection] proj +-- INNER JOIN [fp].[ArchiveFactStaffing] st ON proj.StaffingID = st.StaffingID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalFactStaffingBasisProjectionRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[FactStaffingProjection] proj +-- INNER JOIN [fp].[FactStaffing] st ON proj.StaffingID = st.StaffingID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactStaffingBasisProjectionRecords <> @numberOfOriginalFactStaffingBasisProjectionRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactStaffingProjection] table.', 15, 1); +-- +---- copy FactStaffingHistory table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveFactStaffingHistory]([StaffingID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12], +-- [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12], +-- [CurrentYearBudget01],[CurrentYearBudget02],[CurrentYearBudget03],[CurrentYearBudget04],[CurrentYearBudget05],[CurrentYearBudget06],[CurrentYearBudget07],[CurrentYearBudget08],[CurrentYearBudget09],[CurrentYearBudget10],[CurrentYearBudget11],[CurrentYearBudget12]) +-- SELECT +-- hist.[StaffingID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12], +-- [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12], +-- [CurrentYearBudget01],[CurrentYearBudget02],[CurrentYearBudget03],[CurrentYearBudget04],[CurrentYearBudget05],[CurrentYearBudget06],[CurrentYearBudget07],[CurrentYearBudget08],[CurrentYearBudget09],[CurrentYearBudget10],[CurrentYearBudget11],[CurrentYearBudget12] +-- FROM [fp].[FactStaffingHistory] hist +-- INNER JOIN [fp].[ArchiveFactStaffing] st ON hist.StaffingID = st.StaffingID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactStaffingHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveFactStaffingHistory] hist +-- INNER JOIN [fp].[ArchiveFactStaffing] st ON hist.StaffingID = st.StaffingID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalFactStaffingHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[FactStaffingHistory] hist +-- INNER JOIN [fp].[FactStaffing] st ON hist.StaffingID = st.StaffingID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactStaffingHistoryRecords <> @numberOfOriginalFactStaffingHistoryRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactStaffingHistory] table.', 15, 1); +-- +---- copy StaffingChangeHistory table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveStaffingChangeHistory]([StaffingID],[AdjustmentGUID],[GroupingGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue]) +-- SELECT +-- hist.[StaffingID],[AdjustmentGUID],[GroupingGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],hist.[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue] +-- FROM [fp].[StaffingChangeHistory] hist +-- INNER JOIN [fp].[ArchiveFactStaffing] st ON hist.StaffingID = st.StaffingID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedStaffingChangeHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveStaffingChangeHistory] hist +-- INNER JOIN [fp].[ArchiveFactStaffing] st ON hist.StaffingID = st.StaffingID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalStaffingChangeHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[StaffingChangeHistory] hist +-- INNER JOIN [fp].[FactStaffing] st ON hist.StaffingID = st.StaffingID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedStaffingChangeHistoryRecords <> @numberOfOriginalStaffingChangeHistoryRecords) +-- RAISERROR ('Not all records were archived from [fp].[StaffingChangeHistory] table.', 15, 1); +-- +-- +-- -- remove original data (FK will cascade deletes) +-- DELETE FROM [fp].[FactStaffing] WHERE [BudgetConfigID] = @budgetConfigID; +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactStaffing] WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactStaffing] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactStaffingBudget] bdgt INNER JOIN [fp].[FactStaffing] st ON bdgt.StaffingID = st.StaffingID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactStaffingBudget] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactStaffingProjection] proj INNER JOIN [fp].[FactStaffing] st ON proj.StaffingID = st.StaffingID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactStaffingProjection] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactStaffingHistory] hist INNER JOIN [fp].[FactStaffing] st ON hist.StaffingID = st.StaffingID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactStaffingHistory] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[StaffingChangeHistory] hist INNER JOIN [fp].[FactStaffing] st ON hist.StaffingID = st.StaffingID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[StaffingChangeHistory] table.', 15, 2); +-- +-- +-- COMMIT TRANSACTION ArchiveStaffingData; +-- END TRY +-- BEGIN CATCH +-- ROLLBACK TRANSACTION ArchiveStaffingData; +-- +-- DECLARE @errorMessage NVARCHAR(MAX) = ERROR_MESSAGE(); +-- DECLARE @errorSeverity INT = ERROR_SEVERITY(); +-- DECLARE @errorState INT = ERROR_STATE(); +-- +-- RAISERROR (@errorMessage, @errorSeverity, @errorState); +-- END CATCH +-- +--RETURN; +END +GO + + +--------------------------------------------- + +-- fp.procArchiveStatisticsData +CREATE PROCEDURE [fp].[procArchiveStatisticsData] + @budgetConfigID SMALLINT +AS +BEGIN + SET NOCOUNT ON; + +-- BEGIN TRANSACTION ArchiveStatisticsData; +-- +-- BEGIN TRY +-- +-- -- copy FactStatistics table +-- +-- -- copy records +-- SET IDENTITY_INSERT [fp].[ArchiveFactStatistics] ON +-- INSERT INTO [fp].[ArchiveFactStatistics] ([StatisticsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [PatientClassID], [PayorID], [FinancialReportingID], [AccountID], [UnitTypeID], [AddDate], [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12], [SampledBudget01], [SampledBudget02], [SampledBudget03], [SampledBudget04], [SampledBudget05], [SampledBudget06], [SampledBudget07], [SampledBudget08], [SampledBudget09], [SampledBudget10], [SampledBudget11], [SampledBudget12], [SampledProjection01], [SampledProjection02], [SampledProjection03], [SampledProjection04], [SampledProjection05], [SampledProjection06], [SampledProjection07], [SampledProjection08], [SampledProjection09], [SampledProjection10], [SampledProjection11], [SampledProjection12]) +-- SElECT [StatisticsID], [BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [PatientClassID], [PayorID], [FinancialReportingID], [AccountID], [UnitTypeID], [AddDate], [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12], [SampledBudget01], [SampledBudget02], [SampledBudget03], [SampledBudget04], [SampledBudget05], [SampledBudget06], [SampledBudget07], [SampledBudget08], [SampledBudget09], [SampledBudget10], [SampledBudget11], [SampledBudget12], [SampledProjection01], [SampledProjection02], [SampledProjection03], [SampledProjection04], [SampledProjection05], [SampledProjection06], [SampledProjection07], [SampledProjection08], [SampledProjection09], [SampledProjection10], [SampledProjection11], [SampledProjection12] +-- FROM [fp].[FactStatistics] WHERE [BudgetConfigID] = @budgetConfigID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactAccountBasisRecords INT = (SELECT COUNT(*) FROM [fp].[ArchiveFactStatistics] WHERE [BudgetConfigID] = @budgetConfigID); +-- DECLARE @numberOfOriginalFactAccountBasisRecords INT = (SELECT COUNT(*) FROM [fp].[FactStatistics] WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactAccountBasisRecords <> @numberOfOriginalFactAccountBasisRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactStatistics] table.', 15, 1); +-- +-- +-- -- copy FactStatisticsBudget table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveFactStatisticsBudget] ([StatisticsID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12]) +-- SELECT bdgt.[StatisticsID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12] +-- FROM [fp].[FactStatisticsBudget] bdgt +-- INNER JOIN [fp].[ArchiveFactStatistics] stat ON bdgt.StatisticsID = stat.StatisticsID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactAccountBasisResultRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveFactStatisticsBudget] bdgt +-- INNER JOIN [fp].[ArchiveFactStatistics] stat ON bdgt.StatisticsID = stat.StatisticsID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalFactAccountBasisResultRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[FactStatisticsBudget] bdgt +-- INNER JOIN [fp].[FactStatistics] stat ON bdgt.StatisticsID = stat.StatisticsID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactAccountBasisResultRecords <> @numberOfOriginalFactAccountBasisResultRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactStatisticsBudget] table.', 15, 1); +-- +-- +-- +-- -- copy FactStatisticsProjection table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveFactStatisticsProjection] ([StatisticsID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12]) +-- SELECT proj.[StatisticsID], [LockType], [LockFlag], [BudgetPhaseID], [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12] +-- FROM [fp].[FactStatisticsProjection] proj +-- INNER JOIN [fp].[ArchiveFactStatistics] stat ON proj.StatisticsID = stat.StatisticsID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactAccountBasisProjectionRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveFactStatisticsProjection] proj +-- INNER JOIN [fp].[ArchiveFactStatistics] stat ON proj.StatisticsID = stat.StatisticsID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalFactAccountBasisProjectionRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[FactStatisticsProjection] proj +-- INNER JOIN [fp].[FactStatistics] stat ON proj.StatisticsID = stat.StatisticsID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactAccountBasisProjectionRecords <> @numberOfOriginalFactAccountBasisProjectionRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactStatisticsProjection] table.', 15, 1); +-- +---- copy FactStatisticsHistory table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveFactStatisticsHistory]([StatisticsID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12], +-- [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12], +-- [CurrentYearBudget01],[CurrentYearBudget02],[CurrentYearBudget03],[CurrentYearBudget04],[CurrentYearBudget05],[CurrentYearBudget06],[CurrentYearBudget07],[CurrentYearBudget08],[CurrentYearBudget09],[CurrentYearBudget10],[CurrentYearBudget11],[CurrentYearBudget12]) +-- SELECT +-- hist.[StatisticsID],[PriorYearActualValue01],[PriorYearActualValue02],[PriorYearActualValue03],[PriorYearActualValue04],[PriorYearActualValue05],[PriorYearActualValue06],[PriorYearActualValue07],[PriorYearActualValue08],[PriorYearActualValue09],[PriorYearActualValue10],[PriorYearActualValue11],[PriorYearActualValue12], +-- [ActualYTDValue01],[ActualYTDValue02],[ActualYTDValue03],[ActualYTDValue04],[ActualYTDValue05],[ActualYTDValue06],[ActualYTDValue07],[ActualYTDValue08],[ActualYTDValue09],[ActualYTDValue10],[ActualYTDValue11],[ActualYTDValue12], +-- [CurrentYearBudget01],[CurrentYearBudget02],[CurrentYearBudget03],[CurrentYearBudget04],[CurrentYearBudget05],[CurrentYearBudget06],[CurrentYearBudget07],[CurrentYearBudget08],[CurrentYearBudget09],[CurrentYearBudget10],[CurrentYearBudget11],[CurrentYearBudget12] +-- FROM [fp].[FactStatisticsHistory] hist +-- INNER JOIN [fp].[ArchiveFactStatistics] stat ON hist.StatisticsID = stat.StatisticsID; +-- +-- -- ensure all record were copied +-- DECLARE @numberOfArchivedFactStatisticsHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveFactStatisticsHistory] hist +-- INNER JOIN [fp].[ArchiveFactStatistics] stat ON hist.StatisticsID = stat.StatisticsID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalFactStatisticsHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[FactStatisticsHistory] hist +-- INNER JOIN [fp].[FactStatistics] stat ON hist.StatisticsID = stat.StatisticsID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedFactStatisticsHistoryRecords <> @numberOfOriginalFactStatisticsHistoryRecords) +-- RAISERROR ('Not all records were archived from [fp].[FactStatisticsHistory] table.', 15, 1); +-- +---- copy StatisticsChangeHistory table +-- +-- -- copy records +-- INSERT INTO [fp].[ArchiveStatisticsChangeHistory]([StatisticsID],[AdjustmentGUID],[GroupingGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue]) +-- SELECT +-- hist.[StatisticsID],[AdjustmentGUID],[GroupingGUID],[AdjustmentType],[SortOrder],[FiscalMonthID],hist.[UnitTypeID],[TimeClassID],[BudgetPhaseID],[OldValue],[NewValue] +-- FROM [fp].[StatisticsChangeHistory] hist +-- INNER JOIN [fp].[ArchiveFactStatistics] stat ON hist.StatisticsID = stat.StatisticsID; +-- +-- -- ensure all records were copied +-- DECLARE @numberOfArchivedStatisticsChangeHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[ArchiveStatisticsChangeHistory] hist +-- INNER JOIN [fp].[ArchiveFactStatistics] stat ON hist.StatisticsID = stat.StatisticsID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- DECLARE @numberOfOriginalStatisticsChangeHistoryRecords INT = ( +-- SELECT COUNT(*) +-- FROM [fp].[StatisticsChangeHistory] hist +-- INNER JOIN [fp].[FactStatistics] stat ON hist.StatisticsID = stat.StatisticsID +-- WHERE [BudgetConfigID] = @budgetConfigID); +-- +-- IF (@numberOfArchivedStatisticsChangeHistoryRecords <> @numberOfOriginalStatisticsChangeHistoryRecords) +-- RAISERROR ('Not all records were archived from [fp].[StatisticsChangeHistory] table.', 15, 1); +-- +-- +-- +-- -- remove original data (FK will cascade deletes) +-- DELETE FROM [fp].[FactStatistics] WHERE [BudgetConfigID] = @budgetConfigID; +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactStatistics] WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactStatistics] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactStatisticsBudget] bdgt INNER JOIN [fp].[FactStatistics] stat ON bdgt.StatisticsID = stat.StatisticsID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactStatisticsBudget] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactStatisticsProjection] proj INNER JOIN [fp].[FactStatistics] stat ON proj.StatisticsID = stat.StatisticsID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactStatisticsProjection] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[FactStatisticsHistory] hist INNER JOIN [fp].[FactStatistics] stat ON hist.StatisticsID = stat.StatisticsID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[FactStatisticsHistory] table.', 15, 2); +-- +-- IF EXISTS(SELECT 1 FROM [fp].[StatisticsChangeHistory] hist INNER JOIN [fp].[FactStatistics] stat ON hist.StatisticsID = stat.StatisticsID WHERE [BudgetConfigID] = @budgetConfigID) +-- RAISERROR ('Not all records were removed from [fp].[StatisticsChangeHistory] table.', 15, 2); +-- +-- +-- COMMIT TRANSACTION ArchiveStatisticsData; +-- END TRY +-- BEGIN CATCH +-- ROLLBACK TRANSACTION ArchiveStatisticsData; +-- +-- DECLARE @errorMessage NVARCHAR(MAX) = ERROR_MESSAGE(); +-- DECLARE @errorSeverity INT = ERROR_SEVERITY(); +-- DECLARE @errorState INT = ERROR_STATE(); +-- +-- RAISERROR (@errorMessage, @errorSeverity, @errorState); +-- END CATCH +-- +--RETURN; +END +GO + + +--------------------------------------------- + +-- fp.procBenefitsApplySpread +CREATE PROCEDURE [fp].[procBenefitsApplySpread] + @BudgetConfigID int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2019-03-19 AI B-22404 Initial + ** 2 2019-07-09 VI B-23668 Use viewBenefitsSpreads instead of fp.BenefitsSpreads + ** 3 2019-07-31 NL D-08581 updating the way spread remainder is allocated (w/feature flag) + ** 4 2019-11-01 MY B-24221 removing prevously added FF and making functionality always on + ** 5 2022-08-09 JB JAZZ-23177 Switch usages of funcGetSourceDimensionalityAsTable to a temp table + *************************************************************/ + IF OBJECT_ID('tempdb..#tmpGL') IS NOT NULL DROP TABLE #tmpGL; + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment; + CREATE TABLE #tmpGL (BenefitsID INT, DepartmentID INT, AccountID INT); + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #tmpGL (BenefitsID, DepartmentID, AccountID) + SELECT DISTINCT basis.BenefitsID, basis.DepartmentID, basis.AccountID + FROM [fp].[FactBenefits] basis + INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = basis.DepartmentID + INNER JOIN [fp].[FactBenefitsBudget] bb ON basis.BenefitsID = bb.BenefitsID + WHERE BudgetConfigID = @BudgetConfigID AND basis.UnitTypeID = 34 AND bb.LockType <> 5 AND bb.LockType <> 1 + END ELSE BEGIN + INSERT INTO #tmpGL (BenefitsID, DepartmentID, AccountID) + SELECT DISTINCT basis.BenefitsID, basis.DepartmentID, basis.AccountID + FROM [fp].[FactBenefits] basis + INNER JOIN [fp].[FactBenefitsBudget] bb ON basis.BenefitsID = bb.BenefitsID + WHERE BudgetConfigID = @BudgetConfigID AND basis.UnitTypeID = 34 AND bb.LockType <> 5 AND bb.LockType <> 1 + END + + UPDATE bb + SET LockType = 6, LockFlag = 1 + , AdjustedValue01 = CAST(AdjustedValueTotal * SpreadPercentage01 AS DECIMAL(19,8)) + , AdjustedValue02 = + CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + ELSE CAST(AdjustedValueTotal * SpreadPercentage02 AS DECIMAL(19,8)) END + , AdjustedValue03 = + CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage03 AS DECIMAL(19,8)) END + , AdjustedValue04 = + CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage04 AS DECIMAL(19,8)) END + , AdjustedValue05 = + CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage05 AS DECIMAL(19,8)) END + , AdjustedValue06 = + CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage06 AS DECIMAL(19,8)) END + , AdjustedValue07 = + CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage07 AS DECIMAL(19,8)) END + , AdjustedValue08 = + CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage08 AS DECIMAL(19,8)) END + , AdjustedValue09 = + CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage09 AS DECIMAL(19,8)) END + , AdjustedValue10 = + CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage09) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage10 AS DECIMAL(19,8)) END + , AdjustedValue11 = + CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage10) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage11 AS DECIMAL(19,8)) END + , AdjustedValue12 = + CASE WHEN SpreadPercentage12 != 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage11) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage12 AS DECIMAL(19,8)) END + FROM + [fp].[viewBenefitsSpreads] bs + INNER JOIN [fp].[FactBenefits] b ON bs.BudgetConfigID = b.BudgetConfigID AND bs.DepartmentID = b.DepartmentID AND bs.AccountID = b.AccountID + INNER JOIN #tmpGL tmp on b.BenefitsID = tmp.BenefitsID + INNER JOIN [fp].[FactBenefitsBudget] bb on b.BenefitsID = bb.BenefitsID + WHERE bb.BudgetPhaseID = 3 + AND bs.IsInactive = 0 + + -- Unlock Spreads that are no longer active + UPDATE bb + SET LockType = 0, LockFlag = 0 + FROM + [fp].[BenefitsSpreads] bs + INNER JOIN [fp].[FactBenefits] b ON bs.BudgetConfigID = b.BudgetConfigID AND bs.DepartmentID = b.DepartmentID AND bs.AccountID = b.AccountID + INNER JOIN #tmpGL tmp on b.BenefitsID = tmp.BenefitsID + INNER JOIN [fp].[FactBenefitsBudget] bb on b.BenefitsID = bb.BenefitsID + WHERE bb.BudgetPhaseID = 3 + AND bs.IsInactive = 1 + AND bb.LockFlag = 1 + AND bb.LockType = 6 + +END +GO + + +--------------------------------------------- + +-- fp.procBenefitsCopyNewItems +CREATE PROCEDURE [fp].[procBenefitsCopyNewItems] + @SourceBudgetConfigID INT, + @SourceEntityGroupConfigID INT, + @BudgetConfigID INT, + @EntityGroupConfigID INT +AS +BEGIN + + +INSERT INTO [fp].[FactBenefits] (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, FlexMethodID, AddDate, +SampledBudget01, SampledBudget02, SampledBudget03, SampledBudget04, SampledBudget05, SampledBudget06, SampledBudget07, SampledBudget08, SampledBudget09, SampledBudget10, SampledBudget11, SampledBudget12, +SampledProjection01, SampledProjection02, SampledProjection03, SampledProjection04, SampledProjection05, SampledProjection06, SampledProjection07, SampledProjection08, SampledProjection09, SampledProjection10, SampledProjection11, SampledProjection12, +InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, +InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12, +IsNew) +SELECT @BudgetConfigID, @EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, FlexMethodID, AddDate, +SampledBudget01, SampledBudget02, SampledBudget03, SampledBudget04, SampledBudget05, SampledBudget06, SampledBudget07, SampledBudget08, SampledBudget09, SampledBudget10, SampledBudget11, SampledBudget12, +SampledProjection01, SampledProjection02, SampledProjection03, SampledProjection04, SampledProjection05, SampledProjection06, SampledProjection07, SampledProjection08, SampledProjection09, SampledProjection10, SampledProjection11, SampledProjection12, +InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, +InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12, +IsNew +FROM [fp].[FactBenefits] +WHERE BudgetConfigID = @SourceBudgetConfigID AND EntityGroupConfigID = @SourceEntityGroupConfigID AND IsNew = 1 + +END +GO + + +--------------------------------------------- + +-- fp.procBudgetTargetSplitUpgrade +CREATE PROCEDURE fp.procBudgetTargetSplitUpgrade + @BudgetConfigID INT +AS +BEGIN + + IF EXISTS ( + SELECT TOP 1 1 FROM [fp].[StaffingAdjustment] adj + INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE Comment LIKE '%Target/Budget Upgrade.%' AND bc.BudgetConfigID = @BudgetConfigID + ) + BEGIN + PRINT 'The upgrade has already been completed for this budget' + RETURN; + END + + IF EXISTS ( + SELECT TOP 1 1 FROM [fp].[GeneralLedgerAdjustment] adj + INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE Comment LIKE '%Target/Budget Upgrade.%' AND bc.BudgetConfigID = @BudgetConfigID + ) + BEGIN + PRINT 'The upgrade has already been completed for this budget' + RETURN; + END + + IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'AdjustmentGrouping_PreSplitUpgrade')) + DROP TABLE [bak].[AdjustmentGrouping_PreSplitUpgrade] + + IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'StaffingAdjustment_PreSplitUpgrade')) + DROP TABLE [bak].[StaffingAdjustment_PreSplitUpgrade] + + IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'StaffingAdjustmentImport_PreSplitUpgrade')) + DROP TABLE [bak].[StaffingAdjustmentImport_PreSplitUpgrade] + + IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'StaffingBasisFlexRate_PreSplitUpgrade')) + DROP TABLE [bak].[StaffingBasisFlexRate_PreSplitUpgrade] + + IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'FTERequest_PreSplitUpgrade')) + DROP TABLE [bak].[FTERequest_PreSplitUpgrade] + + IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'FTERequestDetail_PreSplitUpgrade')) + DROP TABLE [bak].[FTERequestDetail_PreSplitUpgrade] + + IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'GeneralLedgerAdjustment_PreSplitUpgrade')) + DROP TABLE [bak].[GeneralLedgerAdjustment_PreSplitUpgrade] + + IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'GeneralLedgerAdjustmentImport_PreSplitUpgrade')) + DROP TABLE [bak].[GeneralLedgerAdjustmentImport_PreSplitUpgrade] + + + SELECT * INTO [bak].[AdjustmentGrouping_PreSplitUpgrade] FROM [fp].[AdjustmentGrouping] + SELECT * INTO [bak].[StaffingAdjustment_PreSplitUpgrade] FROM [fp].[StaffingAdjustment] + SELECT * INTO [bak].[StaffingAdjustmentImport_PreSplitUpgrade] FROM [fp].[StaffingAdjustmentImport] + SELECT * INTO [bak].[StaffingBasisFlexRate_PreSplitUpgrade] FROM [fp].[StaffingBasisFlexRate] + SELECT * INTO [bak].[FTERequest_PreSplitUpgrade] FROM [fp].[FTERequest] + SELECT * INTO [bak].[FTERequestDetail_PreSplitUpgrade] FROM [fp].[FTERequestDetail] + SELECT * INTO [bak].[GeneralLedgerAdjustment_PreSplitUpgrade] FROM [fp].[GeneralLedgerAdjustment] + SELECT * INTO [bak].[GeneralLedgerAdjustmentImport_PreSplitUpgrade] FROM [fp].[GeneralLedgerAdjustmentImport] + + EXEC fp.procBudgetTargetSplitUpgrade_GeneralLedger @BudgetConfigID + EXEC fp.procBudgetTargetSplitUpgrade_Staffing @BudgetConfigID + +END +GO + + +--------------------------------------------- + +-- fp.procBudgetTargetSplitUpgrade_Cleanup +CREATE PROCEDURE fp.procBudgetTargetSplitUpgrade_Cleanup + @BudgetConfigID INT +AS +BEGIN + + -- NOTE: This is for manual use only and used only in the event we need to roll back the upgrade for some reason. This will cleanup + -- all adjustments in staffing and GL with the comment containing Target/Budget split + + SELECT adj.* + INTO #adjustmentsToCopy_Staffing + FROM [fp].[StaffingAdjustment] adj + INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE Comment LIKE '%Target/Budget Upgrade%' + AND bc.BudgetConfigID = @BudgetConfigID + + DELETE data + FROM [fp].[StaffingAdjustmentImport] data + INNER JOIN #adjustmentsToCopy_Staffing adj ON data.AdjustmentGUID = adj.AdjustmentGUID + WHERE data.BudgetPhaseID = 3 + + DELETE data + FROM [fp].[StaffingBasisFlexRate] data + INNER JOIN #adjustmentsToCopy_Staffing adj ON data.AdjustmentGUID = adj.AdjustmentGUID + + DELETE data + FROM [fp].[FTERequest] data + INNER JOIN #adjustmentsToCopy_Staffing adj ON data.FTERequestGUID = adj.GroupingGUID + + DELETE data + FROM [fp].[FTERequestDetail] data + INNER JOIN #adjustmentsToCopy_Staffing adj ON data.FTERequestGUID = adj.GroupingGUID + + DELETE data + FROM [fp].[StaffingAdjustment] data + INNER JOIN #adjustmentsToCopy_Staffing adj ON data.AdjustmentGUID = adj.AdjustmentGUID + + DELETE grp + FROM [fp].[AdjustmentGrouping] grp + INNER JOIN #adjustmentsToCopy_Staffing adj ON grp.GroupingGUID = adj.GroupingGUID + + SELECT adj.* + INTO #adjustmentsToCopy_GeneralLedger + FROM [fp].[GeneralLedgerAdjustment] adj + INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE Comment LIKE '%Target/Budget Upgrade%' + AND bc.BudgetConfigID = @BudgetConfigID + + DELETE data + FROM [fp].[GeneralLedgerAdjustmentImport] data + INNER JOIN #adjustmentsToCopy_GeneralLedger adj ON data.AdjustmentGUID = adj.AdjustmentGUID + WHERE data.BudgetPhaseID = 3 + + DELETE data + FROM [fp].[GeneralLedgerAdjustment] data + INNER JOIN #adjustmentsToCopy_GeneralLedger adj ON data.AdjustmentGUID = adj.AdjustmentGUID + + DELETE grp + FROM [fp].[AdjustmentGrouping] grp + INNER JOIN #adjustmentsToCopy_GeneralLedger adj ON grp.GroupingGUID = adj.GroupingGUID +END +GO + + +--------------------------------------------- + +-- fp.procBudgetTargetSplitUpgrade_Cleanup_Statistics +CREATE PROCEDURE fp.procBudgetTargetSplitUpgrade_Cleanup_Statistics + @BudgetConfigID INT +AS +BEGIN + + -- NOTE: This is for manual use only and used only in the event we need to roll back the upgrade for some reason. + + IF OBJECT_ID('tempdb..#adjustmentsToCopy_Statistics') IS NOT NULL DROP TABLE #adjustmentsToCopy_Statistics + + SELECT adj.* + INTO #adjustmentsToCopy_Statistics + FROM [fp].[StatisticsAdjustment] adj + INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE Comment LIKE '%Target/Budget Upgrade%' + AND bc.BudgetConfigID = @BudgetConfigID + + DELETE data + FROM [fp].[StatisticsAdjustmentRate] data + INNER JOIN #adjustmentsToCopy_Statistics adj ON data.AdjustmentGUID = adj.AdjustmentGUID + WHERE data.BudgetPhaseID = 3 + + DELETE data + FROM [fp].[StatisticsAdjustmentImport] data + INNER JOIN #adjustmentsToCopy_Statistics adj ON data.AdjustmentGUID = adj.AdjustmentGUID + WHERE data.BudgetPhaseID = 3 + + DELETE data + FROM [fp].[StatisticAddProviderAdjustment] data + INNER JOIN #adjustmentsToCopy_Statistics adj ON data.AdjustmentGUID = adj.AdjustmentGUID + WHERE data.BudgetPhaseID = 3 AND data.TimeClassID = 2 + + DELETE data + FROM [fp].[StatisticsAdjustment] data + INNER JOIN #adjustmentsToCopy_Statistics adj ON data.AdjustmentGUID = adj.AdjustmentGUID + WHERE + adj.AdjustmentType <> 15 -- we don't need to delete add provider adjustments, only a comment update needed + + UPDATE data + SET Comment = REPLACE(data.Comment, 'Adjustment has been generated from the Target/Budget Upgrade.', ''), + DateCreatedUTC = DATEADD(yy, +100, DateCreatedUTC) -- return the original date + FROM [fp].[StatisticsAdjustment] data + INNER JOIN [fp].[BudgetConfig] bc ON data.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN #adjustmentsToCopy_Statistics adj ON data.AdjustmentGUID = adj.AdjustmentGUID + WHERE BudgetConfigID = @BudgetConfigID + AND data.AdjustmentType = 15 + AND data.Comment LIKE '%Adjustment has been generated from the Target/Budget Upgrade.%' + + DELETE grp + FROM [fp].[AdjustmentGrouping] grp + INNER JOIN #adjustmentsToCopy_Statistics adj ON grp.GroupingGUID = adj.GroupingGUID + WHERE adj.AdjustmentType <> 4 + +END +GO + + +--------------------------------------------- + +-- fp.procBudgetTargetSplitUpgrade_GeneralLedger +CREATE PROCEDURE [fp].[procBudgetTargetSplitUpgrade_GeneralLedger] + @BudgetConfigID INT, + @IsDebug INT = 0 +AS +BEGIN + DECLARE @Message NVARCHAR(MAX) = 'Adjustment has been generated from the Target/Budget Upgrade.', + @Spacing NVARCHAR(MAX) = ' + +'; -- I know this looks wierd, but leave it, it works. + + + IF EXISTS ( + SELECT TOP 1 1 FROM [fp].[GeneralLedgerAdjustment] adj + INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE Comment LIKE '%Target/Budget Upgrade.%' AND bc.BudgetConfigID = @BudgetConfigID + ) + BEGIN + PRINT 'The upgrade has already been completed for this budget' + RETURN; + END + + -- Get all of the adjustments we need to copy to Budget + SELECT adj.*, adj.AdjustmentGUID AS OriginalAdjustmentGUID + INTO #adjustmentsToCopy + FROM [fp].[GeneralLedgerAdjustment] adj + INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND BudgetPhaseID = 2 -- Imports do not use the budget phase property so we'll just need to make sure we copy those rows over later. + AND TimeClassID = 2 -- We only need to copy budget adjustments, not projection + AND AdjustmentType != 9 -- Spread unlocks can only happen to Budget, not target so we don't have to worry about these. + AND AdjustmentType != 4 -- Just making sure the imports aren't included + + -- copy import adjustments to the table, we do these seperately because we only want target adjusted adjustments + INSERT INTO #adjustmentsToCopy ([AdjustmentGUID], [BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON], [GroupingHierarchyJSON], [AdjustedProperty], + [Comment], [AuthorGUID], [AuthorFullName], [LastModifiedDateUtc], [DateCreatedUtc], [UnitTypeID], [GroupingGUID], [TimeClassID], [BudgetPhaseID], [ClassificationGroupID], + [ClassificationCategoryID], [IsRecordDeleted], [OriginalAdjustmentGUID]) + SELECT + adj.[AdjustmentGUID], adj.[BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON], [GroupingHierarchyJSON], [AdjustedProperty], + [Comment], [AuthorGUID], [AuthorFullName], [LastModifiedDateUtc], [DateCreatedUtc], [UnitTypeID], [GroupingGUID], [TimeClassID], adj.[BudgetPhaseID], [ClassificationGroupID], + [ClassificationCategoryID], [IsRecordDeleted], adj.[AdjustmentGUID] + FROM [fp].[GeneralLedgerAdjustment] adj + INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN (SELECT DISTINCT AdjustmentGUID, BudgetPhaseID FROM [fp].[GeneralLedgerAdjustmentImport]) imp ON adj.AdjustmentGUID = imp.AdjustmentGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND imp.BudgetPhaseID = 2 -- We only want to copy imports that contain target adjustments + AND adj.AdjustmentType = 4 + + -- Get a list of all the unique groupingGuids. We'll then need to update these later + SELECT DISTINCT GroupingGUID, NEWID() AS NewGroupingGUID + INTO #groupings + FROM #adjustmentsToCopy + WHERE AdjustmentType != 4 -- We don't need to copy import because we're not creating seperate adjustments for these. + AND GroupingGUID != '00000000-0000-0000-0000-000000000000' + + -- Create duplicate adjustment groupings + SELECT tmp.NewGroupingGUID, + Description = CASE WHEN LEN(TRIM(Description)) = 0 THEN @Message + WHEN RIGHT(TRIM(Description), 1) != '.' THEN CONCAT(Description, CONCAT(CONCAT('. ', @Spacing), @Message)) + ELSE CONCAT(Description, CONCAT(@Spacing, @Message)) END, + ExcelFile, + IsRecordDeleted + INTO #newGroupings + FROM [fp].[AdjustmentGrouping] grp + INNER JOIN #groupings tmp ON grp.GroupingGUID = tmp.GroupingGUID + + -- Update the adjustments comment, phase, and date time so that they are before any final budget adjustments + UPDATE #adjustmentsToCopy + SET AdjustmentGUID = NEWID(), + Comment = CASE WHEN LEN(TRIM(Comment)) = 0 THEN @Message + WHEN RIGHT(TRIM(Comment), 1) != '.' THEN CONCAT(Comment, CONCAT(CONCAT('. ', @Spacing), @Message)) + ELSE CONCAT(Comment, CONCAT(@Spacing, @Message)) + END, + BudgetPhaseID = 3, + DateCreatedUtc = DATEADD(yy, -100, DateCreatedUtc), -- Descrease the current time by 100 years so we keep the rough date/time + AdjustedProperty = CASE WHEN AdjustedProperty = 'CurrentBudget' THEN 'mgr' ELSE REPLACE(AdjustedProperty, 'm', 'mam') END + + -- Update the groupings for any existing groupings so we keep the adjustments together. + UPDATE adj + SET adj.GroupingGUID = grp.NewGroupingGUID + FROM #adjustmentsToCopy adj + INNER JOIN #groupings grp ON adj.GroupingGUID = grp.GroupingGUID + + -- Copy the target adjustments over to final budget for imports + SELECT + adj.[AdjustmentGUID], [DepartmentID], [AccountID], [FinancialReportingID], imp.[FiscalYearID], imp.[UnitTypeID], [FiscalMonthID], + imp.[Value], [VariabilityID], [EntityID], imp.[TimeClassID], 3 AS BudgetPhaseID, imp.[IsRecordDeleted] + INTO #newImportAdjustments + FROM [fp].[GeneralLedgerAdjustmentImport] imp + INNER JOIN #adjustmentsToCopy adj ON adj.OriginalAdjustmentGUID = imp.AdjustmentGUID + WHERE imp.BudgetPhaseID = 2 + AND imp.TimeClassID = 2 + AND adj.AdjustmentType = 4 + + IF @IsDebug = 1 + BEGIN + + SELECT 'New Groupings', * FROM #newGroupings + SELECT 'New Imports', * FROM #newImportAdjustments + SELECT 'New Adjustments', * FROM #adjustmentsToCopy + + END ELSE + BEGIN + + INSERT INTO [fp].[AdjustmentGrouping] ([GroupingGUID], [Description], [ExcelFile], [IsRecordDeleted]) + SELECT [NewGroupingGUID], [Description], [ExcelFile], [IsRecordDeleted] + FROM #newGroupings + + INSERT INTO [fp].[GeneralLedgerAdjustment] ([AdjustmentGUID], [BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON], [GroupingHierarchyJSON], [AdjustedProperty], + [Comment], [AuthorGUID], [AuthorFullName], [LastModifiedDateUtc], [DateCreatedUtc], [UnitTypeID], [GroupingGUID], [TimeClassID], [BudgetPhaseID], [ClassificationGroupID], + [ClassificationCategoryID], [IsRecordDeleted]) + SELECT + [AdjustmentGUID], [BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON], [GroupingHierarchyJSON], [AdjustedProperty], [Comment], [AuthorGUID], [AuthorFullName], + [LastModifiedDateUtc], [DateCreatedUtc], [UnitTypeID], [GroupingGUID], [TimeClassID], [BudgetPhaseID], [ClassificationGroupID], + [ClassificationCategoryID], [IsRecordDeleted] + FROM #adjustmentsToCopy + + INSERT INTO [fp].[GeneralLedgerAdjustmentImport]([AdjustmentGUID], [DepartmentID], [AccountID], [FinancialReportingID], [FiscalYearID], [UnitTypeID], [FiscalMonthID], + [Value], [VariabilityID], [EntityID], [TimeClassID], [BudgetPhaseID], [IsRecordDeleted]) + SELECT [AdjustmentGUID], [DepartmentID], [AccountID], [FinancialReportingID], [FiscalYearID], [UnitTypeID], [FiscalMonthID], + [Value], [VariabilityID], [EntityID], [TimeClassID], [BudgetPhaseID], [IsRecordDeleted] + FROM #newImportAdjustments + + END + +END; +GO + + +--------------------------------------------- + +-- fp.procBudgetTargetSplitUpgrade_Staffing +CREATE PROCEDURE [fp].[procBudgetTargetSplitUpgrade_Staffing] + @BudgetConfigID INT, + @IsDebug INT = 0 +AS +BEGIN +DECLARE @Message NVARCHAR(MAX) = 'Adjustment has been generated from the Target/Budget Upgrade.', + @Spacing NVARCHAR(MAX) = ' + +'; -- I know this looks wierd, but leave it, it works. + + + IF EXISTS ( + SELECT TOP 1 1 FROM [fp].[StaffingAdjustment] adj + INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE Comment LIKE '%Target/Budget Upgrade.%' AND bc.BudgetConfigID = @BudgetConfigID + ) + BEGIN + PRINT 'The upgrade has already been completed for this budget' + RETURN; + END + + -- Get all of the adjustments we need to copy to Budget + SELECT adj.*, adj.AdjustmentGUID AS OriginalAdjustmentGUID + INTO #adjustmentsToCopy + FROM [fp].[StaffingAdjustment] adj + INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ((BudgetPhaseID = 2 AND TimeClassID = 2) OR AdjustmentType = 6) -- We need add fte and imports as well + AND AdjustmentType != 9 -- Spread unlocks can only happen to Budget, not target so we don't have to worry about these. + AND AdjustmentType != 4 + + -- copy import adjustments to the table, we do these seperately because we only want target adjusted adjustments + INSERT INTO #adjustmentsToCopy ([AdjustmentGUID], [BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON], [GroupingHierarchyJSON], [AdjustedProperty], + [Comment], [AuthorGUID], [AuthorFullName], [LastModifiedDateUtc], [DateCreatedUtc], [UnitTypeID], [GroupingGUID], [TimeClassID], [BudgetPhaseID], [ClassificationGroupID], + [ClassificationCategoryID], [IsRecordDeleted], [OriginalAdjustmentGUID], [ParentFilterJSON]) + SELECT + adj.[AdjustmentGUID], adj.[BudgetConfigGUID], [AdjustmentType], adj.[Value], [AdjustmentFilterJSON], [GroupingHierarchyJSON], [AdjustedProperty], + [Comment], [AuthorGUID], [AuthorFullName], [LastModifiedDateUtc], [DateCreatedUtc], adj.[UnitTypeID], [GroupingGUID], adj.[TimeClassID], adj.[BudgetPhaseID], [ClassificationGroupID], + [ClassificationCategoryID], adj.[IsRecordDeleted], adj.[AdjustmentGUID], [ParentFilterJSON] + FROM [fp].[StaffingAdjustment] adj + INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN (SELECT DISTINCT AdjustmentGUID, BudgetPhaseID FROM [fp].[StaffingAdjustmentImport]) imp ON adj.AdjustmentGUID = imp.AdjustmentGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND imp.BudgetPhaseID = 2 -- We only want to copy imports that contain target adjustments + AND adj.AdjustmentType = 4 + + -- Get a list of all the unique groupingGuids. We'll then need to update these later + SELECT DISTINCT GroupingGUID, '00000000-0000-0000-0000-000000000000' AS NewGroupingGUID + INTO #groupings + FROM #adjustmentsToCopy + WHERE GroupingGUID != '00000000-0000-0000-0000-000000000000' + + UPDATE #groupings SET NewGroupingGUID = NEWID(); + + -- Create duplicate adjustment groupings + SELECT tmp.NewGroupingGUID, + Description = CASE WHEN LEN(TRIM(Description)) = 0 THEN @Message + WHEN RIGHT(TRIM(Description), 1) != '.' THEN CONCAT(Description, CONCAT(CONCAT('. ', @Spacing), @Message)) + ELSE CONCAT(Description, CONCAT(@Spacing, @Message)) END, + ExcelFile, + IsRecordDeleted + INTO #newGroupings + FROM [fp].[AdjustmentGrouping] grp + INNER JOIN #groupings tmp ON grp.GroupingGUID = tmp.GroupingGUID + + -- Update the adjustments comment, phase, and date time so that they are before any final budget adjustments + UPDATE #adjustmentsToCopy + SET AdjustmentGUID = NEWID(), + Comment = CASE WHEN LEN(TRIM(Comment)) = 0 THEN @Message + WHEN RIGHT(TRIM(Comment), 1) != '.' THEN CONCAT(Comment, CONCAT(CONCAT('. ', @Spacing), @Message)) + ELSE CONCAT(Comment, CONCAT(@Spacing, @Message)) + END, + BudgetPhaseID = 3, + DateCreatedUtc = DATEADD(yy, -100, DateCreatedUtc), -- Descrease the current time by 100 years so we keep the rough date/time + AdjustedProperty = CASE + WHEN AdjustedProperty LIKE 'CurrentBudget%' THEN REPLACE(AdjustedProperty, 'CurrentBudget', 'ManagerBudget') + WHEN AdjustedProperty LIKE 'f%' THEN REPLACE(AdjustedProperty, 'f', 'bf') + WHEN AdjustedProperty LIKE 'h%' THEN REPLACE(AdjustedProperty, 'h', 'bh') + WHEN AdjustedProperty LIKE 'd%' THEN REPLACE(AdjustedProperty, 'd', 'bd') + WHEN AdjustedProperty LIKE 'w%' THEN REPLACE(AdjustedProperty, 'w', 'bw') + ELSE AdjustedProperty + END + WHERE AdjustmentType != 8 -- Variable reset, these will need to be handled a bit differently + + ------ VARIABLE SET ADJUSTMENTS - START ------- + + -- Create new adjustmentGuids so we know what we need to populate, need the old one's so we know what we need to copy over and how to link them + SELECT *, NEWID() AS NewAdjustmentGUID + INTO #variableSetAdjustments + FROM #adjustmentsToCopy + WHERE AdjustmentType = 8 + + -- Copy Basis Flex Rate table data + SELECT flex.*, adj.NewAdjustmentGUID AS NewAdjustmentGUID -- The adjustment will get updated next + INTO #variableSetAdjustmentsFlexRate + FROM [fp].[StaffingBasisFlexRate] flex + INNER JOIN #variableSetAdjustments adj ON flex.AdjustmentGUID = adj.AdjustmentGUID + + -- Update the adjustments for the variable set + UPDATE adj + SET adj.AdjustmentGUID = varAdj.NewAdjustmentGUID, + adj.Comment = CASE WHEN LEN(TRIM(adj.Comment)) = 0 THEN @Message + WHEN RIGHT(TRIM(adj.Comment), 1) != '.' THEN CONCAT(adj.Comment, CONCAT(CONCAT('. ', @Spacing), @Message)) + ELSE CONCAT(adj.Comment, CONCAT(@Spacing, @Message)) + END, + adj.BudgetPhaseID = 3, + adj.DateCreatedUtc = DATEADD(yy, -100, adj.DateCreatedUtc), -- Descrease the current time by 100 years so we keep the rough date/time + adj.AdjustedProperty = CASE + WHEN adj.AdjustedProperty LIKE 'CurrentBudget%' THEN REPLACE(adj.AdjustedProperty, 'CurrentBudget', 'ManagerBudget') + WHEN adj.AdjustedProperty LIKE 'f%' THEN REPLACE(adj.AdjustedProperty, 'f', 'bf') + WHEN adj.AdjustedProperty LIKE 'h%' THEN REPLACE(adj.AdjustedProperty, 'h', 'bh') + WHEN adj.AdjustedProperty LIKE 'd%' THEN REPLACE(adj.AdjustedProperty, 'd', 'bd') + WHEN adj.AdjustedProperty LIKE 'w%' THEN REPLACE(adj.AdjustedProperty, 'w', 'bw') + ELSE adj.AdjustedProperty + END + FROM #adjustmentsToCopy adj + INNER JOIN #variableSetAdjustments varAdj ON adj.AdjustmentGUID = varAdj.AdjustmentGUID + + ------ VARIABLE SET ADJUSTMENTS - END ------- + + -- Update the groupings for any existing groupings so we keep the adjustments together. + UPDATE adj + SET adj.GroupingGUID = grp.NewGroupingGUID + FROM #adjustmentsToCopy adj + INNER JOIN #groupings grp ON adj.GroupingGUID = grp.GroupingGUID + + ------ ADD FTE - START ------- + + -- Create new Requests + SELECT [FTERequestGUID], NEWID() AS NewFTERequestGUID, fte.[BudgetConfigGUID], [DepartmentID], [JobCodeID], [FTEAmount], [StartFiscalMonthID], + [WageRate], [Comment], [DateCreatedUtc], grp.NewGroupingGUID AS GroupingGUID + INTO #newFteRequests + FROM [fp].[FTERequest] fte + INNER JOIN fp.BudgetConfig bc ON fte.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN #groupings grp ON grp.GroupingGUID = fte.GroupingGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + + -- Create detail requests + SELECT NEWID() AS FTERequestDetailGUID, req.[NewFTERequestGUID], [PayCodeGroupID], [HoursMix] + INTO #newFteRequestDetails + FROM [fp].[FTERequestDetail] detail + INNER JOIN #newFteRequests req ON req.FTERequestGUID = detail.FTERequestGUID + + ------ ADD FTE - END ------- + + ------ IMPORT - START ------- + + -- Copy the target adjustments over to final budget for imports + SELECT + adj.[AdjustmentGUID], [DepartmentID], [JobCodeID], [ProductiveClassID], [PayCodeGroupID], imp.[FiscalYearID], imp.[UnitTypeID], [FiscalMonthID], + imp.[Value], [VariabilityID], [EntityID], imp.[TimeClassID], 3 AS BudgetPhaseID, imp.[IsRecordDeleted] + INTO #newImportAdjustments + FROM [fp].[StaffingAdjustmentImport] imp + INNER JOIN #adjustmentsToCopy adj ON imp.AdjustmentGUID = adj.OriginalAdjustmentGUID + INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND imp.BudgetPhaseID = 2 + AND imp.TimeClassID = 2 -- We don't need to worry about Projection + + ------ IMPORT - END ------- + + IF @IsDebug = 1 + BEGIN + + SELECT 'New Groupings', * FROM #newGroupings + SELECT 'New Imports', * FROM #newImportAdjustments + SELECT 'New Adjustments', * FROM #adjustmentsToCopy + SELECT 'New Variable Set Adjustments', * FROM #variableSetAdjustmentsFlexRate + SELECT 'New FTE Request', * FROM #newFteRequests + SELECT 'New FTE Request Details', * FROM #newFteRequestDetails + + END ELSE + BEGIN + + INSERT INTO [fp].[AdjustmentGrouping] ([GroupingGUID], [Description], [ExcelFile], [IsRecordDeleted]) + SELECT [NewGroupingGUID], [Description], [ExcelFile], [IsRecordDeleted] + FROM #newGroupings + + INSERT INTO [fp].[StaffingAdjustment] ([AdjustmentGUID], [BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON], [GroupingHierarchyJSON], [AdjustedProperty], + [Comment], [AuthorGUID], [AuthorFullName], [LastModifiedDateUtc], [DateCreatedUtc], [UnitTypeID], [GroupingGUID], [TimeClassID], [BudgetPhaseID], [ClassificationGroupID], + [ClassificationCategoryID], [IsRecordDeleted]) + SELECT + [AdjustmentGUID], [BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON], [GroupingHierarchyJSON], [AdjustedProperty], [Comment], [AuthorGUID], [AuthorFullName], + [LastModifiedDateUtc], [DateCreatedUtc], [UnitTypeID], [GroupingGUID], [TimeClassID], [BudgetPhaseID], [ClassificationGroupID], + [ClassificationCategoryID], [IsRecordDeleted] + FROM #adjustmentsToCopy + + INSERT INTO [fp].[StaffingAdjustmentImport]([AdjustmentGUID], [DepartmentID], [JobCodeID], [ProductiveClassID], [PayCodeGroupID], [FiscalYearID], [UnitTypeID], [FiscalMonthID], + [Value], [VariabilityID], [EntityID], [TimeClassID], [BudgetPhaseID], [IsRecordDeleted]) + SELECT [AdjustmentGUID], [DepartmentID], [JobCodeID], [ProductiveClassID], [PayCodeGroupID], [FiscalYearID], [UnitTypeID], [FiscalMonthID], + [Value], [VariabilityID], [EntityID], [TimeClassID], [BudgetPhaseID], [IsRecordDeleted] + FROM #newImportAdjustments + + INSERT INTO [fp].[StaffingBasisFlexRate]([EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [FiscalYearID], [FiscalMonthID], [TimeClassID], [FlexRate], [BudgetConfigID], [AdjustmentGUID]) + SELECT [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [FiscalYearID], [FiscalMonthID], + [TimeClassID], [FlexRate], [BudgetConfigID], [NewAdjustmentGUID] + FROM #variableSetAdjustmentsFlexRate + + INSERT INTO [fp].[FTERequest] ([FTERequestGUID], [BudgetConfigGUID], [DepartmentID], [JobCodeID], [FTEAmount], [StartFiscalMonthID], [WageRate], [Comment], [DateCreatedUtc], [GroupingGUID]) + SELECT [NewFTERequestGUID], [BudgetConfigGUID], [DepartmentID], [JobCodeID], [FTEAmount], [StartFiscalMonthID], [WageRate], [Comment], [DateCreatedUtc], [GroupingGUID] + FROM #newFteRequests + + INSERT INTO [fp].[FTERequestDetail] ([FTERequestDetailGUID], [FTERequestGUID], [PayCodeGroupID], [HoursMix]) + SELECT [FTERequestDetailGUID], [NewFTERequestGUID], [PayCodeGroupID], [HoursMix] + FROM #newFteRequestDetails + + END + +END; +GO + + +--------------------------------------------- + +-- fp.procBudgetTargetSplitUpgrade_Statistics +CREATE PROCEDURE fp.procBudgetTargetSplitUpgrade_Statistics + @BudgetConfigID INT, + @IsDebug INT = 0 +AS +BEGIN + + IF OBJECT_ID('tempdb..#newGroupings') IS NOT NULL DROP TABLE #newGroupings + IF OBJECT_ID('tempdb..#groupings') IS NOT NULL DROP TABLE #groupings + IF OBJECT_ID('tempdb..#newImportAdjustments') IS NOT NULL DROP TABLE #newImportAdjustments + IF OBJECT_ID('tempdb..#adjustmentsToCopy') IS NOT NULL DROP TABLE #adjustmentsToCopy + IF OBJECT_ID('tempdb..#adjustmentRateToCopy') IS NOT NULL DROP TABLE #adjustmentRateToCopy + IF OBJECT_ID('tempdb..#newAddProviderAdjustments') IS NOT NULL DROP TABLE #newAddProviderAdjustments + + DECLARE @Message NVARCHAR(MAX) = 'Adjustment has been generated from the Target/Budget Upgrade.', + @Spacing NVARCHAR(MAX) = ' + +'; -- I know this looks wierd, but leave it, it works. + + + IF EXISTS ( + SELECT TOP 1 1 FROM [fp].[StatisticsAdjustment] adj + INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE Comment LIKE '%Target/Budget Upgrade.%' AND bc.BudgetConfigID = @BudgetConfigID + ) + BEGIN + PRINT 'The upgrade has already been completed for this budget' + RETURN; + END + + -- Get all of the adjustments we need to copy to Budget + SELECT adj.*, adj.AdjustmentGUID AS OriginalAdjustmentGUID + INTO #adjustmentsToCopy + FROM [fp].[StatisticsAdjustment] adj + INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND BudgetPhaseID = 2 -- Imports do not use the budget phase property so we'll just need to make sure we copy those rows over later. + AND TimeClassID = 2 -- We only need to copy budget adjustments, not projection + AND AdjustmentType != 9 -- Spread unlocks can only happen to Budget, not target so we don't have to worry about these. + AND AdjustmentType != 4 -- Just making sure the imports aren't included + AND AdjustmentType != 15 -- Just making sure the add provider aren't included + + -- copy import adjustments to the table, we do these seperately because we only want target adjusted adjustments + INSERT INTO #adjustmentsToCopy ([AdjustmentGUID], [BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON], + [GroupingHierarchyJSON], [AdjustedProperty], [Comment], [AuthorGUID], [AuthorFullName], [GroupingGUID], [ParentFilterJSON], [TimeClassID], + [ClassificationGroupID], [ClassificationCategoryID], [IsRecordDeleted],[DateCreatedUtc], [LastModifiedDateUtc], [DimensionMemberJson], + [AdjustmentID], [SubsectionID], adj.[BudgetPhaseID], [IsErrored], [OriginalAdjustmentGUID]) + SELECT + adj.[AdjustmentGUID], adj.[BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON], + [GroupingHierarchyJSON], [AdjustedProperty], [Comment], [AuthorGUID], [AuthorFullName], [GroupingGUID], [ParentFilterJSON], [TimeClassID], + [ClassificationGroupID], [ClassificationCategoryID], [IsRecordDeleted],[DateCreatedUtc], [LastModifiedDateUtc], [DimensionMemberJson], + [AdjustmentID], [SubsectionID], adj.[BudgetPhaseID], [IsErrored], adj.[AdjustmentGUID] + FROM [fp].[StatisticsAdjustment] adj + INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN (SELECT DISTINCT AdjustmentGUID, BudgetPhaseID FROM [fp].[StatisticsAdjustmentImport]) imp ON adj.AdjustmentGUID = imp.AdjustmentGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND imp.BudgetPhaseID = 2 -- We only want to copy imports that contain target adjustments + AND adj.AdjustmentType = 4 + + -- Get a list of all the unique groupingGuids. We'll then need to update these later + SELECT DISTINCT GroupingGUID, NEWID() AS NewGroupingGUID + INTO #groupings + FROM #adjustmentsToCopy + WHERE AdjustmentType != 4 -- We don't need to copy import because we're not creating seperate adjustments for these. + AND AdjustmentType != 15 -- We don't need to copy for add provider + AND GroupingGUID != '00000000-0000-0000-0000-000000000000' + + -- Create duplicate adjustment groupings + SELECT tmp.NewGroupingGUID, + Description = CASE WHEN LEN(TRIM(Description)) = 0 THEN @Message + WHEN RIGHT(TRIM(Description), 1) != '.' THEN CONCAT(Description, CONCAT(CONCAT('. ', @Spacing), @Message)) + ELSE CONCAT(Description, CONCAT(@Spacing, @Message)) END, + ExcelFile, + IsRecordDeleted + INTO #newGroupings + FROM [fp].[AdjustmentGrouping] grp + INNER JOIN #groupings tmp ON grp.GroupingGUID = tmp.GroupingGUID + + -- Update the adjustments comment, phase, and date time so that they are before any final budget adjustments + UPDATE #adjustmentsToCopy + SET AdjustmentGUID = NEWID(), + Comment = CASE WHEN LEN(TRIM(Comment)) = 0 THEN @Message + WHEN RIGHT(TRIM(Comment), 1) != '.' THEN CONCAT(Comment, CONCAT(CONCAT('. ', @Spacing), @Message)) + ELSE CONCAT(Comment, CONCAT(@Spacing, @Message)) + END, + BudgetPhaseID = 3, + DateCreatedUTC = DATEADD(yy, -100, DateCreatedUTC), -- Descrease the current time by 100 years so we keep the rough date/time + AdjustedProperty = CASE WHEN AdjustedProperty LIKE 'm[0-9]%' THEN REPLACE(AdjustedProperty, 'm', 'mam') ELSE AdjustedProperty END + + -- Update the groupings for any existing groupings so we keep the adjustments together. + UPDATE adj + SET adj.GroupingGUID = grp.NewGroupingGUID + FROM #adjustmentsToCopy adj + INNER JOIN #groupings grp ON adj.GroupingGUID = grp.GroupingGUID + + -- Copy Dependent Statistics adjustment rate + SELECT adj.[AdjustmentGUID], rate.[AdjustmentID], [BudgetConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], + [PayorID], [PatientClassID], [ProviderLineItemID], [ProviderID], [ProviderSpecialtyID], [ProviderTypeID], rate.[SubsectionID], + rate.[TimeClassID], [Value01], [Value02], [Value03], [Value04], [Value05], [Value06], [Value07], [Value08], [Value09], [Value10], + [Value11], [Value12], 3 AS [BudgetPhaseID] + INTO #adjustmentRateToCopy + FROM [fp].[StatisticsAdjustmentRate] rate + INNER JOIN #adjustmentsToCopy adj ON adj.OriginalAdjustmentGUID = rate.AdjustmentGUID + WHERE rate.BudgetPhaseID = 2 + AND rate.TimeClassID = 2 + + -- Copy the target adjustments over to final budget for imports + SELECT + adj.[AdjustmentGUID], [DepartmentID], [EntityID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID], imp.[FiscalYearID], + [FiscalMonthID], [UnitTypeID], imp.[Value], [Version], imp.[TimeClassID], imp.[IsRecordDeleted], imp.[AdjustmentID], [ProviderID], + [ProviderTypeID], [ProviderLineItemID], [ProviderSpecialtyID], 3 as [BudgetPhaseID] + INTO #newImportAdjustments + FROM [fp].[StatisticsAdjustmentImport] imp + INNER JOIN #adjustmentsToCopy adj ON adj.OriginalAdjustmentGUID = imp.AdjustmentGUID + WHERE imp.BudgetPhaseID = 2 + AND imp.TimeClassID = 2 + AND adj.AdjustmentType = 4 + + -- Copy add provider adjustments + SELECT + [BudgetConfigID], [AdjustmentGUID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID],[PayorID], + [PatientClassID], [ProviderLineItemID], [ProviderID], [ProviderSpecialtyID], [ProviderTypeID], [TimeClassID], 3 as [BudgetPhaseID], [SubsectionID], + [IsRecordDeleted], [Value01], [Value02], [Value03], [Value04], [Value05], [Value06], [Value07], [Value08], [Value09], [Value10], [Value11], [Value12] + INTO #newAddProviderAdjustments + FROM [fp].[StatisticAddProviderAdjustment] + WHERE BudgetConfigID = @BudgetConfigID + AND TimeClassID = 2 + AND BudgetPhaseID = 2 + + -- Update the add provider adjustments comment and date + UPDATE adj + SET Comment = CASE WHEN LEN(TRIM(Comment)) = 0 THEN @Message + WHEN RIGHT(TRIM(Comment), 1) != '.' THEN CONCAT(Comment, CONCAT(CONCAT('. ', @Spacing), @Message)) + ELSE CONCAT(Comment, CONCAT(@Spacing, @Message)) + END, + DateCreatedUTC = DATEADD(yy, -100, DateCreatedUTC) -- If we don't do this, adjustments (made on this provider) generated by our split upgrade will be overridden by this + FROM [fp].[StatisticsAdjustment] adj + INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE BudgetConfigID = @BudgetConfigID + AND adj.AdjustmentType = 15 + + IF @IsDebug = 1 + BEGIN + + SELECT 'New Groupings', * FROM #newGroupings + SELECT 'New Imports', * FROM #newImportAdjustments + SELECT 'New Adjustments', * FROM #adjustmentsToCopy + SELECT 'New Add Provider', * FROM #newAddProviderAdjustments + + END ELSE + BEGIN + + INSERT INTO [fp].[AdjustmentGrouping] ([GroupingGUID], [Description], [ExcelFile], [IsRecordDeleted]) + SELECT [NewGroupingGUID], [Description], [ExcelFile], [IsRecordDeleted] + FROM #newGroupings + + INSERT INTO [fp].[StatisticsAdjustment] ([AdjustmentGUID], [BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON], + [GroupingHierarchyJSON], [AdjustedProperty], [Comment], [AuthorGUID], [AuthorFullName], [GroupingGUID], [ParentFilterJSON], + [TimeClassID], [ClassificationGroupID], [ClassificationCategoryID], [IsRecordDeleted], [DateCreatedUtc], [LastModifiedDateUtc], + [DimensionMemberJson], [SubsectionID], [IsErrored], [BudgetPhaseID] ) + SELECT + [AdjustmentGUID], [BudgetConfigGUID], [AdjustmentType], [Value], [AdjustmentFilterJSON], + [GroupingHierarchyJSON], [AdjustedProperty], [Comment], [AuthorGUID], [AuthorFullName], [GroupingGUID], [ParentFilterJSON], + [TimeClassID], [ClassificationGroupID], [ClassificationCategoryID], [IsRecordDeleted], [DateCreatedUtc], [LastModifiedDateUtc], + [DimensionMemberJson], [SubsectionID], [IsErrored], [BudgetPhaseID] + FROM #adjustmentsToCopy + + INSERT INTO [fp].[StatisticsAdjustmentRate] ([AdjustmentGUID], [AdjustmentID], [BudgetConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], + [PayorID], [PatientClassID], [ProviderLineItemID], [ProviderID], [ProviderSpecialtyID], [ProviderTypeID], [SubsectionID], + [TimeClassID], [Value01], [Value02], [Value03], [Value04], [Value05], [Value06], [Value07], [Value08], [Value09], [Value10], + [Value11], [Value12], [BudgetPhaseID]) + SELECT + [AdjustmentGUID], [AdjustmentID], [BudgetConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], + [PayorID], [PatientClassID], [ProviderLineItemID], [ProviderID], [ProviderSpecialtyID], [ProviderTypeID], [SubsectionID], + [TimeClassID], [Value01], [Value02], [Value03], [Value04], [Value05], [Value06], [Value07], [Value08], [Value09], [Value10], + [Value11], [Value12], [BudgetPhaseID] + FROM #adjustmentRateToCopy + + INSERT INTO [fp].[StatisticsAdjustmentImport] ([AdjustmentGUID], [DepartmentID], [EntityID], [AccountID], [FinancialReportingID], + [PayorID], [PatientClassID], [FiscalYearID], [FiscalMonthID], [UnitTypeID], [Value], [TimeClassID], [IsRecordDeleted], + [AdjustmentID], [ProviderID], [ProviderTypeID], [ProviderLineItemID], [ProviderSpecialtyID], [BudgetPhaseID]) + SELECT [AdjustmentGUID], [DepartmentID], [EntityID], [AccountID], [FinancialReportingID], + [PayorID], [PatientClassID], [FiscalYearID], [FiscalMonthID], [UnitTypeID], [Value], [TimeClassID], [IsRecordDeleted], + [AdjustmentID], [ProviderID], [ProviderTypeID], [ProviderLineItemID], [ProviderSpecialtyID], [BudgetPhaseID] + FROM #newImportAdjustments + + INSERT INTO [fp].[StatisticAddProviderAdjustment] ([BudgetConfigID], [AdjustmentGUID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID],[PayorID], + [PatientClassID], [ProviderLineItemID], [ProviderID], [ProviderSpecialtyID], [ProviderTypeID], [TimeClassID], [BudgetPhaseID], [SubsectionID], + [IsRecordDeleted], [Value01], [Value02], [Value03], [Value04], [Value05], [Value06], [Value07], [Value08], [Value09], [Value10], [Value11], [Value12]) + SELECT [BudgetConfigID], [AdjustmentGUID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID],[PayorID], + [PatientClassID], [ProviderLineItemID], [ProviderID], [ProviderSpecialtyID], [ProviderTypeID], [TimeClassID], [BudgetPhaseID], [SubsectionID], + [IsRecordDeleted], [Value01], [Value02], [Value03], [Value04], [Value05], [Value06], [Value07], [Value08], [Value09], [Value10], [Value11], [Value12] + FROM #newAddProviderAdjustments + + END + +END +GO + + +--------------------------------------------- + +-- fp.procBudgetedCostPerRVUSampling +CREATE PROCEDURE [fp].[procBudgetedCostPerRVUSampling] + @CostingConfigGUID UNIQUEIDENTIFIER, + @EntityGroupConfigGUID UNIQUEIDENTIFIER, + @IsDebug BIT = 0 +AS +BEGIN + + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-06-30 MD JAZZ-13102 Use original department when populating variability + ** 2 11-16-2022 MY JAZZ-46033 Add VariableDirectCost to proc when Enable Patient Activity Flexing Advanced Costing Methods is enabled + ** 3 12-15-2022 MY JAZZ-46093 Overwrite variable costing rates for new activity + ** 4 01-25-2022 MY JAZZ-48927 Update sampling so that the target table does not get deleted when detailed costing is run + ** 4 01-25-2022 MY JAZZ-48927 Removed workaround where TimeClass was copied from 1 to the other. The load checks the TimeClass on the CostingConfig now so it's no longer necessary + ** 5 08-14-2024 NT JAZZ-74586 Populate ChargeCodeID in fp.BudgetedCostPerRVU_Sampled when advanced costing method Feature Flag is ON + ** 6 10-24-2024 NT JAZZ-79088 Eliminate references to the dss.ChargeAllocation table when advanced costing method setting is ON + *************************************************************/ + + SET NOCOUNT ON; + + IF OBJECT_ID('tempdb..#costingData') IS NOT NULL DROP TABLE #costingData; + IF OBJECT_ID('tempdb..#rowsToDelete') IS NOT NULL DROP TABLE #rowsToDelete; + IF OBJECT_ID('tempdb..#costingResult') IS NOT NULL DROP TABLE #costingResult; + IF OBJECT_ID('tempdb..#entities') IS NOT NULL DROP TABLE #entities; + + CREATE TABLE #costingData ( + [DepartmentID] INT NOT NULL DEFAULT(0), + [AccountID] INT NOT NULL DEFAULT(0), + [JobCodeID] INT NOT NULL DEFAULT(0), + [PayCodeGroupID] INT NOT NULL DEFAULT(0), + [FiscalYearID] INT NOT NULL DEFAULT(0), + [CostComponentID] INT NOT NULL DEFAULT(0), + [ChargeCodeID] INT NOT NULL DEFAULT(0), + [BudgetConfigID] INT NOT NULL DEFAULT(0), + [UnitTypeID] INT NOT NULL DEFAULT(0), + [VariableDirectUnitCostPerRVU] DECIMAL(38, 6) NOT NULL DEFAULT(0), + [TotalVariableDirectCost] DECIMAL(38,8) NOT NULL DEFAULT(0), + [TotalCost] DECIMAL(38,6) NOT NULL DEFAULT(0), + [PayCodeID] INT NOT NULL DEFAULT(0), + [TimeClassID] INT NOT NULL DEFAULT(0), + [VariableDirectCost] DECIMAL(38,6) NOT NULL DEFAULT(0) + ); + + CREATE TABLE #rowsToDelete ( + [RowID] INT NOT NULL DEFAULT(0) + ); + + DECLARE @IsAdvancedMethodologiesUsed BIT = ISNULL((SELECT Value FROM fp.SystemSetting WHERE Name = 'Enable Patient Activity Flexing Advanced Costing Methods'), 0) + DECLARE @BudgetConfigID INT = (SELECT DISTINCT bc.BudgetConfigID + FROM [fp].[BudgetConfig] bc + INNER JOIN [fp].[EntityGroupConfig] ec ON ec.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE ec.CostingConfigGUID = @CostingConfigGUID + AND ec.EntityGroupConfigGUID = @EntityGroupConfigGUID); + + SELECT DISTINCT(costRes.CostingResultID) + INTO #costingResult + FROM ( + SELECT FiscalYearID, max(CostingResultID) as CostingResultID + FROM [dss].[CostingResult] cr2 + INNER JOIN [dss].[CostingConfig] cfg on cfg.CostingConfigGuid = cr2.CostingConfigGuid + WHERE cr2.IsActivityBasedDetail = 1 + AND cr2.IsMarkedForDeletion = 0 + AND cr2.IsFailure = 0 + AND cr2.CostingConfigGuid = @CostingConfigGUID + GROUP BY FiscalYearID + ) costRes + + SELECT DISTINCT EntityID + INTO #entities + FROM fp.EntityGroupConfigMapping + WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID + + IF (@IsAdvancedMethodologiesUsed = 1) + BEGIN + -------------------------------------------------------------------------------------- + -- Advanced Costing Methods - Enabled + -------------------------------------------------------------------------------------- + + -- sample from dss.FactCostingOutDetailGL + INSERT INTO #costingData ([DepartmentID], [AccountID], [JobCodeID], [PayCodeID], [PayCodeGroupID], [FiscalYearID], [CostComponentID], [ChargeCodeID], [BudgetConfigID], [UnitTypeID], + [TimeClassID], [VariableDirectUnitCostPerRVU], [TotalVariableDirectCost], [TotalCost], [VariableDirectCost]) + SELECT + gl.OriginalDepartmentID AS DepartmentID --this uses the original department (not reclassed) to sample into the fp tables + , OriginalAccountID AS AccountID + , 0 AS [JobCodeID] + , 0 AS [PayCodeID] + , 0 AS [PayCodeGroupID] + , gl.FiscalYearID + , gl.CostComponentID + , gl.ChargeCodeID + , bc.BudgetConfigID + , 34 AS [UnitTypeID] + , gl.TimeClassID + , 0 AS VariableDirectUnitCostPerRVU -- This isn't required as we aren't using RVUs for Advanced Costing + , 0 AS TotalVariableDirectCost -- This is never used and not sure why we still have it, but leaving for now + , SUM(gl.TotalCost) AS TotalCost + , SUM(gl.VariableDirectUnitCost) AS VariableDirectCost + FROM [dss].[FactCostingOutDetailGL] gl + INNER JOIN [dss].[CostingResult] cr ON gl.CostingResultID = cr.CostingResultID + INNER JOIN [fp].[EntityGroupConfig] ec ON cr.CostingConfigGuid = ec.CostingConfigGUID + AND ec.EntityGroupConfigGUID = @EntityGroupConfigGUID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON ec.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID + INNER JOIN [fw].[DimDepartment] dept ON egcm.EntityID = dept.EntityID + AND gl.OriginalDepartmentID = dept.DepartmentID + INNER JOIN [fp].[BudgetConfig] bc ON ec.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE gl.CostingResultID IN (SELECT DISTINCT CostingResultID FROM #costingResult) + GROUP BY + gl.OriginalAccountID + , gl.OriginalDepartmentID --group by same original department instead of reclassed + , bc.BudgetConfigID + , gl.FiscalYearID + , gl.TimeClassID + , gl.CostComponentID + , gl.ChargeCodeID; + + -- sample from dss.FactCostingOutDetailPayroll + INSERT INTO #costingData ([DepartmentID], [AccountID], [JobCodeID], [PayCodeID], [PayCodeGroupID], [FiscalYearID], [CostComponentID], [ChargeCodeID], [BudgetConfigID], + [UnitTypeID], [TimeClassID], [VariableDirectUnitCostPerRVU], [TotalVariableDirectCost], [TotalCost], [VariableDirectCost]) + SELECT + pay.OriginalDepartmentID AS DepartmentID --this uses the original department (not reclassed) to sample into the fp tables + , ISNULL(cw.AccountID, 0) AS AccountID + , OriginalJobCodeID AS JobCodeID + , OriginalPayCodeID AS PayCodeID + , pc.PayCodeGroupID + , pay.FiscalYearID + , pay.CostComponentID + , pay.ChargeCodeID + , bc.BudgetConfigID + , pay.UnitTypeID + , pay.TimeClassID + , 0 AS VariableDirectUnitCostPerRVU -- This isn't required as we aren't using RVUs for Advanced Costing + , 0 AS TotalVariableDirectCost -- This is never used and not sure why we still have it, but leaving for now + , SUM(pay.TotalCost) AS TotalCost + , SUM(pay.VariableDirectUnitCost) AS VariableDirectCost + FROM [dss].[FactCostingOutDetailPayroll] pay + INNER JOIN [dss].[CostingResult] cr ON pay.CostingResultID = cr.CostingResultID + INNER JOIN [fp].[EntityGroupConfig] ec ON cr.CostingConfigGuid = ec.CostingConfigGUID + AND ec.EntityGroupConfigGUID = @EntityGroupConfigGUID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON ec.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID + INNER JOIN [fw].[DimDepartment] dept ON egcm.EntityID = dept.EntityID + AND pay.OriginalDepartmentID = dept.DepartmentID -- make sure that we join the original department to the fw.DimDepartment table + INNER JOIN [fp].[BudgetConfig] bc ON ec.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = pay.OriginalPayCodeID + LEFT JOIN [clientob].[FactPayrollToAccountCrosswalk] cw ON pay.OriginalJobCodeID = cw.JobCodeID + AND pc.PayCodeGroupID = cw.PayCodeGroupID + AND cw.UnitTypeID = 34 + WHERE pay.CostingResultID IN (SELECT DISTINCT CostingResultID FROM #costingResult) + GROUP BY + cw.AccountID + , pay.OriginalJobCodeID + , pay.OriginalPayCodeID + , pc.PayCodeGroupID + , pay.OriginalDepartmentID --group by same original department instead of reclassed + , bc.BudgetConfigID + , pay.UnitTypeID + , pay.TimeClassiD + , pay.FiscalYearID + , pay.CostComponentID + , pay.ChargeCodeID; + + -- In the event new costing data is added that matches something in the import, we need to clear out the imported record + -- as costing record wins + INSERT INTO #rowsToDelete (RowID) + SELECT cpr.RowID + FROM #costingData cost + INNER JOIN [fp].[BudgetedCostPerRVU_Sampled] cpr ON + cost.[DepartmentID] = cpr.[DepartmentID] + AND cost.[AccountID] = cpr.[AccountID] + AND cost.[CostComponentID] = cpr.[CostComponentID] + AND cost.[ChargeCodeID] = cpr.[ChargeCodeID] + AND cost.[BudgetConfigID] = cpr.[BudgetConfigID] + INNER JOIN fw.DimDepartment dept ON cpr.DepartmentID = dept.DepartmentID + INNER JOIN #entities ent ON dept.EntityID = ent.EntityID + WHERE cpr.BudgetConfigID = @BudgetConfigID + AND cpr.IsImportedFromFile = 1 + + + -- In the event new costing data is added that matches something in the import, we need to clear out the imported record + -- as costing record wins + INSERT INTO #rowsToDelete (RowID) + SELECT cpr.RowID + FROM #costingData cost + INNER JOIN [fp].[BudgetedCostPerRVU_Sampled] cpr ON + cost.[DepartmentID] = cpr.[DepartmentID] + AND cost.[JobCodeID] = cpr.[JobCodeID] + AND cost.[PayCodeGroupID] = cpr.[PayCodeGroupID] + AND cost.[CostComponentID] = cpr.[CostComponentID] + AND cost.[ChargeCodeID] = cpr.[ChargeCodeID] + AND cost.[BudgetConfigID] = cpr.[BudgetConfigID] + INNER JOIN fw.DimDepartment dept ON cpr.DepartmentID = dept.DepartmentID + INNER JOIN #entities ent ON dept.EntityID = ent.EntityID + WHERE cpr.BudgetConfigID = @BudgetConfigID + AND cpr.IsImportedFromFile = 1 + + END ELSE BEGIN + -------------------------------------------------------------------------------------- + -- Advanced Costing Methods - Disabled + -------------------------------------------------------------------------------------- + + -- sample from dss.FactCostingOutDetailGL + INSERT INTO #costingData ([DepartmentID], [AccountID], [JobCodeID], [PayCodeID], [PayCodeGroupID], [FiscalYearID], [CostComponentID], [BudgetConfigID], [UnitTypeID], + [TimeClassID], [VariableDirectUnitCostPerRVU], [TotalVariableDirectCost], [TotalCost], [VariableDirectCost]) + SELECT + gl.OriginalDepartmentID AS DepartmentID --this uses the original department (not reclassed) to sample into the fp tables + , OriginalAccountID AS AccountID + , 0 AS [JobCodeID] + , 0 AS [PayCodeID] + , 0 AS [PayCodeGroupID] + , gl.FiscalYearID + , gl.CostComponentID + , bc.BudgetConfigID + , 34 AS [UnitTypeID] + , gl.TimeClassID + , ISNULL(SUM(gl.VariableDirectUnitCost) / NULLIF(SUM(ca.RVU), 0), 0) AS VariableDirectUnitCostPerRVU + , SUM(gl.VariableDirectUnitCost * gl.Volume) AS TotalVariableDirectCost + , SUM(gl.TotalCost) AS TotalCost + , 0 AS VariableDirectCost + FROM [dss].[FactCostingOutDetailGL] gl + INNER JOIN [dss].[CostingResult] cr ON gl.CostingResultID = cr.CostingResultID + INNER JOIN [fp].[EntityGroupConfig] ec ON cr.CostingConfigGuid = ec.CostingConfigGUID + AND ec.EntityGroupConfigGUID = @EntityGroupConfigGUID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON ec.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID + INNER JOIN [fw].[DimDepartment] dept ON egcm.EntityID = dept.EntityID + AND gl.OriginalDepartmentID = dept.DepartmentID + INNER JOIN [fp].[BudgetConfig] bc ON ec.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN [dss].[ChargeAllocation] ca ON ca.CostingConfigGuid = cr.CostingConfigGUID + AND ca.ChargeCodeID = gl.ChargeCodeID + AND ca.DepartmentID = gl.OriginalDepartmentID -- this joins the reclassed department to the ChargeAllocation table + AND ca.CostComponentID = gl.CostComponentID + AND AllocationType = 1 + AND ca.IsFixed = 0 + AND ca.IsIndirect = 0 + AND ca.RVU <> 0 + WHERE gl.CostingResultID IN (SELECT DISTINCT CostingResultID FROM #costingResult) + GROUP BY + gl.OriginalAccountID + , gl.OriginalDepartmentID --group by same original department instead of reclassed + , bc.BudgetConfigID + , gl.FiscalYearID + , gl.TimeClassID + , gl.CostComponentID; + + -- sample from dss.FactCostingOutDetailPayroll + INSERT INTO #costingData ([DepartmentID], [AccountID], [JobCodeID], [PayCodeID], [PayCodeGroupID], [FiscalYearID], [CostComponentID], [BudgetConfigID], + [UnitTypeID], [TimeClassID], [VariableDirectUnitCostPerRVU], [TotalVariableDirectCost], [TotalCost], [VariableDirectCost]) + SELECT + pay.OriginalDepartmentID AS DepartmentID --this uses the original department (not reclassed) to sample into the fp tables + , ISNULL(cw.AccountID, 0) AS AccountID + , OriginalJobCodeID AS JobCodeID + , OriginalPayCodeID AS PayCodeID + , pc.PayCodeGroupID + , pay.FiscalYearID + , pay.CostComponentID + , bc.BudgetConfigID + , pay.UnitTypeID + , pay.TimeClassID + , ISNULL(SUM(pay.VariableDirectUnitCost) / NULLIF(SUM(ca.RVU), 0), 0) AS VariableDirectUnitCostPerRVU + , SUM(pay.VariableDirectUnitCost * pay.Volume) AS TotalVariableDirectCost + , SUM(pay.TotalCost) AS TotalCost + , 0 AS VariableDirectCost + FROM [dss].[FactCostingOutDetailPayroll] pay + INNER JOIN [dss].[CostingResult] cr ON pay.CostingResultID = cr.CostingResultID + INNER JOIN [fp].[EntityGroupConfig] ec ON cr.CostingConfigGuid = ec.CostingConfigGUID + AND ec.EntityGroupConfigGUID = @EntityGroupConfigGUID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON ec.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID + INNER JOIN [fw].[DimDepartment] dept ON egcm.EntityID = dept.EntityID + AND pay.OriginalDepartmentID = dept.DepartmentID -- make sure that we join the original department to the fw.DimDepartment table + INNER JOIN [fp].[BudgetConfig] bc ON ec.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN [dss].[ChargeAllocation] ca ON ca.CostingConfigGuid = cr.CostingConfigGUID + AND ca.ChargeCodeID = pay.ChargeCodeID + AND ca.DepartmentID = pay.OriginalDepartmentID -- this joins the reclassed department to the ChargeAllocation table + AND ca.CostComponentID = pay.CostComponentID + AND AllocationType = 1 + AND ca.IsFixed = 0 + AND ca.IsIndirect = 0 + AND ca.RVU <> 0 + INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = pay.OriginalPayCodeID + LEFT JOIN [clientob].[FactPayrollToAccountCrosswalk] cw ON pay.OriginalJobCodeID = cw.JobCodeID + AND pc.PayCodeGroupID = cw.PayCodeGroupID + AND cw.UnitTypeID = 34 + WHERE pay.CostingResultID IN (SELECT DISTINCT CostingResultID FROM #costingResult) + GROUP BY + cw.AccountID + , pay.OriginalJobCodeID + , pay.OriginalPayCodeID + , pc.PayCodeGroupID + , pay.OriginalDepartmentID --group by same original department instead of reclassed + , bc.BudgetConfigID + , pay.UnitTypeID + , pay.TimeClassiD + , pay.FiscalYearID + , pay.CostComponentID; + + END + + IF (@IsDebug = 1) + BEGIN + + SELECT 'IsAdvancedMethodologiesUsed', @IsAdvancedMethodologiesUsed + SELECT 'IsAdvancedMethodologiesUsed', EntityID FROM #entities + SELECT '#costingResult', CostingResultID FROM #costingResult + SELECT '#costingData', [DepartmentID], [AccountID], [JobCodeID], [PayCodeGroupID], [FiscalYearID], [CostComponentID], [ChargeCodeID], [BudgetConfigID], [UnitTypeID], [VariableDirectUnitCostPerRVU], + [TotalVariableDirectCost], [TotalCost], [PayCodeID], [TimeClassID], [VariableDirectCost] + FROM #costingData + SELECT '#rowsToDelete', RowID FROM #rowsToDelete + + END ELSE BEGIN + + -- Clear out the records for [fp].[BudgetedCostPerRVU_Sampled] that were not imported in + DELETE sampl + FROM [fp].[BudgetedCostPerRVU_Sampled] sampl + INNER JOIN fw.DimDepartment dept ON sampl.DepartmentID = dept.DepartmentID + INNER JOIN #entities ent ON dept.EntityID = ent.EntityID + WHERE sampl.BudgetConfigID = @BudgetConfigID + AND IsImportedFromFile = 0; + + IF (@IsAdvancedMethodologiesUsed = 1) + BEGIN + -- Clear out rows in the import that have the same dimensionality + DELETE sampl + FROM [fp].[BudgetedCostPerRVU_Sampled] sampl + INNER JOIN #rowsToDelete del ON del.RowID = sampl.RowID + INNER JOIN fw.DimDepartment dept ON sampl.DepartmentID = dept.DepartmentID + INNER JOIN #entities ent ON dept.EntityID = ent.EntityID + WHERE sampl.BudgetConfigID = @BudgetConfigID + AND IsImportedFromFile = 1; + END + + -- Populate costing data + INSERT INTO [fp].[BudgetedCostPerRVU_Sampled] ([DepartmentID], [AccountID], [JobCodeID], [PayCodeGroupID], [FiscalYearID], [CostComponentID], [ChargeCodeID], [BudgetConfigID], [UnitTypeID], [VariableDirectUnitCostPerRVU], + [TotalVariableDirectCost], [TotalCost], [PayCodeID], [TimeClassID], [VariableDirectCost]) + SELECT [DepartmentID], [AccountID], [JobCodeID], [PayCodeGroupID], [FiscalYearID], [CostComponentID], [ChargeCodeID], [BudgetConfigID], [UnitTypeID], [VariableDirectUnitCostPerRVU], + [TotalVariableDirectCost], [TotalCost], [PayCodeID], [TimeClassID], [VariableDirectCost] + FROM #costingData + + END +END +GO + + +--------------------------------------------- + +-- fp.procCacheGeneralLedgerFlexingType +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2021-02-25 MY JAZZ-17526 Corrected targeting for the update +** 2 2021-09-16 NT JAZZ-25494 Replace funcGetGLVariableDataForServiceLineVolumeFlexing by procGetGLVariableDataForServiceLineVolumeFlexing +** 3 8-30-2023 NT JAZZ-59319 Data Restructure changea +** 4 9-5-2023 NT JAZZ-60140 Remove RowID from #patientActivityDimensionality +** 5 9-7-2023 NT JAZZ-59598 Add PercentAdjustmentFactor to #patientActivityDimensionality to support change for PAF +***************************************************************/ +CREATE PROCEDURE [fp].[procCacheGeneralLedgerFlexingType] + @EntityGroupConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 + AS +BEGIN + + DECLARE @EntityGroupConfigGUID UNIQUEIDENTIFIER = (SELECT EntityGroupConfigGUID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID) + DECLARE @FiscalYearID SMALLINT = (SELECT FiscalYearID FROM [fp].[BudgetConfig] bc + INNER JOIN [fp].[EntityGroupConfig] egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID + WHERE EntityGroupConfigID = @EntityGroupConfigID) + + CREATE TABLE #filterTable (GeneralLedgerID INT); + CREATE TABLE #patientActivityFlexing (GeneralLedgerID INT, FlexingTypeID INT); + CREATE TABLE #otherFlexing (GeneralLedgerID INT, FlexingTypeID INT); + + -- Build the department filter + SELECT DISTINCT DepartmentID + INTO #SourceDimensionality + FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- Gather filter table + IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL) + BEGIN + + INSERT INTO #filterTable (GeneralLedgerID) + SELECT DISTINCT basis.GeneralLedgerID + FROM [fp].[GeneralLedger] basis + INNER JOIN #SourceDimensionality SD ON SD.DepartmentID = basis.DepartmentID + WHERE basis.EntityGroupConfigID = @EntityGroupConfigID + + END ELSE BEGIN + + -- If the table source dimensionality is unfiltered, we don't wanna join on the department filter. + INSERT INTO #filterTable (GeneralLedgerID) + SELECT DISTINCT basis.GeneralLedgerID + FROM [fp].[GeneralLedger] basis + WHERE basis.EntityGroupConfigID = @EntityGroupConfigID + + END + + -- Map records based on this page: + -- https://confluence.sdt.local/display/SWPRJ/Common+Calculations%2C+Equations%2C+IDs%2C+and+Look+Up+Values#CommonCalculations,Equations,IDs,andLookUpValues-FlexingType + + -- Note, if the flexing type in the configuration is set to flex, however, the data is not configured to flex, the flexing type ID will default to 0 (fixed) + -- Once the proper data has been added, the flexing type will be cached + + -- Get the dimensionality based on what's being flexed by PAF. The function filters it to variable and dollars when we need everything. + IF ((SELECT IsPatientActivityFlexingForNonStaffing FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID) = 1) + BEGIN + + EXEC[dbo].[procSysDropTempTable] '#patientActivityDimensionality' + CREATE TABLE #patientActivityDimensionality ( + BasisID INT, + BudgetPhaseID TINYINT, + TimeClassID TINYINT, + DepartmentID INT, + AccountID INT, + FiscalYearID SMALLINT, + FiscalMonthID TINYINT, + OriginalValue DECIMAL(19,8), + PercentAdjustmentFactor DECIMAL(19,8)) + + INSERT INTO #patientActivityDimensionality + EXEC fp.procGetGLVariableDataForServiceLineVolumeFlexing @EntityGroupConfigGUID, @EntityGroupConfigID, @FiscalYearID, @SourceDimensionality + + INSERT INTO #patientActivityFlexing (GeneralLedgerID, FlexingTypeID) + SELECT DISTINCT fgl.GeneralLedgerID, 7 AS FlexingTypeID + FROM [fp].[GeneralLedger] fgl + INNER JOIN #filterTable filter ON fgl.GeneralLedgerID = filter.GeneralLedgerID + INNER JOIN #patientActivityDimensionality flex ON + fgl.DepartmentID = flex.DepartmentID + AND fgl.AccountID = flex.AccountID + WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID + + END + + INSERT INTO #otherFlexing (GeneralLedgerID, FlexingTypeID) + SELECT DISTINCT gl.GeneralLedgerID, flex.FlexingTypeID + FROM [fp].[FlexConfigMapping] flex + INNER JOIN [fp].[GeneralLedger] gl ON flex.DepartmentID = gl.DepartmentID AND flex.GLAccountID = gl.AccountID AND flex.EntityGroupConfigID = gl.EntityGroupConfigID + INNER JOIN #filterTable filter ON gl.GeneralLedgerID = filter.GeneralLedgerID + WHERE flex.EntityGroupConfigID = @EntityGroupConfigID + + IF (@IsDebug = 1) + BEGIN + + SELECT '#filterTable', * FROM #filterTable + + IF OBJECT_ID('tempdb..#patientActivityDimensionality') IS NOT NULL + SELECT '#patientActivityDimensionality', * FROM #patientActivityDimensionality + + SELECT '#patientActivityFlexing', * FROM #patientActivityFlexing + SELECT '#otherFlexing', * FROM #otherFlexing + + END ELSE BEGIN + + UPDATE gl + SET gl.FlexingTypeID = COALESCE(paf.FlexingTypeID, flex.FlexingTypeID, 0) + FROM [fp].[GeneralLedger] gl + INNER JOIN #filterTable filter ON gl.GeneralLedgerID = filter.GeneralLedgerID + LEFT JOIN #patientActivityFlexing paf ON paf.GeneralLedgerID = gl.GeneralLedgerID + LEFT JOIN #otherFlexing flex ON flex.GeneralLedgerID = gl.GeneralLedgerID + WHERE gl.FlexingTypeID != COALESCE(paf.FlexingTypeID, flex.FlexingTypeID, 0) + AND gl.EntityGroupConfigID = @EntityGroupConfigID + + END + +END; +GO + + +--------------------------------------------- + +-- fp.procCacheStaffingFlexingType +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2021-02-25 MY JAZZ-17526 Corrected targeting for the update +** 2 2021-05-24 BK JAZZ-3089 Make paf sql more efficient and add drop temp table statements +** 3 2021-07-01 MY FAIL-TEST Corrected targeting case when there is no targeting filter for PAF +** 4 2023-11-07 MD JAZZ-62448 Update for staffing restructure +***************************************************************/ +CREATE PROCEDURE [fp].[procCacheStaffingFlexingType] + @EntityGroupConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 + AS +BEGIN + + IF OBJECT_ID('tempdb..#filterTable') IS NOT NULL DROP TABLE #filterTable + IF OBJECT_ID('tempdb..#SourceDimensionality') IS NOT NULL DROP TABLE #SourceDimensionality + IF OBJECT_ID('tempdb..#patientActivityFlexing') IS NOT NULL DROP TABLE #patientActivityFlexing + IF OBJECT_ID('tempdb..#patientActivityDimensionality') IS NOT NULL DROP TABLE #patientActivityDimensionality + IF OBJECT_ID('tempdb..#otherFlexing') IS NOT NULL DROP TABLE #otherFlexing + + DECLARE @EntityGroupConfigGUID UNIQUEIDENTIFIER = (SELECT EntityGroupConfigGUID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID) + DECLARE @FiscalYearID SMALLINT = (SELECT FiscalYearID FROM [fp].[BudgetConfig] bc + INNER JOIN [fp].[EntityGroupConfig] egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID + WHERE EntityGroupConfigID = @EntityGroupConfigID) + + CREATE TABLE #filterTable (StaffingID INT); + CREATE TABLE #patientActivityFlexing (StaffingID INT, FlexingTYpeID INT); + CREATE TABLE #otherFlexing (StaffingID INT, FlexingTYpeID INT); + + + DECLARE @StaffingSubsectionID INT = 3 + DECLARE @ProviderSubsectionID INT = 4 + + -- Build the department filter + SELECT DISTINCT DepartmentID + INTO #SourceDimensionality + FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- Gather filter table + IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL) + BEGIN + + INSERT INTO #filterTable (StaffingID) + SELECT DISTINCT basis.StaffingID + FROM [fp].[Staffing] basis + INNER JOIN #SourceDimensionality SD ON SD.DepartmentID = basis.DepartmentID + WHERE basis.EntityGroupConfigID = @EntityGroupConfigID + + END ELSE BEGIN + + -- If the table source dimensionality is unfiltered, we don't wanna join on the department filter. + INSERT INTO #filterTable (StaffingID) + SELECT DISTINCT basis.StaffingID + FROM [fp].[Staffing] basis + WHERE basis.EntityGroupConfigID = @EntityGroupConfigID + + END + + -- Map records based on this page: + -- https://confluence.sdt.local/display/SWPRJ/Common+Calculations%2C+Equations%2C+IDs%2C+and+Look+Up+Values#CommonCalculations,Equations,IDs,andLookUpValues-FlexingType + + -- Note, if the flexing type in the configuration is set to flex, however, the data is not configured to flex, the flexing type ID will default to 0 (fixed) + -- Once the proper data has been added, the flexing type will be cached + + -- Get the dimensionality based on what's being flexed by PAF. The function filters it to variable and dollars when we need everything. + + IF ((SELECT IsPatientActivityFlexingForStaffing FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID) = 1) + BEGIN + + SELECT DISTINCT fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID + INTO #patientActivityDimensionality + FROM [fp].[Staffing] fs + INNER JOIN #filterTable filter ON fs.StaffingID = filter.StaffingID + LEFT JOIN [fp].[FlexConfigMapping] map + ON fs.DepartmentID = map.DepartmentID + AND fs.JobCodeID = map.PRJobCodeID + AND fs.EntityGroupConfigID = map.EntityGroupConfigID + LEFT JOIN [fp].[viewStaffingExpenseFlexingConfig] fc + ON fs.DepartmentID = fc.DepartmentID + AND fs.JobCodeID = fc.JobCodeID + AND fc.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.VariabilityID = 2 + AND map.FlexingTypeID IS NULL + AND (fc.FlexMethodID != 6 OR fc.FlexMethodID IS NULL) + + INSERT INTO #patientActivityFlexing (StaffingID, FlexingTypeID) + SELECT DISTINCT fs.StaffingID, 7 AS FlexingTypeID + FROM [fp].[Staffing] fs + INNER JOIN #filterTable filter ON fs.StaffingID = filter.StaffingID + INNER JOIN #patientActivityDimensionality flex ON + fs.DepartmentID = flex.DepartmentID + AND fs.JobCodeID = flex.JobCodeID + AND fs.PayCodeGroupID = flex.PayCodeGroupID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + + END + + -- Staffing + INSERT INTO #otherFlexing (StaffingID, FlexingTypeID) + SELECT DISTINCT staff.StaffingID, flex.FlexingTypeID + FROM [fp].[FlexConfigMapping] flex + INNER JOIN [fp].[Staffing] staff ON flex.DepartmentID = staff.DepartmentID AND flex.PRJobCodeID = staff.JobCodeID AND flex.EntityGroupConfigID = staff.EntityGroupConfigID + INNER JOIN #filterTable filter ON staff.StaffingID = filter.StaffingID + WHERE flex.EntityGroupConfigID = @EntityGroupConfigID and staff.SubsectionID = @StaffingSubsectionID + + -- Provider + INSERT INTO #otherFlexing (StaffingID, FlexingTypeID) + SELECT DISTINCT staff.StaffingID, flex.FlexingTypeID + FROM [fp].[FlexConfigMapping] flex + INNER JOIN [fp].[Staffing] staff ON flex.DepartmentID = staff.DepartmentID AND flex.PRJobCodeID = staff.JobCodeID + AND flex.ProviderLineItemID = staff.ProviderLineItemID AND flex.EntityGroupConfigID = staff.EntityGroupConfigID + INNER JOIN #filterTable filter ON staff.StaffingID = filter.StaffingID + WHERE flex.EntityGroupConfigID = @EntityGroupConfigID and staff.SubsectionID = @ProviderSubsectionID + + + IF (@IsDebug = 1) + BEGIN + + SELECT '#filterTable', * FROM #filterTable + + IF OBJECT_ID('tempdb..#patientActivityDimensionality') IS NOT NULL + SELECT '#patientActivityDimensionality', * FROM #patientActivityDimensionality + + SELECT '#patientActivityFlexing', * FROM #patientActivityFlexing + SELECT '#otherFlexing', * FROM #otherFlexing + + END ELSE BEGIN + + UPDATE staff + SET staff.FlexingTypeID = COALESCE(paf.FlexingTypeID, flex.FlexingTypeID, 0) + FROM [fp].[Staffing] staff + INNER JOIN #filterTable filter ON staff.StaffingID = filter.StaffingID + LEFT JOIN #patientActivityFlexing paf ON paf.StaffingID = staff.StaffingID + LEFT JOIN #otherFlexing flex ON flex.StaffingID = staff.StaffingID + WHERE staff.FlexingTypeID != COALESCE(paf.FlexingTypeID, flex.FlexingTypeID, 0) + AND staff.EntityGroupConfigID = @EntityGroupConfigID + + END +END; +GO + + +--------------------------------------------- + +-- fp.procCalculatePayrollDollarsByWageRate +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2019-03-08 IP B-22295 Removed using table variables, small optimizations +*************************************************************/ +CREATE PROCEDURE [fp].[procCalculatePayrollDollarsByWageRate] + @EntityGroupConfigID INT, + @TimeClassID INT +AS + +DECLARE @BudgetConfigID INT +SET @BudgetConfigID = ( + SELECT bc.BudgetConfigID + FROM [fp].[BudgetConfig] bc + INNER JOIN [fp].[EntityGroupConfig] egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID + WHERE egc.EntityGroupConfigID = @EntityGroupConfigID) + + +CREATE TABLE #EntityIDs(ID INT) +INSERT INTO #EntityIDs + SELECT DISTINCT map.EntityID + FROM [fp].[EntityGroupConfig] egc + INNER JOIN [fp].[EntityGroupConfigMapping] map on egc.EntityGroupConfigGUID = map.EntityGroupConfigGUID + WHERE egc.EntityGroupConfigID = @EntityGroupConfigID + +-- Budgeted + + SELECT + DepartmentID, + JobCodeID, + PayCodeGroupID, + BudgetConfigID, + ProductiveClassID, + VariabilityID, + EntityID, + TimeClassID, + FiscalYearID, + FiscalMonthID, + Value, + ManagerValue, + OriginalValue + INTO #hrs + FROM [fp].[FactPayrollBasisResult] basis + INNER JOIN #EntityIDs e on e.EntityID = basis.EntityID + WHERE + BudgetConfigID = @BudgetConfigID + AND UnitTypeID = 51 + AND TimeClassID = @TimeClassID + + ( + SELECT + DepartmentID, + JobCodeID, + PayCodeGroupID, + BudgetConfigID, + ProductiveClassID, + VariabilityID, + EntityID, + TimeClassID, + FiscalYearID, + FiscalMonthID, + Value, + ManagerValue, + OriginalValue + INTO #wg + FROM [fp].[FactPayrollBasisResult] basis + INNER JOIN #EntityIDs e on e.EntityID = basis.EntityID + WHERE + BudgetConfigID = @BudgetConfigID + AND UnitTypeID = 159 + AND TimeClassID = @TimeClassID + ) + +UPDATE basis +SET + basis.Value = wg.Value * hrs.Value, + basis.ManagerValue = wg.ManagerValue * hrs.ManagerValue, + basis.OriginalValue = wg.OriginalValue * hrs.OriginalValue +FROM [fp].[FactPayrollBasisResult] basis +INNER JOIN #EntityIDs e on e.EntityID = basis.EntityID +INNER JOIN #hrs + ON hrs.DepartmentID = basis.DepartmentID + AND hrs.JobCodeID = basis.JobCodeID + AND hrs.PayCodeGroupID = basis.PayCodeGroupID + AND hrs.BudgetConfigID = basis.BudgetConfigID + AND hrs.ProductiveClassID = basis.ProductiveClassID + AND hrs.VariabilityID = basis.VariabilityID + AND hrs.EntityID = basis.EntityID + AND hrs.TimeClassID = basis.TimeClassID + AND hrs.FiscalYearID = basis.FiscalYearID + AND hrs.FiscalMonthID = basis.FiscalMonthID + INNER JOIN #wg wg + ON wg.DepartmentID = basis.DepartmentID + AND wg.JobCodeID = basis.JobCodeID + AND wg.PayCodeGroupID = basis.PayCodeGroupID + AND wg.BudgetConfigID = basis.BudgetConfigID + AND wg.ProductiveClassID = basis.ProductiveClassID + AND wg.VariabilityID = basis.VariabilityID + AND wg.EntityID = basis.EntityID + AND wg.TimeClassID = basis.TimeClassID + AND wg.FiscalYearID = basis.FiscalYearID + AND wg.FiscalMonthID = basis.FiscalMonthID +WHERE + basis.UnitTypeID = 34 + AND basis.BudgetConfigID = @BudgetConfigID + AND basis.TimeClassID = @TimeClassID +GO + + +--------------------------------------------- + +-- fp.procCascadeChargeMasterPrices +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2021-04-15 LR JAZZ-18924 Adding rolling updates to avoid filling up the logs +** 2 2022-05-23 MY JAZZ-37263 Performance Improvements +** 3 2023-03-06 MY JAZZ-48307 Update charges adjustment to support data model changes +*************************************************************/ +CREATE PROCEDURE [fp].[procCascadeChargeMasterPrices] + @BudgetConfigID INT, + @IsEntityUsed BIT, + @IsPatientClassUsed BIT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + IF OBJECT_ID('tempdb..#recordsToProcess') IS NOT NULL DROP TABLE #recordsToProcess; + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment; + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED) + WHERE BudgetConfigID = @BudgetConfigID + END + + DECLARE @ChargeRateMonth01 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(1, @BudgetConfigID)), + @ChargeRateMonth02 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(2, @BudgetConfigID)), + @ChargeRateMonth03 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(3, @BudgetConfigID)), + @ChargeRateMonth04 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(4, @BudgetConfigID)), + @ChargeRateMonth05 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(5, @BudgetConfigID)), + @ChargeRateMonth06 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(6, @BudgetConfigID)), + @ChargeRateMonth07 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(7, @BudgetConfigID)), + @ChargeRateMonth08 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(8, @BudgetConfigID)), + @ChargeRateMonth09 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(9, @BudgetConfigID)), + @ChargeRateMonth10 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(10, @BudgetConfigID)), + @ChargeRateMonth11 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(11, @BudgetConfigID)), + @ChargeRateMonth12 NVARCHAR(100) = (SELECT fp.funcGetChargeRate(12, @BudgetConfigID)) + + -- Update Statistics before performing update per DBAs + UPDATE STATISTICS fp.ChargeVolume + UPDATE STATISTICS fp.FactChargeMaster + + DECLARE @ChunkCount INT; + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Update Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 500000 END; + + SELECT fcv.ChargeVolumeID + INTO #recordsToProcess + FROM fp.ChargeVolume fcv + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fcv.DepartmentID + WHERE fcv.BudgetConfigID = @BudgetConfigID + ORDER BY fcv.ChargeVolumeID; + + PRINT 'Processing Budget' + + DECLARE @IsEntityUsedSQL NVARCHAR(MAX), + @IsPatientClassUsedSQL NVARCHAR(MAX); + + SET @IsEntityUsedSQL = CASE WHEN @IsEntityUsed = 1 THEN 'FCM.EntityID = fcv.EntityID' ELSE ' 0 = 0' END; + SET @IsPatientClassUsedSQL = CASE WHEN @IsPatientClassUsed = 1 THEN 'FCM.PatientClassID = fcv.PatientClassID' ELSE ' 0 = 0' END; + + DECLARE @ChunkEndID INT = -1; + DECLARE @LastUpdatedID INT = @ChunkEndID -1; + WHILE @ChunkEndID > @LastUpdatedID + BEGIN + BEGIN TRANSACTION; + + SET @LastUpdatedID = @ChunkEndID; + + SELECT TOP ( @ChunkCount ) @ChunkEndID = ChargeVolumeID + FROM #recordsToProcess + WHERE ChargeVolumeID > @ChunkEndID + ORDER BY ChargeVolumeID; + + EXEC(' + UPDATE fcv + SET + -- Updating the prices for ChargeVolumeDollarsBudget + fcv.TargetPrice01 = ISNULL(FCM.' + @ChargeRateMonth01 + ', 0), + fcv.TargetPrice02 = ISNULL(FCM.' + @ChargeRateMonth02 + ', 0), + fcv.TargetPrice03 = ISNULL(FCM.' + @ChargeRateMonth03 + ', 0), + fcv.TargetPrice04 = ISNULL(FCM.' + @ChargeRateMonth04 + ', 0), + fcv.TargetPrice05 = ISNULL(FCM.' + @ChargeRateMonth05 + ', 0), + fcv.TargetPrice06 = ISNULL(FCM.' + @ChargeRateMonth06 + ', 0), + fcv.TargetPrice07 = ISNULL(FCM.' + @ChargeRateMonth07 + ', 0), + fcv.TargetPrice08 = ISNULL(FCM.' + @ChargeRateMonth08 + ', 0), + fcv.TargetPrice09 = ISNULL(FCM.' + @ChargeRateMonth09 + ', 0), + fcv.TargetPrice10 = ISNULL(FCM.' + @ChargeRateMonth10 + ', 0), + fcv.TargetPrice11 = ISNULL(FCM.' + @ChargeRateMonth11 + ', 0), + fcv.TargetPrice12 = ISNULL(FCM.' + @ChargeRateMonth12 + ', 0), + fcv.BudgetPrice01 = ISNULL(FCM.' + @ChargeRateMonth01 + ', 0), + fcv.BudgetPrice02 = ISNULL(FCM.' + @ChargeRateMonth02 + ', 0), + fcv.BudgetPrice03 = ISNULL(FCM.' + @ChargeRateMonth03 + ', 0), + fcv.BudgetPrice04 = ISNULL(FCM.' + @ChargeRateMonth04 + ', 0), + fcv.BudgetPrice05 = ISNULL(FCM.' + @ChargeRateMonth05 + ', 0), + fcv.BudgetPrice06 = ISNULL(FCM.' + @ChargeRateMonth06 + ', 0), + fcv.BudgetPrice07 = ISNULL(FCM.' + @ChargeRateMonth07 + ', 0), + fcv.BudgetPrice08 = ISNULL(FCM.' + @ChargeRateMonth08 + ', 0), + fcv.BudgetPrice09 = ISNULL(FCM.' + @ChargeRateMonth09 + ', 0), + fcv.BudgetPrice10 = ISNULL(FCM.' + @ChargeRateMonth10 + ', 0), + fcv.BudgetPrice11 = ISNULL(FCM.' + @ChargeRateMonth11 + ', 0), + fcv.BudgetPrice12 = ISNULL(FCM.' + @ChargeRateMonth12 + ', 0) + FROM fp.ChargeVolume fcv + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fcv.DepartmentID + LEFT JOIN [fp].[FactChargeMaster] FCM + ON FCM.BudgetConfigID = fcv.BudgetConfigID + AND FCM.ChargeCodeID = fcv.ChargeCodeID + AND FCM.TimeClassID = 2 + AND ' + @IsEntityUsedSQL + ' + AND ' + @IsPatientClassUsedSQL + ' + WHERE fcv.BudgetConfigID = ' + @BudgetConfigID + ' + AND fcv.ChargeVolumeID > ' + @LastUpdatedID + ' + AND fcv.ChargeVolumeID <= ' + @ChunkEndID + ' + AND ( + fcv.TargetPrice01 != ISNULL(FCM.' + @ChargeRateMonth01 + ', 0) OR + fcv.TargetPrice02 != ISNULL(FCM.' + @ChargeRateMonth02 + ', 0) OR + fcv.TargetPrice03 != ISNULL(FCM.' + @ChargeRateMonth03 + ', 0) OR + fcv.TargetPrice04 != ISNULL(FCM.' + @ChargeRateMonth04 + ', 0) OR + fcv.TargetPrice05 != ISNULL(FCM.' + @ChargeRateMonth05 + ', 0) OR + fcv.TargetPrice06 != ISNULL(FCM.' + @ChargeRateMonth06 + ', 0) OR + fcv.TargetPrice07 != ISNULL(FCM.' + @ChargeRateMonth07 + ', 0) OR + fcv.TargetPrice08 != ISNULL(FCM.' + @ChargeRateMonth08 + ', 0) OR + fcv.TargetPrice09 != ISNULL(FCM.' + @ChargeRateMonth09 + ', 0) OR + fcv.TargetPrice10 != ISNULL(FCM.' + @ChargeRateMonth10 + ', 0) OR + fcv.TargetPrice11 != ISNULL(FCM.' + @ChargeRateMonth11 + ', 0) OR + fcv.TargetPrice12 != ISNULL(FCM.' + @ChargeRateMonth12 + ', 0) OR + fcv.BudgetPrice01 != ISNULL(FCM.' + @ChargeRateMonth01 + ', 0) OR + fcv.BudgetPrice02 != ISNULL(FCM.' + @ChargeRateMonth02 + ', 0) OR + fcv.BudgetPrice03 != ISNULL(FCM.' + @ChargeRateMonth03 + ', 0) OR + fcv.BudgetPrice04 != ISNULL(FCM.' + @ChargeRateMonth04 + ', 0) OR + fcv.BudgetPrice05 != ISNULL(FCM.' + @ChargeRateMonth05 + ', 0) OR + fcv.BudgetPrice06 != ISNULL(FCM.' + @ChargeRateMonth06 + ', 0) OR + fcv.BudgetPrice07 != ISNULL(FCM.' + @ChargeRateMonth07 + ', 0) OR + fcv.BudgetPrice08 != ISNULL(FCM.' + @ChargeRateMonth08 + ', 0) OR + fcv.BudgetPrice09 != ISNULL(FCM.' + @ChargeRateMonth09 + ', 0) OR + fcv.BudgetPrice10 != ISNULL(FCM.' + @ChargeRateMonth10 + ', 0) OR + fcv.BudgetPrice11 != ISNULL(FCM.' + @ChargeRateMonth11 + ', 0) OR + fcv.BudgetPrice12 != ISNULL(FCM.' + @ChargeRateMonth12 + ', 0) + ) + '); + + COMMIT TRANSACTION; + END + + PRINT 'Processing Projection' + + DECLARE @SelectClause NVARCHAR(MAX) = '', + @WhereClause NVARCHAR(MAX) = '', + @MonthsLoaded INT = (SELECT MonthsLoaded FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID); + + -- To whom is reading this, yes I am sure you hate this, and yes I am aware, but I don't know what else to do here really. Especially since we can't really do the same FOR loop like in other procs due to needing the price variable from above. + -- The point of this is to generate the update for the months not loaded only. The months loaded prices are not used and not relevent for projection because we pull dollars from the actuals for projection months loaded, therefore the price from the charge master + -- does not impact the months loaded at all as they came from history. + IF (1 > @MonthsLoaded) + BEGIN + SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice01 = ISNULL(FCM.' + @ChargeRateMonth01 + ', 0), '; + SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice01 != ISNULL(FCM.' + @ChargeRateMonth01 + ', 0) OR '; + END + + IF (2 > @MonthsLoaded) + BEGIN + SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice02 = ISNULL(FCM.' + @ChargeRateMonth02 + ', 0), '; + SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice02 != ISNULL(FCM.' + @ChargeRateMonth02 + ', 0) OR '; + END + + IF (3 > @MonthsLoaded) + BEGIN + SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice03 = ISNULL(FCM.' + @ChargeRateMonth03 + ', 0), '; + SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice03 != ISNULL(FCM.' + @ChargeRateMonth03 + ', 0) OR '; + END + + IF (4 > @MonthsLoaded) + BEGIN + SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice04 = ISNULL(FCM.' + @ChargeRateMonth04 + ', 0), '; + SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice04 != ISNULL(FCM.' + @ChargeRateMonth04 + ', 0) OR '; + END + + IF (5 > @MonthsLoaded) + BEGIN + SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice05 = ISNULL(FCM.' + @ChargeRateMonth05 + ', 0), '; + SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice05 != ISNULL(FCM.' + @ChargeRateMonth05 + ', 0) OR '; + END + + IF (6 > @MonthsLoaded) + BEGIN + SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice06 = ISNULL(FCM.' + @ChargeRateMonth06 + ', 0), '; + SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice06 != ISNULL(FCM.' + @ChargeRateMonth06 + ', 0) OR '; + END + + IF (7 > @MonthsLoaded) + BEGIN + SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice07 = ISNULL(FCM.' + @ChargeRateMonth07 + ', 0), '; + SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice07 != ISNULL(FCM.' + @ChargeRateMonth07 + ', 0) OR '; + END + + IF (8 > @MonthsLoaded) + BEGIN + SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice08 = ISNULL(FCM.' + @ChargeRateMonth08 + ', 0), '; + SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice08 != ISNULL(FCM.' + @ChargeRateMonth08 + ', 0) OR '; + END + + IF (9 > @MonthsLoaded) + BEGIN + SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice09 = ISNULL(FCM.' + @ChargeRateMonth09 + ', 0), '; + SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice09 != ISNULL(FCM.' + @ChargeRateMonth09 + ', 0) OR '; + END + + IF (10 > @MonthsLoaded) + BEGIN + SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice10 = ISNULL(FCM.' + @ChargeRateMonth10 + ', 0), '; + SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice10 != ISNULL(FCM.' + @ChargeRateMonth10 + ', 0) OR '; + END + + IF (11 > @MonthsLoaded) + BEGIN + SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice11 = ISNULL(FCM.' + @ChargeRateMonth11 + ', 0), '; + SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice11 != ISNULL(FCM.' + @ChargeRateMonth11 + ', 0) OR '; + END + + IF (12 > @MonthsLoaded) + BEGIN + SET @SelectClause = @SelectClause + ' fcv.ProjectionPrice12 = ISNULL(FCM.' + @ChargeRateMonth12 + ', 0) '; + SET @WhereClause = @WhereClause + ' fcv.ProjectionPrice12 != ISNULL(FCM.' + @ChargeRateMonth12 + ', 0) '; + END + + SET @ChunkEndID = -1; + SET @LastUpdatedID = @ChunkEndID -1; + WHILE @ChunkEndID > @LastUpdatedID + BEGIN + BEGIN TRANSACTION; + + SET @LastUpdatedID = @ChunkEndID; + + SELECT TOP ( @ChunkCount ) @ChunkEndID = ChargeVolumeID + FROM #recordsToProcess + WHERE ChargeVolumeID > @ChunkEndID + ORDER BY ChargeVolumeID; + + EXEC(' + UPDATE fcv + SET + -- Updating the prices for ChargeVolumeDollarsProjection + ' + @SelectClause + ' + FROM fp.ChargeVolume fcv + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fcv.DepartmentID + LEFT JOIN [fp].[FactChargeMaster] FCM + ON FCM.BudgetConfigID = fcv.BudgetConfigID + AND FCM.ChargeCodeID = fcv.ChargeCodeID + AND FCM.TimeClassID = 12 + AND ' + @IsEntityUsedSQL + ' + AND ' + @IsPatientClassUsedSQL + ' + WHERE fcv.BudgetConfigID = ' + @BudgetConfigID + ' + AND fcv.ChargeVolumeID > ' + @LastUpdatedID + ' + AND fcv.ChargeVolumeID <= ' + @ChunkEndID + ' + AND (' + @WhereClause + ') + '); + + COMMIT TRANSACTION; + END + +END +GO + + +--------------------------------------------- + +-- fp.procChargeBudgetStampOff +CREATE PROCEDURE [fp].[procChargeBudgetStampOff] + @BudgetConfigID INT, + @TargetTimeClassID TINYINT +AS +BEGIN + /******************************************************************************* + ** Change History + ******************************************************************************** + ** CID Date Author WI Description + ** 1 01-31-2023 MY JAZZ-48962 Initial Creation + ** 2 02-21-2023 MY JAZZ-49484 Update logic to roll up data + ** 3 03-28-2023 BK JAZZ-51558 Update to use new table structure + ** 4 01-03-2024 MZ JAZZ-65385 Added Target TimeClass + ** 5 03-18-2024 MZ JAZZ-68428 Deleting by Chunks & removed HistoryItemGUID parameter + *******************************************************************************/ + + -- Note: The original script was done here https://confluence.sdt.local/display/DD/Moving+Data+from+a+Plan+Configuration+to+Int+Tables + + DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID ) + DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID) + + DECLARE @HistoryItemGUID UNIQUEIDENTIFIER + EXEC procLogScript 'StampOff: Transferring Budget Data from 1p', @HistoryItemGUID OUTPUT + PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36)) + PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID) + + -- Clear out existing records for the selected FiscalYear and Budgeted Time Class + DECLARE @ChunkCount INT + + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END + + DECLARE @r INT; + SET @r = 1; + + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) FROM [int].[FactCDM] WHERE FiscalYearID = @FiscalYear and TimeClassID = @TargetTimeClassID + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + + --- Charge Units + INSERT INTO [int].[FactCDM] (DepartmentID, DepartmentCode, ChargeCodeID, ChargeCode, FiscalYearID, FiscalYearCode, + TimeClassID, TimeClassCode, FiscalMonthID, FiscalMonthCode, PatientClassID, PatientClassCode, ServiceLineID, + ServiceLine, AgeCohortID, AgeCohort, MedicalSurgicalID, MedSurg, UnitTypeID, UnitType, Value, IsDeleted, HistoryItemGUID) + SELECT + D.DepartmentID, + D.DepartmentCode, + CC.ChargeCodeID, + CC.ChargeCode, + bc.FiscalYearID, + bc.FiscalYearID AS FiscalYearCode, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + fm.FiscalMonthID, + fm.FiscalMonthCode, + PAT.PatientClassID, + PAT.Code AS [PatientClassCode], + SL.ServiceLineID AS ServiceLineID, + SL.Code AS ServiceLine, + AG.AgeCohortID AS AgeCohortID, + AG.Code AS AgeCohort, + MS.MedicalSurgicalID AS MedicalSurgicalID, + MS.Code AS MedSurg, + UT.UnitTypeID, + UT.Name AS [UnitType], + Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID + FROM ( + -- Original Note: Unpivot for Value IT DID NOT LOOK LIKE THERE WERE MANAGER VALUES FOR THIS AT ALL + -- Note from Mike Y: There are Manager Values for this, so this may need to be updated at some point. + SELECT EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, + SUM(BudgetAdjusted01) AS BudgetAdjusted01, SUM(BudgetAdjusted02) AS BudgetAdjusted02, SUM(BudgetAdjusted03) AS BudgetAdjusted03, + SUM(BudgetAdjusted04) AS BudgetAdjusted04, SUM(BudgetAdjusted05) AS BudgetAdjusted05, SUM(BudgetAdjusted06) AS BudgetAdjusted06, + SUM(BudgetAdjusted07) AS BudgetAdjusted07, SUM(BudgetAdjusted08) AS BudgetAdjusted08, SUM(BudgetAdjusted09) AS BudgetAdjusted09, + SUM(BudgetAdjusted10) AS BudgetAdjusted10, SUM(BudgetAdjusted11) AS BudgetAdjusted11, SUM(BudgetAdjusted12) AS BudgetAdjusted12 + FROM fp.ChargeVolume cv + WHERE cv.BudgetConfigID = @BudgetConfigID + AND cv.UnitTypeID = 145 + GROUP BY EntityID, + DepartmentID, + ServiceLineID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + ChargeCodeID, + UnitTypeID + ) cv + UNPIVOT (Value FOR FiscalMonth IN (BudgetAdjusted01, BudgetAdjusted02, BudgetAdjusted03, BudgetAdjusted04, BudgetAdjusted05, BudgetAdjusted06, BudgetAdjusted07, BudgetAdjusted08, BudgetAdjusted09, BudgetAdjusted10, BudgetAdjusted11, BudgetAdjusted12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'BudgetAdjusted', 'Month') + ) BudgetedData + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN [fw].[DimChargeCode] CC on CC.ChargeCodeID = BudgetedData.ChargeCodeID + INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = BudgetedData.PatientClassID + INNER JOIN [fw].[DimServiceLine] SL ON SL.ServiceLineID = BudgetedData.ServiceLineID + INNER JOIN [fw].[DimAgeCohort] AG ON AG.AgeCohortID = BudgetedData.AgeCohortID + INNER JOIN [fw].[DimMedicalSurgical] MS ON MS.MedicalSurgicalID = BudgetedData.MedicalSurgicalID + INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = BudgetedData.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = BudgetedData.FiscalMonthID + INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = BudgetedData.UnitTypeID + WHERE 1=1 + AND BudgetedData.Value <> 0 + AND bc.BudgetConfigID = @BudgetConfigID + UNION ALL + -- Charge Dollars --- + -- NOTE: Currently this logic is not working properly for when (SELECT IsDollarsRemovedFromCharges FROM fp.BudgetConfig) = 0, as dollars are on FactChargeVolume in this case. + SELECT + D.DepartmentID, + D.DepartmentCode, + CC.ChargeCodeID, + CC.ChargeCode, + bc.FiscalYearID, + bc.FiscalYearID AS FiscalYearCode, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + fm.FiscalMonthID, + fm.FiscalMonthCode, + PAT.PatientClassID, + PAT.Code AS [PatientClassCode], + SL.ServiceLineID AS ServiceLineID, + SL.Code AS ServiceLine, + AG.AgeCohortID AS AgeCohortID, + AG.Code AS AgeCohort, + MS.MedicalSurgicalID AS MedicalSurgicalID, + MS.Code AS MedSurg, + UT.UnitTypeID, + UT.Name AS [UnitType], + Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID + FROM ( + -- Original Note: Unpivot for Value IT DID NOT LOOK LIKE THERE WERE MANAGER VALUES FOR THIS AT ALL + -- Note from Mike Y: There are Manager Values for this, so this may need to be updated at some point. + SELECT EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, + SUM(BudgetDollarsAdjusted01) AS BudgetDollarsAdjusted01, SUM(BudgetDollarsAdjusted02) AS BudgetDollarsAdjusted02, SUM(BudgetDollarsAdjusted03) AS BudgetDollarsAdjusted03, + SUM(BudgetDollarsAdjusted04) AS BudgetDollarsAdjusted04, SUM(BudgetDollarsAdjusted05) AS BudgetDollarsAdjusted05, SUM(BudgetDollarsAdjusted06) AS BudgetDollarsAdjusted06, + SUM(BudgetDollarsAdjusted07) AS BudgetDollarsAdjusted07, SUM(BudgetDollarsAdjusted08) AS BudgetDollarsAdjusted08, SUM(BudgetDollarsAdjusted09) AS BudgetDollarsAdjusted09, + SUM(BudgetDollarsAdjusted10) AS BudgetDollarsAdjusted10, SUM(BudgetDollarsAdjusted11) AS BudgetDollarsAdjusted11, SUM(BudgetDollarsAdjusted12) AS BudgetDollarsAdjusted12 + FROM fp.ChargeVolume cv + WHERE cv.BudgetConfigID = @BudgetConfigID + GROUP BY EntityID, + DepartmentID, + ServiceLineID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + ChargeCodeID, + UnitTypeID + ) cv + UNPIVOT (Value FOR FiscalMonth IN (BudgetDollarsAdjusted01, BudgetDollarsAdjusted02, BudgetDollarsAdjusted03, BudgetDollarsAdjusted04, BudgetDollarsAdjusted05, BudgetDollarsAdjusted06, BudgetDollarsAdjusted07, BudgetDollarsAdjusted08, BudgetDollarsAdjusted09, BudgetDollarsAdjusted10, BudgetDollarsAdjusted11, BudgetDollarsAdjusted12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'BudgetDollarsAdjusted', 'Month') + ) BudgetedData + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN [fw].[DimChargeCode] CC on CC.ChargeCodeID = BudgetedData.ChargeCodeID + INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = BudgetedData.PatientClassID + INNER JOIN [fw].[DimServiceLine] SL ON SL.ServiceLineID = BudgetedData.ServiceLineID + INNER JOIN [fw].[DimAgeCohort] AG ON AG.AgeCohortID = BudgetedData.AgeCohortID + INNER JOIN [fw].[DimMedicalSurgical] MS ON MS.MedicalSurgicalID = BudgetedData.MedicalSurgicalID + INNER JOIN [fw].[DimDepartment] D on D.DepartmentID = BudgetedData.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = BudgetedData.FiscalMonthID + INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = 34 -- Charge Dollars + WHERE 1=1 + AND BudgetedData.Value <> 0 + AND bc.BudgetConfigID = @BudgetConfigID +END +GO + + +--------------------------------------------- + +-- fp.procChargeProjectionStampOff +CREATE PROCEDURE [fp].[procChargeProjectionStampOff] + @BudgetConfigID INT, + @TargetTimeClassID TINYINT, + @IsMonthsLoadedIncluded BIT +AS +BEGIN + /******************************************************************************* + ** Change History + ******************************************************************************** + ** CID Date Author WI Description + ** 1 11-09-2023 AO JAZZ-62128 Initial Creation + ** 2 01-03-2024 MZ JAZZ-65385 Added Target TimeClass + ** 3 01-24-2024 MZ JAZZ-64527 Fix Months Loaded + ** 4 03-18-2024 MZ JAZZ-68428 Deleting by Chunks & removed HistoryItemGUID parameter + ** 5 04-03-2024 MZ JAZZ-70053 Fix Month Loaded excluding logic + *******************************************************************************/ + + -- Note: The original script was done here https://confluence.sdt.local/display/DD/Moving+Data+from+a+Plan+Configuration+to+Int+Tables + + DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID - 1 FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID ) + DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID) + DECLARE @MonthsLoaded INT = (SELECT bc.MonthsLoaded FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID) + + DECLARE @HistoryItemGUID UNIQUEIDENTIFIER + EXEC procLogScript 'StampOff: Transferring Projection Data from 1p', @HistoryItemGUID OUTPUT + PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36)) + PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID) + + -- Clear out existing records for the selected FiscalYear and Projected Time Class + -- and all months if months loaded included otherwise only months NOT loaded will be cleared + DECLARE @ChunkCount INT + + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END + + DECLARE @r INT; + SET @r = 1; + + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) c FROM [int].[FactCDM] c + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = c.FiscalMonthID + WHERE c.FiscalYearID = @FiscalYear + AND c.TimeClassID = @TargetTimeClassID + AND (@IsMonthsLoadedIncluded = 1 OR fm.SortOrder > @MonthsLoaded) + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + --- Charge Units + INSERT INTO [int].[FactCDM] (DepartmentID, DepartmentCode, ChargeCodeID, ChargeCode, FiscalYearID, FiscalYearCode, + TimeClassID, TimeClassCode, FiscalMonthID, FiscalMonthCode, PatientClassID, PatientClassCode, ServiceLineID, + ServiceLine, AgeCohortID, AgeCohort, MedicalSurgicalID, MedSurg, UnitTypeID, UnitType, Value, IsDeleted, HistoryItemGUID) + SELECT + D.DepartmentID, + D.DepartmentCode, + CC.ChargeCodeID, + CC.ChargeCode, + @FiscalYear, + @FiscalYear AS FiscalYearCode, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + fm.FiscalMonthID, + fm.FiscalMonthCode, + PAT.PatientClassID, + PAT.Code AS [PatientClassCode], + SL.ServiceLineID AS ServiceLineID, + SL.Code AS ServiceLine, + AG.AgeCohortID AS AgeCohortID, + AG.Code AS AgeCohort, + MS.MedicalSurgicalID AS MedicalSurgicalID, + MS.Code AS MedSurg, + UT.UnitTypeID, + UT.Name AS [UnitType], + Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID + FROM ( + -- Original Note: Unpivot for Value IT DID NOT LOOK LIKE THERE WERE MANAGER VALUES FOR THIS AT ALL + -- Note from Mike Y: There are Manager Values for this, so this may need to be updated at some point. + SELECT EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, + SUM(ProjectionAdjusted01) AS ProjectionAdjusted01, SUM(ProjectionAdjusted02) AS ProjectionAdjusted02, SUM(ProjectionAdjusted03) AS ProjectionAdjusted03, + SUM(ProjectionAdjusted04) AS ProjectionAdjusted04, SUM(ProjectionAdjusted05) AS ProjectionAdjusted05, SUM(ProjectionAdjusted06) AS ProjectionAdjusted06, + SUM(ProjectionAdjusted07) AS ProjectionAdjusted07, SUM(ProjectionAdjusted08) AS ProjectionAdjusted08, SUM(ProjectionAdjusted09) AS ProjectionAdjusted09, + SUM(ProjectionAdjusted10) AS ProjectionAdjusted10, SUM(ProjectionAdjusted11) AS ProjectionAdjusted11, SUM(ProjectionAdjusted12) AS ProjectionAdjusted12 + FROM fp.ChargeVolume cv + WHERE cv.BudgetConfigID = @BudgetConfigID + AND cv.UnitTypeID = 145 + GROUP BY EntityID, + DepartmentID, + ServiceLineID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + ChargeCodeID, + UnitTypeID + ) cv + UNPIVOT (Value FOR FiscalMonth IN (ProjectionAdjusted01, ProjectionAdjusted02, ProjectionAdjusted03, ProjectionAdjusted04, ProjectionAdjusted05, ProjectionAdjusted06, ProjectionAdjusted07, ProjectionAdjusted08, ProjectionAdjusted09, ProjectionAdjusted10, ProjectionAdjusted11, ProjectionAdjusted12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectionAdjusted', 'Month') + ) BudgetedData + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN [fw].[DimChargeCode] CC on CC.ChargeCodeID = BudgetedData.ChargeCodeID + INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = BudgetedData.PatientClassID + INNER JOIN [fw].[DimServiceLine] SL ON SL.ServiceLineID = BudgetedData.ServiceLineID + INNER JOIN [fw].[DimAgeCohort] AG ON AG.AgeCohortID = BudgetedData.AgeCohortID + INNER JOIN [fw].[DimMedicalSurgical] MS ON MS.MedicalSurgicalID = BudgetedData.MedicalSurgicalID + INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = BudgetedData.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = BudgetedData.FiscalMonthID + INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = BudgetedData.UnitTypeID + WHERE 1=1 + AND BudgetedData.Value <> 0 + AND bc.BudgetConfigID = @BudgetConfigID + AND (@IsMonthsLoadedIncluded = 1 OR CAST(fm.FiscalMonthCode AS INT) > bc.MonthsLoaded) + UNION ALL + -- Charge Dollars --- + -- NOTE: Currently this logic is not working properly for when (SELECT IsDollarsRemovedFromCharges FROM fp.BudgetConfig) = 0, as dollars are on FactChargeVolume in this case. + SELECT + D.DepartmentID, + D.DepartmentCode, + CC.ChargeCodeID, + CC.ChargeCode, + @FiscalYear, + @FiscalYear AS FiscalYearCode, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + fm.FiscalMonthID, + fm.FiscalMonthCode, + PAT.PatientClassID, + PAT.Code AS [PatientClassCode], + SL.ServiceLineID AS ServiceLineID, + SL.Code AS ServiceLine, + AG.AgeCohortID AS AgeCohortID, + AG.Code AS AgeCohort, + MS.MedicalSurgicalID AS MedicalSurgicalID, + MS.Code AS MedSurg, + UT.UnitTypeID, + UT.Name AS [UnitType], + Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID + FROM ( + -- Original Note: Unpivot for Value IT DID NOT LOOK LIKE THERE WERE MANAGER VALUES FOR THIS AT ALL + -- Note from Mike Y: There are Manager Values for this, so this may need to be updated at some point. + SELECT EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT cv.EntityID, cv.DepartmentID, cv.ServiceLineID, cv.PatientClassID, cv.AgeCohortID, cv.MedicalSurgicalID, cv.ChargeCodeID, cv.UnitTypeID, + SUM(ProjectionDollarsAdjusted01) AS ProjectionDollarsAdjusted01, SUM(ProjectionDollarsAdjusted02) AS ProjectionDollarsAdjusted02, SUM(ProjectionDollarsAdjusted03) AS ProjectionDollarsAdjusted03, + SUM(ProjectionDollarsAdjusted04) AS ProjectionDollarsAdjusted04, SUM(ProjectionDollarsAdjusted05) AS ProjectionDollarsAdjusted05, SUM(ProjectionDollarsAdjusted06) AS ProjectionDollarsAdjusted06, + SUM(ProjectionDollarsAdjusted07) AS ProjectionDollarsAdjusted07, SUM(ProjectionDollarsAdjusted08) AS ProjectionDollarsAdjusted08, SUM(ProjectionDollarsAdjusted09) AS ProjectionDollarsAdjusted09, + SUM(ProjectionDollarsAdjusted10) AS ProjectionDollarsAdjusted10, SUM(ProjectionDollarsAdjusted11) AS ProjectionDollarsAdjusted11, SUM(ProjectionDollarsAdjusted12) AS ProjectionDollarsAdjusted12 + FROM fp.ChargeVolume cv + WHERE cv.BudgetConfigID = @BudgetConfigID + GROUP BY EntityID, + DepartmentID, + ServiceLineID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + ChargeCodeID, + UnitTypeID + ) cv + UNPIVOT (Value FOR FiscalMonth IN (ProjectionDollarsAdjusted01, ProjectionDollarsAdjusted02, ProjectionDollarsAdjusted03, ProjectionDollarsAdjusted04, ProjectionDollarsAdjusted05, ProjectionDollarsAdjusted06, ProjectionDollarsAdjusted07, ProjectionDollarsAdjusted08, ProjectionDollarsAdjusted09, ProjectionDollarsAdjusted10, ProjectionDollarsAdjusted11, ProjectionDollarsAdjusted12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectionDollarsAdjusted', 'Month') + ) BudgetedData + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN [fw].[DimChargeCode] CC on CC.ChargeCodeID = BudgetedData.ChargeCodeID + INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = BudgetedData.PatientClassID + INNER JOIN [fw].[DimServiceLine] SL ON SL.ServiceLineID = BudgetedData.ServiceLineID + INNER JOIN [fw].[DimAgeCohort] AG ON AG.AgeCohortID = BudgetedData.AgeCohortID + INNER JOIN [fw].[DimMedicalSurgical] MS ON MS.MedicalSurgicalID = BudgetedData.MedicalSurgicalID + INNER JOIN [fw].[DimDepartment] D on D.DepartmentID = BudgetedData.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = BudgetedData.FiscalMonthID + INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = 34 -- Charge Dollars + WHERE 1=1 + AND BudgetedData.Value <> 0 + AND bc.BudgetConfigID = @BudgetConfigID + AND (@IsMonthsLoadedIncluded = 1 OR CAST(fm.FiscalMonthCode AS INT) > bc.MonthsLoaded) +END +GO + + +--------------------------------------------- + +-- fp.procChargeVolumeApplySpread +/********************************************************************* +** Change History +********************************************************************** +** CID Date Author WI Description +** 1 2020-03-11 MY JAZZ-16618 Add Unit Targeting Check for IsCVReportRefreshRequired +** 2 2022-08-09 JB JAZZ-23177 Switch usages of funcGetSourceDimensionalityAsTable to a temp table +** 3 2023-03-06 MY JAZZ-48307 Update charges adjustment to support data model changes +*********************************************************************/ +CREATE PROCEDURE [fp].[procChargeVolumeApplySpread] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + IF OBJECT_ID('tempdb..#filterTable') IS NOT NULL DROP TABLE #filterTable; + IF OBJECT_ID('tempdb..#chargeVolumeIDs') IS NOT NULL DROP TABLE #chargeVolumeIDs; + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment; + + DECLARE @typeIdUnits INT = 145; + + CREATE TABLE #filterTable (ChargeVolumeID INT PRIMARY KEY CLUSTERED); + CREATE TABLE #chargeVolumeIDs (ChargeVolumeID INT); + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #filterTable (ChargeVolumeID) + SELECT DISTINCT basis.ChargeVolumeID + FROM [fp].[ChargeVolume] basis + INNER JOIN [fp].[viewChargeVolumeSpreads] spread + ON spread.BudgetConfigID = basis.BudgetConfigID + AND spread.DepartmentID = basis.DepartmentID + AND spread.ChargeCodeID = basis.ChargeCodeID + AND spread.PatientClassID = basis.PatientClassID + AND spread.AgeCohortID = basis.AgeCohortID + AND spread.MedicalSurgicalID = basis.MedicalSurgicalID + AND spread.ServiceLineID = basis.ServiceLineID + INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = basis.DepartmentID + WHERE basis.BudgetConfigID = @BudgetConfigID AND basis.UnitTypeID = @typeIdUnits AND basis.BudgetLockType <> 1 + END + ELSE BEGIN + INSERT INTO #filterTable (ChargeVolumeID) + SELECT DISTINCT basis.ChargeVolumeID + FROM [fp].[ChargeVolume] basis + INNER JOIN [fp].[viewChargeVolumeSpreads] spread + ON spread.BudgetConfigID = basis.BudgetConfigID + AND spread.DepartmentID = basis.DepartmentID + AND spread.ChargeCodeID = basis.ChargeCodeID + AND spread.PatientClassID = basis.PatientClassID + AND spread.AgeCohortID = basis.AgeCohortID + AND spread.MedicalSurgicalID = basis.MedicalSurgicalID + AND spread.ServiceLineID = basis.ServiceLineID + WHERE basis.BudgetConfigID = @BudgetConfigID AND basis.UnitTypeID = @typeIdUnits AND basis.BudgetLockType <> 1 + END + + + UPDATE fcv + SET + BudgetLockType = 6, + BudgetLockFlag = 1, + BudgetAdjusted01 = CAST(BudgetAdjustedTotal * SpreadPercentage01 AS DECIMAL(19,8)), + BudgetAdjusted02 = + CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage02 AS DECIMAL(19,8)) END, + BudgetAdjusted03 = + CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage03 AS DECIMAL(19,8)) END, + BudgetAdjusted04 = + CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage04 AS DECIMAL(19,8)) END, + BudgetAdjusted05 = + CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage05 AS DECIMAL(19,8)) END, + BudgetAdjusted06 = + CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage06 AS DECIMAL(19,8)) END, + BudgetAdjusted07 = + CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage07 AS DECIMAL(19,8)) END, + BudgetAdjusted08 = + CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage08 AS DECIMAL(19,8)) END, + BudgetAdjusted09 = + CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage09 AS DECIMAL(19,8)) END, + BudgetAdjusted10 = + CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage10 AS DECIMAL(19,8)) END, + BudgetAdjusted11 = + CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage10) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage11 AS DECIMAL(19,8)) END, + BudgetAdjusted12 = + CASE WHEN SpreadPercentage12 != 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage11) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage12 AS DECIMAL(19,8)) END + OUTPUT + INSERTED.ChargeVolumeID + INTO + #chargeVolumeIDs (ChargeVolumeID) + FROM [fp].[ChargeVolume] fcv + INNER JOIN #filterTable tmp on fcv.ChargeVolumeID = tmp.ChargeVolumeID + INNER JOIN [fp].[viewChargeVolumeSpreads] charsp + ON charsp.BudgetConfigID = fcv.BudgetConfigID + AND charsp.DepartmentID = fcv.DepartmentID + AND charsp.ChargeCodeID = fcv.ChargeCodeID + AND charsp.PatientClassID = fcv.PatientClassID + AND charsp.AgeCohortID = fcv.AgeCohortID + AND charsp.MedicalSurgicalID = fcv.MedicalSurgicalID + AND charsp.ServiceLineID = fcv.ServiceLineID + WHERE charsp.IsInactive = 0 + AND ( + BudgetAdjusted01 != CAST(BudgetAdjustedTotal * SpreadPercentage01 AS DECIMAL(19,8)) + OR BudgetAdjusted02 != + CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage02 AS DECIMAL(19,8)) END + OR BudgetAdjusted03 != + CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage03 AS DECIMAL(19,8)) END + OR BudgetAdjusted04 != + CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage04 AS DECIMAL(19,8)) END + OR BudgetAdjusted05 != + CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage05 AS DECIMAL(19,8)) END + OR BudgetAdjusted06 != + CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage06 AS DECIMAL(19,8)) END + OR BudgetAdjusted07 != + CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage07 AS DECIMAL(19,8)) END + OR BudgetAdjusted08 != + CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage08 AS DECIMAL(19,8)) END + OR BudgetAdjusted09 != + CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage09 AS DECIMAL(19,8)) END + OR BudgetAdjusted10 != + CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage10 AS DECIMAL(19,8)) END + OR BudgetAdjusted11 != + CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage10) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage11 AS DECIMAL(19,8)) END + OR BudgetAdjusted12 != + CASE WHEN SpreadPercentage12 != 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage11) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage12 AS DECIMAL(19,8)) END + OR BudgetLockType != 6 + OR BudgetLockFlag != 1 + ) + +END; +GO + + +--------------------------------------------- + +-- fp.procChargeVolumeCopyNewItems +CREATE PROCEDURE [fp].[procChargeVolumeCopyNewItems] + @SourceBudgetConfigID INT, + @SourceEntityGroupConfigID INT, + @BudgetConfigID INT, + @EntityGroupConfigID INT +AS +BEGIN +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-06-28 NT JAZZ-21664 Add missing provider dimensions + ** 2 2022-09-01 JB JAZZ-32095 Remove Payor and PayorGroupID from joins. + ** 3 2023-05-04 BW JAZZ-54095 Updated for new data model + ** 4 2023-06-01 AO JAZZ-55827 Excluded Add Provider records + *************************************************************/ +INSERT INTO [fp].[ChargeVolume] (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, UnitTypeID, AgeCohortID, ChargeCodeID, AddDate, + MedicalSurgicalID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, + PerformingProviderSpecialtyID, BillingCPTID, + SampledBudget01, SampledBudget02, SampledBudget03, SampledBudget04, SampledBudget05, SampledBudget06, SampledBudget07, SampledBudget08, SampledBudget09, SampledBudget10, SampledBudget11, SampledBudget12, + SampledProjection01, SampledProjection02, SampledProjection03, SampledProjection04, SampledProjection05, SampledProjection06, SampledProjection07, SampledProjection08, SampledProjection09, SampledProjection10, SampledProjection11, SampledProjection12, + InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, + InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12, + IsNew) +SELECT @BudgetConfigID, @EntityGroupConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, UnitTypeID, AgeCohortID, ChargeCodeID, AddDate, + MedicalSurgicalID, ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, + PerformingProviderSpecialtyID, BillingCPTID, + SampledBudget01, SampledBudget02, SampledBudget03, SampledBudget04, SampledBudget05, SampledBudget06, SampledBudget07, SampledBudget08, SampledBudget09, SampledBudget10, SampledBudget11, SampledBudget12, + SampledProjection01, SampledProjection02, SampledProjection03, SampledProjection04, SampledProjection05, SampledProjection06, SampledProjection07, SampledProjection08, SampledProjection09, SampledProjection10, SampledProjection11, SampledProjection12, + InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, + InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12, + IsNew +FROM [fp].[ChargeVolume] +LEFT JOIN [fp].[AddProviderSummary] ON ServiceProviderID = ProviderID +WHERE BudgetConfigID = @SourceBudgetConfigID + AND EntityGroupConfigID = @SourceEntityGroupConfigID + AND IsNew = 1 + AND ProviderID IS NULL + +END +GO + + +--------------------------------------------- + +-- fp.procClearBenefitDrivers +CREATE PROC [fp].[procClearBenefitDrivers] + @EntityGroupConfigID INT, + @TimeClassID INT, + @MonthsLoaded INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + + AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table + *************************************************************/ + + CREATE TABLE #FilterByDepartment (DepartmentID int,BudgetPhaseID int) + INSERT INTO #FilterByDepartment (DepartmentID,BudgetPhaseID) + SELECT DepartmentID,BudgetPhaseID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + + IF (@TimeClassID = 2) + BEGIN + + UPDATE budg + SET + AdjustedValue01 = 0, AdjustedValue02 = 0, AdjustedValue03 = 0, AdjustedValue04 = 0, AdjustedValue05 = 0, AdjustedValue06 = 0, + AdjustedValue07 = 0, AdjustedValue08 = 0, AdjustedValue09 = 0, AdjustedValue10 = 0, AdjustedValue11 = 0, AdjustedValue12 = 0, + FlexedValue01 = 0, FlexedValue02 = 0, FlexedValue03 = 0, FlexedValue04 = 0, FlexedValue05 = 0, FlexedValue06 = 0, + FlexedValue07 = 0, FlexedValue08 = 0, FlexedValue09 = 0, FlexedValue10 = 0, FlexedValue11 = 0, FlexedValue12 = 0 + FROM [fp].[FactBenefits] ben + INNER JOIN [fp].[FactBenefitsBudget] budg ON ben.BenefitsID = budg.BenefitsID + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = ben.DepartmentID or ft.DepartmentID is null) + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND UnitTypeID IN (144, 169) -- FTEs and Salaries + AND (ft.BudgetPhaseID IS NULL OR budg.BudgetPhaseID = ft.BudgetPhaseID) + + END ELSE BEGIN + + UPDATE proj + SET + proj.AdjustedValue01 = CASE WHEN 1 <= @MonthsLoaded THEN InitialProjection01 ELSE 0 END, + proj.AdjustedValue02 = CASE WHEN 2 <= @MonthsLoaded THEN InitialProjection02 ELSE 0 END, + proj.AdjustedValue03 = CASE WHEN 3 <= @MonthsLoaded THEN InitialProjection03 ELSE 0 END, + proj.AdjustedValue04 = CASE WHEN 4 <= @MonthsLoaded THEN InitialProjection04 ELSE 0 END, + proj.AdjustedValue05 = CASE WHEN 5 <= @MonthsLoaded THEN InitialProjection05 ELSE 0 END, + proj.AdjustedValue06 = CASE WHEN 6 <= @MonthsLoaded THEN InitialProjection06 ELSE 0 END, + proj.AdjustedValue07 = CASE WHEN 7 <= @MonthsLoaded THEN InitialProjection07 ELSE 0 END, + proj.AdjustedValue08 = CASE WHEN 8 <= @MonthsLoaded THEN InitialProjection08 ELSE 0 END, + proj.AdjustedValue09 = CASE WHEN 9 <= @MonthsLoaded THEN InitialProjection09 ELSE 0 END, + proj.AdjustedValue10 = CASE WHEN 10 <= @MonthsLoaded THEN InitialProjection10 ELSE 0 END, + proj.AdjustedValue11 = CASE WHEN 11 <= @MonthsLoaded THEN InitialProjection11 ELSE 0 END, + proj.AdjustedValue12 = CASE WHEN 12 <= @MonthsLoaded THEN InitialProjection12 ELSE 0 END, + proj.FlexedValue01 = CASE WHEN 1 <= @MonthsLoaded THEN InitialProjection01 ELSE 0 END, + proj.FlexedValue02 = CASE WHEN 2 <= @MonthsLoaded THEN InitialProjection02 ELSE 0 END, + proj.FlexedValue03 = CASE WHEN 3 <= @MonthsLoaded THEN InitialProjection03 ELSE 0 END, + proj.FlexedValue04 = CASE WHEN 4 <= @MonthsLoaded THEN InitialProjection04 ELSE 0 END, + proj.FlexedValue05 = CASE WHEN 5 <= @MonthsLoaded THEN InitialProjection05 ELSE 0 END, + proj.FlexedValue06 = CASE WHEN 6 <= @MonthsLoaded THEN InitialProjection06 ELSE 0 END, + proj.FlexedValue07 = CASE WHEN 7 <= @MonthsLoaded THEN InitialProjection07 ELSE 0 END, + proj.FlexedValue08 = CASE WHEN 8 <= @MonthsLoaded THEN InitialProjection08 ELSE 0 END, + proj.FlexedValue09 = CASE WHEN 9 <= @MonthsLoaded THEN InitialProjection09 ELSE 0 END, + proj.FlexedValue10 = CASE WHEN 10 <= @MonthsLoaded THEN InitialProjection10 ELSE 0 END, + proj.FlexedValue11 = CASE WHEN 11 <= @MonthsLoaded THEN InitialProjection11 ELSE 0 END, + proj.FlexedValue12 = CASE WHEN 12 <= @MonthsLoaded THEN InitialProjection12 ELSE 0 END + FROM [fp].[FactBenefits] ben + INNER JOIN [fp].[FactBenefitsProjection] proj ON ben.BenefitsID = proj.BenefitsID + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = ben.DepartmentID or ft.DepartmentID is null) + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND UnitTypeID IN (144, 169) -- FTEs and Salaries + AND (ft.BudgetPhaseID IS NULL OR proj.BudgetPhaseID = ft.BudgetPhaseID) + + END +GO + + +--------------------------------------------- + +-- fp.procClearBenefitDrivers_InitialValue +CREATE PROC [fp].[procClearBenefitDrivers_InitialValue] + @EntityGroupConfigID INT, + @TimeClassID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + + AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table + *************************************************************/ + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + + IF (@TimeClassID = 2) + BEGIN + + UPDATE tbl + SET + InitialBudget01 = 0, InitialBudget02 = 0, InitialBudget03 = 0, InitialBudget04 = 0, InitialBudget05 = 0, InitialBudget06 = 0, + InitialBudget07 = 0, InitialBudget08 = 0, InitialBudget09 = 0, InitialBudget10 = 0, InitialBudget11 = 0, InitialBudget12 = 0 + FROM [fp].[FactBenefits] tbl + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = tbl.DepartmentID or ft.DepartmentID is null) + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND UnitTypeID IN (144, 169) -- FTEs and Salaries + + END ELSE BEGIN + + DECLARE @MonthsLoaded INT + SELECT @MonthsLoaded = bc.MonthsLoaded from [fp].[BudgetConfig] bc inner join [fp].[EntityGroupConfig] egc on egc.BudgetConfigGUID = bc.BudgetConfigGUID where egc.EntityGroupConfigID = @EntityGroupConfigID + + UPDATE tbl + SET + InitialProjection01 = CASE WHEN 1 <= @MonthsLoaded THEN SampledProjection01 ELSE 0 END, + InitialProjection02 = CASE WHEN 2 <= @MonthsLoaded THEN SampledProjection02 ELSE 0 END, + InitialProjection03 = CASE WHEN 3 <= @MonthsLoaded THEN SampledProjection03 ELSE 0 END, + InitialProjection04 = CASE WHEN 4 <= @MonthsLoaded THEN SampledProjection04 ELSE 0 END, + InitialProjection05 = CASE WHEN 5 <= @MonthsLoaded THEN SampledProjection05 ELSE 0 END, + InitialProjection06 = CASE WHEN 6 <= @MonthsLoaded THEN SampledProjection06 ELSE 0 END, + InitialProjection07 = CASE WHEN 7 <= @MonthsLoaded THEN SampledProjection07 ELSE 0 END, + InitialProjection08 = CASE WHEN 8 <= @MonthsLoaded THEN SampledProjection08 ELSE 0 END, + InitialProjection09 = CASE WHEN 9 <= @MonthsLoaded THEN SampledProjection09 ELSE 0 END, + InitialProjection10 = CASE WHEN 10 <= @MonthsLoaded THEN SampledProjection10 ELSE 0 END, + InitialProjection11 = CASE WHEN 11 <= @MonthsLoaded THEN SampledProjection11 ELSE 0 END, + InitialProjection12 = CASE WHEN 12 <= @MonthsLoaded THEN SampledProjection12 ELSE 0 END + FROM [fp].[FactBenefits] tbl + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = tbl.DepartmentID or ft.DepartmentID is null) + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND UnitTypeID IN (144, 169) -- FTEs and Salaries + + END +GO + + +--------------------------------------------- + +-- fp.procClearChangeHistory +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-10-10 IP B-20922 Added using source dimensionality to ClearChangeHistory +** 2 2018-10-19 GF B-20922 Fix additional filter handling +** 3 2018-10-23 IP B-20922 Made additional refactoring +** 4 2020-01-12 MY B-25963 Fixing all of the above +** 5 2020-07-24 BK B-26717 Add targeting for Service Line Encounters +** 6 2020-12-07 MY X-XXXXX Increased precision for delete setting to allow larger setting +** 7 2022-09-19 BK JAZZ-42503 Add ProviderID to targeting for Service Line Encounters +** 8 2023-02-15 BW JAZZ-48306 Update base table name for new data model - Service Line Encounters +** 9 2023-08-11 AO JAZZ-57724 Fixed base table name for Reimbursement GL +** 10 2023-08-11 AO JAZZ-57724 Fixed base table name for Reimbursement GL +** 11 2024-01-02 MY JAZZ-64770 Fix Restructure Overwrite +*************************************************************/ +CREATE PROCEDURE [fp].[procClearChangeHistory] ( + @Direction VARCHAR(250)-- Benefits/ChargeVolume/GeneralLedger/Staffing/Statistics/ServiceLineEncounter/Reimbursement/ReimbursementGeneralLedger + ,@BudgetConfigID INT + ,@AdditionalFilter VARCHAR(max) = '1=1' + ,@iterationRowCount INT = 100000 + ,@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + ,@isDebug BIT = 0 + ) +AS +BEGIN + DECLARE @isFilterPresent BIT = CASE WHEN (SELECT COUNT(*) FROM @SourceDimensionality) >= 1 THEN 1 ELSE 0 END; + DECLARE @sqlCommand NVARCHAR(MAX) + DECLARE @tableType VARCHAR(10) = CASE WHEN (@Direction IN ('ServiceLineEncounter', 'ChargeVolume', 'GeneralLedger', 'ReimbursementGeneralLedger', 'Staffing')) THEN '' ELSE 'Fact' END; + + DECLARE @FilterLogic NVARCHAR(MAX) = CASE WHEN @isFilterPresent = 1 THEN ' + CREATE TABLE #FilteringTable ( + DepartmentID INT, + INDEX ix_1 NONCLUSTERED (DepartmentID) + ) + INSERT INTO #FilteringTable (DepartmentID) + SELECT DepartmentID + FROM @SourceDimensionality' ELSE '' END; + + DECLARE @FilterJoin NVARCHAR(MAX) = CASE WHEN @isFilterPresent = 1 THEN 'INNER JOIN #FilteringTable ft on ft.DepartmentID = res.DepartmentID' ELSE '' END; + + IF @Direction = 'ServiceLineEncounter' AND @isFilterPresent = 1 BEGIN + SET @FilterLogic = ' + CREATE TABLE #FilteringTable ( + EntityID INT, ServiceLineID INT, ProviderID INT, + INDEX ix_1 NONCLUSTERED (EntityID) + ) + INSERT INTO #FilteringTable (EntityID, ServiceLineID, ProviderID) + SELECT DISTINCT map.EntityID, map.ServiceLineID, map.ProviderID + FROM fp.ServiceLineEncounterChargeVolumeMapping map + INNER JOIN @SourceDimensionality ft on map.DepartmentID = ft.DepartmentID + WHERE map.BudgetConfigID = ' + CAST(@BudgetConfigID AS VARCHAR) + '; ' + + SET @FilterJoin = 'INNER JOIN #FilteringTable ft on ft.EntityID = res.EntityID AND ft.ServiceLineID = res.ServiceLineID AND ft.ProviderID = res.ProviderID' + END + + IF (@isFilterPresent = 0) + BEGIN + SET @sqlCommand = ' + DECLARE @Rowcount INT = 1 + WHILE @Rowcount > 0 + BEGIN + DELETE TOP (' + CAST(@iterationRowCount AS VARCHAR(16)) + ') ch + FROM [fp].[' + @Direction + 'ChangeHistory] ch + WHERE BudgetConfigID = ' + CAST(@BudgetConfigID AS VARCHAR(10)) + CASE + WHEN @AdditionalFilter = '1=1' + THEN '' + ELSE ' AND ' + @AdditionalFilter + END + ' + SET @Rowcount = @@ROWCOUNT + END + ' + END ELSE BEGIN + SET @sqlCommand = @FilterLogic + + ' + SELECT Ch.' + @Direction + 'ID + INTO #DeleteIDs + FROM [fp].[' + @tableType + @Direction + '] res + ' + @FilterJoin + ' + INNER JOIN [fp].[' + @Direction + 'ChangeHistory] ch ON ch.' + @Direction + 'ID = res.' + @Direction + 'ID + WHERE res.BudgetConfigID = ' + CAST(@BudgetConfigID AS VARCHAR(10)) + CASE + WHEN @AdditionalFilter = '1=1' + THEN '' + ELSE ' AND ' + @AdditionalFilter + END + ' + CREATE CLUSTERED INDEX idx_DeleteIDs on #DeleteIDs (' + @Direction + 'ID) + DECLARE @Rowcount INT = 1 + WHILE @Rowcount > 0 + BEGIN + DELETE TOP (' + CAST(@iterationRowCount AS VARCHAR(16)) + ') ch + FROM [fp].[' + @Direction + 'ChangeHistory] ch + INNER JOIN #DeleteIDs D ON ch.' + @Direction + 'ID = D.' + @Direction + 'ID + WHERE ch.BudgetConfigID = ' + CAST(@BudgetConfigID AS VARCHAR(10)) + ' + SET @Rowcount = @@ROWCOUNT + END + ' + END + + IF @isDebug = 1 + PRINT @sqlCommand + ELSE + EXECUTE sp_executesql @sqlCommand + ,N'@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY' + ,@SourceDimensionality = @SourceDimensionality +END +GO + + +--------------------------------------------- + +-- fp.procClearChargeInvalidReimbursement +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-05-12 MY JAZZ-54661 Initial +** 2 2024-01-11 AO JAZZ-64530 Data transfer for SLE is based on selected Model in Plan Config +** 3 2024-02-16 MD JAZZ-67663 Make reimbursement charges stop clearing out on CV update +** 4 2024-02-28 MD JAZZ-68291 Add targeting to update +*************************************************************/ +CREATE PROCEDURE [fp].[procClearChargeInvalidReimbursement] + @BudgetConfigID INT, + @IsReimbursementGLEnabled BIT = 0, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + + DECLARE @IsMedicalSurgicalUsed BIT = 0, + @IsMsdrgUsed BIT = 0, + @IsCptUsed BIT = 0, + @IsUBRevCodeUsed BIT = 0; + + SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'MedicalSurgicalID' + + SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'MSDRGID' + + SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'PrimaryCPTID' + + SELECT @IsUBRevCodeUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'UBRevCodeID' + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + IF OBJECT_ID('tempdb..#factReimbursementCharges') IS NOT NULL DROP TABLE #factReimbursementCharges; + IF OBJECT_ID('tempdb..#invalidReimbursementIds') IS NOT NULL DROP TABLE #invalidReimbursementIds; + + CREATE TABLE #invalidReimbursementIds (ReimbursementChargesID INT); + + CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT); + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #factReimbursementCharges ( + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + PatientClassID INT, + ServiceLineID INT, + ServiceLineRollupID INT, + MedicalSurgicalID INT, + PayorID INT, + PayorGroupID INT, + MSDRGID INT, + PrimaryCPTID INT, + UBRevCodeID INT + ) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED) + WHERE BudgetConfigID = @BudgetConfigID + END + + SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, + CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, + CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID, + CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID + INTO #reimbursementTargeting + FROM fp.ChargeVolume cv + INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID + INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID + WHERE cv.BudgetConfigID = @BudgetConfigID + + -- We are only moving Budget over and not projection because we don't display the baseline for projection so we don't need it. If we do ever need it, we'll need to add it to the mix table as well. + -- For Charges Only Data, we want to stick it in non-specified for Payor and PayorGroup + INSERT INTO #factReimbursementCharges (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, + MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, UBRevCodeID) + SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, + sd.PayorID, sd.PayorGroupID, + CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, + CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID, + CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID + FROM fp.ChargeVolume cv + INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID + INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID + INNER JOIN fp.ServiceLineEncounterToChargePayorMix sd ON cv.ServiceEntityID = sd.EntityID + AND cv.PatientClassID = sd.PatientClassID + AND cv.ServiceLineID = sd.ServiceLineID + AND cv.AgeCohortID = sd.AgeCohortID + AND cv.MedicalSurgicalID = sd.MedicalSurgicalID + AND cv.MSDRGID = sd.MSDRGID + AND cv.PrimaryCPTID = sd.CPTID + AND cv.ServiceProviderID = sd.ProviderID + AND cv.EntityGroupConfigID = sd.EntityGroupConfigID + WHERE cv.BudgetConfigID = @BudgetConfigID + + UNION + + SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, + 0 AS PayorID, 0 AS PayorGroupID, + CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, + CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID, + CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID + FROM fp.ChargeVolume cv + INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID + INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID + LEFT JOIN fp.ServiceLineEncounterToChargePayorMix sd ON cv.ServiceEntityID = sd.EntityID + AND cv.PatientClassID = sd.PatientClassID + AND cv.ServiceLineID = sd.ServiceLineID + AND cv.AgeCohortID = sd.AgeCohortID + AND cv.MedicalSurgicalID = sd.MedicalSurgicalID + AND cv.MSDRGID = sd.MSDRGID + AND cv.PrimaryCPTID = sd.CPTID + AND cv.ServiceProviderID = sd.ProviderID + AND cv.EntityGroupConfigID = sd.EntityGroupConfigID + LEFT JOIN #factReimbursementCharges tmp ON + cv.BudgetConfigID = tmp.BudgetConfigID + AND cv.EntityGroupConfigID = tmp.EntityGroupConfigID + AND cv.EntityID = tmp.EntityID + AND cv.PatientClassID = tmp.PatientClassID + AND cv.ServiceLineID = tmp.ServiceLineID + AND cv.MedicalSurgicalID = tmp.MedicalSurgicalID + AND tmp.PayorID = 0 + AND tmp.PayorGroupID = 0 + AND cv.MSDRGID = tmp.MSDRGID + AND cv.PrimaryCPTID = tmp.PrimaryCPTID + AND cv.UBRevCodeID = tmp.UBRevCodeID + WHERE cv.BudgetConfigID = @BudgetConfigID + AND sd.EntityID IS NULL + AND tmp.BudgetConfigID IS NULL -- Ensure that we didn't already add the 0 PayorID/0 PayorGroupID + + IF (@IsDebug = 1) + BEGIN + SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments + SELECT '#factReimbursementCharges', [BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [MedicalSurgicalID], + [PayorID], [PayorGroupID], [MSDRGID], [PrimaryCPTID], [UBRevCodeID] + FROM #factReimbursementCharges + END ELSE + BEGIN + + -- Set everything to 0 where it's in Reimbursement but not in Charges + UPDATE frc + SET + InitialBudgetChargeDollars01 = 0, + InitialBudgetChargeDollars02 = 0, + InitialBudgetChargeDollars03 = 0, + InitialBudgetChargeDollars04 = 0, + InitialBudgetChargeDollars05 = 0, + InitialBudgetChargeDollars06 = 0, + InitialBudgetChargeDollars07 = 0, + InitialBudgetChargeDollars08 = 0, + InitialBudgetChargeDollars09 = 0, + InitialBudgetChargeDollars10 = 0, + InitialBudgetChargeDollars11 = 0, + InitialBudgetChargeDollars12 = 0, + + InitialBudgetNetAsPercentOfCharge01 = 0, + InitialBudgetNetAsPercentOfCharge02 = 0, + InitialBudgetNetAsPercentOfCharge03 = 0, + InitialBudgetNetAsPercentOfCharge04 = 0, + InitialBudgetNetAsPercentOfCharge05 = 0, + InitialBudgetNetAsPercentOfCharge06 = 0, + InitialBudgetNetAsPercentOfCharge07 = 0, + InitialBudgetNetAsPercentOfCharge08 = 0, + InitialBudgetNetAsPercentOfCharge09 = 0, + InitialBudgetNetAsPercentOfCharge10 = 0, + InitialBudgetNetAsPercentOfCharge11 = 0, + InitialBudgetNetAsPercentOfCharge12 = 0, + + InitialBudgetNetPerDiem01 = 0, + InitialBudgetNetPerDiem02 = 0, + InitialBudgetNetPerDiem03 = 0, + InitialBudgetNetPerDiem04 = 0, + InitialBudgetNetPerDiem05 = 0, + InitialBudgetNetPerDiem06 = 0, + InitialBudgetNetPerDiem07 = 0, + InitialBudgetNetPerDiem08 = 0, + InitialBudgetNetPerDiem09 = 0, + InitialBudgetNetPerDiem10 = 0, + InitialBudgetNetPerDiem11 = 0, + InitialBudgetNetPerDiem12 = 0, + + InitialProjectionChargeDollars01 = 0, + InitialProjectionChargeDollars02 = 0, + InitialProjectionChargeDollars03 = 0, + InitialProjectionChargeDollars04 = 0, + InitialProjectionChargeDollars05 = 0, + InitialProjectionChargeDollars06 = 0, + InitialProjectionChargeDollars07 = 0, + InitialProjectionChargeDollars08 = 0, + InitialProjectionChargeDollars09 = 0, + InitialProjectionChargeDollars10 = 0, + InitialProjectionChargeDollars11 = 0, + InitialProjectionChargeDollars12 = 0, + + InitialProjectionNetAsPercentOfCharge01 = 0, + InitialProjectionNetAsPercentOfCharge02 = 0, + InitialProjectionNetAsPercentOfCharge03 = 0, + InitialProjectionNetAsPercentOfCharge04 = 0, + InitialProjectionNetAsPercentOfCharge05 = 0, + InitialProjectionNetAsPercentOfCharge06 = 0, + InitialProjectionNetAsPercentOfCharge07 = 0, + InitialProjectionNetAsPercentOfCharge08 = 0, + InitialProjectionNetAsPercentOfCharge09 = 0, + InitialProjectionNetAsPercentOfCharge10 = 0, + InitialProjectionNetAsPercentOfCharge11 = 0, + InitialProjectionNetAsPercentOfCharge12 = 0, + + InitialProjectionNetPerDiem01 = 0, + InitialProjectionNetPerDiem02 = 0, + InitialProjectionNetPerDiem03 = 0, + InitialProjectionNetPerDiem04 = 0, + InitialProjectionNetPerDiem05 = 0, + InitialProjectionNetPerDiem06 = 0, + InitialProjectionNetPerDiem07 = 0, + InitialProjectionNetPerDiem08 = 0, + InitialProjectionNetPerDiem09 = 0, + InitialProjectionNetPerDiem10 = 0, + InitialProjectionNetPerDiem11 = 0, + InitialProjectionNetPerDiem12 = 0 + OUTPUT + INSERTED.ReimbursementChargesID + INTO + #invalidReimbursementIds (ReimbursementChargesID) + FROM fp.FactReimbursementCharges frc + INNER JOIN #reimbursementTargeting rt ON + rt.BudgetConfigID = frc.BudgetConfigID + AND rt.EntityGroupConfigID = frc.EntityGroupConfigID + AND rt.EntityID = frc.EntityID + AND rt.PatientClassID = frc.PatientClassID + AND rt.ServiceLineID = frc.ServiceLineID + AND rt.ServiceLineRollupID = frc.ServiceLineRollupID + AND rt.MedicalSurgicalID = frc.MedicalSurgicalID + AND rt.MSDRGID = frc.MSDRGID + AND rt.PrimaryCPTID = frc.PrimaryCPTID + AND rt.UBRevCodeID = frc.UBRevCodeID + LEFT JOIN #factReimbursementCharges tmp ON + frc.BudgetConfigID = tmp.BudgetConfigID + AND frc.EntityGroupConfigID = tmp.EntityGroupConfigID + AND frc.EntityID = tmp.EntityID + AND frc.PatientClassID = tmp.PatientClassID + AND frc.ServiceLineID = tmp.ServiceLineID + AND frc.ServiceLineRollupID = tmp.ServiceLineRollupID + AND frc.MedicalSurgicalID = tmp.MedicalSurgicalID + AND frc.PayorID = tmp.PayorID + AND frc.PayorGroupID = tmp.PayorGroupID + AND frc.MSDRGID = tmp.MSDRGID + AND frc.PrimaryCPTID = tmp.PrimaryCPTID + AND frc.UBRevCodeID = tmp.UBRevCodeID + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = frc.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE frc.BudgetConfigID = @BudgetConfigID + AND ((tmp.BudgetConfigID IS NULL) + OR (@IsReimbursementGLEnabled = 1 AND ((bc.DefaultReimbursementNetRevenueModelID <> 1 AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID <> 1)) OR rnrm.NetRevenueModelID <> 1))) + --JAZZ-67663 - Commenting out for now because CV updates are incorrectly zeroing out reimbursement SLE data. + --OR @IsReimbursementGLEnabled = 0 + + UPDATE fcrb + SET + LockType = 0, + LockFlag = 0, + + AdjustedChargeDollars01 = 0, + AdjustedChargeDollars02 = 0, + AdjustedChargeDollars03 = 0, + AdjustedChargeDollars04 = 0, + AdjustedChargeDollars05 = 0, + AdjustedChargeDollars06 = 0, + AdjustedChargeDollars07 = 0, + AdjustedChargeDollars08 = 0, + AdjustedChargeDollars09 = 0, + AdjustedChargeDollars10 = 0, + AdjustedChargeDollars11 = 0, + AdjustedChargeDollars12 = 0, + + AdjustedNetAsPercentOfCharge01 = 0, + AdjustedNetAsPercentOfCharge02 = 0, + AdjustedNetAsPercentOfCharge03 = 0, + AdjustedNetAsPercentOfCharge04 = 0, + AdjustedNetAsPercentOfCharge05 = 0, + AdjustedNetAsPercentOfCharge06 = 0, + AdjustedNetAsPercentOfCharge07 = 0, + AdjustedNetAsPercentOfCharge08 = 0, + AdjustedNetAsPercentOfCharge09 = 0, + AdjustedNetAsPercentOfCharge10 = 0, + AdjustedNetAsPercentOfCharge11 = 0, + AdjustedNetAsPercentOfCharge12 = 0, + + AdjustedNetPerDiem01 = 0, + AdjustedNetPerDiem02 = 0, + AdjustedNetPerDiem03 = 0, + AdjustedNetPerDiem04 = 0, + AdjustedNetPerDiem05 = 0, + AdjustedNetPerDiem06 = 0, + AdjustedNetPerDiem07 = 0, + AdjustedNetPerDiem08 = 0, + AdjustedNetPerDiem09 = 0, + AdjustedNetPerDiem10 = 0, + AdjustedNetPerDiem11 = 0, + AdjustedNetPerDiem12 = 0 + FROM fp.FactReimbursementChargesBudget fcrb + INNER JOIN #invalidReimbursementIds inv ON inv.ReimbursementChargesID = fcrb.ReimbursementChargesID + + UPDATE fcrb + SET + LockType = 0, + LockFlag = 0, + + AdjustedChargeDollars01 = 0, + AdjustedChargeDollars02 = 0, + AdjustedChargeDollars03 = 0, + AdjustedChargeDollars04 = 0, + AdjustedChargeDollars05 = 0, + AdjustedChargeDollars06 = 0, + AdjustedChargeDollars07 = 0, + AdjustedChargeDollars08 = 0, + AdjustedChargeDollars09 = 0, + AdjustedChargeDollars10 = 0, + AdjustedChargeDollars11 = 0, + AdjustedChargeDollars12 = 0, + + AdjustedNetAsPercentOfCharge01 = 0, + AdjustedNetAsPercentOfCharge02 = 0, + AdjustedNetAsPercentOfCharge03 = 0, + AdjustedNetAsPercentOfCharge04 = 0, + AdjustedNetAsPercentOfCharge05 = 0, + AdjustedNetAsPercentOfCharge06 = 0, + AdjustedNetAsPercentOfCharge07 = 0, + AdjustedNetAsPercentOfCharge08 = 0, + AdjustedNetAsPercentOfCharge09 = 0, + AdjustedNetAsPercentOfCharge10 = 0, + AdjustedNetAsPercentOfCharge11 = 0, + AdjustedNetAsPercentOfCharge12 = 0, + + AdjustedNetPerDiem01 = 0, + AdjustedNetPerDiem02 = 0, + AdjustedNetPerDiem03 = 0, + AdjustedNetPerDiem04 = 0, + AdjustedNetPerDiem05 = 0, + AdjustedNetPerDiem06 = 0, + AdjustedNetPerDiem07 = 0, + AdjustedNetPerDiem08 = 0, + AdjustedNetPerDiem09 = 0, + AdjustedNetPerDiem10 = 0, + AdjustedNetPerDiem11 = 0, + AdjustedNetPerDiem12 = 0 + FROM fp.FactReimbursementChargesProjection fcrb + INNER JOIN #invalidReimbursementIds inv ON inv.ReimbursementChargesID = fcrb.ReimbursementChargesID + + UPDATE fcrb + SET + PriorYearActualChargeDollars01 = 0, + PriorYearActualChargeDollars02 = 0, + PriorYearActualChargeDollars03 = 0, + PriorYearActualChargeDollars04 = 0, + PriorYearActualChargeDollars05 = 0, + PriorYearActualChargeDollars06 = 0, + PriorYearActualChargeDollars07 = 0, + PriorYearActualChargeDollars08 = 0, + PriorYearActualChargeDollars09 = 0, + PriorYearActualChargeDollars10 = 0, + PriorYearActualChargeDollars11 = 0, + PriorYearActualChargeDollars12 = 0, + + ActualYTDChargeDollars01 = 0, + ActualYTDChargeDollars02 = 0, + ActualYTDChargeDollars03 = 0, + ActualYTDChargeDollars04 = 0, + ActualYTDChargeDollars05 = 0, + ActualYTDChargeDollars06 = 0, + ActualYTDChargeDollars07 = 0, + ActualYTDChargeDollars08 = 0, + ActualYTDChargeDollars09 = 0, + ActualYTDChargeDollars10 = 0, + ActualYTDChargeDollars11 = 0, + ActualYTDChargeDollars12 = 0, + + CurrentYearBudgetChargeDollars01 = 0, + CurrentYearBudgetChargeDollars02 = 0, + CurrentYearBudgetChargeDollars03 = 0, + CurrentYearBudgetChargeDollars04 = 0, + CurrentYearBudgetChargeDollars05 = 0, + CurrentYearBudgetChargeDollars06 = 0, + CurrentYearBudgetChargeDollars07 = 0, + CurrentYearBudgetChargeDollars08 = 0, + CurrentYearBudgetChargeDollars09 = 0, + CurrentYearBudgetChargeDollars10 = 0, + CurrentYearBudgetChargeDollars11 = 0, + CurrentYearBudgetChargeDollars12 = 0, + + CurrentYearBudgetChargeUnits01 = 0, + CurrentYearBudgetChargeUnits02 = 0, + CurrentYearBudgetChargeUnits03 = 0, + CurrentYearBudgetChargeUnits04 = 0, + CurrentYearBudgetChargeUnits05 = 0, + CurrentYearBudgetChargeUnits06 = 0, + CurrentYearBudgetChargeUnits07 = 0, + CurrentYearBudgetChargeUnits08 = 0, + CurrentYearBudgetChargeUnits09 = 0, + CurrentYearBudgetChargeUnits10 = 0, + CurrentYearBudgetChargeUnits11 = 0, + CurrentYearBudgetChargeUnits12 = 0, + + PriorYearActualNetAsPercentOfCharge01 = 0, + PriorYearActualNetAsPercentOfCharge02 = 0, + PriorYearActualNetAsPercentOfCharge03 = 0, + PriorYearActualNetAsPercentOfCharge04 = 0, + PriorYearActualNetAsPercentOfCharge05 = 0, + PriorYearActualNetAsPercentOfCharge06 = 0, + PriorYearActualNetAsPercentOfCharge07 = 0, + PriorYearActualNetAsPercentOfCharge08 = 0, + PriorYearActualNetAsPercentOfCharge09 = 0, + PriorYearActualNetAsPercentOfCharge10 = 0, + PriorYearActualNetAsPercentOfCharge11 = 0, + PriorYearActualNetAsPercentOfCharge12 = 0, + + ActualYTDNetAsPercentOfCharge01 = 0, + ActualYTDNetAsPercentOfCharge02 = 0, + ActualYTDNetAsPercentOfCharge03 = 0, + ActualYTDNetAsPercentOfCharge04 = 0, + ActualYTDNetAsPercentOfCharge05 = 0, + ActualYTDNetAsPercentOfCharge06 = 0, + ActualYTDNetAsPercentOfCharge07 = 0, + ActualYTDNetAsPercentOfCharge08 = 0, + ActualYTDNetAsPercentOfCharge09 = 0, + ActualYTDNetAsPercentOfCharge10 = 0, + ActualYTDNetAsPercentOfCharge11 = 0, + ActualYTDNetAsPercentOfCharge12 = 0, + + CurrentYearBudgetNetAsPercentOfCharge01 = 0, + CurrentYearBudgetNetAsPercentOfCharge02 = 0, + CurrentYearBudgetNetAsPercentOfCharge03 = 0, + CurrentYearBudgetNetAsPercentOfCharge04 = 0, + CurrentYearBudgetNetAsPercentOfCharge05 = 0, + CurrentYearBudgetNetAsPercentOfCharge06 = 0, + CurrentYearBudgetNetAsPercentOfCharge07 = 0, + CurrentYearBudgetNetAsPercentOfCharge08 = 0, + CurrentYearBudgetNetAsPercentOfCharge09 = 0, + CurrentYearBudgetNetAsPercentOfCharge10 = 0, + CurrentYearBudgetNetAsPercentOfCharge11 = 0, + CurrentYearBudgetNetAsPercentOfCharge12 = 0, + + PriorYearActualNetPerDiem01 = 0, + PriorYearActualNetPerDiem02 = 0, + PriorYearActualNetPerDiem03 = 0, + PriorYearActualNetPerDiem04 = 0, + PriorYearActualNetPerDiem05 = 0, + PriorYearActualNetPerDiem06 = 0, + PriorYearActualNetPerDiem07 = 0, + PriorYearActualNetPerDiem08 = 0, + PriorYearActualNetPerDiem09 = 0, + PriorYearActualNetPerDiem10 = 0, + PriorYearActualNetPerDiem11 = 0, + PriorYearActualNetPerDiem12 = 0, + + ActualYTDNetPerDiem01 = 0, + ActualYTDNetPerDiem02 = 0, + ActualYTDNetPerDiem03 = 0, + ActualYTDNetPerDiem04 = 0, ActualYTDNetPerDiem05 = 0, + ActualYTDNetPerDiem06 = 0, + ActualYTDNetPerDiem07 = 0, + ActualYTDNetPerDiem08 = 0, + ActualYTDNetPerDiem09 = 0, + ActualYTDNetPerDiem10 = 0, + ActualYTDNetPerDiem11 = 0, + ActualYTDNetPerDiem12 = 0, + + CurrentYearBudgetNetPerDiem01 = 0, + CurrentYearBudgetNetPerDiem02 = 0, + CurrentYearBudgetNetPerDiem03 = 0, + CurrentYearBudgetNetPerDiem04 = 0, + CurrentYearBudgetNetPerDiem05 = 0, + CurrentYearBudgetNetPerDiem06 = 0, + CurrentYearBudgetNetPerDiem07 = 0, + CurrentYearBudgetNetPerDiem08 = 0, + CurrentYearBudgetNetPerDiem09 = 0, + CurrentYearBudgetNetPerDiem10 = 0, + CurrentYearBudgetNetPerDiem11 = 0, + CurrentYearBudgetNetPerDiem12 = 0 + FROM fp.FactReimbursementChargesHistory fcrb + INNER JOIN #invalidReimbursementIds inv ON inv.ReimbursementChargesID = fcrb.ReimbursementChargesID + END +END +GO + + +--------------------------------------------- + +-- fp.procClearEncountersInvalidReimbursement +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-05-12 MY JAZZ-54661 Initial +** 2 2023-11-15 BK JAZZ-62974 Update for Entity and ServiceLines that do not exist in fp.ChargeVolume +** 3 2024-01-11 AO JAZZ-64530 Data transfer for SLE is based on selected Model in Plan Config +** 4 2024-02-16 MD JAZZ-67663 Make reimbursement encounters stop clearing out on SLE spread +** 5 2024-02-28 MD JAZZ-68291 Add targeting to update +*************************************************************/ +CREATE PROCEDURE [fp].[procClearEncountersInvalidReimbursement] + @BudgetConfigID INT, + @IsReimbursementGLEnabled BIT = 0, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + DECLARE @IsMedicalSurgicalUsed BIT, + @IsMsdrgUsed BIT, + @IsCptUsed BIT + + SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 5 -- Reimbursement - Encounters + AND ss.LevelID = 'MedicalSurgicalID' + + SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 5 -- Reimbursement - Encounters + AND ss.LevelID = 'MSDRGID' + + SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 5 -- Reimbursement - Encounters + AND ss.LevelID = 'PrimaryCPTID' + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + IF OBJECT_ID('tempdb..#factReimbursementEncounters') IS NOT NULL DROP TABLE #factReimbursementEncounters; + IF OBJECT_ID('tempdb..#encounterTargeting') IS NOT NULL DROP TABLE #encounterTargeting; + IF OBJECT_ID('tempdb..#invalidReimbursementIds') IS NOT NULL DROP TABLE #invalidReimbursementIds; + + CREATE TABLE #invalidReimbursementIds (ReimbursementEncounterID INT); + + CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT); + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #encounterTargeting (EntityID INT, ServiceLineID INT); + + IF EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #encounterTargeting (EntityID, ServiceLineID) + SELECT DISTINCT map.EntityID, map.ServiceLineID + FROM fp.ServiceLineEncounterChargeVolumeMapping map WITH (READUNCOMMITTED) + INNER JOIN #ChargeVolumeDepartments targeting ON map.DepartmentID = targeting.DepartmentID + WHERE map.BudgetConfigID = @BudgetConfigID + UNION + SELECT DISTINCT sle.EntityID, sle.ServiceLineID + FROM fp.ServiceLineEncounter sle LEFT JOIN fp.ChargeVolume cv on sle.BudgetConfigID = cv.BudgetConfigID AND sle.EntityID = cv.EntityID AND sle.ServiceLineID = cv.ServiceLineID + WHERE sle.BudgetConfigID = @BudgetConfigID AND cv.EntityID IS NULL + + END ELSE + BEGIN + INSERT INTO #encounterTargeting (EntityID, ServiceLineID) + SELECT DISTINCT map.EntityID, map.ServiceLineID + FROM fp.ServiceLineEncounter map WITH (READUNCOMMITTED) + WHERE map.BudgetConfigID = @BudgetConfigID + END + + SELECT DISTINCT sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN sle.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, + sle.PayorID, sle.PayorGroupID, + CASE WHEN @IsMsdrgUsed = 1 THEN sle.MSDRGID ELSE 0 END AS MSDRGID, + CASE WHEN @IsCptUsed = 1 THEN sle.CPTID ELSE 0 END AS CPTID + INTO #factReimbursementEncounters + FROM fp.ServiceLineEncounter sle + INNER JOIN #encounterTargeting targeting ON sle.EntityID = targeting.EntityID AND sle.ServiceLineID = targeting.ServiceLineID + WHERE sle.BudgetConfigID = @BudgetConfigID + + IF (@IsDebug = 1) + BEGIN + SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments + SELECT '#encounterTargeting', EntityID, ServiceLineID FROM #encounterTargeting + SELECT '#factReimbursementEncounters', sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, + sle.MedicalSurgicalID, sle.PayorID, sle.PayorGroupID, sle.MSDRGID, sle.CPTID + FROM #factReimbursementEncounters sle + END ELSE + BEGIN + + -- Set everything to 0 where it's in Reimbursement but not in Charges + UPDATE frc + SET + InitialBudgetEncounters01 = 0, + InitialBudgetEncounters02 = 0, + InitialBudgetEncounters03 = 0, + InitialBudgetEncounters04 = 0, + InitialBudgetEncounters05 = 0, + InitialBudgetEncounters06 = 0, + InitialBudgetEncounters07 = 0, + InitialBudgetEncounters08 = 0, + InitialBudgetEncounters09 = 0, + InitialBudgetEncounters10 = 0, + InitialBudgetEncounters11 = 0, + InitialBudgetEncounters12 = 0, + + InitialBudgetNetPerEncounter01 = 0, + InitialBudgetNetPerEncounter02 = 0, + InitialBudgetNetPerEncounter03 = 0, + InitialBudgetNetPerEncounter04 = 0, + InitialBudgetNetPerEncounter05 = 0, + InitialBudgetNetPerEncounter06 = 0, + InitialBudgetNetPerEncounter07 = 0, + InitialBudgetNetPerEncounter08 = 0, + InitialBudgetNetPerEncounter09 = 0, + InitialBudgetNetPerEncounter10 = 0, + InitialBudgetNetPerEncounter11 = 0, + InitialBudgetNetPerEncounter12 = 0, + + InitialProjectionEncounters01 = 0, + InitialProjectionEncounters02 = 0, + InitialProjectionEncounters03 = 0, + InitialProjectionEncounters04 = 0, + InitialProjectionEncounters05 = 0, + InitialProjectionEncounters06 = 0, + InitialProjectionEncounters07 = 0, + InitialProjectionEncounters08 = 0, + InitialProjectionEncounters09 = 0, + InitialProjectionEncounters10 = 0, + InitialProjectionEncounters11 = 0, + InitialProjectionEncounters12 = 0, + + InitialProjectionNetPerEncounter01 = 0, + InitialProjectionNetPerEncounter02 = 0, + InitialProjectionNetPerEncounter03 = 0, + InitialProjectionNetPerEncounter04 = 0, + InitialProjectionNetPerEncounter05 = 0, + InitialProjectionNetPerEncounter06 = 0, + InitialProjectionNetPerEncounter07 = 0, + InitialProjectionNetPerEncounter08 = 0, + InitialProjectionNetPerEncounter09 = 0, + InitialProjectionNetPerEncounter10 = 0, + InitialProjectionNetPerEncounter11 = 0, + InitialProjectionNetPerEncounter12 = 0 + OUTPUT + INSERTED.ReimbursementEncounterID + INTO + #invalidReimbursementIds (ReimbursementEncounterID) + FROM fp.FactReimbursementEncounter frc + INNER JOIN #encounterTargeting et on frc.EntityID = et.EntityID and frc.ServiceLineID = et.ServiceLineID + LEFT JOIN #factReimbursementEncounters tmp ON + frc.BudgetConfigID = tmp.BudgetConfigID + AND frc.EntityGroupConfigID = tmp.EntityGroupConfigID + AND frc.EntityID = tmp.EntityID + AND frc.PatientClassID = tmp.PatientClassID + AND frc.ServiceLineID = tmp.ServiceLineID + AND frc.ServiceLineRollupID = tmp.ServiceLineRollupID + AND frc.MedicalSurgicalID = tmp.MedicalSurgicalID + AND frc.PayorID = tmp.PayorID + AND frc.PayorGroupID = tmp.PayorGroupID + AND frc.MSDRGID = tmp.MSDRGID + AND frc.CPTID = tmp.CPTID + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = frc.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE frc.BudgetConfigID = @BudgetConfigID + AND ((tmp.BudgetConfigID IS NULL) + OR (@IsReimbursementGLEnabled = 1 AND ((bc.DefaultReimbursementNetRevenueModelID <> 1 AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID <> 1)) OR rnrm.NetRevenueModelID <> 1))) + --JAZZ-67663 - Commenting out for now because SLE spreads are incorrectly zeroing out reimbursement SLE data. + --OR @IsReimbursementGLEnabled = 0 + + UPDATE fcrb + SET + LockType = 0, + LockFlag = 0, + + AdjustedEncounters01 = 0, + AdjustedEncounters02 = 0, + AdjustedEncounters03 = 0, + AdjustedEncounters04 = 0, + AdjustedEncounters05 = 0, + AdjustedEncounters06 = 0, + AdjustedEncounters07 = 0, + AdjustedEncounters08 = 0, + AdjustedEncounters09 = 0, + AdjustedEncounters10 = 0, + AdjustedEncounters11 = 0, + AdjustedEncounters12 = 0, + + AdjustedNetPerEncounterValue01 = 0, + AdjustedNetPerEncounterValue02 = 0, + AdjustedNetPerEncounterValue03 = 0, + AdjustedNetPerEncounterValue04 = 0, + AdjustedNetPerEncounterValue05 = 0, + AdjustedNetPerEncounterValue06 = 0, + AdjustedNetPerEncounterValue07 = 0, + AdjustedNetPerEncounterValue08 = 0, + AdjustedNetPerEncounterValue09 = 0, + AdjustedNetPerEncounterValue10 = 0, + AdjustedNetPerEncounterValue11 = 0, + AdjustedNetPerEncounterValue12 = 0 + + FROM fp.FactReimbursementEncounterBudget fcrb + INNER JOIN #invalidReimbursementIds inv ON inv.ReimbursementEncounterID = fcrb.ReimbursementEncounterID + + UPDATE fcrb + SET + LockType = 0, + LockFlag = 0, + + AdjustedEncounters01 = 0, + AdjustedEncounters02 = 0, + AdjustedEncounters03 = 0, + AdjustedEncounters04 = 0, + AdjustedEncounters05 = 0, + AdjustedEncounters06 = 0, + AdjustedEncounters07 = 0, + AdjustedEncounters08 = 0, + AdjustedEncounters09 = 0, + AdjustedEncounters10 = 0, + AdjustedEncounters11 = 0, + AdjustedEncounters12 = 0, + + AdjustedNetPerEncounterValue01 = 0, + AdjustedNetPerEncounterValue02 = 0, + AdjustedNetPerEncounterValue03 = 0, + AdjustedNetPerEncounterValue04 = 0, + AdjustedNetPerEncounterValue05 = 0, + AdjustedNetPerEncounterValue06 = 0, + AdjustedNetPerEncounterValue07 = 0, + AdjustedNetPerEncounterValue08 = 0, + AdjustedNetPerEncounterValue09 = 0, + AdjustedNetPerEncounterValue10 = 0, + AdjustedNetPerEncounterValue11 = 0, + AdjustedNetPerEncounterValue12 = 0 + + FROM fp.FactReimbursementEncounterProjection fcrb + INNER JOIN #invalidReimbursementIds inv ON inv.ReimbursementEncounterID = fcrb.ReimbursementEncounterID + + UPDATE fcrb + SET + PriorYearActualEncounters01 = 0, + PriorYearActualEncounters02 = 0, + PriorYearActualEncounters03 = 0, + PriorYearActualEncounters04 = 0, + PriorYearActualEncounters05 = 0, + PriorYearActualEncounters06 = 0, + PriorYearActualEncounters07 = 0, + PriorYearActualEncounters08 = 0, + PriorYearActualEncounters09 = 0, + PriorYearActualEncounters10 = 0, + PriorYearActualEncounters11 = 0, + PriorYearActualEncounters12 = 0, + + ActualYTDEncounters01 = 0, + ActualYTDEncounters02 = 0, + ActualYTDEncounters03 = 0, + ActualYTDEncounters04 = 0, + ActualYTDEncounters05 = 0, + ActualYTDEncounters06 = 0, + ActualYTDEncounters07 = 0, + ActualYTDEncounters08 = 0, + ActualYTDEncounters09 = 0, + ActualYTDEncounters10 = 0, + ActualYTDEncounters11 = 0, + ActualYTDEncounters12 = 0, + + CurrentYearBudgetEncounters01 = 0, + CurrentYearBudgetEncounters02 = 0, + CurrentYearBudgetEncounters03 = 0, + CurrentYearBudgetEncounters04 = 0, + CurrentYearBudgetEncounters05 = 0, + CurrentYearBudgetEncounters06 = 0, + CurrentYearBudgetEncounters07 = 0, + CurrentYearBudgetEncounters08 = 0, + CurrentYearBudgetEncounters09 = 0, + CurrentYearBudgetEncounters10 = 0, + CurrentYearBudgetEncounters11 = 0, + CurrentYearBudgetEncounters12 = 0, + + PriorYearActualNetPerEncounterValue01 = 0, + PriorYearActualNetPerEncounterValue02 = 0, + PriorYearActualNetPerEncounterValue03 = 0, + PriorYearActualNetPerEncounterValue04 = 0, + PriorYearActualNetPerEncounterValue05 = 0, + PriorYearActualNetPerEncounterValue06 = 0, + PriorYearActualNetPerEncounterValue07 = 0, + PriorYearActualNetPerEncounterValue08 = 0, + PriorYearActualNetPerEncounterValue09 = 0, + PriorYearActualNetPerEncounterValue10 = 0, + PriorYearActualNetPerEncounterValue11 = 0, + PriorYearActualNetPerEncounterValue12 = 0, + + ActualYTDNetPerEncounterValue01 = 0, + ActualYTDNetPerEncounterValue02 = 0, + ActualYTDNetPerEncounterValue03 = 0, + ActualYTDNetPerEncounterValue04 = 0, + ActualYTDNetPerEncounterValue05 = 0, + ActualYTDNetPerEncounterValue06 = 0, + ActualYTDNetPerEncounterValue07 = 0, + ActualYTDNetPerEncounterValue08 = 0, + ActualYTDNetPerEncounterValue09 = 0, + ActualYTDNetPerEncounterValue10 = 0, + ActualYTDNetPerEncounterValue11 = 0, + ActualYTDNetPerEncounterValue12 = 0, + + CurrentYearNetPerEncounterBudget01 = 0, + CurrentYearNetPerEncounterBudget02 = 0, + CurrentYearNetPerEncounterBudget03 = 0, + CurrentYearNetPerEncounterBudget04 = 0, + CurrentYearNetPerEncounterBudget05 = 0, + CurrentYearNetPerEncounterBudget06 = 0, + CurrentYearNetPerEncounterBudget07 = 0, + CurrentYearNetPerEncounterBudget08 = 0, + CurrentYearNetPerEncounterBudget09 = 0, + CurrentYearNetPerEncounterBudget10 = 0, + CurrentYearNetPerEncounterBudget11 = 0, + CurrentYearNetPerEncounterBudget12 = 0 + + FROM fp.FactReimbursementEncounterHistory fcrb + INNER JOIN #invalidReimbursementIds inv ON inv.ReimbursementEncounterID = fcrb.ReimbursementEncounterID + + END +END +GO + + +--------------------------------------------- + +-- fp.procClearGeneralLedgerInvalidReimbursement +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-07-10 AO JAZZ-57493 Initial +** 2 2023-08-07 MZ JAZZ-55099 Fix targeting +** 3 2024-01-03 AO JAZZ-65384 Data transfer for GL is based on selected Model in Plan Config +** 4 2024-03-05 AO JAZZ-68696 Fix targeting clear +*************************************************************/ +CREATE PROCEDURE [fp].[procClearGeneralLedgerInvalidReimbursement] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#GeneralLedgerDepartments') IS NOT NULL DROP TABLE #GeneralLedgerDepartments; + IF OBJECT_ID('tempdb..#ReimbursementGeneralLedger') IS NOT NULL DROP TABLE #ReimbursementGeneralLedger; + IF OBJECT_ID('tempdb..#invalidReimbursementGeneralLedgerIds') IS NOT NULL DROP TABLE #invalidReimbursementGeneralLedgerIds; + IF OBJECT_ID('tempdb..#ReimbursementTargeting') IS NOT NULL DROP TABLE #ReimbursementTargeting; + + DECLARE @Revenue INT = 1; + DECLARE @Deduction INT = 4; + + CREATE TABLE #invalidReimbursementGeneralLedgerIds (ReimbursementGeneralLedgerID INT); + + CREATE TABLE #GeneralLedgerDepartments (DepartmentID INT); + INSERT INTO #GeneralLedgerDepartments (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #ReimbursementTargeting (EntityID INT); + + CREATE TABLE #ReimbursementGeneralLedger ( + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + PatientClassID INT, + PayorGroupID INT + ) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + -- We need to target EntityID as ReimbursementGL doesn't have DepartmentID + IF EXISTS(SELECT 1 FROM #GeneralLedgerDepartments WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #ReimbursementTargeting (EntityID) + SELECT DISTINCT EntityID + FROM [fp].[GeneralLedger] gl WITH (READUNCOMMITTED) + INNER JOIN #GeneralLedgerDepartments d ON gl.DepartmentID = d.DepartmentID + WHERE gl.BudgetConfigID = @BudgetConfigID + END ELSE + BEGIN + INSERT INTO #ReimbursementTargeting (EntityID) + SELECT DISTINCT EntityID + FROM [fp].[GeneralLedger] gl WITH (READUNCOMMITTED) + WHERE gl.BudgetConfigID = @BudgetConfigID + END + + + INSERT INTO #ReimbursementGeneralLedger (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, PayorGroupID) + SELECT DISTINCT gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.PatientClassID, a.OBPayorGroupID AS PayorGroupID + FROM fp.GeneralLedger gl + INNER JOIN [fw].[DimAccount] a ON gl.AccountID = a.AccountID + INNER JOIN #ReimbursementTargeting targeting ON gl.EntityID = targeting.EntityID + WHERE gl.BudgetConfigID = @BudgetConfigID + AND (gl.APEModelSectionID = @Revenue OR (gl.APEModelSectionID = @Deduction AND a.OBModelSectionName = 'Deductions - Reimbursement')) + + IF (@IsDebug = 1) + BEGIN + SELECT '#GeneralLedgerDepartments', DepartmentID FROM #GeneralLedgerDepartments + SELECT '#ReimbursementTargeting', EntityID FROM #ReimbursementTargeting + SELECT '#ReimbursementGeneralLedger', [BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [PayorGroupID] + FROM #ReimbursementGeneralLedger + END ELSE + BEGIN + + + UPDATE rgl + SET + InitialBudget01 = 0, + InitialBudget02 = 0, + InitialBudget03 = 0, + InitialBudget04 = 0, + InitialBudget05 = 0, + InitialBudget06 = 0, + InitialBudget07 = 0, + InitialBudget08 = 0, + InitialBudget09 = 0, + InitialBudget10 = 0, + InitialBudget11 = 0, + InitialBudget12 = 0, + + InitialProjection01 = 0, + InitialProjection02 = 0, + InitialProjection03 = 0, + InitialProjection04 = 0, + InitialProjection05 = 0, + InitialProjection06 = 0, + InitialProjection07 = 0, + InitialProjection08 = 0, + InitialProjection09 = 0, + InitialProjection10 = 0, + InitialProjection11 = 0, + InitialProjection12 = 0, + + InitialBudgetNetAsPercentOfCharge01 = 0, + InitialBudgetNetAsPercentOfCharge02 = 0, + InitialBudgetNetAsPercentOfCharge03 = 0, + InitialBudgetNetAsPercentOfCharge04 = 0, + InitialBudgetNetAsPercentOfCharge05 = 0, + InitialBudgetNetAsPercentOfCharge06 = 0, + InitialBudgetNetAsPercentOfCharge07 = 0, + InitialBudgetNetAsPercentOfCharge08 = 0, + InitialBudgetNetAsPercentOfCharge09 = 0, + InitialBudgetNetAsPercentOfCharge10 = 0, + InitialBudgetNetAsPercentOfCharge11 = 0, + InitialBudgetNetAsPercentOfCharge12 = 0, + + InitialProjectionNetAsPercentOfCharge01 = 0, + InitialProjectionNetAsPercentOfCharge02 = 0, + InitialProjectionNetAsPercentOfCharge03 = 0, + InitialProjectionNetAsPercentOfCharge04 = 0, + InitialProjectionNetAsPercentOfCharge05 = 0, + InitialProjectionNetAsPercentOfCharge06 = 0, + InitialProjectionNetAsPercentOfCharge07 = 0, + InitialProjectionNetAsPercentOfCharge08 = 0, + InitialProjectionNetAsPercentOfCharge09 = 0, + InitialProjectionNetAsPercentOfCharge10 = 0, + InitialProjectionNetAsPercentOfCharge11 = 0, + InitialProjectionNetAsPercentOfCharge12 = 0, + + TargetAdjusted01 = 0, + TargetAdjusted02 = 0, + TargetAdjusted03 = 0, + TargetAdjusted04 = 0, + TargetAdjusted05 = 0, + TargetAdjusted06 = 0, + TargetAdjusted07 = 0, + TargetAdjusted08 = 0, + TargetAdjusted09 = 0, + TargetAdjusted10 = 0, + TargetAdjusted11 = 0, + TargetAdjusted12 = 0, + + TargetAdjustedNetAsPercentOfCharge01 = 0, + TargetAdjustedNetAsPercentOfCharge02 = 0, + TargetAdjustedNetAsPercentOfCharge03 = 0, + TargetAdjustedNetAsPercentOfCharge04 = 0, + TargetAdjustedNetAsPercentOfCharge05 = 0, + TargetAdjustedNetAsPercentOfCharge06 = 0, + TargetAdjustedNetAsPercentOfCharge07 = 0, + TargetAdjustedNetAsPercentOfCharge08 = 0, + TargetAdjustedNetAsPercentOfCharge09 = 0, + TargetAdjustedNetAsPercentOfCharge10 = 0, + TargetAdjustedNetAsPercentOfCharge11 = 0, + TargetAdjustedNetAsPercentOfCharge12 = 0, + + BudgetAdjusted01 = 0, + BudgetAdjusted02 = 0, + BudgetAdjusted03 = 0, + BudgetAdjusted04 = 0, + BudgetAdjusted05 = 0, + BudgetAdjusted06 = 0, + BudgetAdjusted07 = 0, + BudgetAdjusted08 = 0, + BudgetAdjusted09 = 0, + BudgetAdjusted10 = 0, + BudgetAdjusted11 = 0, + BudgetAdjusted12 = 0, + + BudgetAdjustedNetAsPercentOfCharge01 = 0, + BudgetAdjustedNetAsPercentOfCharge02 = 0, + BudgetAdjustedNetAsPercentOfCharge03 = 0, + BudgetAdjustedNetAsPercentOfCharge04 = 0, + BudgetAdjustedNetAsPercentOfCharge05 = 0, + BudgetAdjustedNetAsPercentOfCharge06 = 0, + BudgetAdjustedNetAsPercentOfCharge07 = 0, + BudgetAdjustedNetAsPercentOfCharge08 = 0, + BudgetAdjustedNetAsPercentOfCharge09 = 0, + BudgetAdjustedNetAsPercentOfCharge10 = 0, + BudgetAdjustedNetAsPercentOfCharge11 = 0, + BudgetAdjustedNetAsPercentOfCharge12 = 0, + + ProjectionAdjusted01 = 0, + ProjectionAdjusted02 = 0, + ProjectionAdjusted03 = 0, + ProjectionAdjusted04 = 0, + ProjectionAdjusted05 = 0, + ProjectionAdjusted06 = 0, + ProjectionAdjusted07 = 0, + ProjectionAdjusted08 = 0, + ProjectionAdjusted09 = 0, + ProjectionAdjusted10 = 0, + ProjectionAdjusted11 = 0, + ProjectionAdjusted12 = 0, + + ProjectionAdjustedNetAsPercentOfCharge01 = 0, + ProjectionAdjustedNetAsPercentOfCharge02 = 0, + ProjectionAdjustedNetAsPercentOfCharge03 = 0, + ProjectionAdjustedNetAsPercentOfCharge04 = 0, + ProjectionAdjustedNetAsPercentOfCharge05 = 0, + ProjectionAdjustedNetAsPercentOfCharge06 = 0, + ProjectionAdjustedNetAsPercentOfCharge07 = 0, + ProjectionAdjustedNetAsPercentOfCharge08 = 0, + ProjectionAdjustedNetAsPercentOfCharge09 = 0, + ProjectionAdjustedNetAsPercentOfCharge10 = 0, + ProjectionAdjustedNetAsPercentOfCharge11 = 0, + ProjectionAdjustedNetAsPercentOfCharge12 = 0, + + BudgetLockType = 0, + BudgetLockFlag = 0, + + TargetLockType = 0, + TargetLockFlag = 0, + + ProjectionLockType = 0, + ProjectionLockFlag = 0 + OUTPUT + INSERTED.ReimbursementGeneralLedgerID + INTO + #invalidReimbursementGeneralLedgerIds (ReimbursementGeneralLedgerID) + FROM fp.ReimbursementGeneralLedger rgl + LEFT JOIN #ReimbursementGeneralLedger tmp ON + rgl.BudgetConfigID = tmp.BudgetConfigID + AND rgl.EntityGroupConfigID = tmp.EntityGroupConfigID + AND rgl.EntityID = tmp.EntityID + AND rgl.PatientClassID = tmp.PatientClassID + AND rgl.PayorGroupID = tmp.PayorGroupID + INNER JOIN #ReimbursementTargeting targeting ON + targeting.EntityID = rgl.EntityID + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON rnrm.EntityID = targeting.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE rgl.BudgetConfigID = @BudgetConfigID + AND ((tmp.BudgetConfigID IS NULL AND targeting.EntityID IS NOT NULL) + OR ((bc.DefaultReimbursementNetRevenueModelID <> 2 AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID <> 2)) + OR rnrm.NetRevenueModelID <> 2)) + + UPDATE rglh + SET + PriorYearActualValue01 = 0, + PriorYearActualValue02 = 0, + PriorYearActualValue03 = 0, + PriorYearActualValue04 = 0, + PriorYearActualValue05 = 0, + PriorYearActualValue06 = 0, + PriorYearActualValue07 = 0, + PriorYearActualValue08 = 0, + PriorYearActualValue09 = 0, + PriorYearActualValue10 = 0, + PriorYearActualValue11 = 0, + PriorYearActualValue12 = 0, + PriorYearActualValueNetAsPercentOfCharge01 = 0, + PriorYearActualValueNetAsPercentOfCharge02 = 0, + PriorYearActualValueNetAsPercentOfCharge03 = 0, + PriorYearActualValueNetAsPercentOfCharge04 = 0, + PriorYearActualValueNetAsPercentOfCharge05 = 0, + PriorYearActualValueNetAsPercentOfCharge06 = 0, + PriorYearActualValueNetAsPercentOfCharge07 = 0, + PriorYearActualValueNetAsPercentOfCharge08 = 0, + PriorYearActualValueNetAsPercentOfCharge09 = 0, + PriorYearActualValueNetAsPercentOfCharge10 = 0, + PriorYearActualValueNetAsPercentOfCharge11 = 0, + PriorYearActualValueNetAsPercentOfCharge12 = 0 + FROM fp.ReimbursementGeneralLedgerHistory rglh + INNER JOIN #invalidReimbursementGeneralLedgerIds inv ON inv.ReimbursementGeneralLedgerID = rglh.ReimbursementGeneralLedgerID + END +END +GO + + +--------------------------------------------- + +-- fp.procClearReportCache +/********************************************************************* +** Change History +********************************************************************** +** CID Date Author WI Description +** 1 2020-03-11 MY JAZZ-16618 Initial +** 2 2020-08-31 MY JAZZ-42472 Added Regular Reporting Sources +** 3 2022-10-24 MD JAZZ-32897 Added reimbursement reporting table +** 4 2024-04-11 DM JAZZ-70189 Added historical table for GL and delete GL data by condition +** 5 2024-07-04 DM JAZZ-70314 Added historical table for Staffing and delete Staffing data by condition +** 6 2024-07-16 YR JAZZ-70315 Added historical table for Statistics and delete Statistics data by condition +** 7 2024-12-05 NH JAZZ-78230 Added Adjustment History reporting table +*********************************************************************/ +CREATE PROCEDURE [fp].[procClearReportCache]( + @IsActiveConfigChanged BIT +) +WITH RECOMPILE +AS +BEGIN + -- when reporting plan is changed we only handle GL, Staffing and Statistic data for now + DELETE frgl + FROM fp.FactReportGeneralLedger frgl + INNER JOIN fp.BudgetConfig bc + ON bc.BudgetConfigID = frgl.BudgetConfigID + WHERE bc.IsActive != 1 AND bc.IsUsedForReportComparison != 1 + + DELETE frglh + FROM fp.FactReportGeneralLedgerHistory frglh + INNER JOIN fp.BudgetConfig bc + ON bc.BudgetConfigID = frglh.BudgetConfigID + WHERE bc.IsActive != 1 AND bc.IsUsedForReportComparison != 1 + + DELETE frs + FROM fp.FactReportStaffing frs + INNER JOIN fp.BudgetConfig bc + ON bc.BudgetConfigID = frs.BudgetConfigID + WHERE bc.IsActive != 1 AND bc.IsUsedForReportComparison != 1 + + DELETE frsh + FROM fp.FactReportStaffingHistory frsh + INNER JOIN fp.BudgetConfig bc + ON bc.BudgetConfigID = frsh.BudgetConfigID + WHERE bc.IsActive != 1 AND bc.IsUsedForReportComparison != 1 + + DELETE frst + FROM fp.FactReportStatistics frst + INNER JOIN fp.BudgetConfig bc + ON bc.BudgetConfigID = frst.BudgetConfigID + WHERE bc.IsActive != 1 AND bc.IsUsedForReportComparison != 1 + + DELETE frsth + FROM fp.FactReportStatisticsHistory frsth + INNER JOIN fp.BudgetConfig bc + ON bc.BudgetConfigID = frsth.BudgetConfigID + WHERE bc.IsActive != 1 AND bc.IsUsedForReportComparison != 1 + + -- This proc is used to clear out the report tables in the event of the active or reporting configuration changing. + -- This is required for nightly run reports so that they can completely refresh data. + IF(@IsActiveConfigChanged = 1) + BEGIN + -- These are done nightly, but also don't do deletes so we need to wipe them on active configuration change. + TRUNCATE TABLE fp.FactReportChargeVolume + TRUNCATE TABLE fp.FactReportEncounter + TRUNCATE TABLE fp.FactReportEncounterHistory + TRUNCATE TABLE fp.FactReportChargeToStatisticsCrosswalk + TRUNCATE TABLE fp.FactReportChargeToStatisticsCrosswalkHistory + TRUNCATE TABLE fp.FactReportReimbursement + TRUNCATE TABLE fp.FactReportAdjustmentHistory + END +END; +GO + + +--------------------------------------------- + +-- fp.procClearSpreadChangeHistory +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-12-08 MY JAZZ-63890 Initial +** 2 2024-01-02 MY JAZZ-64770 Upgrade to Restructure +*************************************************************/ +CREATE PROCEDURE [fp].[procClearSpreadChangeHistory] ( + @Direction VARCHAR(250), + @BudgetConfigID INT, + @AdditionalFilter VARCHAR(max) = '1 = 1', + @iterationRowCount INT = 100000, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @isDebug BIT = 0 +) +AS +BEGIN + DECLARE @isFilterPresent BIT = CASE WHEN (SELECT COUNT(*) FROM @SourceDimensionality) >= 1 THEN 1 ELSE 0 END; + DECLARE @sqlCommand NVARCHAR(MAX) + DECLARE @tableType VARCHAR(10) = CASE WHEN (@Direction IN ('ServiceLineEncounter', 'ChargeVolume', 'GeneralLedger', 'ReimbursementGeneralLedger', 'Staffing')) THEN '' ELSE 'Fact' END; + + DECLARE @FilterLogic NVARCHAR(MAX) = CASE WHEN @isFilterPresent = 1 THEN ' + CREATE TABLE #FilteringTable ( + DepartmentID INT, + INDEX ix_1 NONCLUSTERED (DepartmentID) + ) + INSERT INTO #FilteringTable (DepartmentID) + SELECT DepartmentID + FROM @SourceDimensionality' ELSE '' END; + + DECLARE @FilterJoin NVARCHAR(MAX) = CASE WHEN @isFilterPresent = 1 THEN 'INNER JOIN #FilteringTable ft on ft.DepartmentID = res.DepartmentID' ELSE '' END; + + IF @Direction = 'ServiceLineEncounter' AND @isFilterPresent = 1 BEGIN + SET @FilterLogic = ' + CREATE TABLE #FilteringTable ( + EntityID INT, ServiceLineID INT, ProviderID INT, + INDEX ix_1 NONCLUSTERED (EntityID) + ) + INSERT INTO #FilteringTable (EntityID, ServiceLineID, ProviderID) + SELECT DISTINCT map.EntityID, map.ServiceLineID, map.ProviderID + FROM fp.ServiceLineEncounterChargeVolumeMapping map + INNER JOIN @SourceDimensionality ft on map.DepartmentID = ft.DepartmentID + WHERE map.BudgetConfigID = ' + CAST(@BudgetConfigID AS VARCHAR) + '; ' + + SET @FilterJoin = 'INNER JOIN #FilteringTable ft on ft.EntityID = res.EntityID AND ft.ServiceLineID = res.ServiceLineID AND ft.ProviderID = res.ProviderID' + END + + IF (@isFilterPresent = 0) + BEGIN + SET @sqlCommand = ' + DECLARE @Rowcount INT = 1 + WHILE @Rowcount > 0 + BEGIN + DELETE TOP (' + CAST(@iterationRowCount AS VARCHAR(16)) + ') ch + FROM [fp].[' + @Direction + 'SpreadsChangeHistory] ch + WHERE BudgetConfigID = ' + CAST(@BudgetConfigID AS VARCHAR(10)) + CASE + WHEN @AdditionalFilter = '1=1' + THEN '' + ELSE ' AND ' + @AdditionalFilter + END + ' + SET @Rowcount = @@ROWCOUNT + END + ' + END ELSE BEGIN + SET @sqlCommand = @FilterLogic + + ' + SELECT Ch.' + @Direction + 'ID + INTO #DeleteIDs + FROM [fp].[' + @tableType + @Direction + '] res + ' + @FilterJoin + ' + INNER JOIN [fp].[' + @Direction + 'SpreadsChangeHistory] ch ON ch.' + @Direction + 'ID = res.' + @Direction + 'ID + WHERE res.BudgetConfigID = ' + CAST(@BudgetConfigID AS VARCHAR(10)) + CASE + WHEN @AdditionalFilter = '1=1' + THEN '' + ELSE ' AND ' + @AdditionalFilter + END + ' + CREATE CLUSTERED INDEX idx_DeleteIDs on #DeleteIDs (' + @Direction + 'ID) + DECLARE @Rowcount INT = 1 + WHILE @Rowcount > 0 + BEGIN + DELETE TOP (' + CAST(@iterationRowCount AS VARCHAR(16)) + ') ch + FROM [fp].[' + @Direction + 'SpreadsChangeHistory] ch + INNER JOIN #DeleteIDs D ON ch.' + @Direction + 'ID = D.' + @Direction + 'ID + WHERE ch.BudgetConfigID = ' + CAST(@BudgetConfigID AS VARCHAR(10)) + ' + SET @Rowcount = @@ROWCOUNT + END + ' + END + + IF @isDebug = 1 + PRINT @sqlCommand + ELSE + EXECUTE sp_executesql @sqlCommand + ,N'@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY' + ,@SourceDimensionality = @SourceDimensionality +END +GO + + +--------------------------------------------- + +-- fp.procCopyBenefitsToGeneralLedger +CREATE PROC [fp].[procCopyBenefitsToGeneralLedger] + @BudgetConfigID INT, + @MonthsLoaded INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + WITH RECOMPILE + AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table + ** 2 2020-08-04 NN JAZZ-133 Remove NULL checks to JOINS and drop temp table + ** 3 2023-08-10 MY JAZZ-58216 Update to new structure + ** 4 2023-11-21 MD JAZZ-64023 Add in month 12 check for target and budget + ** 5 2024-01-11 MY JAZZ-65544 Budget values for Benefits Accounts are overwritten + *************************************************************/ + + exec [dbo].[procSysDropTempTable] '#FilterByDepartment' + exec [dbo].[procSysDropTempTable] '#BudgetPhase' + + CREATE TABLE #FilterByDepartment (DepartmentID INT, BudgetPhaseID INT) + INSERT INTO #FilterByDepartment (DepartmentID, BudgetPhaseID) + SELECT DepartmentID, BudgetPhaseID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- Add both BudgetPhaseIDs to #BudgetPhase + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE BudgetPhaseID IS NOT NULL) + BEGIN + CREATE TABLE #BudgetPhase (BudgetPhaseID tinyint) + INSERT INTO #BudgetPhase (BudgetPhaseID) SELECT 2 UNION SELECT 3 + END + + -- If the FilterByDepartment is empty, add all departmentIds to avoid duplication of entire proc + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID, BudgetPhaseID) + SELECT DISTINCT DepartmentID, BudgetPhaseID + FROM [fp].[FactBenefits] d WITH (READUNCOMMITTED) + OUTER APPLY #BudgetPhase bp + WHERE BudgetConfigID = @BudgetConfigID + + DELETE #FilterByDepartment WHERE DepartmentID IS NULL + END + + --If BudgetPhaseID is null, but Dept is present update the table + ELSE IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE BudgetPhaseID IS NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID, BudgetPhaseID) + SELECT DepartmentID, bp.BudgetPhaseID + FROM #FilterByDepartment dd WITH (READUNCOMMITTED) + OUTER APPLY #BudgetPhase bp + + DELETE #FilterByDepartment WHERE BudgetPhaseID IS NULL + END + + DECLARE @CrosswalkTarget BIT = CASE WHEN EXISTS(SELECT 1 FROM #FilterByDepartment WHERE BudgetPhaseID = 2) THEN 1 ELSE 0 END + DECLARE @CrosswalkBudgetOrProjection BIT = CASE WHEN EXISTS(SELECT 1 FROM #FilterByDepartment WHERE BudgetPhaseID = 3) THEN 1 ELSE 0 END + + IF (@CrosswalkTarget = 1) + BEGIN + + UPDATE gl + SET + gl.TargetAdjusted01 = benBudg.AdjustedValue01, + gl.TargetAdjusted02 = benBudg.AdjustedValue02, + gl.TargetAdjusted03 = benBudg.AdjustedValue03, + gl.TargetAdjusted04 = benBudg.AdjustedValue04, + gl.TargetAdjusted05 = benBudg.AdjustedValue05, + gl.TargetAdjusted06 = benBudg.AdjustedValue06, + gl.TargetAdjusted07 = benBudg.AdjustedValue07, + gl.TargetAdjusted08 = benBudg.AdjustedValue08, + gl.TargetAdjusted09 = benBudg.AdjustedValue09, + gl.TargetAdjusted10 = benBudg.AdjustedValue10, + gl.TargetAdjusted11 = benBudg.AdjustedValue11, + gl.TargetAdjusted12 = benBudg.AdjustedValue12, + gl.TargetLockFlag = 1, + gl.TargetLockType = 2 + FROM [fp].[GeneralLedger] gl with (readuncommitted) + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = gl.DepartmentID + INNER JOIN [fp].[FactBenefits] ben with (readuncommitted) + ON gl.BudgetConfigID = ben.BudgetConfigID + AND gl.EntityGroupConfigID = ben.EntityGroupConfigID + AND gl.DepartmentID = ben.DepartmentID + AND gl.AccountID = ben.AccountID + AND ben.UnitTypeID = 34 + AND gl.FinancialReportingID = ben.FinancialReportingID + AND gl.EntityID = ben.EntityID + INNER JOIN [fp].[FactBenefitsBudget] benBudg ON ben.BenefitsID = benBudg.BenefitsID AND benBudg.BudgetPhaseID = 2 + WHERE 1 = 1 + AND ft.BudgetPhaseID = 2 + AND gl.APEModelSectionID = 5 + AND gl.VariabilityID = 2 + AND gl.BudgetConfigID = @BudgetConfigID + AND (gl.TargetAdjusted01 != benBudg.AdjustedValue01 OR + gl.TargetAdjusted02 != benBudg.AdjustedValue02 OR + gl.TargetAdjusted03 != benBudg.AdjustedValue03 OR + gl.TargetAdjusted04 != benBudg.AdjustedValue04 OR + gl.TargetAdjusted05 != benBudg.AdjustedValue05 OR + gl.TargetAdjusted06 != benBudg.AdjustedValue06 OR + gl.TargetAdjusted07 != benBudg.AdjustedValue07 OR + gl.TargetAdjusted08 != benBudg.AdjustedValue08 OR + gl.TargetAdjusted09 != benBudg.AdjustedValue09 OR + gl.TargetAdjusted10 != benBudg.AdjustedValue10 OR + gl.TargetAdjusted11 != benBudg.AdjustedValue11 OR + gl.TargetAdjusted12 != benBudg.AdjustedValue12 OR + gl.TargetLockFlag != 1 OR + gl.TargetLockType != 2) + + END + + IF (@CrosswalkBudgetOrProjection = 1) + BEGIN + + UPDATE gl + SET + gl.BudgetAdjusted01 = benBudg.AdjustedValue01, + gl.BudgetAdjusted02 = benBudg.AdjustedValue02, + gl.BudgetAdjusted03 = benBudg.AdjustedValue03, + gl.BudgetAdjusted04 = benBudg.AdjustedValue04, + gl.BudgetAdjusted05 = benBudg.AdjustedValue05, + gl.BudgetAdjusted06 = benBudg.AdjustedValue06, + gl.BudgetAdjusted07 = benBudg.AdjustedValue07, + gl.BudgetAdjusted08 = benBudg.AdjustedValue08, + gl.BudgetAdjusted09 = benBudg.AdjustedValue09, + gl.BudgetAdjusted10 = benBudg.AdjustedValue10, + gl.BudgetAdjusted11 = benBudg.AdjustedValue11, + gl.BudgetAdjusted12 = benBudg.AdjustedValue12, + gl.BudgetLockFlag = 1, + gl.BudgetLockType = 2, + gl.ProjectionAdjusted01 = CASE WHEN @MonthsLoaded < 1 THEN benProj.AdjustedValue01 ELSE gl.ProjectionAdjusted01 END, + gl.ProjectionAdjusted02 = CASE WHEN @MonthsLoaded < 2 THEN benProj.AdjustedValue02 ELSE gl.ProjectionAdjusted02 END, + gl.ProjectionAdjusted03 = CASE WHEN @MonthsLoaded < 3 THEN benProj.AdjustedValue03 ELSE gl.ProjectionAdjusted03 END, + gl.ProjectionAdjusted04 = CASE WHEN @MonthsLoaded < 4 THEN benProj.AdjustedValue04 ELSE gl.ProjectionAdjusted04 END, + gl.ProjectionAdjusted05 = CASE WHEN @MonthsLoaded < 5 THEN benProj.AdjustedValue05 ELSE gl.ProjectionAdjusted05 END, + gl.ProjectionAdjusted06 = CASE WHEN @MonthsLoaded < 6 THEN benProj.AdjustedValue06 ELSE gl.ProjectionAdjusted06 END, + gl.ProjectionAdjusted07 = CASE WHEN @MonthsLoaded < 7 THEN benProj.AdjustedValue07 ELSE gl.ProjectionAdjusted07 END, + gl.ProjectionAdjusted08 = CASE WHEN @MonthsLoaded < 8 THEN benProj.AdjustedValue08 ELSE gl.ProjectionAdjusted08 END, + gl.ProjectionAdjusted09 = CASE WHEN @MonthsLoaded < 9 THEN benProj.AdjustedValue09 ELSE gl.ProjectionAdjusted09 END, + gl.ProjectionAdjusted10 = CASE WHEN @MonthsLoaded < 10 THEN benProj.AdjustedValue10 ELSE gl.ProjectionAdjusted10 END, + gl.ProjectionAdjusted11 = CASE WHEN @MonthsLoaded < 11 THEN benProj.AdjustedValue11 ELSE gl.ProjectionAdjusted11 END, + gl.ProjectionAdjusted12 = CASE WHEN @MonthsLoaded < 12 THEN benProj.AdjustedValue12 ELSE gl.ProjectionAdjusted12 END, + gl.ProjectionLockFlag = 1, + gl.ProjectionLockType = 2 + FROM [fp].[GeneralLedger] gl with (readuncommitted) + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = gl.DepartmentID + INNER JOIN [fp].[FactBenefits] ben with (readuncommitted) + ON gl.BudgetConfigID = ben.BudgetConfigID + AND gl.EntityGroupConfigID = ben.EntityGroupConfigID + AND gl.DepartmentID = ben.DepartmentID + AND gl.AccountID = ben.AccountID + AND ben.UnitTypeID = 34 + AND gl.FinancialReportingID = ben.FinancialReportingID + AND gl.EntityID = ben.EntityID + INNER JOIN [fp].[FactBenefitsBudget] benBudg ON ben.BenefitsID = benBudg.BenefitsID AND benBudg.BudgetPhaseID = 3 + INNER JOIN [fp].[FactBenefitsProjection] benProj ON ben.BenefitsID = benProj.BenefitsID AND benProj.BudgetPhaseID = 3 + WHERE 1 = 1 + AND ft.BudgetPhaseID = 3 + AND gl.APEModelSectionID = 5 + AND gl.VariabilityID = 2 + AND gl.BudgetConfigID = @BudgetConfigID + AND ( + + gl.BudgetAdjusted01 != benBudg.AdjustedValue01 OR + gl.BudgetAdjusted02 != benBudg.AdjustedValue02 OR + gl.BudgetAdjusted03 != benBudg.AdjustedValue03 OR + gl.BudgetAdjusted04 != benBudg.AdjustedValue04 OR + gl.BudgetAdjusted05 != benBudg.AdjustedValue05 OR + gl.BudgetAdjusted06 != benBudg.AdjustedValue06 OR + gl.BudgetAdjusted07 != benBudg.AdjustedValue07 OR + gl.BudgetAdjusted08 != benBudg.AdjustedValue08 OR + gl.BudgetAdjusted09 != benBudg.AdjustedValue09 OR + gl.BudgetAdjusted10 != benBudg.AdjustedValue10 OR + gl.BudgetAdjusted11 != benBudg.AdjustedValue11 OR + gl.BudgetAdjusted12 != benBudg.AdjustedValue12 OR + gl.BudgetLockFlag != 1 OR + gl.BudgetLockType != 2 OR + gl.ProjectionAdjusted01 != CASE WHEN @MonthsLoaded < 1 THEN benProj.AdjustedValue01 ELSE gl.ProjectionAdjusted01 END OR + gl.ProjectionAdjusted02 != CASE WHEN @MonthsLoaded < 2 THEN benProj.AdjustedValue02 ELSE gl.ProjectionAdjusted02 END OR + gl.ProjectionAdjusted03 != CASE WHEN @MonthsLoaded < 3 THEN benProj.AdjustedValue03 ELSE gl.ProjectionAdjusted03 END OR + gl.ProjectionAdjusted04 != CASE WHEN @MonthsLoaded < 4 THEN benProj.AdjustedValue04 ELSE gl.ProjectionAdjusted04 END OR + gl.ProjectionAdjusted05 != CASE WHEN @MonthsLoaded < 5 THEN benProj.AdjustedValue05 ELSE gl.ProjectionAdjusted05 END OR + gl.ProjectionAdjusted06 != CASE WHEN @MonthsLoaded < 6 THEN benProj.AdjustedValue06 ELSE gl.ProjectionAdjusted06 END OR + gl.ProjectionAdjusted07 != CASE WHEN @MonthsLoaded < 7 THEN benProj.AdjustedValue07 ELSE gl.ProjectionAdjusted07 END OR + gl.ProjectionAdjusted08 != CASE WHEN @MonthsLoaded < 8 THEN benProj.AdjustedValue08 ELSE gl.ProjectionAdjusted08 END OR + gl.ProjectionAdjusted09 != CASE WHEN @MonthsLoaded < 9 THEN benProj.AdjustedValue09 ELSE gl.ProjectionAdjusted09 END OR + gl.ProjectionAdjusted10 != CASE WHEN @MonthsLoaded < 10 THEN benProj.AdjustedValue10 ELSE gl.ProjectionAdjusted10 END OR + gl.ProjectionAdjusted11 != CASE WHEN @MonthsLoaded < 11 THEN benProj.AdjustedValue11 ELSE gl.ProjectionAdjusted11 END OR + gl.ProjectionAdjusted12 != CASE WHEN @MonthsLoaded < 12 THEN benProj.AdjustedValue12 ELSE gl.ProjectionAdjusted12 END OR + gl.ProjectionLockFlag != 1 OR + gl.ProjectionLockType != 2 + ) + + END + + -- Lock any fixed cells that need to be locked + UPDATE gl + SET + TargetLockFlag = 1, + TargetLockType = 2, + BudgetLockFlag = 1, + BudgetLockType = 2, + ProjectionLockFlag = 1, + ProjectionLockType = 2 + FROM [fp].[GeneralLedger] gl + INNER JOIN (SELECT DISTINCT DepartmentID FROM #FilterByDepartment) ft on ft.DepartmentID = gl.DepartmentID + WHERE gl.BudgetConfigID = @BudgetConfigID + AND gl.APEModelSectionID = 5 + AND gl.VariabilityID = 1 + AND (TargetLockFlag = 0 OR BudgetLockFlag = 0 OR ProjectionLockFlag = 0) +GO + + +--------------------------------------------- + +-- fp.procCopyBenefitsToGeneralLedger_Initial +CREATE PROC [fp].[procCopyBenefitsToGeneralLedger_Initial] + @BudgetConfigID INT, + @MonthsLoaded INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + WITH RECOMPILE + AS + + /************************************************************* + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-08-22 MY JAZZ-59505 Initial Creation + *************************************************************/ + + exec [dbo].[procSysDropTempTable] '#FilterByDepartment' + exec [dbo].[procSysDropTempTable] '#BudgetPhase' + + CREATE TABLE #FilterByDepartment (DepartmentID INT) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the FilterByDepartment is empty, add all departmentIds to avoid duplication of entire proc + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[FactBenefits] d WITH (READUNCOMMITTED) + WHERE BudgetConfigID = @BudgetConfigID + + DELETE #FilterByDepartment WHERE DepartmentID IS NULL + END + + -- Update the baseline values + UPDATE gl + SET + gl.InitialBudget01 = ben.InitialBudget01, + gl.InitialBudget02 = ben.InitialBudget02, + gl.InitialBudget03 = ben.InitialBudget03, + gl.InitialBudget04 = ben.InitialBudget04, + gl.InitialBudget05 = ben.InitialBudget05, + gl.InitialBudget06 = ben.InitialBudget06, + gl.InitialBudget07 = ben.InitialBudget07, + gl.InitialBudget08 = ben.InitialBudget08, + gl.InitialBudget09 = ben.InitialBudget09, + gl.InitialBudget10 = ben.InitialBudget10, + gl.InitialBudget11 = ben.InitialBudget11, + gl.InitialBudget12 = ben.InitialBudget12, + + gl.InitialProjection01 = CASE WHEN @MonthsLoaded < 1 THEN ben.InitialProjection01 ELSE gl.InitialProjection01 END, + gl.InitialProjection02 = CASE WHEN @MonthsLoaded < 2 THEN ben.InitialProjection02 ELSE gl.InitialProjection02 END, + gl.InitialProjection03 = CASE WHEN @MonthsLoaded < 3 THEN ben.InitialProjection03 ELSE gl.InitialProjection03 END, + gl.InitialProjection04 = CASE WHEN @MonthsLoaded < 4 THEN ben.InitialProjection04 ELSE gl.InitialProjection04 END, + gl.InitialProjection05 = CASE WHEN @MonthsLoaded < 5 THEN ben.InitialProjection05 ELSE gl.InitialProjection05 END, + gl.InitialProjection06 = CASE WHEN @MonthsLoaded < 6 THEN ben.InitialProjection06 ELSE gl.InitialProjection06 END, + gl.InitialProjection07 = CASE WHEN @MonthsLoaded < 7 THEN ben.InitialProjection07 ELSE gl.InitialProjection07 END, + gl.InitialProjection08 = CASE WHEN @MonthsLoaded < 8 THEN ben.InitialProjection08 ELSE gl.InitialProjection08 END, + gl.InitialProjection09 = CASE WHEN @MonthsLoaded < 9 THEN ben.InitialProjection09 ELSE gl.InitialProjection09 END, + gl.InitialProjection10 = CASE WHEN @MonthsLoaded < 10 THEN ben.InitialProjection10 ELSE gl.InitialProjection10 END, + gl.InitialProjection11 = CASE WHEN @MonthsLoaded < 11 THEN ben.InitialProjection11 ELSE gl.InitialProjection11 END, + gl.InitialProjection12 = CASE WHEN @MonthsLoaded < 12 THEN ben.InitialProjection12 ELSE gl.InitialProjection12 END + FROM [fp].[GeneralLedger] gl + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = gl.DepartmentID + INNER JOIN [fp].[FactBenefits] ben with (readuncommitted) + ON gl.BudgetConfigID = ben.BudgetConfigID + AND gl.EntityGroupConfigID = ben.EntityGroupConfigID + AND gl.DepartmentID = ben.DepartmentID + AND gl.AccountID = ben.AccountID + AND ben.UnitTypeID = 34 + AND gl.FinancialReportingID = ben.FinancialReportingID + AND gl.EntityID = ben.EntityID + WHERE 1 = 1 + AND gl.VariabilityID = 2 + AND gl.BudgetConfigID = @BudgetConfigID + AND (gl.InitialBudget01 != ben.InitialBudget01 OR + gl.InitialBudget02 != ben.InitialBudget02 OR + gl.InitialBudget03 != ben.InitialBudget03 OR + gl.InitialBudget04 != ben.InitialBudget04 OR + gl.InitialBudget05 != ben.InitialBudget05 OR + gl.InitialBudget06 != ben.InitialBudget06 OR + gl.InitialBudget07 != ben.InitialBudget07 OR + gl.InitialBudget08 != ben.InitialBudget08 OR + gl.InitialBudget09 != ben.InitialBudget09 OR + gl.InitialBudget10 != ben.InitialBudget10 OR + gl.InitialBudget11 != ben.InitialBudget11 OR + gl.InitialBudget12 != ben.InitialBudget12 OR + gl.InitialProjection01 != CASE WHEN @MonthsLoaded < 1 THEN ben.InitialProjection01 ELSE gl.InitialProjection01 END OR + gl.InitialProjection02 != CASE WHEN @MonthsLoaded < 2 THEN ben.InitialProjection02 ELSE gl.InitialProjection02 END OR + gl.InitialProjection03 != CASE WHEN @MonthsLoaded < 3 THEN ben.InitialProjection03 ELSE gl.InitialProjection03 END OR + gl.InitialProjection04 != CASE WHEN @MonthsLoaded < 4 THEN ben.InitialProjection04 ELSE gl.InitialProjection04 END OR + gl.InitialProjection05 != CASE WHEN @MonthsLoaded < 5 THEN ben.InitialProjection05 ELSE gl.InitialProjection05 END OR + gl.InitialProjection06 != CASE WHEN @MonthsLoaded < 6 THEN ben.InitialProjection06 ELSE gl.InitialProjection06 END OR + gl.InitialProjection07 != CASE WHEN @MonthsLoaded < 7 THEN ben.InitialProjection07 ELSE gl.InitialProjection07 END OR + gl.InitialProjection08 != CASE WHEN @MonthsLoaded < 8 THEN ben.InitialProjection08 ELSE gl.InitialProjection08 END OR + gl.InitialProjection09 != CASE WHEN @MonthsLoaded < 9 THEN ben.InitialProjection09 ELSE gl.InitialProjection09 END OR + gl.InitialProjection10 != CASE WHEN @MonthsLoaded < 10 THEN ben.InitialProjection10 ELSE gl.InitialProjection10 END OR + gl.InitialProjection11 != CASE WHEN @MonthsLoaded < 11 THEN ben.InitialProjection11 ELSE gl.InitialProjection11 END OR + gl.InitialProjection12 != CASE WHEN @MonthsLoaded < 12 THEN ben.InitialProjection12 ELSE gl.InitialProjection12 END) +GO + + +--------------------------------------------- + +-- fp.procCopyGlobalSpreadsFromOB +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2019-02-21 NL B-22129 Created +** 1 2019-02-21 NL B-22129 renamed GlobalSpread table +*************************************************************/ +CREATE PROCEDURE [fp].[procCopyGlobalSpreadsFromOB] + @BudgetConfigID SMALLINT +WITH RECOMPILE +AS +BEGIN + + IF object_id('tempdb..#OBGlobalSpreads') IS NOT NULL + BEGIN + DROP TABLE #OBGlobalSpreads + END + + CREATE TABLE #OBGlobalSpreads ([sortorder] [int] IDENTITY(3,1) NOT NULL, [Name] nvarchar(4000), Month01 DECIMAL(19,4), Month02 DECIMAL(19,4), Month03 DECIMAL(19,4), Month04 DECIMAL(19,4), Month05 DECIMAL(19,4), Month06 DECIMAL(19,4), + Month07 DECIMAL(19,4), Month08 DECIMAL(19,4), Month09 DECIMAL(19,4), Month10 DECIMAL(19,4), Month11 DECIMAL(19,4), Month12 DECIMAL(19,4), Total DECIMAL(19,4)) + + INSERT INTO #OBGlobalSpreads([Name], [Month01], [Month02], [Month03], [Month04], [Month05], [Month06], [Month07], [Month08], [Month09], [Month10], [Month11], [Month12], [Total]) + SELECT [Name], [Month01], [Month02], [Month03], [Month04], [Month05], [Month06], [Month07], [Month08], [Month09], [Month10], [Month11], [Month12], + ([Month01] + [Month02] + [Month03] + [Month04] + [Month05] + [Month06] + [Month07] + [Month08] + [Month09] + [Month10] + [Month11] + [Month12]) AS Total + FROM [clientob].[FactGlobalSpreads] + WHERE IsDeleted = 0 AND NOT (month01 = 0 and Month02 = 0 and Month03 = 0 and Month04 = 0 and Month05 = 0 and Month06 = 0 and Month07 = 0 and Month08 = 0 and Month09 = 0 and Month10 = 0 and Month11 = 0 and Month12 = 0) + ORDER BY SpreadID + + INSERT INTO [fp].[GlobalSpread]([BudgetConfigID], [SpreadName], [SortOrder], [SpreadPercentage01], [SpreadPercentage02], [SpreadPercentage03], [SpreadPercentage04], [SpreadPercentage05], [SpreadPercentage06], [SpreadPercentage07], [SpreadPercentage08], [SpreadPercentage09], [SpreadPercentage10], [SpreadPercentage11], [SpreadPercentage12], [TotalSpreadValue]) + SELECT @BudgetConfigID, [Name], [sortorder], Month01/Total, Month02/Total, Month03/Total, Month04/Total, Month05/Total, Month06/Total, Month07/Total, Month08/Total, Month09/Total, Month10/Total, Month11/Total, Month12/Total, Total + FROM #OBGlobalSpreads + +END +GO + + +--------------------------------------------- + +-- fp.procCreateGeneralLedgerSnapshot +CREATE PROCEDURE [fp].[procCreateGeneralLedgerSnapshot] + @BudgetConfigID INT, + @SnapshotID INT +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 07-18-2024 MY JAZZ-XXXXX Initial Creation + *************************************************************/ + + INSERT INTO fp.GeneralLedgerSnapshot ([GeneralLedgerID], [SnapshotID], + [BudgetConfigID], + [EntityGroupConfigID], + [EntityID], + [DepartmentID], + [AccountID], + [FinancialReportingID], + [VariabilityID], + [APEModelSectionID], + [AddDate], + [IsNew], + [FlexingTypeID], + [ChangeHistoryGroupingGUID], + [BudgetLockType], + [BudgetLockFlag], + [TargetLockType], + [TargetLockFlag], + [ProjectionLockType], + [ProjectionLockFlag], + [SampledBudget01], + [SampledBudget02], + [SampledBudget03], + [SampledBudget04], + [SampledBudget05], + [SampledBudget06], + [SampledBudget07], + [SampledBudget08], + [SampledBudget09], + [SampledBudget10], + [SampledBudget11], + [SampledBudget12], + [SampledProjection01], + [SampledProjection02], + [SampledProjection03], + [SampledProjection04], + [SampledProjection05], + [SampledProjection06], + [SampledProjection07], + [SampledProjection08], + [SampledProjection09], + [SampledProjection10], + [SampledProjection11], + [SampledProjection12], + [InitialBudget01], + [InitialBudget02], + [InitialBudget03], + [InitialBudget04], + [InitialBudget05], + [InitialBudget06], + [InitialBudget07], + [InitialBudget08], + [InitialBudget09], + [InitialBudget10], + [InitialBudget11], + [InitialBudget12], + [InitialProjection01], + [InitialProjection02], + [InitialProjection03], + [InitialProjection04], + [InitialProjection05], + [InitialProjection06], + [InitialProjection07], + [InitialProjection08], + [InitialProjection09], + [InitialProjection10], + [InitialProjection11], + [InitialProjection12], + [TargetAdjusted01], + [TargetAdjusted02], + [TargetAdjusted03], + [TargetAdjusted04], + [TargetAdjusted05], + [TargetAdjusted06], + [TargetAdjusted07], + [TargetAdjusted08], + [TargetAdjusted09], + [TargetAdjusted10], + [TargetAdjusted11], + [TargetAdjusted12], + [BudgetAdjusted01], + [BudgetAdjusted02], + [BudgetAdjusted03], + [BudgetAdjusted04], + [BudgetAdjusted05], + [BudgetAdjusted06], + [BudgetAdjusted07], + [BudgetAdjusted08], + [BudgetAdjusted09], + [BudgetAdjusted10], + [BudgetAdjusted11], + [BudgetAdjusted12], + [ProjectionAdjusted01], + [ProjectionAdjusted02], + [ProjectionAdjusted03], + [ProjectionAdjusted04], + [ProjectionAdjusted05], + [ProjectionAdjusted06], + [ProjectionAdjusted07], + [ProjectionAdjusted08], + [ProjectionAdjusted09], + [ProjectionAdjusted10], + [ProjectionAdjusted11], + [ProjectionAdjusted12], + [InitialBudgetDollarsPerUOS01], + [InitialBudgetDollarsPerUOS02], + [InitialBudgetDollarsPerUOS03], + [InitialBudgetDollarsPerUOS04], + [InitialBudgetDollarsPerUOS05], + [InitialBudgetDollarsPerUOS06], + [InitialBudgetDollarsPerUOS07], + [InitialBudgetDollarsPerUOS08], + [InitialBudgetDollarsPerUOS09], + [InitialBudgetDollarsPerUOS10], + [InitialBudgetDollarsPerUOS11], + [InitialBudgetDollarsPerUOS12], + [InitialProjectionDollarsPerUOS01], + [InitialProjectionDollarsPerUOS02], + [InitialProjectionDollarsPerUOS03], + [InitialProjectionDollarsPerUOS04], + [InitialProjectionDollarsPerUOS05], + [InitialProjectionDollarsPerUOS06], + [InitialProjectionDollarsPerUOS07], + [InitialProjectionDollarsPerUOS08], + [InitialProjectionDollarsPerUOS09], + [InitialProjectionDollarsPerUOS10], + [InitialProjectionDollarsPerUOS11], + [InitialProjectionDollarsPerUOS12], + [TargetDollarsPerUOSAdjusted01], + [TargetDollarsPerUOSAdjusted02], + [TargetDollarsPerUOSAdjusted03], + [TargetDollarsPerUOSAdjusted04], + [TargetDollarsPerUOSAdjusted05], + [TargetDollarsPerUOSAdjusted06], + [TargetDollarsPerUOSAdjusted07], + [TargetDollarsPerUOSAdjusted08], + [TargetDollarsPerUOSAdjusted09], + [TargetDollarsPerUOSAdjusted10], + [TargetDollarsPerUOSAdjusted11], + [TargetDollarsPerUOSAdjusted12], + [BudgetDollarsPerUOSAdjusted01], + [BudgetDollarsPerUOSAdjusted02], + [BudgetDollarsPerUOSAdjusted03], + [BudgetDollarsPerUOSAdjusted04], + [BudgetDollarsPerUOSAdjusted05], + [BudgetDollarsPerUOSAdjusted06], + [BudgetDollarsPerUOSAdjusted07], + [BudgetDollarsPerUOSAdjusted08], + [BudgetDollarsPerUOSAdjusted09], + [BudgetDollarsPerUOSAdjusted10], + [BudgetDollarsPerUOSAdjusted11], + [BudgetDollarsPerUOSAdjusted12], + [ProjectionDollarsPerUOSAdjusted01], + [ProjectionDollarsPerUOSAdjusted02], + [ProjectionDollarsPerUOSAdjusted03], + [ProjectionDollarsPerUOSAdjusted04], + [ProjectionDollarsPerUOSAdjusted05], + [ProjectionDollarsPerUOSAdjusted06], + [ProjectionDollarsPerUOSAdjusted07], + [ProjectionDollarsPerUOSAdjusted08], + [ProjectionDollarsPerUOSAdjusted09], + [ProjectionDollarsPerUOSAdjusted10], + [ProjectionDollarsPerUOSAdjusted11], + [ProjectionDollarsPerUOSAdjusted12], + [InitialBudgetPercentOfCharge01], + [InitialBudgetPercentOfCharge02], + [InitialBudgetPercentOfCharge03], + [InitialBudgetPercentOfCharge04], + [InitialBudgetPercentOfCharge05], + [InitialBudgetPercentOfCharge06], + [InitialBudgetPercentOfCharge07], + [InitialBudgetPercentOfCharge08], + [InitialBudgetPercentOfCharge09], + [InitialBudgetPercentOfCharge10], + [InitialBudgetPercentOfCharge11], + [InitialBudgetPercentOfCharge12], + [InitialProjectionPercentOfCharge01], + [InitialProjectionPercentOfCharge02], + [InitialProjectionPercentOfCharge03], + [InitialProjectionPercentOfCharge04], + [InitialProjectionPercentOfCharge05], + [InitialProjectionPercentOfCharge06], + [InitialProjectionPercentOfCharge07], + [InitialProjectionPercentOfCharge08], + [InitialProjectionPercentOfCharge09], + [InitialProjectionPercentOfCharge10], + [InitialProjectionPercentOfCharge11], + [InitialProjectionPercentOfCharge12], + [TargetPercentOfChargeAdjusted01], + [TargetPercentOfChargeAdjusted02], + [TargetPercentOfChargeAdjusted03], + [TargetPercentOfChargeAdjusted04], + [TargetPercentOfChargeAdjusted05], + [TargetPercentOfChargeAdjusted06], + [TargetPercentOfChargeAdjusted07], + [TargetPercentOfChargeAdjusted08], + [TargetPercentOfChargeAdjusted09], + [TargetPercentOfChargeAdjusted10], + [TargetPercentOfChargeAdjusted11], + [TargetPercentOfChargeAdjusted12], + [BudgetPercentOfChargeAdjusted01], + [BudgetPercentOfChargeAdjusted02], + [BudgetPercentOfChargeAdjusted03], + [BudgetPercentOfChargeAdjusted04], + [BudgetPercentOfChargeAdjusted05], + [BudgetPercentOfChargeAdjusted06], + [BudgetPercentOfChargeAdjusted07], + [BudgetPercentOfChargeAdjusted08], + [BudgetPercentOfChargeAdjusted09], + [BudgetPercentOfChargeAdjusted10], + [BudgetPercentOfChargeAdjusted11], + [BudgetPercentOfChargeAdjusted12], + [ProjectionPercentOfChargeAdjusted01], + [ProjectionPercentOfChargeAdjusted02], + [ProjectionPercentOfChargeAdjusted03], + [ProjectionPercentOfChargeAdjusted04], + [ProjectionPercentOfChargeAdjusted05], + [ProjectionPercentOfChargeAdjusted06], + [ProjectionPercentOfChargeAdjusted07], + [ProjectionPercentOfChargeAdjusted08], + [ProjectionPercentOfChargeAdjusted09], + [ProjectionPercentOfChargeAdjusted10], + [ProjectionPercentOfChargeAdjusted11], + [ProjectionPercentOfChargeAdjusted12], + [TargetPercentAdjustmentFactor01], + [TargetPercentAdjustmentFactor02], + [TargetPercentAdjustmentFactor03], + [TargetPercentAdjustmentFactor04], + [TargetPercentAdjustmentFactor05], + [TargetPercentAdjustmentFactor06], + [TargetPercentAdjustmentFactor07], + [TargetPercentAdjustmentFactor08], + [TargetPercentAdjustmentFactor09], + [TargetPercentAdjustmentFactor10], + [TargetPercentAdjustmentFactor11], + [TargetPercentAdjustmentFactor12], + [BudgetPercentAdjustmentFactor01], + [BudgetPercentAdjustmentFactor02], + [BudgetPercentAdjustmentFactor03], + [BudgetPercentAdjustmentFactor04], + [BudgetPercentAdjustmentFactor05], + [BudgetPercentAdjustmentFactor06], + [BudgetPercentAdjustmentFactor07], + [BudgetPercentAdjustmentFactor08], + [BudgetPercentAdjustmentFactor09], + [BudgetPercentAdjustmentFactor10], + [BudgetPercentAdjustmentFactor11], + [BudgetPercentAdjustmentFactor12], + [ProjectionPercentAdjustmentFactor01], + [ProjectionPercentAdjustmentFactor02], + [ProjectionPercentAdjustmentFactor03], + [ProjectionPercentAdjustmentFactor04], + [ProjectionPercentAdjustmentFactor05], + [ProjectionPercentAdjustmentFactor06], + [ProjectionPercentAdjustmentFactor07], + [ProjectionPercentAdjustmentFactor08], + [ProjectionPercentAdjustmentFactor09], + [ProjectionPercentAdjustmentFactor10], + [ProjectionPercentAdjustmentFactor11], + [ProjectionPercentAdjustmentFactor12]) + SELECT + [GeneralLedgerID], + @SnapshotID, + [BudgetConfigID], + [EntityGroupConfigID], + [EntityID], + [DepartmentID], + [AccountID], + [FinancialReportingID], + [VariabilityID], + [APEModelSectionID], + [AddDate], + [IsNew], + [FlexingTypeID], + [ChangeHistoryGroupingGUID], + + [BudgetLockType], + [BudgetLockFlag], + [TargetLockType], + [TargetLockFlag], + [ProjectionLockType], + [ProjectionLockFlag], + + [SampledBudget01], + [SampledBudget02], + [SampledBudget03], + [SampledBudget04], + [SampledBudget05], + [SampledBudget06], + [SampledBudget07], + [SampledBudget08], + [SampledBudget09], + [SampledBudget10], + [SampledBudget11], + [SampledBudget12], + [SampledProjection01], + [SampledProjection02], + [SampledProjection03], + [SampledProjection04], + [SampledProjection05], + [SampledProjection06], + [SampledProjection07], + [SampledProjection08], + [SampledProjection09], + [SampledProjection10], + [SampledProjection11], + [SampledProjection12], + [InitialBudget01], + [InitialBudget02], + [InitialBudget03], + [InitialBudget04], + [InitialBudget05], + [InitialBudget06], + [InitialBudget07], + [InitialBudget08], + [InitialBudget09], + [InitialBudget10], + [InitialBudget11], + [InitialBudget12], + [InitialProjection01], + [InitialProjection02], + [InitialProjection03], + [InitialProjection04], + [InitialProjection05], + [InitialProjection06], + [InitialProjection07], + [InitialProjection08], + [InitialProjection09], + [InitialProjection10], + [InitialProjection11], + [InitialProjection12], + [TargetAdjusted01], + [TargetAdjusted02], + [TargetAdjusted03], + [TargetAdjusted04], + [TargetAdjusted05], + [TargetAdjusted06], + [TargetAdjusted07], + [TargetAdjusted08], + [TargetAdjusted09], + [TargetAdjusted10], + [TargetAdjusted11], + [TargetAdjusted12], + [BudgetAdjusted01], + [BudgetAdjusted02], + [BudgetAdjusted03], + [BudgetAdjusted04], + [BudgetAdjusted05], + [BudgetAdjusted06], + [BudgetAdjusted07], + [BudgetAdjusted08], + [BudgetAdjusted09], + [BudgetAdjusted10], + [BudgetAdjusted11], + [BudgetAdjusted12], + [ProjectionAdjusted01], + [ProjectionAdjusted02], + [ProjectionAdjusted03], + [ProjectionAdjusted04], + [ProjectionAdjusted05], + [ProjectionAdjusted06], + [ProjectionAdjusted07], + [ProjectionAdjusted08], + [ProjectionAdjusted09], + [ProjectionAdjusted10], + [ProjectionAdjusted11], + [ProjectionAdjusted12], + + [InitialBudgetDollarsPerUOS01], + [InitialBudgetDollarsPerUOS02], + [InitialBudgetDollarsPerUOS03], + [InitialBudgetDollarsPerUOS04], + [InitialBudgetDollarsPerUOS05], + [InitialBudgetDollarsPerUOS06], + [InitialBudgetDollarsPerUOS07], + [InitialBudgetDollarsPerUOS08], + [InitialBudgetDollarsPerUOS09], + [InitialBudgetDollarsPerUOS10], + [InitialBudgetDollarsPerUOS11], + [InitialBudgetDollarsPerUOS12], + [InitialProjectionDollarsPerUOS01], + [InitialProjectionDollarsPerUOS02], + [InitialProjectionDollarsPerUOS03], + [InitialProjectionDollarsPerUOS04], + [InitialProjectionDollarsPerUOS05], + [InitialProjectionDollarsPerUOS06], + [InitialProjectionDollarsPerUOS07], + [InitialProjectionDollarsPerUOS08], + [InitialProjectionDollarsPerUOS09], + [InitialProjectionDollarsPerUOS10], + [InitialProjectionDollarsPerUOS11], + [InitialProjectionDollarsPerUOS12], + [TargetDollarsPerUOSAdjusted01], + [TargetDollarsPerUOSAdjusted02], + [TargetDollarsPerUOSAdjusted03], + [TargetDollarsPerUOSAdjusted04], + [TargetDollarsPerUOSAdjusted05], + [TargetDollarsPerUOSAdjusted06], + [TargetDollarsPerUOSAdjusted07], + [TargetDollarsPerUOSAdjusted08], + [TargetDollarsPerUOSAdjusted09], + [TargetDollarsPerUOSAdjusted10], + [TargetDollarsPerUOSAdjusted11], + [TargetDollarsPerUOSAdjusted12], + [BudgetDollarsPerUOSAdjusted01], + [BudgetDollarsPerUOSAdjusted02], + [BudgetDollarsPerUOSAdjusted03], + [BudgetDollarsPerUOSAdjusted04], + [BudgetDollarsPerUOSAdjusted05], + [BudgetDollarsPerUOSAdjusted06], + [BudgetDollarsPerUOSAdjusted07], + [BudgetDollarsPerUOSAdjusted08], + [BudgetDollarsPerUOSAdjusted09], + [BudgetDollarsPerUOSAdjusted10], + [BudgetDollarsPerUOSAdjusted11], + [BudgetDollarsPerUOSAdjusted12], + [ProjectionDollarsPerUOSAdjusted01], + [ProjectionDollarsPerUOSAdjusted02], + [ProjectionDollarsPerUOSAdjusted03], + [ProjectionDollarsPerUOSAdjusted04], + [ProjectionDollarsPerUOSAdjusted05], + [ProjectionDollarsPerUOSAdjusted06], + [ProjectionDollarsPerUOSAdjusted07], + [ProjectionDollarsPerUOSAdjusted08], + [ProjectionDollarsPerUOSAdjusted09], + [ProjectionDollarsPerUOSAdjusted10], + [ProjectionDollarsPerUOSAdjusted11], + [ProjectionDollarsPerUOSAdjusted12], + + [InitialBudgetPercentOfCharge01], + [InitialBudgetPercentOfCharge02], + [InitialBudgetPercentOfCharge03], + [InitialBudgetPercentOfCharge04], + [InitialBudgetPercentOfCharge05], + [InitialBudgetPercentOfCharge06], + [InitialBudgetPercentOfCharge07], + [InitialBudgetPercentOfCharge08], + [InitialBudgetPercentOfCharge09], + [InitialBudgetPercentOfCharge10], + [InitialBudgetPercentOfCharge11], + [InitialBudgetPercentOfCharge12], + [InitialProjectionPercentOfCharge01], + [InitialProjectionPercentOfCharge02], + [InitialProjectionPercentOfCharge03], + [InitialProjectionPercentOfCharge04], + [InitialProjectionPercentOfCharge05], + [InitialProjectionPercentOfCharge06], + [InitialProjectionPercentOfCharge07], + [InitialProjectionPercentOfCharge08], + [InitialProjectionPercentOfCharge09], + [InitialProjectionPercentOfCharge10], + [InitialProjectionPercentOfCharge11], + [InitialProjectionPercentOfCharge12], + [TargetPercentOfChargeAdjusted01], + [TargetPercentOfChargeAdjusted02], + [TargetPercentOfChargeAdjusted03], + [TargetPercentOfChargeAdjusted04], + [TargetPercentOfChargeAdjusted05], + [TargetPercentOfChargeAdjusted06], + [TargetPercentOfChargeAdjusted07], + [TargetPercentOfChargeAdjusted08], + [TargetPercentOfChargeAdjusted09], + [TargetPercentOfChargeAdjusted10], + [TargetPercentOfChargeAdjusted11], + [TargetPercentOfChargeAdjusted12], + [BudgetPercentOfChargeAdjusted01], + [BudgetPercentOfChargeAdjusted02], + [BudgetPercentOfChargeAdjusted03], + [BudgetPercentOfChargeAdjusted04], + [BudgetPercentOfChargeAdjusted05], + [BudgetPercentOfChargeAdjusted06], + [BudgetPercentOfChargeAdjusted07], + [BudgetPercentOfChargeAdjusted08], + [BudgetPercentOfChargeAdjusted09], + [BudgetPercentOfChargeAdjusted10], + [BudgetPercentOfChargeAdjusted11], + [BudgetPercentOfChargeAdjusted12], + [ProjectionPercentOfChargeAdjusted01], + [ProjectionPercentOfChargeAdjusted02], + [ProjectionPercentOfChargeAdjusted03], + [ProjectionPercentOfChargeAdjusted04], + [ProjectionPercentOfChargeAdjusted05], + [ProjectionPercentOfChargeAdjusted06], + [ProjectionPercentOfChargeAdjusted07], + [ProjectionPercentOfChargeAdjusted08], + [ProjectionPercentOfChargeAdjusted09], + [ProjectionPercentOfChargeAdjusted10], + [ProjectionPercentOfChargeAdjusted11], + [ProjectionPercentOfChargeAdjusted12], + + [TargetPercentAdjustmentFactor01], + [TargetPercentAdjustmentFactor02], + [TargetPercentAdjustmentFactor03], + [TargetPercentAdjustmentFactor04], + [TargetPercentAdjustmentFactor05], + [TargetPercentAdjustmentFactor06], + [TargetPercentAdjustmentFactor07], + [TargetPercentAdjustmentFactor08], + [TargetPercentAdjustmentFactor09], + [TargetPercentAdjustmentFactor10], + [TargetPercentAdjustmentFactor11], + [TargetPercentAdjustmentFactor12], + [BudgetPercentAdjustmentFactor01], + [BudgetPercentAdjustmentFactor02], + [BudgetPercentAdjustmentFactor03], + [BudgetPercentAdjustmentFactor04], + [BudgetPercentAdjustmentFactor05], + [BudgetPercentAdjustmentFactor06], + [BudgetPercentAdjustmentFactor07], + [BudgetPercentAdjustmentFactor08], + [BudgetPercentAdjustmentFactor09], + [BudgetPercentAdjustmentFactor10], + [BudgetPercentAdjustmentFactor11], + [BudgetPercentAdjustmentFactor12], + [ProjectionPercentAdjustmentFactor01], + [ProjectionPercentAdjustmentFactor02], + [ProjectionPercentAdjustmentFactor03], + [ProjectionPercentAdjustmentFactor04], + [ProjectionPercentAdjustmentFactor05], + [ProjectionPercentAdjustmentFactor06], + [ProjectionPercentAdjustmentFactor07], + [ProjectionPercentAdjustmentFactor08], + [ProjectionPercentAdjustmentFactor09], + [ProjectionPercentAdjustmentFactor10], + [ProjectionPercentAdjustmentFactor11], + [ProjectionPercentAdjustmentFactor12] + FROM [fp].[GeneralLedger] + WHERE BudgetConfigID = @BudgetConfigID + + -- Need to update the number of adjustments in case when this processed vs when it was originally kicked off is different. + DECLARE @NumberOfAdjustments INT; + SET @NumberOfAdjustments = ( + SELECT COUNT(*) + FROM [fp].[viewUserViewGeneralLedgerAdjustments] gla + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = gla.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + ) + + -- Update the Date processed date + UPDATE fp.BudgetSnapshot + SET DateProcessedUTC = GETUTCDATE(), + AdjustmentsStampedOff = @NumberOfAdjustments + WHERE SnapshotID = @SnapshotID + +END +GO + + +--------------------------------------------- + +-- fp.procCrosswalkChargeToGeneralLedger +CREATE PROCEDURE [fp].[procCrosswalkChargeToGeneralLedger] + @EntityGroupConfigID INT, + @MonthsLoaded INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 + WITH RECOMPILE + AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author BLI Description + ** 1 2021-03-10 BK JAZZ-16331 Create proc + ** 2 2021-10-05 MD JAZZ-26615 Add OPTION RECOMPILE + ** 3 2023-04-06 MD JAZZ-52587 Update for new data structure + ** 4 2023-04-21 BK JAZZ------ Performance improvement + ** 5 2023-08-04 BW JAZZ-58151 Update for new GL data structure + ** 6 2024-09-11 MY JAZZ-75442 GL Data is locked with locktype 3 with no crosswalk configured for chosen entity group + *************************************************************/ + BEGIN + + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#CrosswalkRecords') IS NOT NULL DROP TABLE #CrosswalkRecords + + CREATE TABLE #CrosswalkRecords(DepartmentID INT, AccountID INT, + TargetAdjusted01 DECIMAL(19,8), TargetAdjusted02 DECIMAL(19,8), TargetAdjusted03 DECIMAL(19,8), + TargetAdjusted04 DECIMAL(19,8), TargetAdjusted05 DECIMAL(19,8), TargetAdjusted06 DECIMAL(19,8), + TargetAdjusted07 DECIMAL(19,8), TargetAdjusted08 DECIMAL(19,8), TargetAdjusted09 DECIMAL(19,8), + TargetAdjusted10 DECIMAL(19,8), TargetAdjusted11 DECIMAL(19,8), TargetAdjusted12 DECIMAL(19,8), + BudgetAdjusted01 DECIMAL(19,8), BudgetAdjusted02 DECIMAL(19,8), BudgetAdjusted03 DECIMAL(19,8), + BudgetAdjusted04 DECIMAL(19,8), BudgetAdjusted05 DECIMAL(19,8), BudgetAdjusted06 DECIMAL(19,8), + BudgetAdjusted07 DECIMAL(19,8), BudgetAdjusted08 DECIMAL(19,8), BudgetAdjusted09 DECIMAL(19,8), + BudgetAdjusted10 DECIMAL(19,8), BudgetAdjusted11 DECIMAL(19,8), BudgetAdjusted12 DECIMAL(19,8), + ProjectionAdjusted01 DECIMAL(19,8), ProjectionAdjusted02 DECIMAL(19,8), ProjectionAdjusted03 DECIMAL(19,8), + ProjectionAdjusted04 DECIMAL(19,8), ProjectionAdjusted05 DECIMAL(19,8), ProjectionAdjusted06 DECIMAL(19,8), + ProjectionAdjusted07 DECIMAL(19,8), ProjectionAdjusted08 DECIMAL(19,8), ProjectionAdjusted09 DECIMAL(19,8), + ProjectionAdjusted10 DECIMAL(19,8), ProjectionAdjusted11 DECIMAL(19,8), ProjectionAdjusted12 DECIMAL(19,8) + ) + + IF (SELECT COUNT(*) FROM @SourceDimensionality) = 0 + BEGIN + INSERT INTO #CrosswalkRecords (DepartmentID, AccountID, + TargetAdjusted01, TargetAdjusted02, TargetAdjusted03, TargetAdjusted04, TargetAdjusted05, TargetAdjusted06, + TargetAdjusted07, TargetAdjusted08, TargetAdjusted09, TargetAdjusted10, TargetAdjusted11, TargetAdjusted12, + BudgetAdjusted01, BudgetAdjusted02, BudgetAdjusted03, BudgetAdjusted04, BudgetAdjusted05, BudgetAdjusted06, + BudgetAdjusted07, BudgetAdjusted08, BudgetAdjusted09, BudgetAdjusted10, BudgetAdjusted11, BudgetAdjusted12, + ProjectionAdjusted01, ProjectionAdjusted02, ProjectionAdjusted03, ProjectionAdjusted04, ProjectionAdjusted05, ProjectionAdjusted06, + ProjectionAdjusted07, ProjectionAdjusted08, ProjectionAdjusted09, ProjectionAdjusted10, ProjectionAdjusted11, ProjectionAdjusted12) + SELECT DISTINCT config.DepartmentID, config.AccountID, + SUM(TargetDollarsAdjusted01), SUM(TargetDollarsAdjusted02), SUM(TargetDollarsAdjusted03), + SUM(TargetDollarsAdjusted04), SUM(TargetDollarsAdjusted05), SUM(TargetDollarsAdjusted06), + SUM(TargetDollarsAdjusted07), SUM(TargetDollarsAdjusted08), SUM(TargetDollarsAdjusted09), + SUM(TargetDollarsAdjusted10), SUM(TargetDollarsAdjusted11), SUM(TargetDollarsAdjusted12), + SUM(BudgetDollarsAdjusted01), SUM(BudgetDollarsAdjusted02), SUM(BudgetDollarsAdjusted03), + SUM(BudgetDollarsAdjusted04), SUM(BudgetDollarsAdjusted05), SUM(BudgetDollarsAdjusted06), + SUM(BudgetDollarsAdjusted07), SUM(BudgetDollarsAdjusted08), SUM(BudgetDollarsAdjusted09), + SUM(BudgetDollarsAdjusted10), SUM(BudgetDollarsAdjusted11), SUM(BudgetDollarsAdjusted12), + SUM(ProjectionDollarsAdjusted01), SUM(ProjectionDollarsAdjusted02), SUM(ProjectionDollarsAdjusted03), + SUM(ProjectionDollarsAdjusted04), SUM(ProjectionDollarsAdjusted05), SUM(ProjectionDollarsAdjusted06), + SUM(ProjectionDollarsAdjusted07), SUM(ProjectionDollarsAdjusted08), SUM(ProjectionDollarsAdjusted09), + SUM(ProjectionDollarsAdjusted10), SUM(ProjectionDollarsAdjusted11), SUM(ProjectionDollarsAdjusted12) + FROM [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] config (readuncommitted) + INNER JOIN fp.ChargeVolume cv on config.DepartmentID = cv.DepartmentID + AND config.ChargeCodeID = cv.ChargeCodeID + AND config.PatientClassID = cv.PatientClassID + AND config.EntityGroupConfigID = cv.EntityGroupConfigID + WHERE config.EntityGroupConfigID = @EntityGroupConfigID + AND config.IsRecordDeleted = 0 + AND config.AccountID > 0 + GROUP BY config.DepartmentID, config.AccountID + END + ELSE + BEGIN + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + INSERT INTO #CrosswalkRecords (DepartmentID, AccountID, + TargetAdjusted01, TargetAdjusted02, TargetAdjusted03, TargetAdjusted04, TargetAdjusted05, TargetAdjusted06, + TargetAdjusted07, TargetAdjusted08, TargetAdjusted09, TargetAdjusted10, TargetAdjusted11, TargetAdjusted12, + BudgetAdjusted01, BudgetAdjusted02, BudgetAdjusted03, BudgetAdjusted04, BudgetAdjusted05, BudgetAdjusted06, + BudgetAdjusted07, BudgetAdjusted08, BudgetAdjusted09, BudgetAdjusted10, BudgetAdjusted11, BudgetAdjusted12, + ProjectionAdjusted01, ProjectionAdjusted02, ProjectionAdjusted03, ProjectionAdjusted04, ProjectionAdjusted05, ProjectionAdjusted06, + ProjectionAdjusted07, ProjectionAdjusted08, ProjectionAdjusted09, ProjectionAdjusted10, ProjectionAdjusted11, ProjectionAdjusted12) + SELECT DISTINCT config.DepartmentID, config.AccountID, + SUM(TargetDollarsAdjusted01), SUM(TargetDollarsAdjusted02), SUM(TargetDollarsAdjusted03), + SUM(TargetDollarsAdjusted04), SUM(TargetDollarsAdjusted05), SUM(TargetDollarsAdjusted06), + SUM(TargetDollarsAdjusted07), SUM(TargetDollarsAdjusted08), SUM(TargetDollarsAdjusted09), + SUM(TargetDollarsAdjusted10), SUM(TargetDollarsAdjusted11), SUM(TargetDollarsAdjusted12), + SUM(BudgetDollarsAdjusted01), SUM(BudgetDollarsAdjusted02), SUM(BudgetDollarsAdjusted03), + SUM(BudgetDollarsAdjusted04), SUM(BudgetDollarsAdjusted05), SUM(BudgetDollarsAdjusted06), + SUM(BudgetDollarsAdjusted07), SUM(BudgetDollarsAdjusted08), SUM(BudgetDollarsAdjusted09), + SUM(BudgetDollarsAdjusted10), SUM(BudgetDollarsAdjusted11), SUM(BudgetDollarsAdjusted12), + SUM(ProjectionDollarsAdjusted01), SUM(ProjectionDollarsAdjusted02), SUM(ProjectionDollarsAdjusted03), + SUM(ProjectionDollarsAdjusted04), SUM(ProjectionDollarsAdjusted05), SUM(ProjectionDollarsAdjusted06), + SUM(ProjectionDollarsAdjusted07), SUM(ProjectionDollarsAdjusted08), SUM(ProjectionDollarsAdjusted09), + SUM(ProjectionDollarsAdjusted10), SUM(ProjectionDollarsAdjusted11), SUM(ProjectionDollarsAdjusted12) + FROM [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] config (readuncommitted) + INNER JOIN #FilterByDepartment ft ON config.DepartmentID = ft.DepartmentID + INNER JOIN fp.ChargeVolume cv on config.DepartmentID = cv.DepartmentID + AND config.ChargeCodeID = cv.ChargeCodeID + AND config.PatientClassID = cv.PatientClassID + AND config.EntityGroupConfigID = cv.EntityGroupConfigID + WHERE config.EntityGroupConfigID = @EntityGroupConfigID + AND config.IsRecordDeleted = 0 + AND config.AccountID > 0 + GROUP BY config.DepartmentID, config.AccountID + + DROP TABLE #FilterByDepartment + + END + + + IF (@IsDebug = 0) + BEGIN + UPDATE gl + SET + TargetAdjusted01 = xwalk.TargetAdjusted01 + ,TargetAdjusted02 = xwalk.TargetAdjusted02 + ,TargetAdjusted03 = xwalk.TargetAdjusted03 + ,TargetAdjusted04 = xwalk.TargetAdjusted04 + ,TargetAdjusted05 = xwalk.TargetAdjusted05 + ,TargetAdjusted06 = xwalk.TargetAdjusted06 + ,TargetAdjusted07 = xwalk.TargetAdjusted07 + ,TargetAdjusted08 = xwalk.TargetAdjusted08 + ,TargetAdjusted09 = xwalk.TargetAdjusted09 + ,TargetAdjusted10 = xwalk.TargetAdjusted10 + ,TargetAdjusted11 = xwalk.TargetAdjusted11 + ,TargetAdjusted12 = xwalk.TargetAdjusted12 + ,TargetLockType = 3 + ,TargetLockFlag = 1 + ,BudgetAdjusted01 = xwalk.BudgetAdjusted01 + ,BudgetAdjusted02 = xwalk.BudgetAdjusted02 + ,BudgetAdjusted03 = xwalk.BudgetAdjusted03 + ,BudgetAdjusted04 = xwalk.BudgetAdjusted04 + ,BudgetAdjusted05 = xwalk.BudgetAdjusted05 + ,BudgetAdjusted06 = xwalk.BudgetAdjusted06 + ,BudgetAdjusted07 = xwalk.BudgetAdjusted07 + ,BudgetAdjusted08 = xwalk.BudgetAdjusted08 + ,BudgetAdjusted09 = xwalk.BudgetAdjusted09 + ,BudgetAdjusted10 = xwalk.BudgetAdjusted10 + ,BudgetAdjusted11 = xwalk.BudgetAdjusted11 + ,BudgetAdjusted12 = xwalk.BudgetAdjusted12 + ,BudgetLockType = 3 + ,BudgetLockFlag = 1 + FROM fp.GeneralLedger gl + INNER JOIN #CrosswalkRecords xwalk on gl.DepartmentID = xwalk.DepartmentID + AND gl.AccountID = xwalk.AccountID + WHERE + gl.VariabilityID = 2 + AND gl.EntityGroupConfigID = @EntityGroupConfigID + AND ( + gl.TargetAdjusted01 != xwalk.TargetAdjusted01 + OR gl.TargetAdjusted02 != xwalk.TargetAdjusted02 + OR gl.TargetAdjusted03 != xwalk.TargetAdjusted03 + OR gl.TargetAdjusted04 != xwalk.TargetAdjusted04 + OR gl.TargetAdjusted05 != xwalk.TargetAdjusted05 + OR gl.TargetAdjusted06 != xwalk.TargetAdjusted06 + OR gl.TargetAdjusted07 != xwalk.TargetAdjusted07 + OR gl.TargetAdjusted08 != xwalk.TargetAdjusted08 + OR gl.TargetAdjusted09 != xwalk.TargetAdjusted09 + OR gl.TargetAdjusted10 != xwalk.TargetAdjusted10 + OR gl.TargetAdjusted11 != xwalk.TargetAdjusted11 + OR gl.TargetAdjusted12 != xwalk.TargetAdjusted12 + OR gl.TargetLockFlag != 1 + OR gl.BudgetAdjusted01 != xwalk.BudgetAdjusted01 + OR gl.BudgetAdjusted02 != xwalk.BudgetAdjusted02 + OR gl.BudgetAdjusted03 != xwalk.BudgetAdjusted03 + OR gl.BudgetAdjusted04 != xwalk.BudgetAdjusted04 + OR gl.BudgetAdjusted05 != xwalk.BudgetAdjusted05 + OR gl.BudgetAdjusted06 != xwalk.BudgetAdjusted06 + OR gl.BudgetAdjusted07 != xwalk.BudgetAdjusted07 + OR gl.BudgetAdjusted08 != xwalk.BudgetAdjusted08 + OR gl.BudgetAdjusted09 != xwalk.BudgetAdjusted09 + OR gl.BudgetAdjusted10 != xwalk.BudgetAdjusted10 + OR gl.BudgetAdjusted11 != xwalk.BudgetAdjusted11 + OR gl.BudgetAdjusted12 != xwalk.BudgetAdjusted12 + OR gl.BudgetLockFlag != 1 ) + + + UPDATE gl + SET + TargetAdjusted01 = 0 + ,TargetAdjusted02 = 0 + ,TargetAdjusted03 = 0 + ,TargetAdjusted04 = 0 + ,TargetAdjusted05 = 0 + ,TargetAdjusted06 = 0 + ,TargetAdjusted07 = 0 + ,TargetAdjusted08 = 0 + ,TargetAdjusted09 = 0 + ,TargetAdjusted10 = 0 + ,TargetAdjusted11 = 0 + ,TargetAdjusted12 = 0 + ,TargetLockType = 3 + ,TargetLockFlag = 1 + ,BudgetAdjusted01 = 0 + ,BudgetAdjusted02 = 0 + ,BudgetAdjusted03 = 0 + ,BudgetAdjusted04 = 0 + ,BudgetAdjusted05 = 0 + ,BudgetAdjusted06 = 0 + ,BudgetAdjusted07 = 0 + ,BudgetAdjusted08 = 0 + ,BudgetAdjusted09 = 0 + ,BudgetAdjusted10 = 0 + ,BudgetAdjusted11 = 0 + ,BudgetAdjusted12 = 0 + ,BudgetLockType = 3 + ,BudgetLockFlag = 1 + + FROM fp.GeneralLedger gl + INNER JOIN #CrosswalkRecords xwalk on gl.DepartmentID = xwalk.DepartmentID + AND gl.AccountID = xwalk.AccountID + WHERE + gl.VariabilityID = 1 + AND gl.EntityGroupConfigID = @EntityGroupConfigID + AND (gl.TargetAdjusted01 != 0 + OR gl.TargetAdjusted02 != 0 + OR gl.TargetAdjusted03 != 0 + OR gl.TargetAdjusted04 != 0 + OR gl.TargetAdjusted05 != 0 + OR gl.TargetAdjusted06 != 0 + OR gl.TargetAdjusted07 != 0 + OR gl.TargetAdjusted08 != 0 + OR gl.TargetAdjusted09 != 0 + OR gl.TargetAdjusted10 != 0 + OR gl.TargetAdjusted11 != 0 + OR gl.TargetAdjusted12 != 0 + OR gl.TargetLockFlag != 1 + OR gl.BudgetAdjusted01 != 0 + OR gl.BudgetAdjusted02 != 0 + OR gl.BudgetAdjusted03 != 0 + OR gl.BudgetAdjusted04 != 0 + OR gl.BudgetAdjusted05 != 0 + OR gl.BudgetAdjusted06 != 0 + OR gl.BudgetAdjusted07 != 0 + OR gl.BudgetAdjusted08 != 0 + OR gl.BudgetAdjusted09 != 0 + OR gl.BudgetAdjusted10 != 0 + OR gl.BudgetAdjusted11 != 0 + OR gl.BudgetAdjusted12 != 0 + OR gl.BudgetLockFlag != 1 + ) + + UPDATE gl + SET + ProjectionAdjusted01 = CASE WHEN @MonthsLoaded >= 1 THEN gl.ProjectionAdjusted01 ELSE xwalk.ProjectionAdjusted01 END + ,ProjectionAdjusted02 = CASE WHEN @MonthsLoaded >= 2 THEN gl.ProjectionAdjusted02 ELSE xwalk.ProjectionAdjusted02 END + ,ProjectionAdjusted03 = CASE WHEN @MonthsLoaded >= 3 THEN gl.ProjectionAdjusted03 ELSE xwalk.ProjectionAdjusted03 END + ,ProjectionAdjusted04 = CASE WHEN @MonthsLoaded >= 4 THEN gl.ProjectionAdjusted04 ELSE xwalk.ProjectionAdjusted04 END + ,ProjectionAdjusted05 = CASE WHEN @MonthsLoaded >= 5 THEN gl.ProjectionAdjusted05 ELSE xwalk.ProjectionAdjusted05 END + ,ProjectionAdjusted06 = CASE WHEN @MonthsLoaded >= 6 THEN gl.ProjectionAdjusted06 ELSE xwalk.ProjectionAdjusted06 END + ,ProjectionAdjusted07 = CASE WHEN @MonthsLoaded >= 7 THEN gl.ProjectionAdjusted07 ELSE xwalk.ProjectionAdjusted07 END + ,ProjectionAdjusted08 = CASE WHEN @MonthsLoaded >= 8 THEN gl.ProjectionAdjusted08 ELSE xwalk.ProjectionAdjusted08 END + ,ProjectionAdjusted09 = CASE WHEN @MonthsLoaded >= 9 THEN gl.ProjectionAdjusted09 ELSE xwalk.ProjectionAdjusted09 END + ,ProjectionAdjusted10 = CASE WHEN @MonthsLoaded >= 10 THEN gl.ProjectionAdjusted10 ELSE xwalk.ProjectionAdjusted10 END + ,ProjectionAdjusted11 = CASE WHEN @MonthsLoaded >= 11 THEN gl.ProjectionAdjusted11 ELSE xwalk.ProjectionAdjusted11 END + ,ProjectionAdjusted12 = CASE WHEN @MonthsLoaded >= 12 THEN gl.ProjectionAdjusted12 ELSE xwalk.ProjectionAdjusted12 END + ,ProjectionLockType = 3 + ,ProjectionLockFlag = 1 + FROM fp.GeneralLedger gl + INNER JOIN #CrosswalkRecords xwalk on gl.DepartmentID = xwalk.DepartmentID + AND gl.AccountID = xwalk.AccountID + WHERE + gl.VariabilityID = 2 + AND gl.EntityGroupConfigID = @EntityGroupConfigID + AND ( + gl.ProjectionAdjusted01 != CASE WHEN @MonthsLoaded >= 1 THEN gl.ProjectionAdjusted01 ELSE xwalk.ProjectionAdjusted01 END + OR gl.ProjectionAdjusted02 != CASE WHEN @MonthsLoaded >= 2 THEN gl.ProjectionAdjusted02 ELSE xwalk.ProjectionAdjusted02 END + OR gl.ProjectionAdjusted03 != CASE WHEN @MonthsLoaded >= 3 THEN gl.ProjectionAdjusted03 ELSE xwalk.ProjectionAdjusted03 END + OR gl.ProjectionAdjusted04 != CASE WHEN @MonthsLoaded >= 4 THEN gl.ProjectionAdjusted04 ELSE xwalk.ProjectionAdjusted04 END + OR gl.ProjectionAdjusted05 != CASE WHEN @MonthsLoaded >= 5 THEN gl.ProjectionAdjusted05 ELSE xwalk.ProjectionAdjusted05 END + OR gl.ProjectionAdjusted06 != CASE WHEN @MonthsLoaded >= 6 THEN gl.ProjectionAdjusted06 ELSE xwalk.ProjectionAdjusted06 END + OR gl.ProjectionAdjusted07 != CASE WHEN @MonthsLoaded >= 7 THEN gl.ProjectionAdjusted07 ELSE xwalk.ProjectionAdjusted07 END + OR gl.ProjectionAdjusted08 != CASE WHEN @MonthsLoaded >= 8 THEN gl.ProjectionAdjusted08 ELSE xwalk.ProjectionAdjusted08 END + OR gl.ProjectionAdjusted09 != CASE WHEN @MonthsLoaded >= 9 THEN gl.ProjectionAdjusted09 ELSE xwalk.ProjectionAdjusted09 END + OR gl.ProjectionAdjusted10 != CASE WHEN @MonthsLoaded >= 10 THEN gl.ProjectionAdjusted10 ELSE xwalk.ProjectionAdjusted10 END + OR gl.ProjectionAdjusted11 != CASE WHEN @MonthsLoaded >= 11 THEN gl.ProjectionAdjusted11 ELSE xwalk.ProjectionAdjusted11 END + OR gl.ProjectionAdjusted12 != CASE WHEN @MonthsLoaded >= 12 THEN gl.ProjectionAdjusted12 ELSE xwalk.ProjectionAdjusted12 END + OR gl.ProjectionLockFlag != 1 ) + + UPDATE gl + SET + ProjectionAdjusted01 = CASE WHEN @MonthsLoaded >= 1 THEN gl.ProjectionAdjusted01 ELSE 0 END + ,ProjectionAdjusted02 = CASE WHEN @MonthsLoaded >= 2 THEN gl.ProjectionAdjusted02 ELSE 0 END + ,ProjectionAdjusted03 = CASE WHEN @MonthsLoaded >= 3 THEN gl.ProjectionAdjusted03 ELSE 0 END + ,ProjectionAdjusted04 = CASE WHEN @MonthsLoaded >= 4 THEN gl.ProjectionAdjusted04 ELSE 0 END + ,ProjectionAdjusted05 = CASE WHEN @MonthsLoaded >= 5 THEN gl.ProjectionAdjusted05 ELSE 0 END + ,ProjectionAdjusted06 = CASE WHEN @MonthsLoaded >= 6 THEN gl.ProjectionAdjusted06 ELSE 0 END + ,ProjectionAdjusted07 = CASE WHEN @MonthsLoaded >= 7 THEN gl.ProjectionAdjusted07 ELSE 0 END + ,ProjectionAdjusted08 = CASE WHEN @MonthsLoaded >= 8 THEN gl.ProjectionAdjusted08 ELSE 0 END + ,ProjectionAdjusted09 = CASE WHEN @MonthsLoaded >= 9 THEN gl.ProjectionAdjusted09 ELSE 0 END + ,ProjectionAdjusted10 = CASE WHEN @MonthsLoaded >= 10 THEN gl.ProjectionAdjusted10 ELSE 0 END + ,ProjectionAdjusted11 = CASE WHEN @MonthsLoaded >= 11 THEN gl.ProjectionAdjusted11 ELSE 0 END + ,ProjectionAdjusted12 = CASE WHEN @MonthsLoaded >= 12 THEN gl.ProjectionAdjusted12 ELSE 0 END + ,ProjectionLockType = 3 + ,ProjectionLockFlag = 1 + FROM fp.GeneralLedger gl + INNER JOIN #CrosswalkRecords xwalk on gl.DepartmentID = xwalk.DepartmentID + AND gl.AccountID = xwalk.AccountID + WHERE + gl.VariabilityID = 1 + AND gl.EntityGroupConfigID = @EntityGroupConfigID + AND ( + gl.ProjectionAdjusted01 != CASE WHEN @MonthsLoaded >= 1 THEN gl.ProjectionAdjusted01 ELSE 0 END + OR gl.ProjectionAdjusted02 != CASE WHEN @MonthsLoaded >= 2 THEN gl.ProjectionAdjusted02 ELSE 0 END + OR gl.ProjectionAdjusted03 != CASE WHEN @MonthsLoaded >= 3 THEN gl.ProjectionAdjusted03 ELSE 0 END + OR gl.ProjectionAdjusted04 != CASE WHEN @MonthsLoaded >= 4 THEN gl.ProjectionAdjusted04 ELSE 0 END + OR gl.ProjectionAdjusted05 != CASE WHEN @MonthsLoaded >= 5 THEN gl.ProjectionAdjusted05 ELSE 0 END + OR gl.ProjectionAdjusted06 != CASE WHEN @MonthsLoaded >= 6 THEN gl.ProjectionAdjusted06 ELSE 0 END + OR gl.ProjectionAdjusted07 != CASE WHEN @MonthsLoaded >= 7 THEN gl.ProjectionAdjusted07 ELSE 0 END + OR gl.ProjectionAdjusted08 != CASE WHEN @MonthsLoaded >= 8 THEN gl.ProjectionAdjusted08 ELSE 0 END + OR gl.ProjectionAdjusted09 != CASE WHEN @MonthsLoaded >= 9 THEN gl.ProjectionAdjusted09 ELSE 0 END + OR gl.ProjectionAdjusted10 != CASE WHEN @MonthsLoaded >= 10 THEN gl.ProjectionAdjusted10 ELSE 0 END + OR gl.ProjectionAdjusted11 != CASE WHEN @MonthsLoaded >= 11 THEN gl.ProjectionAdjusted11 ELSE 0 END + OR gl.ProjectionAdjusted12 != CASE WHEN @MonthsLoaded >= 12 THEN gl.ProjectionAdjusted12 ELSE 0 END + OR gl.ProjectionLockFlag != 1 ) + + END ELSE BEGIN + SELECT 'RecordsToCrosswalk', * FROM #CrosswalkRecords + END + + END; +GO + + +--------------------------------------------- + +-- fp.procCrosswalkChargeToGeneralLedgerByPayorGroup +CREATE PROCEDURE [fp].[procCrosswalkChargeToGeneralLedgerByPayorGroup] + @EntityGroupConfigID INT, + @MonthsLoaded INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @EntityID INT, + @IsDebug BIT = 0 +WITH RECOMPILE + AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author BLI Description + ** 1 2021-09-21 MY JAZZ-25836 Initial + ** 2 2021-11-18 MY JAZZ-29482 Performance Tuning + ** 3 2021-12-08 MY JAZZ-30002 Add Batch Processing + ** 4 2023-04-06 MD JAZZ-52587 Update to support new CV data structure + ** 5 2023-04-19 MY JAZZ-53575 Improve performance on charge to GL crosswalk + ** 6 6-15-2023 NT JAZZ-56471 Add update statistics on #filterByDepartment on DBA's recommendation to improve performance + ** 7 6-27-2023 MY JAZZ-56923 Adding Service Line into the SLE to Charge payor mix calc + ** 8 2023-08-04 BW JAZZ-58151 Update for new GL data structure + ** 9 2023-04-11 MY JAZZ-70660 Update to leverage additional dimensions in mix table + ** 10 2024-09-12 MY JAZZ-70741 Update Charge to General Ledger Crosswalk Performance Improvement + ** 11 2024-12-05 MY JAZZ-80511 Implement performance improvements from ESC + *************************************************************/ + BEGIN + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#FilteredCrosswalkConfiguration') IS NOT NULL DROP TABLE #FilteredCrosswalkConfiguration + IF OBJECT_ID('tempdb..#DistinctCrosswalkConfiguration_WithoutAccount') IS NOT NULL DROP TABLE #DistinctCrosswalkConfiguration_WithoutAccount + IF OBJECT_ID('tempdb..#DistinctCrosswalkConfiguration_WithAccount') IS NOT NULL DROP TABLE #DistinctCrosswalkConfiguration_WithAccount + IF OBJECT_ID('tempdb..#RecordsWithMixes') IS NOT NULL DROP TABLE #RecordsWithMixes + IF OBJECT_ID('tempdb..#RolledUpValues') IS NOT NULL DROP TABLE #RolledUpValues + IF OBJECT_ID('tempdb..#chargeVolumeEntities') IS NOT NULL DROP TABLE #chargeVolumeEntities + + DECLARE @SQL2 NVARCHAR(MAX); --esc-44799 MP + + -- JAZZ-56923: Adding Service Line into the SLE to Charge payor mix calc + DECLARE @IsServiceLineEnabled BIT = ISNULL((SELECT Value + FROM fp.viewBudgetConfigSetting setting + INNER JOIN fp.BudgetConfig bc ON setting.BudgetConfigID = bc.BudgetConfigID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE egc.EntityGroupConfigID = @EntityGroupConfigID + AND setting.Name = 'Enable ServiceLine level mix for Charge to GL Crosswalk'), 0) + -- JAZZ-70660: Adding Additional Dimensionality into the SLE to Charge payor mix calc + DECLARE @IsAdditionalDimensionalityEnabled BIT = ISNULL((SELECT Value + FROM fp.viewBudgetConfigSetting setting + INNER JOIN fp.BudgetConfig bc ON setting.BudgetConfigID = bc.BudgetConfigID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE egc.EntityGroupConfigID = @EntityGroupConfigID + AND setting.Name = 'Enable Charge to General Ledger Crosswalk to Use Detailed Mix'), 0) + + -- This setting overrides the 'Enable ServiceLine level mix for Charge to GL Crosswalk' setting + IF (@IsAdditionalDimensionalityEnabled = 1) + BEGIN + SET @IsServiceLineEnabled = 1; + END + + CREATE TABLE #RolledUpValues(EntityID INT, DepartmentID INT, AccountID INT, + Target01 DECIMAL(19,8), Target02 DECIMAL(19,8), Target03 DECIMAL(19,8), + Target04 DECIMAL(19,8), Target05 DECIMAL(19,8), Target06 DECIMAL(19,8), + Target07 DECIMAL(19,8), Target08 DECIMAL(19,8), Target09 DECIMAL(19,8), + Target10 DECIMAL(19,8), Target11 DECIMAL(19,8), Target12 DECIMAL(19,8), + Budget01 DECIMAL(19,8), Budget02 DECIMAL(19,8), Budget03 DECIMAL(19,8), + Budget04 DECIMAL(19,8), Budget05 DECIMAL(19,8), Budget06 DECIMAL(19,8), + Budget07 DECIMAL(19,8), Budget08 DECIMAL(19,8), Budget09 DECIMAL(19,8), + Budget10 DECIMAL(19,8), Budget11 DECIMAL(19,8), Budget12 DECIMAL(19,8), + Projection01 DECIMAL(19,8), Projection02 DECIMAL(19,8), Projection03 DECIMAL(19,8), + Projection04 DECIMAL(19,8), Projection05 DECIMAL(19,8), Projection06 DECIMAL(19,8), + Projection07 DECIMAL(19,8), Projection08 DECIMAL(19,8), Projection09 DECIMAL(19,8), + Projection10 DECIMAL(19,8), Projection11 DECIMAL(19,8), Projection12 DECIMAL(19,8), + --INDEX ix_RolledUpValues CLUSTERED (EntityID, DepartmentID, AccountID) + ) + + CREATE TABLE #mixTable ( + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + PatientClassID INT, + ServiceLineID INT, + AgeCohortID INT, + MedicalSurgicalID INT, + MSDRGID INT, + CPTID INT, + ProviderID INT, + PayorID INT, + PayorGroupID INT, + BudgetMixPercentage DECIMAL(19, 8), + ProjectionMixPercentage DECIMAL(19, 8) + ,INDEX BASE CLUSTERED (EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID) + ) + + CREATE TABLE #FilteredCrosswalkConfiguration + ( + BudgetConfigID INT, + EntityGroupConfigID INT, + DepartmentID INT, + ChargeCodeID INT, + PatientClassID INT, + PayorGroupID INT, + AccountID INT + ) + + CREATE TABLE #DistinctCrosswalkConfiguration_WithoutAccount + ( + BudgetConfigID INT, + EntityGroupConfigID INT, + DepartmentID INT, + ChargeCodeID INT, + PatientClassID INT, + PayorGroupID INT + ) + + CREATE TABLE #DistinctCrosswalkConfiguration_WithAccount + ( + BudgetConfigID INT, + EntityGroupConfigID INT, + DepartmentID INT, + AccountID INT + ) + + SELECT DISTINCT EntityID AS ChargeVolumeEntityID, ServiceEntityID AS ServiceLineEncounterEntityID + INTO #chargeVolumeEntities + FROM fp.ChargeVolume + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND EntityID = @EntityID + + IF (@IsAdditionalDimensionalityEnabled = 1) + BEGIN + INSERT INTO #mixTable (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, + MSDRGID, CPTID, ProviderID, PayorID, PayorGroupID, ProjectionMixPercentage, BudgetMixPercentage) + SELECT + BudgetConfigID, + EntityGroupConfigID, + EntityID, + PatientClassID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + MSDRGID, + CPTID, + ProviderID, + PayorID, + PayorGroupID, + ProjectionMixPercentage, + BudgetMixPercentage + FROM fp.ServiceLineEncounterToChargePayorMix mix + INNER JOIN #chargeVolumeEntities ent ON mix.EntityID = ent.ServiceLineEncounterEntityID + WHERE EntityGroupConfigID = @EntityGroupConfigID + END ELSE BEGIN + INSERT INTO #mixTable (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, + MSDRGID, CPTID, ProviderID, PayorID, PayorGroupID, ProjectionMixPercentage, BudgetMixPercentage) + SELECT + BudgetConfigID, + EntityGroupConfigID, + EntityID, + PatientClassID, + CASE WHEN @IsServiceLineEnabled = 0 THEN 0 ELSE ServiceLineID END AS ServiceLineID, + 0 AS AgeCohortID, + 0 AS MedicalSurgicalID, + 0 AS MSDRGID, + 0 AS CPTID, + 0 AS ProviderID, + 0 AS PayorID, + PayorGroupID, + ProjectionMixPercentage, + BudgetMixPercentage + FROM fp.viewServiceLineEncounterPayorGroupMix_Pivoted mix + INNER JOIN #chargeVolumeEntities ent ON mix.EntityID = ent.ServiceLineEncounterEntityID + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + UPDATE STATISTICS #mixTable; --esc-44799 MP + + IF (SELECT COUNT(*) FROM @SourceDimensionality) = 0 + BEGIN + INSERT INTO #FilteredCrosswalkConfiguration + (BudgetConfigID, EntityGroupConfigID, DepartmentID, ChargeCodeID, PatientClassID, PayorGroupID, AccountID) + SELECT DISTINCT + BudgetConfigID, + EntityGroupConfigID, + config.DepartmentID, + ChargeCodeID, + PatientClassID, + PayorGroupID, + AccountID + FROM [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] config WITH (READUNCOMMITTED) + INNER JOIN fw.DimDepartment dw WITH (READUNCOMMITTED) ON config.DepartmentID = dw.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND EntityID = @EntityID -- Entity is required at all times whether it's targeted or not + AND IsRecordDeleted = 0 + + INSERT INTO #DistinctCrosswalkConfiguration_WithAccount (BudgetConfigID, EntityGroupConfigID, DepartmentID, AccountID) + SELECT DISTINCT + BudgetConfigID, + EntityGroupConfigID, + DepartmentID, + AccountID + FROM #FilteredCrosswalkConfiguration fcc + + -- Filter to the distinct charge records so we don't duplicate charge records with the join. + INSERT INTO #DistinctCrosswalkConfiguration_WithoutAccount + (BudgetConfigID, EntityGroupConfigID, DepartmentID, ChargeCodeID, PatientClassID, PayorGroupID) + SELECT DISTINCT + BudgetConfigID, + EntityGroupConfigID, + DepartmentID, + ChargeCodeID, + PatientClassID, + PayorGroupID + FROM #FilteredCrosswalkConfiguration + + SET @SQL2 = ' + INSERT INTO #RolledUpValues (EntityID, DepartmentID, AccountID, Target01, Target02, Target03, + Target04, Target05, Target06, Target07, Target08, Target09, Target10, Target11, Target12, + Budget01, Budget02, Budget03, + Budget04, Budget05, Budget06, Budget07, Budget08, Budget09, Budget10, Budget11, Budget12, + Projection01, Projection02, Projection03, Projection04, Projection05, Projection06, Projection07, Projection08, Projection09, + Projection10, Projection11, Projection12) + SELECT DISTINCT + cv.EntityID, + cv.DepartmentID, + config.AccountID, + SUM(cv.TargetDollarsAdjusted01 * BudgetMixPercentage) AS Target01, + SUM(cv.TargetDollarsAdjusted02 * BudgetMixPercentage) AS Target02, + SUM(cv.TargetDollarsAdjusted03 * BudgetMixPercentage) AS Target03, + SUM(cv.TargetDollarsAdjusted04 * BudgetMixPercentage) AS Target04, + SUM(cv.TargetDollarsAdjusted05 * BudgetMixPercentage) AS Target05, + SUM(cv.TargetDollarsAdjusted06 * BudgetMixPercentage) AS Target06, + SUM(cv.TargetDollarsAdjusted07 * BudgetMixPercentage) AS Target07, + SUM(cv.TargetDollarsAdjusted08 * BudgetMixPercentage) AS Target08, + SUM(cv.TargetDollarsAdjusted09 * BudgetMixPercentage) AS Target09, + SUM(cv.TargetDollarsAdjusted10 * BudgetMixPercentage) AS Target10, + SUM(cv.TargetDollarsAdjusted11 * BudgetMixPercentage) AS Target11, + SUM(cv.TargetDollarsAdjusted12 * BudgetMixPercentage) AS Target12, + SUM(cv.BudgetDollarsAdjusted01 * BudgetMixPercentage) AS Budget01, + SUM(cv.BudgetDollarsAdjusted02 * BudgetMixPercentage) AS Budget02, + SUM(cv.BudgetDollarsAdjusted03 * BudgetMixPercentage) AS Budget03, + SUM(cv.BudgetDollarsAdjusted04 * BudgetMixPercentage) AS Budget04, + SUM(cv.BudgetDollarsAdjusted05 * BudgetMixPercentage) AS Budget05, + SUM(cv.BudgetDollarsAdjusted06 * BudgetMixPercentage) AS Budget06, + SUM(cv.BudgetDollarsAdjusted07 * BudgetMixPercentage) AS Budget07, + SUM(cv.BudgetDollarsAdjusted08 * BudgetMixPercentage) AS Budget08, + SUM(cv.BudgetDollarsAdjusted09 * BudgetMixPercentage) AS Budget09, + SUM(cv.BudgetDollarsAdjusted10 * BudgetMixPercentage) AS Budget10, + SUM(cv.BudgetDollarsAdjusted11 * BudgetMixPercentage) AS Budget11, + SUM(cv.BudgetDollarsAdjusted12 * BudgetMixPercentage) AS Budget12, + SUM(cv.ProjectionDollarsAdjusted01 * ProjectionMixPercentage) AS Projection01, + SUM(cv.ProjectionDollarsAdjusted02 * ProjectionMixPercentage) AS Projection02, + SUM(cv.ProjectionDollarsAdjusted03 * ProjectionMixPercentage) AS Projection03, + SUM(cv.ProjectionDollarsAdjusted04 * ProjectionMixPercentage) AS Projection04, + SUM(cv.ProjectionDollarsAdjusted05 * ProjectionMixPercentage) AS Projection05, + SUM(cv.ProjectionDollarsAdjusted06 * ProjectionMixPercentage) AS Projection06, + SUM(cv.ProjectionDollarsAdjusted07 * ProjectionMixPercentage) AS Projection07, + SUM(cv.ProjectionDollarsAdjusted08 * ProjectionMixPercentage) AS Projection08, + SUM(cv.ProjectionDollarsAdjusted09 * ProjectionMixPercentage) AS Projection09, + SUM(cv.ProjectionDollarsAdjusted10 * ProjectionMixPercentage) AS Projection10, + SUM(cv.ProjectionDollarsAdjusted11 * ProjectionMixPercentage) AS Projection11, + SUM(cv.ProjectionDollarsAdjusted12 * ProjectionMixPercentage) AS Projection12 + FROM fp.ChargeVolume cv + INNER JOIN #mixTable mix on + mix.PatientClassID = cv.PatientClassID + AND mix.EntityID = cv.ServiceEntityID + AND mix.EntityGroupConfigID = cv.EntityGroupConfigID' + + CASE WHEN @IsServiceLineEnabled=0 THEN '' ELSE ' + AND mix.ServiceLineID = cv.ServiceLineID' END + + CASE WHEN @IsAdditionalDimensionalityEnabled=0 THEN '' ELSE ' + AND mix.AgeCohortID = cv.AgeCohortID + AND mix.MedicalSurgicalID = cv.MedicalSurgicalID + AND mix.MSDRGID = cv.MSDRGID + AND mix.CPTID = cv.PrimaryCPTID + AND mix.ProviderID = cv.ServiceProviderID + ' END + ' + INNER JOIN #DistinctCrosswalkConfiguration_WithoutAccount dim ON + dim.BudgetConfigID = cv.BudgetConfigID + AND dim.EntityGroupConfigID = cv.EntityGroupConfigID + AND dim.DepartmentID = cv.DepartmentID + AND dim.ChargeCodeID = cv.ChargeCodeID + AND dim.PatientClassID = cv.PatientClassID + AND dim.PatientClassID = mix.PatientClassID + AND dim.PayorGroupID = mix.PayorGroupID + INNER JOIN #FilteredCrosswalkConfiguration config ON + cv.DepartmentID = config.DepartmentID + AND cv.ChargeCodeID = config.ChargeCodeID + AND mix.PatientClassID = config.PatientClassID + AND mix.PayorGroupID = config.PayorGroupID + WHERE cv.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS VARCHAR(MAX)) + ' + AND cv.EntityID = ' + CAST(@EntityID AS VARCHAR(MAX)) + ' + GROUP BY cv.EntityID, + cv.DepartmentID, + AccountID + OPTION (RECOMPILE);' + + EXEC (@SQL2); --esc-44799 + END + ELSE + BEGIN + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + INSERT INTO #FilteredCrosswalkConfiguration + (BudgetConfigID, EntityGroupConfigID, DepartmentID, ChargeCodeID, PatientClassID, PayorGroupID, AccountID) + SELECT DISTINCT + BudgetConfigID, + EntityGroupConfigID, + config.DepartmentID, + ChargeCodeID, + PatientClassID, + PayorGroupID, + AccountID + FROM [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] config WITH (READUNCOMMITTED) + INNER JOIN #FilterByDepartment dept ON config.DepartmentID = dept.DepartmentID + INNER JOIN fw.DimDepartment dw WITH (READUNCOMMITTED) ON config.DepartmentID = dw.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND EntityID = @EntityID -- Entity is required at all times whether it's targeted or not + AND IsRecordDeleted = 0 + + INSERT INTO #DistinctCrosswalkConfiguration_WithAccount (BudgetConfigID, EntityGroupConfigID, DepartmentID, AccountID) + SELECT DISTINCT + BudgetConfigID, + EntityGroupConfigID, + DepartmentID, + AccountID + FROM #FilteredCrosswalkConfiguration fcc + + -- Filter to the distinct charge records so we don't duplicate charge records with the join. + INSERT INTO #DistinctCrosswalkConfiguration_WithoutAccount + (BudgetConfigID, EntityGroupConfigID, DepartmentID, ChargeCodeID, PatientClassID, PayorGroupID) + SELECT DISTINCT + BudgetConfigID, + EntityGroupConfigID, + DepartmentID, + ChargeCodeID, + PatientClassID, + PayorGroupID + FROM #FilteredCrosswalkConfiguration + + SET @SQL2 = ' + INSERT INTO #RolledUpValues (EntityID, DepartmentID, AccountID, Target01, Target02, Target03, + Target04, Target05, Target06, Target07, Target08, Target09, Target10, Target11, Target12, + Budget01, Budget02, Budget03, + Budget04, Budget05, Budget06, Budget07, Budget08, Budget09, Budget10, Budget11, Budget12, + Projection01, Projection02, Projection03, Projection04, Projection05, Projection06, Projection07, Projection08, Projection09, + Projection10, Projection11, Projection12) + SELECT DISTINCT + cv.EntityID, + cv.DepartmentID, + config.AccountID, + SUM(cv.TargetDollarsAdjusted01 * BudgetMixPercentage) AS Target01, + SUM(cv.TargetDollarsAdjusted02 * BudgetMixPercentage) AS Target02, + SUM(cv.TargetDollarsAdjusted03 * BudgetMixPercentage) AS Target03, + SUM(cv.TargetDollarsAdjusted04 * BudgetMixPercentage) AS Target04, + SUM(cv.TargetDollarsAdjusted05 * BudgetMixPercentage) AS Target05, + SUM(cv.TargetDollarsAdjusted06 * BudgetMixPercentage) AS Target06, + SUM(cv.TargetDollarsAdjusted07 * BudgetMixPercentage) AS Target07, + SUM(cv.TargetDollarsAdjusted08 * BudgetMixPercentage) AS Target08, + SUM(cv.TargetDollarsAdjusted09 * BudgetMixPercentage) AS Target09, + SUM(cv.TargetDollarsAdjusted10 * BudgetMixPercentage) AS Target10, + SUM(cv.TargetDollarsAdjusted11 * BudgetMixPercentage) AS Target11, + SUM(cv.TargetDollarsAdjusted12 * BudgetMixPercentage) AS Target12, + SUM(cv.BudgetDollarsAdjusted01 * BudgetMixPercentage) AS Budget01, + SUM(cv.BudgetDollarsAdjusted02 * BudgetMixPercentage) AS Budget02, + SUM(cv.BudgetDollarsAdjusted03 * BudgetMixPercentage) AS Budget03, + SUM(cv.BudgetDollarsAdjusted04 * BudgetMixPercentage) AS Budget04, + SUM(cv.BudgetDollarsAdjusted05 * BudgetMixPercentage) AS Budget05, + SUM(cv.BudgetDollarsAdjusted06 * BudgetMixPercentage) AS Budget06, + SUM(cv.BudgetDollarsAdjusted07 * BudgetMixPercentage) AS Budget07, + SUM(cv.BudgetDollarsAdjusted08 * BudgetMixPercentage) AS Budget08, + SUM(cv.BudgetDollarsAdjusted09 * BudgetMixPercentage) AS Budget09, + SUM(cv.BudgetDollarsAdjusted10 * BudgetMixPercentage) AS Budget10, + SUM(cv.BudgetDollarsAdjusted11 * BudgetMixPercentage) AS Budget11, + SUM(cv.BudgetDollarsAdjusted12 * BudgetMixPercentage) AS Budget12, + SUM(cv.ProjectionDollarsAdjusted01 * ProjectionMixPercentage) AS Projection01, + SUM(cv.ProjectionDollarsAdjusted02 * ProjectionMixPercentage) AS Projection02, + SUM(cv.ProjectionDollarsAdjusted03 * ProjectionMixPercentage) AS Projection03, + SUM(cv.ProjectionDollarsAdjusted04 * ProjectionMixPercentage) AS Projection04, + SUM(cv.ProjectionDollarsAdjusted05 * ProjectionMixPercentage) AS Projection05, + SUM(cv.ProjectionDollarsAdjusted06 * ProjectionMixPercentage) AS Projection06, + SUM(cv.ProjectionDollarsAdjusted07 * ProjectionMixPercentage) AS Projection07, + SUM(cv.ProjectionDollarsAdjusted08 * ProjectionMixPercentage) AS Projection08, + SUM(cv.ProjectionDollarsAdjusted09 * ProjectionMixPercentage) AS Projection09, + SUM(cv.ProjectionDollarsAdjusted10 * ProjectionMixPercentage) AS Projection10, + SUM(cv.ProjectionDollarsAdjusted11 * ProjectionMixPercentage) AS Projection11, + SUM(cv.ProjectionDollarsAdjusted12 * ProjectionMixPercentage) AS Projection12 + FROM fp.ChargeVolume cv + INNER JOIN #mixTable mix on + mix.PatientClassID = cv.PatientClassID + AND mix.EntityID = cv.ServiceEntityID + AND mix.EntityGroupConfigID = cv.EntityGroupConfigID' + + CASE WHEN @IsServiceLineEnabled=0 THEN '' ELSE ' + AND mix.ServiceLineID = cv.ServiceLineID' END + + CASE WHEN @IsAdditionalDimensionalityEnabled=0 THEN '' ELSE ' + AND mix.AgeCohortID = cv.AgeCohortID + AND mix.MedicalSurgicalID = cv.MedicalSurgicalID + AND mix.MSDRGID = cv.MSDRGID + AND mix.CPTID = cv.PrimaryCPTID + AND mix.ProviderID = cv.ServiceProviderID + ' END + ' + INNER JOIN #DistinctCrosswalkConfiguration_WithoutAccount dim ON + dim.BudgetConfigID = cv.BudgetConfigID + AND dim.EntityGroupConfigID = cv.EntityGroupConfigID + AND dim.DepartmentID = cv.DepartmentID + AND dim.ChargeCodeID = cv.ChargeCodeID + AND dim.PatientClassID = cv.PatientClassID + AND dim.PatientClassID = mix.PatientClassID + AND dim.PayorGroupID = mix.PayorGroupID + INNER JOIN #FilteredCrosswalkConfiguration config ON + cv.DepartmentID = config.DepartmentID + AND cv.ChargeCodeID = config.ChargeCodeID + AND mix.PatientClassID = config.PatientClassID + AND mix.PayorGroupID = config.PayorGroupID + WHERE cv.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS VARCHAR(MAX)) + ' + AND cv.EntityID = ' + CAST(@EntityID AS VARCHAR(MAX)) + ' + GROUP BY cv.EntityID, + cv.DepartmentID, + AccountID + OPTION (RECOMPILE);' + + EXEC (@SQL2); --esc-44799 + END + + IF (@IsDebug = 0) + BEGIN + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#DistinctCrosswalkConfiguration_WithoutAccount') IS NOT NULL DROP TABLE #DistinctCrosswalkConfiguration_WithoutAccount + IF OBJECT_ID('tempdb..#RecordsToCrosswalk') IS NOT NULL DROP TABLE #RecordsToCrosswalk + + UPDATE gl + SET + TargetAdjusted01 = xwalk.Target01, + TargetAdjusted02 = xwalk.Target02, + TargetAdjusted03 = xwalk.Target03, + TargetAdjusted04 = xwalk.Target04, + TargetAdjusted05 = xwalk.Target05, + TargetAdjusted06 = xwalk.Target06, + TargetAdjusted07 = xwalk.Target07, + TargetAdjusted08 = xwalk.Target08, + TargetAdjusted09 = xwalk.Target09, + TargetAdjusted10 = xwalk.Target10, + TargetAdjusted11 = xwalk.Target11, + TargetAdjusted12 = xwalk.Target12, + TargetLockFlag = 1, + TargetLockType = 3, + BudgetAdjusted01 = xwalk.Budget01, + BudgetAdjusted02 = xwalk.Budget02, + BudgetAdjusted03 = xwalk.Budget03, + BudgetAdjusted04 = xwalk.Budget04, + BudgetAdjusted05 = xwalk.Budget05, + BudgetAdjusted06 = xwalk.Budget06, + BudgetAdjusted07 = xwalk.Budget07, + BudgetAdjusted08 = xwalk.Budget08, + BudgetAdjusted09 = xwalk.Budget09, + BudgetAdjusted10 = xwalk.Budget10, + BudgetAdjusted11 = xwalk.Budget11, + BudgetAdjusted12 = xwalk.Budget12, + BudgetLockFlag = 1, + BudgetLockType = 3 + FROM fp.GeneralLedger gl + INNER JOIN #RolledUpValues xwalk ON + gl.DepartmentID = xwalk.DepartmentID + AND gl.AccountID = xwalk.AccountID + WHERE gl.VariabilityID = 2 + AND gl.EntityGroupConfigID = @EntityGroupConfigID + AND ( + TargetAdjusted01 != xwalk.Target01 + OR TargetAdjusted02 != xwalk.Target02 + OR TargetAdjusted03 != xwalk.Target03 + OR TargetAdjusted04 != xwalk.Target04 + OR TargetAdjusted05 != xwalk.Target05 + OR TargetAdjusted06 != xwalk.Target06 + OR TargetAdjusted07 != xwalk.Target07 + OR TargetAdjusted08 != xwalk.Target08 + OR TargetAdjusted09 != xwalk.Target09 + OR TargetAdjusted10 != xwalk.Target10 + OR TargetAdjusted11 != xwalk.Target11 + OR TargetAdjusted12 != xwalk.Target12 + OR TargetLockFlag != 1 + OR TargetLockType != 3 + OR BudgetAdjusted01 != xwalk.Budget01 + OR BudgetAdjusted02 != xwalk.Budget02 + OR BudgetAdjusted03 != xwalk.Budget03 + OR BudgetAdjusted04 != xwalk.Budget04 + OR BudgetAdjusted05 != xwalk.Budget05 + OR BudgetAdjusted06 != xwalk.Budget06 + OR BudgetAdjusted07 != xwalk.Budget07 + OR BudgetAdjusted08 != xwalk.Budget08 + OR BudgetAdjusted09 != xwalk.Budget09 + OR BudgetAdjusted10 != xwalk.Budget10 + OR BudgetAdjusted11 != xwalk.Budget11 + OR BudgetAdjusted12 != xwalk.Budget12 + OR BudgetLockFlag != 1 + OR BudgetLockType != 3 + ) + + DECLARE @i int = @MonthsLoaded + 1 + DECLARE @MonthsLoadedString CHAR(10) + SELECT @MonthsLoadedString = CAST(@i as CHAR(2)); + + DECLARE @sql varchar(max) = 'UPDATE gl SET ' + + WHILE (@i <= 12) + BEGIN + SET @sql = @sql + 'gl.ProjectionAdjusted' + CASE WHEN @i < 10 THEN '0' ELSE '' END + CAST(@i AS VARCHAR(2)) + ' = xwalk.Projection' + CASE WHEN @i < 10 THEN '0' ELSE '' END + CAST(@i AS VARCHAR(2)) + CASE WHEN @i < 12 THEN ',' ELSE '' END + SET @i = @i + 1 + END + + SET @sql = @sql + ' + , ProjectionLockFlag = 1 + , ProjectionLockType = 3 + FROM fp.GeneralLedger gl + INNER JOIN #RolledUpValues xwalk ON + gl.DepartmentID = xwalk.DepartmentID + AND gl.AccountID = xwalk.AccountID + WHERE gl.VariabilityID = 2 + AND gl.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS VARCHAR(10)) + ' + AND ( + (gl.ProjectionAdjusted01 != xwalk.Projection01 AND ' + @MonthsLoadedString + ' <= 1 ) + OR (gl.ProjectionAdjusted02 != xwalk.Projection02 AND ' + @MonthsLoadedString + ' <= 2 ) + OR (gl.ProjectionAdjusted03 != xwalk.Projection03 AND ' + @MonthsLoadedString + ' <= 3 ) + OR (gl.ProjectionAdjusted04 != xwalk.Projection04 AND ' + @MonthsLoadedString + ' <= 4 ) + OR (gl.ProjectionAdjusted05 != xwalk.Projection05 AND ' + @MonthsLoadedString + ' <= 5 ) + OR (gl.ProjectionAdjusted06 != xwalk.Projection06 AND ' + @MonthsLoadedString + ' <= 6 ) + OR (gl.ProjectionAdjusted07 != xwalk.Projection07 AND ' + @MonthsLoadedString + ' <= 7 ) + OR (gl.ProjectionAdjusted08 != xwalk.Projection08 AND ' + @MonthsLoadedString + ' <= 8 ) + OR (gl.ProjectionAdjusted09 != xwalk.Projection09 AND ' + @MonthsLoadedString + ' <= 9 ) + OR (gl.ProjectionAdjusted10 != xwalk.Projection10 AND ' + @MonthsLoadedString + ' <= 10 ) + OR (gl.ProjectionAdjusted11 != xwalk.Projection11 AND ' + @MonthsLoadedString + ' <= 11 ) + OR (gl.ProjectionAdjusted12 != xwalk.Projection12 AND ' + @MonthsLoadedString + ' <= 12 ) + OR ProjectionLockFlag != 1 + OR ProjectionLockType != 3 + ) + ' + + EXEC (@sql); + + -- We 0 out any fixed portion for these crosswalked value + UPDATE gl + SET + TargetAdjusted01 = 0, + TargetAdjusted02 = 0, + TargetAdjusted03 = 0, + TargetAdjusted04 = 0, + TargetAdjusted05 = 0, + TargetAdjusted06 = 0, + TargetAdjusted07 = 0, + TargetAdjusted08 = 0, + TargetAdjusted09 = 0, + TargetAdjusted10 = 0, + TargetAdjusted11 = 0, + TargetAdjusted12 = 0, + TargetLockFlag = 1, + TargetLockType = 3, + BudgetAdjusted01 = 0, + BudgetAdjusted02 = 0, + BudgetAdjusted03 = 0, + BudgetAdjusted04 = 0, + BudgetAdjusted05 = 0, + BudgetAdjusted06 = 0, + BudgetAdjusted07 = 0, + BudgetAdjusted08 = 0, + BudgetAdjusted09 = 0, + BudgetAdjusted10 = 0, + BudgetAdjusted11 = 0, + BudgetAdjusted12 = 0, + BudgetLockFlag = 1, + BudgetLockType = 3 + FROM fp.GeneralLedger gl + INNER JOIN #RolledUpValues xwalk on gl.DepartmentID = xwalk.DepartmentID + AND gl.AccountID = xwalk.AccountID + WHERE gl.VariabilityID = 1 + AND gl.EntityGroupConfigID = @EntityGroupConfigID + AND ( + TargetAdjusted01 != 0 + OR TargetAdjusted02 != 0 + OR TargetAdjusted03 != 0 + OR TargetAdjusted04 != 0 + OR TargetAdjusted05 != 0 + OR TargetAdjusted06 != 0 + OR TargetAdjusted07 != 0 + OR TargetAdjusted08 != 0 + OR TargetAdjusted09 != 0 + OR TargetAdjusted10 != 0 + OR TargetAdjusted11 != 0 + OR TargetAdjusted12 != 0 + OR TargetLockFlag != 1 + OR TargetLockType != 3 + OR BudgetAdjusted01 != 0 + OR BudgetAdjusted02 != 0 + OR BudgetAdjusted03 != 0 + OR BudgetAdjusted04 != 0 + OR BudgetAdjusted05 != 0 + OR BudgetAdjusted06 != 0 + OR BudgetAdjusted07 != 0 + OR BudgetAdjusted08 != 0 + OR BudgetAdjusted09 != 0 + OR BudgetAdjusted10 != 0 + OR BudgetAdjusted11 != 0 + OR BudgetAdjusted12 != 0 + OR BudgetLockFlag != 1 + OR BudgetLockType != 3 + ) + + SET @i = @MonthsLoaded + 1; + SET @sql = 'UPDATE gl SET ' + + WHILE (@i <= 12) + BEGIN + SET @sql = @sql + 'gl.ProjectionAdjusted' + CASE WHEN @i < 10 THEN '0' ELSE '' END + CAST(@i AS VARCHAR(2)) + ' = 0' + CASE WHEN @i < 12 THEN ',' ELSE '' END + SET @i = @i+1 + END + + SET @sql = @sql + ' + , ProjectionLockFlag = 1 + , ProjectionLockType = 3 + FROM fp.GeneralLedger gl + INNER JOIN #RolledUpValues xwalk ON + gl.DepartmentID = xwalk.DepartmentID + AND gl.AccountID = xwalk.AccountID + WHERE gl.VariabilityID = 1 + AND gl.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS VARCHAR(10)) + ' + AND ( + (gl.ProjectionAdjusted01 != 0 AND ' + @MonthsLoadedString + ' <= 1 ) + OR (gl.ProjectionAdjusted02 != 0 AND ' + @MonthsLoadedString + ' <= 2 ) + OR (gl.ProjectionAdjusted03 != 0 AND ' + @MonthsLoadedString + ' <= 3 ) + OR (gl.ProjectionAdjusted04 != 0 AND ' + @MonthsLoadedString + ' <= 4 ) + OR (gl.ProjectionAdjusted05 != 0 AND ' + @MonthsLoadedString + ' <= 5 ) + OR (gl.ProjectionAdjusted06 != 0 AND ' + @MonthsLoadedString + ' <= 6 ) + OR (gl.ProjectionAdjusted07 != 0 AND ' + @MonthsLoadedString + ' <= 7 ) + OR (gl.ProjectionAdjusted08 != 0 AND ' + @MonthsLoadedString + ' <= 8 ) + OR (gl.ProjectionAdjusted09 != 0 AND ' + @MonthsLoadedString + ' <= 9 ) + OR (gl.ProjectionAdjusted10 != 0 AND ' + @MonthsLoadedString + ' <= 10 ) + OR (gl.ProjectionAdjusted11 != 0 AND ' + @MonthsLoadedString + ' <= 11 ) + OR (gl.ProjectionAdjusted12 != 0 AND ' + @MonthsLoadedString + ' <= 12 ) + OR ProjectionLockFlag != 1 + OR ProjectionLockType != 3 + ) + ' + + EXEC (@sql); + + IF (@IsAdditionalDimensionalityEnabled = 1) + BEGIN + -- Update records that do not have a corresponding mix. These are records with a configuration record, but not a corresponding match between Charges and the Encounter mix + -- This can be for a few reasons, but one main reason is you have a config that does not directly map between the data (IE: It contains data in encounters and charges, however + -- the specified Payor Group does not exist) + UPDATE gl + SET + TargetAdjusted01 = 0, TargetAdjusted02 = 0, TargetAdjusted03 = 0, TargetAdjusted04 = 0, TargetAdjusted05 = 0, TargetAdjusted06 = 0, + TargetAdjusted07 = 0, TargetAdjusted08 = 0, TargetAdjusted09 = 0, TargetAdjusted10 = 0, TargetAdjusted11 = 0, TargetAdjusted12 = 0, + BudgetAdjusted01 = 0, BudgetAdjusted02 = 0, BudgetAdjusted03 = 0, BudgetAdjusted04 = 0, BudgetAdjusted05 = 0, BudgetAdjusted06 = 0, + BudgetAdjusted07 = 0, BudgetAdjusted08 = 0, BudgetAdjusted09 = 0, BudgetAdjusted10 = 0, BudgetAdjusted11 = 0, BudgetAdjusted12 = 0, + TargetLockFlag = 1, + TargetLockType = 3, + BudgetLockFlag = 1, + BudgetLockType = 3 + FROM fp.GeneralLedger gl + INNER JOIN #DistinctCrosswalkConfiguration_WithAccount config ON gl.BudgetConfigID = config.BudgetConfigID + AND gl.EntityGroupConfigID = config.EntityGroupConfigID + AND gl.DepartmentID = config.DepartmentID + AND gl.AccountID = config.AccountID + LEFT JOIN #RolledUpValues roll ON roll.EntityID = gl.EntityID + AND roll.DepartmentID = gl.DepartmentID + AND roll.AccountID = gl.AccountID + WHERE 1 = 1 + AND gl.EntityGroupConfigID = @EntityGroupConfigID + AND gl.FlexingTypeID = 4 -- Charge to GL Crosswalk + AND roll.AccountID IS NULL -- We only want records that are configured, but falled out of the value calc above + AND ( + TargetAdjusted01 != 0 OR TargetAdjusted02 != 0 OR TargetAdjusted03 != 0 OR TargetAdjusted04 != 0 OR TargetAdjusted05 != 0 OR TargetAdjusted06 != 0 + OR TargetAdjusted07 != 0 OR TargetAdjusted08 != 0 OR TargetAdjusted09 != 0 OR TargetAdjusted10 != 0 OR TargetAdjusted11 != 0 OR TargetAdjusted12 != 0 + OR BudgetAdjusted01 != 0 OR BudgetAdjusted02 != 0 OR BudgetAdjusted03 != 0 OR BudgetAdjusted04 != 0 OR BudgetAdjusted05 != 0 OR BudgetAdjusted06 != 0 + OR BudgetAdjusted07 != 0 OR BudgetAdjusted08 != 0 OR BudgetAdjusted09 != 0 OR BudgetAdjusted10 != 0 OR BudgetAdjusted11 != 0 OR BudgetAdjusted12 != 0 + OR TargetLockFlag != 1 + OR TargetLockType != 3 + OR BudgetLockFlag != 1 + OR BudgetLockType != 3 + ) + + SET @i = @MonthsLoaded + 1; + SET @sql = 'UPDATE gl SET ' + + WHILE (@i <= 12) + BEGIN + SET @sql = @sql + 'gl.ProjectionAdjusted' + CASE WHEN @i < 10 THEN '0' ELSE '' END + CAST(@i as varchar(2)) + ' = 0' + CASE WHEN @i<12 THEN ',' ELSE '' END + SET @i = @i+1 + END + + SET @sql = @sql + ' + , ProjectionLockFlag = 1 + , ProjectionLockType = 3 + FROM fp.GeneralLedger gl + INNER JOIN #DistinctCrosswalkConfiguration_WithAccount config ON gl.BudgetConfigID = config.BudgetConfigID + AND gl.EntityGroupConfigID = config.EntityGroupConfigID + AND gl.DepartmentID = config.DepartmentID + AND gl.AccountID = config.AccountID + LEFT JOIN #RolledUpValues roll ON roll.EntityID = gl.EntityID + AND roll.DepartmentID = gl.DepartmentID + AND roll.AccountID = gl.AccountID + WHERE 1 = 1 + AND gl.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS VARCHAR(10)) + ' + AND gl.FlexingTypeID = 4 -- Charge to GL Crosswalk + AND roll.AccountID IS NULL -- We only want records that are configured, but falled out of the value calc above + AND ( + (gl.ProjectionAdjusted01 != 0 AND ' + @MonthsLoadedString + ' <= 1 ) + OR (gl.ProjectionAdjusted02 != 0 AND ' + @MonthsLoadedString + ' <= 2 ) + OR (gl.ProjectionAdjusted03 != 0 AND ' + @MonthsLoadedString + ' <= 3 ) + OR (gl.ProjectionAdjusted04 != 0 AND ' + @MonthsLoadedString + ' <= 4 ) + OR (gl.ProjectionAdjusted05 != 0 AND ' + @MonthsLoadedString + ' <= 5 ) + OR (gl.ProjectionAdjusted06 != 0 AND ' + @MonthsLoadedString + ' <= 6 ) + OR (gl.ProjectionAdjusted07 != 0 AND ' + @MonthsLoadedString + ' <= 7 ) + OR (gl.ProjectionAdjusted08 != 0 AND ' + @MonthsLoadedString + ' <= 8 ) + OR (gl.ProjectionAdjusted09 != 0 AND ' + @MonthsLoadedString + ' <= 9 ) + OR (gl.ProjectionAdjusted10 != 0 AND ' + @MonthsLoadedString + ' <= 10 ) + OR (gl.ProjectionAdjusted11 != 0 AND ' + @MonthsLoadedString + ' <= 11 ) + OR (gl.ProjectionAdjusted12 != 0 AND ' + @MonthsLoadedString + ' <= 12 ) + OR ProjectionLockFlag != 1 + OR ProjectionLockType != 3 + ) + ' + + EXEC (@sql); + END + END ELSE BEGIN + SELECT '@IsServiceLineEnabled', @IsServiceLineEnabled + SELECT '@IsAdditionalDimensionalityEnabled', @IsAdditionalDimensionalityEnabled + SELECT '#mixTable', * FROM #mixTable + SELECT '#DistinctCrosswalkConfiguration_WithAccount', * FROM #DistinctCrosswalkConfiguration_WithAccount + SELECT '#DistinctCrosswalkConfiguration_WithoutAccount', * FROM #DistinctCrosswalkConfiguration_WithoutAccount + SELECT '#RolledUpValues', * FROM #RolledUpValues + END + END; +GO + + +--------------------------------------------- + +-- fp.procCrosswalkChargeToGeneralLedgerByPayorGroup_InitialValue +CREATE PROCEDURE [fp].[procCrosswalkChargeToGeneralLedgerByPayorGroup_InitialValue] + @EntityGroupConfigID INT, + @MonthsLoaded INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @EntityID INT, + @IsDebug BIT = 0 +WITH RECOMPILE + AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author BLI Description + ** 1 2021-09-21 MY JAZZ-25836 Initial + ** 2 2021-11-18 MY JAZZ-29482 Performance Tuning + ** 3 2021-12-08 MY JAZZ-30002 Add Batch Processing + ** 4 2023-04-06 MD JAZZ-52587 Update to use new CV data structure + ** 5 2023-04-19 MY JAZZ-53575 Improve performance on charge to GL crosswalk + ** 6 2023-06-15 NT JAZZ-56471 Add update statistics on #filterByDepartment on DBA's recommendation to improve performance + ** 7 2023-06-27 MY JAZZ-56923 Adding Service Line into the SLE to Charge payor mix calc + ** 8 2023-08-04 BW JAZZ-58151 Update for new GL data structure + ** 9 2023-04-11 MY JAZZ-70660 Update to leverage additional dimensions in mix table + ** 10 2024-09-12 MY JAZZ-70741 Update Charge to General Ledger Crosswalk Performance Improvement + ** 11 2024-09-16 MY JAZZ-70683 Add Initial Projection Mix for Reimbursement/Charge to General Ledger Mix + *************************************************************/ + BEGIN + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#FilteredCrosswalkConfiguration') IS NOT NULL DROP TABLE #FilteredCrosswalkConfiguration + IF OBJECT_ID('tempdb..#DistinctCrosswalkConfiguration_WithoutAccount') IS NOT NULL DROP TABLE #DistinctCrosswalkConfiguration_WithoutAccount + IF OBJECT_ID('tempdb..#RecordsWithMixes') IS NOT NULL DROP TABLE #RecordsWithMixes + IF OBJECT_ID('tempdb..#RolledUpValues') IS NOT NULL DROP TABLE #RolledUpValues + IF OBJECT_ID('tempdb..#mixTable') IS NOT NULL DROP TABLE #mixTable + IF OBJECT_ID('tempdb..#chargeVolumeEntities') IS NOT NULL DROP TABLE #chargeVolumeEntities + + -- JAZZ-56923: Adding Service Line into the SLE to Charge payor mix calc + DECLARE @IsServiceLineEnabled BIT = ISNULL((SELECT Value + FROM fp.viewBudgetConfigSetting setting + INNER JOIN fp.BudgetConfig bc ON setting.BudgetConfigID = bc.BudgetConfigID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE egc.EntityGroupConfigID = @EntityGroupConfigID + AND setting.Name = 'Enable ServiceLine level mix for Charge to GL Crosswalk'), 0) + + + -- JAZZ-70660: Adding Additional Dimensionality into the SLE to Charge payor mix calc + DECLARE @IsAdditionalDimensionalityEnabled BIT = ISNULL((SELECT Value + FROM fp.viewBudgetConfigSetting setting + INNER JOIN fp.BudgetConfig bc ON setting.BudgetConfigID = bc.BudgetConfigID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE egc.EntityGroupConfigID = @EntityGroupConfigID + AND setting.Name = 'Enable Charge to General Ledger Crosswalk to Use Detailed Mix'), 0) + + -- JAZZ-70683: Add Initial Projection Mix for Reimbursement/Charge to General Ledger Mix + DECLARE @IsProjectionMixEnabled BIT = ISNULL((SELECT Value + FROM fp.viewBudgetConfigSetting setting + INNER JOIN fp.BudgetConfig bc ON setting.BudgetConfigID = bc.BudgetConfigID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE egc.EntityGroupConfigID = @EntityGroupConfigID + AND setting.Name = 'Enable Initial Projection Mix for Encounter to Charge Payor Group Mix'), 0) + + -- This setting overrides the 'Enable ServiceLine level mix for Charge to GL Crosswalk' setting + IF (@IsAdditionalDimensionalityEnabled = 1) + BEGIN + SET @IsServiceLineEnabled = 1; + END + + CREATE TABLE #RolledUpValues(EntityID INT, DepartmentID INT, AccountID INT, + InitialBudget01 DECIMAL(19,8), InitialBudget02 DECIMAL(19,8), InitialBudget03 DECIMAL(19,8), InitialBudget04 DECIMAL(19,8), InitialBudget05 DECIMAL(19,8), InitialBudget06 DECIMAL(19,8), + InitialBudget07 DECIMAL(19,8), InitialBudget08 DECIMAL(19,8), InitialBudget09 DECIMAL(19,8), InitialBudget10 DECIMAL(19,8), InitialBudget11 DECIMAL(19,8), InitialBudget12 DECIMAL(19,8), + InitialProjection01 DECIMAL(19,8), InitialProjection02 DECIMAL(19,8), InitialProjection03 DECIMAL(19,8), InitialProjection04 DECIMAL(19,8), InitialProjection05 DECIMAL(19,8), InitialProjection06 DECIMAL(19,8), + InitialProjection07 DECIMAL(19,8), InitialProjection08 DECIMAL(19,8), InitialProjection09 DECIMAL(19,8), InitialProjection10 DECIMAL(19,8), InitialProjection11 DECIMAL(19,8), InitialProjection12 DECIMAL(19,8), + ) + + CREATE TABLE #mixTable ( + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + PatientClassID INT, + ServiceLineID INT, + AgeCohortID INT, + MedicalSurgicalID INT, + MSDRGID INT, + CPTID INT, + ProviderID INT, + PayorID INT, + PayorGroupID INT, + InitialProjectionMixPercentage DECIMAL(19, 8), + InitialBudgetMixPercentage DECIMAL(19, 8) + ) + + CREATE TABLE #FilteredCrosswalkConfiguration + ( + BudgetConfigID INT, + EntityGroupConfigID INT, + DepartmentID INT, + ChargeCodeID INT, + PatientClassID INT, + PayorGroupID INT, + AccountID INT + ) + + CREATE TABLE #DistinctCrosswalkConfiguration_WithoutAccount + ( + BudgetConfigID INT, + EntityGroupConfigID INT, + DepartmentID INT, + ChargeCodeID INT, + PatientClassID INT, + PayorGroupID INT + ) + + CREATE TABLE #DistinctCrosswalkConfiguration_WithAccount + ( + BudgetConfigID INT, + EntityGroupConfigID INT, + DepartmentID INT, + AccountID INT + ) + + SELECT DISTINCT EntityID AS ChargeVolumeEntityID, ServiceEntityID AS ServiceLineEncounterEntityID + INTO #chargeVolumeEntities + FROM fp.ChargeVolume + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND EntityID = @EntityID + + IF (@IsAdditionalDimensionalityEnabled = 1) + BEGIN + INSERT INTO #mixTable (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, + MSDRGID, CPTID, ProviderID, PayorID, PayorGroupID, InitialProjectionMixPercentage, InitialBudgetMixPercentage) + SELECT + BudgetConfigID, + EntityGroupConfigID, + EntityID, + PatientClassID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + MSDRGID, + CPTID, + ProviderID, + PayorID, + PayorGroupID, + CASE WHEN @IsProjectionMixEnabled = 1 THEN InitialProjectionMixPercentage ELSE InitialMixPercentage END, + InitialMixPercentage + FROM fp.ServiceLineEncounterToChargePayorMix mix + INNER JOIN #chargeVolumeEntities ent ON mix.EntityID = ent.ServiceLineEncounterEntityID + WHERE EntityGroupConfigID = @EntityGroupConfigID + END ELSE BEGIN + INSERT INTO #mixTable (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, + MSDRGID, CPTID, ProviderID, PayorID, PayorGroupID, InitialProjectionMixPercentage, InitialBudgetMixPercentage) + SELECT + BudgetConfigID, + EntityGroupConfigID, + EntityID, + PatientClassID, + CASE WHEN @IsServiceLineEnabled = 0 THEN 0 ELSE ServiceLineID END AS ServiceLineID, + 0 AS AgeCohortID, + 0 AS MedicalSurgicalID, + 0 AS MSDRGID, + 0 AS CPTID, + 0 AS ProviderID, + 0 AS PayorID, + PayorGroupID, + InitialProjectionMixPercentage, + InitialBudgetMixPercentage + FROM fp.viewServiceLineEncounterPayorGroupMix_Pivoted mix + INNER JOIN #chargeVolumeEntities ent ON mix.EntityID = ent.ServiceLineEncounterEntityID + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + IF (SELECT COUNT(*) FROM @SourceDimensionality) = 0 + BEGIN + INSERT INTO #FilteredCrosswalkConfiguration + (BudgetConfigID, EntityGroupConfigID, DepartmentID, ChargeCodeID, PatientClassID, PayorGroupID, AccountID) + SELECT DISTINCT + BudgetConfigID, + EntityGroupConfigID, + config.DepartmentID, + ChargeCodeID, + PatientClassID, + PayorGroupID, + AccountID + FROM [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] config WITH (READUNCOMMITTED) + INNER JOIN fw.DimDepartment dw WITH (READUNCOMMITTED) ON config.DepartmentID = dw.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND EntityID = @EntityID -- Entity is required at all times whether it's targeted or not + AND IsRecordDeleted = 0 + + INSERT INTO #DistinctCrosswalkConfiguration_WithAccount (BudgetConfigID, EntityGroupConfigID, DepartmentID, AccountID) + SELECT DISTINCT + BudgetConfigID, + EntityGroupConfigID, + DepartmentID, + AccountID + FROM #FilteredCrosswalkConfiguration fcc + + -- Filter to the distinct charge records so we don't duplicate charge records with the join. + INSERT INTO #DistinctCrosswalkConfiguration_WithoutAccount + (BudgetConfigID, EntityGroupConfigID, DepartmentID, ChargeCodeID, PatientClassID, PayorGroupID) + SELECT DISTINCT + BudgetConfigID, + EntityGroupConfigID, + DepartmentID, + ChargeCodeID, + PatientClassID, + PayorGroupID + FROM #FilteredCrosswalkConfiguration + + INSERT INTO #RolledUpValues (EntityID, DepartmentID, AccountID, InitialBudget01, InitialBudget02, InitialBudget03, + InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, + InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, + InitialProjection10, InitialProjection11, InitialProjection12) + SELECT DISTINCT + cv.EntityID, + cv.DepartmentID, + config.AccountID, + SUM(cv.InitialBudgetDollars01 * InitialBudgetMixPercentage) AS InitialBudget01, + SUM(cv.InitialBudgetDollars02 * InitialBudgetMixPercentage) AS InitialBudget02, + SUM(cv.InitialBudgetDollars03 * InitialBudgetMixPercentage) AS InitialBudget03, + SUM(cv.InitialBudgetDollars04 * InitialBudgetMixPercentage) AS InitialBudget04, + SUM(cv.InitialBudgetDollars05 * InitialBudgetMixPercentage) AS InitialBudget05, + SUM(cv.InitialBudgetDollars06 * InitialBudgetMixPercentage) AS InitialBudget06, + SUM(cv.InitialBudgetDollars07 * InitialBudgetMixPercentage) AS InitialBudget07, + SUM(cv.InitialBudgetDollars08 * InitialBudgetMixPercentage) AS InitialBudget08, + SUM(cv.InitialBudgetDollars09 * InitialBudgetMixPercentage) AS InitialBudget09, + SUM(cv.InitialBudgetDollars10 * InitialBudgetMixPercentage) AS InitialBudget10, + SUM(cv.InitialBudgetDollars11 * InitialBudgetMixPercentage) AS InitialBudget11, + SUM(cv.InitialBudgetDollars12 * InitialBudgetMixPercentage) AS InitialBudget12, + SUM(cv.InitialProjectionDollars01 * InitialProjectionMixPercentage) AS InitialProjection01, + SUM(cv.InitialProjectionDollars02 * InitialProjectionMixPercentage) AS InitialProjection02, + SUM(cv.InitialProjectionDollars03 * InitialProjectionMixPercentage) AS InitialProjection03, + SUM(cv.InitialProjectionDollars04 * InitialProjectionMixPercentage) AS InitialProjection04, + SUM(cv.InitialProjectionDollars05 * InitialProjectionMixPercentage) AS InitialProjection05, + SUM(cv.InitialProjectionDollars06 * InitialProjectionMixPercentage) AS InitialProjection06, + SUM(cv.InitialProjectionDollars07 * InitialProjectionMixPercentage) AS InitialProjection07, + SUM(cv.InitialProjectionDollars08 * InitialProjectionMixPercentage) AS InitialProjection08, + SUM(cv.InitialProjectionDollars09 * InitialProjectionMixPercentage) AS InitialProjection09, + SUM(cv.InitialProjectionDollars10 * InitialProjectionMixPercentage) AS InitialProjection10, + SUM(cv.InitialProjectionDollars11 * InitialProjectionMixPercentage) AS InitialProjection11, + SUM(cv.InitialProjectionDollars12 * InitialProjectionMixPercentage) AS InitialProjection12 + FROM fp.ChargeVolume cv WITH (READUNCOMMITTED) + INNER JOIN #mixTable mix WITH (READUNCOMMITTED) on + mix.PatientClassID = cv.PatientClassID + AND mix.EntityID = cv.ServiceEntityID + AND mix.EntityGroupConfigID = cv.EntityGroupConfigID + AND (@IsServiceLineEnabled = 0 OR mix.ServiceLineID = cv.ServiceLineID) + AND (@IsAdditionalDimensionalityEnabled = 0 OR mix.AgeCohortID = cv.AgeCohortID) + AND (@IsAdditionalDimensionalityEnabled = 0 OR mix.MedicalSurgicalID = cv.MedicalSurgicalID) + AND (@IsAdditionalDimensionalityEnabled = 0 OR mix.MSDRGID = cv.MSDRGID) + AND (@IsAdditionalDimensionalityEnabled = 0 OR mix.CPTID = cv.PrimaryCPTID) + AND (@IsAdditionalDimensionalityEnabled = 0 OR mix.ProviderID = cv.ServiceProviderID) + INNER JOIN #DistinctCrosswalkConfiguration_WithoutAccount dim ON + dim.BudgetConfigID = cv.BudgetConfigID + AND dim.EntityGroupConfigID = cv.EntityGroupConfigID + AND dim.DepartmentID = cv.DepartmentID + AND dim.ChargeCodeID = cv.ChargeCodeID + AND dim.PatientClassID = cv.PatientClassID + AND dim.PatientClassID = mix.PatientClassID + AND dim.PayorGroupID = mix.PayorGroupID + INNER JOIN #FilteredCrosswalkConfiguration config WITH (READUNCOMMITTED) ON + cv.DepartmentID = config.DepartmentID + AND cv.ChargeCodeID = config.ChargeCodeID + AND mix.PatientClassID = config.PatientClassID + AND mix.PayorGroupID = config.PayorGroupID + WHERE cv.EntityGroupConfigID = @EntityGroupConfigID + AND cv.EntityID = @EntityID + GROUP BY cv.EntityID, + cv.DepartmentID, + AccountID + OPTION (RECOMPILE) + + END + ELSE + BEGIN + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + INSERT INTO #FilteredCrosswalkConfiguration + (BudgetConfigID, EntityGroupConfigID, DepartmentID, ChargeCodeID, PatientClassID, PayorGroupID, AccountID) + SELECT DISTINCT + BudgetConfigID, + EntityGroupConfigID, + config.DepartmentID, + ChargeCodeID, + PatientClassID, + PayorGroupID, + AccountID + FROM [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] config WITH (READUNCOMMITTED) + INNER JOIN #FilterByDepartment dept ON config.DepartmentID = dept.DepartmentID + INNER JOIN fw.DimDepartment dw WITH (READUNCOMMITTED) ON config.DepartmentID = dw.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND EntityID = @EntityID -- Entity is required at all times whether it's targeted or not + AND IsRecordDeleted = 0 + + INSERT INTO #DistinctCrosswalkConfiguration_WithAccount (BudgetConfigID, EntityGroupConfigID, DepartmentID, AccountID) + SELECT DISTINCT + BudgetConfigID, + EntityGroupConfigID, + DepartmentID, + AccountID + FROM #FilteredCrosswalkConfiguration fcc + + -- Filter to the distinct charge records so we don't duplicate charge records with the join. + INSERT INTO #DistinctCrosswalkConfiguration_WithoutAccount + (BudgetConfigID, EntityGroupConfigID, DepartmentID, ChargeCodeID, PatientClassID, PayorGroupID) + SELECT DISTINCT + BudgetConfigID, + EntityGroupConfigID, + DepartmentID, + ChargeCodeID, + PatientClassID, + PayorGroupID + FROM #FilteredCrosswalkConfiguration + + INSERT INTO #RolledUpValues (EntityID, DepartmentID, AccountID, InitialBudget01, InitialBudget02, InitialBudget03, + InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, + InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, + InitialProjection10, InitialProjection11, InitialProjection12) + SELECT DISTINCT + cv.EntityID, + cv.DepartmentID, + config.AccountID, + SUM(cv.InitialBudgetDollars01 * InitialBudgetMixPercentage) AS InitialBudget01, + SUM(cv.InitialBudgetDollars02 * InitialBudgetMixPercentage) AS InitialBudget02, + SUM(cv.InitialBudgetDollars03 * InitialBudgetMixPercentage) AS InitialBudget03, + SUM(cv.InitialBudgetDollars04 * InitialBudgetMixPercentage) AS InitialBudget04, + SUM(cv.InitialBudgetDollars05 * InitialBudgetMixPercentage) AS InitialBudget05, + SUM(cv.InitialBudgetDollars06 * InitialBudgetMixPercentage) AS InitialBudget06, + SUM(cv.InitialBudgetDollars07 * InitialBudgetMixPercentage) AS InitialBudget07, + SUM(cv.InitialBudgetDollars08 * InitialBudgetMixPercentage) AS InitialBudget08, + SUM(cv.InitialBudgetDollars09 * InitialBudgetMixPercentage) AS InitialBudget09, + SUM(cv.InitialBudgetDollars10 * InitialBudgetMixPercentage) AS InitialBudget10, + SUM(cv.InitialBudgetDollars11 * InitialBudgetMixPercentage) AS InitialBudget11, + SUM(cv.InitialBudgetDollars12 * InitialBudgetMixPercentage) AS InitialBudget12, + SUM(cv.InitialProjectionDollars01 * InitialProjectionMixPercentage) AS InitialProjection01, + SUM(cv.InitialProjectionDollars02 * InitialProjectionMixPercentage) AS InitialProjection02, + SUM(cv.InitialProjectionDollars03 * InitialProjectionMixPercentage) AS InitialProjection03, + SUM(cv.InitialProjectionDollars04 * InitialProjectionMixPercentage) AS InitialProjection04, + SUM(cv.InitialProjectionDollars05 * InitialProjectionMixPercentage) AS InitialProjection05, + SUM(cv.InitialProjectionDollars06 * InitialProjectionMixPercentage) AS InitialProjection06, + SUM(cv.InitialProjectionDollars07 * InitialProjectionMixPercentage) AS InitialProjection07, + SUM(cv.InitialProjectionDollars08 * InitialProjectionMixPercentage) AS InitialProjection08, + SUM(cv.InitialProjectionDollars09 * InitialProjectionMixPercentage) AS InitialProjection09, + SUM(cv.InitialProjectionDollars10 * InitialProjectionMixPercentage) AS InitialProjection10, + SUM(cv.InitialProjectionDollars11 * InitialProjectionMixPercentage) AS InitialProjection11, + SUM(cv.InitialProjectionDollars12 * InitialProjectionMixPercentage) AS InitialProjection12 + FROM fp.ChargeVolume cv WITH (READUNCOMMITTED) + INNER JOIN #mixTable mix WITH (READUNCOMMITTED) on + mix.PatientClassID = cv.PatientClassID + AND mix.EntityID = cv.ServiceEntityID + AND mix.EntityGroupConfigID = cv.EntityGroupConfigID + AND (@IsServiceLineEnabled = 0 OR mix.ServiceLineID = cv.ServiceLineID) + AND (@IsAdditionalDimensionalityEnabled = 0 OR mix.AgeCohortID = cv.AgeCohortID) + AND (@IsAdditionalDimensionalityEnabled = 0 OR mix.MedicalSurgicalID = cv.MedicalSurgicalID) + AND (@IsAdditionalDimensionalityEnabled = 0 OR mix.MSDRGID = cv.MSDRGID) + AND (@IsAdditionalDimensionalityEnabled = 0 OR mix.CPTID = cv.PrimaryCPTID) + AND (@IsAdditionalDimensionalityEnabled = 0 OR mix.ProviderID = cv.ServiceProviderID) + INNER JOIN #DistinctCrosswalkConfiguration_WithoutAccount dim ON + dim.BudgetConfigID = cv.BudgetConfigID + AND dim.EntityGroupConfigID = cv.EntityGroupConfigID + AND dim.DepartmentID = cv.DepartmentID + AND dim.ChargeCodeID = cv.ChargeCodeID + AND dim.PatientClassID = cv.PatientClassID + AND dim.PatientClassID = mix.PatientClassID + AND dim.PayorGroupID = mix.PayorGroupID + INNER JOIN #FilteredCrosswalkConfiguration config WITH (READUNCOMMITTED) ON + cv.DepartmentID = config.DepartmentID + AND cv.ChargeCodeID = config.ChargeCodeID + AND mix.PatientClassID = config.PatientClassID + AND mix.PayorGroupID = config.PayorGroupID + WHERE cv.EntityGroupConfigID = @EntityGroupConfigID + AND cv.EntityID = @EntityID + GROUP BY cv.EntityID, + cv.DepartmentID, + AccountID + OPTION (RECOMPILE) + + END + + IF (@IsDebug = 0) + BEGIN + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#DistinctCrosswalkConfiguration_WithoutAccount') IS NOT NULL DROP TABLE #DistinctCrosswalkConfiguration_WithoutAccount + + UPDATE gl + SET + InitialBudget01 = xwalk.InitialBudget01, + InitialBudget02 = xwalk.InitialBudget02, + InitialBudget03 = xwalk.InitialBudget03, + InitialBudget04 = xwalk.InitialBudget04, + InitialBudget05 = xwalk.InitialBudget05, + InitialBudget06 = xwalk.InitialBudget06, + InitialBudget07 = xwalk.InitialBudget07, + InitialBudget08 = xwalk.InitialBudget08, + InitialBudget09 = xwalk.InitialBudget09, + InitialBudget10 = xwalk.InitialBudget10, + InitialBudget11 = xwalk.InitialBudget11, + InitialBudget12 = xwalk.InitialBudget12 + FROM fp.GeneralLedger gl + INNER JOIN #RolledUpValues xwalk ON + gl.DepartmentID = xwalk.DepartmentID + AND gl.AccountID = xwalk.AccountID + WHERE gl.VariabilityID = 2 + AND gl.EntityGroupConfigID = @EntityGroupConfigID + AND ( gl.InitialBudget01 != xwalk.InitialBudget01 + OR gl.InitialBudget02 != xwalk.InitialBudget02 + OR gl.InitialBudget03 != xwalk.InitialBudget03 + OR gl.InitialBudget04 != xwalk.InitialBudget04 + OR gl.InitialBudget05 != xwalk.InitialBudget05 + OR gl.InitialBudget06 != xwalk.InitialBudget06 + OR gl.InitialBudget07 != xwalk.InitialBudget07 + OR gl.InitialBudget08 != xwalk.InitialBudget08 + OR gl.InitialBudget09 != xwalk.InitialBudget09 + OR gl.InitialBudget10 != xwalk.InitialBudget10 + OR gl.InitialBudget11 != xwalk.InitialBudget11 + OR gl.InitialBudget12 != xwalk.InitialBudget12 + ) + + DECLARE @i int = @MonthsLoaded + 1 + DECLARE @MonthsLoadedString CHAR(10) + SELECT @MonthsLoadedString = CAST(@i as CHAR(2)); + + DECLARE @sql varchar(max) = 'UPDATE gl SET ' + WHILE (@i <= 12) + BEGIN + SET @sql = @sql + 'gl.InitialProjection' + case when @i<10 then '0' else '' end +cast(@i as varchar(2))+' = xwalk.InitialProjection' + case when @i<10 then '0' else '' end +cast(@i as varchar(2))+CASE WHEN @i<12 THEN ',' ELSE '' END + SET @i = @i+1 + END + + SET @sql = @sql + ' + FROM fp.GeneralLedger gl + INNER JOIN #RolledUpValues xwalk ON + gl.DepartmentID = xwalk.DepartmentID + AND gl.AccountID = xwalk.AccountID + WHERE gl.VariabilityID = 2 + AND gl.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS VARCHAR(10)) + ' + AND ( + (gl.InitialProjection01 != xwalk.InitialProjection01 AND ' + @MonthsLoadedString + ' <= 1 ) + OR (gl.InitialProjection02 != xwalk.InitialProjection02 AND ' + @MonthsLoadedString + ' <= 2 ) + OR (gl.InitialProjection03 != xwalk.InitialProjection03 AND ' + @MonthsLoadedString + ' <= 3 ) + OR (gl.InitialProjection04 != xwalk.InitialProjection04 AND ' + @MonthsLoadedString + ' <= 4 ) + OR (gl.InitialProjection05 != xwalk.InitialProjection05 AND ' + @MonthsLoadedString + ' <= 5 ) + OR (gl.InitialProjection06 != xwalk.InitialProjection06 AND ' + @MonthsLoadedString + ' <= 6 ) + OR (gl.InitialProjection07 != xwalk.InitialProjection07 AND ' + @MonthsLoadedString + ' <= 7 ) + OR (gl.InitialProjection08 != xwalk.InitialProjection08 AND ' + @MonthsLoadedString + ' <= 8 ) + OR (gl.InitialProjection09 != xwalk.InitialProjection09 AND ' + @MonthsLoadedString + ' <= 9 ) + OR (gl.InitialProjection10 != xwalk.InitialProjection10 AND ' + @MonthsLoadedString + ' <= 10 ) + OR (gl.InitialProjection11 != xwalk.InitialProjection11 AND ' + @MonthsLoadedString + ' <= 11 ) + OR (gl.InitialProjection12 != xwalk.InitialProjection12 AND ' + @MonthsLoadedString + ' <= 12 ) + ) + ' + + EXEC (@sql); + + SET @i = @MonthsLoaded + 1; + SET @sql = 'UPDATE gl SET ' + WHILE (@i <= 12) + BEGIN + SET @sql = @sql + 'gl.InitialProjection' + CASE WHEN @i < 10 THEN '0' ELSE '' END + CAST(@i AS VARCHAR(2)) + ' = 0' + CASE WHEN @i < 12 THEN ',' ELSE '' END + SET @i = @i+1 + END + + SET @sql = @sql + ' + , ProjectionLockFlag = 1 + , ProjectionLockType = 3 + FROM fp.GeneralLedger gl + INNER JOIN #RolledUpValues xwalk ON + gl.DepartmentID = xwalk.DepartmentID + AND gl.AccountID = xwalk.AccountID + WHERE gl.VariabilityID = 1 + AND gl.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS VARCHAR(10)) + ' + AND ( + (gl.InitialProjection01 != 0 AND ' + @MonthsLoadedString + ' <= 1 ) + OR (gl.InitialProjection02 != 0 AND ' + @MonthsLoadedString + ' <= 2 ) + OR (gl.InitialProjection03 != 0 AND ' + @MonthsLoadedString + ' <= 3 ) + OR (gl.InitialProjection04 != 0 AND ' + @MonthsLoadedString + ' <= 4 ) + OR (gl.InitialProjection05 != 0 AND ' + @MonthsLoadedString + ' <= 5 ) + OR (gl.InitialProjection06 != 0 AND ' + @MonthsLoadedString + ' <= 6 ) + OR (gl.InitialProjection07 != 0 AND ' + @MonthsLoadedString + ' <= 7 ) + OR (gl.InitialProjection08 != 0 AND ' + @MonthsLoadedString + ' <= 8 ) + OR (gl.InitialProjection09 != 0 AND ' + @MonthsLoadedString + ' <= 9 ) + OR (gl.InitialProjection10 != 0 AND ' + @MonthsLoadedString + ' <= 10 ) + OR (gl.InitialProjection11 != 0 AND ' + @MonthsLoadedString + ' <= 11 ) + OR (gl.InitialProjection12 != 0 AND ' + @MonthsLoadedString + ' <= 12 ) + ) + ' + + EXEC (@sql); + + -- We 0 out any fixed portion for these crosswalked value + UPDATE gl + SET + InitialBudget01 = 0, + InitialBudget02 = 0, + InitialBudget03 = 0, + InitialBudget04 = 0, + InitialBudget05 = 0, + InitialBudget06 = 0, + InitialBudget07 = 0, + InitialBudget08 = 0, + InitialBudget09 = 0, + InitialBudget10 = 0, + InitialBudget11 = 0, + InitialBudget12 = 0 + FROM fp.GeneralLedger gl + INNER JOIN #RolledUpValues xwalk on gl.DepartmentID = xwalk.DepartmentID + AND gl.AccountID = xwalk.AccountID + WHERE gl.VariabilityID = 1 + AND gl.EntityGroupConfigID = @EntityGroupConfigID + AND ( + gl.InitialBudget01 != 0 + OR gl.InitialBudget02 != 0 + OR gl.InitialBudget03 != 0 + OR gl.InitialBudget04 != 0 + OR gl.InitialBudget05 != 0 + OR gl.InitialBudget06 != 0 + OR gl.InitialBudget07 != 0 + OR gl.InitialBudget08 != 0 + OR gl.InitialBudget09 != 0 + OR gl.InitialBudget10 != 0 + OR gl.InitialBudget11 != 0 + OR gl.InitialBudget12 != 0 + ) + + IF (@IsAdditionalDimensionalityEnabled = 1) + BEGIN + -- Update records that do not have a corresponding mix. These are records with a configuration record, but not a corresponding match between Charges and the Encounter mix + -- This can be for a few reasons, but one main reason is you have a config that does not directly map between the data (IE: It contains data in encounters and charges, however + -- the specified Payor Group does not exist) + UPDATE gl + SET + InitialBudget01 = 0, InitialBudget02 = 0, InitialBudget03 = 0, InitialBudget04 = 0, InitialBudget05 = 0, InitialBudget06 = 0, + InitialBudget07 = 0, InitialBudget08 = 0, InitialBudget09 = 0, InitialBudget10 = 0, InitialBudget11 = 0, InitialBudget12 = 0 + FROM fp.GeneralLedger gl + INNER JOIN #DistinctCrosswalkConfiguration_WithAccount config ON gl.BudgetConfigID = config.BudgetConfigID + AND gl.EntityGroupConfigID = config.EntityGroupConfigID + AND gl.DepartmentID = config.DepartmentID + AND gl.AccountID = config.AccountID + LEFT JOIN #RolledUpValues roll ON roll.EntityID = gl.EntityID + AND roll.DepartmentID = gl.DepartmentID + AND roll.AccountID = gl.AccountID + WHERE 1 = 1 + AND gl.EntityGroupConfigID = @EntityGroupConfigID + AND gl.FlexingTypeID = 4 -- Charge to GL Crosswalk + AND roll.AccountID IS NULL -- We only want records that are configured, but falled out of the value calc above + AND ( + gl.InitialBudget01 != 0 OR gl.InitialBudget02 != 0 OR gl.InitialBudget03 != 0 OR gl.InitialBudget04 != 0 OR gl.InitialBudget05 != 0 OR gl.InitialBudget06 != 0 + OR gl.InitialBudget07 != 0 OR gl.InitialBudget08 != 0 OR gl.InitialBudget09 != 0 OR gl.InitialBudget10 != 0 OR gl.InitialBudget11 != 0 OR gl.InitialBudget12 != 0 + ) + + SET @i = @MonthsLoaded + 1; + SET @sql = 'UPDATE gl SET ' + WHILE (@i <= 12) + BEGIN + SET @sql = @sql + 'gl.InitialProjection' + CASE WHEN @i < 10 THEN '0' ELSE '' END + CAST(@i AS VARCHAR(2)) + ' = 0' + CASE WHEN @i < 12 THEN ',' ELSE '' END + SET @i = @i+1 + END + + SET @sql = @sql + ' + FROM fp.GeneralLedger gl + INNER JOIN #DistinctCrosswalkConfiguration_WithAccount config ON gl.BudgetConfigID = config.BudgetConfigID + AND gl.EntityGroupConfigID = config.EntityGroupConfigID + AND gl.DepartmentID = config.DepartmentID + AND gl.AccountID = config.AccountID + LEFT JOIN #RolledUpValues roll ON roll.EntityID = gl.EntityID + AND roll.DepartmentID = gl.DepartmentID + AND roll.AccountID = gl.AccountID + WHERE gl.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS VARCHAR(10)) + ' + AND gl.FlexingTypeID = 4 + AND roll.AccountID IS NULL + AND ( + (gl.InitialProjection01 != 0 AND ' + @MonthsLoadedString + ' <= 1 ) + OR (gl.InitialProjection02 != 0 AND ' + @MonthsLoadedString + ' <= 2 ) + OR (gl.InitialProjection03 != 0 AND ' + @MonthsLoadedString + ' <= 3 ) + OR (gl.InitialProjection04 != 0 AND ' + @MonthsLoadedString + ' <= 4 ) + OR (gl.InitialProjection05 != 0 AND ' + @MonthsLoadedString + ' <= 5 ) + OR (gl.InitialProjection06 != 0 AND ' + @MonthsLoadedString + ' <= 6 ) + OR (gl.InitialProjection07 != 0 AND ' + @MonthsLoadedString + ' <= 7 ) + OR (gl.InitialProjection08 != 0 AND ' + @MonthsLoadedString + ' <= 8 ) + OR (gl.InitialProjection09 != 0 AND ' + @MonthsLoadedString + ' <= 9 ) + OR (gl.InitialProjection10 != 0 AND ' + @MonthsLoadedString + ' <= 10 ) + OR (gl.InitialProjection11 != 0 AND ' + @MonthsLoadedString + ' <= 11 ) + OR (gl.InitialProjection12 != 0 AND ' + @MonthsLoadedString + ' <= 12 ) + )'; + + EXEC (@sql) + END + END ELSE BEGIN + SELECT '@IsServiceLineEnabled', @IsServiceLineEnabled + SELECT '@IsAdditionalDimensionalityEnabled', @IsAdditionalDimensionalityEnabled + SELECT '#mixTable', * FROM #mixTable + SELECT '#DistinctCrosswalkConfiguration_WithAccount', * FROM #DistinctCrosswalkConfiguration_WithAccount + SELECT '#DistinctCrosswalkConfiguration_WithoutAccount', * FROM #DistinctCrosswalkConfiguration_WithoutAccount + SELECT '#RolledUpValues', * FROM #RolledUpValues + END + + END; +GO + + +--------------------------------------------- + +-- fp.procCrosswalkChargeToGeneralLedger_InitialValue +CREATE PROCEDURE [fp].[procCrosswalkChargeToGeneralLedger_InitialValue] + @EntityGroupConfigID INT, + @MonthsLoaded INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 + AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author BLI Description + ** 1 2021-03-10 BK JAZZ-16331 Create proc + ** 2 2022-08-04 NH JAZZ-41156 FP ORM produced error + ** 3 2023-04-06 MD JAZZ-52587 Update for new charge volume data structure + ** 4 2023-08-04 BW JAZZ-58151 Update for new GL data structure + ** 5 2024-01-23 BW JAZZ-65717 OnePlan - performance tuning for [procCrosswalkChargeToGeneralLedger_InitialValue] + ** 6 2024-09-11 MY JAZZ-75442 GL Data is locked with locktype 3 with no crosswalk configured for chosen entity group + *************************************************************/ + BEGIN + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#RecordsToCrosswalk') IS NOT NULL DROP TABLE #RecordsToCrosswalk + + CREATE TABLE #RecordsToCrosswalk(DepartmentID INT, AccountID INT, + InitialBudgetDollars01 DECIMAL(19,8), InitialBudgetDollars02 DECIMAL(19,8), InitialBudgetDollars03 DECIMAL(19,8), + InitialBudgetDollars04 DECIMAL(19,8), InitialBudgetDollars05 DECIMAL(19,8), InitialBudgetDollars06 DECIMAL(19,8), + InitialBudgetDollars07 DECIMAL(19,8), InitialBudgetDollars08 DECIMAL(19,8), InitialBudgetDollars09 DECIMAL(19,8), + InitialBudgetDollars10 DECIMAL(19,8), InitialBudgetDollars11 DECIMAL(19,8), InitialBudgetDollars12 DECIMAL(19,8), + InitialProjectionDollars01 DECIMAL(19,8), InitialProjectionDollars02 DECIMAL(19,8), InitialProjectionDollars03 DECIMAL(19,8), + InitialProjectionDollars04 DECIMAL(19,8), InitialProjectionDollars05 DECIMAL(19,8), InitialProjectionDollars06 DECIMAL(19,8), + InitialProjectionDollars07 DECIMAL(19,8), InitialProjectionDollars08 DECIMAL(19,8), InitialProjectionDollars09 DECIMAL(19,8), + InitialProjectionDollars10 DECIMAL(19,8), InitialProjectionDollars11 DECIMAL(19,8), InitialProjectionDollars12 DECIMAL(19,8) + ) + + IF (SELECT COUNT(*) FROM @SourceDimensionality) = 0 + BEGIN + + INSERT INTO #RecordsToCrosswalk (DepartmentID, AccountID, + InitialBudgetDollars01, InitialBudgetDollars02, InitialBudgetDollars03, + InitialBudgetDollars04, InitialBudgetDollars05, InitialBudgetDollars06, + InitialBudgetDollars07, InitialBudgetDollars08, InitialBudgetDollars09, + InitialBudgetDollars10, InitialBudgetDollars11, InitialBudgetDollars12, + InitialProjectionDollars01, InitialProjectionDollars02, InitialProjectionDollars03, + InitialProjectionDollars04, InitialProjectionDollars05, InitialProjectionDollars06, + InitialProjectionDollars07, InitialProjectionDollars08, InitialProjectionDollars09, + InitialProjectionDollars10, InitialProjectionDollars11, InitialProjectionDollars12 + ) + SELECT DISTINCT config.DepartmentID, config.AccountID, + SUM(cv.InitialBudgetDollars01), SUM(cv.InitialBudgetDollars02), SUM(cv.InitialBudgetDollars03), + SUM(cv.InitialBudgetDollars04), SUM(cv.InitialBudgetDollars05), SUM(cv.InitialBudgetDollars06), + SUM(cv.InitialBudgetDollars07), SUM(cv.InitialBudgetDollars08), SUM(cv.InitialBudgetDollars09), + SUM(cv.InitialBudgetDollars10), SUM(cv.InitialBudgetDollars11), SUM(cv.InitialBudgetDollars12), + SUM(cv.InitialProjectionDollars01), SUM(cv.InitialProjectionDollars02), SUM(cv.InitialProjectionDollars03), + SUM(cv.InitialProjectionDollars04), SUM(cv.InitialProjectionDollars05), SUM(cv.InitialProjectionDollars06), + SUM(cv.InitialProjectionDollars07), SUM(cv.InitialProjectionDollars08), SUM(cv.InitialProjectionDollars09), + SUM(cv.InitialProjectionDollars10), SUM(cv.InitialProjectionDollars11), SUM(cv.InitialProjectionDollars12) + FROM [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] config (readuncommitted) + INNER JOIN fp.ChargeVolume cv on config.DepartmentID = cv.DepartmentID + AND config.ChargeCodeID = cv.ChargeCodeID + AND config.PatientClassID = cv.PatientClassID + AND config.EntityGroupConfigID = cv.EntityGroupConfigID + WHERE config.EntityGroupConfigID = @EntityGroupConfigID + AND config.IsRecordDeleted = 0 + AND config.AccountID > 0 + GROUP BY config.DepartmentID, config.AccountID + OPTION (RECOMPILE); + END + ELSE + BEGIN + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + INSERT INTO #RecordsToCrosswalk (DepartmentID, AccountID, + InitialBudgetDollars01, InitialBudgetDollars02, InitialBudgetDollars03, + InitialBudgetDollars04, InitialBudgetDollars05, InitialBudgetDollars06, + InitialBudgetDollars07, InitialBudgetDollars08, InitialBudgetDollars09, + InitialBudgetDollars10, InitialBudgetDollars11, InitialBudgetDollars12, + InitialProjectionDollars01, InitialProjectionDollars02, InitialProjectionDollars03, + InitialProjectionDollars04, InitialProjectionDollars05, InitialProjectionDollars06, + InitialProjectionDollars07, InitialProjectionDollars08, InitialProjectionDollars09, + InitialProjectionDollars10, InitialProjectionDollars11, InitialProjectionDollars12 + ) + SELECT DISTINCT config.DepartmentID, config.AccountID, + SUM(cv.InitialBudgetDollars01), SUM(cv.InitialBudgetDollars02), SUM(cv.InitialBudgetDollars03), + SUM(cv.InitialBudgetDollars04), SUM(cv.InitialBudgetDollars05), SUM(cv.InitialBudgetDollars06), + SUM(cv.InitialBudgetDollars07), SUM(cv.InitialBudgetDollars08), SUM(cv.InitialBudgetDollars09), + SUM(cv.InitialBudgetDollars10), SUM(cv.InitialBudgetDollars11), SUM(cv.InitialBudgetDollars12), + SUM(cv.InitialProjectionDollars01), SUM(cv.InitialProjectionDollars02), SUM(cv.InitialProjectionDollars03), + SUM(cv.InitialProjectionDollars04), SUM(cv.InitialProjectionDollars05), SUM(cv.InitialProjectionDollars06), + SUM(cv.InitialProjectionDollars07), SUM(cv.InitialProjectionDollars08), SUM(cv.InitialProjectionDollars09), + SUM(cv.InitialProjectionDollars10), SUM(cv.InitialProjectionDollars11), SUM(cv.InitialProjectionDollars12) + FROM [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] config (readuncommitted) + INNER JOIN #FilterByDepartment ft ON config.DepartmentID = ft.DepartmentID + INNER JOIN fp.ChargeVolume cv on config.DepartmentID = cv.DepartmentID + AND config.ChargeCodeID = cv.ChargeCodeID + AND config.PatientClassID = cv.PatientClassID + AND config.EntityGroupConfigID = cv.EntityGroupConfigID + WHERE config.EntityGroupConfigID = @EntityGroupConfigID + AND config.IsRecordDeleted = 0 + AND config.AccountID > 0 + GROUP BY config.DepartmentID, config.AccountID + OPTION (RECOMPILE); + + DROP TABLE #FilterByDepartment + END + + IF (@IsDebug = 0) + BEGIN + UPDATE gl + SET InitialBudget01 = xwalk.InitialBudgetDollars01 + ,InitialBudget02 = xwalk.InitialBudgetDollars02 + ,InitialBudget03 = xwalk.InitialBudgetDollars03 + ,InitialBudget04 = xwalk.InitialBudgetDollars04 + ,InitialBudget05 = xwalk.InitialBudgetDollars05 + ,InitialBudget06 = xwalk.InitialBudgetDollars06 + ,InitialBudget07 = xwalk.InitialBudgetDollars07 + ,InitialBudget08 = xwalk.InitialBudgetDollars08 + ,InitialBudget09 = xwalk.InitialBudgetDollars09 + ,InitialBudget10 = xwalk.InitialBudgetDollars10 + ,InitialBudget11 = xwalk.InitialBudgetDollars11 + ,InitialBudget12 = xwalk.InitialBudgetDollars12 + ,InitialProjection01 = CASE WHEN @MonthsLoaded >= 1 THEN gl.InitialProjection01 ELSE xwalk.InitialProjectionDollars01 END + ,InitialProjection02 = CASE WHEN @MonthsLoaded >= 2 THEN gl.InitialProjection02 ELSE xwalk.InitialProjectionDollars01 END + ,InitialProjection03 = CASE WHEN @MonthsLoaded >= 3 THEN gl.InitialProjection03 ELSE xwalk.InitialProjectionDollars03 END + ,InitialProjection04 = CASE WHEN @MonthsLoaded >= 4 THEN gl.InitialProjection04 ELSE xwalk.InitialProjectionDollars04 END + ,InitialProjection05 = CASE WHEN @MonthsLoaded >= 5 THEN gl.InitialProjection05 ELSE xwalk.InitialProjectionDollars05 END + ,InitialProjection06 = CASE WHEN @MonthsLoaded >= 6 THEN gl.InitialProjection06 ELSE xwalk.InitialProjectionDollars06 END + ,InitialProjection07 = CASE WHEN @MonthsLoaded >= 7 THEN gl.InitialProjection07 ELSE xwalk.InitialProjectionDollars07 END + ,InitialProjection08 = CASE WHEN @MonthsLoaded >= 8 THEN gl.InitialProjection08 ELSE xwalk.InitialProjectionDollars08 END + ,InitialProjection09 = CASE WHEN @MonthsLoaded >= 9 THEN gl.InitialProjection09 ELSE xwalk.InitialProjectionDollars09 END + ,InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN gl.InitialProjection10 ELSE xwalk.InitialProjectionDollars10 END + ,InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN gl.InitialProjection11 ELSE xwalk.InitialProjectionDollars11 END + ,InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN gl.InitialProjection12 ELSE xwalk.InitialProjectionDollars12 END + + FROM fp.GeneralLedger gl + INNER JOIN #RecordsToCrosswalk xwalk on gl.DepartmentID = xwalk.DepartmentID + AND gl.AccountID = xwalk.AccountID + WHERE gl.VariabilityID = 2 AND gl.EntityGroupConfigID = @EntityGroupConfigID + + UPDATE gl + SET InitialBudget01 = 0 + ,InitialBudget02 = 0 + ,InitialBudget03 = 0 + ,InitialBudget04 = 0 + ,InitialBudget05 = 0 + ,InitialBudget06 = 0 + ,InitialBudget07 = 0 + ,InitialBudget08 = 0 + ,InitialBudget09 = 0 + ,InitialBudget10 = 0 + ,InitialBudget11 = 0 + ,InitialBudget12 = 0 + ,InitialProjection01 = CASE WHEN @MonthsLoaded >= 1 THEN gl.InitialProjection01 ELSE 0 END + ,InitialProjection02 = CASE WHEN @MonthsLoaded >= 2 THEN gl.InitialProjection02 ELSE 0 END + ,InitialProjection03 = CASE WHEN @MonthsLoaded >= 3 THEN gl.InitialProjection03 ELSE 0 END + ,InitialProjection04 = CASE WHEN @MonthsLoaded >= 4 THEN gl.InitialProjection04 ELSE 0 END + ,InitialProjection05 = CASE WHEN @MonthsLoaded >= 5 THEN gl.InitialProjection05 ELSE 0 END + ,InitialProjection06 = CASE WHEN @MonthsLoaded >= 6 THEN gl.InitialProjection06 ELSE 0 END + ,InitialProjection07 = CASE WHEN @MonthsLoaded >= 7 THEN gl.InitialProjection07 ELSE 0 END + ,InitialProjection08 = CASE WHEN @MonthsLoaded >= 8 THEN gl.InitialProjection08 ELSE 0 END + ,InitialProjection09 = CASE WHEN @MonthsLoaded >= 9 THEN gl.InitialProjection09 ELSE 0 END + ,InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN gl.InitialProjection10 ELSE 0 END + ,InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN gl.InitialProjection11 ELSE 0 END + ,InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN gl.InitialProjection12 ELSE 0 END + FROM fp.GeneralLedger gl + INNER JOIN #RecordsToCrosswalk xwalk on gl.DepartmentID = xwalk.DepartmentID + AND gl.AccountID = xwalk.AccountID + WHERE gl.VariabilityID = 1 AND gl.EntityGroupConfigID = @EntityGroupConfigID + END ELSE BEGIN + SELECT 'RecordsToCrosswalk', * FROM #RecordsToCrosswalk + END + + END +GO + + +--------------------------------------------- + +-- fp.procCrosswalkChargeUnitsToStats +CREATE PROCEDURE [fp].[procCrosswalkChargeUnitsToStats] @EntityGroupConfigID INT + ,@MonthsLoaded INT + ,@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + ,@IsDebug BIT = 0 +AS +BEGIN + exec [dbo].[procSysDropTempTable] '#itemsToFlex' + exec [dbo].[procSysDropTempTable] '#flexValues' + exec [dbo].[procSysDropTempTable] '#weightedUnitsTotal' + exec [dbo].[procSysDropTempTable] '#budget_basisIDs' + exec [dbo].[procSysDropTempTable] '#projection_basisIDs' + exec [dbo].[procSysDropTempTable] '#FilterByDepartment' + exec [dbo].[procSysDropTempTable] '#cv' + + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2018-07-04 IP B-19914 APE Data Refresh - Flexing Revenue and Statistics by DCV + ** 2 2018-10-19 BK D-07730 Fix check for change values to include all months instead of total + ** 3 2018-11-26 GF D-07835 Add source dimensionality param + ** 4 2018-12-16 MY B-21514 Converted to new config table + ** 5 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table + ** 6 2021-03-13 NN JAZZ-14116 Remove null joins + ** 7 2022-09-30 JB JAZZ-43489 Remove FlexedValue references + ** 8 2022-03-15 BW JAZZ-49994 Updated for new data model, use [fp].[ChargeVolume] + ** 8 2022-04-20 BK JAZZ------ Performance tuning based on testing + *************************************************************/ + CREATE TABLE #itemsToFlex ( + DepartmentID INT + ,StatAccountID INT + ,ChargeCodeID INT + ,PatientClassID INT + ) + CREATE TABLE #weightedUnitsTotal( + DepartmentID INT + ,PatientClassID INT + ,ChargeCodeID INT + ,AccountID INT + ,AdjustedTargetValue01 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedTargetValue02 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedTargetValue03 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedTargetValue04 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedTargetValue05 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedTargetValue06 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedTargetValue07 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedTargetValue08 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedTargetValue09 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedTargetValue10 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedTargetValue11 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedTargetValue12 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedBudgetValue01 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedBudgetValue02 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedBudgetValue03 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedBudgetValue04 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedBudgetValue05 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedBudgetValue06 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedBudgetValue07 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedBudgetValue08 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedBudgetValue09 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedBudgetValue10 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedBudgetValue11 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedBudgetValue12 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedProjectionValue01 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedProjectionValue02 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedProjectionValue03 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedProjectionValue04 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedProjectionValue05 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedProjectionValue06 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedProjectionValue07 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedProjectionValue08 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedProjectionValue09 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedProjectionValue10 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedProjectionValue11 DECIMAL(19,8) NOT NULL DEFAULT(0) + ,AdjustedProjectionValue12 DECIMAL(19,8) NOT NULL DEFAULT(0) + ) + + /* Based on performance testing, pulling cv data into the temp table reduced the time for this to run by 45 seconds */ + CREATE TABLE #cv ( DepartmentID int, ChargeCodeID int, PatientClassID int, + TargetAdjusted01 DECIMAL(19,8),TargetAdjusted02 DECIMAL(19,8),TargetAdjusted03 DECIMAL(19,8),TargetAdjusted04 DECIMAL(19,8),TargetAdjusted05 DECIMAL(19,8),TargetAdjusted06 DECIMAL(19,8),TargetAdjusted07 DECIMAL(19,8),TargetAdjusted08 DECIMAL(19,8),TargetAdjusted09 DECIMAL(19,8),TargetAdjusted10 DECIMAL(19,8),TargetAdjusted11 DECIMAL(19,8),TargetAdjusted12 DECIMAL(19,8), + BudgetAdjusted01 DECIMAL(19,8),BudgetAdjusted02 DECIMAL(19,8),BudgetAdjusted03 DECIMAL(19,8),BudgetAdjusted04 DECIMAL(19,8),BudgetAdjusted05 DECIMAL(19,8),BudgetAdjusted06 DECIMAL(19,8),BudgetAdjusted07 DECIMAL(19,8),BudgetAdjusted08 DECIMAL(19,8),BudgetAdjusted09 DECIMAL(19,8),BudgetAdjusted10 DECIMAL(19,8),BudgetAdjusted11 DECIMAL(19,8),BudgetAdjusted12 DECIMAL(19,8), + ProjectionAdjusted01 DECIMAL(19,8),ProjectionAdjusted02 DECIMAL(19,8),ProjectionAdjusted03 DECIMAL(19,8),ProjectionAdjusted04 DECIMAL(19,8),ProjectionAdjusted05 DECIMAL(19,8),ProjectionAdjusted06 DECIMAL(19,8),ProjectionAdjusted07 DECIMAL(19,8),ProjectionAdjusted08 DECIMAL(19,8),ProjectionAdjusted09 DECIMAL(19,8),ProjectionAdjusted10 DECIMAL(19,8),ProjectionAdjusted11 DECIMAL(19,8),ProjectionAdjusted12 DECIMAL(19,8) +) + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- Getting the department and accounts to flex by charge code budget (Once we either lock the screen or can target the adjustment we can target the flexing) + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #itemsToFlex (DepartmentID, StatAccountID, ChargeCodeID, PatientClassID) + SELECT DISTINCT fsc.DepartmentID, fsc.AccountID AS StatAccountID, fsc.ChargeCodeID, fsc.PatientClassID + FROM [fp].[ChargeToStatisticsCrosswalkConfiguration] fsc + WHERE fsc.EntityGroupConfigID = @EntityGroupConfigID AND fsc.AccountID > 0 + + INSERT INTO #cv + SELECT DepartmentID, ChargeCodeID, PatientClassID, + SUM(TargetAdjusted01),SUM(TargetAdjusted02),SUM(TargetAdjusted03),SUM(TargetAdjusted04),SUM(TargetAdjusted05),SUM(TargetAdjusted06),SUM(TargetAdjusted07),SUM(TargetAdjusted08),SUM(TargetAdjusted09),SUM(TargetAdjusted10),SUM(TargetAdjusted11),SUM(TargetAdjusted12), + SUM(BudgetAdjusted01),SUM(BudgetAdjusted02),SUM(BudgetAdjusted03),SUM(BudgetAdjusted04),SUM(BudgetAdjusted05),SUM(BudgetAdjusted06),SUM(BudgetAdjusted07),SUM(BudgetAdjusted08),SUM(BudgetAdjusted09),SUM(BudgetAdjusted10),SUM(BudgetAdjusted11),SUM(BudgetAdjusted12), + SUM(ProjectionAdjusted01),SUM(ProjectionAdjusted02),SUM(ProjectionAdjusted03),SUM(ProjectionAdjusted04),SUM(ProjectionAdjusted05),SUM(ProjectionAdjusted06),SUM(ProjectionAdjusted07),SUM(ProjectionAdjusted08),SUM(ProjectionAdjusted09),SUM(ProjectionAdjusted10),SUM(ProjectionAdjusted11),SUM(ProjectionAdjusted12) + FROM [fp].[ChargeVolume] WHERE UnitTypeID = 145 and EntityGroupConfigID = @EntityGroupConfigID + GROUP BY DepartmentID,PatientClassID,ChargeCodeID + END ELSE BEGIN + INSERT INTO #itemsToFlex (DepartmentID, StatAccountID, ChargeCodeID, PatientClassID) + SELECT DISTINCT fsc.DepartmentID, fsc.AccountID AS StatAccountID, fsc.ChargeCodeID, fsc.PatientClassID + FROM [fp].[ChargeToStatisticsCrosswalkConfiguration] fsc + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fsc.DepartmentID + WHERE fsc.EntityGroupConfigID = @EntityGroupConfigID AND fsc.AccountID > 0 + + INSERT INTO #cv + SELECT cv.DepartmentID, ChargeCodeID, PatientClassID, + SUM(TargetAdjusted01),SUM(TargetAdjusted02),SUM(TargetAdjusted03),SUM(TargetAdjusted04),SUM(TargetAdjusted05),SUM(TargetAdjusted06),SUM(TargetAdjusted07),SUM(TargetAdjusted08),SUM(TargetAdjusted09),SUM(TargetAdjusted10),SUM(TargetAdjusted11),SUM(TargetAdjusted12), + SUM(BudgetAdjusted01),SUM(BudgetAdjusted02),SUM(BudgetAdjusted03),SUM(BudgetAdjusted04),SUM(BudgetAdjusted05),SUM(BudgetAdjusted06),SUM(BudgetAdjusted07),SUM(BudgetAdjusted08),SUM(BudgetAdjusted09),SUM(BudgetAdjusted10),SUM(BudgetAdjusted11),SUM(BudgetAdjusted12), + SUM(ProjectionAdjusted01),SUM(ProjectionAdjusted02),SUM(ProjectionAdjusted03),SUM(ProjectionAdjusted04),SUM(ProjectionAdjusted05),SUM(ProjectionAdjusted06),SUM(ProjectionAdjusted07),SUM(ProjectionAdjusted08),SUM(ProjectionAdjusted09),SUM(ProjectionAdjusted10),SUM(ProjectionAdjusted11),SUM(ProjectionAdjusted12) + FROM [fp].[ChargeVolume] cv INNER JOIN #FilterByDepartment ft on ft.DepartmentID = cv.DepartmentID + WHERE UnitTypeID = 145 and EntityGroupConfigID = @EntityGroupConfigID + GROUP BY cv.DepartmentID,PatientClassID,ChargeCodeID + END + + + + -- get the total weight charge data by department/chargecode/fiscalmonth +INSERT INTO #weightedUnitsTotal (DepartmentID, PatientClassID, ChargeCodeID, AccountID + ,AdjustedTargetValue01 + ,AdjustedTargetValue02 + ,AdjustedTargetValue03 + ,AdjustedTargetValue04 + ,AdjustedTargetValue05 + ,AdjustedTargetValue06 + ,AdjustedTargetValue07 + ,AdjustedTargetValue08 + ,AdjustedTargetValue09 + ,AdjustedTargetValue10 + ,AdjustedTargetValue11 + ,AdjustedTargetValue12 + ,AdjustedBudgetValue01 + ,AdjustedBudgetValue02 + ,AdjustedBudgetValue03 + ,AdjustedBudgetValue04 + ,AdjustedBudgetValue05 + ,AdjustedBudgetValue06 + ,AdjustedBudgetValue07 + ,AdjustedBudgetValue08 + ,AdjustedBudgetValue09 + ,AdjustedBudgetValue10 + ,AdjustedBudgetValue11 + ,AdjustedBudgetValue12 + ,AdjustedProjectionValue01 + ,AdjustedProjectionValue02 + ,AdjustedProjectionValue03 + ,AdjustedProjectionValue04 + ,AdjustedProjectionValue05 + ,AdjustedProjectionValue06 + ,AdjustedProjectionValue07 + ,AdjustedProjectionValue08 + ,AdjustedProjectionValue09 + ,AdjustedProjectionValue10 + ,AdjustedProjectionValue11 + ,AdjustedProjectionValue12 + ) + SELECT + config.DepartmentID + ,config.PatientClassID + ,config.ChargeCodeID + ,config.StatAccountID AS AccountID + ,ISNULL(SUM(cv.TargetAdjusted01 * fsc.RVUWeight), 0) AS AdjustedTargetValue01 + ,ISNULL(SUM(cv.TargetAdjusted02 * fsc.RVUWeight), 0) AS AdjustedTargetValue02 + ,ISNULL(SUM(cv.TargetAdjusted03 * fsc.RVUWeight), 0) AS AdjustedTargetValue03 + ,ISNULL(SUM(cv.TargetAdjusted04 * fsc.RVUWeight), 0) AS AdjustedTargetValue04 + ,ISNULL(SUM(cv.TargetAdjusted05 * fsc.RVUWeight), 0) AS AdjustedTargetValue05 + ,ISNULL(SUM(cv.TargetAdjusted06 * fsc.RVUWeight), 0) AS AdjustedTargetValue06 + ,ISNULL(SUM(cv.TargetAdjusted07 * fsc.RVUWeight), 0) AS AdjustedTargetValue07 + ,ISNULL(SUM(cv.TargetAdjusted08 * fsc.RVUWeight), 0) AS AdjustedTargetValue08 + ,ISNULL(SUM(cv.TargetAdjusted09 * fsc.RVUWeight), 0) AS AdjustedTargetValue09 + ,ISNULL(SUM(cv.TargetAdjusted10 * fsc.RVUWeight), 0) AS AdjustedTargetValue10 + ,ISNULL(SUM(cv.TargetAdjusted11 * fsc.RVUWeight), 0) AS AdjustedTargetValue11 + ,ISNULL(SUM(cv.TargetAdjusted12 * fsc.RVUWeight), 0) AS AdjustedTargetValue12 + ,ISNULL(SUM(cv.BudgetAdjusted01 * fsc.RVUWeight), 0) AS AdjustedBudgetValue01 + ,ISNULL(SUM(cv.BudgetAdjusted02 * fsc.RVUWeight), 0) AS AdjustedBudgetValue02 + ,ISNULL(SUM(cv.BudgetAdjusted03 * fsc.RVUWeight), 0) AS AdjustedBudgetValue03 + ,ISNULL(SUM(cv.BudgetAdjusted04 * fsc.RVUWeight), 0) AS AdjustedBudgetValue04 + ,ISNULL(SUM(cv.BudgetAdjusted05 * fsc.RVUWeight), 0) AS AdjustedBudgetValue05 + ,ISNULL(SUM(cv.BudgetAdjusted06 * fsc.RVUWeight), 0) AS AdjustedBudgetValue06 + ,ISNULL(SUM(cv.BudgetAdjusted07 * fsc.RVUWeight), 0) AS AdjustedBudgetValue07 + ,ISNULL(SUM(cv.BudgetAdjusted08 * fsc.RVUWeight), 0) AS AdjustedBudgetValue08 + ,ISNULL(SUM(cv.BudgetAdjusted09 * fsc.RVUWeight), 0) AS AdjustedBudgetValue09 + ,ISNULL(SUM(cv.BudgetAdjusted10 * fsc.RVUWeight), 0) AS AdjustedBudgetValue10 + ,ISNULL(SUM(cv.BudgetAdjusted11 * fsc.RVUWeight), 0) AS AdjustedBudgetValue11 + ,ISNULL(SUM(cv.BudgetAdjusted12 * fsc.RVUWeight), 0) AS AdjustedBudgetValue12 + ,ISNULL(SUM(cv.ProjectionAdjusted01 * fsc.RVUWeight), 0) AS AdjustedProjectionValue01 + ,ISNULL(SUM(cv.ProjectionAdjusted02 * fsc.RVUWeight), 0) AS AdjustedProjectionValue02 + ,ISNULL(SUM(cv.ProjectionAdjusted03 * fsc.RVUWeight), 0) AS AdjustedProjectionValue03 + ,ISNULL(SUM(cv.ProjectionAdjusted04 * fsc.RVUWeight), 0) AS AdjustedProjectionValue04 + ,ISNULL(SUM(cv.ProjectionAdjusted05 * fsc.RVUWeight), 0) AS AdjustedProjectionValue05 + ,ISNULL(SUM(cv.ProjectionAdjusted06 * fsc.RVUWeight), 0) AS AdjustedProjectionValue06 + ,ISNULL(SUM(cv.ProjectionAdjusted07 * fsc.RVUWeight), 0) AS AdjustedProjectionValue07 + ,ISNULL(SUM(cv.ProjectionAdjusted08 * fsc.RVUWeight), 0) AS AdjustedProjectionValue08 + ,ISNULL(SUM(cv.ProjectionAdjusted09 * fsc.RVUWeight), 0) AS AdjustedProjectionValue09 + ,ISNULL(SUM(cv.ProjectionAdjusted10 * fsc.RVUWeight), 0) AS AdjustedProjectionValue10 + ,ISNULL(SUM(cv.ProjectionAdjusted11 * fsc.RVUWeight), 0) AS AdjustedProjectionValue11 + ,ISNULL(SUM(cv.ProjectionAdjusted12 * fsc.RVUWeight), 0) AS AdjustedProjectionValue12 + FROM #itemsToFlex config + INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] fsc + ON fsc.DepartmentID = config.DepartmentID + AND fsc.ChargeCodeID = config.ChargeCodeID + AND fsc.PatientClassID = config.PatientClassID + AND fsc.AccountID = config.StatAccountID + LEFT JOIN #cv cv + ON cv.DepartmentID = config.DepartmentID + AND cv.ChargeCodeID = config.ChargeCodeID + AND cv.PatientClassID = config.PatientClassID + WHERE fsc.EntityGroupConfigID = @EntityGroupConfigID + GROUP BY config.DepartmentID, + config.PatientClassID, + config.ChargeCodeID, + config.StatAccountID + +SELECT + basis.StatisticsID + ,SUM(ISNULL(abb.AdjustedTargetValue01, 0)) AS AdjustedTargetValue01 + ,SUM(ISNULL(abb.AdjustedTargetValue02, 0)) AS AdjustedTargetValue02 + ,SUM(ISNULL(abb.AdjustedTargetValue03, 0)) AS AdjustedTargetValue03 + ,SUM(ISNULL(abb.AdjustedTargetValue04, 0)) AS AdjustedTargetValue04 + ,SUM(ISNULL(abb.AdjustedTargetValue05, 0)) AS AdjustedTargetValue05 + ,SUM(ISNULL(abb.AdjustedTargetValue06, 0)) AS AdjustedTargetValue06 + ,SUM(ISNULL(abb.AdjustedTargetValue07, 0)) AS AdjustedTargetValue07 + ,SUM(ISNULL(abb.AdjustedTargetValue08, 0)) AS AdjustedTargetValue08 + ,SUM(ISNULL(abb.AdjustedTargetValue09, 0)) AS AdjustedTargetValue09 + ,SUM(ISNULL(abb.AdjustedTargetValue10, 0)) AS AdjustedTargetValue10 + ,SUM(ISNULL(abb.AdjustedTargetValue11, 0)) AS AdjustedTargetValue11 + ,SUM(ISNULL(abb.AdjustedTargetValue12, 0)) AS AdjustedTargetValue12 + ,SUM(ISNULL(abb.AdjustedBudgetValue01, 0)) AS AdjustedBudgetValue01 + ,SUM(ISNULL(abb.AdjustedBudgetValue02, 0)) AS AdjustedBudgetValue02 + ,SUM(ISNULL(abb.AdjustedBudgetValue03, 0)) AS AdjustedBudgetValue03 + ,SUM(ISNULL(abb.AdjustedBudgetValue04, 0)) AS AdjustedBudgetValue04 + ,SUM(ISNULL(abb.AdjustedBudgetValue05, 0)) AS AdjustedBudgetValue05 + ,SUM(ISNULL(abb.AdjustedBudgetValue06, 0)) AS AdjustedBudgetValue06 + ,SUM(ISNULL(abb.AdjustedBudgetValue07, 0)) AS AdjustedBudgetValue07 + ,SUM(ISNULL(abb.AdjustedBudgetValue08, 0)) AS AdjustedBudgetValue08 + ,SUM(ISNULL(abb.AdjustedBudgetValue09, 0)) AS AdjustedBudgetValue09 + ,SUM(ISNULL(abb.AdjustedBudgetValue10, 0)) AS AdjustedBudgetValue10 + ,SUM(ISNULL(abb.AdjustedBudgetValue11, 0)) AS AdjustedBudgetValue11 + ,SUM(ISNULL(abb.AdjustedBudgetValue12, 0)) AS AdjustedBudgetValue12 + ,SUM(ISNULL(abb.AdjustedProjectionValue01, 0)) AS AdjustedProjectionValue01 + ,SUM(ISNULL(abb.AdjustedProjectionValue02, 0)) AS AdjustedProjectionValue02 + ,SUM(ISNULL(abb.AdjustedProjectionValue03, 0)) AS AdjustedProjectionValue03 + ,SUM(ISNULL(abb.AdjustedProjectionValue04, 0)) AS AdjustedProjectionValue04 + ,SUM(ISNULL(abb.AdjustedProjectionValue05, 0)) AS AdjustedProjectionValue05 + ,SUM(ISNULL(abb.AdjustedProjectionValue06, 0)) AS AdjustedProjectionValue06 + ,SUM(ISNULL(abb.AdjustedProjectionValue07, 0)) AS AdjustedProjectionValue07 + ,SUM(ISNULL(abb.AdjustedProjectionValue08, 0)) AS AdjustedProjectionValue08 + ,SUM(ISNULL(abb.AdjustedProjectionValue09, 0)) AS AdjustedProjectionValue09 + ,SUM(ISNULL(abb.AdjustedProjectionValue10, 0)) AS AdjustedProjectionValue10 + ,SUM(ISNULL(abb.AdjustedProjectionValue11, 0)) AS AdjustedProjectionValue11 + ,SUM(ISNULL(abb.AdjustedProjectionValue12, 0)) AS AdjustedProjectionValue12 + INTO #flexValues + FROM [fp].[FactStatistics] basis + INNER JOIN #itemsToFlex fm + ON basis.DepartmentID = fm.DepartmentID + AND basis.AccountID = fm.StatAccountID + LEFT JOIN #weightedUnitsTotal abb + ON basis.DepartmentID = abb.DepartmentID + AND fm.PatientClassID = abb.PatientClassID + AND fm.ChargeCodeID = abb.ChargeCodeID + AND fm.StatAccountID = abb.AccountID + WHERE basis.EntityGroupConfigID = @EntityGroupConfigID + GROUP BY basis.StatisticsID + + IF (@IsDebug = 0) + BEGIN + -- Flex the appropriate departments + + UPDATE basis + SET basis.AdjustedValue01 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue01 ELSE flexed.AdjustedBudgetValue01 END + ,basis.AdjustedValue02 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue02 ELSE flexed.AdjustedBudgetValue02 END + ,basis.AdjustedValue03 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue03 ELSE flexed.AdjustedBudgetValue03 END + ,basis.AdjustedValue04 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue04 ELSE flexed.AdjustedBudgetValue04 END + ,basis.AdjustedValue05 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue05 ELSE flexed.AdjustedBudgetValue05 END + ,basis.AdjustedValue06 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue06 ELSE flexed.AdjustedBudgetValue06 END + ,basis.AdjustedValue07 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue07 ELSE flexed.AdjustedBudgetValue07 END + ,basis.AdjustedValue08 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue08 ELSE flexed.AdjustedBudgetValue08 END + ,basis.AdjustedValue09 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue09 ELSE flexed.AdjustedBudgetValue09 END + ,basis.AdjustedValue10 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue10 ELSE flexed.AdjustedBudgetValue10 END + ,basis.AdjustedValue11 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue11 ELSE flexed.AdjustedBudgetValue11 END + ,basis.AdjustedValue12 = CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue12 ELSE flexed.AdjustedBudgetValue12 END + ,basis.LockFlag = 1 + ,basis.LockType = 3 + FROM [fp].[FactStatisticsBudget] basis + INNER JOIN #flexValues flexed + ON basis.StatisticsID = flexed.StatisticsID + -- AND basis.BudgetPhaseID = flexed.BudgetPhaseID + WHERE + basis.AdjustedValue01 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue01 ELSE flexed.AdjustedBudgetValue01 END + OR basis.AdjustedValue02 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue02 ELSE flexed.AdjustedBudgetValue02 END + OR basis.AdjustedValue03 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue03 ELSE flexed.AdjustedBudgetValue03 END + OR basis.AdjustedValue04 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue04 ELSE flexed.AdjustedBudgetValue04 END + OR basis.AdjustedValue05 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue05 ELSE flexed.AdjustedBudgetValue05 END + OR basis.AdjustedValue06 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue06 ELSE flexed.AdjustedBudgetValue06 END + OR basis.AdjustedValue07 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue07 ELSE flexed.AdjustedBudgetValue07 END + OR basis.AdjustedValue08 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue08 ELSE flexed.AdjustedBudgetValue08 END + OR basis.AdjustedValue09 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue09 ELSE flexed.AdjustedBudgetValue09 END + OR basis.AdjustedValue10 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue10 ELSE flexed.AdjustedBudgetValue10 END + OR basis.AdjustedValue11 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue11 ELSE flexed.AdjustedBudgetValue11 END + OR basis.AdjustedValue12 != CASE WHEN basis.BudgetPhaseID = 2 THEN flexed.AdjustedTargetValue12 ELSE flexed.AdjustedBudgetValue12 END + OR basis.LockFlag = 0 + + + DECLARE @i int = @MonthsLoaded + 1 -- (starting from month that should be changed.) + DECLARE @MonthsLoadedString CHAR(10) + SELECT @MonthsLoadedString = CAST(@i as CHAR(2)); + DECLARE @sql varchar(max) = 'UPDATE basis SET ' + WHILE (@i <= 12) + BEGIN + SET @sql = @sql + 'basis.AdjustedValue' + case when @i < 10 then '0' else '' end +cast(@i as varchar(2))+' = flexed.AdjustedProjectionValue' + case when @i < 10 then '0' else '' end +cast(@i as varchar(2)) + CASE WHEN @i < 12 THEN ', ' ELSE '' END + SET @i = @i + 1 + END + + SET @sql = @sql + ' + , basis.LockFlag = 1 + , basis.LockType = 3 + FROM [fp].[FactStatisticsProjection] basis + INNER JOIN #flexValues flexed + ON basis.StatisticsID = flexed.StatisticsID + --AND basis.BudgetPhaseID = flexed.BudgetPhaseID + WHERE + (basis.AdjustedValue01 != flexed.AdjustedProjectionValue01 AND ' + @MonthsLoadedString + ' <= 1 ) + OR (basis.AdjustedValue02 != flexed.AdjustedProjectionValue02 AND ' + @MonthsLoadedString + ' <= 2 ) + OR (basis.AdjustedValue03 != flexed.AdjustedProjectionValue03 AND ' + @MonthsLoadedString + ' <= 3 ) + OR (basis.AdjustedValue04 != flexed.AdjustedProjectionValue04 AND ' + @MonthsLoadedString + ' <= 4 ) + OR (basis.AdjustedValue05 != flexed.AdjustedProjectionValue05 AND ' + @MonthsLoadedString + ' <= 5 ) + OR (basis.AdjustedValue06 != flexed.AdjustedProjectionValue06 AND ' + @MonthsLoadedString + ' <= 6 ) + OR (basis.AdjustedValue07 != flexed.AdjustedProjectionValue07 AND ' + @MonthsLoadedString + ' <= 7 ) + OR (basis.AdjustedValue08 != flexed.AdjustedProjectionValue08 AND ' + @MonthsLoadedString + ' <= 8 ) + OR (basis.AdjustedValue09 != flexed.AdjustedProjectionValue09 AND ' + @MonthsLoadedString + ' <= 9 ) + OR (basis.AdjustedValue10 != flexed.AdjustedProjectionValue10 AND ' + @MonthsLoadedString + ' <= 10 ) + OR (basis.AdjustedValue11 != flexed.AdjustedProjectionValue11 AND ' + @MonthsLoadedString + ' <= 11 ) + OR (basis.AdjustedValue12 != flexed.AdjustedProjectionValue12 AND ' + @MonthsLoadedString + ' <= 12 ) + OR basis.LockFlag = 0 + ' + + EXEC (@sql) + + END + ELSE + BEGIN + SELECT 'ItemsToFlex', * FROM #itemsToFlex + SELECT 'WeightedUnitTotal', * FROM #weightedUnitTotal + SELECT 'FlexedValues', * FROM #flexValues + END + +END +GO + + +--------------------------------------------- + +-- fp.procCrosswalkChargeUnitsToStats_InitialValue +CREATE PROCEDURE [fp].[procCrosswalkChargeUnitsToStats_InitialValue] + @EntityGroupConfigID INT, + @MonthsLoaded INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 + AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table + ** 2 2021-03-13 NN JAZZ-14116 Remove null joins + ** 3 2022-03-15 BW JAZZ-49994 Updated for new data model, use [fp].[ChargeVolume] + *************************************************************/ + BEGIN + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #itemsToFlex(DepartmentID INT, StatAccountID INT, ChargeCodeID INT, PatientClassID INT) + + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #itemsToFlex(DepartmentID, StatAccountID, ChargeCodeID, PatientClassID) + SELECT DISTINCT fsc.DepartmentID, fsc.AccountID, fsc.ChargeCodeID, fsc.PatientClassID + FROM [fp].[ChargeToStatisticsCrosswalkConfiguration] fsc + WHERE fsc.EntityGroupConfigID = @EntityGroupConfigID and fsc.AccountID > 0 + END ELSE BEGIN + INSERT INTO #itemsToFlex(DepartmentID, StatAccountID, ChargeCodeID, PatientClassID) + SELECT DISTINCT fsc.DepartmentID, fsc.AccountID, fsc.ChargeCodeID, fsc.PatientClassID + FROM [fp].[ChargeToStatisticsCrosswalkConfiguration] fsc + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fsc.DepartmentID + WHERE fsc.EntityGroupConfigID = @EntityGroupConfigID and fsc.AccountID > 0 + END + + + + -- get the total weight charge data by department/chargecode/fiscalmonth + SELECT + flex.DepartmentID, + flex.PatientClassID, + flex.ChargeCodeID, + flex.StatAccountID, + ISNULL(SUM(cv.InitialBudget01 * csc.RVUWeight), 0) As InitialBudget01, + ISNULL(SUM(cv.InitialBudget02 * csc.RVUWeight), 0) As InitialBudget02, + ISNULL(SUM(cv.InitialBudget03 * csc.RVUWeight), 0) As InitialBudget03, + ISNULL(SUM(cv.InitialBudget04 * csc.RVUWeight), 0) As InitialBudget04, + ISNULL(SUM(cv.InitialBudget05 * csc.RVUWeight), 0) As InitialBudget05, + ISNULL(SUM(cv.InitialBudget06 * csc.RVUWeight), 0) As InitialBudget06, + ISNULL(SUM(cv.InitialBudget07 * csc.RVUWeight), 0) As InitialBudget07, + ISNULL(SUM(cv.InitialBudget08 * csc.RVUWeight), 0) As InitialBudget08, + ISNULL(SUM(cv.InitialBudget09 * csc.RVUWeight), 0) As InitialBudget09, + ISNULL(SUM(cv.InitialBudget10 * csc.RVUWeight), 0) As InitialBudget10, + ISNULL(SUM(cv.InitialBudget11 * csc.RVUWeight), 0) As InitialBudget11, + ISNULL(SUM(cv.InitialBudget12 * csc.RVUWeight), 0) As InitialBudget12, + ISNULL(SUM(cv.InitialProjection01 * csc.RVUWeight), 0) As InitialProjection01, + ISNULL(SUM(cv.InitialProjection02 * csc.RVUWeight), 0) As InitialProjection02, + ISNULL(SUM(cv.InitialProjection03 * csc.RVUWeight), 0) As InitialProjection03, + ISNULL(SUM(cv.InitialProjection04 * csc.RVUWeight), 0) As InitialProjection04, + ISNULL(SUM(cv.InitialProjection05 * csc.RVUWeight), 0) As InitialProjection05, + ISNULL(SUM(cv.InitialProjection06 * csc.RVUWeight), 0) As InitialProjection06, + ISNULL(SUM(cv.InitialProjection07 * csc.RVUWeight), 0) As InitialProjection07, + ISNULL(SUM(cv.InitialProjection08 * csc.RVUWeight), 0) As InitialProjection08, + ISNULL(SUM(cv.InitialProjection09 * csc.RVUWeight), 0) As InitialProjection09, + ISNULL(SUM(cv.InitialProjection10 * csc.RVUWeight), 0) As InitialProjection10, + ISNULL(SUM(cv.InitialProjection11 * csc.RVUWeight), 0) As InitialProjection11, + ISNULL(SUM(cv.InitialProjection12 * csc.RVUWeight), 0) As InitialProjection12 + INTO #weightedUnitTotal + FROM #itemsToFlex flex + INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] csc + ON flex.DepartmentID = csc.DepartmentID + AND flex.ChargeCodeID = csc.ChargeCodeID + AND flex.PatientClassID = csc.PatientClassID + AND flex.StatAccountID = csc.AccountID + AND csc.EntityGroupConfigID = @EntityGroupConfigID + LEFT JOIN [fp].[ChargeVolume] cv + ON cv.DepartmentID = flex.DepartmentID + AND cv.ChargeCodeID = flex.ChargeCodeID + AND cv.PatientClassID = flex.PatientClassID + AND cv.UnitTypeID = 145 + AND cv.EntityGroupConfigID = @EntityGroupConfigID + GROUP BY + flex.DepartmentID, + flex.PatientClassID, + flex.ChargeCodeID, + flex.StatAccountID + + SELECT + basis.StatisticsID, + SUM(abb.InitialBudget01) AS InitialBudget01, + SUM(abb.InitialBudget02) AS InitialBudget02, + SUM(abb.InitialBudget03) AS InitialBudget03, + SUM(abb.InitialBudget04) AS InitialBudget04, + SUM(abb.InitialBudget05) AS InitialBudget05, + SUM(abb.InitialBudget06) AS InitialBudget06, + SUM(abb.InitialBudget07) AS InitialBudget07, + SUM(abb.InitialBudget08) AS InitialBudget08, + SUM(abb.InitialBudget09) AS InitialBudget09, + SUM(abb.InitialBudget10) AS InitialBudget10, + SUM(abb.InitialBudget11) AS InitialBudget11, + SUM(abb.InitialBudget12) AS InitialBudget12, + SUM(abb.InitialProjection01) AS InitialProjection01, + SUM(abb.InitialProjection02) AS InitialProjection02, + SUM(abb.InitialProjection03) AS InitialProjection03, + SUM(abb.InitialProjection04) AS InitialProjection04, + SUM(abb.InitialProjection05) AS InitialProjection05, + SUM(abb.InitialProjection06) AS InitialProjection06, + SUM(abb.InitialProjection07) AS InitialProjection07, + SUM(abb.InitialProjection08) AS InitialProjection08, + SUM(abb.InitialProjection09) AS InitialProjection09, + SUM(abb.InitialProjection10) AS InitialProjection10, + SUM(abb.InitialProjection11) AS InitialProjection11, + SUM(abb.InitialProjection12) AS InitialProjection12 + INTO #flexedValues + FROM [fp].[FactStatistics] basis + INNER JOIN #itemsToFlex fm ON basis.DepartmentID = fm.DepartmentID AND basis.AccountID = fm.StatAccountID + INNER JOIN #weightedUnitTotal abb + ON basis.DepartmentID = abb.DepartmentID + AND fm.PatientClassID = abb.PatientClassID + AND fm.ChargeCodeID = abb.ChargeCodeID + AND fm.StatAccountID = abb.StatAccountID + WHERE basis.EntityGroupConfigID = @EntityGroupConfigID + GROUP BY basis.StatisticsID + + + IF (@IsDebug = 0) + BEGIN + + -- Flex + UPDATE basis + SET basis.InitialBudget01 = flexed.InitialBudget01, + basis.InitialBudget02 = flexed.InitialBudget02, + basis.InitialBudget03 = flexed.InitialBudget03, + basis.InitialBudget04 = flexed.InitialBudget04, + basis.InitialBudget05 = flexed.InitialBudget05, + basis.InitialBudget06 = flexed.InitialBudget06, + basis.InitialBudget07 = flexed.InitialBudget07, + basis.InitialBudget08 = flexed.InitialBudget08, + basis.InitialBudget09 = flexed.InitialBudget09, + basis.InitialBudget10 = flexed.InitialBudget10, + basis.InitialBudget11 = flexed.InitialBudget11, + basis.InitialBudget12 = flexed.InitialBudget12, + basis.InitialProjection01 = CASE WHEN @MonthsLoaded >= 1 THEN basis.InitialProjection01 ELSE flexed.InitialProjection01 END, + basis.InitialProjection02 = CASE WHEN @MonthsLoaded >= 2 THEN basis.InitialProjection02 ELSE flexed.InitialProjection02 END, + basis.InitialProjection03 = CASE WHEN @MonthsLoaded >= 3 THEN basis.InitialProjection03 ELSE flexed.InitialProjection03 END, + basis.InitialProjection04 = CASE WHEN @MonthsLoaded >= 4 THEN basis.InitialProjection04 ELSE flexed.InitialProjection04 END, + basis.InitialProjection05 = CASE WHEN @MonthsLoaded >= 5 THEN basis.InitialProjection05 ELSE flexed.InitialProjection05 END, + basis.InitialProjection06 = CASE WHEN @MonthsLoaded >= 6 THEN basis.InitialProjection06 ELSE flexed.InitialProjection06 END, + basis.InitialProjection07 = CASE WHEN @MonthsLoaded >= 7 THEN basis.InitialProjection07 ELSE flexed.InitialProjection07 END, + basis.InitialProjection08 = CASE WHEN @MonthsLoaded >= 8 THEN basis.InitialProjection08 ELSE flexed.InitialProjection08 END, + basis.InitialProjection09 = CASE WHEN @MonthsLoaded >= 9 THEN basis.InitialProjection09 ELSE flexed.InitialProjection09 END, + basis.InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN basis.InitialProjection10 ELSE flexed.InitialProjection10 END, + basis.InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN basis.InitialProjection11 ELSE flexed.InitialProjection11 END, + basis.InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN basis.InitialProjection12 ELSE flexed.InitialProjection12 END + FROM [fp].[FactStatistics] basis + INNER JOIN #flexedValues flexed + ON basis.StatisticsID = flexed.StatisticsID + WHERE basis.EntityGroupConfigID = @EntityGroupConfigID + + END ELSE BEGIN + + SELECT 'ItemsToFlex', * FROM #itemsToFlex + SELECT 'WeightedUnitTotal', * FROM #weightedUnitTotal + SELECT 'FlexedValues', * FROM #flexedValues + + END + + END +GO + + +--------------------------------------------- + +-- fp.procDataRefreshMethodPreActions +CREATE PROCEDURE fp.procDataRefreshMethodPreActions + @BudgetConfigID INT, + @SourceID INT, + @AdjustmentGUID UNIQUEIDENTIFIER, + @DataRefreshMethodName NVARCHAR(MAX), + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + AS + BEGIN + + SET NOCOUNT ON; + + /******************* PLEASE READ BEFORE UPDATING THIS PROC ****************** + + When adding to the proc, please do the following: + - Create a defect + - Create a migration updating this proc with the workaround + - When updating this migration, include the defect number and breif summary + + ****************************************************************************/ + + -- This proc runs before any datarefresh method and can be customized to workaround a specific issue. + + END +GO + + +--------------------------------------------- + +-- fp.procDataViewRegisterDimensions +CREATE proc [fp].[procDataViewRegisterDimensions] + @dvguid uniqueidentifier +as + declare @rdguid uniqueidentifier + declare @dvsql nvarchar(200) + select @dvsql = replace(replace(SQLViewName, '[', ''), ']', '') from DataView where DataViewGUID = @dvguid + + --department + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentID')) begin + print @dvsql + ' - Registering DepartmentID' + + declare @departmentDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'Department') + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Department' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Department' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Department' when a.SQLColumnName = 'Description' then 'Department Description' else isnull(da.FriendlyName, a.FriendlyName) end + from viewScoreAttribute a + join ScoreAttributeSetting attrSet on a.DimensionGUID = attrSet.DimensionGUID and a.AttributeGuid = attrSet.AttributeGuid + left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID + where + a.DimensionGUID = @departmentDimGuid + and ( + (a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 5) and a.SQLColumnName not like '%IsDefined') + or a.SQLColumnName in('Name', 'DepartmentCode') + or attrSet.OBIsUsed = 1 + ) + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --budget config + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'BudgetConfigID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'BudgetConfigID')) begin + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'BudgetConfigID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Budget Config' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Budget Config' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Budget Config' when a.SQLColumnName = 'Description' then 'Budget Config Description' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Budget Config' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID' and a.SQLColumnName != 'OBDollarsFinancialReportingCategory') or a.SQLColumnName in('Name', 'BudgetConfigCode', 'OBModelSectionName', 'OBUnitsFinancialReporting', 'OBUnitsFinancialReportingLineName', 'OBUnitsFinancialReportingSortOrder', 'OBPayor', 'OBPayorGroup', 'OBUnitType', 'PatientClass')) + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --account + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'AccountID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'AccountID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering AccountID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'AccountID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Account' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Account' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Account' when a.SQLColumnName = 'Description' then 'Account Description' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Account' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID' and a.SQLColumnName != 'OBDollarsFinancialReportingCategory') or a.SQLColumnName in('Name', 'AccountCode', 'OBModelSectionName', 'OBUnitsFinancialReporting', 'OBUnitsFinancialReportingLineName', 'OBUnitsFinancialReportingSortOrder', 'OBPayor', 'OBPayorGroup', 'OBUnitType', 'PatientClass', 'GMAccountRollup1', 'GMAccountRollup2', 'GMAccountRollup3', 'GMAccountRollup4', 'GMAccountRollup5', 'GMAccountRollup6') or (@dvsql not like '%statistic%' and a.SQLColumnName in('OBDollarsFinancialReporting', 'OBDollarsFinancialReportingLineName', 'OBDollarsFinancialReportingCategory', 'OBDollarsFinancialReportingSortOrder'))) + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --job code + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'JobCodeID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'JobCodeID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering JobCodeID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'JobCodeID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Job Code' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Job Code' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Job Code Name' when a.SQLColumnName = 'Description' then 'Job Code Description' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Job Code' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName in('Name', 'JobCodeGroup')) + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --pay code + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'PayCodeID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'PayCodeID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering PayCodeID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'PayCodeID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Pay Code' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Pay Code' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Pay Code Name' when a.SQLColumnName = 'Description' then 'Pay Code Description' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Pay Code' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName in('Name', 'PayCodeGroup')) + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --pay code group + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'PayCodeGroupID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'PayCodeGroupID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering PayCodeGroupID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'PayCodeGroupID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Pay Code Group' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Pay Code Group' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Pay Code Group' when a.SQLColumnName = 'Description' then 'Pay Code Group Description' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Pay Code Group' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName in('Name', 'PayClass', 'IsPremium', 'IsOvertime', 'IsAgency', 'IsDirect', 'ProductiveClass')) + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --employee + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'EmployeeID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'EmployeeID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering EmployeeID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'EmployeeID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Employee' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Employee' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Employee' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Employee' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName = 'Name') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --variability + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'VariabilityID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'VariabilityID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering VariabilityID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'VariabilityID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Variability' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Variability' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Variability' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Variability' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName = 'Name') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --time class + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'TimeClassID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'TimeClassID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering TimeClassID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'TimeClassID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Time Class' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Time Class' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Time Class' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Time Class' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName = 'Name') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --Patient class + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'PatientClassID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'PatientClassID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering PatientClassID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'PatientClassID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Patient Class' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Patient Class' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Patient Class' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Patient Class' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName = 'Name') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --fiscal year + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'FiscalYearID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'FiscalYearID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering FiscalYearID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'FiscalYearID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Fiscal Year' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Fiscal Year' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Fiscal Year' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Fiscal Year' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName = 'Name') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --fiscal month + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'FiscalMonthID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'FiscalMonthID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering FiscalMonthID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'FiscalMonthID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Fiscal Month' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Fiscal Month' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Fiscal Month' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Fiscal Month' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName in('Name', 'FiscalMonthCode')) + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --date + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DateID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DateID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering DateID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DateID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Date' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Date' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Date' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Date' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName in('Name', 'CalendarDateTime', 'CalendarMonth', 'CalendarMonthName', 'CalendarYear', 'DayNameOfWeek', 'DayNumberOfMonth', 'FiscalYear', 'IsWeekDay')) + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --unit type + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'UnitTypeID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'UnitTypeID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering UnitTypeID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'UnitTypeID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Unit Type' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Unit Type' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Unit Type' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Unit Type' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName = 'Name') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --provider + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'ProviderID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'ProviderID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering ProviderID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'ProviderID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Provider' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Provider' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Provider' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Provider' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName in('Name', 'NameFirst', 'NameLast', 'ProviderCode', 'Type', 'WorkWeekOverrideID')) + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --physician specialty + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'PhysicianSpecialtyID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'PhysicianSpecialtyID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering PhysicianSpecialtyID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'PhysicianSpecialtyID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Physician Specialty' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Physician Specialty' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Physician Specialty' when a.SQLColumnName = 'Description' then 'Physician Specialty Description' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Physician Specialty' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID' and a.SQLColumnName not in('RVUTarget', 'SpecialtyGroup')) or a.SQLColumnName in('Name', 'PhysicianSpecialtyCode', 'Description')) + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --OB Forecast Detail + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'OBForecastDetailID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'OBForecastDetailID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering OBForecastDetailID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'OBForecastDetailID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'OB Forecast Detail' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'OB Forecast Detail' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'OB Forecast Detail' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'OB Forecast Detail' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName ='Name') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --System + declare @systemGUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'System') + + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'SystemID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'SystemID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering SystemID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'SystemID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'System' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DimensionGUID = rd.DimensionGUID where d.GlobalID = 'System' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'System' when a.SQLColumnName = 'Code' then 'System Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @systemGUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --Entity + declare @entityGUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'Entity') + + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'EntityID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'EntityID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering EntityID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'EntityID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Entity' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Entity' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Entity' when a.SQLColumnName = 'Code' then 'Entity Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @entityGUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --Department Rollup 1 + declare @departmentRollup1GUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'Department Rollup 1') + + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentRollup1ID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentRollup1ID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering DepartmentRollup1ID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentRollup1ID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Department Rollup 1' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Department Rollup 1' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Department Rollup 1' when a.SQLColumnName = 'Code' then 'Department Rollup 1 Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @departmentRollup1GUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --Department Rollup 2 + declare @departmentRollup2GUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'Department Rollup 2') + + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentRollup2ID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentRollup2ID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering DepartmentRollup2ID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentRollup2ID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Department Rollup 2' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Department Rollup 2' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Department Rollup 2' when a.SQLColumnName = 'Code' then 'Department Rollup 2 Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @departmentRollup2GUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --Department Rollup 3 + declare @departmentRollup3GUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'Department Rollup 3') + + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentRollup3ID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentRollup3ID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering DepartmentRollup3ID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentRollup3ID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Department Rollup 3' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Department Rollup 3' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Department Rollup 3' when a.SQLColumnName = 'Code' then 'Department Rollup 3 Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @departmentRollup3GUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --Department Rollup 4 + declare @departmentRollup4GUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'Department Rollup 4') + + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentRollup4ID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentRollup4ID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering DepartmentRollup4ID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentRollup4ID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Department Rollup 4' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Department Rollup 4' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Department Rollup 4' when a.SQLColumnName = 'Code' then 'Department Rollup 4 Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @departmentRollup4GUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --Department Rollup 5 + declare @departmentRollup5GUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'Department Rollup 5') + + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentRollup5ID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentRollup5ID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering DepartmentRollup5ID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentRollup5ID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Department Rollup 5' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Department Rollup 5' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Department Rollup 5' when a.SQLColumnName = 'Code' then 'Department Rollup 5 Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @departmentRollup5GUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --Department Rollup 6 + declare @departmentRollup6GUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'Department Rollup 6') + + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentRollup6ID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentRollup6ID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering DepartmentRollup6ID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentRollup6ID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Department Rollup 6' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Department Rollup 6' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Department Rollup 6' when a.SQLColumnName = 'Code' then 'Department Rollup 6 Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @departmentRollup6GUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --remove duplicates + while (exists(select max(a.registeredattributeguid) from resqlreportregisteredattribute a inner join resqlreportregistereddimension d on d.registereddimensionguid = a.registereddimensionguid where d.DataViewGUID = @dvguid group by d.registereddimensionguid, a.attributeguid having count(*) > 1)) begin + delete from resqlreportregisteredattribute where registeredattributeguid in(select max(a.registeredattributeguid) from resqlreportregisteredattribute a inner join resqlreportregistereddimension d on d.registereddimensionguid = a.registereddimensionguid where d.DataViewGUID = @dvguid group by d.registereddimensionguid, a.attributeguid having count(*) > 1) + end + + --ensure default security + insert into S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) + select @dvguid, g.UserGroupGUID, 1, 0, 0 from UserGroup g where g.Name = 'OB - System Administrator' + and not exists(select 1 from S3SimplePermission ex where ex.LootID = @dvguid and ex.IdentityGUID = g.UserGroupGUID) +GO + + +--------------------------------------------- + +-- fp.procDeductionsByGrossChargesFlexConfigPopulation +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-06-12 IP B-19913 APE Data Refresh - Flex Mappings, add parameter to process particular departments +** 2 2018-07-03 IP TK-59678 fix case when @SourceDimensionality is empty +** 3 2018-09-11 apukii TK-62350 fixed typo in code +** 4 2018-09-25 GF E-02313 Simplify source dimensionality to only department +** 5 2019-03-08 IP B-22295 Removed using table variables, small optimizations +** 6 20201-03-26 NT JAZZ-14122 Simplify code and remove null joins on targeting object +** 7 8-11-2023 NT JAZZ-58154 Data restructure changes +*************************************************************/ +CREATE PROCEDURE [fp].[procDeductionsByGrossChargesFlexConfigPopulation] + @EntityGroupConfigGUID UNIQUEIDENTIFIER, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + DECLARE @BudgetConfigID INT, + @EntityGroupConfigID INT, + @TotalGrossCharges INT, + @FlexTypeID INT + + CREATE TABLE #flexMap (DepartmentID int NOT NULL, GLAccountID int NOT NULL) + + SET @BudgetConfigID = (SELECT bc.BudgetConfigID + FROM [fp].[EntityGroupConfig] egc + INNER JOIN [fp].[BudgetConfig] bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID) + + SET @EntityGroupConfigID = (SELECT EntityGroupConfigID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID) + SET @TotalGrossCharges = 8; + SET @FlexTypeID = 6; + + CREATE TABLE #SourceDimensionality (DepartmentID int) + + + -- Currently overrides is not a thing on deductions yet, so whatever the department is set to is what wins. + -- We just need to find the deduction accounts that are being flexed by total gross charges. Gross Charges By Patient Class will come later + + /* + check if @SourceDimensionality not is empty, then use filter, else - skip using table + */ + IF EXISTS (select 1 from @SourceDimensionality) + BEGIN + INSERT INTO #SourceDimensionality (DepartmentID) + SELECT DepartmentID FROM @SourceDimensionality + END ELSE BEGIN + INSERT INTO #SourceDimensionality (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[GeneralLedger] fgl + WHERE fgl.APEModelSectionID = 4 + AND fgl.BudgetConfigID = @BudgetConfigID + AND fgl.VariabilityID = 2 + END + + INSERT INTO #flexMap(DepartmentID, GLAccountID) + SELECT DISTINCT fgl.DepartmentID, fgl.AccountID AS GLAccountID + FROM [fp].[GeneralLedger] fgl + INNER JOIN [fp].[DeductionsFlexingConfig] dfc ON dfc.DepartmentID = fgl.DepartmentID + INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID = dfc.EntityGroupConfigGUID + INNER JOIN [fw].[DimAccount] a ON fgl.AccountID = a.AccountID + INNER JOIN #SourceDimensionality SD on SD.DepartmentID = fgl.DepartmentID + WHERE fgl.APEModelSectionID = 4 + AND dfc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND dfc.FlexMethodID = @TotalGrossCharges + AND fgl.BudgetConfigID = @BudgetConfigID + AND fgl.VariabilityID = 2; + + + + ;WITH TRG AS + ( + SELECT fcm.EntityGroupConfigID,fcm.DepartmentID,fcm.GLAccountID,fcm.FlexingTypeID + FROM [fp].[FlexConfigMapping] fcm + INNER JOIN #SourceDimensionality SD + ON SD.DepartmentID = fcm.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID AND FlexingTypeID = @FlexTypeID + ) + MERGE TRG + USING (SELECT @EntityGroupConfigID AS EntityGroupConfigID, + DepartmentID, + GLAccountID, + @FlexTypeID AS FlexingTypeID + FROM #flexMap) AS Src ON TRG.DepartmentID = SRC.DepartmentID and TRG.GLAccountID = SRC.GLAccountID + WHEN NOT MATCHED BY TARGET THEN + INSERT VALUES (src.EntityGroupConfigID,src.DepartmentID,src.GLAccountID,src.FlexingTypeID) + WHEN NOT MATCHED BY SOURCE THEN DELETE; + + END +GO + + +--------------------------------------------- + +-- fp.procDeleteOrphanAPESectionRoleAccessData +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-07-26 NH JAZZ-35199 Clean up orphan data +*************************************************************/ +CREATE PROCEDURE fp.procDeleteOrphanAPESectionRoleAccessData +AS +BEGIN + DELETE sra FROM [fp].[APESectionRoleAccess] sra + LEFT JOIN [dbo].[UserRole] ur ON sra.RoleID = ur.RoleID + WHERE ur.RoleID IS NULL +END +GO + + +--------------------------------------------- + +-- fp.procDeleteSnapshotDataGeneralLedger +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2024-10-22 MY JAZZ-77735 Initial Creation +** 2 2024-11-04 MY JAZZ-77737 Delete Reporting Data +***************************************************************/ +CREATE PROCEDURE [fp].[procDeleteSnapshotDataGeneralLedger] + @SnapshotID INT +AS +BEGIN + DECLARE @ChunkCount INT; + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 400000 END; + DECLARE @r INT; + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + + DELETE TOP (@ChunkCount) gl + FROM [fp].[GeneralLedgerSnapshot] gl + WHERE SnapshotID = @SnapshotID + + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + + DELETE TOP (@ChunkCount) gl + FROM [fp].[FactReportGeneralLedgerSnapshot] gl + WHERE SnapshotID = @SnapshotID + + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + + DELETE TOP (@ChunkCount) gl + FROM [fp].[FactReportGeneralLedgerDataTransferSnapshot] gl + WHERE SnapshotID = @SnapshotID + + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END +END +GO + + +--------------------------------------------- + +-- fp.procDependentStatisticsByDriverStatisticsFlexConfigPopulation +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2020-14-12 MY JAZZ-11324 Initial +** 2 2021-22-12 OP JAZZ-30940 Make dependent data sample ignoring IsUsingProviderStats +** 3 2023-13-06 MY JAZZ-53443 Update stats sampling for cross department stats flexing +** 4 2023-19-09 MY JAZZ-60117 Updating flexing to support mix of cross dept flexing and non cross dept flexing +** 5 2023-23-10 MY JAZZ-62535 For Driver > Dependent Flexing without cross department flexing, join on Department +*************************************************************/ +CREATE PROCEDURE [fp].[procDependentStatisticsByDriverStatisticsFlexConfigPopulation] + @EntityGroupConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + -- IMPORTANT NOTE: You may notice that here we're breaking it down by Entity Group Config despite that Provider Sampling is all broken + -- out by budget config. The reason for this is how the current flexing engine works. It processes each flexing type by entity because most + -- of them are by entity. If we were to break this out by budget config, we would have to build out an entirely new flexing process outside of the + -- normal process in order do this which would leave gaps for potential issues. So instead we just parse out the entity groups. + + DECLARE @BudgetConfigID INT, + @FlexTypeID INT + + SET @BudgetConfigID = (SELECT bc.BudgetConfigID + FROM [fp].[EntityGroupConfig] egc + INNER JOIN [fp].[BudgetConfig] bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE EntityGroupConfigID = @EntityGroupConfigID) + SET @FlexTypeID = 8; + + CREATE TABLE #flexMap ( + EntityGroupConfigID INT NOT NULL, + DepartmentID INT NOT NULL, + DriverAccountID INT NOT NULL, + DependentStatisticAccountID INT NOT NULL, + SourceDepartmentID INT NOT NULL + ); + + CREATE TABLE #SourceDimensionality (DepartmentID int) + INSERT INTO #SourceDimensionality (DepartmentID) + SELECT DepartmentID FROM @SourceDimensionality + + IF NOT EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #SourceDimensionality (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[FactStatistics] + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND SubsectionID = 2 -- Dependent + END + + -- We need to find accounts that meet the following criteria + -- 1. The Department must be configured to use Provider + -- 2. Provider sampling must be turned on (this is handled in code since it's just a feature flag) + -- 3. The account combination must be setup as a dependent stat. Accounts labeled as Drivers only are ignored + -- 4. The account combination must exist in FactStatistics for the Department/Driver/Depdendent to appear + + -- Populate flex config mapping where we are using cross department flexing. In this case, Source Department (Driver) may be different than Dependent Department. + INSERT INTO #flexMap (EntityGroupConfigID, DepartmentID, DriverAccountID, DependentStatisticAccountID, SourceDepartmentID) + SELECT DISTINCT depend.EntityGroupConfigID, dsad.DepartmentID, dsa.DriverAccountID, dsa.DependentAccountID, dsa.SourceDepartmentID + FROM [fp].[DependentStatisticsAccount] dsa + INNER JOIN [fp].[DependentStatisticsAccountDepartment] dsad ON dsad.DependentStatisticsAccountID = dsa.DependentStatisticsAccountID + INNER JOIN #SourceDimensionality SD on SD.DepartmentID = dsad.DepartmentID + -- Validating that the driver account exists for the given department otherwise don't populate it + INNER JOIN [fp].[FactStatistics] driver ON driver.BudgetConfigID = dsa.BudgetConfigID AND driver.AccountID = dsa.DriverAccountID AND driver.DepartmentID = dsa.SourceDepartmentID AND driver.SubSectionID = 1 -- Driver + -- Validating that the dependent account exists for the given department otherwise don't populate it + INNER JOIN [fp].[FactStatistics] depend ON depend.BudgetConfigID = dsa.BudgetConfigID AND depend.AccountID = dsa.DependentAccountID AND depend.DepartmentID = dsad.DepartmentID AND depend.SubSectionID = 2 -- Dependent + WHERE driver.BudgetConfigID = @BudgetConfigID + AND driver.UnitTypeID = 140 + AND depend.BudgetConfigID = @BudgetConfigID + AND depend.UnitTypeID = 140 + AND depend.EntityGroupConfigID = @EntityGroupConfigID + + -- Populate Flex Config mapping where not using Cross Department Flexing + INSERT INTO #flexMap (EntityGroupConfigID, DepartmentID, DriverAccountID, DependentStatisticAccountID, SourceDepartmentID) + SELECT DISTINCT depend.EntityGroupConfigID, depend.DepartmentID, dsa.DriverAccountID, dsa.DependentAccountID, depend.DepartmentID + FROM [fp].[FactStatistics] depend + INNER JOIN #SourceDimensionality SD on SD.DepartmentID = depend.DepartmentID + INNER JOIN [fp].[DependentStatisticsAccount] dsa ON depend.BudgetConfigID = dsa.BudgetConfigID AND depend.AccountID = dsa.DependentAccountID -- Validating that the dependent account exists for the given department otherwise don't populate it + -- Validating that the driver account exists for the given department otherwise don't populate it + INNER JOIN [fp].[FactStatistics] driver ON driver.BudgetConfigID = dsa.BudgetConfigID AND driver.AccountID = dsa.DriverAccountID AND driver.DepartmentID = depend.DepartmentID AND driver.SubSectionID = 1 -- Driver + LEFT JOIN [fp].[DependentStatisticsAccountDepartment] dsad ON dsad.DependentStatisticsAccountID = dsa.DependentStatisticsAccountID + LEFT JOIN #flexMap fm ON fm.DepartmentID = depend.DepartmentID AND fm.DependentStatisticAccountID = depend.AccountID + WHERE depend.BudgetConfigID = @BudgetConfigID + AND depend.UnitTypeID = 140 + AND depend.SubSectionID = 2 -- Dependent + AND depend.EntityGroupConfigID = @EntityGroupConfigID + AND dsad.RowID IS NULL + AND fm.DepartmentID IS NULL -- Verify the Department doesn't already exist in here from Cross Department Flexing + + IF (@IsDebug = 0) + BEGIN + ;WITH TRG + AS ( + SELECT + fcm.EntityGroupConfigID, + fcm.DepartmentID, + fcm.StatAccountID, + fcm.DependentStatisticAccountID, + fcm.FlexingTypeID, + fcm.SourceDepartmentID + FROM [fp].[FlexConfigMapping] fcm + INNER JOIN #SourceDimensionality SD ON SD.DepartmentID = fcm.DepartmentID -- NOTE: There may be better ways to handle this merge to get rid of the null condition like this. For now leaving it because the others had it. + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND FlexingTypeID = @FlexTypeID + ) + + MERGE TRG + USING ( + SELECT EntityGroupConfigID, + DepartmentID, + DriverAccountID, + DependentStatisticAccountID, + @FlexTypeID AS FlexingTypeID, + SourceDepartmentID + FROM #flexMap + ) AS Src ON TRG.EntityGroupConfigID = SRC.EntityGroupConfigID + AND TRG.DepartmentID = SRC.DepartmentID + AND TRG.DependentStatisticAccountID = SRC.DependentStatisticAccountID + AND TRG.StatAccountID = SRC.DriverAccountID + AND TRG.SourceDepartmentID = SRC.SourceDepartmentID + WHEN NOT MATCHED BY TARGET THEN + INSERT VALUES (src.EntityGroupConfigID, src.DepartmentID, src.DriverAccountID, src.DependentStatisticAccountID, src.FlexingTypeID, src.SourceDepartmentID) + WHEN NOT MATCHED BY SOURCE THEN DELETE; + END ELSE BEGIN + SELECT DepartmentID FROM #SourceDimensionality + SELECT EntityGroupConfigID, DepartmentID, DriverAccountID, DependentStatisticAccountID, SourceDepartmentID FROM #flexMap + END + +END +GO + + +--------------------------------------------- + +-- fp.procEditRosterAdjustment +/************************************************************************************************************************* +** Change History +************************************************************************************************************************** +** CID Date Author WI Description +** 1 11/13/17 MY B-17923 Creates a Dummy Proc for Roster Changes +*************************************************************************************************************************/ +CREATE PROCEDURE fp.procEditRosterAdjustment + @DepartmentID INT, + @PayCodeGroupID INT, + @Value DECIMAL(19, 4), + @Field NVARCHAR(100), + @JobCodeID INT, + @EmployeeID INT +AS +BEGIN + -- Enter Any Logic that is needed for after saving a Roster Adjustment + PRINT '' +END +GO + + +--------------------------------------------- + +-- fp.procEncounterBudgetStampOff +CREATE PROCEDURE [fp].[procEncounterBudgetStampOff] + @BudgetConfigID INT, + @TargetTimeClassID TINYINT +AS +BEGIN + /******************************************************************************* + ** Change History + ******************************************************************************** + ** CID Date Author WI Description + ** 1 01-31-2023 MY JAZZ-48962 Initial Creation + ** 2 03-28-2023 BK JAZZ-51558 Update to use new table structure + ** 3 01-03-2024 MZ JAZZ-65385 Added Target TimeClass + ** 4 03-18-2024 MZ JAZZ-68428 Deleting by Chunks & removed HistoryItemGUID parameter + *******************************************************************************/ + + -- Note: The original script was done here https://confluence.sdt.local/display/DD/Moving+Data+from+a+Plan+Configuration+to+Int+Tables + + DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID ) + DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID) + + DECLARE @HistoryItemGUID UNIQUEIDENTIFIER + EXEC procLogScript 'StampOff: Transferring Budget Data from 1p', @HistoryItemGUID OUTPUT + PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36)) + PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID) + + -- Clear out existing records for the selected FiscalYear and Budgeted Time Class + DECLARE @ChunkCount INT + + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END + + DECLARE @r INT; + SET @r = 1; + + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) [int].[FactServiceLine] WHERE FiscalYearID = @FiscalYear and TimeClassID = @TargetTimeClassID + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + INSERT INTO [int].[FactServiceLine] ([TimeClassID], [TimeClassCode], [FiscalYearID], [FiscalYearCode], [FiscalMonthID], + [FiscalMonthCode], [EntityID], [EntityCode], [PatientClassID], [PatientClassCode], [ServiceLineID], [ServiceLine], [AgeCohortID], + [AgeCohort], [MedicalSurgicalID], [MedSurg], [DepartmentID], [DepartmentCode], [OBForecastDetailID], [ForecastDetail], [PayorGroupID], + [PayorID], [Value], [IsDeleted], [HistoryItemGUID],[PayorGroupCode], [PayorCode]) + SELECT + @TargetTimeClassID AS [TimeClassID], + @TimeClassCode AS [TimeClassCode], + bc.[FiscalYearID], + bc.[FiscalYearID] AS [FiscalYearCode], + FM.[FiscalMonthID], + FM.[FiscalMonthCode], + FE.[EntityID], + et.Code AS EntityCode, + pt.[PatientClassID], + pt.Code AS [PatientClassCode], + SL.[ServiceLineID], + SL.code AS [ServiceLine], + AG.AgeCohortID AS AgeCohortID, + AG.Code AS AgeCohort, + MS.MedicalSurgicalID AS MedicalSurgicalID, + MS.Code AS MedSurg, + dep.[DepartmentID], + dep.[DepartmentCode], + FD.[OBForecastDetailID], + fd.Name AS [ForecastDetail], + FE.[PayorGroupID], + FE.[PayorID], + [Value], + 0 AS [IsDeleted], + @HistoryItemGUID AS [HistoryItemGUID], + PG.[PayorGroupCode], + PY.[PayorCode] +FROM ( + SELECT ServiceLineEncounterID, BudgetConfigID, DepartmentID, EntityID, PatientClassID, AgeCohortID, MedicalSurgicalID, ServiceLineID, PayorGroupID, PayorID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT sle.ServiceLineEncounterID, sle.BudgetConfigID, sle.DepartmentID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.PayorGroupID, sle.PayorID, sle.AgeCohortID, sle.MedicalSurgicalID, sle.UnitTypeID, + BudgetAdjusted01, BudgetAdjusted02, BudgetAdjusted03, BudgetAdjusted04, + BudgetAdjusted05, BudgetAdjusted06, BudgetAdjusted07, BudgetAdjusted08, + BudgetAdjusted09, BudgetAdjusted10, BudgetAdjusted11, BudgetAdjusted12 + FROM fp.ServiceLineEncounter sle + WHERE BudgetConfigID = @BudgetConfigID + ) sle + UNPIVOT (Value FOR FiscalMonth IN (BudgetAdjusted01, BudgetAdjusted02, BudgetAdjusted03, BudgetAdjusted04, BudgetAdjusted05, BudgetAdjusted06, BudgetAdjusted07, BudgetAdjusted08, BudgetAdjusted09, BudgetAdjusted10, BudgetAdjusted11, BudgetAdjusted12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'BudgetAdjusted', 'Month') + ) FE + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = FE.BudgetConfigID + INNER JOIN [fw].[DimFiscalMonth] FM ON FM.FiscalMonthID = FE.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = FE.DepartmentID + INNER JOIN [fw].[DimEntity] et ON et.EntityID = FE.EntityID + INNER JOIN [fw].[DimAgeCohort] AG ON AG.AgeCohortID = FE.AgeCohortID + INNER JOIN [fw].[DimMedicalSurgical] MS ON MS.MedicalSurgicalID = FE.MedicalSurgicalID + INNER JOIN [fw].[DimPatientClass] PT ON PT.PatientClassID = FE.PatientClassID + INNER JOIN [fw].[DimServiceLine] SL ON SL.ServiceLineID = FE.ServiceLineID -- Primary serice line dimension for OB definitions + INNER JOIN [ob].[DimOBForecastDetail] FD ON FD.OBForecastDetailID = 36 -- Encounters + INNER JOIN [fw].[DimPayorGroup] PG ON PG.PayorGroupID = FE.PayorGroupID + INNER JOIN [fw].[DimPayor] PY ON PY.PayorID = FE.PayorID + WHERE 1=1 + and FE.Value <> 0 + and bc.BudgetConfigID = @BudgetConfigID +END +GO + + +--------------------------------------------- + +-- fp.procEncounterProjectionStampOff +CREATE PROCEDURE [fp].[procEncounterProjectionStampOff] + @BudgetConfigID INT, + @TargetTimeClassID TINYINT, + @IsMonthsLoadedIncluded BIT +AS +BEGIN + /******************************************************************************* + ** Change History + ******************************************************************************** + ** CID Date Author WI Description + ** 1 11-08-2023 AO JAZZ-62128 Initial Creation + ** 2 01-03-2024 MZ JAZZ-65385 Added Target TimeClass + ** 3 01-24-2024 MZ JAZZ-64527 Fix Months Loaded + ** 4 03-18-2024 MZ JAZZ-68428 Deleting by Chunks & removed HistoryItemGUID parameter + ** 5 04-03-2024 MZ JAZZ-70053 Fix Month Loaded excluding logic + *******************************************************************************/ + + -- Note: The original script was done here https://confluence.sdt.local/display/DD/Moving+Data+from+a+Plan+Configuration+to+Int+Tables + + DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID - 1 FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID ) + DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID) + DECLARE @MonthsLoaded INT = (SELECT bc.MonthsLoaded FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID) + + DECLARE @HistoryItemGUID UNIQUEIDENTIFIER + EXEC procLogScript 'StampOff: Transferring Projection Data from 1p', @HistoryItemGUID OUTPUT + PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36)) + PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID) + + -- Clear out existing records for the selected FiscalYear and Projected Time Class + -- and all months if months loaded included otherwise only months NOT loaded will be cleared + DECLARE @ChunkCount INT + + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END + + DECLARE @r INT; + SET @r = 1; + + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) sl FROM [int].[FactServiceLine] sl + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = sl.FiscalMonthID + WHERE sl.FiscalYearID = @FiscalYear + AND sl.TimeClassID = @TargetTimeClassID + AND (@IsMonthsLoadedIncluded = 1 OR fm.SortOrder > @MonthsLoaded) + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + + INSERT INTO [int].[FactServiceLine] ([TimeClassID], [TimeClassCode], [FiscalYearID], [FiscalYearCode], [FiscalMonthID], + [FiscalMonthCode], [EntityID], [EntityCode], [PatientClassID], [PatientClassCode], [ServiceLineID], [ServiceLine], [AgeCohortID], + [AgeCohort], [MedicalSurgicalID], [MedSurg], [DepartmentID], [DepartmentCode], [OBForecastDetailID], [ForecastDetail], [PayorGroupID], + [PayorID], [Value], [IsDeleted], [HistoryItemGUID],[PayorGroupCode], [PayorCode]) + SELECT + @TargetTimeClassID AS [TimeClassID], + @TimeClassCode AS [TimeClassCode], + @FiscalYear, + @FiscalYear AS [FiscalYearCode], + FM.[FiscalMonthID], + FM.[FiscalMonthCode], + FE.[EntityID], + et.Code AS EntityCode, + pt.[PatientClassID], + pt.Code AS [PatientClassCode], + SL.[ServiceLineID], + SL.code AS [ServiceLine], + AG.AgeCohortID AS AgeCohortID, + AG.Code AS AgeCohort, + MS.MedicalSurgicalID AS MedicalSurgicalID, + MS.Code AS MedSurg, + dep.[DepartmentID], + dep.[DepartmentCode], + FD.[OBForecastDetailID], + fd.Name AS [ForecastDetail], + FE.[PayorGroupID], + FE.[PayorID], + [Value], + 0 AS [IsDeleted], + @HistoryItemGUID AS [HistoryItemGUID], + PG.[PayorGroupCode], + PY.[PayorCode] +FROM ( + SELECT ServiceLineEncounterID, BudgetConfigID, DepartmentID, EntityID, PatientClassID, AgeCohortID, MedicalSurgicalID, ServiceLineID, PayorGroupID, PayorID, UnitTypeID, m.FiscalMonthID, f.Value + FROM ( + SELECT sle.ServiceLineEncounterID, sle.BudgetConfigID, sle.DepartmentID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.PayorGroupID, sle.PayorID, sle.AgeCohortID, sle.MedicalSurgicalID, sle.UnitTypeID, + ProjectionAdjusted01, ProjectionAdjusted02, ProjectionAdjusted03, ProjectionAdjusted04, + ProjectionAdjusted05, ProjectionAdjusted06, ProjectionAdjusted07, ProjectionAdjusted08, + ProjectionAdjusted09, ProjectionAdjusted10, ProjectionAdjusted11, ProjectionAdjusted12 + FROM fp.ServiceLineEncounter sle + WHERE BudgetConfigID = @BudgetConfigID + ) sle + UNPIVOT (Value FOR FiscalMonth IN (ProjectionAdjusted01, ProjectionAdjusted02, ProjectionAdjusted03, ProjectionAdjusted04, ProjectionAdjusted05, ProjectionAdjusted06, ProjectionAdjusted07, ProjectionAdjusted08, ProjectionAdjusted09, ProjectionAdjusted10, ProjectionAdjusted11, ProjectionAdjusted12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectionAdjusted', 'Month') + ) FE + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = FE.BudgetConfigID + INNER JOIN [fw].[DimFiscalMonth] FM ON FM.FiscalMonthID = FE.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = FE.DepartmentID + INNER JOIN [fw].[DimEntity] et ON et.EntityID = FE.EntityID + INNER JOIN [fw].[DimAgeCohort] AG ON AG.AgeCohortID = FE.AgeCohortID + INNER JOIN [fw].[DimMedicalSurgical] MS ON MS.MedicalSurgicalID = FE.MedicalSurgicalID + INNER JOIN [fw].[DimPatientClass] PT ON PT.PatientClassID = FE.PatientClassID + INNER JOIN [fw].[DimServiceLine] SL ON SL.ServiceLineID = FE.ServiceLineID -- Primary serice line dimension for OB definitions + INNER JOIN [ob].[DimOBForecastDetail] FD ON FD.OBForecastDetailID = 36 -- Encounters + INNER JOIN [fw].[DimPayorGroup] PG ON PG.PayorGroupID = FE.PayorGroupID + INNER JOIN [fw].[DimPayor] PY ON PY.PayorID = FE.PayorID + WHERE 1=1 + AND FE.Value <> 0 + AND bc.BudgetConfigID = @BudgetConfigID + AND (@IsMonthsLoadedIncluded = 1 OR CAST(fm.FiscalMonthCode AS INT) > bc.MonthsLoaded) +END +GO + + +--------------------------------------------- + +-- fp.procEnginePostActions +CREATE PROCEDURE [fp].[procEnginePostActions] + @BudgetConfigID INT, + @SourceID INT, + @AdjustmentGUID UNIQUEIDENTIFIER, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + SET NOCOUNT ON; + + /******************* PLEASE READ BEFORE UPDATING THIS PROC ****************** + + When adding to the proc, please do the following: + - Create a defect + - Create a migration updating this proc with the workaround + - When updating this migration, include the defect number and breif summary + + ****************************************************************************/ + + -- D-09032 & D-09167: Workaround for issue where Benefits are adjusted, but phase 3 adjustments to Staffing aren't flexing phase 3 Benefits + IF(@SourceID IN (17, 42)) --BenefitsWereAdjusted (D-09032), ReapplyBenefitsAdjustments (D-09167) + BEGIN + CREATE TABLE #FilterByDepartment (DepartmentID INT) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + DECLARE @Json VARCHAR(MAX) + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + DECLARE @DeptList VARCHAR(MAX) + SET @DeptList='' + SELECT @DeptList = @DeptList + CAST(DepartmentID AS VARCHAR) +',' + FROM #FilterByDepartment + SELECT LEFT(@DeptList,LEN(@DeptList)-1) AS DepartmentID + SELECT @Json = '{"AffectedDepartments":[' + LEFT(@DeptList, LEN(@DeptList) - 1) + '],"BudgetPhaseID":null}' + END ELSE BEGIN + SELECT @Json = '{"AffectedDepartments":[],"BudgetPhaseID":null}' + END + INSERT INTO fp.BudgetRefreshRequest (BudgetConfigID, DateTimeStamp, DateTimeStampUTC, SourceDimensionalityJSON, SourceActionID, UserName, IsIgnoreTargetingError) + VALUES (@BudgetConfigID, GETDATE(), GETUTCDATE(), @Json, 48, 'SDT User', 1) -- PayrollDepartmentPhaseWasAdjusted + END + + +END +GO + + +--------------------------------------------- + +-- fp.procEnginePreActions +CREATE PROCEDURE fp.procEnginePreActions + @BudgetConfigID INT, + @SourceID INT, + @AdjustmentGUID UNIQUEIDENTIFIER, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + AS + BEGIN + + SET NOCOUNT ON; + + /******************* PLEASE READ BEFORE UPDATING THIS PROC ****************** + + When adding to the proc, please do the following: + - Create a defect + - Create a migration updating this proc with the workaround + - When updating this migration, include the defect number and breif summary + + ****************************************************************************/ + + + + END +GO + + +--------------------------------------------- + +-- fp.procEnsureRoleSecurityDefaultAccess +create proc fp.procEnsureRoleSecurityDefaultAccess +as + update p set p.ReadValue = 1, p.WriteValue = 1 + from + S3Permission p + inner join S3PermissionSet ps on ps.PermissionSetID = p.PermissionSetID + inner join UserRole r on r.RoleID = p.RoleID + where + ps.Name = 'Department' + and exists(select 1 from fp.APESectionRoleAccess ra where ra.RoleID = r.RoleID) +GO + + +--------------------------------------------- + +-- fp.procFactChargeVolumeBaselineAndHistoryToReportingTransfer +CREATE PROCEDURE [fp].[procFactChargeVolumeBaselineAndHistoryToReportingTransfer] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +WITH RECOMPILE +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-12-27 MD JAZZ-29138 Initial Creation + ** 2 2022-06-01 MY JAZZ-33343 Fix Missing Charge Code Join + ** 3 2022-06-03 MY JAZZ-33343 Update Data Source to Pivoted + ** 4 2022-06-29 BW JAZZ-39340 Switching from MSDRGID to MSDRGRollupID + ** 5 2022-07-18 MY JAZZ-37944 Add Initial Baseline + ** 6 2022-12-21 MD JAZZ-47250 Update history temp table inserts to include dollars without units + ** 7 2023-03-21 MY JAZZ-49993 Update reporting to support new data model + *************************************************************/ + + -- IMPORTANT NOTE: This proc is only used to transfer data from AP to [fp].[FactReportingAPCharges]. + -- This new proc and table are only used in the new advanced analytics solution that leverages + -- snowflake. This proc will transfer data to [fp].[FactReportingAPCharges], where SQL will then replicate + -- to Snowflake. + -- + -- It's also important to note that this functionality is currently only availible on demand and is not automatically synced. + -- This is also why the current procs aren't targeted. Once we hook this up to the engine, we can properly target the proc. + -- + -- More information can be found here: https://confluence.sdt.local/display/DD/Advanced+Analytics + + SET NOCOUNT ON; + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#SRC') IS NOT NULL DROP TABLE #SRC + IF OBJECT_ID('tempdb..#history') IS NOT NULL DROP TABLE #history + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM [fp].[BudgetConfig] WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + + DECLARE @FiscalYearID SMALLINT + SELECT @FiscalYearID = FiscalYearID FROM fp.BudgetConfig WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID + + CREATE TABLE #SRC ( + BudgetConfigID INT, + EntityID INT, + DepartmentID INT, + ServiceLineID INT, + PatientClassID INT, + AgeCohortID INT, + MedicalSurgicalID INT, + ChargeCodeID INT, + FiscalYearID SMALLINT, + + ServiceEntityID INT, + MSDRGID INT, + UBRevCodeID INT, + PrimaryCPTID INT, + ServiceProviderID INT, + ServiceProviderSpecialtyID INT, + PerformingProviderID INT, + PerformingProviderSpecialtyID INT, + BillingCPTID INT, + + ActualDollars01 DECIMAL(19, 8) DEFAULT(0), + ActualDollars02 DECIMAL(19, 8) DEFAULT(0), + ActualDollars03 DECIMAL(19, 8) DEFAULT(0), + ActualDollars04 DECIMAL(19, 8) DEFAULT(0), + ActualDollars05 DECIMAL(19, 8) DEFAULT(0), + ActualDollars06 DECIMAL(19, 8) DEFAULT(0), + ActualDollars07 DECIMAL(19, 8) DEFAULT(0), + ActualDollars08 DECIMAL(19, 8) DEFAULT(0), + ActualDollars09 DECIMAL(19, 8) DEFAULT(0), + ActualDollars10 DECIMAL(19, 8) DEFAULT(0), + ActualDollars11 DECIMAL(19, 8) DEFAULT(0), + ActualDollars12 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars01 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars02 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars03 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars04 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars05 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars06 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars07 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars08 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars09 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars10 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars11 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars12 DECIMAL(19, 8) DEFAULT(0), + + ActualUnits01 DECIMAL(19, 8) DEFAULT(0), + ActualUnits02 DECIMAL(19, 8) DEFAULT(0), + ActualUnits03 DECIMAL(19, 8) DEFAULT(0), + ActualUnits04 DECIMAL(19, 8) DEFAULT(0), + ActualUnits05 DECIMAL(19, 8) DEFAULT(0), + ActualUnits06 DECIMAL(19, 8) DEFAULT(0), + ActualUnits07 DECIMAL(19, 8) DEFAULT(0), + ActualUnits08 DECIMAL(19, 8) DEFAULT(0), + ActualUnits09 DECIMAL(19, 8) DEFAULT(0), + ActualUnits10 DECIMAL(19, 8) DEFAULT(0), + ActualUnits11 DECIMAL(19, 8) DEFAULT(0), + ActualUnits12 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits01 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits02 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits03 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits04 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits05 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits06 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits07 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits08 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits09 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits10 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits11 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits12 DECIMAL(19, 8) DEFAULT(0), + + InitialUnits01 DECIMAL(19, 8) DEFAULT(0), + InitialUnits02 DECIMAL(19, 8) DEFAULT(0), + InitialUnits03 DECIMAL(19, 8) DEFAULT(0), + InitialUnits04 DECIMAL(19, 8) DEFAULT(0), + InitialUnits05 DECIMAL(19, 8) DEFAULT(0), + InitialUnits06 DECIMAL(19, 8) DEFAULT(0), + InitialUnits07 DECIMAL(19, 8) DEFAULT(0), + InitialUnits08 DECIMAL(19, 8) DEFAULT(0), + InitialUnits09 DECIMAL(19, 8) DEFAULT(0), + InitialUnits10 DECIMAL(19, 8) DEFAULT(0), + InitialUnits11 DECIMAL(19, 8) DEFAULT(0), + InitialUnits12 DECIMAL(19, 8) DEFAULT(0), + + InitialDollars01 DECIMAL(19, 8) DEFAULT(0), + InitialDollars02 DECIMAL(19, 8) DEFAULT(0), + InitialDollars03 DECIMAL(19, 8) DEFAULT(0), + InitialDollars04 DECIMAL(19, 8) DEFAULT(0), + InitialDollars05 DECIMAL(19, 8) DEFAULT(0), + InitialDollars06 DECIMAL(19, 8) DEFAULT(0), + InitialDollars07 DECIMAL(19, 8) DEFAULT(0), + InitialDollars08 DECIMAL(19, 8) DEFAULT(0), + InitialDollars09 DECIMAL(19, 8) DEFAULT(0), + InitialDollars10 DECIMAL(19, 8) DEFAULT(0), + InitialDollars11 DECIMAL(19, 8) DEFAULT(0), + InitialDollars12 DECIMAL(19, 8) DEFAULT(0) + ) + + -- Populate Targeting + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If targeting is empty we need all departments + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fp.ChargeVolume + WHERE BudgetConfigID = @BudgetConfigID + END + + -- Populate #history temp table, this way we only need to do the main filtering and JOINs once rather than once per time class + SELECT + cv.BudgetConfigID, + cv.EntityID, + cv.DepartmentID, + cv.ServiceLineID, + cv.PatientClassID, + cv.AgeCohortID, + cv.MedicalSurgicalID, + cv.ChargeCodeID, + cv.ServiceEntityID, + cv.MSDRGID, + cv.UBRevCodeID, + cv.PrimaryCPTID, + cv.ServiceProviderID, + cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, + cv.PerformingProviderSpecialtyID, + cv.BillingCPTID, + + hist.ActualYTDValue01 AS ActualYTDUnits01, + hist.ActualYTDValue02 AS ActualYTDUnits02, + hist.ActualYTDValue03 AS ActualYTDUnits03, + hist.ActualYTDValue04 AS ActualYTDUnits04, + hist.ActualYTDValue05 AS ActualYTDUnits05, + hist.ActualYTDValue06 AS ActualYTDUnits06, + hist.ActualYTDValue07 AS ActualYTDUnits07, + hist.ActualYTDValue08 AS ActualYTDUnits08, + hist.ActualYTDValue09 AS ActualYTDUnits09, + hist.ActualYTDValue10 AS ActualYTDUnits10, + hist.ActualYTDValue11 AS ActualYTDUnits11, + hist.ActualYTDValue12 AS ActualYTDUnits12, + hist.ActualYTDValueTotal AS ActualYTDUnitsTotal, + hist.ActualYTDDollarValue01 AS ActualYTDDollars01, + hist.ActualYTDDollarValue02 AS ActualYTDDollars02, + hist.ActualYTDDollarValue03 AS ActualYTDDollars03, + hist.ActualYTDDollarValue04 AS ActualYTDDollars04, + hist.ActualYTDDollarValue05 AS ActualYTDDollars05, + hist.ActualYTDDollarValue06 AS ActualYTDDollars06, + hist.ActualYTDDollarValue07 AS ActualYTDDollars07, + hist.ActualYTDDollarValue08 AS ActualYTDDollars08, + hist.ActualYTDDollarValue09 AS ActualYTDDollars09, + hist.ActualYTDDollarValue10 AS ActualYTDDollars10, + hist.ActualYTDDollarValue11 AS ActualYTDDollars11, + hist.ActualYTDDollarValue12 AS ActualYTDDollars12, + hist.ActualYTDDollarValueTotal AS ActualYTDDollarsTotal, + + hist.PriorYearActualValue01 AS PriorYearActualUnits01, + hist.PriorYearActualValue02 AS PriorYearActualUnits02, + hist.PriorYearActualValue03 AS PriorYearActualUnits03, + hist.PriorYearActualValue04 AS PriorYearActualUnits04, + hist.PriorYearActualValue05 AS PriorYearActualUnits05, + hist.PriorYearActualValue06 AS PriorYearActualUnits06, + hist.PriorYearActualValue07 AS PriorYearActualUnits07, + hist.PriorYearActualValue08 AS PriorYearActualUnits08, + hist.PriorYearActualValue09 AS PriorYearActualUnits09, + hist.PriorYearActualValue10 AS PriorYearActualUnits10, + hist.PriorYearActualValue11 AS PriorYearActualUnits11, + hist.PriorYearActualValue12 AS PriorYearActualUnits12, + hist.PriorYearActualValueTotal AS PriorYearActualUnitsTotal, + hist.PriorYearActualDollarValue01 AS PriorYearActualDollars01, + hist.PriorYearActualDollarValue02 AS PriorYearActualDollars02, + hist.PriorYearActualDollarValue03 AS PriorYearActualDollars03, + hist.PriorYearActualDollarValue04 AS PriorYearActualDollars04, + hist.PriorYearActualDollarValue05 AS PriorYearActualDollars05, + hist.PriorYearActualDollarValue06 AS PriorYearActualDollars06, + hist.PriorYearActualDollarValue07 AS PriorYearActualDollars07, + hist.PriorYearActualDollarValue08 AS PriorYearActualDollars08, + hist.PriorYearActualDollarValue09 AS PriorYearActualDollars09, + hist.PriorYearActualDollarValue10 AS PriorYearActualDollars10, + hist.PriorYearActualDollarValue11 AS PriorYearActualDollars11, + hist.PriorYearActualDollarValue12 AS PriorYearActualDollars12, + hist.PriorYearActualDollarValueTotal AS PriorYearActualDollarsTotal, + + hist.CurrentYearBudget01 AS CurrentYearBudgetUnits01, + hist.CurrentYearBudget02 AS CurrentYearBudgetUnits02, + hist.CurrentYearBudget03 AS CurrentYearBudgetUnits03, + hist.CurrentYearBudget04 AS CurrentYearBudgetUnits04, + hist.CurrentYearBudget05 AS CurrentYearBudgetUnits05, + hist.CurrentYearBudget06 AS CurrentYearBudgetUnits06, + hist.CurrentYearBudget07 AS CurrentYearBudgetUnits07, + hist.CurrentYearBudget08 AS CurrentYearBudgetUnits08, + hist.CurrentYearBudget09 AS CurrentYearBudgetUnits09, + hist.CurrentYearBudget10 AS CurrentYearBudgetUnits10, + hist.CurrentYearBudget11 AS CurrentYearBudgetUnits11, + hist.CurrentYearBudget12 AS CurrentYearBudgetUnits12, + hist.CurrentYearBudgetTotal AS CurrentYearBudgetUnitsTotal, + hist.CurrentYearBudgetDollar01 AS CurrentYearBudgetDollars01, + hist.CurrentYearBudgetDollar02 AS CurrentYearBudgetDollars02, + hist.CurrentYearBudgetDollar03 AS CurrentYearBudgetDollars03, + hist.CurrentYearBudgetDollar04 AS CurrentYearBudgetDollars04, + hist.CurrentYearBudgetDollar05 AS CurrentYearBudgetDollars05, + hist.CurrentYearBudgetDollar06 AS CurrentYearBudgetDollars06, + hist.CurrentYearBudgetDollar07 AS CurrentYearBudgetDollars07, + hist.CurrentYearBudgetDollar08 AS CurrentYearBudgetDollars08, + hist.CurrentYearBudgetDollar09 AS CurrentYearBudgetDollars09, + hist.CurrentYearBudgetDollar10 AS CurrentYearBudgetDollars10, + hist.CurrentYearBudgetDollar11 AS CurrentYearBudgetDollars11, + hist.CurrentYearBudgetDollar12 AS CurrentYearBudgetDollars12, + hist.CurrentYearBudgetDollarTotal AS CurrentYearBudgetDollarsTotal, + + cv.InitialBudget01 AS InitialUnits01, + cv.InitialBudget02 AS InitialUnits02, + cv.InitialBudget03 AS InitialUnits03, + cv.InitialBudget04 AS InitialUnits04, + cv.InitialBudget05 AS InitialUnits05, + cv.InitialBudget06 AS InitialUnits06, + cv.InitialBudget07 AS InitialUnits07, + cv.InitialBudget08 AS InitialUnits08, + cv.InitialBudget09 AS InitialUnits09, + cv.InitialBudget10 AS InitialUnits10, + cv.InitialBudget11 AS InitialUnits11, + cv.InitialBudget12 AS InitialUnits12, + cv.InitialBudgetTotal AS InitialUnitsTotal, + + cv.InitialBudgetDollars01 AS InitialDollars01, + cv.InitialBudgetDollars02 AS InitialDollars02, + cv.InitialBudgetDollars03 AS InitialDollars03, + cv.InitialBudgetDollars04 AS InitialDollars04, + cv.InitialBudgetDollars05 AS InitialDollars05, + cv.InitialBudgetDollars06 AS InitialDollars06, + cv.InitialBudgetDollars07 AS InitialDollars07, + cv.InitialBudgetDollars08 AS InitialDollars08, + cv.InitialBudgetDollars09 AS InitialDollars09, + cv.InitialBudgetDollars10 AS InitialDollars10, + cv.InitialBudgetDollars11 AS InitialDollars11, + cv.InitialBudgetDollars12 AS InitialDollars12, + cv.InitialBudgetDollarsTotal AS InitialDollarsTotal + INTO #history + FROM fp.ChargeVolume cv + INNER JOIN #FilterByDepartment dept ON cv.DepartmentID = dept.DepartmentID + INNER JOIN fp.ChargeVolumeHistory hist ON cv.ChargeVolumeID = hist.ChargeVolumeID + WHERE cv.UnitTypeID = 145 + AND cv.BudgetConfigID = @BudgetConfigID + + -- Populating Baseline + INSERT INTO #SRC (BudgetConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, + ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, PerformingProviderSpecialtyID, + BillingCPTID, FiscalYearID, + InitialUnits01, InitialUnits02, InitialUnits03, InitialUnits04, InitialUnits05, InitialUnits06, InitialUnits07, InitialUnits08, InitialUnits09, InitialUnits10, InitialUnits11, InitialUnits12, + InitialDollars01, InitialDollars02, InitialDollars03, InitialDollars04, InitialDollars05, InitialDollars06, InitialDollars07, InitialDollars08, InitialDollars09, InitialDollars10, InitialDollars11, InitialDollars12) + SELECT + BudgetConfigID, + EntityID, + DepartmentID, + ServiceLineID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + ChargeCodeID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + BillingCPTID, + @FiscalYearID AS FiscalYearID, + InitialUnits01, + InitialUnits02, + InitialUnits03, + InitialUnits04, + InitialUnits05, + InitialUnits06, + InitialUnits07, + InitialUnits08, + InitialUnits09, + InitialUnits10, + InitialUnits11, + InitialUnits12, + InitialDollars01, + InitialDollars02, + InitialDollars03, + InitialDollars04, + InitialDollars05, + InitialDollars06, + InitialDollars07, + InitialDollars08, + InitialDollars09, + InitialDollars10, + InitialDollars11, + InitialDollars12 + FROM #history + -- JAZZ-47250 - Updating where clause to include CV data that has dollars but no units + WHERE + InitialUnitsTotal != 0 OR InitialDollarsTotal != 0 + + + -- Populating Actual YTD + -- Populating Current Year Budget + INSERT INTO #SRC (BudgetConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, + ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, PerformingProviderSpecialtyID, + BillingCPTID, FiscalYearID, + ActualUnits01, ActualUnits02, ActualUnits03, ActualUnits04, ActualUnits05, ActualUnits06, ActualUnits07, ActualUnits08, ActualUnits09, ActualUnits10, ActualUnits11, ActualUnits12, + ActualDollars01, ActualDollars02, ActualDollars03, ActualDollars04, ActualDollars05, ActualDollars06, ActualDollars07, ActualDollars08, ActualDollars09, ActualDollars10, ActualDollars11, ActualDollars12, + BudgetUnits01, BudgetUnits02, BudgetUnits03, BudgetUnits04, BudgetUnits05, BudgetUnits06, BudgetUnits07, BudgetUnits08, BudgetUnits09, BudgetUnits10, BudgetUnits11, BudgetUnits12, + BudgetDollars01, BudgetDollars02, BudgetDollars03, BudgetDollars04, BudgetDollars05, BudgetDollars06, BudgetDollars07, BudgetDollars08, BudgetDollars09, BudgetDollars10, BudgetDollars11, BudgetDollars12) + SELECT + BudgetConfigID, + EntityID, + DepartmentID, + ServiceLineID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + ChargeCodeID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + BillingCPTID, + @FiscalYearID - 1 AS FiscalYearID, + ActualYTDUnits01, + ActualYTDUnits02, + ActualYTDUnits03, + ActualYTDUnits04, + ActualYTDUnits05, + ActualYTDUnits06, + ActualYTDUnits07, + ActualYTDUnits08, + ActualYTDUnits09, + ActualYTDUnits10, + ActualYTDUnits11, + ActualYTDUnits12, + ActualYTDDollars01, + ActualYTDDollars02, + ActualYTDDollars03, + ActualYTDDollars04, + ActualYTDDollars05, + ActualYTDDollars06, + ActualYTDDollars07, + ActualYTDDollars08, + ActualYTDDollars09, + ActualYTDDollars10, + ActualYTDDollars11, + ActualYTDDollars12, + CurrentYearBudgetUnits01, + CurrentYearBudgetUnits02, + CurrentYearBudgetUnits03, + CurrentYearBudgetUnits04, + CurrentYearBudgetUnits05, + CurrentYearBudgetUnits06, + CurrentYearBudgetUnits07, + CurrentYearBudgetUnits08, + CurrentYearBudgetUnits09, + CurrentYearBudgetUnits10, + CurrentYearBudgetUnits11, + CurrentYearBudgetUnits12, + CurrentYearBudgetDollars01, + CurrentYearBudgetDollars02, + CurrentYearBudgetDollars03, + CurrentYearBudgetDollars04, + CurrentYearBudgetDollars05, + CurrentYearBudgetDollars06, + CurrentYearBudgetDollars07, + CurrentYearBudgetDollars08, + CurrentYearBudgetDollars09, + CurrentYearBudgetDollars10, + CurrentYearBudgetDollars11, + CurrentYearBudgetDollars12 + FROM #history + -- JAZZ-47250 - Updating where clause to include CV data that has dollars but no units + WHERE + ((ActualYTDUnitsTotal != 0 OR ActualYTDDollarsTotal != 0) OR + (CurrentYearBudgetUnitsTotal != 0 OR CurrentYearBudgetDollarsTotal != 0)) + + -- Populating Prior Year Actuals + INSERT INTO #SRC (BudgetConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, + ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, PerformingProviderSpecialtyID, + BillingCPTID, FiscalYearID, + ActualUnits01, ActualUnits02, ActualUnits03, ActualUnits04, ActualUnits05, ActualUnits06, ActualUnits07, ActualUnits08, ActualUnits09, ActualUnits10, ActualUnits11, ActualUnits12, + ActualDollars01, ActualDollars02, ActualDollars03, ActualDollars04, ActualDollars05, ActualDollars06, ActualDollars07, ActualDollars08, ActualDollars09, ActualDollars10, ActualDollars11, ActualDollars12) + SELECT + BudgetConfigID, + EntityID, + DepartmentID, + ServiceLineID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + ChargeCodeID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + BillingCPTID, + @FiscalYearID - 2 AS FiscalYearID, + PriorYearActualUnits01, + PriorYearActualUnits02, + PriorYearActualUnits03, + PriorYearActualUnits04, + PriorYearActualUnits05, + PriorYearActualUnits06, + PriorYearActualUnits07, + PriorYearActualUnits08, + PriorYearActualUnits09, + PriorYearActualUnits10, + PriorYearActualUnits11, + PriorYearActualUnits12, + PriorYearActualDollars01, + PriorYearActualDollars02, + PriorYearActualDollars03, + PriorYearActualDollars04, + PriorYearActualDollars05, + PriorYearActualDollars06, + PriorYearActualDollars07, + PriorYearActualDollars08, + PriorYearActualDollars09, + PriorYearActualDollars10, + PriorYearActualDollars11, + PriorYearActualDollars12 + FROM #history + -- JAZZ-47250 - Updating where clause to include CV data that has dollars but no units + WHERE + PriorYearActualUnitsTotal != 0 OR PriorYearActualDollarsTotal != 0 + + IF (@IsDebug = 1) + BEGIN + SELECT + '#SRC' AS TempTable, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, + ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, + PerformingProviderSpecialtyID, BillingCPTID, FiscalYearID + BudgetUnits01, BudgetUnits02, BudgetUnits03, BudgetUnits04, BudgetUnits05, BudgetUnits06, BudgetUnits07, BudgetUnits08, BudgetUnits09, BudgetUnits10, BudgetUnits11, BudgetUnits12, + BudgetDollars01, BudgetDollars02, BudgetDollars03, BudgetDollars04, BudgetDollars05, BudgetDollars06, BudgetDollars07, BudgetDollars08, BudgetDollars09, BudgetDollars10, BudgetDollars11, BudgetDollars12, + ActualUnits01, ActualUnits02, ActualUnits03, ActualUnits04, ActualUnits05, ActualUnits06, ActualUnits07, ActualUnits08, ActualUnits09, ActualUnits10, ActualUnits11, ActualUnits12, + ActualDollars01, ActualDollars02, ActualDollars03, ActualDollars04, ActualDollars05, ActualDollars06, ActualDollars07, ActualDollars08, ActualDollars09, ActualDollars10, ActualDollars11, ActualDollars12, + InitialUnits01, InitialUnits02, InitialUnits03, InitialUnits04, InitialUnits05, InitialUnits06, InitialUnits07, InitialUnits08, InitialUnits09, InitialUnits10, InitialUnits11, InitialUnits12, + InitialDollars01, InitialDollars02, InitialDollars03, InitialDollars04, InitialDollars05, InitialDollars06, InitialDollars07, InitialDollars08, InitialDollars09, InitialDollars10, InitialDollars11, InitialDollars12 + FROM #SRC; + + RETURN + END + + -- Publish the data from the temp table to fp.FactReportingAPCharges. This uses a merge statement to handle inserts and updates + -- In the event that the active configuration changes, we need to clear out this table because we only hold data for the active configuration. This is done from the UI itself. + + SELECT EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, + ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, + PerformingProviderSpecialtyID, BillingCPTID, FiscalYearID, + BudgetUnits01, BudgetUnits02, BudgetUnits03, BudgetUnits04, BudgetUnits05, BudgetUnits06, BudgetUnits07, BudgetUnits08, BudgetUnits09, BudgetUnits10, BudgetUnits11, BudgetUnits12, + BudgetDollars01, BudgetDollars02, BudgetDollars03, BudgetDollars04, BudgetDollars05, BudgetDollars06, BudgetDollars07, BudgetDollars08, BudgetDollars09, BudgetDollars10, BudgetDollars11, BudgetDollars12, + ActualUnits01, ActualUnits02, ActualUnits03, ActualUnits04, ActualUnits05, ActualUnits06, ActualUnits07, ActualUnits08, ActualUnits09, ActualUnits10, ActualUnits11, ActualUnits12, + ActualDollars01, ActualDollars02, ActualDollars03, ActualDollars04, ActualDollars05, ActualDollars06, ActualDollars07, ActualDollars08, ActualDollars09, ActualDollars10, ActualDollars11, ActualDollars12 + INTO #HistorySRC + FROM #SRC + WHERE FiscalYearID < @FiscalYearID + + -- Historical Values + ;WITH TGT AS + ( + SELECT + EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, + ServiceEntityID, MSDRGRollupID, UBRevenueCodeID, PrimaryCPTID, PhysicianID, PhysicianSpecialtyID, PerformingProviderID, + PerformingPhysicianSpecialtyID, BilledCPTID, FiscalYearID, + BudgetUnits01, BudgetUnits02, BudgetUnits03, BudgetUnits04, BudgetUnits05, BudgetUnits06, BudgetUnits07, BudgetUnits08, BudgetUnits09, BudgetUnits10, BudgetUnits11, BudgetUnits12, + BudgetDollars01, BudgetDollars02, BudgetDollars03, BudgetDollars04, BudgetDollars05, BudgetDollars06, BudgetDollars07, BudgetDollars08, BudgetDollars09, BudgetDollars10, BudgetDollars11, BudgetDollars12, + ActualUnits01, ActualUnits02, ActualUnits03, ActualUnits04, ActualUnits05, ActualUnits06, ActualUnits07, ActualUnits08, ActualUnits09, ActualUnits10, ActualUnits11, ActualUnits12, + ActualDollars01, ActualDollars02, ActualDollars03, ActualDollars04, ActualDollars05, ActualDollars06, ActualDollars07, ActualDollars08, ActualDollars09, ActualDollars10, ActualDollars11, ActualDollars12 + FROM [fp].[FactReportingAPCharges] FRS + WHERE FiscalYearID < @FiscalYearID + ) + MERGE TGT AS target + USING #HistorySRC AS source + ON ( + target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.ServiceLineID = source.ServiceLineID + AND target.PatientClassID = source.PatientClassID + AND target.AgeCohortID = source.AgeCohortID + AND target.MedicalSurgicalID = source.MedicalSurgicalID + AND target.ChargeCodeID = source.ChargeCodeID + AND target.ServiceEntityID = source.ServiceEntityID + AND target.MSDRGRollupID = source.MSDRGID + AND target.UBRevenueCodeID = source.UBRevCodeID + AND target.PrimaryCPTID = source.PrimaryCPTID + AND target.PhysicianID = source.ServiceProviderID + AND target.PhysicianSpecialtyID = source.ServiceProviderSpecialtyID + AND target.PerformingProviderID = source.PerformingProviderID + AND target.PerformingPhysicianSpecialtyID = source.PerformingProviderSpecialtyID + AND target.BilledCPTID = source.BillingCPTID + AND target.FiscalYearID = source.FiscalYearID + ) + WHEN MATCHED AND + ( + target.BudgetDollars01 <> source.BudgetDollars01 + OR target.BudgetDollars02 <> source.BudgetDollars02 + OR target.BudgetDollars03 <> source.BudgetDollars03 + OR target.BudgetDollars04 <> source.BudgetDollars04 + OR target.BudgetDollars05 <> source.BudgetDollars05 + OR target.BudgetDollars06 <> source.BudgetDollars06 + OR target.BudgetDollars07 <> source.BudgetDollars07 + OR target.BudgetDollars08 <> source.BudgetDollars08 + OR target.BudgetDollars09 <> source.BudgetDollars09 + OR target.BudgetDollars10 <> source.BudgetDollars10 + OR target.BudgetDollars11 <> source.BudgetDollars11 + OR target.BudgetDollars12 <> source.BudgetDollars12 + + OR target.ActualDollars01 <> source.ActualDollars01 + OR target.ActualDollars02 <> source.ActualDollars02 + OR target.ActualDollars03 <> source.ActualDollars03 + OR target.ActualDollars04 <> source.ActualDollars04 + OR target.ActualDollars05 <> source.ActualDollars05 + OR target.ActualDollars06 <> source.ActualDollars06 + OR target.ActualDollars07 <> source.ActualDollars07 + OR target.ActualDollars08 <> source.ActualDollars08 + OR target.ActualDollars09 <> source.ActualDollars09 + OR target.ActualDollars10 <> source.ActualDollars10 + OR target.ActualDollars11 <> source.ActualDollars11 + OR target.ActualDollars12 <> source.ActualDollars12 + + OR target.BudgetUnits01 <> source.BudgetUnits01 + OR target.BudgetUnits02 <> source.BudgetUnits02 + OR target.BudgetUnits03 <> source.BudgetUnits03 + OR target.BudgetUnits04 <> source.BudgetUnits04 + OR target.BudgetUnits05 <> source.BudgetUnits05 + OR target.BudgetUnits06 <> source.BudgetUnits06 + OR target.BudgetUnits07 <> source.BudgetUnits07 + OR target.BudgetUnits08 <> source.BudgetUnits08 + OR target.BudgetUnits09 <> source.BudgetUnits09 + OR target.BudgetUnits10 <> source.BudgetUnits10 + OR target.BudgetUnits11 <> source.BudgetUnits11 + OR target.BudgetUnits12 <> source.BudgetUnits12 + + OR target.ActualUnits01 <> source.ActualUnits01 + OR target.ActualUnits02 <> source.ActualUnits02 + OR target.ActualUnits03 <> source.ActualUnits03 + OR target.ActualUnits04 <> source.ActualUnits04 + OR target.ActualUnits05 <> source.ActualUnits05 + OR target.ActualUnits06 <> source.ActualUnits06 + OR target.ActualUnits07 <> source.ActualUnits07 + OR target.ActualUnits08 <> source.ActualUnits08 + OR target.ActualUnits09 <> source.ActualUnits09 + OR target.ActualUnits10 <> source.ActualUnits10 + OR target.ActualUnits11 <> source.ActualUnits11 + OR target.ActualUnits12 <> source.ActualUnits12 + ) + THEN + UPDATE SET + target.BudgetDollars01 = ISNULL(source.BudgetDollars01, 0), + target.BudgetDollars02 = ISNULL(source.BudgetDollars02, 0), + target.BudgetDollars03 = ISNULL(source.BudgetDollars03, 0), + target.BudgetDollars04 = ISNULL(source.BudgetDollars04, 0), + target.BudgetDollars05 = ISNULL(source.BudgetDollars05, 0), + target.BudgetDollars06 = ISNULL(source.BudgetDollars06, 0), + target.BudgetDollars07 = ISNULL(source.BudgetDollars07, 0), + target.BudgetDollars08 = ISNULL(source.BudgetDollars08, 0), + target.BudgetDollars09 = ISNULL(source.BudgetDollars09, 0), + target.BudgetDollars10 = ISNULL(source.BudgetDollars10, 0), + target.BudgetDollars11 = ISNULL(source.BudgetDollars11, 0), + target.BudgetDollars12 = ISNULL(source.BudgetDollars12, 0), + + target.ActualDollars01 = ISNULL(source.ActualDollars01, 0), + target.ActualDollars02 = ISNULL(source.ActualDollars02, 0), + target.ActualDollars03 = ISNULL(source.ActualDollars03, 0), + target.ActualDollars04 = ISNULL(source.ActualDollars04, 0), + target.ActualDollars05 = ISNULL(source.ActualDollars05, 0), + target.ActualDollars06 = ISNULL(source.ActualDollars06, 0), + target.ActualDollars07 = ISNULL(source.ActualDollars07, 0), + target.ActualDollars08 = ISNULL(source.ActualDollars08, 0), + target.ActualDollars09 = ISNULL(source.ActualDollars09, 0), + target.ActualDollars10 = ISNULL(source.ActualDollars10, 0), + target.ActualDollars11 = ISNULL(source.ActualDollars11, 0), + target.ActualDollars12 = ISNULL(source.ActualDollars12, 0), + + target.BudgetUnits01 = ISNULL(source.BudgetUnits01, 0), + target.BudgetUnits02 = ISNULL(source.BudgetUnits02, 0), + target.BudgetUnits03 = ISNULL(source.BudgetUnits03, 0), + target.BudgetUnits04 = ISNULL(source.BudgetUnits04, 0), + target.BudgetUnits05 = ISNULL(source.BudgetUnits05, 0), + target.BudgetUnits06 = ISNULL(source.BudgetUnits06, 0), + target.BudgetUnits07 = ISNULL(source.BudgetUnits07, 0), + target.BudgetUnits08 = ISNULL(source.BudgetUnits08, 0), + target.BudgetUnits09 = ISNULL(source.BudgetUnits09, 0), + target.BudgetUnits10 = ISNULL(source.BudgetUnits10, 0), + target.BudgetUnits11 = ISNULL(source.BudgetUnits11, 0), + target.BudgetUnits12 = ISNULL(source.BudgetUnits12, 0), + + target.ActualUnits01 = ISNULL(source.ActualUnits01, 0), + target.ActualUnits02 = ISNULL(source.ActualUnits02, 0), + target.ActualUnits03 = ISNULL(source.ActualUnits03, 0), + target.ActualUnits04 = ISNULL(source.ActualUnits04, 0), + target.ActualUnits05 = ISNULL(source.ActualUnits05, 0), + target.ActualUnits06 = ISNULL(source.ActualUnits06, 0), + target.ActualUnits07 = ISNULL(source.ActualUnits07, 0), + target.ActualUnits08 = ISNULL(source.ActualUnits08, 0), + target.ActualUnits09 = ISNULL(source.ActualUnits09, 0), + target.ActualUnits10 = ISNULL(source.ActualUnits10, 0), + target.ActualUnits11 = ISNULL(source.ActualUnits11, 0), + target.ActualUnits12 = ISNULL(source.ActualUnits12, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, + ServiceEntityID, MSDRGRollupID, UBRevenueCodeID, PrimaryCPTID, PhysicianID, PhysicianSpecialtyID, PerformingProviderID, + PerformingPhysicianSpecialtyID, BilledCPTID, FiscalYearID, + BudgetUnits01, BudgetUnits02, BudgetUnits03, BudgetUnits04, BudgetUnits05, BudgetUnits06, BudgetUnits07, BudgetUnits08, BudgetUnits09, BudgetUnits10, BudgetUnits11, BudgetUnits12, + BudgetDollars01, BudgetDollars02, BudgetDollars03, BudgetDollars04, BudgetDollars05, BudgetDollars06, BudgetDollars07, BudgetDollars08, BudgetDollars09, BudgetDollars10, BudgetDollars11, BudgetDollars12, + ActualUnits01, ActualUnits02, ActualUnits03, ActualUnits04, ActualUnits05, ActualUnits06, ActualUnits07, ActualUnits08, ActualUnits09, ActualUnits10, ActualUnits11, ActualUnits12, + ActualDollars01, ActualDollars02, ActualDollars03, ActualDollars04, ActualDollars05, ActualDollars06, ActualDollars07, ActualDollars08, ActualDollars09, ActualDollars10, ActualDollars11, ActualDollars12 + ) + VALUES ( + source.EntityID, + source.DepartmentID, + source.ServiceLineID, + source.PatientClassID, + source.AgeCohortID, + source.MedicalSurgicalID, + source.ChargeCodeID, + source.ServiceEntityID, + source.MSDRGID, + source.UBRevCodeID, + source.PrimaryCPTID, + source.ServiceProviderID, + source.ServiceProviderSpecialtyID, + source.PerformingProviderID, + source.PerformingProviderSpecialtyID, + source.BillingCPTID, + source.FiscalYearID, + ISNULL(source.BudgetUnits01, 0), + ISNULL(source.BudgetUnits02, 0), + ISNULL(source.BudgetUnits03, 0), + ISNULL(source.BudgetUnits04, 0), + ISNULL(source.BudgetUnits05, 0), + ISNULL(source.BudgetUnits06, 0), + ISNULL(source.BudgetUnits07, 0), + ISNULL(source.BudgetUnits08, 0), + ISNULL(source.BudgetUnits09, 0), + ISNULL(source.BudgetUnits10, 0), + ISNULL(source.BudgetUnits11, 0), + ISNULL(source.BudgetUnits12, 0), + + ISNULL(source.BudgetDollars01, 0), + ISNULL(source.BudgetDollars02, 0), + ISNULL(source.BudgetDollars03, 0), + ISNULL(source.BudgetDollars04, 0), + ISNULL(source.BudgetDollars05, 0), + ISNULL(source.BudgetDollars06, 0), + ISNULL(source.BudgetDollars07, 0), + ISNULL(source.BudgetDollars08, 0), + ISNULL(source.BudgetDollars09, 0), + ISNULL(source.BudgetDollars10, 0), + ISNULL(source.BudgetDollars11, 0), + ISNULL(source.BudgetDollars12, 0), + + ISNULL(source.ActualUnits01, 0), + ISNULL(source.ActualUnits02, 0), + ISNULL(source.ActualUnits03, 0), + ISNULL(source.ActualUnits04, 0), + ISNULL(source.ActualUnits05, 0), + ISNULL(source.ActualUnits06, 0), + ISNULL(source.ActualUnits07, 0), + ISNULL(source.ActualUnits08, 0), + ISNULL(source.ActualUnits09, 0), + ISNULL(source.ActualUnits10, 0), + ISNULL(source.ActualUnits11, 0), + ISNULL(source.ActualUnits12, 0), + + ISNULL(source.ActualDollars01, 0), + ISNULL(source.ActualDollars02, 0), + ISNULL(source.ActualDollars03, 0), + ISNULL(source.ActualDollars04, 0), + ISNULL(source.ActualDollars05, 0), + ISNULL(source.ActualDollars06, 0), + ISNULL(source.ActualDollars07, 0), + ISNULL(source.ActualDollars08, 0), + ISNULL(source.ActualDollars09, 0), + ISNULL(source.ActualDollars10, 0), + ISNULL(source.ActualDollars11, 0), + ISNULL(source.ActualDollars12, 0) + ); + + + SELECT EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, + ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, + PerformingProviderSpecialtyID, BillingCPTID, FiscalYearID, + InitialUnits01, InitialUnits02, InitialUnits03, InitialUnits04, InitialUnits05, InitialUnits06, InitialUnits07, InitialUnits08, InitialUnits09, InitialUnits10, InitialUnits11, InitialUnits12, + InitialDollars01, InitialDollars02, InitialDollars03, InitialDollars04, InitialDollars05, InitialDollars06, InitialDollars07, InitialDollars08, InitialDollars09, InitialDollars10, InitialDollars11, InitialDollars12 + INTO #BaselineSRC + FROM #SRC + WHERE FiscalYearID = @FiscalYearID + + -- Initial baseline, we need to do these seperately, otherwise when running the baseline row will wipe out Target/Budget + ;WITH TGT AS + ( + SELECT + EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, + ServiceEntityID, MSDRGRollupID, UBRevenueCodeID, PrimaryCPTID, PhysicianID, PhysicianSpecialtyID, PerformingProviderID, + PerformingPhysicianSpecialtyID, BilledCPTID, FiscalYearID, + InitialUnits01, InitialUnits02, InitialUnits03, InitialUnits04, InitialUnits05, InitialUnits06, InitialUnits07, InitialUnits08, InitialUnits09, InitialUnits10, InitialUnits11, InitialUnits12, + InitialDollars01, InitialDollars02, InitialDollars03, InitialDollars04, InitialDollars05, InitialDollars06, InitialDollars07, InitialDollars08, InitialDollars09, InitialDollars10, InitialDollars11, InitialDollars12 + FROM [fp].[FactReportingAPCharges] FRS + WHERE FiscalYearID = @FiscalYearID + ) + MERGE TGT AS target + USING #BaselineSRC AS source + ON ( + target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.ServiceLineID = source.ServiceLineID + AND target.PatientClassID = source.PatientClassID + AND target.AgeCohortID = source.AgeCohortID + AND target.MedicalSurgicalID = source.MedicalSurgicalID + AND target.ChargeCodeID = source.ChargeCodeID + AND target.ServiceEntityID = source.ServiceEntityID + AND target.MSDRGRollupID = source.MSDRGID + AND target.UBRevenueCodeID = source.UBRevCodeID + AND target.PrimaryCPTID = source.PrimaryCPTID + AND target.PhysicianID = source.ServiceProviderID + AND target.PhysicianSpecialtyID = source.ServiceProviderSpecialtyID + AND target.PerformingProviderID = source.PerformingProviderID + AND target.PerformingPhysicianSpecialtyID = source.PerformingProviderSpecialtyID + AND target.BilledCPTID = source.BillingCPTID + AND target.FiscalYearID = source.FiscalYearID + ) + WHEN MATCHED AND + ( + target.InitialDollars01 <> source.InitialDollars01 + OR target.InitialDollars02 <> source.InitialDollars02 + OR target.InitialDollars03 <> source.InitialDollars03 + OR target.InitialDollars04 <> source.InitialDollars04 + OR target.InitialDollars05 <> source.InitialDollars05 + OR target.InitialDollars06 <> source.InitialDollars06 + OR target.InitialDollars07 <> source.InitialDollars07 + OR target.InitialDollars08 <> source.InitialDollars08 + OR target.InitialDollars09 <> source.InitialDollars09 + OR target.InitialDollars10 <> source.InitialDollars10 + OR target.InitialDollars11 <> source.InitialDollars11 + OR target.InitialDollars12 <> source.InitialDollars12 + + OR target.InitialUnits01 <> source.InitialUnits01 + OR target.InitialUnits02 <> source.InitialUnits02 + OR target.InitialUnits03 <> source.InitialUnits03 + OR target.InitialUnits04 <> source.InitialUnits04 + OR target.InitialUnits05 <> source.InitialUnits05 + OR target.InitialUnits06 <> source.InitialUnits06 + OR target.InitialUnits07 <> source.InitialUnits07 + OR target.InitialUnits08 <> source.InitialUnits08 + OR target.InitialUnits09 <> source.InitialUnits09 + OR target.InitialUnits10 <> source.InitialUnits10 + OR target.InitialUnits11 <> source.InitialUnits11 + OR target.InitialUnits12 <> source.InitialUnits12 + ) + THEN + UPDATE SET + + target.InitialDollars01 = ISNULL(source.InitialDollars01, 0), + target.InitialDollars02 = ISNULL(source.InitialDollars02, 0), + target.InitialDollars03 = ISNULL(source.InitialDollars03, 0), + target.InitialDollars04 = ISNULL(source.InitialDollars04, 0), + target.InitialDollars05 = ISNULL(source.InitialDollars05, 0), + target.InitialDollars06 = ISNULL(source.InitialDollars06, 0), + target.InitialDollars07 = ISNULL(source.InitialDollars07, 0), + target.InitialDollars08 = ISNULL(source.InitialDollars08, 0), + target.InitialDollars09 = ISNULL(source.InitialDollars09, 0), + target.InitialDollars10 = ISNULL(source.InitialDollars10, 0), + target.InitialDollars11 = ISNULL(source.InitialDollars11, 0), + target.InitialDollars12 = ISNULL(source.InitialDollars12, 0), + + target.InitialUnits01 = ISNULL(source.InitialUnits01, 0), + target.InitialUnits02 = ISNULL(source.InitialUnits02, 0), + target.InitialUnits03 = ISNULL(source.InitialUnits03, 0), + target.InitialUnits04 = ISNULL(source.InitialUnits04, 0), + target.InitialUnits05 = ISNULL(source.InitialUnits05, 0), + target.InitialUnits06 = ISNULL(source.InitialUnits06, 0), + target.InitialUnits07 = ISNULL(source.InitialUnits07, 0), + target.InitialUnits08 = ISNULL(source.InitialUnits08, 0), + target.InitialUnits09 = ISNULL(source.InitialUnits09, 0), + target.InitialUnits10 = ISNULL(source.InitialUnits10, 0), + target.InitialUnits11 = ISNULL(source.InitialUnits11, 0), + target.InitialUnits12 = ISNULL(source.InitialUnits12, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, + ServiceEntityID, MSDRGRollupID, UBRevenueCodeID, PrimaryCPTID, PhysicianID, PhysicianSpecialtyID, PerformingProviderID, + PerformingPhysicianSpecialtyID, BilledCPTID, FiscalYearID, + InitialUnits01, InitialUnits02, InitialUnits03, InitialUnits04, InitialUnits05, InitialUnits06, InitialUnits07, InitialUnits08, InitialUnits09, InitialUnits10, InitialUnits11, InitialUnits12, + InitialDollars01, InitialDollars02, InitialDollars03, InitialDollars04, InitialDollars05, InitialDollars06, InitialDollars07, InitialDollars08, InitialDollars09, InitialDollars10, InitialDollars11, InitialDollars12 + ) + VALUES ( + source.EntityID, + source.DepartmentID, + source.ServiceLineID, + source.PatientClassID, + source.AgeCohortID, + source.MedicalSurgicalID, + source.ChargeCodeID, + source.ServiceEntityID, + source.MSDRGID, + source.UBRevCodeID, + source.PrimaryCPTID, + source.ServiceProviderID, + source.ServiceProviderSpecialtyID, + source.PerformingProviderID, + source.PerformingProviderSpecialtyID, + source.BillingCPTID, + source.FiscalYearID, + + ISNULL(source.InitialUnits01, 0), + ISNULL(source.InitialUnits02, 0), + ISNULL(source.InitialUnits03, 0), + ISNULL(source.InitialUnits04, 0), + ISNULL(source.InitialUnits05, 0), + ISNULL(source.InitialUnits06, 0), + ISNULL(source.InitialUnits07, 0), + ISNULL(source.InitialUnits08, 0), + ISNULL(source.InitialUnits09, 0), + ISNULL(source.InitialUnits10, 0), + ISNULL(source.InitialUnits11, 0), + ISNULL(source.InitialUnits12, 0), + + ISNULL(source.InitialDollars01, 0), + ISNULL(source.InitialDollars02, 0), + ISNULL(source.InitialDollars03, 0), + ISNULL(source.InitialDollars04, 0), + ISNULL(source.InitialDollars05, 0), + ISNULL(source.InitialDollars06, 0), + ISNULL(source.InitialDollars07, 0), + ISNULL(source.InitialDollars08, 0), + ISNULL(source.InitialDollars09, 0), + ISNULL(source.InitialDollars10, 0), + ISNULL(source.InitialDollars11, 0), + ISNULL(source.InitialDollars12, 0) + ); +END +GO + + +--------------------------------------------- + +-- fp.procFactChargeVolumeToReportingTransfer +CREATE PROCEDURE [fp].[procFactChargeVolumeToReportingTransfer] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +WITH RECOMPILE +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-12-27 MD JAZZ-29138 Initial Creation + ** 2 2022-06-01 MY JAZZ-33343 Fix Missing Charge Code Join + ** 3 2022-06-03 MY JAZZ-33343 Update Data Source to Pivoted + ** 4 2022-06-29 BW JAZZ-39340 Switching from MSDRGID to MSDRGRollupID + ** 5 2022-12-20 MD JAZZ-47250 Make sure dollars without units are brought over + ** 6 2023-02-23 MY JAZZ-49629 Handing zeroing out for AA data marts + ** 7 2023-03-21 MY JAZZ-49993 Update reporting to support new data model + *************************************************************/ + + -- IMPORTANT NOTE: This proc is only used to transfer data from AP to [fp].[FactReportingAPCharges]. + -- This new proc and table are only used in the new advanced analytics solution that leverages + -- snowflake. This proc will transfer data to [fp].[FactReportingAPCharges], where SQL will then replicate + -- to Snowflake. + -- + -- It's also important to note that this functionality is currently only availible on demand and is not automatically synced. + -- This is also why the current procs aren't targeted. Once we hook this up to the engine, we can properly target the proc. + -- + -- More information can be found here: https://confluence.sdt.local/display/DD/Advanced+Analytics + + SET NOCOUNT ON; + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#SRC') IS NOT NULL DROP TABLE #SRC + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM [fp].[BudgetConfig] WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + + DECLARE @FiscalYearID SMALLINT + SELECT @FiscalYearID = FiscalYearID FROM fp.BudgetConfig WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID + + CREATE TABLE #SRC ( + BudgetConfigID INT, + EntityID INT, + DepartmentID INT, + ServiceLineID INT, + PatientClassID INT, + AgeCohortID INT, + MedicalSurgicalID INT, + ChargeCodeID INT, + FiscalYearID SMALLINT, + + ServiceEntityID INT, + MSDRGID INT, + UBRevCodeID INT, + PrimaryCPTID INT, + ServiceProviderID INT, + ServiceProviderSpecialtyID INT, + PerformingProviderID INT, + PerformingProviderSpecialtyID INT, + BillingCPTID INT, + + BudgetDollars01 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars02 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars03 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars04 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars05 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars06 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars07 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars08 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars09 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars10 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars11 DECIMAL(19, 8) DEFAULT(0), + BudgetDollars12 DECIMAL(19, 8) DEFAULT(0), + ProjectedDollars01 DECIMAL(19, 8) DEFAULT(0), + ProjectedDollars02 DECIMAL(19, 8) DEFAULT(0), + ProjectedDollars03 DECIMAL(19, 8) DEFAULT(0), + ProjectedDollars04 DECIMAL(19, 8) DEFAULT(0), + ProjectedDollars05 DECIMAL(19, 8) DEFAULT(0), + ProjectedDollars06 DECIMAL(19, 8) DEFAULT(0), + ProjectedDollars07 DECIMAL(19, 8) DEFAULT(0), + ProjectedDollars08 DECIMAL(19, 8) DEFAULT(0), + ProjectedDollars09 DECIMAL(19, 8) DEFAULT(0), + ProjectedDollars10 DECIMAL(19, 8) DEFAULT(0), + ProjectedDollars11 DECIMAL(19, 8) DEFAULT(0), + ProjectedDollars12 DECIMAL(19, 8) DEFAULT(0), + TargetDollars01 DECIMAL(19, 8) DEFAULT(0), + TargetDollars02 DECIMAL(19, 8) DEFAULT(0), + TargetDollars03 DECIMAL(19, 8) DEFAULT(0), + TargetDollars04 DECIMAL(19, 8) DEFAULT(0), + TargetDollars05 DECIMAL(19, 8) DEFAULT(0), + TargetDollars06 DECIMAL(19, 8) DEFAULT(0), + TargetDollars07 DECIMAL(19, 8) DEFAULT(0), + TargetDollars08 DECIMAL(19, 8) DEFAULT(0), + TargetDollars09 DECIMAL(19, 8) DEFAULT(0), + TargetDollars10 DECIMAL(19, 8) DEFAULT(0), + TargetDollars11 DECIMAL(19, 8) DEFAULT(0), + TargetDollars12 DECIMAL(19, 8) DEFAULT(0), + + BudgetUnits01 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits02 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits03 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits04 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits05 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits06 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits07 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits08 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits09 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits10 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits11 DECIMAL(19, 8) DEFAULT(0), + BudgetUnits12 DECIMAL(19, 8) DEFAULT(0), + ProjectedUnits01 DECIMAL(19, 8) DEFAULT(0), + ProjectedUnits02 DECIMAL(19, 8) DEFAULT(0), + ProjectedUnits03 DECIMAL(19, 8) DEFAULT(0), + ProjectedUnits04 DECIMAL(19, 8) DEFAULT(0), + ProjectedUnits05 DECIMAL(19, 8) DEFAULT(0), + ProjectedUnits06 DECIMAL(19, 8) DEFAULT(0), + ProjectedUnits07 DECIMAL(19, 8) DEFAULT(0), + ProjectedUnits08 DECIMAL(19, 8) DEFAULT(0), + ProjectedUnits09 DECIMAL(19, 8) DEFAULT(0), + ProjectedUnits10 DECIMAL(19, 8) DEFAULT(0), + ProjectedUnits11 DECIMAL(19, 8) DEFAULT(0), + ProjectedUnits12 DECIMAL(19, 8) DEFAULT(0), + TargetUnits01 DECIMAL(19, 8) DEFAULT(0), + TargetUnits02 DECIMAL(19, 8) DEFAULT(0), + TargetUnits03 DECIMAL(19, 8) DEFAULT(0), + TargetUnits04 DECIMAL(19, 8) DEFAULT(0), + TargetUnits05 DECIMAL(19, 8) DEFAULT(0), + TargetUnits06 DECIMAL(19, 8) DEFAULT(0), + TargetUnits07 DECIMAL(19, 8) DEFAULT(0), + TargetUnits08 DECIMAL(19, 8) DEFAULT(0), + TargetUnits09 DECIMAL(19, 8) DEFAULT(0), + TargetUnits10 DECIMAL(19, 8) DEFAULT(0), + TargetUnits11 DECIMAL(19, 8) DEFAULT(0), + TargetUnits12 DECIMAL(19, 8) DEFAULT(0) + ) + + -- Populate Targeting + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If targeting is empty we need all departments + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fp.ChargeVolume + WHERE BudgetConfigID = @BudgetConfigID + END + + -- Populating Target/Budget Values. + INSERT INTO #SRC (BudgetConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, + ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, PerformingProviderSpecialtyID, + BillingCPTID, FiscalYearID, + TargetUnits01, TargetUnits02, TargetUnits03, TargetUnits04, TargetUnits05, TargetUnits06, TargetUnits07, TargetUnits08, TargetUnits09, TargetUnits10, TargetUnits11, TargetUnits12, + BudgetUnits01, BudgetUnits02, BudgetUnits03, BudgetUnits04, BudgetUnits05, BudgetUnits06, BudgetUnits07, BudgetUnits08, BudgetUnits09, BudgetUnits10, BudgetUnits11, BudgetUnits12, + TargetDollars01, TargetDollars02, TargetDollars03, TargetDollars04, TargetDollars05, TargetDollars06, TargetDollars07, TargetDollars08, TargetDollars09, TargetDollars10, TargetDollars11, TargetDollars12, + BudgetDollars01, BudgetDollars02, BudgetDollars03, BudgetDollars04, BudgetDollars05, BudgetDollars06, BudgetDollars07, BudgetDollars08, BudgetDollars09, BudgetDollars10, BudgetDollars11, BudgetDollars12) + SELECT + cv.BudgetConfigID, + cv.EntityID, + cv.DepartmentID, + cv.ServiceLineID, + cv.PatientClassID, + cv.AgeCohortID, + cv.MedicalSurgicalID, + cv.ChargeCodeID, + cv.ServiceEntityID, + cv.MSDRGID, + cv.UBRevCodeID, + cv.PrimaryCPTID, + cv.ServiceProviderID, + cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, + cv.PerformingProviderSpecialtyID, + cv.BillingCPTID, + @FiscalYearID AS FiscalYearID, + cv.TargetAdjusted01 AS TargetUnits01, + cv.TargetAdjusted02 AS TargetUnits02, + cv.TargetAdjusted03 AS TargetUnits03, + cv.TargetAdjusted04 AS TargetUnits04, + cv.TargetAdjusted05 AS TargetUnits05, + cv.TargetAdjusted06 AS TargetUnits06, + cv.TargetAdjusted07 AS TargetUnits07, + cv.TargetAdjusted08 AS TargetUnits08, + cv.TargetAdjusted09 AS TargetUnits09, + cv.TargetAdjusted10 AS TargetUnits10, + cv.TargetAdjusted11 AS TargetUnits11, + cv.TargetAdjusted12 AS TargetUnits12, + cv.BudgetAdjusted01 AS BudgetUnits01, + cv.BudgetAdjusted02 AS BudgetUnits02, + cv.BudgetAdjusted03 AS BudgetUnits03, + cv.BudgetAdjusted04 AS BudgetUnits04, + cv.BudgetAdjusted05 AS BudgetUnits05, + cv.BudgetAdjusted06 AS BudgetUnits06, + cv.BudgetAdjusted07 AS BudgetUnits07, + cv.BudgetAdjusted08 AS BudgetUnits08, + cv.BudgetAdjusted09 AS BudgetUnits09, + cv.BudgetAdjusted10 AS BudgetUnits10, + cv.BudgetAdjusted11 AS BudgetUnits11, + cv.BudgetAdjusted12 AS BudgetUnits12, + cv.TargetDollarsAdjusted01 AS TargetDollars01, + cv.TargetDollarsAdjusted02 AS TargetDollars02, + cv.TargetDollarsAdjusted03 AS TargetDollars03, + cv.TargetDollarsAdjusted04 AS TargetDollars04, + cv.TargetDollarsAdjusted05 AS TargetDollars05, + cv.TargetDollarsAdjusted06 AS TargetDollars06, + cv.TargetDollarsAdjusted07 AS TargetDollars07, + cv.TargetDollarsAdjusted08 AS TargetDollars08, + cv.TargetDollarsAdjusted09 AS TargetDollars09, + cv.TargetDollarsAdjusted10 AS TargetDollars10, + cv.TargetDollarsAdjusted11 AS TargetDollars11, + cv.TargetDollarsAdjusted12 AS TargetDollars12, + cv.BudgetDollarsAdjusted01 AS BudgetDollars01, + cv.BudgetDollarsAdjusted02 AS BudgetDollars02, + cv.BudgetDollarsAdjusted03 AS BudgetDollars03, + cv.BudgetDollarsAdjusted04 AS BudgetDollars04, + cv.BudgetDollarsAdjusted05 AS BudgetDollars05, + cv.BudgetDollarsAdjusted06 AS BudgetDollars06, + cv.BudgetDollarsAdjusted07 AS BudgetDollars07, + cv.BudgetDollarsAdjusted08 AS BudgetDollars08, + cv.BudgetDollarsAdjusted09 AS BudgetDollars09, + cv.BudgetDollarsAdjusted10 AS BudgetDollars10, + cv.BudgetDollarsAdjusted11 AS BudgetDollars11, + cv.BudgetDollarsAdjusted12 AS BudgetDollars12 + FROM fp.ChargeVolume cv + INNER JOIN #FilterByDepartment dept ON cv.DepartmentID = dept.DepartmentID + WHERE cv.UnitTypeID = 145 + AND cv.BudgetConfigID = @BudgetConfigID + -- JAZZ-47250 - Updating where clause to include CV data that has dollars but no units + AND ((cv.TargetAdjustedTotal != 0 OR cv.TargetDollarsAdjustedTotal != 0) + OR (cv.BudgetAdjustedTotal != 0 OR cv.BudgetDollarsAdjustedTotal != 0)) + + + -- Populating Projection Values + INSERT INTO #SRC (BudgetConfigID, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, + ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, PerformingProviderSpecialtyID, + BillingCPTID, FiscalYearID, + ProjectedUnits01, ProjectedUnits02, ProjectedUnits03, ProjectedUnits04, ProjectedUnits05, ProjectedUnits06, ProjectedUnits07, ProjectedUnits08, ProjectedUnits09, ProjectedUnits10, ProjectedUnits11, ProjectedUnits12, + ProjectedDollars01, ProjectedDollars02, ProjectedDollars03, ProjectedDollars04, ProjectedDollars05, ProjectedDollars06, ProjectedDollars07, ProjectedDollars08, ProjectedDollars09, ProjectedDollars10, ProjectedDollars11, ProjectedDollars12) + SELECT + cv.BudgetConfigID, + cv.EntityID, + cv.DepartmentID, + cv.ServiceLineID, + cv.PatientClassID, + cv.AgeCohortID, + cv.MedicalSurgicalID, + cv.ChargeCodeID, + cv.ServiceEntityID, + cv.MSDRGID, + cv.UBRevCodeID, + cv.PrimaryCPTID, + cv.ServiceProviderID, + cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, + cv.PerformingProviderSpecialtyID, + cv.BillingCPTID, + @FiscalYearID - 1 AS FiscalYearID, + cv.ProjectionAdjusted01 AS ProjectedUnits01, + cv.ProjectionAdjusted02 AS ProjectedUnits02, + cv.ProjectionAdjusted03 AS ProjectedUnits03, + cv.ProjectionAdjusted04 AS ProjectedUnits04, + cv.ProjectionAdjusted05 AS ProjectedUnits05, + cv.ProjectionAdjusted06 AS ProjectedUnits06, + cv.ProjectionAdjusted07 AS ProjectedUnits07, + cv.ProjectionAdjusted08 AS ProjectedUnits08, + cv.ProjectionAdjusted09 AS ProjectedUnits09, + cv.ProjectionAdjusted10 AS ProjectedUnits10, + cv.ProjectionAdjusted11 AS ProjectedUnits11, + cv.ProjectionAdjusted12 AS ProjectedUnits12, + cv.ProjectionDollarsAdjusted01 AS ProjectedDollars01, + cv.ProjectionDollarsAdjusted02 AS ProjectedDollars02, + cv.ProjectionDollarsAdjusted03 AS ProjectedDollars03, + cv.ProjectionDollarsAdjusted04 AS ProjectedDollars04, + cv.ProjectionDollarsAdjusted05 AS ProjectedDollars05, + cv.ProjectionDollarsAdjusted06 AS ProjectedDollars06, + cv.ProjectionDollarsAdjusted07 AS ProjectedDollars07, + cv.ProjectionDollarsAdjusted08 AS ProjectedDollars08, + cv.ProjectionDollarsAdjusted09 AS ProjectedDollars09, + cv.ProjectionDollarsAdjusted10 AS ProjectedDollars10, + cv.ProjectionDollarsAdjusted11 AS ProjectedDollars11, + cv.ProjectionDollarsAdjusted12 AS ProjectedDollars12 + FROM fp.ChargeVolume cv + INNER JOIN #FilterByDepartment dept ON cv.DepartmentID = dept.DepartmentID + WHERE cv.UnitTypeID = 145 + AND cv.BudgetConfigID = @BudgetConfigID + -- JAZZ-47250 - Updating where clause to include CV data that has dollars but no units + AND (cv.ProjectionAdjustedTotal != 0 OR cv.ProjectionDollarsAdjustedTotal != 0) + + IF (@IsDebug = 1) + BEGIN + SELECT + '#SRC' AS TempTable, EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, + ServiceEntityID, MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, + PerformingProviderSpecialtyID, BillingCPTID, FiscalYearID + BudgetDollars01, BudgetDollars02, BudgetDollars03, BudgetDollars04, BudgetDollars05, BudgetDollars06, BudgetDollars07, BudgetDollars08, BudgetDollars09, BudgetDollars10, BudgetDollars11, BudgetDollars12, + ProjectedDollars01, ProjectedDollars02, ProjectedDollars03, ProjectedDollars04, ProjectedDollars05, ProjectedDollars06, ProjectedDollars07, ProjectedDollars08, ProjectedDollars09, ProjectedDollars10, ProjectedDollars11, ProjectedDollars12, + TargetDollars01, TargetDollars02, TargetDollars03, TargetDollars04, TargetDollars05, TargetDollars06, TargetDollars07, TargetDollars08, TargetDollars09, TargetDollars10, TargetDollars11, TargetDollars12, + BudgetUnits01, BudgetUnits02, BudgetUnits03, BudgetUnits04, BudgetUnits05, BudgetUnits06, BudgetUnits07, BudgetUnits08, BudgetUnits09, BudgetUnits10, BudgetUnits11, BudgetUnits12, + ProjectedUnits01, ProjectedUnits02, ProjectedUnits03, ProjectedUnits04, ProjectedUnits05, ProjectedUnits06, ProjectedUnits07, ProjectedUnits08, ProjectedUnits09, ProjectedUnits10, ProjectedUnits11, ProjectedUnits12, + TargetUnits01, TargetUnits02, TargetUnits03, TargetUnits04, TargetUnits05, TargetUnits06, TargetUnits07, TargetUnits08, TargetUnits09, TargetUnits10, TargetUnits11, TargetUnits12 + FROM #SRC; + + RETURN + END + + -- Publish the data from the temp table to fp.FactReportingAPCharges. This uses a merge statement to handle inserts and updates + -- In the event that the active configuration changes, we need to clear out this table because we only hold data for the active configuration. This is done from the UI itself. + -- NOTE: We don't handle DELETES here as there shouldn't ever be a reason to delete the data + ;WITH TGT AS + ( + SELECT + EntityID, FRS.DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, + ServiceEntityID, MSDRGRollupID, UBRevenueCodeID, PrimaryCPTID, PhysicianID, PhysicianSpecialtyID, PerformingProviderID, + PerformingPhysicianSpecialtyID, BilledCPTID, FiscalYearID, + BudgetDollars01, BudgetDollars02, BudgetDollars03, BudgetDollars04, BudgetDollars05, BudgetDollars06, BudgetDollars07, BudgetDollars08, BudgetDollars09, BudgetDollars10, BudgetDollars11, BudgetDollars12, + ProjectedDollars01, ProjectedDollars02, ProjectedDollars03, ProjectedDollars04, ProjectedDollars05, ProjectedDollars06, ProjectedDollars07, ProjectedDollars08, ProjectedDollars09, ProjectedDollars10, ProjectedDollars11, ProjectedDollars12, + TargetDollars01, TargetDollars02, TargetDollars03, TargetDollars04, TargetDollars05, TargetDollars06, TargetDollars07, TargetDollars08, TargetDollars09, TargetDollars10, TargetDollars11, TargetDollars12, + BudgetUnits01, BudgetUnits02, BudgetUnits03, BudgetUnits04, BudgetUnits05, BudgetUnits06, BudgetUnits07, BudgetUnits08, BudgetUnits09, BudgetUnits10, BudgetUnits11, BudgetUnits12, + ProjectedUnits01, ProjectedUnits02, ProjectedUnits03, ProjectedUnits04, ProjectedUnits05, ProjectedUnits06, ProjectedUnits07, ProjectedUnits08, ProjectedUnits09, ProjectedUnits10, ProjectedUnits11, ProjectedUnits12, + TargetUnits01, TargetUnits02, TargetUnits03, TargetUnits04, TargetUnits05, TargetUnits06, TargetUnits07, TargetUnits08, TargetUnits09, TargetUnits10, TargetUnits11, TargetUnits12 + FROM [fp].[FactReportingAPCharges] FRS + INNER JOIN #FilterByDepartment dept ON FRS.DepartmentID = dept.DepartmentID + ) + MERGE TGT AS target + USING #SRC AS source + ON ( + target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.ServiceLineID = source.ServiceLineID + AND target.PatientClassID = source.PatientClassID + AND target.AgeCohortID = source.AgeCohortID + AND target.MedicalSurgicalID = source.MedicalSurgicalID + AND target.ChargeCodeID = source.ChargeCodeID + AND target.ServiceEntityID = source.ServiceEntityID + AND target.MSDRGRollupID = source.MSDRGID + AND target.UBRevenueCodeID = source.UBRevCodeID + AND target.PrimaryCPTID = source.PrimaryCPTID + AND target.PhysicianID = source.ServiceProviderID + AND target.PhysicianSpecialtyID = source.ServiceProviderSpecialtyID + AND target.PerformingProviderID = source.PerformingProviderID + AND target.PerformingPhysicianSpecialtyID = source.PerformingProviderSpecialtyID + AND target.BilledCPTID = source.BillingCPTID + AND target.FiscalYearID = source.FiscalYearID + ) + WHEN MATCHED AND + ( + target.BudgetDollars01 <> source.BudgetDollars01 + OR target.BudgetDollars02 <> source.BudgetDollars02 + OR target.BudgetDollars03 <> source.BudgetDollars03 + OR target.BudgetDollars04 <> source.BudgetDollars04 + OR target.BudgetDollars05 <> source.BudgetDollars05 + OR target.BudgetDollars06 <> source.BudgetDollars06 + OR target.BudgetDollars07 <> source.BudgetDollars07 + OR target.BudgetDollars08 <> source.BudgetDollars08 + OR target.BudgetDollars09 <> source.BudgetDollars09 + OR target.BudgetDollars10 <> source.BudgetDollars10 + OR target.BudgetDollars11 <> source.BudgetDollars11 + OR target.BudgetDollars12 <> source.BudgetDollars12 + + OR target.ProjectedDollars01 <> source.ProjectedDollars01 + OR target.ProjectedDollars02 <> source.ProjectedDollars02 + OR target.ProjectedDollars03 <> source.ProjectedDollars03 + OR target.ProjectedDollars04 <> source.ProjectedDollars04 + OR target.ProjectedDollars05 <> source.ProjectedDollars05 + OR target.ProjectedDollars06 <> source.ProjectedDollars06 + OR target.ProjectedDollars07 <> source.ProjectedDollars07 + OR target.ProjectedDollars08 <> source.ProjectedDollars08 + OR target.ProjectedDollars09 <> source.ProjectedDollars09 + OR target.ProjectedDollars10 <> source.ProjectedDollars10 + OR target.ProjectedDollars11 <> source.ProjectedDollars11 + OR target.ProjectedDollars12 <> source.ProjectedDollars12 + + OR target.TargetDollars01 <> source.TargetDollars01 + OR target.TargetDollars02 <> source.TargetDollars02 + OR target.TargetDollars03 <> source.TargetDollars03 + OR target.TargetDollars04 <> source.TargetDollars04 + OR target.TargetDollars05 <> source.TargetDollars05 + OR target.TargetDollars06 <> source.TargetDollars06 + OR target.TargetDollars07 <> source.TargetDollars07 + OR target.TargetDollars08 <> source.TargetDollars08 + OR target.TargetDollars09 <> source.TargetDollars09 + OR target.TargetDollars10 <> source.TargetDollars10 + OR target.TargetDollars11 <> source.TargetDollars11 + OR target.TargetDollars12 <> source.TargetDollars12 + + OR target.BudgetUnits01 <> source.BudgetUnits01 + OR target.BudgetUnits02 <> source.BudgetUnits02 + OR target.BudgetUnits03 <> source.BudgetUnits03 + OR target.BudgetUnits04 <> source.BudgetUnits04 + OR target.BudgetUnits05 <> source.BudgetUnits05 + OR target.BudgetUnits06 <> source.BudgetUnits06 + OR target.BudgetUnits07 <> source.BudgetUnits07 + OR target.BudgetUnits08 <> source.BudgetUnits08 + OR target.BudgetUnits09 <> source.BudgetUnits09 + OR target.BudgetUnits10 <> source.BudgetUnits10 + OR target.BudgetUnits11 <> source.BudgetUnits11 + OR target.BudgetUnits12 <> source.BudgetUnits12 + + OR target.ProjectedUnits01 <> source.ProjectedUnits01 + OR target.ProjectedUnits02 <> source.ProjectedUnits02 + OR target.ProjectedUnits03 <> source.ProjectedUnits03 + OR target.ProjectedUnits04 <> source.ProjectedUnits04 + OR target.ProjectedUnits05 <> source.ProjectedUnits05 + OR target.ProjectedUnits06 <> source.ProjectedUnits06 + OR target.ProjectedUnits07 <> source.ProjectedUnits07 + OR target.ProjectedUnits08 <> source.ProjectedUnits08 + OR target.ProjectedUnits09 <> source.ProjectedUnits09 + OR target.ProjectedUnits10 <> source.ProjectedUnits10 + OR target.ProjectedUnits11 <> source.ProjectedUnits11 + OR target.ProjectedUnits12 <> source.ProjectedUnits12 + + OR target.TargetUnits01 <> source.TargetUnits01 + OR target.TargetUnits02 <> source.TargetUnits02 + OR target.TargetUnits03 <> source.TargetUnits03 + OR target.TargetUnits04 <> source.TargetUnits04 + OR target.TargetUnits05 <> source.TargetUnits05 + OR target.TargetUnits06 <> source.TargetUnits06 + OR target.TargetUnits07 <> source.TargetUnits07 + OR target.TargetUnits08 <> source.TargetUnits08 + OR target.TargetUnits09 <> source.TargetUnits09 + OR target.TargetUnits10 <> source.TargetUnits10 + OR target.TargetUnits11 <> source.TargetUnits11 + OR target.TargetUnits12 <> source.TargetUnits12 + ) + THEN + UPDATE SET + target.BudgetDollars01 = ISNULL(source.BudgetDollars01, 0), + target.BudgetDollars02 = ISNULL(source.BudgetDollars02, 0), + target.BudgetDollars03 = ISNULL(source.BudgetDollars03, 0), + target.BudgetDollars04 = ISNULL(source.BudgetDollars04, 0), + target.BudgetDollars05 = ISNULL(source.BudgetDollars05, 0), + target.BudgetDollars06 = ISNULL(source.BudgetDollars06, 0), + target.BudgetDollars07 = ISNULL(source.BudgetDollars07, 0), + target.BudgetDollars08 = ISNULL(source.BudgetDollars08, 0), + target.BudgetDollars09 = ISNULL(source.BudgetDollars09, 0), + target.BudgetDollars10 = ISNULL(source.BudgetDollars10, 0), + target.BudgetDollars11 = ISNULL(source.BudgetDollars11, 0), + target.BudgetDollars12 = ISNULL(source.BudgetDollars12, 0), + + target.ProjectedDollars01 = ISNULL(source.ProjectedDollars01, 0), + target.ProjectedDollars02 = ISNULL(source.ProjectedDollars02, 0), + target.ProjectedDollars03 = ISNULL(source.ProjectedDollars03, 0), + target.ProjectedDollars04 = ISNULL(source.ProjectedDollars04, 0), + target.ProjectedDollars05 = ISNULL(source.ProjectedDollars05, 0), + target.ProjectedDollars06 = ISNULL(source.ProjectedDollars06, 0), + target.ProjectedDollars07 = ISNULL(source.ProjectedDollars07, 0), + target.ProjectedDollars08 = ISNULL(source.ProjectedDollars08, 0), + target.ProjectedDollars09 = ISNULL(source.ProjectedDollars09, 0), + target.ProjectedDollars10 = ISNULL(source.ProjectedDollars10, 0), + target.ProjectedDollars11 = ISNULL(source.ProjectedDollars11, 0), + target.ProjectedDollars12 = ISNULL(source.ProjectedDollars12, 0), + + target.TargetDollars01 = ISNULL(source.TargetDollars01, 0), + target.TargetDollars02 = ISNULL(source.TargetDollars02, 0), + target.TargetDollars03 = ISNULL(source.TargetDollars03, 0), + target.TargetDollars04 = ISNULL(source.TargetDollars04, 0), + target.TargetDollars05 = ISNULL(source.TargetDollars05, 0), + target.TargetDollars06 = ISNULL(source.TargetDollars06, 0), + target.TargetDollars07 = ISNULL(source.TargetDollars07, 0), + target.TargetDollars08 = ISNULL(source.TargetDollars08, 0), + target.TargetDollars09 = ISNULL(source.TargetDollars09, 0), + target.TargetDollars10 = ISNULL(source.TargetDollars10, 0), + target.TargetDollars11 = ISNULL(source.TargetDollars11, 0), + target.TargetDollars12 = ISNULL(source.TargetDollars12, 0), + + target.BudgetUnits01 = ISNULL(source.BudgetUnits01, 0), + target.BudgetUnits02 = ISNULL(source.BudgetUnits02, 0), + target.BudgetUnits03 = ISNULL(source.BudgetUnits03, 0), + target.BudgetUnits04 = ISNULL(source.BudgetUnits04, 0), + target.BudgetUnits05 = ISNULL(source.BudgetUnits05, 0), + target.BudgetUnits06 = ISNULL(source.BudgetUnits06, 0), + target.BudgetUnits07 = ISNULL(source.BudgetUnits07, 0), + target.BudgetUnits08 = ISNULL(source.BudgetUnits08, 0), + target.BudgetUnits09 = ISNULL(source.BudgetUnits09, 0), + target.BudgetUnits10 = ISNULL(source.BudgetUnits10, 0), + target.BudgetUnits11 = ISNULL(source.BudgetUnits11, 0), + target.BudgetUnits12 = ISNULL(source.BudgetUnits12, 0), + + target.ProjectedUnits01 = ISNULL(source.ProjectedUnits01, 0), + target.ProjectedUnits02 = ISNULL(source.ProjectedUnits02, 0), + target.ProjectedUnits03 = ISNULL(source.ProjectedUnits03, 0), + target.ProjectedUnits04 = ISNULL(source.ProjectedUnits04, 0), + target.ProjectedUnits05 = ISNULL(source.ProjectedUnits05, 0), + target.ProjectedUnits06 = ISNULL(source.ProjectedUnits06, 0), + target.ProjectedUnits07 = ISNULL(source.ProjectedUnits07, 0), + target.ProjectedUnits08 = ISNULL(source.ProjectedUnits08, 0), + target.ProjectedUnits09 = ISNULL(source.ProjectedUnits09, 0), + target.ProjectedUnits10 = ISNULL(source.ProjectedUnits10, 0), + target.ProjectedUnits11 = ISNULL(source.ProjectedUnits11, 0), + target.ProjectedUnits12 = ISNULL(source.ProjectedUnits12, 0), + + target.TargetUnits01 = ISNULL(source.TargetUnits01, 0), + target.TargetUnits02 = ISNULL(source.TargetUnits02, 0), + target.TargetUnits03 = ISNULL(source.TargetUnits03, 0), + target.TargetUnits04 = ISNULL(source.TargetUnits04, 0), + target.TargetUnits05 = ISNULL(source.TargetUnits05, 0), + target.TargetUnits06 = ISNULL(source.TargetUnits06, 0), + target.TargetUnits07 = ISNULL(source.TargetUnits07, 0), + target.TargetUnits08 = ISNULL(source.TargetUnits08, 0), + target.TargetUnits09 = ISNULL(source.TargetUnits09, 0), + target.TargetUnits10 = ISNULL(source.TargetUnits10, 0), + target.TargetUnits11 = ISNULL(source.TargetUnits11, 0), + target.TargetUnits12 = ISNULL(source.TargetUnits12, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + EntityID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID, + ServiceEntityID, MSDRGRollupID, UBRevenueCodeID, PrimaryCPTID, PhysicianID, PhysicianSpecialtyID, PerformingProviderID, + PerformingPhysicianSpecialtyID, BilledCPTID, FiscalYearID, + BudgetDollars01, BudgetDollars02, BudgetDollars03, BudgetDollars04, BudgetDollars05, BudgetDollars06, BudgetDollars07, BudgetDollars08, BudgetDollars09, BudgetDollars10, BudgetDollars11, BudgetDollars12, + ProjectedDollars01, ProjectedDollars02, ProjectedDollars03, ProjectedDollars04, ProjectedDollars05, ProjectedDollars06, ProjectedDollars07, ProjectedDollars08, ProjectedDollars09, ProjectedDollars10, ProjectedDollars11, ProjectedDollars12, + TargetDollars01, TargetDollars02, TargetDollars03, TargetDollars04, TargetDollars05, TargetDollars06, TargetDollars07, TargetDollars08, TargetDollars09, TargetDollars10, TargetDollars11, TargetDollars12, + BudgetUnits01, BudgetUnits02, BudgetUnits03, BudgetUnits04, BudgetUnits05, BudgetUnits06, BudgetUnits07, BudgetUnits08, BudgetUnits09, BudgetUnits10, BudgetUnits11, BudgetUnits12, + ProjectedUnits01, ProjectedUnits02, ProjectedUnits03, ProjectedUnits04, ProjectedUnits05, ProjectedUnits06, ProjectedUnits07, ProjectedUnits08, ProjectedUnits09, ProjectedUnits10, ProjectedUnits11, ProjectedUnits12, + TargetUnits01, TargetUnits02, TargetUnits03, TargetUnits04, TargetUnits05, TargetUnits06, TargetUnits07, TargetUnits08, TargetUnits09, TargetUnits10, TargetUnits11, TargetUnits12 + ) + VALUES ( + source.EntityID, + source.DepartmentID, + source.ServiceLineID, + source.PatientClassID, + source.AgeCohortID, + source.MedicalSurgicalID, + source.ChargeCodeID, + source.ServiceEntityID, + source.MSDRGID, + source.UBRevCodeID, + source.PrimaryCPTID, + source.ServiceProviderID, + source.ServiceProviderSpecialtyID, + source.PerformingProviderID, + source.PerformingProviderSpecialtyID, + source.BillingCPTID, + source.FiscalYearID, + ISNULL(source.BudgetDollars01, 0), + ISNULL(source.BudgetDollars02, 0), + ISNULL(source.BudgetDollars03, 0), + ISNULL(source.BudgetDollars04, 0), + ISNULL(source.BudgetDollars05, 0), + ISNULL(source.BudgetDollars06, 0), + ISNULL(source.BudgetDollars07, 0), + ISNULL(source.BudgetDollars08, 0), + ISNULL(source.BudgetDollars09, 0), + ISNULL(source.BudgetDollars10, 0), + ISNULL(source.BudgetDollars11, 0), + ISNULL(source.BudgetDollars12, 0), + ISNULL(source.ProjectedDollars01, 0), + ISNULL(source.ProjectedDollars02, 0), + ISNULL(source.ProjectedDollars03, 0), + ISNULL(source.ProjectedDollars04, 0), + ISNULL(source.ProjectedDollars05, 0), + ISNULL(source.ProjectedDollars06, 0), + ISNULL(source.ProjectedDollars07, 0), + ISNULL(source.ProjectedDollars08, 0), + ISNULL(source.ProjectedDollars09, 0), + ISNULL(source.ProjectedDollars10, 0), + ISNULL(source.ProjectedDollars11, 0), + ISNULL(source.ProjectedDollars12, 0), + ISNULL(source.TargetDollars01, 0), + ISNULL(source.TargetDollars02, 0), + ISNULL(source.TargetDollars03, 0), + ISNULL(source.TargetDollars04, 0), + ISNULL(source.TargetDollars05, 0), + ISNULL(source.TargetDollars06, 0), + ISNULL(source.TargetDollars07, 0), + ISNULL(source.TargetDollars08, 0), + ISNULL(source.TargetDollars09, 0), + ISNULL(source.TargetDollars10, 0), + ISNULL(source.TargetDollars11, 0), + ISNULL(source.TargetDollars12, 0), + ISNULL(source.BudgetUnits01, 0), + ISNULL(source.BudgetUnits02, 0), + ISNULL(source.BudgetUnits03, 0), + ISNULL(source.BudgetUnits04, 0), + ISNULL(source.BudgetUnits05, 0), + ISNULL(source.BudgetUnits06, 0), + ISNULL(source.BudgetUnits07, 0), + ISNULL(source.BudgetUnits08, 0), + ISNULL(source.BudgetUnits09, 0), + ISNULL(source.BudgetUnits10, 0), + ISNULL(source.BudgetUnits11, 0), + ISNULL(source.BudgetUnits12, 0), + ISNULL(source.ProjectedUnits01, 0), + ISNULL(source.ProjectedUnits02, 0), + ISNULL(source.ProjectedUnits03, 0), + ISNULL(source.ProjectedUnits04, 0), + ISNULL(source.ProjectedUnits05, 0), + ISNULL(source.ProjectedUnits06, 0), + ISNULL(source.ProjectedUnits07, 0), + ISNULL(source.ProjectedUnits08, 0), + ISNULL(source.ProjectedUnits09, 0), + ISNULL(source.ProjectedUnits10, 0), + ISNULL(source.ProjectedUnits11, 0), + ISNULL(source.ProjectedUnits12, 0), + ISNULL(source.TargetUnits01, 0), + ISNULL(source.TargetUnits02, 0), + ISNULL(source.TargetUnits03, 0), + ISNULL(source.TargetUnits04, 0), + ISNULL(source.TargetUnits05, 0), + ISNULL(source.TargetUnits06, 0), + ISNULL(source.TargetUnits07, 0), + ISNULL(source.TargetUnits08, 0), + ISNULL(source.TargetUnits09, 0), + ISNULL(source.TargetUnits10, 0), + ISNULL(source.TargetUnits11, 0), + ISNULL(source.TargetUnits12, 0) + ); + + ------------------------------------------------------------------------------------------------------- + -- JAZZ-49629 : Handing zeroing out for AA data marts + -- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the + -- targeting above. + ------------------------------------------------------------------------------------------------------- + + -- Get all records that were adjusted + SELECT DISTINCT chg.ChargeVolumeID + INTO #adjustedRecords + FROM [fp].[ChargeVolumeChangeHistory] chg + INNER JOIN [fp].[ChargeVolume] fgl ON chg.ChargeVolumeID = fgl.ChargeVolumeID + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fgl.DepartmentID + WHERE chg.BudgetConfigID = @BudgetConfigID + + -- Get the records that have 0's in them that might have been filtered out from the previous logic + SELECT + cv.BudgetConfigID, + cv.EntityID, + cv.DepartmentID, + cv.ServiceLineID, + cv.PatientClassID, + cv.AgeCohortID, + cv.MedicalSurgicalID, + cv.ChargeCodeID, + cv.ServiceEntityID, + cv.MSDRGID, + cv.UBRevCodeID, + cv.PrimaryCPTID, + cv.ServiceProviderID, + cv.ServiceProviderSpecialtyID, + cv.PerformingProviderID, + cv.PerformingProviderSpecialtyID, + cv.BillingCPTID, + cv.TargetAdjusted01 AS TargetUnits01, + cv.TargetAdjusted02 AS TargetUnits02, + cv.TargetAdjusted03 AS TargetUnits03, + cv.TargetAdjusted04 AS TargetUnits04, + cv.TargetAdjusted05 AS TargetUnits05, + cv.TargetAdjusted06 AS TargetUnits06, + cv.TargetAdjusted07 AS TargetUnits07, + cv.TargetAdjusted08 AS TargetUnits08, + cv.TargetAdjusted09 AS TargetUnits09, + cv.TargetAdjusted10 AS TargetUnits10, + cv.TargetAdjusted11 AS TargetUnits11, + cv.TargetAdjusted12 AS TargetUnits12, + cv.BudgetAdjusted01 AS BudgetUnits01, + cv.BudgetAdjusted02 AS BudgetUnits02, + cv.BudgetAdjusted03 AS BudgetUnits03, + cv.BudgetAdjusted04 AS BudgetUnits04, + cv.BudgetAdjusted05 AS BudgetUnits05, + cv.BudgetAdjusted06 AS BudgetUnits06, + cv.BudgetAdjusted07 AS BudgetUnits07, + cv.BudgetAdjusted08 AS BudgetUnits08, + cv.BudgetAdjusted09 AS BudgetUnits09, + cv.BudgetAdjusted10 AS BudgetUnits10, + cv.BudgetAdjusted11 AS BudgetUnits11, + cv.BudgetAdjusted12 AS BudgetUnits12, + cv.ProjectionAdjusted01 AS ProjectionUnits01, + cv.ProjectionAdjusted02 AS ProjectionUnits02, + cv.ProjectionAdjusted03 AS ProjectionUnits03, + cv.ProjectionAdjusted04 AS ProjectionUnits04, + cv.ProjectionAdjusted05 AS ProjectionUnits05, + cv.ProjectionAdjusted06 AS ProjectionUnits06, + cv.ProjectionAdjusted07 AS ProjectionUnits07, + cv.ProjectionAdjusted08 AS ProjectionUnits08, + cv.ProjectionAdjusted09 AS ProjectionUnits09, + cv.ProjectionAdjusted10 AS ProjectionUnits10, + cv.ProjectionAdjusted11 AS ProjectionUnits11, + cv.ProjectionAdjusted12 AS ProjectionUnits12, + cv.TargetDollarsAdjusted01 AS TargetDollars01, + cv.TargetDollarsAdjusted02 AS TargetDollars02, + cv.TargetDollarsAdjusted03 AS TargetDollars03, + cv.TargetDollarsAdjusted04 AS TargetDollars04, + cv.TargetDollarsAdjusted05 AS TargetDollars05, + cv.TargetDollarsAdjusted06 AS TargetDollars06, + cv.TargetDollarsAdjusted07 AS TargetDollars07, + cv.TargetDollarsAdjusted08 AS TargetDollars08, + cv.TargetDollarsAdjusted09 AS TargetDollars09, + cv.TargetDollarsAdjusted10 AS TargetDollars10, + cv.TargetDollarsAdjusted11 AS TargetDollars11, + cv.TargetDollarsAdjusted12 AS TargetDollars12, + cv.BudgetDollarsAdjusted01 AS BudgetDollars01, + cv.BudgetDollarsAdjusted02 AS BudgetDollars02, + cv.BudgetDollarsAdjusted03 AS BudgetDollars03, + cv.BudgetDollarsAdjusted04 AS BudgetDollars04, + cv.BudgetDollarsAdjusted05 AS BudgetDollars05, + cv.BudgetDollarsAdjusted06 AS BudgetDollars06, + cv.BudgetDollarsAdjusted07 AS BudgetDollars07, + cv.BudgetDollarsAdjusted08 AS BudgetDollars08, + cv.BudgetDollarsAdjusted09 AS BudgetDollars09, + cv.BudgetDollarsAdjusted10 AS BudgetDollars10, + cv.BudgetDollarsAdjusted11 AS BudgetDollars11, + cv.BudgetDollarsAdjusted12 AS BudgetDollars12, + cv.ProjectionDollarsAdjusted01 AS ProjectionDollars01, + cv.ProjectionDollarsAdjusted02 AS ProjectionDollars02, + cv.ProjectionDollarsAdjusted03 AS ProjectionDollars03, + cv.ProjectionDollarsAdjusted04 AS ProjectionDollars04, + cv.ProjectionDollarsAdjusted05 AS ProjectionDollars05, + cv.ProjectionDollarsAdjusted06 AS ProjectionDollars06, + cv.ProjectionDollarsAdjusted07 AS ProjectionDollars07, + cv.ProjectionDollarsAdjusted08 AS ProjectionDollars08, + cv.ProjectionDollarsAdjusted09 AS ProjectionDollars09, + cv.ProjectionDollarsAdjusted10 AS ProjectionDollars10, + cv.ProjectionDollarsAdjusted11 AS ProjectionDollars11, + cv.ProjectionDollarsAdjusted12 AS ProjectionDollars12 + INTO #tempUnpivoted + FROM fp.ChargeVolume cv + INNER JOIN #FilterByDepartment dept ON cv.DepartmentID = dept.DepartmentID + INNER JOIN #adjustedRecords adj ON cv.ChargeVolumeID = adj.ChargeVolumeID + WHERE cv.UnitTypeID = 145 + AND cv.BudgetConfigID = @BudgetConfigID + -- JAZZ-47250 - Updating where clause to include CV data that has dollars but no units + AND ( + (cv.TargetAdjustedTotal = 0 OR cv.TargetDollarsAdjustedTotal = 0) + OR (cv.BudgetAdjustedTotal = 0 OR cv.BudgetDollarsAdjustedTotal = 0) + OR (cv.ProjectionAdjustedTotal = 0 OR cv.ProjectionDollarsAdjustedTotal = 0) + ) + + -- Find the records that need to be updated by comparing the source to the reporting table + SELECT + frgl.RowID, + cv.TargetUnits01, + cv.TargetUnits02, + cv.TargetUnits03, + cv.TargetUnits04, + cv.TargetUnits05, + cv.TargetUnits06, + cv.TargetUnits07, + cv.TargetUnits08, + cv.TargetUnits09, + cv.TargetUnits10, + cv.TargetUnits11, + cv.TargetUnits12, + cv.BudgetUnits01, + cv.BudgetUnits02, + cv.BudgetUnits03, + cv.BudgetUnits04, + cv.BudgetUnits05, + cv.BudgetUnits06, + cv.BudgetUnits07, + cv.BudgetUnits08, + cv.BudgetUnits09, + cv.BudgetUnits10, + cv.BudgetUnits11, + cv.BudgetUnits12, + cv.ProjectionUnits01, + cv.ProjectionUnits02, + cv.ProjectionUnits03, + cv.ProjectionUnits04, + cv.ProjectionUnits05, + cv.ProjectionUnits06, + cv.ProjectionUnits07, + cv.ProjectionUnits08, + cv.ProjectionUnits09, + cv.ProjectionUnits10, + cv.ProjectionUnits11, + cv.ProjectionUnits12, + cv.TargetDollars01, + cv.TargetDollars02, + cv.TargetDollars03, + cv.TargetDollars04, + cv.TargetDollars05, + cv.TargetDollars06, + cv.TargetDollars07, + cv.TargetDollars08, + cv.TargetDollars09, + cv.TargetDollars10, + cv.TargetDollars11, + cv.TargetDollars12, + cv.BudgetDollars01, + cv.BudgetDollars02, + cv.BudgetDollars03, + cv.BudgetDollars04, + cv.BudgetDollars05, + cv.BudgetDollars06, + cv.BudgetDollars07, + cv.BudgetDollars08, + cv.BudgetDollars09, + cv.BudgetDollars10, + cv.BudgetDollars11, + cv.BudgetDollars12, + cv.ProjectionDollars01, + cv.ProjectionDollars02, + cv.ProjectionDollars03, + cv.ProjectionDollars04, + cv.ProjectionDollars05, + cv.ProjectionDollars06, + cv.ProjectionDollars07, + cv.ProjectionDollars08, + cv.ProjectionDollars09, + cv.ProjectionDollars10, + cv.ProjectionDollars11, + cv.ProjectionDollars12 + INTO #dataToUpdate_Budget + FROM [fp].[FactReportingAPCharges] frgl + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = frgl.DepartmentID + INNER JOIN #tempUnpivoted cv ON + cv.EntityID = frgl.EntityID + AND cv.DepartmentID = frgl.DepartmentID + AND cv.ServiceLineID = frgl.ServiceLineID + AND cv.PatientClassID = frgl.PatientClassID + AND cv.AgeCohortID = frgl.AgeCohortID + AND cv.MedicalSurgicalID = frgl.MedicalSurgicalID + AND cv.ChargeCodeID = frgl.ChargeCodeID + AND cv.ServiceEntityID = frgl.ServiceEntityID + AND cv.MSDRGID = frgl.MSDRGRollupID + AND cv.UBRevCodeID = frgl.UBRevenueCodeID + AND cv.PrimaryCPTID = frgl.PrimaryCPTID + AND cv.ServiceProviderID = frgl.PhysicianID + AND cv.ServiceProviderSpecialtyID = frgl.PhysicianSpecialtyID + AND cv.PerformingProviderID = frgl.PerformingProviderID + AND cv.PerformingProviderSpecialtyID = frgl.PerformingPhysicianSpecialtyID + AND cv.BillingCPTID = frgl.BilledCPTID + AND @FiscalYearID = frgl.FiscalYearID + WHERE 1 = 1 + AND ( + cv.TargetUnits01 != frgl.TargetUnits01 + OR cv.TargetUnits02 != frgl.TargetUnits02 + OR cv.TargetUnits03 != frgl.TargetUnits03 + OR cv.TargetUnits04 != frgl.TargetUnits04 + OR cv.TargetUnits05 != frgl.TargetUnits05 + OR cv.TargetUnits06 != frgl.TargetUnits06 + OR cv.TargetUnits07 != frgl.TargetUnits07 + OR cv.TargetUnits08 != frgl.TargetUnits08 + OR cv.TargetUnits09 != frgl.TargetUnits09 + OR cv.TargetUnits10 != frgl.TargetUnits10 + OR cv.TargetUnits11 != frgl.TargetUnits11 + OR cv.TargetUnits12 != frgl.TargetUnits12 + OR cv.BudgetUnits01 != frgl.BudgetUnits01 + OR cv.BudgetUnits02 != frgl.BudgetUnits02 + OR cv.BudgetUnits03 != frgl.BudgetUnits03 + OR cv.BudgetUnits04 != frgl.BudgetUnits04 + OR cv.BudgetUnits05 != frgl.BudgetUnits05 + OR cv.BudgetUnits06 != frgl.BudgetUnits06 + OR cv.BudgetUnits07 != frgl.BudgetUnits07 + OR cv.BudgetUnits08 != frgl.BudgetUnits08 + OR cv.BudgetUnits09 != frgl.BudgetUnits09 + OR cv.BudgetUnits10 != frgl.BudgetUnits10 + OR cv.BudgetUnits11 != frgl.BudgetUnits11 + OR cv.BudgetUnits12 != frgl.BudgetUnits12 + OR cv.TargetDollars01 != frgl.TargetDollars01 + OR cv.TargetDollars02 != frgl.TargetDollars02 + OR cv.TargetDollars03 != frgl.TargetDollars03 + OR cv.TargetDollars04 != frgl.TargetDollars04 + OR cv.TargetDollars05 != frgl.TargetDollars05 + OR cv.TargetDollars06 != frgl.TargetDollars06 + OR cv.TargetDollars07 != frgl.TargetDollars07 + OR cv.TargetDollars08 != frgl.TargetDollars08 + OR cv.TargetDollars09 != frgl.TargetDollars09 + OR cv.TargetDollars10 != frgl.TargetDollars10 + OR cv.TargetDollars11 != frgl.TargetDollars11 + OR cv.TargetDollars12 != frgl.TargetDollars12 + OR cv.BudgetDollars01 != frgl.BudgetDollars01 + OR cv.BudgetDollars02 != frgl.BudgetDollars02 + OR cv.BudgetDollars03 != frgl.BudgetDollars03 + OR cv.BudgetDollars04 != frgl.BudgetDollars04 + OR cv.BudgetDollars05 != frgl.BudgetDollars05 + OR cv.BudgetDollars06 != frgl.BudgetDollars06 + OR cv.BudgetDollars07 != frgl.BudgetDollars07 + OR cv.BudgetDollars08 != frgl.BudgetDollars08 + OR cv.BudgetDollars09 != frgl.BudgetDollars09 + OR cv.BudgetDollars10 != frgl.BudgetDollars10 + OR cv.BudgetDollars11 != frgl.BudgetDollars11 + OR cv.BudgetDollars12 != frgl.BudgetDollars12 + ) + + SELECT + frgl.RowID, + cv.ProjectionUnits01, + cv.ProjectionUnits02, + cv.ProjectionUnits03, + cv.ProjectionUnits04, + cv.ProjectionUnits05, + cv.ProjectionUnits06, + cv.ProjectionUnits07, + cv.ProjectionUnits08, + cv.ProjectionUnits09, + cv.ProjectionUnits10, + cv.ProjectionUnits11, + cv.ProjectionUnits12, + cv.ProjectionDollars01, + cv.ProjectionDollars02, + cv.ProjectionDollars03, + cv.ProjectionDollars04, + cv.ProjectionDollars05, + cv.ProjectionDollars06, + cv.ProjectionDollars07, + cv.ProjectionDollars08, + cv.ProjectionDollars09, + cv.ProjectionDollars10, + cv.ProjectionDollars11, + cv.ProjectionDollars12 + INTO #dataToUpdate_Projection + FROM [fp].[FactReportingAPCharges] frgl + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = frgl.DepartmentID + INNER JOIN #tempUnpivoted cv ON + cv.EntityID = frgl.EntityID + AND cv.DepartmentID = frgl.DepartmentID + AND cv.ServiceLineID = frgl.ServiceLineID + AND cv.PatientClassID = frgl.PatientClassID + AND cv.AgeCohortID = frgl.AgeCohortID + AND cv.MedicalSurgicalID = frgl.MedicalSurgicalID + AND cv.ChargeCodeID = frgl.ChargeCodeID + AND cv.ServiceEntityID = frgl.ServiceEntityID + AND cv.MSDRGID = frgl.MSDRGRollupID + AND cv.UBRevCodeID = frgl.UBRevenueCodeID + AND cv.PrimaryCPTID = frgl.PrimaryCPTID + AND cv.ServiceProviderID = frgl.PhysicianID + AND cv.ServiceProviderSpecialtyID = frgl.PhysicianSpecialtyID + AND cv.PerformingProviderID = frgl.PerformingProviderID + AND cv.PerformingProviderSpecialtyID = frgl.PerformingPhysicianSpecialtyID + AND cv.BillingCPTID = frgl.BilledCPTID + AND @FiscalYearID - 1 = frgl.FiscalYearID + WHERE 1 = 1 + AND ( + cv.ProjectionUnits01 != frgl.ProjectedUnits01 + OR cv.ProjectionUnits02 != frgl.ProjectedUnits02 + OR cv.ProjectionUnits03 != frgl.ProjectedUnits03 + OR cv.ProjectionUnits04 != frgl.ProjectedUnits04 + OR cv.ProjectionUnits05 != frgl.ProjectedUnits05 + OR cv.ProjectionUnits06 != frgl.ProjectedUnits06 + OR cv.ProjectionUnits07 != frgl.ProjectedUnits07 + OR cv.ProjectionUnits08 != frgl.ProjectedUnits08 + OR cv.ProjectionUnits09 != frgl.ProjectedUnits09 + OR cv.ProjectionUnits10 != frgl.ProjectedUnits10 + OR cv.ProjectionUnits11 != frgl.ProjectedUnits11 + OR cv.ProjectionUnits12 != frgl.ProjectedUnits12 + OR cv.ProjectionDollars01 != frgl.ProjectedDollars01 + OR cv.ProjectionDollars02 != frgl.ProjectedDollars02 + OR cv.ProjectionDollars03 != frgl.ProjectedDollars03 + OR cv.ProjectionDollars04 != frgl.ProjectedDollars04 + OR cv.ProjectionDollars05 != frgl.ProjectedDollars05 + OR cv.ProjectionDollars06 != frgl.ProjectedDollars06 + OR cv.ProjectionDollars07 != frgl.ProjectedDollars07 + OR cv.ProjectionDollars08 != frgl.ProjectedDollars08 + OR cv.ProjectionDollars09 != frgl.ProjectedDollars09 + OR cv.ProjectionDollars10 != frgl.ProjectedDollars10 + OR cv.ProjectionDollars11 != frgl.ProjectedDollars11 + OR cv.ProjectionDollars12 != frgl.ProjectedDollars12 + ) + + -- Update the records + UPDATE report + SET + report.TargetUnits01 = upd.TargetUnits01, + report.TargetUnits02 = upd.TargetUnits02, + report.TargetUnits03 = upd.TargetUnits03, + report.TargetUnits04 = upd.TargetUnits04, + report.TargetUnits05 = upd.TargetUnits05, + report.TargetUnits06 = upd.TargetUnits06, + report.TargetUnits07 = upd.TargetUnits07, + report.TargetUnits08 = upd.TargetUnits08, + report.TargetUnits09 = upd.TargetUnits09, + report.TargetUnits10 = upd.TargetUnits10, + report.TargetUnits11 = upd.TargetUnits11, + report.TargetUnits12 = upd.TargetUnits12, + report.BudgetUnits01 = upd.BudgetUnits01, + report.BudgetUnits02 = upd.BudgetUnits02, + report.BudgetUnits03 = upd.BudgetUnits03, + report.BudgetUnits04 = upd.BudgetUnits04, + report.BudgetUnits05 = upd.BudgetUnits05, + report.BudgetUnits06 = upd.BudgetUnits06, + report.BudgetUnits07 = upd.BudgetUnits07, + report.BudgetUnits08 = upd.BudgetUnits08, + report.BudgetUnits09 = upd.BudgetUnits09, + report.BudgetUnits10 = upd.BudgetUnits10, + report.BudgetUnits11 = upd.BudgetUnits11, + report.BudgetUnits12 = upd.BudgetUnits12, + report.TargetDollars01 = upd.TargetDollars01, + report.TargetDollars02 = upd.TargetDollars02, + report.TargetDollars03 = upd.TargetDollars03, + report.TargetDollars04 = upd.TargetDollars04, + report.TargetDollars05 = upd.TargetDollars05, + report.TargetDollars06 = upd.TargetDollars06, + report.TargetDollars07 = upd.TargetDollars07, + report.TargetDollars08 = upd.TargetDollars08, + report.TargetDollars09 = upd.TargetDollars09, + report.TargetDollars10 = upd.TargetDollars10, + report.TargetDollars11 = upd.TargetDollars11, + report.TargetDollars12 = upd.TargetDollars12, + report.BudgetDollars01 = upd.BudgetDollars01, + report.BudgetDollars02 = upd.BudgetDollars02, + report.BudgetDollars03 = upd.BudgetDollars03, + report.BudgetDollars04 = upd.BudgetDollars04, + report.BudgetDollars05 = upd.BudgetDollars05, + report.BudgetDollars06 = upd.BudgetDollars06, + report.BudgetDollars07 = upd.BudgetDollars07, + report.BudgetDollars08 = upd.BudgetDollars08, + report.BudgetDollars09 = upd.BudgetDollars09, + report.BudgetDollars10 = upd.BudgetDollars10, + report.BudgetDollars11 = upd.BudgetDollars11, + report.BudgetDollars12 = upd.BudgetDollars12 + FROM [fp].[FactReportingAPCharges] report + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID + INNER JOIN #dataToUpdate_Budget upd ON upd.RowID = report.RowID + WHERE 1 = 1 + AND ( + report.TargetUnits01 != upd.TargetUnits01 + OR report.TargetUnits02 != upd.TargetUnits02 + OR report.TargetUnits03 != upd.TargetUnits03 + OR report.TargetUnits04 != upd.TargetUnits04 + OR report.TargetUnits05 != upd.TargetUnits05 + OR report.TargetUnits06 != upd.TargetUnits06 + OR report.TargetUnits07 != upd.TargetUnits07 + OR report.TargetUnits08 != upd.TargetUnits08 + OR report.TargetUnits09 != upd.TargetUnits09 + OR report.TargetUnits10 != upd.TargetUnits10 + OR report.TargetUnits11 != upd.TargetUnits11 + OR report.TargetUnits12 != upd.TargetUnits12 + OR report.BudgetUnits01 != upd.BudgetUnits01 + OR report.BudgetUnits02 != upd.BudgetUnits02 + OR report.BudgetUnits03 != upd.BudgetUnits03 + OR report.BudgetUnits04 != upd.BudgetUnits04 + OR report.BudgetUnits05 != upd.BudgetUnits05 + OR report.BudgetUnits06 != upd.BudgetUnits06 + OR report.BudgetUnits07 != upd.BudgetUnits07 + OR report.BudgetUnits08 != upd.BudgetUnits08 + OR report.BudgetUnits09 != upd.BudgetUnits09 + OR report.BudgetUnits10 != upd.BudgetUnits10 + OR report.BudgetUnits11 != upd.BudgetUnits11 + OR report.BudgetUnits12 != upd.BudgetUnits12 + OR report.TargetDollars01 != upd.TargetDollars01 + OR report.TargetDollars02 != upd.TargetDollars02 + OR report.TargetDollars03 != upd.TargetDollars03 + OR report.TargetDollars04 != upd.TargetDollars04 + OR report.TargetDollars05 != upd.TargetDollars05 + OR report.TargetDollars06 != upd.TargetDollars06 + OR report.TargetDollars07 != upd.TargetDollars07 + OR report.TargetDollars08 != upd.TargetDollars08 + OR report.TargetDollars09 != upd.TargetDollars09 + OR report.TargetDollars10 != upd.TargetDollars10 + OR report.TargetDollars11 != upd.TargetDollars11 + OR report.TargetDollars12 != upd.TargetDollars12 + OR report.BudgetDollars01 != upd.BudgetDollars01 + OR report.BudgetDollars02 != upd.BudgetDollars02 + OR report.BudgetDollars03 != upd.BudgetDollars03 + OR report.BudgetDollars04 != upd.BudgetDollars04 + OR report.BudgetDollars05 != upd.BudgetDollars05 + OR report.BudgetDollars06 != upd.BudgetDollars06 + OR report.BudgetDollars07 != upd.BudgetDollars07 + OR report.BudgetDollars08 != upd.BudgetDollars08 + OR report.BudgetDollars09 != upd.BudgetDollars09 + OR report.BudgetDollars10 != upd.BudgetDollars10 + OR report.BudgetDollars11 != upd.BudgetDollars11 + OR report.BudgetDollars12 != upd.BudgetDollars12 + ) + + + UPDATE report + SET + report.ProjectedUnits01 = upd.ProjectionUnits01, + report.ProjectedUnits02 = upd.ProjectionUnits02, + report.ProjectedUnits03 = upd.ProjectionUnits03, + report.ProjectedUnits04 = upd.ProjectionUnits04, + report.ProjectedUnits05 = upd.ProjectionUnits05, + report.ProjectedUnits06 = upd.ProjectionUnits06, + report.ProjectedUnits07 = upd.ProjectionUnits07, + report.ProjectedUnits08 = upd.ProjectionUnits08, + report.ProjectedUnits09 = upd.ProjectionUnits09, + report.ProjectedUnits10 = upd.ProjectionUnits10, + report.ProjectedUnits11 = upd.ProjectionUnits11, + report.ProjectedUnits12 = upd.ProjectionUnits12, + report.ProjectedDollars01 = upd.ProjectionDollars01, + report.ProjectedDollars02 = upd.ProjectionDollars02, + report.ProjectedDollars03 = upd.ProjectionDollars03, + report.ProjectedDollars04 = upd.ProjectionDollars04, + report.ProjectedDollars05 = upd.ProjectionDollars05, + report.ProjectedDollars06 = upd.ProjectionDollars06, + report.ProjectedDollars07 = upd.ProjectionDollars07, + report.ProjectedDollars08 = upd.ProjectionDollars08, + report.ProjectedDollars09 = upd.ProjectionDollars09, + report.ProjectedDollars10 = upd.ProjectionDollars10, + report.ProjectedDollars11 = upd.ProjectionDollars11, + report.ProjectedDollars12 = upd.ProjectionDollars12 + FROM [fp].[FactReportingAPCharges] report + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID + INNER JOIN #dataToUpdate_Projection upd ON upd.RowID = report.RowID + WHERE 1 = 1 + AND ( + report.ProjectedUnits01 != upd.ProjectionUnits01 + OR report.ProjectedUnits02 != upd.ProjectionUnits02 + OR report.ProjectedUnits03 != upd.ProjectionUnits03 + OR report.ProjectedUnits04 != upd.ProjectionUnits04 + OR report.ProjectedUnits05 != upd.ProjectionUnits05 + OR report.ProjectedUnits06 != upd.ProjectionUnits06 + OR report.ProjectedUnits07 != upd.ProjectionUnits07 + OR report.ProjectedUnits08 != upd.ProjectionUnits08 + OR report.ProjectedUnits09 != upd.ProjectionUnits09 + OR report.ProjectedUnits10 != upd.ProjectionUnits10 + OR report.ProjectedUnits11 != upd.ProjectionUnits11 + OR report.ProjectedUnits12 != upd.ProjectionUnits12 + OR report.ProjectedDollars01 != upd.ProjectionDollars01 + OR report.ProjectedDollars02 != upd.ProjectionDollars02 + OR report.ProjectedDollars03 != upd.ProjectionDollars03 + OR report.ProjectedDollars04 != upd.ProjectionDollars04 + OR report.ProjectedDollars05 != upd.ProjectionDollars05 + OR report.ProjectedDollars06 != upd.ProjectionDollars06 + OR report.ProjectedDollars07 != upd.ProjectionDollars07 + OR report.ProjectedDollars08 != upd.ProjectionDollars08 + OR report.ProjectedDollars09 != upd.ProjectionDollars09 + OR report.ProjectedDollars10 != upd.ProjectionDollars10 + OR report.ProjectedDollars11 != upd.ProjectionDollars11 + OR report.ProjectedDollars12 != upd.ProjectionDollars12 + ) +END +GO + + +--------------------------------------------- + +-- fp.procFactEncounterBaselineAndHistoryToReportingTransfer +CREATE PROCEDURE [fp].[procFactEncounterBaselineAndHistoryToReportingTransfer] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +WITH RECOMPILE +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-12-09 BW JAZZ-29137 Initial Creation + ** 2 2022-06-29 BW JAZZ-39340 Switching from MSDRGID to MSDRGRollupID + ** 3 2022-07-18 MY JAZZ-37944 Add Initial Baseline + ** 4 11-28-2022 MY JAZZ-43418 Add FiscalTimeID to Update + *************************************************************/ + + -- IMPORTANT NOTE: This proc is only used to transfer data from AP to fp.FactReportingAPEncounters. + -- This new proc and table are only used in the new advanced analytics solution that leverages + -- snowflake. This proc will transfer data to fp.FactReportingAPEncounters, where SQL will then replicate + -- to Snowflake. + -- + -- It's also important to note that this functionality is currently only availible on demand and is not automatically synced. + -- This is also why the current procs aren't targeted. Once we hook this up to the engine, we can properly target the proc. + -- + -- More information can be found here: https://confluence.sdt.local/display/DD/Advanced+Analytics + + SET NOCOUNT ON; + + EXEC [dbo].[procSysDropTempTable] '#SRC' + EXEC [dbo].[procSysDropTempTable] '#encounterSource' + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM [fp].[BudgetConfig] WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + + DECLARE @FiscalYearID INT = (SELECT FiscalYearID FROM [fp].[BudgetConfig] WHERE BudgetConfigID = @BudgetConfigID); + + CREATE TABLE #SRC ( + EntityID INT, + DepartmentID INT, + ServiceLineID INT, + ServiceLineRollupID INT, + PatientClassID INT, + AgeCohortID INT, + MedicalSurgicalID INT, + PayorID INT, + PayorGroupID INT, + MSDRGID INT, + CPTID INT, + ProviderID INT, + PhysicianSpecialtyID INT, + FiscalMonthID TINYINT, + FiscalYearID SMALLINT, + FiscalTimeID INT, + ActualEncountersYTD DECIMAL(19, 8), + ActualEncounters DECIMAL(19, 8), + BudgetEncounters DECIMAL(19, 8), + InitialEncounters DECIMAL(19, 8) + ) + + SELECT + EntityID, + DepartmentID, + ServiceLineID, + ServiceLineRollupID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + PayorID, + PayorGroupID, + MSDRGID, + CPTID, + ProviderID, + PhysicianSpecialtyID, + TimeClassID, + VW.FiscalMonthID, + VW.FiscalYearID, + FiscalTimeID, + Value + INTO #encounterSource + FROM [fp].[viewFactEncounterHistory_Unpivoted_source] VW -- This view is SLOOOOOOOOOOW, so trying to speed this up by only using this once. + INNER JOIN fw.DimFiscalTime dft ON VW.FiscalYearID = dft.FiscalYearID + AND VW.FiscalMonthID = dft.FiscalMonthID + WHERE VW.BudgetConfigID = @BudgetConfigID + AND Value != 0 + + SELECT + EntityID, + DepartmentID, + ServiceLineID, + ServiceLineRollupID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + PayorID, + PayorGroupID, + MSDRGID, + CPTID, + ProviderID, + PhysicianSpecialtyID, + TimeClassID, + VW.FiscalMonthID, + VW.FiscalYearID, + FiscalTimeID, + OriginalValue + INTO #baselineEncounterSource + FROM [fp].[viewFactEncounter_Unpivoted_BaselineOnly] VW -- This view is SLOOOOOOOOOOW, so trying to speed this up by only using this once. + INNER JOIN fw.DimFiscalTime dft ON VW.FiscalYearID = dft.FiscalYearID + AND VW.FiscalMonthID = dft.FiscalMonthID + WHERE VW.BudgetConfigID = @BudgetConfigID + AND OriginalValue != 0 + + CREATE CLUSTERED INDEX inx_stat ON #encounterSource ( + TimeClassID, + EntityID, + DepartmentID, + ServiceLineID, + ServiceLineRollupID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + PayorID, + PayorGroupID, + MSDRGID, + CPTID, + ProviderID, + PhysicianSpecialtyID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + ) + + -- Populate the dimensionality first + INSERT INTO #SRC (EntityID, VW.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, + ProviderID, PhysicianSpecialtyID, FiscalMonthID, FiscalYearID, FiscalTimeID) + SELECT DISTINCT + EntityID, + DepartmentID, + ServiceLineID, + ServiceLineRollupID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + PayorID, + PayorGroupID, + MSDRGID, + CPTID, + ProviderID, + PhysicianSpecialtyID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + FROM #encounterSource VW + UNION ALL + SELECT DISTINCT + EntityID, + DepartmentID, + ServiceLineID, + ServiceLineRollupID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + PayorID, + PayorGroupID, + MSDRGID, + CPTID, + ProviderID, + PhysicianSpecialtyID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + FROM #baselineEncounterSource VW + + CREATE CLUSTERED INDEX inx_src ON #SRC ( + EntityID, + DepartmentID, + ServiceLineID, + ServiceLineRollupID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + PayorID, + PayorGroupID, + MSDRGID, + CPTID, + ProviderID, + PhysicianSpecialtyID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + ) + + -- Updating each column individually because we can't necessarily do it all in one update. This is because the Src table has unit type and time class on columns not rows. + -- Case statements wouldn't work in this case because we only want to update certain columns when it meets certain criteria. IE: you wouldn't want to do TargetDollars = CASE WHEN ap.TimeClassID = 2 THEN ap.Value ELSE 0 END + -- because then when it hits a row that doesn't match that, it's gonna set the target to 0. + + -- Update Initial Baseline + UPDATE src + SET + InitialEncounters = ap.OriginalValue + FROM #SRC src + INNER JOIN #baselineEncounterSource ap ON + src.EntityID = ap.EntityID + AND src.DepartmentID = ap.DepartmentID + AND src.ServiceLineID = ap.ServiceLineID + AND src.ServiceLineRollupID = ap.ServiceLineRollupID + AND src.PatientClassID = ap.PatientClassID + AND src.AgeCohortID = ap.AgeCohortID + AND src.PatientClassID = ap.PatientClassID + AND src.MedicalSurgicalID = ap.MedicalSurgicalID + AND src.PayorID = ap.PayorID + AND src.PayorGroupID = ap.PayorGroupID + AND src.MSDRGID = ap.MSDRGID + AND src.CPTID = ap.CPTID + AND src.ProviderID = ap.ProviderID + AND src.CPTID = ap.CPTID + AND src.PhysicianSpecialtyID = ap.PhysicianSpecialtyID + AND src.FiscalYearID = ap.FiscalYearID + AND src.FiscalMonthID = ap.FiscalMonthID + WHERE ap.TimeClassID = 2 + AND ap.FiscalYearID = @FiscalYearID + + -- Update ActualYTD Encounters + UPDATE src + SET + ActualEncountersYTD = ap.Value + FROM #SRC src + INNER JOIN #encounterSource ap ON + src.EntityID = ap.EntityID + AND src.DepartmentID = ap.DepartmentID + AND src.ServiceLineID = ap.ServiceLineID + AND src.ServiceLineRollupID = ap.ServiceLineRollupID + AND src.PatientClassID = ap.PatientClassID + AND src.AgeCohortID = ap.AgeCohortID + AND src.PatientClassID = ap.PatientClassID + AND src.MedicalSurgicalID = ap.MedicalSurgicalID + AND src.PayorID = ap.PayorID + AND src.PayorGroupID = ap.PayorGroupID + AND src.MSDRGID = ap.MSDRGID + AND src.CPTID = ap.CPTID + AND src.ProviderID = ap.ProviderID + AND src.CPTID = ap.CPTID + AND src.PhysicianSpecialtyID = ap.PhysicianSpecialtyID + AND src.FiscalYearID = ap.FiscalYearID + AND src.FiscalMonthID = ap.FiscalMonthID + WHERE ap.TimeClassID = 1 + AND ap.FiscalYearID = @FiscalYearID - 1 + + -- Update CurrentYearBudget Encounters + UPDATE src + SET + BudgetEncounters = ap.Value + FROM #SRC src + INNER JOIN #encounterSource ap ON + src.EntityID = ap.EntityID + AND src.DepartmentID = ap.DepartmentID + AND src.ServiceLineID = ap.ServiceLineID + AND src.ServiceLineRollupID = ap.ServiceLineRollupID + AND src.PatientClassID = ap.PatientClassID + AND src.AgeCohortID = ap.AgeCohortID + AND src.PatientClassID = ap.PatientClassID + AND src.MedicalSurgicalID = ap.MedicalSurgicalID + AND src.PayorID = ap.PayorID + AND src.PayorGroupID = ap.PayorGroupID + AND src.MSDRGID = ap.MSDRGID + AND src.CPTID = ap.CPTID + AND src.ProviderID = ap.ProviderID + AND src.CPTID = ap.CPTID + AND src.PhysicianSpecialtyID = ap.PhysicianSpecialtyID + AND src.FiscalYearID = ap.FiscalYearID + AND src.FiscalMonthID = ap.FiscalMonthID + WHERE ap.TimeClassID = 2 + AND ap.FiscalYearID = @FiscalYearID - 1 + + -- Update PriorYearActual Encounters + UPDATE src + SET + ActualEncounters = ap.Value + FROM #SRC src + INNER JOIN #encounterSource ap ON + src.EntityID = ap.EntityID + AND src.DepartmentID = ap.DepartmentID + AND src.ServiceLineID = ap.ServiceLineID + AND src.ServiceLineRollupID = ap.ServiceLineRollupID + AND src.PatientClassID = ap.PatientClassID + AND src.AgeCohortID = ap.AgeCohortID + AND src.PatientClassID = ap.PatientClassID + AND src.MedicalSurgicalID = ap.MedicalSurgicalID + AND src.PayorID = ap.PayorID + AND src.PayorGroupID = ap.PayorGroupID + AND src.MSDRGID = ap.MSDRGID + AND src.CPTID = ap.CPTID + AND src.ProviderID = ap.ProviderID + AND src.CPTID = ap.CPTID + AND src.PhysicianSpecialtyID = ap.PhysicianSpecialtyID + AND src.FiscalYearID = ap.FiscalYearID + AND src.FiscalMonthID = ap.FiscalMonthID + WHERE ap.TimeClassID = 1 + AND ap.FiscalYearID = @FiscalYearID - 2 + + ------------------------------------------------------------------------------------------------------- + -- D-09168 : CCF: Data not flowing through into reports + -- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the + -- targeting above. This is a short term solution until we can get a more performant solution. + -- + -- NOTE: This is not a problem yet, since we don't have targeting, but I am squirreling this until + -- we add it so we don't re-introduce this bug. + -- + -- IMPORTANT NOTE: WHEN WE ADD TARGETING YOU NEED TO IMPLEMENT THIS WORKAROUND. GRAB THIS FROM THE + -- EXISTING PROCS AND UPDATE IT FOR THIS. + ------------------------------------------------------------------------------------------------------- + + IF (@IsDebug = 1) + BEGIN + SELECT '#SRC' AS TempTable, EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, + FiscalMonthID, FiscalYearID, FiscalTimeID, BudgetEncounters, ActualEncountersYTD, ActualEncounters, InitalEncounters + FROM #SRC + ORDER BY EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID,FiscalYearID DESC, FiscalMonthID; + + SELECT '#encounterSource' AS TempTable, EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, + TimeClassID, FiscalMonthID, FiscalYearID, FiscalTimeID, Value + FROM #encounterSource + ORDER BY EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID,FiscalYearID DESC, FiscalMonthID; + + SELECT '#baselineEncounterSource' AS TempTable, EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, + TimeClassID, FiscalMonthID, FiscalYearID, FiscalTimeID, OriginalValue + FROM #baselineEncounterSource + ORDER BY EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID,FiscalYearID DESC, FiscalMonthID; + + RETURN + END + + SELECT EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, + PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, FiscalMonthID, FiscalYearID, FiscalTimeID, BudgetEncounters, ActualEncountersYTD, ActualEncounters + INTO #HistorySRC + FROM #SRC + WHERE FiscalYearID < @FiscalYearID + + -- Publish the data from the temp table to fp.FactReportingAPEncounters. This uses a merge statement to handle inserts and updates + -- In the event that the active configuration changes, we need to clear out this table because we only hold data for the active configuration. This is done from the UI itself. + -- We don't do any deletes from the reporting table because we have multiple sources going into it at a given time. In the future if we + -- needed to do a delete for some reason, we would need to combine them all into one MEGA proc which is gross and nasty. Since we don't delete data, this shouldn't be an issue + + -- Publish History First + ;WITH TGT AS + ( + SELECT EntityID, FRE.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, + PayorGroupID, MSDRGRollupID, CPTID, ProviderID, PhysicianSpecialtyID, FiscalMonthID, FiscalYearID, FiscalTimeID, BudgetEncounters, ActualEncountersYTD, ActualEncounters, InitialEncounters + FROM [fp].[FactReportingAPEncounters] FRE + + ) + MERGE TGT AS target + USING #HistorySRC AS source + ON ( + target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.ServiceLineID = source.ServiceLineID + AND target.ServiceLineRollupID = source.ServiceLineRollupID + AND target.PatientClassID = source.PatientClassID + AND target.AgeCohortID = source.AgeCohortID + AND target.MedicalSurgicalID = source.MedicalSurgicalID + AND target.PayorID = source.PayorID + AND target.PayorGroupID = source.PayorGroupID + AND target.MSDRGRollupID = source.MSDRGID + AND target.CPTID = source.CPTID + AND target.ProviderID = source.ProviderID + AND target.PhysicianSpecialtyID= source.PhysicianSpecialtyID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + AND target.FiscalTimeID = source.FiscalTimeID + + ) + WHEN MATCHED AND ( + target.BudgetEncounters <> source.BudgetEncounters + OR target.ActualEncountersYTD <> source.ActualEncountersYTD + OR target.ActualEncounters <> source.ActualEncounters ) + THEN + UPDATE SET + target.BudgetEncounters = ISNULL(source.BudgetEncounters, 0), + target.ActualEncountersYTD = ISNULL(source.ActualEncountersYTD, 0), + target.ActualEncounters = ISNULL(source.ActualEncounters, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + EntityID + , DepartmentID + , ServiceLineID + , ServiceLineRollupID + , PatientClassID + , AgeCohortID + , MedicalSurgicalID + , PayorID + , PayorGroupID + , MSDRGRollupID + , CPTID + , ProviderID + , PhysicianSpecialtyID + , FiscalMonthID + , FiscalYearID + , FiscalTimeID + , BudgetEncounters + , ActualEncountersYTD + , ActualEncounters + ) + VALUES ( + source.EntityID + , source.DepartmentID + , source.ServiceLineID + , source.ServiceLineRollupID + , source.PatientClassID + , source.AgeCohortID + , source.MedicalSurgicalID + , source.PayorID + , source.PayorGroupID + , source.MSDRGID + , source.CPTID + , source.ProviderID + , source.PhysicianSpecialtyID + , source.FiscalMonthID + , source.FiscalYearID + , source.FiscalTimeID + , ISNULL(source.BudgetEncounters, 0) + , ISNULL(source.ActualEncountersYTD, 0) + , ISNULL(source.ActualEncounters, 0) + ); + + + SELECT EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, + PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, FiscalMonthID, FiscalYearID, FiscalTimeID, InitialEncounters + INTO #BaselineSRC + FROM #SRC + WHERE FiscalYearID = @FiscalYearID + + -- Publish Initials (we need to do these seperately because otherwise Baseline will wipe out Target/Budget) + ;WITH TGT AS + ( + SELECT EntityID, FRE.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, + PayorGroupID, MSDRGRollupID, CPTID, ProviderID, PhysicianSpecialtyID, FiscalMonthID, FiscalYearID, FiscalTimeID, InitialEncounters + FROM [fp].[FactReportingAPEncounters] FRE + + ) + MERGE TGT AS target + USING #BaselineSRC AS source + ON ( + target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.ServiceLineID = source.ServiceLineID + AND target.ServiceLineRollupID = source.ServiceLineRollupID + AND target.PatientClassID = source.PatientClassID + AND target.AgeCohortID = source.AgeCohortID + AND target.MedicalSurgicalID = source.MedicalSurgicalID + AND target.PayorID = source.PayorID + AND target.PayorGroupID = source.PayorGroupID + AND target.MSDRGRollupID = source.MSDRGID + AND target.CPTID = source.CPTID + AND target.ProviderID = source.ProviderID + AND target.PhysicianSpecialtyID= source.PhysicianSpecialtyID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + AND target.FiscalTimeID = source.FiscalTimeID + + ) + WHEN MATCHED AND ( + target.InitialEncounters <> source.InitialEncounters) + THEN + UPDATE SET + target.InitialEncounters = ISNULL(source.InitialEncounters, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + EntityID + , DepartmentID + , ServiceLineID + , ServiceLineRollupID + , PatientClassID + , AgeCohortID + , MedicalSurgicalID + , PayorID + , PayorGroupID + , MSDRGRollupID + , CPTID + , ProviderID + , PhysicianSpecialtyID + , FiscalMonthID + , FiscalYearID + , FiscalTimeID + , InitialEncounters + ) + VALUES ( + source.EntityID + , source.DepartmentID + , source.ServiceLineID + , source.ServiceLineRollupID + , source.PatientClassID + , source.AgeCohortID + , source.MedicalSurgicalID + , source.PayorID + , source.PayorGroupID + , source.MSDRGID + , source.CPTID + , source.ProviderID + , source.PhysicianSpecialtyID + , source.FiscalMonthID + , source.FiscalYearID + , source.FiscalTimeID + , ISNULL(source.InitialEncounters, 0) + ); +END +GO + + +--------------------------------------------- + +-- fp.procFactEncounterToReportingTransfer +CREATE PROCEDURE fp.procFactEncounterToReportingTransfer + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +WITH RECOMPILE +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-12-07 BW JAZZ-29137 Initial Creation + ** 2 2022-06-15 MY JAZZ-38632 Add Targeting + ** 3 2022-06-29 BW JAZZ-39340 Switching from MSDRGID to MSDRGRollupID + ** 4 11-28-2022 MY JAZZ-43418 Add FiscalTimeID to Update + ** 5 2022-12-19 MD JAZZ-47250 Include encounter data that doesn't have corresponding charge data + ** 6 2023-02-23 MY JAZZ-49629 Handing zeroing out for AA data marts + ** 7 2023-02-28 BW JAZZ-49992 Updated for new data model, use [fp].[ServiceLineEncounter] + *************************************************************/ + + -- IMPORTANT NOTE: This proc is only used to transfer data from AP to fp.FactReportingAPEncounters. + -- This new proc and table are only used in the new advanced analytics solution that leverages + -- snowflake. This proc will transfer data to fp.FactReportingAPEncounters, where SQL will then replicate + -- to Snowflake. + -- + -- More information can be found here: https://confluence.sdt.local/display/DD/Advanced+Analytics + + SET NOCOUNT ON; + + EXEC [dbo].[procSysDropTempTable] '#SRC' + EXEC [dbo].[procSysDropTempTable] '#encounterSource' + EXEC [dbo].[procSysDropTempTable] '#ChargeVolumeDepartments' + EXEC [dbo].[procSysDropTempTable] '#allServiceLineDimensionality' + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM [fp].[BudgetConfig] WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + + CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT); + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #encounterTargeting (EntityID INT, ServiceLineID INT); + + CREATE TABLE #allServiceLineDimensionality (SLEEntityID INT, SLEServiceLineID INT, MapEntityID INT, MapServiceLineID INT) + INSERT INTO #allServiceLineDimensionality (SLEEntityID, SLEServiceLineID, MapEntityID, MapServiceLineID) + SELECT DISTINCT sle.EntityID as SLEEntity, sle.ServiceLineID as SLEServiceLine, + map.EntityID as MapEntity, map.ServiceLineID as MapServiceLine + FROM fp.ServiceLineEncounter sle + left join fp.ServiceLineEncounterChargeVolumeMapping map + on sle.EntityID = map.EntityID + and sle.ServiceLineID = map.ServiceLineID + and sle.BudgetConfigID = map.BudgetConfigID + WHERE sle.BudgetConfigID = @BudgetConfigID + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #encounterTargeting (EntityID, ServiceLineID) + SELECT DISTINCT map.EntityID, map.ServiceLineID + FROM fp.ServiceLineEncounterChargeVolumeMapping map WITH (READUNCOMMITTED) + INNER JOIN #ChargeVolumeDepartments targeting ON map.DepartmentID = targeting.DepartmentID + WHERE map.BudgetConfigID = @BudgetConfigID + END ELSE + BEGIN + INSERT INTO #encounterTargeting (EntityID, ServiceLineID) + SELECT DISTINCT map.EntityID, map.ServiceLineID + FROM fp.ServiceLineEncounterChargeVolumeMapping map WITH (READUNCOMMITTED) + WHERE map.BudgetConfigID = @BudgetConfigID + -- JAZZ-47250 - Adding this union to account for SL data that doesn't have reflecting charge data + UNION + SELECT SLEEntityID, SLEServiceLineID + FROM #allServiceLineDimensionality + WHERE MapEntityID IS NULL + END + + CREATE TABLE #SRC ( + EntityID INT, + DepartmentID INT, + ServiceLineID INT, + ServiceLineRollupID INT, + PatientClassID INT, + AgeCohortID INT, + MedicalSurgicalID INT, + PayorID INT, + PayorGroupID INT, + MSDRGID INT, + CPTID INT, + ProviderID INT, + PhysicianSpecialtyID INT, + FiscalMonthID TINYINT, + FiscalYearID SMALLINT, + FiscalTimeID INT, + BudgetEncounters DECIMAL(19, 8), + ProjectedEncounters DECIMAL(19, 8), + TargetEncounters DECIMAL(19, 8) + ) + + SELECT + VW.EntityID, + DepartmentID, + VW.ServiceLineID, + ServiceLineRollupID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + PayorID, + PayorGroupID, + MSDRGID, + CPTID, + ProviderID, + PhysicianSpecialtyID, + TimeClassID, + VW.FiscalMonthID, + VW.FiscalYearID, + FiscalTimeID, + OriginalValue, + Value, + ManagerValue + INTO #encounterSource + FROM [fp].[viewFactEncounter_Unpivoted_source] VW -- This view is SLOOOOOOOOOOW, so trying to speed this up by only using this once. + INNER JOIN #encounterTargeting tgt ON VW.EntityID = tgt.EntityID AND VW.ServiceLineID = tgt.ServiceLineID + INNER JOIN fw.DimFiscalTime dft ON VW.FiscalYearID = dft.FiscalYearID + AND VW.FiscalMonthID = dft.FiscalMonthID + WHERE VW.BudgetConfigID = @BudgetConfigID + AND (Value != 0 OR ManagerValue != 0) + + CREATE CLUSTERED INDEX inx_stat ON #encounterSource ( + TimeClassID, + EntityID, + DepartmentID, + ServiceLineID, + ServiceLineRollupID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + PayorID, + PayorGroupID, + MSDRGID, + CPTID, + ProviderID, + PhysicianSpecialtyID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + ) + + -- Populate the dimensionality first + INSERT INTO #SRC (EntityID, VW.DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, FiscalMonthID, FiscalYearID, + FiscalTimeID) + SELECT DISTINCT + EntityID, + DepartmentID, + ServiceLineID, + ServiceLineRollupID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + PayorID, + PayorGroupID, + MSDRGID, + CPTID, + ProviderID, + PhysicianSpecialtyID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + FROM #encounterSource VW + + CREATE CLUSTERED INDEX inx_src ON #SRC ( + EntityID, + DepartmentID, + ServiceLineID, + ServiceLineRollupID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + PayorID, + PayorGroupID, + MSDRGID, + CPTID, + ProviderID, + PhysicianSpecialtyID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + ) + + -- Updating each column individually because we can't necessarily do it all in one update. This is because the Src table has unit type and time class on columns not rows. + -- Case statements wouldn't work in this case because we only want to update certain columns when it meets certain criteria. IE: you wouldn't want to do TargetDollars = CASE WHEN ap.TimeClassID = 2 THEN ap.Value ELSE 0 END + -- because then when it hits a row that doesn't match that, it's gonna set the target to 0. + + -- Update Budget/Target Encounters + UPDATE src + SET + BudgetEncounters = ap.ManagerValue, + TargetEncounters = ap.Value + FROM #SRC src + INNER JOIN #encounterSource ap ON + src.EntityID = ap.EntityID + AND src.DepartmentID = ap.DepartmentID + AND src.ServiceLineID = ap.ServiceLineID + AND src.ServiceLineRollupID = ap.ServiceLineRollupID + AND src.PatientClassID = ap.PatientClassID + AND src.AgeCohortID = ap.AgeCohortID + AND src.PatientClassID = ap.PatientClassID + AND src.MedicalSurgicalID = ap.MedicalSurgicalID + AND src.PayorID = ap.PayorID + AND src.PayorGroupID = ap.PayorGroupID + AND src.MSDRGID = ap.MSDRGID + AND src.CPTID = ap.CPTID + AND src.ProviderID = ap.ProviderID + AND src.CPTID = ap.CPTID + AND src.PhysicianSpecialtyID = ap.PhysicianSpecialtyID + AND src.FiscalYearID = ap.FiscalYearID + AND src.FiscalMonthID = ap.FiscalMonthID + WHERE ap.TimeClassID = 2 + + -- Update Projected Encounters + UPDATE src + SET + ProjectedEncounters = ap.Value + FROM #SRC src + INNER JOIN #encounterSource ap ON + src.EntityID = ap.EntityID + AND src.DepartmentID = ap.DepartmentID + AND src.ServiceLineID = ap.ServiceLineID + AND src.ServiceLineRollupID = ap.ServiceLineRollupID + AND src.PatientClassID = ap.PatientClassID + AND src.AgeCohortID = ap.AgeCohortID + AND src.PatientClassID = ap.PatientClassID + AND src.MedicalSurgicalID = ap.MedicalSurgicalID + AND src.PayorID = ap.PayorID + AND src.PayorGroupID = ap.PayorGroupID + AND src.MSDRGID = ap.MSDRGID + AND src.CPTID = ap.CPTID + AND src.ProviderID = ap.ProviderID + AND src.CPTID = ap.CPTID + AND src.PhysicianSpecialtyID = ap.PhysicianSpecialtyID + AND src.FiscalYearID = ap.FiscalYearID + AND src.FiscalMonthID = ap.FiscalMonthID + WHERE ap.TimeClassID = 12 + + IF (@IsDebug = 1) + BEGIN + SELECT '#SRC' AS TempTable, EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, FiscalMonthID, FiscalYearID, + FiscalTimeID, BudgetEncounters, ProjectedEncounters, TargetEncounters + FROM #SRC + ORDER BY EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, FiscalYearID DESC, + FiscalTimeID, FiscalMonthID; + + SELECT '#encounterSource' AS TempTable, EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID, TimeClassID, FiscalMonthID, FiscalYearID, + FiscalTimeID, OriginalValue, Value, ManagerValue + FROM #encounterSource + ORDER BY EntityID, DepartmentID, ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, CPTID, ProviderID, PhysicianSpecialtyID,FiscalYearID DESC, + FiscalTimeID, FiscalMonthID; + + RETURN + END + + -- Publish the data from the temp table to fp.FactReportingAPEncounters. This uses a merge statement to handle inserts and updates + -- In the event that the active configuration changes, we need to clear out this table because we only hold data for the active configuration. This is done from the UI itself. + -- We don't do any deletes from the reporting table because we have multiple sources going into it at a given time. In the future if we + -- needed to do a delete for some reason, we would need to combine them all into one MEGA proc which is gross and nasty. Since we don't delete data, this shouldn't be an issue + ;WITH TGT AS + ( + SELECT FRE.EntityID, FRE.DepartmentID, FRE.ServiceLineID, ServiceLineRollupID, PatientClassID, AgeCohortID, MedicalSurgicalID, PayorID, + PayorGroupID, MSDRGRollupID, CPTID, ProviderID, PhysicianSpecialtyID, FiscalMonthID, FiscalYearID, + FiscalTimeID, BudgetEncounters, ProjectedEncounters, TargetEncounters + FROM [fp].[FactReportingAPEncounters] FRE + INNER JOIN #encounterTargeting tgt ON FRE.EntityID = tgt.EntityID AND FRE.ServiceLineID = tgt.ServiceLineID + + ) + MERGE TGT AS target + USING #SRC AS source + ON ( + target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.ServiceLineID = source.ServiceLineID + AND target.ServiceLineRollupID = source.ServiceLineRollupID + AND target.PatientClassID = source.PatientClassID + AND target.AgeCohortID = source.AgeCohortID + AND target.MedicalSurgicalID = source.MedicalSurgicalID + AND target.PayorID = source.PayorID + AND target.PayorGroupID = source.PayorGroupID + AND target.MSDRGRollupID = source.MSDRGID + AND target.CPTID = source.CPTID + AND target.ProviderID = source.ProviderID + AND target.PhysicianSpecialtyID= source.PhysicianSpecialtyID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + AND target.FiscalTimeID = source.FiscalTimeID + + ) + WHEN MATCHED AND ( + target.BudgetEncounters <> source.BudgetEncounters + OR target.ProjectedEncounters <> source.ProjectedEncounters + OR target.TargetEncounters <> source.TargetEncounters) + THEN + UPDATE SET + target.BudgetEncounters = ISNULL(source.BudgetEncounters, 0), + target.ProjectedEncounters = ISNULL(source.ProjectedEncounters, 0), + target.TargetEncounters = ISNULL(source.TargetEncounters, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + EntityID + , DepartmentID + , ServiceLineID + , ServiceLineRollupID + , PatientClassID + , AgeCohortID + , MedicalSurgicalID + , PayorID + , PayorGroupID + , MSDRGRollupID + , CPTID + , ProviderID + , PhysicianSpecialtyID + , FiscalMonthID + , FiscalYearID + , FiscalTimeID + , BudgetEncounters + , ProjectedEncounters + , TargetEncounters + ) + VALUES ( + source.EntityID + , source.DepartmentID + , source.ServiceLineID + , source.ServiceLineRollupID + , source.PatientClassID + , source.AgeCohortID + , source.MedicalSurgicalID + , source.PayorID + , source.PayorGroupID + , source.MSDRGID + , source.CPTID + , source.ProviderID + , source.PhysicianSpecialtyID + , source.FiscalMonthID + , source.FiscalYearID + , source.FiscalTimeID + , ISNULL(source.BudgetEncounters, 0) + , ISNULL(source.ProjectedEncounters, 0) + , ISNULL(source.TargetEncounters, 0) + ); + + ------------------------------------------------------------------------------------------------------- + -- JAZZ-49629 : Handing zeroing out for AA data marts + -- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the + -- targeting above. + ------------------------------------------------------------------------------------------------------- + + -- Get all records that were adjusted + SELECT DISTINCT chg.ServiceLineEncounterID + INTO #adjustedRecords + FROM [fp].[ServiceLineEncounterChangeHistory] chg + INNER JOIN [fp].[ServiceLineEncounter] fgl ON chg.ServiceLineEncounterID = fgl.ServiceLineEncounterID + INNER JOIN #encounterTargeting tgt ON fgl.EntityID = tgt.EntityID AND fgl.ServiceLineID = tgt.ServiceLineID + WHERE chg.BudgetConfigID = @BudgetConfigID + + SELECT + VW.EntityID, + DepartmentID, + VW.ServiceLineID, + ServiceLineRollupID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + PayorID, + PayorGroupID, + MSDRGID, + CPTID, + ProviderID, + PhysicianSpecialtyID, + TimeClassID, + VW.FiscalMonthID, + VW.FiscalYearID, + Value, + ManagerValue + INTO #tempUnpivoted + FROM [fp].[viewFactEncounter_Unpivoted_source] VW -- This view is SLOOOOOOOOOOW, so trying to speed this up by only using this once. + INNER JOIN #encounterTargeting tgt ON VW.EntityID = tgt.EntityID AND VW.ServiceLineID = tgt.ServiceLineID + INNER JOIN #adjustedRecords adj ON VW.ServiceLineEncounterID = adj.ServiceLineEncounterID + INNER JOIN fp.BudgetConfig bc ON VW.BudgetConfigID = bc.BudgetConfigID + WHERE VW.BudgetConfigID = @BudgetConfigID + AND ( + (VW.FiscalYearID = bc.FiscalYearID AND VW.TimeClassID = 2) + OR (VW.FiscalYearID = bc.FiscalYearID - 1 AND VW.TimeClassID = 12) + ) + AND ( + (VW.TimeClassID = 2 AND (Value = 0 OR ManagerValue = 0)) + OR (VW.TimeClassID = 12 AND Value = 0) + ) + + -- Find the records that need to be updated by comparing the source to the reporting table + SELECT + frgl.RowID, + cv.Value, + cv.ManagerValue + INTO #dataToUpdate_Budgeted + FROM [fp].[FactReportingAPEncounters] frgl + INNER JOIN #encounterTargeting tgt ON frgl.EntityID = tgt.EntityID AND frgl.ServiceLineID = tgt.ServiceLineID + INNER JOIN #tempUnpivoted cv ON + cv.EntityID = frgl.EntityID + AND cv.PatientClassID = frgl.PatientClassID + AND cv.ServiceLineID = frgl.ServiceLineID + AND cv.ServiceLineRollupID = frgl.ServiceLineRollupID + AND cv.AgeCohortID = frgl.AgeCohortID + AND cv.MedicalSurgicalID = frgl.MedicalSurgicalID + AND cv.DepartmentID = frgl.DepartmentID + AND cv.PayorID = frgl.PayorID + AND cv.PayorGroupID = frgl.PayorGroupID + AND cv.CPTID = frgl.CPTID + AND cv.ProviderID = frgl.ProviderID + AND cv.PhysicianSpecialtyID = frgl.PhysicianSpecialtyID + AND cv.FiscalYearID = frgl.FiscalYearID + AND cv.FiscalMonthID = frgl.FiscalMonthID + WHERE 1 = 1 + AND cv.TimeClassID = 2 + AND ( + cv.ManagerValue != frgl.BudgetEncounters + OR cv.Value != frgl.TargetEncounters + ) + + SELECT + frgl.RowID, + cv.Value + INTO #dataToUpdate_Projected + FROM [fp].[FactReportingAPEncounters] frgl + INNER JOIN #encounterTargeting tgt ON frgl.EntityID = tgt.EntityID AND frgl.ServiceLineID = tgt.ServiceLineID + INNER JOIN #tempUnpivoted cv ON + cv.EntityID = frgl.EntityID + AND cv.PatientClassID = frgl.PatientClassID + AND cv.ServiceLineID = frgl.ServiceLineID + AND cv.ServiceLineRollupID = frgl.ServiceLineRollupID + AND cv.AgeCohortID = frgl.AgeCohortID + AND cv.MedicalSurgicalID = frgl.MedicalSurgicalID + AND cv.DepartmentID = frgl.DepartmentID + AND cv.PayorID = frgl.PayorID + AND cv.PayorGroupID = frgl.PayorGroupID + AND cv.CPTID = frgl.CPTID + AND cv.ProviderID = frgl.ProviderID + AND cv.PhysicianSpecialtyID = frgl.PhysicianSpecialtyID + AND cv.FiscalYearID = frgl.FiscalYearID + AND cv.FiscalMonthID = frgl.FiscalMonthID + WHERE 1 = 1 + AND cv.TimeClassID = 12 + AND cv.Value != frgl.ProjectedEncounters + + -- Update the records + UPDATE report + SET + report.BudgetEncounters = upd.ManagerValue, + report.TargetEncounters = upd.Value + FROM [fp].[FactReportingAPEncounters] report + INNER JOIN #encounterTargeting tgt ON report.EntityID = tgt.EntityID AND report.ServiceLineID = tgt.ServiceLineID + INNER JOIN #dataToUpdate_Budgeted upd ON upd.RowID = report.RowID + WHERE 1 = 1 + AND ( + report.TargetEncounters != upd.Value + OR report.BudgetEncounters != upd.ManagerValue + ) + + UPDATE report + SET + report.ProjectedEncounters = upd.Value + FROM [fp].[FactReportingAPEncounters] report + INNER JOIN #encounterTargeting tgt ON report.EntityID = tgt.EntityID AND report.ServiceLineID = tgt.ServiceLineID + INNER JOIN #dataToUpdate_Projected upd ON upd.RowID = report.RowID + WHERE 1 = 1 + AND report.ProjectedEncounters != upd.Value +END +GO + + +--------------------------------------------- + +-- fp.procFactGeneralLedgerBaselineAndHistoryToReportingTransfer +CREATE PROCEDURE [fp].[procFactGeneralLedgerBaselineAndHistoryToReportingTransfer] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +WITH RECOMPILE +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2020-07-24 MY JAZZ-2849 Initial Creation + ** 2 2022-06-15 MY JAZZ-38632 Add Targeting + ** 3 2022-07-18 MY JAZZ-37944 Add Initial Baseline + ** 4 11-28-2022 MY JAZZ-43418 Add FiscalTimeID to Update + *************************************************************/ + + -- IMPORTANT NOTE: This proc is only used to transfer data from AP to fp.FactReportingAP. + -- This new proc and table are only used in the new advanced analytics solution that leverages + -- snowflake. This proc will transfer data to fp.FactReportingAP, where SQL will then replicate + -- to Snowflake. + -- + -- It's also important to note that this functionality is currently only availible on demand and is not automatically synced. + -- This is also why the current procs aren't targeted. Once we hook this up to the engine, we can properly target the proc. + -- + -- More information can be found here: https://confluence.sdt.local/display/DD/Advanced+Analytics + + SET NOCOUNT ON; + + EXEC [dbo].[procSysDropTempTable] '#SRC' + EXEC [dbo].[procSysDropTempTable] '#generalLedgerSource' + EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment' + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM [fp].[BudgetConfig] WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[GeneralLedger] d WITH (READUNCOMMITTED) + WHERE BudgetConfigID = @BudgetConfigID + END + + CREATE TABLE #SRC ( + BudgetConfigID INT, + EntityID INT, + DepartmentID INT, + AccountID INT, + FinancialReportingID INT, + VariabilityID INT, + FiscalMonthID TINYINT, + FiscalYearID SMALLINT, + FiscalTimeID INT, + InitialDollars DECIMAL(19, 8) DEFAULT(0) + ) + + SELECT + gl.GeneralLedgerID, + gl.BudgetConfigID, + gl.EntityGroupConfigID, + gl.EntityID, + gl.DepartmentID, + gl.AccountID, + gl.FinancialReportingID, + gl.APEModelSectionID, + gl.VariabilityID, + 34 AS UnitTypeID, + bc.FiscalYearID, + m.FiscalMonthID, + gl.TargetLockType, + gl.BudgetLockType, + gl.ProjectionLockType, + InitialBudget + INTO #glPivoted + FROM fp.GeneralLedger gl + INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = gl.DepartmentID + CROSS APPLY ( + VALUES + (01, InitialBudget01), + (02, InitialBudget02), + (03, InitialBudget03), + (04, InitialBudget04), + (05, InitialBudget05), + (06, InitialBudget06), + (07, InitialBudget07), + (08, InitialBudget08), + (09, InitialBudget09), + (10, InitialBudget10), + (11, InitialBudget11), + (12, InitialBudget12) + ) AS CrossApplied (MonthSortOrder, InitialBudget) + LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder + WHERE gl.BudgetConfigID = @BudgetConfigID + + SELECT + EntityID, + VW.DepartmentID, + AccountID, + FinancialReportingID, + VariabilityID, + UnitTypeID, + 2 AS TimeClassID, + vw.FiscalMonthID, + vw.FiscalYearID, + FiscalTimeID, + InitialBudget AS OriginalValue + INTO #generalLedgerSource + FROM #glPivoted vw + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = VW.DepartmentID + INNER JOIN fw.DimFiscalTime dft ON VW.FiscalYearID = dft.FiscalYearID + AND VW.FiscalMonthID = dft.FiscalMonthID + WHERE VW.BudgetConfigID = @BudgetConfigID + AND (InitialBudget != 0) + + CREATE CLUSTERED INDEX inx_stat ON #generalLedgerSource ( + TimeClassID, + EntityID, + DepartmentID, + AccountID, + FinancialReportingID, + VariabilityID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + ) + + -- Populate the dimensionality first + INSERT INTO #SRC (EntityID, VW.DepartmentID, AccountID, FinancialReportingID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID) + SELECT DISTINCT + EntityID, + VW.DepartmentID, + AccountID, + FinancialReportingID, + VariabilityID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + FROM #generalLedgerSource VW + + CREATE CLUSTERED INDEX inx_src ON #SRC ( + EntityID, + DepartmentID, + AccountID, + FinancialReportingID, + VariabilityID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + ) + + -- Updating each column individually because we can't necessarily do it all in one update. This is because the Src table has unit type and time class on columns not rows. + -- Case statements wouldn't work in this case because we only want to update certain columns when it meets certain criteria. IE: you wouldn't want to do TargetDollars = CASE WHEN ap.TimeClassID = 2 THEN ap.Value ELSE 0 END + -- because then when it hits a row that doesn't match that, it's gonna set the target to 0. + + -- Update Budget/Target Dollars + UPDATE src + SET + InitialDollars = ap.OriginalValue + FROM #SRC src + INNER JOIN #generalLedgerSource ap ON + src.EntityID = ap.EntityID + AND src.DepartmentID = ap.DepartmentID + AND src.AccountID = ap.AccountID + AND src.FinancialReportingID = ap.FinancialReportingID + AND src.VariabilityID = ap.VariabilityID + AND src.FiscalYearID = ap.FiscalYearID + AND src.FiscalMonthID = ap.FiscalMonthID + WHERE ap.TimeClassID = 2 + + ------------------------------------------------------------------------------------------------------- + -- D-09168 : CCF: Data not flowing through into reports + -- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the + -- targeting above. This is a short term solution until we can get a more performant solution. + -- + -- NOTE: This is not a problem yet, since we don't have targeting, but I am squirreling this until + -- we add it so we don't re-introduce this bug. + -- + -- IMPORTANT NOTE: WHEN WE ADD TARGETING YOU NEED TO IMPLEMENT THIS WORKAROUND. GRAB THIS FROM THE + -- EXISTING PROCS AND UPDATE IT FOR THIS. + ------------------------------------------------------------------------------------------------------- + + IF (@IsDebug = 1) + BEGIN + SELECT '#SRC' AS TempTable, EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID, InitialDollars + FROM #SRC; + + SELECT '#generalLedgerSource' AS TempTable, EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, FiscalTimeID, OriginalValue + FROM #generalLedgerSource + + RETURN + END + + -- Publish the data from the temp table to fp.FactReportingAP. This uses a merge statement to handle inserts and updates + -- In the event that the active configuration changes, we need to clear out this table because we only hold data for the active configuration. This is done from the UI itself. + -- We don't do any deletes from the reporting table because we have multiple sources going into it at a given time. In the future if we + -- needed to do a delete for some reason, we would need to combine them all into one MEGA proc which is gross and nasty. Since we don't delete data, this shouldn't be an issue + ;WITH TGT AS + ( + SELECT EntityID, FRS.DepartmentID, AccountID, FinancialReportingID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID, InitialDollars + FROM [fp].[FactReportingAP] FRS + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = FRS.DepartmentID + ) + MERGE TGT AS target + USING #SRC AS source + ON ( + target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.AccountID = source.AccountID + AND target.FinancialReportingID = source.FinancialReportingID + AND target.VariabilityID = source.VariabilityID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + AND target.FiscalTimeID = source.FiscalTimeID + ) + WHEN MATCHED AND + ( + target.InitialDollars <> source.InitialDollars + ) + THEN + UPDATE SET + target.InitialDollars = ISNULL(source.InitialDollars, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + EntityID, + DepartmentID, + AccountID, + FinancialReportingID, + VariabilityID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID, + InitialDollars + ) + VALUES ( + source.EntityID, + source.DepartmentID, + source.AccountID, + source.FinancialReportingID, + source.VariabilityID, + source.FiscalMonthID, + source.FiscalYearID, + source.FiscalTimeID, + ISNULL(source.InitialDollars, 0) + ); + +END +GO + + +--------------------------------------------- + +-- fp.procFactGeneralLedgerToReportingTransfer +CREATE PROCEDURE [fp].[procFactGeneralLedgerToReportingTransfer] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +WITH RECOMPILE +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2020-07-24 MY JAZZ-2849 Initial Creation + ** 2 2022-06-15 MY JAZZ-38632 Add Targeting + ** 3 11-28-2022 MY JAZZ-43418 Add FiscalTimeID to Update + ** 4 01-26-2023 MD JAZZ-49070 Update projection to use ManagerValue + ** 5 2023-02-23 MY JAZZ-49629 Handing zeroing out for AA data marts + ** 6 2023-08-17 MY JAZZ-58757 Handing zeroing out for AA data marts + *************************************************************/ + + -- IMPORTANT NOTE: This proc is only used to transfer data from AP to fp.FactReportingAP. + -- This new proc and table are only used in the new advanced analytics solution that leverages + -- snowflake. This proc will transfer data to fp.FactReportingAP, where SQL will then replicate + -- to Snowflake. + -- + -- More information can be found here: https://confluence.sdt.local/display/DD/Advanced+Analytics + + SET NOCOUNT ON; + + EXEC [dbo].[procSysDropTempTable] '#SRC' + EXEC [dbo].[procSysDropTempTable] '#generalLedgerSource' + EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment' + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM [fp].[BudgetConfig] WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[GeneralLedger] d WITH (READUNCOMMITTED) + WHERE BudgetConfigID = @BudgetConfigID + END + + CREATE TABLE #SRC ( + BudgetConfigID INT, + EntityID INT, + DepartmentID INT, + AccountID INT, + FinancialReportingID INT, + VariabilityID INT, + FiscalMonthID TINYINT, + FiscalYearID SMALLINT, + FiscalTimeID INT, + BudgetDollars DECIMAL(19, 8) DEFAULT(0), + ProjectedDollars DECIMAL(19, 8) DEFAULT(0), + TargetDollars DECIMAL(19, 8) DEFAULT(0) + ) + + SELECT + gl.GeneralLedgerID, + gl.BudgetConfigID, + gl.EntityGroupConfigID, + gl.EntityID, + gl.DepartmentID, + gl.AccountID, + gl.FinancialReportingID, + gl.APEModelSectionID, + gl.VariabilityID, + 34 AS UnitTypeID, + bc.FiscalYearID, + m.FiscalMonthID, + gl.TargetLockType, + gl.BudgetLockType, + gl.ProjectionLockType, + InitialBudget, + Target, + Budget, + Projection + INTO #glPivoted + FROM fp.GeneralLedger gl + INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = gl.DepartmentID + CROSS APPLY ( + VALUES + (01, InitialBudget01, TargetAdjusted01, BudgetAdjusted01, ProjectionAdjusted01), + (02, InitialBudget02, TargetAdjusted02, BudgetAdjusted02, ProjectionAdjusted02), + (03, InitialBudget03, TargetAdjusted03, BudgetAdjusted03, ProjectionAdjusted03), + (04, InitialBudget04, TargetAdjusted04, BudgetAdjusted04, ProjectionAdjusted04), + (05, InitialBudget05, TargetAdjusted05, BudgetAdjusted05, ProjectionAdjusted05), + (06, InitialBudget06, TargetAdjusted06, BudgetAdjusted06, ProjectionAdjusted06), + (07, InitialBudget07, TargetAdjusted07, BudgetAdjusted07, ProjectionAdjusted07), + (08, InitialBudget08, TargetAdjusted08, BudgetAdjusted08, ProjectionAdjusted08), + (09, InitialBudget09, TargetAdjusted09, BudgetAdjusted09, ProjectionAdjusted09), + (10, InitialBudget10, TargetAdjusted10, BudgetAdjusted10, ProjectionAdjusted10), + (11, InitialBudget11, TargetAdjusted11, BudgetAdjusted11, ProjectionAdjusted11), + (12, InitialBudget12, TargetAdjusted12, BudgetAdjusted12, ProjectionAdjusted12) + ) AS CrossApplied (MonthSortOrder, InitialBudget, Target, Budget, Projection) + LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder + WHERE gl.BudgetConfigID = @BudgetConfigID + + SELECT + EntityID, + vw.DepartmentID, + AccountID, + FinancialReportingID, + VariabilityID, + UnitTypeID, + 2 AS TimeClassID, + vw.FiscalMonthID, + vw.FiscalYearID, + FiscalTimeID, + InitialBudget AS OriginalValue, + Target AS Value, + Budget AS ManagerValue + INTO #generalLedgerSource + FROM #glPivoted vw + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = vw.DepartmentID + INNER JOIN fw.DimFiscalTime dft ON VW.FiscalYearID = dft.FiscalYearID AND VW.FiscalMonthID = dft.FiscalMonthID + WHERE vw.BudgetConfigID = @BudgetConfigID + AND (Target != 0 OR Budget != 0) + + INSERT INTO #generalLedgerSource (EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID, UnitTypeID, + TimeClassID, FiscalMonthID, FiscalYearID, FiscalTimeID, OriginalValue, Value, ManagerValue) + SELECT + EntityID, + vw.DepartmentID, + AccountID, + FinancialReportingID, + VariabilityID, + UnitTypeID, + 12 AS TimeClassID, + vw.FiscalMonthID, + vw.FiscalYearID - 1, + FiscalTimeID, + 0 AS OriginalValue, + Projection AS Value, + Projection AS ManagerValue + FROM #glPivoted vw + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = vw.DepartmentID + INNER JOIN fw.DimFiscalTime dft ON vw.FiscalYearID - 1 = dft.FiscalYearID AND VW.FiscalMonthID = dft.FiscalMonthID + WHERE vw.BudgetConfigID = @BudgetConfigID + AND (Projection != 0) + + CREATE CLUSTERED INDEX inx_stat ON #generalLedgerSource ( + TimeClassID, + EntityID, + DepartmentID, + AccountID, + FinancialReportingID, + VariabilityID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + ) + + -- Populate the dimensionality first + INSERT INTO #SRC (EntityID, VW.DepartmentID, AccountID, FinancialReportingID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID) + SELECT DISTINCT + EntityID, + VW.DepartmentID, + AccountID, + FinancialReportingID, + VariabilityID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + FROM #generalLedgerSource VW + + CREATE CLUSTERED INDEX inx_src ON #SRC ( + EntityID, + DepartmentID, + AccountID, + FinancialReportingID, + VariabilityID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + ) + + -- Updating each column individually because we can't necessarily do it all in one update. This is because the Src table has unit type and time class on columns not rows. + -- Case statements wouldn't work in this case because we only want to update certain columns when it meets certain criteria. IE: you wouldn't want to do TargetDollars = CASE WHEN ap.TimeClassID = 2 THEN ap.Value ELSE 0 END + -- because then when it hits a row that doesn't match that, it's gonna set the target to 0. + + -- Update Budget/Target Dollars + UPDATE src + SET + BudgetDollars = ap.ManagerValue, + TargetDollars = ap.Value + FROM #SRC src + INNER JOIN #generalLedgerSource ap ON + src.EntityID = ap.EntityID + AND src.DepartmentID = ap.DepartmentID + AND src.AccountID = ap.AccountID + AND src.FinancialReportingID = ap.FinancialReportingID + AND src.VariabilityID = ap.VariabilityID + AND src.FiscalYearID = ap.FiscalYearID + AND src.FiscalMonthID = ap.FiscalMonthID + WHERE ap.TimeClassID = 2 + + -- Update Projected Dollars + UPDATE src + SET + ProjectedDollars = ap.ManagerValue + FROM #SRC src + INNER JOIN #generalLedgerSource ap ON + src.EntityID = ap.EntityID + AND src.DepartmentID = ap.DepartmentID + AND src.AccountID = ap.AccountID + AND src.FinancialReportingID = ap.FinancialReportingID + AND src.VariabilityID = ap.VariabilityID + AND src.FiscalYearID = ap.FiscalYearID + AND src.FiscalMonthID = ap.FiscalMonthID + WHERE ap.TimeClassID = 12 + + IF (@IsDebug = 1) + BEGIN + SELECT '#SRC' AS TempTable, EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID, BudgetDollars, ProjectedDollars, TargetDollars + FROM #SRC; + + SELECT '#generalLedgerSource' AS TempTable, EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, FiscalTimeID, OriginalValue, Value, ManagerValue + FROM #generalLedgerSource + + RETURN + END + + -- Publish the data from the temp table to fp.FactReportingAP. This uses a merge statement to handle inserts and updates + -- In the event that the active configuration changes, we need to clear out this table because we only hold data for the active configuration. This is done from the UI itself. + -- We don't do any deletes from the reporting table because we have multiple sources going into it at a given time. In the future if we + -- needed to do a delete for some reason, we would need to combine them all into one MEGA proc which is gross and nasty. Since we don't delete data, this shouldn't be an issue + ;WITH TGT AS + ( + SELECT EntityID, FRS.DepartmentID, AccountID, FinancialReportingID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID, BudgetDollars, ProjectedDollars, TargetDollars + FROM [fp].[FactReportingAP] FRS + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = FRS.DepartmentID + ) + MERGE TGT AS target + USING #SRC AS source + ON ( + target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.AccountID = source.AccountID + AND target.FinancialReportingID = source.FinancialReportingID + AND target.VariabilityID = source.VariabilityID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + AND target.FiscalTimeID = source.FiscalTimeID + ) + WHEN MATCHED AND + ( + target.BudgetDollars <> source.BudgetDollars + OR target.ProjectedDollars <> source.ProjectedDollars + OR target.TargetDollars <> source.TargetDollars + ) + THEN + UPDATE SET + target.BudgetDollars = ISNULL(source.BudgetDollars, 0), + target.ProjectedDollars = ISNULL(source.ProjectedDollars, 0), + target.TargetDollars = ISNULL(source.TargetDollars, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + EntityID, + DepartmentID, + AccountID, + FinancialReportingID, + VariabilityID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID, + BudgetDollars, + ProjectedDollars, + TargetDollars + ) + VALUES ( + source.EntityID, + source.DepartmentID, + source.AccountID, + source.FinancialReportingID, + source.VariabilityID, + source.FiscalMonthID, + source.FiscalYearID, + source.FiscalTimeID, + ISNULL(source.BudgetDollars, 0), + ISNULL(source.ProjectedDollars, 0), + ISNULL(source.TargetDollars, 0) + ); + + + ------------------------------------------------------------------------------------------------------- + -- JAZZ-49629 : Handing zeroing out for AA data marts + -- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the + -- targeting above. + ------------------------------------------------------------------------------------------------------- + + -- Get all records that were adjusted + SELECT DISTINCT chg.GeneralLedgerID + INTO #adjustedRecords + FROM [fp].[GeneralLedgerChangeHistory] chg + INNER JOIN [fp].[GeneralLedger] fgl ON chg.GeneralLedgerID = fgl.GeneralLedgerID + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fgl.DepartmentID + WHERE chg.BudgetConfigID = @BudgetConfigID + + SELECT + EntityID, + VW.DepartmentID, + AccountID, + FinancialReportingID, + VariabilityID, + UnitTypeID, + 2 AS TimeClassID, + vw.FiscalMonthID, + vw.FiscalYearID, + 0 AS OriginalValue, + Target AS Value, + Budget AS ManagerValue + INTO #tempUnpivoted + FROM #glPivoted vw + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = VW.DepartmentID + INNER JOIN #adjustedRecords adj ON VW.GeneralLedgerID = adj.GeneralLedgerID + INNER JOIN fp.BudgetConfig bc ON VW.BudgetConfigID = bc.BudgetConfigID + WHERE VW.BudgetConfigID = @BudgetConfigID + AND (Target = 0 OR Budget = 0) + + INSERT INTO #tempUnpivoted (EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID, + UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, OriginalValue, Value, ManagerValue) + SELECT + EntityID, + VW.DepartmentID, + AccountID, + FinancialReportingID, + VariabilityID, + UnitTypeID, + 12 AS TimeClassID, + vw.FiscalMonthID, + vw.FiscalYearID - 1, + 0 AS OriginalValue, + Projection AS Value, + Projection AS ManagerValue + FROM #glPivoted vw + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = VW.DepartmentID + INNER JOIN #adjustedRecords adj ON VW.GeneralLedgerID = adj.GeneralLedgerID + INNER JOIN fp.BudgetConfig bc ON VW.BudgetConfigID = bc.BudgetConfigID + WHERE VW.BudgetConfigID = @BudgetConfigID + AND Projection = 0 + + -- Find the records that need to be updated by comparing the source to the reporting table + SELECT + frgl.RowID, + cv.Value, + cv.ManagerValue + INTO #dataToUpdate_Budgeted + FROM [fp].[FactReportingAP] frgl + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = frgl.DepartmentID + INNER JOIN #tempUnpivoted cv ON + cv.EntityID = frgl.EntityID + AND cv.DepartmentID = frgl.DepartmentID + AND cv.AccountID = frgl.AccountID + AND cv.FinancialReportingID = frgl.FinancialReportingID + AND cv.VariabilityID = frgl.VariabilityID + AND cv.FiscalYearID = frgl.FiscalYearID + AND cv.FiscalMonthID = frgl.FiscalMonthID + WHERE 1 = 1 + AND cv.TimeClassID = 2 + AND ( + cv.ManagerValue != frgl.BudgetDollars + OR cv.Value != frgl.TargetDollars + ) + + SELECT + frgl.RowID, + cv.Value, + cv.ManagerValue + INTO #dataToUpdate_Projected + FROM [fp].[FactReportingAP] frgl + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = frgl.DepartmentID + INNER JOIN #tempUnpivoted cv ON + cv.EntityID = frgl.EntityID + AND cv.DepartmentID = frgl.DepartmentID + AND cv.AccountID = frgl.AccountID + AND cv.FinancialReportingID = frgl.FinancialReportingID + AND cv.VariabilityID = frgl.VariabilityID + AND cv.FiscalYearID = frgl.FiscalYearID + AND cv.FiscalMonthID = frgl.FiscalMonthID + WHERE 1 = 1 + AND cv.TimeClassID = 12 + AND cv.ManagerValue != frgl.ProjectedDollars + + -- Update the records + UPDATE report + SET + report.BudgetDollars = upd.ManagerValue, + report.TargetDollars = upd.Value + FROM [fp].[FactReportingAP] report + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID + INNER JOIN #dataToUpdate_Budgeted upd ON upd.RowID = report.RowID + WHERE 1 = 1 + AND ( + report.TargetDollars != upd.Value + OR report.BudgetDollars != upd.ManagerValue + ) + + UPDATE report + SET + report.ProjectedDollars = upd.Value + FROM [fp].[FactReportingAP] report + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID + INNER JOIN #dataToUpdate_Projected upd ON upd.RowID = report.RowID + WHERE 1 = 1 + AND report.ProjectedDollars != upd.Value +END +GO + + +--------------------------------------------- + +-- fp.procFactReportFinancialStatementInsert +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 08-25-2023 MY JAZZ-59500 Updated view to restructure +*************************************************************/ +CREATE PROC [fp].[procFactReportFinancialStatementInsert] + @BudgetConfigID int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +WITH RECOMPILE +AS + EXEC fp.procProcessReportFactStatistics_TargetBudget @BudgetConfigID, @SourceDimensionality; + EXEC fp.procProcessReportFactStatistics_Initial @BudgetConfigID, @SourceDimensionality; + EXEC fp.ProcReportFactStatisticsHistoryBackup @BudgetConfigID, @SourceDimensionality; + + EXEC fp.procProcessReportFactStaffing_TargetBudget @BudgetConfigID, @SourceDimensionality; + EXEC fp.procProcessReportFactStaffing_Initial @BudgetConfigID, @SourceDimensionality; + EXEC fp.ProcReportFactStaffingHistoryBackup @BudgetConfigID, @SourceDimensionality; + + EXEC fp.procProcessReportFactGeneralLedger @BudgetConfigID, @SourceDimensionality; + EXEC fp.procProcessReportFactGeneralLedger_Initial @BudgetConfigID, @SourceDimensionality; + EXEC fp.ProcReportFactGeneralLedgerHistoryBackup @BudgetConfigID, @SourceDimensionality; + + -- Note: the annualization factor here is wrong, it technically comes from GetAnnualizationFactor, however + -- with the way this proc is called we can't pass this in here. I'm also not entirely sure this proc is used + -- as it hasn't been updated from a while ago and we didn't get any bugs for it. I am adding this here just in case. + -- However, if this is causing issues we'll need to add tests for this proc for one to catch things, but also + -- take the code that is getting the annualization factor and pull it into SQL. + DECLARE @AnnualizationFactor DECIMAL(19, 8) = 1; + EXEC fp.ProcReportFactStatisticsISBackup @BudgetConfigID, @SourceDimensionality; +GO + + +--------------------------------------------- + +-- fp.procFactReportFinancialStatementInsert_archive +CREATE PROC fp.procFactReportFinancialStatementInsert_archive +WITH RECOMPILE +AS + declare @ActiveConfigID int + select @ActiveConfigID = BudgetConfigID from fp.BudgetConfig where IsActive = 1; + + DROP TABLE fp.FactReportGeneralLedger_archive; + SELECT * INTO fp.FactReportGeneralLedger_archive FROM [fp].[viewFactGeneralLedger_Unpivoted_source] where BudgetConfigID != @ActiveConfigID and (OriginalValue != 0 or Value != 0 or ManagerValue != 0); + CREATE CLUSTERED INDEX IDX_FactReportGeneralLedger_archive ON fp.FactReportGeneralLedger_archive (GeneralLedgerID,BudgetConfigID,EntityGroupConfigID,EntityID,DepartmentID,AccountID,FinancialReportingID,APEModelSectionID,VariabilityID,UnitTypeID,TimeClassID,FiscalYearID,FiscalMonthID); + + DROP TABLE fp.FactReportGeneralLedgerHistory_archive; + SELECT * INTO fp.FactReportGeneralLedgerHistory_archive FROM [fp].[viewFactGeneralLedgerHistory_Unpivoted_source] where BudgetConfigID != @ActiveConfigID and Value != 0; + CREATE CLUSTERED INDEX IDX_FactReportGeneralLedgerHistory_archive ON fp.FactReportGeneralLedgerHistory_archive (GeneralLedgerID,BudgetConfigID,EntityGroupConfigID,EntityID,DepartmentID,AccountID,FinancialReportingID,APEModelSectionID,VariabilityID,UnitTypeID,TimeClassID,FiscalYearID,FiscalMonthID); + + DROP TABLE fp.FactReportStaffing_archive; + SELECT * INTO fp.FactReportStaffing_archive FROM [fp].viewFactStaffing_Unpivoted_source where BudgetConfigID != @ActiveConfigID and (OriginalValue != 0 or Value != 0 or ManagerValue != 0); + CREATE CLUSTERED INDEX IDX_FactReportStaffing_archive ON fp.FactReportStaffing_archive (BudgetConfigID,EntityID,DepartmentID,JobCodeID,PayCodeGroupID,VariabilityID,ProductiveClassID,UnitTypeID,TimeClassID,FiscalMonthID,FiscalYearID); + + DROP TABLE fp.FactReportStaffingHistory_archive; + SELECT * INTO fp.FactReportStaffingHistory_archive FROM [fp].viewFactStaffingHistory_Unpivoted_source where BudgetConfigID != @ActiveConfigID and Value != 0; + CREATE CLUSTERED INDEX IDX_FactReportStaffingHistory_archive ON fp.FactReportStaffingHistory_archive (StaffingID,BudgetConfigID,EntityGroupConfigID,EntityID,DepartmentID,JobCodeID,PayCodeGroupID,ProductiveClassID,VariabilityID,UnitTypeID,TimeClassID,FiscalYearID,FiscalMonthID); + + DROP TABLE fp.FactReportStatistics_archive; + SELECT * INTO fp.FactReportStatistics_archive FROM [fp].viewFactStatistics_Unpivoted_source where BudgetConfigID != @ActiveConfigID and (OriginalValue != 0 or Value != 0 or ManagerValue != 0); + CREATE CLUSTERED INDEX IDX_FactReportStatistics_archive ON fp.FactReportStatistics_archive (BudgetConfigID,EntityID,DepartmentID,AccountID,PatientClassID,PayorID,FinancialReportingID,UnitTypeID,TimeClassID,FiscalMonthID,FiscalYearID); + + DROP TABLE fp.FactReportStatisticsHistory_archive; + SELECT * INTO fp.FactReportStatisticsHistory_archive FROM [fp].viewFactStatisticsHistory_Unpivoted_source where BudgetConfigID != @ActiveConfigID and Value != 0; + CREATE CLUSTERED INDEX IDX_FactReportStatisticsHistory_archive ON fp.FactReportStatisticsHistory_archive (StatisticsID,BudgetConfigID,EntityGroupConfigID,EntityID,DepartmentID,AccountID,FinancialReportingID,PayorID,PatientClassID,UnitTypeID,TimeClassID,FiscalYearID,FiscalMonthID); +GO + + +--------------------------------------------- + +-- fp.procFactStaffingBaselineAndHistoryToReportingTransfer +CREATE PROCEDURE [fp].[procFactStaffingBaselineAndHistoryToReportingTransfer] + @EntityGroupConfigID INT, + @SqlJoin NVARCHAR(MAX), + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +WITH RECOMPILE +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2020-07-24 MY JAZZ-2849 Initial Creation + ** 2 2022-06-15 MY JAZZ-38632 Add Targeting + ** 3 2022-07-18 MY JAZZ-37944 Add Initial Baseline + ** 4 2022-07-27 MY JAZZ-37944 Add NULL check for when the Staffing > GL Crosswalk is not filled out + ** 5 11-28-2022 MY JAZZ-43418 Add FiscalTimeID to Update + ** 6 2023-12-07 BW JAZZ-63600 Data model restructure + *************************************************************/ + + -- IMPORTANT NOTE: This proc is only used to transfer data from AP to fp.FactReportingAP. + -- This new proc and table are only used in the new advanced analytics solution that leverages + -- snowflake. This proc will transfer data to fp.FactReportingAP, where SQL will then replicate + -- to Snowflake. + -- + -- It's also important to note that this functionality is currently only availible on demand and is not automatically synced. + -- This is also why the current procs aren't targeted. Once we hook this up to the engine, we can properly target the proc. + -- + -- More information can be found here: https://stratadecision.atlassian.net/wiki/spaces/DD/pages/3116214472/Advanced+Analytics + + SET NOCOUNT ON; + + EXEC [dbo].[procSysDropTempTable] '#SRC' + EXEC [dbo].[procSysDropTempTable] '#staffingSource' + EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment' + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM [fp].[BudgetConfig] bc INNER JOIN [fp].[EntityGroupConfig] egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE bc.IsActive = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID)) BEGIN RETURN END + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[Staffing] d WITH (READUNCOMMITTED) + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + CREATE TABLE #SRC ( + EntityGroupConfigID INT, + EntityID INT, + DepartmentID INT, + JobCodeID INT, + ProductiveClassID INT, + PayCodeGroupID INT, + EmployeeID INT, + VariabilityID INT, + FiscalMonthID TINYINT, + FiscalYearID SMALLINT, + FiscalTimeID INT, + InitialDollars DECIMAL(19, 8) DEFAULT(0), + InitialHours DECIMAL(19, 8) DEFAULT(0), + InitialFTEs DECIMAL(19, 8) DEFAULT(0), + GLAccountID INT -- This is used purely in reporting and all we're doing is updating it based on the crosswalk + ) + + SELECT + EntityGroupConfigID, + EntityID, + VW.DepartmentID, + JobCodeID, + ProductiveClassID, + PayCodeGroupID, + EmployeeID, + VariabilityID, + UnitTypeID, + TimeClassID, + VW.FiscalMonthID, + VW.FiscalYearID, + FiscalTimeID, + OriginalValue + INTO #staffingSource + FROM [fp].[viewFactStaffing_Unpivoted_BaselineOnly] VW -- This view is SLOOOOOOOOOOW, so trying to speed this up by only using this once. + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = VW.DepartmentID + INNER JOIN fw.DimFiscalTime dft ON VW.FiscalYearID = dft.FiscalYearID + AND VW.FiscalMonthID = dft.FiscalMonthID + WHERE VW.EntityGroupConfigID = @EntityGroupConfigID + AND UnitTypeID IN (34, 51, 144) -- We only want the dollars, hours, and FTEs. We don't want rates. + AND (OriginalValue != 0) + + CREATE CLUSTERED INDEX inx_stat ON #staffingSource ( + TimeClassID, + UnitTypeID, + EntityID, + DepartmentID, + JobCodeID, + ProductiveClassID, + PayCodeGroupID, + EmployeeID, + VariabilityID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + ) + + -- Populate the dimensionality first + INSERT INTO #SRC (EntityID, VW.DepartmentID, JobCodeID, ProductiveClassID, PayCodeGroupID, EmployeeID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID) + SELECT DISTINCT + EntityID, + VW.DepartmentID, + JobCodeID, + ProductiveClassID, + PayCodeGroupID, + EmployeeID, + VariabilityID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + FROM #staffingSource VW + + CREATE CLUSTERED INDEX inx_src ON #SRC ( + EntityID, + DepartmentID, + JobCodeID, + ProductiveClassID, + PayCodeGroupID, + EmployeeID, + VariabilityID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + ) + + DECLARE @SQL NVARCHAR(MAX) = ' + UPDATE staff + SET staff.GLAccountID = pax.AccountID + FROM #SRC staff + ' + @SqlJoin + ' + WHERE pax.UnitTypeID = 34' + + EXEC(@SQL); + + IF @IsDebug = 1 + PRINT @SQL + + -- Updating each column individually because we can't necessarily do it all in one update. This is because the Src table has unit type and time class on columns not rows. + -- Case statements wouldn't work in this case because we only want to update certain columns when it meets certain criteria. IE: you wouldn't want to do TargetDollars = CASE WHEN ap.TimeClassID = 2 THEN ap.Value ELSE 0 END + -- because then when it hits a row that doesn't match that, it's gonna set the target to 0. + + -- Update Budget/Target Dollars + UPDATE src + SET + InitialDollars = ap.OriginalValue + FROM #SRC src + INNER JOIN #staffingSource ap ON + src.EntityID = ap.EntityID + AND src.DepartmentID = ap.DepartmentID + AND src.JobCodeID = ap.JobCodeID + AND src.ProductiveClassID = ap.ProductiveClassID + AND src.PayCodeGroupID = ap.PayCodeGroupID + AND src.EmployeeID = ap.EmployeeID + AND src.VariabilityID = ap.VariabilityID + AND src.FiscalYearID = ap.FiscalYearID + AND src.FiscalMonthID = ap.FiscalMonthID + WHERE ap.TimeClassID = 2 AND ap.UnitTypeID = 34 + + -- Update Budget/Target Hours + UPDATE src + SET + InitialHours = ap.OriginalValue + FROM #SRC src + INNER JOIN #staffingSource ap ON + src.EntityID = ap.EntityID + AND src.DepartmentID = ap.DepartmentID + AND src.JobCodeID = ap.JobCodeID + AND src.ProductiveClassID = ap.ProductiveClassID + AND src.PayCodeGroupID = ap.PayCodeGroupID + AND src.EmployeeID = ap.EmployeeID + AND src.VariabilityID = ap.VariabilityID + AND src.FiscalYearID = ap.FiscalYearID + AND src.FiscalMonthID = ap.FiscalMonthID + WHERE ap.TimeClassID = 2 AND ap.UnitTypeID = 51 + + -- Update Budget/Target FTEs + UPDATE src + SET + InitialFTEs = ap.OriginalValue + FROM #SRC src + INNER JOIN #staffingSource ap ON + src.EntityID = ap.EntityID + AND src.DepartmentID = ap.DepartmentID + AND src.JobCodeID = ap.JobCodeID + AND src.ProductiveClassID = ap.ProductiveClassID + AND src.PayCodeGroupID = ap.PayCodeGroupID + AND src.EmployeeID = ap.EmployeeID + AND src.VariabilityID = ap.VariabilityID + AND src.FiscalYearID = ap.FiscalYearID + AND src.FiscalMonthID = ap.FiscalMonthID + WHERE ap.TimeClassID = 2 AND ap.UnitTypeID = 144 + + ------------------------------------------------------------------------------------------------------- + -- D-09168 : CCF: Data not flowing through into reports + -- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the + -- targeting above. This is a short term solution until we can get a more performant solution. + -- + -- NOTE: This is not a problem yet, since we don't have targeting, but I am squirreling this until + -- we add it so we don't re-introduce this bug. + -- + -- IMPORTANT NOTE: WHEN WE ADD TARGETING YOU NEED TO IMPLEMENT THIS WORKAROUND. GRAB THIS FROM THE + -- EXISTING PROCS AND UPDATE IT FOR THIS. + ------------------------------------------------------------------------------------------------------- + + IF (@IsDebug = 1) + BEGIN + SELECT '#SRC' AS TempTable, EntityID, DepartmentID, JobCodeID, ProductiveClassID, PayCodeGroupID, EmployeeID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID, GLAccountID, + InitialDollars, + InitialHours, + InitialFTEs + FROM #SRC; + + SELECT '#staffingSource' AS TempTable, EntityID, DepartmentID, JobCodeID, ProductiveClassID, PayCodeGroupID, EmployeeID, VariabilityID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, FiscalTimeID, OriginalValue + FROM #staffingSource + + RETURN + END + + -- Publish the data from the temp table to fp.FactReportingAP. This uses a merge statement to handle inserts and updates + -- In the event that the active configuration changes, we need to clear out this table because we only hold data for the active configuration. This is done from the UI itself. + -- We don't do any deletes from the reporting table because we have multiple sources going into it at a given time. In the future if we + -- needed to do a delete for some reason, we would need to combine them all into one MEGA proc which is gross and nasty. Since we don't delete data, this shouldn't be an issue + ;WITH TGT AS + ( + SELECT EntityID, FRS.DepartmentID, JobCodeID, ProductiveClassID, PayCodeGroupID, EmployeeID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID, AccountID, + InitialDollars, + InitialHours, + InitialFTEs + FROM [fp].[FactReportingAP] FRS + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = FRS.DepartmentID + ) + MERGE TGT AS target + USING #SRC AS source + ON ( + target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.JobCodeID = source.JobCodeID + AND target.ProductiveClassID = source.ProductiveClassID + AND target.PayCodeGroupID = source.PayCodeGroupID + AND target.EmployeeID = source.EmployeeID + AND target.VariabilityID = source.VariabilityID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + AND target.FiscalTimeID = source.FiscalTimeID + AND target.AccountID = ISNULL(source.GLAccountID, 0) + ) + WHEN MATCHED AND + ( + target.InitialDollars <> source.InitialDollars + OR target.InitialHours <> source.InitialHours + OR target.InitialFTEs <> source.InitialFTEs + OR target.AccountID <> ISNULL(source.GLAccountID, 0) + ) + THEN + UPDATE SET + target.InitialDollars = ISNULL(source.InitialDollars, 0), + target.InitialHours = ISNULL(source.InitialHours, 0), + target.InitialFTEs = ISNULL(source.InitialFTEs, 0), + target.AccountID = ISNULL(source.GLAccountID, 0) -- We need to update the account in the event it gets changed + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + EntityID, + DepartmentID, + JobCodeID, + ProductiveClassID, + PayCodeGroupID, + EmployeeID, + VariabilityID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID, + AccountID, + InitialDollars, + InitialHours, + InitialFTEs + ) + VALUES ( + source.EntityID, + source.DepartmentID, + source.JobCodeID, + source.ProductiveClassID, + source.PayCodeGroupID, + source.EmployeeID, + source.VariabilityID, + source.FiscalMonthID, + source.FiscalYearID, + source.FiscalTimeID, + ISNULL(source.GLAccountID, 0), + ISNULL(source.InitialDollars, 0), + ISNULL(source.InitialHours, 0), + ISNULL(source.InitialFTEs, 0) + ); + +END +GO + + +--------------------------------------------- + +-- fp.procFactStaffingToReportingTransfer +CREATE PROCEDURE [fp].[procFactStaffingToReportingTransfer] + @EntityGroupConfigID INT, + @SqlJoin NVARCHAR(MAX), + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +WITH RECOMPILE +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2020-07-24 MY JAZZ-2849 Initial Creation + ** 2 2022-06-15 MY JAZZ-38632 Add Targeting + ** 3 2022-07-27 MY JAZZ-37944 Add NULL check for when the Staffing > GL Crosswalk is not filled out + ** 4 11-28-2022 MY JAZZ-43418 Add FiscalTimeID to Update + ** 5 2023-02-23 MY JAZZ-49629 Handing zeroing out for AA data marts + ** 6 2023-12-07 BW JAZZ-63600 Data model restructure + ** 7 2024-12-12 MY JAZZ-79803 SQL Optimization recommendation per MP + *************************************************************/ + + -- IMPORTANT NOTE: This proc is only used to transfer data from AP to fp.FactReportingAP. + -- This new proc and table are only used in the new advanced analytics solution that leverages + -- snowflake. This proc will transfer data to fp.FactReportingAP, where SQL will then replicate + -- to Snowflake. + -- + -- More information can be found here: https://stratadecision.atlassian.net/wiki/spaces/DD/pages/3116214472/Advanced+Analytics + + SET NOCOUNT ON; + + EXEC [dbo].[procSysDropTempTable] '#SRC' + EXEC [dbo].[procSysDropTempTable] '#staffingSource' + EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment' + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM [fp].[BudgetConfig] bc INNER JOIN [fp].[EntityGroupConfig] egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE bc.IsActive = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID)) BEGIN RETURN END + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[Staffing] d WITH (READUNCOMMITTED) + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + CREATE TABLE #SRC ( + EntityGroupConfigID INT, + EntityID INT, + DepartmentID INT, + JobCodeID INT, + ProductiveClassID INT, + PayCodeGroupID INT, + EmployeeID INT, + VariabilityID INT, + FiscalMonthID TINYINT, + FiscalYearID SMALLINT, + FiscalTimeID INT, + BudgetDollars DECIMAL(19, 8) DEFAULT(0), + ProjectedDollars DECIMAL(19, 8) DEFAULT(0), + TargetDollars DECIMAL(19, 8) DEFAULT(0), + BudgetHours DECIMAL(19, 8) DEFAULT(0), + ProjectedHours DECIMAL(19, 8) DEFAULT(0), + TargetHours DECIMAL(19, 8) DEFAULT(0), + BudgetFTEs DECIMAL(19, 8) DEFAULT(0), + ProjectedFTEs DECIMAL(19, 8) DEFAULT(0), + TargetFTEs DECIMAL(19, 8) DEFAULT(0), + GLAccountID INT -- This is used purely in reporting and all we're doing is updating it based on the crosswalk + ) + + SELECT + EntityGroupConfigID, + EntityID, + VW.DepartmentID, + JobCodeID, + ProductiveClassID, + PayCodeGroupID, + EmployeeID, + VariabilityID, + UnitTypeID, + TimeClassID, + VW.FiscalMonthID, + VW.FiscalYearID, + FiscalTimeID, + OriginalValue, + Value, + ManagerValue + INTO #staffingSource + FROM [fp].[viewFactStaffing_Unpivoted_source] VW -- This view is SLOOOOOOOOOOW, so trying to speed this up by only using this once. + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = VW.DepartmentID + INNER JOIN fw.DimFiscalTime dft ON VW.FiscalYearID = dft.FiscalYearID + AND VW.FiscalMonthID = dft.FiscalMonthID + WHERE VW.EntityGroupConfigID = @EntityGroupConfigID + AND UnitTypeID IN (34, 51, 144) -- We only want the dollars, hours, and FTEs. We don't want rates. + AND (Value != 0 OR ManagerValue != 0) + + CREATE CLUSTERED INDEX inx_stat ON #staffingSource ( + TimeClassID, + UnitTypeID, + EntityID, + DepartmentID, + JobCodeID, + ProductiveClassID, + PayCodeGroupID, + EmployeeID, + VariabilityID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + ) + + -- Populate the dimensionality first + INSERT INTO #SRC (EntityID, VW.DepartmentID, JobCodeID, ProductiveClassID, PayCodeGroupID, EmployeeID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID) + SELECT DISTINCT + EntityID, + VW.DepartmentID, + JobCodeID, + ProductiveClassID, + PayCodeGroupID, + EmployeeID, + VariabilityID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + FROM #staffingSource VW + + CREATE CLUSTERED INDEX inx_src ON #SRC ( + EntityID, + DepartmentID, + JobCodeID, + ProductiveClassID, + PayCodeGroupID, + EmployeeID, + VariabilityID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + ) + + UPDATE STATISTICS #SRC; -- JAZZ-79803: Recommendation per MP + + DECLARE @SQL NVARCHAR(MAX) = ' + UPDATE staff + SET staff.GLAccountID = pax.AccountID + FROM #SRC staff + ' + @SqlJoin + ' + WHERE pax.UnitTypeID = 34 + OPTION (RECOMPILE)' -- JAZZ-79803: Recommendation per MP + + EXEC(@SQL); + + IF @IsDebug = 1 + PRINT @SQL + + -- Updating each column individually because we can't necessarily do it all in one update. This is because the Src table has unit type and time class on columns not rows. + -- Case statements wouldn't work in this case because we only want to update certain columns when it meets certain criteria. IE: you wouldn't want to do TargetDollars = CASE WHEN ap.TimeClassID = 2 THEN ap.Value ELSE 0 END + -- because then when it hits a row that doesn't match that, it's gonna set the target to 0. + + -- Update Budget/Target Dollars + UPDATE src + SET + BudgetDollars = ap.ManagerValue, + TargetDollars = ap.Value + FROM #SRC src + INNER JOIN #staffingSource ap ON + src.EntityID = ap.EntityID + AND src.DepartmentID = ap.DepartmentID + AND src.JobCodeID = ap.JobCodeID + AND src.ProductiveClassID = ap.ProductiveClassID + AND src.PayCodeGroupID = ap.PayCodeGroupID + AND src.EmployeeID = ap.EmployeeID + AND src.VariabilityID = ap.VariabilityID + AND src.FiscalYearID = ap.FiscalYearID + AND src.FiscalMonthID = ap.FiscalMonthID + WHERE ap.TimeClassID = 2 AND ap.UnitTypeID = 34 + + -- Update Projected Dollars + UPDATE src + SET + ProjectedDollars = ap.Value + FROM #SRC src + INNER JOIN #staffingSource ap ON + src.EntityID = ap.EntityID + AND src.DepartmentID = ap.DepartmentID + AND src.JobCodeID = ap.JobCodeID + AND src.ProductiveClassID = ap.ProductiveClassID + AND src.PayCodeGroupID = ap.PayCodeGroupID + AND src.EmployeeID = ap.EmployeeID + AND src.VariabilityID = ap.VariabilityID + AND src.FiscalYearID = ap.FiscalYearID + AND src.FiscalMonthID = ap.FiscalMonthID + WHERE ap.TimeClassID = 12 AND ap.UnitTypeID = 34 + + -- Update Budget/Target Hours + UPDATE src + SET + BudgetHours = ap.ManagerValue, + TargetHours = ap.Value + FROM #SRC src + INNER JOIN #staffingSource ap ON + src.EntityID = ap.EntityID + AND src.DepartmentID = ap.DepartmentID + AND src.JobCodeID = ap.JobCodeID + AND src.ProductiveClassID = ap.ProductiveClassID + AND src.PayCodeGroupID = ap.PayCodeGroupID + AND src.EmployeeID = ap.EmployeeID + AND src.VariabilityID = ap.VariabilityID + AND src.FiscalYearID = ap.FiscalYearID + AND src.FiscalMonthID = ap.FiscalMonthID + WHERE ap.TimeClassID = 2 AND ap.UnitTypeID = 51 + + -- Update Projected Hours + UPDATE src + SET + ProjectedHours = ap.Value + FROM #SRC src + INNER JOIN #staffingSource ap ON + src.EntityID = ap.EntityID + AND src.DepartmentID = ap.DepartmentID + AND src.JobCodeID = ap.JobCodeID + AND src.ProductiveClassID = ap.ProductiveClassID + AND src.PayCodeGroupID = ap.PayCodeGroupID + AND src.EmployeeID = ap.EmployeeID + AND src.VariabilityID = ap.VariabilityID + AND src.FiscalYearID = ap.FiscalYearID + AND src.FiscalMonthID = ap.FiscalMonthID + WHERE ap.TimeClassID = 12 AND ap.UnitTypeID = 51 + + -- Update Budget/Target FTEs + UPDATE src + SET + BudgetFTEs = ap.ManagerValue, + TargetFTEs = ap.Value + FROM #SRC src + INNER JOIN #staffingSource ap ON + src.EntityID = ap.EntityID + AND src.DepartmentID = ap.DepartmentID + AND src.JobCodeID = ap.JobCodeID + AND src.ProductiveClassID = ap.ProductiveClassID + AND src.PayCodeGroupID = ap.PayCodeGroupID + AND src.EmployeeID = ap.EmployeeID + AND src.VariabilityID = ap.VariabilityID + AND src.FiscalYearID = ap.FiscalYearID + AND src.FiscalMonthID = ap.FiscalMonthID + WHERE ap.TimeClassID = 2 AND ap.UnitTypeID = 144 + + -- Update Projected FTEs + UPDATE src + SET + ProjectedFTEs = ap.Value + FROM #SRC src + INNER JOIN #staffingSource ap ON + src.EntityID = ap.EntityID + AND src.DepartmentID = ap.DepartmentID + AND src.JobCodeID = ap.JobCodeID + AND src.ProductiveClassID = ap.ProductiveClassID + AND src.PayCodeGroupID = ap.PayCodeGroupID + AND src.EmployeeID = ap.EmployeeID + AND src.VariabilityID = ap.VariabilityID + AND src.FiscalYearID = ap.FiscalYearID + AND src.FiscalMonthID = ap.FiscalMonthID + WHERE ap.TimeClassID = 12 AND ap.UnitTypeID = 144 + + ------------------------------------------------------------------------------------------------------- + -- D-09168 : CCF: Data not flowing through into reports + -- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the + -- targeting above. This is a short term solution until we can get a more performant solution. + -- + -- NOTE: This is not a problem yet, since we don't have targeting, but I am squirreling this until + -- we add it so we don't re-introduce this bug. + -- + -- IMPORTANT NOTE: WHEN WE ADD TARGETING YOU NEED TO IMPLEMENT THIS WORKAROUND. GRAB THIS FROM THE + -- EXISTING PROCS AND UPDATE IT FOR THIS. + ------------------------------------------------------------------------------------------------------- + + IF (@IsDebug = 1) + BEGIN + SELECT '#SRC' AS TempTable, EntityID, DepartmentID, JobCodeID, ProductiveClassID, PayCodeGroupID, EmployeeID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID, GLAccountID, + BudgetDollars, ProjectedDollars, TargetDollars, + BudgetHours, ProjectedHours, TargetHours, + BudgetFTEs, ProjectedFTEs, TargetFTEs + FROM #SRC; + + SELECT '#staffingSource' AS TempTable, EntityID, DepartmentID, JobCodeID, ProductiveClassID, PayCodeGroupID, EmployeeID, VariabilityID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, FiscalTimeID, OriginalValue, Value, ManagerValue + FROM #staffingSource + + RETURN + END + + -- Publish the data from the temp table to fp.FactReportingAP. This uses a merge statement to handle inserts and updates + -- In the event that the active configuration changes, we need to clear out this table because we only hold data for the active configuration. This is done from the UI itself. + -- We don't do any deletes from the reporting table because we have multiple sources going into it at a given time. In the future if we + -- needed to do a delete for some reason, we would need to combine them all into one MEGA proc which is gross and nasty. Since we don't delete data, this shouldn't be an issue + ;WITH TGT AS + ( + SELECT EntityID, FRS.DepartmentID, JobCodeID, ProductiveClassID, PayCodeGroupID, EmployeeID, VariabilityID, FiscalMonthID, FiscalYearID, FiscalTimeID, AccountID, + BudgetDollars, ProjectedDollars, TargetDollars, + BudgetHours, ProjectedHours, TargetHours, + BudgetFTEs, ProjectedFTEs, TargetFTEs + FROM [fp].[FactReportingAP] FRS + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = FRS.DepartmentID + ) + MERGE TGT AS target + USING #SRC AS source + ON ( + target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.JobCodeID = source.JobCodeID + AND target.ProductiveClassID = source.ProductiveClassID + AND target.PayCodeGroupID = source.PayCodeGroupID + AND target.EmployeeID = source.EmployeeID + AND target.VariabilityID = source.VariabilityID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + AND target.FiscalTimeID = source.FiscalTimeID + AND target.AccountID = ISNULL(source.GLAccountID, 0) + ) + WHEN MATCHED AND + ( + target.BudgetDollars <> source.BudgetDollars + OR target.ProjectedDollars <> source.ProjectedDollars + OR target.TargetDollars <> source.TargetDollars + + OR target.BudgetHours <> source.BudgetHours + OR target.ProjectedHours <> source.ProjectedHours + OR target.TargetHours <> source.TargetHours + + OR target.BudgetFTEs <> source.BudgetFTEs + OR target.ProjectedFTEs <> source.ProjectedFTEs + OR target.TargetFTEs <> source.TargetFTEs + + OR target.AccountID <> ISNULL(source.GLAccountID, 0) + ) + THEN + UPDATE SET + target.BudgetDollars = ISNULL(source.BudgetDollars, 0), + target.ProjectedDollars = ISNULL(source.ProjectedDollars, 0), + target.TargetDollars = ISNULL(source.TargetDollars, 0), + + target.BudgetHours = ISNULL(source.BudgetHours, 0), + target.ProjectedHours = ISNULL(source.ProjectedHours, 0), + target.TargetHours = ISNULL(source.TargetHours, 0), + + target.BudgetFTEs = ISNULL(source.BudgetFTEs, 0), + target.ProjectedFTEs = ISNULL(source.ProjectedFTEs, 0), + target.TargetFTEs = ISNULL(source.TargetFTEs, 0), + + target.AccountID = ISNULL(source.GLAccountID, 0) -- We need to update the account in the event it gets changed + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + EntityID, + DepartmentID, + JobCodeID, + ProductiveClassID, + PayCodeGroupID, + EmployeeID, + VariabilityID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID, + AccountID, + BudgetDollars, + ProjectedDollars, + TargetDollars, + BudgetHours, + ProjectedHours, + TargetHours, + BudgetFTEs, + ProjectedFTEs, + TargetFTEs + ) + VALUES ( + source.EntityID, + source.DepartmentID, + source.JobCodeID, + source.ProductiveClassID, + source.PayCodeGroupID, + source.EmployeeID, + source.VariabilityID, + source.FiscalMonthID, + source.FiscalYearID, + source.FiscalTimeID, + ISNULL(source.GLAccountID, 0), -- While unlikely, we'll get a null error if the crosswalk isn't configured. + ISNULL(source.BudgetDollars, 0), + ISNULL(source.ProjectedDollars, 0), + ISNULL(source.TargetDollars, 0), + + ISNULL(source.BudgetHours, 0), + ISNULL(source.ProjectedHours, 0), + ISNULL(source.TargetHours, 0), + + ISNULL(source.BudgetFTEs, 0), + ISNULL(source.ProjectedFTEs, 0), + ISNULL(source.TargetFTEs, 0) + ); + + ------------------------------------------------------------------------------------------------------- + -- JAZZ-49629 : Handing zeroing out for AA data marts + -- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the + -- targeting above. + ------------------------------------------------------------------------------------------------------- + + -- Get all records that were adjusted + SELECT DISTINCT chg.StaffingID + INTO #adjustedRecords + FROM [fp].[StaffingChangeHistory] chg + INNER JOIN [fp].[Staffing] fgl ON chg.StaffingID = fgl.StaffingID + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fgl.DepartmentID + WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID + + SELECT + EntityGroupConfigID, + EntityID, + VW.DepartmentID, + JobCodeID, + ProductiveClassID, + PayCodeGroupID, + EmployeeID, + VariabilityID, + UnitTypeID, + TimeClassID, + VW.FiscalMonthID, + VW.FiscalYearID, + Value, + ManagerValue + INTO #tempUnpivoted + FROM [fp].[viewFactStaffing_Unpivoted_source] VW -- This view is SLOOOOOOOOOOW, so trying to speed this up by only using this once. + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = VW.DepartmentID + INNER JOIN #adjustedRecords adj ON VW.StaffingID = adj.StaffingID + INNER JOIN fp.BudgetConfig bc ON VW.BudgetConfigID = bc.BudgetConfigID + WHERE VW.EntityGroupConfigID = @EntityGroupConfigID + AND UnitTypeID IN (34, 51, 144) -- We only want the dollars, hours, and FTEs. We don't want rates. + AND ( + (VW.FiscalYearID = bc.FiscalYearID AND VW.TimeClassID = 2) + OR (VW.FiscalYearID = bc.FiscalYearID - 1 AND VW.TimeClassID = 12) + ) + AND ( + (VW.TimeClassID = 2 AND (Value = 0 OR ManagerValue = 0)) + OR (VW.TimeClassID = 12 AND Value = 0) + ) + + -- Find the records that need to be updated by comparing the source to the reporting table + SELECT + frgl.RowID, + cv.UnitTypeID, + cv.Value, + cv.ManagerValue + INTO #dataToUpdate_Budgeted + FROM [fp].[FactReportingAP] frgl + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = frgl.DepartmentID + INNER JOIN #tempUnpivoted cv ON + cv.EntityID = frgl.EntityID + AND cv.DepartmentID = frgl.DepartmentID + AND cv.JobCodeID = frgl.JobCodeID + AND cv.ProductiveClassID = frgl.ProductiveClassID + AND cv.PayCodeGroupID = frgl.PayCodeGroupID + AND cv.EmployeeID = frgl.EmployeeID + AND cv.VariabilityID = frgl.VariabilityID + AND cv.FiscalMonthID = frgl.FiscalMonthID + AND cv.FiscalYearID = frgl.FiscalYearID + WHERE 1 = 1 + AND cv.TimeClassID = 2 + AND ( + (cv.UnitTypeID = 34 AND (Value != frgl.TargetDollars OR ManagerValue != frgl.BudgetDollars)) + OR (cv.UnitTypeID = 51 AND (Value != frgl.TargetHours OR ManagerValue != frgl.BudgetHours)) + OR (cv.UnitTypeID = 144 AND (Value != frgl.TargetFTEs OR ManagerValue != frgl.BudgetFTEs)) + ) + + SELECT + frgl.RowID, + cv.UnitTypeID, + cv.Value, + cv.ManagerValue + INTO #dataToUpdate_Projected + FROM [fp].[FactReportingAP] frgl + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = frgl.DepartmentID + INNER JOIN #tempUnpivoted cv ON + cv.EntityID = frgl.EntityID + AND cv.DepartmentID = frgl.DepartmentID + AND cv.JobCodeID = frgl.JobCodeID + AND cv.ProductiveClassID = frgl.ProductiveClassID + AND cv.PayCodeGroupID = frgl.PayCodeGroupID + AND cv.EmployeeID = frgl.EmployeeID + AND cv.VariabilityID = frgl.VariabilityID + AND cv.FiscalMonthID = frgl.FiscalMonthID + AND cv.FiscalYearID = frgl.FiscalYearID + WHERE 1 = 1 + AND cv.TimeClassID = 12 + AND ( + (cv.UnitTypeID = 34 AND Value != frgl.ProjectedDollars) + OR (cv.UnitTypeID = 51 AND Value != frgl.ProjectedHours) + OR (cv.UnitTypeID = 144 AND Value != frgl.ProjectedFTEs) + ) + + -- Update the records + -- Budget + UPDATE report + SET + report.TargetDollars = upd.Value, + report.BudgetDollars = upd.ManagerValue + FROM [fp].[FactReportingAP] report + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID + INNER JOIN #dataToUpdate_Budgeted upd ON upd.RowID = report.RowID + WHERE 1 = 1 + AND upd.UnitTypeID = 34 + AND ( + report.TargetDollars != upd.Value + OR report.BudgetDollars != upd.ManagerValue + ) + + UPDATE report + SET + report.TargetHours = upd.Value, + report.BudgetHours = upd.ManagerValue + FROM [fp].[FactReportingAP] report + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID + INNER JOIN #dataToUpdate_Budgeted upd ON upd.RowID = report.RowID + WHERE 1 = 1 + AND upd.UnitTypeID = 51 + AND ( + report.TargetHours != upd.Value + OR report.BudgetHours != upd.ManagerValue + ) + + UPDATE report + SET + report.TargetFTEs = upd.Value, + report.BudgetFTEs = upd.ManagerValue + FROM [fp].[FactReportingAP] report + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID + INNER JOIN #dataToUpdate_Budgeted upd ON upd.RowID = report.RowID + WHERE 1 = 1 + AND upd.UnitTypeID = 144 + AND ( + report.TargetFTEs != upd.Value + OR report.BudgetFTEs != upd.ManagerValue + ) + + -- Projection + UPDATE report + SET + report.ProjectedDollars = upd.Value + FROM [fp].[FactReportingAP] report + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID + INNER JOIN #dataToUpdate_Projected upd ON upd.RowID = report.RowID + WHERE 1 = 1 + AND upd.UnitTypeID = 34 + AND report.ProjectedDollars != upd.Value + + UPDATE report + SET + report.ProjectedHours = upd.Value + FROM [fp].[FactReportingAP] report + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID + INNER JOIN #dataToUpdate_Projected upd ON upd.RowID = report.RowID + WHERE 1 = 1 + AND upd.UnitTypeID = 51 + AND report.ProjectedHours != upd.Value + + UPDATE report + SET + report.ProjectedFTEs = upd.Value + FROM [fp].[FactReportingAP] report + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID + INNER JOIN #dataToUpdate_Projected upd ON upd.RowID = report.RowID + WHERE 1 = 1 + AND upd.UnitTypeID = 144 + AND report.ProjectedFTEs != upd.Value +END +GO + + +--------------------------------------------- + +-- fp.procFactStatisticsBaselineAndHistoryToReportingTransfer +CREATE PROCEDURE [fp].[procFactStatisticsBaselineAndHistoryToReportingTransfer] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +WITH RECOMPILE +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2020-07-24 MY JAZZ-2849 Initial Creation + ** 2 2022-06-15 MY JAZZ-38632 Add Targeting + ** 3 2022-07-18 MY JAZZ-37944 Add Initial Baseline + ** 4 11-28-2022 MY JAZZ-43418 Add FiscalTimeID to Update + *************************************************************/ + + -- IMPORTANT NOTE: This proc is only used to transfer data from AP to fp.FactReportingAP. + -- This new proc and table are only used in the new advanced analytics solution that leverages + -- snowflake. This proc will transfer data to fp.FactReportingAP, where SQL will then replicate + -- to Snowflake. + -- + -- It's also important to note that this functionality is currently only availible on demand and is not automatically synced. + -- This is also why the current procs aren't targeted. Once we hook this up to the engine, we can properly target the proc. + -- + -- More information can be found here: https://confluence.sdt.local/display/DD/Advanced+Analytics + + SET NOCOUNT ON; + + EXEC [dbo].[procSysDropTempTable] '#SRC' + EXEC [dbo].[procSysDropTempTable] '#statisticsSource' + EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment' + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM [fp].[BudgetConfig] WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[FactStatistics] d WITH (READUNCOMMITTED) + WHERE BudgetConfigID = @BudgetConfigID + END + + CREATE TABLE #SRC ( + BudgetConfigID INT, + EntityID INT, + DepartmentID INT, + AccountID INT, + PatientClassID INT, + PayorID INT, + FinancialReportingID INT, + FiscalMonthID TINYINT, + FiscalYearID SMALLINT, + FiscalTimeID INT, + InitialUnits DECIMAL(19, 8) DEFAULT(0) + ) + + SELECT + EntityID, + VW.DepartmentID, + AccountID, + PatientClassID, + PayorID, + FinancialReportingID, + UnitTypeID, + TimeClassID, + VW.FiscalMonthID, + VW.FiscalYearID, + FiscalTimeID, + OriginalValue + INTO #statisticsSource + FROM [fp].[viewFactStatistics_Unpivoted_BaselineOnly] VW -- This view is SLOOOOOOOOOOW, so trying to speed this up by only using this once. + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = VW.DepartmentID + INNER JOIN fw.DimFiscalTime dft ON VW.FiscalYearID = dft.FiscalYearID + AND VW.FiscalMonthID = dft.FiscalMonthID + WHERE VW.BudgetConfigID = @BudgetConfigID + AND (OriginalValue != 0) + + CREATE CLUSTERED INDEX inx_stat ON #statisticsSource ( + TimeClassID, + EntityID, + DepartmentID, + AccountID, + PatientClassID, + PayorID, + FinancialReportingID, + FiscalMonthID, + FiscalYearID + ) + + -- Populate the dimensionality first + INSERT INTO #SRC (EntityID, VW.DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, FiscalMonthID, FiscalYearID, FiscalTimeID) + SELECT DISTINCT + EntityID, + VW.DepartmentID, + AccountID, + PatientClassID, + PayorID, + FinancialReportingID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + FROM #statisticsSource VW + + CREATE CLUSTERED INDEX inx_src ON #SRC ( + EntityID, + DepartmentID, + AccountID, + PatientClassID, + PayorID, + FinancialReportingID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + ) + + -- Updating each column individually because we can't necessarily do it all in one update. This is because the Src table has unit type and time class on columns not rows. + -- Case statements wouldn't work in this case because we only want to update certain columns when it meets certain criteria. IE: you wouldn't want to do TargetDollars = CASE WHEN ap.TimeClassID = 2 THEN ap.Value ELSE 0 END + -- because then when it hits a row that doesn't match that, it's gonna set the target to 0. + + -- Update Budget/Target Units + UPDATE src + SET + InitialUnits = ap.OriginalValue + FROM #SRC src + INNER JOIN #statisticsSource ap ON + src.EntityID = ap.EntityID + AND src.DepartmentID = ap.DepartmentID + AND src.AccountID = ap.AccountID + AND src.PatientClassID = ap.PatientClassID + AND src.PayorID = ap.PayorID + AND src.FinancialReportingID = ap.FinancialReportingID + AND src.FiscalYearID = ap.FiscalYearID + AND src.FiscalMonthID = ap.FiscalMonthID + WHERE ap.TimeClassID = 2 + + ------------------------------------------------------------------------------------------------------- + -- D-09168 : CCF: Data not flowing through into reports + -- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the + -- targeting above. This is a short term solution until we can get a more performant solution. + -- + -- NOTE: This is not a problem yet, since we don't have targeting, but I am squirreling this until + -- we add it so we don't re-introduce this bug. + -- + -- IMPORTANT NOTE: WHEN WE ADD TARGETING YOU NEED TO IMPLEMENT THIS WORKAROUND. GRAB THIS FROM THE + -- EXISTING PROCS AND UPDATE IT FOR THIS. + ------------------------------------------------------------------------------------------------------- + + IF (@IsDebug = 1) + BEGIN + SELECT '#SRC' AS TempTable, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, FiscalMonthID, FiscalYearID, FiscalTimeID, InitialUnits + FROM #SRC; + + SELECT '#statisticsSource' AS TempTable, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, FiscalTimeID, OriginalValue + FROM #statisticsSource + + RETURN + END + + -- Publish the data from the temp table to fp.FactReportingAP. This uses a merge statement to handle inserts and updates + -- In the event that the active configuration changes, we need to clear out this table because we only hold data for the active configuration. This is done from the UI itself. + -- We don't do any deletes from the reporting table because we have multiple sources going into it at a given time. In the future if we + -- needed to do a delete for some reason, we would need to combine them all into one MEGA proc which is gross and nasty. Since we don't delete data, this shouldn't be an issue + ;WITH TGT AS + ( + SELECT EntityID, FRS.DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, FiscalMonthID, FiscalYearID, FiscalTimeID, InitialUnits + FROM [fp].[FactReportingAP] FRS + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = FRS.DepartmentID + ) + MERGE TGT AS target + USING #SRC AS source + ON ( + target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.AccountID = source.AccountID + AND target.PatientClassID = source.PatientClassID + AND target.PayorID = source.PayorID + AND target.FinancialReportingID = source.FinancialReportingID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + AND target.FiscalTimeID = source.FiscalTimeID + ) + WHEN MATCHED AND + ( + target.InitialUnits <> source.InitialUnits + ) + THEN + UPDATE SET + target.InitialUnits = ISNULL(source.InitialUnits, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + EntityID, + DepartmentID, + AccountID, + PatientClassID, + PayorID, + FinancialReportingID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID, + InitialUnits + ) + VALUES ( + source.EntityID, + source.DepartmentID, + source.AccountID, + source.PatientClassID, + source.PayorID, + source.FinancialReportingID, + source.FiscalMonthID, + source.FiscalYearID, + source.FiscalTimeID, + ISNULL(source.InitialUnits, 0) + ); + +END +GO + + +--------------------------------------------- + +-- fp.procFactStatisticsToReportingTransfer +CREATE PROCEDURE fp.procFactStatisticsToReportingTransfer + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +WITH RECOMPILE +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2020-07-24 MY JAZZ-2849 Initial Creation + ** 2 2022-06-15 MY JAZZ-38632 Add Targeting + ** 3 11-28-2022 MY JAZZ-43418 Add FiscalTimeID to Update + ** 5 2023-02-23 MY JAZZ-49629 Handing zeroing out for AA data marts + *************************************************************/ + + -- IMPORTANT NOTE: This proc is only used to transfer data from AP to fp.FactReportingAP. + -- This new proc and table are only used in the new advanced analytics solution that leverages + -- snowflake. This proc will transfer data to fp.FactReportingAP, where SQL will then replicate + -- to Snowflake. + -- + -- More information can be found here: https://confluence.sdt.local/display/DD/Advanced+Analytics + + SET NOCOUNT ON; + + EXEC [dbo].[procSysDropTempTable] '#SRC' + EXEC [dbo].[procSysDropTempTable] '#statisticsSource' + EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment' + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM [fp].[BudgetConfig] WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[FactStatistics] d WITH (READUNCOMMITTED) + WHERE BudgetConfigID = @BudgetConfigID + END + + CREATE TABLE #SRC ( + BudgetConfigID INT, + EntityID INT, + DepartmentID INT, + AccountID INT, + PatientClassID INT, + PayorID INT, + FinancialReportingID INT, + FiscalMonthID TINYINT, + FiscalYearID SMALLINT, + FiscalTimeID INT, + BudgetUnits DECIMAL(19, 8) DEFAULT(0), + ProjectedUnits DECIMAL(19, 8) DEFAULT(0), + TargetUnits DECIMAL(19, 8) DEFAULT(0) + ) + + SELECT + EntityID, + VW.DepartmentID, + AccountID, + PatientClassID, + PayorID, + FinancialReportingID, + UnitTypeID, + TimeClassID, + VW.FiscalMonthID, + VW.FiscalYearID, + FiscalTimeID, + OriginalValue, + Value, + ManagerValue + INTO #statisticsSource + FROM [fp].[viewFactStatistics_Unpivoted_source] VW -- This view is SLOOOOOOOOOOW, so trying to speed this up by only using this once. + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = VW.DepartmentID + INNER JOIN fw.DimFiscalTime dft ON VW.FiscalYearID = dft.FiscalYearID + AND VW.FiscalMonthID = dft.FiscalMonthID + WHERE VW.BudgetConfigID = @BudgetConfigID + AND (Value != 0 OR ManagerValue != 0) + + CREATE CLUSTERED INDEX inx_stat ON #statisticsSource ( + TimeClassID, + EntityID, + DepartmentID, + AccountID, + PatientClassID, + PayorID, + FinancialReportingID, + FiscalMonthID, + FiscalYearID + ) + + -- Populate the dimensionality first + INSERT INTO #SRC (EntityID, VW.DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, FiscalMonthID, FiscalYearID, FiscalTimeID) + SELECT DISTINCT + EntityID, + VW.DepartmentID, + AccountID, + PatientClassID, + PayorID, + FinancialReportingID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + FROM #statisticsSource VW + + CREATE CLUSTERED INDEX inx_src ON #SRC ( + EntityID, + DepartmentID, + AccountID, + PatientClassID, + PayorID, + FinancialReportingID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID + ) + + -- Updating each column individually because we can't necessarily do it all in one update. This is because the Src table has unit type and time class on columns not rows. + -- Case statements wouldn't work in this case because we only want to update certain columns when it meets certain criteria. IE: you wouldn't want to do TargetDollars = CASE WHEN ap.TimeClassID = 2 THEN ap.Value ELSE 0 END + -- because then when it hits a row that doesn't match that, it's gonna set the target to 0. + + -- Update Budget/Target Units + UPDATE src + SET + BudgetUnits = ap.ManagerValue, + TargetUnits = ap.Value + FROM #SRC src + INNER JOIN #statisticsSource ap ON + src.EntityID = ap.EntityID + AND src.DepartmentID = ap.DepartmentID + AND src.AccountID = ap.AccountID + AND src.PatientClassID = ap.PatientClassID + AND src.PayorID = ap.PayorID + AND src.FinancialReportingID = ap.FinancialReportingID + AND src.FiscalYearID = ap.FiscalYearID + AND src.FiscalMonthID = ap.FiscalMonthID + WHERE ap.TimeClassID = 2 + + -- Update Projected Units + UPDATE src + SET + ProjectedUnits = ap.Value + FROM #SRC src + INNER JOIN #statisticsSource ap ON + src.EntityID = ap.EntityID + AND src.DepartmentID = ap.DepartmentID + AND src.AccountID = ap.AccountID + AND src.PatientClassID = ap.PatientClassID + AND src.PayorID = ap.PayorID + AND src.FinancialReportingID = ap.FinancialReportingID + AND src.FiscalYearID = ap.FiscalYearID + AND src.FiscalMonthID = ap.FiscalMonthID + WHERE ap.TimeClassID = 12 + + IF (@IsDebug = 1) + BEGIN + SELECT '#SRC' AS TempTable, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, FiscalMonthID, FiscalYearID, FiscalTimeID, BudgetUnits, ProjectedUnits, TargetUnits + FROM #SRC; + + SELECT '#statisticsSource' AS TempTable, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, TimeClassID, FiscalMonthID, FiscalYearID, FiscalTimeID, OriginalValue, Value, ManagerValue + FROM #statisticsSource + + RETURN + END + + -- Publish the data from the temp table to fp.FactReportingAP. This uses a merge statement to handle inserts and updates + -- In the event that the active configuration changes, we need to clear out this table because we only hold data for the active configuration. This is done from the UI itself. + -- We don't do any deletes from the reporting table because we have multiple sources going into it at a given time. In the future if we + -- needed to do a delete for some reason, we would need to combine them all into one MEGA proc which is gross and nasty. Since we don't delete data, this shouldn't be an issue + ;WITH TGT AS + ( + SELECT EntityID, FRS.DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, FiscalMonthID, FiscalYearID, BudgetUnits, ProjectedUnits, TargetUnits, FiscalTimeID + FROM [fp].[FactReportingAP] FRS + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = FRS.DepartmentID + ) + MERGE TGT AS target + USING #SRC AS source + ON ( + target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.AccountID = source.AccountID + AND target.PatientClassID = source.PatientClassID + AND target.PayorID = source.PayorID + AND target.FinancialReportingID = source.FinancialReportingID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + AND target.FiscalTimeID = source.FiscalTimeID + ) + WHEN MATCHED AND + ( + target.BudgetUnits <> source.BudgetUnits + OR target.ProjectedUnits <> source.ProjectedUnits + OR target.TargetUnits <> source.TargetUnits + ) + THEN + UPDATE SET + target.BudgetUnits = ISNULL(source.BudgetUnits, 0), + target.ProjectedUnits = ISNULL(source.ProjectedUnits, 0), + target.TargetUnits = ISNULL(source.TargetUnits, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + EntityID, + DepartmentID, + AccountID, + PatientClassID, + PayorID, + FinancialReportingID, + FiscalMonthID, + FiscalYearID, + FiscalTimeID, + BudgetUnits, + ProjectedUnits, + TargetUnits + ) + VALUES ( + source.EntityID, + source.DepartmentID, + source.AccountID, + source.PatientClassID, + source.PayorID, + source.FinancialReportingID, + source.FiscalMonthID, + source.FiscalYearID, + source.FiscalTimeID, + ISNULL(source.BudgetUnits, 0), + ISNULL(source.ProjectedUnits, 0), + ISNULL(source.TargetUnits, 0) + ); + + ------------------------------------------------------------------------------------------------------- + -- JAZZ-49629 : Handing zeroing out for AA data marts + -- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the + -- targeting above. + ------------------------------------------------------------------------------------------------------- + + -- Get all records that were adjusted + SELECT DISTINCT chg.StatisticsID + INTO #adjustedRecords + FROM [fp].[StatisticsChangeHistory] chg + INNER JOIN [fp].[FactStatistics] fgl ON chg.StatisticsID = fgl.StatisticsID + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fgl.DepartmentID + WHERE chg.BudgetConfigID = @BudgetConfigID + + SELECT + EntityID, + VW.DepartmentID, + AccountID, + PatientClassID, + PayorID, + FinancialReportingID, + UnitTypeID, + TimeClassID, + VW.FiscalMonthID, + VW.FiscalYearID, + Value, + ManagerValue + INTO #tempUnpivoted + FROM [fp].[viewFactStatistics_Unpivoted_source] VW -- This view is SLOOOOOOOOOOW, so trying to speed this up by only using this once. + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = VW.DepartmentID + INNER JOIN #adjustedRecords adj ON VW.StatisticsID = adj.StatisticsID + INNER JOIN fp.BudgetConfig bc ON VW.BudgetConfigID = bc.BudgetConfigID + WHERE VW.BudgetConfigID = @BudgetConfigID + AND UnitTypeID = 140 -- Units + AND ( + (VW.FiscalYearID = bc.FiscalYearID AND VW.TimeClassID = 2) + OR (VW.FiscalYearID = bc.FiscalYearID - 1 AND VW.TimeClassID = 12) + ) + AND ( + (VW.TimeClassID = 2 AND (Value = 0 OR ManagerValue = 0)) + OR (VW.TimeClassID = 12 AND Value = 0) + ) + + -- Find the records that need to be updated by comparing the source to the reporting table + SELECT + frgl.RowID, + cv.Value, + cv.ManagerValue + INTO #dataToUpdate_Budgeted + FROM [fp].[FactReportingAP] frgl + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = frgl.DepartmentID + INNER JOIN #tempUnpivoted cv ON + cv.EntityID = frgl.EntityID + AND cv.DepartmentID = frgl.DepartmentID + AND cv.AccountID = frgl.AccountID + AND cv.PatientClassID = frgl.PatientClassID + AND cv.PayorID = frgl.PayorID + AND cv.FinancialReportingID = frgl.FinancialReportingID + AND cv.FiscalYearID = frgl.FiscalYearID + AND cv.FiscalMonthID = frgl.FiscalMonthID + WHERE 1 = 1 + AND cv.TimeClassID = 2 + AND ( + cv.ManagerValue != frgl.BudgetUnits + OR cv.Value != frgl.TargetUnits + ) + + SELECT + frgl.RowID, + cv.Value + INTO #dataToUpdate_Projected + FROM [fp].[FactReportingAP] frgl + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = frgl.DepartmentID + INNER JOIN #tempUnpivoted cv ON + cv.EntityID = frgl.EntityID + AND cv.DepartmentID = frgl.DepartmentID + AND cv.AccountID = frgl.AccountID + AND cv.PatientClassID = frgl.PatientClassID + AND cv.PayorID = frgl.PayorID + AND cv.FinancialReportingID = frgl.FinancialReportingID + AND cv.FiscalYearID = frgl.FiscalYearID + AND cv.FiscalMonthID = frgl.FiscalMonthID + WHERE 1 = 1 + AND cv.TimeClassID = 12 + AND cv.Value != frgl.ProjectedUnits + + -- Update the records + UPDATE report + SET + report.BudgetUnits = upd.ManagerValue, + report.TargetUnits = upd.Value + FROM [fp].[FactReportingAP] report + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID + INNER JOIN #dataToUpdate_Budgeted upd ON upd.RowID = report.RowID + WHERE 1 = 1 + AND ( + report.TargetUnits != upd.Value + OR report.BudgetUnits != upd.ManagerValue + ) + + UPDATE report + SET + report.ProjectedUnits = upd.Value + FROM [fp].[FactReportingAP] report + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = report.DepartmentID + INNER JOIN #dataToUpdate_Projected upd ON upd.RowID = report.RowID + WHERE 1 = 1 + AND report.ProjectedUnits != upd.Value + +END +GO + + +--------------------------------------------- + +-- fp.procFindAdvancedPlanningPerformanceFlaws +CREATE PROCEDURE [fp].[procFindAdvancedPlanningPerformanceFlaws] + @SchemaName NVARCHAR(10) = '', -- Provide the schema you wish to check + @SpecificObj NVARCHAR(1000) = '' -- If you are looking for a specific object, specify it here, otherwise the entire schema will be checked +AS +BEGIN + + /* + Script Owner: Mike Y. + + Script Notes: + - This is not a performant script, so ignore the amount of cursors, can always tweak it later + - There are false positives, will work on trying to narrow that down as we use this + - Will add more checks as time goes on. + + Left to do: + - Use Search Arguments ( will look /search for table scan at SQL level in Perf Env as a first step) + - Avoid using table variables, cursors or function calls that evaluate each row in where clause + + Change Log: + 08/15/2019 - Initial + */ + + SET NOCOUNT ON; + IF OBJECT_ID('tempdb.dbo.#objects') IS NOT NULL + DROP TABLE #objects + + CREATE TABLE #Results ( + Name NVARCHAR(MAX), + ObjectType NVARCHAR(MAX), + Severity SMALLINT, + Category NVARCHAR(MAX), + Description NVARCHAR(MAX) + ) + + SELECT * + INTO #objects + FROM [sys].[objects] + WHERE type IN ('U', 'P', 'V') -- https://docs.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-objects-transact-sql?view=sql-server-2017 + AND schema_id = SCHEMA_ID(@SchemaName) + AND (@SpecificObj = '' OR object_id = OBJECT_ID(@SchemaName + '.' + @SpecificObj)) + + IF ((SELECT COUNT(*) FROM #objects) = 0) + BEGIN + SELECT @SchemaName + '.' + @SpecificObj + ' was not found in this database' AS Error + RETURN; + END + + -- Rule 1 do not join on source dimensionality + CREATE TABLE #TargetingJoin ( + Name NVARCHAR(MAX), + ObjectType NVARCHAR(MAX) + ) + + -- Rule 2 do not join with Department IS NULL + CREATE TABLE #DepartmentNull ( + Name NVARCHAR(MAX), + ObjectType NVARCHAR(MAX) + ) + + -- Loop through any procs + DECLARE @ObjectId INT, + @SchemaId INT, + @Type NVARCHAR(MAX) + + DECLARE crsObjs CURSOR FAST_FORWARD FOR SELECT Object_Id, Schema_Id, Type_Desc FROM #objects WHERE Type != 'U' + OPEN crsObjs + FETCH NEXT FROM crsObjs INTO @ObjectId, @SchemaId, @Type + DECLARE @sql NVARCHAR(MAX) + WHILE (@@fetch_status = 0) + BEGIN + SELECT @sql = OBJECT_DEFINITION(@ObjectId) + + INSERT INTO #Results (Name, ObjectType, Category, Description, Severity) + SELECT SCHEMA_NAME(@SchemaId) + '.' + OBJECT_NAME(@ObjectId), @Type, Category, Description, Severity FROM [fp].[funcFindTSQLPerformanceFlaws_AdvancedPlanning](@sql); + + FETCH next FROM crsObjs INTO @ObjectId, @SchemaId, @Type + + END + CLOSE crsObjs + DEALLOCATE crsObjs + + DECLARE @TableName NVARCHAR(MAX); + + -- Populate results tables + + -- Severity + -- 3 - High + -- 2 - Medium + -- 1 - Low + + SELECT Name, CASE WHEN Severity = 3 THEN 'High' + WHEN Severity = 2 THEN 'Medium' + WHEN Severity = 1 THEN 'Low' ELSE 'N/A' END AS Severity, + ObjectType, Category, Description + FROM #Results + ORDER BY Name, Category, ObjectType + +END +GO + + +--------------------------------------------- + +-- fp.procFlexDeductionsByGrossCharges +/************************************************************** +** Change History +************************************************************** +** 1 2019-03-08 IP B-22295 Removed using table variables, small optimizations +** 2 2019-03-14 IP TK-71351 Fixed crash of [fp].[procFlexDeductionsByGrossCharges] because of missing table #flexed +** 3 2019-03-14 IP TK-71378 Fixed crash of budgeting engine because of returning debug info [fp].[procFlexDeductionsByGrossCharges] (removed debug info) +** 4 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table +** 5 2019-08-20 MY TK-77476 Short circuted flexing if there is nothing to flex +** 6 2020-04-15 NN D-09426 Fix Change History during flexing +** 7 2022-09-07 NT JAZZ-40956 Include all gross charges accounts and not just variable revenue accounts when calculating percent of charges +** 8 2023-08-03 NT JAZZ-58154 Data restructure changes +** 9 2023-08-22 MY JAZZ-58154 procGLApplyRate fix for Restructure +*************************************************************/ +CREATE PROCEDURE [fp].[procFlexDeductionsByGrossCharges] + @EntityGroupConfigID int, + @MonthsLoaded int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 + AS + BEGIN + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF OBJECT_ID('tempdb..#itemsToFlex') IS NOT NULL DROP TABLE #itemsToFlex + IF OBJECT_ID('tempdb..#budget_basisIDs') IS NOT NULL DROP TABLE #budget_basisIDs + IF OBJECT_ID('tempdb..#projection_basisIDs') IS NOT NULL DROP TABLE #projection_basisIDs + IF OBJECT_ID('tempdb..#Filter') IS NOT NULL DROP TABLE #Filter + IF OBJECT_ID('tempdb..#flexed') IS NOT NULL DROP TABLE #flexed + + CREATE TABLE #itemsToFlex(DepartmentID int, GLAccountID int) + CREATE TABLE #budget_basisIDs (GeneralLedgerID INT); + CREATE TABLE #projection_basisIDs (GeneralLedgerID INT); + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #itemsToFlex(DepartmentID, GLAccountID) + SELECT DISTINCT fsc.DepartmentID, fsc.GLAccountID + FROM [fp].[GeneralLedger] gl + INNER JOIN [fp].[FlexConfigMapping] fsc ON fsc.DepartmentID = gl.DepartmentID AND fsc.GLAccountID = gl.AccountID + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fsc.DepartmentID + WHERE fsc.FlexingTypeID = 6 -- Deductions + AND fsc.EntityGroupConfigID = @EntityGroupConfigID + AND gl.EntityGroupConfigID = @EntityGroupConfigID + END ELSE BEGIN + INSERT INTO #itemsToFlex(DepartmentID, GLAccountID) + SELECT DISTINCT fsc.DepartmentID, fsc.GLAccountID + FROM [fp].[GeneralLedger] gl + INNER JOIN [fp].[FlexConfigMapping] fsc ON fsc.DepartmentID = gl.DepartmentID AND fsc.GLAccountID = gl.AccountID + WHERE fsc.FlexingTypeID = 6 -- Deductions + AND fsc.EntityGroupConfigID = @EntityGroupConfigID + AND gl.EntityGroupConfigID = @EntityGroupConfigID + END + + DECLARE @BudgetConfigID INT + SELECT @BudgetConfigID = BudgetConfigID + FROM fp.EntityGroupConfig egc INNER JOIN fp.BudgetConfig b on egc.BudgetConfigGUID = b.BudgetConfigGUID + WHERE egc.EntityGroupConfigID = @EntityGroupConfigID + + DECLARE @IncludeAllGrossChargesFlag BIT = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting WHERE Name = 'Include All Gross Charges Accounts' AND BudgetConfigID = @BudgetConfigID), 0) + + --grossOrPercent -> 1 = gross charges, 2 = Percent of charges + SELECT EntityGroupConfigID = @EntityGroupConfigID, + APEModelSectionID = 1, + CASE WHEN @IncludeAllGrossChargesFlag = 1 THEN null ELSE 2 END AS VariabilityID, --we will only include variable revenue accounts if the FF is off + DepartmentID, + null as Account, + 1 as grossOrPercent + INTO #Filter + from #itemsToFlex + UNION + SELECT EntityGroupConfigID = @EntityGroupConfigID, + APEModelSectionID = 4, + VariabilityID = 2, -- we only include variable deduction accounts for rate + DepartmentID, + GLAccountID, + 2 as grossOrPercent + from #itemsToFlex + + IF ((SELECT COUNT(*) FROM #itemsToFlex) = 0) + BEGIN + RETURN -- There were no results so no need to proceed + END + + SELECT x.* + INTO #flexed + FROM ( + SELECT + gl.GeneralLedgerID, gl.VariabilityID, + SUM(CASE WHEN grossOrPercent = 1 THEN TargetAdjusted01 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted01 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue01, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted02 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted02 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue02, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted03 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted03 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue03, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted04 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted04 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue04, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted05 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted05 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue05, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted06 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted06 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue06, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted07 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted07 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue07, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted08 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted08 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue08, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted09 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted09 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue09, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted10 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted10 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue10, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted11 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted11 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue11, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.TargetAdjusted12 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.TargetPercentOfChargeAdjusted12 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedTargetValue12, + + SUM(CASE WHEN grossOrPercent = 1 THEN BudgetAdjusted01 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted01 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue01, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted02 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted02 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue02, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted03 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted03 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue03, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted04 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted04 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue04, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted05 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted05 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue05, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted06 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted06 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue06, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted07 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted07 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue07, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted08 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted08 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue08, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted09 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted09 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue09, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted10 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted10 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue10, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted11 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted11 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue11, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.BudgetAdjusted12 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.BudgetPercentOfChargeAdjusted12 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedBudgetValue12, + + SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted01 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted01 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue01, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted02 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted02 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue02, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted03 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted03 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue03, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted04 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted04 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue04, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted05 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted05 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue05, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted06 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted06 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue06, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted07 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted07 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue07, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted08 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted08 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue08, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted09 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted09 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue09, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted10 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted10 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue10, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted11 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted11 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue11, + SUM(CASE WHEN grossOrPercent = 1 THEN gl.ProjectionAdjusted12 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID)*SUM(CASE WHEN grossOrPercent = 2 THEN gl.ProjectionPercentOfChargeAdjusted12 ELSE 0 END) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) As FlexedProjectionValue12, + MAX(F.DepartmentID) OVER (PARTITION BY gl.DepartmentID) AS DeptFilter, + MAX(F.Account) OVER (PARTITION BY gl.DepartmentID,gl.AccountID) AS AccFilter + FROM [fp].[GeneralLedger] gl WITH(NOLOCK) + INNER JOIN #Filter F ON F.APEModelSectionID = gl.APEModelSectionID + AND F.DepartmentID = gl.DepartmentID + AND ISNULL(F.Account, gl.AccountID) = gl.AccountID + AND gl.EntityGroupConfigID = F.EntityGroupConfigID + AND ISNULL(F.VariabilityID, gl.VariabilityID) = gl.VariabilityID + WHERE gl.EntityGroupConfigID = @EntityGroupConfigID + ) x + INNER JOIN #itemsToFlex itf on itf.DepartmentID = x.DeptFilter and itf.GLAccountID = x.AccFilter + AND x.VariabilityID = 2 --this is to make sure we only flex variable deductions + ORDER BY GeneralLedgerID + + IF (@IsDebug = 0) + BEGIN + + UPDATE basis + SET TargetAdjusted01 = FlexedTargetValue01 * TargetPercentAdjustmentFactor01, + TargetAdjusted02 = FlexedTargetValue02 * TargetPercentAdjustmentFactor02, + TargetAdjusted03 = FlexedTargetValue03 * TargetPercentAdjustmentFactor03, + TargetAdjusted04 = FlexedTargetValue04 * TargetPercentAdjustmentFactor04, + TargetAdjusted05 = FlexedTargetValue05 * TargetPercentAdjustmentFactor05, + TargetAdjusted06 = FlexedTargetValue06 * TargetPercentAdjustmentFactor06, + TargetAdjusted07 = FlexedTargetValue07 * TargetPercentAdjustmentFactor07, + TargetAdjusted08 = FlexedTargetValue08 * TargetPercentAdjustmentFactor08, + TargetAdjusted09 = FlexedTargetValue09 * TargetPercentAdjustmentFactor09, + TargetAdjusted10 = FlexedTargetValue10 * TargetPercentAdjustmentFactor10, + TargetAdjusted11 = FlexedTargetValue11 * TargetPercentAdjustmentFactor11, + TargetAdjusted12 = FlexedTargetValue12 * TargetPercentAdjustmentFactor12, + + BudgetAdjusted01 = FlexedBudgetValue01 * BudgetPercentAdjustmentFactor01, + BudgetAdjusted02 = FlexedBudgetValue02 * BudgetPercentAdjustmentFactor02, + BudgetAdjusted03 = FlexedBudgetValue03 * BudgetPercentAdjustmentFactor03, + BudgetAdjusted04 = FlexedBudgetValue04 * BudgetPercentAdjustmentFactor04, + BudgetAdjusted05 = FlexedBudgetValue05 * BudgetPercentAdjustmentFactor05, + BudgetAdjusted06 = FlexedBudgetValue06 * BudgetPercentAdjustmentFactor06, + BudgetAdjusted07 = FlexedBudgetValue07 * BudgetPercentAdjustmentFactor07, + BudgetAdjusted08 = FlexedBudgetValue08 * BudgetPercentAdjustmentFactor08, + BudgetAdjusted09 = FlexedBudgetValue09 * BudgetPercentAdjustmentFactor09, + BudgetAdjusted10 = FlexedBudgetValue10 * BudgetPercentAdjustmentFactor10, + BudgetAdjusted11 = FlexedBudgetValue11 * BudgetPercentAdjustmentFactor11, + BudgetAdjusted12 = FlexedBudgetValue12 * BudgetPercentAdjustmentFactor12 + + OUTPUT + INSERTED.GeneralLedgerID + INTO + #budget_basisIDs (GeneralLedgerID) + FROM [fp].[GeneralLedger] basis + INNER JOIN #flexed flexed ON basis.GeneralLedgerID = flexed.GeneralLedgerID + WHERE ( basis.TargetAdjusted01 != flexed.FlexedTargetValue01 * TargetPercentAdjustmentFactor01 OR + basis.TargetAdjusted02 != flexed.FlexedTargetValue02 * TargetPercentAdjustmentFactor02 OR + basis.TargetAdjusted03 != flexed.FlexedTargetValue03 * TargetPercentAdjustmentFactor03 OR + basis.TargetAdjusted04 != flexed.FlexedTargetValue04 * TargetPercentAdjustmentFactor04 OR + basis.TargetAdjusted05 != flexed.FlexedTargetValue05 * TargetPercentAdjustmentFactor05 OR + basis.TargetAdjusted06 != flexed.FlexedTargetValue06 * TargetPercentAdjustmentFactor06 OR + basis.TargetAdjusted07 != flexed.FlexedTargetValue07 * TargetPercentAdjustmentFactor07 OR + basis.TargetAdjusted08 != flexed.FlexedTargetValue08 * TargetPercentAdjustmentFactor08 OR + basis.TargetAdjusted09 != flexed.FlexedTargetValue09 * TargetPercentAdjustmentFactor09 OR + basis.TargetAdjusted10 != flexed.FlexedTargetValue10 * TargetPercentAdjustmentFactor10 OR + basis.TargetAdjusted11 != flexed.FlexedTargetValue11 * TargetPercentAdjustmentFactor11 OR + basis.TargetAdjusted12 != flexed.FlexedTargetValue12 * TargetPercentAdjustmentFactor12 OR + + basis.BudgetAdjusted01 != flexed.FlexedBudgetValue01 * BudgetPercentAdjustmentFactor01 OR + basis.BudgetAdjusted02 != flexed.FlexedBudgetValue02 * BudgetPercentAdjustmentFactor02 OR + basis.BudgetAdjusted03 != flexed.FlexedBudgetValue03 * BudgetPercentAdjustmentFactor03 OR + basis.BudgetAdjusted04 != flexed.FlexedBudgetValue04 * BudgetPercentAdjustmentFactor04 OR + basis.BudgetAdjusted05 != flexed.FlexedBudgetValue05 * BudgetPercentAdjustmentFactor05 OR + basis.BudgetAdjusted06 != flexed.FlexedBudgetValue06 * BudgetPercentAdjustmentFactor06 OR + basis.BudgetAdjusted07 != flexed.FlexedBudgetValue07 * BudgetPercentAdjustmentFactor07 OR + basis.BudgetAdjusted08 != flexed.FlexedBudgetValue08 * BudgetPercentAdjustmentFactor08 OR + basis.BudgetAdjusted09 != flexed.FlexedBudgetValue09 * BudgetPercentAdjustmentFactor09 OR + basis.BudgetAdjusted10 != flexed.FlexedBudgetValue10 * BudgetPercentAdjustmentFactor10 OR + basis.BudgetAdjusted11 != flexed.FlexedBudgetValue11 * BudgetPercentAdjustmentFactor11 OR + basis.BudgetAdjusted12 != flexed.FlexedBudgetValue12 * BudgetPercentAdjustmentFactor12) + + UPDATE basis + SET basis.ProjectionAdjusted01 = CASE WHEN @MonthsLoaded >= 1 THEN basis.ProjectionAdjusted01 ELSE flexed.FlexedProjectionValue01 * ProjectionPercentAdjustmentFactor01 END, + basis.ProjectionAdjusted02 = CASE WHEN @MonthsLoaded >= 2 THEN basis.ProjectionAdjusted02 ELSE flexed.FlexedProjectionValue02 * ProjectionPercentAdjustmentFactor02 END, + basis.ProjectionAdjusted03 = CASE WHEN @MonthsLoaded >= 3 THEN basis.ProjectionAdjusted03 ELSE flexed.FlexedProjectionValue03 * ProjectionPercentAdjustmentFactor03 END, + basis.ProjectionAdjusted04 = CASE WHEN @MonthsLoaded >= 4 THEN basis.ProjectionAdjusted04 ELSE flexed.FlexedProjectionValue04 * ProjectionPercentAdjustmentFactor04 END, + basis.ProjectionAdjusted05 = CASE WHEN @MonthsLoaded >= 5 THEN basis.ProjectionAdjusted05 ELSE flexed.FlexedProjectionValue05 * ProjectionPercentAdjustmentFactor05 END, + basis.ProjectionAdjusted06 = CASE WHEN @MonthsLoaded >= 6 THEN basis.ProjectionAdjusted06 ELSE flexed.FlexedProjectionValue06 * ProjectionPercentAdjustmentFactor06 END, + basis.ProjectionAdjusted07 = CASE WHEN @MonthsLoaded >= 7 THEN basis.ProjectionAdjusted07 ELSE flexed.FlexedProjectionValue07 * ProjectionPercentAdjustmentFactor07 END, + basis.ProjectionAdjusted08 = CASE WHEN @MonthsLoaded >= 8 THEN basis.ProjectionAdjusted08 ELSE flexed.FlexedProjectionValue08 * ProjectionPercentAdjustmentFactor08 END, + basis.ProjectionAdjusted09 = CASE WHEN @MonthsLoaded >= 9 THEN basis.ProjectionAdjusted09 ELSE flexed.FlexedProjectionValue09 * ProjectionPercentAdjustmentFactor09 END, + basis.ProjectionAdjusted10 = CASE WHEN @MonthsLoaded >= 10 THEN basis.ProjectionAdjusted10 ELSE flexed.FlexedProjectionValue10 * ProjectionPercentAdjustmentFactor10 END, + basis.ProjectionAdjusted11 = CASE WHEN @MonthsLoaded >= 11 THEN basis.ProjectionAdjusted11 ELSE flexed.FlexedProjectionValue11 * ProjectionPercentAdjustmentFactor11 END, + basis.ProjectionAdjusted12 = CASE WHEN @MonthsLoaded >= 12 THEN basis.ProjectionAdjusted12 ELSE flexed.FlexedProjectionValue12 * ProjectionPercentAdjustmentFactor12 END + OUTPUT + INSERTED.GeneralLedgerID + INTO #projection_basisIDs (GeneralLedgerID) + FROM [fp].[GeneralLedger] basis + INNER JOIN #flexed flexed ON basis.GeneralLEdgerID = flexed.GeneralLedgerID + WHERE + (basis.ProjectionAdjusted01 != CASE WHEN @MonthsLoaded >= 1 THEN basis.ProjectionAdjusted01 ELSE flexed.FlexedProjectionValue01 * ProjectionPercentAdjustmentFactor01 END OR + basis.ProjectionAdjusted02 != CASE WHEN @MonthsLoaded >= 2 THEN basis.ProjectionAdjusted02 ELSE flexed.FlexedProjectionValue02 * ProjectionPercentAdjustmentFactor02 END OR + basis.ProjectionAdjusted03 != CASE WHEN @MonthsLoaded >= 3 THEN basis.ProjectionAdjusted03 ELSE flexed.FlexedProjectionValue03 * ProjectionPercentAdjustmentFactor03 END OR + basis.ProjectionAdjusted04 != CASE WHEN @MonthsLoaded >= 4 THEN basis.ProjectionAdjusted04 ELSE flexed.FlexedProjectionValue04 * ProjectionPercentAdjustmentFactor04 END OR + basis.ProjectionAdjusted05 != CASE WHEN @MonthsLoaded >= 5 THEN basis.ProjectionAdjusted05 ELSE flexed.FlexedProjectionValue05 * ProjectionPercentAdjustmentFactor05 END OR + basis.ProjectionAdjusted06 != CASE WHEN @MonthsLoaded >= 6 THEN basis.ProjectionAdjusted06 ELSE flexed.FlexedProjectionValue06 * ProjectionPercentAdjustmentFactor06 END OR + basis.ProjectionAdjusted07 != CASE WHEN @MonthsLoaded >= 7 THEN basis.ProjectionAdjusted07 ELSE flexed.FlexedProjectionValue07 * ProjectionPercentAdjustmentFactor07 END OR + basis.ProjectionAdjusted08 != CASE WHEN @MonthsLoaded >= 8 THEN basis.ProjectionAdjusted08 ELSE flexed.FlexedProjectionValue08 * ProjectionPercentAdjustmentFactor08 END OR + basis.ProjectionAdjusted09 != CASE WHEN @MonthsLoaded >= 9 THEN basis.ProjectionAdjusted09 ELSE flexed.FlexedProjectionValue09 * ProjectionPercentAdjustmentFactor09 END OR + basis.ProjectionAdjusted10 != CASE WHEN @MonthsLoaded >= 10 THEN basis.ProjectionAdjusted10 ELSE flexed.FlexedProjectionValue10 * ProjectionPercentAdjustmentFactor10 END OR + basis.ProjectionAdjusted11 != CASE WHEN @MonthsLoaded >= 11 THEN basis.ProjectionAdjusted11 ELSE flexed.FlexedProjectionValue11 * ProjectionPercentAdjustmentFactor11 END OR + basis.ProjectionAdjusted12 != CASE WHEN @MonthsLoaded >= 12 THEN basis.ProjectionAdjusted12 ELSE flexed.FlexedProjectionValue12 * ProjectionPercentAdjustmentFactor12 END) + + + -- returns the info on the rows that were flexed in order to fix the change history + SELECT bdg.GeneralLedgerID, m.FiscalMonthID, CAST(2 AS TINYINT) AS BudgetPhaseID, CAST(2 AS TINYINT) AS TimeClassID, CrossApplied.Value + FROM #budget_basisIDs ids + INNER JOIN [fp].[GeneralLedger] bdg ON ids.GeneralLedgerID = bdg.GeneralLedgerID + CROSS APPLY ( + VALUES + (TargetAdjusted01, 1), + (TargetAdjusted02, 2), + (TargetAdjusted03, 3), + (TargetAdjusted04, 4), + (TargetAdjusted05, 5), + (TargetAdjusted06, 6), + (TargetAdjusted07, 7), + (TargetAdjusted08, 8), + (TargetAdjusted09, 9), + (TargetAdjusted10, 10), + (TargetAdjusted11, 11), + (TargetAdjusted12, 12) + ) CrossApplied (Value, MonthSortOrder) + INNER JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder + UNION ALL + SELECT bdg.GeneralLedgerID, m.FiscalMonthID, CAST(3 AS TINYINT) AS BudgetPhaseID, CAST(2 AS TINYINT) AS TimeClassID, CrossApplied.Value + FROM #budget_basisIDs ids + INNER JOIN [fp].[GeneralLedger] bdg ON ids.GeneralLedgerID = bdg.GeneralLedgerID + CROSS APPLY ( + VALUES + (BudgetAdjusted01, 1), + (BudgetAdjusted02, 2), + (BudgetAdjusted03, 3), + (BudgetAdjusted04, 4), + (BudgetAdjusted05, 5), + (BudgetAdjusted06, 6), + (BudgetAdjusted07, 7), + (BudgetAdjusted08, 8), + (BudgetAdjusted09, 9), + (BudgetAdjusted10, 10), + (BudgetAdjusted11, 11), + (BudgetAdjusted12, 12) + ) CrossApplied (Value, MonthSortOrder) + INNER JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder + UNION ALL + SELECT proj.GeneralLedgerID, m.FiscalMonthID, CAST(3 AS TINYINT) AS BudgetPhaseID, CAST(12 AS TINYINT) AS TimeClassID, CrossApplied.Value + FROM #projection_basisIDs ids + INNER JOIN [fp].[GeneralLedger] proj ON ids.GeneralLedgerID = proj.GeneralLedgerID + CROSS APPLY ( + VALUES + (ProjectionAdjusted01, 1), + (ProjectionAdjusted02, 2), + (ProjectionAdjusted03, 3), + (ProjectionAdjusted04, 4), + (ProjectionAdjusted05, 5), + (ProjectionAdjusted06, 6), + (ProjectionAdjusted07, 7), + (ProjectionAdjusted08, 8), + (ProjectionAdjusted09, 9), + (ProjectionAdjusted10, 10), + (ProjectionAdjusted11, 11), + (ProjectionAdjusted12, 12) + ) CrossApplied (Value, MonthSortOrder) + INNER JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder + + END ELSE BEGIN + SELECT 'ItemsToFlex', * FROM #itemsToFlex + SELECT 'Filter', * FROM #filter + SELECT 'Flexed', * FROM #flexed + END + END +GO + + +--------------------------------------------- + +-- fp.procFlexDeductionsByGrossCharges_InitialValue +CREATE PROCEDURE [fp].[procFlexDeductionsByGrossCharges_InitialValue] + @EntityGroupConfigID int, + @MonthsLoaded int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 + AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table + ** 2 2021-04-13 NN JAZZ-14121 Remove null joins on targeting + ** 3 2022-09-07 NT JAZZ-40956 Include all gross charges accounts and not just variable revenue accounts when calculating percent of charges + ** 4 8-2-2023 NT JAZZ-58154 Data restructure changes + *************************************************************/ + BEGIN + CREATE TABLE #itemsToFlex(DepartmentID int, GLAccountID int) + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[GeneralLedger] gl WITH (READUNCOMMITTED) + where gl.EntityGroupConfigID = @EntityGroupConfigID + END + + -- populate a temp + INSERT INTO #itemsToFlex(DepartmentID, GLAccountID) + SELECT DISTINCT fsc.DepartmentID, fsc.GLAccountID + FROM [fp].[GeneralLedger] gl + INNER JOIN [fp].[FlexConfigMapping] fsc ON fsc.DepartmentID = gl.DepartmentID AND fsc.GLAccountID = gl.AccountID + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fsc.DepartmentID + WHERE fsc.FlexingTypeID = 6 -- Deductions + AND fsc.EntityGroupConfigID = @EntityGroupConfigID + AND gl.EntityGroupConfigID = @EntityGroupConfigID + + DECLARE @BudgetConfigID INT + SELECT @BudgetConfigID = BudgetConfigID + FROM fp.EntityGroupConfig egc INNER JOIN fp.BudgetConfig b on egc.BudgetConfigGUID = b.BudgetConfigGUID + WHERE egc.EntityGroupConfigID = @EntityGroupConfigID + + DECLARE @IncludeAllGrossChargesFlag BIT = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting WHERE Name = 'Include All Gross Charges Accounts' AND BudgetConfigID = @BudgetConfigID), 0) + + SELECT + fgl.DepartmentID, + SUM(fgl.InitialBudget01) AS BudgetValue01, + SUM(fgl.InitialBudget02) AS BudgetValue02, + SUM(fgl.InitialBudget03) AS BudgetValue03, + SUM(fgl.InitialBudget04) AS BudgetValue04, + SUM(fgl.InitialBudget05) AS BudgetValue05, + SUM(fgl.InitialBudget06) AS BudgetValue06, + SUM(fgl.InitialBudget07) AS BudgetValue07, + SUM(fgl.InitialBudget08) AS BudgetValue08, + SUM(fgl.InitialBudget09) AS BudgetValue09, + SUM(fgl.InitialBudget10) AS BudgetValue10, + SUM(fgl.InitialBudget11) AS BudgetValue11, + SUM(fgl.InitialBudget12) AS BudgetValue12, + SUM(fgl.InitialProjection01) AS ProjectionValue01, + SUM(fgl.InitialProjection02) AS ProjectionValue02, + SUM(fgl.InitialProjection03) AS ProjectionValue03, + SUM(fgl.InitialProjection04) AS ProjectionValue04, + SUM(fgl.InitialProjection05) AS ProjectionValue05, + SUM(fgl.InitialProjection06) AS ProjectionValue06, + SUM(fgl.InitialProjection07) AS ProjectionValue07, + SUM(fgl.InitialProjection08) AS ProjectionValue08, + SUM(fgl.InitialProjection09) AS ProjectionValue09, + SUM(fgl.InitialProjection10) AS ProjectionValue10, + SUM(fgl.InitialProjection11) AS ProjectionValue11, + SUM(fgl.InitialProjection12) AS ProjectionValue12 + INTO #grossCharges + FROM [fp].[GeneralLedger] fgl WITH(NOLOCK) + INNER JOIN (SELECT DISTINCT DepartmentID FROM #itemsToFlex) flex ON fgl.DepartmentID = flex.DepartmentID + WHERE + fgl.EntityGroupConfigID = @EntityGroupConfigID + AND fgl.APEModelSectionID = 1 -- Revenue + AND (@IncludeAllGrossChargesFlag = 1 OR fgl.VariabilityID = 2) + GROUP BY fgl.DepartmentID + + SELECT + fgl.DepartmentID, + fgl.AccountID, + SUM(fgl.InitialBudgetPercentOfCharge01) AS BudgetValue01, + SUM(fgl.InitialBudgetPercentOfCharge02) AS BudgetValue02, + SUM(fgl.InitialBudgetPercentOfCharge03) AS BudgetValue03, + SUM(fgl.InitialBudgetPercentOfCharge04) AS BudgetValue04, + SUM(fgl.InitialBudgetPercentOfCharge05) AS BudgetValue05, + SUM(fgl.InitialBudgetPercentOfCharge06) AS BudgetValue06, + SUM(fgl.InitialBudgetPercentOfCharge07) AS BudgetValue07, + SUM(fgl.InitialBudgetPercentOfCharge08) AS BudgetValue08, + SUM(fgl.InitialBudgetPercentOfCharge09) AS BudgetValue09, + SUM(fgl.InitialBudgetPercentOfCharge10) AS BudgetValue10, + SUM(fgl.InitialBudgetPercentOfCharge11) AS BudgetValue11, + SUM(fgl.InitialBudgetPercentOfCharge12) AS BudgetValue12, + SUM(fgl.InitialProjectionPercentOfCharge01) AS ProjectionValue01, + SUM(fgl.InitialProjectionPercentOfCharge02) AS ProjectionValue02, + SUM(fgl.InitialProjectionPercentOfCharge03) AS ProjectionValue03, + SUM(fgl.InitialProjectionPercentOfCharge04) AS ProjectionValue04, + SUM(fgl.InitialProjectionPercentOfCharge05) AS ProjectionValue05, + SUM(fgl.InitialProjectionPercentOfCharge06) AS ProjectionValue06, + SUM(fgl.InitialProjectionPercentOfCharge07) AS ProjectionValue07, + SUM(fgl.InitialProjectionPercentOfCharge08) AS ProjectionValue08, + SUM(fgl.InitialProjectionPercentOfCharge09) AS ProjectionValue09, + SUM(fgl.InitialProjectionPercentOfCharge10) AS ProjectionValue10, + SUM(fgl.InitialProjectionPercentOfCharge11) AS ProjectionValue11, + SUM(fgl.InitialProjectionPercentOfCharge12) AS ProjectionValue12 + INTO #percentOfCharges + FROM [fp].[GeneralLedger] fgl WITH(NOLOCK) + INNER JOIN #itemsToFlex flex ON fgl.DepartmentID = flex.DepartmentID AND fgl.AccountID = flex.GLAccountID + WHERE + fgl.EntityGroupConfigID = @EntityGroupConfigID + AND fgl.APEModelSectionID = 4 -- Deductions + AND fgl.VariabilityID = 2 + GROUP BY fgl.DepartmentID, fgl.AccountID + + SELECT poc.DepartmentID, poc.AccountID, + SUM(poc.BudgetValue01 * charges.BudgetValue01) As FlexedBudgetValue01, + SUM(poc.BudgetValue02 * charges.BudgetValue02) As FlexedBudgetValue02, + SUM(poc.BudgetValue03 * charges.BudgetValue03) As FlexedBudgetValue03, + SUM(poc.BudgetValue04 * charges.BudgetValue04) As FlexedBudgetValue04, + SUM(poc.BudgetValue05 * charges.BudgetValue05) As FlexedBudgetValue05, + SUM(poc.BudgetValue06 * charges.BudgetValue06) As FlexedBudgetValue06, + SUM(poc.BudgetValue07 * charges.BudgetValue07) As FlexedBudgetValue07, + SUM(poc.BudgetValue08 * charges.BudgetValue08) As FlexedBudgetValue08, + SUM(poc.BudgetValue09 * charges.BudgetValue09) As FlexedBudgetValue09, + SUM(poc.BudgetValue10 * charges.BudgetValue10) As FlexedBudgetValue10, + SUM(poc.BudgetValue11 * charges.BudgetValue11) As FlexedBudgetValue11, + SUM(poc.BudgetValue12 * charges.BudgetValue12) As FlexedBudgetValue12, + SUM(poc.ProjectionValue01 * charges.ProjectionValue01) As FlexedProjectionValue01, + SUM(poc.ProjectionValue02 * charges.ProjectionValue02) As FlexedProjectionValue02, + SUM(poc.ProjectionValue03 * charges.ProjectionValue03) As FlexedProjectionValue03, + SUM(poc.ProjectionValue04 * charges.ProjectionValue04) As FlexedProjectionValue04, + SUM(poc.ProjectionValue05 * charges.ProjectionValue05) As FlexedProjectionValue05, + SUM(poc.ProjectionValue06 * charges.ProjectionValue06) As FlexedProjectionValue06, + SUM(poc.ProjectionValue07 * charges.ProjectionValue07) As FlexedProjectionValue07, + SUM(poc.ProjectionValue08 * charges.ProjectionValue08) As FlexedProjectionValue08, + SUM(poc.ProjectionValue09 * charges.ProjectionValue09) As FlexedProjectionValue09, + SUM(poc.ProjectionValue10 * charges.ProjectionValue10) As FlexedProjectionValue10, + SUM(poc.ProjectionValue11 * charges.ProjectionValue11) As FlexedProjectionValue11, + SUM(poc.ProjectionValue12 * charges.ProjectionValue12) As FlexedProjectionValue12 + INTO #flexed + FROM + #itemsToFlex fm + INNER JOIN #percentOfCharges poc ON poc.DepartmentID = fm.DepartmentID AND poc.AccountID = fm.GLAccountID + INNER JOIN #grossCharges charges ON poc.DepartmentID = charges.DepartmentID + GROUP BY poc.DepartmentID, poc.AccountID + + IF (@IsDebug = 0) + BEGIN + + UPDATE fgl + SET InitialBudget01 = FlexedBudgetValue01, + InitialBudget02 = FlexedBudgetValue02, + InitialBudget03 = FlexedBudgetValue03, + InitialBudget04 = FlexedBudgetValue04, + InitialBudget05 = FlexedBudgetValue05, + InitialBudget06 = FlexedBudgetValue06, + InitialBudget07 = FlexedBudgetValue07, + InitialBudget08 = FlexedBudgetValue08, + InitialBudget09 = FlexedBudgetValue09, + InitialBudget10 = FlexedBudgetValue10, + InitialBudget11 = FlexedBudgetValue11, + InitialBudget12 = FlexedBudgetValue12, + InitialProjection01 = CASE WHEN @MonthsLoaded >= 1 THEN InitialProjection01 ELSE flexed.FlexedProjectionValue01 END, + InitialProjection02 = CASE WHEN @MonthsLoaded >= 2 THEN InitialProjection02 ELSE flexed.FlexedProjectionValue02 END, + InitialProjection03 = CASE WHEN @MonthsLoaded >= 3 THEN InitialProjection03 ELSE flexed.FlexedProjectionValue03 END, + InitialProjection04 = CASE WHEN @MonthsLoaded >= 4 THEN InitialProjection04 ELSE flexed.FlexedProjectionValue04 END, + InitialProjection05 = CASE WHEN @MonthsLoaded >= 5 THEN InitialProjection05 ELSE flexed.FlexedProjectionValue05 END, + InitialProjection06 = CASE WHEN @MonthsLoaded >= 6 THEN InitialProjection06 ELSE flexed.FlexedProjectionValue06 END, + InitialProjection07 = CASE WHEN @MonthsLoaded >= 7 THEN InitialProjection07 ELSE flexed.FlexedProjectionValue07 END, + InitialProjection08 = CASE WHEN @MonthsLoaded >= 8 THEN InitialProjection08 ELSE flexed.FlexedProjectionValue08 END, + InitialProjection09 = CASE WHEN @MonthsLoaded >= 9 THEN InitialProjection09 ELSE flexed.FlexedProjectionValue09 END, + InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjection10 ELSE flexed.FlexedProjectionValue10 END, + InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjection11 ELSE flexed.FlexedProjectionValue11 END, + InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN InitialProjection12 ELSE flexed.FlexedProjectionValue12 END + FROM [fp].[GeneralLedger] fgl + INNER JOIN #itemsToFlex fm ON fm.DepartmentID = fgl.DepartmentID AND fm.GLAccountID = fgl.AccountID + LEFT JOIN #flexed flexed ON fgl.DepartmentID = flexed.DepartmentID AND fgl.AccountID = flexed.AccountID + WHERE fgl.VariabilityID = 2 + AND fgl.EntityGroupConfigID = @EntityGroupConfigID + AND (fgl.InitialBudget01 != flexed.FlexedBudgetValue01 OR + fgl.InitialBudget02 != flexed.FlexedBudgetValue02 OR + fgl.InitialBudget03 != flexed.FlexedBudgetValue03 OR + fgl.InitialBudget04 != flexed.FlexedBudgetValue04 OR + fgl.InitialBudget05 != flexed.FlexedBudgetValue05 OR + fgl.InitialBudget06 != flexed.FlexedBudgetValue06 OR + fgl.InitialBudget07 != flexed.FlexedBudgetValue07 OR + fgl.InitialBudget08 != flexed.FlexedBudgetValue08 OR + fgl.InitialBudget09 != flexed.FlexedBudgetValue09 OR + fgl.InitialBudget10 != flexed.FlexedBudgetValue10 OR + fgl.InitialBudget11 != flexed.FlexedBudgetValue11 OR + fgl.InitialBudget12 != flexed.FlexedBudgetValue12 OR + fgl.InitialProjection01 != flexed.FlexedProjectionValue01 OR + fgl.InitialProjection02 != flexed.FlexedProjectionValue02 OR + fgl.InitialProjection03 != flexed.FlexedProjectionValue03 OR + fgl.InitialProjection04 != flexed.FlexedProjectionValue04 OR + fgl.InitialProjection05 != flexed.FlexedProjectionValue05 OR + fgl.InitialProjection06 != flexed.FlexedProjectionValue06 OR + fgl.InitialProjection07 != flexed.FlexedProjectionValue07 OR + fgl.InitialProjection08 != flexed.FlexedProjectionValue08 OR + fgl.InitialProjection09 != flexed.FlexedProjectionValue09 OR + fgl.InitialProjection10 != flexed.FlexedProjectionValue10 OR + fgl.InitialProjection11 != flexed.FlexedProjectionValue11 OR + fgl.InitialProjection12 != flexed.FlexedProjectionValue12) + + END ELSE BEGIN + + SELECT 'ItemsToFlex', * FROM #itemsToFlex + SELECT 'GrossCharges', * FROM #grossCharges + SELECT 'PercentOfCharges', * FROM #percentOfCharges + SELECT 'Flexed', * FROM #flexed + + END + + END +GO + + +--------------------------------------------- + +-- fp.procFlexDependentByDriverStatistics +CREATE PROCEDURE [fp].[procFlexDependentByDriverStatistics] + @EntityGroupConfigID int, + @MonthsLoaded int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 + AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2020-12-16 MY JAZZ-11325 Initial + ** 2 2021-02-18 BK JAZZ-15007 Add distinct to fix flexing inflation problem + ** 3 2021-04-21 BK JAZZ-18500 Add ProviderID to flexing join + ** 4 2022-09-30 JB JAZZ-43489 Remove FlexedValue references + ** 5 2023-06-29 MY JAZZ-53442 Update stats flexing to support x-department stats flexing + ** 6 2023-02-29 MY JAZZ-68469 Cross Department Flexing Stats - Adjustments to source dept/acct + changing dependent rate rather than value + *************************************************************/ + + EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment' + EXEC [dbo].[procSysDropTempTable] '#itemsToFlex' + EXEC [dbo].[procSysDropTempTable] '#driverBudget' + EXEC [dbo].[procSysDropTempTable] '#budget_basisIDs' + EXEC [dbo].[procSysDropTempTable] '#projection_basisIDs' + EXEC [dbo].[procSysDropTempTable] '#budgetFlexed' + EXEC [dbo].[procSysDropTempTable] '#driverProjection' + EXEC [dbo].[procSysDropTempTable] '#dependentBudget' + EXEC [dbo].[procSysDropTempTable] '#dependentProjection' + EXEC [dbo].[procSysDropTempTable] '#projectionFlexed' + + DECLARE @BudgetConfigID INT = (SELECT DISTINCT TOP 1 BudgetConfigID + FROM fp.EntityGroupConfig egc + INNER JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE egc.EntityGroupConfigID = @EntityGroupConfigID) + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + DECLARE @Driver INT = (SELECT SubSectionID FROM [fp].[PlanSubsection] sub INNER JOIN [fp].[PlanSection] pe ON sub.PlanSectionID = pe.PlanSectionID WHERE pe.Description = 'Statistics' AND sub.Subsection = 'Driver'), + @Dependent INT = (SELECT SubSectionID FROM [fp].[PlanSubsection] sub INNER JOIN [fp].[PlanSection] pe ON sub.PlanSectionID = pe.PlanSectionID WHERE pe.Description = 'Statistics' AND sub.Subsection = 'Dependent') + + CREATE TABLE #itemsToFlex(DependentDepartmentID INT, DependentStatisticAccountID INT, + DriverDepartmentID INT, DriverStatisticAccountID INT) + + -- populate a temporary list of items to flex + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #itemsToFlex(DependentDepartmentID, DependentStatisticAccountID, DriverDepartmentID, DriverStatisticAccountID) + SELECT DISTINCT fsc.DepartmentID, fsc.DependentStatisticAccountID, fsc.SourceDepartmentID, fsc.StatAccountID + FROM [fp].[FlexConfigMapping] fsc + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fsc.DepartmentID + WHERE fsc.FlexingTypeID = 8 -- Stats by Stats + AND fsc.EntityGroupConfigID = @EntityGroupConfigID + END ELSE BEGIN + INSERT INTO #itemsToFlex(DependentDepartmentID, DependentStatisticAccountID, DriverDepartmentID, DriverStatisticAccountID) + SELECT DISTINCT fsc.DepartmentID, fsc.DependentStatisticAccountID, fsc.SourceDepartmentID, fsc.StatAccountID + FROM [fp].[FlexConfigMapping] fsc + WHERE fsc.FlexingTypeID = 8 -- Stats by Stats + AND fsc.EntityGroupConfigID = @EntityGroupConfigID + END + + CREATE TABLE #budget_basisIDs (StatisticsID INT, BudgetPhaseID INT); + CREATE TABLE #projection_basisIDs (StatisticsID INT, BudgetPhaseID INT); + + ------------------------------------------------------------------------- + -- Perform Budget Flexing + ------------------------------------------------------------------------- + SELECT + fcm.DependentDepartmentID AS DepartmentID, + fcm.DependentStatisticAccountID AS AccountID, + fs.ProviderID, + fsb.BudgetPhaseID, + SUM(fsb.AdjustedValue01) as NewValue01, + SUM(fsb.AdjustedValue02) as NewValue02, + SUM(fsb.AdjustedValue03) as NewValue03, + SUM(fsb.AdjustedValue04) as NewValue04, + SUM(fsb.AdjustedValue05) as NewValue05, + SUM(fsb.AdjustedValue06) as NewValue06, + SUM(fsb.AdjustedValue07) as NewValue07, + SUM(fsb.AdjustedValue08) as NewValue08, + SUM(fsb.AdjustedValue09) as NewValue09, + SUM(fsb.AdjustedValue10) as NewValue10, + SUM(fsb.AdjustedValue11) as NewValue11, + SUM(fsb.AdjustedValue12) as NewValue12 + into #driverBudget + FROM [fp].[FactStatistics] fs + INNER JOIN [fp].[FactStatisticsBudget] fsb ON fs.StatisticsID = fsb.StatisticsID + INNER JOIN #itemsToFlex fcm ON fs.DepartmentID = fcm.DriverDepartmentID AND fs.AccountID = fcm.DriverStatisticAccountID + WHERE fs.BudgetConfigID = @BudgetConfigID + AND fs.SubSectionID = @Driver + GROUP BY fcm.DependentDepartmentID, fcm.DependentStatisticAccountID, fs.ProviderID, fsb.BudgetPhaseID + + SELECT + fs.DepartmentID, + fs.AccountID, + fs.ProviderID, + fsb.BudgetPhaseID, + fsb.RateAdjustedValue01, + fsb.RateAdjustedValue02, + fsb.RateAdjustedValue03, + fsb.RateAdjustedValue04, + fsb.RateAdjustedValue05, + fsb.RateAdjustedValue06, + fsb.RateAdjustedValue07, + fsb.RateAdjustedValue08, + fsb.RateAdjustedValue09, + fsb.RateAdjustedValue10, + fsb.RateAdjustedValue11, + fsb.RateAdjustedValue12 + INTO #dependentBudget + FROM [fp].[FactStatistics] fs + INNER JOIN [fp].[FactStatisticsBudget] fsb on fs.StatisticsID = fsb.StatisticsID + INNER JOIN (SELECT DISTINCT DependentDepartmentID, DependentStatisticAccountID FROM #itemsToFlex) fcm ON fs.DepartmentID = fcm.DependentDepartmentID AND fs.AccountID = fcm.DependentStatisticAccountID -- We must do distinct here otherwise accounts flexed by multiple drivers would show up multiple times and skew the numbers + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.UnitTypeID = 140 + AND fs.SubSectionID = @Dependent + + SELECT + rate.DepartmentID, + rate.AccountID, + rate.ProviderID, + rate.BudgetPhaseID, + SUM(rate.RateAdjustedValue01 * stat.NewValue01) As FlexedValue01, + SUM(rate.RateAdjustedValue02 * stat.NewValue02) As FlexedValue02, + SUM(rate.RateAdjustedValue03 * stat.NewValue03) As FlexedValue03, + SUM(rate.RateAdjustedValue04 * stat.NewValue04) As FlexedValue04, + SUM(rate.RateAdjustedValue05 * stat.NewValue05) As FlexedValue05, + SUM(rate.RateAdjustedValue06 * stat.NewValue06) As FlexedValue06, + SUM(rate.RateAdjustedValue07 * stat.NewValue07) As FlexedValue07, + SUM(rate.RateAdjustedValue08 * stat.NewValue08) As FlexedValue08, + SUM(rate.RateAdjustedValue09 * stat.NewValue09) As FlexedValue09, + SUM(rate.RateAdjustedValue10 * stat.NewValue10) As FlexedValue10, + SUM(rate.RateAdjustedValue11 * stat.NewValue11) As FlexedValue11, + SUM(rate.RateAdjustedValue12 * stat.NewValue12) As FlexedValue12 + INTO #budgetFlexed + FROM #dependentBudget rate + INNER JOIN #driverBudget stat ON rate.AccountID = stat.AccountID + AND rate.DepartmentID = stat.DepartmentID + AND rate.BudgetPhaseID = stat.BudgetPhaseID + AND rate.ProviderID = stat.ProviderID + GROUP BY rate.DepartmentID, rate.AccountID, rate.ProviderID, rate.BudgetPhaseID + + IF (@IsDebug = 0) + BEGIN + + -- flex budget data and reset the adjusted value as well + UPDATE basis + SET + basis.AdjustedValue01 = dependentFlexed.FlexedValue01, + basis.AdjustedValue02 = dependentFlexed.FlexedValue02, + basis.AdjustedValue03 = dependentFlexed.FlexedValue03, + basis.AdjustedValue04 = dependentFlexed.FlexedValue04, + basis.AdjustedValue05 = dependentFlexed.FlexedValue05, + basis.AdjustedValue06 = dependentFlexed.FlexedValue06, + basis.AdjustedValue07 = dependentFlexed.FlexedValue07, + basis.AdjustedValue08 = dependentFlexed.FlexedValue08, + basis.AdjustedValue09 = dependentFlexed.FlexedValue09, + basis.AdjustedValue10 = dependentFlexed.FlexedValue10, + basis.AdjustedValue11 = dependentFlexed.FlexedValue11, + basis.AdjustedValue12 = dependentFlexed.FlexedValue12 + OUTPUT + INSERTED.StatisticsID, INSERTED.BudgetPhaseID + INTO + #budget_basisIDs (StatisticsID, BudgetPhaseID) + FROM [fp].[FactStatisticsBudget] basis + INNER JOIN [fp].[FactStatistics] fs on fs.StatisticsID = basis.StatisticsID + INNER JOIN #budgetFlexed dependentFlexed + ON fs.DepartmentID = dependentFlexed.DepartmentID + AND fs.AccountID = dependentFlexed.AccountID + AND fs.ProviderID = dependentFlexed.ProviderID + AND basis.BudgetPhaseID = dependentFlexed.BudgetPhaseID + WHERE fs.UnitTypeID = 140 + AND fs.EntityGroupConfigID = @EntityGroupConfigID + AND ( + basis.AdjustedValue01 != dependentFlexed.FlexedValue01 + OR basis.AdjustedValue02 != dependentFlexed.FlexedValue02 + OR basis.AdjustedValue03 != dependentFlexed.FlexedValue03 + OR basis.AdjustedValue04 != dependentFlexed.FlexedValue04 + OR basis.AdjustedValue05 != dependentFlexed.FlexedValue05 + OR basis.AdjustedValue06 != dependentFlexed.FlexedValue06 + OR basis.AdjustedValue07 != dependentFlexed.FlexedValue07 + OR basis.AdjustedValue08 != dependentFlexed.FlexedValue08 + OR basis.AdjustedValue09 != dependentFlexed.FlexedValue09 + OR basis.AdjustedValue10 != dependentFlexed.FlexedValue10 + OR basis.AdjustedValue11 != dependentFlexed.FlexedValue11 + OR basis.AdjustedValue12 != dependentFlexed.FlexedValue12 + ) + + END ELSE BEGIN + SELECT 'ItemsToFlex', * FROM #itemsToFlex + SELECT 'DependentBudget', * FROM #dependentBudget + SELECT 'DriverBudget', * FROM #driverBudget + SELECT 'BudgetFlexed', * FROM #budgetFlexed + END + + ------------------------------------------------------------------------- + -- Perform Projection Flexing + ------------------------------------------------------------------------- + SELECT + fcm.DependentDepartmentID AS DepartmentID, + fcm.DependentStatisticAccountID AS AccountID, + fs.ProviderID, + fsb.BudgetPhaseID, + SUM(fsb.AdjustedValue01) as NewValue01, + SUM(fsb.AdjustedValue02) as NewValue02, + SUM(fsb.AdjustedValue03) as NewValue03, + SUM(fsb.AdjustedValue04) as NewValue04, + SUM(fsb.AdjustedValue05) as NewValue05, + SUM(fsb.AdjustedValue06) as NewValue06, + SUM(fsb.AdjustedValue07) as NewValue07, + SUM(fsb.AdjustedValue08) as NewValue08, + SUM(fsb.AdjustedValue09) as NewValue09, + SUM(fsb.AdjustedValue10) as NewValue10, + SUM(fsb.AdjustedValue11) as NewValue11, + SUM(fsb.AdjustedValue12) as NewValue12 + into #driverProjection + FROM [fp].[FactStatistics] fs + INNER JOIN [fp].[FactStatisticsProjection] fsb ON fs.StatisticsID = fsb.StatisticsID + INNER JOIN #itemsToFlex fcm ON fs.DepartmentID = fcm.DriverDepartmentID AND fs.AccountID = fcm.DriverStatisticAccountID + WHERE fs.BudgetConfigID = @BudgetConfigID + AND fs.SubSectionID = @Driver + GROUP BY fcm.DependentDepartmentID, fcm.DependentStatisticAccountID, fs.ProviderID, fsb.BudgetPhaseID + + SELECT + fs.DepartmentID, + fs.AccountID, + fs.ProviderID, + fsb.BudgetPhaseID, + fsb.RateAdjustedValue01, + fsb.RateAdjustedValue02, + fsb.RateAdjustedValue03, + fsb.RateAdjustedValue04, + fsb.RateAdjustedValue05, + fsb.RateAdjustedValue06, + fsb.RateAdjustedValue07, + fsb.RateAdjustedValue08, + fsb.RateAdjustedValue09, + fsb.RateAdjustedValue10, + fsb.RateAdjustedValue11, + fsb.RateAdjustedValue12 + INTO #dependentProjection + FROM [fp].[FactStatistics] fs + INNER JOIN [fp].[FactStatisticsProjection] fsb on fs.StatisticsID = fsb.StatisticsID + INNER JOIN (SELECT DISTINCT DependentDepartmentID, DependentStatisticAccountID FROM #itemsToFlex) fcm ON fs.DepartmentID = fcm.DependentDepartmentID AND fs.AccountID = fcm.DependentStatisticAccountID -- We must do distinct here otherwise accounts flexed by multiple drivers would show up multiple times and skew the numbers + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.UnitTypeID = 140 + AND fs.SubSectionID = @Dependent + + SELECT + rate.DepartmentID, + rate.AccountID, + rate.ProviderID, + rate.BudgetPhaseID, + SUM(rate.RateAdjustedValue01 * stat.NewValue01) As FlexedValue01, + SUM(rate.RateAdjustedValue02 * stat.NewValue02) As FlexedValue02, + SUM(rate.RateAdjustedValue03 * stat.NewValue03) As FlexedValue03, + SUM(rate.RateAdjustedValue04 * stat.NewValue04) As FlexedValue04, + SUM(rate.RateAdjustedValue05 * stat.NewValue05) As FlexedValue05, + SUM(rate.RateAdjustedValue06 * stat.NewValue06) As FlexedValue06, + SUM(rate.RateAdjustedValue07 * stat.NewValue07) As FlexedValue07, + SUM(rate.RateAdjustedValue08 * stat.NewValue08) As FlexedValue08, + SUM(rate.RateAdjustedValue09 * stat.NewValue09) As FlexedValue09, + SUM(rate.RateAdjustedValue10 * stat.NewValue10) As FlexedValue10, + SUM(rate.RateAdjustedValue11 * stat.NewValue11) As FlexedValue11, + SUM(rate.RateAdjustedValue12 * stat.NewValue12) As FlexedValue12 + INTO #projectionFlexed + FROM #dependentProjection rate + INNER JOIN #driverProjection stat ON rate.AccountID = stat.AccountID + AND rate.DepartmentID = stat.DepartmentID + AND rate.BudgetPhaseID = stat.BudgetPhaseID + AND rate.ProviderID = stat.ProviderID + GROUP BY rate.DepartmentID, rate.AccountID, rate.ProviderID, rate.BudgetPhaseID + + -- flex projection data and reset the adjusted value as well + DECLARE @i int = @MonthsLoaded + 1 + DECLARE @MonthsLoadedString CHAR(10) + SELECT @MonthsLoadedString = CAST(@i as CHAR(2)); + + DECLARE @sql varchar(max) = 'UPDATE basis SET ' + WHILE (@i <= 12) + BEGIN + SET @sql = @sql + 'basis.AdjustedValue' + case when @i<10 then '0' else '' end +cast(@i as varchar(2))+' = dependentFlexed.FlexedValue' + case when @i<10 then '0' else '' end +cast(@i as varchar(2))+CASE WHEN @i<12 THEN ',' ELSE '' END + SET @i = @i+1 + END + SET @sql = @sql + ' + OUTPUT + INSERTED.StatisticsID, INSERTED.BudgetPhaseID + INTO + #projection_basisIDs (StatisticsID, BudgetPhaseID) + FROM [fp].[FactStatisticsProjection] basis + INNER JOIN [fp].[FactStatistics] fs on fs.StatisticsID = basis.StatisticsID + INNER JOIN #projectionFlexed dependentFlexed + ON fs.DepartmentID = dependentFlexed.DepartmentID + and fs.AccountID = dependentFlexed.AccountID + and fs.ProviderID = dependentFlexed.ProviderID + and basis.BudgetPhaseID = dependentFlexed.BudgetPhaseID + WHERE fs.UnitTypeID = 140 + AND fs.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS VARCHAR(10)) + ' + AND ((basis.AdjustedValue01 != dependentFlexed.FlexedValue01 AND ' + @MonthsLoadedString + ' <= 1 ) + OR (basis.AdjustedValue02 != dependentFlexed.FlexedValue02 AND ' + @MonthsLoadedString + ' <= 2 ) + OR (basis.AdjustedValue03 != dependentFlexed.FlexedValue03 AND ' + @MonthsLoadedString + ' <= 3 ) + OR (basis.AdjustedValue04 != dependentFlexed.FlexedValue04 AND ' + @MonthsLoadedString + ' <= 4 ) + OR (basis.AdjustedValue05 != dependentFlexed.FlexedValue05 AND ' + @MonthsLoadedString + ' <= 5 ) + OR (basis.AdjustedValue06 != dependentFlexed.FlexedValue06 AND ' + @MonthsLoadedString + ' <= 6 ) + OR (basis.AdjustedValue07 != dependentFlexed.FlexedValue07 AND ' + @MonthsLoadedString + ' <= 7 ) + OR (basis.AdjustedValue08 != dependentFlexed.FlexedValue08 AND ' + @MonthsLoadedString + ' <= 8 ) + OR (basis.AdjustedValue09 != dependentFlexed.FlexedValue09 AND ' + @MonthsLoadedString + ' <= 9 ) + OR (basis.AdjustedValue10 != dependentFlexed.FlexedValue10 AND ' + @MonthsLoadedString + ' <= 10 ) + OR (basis.AdjustedValue11 != dependentFlexed.FlexedValue11 AND ' + @MonthsLoadedString + ' <= 11 ) + OR (basis.AdjustedValue12 != dependentFlexed.FlexedValue12 AND ' + @MonthsLoadedString + ' <= 12 ) + ) + ' + + IF (@IsDebug = 0) + BEGIN + EXEC (@sql) + END ELSE BEGIN + PRINT @sql + SELECT 'ProjectionFlexed', * FROM #projectionFlexed + END + + IF (@IsDebug = 0) + BEGIN + -- returns the info on the rows that were flexed in order to fix the change history + SELECT DISTINCT StatisticsID + ,m.FiscalMonthID + ,BudgetPhaseID + ,TimeClassID + ,f.Value + FROM ( + SELECT bdgt.StatisticsID + ,bdgt.AdjustedValue01 + ,bdgt.AdjustedValue02 + ,bdgt.AdjustedValue03 + ,bdgt.AdjustedValue04 + ,bdgt.AdjustedValue05 + ,bdgt.AdjustedValue06 + ,bdgt.AdjustedValue07 + ,bdgt.AdjustedValue08 + ,bdgt.AdjustedValue09 + ,bdgt.AdjustedValue10 + ,bdgt.AdjustedValue11 + ,bdgt.AdjustedValue12 + ,bdgt.BudgetPhaseID + ,cast(2 AS TINYINT) AS TimeClassID + FROM #budget_basisIDs ids + INNER JOIN [fp].[FactStatisticsBudget] bdgt + ON ids.StatisticsID = bdgt.StatisticsID + AND ids.BudgetPhaseID = bdgt.BudgetPhaseID + UNION ALL + SELECT + bdgt.StatisticsID + ,bdgt.AdjustedValue01 + ,bdgt.AdjustedValue02 + ,bdgt.AdjustedValue03 + ,bdgt.AdjustedValue04 + ,bdgt.AdjustedValue05 + ,bdgt.AdjustedValue06 + ,bdgt.AdjustedValue07 + ,bdgt.AdjustedValue08 + ,bdgt.AdjustedValue09 + ,bdgt.AdjustedValue10 + ,bdgt.AdjustedValue11 + ,bdgt.AdjustedValue12 + ,bdgt.BudgetPhaseID + ,cast(12 AS TINYINT) AS TimeClassID + FROM #projection_basisIDs ids + INNER JOIN [fp].[FactStatisticsProjection] bdgt + ON ids.StatisticsID = bdgt.StatisticsID + AND ids.BudgetPhaseID = bdgt.BudgetPhaseID + ) gl + UNPIVOT(Value FOR FiscalMonth IN (AdjustedValue01,AdjustedValue02,AdjustedValue03,AdjustedValue04,AdjustedValue05,AdjustedValue06,AdjustedValue07,AdjustedValue08,AdjustedValue09,AdjustedValue10,AdjustedValue11,AdjustedValue12 )) AS f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month') + END ELSE BEGIN + SELECT '#budget_basisIDs', * FROM #budget_basisIDs + SELECT '#projection_basisIDs', * FROM #projection_basisIDs + END + END +GO + + +--------------------------------------------- + +-- fp.procFlexDependentByDriverStatistics_InitialValue +CREATE PROCEDURE [fp].[procFlexDependentByDriverStatistics_InitialValue] + @EntityGroupConfigID int, + @MonthsLoaded int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 + AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2020-12-16 MY JAZZ-11325 Initial + ** 2 2021-02-18 BK JAZZ-15007 Add distinct to fix flexing inflation problem + ** 3 2021-04-21 BK JAZZ-18500 Add ProviderID to flexing join + ** 4 2023-06-29 MY JAZZ-53442 Update stats flexing to support x-department stats flexing + ** 5 2023-02-29 MY JAZZ-68469 Cross Department Flexing Stats - Adjustments to source dept/acct + changing dependent rate rather than value + *************************************************************/ + + BEGIN + + EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment' + EXEC [dbo].[procSysDropTempTable] '#itemsToFlex' + EXEC [dbo].[procSysDropTempTable] '#flexedValues' + EXEC [dbo].[procSysDropTempTable] '#driver' + EXEC [dbo].[procSysDropTempTable] '#dependent' + EXEC [dbo].[procSysDropTempTable] '#driverDepartments' + EXEC [dbo].[procSysDropTempTable] '#dependentDepartments' + + DECLARE @BudgetConfigID INT = (SELECT DISTINCT TOP 1 BudgetConfigID + FROM fp.EntityGroupConfig egc + INNER JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE egc.EntityGroupConfigID = @EntityGroupConfigID) + + CREATE TABLE #FilterByDepartment (DepartmentID INT) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + DECLARE @Driver INT = (SELECT SubSectionID FROM [fp].[PlanSubsection] sub INNER JOIN [fp].[PlanSection] pe ON sub.PlanSectionID = pe.PlanSectionID WHERE pe.Description = 'Statistics' AND sub.Subsection = 'Driver'), + @Dependent INT = (SELECT SubSectionID FROM [fp].[PlanSubsection] sub INNER JOIN [fp].[PlanSection] pe ON sub.PlanSectionID = pe.PlanSectionID WHERE pe.Description = 'Statistics' AND sub.Subsection = 'Dependent') + + CREATE TABLE #itemsToFlex(DependentDepartmentID INT, DependentStatisticAccountID INT, DriverDepartmentID INT, DriverStatisticAccountID INT) + + -- populate a temporary list of items to flex + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #itemsToFlex (DependentDepartmentID, DependentStatisticAccountID, DriverDepartmentID, DriverStatisticAccountID) + SELECT DISTINCT fsc.DepartmentID, fsc.DependentStatisticAccountID, fsc.SourceDepartmentID, fsc.StatAccountID + FROM [fp].[FlexConfigMapping] fsc + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fsc.DepartmentID + WHERE fsc.FlexingTypeID = 8 -- Stats by Stats + AND fsc.EntityGroupConfigID = @EntityGroupConfigID + END ELSE BEGIN + INSERT INTO #itemsToFlex (DependentDepartmentID, DependentStatisticAccountID, DriverDepartmentID, DriverStatisticAccountID) + SELECT DISTINCT fsc.DepartmentID, fsc.DependentStatisticAccountID, fsc.SourceDepartmentID, fsc.StatAccountID + FROM [fp].[FlexConfigMapping] fsc + WHERE fsc.FlexingTypeID = 8 -- Stats by Stats + AND fsc.EntityGroupConfigID = @EntityGroupConfigID + END + + SELECT DISTINCT DriverDepartmentID + INTO #driverDepartments + FROM #itemsToFlex + + SELECT DISTINCT DependentDepartmentID + INTO #dependentDepartments + FROM #itemsToFlex + + SELECT + fs.DepartmentID, + fs.AccountID, + fs.ProviderID, + SUM(fs.InitialBudget01) AS NewBudgetValue01, + SUM(fs.InitialBudget02) AS NewBudgetValue02, + SUM(fs.InitialBudget03) AS NewBudgetValue03, + SUM(fs.InitialBudget04) AS NewBudgetValue04, + SUM(fs.InitialBudget05) AS NewBudgetValue05, + SUM(fs.InitialBudget06) AS NewBudgetValue06, + SUM(fs.InitialBudget07) AS NewBudgetValue07, + SUM(fs.InitialBudget08) AS NewBudgetValue08, + SUM(fs.InitialBudget09) AS NewBudgetValue09, + SUM(fs.InitialBudget10) AS NewBudgetValue10, + SUM(fs.InitialBudget11) AS NewBudgetValue11, + SUM(fs.InitialBudget12) AS NewBudgetValue12, + SUM(fs.InitialProjection01) AS NewProjectionValue01, + SUM(fs.InitialProjection02) AS NewProjectionValue02, + SUM(fs.InitialProjection03) AS NewProjectionValue03, + SUM(fs.InitialProjection04) AS NewProjectionValue04, + SUM(fs.InitialProjection05) AS NewProjectionValue05, + SUM(fs.InitialProjection06) AS NewProjectionValue06, + SUM(fs.InitialProjection07) AS NewProjectionValue07, + SUM(fs.InitialProjection08) AS NewProjectionValue08, + SUM(fs.InitialProjection09) AS NewProjectionValue09, + SUM(fs.InitialProjection10) AS NewProjectionValue10, + SUM(fs.InitialProjection11) AS NewProjectionValue11, + SUM(fs.InitialProjection12) AS NewProjectionValue12 + INTO #driver + FROM [fp].[FactStatistics] fs + INNER JOIN #driverDepartments driver ON fs.DepartmentID = driver.DriverDepartmentID + WHERE fs.BudgetConfigID = @BudgetConfigID + AND fs.SubSectionID = @Driver + GROUP BY fs.DepartmentID, fs.AccountID, fs.ProviderID + + SELECT + stat.DepartmentID, + stat.AccountID, + stat.ProviderID, + stat.InitialBudgetRate01, + stat.InitialBudgetRate02, + stat.InitialBudgetRate03, + stat.InitialBudgetRate04, + stat.InitialBudgetRate05, + stat.InitialBudgetRate06, + stat.InitialBudgetRate07, + stat.InitialBudgetRate08, + stat.InitialBudgetRate09, + stat.InitialBudgetRate10, + stat.InitialBudgetRate11, + stat.InitialBudgetRate12, + stat.InitialProjectionRate01, + stat.InitialProjectionRate02, + stat.InitialProjectionRate03, + stat.InitialProjectionRate04, + stat.InitialProjectionRate05, + stat.InitialProjectionRate06, + stat.InitialProjectionRate07, + stat.InitialProjectionRate08, + stat.InitialProjectionRate09, + stat.InitialProjectionRate10, + stat.InitialProjectionRate11, + stat.InitialProjectionRate12 + INTO #dependent + FROM [fp].[FactStatistics] stat + INNER JOIN #dependentDepartments depend ON stat.DepartmentID = depend.DependentDepartmentID + WHERE stat.EntityGroupConfigID = @EntityGroupConfigID + AND stat.SubSectionID = @Dependent + + SELECT dependent.DepartmentID, dependent.AccountID, dependent.ProviderID, + SUM(dependent.InitialBudgetRate01 * driver.NewBudgetValue01) As FlexedBudget01, + SUM(dependent.InitialBudgetRate02 * driver.NewBudgetValue02) As FlexedBudget02, + SUM(dependent.InitialBudgetRate03 * driver.NewBudgetValue03) As FlexedBudget03, + SUM(dependent.InitialBudgetRate04 * driver.NewBudgetValue04) As FlexedBudget04, + SUM(dependent.InitialBudgetRate05 * driver.NewBudgetValue05) As FlexedBudget05, + SUM(dependent.InitialBudgetRate06 * driver.NewBudgetValue06) As FlexedBudget06, + SUM(dependent.InitialBudgetRate07 * driver.NewBudgetValue07) As FlexedBudget07, + SUM(dependent.InitialBudgetRate08 * driver.NewBudgetValue08) As FlexedBudget08, + SUM(dependent.InitialBudgetRate09 * driver.NewBudgetValue09) As FlexedBudget09, + SUM(dependent.InitialBudgetRate10 * driver.NewBudgetValue10) As FlexedBudget10, + SUM(dependent.InitialBudgetRate11 * driver.NewBudgetValue11) As FlexedBudget11, + SUM(dependent.InitialBudgetRate12 * driver.NewBudgetValue12) As FlexedBudget12, + SUM(dependent.InitialProjectionRate01 * driver.NewProjectionValue01) As FlexedProjection01, + SUM(dependent.InitialProjectionRate02 * driver.NewProjectionValue02) As FlexedProjection02, + SUM(dependent.InitialProjectionRate03 * driver.NewProjectionValue03) As FlexedProjection03, + SUM(dependent.InitialProjectionRate04 * driver.NewProjectionValue04) As FlexedProjection04, + SUM(dependent.InitialProjectionRate05 * driver.NewProjectionValue05) As FlexedProjection05, + SUM(dependent.InitialProjectionRate06 * driver.NewProjectionValue06) As FlexedProjection06, + SUM(dependent.InitialProjectionRate07 * driver.NewProjectionValue07) As FlexedProjection07, + SUM(dependent.InitialProjectionRate08 * driver.NewProjectionValue08) As FlexedProjection08, + SUM(dependent.InitialProjectionRate09 * driver.NewProjectionValue09) As FlexedProjection09, + SUM(dependent.InitialProjectionRate10 * driver.NewProjectionValue10) As FlexedProjection10, + SUM(dependent.InitialProjectionRate11 * driver.NewProjectionValue11) As FlexedProjection11, + SUM(dependent.InitialProjectionRate12 * driver.NewProjectionValue12) As FlexedProjection12 + INTO #flexedValues + FROM + #itemsToFlex fm + INNER JOIN #dependent dependent ON dependent.DepartmentID = fm.DependentDepartmentID AND dependent.AccountID = fm.DependentStatisticAccountID + INNER JOIN #driver driver ON fm.DriverStatisticAccountID = driver.AccountID AND fm.DriverDepartmentID = driver.DepartmentID + WHERE driver.ProviderID = dependent.ProviderID + GROUP BY dependent.DepartmentID, dependent.AccountID, dependent.ProviderID + + IF (@IsDebug = 0) + BEGIN + + -- flex projection data and reset the adjusted value as well + UPDATE basis + SET + basis.InitialBudget01 = flexed.FlexedBudget01, + basis.InitialBudget02 = flexed.FlexedBudget02, + basis.InitialBudget03 = flexed.FlexedBudget03, + basis.InitialBudget04 = flexed.FlexedBudget04, + basis.InitialBudget05 = flexed.FlexedBudget05, + basis.InitialBudget06 = flexed.FlexedBudget06, + basis.InitialBudget07 = flexed.FlexedBudget07, + basis.InitialBudget08 = flexed.FlexedBudget08, + basis.InitialBudget09 = flexed.FlexedBudget09, + basis.InitialBudget10 = flexed.FlexedBudget10, + basis.InitialBudget11 = flexed.FlexedBudget11, + basis.InitialBudget12 = flexed.FlexedBudget12, + basis.InitialProjection01 = CASE WHEN @MonthsLoaded >= 1 THEN basis.InitialProjection01 ELSE flexed.FlexedProjection01 END, + basis.InitialProjection02 = CASE WHEN @MonthsLoaded >= 2 THEN basis.InitialProjection02 ELSE flexed.FlexedProjection02 END, + basis.InitialProjection03 = CASE WHEN @MonthsLoaded >= 3 THEN basis.InitialProjection03 ELSE flexed.FlexedProjection03 END, + basis.InitialProjection04 = CASE WHEN @MonthsLoaded >= 4 THEN basis.InitialProjection04 ELSE flexed.FlexedProjection04 END, + basis.InitialProjection05 = CASE WHEN @MonthsLoaded >= 5 THEN basis.InitialProjection05 ELSE flexed.FlexedProjection05 END, + basis.InitialProjection06 = CASE WHEN @MonthsLoaded >= 6 THEN basis.InitialProjection06 ELSE flexed.FlexedProjection06 END, + basis.InitialProjection07 = CASE WHEN @MonthsLoaded >= 7 THEN basis.InitialProjection07 ELSE flexed.FlexedProjection07 END, + basis.InitialProjection08 = CASE WHEN @MonthsLoaded >= 8 THEN basis.InitialProjection08 ELSE flexed.FlexedProjection08 END, + basis.InitialProjection09 = CASE WHEN @MonthsLoaded >= 9 THEN basis.InitialProjection09 ELSE flexed.FlexedProjection09 END, + basis.InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN basis.InitialProjection10 ELSE flexed.FlexedProjection10 END, + basis.InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN basis.InitialProjection11 ELSE flexed.FlexedProjection11 END, + basis.InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN basis.InitialProjection12 ELSE flexed.FlexedProjection12 END + FROM [fp].[FactStatistics] basis + INNER JOIN #flexedValues flexed + ON basis.DepartmentID = flexed.DepartmentID + and basis.AccountID = flexed.AccountID + and basis.ProviderID = flexed.ProviderID + WHERE basis.UnitTypeID = 140 + AND basis.EntityGroupConfigID = @EntityGroupConfigID + AND ( + basis.InitialBudget01 != flexed.FlexedBudget01 OR + basis.InitialBudget02 != flexed.FlexedBudget02 OR + basis.InitialBudget03 != flexed.FlexedBudget03 OR + basis.InitialBudget04 != flexed.FlexedBudget04 OR + basis.InitialBudget05 != flexed.FlexedBudget05 OR + basis.InitialBudget06 != flexed.FlexedBudget06 OR + basis.InitialBudget07 != flexed.FlexedBudget07 OR + basis.InitialBudget08 != flexed.FlexedBudget08 OR + basis.InitialBudget09 != flexed.FlexedBudget09 OR + basis.InitialBudget10 != flexed.FlexedBudget10 OR + basis.InitialBudget11 != flexed.FlexedBudget11 OR + basis.InitialBudget12 != flexed.FlexedBudget12 OR + basis.InitialProjection01 != flexed.FlexedProjection01 OR + basis.InitialProjection02 != flexed.FlexedProjection02 OR + basis.InitialProjection03 != flexed.FlexedProjection03 OR + basis.InitialProjection04 != flexed.FlexedProjection04 OR + basis.InitialProjection05 != flexed.FlexedProjection05 OR + basis.InitialProjection06 != flexed.FlexedProjection06 OR + basis.InitialProjection07 != flexed.FlexedProjection07 OR + basis.InitialProjection08 != flexed.FlexedProjection08 OR + basis.InitialProjection09 != flexed.FlexedProjection09 OR + basis.InitialProjection10 != flexed.FlexedProjection10 OR + basis.InitialProjection11 != flexed.FlexedProjection11 OR + basis.InitialProjection12 != flexed.FlexedProjection12) + + END ELSE BEGIN + SELECT '#driver', * FROM #driver + SELECT '#dependent', * FROM #dependent + SELECT '#FilterByDepartment', * FROM #FilterByDepartment + SELECT '#itemsToFlex', * FROM #itemsToFlex + SELECT '#flexedValues', * FROM #flexedValues + END +END +GO + + +--------------------------------------------- + +-- fp.procFlexNonStaffingByStatistics_InitialValue +CREATE PROCEDURE [fp].[procFlexNonStaffingByStatistics_InitialValue] + @EntityGroupConfigID int, + @MonthsLoaded int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 + AS + BEGIN + + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table + ** 2 2021-04-13 NN JAZZ-14121 Remove null joins on targeting + ** 3 2023-02-07 MY JAZZ-48980 Update flexing to support x-department flexing + ** 4 2023-08-09 BK JAZZ-58152 Update for new data structure + ** 5 2023-08-25 MY JAZZ-58152 Fix missed reference + *************************************************************/ + + -- Confluence: https://confluence.sdt.local/display/DD/Non-Staffing+Flexing+-+1 + + EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment' + EXEC [dbo].[procSysDropTempTable] '#itemsToFlex' + EXEC [dbo].[procSysDropTempTable] '#dollarPerUos' + EXEC [dbo].[procSysDropTempTable] '#stats' + EXEC [dbo].[procSysDropTempTable] '#flexed' + EXEC [dbo].[procSysDropTempTable] '#gl' + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[viewGeneralLedgerDataForStatsToNonStaffing] st WITH (READUNCOMMITTED) + WHERE st.EntityGroupConfigID = @EntityGroupConfigID + AND st.FlexingTypeID = 1 -- Non-Staffing + END + + CREATE TABLE #itemsToFlex (DepartmentID INT, GLAccountID INT, StatAccountID INT, SourceDepartmentID INT) + + -- populate a temporary list of items to flex + INSERT INTO #itemsToFlex(DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID) + SELECT fsc.DepartmentID, fsc.GLAccountID, fsc.StatAccountID, fsc.SourceDepartmentID + FROM [fp].[FlexConfigMapping] fsc + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fsc.DepartmentID + WHERE fsc.FlexingTypeID = 1 -- NonStaffing + AND fsc.EntityGroupConfigID = @EntityGroupConfigID + + CREATE TABLE #gl (GeneralLedgerID INT, DepartmentID INT, AccountID INT, + InitialBudget01 DECIMAL(19,8),InitialBudget02 DECIMAL(19,8),InitialBudget03 DECIMAL(19,8),InitialBudget04 DECIMAL(19,8),InitialBudget05 DECIMAL(19,8),InitialBudget06 DECIMAL(19,8), + InitialBudget07 DECIMAL(19,8),InitialBudget08 DECIMAL(19,8),InitialBudget09 DECIMAL(19,8),InitialBudget10 DECIMAL(19,8),InitialBudget11 DECIMAL(19,8),InitialBudget12 DECIMAL(19,8), + InitialProjection01 DECIMAL(19,8),InitialProjection02 DECIMAL(19,8),InitialProjection03 DECIMAL(19,8),InitialProjection04 DECIMAL(19,8),InitialProjection05 DECIMAL(19,8),InitialProjection06 DECIMAL(19,8), + InitialProjection07 DECIMAL(19,8),InitialProjection08 DECIMAL(19,8),InitialProjection09 DECIMAL(19,8),InitialProjection10 DECIMAL(19,8),InitialProjection11 DECIMAL(19,8),InitialProjection12 DECIMAL(19,8), + InitialBudgetDollarsPerUOS01 DECIMAL(19,8),InitialBudgetDollarsPerUOS02 DECIMAL(19,8),InitialBudgetDollarsPerUOS03 DECIMAL(19,8),InitialBudgetDollarsPerUOS04 DECIMAL(19,8),InitialBudgetDollarsPerUOS05 DECIMAL(19,8),InitialBudgetDollarsPerUOS06 DECIMAL(19,8), + InitialBudgetDollarsPerUOS07 DECIMAL(19,8),InitialBudgetDollarsPerUOS08 DECIMAL(19,8),InitialBudgetDollarsPerUOS09 DECIMAL(19,8),InitialBudgetDollarsPerUOS10 DECIMAL(19,8),InitialBudgetDollarsPerUOS11 DECIMAL(19,8),InitialBudgetDollarsPerUOS12 DECIMAL(19,8), + InitialProjectionDollarsPerUOS01 DECIMAL(19,8),InitialProjectionDollarsPerUOS02 DECIMAL(19,8),InitialProjectionDollarsPerUOS03 DECIMAL(19,8),InitialProjectionDollarsPerUOS04 DECIMAL(19,8),InitialProjectionDollarsPerUOS05 DECIMAL(19,8),InitialProjectionDollarsPerUOS06 DECIMAL(19,8), + InitialProjectionDollarsPerUOS07 DECIMAL(19,8),InitialProjectionDollarsPerUOS08 DECIMAL(19,8),InitialProjectionDollarsPerUOS09 DECIMAL(19,8),InitialProjectionDollarsPerUOS10 DECIMAL(19,8),InitialProjectionDollarsPerUOS11 DECIMAL(19,8),InitialProjectionDollarsPerUOS12 DECIMAL(19,8) + ); + + SELECT + GeneralLedgerID, + gl.DepartmentID, + AccountID, + InitialBudgetDollarsPerUOS01, + InitialBudgetDollarsPerUOS02, + InitialBudgetDollarsPerUOS03, + InitialBudgetDollarsPerUOS04, + InitialBudgetDollarsPerUOS05, + InitialBudgetDollarsPerUOS06, + InitialBudgetDollarsPerUOS07, + InitialBudgetDollarsPerUOS08, + InitialBudgetDollarsPerUOS09, + InitialBudgetDollarsPerUOS10, + InitialBudgetDollarsPerUOS11, + InitialBudgetDollarsPerUOS12, + InitialProjectionDollarsPerUOS01, + InitialProjectionDollarsPerUOS02, + InitialProjectionDollarsPerUOS03, + InitialProjectionDollarsPerUOS04, + InitialProjectionDollarsPerUOS05, + InitialProjectionDollarsPerUOS06, + InitialProjectionDollarsPerUOS07, + InitialProjectionDollarsPerUOS08, + InitialProjectionDollarsPerUOS09, + InitialProjectionDollarsPerUOS10, + InitialProjectionDollarsPerUOS11, + InitialProjectionDollarsPerUOS12 + INTO #dollarPerUos + FROM [fp].[GeneralLedger] gl + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = gl.DepartmentID + WHERE gl.EntityGroupConfigID = @EntityGroupConfigID + AND gl.VariabilityID = 2 + + -- Calculate the Stats for the Source Department/Stat Account combinations found in our flexing config + SELECT + fs.DepartmentID AS SourceDepartmentID, + fs.AccountID, + SUM(fs.InitialBudget01) as NewBudgetValue01, + SUM(fs.InitialBudget02) as NewBudgetValue02, + SUM(fs.InitialBudget03) as NewBudgetValue03, + SUM(fs.InitialBudget04) as NewBudgetValue04, + SUM(fs.InitialBudget05) as NewBudgetValue05, + SUM(fs.InitialBudget06) as NewBudgetValue06, + SUM(fs.InitialBudget07) as NewBudgetValue07, + SUM(fs.InitialBudget08) as NewBudgetValue08, + SUM(fs.InitialBudget09) as NewBudgetValue09, + SUM(fs.InitialBudget10) as NewBudgetValue10, + SUM(fs.InitialBudget11) as NewBudgetValue11, + SUM(fs.InitialBudget12) as NewBudgetValue12, + SUM(fs.InitialProjection01) as NewProjectionValue01, + SUM(fs.InitialProjection02) as NewProjectionValue02, + SUM(fs.InitialProjection03) as NewProjectionValue03, + SUM(fs.InitialProjection04) as NewProjectionValue04, + SUM(fs.InitialProjection05) as NewProjectionValue05, + SUM(fs.InitialProjection06) as NewProjectionValue06, + SUM(fs.InitialProjection07) as NewProjectionValue07, + SUM(fs.InitialProjection08) as NewProjectionValue08, + SUM(fs.InitialProjection09) as NewProjectionValue09, + SUM(fs.InitialProjection10) as NewProjectionValue10, + SUM(fs.InitialProjection11) as NewProjectionValue11, + SUM(fs.InitialProjection12) as NewProjectionValue12 + INTO #stats + FROM [fp].[FactStatistics] fs + INNER JOIN (SELECT DISTINCT SourceDepartmentID, StatAccountID FROM #itemsToFlex) fl ON fs.DepartmentID = fl.SourceDepartmentID AND fl.StatAccountID = fs.AccountID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + GROUP BY fs.DepartmentID, + fs.AccountID + + -- Calculate the stats at an individual flex config level. + SELECT + fs.DepartmentID, + fs.SourceDepartmentID, + fs.StatAccountID, + fs.GLAccountID, + SUM(NewBudgetValue01) AS NewBudgetValue01, + SUM(NewBudgetValue02) AS NewBudgetValue02, + SUM(NewBudgetValue03) AS NewBudgetValue03, + SUM(NewBudgetValue04) AS NewBudgetValue04, + SUM(NewBudgetValue05) AS NewBudgetValue05, + SUM(NewBudgetValue06) AS NewBudgetValue06, + SUM(NewBudgetValue07) AS NewBudgetValue07, + SUM(NewBudgetValue08) AS NewBudgetValue08, + SUM(NewBudgetValue09) AS NewBudgetValue09, + SUM(NewBudgetValue10) AS NewBudgetValue10, + SUM(NewBudgetValue11) AS NewBudgetValue11, + SUM(NewBudgetValue12) AS NewBudgetValue12, + SUM(NewProjectionValue01) AS NewProjectionValue01, + SUM(NewProjectionValue02) AS NewProjectionValue02, + SUM(NewProjectionValue03) AS NewProjectionValue03, + SUM(NewProjectionValue04) AS NewProjectionValue04, + SUM(NewProjectionValue05) AS NewProjectionValue05, + SUM(NewProjectionValue06) AS NewProjectionValue06, + SUM(NewProjectionValue07) AS NewProjectionValue07, + SUM(NewProjectionValue08) AS NewProjectionValue08, + SUM(NewProjectionValue09) AS NewProjectionValue09, + SUM(NewProjectionValue10) AS NewProjectionValue10, + SUM(NewProjectionValue11) AS NewProjectionValue11, + SUM(NewProjectionValue12) AS NewProjectionValue12 + INTO #statsBySourceDept + FROM #itemsToFlex fs + INNER JOIN #stats st ON fs.SourceDepartmentID = st.SourceDepartmentID AND fs.StatAccountID = st.AccountID + GROUP BY fs.DepartmentID, + fs.SourceDepartmentID, + fs.StatAccountID, + fs.GLAccountID + + -- Group all of the data together and flex them by taking the Stats * $/UOS + SELECT + uos.DepartmentID, + uos.AccountID, + SUM(uos.InitialBudgetDollarsPerUOS01 * stat.NewBudgetValue01) As FlexedBudget01, + SUM(uos.InitialBudgetDollarsPerUOS02 * stat.NewBudgetValue02) As FlexedBudget02, + SUM(uos.InitialBudgetDollarsPerUOS03 * stat.NewBudgetValue03) As FlexedBudget03, + SUM(uos.InitialBudgetDollarsPerUOS04 * stat.NewBudgetValue04) As FlexedBudget04, + SUM(uos.InitialBudgetDollarsPerUOS05 * stat.NewBudgetValue05) As FlexedBudget05, + SUM(uos.InitialBudgetDollarsPerUOS06 * stat.NewBudgetValue06) As FlexedBudget06, + SUM(uos.InitialBudgetDollarsPerUOS07 * stat.NewBudgetValue07) As FlexedBudget07, + SUM(uos.InitialBudgetDollarsPerUOS08 * stat.NewBudgetValue08) As FlexedBudget08, + SUM(uos.InitialBudgetDollarsPerUOS09 * stat.NewBudgetValue09) As FlexedBudget09, + SUM(uos.InitialBudgetDollarsPerUOS10 * stat.NewBudgetValue10) As FlexedBudget10, + SUM(uos.InitialBudgetDollarsPerUOS11 * stat.NewBudgetValue11) As FlexedBudget11, + SUM(uos.InitialBudgetDollarsPerUOS12 * stat.NewBudgetValue12) As FlexedBudget12, + SUM(uos.InitialProjectionDollarsPerUOS01 * stat.NewProjectionValue01) As FlexedProjection01, + SUM(uos.InitialProjectionDollarsPerUOS02 * stat.NewProjectionValue02) As FlexedProjection02, + SUM(uos.InitialProjectionDollarsPerUOS03 * stat.NewProjectionValue03) As FlexedProjection03, + SUM(uos.InitialProjectionDollarsPerUOS04 * stat.NewProjectionValue04) As FlexedProjection04, + SUM(uos.InitialProjectionDollarsPerUOS05 * stat.NewProjectionValue05) As FlexedProjection05, + SUM(uos.InitialProjectionDollarsPerUOS06 * stat.NewProjectionValue06) As FlexedProjection06, + SUM(uos.InitialProjectionDollarsPerUOS07 * stat.NewProjectionValue07) As FlexedProjection07, + SUM(uos.InitialProjectionDollarsPerUOS08 * stat.NewProjectionValue08) As FlexedProjection08, + SUM(uos.InitialProjectionDollarsPerUOS09 * stat.NewProjectionValue09) As FlexedProjection09, + SUM(uos.InitialProjectionDollarsPerUOS10 * stat.NewProjectionValue10) As FlexedProjection10, + SUM(uos.InitialProjectionDollarsPerUOS11 * stat.NewProjectionValue11) As FlexedProjection11, + SUM(uos.InitialProjectionDollarsPerUOS12 * stat.NewProjectionValue12) As FlexedProjection12 + INTO #flexed + FROM (SELECT DISTINCT f.DepartmentID, f.GLAccountID, f.StatAccountID FROM #itemsToFlex f) fm + INNER JOIN #dollarPerUos uos ON uos.DepartmentID = fm.DepartmentID AND uos.AccountID = fm.GLAccountID + INNER JOIN #statsBySourceDept stat ON fm.StatAccountID = stat.StatAccountID + AND fm.DepartmentID = stat.DepartmentID + AND uos.AccountID = stat.GLAccountID + GROUP BY uos.DepartmentID, + uos.AccountID + + IF @IsDebug = 1 + BEGIN + SELECT '#FilterByDepartment', * FROM #FilterByDepartment + SELECT '#itemsToFlex', * FROM #itemsToFlex + SELECT '#dollarPerUos', * FROM #dollarPerUos + SELECT '#stats', * FROM #stats + SELECT '#statsBySourceDept', * FROM #statsBySourceDept + SELECT '#flexed', * FROM #flexed + END ELSE + BEGIN + + -- flex projection data and reset the adjusted value as well + UPDATE basis + SET + basis.InitialBudget01 = abb.FlexedBudget01, + basis.InitialBudget02 = abb.FlexedBudget02, + basis.InitialBudget03 = abb.FlexedBudget03, + basis.InitialBudget04 = abb.FlexedBudget04, + basis.InitialBudget05 = abb.FlexedBudget05, + basis.InitialBudget06 = abb.FlexedBudget06, + basis.InitialBudget07 = abb.FlexedBudget07, + basis.InitialBudget08 = abb.FlexedBudget08, + basis.InitialBudget09 = abb.FlexedBudget09, + basis.InitialBudget10 = abb.FlexedBudget10, + basis.InitialBudget11 = abb.FlexedBudget11, + basis.InitialBudget12 = abb.FlexedBudget12, + basis.InitialProjection01 = CASE WHEN @MonthsLoaded >= 1 THEN basis.InitialProjection01 ELSE abb.FlexedProjection01 END, + basis.InitialProjection02 = CASE WHEN @MonthsLoaded >= 2 THEN basis.InitialProjection02 ELSE abb.FlexedProjection02 END, + basis.InitialProjection03 = CASE WHEN @MonthsLoaded >= 3 THEN basis.InitialProjection03 ELSE abb.FlexedProjection03 END, + basis.InitialProjection04 = CASE WHEN @MonthsLoaded >= 4 THEN basis.InitialProjection04 ELSE abb.FlexedProjection04 END, + basis.InitialProjection05 = CASE WHEN @MonthsLoaded >= 5 THEN basis.InitialProjection05 ELSE abb.FlexedProjection05 END, + basis.InitialProjection06 = CASE WHEN @MonthsLoaded >= 6 THEN basis.InitialProjection06 ELSE abb.FlexedProjection06 END, + basis.InitialProjection07 = CASE WHEN @MonthsLoaded >= 7 THEN basis.InitialProjection07 ELSE abb.FlexedProjection07 END, + basis.InitialProjection08 = CASE WHEN @MonthsLoaded >= 8 THEN basis.InitialProjection08 ELSE abb.FlexedProjection08 END, + basis.InitialProjection09 = CASE WHEN @MonthsLoaded >= 9 THEN basis.InitialProjection09 ELSE abb.FlexedProjection09 END, + basis.InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN basis.InitialProjection10 ELSE abb.FlexedProjection10 END, + basis.InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN basis.InitialProjection11 ELSE abb.FlexedProjection11 END, + basis.InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN basis.InitialProjection12 ELSE abb.FlexedProjection12 END + FROM [fp].[GeneralLedger] basis + INNER JOIN #flexed abb ON basis.DepartmentID = abb.DepartmentID AND basis.AccountID = abb.AccountID + WHERE basis.VariabilityID = 2 + AND basis.EntityGroupConfigID = @EntityGroupConfigID + AND ( + basis.InitialBudget01 != abb.FlexedBudget01 + OR basis.InitialBudget02 != abb.FlexedBudget02 + OR basis.InitialBudget03 != abb.FlexedBudget03 + OR basis.InitialBudget04 != abb.FlexedBudget04 + OR basis.InitialBudget05 != abb.FlexedBudget05 + OR basis.InitialBudget06 != abb.FlexedBudget06 + OR basis.InitialBudget07 != abb.FlexedBudget07 + OR basis.InitialBudget08 != abb.FlexedBudget08 + OR basis.InitialBudget09 != abb.FlexedBudget09 + OR basis.InitialBudget10 != abb.FlexedBudget10 + OR basis.InitialBudget11 != abb.FlexedBudget11 + OR basis.InitialBudget12 != abb.FlexedBudget12 + OR basis.InitialProjection01 != abb.FlexedProjection01 + OR basis.InitialProjection02 != abb.FlexedProjection02 + OR basis.InitialProjection03 != abb.FlexedProjection03 + OR basis.InitialProjection04 != abb.FlexedProjection04 + OR basis.InitialProjection05 != abb.FlexedProjection05 + OR basis.InitialProjection06 != abb.FlexedProjection06 + OR basis.InitialProjection07 != abb.FlexedProjection07 + OR basis.InitialProjection08 != abb.FlexedProjection08 + OR basis.InitialProjection09 != abb.FlexedProjection09 + OR basis.InitialProjection10 != abb.FlexedProjection10 + OR basis.InitialProjection11 != abb.FlexedProjection11 + OR basis.InitialProjection12 != abb.FlexedProjection12 + ) + + END + +END +GO + + +--------------------------------------------- + +-- fp.procFlexRevenueByStatistics_InitialValue +CREATE PROCEDURE [fp].[procFlexRevenueByStatistics_InitialValue] + @EntityGroupConfigID INT, + @MonthsLoaded INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug INT = 0 + AS + BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table + ** 2 2021-04-13 NN JAZZ-14121 Remove null joins on targeting + ** 3 2023-02-07 MY JAZZ-48980 Update flexing to support x-department flexing + ** 4 2023-08-01 MY JAZZ-58153 Update to new structure + *************************************************************/ + + -- Confluence: https://confluence.sdt.local/display/DD/Revenue+Flexing+-+2 + + EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment' + EXEC [dbo].[procSysDropTempTable] '#itemsToFlex' + EXEC [dbo].[procSysDropTempTable] '#dollarPerUosRates' + EXEC [dbo].[procSysDropTempTable] '#stats' + EXEC [dbo].[procSysDropTempTable] '#flexedValues' + + CREATE TABLE #FilterByDepartment (DepartmentID INT) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[GeneralLedger] st WITH (READUNCOMMITTED) + WHERE st.EntityGroupConfigID = @EntityGroupConfigID + AND st.FlexingTypeID = 2 -- Revenue + END + + CREATE TABLE #itemsToFlex(DepartmentID INT, GLAccountID INT, StatAccountID INT, SourceDepartmentID INT) + + -- populate a temporary list of items to flex + INSERT INTO #itemsToFlex(DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID) + SELECT fcm.DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID + FROM [fp].[FlexConfigMapping] fcm + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fcm.DepartmentID -- We only want to filter on the department being flexed, not the source departments + WHERE FlexingTypeID = 2 -- Revenue by Stats + AND EntityGroupConfigID = @EntityGroupConfigID + + -- Pull out the rates for GL + SELECT + GeneralLedgerID, + fgl.DepartmentID, + AccountID, + InitialBudgetDollarsPerUOS01 AS InitialBudget01, + InitialBudgetDollarsPerUOS02 AS InitialBudget02, + InitialBudgetDollarsPerUOS03 AS InitialBudget03, + InitialBudgetDollarsPerUOS04 AS InitialBudget04, + InitialBudgetDollarsPerUOS05 AS InitialBudget05, + InitialBudgetDollarsPerUOS06 AS InitialBudget06, + InitialBudgetDollarsPerUOS07 AS InitialBudget07, + InitialBudgetDollarsPerUOS08 AS InitialBudget08, + InitialBudgetDollarsPerUOS09 AS InitialBudget09, + InitialBudgetDollarsPerUOS10 AS InitialBudget10, + InitialBudgetDollarsPerUOS11 AS InitialBudget11, + InitialBudgetDollarsPerUOS12 AS InitialBudget12, + InitialProjectionDollarsPerUOS01 AS InitialProjection01, + InitialProjectionDollarsPerUOS02 AS InitialProjection02, + InitialProjectionDollarsPerUOS03 AS InitialProjection03, + InitialProjectionDollarsPerUOS04 AS InitialProjection04, + InitialProjectionDollarsPerUOS05 AS InitialProjection05, + InitialProjectionDollarsPerUOS06 AS InitialProjection06, + InitialProjectionDollarsPerUOS07 AS InitialProjection07, + InitialProjectionDollarsPerUOS08 AS InitialProjection08, + InitialProjectionDollarsPerUOS09 AS InitialProjection09, + InitialProjectionDollarsPerUOS10 AS InitialProjection10, + InitialProjectionDollarsPerUOS11 AS InitialProjection11, + InitialProjectionDollarsPerUOS12 AS InitialProjection12 + INTO #dollarPerUosRates + FROM [fp].[GeneralLedger] fgl + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fgl.DepartmentID -- We only want to filter on the department being flexed, not the source departments + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND VariabilityID = 2 + + -- Calculate the Stats for the Source Department/Stat Account combinations found in our flexing config + SELECT + fs.DepartmentID AS SourceDepartmentID, + fs.AccountID, + SUM(fs.InitialBudget01) as NewBudgetValue01, + SUM(fs.InitialBudget02) as NewBudgetValue02, + SUM(fs.InitialBudget03) as NewBudgetValue03, + SUM(fs.InitialBudget04) as NewBudgetValue04, + SUM(fs.InitialBudget05) as NewBudgetValue05, + SUM(fs.InitialBudget06) as NewBudgetValue06, + SUM(fs.InitialBudget07) as NewBudgetValue07, + SUM(fs.InitialBudget08) as NewBudgetValue08, + SUM(fs.InitialBudget09) as NewBudgetValue09, + SUM(fs.InitialBudget10) as NewBudgetValue10, + SUM(fs.InitialBudget11) as NewBudgetValue11, + SUM(fs.InitialBudget12) as NewBudgetValue12, + SUM(fs.InitialProjection01) as NewProjectionValue01, + SUM(fs.InitialProjection02) as NewProjectionValue02, + SUM(fs.InitialProjection03) as NewProjectionValue03, + SUM(fs.InitialProjection04) as NewProjectionValue04, + SUM(fs.InitialProjection05) as NewProjectionValue05, + SUM(fs.InitialProjection06) as NewProjectionValue06, + SUM(fs.InitialProjection07) as NewProjectionValue07, + SUM(fs.InitialProjection08) as NewProjectionValue08, + SUM(fs.InitialProjection09) as NewProjectionValue09, + SUM(fs.InitialProjection10) as NewProjectionValue10, + SUM(fs.InitialProjection11) as NewProjectionValue11, + SUM(fs.InitialProjection12) as NewProjectionValue12 + INTO #stats + FROM [fp].[FactStatistics] fs + INNER JOIN (SELECT DISTINCT SourceDepartmentID, StatAccountID FROM #itemsToFlex) fl ON fs.DepartmentID = fl.SourceDepartmentID AND fl.StatAccountID = fs.AccountID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + GROUP BY fs.DepartmentID, + fs.AccountID + + -- Calculate the stats at an individual flex config level. + SELECT + fs.DepartmentID, + fs.SourceDepartmentID, + fs.StatAccountID, + fs.GLAccountID, + SUM(NewBudgetValue01) AS NewBudgetValue01, + SUM(NewBudgetValue02) AS NewBudgetValue02, + SUM(NewBudgetValue03) AS NewBudgetValue03, + SUM(NewBudgetValue04) AS NewBudgetValue04, + SUM(NewBudgetValue05) AS NewBudgetValue05, + SUM(NewBudgetValue06) AS NewBudgetValue06, + SUM(NewBudgetValue07) AS NewBudgetValue07, + SUM(NewBudgetValue08) AS NewBudgetValue08, + SUM(NewBudgetValue09) AS NewBudgetValue09, + SUM(NewBudgetValue10) AS NewBudgetValue10, + SUM(NewBudgetValue11) AS NewBudgetValue11, + SUM(NewBudgetValue12) AS NewBudgetValue12, + SUM(NewProjectionValue01) AS NewProjectionValue01, + SUM(NewProjectionValue02) AS NewProjectionValue02, + SUM(NewProjectionValue03) AS NewProjectionValue03, + SUM(NewProjectionValue04) AS NewProjectionValue04, + SUM(NewProjectionValue05) AS NewProjectionValue05, + SUM(NewProjectionValue06) AS NewProjectionValue06, + SUM(NewProjectionValue07) AS NewProjectionValue07, + SUM(NewProjectionValue08) AS NewProjectionValue08, + SUM(NewProjectionValue09) AS NewProjectionValue09, + SUM(NewProjectionValue10) AS NewProjectionValue10, + SUM(NewProjectionValue11) AS NewProjectionValue11, + SUM(NewProjectionValue12) AS NewProjectionValue12 + INTO #statsBySourceDept + FROM #itemsToFlex fs + INNER JOIN #stats st ON fs.SourceDepartmentID = st.SourceDepartmentID AND fs.StatAccountID = st.AccountID + GROUP BY fs.DepartmentID, + fs.SourceDepartmentID, + fs.StatAccountID, + fs.GLAccountID + + -- Group all of the data together and flex them by taking the Stats * $/UOS + SELECT + uos.DepartmentID, + uos.AccountID, + SUM(uos.InitialBudget01 * stat.NewBudgetValue01) As FlexedBudget01, + SUM(uos.InitialBudget02 * stat.NewBudgetValue02) As FlexedBudget02, + SUM(uos.InitialBudget03 * stat.NewBudgetValue03) As FlexedBudget03, + SUM(uos.InitialBudget04 * stat.NewBudgetValue04) As FlexedBudget04, + SUM(uos.InitialBudget05 * stat.NewBudgetValue05) As FlexedBudget05, + SUM(uos.InitialBudget06 * stat.NewBudgetValue06) As FlexedBudget06, + SUM(uos.InitialBudget07 * stat.NewBudgetValue07) As FlexedBudget07, + SUM(uos.InitialBudget08 * stat.NewBudgetValue08) As FlexedBudget08, + SUM(uos.InitialBudget09 * stat.NewBudgetValue09) As FlexedBudget09, + SUM(uos.InitialBudget10 * stat.NewBudgetValue10) As FlexedBudget10, + SUM(uos.InitialBudget11 * stat.NewBudgetValue11) As FlexedBudget11, + SUM(uos.InitialBudget12 * stat.NewBudgetValue12) As FlexedBudget12, + SUM(uos.InitialProjection01 * stat.NewProjectionValue01) As FlexedProjection01, + SUM(uos.InitialProjection02 * stat.NewProjectionValue02) As FlexedProjection02, + SUM(uos.InitialProjection03 * stat.NewProjectionValue03) As FlexedProjection03, + SUM(uos.InitialProjection04 * stat.NewProjectionValue04) As FlexedProjection04, + SUM(uos.InitialProjection05 * stat.NewProjectionValue05) As FlexedProjection05, + SUM(uos.InitialProjection06 * stat.NewProjectionValue06) As FlexedProjection06, + SUM(uos.InitialProjection07 * stat.NewProjectionValue07) As FlexedProjection07, + SUM(uos.InitialProjection08 * stat.NewProjectionValue08) As FlexedProjection08, + SUM(uos.InitialProjection09 * stat.NewProjectionValue09) As FlexedProjection09, + SUM(uos.InitialProjection10 * stat.NewProjectionValue10) As FlexedProjection10, + SUM(uos.InitialProjection11 * stat.NewProjectionValue11) As FlexedProjection11, + SUM(uos.InitialProjection12 * stat.NewProjectionValue12) As FlexedProjection12 + INTO #flexedValues + FROM (SELECT DISTINCT f.DepartmentID, f.GLAccountID, f.StatAccountID FROM #itemsToFlex f) fm + INNER JOIN #dollarPerUosRates uos ON uos.DepartmentID = fm.DepartmentID AND uos.AccountID = fm.GLAccountID + INNER JOIN #statsBySourceDept stat ON fm.StatAccountID = stat.StatAccountID + AND fm.DepartmentID = stat.DepartmentID + AND uos.AccountID = stat.GLAccountID + GROUP BY uos.DepartmentID, + uos.AccountID + + IF @IsDebug = 1 + BEGIN + SELECT '#FilterByDepartment', * FROM #FilterByDepartment + SELECT '#itemsToFlex', * FROM #itemsToFlex + SELECT '#dollarPerUosRates', * FROM #dollarPerUosRates + SELECT '#stats', * FROM #stats + SELECT '#statsBySourceDept', * FROM #statsBySourceDept + SELECT '#flexedValues', * FROM #flexedValues + END ELSE + BEGIN + + -- flex projection data and reset the adjusted value as well + UPDATE basis + SET + basis.InitialBudget01 = flexed.FlexedBudget01, + basis.InitialBudget02 = flexed.FlexedBudget02, + basis.InitialBudget03 = flexed.FlexedBudget03, + basis.InitialBudget04 = flexed.FlexedBudget04, + basis.InitialBudget05 = flexed.FlexedBudget05, + basis.InitialBudget06 = flexed.FlexedBudget06, + basis.InitialBudget07 = flexed.FlexedBudget07, + basis.InitialBudget08 = flexed.FlexedBudget08, + basis.InitialBudget09 = flexed.FlexedBudget09, + basis.InitialBudget10 = flexed.FlexedBudget10, + basis.InitialBudget11 = flexed.FlexedBudget11, + basis.InitialBudget12 = flexed.FlexedBudget12, + basis.InitialProjection01 = CASE WHEN @MonthsLoaded >= 1 THEN basis.InitialProjection01 ELSE flexed.FlexedProjection01 END, + basis.InitialProjection02 = CASE WHEN @MonthsLoaded >= 2 THEN basis.InitialProjection02 ELSE flexed.FlexedProjection02 END, + basis.InitialProjection03 = CASE WHEN @MonthsLoaded >= 3 THEN basis.InitialProjection03 ELSE flexed.FlexedProjection03 END, + basis.InitialProjection04 = CASE WHEN @MonthsLoaded >= 4 THEN basis.InitialProjection04 ELSE flexed.FlexedProjection04 END, + basis.InitialProjection05 = CASE WHEN @MonthsLoaded >= 5 THEN basis.InitialProjection05 ELSE flexed.FlexedProjection05 END, + basis.InitialProjection06 = CASE WHEN @MonthsLoaded >= 6 THEN basis.InitialProjection06 ELSE flexed.FlexedProjection06 END, + basis.InitialProjection07 = CASE WHEN @MonthsLoaded >= 7 THEN basis.InitialProjection07 ELSE flexed.FlexedProjection07 END, + basis.InitialProjection08 = CASE WHEN @MonthsLoaded >= 8 THEN basis.InitialProjection08 ELSE flexed.FlexedProjection08 END, + basis.InitialProjection09 = CASE WHEN @MonthsLoaded >= 9 THEN basis.InitialProjection09 ELSE flexed.FlexedProjection09 END, + basis.InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN basis.InitialProjection10 ELSE flexed.FlexedProjection10 END, + basis.InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN basis.InitialProjection11 ELSE flexed.FlexedProjection11 END, + basis.InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN basis.InitialProjection12 ELSE flexed.FlexedProjection12 END + FROM [fp].[GeneralLedger] basis + INNER JOIN #flexedValues flexed ON basis.DepartmentID = flexed.DepartmentID AND basis.AccountID = flexed.AccountID + WHERE basis.VariabilityID = 2 + AND basis.EntityGroupConfigID = @EntityGroupConfigID + AND ( + basis.InitialBudget01 != flexed.FlexedBudget01 + OR basis.InitialBudget02 != flexed.FlexedBudget02 + OR basis.InitialBudget03 != flexed.FlexedBudget03 + OR basis.InitialBudget04 != flexed.FlexedBudget04 + OR basis.InitialBudget05 != flexed.FlexedBudget05 + OR basis.InitialBudget06 != flexed.FlexedBudget06 + OR basis.InitialBudget07 != flexed.FlexedBudget07 + OR basis.InitialBudget08 != flexed.FlexedBudget08 + OR basis.InitialBudget09 != flexed.FlexedBudget09 + OR basis.InitialBudget10 != flexed.FlexedBudget10 + OR basis.InitialBudget11 != flexed.FlexedBudget11 + OR basis.InitialBudget12 != flexed.FlexedBudget12 + OR basis.InitialProjection01 != flexed.FlexedProjection01 + OR basis.InitialProjection02 != flexed.FlexedProjection02 + OR basis.InitialProjection03 != flexed.FlexedProjection03 + OR basis.InitialProjection04 != flexed.FlexedProjection04 + OR basis.InitialProjection05 != flexed.FlexedProjection05 + OR basis.InitialProjection06 != flexed.FlexedProjection06 + OR basis.InitialProjection07 != flexed.FlexedProjection07 + OR basis.InitialProjection08 != flexed.FlexedProjection08 + OR basis.InitialProjection09 != flexed.FlexedProjection09 + OR basis.InitialProjection10 != flexed.FlexedProjection10 + OR basis.InitialProjection11 != flexed.FlexedProjection11 + OR basis.InitialProjection12 != flexed.FlexedProjection12 + ) + + END +END +GO + + +--------------------------------------------- + +-- fp.procGLCopyNewItems +CREATE PROCEDURE [fp].[procGLCopyNewItems] + @SourceBudgetConfigID INT, + @SourceEntityGroupConfigID INT, + @BudgetConfigID INT, + @EntityGroupConfigID INT +AS +BEGIN + +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 8-15-2023 NT JAZZ-58783 Data restructure changes +*************************************************************/ + + +INSERT INTO [fp].[GeneralLedger] (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, AddDate, +SampledBudget01, SampledBudget02, SampledBudget03, SampledBudget04, SampledBudget05, SampledBudget06, SampledBudget07, SampledBudget08, SampledBudget09, SampledBudget10, SampledBudget11, SampledBudget12, +SampledProjection01, SampledProjection02, SampledProjection03, SampledProjection04, SampledProjection05, SampledProjection06, SampledProjection07, SampledProjection08, SampledProjection09, SampledProjection10, SampledProjection11, SampledProjection12, +InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, +InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12, +IsNew) +SELECT @BudgetConfigID, @EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, AddDate, +SampledBudget01, SampledBudget02, SampledBudget03, SampledBudget04, SampledBudget05, SampledBudget06, SampledBudget07, SampledBudget08, SampledBudget09, SampledBudget10, SampledBudget11, SampledBudget12, +SampledProjection01, SampledProjection02, SampledProjection03, SampledProjection04, SampledProjection05, SampledProjection06, SampledProjection07, SampledProjection08, SampledProjection09, SampledProjection10, SampledProjection11, SampledProjection12, +InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, +InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12, +IsNew +FROM [fp].[GeneralLedger] +WHERE BudgetConfigID = @SourceBudgetConfigID AND EntityGroupConfigID = @SourceEntityGroupConfigID AND IsNew = 1 + +END +GO + + +--------------------------------------------- + +-- fp.procGeneralLedgerApplySpread +CREATE PROCEDURE [fp].[procGeneralLedgerApplySpread] + @BudgetConfigID int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2018-12-04 BK B-21418 Initial + ** 2 2018-12-11 MY B-21444 Adding ability to unlock spread if inactive and fixing case where row in GL but not in benefits is not spread. + ** 3 2010-02-18 NL B-22129 changing proc to use spread view instead of table directly (to incorporate global spreads) + ** 4 2019-07-31 NL D-08581 updating the way spread remainder is allocated (w/feature flag) + ** 5 2019-11-01 MY B-24221 removing CID 4's FF and making it always on + ** 6 2022-08-09 JB JAZZ-23177 Switch usages of funcGetSourceDimensionalityAsTable to a temp table + ** 7 2023-07-14 BW JAZZ-55784 Data model restructure + ** 8 2024-01-22 MY JAZZ-64799 History Viewer does not handle Spread Impact for Monthly Values + *************************************************************/ + + IF OBJECT_ID('tempdb..#tmpGL') IS NOT NULL DROP TABLE #tmpGL; + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment; + IF OBJECT_ID('tempdb..#spreadsChangeHistory') IS NOT NULL DROP TABLE #spreadsChangeHistory; + + CREATE TABLE #tmpGL (GeneralLedgerID INT, DepartmentID INT, AccountID INT); + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #spreadsChangeHistory ( + GeneralLedgerID INT, + OldValue01 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue02 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue03 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue04 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue05 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue06 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue07 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue08 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue09 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue10 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue11 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue12 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue01 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue02 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue03 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue04 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue05 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue06 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue07 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue08 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue09 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue10 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue11 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue12 DECIMAL(19, 8) NOT NULL DEFAULT(0), + ); + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #tmpGL (GeneralLedgerID, DepartmentID, AccountID) + SELECT DISTINCT basis.GeneralLedgerID, basis.DepartmentID, basis.AccountID + FROM [fp].[GeneralLedger] basis + INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = basis.DepartmentID + WHERE BudgetConfigID = @BudgetConfigID AND basis.VariabilityID = 1 AND BudgetLockType <> 2 AND BudgetLockType <> 3 AND BudgetLockType <> 1 AND BudgetLockType <> 7 + END ELSE BEGIN + INSERT INTO #tmpGL (GeneralLedgerID, DepartmentID, AccountID) + SELECT DISTINCT basis.GeneralLedgerID, basis.DepartmentID, basis.AccountID + FROM [fp].[GeneralLedger] basis + WHERE BudgetConfigID = @BudgetConfigID AND basis.VariabilityID = 1 AND BudgetLockType <> 2 AND BudgetLockType <> 3 AND BudgetLockType <> 1 AND BudgetLockType <> 7 + END + + UPDATE fgl + SET BudgetLockType = 6, BudgetLockFlag = 1 + , BudgetAdjusted01 = CAST(BudgetAdjustedTotal * SpreadPercentage01 AS DECIMAL(19,8)) + , BudgetAdjusted02 = + CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage02 AS DECIMAL(19,8)) END + , BudgetAdjusted03 = + CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage03 AS DECIMAL(19,8)) END + , BudgetAdjusted04 = + CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage04 AS DECIMAL(19,8)) END + , BudgetAdjusted05 = + CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage05 AS DECIMAL(19,8)) END + , BudgetAdjusted06 = + CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage06 AS DECIMAL(19,8)) END + , BudgetAdjusted07 = + CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage07 AS DECIMAL(19,8)) END + , BudgetAdjusted08 = + CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage08 AS DECIMAL(19,8)) END + , BudgetAdjusted09 = + CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage09 AS DECIMAL(19,8)) END + , BudgetAdjusted10 = + CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage10 AS DECIMAL(19,8)) END + , BudgetAdjusted11 = + CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage10) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage11 AS DECIMAL(19,8)) END + , BudgetAdjusted12 = + CASE WHEN SpreadPercentage12 != 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage11) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage12 AS DECIMAL(19,8)) END + OUTPUT + inserted.GeneralLedgerID, + deleted.BudgetAdjusted01, deleted.BudgetAdjusted02, deleted.BudgetAdjusted03, deleted.BudgetAdjusted04, deleted.BudgetAdjusted05, deleted.BudgetAdjusted06, + deleted.BudgetAdjusted07, deleted.BudgetAdjusted08, deleted.BudgetAdjusted09, deleted.BudgetAdjusted10, deleted.BudgetAdjusted11, deleted.BudgetAdjusted12, + inserted.BudgetAdjusted01, inserted.BudgetAdjusted02, inserted.BudgetAdjusted03, inserted.BudgetAdjusted04, inserted.BudgetAdjusted05, inserted.BudgetAdjusted06, + inserted.BudgetAdjusted07, inserted.BudgetAdjusted08, inserted.BudgetAdjusted09, inserted.BudgetAdjusted10, inserted.BudgetAdjusted11, inserted.BudgetAdjusted12 + INTO + #spreadsChangeHistory (GeneralLedgerID, + OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06, + OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12, + NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06, + NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) + FROM [fp].[viewGeneralLedgerSpreads] gls + INNER JOIN [fp].[GeneralLedger] fgl ON gls.BudgetConfigID = fgl.BudgetConfigID AND gls.DepartmentID = fgl.DepartmentID AND gls.AccountID = fgl.AccountID + INNER JOIN #tmpGL tmp on fgl.GeneralLedgerID = tmp.GeneralLedgerID + WHERE gls.IsInactive = 0 + + + -- Unlock Spreads that are no longer active + UPDATE fgl + SET BudgetLockType = 0, BudgetLockFlag = 0 + FROM [fp].[GeneralLedgerSpreads] gls -- We don't want to use the view here because the view filters out not specified records + INNER JOIN [fp].[GeneralLedger] fgl ON gls.BudgetConfigID = fgl.BudgetConfigID AND gls.DepartmentID = fgl.DepartmentID AND gls.AccountID = fgl.AccountID + INNER JOIN #tmpGL tmp on fgl.GeneralLedgerID = tmp.GeneralLedgerID + WHERE gls.IsInactive = 1 + AND fgl.BudgetLockFlag = 1 + AND fgl.BudgetLockType = 6 + + -- Populate Change History + IF EXISTS(SELECT 1 + FROM fp.BudgetConfigSetting setting + INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON setting.SettingID = def.SettingID + WHERE def.Name = 'Spreads Change History Logic Is Enabled' + AND setting.Value = 1) + BEGIN + + INSERT INTO fp.GeneralLedgerSpreadsChangeHistory (GeneralLedgerID, BudgetConfigID, OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06, + OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12, NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06, + NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) + SELECT GeneralLedgerID, @BudgetConfigID, + ISNULL(OldValue01, 0), ISNULL(OldValue02, 0), ISNULL(OldValue03, 0), ISNULL(OldValue04, 0), ISNULL(OldValue05, 0), ISNULL(OldValue06, 0), + ISNULL(OldValue07, 0), ISNULL(OldValue08, 0), ISNULL(OldValue09, 0), ISNULL(OldValue10, 0), ISNULL(OldValue11, 0), ISNULL(OldValue12, 0), + ISNULL(NewValue01, 0), ISNULL(NewValue02, 0), ISNULL(NewValue03, 0), ISNULL(NewValue04, 0), ISNULL(NewValue05, 0), ISNULL(NewValue06, 0), + ISNULL(NewValue07, 0), ISNULL(NewValue08, 0), ISNULL(NewValue09, 0), ISNULL(NewValue10, 0), ISNULL(NewValue11, 0), ISNULL(NewValue12, 0) + FROM #spreadsChangeHistory + WHERE 1 = 1 + AND ( + OldValue01 != NewValue01 + OR OldValue02 != NewValue02 + OR OldValue03 != NewValue03 + OR OldValue04 != NewValue04 + OR OldValue05 != NewValue05 + OR OldValue06 != NewValue06 + OR OldValue07 != NewValue07 + OR OldValue08 != NewValue08 + OR OldValue09 != NewValue09 + OR OldValue10 != NewValue10 + OR OldValue11 != NewValue11 + OR OldValue12 != NewValue12 + ) + END +END +GO + + +--------------------------------------------- + +-- fp.procGeneralLedgerApplySpreadItemized +CREATE PROCEDURE [fp].[procGeneralLedgerApplySpreadItemized] + @BudgetConfigID int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-03-16 MD JAZZ-16700 Initial + ** 2 2022-08-09 JB JAZZ-23177 Switch usages of funcGetSourceDimensionalityAsTable to a temp table + ** 3 2023-07-17 BW JAZZ-55784 Data model restructure + ** 4 2024-03-15 AO JAZZ-65797 GeneralLedgerItemizationDetail table rename + *************************************************************/ + + IF OBJECT_ID('tempdb..#tmpGL') IS NOT NULL DROP TABLE #tmpGL; + IF OBJECT_ID('tempdb..#deletedItemizedAdjustments') IS NOT NULL DROP TABLE #deletedItemizedAdjustments; + IF OBJECT_ID('tempdb..#removeSpreadLockAdjustments') IS NOT NULL DROP TABLE #removeSpreadLockAdjustments; + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment; + + CREATE TABLE #tmpGL (GeneralLedgerID INT, DepartmentID INT, AccountID INT); + CREATE TABLE #deletedItemizedAdjustments (OriginalCommentGUID uniqueidentifier, InverseCommentGUID uniqueidentifier); + CREATE TABLE #removeSpreadLockAdjustments (DepartmentID INT, AccountID INT, CountExistingAdjustmentsWithSpreads INT); + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #tmpGL (GeneralLedgerID, DepartmentID, AccountID) + SELECT DISTINCT basis.GeneralLedgerID, basis.DepartmentID, basis.AccountID + FROM [fp].[GeneralLedger] basis + INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = basis.DepartmentID + LEFT JOIN fp.GeneralLedgerSpreads gls ON gls.BudgetConfigID = basis.BudgetConfigID AND basis.DepartmentID = gls.DepartmentID AND basis.AccountID = gls.AccountID + WHERE basis.BudgetConfigID = @BudgetConfigID AND basis.VariabilityID = 1 + AND BudgetLockType <> 2 AND BudgetLockType <> 3 AND BudgetLockType <> 1 AND BudgetLockType <> 7 + AND gls.GlobalSpreadID = 0 OR gls.GlobalSpreadID is null + + INSERT INTO #deletedItemizedAdjustments (OriginalCommentGUID, InverseCommentGUID) + select id.CommentGUID, idl.InverseAdjustmentCommentGUID + FROM fp.GeneralLedgerFixedDetail id + INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = id.DepartmentID + INNER JOIN fp.GeneralLedgerItemizationDetailLink idl ON id.CommentGUID = idl.OriginalAdjustmentCommentGUID + END ELSE BEGIN + INSERT INTO #tmpGL (GeneralLedgerID, DepartmentID, AccountID) + SELECT DISTINCT basis.GeneralLedgerID, basis.DepartmentID, basis.AccountID + FROM [fp].[GeneralLedger] basis + LEFT JOIN fp.GeneralLedgerSpreads gls ON gls.BudgetConfigID = basis.BudgetConfigID AND basis.DepartmentID = gls.DepartmentID AND basis.AccountID = gls.AccountID + WHERE basis.BudgetConfigID = @BudgetConfigID AND basis.VariabilityID = 1 + AND BudgetLockType <> 2 AND BudgetLockType <> 3 AND BudgetLockType <> 1 AND BudgetLockType <> 7 + AND gls.GlobalSpreadID = 0 OR gls.GlobalSpreadID is null + + INSERT INTO #deletedItemizedAdjustments (OriginalCommentGUID, InverseCommentGUID) + select id.CommentGUID, idl.InverseAdjustmentCommentGUID + FROM fp.GeneralLedgerFixedDetail id + INNER JOIN fp.GeneralLedgerItemizationDetailLink idl ON id.CommentGUID = idl.OriginalAdjustmentCommentGUID + END + + --Lock cells that have itemized adjustments with spreads + UPDATE fgl + SET BudgetLockType = 6, BudgetLockFlag = 1 + FROM + [fp].[GeneralLedgerFixedDetail] glid + INNER JOIN [fp].[GeneralLedger] fgl ON glid.BudgetConfigID = fgl.BudgetConfigID AND glid.DepartmentID = fgl.DepartmentID AND glid.AccountID = fgl.AccountID + INNER JOIN #tmpGL tmp on fgl.GeneralLedgerID = tmp.GeneralLedgerID + LEFT JOIN #deletedItemizedAdjustments da on glid.CommentGUID = da.OriginalCommentGUID + LEFT JOIN #deletedItemizedAdjustments da1 on glid.CommentGUID = da1.InverseCommentGUID + WHERE da.OriginalCommentGUID IS NULL AND glid.SpreadID > 0 AND glid.TimeClassID = 2 and fgl.VariabilityID = 1 AND da1.InverseCommentGUID IS NULL + + INSERT INTO #removeSpreadLockAdjustments (DepartmentID, AccountID, CountExistingAdjustmentsWithSpreads) + SELECT tmp.DepartmentID, tmp.AccountID, count(*) + FROM [fp].[GeneralLedgerFixedDetail] glid + INNER JOIN [fp].[GeneralLedger] fgl ON glid.BudgetConfigID = fgl.BudgetConfigID AND glid.DepartmentID = fgl.DepartmentID AND glid.AccountID = fgl.AccountID + INNER JOIN #tmpGL tmp on fgl.GeneralLedgerID = tmp.GeneralLedgerID + LEFT JOIN #deletedItemizedAdjustments da ON glid.CommentGUID = da.OriginalCommentGUID + LEFT JOIN #deletedItemizedAdjustments da1 on glid.CommentGUID = da1.InverseCommentGUID + WHERE glid.SpreadID > 0 AND BudgetLockFlag = 1 AND BudgetLockType = 6 + AND da.OriginalCommentGUID IS NULL + AND da1.InverseCommentGUID IS NULL + GROUP BY tmp.DepartmentID, tmp.AccountID + + + -- Unlock Spreads that are no longer active + UPDATE fgl + SET BudgetLockType = 0, BudgetLockFlag = 0 + FROM + [fp].[GeneralLedger] fgl + INNER JOIN #tmpGL tmp on fgl.GeneralLedgerID = tmp.GeneralLedgerID + LEFT JOIN #removeSpreadLockAdjustments rsla on tmp.DepartmentID = rsla.DepartmentID AND tmp.AccountID = rsla.AccountID + WHERE BudgetLockFlag = 1 AND BudgetLockType = 6 AND rsla.DepartmentID IS NULL + +END +GO + + +--------------------------------------------- + +-- fp.procGeneralLedgerBudgetStampOff +CREATE PROCEDURE [fp].[procGeneralLedgerBudgetStampOff] + @BudgetConfigID INT, + @TargetTimeClassID TINYINT +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 01-31-2023 MY JAZZ-48962 Initial Creation + ** 2 08-15-2023 MY JAZZ-58778 Update budget stamp off process - GL + ** 3 01-03-2024 MZ JAZZ-65385 Added Target TimeClass + ** 4 03-18-2024 MZ JAZZ-68428 Deleting by Chunks & removed HistoryItemGUID parameter + *************************************************************/ + + -- Note: The original script was done here https://confluence.sdt.local/display/DD/Moving+Data+from+a+Plan+Configuration+to+Int+Tables + + DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID ) + DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID) + + DECLARE @HistoryItemGUID UNIQUEIDENTIFIER + EXEC procLogScript 'StampOff: Transferring Budget Data from 1p', @HistoryItemGUID OUTPUT + PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36)) + PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID) + + -- Clear out existing records for the selected FiscalYear and Budgeted Time Class + DECLARE @ChunkCount INT + + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END + + DECLARE @r INT; + SET @r = 1; + + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) FROM [int].[FactGL] WHERE FiscalYearID = @FiscalYear and TimeClassID = @TargetTimeClassID + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + INSERT INTO [int].[FactGL] ([DepartmentID], [DepartmentCode], [AccountID], [AccountCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], + [TimeClassCode], [FiscalMonthID], [FiscalMonthCode], [Value], [IsDeleted], [HistoryItemGUID]) + SELECT + d.DepartmentID, + d.DepartmentCode, + acc.AccountID, + acc.AccountCode, + bc.FiscalYearID, + bc.FiscalYearID AS FiscalYearCode, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + fm.FiscalMonthID, + fm.FiscalMonthCode, + acc.inversion * Value AS Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID + FROM ( + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, m.FiscalMonthID, f.Value AS Value + FROM ( + SELECT gl.GeneralLedgerID, gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, gl.DepartmentID, gl.AccountID, gl.FinancialReportingID, gl.APEModelSectionID, gl.VariabilityID, + gl.BudgetAdjusted01, gl.BudgetAdjusted02, gl.BudgetAdjusted03, gl.BudgetAdjusted04, gl.BudgetAdjusted05, gl.BudgetAdjusted06, gl.BudgetAdjusted07, + gl.BudgetAdjusted08, gl.BudgetAdjusted09, gl.BudgetAdjusted10, gl.BudgetAdjusted11, gl.BudgetAdjusted12 + FROM fp.GeneralLedger gl + WHERE gl.BudgetConfigID = @BudgetConfigID + ) gl + UNPIVOT (Value FOR FiscalMonth IN (BudgetAdjusted01, BudgetAdjusted02, BudgetAdjusted03, BudgetAdjusted04, BudgetAdjusted05, BudgetAdjusted06, BudgetAdjusted07, BudgetAdjusted08, BudgetAdjusted09, BudgetAdjusted10, BudgetAdjusted11, BudgetAdjusted12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'BudgetAdjusted', 'Month') + ) BudgetedData + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = BudgetedData.BudgetConfigID + INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = BudgetedData.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = BudgetedData.FiscalMonthID + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = BudgetedData.AccountID + WHERE 1=1 + AND BudgetedData.Value <> 0 + AND bc.BudgetConfigID = @BudgetConfigID +END +GO + + +--------------------------------------------- + +-- fp.procGeneralLedgerProjectionStampOff +CREATE PROCEDURE [fp].[procGeneralLedgerProjectionStampOff] + @BudgetConfigID INT, + @TargetTimeClassID TINYINT, + @IsMonthsLoadedIncluded BIT +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 11-10-2023 AO JAZZ-62128 Initial Creation + ** 2 01-04-2024 MZ JAZZ-65385 Added Target TimeClass and IsMonthsLoadedIncluded + ** 3 01-24-2024 MZ JAZZ-64527 Fix Months Loaded + ** 4 03-18-2024 MZ JAZZ-68428 Deleting by Chunks & removed HistoryItemGUID parameter + ** 5 04-03-2024 MZ JAZZ-70053 Fix Month Loaded excluding logic + *************************************************************/ + + -- Note: The original script was done here https://confluence.sdt.local/display/DD/Moving+Data+from+a+Plan+Configuration+to+Int+Tables + + DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID - 1 FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID ) + DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID) + DECLARE @MonthsLoaded INT = (SELECT bc.MonthsLoaded FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID) + + DECLARE @HistoryItemGUID UNIQUEIDENTIFIER + EXEC procLogScript 'StampOff: Transferring Projection Data from 1p', @HistoryItemGUID OUTPUT + PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36)) + PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID) + + -- Clear out existing records for the selected FiscalYear and Projected Time Class + -- and all months if months loaded included otherwise only months NOT loaded will be cleared + DECLARE @ChunkCount INT + + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END + + DECLARE @r INT; + SET @r = 1; + + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) gl FROM [int].[FactGL] gl + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = gl.FiscalMonthID + WHERE gl.FiscalYearID = @FiscalYear + AND gl.TimeClassID = @TargetTimeClassID + AND (@IsMonthsLoadedIncluded = 1 OR fm.SortOrder > @MonthsLoaded) + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + INSERT INTO [int].[FactGL] ([DepartmentID], [DepartmentCode], [AccountID], [AccountCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], + [TimeClassCode], [FiscalMonthID], [FiscalMonthCode], [Value], [IsDeleted], [HistoryItemGUID]) + SELECT + d.DepartmentID, + d.DepartmentCode, + acc.AccountID, + acc.AccountCode, + @FiscalYear, + @FiscalYear AS FiscalYearCode, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + fm.FiscalMonthID, + fm.FiscalMonthCode, + acc.inversion * Value AS Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID + FROM ( + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, VariabilityID, m.FiscalMonthID, f.Value AS Value + FROM ( + SELECT gl.GeneralLedgerID, gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, gl.DepartmentID, gl.AccountID, gl.FinancialReportingID, gl.APEModelSectionID, gl.VariabilityID, + gl.ProjectionAdjusted01, gl.ProjectionAdjusted02, gl.ProjectionAdjusted03, gl.ProjectionAdjusted04, gl.ProjectionAdjusted05, gl.ProjectionAdjusted06, gl.ProjectionAdjusted07, + gl.ProjectionAdjusted08, gl.ProjectionAdjusted09, gl.ProjectionAdjusted10, gl.ProjectionAdjusted11, gl.ProjectionAdjusted12 + FROM fp.GeneralLedger gl + WHERE gl.BudgetConfigID = @BudgetConfigID + ) gl + UNPIVOT (Value FOR FiscalMonth IN (ProjectionAdjusted01, ProjectionAdjusted02, ProjectionAdjusted03, ProjectionAdjusted04, ProjectionAdjusted05, ProjectionAdjusted06, ProjectionAdjusted07, ProjectionAdjusted08, ProjectionAdjusted09, ProjectionAdjusted10, ProjectionAdjusted11, ProjectionAdjusted12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'ProjectionAdjusted', 'Month') + ) BudgetedData + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = BudgetedData.BudgetConfigID + INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = BudgetedData.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = BudgetedData.FiscalMonthID + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = BudgetedData.AccountID + WHERE 1=1 + AND BudgetedData.Value <> 0 + AND bc.BudgetConfigID = @BudgetConfigID + AND (@IsMonthsLoadedIncluded = 1 OR CAST(fm.FiscalMonthCode AS INT) > bc.MonthsLoaded) +END +GO + + +--------------------------------------------- + +-- fp.procGetAPDetailsDebug +CREATE PROCEDURE [fp].[procGetAPDetailsDebug] + @BudgetConfigID INT = 0 + AS + BEGIN + + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2-13-2023 MY JAZZ-XXXXX Initial + ** 2 2-15-2023 MY JAZZ-XXXXX Added Chunking Config and Sorting + *************************************************************/ + + -- Note about this proc, it's used in the SSMS Extension, but can also be called to get a high level view of all settings in the system + + EXEC [dbo].[procSysDropTempTable] '#settings' + EXEC [dbo].[procSysDropTempTable] '#budgetConfig' + + IF (@BudgetConfigID = 0) + SET @BudgetConfigID = (SELECT BudgetConfigID FROM fp.BudgetConfig WHERE IsActive = 1) + + CREATE TABLE #settings ( + Name NVARCHAR(MAX) NOT NULL DEFAULT(''), + SourceTable NVARCHAR(MAX) NOT NULL DEFAULT(''), + Category NVARCHAR(50) NOT NULL DEFAULT(''), + Value NVARCHAR(MAX) NOT NULL DEFAULT(''), -- Using this because the value could be anything + Description NVARCHAR(MAX) NOT NULL DEFAULT(''), + EntityGroupConfigName NVARCHAR(MAX) NOT NULL DEFAULT(''), + SortOrder INT NOT NULL DEFAULT(1) -- Defaulting to 1 so that anything with 0 can show up first + ); + + ---------------------------------------------------------------- + -- Budget Config + ---------------------------------------------------------------- + + ---- I know what you are thinking and yes, this is easier than having a huge wall of unions and this is dynamic at least... + DECLARE @Sql NVARCHAR(MAX) = 'SELECT '; + DECLARE @ColumnName VARCHAR(MAX); + + DECLARE cursor_config CURSOR + FOR SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'BudgetConfig' AND TABLE_SCHEMA = 'fp' + OPEN cursor_config; + + FETCH NEXT FROM cursor_config INTO @ColumnName; + + WHILE @@FETCH_STATUS = 0 + BEGIN + SET @Sql = @Sql + 'CAST([' + @ColumnName + '] AS NVARCHAR(MAX)) AS [' + @ColumnName + '],' + CHAR(10); + + FETCH NEXT FROM cursor_config INTO @ColumnName; + END; + + CLOSE cursor_config; + DEALLOCATE cursor_config; + + SET @Sql = SUBSTRING(@Sql, 1, LEN(@Sql) - 1); -- Remove last carriage return + SET @Sql = LEFT(@Sql, LEN(@Sql) - 1); -- Remove last comma + + SET @Sql = @Sql + CHAR(10) + 'INTO #budgetConfig' + CHAR(10); + SET @Sql = @Sql + 'FROM fp.BudgetConfig' + CHAR(10); + SET @Sql = @Sql + 'WHERE BudgetConfigID = ' + CAST(@BudgetConfigID AS NVARCHAR(MAX)) + CHAR(10) + CHAR(10); + + SET @Sql = @Sql + 'INSERT INTO #settings (Name, SourceTable, Category, Value, Description, SortOrder)' + CHAR(10); + SET @Sql = @Sql + 'SELECT ColumnName, ''fp.BudgetConfig'', ''Plan Config'', ColumnValue, '''', 0' + CHAR(10); + SET @Sql = @Sql + 'FROM #budgetConfig' + CHAR(10); + SET @Sql = @Sql + 'UNPIVOT(ColumnValue For ColumnName IN (' + CHAR(10); + + DECLARE cursor_config CURSOR + FOR SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'BudgetConfig' AND TABLE_SCHEMA = 'fp' + OPEN cursor_config; + + FETCH NEXT FROM cursor_config INTO @ColumnName; + + WHILE @@FETCH_STATUS = 0 + BEGIN + SET @Sql = @Sql + @ColumnName + ',' + CHAR(10); + + FETCH NEXT FROM cursor_config INTO @ColumnName; + END; + + CLOSE cursor_config; + DEALLOCATE cursor_config; + + SET @Sql = SUBSTRING(@Sql, 1, LEN(@Sql) - 1); -- Remove last carriage return + SET @Sql = LEFT(@Sql, LEN(@Sql) - 1); -- Remove last comma + + SET @Sql = @Sql + ')) AS f' + CHAR(10); + + EXECUTE sp_executesql @Sql + + ---------------------------------------------------------------- + -- Entity Group Config + ---------------------------------------------------------------- + + DECLARE @EntityGroupConfigName VARCHAR(MAX); + + DECLARE cursor_egc CURSOR + FOR SELECT Name FROM fp.EntityGroupConfig egc INNER JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID WHERE bc.BudgetConfigID = @BudgetConfigID + OPEN cursor_egc; + + FETCH NEXT FROM cursor_egc INTO @EntityGroupConfigName; + + WHILE @@FETCH_STATUS = 0 + BEGIN + + SET @Sql = 'SELECT '; + + DECLARE cursor_config CURSOR + FOR SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'EntityGroupConfig' AND TABLE_SCHEMA = 'fp' + OPEN cursor_config; + + FETCH NEXT FROM cursor_config INTO @ColumnName; + + WHILE @@FETCH_STATUS = 0 + BEGIN + SET @Sql = @Sql + 'CAST([' + @ColumnName + '] AS NVARCHAR(MAX)) AS [' + @ColumnName + '],' + CHAR(10); + FETCH NEXT FROM cursor_config INTO @ColumnName; + END; + + CLOSE cursor_config; + DEALLOCATE cursor_config; + + SET @Sql = SUBSTRING(@Sql, 1, LEN(@Sql) - 1); -- Remove last carriage return + SET @Sql = LEFT(@Sql, LEN(@Sql) - 1); -- Remove last comma + + SET @Sql = @Sql + CHAR(10) + 'INTO #entityGroupConfig' + CHAR(10); + SET @Sql = @Sql + 'FROM fp.EntityGroupConfig' + CHAR(10); + SET @Sql = @Sql + 'WHERE BudgetConfigGUID = ' + '''' + CAST((SELECT BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID) AS NVARCHAR(MAX)) + '''' + CHAR(10) + CHAR(10); + + SET @Sql = @Sql + 'INSERT INTO #settings (Name, SourceTable, Category, Value, Description, EntityGroupConfigName, SortOrder)' + CHAR(10); + SET @Sql = @Sql + 'SELECT ColumnName, ''fp.EntityGroupConfig'', ''Entity Group Config'', ColumnValue, '''', '+ '''' + @EntityGroupConfigName + ''', 0' + CHAR(10); + SET @Sql = @Sql + 'FROM #entityGroupConfig' + CHAR(10); + SET @Sql = @Sql + 'UNPIVOT(ColumnValue For ColumnName IN (' + CHAR(10); + + DECLARE cursor_config CURSOR + FOR SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'EntityGroupConfig' AND TABLE_SCHEMA = 'fp' + OPEN cursor_config; + + FETCH NEXT FROM cursor_config INTO @ColumnName; + + WHILE @@FETCH_STATUS = 0 + BEGIN + SET @Sql = @Sql + @ColumnName + ',' + CHAR(10); + + FETCH NEXT FROM cursor_config INTO @ColumnName; + END; + + CLOSE cursor_config; + DEALLOCATE cursor_config; + + SET @Sql = SUBSTRING(@Sql, 1, LEN(@Sql) - 1); -- Remove last carriage return + SET @Sql = LEFT(@Sql, LEN(@Sql) - 1); -- Remove last comma + + SET @Sql = @Sql + ')) AS f' + CHAR(10); + + EXECUTE sp_executesql @Sql + + FETCH NEXT FROM cursor_egc INTO @EntityGroupConfigName; + END; + + CLOSE cursor_egc; + DEALLOCATE cursor_egc; + + ---------------------------------------------------------------- + -- Entity Group Config Mapping + ---------------------------------------------------------------- + + INSERT INTO #settings (Name, SourceTable, Category, Value, Description, EntityGroupConfigName) + SELECT 'EntityID', 'fp.EntityGroupConfigMapping', 'Entity Group Config', egcm.EntityID, e.Name, egc.Name + FROM fp.EntityGroupConfigMapping egcm + INNER JOIN fw.DimEntity e ON egcm.EntityID = e.EntityID + INNER JOIN fp.EntityGroupConfig egc ON egc.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID + INNER JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + + ---------------------------------------------------------------- + -- Other Settings + ---------------------------------------------------------------- + + INSERT INTO #settings (Name, SourceTable, Category, Value, Description) + SELECT + Name, + 'fp.SystemSetting', + 'Feature Flag' AS Category, + Value, + Description + FROM fp.SystemSetting + WHERE IsFeatureFlag = 1 + + INSERT INTO #settings (Name, SourceTable, Category, Value, Description) + SELECT + Name, + 'fp.SystemSetting', + 'System Setting' AS Category, + Value, + Description + FROM fp.SystemSetting + WHERE IsFeatureFlag = 0 + + INSERT INTO #settings (Name, SourceTable, Category, Value, Description) + SELECT + Name, + 'fp.viewBudgetConfigSetting', + 'Plan-Level Feature Flag' AS Category, + Value, + Description + FROM fp.viewBudgetConfigSetting + WHERE BudgetConfigID = @BudgetConfigID + + INSERT INTO #settings (Name, SourceTable, Category, Value, Description, SortOrder) + SELECT 'IsChunkingEnabled - ' + Description, 'fp.AdjustmentChunkingConfiguration', 'Chunking Configuration', IsChunkingEnabled, '', 2 FROM fp.AdjustmentChunkingConfiguration + UNION ALL + SELECT 'MaxAdjustmentsPerChunk - ' + Description, 'fp.AdjustmentChunkingConfiguration', 'Chunking Configuration', MaxAdjustmentsPerChunk, '', 2 FROM fp.AdjustmentChunkingConfiguration + UNION ALL + SELECT 'MaxImportAdjustmentsPerChunk - ' + Description, 'fp.AdjustmentChunkingConfiguration', 'Chunking Configuration', MaxImportAdjustmentsPerChunk, '', 2 FROM fp.AdjustmentChunkingConfiguration + UNION ALL + SELECT 'MaxAdjustmentRecordCountForChunking - ' + Description, 'fp.AdjustmentChunkingConfiguration', 'Chunking Configuration', MaxAdjustmentRecordCountForChunking, '', 2 FROM fp.AdjustmentChunkingConfiguration + + SELECT Name, SourceTable, Category, Value, Description, EntityGroupConfigName FROM #settings ORDER BY SortOrder, SourceTable, Category, EntityGroupConfigName + + END; +GO + + +--------------------------------------------- + +-- fp.procGetChargeVolumeUosData +CREATE PROCEDURE [fp].[procGetChargeVolumeUosData] + @BudgetConfigID INT, + @DepartmentID INT, + @UnitTypeID TINYINT, + @TimeClassID TINYINT, + @IsLoadingRvuByEntity BIT, + @IsLoadingRvuByPatientClass BIT + AS +/********************************************************************* +** Change History +********************************************************************** +** CID Date Author WI Description +** 1 2021-11-10 NT JAZZ-26946 Initial. This is a replacement for func fp.viewChargeVolumeUosDataQuery, which is not the most efficient. +** 2 2021-11-17 MD JAZZ-27519 Update data pull to honor IsDollarsRemovedFromCharges flag on budget config +** 3 2023-04-03 BW JAZZ-52557 Updated for new data model, use [fp].[ChargeVolume] +*********************************************************************/ +BEGIN + SELECT + h.BudgetConfigID, + h.DepartmentID, + COALESCE(xwalk.AccountID, 0) AS AccountID, + CASE xwalk.AccountID WHEN 0 THEN '' ELSE COALESCE(acct.Name, '') END as AccountName, + h.EntityID, + h.PatientClassID, + pc.Name As PatientClassName, + h.ChargeCodeID, + cc.Name As ChargeCodeName, + h.TimeClassID, + h.UnitTypeID, + SUM(h.Value) AS Value, + SUM(h.OriginalValue) AS OriginalValue, + SUM(h.ManagerValue) AS ManagerValue, + COALESCE(fcm.ChargeRate1, 0) AS ChargeRate, -- Note: this is a bug, we cannot assume they are using charge rate 1. + COALESCE(xwalk.RVUWeight, 0) AS RVUWeight + FROM + ( + SELECT + h.BudgetConfigID, + h.DepartmentID, + h.EntityGroupConfigID, + h.EntityID, + h.PatientClassID, + h.ChargeCodeID, + @TimeClassID AS TimeClassID, + @UnitTypeID AS UnitTypeID, + 0 AS Value, + SUM(CASE + WHEN @TimeClassID = 2 AND @UnitTypeID = 145 THEN InitialBudgetTotal + WHEN @TimeClassID = 12 AND @UnitTypeID = 145 THEN InitialProjectionTotal + WHEN @TimeClassID = 2 AND @UnitTypeID = 34 THEN InitialBudgetDollarsTotal + WHEN @TimeClassID = 12 AND @UnitTypeID = 34 THEN InitialProjectionDollarsTotal + END) AS OriginalValue, + 0 AS ManagerValue + FROM + [fp].[ChargeVolume] h + WHERE + h.DepartmentID = @DepartmentID + and h.BudgetConfigID = @BudgetConfigID + GROUP BY + h.BudgetConfigID, + h.DepartmentID, + h.EntityGroupConfigID, + h.EntityID, + h.PatientClassID, + h.ChargeCodeID, + h.UnitTypeID + UNION ALL + SELECT + h.BudgetConfigID, + h.DepartmentID, + h.EntityGroupConfigID, + h.EntityID, + h.PatientClassID, + h.ChargeCodeID, + @TimeClassID AS TimeClassID, + @UnitTypeID AS UnitTypeID, + SUM(CASE + WHEN @UnitTypeID = 145 THEN TargetAdjustedTotal + WHEN @UnitTypeID = 34 THEN TargetDollarsAdjustedTotal + END) AS Value, + 0 AS OriginalValue, + SUM(CASE + WHEN @UnitTypeID = 145 THEN BudgetAdjustedTotal + WHEN @UnitTypeID = 34 THEN BudgetDollarsAdjustedTotal + END) AS ManagerValue + FROM + [fp].[ChargeVolume] h + WHERE + h.DepartmentID = @DepartmentID + AND h.BudgetConfigID = @BudgetConfigID + AND @TimeClassID = 2 + GROUP BY + h.BudgetConfigID, + h.DepartmentID, + h.EntityGroupConfigID, + h.EntityID, + h.PatientClassID, + h.ChargeCodeID, + h.UnitTypeID + UNION ALL + SELECT + h.BudgetConfigID, + h.DepartmentID, + h.EntityGroupConfigID, + h.EntityID, + h.PatientClassID, + h.ChargeCodeID, + @TimeClassID AS TimeClassID, + @UnitTypeID AS UnitTypeID, + SUM(CASE + WHEN @UnitTypeID = 145 THEN ProjectionAdjustedTotal + WHEN @UnitTypeID = 34 THEN ProjectionDollarsAdjustedTotal + END) AS Value, + 0 AS OriginalValue, + SUM(CASE + WHEN @UnitTypeID = 145 THEN ProjectionAdjustedTotal + WHEN @UnitTypeID = 34 THEN ProjectionDollarsAdjustedTotal END) AS ManagerValue + FROM + [fp].[ChargeVolume] h + WHERE + h.DepartmentID = @DepartmentID + AND h.BudgetConfigID = @BudgetConfigID + AND @TimeClassID = 12 + GROUP BY + h.BudgetConfigID, + h.DepartmentID, + h.EntityGroupConfigID, + h.EntityID, + h.PatientClassID, + h.ChargeCodeID, + h.UnitTypeID + ) h + LEFT JOIN [fp].[FactChargeMaster] fcm + ON fcm.BudgetConfigID = h.BudgetConfigID + AND fcm.ChargeCodeID = h.ChargeCodeID + AND fcm.TimeClassID = h.TimeClassID + AND (@IsLoadingRvuByEntity = 0 OR fcm.EntityID = h.EntityID) + AND (@IsLoadingRvuByPatientClass = 0 OR fcm.PatientClassID = h.PatientClassID) + INNER JOIN [fw].[DimChargeCode] cc + ON h.ChargeCodeID = cc.ChargeCodeID + INNER JOIN [fw].[DimPatientClass] pc + ON h.PatientClassID = pc.PatientClassID + LEFT JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] xwalk + ON h.ChargeCodeID = xwalk.ChargeCodeID + AND h.EntityGroupConfigID = xwalk.EntityGroupConfigID + AND h.DepartmentID = xwalk.DepartmentID + AND h.PatientClassID = xwalk.PatientClassID + LEFT JOIN [fw].[DimAccount] acct + ON xwalk.AccountID = acct.AccountID + GROUP BY h.BudgetConfigID, + h.DepartmentID, + h.EntityID, + h.PatientClassID, + pc.Name, + h.ChargeCodeID, + cc.Name, + h.TimeClassID, + h.UnitTypeID, + fcm.ChargeRate1, + xwalk.RVUWeight, + xwalk.AccountID, + acct.Name + ORDER BY h.DepartmentID, pc.Name, cc.Name, CASE xwalk.AccountID WHEN 0 THEN '' ELSE COALESCE(acct.Name, '') END + OPTION (RECOMPILE) + + END +GO + + +--------------------------------------------- + +-- fp.procGetDepartmentChargeVolumeHistoricalData +CREATE PROCEDURE [fp].[procGetDepartmentChargeVolumeHistoricalData] + @BudgetConfigID INT, + @DepartmentID INT, + @UnitTypeID INT + AS +/********************************************************************* +** Change History +********************************************************************** +** CID Date Author WI Description +** 1 2021-11-10 NT JAZZ-26946 Initial. This is a replacement for func fp.viewDepartmentChargeVolumeHistoricalDataQuery, which is not the most efficient. +** 2 2021-11-17 MD JAZZ-27519 Updating proc to honor IsDollarsRemovedFromCharges flag on budget config +** 3 2023-04-03 BW JAZZ-52557 Updated for new data model, use [fp].[ChargeVolume] +*********************************************************************/ + BEGIN + + SELECT + fcv.DepartmentID, + COALESCE(xwalk.AccountID, 0) AS AccountID, + CASE xwalk.AccountID WHEN 0 THEN '' ELSE COALESCE(acct.Name, '') END as AccountName, + fcv.EntityID, + fcv.PatientClassID, + pc.Name as PatientClassName, + fcv.ChargeCodeID, + cc.Name AS ChargeCodeName, + @UnitTypeID AS UnitTypeID, + SUM(CASE WHEN @UnitTypeID = 145 THEN PriorYearActualValueTotal ELSE PriorYearActualDollarValueTotal END) AS Actual, + SUM(CASE WHEN @UnitTypeID = 145 THEN ActualYTDValueTotal ELSE ActualYTDDollarValueTotal END) AS ActualYTD + FROM [fp].[ChargeVolumeHistory] h + INNER JOIN [fp].[ChargeVolume] fcv + ON h.ChargeVolumeID = fcv.ChargeVolumeID + LEFT JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] xwalk + ON fcv.ChargeCodeID = xwalk.ChargeCodeID + AND fcv.EntityGroupConfigID = xwalk.EntityGroupConfigID + AND fcv.DepartmentID = xwalk.DepartmentID + AND fcv.PatientClassID = xwalk.PatientClassID + LEFT JOIN [fw].[DimAccount] acct on xwalk.AccountID = acct.AccountID + INNER JOIN [fw].[DimChargeCode] cc on fcv.ChargeCodeID = cc.ChargeCodeID + INNER JOIN [fw].[DimPatientClass] pc on fcv.PatientClassID = pc.PatientClassID + WHERE + fcv.DepartmentID = @DepartmentID + AND fcv.BudgetConfigID = @BudgetConfigID + GROUP BY + fcv.DepartmentID, + fcv.EntityID, + fcv.PatientClassID, + fcv.ChargeCodeID, + fcv.UnitTypeID, + xwalk.AccountID, + acct.Name, + pc.Name, + cc.Name + ORDER BY fcv.DepartmentID, pc.Name, cc.Name, CASE xwalk.AccountID WHEN 0 THEN '' ELSE COALESCE(acct.Name, '') END + OPTION (RECOMPILE) + END +GO + + +--------------------------------------------- + +-- fp.procGetFlexingExceptionReport +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 05-18-2023 MY JAZZ-55153 Updated view to restructure +** 2 08-25-2023 MY JAZZ-59500 Updated view to restructure +*************************************************************/ +CREATE PROCEDURE fp.procGetFlexingExceptionReport + AS + BEGIN + CREATE TABLE #Results (BudgetConfigID INT, FlexingMethodID INT, FlexingTypeID INT, DepartmentID INT, DepartmentName NVARCHAR(500), AccountID INT, AccountName NVARCHAR(500), Message NVARCHAR(MAX)) + + SELECT config.*, efc.EntityGroupConfigID + INTO #StatisticsFlexing + FROM [fp].[StatisticsFlexingConfig] config + INNER JOIN [fp].[EntityGroupConfig] efc ON config.EntityGroupConfigGUID = efc.EntityGroupConfigGUID + WHERE FlexMethodID != 6 + + INSERT INTO #Results (BudgetConfigID, FlexingMethodID, FlexingTypeID, DepartmentID, AccountID, Message) + SELECT DISTINCT fs.BudgetConfigID, 10, 5, fs.DepartmentID, fs.AccountID, 'Department contains an account to be flexed by total charge code budget, but has no charge volumes.' + FROM [fp].[FactStatistics] fs + INNER JOIN #StatisticsFlexing config ON fs.EntityGroupConfigID = config.EntityGroupConfigID AND fs.AccountID = config.AccountID + LEFT JOIN [fp].[ChargeVolume] cv + ON fs.EntityGroupConfigID = cv.EntityGroupConfigID + AND fs.DepartmentID = cv.DepartmentID + WHERE config.FlexMethodID = 10 + AND cv.ChargeVolumeID IS NULL + + INSERT INTO #Results (BudgetConfigID, FlexingMethodID, FlexingTypeID, DepartmentID, AccountID, Message) + SELECT DISTINCT fs.BudgetConfigID, 9, 5, fs.DepartmentID, fs.AccountID, 'Department contains a patient class to be flexed by charge code budget, but has no charge volumes.' + FROM [fp].[FactStatistics] fs + INNER JOIN #StatisticsFlexing config ON fs.EntityGroupConfigID = config.EntityGroupConfigID AND fs.AccountID = config.AccountID + LEFT JOIN [fp].[ChargeVolume] cv + ON fs.EntityGroupConfigID = cv.EntityGroupConfigID + AND fs.DepartmentID = cv.DepartmentID + AND fs.PatientClassID = cv.PatientClassID + WHERE config.FlexMethodID = 9 + AND cv.ChargeVolumeID IS NULL + + INSERT INTO #Results (BudgetConfigID, FlexingMethodID, FlexingTypeID, AccountID, Message) + SELECT DISTINCT basis.BudgetConfigID, config.FlexMethodID, 2, basis.AccountID, 'Account is marked to flex, but has no accounts in Statistics.' + FROM [fp].[FactStatistics] basis + LEFT JOIN #StatisticsFlexing config ON basis.EntityGroupConfigID = config.EntityGroupConfigID AND basis.AccountID = config.AccountID + WHERE config.AccountID IS NULL + + SELECT config.*, efc.EntityGroupConfigID + INTO #RevenueFlexing + FROM [fp].[RevenueExpenseFlexingConfig] config + INNER JOIN [fp].[EntityGroupConfig] efc ON config.EntityGroupConfigGUID = efc.EntityGroupConfigGUID + WHERE FlexMethodID NOT IN (2, 6) + + INSERT INTO #Results (BudgetConfigID, FlexingMethodID, FlexingTypeID, DepartmentID, Message) + SELECT DISTINCT basis.BudgetConfigID, 3, 2, basis.DepartmentID, 'Department is marked to be flexed by charge code budget, but has no charge volumes.' + FROM [fp].[FactGeneralLedger] basis + INNER JOIN #RevenueFlexing config ON basis.EntityGroupConfigID = config.EntityGroupConfigID AND basis.DepartmentID = config.DepartmentID + LEFT JOIN [fp].[ChargeVolume] cv + ON basis.EntityGroupConfigID = cv.EntityGroupConfigID + AND basis.DepartmentID = cv.DepartmentID + WHERE config.FlexMethodID = 3 + AND cv.ChargeVolumeID IS NULL + + INSERT INTO #Results (BudgetConfigID, FlexingMethodID, FlexingTypeID, DepartmentID, Message) + SELECT DISTINCT basis.BudgetConfigID, config.FlexMethodID, 2, basis.DepartmentID, 'Department is marked to flex, but has no accounts in GL.' + FROM [fp].[GeneralLedger] basis + LEFT JOIN #RevenueFlexing config ON basis.EntityGroupConfigID = config.EntityGroupConfigID AND basis.DepartmentID = config.DepartmentID + WHERE config.DepartmentID IS NULL + + INSERT INTO #Results (BudgetConfigID, FlexingMethodID, FlexingTypeID, DepartmentID, Message) + SELECT DISTINCT basis.BudgetConfigID, config.FlexMethodID, 2, basis.DepartmentID, 'Department is marked to be flexed by statistics, but has no primary statistics.' + FROM [fp].[GeneralLedger] basis + INNER JOIN #RevenueFlexing config ON basis.EntityGroupConfigID = config.EntityGroupConfigID AND basis.DepartmentID = config.DepartmentID + INNER JOIN [fp].[PrimaryStatisticsConfig] prim ON prim.EntityGroupConfigGUID = config.EntityGroupConfigGUID + LEFT JOIN [fp].[FactStatistics] cv + ON basis.EntityGroupConfigID = cv.EntityGroupConfigID + AND basis.DepartmentID = cv.DepartmentID + AND prim.DepartmentID = cv.DepartmentID + AND prim.AccountID = cv.AccountID + AND prim.IsRevenue = 1 + WHERE config.FlexMethodID IN (4, 3) + AND cv.StatisticsID IS NULL + + + UPDATE r + SET r.DepartmentName = dept.Name + FROM #Results r + INNER JOIN [fw].[DimDepartment] dept ON r.DepartmentID = dept.DepartmentID + + UPDATE r + SET r.AccountName = acc.Name + FROM #Results r + INNER JOIN [fw].[DimAccount] acc ON r.AccountID = acc.AccountID + + UPDATE #Results SET DepartmentName = '' WHERE DepartmentName IS NULL + UPDATE #Results SET DepartmentID = -1 WHERE DepartmentID IS NULL + UPDATE #Results SET AccountName = '' WHERE AccountName IS NULL + UPDATE #Results SET AccountID = -1 WHERE AccountID IS NULL + UPDATE #Results SET FlexingMethodID = -1 WHERE FlexingMethodID IS NULL + + SELECT * FROM #Results + END +GO + + +--------------------------------------------- + +-- fp.procGetGLVariableDataForServiceLineVolumeFlexing +CREATE PROCEDURE [fp].[procGetGLVariableDataForServiceLineVolumeFlexing] + @EntityGroupConfigGUID UNIQUEIDENTIFIER, + @EntityGroupConfigID INT, + @FiscalYearID SMALLINT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + AS + BEGIN + /********************************************************************* + ** Change History + ********************************************************************** + ** CID Date Author WI Description + ** 1 2021-09-10 NT JAZZ-25494 Initial. This is a replacemnet for funcGetGLVariableDataForServiceLineVolumeFlexing that contained the dreaded "OR DepartmentID IS NULL" clause and unnecessary REPLACE + ** 2 2021-09-24 MD JAZZ-25923 Update load to inner join on fp.FlexConfigMap + ** 3 2022-08-12 BW JAZZ-40536 Update load to include projection + ** 4 2023-08-14 BW JAZZ-58199 Data model restructure for GL + ** 5 2023-08-14 MY JAZZ-59598 Update view to pull correct values + *********************************************************************/ + + EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment' + EXEC [dbo].[procSysDropTempTable] '#FilteredData' + EXEC [dbo].[procSysDropTempTable] '#glPivoted' + EXEC [dbo].[procSysDropTempTable] '#GLData' + + DECLARE @IsProjectionFlexingEnabled bit + SELECT @IsProjectionFlexingEnabled = CAST(Value AS BIT) + FROM fp.SystemSetting + WHERE Name = 'Is Baseline And Projection PAF Enabled' + + CREATE TABLE #GLData ( + BasisID INT, + BudgetPhaseID TINYINT, + TimeClassID TINYINT, + DepartmentID INT, + AccountID INT, + FiscalYearID SMALLINT, + FiscalMonthID TINYINT, + OriginalValue DECIMAL(19,8), + PercentAdjustmentFactor DECIMAL(19,8) + ) + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #FilteredData (GeneralLedgerID INT PRIMARY KEY CLUSTERED) + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + + INSERT INTO #FilteredData + SELECT fg.GeneralLedgerID + FROM [fp].[GeneralLedger] fg + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = fg.DepartmentID + WHERE fg.EntityGroupConfigID = @EntityGroupConfigID + AND fg.VariabilityID = 2 --Variable + + END ELSE BEGIN + + INSERT INTO #FilteredData + SELECT fg.GeneralLedgerID + FROM [fp].[GeneralLedger] fg + WHERE fg.EntityGroupConfigID = @EntityGroupConfigID + AND fg.VariabilityID = 2 --Variable + + END + + SELECT + gl.GeneralLedgerID, + gl.BudgetConfigID, + gl.EntityGroupConfigID, + gl.EntityID, + gl.DepartmentID, + gl.AccountID, + gl.FinancialReportingID, + gl.APEModelSectionID, + gl.VariabilityID, + 34 AS UnitTypeID, + m.FiscalMonthID, + TargetAdjusted, + BudgetAdjusted, + ProjectionAdjusted, + TargetPercentAdjustmentFactor, + BudgetPercentAdjustmentFactor, + ProjectionPercentAdjustmentFactor + INTO #glPivoted + FROM fp.GeneralLedger gl + INNER JOIN #FilteredData ft ON ft.GeneralLedgerID = gl.GeneralLedgerID + INNER JOIN [fp].[viewNonStaffingExpenseAccounts] acc ON gl.AccountID = acc.AccountID -- Patient Activity Flexing for GL can only affect non-staffing accounts + INNER JOIN [fp].[FlexConfigMapping] map + ON gl.DepartmentID = map.DepartmentID + AND gl.AccountID = map.GLAccountID + AND gl.EntityGroupConfigID = map.EntityGroupConfigID + AND map.FlexingTypeID = 7 + CROSS APPLY ( + VALUES + (01, TargetAdjusted01, BudgetAdjusted01, ProjectionAdjusted01, TargetPercentAdjustmentFactor01, BudgetPercentAdjustmentFactor01, ProjectionPercentAdjustmentFactor01), + (02, TargetAdjusted02, BudgetAdjusted02, ProjectionAdjusted02, TargetPercentAdjustmentFactor02, BudgetPercentAdjustmentFactor02, ProjectionPercentAdjustmentFactor02), + (03, TargetAdjusted03, BudgetAdjusted03, ProjectionAdjusted03, TargetPercentAdjustmentFactor03, BudgetPercentAdjustmentFactor03, ProjectionPercentAdjustmentFactor03), + (04, TargetAdjusted04, BudgetAdjusted04, ProjectionAdjusted04, TargetPercentAdjustmentFactor04, BudgetPercentAdjustmentFactor04, ProjectionPercentAdjustmentFactor04), + (05, TargetAdjusted05, BudgetAdjusted05, ProjectionAdjusted05, TargetPercentAdjustmentFactor05, BudgetPercentAdjustmentFactor05, ProjectionPercentAdjustmentFactor05), + (06, TargetAdjusted06, BudgetAdjusted06, ProjectionAdjusted06, TargetPercentAdjustmentFactor06, BudgetPercentAdjustmentFactor06, ProjectionPercentAdjustmentFactor06), + (07, TargetAdjusted07, BudgetAdjusted07, ProjectionAdjusted07, TargetPercentAdjustmentFactor07, BudgetPercentAdjustmentFactor07, ProjectionPercentAdjustmentFactor07), + (08, TargetAdjusted08, BudgetAdjusted08, ProjectionAdjusted08, TargetPercentAdjustmentFactor08, BudgetPercentAdjustmentFactor08, ProjectionPercentAdjustmentFactor08), + (09, TargetAdjusted09, BudgetAdjusted09, ProjectionAdjusted09, TargetPercentAdjustmentFactor09, BudgetPercentAdjustmentFactor09, ProjectionPercentAdjustmentFactor09), + (10, TargetAdjusted10, BudgetAdjusted10, ProjectionAdjusted10, TargetPercentAdjustmentFactor10, BudgetPercentAdjustmentFactor10, ProjectionPercentAdjustmentFactor10), + (11, TargetAdjusted11, BudgetAdjusted11, ProjectionAdjusted11, TargetPercentAdjustmentFactor11, BudgetPercentAdjustmentFactor11, ProjectionPercentAdjustmentFactor11), + (12, TargetAdjusted12, BudgetAdjusted12, ProjectionAdjusted12, TargetPercentAdjustmentFactor12, BudgetPercentAdjustmentFactor12, ProjectionPercentAdjustmentFactor12) + ) AS CrossApplied (MonthSortOrder, TargetAdjusted, BudgetAdjusted, ProjectionAdjusted, TargetPercentAdjustmentFactor, BudgetPercentAdjustmentFactor, ProjectionPercentAdjustmentFactor) + LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder + WHERE gl.EntityGroupConfigID = @EntityGroupConfigID + + INSERT INTO #GLData (BasisID, BudgetPhaseID, TimeClassID, DepartmentID, AccountID, FiscalYearID, FiscalMonthID, OriginalValue, PercentAdjustmentFactor) + SELECT + GeneralLedgerID AS BasisID, + CAST(2 AS TINYINT) AS BudgetPhaseID, + CAST(2 AS TINYINT) AS TimeClassID, + DepartmentID, + AccountID, + @FiscalYearID as FiscalYearID, + FiscalMonthID, + TargetAdjusted AS OriginalValue, + TargetPercentAdjustmentFactor AS PercentAdjustmentFactor + FROM #glPivoted + + INSERT INTO #GLData (BasisID, BudgetPhaseID, TimeClassID, DepartmentID, AccountID, FiscalYearID, FiscalMonthID, OriginalValue, PercentAdjustmentFactor) + SELECT + GeneralLedgerID AS BasisID, + CAST(3 AS TINYINT) AS BudgetPhaseID, + CAST(2 AS TINYINT) AS TimeClassID, + DepartmentID, + AccountID, + @FiscalYearID as FiscalYearID, + FiscalMonthID, + BudgetAdjusted AS OriginalValue, + BudgetPercentAdjustmentFactor AS PercentAdjustmentFactor + FROM #glPivoted + + IF(@IsProjectionFlexingEnabled = 1) -- JAZZ-40536 + BEGIN + + INSERT INTO #GLData (BasisID, BudgetPhaseID, TimeClassID, DepartmentID, AccountID, FiscalYearID, FiscalMonthID, OriginalValue, PercentAdjustmentFactor) + SELECT + GeneralLedgerID AS BasisID, + CAST(2 AS TINYINT) AS BudgetPhaseID, + CAST(12 AS TINYINT) AS TimeClassID, + DepartmentID, + AccountID, + @FiscalYearID as FiscalYearID, -- This is technically wrong, but leaving it for now as I don't know what this might impact. + FiscalMonthID, + ProjectionAdjusted AS OriginalValue, + ProjectionPercentAdjustmentFactor AS PercentAdjustmentFactor + FROM #glPivoted + + END + + -- Return final results + SELECT * FROM #GLData + + END +GO + + +--------------------------------------------- + +-- fp.procGetGLVariableDataForServiceLineVolumeFlexing_Initial +CREATE PROCEDURE [fp].[procGetGLVariableDataForServiceLineVolumeFlexing_Initial] + @EntityGroupConfigGUID UNIQUEIDENTIFIER, + @EntityGroupConfigID INT, + @FiscalYearID SMALLINT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + AS + BEGIN + /********************************************************************* + ** Change History + ********************************************************************** + ** CID Date Author WI Description + ** 1 2022-08-16 BW JAZZ-40536 Initial + ** 2 2023-08-09 BW JAZZ-58199 Data model restructure for GL + *********************************************************************/ + + EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment' + EXEC [dbo].[procSysDropTempTable] '#FilteredData' + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #FilteredData (GeneralLedgerID INT PRIMARY KEY CLUSTERED) + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilteredData + SELECT fg.GeneralLedgerID + FROM [fp].[GeneralLedger] fg + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = fg.DepartmentID + WHERE fg.EntityGroupConfigID = @EntityGroupConfigID + AND fg.VariabilityID = 2 --Variable + END ELSE BEGIN + INSERT INTO #FilteredData + SELECT fg.GeneralLedgerID + FROM [fp].[GeneralLedger] fg + WHERE fg.EntityGroupConfigID = @EntityGroupConfigID + AND fg.VariabilityID = 2 --Variable + END + + SELECT + GeneralLedgerID AS BasisID, + CAST(2 AS TINYINT) AS BudgetPhaseID, + CAST(2 AS TINYINT) AS TimeClassID, + DepartmentID, + AccountID, + @FiscalYearID as FiscalYearID, + FiscalMonthID, + OriginalValue + FROM + (SELECT + fg.GeneralLedgerID, + fg.DepartmentID, + fg.AccountID, + fg.InitialBudget01 AS 'Month01', + fg.InitialBudget02 AS 'Month02', + fg.InitialBudget03 AS 'Month03', + fg.InitialBudget04 AS 'Month04', + fg.InitialBudget05 AS 'Month05', + fg.InitialBudget06 AS 'Month06', + fg.InitialBudget07 AS 'Month07', + fg.InitialBudget08 AS 'Month08', + fg.InitialBudget09 AS 'Month09', + fg.InitialBudget10 AS 'Month10', + fg.InitialBudget11 AS 'Month11', + fg.InitialBudget12 AS 'Month12' + FROM + [fp].[GeneralLedger] fg + INNER JOIN #FilteredData ft ON ft.GeneralLedgerID = fg.GeneralLedgerID + INNER JOIN [fp].[viewNonStaffingExpenseAccounts] acc ON fg.AccountID = acc.AccountID -- Patient Activity Flexing for GL can only affect non-staffing accounts + INNER JOIN [fp].[FlexConfigMapping] map + ON fg.DepartmentID = map.DepartmentID + AND fg.AccountID = map.GLAccountID + AND fg.EntityGroupConfigID = map.EntityGroupConfigID + WHERE map.FlexingTypeID = 7) PIV + UNPIVOT(OriginalValue FOR FiscalMonth IN ([Month01], [Month02], [Month03], [Month04], [Month05], [Month06], [Month07], [Month08], [Month09], [Month10], [Month11], [Month12])) AS f + LEFT JOIN fw.DImFiscalMonth m WITH (readuncommitted) ON m.MonthColumnName = f.FiscalMonth + + END +GO + + +--------------------------------------------- + +-- fp.procGetNonStaffingFlexingExceptionItems +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2024-09-12 MZ/MY JAZZ-75490 Created proc +** 2 2024-09-19 NH JAZZ-77178 Updated message +** 3 2024-09-24 MY JAZZ-76786 Pass in Budget Config for inactive configs +*************************************************************/ +CREATE PROCEDURE [fp].[procGetNonStaffingFlexingExceptionItems] + @IsInitialPlansEnabled BIT = 0, + @BudgetConfigID INT = 0, + @IsDebug BIT = 0 +AS +BEGIN + + EXEC [dbo].[procSysDropTempTable] '#accountsToValidate' + EXEC [dbo].[procSysDropTempTable] '#missingPrimaryStats' + EXEC [dbo].[procSysDropTempTable] '#finalValidatedTable' + EXEC [dbo].[procSysDropTempTable] '#statisticsMapping' + EXEC [dbo].[procSysDropTempTable] '#missingStatistics' + EXEC [dbo].[procSysDropTempTable] '#statisticsWithZeroValues' + EXEC [dbo].[procSysDropTempTable] '#noFlexConfigMapping' + EXEC [dbo].[procSysDropTempTable] '#timeClassByEgc' + EXEC [dbo].[procSysDropTempTable] '#statisticsHistoryMissing' + EXEC [dbo].[procSysDropTempTable] '#revenueHistoryMissing' + + CREATE TABLE #finalValidatedTable ( + DepartmentID INT, + AccountID INT, + FlexMethodID INT, + FlexMethod NVARCHAR(MAX), + Detail NVARCHAR(MAX), + EntityGroupConfigGUID UNIQUEIDENTIFIER, + EntityGroupConfigName NVARCHAR(MAX), + IsNew INT + ) + + SELECT EntityGroupConfigID, EntityGroupConfigGUID, AccountFiscalYearID, AccountTimeClassID + INTO #timeClassByEgc + FROM fp.EntityGroupConfig + + -- Populate NonStaffing records that we can check has Statistics or not. By default, + -- NonStaffing accounts are 100% Variable so we don't need to check if it's Variable or not. + -- Populates: #accountsToValidate + SELECT DISTINCT + dep.DepartmentID, + acc.AccountID, + flex.FlexMethodID, + 'Statistics Accounts' AS FlexMethod, + '' AS Detail, + ec.EntityGroupConfigGUID, + ec.Name, + gl.IsNew + INTO #accountsToValidate + FROM fp.GeneralLedger gl + INNER JOIN fw.DimDepartment dep ON dep.DepartmentID = gl.DepartmentID + INNER JOIN fw.DimAccount acc ON acc.AccountID = gl.AccountID + INNER join fp.BudgetConfig bc ON bc.BudgetConfigID = gl.BudgetConfigID + INNER JOIN fp.EntityGroupConfig ec ON ec.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.ModelSectionMap map ON map.APEModelSectionID = gl.APEModelSectionID + INNER JOIN fp.NonStaffingExpenseFlexingConfig flex ON flex.DepartmentID = gl.DepartmentID + AND flex.EntityGroupConfigGUID = ec.EntityGroupConfigGUID + INNER JOIN fp.NonStaffingVariabilityConfig nsvb ON ec.EntityGroupConfigGUID = nsvb.EntityGroupConfigGUID + AND gl.AccountID = nsvb.AccountID + LEFT JOIN fp.NonStaffingExpenseFlexingOverrideConfig ovr ON ovr.EntityGroupConfigGUID = ec.EntityGroupConfigGUID + AND ovr.DepartmentID = gl.DepartmentID + AND ovr.AccountID = gl.AccountID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND map.APEModelSectionName = 'Non-Staffing' + AND gl.VariabilityID = 2 -- Merely limiting the records as VariabilityID != Variability Percentage + AND flex.flexMethodID = 1 -- Statistic Accounts + AND dep.OBIsDefined = 1 + AND nsvb.Variability > 0 -- Only find accounts that are at least partial variabile + AND (ovr.OverrideFlexConfigGUID IS NULL OR (ovr.FlexMethodID != 6 AND ovr.FlexMethodID != 2)) -- 6 = Fixed, 2 = Patient Activity + + IF (@IsDebug = 1) + BEGIN + SELECT '#accountsToValidate' AS '#accountsToValidate', * FROM #accountsToValidate + END + + -- Check to see if there are Primary Statistics configured or not + SELECT DISTINCT + atv.DepartmentID, + atv.AccountID, + atv.FlexMethodID, + atv.FlexMethod, + atv.EntityGroupConfigGUID, + atv.Name, + atv.IsNew + INTO #missingPrimaryStats + FROM #accountsToValidate atv + LEFT JOIN fp.PrimaryStatisticsConfig psc ON atv.DepartmentID = psc.DepartmentID + AND atv.EntityGroupConfigGUID = psc.EntityGroupConfigGUID + AND psc.IsNonStaffing = 1 + LEFT JOIN fp.NonStaffingExpenseFlexingOverrideConfig ovr ON atv.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID + AND ovr.DepartmentID = atv.DepartmentID + AND ovr.AccountID = atv.AccountID + WHERE psc.RowID IS NULL + AND ovr.OverrideFlexConfigGUID IS NULL + + IF (@IsDebug = 1) + BEGIN + SELECT '#missingPrimaryStats' AS '#missingPrimaryStats', * FROM #missingPrimaryStats + END + + -- If there are any missing primary stats, add them to the final validation. Doing this first to weed out + -- potential duplicates down the line + IF EXISTS (SELECT 1 FROM #missingPrimaryStats) + BEGIN + INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + AccountID, + FlexMethodID, + FlexMethod, + 'Department/Account is set up for flexing but has no primary statistics configured for non-staffing. To resolve, add primary statistics for this department.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #missingPrimaryStats + + DELETE atv + FROM #accountsToValidate atv + INNER JOIN #missingPrimaryStats mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID + END + + -- Build a mapping of Department/Account to Statististics Department/Account + -- First build it without overrides + SELECT DISTINCT + atv.DepartmentID, + atv.AccountID, + atv.FlexMethodID, + atv.FlexMethod, + atv.EntityGroupConfigGUID, + atv.Name, + COALESCE(pscs.DepartmentID, psc.DepartmentID) AS StatisticsDepartmentID, + psc.AccountID AS StatisticsAccountID, + atv.IsNew + INTO #statisticsMapping + FROM #accountsToValidate atv + INNER JOIN fp.PrimaryStatisticsConfig psc ON atv.DepartmentID = psc.DepartmentID + AND atv.EntityGroupConfigGUID = psc.EntityGroupConfigGUID + AND psc.IsNonStaffing = 1 + INNER JOIN fp.EntityGroupConfig ecc ON ecc.EntityGroupConfigGUID = atv.EntityGroupConfigGUID + INNER JOIN fp.BudgetConfig bcs ON ecc.BudgetConfigGUID = bcs.BudgetConfigGUID + LEFT JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscs ON psc.RowID = pscs.PrimaryStatisticsConfigID + LEFT JOIN fp.NonStaffingExpenseFlexingOverrideConfig ovr ON atv.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID + AND ovr.DepartmentID = atv.DepartmentID + AND ovr.AccountID = atv.AccountID + WHERE ovr.OverrideFlexConfigGUID IS NULL + + -- Now build the overrides + INSERT INTO #statisticsMapping (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, StatisticsDepartmentID, StatisticsAccountID, IsNew) + SELECT DISTINCT + atv.DepartmentID, + atv.AccountID, + atv.FlexMethodID, + atv.FlexMethod, + atv.EntityGroupConfigGUID, + atv.Name, + ovr.DepartmentID AS StatisticsDepartmentID, + ass.AccountID AS StatisticsAccountID, + IsNew + FROM #accountsToValidate atv + INNER JOIN fp.EntityGroupConfig ecc ON ecc.EntityGroupConfigGUID = atv.EntityGroupConfigGUID + INNER JOIN fp.BudgetConfig bcs ON ecc.BudgetConfigGUID = bcs.BudgetConfigGUID + INNER JOIN fp.NonStaffingExpenseFlexingOverrideConfig ovr ON atv.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID + AND ovr.DepartmentID = atv.DepartmentID + AND ovr.AccountID = atv.AccountID + INNER JOIN fp.NSOverrideFlexConfigAssignment ass ON ovr.OverrideFlexConfigGUID = ass.OverrideFlexConfigGUID + + IF (@IsDebug = 1) + BEGIN + SELECT '#statisticsMapping' AS '#statisticsMapping', * FROM #statisticsMapping + END + + -- Next, we need to check to see if Primary Stats exist, but there are no Statistics for it + SELECT DISTINCT + sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + INTO #missingStatistics + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID + LEFT JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.StatisticsDepartmentID = fs.DepartmentID + AND sm.StatisticsAccountID = fs.AccountID + GROUP BY sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING COUNT(fs.StatisticsID) = 0 + + IF (@IsDebug = 1) + BEGIN + SELECT '#missingStatistics' AS '#missingStatistics', * FROM #missingStatistics + END + + IF EXISTS (SELECT 1 FROM #missingStatistics) + BEGIN + INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + AccountID, + FlexMethodID, + FlexMethod, + 'Department/Account is set up for flexing but has no statistics data. To resolve, add budget or projection statistic volumes in Plan Editor or change department flex method in entity group configuration.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #missingStatistics + + DELETE atv + FROM #accountsToValidate atv + INNER JOIN #missingStatistics mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID + + DELETE atv + FROM #statisticsMapping atv + INNER JOIN #missingStatistics mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID + END + + -- Next, check for cases where we have statistics, but they are zero + SELECT DISTINCT + sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + 12 AS TimeClassID, + sm.IsNew + INTO #statisticsWithZeroValues + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID + INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.StatisticsDepartmentID = fs.DepartmentID + AND sm.StatisticsAccountID = fs.AccountID + INNER JOIN fp.FactStatisticsBudget fsb ON fsb.StatisticsID = fs.StatisticsID AND fsb.BudgetPhaseID = 3 + INNER JOIN fp.FactStatisticsProjection fsp ON fsp.StatisticsID = fs.StatisticsID AND fsp.BudgetPhaseID = 3 + GROUP BY sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING ( + SUM(CASE WHEN bc.MonthsLoaded = 1 THEN fsp.AdjustedValue02 + fsp.AdjustedValue03 + fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 2 THEN fsp.AdjustedValue03 + fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 3 THEN fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 4 THEN fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 5 THEN fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 6 THEN fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 7 THEN fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 8 THEN fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 9 THEN fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 10 THEN fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 11 THEN fsp.AdjustedValue12 END + ) = 0 -- Non Zero volume data for driver statistics - Projection, made it a sum to consider that there can be multiple records for provider + ) + + INSERT #statisticsWithZeroValues (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, TimeClassID, IsNew) + SELECT DISTINCT + sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + 2 AS TimeClassID, + sm.IsNew + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID + INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.StatisticsDepartmentID = fs.DepartmentID + AND sm.StatisticsAccountID = fs.AccountID + INNER JOIN fp.FactStatisticsBudget fsb ON fsb.StatisticsID = fs.StatisticsID AND fsb.BudgetPhaseID = 3 + GROUP BY sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING ( + SUM(fsb.AdjustedValueTotal) = 0 + ) + + INSERT #statisticsWithZeroValues (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, TimeClassID, IsNew) + SELECT DISTINCT + sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + 22 AS TimeClassID, + sm.IsNew + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID + INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.StatisticsDepartmentID = fs.DepartmentID + AND sm.StatisticsAccountID = fs.AccountID + INNER JOIN fp.FactStatisticsBudget fsb ON fsb.StatisticsID = fs.StatisticsID AND fsb.BudgetPhaseID = 2 + GROUP BY sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING ( + SUM(fsb.AdjustedValueTotal) = 0 + ) + + IF (@IsDebug = 1) + BEGIN + SELECT '#statisticsWithZeroValues' AS '#statisticsWithZeroValues', * FROM #statisticsWithZeroValues + END + + IF EXISTS (SELECT 1 FROM #statisticsWithZeroValues) + BEGIN + INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + AccountID, + FlexMethodID, + FlexMethod, + 'Department/Account is set up for flexing but the statistics are zero for projection. To resolve, add projection statistic volumes in Plan Editor or change department flex method in entity group configuration.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #statisticsWithZeroValues + WHERE TimeClassID = 12 + + INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + AccountID, + FlexMethodID, + FlexMethod, + 'Department/Account is set up for flexing but the statistics are zero for budget. To resolve, add budget statistic volumes in Plan Editor or change department flex method in entity group configuration.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #statisticsWithZeroValues + WHERE TimeClassID = 2 + + INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + AccountID, + FlexMethodID, + FlexMethod, + 'Department/Account is set up for flexing but the statistics are zero for target. To resolve, add target statistic volumes in Plan Editor or change department flex method in entity group configuration.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #statisticsWithZeroValues + WHERE TimeClassID = 22 + + DELETE atv + FROM #accountsToValidate atv + INNER JOIN #statisticsWithZeroValues mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID + + DELETE atv + FROM #statisticsMapping atv + INNER JOIN #statisticsWithZeroValues mps ON atv.DepartmentID = mps.DepartmentID AND atv.AccountID = mps.AccountID + END + + -- This only works for when Initial Plan is disabled + IF (@IsInitialPlansEnabled = 0) + BEGIN + + -- We need to check the historical data to ensure the rate is calculate correctly + -- aka [fp].[procSampleGLDollarsPerUOS]. + SELECT DISTINCT + sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + INTO #statisticsHistoryMissing + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID + INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.StatisticsDepartmentID = fs.DepartmentID + AND sm.StatisticsAccountID = fs.AccountID + INNER JOIN fp.FactStatisticsHistory hist ON hist.StatisticsID = fs.StatisticsID + INNER JOIN #timeClassByEgc tcEgc ON tcEgc.EntityGroupConfigID = fs.EntityGroupConfigID + GROUP BY sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING ( + SUM(CASE + WHEN tcEgc.AccountFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.AccountTimeClassID = 1 THEN hist.ActualYTDValueTotal + WHEN tcEgc.AccountFiscalYearID = bc.FiscalYearID - 2 AND tcEgc.AccountTimeClassID = 1 THEN hist.PriorYearActualValueTotal + WHEN tcegc.AccountFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.AccountTimeClassID = 2 THEN hist.CurrentYearBudgetTotal + ELSE 0 END + ) = 0 -- Non Zero volume data for driver statistics - Projection, made it a sum to consider that there can be multiple records for provider + ) + + SELECT DISTINCT + sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + INTO #revenueHistoryMissing + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN [fp].[GeneralLedger] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.DepartmentID = fs.DepartmentID + AND sm.AccountID = fs.AccountID + INNER JOIN fp.GeneralLedgerHistory hist ON hist.GeneralLedgerID = fs.GeneralLedgerID + INNER JOIN #timeClassByEgc tcEgc ON tcEgc.EntityGroupConfigID = fs.EntityGroupConfigID + GROUP BY sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING ( + SUM(CASE + WHEN tcEgc.AccountFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.AccountTimeClassID = 1 THEN hist.ActualYTDValueTotal + WHEN tcEgc.AccountFiscalYearID = bc.FiscalYearID - 2 AND tcEgc.AccountTimeClassID = 1 THEN hist.PriorYearActualValueTotal + WHEN tcegc.AccountFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.AccountTimeClassID = 2 THEN hist.CurrentYearBudgetTotal + ELSE 0 END + ) = 0 -- Non Zero volume data for driver statistics - Projection, made it a sum to consider that there can be multiple records for provider + ) + + IF (@IsDebug = 1) + BEGIN + SELECT '#statisticsHistoryMissing' AS '#statisticsHistoryMissing', * FROM #statisticsHistoryMissing + SELECT '#revenueHistoryMissing' AS '#revenueHistoryMissing', * FROM #revenueHistoryMissing + END + + IF EXISTS (SELECT 1 FROM #statisticsHistoryMissing) OR EXISTS(SELECT 1 FROM #revenueHistoryMissing) + BEGIN + INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + AccountID, + FlexMethodID, + FlexMethod, + -- If you need to debug this, you can look at [fp].[procSampleGLDollarsPerUOS] + 'Department/Account is missing historical statistics data, resulting in a calculated rate of zero.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #statisticsHistoryMissing + + INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + AccountID, + FlexMethodID, + FlexMethod, + -- If you need to debug this, you can look at [fp].[procSampleGLDollarsPerUOS] + 'Department/Account is missing historical non-staffing data, resulting in a calculated rate of zero.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #revenueHistoryMissing + + DELETE atv + FROM #accountsToValidate atv + INNER JOIN #statisticsHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID + + DELETE atv + FROM #statisticsMapping atv + INNER JOIN #statisticsHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID + + DELETE atv + FROM #accountsToValidate atv + INNER JOIN #revenueHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID + + DELETE atv + FROM #statisticsMapping atv + INNER JOIN #revenueHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID + END + + END + + -- Lastly, we need our catch-all for other issues. This is going to be vague, but it's basically, hey we know this isn't flexing, but don't know why + SELECT DISTINCT + sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + IsNew + INTO #noFlexConfigMapping + FROM #statisticsMapping sm + INNER JOIN fp.EntityGroupConfig egc ON sm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + LEFT JOIN fp.FlexConfigMapping fcm ON fcm.EntityGroupConfigID = egc.EntityGroupConfigID + AND fcm.DepartmentID = sm.DepartmentID + AND fcm.GLAccountID = sm.AccountID + AND fcm.FlexingTypeID = 1 + WHERE fcm.StatAccountID IS NULL + + IF (@IsDebug = 1) + BEGIN + SELECT '#noFlexConfigMapping' AS '#noFlexConfigMapping', * FROM #noFlexConfigMapping + END + + IF EXISTS (SELECT 1 FROM #noFlexConfigMapping) + BEGIN + INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + AccountID, + FlexMethodID, + FlexMethod, + -- Aka, if it falls in here, we're missing something in this script. + -- In this case, we need to debug [fp].[procNonStaffingByStatisticsFlexConfigPopulation] + 'An unknown error prevented the Department/Account from flexing. Contact support@stratadecision.com.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #noFlexConfigMapping + + DELETE atv + FROM #accountsToValidate atv + INNER JOIN #noFlexConfigMapping mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID + + DELETE atv + FROM #statisticsMapping atv + INNER JOIN #noFlexConfigMapping mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID + END + + -- Return final results + SELECT dep.DepartmentCode, dep.Description as DepartmentDescription, acc.AccountCode, acc.Description as AccountDescription, fv.* + FROM #finalValidatedTable fv + INNER JOIN fw.DimDepartment dep ON dep.DepartmentID = fv.DepartmentID + INNER JOIN fw.DimAccount acc ON acc.AccountID = fv.AccountID +END +GO + + +--------------------------------------------- + +-- fp.procGetOBNotificationsByEntityGroupConfiguration +CREATE PROCEDURE fp.procGetOBNotificationsByEntityGroupConfiguration + @EntityGroupConfigGUID UNIQUEIDENTIFIER + AS + BEGIN + SET NOCOUNT ON + + SELECT dept.DepartmentID, wrole.RoleID, N'DEPT|' + CONVERT(NVARCHAR(10), DepartmentID) LootID + INTO #TempDepartmentRole + FROM fp.APEWorkflow wflw + JOIN fp.EntityGroupConfig egc ON wflw.EntityGroupConfigID = egc.EntityGroupConfigID + JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + JOIN fp.APEWorkflowRole wrole ON wflw.WorkflowStepID = wrole.WorkflowStepID + JOIN fp.APEDepartmentWorkflowStatus dept ON wflw.WorkflowStepID = dept.WorkflowStepID + WHERE + bc.IsActive = 1 + AND wflw.IsNotificationEnabled = 1 + AND egc.EntityGroupConfigGUID = @EntityGroupConfigGUID + + SELECT up.UserGUID AS UserGuid, EmailAddress AS UserEmail, COUNT(tdr.DepartmentId) AS DepartmentsToReview + FROM viewS3RoleAssignment ra + JOIN UserProfile up ON up.UserGUID = ra.IdentityGUID + JOIN #TempDepartmentRole tdr ON tdr.LootID = ra.LootGroupID AND tdr.RoleID = ra.RoleID + WHERE + up.IsDisabled = 0 AND up.EmailAddress <> N'' AND up.EmailAddress IS NOT NULL + GROUP BY up.UserGUID, EmailAddress + + DROP TABLE IF EXISTS #TempDepartmentRole; + END +GO + + +--------------------------------------------- + +-- fp.procGetOBNotificationsByUser +CREATE PROCEDURE fp.procGetOBNotificationsByUser + @UserGUID UNIQUEIDENTIFIER + AS + BEGIN + SET NOCOUNT ON + + SELECT dept.DepartmentID, egc.EntityGroupConfigGUID, wrole.RoleID, N'DEPT|' + CONVERT(NVARCHAR(10), DepartmentID) LootID + INTO #TempDepartmentRole + FROM fp.APEWorkflow wflw + JOIN fp.EntityGroupConfig egc ON wflw.EntityGroupConfigID = egc.EntityGroupConfigID + JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + JOIN fp.APEWorkflowRole wrole ON wflw.WorkflowStepID = wrole.WorkflowStepID + JOIN fp.APEDepartmentWorkflowStatus dept ON wflw.WorkflowStepID = dept.WorkflowStepID + WHERE + bc.IsActive = 1 + AND wflw.IsNotificationEnabled = 1 + + SELECT EntityGroupConfigGUID AS EntityGroupConfigurationGuid, COUNT(tdr.DepartmentId) AS DepartmentsToReview + FROM viewS3RoleAssignment ra + JOIN UserProfile up ON up.UserGUID = ra.IdentityGUID + JOIN #TempDepartmentRole tdr ON tdr.LootID = ra.LootGroupID AND tdr.RoleID = ra.RoleID + WHERE + up.UserGUID = @UserGUID + GROUP BY tdr.EntityGroupConfigGUID + + DROP TABLE IF EXISTS #TempDepartmentRole; + END +GO + + +--------------------------------------------- + +-- fp.procGetRevenueFlexingExceptionItems +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2024-09-12 MZ/MY JAZZ-75490 Created proc +** 2 2024-09-19 NH JAZZ-77178 Updated message +** 3 2024-09-24 MY JAZZ-76786 Pass in Budget Config for inactive configs +*************************************************************/ +CREATE PROCEDURE [fp].[procGetRevenueFlexingExceptionItems] + @IsInitialPlansEnabled BIT = 0, + @BudgetConfigID INT = 0, + @IsDebug BIT = 0 +AS +BEGIN + + EXEC [dbo].[procSysDropTempTable] '#accountsToValidate' + EXEC [dbo].[procSysDropTempTable] '#missingPrimaryStats' + EXEC [dbo].[procSysDropTempTable] '#finalValidatedTable' + EXEC [dbo].[procSysDropTempTable] '#statisticsMapping' + EXEC [dbo].[procSysDropTempTable] '#missingStatistics' + EXEC [dbo].[procSysDropTempTable] '#statisticsWithZeroValues' + EXEC [dbo].[procSysDropTempTable] '#noFlexConfigMapping' + EXEC [dbo].[procSysDropTempTable] '#timeClassByEgc' + EXEC [dbo].[procSysDropTempTable] '#statisticsHistoryMissing' + EXEC [dbo].[procSysDropTempTable] '#revenueHistoryMissing' + + + CREATE TABLE #finalValidatedTable ( + DepartmentID INT, + AccountID INT, + FlexMethodID INT, + FlexMethod NVARCHAR(MAX), + Detail NVARCHAR(MAX), + EntityGroupConfigGUID UNIQUEIDENTIFIER, + EntityGroupConfigName NVARCHAR(MAX), + IsNew INT + ) + + SELECT EntityGroupConfigID, EntityGroupConfigGUID, RevenueAndDeductionsFiscalYearID, RevenueAndDeductionsTimeClassID + INTO #timeClassByEgc + FROM fp.EntityGroupConfig + + -- Populate Revenue records that we can check has Statistics or not. By default, + -- Revenue accounts are 100% Variable so we don't need to check if it's Variable or not. + -- Populates: #accountsToValidate + SELECT DISTINCT + dep.DepartmentID , + acc.AccountID , + COALESCE(ovr.FlexMethodID, flex.FlexMethodID) AS FlexMethodID , + CASE WHEN COALESCE(ovr.FlexMethodID, flex.FlexMethodID) = 3 THEN 'Statistics Accounts By Patient Class' ELSE 'Total Statistics Accounts' END AS FlexMethod, + '' AS Detail, + ec.EntityGroupConfigGUID, + ec.Name, + gl.IsNew + INTO #accountsToValidate + FROM fp.GeneralLedger gl + INNER JOIN fw.DimDepartment dep ON dep.DepartmentID = gl.DepartmentID + INNER JOIN fw.DimAccount acc ON acc.AccountID = gl.AccountID + INNER join fp.BudgetConfig bc ON bc.BudgetConfigID = gl.BudgetConfigID + INNER JOIN fp.EntityGroupConfig ec ON ec.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.ModelSectionMap map ON map.APEModelSectionID = gl.APEModelSectionID + INNER JOIN fp.RevenueExpenseFlexingConfig flex ON flex.DepartmentID = gl.DepartmentID + AND flex.EntityGroupConfigGUID = ec.EntityGroupConfigGUID + LEFT JOIN fp.RevenueFlexingOverrideConfig ovr ON ovr.EntityGroupConfigGUID = ec.EntityGroupConfigGUID + AND ovr.DepartmentID = gl.DepartmentID + AND ovr.AccountID = gl.AccountID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND map.APEModelSectionName = 'Revenue' + AND gl.VariabilityID = 2 -- Merely limiting the records as VariabilityID != Variability Percentage + AND flex.flexMethodID IN (3, 4) -- Stats by patient Class (3), Total Statistics Accounts (4) + AND (ovr.OverrideFlexConfigGUID IS NULL OR ovr.FlexMethodID != 6) -- Override as "Fixed" + + IF (@IsDebug = 1) + BEGIN + SELECT '#accountsToValidate' AS '#accountsToValidate', * FROM #accountsToValidate + END + + -- Check to see if there are Primary Statistics configured or not + SELECT DISTINCT + atv.DepartmentID, + atv.AccountID, + atv.FlexMethodID, + atv.FlexMethod, + atv.EntityGroupConfigGUID, + atv.Name, + atv.IsNew + INTO #missingPrimaryStats + FROM #accountsToValidate atv + LEFT JOIN fp.PrimaryStatisticsConfig psc ON atv.DepartmentID = psc.DepartmentID + AND atv.EntityGroupConfigGUID = psc.EntityGroupConfigGUID + AND psc.IsRevenue = 1 + LEFT JOIN fp.RevenueFlexingOverrideConfig ovr ON atv.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID + AND ovr.DepartmentID = atv.DepartmentID + AND ovr.AccountID = atv.AccountID + WHERE psc.RowID IS NULL + AND ovr.OverrideFlexConfigGUID IS NULL + + IF (@IsDebug = 1) + BEGIN + SELECT '#missingPrimaryStats' AS '#missingPrimaryStats', * FROM #missingPrimaryStats + END + + -- If there are any missing primary stats, add them to the final validation. Doing this first to weed out + -- potential duplicates down the line + IF EXISTS (SELECT 1 FROM #missingPrimaryStats) + BEGIN + INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + AccountID, + FlexMethodID, + FlexMethod, + 'Department/Account is set up for flexing but has no primary statistics configured for revenue. To resolve, add primary statistics for this department.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #missingPrimaryStats + + DELETE atv + FROM #accountsToValidate atv + INNER JOIN #missingPrimaryStats mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID + END + + -- Build a mapping of Department/Account to Statististics Department/Account + -- First build it without overrides + SELECT DISTINCT + atv.DepartmentID, + atv.AccountID, + atv.FlexMethodID, + atv.FlexMethod, + atv.EntityGroupConfigGUID, + atv.Name, + COALESCE(pscs.DepartmentID, psc.DepartmentID) AS StatisticsDepartmentID, + psc.AccountID AS StatisticsAccountID, + IsNew + INTO #statisticsMapping + FROM #accountsToValidate atv + INNER JOIN fp.PrimaryStatisticsConfig psc ON atv.DepartmentID = psc.DepartmentID + AND atv.EntityGroupConfigGUID = psc.EntityGroupConfigGUID + AND psc.IsRevenue = 1 + INNER JOIN fp.EntityGroupConfig ecc ON ecc.EntityGroupConfigGUID = atv.EntityGroupConfigGUID + INNER JOIN fp.BudgetConfig bcs ON ecc.BudgetConfigGUID = bcs.BudgetConfigGUID + LEFT JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscs ON psc.RowID = pscs.PrimaryStatisticsConfigID + LEFT JOIN fp.RevenueFlexingOverrideConfig ovr ON atv.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID + AND ovr.DepartmentID = atv.DepartmentID + AND ovr.AccountID = atv.AccountID + WHERE ovr.OverrideFlexConfigGUID IS NULL + + -- Now build the overrides + INSERT INTO #statisticsMapping (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, StatisticsDepartmentID, StatisticsAccountID, IsNew) + SELECT DISTINCT + atv.DepartmentID, + atv.AccountID, + atv.FlexMethodID, + atv.FlexMethod, + atv.EntityGroupConfigGUID, + atv.Name, + ovr.DepartmentID AS StatisticsDepartmentID, + ass.AccountID AS StatisticsAccountID, + IsNew + FROM #accountsToValidate atv + INNER JOIN fp.EntityGroupConfig ecc ON ecc.EntityGroupConfigGUID = atv.EntityGroupConfigGUID + INNER JOIN fp.BudgetConfig bcs ON ecc.BudgetConfigGUID = bcs.BudgetConfigGUID + INNER JOIN fp.RevenueFlexingOverrideConfig ovr ON atv.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID + AND ovr.DepartmentID = atv.DepartmentID + AND ovr.AccountID = atv.AccountID + INNER JOIN fp.RevenueFlexingOverrideConfigAssignment ass ON ovr.OverrideFlexConfigGUID = ass.OverrideFlexConfigGUID + + IF (@IsDebug = 1) + BEGIN + SELECT '#statisticsMapping' AS '#statisticsMapping', * FROM #statisticsMapping + END + + -- Next, we need to check to see if Primary Stats exist, but there are no Statistics for it + SELECT DISTINCT + sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + INTO #missingStatistics + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID + LEFT JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.StatisticsDepartmentID = fs.DepartmentID + AND sm.StatisticsAccountID = fs.AccountID + WHERE sm.FlexMethodID = 4 + GROUP BY sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING COUNT(fs.StatisticsID) = 0 + + INSERT INTO #missingStatistics (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, IsNew) + SELECT DISTINCT + sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID + LEFT JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.StatisticsDepartmentID = fs.DepartmentID + AND sm.StatisticsAccountID = fs.AccountID AND acc.PatientClassID = fs.PatientClassID + WHERE sm.FlexMethodID = 3 + GROUP BY sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING COUNT(fs.StatisticsID) = 0 + + IF (@IsDebug = 1) + BEGIN + SELECT '#missingStatistics' AS '#missingStatistics', * FROM #missingStatistics + END + + IF EXISTS (SELECT 1 FROM #missingStatistics) + BEGIN + INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + AccountID, + FlexMethodID, + FlexMethod, + CASE WHEN FlexMethodID = 3 THEN 'Department/Account is set up for flexing but has no statistics data for statistics accounts by patient class. To resolve, add budget or projection statistic volumes in Plan Editor or change department flex method in entity group configuration.' + ELSE 'Department/Account is set up for flexing but has no statistics data. To resolve, add budget or projection statistic volumes in Plan Editor or change department flex method in entity group configuration.' END, + EntityGroupConfigGUID, + Name, + IsNew + FROM #missingStatistics + + DELETE atv + FROM #accountsToValidate atv + INNER JOIN #missingStatistics mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID + + DELETE atv + FROM #statisticsMapping atv + INNER JOIN #missingStatistics mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID + END + + -- Next, check for cases where we have statistics, but they are zero + SELECT DISTINCT + sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + 12 AS TimeClassID, + sm.IsNew + INTO #statisticsWithZeroValues + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID + INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.StatisticsDepartmentID = fs.DepartmentID + AND sm.StatisticsAccountID = fs.AccountID + INNER JOIN fp.FactStatisticsProjection fsp ON fsp.StatisticsID = fs.StatisticsID AND fsp.BudgetPhaseID = 3 + WHERE sm.FlexMethodID = 4 + GROUP BY sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING ( + SUM(CASE WHEN bc.MonthsLoaded = 1 THEN fsp.AdjustedValue02 + fsp.AdjustedValue03 + fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 2 THEN fsp.AdjustedValue03 + fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 3 THEN fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 4 THEN fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 5 THEN fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 6 THEN fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 7 THEN fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 8 THEN fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 9 THEN fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 10 THEN fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 11 THEN fsp.AdjustedValue12 END + ) = 0 -- Non Zero volume data for driver statistics - Projection, made it a sum to consider that there can be multiple records for provider + ) + + INSERT #statisticsWithZeroValues (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, TimeClassID, IsNew) + SELECT DISTINCT + sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + 12 AS TimeClassID, + sm.IsNew + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID + INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.StatisticsDepartmentID = fs.DepartmentID + AND sm.StatisticsAccountID = fs.AccountID AND acc.PatientClassID = fs.PatientClassID + INNER JOIN fp.FactStatisticsProjection fsp ON fsp.StatisticsID = fs.StatisticsID AND fsp.BudgetPhaseID = 3 + WHERE sm.FlexMethodID = 3 + GROUP BY sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING ( + SUM(CASE WHEN bc.MonthsLoaded = 1 THEN fsp.AdjustedValue02 + fsp.AdjustedValue03 + fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 2 THEN fsp.AdjustedValue03 + fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 3 THEN fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 4 THEN fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 5 THEN fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 6 THEN fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 7 THEN fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 8 THEN fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 9 THEN fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 10 THEN fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 11 THEN fsp.AdjustedValue12 END + ) = 0 -- Non Zero volume data for driver statistics - Projection, made it a sum to consider that there can be multiple records for provider + ) + + INSERT #statisticsWithZeroValues (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, TimeClassID, IsNew) + SELECT DISTINCT + sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + 2 AS TimeClassID, + sm.IsNew + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID + INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.StatisticsDepartmentID = fs.DepartmentID + AND sm.StatisticsAccountID = fs.AccountID + INNER JOIN fp.FactStatisticsBudget fsb ON fsb.StatisticsID = fs.StatisticsID AND fsb.BudgetPhaseID = 3 + WHERE sm.FlexMethodID = 4 + GROUP BY sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING ( + SUM(fsb.AdjustedValueTotal) = 0 + ) + + INSERT #statisticsWithZeroValues (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, TimeClassID, IsNew) + SELECT DISTINCT + sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + 2 AS TimeClassID, + sm.IsNew + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID + INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.StatisticsDepartmentID = fs.DepartmentID + AND sm.StatisticsAccountID = fs.AccountID AND acc.PatientClassID = fs.PatientClassID + INNER JOIN fp.FactStatisticsBudget fsb ON fsb.StatisticsID = fs.StatisticsID AND fsb.BudgetPhaseID = 3 + WHERE sm.FlexMethodID = 3 + GROUP BY sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING ( + SUM(fsb.AdjustedValueTotal) = 0 + ) + + INSERT #statisticsWithZeroValues (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, TimeClassID, IsNew) + SELECT DISTINCT + sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + 22 AS TimeClassID, + sm.IsNew + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID + INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.StatisticsDepartmentID = fs.DepartmentID + AND sm.StatisticsAccountID = fs.AccountID + INNER JOIN fp.FactStatisticsBudget fsb ON fsb.StatisticsID = fs.StatisticsID AND fsb.BudgetPhaseID = 2 + WHERE sm.FlexMethodID = 4 + GROUP BY sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING ( + SUM(fsb.AdjustedValueTotal) = 0 + ) + + INSERT #statisticsWithZeroValues (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, TimeClassID, IsNew) + SELECT DISTINCT + sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + 22 AS TimeClassID, + sm.IsNew + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID + INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.StatisticsDepartmentID = fs.DepartmentID + AND sm.StatisticsAccountID = fs.AccountID AND acc.PatientClassID = fs.PatientClassID + INNER JOIN fp.FactStatisticsBudget fsb ON fsb.StatisticsID = fs.StatisticsID AND fsb.BudgetPhaseID = 2 + WHERE sm.FlexMethodID = 3 + GROUP BY sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING ( + SUM(fsb.AdjustedValueTotal) = 0 + ) + + IF (@IsDebug = 1) + BEGIN + SELECT '#statisticsWithZeroValues' AS '#statisticsWithZeroValues', * FROM #statisticsWithZeroValues + END + + IF EXISTS (SELECT 1 FROM #statisticsWithZeroValues) + BEGIN + INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + AccountID, + FlexMethodID, + FlexMethod, + 'Department/Account is set up for flexing but the statistics are zero for projection. To resolve, add projection statistic volumes in Plan Editor or change department flex method in entity group configuration.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #statisticsWithZeroValues + WHERE TimeClassID = 12 + + INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + AccountID, + FlexMethodID, + FlexMethod, + 'Department/Account is set up for flexing but the statistics are zero for budget. To resolve, add budget statistic volumes in Plan Editor or change department flex method in entity group configuration.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #statisticsWithZeroValues + WHERE TimeClassID = 2 + + INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + AccountID, + FlexMethodID, + FlexMethod, + 'Department/Account is set up for flexing but the statistics are zero for target. To resolve, add target statistic volumes in Plan Editor or change department flex method in entity group configuration.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #statisticsWithZeroValues + WHERE TimeClassID = 22 + + DELETE atv + FROM #accountsToValidate atv + INNER JOIN #statisticsWithZeroValues mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID + + DELETE atv + FROM #statisticsMapping atv + INNER JOIN #statisticsWithZeroValues mps ON atv.DepartmentID = mps.DepartmentID AND atv.AccountID = mps.AccountID + END + + -- This only works for when Initial Plan is disabled + IF (@IsInitialPlansEnabled = 0) + BEGIN + + -- We need to check the historical data to ensure the rate is calculate correctly + -- aka [fp].[procSampleGLDollarsPerUOS]. + SELECT DISTINCT + sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + INTO #statisticsHistoryMissing + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID + INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.StatisticsDepartmentID = fs.DepartmentID + AND sm.FlexMethodID = 4 AND sm.StatisticsAccountID = fs.AccountID + INNER JOIN fp.FactStatisticsHistory hist ON hist.StatisticsID = fs.StatisticsID + INNER JOIN #timeClassByEgc tcEgc ON tcEgc.EntityGroupConfigID = fs.EntityGroupConfigID + WHERE sm.FlexMethodID = 4 + GROUP BY sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING ( + SUM(CASE + WHEN tcEgc.RevenueAndDeductionsFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.RevenueAndDeductionsTimeClassID = 1 THEN hist.ActualYTDValueTotal + WHEN tcEgc.RevenueAndDeductionsFiscalYearID = bc.FiscalYearID - 2 AND tcEgc.RevenueAndDeductionsTimeClassID = 1 THEN hist.PriorYearActualValueTotal + WHEN tcegc.RevenueAndDeductionsFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.RevenueAndDeductionsTimeClassID = 2 THEN hist.CurrentYearBudgetTotal + ELSE 0 END + ) = 0 -- Non Zero volume data for driver statistics - Projection, made it a sum to consider that there can be multiple records for provider + ) + + INSERT INTO #statisticsHistoryMissing (DepartmentID, AccountID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, IsNew) + SELECT DISTINCT + sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN fw.DimAccount acc ON sm.AccountID = acc.AccountID + INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.StatisticsDepartmentID = fs.DepartmentID + AND sm.StatisticsAccountID = fs.AccountID AND acc.PatientClassID = fs.PatientClassID + INNER JOIN fp.FactStatisticsHistory hist ON hist.StatisticsID = fs.StatisticsID + INNER JOIN #timeClassByEgc tcEgc ON tcEgc.EntityGroupConfigID = fs.EntityGroupConfigID + WHERE sm.FlexMethodID = 3 + GROUP BY sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING ( + SUM(CASE + WHEN tcEgc.RevenueAndDeductionsFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.RevenueAndDeductionsTimeClassID = 1 THEN hist.ActualYTDValueTotal + WHEN tcEgc.RevenueAndDeductionsFiscalYearID = bc.FiscalYearID - 2 AND tcEgc.RevenueAndDeductionsTimeClassID = 1 THEN hist.PriorYearActualValueTotal + WHEN tcegc.RevenueAndDeductionsFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.RevenueAndDeductionsTimeClassID = 2 THEN hist.CurrentYearBudgetTotal + ELSE 0 END + ) = 0 -- Non Zero volume data for driver statistics - Projection, made it a sum to consider that there can be multiple records for provider + ) + + SELECT DISTINCT + sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + INTO #revenueHistoryMissing + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN [fp].[GeneralLedger] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.DepartmentID = fs.DepartmentID + AND sm.AccountID = fs.AccountID + INNER JOIN fp.GeneralLedgerHistory hist ON hist.GeneralLedgerID = fs.GeneralLedgerID + INNER JOIN #timeClassByEgc tcEgc ON tcEgc.EntityGroupConfigID = fs.EntityGroupConfigID + GROUP BY sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING ( + SUM(CASE + WHEN tcEgc.RevenueAndDeductionsFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.RevenueAndDeductionsTimeClassID = 1 THEN hist.ActualYTDValueTotal + WHEN tcEgc.RevenueAndDeductionsFiscalYearID = bc.FiscalYearID - 2 AND tcEgc.RevenueAndDeductionsTimeClassID = 1 THEN hist.PriorYearActualValueTotal + WHEN tcegc.RevenueAndDeductionsFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.RevenueAndDeductionsTimeClassID = 2 THEN hist.CurrentYearBudgetTotal + ELSE 0 END + ) = 0 -- Non Zero volume data for driver statistics - Projection, made it a sum to consider that there can be multiple records for provider + ) + + IF (@IsDebug = 1) + BEGIN + SELECT '#statisticsHistoryMissing' AS '#statisticsHistoryMissing', * FROM #statisticsHistoryMissing + SELECT '#revenueHistoryMissing' AS '#revenueHistoryMissing', * FROM #revenueHistoryMissing + END + + IF EXISTS (SELECT 1 FROM #statisticsHistoryMissing) OR EXISTS(SELECT 1 FROM #revenueHistoryMissing) + BEGIN + INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + AccountID, + FlexMethodID, + FlexMethod, + -- If you need to debug this, you can look at [fp].[procSampleGLDollarsPerUOS] + 'Department/Account is missing historical statistics data, resulting in a calculated rate of zero.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #statisticsHistoryMissing + + INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + AccountID, + FlexMethodID, + FlexMethod, + -- If you need to debug this, you can look at [fp].[procSampleGLDollarsPerUOS] + 'Department/Account is missing historical revenue data, resulting in a calculated rate of zero.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #revenueHistoryMissing + + DELETE atv + FROM #accountsToValidate atv + INNER JOIN #statisticsHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID + + DELETE atv + FROM #statisticsMapping atv + INNER JOIN #statisticsHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID + + DELETE atv + FROM #accountsToValidate atv + INNER JOIN #revenueHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID + + DELETE atv + FROM #statisticsMapping atv + INNER JOIN #revenueHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID + END + + END + + -- Lastly, we need our catch-all for other issues. This is going to be vague, but it's basically, hey we know this isn't flexing, but don't know why + SELECT DISTINCT + sm.DepartmentID, + sm.AccountID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + INTO #noFlexConfigMapping + FROM #statisticsMapping sm + INNER JOIN fp.EntityGroupConfig egc ON sm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + LEFT JOIN fp.FlexConfigMapping fcm ON fcm.EntityGroupConfigID = egc.EntityGroupConfigID + AND fcm.DepartmentID = sm.DepartmentID + AND fcm.GLAccountID = sm.AccountID + AND fcm.FlexingTypeID = 2 + WHERE fcm.StatAccountID IS NULL + + IF (@IsDebug = 1) + BEGIN + SELECT '#noFlexConfigMapping' AS '#noFlexConfigMapping', * FROM #noFlexConfigMapping + END + + IF EXISTS (SELECT 1 FROM #noFlexConfigMapping) + BEGIN + INSERT INTO #finalValidatedTable (DepartmentID, AccountID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + AccountID, + FlexMethodID, + FlexMethod, + -- Aka, if it falls in here, we're missing something in this script. + -- In this case, we need to debug [fp].[procRevenueByStatisticsFlexConfigPopulation] + 'An unknown error prevented the Department/Account from flexing. Contact support@stratadecision.com.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #noFlexConfigMapping + + DELETE atv + FROM #accountsToValidate atv + INNER JOIN #noFlexConfigMapping mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID + + DELETE atv + FROM #statisticsMapping atv + INNER JOIN #noFlexConfigMapping mps ON atv.DepartmentID = mps.DepartmentID AND mps.AccountID = atv.AccountID + END + + -- Return final results + SELECT dep.DepartmentCode, dep.Description as DepartmentDescription, acc.AccountCode, acc.Description as AccountDescription, fv.* + FROM #finalValidatedTable fv + INNER JOIN fw.DimDepartment dep ON dep.DepartmentID = fv.DepartmentID + INNER JOIN fw.DimAccount acc ON acc.AccountID = fv.AccountID +END +GO + + +--------------------------------------------- + +-- fp.procGetStaffingFlexingExceptionItems +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2024-09-12 MZ/MY JAZZ-75490 Created proc +** 2 2024-09-19 NH JAZZ-77178 Updated message +** 3 2024-09-24 MY JAZZ-76786 Pass in Budget Config for inactive configs +*************************************************************/ +CREATE PROCEDURE [fp].[procGetStaffingFlexingExceptionItems] + @IsInitialPlansEnabled BIT = 0, + @BudgetConfigID INT = 0, + @IsDebug BIT = 0 +AS +BEGIN + + EXEC [dbo].[procSysDropTempTable] '#departmentsToValidate' + EXEC [dbo].[procSysDropTempTable] '#missingPrimaryStats' + EXEC [dbo].[procSysDropTempTable] '#finalValidatedTable' + EXEC [dbo].[procSysDropTempTable] '#statisticsMapping' + EXEC [dbo].[procSysDropTempTable] '#missingStatistics' + EXEC [dbo].[procSysDropTempTable] '#statisticsWithZeroValues' + EXEC [dbo].[procSysDropTempTable] '#noFlexConfigMapping' + EXEC [dbo].[procSysDropTempTable] '#timeClassByEgc' + EXEC [dbo].[procSysDropTempTable] '#statisticsHistoryMissing' + EXEC [dbo].[procSysDropTempTable] '#payrollHistoryMissing' + + CREATE TABLE #finalValidatedTable ( + DepartmentID INT, + JobCodeID INT, + FlexMethodID INT, + FlexMethod NVARCHAR(MAX), + Detail NVARCHAR(MAX), + EntityGroupConfigGUID UNIQUEIDENTIFIER, + EntityGroupConfigName NVARCHAR(MAX), + IsNew INT + ) + + SELECT EntityGroupConfigID, EntityGroupConfigGUID, PayrollFiscalYearID, PayrollTimeClassID + INTO #timeClassByEgc + FROM fp.EntityGroupConfig + + -- Populate NonStaffing records that we can check has Statistics or not. By default, + -- NonStaffing accounts are 100% Variable so we don't need to check if it's Variable or not. + -- Populates: #departmentsToValidate + SELECT DISTINCT + dep.DepartmentID, + st.JobCodeID, + flex.FlexMethodID, + 'Statistics Accounts' AS FlexMethod, + '' AS Detail, + ec.EntityGroupConfigGUID, + ec.Name, + MIN(CAST(IsNew AS INT)) AS IsNew + INTO #departmentsToValidate + FROM fp.Staffing st + INNER JOIN fw.DimDepartment dep ON dep.DepartmentID = st.DepartmentID + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = st.BudgetConfigID + INNER JOIN fp.EntityGroupConfig ec ON ec.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.StaffingExpenseFlexingConfig flex ON flex.DepartmentID = st.DepartmentID + AND flex.EntityGroupConfigGUID = ec.EntityGroupConfigGUID + INNER JOIN fp.PayrollVariabilityConfig nsvb ON ec.EntityGroupConfigGUID = nsvb.EntityGroupConfigGUID + AND st.JobCodeID = nsvb.JobCodeID + LEFT JOIN fp.StaffingVariabilityOverrideConfig svoc ON ec.EntityGroupConfigGUID = svoc.EntityGroupConfigGUID + AND st.DepartmentID = svoc.DepartmentID + AND st.JobCodeID = svoc.JobCodeID + LEFT JOIN fp.StaffingFlexingOverrideConfig ovr ON ec.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID + AND st.DepartmentID = ovr.DepartmentID + AND st.JobCodeID = ovr.JobCodeID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND st.VariabilityID = 2 -- Merely limiting the records as VariabilityID != Variability Percentage + AND flex.flexMethodID = 1 -- Statistic Accounts + AND dep.OBIsDefined = 1 + AND st.SubsectionID = 3 -- Staffing Only, Exclude Provider for now + AND COALESCE(svoc.Variability, nsvb.Variability) > 0 -- Only find job codes that are at least partial variable + AND (ovr.OverrideFlexConfigGUID IS NULL OR (ovr.FlexMethodID != 6 AND ovr.FlexMethodID != 2)) -- 6 = Fixed, 2 = Patient Activity + GROUP BY dep.DepartmentID, + st.JobCodeID, + flex.FlexMethodID, + ec.EntityGroupConfigGUID, + ec.Name + + IF (@IsDebug = 1) + BEGIN + SELECT '#departmentsToValidate' AS '#departmentsToValidate', * FROM #departmentsToValidate + END + + -- Check to see if there are Primary Statistics configured or not + SELECT DISTINCT + atv.DepartmentID, + atv.JobCodeID, + atv.FlexMethodID, + atv.FlexMethod, + atv.EntityGroupConfigGUID, + atv.Name, + atv.IsNew + INTO #missingPrimaryStats + FROM #departmentsToValidate atv + LEFT JOIN fp.PrimaryStatisticsConfig psc ON atv.DepartmentID = psc.DepartmentID + AND atv.EntityGroupConfigGUID = psc.EntityGroupConfigGUID + AND psc.IsStaffing = 1 + LEFT JOIN fp.StaffingFlexingOverrideConfig ovr ON atv.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID + AND atv.DepartmentID = ovr.DepartmentID + AND atv.JobCodeID = ovr.JobCodeID + WHERE psc.RowID IS NULL + AND ovr.OverrideFlexConfigGUID IS NULL + + IF (@IsDebug = 1) + BEGIN + SELECT '#missingPrimaryStats' AS '#missingPrimaryStats', * FROM #missingPrimaryStats + END + + -- If there are any missing primary stats, add them to the final validation. Doing this first to weed out + -- potential duplicates down the line + IF EXISTS (SELECT 1 FROM #missingPrimaryStats) + BEGIN + INSERT INTO #finalValidatedTable (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + JobCodeID, + FlexMethodID, + FlexMethod, + 'Department/Job Code is set up for flexing but has no primary statistics configured for staffing. To resolve, add primary statistics for this department.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #missingPrimaryStats + + DELETE atv + FROM #departmentsToValidate atv + INNER JOIN #missingPrimaryStats mps ON atv.DepartmentID = mps.DepartmentID AND mps.JobCodeID = atv.JobCodeID + END + + -- Build a mapping of Department/Job Code to Statististics Department/Job Code + SELECT DISTINCT + atv.DepartmentID, + atv.JobCodeID, + atv.FlexMethodID, + atv.FlexMethod, + atv.EntityGroupConfigGUID, + atv.Name, + COALESCE(pscs.DepartmentID, psc.DepartmentID) AS StatisticsDepartmentID, + psc.AccountID AS StatisticsAccountID, + atv.IsNew + INTO #statisticsMapping + FROM #departmentsToValidate atv + INNER JOIN fp.PrimaryStatisticsConfig psc ON atv.DepartmentID = psc.DepartmentID + AND atv.EntityGroupConfigGUID = psc.EntityGroupConfigGUID + AND psc.IsStaffing = 1 + INNER JOIN fp.EntityGroupConfig ecc ON ecc.EntityGroupConfigGUID = atv.EntityGroupConfigGUID + INNER JOIN fp.BudgetConfig bcs ON ecc.BudgetConfigGUID = bcs.BudgetConfigGUID + LEFT JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscs ON psc.RowID = pscs.PrimaryStatisticsConfigID + LEFT JOIN fp.StaffingFlexingOverrideConfig ovr ON atv.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID + AND atv.DepartmentID = ovr.DepartmentID + AND atv.JobCodeID = ovr.JobCodeID + WHERE ovr.OverrideFlexConfigGUID IS NULL + + -- Now build the overrides + INSERT INTO #statisticsMapping (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, StatisticsDepartmentID, StatisticsAccountID, IsNew) + SELECT DISTINCT + atv.DepartmentID, + atv.JobCodeID, + atv.FlexMethodID, + atv.FlexMethod, + atv.EntityGroupConfigGUID, + atv.Name, + ovr.DepartmentID AS StatisticsDepartmentID, + ass.AccountID AS StatisticsAccountID, + IsNew + FROM #departmentsToValidate atv + INNER JOIN fp.EntityGroupConfig ecc ON ecc.EntityGroupConfigGUID = atv.EntityGroupConfigGUID + INNER JOIN fp.BudgetConfig bcs ON ecc.BudgetConfigGUID = bcs.BudgetConfigGUID + INNER JOIN fp.StaffingFlexingOverrideConfig ovr ON atv.EntityGroupConfigGUID = ovr.EntityGroupConfigGUID + AND atv.DepartmentID = ovr.DepartmentID + AND atv.JobCodeID = ovr.JobCodeID + INNER JOIN fp.StaffingFlexingOverrideConfigAssignment ass ON ovr.OverrideFlexConfigGUID = ass.OverrideFlexConfigGUID + + IF (@IsDebug = 1) + BEGIN + SELECT '#statisticsMapping' AS '#statisticsMapping', * FROM #statisticsMapping + END + + -- Next, we need to check to see if Primary Stats exist, but there are no Statistics for it + SELECT DISTINCT + sm.DepartmentID, + sm.JobCodeID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + INTO #missingStatistics + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.StatisticsDepartmentID = fs.DepartmentID + AND sm.StatisticsAccountID = fs.AccountID + GROUP BY sm.DepartmentID, + sm.JobCodeID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING COUNT(fs.StatisticsID) = 0 + + IF (@IsDebug = 1) + BEGIN + SELECT '#missingStatistics' AS '#missingStatistics', * FROM #missingStatistics + END + + IF EXISTS (SELECT 1 FROM #missingStatistics) + BEGIN + INSERT INTO #finalValidatedTable (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + JobCodeID, + FlexMethodID, + FlexMethod, + 'Department/Job Code is set up for flexing but has no statistics data. To resolve, add budget or projection statistic volumes in Plan Editor or change department flex method in entity group configuration.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #missingStatistics + + DELETE atv + FROM #departmentsToValidate atv + INNER JOIN #missingStatistics mps ON atv.DepartmentID = mps.DepartmentID AND mps.JobCodeID = atv.JobCodeID + + DELETE atv + FROM #statisticsMapping atv + INNER JOIN #missingStatistics mps ON atv.DepartmentID = mps.DepartmentID AND mps.JobCodeID = atv.JobCodeID + END + + -- Next, check for cases where we have statistics, but they are zero + SELECT DISTINCT + sm.DepartmentID, + sm.JobCodeID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + 12 AS TimeClassID, + sm.IsNew + INTO #statisticsWithZeroValues + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.StatisticsDepartmentID = fs.DepartmentID + AND sm.StatisticsAccountID = fs.AccountID + INNER JOIN fp.FactStatisticsProjection fsp ON fsp.StatisticsID = fs.StatisticsID AND fsp.BudgetPhaseID = 3 + GROUP BY sm.DepartmentID, + sm.JobCodeID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING ( + SUM(CASE WHEN bc.MonthsLoaded = 1 THEN fsp.AdjustedValue02 + fsp.AdjustedValue03 + fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 2 THEN fsp.AdjustedValue03 + fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 3 THEN fsp.AdjustedValue04 + fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 4 THEN fsp.AdjustedValue05 + fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 5 THEN fsp.AdjustedValue06 + fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 6 THEN fsp.AdjustedValue07 + fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 7 THEN fsp.AdjustedValue08 + fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 8 THEN fsp.AdjustedValue09 + fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 9 THEN fsp.AdjustedValue10 + fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 10 THEN fsp.AdjustedValue11 + fsp.AdjustedValue12 + WHEN bc.MonthsLoaded = 11 THEN fsp.AdjustedValue12 END + ) = 0 -- Non Zero volume data for driver statistics - Projection, made it a sum to consider that there can be multiple records for provider + ) + + INSERT #statisticsWithZeroValues (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, TimeClassID, IsNew) + SELECT DISTINCT + sm.DepartmentID, + sm.JobCodeID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + 2 AS TimeClassID, + sm.IsNew + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.StatisticsDepartmentID = fs.DepartmentID + AND sm.StatisticsAccountID = fs.AccountID + INNER JOIN fp.FactStatisticsBudget fsb ON fsb.StatisticsID = fs.StatisticsID AND fsb.BudgetPhaseID = 3 + GROUP BY sm.DepartmentID, + sm.JobCodeID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING ( + SUM(fsb.AdjustedValueTotal) = 0 + ) + + INSERT #statisticsWithZeroValues (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, EntityGroupConfigGUID, Name, TimeClassID, IsNew) + SELECT DISTINCT + sm.DepartmentID, + sm.JobCodeID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + 22 AS TimeClassID, + sm.IsNew + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.StatisticsDepartmentID = fs.DepartmentID + AND sm.StatisticsAccountID = fs.AccountID + INNER JOIN fp.FactStatisticsBudget fsb ON fsb.StatisticsID = fs.StatisticsID AND fsb.BudgetPhaseID = 2 + GROUP BY sm.DepartmentID, + sm.JobCodeID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING ( + SUM(fsb.AdjustedValueTotal) = 0 + ) + + IF (@IsDebug = 1) + BEGIN + SELECT '#statisticsWithZeroValues' AS '#statisticsWithZeroValues', * FROM #statisticsWithZeroValues + END + + IF EXISTS (SELECT 1 FROM #statisticsWithZeroValues) + BEGIN + INSERT INTO #finalValidatedTable (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + JobCodeID, + FlexMethodID, + FlexMethod, + 'Department/Job Code is set up for flexing but the statistics are zero for projection. To resolve, add projection statistic volumes in Plan Editor or change department flex method in entity group configuration.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #statisticsWithZeroValues + WHERE TimeClassID = 12 + + INSERT INTO #finalValidatedTable (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + JobCodeID, + FlexMethodID, + FlexMethod, + 'Department/Job Code is set up for flexing but the statistics are zero for budget. To resolve, add budget statistic volumes in Plan Editor or change department flex method in entity group configuration.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #statisticsWithZeroValues + WHERE TimeClassID = 2 + + INSERT INTO #finalValidatedTable (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + JobCodeID, + FlexMethodID, + FlexMethod, + 'Department/Job Code is set up for flexing but the statistics are zero for target. To resolve, add target statistic volumes in Plan Editor or change department flex method in entity group configuration.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #statisticsWithZeroValues + WHERE TimeClassID = 22 + + DELETE atv + FROM #departmentsToValidate atv + INNER JOIN #statisticsWithZeroValues mps ON atv.DepartmentID = mps.DepartmentID AND mps.JobCodeID = atv.JobCodeID + + DELETE atv + FROM #statisticsMapping atv + INNER JOIN #statisticsWithZeroValues mps ON atv.DepartmentID = mps.DepartmentID AND atv.JobCodeID = mps.JobCodeID + END + + -- This only works for when Initial Plan is disabled + IF (@IsInitialPlansEnabled = 0) + BEGIN + + -- We need to check the historical data to ensure the rate is calculate correctly + -- aka [fp].[procSampleStaffingHoursPerUOS]. + SELECT DISTINCT + sm.DepartmentID, + sm.JobCodeID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + INTO #statisticsHistoryMissing + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN [fp].[FactStatistics] fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.StatisticsDepartmentID = fs.DepartmentID + AND sm.StatisticsAccountID = fs.AccountID + INNER JOIN fp.FactStatisticsHistory hist ON hist.StatisticsID = fs.StatisticsID + INNER JOIN #timeClassByEgc tcEgc ON tcEgc.EntityGroupConfigID = fs.EntityGroupConfigID + GROUP BY sm.DepartmentID, + sm.JobCodeID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING ( + SUM(CASE + WHEN tcEgc.PayrollFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.PayrollTimeClassID = 1 THEN hist.ActualYTDValueTotal + WHEN tcEgc.PayrollFiscalYearID = bc.FiscalYearID - 2 AND tcEgc.PayrollTimeClassID = 1 THEN hist.PriorYearActualValueTotal + WHEN tcegc.PayrollFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.PayrollTimeClassID = 2 THEN hist.CurrentYearBudgetTotal + ELSE 0 END + ) = 0 -- Non Zero volume data for driver statistics - Projection, made it a sum to consider that there can be multiple records for provider + ) + + SELECT DISTINCT + sm.DepartmentID, + sm.JobCodeID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + INTO #payrollHistoryMissing + FROM #statisticsMapping sm + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN fp.Staffing fs ON bc.BudgetConfigID = fs.BudgetConfigID + AND sm.DepartmentID = fs.DepartmentID + AND sm.JobCodeID = fs.JobCodeID + INNER JOIN fp.StaffingHistory hist ON hist.StaffingID = fs.StaffingID + INNER JOIN #timeClassByEgc tcEgc ON tcEgc.EntityGroupConfigID = fs.EntityGroupConfigID + GROUP BY sm.DepartmentID, + sm.JobCodeID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + HAVING ( + SUM(CASE + WHEN tcEgc.PayrollFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.PayrollTimeClassID = 1 THEN hist.ActualYTDHoursTotal + WHEN tcEgc.PayrollFiscalYearID = bc.FiscalYearID - 2 AND tcEgc.PayrollTimeClassID = 1 THEN hist.PriorYearActualHoursTotal + WHEN tcegc.PayrollFiscalYearID = bc.FiscalYearID - 1 AND tcEgc.PayrollTimeClassID = 2 THEN hist.CurrentYearBudgetHoursTotal + ELSE 0 END + ) = 0 -- Non Zero volume data for driver staffing - Projection, made it a sum to consider that there can be multiple records for provider + ) + + IF (@IsDebug = 1) + BEGIN + SELECT '#statisticsHistoryMissing' AS '#statisticsHistoryMissing', * FROM #statisticsHistoryMissing + SELECT '#payrollHistoryMissing' AS '#payrollHistoryMissing', * FROM #payrollHistoryMissing + END + + IF EXISTS (SELECT 1 FROM #statisticsHistoryMissing) OR EXISTS(SELECT 1 FROM #payrollHistoryMissing) + BEGIN + INSERT INTO #finalValidatedTable (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + JobCodeID, + FlexMethodID, + FlexMethod, + -- If you need to debug this, you can look at [fp].[procSampleGLDollarsPerUOS] + 'Department/Job Code is missing historical statistics data, resulting in a calculated rate of zero.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #statisticsHistoryMissing + + INSERT INTO #finalValidatedTable (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + JobCodeID, + FlexMethodID, + FlexMethod, + -- If you need to debug this, you can look at [fp].[procSampleGLDollarsPerUOS] + 'Department/Job Code is missing historical staffing data, resulting in a calculated rate of zero.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #payrollHistoryMissing + + DELETE atv + FROM #departmentsToValidate atv + INNER JOIN #statisticsHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.JobCodeID = atv.JobCodeID + + DELETE atv + FROM #statisticsMapping atv + INNER JOIN #statisticsHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.JobCodeID = atv.JobCodeID + + DELETE atv + FROM #departmentsToValidate atv + INNER JOIN #payrollHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.JobCodeID = atv.JobCodeID + + DELETE atv + FROM #statisticsMapping atv + INNER JOIN #payrollHistoryMissing mps ON atv.DepartmentID = mps.DepartmentID AND mps.JobCodeID = atv.JobCodeID + END + + END + + -- Lastly, we need our catch-all for other issues. This is going to be vague, but it's basically, hey we know this isn't flexing, but don't know why + SELECT DISTINCT + sm.DepartmentID, + sm.JobCodeID, + sm.FlexMethodID, + sm.FlexMethod, + sm.EntityGroupConfigGUID, + sm.Name, + sm.IsNew + INTO #noFlexConfigMapping + FROM #statisticsMapping sm + INNER JOIN fp.EntityGroupConfig egc ON sm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + LEFT JOIN fp.FlexConfigMapping fcm ON fcm.EntityGroupConfigID = egc.EntityGroupConfigID + AND fcm.DepartmentID = sm.DepartmentID + AND fcm.PRJobCodeID = sm.JobCodeID + AND fcm.FlexingTypeID = 3 -- Staffing + WHERE fcm.StatAccountID IS NULL + + IF (@IsDebug = 1) + BEGIN + SELECT '#noFlexConfigMapping' AS '#noFlexConfigMapping', * FROM #noFlexConfigMapping + END + + IF EXISTS (SELECT 1 FROM #noFlexConfigMapping) + BEGIN + INSERT INTO #finalValidatedTable (DepartmentID, JobCodeID, FlexMethodID, FlexMethod, Detail, EntityGroupConfigGUID, EntityGroupConfigName, IsNew) + SELECT + DepartmentID, + JobCodeID, + FlexMethodID, + FlexMethod, + -- Aka, if it falls in here, we're missing something in this script. + -- In this case, we need to debug [fp].[procNonStaffingByStatisticsFlexConfigPopulation] + 'An unknown error prevented the Department/Job Code from flexing. Contact support@stratadecision.com.', + EntityGroupConfigGUID, + Name, + IsNew + FROM #noFlexConfigMapping + + DELETE atv + FROM #departmentsToValidate atv + INNER JOIN #noFlexConfigMapping mps ON atv.DepartmentID = mps.DepartmentID AND mps.JobCodeID = atv.JobCodeID + + DELETE atv + FROM #statisticsMapping atv + INNER JOIN #noFlexConfigMapping mps ON atv.DepartmentID = mps.DepartmentID AND mps.JobCodeID = atv.JobCodeID + END + + -- Return final results + SELECT dep.DepartmentCode, dep.Description as DepartmentDescription, jc.JobCode, jc.Description as JobCodeDescription, fv.* + FROM #finalValidatedTable fv + INNER JOIN fw.DimDepartment dep ON dep.DepartmentID = fv.DepartmentID + INNER JOIN fw.DimJobCode jc ON jc.JobCodeID = fv.JobCodeID +END +GO + + +--------------------------------------------- + +-- fp.procGetStaffingVariableDataForServiceLineVolumeFlexing +CREATE PROCEDURE [fp].[procGetStaffingVariableDataForServiceLineVolumeFlexing] + @EntityGroupConfigGUID UNIQUEIDENTIFIER, + @EntityGroupConfigID INT, + @FiscalYearID SMALLINT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + /********************************************************************* + ** Change History + ********************************************************************** + ** CID Date Author WI Description + ** 1 2021-09-10 NT JAZZ-25494 Initial. This is a replacemnet for funcGetStaffingVariableDataForServiceLineVolumeFlexing + that contained the dreaded "OR DepartmentID IS NULL" clause and unnecessary REPLACE. + ** 2 2021-09-24 MD JAZZ-25923 Update load to INNER JOIN on fp.FlexConfigMapping + ** 3 2022-07-21 MD JAZZ-38981 Add projection data pull (behind flag) + ** 4 2023-10-31 MY JAZZ-61705 Support PAF for the new data model - Staffing + ** 5 2024-06-14 SM JAZZ-71536 change JobCodeID from smallint to int + ** 6 2024-10-17 NT JAZZ-78775 change to pull correct original values + *********************************************************************/ + + EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment' + EXEC [dbo].[procSysDropTempTable] '#FilteredData' + EXEC [dbo].[procSysDropTempTable] '#staffingPivoted' + + DECLARE @IsProjectionFlexingEnabled bit + SELECT @IsProjectionFlexingEnabled = CAST(Value AS BIT) + FROM fp.SystemSetting + WHERE Name = 'Is Baseline And Projection PAF Enabled' + + CREATE TABLE #StaffingData ( + RowID INT, + BasisID INT, + BudgetPhaseID TINYINT, + TimeClassID TINYINT, + DepartmentID INT, + JobCodeID INT, + PayCodeGroupID INT, + FiscalYearID SMALLINT, + FiscalMonthID TINYINT, + OriginalValue DECIMAL(19,8), + PercentAdjustmentFactor DECIMAL(19,8) + ) + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #FilteredData (StaffingID INT PRIMARY KEY CLUSTERED) + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilteredData + SELECT fs.StaffingID + FROM [fp].[Staffing] fs + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = fs.DepartmentID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.VariabilityID = 2 --Variable + END ELSE BEGIN + INSERT INTO #FilteredData + SELECT fs.StaffingID + FROM [fp].[Staffing] fs + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.VariabilityID = 2 --Variable + END + + SELECT + fs.StaffingID, + fs.DepartmentID, + CAST(JobCodeID AS INT) AS JobCodeID, + fs.PayCodeGroupID, + fs.VariabilityID, + 34 AS UnitTypeID, + m.FiscalMonthID, + TargetAdjusted, + BudgetAdjusted, + ProjectionAdjusted, + TargetPercentAdjustmentFactor, + BudgetPercentAdjustmentFactor, + ProjectionPercentAdjustmentFactor + INTO #staffingPivoted + FROM fp.Staffing fs + INNER JOIN #FilteredData ft ON ft.StaffingID = fs.StaffingID + INNER JOIN [fp].[FlexConfigMapping] map + ON fs.DepartmentID = map.DepartmentID + AND fs.JobCodeID = map.PRJobCodeID + AND fs.EntityGroupConfigID = map.EntityGroupConfigID + AND map.FlexingTypeID = 7 + CROSS APPLY ( + VALUES + (01, TargetAdjustedDollars01, BudgetAdjustedDollars01, ProjectionAdjustedDollars01, TargetDollarsPercentAdjustmentFactor01, BudgetDollarsPercentAdjustmentFactor01, ProjectionDollarsPercentAdjustmentFactor01), + (02, TargetAdjustedDollars02, BudgetAdjustedDollars02, ProjectionAdjustedDollars02, TargetDollarsPercentAdjustmentFactor02, BudgetDollarsPercentAdjustmentFactor02, ProjectionDollarsPercentAdjustmentFactor02), + (03, TargetAdjustedDollars03, BudgetAdjustedDollars03, ProjectionAdjustedDollars03, TargetDollarsPercentAdjustmentFactor03, BudgetDollarsPercentAdjustmentFactor03, ProjectionDollarsPercentAdjustmentFactor03), + (04, TargetAdjustedDollars04, BudgetAdjustedDollars04, ProjectionAdjustedDollars04, TargetDollarsPercentAdjustmentFactor04, BudgetDollarsPercentAdjustmentFactor04, ProjectionDollarsPercentAdjustmentFactor04), + (05, TargetAdjustedDollars05, BudgetAdjustedDollars05, ProjectionAdjustedDollars05, TargetDollarsPercentAdjustmentFactor05, BudgetDollarsPercentAdjustmentFactor05, ProjectionDollarsPercentAdjustmentFactor05), + (06, TargetAdjustedDollars06, BudgetAdjustedDollars06, ProjectionAdjustedDollars06, TargetDollarsPercentAdjustmentFactor06, BudgetDollarsPercentAdjustmentFactor06, ProjectionDollarsPercentAdjustmentFactor06), + (07, TargetAdjustedDollars07, BudgetAdjustedDollars07, ProjectionAdjustedDollars07, TargetDollarsPercentAdjustmentFactor07, BudgetDollarsPercentAdjustmentFactor07, ProjectionDollarsPercentAdjustmentFactor07), + (08, TargetAdjustedDollars08, BudgetAdjustedDollars08, ProjectionAdjustedDollars08, TargetDollarsPercentAdjustmentFactor08, BudgetDollarsPercentAdjustmentFactor08, ProjectionDollarsPercentAdjustmentFactor08), + (09, TargetAdjustedDollars09, BudgetAdjustedDollars09, ProjectionAdjustedDollars09, TargetDollarsPercentAdjustmentFactor09, BudgetDollarsPercentAdjustmentFactor09, ProjectionDollarsPercentAdjustmentFactor09), + (10, TargetAdjustedDollars10, BudgetAdjustedDollars10, ProjectionAdjustedDollars10, TargetDollarsPercentAdjustmentFactor10, BudgetDollarsPercentAdjustmentFactor10, ProjectionDollarsPercentAdjustmentFactor10), + (11, TargetAdjustedDollars11, BudgetAdjustedDollars11, ProjectionAdjustedDollars11, TargetDollarsPercentAdjustmentFactor11, BudgetDollarsPercentAdjustmentFactor11, ProjectionDollarsPercentAdjustmentFactor11), + (12, TargetAdjustedDollars12, BudgetAdjustedDollars12, ProjectionAdjustedDollars12, TargetDollarsPercentAdjustmentFactor12, BudgetDollarsPercentAdjustmentFactor12, ProjectionDollarsPercentAdjustmentFactor12) + ) AS CrossApplied (MonthSortOrder, TargetAdjusted, BudgetAdjusted, ProjectionAdjusted, TargetPercentAdjustmentFactor, BudgetPercentAdjustmentFactor, ProjectionPercentAdjustmentFactor) + LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.MonthSortOrder + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + + INSERT INTO #StaffingData (RowID, BasisID, BudgetPhaseID, TimeClassID, DepartmentID, JobCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, OriginalValue, PercentAdjustmentFactor) + SELECT + StaffingID AS RowID, + StaffingID AS BasisID, + CAST(2 AS TINYINT) AS BudgetPhaseID, + CAST(2 AS TINYINT) AS TimeClassID, + DepartmentID, + JobCodeID, + PayCodeGroupID, + @FiscalYearID as FiscalYearID, + FiscalMonthID, + TargetAdjusted AS OriginalValue, + TargetPercentAdjustmentFactor AS PercentAdjustmentFactor + FROM #staffingPivoted + + INSERT INTO #StaffingData (RowID, BasisID, BudgetPhaseID, TimeClassID, DepartmentID, JobCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, OriginalValue, PercentAdjustmentFactor) + SELECT + StaffingID AS RowID, + StaffingID AS BasisID, + CAST(3 AS TINYINT) AS BudgetPhaseID, + CAST(2 AS TINYINT) AS TimeClassID, + DepartmentID, + JobCodeID, + PayCodeGroupID, + @FiscalYearID as FiscalYearID, + FiscalMonthID, + BudgetAdjusted AS OriginalValue, + BudgetPercentAdjustmentFactor AS PercentAdjustmentFactor + FROM #staffingPivoted + + IF(@IsProjectionFlexingEnabled = 1) -- JAZZ-40536 + BEGIN + INSERT INTO #StaffingData (RowID, BasisID, BudgetPhaseID, TimeClassID, DepartmentID, JobCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, OriginalValue, PercentAdjustmentFactor) + SELECT + StaffingID AS RowID, + StaffingID AS BasisID, + CAST(3 AS TINYINT) AS BudgetPhaseID, + CAST(12 AS TINYINT) AS TimeClassID, + DepartmentID, + JobCodeID, + PayCodeGroupID, + @FiscalYearID as FiscalYearID, -- This is technically wrong, but leaving it for now as I don't know what this might impact. + FiscalMonthID, + ProjectionAdjusted AS OriginalValue, + ProjectionPercentAdjustmentFactor AS PercentAdjustmentFactor + FROM #staffingPivoted + END + + -- Return final results + SELECT RowID, BasisID, BudgetPhaseID, TimeClassID, DepartmentID, JobCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, OriginalValue, PercentAdjustmentFactor + FROM #StaffingData + + END; +GO + + +--------------------------------------------- + +-- fp.procGetStaffingVariableDataForServiceLineVolumeFlexing_Initials +CREATE PROCEDURE [fp].[procGetStaffingVariableDataForServiceLineVolumeFlexing_Initials] + @EntityGroupConfigGUID UNIQUEIDENTIFIER, + @EntityGroupConfigID INT, + @FiscalYearID SMALLINT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + /********************************************************************* + ** Change History + ********************************************************************** + ** CID Date Author WI Description + ** 1 2022-07-12 MD JAZZ-38981 Initial + ** 2 2023-10-31 MY JAZZ-61705 Support PAF for the new data model - Staffing + ** 3 2024-06-14 SM JAZZ-71536 change JobCodeID from smallint to int + *********************************************************************/ + + EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment' + EXEC [dbo].[procSysDropTempTable] '#FilteredData' + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #FilteredData (StaffingID INT PRIMARY KEY CLUSTERED) + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilteredData + SELECT fs.StaffingID + FROM [fp].[Staffing] fs + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = fs.DepartmentID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.VariabilityID = 2 --Variable + END ELSE BEGIN + INSERT INTO #FilteredData + SELECT fs.StaffingID + FROM [fp].[Staffing] fs + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.VariabilityID = 2 --Variable + END + + SELECT + StaffingID AS BasisID, + TimeClassID, + DepartmentID, + CAST(JobCodeID AS INT) AS JobCodeID, + PayCodeGroupID, + @FiscalYearID, + FiscalMonthID, + OriginalValue + FROM + ( + SELECT + fs.StaffingID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + CAST(2 AS TINYINT) AS TimeClassID, + fs.InitialBudgetDollars01 AS 'Month01', + fs.InitialBudgetDollars02 AS 'Month02', + fs.InitialBudgetDollars03 AS 'Month03', + fs.InitialBudgetDollars04 AS 'Month04', + fs.InitialBudgetDollars05 AS 'Month05', + fs.InitialBudgetDollars06 AS 'Month06', + fs.InitialBudgetDollars07 AS 'Month07', + fs.InitialBudgetDollars08 AS 'Month08', + fs.InitialBudgetDollars09 AS 'Month09', + fs.InitialBudgetDollars10 AS 'Month10', + fs.InitialBudgetDollars11 AS 'Month11', + fs.InitialBudgetDollars12 AS 'Month12' + FROM [fp].[Staffing] fs + INNER JOIN #FilteredData ft ON ft.StaffingID = fs.StaffingID + INNER JOIN [fp].[FlexConfigMapping] map ON fs.DepartmentID = map.DepartmentID + AND fs.JobCodeID = map.PRJobCodeID + AND fs.EntityGroupConfigID = map.EntityGroupConfigID + WHERE map.FlexingTypeID = 7 + ) PIV + UNPIVOT(OriginalValue FOR FiscalMonth IN ([Month01], [Month02], [Month03], [Month04], [Month05], [Month06], [Month07], [Month08], [Month09], [Month10], [Month11], [Month12])) AS f + LEFT JOIN fw.DimFiscalMonth m WITH (readuncommitted) ON m.MonthColumnName = f.FiscalMonth + + END; +GO + + +--------------------------------------------- + +-- fp.procGetWritableDepartmentsByEntityGroupConfigIDRoleID +CREATE PROCEDURE fp.procGetWritableDepartmentsByEntityGroupConfigIDRoleID( + @EntityGroupConfigID AS INT, + @RoleID AS INT + ) + AS + +BEGIN + + -- Disallow NULL + IF (@EntityGroupConfigID IS NULL) + RAISERROR('The value for @EntityGroupConfigID should not be null', 16, 1, @EntityGroupConfigID) + IF (@RoleID IS NULL) + RAISERROR('The value for @RoleID should not be null', 16, 1, @RoleID) + + IF OBJECT_ID('tempdb..#dept_LootID') IS NOT NULL DROP TABLE #dept_LootID + + + CREATE TABLE #dept_LootID ( + [value] [nvarchar](128) NOT NULL PRIMARY KEY CLUSTERED ([value] ASC) WITH (IGNORE_DUP_KEY = OFF), + [DepartmentID] INT NOT NULL + ) + + INSERT INTO #dept_LootID + SELECT CONCAT('Dept|', d.DepartmentID), d.DepartmentID + FROM fp.EntityGroupConfig egc + INNER JOIN fp.EntityGroupConfigMapping egcm ON egc.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID + INNER JOIN fw.viewDimDepartment_Real d ON egcm.EntityID = d.EntityID + WHERE egc.EntityGroupConfigID = @EntityGroupConfigID + + SELECT + UserGUID, acl.RoleID, LootID, dept.DepartmentID + FROM + [dbo].[viewS3ACLDetail] acl + INNER JOIN #dept_LootID dept ON dept.value = acl.LootID + WHERE acl.RoleID = @RoleID + AND acl.WriteAllowpts > acl.WriteDenypts -- IsWritable + + END +GO + + +--------------------------------------------- + +-- fp.procImportRosterAdjustment +/************************************************************************************************************************* +** Change History +************************************************************************************************************************** +** CID Date Author WI Description +** 1 11/13/17 MY B-17923 Creates a Dummy Proc for Roster Changes +*************************************************************************************************************************/ +CREATE PROCEDURE fp.procImportRosterAdjustment + +AS +BEGIN + -- Enter Any Logic that is needed for after saving a Roster Adjustment + PRINT '' +END +GO + + +--------------------------------------------- + +-- fp.procLockBenefitsByConfiguration +CREATE procedure [fp].[procLockBenefitsByConfiguration] + @BudgetConfigID int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @EntityGroupConfigID INT = null, + @AccountID VARCHAR(MAX) = null, + @FinancialReportingID INT = null +AS +BEGIN + + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2018-09-25 GF E-02313 Simplify source dimensionality to only department + ** 2 2019-01-08 MY B-20548 Lock Variable Dollar Records + ** 3 2019-02-12 IP B-22020 Added targeted refresh by adding parameters (added to subqueries). Manager staffing adjustment performance improvements + ** 4 2019-02-14 IP B-22020 Added AccountID as CSV + ** 5 2019-06-03 MY TK-74658 Made some Performance Ehancements to the existing Benefits Lock proc + ** 6 2021-02-16 NN Jazz-466 Remove null joins on dept + ** 7 2022-07-07 MD JAZZ-39280 Replace dbo.ConvertCSValuesToTable with STRING_SPLIT + *************************************************************/ + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[FactBenefits] WITH (READUNCOMMITTED) + WHERE BudgetConfigID = @BudgetConfigID + END + + CREATE TABLE #AccountIDs (AccountID int) + INSERT INTO #AccountIDs (AccountID) + SELECT DISTINCT value as AccountID FROM STRING_SPLIT(@AccountID, ',') + + CREATE TABLE #tmpBenefits (BenefitsID INT, UnitTypeID INT, FlexMethodID INT); + + INSERT INTO #tmpBenefits (BenefitsID, UnitTypeID, FlexMethodID) + SELECT BenefitsID, basis.UnitTypeID, FlexMethodID + FROM [fp].[FactBenefits] basis + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = basis.DepartmentID + WHERE BudgetConfigID = @BudgetConfigID + AND (basis.EntityGroupConfigID = @EntityGroupConfigID or @EntityGroupConfigID is null) + and (basis.AccountID IN ((SELECT AccountID FROM #AccountIDs)) or @AccountID is null) + and (basis.FinancialReportingID = @FinancialReportingID or @FinancialReportingID is null) + + DECLARE @PercentOfSalaries INT = 170, + @DollarsPerFTE INT = 171, + @Dollars INT = 34; + + DECLARE @Fixed INT = 0, + @FlexAccountByFTEs INT = 1, + @FlexAccountBySalaries INT = 2 + + -- Lock $/FTE columns for % of salary or fixed flex methods + UPDATE budg + SET budg.LockFlag = 1, + budg.LockType = 5 + FROM [fp].[FactBenefitsBudget] (READUNCOMMITTED) budg + INNER JOIN #tmpBenefits ben ON budg.BenefitsID = ben.BenefitsID + WHERE ben.FlexMethodID IN (@Fixed, @FlexAccountBySalaries) + AND ben.UnitTypeID = @DollarsPerFTE + AND budg.LockFlag = 0 + + -- Lock % of salary columns for $/FTE or fixed flex methods + UPDATE budg + SET budg.LockFlag = 1, + budg.LockType = 5 + FROM [fp].[FactBenefitsBudget](READUNCOMMITTED) budg + INNER JOIN #tmpBenefits ben ON budg.BenefitsID = ben.BenefitsID + WHERE ben.FlexMethodID IN (@Fixed , @FlexAccountByFTEs) + AND ben.UnitTypeID = @PercentOfSalaries + AND budg.LockFlag = 0 + + -- Lock $/FTE columns for % of salary or fixed flex methods + UPDATE proj + SET proj.LockFlag = 1, + proj.LockType = 5 + FROM [fp].[FactBenefitsProjection](READUNCOMMITTED) proj + INNER JOIN #tmpBenefits ben ON proj.BenefitsID = ben.BenefitsID + WHERE ben.FlexMethodID IN (@Fixed, @FlexAccountBySalaries) + AND ben.UnitTypeID = @DollarsPerFTE + AND proj.LockFlag = 0 + + -- Lock % of salary columns for $/FTE or fixed flex methods + UPDATE proj + SET proj.LockFlag = 1, + proj.LockType = 5 + FROM [fp].[FactBenefitsProjection](READUNCOMMITTED) proj + INNER JOIN #tmpBenefits ben ON proj.BenefitsID = ben.BenefitsID + WHERE ben.FlexMethodID IN (@Fixed , @FlexAccountByFTEs) + AND ben.UnitTypeID = @PercentOfSalaries + AND proj.LockFlag = 0 + + -- Lock dollar columns for $/FTE or % of Salary flex methods + UPDATE budg + SET budg.LockFlag = 1, + budg.LockType = 5 + FROM [fp].[FactBenefitsBudget](READUNCOMMITTED) budg + INNER JOIN #tmpBenefits ben ON budg.BenefitsID = ben.BenefitsID + WHERE ben.FlexMethodID IN (@FlexAccountBySalaries , @FlexAccountByFTEs) + AND ben.UnitTypeID = @Dollars + AND budg.LockFlag = 0 + + -- Lock dollar columns for $/FTE or % of Salary flex methods + UPDATE proj + SET proj.LockFlag = 1, + proj.LockType = 5 + FROM [fp].[FactBenefitsProjection](READUNCOMMITTED) proj + INNER JOIN #tmpBenefits ben ON proj.BenefitsID = ben.BenefitsID + WHERE ben.FlexMethodID IN (@FlexAccountBySalaries , @FlexAccountByFTEs) + AND ben.UnitTypeID = @Dollars + AND proj.LockFlag = 0 + +END +GO + + +--------------------------------------------- + +-- fp.procLockStaffingByConfiguration +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2019-02-06 BK B-21763 Lock FTE Records That Belong To Specified Productive Classes +** 2 2020-09-16 NN JAZZ-4909 Lock Hours & Wage Rate for Dollars-only Productive Class; Remove Null check +** 3 2023-10-10 MY JAZZ-61397 Update Staffing/Provider Comp adjustments to support data model changes +*************************************************************/ +CREATE PROCEDURE [fp].[procLockStaffingByConfiguration] + @EntityGroupConfigID int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + CREATE TABLE #SourceDimensionality (DepartmentID INT); + INSERT INTO #SourceDimensionality (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + --If #SourceDimensionality is empty pass in all DepartmentIds + IF NOT EXISTS(SELECT 1 FROM #SourceDimensionality where DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #SourceDimensionality (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[Staffing] + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + CREATE TABLE #tmpStaffing (StaffingID INT); + + -- Lock FTEs for PCG/PC that do not use FTEs + UPDATE basis + SET + basis.TargetFTEsLockFlag = 1, + basis.TargetFTEsLockType = 5, + basis.BudgetFTEsLockFlag = 1, + basis.BudgetFTEsLockType = 5, + basis.ProjectionFTEsLockFlag = 1, + basis.ProjectionFTEsLockType = 5 + FROM [fp].[Staffing] basis + INNER JOIN #SourceDimensionality SD ON SD.DepartmentID = basis.DepartmentID + INNER JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on basis.PayCodeGroupID = exc.PayCodeGroupID + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND ( + TargetFTEsLockFlag = 0 OR + BudgetFTEsLockFlag = 0 OR + ProjectionFTEsLockFlag = 0 + ) + + -- Lock hours for dollars only records + UPDATE basis + SET + basis.TargetHoursLockFlag = 1, + basis.TargetHoursLockType = 5, + basis.BudgetHoursLockFlag = 1, + basis.BudgetHoursLockType = 5, + basis.ProjectionHoursLockFlag = 1, + basis.ProjectionHoursLockType = 5 + FROM [fp].[Staffing] basis + INNER JOIN #SourceDimensionality SD ON SD.DepartmentID = basis.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND ProductiveClassID = 4 + AND ( + TargetHoursLockFlag = 0 OR + BudgetHoursLockFlag = 0 OR + ProjectionHoursLockFlag = 0 + ) + + -- Lock wage rate for dollars only records + UPDATE swr + SET + swr.TargetWageRateLockFlag = 1, + swr.TargetWageRateLockType = 5, + swr.BudgetWageRateLockFlag = 1, + swr.BudgetWageRateLockType = 5, + swr.ProjectionWageRateLockFlag = 1, + swr.ProjectionWageRateLockType = 5 + FROM [fp].[StaffingWageRate] swr + INNER JOIN [fp].[Staffing] basis ON basis.StaffingWageRateID = swr.StaffingWageRateID + INNER JOIN #SourceDimensionality SD ON SD.DepartmentID = basis.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND ProductiveClassID = 4 + AND basis.VariabilityID = 1 + AND ( + TargetWageRateLockFlag = 0 OR + BudgetWageRateLockFlag = 0 OR + ProjectionWageRateLockFlag = 0 + ) + +END +GO + + +--------------------------------------------- + +-- fp.procMRProviderBudgetStampOff +CREATE PROCEDURE [fp].[procMRProviderBudgetStampOff] + @BudgetConfigID INT, + @TargetTimeClassID TINYINT +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 05-08-2023 BW JAZZ-51541 Initial Creation + ** 2 01-03-2024 MZ JAZZ-65385 Added Target TimeClass + ** 3 12-04-2023 BW/MZ JAZZ-63562 Data model restructure for Staffing/Merge with main + ** 4 03-18-2024 MZ JAZZ-68428 Deleting by Chunks & removed HistoryItemGUID parameter + ** 5 06-14-2024 MZ JAZZ-73080 Filtering out 0 NPIs providers + *************************************************************/ + + -- Note: The original script was done here https://stratadecision.atlassian.net/wiki/spaces/DD/pages/3116205785/Moving+Data+from+a+Plan+Configuration+to+Int+Tables + + DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID ) + DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID) + + DECLARE @HistoryItemGUID UNIQUEIDENTIFIER + EXEC procLogScript 'StampOff: Transferring Budget Data from 1p', @HistoryItemGUID OUTPUT + PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36)) + PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID) + + -- Clear out existing records for the selected FiscalYear and Budgeted Time Class + DECLARE @ChunkCount INT + + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END + + DECLARE @r INT; + SET @r = 1; + + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) FROM [int].[FactImportProvider] WHERE FiscalYearID = @FiscalYear and TimeClassID = @TargetTimeClassID + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + -- Volumes + INSERT INTO [int].[FactImportProvider] ([DepartmentID], [DepartmentCode], [ProviderID], [ProviderCode], [OBForecastDetailID], [AccountRollup], [TimeClassID], [TimeClassCode], + [FiscalYearID], [FiscalYearCode], [FiscalMonthID], [FiscalMonthCode], [Value], [IsDeleted], [HistoryitemGUID]) + SELECT + d.DepartmentID, + d.DepartmentCode, + pr.[ProviderID], + pr.[ProviderCode] , + map.[OBForecastDetailID], + obfd.Code AS AccountRollup, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + bc.FiscalYearID, + bc.FiscalYearID AS FiscalYearCode, + fm.FiscalMonthID, + fm.FiscalMonthCode, + Value AS Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID + FROM ( + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, ProviderID, PatientClassID, PayorID, FinancialReportingID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT cv.StatisticsID, cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.AccountID, cv.ProviderID, PatientClassID, PayorID, FinancialReportingID, + bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, + bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactStatistics cv + INNER JOIN fp.FactStatisticsBudget bdgt ON cv.StatisticsID = bdgt.StatisticsID + Inner JOIN fp.ProviderStatisticsConfig PrConfig ON Prconfig.BudgetConfigID = cv.BudgetConfigID and PrConfig.AccountID = cv.AccountID + WHERE bdgt.BudgetPhaseID = 3 + AND cv.BudgetConfigID = @BudgetConfigID + ) cv + UNPIVOT (Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month') + ) BudgetedData + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = BudgetedData.BudgetConfigID + INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = BudgetedData.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = BudgetedData.FiscalMonthID + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = BudgetedData.AccountID + INNER JOIN [dss].[DimPhysician] ph ON ph.PhysicianID = BudgetedData.ProviderID + INNER JOIN [fw].[DimProvider] pr ON pr.NPI = ph.NPI + INNER JOIN [fp].[AccountOBForecastDetailMapping] map ON map.AccountID = BudgetedData.AccountID AND map.BudgetConfigID = @BudgetConfigID + INNER JOIN [ob].[DimOBForecastDetail] obfd ON obfd.OBForecastDetailID = map.OBForecastDetailID + WHERE 1=1 + AND BudgetedData.Value <> 0 + AND bc.BudgetConfigID = @BudgetConfigID + AND pr.NPI NOT IN ('Not Specified', '0', '') + + -- Compensation + INSERT INTO [int].[FactImportProvider] ([DepartmentID], [DepartmentCode], [ProviderID], [ProviderCode], [OBForecastDetailID], [AccountRollup], [TimeClassID], [TimeClassCode], + [FiscalYearID], [FiscalYearCode], [FiscalMonthID], [FiscalMonthCode], [Value], [IsDeleted], [HistoryitemGUID]) + SELECT + d.DepartmentID, + d.DepartmentCode, + pr.ProviderID, + pr.ProviderCode, + map.[OBForecastDetailID] AS [OBForecastDetailID], + obfd.Code AS AccountRollup, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + bc.FiscalYearID, + bc.FiscalYearID AS FiscalYearCode, + m.FiscalMonthID, + m.FiscalMonthCode, + Value AS Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID + FROM fp.Staffing staff (READUNCOMMITTED) + INNER JOIN fp.ProviderStaffingConfig PrConfig ON Prconfig.BudgetConfigID = staff.BudgetConfigID and PrConfig.ProviderLineItemID = staff.ProviderLineItemID + CROSS APPLY ( + VALUES + ( 1, 34, BudgetAdjustedDollars01), + ( 2, 34, BudgetAdjustedDollars02), + ( 3, 34, BudgetAdjustedDollars03), + ( 4, 34, BudgetAdjustedDollars04), + ( 5, 34, BudgetAdjustedDollars05), + ( 6, 34, BudgetAdjustedDollars06), + ( 7, 34, BudgetAdjustedDollars07), + ( 8, 34, BudgetAdjustedDollars08), + ( 9, 34, BudgetAdjustedDollars09), + ( 10, 34, BudgetAdjustedDollars10), + ( 11, 34, BudgetAdjustedDollars11), + ( 12, 34, BudgetAdjustedDollars12) + ) AS CrossApplied (FiscalMonth, UnitTypeID, Value) + LEFT JOIN fw.DimUnitType ut ON ut.UnitTypeID = CrossApplied.UnitTypeID + LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.FiscalMonth + INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = staff.DepartmentID + INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [dss].[DimPhysician] ph ON ph.PhysicianID = staff.ProviderID + INNER JOIN [fw].[DimProvider] pr ON pr.NPI = ph.NPI + INNER JOIN [fp].[ProviderLineItemOBForecastDetailMapping] map ON map.ProviderLineItemID = staff.ProviderLineItemID AND map.BudgetConfigID = @BudgetConfigID + INNER JOIN [ob].[DimOBForecastDetail] obfd ON obfd.OBForecastDetailID = map.OBForecastDetailID + WHERE Value <> 0 + AND bc.BudgetConfigID = @BudgetConfigID + AND pr.NPI NOT IN ('Not Specified', '0', '') +END +GO + + +--------------------------------------------- + +-- fp.procMRProviderProjectionStampOff +CREATE PROCEDURE [fp].[procMRProviderProjectionStampOff] + @BudgetConfigID INT, + @TargetTimeClassID TINYINT, + @IsMonthsLoadedIncluded BIT +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 11-10-2023 AO JAZZ-62128 Initial Creation + ** 2 01-04-2024 MZ JAZZ-65385 Added Target TimeClass and IsMonthsLoadedIncluded + ** 3 01-24-2024 MZ JAZZ-64527 Fix Months Loaded + ** 4 12-04-2023 BW/MZ JAZZ-63562 Data model restructure for Staffing/Merge with main + ** 5 03-18-2024 MZ JAZZ-68428 Deleting by Chunks & removed HistoryItemGUID parameter + ** 6 04-03-2024 MZ JAZZ-70053 Fix Month Loaded excluding logic + ** 7 06-14-2024 MZ JAZZ-73080 Filtering out 0 NPIs providers + *************************************************************/ + + -- Note: The original script was done here https://stratadecision.atlassian.net/wiki/spaces/DD/pages/3116205785/Moving+Data+from+a+Plan+Configuration+to+Int+Tables + + DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID - 1 FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID ) + DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID) + DECLARE @MonthsLoaded INT = (SELECT bc.MonthsLoaded FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID) + + DECLARE @HistoryItemGUID UNIQUEIDENTIFIER + EXEC procLogScript 'StampOff: Transferring Projection Data from 1p', @HistoryItemGUID OUTPUT + PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36)) + PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID) + + -- Clear out existing records for the selected FiscalYear and Projected Time Class + -- and all months if months loaded included otherwise only months NOT loaded will be cleared + DECLARE @ChunkCount INT + + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END + + DECLARE @r INT; + SET @r = 1; + + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) prov FROM [int].[FactImportProvider] prov + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID + WHERE prov.FiscalYearID = @FiscalYear + AND prov.TimeClassID = @TargetTimeClassID + AND (@IsMonthsLoadedIncluded = 1 OR fm.SortOrder > @MonthsLoaded) + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + -- Volumes + INSERT INTO [int].[FactImportProvider] ([DepartmentID], [DepartmentCode], [ProviderID], [ProviderCode], [OBForecastDetailID], [AccountRollup], [TimeClassID], [TimeClassCode], + [FiscalYearID], [FiscalYearCode], [FiscalMonthID], [FiscalMonthCode], [Value], [IsDeleted], [HistoryitemGUID]) + SELECT + d.DepartmentID, + d.DepartmentCode, + pr.[ProviderID], + pr.[ProviderCode] , + map.[OBForecastDetailID], + obfd.Code AS AccountRollup, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + @FiscalYear, + @FiscalYear AS FiscalYearCode, + fm.FiscalMonthID, + fm.FiscalMonthCode, + Value AS Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID + FROM ( + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, ProviderID, PatientClassID, PayorID, FinancialReportingID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT cv.StatisticsID, cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.AccountID, cv.ProviderID, PatientClassID, PayorID, FinancialReportingID, + bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, + bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactStatistics cv + INNER JOIN fp.FactStatisticsProjection bdgt ON cv.StatisticsID = bdgt.StatisticsID + INNER JOIN fp.ProviderStatisticsConfig PrConfig ON Prconfig.BudgetConfigID = cv.BudgetConfigID and PrConfig.AccountID = cv.AccountID + WHERE bdgt.BudgetPhaseID = 3 + AND cv.BudgetConfigID = @BudgetConfigID + ) cv + UNPIVOT (Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month') + ) BudgetedData + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = BudgetedData.BudgetConfigID + INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = BudgetedData.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = BudgetedData.FiscalMonthID + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = BudgetedData.AccountID + INNER JOIN [dss].[DimPhysician] ph ON ph.PhysicianID = BudgetedData.ProviderID + INNER JOIN [fw].[DimProvider] pr ON pr.NPI = ph.NPI + INNER JOIN [fp].[AccountOBForecastDetailMapping] map ON map.AccountID = BudgetedData.AccountID AND map.BudgetConfigID = @BudgetConfigID + INNER JOIN [ob].[DimOBForecastDetail] obfd ON obfd.OBForecastDetailID = map.OBForecastDetailID + WHERE 1=1 + AND BudgetedData.Value <> 0 + AND bc.BudgetConfigID = @BudgetConfigID + AND pr.NPI NOT IN ('Not Specified', '0', '') + AND (@IsMonthsLoadedIncluded = 1 OR CAST(fm.FiscalMonthCode AS INT) > bc.MonthsLoaded) + + -- Compensation + INSERT INTO [int].[FactImportProvider] ([DepartmentID], [DepartmentCode], [ProviderID], [ProviderCode], [OBForecastDetailID], [AccountRollup], [TimeClassID], [TimeClassCode], + [FiscalYearID], [FiscalYearCode], [FiscalMonthID], [FiscalMonthCode], [Value], [IsDeleted], [HistoryitemGUID]) + SELECT + d.DepartmentID, + d.DepartmentCode, + pr.ProviderID, + pr.ProviderCode, + map.[OBForecastDetailID] AS [OBForecastDetailID], + obfd.Code AS AccountRollup, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + @FiscalYear, + @FiscalYear AS FiscalYearCode, + m.FiscalMonthID, + m.FiscalMonthCode, + Value AS Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID + FROM fp.Staffing staff (READUNCOMMITTED) + INNER JOIN fp.ProviderStaffingConfig PrConfig ON Prconfig.BudgetConfigID = staff.BudgetConfigID and PrConfig.ProviderLineItemID = staff.ProviderLineItemID + CROSS APPLY ( + VALUES + ( 1, 34, ProjectionAdjustedDollars01), + ( 2, 34, ProjectionAdjustedDollars02), + ( 3, 34, ProjectionAdjustedDollars03), + ( 4, 34, ProjectionAdjustedDollars04), + ( 5, 34, ProjectionAdjustedDollars05), + ( 6, 34, ProjectionAdjustedDollars06), + ( 7, 34, ProjectionAdjustedDollars07), + ( 8, 34, ProjectionAdjustedDollars08), + ( 9, 34, ProjectionAdjustedDollars09), + ( 10, 34, ProjectionAdjustedDollars10), + ( 11, 34, ProjectionAdjustedDollars11), + ( 12, 34, ProjectionAdjustedDollars12) + ) AS CrossApplied (FiscalMonth, UnitTypeID, Value) + LEFT JOIN fw.DimUnitType ut ON ut.UnitTypeID = CrossApplied.UnitTypeID + LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.FiscalMonth + INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = staff.DepartmentID + INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [dss].[DimPhysician] ph ON ph.PhysicianID = staff.ProviderID + INNER JOIN [fw].[DimProvider] pr ON pr.NPI = ph.NPI + INNER JOIN [fp].[ProviderLineItemOBForecastDetailMapping] map ON map.ProviderLineItemID = staff.ProviderLineItemID AND map.BudgetConfigID = @BudgetConfigID + INNER JOIN [ob].[DimOBForecastDetail] obfd ON obfd.OBForecastDetailID = map.OBForecastDetailID + WHERE Value <> 0 + AND bc.BudgetConfigID = @BudgetConfigID + AND pr.NPI NOT IN ('Not Specified', '0', '') + AND (@IsMonthsLoadedIncluded = 1 OR CAST(m.FiscalMonthCode AS INT) > bc.MonthsLoaded) +END +GO + + +--------------------------------------------- + +-- fp.procMigrationConflictCheck +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-09-26 GF E-02313 Created to monitor for possible merge conflicts +*************************************************************/ +create proc fp.procMigrationConflictCheck + @versionService nvarchar(100), + @versionMajor nvarchar(100) +as + select p.name into #procs from sys.procedures p inner join sys.schemas s on s.schema_id = p.schema_id where s.name = 'fp' + + select + p.name as ProcName, + l.MigrationID, + l.Name, + l.Branch, + l.DateTimeStamp, + l.ForwardScript + into #procHistory + from + migration.migrationlog l + inner join #procs p on l.ForwardScript like '%' + p.name + '%' + where + l.branch in(@versionService, @versionMajor) + and l.sourcefolder = 'OB' + + select + hService.ProcName, + hService.Name as ServiceMigration, + hService.DateTimeStamp as ServiceMigrationRunDate, + hService.ForwardScript as ServiceForwardScript, + hMajor.Name as MajorMigration, + hMajor.DateTimeStamp as MajorMigrationRunDate, + hMajor.ForwardScript as MajorForwardScript + from + #procHistory hService + inner join #procHistory hMajor on hService.ProcName = hMajor.ProcName and hService.MigrationID != hMajor.MigrationID + where + hService.Branch = @versionService + and hMajor.Branch = @versionMajor + and hService.DateTimeStamp > hMajor.DateTimeStamp; + + drop table #procs + drop table #procHistory +GO + + +--------------------------------------------- + +-- fp.procNonStaffingByStatisticsFlexConfigPopulation +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-06-12 IP D-05613 APE Data Refresh - Flex Mappings, add parameter to process particular departments +** 2 2018-07-03 IP TK-59678 fix case when @SourceDimensionality is empty +** 3 2018-08-22 IP TK-62741 fix case validating if @SourceDimensionality is empty +** 4 2018-09-25 GF E-02313 Simplify source dimensionality to only department +** 5 2019-03-08 IP B-22295 Removed using table variables, small optimizations +** 6 2021-03-26 NT JAZZ-14122 Simplify code to remove null joins +** 7 2023-02-06 MY JAZZ-48980 Update flexing to support x-department flexing +** 8 2023-05-01 MY JAZZ-54277 Flex Config Mapping is not taking handling Cross Department Flexing properly +** 9 2023-08-09 BK JAZZ-58152 Update for new data structure +*************************************************************/ +CREATE PROCEDURE [fp].[procNonStaffingByStatisticsFlexConfigPopulation] + @EntityGroupConfigGUID UNIQUEIDENTIFIER, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + EXEC [dbo].[procSysDropTempTable] '#flexMap' + EXEC [dbo].[procSysDropTempTable] '#SourceDimensionality' + + DECLARE @BudgetConfigID INT, + @EntityGroupConfigID INT; + + SET @BudgetConfigID = (SELECT bc.BudgetConfigID + FROM [fp].[EntityGroupConfig] egc + INNER JOIN [fp].[BudgetConfig] bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID) + SET @EntityGroupConfigID = (SELECT EntityGroupConfigID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID) + + CREATE TABLE #flexMap ( + DepartmentID INT NOT NULL, + GLAccountID INT NOT NULL, + StatAccountID INT NOT NULL, + SourceDepartmentID INT NOT NULL + ); + + CREATE TABLE #SourceDimensionality (DepartmentID int) + INSERT INTO #SourceDimensionality (DepartmentID) + SELECT DepartmentID FROM @SourceDimensionality + + --If department filter table is empty then get distinct from FactStatistics + IF NOT EXISTS (SELECT 1 FROM #SourceDimensionality) + BEGIN + INSERT INTO #SourceDimensionality(DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[PrimaryStatisticsConfig] + WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID + AND IsNonStaffing = 1 + END + + -- Process the overrides as they overidde all configurations + INSERT INTO #flexMap(DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID) + SELECT DISTINCT stat.DepartmentID, fgl.AccountID AS GLAccountID, nso.AccountID AS StatAccountID, stat.DepartmentID + FROM [fp].[FactStatistics] stat + INNER JOIN [fp].[GeneralLedger] fgl ON fgl.DepartmentID = stat.DepartmentID and fgl.BudgetConfigID = stat.BudgetConfigID + INNER JOIN [fp].[NonStaffingExpenseFlexingOverrideConfig] ns ON ns.DepartmentID = fgl.DepartmentID AND ns.AccountID = fgl.AccountID + INNER JOIN [fp].[NSOverrideFlexConfigAssignment] nso ON nso.OverrideFlexConfigGUID = ns.OverrideFlexConfigGUID + INNER JOIN #SourceDimensionality SD on SD.DepartmentID = fgl.DepartmentID + WHERE fgl.APEModelSectionID = 2 + AND ns.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND stat.BudgetConfigID = @BudgetConfigID + AND ns.FlexMethodID = 1 -- Statistics Accounts + AND fgl.VariabilityID = 2 -- Variable only (simply to filter the data) + + -- Process department level configuration changes that are not overriden. We also will exclude Department/Account combos + -- that have multiple source departments here as that is handled in the statement below. + -- Aka: Process the Department/Account combinations that have primary stats of "Same as Department" in the Primary Stat Config + INSERT INTO #flexMap(DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID) + SELECT DISTINCT stat.DepartmentID, fgl.AccountID AS GLAccountID, stat.AccountID AS StatAccountID, stat.DepartmentID + FROM [fp].[FactStatistics] stat + INNER JOIN [fp].[PrimaryStatisticsConfig] fsc ON fsc.DepartmentID = stat.DepartmentID AND fsc.AccountID = stat.AccountID + INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID = fsc.EntityGroupConfigGUID + INNER JOIN [fp].[GeneralLedger] fgl ON fgl.DepartmentID = stat.DepartmentID and fgl.BudgetConfigID = stat.BudgetConfigID + INNER JOIN [fp].[NonStaffingExpenseFlexingConfig] ns ON ns.DepartmentID = fgl.DepartmentID + INNER JOIN #SourceDimensionality SD on SD.DepartmentID = fgl.DepartmentID + LEFT JOIN ( + SELECT DepartmentID, AccountID + FROM [fp].[NonStaffingExpenseFlexingOverrideConfig] + WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID) ovr + ON ovr.DepartmentID = stat.DepartmentID + AND ovr.AccountID = fgl.AccountID + LEFT JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscsd ON fsc.RowID = pscsd.PrimaryStatisticsConfigID + WHERE fgl.APEModelSectionID = 2 + AND fsc.IsNonStaffing = 1 + AND fsc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND ns.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND stat.BudgetConfigID = @BudgetConfigID + AND ns.FlexMethodID = 1 -- Statistics Accounts + AND fgl.VariabilityID = 2 -- Variable only (simply to filter the data) + AND ovr.DepartmentID IS NULL -- We only want records that are not overridden + AND pscsd.DepartmentID IS NULL; -- We want records where there is no source department specified. When no source department is specified, it's the same as the regular department + + -- Process departments with multiple source departments + INSERT INTO #flexMap(DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID) + SELECT DISTINCT fsc.DepartmentID, fgl.AccountID AS GLAccountID, stat.AccountID AS StatAccountID, pscsd.DepartmentID + FROM [fp].[PrimaryStatisticsConfig] fsc + INNER JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscsd ON fsc.RowID = pscsd.PrimaryStatisticsConfigID -- We only want records where there are multiple source departments + INNER JOIN [fp].[FactStatistics] stat ON pscsd.DepartmentID = stat.DepartmentID AND fsc.AccountID = stat.AccountID + INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID = fsc.EntityGroupConfigGUID + INNER JOIN [fp].[GeneralLedger] fgl ON fgl.DepartmentID = fsc.DepartmentID and fgl.BudgetConfigID = stat.BudgetConfigID + INNER JOIN [fp].[NonStaffingExpenseFlexingConfig] ns ON ns.DepartmentID = fsc.DepartmentID + INNER JOIN #SourceDimensionality SD on SD.DepartmentID = fsc.DepartmentID + LEFT JOIN ( + SELECT DepartmentID, AccountID + FROM [fp].[NonStaffingExpenseFlexingOverrideConfig] + WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID) ovr + ON ovr.DepartmentID = fsc.DepartmentID + AND ovr.AccountID = fgl.AccountID + WHERE fgl.APEModelSectionID = 2 -- Non-Staffing + AND fsc.IsNonStaffing = 1 + AND fsc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND ns.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND stat.BudgetConfigID = @BudgetConfigID + AND ns.FlexMethodID = 1 -- Statistics Accounts + AND fgl.VariabilityID = 2 -- Variable only (simply to filter the data) + AND ovr.DepartmentID IS NULL; -- We only want records that are not overridden + + IF @IsDebug = 1 + BEGIN + SELECT '#SourceDimensionality', DepartmentID FROM #SourceDimensionality + SELECT '#flexMap', DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID FROM #flexMap + END ELSE + BEGIN + + ;WITH TRG + AS ( + SELECT fcm.EntityGroupConfigID, + fcm.DepartmentID, + fcm.GLAccountID, + fcm.StatAccountID, + fcm.FlexingTypeID, + fcm.SourceDepartmentID + FROM [fp].[FlexConfigMapping] fcm + INNER JOIN #SourceDimensionality SD ON SD.DepartmentID = fcm.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND FlexingTypeID = 1 -- 1 is NonStaffingTypeID + ) + MERGE TRG + USING ( + SELECT @EntityGroupConfigID AS EntityGroupConfigID, + DepartmentID, + GLAccountID, + StatAccountID, + 1 AS FlexingTypeID, -- 1 is NonStaffing (https://confluence.sdt.local/display/DD/Common+Calculations%2C+Equations%2C+IDs%2C+and+Look+Up+Values#CommonCalculations,Equations,IDs,andLookUpValues-FlexingIDs) + SourceDepartmentID + FROM #flexMap + ) AS Src ON TRG.DepartmentID = SRC.DepartmentID + AND TRG.GLAccountID = SRC.GLAccountID + AND TRG.StatAccountID = SRC.StatAccountID + AND TRG.SourceDepartmentID = SRC.SourceDepartmentID + WHEN NOT MATCHED BY TARGET THEN + INSERT VALUES (src.EntityGroupConfigID, src.DepartmentID, src.GLAccountID, src.StatAccountID, src.FlexingTypeID, src.SourceDepartmentID) + WHEN NOT MATCHED BY SOURCE THEN DELETE; + + END + + END +GO + + +--------------------------------------------- + +-- fp.procOptimizationRebuildIndexes +CREATE PROC [fp].[procOptimizationRebuildIndexes] +AS + SET NOCOUNT ON; + + DECLARE @SCHEMA nvarchar(256) + DECLARE @FactTableName nvarchar(256) + DECLARE @SQL nvarchar(1024) + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t + where + t.schema_id in(select schema_id from sys.schemas where name = 'fp') + and t.name not like 'Archive%' + and t.name not like 'Temp%' + order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + --=================== BEGIN CID 1 ===================== + set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE) + update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN' + --=================== END CID 1 ======================= + --print @SQL + EXECUTE sp_executesql @SQL + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor +GO + + +--------------------------------------------- + +-- fp.procPadBenefits +CREATE PROCEDURE [fp].[procPadBenefits] + @BudgetConfigID int, + @EntityGroupConfigID INT = NULL, + @AccountID VARCHAR(MAX) = NULL, + @FinancialReportingID INT = NULL, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + AS + BEGIN + + /************************************************************** + ** Change History + ** CID Date Author WI Description + ** 1 2019-02-12 IP B-22020 Added targeted refresh by adding parameters (added to subqueries). Manager staffing adjustment performance improvements + ** 2 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table + ** 3 2019-04-30 BK D-08400 Fix duplicate key error on insert + ** 4 2019-06-03 MY TK-74658 Removing Table Varibles in query + ** 5 2021-02-16 NN Jazz-466 Remove null joins on dept + ** 6 2022-07-07 MD JAZZ-39280 Replace dbo.ConvertCSValuesToTable with STRING_SPLIT + *************************************************************/ + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[FactBenefits] WITH (READUNCOMMITTED) + WHERE BudgetConfigID = @BudgetConfigID + END + + CREATE TABLE #AccountIDs (AccountID int) + INSERT INTO #AccountIDs (AccountID) + SELECT DISTINCT value as AccountID FROM STRING_SPLIT(@AccountID, ',') + + CREATE TABLE #BudgetPhase (BudgetPhaseID tinyint) + INSERT INTO #BudgetPhase (BudgetPhaseID) SELECT 2 UNION SELECT 3 + + CREATE TABLE #FilteredData (BenefitsID int) + INSERT INTO #FilteredData + SELECT [fb].[BenefitsID] + FROM [fp].[FactBenefits] fb + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fb.DepartmentID + WHERE fb.BudgetConfigID = @BudgetConfigID + AND (fb.EntityGroupConfigID = @EntityGroupConfigID or @EntityGroupConfigID is null) + and (fb.AccountID IN (SELECT AccountID FROM #AccountIDs) or @AccountID is null) + and (fb.FinancialReportingID = @FinancialReportingID or @FinancialReportingID is null) + + INSERT INTO [fp].[FactBenefitsBudget]([BenefitsID], [BudgetPhaseID]) + SELECT [fb].[BenefitsID], [psh].[BudgetPhaseID] + FROM #FilteredData fb + OUTER APPLY #BudgetPhase psh + WHERE NOT EXISTS (SELECT 1 FROM fp.FactBenefitsBudget bud WITH (READUNCOMMITTED) WHERE fb.BenefitsID = bud.BenefitsID AND bud.BudgetPhaseID = psh.BudgetPhaseID) + + INSERT INTO [fp].[FactBenefitsProjection]([BenefitsID], [BudgetPhaseID]) + SELECT [fb].[BenefitsID], [psh].[BudgetPhaseID] + FROM #FilteredData fb + OUTER APPLY #BudgetPhase psh + WHERE NOT EXISTS (SELECT 1 FROM fp.FactBenefitsProjection proj WITH (READUNCOMMITTED) WHERE fb.BenefitsID = proj.BenefitsID AND proj.BudgetPhaseID = psh.BudgetPhaseID) + + INSERT INTO [fp].[FactBenefitsHistory]([BenefitsID]) + SELECT [fb].[BenefitsID] + FROM #FilteredData fb + WHERE NOT EXISTS (SELECT 1 FROM fp.FactBenefitsHistory hist WITH (READUNCOMMITTED) WHERE fb.BenefitsID = hist.BenefitsID) + END +GO + + +--------------------------------------------- + +-- fp.procPadBenefitsFromStaffing +/************************************************************** +** Change History +** CID Date Author WI Description +** 1 2019-01-15 IP B-21392 Added targeted refresh by adding parameters +** 2 2019-02-12 IP B-22020 Added targeted refresh by adding parameters (added to subqueries). Manager staffing adjustment performance improvements +** 3 2019-02-14 IP B-22020 Added AccountID as CSV +** 4 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table +** 5 2019-05-10 PA D-08438 More switch usages of funcGetSourceDimensionalityAsTable to a temp table +** 6 2019-05-13 PA D-08438 Move padding proc inside if block +** 7 2019-05-13 PA D-08438 Use @@RowCount and Select Into +** 8 2020-04-02 LR B-24089 Removed check for null within join conditions +** 9 2022-08-31 BW JAZZ-41678 Insert the assignment config's jc/pcg detail into a temp table for the @PayrollFilterSQL to join on +** 10 2023-10-31 BK JAZZ-62801 Update for Staffing restructure +*************************************************************/ +CREATE PROCEDURE [fp].[procPadBenefitsFromStaffing] + @BudgetConfigID INT, + @EntityGroupConfigID INT, + @AccountID VARCHAR(MAX), + @FinancialReportingID INT, + @FlexMethodID INT, + @PayrollFilterSQL VARCHAR(MAX), + @PayrollFilterTempTableSQL VARCHAR(MAX), + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +WITH RECOMPILE +AS +BEGIN + -- Temp workaround so benefits flexing does blow up overnight + SET NOCOUNT ON; + + IF OBJECT_ID('tempdb..#AccountsList') IS NOT NULL DROP TABLE #AccountsList + -- Used in benefits flexing to pad data from staffing that are not in benefits. Doing this in flexing, but I can move this to repo, I'm just concerned with that + -- method getting overly bogged down. We'd also need to make this a datarefresh method cause it would need to get called before flexing runs after sampling ran initially. + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF object_id('tempdb..#paddedBenefits') IS NOT NULL + BEGIN + DROP TABLE #paddedBenefits + END + CREATE TABLE #paddedBenefits (BudgetConfigID INT, EntityGroupConfigID INT, EntityID INT, DepartmentID INT, AccountID INT, + FinancialReportingID INT, UnitTypeID INT, FlexMethodID INT) + + DECLARE @DynamicSql NVARCHAR(MAX) + + set @DynamicSql = ' + ' + @PayrollFilterTempTableSQL + ' + + CREATE TABLE #accountIdList (AccountID INT PRIMARY KEY CLUSTERED) + INSERT INTO #accountIdList (AccountID) + SELECT DISTINCT value as AccountID FROM STRING_SPLIT('''+@AccountID+''','','') + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[FactBenefits] d WITH (READUNCOMMITTED) + WHERE BudgetConfigID = @BudgetConfigID + END + + INSERT INTO #paddedBenefits + SELECT DISTINCT + pr.BudgetConfigID, + pr.EntityGroupConfigID, + pr.EntityID, + pr.DepartmentID, + AccLst.AccountID, + ' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID, + ut.UnitTypeID, + ' + CAST(@FlexMethodID as nvarchar(50)) + ' AS FlexMethodID + FROM [fp].[Staffing] (READUNCOMMITTED) pr + CROSS APPLY (VALUES (34),(170),(171),(144),(169)) ut(UnitTypeID) + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = pr.DepartmentID) + CROSS APPLY (SELECT AccountID FROM #accountIdList) AccLst + LEFT JOIN [fp].[FactBenefits] (READUNCOMMITTED) fbb ON pr.BudgetConfigID = fbb.BudgetConfigID + AND pr.DepartmentID = fbb.DepartmentID + AND ut.UnitTypeID = fbb.UnitTypeID + AND pr.EntityID = fbb.EntityID + AND fbb.FinancialReportingID = ' + CAST(@FinancialReportingID as nvarchar(50)) + ' + AND fbb.AccountID = AccLst.AccountID + WHERE + pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + AND pr.VariabilityID = 1 + AND ' + @PayrollFilterSQL + ' + AND fbb.BenefitsID IS NULL + + + IF (@@ROWCOUNT > 0) + BEGIN + INSERT INTO [fp].[FactBenefits] (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, FlexMethodID, IsNew, AddDate) + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, FlexMethodID, 1 AS IsNew, GETDATE() AS AddDate FROM #paddedBenefits + + EXEC [fp].[procPadBenefits] @BudgetConfigID, @EntityGroupConfigID, @AccountID, @FinancialReportingID, @SourceDimensionality + + END + + + + -- Pad GL with any newly added benefit accounts + DECLARE @AccountFromList INT + DECLARE cur CURSOR LOCAL + FOR + SELECT DISTINCT AccountID FROM #accountIdList AccLst + OPEN cur + FETCH NEXT FROM cur INTO @AccountFromList + WHILE @@FETCH_STATUS = 0 + BEGIN + --execute your sproc on each row + EXEC [fp].[procLockBenefitsByConfiguration] @BudgetConfigID, @SourceDimensionality, @EntityGroupConfigID, @AccountFromList, @FinancialReportingID + FETCH NEXT FROM cur INTO @AccountFromList + END + CLOSE cur + DEALLOCATE cur + '; + + + EXECUTE sp_executesql @DynamicSql, + N'@BudgetConfigID INT, + @EntityGroupConfigID INT, + @AccountID VARCHAR(MAX), + @FinancialReportingID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY', + @SourceDimensionality = @SourceDimensionality, + @BudgetConfigID = @BudgetConfigID, + @EntityGroupConfigID = @EntityGroupConfigID, + @AccountID = @AccountID, + @FinancialReportingID = @FinancialReportingID; + +END +GO + + +--------------------------------------------- + +-- fp.procPadChargeDollarsToReimbursement +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-01-11 MY JAZZ-31850 Initial +** 2 2022-02-15 BW JAZZ-33266 Pulling in configuration via Plan Config > Section Setup +** 3 2022-06-06 MD JAZZ-37249 Making charge temp table dimensionality unique +** 4 2023-01-30 NT JAZZ-48268 Make change to use the new fp.ChargeVolume (data restructure) +** 5 2024-01-11 AO JAZZ-64530 Data transfer for SLE is based on selected Model in Plan Config +*************************************************************/ +CREATE PROCEDURE [fp].[procPadChargeDollarsToReimbursement] + @BudgetConfigID INT, + @IsReimbursementGLEnabled BIT = 0, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + + DECLARE @IsMedicalSurgicalUsed BIT = 0, + @IsMsdrgUsed BIT = 0, + @IsCptUsed BIT = 0, + @IsUBRevCodeUsed BIT = 0; + + SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'MedicalSurgicalID' + + SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'MSDRGID' + + SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'PrimaryCPTID' + + SELECT @IsUBRevCodeUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'UBRevCodeID' + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + IF OBJECT_ID('tempdb..#factReimbursementCharges') IS NOT NULL DROP TABLE #factReimbursementCharges; + + CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT); + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #factReimbursementCharges ( + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + PatientClassID INT, + ServiceLineID INT, + ServiceLineRollupID INT, + MedicalSurgicalID INT, + PayorID INT, + PayorGroupID INT, + MSDRGID INT, + PrimaryCPTID INT, + UBRevCodeID INT + ) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED) + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = d.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE d.BudgetConfigID = @BudgetConfigID + AND ((@IsReimbursementGLEnabled = 1 + AND (bc.DefaultReimbursementNetRevenueModelID = 1 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model + OR rnrm.NetRevenueModelID = 1) + OR @IsReimbursementGLEnabled = 0) + END + + SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, + CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, + CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID, + CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID + INTO #reimbursementTargeting + FROM fp.ChargeVolume cv + INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID + INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID + WHERE cv.BudgetConfigID = @BudgetConfigID + + -- We are only moving Budget over and not projection because we don't display the baseline for projection so we don't need it. If we do ever need it, we'll need to add it to the mix table as well. + -- For Charges Only Data, we want to stick it in non-specified for Payor and PayorGroup + INSERT INTO #factReimbursementCharges (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, + MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, UBRevCodeID) + SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, + sd.PayorID, sd.PayorGroupID, + CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, + CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID, + CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID + FROM fp.ChargeVolume cv + INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID + INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID + INNER JOIN fp.ServiceLineEncounterToChargePayorMix sd ON cv.ServiceEntityID = sd.EntityID + AND cv.PatientClassID = sd.PatientClassID + AND cv.ServiceLineID = sd.ServiceLineID + AND cv.AgeCohortID = sd.AgeCohortID + AND cv.MedicalSurgicalID = sd.MedicalSurgicalID + AND cv.MSDRGID = sd.MSDRGID + AND cv.PrimaryCPTID = sd.CPTID + AND cv.ServiceProviderID = sd.ProviderID + AND cv.EntityGroupConfigID = sd.EntityGroupConfigID + WHERE cv.BudgetConfigID = @BudgetConfigID + + UNION + + SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, + 0 AS PayorID, 0 AS PayorGroupID, + CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, + CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID, + CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID + FROM fp.ChargeVolume cv + INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID + INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID + LEFT JOIN fp.ServiceLineEncounterToChargePayorMix sd ON cv.ServiceEntityID = sd.EntityID + AND cv.PatientClassID = sd.PatientClassID + AND cv.ServiceLineID = sd.ServiceLineID + AND cv.AgeCohortID = sd.AgeCohortID + AND cv.MedicalSurgicalID = sd.MedicalSurgicalID + AND cv.MSDRGID = sd.MSDRGID + AND cv.PrimaryCPTID = sd.CPTID + AND cv.ServiceProviderID = sd.ProviderID + AND cv.EntityGroupConfigID = sd.EntityGroupConfigID + LEFT JOIN #factReimbursementCharges tmp ON + cv.BudgetConfigID = tmp.BudgetConfigID + AND cv.EntityGroupConfigID = tmp.EntityGroupConfigID + AND cv.EntityID = tmp.EntityID + AND cv.PatientClassID = tmp.PatientClassID + AND cv.ServiceLineID = tmp.ServiceLineID + AND cv.MedicalSurgicalID = tmp.MedicalSurgicalID + AND tmp.PayorID = 0 + AND tmp.PayorGroupID = 0 + AND cv.MSDRGID = tmp.MSDRGID + AND cv.PrimaryCPTID = tmp.PrimaryCPTID + AND cv.UBRevCodeID = tmp.UBRevCodeID + WHERE cv.BudgetConfigID = @BudgetConfigID + AND sd.EntityID IS NULL + AND tmp.BudgetConfigID IS NULL -- Ensure that we didn't already add the 0 PayorID/0 PayorGroupID + + IF (@IsDebug = 1) + BEGIN + SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments + SELECT '#factReimbursementCharges', [BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [MedicalSurgicalID], + [PayorID], [PayorGroupID], [MSDRGID], [PrimaryCPTID], [UBRevCodeID] + FROM #factReimbursementCharges + END ELSE + BEGIN + -- Publish + ;WITH TGT AS + ( + SELECT fact.[BudgetConfigID], fact.[EntityGroupConfigID], fact.[EntityID], fact.[PatientClassID], fact.[ServiceLineID], fact.[ServiceLineRollupID], fact.[MedicalSurgicalID], + [PayorID], [PayorGroupID], fact.[MSDRGID], fact.[PrimaryCPTID], fact.[UBRevCodeID] + FROM [fp].[FactReimbursementCharges] fact + INNER JOIN #reimbursementTargeting targeting ON + fact.BudgetConfigID = targeting.BudgetConfigID + AND fact.EntityGroupConfigID = targeting.EntityGroupConfigID + AND fact.EntityID = targeting.EntityID + AND fact.PatientClassID = targeting.PatientClassID + AND fact.ServiceLineID = targeting.ServiceLineID + AND fact.ServiceLineRollupID = targeting.ServiceLineRollupID + AND fact.MedicalSurgicalID = targeting.MedicalSurgicalID + AND fact.MSDRGID = targeting.MSDRGID + AND fact.PrimaryCPTID = targeting.PrimaryCPTID + AND fact.UBRevCodeID = targeting.UBRevCodeID + WHERE fact.BudgetConfigID = @BudgetConfigID + ) + + MERGE TGT AS target + USING #factReimbursementCharges AS src + ON ( + target.BudgetConfigID = src.BudgetConfigID + AND target.EntityGroupConfigID = src.EntityGroupConfigID + AND target.EntityID = src.EntityID + AND target.PatientClassID = src.PatientClassID + AND target.ServiceLineID = src.ServiceLineID + AND target.ServiceLineRollupID = src.ServiceLineRollupID + AND target.MedicalSurgicalID = src.MedicalSurgicalID + AND target.MSDRGID = src.MSDRGID + AND target.PrimaryCPTID = src.PrimaryCPTID + AND target.UBRevCodeID = src.UBRevCodeID + AND target.PayorID = src.PayorID + AND target.PayorGroupID = src.PayorGroupID + ) + WHEN NOT MATCHED BY TARGET THEN + INSERT ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [MedicalSurgicalID], + [PayorID], [PayorGroupID], [MSDRGID], [PrimaryCPTID], [UBRevCodeID]) + VALUES (src.BudgetConfigID, src.EntityGroupConfigID, src.EntityID, src.PatientClassID, src.ServiceLineID, src.ServiceLineRollupID, src.MedicalSurgicalID, + src.PayorID, src.PayorGroupID, src.MSDRGID, src.PrimaryCPTID, src.UBRevCodeID); + + -- Pad the other tables (Budget, Projection, and History) + EXEC [fp].[procPadReimbursementCharges] @BudgetConfigID, @SourceDimensionality + END +END +GO + + +--------------------------------------------- + +-- fp.procPadChargeToGeneralLedgerCrosswalk +CREATE PROCEDURE [fp].[procPadChargeToGeneralLedgerCrosswalk] + @BudgetConfigID INT, + @EntityGroupConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + AS + BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author BLI Description + ** 1 2021-03-09 BK JAZZ-16331 Create proc + ** 2 2021-04-05 SD JAZZ-18186 Fix alias + ** 3 2021-10-04 NT JAZZ-26831 FinancialReportingID should be OBDollarsFinancialReportingID instead of OBUnitsFinancialReportingID. + ** 4 2023-08-04 BW JAZZ-58151 Update for new GL data structure + ** 5 2023-11-07 MY JAZZ-63252 Add ChangeHistoryGroupingGUID to new Record + *************************************************************/ + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#RecordsToPad') IS NOT NULL DROP TABLE #recordsToPad + + CREATE TABLE #RecordsToPad (DepartmentID int, EntityID int, AccountID int) + + + IF (SELECT COUNT(*) FROM @SourceDimensionality) = 0 + BEGIN + + INSERT INTO #RecordsToPad (DepartmentID, EntityID, AccountID) + SELECT DISTINCT config.DepartmentID, dept.EntityID, config.AccountID + FROM [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] config (readuncommitted) + INNER JOIN fw.DimDepartment dept ON config.DepartmentID = dept.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID AND config.AccountID > 0 + END + ELSE + BEGIN + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + INSERT INTO #RecordsToPad (DepartmentID, EntityID, AccountID) + SELECT DISTINCT config.DepartmentID, dept.EntityID, config.AccountID + FROM [fp].[ChargeToGeneralLedgerCrosswalkConfiguration] config (readuncommitted) + INNER JOIN #FilterByDepartment ft ON config.DepartmentID = ft.DepartmentID + INNER JOIN fw.DimDepartment dept ON ft.DepartmentID = dept.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID AND config.AccountID > 0 + END + + -- Pad records from the crosswalk configuration to stats + INSERT INTO [fp].[GeneralLedger] (BudgetConfigID, EntityGroupConfigID, DepartmentID, EntityID, AccountID, FinancialReportingID, VariabilityID, APEModelSectionID, IsNew, AddDate, ChangeHistoryGroupingGUID) + SELECT + @BudgetConfigID AS BudgetConfigID, + @EntityGroupConfigID AS EntityGroupConfigID, + pad.DepartmentID, + pad.EntityID, + pad.AccountID, + acc.OBDollarsFinancialReportingID, + variability.VariablitiyID, + 1 as APEModelSectionID, + 1 AS IsNew, + GETDATE() AS AddDate, + NEWID() AS ChangeHistoryGroupingGUID + FROM #recordsToPad pad + INNER JOIN [fw].[DimAccount] acc ON pad.AccountID = acc.AccountID + CROSS JOIN (SELECT 1 AS VariablitiyID UNION SELECT 2 AS VariablitiyID) variability + LEFT JOIN [fp].[GeneralLedger] gl ON + gl.DepartmentID = pad.DepartmentID + AND gl.AccountID = pad.AccountID + AND gl.EntityGroupConfigID = @EntityGroupConfigID + WHERE gl.GeneralLedgerID IS NULL + + -- Pad any GL depdendent data + EXEC [fp].[procPadGeneralLedger] @BudgetConfigID, @SourceDimensionality, @EntityGroupConfigID + + -- Lock the cells + UPDATE gl + SET TargetLockFlag = 1, + TargetLockType = 3, + BudgetLockFlag = 1, + BudgetLockType = 3, + ProjectionLockFlag = 1, + ProjectionLockType = 3 + FROM #recordsToPad config + INNER JOIN [fp].[GeneralLedger] gl + ON gl.DepartmentID = config.DepartmentID + AND gl.AccountID = config.AccountID + WHERE gl.EntityGroupConfigID = @EntityGroupConfigID + + END +GO + + +--------------------------------------------- + +-- fp.procPadChargeUnitToStatCrosswalk +CREATE PROCEDURE [fp].[procPadChargeUnitToStatCrosswalk] + @BudgetConfigID INT, + @EntityGroupConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + AS + BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table + *************************************************************/ + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + SELECT DISTINCT config.DepartmentID, AccountID + INTO #recordsToPad + FROM [fp].[ChargeToStatisticsCrosswalkConfiguration] config (readuncommitted) + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = config.DepartmentID or ft.DepartmentID is null) + WHERE EntityGroupConfigID = @EntityGroupConfigID and config.AccountID > 0 + + -- Pad records from the crosswalk configuration to stats + INSERT INTO [fp].[FactStatistics] (EntityGroupConfigID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, BudgetConfigID, EntityID, IsNew, AddDate) + SELECT + @EntityGroupConfigID AS EntityGroupConfigID, + pad.DepartmentID, + pad.AccountID, + acc.PatientClassID, + acc.OBPayorID, + acc.OBUnitsFinancialReportingID, + 140 AS UnitTypeID, + @BudgetConfigID AS BudgetConfigID, + dept.EntityID, + 1 AS IsNew, + GETDATE() AS AddDate + FROM #recordsToPad pad + INNER JOIN [fw].[DimAccount] acc ON pad.AccountID = acc.AccountID + INNER JOIN [fw].[DimDepartment] dept ON pad.DepartmentID = dept.DepartmentID + LEFT JOIN [fp].[FactStatistics] stat ON + stat.DepartmentID = pad.DepartmentID + AND stat.AccountID = pad.AccountID + AND stat.UnitTypeID = 140 + AND stat.EntityGroupConfigID = @EntityGroupConfigID + WHERE stat.StatisticsID IS NULL + + -- Pad any statistic depdendent data + EXEC [fp].[procPadStatistics] @BudgetConfigID + + -- Lock the cells + UPDATE budg + SET budg.LockFlag = 1, + budg.LockType = 3 + FROM #recordsToPad config + INNER JOIN [fp].[FactStatistics] fs + ON fs.DepartmentID = config.DepartmentID + AND fs.AccountID = config.AccountID + INNER JOIN [fp].[FactStatisticsBudget] budg ON fs.StatisticsID = budg.StatisticsID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + + UPDATE proj + SET proj.LockFlag = 1, + proj.LockType = 3 + FROM #recordsToPad config + INNER JOIN [fp].[FactStatistics] fs + ON fs.DepartmentID = config.DepartmentID + AND fs.AccountID = config.AccountID + INNER JOIN [fp].[FactStatisticsProjection] proj ON fs.StatisticsID = proj.StatisticsID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + + + END +GO + + +--------------------------------------------- + +-- fp.procPadChargeVolume +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-03-08 LR JAZZ-16329 Added padding for the new ChargeVolumeDollar tables + ** 2 2021-08-12 MD JAZZ-24639 Added padding for the new ChargeVolumeDollarHistory table + ** 3 2022-08-31 VZ JAZZ-41715 Removed check for null from join clause + ** 4 2023-03-06 MY JAZZ-48307 Update charges adjustment to support data model changes +*************************************************************/ +CREATE PROCEDURE [fp].[procPadChargeVolume] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + CREATE TABLE #FilterByDepartment (DepartmentID INT) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #BudgetPhase (BudgetPhaseID TINYINT) + INSERT INTO #BudgetPhase (BudgetPhaseID) SELECT 2 UNION SELECT 3 + + CREATE TABLE #FilteredData (ChargeVolumeID INT PRIMARY KEY CLUSTERED) + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilteredData + SELECT [fcv].[ChargeVolumeID] + FROM [fp].[ChargeVolume] fcv + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fcv.DepartmentID + WHERE fcv.BudgetConfigID = @BudgetConfigID + END ELSE BEGIN + INSERT INTO #FilteredData + SELECT [fcv].[ChargeVolumeID] + FROM [fp].[ChargeVolume] fcv + WHERE fcv.BudgetConfigID = @BudgetConfigID + END + + INSERT INTO [fp].[ChargeVolumeHistory]([ChargeVolumeID]) + SELECT [fcv].[ChargeVolumeID] + FROM [fp].[ChargeVolume] fcv + INNER JOIN #FilteredData filter ON fcv.ChargeVolumeID = filter.ChargeVolumeID + WHERE BudgetConfigID = @BudgetConfigID + AND NOT EXISTS (SELECT 1 FROM fp.ChargeVolumeHistory hist WITH (READUNCOMMITTED) WHERE fcv.ChargeVolumeID = hist.ChargeVolumeID) + +END +GO + + +--------------------------------------------- + +-- fp.procPadEncountersToReimbursement +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-02-04 MY JAZZ-31904 Initial +** 2 2023-01-17 BK JAZZ-48267 New data structure +** 3 2023-11-15 BK JAZZ-62974 Fix when Entity and ServiceLine not in Charges +** 4 2024-01-11 AO JAZZ-64530 Data transfer for SLE is based on selected Model in Plan Config +*************************************************************/ +CREATE PROCEDURE [fp].[procPadEncountersToReimbursement] + @BudgetConfigID INT, + @IsReimbursementGLEnabled BIT = 0, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + DECLARE @IsMedicalSurgicalUsed BIT, + @IsMsdrgUsed BIT, + @IsCptUsed BIT + + SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 5 -- Reimbursement - Encounters + AND ss.LevelID = 'MedicalSurgicalID' + + SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 5 -- Reimbursement - Encounters + AND ss.LevelID = 'MSDRGID' + + SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 5 -- Reimbursement - Encounters + AND ss.LevelID = 'PrimaryCPTID' + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + IF OBJECT_ID('tempdb..#factReimbursementEncounters') IS NOT NULL DROP TABLE #factReimbursementEncounters; + IF OBJECT_ID('tempdb..#encounterTargeting') IS NOT NULL DROP TABLE #encounterTargeting; + + CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT); + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #encounterTargeting (EntityID INT, ServiceLineID INT); + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #encounterTargeting (EntityID, ServiceLineID) + SELECT DISTINCT map.EntityID, map.ServiceLineID + FROM fp.ServiceLineEncounterChargeVolumeMapping map WITH (READUNCOMMITTED) + INNER JOIN #ChargeVolumeDepartments targeting ON map.DepartmentID = targeting.DepartmentID + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = map.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE map.BudgetConfigID = @BudgetConfigID + AND ((@IsReimbursementGLEnabled = 1 + AND (bc.DefaultReimbursementNetRevenueModelID = 1 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model + OR rnrm.NetRevenueModelID = 1) + OR @IsReimbursementGLEnabled = 0) + UNION + SELECT DISTINCT sle.EntityID, sle.ServiceLineID + FROM fp.ServiceLineEncounter sle + LEFT JOIN fp.ChargeVolume cv on sle.BudgetConfigID = cv.BudgetConfigID AND sle.EntityID = cv.EntityID AND sle.ServiceLineID = cv.ServiceLineID + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = sle.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE sle.BudgetConfigID = @BudgetConfigID AND cv.EntityID IS NULL + AND ((@IsReimbursementGLEnabled = 1 + AND (bc.DefaultReimbursementNetRevenueModelID = 1 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model + OR rnrm.NetRevenueModelID = 1) + OR @IsReimbursementGLEnabled = 0) + + END ELSE + BEGIN + INSERT INTO #encounterTargeting (EntityID, ServiceLineID) + SELECT DISTINCT map.EntityID, map.ServiceLineID + FROM fp.ServiceLineEncounter map WITH (READUNCOMMITTED) + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = map.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE map.BudgetConfigID = @BudgetConfigID + AND ((@IsReimbursementGLEnabled = 1 + AND (bc.DefaultReimbursementNetRevenueModelID = 1 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model + OR rnrm.NetRevenueModelID = 1) + OR @IsReimbursementGLEnabled = 0) + END + + SELECT DISTINCT sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN sle.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, + sle.PayorID, sle.PayorGroupID, + CASE WHEN @IsMsdrgUsed = 1 THEN sle.MSDRGID ELSE 0 END AS MSDRGID, + CASE WHEN @IsCptUsed = 1 THEN sle.CPTID ELSE 0 END AS CPTID + INTO #factReimbursementEncounters + FROM fp.ServiceLineEncounter sle + INNER JOIN #encounterTargeting targeting ON sle.EntityID = targeting.EntityID AND sle.ServiceLineID = targeting.ServiceLineID + WHERE sle.BudgetConfigID = @BudgetConfigID + + IF (@IsDebug = 1) + BEGIN + SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments + SELECT '#encounterTargeting', EntityID, ServiceLineID FROM #encounterTargeting + SELECT '#factReimbursementEncounters', sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, + sle.MedicalSurgicalID, sle.PayorID, sle.PayorGroupID, sle.MSDRGID, sle.CPTID + FROM #factReimbursementEncounters sle + END ELSE + BEGIN + -- Publish + ;WITH TGT AS + ( + SELECT fact.[BudgetConfigID], fact.[EntityGroupConfigID], fact.[EntityID], fact.[PatientClassID], fact.[ServiceLineID], fact.[ServiceLineRollupID], fact.[MedicalSurgicalID], + [PayorID], [PayorGroupID], fact.[MSDRGID], fact.[CPTID] + FROM [fp].[FactReimbursementEncounter] fact + INNER JOIN #encounterTargeting targeting ON fact.EntityID = targeting.EntityID AND fact.ServiceLineID = targeting.ServiceLineID + WHERE fact.BudgetConfigID = @BudgetConfigID + ) + + MERGE TGT AS target + USING #factReimbursementEncounters AS src + ON ( + target.BudgetConfigID = src.BudgetConfigID + AND target.EntityGroupConfigID = src.EntityGroupConfigID + AND target.EntityID = src.EntityID + AND target.PatientClassID = src.PatientClassID + AND target.ServiceLineID = src.ServiceLineID + AND target.ServiceLineRollupID = src.ServiceLineRollupID + AND target.MedicalSurgicalID = src.MedicalSurgicalID + AND target.MSDRGID = src.MSDRGID + AND target.CPTID = src.CPTID + AND target.PayorID = src.PayorID + AND target.PayorGroupID = src.PayorGroupID + ) + WHEN NOT MATCHED BY TARGET THEN + INSERT ([BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [MedicalSurgicalID], + [PayorID], [PayorGroupID], [MSDRGID], [CPTID]) + VALUES (src.BudgetConfigID, src.EntityGroupConfigID, src.EntityID, src.PatientClassID, src.ServiceLineID, src.ServiceLineRollupID, src.MedicalSurgicalID, + src.PayorID, src.PayorGroupID, src.MSDRGID, src.CPTID); + + -- Pad the other tables (Budget, Projection, and History) + EXEC [fp].[procPadReimbursementEncounters] @BudgetConfigID, @SourceDimensionality + END +END +GO + + +--------------------------------------------- + +-- fp.procPadGLForBenefitsToGLCrosswalk +/************************************************************** +** Change History +** CID Date Author WI Description +** 1 2019-01-15 IP B-21392 Added targeted refresh by adding parameters +** 2 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table +** 3 2019-06-19 MY TK-75217 Add Date and IsNew Flag now gets populated during padding +** 4 2020-08-04 NN JAZZ-133 Remove NULL checks to JOINS and drop temp table +** 5 2021-09-03 NT JAZZ-25623 Pad records for both variability 1 & 2 +** 6 2023-08-10 MY JAZZ-58216 Upgrade GL Structure +*************************************************************/ +CREATE PROC [fp].[procPadGLForBenefitsToGLCrosswalk] + @BudgetConfigID int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @EntityGroupConfigID INT = NULL, + @AccountID INT = NULL, + @FinancialReportingID INT = NULL + AS +BEGIN + + EXEC [dbo].[procSysDropTempTable] '#FilterByDepartment' + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + -- Pad records from Benefits to GL + INSERT INTO [fp].[GeneralLedger] (EntityGroupConfigID, DepartmentID, AccountID, BudgetConfigID, FinancialReportingID, + VariabilityID, EntityID, APEModelSectionID, IsNew, AddDate) + SELECT + be.EntityGroupConfigID, + be.DepartmentID, + be.AccountID, + be.BudgetConfigID, + be.FinancialReportingID, + va.VariabilityID, + be.EntityID, + 5 AS APEModelSectionID, -- Benefits + 1 AS IsNew, + GETDATE() AS AddDate + FROM [fp].[FactBenefits] be + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = be.DepartmentID + INNER JOIN fw.DimVariability va on 1=1 + LEFT JOIN [fp].[GeneralLedger] gl + ON gl.BudgetConfigID = be.BudgetConfigID + AND gl.DepartmentID = be.DepartmentID + AND gl.AccountID = be.AccountID + AND be.UnitTypeID = 34 + AND gl.FinancialReportingID = be.FinancialReportingID + AND gl.EntityID = be.EntityID + AND gl.VariabilityID = va.VariabilityID + WHERE + be.BudgetConfigID = @BudgetConfigID + AND be.UnitTypeID = 34 + and (be.AccountID = @AccountID or @AccountID is null) + and (be.EntityGroupConfigID = @EntityGroupConfigID or @EntityGroupConfigID is null) + and (be.FinancialReportingID = @FinancialReportingID or @FinancialReportingID is null) + AND va.VariabilityID IN (1, 2) + AND gl.GeneralLedgerID IS NULL + + END ELSE + BEGIN + + -- Pad records from Benefits to GL + INSERT INTO [fp].[GeneralLedger] (EntityGroupConfigID, DepartmentID, AccountID, BudgetConfigID, FinancialReportingID, + VariabilityID, EntityID, APEModelSectionID, IsNew, AddDate) + SELECT + be.EntityGroupConfigID, + be.DepartmentID, + be.AccountID, + be.BudgetConfigID, + be.FinancialReportingID, + va.VariabilityID, + be.EntityID, + 5 AS APEModelSectionID, -- Benefits + 1 AS IsNew, + GETDATE() AS AddDate + FROM [fp].[FactBenefits] be + INNER JOIN fw.DimVariability va on 1=1 + LEFT JOIN [fp].[GeneralLedger] gl + ON gl.BudgetConfigID = be.BudgetConfigID + AND gl.DepartmentID = be.DepartmentID + AND gl.AccountID = be.AccountID + AND be.UnitTypeID = 34 + AND gl.FinancialReportingID = be.FinancialReportingID + AND gl.EntityID = be.EntityID + AND gl.VariabilityID = va.VariabilityID + WHERE + be.BudgetConfigID = @BudgetConfigID + AND be.UnitTypeID = 34 + and (be.AccountID = @AccountID or @AccountID is null) + and (be.EntityGroupConfigID = @EntityGroupConfigID or @EntityGroupConfigID is null) + and (be.FinancialReportingID = @FinancialReportingID or @FinancialReportingID is null) + AND va.VariabilityID IN (1, 2) + AND gl.GeneralLedgerID IS NULL + + END + + -- Pad the remaining tables missing data + EXEC [fp].[procPadGeneralLedger] @BudgetConfigID, @SourceDimensionality, @EntityGroupConfigID, @AccountID, @FinancialReportingID + +END +GO + + +--------------------------------------------- + +-- fp.procPadGeneralLedger +/************************************************************** +** Change History +** CID Date Author WI Description +** 1 2019-01-15 IP B-21392 Added targeted refresh by adding parameters +** 2 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table +** 3 2019-04-30 BK D-08400 Fix duplicate key error on insert and eliminated duplicate query with temp table +** 4 2020-08-04 NN JAZZ-133 Remove NULL checks to JOINS and drop temp tables +** 5 5-15-2023 NT JAZZ-54290 Data restructure changes to use new fp.GeneralLedger table +*************************************************************/ +CREATE PROCEDURE [fp].[procPadGeneralLedger] + @BudgetConfigID int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @EntityGroupConfigID INT = NULL, + @AccountID INT = NULL, + @FinancialReportingID INT = NULL +AS +BEGIN + + exec [dbo].[procSysDropTempTable] '#FilterByDepartment' + exec [dbo].[procSysDropTempTable] '#FilteredData' + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #FilteredData (GeneralLedgerID int) + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilteredData + SELECT [fgl].[GeneralLedgerID] + FROM [fp].[GeneralLedger] fgl + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fgl.DepartmentID + WHERE fgl.BudgetConfigID = @BudgetConfigID + and (fgl.AccountID = @AccountID or @AccountID is null) + and (fgl.EntityGroupConfigID = @EntityGroupConfigID or @EntityGroupConfigID is null) + and (fgl.FinancialReportingID = @FinancialReportingID or @FinancialReportingID is null) + END ELSE BEGIN + INSERT INTO #FilteredData + SELECT [fgl].[GeneralLedgerID] + FROM [fp].[GeneralLedger] fgl + WHERE fgl.BudgetConfigID = @BudgetConfigID + and (fgl.AccountID = @AccountID or @AccountID is null) + and (fgl.EntityGroupConfigID = @EntityGroupConfigID or @EntityGroupConfigID is null) + and (fgl.FinancialReportingID = @FinancialReportingID or @FinancialReportingID is null) + END + + INSERT INTO [fp].[GeneralLedgerHistory]([GeneralLedgerID]) + SELECT [fgl].[GeneralLedgerID] + FROM #FilteredData fgl + WHERE NOT EXISTS (SELECT 1 FROM fp.GeneralLedgerHistory hist WITH (READUNCOMMITTED) WHERE fgl.GeneralLedgerID = hist.GeneralLedgerID) +END +GO + + +--------------------------------------------- + +-- fp.procPadGeneralLedgerReimbursement +CREATE PROCEDURE [fp].[procPadGeneralLedgerReimbursement] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 05-23-2023 MZ JAZZ-54503 Initial Creation + *************************************************************/ + + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment; + IF OBJECT_ID('tempdb..#entities') IS NOT NULL DROP TABLE #entities; + + CREATE TABLE #FilterByDepartment (DepartmentID INT); + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #entities (EntityID INT) + + -- We need to convert the departments into the Entities because we don't have that coming in. + -- If this ends up being slow, we can target this further by using the mapping table or similarly to + -- [fp].[procPadReimbursementCharges] + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #entities (EntityID) + SELECT DISTINCT dept.EntityID + FROM fw.DimDepartment dept + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = dept.DepartmentID + END ELSE BEGIN + INSERT INTO #entities (EntityID) + SELECT DISTINCT EntityID + FROM fw.DimEntity + END + + + INSERT INTO [fp].[ReimbursementGeneralLedgerHistory] ([ReimbursementGeneralLedgerID]) + SELECT [ReimbursementGeneralLedgerID] + FROM [fp].[ReimbursementGeneralLedger] rgl + INNER JOIN #entities tgt ON tgt.EntityID = rgl.EntityID + WHERE rgl.BudgetConfigID = @BudgetConfigID + AND NOT EXISTS (SELECT 1 FROM [fp].[ReimbursementGeneralLedgerHistory] hist WITH (READUNCOMMITTED) WHERE rgl.[ReimbursementGeneralLedgerID] = hist.[ReimbursementGeneralLedgerID]) + + +END +GO + + +--------------------------------------------- + +-- fp.procPadGeneralLedgerToReimbursement +CREATE PROCEDURE [fp].[procPadGeneralLedgerToReimbursement] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 05-23-2023 MZ JAZZ-54503 Initial Creation + ** 2 07-12-2023 AO JAZZ-57493 Added check when not matched + ** 3 01-03-2024 AO JAZZ-65384 Data transfer for GL is based on selected Model in Plan Config + *************************************************************/ + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment; + IF OBJECT_ID('tempdb..#RevenueData') IS NOT NULL DROP TABLE #RevenueData; + + CREATE TABLE #FilterByDepartment (DepartmentID INT); + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + DECLARE @Revenue INT = 1; + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[GeneralLedger] gl WITH (READUNCOMMITTED) + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON rnrm.EntityID = gl.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE gl.BudgetConfigID = @BudgetConfigID + AND ((bc.DefaultReimbursementNetRevenueModelID = 2 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,2))) + OR rnrm.NetRevenueModelID = 2) -- GL Model + END ELSE + BEGIN + DELETE d FROM #FilterByDepartment d + INNER JOIN [fp].[GeneralLedger] gl WITH (READUNCOMMITTED) ON d.DepartmentID = gl.DepartmentID + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON rnrm.EntityID = gl.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE gl.BudgetConfigID <> @BudgetConfigID + AND ((bc.DefaultReimbursementNetRevenueModelID <> 2 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID <> 2)) + OR rnrm.NetRevenueModelID <> 2) -- GL Model + END + + + SELECT DISTINCT gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID, a.PatientClassID + INTO #RevenueData + FROM [fp].[GeneralLedger] gl + JOIN #FilterByDepartment ft ON ft.DepartmentID = gl.DepartmentID + INNER JOIN [fw].[DimAccount] a ON gl.AccountID = a.AccountID + WHERE gl.BudgetConfigID = @BudgetConfigID + AND gl.APEModelSectionID = @Revenue + + IF (@IsDebug = 1) + BEGIN + SELECT '#FilterByDepartment', DepartmentID FROM #FilterByDepartment + SELECT '#RevenueData', * FROM #RevenueData + END ELSE + BEGIN + -- Publish + ;WITH TGT AS + ( + SELECT [BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [PayorGroupID] + FROM [fp].[ReimbursementGeneralLedger] + WHERE BudgetConfigID = @BudgetConfigID + ) + + MERGE TGT AS target + USING #RevenueData AS src + ON ( + target.BudgetConfigID = src.BudgetConfigID + AND target.EntityGroupConfigID = src.EntityGroupConfigID + AND target.EntityID = src.EntityID + AND target.PatientClassID = src.PatientClassID + AND target.PayorGroupID = src.OBPayorGroupID + ) + WHEN NOT MATCHED BY TARGET THEN + INSERT (BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID) + VALUES (src.BudgetConfigID, src.EntityGroupConfigID, src.EntityID, src.OBPayorGroupID, src.PatientClassID); + + -- Pad History table + EXEC [fp].[procPadGeneralLedgerReimbursement] @BudgetConfigID, @SourceDimensionality + END + +END +GO + + +--------------------------------------------- + +-- fp.procPadReimbursementCharges +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-01-12 MY JAZZ-31850 Initial + ** 2 2022-02-15 BW JAZZ-33266 Pulling in configuration via Plan Config > Section Setup + ** 4 2023-01-26 NT JAZZ-48268 Make change to use the new fp.ChargeVolume (data restructure) +*************************************************************/ +CREATE PROCEDURE [fp].[procPadReimbursementCharges] + @BudgetConfigID int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + DECLARE @IsMedicalSurgicalUsed BIT = 0, + @IsMsdrgUsed BIT = 0, + @IsCptUsed BIT = 0, + @IsUBRevCodeUsed BIT = 0; + + SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'MedicalSurgicalID' + + SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'MSDRGID' + + SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'PrimaryCPTID' + + SELECT @IsUBRevCodeUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'UBRevCodeID' + + CREATE TABLE #FilterByDepartment (DepartmentID INT) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #BudgetPhase (BudgetPhaseID TINYINT) + INSERT INTO #BudgetPhase (BudgetPhaseID) SELECT 2 UNION SELECT 3 + + CREATE TABLE #FilteredData (ReimbursementChargesID INT PRIMARY KEY CLUSTERED) + + -- You will notice we don't have Payor on here, that's just because we don't have that inate with Charges + -- and the performance benefit of getting that outweights the targeting. + CREATE TABLE #reimbursementTargeting ( + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + PatientClassID INT, + ServiceLineID INT, + ServiceLineRollupID INT, + MedicalSurgicalID INT, + MSDRGID INT, + PrimaryCPTID INT, + UBRevCodeID INT + ) + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #reimbursementTargeting (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, + MedicalSurgicalID, MSDRGID, PrimaryCPTID, UBRevCodeID) + SELECT DISTINCT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, + CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, + CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID, + CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID + FROM fp.ChargeVolume cv + INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = cv.DepartmentID + WHERE cv.BudgetConfigID = @BudgetConfigID + END ELSE BEGIN + INSERT INTO #reimbursementTargeting (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, + MedicalSurgicalID, MSDRGID, PrimaryCPTID, UBRevCodeID) + SELECT DISTINCT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, + CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, + CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID, + CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID + FROM fp.ChargeVolume cv + INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID + WHERE cv.BudgetConfigID = @BudgetConfigID + END + + INSERT INTO #FilteredData (ReimbursementChargesID) + SELECT DISTINCT ReimbursementChargesID + FROM fp.FactReimbursementCharges frc + INNER JOIN #reimbursementTargeting tgt ON + tgt.BudgetConfigID = frc.BudgetConfigID + AND tgt.EntityGroupConfigID = frc.EntityGroupConfigID + AND tgt.EntityID = frc.EntityID + AND tgt.PatientClassID = frc.PatientClassID + AND tgt.ServiceLineID = frc.ServiceLineID + AND tgt.MedicalSurgicalID = frc.MedicalSurgicalID + AND tgt.MSDRGID = frc.MSDRGID + AND tgt.PrimaryCPTID = frc.PrimaryCPTID + AND tgt.UBRevCodeID = frc.UBRevCodeID + + INSERT INTO [fp].[FactReimbursementChargesBudget]([ReimbursementChargesID], [BudgetPhaseID]) + SELECT [fcv].[ReimbursementChargesID], [psh].[BudgetPhaseID] + FROM [fp].[FactReimbursementCharges] fcv + INNER JOIN #FilteredData filter ON fcv.ReimbursementChargesID = filter.ReimbursementChargesID + OUTER APPLY #BudgetPhase psh + WHERE BudgetConfigID = @BudgetConfigID + AND NOT EXISTS (SELECT 1 FROM fp.FactReimbursementChargesBudget bud WITH (READUNCOMMITTED) WHERE fcv.ReimbursementChargesID = bud.ReimbursementChargesID AND bud.BudgetPhaseID = psh.BudgetPhaseID) + + INSERT INTO [fp].[FactReimbursementChargesProjection]([ReimbursementChargesID], [BudgetPhaseID]) + SELECT [fcv].[ReimbursementChargesID], [psh].[BudgetPhaseID] + FROM [fp].[FactReimbursementCharges] fcv + INNER JOIN #FilteredData filter ON fcv.ReimbursementChargesID = filter.ReimbursementChargesID + OUTER APPLY #BudgetPhase psh + WHERE BudgetConfigID = @BudgetConfigID + AND NOT EXISTS (SELECT 1 FROM fp.FactReimbursementChargesProjection proj WITH (READUNCOMMITTED) WHERE fcv.ReimbursementChargesID = proj.ReimbursementChargesID AND proj.BudgetPhaseID = psh.BudgetPhaseID) + + INSERT INTO [fp].[FactReimbursementChargesHistory]([ReimbursementChargesID]) + SELECT [fcv].[ReimbursementChargesID] + FROM [fp].[FactReimbursementCharges] fcv + INNER JOIN #FilteredData filter ON fcv.ReimbursementChargesID = filter.ReimbursementChargesID + WHERE BudgetConfigID = @BudgetConfigID + AND NOT EXISTS (SELECT 1 FROM fp.FactReimbursementChargesHistory hist WITH (READUNCOMMITTED) WHERE fcv.ReimbursementChargesID = hist.ReimbursementChargesID) + +END +GO + + +--------------------------------------------- + +-- fp.procPadReimbursementEncounters +------------------------------------------------------------- +-- re-add proc +------------------------------------------------------------- +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-01-12 MY JAZZ-31850 Initial +*************************************************************/ +CREATE PROCEDURE [fp].[procPadReimbursementEncounters] + @BudgetConfigID int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + CREATE TABLE #FilterByDepartment (DepartmentID INT) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #BudgetPhase (BudgetPhaseID TINYINT) + INSERT INTO #BudgetPhase (BudgetPhaseID) SELECT 2 UNION SELECT 3 + + CREATE TABLE #FilteredData (ReimbursementEncounterID INT PRIMARY KEY CLUSTERED) + CREATE TABLE #entities (EntityID INT) + + -- We need to convert the departments into the Entities because we don't have that coming in. + -- If this ends up being slow, we can target this further by using the mapping table or similarly to + -- [fp].[procPadReimbursementCharges] + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #entities (EntityID) + SELECT DISTINCT dept.EntityID + FROM fw.DimDepartment dept + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = dept.DepartmentID + END ELSE BEGIN + INSERT INTO #entities (EntityID) + SELECT DISTINCT EntityID + FROM fw.DimEntity + END + + INSERT INTO #FilteredData (ReimbursementEncounterID) + SELECT DISTINCT ReimbursementEncounterID + FROM fp.FactReimbursementEncounter frc + INNER JOIN #entities tgt ON tgt.EntityID = frc.EntityID + WHERE frc.BudgetConfigID = @BudgetConfigID + + INSERT INTO [fp].[FactReimbursementEncounterBudget] ([ReimbursementEncounterID], [BudgetPhaseID]) + SELECT [fcv].[ReimbursementEncounterID], [psh].[BudgetPhaseID] + FROM [fp].[FactReimbursementEncounter] fcv + INNER JOIN #FilteredData filter ON fcv.ReimbursementEncounterID = filter.ReimbursementEncounterID + OUTER APPLY #BudgetPhase psh + WHERE BudgetConfigID = @BudgetConfigID + AND NOT EXISTS (SELECT 1 FROM fp.FactReimbursementEncounterBudget bud WITH (READUNCOMMITTED) WHERE fcv.ReimbursementEncounterID = bud.ReimbursementEncounterID AND bud.BudgetPhaseID = psh.BudgetPhaseID) + + INSERT INTO [fp].[FactReimbursementEncounterProjection] ([ReimbursementEncounterID], [BudgetPhaseID]) + SELECT [fcv].[ReimbursementEncounterID], [psh].[BudgetPhaseID] + FROM [fp].[FactReimbursementEncounter] fcv + INNER JOIN #FilteredData filter ON fcv.ReimbursementEncounterID = filter.ReimbursementEncounterID + OUTER APPLY #BudgetPhase psh + WHERE BudgetConfigID = @BudgetConfigID + AND NOT EXISTS (SELECT 1 FROM fp.FactReimbursementEncounterProjection proj WITH (READUNCOMMITTED) WHERE fcv.ReimbursementEncounterID = proj.ReimbursementEncounterID AND proj.BudgetPhaseID = psh.BudgetPhaseID) + + INSERT INTO [fp].[FactReimbursementEncounterHistory] ([ReimbursementEncounterID]) + SELECT [fcv].[ReimbursementEncounterID] + FROM [fp].[FactReimbursementEncounter] fcv + INNER JOIN #FilteredData filter ON fcv.ReimbursementEncounterID = filter.ReimbursementEncounterID + WHERE BudgetConfigID = @BudgetConfigID + AND NOT EXISTS (SELECT 1 FROM fp.FactReimbursementEncounterHistory hist WITH (READUNCOMMITTED) WHERE fcv.ReimbursementEncounterID = hist.ReimbursementEncounterID) + +END +GO + + +--------------------------------------------- + +-- fp.procPadReimbursementToGLCrosswalk +CREATE PROC [fp].[procPadReimbursementToGLCrosswalk] + @EntityGroupConfigID INT, + @BudgetConfigID INT, + @BudgetConfigGUID UNIQUEIDENTIFIER, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-05-17 MD JAZZ-37249 Initial Commit + ** 2 2022-08-16 MD JAZZ-42139 Update to handle EntityID on ReimbursementToGeneralLedgerCrosswalkConfiguration + ** 3 2023-08-16 MD JAZZ-58766 Update for GL restructure + *******************************************************/ + IF OBJECT_ID('tempdb..#itemsToPad') IS NOT NULL DROP TABLE #itemsToPad + IF OBJECT_ID('tempdb..#uniqueCADimensions') IS NOT NULL DROP TABLE #uniqueCADimensions + IF OBJECT_ID('tempdb..#insertTemp') IS NOT NULL DROP TABLE #insertTemp + IF OBJECT_ID('tempdb..#tmpReimbursement') IS NOT NULL DROP TABLE #tmpReimbursement + + CREATE TABLE #tmpReimbursement ( + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + DepartmentID INT, + AccountID INT, + OBDollarsFinancialReportingID INT + ) + + CREATE TABLE #itemsToPad ( + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + DepartmentID INT, + AccountID INT, + OBDollarsFinancialReportingID INT + ) + + -------------------------------------------------------------- + --Get unique contractual allowance config dimensionality for given budget config + -------------------------------------------------------------- + SELECT DISTINCT + data.BudgetConfigGUID, + data.EntityID, + data.DepartmentID, + data.AccountID, + da.OBDollarsFinancialReportingID + INTO #uniqueCADimensions + FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data + INNER JOIN [fp].[viewDeductionsAccounts] da on data.AccountID = da.AccountID + WHERE + data.BudgetConfigGUID = @BudgetConfigGUID + + -------------------------------------------------------------- + --Insert into temp table + -------------------------------------------------------------- + SELECT + @BudgetConfigID AS BudgetConfigID, + @EntityGroupConfigID AS EntityGroupConfigID, + ca.EntityID, + ca.DepartmentID, + ca.AccountID, + ca.OBDollarsFinancialReportingID, + vari.VariabilityID, + 4 AS APEModelSectionID, + 1 AS IsNew, + GETDATE() AS AddDate + INTO #insertTemp + FROM #uniqueCADimensions ca + INNER JOIN fw.DimDepartment dd on ca.DepartmentID = dd.DepartmentID + LEFT JOIN fp.GeneralLedger gl + ON gl.BudgetConfigID = @BudgetConfigID + AND gl.EntityGroupConfigID = @EntityGroupConfigID + AND ca.EntityID = gl.EntityID + AND ca.DepartmentID = gl.DepartmentID + AND ca.OBDollarsFinancialReportingID = gl.FinancialReportingID + AND ca.AccountID = gl.AccountID + INNER JOIN fp.EntityGroupConfig egc on egc.EntityGroupConfigID = @EntityGroupConfigID + INNER JOIN fp.EntityGroupConfigMapping egcm on egc.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID + CROSS APPLY (VALUES (1),(2)) vari(VariabilityID) + WHERE + gl.GeneralLedgerID IS NULL + AND dd.EntityID = egcm.EntityID + + IF(@IsDebug = 0) + BEGIN + -------------------------------------------------------------- + --Insert missing dimensionality into GL + -------------------------------------------------------------- + INSERT INTO [fp].[GeneralLedger] + ( + BudgetConfigID, + EntityGroupConfigID, + EntityID, + DepartmentID, + AccountID, + FinancialReportingID, + VariabilityID, + APEModelSectionID, + IsNew, + AddDate + ) + SELECT + @BudgetConfigID, + @EntityGroupConfigID, + EntityID, + DepartmentID, + AccountID, + OBDollarsFinancialReportingID, + VariabilityID, + APEModelSectionID, + IsNew, + AddDate + FROM #insertTemp + + -------------------------------------------------------------- + -- Pad the budget/projection tables + -------------------------------------------------------------- + EXEC [fp].[procPadGeneralLedger] @BudgetConfigID, @SourceDimensionality + END ELSE + BEGIN + SELECT + @BudgetConfigID, + @EntityGroupConfigID, + EntityID, + DepartmentID, + AccountID, + OBDollarsFinancialReportingID, + VariabilityID, + APEModelSectionID, + IsNew, + AddDate + FROM #insertTemp + END +END +GO + + +--------------------------------------------- + +-- fp.procPadServiceLineEncounter +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-02-13 BW JAZZ-48306 Updated for new data model, use [fp].[ServiceLineEncounter] +*************************************************************/ +CREATE PROCEDURE [fp].[procPadServiceLineEncounter] + @BudgetConfigID int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + CREATE TABLE #FilterByDepartment (DepartmentID INT) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #BudgetPhase (BudgetPhaseID TINYINT) + INSERT INTO #BudgetPhase (BudgetPhaseID) SELECT 2 UNION SELECT 3 + + CREATE TABLE #FilteredData (ServiceLineEncounterID INT PRIMARY KEY CLUSTERED) + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilteredData + SELECT [fcv].[ServiceLineEncounterID] + FROM [fp].[ServiceLineEncounter] fcv + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fcv.DepartmentID + WHERE fcv.BudgetConfigID = @BudgetConfigID + END ELSE BEGIN + INSERT INTO #FilteredData + SELECT [fcv].[ServiceLineEncounterID] + FROM [fp].[ServiceLineEncounter] fcv + WHERE fcv.BudgetConfigID = @BudgetConfigID + END + + INSERT INTO [fp].[ServiceLineEncounterHistory]([ServiceLineEncounterID]) + SELECT [fcv].[ServiceLineEncounterID] + FROM [fp].[ServiceLineEncounter] fcv + INNER JOIN #FilteredData filter ON fcv.ServiceLineEncounterID = filter.ServiceLineEncounterID + WHERE BudgetConfigID = @BudgetConfigID + AND NOT EXISTS (SELECT 1 FROM fp.ServiceLineEncounterHistory hist WITH (READUNCOMMITTED) WHERE fcv.ServiceLineEncounterID = hist.ServiceLineEncounterID) +END +GO + + +--------------------------------------------- + +-- fp.procPadServiceLineToChargeVolumeDepartmentMapping +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-09-19 BK JAZZ-42503 Add ProviderID to targeting for Service Line Encounters +** 2 2023-01-31 NT JAZZ-48268 Make change to use the new fp.ChargeVolume (data restructure) +*************************************************************/ +CREATE PROCEDURE fp.procPadServiceLineToChargeVolumeDepartmentMapping + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID FROM fp.ChargeVolume WHERE BudgetConfigID = @BudgetConfigID + END + + + INSERT INTO fp.ServiceLineEncounterChargeVolumeMapping (BudgetConfigID, EntityID, DepartmentID, ServiceLineID, ProviderID) + SELECT DISTINCT cv.BudgetConfigID, cv.ServiceEntityID, cv.DepartmentID, cv.ServiceLineID, cv.ServiceProviderID + FROM [fp].[ChargeVolume] cv INNER JOIN [fp].[ServiceLineEncounter] sle + ON cv.ServiceEntityID = sle.EntityID + AND cv.BudgetConfigID = sle.BudgetConfigID + AND cv.ServiceLineID = sle.ServiceLineID + AND cv.ServiceProviderID = sle.ProviderID + INNER JOIN #FilterByDepartment SD on SD.DepartmentID = cv.DepartmentID + WHERE cv.BudgetConfigID = @BudgetConfigID + AND NOT EXISTS (SELECT 1 FROM fp.ServiceLineEncounterChargeVolumeMapping map WHERE + cv.ServiceEntityID = map.EntityID + AND cv.DepartmentID = map.DepartmentID + AND cv.ServiceLineID = map.ServiceLineID + AND cv.ServiceProviderID = map.ProviderID + AND cv.BudgetConfigID = map.BudgetConfigID) + + + +END +GO + + +--------------------------------------------- + +-- fp.procPadStaffing +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-10-09 MY JAZZ-61365 Upgrade to new structure +** 2 2023-10-23 MY JAZZ-61397 Fix Targeting +*************************************************************/ +CREATE PROCEDURE [fp].[procPadStaffing] + @BudgetConfigID int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + CREATE TABLE #FilterByDepartment (DepartmentID INT) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #FilteredData (StaffingID INT PRIMARY KEY CLUSTERED) + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilteredData + SELECT [fgl].[StaffingID] + FROM [fp].[Staffing] fgl + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = fgl.DepartmentID + WHERE fgl.BudgetConfigID = @BudgetConfigID + END + ELSE + BEGIN + INSERT INTO #FilteredData + SELECT [fgl].[StaffingID] + FROM [fp].[Staffing] fgl + WHERE fgl.BudgetConfigID = @BudgetConfigID + END + + INSERT INTO [fp].[StaffingHistory]([StaffingID]) + SELECT [fgl].[StaffingID] + FROM [fp].[Staffing] fgl + INNER JOIN #FilteredData filter ON fgl.StaffingID = filter.StaffingID + WHERE BudgetConfigID = @BudgetConfigID + AND NOT EXISTS + ( + SELECT 1 FROM fp.StaffingHistory hist WITH (READUNCOMMITTED) + WHERE fgl.StaffingID = hist.StaffingID + ) + + INSERT INTO [fp].[StaffingWageRate] (StaffingWageRateID) + SELECT st.StaffingID + FROM fp.Staffing st + INNER JOIN #FilteredData filter ON st.StaffingID = filter.StaffingID + WHERE VariabilityID = 1 + AND st.StaffingWageRateID = 0 + + UPDATE staff SET StaffingWageRateID = staff.StaffingID + FROM fp.Staffing staff + INNER JOIN #FilteredData filter ON staff.StaffingID = filter.StaffingID + WHERE VariabilityID = 1 + AND staff.StaffingWageRateID = 0 + + UPDATE varb SET varb.StaffingWageRateID = fixed.StaffingID + FROM fp.Staffing varb + INNER JOIN fp.Staffing fixed ON + varb.DepartmentID = fixed.DepartmentID + AND varb.JobCodeID = fixed.JobCodeID + AND varb.PayCodeGroupID = fixed.PayCodeGroupID + AND varb.BudgetConfigID = fixed.BudgetConfigID + AND varb.EntityGroupConfigID = fixed.EntityGroupConfigID + AND varb.EntityID = fixed.EntityID + AND varb.ProductiveClassID = fixed.ProductiveClassID + AND varb.ProviderID = fixed.ProviderID + AND varb.ProviderLineItemID = fixed.ProviderLineItemID + AND varb.ProviderTypeID = fixed.ProviderTypeID + AND varb.ProviderSpecialtyID = fixed.ProviderSpecialtyID + AND varb.EmployeeID = fixed.EmployeeID + INNER JOIN #FilteredData ft ON ft.StaffingID = fixed.StaffingID + WHERE varb.VariabilityID = 2 + AND fixed.VariabilityID = 1 + AND varb.StaffingWageRateID = 0 +END +GO + + +--------------------------------------------- + +-- fp.procPadStaffingToGlCrosswalk +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2018-09-25 GF E-02313 Simplify source dimensionality to only department + ** 2 2021-05-05 BK JAZZ-18217 Add Provider Compensation Dollars To GL Crosswalk + ** 3 2023-07-31 BK JAZZ-58155 GL Data restructure + ** 4 2023-10-23 Matt Hayden JAZZ-62450 Update for Staffing table restructure + ** 5 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config + *******************************************************/ +CREATE procedure fp.procPadStaffingToGlCrosswalk +@EntityGroupConfigID INT, +@BudgetConfigID INT, +@SqlJoin NVARCHAR(MAX), +@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, +@IsDebug BIT = 0 +AS BEGIN + +IF OBJECT_ID('tempdb..#Accts') IS NOT NULL DROP TABLE #Accts +IF OBJECT_ID('tempdb..#itemsToPad') IS NOT NULL DROP TABLE #itemsToPad +IF OBJECT_ID('tempdb..#tmpStaffing') IS NOT NULL DROP TABLE #tmpStaffing +IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + +CREATE TABLE #FilterByDepartment (DepartmentID int) + +INSERT INTO + #FilterByDepartment (DepartmentID) +SELECT + DepartmentID +FROM + fp.funcGetSourceDimensionalityAsTable(@SourceDimensionality) + +CREATE TABLE #tmpStaffing ( + DepartmentID INT, + JobCodeID INT, + PayCodeGroupID INT, + EntityID INT, + VariabilityID INT, + EntityGroupConfigID INT, + BudgetConfigID INT +) + +CREATE TABLE #itemsToPad ( + DepartmentID INT, + AccountID INT, + OBDollarsFinancialReportingID INT, + EntityID INT, + VariabilityID INT, + EntityGroupConfigID INT, + BudgetConfigID INT +) + +IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) BEGIN + INSERT INTO + #tmpStaffing (DepartmentID, JobCodeID, PayCodeGroupID, EntityID, VariabilityID, EntityGroupConfigID, BudgetConfigID) + SELECT DISTINCT + staff.DepartmentID, + staff.JobCodeID, + staff.PayCodeGroupID, + staff.EntityID, + staff.VariabilityID, + staff.EntityGroupConfigID, + @BudgetConfigID AS BudgetConfigID + FROM [fp].[Staffing] staff (readuncommitted) + INNER JOIN #FilterByDepartment SD on SD.DepartmentID = staff.DepartmentID + WHERE staff.EntityGroupConfigID = @EntityGroupConfigID + AND staff.SubsectionID = 3 +END +ELSE BEGIN + INSERT INTO + #tmpStaffing (DepartmentID, JobCodeID, PayCodeGroupID, EntityID, VariabilityID, EntityGroupConfigID, BudgetConfigID) + SELECT DISTINCT + staff.DepartmentID, + staff.JobCodeID, + staff.PayCodeGroupID, + staff.EntityID, + staff.VariabilityID, + staff.EntityGroupConfigID, + @BudgetConfigID AS BudgetConfigID + FROM [fp].[Staffing] staff (readuncommitted) + WHERE staff.EntityGroupConfigID = @EntityGroupConfigID + AND staff.SubsectionID = 3 +END + +-- Load any rows that need to be crosswalked +EXEC( + ' + INSERT INTO #itemsToPad + SELECT DISTINCT + staff.DepartmentID, + pax.AccountID, + acc.OBDollarsFinancialReportingID, + staff.EntityID, + staff.VariabilityID, + staff.EntityGroupConfigID, + staff.BudgetConfigID + FROM #tmpStaffing staff + ' + @SqlJoin + ' + INNER JOIN [fw].[DimAccount] acc (readuncommitted) on pax.AccountID = acc.AccountID + WHERE + pax.UnitTypeID = 34 + AND staff.EntityGroupConfigID = ' + @EntityGroupConfigID +) + +IF EXISTS (SELECT 1 FROM #itemsToPad) BEGIN + -- For any rows not in the GeneralLedger, insert them in now. + INSERT INTO [fp].[GeneralLedger] + (DepartmentID, AccountID, FinancialReportingID, EntityID, VariabilityID, BudgetConfigID, EntityGroupConfigID, APEModelSectionID, IsNew, AddDate) + SELECT + pbr.DepartmentID, + pbr.AccountID, + pbr.OBDollarsFinancialReportingID, + pbr.EntityID, + pbr.VariabilityID, + pbr.BudgetConfigID, + pbr.EntityGroupConfigID, + 6 AS APEModelSectionID, + 1 AS IsNew, + GETDATE() AS AddDate + FROM #itemsToPad pbr + LEFT JOIN [fp].[GeneralLedger] abr (readuncommitted) ON pbr.DepartmentID = abr.DepartmentID + AND pbr.AccountID = abr.AccountID + AND pbr.EntityGroupConfigID = abr.EntityGroupConfigID + AND pbr.VariabilityID = abr.VariabilityID + AND pbr.EntityID = abr.EntityID + AND pbr.OBDollarsFinancialReportingID = abr.FinancialReportingID + WHERE abr.GeneralLedgerID IS NULL; +END + +IF OBJECT_ID('tempdb..#tmpStaffing') IS NOT NULL DROP TABLE #tmpStaffing + +DECLARE @IsProviderPlanningEnabled BIT; +SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID; + +IF @IsProviderPlanningEnabled = 1 BEGIN + TRUNCATE TABLE #itemsToPad + + CREATE TABLE #Accts ( + AccountID INT, + ProviderTypeID INT, + ProviderLineItemID INT, + OBDollarsFinancialReportingID INT + ) + + INSERT INTO + #Accts (AccountID, ProviderTypeID, ProviderLineItemID, OBDollarsFinancialReportingID) + SELECT DISTINCT psc.AccountID, 0, ProviderLineItemID, OBDollarsFinancialReportingID + FROM fp.ProviderStaffingConfig psc + INNER JOIN fw.DimAccount acct on psc.AccountID = acct.AccountID + WHERE BudgetConfigID = @BudgetConfigID + AND IsEditByProviderType = 0 + AND psc.AccountID > 0 + UNION + SELECT DISTINCT t.AccountID, ProviderTypeID, ProviderLineItemID, OBDollarsFinancialReportingID + FROM fp.ProviderStaffingConfigProviderType t + INNER JOIN fp.ProviderStaffingConfig psc on t.ProviderStaffingConfigID = psc.ProviderStaffingConfigID + INNER JOIN fw.DimAccount acct on t.AccountID = acct.AccountID + WHERE BudgetConfigID = @BudgetConfigID + AND IsEditByProviderType = 1 + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) BEGIN + INSERT INTO + #itemsToPad (DepartmentID, AccountID, OBDollarsFinancialReportingID, EntityID, VariabilityID, BudgetConfigID, EntityGroupConfigID) + SELECT + DISTINCT staff.DepartmentID, + acct.AccountID, + acct.OBDollarsFinancialReportingID, + staff.EntityID, + staff.VariabilityID, + staff.BudgetConfigID, + staff.EntityGroupConfigID + FROM #Accts acct + INNER JOIN fp.Staffing staff ON acct.ProviderLineItemID = staff.ProviderLineItemID + AND acct.ProviderLineItemID = staff.ProviderLineItemID + INNER JOIN #FilterByDepartment dept on staff.DepartmentID = dept.DepartmentID + WHERE staff.EntityGroupConfigID = @EntityGroupConfigID + AND staff.SubsectionID = 4 + END + ELSE BEGIN + INSERT INTO + #itemsToPad (DepartmentID, AccountID, OBDollarsFinancialReportingID, EntityID, VariabilityID, BudgetConfigID, EntityGroupConfigID) + SELECT DISTINCT + staff.DepartmentID, + acct.AccountID, + acct.OBDollarsFinancialReportingID, + staff.EntityID, + staff.VariabilityID, + staff.BudgetConfigID, + staff.EntityGroupConfigID + FROM #Accts acct + INNER JOIN fp.Staffing staff ON acct.ProviderLineItemID = staff.ProviderLineItemID + AND acct.ProviderLineItemID = staff.ProviderLineItemID + WHERE staff.EntityGroupConfigID = @EntityGroupConfigID + AND staff.SubsectionID = 4 + END + + INSERT INTO [fp].[GeneralLedger] ( + DepartmentID, + AccountID, + FinancialReportingID, + EntityID, + VariabilityID, + BudgetConfigID, + EntityGroupConfigID, + APEModelSectionID, + IsNew, + AddDate) + SELECT + staff.DepartmentID, + staff.AccountID, + staff.OBDollarsFinancialReportingID, + staff.EntityID, + staff.VariabilityID, + staff.BudgetConfigID, + staff.EntityGroupConfigID, + 6 AS APEModelSectionID, + 1 AS IsNew, + GETDATE() AS AddDate + FROM + #itemsToPad staff + LEFT JOIN [fp].[GeneralLedger] gl (readuncommitted) ON staff.DepartmentID = gl.DepartmentID + AND staff.AccountID = gl.AccountID + AND staff.EntityGroupConfigID = gl.EntityGroupConfigID + AND staff.VariabilityID = gl.VariabilityID + AND staff.EntityID = gl.EntityID + AND staff.OBDollarsFinancialReportingID = gl.FinancialReportingID + WHERE gl.GeneralLedgerID IS NULL; + +END +END +GO + + +--------------------------------------------- + +-- fp.procPadStatistics +CREATE PROCEDURE [fp].[procPadStatistics] + @BudgetConfigID int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + CREATE TABLE #FilterByDepartment (DepartmentID INT) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #BudgetPhase (BudgetPhaseID TINYINT) + INSERT INTO #BudgetPhase (BudgetPhaseID) SELECT 2 UNION SELECT 3 + + CREATE TABLE #FilteredData (StatisticsID INT PRIMARY KEY CLUSTERED) + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilteredData + SELECT [fs].[StatisticsID] + FROM [fp].[FactStatistics] fs + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = fs.DepartmentID or ft.DepartmentID is null) + WHERE fs.BudgetConfigID = @BudgetConfigID + END ELSE BEGIN + INSERT INTO #FilteredData + SELECT [fs].[StatisticsID] + FROM [fp].[FactStatistics] fs + WHERE fs.BudgetConfigID = @BudgetConfigID + END + + INSERT INTO [fp].[FactStatisticsBudget]([StatisticsID], [BudgetPhaseID]) + SELECT [fgl].[StatisticsID], psh.[BudgetPhaseID] + FROM [fp].[FactStatistics] fgl + INNER JOIN #FilteredData filter ON fgl.StatisticsID = filter.StatisticsID + OUTER APPLY #BudgetPhase psh + WHERE BudgetConfigID = @BudgetConfigID + AND NOT EXISTS (SELECT 1 FROM fp.FactStatisticsBudget bud WITH (READUNCOMMITTED) WHERE fgl.StatisticsID = bud.StatisticsID AND bud.BudgetPhaseID = psh.BudgetPhaseID) + + INSERT INTO [fp].[FactStatisticsProjection]([StatisticsID], [BudgetPhaseID]) + SELECT [fgl].[StatisticsID], psh.[BudgetPhaseID] + FROM [fp].[FactStatistics] fgl + INNER JOIN #FilteredData filter ON fgl.StatisticsID = filter.StatisticsID + OUTER APPLY #BudgetPhase psh + WHERE BudgetConfigID = @BudgetConfigID + AND NOT EXISTS (SELECT 1 FROM fp.FactStatisticsProjection proj WITH (READUNCOMMITTED) WHERE fgl.StatisticsID = proj.StatisticsID AND proj.BudgetPhaseID = psh.BudgetPhaseID) + + INSERT INTO [fp].[FactStatisticsHistory]([StatisticsID]) + SELECT [fgl].[StatisticsID] + FROM [fp].[FactStatistics] fgl + INNER JOIN #FilteredData filter ON fgl.StatisticsID = filter.StatisticsID + WHERE BudgetConfigID = @BudgetConfigID + AND NOT EXISTS (SELECT 1 FROM fp.FactStatisticsHistory hist WITH (READUNCOMMITTED) WHERE fgl.StatisticsID = hist.StatisticsID) +END +GO + + +--------------------------------------------- + +-- fp.procPatientActivityFlexingConfigPopulation +CREATE PROCEDURE fp.procPatientActivityFlexingConfigPopulation + @EntityGroupConfigGUID UNIQUEIDENTIFIER, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsGL bit = 1, + @IsStaffing bit = 1 +AS +BEGIN + /********************************************************************* + ** Change History + ********************************************************************** + ** CID Date Author WI Description + ** 1 2021-09-24 MD JAZZ-25923 Add Patient Activity Flex data to fp.FlexConfigMapping table + ** 2 2021-11-22 NT JAZZ-28343 Pass in boolean to determine whether populating patient activity mapping for staffing or GL section + ** 3 2023-08-09 BW JAZZ-58199 Data model restructure for GL + ** 4 2023-11-08 MD JAZZ-62448 Data model restructure for Staffing + *********************************************************************/ + DECLARE @BudgetConfigID INT, + @EntityGroupConfigID INT, + @PAFlexMethod INT, + @FlexTypeID INT + + SELECT @BudgetConfigID = bc.BudgetConfigID, @EntityGroupConfigID = egc.EntityGroupConfigID + FROM [fp].[EntityGroupConfig] egc + INNER JOIN [fp].[BudgetConfig] bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID + + SET @PAFlexMethod = 2; + SET @FlexTypeID = 7; + + EXEC [dbo].[procSysDropTempTable] '#flexMap' + EXEC [dbo].[procSysDropTempTable] '#filteringTable' + + CREATE TABLE #flexMap ( + DepartmentID int NOT NULL, + GLAccountID int NOT NULL, + PRJobCodeID int NOT NULL + ); + + CREATE TABLE #filteringTable ( + DepartmentID INT + ,INDEX ix_1 NONCLUSTERED (DepartmentID) + ) + + INSERT INTO #filteringTable (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the #FilteringTable is empty, pass all dept to avoid duplicate statements + IF NOT EXISTS(SELECT 1 FROM #filteringTable WHERE DepartmentID IS NOT NULL) + BEGIN + ;WITH Departments AS ( + SELECT DISTINCT DepartmentID FROM fp.Staffing WHERE EntityGroupConfigID = @EntityGroupConfigID + UNION ALL + SELECT DISTINCT DepartmentID FROM fp.GeneralLedger WHERE EntityGroupConfigID = @EntityGroupConfigID + ) + INSERT INTO #filteringTable (DepartmentID) + SELECT DISTINCT DepartmentID FROM Departments + END + + ----------------------------------------------------------------- + --Do staffing flex config map + IF (@IsStaffing = 1) + BEGIN + INSERT INTO #flexMap(DepartmentID, PRJobCodeID, GLAccountID) + SELECT DISTINCT fs.DepartmentID, fs.JobCodeID, 0 + FROM fp.Staffing fs + JOIN #filteringTable ft ON fs.DepartmentID = ft.DepartmentID + JOIN [fp].[viewStaffingExpenseFlexingConfig] fc + ON fc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND ft.DepartmentID = fc.DepartmentID + AND fs.JobCodeID = fc.JobCodeID + WHERE 1=1 + AND fs.BudgetConfigID = @BudgetConfigID + AND fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.VariabilityID = 2 + AND fc.FlexMethodID = @PAFlexMethod + END + + IF (@IsGL = 1) + BEGIN + --Do non staffing flex config map + INSERT INTO #flexMap(DepartmentID, GLAccountID, PRJobCodeID) + SELECT DISTINCT gl.DepartmentID, gl.AccountID, 0 + FROM fp.GeneralLedger gl + JOIN #filteringTable ft ON gl.DepartmentID = ft.DepartmentID + JOIN [fp].[viewNonStaffingExpenseFlexingConfig] fc + ON fc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND ft.DepartmentID = fc.DepartmentID + AND gl.AccountID = fc.AccountID + WHERE 1=1 + AND gl.BudgetConfigID = @BudgetConfigID + AND gl.EntityGroupConfigID = @EntityGroupConfigID + AND gl.VariabilityID = 2 + AND fc.FlexMethodID = @PAFlexMethod + END + + ----------------------------------------------------------------- + + ;WITH TRG AS + (SELECT fcm.EntityGroupConfigID,fcm.DepartmentID,fcm.GLAccountID,fcm.PRJobCodeID,fcm.FlexingTypeID FROM [fp].[FlexConfigMapping] fcm + INNER JOIN #filteringTable ft on ft.DepartmentID = fcm.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND FlexingTypeID = @FlexTypeID + AND ((@IsGL = 1 AND PRJobCodeID = 0) OR + (@IsStaffing = 1 AND GLAccountID = 0)) + ) + + MERGE TRG + USING (SELECT @EntityGroupConfigID AS EntityGroupConfigID, + DepartmentID, + GLAccountID, + PRJobCodeID, + @FlexTypeID AS FlexingTypeID + FROM #flexMap) AS Src ON TRG.DepartmentID = SRC.DepartmentID and TRG.GLAccountID = SRC.GLAccountID and TRG.PRJobCodeID = SRC.PRJobcodeID + WHEN NOT MATCHED BY TARGET THEN + INSERT VALUES (src.EntityGroupConfigID,src.DepartmentID,src.GLAccountID,src.PRJobCodeID,src.FlexingTypeID) + WHEN NOT MATCHED BY SOURCE THEN DELETE; +END +GO + + +--------------------------------------------- + +-- fp.procPopulateAccountVariability +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2021-03-23 NN JAZZ-14117 Remove null joins and joins on targting object +** 2 2021-07-01 MD JAZZ-13102 Use original department when populating variability +** 3 5-9-2023 NT JAZZ-54290 Data restructure changes to use new fp.GeneralLedger table +*************************************************************/ + +CREATE PROCEDURE [fp].[procPopulateAccountVariability] + @EntityGroupConfigGUID UNIQUEIDENTIFIER, + @EntityGroupConfigID int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fp.GeneralLedger gl WITH (READUNCOMMITTED) + where gl.EntityGroupConfigID = @EntityGroupConfigID + END + + DELETE av FROM [fp].[FactAccountVariability] av + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = av.DepartmentID + WHERE av.EntityGroupConfigGUID = @EntityGroupConfigGUID + + + -- Patient Activity + INSERT INTO [fp].[FactAccountVariability](EntityGroupConfigGUID, DepartmentID, AccountID, FixedPercentage) + SELECT + fp.EntityGroupConfigGUID, + fp.DepartmentID, + fp.AccountID, + CASE WHEN fp.TotalCost = 0 THEN 0 + WHEN (fp.TotalFixedDirectCost / fp.TotalCost) > .9999 THEN 1.0 + ELSE (fp.TotalFixedDirectCost / fp.TotalCost) END AS [FixedPercentage] + FROM + (SELECT + ec.EntityGroupConfigGUID, + base.OriginalDepartmentID as DepartmentID, --use original department for fp tables, not reclassed department + OriginalAccountID as AccountID, + efc.FlexMethodID, + SUM(base.FixedDirectUnitCost * base.Volume) as TotalFixedDirectCost, + SUM(base.TotalCost) as TotalCost + FROM + [dss].[FactCostingOutDetailGL] base + INNER JOIN [dss].[CostingResult] cr on base.CostingResultID = cr.CostingResultID + INNER JOIN [fp].[EntityGroupConfig] ec on cr.CostingConfigGuid = ec.CostingConfigGUID + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = base.OriginalDepartmentID -- make sure we are filtering on the Original Department + INNER JOIN [fp].[viewNonStaffingExpenseFlexingConfig] efc + ON ec.EntityGroupConfigGUID = efc.EntityGroupConfigGUID + AND base.OriginalDepartmentID = efc.DepartmentID + AND base.OriginalAccountID = efc.AccountID + WHERE + base.CostingResultID IN (select max(cr2.CostingResultID) from [dss].[CostingResult] cr2 where cr2.CostingConfigGuid = ec.CostingConfigGuid and cr2.IsActivityBasedDetail = 1 and cr2.IsMarkedForDeletion = 0) + AND base.TimeClassID = ec.CostingConfigTimeClassID + AND ec.EntityGroupConfigGuid = @EntityGroupConfigGuid + AND efc.FlexMethodID = 2 -- patient activity + GROUP BY + ec.EntityGroupConfigGUID, + base.OriginalAccountID, + base.OriginalDepartmentID, --group by same Original Department as we are using to insert data into fp tables + base.FiscalYearID, + efc.FlexMethodID + ) fp + WHERE + fp.EntityGroupConfigGUID = @EntityGroupConfigGuid + AND NOT(CASE WHEN fp.TotalCost = 0 THEN 0 ELSE fp.TotalFixedDirectCost / fp.TotalCost END > .9999) -- Filter out fixed records + + + -- Stat Accounts + INSERT INTO [fp].[FactAccountVariability](EntityGroupConfigGUID, DepartmentID, AccountID, FixedPercentage) + SELECT + fc.EntityGroupConfigGUID, + fc.DepartmentID, + vc.AccountID, + 1 - vc.Variability AS [FixedPercentage] + FROM [fp].[NonStaffingVariabilityConfig] vc + INNER JOIN [fp].[viewNonStaffingExpenseFlexingConfig] fc + ON vc.EntityGroupConfigGUID = fc.EntityGroupConfigGUID + AND vc.AccountID = fc.AccountID + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = fc.DepartmentID + WHERE + vc.EntityGroupConfigGUID = @EntityGroupConfigGuid + AND fc.FlexMethodID in (1) -- StatisticAccounts + AND vc.Variability > 0 -- Filter out fixed records + + -- Revenue accounts (revenue accounts are 100% variable unless marked as fixed) + INSERT INTO [fp].[FactAccountVariability](EntityGroupConfigGUID, DepartmentID, AccountID, FixedPercentage) + SELECT + fc.EntityGroupConfigGUID, + fc.DepartmentID, + fc.AccountID, + 0 AS [FixedPercentage] + FROM [fp].[viewRevenueExpenseFlexingConfig] fc + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = fc.DepartmentID + WHERE fc.EntityGroupConfigGUID = @EntityGroupConfigGuid + AND fc.FlexMethodID != 6 -- Filter out fixed records + + -- Variable deductions accounts (deductions are 100% variable unless marked as fixed) + INSERT INTO [fp].[FactAccountVariability](EntityGroupConfigGUID, DepartmentID, AccountID, FixedPercentage) + SELECT + fc.EntityGroupConfigGUID, + fc.DepartmentID, + fc.AccountID, + 0 AS [FixedPercentage] + FROM [fp].[viewDeductionsFlexingConfig] fc + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = fc.DepartmentID + WHERE fc.EntityGroupConfigGUID = @EntityGroupConfigGuid + AND fc.FlexMethodID != 6 -- Filter out fixed records + + -- Benefits accounts (benefit accounts are 100% variable) + INSERT INTO [fp].[FactAccountVariability](EntityGroupConfigGUID, DepartmentID, AccountID, FixedPercentage) + SELECT DISTINCT + @EntityGroupConfigGuid, + gl.DepartmentID, + gl.AccountID, + 0 AS [FixedPercentage] + FROM [fp].[GeneralLedger] gl + INNER JOIN [fp].[viewBenefitsAccounts] ba ON gl.AccountID = ba.AccountID + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = gl.DepartmentID + WHERE gl.EntityGroupConfigID = @EntityGroupConfigID + +END +GO + + +--------------------------------------------- + +-- fp.procPopulateAccountVariabilityByBudgetConfig +CREATE PROC fp.procPopulateAccountVariabilityByBudgetConfig + @BudgetConfigID INT +AS +BEGIN + DECLARE @EntityGroupConfigGuid UNIQUEIDENTIFIER + DECLARE @EntityGroupConfigId INT + + DECLARE entityGroupConfigCrs CURSOR FOR + SELECT + EntityGroupConfigGUID, + EntityGroupConfigID + FROM [fp].[EntityGroupConfig] egc + INNER JOIN [fp].[BudgetConfig] bc on egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigId; + + OPEN entityGroupConfigCrs + + FETCH NEXT FROM entityGroupConfigCrs INTO @EntityGroupConfigGuid, @EntityGroupConfigId + + WHILE @@FETCH_STATUS = 0 + BEGIN + EXEC [fp].[procPopulateAccountVariability] @EntityGroupConfigGUID = @EntityGroupConfigGuid, @EntityGroupConfigID = @EntityGroupConfigId + + FETCH NEXT FROM entityGroupConfigCrs INTO @EntityGroupConfigGuid, @EntityGroupConfigId + END + + CLOSE entityGroupConfigCrs; + DEALLOCATE entityGroupConfigCrs; +END +GO + + +--------------------------------------------- + +-- fp.procPopulateAccountVariability_InitialPlan +CREATE PROCEDURE [fp].[procPopulateAccountVariability_InitialPlan] + @BudgetConfigGUID UNIQUEIDENTIFIER, + @BudgetConfigID SMALLINT, + @EntityGroupConfigIDs VARCHAR(MAX), + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + 1 2024-05-27 MV JAZZ-71177 Create SP for Initial plan method baseed on [fp].[procPopulateAccountVariability] + *************************************************************/ + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#FilterByEntityGroupConfig') IS NOT NULL DROP TABLE #FilterByEntityGroupConfig + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #FilterByEntityGroupConfig (EntityGroupConfigID int, EntityGroupConfigGUID uniqueidentifier) + + IF @EntityGroupConfigIDs IS NOT NULL AND @EntityGroupConfigIDs <> '' + BEGIN + INSERT INTO #FilterByEntityGroupConfig (EntityGroupConfigID, EntityGroupConfigGUID) + SELECT EntityGroupConfigID, EntityGroupConfigGUID FROM [fp].[EntityGroupConfig] + WHERE BudgetConfigGUID = @BudgetConfigGUID + AND EntityGroupConfigID IN (SELECT TRIM([value]) AS EntityGroupConfigID FROM STRING_SPLIT(@EntityGroupConfigIDs, ',' )) + END + ELSE BEGIN + INSERT INTO #FilterByEntityGroupConfig (EntityGroupConfigID, EntityGroupConfigGUID) + SELECT EntityGroupConfigID, EntityGroupConfigGUID FROM [fp].[EntityGroupConfig] + WHERE BudgetConfigGUID = @BudgetConfigGUID + END + + + + -- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fp.GeneralLedger gl WITH (READUNCOMMITTED) + INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = gl.EntityGroupConfigID + WHERE gl.BudgetConfigID = @BudgetConfigID + END + + DELETE av FROM [fp].[FactAccountVariability] av + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = av.DepartmentID + INNER JOIN #FilterByEntityGroupConfig fegc on fegc.EntityGroupConfigGUID = av.EntityGroupConfigGUID + + + -- Patient Activity + INSERT INTO [fp].[FactAccountVariability](EntityGroupConfigGUID, DepartmentID, AccountID, FixedPercentage) + SELECT + fp.EntityGroupConfigGUID, + fp.DepartmentID, + fp.AccountID, + CASE WHEN fp.TotalCost = 0 THEN 0 + WHEN (fp.TotalFixedDirectCost / fp.TotalCost) > .9999 THEN 1.0 + ELSE (fp.TotalFixedDirectCost / fp.TotalCost) END AS [FixedPercentage] + FROM + (SELECT + ec.EntityGroupConfigGUID, + base.OriginalDepartmentID as DepartmentID, --use original department for fp tables, not reclassed department + OriginalAccountID as AccountID, + efc.FlexMethodID, + SUM(base.FixedDirectUnitCost * base.Volume) as TotalFixedDirectCost, + SUM(base.TotalCost) as TotalCost + FROM + [dss].[FactCostingOutDetailGL] base + INNER JOIN [dss].[CostingResult] cr on base.CostingResultID = cr.CostingResultID + INNER JOIN [fp].[EntityGroupConfig] ec on cr.CostingConfigGuid = ec.CostingConfigGUID + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = base.OriginalDepartmentID -- make sure we are filtering on the Original Department + INNER JOIN [fp].[viewNonStaffingExpenseFlexingConfig] efc + ON ec.EntityGroupConfigGUID = efc.EntityGroupConfigGUID + AND base.OriginalDepartmentID = efc.DepartmentID + AND base.OriginalAccountID = efc.AccountID + INNER JOIN #FilterByEntityGroupConfig fegc on fegc.EntityGroupConfigGUID = ec.EntityGroupConfigGUID + WHERE + base.CostingResultID IN (select max(cr2.CostingResultID) from [dss].[CostingResult] cr2 where cr2.CostingConfigGuid = ec.CostingConfigGuid and cr2.IsActivityBasedDetail = 1 and cr2.IsMarkedForDeletion = 0) + AND base.TimeClassID = ec.CostingConfigTimeClassID + AND efc.FlexMethodID = 2 -- patient activity + GROUP BY + ec.EntityGroupConfigGUID, + base.OriginalAccountID, + base.OriginalDepartmentID, --group by same Original Department as we are using to insert data into fp tables + base.FiscalYearID, + efc.FlexMethodID + ) fp + WHERE + NOT(CASE WHEN fp.TotalCost = 0 THEN 0 ELSE fp.TotalFixedDirectCost / fp.TotalCost END > .9999) -- Filter out fixed records + + + -- Stat Accounts + INSERT INTO [fp].[FactAccountVariability](EntityGroupConfigGUID, DepartmentID, AccountID, FixedPercentage) + SELECT + fc.EntityGroupConfigGUID, + fc.DepartmentID, + vc.AccountID, + 1 - vc.Variability AS [FixedPercentage] + FROM [fp].[NonStaffingVariabilityConfig] vc + INNER JOIN [fp].[viewNonStaffingExpenseFlexingConfig] fc + ON vc.EntityGroupConfigGUID = fc.EntityGroupConfigGUID + AND vc.AccountID = fc.AccountID + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = fc.DepartmentID + INNER JOIN #FilterByEntityGroupConfig fegc on fegc.EntityGroupConfigGUID = vc.EntityGroupConfigGUID + WHERE + fc.FlexMethodID in (1) -- StatisticAccounts + AND vc.Variability > 0 -- Filter out fixed records + + -- Revenue accounts (revenue accounts are 100% variable unless marked as fixed) + INSERT INTO [fp].[FactAccountVariability](EntityGroupConfigGUID, DepartmentID, AccountID, FixedPercentage) + SELECT + fc.EntityGroupConfigGUID, + fc.DepartmentID, + fc.AccountID, + 0 AS [FixedPercentage] + FROM [fp].[viewRevenueExpenseFlexingConfig] fc + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = fc.DepartmentID + INNER JOIN #FilterByEntityGroupConfig fegc on fegc.EntityGroupConfigGUID = fc.EntityGroupConfigGUID + WHERE + fc.FlexMethodID != 6 -- Filter out fixed records + + -- Variable deductions accounts (deductions are 100% variable unless marked as fixed) + INSERT INTO [fp].[FactAccountVariability](EntityGroupConfigGUID, DepartmentID, AccountID, FixedPercentage) + SELECT + fc.EntityGroupConfigGUID, + fc.DepartmentID, + fc.AccountID, + 0 AS [FixedPercentage] + FROM [fp].[viewDeductionsFlexingConfig] fc + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = fc.DepartmentID + INNER JOIN #FilterByEntityGroupConfig fegc on fegc.EntityGroupConfigGUID = fc.EntityGroupConfigGUID + WHERE + fc.FlexMethodID != 6 -- Filter out fixed records + + -- Benefits accounts (benefit accounts are 100% variable) + INSERT INTO [fp].[FactAccountVariability](EntityGroupConfigGUID, DepartmentID, AccountID, FixedPercentage) + SELECT DISTINCT + fegc.EntityGroupConfigGuid, + gl.DepartmentID, + gl.AccountID, + 0 AS [FixedPercentage] + FROM [fp].[GeneralLedger] gl + INNER JOIN [fp].[viewBenefitsAccounts] ba ON gl.AccountID = ba.AccountID + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = gl.DepartmentID + INNER JOIN #FilterByEntityGroupConfig fegc on fegc.EntityGroupConfigID = gl.EntityGroupConfigID + WHERE gl.BudgetConfigID = @BudgetConfigID + +END +GO + + +--------------------------------------------- + +-- fp.procPopulateBudgetConfigSettings +/********************************************************************* +** Change History +********************************************************************** +** CID Date Author WI Description +** 1 2020-05-24 MY JAZZ-20113 Initial +*********************************************************************/ +CREATE PROCEDURE [fp].[procPopulateBudgetConfigSettings] + @BudgetConfigID INT = 0 +AS +BEGIN + + INSERT INTO fp.BudgetConfigSetting (BudgetConfigID, SettingID, Value) + SELECT + bc.BudgetConfigID, + s.SettingID, + DefaultValue AS Value + FROM [fp].[BudgetConfigDefaultSetting] s + CROSS APPLY (SELECT DISTINCT BudgetConfigID FROM [fp].[BudgetConfig] WHERE BudgetConfigID = @BudgetConfigID OR @BudgetConfigID = 0) bc + LEFT JOIN [fp].[BudgetConfigSetting] bcs ON bc.BudgetConfigID = bcs.BudgetConfigID AND bcs.SettingID = s.SettingID + WHERE bcs.BudgetConfigID IS NULL + +END +GO + + +--------------------------------------------- + +-- fp.procPopulateChargeVolumeToStatCrosswalk +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 5-18-2023 MY JAZZ-55153 Updated view to restructure +*************************************************************/ +CREATE PROCEDURE [fp].[procPopulateChargeVolumeToStatCrosswalk] + @EntityGroupConfigID int +AS +BEGIN + DECLARE @IsRecordsInChargeVolume INT + SELECT @IsRecordsInChargeVolume = COUNT(*) FROM [fp].[ChargeVolume] WHERE EntityGroupConfigID = @EntityGroupConfigID + IF @IsRecordsInChargeVolume = 0 + SELECT @IsRecordsInChargeVolume; + ELSE + INSERT INTO [fp].[ChargeToStatisticsCrosswalkConfiguration] + (EntityGroupConfigID, DepartmentID, ChargeCodeID, PatientClassID, RVUWeight) + + SELECT DISTINCT + fcv.EntityGroupConfigID, + fcv.DepartmentID, + fcv.ChargeCodeID, + fcv.PatientClassID, + dcc.RVUWeight + FROM [fp].[ChargeVolume] fcv + INNER JOIN [fw].[DimChargeCode] dcc + ON fcv.ChargeCodeID = dcc.ChargeCodeID + WHERE fcv.EntityGroupConfigID = @EntityGroupConfigID + EXCEPT + SELECT + fcv.EntityGroupConfigID, + fcv.DepartmentID, + fcv.ChargeCodeID, + fcv.PatientClassID, + dcc.RVUWeight + FROM [fp].[ChargeVolume] fcv + INNER JOIN [fp].[ChargeToStatisticsCrosswalkConfiguration] crosswalk + ON fcv.EntityGroupConfigID = crosswalk.EntityGroupConfigID + AND fcv.DepartmentID = crosswalk.DepartmentID + AND fcv.ChargeCodeID = crosswalk.ChargeCodeID + AND fcv.PatientClassID = crosswalk.PatientClassID + INNER JOIN [fw].[DimChargeCode] dcc + ON fcv.ChargeCodeID = dcc.ChargeCodeID + WHERE fcv.EntityGroupConfigID = @EntityGroupConfigID; + + SELECT @IsRecordsInChargeVolume; +END +GO + + +--------------------------------------------- + +-- fp.procPopulateDepartmentConfig +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-09-25 GF E-02313 Simplify source dimensionality to only department +** 2 2020-12-11 BW JAZZ-8104 Departments with Expenses-Zero Based accounts to get populated in Department config +** 3 2021-02-16 NN JAZZ-467 Remove null joins and joins on targting object +** 4 2023-06-01 MY JAZZ-54655 Update to new GL Structure +** 5 01-03-2023 MY JAZZ-63564 Final Pass Of Fact References (SQL) +** 6 2024-05-21 MY JAZZ-72116 Fix Duplicate Key Issue with Unnecessary Join to Mapping Table +*************************************************************/ +CREATE PROCEDURE [fp].[procPopulateDepartmentConfig] + @EntityGroupConfigGUID UNIQUEIDENTIFIER, + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +WITH RECOMPILE +AS +BEGIN + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fw].[DimDepartment] d WITH (READUNCOMMITTED) + END + + CREATE TABLE #DepartmentConfigData ( + EntityGroupConfigGUID UNIQUEIDENTIFIER, + DepartmentID INT, + SectionName NVARCHAR(MAX), + SectionValue INT + ); + + INSERT INTO #DepartmentConfigData (EntityGroupConfigGUID, DepartmentID, SectionName, SectionValue) + SELECT * + FROM ( + SELECT DISTINCT egc.EntityGroupConfigGUID, basis.DepartmentID, 'HasStatistics' AS SectionName, 1 AS SectionValue + FROM [fp].[FactStatistics] basis + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = basis.DepartmentID + INNER JOIN fp.EntityGroupConfigMapping map ON map.EntityID = basis.EntityID + INNER JOIN fp.EntityGroupConfig egc ON egc.EntityGroupConfigGUID = map.EntityGroupConfigGUID + WHERE egc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND basis.BudgetConfigID = @BudgetConfigID + + UNION + + SELECT DISTINCT egc.EntityGroupConfigGUID, basis.DepartmentID, 'HasRevenueAndDeductions' AS SectionName, 1 AS SectionValue + FROM [fp].[GeneralLedger] basis + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = basis.DepartmentID + INNER JOIN fp.EntityGroupConfigMapping map ON map.EntityID = basis.EntityID + INNER JOIN fp.EntityGroupConfig egc ON egc.EntityGroupConfigGUID = map.EntityGroupConfigGUID + INNER JOIN [fw].[DimAccount] acc ON basis.AccountID = acc.AccountID + INNER JOIN [ob].[DimAccountPH] ph ON acc.OBAccountPHID = ph.AccountPHID + WHERE ph.Name IN ('Deductions', 'Deductions - Charity and Bad Debt', 'Deductions - Reimbursement', 'Gross Charges - Clinic', 'Gross Charges - ED', 'Gross Charges - Inpatient', 'Gross Charges - Observation', 'Gross Charges - Other', 'Gross Charges - Outpatient') + AND egc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND basis.BudgetConfigID = @BudgetConfigID + + UNION + + SELECT DISTINCT egc.EntityGroupConfigGUID, basis.DepartmentID, 'HasOtherRevenue' AS SectionName, 1 AS SectionValue + FROM [fp].[GeneralLedger] basis + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = basis.DepartmentID + INNER JOIN [fw].[DimAccount] acc ON basis.AccountID = acc.AccountID + INNER JOIN fp.EntityGroupConfigMapping map ON map.EntityID = basis.EntityID + INNER JOIN fp.EntityGroupConfig egc ON egc.EntityGroupConfigGUID = map.EntityGroupConfigGUID + WHERE acc.OBModelSectionName IN ('Other Revenue', 'Other Revenue - Zero Based') + AND egc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND basis.BudgetConfigID = @BudgetConfigID + + UNION + + SELECT DISTINCT egc.EntityGroupConfigGUID, basis.DepartmentID, 'HasStaffing' AS SectionName, 1 AS SectionValue + FROM [fp].[Staffing] basis + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = basis.DepartmentID + INNER JOIN fp.EntityGroupConfigMapping map ON map.EntityID = basis.EntityID + INNER JOIN fp.EntityGroupConfig egc ON egc.EntityGroupConfigGUID = map.EntityGroupConfigGUID + WHERE egc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND basis.BudgetConfigID = @BudgetConfigID + + UNION + + SELECT DISTINCT egc.EntityGroupConfigGUID, basis.DepartmentID, 'HasBenefits' AS SectionName, 1 AS SectionValue + FROM fp.FactBenefits basis + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = basis.DepartmentID + INNER JOIN fp.EntityGroupConfigMapping map ON map.EntityID = basis.EntityID + INNER JOIN fp.EntityGroupConfig egc ON egc.EntityGroupConfigGUID = map.EntityGroupConfigGUID + WHERE egc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND basis.BudgetConfigID = @BudgetConfigID + + UNION + + SELECT DISTINCT egc.EntityGroupConfigGUID, basis.DepartmentID, 'HasNonStaffingExpenses' AS SectionName, 1 AS SectionValue + FROM [fp].[GeneralLedger] basis + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = basis.DepartmentID + INNER JOIN [fw].[DimAccount] acc ON basis.AccountID = acc.AccountID + INNER JOIN [ob].[DimAccountPH] ph ON acc.OBAccountPHID = ph.AccountPHID + INNER JOIN fp.EntityGroupConfigMapping map ON map.EntityID = basis.EntityID + INNER JOIN fp.EntityGroupConfig egc ON egc.EntityGroupConfigGUID = map.EntityGroupConfigGUID + WHERE ph.Name IN ('Expenses - Non-Staffing') AND egc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND basis.BudgetConfigID = @BudgetConfigID + + + UNION + + SELECT DISTINCT egc.EntityGroupConfigGUID, basis.DepartmentID, 'HasZeroBasedExpenses' AS SectionName, 1 AS SectionValue + FROM [fp].[GeneralLedger] basis + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = basis.DepartmentID + INNER JOIN [fw].[DimAccount] acc ON basis.AccountID = acc.AccountID + INNER JOIN [ob].[DimAccountPH] ph ON acc.OBAccountPHID = ph.AccountPHID + INNER JOIN fp.EntityGroupConfigMapping map ON map.EntityID = basis.EntityID + INNER JOIN fp.EntityGroupConfig egc ON egc.EntityGroupConfigGUID = map.EntityGroupConfigGUID + WHERE ph.Name IN ('Expenses - Zero Based') AND egc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND basis.BudgetConfigID = @BudgetConfigID + + ) data + + ;WITH TargetData AS ( + + select config.* + from [fp].[DepartmentConfig] config + where config.EntityGroupConfigGUID = @EntityGroupConfigGUID + + ) + + MERGE TargetData targetConfig + USING ( + SELECT pvt.DepartmentID , + pvt.EntityGroupConfigGUID , + CAST(ISNULL(pvt.HasStatistics , 0) AS BIT) AS HasStatistics , + CAST(ISNULL(pvt.HasRevenueAndDeductions , 0) AS BIT) AS HasRevenueAndDeductions , + CAST(ISNULL(pvt.HasOtherRevenue , 0) AS BIT) AS HasOtherRevenue , + CAST(ISNULL(pvt.HasRoster , 0) AS BIT) AS HasRoster , + CAST(ISNULL(pvt.HasStaffing , 0) AS BIT) AS HasStaffing , + CAST(ISNULL(pvt.HasBenefits , 0) AS BIT) AS HasBenefits , + CAST(ISNULL(pvt.HasNonStaffingExpenses , 0) AS BIT) AS HasNonStaffingExpenses, + CAST(ISNULL(pvt.HasZeroBasedExpenses , 0) AS BIT) AS HasZeroBasedExpenses + + FROM + ( + SELECT d.EntityGroupConfigGUID , + d.DepartmentID , + d.SectionName , + d.SectionValue + FROM #DepartmentConfigData d + WHERE d.DepartmentID <> 0 + ) src + PIVOT + ( + SUM(SectionValue) + FOR SectionName IN (HasStatistics, HasRevenueAndDeductions, HasOtherRevenue, HasRoster, HasStaffing, HasBenefits, HasNonStaffingExpenses, HasZeroBasedExpenses) + ) pvt + ) AS sourceConfig ON sourceConfig.EntityGroupConfigGUID = targetConfig.EntityGroupConfigGUID AND sourceConfig.DepartmentID = targetConfig.DepartmentID + WHEN MATCHED THEN + UPDATE SET targetConfig.HasStatistics = sourceConfig.HasStatistics , + targetConfig.HasRevenueAndDeductions = sourceConfig.HasRevenueAndDeductions , + targetConfig.HasOtherRevenue = sourceConfig.HasOtherRevenue , + targetConfig.HasRoster = sourceConfig.HasRoster , + targetConfig.HasStaffing = sourceConfig.HasStaffing , + targetConfig.HasBenefits = sourceConfig.HasBenefits , + targetConfig.HasNonStaffingExpenses = sourceConfig.HasNonStaffingExpenses, + targetConfig.HasZeroBasedExpenses = sourceConfig.HasZeroBasedExpenses + + WHEN NOT MATCHED BY TARGET THEN + INSERT (DepartmentID, EntityGroupConfigGUID, HasStatistics, HasRevenueAndDeductions, HasOtherRevenue, HasRoster, HasStaffing, HasBenefits, HasNonStaffingExpenses, HasZeroBasedExpenses) + VALUES (sourceConfig.DepartmentID, sourceConfig.EntityGroupConfigGUID, sourceConfig.HasStatistics, sourceConfig.HasRevenueAndDeductions, + sourceConfig.HasOtherRevenue, sourceConfig.HasRoster, sourceConfig.HasStaffing, sourceConfig.HasBenefits, sourceConfig.HasNonStaffingExpenses, HasZeroBasedExpenses) + + -- We only want to do the delete when the data is not being targeted, otherwise it'll wipe out everything else and that would be bad. + WHEN NOT MATCHED BY SOURCE AND ((SELECT COUNT(*) FROM #FilterByDepartment) = 0) THEN + DELETE + OUTPUT $action AS ActionType, ISNULL(Deleted.DepartmentID, Inserted.DepartmentID) AS DepartmentID; + +END +GO + + +--------------------------------------------- + +-- fp.procPopulateFactBenefitsChangeHistoryGrouping +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-26-07 MY JAZZ-39273 Added Option Recomiple to SELECTs +*************************************************************/ +CREATE PROCEDURE [fp].[procPopulateFactBenefitsChangeHistoryGrouping] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + SET NOCOUNT ON; + + CREATE TABLE #dimensionality ( + EntityID INT, + DepartmentID INT, + AccountID INT, + FinancialReportingID INT, + ChangeHistoryGroupingGUID UNIQUEIDENTIFIER + ); + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS (SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #dimensionality(EntityID, DepartmentID, AccountID, FinancialReportingID, ChangeHistoryGroupingGUID) + SELECT DISTINCT EntityID, fs.DepartmentID, AccountID, FinancialReportingID, NEWID() AS ChangeHistoryGroupingGUID + FROM [fp].[FactBenefits] fs + INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = fs.DepartmentID + WHERE BudgetConfigID = @BudgetConfigID + AND UnitTypeID = 34 + OPTION(RECOMPILE) + END ELSE BEGIN + INSERT INTO #dimensionality(EntityID, DepartmentID, AccountID, FinancialReportingID, ChangeHistoryGroupingGUID) + SELECT DISTINCT EntityID, DepartmentID, AccountID, FinancialReportingID, NEWID() AS ChangeHistoryGroupingGUID + FROM [fp].[FactBenefits] fs + WHERE BudgetConfigID = @BudgetConfigID + AND UnitTypeID = 34 + OPTION(RECOMPILE) + END + + UPDATE fs + SET fs.ChangeHistoryGroupingGUID = dim.ChangeHistoryGroupingGUID + FROM [fp].[FactBenefits] fs + INNER JOIN #dimensionality dim ON + fs.EntityID = dim.EntityID + AND fs.DepartmentID = dim.DepartmentID + AND fs.AccountID = dim.AccountID + AND fs.FinancialReportingID = dim.FinancialReportingID + WHERE fs.BudgetConfigID = @BudgetConfigID + AND fs.ChangeHistoryGroupingGUID = '00000000-0000-0000-0000-000000000000' + +END +GO + + +--------------------------------------------- + +-- fp.procPopulateFactGeneralLedgerChangeHistoryGrouping +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-26-07 MY JAZZ-39273 Added Option Recomiple to SELECTs +** 2 5-10-2023 NT JAZZ-54290 Data restructure changes to use new fp.GeneralLedger table +*************************************************************/ +CREATE PROCEDURE [fp].[procPopulateFactGeneralLedgerChangeHistoryGrouping] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + SET NOCOUNT ON; + + CREATE TABLE #dimensionality ( + EntityID INT, + DepartmentID INT, + AccountID INT, + FinancialReportingID INT, + VariabilityID INT, + ChangeHistoryGroupingGUID UNIQUEIDENTIFIER + ); + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS (SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #dimensionality(EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID, ChangeHistoryGroupingGUID) + SELECT DISTINCT EntityID, fs.DepartmentID, AccountID, FinancialReportingID, VariabilityID, NEWID() AS ChangeHistoryGroupingGUID + FROM [fp].[GeneralLedger] fs + INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = fs.DepartmentID + WHERE BudgetConfigID = @BudgetConfigID + AND VariabilityID = 2 + OPTION(RECOMPILE) + END ELSE BEGIN + INSERT INTO #dimensionality(EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID, ChangeHistoryGroupingGUID) + SELECT DISTINCT EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID, NEWID() AS ChangeHistoryGroupingGUID + FROM [fp].[GeneralLedger] fs + WHERE BudgetConfigID = @BudgetConfigID + AND VariabilityID = 2 + OPTION(RECOMPILE) + END + + UPDATE fs + SET fs.ChangeHistoryGroupingGUID = dim.ChangeHistoryGroupingGUID + FROM [fp].[GeneralLedger] fs + INNER JOIN #dimensionality dim ON + fs.EntityID = dim.EntityID + AND fs.DepartmentID = dim.DepartmentID + AND fs.AccountID = dim.AccountID + AND fs.FinancialReportingID = dim.FinancialReportingID + AND fs.VariabilityID = dim.VariabilityID + WHERE fs.BudgetConfigID = @BudgetConfigID + AND fs.ChangeHistoryGroupingGUID = '00000000-0000-0000-0000-000000000000' + AND fs.VariabilityID = 2 -- We only need to use this for variable records, fixed doesn't use it + +END +GO + + +--------------------------------------------- + +-- fp.procPopulateFactStaffingChangeHistoryGrouping +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-26-07 MY JAZZ-39273 Added Option Recomiple to SELECTs +** 2 2023-09-20 BK JAZZ-60973 Update for new data structure +*************************************************************/ +CREATE PROCEDURE [fp].[procPopulateFactStaffingChangeHistoryGrouping] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + SET NOCOUNT ON; + + CREATE TABLE #dimensionality ( + EntityID INT, + DepartmentID INT, + JobCodeID INT, + PayCodeGroupID INT, + ProductiveClassID INT, + VariabilityID INT, + EmployeeID INT, + ChangeHistoryGroupingGUID UNIQUEIDENTIFIER + ); + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS (SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #dimensionality(EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, ChangeHistoryGroupingGUID) + SELECT DISTINCT EntityID, fs.DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, NEWID() AS ChangeHistoryGroupingGUID + FROM [fp].[Staffing] fs + INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = fs.DepartmentID + WHERE BudgetConfigID = @BudgetConfigID + OPTION(RECOMPILE) + END ELSE BEGIN + INSERT INTO #dimensionality(EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, ChangeHistoryGroupingGUID) + SELECT DISTINCT EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, NEWID() AS ChangeHistoryGroupingGUID + FROM [fp].[Staffing] fs + WHERE BudgetConfigID = @BudgetConfigID + OPTION(RECOMPILE) + END + + UPDATE fs + SET fs.ChangeHistoryGroupingGUID = dim.ChangeHistoryGroupingGUID + FROM [fp].[Staffing] fs + INNER JOIN #dimensionality dim ON + fs.EntityID = dim.EntityID + AND fs.DepartmentID = dim.DepartmentID + AND fs.JobCodeID = dim.JobCodeID + AND fs.PayCodeGroupID = dim.PayCodeGroupID + AND fs.ProductiveClassID = dim.ProductiveClassID + AND fs.EmployeeID = dim.EmployeeID + WHERE fs.BudgetConfigID = @BudgetConfigID + AND fs.ChangeHistoryGroupingGUID = '00000000-0000-0000-0000-000000000000' + AND fs.VariabilityID = 2 -- We only need to use this for variable records, fixed doesn't use it + +END +GO + + +--------------------------------------------- + +-- fp.procPopulateFactStaffingVariability_PayCodeGroup +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-04-29 MY JAZZ-28395 Cache Variability Percentage on FactStaffing +** 2 2022-08-16 MY JAZZ-40590 Exclude Dollars Only from Variability +** 3 2022-09-20 MY JAZZ-42870 Reset Data before applying variability +** 4 2022-10-12 NST JAZZ-35951 Always set Varaiability to 1 for new employees addded from Add Wizard +** 5 2022-11-10 MY JAZZ-35951 Fix issue for Employeee where it's getting set by the job code +** 6 2023-09-20 BK JAZZ-60973 Update for new data structure +** 7 2024-01-30 BK JAZZ-63880 Update JobCodeID and PayCodeID from smallint to int +** 8 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config +*************************************************************/ +CREATE PROCEDURE [fp].[procPopulateFactStaffingVariability_PayCodeGroup] + @EntityGroupConfigGUID UNIQUEIDENTIFIER, + @EntityGroupConfigID INT, + @FiscalYearID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 + AS + BEGIN + + SET NOCOUNT ON; + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#staffingDim') IS NOT NULL DROP TABLE #staffingDim + IF OBJECT_ID('tempdb..#variability') IS NOT NULL DROP TABLE #variability + IF OBJECT_ID('tempdb..#providerVariability') IS NOT NULL DROP TABLE #providerVariability + IF OBJECT_ID('tempdb..#staffingVariability') IS NOT NULL DROP TABLE #staffingVariability + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fp.Staffing + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + DECLARE @BudgetConfigID INT + SELECT @BudgetConfigID = BudgetConfigID + FROM fp.EntityGroupConfig egc + INNER JOIN fp.BudgetConfig b on egc.BudgetConfigGUID = b.BudgetConfigGUID + WHERE egc.EntityGroupConfigGUID = @EntityGroupConfigGUID + + DECLARE @IsForceDollarsOnlyToFixedFlag BIT = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting WHERE Name = 'Force Dollars Only to be Fixed' AND BudgetConfigID = @BudgetConfigID), 0) + + DECLARE @IsProviderPlanningEnabled BIT; + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID; + + DECLARE @StaffingSubsectionID INT = (SELECT SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Staffing'); + DECLARE @ProviderSubsectionID INT = (SELECT SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Provider'); + + CREATE TABLE #staffingVariability (EntityGroupConfigGUID UNIQUEIDENTIFIER, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, ProviderLineItemID INT, EmployeeID INT, FixedPercentage DECIMAL(38, 6)) + + /* + NOTE ABOUT JAZZ-35951 + ----------------------------- + We now store variability at the Employee level, this is to allow cases where a Department/Job Code combination is set to variable, however + it has employee budgeting enabled and they add an employee to it. This would add the employee, but we want it to be 100% Fixed. + + Employees in Employee Budgeting are always 100% Fixed. This is why we are setting EmployeeID = 0, essentially all rows where EmployeeID > 0, it should + always have a Fixed Percentage of 100%. Anything that is variable is going to have EmployeeID = 0. + */ + + ------------------------------------------------------------------------------------------- + -- Patient Activity + ------------------------------------------------------------------------------------------- + IF EXISTS(SELECT 1 FROM [fp].[EntityGroupConfig] WHERE IsPatientActivityFlexingForStaffing = 1 AND EntityGroupConfigGUID = @EntityGroupConfigGUID ) + BEGIN + + INSERT INTO #staffingVariability (EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, EmployeeID, FixedPercentage) + SELECT + a.EntityGroupConfigGUID, + a.DepartmentID, + a.JobCodeID, + a.PayCodeGroupID, + 0 AS ProviderLineItemID, + 0 AS EmployeeID, + a.FixedPercentage + FROM ( + SELECT + fp.EntityGroupConfigGUID, + fp.DepartmentID, + fp.JobCodeID, + fp.PayCodeGroupID, + CASE + WHEN TotalCost = 0 THEN 0 + WHEN (TotalFixedDirectCost/TotalCost) > .9999 THEN 1.0 + ELSE (TotalFixedDirectCost/TotalCost) + END AS [FixedPercentage], + COALESCE(conovr.FlexMethodID, fp.FlexMethodID) as [FlexMethodID] + FROM ( + SELECT + ec.EntityGroupConfigGuid, + pay.DepartmentID, + pay.OriginalJobCodeID as JobCodeID, + pc.PayCodeGroupID, + fc.FlexMethodID, + SUM(pay.FixedDirectUnitCost * pay.Volume) as TotalFixedDirectCost, + SUM(pay.TotalCost) as TotalCost + FROM + [dss].[FactCostingOutDetailPayroll] pay + INNER JOIN [fw].[DimPayCode] pc on pay.OriginalPayCodeID = pc.PayCodeID + INNER JOIN [dss].[CostingResult] cr on pay.CostingResultID = cr.CostingResultID + INNER JOIN [fp].[EntityGroupConfig] ec on cr.CostingConfigGuid = ec.CostingConfigGUID + INNER JOIN [fp].[StaffingExpenseFlexingConfig] fc ON fc.EntityGroupConfigGUID = ec.EntityGroupConfigGUID AND fc.DepartmentID = pay.DepartmentID + INNER JOIN fw.DimPayCodeGroup pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = fc.DepartmentID + WHERE + pay.CostingResultID in (select max(cr2.CostingResultID) from [dss].[CostingResult] cr2 where cr2.CostingConfigGuid = ec.CostingConfigGuid and cr2.IsActivityBasedDetail = 1 and cr2.IsMarkedForDeletion = 0 and cr2.IsFailure = 0) + AND pay.TimeClassID = ec.CostingConfigTimeClassID + AND ec.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND (@IsForceDollarsOnlyToFixedFlag = 0 OR pcg.ProductiveClassID != 4) -- 4 = Dollars Only; + GROUP BY + ec.EntityGroupConfigGuid, pay.DepartmentID, pay.OriginalJobCodeID, pc.PayCodeGroupID, pay.FiscalYearID, fc.FlexMethodID + ) fp + LEFT JOIN [fp].[StaffingFlexingOverrideConfig] conovr + ON fp.EntityGroupConfigGuid = conovr.EntityGroupConfigGuid + AND fp.DepartmentID = conovr.DepartmentID + AND fp.JobCodeID = conovr.JobCodeID + ) a + WHERE + a.FlexMethodID = 2 + AND FixedPercentage < 1; + END + + -- Get distinct dimensionality from staffing + SELECT DISTINCT + fs.DepartmentID, + JobCodeID, + fs.PayCodeGroupID, + fs.ProviderLineItemID, + fs.SubsectionID, + fs.EmployeeID, + fs.IsNew + INTO #staffingDim + FROM [fp].[Staffing] fs + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = fs.DepartmentID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.VariabilityID = 2 -- limit to variability = 2 only to make query faster, all unit types should be there but we only need Dept/JobCode/PayCode/ProviderLineItem + AND (@IsForceDollarsOnlyToFixedFlag = 0 OR fs.ProductiveClassID != 4) -- 4 = Dollars Only; + + ------------------------------------------------------------------------------------------- + -- Regular Staffing Variability + ------------------------------------------------------------------------------------------- + SELECT + a.DepartmentID, + a.JobCodeID, + fs.PayCodeGroupID, + a.FixedPercentage, + 0 as ProviderLineItemID, + 0 AS EmployeeID + INTO #variability + FROM + ( + SELECT + pvc.EntityGroupConfigGUID, + COALESCE(conovr.DepartmentID, efc.DepartmentID) AS 'DepartmentID', + COALESCE(conovr.JobCodeID, pvc.JobCodeID) AS 'JobCodeID', + (1 - COALESCE(varovr.Variability, pvc.Variability)) AS 'FixedPercentage', + COALESCE(conovr.FlexMethodID, efc.FlexMethodID) AS 'FlexMethodID' + FROM + [fp].[PayrollVariabilityConfig] pvc + INNER JOIN [fp].[StaffingExpenseFlexingConfig] efc ON pvc.EntityGroupConfigGUID = efc.EntityGroupConfigGUID + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = efc.DepartmentID + LEFT JOIN [fp].[StaffingVariabilityOverrideConfig] varovr ON efc.EntityGroupConfigGUID = varovr.EntityGroupConfigGUID AND efc.DepartmentID = varovr.DepartmentID AND pvc.JobCodeID = varovr.JobCodeID + LEFT JOIN [fp].[StaffingFlexingOverrideConfig] conovr ON efc.EntityGroupConfigGUID = conovr.EntityGroupConfigGUID AND efc.DepartmentID = conovr.DepartmentID AND pvc.JobCodeID = conovr.JobCodeID + WHERE + pvc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND COALESCE(conovr.FlexMethodID, efc.FlexMethodID) = 1 + AND COALESCE(varovr.Variability, pvc.Variability) != 0 + ) a + INNER JOIN ( + SELECT DISTINCT + DepartmentID, + JobCodeID, + PayCodeGroupID + FROM #staffingDim + WHERE SubSectionID = @StaffingSubsectionID + ) fs ON fs.DepartmentID = a.DepartmentID AND fs.JobCodeID = a.JobCodeID + + ------------------------------------------------------------------------------------------- + -- Provider Staffing Variability (overrides regular Staffing Variability) + ------------------------------------------------------------------------------------------- + SELECT DISTINCT + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.ProviderLineItemID, + 0 AS EmployeeID, + CASE WHEN psc.VariabilityID = 1 THEN 1 ELSE 0 END as ProviderFixedPercentage + INTO #ProviderVariability + FROM #staffingDim fs + INNER JOIN [fp].[ProviderStaffingConfig] psc ON fs.ProviderLineItemID = psc.ProviderLineItemID + LEFT JOIN ( SELECT + COALESCE(conovr.DepartmentID, efc.DepartmentID) AS 'DepartmentID' + FROM + [fp].[PayrollVariabilityConfig] pvc + INNER JOIN [fp].[StaffingExpenseFlexingConfig] efc ON pvc.EntityGroupConfigGUID = efc.EntityGroupConfigGUID + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = efc.DepartmentID + LEFT JOIN [fp].[StaffingVariabilityOverrideConfig] varovr ON efc.EntityGroupConfigGUID = varovr.EntityGroupConfigGUID AND efc.DepartmentID = varovr.DepartmentID AND pvc.JobCodeID = varovr.JobCodeID + LEFT JOIN [fp].[StaffingFlexingOverrideConfig] conovr ON efc.EntityGroupConfigGUID = conovr.EntityGroupConfigGUID AND efc.DepartmentID = conovr.DepartmentID AND pvc.JobCodeID = conovr.JobCodeID + WHERE + pvc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND COALESCE(conovr.FlexMethodID, efc.FlexMethodID) = 6 + ) fixed ON fs.DepartmentID = fixed.DepartmentID + WHERE fs.SubSectionID = @ProviderSubsectionID AND @IsProviderPlanningEnabled = 1 AND fixed.DepartmentID IS NULL and psc.BudgetConfigID = @BudgetConfigID + + ------------------------------------------------------------------------------------------- + -- Stat Accounts + ------------------------------------------------------------------------------------------- + INSERT INTO #staffingVariability (EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeGroupID, FixedPercentage, ProviderLineItemID, EmployeeID) + SELECT + @EntityGroupConfigGUID, + s.DepartmentID, + s.JobCodeID AS JobCodeID, + s.PayCodeGroupID AS PayCodeID, + s.FixedPercentage, + 0 as ProviderLineItemID, + 0 AS EmployeeID + FROM #variability s LEFT JOIN #ProviderVariability p ON s.DepartmentID = p.DepartmentID AND s.JobCodeID = p.JobCodeID + WHERE p.DepartmentID IS NULL AND p.JobCodeID IS NULL + + ------------------------------------------------------------------------------------------- + -- Provider Stat Accounts + ------------------------------------------------------------------------------------------- + INSERT INTO #staffingVariability (EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeGroupID, FixedPercentage, ProviderLineItemID, EmployeeID) + SELECT + @EntityGroupConfigGUID, + p.DepartmentID, + p.JobCodeID AS JobCodeID, + p.PayCodeGroupID AS PayCodeID, + p.ProviderFixedPercentage, + p.ProviderLineItemID, + 0 AS EmployeeID + FROM #ProviderVariability p + + ------------------------------------------------------------------------------------------- + -- Publish FixedVariability Percentage to Staffing + ------------------------------------------------------------------------------------------- + IF (@IsDebug = 1) + BEGIN + SELECT EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeGroupID, ProviderLineItemID, FixedPercentage FROM #staffingVariability + END ELSE BEGIN + + -- Reset the values to Fixed as we exclude things below (this is similar to deleting everything) + UPDATE pv + SET pv.FixedVariabilityPercentage = 1 + FROM [fp].[Staffing] pv + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = pv.DepartmentID + WHERE pv.EntityGroupConfigID = @EntityGroupConfigID + AND pv.FixedVariabilityPercentage != 1 + + UPDATE fs + SET fs.FixedVariabilityPercentage = varb.FixedPercentage + FROM fp.Staffing fs + INNER JOIN #staffingVariability varb ON + fs.DepartmentID = varb.DepartmentID + AND fs.JobCodeID = varb.JobCodeID + AND fs.PayCodeGroupID = varb.PayCodeGroupID + AND fs.ProviderLineItemID = varb.ProviderLineItemID + AND fs.EmployeeID = varb.EmployeeID + AND varb.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.FixedVariabilityPercentage != varb.FixedPercentage + END + + END +GO + + +--------------------------------------------- + +-- fp.procPopulateMissingWorkflowSteps +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2021-03-17 NN JAZZ-467 Remove null joins and joins on targting object +** 2 2022-07-06 BW JAZZ-37489 Prevent duplicate inserts for untargeted +*************************************************************/ +CREATE PROCEDURE fp.procPopulateMissingWorkflowSteps + @EntityGroupConfigGUID UNIQUEIDENTIFIER, + @EntityGroupConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + AS + BEGIN + SELECT DepartmentID + INTO #SourceDimensionality + FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + -- JAZZ-9178 prevent duplicate inserts + DELETE #SourceDimensionality + FROM #SourceDimensionality a + INNER JOIN [fp].[viewAPEDepartmentWorkflowStatus] b + ON b.DepartmentID = a.DepartmentId + AND b.EntityGroupConfigID = @EntityGroupConfigID + --The left join to [fp].[APEDepartmentWorkflowStatus] was missing that last clause on WorkflowStepID, + --which stopped users from adding the same department to multiple budget configs through adjustment import + IF (SELECT COUNT(*) FROM #SourceDimensionality WHERE DepartmentID IS NULL) >= 1 + BEGIN + INSERT INTO [fp].[APEDepartmentWorkflowStatus] (WorkflowStepID, DepartmentID, EnteredStepDateTimeUtc, Status) + SELECT DISTINCT aw.WorkflowStepID, dc.DepartmentID, GetUTCDate(), 0 + FROM [fp].[DepartmentConfig] dc + INNER JOIN [fp].[EntityGroupConfig] ec ON ec.EntityGroupConfigGUID = dc.EntityGroupConfigGUID + INNER JOIN [fp].[APEWorkflow] aw ON aw.EntityGroupConfigID = @EntityGroupConfigID and aw.WorkflowStepOrder = 1 + LEFT JOIN [fp].[APEDepartmentWorkflowStatus] dw ON dc.DepartmentID = dw.DepartmentID and aw.WorkflowStepID = dw.WorkflowStepID + WHERE dw.DepartmentID IS NULL + AND dc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND NOT EXISTS ( + SELECT DepartmentID + FROM [fp].[viewAPEDepartmentWorkflowStatus] + WHERE EntityGroupConfigID = @EntityGroupConfigID + ) + + END ELSE BEGIN + INSERT INTO [fp].[APEDepartmentWorkflowStatus] (WorkflowStepID, DepartmentID, EnteredStepDateTimeUtc, Status) + SELECT DISTINCT aw.WorkflowStepID, dc.DepartmentID, GetUTCDate(), 0 + FROM [fp].[DepartmentConfig] dc + INNER JOIN [fp].[EntityGroupConfig] ec ON ec.EntityGroupConfigGUID = dc.EntityGroupConfigGUID + INNER JOIN [fp].[APEWorkflow] aw ON aw.EntityGroupConfigID = @EntityGroupConfigID and aw.WorkflowStepOrder = 1 + INNER JOIN #SourceDimensionality SD ON SD.DepartmentID = dc.DepartmentID + LEFT JOIN [fp].[APEDepartmentWorkflowStatus] dw ON dc.DepartmentID = dw.DepartmentID and aw.WorkflowStepID = dw.WorkflowStepID + WHERE dw.DepartmentID IS NULL + AND dc.EntityGroupConfigGUID = @EntityGroupConfigGUID + END + END +GO + + +--------------------------------------------- + +-- fp.procPopulateReportChargesNotCrosswalkedData +CREATE PROCEDURE [fp].[procPopulateReportChargesNotCrosswalkedData] + @EntityGroupConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 05-16-2023 MY JAZZ-54654 Initial Creation + ** 2 07-11-2023 MY JAZZ-57364 Convert to use EntityGroupConfigID + ** 3 08-05-2024 MD JAZZ-70711 Update to only load projection months NOT loaded + ** 4 09-27-2024 MY JAZZ-75442 Add Check for IsRecordDeleted + *************************************************************/ + + EXEC [dbo].[procSysDropTempTable] '#chargeDimensionality' + EXEC [dbo].[procSysDropTempTable] '#crosswalkDimensionality' + EXEC [dbo].[procSysDropTempTable] '#missingDimensionality' + EXEC [dbo].[procSysDropTempTable] '#missingDollars' + EXEC [dbo].[procSysDropTempTable] '#filteringTable' + + DECLARE @MonthsLoaded INT = (SELECT MonthsLoaded FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID WHERE egc.EntityGroupConfigID = @EntityGroupConfigID) + + CREATE TABLE #FilteringTable (DepartmentID INT, INDEX ix_1 NONCLUSTERED (DepartmentID)) + + -- Get Targeting + IF (SELECT COUNT(*) FROM @SourceDimensionality) = 0 BEGIN + INSERT INTO #filteringTable (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fp.ChargeVolume + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + ELSE BEGIN + INSERT INTO #filteringTable (DepartmentID) + SELECT DepartmentID + FROM @SourceDimensionality + END + + -- First we need to determine what is in Charge Volume that is missing from the crosswalk + SELECT DISTINCT cv.DepartmentID, ChargeCodeID, PatientClassID + INTO #chargeDimensionality + FROM fp.ChargeVolume cv + INNER JOIN #filteringTable ft ON cv.DepartmentID = ft.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID + + SELECT DISTINCT cv.DepartmentID, ChargeCodeID, PatientClassID + INTO #crosswalkDimensionality + FROM fp.ChargeToGeneralLedgerCrosswalkConfiguration cv + INNER JOIN #filteringTable ft ON cv.DepartmentID = ft.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND cv.IsRecordDeleted = 0 + + SELECT DISTINCT chrg.DepartmentID, chrg.ChargeCodeID, chrg.PatientClassID + INTO #missingDimensionality + FROM #chargeDimensionality chrg + LEFT JOIN #crosswalkDimensionality walk ON chrg.DepartmentID = walk.DepartmentID + AND chrg.ChargeCodeID = walk.ChargeCodeID + AND chrg.PatientClassID = walk.PatientClassID + WHERE walk.DepartmentID IS NULL + + IF @IsDebug = 1 + BEGIN + SELECT '#chargeDimensionality' AS #chargeDimensionality, * FROM #chargeDimensionality + SELECT '#crosswalkDimensionality' AS #crosswalkDimensionality, * FROM #crosswalkDimensionality + SELECT '#missingDimensionality' AS #missingDimensionality, * FROM #missingDimensionality + END + + -- We no longer need these as we can just use what is missing + EXEC [dbo].[procSysDropTempTable] '#chargeDimensionality' + EXEC [dbo].[procSysDropTempTable] '#crosswalkDimensionality' + + -- Now that we have the missing dimensionality, we need to get the total values for each. + SELECT + cv.DepartmentID, + cv.PatientClassID, + cv.ChargeCodeID, + cv.BudgetConfigID, + cv.EntityGroupConfigID, + SUM( + CASE + WHEN @MonthsLoaded = 1 THEN cv.ProjectionDollarsAdjusted02 + cv.ProjectionDollarsAdjusted03 + cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 2 THEN cv.ProjectionDollarsAdjusted03 + cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 3 THEN cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 4 THEN cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 5 THEN cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 6 THEN cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 7 THEN cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 8 THEN cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 9 THEN cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 10 THEN cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 11 THEN cv.ProjectionDollarsAdjusted12 + ELSE 0 END + ) AS ProjectionDollarsAdjustedTotal, + SUM(cv.TargetDollarsAdjustedTotal) AS TargetDollarsAdjustedTotal, + SUM(cv.BudgetDollarsAdjustedTotal) AS BudgetDollarsAdjustedTotal + INTO #missingDollars + FROM fp.ChargeVolume cv + INNER JOIN #missingDimensionality miss ON cv.DepartmentID = miss.DepartmentID + AND cv.PatientClassID = miss.PatientClassID + AND cv.ChargeCodeID = miss.ChargeCodeID + WHERE cv.EntityGroupConfigID = @EntityGroupConfigID + AND ( + cv.ProjectionDollarsAdjustedTotal > 0 OR + cv.TargetDollarsAdjustedTotal > 0 OR + cv.BudgetDollarsAdjustedTotal > 0 + ) + GROUP BY cv.DepartmentID, + cv.PatientClassID, + cv.ChargeCodeID, + cv.BudgetConfigID, + cv.EntityGroupConfigID + + EXEC [dbo].[procSysDropTempTable] '#missingDimensionality' + + IF @IsDebug = 1 + BEGIN + SELECT '#missingDollars' AS #missingDollars, * FROM #missingDollars + END ELSE + BEGIN + + ;WITH TGT AS + ( + SELECT FRS.DepartmentID, PatientClassID, ChargeCodeID, BudgetConfigID, EntityGroupConfigID, ProjectionDollarsAdjustedTotal, TargetDollarsAdjustedTotal, BudgetDollarsAdjustedTotal + FROM fp.FactReportChargesNotCrosswalkedData FRS + INNER JOIN #filteringTable ft ON FRS.DepartmentID = ft.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID + ) + MERGE TGT AS target + USING #missingDollars AS SOURCE + ON ( + target.DepartmentID = source.DepartmentID + AND target.PatientClassID = source.PatientClassID + AND target.ChargeCodeID = source.ChargeCodeID + AND target.BudgetConfigID = source.BudgetConfigID + AND target.EntityGroupConfigID = source.EntityGroupConfigID + ) + WHEN MATCHED AND + ( + target.BudgetDollarsAdjustedTotal <> source.BudgetDollarsAdjustedTotal + OR target.ProjectionDollarsAdjustedTotal <> source.ProjectionDollarsAdjustedTotal + OR target.TargetDollarsAdjustedTotal <> source.TargetDollarsAdjustedTotal + ) + THEN + UPDATE SET + target.BudgetDollarsAdjustedTotal = ISNULL(source.BudgetDollarsAdjustedTotal, 0), + target.ProjectionDollarsAdjustedTotal = ISNULL(source.ProjectionDollarsAdjustedTotal, 0), + target.TargetDollarsAdjustedTotal = ISNULL(source.TargetDollarsAdjustedTotal, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT (DepartmentID, PatientClassID, ChargeCodeID, BudgetConfigID, EntityGroupConfigID, ProjectionDollarsAdjustedTotal, TargetDollarsAdjustedTotal, BudgetDollarsAdjustedTotal) + VALUES ( + source.DepartmentID, + source.PatientClassID, + source.ChargeCodeID, + source.BudgetConfigID, + source.EntityGroupConfigID, + ISNULL(source.ProjectionDollarsAdjustedTotal, 0), + ISNULL(source.TargetDollarsAdjustedTotal, 0), + ISNULL(source.BudgetDollarsAdjustedTotal, 0) + ) + WHEN NOT MATCHED BY SOURCE + THEN DELETE; + + END + +END +GO + + +--------------------------------------------- + +-- fp.procPopulateReportChargesNotCrosswalkedData_WithPayorGroup +CREATE PROCEDURE [fp].[procPopulateReportChargesNotCrosswalkedData_WithPayorGroup] + @EntityGroupConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-07-11 MY JAZZ-57364 Initial Creation + ** 2 2024-04-11 MY JAZZ-70660 Update to leverage additional dimensions in mix table + ** 3 2024-08-05 MD JAZZ-70711 Update to only load projection months NOT loaded + ** 4 2024-09-12 MY JAZZ-75442 Filter out the Soft Deleted Records + *************************************************************/ + + EXEC [dbo].[procSysDropTempTable] '#chargeDimensionality' + EXEC [dbo].[procSysDropTempTable] '#crosswalkDimensionality' + EXEC [dbo].[procSysDropTempTable] '#missingDimensionality' + EXEC [dbo].[procSysDropTempTable] '#missingDollars' + EXEC [dbo].[procSysDropTempTable] '#filteringTable' + EXEC [dbo].[procSysDropTempTable] '#chargeDimensionality_WithPayorMix' + + CREATE TABLE #FilteringTable (DepartmentID INT, INDEX ix_1 NONCLUSTERED (DepartmentID)) + + DECLARE @BudgetConfigID INT = (SELECT BudgetConfigID FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID WHERE egc.EntityGroupConfigID = @EntityGroupConfigID) + DECLARE @MonthsLoaded INT = (SELECT MonthsLoaded FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID WHERE egc.EntityGroupConfigID = @EntityGroupConfigID) + DECLARE @IsServiceLineInMix INT = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting WHERE BudgetConfigID = @BudgetConfigID AND Name = 'Enable ServiceLine level mix for Charge to GL Crosswalk'), 0) + + -- JAZZ-70660: Adding Additional Dimensionality into the SLE to Charge payor mix calc + DECLARE @IsAdditionalDimensionalityEnabled BIT = ISNULL((SELECT Value + FROM fp.viewBudgetConfigSetting setting + INNER JOIN fp.BudgetConfig bc ON setting.BudgetConfigID = bc.BudgetConfigID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE egc.EntityGroupConfigID = @EntityGroupConfigID + AND setting.Name = 'Enable Charge to General Ledger Crosswalk to Use Detailed Mix'), 0) + + -- Get Targeting + IF (SELECT COUNT(*) FROM @SourceDimensionality) = 0 BEGIN + INSERT INTO #filteringTable (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fp.ChargeVolume + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + ELSE BEGIN + INSERT INTO #filteringTable (DepartmentID) + SELECT DepartmentID + FROM @SourceDimensionality + END + + CREATE TABLE #missingDollars ( + DepartmentID INT NOT NULL, + PatientClassID INT NOT NULL, + ChargeCodeID INT NOT NULL, + BudgetConfigID INT NOT NULL, + PayorGroupID INT NOT NULL, + EntityGroupConfigID INT NOT NULL, + ProjectionDollarsAdjustedTotal DECIMAL(36, 8) NOT NULL, + TargetDollarsAdjustedTotal DECIMAL(36, 8) NOT NULL, + BudgetDollarsAdjustedTotal DECIMAL(36, 8) NOT NULL + ) + + -- Clear out report data since the merge wasn't always cleaning it up. + DELETE rpt + FROM fp.FactReportChargesNotCrosswalkedData rpt + INNER JOIN #filteringTable ft ON rpt.DepartmentID = ft.DepartmentID + WHERE rpt.EntityGroupConfigID = @EntityGroupConfigID + + -- DBA's recommendation + UPDATE STATISTICS #filteringTable WITH FULLSCAN + + IF (@IsAdditionalDimensionalityEnabled = 0) + BEGIN + + -- First we need to determine what is in Charge Volume that is missing from the crosswalk + SELECT DISTINCT + cv.BudgetConfigID, cv.EntityGroupConfigID, cv.DepartmentID, cv.ServiceEntityID, + cv.ServiceLineID, ChargeCodeID, PatientClassID, + --JAZZ-70711 - We only want to display months not loaded + CASE + WHEN @MonthsLoaded = 1 THEN cv.ProjectionDollarsAdjusted02 + cv.ProjectionDollarsAdjusted03 + cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 2 THEN cv.ProjectionDollarsAdjusted03 + cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 3 THEN cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 4 THEN cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 5 THEN cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 6 THEN cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 7 THEN cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 8 THEN cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 9 THEN cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 10 THEN cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 11 THEN cv.ProjectionDollarsAdjusted12 + ELSE 0 + END AS ProjectionDollarsAdjustedTotal, + TargetDollarsAdjustedTotal, BudgetDollarsAdjustedTotal + INTO #chargeDimensionality + FROM fp.ChargeVolume cv + INNER JOIN #filteringTable ft ON cv.DepartmentID = ft.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID + + -- Right now we only have 1 mix for Budget that covers Target and Budget, that will not always be the case. + SELECT DISTINCT cv.BudgetConfigID, cv.EntityGroupConfigID, cv.DepartmentID, cv.ChargeCodeID, cv.PatientClassID, mix.PayorGroupID, mix.BudgetMixPercentage, mix.ProjectionMixPercentage, ProjectionDollarsAdjustedTotal, TargetDollarsAdjustedTotal, BudgetDollarsAdjustedTotal + INTO #chargeDimensionality_WithPayorMix + FROM #chargeDimensionality cv WITH (READUNCOMMITTED) + INNER JOIN fp.viewServiceLineEncounterPayorGroupMix_Pivoted mix WITH (READUNCOMMITTED) on + mix.PatientClassID = cv.PatientClassID + AND mix.EntityID = cv.ServiceEntityID + AND (@IsServiceLineInMix = 0 OR mix.ServiceLineID = cv.ServiceLineID) + WHERE mix.EntityGroupConfigID = @EntityGroupConfigID + + SELECT DISTINCT cv.DepartmentID, ChargeCodeID, PatientClassID, PayorGroupID + INTO #crosswalkDimensionality + FROM fp.ChargeToGeneralLedgerCrosswalkConfiguration cv + INNER JOIN #filteringTable ft ON cv.DepartmentID = ft.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND cv.IsRecordDeleted = 0 + + SELECT DISTINCT chrg.BudgetConfigID, chrg.EntityGroupConfigID, chrg.DepartmentID, chrg.ChargeCodeID, chrg.PatientClassID, chrg.PayorGroupID, chrg.BudgetMixPercentage, chrg.ProjectionMixPercentage, ProjectionDollarsAdjustedTotal, TargetDollarsAdjustedTotal, BudgetDollarsAdjustedTotal + INTO #missingDimensionality + FROM #chargeDimensionality_WithPayorMix chrg + LEFT JOIN #crosswalkDimensionality walk ON chrg.DepartmentID = walk.DepartmentID + AND chrg.ChargeCodeID = walk.ChargeCodeID + AND chrg.PatientClassID = walk.PatientClassID + AND chrg.PayorGroupID = walk.PayorGroupID + WHERE walk.DepartmentID IS NULL + + IF @IsDebug = 1 + BEGIN + SELECT '#chargeDimensionality' AS #chargeDimensionality, * FROM #chargeDimensionality + SELECT '#chargeDimensionality_WithPayorMix' AS #chargeDimensionality_WithPayorMix, * FROM #chargeDimensionality_WithPayorMix + SELECT '#crosswalkDimensionality' AS #crosswalkDimensionality, * FROM #crosswalkDimensionality + SELECT '#missingDimensionality' AS #missingDimensionality, * FROM #missingDimensionality + END + + -- We no longer need these as we can just use what is missing + EXEC [dbo].[procSysDropTempTable] '#chargeDimensionality' + EXEC [dbo].[procSysDropTempTable] '#crosswalkDimensionality' + + -- Now that we have the missing dimensionality, we need to get the total values for each. + INSERT INTO #missingDollars (DepartmentID, + PatientClassID, + ChargeCodeID, + BudgetConfigID, + PayorGroupID, + EntityGroupConfigID, + ProjectionDollarsAdjustedTotal, + TargetDollarsAdjustedTotal, + BudgetDollarsAdjustedTotal) + SELECT + DepartmentID, + PatientClassID, + ChargeCodeID, + BudgetConfigID, + PayorGroupID, + EntityGroupConfigID, + SUM(ProjectionDollarsAdjustedTotal * ProjectionMixPercentage) AS ProjectionDollarsAdjustedTotal, + SUM(TargetDollarsAdjustedTotal * BudgetMixPercentage) AS TargetDollarsAdjustedTotal, + SUM(BudgetDollarsAdjustedTotal * BudgetMixPercentage) AS BudgetDollarsAdjustedTotal + FROM #missingDimensionality + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND ( + ProjectionDollarsAdjustedTotal != 0 OR + TargetDollarsAdjustedTotal != 0 OR + BudgetDollarsAdjustedTotal != 0 + ) + GROUP BY DepartmentID, + PatientClassID, + ChargeCodeID, + BudgetConfigID, + PayorGroupID, + EntityGroupConfigID + + EXEC [dbo].[procSysDropTempTable] '#missingDimensionality' + + END ELSE BEGIN + + INSERT INTO #missingDollars ( + DepartmentID, + PatientClassID, + ChargeCodeID, + BudgetConfigID, + PayorGroupID, + EntityGroupConfigID, + ProjectionDollarsAdjustedTotal, + TargetDollarsAdjustedTotal, + BudgetDollarsAdjustedTotal) + SELECT cv.DepartmentID, cv.PatientClassID, cv.ChargeCodeID, cv.BudgetConfigID, mix.PayorGroupID, cv.EntityGroupConfigID, + SUM( + CASE + WHEN @MonthsLoaded = 1 THEN cv.ProjectionDollarsAdjusted02 + cv.ProjectionDollarsAdjusted03 + cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 2 THEN cv.ProjectionDollarsAdjusted03 + cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 3 THEN cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 4 THEN cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 5 THEN cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 6 THEN cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 7 THEN cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 8 THEN cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 9 THEN cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 10 THEN cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 11 THEN cv.ProjectionDollarsAdjusted12 + ELSE 0 END * ProjectionMixPercentage + ) AS ProjectionTotal, + SUM(TargetDollarsAdjustedTotal * mix.BudgetMixPercentage) AS TargetTotal, SUM(cv.BudgetDollarsAdjustedTotal * mix.BudgetMixPercentage) AS BudgetTotal + FROM fp.ChargeVolume cv + INNER JOIN fp.ServiceLineEncounterToChargePayorMix mix on + mix.BudgetConfigID = cv.BudgetConfigID + AND mix.EntityGroupConfigID = cv.EntityGroupConfigID + AND mix.PatientClassID = cv.PatientClassID + AND mix.EntityID = cv.ServiceEntityID + AND mix.ServiceLineID = cv.ServiceLineID + AND mix.AgeCohortID = cv.AgeCohortID + AND mix.MedicalSurgicalID = cv.MedicalSurgicalID + AND mix.MSDRGID = cv.MSDRGID + AND mix.CPTID = cv.PrimaryCPTID + AND mix.ProviderID = cv.ServiceProviderID + INNER JOIN #filteringTable ft ON cv.DepartmentID = ft.DepartmentID + INNER JOIN fp.EntityGroupConfig egc ON cv.EntityGroupConfigID = egc.EntityGroupConfigID + LEFT JOIN (SELECT DISTINCT BudgetConfigID, EntityGroupConfigID, DepartmentID, ChargeCodeID, PatientClassID, PayorGroupID FROM fp.ChargeToGeneralLedgerCrosswalkConfiguration WHERE IsRecordDeleted = 0) config ON + cv.BudgetConfigID = config.BudgetConfigID + AND cv.EntityGroupConfigID = config.EntityGroupConfigID + AND cv.DepartmentID = config.DepartmentID + AND cv.ChargeCodeID = config.ChargeCodeID + AND cv.PatientClassID = config.PatientClassID + AND mix.PayorGroupID = config.PayorGroupID + WHERE 1 = 1 + AND egc.IsPayorGroupUsedForCrosswalk = 1 + AND cv.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID IS NULL + GROUP BY cv.DepartmentID, cv.PatientClassID, cv.ChargeCodeID, cv.BudgetConfigID, mix.PayorGroupID, + cv.EntityGroupConfigID + HAVING (SUM( + CASE + WHEN @MonthsLoaded = 1 THEN cv.ProjectionDollarsAdjusted02 + cv.ProjectionDollarsAdjusted03 + cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 2 THEN cv.ProjectionDollarsAdjusted03 + cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 3 THEN cv.ProjectionDollarsAdjusted04 + cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 4 THEN cv.ProjectionDollarsAdjusted05 + cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 5 THEN cv.ProjectionDollarsAdjusted06 + cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 6 THEN cv.ProjectionDollarsAdjusted07 + cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 7 THEN cv.ProjectionDollarsAdjusted08 + cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 8 THEN cv.ProjectionDollarsAdjusted09 + cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 9 THEN cv.ProjectionDollarsAdjusted10 + cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 10 THEN cv.ProjectionDollarsAdjusted11 + cv.ProjectionDollarsAdjusted12 + WHEN @MonthsLoaded = 11 THEN cv.ProjectionDollarsAdjusted12 + ELSE 0 END * ProjectionMixPercentage + ) != 0 + OR SUM(cv.TargetDollarsAdjustedTotal * mix.BudgetMixPercentage) != 0 + OR SUM(cv.BudgetDollarsAdjustedTotal * mix.BudgetMixPercentage) != 0) + + END + + IF @IsDebug = 1 + BEGIN + SELECT '#missingDollars' AS #missingDollars, * FROM #missingDollars + END ELSE + BEGIN + + ;WITH TGT AS + ( + SELECT FRS.DepartmentID, PatientClassID, ChargeCodeID, BudgetConfigID, EntityGroupConfigID, PayorGroupID, ProjectionDollarsAdjustedTotal, TargetDollarsAdjustedTotal, BudgetDollarsAdjustedTotal + FROM fp.FactReportChargesNotCrosswalkedData FRS + INNER JOIN #filteringTable ft ON FRS.DepartmentID = ft.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID + ) + MERGE TGT AS target + USING #missingDollars AS SOURCE + ON ( + target.BudgetConfigID = source.BudgetConfigID + AND target.EntityGroupConfigID = source.EntityGroupConfigID + AND target.DepartmentID = source.DepartmentID + AND target.PatientClassID = source.PatientClassID + AND target.ChargeCodeID = source.ChargeCodeID + AND target.PayorGroupID = source.PayorGroupID + ) + WHEN MATCHED AND + ( + target.BudgetDollarsAdjustedTotal <> source.BudgetDollarsAdjustedTotal + OR target.ProjectionDollarsAdjustedTotal <> source.ProjectionDollarsAdjustedTotal + OR target.TargetDollarsAdjustedTotal <> source.TargetDollarsAdjustedTotal + ) + THEN + UPDATE SET + target.BudgetDollarsAdjustedTotal = ISNULL(source.BudgetDollarsAdjustedTotal, 0), + target.ProjectionDollarsAdjustedTotal = ISNULL(source.ProjectionDollarsAdjustedTotal, 0), + target.TargetDollarsAdjustedTotal = ISNULL(source.TargetDollarsAdjustedTotal, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT (DepartmentID, PatientClassID, ChargeCodeID, BudgetConfigID, PayorGroupID, EntityGroupConfigID, ProjectionDollarsAdjustedTotal, TargetDollarsAdjustedTotal, BudgetDollarsAdjustedTotal) + VALUES ( + source.DepartmentID, + source.PatientClassID, + source.ChargeCodeID, + source.BudgetConfigID, + source.PayorGroupID, + source.EntityGroupConfigID, + ISNULL(source.ProjectionDollarsAdjustedTotal, 0), + ISNULL(source.TargetDollarsAdjustedTotal, 0), + ISNULL(source.BudgetDollarsAdjustedTotal, 0) + ) + WHEN NOT MATCHED BY SOURCE + THEN DELETE; + + END + +END +GO + + +--------------------------------------------- + +-- fp.procPopulateReportFactChargeVolume_Dollars_Budget +/********************************************************************* +** Change History +********************************************************************** +** CID Date Author WI Description +** 1 2020-03-04 MY JAZZ-16292 Initial +** 2 2020-02-14 MY JAZZ-33542 Add Targeting +** 3 2023-03-21 MY JAZZ-49993 Update reporting to support new data model +** 4 2023-06-12 MY JAZZ-54952 Update to new column names +*********************************************************************/ +CREATE PROCEDURE fp.procPopulateReportFactChargeVolume_Dollars_Budget ( + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +) +WITH RECOMPILE +AS +BEGIN + + EXEC [dbo].[procSysDropTempTable] '#source' + EXEC [dbo].[procSysDropTempTable] '#recordsUpdated' + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + + DECLARE @BudgetYear INT; + SET @BudgetYear = (SELECT FiscalYearID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID); + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + + CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT); + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED) + WHERE BudgetConfigID = @BudgetConfigID + END + + CREATE TABLE #source ( + ChargeVolumeID INT, + BudgetConfigID INT, + EntityID INT, + DepartmentID INT, + PatientClassID INT, + ChargeCodeID INT, + ServiceLineID INT, + AgeCohortID INT, + MedicalSurgicalID INT, + ServiceEntityID INT, + MSDRGID INT, + UBRevCodeID INT, + PrimaryCPTID INT, + ServiceProviderID INT, + ServiceProviderSpecialtyID INT, + PerformingProviderID INT, + PerformingProviderSpecialtyID INT, + BillingCPTID INT, + UnitTypeID INT, + TimeClassID INT, + FiscalMonthID INT, + FiscalYearID INT, + OriginalValue01 DECIMAL(19, 8), + OriginalValue02 DECIMAL(19, 8), + OriginalValue03 DECIMAL(19, 8), + OriginalValue04 DECIMAL(19, 8), + OriginalValue05 DECIMAL(19, 8), + OriginalValue06 DECIMAL(19, 8), + OriginalValue07 DECIMAL(19, 8), + OriginalValue08 DECIMAL(19, 8), + OriginalValue09 DECIMAL(19, 8), + OriginalValue10 DECIMAL(19, 8), + OriginalValue11 DECIMAL(19, 8), + OriginalValue12 DECIMAL(19, 8), + OriginalValueTotal DECIMAL(19, 8), + Value01 DECIMAL(19, 8), + Value02 DECIMAL(19, 8), + Value03 DECIMAL(19, 8), + Value04 DECIMAL(19, 8), + Value05 DECIMAL(19, 8), + Value06 DECIMAL(19, 8), + Value07 DECIMAL(19, 8), + Value08 DECIMAL(19, 8), + Value09 DECIMAL(19, 8), + Value10 DECIMAL(19, 8), + Value11 DECIMAL(19, 8), + Value12 DECIMAL(19, 8), + ValueTotal DECIMAL(19, 8), + ManagerValue01 DECIMAL(19, 8), + ManagerValue02 DECIMAL(19, 8), + ManagerValue03 DECIMAL(19, 8), + ManagerValue04 DECIMAL(19, 8), + ManagerValue05 DECIMAL(19, 8), + ManagerValue06 DECIMAL(19, 8), + ManagerValue07 DECIMAL(19, 8), + ManagerValue08 DECIMAL(19, 8), + ManagerValue09 DECIMAL(19, 8), + ManagerValue10 DECIMAL(19, 8), + ManagerValue11 DECIMAL(19, 8), + ManagerValue12 DECIMAL(19, 8), + ManagerValueTotal DECIMAL(19, 8) + ) + + -- Budget + INSERT INTO #source (ChargeVolumeID, BudgetConfigID, EntityID, DepartmentID, PatientClassID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, ServiceEntityID, + MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, PerformingProviderSpecialtyID, + BillingCPTID, UnitTypeID, TimeClassID, FiscalYearID, + OriginalValue01, OriginalValue02, OriginalValue03, OriginalValue04, OriginalValue05, OriginalValue06, OriginalValue07, OriginalValue08, OriginalValue09, OriginalValue10, OriginalValue11, OriginalValue12, OriginalValueTotal, + Value01, Value02, Value03, Value04, Value05, Value06, Value07, Value08, Value09, Value10, Value11, Value12, ValueTotal, + ManagerValue01, ManagerValue02, ManagerValue03, ManagerValue04, ManagerValue05, ManagerValue06, ManagerValue07, ManagerValue08, ManagerValue09, ManagerValue10, ManagerValue11, ManagerValue12, ManagerValueTotal) + SELECT fcv.ChargeVolumeID, fcv.BudgetConfigID, fcv.EntityID, fcv.DepartmentID, fcv.PatientClassID, fcv.ChargeCodeID, fcv.ServiceLineID, fcv.AgeCohortID, fcv.MedicalSurgicalID, fcv.ServiceEntityID, + fcv.MSDRGID, fcv.UBRevCodeID, fcv.PrimaryCPTID, fcv.ServiceProviderID, fcv.ServiceProviderSpecialtyID, fcv.PerformingProviderID, fcv.PerformingProviderSpecialtyID, + fcv.BillingCPTID, 34 AS UnitTypeID, 2 AS TimeClassID, @BudgetYear AS FiscalYearID, + fcv.InitialBudgetDollars01, fcv.InitialBudgetDollars02, fcv.InitialBudgetDollars03, fcv.InitialBudgetDollars04, fcv.InitialBudgetDollars05, fcv.InitialBudgetDollars06, fcv.InitialBudgetDollars07, fcv.InitialBudgetDollars08, fcv.InitialBudgetDollars09, fcv.InitialBudgetDollars10, fcv.InitialBudgetDollars11, fcv.InitialBudgetDollars12, fcv.InitialBudgetDollarsTotal, + fcv.TargetDollarsAdjusted01, fcv.TargetDollarsAdjusted02, fcv.TargetDollarsAdjusted03, fcv.TargetDollarsAdjusted04, fcv.TargetDollarsAdjusted05, fcv.TargetDollarsAdjusted06, fcv.TargetDollarsAdjusted07, fcv.TargetDollarsAdjusted08, fcv.TargetDollarsAdjusted09, fcv.TargetDollarsAdjusted10, fcv.TargetDollarsAdjusted11, fcv.TargetDollarsAdjusted12, fcv.TargetDollarsAdjustedTotal, + fcv.BudgetDollarsAdjusted01, fcv.BudgetDollarsAdjusted02, fcv.BudgetDollarsAdjusted03, fcv.BudgetDollarsAdjusted04, fcv.BudgetDollarsAdjusted05, fcv.BudgetDollarsAdjusted06, fcv.BudgetDollarsAdjusted07, fcv.BudgetDollarsAdjusted08, fcv.BudgetDollarsAdjusted09, fcv.BudgetDollarsAdjusted10, fcv.BudgetDollarsAdjusted11, fcv.BudgetDollarsAdjusted12, fcv.BudgetDollarsAdjustedTotal + FROM fp.ChargeVolume fcv + INNER JOIN #ChargeVolumeDepartments depts ON fcv.DepartmentID = depts.DepartmentID + WHERE fcv.BudgetConfigID = @BudgetConfigID + + CREATE CLUSTERED INDEX inx_src ON #source ( + ChargeVolumeID, + BudgetConfigID, + EntityID, + DepartmentID, + PatientClassID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + BillingCPTID, + UnitTypeID, + TimeClassID, + FiscalYearID + ) with (data_compression = page) + + ;WITH TGT AS + ( + SELECT + ChargeVolumeID, + BudgetConfigID, + EntityID, + FRS.DepartmentID, + PatientClassID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + BillingCPTID, + UnitTypeID, + InitialBudget01, + InitialBudget02, + InitialBudget03, + InitialBudget04, + InitialBudget05, + InitialBudget06, + InitialBudget07, + InitialBudget08, + InitialBudget09, + InitialBudget10, + InitialBudget11, + InitialBudget12, + InitialBudgetTotal, + Target01, + Target02, + Target03, + Target04, + Target05, + Target06, + Target07, + Target08, + Target09, + Target10, + Target11, + Target12, + TargetTotal, + Budget01, + Budget02, + Budget03, + Budget04, + Budget05, + Budget06, + Budget07, + Budget08, + Budget09, + Budget10, + Budget11, + Budget12, + BudgetTotal + FROM [fp].[FactReportChargeVolume] FRS + INNER JOIN #ChargeVolumeDepartments depts ON FRS.DepartmentID = depts.DepartmentID + WHERE FRS.BudgetConfigID = @BudgetConfigID + ) + MERGE TGT AS target + USING #source AS source + ON ( + target.ChargeVolumeID = source.ChargeVolumeID + AND target.BudgetConfigID = source.BudgetConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.PatientClassID = source.PatientClassID + AND target.ChargeCodeID = source.ChargeCodeID + AND target.ServiceLineID = source.ServiceLineID + AND target.AgeCohortID = source.AgeCohortID + AND target.MedicalSurgicalID = source.MedicalSurgicalID + AND target.ServiceEntityID = source.ServiceEntityID + AND target.MSDRGID = source.MSDRGID + AND target.UBRevCodeID = source.UBRevCodeID + AND target.PrimaryCPTID = source.PrimaryCPTID + AND target.ServiceProviderID = source.ServiceProviderID + AND target.ServiceProviderSpecialtyID = source.ServiceProviderSpecialtyID + AND target.PerformingProviderID = source.PerformingProviderID + AND target.PerformingProviderSpecialtyID = source.PerformingProviderSpecialtyID + AND target.BillingCPTID = source.BillingCPTID + AND target.UnitTypeID = source.UnitTypeID + + ) + WHEN MATCHED AND ( + target.InitialBudget01 <> source.OriginalValue01 + OR target.InitialBudget02 <> source.OriginalValue02 + OR target.InitialBudget03 <> source.OriginalValue03 + OR target.InitialBudget04 <> source.OriginalValue04 + OR target.InitialBudget05 <> source.OriginalValue05 + OR target.InitialBudget06 <> source.OriginalValue06 + OR target.InitialBudget07 <> source.OriginalValue07 + OR target.InitialBudget08 <> source.OriginalValue08 + OR target.InitialBudget09 <> source.OriginalValue09 + OR target.InitialBudget10 <> source.OriginalValue10 + OR target.InitialBudget11 <> source.OriginalValue11 + OR target.InitialBudget12 <> source.OriginalValue12 + OR target.InitialBudgetTotal <> source.OriginalValueTotal + OR target.Target01 <> source.Value01 + OR target.Target02 <> source.Value02 + OR target.Target03 <> source.Value03 + OR target.Target04 <> source.Value04 + OR target.Target05 <> source.Value05 + OR target.Target06 <> source.Value06 + OR target.Target07 <> source.Value07 + OR target.Target08 <> source.Value08 + OR target.Target09 <> source.Value09 + OR target.Target10 <> source.Value10 + OR target.Target11 <> source.Value11 + OR target.Target12 <> source.Value12 + OR target.TargetTotal <> source.ValueTotal + OR target.Budget01 <> source.ManagerValue01 + OR target.Budget02 <> source.ManagerValue02 + OR target.Budget03 <> source.ManagerValue03 + OR target.Budget04 <> source.ManagerValue04 + OR target.Budget05 <> source.ManagerValue05 + OR target.Budget06 <> source.ManagerValue06 + OR target.Budget07 <> source.ManagerValue07 + OR target.Budget08 <> source.ManagerValue08 + OR target.Budget09 <> source.ManagerValue09 + OR target.Budget10 <> source.ManagerValue10 + OR target.Budget11 <> source.ManagerValue11 + OR target.Budget12 <> source.ManagerValue12 + OR target.BudgetTotal <> source.ManagerValueTotal) + THEN + UPDATE SET + target.InitialBudget01 = ISNULL(source.OriginalValue01, 0), + target.InitialBudget02 = ISNULL(source.OriginalValue02, 0), + target.InitialBudget03 = ISNULL(source.OriginalValue03, 0), + target.InitialBudget04 = ISNULL(source.OriginalValue04, 0), + target.InitialBudget05 = ISNULL(source.OriginalValue05, 0), + target.InitialBudget06 = ISNULL(source.OriginalValue06, 0), + target.InitialBudget07 = ISNULL(source.OriginalValue07, 0), + target.InitialBudget08 = ISNULL(source.OriginalValue08, 0), + target.InitialBudget09 = ISNULL(source.OriginalValue09, 0), + target.InitialBudget10 = ISNULL(source.OriginalValue10, 0), + target.InitialBudget11 = ISNULL(source.OriginalValue11, 0), + target.InitialBudget12 = ISNULL(source.OriginalValue12, 0), + target.InitialBudgetTotal = ISNULL(source.OriginalValueTotal, 0), + target.Target01 = ISNULL(source.Value01, 0), + target.Target02 = ISNULL(source.Value02, 0), + target.Target03 = ISNULL(source.Value03, 0), + target.Target04 = ISNULL(source.Value04, 0), + target.Target05 = ISNULL(source.Value05, 0), + target.Target06 = ISNULL(source.Value06, 0), + target.Target07 = ISNULL(source.Value07, 0), + target.Target08 = ISNULL(source.Value08, 0), + target.Target09 = ISNULL(source.Value09, 0), + target.Target10 = ISNULL(source.Value10, 0), + target.Target11 = ISNULL(source.Value11, 0), + target.Target12 = ISNULL(source.Value12, 0), + target.TargetTotal = ISNULL(source.ValueTotal, 0), + target.Budget01 = ISNULL(source.ManagerValue01, 0), + target.Budget02 = ISNULL(source.ManagerValue02, 0), + target.Budget03 = ISNULL(source.ManagerValue03, 0), + target.Budget04 = ISNULL(source.ManagerValue04, 0), + target.Budget05 = ISNULL(source.ManagerValue05, 0), + target.Budget06 = ISNULL(source.ManagerValue06, 0), + target.Budget07 = ISNULL(source.ManagerValue07, 0), + target.Budget08 = ISNULL(source.ManagerValue08, 0), + target.Budget09 = ISNULL(source.ManagerValue09, 0), + target.Budget10 = ISNULL(source.ManagerValue10, 0), + target.Budget11 = ISNULL(source.ManagerValue11, 0), + target.Budget12 = ISNULL(source.ManagerValue12, 0), + target.BudgetTotal = ISNULL(source.ManagerValueTotal, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + ChargeVolumeID, + BudgetConfigID, + EntityID, + DepartmentID, + PatientClassID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + BillingCPTID, + UnitTypeID, + InitialBudget01, + InitialBudget02, + InitialBudget03, + InitialBudget04, + InitialBudget05, + InitialBudget06, + InitialBudget07, + InitialBudget08, + InitialBudget09, + InitialBudget10, + InitialBudget11, + InitialBudget12, + InitialBudgetTotal, + Target01, + Target02, + Target03, + Target04, + Target05, + Target06, + Target07, + Target08, + Target09, + Target10, + Target11, + Target12, + TargetTotal, + Budget01, + Budget02, + Budget03, + Budget04, + Budget05, + Budget06, + Budget07, + Budget08, + Budget09, + Budget10, + Budget11, + Budget12, + BudgetTotal + ) + VALUES ( + source.ChargeVolumeID, + source.BudgetConfigID, + source.EntityID, + source.DepartmentID, + source.PatientClassID, + source.ChargeCodeID, + source.ServiceLineID, + source.AgeCohortID, + source.MedicalSurgicalID, + source.ServiceEntityID, + source.MSDRGID, + source.UBRevCodeID, + source.PrimaryCPTID, + source.ServiceProviderID, + source.ServiceProviderSpecialtyID, + source.PerformingProviderID, + source.PerformingProviderSpecialtyID, + source.BillingCPTID, + source.UnitTypeID, + ISNULL(OriginalValue01, 0), + ISNULL(OriginalValue02, 0), + ISNULL(OriginalValue03, 0), + ISNULL(OriginalValue04, 0), + ISNULL(OriginalValue05, 0), + ISNULL(OriginalValue06, 0), + ISNULL(OriginalValue07, 0), + ISNULL(OriginalValue08, 0), + ISNULL(OriginalValue09, 0), + ISNULL(OriginalValue10, 0), + ISNULL(OriginalValue11, 0), + ISNULL(OriginalValue12, 0), + ISNULL(OriginalValueTotal, 0), + ISNULL(Value01, 0), + ISNULL(Value02, 0), + ISNULL(Value03, 0), + ISNULL(Value04, 0), + ISNULL(Value05, 0), + ISNULL(Value06, 0), + ISNULL(Value07, 0), + ISNULL(Value08, 0), + ISNULL(Value09, 0), + ISNULL(Value10, 0), + ISNULL(Value11, 0), + ISNULL(Value12, 0), + ISNULL(ValueTotal, 0), + ISNULL(ManagerValue01, 0), + ISNULL(ManagerValue02, 0), + ISNULL(ManagerValue03, 0), + ISNULL(ManagerValue04, 0), + ISNULL(ManagerValue05, 0), + ISNULL(ManagerValue06, 0), + ISNULL(ManagerValue07, 0), + ISNULL(ManagerValue08, 0), + ISNULL(ManagerValue09, 0), + ISNULL(ManagerValue10, 0), + ISNULL(ManagerValue11, 0), + ISNULL(ManagerValue12, 0), + ISNULL(ManagerValueTotal, 0) + ); + +END +GO + + +--------------------------------------------- + +-- fp.procPopulateReportFactChargeVolume_Dollars_Projection +/********************************************************************* +** Change History +********************************************************************** +** CID Date Author WI Description +** 1 2020-03-04 MY JAZZ-16292 Initial +** 2 2020-02-14 MY JAZZ-33542 Add Targeting +** 3 2023-03-21 MY JAZZ-49993 Update reporting to support new data model +** 4 2023-06-12 MY JAZZ-54952 Update to new columns +*********************************************************************/ +CREATE PROCEDURE fp.procPopulateReportFactChargeVolume_Dollars_Projection ( + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +) +WITH RECOMPILE +AS +BEGIN + + EXEC [dbo].[procSysDropTempTable] '#source' + EXEC [dbo].[procSysDropTempTable] '#recordsUpdated' + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + + DECLARE @ProjectionYear INT; + SET @ProjectionYear = (SELECT FiscalYearID - 1 FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID); + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + + CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT); + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED) + WHERE BudgetConfigID = @BudgetConfigID + END + + CREATE TABLE #source ( + ChargeVolumeID INT, + BudgetConfigID INT, + EntityID INT, + DepartmentID INT, + PatientClassID INT, + ChargeCodeID INT, + ServiceLineID INT, + AgeCohortID INT, + MedicalSurgicalID INT, + ServiceEntityID INT, + MSDRGID INT, + UBRevCodeID INT, + PrimaryCPTID INT, + ServiceProviderID INT, + ServiceProviderSpecialtyID INT, + PerformingProviderID INT, + PerformingProviderSpecialtyID INT, + BillingCPTID INT, + UnitTypeID INT, + TimeClassID INT, + FiscalMonthID INT, + FiscalYearID INT, + Projection01 DECIMAL(19, 8), + Projection02 DECIMAL(19, 8), + Projection03 DECIMAL(19, 8), + Projection04 DECIMAL(19, 8), + Projection05 DECIMAL(19, 8), + Projection06 DECIMAL(19, 8), + Projection07 DECIMAL(19, 8), + Projection08 DECIMAL(19, 8), + Projection09 DECIMAL(19, 8), + Projection10 DECIMAL(19, 8), + Projection11 DECIMAL(19, 8), + Projection12 DECIMAL(19, 8), + ProjectionTotal DECIMAL(19, 8) + ) + + -- Projection + INSERT INTO #source (ChargeVolumeID, BudgetConfigID, EntityID, DepartmentID, PatientClassID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, ServiceEntityID, + MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, PerformingProviderSpecialtyID, + BillingCPTID, UnitTypeID, TimeClassID, FiscalYearID, + Projection01, Projection02, Projection03, Projection04, Projection05, Projection06, Projection07, Projection08, Projection09, Projection10, Projection11, Projection12, ProjectionTotal) + SELECT fcv.ChargeVolumeID, fcv.BudgetConfigID, fcv.EntityID, fcv.DepartmentID, fcv.PatientClassID, fcv.ChargeCodeID, fcv.ServiceLineID, fcv.AgeCohortID, fcv.MedicalSurgicalID, fcv.ServiceEntityID, + fcv.MSDRGID, fcv.UBRevCodeID, fcv.PrimaryCPTID, fcv.ServiceProviderID, fcv.ServiceProviderSpecialtyID, fcv.PerformingProviderID, fcv.PerformingProviderSpecialtyID, + fcv.BillingCPTID, 34 AS UnitTypeID, 12 AS TimeClassID, @ProjectionYear AS FiscalYearID, + fcv.ProjectionDollarsAdjusted01, fcv.ProjectionDollarsAdjusted02, fcv.ProjectionDollarsAdjusted03, fcv.ProjectionDollarsAdjusted04, fcv.ProjectionDollarsAdjusted05, fcv.ProjectionDollarsAdjusted06, fcv.ProjectionDollarsAdjusted07, fcv.ProjectionDollarsAdjusted08, fcv.ProjectionDollarsAdjusted09, fcv.ProjectionDollarsAdjusted10, fcv.ProjectionDollarsAdjusted11, fcv.ProjectionDollarsAdjusted12, fcv.ProjectionDollarsAdjustedTotal + FROM fp.ChargeVolume fcv + INNER JOIN #ChargeVolumeDepartments depts ON fcv.DepartmentID = depts.DepartmentID + WHERE fcv.BudgetConfigID = @BudgetConfigID + + CREATE CLUSTERED INDEX inx_src ON #source ( + ChargeVolumeID, + BudgetConfigID, + EntityID, + DepartmentID, + PatientClassID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + BillingCPTID, + UnitTypeID, + TimeClassID, + FiscalYearID + ) with (data_compression = page) + + ;WITH TGT AS + ( + SELECT + ChargeVolumeID, + BudgetConfigID, + EntityID, + FRS.DepartmentID, + PatientClassID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + BillingCPTID, + UnitTypeID, + Projection01, + Projection02, + Projection03, + Projection04, + Projection05, + Projection06, + Projection07, + Projection08, + Projection09, + Projection10, + Projection11, + Projection12, + ProjectionTotal + FROM [fp].[FactReportChargeVolume] FRS + INNER JOIN #ChargeVolumeDepartments depts ON FRS.DepartmentID = depts.DepartmentID + WHERE FRS.BudgetConfigID = @BudgetConfigID + ) + MERGE TGT AS target + USING #source AS source + ON ( + target.ChargeVolumeID = source.ChargeVolumeID + AND target.BudgetConfigID = source.BudgetConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.PatientClassID = source.PatientClassID + AND target.ChargeCodeID = source.ChargeCodeID + AND target.ServiceLineID = source.ServiceLineID + AND target.AgeCohortID = source.AgeCohortID + AND target.MedicalSurgicalID = source.MedicalSurgicalID + AND target.ServiceEntityID = source.ServiceEntityID + AND target.MSDRGID = source.MSDRGID + AND target.UBRevCodeID = source.UBRevCodeID + AND target.PrimaryCPTID = source.PrimaryCPTID + AND target.ServiceProviderID = source.ServiceProviderID + AND target.ServiceProviderSpecialtyID = source.ServiceProviderSpecialtyID + AND target.PerformingProviderID = source.PerformingProviderID + AND target.PerformingProviderSpecialtyID = source.PerformingProviderSpecialtyID + AND target.BillingCPTID = source.BillingCPTID + AND target.UnitTypeID = source.UnitTypeID + + ) + WHEN MATCHED AND ( + target.Projection01 <> source.Projection01 + OR target.Projection02 <> source.Projection02 + OR target.Projection03 <> source.Projection03 + OR target.Projection04 <> source.Projection04 + OR target.Projection05 <> source.Projection05 + OR target.Projection06 <> source.Projection06 + OR target.Projection07 <> source.Projection07 + OR target.Projection08 <> source.Projection08 + OR target.Projection09 <> source.Projection09 + OR target.Projection10 <> source.Projection10 + OR target.Projection11 <> source.Projection11 + OR target.Projection12 <> source.Projection12 + OR target.ProjectionTotal <> source.ProjectionTotal) + THEN + UPDATE SET + target.Projection01 = ISNULL(source.Projection01, 0), + target.Projection02 = ISNULL(source.Projection02, 0), + target.Projection03 = ISNULL(source.Projection03, 0), + target.Projection04 = ISNULL(source.Projection04, 0), + target.Projection05 = ISNULL(source.Projection05, 0), + target.Projection06 = ISNULL(source.Projection06, 0), + target.Projection07 = ISNULL(source.Projection07, 0), + target.Projection08 = ISNULL(source.Projection08, 0), + target.Projection09 = ISNULL(source.Projection09, 0), + target.Projection10 = ISNULL(source.Projection10, 0), + target.Projection11 = ISNULL(source.Projection11, 0), + target.Projection12 = ISNULL(source.Projection12, 0), + target.ProjectionTotal = ISNULL(source.ProjectionTotal, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + ChargeVolumeID, + BudgetConfigID, + EntityID, + DepartmentID, + PatientClassID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + BillingCPTID, + UnitTypeID, + Projection01, + Projection02, + Projection03, + Projection04, + Projection05, + Projection06, + Projection07, + Projection08, + Projection09, + Projection10, + Projection11, + Projection12, + ProjectionTotal + ) + VALUES ( + source.ChargeVolumeID, + source.BudgetConfigID, + source.EntityID, + source.DepartmentID, + source.PatientClassID, + source.ChargeCodeID, + source.ServiceLineID, + source.AgeCohortID, + source.MedicalSurgicalID, + source.ServiceEntityID, + source.MSDRGID, + source.UBRevCodeID, + source.PrimaryCPTID, + source.ServiceProviderID, + source.ServiceProviderSpecialtyID, + source.PerformingProviderID, + source.PerformingProviderSpecialtyID, + source.BillingCPTID, + source.UnitTypeID, + ISNULL(Projection01, 0), + ISNULL(Projection02, 0), + ISNULL(Projection03, 0), + ISNULL(Projection04, 0), + ISNULL(Projection05, 0), + ISNULL(Projection06, 0), + ISNULL(Projection07, 0), + ISNULL(Projection08, 0), + ISNULL(Projection09, 0), + ISNULL(Projection10, 0), + ISNULL(Projection11, 0), + ISNULL(Projection12, 0), + ISNULL(ProjectionTotal, 0) + ); + +END +GO + + +--------------------------------------------- + +-- fp.procPopulateReportFactChargeVolume_Units_Budget +/********************************************************************* +** Change History +********************************************************************** +** CID Date Author WI Description +** 1 2020-03-11 MY JAZZ-16618 Initial +** 2 2020-02-14 MY JAZZ-33542 Add Targeting +** 3 2023-03-21 MY JAZZ-49993 Update reporting to support new data model +** 4 2023-06-12 MY JAZZ-54952 Update to new column names +*********************************************************************/ +CREATE PROCEDURE fp.procPopulateReportFactChargeVolume_Units_Budget ( + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +) +WITH RECOMPILE +AS +BEGIN + + EXEC [dbo].[procSysDropTempTable] '#source' + EXEC [dbo].[procSysDropTempTable] '#recordsUpdated' + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + + DECLARE @BudgetYear INT; + SET @BudgetYear = (SELECT FiscalYearID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID); + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + + CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT); + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED) + WHERE BudgetConfigID = @BudgetConfigID + END + + CREATE TABLE #source ( + ChargeVolumeID INT, + BudgetConfigID INT, + EntityID INT, + DepartmentID INT, + PatientClassID INT, + ChargeCodeID INT, + ServiceLineID INT, + AgeCohortID INT, + MedicalSurgicalID INT, + ServiceEntityID INT, + MSDRGID INT, + UBRevCodeID INT, + PrimaryCPTID INT, + ServiceProviderID INT, + ServiceProviderSpecialtyID INT, + PerformingProviderID INT, + PerformingProviderSpecialtyID INT, + BillingCPTID INT, + UnitTypeID INT, + TimeClassID INT, + FiscalMonthID INT, + FiscalYearID INT, + OriginalValue01 DECIMAL(19, 8), + OriginalValue02 DECIMAL(19, 8), + OriginalValue03 DECIMAL(19, 8), + OriginalValue04 DECIMAL(19, 8), + OriginalValue05 DECIMAL(19, 8), + OriginalValue06 DECIMAL(19, 8), + OriginalValue07 DECIMAL(19, 8), + OriginalValue08 DECIMAL(19, 8), + OriginalValue09 DECIMAL(19, 8), + OriginalValue10 DECIMAL(19, 8), + OriginalValue11 DECIMAL(19, 8), + OriginalValue12 DECIMAL(19, 8), + OriginalValueTotal DECIMAL(19, 8), + Value01 DECIMAL(19, 8), + Value02 DECIMAL(19, 8), + Value03 DECIMAL(19, 8), + Value04 DECIMAL(19, 8), + Value05 DECIMAL(19, 8), + Value06 DECIMAL(19, 8), + Value07 DECIMAL(19, 8), + Value08 DECIMAL(19, 8), + Value09 DECIMAL(19, 8), + Value10 DECIMAL(19, 8), + Value11 DECIMAL(19, 8), + Value12 DECIMAL(19, 8), + ValueTotal DECIMAL(19, 8), + ManagerValue01 DECIMAL(19, 8), + ManagerValue02 DECIMAL(19, 8), + ManagerValue03 DECIMAL(19, 8), + ManagerValue04 DECIMAL(19, 8), + ManagerValue05 DECIMAL(19, 8), + ManagerValue06 DECIMAL(19, 8), + ManagerValue07 DECIMAL(19, 8), + ManagerValue08 DECIMAL(19, 8), + ManagerValue09 DECIMAL(19, 8), + ManagerValue10 DECIMAL(19, 8), + ManagerValue11 DECIMAL(19, 8), + ManagerValue12 DECIMAL(19, 8), + ManagerValueTotal DECIMAL(19, 8) + ) + + -- Budget + INSERT INTO #source (ChargeVolumeID, BudgetConfigID, EntityID, DepartmentID, PatientClassID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, ServiceEntityID, + MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, PerformingProviderSpecialtyID, + BillingCPTID, UnitTypeID, TimeClassID, FiscalYearID, + OriginalValue01, OriginalValue02, OriginalValue03, OriginalValue04, OriginalValue05, OriginalValue06, OriginalValue07, OriginalValue08, OriginalValue09, OriginalValue10, OriginalValue11, OriginalValue12, OriginalValueTotal, + Value01, Value02, Value03, Value04, Value05, Value06, Value07, Value08, Value09, Value10, Value11, Value12, ValueTotal, + ManagerValue01, ManagerValue02, ManagerValue03, ManagerValue04, ManagerValue05, ManagerValue06, ManagerValue07, ManagerValue08, ManagerValue09, ManagerValue10, ManagerValue11, ManagerValue12, ManagerValueTotal) + SELECT fcv.ChargeVolumeID, fcv.BudgetConfigID, fcv.EntityID, fcv.DepartmentID, fcv.PatientClassID, fcv.ChargeCodeID, fcv.ServiceLineID, fcv.AgeCohortID, fcv.MedicalSurgicalID, fcv.ServiceEntityID, + fcv.MSDRGID, fcv.UBRevCodeID, fcv.PrimaryCPTID, fcv.ServiceProviderID, fcv.ServiceProviderSpecialtyID, fcv.PerformingProviderID, fcv.PerformingProviderSpecialtyID, + fcv.BillingCPTID, fcv.UnitTypeID, 2 AS TimeClassID, @BudgetYear AS FiscalYearID, + fcv.InitialBudget01, fcv.InitialBudget02, fcv.InitialBudget03, fcv.InitialBudget04, fcv.InitialBudget05, fcv.InitialBudget06, fcv.InitialBudget07, fcv.InitialBudget08, fcv.InitialBudget09, fcv.InitialBudget10, fcv.InitialBudget11, fcv.InitialBudget12, fcv.InitialBudgetTotal, + fcv.TargetAdjusted01, fcv.TargetAdjusted02, fcv.TargetAdjusted03, fcv.TargetAdjusted04, fcv.TargetAdjusted05, fcv.TargetAdjusted06, fcv.TargetAdjusted07, fcv.TargetAdjusted08, fcv.TargetAdjusted09, fcv.TargetAdjusted10, fcv.TargetAdjusted11, fcv.TargetAdjusted12, fcv.TargetAdjustedTotal, + fcv.BudgetAdjusted01, fcv.BudgetAdjusted02, fcv.BudgetAdjusted03, fcv.BudgetAdjusted04, fcv.BudgetAdjusted05, fcv.BudgetAdjusted06, fcv.BudgetAdjusted07, fcv.BudgetAdjusted08, fcv.BudgetAdjusted09, fcv.BudgetAdjusted10, fcv.BudgetAdjusted11, fcv.BudgetAdjusted12, fcv.BudgetAdjustedTotal + FROM fp.ChargeVolume fcv + INNER JOIN #ChargeVolumeDepartments depts ON fcv.DepartmentID = depts.DepartmentID + WHERE fcv.BudgetConfigID = @BudgetConfigID + AND fcv.UnitTypeID = 145 + + CREATE CLUSTERED INDEX inx_src ON #source ( + ChargeVolumeID, + BudgetConfigID, + EntityID, + DepartmentID, + PatientClassID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + BillingCPTID, + UnitTypeID, + TimeClassID, + FiscalYearID + ) with (data_compression = page) + + ;WITH TGT AS + ( + SELECT + ChargeVolumeID, + BudgetConfigID, + EntityID, + FRS.DepartmentID, + PatientClassID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + BillingCPTID, + UnitTypeID, + InitialBudget01, + InitialBudget02, + InitialBudget03, + InitialBudget04, + InitialBudget05, + InitialBudget06, + InitialBudget07, + InitialBudget08, + InitialBudget09, + InitialBudget10, + InitialBudget11, + InitialBudget12, + InitialBudgetTotal, + Target01, + Target02, + Target03, + Target04, + Target05, + Target06, + Target07, + Target08, + Target09, + Target10, + Target11, + Target12, + TargetTotal, + Budget01, + Budget02, + Budget03, + Budget04, + Budget05, + Budget06, + Budget07, + Budget08, + Budget09, + Budget10, + Budget11, + Budget12, + BudgetTotal + FROM [fp].[FactReportChargeVolume] FRS + INNER JOIN #ChargeVolumeDepartments depts ON FRS.DepartmentID = depts.DepartmentID + WHERE FRS.BudgetConfigID = @BudgetConfigID + ) + MERGE TGT AS target + USING #source AS source + ON ( + target.ChargeVolumeID = source.ChargeVolumeID + AND target.BudgetConfigID = source.BudgetConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.PatientClassID = source.PatientClassID + AND target.ChargeCodeID = source.ChargeCodeID + AND target.ServiceLineID = source.ServiceLineID + AND target.AgeCohortID = source.AgeCohortID + AND target.MedicalSurgicalID = source.MedicalSurgicalID + AND target.ServiceEntityID = source.ServiceEntityID + AND target.MSDRGID = source.MSDRGID + AND target.UBRevCodeID = source.UBRevCodeID + AND target.PrimaryCPTID = source.PrimaryCPTID + AND target.ServiceProviderID = source.ServiceProviderID + AND target.ServiceProviderSpecialtyID = source.ServiceProviderSpecialtyID + AND target.PerformingProviderID = source.PerformingProviderID + AND target.PerformingProviderSpecialtyID = source.PerformingProviderSpecialtyID + AND target.BillingCPTID = source.BillingCPTID + AND target.UnitTypeID = source.UnitTypeID + + ) + WHEN MATCHED AND ( + target.InitialBudget01 <> source.OriginalValue01 + OR target.InitialBudget02 <> source.OriginalValue02 + OR target.InitialBudget03 <> source.OriginalValue03 + OR target.InitialBudget04 <> source.OriginalValue04 + OR target.InitialBudget05 <> source.OriginalValue05 + OR target.InitialBudget06 <> source.OriginalValue06 + OR target.InitialBudget07 <> source.OriginalValue07 + OR target.InitialBudget08 <> source.OriginalValue08 + OR target.InitialBudget09 <> source.OriginalValue09 + OR target.InitialBudget10 <> source.OriginalValue10 + OR target.InitialBudget11 <> source.OriginalValue11 + OR target.InitialBudget12 <> source.OriginalValue12 + OR target.InitialBudgetTotal <> source.OriginalValueTotal + OR target.Target01 <> source.Value01 + OR target.Target02 <> source.Value02 + OR target.Target03 <> source.Value03 + OR target.Target04 <> source.Value04 + OR target.Target05 <> source.Value05 + OR target.Target06 <> source.Value06 + OR target.Target07 <> source.Value07 + OR target.Target08 <> source.Value08 + OR target.Target09 <> source.Value09 + OR target.Target10 <> source.Value10 + OR target.Target11 <> source.Value11 + OR target.Target12 <> source.Value12 + OR target.TargetTotal <> source.ValueTotal + OR target.Budget01 <> source.ManagerValue01 + OR target.Budget02 <> source.ManagerValue02 + OR target.Budget03 <> source.ManagerValue03 + OR target.Budget04 <> source.ManagerValue04 + OR target.Budget05 <> source.ManagerValue05 + OR target.Budget06 <> source.ManagerValue06 + OR target.Budget07 <> source.ManagerValue07 + OR target.Budget08 <> source.ManagerValue08 + OR target.Budget09 <> source.ManagerValue09 + OR target.Budget10 <> source.ManagerValue10 + OR target.Budget11 <> source.ManagerValue11 + OR target.Budget12 <> source.ManagerValue12 + OR target.BudgetTotal <> source.ManagerValueTotal) + THEN + UPDATE SET + target.InitialBudget01 = ISNULL(source.OriginalValue01, 0), + target.InitialBudget02 = ISNULL(source.OriginalValue02, 0), + target.InitialBudget03 = ISNULL(source.OriginalValue03, 0), + target.InitialBudget04 = ISNULL(source.OriginalValue04, 0), + target.InitialBudget05 = ISNULL(source.OriginalValue05, 0), + target.InitialBudget06 = ISNULL(source.OriginalValue06, 0), + target.InitialBudget07 = ISNULL(source.OriginalValue07, 0), + target.InitialBudget08 = ISNULL(source.OriginalValue08, 0), + target.InitialBudget09 = ISNULL(source.OriginalValue09, 0), + target.InitialBudget10 = ISNULL(source.OriginalValue10, 0), + target.InitialBudget11 = ISNULL(source.OriginalValue11, 0), + target.InitialBudget12 = ISNULL(source.OriginalValue12, 0), + target.InitialBudgetTotal = ISNULL(source.OriginalValueTotal, 0), + target.Target01 = ISNULL(source.Value01, 0), + target.Target02 = ISNULL(source.Value02, 0), + target.Target03 = ISNULL(source.Value03, 0), + target.Target04 = ISNULL(source.Value04, 0), + target.Target05 = ISNULL(source.Value05, 0), + target.Target06 = ISNULL(source.Value06, 0), + target.Target07 = ISNULL(source.Value07, 0), + target.Target08 = ISNULL(source.Value08, 0), + target.Target09 = ISNULL(source.Value09, 0), + target.Target10 = ISNULL(source.Value10, 0), + target.Target11 = ISNULL(source.Value11, 0), + target.Target12 = ISNULL(source.Value12, 0), + target.TargetTotal = ISNULL(source.ValueTotal, 0), + target.Budget01 = ISNULL(source.ManagerValue01, 0), + target.Budget02 = ISNULL(source.ManagerValue02, 0), + target.Budget03 = ISNULL(source.ManagerValue03, 0), + target.Budget04 = ISNULL(source.ManagerValue04, 0), + target.Budget05 = ISNULL(source.ManagerValue05, 0), + target.Budget06 = ISNULL(source.ManagerValue06, 0), + target.Budget07 = ISNULL(source.ManagerValue07, 0), + target.Budget08 = ISNULL(source.ManagerValue08, 0), + target.Budget09 = ISNULL(source.ManagerValue09, 0), + target.Budget10 = ISNULL(source.ManagerValue10, 0), + target.Budget11 = ISNULL(source.ManagerValue11, 0), + target.Budget12 = ISNULL(source.ManagerValue12, 0), + target.BudgetTotal = ISNULL(source.ManagerValueTotal, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + ChargeVolumeID, + BudgetConfigID, + EntityID, + DepartmentID, + PatientClassID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + BillingCPTID, + UnitTypeID, + InitialBudget01, + InitialBudget02, + InitialBudget03, + InitialBudget04, + InitialBudget05, + InitialBudget06, + InitialBudget07, + InitialBudget08, + InitialBudget09, + InitialBudget10, + InitialBudget11, + InitialBudget12, + InitialBudgetTotal, + Target01, + Target02, + Target03, + Target04, + Target05, + Target06, + Target07, + Target08, + Target09, + Target10, + Target11, + Target12, + TargetTotal, + Budget01, + Budget02, + Budget03, + Budget04, + Budget05, + Budget06, + Budget07, + Budget08, + Budget09, + Budget10, + Budget11, + Budget12, + BudgetTotal + ) + VALUES ( + source.ChargeVolumeID, + source.BudgetConfigID, + source.EntityID, + source.DepartmentID, + source.PatientClassID, + source.ChargeCodeID, + source.ServiceLineID, + source.AgeCohortID, + source.MedicalSurgicalID, + source.ServiceEntityID, + source.MSDRGID, + source.UBRevCodeID, + source.PrimaryCPTID, + source.ServiceProviderID, + source.ServiceProviderSpecialtyID, + source.PerformingProviderID, + source.PerformingProviderSpecialtyID, + source.BillingCPTID, + source.UnitTypeID, + ISNULL(OriginalValue01, 0), + ISNULL(OriginalValue02, 0), + ISNULL(OriginalValue03, 0), + ISNULL(OriginalValue04, 0), + ISNULL(OriginalValue05, 0), + ISNULL(OriginalValue06, 0), + ISNULL(OriginalValue07, 0), + ISNULL(OriginalValue08, 0), + ISNULL(OriginalValue09, 0), + ISNULL(OriginalValue10, 0), + ISNULL(OriginalValue11, 0), + ISNULL(OriginalValue12, 0), + ISNULL(OriginalValueTotal, 0), + ISNULL(Value01, 0), + ISNULL(Value02, 0), + ISNULL(Value03, 0), + ISNULL(Value04, 0), + ISNULL(Value05, 0), + ISNULL(Value06, 0), + ISNULL(Value07, 0), + ISNULL(Value08, 0), + ISNULL(Value09, 0), + ISNULL(Value10, 0), + ISNULL(Value11, 0), + ISNULL(Value12, 0), + ISNULL(ValueTotal, 0), + ISNULL(ManagerValue01, 0), + ISNULL(ManagerValue02, 0), + ISNULL(ManagerValue03, 0), + ISNULL(ManagerValue04, 0), + ISNULL(ManagerValue05, 0), + ISNULL(ManagerValue06, 0), + ISNULL(ManagerValue07, 0), + ISNULL(ManagerValue08, 0), + ISNULL(ManagerValue09, 0), + ISNULL(ManagerValue10, 0), + ISNULL(ManagerValue11, 0), + ISNULL(ManagerValue12, 0), + ISNULL(ManagerValueTotal, 0) + ); + -- NOTE: We are not deleting for performance reasons, otherwise we would have to join the report information on what's being passed in + -- If this ends up being a problem we can add it and work with the performance aspect of it. This is also why when sampling charge volume + -- or changing the active configuration, it wipes the report table to begin with and waits for it to be refreshed. +END +GO + + +--------------------------------------------- + +-- fp.procPopulateReportFactChargeVolume_Units_Projection +/********************************************************************* +** Change History +********************************************************************** +** CID Date Author WI Description +** 1 2020-03-11 MY JAZZ-16618 Initial +** 2 2020-02-14 MY JAZZ-33542 Add Targeting +** 3 2023-03-21 MY JAZZ-49993 Update reporting to support new data model +** 4 2023-06-12 MY JAZZ-54952 Update to new columns +*********************************************************************/ +CREATE PROCEDURE fp.procPopulateReportFactChargeVolume_Units_Projection ( + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +) +WITH RECOMPILE +AS +BEGIN + + EXEC [dbo].[procSysDropTempTable] '#source' + EXEC [dbo].[procSysDropTempTable] '#recordsUpdated' + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE IsActive = 1 AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + + DECLARE @ProjectionYear INT; + SET @ProjectionYear = (SELECT FiscalYearID - 1 FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID); + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + + CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT); + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED) + WHERE BudgetConfigID = @BudgetConfigID + END + + CREATE TABLE #source ( + ChargeVolumeID INT, + BudgetConfigID INT, + EntityID INT, + DepartmentID INT, + PatientClassID INT, + ChargeCodeID INT, + ServiceLineID INT, + AgeCohortID INT, + MedicalSurgicalID INT, + ServiceEntityID INT, + MSDRGID INT, + UBRevCodeID INT, + PrimaryCPTID INT, + ServiceProviderID INT, + ServiceProviderSpecialtyID INT, + PerformingProviderID INT, + PerformingProviderSpecialtyID INT, + BillingCPTID INT, + UnitTypeID INT, + TimeClassID INT, + FiscalMonthID INT, + FiscalYearID INT, + Projection01 DECIMAL(19, 8), + Projection02 DECIMAL(19, 8), + Projection03 DECIMAL(19, 8), + Projection04 DECIMAL(19, 8), + Projection05 DECIMAL(19, 8), + Projection06 DECIMAL(19, 8), + Projection07 DECIMAL(19, 8), + Projection08 DECIMAL(19, 8), + Projection09 DECIMAL(19, 8), + Projection10 DECIMAL(19, 8), + Projection11 DECIMAL(19, 8), + Projection12 DECIMAL(19, 8), + ProjectionTotal DECIMAL(19, 8) + ) + + -- Projection + INSERT INTO #source (ChargeVolumeID, BudgetConfigID, EntityID, DepartmentID, PatientClassID, ChargeCodeID, ServiceLineID, AgeCohortID, MedicalSurgicalID, ServiceEntityID, + MSDRGID, UBRevCodeID, PrimaryCPTID, ServiceProviderID, ServiceProviderSpecialtyID, PerformingProviderID, PerformingProviderSpecialtyID, + BillingCPTID, UnitTypeID, TimeClassID, FiscalYearID, + Projection01, Projection02, Projection03, Projection04, Projection05, Projection06, Projection07, Projection08, Projection09, Projection10, Projection11, Projection12, ProjectionTotal) + SELECT fcv.ChargeVolumeID, fcv.BudgetConfigID, fcv.EntityID, fcv.DepartmentID, fcv.PatientClassID, fcv.ChargeCodeID, fcv.ServiceLineID, fcv.AgeCohortID, fcv.MedicalSurgicalID, fcv.ServiceEntityID, + fcv.MSDRGID, fcv.UBRevCodeID, fcv.PrimaryCPTID, fcv.ServiceProviderID, fcv.ServiceProviderSpecialtyID, fcv.PerformingProviderID, fcv.PerformingProviderSpecialtyID, + fcv.BillingCPTID, fcv.UnitTypeID, 12 AS TimeClassID, @ProjectionYear AS FiscalYearID, + fcv.ProjectionAdjusted01, fcv.ProjectionAdjusted02, fcv.ProjectionAdjusted03, fcv.ProjectionAdjusted04, fcv.ProjectionAdjusted05, fcv.ProjectionAdjusted06, fcv.ProjectionAdjusted07, fcv.ProjectionAdjusted08, fcv.ProjectionAdjusted09, fcv.ProjectionAdjusted10, fcv.ProjectionAdjusted11, fcv.ProjectionAdjusted12, fcv.ProjectionAdjustedTotal + FROM fp.ChargeVolume fcv + INNER JOIN #ChargeVolumeDepartments depts ON fcv.DepartmentID = depts.DepartmentID + WHERE fcv.BudgetConfigID = @BudgetConfigID + AND fcv.UnitTypeID = 145 + + CREATE CLUSTERED INDEX inx_src ON #source ( + ChargeVolumeID, + BudgetConfigID, + EntityID, + DepartmentID, + PatientClassID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + BillingCPTID, + UnitTypeID, + TimeClassID, + FiscalYearID + ) with (data_compression = page) + + ;WITH TGT AS + ( + SELECT + ChargeVolumeID, + BudgetConfigID, + EntityID, + FRS.DepartmentID, + PatientClassID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + BillingCPTID, + UnitTypeID, + Projection01, + Projection02, + Projection03, + Projection04, + Projection05, + Projection06, + Projection07, + Projection08, + Projection09, + Projection10, + Projection11, + Projection12, + ProjectionTotal + FROM [fp].[FactReportChargeVolume] FRS + INNER JOIN #ChargeVolumeDepartments depts ON FRS.DepartmentID = depts.DepartmentID + WHERE FRS.BudgetConfigID = @BudgetConfigID + ) + MERGE TGT AS target + USING #source AS source + ON ( + target.ChargeVolumeID = source.ChargeVolumeID + AND target.BudgetConfigID = source.BudgetConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.PatientClassID = source.PatientClassID + AND target.ChargeCodeID = source.ChargeCodeID + AND target.ServiceLineID = source.ServiceLineID + AND target.AgeCohortID = source.AgeCohortID + AND target.MedicalSurgicalID = source.MedicalSurgicalID + AND target.ServiceEntityID = source.ServiceEntityID + AND target.MSDRGID = source.MSDRGID + AND target.UBRevCodeID = source.UBRevCodeID + AND target.PrimaryCPTID = source.PrimaryCPTID + AND target.ServiceProviderID = source.ServiceProviderID + AND target.ServiceProviderSpecialtyID = source.ServiceProviderSpecialtyID + AND target.PerformingProviderID = source.PerformingProviderID + AND target.PerformingProviderSpecialtyID = source.PerformingProviderSpecialtyID + AND target.BillingCPTID = source.BillingCPTID + AND target.UnitTypeID = source.UnitTypeID + + ) + WHEN MATCHED AND ( + target.Projection01 <> source.Projection01 + OR target.Projection02 <> source.Projection02 + OR target.Projection03 <> source.Projection03 + OR target.Projection04 <> source.Projection04 + OR target.Projection05 <> source.Projection05 + OR target.Projection06 <> source.Projection06 + OR target.Projection07 <> source.Projection07 + OR target.Projection08 <> source.Projection08 + OR target.Projection09 <> source.Projection09 + OR target.Projection10 <> source.Projection10 + OR target.Projection11 <> source.Projection11 + OR target.Projection12 <> source.Projection12 + OR target.ProjectionTotal <> source.ProjectionTotal) + THEN + UPDATE SET + target.Projection01 = ISNULL(source.Projection01, 0), + target.Projection02 = ISNULL(source.Projection02, 0), + target.Projection03 = ISNULL(source.Projection03, 0), + target.Projection04 = ISNULL(source.Projection04, 0), + target.Projection05 = ISNULL(source.Projection05, 0), + target.Projection06 = ISNULL(source.Projection06, 0), + target.Projection07 = ISNULL(source.Projection07, 0), + target.Projection08 = ISNULL(source.Projection08, 0), + target.Projection09 = ISNULL(source.Projection09, 0), + target.Projection10 = ISNULL(source.Projection10, 0), + target.Projection11 = ISNULL(source.Projection11, 0), + target.Projection12 = ISNULL(source.Projection12, 0), + target.ProjectionTotal = ISNULL(source.ProjectionTotal, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + ChargeVolumeID, + BudgetConfigID, + EntityID, + DepartmentID, + PatientClassID, + ChargeCodeID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderID, + ServiceProviderSpecialtyID, + PerformingProviderID, + PerformingProviderSpecialtyID, + BillingCPTID, + UnitTypeID, + Projection01, + Projection02, + Projection03, + Projection04, + Projection05, + Projection06, + Projection07, + Projection08, + Projection09, + Projection10, + Projection11, + Projection12, + ProjectionTotal + ) + VALUES ( + source.ChargeVolumeID, + source.BudgetConfigID, + source.EntityID, + source.DepartmentID, + source.PatientClassID, + source.ChargeCodeID, + source.ServiceLineID, + source.AgeCohortID, + source.MedicalSurgicalID, + source.ServiceEntityID, + source.MSDRGID, + source.UBRevCodeID, + source.PrimaryCPTID, + source.ServiceProviderID, + source.ServiceProviderSpecialtyID, + source.PerformingProviderID, + source.PerformingProviderSpecialtyID, + source.BillingCPTID, + source.UnitTypeID, + ISNULL(Projection01, 0), + ISNULL(Projection02, 0), + ISNULL(Projection03, 0), + ISNULL(Projection04, 0), + ISNULL(Projection05, 0), + ISNULL(Projection06, 0), + ISNULL(Projection07, 0), + ISNULL(Projection08, 0), + ISNULL(Projection09, 0), + ISNULL(Projection10, 0), + ISNULL(Projection11, 0), + ISNULL(Projection12, 0), + ISNULL(ProjectionTotal, 0) + ); + -- NOTE: We are not deleting for performance reasons, otherwise we would have to join the report information on what's being passed in + -- If this ends up being a problem we can add it and work with the performance aspect of it. This is also why when sampling charge volume + -- or changing the active configuration, it wipes the report table to begin with and waits for it to be refreshed. +END +GO + + +--------------------------------------------- + +-- fp.procPopulateServiceLineEncounterPayorGroupMix +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2021-09-15 MY JAZZ-25836 Initial +** 2 2022-09-19 BK JAZZ-42503 Add distinct to select from mapping table +** 3 2023-02-24 BW JAZZ-48306 Updated for new data model, use [fp].[ServiceLineEncounter] +** 4 6-27-2023 MY JAZZ-56923 Adding Service Line into the SLE to Charge payor mix calc +** 5 2024-01-11 AO JAZZ-64530 Data transfer for SLE is based on selected Model in Plan Config +** 6 2024-04-17 MY JAZZ-70660 Updating payor group charge mix temporary workaround +** 7 2024-04-18 MY JAZZ-70774 Remove temporary workaround +*************************************************************/ +CREATE PROCEDURE [fp].[procPopulateServiceLineEncounterPayorGroupMix] + @BudgetConfigID INT, + @EntityGroupConfigID INT, + @IsReimbursementGLEnabled BIT = 0, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +WITH RECOMPILE +AS +BEGIN + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + IF OBJECT_ID('tempdb..#TargetingFilter') IS NOT NULL DROP TABLE #TargetingFilter; + IF OBJECT_ID('tempdb..#MixByEntityAndPatientClass') IS NOT NULL DROP TABLE #MixByEntityAndPatientClass; + IF OBJECT_ID('tempdb..#MixByPayorGroup') IS NOT NULL DROP TABLE #MixByPayorGroup; + IF OBJECT_ID('tempdb..#DimesionalityWithRoundingIssues') IS NOT NULL DROP TABLE #DimesionalityWithRoundingIssues; + IF OBJECT_ID('tempdb..#mixesRanked') IS NOT NULL DROP TABLE #mixesRanked; + IF OBJECT_ID('tempdb..#Working_ServiceLineEncounterPayorGroupMix') IS NOT NULL DROP TABLE #Working_ServiceLineEncounterPayorGroupMix; + + -- JAZZ-56923: Adding Service Line into the SLE to Charge payor mix calc + DECLARE @IsServiceLineEnabled BIT = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting WHERE BudgetConfigID = @BudgetConfigID AND Name = 'Enable ServiceLine level mix for Charge to GL Crosswalk'), 0) + + CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT); + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED) + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = d.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND ((@IsReimbursementGLEnabled = 1 + AND (bc.DefaultReimbursementNetRevenueModelID = 1 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model + OR rnrm.NetRevenueModelID = 1) + OR @IsReimbursementGLEnabled = 0) + END + + -- Translate the CV Departments to Encounter dimensionality + CREATE TABLE #TargetingFilter (EntityID INT, ServiceLineID INT); + INSERT INTO #TargetingFilter (EntityID, ServiceLineID) + SELECT DISTINCT slecvm.EntityID, ServiceLineID + FROM fp.ServiceLineEncounterChargeVolumeMapping slecvm + INNER JOIN #ChargeVolumeDepartments cv ON cv.DepartmentID = slecvm.DepartmentID + WHERE slecvm.BudgetConfigID = @BudgetConfigID + + IF (@IsDebug = 1) -- Displaying this now so we can clean it up after we don't need the charge table + BEGIN + SELECT '#ChargeVolumeDepartments', * FROM #ChargeVolumeDepartments + END + + -- We no longer need the charge volume departments, so we can drop it here. + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + + CREATE TABLE #Working_ServiceLineEncounterPayorGroupMix ( + [BudgetConfigID] [int] NOT NULL DEFAULT(0), + [EntityGroupConfigID] [int] NOT NULL DEFAULT(0), + [EntityID] [int] NOT NULL DEFAULT(0), + [PatientClassID] [int] NOT NULL DEFAULT(0), + [ServiceLineID] [int] NOT NULL DEFAULT(0), + [PayorGroupID] [int] NOT NULL DEFAULT(0), + [TimeClassID] [int] NOT NULL DEFAULT(0), + [MixPercentage] [decimal](22, 18) NOT NULL DEFAULT(0) + ) + + -- Find the total values for each payor group + SELECT fsle.EntityID, fsle.PatientClassID, CASE WHEN @IsServiceLineEnabled = 0 THEN 0 ELSE fsle.ServiceLineID END AS ServiceLineID, fsle.PayorGroupID, SUM(fsle.BudgetAdjustedTotal) AS BudgetTotal, SUM(fsle.ProjectionAdjustedTotal) AS ProjectionTotal + INTO #MixByPayorGroup + FROM fp.ServiceLineEncounter fsle + INNER JOIN #TargetingFilter targeting ON fsle.EntityID = targeting.EntityID + AND fsle.ServiceLineID = targeting.ServiceLineID + WHERE fsle.EntityGroupConfigID = @EntityGroupConfigID + GROUP BY fsle.EntityID, CASE WHEN @IsServiceLineEnabled = 0 THEN 0 ELSE fsle.ServiceLineID END, fsle.PatientClassID, fsle.PayorGroupID + + -- Find the rolled up values by Service Line / Patient Class + SELECT EntityID, PatientClassID, ServiceLineID, SUM(BudgetTotal) AS BudgetTotal, SUM(ProjectionTotal) AS ProjectionTotal + INTO #MixByEntityAndPatientClass + FROM #MixByPayorGroup + GROUP BY EntityID, PatientClassID, ServiceLineID + + -- Populate Budget + INSERT INTO #Working_ServiceLineEncounterPayorGroupMix (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, PayorGroupID, TimeClassID, MixPercentage) + SELECT + @BudgetConfigID, + @EntityGroupConfigID, + pg.EntityID, + pg.PatientClassID, + pg.ServiceLineID, + pg.PayorGroupID, + 2 AS TimeClassID, + COALESCE(CAST(pg.BudgetTotal AS DECIMAL(36, 18)) / CAST(NULLIF(roll.BudgetTotal, 0) AS DECIMAL(36, 18)), 0) AS MixPercentage + FROM #MixByPayorGroup pg + INNER JOIN #MixByEntityAndPatientClass roll ON pg.EntityID = roll.EntityID + AND pg.PatientClassID = roll.PatientClassID + AND pg.ServiceLineID = roll.ServiceLineID + + -- Populate Projection + INSERT INTO #Working_ServiceLineEncounterPayorGroupMix (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, PayorGroupID, TimeClassID, MixPercentage) + SELECT + @BudgetConfigID, + @EntityGroupConfigID, + pg.EntityID, + pg.PatientClassID, + pg.ServiceLineID, + pg.PayorGroupID, + 12 AS TimeClassID, + CAST(COALESCE(pg.ProjectionTotal / NULLIF(roll.ProjectionTotal, 0), 0) AS DECIMAL(22, 18)) AS MixPercentage + FROM #MixByPayorGroup pg + INNER JOIN #MixByEntityAndPatientClass roll ON pg.EntityID = roll.EntityID + AND pg.PatientClassID = roll.PatientClassID + AND pg.ServiceLineID = roll.ServiceLineID + + --------------------- + -- Rounding + --------------------- + -- Handle rounding issues. Because we can't story infinite amount of data and the raw data ins 18, 9, we can't store a very small decimal. + -- This can lean to small rounding errors where when adding the PayorGroups together, it won't come out to a perfect 1 like it should. + -- Without this logic, when summing up the percentages for a specific ServiceLine, PatientClass, you can have cases where it comes out to 0.9999994 for example. + -- This can be a problem because when we go to apply the dollars later it cause a small fraction of dollars to be missing. While this numbers is very small + -- and likely neglible, we have seen in the past where small numbers can cause discrepancies especially when dealing with larger values. + -- + -- If this logic is working correctly, the following SQL should return nothing: + -- SELECT BudgetConfigID, EntityID, PatientClassID, TimeClassID, SUM(MixPercentage) + -- FROM [fp].[ServiceLineEncounterPayorGroupMix] + -- GROUP BY BudgetConfigID, EntityID, PatientClassID, TimeClassID + -- HAVING SUM(MixPercentage) != 1 AND SUM(MixPercentage) != 0 + + -- First, find the rounding issues + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, TimeClassID, SUM(MixPercentage) AS MixPercentageTotal, 1 - SUM(MixPercentage) AS RoundingDifference + INTO #DimesionalityWithRoundingIssues + FROM #Working_ServiceLineEncounterPayorGroupMix + GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, TimeClassID + HAVING SUM(MixPercentage) != 1 AND SUM(MixPercentage) != 0 + + -- Next we need to find the highest value of each group so we know where we need to put the remainder + SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.TimeClassID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.PayorGroupID, mix.MixPercentage, rounding.RoundingDifference, ROW_NUMBER() OVER (PARTITION BY mix.TimeClassID, mix.EntityID, mix.PatientClassID ORDER BY mix.MixPercentage DESC) AS RowID + INTO #mixesRanked + FROM #Working_ServiceLineEncounterPayorGroupMix mix + INNER JOIN #DimesionalityWithRoundingIssues rounding ON mix.EntityID = rounding.EntityID + AND mix.PatientClassID = rounding.PatientClassID + AND mix.ServiceLineID = rounding.ServiceLineID + AND mix.TimeClassID = rounding.TimeClassID + + -- Update the mixed percentage + UPDATE mix + SET mix.MixPercentage = mix.MixPercentage + rounding.RoundingDifference + FROM #Working_ServiceLineEncounterPayorGroupMix mix + INNER JOIN #mixesRanked rounding ON mix.EntityID = rounding.EntityID + AND mix.PatientClassID = rounding.PatientClassID + AND mix.ServiceLineID = rounding.ServiceLineID + AND mix.TimeClassID = rounding.TimeClassID + AND mix.PayorGroupID = rounding.PayorGroupID + WHERE rounding.RowID = 1 -- We want the highest valued record to dump the remainder + + IF (@IsDebug = 1) + BEGIN + SELECT '#TargetingFilter', * FROM #TargetingFilter + SELECT '#MixByEntityAndPatientClass', * FROM #MixByEntityAndPatientClass + SELECT '#MixByPayorGroup', * FROM #MixByPayorGroup + SELECT '#DimesionalityWithRoundingIssues', * FROM #DimesionalityWithRoundingIssues + SELECT '#mixesRanked', * FROM #mixesRanked + SELECT '#Working_ServiceLineEncounterPayorGroupMix', * FROM #Working_ServiceLineEncounterPayorGroupMix + END ELSE + BEGIN + -- Publish + ;WITH TGT AS + ( + SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.PayorGroupID, mix.TimeClassID, mix.MixPercentage + FROM [fp].[ServiceLineEncounterPayorGroupMix] mix + INNER JOIN (SELECT DISTINCT EntityID FROM #TargetingFilter) targeting ON mix.EntityID = targeting.EntityID + WHERE mix.EntityGroupConfigID = @EntityGroupConfigID + ) + + MERGE TGT AS target + USING #Working_ServiceLineEncounterPayorGroupMix AS src + ON ( + target.BudgetConfigID = src.BudgetConfigID + AND target.EntityGroupConfigID = src.EntityGroupConfigID + AND target.EntityID = src.EntityID + AND target.PatientClassID = src.PatientClassID + AND target.ServiceLineID = src.ServiceLineID + AND target.PayorGroupID = src.PayorGroupID + AND target.TimeClassID = src.TimeClassID + ) + WHEN MATCHED AND (target.MixPercentage <> src.MixPercentage) + THEN + UPDATE SET target.MixPercentage = src.MixPercentage + WHEN NOT MATCHED BY TARGET THEN + INSERT (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, PayorGroupID, TimeClassID, MixPercentage) + VALUES (src.BudgetConfigID, src.EntityGroupConfigID, src.EntityID, src.PatientClassID, src.ServiceLineID, src.PayorGroupID, src.TimeClassID, src.MixPercentage); + + END + +END +GO + + +--------------------------------------------- + +-- fp.procPopulateServiceLineEncounterPayorGroup_InitialMix +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2021-09-15 MY JAZZ-25836 Initial +** 2 2022-09-19 BK JAZZ-42503 Add distinct to select on fp.ServiceLineEncounterChargeVolumeMapping because of ProviderID addition +** 3 2023-02-24 BW JAZZ-48306 Updated for new data model, use [fp].[ServiceLineEncounter] +** 4 6-27-2023 MY JAZZ-56923 Adding Service Line into the SLE to Charge payor mix calc +** 5 2024-01-11 AO JAZZ-64530 Data transfer for SLE is based on selected Model in Plan Config +** 6 2024-04-17 MY JAZZ-70660 Updating payor group charge mix temporary workaround +** 7 2024-04-18 MY JAZZ-70774 Remove temporary workaround +*************************************************************/ +CREATE PROCEDURE [fp].[procPopulateServiceLineEncounterPayorGroup_InitialMix] + @BudgetConfigID INT, + @EntityGroupConfigID INT, + @IsReimbursementGLEnabled BIT = 0, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +WITH RECOMPILE +AS +BEGIN + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + IF OBJECT_ID('tempdb..#TargetingFilter') IS NOT NULL DROP TABLE #TargetingFilter; + IF OBJECT_ID('tempdb..#MixByEntityAndPatientClass') IS NOT NULL DROP TABLE #MixByEntityAndPatientClass; + IF OBJECT_ID('tempdb..#MixByPayorGroup') IS NOT NULL DROP TABLE #MixByPayorGroup; + IF OBJECT_ID('tempdb..#DimesionalityWithRoundingIssues') IS NOT NULL DROP TABLE #DimesionalityWithRoundingIssues; + IF OBJECT_ID('tempdb..#mixesRanked') IS NOT NULL DROP TABLE #mixesRanked; + IF OBJECT_ID('tempdb..#Working_ServiceLineEncounterPayorGroupMix') IS NOT NULL DROP TABLE #Working_ServiceLineEncounterPayorGroupMix; + + CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT); + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- JAZZ-56923: Adding Service Line into the SLE to Charge payor mix calc + DECLARE @IsServiceLineEnabled BIT = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting WHERE BudgetConfigID = @BudgetConfigID AND Name = 'Enable ServiceLine level mix for Charge to GL Crosswalk'), 0) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED) + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = d.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND ((@IsReimbursementGLEnabled = 1 + AND (bc.DefaultReimbursementNetRevenueModelID = 1 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model + OR rnrm.NetRevenueModelID = 1) + OR @IsReimbursementGLEnabled = 0) + END + + -- Translate the CV Departments to Encounter dimensionality + CREATE TABLE #TargetingFilter (EntityID INT, ServiceLineID INT); + INSERT INTO #TargetingFilter (EntityID, ServiceLineID) + SELECT DISTINCT slecvm.EntityID, ServiceLineID + FROM fp.ServiceLineEncounterChargeVolumeMapping slecvm + INNER JOIN #ChargeVolumeDepartments cv ON cv.DepartmentID = slecvm.DepartmentID + WHERE slecvm.BudgetConfigID = @BudgetConfigID + + IF (@IsDebug = 1) -- Displaying this now so we can clean it up after we don't need the charge table + BEGIN + SELECT '#ChargeVolumeDepartments', * FROM #ChargeVolumeDepartments + END + + -- We no longer need the charge volume departments, so we can drop it here. + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + + CREATE TABLE #Working_ServiceLineEncounterPayorGroupMix ( + [BudgetConfigID] [int] NOT NULL DEFAULT(0), + [EntityGroupConfigID] [int] NOT NULL DEFAULT(0), + [EntityID] [int] NOT NULL DEFAULT(0), + [PatientClassID] [int] NOT NULL DEFAULT(0), + [ServiceLineID] [int] NOT NULL DEFAULT(0), + [PayorGroupID] [int] NOT NULL DEFAULT(0), + [TimeClassID] [int] NOT NULL DEFAULT(0), + [InitialMixPercentage] [decimal](22, 18) NOT NULL DEFAULT(0) + ) + + -- Find the total values for each payor group + SELECT fsle.EntityID, fsle.PatientClassID, CASE WHEN @IsServiceLineEnabled = 0 THEN 0 ELSE fsle.ServiceLineID END AS ServiceLineID, fsle.PayorGroupID, SUM(fsle.InitialBudgetTotal) AS BudgetTotal, SUM(fsle.InitialProjectionTotal) AS ProjectionTotal + INTO #MixByPayorGroup + FROM fp.ServiceLineEncounter fsle + INNER JOIN #TargetingFilter targeting ON fsle.EntityID = targeting.EntityID AND fsle.ServiceLineID = targeting.ServiceLineID + WHERE fsle.EntityGroupConfigID = @EntityGroupConfigID + GROUP BY fsle.EntityID, fsle.PatientClassID, CASE WHEN @IsServiceLineEnabled = 0 THEN 0 ELSE fsle.ServiceLineID END, fsle.PayorGroupID + + -- Find the rolled up values by Service Line / Patient Class + SELECT EntityID, ServiceLineID, PatientClassID, SUM(BudgetTotal) AS BudgetTotal, SUM(ProjectionTotal) AS ProjectionTotal + INTO #MixByEntityAndPatientClass + FROM #MixByPayorGroup + GROUP BY EntityID, ServiceLineID, PatientClassID + + -- Populate Budget + INSERT INTO #Working_ServiceLineEncounterPayorGroupMix (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, PayorGroupID, TimeClassID, InitialMixPercentage) + SELECT + @BudgetConfigID, + @EntityGroupConfigID, + pg.EntityID, + pg.PatientClassID, + pg.ServiceLineID, + pg.PayorGroupID, + 2 AS TimeClassID, + COALESCE(CAST(pg.BudgetTotal AS DECIMAL(36, 18)) / CAST(NULLIF(roll.BudgetTotal, 0) AS DECIMAL(36, 18)), 0) AS InitialMixPercentage + FROM #MixByPayorGroup pg + INNER JOIN #MixByEntityAndPatientClass roll ON pg.EntityID = roll.EntityID + AND pg.PatientClassID = roll.PatientClassID + AND pg.ServiceLineID = roll.ServiceLineID + + -- Populate Projection + INSERT INTO #Working_ServiceLineEncounterPayorGroupMix (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, PayorGroupID, TimeClassID, InitialMixPercentage) + SELECT + @BudgetConfigID, + @EntityGroupConfigID, + pg.EntityID, + pg.PatientClassID, + pg.ServiceLineID, + pg.PayorGroupID, + 12 AS TimeClassID, + CAST(COALESCE(pg.ProjectionTotal / NULLIF(roll.ProjectionTotal, 0), 0) AS DECIMAL(22, 18)) AS InitialMixPercentage + FROM #MixByPayorGroup pg + INNER JOIN #MixByEntityAndPatientClass roll ON pg.EntityID = roll.EntityID + AND pg.PatientClassID = roll.PatientClassID + AND pg.ServiceLineID = roll.ServiceLineID + + --------------------- + -- Rounding + --------------------- + -- Handle rounding issues. Because we can't story infinite amount of data and the raw data ins 18, 9, we can't store a very small decimal. + -- This can lean to small rounding errors where when adding the PayorGroups together, it won't come out to a perfect 1 like it should. + -- Without this logic, when summing up the percentages for a specific ServiceLine, PatientClass, you can have cases where it comes out to 0.9999994 for example. + -- This can be a problem because when we go to apply the dollars later it cause a small fraction of dollars to be missing. While this numbers is very small + -- and likely neglible, we have seen in the past where small numbers can cause discrepancies especially when dealing with larger values. + -- + -- If this logic is working correctly, the following SQL should return nothing: + -- SELECT BudgetConfigID, EntityID, PatientClassID, TimeClassID, SUM(InitialMixPercentage) + -- FROM [fp].[ServiceLineEncounterPayorGroupMix] + -- GROUP BY BudgetConfigID, EntityID, PatientClassID, TimeClassID + -- HAVING SUM(InitialMixPercentage) != 1 AND SUM(InitialMixPercentage) != 0 + + -- First, find the rounding issues + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, TimeClassID, SUM(InitialMixPercentage) AS MixPercentageTotal, 1 - SUM(InitialMixPercentage) AS RoundingDifference + INTO #DimesionalityWithRoundingIssues + FROM #Working_ServiceLineEncounterPayorGroupMix + GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, TimeClassID + HAVING SUM(InitialMixPercentage) != 1 AND SUM(InitialMixPercentage) != 0 + + -- Next we need to find the highest value of each group so we know where we need to put the remainder + SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.TimeClassID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.PayorGroupID, mix.InitialMixPercentage, rounding.RoundingDifference, ROW_NUMBER() OVER (PARTITION BY mix.TimeClassID, mix.EntityID, mix.PatientClassID ORDER BY mix.InitialMixPercentage DESC) AS RowID + INTO #mixesRanked + FROM #Working_ServiceLineEncounterPayorGroupMix mix + INNER JOIN #DimesionalityWithRoundingIssues rounding ON mix.EntityID = rounding.EntityID + AND mix.PatientClassID = rounding.PatientClassID + AND mix.ServiceLineID = rounding.ServiceLineID + AND mix.TimeClassID = rounding.TimeClassID + + -- Update the mixed percentage + UPDATE mix + SET mix.InitialMixPercentage = mix.InitialMixPercentage + rounding.RoundingDifference + FROM #Working_ServiceLineEncounterPayorGroupMix mix + INNER JOIN #mixesRanked rounding ON mix.EntityID = rounding.EntityID + AND mix.PatientClassID = rounding.PatientClassID + AND mix.ServiceLineID = rounding.ServiceLineID + AND mix.TimeClassID = rounding.TimeClassID + AND mix.PayorGroupID = rounding.PayorGroupID + WHERE rounding.RowID = 1 -- We want the highest valued record to dump the remainder + + IF (@IsDebug = 1) + BEGIN + SELECT '#TargetingFilter', * FROM #TargetingFilter + SELECT '#MixByEntityAndPatientClass', * FROM #MixByEntityAndPatientClass + SELECT '#MixByPayorGroup', * FROM #MixByPayorGroup + SELECT '#DimesionalityWithRoundingIssues', * FROM #DimesionalityWithRoundingIssues + SELECT '#mixesRanked', * FROM #mixesRanked + SELECT '#Working_ServiceLineEncounterPayorGroupMix', * FROM #Working_ServiceLineEncounterPayorGroupMix + END ELSE + BEGIN + -- Publish + ;WITH TGT AS + ( + SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.PayorGroupID, mix.TimeClassID, mix.InitialMixPercentage + FROM [fp].[ServiceLineEncounterPayorGroupMix] mix + INNER JOIN (SELECT DISTINCT EntityID FROM #TargetingFilter) targeting ON mix.EntityID = targeting.EntityID + WHERE mix.EntityGroupConfigID = @EntityGroupConfigID + ) + + MERGE TGT AS target + USING #Working_ServiceLineEncounterPayorGroupMix AS src + ON ( + target.BudgetConfigID = src.BudgetConfigID + AND target.EntityGroupConfigID = src.EntityGroupConfigID + AND target.EntityID = src.EntityID + AND target.PatientClassID = src.PatientClassID + AND target.ServiceLineID = src.ServiceLineID + AND target.PayorGroupID = src.PayorGroupID + AND target.TimeClassID = src.TimeClassID + ) + WHEN MATCHED AND (target.InitialMixPercentage <> src.InitialMixPercentage) + THEN + UPDATE SET target.InitialMixPercentage = src.InitialMixPercentage + WHEN NOT MATCHED BY TARGET THEN + INSERT (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, PayorGroupID, TimeClassID, InitialMixPercentage) + VALUES (src.BudgetConfigID, src.EntityGroupConfigID, src.EntityID, src.PatientClassID, src.ServiceLineID, src.PayorGroupID, src.TimeClassID, src.InitialMixPercentage); + + END + +END +GO + + +--------------------------------------------- + +-- fp.procPopulateServiceLineEncounterToChargeVolumePayorMix +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-01-10 MY JAZZ-31850 Initial +** 2 2023-01-17 BK JAZZ-48267 Update for new data structure +** 3 2023-06-21 MY JAZZ-55363 Clear out data that is no longer valid +** 4 2024-01-11 AO JAZZ-64530 Data transfer for SLE is based on selected Model in Plan Config +*************************************************************/ +CREATE PROCEDURE [fp].[procPopulateServiceLineEncounterToChargeVolumePayorMix] + @BudgetConfigID INT, + @EntityGroupConfigID INT, + @IsReimbursementGLEnabled BIT = 0, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + IF OBJECT_ID('tempdb..#TargetingFilter') IS NOT NULL DROP TABLE #TargetingFilter; + IF OBJECT_ID('tempdb..#MixByEntityAndPatientClass') IS NOT NULL DROP TABLE #MixByEntityAndPatientClass; + IF OBJECT_ID('tempdb..#MixByPayorGroup') IS NOT NULL DROP TABLE #MixByPayorGroup; + IF OBJECT_ID('tempdb..#DimesionalityWithRoundingIssues') IS NOT NULL DROP TABLE #DimesionalityWithRoundingIssues; + IF OBJECT_ID('tempdb..#mixesRankedBudget') IS NOT NULL DROP TABLE #mixesRankedBudget; + IF OBJECT_ID('tempdb..#mixesRankedProjection') IS NOT NULL DROP TABLE #mixesRankedProjection; + IF OBJECT_ID('tempdb..#Working_ServiceLineEncounterPayorGroupMix') IS NOT NULL DROP TABLE #Working_ServiceLineEncounterPayorGroupMix; + + CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT); + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED) + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = d.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE d.BudgetConfigID = @BudgetConfigID + AND ((@IsReimbursementGLEnabled = 1 + AND (bc.DefaultReimbursementNetRevenueModelID = 1 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model + OR rnrm.NetRevenueModelID = 1) + OR @IsReimbursementGLEnabled = 0) + END + + -- Translate the CV Departments to Encounter dimensionality + CREATE TABLE #TargetingFilter (EntityID INT, ServiceLineID INT); + INSERT INTO #TargetingFilter (EntityID, ServiceLineID) + SELECT DISTINCT slecvm.EntityID, ServiceLineID + FROM fp.ServiceLineEncounterChargeVolumeMapping slecvm + INNER JOIN #ChargeVolumeDepartments cv ON cv.DepartmentID = slecvm.DepartmentID + INNER JOIN fp.BudgetConfig bc ON slecvm.BudgetConfigID = bc.BudgetConfigID + INNER JOIN fp.EntityGroupConfig egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfigMapping egcm ON egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID AND egcm.EntityID = slecvm.EntityID + WHERE slecvm.BudgetConfigID = @BudgetConfigID + AND egc.EntityGroupConfigID = @EntityGroupConfigID + + IF (@IsDebug = 1) -- Displaying this now so we can clean it up after we don't need the charge table + BEGIN + SELECT '#ChargeVolumeDepartments', * FROM #ChargeVolumeDepartments + END + + -- We no longer need the charge volume departments, so we can drop it here. + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + + CREATE TABLE #Working_ServiceLineEncounterPayorGroupMix ( + [BudgetConfigID] [int] NOT NULL DEFAULT(0), + [EntityGroupConfigID] [int] NOT NULL DEFAULT(0), + [EntityID] [int] NOT NULL DEFAULT(0), + [PatientClassID] [int] NOT NULL DEFAULT(0), + [ServiceLineID] [int] NOT NULL DEFAULT(0), + [AgeCohortID] [int] NOT NULL DEFAULT(0), + [MedicalSurgicalID] [int] NOT NULL DEFAULT(0), + [MSDRGID] [int] NOT NULL DEFAULT(0), + [CPTID] [int] NOT NULL DEFAULT(0), + [ProviderID] [int] NOT NULL DEFAULT(0), + [PayorID] [int] NOT NULL DEFAULT(0), + [PayorGroupID] [int] NOT NULL DEFAULT(0), + [InitialMixPercentage] [decimal](22, 18) NOT NULL DEFAULT(0), + [ProjectionMixPercentage] [decimal](22, 18) NOT NULL DEFAULT(0), + [BudgetMixPercentage] [decimal](22, 18) NOT NULL DEFAULT(0) -- Note: We're not including Target and only using budget becuase they are going to be the same. The only difference would be the spread which wouldn't matter for this case. + ) + + -- Find the total values for each payor group + SELECT sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.AgeCohortID, sle.MedicalSurgicalID, sle.MSDRGID, sle.CPTID, sle.ProviderID, sle.PayorID, sle.PayorGroupID, + SUM(TargetAdjustedTotal) AS BudgetTotal, -- this was joining on the budget table with BudgetPhaseID = 2, so used Target instead of Budget + SUM(ProjectionAdjustedTotal) AS ProjectionTotal + INTO #MixByPayorGroup + FROM fp.ServiceLineEncounter sle + INNER JOIN #TargetingFilter targeting ON sle.EntityID = targeting.EntityID AND sle.ServiceLineID = targeting.ServiceLineID + WHERE sle.EntityGroupConfigID = @EntityGroupConfigID + GROUP BY sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.AgeCohortID, sle.MedicalSurgicalID, sle.MSDRGID, sle.CPTID, sle.ProviderID, sle.PayorID, sle.PayorGroupID + + -- Find the rolled up values by Service Line / Patient Class + SELECT EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, SUM(BudgetTotal) AS BudgetTotal, SUM(ProjectionTotal) AS ProjectionTotal + INTO #MixByEntityAndPatientClass + FROM #MixByPayorGroup + GROUP BY EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID + + -- Populate Budget, Target, and Projection + INSERT INTO #Working_ServiceLineEncounterPayorGroupMix (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, + MSDRGID, CPTID, ProviderID, PayorID, PayorGroupID, ProjectionMixPercentage, BudgetMixPercentage) + SELECT + @BudgetConfigID, + @EntityGroupConfigID, + pg.EntityID, + pg.PatientClassID, + pg.ServiceLineID, + pg.AgeCohortID, + pg.MedicalSurgicalID, + pg.MSDRGID, + pg.CPTID, + pg.ProviderID, + pg.PayorID, + pg.PayorGroupID, + COALESCE(CAST(pg.ProjectionTotal AS DECIMAL(36, 18)) / CAST(NULLIF(roll.ProjectionTotal, 0) AS DECIMAL(36, 18)), 0) AS ProjectionMixPercentage, + COALESCE(CAST(pg.BudgetTotal AS DECIMAL(36, 18)) / CAST(NULLIF(roll.BudgetTotal, 0) AS DECIMAL(36, 18)), 0) AS BudgetMixPercentage + FROM #MixByPayorGroup pg + INNER JOIN #MixByEntityAndPatientClass roll ON + pg.EntityID = roll.EntityID + AND pg.PatientClassID = roll.PatientClassID + AND pg.ServiceLineID = roll.ServiceLineID + AND pg.AgeCohortID = roll.AgeCohortID + AND pg.MedicalSurgicalID = roll.MedicalSurgicalID + AND pg.MSDRGID = roll.MSDRGID + AND pg.CPTID = roll.CPTID + AND pg.ProviderID = roll.ProviderID + + --------------------- + -- Rounding + --------------------- + -- Handle rounding issues. Because we can't story infinite amount of data and the raw data ins 18, 9, we can't store a very small decimal. + -- This can lean to small rounding errors where when adding the PayorGroups together, it won't come out to a perfect 1 like it should. + -- Without this logic, when summing up the percentages for a specific ServiceLine, PatientClass, you can have cases where it comes out to 0.9999994 for example. + -- This can be a problem because when we go to apply the dollars later it cause a small fraction of dollars to be missing. While this numbers is very small + -- and likely neglible, we have seen in the past where small numbers can cause discrepancies especially when dealing with larger values. + -- + -- If this logic is working correctly, the following SQL should return nothing: + -- SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, SUM(BudgetMixPercentage) + -- FROM [fp].[ServiceLineEncounterToChargePayorMix] + -- GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID + -- HAVING SUM(BudgetMixPercentage) != 1 AND SUM(BudgetMixPercentage) != 0 + + -- First, find the rounding issues + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, + 1 - SUM(ProjectionMixPercentage) AS ProjectionRoundingDifference, + 1 - SUM(BudgetMixPercentage) AS BudgetRoundingDifference + INTO #DimesionalityWithRoundingIssues + FROM #Working_ServiceLineEncounterPayorGroupMix + GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID + HAVING (SUM(ProjectionMixPercentage) != 1 AND SUM(ProjectionMixPercentage) != 0) OR (SUM(BudgetMixPercentage) != 1 AND SUM(BudgetMixPercentage) != 0) + + -- Check Remainder for Projection + -- Next we need to find the highest value of each group so we know where we need to put the remainder + SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, + mix.PayorID, mix.PayorGroupID, mix.ProjectionMixPercentage, rounding.ProjectionRoundingDifference, ROW_NUMBER() OVER (PARTITION BY mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID ORDER BY mix.ProjectionMixPercentage DESC) AS RowID + INTO #mixesRankedProjection + FROM #Working_ServiceLineEncounterPayorGroupMix mix + INNER JOIN #DimesionalityWithRoundingIssues rounding ON + mix.EntityID = rounding.EntityID + AND mix.PatientClassID = rounding.PatientClassID + AND mix.ServiceLineID = rounding.ServiceLineID + AND mix.AgeCohortID = rounding.AgeCohortID + AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID + AND mix.MSDRGID = rounding.MSDRGID + AND mix.CPTID = rounding.CPTID + AND mix.ProviderID = rounding.ProviderID + + -- Update the mixed percentage + UPDATE mix + SET mix.ProjectionMixPercentage = mix.ProjectionMixPercentage + rounding.ProjectionRoundingDifference + FROM #Working_ServiceLineEncounterPayorGroupMix mix + INNER JOIN #mixesRankedProjection rounding ON + mix.EntityID = rounding.EntityID + AND mix.PatientClassID = rounding.PatientClassID + AND mix.ServiceLineID = rounding.ServiceLineID + AND mix.AgeCohortID = rounding.AgeCohortID + AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID + AND mix.MSDRGID = rounding.MSDRGID + AND mix.CPTID = rounding.CPTID + AND mix.ProviderID = rounding.ProviderID + AND mix.PayorID = rounding.PayorID + AND mix.PayorGroupID = rounding.PayorGroupID + WHERE rounding.RowID = 1 -- We want the highest valued record to dump the remainder + + -- Check Remainder for Budget + -- Next we need to find the highest value of each group so we know where we need to put the remainder + SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, + mix.PayorID, mix.PayorGroupID, mix.BudgetMixPercentage, rounding.BudgetRoundingDifference, ROW_NUMBER() OVER (PARTITION BY mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID ORDER BY mix.BudgetMixPercentage DESC) AS RowID + INTO #mixesRankedBudget + FROM #Working_ServiceLineEncounterPayorGroupMix mix + INNER JOIN #DimesionalityWithRoundingIssues rounding ON + mix.EntityID = rounding.EntityID + AND mix.PatientClassID = rounding.PatientClassID + AND mix.ServiceLineID = rounding.ServiceLineID + AND mix.AgeCohortID = rounding.AgeCohortID + AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID + AND mix.MSDRGID = rounding.MSDRGID + AND mix.CPTID = rounding.CPTID + AND mix.ProviderID = rounding.ProviderID + + -- Update the mixed percentage + UPDATE mix + SET mix.BudgetMixPercentage = mix.BudgetMixPercentage + rounding.BudgetRoundingDifference + FROM #Working_ServiceLineEncounterPayorGroupMix mix + INNER JOIN #mixesRankedBudget rounding ON + mix.EntityID = rounding.EntityID + AND mix.PatientClassID = rounding.PatientClassID + AND mix.ServiceLineID = rounding.ServiceLineID + AND mix.AgeCohortID = rounding.AgeCohortID + AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID + AND mix.MSDRGID = rounding.MSDRGID + AND mix.CPTID = rounding.CPTID + AND mix.ProviderID = rounding.ProviderID + AND mix.PayorID = rounding.PayorID + AND mix.PayorGroupID = rounding.PayorGroupID + WHERE rounding.RowID = 1 -- We want the highest valued record to dump the remainder + + IF (@IsDebug = 1) + BEGIN + SELECT '#TargetingFilter', * FROM #TargetingFilter + SELECT '#MixByEntityAndPatientClass', * FROM #MixByEntityAndPatientClass + SELECT '#MixByPayorGroup', * FROM #MixByPayorGroup + SELECT '#DimesionalityWithRoundingIssues', * FROM #DimesionalityWithRoundingIssues + SELECT '#mixesRankedProjection', * FROM #mixesRankedProjection + SELECT '#mixesRankedBudget', * FROM #mixesRankedBudget + SELECT '#Working_ServiceLineEncounterPayorGroupMix', * FROM #Working_ServiceLineEncounterPayorGroupMix + END ELSE + BEGIN + -- Publish + ;WITH TGT AS + ( + SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, mix.PayorID, mix.PayorGroupID, + mix.ProjectionMixPercentage, BudgetMixPercentage + FROM [fp].[ServiceLineEncounterToChargePayorMix] mix + INNER JOIN (SELECT DISTINCT EntityID FROM #TargetingFilter) targeting ON mix.EntityID = targeting.EntityID + WHERE mix.EntityGroupConfigID = @EntityGroupConfigID + ) + + MERGE TGT AS target + USING #Working_ServiceLineEncounterPayorGroupMix AS src + ON ( + target.BudgetConfigID = src.BudgetConfigID + AND target.EntityGroupConfigID = src.EntityGroupConfigID + AND target.EntityID = src.EntityID + AND target.PatientClassID = src.PatientClassID + AND target.ServiceLineID = src.ServiceLineID + AND target.AgeCohortID = src.AgeCohortID + AND target.MedicalSurgicalID = src.MedicalSurgicalID + AND target.MSDRGID = src.MSDRGID + AND target.CPTID = src.CPTID + AND target.ProviderID = src.ProviderID + AND target.PayorID = src.PayorID + AND target.PayorGroupID = src.PayorGroupID + ) + WHEN MATCHED AND ((target.ProjectionMixPercentage <> src.ProjectionMixPercentage) OR (target.BudgetMixPercentage <> src.BudgetMixPercentage)) + THEN + UPDATE SET target.ProjectionMixPercentage = src.ProjectionMixPercentage, + target.BudgetMixPercentage = src.BudgetMixPercentage + WHEN NOT MATCHED BY TARGET THEN + INSERT (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, PayorID, PayorGroupID, + ProjectionMixPercentage, BudgetMixPercentage) + VALUES (src.BudgetConfigID, src.EntityGroupConfigID, src.EntityID, src.PatientClassID, src.ServiceLineID, src.AgeCohortID, src.MedicalSurgicalID, src.MSDRGID, src.CPTID, src.ProviderID, src.PayorID, src.PayorGroupID, + src.ProjectionMixPercentage, BudgetMixPercentage); + --Important Note (and why this is left commented out). We cannot delete records from these procs because there are multiple procs touching the same table so in the event for example, + --the historical mix was 0, but the non-historical was not 0, the historical proc would incorrectly delete the record because there was no match. Clearing out of invalid data needs to happen outside of this proc + --WHEN NOT MATCHED BY SOURCE THEN DELETE; + END + +END +GO + + +--------------------------------------------- + +-- fp.procPopulateServiceLineEncounterToChargeVolumePayorMix_History +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-01-10 MY JAZZ-31850 Initial +** 2 2022-09-19 BK JAZZ-42503 Filter by EGC immediately instead of during second step +** 3 2023-01-17 BK JAZZ-48267 Update for new data structure +** 4 2023-06-21 MY JAZZ-55363 Clear out data that is no longer valid +** 5 2024-01-11 AO JAZZ-64530 Data transfer for SLE is based on selected Model in Plan Config +*************************************************************/ +CREATE PROCEDURE [fp].[procPopulateServiceLineEncounterToChargeVolumePayorMix_History] + @BudgetConfigID INT, + @EntityGroupConfigID INT, + @IsReimbursementGLEnabled BIT = 0, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + IF OBJECT_ID('tempdb..#TargetingFilter') IS NOT NULL DROP TABLE #TargetingFilter; + IF OBJECT_ID('tempdb..#MixByEntityAndPatientClass') IS NOT NULL DROP TABLE #MixByEntityAndPatientClass; + IF OBJECT_ID('tempdb..#MixByPayorGroup') IS NOT NULL DROP TABLE #MixByPayorGroup; + IF OBJECT_ID('tempdb..#DimesionalityWithRoundingIssues') IS NOT NULL DROP TABLE #DimesionalityWithRoundingIssues; + IF OBJECT_ID('tempdb..#mixesRankedActualYTD') IS NOT NULL DROP TABLE #mixesRankedActualYTD; + IF OBJECT_ID('tempdb..#mixesRankedPriorYearActual') IS NOT NULL DROP TABLE #mixesRankedPriorYearActual; + IF OBJECT_ID('tempdb..#mixesRankedCurrentYearBudget') IS NOT NULL DROP TABLE #mixesRankedCurrentYearBudget; + IF OBJECT_ID('tempdb..#Working_ServiceLineEncounterPayorGroupMix') IS NOT NULL DROP TABLE #Working_ServiceLineEncounterPayorGroupMix; + + CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT); + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED) + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = d.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND ((@IsReimbursementGLEnabled = 1 + AND (bc.DefaultReimbursementNetRevenueModelID = 1 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model + OR rnrm.NetRevenueModelID = 1) + OR @IsReimbursementGLEnabled = 0) + END + + -- Translate the CV Departments to Encounter dimensionality + CREATE TABLE #TargetingFilter (EntityID INT, ServiceLineID INT); + INSERT INTO #TargetingFilter (EntityID, ServiceLineID) + SELECT DISTINCT slecvm.EntityID, ServiceLineID + FROM fp.ServiceLineEncounterChargeVolumeMapping slecvm + INNER JOIN #ChargeVolumeDepartments cv ON cv.DepartmentID = slecvm.DepartmentID + WHERE slecvm.BudgetConfigID = @BudgetConfigID + + IF (@IsDebug = 1) -- Displaying this now so we can clean it up after we don't need the charge table + BEGIN + SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments + END + + -- We no longer need the charge volume departments, so we can drop it here. + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + + CREATE TABLE #Working_ServiceLineEncounterPayorGroupMix ( + [BudgetConfigID] [int] NOT NULL DEFAULT(0), + [EntityGroupConfigID] [int] NOT NULL DEFAULT(0), + [EntityID] [int] NOT NULL DEFAULT(0), + [PatientClassID] [int] NOT NULL DEFAULT(0), + [ServiceLineID] [int] NOT NULL DEFAULT(0), + [AgeCohortID] [int] NOT NULL DEFAULT(0), + [MedicalSurgicalID] [int] NOT NULL DEFAULT(0), + [MSDRGID] [int] NOT NULL DEFAULT(0), + [CPTID] [int] NOT NULL DEFAULT(0), + [ProviderID] [int] NOT NULL DEFAULT(0), + [PayorID] [int] NOT NULL DEFAULT(0), + [PayorGroupID] [int] NOT NULL DEFAULT(0), + [ActualYTDMixPercentage] [decimal](22, 18) NOT NULL DEFAULT(0), + [PriorYearActualMixPercentage] [decimal](22, 18) NOT NULL DEFAULT(0), + [CurrentYearBudgetMixPercentage] [decimal](22, 18) NOT NULL DEFAULT(0) + ) + + -- Find the total values for each payor group + SELECT sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.AgeCohortID, sle.MedicalSurgicalID, sle.MSDRGID, sle.CPTID, sle.ProviderID, sle.PayorID, sle.PayorGroupID, + SUM(hist.ActualYTDValueTotal) AS ActualYTDValueTotal, SUM(hist.PriorYearActualValueTotal) AS PriorYearActualValueTotal, SUM(hist.CurrentYearBudgetTotal) AS CurrentYearBudgetTotal + INTO #MixByPayorGroup + FROM fp.ServiceLineEncounter sle + INNER JOIN fp.ServiceLineEncounterHistory hist ON sle.ServiceLineEncounterID = hist.ServiceLineEncounterID + INNER JOIN #TargetingFilter targeting ON sle.EntityID = targeting.EntityID AND sle.ServiceLineID = targeting.ServiceLineID + WHERE sle.EntityGroupConfigID = @EntityGroupConfigID + GROUP BY sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.AgeCohortID, sle.MedicalSurgicalID, sle.MSDRGID, sle.CPTID, sle.ProviderID, sle.PayorID, sle.PayorGroupID + + -- Find the rolled up values by Service Line / Patient Class + SELECT EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, + SUM(ActualYTDValueTotal) AS ActualYTDValueTotal, SUM(PriorYearActualValueTotal) AS PriorYearActualValueTotal, SUM(CurrentYearBudgetTotal) AS CurrentYearBudgetTotal + INTO #MixByEntityAndPatientClass + FROM #MixByPayorGroup + GROUP BY EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID + + -- Populate Budget, Target, and Projection + INSERT INTO #Working_ServiceLineEncounterPayorGroupMix (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, + MSDRGID, CPTID, ProviderID, PayorID, PayorGroupID, ActualYTDMixPercentage, PriorYearActualMixPercentage, CurrentYearBudgetMixPercentage) + SELECT + @BudgetConfigID, + @EntityGroupConfigID, + pg.EntityID, + pg.PatientClassID, + pg.ServiceLineID, + pg.AgeCohortID, + pg.MedicalSurgicalID, + pg.MSDRGID, + pg.CPTID, + pg.ProviderID, + pg.PayorID, + pg.PayorGroupID, + COALESCE(CAST(pg.ActualYTDValueTotal AS DECIMAL(36, 18)) / CAST(NULLIF(roll.ActualYTDValueTotal, 0) AS DECIMAL(36, 18)), 0) AS ActualYTDMixPercentage, + COALESCE(CAST(pg.PriorYearActualValueTotal AS DECIMAL(36, 18)) / CAST(NULLIF(roll.PriorYearActualValueTotal, 0) AS DECIMAL(36, 18)), 0) AS PriorYearActualMixPercentage, + COALESCE(CAST(pg.CurrentYearBudgetTotal AS DECIMAL(36, 18)) / CAST(NULLIF(roll.CurrentYearBudgetTotal, 0) AS DECIMAL(36, 18)), 0) AS CurrentYearBudgetMixPercentage + FROM #MixByPayorGroup pg + INNER JOIN #MixByEntityAndPatientClass roll ON + pg.EntityID = roll.EntityID + AND pg.PatientClassID = roll.PatientClassID + AND pg.ServiceLineID = roll.ServiceLineID + AND pg.AgeCohortID = roll.AgeCohortID + AND pg.MedicalSurgicalID = roll.MedicalSurgicalID + AND pg.MSDRGID = roll.MSDRGID + AND pg.CPTID = roll.CPTID + AND pg.ProviderID = roll.ProviderID + + --------------------- + -- Rounding + --------------------- + -- Handle rounding issues. Because we can't story infinite amount of data and the raw data ins 18, 9, we can't store a very small decimal. + -- This can lean to small rounding errors where when adding the PayorGroups together, it won't come out to a perfect 1 like it should. + -- Without this logic, when summing up the percentages for a specific ServiceLine, PatientClass, you can have cases where it comes out to 0.9999994 for example. + -- This can be a problem because when we go to apply the dollars later it cause a small fraction of dollars to be missing. While this numbers is very small + -- and likely neglible, we have seen in the past where small numbers can cause discrepancies especially when dealing with larger values. + -- + -- If this logic is working correctly, the following SQL should return nothing: + -- SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, SUM(BudgetMixPercentage) + -- FROM [fp].[ServiceLineEncounterToChargePayorMix] + -- GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID + -- HAVING SUM(BudgetMixPercentage) != 1 AND SUM(BudgetMixPercentage) != 0 + + -- First, find the rounding issues + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, + 1 - SUM(ActualYTDMixPercentage) AS ActualYTDRoundingDifference, + 1 - SUM(PriorYearActualMixPercentage) AS PriorYearActualRoundingDifference, + 1 - SUM(CurrentYearBudgetMixPercentage) AS CurrentYearBudgetRoundingDifference + INTO #DimesionalityWithRoundingIssues + FROM #Working_ServiceLineEncounterPayorGroupMix + GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID + HAVING SUM(ActualYTDMixPercentage) != 1 AND SUM(ActualYTDMixPercentage) != 0 OR + SUM(PriorYearActualMixPercentage) != 1 AND SUM(PriorYearActualMixPercentage) != 0 OR + SUM(CurrentYearBudgetMixPercentage) != 1 AND SUM(CurrentYearBudgetMixPercentage) != 0 + + -- Check Remainder for ActualYTDMix + -- Next we need to find the highest value of each group so we know where we need to put the remainder + SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, + mix.PayorID, mix.PayorGroupID, mix.ActualYTDMixPercentage, rounding.ActualYTDRoundingDifference, + ROW_NUMBER() OVER (PARTITION BY mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID ORDER BY mix.ActualYTDMixPercentage DESC) AS RowID + INTO #mixesRankedActualYTD + FROM #Working_ServiceLineEncounterPayorGroupMix mix + INNER JOIN #DimesionalityWithRoundingIssues rounding ON + mix.EntityID = rounding.EntityID + AND mix.PatientClassID = rounding.PatientClassID + AND mix.ServiceLineID = rounding.ServiceLineID + AND mix.AgeCohortID = rounding.AgeCohortID + AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID + AND mix.MSDRGID = rounding.MSDRGID + AND mix.CPTID = rounding.CPTID + AND mix.ProviderID = rounding.ProviderID + + -- Update the mixed percentage + UPDATE mix + SET mix.ActualYTDMixPercentage = mix.ActualYTDMixPercentage + rounding.ActualYTDRoundingDifference + FROM #Working_ServiceLineEncounterPayorGroupMix mix + INNER JOIN #mixesRankedActualYTD rounding ON + mix.EntityID = rounding.EntityID + AND mix.PatientClassID = rounding.PatientClassID + AND mix.ServiceLineID = rounding.ServiceLineID + AND mix.AgeCohortID = rounding.AgeCohortID + AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID + AND mix.MSDRGID = rounding.MSDRGID + AND mix.CPTID = rounding.CPTID + AND mix.ProviderID = rounding.ProviderID + AND mix.PayorID = rounding.PayorID + AND mix.PayorGroupID = rounding.PayorGroupID + WHERE rounding.RowID = 1 -- We want the highest valued record to dump the remainder + + -- Check Remainder for PriorYearActual + -- Next we need to find the highest value of each group so we know where we need to put the remainder + SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, + mix.PayorID, mix.PayorGroupID, mix.PriorYearActualMixPercentage, rounding.PriorYearActualRoundingDifference, + ROW_NUMBER() OVER (PARTITION BY mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID ORDER BY mix.PriorYearActualMixPercentage DESC) AS RowID + INTO #mixesRankedPriorYearActual + FROM #Working_ServiceLineEncounterPayorGroupMix mix + INNER JOIN #DimesionalityWithRoundingIssues rounding ON + mix.EntityID = rounding.EntityID + AND mix.PatientClassID = rounding.PatientClassID + AND mix.ServiceLineID = rounding.ServiceLineID + AND mix.AgeCohortID = rounding.AgeCohortID + AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID + AND mix.MSDRGID = rounding.MSDRGID + AND mix.CPTID = rounding.CPTID + AND mix.ProviderID = rounding.ProviderID + + -- Update the mixed percentage + UPDATE mix + SET mix.PriorYearActualMixPercentage = mix.PriorYearActualMixPercentage + rounding.PriorYearActualRoundingDifference + FROM #Working_ServiceLineEncounterPayorGroupMix mix + INNER JOIN #mixesRankedPriorYearActual rounding ON + mix.EntityID = rounding.EntityID + AND mix.PatientClassID = rounding.PatientClassID + AND mix.ServiceLineID = rounding.ServiceLineID + AND mix.AgeCohortID = rounding.AgeCohortID + AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID + AND mix.MSDRGID = rounding.MSDRGID + AND mix.CPTID = rounding.CPTID + AND mix.ProviderID = rounding.ProviderID + AND mix.PayorID = rounding.PayorID + AND mix.PayorGroupID = rounding.PayorGroupID + WHERE rounding.RowID = 1 -- We want the highest valued record to dump the remainder + + -- Check Remainder for CurrentYearBudget + -- Next we need to find the highest value of each group so we know where we need to put the remainder + SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, + mix.PayorID, mix.PayorGroupID, mix.CurrentYearBudgetMixPercentage, rounding.CurrentYearBudgetRoundingDifference, + ROW_NUMBER() OVER (PARTITION BY mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID ORDER BY mix.CurrentYearBudgetMixPercentage DESC) AS RowID + INTO #mixesRankedCurrentYearBudget + FROM #Working_ServiceLineEncounterPayorGroupMix mix + INNER JOIN #DimesionalityWithRoundingIssues rounding ON + mix.EntityID = rounding.EntityID + AND mix.PatientClassID = rounding.PatientClassID + AND mix.ServiceLineID = rounding.ServiceLineID + AND mix.AgeCohortID = rounding.AgeCohortID + AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID + AND mix.MSDRGID = rounding.MSDRGID + AND mix.CPTID = rounding.CPTID + AND mix.ProviderID = rounding.ProviderID + + -- Update the mixed percentage + UPDATE mix + SET mix.CurrentYearBudgetMixPercentage = mix.CurrentYearBudgetMixPercentage + rounding.CurrentYearBudgetRoundingDifference + FROM #Working_ServiceLineEncounterPayorGroupMix mix + INNER JOIN #mixesRankedCurrentYearBudget rounding ON + mix.EntityID = rounding.EntityID + AND mix.PatientClassID = rounding.PatientClassID + AND mix.ServiceLineID = rounding.ServiceLineID + AND mix.AgeCohortID = rounding.AgeCohortID + AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID + AND mix.MSDRGID = rounding.MSDRGID + AND mix.CPTID = rounding.CPTID + AND mix.ProviderID = rounding.ProviderID + AND mix.PayorID = rounding.PayorID + AND mix.PayorGroupID = rounding.PayorGroupID + WHERE rounding.RowID = 1 -- We want the highest valued record to dump the remainder + + IF (@IsDebug = 1) + BEGIN + SELECT '#TargetingFilter', * FROM #TargetingFilter + SELECT '#MixByEntityAndPatientClass', * FROM #MixByEntityAndPatientClass + SELECT '#MixByPayorGroup', * FROM #MixByPayorGroup + SELECT '#DimesionalityWithRoundingIssues', * FROM #DimesionalityWithRoundingIssues + SELECT '#mixesRankedActualYTD', * FROM #mixesRankedActualYTD + SELECT '#mixesRankedPriorYearActual', * FROM #mixesRankedPriorYearActual + SELECT '#mixesRankedCurrentYearBudget', * FROM #mixesRankedCurrentYearBudget + SELECT '#Working_ServiceLineEncounterPayorGroupMix', * FROM #Working_ServiceLineEncounterPayorGroupMix + END ELSE + BEGIN + -- Publish + ;WITH TGT AS + ( + SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, mix.PayorID, mix.PayorGroupID, + mix.ActualYTDMixPercentage, mix.PriorYearActualMixPercentage, mix.CurrentYearBudgetMixPercentage + FROM [fp].[ServiceLineEncounterToChargePayorMix] mix + INNER JOIN (SELECT DISTINCT EntityID FROM #TargetingFilter) targeting ON mix.EntityID = targeting.EntityID + WHERE mix.EntityGroupConfigID = @EntityGroupConfigID + ) + + MERGE TGT AS target + USING #Working_ServiceLineEncounterPayorGroupMix AS src + ON ( + target.BudgetConfigID = src.BudgetConfigID + AND target.EntityGroupConfigID = src.EntityGroupConfigID + AND target.EntityID = src.EntityID + AND target.PatientClassID = src.PatientClassID + AND target.ServiceLineID = src.ServiceLineID + AND target.AgeCohortID = src.AgeCohortID + AND target.MedicalSurgicalID = src.MedicalSurgicalID + AND target.MSDRGID = src.MSDRGID + AND target.CPTID = src.CPTID + AND target.ProviderID = src.ProviderID + AND target.PayorID = src.PayorID + AND target.PayorGroupID = src.PayorGroupID + ) + WHEN MATCHED AND ( + target.ActualYTDMixPercentage <> src.ActualYTDMixPercentage OR + target.PriorYearActualMixPercentage <> src.PriorYearActualMixPercentage OR + target.CurrentYearBudgetMixPercentage <> src.CurrentYearBudgetMixPercentage + ) + THEN + UPDATE SET + target.ActualYTDMixPercentage = src.ActualYTDMixPercentage, + target.PriorYearActualMixPercentage = src.PriorYearActualMixPercentage, + target.CurrentYearBudgetMixPercentage = src.CurrentYearBudgetMixPercentage + WHEN NOT MATCHED BY TARGET THEN + INSERT (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, PayorID, PayorGroupID, + ActualYTDMixPercentage, PriorYearActualMixPercentage, CurrentYearBudgetMixPercentage) + VALUES (src.BudgetConfigID, src.EntityGroupConfigID, src.EntityID, src.PatientClassID, src.ServiceLineID, src.AgeCohortID, src.MedicalSurgicalID, src.MSDRGID, src.CPTID, src.ProviderID, src.PayorID, src.PayorGroupID, + src.ActualYTDMixPercentage, src.PriorYearActualMixPercentage, src.CurrentYearBudgetMixPercentage); + --Important Note (and why this is left commented out). We cannot delete records from these procs because there are multiple procs touching the same table so in the event for example, + --the historical mix was 0, but the non-historical was not 0, the historical proc would incorrectly delete the record because there was no match. Clearing out of invalid data needs to happen outside of this proc + --WHEN NOT MATCHED BY SOURCE THEN DELETE; + END + +END +GO + + +--------------------------------------------- + +-- fp.procPopulateServiceLineEncounterToChargeVolumePayorMix_Initial +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-01-10 MY JAZZ-31850 Initial +** 2 2023-01-17 BK JAZZ-48267 Update for new data structure +** 3 2023-06-21 MY JAZZ-55363 Clear out data that is no longer valid +** 4 2024-01-11 AO JAZZ-64530 Data transfer for SLE is based on selected Model in Plan Config +** 5 2024-09-16 MY JAZZ-70683 Add Initial Projection Mix for Reimbursement/Charge to General Ledger Mix +*************************************************************/ +CREATE PROCEDURE [fp].[procPopulateServiceLineEncounterToChargeVolumePayorMix_Initial] + @BudgetConfigID INT, + @EntityGroupConfigID INT, + @IsReimbursementGLEnabled BIT = 0, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + IF OBJECT_ID('tempdb..#TargetingFilter') IS NOT NULL DROP TABLE #TargetingFilter; + IF OBJECT_ID('tempdb..#MixByEntityAndPatientClass') IS NOT NULL DROP TABLE #MixByEntityAndPatientClass; + IF OBJECT_ID('tempdb..#MixByPayorGroup') IS NOT NULL DROP TABLE #MixByPayorGroup; + IF OBJECT_ID('tempdb..#DimesionalityWithRoundingIssues') IS NOT NULL DROP TABLE #DimesionalityWithRoundingIssues; + IF OBJECT_ID('tempdb..#mixesRankedBudget') IS NOT NULL DROP TABLE #mixesRankedBudget; + IF OBJECT_ID('tempdb..#mixesRankedProjection') IS NOT NULL DROP TABLE #mixesRankedProjection; + IF OBJECT_ID('tempdb..#Working_ServiceLineEncounterPayorGroupMix') IS NOT NULL DROP TABLE #Working_ServiceLineEncounterPayorGroupMix; + + -- JAZZ-70683: Add Initial Projection Mix for Reimbursement/Charge to General Ledger Mix + DECLARE @IsProjectionMixEnabled BIT = ISNULL((SELECT Value + FROM fp.viewBudgetConfigSetting setting + INNER JOIN fp.BudgetConfig bc ON setting.BudgetConfigID = bc.BudgetConfigID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE egc.EntityGroupConfigID = @EntityGroupConfigID + AND setting.Name = 'Enable Initial Projection Mix for Encounter to Charge Payor Group Mix'), 0) + + CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT); + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED) + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = d.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE d.BudgetConfigID = @BudgetConfigID + AND ((@IsReimbursementGLEnabled = 1 + AND (bc.DefaultReimbursementNetRevenueModelID = 1 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model + OR rnrm.NetRevenueModelID = 1) + OR @IsReimbursementGLEnabled = 0) + END + + -- Translate the CV Departments to Encounter dimensionality + CREATE TABLE #TargetingFilter (EntityID INT, ServiceLineID INT); + INSERT INTO #TargetingFilter (EntityID, ServiceLineID) + SELECT DISTINCT slecvm.EntityID, ServiceLineID + FROM fp.ServiceLineEncounterChargeVolumeMapping slecvm + INNER JOIN #ChargeVolumeDepartments cv ON cv.DepartmentID = slecvm.DepartmentID + INNER JOIN fp.BudgetConfig bc ON slecvm.BudgetConfigID = bc.BudgetConfigID + INNER JOIN fp.EntityGroupConfig egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfigMapping egcm ON egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID AND egcm.EntityID = slecvm.EntityID + WHERE slecvm.BudgetConfigID = @BudgetConfigID + AND egc.EntityGroupConfigID = @EntityGroupConfigID + + IF (@IsDebug = 1) -- Displaying this now so we can clean it up after we don't need the charge table + BEGIN + SELECT '#ChargeVolumeDepartments', * FROM #ChargeVolumeDepartments + END + + -- We no longer need the charge volume departments, so we can drop it here. + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + + CREATE TABLE #Working_ServiceLineEncounterPayorGroupMix ( + [BudgetConfigID] [int] NOT NULL DEFAULT(0), + [EntityGroupConfigID] [int] NOT NULL DEFAULT(0), + [EntityID] [int] NOT NULL DEFAULT(0), + [PatientClassID] [int] NOT NULL DEFAULT(0), + [ServiceLineID] [int] NOT NULL DEFAULT(0), + [AgeCohortID] [int] NOT NULL DEFAULT(0), + [MedicalSurgicalID] [int] NOT NULL DEFAULT(0), + [MSDRGID] [int] NOT NULL DEFAULT(0), + [CPTID] [int] NOT NULL DEFAULT(0), + [ProviderID] [int] NOT NULL DEFAULT(0), + [PayorID] [int] NOT NULL DEFAULT(0), + [PayorGroupID] [int] NOT NULL DEFAULT(0), + [InitialMixPercentage] [decimal](22, 18) NOT NULL DEFAULT(0), + [InitialProjectionMixPercentage] [decimal](22, 18) NOT NULL DEFAULT(0) + ) + + -- Find the total values for each payor group + SELECT sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.AgeCohortID, sle.MedicalSurgicalID, sle.MSDRGID, sle.CPTID, sle.ProviderID, sle.PayorID, sle.PayorGroupID, + SUM(sle.InitialBudgetTotal) AS BudgetTotal, SUM(sle.InitialProjectionTotal) AS ProjectionTotal + INTO #MixByPayorGroup + FROM fp.ServiceLineEncounter sle + INNER JOIN #TargetingFilter targeting ON sle.EntityID = targeting.EntityID AND sle.ServiceLineID = targeting.ServiceLineID + WHERE sle.EntityGroupConfigID = @EntityGroupConfigID + GROUP BY sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.AgeCohortID, sle.MedicalSurgicalID, sle.MSDRGID, sle.CPTID, sle.ProviderID, sle.PayorID, sle.PayorGroupID + + -- Find the rolled up values by Service Line / Patient Class + SELECT EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, SUM(BudgetTotal) AS BudgetTotal, SUM(ProjectionTotal) AS ProjectionTotal + INTO #MixByEntityAndPatientClass + FROM #MixByPayorGroup + GROUP BY EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID + + -- Populate Budget, Target, and Projection + INSERT INTO #Working_ServiceLineEncounterPayorGroupMix (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, + MSDRGID, CPTID, ProviderID, PayorID, PayorGroupID, InitialMixPercentage, InitialProjectionMixPercentage) + SELECT + @BudgetConfigID, + @EntityGroupConfigID, + pg.EntityID, + pg.PatientClassID, + pg.ServiceLineID, + pg.AgeCohortID, + pg.MedicalSurgicalID, + pg.MSDRGID, + pg.CPTID, + pg.ProviderID, + pg.PayorID, + pg.PayorGroupID, + COALESCE(CAST(pg.BudgetTotal AS DECIMAL(36, 18)) / CAST(NULLIF(roll.BudgetTotal, 0) AS DECIMAL(36, 18)), 0) AS InitialMixPercentage, + COALESCE(CAST(pg.ProjectionTotal AS DECIMAL(36, 18)) / CAST(NULLIF(roll.ProjectionTotal, 0) AS DECIMAL(36, 18)), 0) AS InitialProjectionMixPercentage + FROM #MixByPayorGroup pg + INNER JOIN #MixByEntityAndPatientClass roll ON + pg.EntityID = roll.EntityID + AND pg.PatientClassID = roll.PatientClassID + AND pg.ServiceLineID = roll.ServiceLineID + AND pg.AgeCohortID = roll.AgeCohortID + AND pg.MedicalSurgicalID = roll.MedicalSurgicalID + AND pg.MSDRGID = roll.MSDRGID + AND pg.CPTID = roll.CPTID + AND pg.ProviderID = roll.ProviderID + + --------------------- + -- Rounding + --------------------- + -- Handle rounding issues. Because we can't story infinite amount of data and the raw data ins 18, 9, we can't store a very small decimal. + -- This can lean to small rounding errors where when adding the PayorGroups together, it won't come out to a perfect 1 like it should. + -- Without this logic, when summing up the percentages for a specific ServiceLine, PatientClass, you can have cases where it comes out to 0.9999994 for example. + -- This can be a problem because when we go to apply the dollars later it cause a small fraction of dollars to be missing. While this numbers is very small + -- and likely neglible, we have seen in the past where small numbers can cause discrepancies especially when dealing with larger values. + -- + -- If this logic is working correctly, the following SQL should return nothing: + -- SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, SUM(BudgetMixPercentage) + -- FROM [fp].[ServiceLineEncounterToChargePayorMix] + -- GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID + -- HAVING SUM(BudgetMixPercentage) != 1 AND SUM(BudgetMixPercentage) != 0 + + -- First, find the rounding issues + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, + 1 - SUM(InitialMixPercentage) AS BudgetRoundingDifference + INTO #DimesionalityWithRoundingIssues + FROM #Working_ServiceLineEncounterPayorGroupMix + GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID + HAVING SUM(InitialMixPercentage) != 1 AND SUM(InitialMixPercentage) != 0 + + -- Check Remainder for Budget + -- Next we need to find the highest value of each group so we know where we need to put the remainder + SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, + mix.PayorID, mix.PayorGroupID, mix.InitialMixPercentage, rounding.BudgetRoundingDifference, ROW_NUMBER() OVER (PARTITION BY mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID ORDER BY mix.InitialMixPercentage DESC) AS RowID + INTO #mixesRankedBudget + FROM #Working_ServiceLineEncounterPayorGroupMix mix + INNER JOIN #DimesionalityWithRoundingIssues rounding ON + mix.EntityID = rounding.EntityID + AND mix.PatientClassID = rounding.PatientClassID + AND mix.ServiceLineID = rounding.ServiceLineID + AND mix.AgeCohortID = rounding.AgeCohortID + AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID + AND mix.MSDRGID = rounding.MSDRGID + AND mix.CPTID = rounding.CPTID + AND mix.ProviderID = rounding.ProviderID + + -- Update the mixed percentage + UPDATE mix + SET mix.InitialMixPercentage = mix.InitialMixPercentage + rounding.BudgetRoundingDifference + FROM #Working_ServiceLineEncounterPayorGroupMix mix + INNER JOIN #mixesRankedBudget rounding ON + mix.EntityID = rounding.EntityID + AND mix.PatientClassID = rounding.PatientClassID + AND mix.ServiceLineID = rounding.ServiceLineID + AND mix.AgeCohortID = rounding.AgeCohortID + AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID + AND mix.MSDRGID = rounding.MSDRGID + AND mix.CPTID = rounding.CPTID + AND mix.ProviderID = rounding.ProviderID + AND mix.PayorID = rounding.PayorID + AND mix.PayorGroupID = rounding.PayorGroupID + WHERE rounding.RowID = 1 -- We want the highest valued record to dump the remainder + + IF (@IsProjectionMixEnabled = 1) + BEGIN + + -------------------------------------------------------- + -- Projection + -------------------------------------------------------- + + -- First, find the rounding issues + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, + 1 - SUM(InitialProjectionMixPercentage) AS RoundingDifference + INTO #DimesionalityWithRoundingIssues_Projection + FROM #Working_ServiceLineEncounterPayorGroupMix + GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID + HAVING SUM(InitialProjectionMixPercentage) != 1 AND SUM(InitialProjectionMixPercentage) != 0 + + -- Check Remainder for Budget + -- Next we need to find the highest value of each group so we know where we need to put the remainder + SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, + mix.PayorID, mix.PayorGroupID, mix.InitialProjectionMixPercentage, rounding.RoundingDifference, ROW_NUMBER() OVER (PARTITION BY mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID ORDER BY mix.InitialMixPercentage DESC) AS RowID + INTO #mixesRankedProjection + FROM #Working_ServiceLineEncounterPayorGroupMix mix + INNER JOIN #DimesionalityWithRoundingIssues_Projection rounding ON + mix.EntityID = rounding.EntityID + AND mix.PatientClassID = rounding.PatientClassID + AND mix.ServiceLineID = rounding.ServiceLineID + AND mix.AgeCohortID = rounding.AgeCohortID + AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID + AND mix.MSDRGID = rounding.MSDRGID + AND mix.CPTID = rounding.CPTID + AND mix.ProviderID = rounding.ProviderID + + -- Update the mixed percentage + UPDATE mix + SET mix.InitialProjectionMixPercentage = mix.InitialProjectionMixPercentage + rounding.RoundingDifference + FROM #Working_ServiceLineEncounterPayorGroupMix mix + INNER JOIN #mixesRankedProjection rounding ON + mix.EntityID = rounding.EntityID + AND mix.PatientClassID = rounding.PatientClassID + AND mix.ServiceLineID = rounding.ServiceLineID + AND mix.AgeCohortID = rounding.AgeCohortID + AND mix.MedicalSurgicalID = rounding.MedicalSurgicalID + AND mix.MSDRGID = rounding.MSDRGID + AND mix.CPTID = rounding.CPTID + AND mix.ProviderID = rounding.ProviderID + AND mix.PayorID = rounding.PayorID + AND mix.PayorGroupID = rounding.PayorGroupID + WHERE rounding.RowID = 1 -- We want the highest valued record to dump the remainder + + END + + IF (@IsDebug = 1) + BEGIN + SELECT '#TargetingFilter', * FROM #TargetingFilter + SELECT '#MixByEntityAndPatientClass', * FROM #MixByEntityAndPatientClass + SELECT '#MixByPayorGroup', * FROM #MixByPayorGroup + SELECT '#DimesionalityWithRoundingIssues', * FROM #DimesionalityWithRoundingIssues + SELECT '#mixesRankedBudget', * FROM #mixesRankedBudget + SELECT '#Working_ServiceLineEncounterPayorGroupMix', * FROM #Working_ServiceLineEncounterPayorGroupMix + END ELSE + BEGIN + -- Publish + ;WITH TGT AS + ( + SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, mix.PayorID, mix.PayorGroupID, + mix.InitialMixPercentage + FROM [fp].[ServiceLineEncounterToChargePayorMix] mix + INNER JOIN (SELECT DISTINCT EntityID FROM #TargetingFilter) targeting ON mix.EntityID = targeting.EntityID + WHERE mix.EntityGroupConfigID = @EntityGroupConfigID + ) + + MERGE TGT AS target + USING #Working_ServiceLineEncounterPayorGroupMix AS src + ON ( + target.BudgetConfigID = src.BudgetConfigID + AND target.EntityGroupConfigID = src.EntityGroupConfigID + AND target.EntityID = src.EntityID + AND target.PatientClassID = src.PatientClassID + AND target.ServiceLineID = src.ServiceLineID + AND target.AgeCohortID = src.AgeCohortID + AND target.MedicalSurgicalID = src.MedicalSurgicalID + AND target.MSDRGID = src.MSDRGID + AND target.CPTID = src.CPTID + AND target.ProviderID = src.ProviderID + AND target.PayorID = src.PayorID + AND target.PayorGroupID = src.PayorGroupID + ) + WHEN MATCHED AND (target.InitialMixPercentage <> src.InitialMixPercentage) + THEN + UPDATE SET target.InitialMixPercentage = src.InitialMixPercentage + WHEN NOT MATCHED BY TARGET THEN + INSERT (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, PayorID, PayorGroupID, + InitialMixPercentage) + VALUES (src.BudgetConfigID, src.EntityGroupConfigID, src.EntityID, src.PatientClassID, src.ServiceLineID, src.AgeCohortID, src.MedicalSurgicalID, src.MSDRGID, src.CPTID, src.ProviderID, src.PayorID, src.PayorGroupID, + src.InitialMixPercentage); + --Important Note (and why this is left commented out). We cannot delete records from these procs because there are multiple procs touching the same table so in the event for example, + --the historical mix was 0, but the non-historical was not 0, the historical proc would incorrectly delete the record because there was no match. Clearing out of invalid data needs to happen outside of this proc + --WHEN NOT MATCHED BY SOURCE THEN DELETE; + + IF (@IsProjectionMixEnabled = 1) + BEGIN + + -- Publish + ;WITH TGT AS + ( + SELECT mix.BudgetConfigID, mix.EntityGroupConfigID, mix.EntityID, mix.PatientClassID, mix.ServiceLineID, mix.AgeCohortID, mix.MedicalSurgicalID, mix.MSDRGID, mix.CPTID, mix.ProviderID, mix.PayorID, mix.PayorGroupID, + mix.InitialProjectionMixPercentage + FROM [fp].[ServiceLineEncounterToChargePayorMix] mix + INNER JOIN (SELECT DISTINCT EntityID FROM #TargetingFilter) targeting ON mix.EntityID = targeting.EntityID + WHERE mix.EntityGroupConfigID = @EntityGroupConfigID + ) + + MERGE TGT AS target + USING #Working_ServiceLineEncounterPayorGroupMix AS src + ON ( + target.BudgetConfigID = src.BudgetConfigID + AND target.EntityGroupConfigID = src.EntityGroupConfigID + AND target.EntityID = src.EntityID + AND target.PatientClassID = src.PatientClassID + AND target.ServiceLineID = src.ServiceLineID + AND target.AgeCohortID = src.AgeCohortID + AND target.MedicalSurgicalID = src.MedicalSurgicalID + AND target.MSDRGID = src.MSDRGID + AND target.CPTID = src.CPTID + AND target.ProviderID = src.ProviderID + AND target.PayorID = src.PayorID + AND target.PayorGroupID = src.PayorGroupID + ) + WHEN MATCHED AND (target.InitialProjectionMixPercentage <> src.InitialProjectionMixPercentage) + THEN + UPDATE SET target.InitialProjectionMixPercentage = src.InitialProjectionMixPercentage + WHEN NOT MATCHED BY TARGET THEN + INSERT (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, PayorID, PayorGroupID, + InitialProjectionMixPercentage) + VALUES (src.BudgetConfigID, src.EntityGroupConfigID, src.EntityID, src.PatientClassID, src.ServiceLineID, src.AgeCohortID, src.MedicalSurgicalID, src.MSDRGID, src.CPTID, src.ProviderID, src.PayorID, src.PayorGroupID, + src.InitialProjectionMixPercentage); + --Important Note (and why this is left commented out). We cannot delete records from these procs because there are multiple procs touching the same table so in the event for example, + --the historical mix was 0, but the non-historical was not 0, the historical proc would incorrectly delete the record because there was no match. Clearing out of invalid data needs to happen outside of this proc + --WHEN NOT MATCHED BY SOURCE THEN DELETE; + + END + END + +END +GO + + +--------------------------------------------- + +-- fp.procPopulateStaffingVariabilityByBudgetConfig_PayCode +CREATE PROC fp.procPopulateStaffingVariabilityByBudgetConfig_PayCode + @BudgetConfigID INT +AS +BEGIN + DECLARE @EntityGroupConfigGuid UNIQUEIDENTIFIER + DECLARE @EntityGroupConfigId INT + DECLARE @FiscalYearId INT + + DECLARE entityGroupConfigCrs CURSOR FOR + SELECT + EntityGroupConfigGUID, + EntityGroupConfigID, + FiscalYearID + FROM [fp].[EntityGroupConfig] egc + INNER JOIN [fp].[BudgetConfig] bc on egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigId; + + OPEN entityGroupConfigCrs + + FETCH NEXT FROM entityGroupConfigCrs INTO @EntityGroupConfigGuid, @EntityGroupConfigId, @FiscalYearId + + WHILE @@FETCH_STATUS = 0 + BEGIN + EXEC [fp].[procPopulateStaffingVariability_PayCode] @EntityGroupConfigGuid, @EntityGroupConfigId, @FiscalYearId + + FETCH NEXT FROM entityGroupConfigCrs INTO @EntityGroupConfigGuid, @EntityGroupConfigId, @FiscalYearId + END + + CLOSE entityGroupConfigCrs; + DEALLOCATE entityGroupConfigCrs; +END +GO + + +--------------------------------------------- + +-- fp.procPopulateStaffingVariability_PayCode +CREATE PROCEDURE [fp].[procPopulateStaffingVariability_PayCode] + @EntityGroupConfigGUID UNIQUEIDENTIFIER, + @EntityGroupConfigID INT, + @FiscalYearID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 + AS + BEGIN + + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-06-30 MD JAZZ-13102 Use original department when populating variability + ** 2 2022-08-16 MY JAZZ-40590 Exclude Dollars Only from Variability + ** 3 2022-11-07 MY JAZZ-35951 Refactor and add debug + ** 4 2022-11-07 MY JAZZ-35951 Add Employee to FactStaffingVariabilityDetail + ** 5 2023-04-24 NT JAZZ-53870 Add option recompile to improve performance + ** 6 2023-09-20 BK JAZZ-60973 Update for new data structure + ** 7 2024-01-30 BK JAZZ-63880 Change JobCodeID and PayCodeID to int from smallint + ** 8 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config + ** 9 2024-05-09 AO JAZZ-71284 Added index to #staffingDim to improve performance + ** 10 2024-06-25 JB JAZZ-72523 Added index to #StaffingVariability and #providerVariability + *************************************************************/ + + SET NOCOUNT ON; + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#staffingDim') IS NOT NULL DROP TABLE #staffingDim + IF OBJECT_ID('tempdb..#staffingVariability') IS NOT NULL DROP TABLE #staffingVariability + IF OBJECT_ID('tempdb..#providerVariability') IS NOT NULL DROP TABLE #providerVariability + IF OBJECT_ID('tempdb..#StaffingVariabilityDetail') IS NOT NULL DROP TABLE #StaffingVariabilityDetail + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fp.Staffing + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + DECLARE @StaffingSubsectionID INT, + @ProviderSubsectionID INT, + @BudgetConfigID INT, + @IsProviderPlanningEnabled BIT, + @IsForceDollarsOnlyToFixedFlag BIT; + + SELECT @BudgetConfigID = BudgetConfigID FROM fp.EntityGroupConfig egc INNER JOIN fp.BudgetConfig b on egc.BudgetConfigGUID = b.BudgetConfigGUID WHERE egc.EntityGroupConfigGUID = @EntityGroupConfigGUID + SET @IsForceDollarsOnlyToFixedFlag = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting WHERE Name = 'Force Dollars Only to be Fixed' AND BudgetConfigID = @BudgetConfigID), 0); + + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID; + + SELECT @StaffingSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Staffing' + SELECT @ProviderSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Provider' + + CREATE TABLE #staffingDim (DepartmentID INT, JobCodeID INT, PayCodeID INT, ProviderLineItemID INT, SubsectionID INT, INDEX BASE CLUSTERED (SubsectionID, DepartmentID) ); + CREATE TABLE #StaffingVariabilityDetail (EntityGroupConfigGUID UNIQUEIDENTIFIER, DepartmentID INT, JobCodeID INT, PayCodeID INT, ProviderLineItemID INT, EmployeeID INT, FixedPercentage DECIMAL(19, 8)) + + /* + NOTE ABOUT JAZZ-35951 + ----------------------------- + We now store variability at the Employee level, this is to allow cases where a Department/Job Code combination is set to variable, however + it has employee budgeting enabled and they add an employee to it. This would add the employee, but we want it to be 100% Fixed. + + Employees in Employee Budgeting are always 100% Fixed. This is why we are setting EmployeeID = 0, essentially all rows where EmployeeID > 0, it should + always have a Fixed Percentage of 100%. Anything that is variable is going to have EmployeeID = 0. + */ + + IF EXISTS(SELECT 1 FROM [fp].[EntityGroupConfig] WHERE IsPatientActivityFlexingForStaffing = 1 AND EntityGroupConfigGUID = @EntityGroupConfigGUID ) + BEGIN + ------------------------------------------------------------------------------------------- + -- Patient Activity + ------------------------------------------------------------------------------------------- + INSERT INTO #StaffingVariabilityDetail (EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeID, FixedPercentage, ProviderLineItemID, EmployeeID) + SELECT + a.EntityGroupConfigGUID, + a.DepartmentID, + a.JobCodeID, + a.PayCodeID, + a.FixedPercentage, + -- Employee and Provider Line Item will not be on the Detailed Costing table and thus not used + 0 as ProviderLineItemID, + 0 as EmployeeID + FROM ( + SELECT + fp.EntityGroupConfigGUID, + fp.DepartmentID, + fp.JobCodeID, + fp.PayCodeID, + CASE + WHEN TotalCost = 0 THEN 0 + WHEN (TotalFixedDirectCost/TotalCost) > .9999 THEN 1.0 + ELSE (TotalFixedDirectCost/TotalCost) + END AS [FixedPercentage], + COALESCE(conovr.FlexMethodID, fp.FlexMethodID) as [FlexMethodID] + FROM ( + SELECT + ec.EntityGroupConfigGuid, + pay.OriginalDepartmentID as DepartmentID, --use original department (not reclassed) to insert into fp tables + pay.OriginalJobCodeID as JobCodeID, + pay.OriginalPayCodeID as PayCodeID, + fc.FlexMethodID, + SUM(pay.FixedDirectUnitCost * pay.Volume) as TotalFixedDirectCost, + SUM(pay.TotalCost) as TotalCost + FROM + [dss].[FactCostingOutDetailPayroll] pay + INNER JOIN [dss].[CostingResult] cr on pay.CostingResultID = cr.CostingResultID + INNER JOIN [fp].[EntityGroupConfig] ec on cr.CostingConfigGuid = ec.CostingConfigGUID + INNER JOIN [fp].[StaffingExpenseFlexingConfig] fc ON fc.EntityGroupConfigGUID = ec.EntityGroupConfigGUID AND fc.DepartmentID = pay.OriginalDepartmentID + INNER JOIN fw.DimPayCode pc ON pay.OriginalPayCodeID = pc.PayCodeID + INNER JOIN fw.DimPayCodeGroup pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = pay.OriginalDepartmentID + WHERE + pay.CostingResultID in (select max(cr2.CostingResultID) from [dss].[CostingResult] cr2 where cr2.CostingConfigGuid = ec.CostingConfigGuid and cr2.IsActivityBasedDetail = 1 and cr2.IsMarkedForDeletion = 0 and cr2.IsFailure = 0) + AND pay.TimeClassID = ec.CostingConfigTimeClassID + AND ec.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND (@IsForceDollarsOnlyToFixedFlag = 0 OR pcg.ProductiveClassID != 4) -- 4 = Dollars Only; + GROUP BY + ec.EntityGroupConfigGuid, pay.OriginalDepartmentID, pay.OriginalJobCodeID, pay.OriginalPayCodeID, pay.FiscalYearID, fc.FlexMethodID + ) fp + LEFT JOIN [fp].[StaffingFlexingOverrideConfig] conovr + ON fp.EntityGroupConfigGuid = conovr.EntityGroupConfigGuid + AND fp.DepartmentID = conovr.DepartmentID + AND fp.JobCodeID = conovr.JobCodeID + ) a + WHERE + a.FlexMethodID = 2 + AND FixedPercentage < 1 + + IF (@IsDebug = 1) + BEGIN + SELECT 'After Patient Activity Flexing', @EntityGroupConfigGUID AS EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeID, ProviderLineItemID, EmployeeID, FixedPercentage + FROM #StaffingVariabilityDetail + END + END + + ------------------------------------------------------------------------------------------- + -- Process Regular (Non-Paf) Variability + ------------------------------------------------------------------------------------------- + + INSERT INTO #staffingDim (DepartmentID, JobCodeID, PayCodeID, ProviderLineItemID, SubsectionID) + SELECT DISTINCT + fs.DepartmentID, + JobCodeID, + ISNULL(pc.PayCodeID, 0) as PayCodeID, + fs.ProviderLineItemID, + fs.SubsectionID + FROM [fp].[Staffing] fs + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = fs.DepartmentID + LEFT JOIN [fw].[DimPayCode] pc ON fs.PayCodeGroupID = pc.PayCodeGroupID + LEFT JOIN [fw].[DimPayCodeGroup] pcg ON fs.PayCodeGroupID = pcg.PayCodeGroupID + -- limit to variability = 1 only to make query faster, all unit types should be there but we only need Dept/JobCode/PayCode/ProviderLineItem/Employee + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.VariabilityID = 1 + AND (@IsForceDollarsOnlyToFixedFlag = 0 OR fs.ProductiveClassID != 4 AND pcg.ProductiveClassID != 4) -- 4 = Dollars Only; + + ------------------------------------------------------------------------------------------- + -- Regular Staffing Variability + ------------------------------------------------------------------------------------------- + CREATE TABLE #StaffingVariability ( + DepartmentID INT, + JobCodeID INT, + PayCodeID INT, + FixedPercentage DECIMAL(19, 8), + ProviderLineItemID INT, + EmployeeID INT +); + +INSERT INTO #StaffingVariability (DepartmentID, JobCodeID, PayCodeID, FixedPercentage, ProviderLineItemID, EmployeeID) + SELECT + a.DepartmentID, + a.JobCodeID, + fs.PayCodeID, + a.FixedPercentage, + 0 as ProviderLineItemID, + 0 as EmployeeID + FROM + ( + SELECT + pvc.EntityGroupConfigGUID, + COALESCE(conovr.DepartmentID, efc.DepartmentID) AS 'DepartmentID', + COALESCE(conovr.JobCodeID, pvc.JobCodeID) AS 'JobCodeID', + (1 - COALESCE(varovr.Variability, pvc.Variability)) AS 'FixedPercentage', + COALESCE(conovr.FlexMethodID, efc.FlexMethodID) AS 'FlexMethodID' + FROM + [fp].[PayrollVariabilityConfig] pvc + INNER JOIN [fp].[StaffingExpenseFlexingConfig] efc ON pvc.EntityGroupConfigGUID = efc.EntityGroupConfigGUID + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = efc.DepartmentID + LEFT JOIN [fp].[StaffingVariabilityOverrideConfig] varovr ON efc.EntityGroupConfigGUID = varovr.EntityGroupConfigGUID AND efc.DepartmentID = varovr.DepartmentID AND pvc.JobCodeID = varovr.JobCodeID + LEFT JOIN [fp].[StaffingFlexingOverrideConfig] conovr ON efc.EntityGroupConfigGUID = conovr.EntityGroupConfigGUID AND efc.DepartmentID = conovr.DepartmentID AND pvc.JobCodeID = conovr.JobCodeID + WHERE + pvc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND COALESCE(conovr.FlexMethodID, efc.FlexMethodID) = 1 + AND COALESCE(varovr.Variability, pvc.Variability) != 0 + ) a + INNER JOIN + ( + SELECT DISTINCT + DepartmentID, + JobCodeID, + PayCodeID + FROM #staffingDim + WHERE SubSectionID = @StaffingSubsectionID + ) fs ON fs.DepartmentID = a.DepartmentID AND fs.JobCodeID = a.JobCodeID + OPTION (RECOMPILE); +CREATE INDEX idx_staffingVariability ON #StaffingVariability (DepartmentID, JobCodeID); + + ------------------------------------------------------------------------------------------- + -- Provider Staffing Variability (overrides regular Staffing Variability) + ------------------------------------------------------------------------------------------- + + CREATE TABLE #ProviderVariability ( + DepartmentID INT, + JobCodeID INT, + PayCodeID INT, + ProviderLineItemID INT, + EmployeeID INT, + ProviderFixedPercentage DECIMAL(19, 8) +); + +INSERT INTO #ProviderVariability (DepartmentID, JobCodeID, PayCodeID, ProviderLineItemID, EmployeeID, ProviderFixedPercentage) + SELECT DISTINCT + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeID, + fs.ProviderLineItemID, + 0 as EmployeeID, + CASE WHEN psc.VariabilityID = 1 THEN 1 ELSE 0 END as ProviderFixedPercentage + FROM #staffingDim fs + INNER JOIN [fp].[ProviderStaffingConfig] psc ON fs.ProviderLineItemID = psc.ProviderLineItemID + LEFT JOIN ( + SELECT + COALESCE(conovr.DepartmentID, efc.DepartmentID) AS 'DepartmentID' + FROM + [fp].[PayrollVariabilityConfig] pvc + INNER JOIN [fp].[StaffingExpenseFlexingConfig] efc ON pvc.EntityGroupConfigGUID = efc.EntityGroupConfigGUID + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = efc.DepartmentID + LEFT JOIN [fp].[StaffingVariabilityOverrideConfig] varovr ON efc.EntityGroupConfigGUID = varovr.EntityGroupConfigGUID AND efc.DepartmentID = varovr.DepartmentID AND pvc.JobCodeID = varovr.JobCodeID + LEFT JOIN [fp].[StaffingFlexingOverrideConfig] conovr ON efc.EntityGroupConfigGUID = conovr.EntityGroupConfigGUID AND efc.DepartmentID = conovr.DepartmentID AND pvc.JobCodeID = conovr.JobCodeID + WHERE + pvc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND COALESCE(conovr.FlexMethodID, efc.FlexMethodID) = 6 + ) fixed ON fs.DepartmentID = fixed.DepartmentID + WHERE fs.SubSectionID = @ProviderSubsectionID + AND @IsProviderPlanningEnabled = 1 + AND fixed.DepartmentID IS NULL + AND psc.BudgetConfigID = @BudgetConfigID +CREATE INDEX idx_providerVariability ON #ProviderVariability (DepartmentID, JobCodeID); + + ------------------------------------------------------------------------------------------- + -- Stat Accounts + ------------------------------------------------------------------------------------------- + INSERT INTO #StaffingVariabilityDetail (EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeID, FixedPercentage, ProviderLineItemID, EmployeeID) + SELECT + @EntityGroupConfigGUID, + s.DepartmentID, + s.JobCodeID, + s.PayCodeID, + s.FixedPercentage, + 0 as ProviderLineItemID, + 0 as EmployeeID + FROM #StaffingVariability s + LEFT JOIN #ProviderVariability p ON s.DepartmentID = p.DepartmentID AND s.JobCodeID = p.JobCodeID + WHERE p.DepartmentID IS NULL + AND p.JobCodeID IS NULL + + IF (@IsDebug = 1) + BEGIN + SELECT 'After Regular Flexing', @EntityGroupConfigGUID AS EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeID, ProviderLineItemID, EmployeeID, FixedPercentage + FROM #StaffingVariabilityDetail + END + + ------------------------------------------------------------------------------------------- + -- Provider Stat Accounts + ------------------------------------------------------------------------------------------- + INSERT INTO #StaffingVariabilityDetail (EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeID, FixedPercentage, ProviderLineItemID, EmployeeID) + SELECT + @EntityGroupConfigGUID, + p.DepartmentID, + p.JobCodeID, + p.PayCodeID, + p.ProviderFixedPercentage, + p.ProviderLineItemID, + 0 as EmployeeID + FROM #ProviderVariability p + + IF (@IsDebug = 1) + BEGIN + SELECT 'After Provider', @EntityGroupConfigGUID AS EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeID, ProviderLineItemID, EmployeeID, FixedPercentage + FROM #StaffingVariabilityDetail + END + + ------------------------------------------------------------------------------------------- + -- Publish + ------------------------------------------------------------------------------------------- + IF (@IsDebug = 0) + BEGIN + + DELETE pv FROM [fp].[FactStaffingVariabilityDetail] pv + INNER JOIN #FilterByDepartment ff on ff.DepartmentID = pv.DepartmentID + WHERE pv.EntityGroupConfigGUID = @EntityGroupConfigGUID + + INSERT INTO [fp].[FactStaffingVariabilityDetail] (EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeID, ProviderLineItemID, EmployeeID, FixedPercentage) + SELECT + @EntityGroupConfigGUID, + DepartmentID, + JobCodeID, + PayCodeID, + ProviderLineItemID, + EmployeeID, -- Employee should always be 0 as Employees are treated as 100% fixed and thus should never have a row in [fp].[FactStaffingVariabilityDetail] + FixedPercentage + FROM #StaffingVariabilityDetail + WHERE FixedPercentage < 1 -- We assume when something isn't in the table that it's 100% fixed. + + END ELSE + BEGIN + SELECT 'Final', @EntityGroupConfigGUID AS EntityGroupConfigGUID, DepartmentID, JobCodeID, PayCodeID, ProviderLineItemID, EmployeeID, FixedPercentage + FROM #StaffingVariabilityDetail + END + + END +GO + + +--------------------------------------------- + +-- fp.procProcessReportFactGeneralLedger +CREATE PROCEDURE [fp].[procProcessReportFactGeneralLedger] ( + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +) +WITH RECOMPILE +AS +BEGIN + + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2018-12-24 IP B-21543 Added temp table to index source as well + ** 2 2018-12-24 IP B-21543 Added temp table to index source as well + ** 3 2019-01-09 GF B-21715 Optimize full config refresh case + ** 4 2019-01-11 GF B-21715 Optimize targeted refresh case + ** 5 2019-05-02 GF Remove special handling of all case to make concurrency work + ** 6 2019-07-22 MY Performance updates + ** 7 2020-01-13 MY D-09168 CCF: Data not flowing through into reports + ** 8 2021-11-10 BW JAZZ-1358 Add dept to the filter when untargeted, to remove orphans + ** 9 2022-10-28 MY JAZZ-45443 Roll proc back to before perf changes + ** 10 2023-08-11 BK JAZZ-58752 Rename from 'procProcessReportFactGeneralLedger_TargetBudget' and update for new gl data structure + ** 11 2024-04-11 DM JAZZ-70189 Budget Config used for Report comparison is processed as well + *************************************************************/ + + exec [dbo].[procSysDropTempTable] '#SRC' + exec [dbo].[procSysDropTempTable] '#SourceDimensionality' + exec [dbo].[procSysDropTempTable] '#departments' + exec [dbo].[procSysDropTempTable] '#adjustedRecords' + exec [dbo].[procSysDropTempTable] '#tempUnpivoted' + exec [dbo].[procSysDropTempTable] '#dataToUpdate' + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE (IsActive = 1 OR IsUsedForReportComparison = 1) AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + + SELECT DISTINCT DepartmentID INTO #SourceDimensionality FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #departments (DepartmentID INT); + + CREATE TABLE #SRC ( + GeneralLedgerID INT, + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + DepartmentID INT, + AccountID INT, + FinancialReportingID INT, + APEModelSectionID INT, + VariabilityID INT, + UnitTypeID SMALLINT, + TimeClassID TINYINT, + FiscalYearID SMALLINT, + FiscalMonthID TINYINT, + LockType TINYINT, + OriginalValue DECIMAL(19, 8), + Value DECIMAL(19, 8), + ManagerValue DECIMAL(19, 8), + Rate DECIMAL(19, 8) + ) + + IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL) + BEGIN + + INSERT INTO #SRC(GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, LockType, OriginalValue, Value, ManagerValue, Rate) + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, LockType, OriginalValue, Value, ManagerValue, Rate + FROM [fp].[viewFactGeneralLedger_Unpivoted_source] VW + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = VW.DepartmentID + WHERE VW.BudgetConfigID = @BudgetConfigID + AND (OriginalValue != 0 or Value != 0 or ManagerValue != 0) + + END ELSE BEGIN + + INSERT INTO #SRC(GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, LockType, OriginalValue, Value, ManagerValue, Rate) + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, LockType, OriginalValue, Value, ManagerValue, Rate + FROM [fp].[viewFactGeneralLedger_Unpivoted_source] VW + WHERE VW.BudgetConfigID = @BudgetConfigID + AND (OriginalValue != 0 or Value != 0 or ManagerValue != 0) + + END + + CREATE CLUSTERED INDEX inx_src ON #SRC ( + GeneralLedgerID + ,BudgetConfigID + ,EntityGroupConfigID + ,EntityID + ,DepartmentID + ,AccountID + ,FinancialReportingID + ,APEModelSectionID + ,VariabilityID + ,UnitTypeID + ,TimeClassID + ,FiscalYearID + ,FiscalMonthID + ) + + + IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #departments (DepartmentID) + SELECT DISTINCT DepartmentID FROM fp.GeneralLedger + WHERE BudgetConfigID = @BudgetConfigID + END + ELSE BEGIN + -- Get all of the departments in that could be affected. We need to get this list to eliminate + -- the null check in the join in the with statement. + INSERT INTO #departments (DepartmentID) + SELECT DISTINCT DepartmentID + FROM ( + SELECT DISTINCT DepartmentID FROM #SRC + UNION ALL + SELECT DISTINCT DepartmentID FROM #SourceDimensionality + ) data + END + + + ;WITH TGT AS + ( + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, FRS.DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, LockType, OriginalValue, Value, ManagerValue, Rate + FROM fp.FactReportGeneralLedger FRS + INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID + WHERE FRS.BudgetConfigID = @BudgetConfigID + ) + + MERGE TGT AS target + USING #SRC AS source + ON ( + target.GeneralLedgerID = source.GeneralLedgerID + AND target.BudgetConfigID = source.BudgetConfigID + AND target.EntityGroupConfigID = source.EntityGroupConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.AccountID = source.AccountID + AND target.FinancialReportingID = source.FinancialReportingID + AND target.APEModelSectionID = source.APEModelSectionID + AND target.VariabilityID = source.VariabilityID + AND target.UnitTypeID = source.UnitTypeID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalYearID = source.FiscalYearID + AND target.FiscalMonthID = source.FiscalMonthID + ) + WHEN MATCHED AND (target.LockType <> source.LockType + OR target.OriginalValue <> source.OriginalValue + OR target.Value <> source.Value + OR target.ManagerValue <> source.ManagerValue + OR target.Rate <> source.Rate) + THEN + UPDATE + SET target.LockType = ISNULL(source.LockType, 0), + target.OriginalValue = ISNULL(source.OriginalValue, 0), + target.Value = ISNULL(source.Value, 0), + target.ManagerValue = ISNULL(source.ManagerValue, 0), + target.Rate = ISNULL(source.Rate, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + GeneralLedgerID + ,BudgetConfigID + ,EntityGroupConfigID + ,EntityID + ,DepartmentID + ,AccountID + ,FinancialReportingID + ,APEModelSectionID + ,VariabilityID + ,UnitTypeID + ,TimeClassID + ,FiscalYearID + ,FiscalMonthID + ,LockType + ,OriginalValue + ,Value + ,ManagerValue + ,Rate + ) + VALUES ( + source.GeneralLedgerID + ,source.BudgetConfigID + ,source.EntityGroupConfigID + ,source.EntityID + ,source.DepartmentID + ,source.AccountID + ,source.FinancialReportingID + ,source.APEModelSectionID + ,source.VariabilityID + ,source.UnitTypeID + ,source.TimeClassID + ,source.FiscalYearID + ,source.FiscalMonthID + ,ISNULL(source.LockType, 0) + ,ISNULL(source.OriginalValue, 0) + ,ISNULL(source.Value, 0) + ,ISNULL(source.ManagerValue, 0) + ,ISNULL(source.Rate, 0) + ) + WHEN NOT MATCHED BY Source + THEN + DELETE; + + + ------------------------------------------------------------------------------------------------------- + -- D-09168 : CCF: Data not flowing through into reports + -- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the + -- targeting above. This is a short term solution until we can get a more performant solution. + ------------------------------------------------------------------------------------------------------- + + -- Check if targeting exists, if it doesn't for this part, wipe it and populate all departments + -- We can't rely on the existing departments because of the check for the padded rows. + IF NOT EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL) + BEGIN + + TRUNCATE TABLE #departments; + + INSERT INTO #departments (DepartmentID) + SELECT DepartmentID + FROM [fw].[DimDepartment] dept + + END + + -- Get all records that were adjusted + SELECT DISTINCT chg.GeneralLedgerID + INTO #adjustedRecords + FROM [fp].[GeneralLedgerChangeHistory] chg + INNER JOIN [fp].[GeneralLedger] gl ON chg.GeneralLedgerID = gl.GeneralLedgerID + INNER JOIN [fp].[GeneralLedgerAdjustment] adj ON chg.AdjustmentGUID = adj.AdjustmentGUID + INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN #departments ft on ft.DepartmentID = gl.DepartmentID + WHERE bc.BudgetConfigID = @BudgetConfigID + + -- Get the records that have 0's in them that might have been filtered out from the previous logic + SELECT src.* + INTO #tempUnpivoted + FROM #adjustedRecords adj + INNER JOIN [fp].[viewFactGeneralLedger_Unpivoted_source] src ON src.GeneralLedgerID = adj.GeneralLedgerID + WHERE src.BudgetConfigID = @BudgetConfigID + AND (src.OriginalValue = 0 OR src.Value = 0 OR src.ManagerValue = 0) + + -- Find the records that need to be updated by comparing the source to the reporting table + SELECT VW.* + INTO #dataToUpdate + FROM [fp].[FactReportGeneralLedger] frgl + INNER JOIN #departments ft on ft.DepartmentID = frgl.DepartmentID + INNER JOIN #tempUnpivoted VW ON VW.GeneralLedgerID = frgl.GeneralLedgerID + AND VW.FiscalMonthID = frgl.FiscalMonthID + AND VW.UnitTypeID = frgl.UnitTypeID + AND VW.FiscalYearID = frgl.FiscalYearID + AND VW.TimeClassID = frgl.TimeClassID + WHERE frgl.BudgetConfigID = @BudgetConfigID + AND (VW.OriginalValue != frgl.OriginalValue OR VW.Value != frgl.Value OR VW.ManagerValue != frgl.ManagerValue) + + -- Update the records + UPDATE frgl + SET frgl.OriginalValue = ISNULL(upd.OriginalValue, 0), + frgl.Value = ISNULL(upd.Value, 0), + frgl.ManagerValue = ISNULL(upd.ManagerValue, 0) + FROM [fp].[FactReportGeneralLedger] frgl + INNER JOIN #departments ft on ft.DepartmentID = frgl.DepartmentID + INNER JOIN #dataToUpdate upd ON upd.GeneralLedgerID = frgl.GeneralLedgerID AND upd.FiscalMonthID = frgl.FiscalMonthID AND upd.UnitTypeID = frgl.UnitTypeID + + +END +GO + + +--------------------------------------------- + +-- fp.procProcessReportFactGeneralLedgerSnapshot +CREATE PROCEDURE [fp].[procProcessReportFactGeneralLedgerSnapshot] ( + @SnapshotID INT +) +WITH RECOMPILE +AS +BEGIN + + /************************************************************* + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2024-11-04 MY JAZZ-77737 Initial + ***************************************************************/ + + exec [dbo].[procSysDropTempTable] '#SRC' + exec [dbo].[procSysDropTempTable] '#SourceDimensionality' + exec [dbo].[procSysDropTempTable] '#departments' + exec [dbo].[procSysDropTempTable] '#adjustedRecords' + exec [dbo].[procSysDropTempTable] '#tempUnpivoted' + exec [dbo].[procSysDropTempTable] '#dataToUpdate' + + DECLARE @BudgetConfigID INT = (SELECT BudgetConfigID FROM fp.BudgetSnapshot WHERE SnapshotID = @SnapshotID); + + CREATE TABLE #SRC ( + GeneralLedgerID INT, + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + DepartmentID INT, + AccountID INT, + FinancialReportingID INT, + APEModelSectionID INT, + VariabilityID INT, + UnitTypeID SMALLINT, + TimeClassID TINYINT, + FiscalYearID SMALLINT, + FiscalMonthID TINYINT, + LockType TINYINT, + OriginalValue DECIMAL(19, 8), + Value DECIMAL(19, 8), + ManagerValue DECIMAL(19, 8), + Rate DECIMAL(19, 8) + ) + + INSERT INTO #SRC(GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, LockType, OriginalValue, Value, ManagerValue, Rate) + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, VW.DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, LockType, OriginalValue, Value, ManagerValue, Rate + FROM [fp].[viewFactGeneralLedger_Snapshot] VW + WHERE VW.SnapshotID = @SnapshotID + AND (OriginalValue != 0 or Value != 0 or ManagerValue != 0) + + CREATE CLUSTERED INDEX inx_src ON #SRC ( + GeneralLedgerID + ,BudgetConfigID + ,EntityGroupConfigID + ,EntityID + ,DepartmentID + ,AccountID + ,FinancialReportingID + ,APEModelSectionID + ,VariabilityID + ,UnitTypeID + ,TimeClassID + ,FiscalYearID + ,FiscalMonthID + ) + + ;WITH TGT AS + ( + SELECT GeneralLedgerID, SnapshotID, BudgetConfigID, EntityGroupConfigID, EntityID, FRS.DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, LockType, OriginalValue, Value, ManagerValue, Rate + FROM fp.FactReportGeneralLedgerSnapshot FRS + WHERE FRS.SnapshotID = @SnapshotID + ) + + MERGE TGT AS target + USING #SRC AS source + ON ( + target.GeneralLedgerID = source.GeneralLedgerID + AND target.SnapshotID = @SnapshotID + AND target.BudgetConfigID = source.BudgetConfigID + AND target.EntityGroupConfigID = source.EntityGroupConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.AccountID = source.AccountID + AND target.FinancialReportingID = source.FinancialReportingID + AND target.APEModelSectionID = source.APEModelSectionID + AND target.VariabilityID = source.VariabilityID + AND target.UnitTypeID = source.UnitTypeID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalYearID = source.FiscalYearID + AND target.FiscalMonthID = source.FiscalMonthID + ) + WHEN MATCHED AND (target.LockType <> source.LockType + OR target.OriginalValue <> source.OriginalValue + OR target.Value <> source.Value + OR target.ManagerValue <> source.ManagerValue + OR target.Rate <> source.Rate) + THEN + UPDATE + SET target.LockType = ISNULL(source.LockType, 0), + target.OriginalValue = ISNULL(source.OriginalValue, 0), + target.Value = ISNULL(source.Value, 0), + target.ManagerValue = ISNULL(source.ManagerValue, 0), + target.Rate = ISNULL(source.Rate, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + GeneralLedgerID + ,SnapshotID + ,BudgetConfigID + ,EntityGroupConfigID + ,EntityID + ,DepartmentID + ,AccountID + ,FinancialReportingID + ,APEModelSectionID + ,VariabilityID + ,UnitTypeID + ,TimeClassID + ,FiscalYearID + ,FiscalMonthID + ,LockType + ,OriginalValue + ,Value + ,ManagerValue + ,Rate + ) + VALUES ( + source.GeneralLedgerID + ,@SnapshotID + ,source.BudgetConfigID + ,source.EntityGroupConfigID + ,source.EntityID + ,source.DepartmentID + ,source.AccountID + ,source.FinancialReportingID + ,source.APEModelSectionID + ,source.VariabilityID + ,source.UnitTypeID + ,source.TimeClassID + ,source.FiscalYearID + ,source.FiscalMonthID + ,ISNULL(source.LockType, 0) + ,ISNULL(source.OriginalValue, 0) + ,ISNULL(source.Value, 0) + ,ISNULL(source.ManagerValue, 0) + ,ISNULL(source.Rate, 0) + ) + WHEN NOT MATCHED BY Source + THEN + DELETE; + + -- Copy the UK to US Datatransfer data at the time of the snapshot + INSERT INTO [fp].[FactReportGeneralLedgerDataTransferSnapshot] (SnapshotID, BudgetconfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID, UnitTypeID, + TimeClassID, FiscalYearID, FiscalMonthID, OriginalValue, Value, ManagerValue, Rate) + SELECT @SnapshotID, BudgetConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, VariabilityID, UnitTypeID, + TimeClassID, FiscalYearID, FiscalMonthID, OriginalValue, Value, ManagerValue, Rate + FROM [fp].[FactReportGeneralLedgerDataTransfer] + WHERE BudgetConfigID = @BudgetConfigID + +END +GO + + +--------------------------------------------- + +-- fp.procProcessReportFactGeneralLedger_Initial +CREATE PROCEDURE [fp].[procProcessReportFactGeneralLedger_Initial] ( + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +) +WITH RECOMPILE +AS +BEGIN +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-08-30 MY JAZZ-42472 Initial +** 2 2023-08-11 BK JAZZ-58752 Update for new gl data structure +** 3 2024-04-11 DM JAZZ-70189 Budget Config used for Report comparison is processed as well +*************************************************************/ + + exec [dbo].[procSysDropTempTable] '#SRC' + exec [dbo].[procSysDropTempTable] '#SourceDimensionality' + exec [dbo].[procSysDropTempTable] '#departments' + exec [dbo].[procSysDropTempTable] '#adjustedRecords' + exec [dbo].[procSysDropTempTable] '#tempUnpivoted' + exec [dbo].[procSysDropTempTable] '#dataToUpdate' + exec [dbo].[procSysDropTempTable] '#joinedGLData' + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE (IsActive = 1 OR IsUsedForReportComparison = 1) AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + + SELECT DISTINCT DepartmentID INTO #SourceDimensionality FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #SourceDimensionality (DepartmentID) + SELECT DISTINCT DepartmentID FROM fp.GeneralLedger + WHERE BudgetConfigID = @BudgetConfigID + END + + CREATE TABLE #SRC ( + GeneralLedgerID INT, + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + DepartmentID INT, + AccountID INT, + FinancialReportingID INT, + APEModelSectionID INT, + VariabilityID INT, + UnitTypeID SMALLINT, + TimeClassID TINYINT, + FiscalYearID SMALLINT, + FiscalMonthID TINYINT, + OriginalValue DECIMAL(19, 8) + ) + + CREATE TABLE #joinedGLData ( + GeneralLedgerID INT, + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + DepartmentID INT, + AccountID INT, + FinancialReportingID INT, + APEModelSectionID INT, + VariabilityID INT, + UnitTypeID SMALLINT, + TimeClassID TINYINT, + FiscalYearID SMALLINT, + Month01 DECIMAL(19, 8), + Month02 DECIMAL(19, 8), + Month03 DECIMAL(19, 8), + Month04 DECIMAL(19, 8), + Month05 DECIMAL(19, 8), + Month06 DECIMAL(19, 8), + Month07 DECIMAL(19, 8), + Month08 DECIMAL(19, 8), + Month09 DECIMAL(19, 8), + Month10 DECIMAL(19, 8), + Month11 DECIMAL(19, 8), + Month12 DECIMAL(19, 8) + ) + + INSERT INTO #joinedGLData (GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, + Month09, Month10, Month11, Month12) + SELECT + gl.GeneralLedgerID, + gl.BudgetConfigID, + gl.EntityGroupConfigID, + gl.EntityID, + gl.DepartmentID, + gl.AccountID, + gl.FinancialReportingID, + gl.APEModelSectionID, + gl.VariabilityID, + 34 as UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + gl.InitialBudget01 AS Month01, + gl.InitialBudget02 AS Month02, + gl.InitialBudget03 AS Month03, + gl.InitialBudget04 AS Month04, + gl.InitialBudget05 AS Month05, + gl.InitialBudget06 AS Month06, + gl.InitialBudget07 AS Month07, + gl.InitialBudget08 AS Month08, + gl.InitialBudget09 AS Month09, + gl.InitialBudget10 AS Month10, + gl.InitialBudget11 AS Month11, + gl.InitialBudget12 AS Month12 + FROM fp.GeneralLedger gl + INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = gl.DepartmentID + WHERE gl.BudgetConfigID = @BudgetConfigID + + INSERT INTO #joinedGLData (GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, + Month09, Month10, Month11, Month12) + SELECT + gl.GeneralLedgerID, + gl.BudgetConfigID, + gl.EntityGroupConfigID, + gl.EntityID, + gl.DepartmentID, + gl.AccountID, + gl.FinancialReportingID, + gl.APEModelSectionID, + gl.VariabilityID, + 34 as UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID - 1, + gl.InitialProjection01 AS Month01, + gl.InitialProjection02 AS Month02, + gl.InitialProjection03 AS Month03, + gl.InitialProjection04 AS Month04, + gl.InitialProjection05 AS Month05, + gl.InitialProjection06 AS Month06, + gl.InitialProjection07 AS Month07, + gl.InitialProjection08 AS Month08, + gl.InitialProjection09 AS Month09, + gl.InitialProjection10 AS Month10, + gl.InitialProjection11 AS Month11, + gl.InitialProjection12 AS Month12 + FROM fp.GeneralLedger gl + INNER JOIN fp.BudgetConfig bc ON gl.BudgetConfigID = bc.BudgetConfigID + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = gl.DepartmentID + WHERE gl.BudgetConfigID = @BudgetConfigID + + CREATE CLUSTERED INDEX inx_src ON #SRC ( + GeneralLedgerID + ,BudgetConfigID + ,EntityGroupConfigID + ,EntityID + ,DepartmentID + ,AccountID + ,FinancialReportingID + ,APEModelSectionID + ,VariabilityID + ,UnitTypeID + ,TimeClassID + ,FiscalYearID + ,FiscalMonthID + ) + + -- Pivot the data into the #SRC Table + INSERT INTO #SRC(GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, OriginalValue) + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, m.FiscalMonthID, OriginalValue + FROM #joinedGLData FGL + CROSS APPLY ( + VALUES + (1, Month01), + (2, Month02), + (3, Month03), + (4, Month04), + (5, Month05), + (6, Month06), + (7, Month07), + (8, Month08), + (9, Month09), + (10, Month10), + (11, Month11), + (12, Month12)) cv (FiscalMonth, OriginalValue) + INNER JOIN fw.DimFiscalMonth m ON m.SortOrder = cv.FiscalMonth + WHERE cv.OriginalValue != 0 -- In the original we exclude (OriginalValue != 0 or Value != 0 or ManagerValue != 0) to avoid too many empty rows. It helps lean out the data some. + + + -- Get all of the departments in that could be affected. We need to get this list to eliminate + -- the null check in the join in the with statement. + SELECT DISTINCT DepartmentID INTO #departments + FROM ( + SELECT DISTINCT DepartmentID FROM #SRC + UNION ALL + SELECT DISTINCT DepartmentID FROM #SourceDimensionality + ) data + + ;WITH TGT AS + ( + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, FRS.DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, OriginalValue + FROM fp.FactReportGeneralLedger FRS + INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID + WHERE FRS.BudgetConfigID = @BudgetConfigID + ) + + MERGE TGT AS target + USING #SRC AS source + ON ( + target.GeneralLedgerID = source.GeneralLedgerID + AND target.BudgetConfigID = source.BudgetConfigID + AND target.EntityGroupConfigID = source.EntityGroupConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.AccountID = source.AccountID + AND target.FinancialReportingID = source.FinancialReportingID + AND target.APEModelSectionID = source.APEModelSectionID + AND target.VariabilityID = source.VariabilityID + AND target.UnitTypeID = source.UnitTypeID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalYearID = source.FiscalYearID + AND target.FiscalMonthID = source.FiscalMonthID + ) + WHEN MATCHED AND (target.OriginalValue <> source.OriginalValue) + THEN + UPDATE + SET target.OriginalValue = ISNULL(source.OriginalValue, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + GeneralLedgerID + ,BudgetConfigID + ,EntityGroupConfigID + ,EntityID + ,DepartmentID + ,AccountID + ,FinancialReportingID + ,APEModelSectionID + ,VariabilityID + ,UnitTypeID + ,TimeClassID + ,FiscalYearID + ,FiscalMonthID + ,OriginalValue + ) + VALUES ( + source.GeneralLedgerID + ,source.BudgetConfigID + ,source.EntityGroupConfigID + ,source.EntityID + ,source.DepartmentID + ,source.AccountID + ,source.FinancialReportingID + ,source.APEModelSectionID + ,source.VariabilityID + ,source.UnitTypeID + ,source.TimeClassID + ,source.FiscalYearID + ,source.FiscalMonthID + ,ISNULL(source.OriginalValue, 0) + ); + -- NOTE: We are not removing any records that don't match because we don't want cases where there is a record for Original Value, but not for Target/Budget (aka it's 0) and then the Baseline gets deleted. + + ------------------------------------------------------------------------------------------------------- + -- Data not flowing through into reports after setting the record to 0 + -- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the + -- targeting above because we only populate records that are not 0 + ------------------------------------------------------------------------------------------------------- + + -- Get the records that have 0's in them that might have been filtered out from the previous logic + /*SELECT + cv.GeneralLedgerID, + cv.BudgetConfigID, + cv.EntityGroupConfigID, + cv.EntityID, + cv.DepartmentID, + cv.AccountID, + cv.FinancialReportingID, + cv.APEModelSectionID, + cv.VariabilityID, + cv.UnitTypeID, + cv.TimeClassID, + cv.FiscalYearID, + m.FiscalMonthID, + SUM(cv.OriginalValue) AS OriginalValue + FROM (*/ + SELECT GeneralLedgerID, BudgetConfigID, EntityGroupConfigID, EntityID, FGL.DepartmentID, AccountID, FinancialReportingID, APEModelSectionID, + VariabilityID, UnitTypeID, TimeClassID, FiscalYearID, m.FiscalMonthID, OriginalValue + INTO #tempUnpivoted + FROM #joinedGLData FGL + INNER JOIN #SourceDimensionality dept ON FGL.DepartmentID = dept.DepartmentID + CROSS APPLY ( + VALUES + (1, Month01), + (2, Month02), + (3, Month03), + (4, Month04), + (5, Month05), + (6, Month06), + (7, Month07), + (8, Month08), + (9, Month09), + (10, Month10), + (11, Month11), + (12, Month12)) cv (FiscalMonth, OriginalValue) + INNER JOIN fw.DimFiscalMonth m ON m.SortOrder = cv.FiscalMonth + WHERE cv.OriginalValue = 0 -- In the original we exclude (OriginalValue != 0 or Value != 0 or ManagerValue != 0) to avoid too many empty rows. It helps lean out the data some. + + + -- Find the records that need to be updated by comparing the source to the reporting table + SELECT + vw.GeneralLedgerID, + vw.TimeClassID, + vw.FiscalMonthID, + vw.UnitTypeID, + vw.OriginalValue + INTO #dataToUpdate + FROM [fp].[FactReportGeneralLedger] frgl + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = frgl.DepartmentID + INNER JOIN #tempUnpivoted vw ON vw.GeneralLedgerID = frgl.GeneralLedgerID + AND vw.FiscalMonthID = frgl.FiscalMonthID + AND vw.UnitTypeID = frgl.UnitTypeID + AND vw.FiscalYearID = frgl.FiscalYearID + AND vw.TimeClassID = frgl.TimeClassID + WHERE frgl.BudgetConfigID = @BudgetConfigID + AND vw.OriginalValue != frgl.OriginalValue + + -- Update the records + UPDATE frgl + SET + frgl.OriginalValue = ISNULL(upd.OriginalValue, 0) + FROM [fp].[FactReportGeneralLedger] frgl + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = frgl.DepartmentID + INNER JOIN #dataToUpdate upd ON upd.GeneralLedgerID = frgl.GeneralLedgerID AND upd.FiscalMonthID = frgl.FiscalMonthID AND upd.UnitTypeID = frgl.UnitTypeID AND frgl.TimeClassID = upd.TimeClassID + +END +GO + + +--------------------------------------------- + +-- fp.procProcessReportFactStaffing_Initial +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-08-30 MY JAZZ-42472 Initial +** 2 2023-11-01 BW JAZZ-62798 New data model update +** 3 2024-07-04 DM JAZZ-70314 Budget Config used for Report comparison is processed as well +*************************************************************/ +CREATE PROCEDURE [fp].[procProcessReportFactStaffing_Initial] ( + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY) +WITH RECOMPILE +AS +BEGIN + exec [dbo].[procSysDropTempTable] '#SRC' + exec [dbo].[procSysDropTempTable] '#SourceDimensionality' + exec [dbo].[procSysDropTempTable] '#departments' + exec [dbo].[procSysDropTempTable] '#joinedStaffingData' + exec [dbo].[procSysDropTempTable] '#tempUnpivoted' + exec [dbo].[procSysDropTempTable] '#dataToUpdate' + + --only the active config is supported currently + if (not exists(select 1 from fp.BudgetConfig where (IsActive = 1 OR IsUsedForReportComparison = 1) AND BudgetConfigID = @BudgetConfigID)) begin return end + + SELECT DISTINCT DepartmentID INTO #SourceDimensionality + FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #SourceDimensionality (DepartmentID) + SELECT DISTINCT DepartmentID FROM fp.Staffing + WHERE BudgetConfigID = @BudgetConfigID + END + + CREATE TABLE #SRC ( + [BudgetConfigID] INT, + [EntityID] INT, + [DepartmentID] INT, + [JobCodeID] INT, + [PayCodeGroupID] INT, + [VariabilityID] INT, + [ProductiveClassID] INT, + [EmployeeID] INT, + [ProviderID] INT, + [ProviderLineItemID] INT, + [ProviderTypeID] INT, + [ProviderSpecialtyID] INT, + [UnitTypeID] SMALLINT, + [TimeClassID] TINYINT, + [FiscalMonthID] TINYINT, + [FiscalYearID] SMALLINT, + [OriginalValue] DECIMAL(19, 8) + ); + + CREATE TABLE #joinedStaffingData ( + [StaffingID] INT, + [BudgetConfigID] INT, + [EntityID] INT, + [DepartmentID] INT, + [JobCodeID] INT, + [PayCodeGroupID] INT, + [VariabilityID] INT, + [ProductiveClassID] INT, + [EmployeeID] INT, + [ProviderID] INT, + [ProviderLineItemID] INT, + [ProviderTypeID] INT, + [ProviderSpecialtyID] INT, + UnitTypeID SMALLINT, + TimeClassID TINYINT, + FiscalYearID SMALLINT, + Month01 DECIMAL(19, 8), + Month02 DECIMAL(19, 8), + Month03 DECIMAL(19, 8), + Month04 DECIMAL(19, 8), + Month05 DECIMAL(19, 8), + Month06 DECIMAL(19, 8), + Month07 DECIMAL(19, 8), + Month08 DECIMAL(19, 8), + Month09 DECIMAL(19, 8), + Month10 DECIMAL(19, 8), + Month11 DECIMAL(19, 8), + Month12 DECIMAL(19, 8) + ) + + INSERT INTO #joinedStaffingData (StaffingID, BudgetConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, VariabilityID, + ProductiveClassID, EmployeeID, ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, + Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12) + SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.VariabilityID, + fs.ProductiveClassID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderLineItemID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + 34 AS UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + fs.InitialBudgetDollars01 AS Month01, + fs.InitialBudgetDollars02 AS Month02, + fs.InitialBudgetDollars03 AS Month03, + fs.InitialBudgetDollars04 AS Month04, + fs.InitialBudgetDollars05 AS Month05, + fs.InitialBudgetDollars06 AS Month06, + fs.InitialBudgetDollars07 AS Month07, + fs.InitialBudgetDollars08 AS Month08, + fs.InitialBudgetDollars09 AS Month09, + fs.InitialBudgetDollars10 AS Month10, + fs.InitialBudgetDollars11 AS Month11, + fs.InitialBudgetDollars12 AS Month12 + FROM fp.Staffing fs + INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID + WHERE fs.BudgetConfigID = @BudgetConfigID + + INSERT INTO #joinedStaffingData (StaffingID, BudgetConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, VariabilityID, + ProductiveClassID, EmployeeID, ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, + Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12) + SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.VariabilityID, + fs.ProductiveClassID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderLineItemID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + 51 AS UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + fs.InitialBudgetHours01 AS Month01, + fs.InitialBudgetHours02 AS Month02, + fs.InitialBudgetHours03 AS Month03, + fs.InitialBudgetHours04 AS Month04, + fs.InitialBudgetHours05 AS Month05, + fs.InitialBudgetHours06 AS Month06, + fs.InitialBudgetHours07 AS Month07, + fs.InitialBudgetHours08 AS Month08, + fs.InitialBudgetHours09 AS Month09, + fs.InitialBudgetHours10 AS Month10, + fs.InitialBudgetHours11 AS Month11, + fs.InitialBudgetHours12 AS Month12 + FROM fp.Staffing fs + INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID + WHERE fs.BudgetConfigID = @BudgetConfigID + + INSERT INTO #joinedStaffingData (StaffingID, BudgetConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, VariabilityID, + ProductiveClassID, EmployeeID, ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, + Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12) + SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.VariabilityID, + fs.ProductiveClassID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderLineItemID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + 144 AS UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + fs.InitialBudgetFTEs01 AS Month01, + fs.InitialBudgetFTEs02 AS Month02, + fs.InitialBudgetFTEs03 AS Month03, + fs.InitialBudgetFTEs04 AS Month04, + fs.InitialBudgetFTEs05 AS Month05, + fs.InitialBudgetFTEs06 AS Month06, + fs.InitialBudgetFTEs07 AS Month07, + fs.InitialBudgetFTEs08 AS Month08, + fs.InitialBudgetFTEs09 AS Month09, + fs.InitialBudgetFTEs10 AS Month10, + fs.InitialBudgetFTEs11 AS Month11, + fs.InitialBudgetFTEs12 AS Month12 + FROM fp.Staffing fs + INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID + WHERE fs.BudgetConfigID = @BudgetConfigID + + INSERT INTO #joinedStaffingData (StaffingID, BudgetConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, VariabilityID, + ProductiveClassID, EmployeeID, ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, + Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12) + SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.VariabilityID, + fs.ProductiveClassID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderLineItemID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + 172 AS UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + fs.InitialBudgetRate01 AS Month01, + fs.InitialBudgetRate02 AS Month02, + fs.InitialBudgetRate03 AS Month03, + fs.InitialBudgetRate04 AS Month04, + fs.InitialBudgetRate05 AS Month05, + fs.InitialBudgetRate06 AS Month06, + fs.InitialBudgetRate07 AS Month07, + fs.InitialBudgetRate08 AS Month08, + fs.InitialBudgetRate09 AS Month09, + fs.InitialBudgetRate10 AS Month10, + fs.InitialBudgetRate11 AS Month11, + fs.InitialBudgetRate12 AS Month12 + FROM fp.Staffing fs + INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID + WHERE fs.BudgetConfigID = @BudgetConfigID + + INSERT INTO #joinedStaffingData (StaffingID, BudgetConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, VariabilityID, + ProductiveClassID, EmployeeID, ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, + Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12) + SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.VariabilityID, + fs.ProductiveClassID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderLineItemID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + 34 AS UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID - 1, + fs.InitialProjectionDollars01 AS Month01, + fs.InitialProjectionDollars02 AS Month02, + fs.InitialProjectionDollars03 AS Month03, + fs.InitialProjectionDollars04 AS Month04, + fs.InitialProjectionDollars05 AS Month05, + fs.InitialProjectionDollars06 AS Month06, + fs.InitialProjectionDollars07 AS Month07, + fs.InitialProjectionDollars08 AS Month08, + fs.InitialProjectionDollars09 AS Month09, + fs.InitialProjectionDollars10 AS Month10, + fs.InitialProjectionDollars11 AS Month11, + fs.InitialProjectionDollars12 AS Month12 + FROM fp.Staffing fs + INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID + WHERE fs.BudgetConfigID = @BudgetConfigID + + INSERT INTO #joinedStaffingData (StaffingID, BudgetConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, VariabilityID, + ProductiveClassID, EmployeeID, ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, + Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12) + SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.VariabilityID, + fs.ProductiveClassID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderLineItemID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + 51 AS UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID - 1, + fs.InitialProjectionHours01 AS Month01, + fs.InitialProjectionHours02 AS Month02, + fs.InitialProjectionHours03 AS Month03, + fs.InitialProjectionHours04 AS Month04, + fs.InitialProjectionHours05 AS Month05, + fs.InitialProjectionHours06 AS Month06, + fs.InitialProjectionHours07 AS Month07, + fs.InitialProjectionHours08 AS Month08, + fs.InitialProjectionHours09 AS Month09, + fs.InitialProjectionHours10 AS Month10, + fs.InitialProjectionHours11 AS Month11, + fs.InitialProjectionHours12 AS Month12 + FROM fp.Staffing fs + INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID + WHERE fs.BudgetConfigID = @BudgetConfigID + + INSERT INTO #joinedStaffingData (StaffingID, BudgetConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, VariabilityID, + ProductiveClassID, EmployeeID, ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, + Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12) + SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.VariabilityID, + fs.ProductiveClassID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderLineItemID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + 144 AS UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID - 1, + fs.InitialProjectionFTEs01 AS Month01, + fs.InitialProjectionFTEs02 AS Month02, + fs.InitialProjectionFTEs03 AS Month03, + fs.InitialProjectionFTEs04 AS Month04, + fs.InitialProjectionFTEs05 AS Month05, + fs.InitialProjectionFTEs06 AS Month06, + fs.InitialProjectionFTEs07 AS Month07, + fs.InitialProjectionFTEs08 AS Month08, + fs.InitialProjectionFTEs09 AS Month09, + fs.InitialProjectionFTEs10 AS Month10, + fs.InitialProjectionFTEs11 AS Month11, + fs.InitialProjectionFTEs12 AS Month12 + FROM fp.Staffing fs + INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID + WHERE fs.BudgetConfigID = @BudgetConfigID + + INSERT INTO #joinedStaffingData (StaffingID, BudgetConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, VariabilityID, + ProductiveClassID, EmployeeID, ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, UnitTypeID, TimeClassID, FiscalYearID, + Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12) + SELECT + fs.StaffingID, + fs.BudgetConfigID, + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.VariabilityID, + fs.ProductiveClassID, + fs.EmployeeID, + fs.ProviderID, + fs.ProviderLineItemID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + 172 AS UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID - 1, + fs.InitialProjectionRate01 AS Month01, + fs.InitialProjectionRate02 AS Month02, + fs.InitialProjectionRate03 AS Month03, + fs.InitialProjectionRate04 AS Month04, + fs.InitialProjectionRate05 AS Month05, + fs.InitialProjectionRate06 AS Month06, + fs.InitialProjectionRate07 AS Month07, + fs.InitialProjectionRate08 AS Month08, + fs.InitialProjectionRate09 AS Month09, + fs.InitialProjectionRate10 AS Month10, + fs.InitialProjectionRate11 AS Month11, + fs.InitialProjectionRate12 AS Month12 + FROM fp.Staffing fs + INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID + WHERE fs.BudgetConfigID = @BudgetConfigID + + -- Pivot the data into the #SRC Table + INSERT INTO #SRC([BudgetConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID], [ProductiveClassID], + [EmployeeID], [ProviderID], [ProviderLineItemID], [ProviderTypeID], [ProviderSpecialtyID], + [UnitTypeID], [TimeClassID], [FiscalYearID], [FiscalMonthID], [OriginalValue]) + SELECT + cv.BudgetConfigID, + cv.EntityID, + cv.DepartmentID, + cv.JobCodeID, + cv.PayCodeGroupID, + cv.VariabilityID, + cv.ProductiveClassID, + cv.EmployeeID, + cv.ProviderID, + cv.ProviderLineItemID, + cv.ProviderTypeID, + cv.ProviderSpecialtyID, + cv.UnitTypeID, + cv.TimeClassID, + cv.FiscalYearID, + m.FiscalMonthID, + SUM(cv.Value) AS OriginalValue + FROM ( + SELECT BudgetConfigID, EntityID, DepartmentID, JobCodeID, VariabilityID, ProductiveClassID, PayCodeGroupID, + EmployeeID, ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, UnitTypeID, + TimeClassID, FiscalYearID, FiscalMonth, Value + FROM #joinedStaffingData FGL + CROSS APPLY ( + VALUES + ('Month01', Month01), + ('Month02', Month02), + ('Month03', Month03), + ('Month04', Month04), + ('Month05', Month05), + ('Month06', Month06), + ('Month07', Month07), + ('Month08', Month08), + ('Month09', Month09), + ('Month10', Month10), + ('Month11', Month11), + ('Month12', Month12)) X (FiscalMonth, Value) + ) cv + INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = cv.FiscalMonth + WHERE cv.Value != 0 -- In the original we exclude (OriginalValue != 0 or Value != 0 or ManagerValue != 0) to avoid too many empty rows. It helps lean out the data some. + GROUP BY cv.BudgetConfigID, + cv.EntityID, + cv.DepartmentID, + cv.JobCodeID, + cv.VariabilityID, + cv.ProductiveClassID, + cv.PayCodeGroupID, + cv.EmployeeID, + cv.ProviderID, + cv.ProviderLineItemID, + cv.ProviderTypeID, + cv.ProviderSpecialtyID, + cv.UnitTypeID, + cv.TimeClassID, + cv.FiscalYearID, + m.FiscalMonthID + + CREATE CLUSTERED INDEX inx_src ON #SRC ( + BudgetConfigID + ,EntityID + ,DepartmentID + ,JobCodeID + ,PayCodeGroupID + ,VariabilityID + ,ProductiveClassID + ,UnitTypeID + ,TimeClassID + ,FiscalMonthID + ,FiscalYearID + ,EmployeeID + ,ProviderID + ,ProviderLineItemID + ,ProviderTypeID + ,ProviderSpecialtyID + ) + + -- Get all of the departments in that could be affected. We need to get this list to eliminate + -- the null check in the join in the with statement. + SELECT DISTINCT DepartmentID INTO #departments + FROM ( + SELECT DISTINCT DepartmentID FROM #SRC + UNION ALL + SELECT DISTINCT DepartmentID FROM #SourceDimensionality + ) data + + ;WITH TGT AS + ( + SELECT [BudgetConfigID], [EntityID], [FRS].[DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID], + [ProductiveClassID], [UnitTypeID], [TimeClassID], [FiscalMonthID], [FiscalYearID], [OriginalValue], [EmployeeID], [ProviderID], [ProviderLineItemID], + [ProviderTypeID], [ProviderSpecialtyID] + FROM fp.FactReportStaffing FRS + INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID + WHERE FRS.BudgetConfigID = @BudgetConfigID + ) + + MERGE TGT AS target + USING #SRC AS source + ON ( + target.BudgetConfigID = source.BudgetConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.JobCodeID = source.JobCodeID + AND target.PayCodeGroupID = source.PayCodeGroupID + AND target.VariabilityID = source.VariabilityID + AND target.ProductiveClassID= source.ProductiveClassID + AND target.UnitTypeID= source.UnitTypeID + AND target.TimeClassID= source.TimeClassID + AND target.FiscalMonthID= source.FiscalMonthID + AND target.FiscalYearID= source.FiscalYearID + AND target.EmployeeID= source.EmployeeID + AND target.ProviderID= source.ProviderID + AND target.ProviderLineItemID= source.ProviderLineItemID + AND target.ProviderTypeID= source.ProviderTypeID + AND target.ProviderSpecialtyID= source.ProviderSpecialtyID + ) + WHEN MATCHED AND (target.OriginalValue <> source.OriginalValue) + THEN + UPDATE SET + target.OriginalValue = ISNULL(source.OriginalValue, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + BudgetConfigID + ,EntityID + ,DepartmentID + ,JobCodeID + ,PayCodeGroupID + ,VariabilityID + ,ProductiveClassID + ,UnitTypeID + ,TimeClassID + ,FiscalMonthID + ,FiscalYearID + ,OriginalValue + ,EmployeeID + ,ProviderID + ,ProviderLineItemID + ,ProviderTypeID + ,ProviderSpecialtyID + ) + VALUES ( + source. BudgetConfigID + ,source.EntityID + ,source.DepartmentID + ,source.JobCodeID + ,source.PayCodeGroupID + ,source.VariabilityID + ,source.ProductiveClassID + ,source.UnitTypeID + ,source.TimeClassID + ,source.FiscalMonthID + ,source.FiscalYearID + ,ISNULL(source.OriginalValue, 0) + ,source.EmployeeID + ,source.ProviderID + ,source.ProviderLineItemID + ,source.ProviderTypeID + ,source.ProviderSpecialtyID + ); + -- NOTE: We are not removing any records that don't match because we don't want cases where there is a record for Original Value, but not for Target/Budget (aka it's 0) and then the Baseline gets deleted. + + --remove invalid FTE data + DELETE fs FROM fp.FactReportStaffing fs INNER JOIN [fp].[viewExcludedProductiveClassesForFTE] exc ON fs.PayCodeGroupID = exc.PayCodeGroupID WHERE fs.UnitTypeID = 144; + + ------------------------------------------------------------------------------------------------------- + -- Data not flowing through into reports after setting the record to 0 + -- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the + -- targeting above because we only populate records that are not 0 + ------------------------------------------------------------------------------------------------------- + + -- Get the records that have 0's in them that might have been filtered out from the previous logic + SELECT + cv.BudgetConfigID, + cv.EntityID, + cv.DepartmentID, + cv.JobCodeID, + cv.PayCodeGroupID, + cv.VariabilityID, + cv.ProductiveClassID, + cv.EmployeeID, + cv.ProviderID, + cv.ProviderLineItemID, + cv.ProviderTypeID, + cv.ProviderSpecialtyID, + cv.UnitTypeID, + cv.TimeClassID, + cv.FiscalYearID, + m.FiscalMonthID, + SUM(cv.Value) AS OriginalValue + INTO #tempUnpivoted + FROM ( + SELECT BudgetConfigID, EntityID, FGL.DepartmentID, JobCodeID, VariabilityID, ProductiveClassID, PayCodeGroupID, + EmployeeID, ProviderID, ProviderLineItemID, ProviderTypeID, ProviderSpecialtyID, UnitTypeID, + TimeClassID, FiscalYearID, FiscalMonth, Value + FROM #joinedStaffingData FGL + INNER JOIN #SourceDimensionality dept ON FGL.DepartmentID = dept.DepartmentID + CROSS APPLY ( + VALUES + ('Month01', Month01), + ('Month02', Month02), + ('Month03', Month03), + ('Month04', Month04), + ('Month05', Month05), + ('Month06', Month06), + ('Month07', Month07), + ('Month08', Month08), + ('Month09', Month09), + ('Month10', Month10), + ('Month11', Month11), + ('Month12', Month12)) X (FiscalMonth, Value) + ) cv + INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = cv.FiscalMonth + WHERE cv.Value = 0 -- In the original we exclude (OriginalValue != 0 or Value != 0 or ManagerValue != 0) to avoid too many empty rows. It helps lean out the data some. + GROUP BY cv.BudgetConfigID, + cv.EntityID, + cv.DepartmentID, + cv.JobCodeID, + cv.VariabilityID, + cv.ProductiveClassID, + cv.PayCodeGroupID, + cv.EmployeeID, + cv.ProviderID, + cv.ProviderLineItemID, + cv.ProviderTypeID, + cv.ProviderSpecialtyID, + cv.UnitTypeID, + cv.TimeClassID, + cv.FiscalYearID, + m.FiscalMonthID + + -- Find the records that need to be updated by comparing the source to the reporting table + SELECT + target.BudgetConfigID, + target.EntityID, + target.DepartmentID, + target.JobCodeID, + target.VariabilityID, + target.ProductiveClassID, + target.PayCodeGroupID, + target.EmployeeID, + target.ProviderID, + target.ProviderTypeID, + target.ProviderSpecialtyID, + target.ProviderLineItemID, + target.UnitTypeID, + target.TimeClassID, + target.FiscalMonthID, + target.FiscalYearID, + SUM(target.OriginalValue) AS OriginalValue + INTO #dataToUpdate + FROM [fp].[FactReportStaffing] source + INNER JOIN #departments ft on ft.DepartmentID = source.DepartmentID + INNER JOIN #tempUnpivoted target ON target.BudgetConfigID = source.BudgetConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.JobCodeID = source.JobCodeID + AND target.PayCodeGroupID = source.PayCodeGroupID + AND target.ProductiveClassID = source.ProductiveClassID + AND target.VariabilityID = source.VariabilityID + AND target.EmployeeID = source.EmployeeID + AND target.UnitTypeID = source.UnitTypeID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + AND target.ProviderID = source.ProviderID + AND target.ProviderTypeID = source.ProviderTypeID + AND target.ProviderSpecialtyID = source.ProviderSpecialtyID + AND target.ProviderLineItemID = source.ProviderLineItemID + WHERE source.BudgetConfigID = @BudgetConfigID + AND target.OriginalValue != source.OriginalValue + GROUP BY target.BudgetConfigID, + target.EntityID, + target.DepartmentID, + target.JobCodeID, + target.PayCodeGroupID, + target.ProductiveClassID, + target.VariabilityID, + target.EmployeeID, + target.UnitTypeID, + target.TimeClassID, + target.FiscalMonthID, + target.FiscalYearID, + target.ProviderID, + target.ProviderTypeID, + target.ProviderSpecialtyID, + target.ProviderLineItemID + + -- Update the records + UPDATE source + SET + source.OriginalValue = ISNULL(target.OriginalValue, 0) + FROM [fp].[FactReportStaffing] source + INNER JOIN #departments ft on ft.DepartmentID = source.DepartmentID + INNER JOIN #dataToUpdate target ON target.BudgetConfigID = source.BudgetConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.JobCodeID = source.JobCodeID + AND target.PayCodeGroupID = source.PayCodeGroupID + AND target.ProductiveClassID = source.ProductiveClassID + AND target.VariabilityID = source.VariabilityID + AND target.EmployeeID = source.EmployeeID + AND target.UnitTypeID = source.UnitTypeID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + AND target.ProviderID = source.ProviderID + AND target.ProviderTypeID = source.ProviderTypeID + AND target.ProviderSpecialtyID = source.ProviderSpecialtyID + AND target.ProviderLineItemID = source.ProviderLineItemID +END +GO + + +--------------------------------------------- + +-- fp.procProcessReportFactStaffing_TargetBudget +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-12-24 IP B-21543 Added temp table to index source as well +** 2 2019-01-09 GF B-21715 Optimize full config refresh case +** 3 2019-01-11 GF B-21715 Optimize targeted refresh case +** 4 2019-04-15 GF D-08357 Removed differential and dollars-only FTEs +** 5 2019-05-02 GF X-XXXXX Remove special handling of all case to make concurrency work +** 6 2019-07-22 MY X-XXXXX Performance updates to reports +** 7 2019-11-13 MD B-24632 Add EmployeeID to staffing sampling +** 8 2020-02-18 MY JAZZ-15375 Roll-up data above Provider for Report +** 9 2021-11-30 SD JAZZ-30301 Add provider dimensions to Staffing reporting data sources +** 10 2022-08-30 MY JAZZ-42472 Improve Pivoting of Data for Reports +** 11 2022-10-28 MY JAZZ-45443 Roll proc back to before perf changes +** 12 2024-07-04 DM JAZZ-70314 Budget Config used for Report comparison is processed as well +*************************************************************/ +CREATE PROCEDURE [fp].[procProcessReportFactStaffing_TargetBudget] ( + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY) +WITH RECOMPILE +AS +BEGIN + + exec [dbo].[procSysDropTempTable] '#SRC' + exec [dbo].[procSysDropTempTable] '#SourceDimensionality' + exec [dbo].[procSysDropTempTable] '#departments' + + --only the active and used for comparison configs are supported currently + if (not exists(select 1 from fp.BudgetConfig where (IsActive = 1 OR IsUsedForReportComparison = 1) AND BudgetConfigID = @BudgetConfigID)) begin return end + + SELECT DISTINCT DepartmentID INTO #SourceDimensionality FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #SRC ( + [BudgetConfigID] INT, + [EntityID] INT, + [DepartmentID] INT, + [JobCodeID] INT, + [PayCodeGroupID] INT, + [VariabilityID] INT, + [ProductiveClassID] INT, + [UnitTypeID] SMALLINT, + [TimeClassID] TINYINT, + [FiscalMonthID] TINYINT, + [FiscalYearID] SMALLINT, + [OriginalValue] DECIMAL(19, 8), + [Value] DECIMAL(19, 8), + [ManagerValue] DECIMAL(19, 8), + [EmployeeID] INT, + [ProviderID] INT, + [ProviderLineItemID] INT, + [ProviderTypeID] INT, + [ProviderSpecialtyID] INT + ); + + IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #SRC ([BudgetConfigID], [EntityID], [VW].[DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID], [ProductiveClassID], + [UnitTypeID], [TimeClassID], [FiscalMonthID], [FiscalYearID], [OriginalValue], [Value], [ManagerValue], [EmployeeID], [ProviderID], [ProviderLineItemID], + [ProviderTypeID], [ProviderSpecialtyID]) + SELECT [BudgetConfigID], [EntityID], VW.[DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID], + [ProductiveClassID], [UnitTypeID], [TimeClassID], [FiscalMonthID], [FiscalYearID], + SUM([OriginalValue]), SUM([Value]), SUM([ManagerValue]), [EmployeeID], [ProviderID], [ProviderLineItemID], + [ProviderTypeID], [ProviderSpecialtyID] + FROM [fp].[viewFactStaffing_Unpivoted_source] VW + INNER JOIN #SourceDimensionality ft ON ft.DepartmentID = VW.DepartmentID + WHERE VW.BudgetConfigID = @BudgetConfigID + AND (OriginalValue != 0 or Value != 0 or ManagerValue != 0) + GROUP BY [BudgetConfigID], [EntityID], VW.[DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID], + [ProductiveClassID], [UnitTypeID], [TimeClassID], [FiscalMonthID], [FiscalYearID], [EmployeeID], [ProviderID], [ProviderLineItemID], + [ProviderTypeID], [ProviderSpecialtyID] + END ELSE BEGIN + INSERT INTO #SRC ([BudgetConfigID], [EntityID], [VW].[DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID], [ProductiveClassID], + [UnitTypeID], [TimeClassID], [FiscalMonthID], [FiscalYearID], [OriginalValue], [Value], [ManagerValue], [EmployeeID], [ProviderID], [ProviderLineItemID], + [ProviderTypeID], [ProviderSpecialtyID]) + SELECT [BudgetConfigID], [EntityID], VW.[DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID], + [ProductiveClassID], [UnitTypeID], [TimeClassID], [FiscalMonthID], [FiscalYearID], + SUM([OriginalValue]), SUM([Value]), SUM([ManagerValue]), [EmployeeID], [ProviderID], [ProviderLineItemID], + [ProviderTypeID], [ProviderSpecialtyID] + FROM [fp].[viewFactStaffing_Unpivoted_source] VW + WHERE VW.BudgetConfigID = @BudgetConfigID + AND (OriginalValue != 0 or Value != 0 or ManagerValue != 0) + GROUP BY [BudgetConfigID], [EntityID], VW.[DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID], + [ProductiveClassID], [UnitTypeID], [TimeClassID], [FiscalMonthID], [FiscalYearID], [EmployeeID], [ProviderID], [ProviderLineItemID], + [ProviderTypeID], [ProviderSpecialtyID] + END + + CREATE CLUSTERED INDEX inx_src ON #SRC ( + BudgetConfigID + ,EntityID + ,DepartmentID + ,JobCodeID + ,PayCodeGroupID + ,VariabilityID + ,ProductiveClassID + ,UnitTypeID + ,TimeClassID + ,FiscalMonthID + ,FiscalYearID + ,EmployeeID + ,ProviderID + ,ProviderLineItemID + ,ProviderTypeID + ,ProviderSpecialtyID + ) + + -- Get all of the departments in that could be affected. We need to get this list to eliminate + -- the null check in the join in the with statement. + SELECT DISTINCT DepartmentID INTO #departments + FROM ( + SELECT DISTINCT DepartmentID FROM #SRC + UNION ALL + SELECT DISTINCT DepartmentID FROM #SourceDimensionality + ) data + + ;WITH TGT AS + ( + SELECT [BudgetConfigID], [EntityID], [FRS].[DepartmentID], [JobCodeID], [PayCodeGroupID], [VariabilityID], + [ProductiveClassID], [UnitTypeID], [TimeClassID], [FiscalMonthID], [FiscalYearID], [OriginalValue], + [Value], [ManagerValue], [EmployeeID], [ProviderID], [ProviderLineItemID], + [ProviderTypeID], [ProviderSpecialtyID] + FROM fp.FactReportStaffing FRS + INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID + WHERE FRS.BudgetConfigID = @BudgetConfigID + ) + + MERGE TGT AS target + USING #SRC AS source + ON ( + target.BudgetConfigID = source.BudgetConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.JobCodeID = source.JobCodeID + AND target.PayCodeGroupID = source.PayCodeGroupID + AND target.VariabilityID = source.VariabilityID + AND target.ProductiveClassID= source.ProductiveClassID + AND target.UnitTypeID= source.UnitTypeID + AND target.TimeClassID= source.TimeClassID + AND target.FiscalMonthID= source.FiscalMonthID + AND target.FiscalYearID= source.FiscalYearID + AND target.EmployeeID= source.EmployeeID + AND target.ProviderID= source.ProviderID + AND target.ProviderLineItemID= source.ProviderLineItemID + AND target.ProviderTypeID= source.ProviderTypeID + AND target.ProviderSpecialtyID= source.ProviderSpecialtyID + ) + WHEN MATCHED AND ( + target.OriginalValue <> source.OriginalValue + OR target.Value <> source.Value + OR target.ManagerValue <> source.ManagerValue) + THEN + UPDATE SET + target.OriginalValue = source.OriginalValue, + target.Value = source.Value, + target.ManagerValue = source.ManagerValue + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + BudgetConfigID + ,EntityID + ,DepartmentID + ,JobCodeID + ,PayCodeGroupID + ,VariabilityID + ,ProductiveClassID + ,UnitTypeID + ,TimeClassID + ,FiscalMonthID + ,FiscalYearID + ,OriginalValue + ,Value + ,ManagerValue + ,EmployeeID + ,ProviderID + ,ProviderLineItemID + ,ProviderTypeID + ,ProviderSpecialtyID + ) + VALUES ( + source. BudgetConfigID + ,source.EntityID + ,source.DepartmentID + ,source.JobCodeID + ,source.PayCodeGroupID + ,source.VariabilityID + ,source.ProductiveClassID + ,source.UnitTypeID + ,source.TimeClassID + ,source.FiscalMonthID + ,source.FiscalYearID + ,source.OriginalValue + ,source.Value + ,source.ManagerValue + ,source.EmployeeID + ,source.ProviderID + ,source.ProviderLineItemID + ,source.ProviderTypeID + ,source.ProviderSpecialtyID + ) + WHEN NOT MATCHED BY Source + THEN + DELETE; + + --remove invalid FTE data + DELETE fs FROM fp.FactReportStaffing fs INNER JOIN [fp].[viewExcludedProductiveClassesForFTE] exc ON fs.PayCodeGroupID = exc.PayCodeGroupID WHERE fs.UnitTypeID = 144; + +END +GO + + +--------------------------------------------- + +-- fp.procProcessReportFactStatistics_Initial +CREATE PROCEDURE [fp].[procProcessReportFactStatistics_Initial] ( + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +) +WITH RECOMPILE +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2018-12-24 IP B-21543 Added temp table to index source as well + ** 2 2019-01-09 GF B-21715 Optimize full config refresh case + ** 3 2019-01-11 GF B-21715 Optimize targeted refresh case + ** 4 2019-05-02 GF X-XXXXX Remove special handling of all case to make concurrency work + ** 5 2019-07-22 MY X-XXXXX Performance updates + ** 6 2020-01-13 MY D-09168 CCF: Data not flowing through into reports + ** 7 2020-02-18 MY JAZZ-15375 Roll-up data above Provider for Report + ** 8 2021-05-10 MD JAZZ-15686 Add Provider dimensions to Stats data sources + ** 9 2021-11-10 BW JAZZ-1358 Add dept to the filter when untargeted, to remove orphans + ** 10 2022-08-30 MY JAZZ-42472 Improve Pivoting of Data for Reports + ** 11 2024-07-16 YR JAZZ-70315 Budget Config used for Report comparison is processed as well + *************************************************************/ + + EXEC [dbo].[procSysDropTempTable] '#SRC' + EXEC [dbo].[procSysDropTempTable] '#SourceDimensionality' + EXEC [dbo].[procSysDropTempTable] '#departments' + EXEC [dbo].[procSysDropTempTable] '#joinedStatData' + EXEC [dbo].[procSysDropTempTable] '#tempUnpivoted' + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE (IsActive = 1 OR IsUsedForReportComparison = 1) AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + + SELECT DISTINCT DepartmentID INTO #SourceDimensionality from fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #SourceDimensionality (DepartmentID) + SELECT DISTINCT DepartmentID FROM fp.FactStatistics + WHERE BudgetConfigID = @BudgetConfigID + END + + CREATE TABLE #SRC ( + BudgetConfigID INT, + EntityID INT, + DepartmentID INT, + AccountID INT, + PatientClassID INT, + PayorID INT, + FinancialReportingID INT, + UnitTypeID SMALLINT, + TimeClassID TINYINT, + FiscalMonthID TINYINT, + FiscalYearID SMALLINT, + ProviderID INT, + ProviderTypeID INT, + ProviderSpecialtyID INT, + ProviderLineItemID INT, + OriginalValue DECIMAL(19, 8) + ) + + CREATE TABLE #joinedStatData ( + StatisticsID INT, + BudgetConfigID INT, + EntityID INT, + DepartmentID INT, + AccountID INT, + PatientClassID INT, + PayorID INT, + FinancialReportingID INT, + ProviderID INT, + ProviderTypeID INT, + ProviderSpecialtyID INT, + ProviderLineItemID INT, + UnitTypeID SMALLINT, + TimeClassID TINYINT, + FiscalYearID SMALLINT, + Month01 DECIMAL(19, 8), + Month02 DECIMAL(19, 8), + Month03 DECIMAL(19, 8), + Month04 DECIMAL(19, 8), + Month05 DECIMAL(19, 8), + Month06 DECIMAL(19, 8), + Month07 DECIMAL(19, 8), + Month08 DECIMAL(19, 8), + Month09 DECIMAL(19, 8), + Month10 DECIMAL(19, 8), + Month11 DECIMAL(19, 8), + Month12 DECIMAL(19, 8) + ) + + INSERT INTO #joinedStatData (StatisticsID, BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, ProviderID, + ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, UnitTypeID, TimeClassID, FiscalYearID, + Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12) + SELECT + fs.StatisticsID, + fs.BudgetConfigID, + fs.EntityID, + fs.DepartmentID, + fs.AccountID, + fs.PatientClassID, + fs.PayorID, + fs.FinancialReportingID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + fs.InitialBudget01 AS Month01, + fs.InitialBudget02 AS Month02, + fs.InitialBudget03 AS Month03, + fs.InitialBudget04 AS Month04, + fs.InitialBudget05 AS Month05, + fs.InitialBudget06 AS Month06, + fs.InitialBudget07 AS Month07, + fs.InitialBudget08 AS Month08, + fs.InitialBudget09 AS Month09, + fs.InitialBudget10 AS Month10, + fs.InitialBudget11 AS Month11, + fs.InitialBudget12 AS Month12 + FROM fp.FactStatistics fs + INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID + WHERE fs.BudgetConfigID = @BudgetConfigID + + INSERT INTO #joinedStatData (StatisticsID, BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, ProviderID, + ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, UnitTypeID, TimeClassID, FiscalYearID, + Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12) + SELECT + fs.StatisticsID, + fs.BudgetConfigID, + fs.EntityID, + fs.DepartmentID, + fs.AccountID, + fs.PatientClassID, + fs.PayorID, + fs.FinancialReportingID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID - 1, + fs.InitialProjection01 AS Month01, + fs.InitialProjection02 AS Month02, + fs.InitialProjection03 AS Month03, + fs.InitialProjection04 AS Month04, + fs.InitialProjection05 AS Month05, + fs.InitialProjection06 AS Month06, + fs.InitialProjection07 AS Month07, + fs.InitialProjection08 AS Month08, + fs.InitialProjection09 AS Month09, + fs.InitialProjection10 AS Month10, + fs.InitialProjection11 AS Month11, + fs.InitialProjection12 AS Month12 + FROM fp.FactStatistics fs + INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID + WHERE fs.BudgetConfigID = @BudgetConfigID + + CREATE CLUSTERED INDEX inx_src ON #SRC ( + BudgetConfigID + ,EntityID + ,DepartmentID + ,AccountID + ,PatientClassID + ,PayorID + ,FinancialReportingID + ,UnitTypeID + ,TimeClassID + ,FiscalMonthID + ,FiscalYearID + ,ProviderID + ,ProviderTypeID + ,ProviderSpecialtyID + ,ProviderLineItemID + ) WITH (DATA_COMPRESSION = PAGE) + + -- Pivot the data into the #SRC Table + INSERT INTO #SRC(BudgetConfigID, EntityID, VW.DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, + OriginalValue) + SELECT + cv.BudgetConfigID, + cv.EntityID, + cv.DepartmentID, + cv.AccountID, + cv.PatientClassID, + cv.PayorID, + cv.FinancialReportingID, + cv.ProviderID, + cv.ProviderTypeID, + cv.ProviderSpecialtyID, + cv.ProviderLineItemID, + cv.UnitTypeID, + cv.TimeClassID, + cv.FiscalYearID, + m.FiscalMonthID, + SUM(cv.Value) AS OrginalValue + FROM ( + SELECT BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, ProviderID, ProviderTypeID, + ProviderSpecialtyID, ProviderLineItemID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonth, Value + FROM #joinedStatData stat + CROSS APPLY ( + VALUES + ('Month01', Month01), + ('Month02', Month02), + ('Month03', Month03), + ('Month04', Month04), + ('Month05', Month05), + ('Month06', Month06), + ('Month07', Month07), + ('Month08', Month08), + ('Month09', Month09), + ('Month10', Month10), + ('Month11', Month11), + ('Month12', Month12)) X (FiscalMonth, Value) + ) cv + INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = cv.FiscalMonth + WHERE cv.Value != 0 -- In the original we exclude (OriginalValue != 0 or Value != 0 or ManagerValue != 0) to avoid too many empty rows. It helps lean out the data some. + GROUP BY cv.BudgetConfigID, + cv.EntityID, + cv.DepartmentID, + cv.AccountID, + cv.PatientClassID, + cv.PayorID, + cv.FinancialReportingID, + cv.ProviderID, + cv.ProviderTypeID, + cv.ProviderSpecialtyID, + cv.ProviderLineItemID, + cv.UnitTypeID, + cv.TimeClassID, + cv.FiscalYearID, + m.FiscalMonthID + + -- Get all of the departments in that could be affected. We need to get this list to eliminate + -- the null check in the join in the with statement. + SELECT DISTINCT DepartmentID INTO #departments + FROM ( + SELECT DISTINCT DepartmentID FROM #SRC + UNION ALL + SELECT DISTINCT DepartmentID FROM #SourceDimensionality + ) data + + ;WITH TGT AS + ( + SELECT BudgetConfigID, EntityID, FRS.DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, + TimeClassID, FiscalMonthID, FiscalYearID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, + OriginalValue + FROM fp.FactReportStatistics FRS + INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID + WHERE FRS.BudgetConfigID = @BudgetConfigID + ) + MERGE TGT AS target + USING #SRC AS source + ON ( + target.BudgetConfigID = source.BudgetConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.AccountID = source.AccountID + AND target.PatientClassID = source.PatientClassID + AND target.PayorID = source.PayorID + AND target.FinancialReportingID = source.FinancialReportingID + AND target.UnitTypeID = source.UnitTypeID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + AND target.ProviderID = source.ProviderID + AND target.ProviderTypeID = source.ProviderTypeID + AND target.ProviderSpecialtyID = source.ProviderSpecialtyID + AND target.ProviderLineItemID = source.ProviderLineItemID + + ) + WHEN MATCHED AND (target.OriginalValue <> source.OriginalValue) + THEN + UPDATE SET + target.OriginalValue = ISNULL(source.OriginalValue, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + BudgetConfigID + ,EntityID + ,DepartmentID + ,AccountID + ,PatientClassID + ,PayorID + ,FinancialReportingID + ,UnitTypeID + ,TimeClassID + ,FiscalMonthID + ,FiscalYearID + ,ProviderID + ,ProviderTypeID + ,ProviderSpecialtyID + ,ProviderLineItemID + ,OriginalValue + ) + VALUES ( + source. BudgetConfigID + ,source.EntityID + ,source.DepartmentID + ,source.AccountID + ,source.PatientClassID + ,source.PayorID + ,source.FinancialReportingID + ,source.UnitTypeID + ,source.TimeClassID + ,source.FiscalMonthID + ,source.FiscalYearID + ,source.ProviderID + ,source.ProviderTypeID + ,source.ProviderSpecialtyID + ,source.ProviderLineItemID + ,ISNULL(source.OriginalValue, 0) + ); + -- NOTE: We are not removing any records that don't match because we don't want cases where there is a record for Original Value, but not for Target/Budget (aka it's 0) and then the Baseline gets deleted. + + + ------------------------------------------------------------------------------------------------------- + -- Data not flowing through into reports after setting the record to 0 + -- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the + -- targeting above because we only populate records that are not 0 + ------------------------------------------------------------------------------------------------------- + + -- Get the records that have 0's in them that might have been filtered out from the previous logic + SELECT + cv.BudgetConfigID, + cv.EntityID, + cv.DepartmentID, + cv.AccountID, + cv.PatientClassID, + cv.PayorID, + cv.FinancialReportingID, + cv.ProviderID, + cv.ProviderTypeID, + cv.ProviderSpecialtyID, + cv.ProviderLineItemID, + cv.UnitTypeID, + cv.TimeClassID, + cv.FiscalYearID, + m.FiscalMonthID, + SUM(cv.Value) AS OriginalValue + INTO #tempUnpivoted + FROM ( + SELECT BudgetConfigID, EntityID, stat.DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, ProviderID, ProviderTypeID, + ProviderSpecialtyID, ProviderLineItemID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonth, Value + FROM #joinedStatData stat + INNER JOIN #SourceDimensionality dept ON stat.DepartmentID = dept.DepartmentID + CROSS APPLY ( + VALUES + ('Month01', Month01), + ('Month02', Month02), + ('Month03', Month03), + ('Month04', Month04), + ('Month05', Month05), + ('Month06', Month06), + ('Month07', Month07), + ('Month08', Month08), + ('Month09', Month09), + ('Month10', Month10), + ('Month11', Month11), + ('Month12', Month12)) X (FiscalMonth, Value) + ) cv + INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = cv.FiscalMonth + WHERE cv.Value = 0 -- In the original we exclude (OriginalValue != 0 or Value != 0 or ManagerValue != 0) to avoid too many empty rows. It helps lean out the data some. + GROUP BY cv.BudgetConfigID, + cv.EntityID, + cv.DepartmentID, + cv.AccountID, + cv.PatientClassID, + cv.PayorID, + cv.FinancialReportingID, + cv.ProviderID, + cv.ProviderTypeID, + cv.ProviderSpecialtyID, + cv.ProviderLineItemID, + cv.UnitTypeID, + cv.TimeClassID, + cv.FiscalYearID, + m.FiscalMonthID + + -- Find the records that need to be updated by comparing the source to the reporting table + SELECT + target.BudgetConfigID, + target.EntityID, + target.DepartmentID, + target.AccountID, + target.PatientClassID, + target.PayorID, + target.FinancialReportingID, + target.UnitTypeID, + target.TimeClassID, + target.FiscalMonthID, + target.FiscalYearID, + target.ProviderID, + target.ProviderTypeID, + target.ProviderSpecialtyID, + target.ProviderLineItemID, + SUM(target.OriginalValue) AS OriginalValue + INTO #dataToUpdate + FROM [fp].[FactReportStatistics] source + INNER JOIN #departments ft on ft.DepartmentID = source.DepartmentID + INNER JOIN #tempUnpivoted target ON target.BudgetConfigID = source.BudgetConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.AccountID = source.AccountID + AND target.PatientClassID = source.PatientClassID + AND target.PayorID = source.PayorID + AND target.FinancialReportingID = source.FinancialReportingID + AND target.UnitTypeID = source.UnitTypeID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + AND target.ProviderID = source.ProviderID + AND target.ProviderTypeID = source.ProviderTypeID + AND target.ProviderSpecialtyID = source.ProviderSpecialtyID + AND target.ProviderLineItemID = source.ProviderLineItemID + WHERE source.BudgetConfigID = @BudgetConfigID + AND target.OriginalValue != source.OriginalValue + GROUP BY target.BudgetConfigID, + target.EntityID, + target.DepartmentID, + target.AccountID, + target.PatientClassID, + target.PayorID, + target.FinancialReportingID, + target.UnitTypeID, + target.TimeClassID, + target.FiscalMonthID, + target.FiscalYearID, + target.ProviderID, + target.ProviderTypeID, + target.ProviderSpecialtyID, + target.ProviderLineItemID + + -- Update the records + UPDATE source + SET + source.OriginalValue = ISNULL(target.OriginalValue, 0) + FROM [fp].[FactReportStatistics] source + INNER JOIN #departments ft on ft.DepartmentID = source.DepartmentID + INNER JOIN #dataToUpdate target ON target.BudgetConfigID = source.BudgetConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.AccountID = source.AccountID + AND target.PatientClassID = source.PatientClassID + AND target.PayorID = source.PayorID + AND target.FinancialReportingID = source.FinancialReportingID + AND target.UnitTypeID = source.UnitTypeID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + AND target.ProviderID = source.ProviderID + AND target.ProviderTypeID = source.ProviderTypeID + AND target.ProviderSpecialtyID = source.ProviderSpecialtyID + AND target.ProviderLineItemID = source.ProviderLineItemID + +END +GO + + +--------------------------------------------- + +-- fp.procProcessReportFactStatistics_TargetBudget +CREATE PROCEDURE [fp].[procProcessReportFactStatistics_TargetBudget] ( + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +) +WITH RECOMPILE +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2018-12-24 IP B-21543 Added temp table to index source as well + ** 2 2019-01-09 GF B-21715 Optimize full config refresh case + ** 3 2019-01-11 GF B-21715 Optimize targeted refresh case + ** 4 2019-05-02 GF X-XXXXX Remove special handling of all case to make concurrency work + ** 5 2019-07-22 MY X-XXXXX Performance updates + ** 6 2020-01-13 MY D-09168 CCF: Data not flowing through into reports + ** 7 2020-02-18 MY JAZZ-15375 Roll-up data above Provider for Report + ** 8 2021-05-10 MD JAZZ-15686 Add Provider dimensions to Stats data sources + ** 9 2021-11-10 BW JAZZ-1358 Add dept to the filter when untargeted, to remove orphans + ** 10 2022-08-30 MY JAZZ-42472 Improve Pivoting of Data for Reports + ** 11 2024-07-16 YR JAZZ-70315 Budget Config used for Report comparison is processed as well + *************************************************************/ + + EXEC [dbo].[procSysDropTempTable] '#SRC' + EXEC [dbo].[procSysDropTempTable] '#SourceDimensionality' + EXEC [dbo].[procSysDropTempTable] '#departments' + EXEC [dbo].[procSysDropTempTable] '#joinedStatData' + EXEC [dbo].[procSysDropTempTable] '#tempUnpivoted' + + --only the active config is supported currently + IF (NOT EXISTS(SELECT 1 FROM fp.BudgetConfig WHERE (IsActive = 1 OR IsUsedForReportComparison = 1) AND BudgetConfigID = @BudgetConfigID)) BEGIN RETURN END + + SELECT DISTINCT DepartmentID INTO #SourceDimensionality from fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #SourceDimensionality (DepartmentID) + SELECT DISTINCT DepartmentID FROM fp.FactStatistics + WHERE BudgetConfigID = @BudgetConfigID + END + + CREATE TABLE #SRC ( + BudgetConfigID INT, + EntityID INT, + DepartmentID INT, + AccountID INT, + PatientClassID INT, + PayorID INT, + FinancialReportingID INT, + UnitTypeID SMALLINT, + TimeClassID TINYINT, + FiscalMonthID TINYINT, + FiscalYearID SMALLINT, + ProviderID INT, + ProviderTypeID INT, + ProviderSpecialtyID INT, + ProviderLineItemID INT, + Value DECIMAL(19, 8), + ManagerValue DECIMAL(19, 8) + ) + + CREATE TABLE #joinedStatData ( + StatisticsID INT, + BudgetConfigID INT, + EntityID INT, + DepartmentID INT, + AccountID INT, + PatientClassID INT, + PayorID INT, + FinancialReportingID INT, + ProviderID INT, + ProviderTypeID INT, + ProviderSpecialtyID INT, + ProviderLineItemID INT, + UnitTypeID SMALLINT, + TimeClassID TINYINT, + FiscalYearID SMALLINT, + BudgetPhaseID TINYINT, + Month01 DECIMAL(19, 8), + Month02 DECIMAL(19, 8), + Month03 DECIMAL(19, 8), + Month04 DECIMAL(19, 8), + Month05 DECIMAL(19, 8), + Month06 DECIMAL(19, 8), + Month07 DECIMAL(19, 8), + Month08 DECIMAL(19, 8), + Month09 DECIMAL(19, 8), + Month10 DECIMAL(19, 8), + Month11 DECIMAL(19, 8), + Month12 DECIMAL(19, 8) + ) + + INSERT INTO #joinedStatData (StatisticsID, BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, ProviderID, + ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, UnitTypeID, TimeClassID, FiscalYearID, BudgetPhaseID, + Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12) + SELECT + fs.StatisticsID, + fs.BudgetConfigID, + fs.EntityID, + fs.DepartmentID, + fs.AccountID, + fs.PatientClassID, + fs.PayorID, + fs.FinancialReportingID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.UnitTypeID, + 2 as TimeClassID, + bc.FiscalYearID, + bdgt.BudgetPhaseID, + bdgt.AdjustedValue01 AS Month01, + bdgt.AdjustedValue02 AS Month02, + bdgt.AdjustedValue03 AS Month03, + bdgt.AdjustedValue04 AS Month04, + bdgt.AdjustedValue05 AS Month05, + bdgt.AdjustedValue06 AS Month06, + bdgt.AdjustedValue07 AS Month07, + bdgt.AdjustedValue08 AS Month08, + bdgt.AdjustedValue09 AS Month09, + bdgt.AdjustedValue10 AS Month10, + bdgt.AdjustedValue11 AS Month11, + bdgt.AdjustedValue12 AS Month12 + FROM fp.FactStatistics fs + INNER JOIN fp.FactStatisticsBudget bdgt ON fs.StatisticsID = bdgt.StatisticsID + INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID + WHERE fs.BudgetConfigID = @BudgetConfigID + + INSERT INTO #joinedStatData (StatisticsID, BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, ProviderID, + ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, UnitTypeID, TimeClassID, FiscalYearID, BudgetPhaseID, + Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12) + SELECT + fs.StatisticsID, + fs.BudgetConfigID, + fs.EntityID, + fs.DepartmentID, + fs.AccountID, + fs.PatientClassID, + fs.PayorID, + fs.FinancialReportingID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.UnitTypeID, + 12 as TimeClassID, + bc.FiscalYearID - 1, + bdgt.BudgetPhaseID, + bdgt.AdjustedValue01 AS Month01, + bdgt.AdjustedValue02 AS Month02, + bdgt.AdjustedValue03 AS Month03, + bdgt.AdjustedValue04 AS Month04, + bdgt.AdjustedValue05 AS Month05, + bdgt.AdjustedValue06 AS Month06, + bdgt.AdjustedValue07 AS Month07, + bdgt.AdjustedValue08 AS Month08, + bdgt.AdjustedValue09 AS Month09, + bdgt.AdjustedValue10 AS Month10, + bdgt.AdjustedValue11 AS Month11, + bdgt.AdjustedValue12 AS Month12 + FROM fp.FactStatistics fs + INNER JOIN fp.FactStatisticsProjection bdgt ON fs.StatisticsID = bdgt.StatisticsID + INNER JOIN fp.BudgetConfig bc ON fs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN #SourceDimensionality ft on ft.DepartmentID = fs.DepartmentID + WHERE fs.BudgetConfigID = @BudgetConfigID + + CREATE CLUSTERED INDEX inx_src ON #SRC ( + BudgetConfigID + ,EntityID + ,DepartmentID + ,AccountID + ,PatientClassID + ,PayorID + ,FinancialReportingID + ,UnitTypeID + ,TimeClassID + ,FiscalMonthID + ,FiscalYearID + ,ProviderID + ,ProviderTypeID + ,ProviderSpecialtyID + ,ProviderLineItemID + ) WITH (DATA_COMPRESSION = PAGE) + + -- Pivot the data into the #SRC Table + INSERT INTO #SRC(BudgetConfigID, EntityID, VW.DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, UnitTypeID, TimeClassID, FiscalYearID, FiscalMonthID, + Value, ManagerValue) + SELECT + cv.BudgetConfigID, + cv.EntityID, + cv.DepartmentID, + cv.AccountID, + cv.PatientClassID, + cv.PayorID, + cv.FinancialReportingID, + cv.ProviderID, + cv.ProviderTypeID, + cv.ProviderSpecialtyID, + cv.ProviderLineItemID, + cv.UnitTypeID, + cv.TimeClassID, + cv.FiscalYearID, + m.FiscalMonthID, + SUM(CASE WHEN cv.BudgetPhaseID = 2 THEN cv.Value ELSE NULL END) AS Value, + SUM(CASE WHEN cv.BudgetPhaseID = 3 THEN cv.Value ELSE NULL END) AS ManagerValue + FROM ( + SELECT BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, ProviderID, ProviderTypeID, + ProviderSpecialtyID, ProviderLineItemID, UnitTypeID, TimeClassID, FiscalYearID, BudgetPhaseID, FiscalMonth, Value + FROM #joinedStatData stat + CROSS APPLY ( + VALUES + ('Month01', Month01), + ('Month02', Month02), + ('Month03', Month03), + ('Month04', Month04), + ('Month05', Month05), + ('Month06', Month06), + ('Month07', Month07), + ('Month08', Month08), + ('Month09', Month09), + ('Month10', Month10), + ('Month11', Month11), + ('Month12', Month12)) X (FiscalMonth, Value) + ) cv + INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = cv.FiscalMonth + WHERE 1 = 1 + AND ( + CASE WHEN cv.BudgetPhaseID = 2 THEN cv.Value ELSE NULL END != 0 OR + CASE WHEN cv.BudgetPhaseID = 3 THEN cv.Value ELSE NULL END != 0 + ) -- In the original we exclude (OriginalValue != 0 or Value != 0 or ManagerValue != 0) to avoid too many empty rows. It helps lean out the data some. + GROUP BY cv.BudgetConfigID, + cv.EntityID, + cv.DepartmentID, + cv.AccountID, + cv.PatientClassID, + cv.PayorID, + cv.FinancialReportingID, + cv.ProviderID, + cv.ProviderTypeID, + cv.ProviderSpecialtyID, + cv.ProviderLineItemID, + cv.UnitTypeID, + cv.TimeClassID, + cv.FiscalYearID, + m.FiscalMonthID + + -- Get all of the departments in that could be affected. We need to get this list to eliminate + -- the null check in the join in the with statement. + SELECT DISTINCT DepartmentID INTO #departments + FROM ( + SELECT DISTINCT DepartmentID FROM #SRC + UNION ALL + SELECT DISTINCT DepartmentID FROM #SourceDimensionality + ) data + + ;WITH TGT AS + ( + SELECT BudgetConfigID, EntityID, FRS.DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, + TimeClassID, FiscalMonthID, FiscalYearID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, + Value, ManagerValue + FROM fp.FactReportStatistics FRS + INNER JOIN #departments ft on ft.DepartmentID = FRS.DepartmentID + WHERE FRS.BudgetConfigID = @BudgetConfigID + ) + MERGE TGT AS target + USING #SRC AS source + ON ( + target.BudgetConfigID = source.BudgetConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.AccountID = source.AccountID + AND target.PatientClassID = source.PatientClassID + AND target.PayorID = source.PayorID + AND target.FinancialReportingID = source.FinancialReportingID + AND target.UnitTypeID = source.UnitTypeID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + AND target.ProviderID = source.ProviderID + AND target.ProviderTypeID = source.ProviderTypeID + AND target.ProviderSpecialtyID = source.ProviderSpecialtyID + AND target.ProviderLineItemID = source.ProviderLineItemID + + ) + WHEN MATCHED AND ( + target.Value <> source.Value + OR target.ManagerValue <> source.ManagerValue) + THEN + UPDATE SET + target.Value = ISNULL(source.Value, 0), + target.ManagerValue = ISNULL(source.ManagerValue, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + BudgetConfigID + ,EntityID + ,DepartmentID + ,AccountID + ,PatientClassID + ,PayorID + ,FinancialReportingID + ,UnitTypeID + ,TimeClassID + ,FiscalMonthID + ,FiscalYearID + ,ProviderID + ,ProviderTypeID + ,ProviderSpecialtyID + ,ProviderLineItemID + ,Value + ,ManagerValue + ) + VALUES ( + source. BudgetConfigID + ,source.EntityID + ,source.DepartmentID + ,source.AccountID + ,source.PatientClassID + ,source.PayorID + ,source.FinancialReportingID + ,source.UnitTypeID + ,source.TimeClassID + ,source.FiscalMonthID + ,source.FiscalYearID + ,source.ProviderID + ,source.ProviderTypeID + ,source.ProviderSpecialtyID + ,source.ProviderLineItemID + ,ISNULL(source.Value, 0) + ,ISNULL(source.ManagerValue, 0) + ); + -- NOTE: We are not removing any records that don't match because we don't want cases where there is a record for Original Value, but not for Target/Budget (aka it's 0) and then the Baseline gets deleted. + + ------------------------------------------------------------------------------------------------------- + -- Data not flowing through into reports after setting the record to 0 + -- This would happen when records were being 0'd out in plan editor and they'd be filtered out during the + -- targeting above because we only populate records that are not 0 + ------------------------------------------------------------------------------------------------------- + + -- Check if targeting exists, if it doesn't for this part, wipe it and populate all departments + -- We can't rely on the existing departments because of the check for the padded rows. + IF NOT EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL) + BEGIN + + TRUNCATE TABLE #departments; + + INSERT INTO #departments (DepartmentID) + SELECT DepartmentID + FROM [fw].[DimDepartment] dept + + END + + -- Get all records that were adjusted + SELECT DISTINCT chg.StatisticsID + INTO #adjustedRecords + FROM [fp].[StatisticsChangeHistory] chg + INNER JOIN [fp].[FactStatistics] fgl ON chg.BudgetConfigID = fgl.BudgetConfigID AND chg.StatisticsID = fgl.StatisticsID + INNER JOIN #departments ft on ft.DepartmentID = fgl.DepartmentID + WHERE chg.BudgetConfigID = @BudgetConfigID + + -- Get the records that have 0's in them that might have been filtered out from the previous logic + SELECT + cv.BudgetConfigID, + cv.EntityID, + cv.DepartmentID, + cv.AccountID, + cv.PatientClassID, + cv.PayorID, + cv.FinancialReportingID, + cv.ProviderID, + cv.ProviderTypeID, + cv.ProviderSpecialtyID, + cv.ProviderLineItemID, + cv.UnitTypeID, + cv.TimeClassID, + cv.FiscalYearID, + m.FiscalMonthID, + SUM(CASE WHEN cv.BudgetPhaseID = 2 THEN cv.Value ELSE NULL END) AS Value, + SUM(CASE WHEN cv.BudgetPhaseID = 3 THEN cv.Value ELSE NULL END) AS ManagerValue + INTO #tempUnpivoted + FROM ( + SELECT BudgetConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, ProviderID, ProviderTypeID, + ProviderSpecialtyID, ProviderLineItemID, UnitTypeID, TimeClassID, FiscalYearID, BudgetPhaseID, FiscalMonth, Value + FROM #joinedStatData stat + CROSS APPLY ( + VALUES + ('Month01', Month01), + ('Month02', Month02), + ('Month03', Month03), + ('Month04', Month04), + ('Month05', Month05), + ('Month06', Month06), + ('Month07', Month07), + ('Month08', Month08), + ('Month09', Month09), + ('Month10', Month10), + ('Month11', Month11), + ('Month12', Month12)) X (FiscalMonth, Value) + ) cv + INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = cv.FiscalMonth + WHERE 1 = 1 + AND ( + CASE WHEN cv.BudgetPhaseID = 2 THEN cv.Value ELSE NULL END = 0 OR + CASE WHEN cv.BudgetPhaseID = 3 THEN cv.Value ELSE NULL END = 0 + ) + GROUP BY cv.BudgetConfigID, + cv.EntityID, + cv.DepartmentID, + cv.AccountID, + cv.PatientClassID, + cv.PayorID, + cv.FinancialReportingID, + cv.ProviderID, + cv.ProviderTypeID, + cv.ProviderSpecialtyID, + cv.ProviderLineItemID, + cv.UnitTypeID, + cv.TimeClassID, + cv.FiscalYearID, + m.FiscalMonthID + + -- Find the records that need to be updated by comparing the source to the reporting table + SELECT + target.BudgetConfigID, + target.EntityID, + target.DepartmentID, + target.AccountID, + target.PatientClassID, + target.PayorID, + target.FinancialReportingID, + target.UnitTypeID, + target.TimeClassID, + target.FiscalMonthID, + target.FiscalYearID, + target.ProviderID, + target.ProviderTypeID, + target.ProviderSpecialtyID, + target.ProviderLineItemID, + SUM(target.Value) AS Value, + SUM(target.ManagerValue) AS ManagerValue + INTO #dataToUpdate + FROM [fp].[FactReportStatistics] source + INNER JOIN #departments ft on ft.DepartmentID = source.DepartmentID + INNER JOIN #tempUnpivoted target ON target.BudgetConfigID = source.BudgetConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.AccountID = source.AccountID + AND target.PatientClassID = source.PatientClassID + AND target.PayorID = source.PayorID + AND target.FinancialReportingID = source.FinancialReportingID + AND target.UnitTypeID = source.UnitTypeID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + AND target.ProviderID = source.ProviderID + AND target.ProviderTypeID = source.ProviderTypeID + AND target.ProviderSpecialtyID = source.ProviderSpecialtyID + AND target.ProviderLineItemID = source.ProviderLineItemID + WHERE source.BudgetConfigID = @BudgetConfigID + AND (target.Value != source.Value OR target.ManagerValue != source.ManagerValue) + GROUP BY target.BudgetConfigID, + target.EntityID, + target.DepartmentID, + target.AccountID, + target.PatientClassID, + target.PayorID, + target.FinancialReportingID, + target.UnitTypeID, + target.TimeClassID, + target.FiscalMonthID, + target.FiscalYearID, + target.ProviderID, + target.ProviderTypeID, + target.ProviderSpecialtyID, + target.ProviderLineItemID + + -- Update the records + UPDATE source + SET + source.Value = ISNULL(target.Value, 0), + source.ManagerValue = ISNULL(target.ManagerValue, 0) + FROM [fp].[FactReportStatistics] source + INNER JOIN #departments ft on ft.DepartmentID = source.DepartmentID + INNER JOIN #dataToUpdate target ON target.BudgetConfigID = source.BudgetConfigID + AND target.EntityID = source.EntityID + AND target.DepartmentID = source.DepartmentID + AND target.AccountID = source.AccountID + AND target.PatientClassID = source.PatientClassID + AND target.PayorID = source.PayorID + AND target.FinancialReportingID = source.FinancialReportingID + AND target.UnitTypeID = source.UnitTypeID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.FiscalYearID = source.FiscalYearID + AND target.ProviderID = source.ProviderID + AND target.ProviderTypeID = source.ProviderTypeID + AND target.ProviderSpecialtyID = source.ProviderSpecialtyID + AND target.ProviderLineItemID = source.ProviderLineItemID +END +GO + + +--------------------------------------------- + +-- fp.procProviderBudgetStampOff +CREATE PROCEDURE [fp].[procProviderBudgetStampOff] + @BudgetConfigID INT, + @TargetTimeClassID TINYINT +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 01-31-2023 MY JAZZ-48962 Initial Creation + ** 2 05-15-2023 BW JAZZ-51541 Add provider compensation + ** 3 01-03-2024 MZ JAZZ-65385 Added Target TimeClass + ** 4 12-04-2023 BW/MZ JAZZ-63562 Data model restructure for Staffing/Merge with main + ** 5 03-18-2024 MZ JAZZ-68428 Deleting by Chunks & removed HistoryItemGUID parameter + *************************************************************/ + + -- Note: The original script was done here https://stratadecision.atlassian.net/wiki/spaces/DD/pages/3116205785/Moving+Data+from+a+Plan+Configuration+to+Int+Tables + + DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID ) + DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID) + + DECLARE @HistoryItemGUID UNIQUEIDENTIFIER + EXEC procLogScript 'StampOff: Transferring Budget Data from 1p', @HistoryItemGUID OUTPUT + PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36)) + PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID) + + -- Clear out existing records for the selected FiscalYear and Budgeted Time Class + DECLARE @ChunkCount INT + + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END + + DECLARE @r INT; + SET @r = 1; + + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) FROM [int].[FactProvider] WHERE FiscalYearID = @FiscalYear and TimeClassID = @TargetTimeClassID + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + INSERT INTO [int].[FactProvider] ([DepartmentID], [DepartmentCode], [PhysicianID], [ProviderCode], [ProviderLineItemID], [TimeClassID], [TimeClassCode], + [FiscalYearID], [FiscalYearCode], [FiscalMonthID], [FiscalMonthCode], [UnitTypeID], [UnitTypeName], [Value], [IsDeleted], [HistoryitemGUID]) + SELECT + d.DepartmentID, + d.DepartmentCode, + ph.PhysicianID, + ph.PhysicianCode , + ProviderLineItemID, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + bc.FiscalYearID, + bc.FiscalYearID AS FiscalYearCode, + fm.FiscalMonthID, + fm.FiscalMonthCode, + ut.UnitTypeID, + ut.Name AS UnitTypeName, + Value AS Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID + FROM ( + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, ProviderID, providerlineitemID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT cv.StatisticsID, cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.AccountID, cv.ProviderID, cv.ProviderlineitemID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, + bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, + bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactStatistics cv + INNER JOIN fp.FactStatisticsBudget bdgt ON cv.StatisticsID = bdgt.StatisticsID + Inner JOIN fp.ProviderStatisticsConfig PrConfig ON Prconfig.BudgetConfigID = cv.BudgetConfigID and PrConfig.AccountID = cv.AccountID + WHERE bdgt.BudgetPhaseID = 3 + AND cv.BudgetConfigID = @BudgetConfigID + ) cv + UNPIVOT (Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month') + ) BudgetedData + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = BudgetedData.BudgetConfigID + INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = BudgetedData.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = BudgetedData.FiscalMonthID + INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = BudgetedData.UnitTypeID + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = BudgetedData.AccountID + INNER JOIN dss.DimPhysician ph ON ph.PhysicianID = BudgetedData.ProviderID + WHERE 1=1 + AND BudgetedData.Value <> 0 + AND bc.BudgetConfigID = @BudgetConfigID + + -- Compensation + INSERT INTO [int].[FactProvider] ([DepartmentID], [DepartmentCode], [PhysicianID], [ProviderCode], [ProviderLineItemID], [TimeClassID], [TimeClassCode], + [FiscalYearID], [FiscalYearCode], [FiscalMonthID], [FiscalMonthCode], [UnitTypeID], [UnitTypeName], [Value], [IsDeleted], [HistoryitemGUID]) + SELECT + d.DepartmentID, + d.DepartmentCode, + ph.PhysicianID, + ph.PhysicianCode , + staff.ProviderLineItemID, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + bc.FiscalYearID, + bc.FiscalYearID AS FiscalYearCode, + m.FiscalMonthID, + m.FiscalMonthCode, + ut.UnitTypeID, + ut.Name AS UnitTypeName, + Value AS Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID + FROM fp.Staffing staff (READUNCOMMITTED) + INNER JOIN fp.ProviderStaffingConfig PrConfig ON Prconfig.BudgetConfigID = staff.BudgetConfigID and PrConfig.ProviderLineItemID = staff.ProviderLineItemID + CROSS APPLY ( + VALUES + ( 1, 34, BudgetAdjustedDollars01), + ( 2, 34, BudgetAdjustedDollars02), + ( 3, 34, BudgetAdjustedDollars03), + ( 4, 34, BudgetAdjustedDollars04), + ( 5, 34, BudgetAdjustedDollars05), + ( 6, 34, BudgetAdjustedDollars06), + ( 7, 34, BudgetAdjustedDollars07), + ( 8, 34, BudgetAdjustedDollars08), + ( 9, 34, BudgetAdjustedDollars09), + ( 10, 34, BudgetAdjustedDollars10), + ( 11, 34, BudgetAdjustedDollars11), + ( 12, 34, BudgetAdjustedDollars12) + + ) AS CrossApplied (FiscalMonth, UnitTypeID, Value) + LEFT JOIN fw.DimUnitType ut ON ut.UnitTypeID = CrossApplied.UnitTypeID + LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.FiscalMonth + INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = staff.DepartmentID + INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [dss].[DimPhysician] ph ON ph.PhysicianID = staff.ProviderID + WHERE Value <> 0 + AND bc.BudgetConfigID = @BudgetConfigID +END +GO + + +--------------------------------------------- + +-- fp.procProviderCompensationApplySpread +CREATE PROCEDURE [fp].[procProviderCompensationApplySpread] + @BudgetConfigID int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-04-13 OP JAZZ-18025 Created + ** 2 2022-04-19 MZ JAZZ-33812 Extended by UnitTypeID (cut with Hours and added condition on the update) + ** 3 2023-10-05 BK JAZZ-60975 Update for new data structure + ** 4 2023-12-13 BW JAZZ-62541 Update for new data structure - update to use the latest working hours view [fp].[viewWorkingHours] + ** 5 2023-02-21 MY JAZZ-67948 Fix Issue where spreads to Dollars Impacts Hours + ** 6 2024-05-01 MY JAZZ-66044 Added Change History to Spreads + *************************************************************/ + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #filterTable (StaffingID INT PRIMARY KEY CLUSTERED, AllowDollars bit, AllowHours bit, AllowFTEs bit); + + CREATE TABLE #spreadsChangeHistory ( + StaffingID INT, + UnitTypeID SMALLINT NOT NULL DEFAULT(0), + OldValue01 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue02 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue03 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue04 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue05 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue06 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue07 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue08 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue09 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue10 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue11 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue12 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue01 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue02 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue03 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue04 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue05 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue06 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue07 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue08 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue09 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue10 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue11 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue12 DECIMAL(19, 8) NOT NULL DEFAULT(0), + ); + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + + INSERT INTO #filterTable (StaffingID, AllowDollars, AllowHours, AllowFTEs) + SELECT DISTINCT basis.StaffingID, + CASE WHEN (basis.BudgetDollarsLockType <> 1 AND basis.BudgetDollarsLockType <> 7) THEN 1 ELSE 0 END as AllowDollars, + CASE WHEN (basis.BudgetHoursLockType <> 1 AND basis.BudgetHoursLockType <> 7) THEN 1 ELSE 0 END as AllowHours, + CASE WHEN (basis.BudgetFTEsLockType <> 1 AND basis.BudgetFTEsLockType <> 7) THEN 1 ELSE 0 END as AllowFTEs + FROM [fp].[Staffing] basis + INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = basis.DepartmentID + INNER JOIN [fp].[ProviderCompensationSpreads] spread ON spread.BudgetConfigID = basis.BudgetConfigID + AND spread.DepartmentID = basis.DepartmentID + AND spread.JobCodeID = basis.JobCodeID + AND spread.PayCodeGroupID = basis.PayCodeGroupID + AND spread.ProviderID = basis.ProviderID + AND spread.ProviderLineItemID = basis.ProviderLineItemID + WHERE basis.BudgetConfigID = @BudgetConfigID + AND basis.VariabilityID = 1 -- fixed + AND spread.IsInactive = 0 + AND ( + (basis.BudgetDollarsLockType <> 1 AND basis.BudgetDollarsLockType <> 7) -- Ignore Final Value and Locked Adjustments + OR (basis.BudgetHoursLockType <> 1 AND basis.BudgetHoursLockType <> 7) -- Ignore Final Value and Locked Adjustments + OR (basis.BudgetFTEsLockType <> 1 AND basis.BudgetFTEsLockType <> 7) -- Ignore Final Value and Locked Adjustments + ) + AND basis.SubsectionID = 4 -- Provider Compensation + + END ELSE BEGIN + + -- If the table source dimensionality is unfiltered, we don't wanna join on the department filter. + INSERT INTO #filterTable (StaffingID, AllowDollars, AllowHours, AllowFTEs) + SELECT DISTINCT basis.StaffingID, + CASE WHEN (basis.BudgetDollarsLockType <> 1 AND basis.BudgetDollarsLockType <> 7) THEN 1 ELSE 0 END as AllowDollars, + CASE WHEN (basis.BudgetHoursLockType <> 1 AND basis.BudgetHoursLockType <> 7) THEN 1 ELSE 0 END as AllowHours, + CASE WHEN (basis.BudgetFTEsLockType <> 1 AND basis.BudgetFTEsLockType <> 7) THEN 1 ELSE 0 END as AllowFTEs + FROM [fp].[Staffing] basis + INNER JOIN [fp].[ProviderCompensationSpreads] spread ON spread.BudgetConfigID = basis.BudgetConfigID + AND spread.DepartmentID = basis.DepartmentID + AND spread.JobCodeID = basis.JobCodeID + AND spread.PayCodeGroupID = basis.PayCodeGroupID + AND spread.ProviderID = basis.ProviderID + AND spread.ProviderLineItemID = basis.ProviderLineItemID + WHERE basis.BudgetConfigID = @BudgetConfigID + AND basis.VariabilityID = 1 -- fixed + AND spread.IsInactive = 0 + AND ( + (basis.BudgetDollarsLockType <> 1 AND basis.BudgetDollarsLockType <> 7) -- Ignore Final Value and Locked Adjustments + OR (basis.BudgetHoursLockType <> 1 AND basis.BudgetHoursLockType <> 7) -- Ignore Final Value and Locked Adjustments + OR (basis.BudgetFTEsLockType <> 1 AND basis.BudgetFTEsLockType <> 7) -- Ignore Final Value and Locked Adjustments + ) + AND basis.SubsectionID = 4 -- Provider Compensation + + END + + -- Update dollars + UPDATE dollars + SET dollars.BudgetAdjustedDollars01 = CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01 AS DECIMAL(19,8)) + , dollars.BudgetAdjustedDollars02 = + CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN dollars.BudgetAdjustedDollarsTotal - CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02 AS DECIMAL(19,8)) END + , dollars.BudgetAdjustedDollars03 = + CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8))) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03 AS DECIMAL(19,8)) END + , dollars.BudgetAdjustedDollars04 = + CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8))) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04 AS DECIMAL(19,8)) END + , dollars.BudgetAdjustedDollars05 = + CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8))) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05 AS DECIMAL(19,8)) END + , dollars.BudgetAdjustedDollars06 = + CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8))) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06 AS DECIMAL(19,8)) END + , dollars.BudgetAdjustedDollars07 = + CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8))) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07 AS DECIMAL(19,8)) END + , dollars.BudgetAdjustedDollars08 = + CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07) AS DECIMAL(19, 8))) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage08 AS DECIMAL(19,8)) END + , dollars.BudgetAdjustedDollars09 = + CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage08) AS DECIMAL(19, 8))) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage09 AS DECIMAL(19,8)) END + , dollars.BudgetAdjustedDollars10 = + CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage09) AS DECIMAL(19, 8))) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage10 AS DECIMAL(19,8)) END + , dollars.BudgetAdjustedDollars11 = + CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 + THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage10) AS DECIMAL(19, 8))) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage11 AS DECIMAL(19,8)) END + , dollars.BudgetAdjustedDollars12 = + CASE WHEN SpreadPercentage12 != 0 + THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage11) AS DECIMAL(19, 8))) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage12 AS DECIMAL(19,8)) END + , BudgetDollarsLockType = CASE WHEN dollars.BudgetDollarsLockType IN (1,4,5) THEN dollars.BudgetDollarsLockType ELSE 6 END + , BudgetDollarsLockFlag = 1 + OUTPUT + inserted.StaffingID, 34, + deleted.BudgetAdjustedDollars01, deleted.BudgetAdjustedDollars02, deleted.BudgetAdjustedDollars03, deleted.BudgetAdjustedDollars04, deleted.BudgetAdjustedDollars05, deleted.BudgetAdjustedDollars06, + deleted.BudgetAdjustedDollars07, deleted.BudgetAdjustedDollars08, deleted.BudgetAdjustedDollars09, deleted.BudgetAdjustedDollars10, deleted.BudgetAdjustedDollars11, deleted.BudgetAdjustedDollars12, + inserted.BudgetAdjustedDollars01, inserted.BudgetAdjustedDollars02, inserted.BudgetAdjustedDollars03, inserted.BudgetAdjustedDollars04, inserted.BudgetAdjustedDollars05, inserted.BudgetAdjustedDollars06, + inserted.BudgetAdjustedDollars07, inserted.BudgetAdjustedDollars08, inserted.BudgetAdjustedDollars09, inserted.BudgetAdjustedDollars10, inserted.BudgetAdjustedDollars11, inserted.BudgetAdjustedDollars12 + INTO + #spreadsChangeHistory (StaffingID, UnitTypeID, + OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06, + OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12, + NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06, + NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) + FROM [fp].[viewProviderCompensationSpreads] spread + INNER JOIN [fp].[Staffing] dollars + ON spread.BudgetConfigID = dollars.BudgetConfigID + AND spread.DepartmentID = dollars.DepartmentID + AND spread.JobCodeID = dollars.JobCodeID + AND spread.PayCodeGroupID = dollars.PayCodeGroupID + AND spread.ProviderID = dollars.ProviderID + AND spread.ProviderLineItemID = dollars.ProviderLineItemID + INNER JOIN #filterTable tmp on dollars.StaffingID = tmp.StaffingID + WHERE spread.IsInactive = 0 + AND tmp.AllowDollars = 1 + AND spread.UnitTypeID = 34 -- dollars + + -- Update hours + UPDATE hours + SET hours.BudgetAdjustedHours01 = CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage01 AS DECIMAL(19,8)) + , hours.BudgetAdjustedHours02 = + CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN hours.BudgetAdjustedHoursTotal - CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage02 AS DECIMAL(19,8)) END + , hours.BudgetAdjustedHours03 = + CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8))) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage03 AS DECIMAL(19,8)) END + , hours.BudgetAdjustedHours04 = + CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8))) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage04 AS DECIMAL(19,8)) END + , hours.BudgetAdjustedHours05 = + CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8))) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage05 AS DECIMAL(19,8)) END + , hours.BudgetAdjustedHours06 = + CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8))) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage06 AS DECIMAL(19,8)) END + , hours.BudgetAdjustedHours07 = + CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8))) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage07 AS DECIMAL(19,8)) END + , hours.BudgetAdjustedHours08 = + CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage07) AS DECIMAL(19, 8))) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage08 AS DECIMAL(19,8)) END + , hours.BudgetAdjustedHours09 = + CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage08) AS DECIMAL(19, 8))) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage09 AS DECIMAL(19,8)) END + , hours.BudgetAdjustedHours10 = + CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage09) AS DECIMAL(19, 8))) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage10 AS DECIMAL(19,8)) END + , hours.BudgetAdjustedHours11 = + CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 + THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage10) AS DECIMAL(19, 8))) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage11 AS DECIMAL(19,8)) END + , hours.BudgetAdjustedHours12 = + CASE WHEN SpreadPercentage12 != 0 + THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage11) AS DECIMAL(19, 8))) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage12 AS DECIMAL(19,8)) END + , BudgetHoursLockType = CASE WHEN hours.BudgetHoursLockType IN (1,4,5) THEN hours.BudgetHoursLockType ELSE 6 END + , BudgetHoursLockFlag = 1 + OUTPUT + inserted.StaffingID, 51, + deleted.BudgetAdjustedHours01, deleted.BudgetAdjustedHours02, deleted.BudgetAdjustedHours03, deleted.BudgetAdjustedHours04, deleted.BudgetAdjustedHours05, deleted.BudgetAdjustedHours06, + deleted.BudgetAdjustedHours07, deleted.BudgetAdjustedHours08, deleted.BudgetAdjustedHours09, deleted.BudgetAdjustedHours10, deleted.BudgetAdjustedHours11, deleted.BudgetAdjustedHours12, + inserted.BudgetAdjustedHours01, inserted.BudgetAdjustedHours02, inserted.BudgetAdjustedHours03, inserted.BudgetAdjustedHours04, inserted.BudgetAdjustedHours05, inserted.BudgetAdjustedHours06, + inserted.BudgetAdjustedHours07, inserted.BudgetAdjustedHours08, inserted.BudgetAdjustedHours09, inserted.BudgetAdjustedHours10, inserted.BudgetAdjustedHours11, inserted.BudgetAdjustedHours12 + INTO + #spreadsChangeHistory (StaffingID, UnitTypeID, + OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06, + OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12, + NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06, + NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) + FROM [fp].[viewProviderCompensationSpreads] spread + INNER JOIN [fp].[Staffing] hours + ON spread.BudgetConfigID = hours.BudgetConfigID + AND spread.DepartmentID = hours.DepartmentID + AND spread.JobCodeID = hours.JobCodeID + AND spread.PayCodeGroupID = hours.PayCodeGroupID + AND spread.ProviderID = hours.ProviderID + AND spread.ProviderLineItemID = hours.ProviderLineItemID + INNER JOIN #filterTable tmp on hours.StaffingID = tmp.StaffingID + WHERE spread.IsInactive = 0 + AND tmp.AllowHours = 1 + AND spread.UnitTypeID = 51 -- hours + + -- Recalculate FTEs based on Hours + UPDATE ftes + SET + ftes.BudgetAdjustedFTEs01 = CASE WHEN hours.BudgetWorkingHours01 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours01 / hours.BudgetWorkingHours01 END, + ftes.BudgetAdjustedFTEs02 = CASE WHEN hours.BudgetWorkingHours02 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours02 / hours.BudgetWorkingHours02 END, + ftes.BudgetAdjustedFTEs03 = CASE WHEN hours.BudgetWorkingHours03 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours03 / hours.BudgetWorkingHours03 END, + ftes.BudgetAdjustedFTEs04 = CASE WHEN hours.BudgetWorkingHours04 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours04 / hours.BudgetWorkingHours04 END, + ftes.BudgetAdjustedFTEs05 = CASE WHEN hours.BudgetWorkingHours05 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours05 / hours.BudgetWorkingHours05 END, + ftes.BudgetAdjustedFTEs06 = CASE WHEN hours.BudgetWorkingHours06 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours06 / hours.BudgetWorkingHours06 END, + ftes.BudgetAdjustedFTEs07 = CASE WHEN hours.BudgetWorkingHours07 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours07 / hours.BudgetWorkingHours07 END, + ftes.BudgetAdjustedFTEs08 = CASE WHEN hours.BudgetWorkingHours08 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours08 / hours.BudgetWorkingHours08 END, + ftes.BudgetAdjustedFTEs09 = CASE WHEN hours.BudgetWorkingHours09 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours09 / hours.BudgetWorkingHours09 END, + ftes.BudgetAdjustedFTEs10 = CASE WHEN hours.BudgetWorkingHours10 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours10 / hours.BudgetWorkingHours10 END, + ftes.BudgetAdjustedFTEs11 = CASE WHEN hours.BudgetWorkingHours11 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours11 / hours.BudgetWorkingHours11 END, + ftes.BudgetAdjustedFTEs12 = CASE WHEN hours.BudgetWorkingHours12 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours12 / hours.BudgetWorkingHours12 END, + ftes.BudgetFTEsLockType = CASE WHEN ftes.BudgetFTEsLockType IN (1,4,5) THEN ftes.BudgetFTEsLockType ELSE 6 END, + ftes.BudgetFTEsLockFlag = 1 + OUTPUT + inserted.StaffingID, 144, + deleted.BudgetAdjustedFTEs01, deleted.BudgetAdjustedFTEs02, deleted.BudgetAdjustedFTEs03, deleted.BudgetAdjustedFTEs04, deleted.BudgetAdjustedFTEs05, deleted.BudgetAdjustedFTEs06, + deleted.BudgetAdjustedFTEs07, deleted.BudgetAdjustedFTEs08, deleted.BudgetAdjustedFTEs09, deleted.BudgetAdjustedFTEs10, deleted.BudgetAdjustedFTEs11, deleted.BudgetAdjustedFTEs12, + inserted.BudgetAdjustedFTEs01, inserted.BudgetAdjustedFTEs02, inserted.BudgetAdjustedFTEs03, inserted.BudgetAdjustedFTEs04, inserted.BudgetAdjustedFTEs05, inserted.BudgetAdjustedFTEs06, + inserted.BudgetAdjustedFTEs07, inserted.BudgetAdjustedFTEs08, inserted.BudgetAdjustedFTEs09, inserted.BudgetAdjustedFTEs10, inserted.BudgetAdjustedFTEs11, inserted.BudgetAdjustedFTEs12 + INTO + #spreadsChangeHistory (StaffingID, UnitTypeID, + OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06, + OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12, + NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06, + NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) + FROM [fp].[Staffing] ftes + INNER JOIN [fp].[viewProviderCompensationSpreads] spread + ON spread.BudgetConfigID = ftes.BudgetConfigID + AND spread.DepartmentID = ftes.DepartmentID + AND spread.JobCodeID = ftes.JobCodeID + AND spread.PayCodeGroupID = ftes.PayCodeGroupID + AND spread.ProviderID = ftes.ProviderID + AND spread.ProviderLineItemID = ftes.ProviderLineItemID + INNER JOIN [fp].[viewWorkingHours] hours + ON ftes.DepartmentID = hours.DepartmentID + AND ftes.EntityID = hours.EntityID + AND ftes.JobCodeID = hours.JobCodeID + AND ftes.PayCodeGroupID = hours.PayCodeGroupID + AND ftes.ProductiveClassID = hours.ProductiveClassID + AND ftes.EntityGroupConfigID = hours.EntityGroupConfigID + AND ftes.EmployeeID = hours.EmployeeID + AND ftes.VariabilityID = hours.VariabilityID + INNER JOIN #filterTable f ON f.StaffingID = ftes.StaffingID -- should be limited to rows needing spread by this + WHERE ftes.VariabilityID = 1 + AND f.AllowFTEs = 1 + AND spread.UnitTypeID = 51 -- Only Lock and Recalc FTEs for Hour based Spreads + AND ftes.ProductiveClassID NOT IN (4, 5, 6) -- Dollars-Only, Differential, Productive Non-FTE + AND ( + ftes.BudgetAdjustedHours01 <> 0 + OR ftes.BudgetAdjustedHours02 <> 0 + OR ftes.BudgetAdjustedHours03 <> 0 + OR ftes.BudgetAdjustedHours04 <> 0 + OR ftes.BudgetAdjustedHours05 <> 0 + OR ftes.BudgetAdjustedHours06 <> 0 + OR ftes.BudgetAdjustedHours07 <> 0 + OR ftes.BudgetAdjustedHours08 <> 0 + OR ftes.BudgetAdjustedHours09 <> 0 + OR ftes.BudgetAdjustedHours10 <> 0 + OR ftes.BudgetAdjustedHours11 <> 0 + OR ftes.BudgetAdjustedHours12 <> 0 + ) + + -- Populate Change History + IF EXISTS(SELECT 1 + FROM fp.viewBudgetConfigSetting + WHERE Name = 'Spreads Change History Logic Is Enabled' + AND BudgetConfigID = @BudgetConfigID + AND Value = 1) + BEGIN + + INSERT INTO fp.StaffingSpreadsChangeHistory (StaffingID, BudgetConfigID, SubsectionID, UnitTypeID, OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06, + OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12, NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06, + NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) + SELECT StaffingID, @BudgetConfigID, 4 -- Provider + , UnitTypeID, + ISNULL(OldValue01, 0), ISNULL(OldValue02, 0), ISNULL(OldValue03, 0), ISNULL(OldValue04, 0), ISNULL(OldValue05, 0), ISNULL(OldValue06, 0), + ISNULL(OldValue07, 0), ISNULL(OldValue08, 0), ISNULL(OldValue09, 0), ISNULL(OldValue10, 0), ISNULL(OldValue11, 0), ISNULL(OldValue12, 0), + ISNULL(NewValue01, 0), ISNULL(NewValue02, 0), ISNULL(NewValue03, 0), ISNULL(NewValue04, 0), ISNULL(NewValue05, 0), ISNULL(NewValue06, 0), + ISNULL(NewValue07, 0), ISNULL(NewValue08, 0), ISNULL(NewValue09, 0), ISNULL(NewValue10, 0), ISNULL(NewValue11, 0), ISNULL(NewValue12, 0) + FROM #spreadsChangeHistory + WHERE 1 = 1 + AND ( + OldValue01 != NewValue01 + OR OldValue02 != NewValue02 + OR OldValue03 != NewValue03 + OR OldValue04 != NewValue04 + OR OldValue05 != NewValue05 + OR OldValue06 != NewValue06 + OR OldValue07 != NewValue07 + OR OldValue08 != NewValue08 + OR OldValue09 != NewValue09 + OR OldValue10 != NewValue10 + OR OldValue11 != NewValue11 + OR OldValue12 != NewValue12 + ) + + END + +END +GO + + +--------------------------------------------- + +-- fp.procProviderProjectionStampOff +CREATE PROCEDURE [fp].[procProviderProjectionStampOff] + @BudgetConfigID INT, + @TargetTimeClassID TINYINT, + @IsMonthsLoadedIncluded BIT +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 11-10-2023 AO JAZZ-62128 Initial Creation + ** 2 01-04-2024 MZ JAZZ-65385 Added Target TimeClass and IsMonthsLoadedIncluded + ** 3 01-24-2024 MZ JAZZ-64527 Fix Months Loaded + ** 4 12-04-2023 BW/MZ JAZZ-63562 Data model restructure for Staffing/Merge with main + ** 5 03-18-2024 MZ JAZZ-68428 Deleting by Chunks & removed HistoryItemGUID parameter + ** 6 04-03-2024 MZ JAZZ-70053 Fix Month Loaded excluding logic + *************************************************************/ + + -- Note: The original script was done here https://stratadecision.atlassian.net/wiki/spaces/DD/pages/3116205785/Moving+Data+from+a+Plan+Configuration+to+Int+Tables + + DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID - 1 FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID ) + DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID) + DECLARE @MonthsLoaded INT = (SELECT bc.MonthsLoaded FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID) + + DECLARE @HistoryItemGUID UNIQUEIDENTIFIER + EXEC procLogScript 'StampOff: Transferring Projection Data from 1p', @HistoryItemGUID OUTPUT + PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36)) + PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID) + + -- Clear out existing records for the selected FiscalYear and Projected Time Class + -- and all months if months loaded included otherwise only months NOT loaded will be cleared + DECLARE @ChunkCount INT + + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END + + DECLARE @r INT; + SET @r = 1; + + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) prov FROM [int].[FactProvider] prov + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID + WHERE prov.FiscalYearID = @FiscalYear + AND prov.TimeClassID = @TargetTimeClassID + AND (@IsMonthsLoadedIncluded = 1 OR fm.SortOrder > @MonthsLoaded) + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + INSERT INTO [int].[FactProvider] ([DepartmentID], [DepartmentCode], [PhysicianID], [ProviderCode], [ProviderLineItemID], [TimeClassID], [TimeClassCode], + [FiscalYearID], [FiscalYearCode], [FiscalMonthID], [FiscalMonthCode], [UnitTypeID], [UnitTypeName], [Value], [IsDeleted], [HistoryitemGUID]) + SELECT + d.DepartmentID, + d.DepartmentCode, + ph.PhysicianID, + ph.PhysicianCode , + ProviderLineItemID, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + @FiscalYear, + @FiscalYear AS FiscalYearCode, + fm.FiscalMonthID, + fm.FiscalMonthCode, + ut.UnitTypeID, + ut.Name AS UnitTypeName, + Value AS Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID + FROM ( + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, ProviderID, providerlineitemID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT cv.StatisticsID, cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.AccountID, cv.ProviderID, cv.ProviderlineitemID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, + bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, + bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactStatistics cv + INNER JOIN fp.FactStatisticsProjection bdgt ON cv.StatisticsID = bdgt.StatisticsID + INNER JOIN fp.ProviderStatisticsConfig PrConfig ON Prconfig.BudgetConfigID = cv.BudgetConfigID and PrConfig.AccountID = cv.AccountID + WHERE bdgt.BudgetPhaseID = 3 + AND cv.BudgetConfigID = @BudgetConfigID + ) cv + UNPIVOT (Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month') + ) BudgetedData + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = BudgetedData.BudgetConfigID + INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = BudgetedData.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = BudgetedData.FiscalMonthID + INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = BudgetedData.UnitTypeID + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = BudgetedData.AccountID + INNER JOIN dss.DimPhysician ph ON ph.PhysicianID = BudgetedData.ProviderID + WHERE 1=1 + AND BudgetedData.Value <> 0 + AND bc.BudgetConfigID = @BudgetConfigID + AND (@IsMonthsLoadedIncluded = 1 OR CAST(fm.FiscalMonthCode AS INT) > bc.MonthsLoaded) + + -- Compensation + INSERT INTO [int].[FactProvider] ([DepartmentID], [DepartmentCode], [PhysicianID], [ProviderCode], [ProviderLineItemID], [TimeClassID], [TimeClassCode], + [FiscalYearID], [FiscalYearCode], [FiscalMonthID], [FiscalMonthCode], [UnitTypeID], [UnitTypeName], [Value], [IsDeleted], [HistoryitemGUID]) + SELECT + d.DepartmentID, + d.DepartmentCode, + ph.PhysicianID, + ph.PhysicianCode , + staff.ProviderLineItemID, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + @FiscalYear, + @FiscalYear AS FiscalYearCode, + m.FiscalMonthID, + m.FiscalMonthCode, + ut.UnitTypeID, + ut.Name AS UnitTypeName, + Value AS Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID + FROM fp.Staffing staff (READUNCOMMITTED) + INNER JOIN fp.ProviderStaffingConfig PrConfig ON Prconfig.BudgetConfigID = staff.BudgetConfigID and PrConfig.ProviderLineItemID = staff.ProviderLineItemID + CROSS APPLY ( + VALUES + ( 1, 34, ProjectionAdjustedDollars01), + ( 2, 34, ProjectionAdjustedDollars02), + ( 3, 34, ProjectionAdjustedDollars03), + ( 4, 34, ProjectionAdjustedDollars04), + ( 5, 34, ProjectionAdjustedDollars05), + ( 6, 34, ProjectionAdjustedDollars06), + ( 7, 34, ProjectionAdjustedDollars07), + ( 8, 34, ProjectionAdjustedDollars08), + ( 9, 34, ProjectionAdjustedDollars09), + ( 10, 34, ProjectionAdjustedDollars10), + ( 11, 34, ProjectionAdjustedDollars11), + ( 12, 34, ProjectionAdjustedDollars12) + + ) AS CrossApplied (FiscalMonth, UnitTypeID, Value) + LEFT JOIN fw.DimUnitType ut ON ut.UnitTypeID = CrossApplied.UnitTypeID + LEFT JOIN fw.DimFiscalMonth m ON m.SortOrder = CrossApplied.FiscalMonth + INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = staff.DepartmentID + INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [dss].[DimPhysician] ph ON ph.PhysicianID = staff.ProviderID + WHERE Value <> 0 + AND bc.BudgetConfigID = @BudgetConfigID + AND (@IsMonthsLoadedIncluded = 1 OR CAST(m.FiscalMonthCode AS INT) > bc.MonthsLoaded) + +END +GO + + +--------------------------------------------- + +-- fp.procRebuildDatabaseStatistics +CREATE PROC [fp].[procRebuildDatabaseStatistics] + @IsDebug BIT = 0 +AS +BEGIN + SET NOCOUNT ON; + + IF OBJECT_ID('tempdb..#Debug') IS NOT NULL DROP TABLE #Debug + CREATE TABLE #Debug (SqlToExecute NVARCHAR(1024)) + + DECLARE @Schema NVARCHAR(2) + DECLARE @FactTableName NVARCHAR(256) + DECLARE @SQL nvarchar(1024) + + DECLARE FactTableCursor CURSOR FOR + SELECT TableName, SchemaName + FROM fp.RefreshDatabaseStatisticsConfiguration + WHERE IsActive = 1 + + OPEN FactTableCursor + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @Schema + WHILE @@FETCH_STATUS = 0 + BEGIN + + SET @SQL = 'UPDATE STATISTICS ' + @Schema + '.' + @FactTableName + ' WITH FULLSCAN' + + IF @IsDebug = 1 BEGIN + INSERT INTO #Debug (SqlToExecute) VALUES (@SQL) + END ELSE BEGIN + EXECUTE sp_executesql @SQL + END + + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @Schema + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + + IF @IsDebug = 1 BEGIN + SELECT * FROM #Debug + END +END +GO + + +--------------------------------------------- + +-- fp.procRebuildIndexesTargeted +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 05-16-2023 MY JAZZ-54812 Fix issue with renamed tables +** 2 12-13-2023 MY JAZZ-64522 Filtered out anything with OLD in the name as these are likely backup restructure tables +** 3 08-29-2024 MY JAZZ-74223 Remove FULLSCAN +** 4 11-06-2024 NH JAZZ-79530 Added square brackets to avoid conflicts +*************************************************************/ +CREATE PROC [fp].[procRebuildIndexesTargeted] + @isEncounter BIT, + @isChargeVolume BIT, + @isStats BIT, + @isStaffing BIT, + @isBenefits BIT, + @isGeneralLedger BIT, + @isDebug BIT +AS + SET NOCOUNT ON; + + DECLARE @SchemaID INT; + SELECT @SchemaID = schema_id from sys.schemas where name = 'fp' + DECLARE @SCHEMA NVARCHAR(2) + DECLARE @FactTableName NVARCHAR(256) + DECLARE @SQL nvarchar(1024) + + IF OBJECT_ID('tempdb..#Debug') IS NOT NULL DROP TABLE #Debug + CREATE TABLE #Debug (SqlToExecute NVARCHAR(1024)) + DECLARE FactTableCursor CURSOR FOR + SELECT t.name, 'fp' from sys.tables t + WHERE + t.schema_id = @SchemaID + AND t.name NOT LIKE '%Archive%' + AND t.name NOT LIKE 'Temp%' + AND t.name NOT LIKE '%old%' + AND ( (@isEncounter = 1 AND t.name like '%Encounter%') + OR (@isChargeVolume = 1 AND (t.name like '%ChargeVolume%')) + OR (@isStats = 1 AND t.name like '%Statistics%') + OR (@isStaffing = 1 AND t.name like '%Staffing%') + OR (@isBenefits = 1 AND t.name like '%Benefit%') + OR (@isGeneralLedger = 1 AND t.name like '%General%')) + + ORDER BY t.name + + OPEN FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + SET @SQL = 'update statistics [' + @SCHEMA + '].[' + @FactTableName + ']' + + IF @isDebug = 1 BEGIN + INSERT INTO #Debug (SqlToExecute) VALUES (@SQL) + END ELSE BEGIN + EXECUTE sp_executesql @SQL + END + + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + + IF @isDebug = 1 BEGIN + SELECT * FROM #Debug + END +GO + + +--------------------------------------------- + +-- fp.procRecalcBenefitsTotals +CREATE PROCEDURE [fp].[procRecalcBenefitsTotals] + @EntityGroupConfigID INT, + @EntityGroupConfigGUID UNIQUEIDENTIFIER, + @TimeClassID INT, + @SourceDimensionality [fp].BudgetRefreshSourceDimensionality READONLY + AS + BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table + ** 2 2022-02-23 NT JAZZ-33434 Clean up by removing IS NULL JOIN and SELECT * + ** 3 2022-07-12 NT JAZZ-39267 Add OPTION RECOMPILE to improve performance + ** 3 2022-09-07 BK JAZZ-42570 Add hash to inner join per Oleg recommendation + *************************************************************/ + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#FactBenefits') IS NOT NULL DROP TABLE #FactBenefits + + CREATE TABLE #FilterByDepartment (DepartmentID int, BudgetPhaseID int) + INSERT INTO #FilterByDepartment (DepartmentID, BudgetPhaseID) + SELECT DepartmentID, BudgetPhaseID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the FilterByDepartment does not have valid data then pass all departments to avoid duplicate statements + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[FactBenefits] fb + WHERE fb.EntityGroupConfigID = @EntityGroupConfigID + END + + DECLARE @Dollars INT = 34, + @Ftes INT = 144, + @DollarsPerFte INT = 171, + @Salaries INT = 169, + @PercentOfSalaries INT = 170 + + DECLARE @MonthsLoaded INT + SELECT @MonthsLoaded = bc.MonthsLoaded from [fp].[BudgetConfig] bc inner join [fp].[EntityGroupConfig] egc on egc.BudgetConfigGUID = bc.BudgetConfigGUID where egc.EntityGroupConfigID = @EntityGroupConfigID + + -- We need to return the benefits items that were adjusted to fix the change history + CREATE TABLE #budget_basisIDs (BenefitsID INT); + CREATE TABLE #projection_basisIDs (BenefitsID INT); + + CREATE TABLE #FactBenefits (BudgetConfigID INT, EntityID INT, DepartmentID INT, AccountID INT, UnitTypeID INT, FinancialReportingID INT, BudgetPhaseID INT, + Value01 DECIMAL(19,8), Value02 DECIMAL(19,8), Value03 DECIMAL(19,8), Value04 DECIMAL(19,8), Value05 DECIMAL(19,8), + Value06 DECIMAL(19,8), Value07 DECIMAL(19,8), Value08 DECIMAL(19,8), Value09 DECIMAL(19,8), Value10 DECIMAL(19,8), + Value11 DECIMAL(19,8), Value12 DECIMAL(19,8)) + + IF (@TimeClassID = 2) + BEGIN + + -- SAMPLE TOTALS FOR ACCOUNTS THAT ARE FLEXED BY SALARIES + INSERT INTO #FactBenefits (BudgetConfigID, EntityID, DepartmentID, AccountID, UnitTypeID, FinancialReportingID, BudgetPhaseID, Value01, + Value02, Value03, Value04, Value05, Value06, Value07, Value08, Value09, Value10, Value11, Value12) + SELECT + vol.BudgetConfigID, + vol.EntityID, + vol.DepartmentID, + vol.AccountID, + @Dollars as UnitTypeID, + vol.FinancialReportingID, + vol.BudgetPhaseID, + vol.AdjustedValue01 * rate.AdjustedValue01 AS Value01, + vol.AdjustedValue02 * rate.AdjustedValue02 AS Value02, + vol.AdjustedValue03 * rate.AdjustedValue03 AS Value03, + vol.AdjustedValue04 * rate.AdjustedValue04 AS Value04, + vol.AdjustedValue05 * rate.AdjustedValue05 AS Value05, + vol.AdjustedValue06 * rate.AdjustedValue06 AS Value06, + vol.AdjustedValue07 * rate.AdjustedValue07 AS Value07, + vol.AdjustedValue08 * rate.AdjustedValue08 AS Value08, + vol.AdjustedValue09 * rate.AdjustedValue09 AS Value09, + vol.AdjustedValue10 * rate.AdjustedValue10 AS Value10, + vol.AdjustedValue11 * rate.AdjustedValue11 AS Value11, + vol.AdjustedValue12 * rate.AdjustedValue12 AS Value12 + FROM + ( + SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID, budg.BudgetPhaseID, + budg.AdjustedValue01, budg.AdjustedValue02, budg.AdjustedValue03, budg.AdjustedValue04, budg.AdjustedValue05, budg.AdjustedValue06, budg.AdjustedValue07, + budg.AdjustedValue08, budg.AdjustedValue09, budg.AdjustedValue10, budg.AdjustedValue11, budg.AdjustedValue12 + FROM [fp].[FactBenefits] ben + INNER hash JOIN [fp].[FactBenefitsBudget] budg ON ben.BenefitsID = budg.BenefitsID + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID + WHERE UnitTypeID = @Salaries + AND EntityGroupConfigID = @EntityGroupConfigID + AND (budg.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL) + ) vol -- vol will give us the amount of either salaries or FTEs, the rate table will give us the % of salaries or $ per FTEs value + + INNER JOIN + ( + SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID, + budg.BudgetPhaseID, budg.AdjustedValue01, budg.AdjustedValue02, budg.AdjustedValue03, budg.AdjustedValue04, budg.AdjustedValue05, budg.AdjustedValue06, budg.AdjustedValue07, + budg.AdjustedValue08, budg.AdjustedValue09, budg.AdjustedValue10, budg.AdjustedValue11, budg.AdjustedValue12 + FROM [fp].[FactBenefits] ben + INNER JOIN #FilterByDepartment ft On ft.DepartmentID = ben.DepartmentID + INNER hash JOIN [fp].[FactBenefitsBudget] budg ON ben.BenefitsID = budg.BenefitsID + WHERE UnitTypeID = @PercentOfSalaries + AND EntityGroupConfigID = @EntityGroupConfigID + AND (budg.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL) + ) rate + ON rate.EntityGroupConfigID = vol.EntityGroupConfigID + AND rate.EntityID = vol.EntityID + AND rate.DepartmentID = vol.DepartmentID + AND rate.AccountID = vol.AccountID + AND rate.FinancialReportingID = vol.FinancialReportingID + AND rate.BudgetPhaseID = vol.BudgetPhaseID + WHERE + vol.FlexMethodID = 2 -- FlexAccountBySalaries + OPTION (RECOMPILE) + + + -- SAMPLE TOTALS FOR ACCOUNTS THAT ARE FLEXED BY FTES + INSERT INTO #FactBenefits (BudgetConfigID, EntityID, DepartmentID, AccountID, UnitTypeID, FinancialReportingID, BudgetPhaseID, Value01, + Value02, Value03, Value04, Value05, Value06, Value07, Value08, Value09, Value10, Value11, Value12) + SELECT + vol.BudgetConfigID, + vol.EntityID, + vol.DepartmentID, + vol.AccountID, + @Dollars as UnitTypeID, + vol.FinancialReportingID, + vol.BudgetPhaseID, + vol.AdjustedValue01 * rate.AdjustedValue01 AS Value01, + vol.AdjustedValue02 * rate.AdjustedValue02 AS Value02, + vol.AdjustedValue03 * rate.AdjustedValue03 AS Value03, + vol.AdjustedValue04 * rate.AdjustedValue04 AS Value04, + vol.AdjustedValue05 * rate.AdjustedValue05 AS Value05, + vol.AdjustedValue06 * rate.AdjustedValue06 AS Value06, + vol.AdjustedValue07 * rate.AdjustedValue07 AS Value07, + vol.AdjustedValue08 * rate.AdjustedValue08 AS Value08, + vol.AdjustedValue09 * rate.AdjustedValue09 AS Value09, + vol.AdjustedValue10 * rate.AdjustedValue10 AS Value10, + vol.AdjustedValue11 * rate.AdjustedValue11 AS Value11, + vol.AdjustedValue12 * rate.AdjustedValue12 AS Value12 + FROM + ( + SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID, + budg.BudgetPhaseID, budg.AdjustedValue01, budg.AdjustedValue02, budg.AdjustedValue03, budg.AdjustedValue04, budg.AdjustedValue05, budg.AdjustedValue06, budg.AdjustedValue07, + budg.AdjustedValue08, budg.AdjustedValue09, budg.AdjustedValue10, budg.AdjustedValue11, budg.AdjustedValue12 + FROM [fp].[FactBenefits] ben + INNER hash JOIN [fp].[FactBenefitsBudget] budg ON ben.BenefitsID = budg.BenefitsID + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID + WHERE UnitTypeID = @Ftes + AND EntityGroupConfigID = @EntityGroupConfigID + AND (budg.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL) + ) vol -- vol will give us the amount of either salaries or FTEs, the rate table will give us the % of salaries or $ per FTEs value + + INNER JOIN + ( + SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID, + budg.BudgetPhaseID, budg.AdjustedValue01, budg.AdjustedValue02, budg.AdjustedValue03, budg.AdjustedValue04, budg.AdjustedValue05, budg.AdjustedValue06, budg.AdjustedValue07, + budg.AdjustedValue08, budg.AdjustedValue09, budg.AdjustedValue10, budg.AdjustedValue11, budg.AdjustedValue12 + FROM [fp].[FactBenefits] ben + INNER hash JOIN [fp].[FactBenefitsBudget] budg ON ben.BenefitsID = budg.BenefitsID + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID + WHERE UnitTypeID = @DollarsPerFte + AND EntityGroupConfigID = @EntityGroupConfigID + AND (budg.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL) + ) rate + ON rate.EntityGroupConfigID = vol.EntityGroupConfigID + AND rate.EntityID = vol.EntityID + AND rate.DepartmentID = vol.DepartmentID + AND rate.AccountID = vol.AccountID + AND rate.FinancialReportingID = vol.FinancialReportingID + AND rate.BudgetPhaseID = vol.BudgetPhaseID + WHERE + vol.FlexMethodID = 1 -- FlexAccountByFTEs + OPTION (RECOMPILE) + + UPDATE + budg + SET + budg.AdjustedValue01 = Value01, + budg.AdjustedValue02 = Value02, + budg.AdjustedValue03 = Value03, + budg.AdjustedValue04 = Value04, + budg.AdjustedValue05 = Value05, + budg.AdjustedValue06 = Value06, + budg.AdjustedValue07 = Value07, + budg.AdjustedValue08 = Value08, + budg.AdjustedValue09 = Value09, + budg.AdjustedValue10 = Value10, + budg.AdjustedValue11 = Value11, + budg.AdjustedValue12 = Value12, + budg.FlexedValue01 = Value01, + budg.FlexedValue02 = Value02, + budg.FlexedValue03 = Value03, + budg.FlexedValue04 = Value04, + budg.FlexedValue05 = Value05, + budg.FlexedValue06 = Value06, + budg.FlexedValue07 = Value07, + budg.FlexedValue08 = Value08, + budg.FlexedValue09 = Value09, + budg.FlexedValue10 = Value10, + budg.FlexedValue11 = Value11, + budg.FlexedValue12 = Value12 + OUTPUT + INSERTED.BenefitsID + INTO + #budget_basisIDs (BenefitsID) + FROM + [fp].[FactBenefits] ben + INNER JOIN [fp].[FactBenefitsBudget] budg ON + ben.BenefitsID = budg.BenefitsID + INNER JOIN #FactBenefits tmp ON + ben.budgetConfigID = tmp.budgetConfigID + AND ben.EntityID = tmp.EntityID + AND ben.DepartmentID = tmp.DepartmentID + AND ben.AccountID = tmp.AccountID + AND ben.UnitTypeID = tmp.UnitTypeID + AND ben.FinancialReportingID = tmp.FinancialReportingID + AND budg.BudgetPhaseID = tmp.BudgetPhaseID + WHERE ben.EntityGroupConfigID = @EntityGroupConfigID + AND ( + budg.AdjustedValue01 <> Value01 OR + budg.AdjustedValue02 <> Value02 OR + budg.AdjustedValue03 <> Value03 OR + budg.AdjustedValue04 <> Value04 OR + budg.AdjustedValue05 <> Value05 OR + budg.AdjustedValue06 <> Value06 OR + budg.AdjustedValue07 <> Value07 OR + budg.AdjustedValue08 <> Value08 OR + budg.AdjustedValue09 <> Value09 OR + budg.AdjustedValue10 <> Value10 OR + budg.AdjustedValue11 <> Value11 OR + budg.AdjustedValue12 <> Value12 OR + budg.FlexedValue01 <> Value01 OR + budg.FlexedValue02 <> Value02 OR + budg.FlexedValue03 <> Value03 OR + budg.FlexedValue04 <> Value04 OR + budg.FlexedValue05 <> Value05 OR + budg.FlexedValue06 <> Value06 OR + budg.FlexedValue07 <> Value07 OR + budg.FlexedValue08 <> Value08 OR + budg.FlexedValue09 <> Value09 OR + budg.FlexedValue10 <> Value10 OR + budg.FlexedValue11 <> Value11 OR + budg.FlexedValue12 <> Value12 + ) + + + END ELSE BEGIN + + ------------------------------------------------------------ + -- Projection + ------------------------------------------------------------ + + -- SAMPLE TOTALS FOR ACCOUNTS THAT ARE FLEXED BY SALARIES + INSERT INTO #FactBenefits (BudgetConfigID, EntityID, DepartmentID, AccountID, UnitTypeID, FinancialReportingID, BudgetPhaseID, Value01, + Value02, Value03, Value04, Value05, Value06, Value07, Value08, Value09, Value10, Value11, Value12) + SELECT + vol.BudgetConfigID, + vol.EntityID, + vol.DepartmentID, + vol.AccountID, + @Dollars as UnitTypeID, + vol.FinancialReportingID, + vol.BudgetPhaseID, + vol.AdjustedValue01 * rate.AdjustedValue01 AS Value01, + vol.AdjustedValue02 * rate.AdjustedValue02 AS Value02, + vol.AdjustedValue03 * rate.AdjustedValue03 AS Value03, + vol.AdjustedValue04 * rate.AdjustedValue04 AS Value04, + vol.AdjustedValue05 * rate.AdjustedValue05 AS Value05, + vol.AdjustedValue06 * rate.AdjustedValue06 AS Value06, + vol.AdjustedValue07 * rate.AdjustedValue07 AS Value07, + vol.AdjustedValue08 * rate.AdjustedValue08 AS Value08, + vol.AdjustedValue09 * rate.AdjustedValue09 AS Value09, + vol.AdjustedValue10 * rate.AdjustedValue10 AS Value10, + vol.AdjustedValue11 * rate.AdjustedValue11 AS Value11, + vol.AdjustedValue12 * rate.AdjustedValue12 AS Value12 + FROM + ( + SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID, + proj.BudgetPhaseID, proj.AdjustedValue01, proj.AdjustedValue02, proj.AdjustedValue03, proj.AdjustedValue04, proj.AdjustedValue05, proj.AdjustedValue06, proj.AdjustedValue07, + proj.AdjustedValue08, proj.AdjustedValue09, proj.AdjustedValue10, proj.AdjustedValue11, proj.AdjustedValue12 + FROM [fp].[FactBenefits] ben + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID + INNER hash JOIN [fp].[FactBenefitsProjection] proj ON ben.BenefitsID = proj.BenefitsID + WHERE UnitTypeID = @Salaries + AND EntityGroupConfigID = @EntityGroupConfigID + AND (proj.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL) + ) vol -- vol will give us the amount of either salaries or FTEs, the rate table will give us the % of salaries or $ per FTEs value + + INNER JOIN + ( + SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID, + proj.BudgetPhaseID, proj.AdjustedValue01, proj.AdjustedValue02, proj.AdjustedValue03, proj.AdjustedValue04, proj.AdjustedValue05, proj.AdjustedValue06, proj.AdjustedValue07, + proj.AdjustedValue08, proj.AdjustedValue09, proj.AdjustedValue10, proj.AdjustedValue11, proj.AdjustedValue12 + FROM [fp].[FactBenefits] ben + INNER hash JOIN [fp].[FactBenefitsProjection] proj ON ben.BenefitsID = proj.BenefitsID + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID + WHERE UnitTypeID = @PercentOfSalaries + AND EntityGroupConfigID = @EntityGroupConfigID + AND (proj.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL) + ) rate + ON rate.EntityGroupConfigID = vol.EntityGroupConfigID + AND rate.EntityID = vol.EntityID + AND rate.DepartmentID = vol.DepartmentID + AND rate.AccountID = vol.AccountID + AND rate.FinancialReportingID = vol.FinancialReportingID + AND rate.BudgetPhaseID = vol.BudgetPhaseID + WHERE + vol.FlexMethodID = 2 -- FlexAccountBySalaries + OPTION (RECOMPILE) + + -- SAMPLE TOTALS FOR ACCOUNTS THAT ARE FLEXED BY FTES + INSERT INTO #FactBenefits (BudgetConfigID, EntityID, DepartmentID, AccountID, UnitTypeID, FinancialReportingID, BudgetPhaseID, Value01, + Value02, Value03, Value04, Value05, Value06, Value07, Value08, Value09, Value10, Value11, Value12) + SELECT + vol.BudgetConfigID, + vol.EntityID, + vol.DepartmentID, + vol.AccountID, + @Dollars as UnitTypeID, + vol.FinancialReportingID, + vol.BudgetPhaseID, + vol.AdjustedValue01 * rate.AdjustedValue01 AS Value01, + vol.AdjustedValue02 * rate.AdjustedValue02 AS Value02, + vol.AdjustedValue03 * rate.AdjustedValue03 AS Value03, + vol.AdjustedValue04 * rate.AdjustedValue04 AS Value04, + vol.AdjustedValue05 * rate.AdjustedValue05 AS Value05, + vol.AdjustedValue06 * rate.AdjustedValue06 AS Value06, + vol.AdjustedValue07 * rate.AdjustedValue07 AS Value07, + vol.AdjustedValue08 * rate.AdjustedValue08 AS Value08, + vol.AdjustedValue09 * rate.AdjustedValue09 AS Value09, + vol.AdjustedValue10 * rate.AdjustedValue10 AS Value10, + vol.AdjustedValue11 * rate.AdjustedValue11 AS Value11, + vol.AdjustedValue12 * rate.AdjustedValue12 AS Value12 + FROM + ( + SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID, + proj.BudgetPhaseID, proj.AdjustedValue01, proj.AdjustedValue02, proj.AdjustedValue03, proj.AdjustedValue04, proj.AdjustedValue05, proj.AdjustedValue06, proj.AdjustedValue07, + proj.AdjustedValue08, proj.AdjustedValue09, proj.AdjustedValue10, proj.AdjustedValue11, proj.AdjustedValue12 + FROM [fp].[FactBenefits] ben + INNER hash JOIN [fp].[FactBenefitsProjection] proj ON ben.BenefitsID = proj.BenefitsID + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID + WHERE UnitTypeID = @Ftes + AND EntityGroupConfigID = @EntityGroupConfigID + AND (proj.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL) + ) vol -- vol will give us the amount of either salaries or FTEs, the rate table will give us the % of salaries or $ per FTEs value + + INNER JOIN + ( + SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID, + proj.BudgetPhaseID, proj.AdjustedValue01, proj.AdjustedValue02, proj.AdjustedValue03, proj.AdjustedValue04, proj.AdjustedValue05, proj.AdjustedValue06, proj.AdjustedValue07, + proj.AdjustedValue08, proj.AdjustedValue09, proj.AdjustedValue10, proj.AdjustedValue11, proj.AdjustedValue12 + FROM [fp].[FactBenefits] ben + INNER hash JOIN [fp].[FactBenefitsProjection] proj ON ben.BenefitsID = proj.BenefitsID + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID + WHERE UnitTypeID = @DollarsPerFte + AND EntityGroupConfigID = @EntityGroupConfigID + AND (proj.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL) + ) rate + ON rate.EntityGroupConfigID = vol.EntityGroupConfigID + AND rate.EntityID = vol.EntityID + AND rate.DepartmentID = vol.DepartmentID + AND rate.AccountID = vol.AccountID + AND rate.FinancialReportingID = vol.FinancialReportingID + AND rate.BudgetPhaseID = vol.BudgetPhaseID + WHERE + vol.FlexMethodID = 1 -- FlexAccountByFTEs + OPTION (RECOMPILE) + + UPDATE proj + SET + proj.AdjustedValue01 = CASE WHEN 1 <= @MonthsLoaded THEN InitialProjection01 ELSE Value01 END, + proj.AdjustedValue02 = CASE WHEN 2 <= @MonthsLoaded THEN InitialProjection02 ELSE Value02 END, + proj.AdjustedValue03 = CASE WHEN 3 <= @MonthsLoaded THEN InitialProjection03 ELSE Value03 END, + proj.AdjustedValue04 = CASE WHEN 4 <= @MonthsLoaded THEN InitialProjection04 ELSE Value04 END, + proj.AdjustedValue05 = CASE WHEN 5 <= @MonthsLoaded THEN InitialProjection05 ELSE Value05 END, + proj.AdjustedValue06 = CASE WHEN 6 <= @MonthsLoaded THEN InitialProjection06 ELSE Value06 END, + proj.AdjustedValue07 = CASE WHEN 7 <= @MonthsLoaded THEN InitialProjection07 ELSE Value07 END, + proj.AdjustedValue08 = CASE WHEN 8 <= @MonthsLoaded THEN InitialProjection08 ELSE Value08 END, + proj.AdjustedValue09 = CASE WHEN 9 <= @MonthsLoaded THEN InitialProjection09 ELSE Value09 END, + proj.AdjustedValue10 = CASE WHEN 10 <= @MonthsLoaded THEN InitialProjection10 ELSE Value10 END, + proj.AdjustedValue11 = CASE WHEN 11 <= @MonthsLoaded THEN InitialProjection11 ELSE Value11 END, + proj.AdjustedValue12 = CASE WHEN 12 <= @MonthsLoaded THEN InitialProjection12 ELSE Value12 END, + proj.FlexedValue01 = CASE WHEN 1 <= @MonthsLoaded THEN InitialProjection01 ELSE Value01 END, + proj.FlexedValue02 = CASE WHEN 2 <= @MonthsLoaded THEN InitialProjection02 ELSE Value02 END, + proj.FlexedValue03 = CASE WHEN 3 <= @MonthsLoaded THEN InitialProjection03 ELSE Value03 END, + proj.FlexedValue04 = CASE WHEN 4 <= @MonthsLoaded THEN InitialProjection04 ELSE Value04 END, + proj.FlexedValue05 = CASE WHEN 5 <= @MonthsLoaded THEN InitialProjection05 ELSE Value05 END, + proj.FlexedValue06 = CASE WHEN 6 <= @MonthsLoaded THEN InitialProjection06 ELSE Value06 END, + proj.FlexedValue07 = CASE WHEN 7 <= @MonthsLoaded THEN InitialProjection07 ELSE Value07 END, + proj.FlexedValue08 = CASE WHEN 8 <= @MonthsLoaded THEN InitialProjection08 ELSE Value08 END, + proj.FlexedValue09 = CASE WHEN 9 <= @MonthsLoaded THEN InitialProjection09 ELSE Value09 END, + proj.FlexedValue10 = CASE WHEN 10 <= @MonthsLoaded THEN InitialProjection10 ELSE Value10 END, + proj.FlexedValue11 = CASE WHEN 11 <= @MonthsLoaded THEN InitialProjection11 ELSE Value11 END, + proj.FlexedValue12 = CASE WHEN 12 <= @MonthsLoaded THEN InitialProjection12 ELSE Value12 END + OUTPUT + INSERTED.BenefitsID + INTO + #projection_basisIDs (BenefitsID) + FROM [fp].[FactBenefits] ben + INNER JOIN [fp].[FactBenefitsProjection] proj ON ben.BenefitsID = proj.BenefitsID + INNER JOIN #FactBenefits tmp ON + ben.BudgetConfigID = tmp.BudgetConfigID + AND ben.EntityID = tmp.EntityID + AND ben.DepartmentID = tmp.DepartmentID + AND ben.AccountID = tmp.AccountID + AND ben.UnitTypeID = tmp.UnitTypeID + AND ben.FinancialReportingID = tmp.FinancialReportingID + AND proj.BudgetPhaseID = tmp.BudgetPhaseID + WHERE ben.EntityGroupConfigID = @EntityGroupConfigID + AND ( + (proj.AdjustedValue01 <> CASE WHEN 1 <= @MonthsLoaded THEN InitialProjection01 ELSE Value01 END) OR + (proj.AdjustedValue02 <> CASE WHEN 2 <= @MonthsLoaded THEN InitialProjection02 ELSE Value02 END) OR + (proj.AdjustedValue03 <> CASE WHEN 3 <= @MonthsLoaded THEN InitialProjection03 ELSE Value03 END) OR + (proj.AdjustedValue04 <> CASE WHEN 4 <= @MonthsLoaded THEN InitialProjection04 ELSE Value04 END) OR + (proj.AdjustedValue05 <> CASE WHEN 5 <= @MonthsLoaded THEN InitialProjection05 ELSE Value05 END) OR + (proj.AdjustedValue06 <> CASE WHEN 6 <= @MonthsLoaded THEN InitialProjection06 ELSE Value06 END) OR + (proj.AdjustedValue07 <> CASE WHEN 7 <= @MonthsLoaded THEN InitialProjection07 ELSE Value07 END) OR + (proj.AdjustedValue08 <> CASE WHEN 8 <= @MonthsLoaded THEN InitialProjection08 ELSE Value08 END) OR + (proj.AdjustedValue09 <> CASE WHEN 9 <= @MonthsLoaded THEN InitialProjection09 ELSE Value09 END) OR + (proj.AdjustedValue10 <> CASE WHEN 10 <= @MonthsLoaded THEN InitialProjection10 ELSE Value10 END) OR + (proj.AdjustedValue11 <> CASE WHEN 11 <= @MonthsLoaded THEN InitialProjection11 ELSE Value11 END) OR + (proj.AdjustedValue12 <> CASE WHEN 12 <= @MonthsLoaded THEN InitialProjection12 ELSE Value12 END) OR + (proj.FlexedValue01 <> CASE WHEN 1 <= @MonthsLoaded THEN InitialProjection01 ELSE Value01 END) OR + (proj.FlexedValue02 <> CASE WHEN 2 <= @MonthsLoaded THEN InitialProjection02 ELSE Value02 END) OR + (proj.FlexedValue03 <> CASE WHEN 3 <= @MonthsLoaded THEN InitialProjection03 ELSE Value03 END) OR + (proj.FlexedValue04 <> CASE WHEN 4 <= @MonthsLoaded THEN InitialProjection04 ELSE Value04 END) OR + (proj.FlexedValue05 <> CASE WHEN 5 <= @MonthsLoaded THEN InitialProjection05 ELSE Value05 END) OR + (proj.FlexedValue06 <> CASE WHEN 6 <= @MonthsLoaded THEN InitialProjection06 ELSE Value06 END) OR + (proj.FlexedValue07 <> CASE WHEN 7 <= @MonthsLoaded THEN InitialProjection07 ELSE Value07 END) OR + (proj.FlexedValue08 <> CASE WHEN 8 <= @MonthsLoaded THEN InitialProjection08 ELSE Value08 END) OR + (proj.FlexedValue09 <> CASE WHEN 9 <= @MonthsLoaded THEN InitialProjection09 ELSE Value09 END) OR + (proj.FlexedValue10 <> CASE WHEN 10 <= @MonthsLoaded THEN InitialProjection10 ELSE Value10 END) OR + (proj.FlexedValue11 <> CASE WHEN 11 <= @MonthsLoaded THEN InitialProjection11 ELSE Value11 END) OR + (proj.FlexedValue12 <> CASE WHEN 12 <= @MonthsLoaded THEN InitialProjection12 ELSE Value12 END) + ) + + END + + -- returns the info on the rows that were flexed in order to fix the change history + SELECT DISTINCT BenefitsID + ,m.FiscalMonthID + ,BudgetPhaseID + ,TimeClassID + ,f.Value + FROM ( + SELECT bdgt.BenefitsID + ,bdgt.AdjustedValue01 + ,bdgt.AdjustedValue02 + ,bdgt.AdjustedValue03 + ,bdgt.AdjustedValue04 + ,bdgt.AdjustedValue05 + ,bdgt.AdjustedValue06 + ,bdgt.AdjustedValue07 + ,bdgt.AdjustedValue08 + ,bdgt.AdjustedValue09 + ,bdgt.AdjustedValue10 + ,bdgt.AdjustedValue11 + ,bdgt.AdjustedValue12 + ,bdgt.BudgetPhaseID + ,cast(2 AS TINYINT) AS TimeClassID + FROM #budget_basisIDs ids + INNER JOIN [fp].[FactBenefitsBudget] bdgt + ON ids.BenefitsID = bdgt.BenefitsID + WHERE bdgt.BudgetPhaseID = 2 + UNION ALL + SELECT + bdgt.BenefitsID + ,bdgt.AdjustedValue01 + ,bdgt.AdjustedValue02 + ,bdgt.AdjustedValue03 + ,bdgt.AdjustedValue04 + ,bdgt.AdjustedValue05 + ,bdgt.AdjustedValue06 + ,bdgt.AdjustedValue07 + ,bdgt.AdjustedValue08 + ,bdgt.AdjustedValue09 + ,bdgt.AdjustedValue10 + ,bdgt.AdjustedValue11 + ,bdgt.AdjustedValue12 + ,bdgt.BudgetPhaseID + ,cast(12 AS TINYINT) AS TimeClassID + FROM #projection_basisIDs ids + INNER JOIN [fp].[FactBenefitsProjection] bdgt + ON ids.BenefitsID = bdgt.BenefitsID + WHERE bdgt.BudgetPhaseID = 2 + ) gl + UNPIVOT(Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) AS f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month') + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#FactBenefits') IS NOT NULL DROP TABLE #FactBenefits + +END; +GO + + +--------------------------------------------- + +-- fp.procRecalcBenefitsTotals_InitialValue +CREATE PROCEDURE [fp].[procRecalcBenefitsTotals_InitialValue] + @EntityGroupConfigID INT, + @EntityGroupConfigGUID UNIQUEIDENTIFIER, + @TimeClassID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + AS + BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table + ** 2 2022-02-23 NT JAZZ-33434 Clean up by removing IS NULL JOIN and SELECT * + *************************************************************/ + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#FactBenefits') IS NOT NULL DROP TABLE #FactBenefits + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the FilterByDepartment does not contain valid data then pass all departments to avoid duplicate statements + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[FactBenefits] fb + WHERE fb.EntityGroupConfigID = @EntityGroupConfigID + END + + DECLARE @Dollars INT = 34, + @Ftes INT = 144, + @DollarsPerFte INT = 171, + @Salaries INT = 169, + @PercentOfSalaries INT = 170 + + DECLARE @MonthsLoaded INT + SELECT @MonthsLoaded = bc.MonthsLoaded from [fp].[BudgetConfig] bc inner join [fp].[EntityGroupConfig] egc on egc.BudgetConfigGUID = bc.BudgetConfigGUID where egc.EntityGroupConfigID = @EntityGroupConfigID + + CREATE TABLE #FactBenefits (BudgetConfigID INT, EntityID INT, DepartmentID INT, AccountID INT, UnitTypeID INT, FinancialReportingID INT, + OriginalValue01 DECIMAL(19,8), OriginalValue02 DECIMAL(19,8), OriginalValue03 DECIMAL(19,8), OriginalValue04 DECIMAL(19,8), OriginalValue05 DECIMAL(19,8), + OriginalValue06 DECIMAL(19,8), OriginalValue07 DECIMAL(19,8), OriginalValue08 DECIMAL(19,8), OriginalValue09 DECIMAL(19,8), OriginalValue10 DECIMAL(19,8), + OriginalValue11 DECIMAL(19,8), OriginalValue12 DECIMAL(19,8)) + + IF (@TimeClassID = 2) + BEGIN + + -- SAMPLE TOTALS FOR ACCOUNTS THAT ARE FLEXED BY SALARIES + INSERT INTO #FactBenefits (BudgetConfigID, EntityID, DepartmentID, AccountID, UnitTypeID, FinancialReportingID, OriginalValue01, OriginalValue02, OriginalValue03, OriginalValue04, + OriginalValue05, OriginalValue06, OriginalValue07, OriginalValue08, OriginalValue09, OriginalValue10, OriginalValue11, OriginalValue12) + SELECT + vol.BudgetConfigID, + vol.EntityID, + vol.DepartmentID, + vol.AccountID, + @Dollars as UnitTypeID, + vol.FinancialReportingID, + vol.InitialBudget01 * rate.InitialBudget01 AS OriginalValue01, + vol.InitialBudget02 * rate.InitialBudget02 AS OriginalValue02, + vol.InitialBudget03 * rate.InitialBudget03 AS OriginalValue03, + vol.InitialBudget04 * rate.InitialBudget04 AS OriginalValue04, + vol.InitialBudget05 * rate.InitialBudget05 AS OriginalValue05, + vol.InitialBudget06 * rate.InitialBudget06 AS OriginalValue06, + vol.InitialBudget07 * rate.InitialBudget07 AS OriginalValue07, + vol.InitialBudget08 * rate.InitialBudget08 AS OriginalValue08, + vol.InitialBudget09 * rate.InitialBudget09 AS OriginalValue09, + vol.InitialBudget10 * rate.InitialBudget10 AS OriginalValue10, + vol.InitialBudget11 * rate.InitialBudget11 AS OriginalValue11, + vol.InitialBudget12 * rate.InitialBudget12 AS OriginalValue12 + FROM + ( + SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID, + ben.InitialBudget01, ben.InitialBudget02, ben.InitialBudget03, ben.InitialBudget04, ben.InitialBudget05, ben.InitialBudget06, + ben.InitialBudget07, ben.InitialBudget08, ben.InitialBudget09, ben.InitialBudget10, ben.InitialBudget11, ben.InitialBudget12 + FROM [fp].[FactBenefits] ben + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID + WHERE UnitTypeID = @Salaries + AND EntityGroupConfigID = @EntityGroupConfigID + ) vol -- vol will give us the amount of either salaries or FTEs, the rate table will give us the % of salaries or $ per FTEs value + + + INNER JOIN + ( + SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID, + ben.InitialBudget01, ben.InitialBudget02, ben.InitialBudget03, ben.InitialBudget04, ben.InitialBudget05, ben.InitialBudget06, + ben.InitialBudget07, ben.InitialBudget08, ben.InitialBudget09, ben.InitialBudget10, ben.InitialBudget11, ben.InitialBudget12 + FROM [fp].[FactBenefits] ben + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID + WHERE UnitTypeID = @PercentOfSalaries + AND EntityGroupConfigID = @EntityGroupConfigID + ) rate + ON rate.EntityGroupConfigID = vol.EntityGroupConfigID + AND rate.EntityID = vol.EntityID + AND rate.DepartmentID = vol.DepartmentID + AND rate.AccountID = vol.AccountID + AND rate.FinancialReportingID = vol.FinancialReportingID + WHERE + vol.FlexMethodID = 2 -- FlexAccountBySalaries + + + -- SAMPLE TOTALS FOR ACCOUNTS THAT ARE FLEXED BY FTES + INSERT INTO #FactBenefits (BudgetConfigID, EntityID, DepartmentID, AccountID, UnitTypeID, FinancialReportingID, OriginalValue01, OriginalValue02, OriginalValue03, OriginalValue04, + OriginalValue05, OriginalValue06, OriginalValue07, OriginalValue08, OriginalValue09, OriginalValue10, OriginalValue11, OriginalValue12) + SELECT + vol.BudgetConfigID, + vol.EntityID, + vol.DepartmentID, + vol.AccountID, + @Dollars as UnitTypeID, + vol.FinancialReportingID, + vol.InitialBudget01 * rate.InitialBudget01 AS OriginalValue01, + vol.InitialBudget02 * rate.InitialBudget02 AS OriginalValue02, + vol.InitialBudget03 * rate.InitialBudget03 AS OriginalValue03, + vol.InitialBudget04 * rate.InitialBudget04 AS OriginalValue04, + vol.InitialBudget05 * rate.InitialBudget05 AS OriginalValue05, + vol.InitialBudget06 * rate.InitialBudget06 AS OriginalValue06, + vol.InitialBudget07 * rate.InitialBudget07 AS OriginalValue07, + vol.InitialBudget08 * rate.InitialBudget08 AS OriginalValue08, + vol.InitialBudget09 * rate.InitialBudget09 AS OriginalValue09, + vol.InitialBudget10 * rate.InitialBudget10 AS OriginalValue10, + vol.InitialBudget11 * rate.InitialBudget11 AS OriginalValue11, + vol.InitialBudget12 * rate.InitialBudget12 AS OriginalValue12 + FROM + ( + SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID, + ben.InitialBudget01, ben.InitialBudget02, ben.InitialBudget03, ben.InitialBudget04, ben.InitialBudget05, ben.InitialBudget06, + ben.InitialBudget07, ben.InitialBudget08, ben.InitialBudget09, ben.InitialBudget10, ben.InitialBudget11, ben.InitialBudget12 + FROM [fp].[FactBenefits] ben + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID + WHERE UnitTypeID = @Ftes + AND EntityGroupConfigID = @EntityGroupConfigID + ) vol -- vol will give us the amount of either salaries or FTEs, the rate table will give us the % of salaries or $ per FTEs value + + INNER JOIN + ( + SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID, + ben.InitialBudget01, ben.InitialBudget02, ben.InitialBudget03, ben.InitialBudget04, ben.InitialBudget05, ben.InitialBudget06, + ben.InitialBudget07, ben.InitialBudget08, ben.InitialBudget09, ben.InitialBudget10, ben.InitialBudget11, ben.InitialBudget12 + FROM [fp].[FactBenefits] ben + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID + WHERE UnitTypeID = @DollarsPerFte + AND EntityGroupConfigID = @EntityGroupConfigID + ) rate + ON rate.EntityGroupConfigID = vol.EntityGroupConfigID + AND rate.EntityID = vol.EntityID + AND rate.DepartmentID = vol.DepartmentID + AND rate.AccountID = vol.AccountID + AND rate.FinancialReportingID = vol.FinancialReportingID + WHERE + vol.FlexMethodID = 1 -- FlexAccountByFTEs + + UPDATE ben + SET + ben.InitialBudget01 = OriginalValue01, + ben.InitialBudget02 = OriginalValue02, + ben.InitialBudget03 = OriginalValue03, + ben.InitialBudget04 = OriginalValue04, + ben.InitialBudget05 = OriginalValue05, + ben.InitialBudget06 = OriginalValue06, + ben.InitialBudget07 = OriginalValue07, + ben.InitialBudget08 = OriginalValue08, + ben.InitialBudget09 = OriginalValue09, + ben.InitialBudget10 = OriginalValue10, + ben.InitialBudget11 = OriginalValue11, + ben.InitialBudget12 = OriginalValue12 + FROM [fp].[FactBenefits] ben + INNER JOIN #FactBenefits tmp ON + ben.BudgetConfigID = tmp.BudgetConfigID + AND ben.EntityID = tmp.EntityID + AND ben.DepartmentID = tmp.DepartmentID + AND ben.AccountID = tmp.AccountID + AND ben.UnitTypeID = tmp.UnitTypeID + AND ben.FinancialReportingID = tmp.FinancialReportingID + WHERE ben.EntityGroupConfigID = @EntityGroupConfigID + AND ( + ben.InitialBudget01 <> OriginalValue01 OR + ben.InitialBudget02 <> OriginalValue02 OR + ben.InitialBudget03 <> OriginalValue03 OR + ben.InitialBudget04 <> OriginalValue04 OR + ben.InitialBudget05 <> OriginalValue05 OR + ben.InitialBudget06 <> OriginalValue06 OR + ben.InitialBudget07 <> OriginalValue07 OR + ben.InitialBudget08 <> OriginalValue08 OR + ben.InitialBudget09 <> OriginalValue09 OR + ben.InitialBudget10 <> OriginalValue10 OR + ben.InitialBudget11 <> OriginalValue11 OR + ben.InitialBudget12 <> OriginalValue12 + ) + + END ELSE BEGIN + + ------------------------------------------------------------ + -- Projection + ------------------------------------------------------------ + + -- SAMPLE TOTALS FOR ACCOUNTS THAT ARE FLEXED BY SALARIES + INSERT INTO #FactBenefits (BudgetConfigID, EntityID, DepartmentID, AccountID, UnitTypeID, FinancialReportingID, OriginalValue01, OriginalValue02, OriginalValue03, OriginalValue04, + OriginalValue05, OriginalValue06, OriginalValue07, OriginalValue08, OriginalValue09, OriginalValue10, OriginalValue11, OriginalValue12) + SELECT + vol.BudgetConfigID, + vol.EntityID, + vol.DepartmentID, + vol.AccountID, + @Dollars as UnitTypeID, + vol.FinancialReportingID, + vol.InitialProjection01 * rate.InitialProjection01 AS OriginalValue01, + vol.InitialProjection02 * rate.InitialProjection02 AS OriginalValue02, + vol.InitialProjection03 * rate.InitialProjection03 AS OriginalValue03, + vol.InitialProjection04 * rate.InitialProjection04 AS OriginalValue04, + vol.InitialProjection05 * rate.InitialProjection05 AS OriginalValue05, + vol.InitialProjection06 * rate.InitialProjection06 AS OriginalValue06, + vol.InitialProjection07 * rate.InitialProjection07 AS OriginalValue07, + vol.InitialProjection08 * rate.InitialProjection08 AS OriginalValue08, + vol.InitialProjection09 * rate.InitialProjection09 AS OriginalValue09, + vol.InitialProjection10 * rate.InitialProjection10 AS OriginalValue10, + vol.InitialProjection11 * rate.InitialProjection11 AS OriginalValue11, + vol.InitialProjection12 * rate.InitialProjection12 AS OriginalValue12 + FROM + ( + SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID, + ben.InitialProjection01, ben.InitialProjection02, ben.InitialProjection03, ben.InitialProjection04, ben.InitialProjection05, ben.InitialProjection06, + ben.InitialProjection07, ben.InitialProjection08, ben.InitialProjection09, ben.InitialProjection10, ben.InitialProjection11, ben.InitialProjection12 + FROM [fp].[FactBenefits] ben + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID + WHERE UnitTypeID = @Salaries + AND EntityGroupConfigID = @EntityGroupConfigID + ) vol -- vol will give us the amount of either salaries or FTEs, the rate table will give us the % of salaries or $ per FTEs value + + INNER JOIN + ( + SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID, + ben.InitialProjection01, ben.InitialProjection02, ben.InitialProjection03, ben.InitialProjection04, ben.InitialProjection05, ben.InitialProjection06, + ben.InitialProjection07, ben.InitialProjection08, ben.InitialProjection09, ben.InitialProjection10, ben.InitialProjection11, ben.InitialProjection12 + FROM [fp].[FactBenefits] ben + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID + WHERE UnitTypeID = @PercentOfSalaries + AND EntityGroupConfigID = @EntityGroupConfigID + ) rate + ON rate.EntityGroupConfigID = vol.EntityGroupConfigID + AND rate.EntityID = vol.EntityID + AND rate.DepartmentID = vol.DepartmentID + AND rate.AccountID = vol.AccountID + AND rate.FinancialReportingID = vol.FinancialReportingID + WHERE + vol.FlexMethodID = 2 -- FlexAccountBySalaries + + + -- SAMPLE TOTALS FOR ACCOUNTS THAT ARE FLEXED BY FTES + INSERT INTO #FactBenefits (BudgetConfigID, EntityID, DepartmentID, AccountID, UnitTypeID, FinancialReportingID, OriginalValue01, OriginalValue02, OriginalValue03, OriginalValue04, + OriginalValue05, OriginalValue06, OriginalValue07, OriginalValue08, OriginalValue09, OriginalValue10, OriginalValue11, OriginalValue12) + SELECT + vol.BudgetConfigID, + vol.EntityID, + vol.DepartmentID, + vol.AccountID, + @Dollars as UnitTypeID, + vol.FinancialReportingID, + vol.InitialProjection01 * rate.InitialProjection01 AS OriginalValue01, + vol.InitialProjection02 * rate.InitialProjection02 AS OriginalValue02, + vol.InitialProjection03 * rate.InitialProjection03 AS OriginalValue03, + vol.InitialProjection04 * rate.InitialProjection04 AS OriginalValue04, + vol.InitialProjection05 * rate.InitialProjection05 AS OriginalValue05, + vol.InitialProjection06 * rate.InitialProjection06 AS OriginalValue06, + vol.InitialProjection07 * rate.InitialProjection07 AS OriginalValue07, + vol.InitialProjection08 * rate.InitialProjection08 AS OriginalValue08, + vol.InitialProjection09 * rate.InitialProjection09 AS OriginalValue09, + vol.InitialProjection10 * rate.InitialProjection10 AS OriginalValue10, + vol.InitialProjection11 * rate.InitialProjection11 AS OriginalValue11, + vol.InitialProjection12 * rate.InitialProjection12 AS OriginalValue12 + FROM + ( + SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID, + ben.InitialProjection01, ben.InitialProjection02, ben.InitialProjection03, ben.InitialProjection04, ben.InitialProjection05, ben.InitialProjection06, + ben.InitialProjection07, ben.InitialProjection08, ben.InitialProjection09, ben.InitialProjection10, ben.InitialProjection11, ben.InitialProjection12 + FROM [fp].[FactBenefits] ben + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID + WHERE UnitTypeID = @Ftes + AND EntityGroupConfigID = @EntityGroupConfigID + ) vol -- vol will give us the amount of either salaries or FTEs, the rate table will give us the % of salaries or $ per FTEs value + + INNER JOIN + ( + SELECT ben.BudgetConfigID, ben.EntityGroupConfigID, ben.FlexMethodID, ben.EntityID, ben.DepartmentID, ben.AccountID, ben.UnitTypeID, ben.FinancialReportingID, + ben.InitialProjection01, ben.InitialProjection02, ben.InitialProjection03, ben.InitialProjection04, ben.InitialProjection05, ben.InitialProjection06, + ben.InitialProjection07, ben.InitialProjection08, ben.InitialProjection09, ben.InitialProjection10, ben.InitialProjection11, ben.InitialProjection12 + FROM [fp].[FactBenefits] ben + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = ben.DepartmentID + WHERE UnitTypeID = @DollarsPerFte + AND EntityGroupConfigID = @EntityGroupConfigID + ) rate + ON rate.EntityGroupConfigID = vol.EntityGroupConfigID + AND rate.EntityID = vol.EntityID + AND rate.DepartmentID = vol.DepartmentID + AND rate.AccountID = vol.AccountID + AND rate.FinancialReportingID = vol.FinancialReportingID + WHERE + vol.FlexMethodID = 1 -- FlexAccountByFTEs + + UPDATE ben + SET + ben.InitialProjection01 = CASE WHEN 1 <= @MonthsLoaded THEN SampledProjection01 ELSE OriginalValue01 END, + ben.InitialProjection02 = CASE WHEN 2 <= @MonthsLoaded THEN SampledProjection02 ELSE OriginalValue02 END, + ben.InitialProjection03 = CASE WHEN 3 <= @MonthsLoaded THEN SampledProjection03 ELSE OriginalValue03 END, + ben.InitialProjection04 = CASE WHEN 4 <= @MonthsLoaded THEN SampledProjection04 ELSE OriginalValue04 END, + ben.InitialProjection05 = CASE WHEN 5 <= @MonthsLoaded THEN SampledProjection05 ELSE OriginalValue05 END, + ben.InitialProjection06 = CASE WHEN 6 <= @MonthsLoaded THEN SampledProjection06 ELSE OriginalValue06 END, + ben.InitialProjection07 = CASE WHEN 7 <= @MonthsLoaded THEN SampledProjection07 ELSE OriginalValue07 END, + ben.InitialProjection08 = CASE WHEN 8 <= @MonthsLoaded THEN SampledProjection08 ELSE OriginalValue08 END, + ben.InitialProjection09 = CASE WHEN 9 <= @MonthsLoaded THEN SampledProjection09 ELSE OriginalValue09 END, + ben.InitialProjection10 = CASE WHEN 10 <= @MonthsLoaded THEN SampledProjection10 ELSE OriginalValue10 END, + ben.InitialProjection11 = CASE WHEN 11 <= @MonthsLoaded THEN SampledProjection11 ELSE OriginalValue11 END, + ben.InitialProjection12 = CASE WHEN 12 <= @MonthsLoaded THEN SampledProjection12 ELSE OriginalValue12 END + FROM [fp].[FactBenefits] ben + INNER JOIN #FactBenefits tmp ON + ben.BudgetConfigID = tmp.BudgetConfigID + AND ben.EntityID = tmp.EntityID + AND ben.DepartmentID = tmp.DepartmentID + AND ben.AccountID = tmp.AccountID + AND ben.UnitTypeID = tmp.UnitTypeID + AND ben.FinancialReportingID = tmp.FinancialReportingID + WHERE ben.EntityGroupConfigID = @EntityGroupConfigID + AND ( + ben.InitialProjection01 <> CASE WHEN 1 <= @MonthsLoaded THEN SampledProjection01 ELSE OriginalValue01 END OR + ben.InitialProjection02 <> CASE WHEN 2 <= @MonthsLoaded THEN SampledProjection02 ELSE OriginalValue02 END OR + ben.InitialProjection03 <> CASE WHEN 3 <= @MonthsLoaded THEN SampledProjection03 ELSE OriginalValue03 END OR + ben.InitialProjection04 <> CASE WHEN 4 <= @MonthsLoaded THEN SampledProjection04 ELSE OriginalValue04 END OR + ben.InitialProjection05 <> CASE WHEN 5 <= @MonthsLoaded THEN SampledProjection05 ELSE OriginalValue05 END OR + ben.InitialProjection06 <> CASE WHEN 6 <= @MonthsLoaded THEN SampledProjection06 ELSE OriginalValue06 END OR + ben.InitialProjection07 <> CASE WHEN 7 <= @MonthsLoaded THEN SampledProjection07 ELSE OriginalValue07 END OR + ben.InitialProjection08 <> CASE WHEN 8 <= @MonthsLoaded THEN SampledProjection08 ELSE OriginalValue08 END OR + ben.InitialProjection09 <> CASE WHEN 9 <= @MonthsLoaded THEN SampledProjection09 ELSE OriginalValue09 END OR + ben.InitialProjection10 <> CASE WHEN 10 <= @MonthsLoaded THEN SampledProjection10 ELSE OriginalValue10 END OR + ben.InitialProjection11 <> CASE WHEN 11 <= @MonthsLoaded THEN SampledProjection11 ELSE OriginalValue11 END OR + ben.InitialProjection12 <> CASE WHEN 12 <= @MonthsLoaded THEN SampledProjection12 ELSE OriginalValue12 END + ) + + END + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#FactBenefits') IS NOT NULL DROP TABLE #FactBenefits + + END +GO + + +--------------------------------------------- + +-- fp.procReimbursementAdjustmentActivityList +CREATE PROCEDURE [fp].[procReimbursementAdjustmentActivityList] + @budgetGUID UNIQUEIDENTIFIER, + @start INT, + @end INT, + @search VARCHAR(MAX), + @filter VARCHAR(MAX), + @userGUID UNIQUEIDENTIFIER, + @isDataSecured BIT, + @dateTimeFormat VARCHAR(30), + @userTimeZone VARCHAR(50) +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-04-13 MD JAZZ-33206 Initial + ** 2 2022-06-21 MY JAZZ-36070 Unleash the Kraken (remove adjustment type limit) + ** 3 2023-09-21 MD JAZZ-59398 Only pull back budget adjustments + *************************************************************/ +BEGIN + + DECLARE @guidEmpty UNIQUEIDENTIFIER = '00000000-0000-0000-0000-000000000000' + DECLARE @pageSize INT = @end - @start; + + SET @search = LOWER(NULLIF('%' + @search+ '%', '%\%')) + SET @filter = LOWER(NULLIF(@filter, '')) + + ---------------------------------------------------------------------- + --Get all adjustments + ---------------------------------------------------------------------- + SELECT AdjustmentID + ,GroupingHierarchyJSON + INTO #adjustments + FROM fp.ReimbursementAdjustment AS slea WITH (NOLOCK) + WHERE slea.BudgetConfigGUID = @budgetGUID + AND slea.BudgetPhaseID <> 2 --JAZZ-59398 only want to bring back budget grid and import adjustments + + CREATE CLUSTERED INDEX PK_Adjustmnets ON #adjustments (AdjustmentID) + + ---------------------------------------------------------------------- + --Get import adjustments + ---------------------------------------------------------------------- + SELECT iadj.AdjustmentID, + iadj.UnitTypeID + INTO #importAdjustments + FROM fp.viewReimbursementAdjustmentImport AS iadj WITH (NOLOCK) + JOIN #adjustments AS sadj ON sadj.AdjustmentID = iadj.AdjustmentID + GROUP BY iadj.AdjustmentID, + iadj.UnitTypeID + + CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentID, UnitTypeID) + + ---------------------------------------------------------------------- + --Build dto + ---------------------------------------------------------------------- + SELECT res.TotalRowsCount + ,res.AdjustmentID + ,res.BudgetConfigGUID + ,res.AdjustmentType + ,res.[Value] + ,res.AdjustmentFilterJSON + ,res.GroupingHierarchyJSON + ,res.AdjustedProperty + ,res.Comment + ,res.AuthorGUID + ,res.AuthorFullName + ,res.LastModifiedDateUtc + ,res.DateCreatedUtc + ,res.GroupingGUID + ,res.TimeClassID + ,3 as BudgetPhaseID --hardcode budget phase to 3 since not on fp.ReimbursementAdjustment + ,res.ClassificationGroupID + ,res.ClassificationCategoryID + ,res.JobCode + ,res.JobCodeCount + ,res.DepartmentCode + ,res.DepartmentCount + ,res.UnitTypeID + ,res.ImportUnitTypeIDs + ,res.IsRecordDeleted + ,res.IsCarryForward + FROM ( + SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount, + * + FROM ( + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber + , slea.AdjustmentID + ,slea.BudgetConfigGUID + ,slea.AdjustmentType + ,slea.[Value] + ,slea.AdjustmentFilterJSON + ,slea.GroupingHierarchyJSON + ,slea.AdjustedProperty + ,ISNULL(ag.Description, slea.Comment) AS Comment + ,slea.AuthorGUID + ,slea.AuthorFullName + ,slea.LastModifiedDateUtc + ,slea.DateCreatedUtc + ,slea.GroupingGUID + ,slea.TimeClassID + ,3 as BudgetPhaseID --hardcode budget phase to 3 since not on fp.ReimbursementAdjustment + ,slea.ClassificationGroupID + ,slea.ClassificationCategoryID + ,slea.UnitTypeID + ,NULL AS JobCode + ,NULL AS JobCodeCount + ,NULL AS DepartmentCode + ,NULL AS DepartmentCount + ,sai.ImportUnitTypeIDs + ,slea.IsRecordDeleted + ,slea.IsCarryForward + FROM fp.ReimbursementAdjustment AS slea WITH (NOLOCK) + JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID + LEFT JOIN ( + SELECT p.AdjustmentID, + ImportUnitTypeIDs = + TRIM(STUFF( + (SELECT N' ' + CAST(p2.UnitTypeID AS VARCHAR(5)) + FROM #importAdjustments AS p2 + WHERE p2.AdjustmentID = p.AdjustmentID + GROUP BY p2.AdjustmentID, + p2.UnitTypeID + FOR XML PATH(N'')) + , 1, 0, N'')) + FROM #importAdjustments AS p + GROUP BY p.AdjustmentID + ) AS sai ON sai.AdjustmentID = slea.AdjustmentID + LEFT JOIN fp.viewAdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID + LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID + LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acg.GroupID = acg.GroupID + AND slea.ClassificationCategoryID = acc.CategoryID + LEFT JOIN ( + SELECT nsa.GroupingGUID + FROM fp.ReimbursementAdjustment as nsa WITH (NOLOCK) + WHERE nsa.AdjustmentType IN (12, 13, 14) -- Currently not supported types + AND nsa.BudgetConfigGUID = @budgetGUID + GROUP BY nsa.GroupingGUID + ) AS ra ON ra.GroupingGUID = slea.GroupingGUID + WHERE (slea.AdjustmentType <> 4 OR sai.ImportUnitTypeIDs <> '') + AND (ra.GroupingGUID IS NULL OR slea.AdjustmentType IN (12, 13, 14)) + AND (@search IS NULL + OR ( + LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\' + OR LOWER(ISNULL(ag.Description, slea.Comment)) LIKE @search ESCAPE '\' + OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR acc.[Name] LIKE @search ESCAPE '\' + OR acg.[Name] LIKE @search ESCAPE '\' + OR fp.SearchHierarchyLevel(slea.AdjustmentFilterJSON, @search) = 1 + OR LOWER(fp.GetAdjustmentMeasure(slea.AdjustmentType, slea.UnitTypeID)) LIKE @search ESCAPE '\' + OR fp.SearchAdjustmentMeasureForImport(slea.AdjustmentType, sai.ImportUnitTypeIDs, @search) = 1 + ) + ) + AND (@filter IS NULL + OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, 3) IN ( --hardcode budget phase to 3 since not on fp.ReimbursementAdjustment + SELECT [value] + FROM STRING_SPLIT(@filter, ' ') + ) + ) + ) AS res_inner + WHERE res_inner.RowNumber = 1 ) AS res + WHERE res.RowNumber = 1 + ORDER BY res.DateCreatedUtc DESC + OFFSET @start ROWS + FETCH NEXT @pageSize ROWS ONLY; +END; +GO + + +--------------------------------------------- + +-- fp.procReimbursementChargesRateProjectionAnnualize +CREATE PROCEDURE [fp].[procReimbursementChargesRateProjectionAnnualize] + @BudgetConfigID INT, + @BudgetConfigGUID UNIQUEIDENTIFIER, + @MonthsLoaded INT, + @DefaultReimbursementProjectionMethodID INT + AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author BLI Description + ** 1 2022-02-04 NT JAZZ-31779 Initial + ** 2 2023-04-03 MD JAZZ-52160 Update IDsToUpdate insert logic to include records that have no default projection method + *************************************************************/ + BEGIN + DECLARE @UseDefault INT = -1 + IF @DefaultReimbursementProjectionMethodID = 1 BEGIN SET @UseDefault = 0 END + + IF OBJECT_ID('tempdb..#IDsToUpdate') IS NOT NULL DROP TABLE #IDsToUpdate + + CREATE TABLE #IDsToUpdate (ReimbursementChargesID INT, MonthsLoadedAverage DECIMAL(18,9)) + + INSERT INTO #IDsToUpdate (ReimbursementChargesID, MonthsLoadedAverage) + SELECT ReimbursementChargesID, + CASE WHEN @MonthsLoaded = 1 THEN InitialProjectionNetAsPercentOfCharge01 + WHEN @MonthsLoaded = 2 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02) / 2 + WHEN @MonthsLoaded = 3 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03) / 3 + WHEN @MonthsLoaded = 4 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04) / 4 + WHEN @MonthsLoaded = 5 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05) / 5 + WHEN @MonthsLoaded = 6 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06) / 6 + WHEN @MonthsLoaded = 7 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06 + InitialProjectionNetAsPercentOfCharge07) / 7 + WHEN @MonthsLoaded = 8 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06 + InitialProjectionNetAsPercentOfCharge07 + InitialProjectionNetAsPercentOfCharge08) / 8 + WHEN @MonthsLoaded = 9 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06 + InitialProjectionNetAsPercentOfCharge07 + InitialProjectionNetAsPercentOfCharge08 + InitialProjectionNetAsPercentOfCharge09) / 9 + WHEN @MonthsLoaded = 10 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06 + InitialProjectionNetAsPercentOfCharge07 + InitialProjectionNetAsPercentOfCharge08 + InitialProjectionNetAsPercentOfCharge09 + InitialProjectionNetAsPercentOfCharge10) / 10 + WHEN @MonthsLoaded = 11 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06 + InitialProjectionNetAsPercentOfCharge07 + InitialProjectionNetAsPercentOfCharge08 + InitialProjectionNetAsPercentOfCharge09 + InitialProjectionNetAsPercentOfCharge10 + InitialProjectionNetAsPercentOfCharge11) / 11 + /* We don't allow MonthsLoaded to = 12 */ + END + FROM fp.FactReimbursementCharges chg + LEFT JOIN fp.ReimbursementProjectionMethod pm + ON chg.PayorGroupID = pm.PayorGroupID + WHERE chg.BudgetConfigID = @BudgetConfigID + AND (pm.ProjectionMethodID IN (1, @UseDefault) + AND pm.BudgetConfigGUID = @BudgetConfigGUID) /* Annualized */ + + --Insert IDs whose payor groups are not explicitly defined in fp.ReimbursementProjectionMethod if the default projection method is annualized + IF (@UseDefault = 0) + BEGIN + INSERT INTO #IDsToUpdate (ReimbursementChargesID, MonthsLoadedAverage) + SELECT chg.ReimbursementChargesID, + CASE WHEN @MonthsLoaded = 1 THEN InitialProjectionNetAsPercentOfCharge01 + WHEN @MonthsLoaded = 2 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02) / 2 + WHEN @MonthsLoaded = 3 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03) / 3 + WHEN @MonthsLoaded = 4 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04) / 4 + WHEN @MonthsLoaded = 5 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05) / 5 + WHEN @MonthsLoaded = 6 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06) / 6 + WHEN @MonthsLoaded = 7 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06 + InitialProjectionNetAsPercentOfCharge07) / 7 + WHEN @MonthsLoaded = 8 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06 + InitialProjectionNetAsPercentOfCharge07 + InitialProjectionNetAsPercentOfCharge08) / 8 + WHEN @MonthsLoaded = 9 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06 + InitialProjectionNetAsPercentOfCharge07 + InitialProjectionNetAsPercentOfCharge08 + InitialProjectionNetAsPercentOfCharge09) / 9 + WHEN @MonthsLoaded = 10 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06 + InitialProjectionNetAsPercentOfCharge07 + InitialProjectionNetAsPercentOfCharge08 + InitialProjectionNetAsPercentOfCharge09 + InitialProjectionNetAsPercentOfCharge10) / 10 + WHEN @MonthsLoaded = 11 THEN (InitialProjectionNetAsPercentOfCharge01 + InitialProjectionNetAsPercentOfCharge02 + InitialProjectionNetAsPercentOfCharge03 + InitialProjectionNetAsPercentOfCharge04 + InitialProjectionNetAsPercentOfCharge05 + InitialProjectionNetAsPercentOfCharge06 + InitialProjectionNetAsPercentOfCharge07 + InitialProjectionNetAsPercentOfCharge08 + InitialProjectionNetAsPercentOfCharge09 + InitialProjectionNetAsPercentOfCharge10 + InitialProjectionNetAsPercentOfCharge11) / 11 + /* We don't allow MonthsLoaded to = 12 */ + END + FROM fp.FactReimbursementCharges chg + LEFT JOIN fp.ReimbursementProjectionMethod pm + ON chg.PayorGroupID = pm.PayorGroupID + AND pm.BudgetConfigGUID = @BudgetConfigGUID + LEFT JOIN #IDsToUpdate id on chg.ReimbursementChargesID = id.ReimbursementChargesID + WHERE chg.BudgetConfigID = @BudgetConfigID + AND pm.RowID is null + AND id.ReimbursementChargesID IS NULL --Don't want to insert duplicates from first insert + END + + UPDATE + chg + SET + InitialProjectionNetAsPercentOfCharge02 = + CASE + WHEN @MonthsLoaded >= 2 THEN InitialProjectionNetAsPercentOfCharge02 + ELSE MonthsLoadedAverage + END, + InitialProjectionNetAsPercentOfCharge03 = + CASE + WHEN @MonthsLoaded >= 3 THEN InitialProjectionNetAsPercentOfCharge03 + ELSE MonthsLoadedAverage + END, + InitialProjectionNetAsPercentOfCharge04 = + CASE + WHEN @MonthsLoaded >= 4 THEN InitialProjectionNetAsPercentOfCharge04 + ELSE MonthsLoadedAverage + END, + InitialProjectionNetAsPercentOfCharge05 = + CASE + WHEN @MonthsLoaded >= 5 THEN InitialProjectionNetAsPercentOfCharge05 + ELSE MonthsLoadedAverage + END, + InitialProjectionNetAsPercentOfCharge06 = + CASE + WHEN @MonthsLoaded >= 6 THEN InitialProjectionNetAsPercentOfCharge06 + ELSE MonthsLoadedAverage + END, + InitialProjectionNetAsPercentOfCharge07 = + CASE + WHEN @MonthsLoaded >= 7 THEN InitialProjectionNetAsPercentOfCharge07 + ELSE MonthsLoadedAverage + END, + InitialProjectionNetAsPercentOfCharge08 = + CASE + WHEN @MonthsLoaded >= 8 THEN InitialProjectionNetAsPercentOfCharge08 + ELSE MonthsLoadedAverage + END, + InitialProjectionNetAsPercentOfCharge09 = + CASE + WHEN @MonthsLoaded >= 9 THEN InitialProjectionNetAsPercentOfCharge09 + ELSE MonthsLoadedAverage + END, + InitialProjectionNetAsPercentOfCharge10 = + CASE + WHEN @MonthsLoaded >= 10 THEN InitialProjectionNetAsPercentOfCharge10 + ELSE MonthsLoadedAverage + END, + InitialProjectionNetAsPercentOfCharge11 = + CASE + WHEN @MonthsLoaded >= 11 THEN InitialProjectionNetAsPercentOfCharge11 + ELSE MonthsLoadedAverage + END, + InitialProjectionNetAsPercentOfCharge12 = MonthsLoadedAverage, + InitialBudgetNetAsPercentOfCharge01 = MonthsLoadedAverage, + InitialBudgetNetAsPercentOfCharge02 = MonthsLoadedAverage, + InitialBudgetNetAsPercentOfCharge03 = MonthsLoadedAverage, + InitialBudgetNetAsPercentOfCharge04 = MonthsLoadedAverage, + InitialBudgetNetAsPercentOfCharge05 = MonthsLoadedAverage, + InitialBudgetNetAsPercentOfCharge06 = MonthsLoadedAverage, + InitialBudgetNetAsPercentOfCharge07 = MonthsLoadedAverage, + InitialBudgetNetAsPercentOfCharge08 = MonthsLoadedAverage, + InitialBudgetNetAsPercentOfCharge09 = MonthsLoadedAverage, + InitialBudgetNetAsPercentOfCharge10 = MonthsLoadedAverage, + InitialBudgetNetAsPercentOfCharge11 = MonthsLoadedAverage, + InitialBudgetNetAsPercentOfCharge12 = MonthsLoadedAverage + FROM + [fp].[FactReimbursementCharges] chg + INNER JOIN #IDsToUpdate i ON + chg.ReimbursementChargesID = i.ReimbursementChargesID + + UPDATE rcb + SET + AdjustedNetAsPercentOfCharge01 = MonthsLoadedAverage, + AdjustedNetAsPercentOfCharge02 = MonthsLoadedAverage, + AdjustedNetAsPercentOfCharge03 = MonthsLoadedAverage, + AdjustedNetAsPercentOfCharge04 = MonthsLoadedAverage, + AdjustedNetAsPercentOfCharge05 = MonthsLoadedAverage, + AdjustedNetAsPercentOfCharge06 = MonthsLoadedAverage, + AdjustedNetAsPercentOfCharge07 = MonthsLoadedAverage, + AdjustedNetAsPercentOfCharge08 = MonthsLoadedAverage, + AdjustedNetAsPercentOfCharge09 = MonthsLoadedAverage, + AdjustedNetAsPercentOfCharge10 = MonthsLoadedAverage, + AdjustedNetAsPercentOfCharge11 = MonthsLoadedAverage, + AdjustedNetAsPercentOfCharge12 = MonthsLoadedAverage + FROM [fp].[FactReimbursementCharges] rc INNER JOIN #IDsToUpdate i ON rc.ReimbursementChargesID = i.ReimbursementChargesID + INNER JOIN [fp].[FactReimbursementChargesBudget] rcb on rc.ReimbursementChargesID = rcb.ReimbursementChargesID + + UPDATE rcp + SET + AdjustedNetAsPercentOfCharge01 = InitialProjectionNetAsPercentOfCharge01, + AdjustedNetAsPercentOfCharge02 = CASE WHEN @MonthsLoaded >= 2 THEN InitialProjectionNetAsPercentOfCharge02 ELSE MonthsLoadedAverage END, + AdjustedNetAsPercentOfCharge03 = CASE WHEN @MonthsLoaded >= 3 THEN InitialProjectionNetAsPercentOfCharge03 ELSE MonthsLoadedAverage END, + AdjustedNetAsPercentOfCharge04 = CASE WHEN @MonthsLoaded >= 4 THEN InitialProjectionNetAsPercentOfCharge04 ELSE MonthsLoadedAverage END, + AdjustedNetAsPercentOfCharge05 = CASE WHEN @MonthsLoaded >= 5 THEN InitialProjectionNetAsPercentOfCharge05 ELSE MonthsLoadedAverage END, + AdjustedNetAsPercentOfCharge06 = CASE WHEN @MonthsLoaded >= 6 THEN InitialProjectionNetAsPercentOfCharge06 ELSE MonthsLoadedAverage END, + AdjustedNetAsPercentOfCharge07 = CASE WHEN @MonthsLoaded >= 7 THEN InitialProjectionNetAsPercentOfCharge07 ELSE MonthsLoadedAverage END, + AdjustedNetAsPercentOfCharge08 = CASE WHEN @MonthsLoaded >= 8 THEN InitialProjectionNetAsPercentOfCharge08 ELSE MonthsLoadedAverage END, + AdjustedNetAsPercentOfCharge09 = CASE WHEN @MonthsLoaded >= 9 THEN InitialProjectionNetAsPercentOfCharge09 ELSE MonthsLoadedAverage END, + AdjustedNetAsPercentOfCharge10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjectionNetAsPercentOfCharge10 ELSE MonthsLoadedAverage END, + AdjustedNetAsPercentOfCharge11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjectionNetAsPercentOfCharge11 ELSE MonthsLoadedAverage END, + AdjustedNetAsPercentOfCharge12 = MonthsLoadedAverage + FROM [fp].[FactReimbursementCharges] rc INNER JOIN #IDsToUpdate i ON rc.ReimbursementChargesID = i.ReimbursementChargesID + INNER JOIN [fp].[FactReimbursementChargesProjection] rcp on rc.ReimbursementChargesID = rcp.ReimbursementChargesID + + IF OBJECT_ID('tempdb..#IDsToUpdate') IS NOT NULL DROP TABLE #IDsToUpdate + + END +GO + + +--------------------------------------------- + +-- fp.procReimbursementChargesRateProjectionLastObserved +CREATE PROCEDURE [fp].[procReimbursementChargesRateProjectionLastObserved] + @BudgetConfigID INT, + @BudgetConfigGUID UNIQUEIDENTIFIER, + @MonthsLoaded INT, + @DefaultReimbursementProjectionMethodID INT, + @IsDebugFlag BIT = 0 + AS + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author BLI Description + ** 1 2022-02-07 NT JAZZ-31779 Initial + ** 2 2023-05-11 MD JAZZ-52160 Update IDsToUpdate insert logic to include records that have no default projection method + *************************************************************/ + BEGIN + DECLARE @UseDefault INT = -1 + IF @DefaultReimbursementProjectionMethodID = 2 BEGIN SET @UseDefault = 0 END + + IF OBJECT_ID('tempdb..#IDsToUpdate') IS NOT NULL DROP TABLE #IDsToUpdate + IF OBJECT_ID('tempdb..#unpivoted') IS NOT NULL DROP TABLE #unpivoted + IF OBJECT_ID('tempdb..#LastObservedMonth') IS NOT NULL DROP TABLE #LastObservedMonth + + CREATE TABLE #IDsToUpdate ( + ReimbursementChargesID INT, + LastObservedMonthValue DECIMAL(18,9) + ) + + --Create #unpivoted temp table to unpivot monthly Percent of Charge data to determine LastObservedMonth + CREATE TABLE #unpivoted (ReimbursementChargesID INT, MonthPivotColName VARCHAR(50), MonthNumber tinyint, MonthValue DECIMAL(19,8)) + + INSERT INTO #unpivoted(ReimbursementChargesID, MonthPivotColName, MonthNumber, MonthValue) + SELECT ReimbursementChargesID, MonthPivotColName, CAST(RIGHT(MonthPivotColName,2) AS INT) As MonthNumber, MonthValue + FROM (SELECT ReimbursementChargesID, + InitialProjectionNetAsPercentOfCharge01, + InitialProjectionNetAsPercentOfCharge02, + InitialProjectionNetAsPercentOfCharge03, + InitialProjectionNetAsPercentOfCharge04, + InitialProjectionNetAsPercentOfCharge05, + InitialProjectionNetAsPercentOfCharge06, + InitialProjectionNetAsPercentOfCharge07, + InitialProjectionNetAsPercentOfCharge08, + InitialProjectionNetAsPercentOfCharge09, + InitialProjectionNetAsPercentOfCharge10, + InitialProjectionNetAsPercentOfCharge11, + InitialProjectionNetAsPercentOfCharge12 + FROM fp.FactReimbursementCharges chg + INNER JOIN fp.ReimbursementProjectionMethod pm + ON chg.PayorGroupID = pm.PayorGroupID + WHERE chg.BudgetConfigID = @BudgetConfigID + AND pm.ProjectionMethodID IN (2, @UseDefault) /* Last Observed Month */ + AND pm.BudgetConfigGUID = @BudgetConfigGUID + ) pvt + UNPIVOT + (MonthValue For MonthPivotColName in (InitialProjectionNetAsPercentOfCharge01, + InitialProjectionNetAsPercentOfCharge02, + InitialProjectionNetAsPercentOfCharge03, + InitialProjectionNetAsPercentOfCharge04, + InitialProjectionNetAsPercentOfCharge05, + InitialProjectionNetAsPercentOfCharge06, + InitialProjectionNetAsPercentOfCharge07, + InitialProjectionNetAsPercentOfCharge08, + InitialProjectionNetAsPercentOfCharge09, + InitialProjectionNetAsPercentOfCharge10, + InitialProjectionNetAsPercentOfCharge11, + InitialProjectionNetAsPercentOfCharge12)) As unpvt + + --Create temporary table for LastObservedMonthValue per ReimbursementChargesID + CREATE TABLE #LastObservedMonth (ReimbursementChargesID INT, LastObservedMonth INT) + + INSERT INTO #LastObservedMonth (ReimbursementChargesID, LastObservedMonth) + SELECT ReimbursementChargesID, MAX(MonthNumber) AS LastObservedMonth --Last Month that is non-zero + FROM #unpivoted + WHERE MonthNumber <= @MonthsLoaded --Only Months that are imported + AND MonthValue > 0 --MonthValue is not 0 + GROUP BY ReimbursementChargesID + + --Now Insert LastObservedMonthValue based on #LastObservedMonth & DISTINCT ReimbursementChargesID from #unpivoted + INSERT INTO #IDsToUpdate (ReimbursementChargesID, LastObservedMonthValue) + SELECT uv.ReimbursementChargesID, ISNULL(LastObservedMonthValue, 0) + FROM (SELECT DISTINCT ReimbursementChargesID + FROM #unpivoted) uv + LEFT JOIN (SELECT lom.ReimbursementChargesID, lommv.MonthValue As LastObservedMonthValue + FROM #LastObservedMonth lom + INNER JOIN #unpivoted lommv + ON lommv.ReimbursementChargesID = lom.ReimbursementChargesID + AND lommv.MonthNumber = lom.LastObservedMonth + ) lom + ON uv.ReimbursementChargesID = lom.ReimbursementChargesID + + IF(@UseDefault = 0) + BEGIN + INSERT INTO #unpivoted(ReimbursementChargesID, MonthPivotColName, MonthNumber, MonthValue) + SELECT ReimbursementChargesID, MonthPivotColName, CAST(RIGHT(MonthPivotColName,2) AS INT) As MonthNumber, MonthValue + FROM (SELECT chg.ReimbursementChargesID, + InitialProjectionNetAsPercentOfCharge01, + InitialProjectionNetAsPercentOfCharge02, + InitialProjectionNetAsPercentOfCharge03, + InitialProjectionNetAsPercentOfCharge04, + InitialProjectionNetAsPercentOfCharge05, + InitialProjectionNetAsPercentOfCharge06, + InitialProjectionNetAsPercentOfCharge07, + InitialProjectionNetAsPercentOfCharge08, + InitialProjectionNetAsPercentOfCharge09, + InitialProjectionNetAsPercentOfCharge10, + InitialProjectionNetAsPercentOfCharge11, + InitialProjectionNetAsPercentOfCharge12 + FROM fp.FactReimbursementCharges chg + LEFT JOIN fp.ReimbursementProjectionMethod pm + ON chg.PayorGroupID = pm.PayorGroupID + AND pm.BudgetConfigGUID = @BudgetConfigGUID + LEFT JOIN #unpivoted uv on chg.ReimbursementChargesID = uv.ReimbursementChargesID + WHERE chg.BudgetConfigID = @BudgetConfigID + AND uv.ReimbursementChargesID IS NULL + AND pm.RowID IS NULL + ) pvt + UNPIVOT + (MonthValue For MonthPivotColName in (InitialProjectionNetAsPercentOfCharge01, + InitialProjectionNetAsPercentOfCharge02, + InitialProjectionNetAsPercentOfCharge03, + InitialProjectionNetAsPercentOfCharge04, + InitialProjectionNetAsPercentOfCharge05, + InitialProjectionNetAsPercentOfCharge06, + InitialProjectionNetAsPercentOfCharge07, + InitialProjectionNetAsPercentOfCharge08, + InitialProjectionNetAsPercentOfCharge09, + InitialProjectionNetAsPercentOfCharge10, + InitialProjectionNetAsPercentOfCharge11, + InitialProjectionNetAsPercentOfCharge12)) As unpvt + + INSERT INTO #LastObservedMonth (ReimbursementChargesID, LastObservedMonth) + SELECT uv.ReimbursementChargesID, MAX(MonthNumber) AS LastObservedMonth --Last Month that is non-zero + FROM #unpivoted uv + LEFT JOIN #LastObservedMonth lm on uv.ReimbursementChargesID = lm.ReimbursementChargesID + WHERE MonthNumber <= @MonthsLoaded --Only Months that are imported + AND MonthValue > 0 --MonthValue is not 0 + GROUP BY uv.ReimbursementChargesID + + --Now Insert LastObservedMonthValue based on #LastObservedMonth & DISTINCT ReimbursementChargesID from #unpivoted + INSERT INTO #IDsToUpdate (ReimbursementChargesID, LastObservedMonthValue) + SELECT uv.ReimbursementChargesID, ISNULL(lom.LastObservedMonthValue, 0) + FROM (SELECT DISTINCT ReimbursementChargesID + FROM #unpivoted) uv + LEFT JOIN (SELECT lom.ReimbursementChargesID, lommv.MonthValue As LastObservedMonthValue + FROM #LastObservedMonth lom + INNER JOIN #unpivoted lommv + ON lommv.ReimbursementChargesID = lom.ReimbursementChargesID + AND lommv.MonthNumber = lom.LastObservedMonth + ) lom + ON uv.ReimbursementChargesID = lom.ReimbursementChargesID + LEFT JOIN #IDsToUpdate id on uv.ReimbursementChargesID = id.ReimbursementChargesID + END + + IF (@IsDebugFlag = 1) + BEGIN + PRINT 'Debug Mode ON' + SELECT '#unpivoted', * FROM #unpivoted + SELECT '#LastObservedMonth' FROM #LastObservedMonth + SELECT '#IDsToUpdate', * FROM #IDsToUpdate + END + ELSE + BEGIN + UPDATE chg SET + InitialProjectionNetAsPercentOfCharge02 = + CASE + WHEN @MonthsLoaded >= 2 THEN InitialProjectionNetAsPercentOfCharge02 + ELSE LastObservedMonthValue + END, + InitialProjectionNetAsPercentOfCharge03 = + CASE + WHEN @MonthsLoaded >= 3 THEN InitialProjectionNetAsPercentOfCharge03 + ELSE LastObservedMonthValue + END, + InitialProjectionNetAsPercentOfCharge04 = + CASE + WHEN @MonthsLoaded >= 4 THEN InitialProjectionNetAsPercentOfCharge04 + ELSE LastObservedMonthValue + END, + InitialProjectionNetAsPercentOfCharge05 = + CASE + WHEN @MonthsLoaded >= 5 THEN InitialProjectionNetAsPercentOfCharge05 + ELSE LastObservedMonthValue + END, + InitialProjectionNetAsPercentOfCharge06 = + CASE + WHEN @MonthsLoaded >= 6 THEN InitialProjectionNetAsPercentOfCharge06 + ELSE LastObservedMonthValue + END, + InitialProjectionNetAsPercentOfCharge07 = + CASE + WHEN @MonthsLoaded >= 7 THEN InitialProjectionNetAsPercentOfCharge07 + ELSE LastObservedMonthValue + END, + InitialProjectionNetAsPercentOfCharge08 = + CASE + WHEN @MonthsLoaded >= 8 THEN InitialProjectionNetAsPercentOfCharge08 + ELSE LastObservedMonthValue + END, + InitialProjectionNetAsPercentOfCharge09 = + CASE + WHEN @MonthsLoaded >= 9 THEN InitialProjectionNetAsPercentOfCharge09 + ELSE LastObservedMonthValue + END, + InitialProjectionNetAsPercentOfCharge10 = + CASE + WHEN @MonthsLoaded >= 10 THEN InitialProjectionNetAsPercentOfCharge10 + ELSE LastObservedMonthValue + END, + InitialProjectionNetAsPercentOfCharge11 = + CASE + WHEN @MonthsLoaded >= 11 THEN InitialProjectionNetAsPercentOfCharge11 + ELSE LastObservedMonthValue + END, + InitialProjectionNetAsPercentOfCharge12 = LastObservedMonthValue, + InitialBudgetNetAsPercentOfCharge01 = LastObservedMonthValue, + InitialBudgetNetAsPercentOfCharge02 = LastObservedMonthValue, + InitialBudgetNetAsPercentOfCharge03 = LastObservedMonthValue, + InitialBudgetNetAsPercentOfCharge04 = LastObservedMonthValue, + InitialBudgetNetAsPercentOfCharge05 = LastObservedMonthValue, + InitialBudgetNetAsPercentOfCharge06 = LastObservedMonthValue, + InitialBudgetNetAsPercentOfCharge07 = LastObservedMonthValue, + InitialBudgetNetAsPercentOfCharge08 = LastObservedMonthValue, + InitialBudgetNetAsPercentOfCharge09 = LastObservedMonthValue, + InitialBudgetNetAsPercentOfCharge10 = LastObservedMonthValue, + InitialBudgetNetAsPercentOfCharge11 = LastObservedMonthValue, + InitialBudgetNetAsPercentOfCharge12 = LastObservedMonthValue + FROM + [fp].[FactReimbursementCharges] chg + INNER JOIN #IDsToUpdate i ON + chg.ReimbursementChargesID = i.ReimbursementChargesID + + UPDATE rcb + SET + AdjustedNetAsPercentOfCharge01 = LastObservedMonthValue, + AdjustedNetAsPercentOfCharge02 = LastObservedMonthValue, + AdjustedNetAsPercentOfCharge03 = LastObservedMonthValue, + AdjustedNetAsPercentOfCharge04 = LastObservedMonthValue, + AdjustedNetAsPercentOfCharge05 = LastObservedMonthValue, + AdjustedNetAsPercentOfCharge06 = LastObservedMonthValue, + AdjustedNetAsPercentOfCharge07 = LastObservedMonthValue, + AdjustedNetAsPercentOfCharge08 = LastObservedMonthValue, + AdjustedNetAsPercentOfCharge09 = LastObservedMonthValue, + AdjustedNetAsPercentOfCharge10 = LastObservedMonthValue, + AdjustedNetAsPercentOfCharge11 = LastObservedMonthValue, + AdjustedNetAsPercentOfCharge12 = LastObservedMonthValue + FROM [fp].[FactReimbursementCharges] rc INNER JOIN #IDsToUpdate i ON rc.ReimbursementChargesID = i.ReimbursementChargesID + INNER JOIN [fp].[FactReimbursementChargesBudget] rcb on rc.ReimbursementChargesID = rcb.ReimbursementChargesID + + UPDATE rcp + SET + AdjustedNetAsPercentOfCharge01 = InitialProjectionNetAsPercentOfCharge01, + AdjustedNetAsPercentOfCharge02 = CASE WHEN @MonthsLoaded >= 2 THEN InitialProjectionNetAsPercentOfCharge02 ELSE LastObservedMonthValue END, + AdjustedNetAsPercentOfCharge03 = CASE WHEN @MonthsLoaded >= 3 THEN InitialProjectionNetAsPercentOfCharge03 ELSE LastObservedMonthValue END, + AdjustedNetAsPercentOfCharge04 = CASE WHEN @MonthsLoaded >= 4 THEN InitialProjectionNetAsPercentOfCharge04 ELSE LastObservedMonthValue END, + AdjustedNetAsPercentOfCharge05 = CASE WHEN @MonthsLoaded >= 5 THEN InitialProjectionNetAsPercentOfCharge05 ELSE LastObservedMonthValue END, + AdjustedNetAsPercentOfCharge06 = CASE WHEN @MonthsLoaded >= 6 THEN InitialProjectionNetAsPercentOfCharge06 ELSE LastObservedMonthValue END, + AdjustedNetAsPercentOfCharge07 = CASE WHEN @MonthsLoaded >= 7 THEN InitialProjectionNetAsPercentOfCharge07 ELSE LastObservedMonthValue END, + AdjustedNetAsPercentOfCharge08 = CASE WHEN @MonthsLoaded >= 8 THEN InitialProjectionNetAsPercentOfCharge08 ELSE LastObservedMonthValue END, + AdjustedNetAsPercentOfCharge09 = CASE WHEN @MonthsLoaded >= 9 THEN InitialProjectionNetAsPercentOfCharge09 ELSE LastObservedMonthValue END, + AdjustedNetAsPercentOfCharge10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjectionNetAsPercentOfCharge10 ELSE LastObservedMonthValue END, + AdjustedNetAsPercentOfCharge11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjectionNetAsPercentOfCharge11 ELSE LastObservedMonthValue END, + AdjustedNetAsPercentOfCharge12 = LastObservedMonthValue + FROM [fp].[FactReimbursementCharges] rc INNER JOIN #IDsToUpdate i ON rc.ReimbursementChargesID = i.ReimbursementChargesID + INNER JOIN [fp].[FactReimbursementChargesProjection] rcp on rc.ReimbursementChargesID = rcp.ReimbursementChargesID + + END + + IF OBJECT_ID('tempdb..#IDsToUpdate') IS NOT NULL DROP TABLE #IDsToUpdate + IF OBJECT_ID('tempdb..#unpivoted') IS NOT NULL DROP TABLE #unpivoted + IF OBJECT_ID('tempdb..#LastObservedMonth') IS NOT NULL DROP TABLE #LastObservedMonth + + END +GO + + +--------------------------------------------- + +-- fp.procReimbursementEncounterRateProjectionAnnualize +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-02-03 BK JAZZ-31778 Initial + ** 2 2023-04-03 MD JAZZ-52160 Update IDsToUpdate insert logic to include records that have no default projection method +*************************************************************/ +CREATE PROCEDURE [fp].[procReimbursementEncounterRateProjectionAnnualize] + @BudgetConfigGUID UNIQUEIDENTIFIER, + @BudgetConfigID INT, + @MonthsLoaded TINYINT, + @DefaultProjectionMethodID INT +AS +BEGIN + +IF OBJECT_ID('tempdb..#IDsToUpdate') IS NOT NULL DROP TABLE #IDsToUpdate + +CREATE TABLE #IDsToUpdate (ReimbursementEncounterID INT, MonthsLoadedAverage DECIMAL(18,9)) + +DECLARE @UseDefault INT = -1 +IF @DefaultProjectionMethodID = 1 BEGIN SET @UseDefault = 0 END + +INSERT INTO #IDsToUpdate (ReimbursementEncounterID, MonthsLoadedAverage) +SELECT ReimbursementEncounterID, + CASE WHEN @MonthsLoaded = 1 THEN InitialProjectionNetPerEncounter01 + WHEN @MonthsLoaded = 2 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02) / 2 + WHEN @MonthsLoaded = 3 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03) / 3 + WHEN @MonthsLoaded = 4 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04) / 4 + WHEN @MonthsLoaded = 5 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05) / 5 + WHEN @MonthsLoaded = 6 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06) / 6 + WHEN @MonthsLoaded = 7 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06 + InitialProjectionNetPerEncounter07) / 7 + WHEN @MonthsLoaded = 8 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06 + InitialProjectionNetPerEncounter07 + InitialProjectionNetPerEncounter08) / 8 + WHEN @MonthsLoaded = 9 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06 + InitialProjectionNetPerEncounter07 + InitialProjectionNetPerEncounter08 + InitialProjectionNetPerEncounter09) / 9 + WHEN @MonthsLoaded = 10 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06 + InitialProjectionNetPerEncounter07 + InitialProjectionNetPerEncounter08 + InitialProjectionNetPerEncounter09 + InitialProjectionNetPerEncounter10) / 10 + WHEN @MonthsLoaded = 11 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06 + InitialProjectionNetPerEncounter07 + InitialProjectionNetPerEncounter08 + InitialProjectionNetPerEncounter09 + InitialProjectionNetPerEncounter10 + InitialProjectionNetPerEncounter11) / 11 + /* We don't allow MonthsLoaded to = 12 */ + END +FROM fp.FactReimbursementEncounter enc +LEFT JOIN fp.ReimbursementProjectionMethod pm + ON enc.PayorGroupID = pm.PayorGroupID + AND pm.BudgetConfigGUID = @BudgetConfigGUID +WHERE enc.BudgetConfigID = @BudgetConfigID + AND pm.ProjectionMethodID IN (1, @UseDefault) /* Annualized */ + +--Insert IDs whose payor groups are not explicitly defined in fp.ReimbursementProjectionMethod if the default projection method is annualized +IF (@UseDefault = 0) +BEGIN + INSERT INTO #IDsToUpdate (ReimbursementEncounterID, MonthsLoadedAverage) +SELECT enc.ReimbursementEncounterID, + CASE WHEN @MonthsLoaded = 1 THEN InitialProjectionNetPerEncounter01 + WHEN @MonthsLoaded = 2 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02) / 2 + WHEN @MonthsLoaded = 3 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03) / 3 + WHEN @MonthsLoaded = 4 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04) / 4 + WHEN @MonthsLoaded = 5 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05) / 5 + WHEN @MonthsLoaded = 6 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06) / 6 + WHEN @MonthsLoaded = 7 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06 + InitialProjectionNetPerEncounter07) / 7 + WHEN @MonthsLoaded = 8 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06 + InitialProjectionNetPerEncounter07 + InitialProjectionNetPerEncounter08) / 8 + WHEN @MonthsLoaded = 9 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06 + InitialProjectionNetPerEncounter07 + InitialProjectionNetPerEncounter08 + InitialProjectionNetPerEncounter09) / 9 + WHEN @MonthsLoaded = 10 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06 + InitialProjectionNetPerEncounter07 + InitialProjectionNetPerEncounter08 + InitialProjectionNetPerEncounter09 + InitialProjectionNetPerEncounter10) / 10 + WHEN @MonthsLoaded = 11 THEN (InitialProjectionNetPerEncounter01 + InitialProjectionNetPerEncounter02 + InitialProjectionNetPerEncounter03 + InitialProjectionNetPerEncounter04 + InitialProjectionNetPerEncounter05 + InitialProjectionNetPerEncounter06 + InitialProjectionNetPerEncounter07 + InitialProjectionNetPerEncounter08 + InitialProjectionNetPerEncounter09 + InitialProjectionNetPerEncounter10 + InitialProjectionNetPerEncounter11) / 11 + /* We don't allow MonthsLoaded to = 12 */ + END +FROM fp.FactReimbursementEncounter enc +LEFT JOIN fp.ReimbursementProjectionMethod pm + ON enc.PayorGroupID = pm.PayorGroupID + AND pm.BudgetConfigGUID = @BudgetConfigGUID +LEFT JOIN #IDsToUpdate id on enc.ReimbursementEncounterID = id.ReimbursementEncounterID +WHERE + enc.BudgetConfigID = @BudgetConfigID + AND pm.RowID is null + AND id.ReimbursementEncounterID IS NULL --Don't want to insert duplicates from first insert +END + +UPDATE re +SET + InitialProjectionNetPerEncounter02 = CASE WHEN @MonthsLoaded >= 2 THEN InitialProjectionNetPerEncounter02 ELSE MonthsLoadedAverage END, + InitialProjectionNetPerEncounter03 = CASE WHEN @MonthsLoaded >= 3 THEN InitialProjectionNetPerEncounter03 ELSE MonthsLoadedAverage END, + InitialProjectionNetPerEncounter04 = CASE WHEN @MonthsLoaded >= 4 THEN InitialProjectionNetPerEncounter04 ELSE MonthsLoadedAverage END, + InitialProjectionNetPerEncounter05 = CASE WHEN @MonthsLoaded >= 5 THEN InitialProjectionNetPerEncounter05 ELSE MonthsLoadedAverage END, + InitialProjectionNetPerEncounter06 = CASE WHEN @MonthsLoaded >= 6 THEN InitialProjectionNetPerEncounter06 ELSE MonthsLoadedAverage END, + InitialProjectionNetPerEncounter07 = CASE WHEN @MonthsLoaded >= 7 THEN InitialProjectionNetPerEncounter07 ELSE MonthsLoadedAverage END, + InitialProjectionNetPerEncounter08 = CASE WHEN @MonthsLoaded >= 8 THEN InitialProjectionNetPerEncounter08 ELSE MonthsLoadedAverage END, + InitialProjectionNetPerEncounter09 = CASE WHEN @MonthsLoaded >= 9 THEN InitialProjectionNetPerEncounter09 ELSE MonthsLoadedAverage END, + InitialProjectionNetPerEncounter10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjectionNetPerEncounter10 ELSE MonthsLoadedAverage END, + InitialProjectionNetPerEncounter11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjectionNetPerEncounter11 ELSE MonthsLoadedAverage END, + InitialProjectionNetPerEncounter12 = MonthsLoadedAverage, + InitialBudgetNetPerEncounter01 = MonthsLoadedAverage, + InitialBudgetNetPerEncounter02 = MonthsLoadedAverage, + InitialBudgetNetPerEncounter03 = MonthsLoadedAverage, + InitialBudgetNetPerEncounter04 = MonthsLoadedAverage, + InitialBudgetNetPerEncounter05 = MonthsLoadedAverage, + InitialBudgetNetPerEncounter06 = MonthsLoadedAverage, + InitialBudgetNetPerEncounter07 = MonthsLoadedAverage, + InitialBudgetNetPerEncounter08 = MonthsLoadedAverage, + InitialBudgetNetPerEncounter09 = MonthsLoadedAverage, + InitialBudgetNetPerEncounter10 = MonthsLoadedAverage, + InitialBudgetNetPerEncounter11 = MonthsLoadedAverage, + InitialBudgetNetPerEncounter12 = MonthsLoadedAverage +FROM [fp].[FactReimbursementEncounter] re INNER JOIN #IDsToUpdate i ON re.ReimbursementEncounterID = i.ReimbursementEncounterID + +UPDATE reb +SET + AdjustedNetPerEncounterValue01 = MonthsLoadedAverage, + AdjustedNetPerEncounterValue02 = MonthsLoadedAverage, + AdjustedNetPerEncounterValue03 = MonthsLoadedAverage, + AdjustedNetPerEncounterValue04 = MonthsLoadedAverage, + AdjustedNetPerEncounterValue05 = MonthsLoadedAverage, + AdjustedNetPerEncounterValue06 = MonthsLoadedAverage, + AdjustedNetPerEncounterValue07 = MonthsLoadedAverage, + AdjustedNetPerEncounterValue08 = MonthsLoadedAverage, + AdjustedNetPerEncounterValue09 = MonthsLoadedAverage, + AdjustedNetPerEncounterValue10 = MonthsLoadedAverage, + AdjustedNetPerEncounterValue11 = MonthsLoadedAverage, + AdjustedNetPerEncounterValue12 = MonthsLoadedAverage +FROM [fp].[FactReimbursementEncounter] re INNER JOIN #IDsToUpdate i ON re.ReimbursementEncounterID = i.ReimbursementEncounterID + INNER JOIN fp.FactReimbursementEncounterBudget reb on re.ReimbursementEncounterID = reb.ReimbursementEncounterID + +UPDATE rep +SET + AdjustedNetPerEncounterValue01 = InitialProjectionNetPerEncounter01, + AdjustedNetPerEncounterValue02 = CASE WHEN @MonthsLoaded >= 2 THEN InitialProjectionNetPerEncounter02 ELSE MonthsLoadedAverage END, + AdjustedNetPerEncounterValue03 = CASE WHEN @MonthsLoaded >= 3 THEN InitialProjectionNetPerEncounter03 ELSE MonthsLoadedAverage END, + AdjustedNetPerEncounterValue04 = CASE WHEN @MonthsLoaded >= 4 THEN InitialProjectionNetPerEncounter04 ELSE MonthsLoadedAverage END, + AdjustedNetPerEncounterValue05 = CASE WHEN @MonthsLoaded >= 5 THEN InitialProjectionNetPerEncounter05 ELSE MonthsLoadedAverage END, + AdjustedNetPerEncounterValue06 = CASE WHEN @MonthsLoaded >= 6 THEN InitialProjectionNetPerEncounter06 ELSE MonthsLoadedAverage END, + AdjustedNetPerEncounterValue07 = CASE WHEN @MonthsLoaded >= 7 THEN InitialProjectionNetPerEncounter07 ELSE MonthsLoadedAverage END, + AdjustedNetPerEncounterValue08 = CASE WHEN @MonthsLoaded >= 8 THEN InitialProjectionNetPerEncounter08 ELSE MonthsLoadedAverage END, + AdjustedNetPerEncounterValue09 = CASE WHEN @MonthsLoaded >= 9 THEN InitialProjectionNetPerEncounter09 ELSE MonthsLoadedAverage END, + AdjustedNetPerEncounterValue10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjectionNetPerEncounter10 ELSE MonthsLoadedAverage END, + AdjustedNetPerEncounterValue11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjectionNetPerEncounter11 ELSE MonthsLoadedAverage END, + AdjustedNetPerEncounterValue12 = MonthsLoadedAverage +FROM [fp].[FactReimbursementEncounter] re INNER JOIN #IDsToUpdate i ON re.ReimbursementEncounterID = i.ReimbursementEncounterID + INNER JOIN fp.FactReimbursementEncounterProjection rep on re.ReimbursementEncounterID = rep.ReimbursementEncounterID +END +GO + + +--------------------------------------------- + +-- fp.procReimbursementEncounterRateProjectionLastObserved +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-02-03 BK JAZZ-31778 Initial + ** 2 2023-05-11 MD JAZZ-52160 Update IDsToUpdate insert logic to include records that have no default projection method +*************************************************************/ +CREATE PROCEDURE [fp].[procReimbursementEncounterRateProjectionLastObserved] + @BudgetConfigGUID UNIQUEIDENTIFIER, + @BudgetConfigID INT, + @MonthsLoaded TINYINT, + @DefaultProjectionMethodID INT +AS +BEGIN + +IF OBJECT_ID('tempdb..#UnpivotedValues') IS NOT NULL DROP TABLE #UnpivotedValues +IF OBJECT_ID('tempdb..#LastMonth') IS NOT NULL DROP TABLE #LastMonth +IF OBJECT_ID('tempdb..#IDsToUpdate') IS NOT NULL DROP TABLE #IDsToUpdate + +DECLARE @UseDefault INT = -1 +IF @DefaultProjectionMethodID = 2 BEGIN SET @UseDefault = 0 END + +CREATE TABLE #UnpivotedValues (ReimbursementEncounterID INT, MonthValue VARCHAR(35), MonthID INT, PerEncounterValue DECIMAL(18,9)) +CREATE TABLE #LastMonth (ReimbursementEncounterID INT, MonthValue VARCHAR(35)) +CREATE TABLE #IDsToUpdate (ReimbursementEncounterID INT, LastObservedValue DECIMAL(18,9)) + +INSERT INTO #UnpivotedValues (ReimbursementEncounterID, MonthValue, MonthID, PerEncounterValue) +SELECT ReimbursementEncounterID, MonthValue, CAST(RIGHT(MonthValue,2) as INT), PerEncounterValue +FROM +(SELECT ReimbursementEncounterID, PayorGroupID, InitialProjectionNetPerEncounter01, InitialProjectionNetPerEncounter02, InitialProjectionNetPerEncounter03, InitialProjectionNetPerEncounter04, InitialProjectionNetPerEncounter05, InitialProjectionNetPerEncounter06, InitialProjectionNetPerEncounter07, InitialProjectionNetPerEncounter08, InitialProjectionNetPerEncounter09, InitialProjectionNetPerEncounter10, InitialProjectionNetPerEncounter11, InitialProjectionNetPerEncounter12 + FROM fp.FactReimbursementEncounter WHERE BudgetConfigID = @BudgetConfigID) e + UNPIVOT + (PerEncounterValue FOR MonthValue IN (InitialProjectionNetPerEncounter01, InitialProjectionNetPerEncounter02, InitialProjectionNetPerEncounter03, InitialProjectionNetPerEncounter04, InitialProjectionNetPerEncounter05, InitialProjectionNetPerEncounter06, InitialProjectionNetPerEncounter07, InitialProjectionNetPerEncounter08, InitialProjectionNetPerEncounter09, InitialProjectionNetPerEncounter10, InitialProjectionNetPerEncounter11, InitialProjectionNetPerEncounter12) ) AS enc + +INNER JOIN fp.ReimbursementProjectionMethod pm on enc.PayorGroupID = pm.PayorGroupID +WHERE ProjectionMethodID IN (2, @UseDefault) /* Last Observed Month */ + AND BudgetConfigGUID = @BudgetConfigGUID + + +INSERT INTO #LastMonth (ReimbursementEncounterID, MonthValue) +SELECT ReimbursementEncounterID, MAX(MonthValue) +FROM #UnpivotedValues WHERE PerEncounterValue > 0 AND MonthID <= @MonthsLoaded +GROUP BY ReimbursementEncounterID + +INSERT INTO #IDsToUpdate (ReimbursementEncounterID, LastObservedValue) +SELECT uv.ReimbursementEncounterID, ISNULL(PerEncounterValue, 0) +FROM (SELECT DISTINCT ReimbursementEncounterID FROM #UnpivotedValues) uv LEFT JOIN +(SELECT uv.* FROM #UnpivotedValues uv INNER JOIN #LastMonth lm ON uv.ReimbursementEncounterID = lm.ReimbursementEncounterID AND uv.MonthValue = lm.MonthValue) lastObserved +ON uv.ReimbursementEncounterID = lastObserved.ReimbursementEncounterID + +--Insert IDs whose payor groups are not explicitly defined in fp.ReimbursementProjectionMethod if the default projection method is annualized +IF (@UseDefault = 0) +BEGIN + INSERT INTO #UnpivotedValues (ReimbursementEncounterID, MonthValue, MonthID, PerEncounterValue) + SELECT enc.ReimbursementEncounterID, enc.MonthValue, CAST(RIGHT(enc.MonthValue,2) as INT), enc.PerEncounterValue + FROM + (SELECT ReimbursementEncounterID, BudgetConfigID, PayorGroupID, InitialProjectionNetPerEncounter01, InitialProjectionNetPerEncounter02, InitialProjectionNetPerEncounter03, InitialProjectionNetPerEncounter04, InitialProjectionNetPerEncounter05, InitialProjectionNetPerEncounter06, InitialProjectionNetPerEncounter07, InitialProjectionNetPerEncounter08, InitialProjectionNetPerEncounter09, InitialProjectionNetPerEncounter10, InitialProjectionNetPerEncounter11, InitialProjectionNetPerEncounter12 + FROM fp.FactReimbursementEncounter WHERE BudgetConfigID = @BudgetConfigID) e + UNPIVOT + (PerEncounterValue FOR MonthValue IN (InitialProjectionNetPerEncounter01, InitialProjectionNetPerEncounter02, InitialProjectionNetPerEncounter03, InitialProjectionNetPerEncounter04, InitialProjectionNetPerEncounter05, InitialProjectionNetPerEncounter06, InitialProjectionNetPerEncounter07, InitialProjectionNetPerEncounter08, InitialProjectionNetPerEncounter09, InitialProjectionNetPerEncounter10, InitialProjectionNetPerEncounter11, InitialProjectionNetPerEncounter12) ) + AS enc + LEFT JOIN fp.ReimbursementProjectionMethod pm + ON enc.PayorGroupID = pm.PayorGroupID + AND pm.BudgetConfigGUID = @BudgetConfigGUID + LEFT JOIN #UnpivotedValues uv on enc.ReimbursementEncounterID = uv.ReimbursementEncounterID + WHERE enc.BudgetConfigID = @BudgetConfigID + AND uv.ReimbursementEncounterID IS NULL --Don't want to insert duplicates from first insert + AND pm.RowID IS NULL + + INSERT INTO #LastMonth (ReimbursementEncounterID, MonthValue) + SELECT uv.ReimbursementEncounterID, MAX(uv.MonthValue) + FROM #UnpivotedValues uv + LEFT JOIN #LastMonth lm on uv.ReimbursementEncounterID = lm.ReimbursementEncounterID + WHERE PerEncounterValue > 0 AND MonthID <= @MonthsLoaded + GROUP BY uv.ReimbursementEncounterID + + INSERT INTO #IDsToUpdate (ReimbursementEncounterID, LastObservedValue) + SELECT uv.ReimbursementEncounterID, ISNULL(PerEncounterValue, 0) + FROM (SELECT DISTINCT ReimbursementEncounterID FROM #UnpivotedValues) uv + LEFT JOIN + (SELECT uv.* FROM #UnpivotedValues uv INNER JOIN #LastMonth lm ON uv.ReimbursementEncounterID = lm.ReimbursementEncounterID AND uv.MonthValue = lm.MonthValue) lastObserved + ON uv.ReimbursementEncounterID = lastObserved.ReimbursementEncounterID + LEFT JOIN #IDsToUpdate id on uv.ReimbursementEncounterID = id.ReimbursementEncounterID +END + +UPDATE re +SET + InitialProjectionNetPerEncounter02 = CASE WHEN @MonthsLoaded >= 2 THEN InitialProjectionNetPerEncounter02 ELSE LastObservedValue END, + InitialProjectionNetPerEncounter03 = CASE WHEN @MonthsLoaded >= 3 THEN InitialProjectionNetPerEncounter03 ELSE LastObservedValue END, + InitialProjectionNetPerEncounter04 = CASE WHEN @MonthsLoaded >= 4 THEN InitialProjectionNetPerEncounter04 ELSE LastObservedValue END, + InitialProjectionNetPerEncounter05 = CASE WHEN @MonthsLoaded >= 5 THEN InitialProjectionNetPerEncounter05 ELSE LastObservedValue END, + InitialProjectionNetPerEncounter06 = CASE WHEN @MonthsLoaded >= 6 THEN InitialProjectionNetPerEncounter06 ELSE LastObservedValue END, + InitialProjectionNetPerEncounter07 = CASE WHEN @MonthsLoaded >= 7 THEN InitialProjectionNetPerEncounter07 ELSE LastObservedValue END, + InitialProjectionNetPerEncounter08 = CASE WHEN @MonthsLoaded >= 8 THEN InitialProjectionNetPerEncounter08 ELSE LastObservedValue END, + InitialProjectionNetPerEncounter09 = CASE WHEN @MonthsLoaded >= 9 THEN InitialProjectionNetPerEncounter09 ELSE LastObservedValue END, + InitialProjectionNetPerEncounter10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjectionNetPerEncounter10 ELSE LastObservedValue END, + InitialProjectionNetPerEncounter11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjectionNetPerEncounter11 ELSE LastObservedValue END, + InitialProjectionNetPerEncounter12 = LastObservedValue, + InitialBudgetNetPerEncounter01 = LastObservedValue, + InitialBudgetNetPerEncounter02 = LastObservedValue, + InitialBudgetNetPerEncounter03 = LastObservedValue, + InitialBudgetNetPerEncounter04 = LastObservedValue, + InitialBudgetNetPerEncounter05 = LastObservedValue, + InitialBudgetNetPerEncounter06 = LastObservedValue, + InitialBudgetNetPerEncounter07 = LastObservedValue, + InitialBudgetNetPerEncounter08 = LastObservedValue, + InitialBudgetNetPerEncounter09 = LastObservedValue, + InitialBudgetNetPerEncounter10 = LastObservedValue, + InitialBudgetNetPerEncounter11 = LastObservedValue, + InitialBudgetNetPerEncounter12 = LastObservedValue +FROM [fp].[FactReimbursementEncounter] re INNER JOIN #IDsToUpdate i ON re.ReimbursementEncounterID = i.ReimbursementEncounterID + +UPDATE reb +SET + AdjustedNetPerEncounterValue01 = LastObservedValue, + AdjustedNetPerEncounterValue02 = LastObservedValue, + AdjustedNetPerEncounterValue03 = LastObservedValue, + AdjustedNetPerEncounterValue04 = LastObservedValue, + AdjustedNetPerEncounterValue05 = LastObservedValue, + AdjustedNetPerEncounterValue06 = LastObservedValue, + AdjustedNetPerEncounterValue07 = LastObservedValue, + AdjustedNetPerEncounterValue08 = LastObservedValue, + AdjustedNetPerEncounterValue09 = LastObservedValue, + AdjustedNetPerEncounterValue10 = LastObservedValue, + AdjustedNetPerEncounterValue11 = LastObservedValue, + AdjustedNetPerEncounterValue12 = LastObservedValue +FROM [fp].[FactReimbursementEncounter] re INNER JOIN #IDsToUpdate i ON re.ReimbursementEncounterID = i.ReimbursementEncounterID + INNER JOIN fp.FactReimbursementEncounterBudget reb on re.ReimbursementEncounterID = reb.ReimbursementEncounterID + +UPDATE rep +SET + AdjustedNetPerEncounterValue01 = InitialProjectionNetPerEncounter01, + AdjustedNetPerEncounterValue02 = CASE WHEN @MonthsLoaded >= 2 THEN InitialProjectionNetPerEncounter02 ELSE LastObservedValue END, + AdjustedNetPerEncounterValue03 = CASE WHEN @MonthsLoaded >= 3 THEN InitialProjectionNetPerEncounter03 ELSE LastObservedValue END, + AdjustedNetPerEncounterValue04 = CASE WHEN @MonthsLoaded >= 4 THEN InitialProjectionNetPerEncounter04 ELSE LastObservedValue END, + AdjustedNetPerEncounterValue05 = CASE WHEN @MonthsLoaded >= 5 THEN InitialProjectionNetPerEncounter05 ELSE LastObservedValue END, + AdjustedNetPerEncounterValue06 = CASE WHEN @MonthsLoaded >= 6 THEN InitialProjectionNetPerEncounter06 ELSE LastObservedValue END, + AdjustedNetPerEncounterValue07 = CASE WHEN @MonthsLoaded >= 7 THEN InitialProjectionNetPerEncounter07 ELSE LastObservedValue END, + AdjustedNetPerEncounterValue08 = CASE WHEN @MonthsLoaded >= 8 THEN InitialProjectionNetPerEncounter08 ELSE LastObservedValue END, + AdjustedNetPerEncounterValue09 = CASE WHEN @MonthsLoaded >= 9 THEN InitialProjectionNetPerEncounter09 ELSE LastObservedValue END, + AdjustedNetPerEncounterValue10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjectionNetPerEncounter10 ELSE LastObservedValue END, + AdjustedNetPerEncounterValue11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjectionNetPerEncounter11 ELSE LastObservedValue END, + AdjustedNetPerEncounterValue12 = LastObservedValue +FROM [fp].[FactReimbursementEncounter] re INNER JOIN #IDsToUpdate i ON re.ReimbursementEncounterID = i.ReimbursementEncounterID + INNER JOIN fp.FactReimbursementEncounterProjection rep on re.ReimbursementEncounterID = rep.ReimbursementEncounterID +END +GO + + +--------------------------------------------- + +-- fp.procReimbursementGLToGLCrosswalk +CREATE PROCEDURE [fp].[procReimbursementGLToGLCrosswalk] + @BudgetConfigID INT, + @BudgetConfigGUID UNIQUEIDENTIFIER, + @EntityConfigID INT, + @MonthsLoaded INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + + /************************************************************** + ** Change History + + ** CID Date Author WI Description + ** 1 2023-07-31 AO JAZZ-57673 Initial + *************************************************************/ + + IF OBJECT_ID('tempdb..#contractualAllowances') IS NOT NULL DROP TABLE #contractualAllowances + IF OBJECT_ID('tempdb..#tmpReimbursementGL') IS NOT NULL DROP TABLE #tmpReimbursementGL + IF OBJECT_ID('tempdb..#tmpConAllowanceCalc') IS NOT NULL DROP TABLE #tmpConAllowanceCalc + IF OBJECT_ID('tempdb..#uniquePayorGroups') IS NOT NULL DROP TABLE #uniquePayorGroups + IF OBJECT_ID('tempdb..#tempInsert') IS NOT NULL DROP TABLE #tempInsert + + CREATE TABLE #tmpReimbursementGL ( + BudgetConfigID INT, + PayorGroupID INT, + EntityID INT, + PatientClassID INT, + TargetAdjusted01 DECIMAL (19,8), + TargetAdjusted02 DECIMAL (19,8), + TargetAdjusted03 DECIMAL (19,8), + TargetAdjusted04 DECIMAL (19,8), + TargetAdjusted05 DECIMAL (19,8), + TargetAdjusted06 DECIMAL (19,8), + TargetAdjusted07 DECIMAL (19,8), + TargetAdjusted08 DECIMAL (19,8), + TargetAdjusted09 DECIMAL (19,8), + TargetAdjusted10 DECIMAL (19,8), + TargetAdjusted11 DECIMAL (19,8), + TargetAdjusted12 DECIMAL (19,8), + + BudgetAdjusted01 DECIMAL (19,8), + BudgetAdjusted02 DECIMAL (19,8), + BudgetAdjusted03 DECIMAL (19,8), + BudgetAdjusted04 DECIMAL (19,8), + BudgetAdjusted05 DECIMAL (19,8), + BudgetAdjusted06 DECIMAL (19,8), + BudgetAdjusted07 DECIMAL (19,8), + BudgetAdjusted08 DECIMAL (19,8), + BudgetAdjusted09 DECIMAL (19,8), + BudgetAdjusted10 DECIMAL (19,8), + BudgetAdjusted11 DECIMAL (19,8), + BudgetAdjusted12 DECIMAL (19,8), + + ProjectionAdjusted01 DECIMAL (19,8), + ProjectionAdjusted02 DECIMAL (19,8), + ProjectionAdjusted03 DECIMAL (19,8), + ProjectionAdjusted04 DECIMAL (19,8), + ProjectionAdjusted05 DECIMAL (19,8), + ProjectionAdjusted06 DECIMAL (19,8), + ProjectionAdjusted07 DECIMAL (19,8), + ProjectionAdjusted08 DECIMAL (19,8), + ProjectionAdjusted09 DECIMAL (19,8), + ProjectionAdjusted10 DECIMAL (19,8), + ProjectionAdjusted11 DECIMAL (19,8), + ProjectionAdjusted12 DECIMAL (19,8), + + TargetAdjustedNetReimbursement01 DECIMAL (19,8), + TargetAdjustedNetReimbursement02 DECIMAL (19,8), + TargetAdjustedNetReimbursement03 DECIMAL (19,8), + TargetAdjustedNetReimbursement04 DECIMAL (19,8), + TargetAdjustedNetReimbursement05 DECIMAL (19,8), + TargetAdjustedNetReimbursement06 DECIMAL (19,8), + TargetAdjustedNetReimbursement07 DECIMAL (19,8), + TargetAdjustedNetReimbursement08 DECIMAL (19,8), + TargetAdjustedNetReimbursement09 DECIMAL (19,8), + TargetAdjustedNetReimbursement10 DECIMAL (19,8), + TargetAdjustedNetReimbursement11 DECIMAL (19,8), + TargetAdjustedNetReimbursement12 DECIMAL (19,8), + + BudgetAdjustedNetReimbursement01 DECIMAL (19,8), + BudgetAdjustedNetReimbursement02 DECIMAL (19,8), + BudgetAdjustedNetReimbursement03 DECIMAL (19,8), + BudgetAdjustedNetReimbursement04 DECIMAL (19,8), + BudgetAdjustedNetReimbursement05 DECIMAL (19,8), + BudgetAdjustedNetReimbursement06 DECIMAL (19,8), + BudgetAdjustedNetReimbursement07 DECIMAL (19,8), + BudgetAdjustedNetReimbursement08 DECIMAL (19,8), + BudgetAdjustedNetReimbursement09 DECIMAL (19,8), + BudgetAdjustedNetReimbursement10 DECIMAL (19,8), + BudgetAdjustedNetReimbursement11 DECIMAL (19,8), + BudgetAdjustedNetReimbursement12 DECIMAL (19,8), + + ProjectionAdjustedNetReimbursement01 DECIMAL (19,8), + ProjectionAdjustedNetReimbursement02 DECIMAL (19,8), + ProjectionAdjustedNetReimbursement03 DECIMAL (19,8), + ProjectionAdjustedNetReimbursement04 DECIMAL (19,8), + ProjectionAdjustedNetReimbursement05 DECIMAL (19,8), + ProjectionAdjustedNetReimbursement06 DECIMAL (19,8), + ProjectionAdjustedNetReimbursement07 DECIMAL (19,8), + ProjectionAdjustedNetReimbursement08 DECIMAL (19,8), + ProjectionAdjustedNetReimbursement09 DECIMAL (19,8), + ProjectionAdjustedNetReimbursement10 DECIMAL (19,8), + ProjectionAdjustedNetReimbursement11 DECIMAL (19,8), + ProjectionAdjustedNetReimbursement12 DECIMAL (19,8) + ) + + CREATE TABLE #tmpConAllowanceCalc ( + BudgetConfigID INT, + PayorGroupID INT, + EntityID INT, + PatientClassID INT, + TargetConAllowance01 DECIMAL (19,8), + TargetConAllowance02 DECIMAL (19,8), + TargetConAllowance03 DECIMAL (19,8), + TargetConAllowance04 DECIMAL (19,8), + TargetConAllowance05 DECIMAL (19,8), + TargetConAllowance06 DECIMAL (19,8), + TargetConAllowance07 DECIMAL (19,8), + TargetConAllowance08 DECIMAL (19,8), + TargetConAllowance09 DECIMAL (19,8), + TargetConAllowance10 DECIMAL (19,8), + TargetConAllowance11 DECIMAL (19,8), + TargetConAllowance12 DECIMAL (19,8), + + BudgetConAllowance01 DECIMAL (19,8), + BudgetConAllowance02 DECIMAL (19,8), + BudgetConAllowance03 DECIMAL (19,8), + BudgetConAllowance04 DECIMAL (19,8), + BudgetConAllowance05 DECIMAL (19,8), + BudgetConAllowance06 DECIMAL (19,8), + BudgetConAllowance07 DECIMAL (19,8), + BudgetConAllowance08 DECIMAL (19,8), + BudgetConAllowance09 DECIMAL (19,8), + BudgetConAllowance10 DECIMAL (19,8), + BudgetConAllowance11 DECIMAL (19,8), + BudgetConAllowance12 DECIMAL (19,8), + + ProjectionConAllowance01 DECIMAL (19,8), + ProjectionConAllowance02 DECIMAL (19,8), + ProjectionConAllowance03 DECIMAL (19,8), + ProjectionConAllowance04 DECIMAL (19,8), + ProjectionConAllowance05 DECIMAL (19,8), + ProjectionConAllowance06 DECIMAL (19,8), + ProjectionConAllowance07 DECIMAL (19,8), + ProjectionConAllowance08 DECIMAL (19,8), + ProjectionConAllowance09 DECIMAL (19,8), + ProjectionConAllowance10 DECIMAL (19,8), + ProjectionConAllowance11 DECIMAL (19,8), + ProjectionConAllowance12 DECIMAL (19,8) + ) + + -------------------------------------------------------------- + --Get reimbursement contractual allowances config for given budget config + -------------------------------------------------------------- + SELECT + data.BudgetConfigGUID, + data.PayorGroupID, + data.EntityID, + data.PatientClassID, + data.DepartmentID, + data.AccountID, + sum(data.ProjectionAllocationPercent) AS ProjectionAllocationPercent, + sum(data.BudgetAllocationPercent) AS BudgetAllocationPercent + INTO #contractualAllowances + FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data + INNER JOIN fw.DimDepartment dd on data.DepartmentID = dd.DepartmentID + INNER JOIN [fp].[viewReimbursementDeductionsAccounts] da on data.AccountID = da.AccountID + WHERE + data.BudgetConfigGUID = @BudgetConfigGUID + GROUP BY + data.BudgetConfigGUID, + data.PayorGroupID, + data.EntityID, + data.PatientClassID, + data.DepartmentID, + data.AccountID + + SELECT + data.PayorGroupID, + data.EntityID, + data.PatientClassID + INTO #uniquePayorGroups + FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data + INNER JOIN fw.DimDepartment dd on data.DepartmentID = dd.DepartmentID + INNER JOIN [fp].[viewReimbursementDeductionsAccounts] da on data.AccountID = da.AccountID + WHERE + data.BudgetConfigGUID = @BudgetConfigGUID + GROUP BY + data.PayorGroupID, + data.EntityID, + data.PatientClassID + + -------------------------------------------------------------- + --Get reimbursement data using CA dimensionality to group + -------------------------------------------------------------- + INSERT INTO #tmpReimbursementGL (PayorGroupID, EntityID, PatientClassID, + TargetAdjusted01, TargetAdjusted02, TargetAdjusted03, TargetAdjusted04, TargetAdjusted05, TargetAdjusted06, + TargetAdjusted07, TargetAdjusted08, TargetAdjusted09, TargetAdjusted10, TargetAdjusted11, TargetAdjusted12, + BudgetAdjusted01, BudgetAdjusted02, BudgetAdjusted03,BudgetAdjusted04, BudgetAdjusted05, BudgetAdjusted06, + BudgetAdjusted07, BudgetAdjusted08, BudgetAdjusted09, BudgetAdjusted10, BudgetAdjusted11, BudgetAdjusted12, + ProjectionAdjusted01, ProjectionAdjusted02, ProjectionAdjusted03, ProjectionAdjusted04, ProjectionAdjusted05, ProjectionAdjusted06, + ProjectionAdjusted07, ProjectionAdjusted08, ProjectionAdjusted09, ProjectionAdjusted10, ProjectionAdjusted11, ProjectionAdjusted12, + TargetAdjustedNetReimbursement01, TargetAdjustedNetReimbursement02, TargetAdjustedNetReimbursement03, TargetAdjustedNetReimbursement04, + TargetAdjustedNetReimbursement05, TargetAdjustedNetReimbursement06, TargetAdjustedNetReimbursement07, TargetAdjustedNetReimbursement08, + TargetAdjustedNetReimbursement09, TargetAdjustedNetReimbursement10, TargetAdjustedNetReimbursement11, TargetAdjustedNetReimbursement12, + BudgetAdjustedNetReimbursement01, BudgetAdjustedNetReimbursement02, BudgetAdjustedNetReimbursement03, BudgetAdjustedNetReimbursement04, + BudgetAdjustedNetReimbursement05, BudgetAdjustedNetReimbursement06, BudgetAdjustedNetReimbursement07, BudgetAdjustedNetReimbursement08, + BudgetAdjustedNetReimbursement09, BudgetAdjustedNetReimbursement10, BudgetAdjustedNetReimbursement11, BudgetAdjustedNetReimbursement12, + ProjectionAdjustedNetReimbursement01, ProjectionAdjustedNetReimbursement02, ProjectionAdjustedNetReimbursement03, ProjectionAdjustedNetReimbursement04, + ProjectionAdjustedNetReimbursement05, ProjectionAdjustedNetReimbursement06, ProjectionAdjustedNetReimbursement07, ProjectionAdjustedNetReimbursement08, + ProjectionAdjustedNetReimbursement09, ProjectionAdjustedNetReimbursement10, ProjectionAdjustedNetReimbursement11, ProjectionAdjustedNetReimbursement12) + + SELECT + upg.PayorGroupID, + upg.EntityID, + upg.PatientClassID, + SUM(TargetAdjusted01), + SUM(TargetAdjusted02), + SUM(TargetAdjusted03), + SUM(TargetAdjusted04), + SUM(TargetAdjusted05), + SUM(TargetAdjusted06), + SUM(TargetAdjusted07), + SUM(TargetAdjusted08), + SUM(TargetAdjusted09), + SUM(TargetAdjusted10), + SUM(TargetAdjusted11), + SUM(TargetAdjusted12), + + SUM(BudgetAdjusted01), + SUM(BudgetAdjusted02), + SUM(BudgetAdjusted03), + SUM(BudgetAdjusted04), + SUM(BudgetAdjusted05), + SUM(BudgetAdjusted06), + SUM(BudgetAdjusted07), + SUM(BudgetAdjusted08), + SUM(BudgetAdjusted09), + SUM(BudgetAdjusted10), + SUM(BudgetAdjusted11), + SUM(BudgetAdjusted12), + + SUM(ProjectionAdjusted01), + SUM(ProjectionAdjusted02), + SUM(ProjectionAdjusted03), + SUM(ProjectionAdjusted04), + SUM(ProjectionAdjusted05), + SUM(ProjectionAdjusted06), + SUM(ProjectionAdjusted07), + SUM(ProjectionAdjusted08), + SUM(ProjectionAdjusted09), + SUM(ProjectionAdjusted10), + SUM(ProjectionAdjusted11), + SUM(ProjectionAdjusted12), + + SUM(TargetAdjustedNetReimbursement01), + SUM(TargetAdjustedNetReimbursement02), + SUM(TargetAdjustedNetReimbursement03), + SUM(TargetAdjustedNetReimbursement04), + SUM(TargetAdjustedNetReimbursement05), + SUM(TargetAdjustedNetReimbursement06), + SUM(TargetAdjustedNetReimbursement07), + SUM(TargetAdjustedNetReimbursement08), + SUM(TargetAdjustedNetReimbursement09), + SUM(TargetAdjustedNetReimbursement10), + SUM(TargetAdjustedNetReimbursement11), + SUM(TargetAdjustedNetReimbursement12), + + SUM(BudgetAdjustedNetReimbursement01), + SUM(BudgetAdjustedNetReimbursement02), + SUM(BudgetAdjustedNetReimbursement03), + SUM(BudgetAdjustedNetReimbursement04), + SUM(BudgetAdjustedNetReimbursement05), + SUM(BudgetAdjustedNetReimbursement06), + SUM(BudgetAdjustedNetReimbursement07), + SUM(BudgetAdjustedNetReimbursement08), + SUM(BudgetAdjustedNetReimbursement09), + SUM(BudgetAdjustedNetReimbursement10), + SUM(BudgetAdjustedNetReimbursement11), + SUM(BudgetAdjustedNetReimbursement12), + + SUM(ProjectionAdjustedNetReimbursement01), + SUM(ProjectionAdjustedNetReimbursement02), + SUM(ProjectionAdjustedNetReimbursement03), + SUM(ProjectionAdjustedNetReimbursement04), + SUM(ProjectionAdjustedNetReimbursement05), + SUM(ProjectionAdjustedNetReimbursement06), + SUM(ProjectionAdjustedNetReimbursement07), + SUM(ProjectionAdjustedNetReimbursement08), + SUM(ProjectionAdjustedNetReimbursement09), + SUM(ProjectionAdjustedNetReimbursement10), + SUM(ProjectionAdjustedNetReimbursement11), + SUM(ProjectionAdjustedNetReimbursement12) + FROM fp.ReimbursementGeneralLedger rgl + INNER JOIN #uniquePayorGroups upg + ON rgl.PayorGroupID = upg.PayorGroupID + AND rgl.EntityID = upg.EntityID + AND rgl.PatientClassID = upg.PatientClassID + WHERE + rgl.BudgetConfigID = @BudgetConfigID + AND rgl.EntityGroupConfigID = @EntityConfigID + GROUP BY + upg.PayorGroupID, + upg.EntityID, + upg.PatientClassID + + -------------------------------------------------------------- + --Do allocation calculation + --DeductionsXX = RevenueXX - NetReimbursementXX + -------------------------------------------------------------- + INSERT INTO #tmpConAllowanceCalc(BudgetConfigID, PayorGroupID, EntityID, PatientClassID, + TargetConAllowance01, TargetConAllowance02, TargetConAllowance03, TargetConAllowance04, + TargetConAllowance05, TargetConAllowance06, TargetConAllowance07, TargetConAllowance08, + TargetConAllowance09, TargetConAllowance10, TargetConAllowance11, TargetConAllowance12, + BudgetConAllowance01, BudgetConAllowance02, BudgetConAllowance03, BudgetConAllowance04, + BudgetConAllowance05, BudgetConAllowance06, BudgetConAllowance07, BudgetConAllowance08, + BudgetConAllowance09, BudgetConAllowance10, BudgetConAllowance11, BudgetConAllowance12, + ProjectionConAllowance01, ProjectionConAllowance02, ProjectionConAllowance03, ProjectionConAllowance04, + ProjectionConAllowance05, ProjectionConAllowance06, ProjectionConAllowance07, ProjectionConAllowance08, + ProjectionConAllowance09, ProjectionConAllowance10, ProjectionConAllowance11, ProjectionConAllowance12) + SELECT + tr.BudgetConfigID, + tr.PayorGroupID, + tr.EntityID, + tr.PatientClassID, + ISNULL(tr.TargetAdjusted01,0) - ISNULL(tr.TargetAdjustedNetReimbursement01,0) AS TargetConAllowance01, + ISNULL(tr.TargetAdjusted02,0) - ISNULL(tr.TargetAdjustedNetReimbursement02,0) AS TargetConAllowance02, + ISNULL(tr.TargetAdjusted03,0) - ISNULL(tr.TargetAdjustedNetReimbursement03,0) AS TargetConAllowance03, + ISNULL(tr.TargetAdjusted04,0) - ISNULL(tr.TargetAdjustedNetReimbursement04,0) AS TargetConAllowance04, + ISNULL(tr.TargetAdjusted05,0) - ISNULL(tr.TargetAdjustedNetReimbursement05,0) AS TargetConAllowance05, + ISNULL(tr.TargetAdjusted06,0) - ISNULL(tr.TargetAdjustedNetReimbursement06,0) AS TargetConAllowance06, + ISNULL(tr.TargetAdjusted07,0) - ISNULL(tr.TargetAdjustedNetReimbursement07,0) AS TargetConAllowance07, + ISNULL(tr.TargetAdjusted08,0) - ISNULL(tr.TargetAdjustedNetReimbursement08,0) AS TargetConAllowance08, + ISNULL(tr.TargetAdjusted09,0) - ISNULL(tr.TargetAdjustedNetReimbursement09,0) AS TargetConAllowance09, + ISNULL(tr.TargetAdjusted10,0) - ISNULL(tr.TargetAdjustedNetReimbursement10,0) AS TargetConAllowance10, + ISNULL(tr.TargetAdjusted11,0) - ISNULL(tr.TargetAdjustedNetReimbursement11,0) AS TargetConAllowance11, + ISNULL(tr.TargetAdjusted12,0) - ISNULL(tr.TargetAdjustedNetReimbursement12,0) AS TargetConAllowance12, + + ISNULL(tr.BudgetAdjusted01,0) - ISNULL(tr.BudgetAdjustedNetReimbursement01,0) AS BudgetConAllowance01, + ISNULL(tr.BudgetAdjusted02,0) - ISNULL(tr.BudgetAdjustedNetReimbursement02,0) AS BudgetConAllowance02, + ISNULL(tr.BudgetAdjusted03,0) - ISNULL(tr.BudgetAdjustedNetReimbursement03,0) AS BudgetConAllowance03, + ISNULL(tr.BudgetAdjusted04,0) - ISNULL(tr.BudgetAdjustedNetReimbursement04,0) AS BudgetConAllowance04, + ISNULL(tr.BudgetAdjusted05,0) - ISNULL(tr.BudgetAdjustedNetReimbursement05,0) AS BudgetConAllowance05, + ISNULL(tr.BudgetAdjusted06,0) - ISNULL(tr.BudgetAdjustedNetReimbursement06,0) AS BudgetConAllowance06, + ISNULL(tr.BudgetAdjusted07,0) - ISNULL(tr.BudgetAdjustedNetReimbursement07,0) AS BudgetConAllowance07, + ISNULL(tr.BudgetAdjusted08,0) - ISNULL(tr.BudgetAdjustedNetReimbursement08,0) AS BudgetConAllowance08, + ISNULL(tr.BudgetAdjusted09,0) - ISNULL(tr.BudgetAdjustedNetReimbursement09,0) AS BudgetConAllowance09, + ISNULL(tr.BudgetAdjusted10,0) - ISNULL(tr.BudgetAdjustedNetReimbursement10,0) AS BudgetConAllowance10, + ISNULL(tr.BudgetAdjusted11,0) - ISNULL(tr.BudgetAdjustedNetReimbursement11,0) AS BudgetConAllowance11, + ISNULL(tr.BudgetAdjusted12,0) - ISNULL(tr.BudgetAdjustedNetReimbursement12,0) AS BudgetConAllowance12, + + ISNULL(tr.ProjectionAdjusted01,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement01,0) AS ProjectionConAllowance01, + ISNULL(tr.ProjectionAdjusted02,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement02,0) AS ProjectionConAllowance02, + ISNULL(tr.ProjectionAdjusted03,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement03,0) AS ProjectionConAllowance03, + ISNULL(tr.ProjectionAdjusted04,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement04,0) AS ProjectionConAllowance04, + ISNULL(tr.ProjectionAdjusted05,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement05,0) AS ProjectionConAllowance05, + ISNULL(tr.ProjectionAdjusted06,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement06,0) AS ProjectionConAllowance06, + ISNULL(tr.ProjectionAdjusted07,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement07,0) AS ProjectionConAllowance07, + ISNULL(tr.ProjectionAdjusted08,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement08,0) AS ProjectionConAllowance08, + ISNULL(tr.ProjectionAdjusted09,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement09,0) AS ProjectionConAllowance09, + ISNULL(tr.ProjectionAdjusted10,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement10,0) AS ProjectionConAllowance10, + ISNULL(tr.ProjectionAdjusted11,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement11,0) AS ProjectionConAllowance11, + ISNULL(tr.ProjectionAdjusted12,0) - ISNULL(tr.ProjectionAdjustedNetReimbursement12,0) AS ProjectionConAllowance12 + FROM #tmpReimbursementGL tr + + -------------------------------------------------------------- + --Insert into temp table + --Using this intermediary step to sum up unique PG/E/PC's that flex to the same department/account in GL + -------------------------------------------------------------- + SELECT + ca.BudgetAllocationPercent, + ca.ProjectionAllocationPercent, + gl.DepartmentID, + gl.AccountID, + gl.VariabilityID, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance01 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted01 END) AS TargetAllocatedAmount01, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance02 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted02 END) AS TargetAllocatedAmount02, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance03 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted03 END) AS TargetAllocatedAmount03, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance04 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted04 END) AS TargetAllocatedAmount04, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance05 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted05 END) AS TargetAllocatedAmount05, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance06 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted06 END) AS TargetAllocatedAmount06, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance07 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted07 END) AS TargetAllocatedAmount07, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance08 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted08 END) AS TargetAllocatedAmount08, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance09 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted09 END) AS TargetAllocatedAmount09, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance10 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted10 END) AS TargetAllocatedAmount10, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance11 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted11 END) AS TargetAllocatedAmount11, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.TargetConAllowance12 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted12 END) AS TargetAllocatedAmount12, + + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance01 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted01 END) AS BudgetAllocatedAmount01, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance02 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted02 END) AS BudgetAllocatedAmount02, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance03 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted03 END) AS BudgetAllocatedAmount03, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance04 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted04 END) AS BudgetAllocatedAmount04, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance05 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted05 END) AS BudgetAllocatedAmount05, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance06 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted06 END) AS BudgetAllocatedAmount06, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance07 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted07 END) AS BudgetAllocatedAmount07, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance08 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted08 END) AS BudgetAllocatedAmount08, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance09 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted09 END) AS BudgetAllocatedAmount09, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance10 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted10 END) AS BudgetAllocatedAmount10, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance11 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted11 END) AS BudgetAllocatedAmount11, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance12 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted12 END) AS BudgetAllocatedAmount12, + + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 1 THEN gl.ProjectionAdjusted01 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 1 THEN gl.ProjectionAdjusted01 ELSE calc.ProjectionConAllowance01 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount01, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 2 THEN gl.ProjectionAdjusted02 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 2 THEN gl.ProjectionAdjusted02 ELSE calc.ProjectionConAllowance02 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount02, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 3 THEN gl.ProjectionAdjusted03 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 3 THEN gl.ProjectionAdjusted03 ELSE calc.ProjectionConAllowance03 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount03, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 4 THEN gl.ProjectionAdjusted04 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 4 THEN gl.ProjectionAdjusted04 ELSE calc.ProjectionConAllowance04 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount04, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 5 THEN gl.ProjectionAdjusted05 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 5 THEN gl.ProjectionAdjusted05 ELSE calc.ProjectionConAllowance05 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount05, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 6 THEN gl.ProjectionAdjusted06 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 6 THEN gl.ProjectionAdjusted06 ELSE calc.ProjectionConAllowance06 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount06, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 7 THEN gl.ProjectionAdjusted07 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 7 THEN gl.ProjectionAdjusted07 ELSE calc.ProjectionConAllowance07 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount07, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 8 THEN gl.ProjectionAdjusted08 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 8 THEN gl.ProjectionAdjusted08 ELSE calc.ProjectionConAllowance08 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount08, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 9 THEN gl.ProjectionAdjusted09 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 9 THEN gl.ProjectionAdjusted09 ELSE calc.ProjectionConAllowance09 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount09, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 10 THEN gl.ProjectionAdjusted10 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 10 THEN gl.ProjectionAdjusted10 ELSE calc.ProjectionConAllowance10 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount10, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 11 THEN gl.ProjectionAdjusted11 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 11 THEN gl.ProjectionAdjusted11 ELSE calc.ProjectionConAllowance11 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount11, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 12 THEN gl.ProjectionAdjusted12 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 12 THEN gl.ProjectionAdjusted12 ELSE calc.ProjectionConAllowance12 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount12 + INTO #tempInsert + FROM fp.GeneralLedger gl + INNER JOIN #contractualAllowances ca + ON ca.DepartmentID = gl.DepartmentID + AND ca.AccountID = gl.AccountID + INNER JOIN #tmpConAllowanceCalc calc + ON ca.PayorGroupID = calc.PayorGroupID + AND ca.EntityID = calc.EntityID + AND ca.PatientClassID = calc.PatientClassID + WHERE gl.APEModelSectionID = 4 + AND gl.BudgetConfigID = @BudgetConfigID + AND gl.EntityGroupConfigID = @EntityConfigID + GROUP BY + gl.DepartmentID, + gl.AccountID, + gl.VariabilityID, + ca.BudgetAllocationPercent, + ca.ProjectionAllocationPercent + + -------------------------------------------------------------- + --Update + -------------------------------------------------------------- + IF (@IsDebug = 1) + BEGIN + SELECT * FROM #tempInsert + END ELSE BEGIN + + -------------------------------------------------------------- + --Update Target/Budget where BudgetAllocationPercent <> 0 + -------------------------------------------------------------- + UPDATE gl + SET + TargetLockFlag = 1, + TargetLockType = 3, + TargetAdjusted01 = ti.TargetAllocatedAmount01, + TargetAdjusted02 = ti.TargetAllocatedAmount02, + TargetAdjusted03 = ti.TargetAllocatedAmount03, + TargetAdjusted04 = ti.TargetAllocatedAmount04, + TargetAdjusted05 = ti.TargetAllocatedAmount05, + TargetAdjusted06 = ti.TargetAllocatedAmount06, + TargetAdjusted07 = ti.TargetAllocatedAmount07, + TargetAdjusted08 = ti.TargetAllocatedAmount08, + TargetAdjusted09 = ti.TargetAllocatedAmount09, + TargetAdjusted10 = ti.TargetAllocatedAmount10, + TargetAdjusted11 = ti.TargetAllocatedAmount11, + TargetAdjusted12 = ti.TargetAllocatedAmount12, + + BudgetLockFlag = 1, + BudgetLockType = 3, + BudgetAdjusted01 = ti.BudgetAllocatedAmount01, + BudgetAdjusted02 = ti.BudgetAllocatedAmount02, + BudgetAdjusted03 = ti.BudgetAllocatedAmount03, + BudgetAdjusted04 = ti.BudgetAllocatedAmount04, + BudgetAdjusted05 = ti.BudgetAllocatedAmount05, + BudgetAdjusted06 = ti.BudgetAllocatedAmount06, + BudgetAdjusted07 = ti.BudgetAllocatedAmount07, + BudgetAdjusted08 = ti.BudgetAllocatedAmount08, + BudgetAdjusted09 = ti.BudgetAllocatedAmount09, + BudgetAdjusted10 = ti.BudgetAllocatedAmount10, + BudgetAdjusted11 = ti.BudgetAllocatedAmount11, + BudgetAdjusted12 = ti.BudgetAllocatedAmount12 + FROM fp.GeneralLedger gl + INNER JOIN #tempInsert ti + ON gl.DepartmentID = ti.DepartmentID + AND gl.AccountID = ti.AccountID + AND gl.VariabilityID = ti.VariabilityID + WHERE ti.BudgetAllocationPercent <> 0 + AND gl.APEModelSectionID = 4 + AND gl.BudgetConfigID = @BudgetConfigID + AND gl.EntityGroupConfigID = @EntityConfigID + + -------------------------------------------------------------- + --Update Projection where ProjectionAllocationPercent <> 0 + -------------------------------------------------------------- + UPDATE gl + SET + ProjectionLockFlag = 1, + ProjectionLockType = 3, + ProjectionAdjusted01 = ti.ProjectionAllocatedAmount01, + ProjectionAdjusted02 = ti.ProjectionAllocatedAmount02, + ProjectionAdjusted03 = ti.ProjectionAllocatedAmount03, + ProjectionAdjusted04 = ti.ProjectionAllocatedAmount04, + ProjectionAdjusted05 = ti.ProjectionAllocatedAmount05, + ProjectionAdjusted06 = ti.ProjectionAllocatedAmount06, + ProjectionAdjusted07 = ti.ProjectionAllocatedAmount07, + ProjectionAdjusted08 = ti.ProjectionAllocatedAmount08, + ProjectionAdjusted09 = ti.ProjectionAllocatedAmount09, + ProjectionAdjusted10 = ti.ProjectionAllocatedAmount10, + ProjectionAdjusted11 = ti.ProjectionAllocatedAmount11, + ProjectionAdjusted12 = ti.ProjectionAllocatedAmount12 + FROM fp.GeneralLedger gl + INNER JOIN #tempInsert ti + ON gl.DepartmentID = ti.DepartmentID + AND gl.AccountID = ti.AccountID + AND gl.VariabilityID = ti.VariabilityID + WHERE ti.ProjectionAllocationPercent <> 0 + AND gl.APEModelSectionID = 4 + AND gl.BudgetConfigID = @BudgetConfigID + AND gl.EntityGroupConfigID = @EntityConfigID + END +END +GO + + +--------------------------------------------- + +-- fp.procReimbursementGLToGLCrosswalk_Initial +CREATE PROCEDURE [fp].[procReimbursementGLToGLCrosswalk_Initial] + @BudgetConfigID INT, + @BudgetConfigGUID UNIQUEIDENTIFIER, + @EntityConfigID INT, + @MonthsLoaded INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 + +AS +BEGIN + + /************************************************************** + ** Change History + ** CID Date Author WI Description + ** 1 2023-08-07 AO JAZZ-57673 Initial + *************************************************************/ + + IF OBJECT_ID('tempdb..#contractualAllowances') IS NOT NULL DROP TABLE #contractualAllowances + IF OBJECT_ID('tempdb..#tmpReimbursementGL') IS NOT NULL DROP TABLE #tmpReimbursementGL + IF OBJECT_ID('tempdb..#tmpConAllowanceCalc') IS NOT NULL DROP TABLE #tmpConAllowanceCalc + IF OBJECT_ID('tempdb..#uniquePayorGroups') IS NOT NULL DROP TABLE #uniquePayorGroups + IF OBJECT_ID('tempdb..#tempInsert') IS NOT NULL DROP TABLE #tempInsert + + CREATE TABLE #tmpReimbursementGL ( + BudgetConfigID INT, + PayorGroupID INT, + EntityID INT, + PatientClassID INT, + + InitialBudget01 DECIMAL (19,8), + InitialBudget02 DECIMAL (19,8), + InitialBudget03 DECIMAL (19,8), + InitialBudget04 DECIMAL (19,8), + InitialBudget05 DECIMAL (19,8), + InitialBudget06 DECIMAL (19,8), + InitialBudget07 DECIMAL (19,8), + InitialBudget08 DECIMAL (19,8), + InitialBudget09 DECIMAL (19,8), + InitialBudget10 DECIMAL (19,8), + InitialBudget11 DECIMAL (19,8), + InitialBudget12 DECIMAL (19,8), + + InitialProjection01 DECIMAL (19,8), + InitialProjection02 DECIMAL (19,8), + InitialProjection03 DECIMAL (19,8), + InitialProjection04 DECIMAL (19,8), + InitialProjection05 DECIMAL (19,8), + InitialProjection06 DECIMAL (19,8), + InitialProjection07 DECIMAL (19,8), + InitialProjection08 DECIMAL (19,8), + InitialProjection09 DECIMAL (19,8), + InitialProjection10 DECIMAL (19,8), + InitialProjection11 DECIMAL (19,8), + InitialProjection12 DECIMAL (19,8), + + InitialBudgetNetReimbursement01 DECIMAL (19,8), + InitialBudgetNetReimbursement02 DECIMAL (19,8), + InitialBudgetNetReimbursement03 DECIMAL (19,8), + InitialBudgetNetReimbursement04 DECIMAL (19,8), + InitialBudgetNetReimbursement05 DECIMAL (19,8), + InitialBudgetNetReimbursement06 DECIMAL (19,8), + InitialBudgetNetReimbursement07 DECIMAL (19,8), + InitialBudgetNetReimbursement08 DECIMAL (19,8), + InitialBudgetNetReimbursement09 DECIMAL (19,8), + InitialBudgetNetReimbursement10 DECIMAL (19,8), + InitialBudgetNetReimbursement11 DECIMAL (19,8), + InitialBudgetNetReimbursement12 DECIMAL (19,8), + + InitialProjectionNetReimbursement01 DECIMAL (19,8), + InitialProjectionNetReimbursement02 DECIMAL (19,8), + InitialProjectionNetReimbursement03 DECIMAL (19,8), + InitialProjectionNetReimbursement04 DECIMAL (19,8), + InitialProjectionNetReimbursement05 DECIMAL (19,8), + InitialProjectionNetReimbursement06 DECIMAL (19,8), + InitialProjectionNetReimbursement07 DECIMAL (19,8), + InitialProjectionNetReimbursement08 DECIMAL (19,8), + InitialProjectionNetReimbursement09 DECIMAL (19,8), + InitialProjectionNetReimbursement10 DECIMAL (19,8), + InitialProjectionNetReimbursement11 DECIMAL (19,8), + InitialProjectionNetReimbursement12 DECIMAL (19,8) + ) + + CREATE TABLE #tmpConAllowanceCalc ( + PayorGroupID INT, + EntityID INT, + PatientClassID INT, + BudgetConAllowance01 DECIMAL (19,8), + BudgetConAllowance02 DECIMAL (19,8), + BudgetConAllowance03 DECIMAL (19,8), + BudgetConAllowance04 DECIMAL (19,8), + BudgetConAllowance05 DECIMAL (19,8), + BudgetConAllowance06 DECIMAL (19,8), + BudgetConAllowance07 DECIMAL (19,8), + BudgetConAllowance08 DECIMAL (19,8), + BudgetConAllowance09 DECIMAL (19,8), + BudgetConAllowance10 DECIMAL (19,8), + BudgetConAllowance11 DECIMAL (19,8), + BudgetConAllowance12 DECIMAL (19,8), + + ProjectionConAllowance01 DECIMAL (19,8), + ProjectionConAllowance02 DECIMAL (19,8), + ProjectionConAllowance03 DECIMAL (19,8), + ProjectionConAllowance04 DECIMAL (19,8), + ProjectionConAllowance05 DECIMAL (19,8), + ProjectionConAllowance06 DECIMAL (19,8), + ProjectionConAllowance07 DECIMAL (19,8), + ProjectionConAllowance08 DECIMAL (19,8), + ProjectionConAllowance09 DECIMAL (19,8), + ProjectionConAllowance10 DECIMAL (19,8), + ProjectionConAllowance11 DECIMAL (19,8), + ProjectionConAllowance12 DECIMAL (19,8) + ) + + -------------------------------------------------------------- + --Get reimbursement contractual allowances config for given budget config + -------------------------------------------------------------- + SELECT + data.BudgetConfigGUID, + data.PayorGroupID, + data.EntityID, + data.PatientClassID, + data.DepartmentID, + data.AccountID, + sum(data.ProjectionAllocationPercent) AS ProjectionAllocationPercent, + sum(data.BudgetAllocationPercent) AS BudgetAllocationPercent + INTO #contractualAllowances + FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data + INNER JOIN fw.DimDepartment dd on data.DepartmentID = dd.DepartmentID + INNER JOIN [fp].[viewReimbursementDeductionsAccounts] da on data.AccountID = da.AccountID + WHERE + data.BudgetConfigGUID = @BudgetConfigGUID + GROUP BY + data.BudgetConfigGUID, + data.PayorGroupID, + data.EntityID, + data.PatientClassID, + data.DepartmentID, + data.AccountID + + SELECT + data.PayorGroupID, + data.EntityID, + data.PatientClassID + INTO #uniquePayorGroups + FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data + INNER JOIN fw.DimDepartment dd on data.DepartmentID = dd.DepartmentID + INNER JOIN [fp].[viewReimbursementDeductionsAccounts] da on data.AccountID = da.AccountID + WHERE + data.BudgetConfigGUID = @BudgetConfigGUID + GROUP BY + data.PayorGroupID, + data.EntityID, + data.PatientClassID + + -------------------------------------------------------------- + --Get reimbursement charge data using CA dimensionality to group + -------------------------------------------------------------- + INSERT INTO #tmpReimbursementGL (PayorGroupID, EntityID, PatientClassID, + InitialBudget01, InitialBudget02, InitialBudget03,InitialBudget04, InitialBudget05, InitialBudget06, + InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, + InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, + InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12, + InitialBudgetNetReimbursement01, InitialBudgetNetReimbursement02, InitialBudgetNetReimbursement03, InitialBudgetNetReimbursement04, + InitialBudgetNetReimbursement05, InitialBudgetNetReimbursement06, InitialBudgetNetReimbursement07, InitialBudgetNetReimbursement08, + InitialBudgetNetReimbursement09, InitialBudgetNetReimbursement10, InitialBudgetNetReimbursement11, InitialBudgetNetReimbursement12, + InitialProjectionNetReimbursement01, InitialProjectionNetReimbursement02, InitialProjectionNetReimbursement03, InitialProjectionNetReimbursement04, + InitialProjectionNetReimbursement05, InitialProjectionNetReimbursement06, InitialProjectionNetReimbursement07, InitialProjectionNetReimbursement08, + InitialProjectionNetReimbursement09, InitialProjectionNetReimbursement10, InitialProjectionNetReimbursement11, InitialProjectionNetReimbursement12) + + SELECT + upg.PayorGroupID, + upg.EntityID, + upg.PatientClassID, + + SUM(InitialBudget01), + SUM(InitialBudget02), + SUM(InitialBudget03), + SUM(InitialBudget04), + SUM(InitialBudget05), + SUM(InitialBudget06), + SUM(InitialBudget07), + SUM(InitialBudget08), + SUM(InitialBudget09), + SUM(InitialBudget10), + SUM(InitialBudget11), + SUM(InitialBudget12), + + SUM(InitialProjection01), + SUM(InitialProjection02), + SUM(InitialProjection03), + SUM(InitialProjection04), + SUM(InitialProjection05), + SUM(InitialProjection06), + SUM(InitialProjection07), + SUM(InitialProjection08), + SUM(InitialProjection09), + SUM(InitialProjection10), + SUM(InitialProjection11), + SUM(InitialProjection12), + + SUM(InitialBudgetNetReimbursement01), + SUM(InitialBudgetNetReimbursement02), + SUM(InitialBudgetNetReimbursement03), + SUM(InitialBudgetNetReimbursement04), + SUM(InitialBudgetNetReimbursement05), + SUM(InitialBudgetNetReimbursement06), + SUM(InitialBudgetNetReimbursement07), + SUM(InitialBudgetNetReimbursement08), + SUM(InitialBudgetNetReimbursement09), + SUM(InitialBudgetNetReimbursement10), + SUM(InitialBudgetNetReimbursement11), + SUM(InitialBudgetNetReimbursement12), + + SUM(InitialProjectionNetReimbursement01), + SUM(InitialProjectionNetReimbursement02), + SUM(InitialProjectionNetReimbursement03), + SUM(InitialProjectionNetReimbursement04), + SUM(InitialProjectionNetReimbursement05), + SUM(InitialProjectionNetReimbursement06), + SUM(InitialProjectionNetReimbursement07), + SUM(InitialProjectionNetReimbursement08), + SUM(InitialProjectionNetReimbursement09), + SUM(InitialProjectionNetReimbursement10), + SUM(InitialProjectionNetReimbursement11), + SUM(InitialProjectionNetReimbursement12) + FROM fp.ReimbursementGeneralLedger rgl + INNER JOIN #uniquePayorGroups upg + ON rgl.PayorGroupID = upg.PayorGroupID + AND rgl.EntityID = upg.EntityID + AND rgl.PatientClassID = upg.PatientClassID + WHERE rgl.BudgetConfigID = @BudgetConfigID + AND rgl.EntityGroupConfigID = @EntityConfigID + GROUP BY + upg.PayorGroupID, + upg.EntityID, + upg.PatientClassID + + -------------------------------------------------------------- + --Do allocation calculation + --DeductionsXX = RevenueXX - NetReimbursementXX + -------------------------------------------------------------- + INSERT INTO #tmpConAllowanceCalc(PayorGroupID, EntityID, PatientClassID, + BudgetConAllowance01, BudgetConAllowance02, BudgetConAllowance03, BudgetConAllowance04, + BudgetConAllowance05, BudgetConAllowance06, BudgetConAllowance07, BudgetConAllowance08, + BudgetConAllowance09, BudgetConAllowance10, BudgetConAllowance11, BudgetConAllowance12, + ProjectionConAllowance01, ProjectionConAllowance02, ProjectionConAllowance03, ProjectionConAllowance04, + ProjectionConAllowance05, ProjectionConAllowance06, ProjectionConAllowance07, ProjectionConAllowance08, + ProjectionConAllowance09, ProjectionConAllowance10, ProjectionConAllowance11, ProjectionConAllowance12) + SELECT + tr.PayorGroupID, + tr.EntityID, + tr.PatientClassID, + + ISNULL(tr.InitialBudget01,0) - ISNULL(tr.InitialBudgetNetReimbursement01,0) AS BudgetConAllowance01, + ISNULL(tr.InitialBudget02,0) - ISNULL(tr.InitialBudgetNetReimbursement02,0) AS BudgetConAllowance02, + ISNULL(tr.InitialBudget03,0) - ISNULL(tr.InitialBudgetNetReimbursement03,0) AS BudgetConAllowance03, + ISNULL(tr.InitialBudget04,0) - ISNULL(tr.InitialBudgetNetReimbursement04,0) AS BudgetConAllowance04, + ISNULL(tr.InitialBudget05,0) - ISNULL(tr.InitialBudgetNetReimbursement05,0) AS BudgetConAllowance05, + ISNULL(tr.InitialBudget06,0) - ISNULL(tr.InitialBudgetNetReimbursement06,0) AS BudgetConAllowance06, + ISNULL(tr.InitialBudget07,0) - ISNULL(tr.InitialBudgetNetReimbursement07,0) AS BudgetConAllowance07, + ISNULL(tr.InitialBudget08,0) - ISNULL(tr.InitialBudgetNetReimbursement08,0) AS BudgetConAllowance08, + ISNULL(tr.InitialBudget09,0) - ISNULL(tr.InitialBudgetNetReimbursement09,0) AS BudgetConAllowance09, + ISNULL(tr.InitialBudget10,0) - ISNULL(tr.InitialBudgetNetReimbursement10,0) AS BudgetConAllowance10, + ISNULL(tr.InitialBudget11,0) - ISNULL(tr.InitialBudgetNetReimbursement11,0) AS BudgetConAllowance11, + ISNULL(tr.InitialBudget12,0) - ISNULL(tr.InitialBudgetNetReimbursement12,0) AS BudgetConAllowance12, + + ISNULL(tr.InitialProjection01,0) - ISNULL(tr.InitialProjectionNetReimbursement01,0) AS ProjectionConAllowance01, + ISNULL(tr.InitialProjection02,0) - ISNULL(tr.InitialProjectionNetReimbursement02,0) AS ProjectionConAllowance02, + ISNULL(tr.InitialProjection03,0) - ISNULL(tr.InitialProjectionNetReimbursement03,0) AS ProjectionConAllowance03, + ISNULL(tr.InitialProjection04,0) - ISNULL(tr.InitialProjectionNetReimbursement04,0) AS ProjectionConAllowance04, + ISNULL(tr.InitialProjection05,0) - ISNULL(tr.InitialProjectionNetReimbursement05,0) AS ProjectionConAllowance05, + ISNULL(tr.InitialProjection06,0) - ISNULL(tr.InitialProjectionNetReimbursement06,0) AS ProjectionConAllowance06, + ISNULL(tr.InitialProjection07,0) - ISNULL(tr.InitialProjectionNetReimbursement07,0) AS ProjectionConAllowance07, + ISNULL(tr.InitialProjection08,0) - ISNULL(tr.InitialProjectionNetReimbursement08,0) AS ProjectionConAllowance08, + ISNULL(tr.InitialProjection09,0) - ISNULL(tr.InitialProjectionNetReimbursement09,0) AS ProjectionConAllowance09, + ISNULL(tr.InitialProjection10,0) - ISNULL(tr.InitialProjectionNetReimbursement10,0) AS ProjectionConAllowance10, + ISNULL(tr.InitialProjection11,0) - ISNULL(tr.InitialProjectionNetReimbursement11,0) AS ProjectionConAllowance11, + ISNULL(tr.InitialProjection12,0) - ISNULL(tr.InitialProjectionNetReimbursement12,0) AS ProjectionConAllowance12 + FROM #tmpReimbursementGL tr + + -------------------------------------------------------------- + --Insert into temp table + --Using this intermediary step to sum up unique PG/E/PC's that flex to the same department/account in GL + -------------------------------------------------------------- + SELECT + ca.BudgetAllocationPercent, + ca.ProjectionAllocationPercent, + gl.DepartmentID, + gl.AccountID, + gl.VariabilityID, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance01 * ca.BudgetAllocationPercent ELSE gl.InitialBudget01 END) AS BudgetAllocatedAmount01, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance02 * ca.BudgetAllocationPercent ELSE gl.InitialBudget02 END) AS BudgetAllocatedAmount02, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance03 * ca.BudgetAllocationPercent ELSE gl.InitialBudget03 END) AS BudgetAllocatedAmount03, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance04 * ca.BudgetAllocationPercent ELSE gl.InitialBudget04 END) AS BudgetAllocatedAmount04, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance05 * ca.BudgetAllocationPercent ELSE gl.InitialBudget05 END) AS BudgetAllocatedAmount05, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance06 * ca.BudgetAllocationPercent ELSE gl.InitialBudget06 END) AS BudgetAllocatedAmount06, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance07 * ca.BudgetAllocationPercent ELSE gl.InitialBudget07 END) AS BudgetAllocatedAmount07, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance08 * ca.BudgetAllocationPercent ELSE gl.InitialBudget08 END) AS BudgetAllocatedAmount08, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance09 * ca.BudgetAllocationPercent ELSE gl.InitialBudget09 END) AS BudgetAllocatedAmount09, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance10 * ca.BudgetAllocationPercent ELSE gl.InitialBudget10 END) AS BudgetAllocatedAmount10, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance11 * ca.BudgetAllocationPercent ELSE gl.InitialBudget11 END) AS BudgetAllocatedAmount11, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance12 * ca.BudgetAllocationPercent ELSE gl.InitialBudget12 END) AS BudgetAllocatedAmount12, + + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 1 THEN gl.InitialProjection01 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 1 THEN gl.InitialProjection01 ELSE calc.ProjectionConAllowance01 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount01, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 2 THEN gl.InitialProjection02 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 2 THEN gl.InitialProjection02 ELSE calc.ProjectionConAllowance02 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount02, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 3 THEN gl.InitialProjection03 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 3 THEN gl.InitialProjection03 ELSE calc.ProjectionConAllowance03 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount03, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 4 THEN gl.InitialProjection04 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 4 THEN gl.InitialProjection04 ELSE calc.ProjectionConAllowance04 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount04, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 5 THEN gl.InitialProjection05 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 5 THEN gl.InitialProjection05 ELSE calc.ProjectionConAllowance05 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount05, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 6 THEN gl.InitialProjection06 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 6 THEN gl.InitialProjection06 ELSE calc.ProjectionConAllowance06 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount06, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 7 THEN gl.InitialProjection07 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 7 THEN gl.InitialProjection07 ELSE calc.ProjectionConAllowance07 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount07, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 8 THEN gl.InitialProjection08 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 8 THEN gl.InitialProjection08 ELSE calc.ProjectionConAllowance08 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount08, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 9 THEN gl.InitialProjection09 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 9 THEN gl.InitialProjection09 ELSE calc.ProjectionConAllowance09 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount09, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 10 THEN gl.InitialProjection10 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 10 THEN gl.InitialProjection10 ELSE calc.ProjectionConAllowance10 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount10, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 11 THEN gl.InitialProjection11 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 11 THEN gl.InitialProjection11 ELSE calc.ProjectionConAllowance11 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount11, + SUM(CASE WHEN gl.VariabilityID = 1 THEN CASE WHEN @MonthsLoaded >= 12 THEN gl.InitialProjection12 ELSE 0 END + WHEN gl.VariabilityID = 2 THEN CASE WHEN @MonthsLoaded >= 12 THEN gl.InitialProjection12 ELSE calc.ProjectionConAllowance12 * ca.ProjectionAllocationPercent END END) AS ProjectionAllocatedAmount12 + INTO #tempInsert + FROM fp.GeneralLedger gl + INNER JOIN #contractualAllowances ca + ON ca.DepartmentID = gl.DepartmentID + AND ca.AccountID = gl.AccountID + INNER JOIN #tmpConAllowanceCalc calc + ON ca.PayorGroupID = calc.PayorGroupID + AND ca.EntityID = calc.EntityID + AND ca.PatientClassID = calc.PatientClassID + WHERE gl.APEModelSectionID = 4 + AND gl.BudgetConfigID = @BudgetConfigID + AND gl.EntityGroupConfigID = @EntityConfigID + GROUP BY + gl.DepartmentID, + gl.AccountID, + gl.VariabilityID, + ca.BudgetAllocationPercent, + ca.ProjectionAllocationPercent + + + -------------------------------------------------------------- + --Update initials + -------------------------------------------------------------- + IF (@IsDebug = 1) + BEGIN + SELECT * FROM #tempInsert + END ELSE BEGIN + + -------------------------------------------------------------- + --Update Budget where BudgetAllocationPercent <> 0 + -------------------------------------------------------------- + UPDATE gl + SET + InitialBudget01 = ti.BudgetAllocatedAmount01, + InitialBudget02 = ti.BudgetAllocatedAmount02, + InitialBudget03 = ti.BudgetAllocatedAmount03, + InitialBudget04 = ti.BudgetAllocatedAmount04, + InitialBudget05 = ti.BudgetAllocatedAmount05, + InitialBudget06 = ti.BudgetAllocatedAmount06, + InitialBudget07 = ti.BudgetAllocatedAmount07, + InitialBudget08 = ti.BudgetAllocatedAmount08, + InitialBudget09 = ti.BudgetAllocatedAmount09, + InitialBudget10 = ti.BudgetAllocatedAmount10, + InitialBudget11 = ti.BudgetAllocatedAmount11, + InitialBudget12 = ti.BudgetAllocatedAmount12, + + SampledBudget01 = ti.BudgetAllocatedAmount01, + SampledBudget02 = ti.BudgetAllocatedAmount02, + SampledBudget03 = ti.BudgetAllocatedAmount03, + SampledBudget04 = ti.BudgetAllocatedAmount04, + SampledBudget05 = ti.BudgetAllocatedAmount05, + SampledBudget06 = ti.BudgetAllocatedAmount06, + SampledBudget07 = ti.BudgetAllocatedAmount07, + SampledBudget08 = ti.BudgetAllocatedAmount08, + SampledBudget09 = ti.BudgetAllocatedAmount09, + SampledBudget10 = ti.BudgetAllocatedAmount10, + SampledBudget11 = ti.BudgetAllocatedAmount11, + SampledBudget12 = ti.BudgetAllocatedAmount12 + + FROM fp.GeneralLedger gl + INNER JOIN #tempInsert ti + ON gl.DepartmentID = ti.DepartmentID + AND gl.AccountID = ti.AccountID + AND gl.VariabilityID = ti.VariabilityID + WHERE ti.BudgetAllocationPercent <> 0 + AND gl.APEModelSectionID = 4 + AND gl.BudgetConfigID = @BudgetConfigID + AND gl.EntityGroupConfigID = @EntityConfigID + + -------------------------------------------------------------- + --Update Projection where ProjectionAllocationPercent <> 0 + -------------------------------------------------------------- + UPDATE gl + SET + InitialProjection01 = ti.ProjectionAllocatedAmount01, + InitialProjection02 = ti.ProjectionAllocatedAmount02, + InitialProjection03 = ti.ProjectionAllocatedAmount03, + InitialProjection04 = ti.ProjectionAllocatedAmount04, + InitialProjection05 = ti.ProjectionAllocatedAmount05, + InitialProjection06 = ti.ProjectionAllocatedAmount06, + InitialProjection07 = ti.ProjectionAllocatedAmount07, + InitialProjection08 = ti.ProjectionAllocatedAmount08, + InitialProjection09 = ti.ProjectionAllocatedAmount09, + InitialProjection10 = ti.ProjectionAllocatedAmount10, + InitialProjection11 = ti.ProjectionAllocatedAmount11, + InitialProjection12 = ti.ProjectionAllocatedAmount12, + + SampledProjection01 = ti.ProjectionAllocatedAmount01, + SampledProjection02 = ti.ProjectionAllocatedAmount02, + SampledProjection03 = ti.ProjectionAllocatedAmount03, + SampledProjection04 = ti.ProjectionAllocatedAmount04, + SampledProjection05 = ti.ProjectionAllocatedAmount05, + SampledProjection06 = ti.ProjectionAllocatedAmount06, + SampledProjection07 = ti.ProjectionAllocatedAmount07, + SampledProjection08 = ti.ProjectionAllocatedAmount08, + SampledProjection09 = ti.ProjectionAllocatedAmount09, + SampledProjection10 = ti.ProjectionAllocatedAmount10, + SampledProjection11 = ti.ProjectionAllocatedAmount11, + SampledProjection12 = ti.ProjectionAllocatedAmount12 + + FROM fp.GeneralLedger gl + INNER JOIN #tempInsert ti + ON gl.DepartmentID = ti.DepartmentID + AND gl.AccountID = ti.AccountID + AND gl.VariabilityID = ti.VariabilityID + WHERE ti.ProjectionAllocationPercent <> 0 + AND gl.APEModelSectionID = 4 + AND gl.BudgetConfigID = @BudgetConfigID + AND gl.EntityGroupConfigID = @EntityConfigID + END +END +GO + + +--------------------------------------------- + +-- fp.procReimbursementGeneralLedgerAdjustmentActivityList +CREATE PROCEDURE [fp].[procReimbursementGeneralLedgerAdjustmentActivityList] + @budgetGUID UNIQUEIDENTIFIER, + @start INT, + @end INT, + @search VARCHAR(MAX), + @filter VARCHAR(MAX), + @userGUID UNIQUEIDENTIFIER, + @isDataSecured BIT, + @dateTimeFormat VARCHAR(30), + @userTimeZone VARCHAR(50) +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-07-19 VZ JAZZ-56779 Initial + ** 2 2023-09-10 AO JAZZ-59350 Updated filtering by timeClass + ** 3 2023-12-4 AO JAZZ-62691 Added security + *************************************************************/ +BEGIN + + + + CREATE TABLE #departmentsSecurity ( + DepartmentID INT NULL, + EntityID INT NULL + ) + + CREATE TABLE #securedAdjustments ( + AdjustmentID INT NULL + ) + + SET @search = LOWER(NULLIF('%' + @search+ '%', '%\%')) + SET @filter = LOWER(NULLIF(@filter, '')) + + ---------------------------------------------------------------------- + --Get all adjustments + ---------------------------------------------------------------------- + + Select AdjustmentID, GroupingHierarchyJSON, JSON_VALUE(AdjustmentFilterJSON, '$.Entity.ID') AS EntityID + INTO #adjustments + FROM fp.ReimbursementGeneralLedgerAdjustment AS rgla WITH (NOLOCK) + WHERE rgla.BudgetConfigGUID = @budgetGUID + IF @isDataSecured = 1 + BEGIN + INSERT INTO #departmentsSecurity + EXEC fp.DepartmentsSecurity_SEL + @userGUID = @userGUID, + @pageName = 'Reimbursement' + + CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #departmentsSecurity (DepartmentID, EntityID) + + SELECT adj.AdjustmentID, + ahe.ID AS EntityID + INTO #adjustmentGroupingHierarchyEntities + FROM #adjustments AS adj + OUTER APPLY fp.GetAdjustmentHierarchyIDs(adj.GroupingHierarchyJSON, 'Entity') AS ahe + GROUP BY adj.AdjustmentID + ,ahe.ID + + INSERT INTO #securedAdjustments + SELECT res.AdjustmentID + FROM ( + SELECT slea.AdjustmentID + FROM #adjustments AS slea + JOIN #departmentsSecurity AS dse ON dse.EntityID = slea.EntityID + GROUP BY slea.AdjustmentID + + UNION ALL + + SELECT aghe.AdjustmentID + FROM #adjustmentGroupingHierarchyEntities AS aghe + JOIN #departmentsSecurity AS dshd ON dshd.EntityID = aghe.EntityID + GROUP BY aghe.AdjustmentID + + UNION ALL + + SELECT adj.AdjustmentID + FROM #adjustments AS adj + JOIN #adjustmentGroupingHierarchyEntities AS aghe ON aghe.AdjustmentID = adj.AdjustmentID + WHERE adj.EntityID IS NULL + AND aghe.EntityID IS NULL + GROUP BY adj.AdjustmentID + ) AS res + + END + ELSE + BEGIN + + INSERT INTO #securedAdjustments + SELECT AdjustmentID + FROM #adjustments + + END + + CREATE CLUSTERED INDEX PK_Adjustment ON #securedAdjustments (AdjustmentID) + + ---------------------------------------------------------------------- + --Get import adjustments + ---------------------------------------------------------------------- + + SELECT iadj.AdjustmentID + INTO #importAdjustments + FROM fp.ReimbursementGeneralLedgerAdjustmentImport AS iadj WITH (NOLOCK) + JOIN #securedAdjustments AS sadj ON sadj.AdjustmentID = iadj.AdjustmentID + LEFT JOIN #departmentsSecurity AS ds ON ds.EntityID = iadj.EntityID + WHERE ds.EntityID IS NOT NULL + OR @isDataSecured = 0 + + CREATE CLUSTERED INDEX PK_ImportAdjustmen ON #importAdjustments (AdjustmentID) + + ---------------------------------------------------------------------- + --Build dto + ---------------------------------------------------------------------- + + SELECT * + FROM ( + SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount, * + FROM ( + SELECT + ROW_NUMBER() OVER (PARTITION BY rgla.AdjustmentID ORDER BY rgla.DateCreatedUtc DESC) AS RowNumber, + rgla.AdjustmentID, + rgla.BudgetConfigGUID, + rgla.Value, + rgla.AdjustmentFilterJSON, + rgla.GroupingHierarchyJSON, + rgla.AdjustedProperty, + ISNULL(ag.Description, rgla.Comment) AS Comment, + rgla.AuthorGUID, + rgla.AuthorFullName, + rgla.LastModifiedDateUtc, + rgla.DateCreatedUtc, + rgla.GroupingGUID, + rgla.TimeClassID, + rgla.BudgetPhaseID, + rgla.ClassificationGroupID, + rgla.ClassificationCategoryID, + NULL AS JobCode, + NULL AS JobCodeCount, + NULL AS DepartmentCode, + NULL As DepartmentCount, + rgla.IsRecordDeleted, + rgla.IsCarryForward, + rgla.AdjustmentType + FROM fp.ReimbursementGeneralLedgerAdjustment AS rgla WITH (NOLOCK) + JOIN #securedAdjustments AS sleas ON sleas.AdjustmentID = rgla.AdjustmentID + LEFT JOIN (select AdjustmentID FROM #importAdjustments GROUP BY AdjustmentID) AS sai ON sai.AdjustmentID = rgla.AdjustmentID + LEFT JOIN fp.viewAdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = rgla.GroupingGUID + LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = rgla.ClassificationGroupID + LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acg.GroupID = acg.GroupID and rgla.ClassificationCategoryID = acc.CategoryID + LEFT JOIN ( + SELECT nsa.GroupingGUID + FROM fp.ReimbursementGeneralLedgerAdjustment AS nsa WITH (NOLOCK) + WHERE nsa.AdjustmentType IN (12, 13, 14) AND nsa.budgetConfigGUID = @budgetGUID + GROUP BY nsa.GroupingGUID + ) as ra ON ra.GroupingGUID = rgla.GroupingGUID + WHERE (ra.GroupingGUID IS NULL OR rgla.AdjustmentType IN (12, 13, 14)) AND (@search IS NULL + OR ( + LOWER(fp.GetAdjustmentType(rgla.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(fp.GetAdjustmentValue(rgla.Value, rgla.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(rgla.AuthorFullName) LIKE @search ESCAPE '\' + OR LOWER(ISNULL(ag.Description, rgla.Comment)) LIKE @search ESCAPE '\' + OR fp.funcCompareAdjustmentDateTime(rgla.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR fp.funcCompareAdjustmentDateTime(rgla.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR acc.[Name] LIKE @search ESCAPE '\' + OR acg.[Name] LIKE @search ESCAPE '\' + OR fp.SearchHierarchyLevel(rgla.AdjustmentFilterJSON, @search) = 1 + )) + + AND (@filter IS NULL + OR fp.GetAdjustmentTimeClassString(rgla.AdjustmentType, rgla.TimeclassID, rgla.BudgetPhaseID) IN ( + SELECT [value] + FROM STRING_SPLIT(@filter, ' ') + ) + ) + ) AS res_inner + WHERE res_inner.RowNumber = 1) AS res + WHERE res.RowNumber = 1 + ORDER BY res.DateCreatedUtc DESC +END; +GO + + +--------------------------------------------- + +-- fp.procReimbursementGeneralLedgerCopyNewItems +CREATE PROCEDURE [fp].[procReimbursementGeneralLedgerCopyNewItems] + @SourceBudgetConfigID INT, + @SourceEntityGroupConfigID INT, + @BudgetConfigID INT, + @EntityGroupConfigID INT +AS +BEGIN + + +INSERT INTO [fp].[ReimbursementGeneralLedger] (BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, AddDate, +InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, +InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12, +InitialBudgetNetAsPercentOfCharge01, InitialBudgetNetAsPercentOfCharge02, InitialBudgetNetAsPercentOfCharge03, InitialBudgetNetAsPercentOfCharge04, InitialBudgetNetAsPercentOfCharge05, InitialBudgetNetAsPercentOfCharge06, InitialBudgetNetAsPercentOfCharge07, InitialBudgetNetAsPercentOfCharge08, InitialBudgetNetAsPercentOfCharge09, InitialBudgetNetAsPercentOfCharge10, InitialBudgetNetAsPercentOfCharge11, InitialBudgetNetAsPercentOfCharge12, +InitialProjectionNetAsPercentOfCharge01, InitialProjectionNetAsPercentOfCharge02, InitialProjectionNetAsPercentOfCharge03, InitialProjectionNetAsPercentOfCharge04, InitialProjectionNetAsPercentOfCharge05, InitialProjectionNetAsPercentOfCharge06, InitialProjectionNetAsPercentOfCharge07, InitialProjectionNetAsPercentOfCharge08, InitialProjectionNetAsPercentOfCharge09, InitialProjectionNetAsPercentOfCharge10, InitialProjectionNetAsPercentOfCharge11, InitialProjectionNetAsPercentOfCharge12, +IsNew) +SELECT @BudgetConfigID, @EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, AddDate, +InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, +InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12, +InitialBudgetNetAsPercentOfCharge01, InitialBudgetNetAsPercentOfCharge02, InitialBudgetNetAsPercentOfCharge03, InitialBudgetNetAsPercentOfCharge04, InitialBudgetNetAsPercentOfCharge05, InitialBudgetNetAsPercentOfCharge06, InitialBudgetNetAsPercentOfCharge07, InitialBudgetNetAsPercentOfCharge08, InitialBudgetNetAsPercentOfCharge09, InitialBudgetNetAsPercentOfCharge10, InitialBudgetNetAsPercentOfCharge11, InitialBudgetNetAsPercentOfCharge12, +InitialProjectionNetAsPercentOfCharge01, InitialProjectionNetAsPercentOfCharge02, InitialProjectionNetAsPercentOfCharge03, InitialProjectionNetAsPercentOfCharge04, InitialProjectionNetAsPercentOfCharge05, InitialProjectionNetAsPercentOfCharge06, InitialProjectionNetAsPercentOfCharge07, InitialProjectionNetAsPercentOfCharge08, InitialProjectionNetAsPercentOfCharge09, InitialProjectionNetAsPercentOfCharge10, InitialProjectionNetAsPercentOfCharge11, InitialProjectionNetAsPercentOfCharge12, +IsNew +FROM [fp].[ReimbursementGeneralLedger] +WHERE BudgetConfigID = @SourceBudgetConfigID AND EntityGroupConfigID = @SourceEntityGroupConfigID AND IsNew = 1 +END +GO + + +--------------------------------------------- + +-- fp.procReimbursementToGLCrosswalk_Budget +CREATE PROCEDURE [fp].[procReimbursementToGLCrosswalk_Budget] + @BudgetConfigID INT, + @BudgetConfigGUID UNIQUEIDENTIFIER, + @EntityConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + + /************************************************************** + ** Change History + + ** CID Date Author WI Description + ** 1 2022-06-21 MD JAZZ-37249 Initial + ** 2 2022-08-16 MD JAZZ-42139 Update to make work with new dimensionality + ** 3 2023-08-14 MD JAZZ-58776 Update for GL restructure + *************************************************************/ + + IF OBJECT_ID('tempdb..#contractualAllowances') IS NOT NULL DROP TABLE #contractualAllowances + IF OBJECT_ID('tempdb..#tmpReimbursementCharge') IS NOT NULL DROP TABLE #tmpReimbursementCharge + IF OBJECT_ID('tempdb..#tmpReimbursementEncounter') IS NOT NULL DROP TABLE #tmpReimbursementEncounter + IF OBJECT_ID('tempdb..#tmpConAllowanceCalc') IS NOT NULL DROP TABLE #tmpConAllowanceCalc + IF OBJECT_ID('tempdb..#uniquePayorGroups') IS NOT NULL DROP TABLE #uniquePayorGroups + IF OBJECT_ID('tempdb..#tempInsert') IS NOT NULL DROP TABLE #tempInsert + + CREATE TABLE #tmpReimbursementCharge ( + BudgetConfigID INT, + PayorGroupID INT, + EntityID INT, + PatientClassID INT, + BudgetPhaseID TINYINT, + BudgetChargeDollars01 DECIMAL (19,8), + BudgetChargeDollars02 DECIMAL (19,8), + BudgetChargeDollars03 DECIMAL (19,8), + BudgetChargeDollars04 DECIMAL (19,8), + BudgetChargeDollars05 DECIMAL (19,8), + BudgetChargeDollars06 DECIMAL (19,8), + BudgetChargeDollars07 DECIMAL (19,8), + BudgetChargeDollars08 DECIMAL (19,8), + BudgetChargeDollars09 DECIMAL (19,8), + BudgetChargeDollars10 DECIMAL (19,8), + BudgetChargeDollars11 DECIMAL (19,8), + BudgetChargeDollars12 DECIMAL (19,8), + BudgetNetReimbursement01 DECIMAL (19,8), + BudgetNetReimbursement02 DECIMAL (19,8), + BudgetNetReimbursement03 DECIMAL (19,8), + BudgetNetReimbursement04 DECIMAL (19,8), + BudgetNetReimbursement05 DECIMAL (19,8), + BudgetNetReimbursement06 DECIMAL (19,8), + BudgetNetReimbursement07 DECIMAL (19,8), + BudgetNetReimbursement08 DECIMAL (19,8), + BudgetNetReimbursement09 DECIMAL (19,8), + BudgetNetReimbursement10 DECIMAL (19,8), + BudgetNetReimbursement11 DECIMAL (19,8), + BudgetNetReimbursement12 DECIMAL (19,8) + ) + + CREATE TABLE #tmpReimbursementEncounter ( + BudgetConfigID INT, + PayorGroupID INT, + EntityID INT, + PatientClassID INT, + BudgetPhaseID TINYINT, + BudgetNetReimbursement01 DECIMAL (19,8), + BudgetNetReimbursement02 DECIMAL (19,8), + BudgetNetReimbursement03 DECIMAL (19,8), + BudgetNetReimbursement04 DECIMAL (19,8), + BudgetNetReimbursement05 DECIMAL (19,8), + BudgetNetReimbursement06 DECIMAL (19,8), + BudgetNetReimbursement07 DECIMAL (19,8), + BudgetNetReimbursement08 DECIMAL (19,8), + BudgetNetReimbursement09 DECIMAL (19,8), + BudgetNetReimbursement10 DECIMAL (19,8), + BudgetNetReimbursement11 DECIMAL (19,8), + BudgetNetReimbursement12 DECIMAL (19,8) + ) + + CREATE TABLE #tmpConAllowanceCalc ( + BudgetConfigID INT, + PayorGroupID INT, + EntityID INT, + PatientClassID INT, + BudgetPhaseID TINYINT, + BudgetConAllowance01 DECIMAL (19,8), + BudgetConAllowance02 DECIMAL (19,8), + BudgetConAllowance03 DECIMAL (19,8), + BudgetConAllowance04 DECIMAL (19,8), + BudgetConAllowance05 DECIMAL (19,8), + BudgetConAllowance06 DECIMAL (19,8), + BudgetConAllowance07 DECIMAL (19,8), + BudgetConAllowance08 DECIMAL (19,8), + BudgetConAllowance09 DECIMAL (19,8), + BudgetConAllowance10 DECIMAL (19,8), + BudgetConAllowance11 DECIMAL (19,8), + BudgetConAllowance12 DECIMAL (19,8) + ) + + -------------------------------------------------------------- + --Get reimbursement contractual allowances config for given budget config + -------------------------------------------------------------- + SELECT + data.BudgetConfigGUID, + data.PayorGroupID, + data.EntityID, + data.PatientClassID, + data.DepartmentID, + data.AccountID, + sum(data.ProjectionAllocationPercent) AS ProjectionAllocationPercent, + sum(data.BudgetAllocationPercent) AS BudgetAllocationPercent + INTO #contractualAllowances + FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data + INNER JOIN [fp].[viewDeductionsAccounts] da on data.AccountID = da.AccountID + WHERE + data.BudgetConfigGUID = @BudgetConfigGUID + GROUP BY + data.BudgetConfigGUID, + data.PayorGroupID, + data.EntityID, + data.PatientClassID, + data.DepartmentID, + data.AccountID + + SELECT + data.PayorGroupID, + data.EntityID, + data.PatientClassID + INTO #uniquePayorGroups + FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data + INNER JOIN [fp].[viewDeductionsAccounts] da on data.AccountID = da.AccountID + WHERE + data.BudgetConfigGUID = @BudgetConfigGUID + GROUP BY + data.PayorGroupID, + data.EntityID, + data.PatientClassID + + -------------------------------------------------------------- + --Get reimbursement encounter data using CA dimensionality to group + -------------------------------------------------------------- + INSERT INTO #tmpReimbursementEncounter (PayorGroupID, EntityID, PatientClassID, BudgetPhaseID, + BudgetNetReimbursement01, BudgetNetReimbursement02, BudgetNetReimbursement03, BudgetNetReimbursement04, + BudgetNetReimbursement05, BudgetNetReimbursement06, BudgetNetReimbursement07, BudgetNetReimbursement08, + BudgetNetReimbursement09, BudgetNetReimbursement10, BudgetNetReimbursement11, BudgetNetReimbursement12 + ) + SELECT + ca.PayorGroupID, + ca.EntityID, + ca.PatientClassID, + freb.BudgetPhaseID, + sum(freb.AdjustedNetReimbursementValue01), + sum(freb.AdjustedNetReimbursementValue02), + sum(freb.AdjustedNetReimbursementValue03), + sum(freb.AdjustedNetReimbursementValue04), + sum(freb.AdjustedNetReimbursementValue05), + sum(freb.AdjustedNetReimbursementValue06), + sum(freb.AdjustedNetReimbursementValue07), + sum(freb.AdjustedNetReimbursementValue08), + sum(freb.AdjustedNetReimbursementValue09), + sum(freb.AdjustedNetReimbursementValue10), + sum(freb.AdjustedNetReimbursementValue11), + sum(freb.AdjustedNetReimbursementValue12) + FROM fp.FactReimbursementEncounter fre + INNER JOIN #uniquePayorGroups ca + ON fre.PayorGroupID = ca.PayorGroupID + AND fre.EntityID = ca.EntityID + AND fre.PatientClassID = ca.PatientClassID + INNER JOIN fp.FactReimbursementEncounterBudget freb + ON fre.ReimbursementEncounterID = freb.ReimbursementEncounterID + WHERE + fre.BudgetConfigID = @BudgetConfigID + AND fre.EntityGroupConfigID = @EntityConfigID + AND ca.PatientClassID > 0 + GROUP BY + ca.PayorGroupID, + ca.EntityID, + ca.PatientClassID, + freb.BudgetPhaseID + + UNION ALL + + SELECT + ca.PayorGroupID, + ca.EntityID, + 0 as PatientClassID, + freb.BudgetPhaseID, + sum(freb.AdjustedNetReimbursementValue01), + sum(freb.AdjustedNetReimbursementValue02), + sum(freb.AdjustedNetReimbursementValue03), + sum(freb.AdjustedNetReimbursementValue04), + sum(freb.AdjustedNetReimbursementValue05), + sum(freb.AdjustedNetReimbursementValue06), + sum(freb.AdjustedNetReimbursementValue07), + sum(freb.AdjustedNetReimbursementValue08), + sum(freb.AdjustedNetReimbursementValue09), + sum(freb.AdjustedNetReimbursementValue10), + sum(freb.AdjustedNetReimbursementValue11), + sum(freb.AdjustedNetReimbursementValue12) + FROM fp.FactReimbursementEncounter fre + INNER JOIN #uniquePayorGroups ca + ON fre.PayorGroupID = ca.PayorGroupID + AND fre.EntityID = ca.EntityID + INNER JOIN fp.FactReimbursementEncounterBudget freb + ON fre.ReimbursementEncounterID = freb.ReimbursementEncounterID + WHERE + fre.BudgetConfigID = @BudgetConfigID + AND fre.EntityGroupConfigID = @EntityConfigID + AND ca.PatientClassID = 0 + GROUP BY + ca.PayorGroupID, + ca.EntityID, + freb.BudgetPhaseID + + -------------------------------------------------------------- + --Get reimbursement charge data using CA dimensionality to group + -------------------------------------------------------------- + INSERT INTO #tmpReimbursementCharge (PayorGroupID, EntityID, PatientClassID, BudgetPhaseID, + BudgetNetReimbursement01, BudgetNetReimbursement02, BudgetNetReimbursement03, BudgetNetReimbursement04, + BudgetNetReimbursement05, BudgetNetReimbursement06, BudgetNetReimbursement07, BudgetNetReimbursement08, + BudgetNetReimbursement09, BudgetNetReimbursement10, BudgetNetReimbursement11, BudgetNetReimbursement12, + BudgetChargeDollars01, BudgetChargeDollars02, BudgetChargeDollars03, BudgetChargeDollars04, + BudgetChargeDollars05, BudgetChargeDollars06, BudgetChargeDollars07, BudgetChargeDollars08, + BudgetChargeDollars09, BudgetChargeDollars10, BudgetChargeDollars11, BudgetChargeDollars12) + + SELECT + ca.PayorGroupID, + ca.EntityID, + ca.PatientClassID, + frcb.BudgetPhaseID, + sum(frcb.AdjustedNetReimbursementValue01), + sum(frcb.AdjustedNetReimbursementValue02), + sum(frcb.AdjustedNetReimbursementValue03), + sum(frcb.AdjustedNetReimbursementValue04), + sum(frcb.AdjustedNetReimbursementValue05), + sum(frcb.AdjustedNetReimbursementValue06), + sum(frcb.AdjustedNetReimbursementValue07), + sum(frcb.AdjustedNetReimbursementValue08), + sum(frcb.AdjustedNetReimbursementValue09), + sum(frcb.AdjustedNetReimbursementValue10), + sum(frcb.AdjustedNetReimbursementValue11), + sum(frcb.AdjustedNetReimbursementValue12), + sum(frcb.AdjustedChargeDollars01), + sum(frcb.AdjustedChargeDollars02), + sum(frcb.AdjustedChargeDollars03), + sum(frcb.AdjustedChargeDollars04), + sum(frcb.AdjustedChargeDollars05), + sum(frcb.AdjustedChargeDollars06), + sum(frcb.AdjustedChargeDollars07), + sum(frcb.AdjustedChargeDollars08), + sum(frcb.AdjustedChargeDollars09), + sum(frcb.AdjustedChargeDollars10), + sum(frcb.AdjustedChargeDollars11), + sum(frcb.AdjustedChargeDollars12) + FROM fp.FactReimbursementCharges frc + INNER JOIN #uniquePayorGroups ca + ON frc.PayorGroupID = ca.PayorGroupID + AND frc.EntityID = ca.EntityID + AND frc.PatientClassID = ca.PatientClassID + INNER JOIN fp.FactReimbursementChargesBudget frcb + ON frc.ReimbursementChargesID = frcb.ReimbursementChargesID + WHERE + frc.BudgetConfigID = @BudgetConfigID + AND frc.EntityGroupConfigID = @EntityConfigID + AND ca.PatientClassID > 0 + GROUP BY + ca.PayorGroupID, + ca.EntityID, + ca.PatientClassID, + frcb.BudgetPhaseID + + UNION ALL + + SELECT + ca.PayorGroupID, + ca.EntityID, + 0 AS PatientClassID, + frcb.BudgetPhaseID, + sum(frcb.AdjustedNetReimbursementValue01), + sum(frcb.AdjustedNetReimbursementValue02), + sum(frcb.AdjustedNetReimbursementValue03), + sum(frcb.AdjustedNetReimbursementValue04), + sum(frcb.AdjustedNetReimbursementValue05), + sum(frcb.AdjustedNetReimbursementValue06), + sum(frcb.AdjustedNetReimbursementValue07), + sum(frcb.AdjustedNetReimbursementValue08), + sum(frcb.AdjustedNetReimbursementValue09), + sum(frcb.AdjustedNetReimbursementValue10), + sum(frcb.AdjustedNetReimbursementValue11), + sum(frcb.AdjustedNetReimbursementValue12), + sum(frcb.AdjustedChargeDollars01), + sum(frcb.AdjustedChargeDollars02), + sum(frcb.AdjustedChargeDollars03), + sum(frcb.AdjustedChargeDollars04), + sum(frcb.AdjustedChargeDollars05), + sum(frcb.AdjustedChargeDollars06), + sum(frcb.AdjustedChargeDollars07), + sum(frcb.AdjustedChargeDollars08), + sum(frcb.AdjustedChargeDollars09), + sum(frcb.AdjustedChargeDollars10), + sum(frcb.AdjustedChargeDollars11), + sum(frcb.AdjustedChargeDollars12) + FROM fp.FactReimbursementCharges frc + INNER JOIN #uniquePayorGroups ca + ON frc.PayorGroupID = ca.PayorGroupID + AND frc.EntityID = ca.EntityID + INNER JOIN fp.FactReimbursementChargesBudget frcb + ON frc.ReimbursementChargesID = frcb.ReimbursementChargesID + WHERE + frc.BudgetConfigID = @BudgetConfigID + AND frc.EntityGroupConfigID = @EntityConfigID + AND ca.PatientClassID = 0 + GROUP BY + ca.PayorGroupID, + ca.EntityID, + frcb.BudgetPhaseID + + -------------------------------------------------------------- + --Do allocation calculation + --ChargeDollarsXX - ChargeNetReimbursementXX - EncounterNetReimbursementXX + -------------------------------------------------------------- + INSERT INTO #tmpConAllowanceCalc(BudgetConfigID, PayorGroupID, EntityID, PatientClassID, BudgetPhaseID, + BudgetConAllowance01, BudgetConAllowance02, BudgetConAllowance03, BudgetConAllowance04, + BudgetConAllowance05, BudgetConAllowance06, BudgetConAllowance07, BudgetConAllowance08, + BudgetConAllowance09, BudgetConAllowance10, BudgetConAllowance11, BudgetConAllowance12) + SELECT + tc.BudgetConfigID, + tc.PayorGroupID, + tc.EntityID, + tc.PatientClassID, + tc.BudgetPhaseID, + ISNULL(tc.BudgetChargeDollars01,0) - ISNULL(tc.BudgetNetReimbursement01,0) - ISNULL(te.BudgetNetReimbursement01,0) AS BudgetConAllowance01, + ISNULL(tc.BudgetChargeDollars02,0) - ISNULL(tc.BudgetNetReimbursement02,0) - ISNULL(te.BudgetNetReimbursement02,0) AS BudgetConAllowance02, + ISNULL(tc.BudgetChargeDollars03,0) - ISNULL(tc.BudgetNetReimbursement03,0) - ISNULL(te.BudgetNetReimbursement03,0) AS BudgetConAllowance03, + ISNULL(tc.BudgetChargeDollars04,0) - ISNULL(tc.BudgetNetReimbursement04,0) - ISNULL(te.BudgetNetReimbursement04,0) AS BudgetConAllowance04, + ISNULL(tc.BudgetChargeDollars05,0) - ISNULL(tc.BudgetNetReimbursement05,0) - ISNULL(te.BudgetNetReimbursement05,0) AS BudgetConAllowance05, + ISNULL(tc.BudgetChargeDollars06,0) - ISNULL(tc.BudgetNetReimbursement06,0) - ISNULL(te.BudgetNetReimbursement06,0) AS BudgetConAllowance06, + ISNULL(tc.BudgetChargeDollars07,0) - ISNULL(tc.BudgetNetReimbursement07,0) - ISNULL(te.BudgetNetReimbursement07,0) AS BudgetConAllowance07, + ISNULL(tc.BudgetChargeDollars08,0) - ISNULL(tc.BudgetNetReimbursement08,0) - ISNULL(te.BudgetNetReimbursement08,0) AS BudgetConAllowance08, + ISNULL(tc.BudgetChargeDollars09,0) - ISNULL(tc.BudgetNetReimbursement09,0) - ISNULL(te.BudgetNetReimbursement09,0) AS BudgetConAllowance09, + ISNULL(tc.BudgetChargeDollars10,0) - ISNULL(tc.BudgetNetReimbursement10,0) - ISNULL(te.BudgetNetReimbursement10,0) AS BudgetConAllowance10, + ISNULL(tc.BudgetChargeDollars11,0) - ISNULL(tc.BudgetNetReimbursement11,0) - ISNULL(te.BudgetNetReimbursement11,0) AS BudgetConAllowance11, + ISNULL(tc.BudgetChargeDollars12,0) - ISNULL(tc.BudgetNetReimbursement12,0) - ISNULL(te.BudgetNetReimbursement12,0) AS BudgetConAllowance12 + FROM #tmpReimbursementCharge tc + FULL JOIN #tmpReimbursementEncounter te + ON tc.PayorGroupID = te.PayorGroupID + AND tc.EntityID = te.EntityID + AND tc.PatientClassID = te.PatientClassID + AND tc.BudgetPhaseID = te.BudgetPhaseID + + -------------------------------------------------------------- + --Insert into temp table + --Using this intermediary step to sum up unique PG/E/PC's that flex to the same department/account in GL + -------------------------------------------------------------- + SELECT + gl.DepartmentID, + gl.AccountID, + gl.VariabilityID, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance01 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted01 END) AS TargetAllocatedAmount01, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance02 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted02 END) AS TargetAllocatedAmount02, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance03 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted03 END) AS TargetAllocatedAmount03, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance04 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted04 END) AS TargetAllocatedAmount04, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance05 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted05 END) AS TargetAllocatedAmount05, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance06 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted06 END) AS TargetAllocatedAmount06, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance07 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted07 END) AS TargetAllocatedAmount07, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance08 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted08 END) AS TargetAllocatedAmount08, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance09 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted09 END) AS TargetAllocatedAmount09, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance10 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted10 END) AS TargetAllocatedAmount10, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance11 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted11 END) AS TargetAllocatedAmount11, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance12 * ca.BudgetAllocationPercent ELSE gl.TargetAdjusted12 END) AS TargetAllocatedAmount12, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance01 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted01 END) AS BudgetAllocatedAmount01, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance02 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted02 END) AS BudgetAllocatedAmount02, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance03 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted03 END) AS BudgetAllocatedAmount03, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance04 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted04 END) AS BudgetAllocatedAmount04, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance05 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted05 END) AS BudgetAllocatedAmount05, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance06 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted06 END) AS BudgetAllocatedAmount06, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance07 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted07 END) AS BudgetAllocatedAmount07, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance08 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted08 END) AS BudgetAllocatedAmount08, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance09 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted09 END) AS BudgetAllocatedAmount09, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance10 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted10 END) AS BudgetAllocatedAmount10, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance11 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted11 END) AS BudgetAllocatedAmount11, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc2.BudgetConAllowance12 * ca.BudgetAllocationPercent ELSE gl.BudgetAdjusted12 END) AS BudgetAllocatedAmount12 + INTO #tempInsert + FROM fp.GeneralLedger gl + INNER JOIN #contractualAllowances ca + ON ca.DepartmentID = gl.DepartmentID + AND ca.AccountID = gl.AccountID + INNER JOIN #tmpConAllowanceCalc calc + ON ca.PayorGroupID = calc.PayorGroupID + AND ca.EntityID = calc.EntityID + AND ca.PatientClassID = calc.PatientClassID + INNER JOIN #tmpConAllowanceCalc calc2 + ON ca.PayorGroupID = calc2.PayorGroupID + AND ca.EntityID = calc2.EntityID + AND ca.PatientClassID = calc2.PatientClassID + WHERE + gl.APEModelSectionID = 4 + AND gl.BudgetConfigID = @BudgetConfigID + AND gl.EntityGroupConfigID = @EntityConfigID + AND ca.BudgetAllocationPercent <> 0 + AND calc.BudgetPhaseID = 2 + AND calc2.BudgetPhaseID = 3 + GROUP BY + gl.DepartmentID, + gl.AccountID, + gl.VariabilityID + + -------------------------------------------------------------- + --Update budget + -------------------------------------------------------------- + IF (@IsDebug = 1) + BEGIN + SELECT * FROM #tempInsert + END ELSE BEGIN + UPDATE gl + SET + BudgetLockFlag = 1, + BudgetLockType = 3, + TargetLockFlag = 1, + TargetLockType = 3, + BudgetAdjusted01 = ti.BudgetAllocatedAmount01, + BudgetAdjusted02 = ti.BudgetAllocatedAmount02, + BudgetAdjusted03 = ti.BudgetAllocatedAmount03, + BudgetAdjusted04 = ti.BudgetAllocatedAmount04, + BudgetAdjusted05 = ti.BudgetAllocatedAmount05, + BudgetAdjusted06 = ti.BudgetAllocatedAmount06, + BudgetAdjusted07 = ti.BudgetAllocatedAmount07, + BudgetAdjusted08 = ti.BudgetAllocatedAmount08, + BudgetAdjusted09 = ti.BudgetAllocatedAmount09, + BudgetAdjusted10 = ti.BudgetAllocatedAmount10, + BudgetAdjusted11 = ti.BudgetAllocatedAmount11, + BudgetAdjusted12 = ti.BudgetAllocatedAmount12, + TargetAdjusted01 = ti.TargetAllocatedAmount01, + TargetAdjusted02 = ti.TargetAllocatedAmount02, + TargetAdjusted03 = ti.TargetAllocatedAmount03, + TargetAdjusted04 = ti.TargetAllocatedAmount04, + TargetAdjusted05 = ti.TargetAllocatedAmount05, + TargetAdjusted06 = ti.TargetAllocatedAmount06, + TargetAdjusted07 = ti.TargetAllocatedAmount07, + TargetAdjusted08 = ti.TargetAllocatedAmount08, + TargetAdjusted09 = ti.TargetAllocatedAmount09, + TargetAdjusted10 = ti.TargetAllocatedAmount10, + TargetAdjusted11 = ti.TargetAllocatedAmount11, + TargetAdjusted12 = ti.TargetAllocatedAmount12 + FROM fp.GeneralLedger gl + INNER JOIN #tempInsert ti + ON gl.DepartmentID = ti.DepartmentID + AND gl.AccountID = ti.AccountID + AND gl.VariabilityID = ti.VariabilityID + WHERE + gl.APEModelSectionID = 4 + AND gl.BudgetConfigID = @BudgetConfigID + AND gl.EntityGroupConfigID = @EntityConfigID + END +END +GO + + +--------------------------------------------- + +-- fp.procReimbursementToGLCrosswalk_Initial +CREATE PROCEDURE [fp].[procReimbursementToGLCrosswalk_Initial] + @BudgetConfigID INT, + @BudgetConfigGUID UNIQUEIDENTIFIER, + @EntityConfigID INT, + @MonthsLoaded INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + + /************************************************************** + ** Change History + ** CID Date Author WI Description + ** 1 2022-06-21 MD JAZZ-37249 Initial + ** 2 2022-10-12 MD JAZZ-42139 Updating the allocation method of contractuals for reimbursement + ** 3 2023-08-14 MD JAZZ-58776 Update for GL restructure + *************************************************************/ + + IF OBJECT_ID('tempdb..#contractualAllowances') IS NOT NULL DROP TABLE #contractualAllowances + IF OBJECT_ID('tempdb..#tmpReimbursementCharge') IS NOT NULL DROP TABLE #tmpReimbursementCharge + IF OBJECT_ID('tempdb..#tmpReimbursementEncounter') IS NOT NULL DROP TABLE #tmpReimbursementEncounter + IF OBJECT_ID('tempdb..#tmpConAllowanceCalc') IS NOT NULL DROP TABLE #tmpConAllowanceCalc + IF OBJECT_ID('tempdb..#uniqueDimensionality') IS NOT NULL DROP TABLE #uniqueDimensionality + IF OBJECT_ID('tempdb..#tempInsert') IS NOT NULL DROP TABLE #tempInsert + + CREATE TABLE #tmpReimbursementCharge ( + PayorGroupID INT, + EntityID INT, + PatientClassID INT, + BudgetChargeDollars01 DECIMAL (19,8), + BudgetChargeDollars02 DECIMAL (19,8), + BudgetChargeDollars03 DECIMAL (19,8), + BudgetChargeDollars04 DECIMAL (19,8), + BudgetChargeDollars05 DECIMAL (19,8), + BudgetChargeDollars06 DECIMAL (19,8), + BudgetChargeDollars07 DECIMAL (19,8), + BudgetChargeDollars08 DECIMAL (19,8), + BudgetChargeDollars09 DECIMAL (19,8), + BudgetChargeDollars10 DECIMAL (19,8), + BudgetChargeDollars11 DECIMAL (19,8), + BudgetChargeDollars12 DECIMAL (19,8), + BudgetNetReimbursement01 DECIMAL (19,8), + BudgetNetReimbursement02 DECIMAL (19,8), + BudgetNetReimbursement03 DECIMAL (19,8), + BudgetNetReimbursement04 DECIMAL (19,8), + BudgetNetReimbursement05 DECIMAL (19,8), + BudgetNetReimbursement06 DECIMAL (19,8), + BudgetNetReimbursement07 DECIMAL (19,8), + BudgetNetReimbursement08 DECIMAL (19,8), + BudgetNetReimbursement09 DECIMAL (19,8), + BudgetNetReimbursement10 DECIMAL (19,8), + BudgetNetReimbursement11 DECIMAL (19,8), + BudgetNetReimbursement12 DECIMAL (19,8) + ) + + CREATE TABLE #tmpReimbursementEncounter ( + PayorGroupID INT, + EntityID INT, + PatientClassID INT, + BudgetNetReimbursement01 DECIMAL (19,8), + BudgetNetReimbursement02 DECIMAL (19,8), + BudgetNetReimbursement03 DECIMAL (19,8), + BudgetNetReimbursement04 DECIMAL (19,8), + BudgetNetReimbursement05 DECIMAL (19,8), + BudgetNetReimbursement06 DECIMAL (19,8), + BudgetNetReimbursement07 DECIMAL (19,8), + BudgetNetReimbursement08 DECIMAL (19,8), + BudgetNetReimbursement09 DECIMAL (19,8), + BudgetNetReimbursement10 DECIMAL (19,8), + BudgetNetReimbursement11 DECIMAL (19,8), + BudgetNetReimbursement12 DECIMAL (19,8) + ) + + CREATE TABLE #tmpConAllowanceCalc ( + PayorGroupID INT, + EntityID INT, + PatientClassID INT, + BudgetConAllowance01 DECIMAL (19,8), + BudgetConAllowance02 DECIMAL (19,8), + BudgetConAllowance03 DECIMAL (19,8), + BudgetConAllowance04 DECIMAL (19,8), + BudgetConAllowance05 DECIMAL (19,8), + BudgetConAllowance06 DECIMAL (19,8), + BudgetConAllowance07 DECIMAL (19,8), + BudgetConAllowance08 DECIMAL (19,8), + BudgetConAllowance09 DECIMAL (19,8), + BudgetConAllowance10 DECIMAL (19,8), + BudgetConAllowance11 DECIMAL (19,8), + BudgetConAllowance12 DECIMAL (19,8) + ) + + -------------------------------------------------------------- + --Get reimbursement contractual allowances config for given budget config + -------------------------------------------------------------- + SELECT + data.BudgetConfigGUID, + data.PayorGroupID, + data.EntityID, + data.PatientClassID, + data.DepartmentID, + data.AccountID, + sum(data.ProjectionAllocationPercent) AS ProjectionAllocationPercent, + sum(data.BudgetAllocationPercent) AS BudgetAllocationPercent + INTO #contractualAllowances + FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data + INNER JOIN [fp].[viewDeductionsAccounts] da on data.AccountID = da.AccountID + WHERE + data.BudgetConfigGUID = @BudgetConfigGUID + GROUP BY + data.BudgetConfigGUID, + data.PayorGroupID, + data.EntityID, + data.PatientClassID, + data.DepartmentID, + data.AccountID + + SELECT + data.PayorGroupID, + data.EntityID, + data.PatientClassID + INTO #uniqueDimensionality + FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data + INNER JOIN [fp].[viewDeductionsAccounts] da on data.AccountID = da.AccountID + WHERE + data.BudgetConfigGUID = @BudgetConfigGUID + GROUP BY + data.PayorGroupID, + data.EntityID, + data.PatientClassID + + -------------------------------------------------------------- + --Get reimbursement encounter data using CA dimensionality to group + -------------------------------------------------------------- + INSERT INTO #tmpReimbursementEncounter (PayorGroupID, EntityID, PatientClassID, + BudgetNetReimbursement01, BudgetNetReimbursement02, BudgetNetReimbursement03, BudgetNetReimbursement04, + BudgetNetReimbursement05, BudgetNetReimbursement06, BudgetNetReimbursement07, BudgetNetReimbursement08, + BudgetNetReimbursement09, BudgetNetReimbursement10, BudgetNetReimbursement11, BudgetNetReimbursement12 + ) + SELECT + ca.PayorGroupID, + ca.EntityID, + ca.PatientClassID, + sum(fre.InitialBudgetNetReimbursement01), + sum(fre.InitialBudgetNetReimbursement02), + sum(fre.InitialBudgetNetReimbursement03), + sum(fre.InitialBudgetNetReimbursement04), + sum(fre.InitialBudgetNetReimbursement05), + sum(fre.InitialBudgetNetReimbursement06), + sum(fre.InitialBudgetNetReimbursement07), + sum(fre.InitialBudgetNetReimbursement08), + sum(fre.InitialBudgetNetReimbursement09), + sum(fre.InitialBudgetNetReimbursement10), + sum(fre.InitialBudgetNetReimbursement11), + sum(fre.InitialBudgetNetReimbursement12) + FROM fp.FactReimbursementEncounter fre + INNER JOIN #uniqueDimensionality ca + ON fre.PayorGroupID = ca.PayorGroupID + AND fre.EntityID = ca.EntityID + AND fre.PatientClassID = ca.PatientClassID + WHERE + fre.BudgetConfigID = @BudgetConfigID + AND fre.EntityGroupConfigID = @EntityConfigID + AND ca.PatientClassID > 0 + GROUP BY + ca.PayorGroupID, + ca.EntityID, + ca.PatientClassID + + UNION ALL + + SELECT + ca.PayorGroupID, + ca.EntityID, + 0 AS PatientClassID, + sum(fre.InitialBudgetNetReimbursement01), + sum(fre.InitialBudgetNetReimbursement02), + sum(fre.InitialBudgetNetReimbursement03), + sum(fre.InitialBudgetNetReimbursement04), + sum(fre.InitialBudgetNetReimbursement05), + sum(fre.InitialBudgetNetReimbursement06), + sum(fre.InitialBudgetNetReimbursement07), + sum(fre.InitialBudgetNetReimbursement08), + sum(fre.InitialBudgetNetReimbursement09), + sum(fre.InitialBudgetNetReimbursement10), + sum(fre.InitialBudgetNetReimbursement11), + sum(fre.InitialBudgetNetReimbursement12) + FROM fp.FactReimbursementEncounter fre + INNER JOIN #uniqueDimensionality ca + ON fre.PayorGroupID = ca.PayorGroupID + AND fre.EntityID = ca.EntityID + WHERE + fre.BudgetConfigID = @BudgetConfigID + AND fre.EntityGroupConfigID = @EntityConfigID + AND ca.PatientClassID = 0 + GROUP BY + ca.PayorGroupID, + ca.EntityID + + -------------------------------------------------------------- + --Get reimbursement charge data using CA dimensionality to group + -------------------------------------------------------------- + INSERT INTO #tmpReimbursementCharge (PayorGroupID, EntityID, PatientClassID, + BudgetNetReimbursement01, BudgetNetReimbursement02, BudgetNetReimbursement03, BudgetNetReimbursement04, + BudgetNetReimbursement05, BudgetNetReimbursement06, BudgetNetReimbursement07, BudgetNetReimbursement08, + BudgetNetReimbursement09, BudgetNetReimbursement10, BudgetNetReimbursement11, BudgetNetReimbursement12, + BudgetChargeDollars01, BudgetChargeDollars02, BudgetChargeDollars03, BudgetChargeDollars04, + BudgetChargeDollars05, BudgetChargeDollars06, BudgetChargeDollars07, BudgetChargeDollars08, + BudgetChargeDollars09, BudgetChargeDollars10, BudgetChargeDollars11, BudgetChargeDollars12) + SELECT + ca.PayorGroupID, + ca.EntityID, + ca.PatientClassID, + sum(frc.InitialBudgetNetReimbursement01), + sum(frc.InitialBudgetNetReimbursement02), + sum(frc.InitialBudgetNetReimbursement03), + sum(frc.InitialBudgetNetReimbursement04), + sum(frc.InitialBudgetNetReimbursement05), + sum(frc.InitialBudgetNetReimbursement06), + sum(frc.InitialBudgetNetReimbursement07), + sum(frc.InitialBudgetNetReimbursement08), + sum(frc.InitialBudgetNetReimbursement09), + sum(frc.InitialBudgetNetReimbursement10), + sum(frc.InitialBudgetNetReimbursement11), + sum(frc.InitialBudgetNetReimbursement12), + sum(frc.InitialBudgetChargeDollars01), + sum(frc.InitialBudgetChargeDollars02), + sum(frc.InitialBudgetChargeDollars03), + sum(frc.InitialBudgetChargeDollars04), + sum(frc.InitialBudgetChargeDollars05), + sum(frc.InitialBudgetChargeDollars06), + sum(frc.InitialBudgetChargeDollars07), + sum(frc.InitialBudgetChargeDollars08), + sum(frc.InitialBudgetChargeDollars09), + sum(frc.InitialBudgetChargeDollars10), + sum(frc.InitialBudgetChargeDollars11), + sum(frc.InitialBudgetChargeDollars12) + FROM fp.FactReimbursementCharges frc + INNER JOIN #uniqueDimensionality ca + ON frc.PayorGroupID = ca.PayorGroupID + AND frc.EntityID = ca.EntityID + AND frc.PatientClassID = ca.PatientClassID + WHERE + frc.BudgetConfigID = @BudgetConfigID + AND frc.EntityGroupConfigID = @EntityConfigID + AND ca.PatientClassID > 0 + GROUP BY + ca.PayorGroupID, + ca.EntityID, + ca.PatientClassID + + UNION ALL + + SELECT + ca.PayorGroupID, + ca.EntityID, + 0 as PatientClassID, + sum(frc.InitialBudgetNetReimbursement01), + sum(frc.InitialBudgetNetReimbursement02), + sum(frc.InitialBudgetNetReimbursement03), + sum(frc.InitialBudgetNetReimbursement04), + sum(frc.InitialBudgetNetReimbursement05), + sum(frc.InitialBudgetNetReimbursement06), + sum(frc.InitialBudgetNetReimbursement07), + sum(frc.InitialBudgetNetReimbursement08), + sum(frc.InitialBudgetNetReimbursement09), + sum(frc.InitialBudgetNetReimbursement10), + sum(frc.InitialBudgetNetReimbursement11), + sum(frc.InitialBudgetNetReimbursement12), + sum(frc.InitialBudgetChargeDollars01), + sum(frc.InitialBudgetChargeDollars02), + sum(frc.InitialBudgetChargeDollars03), + sum(frc.InitialBudgetChargeDollars04), + sum(frc.InitialBudgetChargeDollars05), + sum(frc.InitialBudgetChargeDollars06), + sum(frc.InitialBudgetChargeDollars07), + sum(frc.InitialBudgetChargeDollars08), + sum(frc.InitialBudgetChargeDollars09), + sum(frc.InitialBudgetChargeDollars10), + sum(frc.InitialBudgetChargeDollars11), + sum(frc.InitialBudgetChargeDollars12) + FROM fp.FactReimbursementCharges frc + INNER JOIN #uniqueDimensionality ca + ON frc.PayorGroupID = ca.PayorGroupID + AND frc.EntityID = ca.EntityID + WHERE + frc.BudgetConfigID = @BudgetConfigID + AND frc.EntityGroupConfigID = @EntityConfigID + AND ca.PatientClassID = 0 + GROUP BY + ca.PayorGroupID, + ca.EntityID + + -------------------------------------------------------------- + --Do allocation calculation + --ChargeDollarsXX - ChargeNetReimbursementXX - EncounterNetReimbursementXX + -------------------------------------------------------------- + INSERT INTO #tmpConAllowanceCalc(PayorGroupID, EntityID, PatientClassID, + BudgetConAllowance01, BudgetConAllowance02, BudgetConAllowance03, BudgetConAllowance04, + BudgetConAllowance05, BudgetConAllowance06, BudgetConAllowance07, BudgetConAllowance08, + BudgetConAllowance09, BudgetConAllowance10, BudgetConAllowance11, BudgetConAllowance12) + SELECT + tc.PayorGroupID, + tc.EntityID, + tc.PatientClassID, + ISNULL(tc.BudgetChargeDollars01,0) - ISNULL(tc.BudgetNetReimbursement01,0) - ISNULL(te.BudgetNetReimbursement01,0) AS BudgetConAllowance01, + ISNULL(tc.BudgetChargeDollars02,0) - ISNULL(tc.BudgetNetReimbursement02,0) - ISNULL(te.BudgetNetReimbursement02,0) AS BudgetConAllowance02, + ISNULL(tc.BudgetChargeDollars03,0) - ISNULL(tc.BudgetNetReimbursement03,0) - ISNULL(te.BudgetNetReimbursement03,0) AS BudgetConAllowance03, + ISNULL(tc.BudgetChargeDollars04,0) - ISNULL(tc.BudgetNetReimbursement04,0) - ISNULL(te.BudgetNetReimbursement04,0) AS BudgetConAllowance04, + ISNULL(tc.BudgetChargeDollars05,0) - ISNULL(tc.BudgetNetReimbursement05,0) - ISNULL(te.BudgetNetReimbursement05,0) AS BudgetConAllowance05, + ISNULL(tc.BudgetChargeDollars06,0) - ISNULL(tc.BudgetNetReimbursement06,0) - ISNULL(te.BudgetNetReimbursement06,0) AS BudgetConAllowance06, + ISNULL(tc.BudgetChargeDollars07,0) - ISNULL(tc.BudgetNetReimbursement07,0) - ISNULL(te.BudgetNetReimbursement07,0) AS BudgetConAllowance07, + ISNULL(tc.BudgetChargeDollars08,0) - ISNULL(tc.BudgetNetReimbursement08,0) - ISNULL(te.BudgetNetReimbursement08,0) AS BudgetConAllowance08, + ISNULL(tc.BudgetChargeDollars09,0) - ISNULL(tc.BudgetNetReimbursement09,0) - ISNULL(te.BudgetNetReimbursement09,0) AS BudgetConAllowance09, + ISNULL(tc.BudgetChargeDollars10,0) - ISNULL(tc.BudgetNetReimbursement10,0) - ISNULL(te.BudgetNetReimbursement10,0) AS BudgetConAllowance10, + ISNULL(tc.BudgetChargeDollars11,0) - ISNULL(tc.BudgetNetReimbursement11,0) - ISNULL(te.BudgetNetReimbursement11,0) AS BudgetConAllowance11, + ISNULL(tc.BudgetChargeDollars12,0) - ISNULL(tc.BudgetNetReimbursement12,0) - ISNULL(te.BudgetNetReimbursement12,0) AS BudgetConAllowance12 + FROM #tmpReimbursementCharge tc + FULL JOIN #tmpReimbursementEncounter te + ON tc.PayorGroupID = te.PayorGroupID + AND tc.EntityID = te.EntityID + AND tc.PatientClassID = te.PatientClassID + + -------------------------------------------------------------- + --Insert into temp table + --Using this intermediary step to sum up unique PG/E/PC's that flex to the same department/account in GL + -------------------------------------------------------------- + SELECT + gl.DepartmentID, + gl.AccountID, + gl.VariabilityID, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance01 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount01, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance02 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount02, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance03 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount03, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance04 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount04, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance05 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount05, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance06 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount06, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance07 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount07, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance08 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount08, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance09 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount09, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance10 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount10, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance11 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount11, + SUM(CASE WHEN gl.VariabilityID = 1 THEN 0 WHEN gl.VariabilityID = 2 THEN calc.BudgetConAllowance12 * ca.BudgetAllocationPercent END) AS BudgetAllocatedAmount12 + INTO #tempInsert + FROM fp.GeneralLedger gl + INNER JOIN #contractualAllowances ca + ON ca.DepartmentID = gl.DepartmentID + AND ca.AccountID = gl.AccountID + INNER JOIN #tmpConAllowanceCalc calc + ON ca.PayorGroupID = calc.PayorGroupID + AND ca.EntityID = calc.EntityID + AND ca.PatientClassID = calc.PatientClassID + WHERE + gl.BudgetConfigID = @BudgetConfigID + AND gl.EntityGroupConfigID = @EntityConfigID + GROUP BY + gl.DepartmentID, + gl.AccountID, + gl.VariabilityID + + -------------------------------------------------------------- + --Update initials + -------------------------------------------------------------- + IF (@IsDebug = 1) + BEGIN + SELECT * FROM #tempInsert + END ELSE BEGIN + UPDATE gl + SET + SampledBudget01 = ti.BudgetAllocatedAmount01, + SampledBudget02 = ti.BudgetAllocatedAmount02, + SampledBudget03 = ti.BudgetAllocatedAmount03, + SampledBudget04 = ti.BudgetAllocatedAmount04, + SampledBudget05 = ti.BudgetAllocatedAmount05, + SampledBudget06 = ti.BudgetAllocatedAmount06, + SampledBudget07 = ti.BudgetAllocatedAmount07, + SampledBudget08 = ti.BudgetAllocatedAmount08, + SampledBudget09 = ti.BudgetAllocatedAmount09, + SampledBudget10 = ti.BudgetAllocatedAmount10, + SampledBudget11 = ti.BudgetAllocatedAmount11, + SampledBudget12 = ti.BudgetAllocatedAmount12, + InitialBudget01 = ti.BudgetAllocatedAmount01, + InitialBudget02 = ti.BudgetAllocatedAmount02, + InitialBudget03 = ti.BudgetAllocatedAmount03, + InitialBudget04 = ti.BudgetAllocatedAmount04, + InitialBudget05 = ti.BudgetAllocatedAmount05, + InitialBudget06 = ti.BudgetAllocatedAmount06, + InitialBudget07 = ti.BudgetAllocatedAmount07, + InitialBudget08 = ti.BudgetAllocatedAmount08, + InitialBudget09 = ti.BudgetAllocatedAmount09, + InitialBudget10 = ti.BudgetAllocatedAmount10, + InitialBudget11 = ti.BudgetAllocatedAmount11, + InitialBudget12 = ti.BudgetAllocatedAmount12 + FROM fp.GeneralLedger gl + INNER JOIN #tempInsert ti + ON gl.DepartmentID = ti.DepartmentID + AND gl.AccountID = ti.AccountID + AND gl.VariabilityID = ti.VariabilityID + WHERE + gl.APEModelSectionID = 4 + AND gl.BudgetConfigID = @BudgetConfigID + AND gl.EntityGroupConfigID = @EntityConfigID + END +END +GO + + +--------------------------------------------- + +-- fp.procReimbursementToGLCrosswalk_Projection +CREATE PROCEDURE [fp].[procReimbursementToGLCrosswalk_Projection] + @BudgetConfigID INT, + @BudgetConfigGUID UNIQUEIDENTIFIER, + @EntityConfigID INT, + @MonthsLoaded INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + + /************************************************************** + ** Change History + + ** CID Date Author WI Description + ** 1 2022-06-21 MD JAZZ-37249 Initial + ** 2 2022-08-16 MD JAZZ-42139 Update to handle new dimensionality + ** 3 2023-08-14 MD JAZZ-58776 Update for GL restructure + *************************************************************/ + + IF OBJECT_ID('tempdb..#contractualAllowances') IS NOT NULL DROP TABLE #contractualAllowances + IF OBJECT_ID('tempdb..#tmpReimbursementCharge') IS NOT NULL DROP TABLE #tmpReimbursementCharge + IF OBJECT_ID('tempdb..#tmpReimbursementEncounter') IS NOT NULL DROP TABLE #tmpReimbursementEncounter + IF OBJECT_ID('tempdb..#tmpConAllowanceCalc') IS NOT NULL DROP TABLE #tmpConAllowanceCalc + IF OBJECT_ID('tempdb..#uniqueDimensionality') IS NOT NULL DROP TABLE #uniqueDimensionality + IF OBJECT_ID('tempdb..#tempInsert') IS NOT NULL DROP TABLE #tempInsert + + + CREATE TABLE #tmpReimbursementCharge ( + PayorGroupID INT, + EntityID INT, + PatientClassID INT, + BudgetPhaseID TINYINT, + ProjectionChargeDollars01 DECIMAL (19,8), + ProjectionChargeDollars02 DECIMAL (19,8), + ProjectionChargeDollars03 DECIMAL (19,8), + ProjectionChargeDollars04 DECIMAL (19,8), + ProjectionChargeDollars05 DECIMAL (19,8), + ProjectionChargeDollars06 DECIMAL (19,8), + ProjectionChargeDollars07 DECIMAL (19,8), + ProjectionChargeDollars08 DECIMAL (19,8), + ProjectionChargeDollars09 DECIMAL (19,8), + ProjectionChargeDollars10 DECIMAL (19,8), + ProjectionChargeDollars11 DECIMAL (19,8), + ProjectionChargeDollars12 DECIMAL (19,8), + ProjectionNetReimbursement01 DECIMAL (19,8), + ProjectionNetReimbursement02 DECIMAL (19,8), + ProjectionNetReimbursement03 DECIMAL (19,8), + ProjectionNetReimbursement04 DECIMAL (19,8), + ProjectionNetReimbursement05 DECIMAL (19,8), + ProjectionNetReimbursement06 DECIMAL (19,8), + ProjectionNetReimbursement07 DECIMAL (19,8), + ProjectionNetReimbursement08 DECIMAL (19,8), + ProjectionNetReimbursement09 DECIMAL (19,8), + ProjectionNetReimbursement10 DECIMAL (19,8), + ProjectionNetReimbursement11 DECIMAL (19,8), + ProjectionNetReimbursement12 DECIMAL (19,8) + ) + + CREATE TABLE #tmpReimbursementEncounter ( + PayorGroupID INT, + EntityID INT, + PatientClassID INT, + BudgetPhaseID TINYINT, + ProjectionNetReimbursement01 DECIMAL (19,8), + ProjectionNetReimbursement02 DECIMAL (19,8), + ProjectionNetReimbursement03 DECIMAL (19,8), + ProjectionNetReimbursement04 DECIMAL (19,8), + ProjectionNetReimbursement05 DECIMAL (19,8), + ProjectionNetReimbursement06 DECIMAL (19,8), + ProjectionNetReimbursement07 DECIMAL (19,8), + ProjectionNetReimbursement08 DECIMAL (19,8), + ProjectionNetReimbursement09 DECIMAL (19,8), + ProjectionNetReimbursement10 DECIMAL (19,8), + ProjectionNetReimbursement11 DECIMAL (19,8), + ProjectionNetReimbursement12 DECIMAL (19,8) + ) + + CREATE TABLE #tmpConAllowanceCalc ( + PayorGroupID INT, + EntityID INT, + PatientClassID INT, + BudgetPhaseID TINYINT, + ProjectionConAllowance01 DECIMAL (19,8), + ProjectionConAllowance02 DECIMAL (19,8), + ProjectionConAllowance03 DECIMAL (19,8), + ProjectionConAllowance04 DECIMAL (19,8), + ProjectionConAllowance05 DECIMAL (19,8), + ProjectionConAllowance06 DECIMAL (19,8), + ProjectionConAllowance07 DECIMAL (19,8), + ProjectionConAllowance08 DECIMAL (19,8), + ProjectionConAllowance09 DECIMAL (19,8), + ProjectionConAllowance10 DECIMAL (19,8), + ProjectionConAllowance11 DECIMAL (19,8), + ProjectionConAllowance12 DECIMAL (19,8) + ) + + -------------------------------------------------------------- + --Get reimbursement contractual allowances config for given budget config + -------------------------------------------------------------- + SELECT + data.BudgetConfigGUID, + data.PayorGroupID, + data.EntityID, + data.PatientClassID, + data.DepartmentID, + data.AccountID, + sum(data.ProjectionAllocationPercent) AS ProjectionAllocationPercent, + sum(data.BudgetAllocationPercent) AS BudgetAllocationPercent + INTO #contractualAllowances + FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data + INNER JOIN [fp].[viewDeductionsAccounts] da on data.AccountID = da.AccountID + WHERE + data.BudgetConfigGUID = @BudgetConfigGUID + GROUP BY + data.BudgetConfigGUID, + data.PayorGroupID, + data.EntityID, + data.PatientClassID, + data.DepartmentID, + data.AccountID + + SELECT + data.PayorGroupID, + data.EntityID, + data.PatientClassID + INTO #uniqueDimensionality + FROM fp.ReimbursementToGeneralLedgerCrosswalkConfiguration data + INNER JOIN [fp].[viewDeductionsAccounts] da on data.AccountID = da.AccountID + WHERE + data.BudgetConfigGUID = @BudgetConfigGUID + GROUP BY + data.PayorGroupID, + data.EntityID, + data.PatientClassID + + -------------------------------------------------------------- + --Get reimbursement encounter data using CA dimensionality to group + -------------------------------------------------------------- + INSERT INTO #tmpReimbursementEncounter (PayorGroupID, EntityID, PatientClassID, BudgetPhaseID, + ProjectionNetReimbursement01, ProjectionNetReimbursement02, ProjectionNetReimbursement03, ProjectionNetReimbursement04, + ProjectionNetReimbursement05, ProjectionNetReimbursement06, ProjectionNetReimbursement07, ProjectionNetReimbursement08, + ProjectionNetReimbursement09, ProjectionNetReimbursement10, ProjectionNetReimbursement11, ProjectionNetReimbursement12 + ) + SELECT + ca.PayorGroupID, + ca.EntityID, + ca.PatientClassID, + frep.BudgetPhaseID, + sum(frep.AdjustedNetReimbursementValue01), + sum(frep.AdjustedNetReimbursementValue02), + sum(frep.AdjustedNetReimbursementValue03), + sum(frep.AdjustedNetReimbursementValue04), + sum(frep.AdjustedNetReimbursementValue05), + sum(frep.AdjustedNetReimbursementValue06), + sum(frep.AdjustedNetReimbursementValue07), + sum(frep.AdjustedNetReimbursementValue08), + sum(frep.AdjustedNetReimbursementValue09), + sum(frep.AdjustedNetReimbursementValue10), + sum(frep.AdjustedNetReimbursementValue11), + sum(frep.AdjustedNetReimbursementValue12) + FROM fp.FactReimbursementEncounter fre + INNER JOIN #uniqueDimensionality ca + ON fre.PayorGroupID = ca.PayorGroupID + AND fre.EntityID = ca.EntityID + AND fre.PatientClassID = ca.PatientClassID + INNER JOIN fp.FactReimbursementEncounterProjection frep + ON fre.ReimbursementEncounterID = frep.ReimbursementEncounterID + WHERE + fre.BudgetConfigID = @BudgetConfigID + AND fre.EntityGroupConfigID = @EntityConfigID + AND ca.PatientClassID > 0 + AND frep.BudgetPhaseID = 3 + GROUP BY + ca.PayorGroupID, + ca.EntityID, + ca.PatientClassID, + frep.BudgetPhaseID + + UNION ALL + + SELECT + ca.PayorGroupID, + ca.EntityID, + 0 AS PatientClassID, + frep.BudgetPhaseID, + sum(frep.AdjustedNetReimbursementValue01), + sum(frep.AdjustedNetReimbursementValue02), + sum(frep.AdjustedNetReimbursementValue03), + sum(frep.AdjustedNetReimbursementValue04), + sum(frep.AdjustedNetReimbursementValue05), + sum(frep.AdjustedNetReimbursementValue06), + sum(frep.AdjustedNetReimbursementValue07), + sum(frep.AdjustedNetReimbursementValue08), + sum(frep.AdjustedNetReimbursementValue09), + sum(frep.AdjustedNetReimbursementValue10), + sum(frep.AdjustedNetReimbursementValue11), + sum(frep.AdjustedNetReimbursementValue12) + FROM fp.FactReimbursementEncounter fre + INNER JOIN #uniqueDimensionality ca + ON fre.PayorGroupID = ca.PayorGroupID + AND fre.EntityID = ca.EntityID + INNER JOIN fp.FactReimbursementEncounterProjection frep + ON fre.ReimbursementEncounterID = frep.ReimbursementEncounterID + WHERE + fre.BudgetConfigID = @BudgetConfigID + AND fre.EntityGroupConfigID = @EntityConfigID + AND ca.PatientClassID = 0 + AND frep.BudgetPhaseID = 3 + GROUP BY + ca.PayorGroupID, + ca.EntityID, + frep.BudgetPhaseID + + -------------------------------------------------------------- + --Get reimbursement charge data using CA dimensionality to group + -------------------------------------------------------------- + INSERT INTO #tmpReimbursementCharge (PayorGroupID, EntityID, PatientClassID, BudgetPhaseID, + ProjectionNetReimbursement01, ProjectionNetReimbursement02, ProjectionNetReimbursement03, ProjectionNetReimbursement04, + ProjectionNetReimbursement05, ProjectionNetReimbursement06, ProjectionNetReimbursement07, ProjectionNetReimbursement08, + ProjectionNetReimbursement09, ProjectionNetReimbursement10, ProjectionNetReimbursement11, ProjectionNetReimbursement12, + ProjectionChargeDollars01, ProjectionChargeDollars02, ProjectionChargeDollars03, ProjectionChargeDollars04, + ProjectionChargeDollars05, ProjectionChargeDollars06, ProjectionChargeDollars07, ProjectionChargeDollars08, + ProjectionChargeDollars09, ProjectionChargeDollars10, ProjectionChargeDollars11, ProjectionChargeDollars12) + + SELECT + ca.PayorGroupID, + ca.EntityID, + ca.PatientClassID, + frcp.BudgetPhaseID, + sum(frcp.AdjustedNetReimbursementValue01), + sum(frcp.AdjustedNetReimbursementValue02), + sum(frcp.AdjustedNetReimbursementValue03), + sum(frcp.AdjustedNetReimbursementValue04), + sum(frcp.AdjustedNetReimbursementValue05), + sum(frcp.AdjustedNetReimbursementValue06), + sum(frcp.AdjustedNetReimbursementValue07), + sum(frcp.AdjustedNetReimbursementValue08), + sum(frcp.AdjustedNetReimbursementValue09), + sum(frcp.AdjustedNetReimbursementValue10), + sum(frcp.AdjustedNetReimbursementValue11), + sum(frcp.AdjustedNetReimbursementValue12), + sum(frcp.AdjustedChargeDollars01), + sum(frcp.AdjustedChargeDollars02), + sum(frcp.AdjustedChargeDollars03), + sum(frcp.AdjustedChargeDollars04), + sum(frcp.AdjustedChargeDollars05), + sum(frcp.AdjustedChargeDollars06), + sum(frcp.AdjustedChargeDollars07), + sum(frcp.AdjustedChargeDollars08), + sum(frcp.AdjustedChargeDollars09), + sum(frcp.AdjustedChargeDollars10), + sum(frcp.AdjustedChargeDollars11), + sum(frcp.AdjustedChargeDollars12) + FROM fp.FactReimbursementCharges frc + INNER JOIN #uniqueDimensionality ca + ON frc.PayorGroupID = ca.PayorGroupID + AND frc.EntityID = ca.EntityID + AND frc.PatientClassID = ca.PatientClassID + INNER JOIN fp.FactReimbursementChargesProjection frcp + ON frc.ReimbursementChargesID = frcp.ReimbursementChargesID + WHERE + frc.BudgetConfigID = @BudgetConfigID + AND frc.EntityGroupConfigID = @EntityConfigID + AND ca.PatientClassID > 0 + AND frcp.BudgetPhaseID = 3 + GROUP BY + ca.PayorGroupID, + ca.EntityID, + ca.PatientClassID, + frcp.BudgetPhaseID + + UNION ALL + + SELECT + ca.PayorGroupID, + ca.EntityID, + 0 AS PatientClassID, + frcp.BudgetPhaseID, + sum(frcp.AdjustedNetReimbursementValue01), + sum(frcp.AdjustedNetReimbursementValue02), + sum(frcp.AdjustedNetReimbursementValue03), + sum(frcp.AdjustedNetReimbursementValue04), + sum(frcp.AdjustedNetReimbursementValue05), + sum(frcp.AdjustedNetReimbursementValue06), + sum(frcp.AdjustedNetReimbursementValue07), + sum(frcp.AdjustedNetReimbursementValue08), + sum(frcp.AdjustedNetReimbursementValue09), + sum(frcp.AdjustedNetReimbursementValue10), + sum(frcp.AdjustedNetReimbursementValue11), + sum(frcp.AdjustedNetReimbursementValue12), + sum(frcp.AdjustedChargeDollars01), + sum(frcp.AdjustedChargeDollars02), + sum(frcp.AdjustedChargeDollars03), + sum(frcp.AdjustedChargeDollars04), + sum(frcp.AdjustedChargeDollars05), + sum(frcp.AdjustedChargeDollars06), + sum(frcp.AdjustedChargeDollars07), + sum(frcp.AdjustedChargeDollars08), + sum(frcp.AdjustedChargeDollars09), + sum(frcp.AdjustedChargeDollars10), + sum(frcp.AdjustedChargeDollars11), + sum(frcp.AdjustedChargeDollars12) + FROM fp.FactReimbursementCharges frc + INNER JOIN #uniqueDimensionality ca + ON frc.PayorGroupID = ca.PayorGroupID + AND frc.EntityID = ca.EntityID + INNER JOIN fp.FactReimbursementChargesProjection frcp + ON frc.ReimbursementChargesID = frcp.ReimbursementChargesID + WHERE + frc.BudgetConfigID = @BudgetConfigID + AND frc.EntityGroupConfigID = @EntityConfigID + AND ca.PatientClassID = 0 + AND frcp.BudgetPhaseID = 3 + GROUP BY + ca.PayorGroupID, + ca.EntityID, + frcp.BudgetPhaseID + + -------------------------------------------------------------- + --Do allocation calculation + --ChargeDollarsXX - ChargeNetReimbursementXX - EncounterNetReimbursementXX + -------------------------------------------------------------- + INSERT INTO #tmpConAllowanceCalc(PayorGroupID, EntityID, PatientClassID, + ProjectionConAllowance01, ProjectionConAllowance02, ProjectionConAllowance03, ProjectionConAllowance04, + ProjectionConAllowance05, ProjectionConAllowance06, ProjectionConAllowance07, ProjectionConAllowance08, + ProjectionConAllowance09, ProjectionConAllowance10, ProjectionConAllowance11, ProjectionConAllowance12) + SELECT + tc.PayorGroupID, + tc.EntityID, + tc.PatientClassID, + ISNULL(tc.ProjectionChargeDollars01,0) - ISNULL(tc.ProjectionNetReimbursement01,0) - ISNULL(te.ProjectionNetReimbursement01,0) AS ProjectionConAllowance01, + ISNULL(tc.ProjectionChargeDollars02,0) - ISNULL(tc.ProjectionNetReimbursement02,0) - ISNULL(te.ProjectionNetReimbursement02,0) AS ProjectionConAllowance02, + ISNULL(tc.ProjectionChargeDollars03,0) - ISNULL(tc.ProjectionNetReimbursement03,0) - ISNULL(te.ProjectionNetReimbursement03,0) AS ProjectionConAllowance03, + ISNULL(tc.ProjectionChargeDollars04,0) - ISNULL(tc.ProjectionNetReimbursement04,0) - ISNULL(te.ProjectionNetReimbursement04,0) AS ProjectionConAllowance04, + ISNULL(tc.ProjectionChargeDollars05,0) - ISNULL(tc.ProjectionNetReimbursement05,0) - ISNULL(te.ProjectionNetReimbursement05,0) AS ProjectionConAllowance05, + ISNULL(tc.ProjectionChargeDollars06,0) - ISNULL(tc.ProjectionNetReimbursement06,0) - ISNULL(te.ProjectionNetReimbursement06,0) AS ProjectionConAllowance06, + ISNULL(tc.ProjectionChargeDollars07,0) - ISNULL(tc.ProjectionNetReimbursement07,0) - ISNULL(te.ProjectionNetReimbursement07,0) AS ProjectionConAllowance07, + ISNULL(tc.ProjectionChargeDollars08,0) - ISNULL(tc.ProjectionNetReimbursement08,0) - ISNULL(te.ProjectionNetReimbursement08,0) AS ProjectionConAllowance08, + ISNULL(tc.ProjectionChargeDollars09,0) - ISNULL(tc.ProjectionNetReimbursement09,0) - ISNULL(te.ProjectionNetReimbursement09,0) AS ProjectionConAllowance09, + ISNULL(tc.ProjectionChargeDollars10,0) - ISNULL(tc.ProjectionNetReimbursement10,0) - ISNULL(te.ProjectionNetReimbursement10,0) AS ProjectionConAllowance10, + ISNULL(tc.ProjectionChargeDollars11,0) - ISNULL(tc.ProjectionNetReimbursement11,0) - ISNULL(te.ProjectionNetReimbursement11,0) AS ProjectionConAllowance11, + ISNULL(tc.ProjectionChargeDollars12,0) - ISNULL(tc.ProjectionNetReimbursement12,0) - ISNULL(te.ProjectionNetReimbursement12,0) AS ProjectionConAllowance12 + FROM #tmpReimbursementCharge tc + FULL JOIN #tmpReimbursementEncounter te + ON tc.PayorGroupID = te.PayorGroupID + AND tc.EntityID = te.EntityID + AND tc.PatientClassID = te.PatientClassID + + -------------------------------------------------------------- + --Insert into temp table + --Using this intermediary step to sum up unique PG/E/PC's that flex to the same department/account in GL + -------------------------------------------------------------- + SELECT + gl.DepartmentID, + gl.AccountID, + gl.VariabilityID, + SUM(CASE WHEN @MonthsLoaded >= 1 THEN gl.ProjectionAdjusted01 + ELSE calc.ProjectionConAllowance01 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance01, + SUM(CASE WHEN @MonthsLoaded >= 2 THEN gl.ProjectionAdjusted02 + ELSE calc.ProjectionConAllowance02 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance02, + SUM(CASE WHEN @MonthsLoaded >= 3 THEN gl.ProjectionAdjusted03 + ELSE calc.ProjectionConAllowance03 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance03, + SUM(CASE WHEN @MonthsLoaded >= 4 THEN gl.ProjectionAdjusted04 + ELSE calc.ProjectionConAllowance04 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance04, + SUM(CASE WHEN @MonthsLoaded >= 5 THEN gl.ProjectionAdjusted05 + ELSE calc.ProjectionConAllowance05 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance05, + SUM(CASE WHEN @MonthsLoaded >= 6 THEN gl.ProjectionAdjusted06 + ELSE calc.ProjectionConAllowance06 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance06, + SUM(CASE WHEN @MonthsLoaded >= 7 THEN gl.ProjectionAdjusted07 + ELSE calc.ProjectionConAllowance07 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance07, + SUM(CASE WHEN @MonthsLoaded >= 8 THEN gl.ProjectionAdjusted08 + ELSE calc.ProjectionConAllowance08 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance08, + SUM(CASE WHEN @MonthsLoaded >= 9 THEN gl.ProjectionAdjusted09 + ELSE calc.ProjectionConAllowance09 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance09, + SUM(CASE WHEN @MonthsLoaded >= 10 THEN gl.ProjectionAdjusted10 + ELSE calc.ProjectionConAllowance10 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance10, + SUM(CASE WHEN @MonthsLoaded >= 11 THEN gl.ProjectionAdjusted11 + ELSE calc.ProjectionConAllowance11 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance11, + SUM(CASE WHEN @MonthsLoaded >= 12 THEN gl.ProjectionAdjusted12 + ELSE calc.ProjectionConAllowance12 * ca.ProjectionAllocationPercent END) AS ProjectionAllowance12 + INTO #tempInsert + FROM fp.GeneralLedger gl + INNER JOIN #contractualAllowances ca + ON ca.DepartmentID = gl.DepartmentID + AND ca.AccountID = gl.AccountID + INNER JOIN #tmpConAllowanceCalc calc + ON ca.PayorGroupID = calc.PayorGroupID + AND ca.EntityID = calc.EntityID + AND ca.PatientClassID = calc.PatientClassID + WHERE + gl.APEModelSectionID = 4 + AND gl.BudgetConfigID = @BudgetConfigID + AND gl.EntityGroupConfigID = @EntityConfigID + AND ca.ProjectionAllocationPercent <> 0 + AND gl.VariabilityID = 2 + GROUP BY + gl.DepartmentID, + gl.AccountID, + gl.VariabilityID + UNION ALL + SELECT + gl.DepartmentID, + gl.AccountID, + gl.VariabilityID, + SUM(CASE WHEN @MonthsLoaded >= 1 THEN gl.ProjectionAdjusted01 ELSE 0 END) AS ProjectionAllowance01, + SUM(CASE WHEN @MonthsLoaded >= 2 THEN gl.ProjectionAdjusted02 ELSE 0 END) AS ProjectionAllowance02, + SUM(CASE WHEN @MonthsLoaded >= 3 THEN gl.ProjectionAdjusted03 ELSE 0 END) AS ProjectionAllowance03, + SUM(CASE WHEN @MonthsLoaded >= 4 THEN gl.ProjectionAdjusted04 ELSE 0 END) AS ProjectionAllowance04, + SUM(CASE WHEN @MonthsLoaded >= 5 THEN gl.ProjectionAdjusted05 ELSE 0 END) AS ProjectionAllowance05, + SUM(CASE WHEN @MonthsLoaded >= 6 THEN gl.ProjectionAdjusted06 ELSE 0 END) AS ProjectionAllowance06, + SUM(CASE WHEN @MonthsLoaded >= 7 THEN gl.ProjectionAdjusted07 ELSE 0 END) AS ProjectionAllowance07, + SUM(CASE WHEN @MonthsLoaded >= 8 THEN gl.ProjectionAdjusted08 ELSE 0 END) AS ProjectionAllowance08, + SUM(CASE WHEN @MonthsLoaded >= 9 THEN gl.ProjectionAdjusted09 ELSE 0 END) AS ProjectionAllowance09, + SUM(CASE WHEN @MonthsLoaded >= 10 THEN gl.ProjectionAdjusted10 ELSE 0 END) AS ProjectionAllowance10, + SUM(CASE WHEN @MonthsLoaded >= 11 THEN gl.ProjectionAdjusted11 ELSE 0 END) AS ProjectionAllowance11, + SUM(CASE WHEN @MonthsLoaded >= 12 THEN gl.ProjectionAdjusted12 ELSE 0 END) AS ProjectionAllowance12 + FROM fp.GeneralLedger gl + INNER JOIN #contractualAllowances ca + ON ca.DepartmentID = gl.DepartmentID + AND ca.AccountID = gl.AccountID + INNER JOIN #tmpConAllowanceCalc calc + ON ca.PayorGroupID = calc.PayorGroupID + AND ca.EntityID = calc.EntityID + AND ca.PatientClassID = calc.PatientClassID + WHERE + gl.APEModelSectionID = 4 + AND gl.BudgetConfigID = @BudgetConfigID + AND gl.EntityGroupConfigID = @EntityConfigID + AND ca.ProjectionAllocationPercent <> 0 + AND gl.VariabilityID = 1 + GROUP BY + gl.DepartmentID, + gl.AccountID, + gl.VariabilityID + + -------------------------------------------------------------- + --Update projection table + -------------------------------------------------------------- + IF (@IsDebug = 1) + BEGIN + SELECT * FROM #tempInsert + END ELSE BEGIN + UPDATE gl + SET + ProjectionLockFlag = 1, + ProjectionLockType = 3, + ProjectionAdjusted01 = ti.ProjectionAllowance01, + ProjectionAdjusted02 = ti.ProjectionAllowance02, + ProjectionAdjusted03 = ti.ProjectionAllowance03, + ProjectionAdjusted04 = ti.ProjectionAllowance04, + ProjectionAdjusted05 = ti.ProjectionAllowance05, + ProjectionAdjusted06 = ti.ProjectionAllowance06, + ProjectionAdjusted07 = ti.ProjectionAllowance07, + ProjectionAdjusted08 = ti.ProjectionAllowance08, + ProjectionAdjusted09 = ti.ProjectionAllowance09, + ProjectionAdjusted10 = ti.ProjectionAllowance10, + ProjectionAdjusted11 = ti.ProjectionAllowance11, + ProjectionAdjusted12 = ti.ProjectionAllowance12 + FROM fp.GeneralLedger gl + INNER JOIN #tempInsert ti + ON gl.DepartmentID = ti.DepartmentID + AND gl.AccountID = ti.AccountID + AND gl.VariabilityID = ti.VariabilityID + WHERE + gl.APEModelSectionID = 4 + AND gl.BudgetConfigID = @BudgetConfigID + AND gl.EntityGroupConfigID = @EntityConfigID + AND gl.VariabilityID = 2 + + UPDATE gl + SET + ProjectionLockFlag = 1, + ProjectionLockType = 3, + ProjectionAdjusted01 = CASE WHEN @MonthsLoaded >= 1 THEN gl.ProjectionAdjusted01 ELSE 0 END, + ProjectionAdjusted02 = CASE WHEN @MonthsLoaded >= 2 THEN gl.ProjectionAdjusted02 ELSE 0 END, + ProjectionAdjusted03 = CASE WHEN @MonthsLoaded >= 3 THEN gl.ProjectionAdjusted03 ELSE 0 END, + ProjectionAdjusted04 = CASE WHEN @MonthsLoaded >= 4 THEN gl.ProjectionAdjusted04 ELSE 0 END, + ProjectionAdjusted05 = CASE WHEN @MonthsLoaded >= 5 THEN gl.ProjectionAdjusted05 ELSE 0 END, + ProjectionAdjusted06 = CASE WHEN @MonthsLoaded >= 6 THEN gl.ProjectionAdjusted06 ELSE 0 END, + ProjectionAdjusted07 = CASE WHEN @MonthsLoaded >= 7 THEN gl.ProjectionAdjusted07 ELSE 0 END, + ProjectionAdjusted08 = CASE WHEN @MonthsLoaded >= 8 THEN gl.ProjectionAdjusted08 ELSE 0 END, + ProjectionAdjusted09 = CASE WHEN @MonthsLoaded >= 9 THEN gl.ProjectionAdjusted09 ELSE 0 END, + ProjectionAdjusted10 = CASE WHEN @MonthsLoaded >= 10 THEN gl.ProjectionAdjusted10 ELSE 0 END, + ProjectionAdjusted11 = CASE WHEN @MonthsLoaded >= 11 THEN gl.ProjectionAdjusted11 ELSE 0 END, + ProjectionAdjusted12 = CASE WHEN @MonthsLoaded >= 12 THEN gl.ProjectionAdjusted12 ELSE 0 END + FROM fp.GeneralLedger gl + INNER JOIN #tempInsert ti + ON gl.DepartmentID = ti.DepartmentID + AND gl.AccountID = ti.AccountID + AND gl.VariabilityID = ti.VariabilityID + WHERE + gl.APEModelSectionID = 4 + AND gl.BudgetConfigID = @BudgetConfigID + AND gl.EntityGroupConfigID = @EntityConfigID + AND gl.VariabilityID = 1 + END +END +GO + + +--------------------------------------------- + +-- fp.procRemoveCategoryForSetting +CREATE PROCEDURE [fp].[procRemoveCategoryForSetting] + @CategoryName NVARCHAR(100), + @SettingName NVARCHAR(100) +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 10-18-2022 MY Felt Like it Initial Creation + *************************************************************/ + + DECLARE @CategoryID INT = (SELECT CategoryID FROM fp.DimCategory WHERE Category = @CategoryName) + + DECLARE @SystemSettingID INT = (SELECT SystemSettingID FROM fp.SystemSetting WHERE Name = @SettingName) + IF (@SystemSettingID IS NOT NULL) + BEGIN + DELETE FROM fp.SettingCategory WHERE CategoryID = @CategoryID AND SystemSettingID = @SystemSettingID + END + + SET @SystemSettingID = (SELECT SettingID FROM fp.BudgetConfigDefaultSetting WHERE Name = @SettingName) + IF (@SystemSettingID IS NOT NULL) + BEGIN + DELETE FROM fp.SettingCategory WHERE CategoryID = @CategoryID AND BudgetConfigDefaultSettingID = @SystemSettingID + END +END +GO + + +--------------------------------------------- + +-- fp.procRemoveDataByStatisticsModel +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2024-01-17 mdeboer JAZZ-64957 Initial +***************************************************************/ +CREATE PROC fp.procRemoveDataByStatisticsModel + @BudgetConfigID INT, + @EntityGroupConfigID INT +AS +BEGIN + DECLARE @StatsModelType SMALLINT + SELECT @StatsModelType = StatisticsModel FROM fp.EntityGroupConfig WHERE EntityGroupConfigID = @EntityGroupConfigID + + IF OBJECT_ID('tempdb..#IDs') IS NOT NULL DROP TABLE #IDs + CREATE TABLE #IDs (ID INT) + + --StatModelType = 0 -> SLE_CV_ACCT + --Delete SLE data if stat model type <> 0 + IF(@StatsModelType <> 0) + BEGIN + INSERT INTO #IDs (ID) + SELECT + sle.ServiceLineEncounterID + FROM fp.ServiceLineEncounter sle + WHERE + sle.BudgetConfigID = @BudgetConfigID + AND sle.EntityGroupConfigID = @EntityGroupConfigID + + DELETE sle + FROM fp.ServiceLineEncounter sle + JOIN #IDs id on sle.ServiceLineEncounterID = id.ID + END + + TRUNCATE TABLE #IDs + + --StatModelType = 1 -> CV_ACCT + --Delete CV data if stat model type = 2 + IF(@StatsModelType = 2) + BEGIN + INSERT INTO #IDs (ID) + SELECT + cv.ChargeVolumeID + FROM fp.ChargeVolume cv + WHERE + cv.BudgetConfigID = @BudgetConfigID + AND cv.EntityGroupConfigID = @EntityGroupConfigID + + DELETE cv + FROM fp.ChargeVolume cv + JOIN #IDs id on cv.ChargeVolumeID = id.ID + END +END +GO + + +--------------------------------------------- + +-- fp.procReportAdjustmentHistory_Benefits +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2024-10-15 NH JAZZ-74988 Adjustment history report + *************************************************************/ + +CREATE PROCEDURE fp.procReportAdjustmentHistory_Benefits ( + @BudgetConfigID INT +) +AS +BEGIN + +EXEC [dbo].[procSysDropTempTable] '#src' +EXEC [dbo].[procSysDropTempTable] '#adjustments' +EXEC [dbo].[procSysDropTempTable] '#importAdjustments' + +CREATE TABLE #src ( + BudgetConfigID INT, + SectionID INT, + AdjustmentID INT, + AdjustmentType TINYINT, + Months NVARCHAR(50), + AdjustmentValue NVARCHAR(MAX), + AdjustedLevel NVARCHAR(MAX), + UnitTypeID TINYINT, + TimeClassID TINYINT, + LastModifiedDateUtc DATETIME, + DateCreatedUtc DATETIME, + Comment NVARCHAR(MAX), + AuthorFullName NVARCHAR(260), + ClassificationGroupID INT, + ClassificationCategoryID INT, + IsErrored BIT, + IsRecordDeleted BIT +) + +CREATE TABLE #adjustments ( + AdjustmentID INT +) + +DECLARE @BudgetGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID) +DECLARE @SectionID INT = 7 +DECLARE @PlanSectionID INT = 5 + +---------------------------------------------------------------------- +--Get all adjustments +---------------------------------------------------------------------- +INSERT INTO #adjustments +SELECT adj.AdjustmentID +FROM fp.BenefitsAdjustment adj WITH (NOLOCK) +LEFT JOIN fp.FactReportAdjustmentHistory frah ON adj.AdjustmentID = frah.AdjustmentID AND frah.SectionID = @SectionID +WHERE adj.BudgetConfigGUID = @BudgetGUID + AND ( + (adj.GroupingGUID = '00000000-0000-0000-0000-000000000000' AND adj.AdjustmentType IN (0, 2, 3)) -- filter roll up adjustments + OR adj.AdjustmentType IN (1, 4, 10, 11, 12, 13, 14) + ) + AND (adj.LastModifiedDateUtc <> frah.LastModifiedDateUtc + OR frah.LastModifiedDateUtc is NULL) + +CREATE CLUSTERED INDEX PK_SecuredAdjustmnets ON #adjustments (AdjustmentID) + +---------------------------------------------------------------------- +--Get import adjustments +---------------------------------------------------------------------- + +SELECT AdjustmentID, + COUNT(DISTINCT DepartmentID) AS DepartmentCount, + MAX(DepartmentID) AS DepartmentID, + TimeClassID, + UnitTypeID, + COUNT(DISTINCT FiscalMonthID) AS FiscalMonthCount, + MAX(FiscalMonthID) AS FiscalMonthID, + COUNT(*) AS RecordsCount, + SUM(RecordValue) AS TotalValue + INTO #importAdjustments + FROM (SELECT iadj.AdjustmentID, + TimeClassID, + UnitTypeID, + DepartmentID, + CASE WHEN COUNT(DISTINCT FiscalMonthID) > 1 THEN 13 + ELSE MAX(FiscalMonthID) + END AS FiscalMonthID, + SUM(Value) AS RecordValue + FROM fp.BenefitsAdjustmentImport AS iadj WITH (NOLOCK) + JOIN #adjustments AS sadj ON sadj.AdjustmentID = iadj.AdjustmentID + GROUP BY iadj.AdjustmentID, + TimeClassID, + DepartmentID, + EntityID, + AccountID, + FinancialReportingID, + UnitTypeID) AS ImportRecord + GROUP BY AdjustmentID, + TimeClassID, + UnitTypeID + +CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentID, UnitTypeID) + +INSERT INTO #SRC( + BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted) + SELECT @BudgetConfigID, + @SectionID, + res.AdjustmentID, + res.AdjustmentType, + res.Months, + res.Value, + res.AdjustedLevel, + res.UnitTypeID, + fp.GetAdjustmentTimeClass(res.TimeClassID, res.BudgetPhaseID), + res.LastModifiedDateUtc, + res.DateCreatedUtc, + ISNULL(res.Comment, ''), + res.AuthorFullName, + res.ClassificationGroupID, + res.ClassificationCategoryID, + res.IsErrored, + res.IsRecordDeleted + FROM ( + SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount, + * + FROM ( + SELECT ROW_NUMBER() OVER (PARTITION BY adj.AdjustmentID ORDER BY adj.DateCreatedUtc DESC) AS RowNumber, + adj.AdjustmentID, + adj.BudgetConfigGUID, + adj.AdjustmentType, + fp.GetAdjustmentReportValue(adj.Value, adj.AdjustmentType) AS Value, + [fp].[GetAdjustmentPath](adj.AdjustmentFilterJSON, adj.GroupingHierarchyJSON, @PlanSectionID) AS AdjustedLevel, + ISNULL(dfm.Name, 'All') AS Months, + adj.Comment, + adj.AuthorFullName, + adj.LastModifiedDateUtc, + adj.DateCreatedUtc, + adj.TimeClassID, + adj.BudgetPhaseID, + adj.ClassificationGroupID, + adj.ClassificationCategoryID, + adj.UnitTypeID, + adj.IsRecordDeleted, + adj.IsErrored + FROM fp.BenefitsAdjustment AS adj WITH (NOLOCK) + JOIN #adjustments AS adjs ON adjs.AdjustmentID = adj.AdjustmentID + LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) ON dfm.FiscalMonthID = TRY_CAST(SUBSTRING(AdjustedProperty, PATINDEX('%[0-9]%', AdjustedProperty), LEN(AdjustedProperty)) AS INT) + WHERE adj.AdjustmentType IN (0, 2, 1, 3, 10, 11, 12, 13, 14) + AND (adj.GroupingGUID = '00000000-0000-0000-0000-000000000000' + OR adj.AdjustmentType IN (12, 13, 14)) + UNION ALL + + SELECT ROW_NUMBER() OVER (PARTITION BY adj.AdjustmentID ORDER BY adj.DateCreatedUtc DESC) AS RowNumber, + adj.AdjustmentID, + adj.BudgetConfigGUID, + adj.AdjustmentType, + CASE WHEN iadj.RecordsCount = 1 AND iadj.UnitTypeID IN (144, 170, 171) THEN '1 record affected' + WHEN iadj.RecordsCount = 1 THEN fp.GetAdjustmentReportValue(TotalValue, adj.AdjustmentType) + ELSE CAST(iadj.RecordsCount AS VARCHAR(30)) + ' records affected' + END AS [Value], + CASE WHEN iadj.DepartmentCount = 1 THEN d.Name + ELSE CAST(iadj.DepartmentCount AS VARCHAR(30)) + ' departments' + END AS AdjustedLevel, + CASE WHEN iadj.FiscalMonthCount = 1 THEN ISNULL(dfm.Name, 'Multiple') + ELSE 'Multiple' + END AS Months, + ISNULL(ag.Description, adj.Comment) AS Comment, + adj.AuthorFullName, + adj.LastModifiedDateUtc, + adj.DateCreatedUtc, + iadj.TimeClassID, + adj.BudgetPhaseID, + adj.ClassificationGroupID, + adj.ClassificationCategoryID, + iadj.UnitTypeID, + adj.IsRecordDeleted, + adj.IsErrored + FROM fp.BenefitsAdjustment AS adj WITH (NOLOCK) + JOIN #importAdjustments AS iadj ON iadj.AdjustmentID = adj.AdjustmentID + JOIN fw.DimDepartment AS d WITH (NOLOCK) ON iadj.DepartmentID = d.DepartmentID + LEFT JOIN fp.viewAdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = adj.GroupingGUID + LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) on iadj.FiscalMonthID = dfm.FiscalMonthID + WHERE adj.AdjustmentType = 4 + + ) AS res_inner + WHERE res_inner.RowNumber = 1 ) AS res + WHERE res.RowNumber = 1 + ORDER BY res.DateCreatedUtc DESC + +---------------------------------------------------------------------- +-- Insert data to reportTable +---------------------------------------------------------------------- + +;WITH TGT AS +( + SELECT BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted + FROM fp.FactReportAdjustmentHistory fr + WHERE fr.BudgetConfigID = @BudgetConfigID + AND fr.SectionID = @SectionID +) + MERGE TGT as target + USING #src AS source + ON ( + target.BudgetConfigID = source.BudgetConfigID + AND target.AdjustmentID = source.AdjustmentID + AND target.SectionID = source.SectionID + AND target.TimeClassID = source.TimeClassID + AND target.UnitTypeID = source.UnitTypeID + ) + WHEN MATCHED AND (target.LastModifiedDateUtc <> source.LastModifiedDateUtc) + THEN + UPDATE + SET target.LastModifiedDateUtc = source.LastModifiedDateUtc, + target.AdjustmentValue = source.AdjustmentValue, + target.IsErrored = source.IsErrored, + target.IsRecordDeleted = source.IsRecordDeleted, + target.ClassificationGroupID = source.ClassificationGroupID, + target.ClassificationCategoryID = source.ClassificationCategoryID, + target.Comment = source.Comment + + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted + ) + VALUES ( + source.BudgetConfigID, + source.SectionID, + source.AdjustmentID, + source.AdjustmentType, + source.Months, + source.AdjustmentValue, + source.AdjustedLevel, + source.UnitTypeID, + source.TimeClassID, + source.LastModifiedDateUtc, + source.DateCreatedUtc, + source.Comment, + source.AuthorFullName, + source.ClassificationGroupID, + source.ClassificationCategoryID, + source.IsErrored, + source.IsRecordDeleted + ); + +END +GO + + +--------------------------------------------- + +-- fp.procReportAdjustmentHistory_ChargeVolume +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2024-10-15 NH JAZZ-74988 Adjustment history report + *************************************************************/ +CREATE PROCEDURE fp.procReportAdjustmentHistory_ChargeVolume ( + @BudgetConfigID INT +) +AS +BEGIN + +EXEC [dbo].[procSysDropTempTable] '#src' +EXEC [dbo].[procSysDropTempTable] '#adjustments' +EXEC [dbo].[procSysDropTempTable] '#importAdjustments' + +CREATE TABLE #src ( + BudgetConfigID INT, + SectionID INT, + AdjustmentID INT, + AdjustmentType TINYINT, + Months NVARCHAR(50), + AdjustmentValue NVARCHAR(MAX), + AdjustedLevel NVARCHAR(MAX), + UnitTypeID TINYINT, + TimeClassID TINYINT, + LastModifiedDateUtc DATETIME, + DateCreatedUtc DATETIME, + Comment NVARCHAR(MAX), + AuthorFullName NVARCHAR(260), + ClassificationGroupID INT, + ClassificationCategoryID INT, + IsErrored BIT, + IsRecordDeleted BIT +) + +CREATE TABLE #adjustments ( + AdjustmentID INT +) + +DECLARE @BudgetGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID) +DECLARE @SectionID INT = 2 +DECLARE @PlanSectionID INT = 2 + +---------------------------------------------------------------------- +--Get all adjustments +---------------------------------------------------------------------- +INSERT INTO #adjustments +SELECT dcva.AdjustmentID +FROM fp.DepartmentChargeVolumeAdjustment dcva WITH (NOLOCK) +LEFT JOIN fp.FactReportAdjustmentHistory frah ON dcva.AdjustmentID = frah.AdjustmentID AND frah.SectionID = @SectionID +WHERE dcva.BudgetConfigGUID = @budgetGUID + AND ( + (dcva.GroupingGUID = '00000000-0000-0000-0000-000000000000' AND dcva.AdjustmentType IN (0, 2, 3)) -- filter roll up adjustments + OR dcva.AdjustmentType IN (1, 4, 12, 13, 14) + ) + AND (dcva.LastModifiedDateUtc <> frah.LastModifiedDateUtc + OR frah.LastModifiedDateUtc is NULL) + +CREATE CLUSTERED INDEX PK_SecuredAdjustments ON #adjustments (AdjustmentID) + +---------------------------------------------------------------------- +--Get import adjustments +---------------------------------------------------------------------- +SELECT AdjustmentID, + COUNT(DISTINCT DepartmentID) AS DepartmentCount, + MAX(DepartmentID) AS DepartmentID, + TimeClassID, + COUNT(DISTINCT FiscalMonthID) AS FiscalMonthCount, + MAX(FiscalMonthID) AS FiscalMonthID, + COUNT(*) AS RecordsCount, + SUM(RecordValue) AS TotalValue + INTO #importAdjustments + FROM (SELECT iadj.AdjustmentID, + TimeClassID, + DepartmentID, + CASE WHEN COUNT(DISTINCT FiscalMonthID)> 1 THEN 13 + ELSE MAX(FiscalMonthID) + END AS FiscalMonthID, + SUM(Value) AS RecordValue + FROM fp.DepartmentChargeAdjustmentImport AS iadj WITH (NOLOCK) + JOIN #adjustments AS sadj ON sadj.AdjustmentID = iadj.AdjustmentID + GROUP BY iadj.AdjustmentID, + TimeClassID, + DepartmentID, + ServiceLineID, + PatientClassID, + AgeCohortID, + MedicalSurgicalID, + ChargeCodeID, + ServiceEntityID, + MSDRGID, + UBRevCodeID, + PrimaryCPTID, + ServiceProviderID, + --ServiceProviderSpecialtyID, + PerformingProviderID, + --PerformingProviderSpecialtyID, + BillingCPTID + --EntityID + ) AS ImportRecord + GROUP BY AdjustmentID, + TimeClassID + +CREATE CLUSTERED INDEX PK_ImportAdjustments ON #importAdjustments (AdjustmentID) + +INSERT INTO #SRC + (BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted) + SELECT @BudgetConfigID, + @SectionID, + res.AdjustmentID, + res.AdjustmentType, + res.Months, + res.[Value], + res.AdjustedLevel, + res.UnitTypeID, + fp.GetAdjustmentTimeClass(res.TimeClassID, res.BudgetPhaseID), + res.LastModifiedDateUtc, + res.DateCreatedUtc, + ISNULL(res.Comment, ''), + res.AuthorFullName, + res.ClassificationGroupID, + res.ClassificationCategoryID, + res.IsErrored, + res.IsRecordDeleted + FROM ( + SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount, + * + FROM ( + SELECT ROW_NUMBER() OVER (PARTITION BY dcva.AdjustmentID ORDER BY dcva.DateCreatedUtc DESC) AS RowNumber, + dcva.AdjustmentID, + dcva.AdjustmentType, + fp.GetAdjustmentReportValue(dcva.Value, dcva.AdjustmentType) AS Value, + fp.GetAdjustmentPath(dcva.AdjustmentFilterJSON, dcva.GroupingHierarchyJSON, @PlanSectionID) AS AdjustedLevel, + ISNULL(dfm.Name, 'All') AS Months, + dcva.Comment, + dcva.AuthorFullName, + dcva.LastModifiedDateUtc, + dcva.DateCreatedUtc, + dcva.TimeClassID, + CAST(2 AS TINYINT) AS BudgetPhaseID, + dcva.ClassificationGroupID, + dcva.ClassificationCategoryID, + CAST(145 AS TINYINT) AS UnitTypeID, + dcva.IsRecordDeleted, + dcva.IsErrored + FROM fp.DepartmentChargeVolumeAdjustment AS dcva WITH (NOLOCK) + JOIN #adjustments AS adj ON adj.AdjustmentID = dcva.AdjustmentID + LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) ON dfm.FiscalMonthID = TRY_CAST(SUBSTRING(AdjustedProperty, PATINDEX('%[0-9]%', AdjustedProperty), LEN(AdjustedProperty)) AS INT) + WHERE dcva.AdjustmentType <> 4 + + UNION ALL + + -- Import Adjustments + SELECT ROW_NUMBER() OVER (PARTITION BY dcva.AdjustmentID ORDER BY dcva.DateCreatedUtc DESC) AS RowNumber, + dcva.AdjustmentID, + dcva.AdjustmentType, + CASE WHEN sai.RecordsCount = 1 THEN fp.GetAdjustmentReportValue(TotalValue, dcva.AdjustmentType) + ELSE CAST(sai.RecordsCount AS VARCHAR(30)) + ' records affected' + END AS [Value], + CASE WHEN sai.DepartmentCount = 1 THEN d.Name + ELSE CAST(sai.DepartmentCount AS VARCHAR(30)) + ' departments' + END AS AdjustedLevel, + CASE WHEN sai.FiscalMonthCount = 1 THEN ISNULL(dfm.Name, 'Multiple') + ELSE 'Multiple' + END AS Months, + ISNULL(ag.Description, dcva.Comment) AS Comment, + dcva.AuthorFullName, + dcva.LastModifiedDateUtc, + dcva.DateCreatedUtc, + sai.TimeClassID, + CAST(2 AS TINYINT), + dcva.ClassificationGroupID, + dcva.ClassificationCategoryID, + CAST(145 AS TINYINT) AS UnitTypeID, + dcva.IsRecordDeleted, + dcva.IsErrored + FROM fp.DepartmentChargeVolumeAdjustment AS dcva WITH (NOLOCK) + JOIN #importAdjustments AS sai ON sai.AdjustmentID = dcva.AdjustmentID + JOIN fw.DimDepartment AS d WITH (NOLOCK) ON sai.DepartmentID = d.DepartmentID + LEFT JOIN fp.AdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = dcva.GroupingGUID + LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) on sai.FiscalMonthID = dfm.FiscalMonthID + WHERE dcva.AdjustmentType = 4 + + ) AS res_inner + WHERE res_inner.RowNumber = 1 ) AS res + ORDER BY res.DateCreatedUtc DESC + +---------------------------------------------------------------------- +-- Insert data to reportTable +---------------------------------------------------------------------- +;WITH TGT AS +( + SELECT BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted + FROM fp.FactReportAdjustmentHistory fr + WHERE fr.BudgetConfigID = @BudgetConfigID + AND fr.SectionID = @SectionID +) + MERGE TGT AS target + USING #src AS source + ON ( + target.BudgetConfigID = source.BudgetConfigID + AND target.AdjustmentID = source.AdjustmentID + AND target.SectionID = source.SectionID + ) + WHEN MATCHED AND (target.LastModifiedDateUtc <> source.LastModifiedDateUtc) + THEN + UPDATE + SET target.LastModifiedDateUtc = source.LastModifiedDateUtc, + target.AdjustmentValue = source.AdjustmentValue, + target.IsErrored = source.IsErrored, + target.IsRecordDeleted = source.IsRecordDeleted, + target.ClassificationGroupID = source.ClassificationGroupID, + target.ClassificationCategoryID = source.ClassificationCategoryID, + target.Comment = source.Comment + + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted + ) + VALUES ( + source.BudgetConfigID, + source.SectionID, + source.AdjustmentID, + source.AdjustmentType, + source.Months, + source.AdjustmentValue, + source.AdjustedLevel, + source.UnitTypeID, + source.TimeClassID, + source.LastModifiedDateUtc, + source.DateCreatedUtc, + source.Comment, + source.AuthorFullName, + source.ClassificationGroupID, + source.ClassificationCategoryID, + source.IsErrored, + source.IsRecordDeleted + ); + +END +GO + + +--------------------------------------------- + +-- fp.procReportAdjustmentHistory_GeneralLedger +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2024-10-15 NH JAZZ-74988 Adjustment history report + *************************************************************/ +CREATE PROCEDURE fp.procReportAdjustmentHistory_GeneralLedger ( + @BudgetConfigID INT +) +AS +BEGIN + +EXEC [dbo].[procSysDropTempTable] '#src' +EXEC [dbo].[procSysDropTempTable] '#adjustments' +EXEC [dbo].[procSysDropTempTable] '#importAdjustments' + +CREATE TABLE #adjustments ( + AdjustmentID INT +) + +CREATE TABLE #src ( + BudgetConfigID INT, + SectionID INT, + AdjustmentID INT, + AdjustmentType TINYINT, + Months NVARCHAR(50), + AdjustmentValue NVARCHAR(MAX), + AdjustedLevel NVARCHAR(MAX), + UnitTypeID TINYINT, + TimeClassID TINYINT, + LastModifiedDateUtc DATETIME, + DateCreatedUtc DATETIME, + Comment NVARCHAR(MAX), + AuthorFullName NVARCHAR(260), + ClassificationGroupID INT, + ClassificationCategoryID INT, + IsErrored BIT, + IsRecordDeleted BIT, + IsSetValue BIT +) + +DECLARE @BudgetGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID) +DECLARE @SectionID INT = 8 +DECLARE @PlanSectionID INT = 6 + +---------------------------------------------------------------------- +--Get all adjustments +---------------------------------------------------------------------- +INSERT INTO #adjustments +SELECT gla.AdjustmentID +FROM fp.GeneralLedgerAdjustment gla WITH (NOLOCK) +LEFT JOIN fp.FactReportAdjustmentHistory frah ON gla.AdjustmentID = frah.AdjustmentID AND frah.SectionID = @SectionID +WHERE gla.BudgetConfigGUID = @budgetGUID + AND ( + (gla.GroupingGUID = '00000000-0000-0000-0000-000000000000' AND gla.AdjustmentType IN (0, 2, 3)) -- filter roll up adjustments + OR gla.AdjustmentType IN (1, 4, 8, 10, 11, 12, 13, 14, 16, 18, 19) + ) + AND (gla.LastModifiedDateUtc <> frah.LastModifiedDateUtc + OR frah.LastModifiedDateUtc is NULL) + +CREATE CLUSTERED INDEX PK_SecuredAdjustmnets ON #adjustments (AdjustmentID) + +---------------------------------------------------------------------- +--Get import adjustments +---------------------------------------------------------------------- +SELECT AdjustmentID, + COUNT(DISTINCT DepartmentID) AS DepartmentCount, + MAX(DepartmentID) AS DepartmentID, + TimeClassID, + BudgetPhaseID, + UnitTypeID, + COUNT(DISTINCT FiscalMonthID) AS FiscalMonthCount, + MAX(FiscalMonthID) AS FiscalMonthID, + COUNT(*) AS RecordsCount, + SUM(RecordValue) AS TotalValue + INTO #importAdjustments + FROM (SELECT iadj.AdjustmentID, + TimeClassID, + DepartmentID, + BudgetPhaseID, + ISNULL(ORIGINALUNITTYPEID, UnitTypeID) AS UnitTypeID, + CASE WHEN COUNT(DISTINCT FiscalMonthID)> 1 THEN 13 + ELSE MAX(FiscalMonthID) + END AS FiscalMonthID, + SUM(Value) AS RecordValue + FROM fp.GeneralLedgerAdjustmentImport AS iadj WITH (NOLOCK) + JOIN #adjustments AS sadj ON sadj.AdjustmentID = iadj.AdjustmentID + GROUP BY iadj.AdjustmentID, + TimeClassID, + BudgetPhaseID, + DepartmentID, + AccountID, + FinancialReportingID, + VariabilityID, + EntityID, + ISNULL(ORIGINALUNITTYPEID, UnitTypeID) + ) AS ImportRecord + GROUP BY AdjustmentID, + TimeClassID, + BudgetPhaseID, + UnitTypeID + +CREATE CLUSTERED INDEX PK_ImportAdjustments ON #importAdjustments (AdjustmentID, UnitTypeID) + + +INSERT INTO #SRC( + BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted, + IsSetValue) + SELECT @BudgetConfigID, + @SectionID, + res.AdjustmentID, + res.AdjustmentType, + res.Months, + res.[Value], + res.AdjustedLevel, + res.UnitTypeID, + fp.GetAdjustmentTimeClass(res.TimeClassID, res.BudgetPhaseID), + res.LastModifiedDateUtc, + res.DateCreatedUtc, + ISNULL(res.Comment, ''), + res.AuthorFullName, + res.ClassificationGroupID, + res.ClassificationCategoryID, + res.IsErrored, + res.IsRecordDeleted, + res.IsSetValue + FROM ( + SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount, + * + FROM ( + SELECT ROW_NUMBER() OVER (PARTITION BY gla.AdjustmentID ORDER BY gla.DateCreatedUtc DESC) AS RowNumber, + gla.AdjustmentID, + gla.AdjustmentType, + fp.GetAdjustmentReportValue(gla.Value, gla.AdjustmentType) AS Value, + [fp].[GetAdjustmentPath](gla.AdjustmentFilterJSON, gla.GroupingHierarchyJSON, @PlanSectionID) AS AdjustedLevel, + ISNULL(dfm.Name, 'All') AS Months, + gla.Comment, + gla.AuthorFullName, + gla.LastModifiedDateUtc, + gla.DateCreatedUtc, + gla.TimeClassID, + gla.BudgetPhaseID, + gla.ClassificationGroupID, + gla.ClassificationCategoryID, + gla.UnitTypeId, + gla.IsRecordDeleted, + gla.IsErrored, + 0 AS IsSetValue + FROM fp.GeneralLedgerAdjustment AS gla WITH (NOLOCK) + JOIN #adjustments AS glas ON glas.AdjustmentID = gla.AdjustmentID + LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) ON dfm.FiscalMonthID = TRY_CAST(SUBSTRING(AdjustedProperty, PATINDEX('%[0-9]%', AdjustedProperty), LEN(AdjustedProperty)) AS INT) + WHERE gla.AdjustmentType NOT IN (4, 16, 18, 19) + + UNION ALL + + -- Import Adjustments + SELECT ROW_NUMBER() OVER (PARTITION BY gla.AdjustmentID, sai.TimeClassID, sai.BudgetPhaseID, sai.UnitTypeId ORDER BY gla.DateCreatedUtc DESC) AS RowNumber, + gla.AdjustmentID, + gla.AdjustmentType, + CASE WHEN sai.RecordsCount = 1 AND sai.UnitTypeID = 33 THEN '1 record affected' + WHEN sai.RecordsCount = 1 THEN fp.GetAdjustmentReportValue(TotalValue, gla.AdjustmentType) + ELSE CAST(sai.RecordsCount AS VARCHAR(30)) + ' records affected' + END AS [Value], + CASE WHEN sai.DepartmentCount = 1 THEN d.Name + ELSE CAST(sai.DepartmentCount AS VARCHAR(30)) + ' departments' + END AS AdjustedLevel, + CASE WHEN sai.FiscalMonthCount = 1 THEN ISNULL(dfm.Name, 'Multiple') + ELSE 'Multiple' + END AS Months, + ISNULL(ag.Description, gla.Comment) AS Comment, + gla.AuthorFullName, + gla.LastModifiedDateUtc, + gla.DateCreatedUtc, + sai.TimeClassID, + sai.BudgetPhaseID, + gla.ClassificationGroupID, + gla.ClassificationCategoryID, + sai.UnitTypeId, + gla.IsRecordDeleted, + gla.IsErrored, + 0 AS IsSetValue + FROM fp.GeneralLedgerAdjustment AS gla WITH (NOLOCK) + JOIN #importAdjustments AS sai ON sai.AdjustmentID = gla.AdjustmentID + JOIN fw.DimDepartment AS d WITH (NOLOCK) ON sai.DepartmentID = d.DepartmentID + JOIN fp.viewAdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = gla.GroupingGUID + LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) ON sai.FiscalMonthID = dfm.FiscalMonthID + WHERE gla.AdjustmentType = 4 + + UNION ALL + + -- SubAccount Adjustments + SELECT ROW_NUMBER() OVER (PARTITION BY gla.AdjustmentID ORDER BY gla.DateCreatedUtc DESC) AS RowNumber, + gla.AdjustmentID, + gla.AdjustmentType, + CASE WHEN subAccountAdj.RecordsCount = 1 THEN fp.GetAdjustmentReportValue(TotalValue, gla.AdjustmentType) + ELSE CAST(subAccountAdj.RecordsCount AS VARCHAR(30)) + ' records affected' + END AS [Value], + CASE WHEN DepartmentCount = 1 THEN dept.Name + ELSE CAST(DepartmentCount AS VARCHAR(30)) + ' departments' + END AS AdjustedLevel, + 'Multiple' AS Months , + gla.Comment, + gla.AuthorFullName, + gla.LastModifiedDateUtc, + gla.DateCreatedUtc, + gla.TimeClassID, + gla.BudgetPhaseID, + gla.ClassificationGroupID, + gla.ClassificationCategoryID, + gla.UnitTypeId, + gla.IsRecordDeleted, + gla.IsErrored, + 0 AS IsSetValue + FROM fp.GeneralLedgerAdjustment AS gla WITH (NOLOCK) + JOIN #adjustments AS glas ON glas.AdjustmentID = gla.AdjustmentID + LEFT JOIN ( + SELECT + OBJ.AdjustmentID AS AdjustmentID + ,MAX(OBJ.DepartmentID) AS DepartmentID + ,COUNT(DISTINCT dept.DepartmentID) AS DepartmentCount + ,SUM(Value01) + SUM(Value02) +SUM(Value03) + SUM(Value04) + SUM(Value05) + SUM(Value06) + SUM(Value07) + SUM(Value08) + SUM(Value09) + SUM(Value10) + SUM(Value11) + SUM(Value12) AS TotalValue + ,COUNT(SubAccountItemizedID) AS RecordsCount + FROM fp.GeneralLedgerSubAccountItemizedAdjustment AS OBJ WITH (NOLOCK) + JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = OBJ.DepartmentID + WHERE 1=1 + GROUP BY OBJ.AdjustmentID + ) AS subAccountAdj ON subAccountAdj.AdjustmentID = gla.AdjustmentID + JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = subAccountAdj.DepartmentID + WHERE gla.AdjustmentType = 18 + + UNION ALL + + -- AddAccount Adj + SELECT ROW_NUMBER() OVER (PARTITION BY gla.AdjustmentID ORDER BY gla.DateCreatedUtc DESC) AS RowNumber, + gla.AdjustmentID, + gla.AdjustmentType, + CASE WHEN addAccountAdj.RecordsCount = 1 THEN '1 record affected' + ELSE CAST(addAccountAdj.RecordsCount AS VARCHAR(30)) + ' records affected' + END AS [Value], + CASE WHEN addAccountAdj.DepartmentCount = 1 THEN dept.Name + ELSE CAST(addAccountAdj.DepartmentCount AS VARCHAR(30)) + ' departments' + END AS AdjustedLevel, + 'All' AS Months, + CASE WHEN addAccountAdj.CommentsCount = 0 THEN '' + WHEN addAccountAdj.CommentsCount = 1 THEN addAccountAdj.Comment + ELSE 'Multiple Comments' + END AS Comment, + gla.AuthorFullName, + gla.LastModifiedDateUtc, + gla.DateCreatedUtc, + TimeClassID, + gla.BudgetPhaseID, + 0 AS ClassificationGroupID, + 0 AS ClassificationCategoryID, + 0 AS UnitTypeId, + gla.IsRecordDeleted, + gla.IsErrored, + 0 AS IsSetValue + FROM fp.GeneralLedgerAdjustment AS gla WITH (NOLOCK) + JOIN #adjustments AS glas ON glas.AdjustmentID = gla.AdjustmentID + LEFT JOIN ( + SELECT + OBJ.AdjustmentID AS AdjustmentID, + MAX(OBJ.DepartmentID) AS DepartmentID, + COUNT(DISTINCT DepartmentID) AS DepartmentCount, + STRING_AGG(CASE WHEN Comment <> '' THEN CAST(Comment AS NVARCHAR(MAX)) ELSE NULL END, ';') AS Comment, + SUM(CASE WHEN Comment <> '' THEN 1 ELSE 0 END) AS CommentsCount, + COUNT(RowID) AS RecordsCount + FROM fp.GeneralLedgerAddAccountAdjustment AS OBJ WITH (NOLOCK) + WHERE 1=1 + GROUP BY OBJ.AdjustmentID + ) AS addAccountAdj ON addAccountAdj.AdjustmentID = gla.AdjustmentID + JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = addAccountAdj.DepartmentID + WHERE gla.AdjustmentType = 19 + + UNION ALL + -- My Budget Adjustments + SELECT ROW_NUMBER() OVER (PARTITION BY gla.AdjustmentID, adjDetail.TimeClassID ORDER BY gla.DateCreatedUtc DESC) AS RowNumber, + gla.AdjustmentID, + gla.AdjustmentType, + CASE WHEN adjDetail.RecordsCount = 1 THEN fp.GetAdjustmentReportValue(TotalValue, gla.AdjustmentType) + ELSE CAST(adjDetail.RecordsCount as varchar(30)) + ' records affected' + END AS [Value], + dept.Name AS AdjustedLevel, + 'All' AS Months, + CASE WHEN adjDetail.CommentsCount = 0 THEN '' + WHEN adjDetail.CommentsCount = 1 THEN adjDetail.CommentTotal + ELSE 'Multiple Comments' + END AS Comment, + gla.AuthorFullName, + gla.LastModifiedDateUtc, + gla.DateCreatedUtc, + adjDetail.TimeClassID, + gla.BudgetPhaseID, + gla.ClassificationGroupID, + gla.ClassificationCategoryID, + 33, -- UNIT TYPE ID + gla.IsRecordDeleted, + gla.IsErrored, + adjDetail.IsSetValue + FROM fp.GeneralLedgerAdjustment AS gla WITH (NOLOCK) + JOIN #adjustments AS glas ON glas.AdjustmentID = gla.AdjustmentID + JOIN (SELECT AdjustmentID, + DepartmentID, + TimeClassID, + STRING_AGG(CASE WHEN Comment <> '' THEN CAST(Comment AS NVARCHAR(MAX)) ELSE NULL END, ';') AS CommentTotal, + COUNT(Comment) AS RecordsCount, + SUM(DollarsValue) AS TotalValue, + SUM(CASE WHEN Comment <> '' THEN 1 ELSE 0 END) AS CommentsCount, + 1 AS IsSetValue + FROM fp.GeneralLedgerVariableDetail WITH (NOLOCK) + GROUP BY AdjustmentID, DepartmentID, TimeClassID + ) AS adjDetail ON gla.AdjustmentID = adjDetail.AdjustmentID + JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = adjDetail.DepartmentID + WHERE AdjustmentType = 16 + + UNION ALL + + SELECT ROW_NUMBER() OVER (PARTITION BY gla.AdjustmentID, adjDetail.TimeClassID, adjDetail.IsMarkedForDeletion ORDER BY gla.DateCreatedUtc DESC) AS RowNumber, + gla.AdjustmentID, + gla.AdjustmentType, + CASE WHEN adjDetail.RecordsCount = 1 THEN fp.GetAdjustmentReportValue(TotalValue, gla.AdjustmentType) + ELSE CAST(adjDetail.RecordsCount as varchar(30)) + ' records affected' + END AS [Value], + dept.Name AS AdjustedLevel, + 'All' AS Months, + CASE WHEN adjDetail.CommentsCount = 0 THEN '' + WHEN adjDetail.CommentsCount = 1 THEN adjDetail.CommentTotal + ELSE 'Multiple Comments' + END AS Comment, + gla.AuthorFullName, + gla.LastModifiedDateUtc, + gla.DateCreatedUtc, + adjDetail.TimeClassID, + gla.BudgetPhaseID, + gla.ClassificationGroupID, + gla.ClassificationCategoryID, + 34, -- UNIT TYPE ID + adjDetail.IsMarkedForDeletion AS IsRecordDeleted, + gla.IsErrored, + adjDetail.IsSetValue + FROM fp.GeneralLedgerAdjustment AS gla WITH (NOLOCK) + JOIN #adjustments AS glas ON glas.AdjustmentID = gla.AdjustmentID + JOIN (SELECT AdjustmentID, + DepartmentID, + TimeClassID, + STRING_AGG(CASE WHEN Comment <> '' THEN CAST(Comment AS NVARCHAR(MAX)) ELSE NULL END, ';') AS CommentTotal, + COUNT(Comment) AS RecordsCount, + SUM(DollarsValue) AS TotalValue, + SUM(CASE WHEN Comment <> '' THEN 1 ELSE 0 END) AS CommentsCount, + IsSetValue, + IsMarkedForDeletion + FROM fp.GeneralLedgerFixedDetail WITH (NOLOCK) + GROUP BY AdjustmentID, DepartmentID, TimeClassID, IsSetValue, IsMarkedForDeletion + ) AS adjDetail ON gla.AdjustmentID = adjDetail.AdjustmentID + JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = adjDetail.DepartmentID + WHERE AdjustmentType = 16 + + ) AS res_inner + WHERE res_inner.RowNumber = 1 ) AS res + +---------------------------------------------------------------------- +-- Insert data to reportTable +---------------------------------------------------------------------- +;WITH TGT AS +( + SELECT BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted, + IsSetValue + FROM fp.FactReportAdjustmentHistory fr + WHERE fr.BudgetConfigID = @BudgetConfigID + AND fr.SectionID = @SectionID +) + MERGE TGT AS target + USING #src AS source + ON ( + target.BudgetConfigID = source.BudgetConfigID + AND target.AdjustmentID = source.AdjustmentID + AND target.SectionID = source.SectionID + AND target.TimeClassID = source.TimeClassID + AND target.UnitTypeID = source.UnitTypeID + ) + WHEN MATCHED AND (target.LastModifiedDateUtc <> source.LastModifiedDateUtc) + THEN + UPDATE + SET target.LastModifiedDateUtc = source.LastModifiedDateUtc, + target.AdjustmentValue = source.AdjustmentValue, + target.IsErrored = source.IsErrored, + target.IsRecordDeleted = source.IsRecordDeleted, + target.ClassificationGroupID = source.ClassificationGroupID, + target.ClassificationCategoryID = source.ClassificationCategoryID, + target.Comment = source.Comment + + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted, + IsSetValue + ) + VALUES ( + source.BudgetConfigID, + source.SectionID, + source.AdjustmentID, + source.AdjustmentType, + source.Months, + source.AdjustmentValue, + source.AdjustedLevel, + source.UnitTypeID, + source.TimeClassID, + source.LastModifiedDateUtc, + source.DateCreatedUtc, + source.Comment, + source.AuthorFullName, + source.ClassificationGroupID, + source.ClassificationCategoryID, + source.IsErrored, + source.IsRecordDeleted, + source.IsSetValue + ); + +END +GO + + +--------------------------------------------- + +-- fp.procReportAdjustmentHistory_ProviderCompensation +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2024-10-15 NH JAZZ-74988 Adjustment history report + *************************************************************/ + +CREATE PROCEDURE fp.procReportAdjustmentHistory_ProviderCompensation ( + @BudgetConfigID INT +) +AS +BEGIN + +EXEC [dbo].[procSysDropTempTable] '#src' +EXEC [dbo].[procSysDropTempTable] '#adjustments' +EXEC [dbo].[procSysDropTempTable] '#importAdjustments' + +CREATE TABLE #src ( + BudgetConfigID INT, + SectionID INT, + AdjustmentID INT, + AdjustmentType TINYINT, + Months NVARCHAR(50), + AdjustmentValue NVARCHAR(max), + AdjustedLevel NVARCHAR(max), + UnitTypeID TINYINT, + TimeClassID TINYINT, + LastModifiedDateUtc DATETIME, + DateCreatedUtc DATETIME, + Comment NVARCHAR(max), + AuthorFullName NVARCHAR(260), + ClassificationGroupID INT, + ClassificationCategoryID INT, + IsErrored BIT, + IsRecordDeleted BIT +) + +DECLARE @BudgetGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID) +DECLARE @SectionID INT = 6 +DECLARE @PlanSectionID INT = 4 + +---------------------------------------------------------------------- +-- Get all adjustments +---------------------------------------------------------------------- +SELECT slea.AdjustmentID +INTO #adjustments +FROM fp.StaffingAdjustment slea WITH (NOLOCK) +LEFT JOIN fp.FactReportAdjustmentHistory frah ON slea.AdjustmentID = frah.AdjustmentID AND frah.SectionID = @SectionID +WHERE slea.BudgetConfigGUID = @budgetGUID + AND slea.SubsectionID = 4 -- Provider + AND ( + (slea.GroupingGUID = '00000000-0000-0000-0000-000000000000' AND slea.AdjustmentType IN (0, 2, 3)) -- filter roll up adjustments + OR slea.AdjustmentType IN (1, 4, 8, 10, 11, 12, 13, 14, 15) + ) + AND (slea.LastModifiedDateUtc <> frah.LastModifiedDateUtc + OR frah.LastModifiedDateUtc is NULL) + +CREATE CLUSTERED INDEX PK_SecuredAdjustmnets ON #adjustments (AdjustmentID) + +---------------------------------------------------------------------- +--Get import adjustments +---------------------------------------------------------------------- +SELECT AdjustmentID, + COUNT(DISTINCT DepartmentID) AS DepartmentCount, + MAX(DepartmentID) AS DepartmentID, + TimeClassID, + UnitTypeID, + BudgetPhaseID, + COUNT(DISTINCT FiscalMonthID) AS FiscalMonthCount, + MAX(FiscalMonthID) AS FiscalMonthID, + COUNT(*) AS RecordsCount, + SUM(RecordValue) AS TotalValue + INTO #importAdjustments + FROM (SELECT iadj.AdjustmentID, + TimeClassID, + BudgetPhaseID, + ISNULL(ORIGINALUNITTYPEID, UnitTypeID) AS UnitTypeID, + DepartmentID, + CASE WHEN COUNT(DISTINCT FiscalMonthID) > 1 THEN 13 + ELSE MAX(FiscalMonthID) + END AS FiscalMonthID, + SUM(Value) AS RecordValue + FROM fp.StaffingAdjustmentImport AS iadj WITH (NOLOCK) + JOIN #adjustments AS sadj ON sadj.AdjustmentID = iadj.AdjustmentID + GROUP BY iadj.AdjustmentID, + TimeClassID, + BudgetPhaseID, + DepartmentID, + JobCodeID, + PayCodeGroupID, + --ProductiveClassID, Taken from PayCodeGroupID + VariabilityID, + --EntityID, Taken from Department + --EmployeeID, is zero for ProvComp + ProviderID, + --ProviderTypeID, Taken from provider + ProviderLineItemID, + --ProviderSpecialtyID, Taken from provider + ISNULL(ORIGINALUNITTYPEID, UnitTypeID) + ) AS ImportRecord + GROUP BY AdjustmentID, + TimeClassID, + BudgetPhaseID, + UnitTypeID + +-- Creating indexes for faster selection +CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentID, UnitTypeID) + +INSERT INTO #src + (BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted) + SELECT @BudgetConfigID, + @SectionID, + res.AdjustmentID, + res.AdjustmentType, + res.Months, + res.[Value], + res.AdjustedLevel, + res.UnitTypeID, + fp.GetAdjustmentTimeClass(res.TimeClassID, res.BudgetPhaseID), + res.LastModifiedDateUtc, + res.DateCreatedUtc, + res.Comment, + res.AuthorFullName, + res.ClassificationGroupID, + res.ClassificationCategoryID, + res.IsErrored, + res.IsRecordDeleted + FROM ( + SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount, + * + FROM ( + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber, + slea.AdjustmentID, + slea.BudgetConfigGUID, + slea.AdjustmentType, + fp.GetAdjustmentReportValue(slea.Value, slea.AdjustmentType) AS Value, + fp.GetAdjustmentPath(slea.AdjustmentFilterJSON, slea.GroupingHierarchyJSON, @PlanSectionID) AS AdjustedLevel, + ISNULL(dfm.Name, 'All') AS Months, + slea.Comment AS Comment, + slea.AuthorFullName, + slea.LastModifiedDateUtc, + slea.DateCreatedUtc, + slea.TimeClassID, + slea.BudgetPhaseID, + slea.ClassificationGroupID, + slea.ClassificationCategoryID, + slea.UnitTypeID, + slea.IsRecordDeleted, + slea.IsErrored + FROM fp.StaffingAdjustment AS slea WITH (NOLOCK) + JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID + LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) ON dfm.FiscalMonthID = TRY_CAST(SUBSTRING(AdjustedProperty, PATINDEX('%[0-9]%', AdjustedProperty), LEN(AdjustedProperty)) AS INT) + WHERE slea.AdjustmentType NOT IN (4, 15) + + --Import + UNION ALL + + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID, sai.TimeClassID, sai.BudgetPhaseID, sai.UnitTypeID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber, + slea.AdjustmentID, + slea.BudgetConfigGUID, + slea.AdjustmentType, + CASE WHEN sai.RecordsCount = 1 AND sai.UnitTypeID IN (144, 159) THEN '1 record affected' + WHEN sai.RecordsCount = 1 THEN fp.GetAdjustmentReportValue(TotalValue, slea.AdjustmentType) + ELSE CAST(sai.RecordsCount AS VARCHAR(30)) + ' records affected' + END AS [Value], + CASE WHEN sai.DepartmentCount = 1 THEN d.Name + ELSE CAST(sai.DepartmentCount AS VARCHAR(30)) + ' departments' + END AS AdjustedLevel, + CASE WHEN sai.FiscalMonthCount = 1 THEN ISNULL(dfm.Name, 'Multiple') + ELSE 'Multiple' + END AS Months, + ag.Description AS Comment, + slea.AuthorFullName, + slea.LastModifiedDateUtc, + slea.DateCreatedUtc, + sai.TimeClassID, + sai.BudgetPhaseID, + slea.ClassificationGroupID, + slea.ClassificationCategoryID, + sai.UnitTypeID, + slea.IsRecordDeleted, + slea.IsErrored + FROM fp.StaffingAdjustment AS slea WITH (NOLOCK) + JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID + JOIN #importAdjustments AS sai ON sai.AdjustmentID = slea.AdjustmentID + JOIN fw.DimDepartment AS d WITH (NOLOCK) ON sai.DepartmentID = d.DepartmentID + LEFT JOIN fp.AdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID + LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) on sai.FiscalMonthID = dfm.FiscalMonthID + WHERE slea.AdjustmentType = 4 + + -- Add Provider adjustment + UNION ALL + + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID, impact.TimeClassID, impact.BudgetPhaseID, impact.UnitTypeID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber, + slea.AdjustmentID, + slea.BudgetConfigGUID, + slea.AdjustmentType, + fp.GetAdjustmentReportValue(impact.ImpactValue, slea.AdjustmentType) AS Value, + phys.Physician AS AdjustedLevel, + 'Multiple' AS Months, + aps.Comment, + slea.AuthorFullName, + slea.LastModifiedDateUtc, + slea.DateCreatedUtc, + impact.TimeClassID, + impact.BudgetPhaseID, + aps.ClassificationGroupID, + aps.ClassificationCategoryID, + impact.UnitTypeID, + slea.IsRecordDeleted, + slea.IsErrored + FROM fp.StaffingAdjustment AS slea WITH (NOLOCK) + JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID + JOIN fp.StatisticAddProviderSummary AS aps ON aps.StaffingAdjustmentGUID = slea.AdjustmentGUID + JOIN (SELECT SummaryID, ProjectionImpact AS ImpactValue, UnitTypeID, 12 AS TimeClassID, 3 AS BudgetPhaseID FROM fp.ProvCompAddProviderSummaryDetails WITH (NOLOCK) + UNION ALL + SELECT SummaryID, COALESCE(NULLIF(BudgetImpact, 0), AnnualImpact) AS ImpactValue, UnitTypeID, 2 AS TimeClassID, 3 AS BudgetPhaseID FROM fp.ProvCompAddProviderSummaryDetails WITH (NOLOCK) + UNION ALL + SELECT SummaryID, COALESCE(NULLIF(TargetImpact, 0), COALESCE(NULLIF(BudgetImpact, 0), AnnualImpact)) AS ImpactValue, UnitTypeID, 2 AS TimeClassID, 2 AS BudgetPhaseID FROM fp.ProvCompAddProviderSummaryDetails WITH (NOLOCK) + ) AS impact ON aps.SummaryID = impact.SummaryID + JOIN (SELECT SummaryID, SUM(ProjectionImpact) AS StatisticsImpact, 12 AS TimeClassID, 3 AS BudgetPhaseID FROM fp.StatisticAddProviderSummaryDetails WITH (NOLOCK) GROUP BY SummaryID + UNION ALL + SELECT SummaryID, SUM(TargetImpact) AS StatisticsImpact, 2 AS TimeClassID, 2 AS BudgetPhaseID FROM fp.StatisticAddProviderSummaryDetails WITH (NOLOCK) GROUP BY SummaryID + UNION ALL + SELECT SummaryID, SUM(BudgetImpact) AS StatisticsImpact, 2 AS TimeClassID, 3 AS BudgetPhaseID FROM fp.StatisticAddProviderSummaryDetails WITH (NOLOCK) GROUP BY SummaryID) + AS apsd ON apsd.SummaryID = impact.SummaryID AND apsd.TimeClassID = impact.TimeClassID AND apsd.BudgetPhaseID = impact.BudgetPhaseID + JOIN dss.DimPhysician AS phys WITH (NOLOCK) ON phys.PhysicianID = aps.ProviderID + WHERE slea.AdjustmentType = 15 AND apsd.StatisticsImpact <> 0 AND impact.ImpactValue <> 0 + ) AS res_inner + WHERE res_inner.RowNumber = 1) AS res + ORDER BY res.DateCreatedUtc DESC + +---------------------------------------------------------------------- +-- Insert data to reportTable +---------------------------------------------------------------------- + +;WITH TGT AS +( + SELECT BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted + FROM fp.FactReportAdjustmentHistory fr + WHERE fr.BudgetConfigID = @BudgetConfigID + AND fr.SectionID = @SectionID +) + MERGE TGT as target + USING #src AS source + ON ( + target.BudgetConfigID = source.BudgetConfigID + AND target.AdjustmentID = source.AdjustmentID + AND target.SectionID = source.SectionID + AND target.TimeClassID = source.TimeClassID + AND target.UnitTypeID = source.UnitTypeID + ) + WHEN MATCHED AND (target.LastModifiedDateUtc <> source.LastModifiedDateUtc) + THEN + UPDATE + SET target.LastModifiedDateUtc = source.LastModifiedDateUtc, + target.AdjustmentValue = source.AdjustmentValue, + target.IsErrored = source.IsErrored, + target.IsRecordDeleted = source.IsRecordDeleted, + target.ClassificationGroupID = source.ClassificationGroupID, + target.ClassificationCategoryID = source.ClassificationCategoryID, + target.Comment = source.Comment + + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted + ) + VALUES ( + source.BudgetConfigID, + source.SectionID, + source.AdjustmentID, + source.AdjustmentType, + source.Months, + source.AdjustmentValue, + source.AdjustedLevel, + source.UnitTypeID, + source.TimeClassID, + source.LastModifiedDateUtc, + source.DateCreatedUtc, + source.Comment, + source.AuthorFullName, + source.ClassificationGroupID, + source.ClassificationCategoryID, + source.IsErrored, + source.IsRecordDeleted + ); +END +GO + + +--------------------------------------------- + +-- fp.procReportAdjustmentHistory_Reimbursement +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2024-10-15 NH JAZZ-74988 Adjustment history report + *************************************************************/ +CREATE PROCEDURE fp.procReportAdjustmentHistory_Reimbursement ( + @BudgetConfigID INT +) +AS +BEGIN + +EXEC [dbo].[procSysDropTempTable] '#src' +EXEC [dbo].[procSysDropTempTable] '#adjustments' + +DECLARE @BudgetGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID) +DECLARE @SectionID INT = 9 +DECLARE @PlanSectionID INT = 7 + +CREATE TABLE #src ( + BudgetConfigID INT, + SectionID INT, + AdjustmentID INT, + AdjustmentType TINYINT, + Months NVARCHAR(50), + AdjustmentValue NVARCHAR(MAX), + AdjustedLevel NVARCHAR(MAX), + UnitTypeID TINYINT, + TimeClassID TINYINT, + LastModifiedDateUtc DATETIME, + DateCreatedUtc DATETIME, + Comment NVARCHAR(MAX), + AuthorFullName NVARCHAR(260), + ClassificationGroupID INT, + ClassificationCategoryID INT, + IsErrored BIT, + IsRecordDeleted BIT +) + +---------------------------------------------------------------------- +--Get all adjustments +---------------------------------------------------------------------- +SELECT rgla.AdjustmentID +INTO #adjustments +FROM fp.ReimbursementAdjustment AS rgla WITH (NOLOCK) +LEFT JOIN fp.FactReportAdjustmentHistory frah ON rgla.AdjustmentID = frah.AdjustmentID AND frah.SectionID = @SectionID +WHERE rgla.BudgetConfigGUID = @BudgetGUID + AND rgla.BudgetPhaseID <> 2 + AND (rgla.GroupingGUID = '00000000-0000-0000-0000-000000000000' OR rgla.AdjustmentType = 4) + AND (rgla.LastModifiedDateUtc <> frah.LastModifiedDateUtc OR frah.LastModifiedDateUtc is NULL) + +CREATE CLUSTERED INDEX PK_Adjustments ON #adjustments (AdjustmentID) +---------------------------------------------------------------------- +--Get import adjustments +---------------------------------------------------------------------- +SELECT vrai.AdjustmentID, + vrai.UnitTypeID, + vrai.TimeClassID, + vrai.BudgetPhaseID, + MIN(PayorGroupCount) AS PayorGroupCount, + MIN(iadj.PayorGroupID) AS PayorGroupID, + MIN(FiscalMonthName) AS FiscalMonthName, + MIN(FiscalMonthCount) AS FiscalMonthCount, + COUNT(*) AS RecordsCount +INTO #importAdjustments +FROM fp.viewReimbursementAdjustmentImport vrai WITH (NOLOCK) +JOIN #adjustments AS adj ON vrai.AdjustmentID = adj.AdjustmentID +JOIN ( SELECT AdjustmentID, + COUNT(DISTINCT PayorGroupID) AS PayorGroupCount, + MAX(PayorGroupID) AS PayorGroupID, + UnitTypeID, + TimeClassID, + BudgetPhaseID, + COUNT(DISTINCT Name) AS FiscalMonthCount, + MAX(Name) AS FiscalMonthName + FROM fp.viewReimbursementAdjustmentImport rai WITH (NOLOCK) + UNPIVOT (Value For FiscalMonth IN (Value01, Value02, Value03,Value04, Value05, Value06, Value07,Value08, Value09, Value10, Value11, Value12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'Value', 'Month') + GROUP BY AdjustmentID, UnitTypeID, TimeClassID, BudgetPhaseID +) iadj ON vrai.AdjustmentID = iadj.AdjustmentID AND vrai.UnitTypeID = iadj.UnitTypeID AND vrai.TimeClassID = iadj.TimeClassID AND vrai.BudgetPhaseID = iadj.BudgetPhaseID +GROUP BY vrai.AdjustmentID, + vrai.UnitTypeID, + vrai.TimeClassID, + vrai.BudgetPhaseID + +CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentID, UnitTypeID) +---------------------------------------------------------------------- +--Build dto +---------------------------------------------------------------------- +INSERT INTO #SRC + (BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted) + SELECT @BudgetConfigID, + @SectionID, + res.AdjustmentID, + res.AdjustmentType, + res.Months, + res.Value, + AdjustedLevel, + res.UnitTypeID, + fp.GetAdjustmentTimeClass(res.TimeClassID, res.BudgetPhaseID), + res.LastModifiedDateUtc, + res.DateCreatedUtc, + res.Comment, + res.AuthorFullName, + res.ClassificationGroupID, + res.ClassificationCategoryID, + 0, + res.IsRecordDeleted + FROM ( + SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount, + * + FROM ( + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber, + slea.AdjustmentID, + slea.AdjustmentType, + fp.GetAdjustmentReportValue(slea.Value, slea.AdjustmentType) AS Value, + fp.GetAdjustmentPath(slea.AdjustmentFilterJSON, slea.GroupingHierarchyJSON, @PlanSectionID) AS AdjustedLevel, + ISNULL(dfm.Name, 'All') AS Months, + slea.Comment, + slea.AuthorFullName, + slea.LastModifiedDateUtc, + slea.DateCreatedUtc, + slea.TimeClassID, + slea.BudgetPhaseID, + slea.ClassificationGroupID, + slea.ClassificationCategoryID, + slea.UnitTypeID, + slea.IsRecordDeleted + FROM fp.ReimbursementAdjustment AS slea WITH (NOLOCK) + JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID + LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) ON dfm.FiscalMonthID = TRY_CAST(SUBSTRING(AdjustedProperty, PATINDEX('%[0-9]%', AdjustedProperty), LEN(AdjustedProperty)) AS INT) + WHERE slea.AdjustmentType <> 4 + + UNION ALL + + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID, sai.TimeClassID, sai.UnitTypeID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber, + slea.AdjustmentID, + slea.AdjustmentType, + CASE WHEN sai.RecordsCount = 1 THEN '1 record affected' + ELSE CAST(sai.RecordsCount AS VARCHAR(30)) + ' records affected' + END AS [Value], + CASE WHEN sai.PayorGroupCount = 1 THEN pg.Name + ELSE CAST(sai.PayorGroupCount AS VARCHAR(30)) + ' payor groups' + END AS AdjustedLevel, + CASE WHEN sai.FiscalMonthCount = 1 THEN FiscalMonthName + ELSE 'Multiple' + END AS Months, + ag.Description AS Comment, + slea.AuthorFullName, + slea.LastModifiedDateUtc, + slea.DateCreatedUtc, + sai.TimeClassID, + sai.BudgetPhaseID, + slea.ClassificationGroupID, + slea.ClassificationCategoryID, + sai.UnitTypeID, + slea.IsRecordDeleted + FROM fp.ReimbursementAdjustment AS slea WITH (NOLOCK) + JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID + JOIN #importAdjustments AS sai ON sai.AdjustmentID = slea.AdjustmentID + JOIN fw.DimPayorGroup AS pg WITH (NOLOCK) ON pg.PayorGroupID = sai.PayorGroupID + LEFT JOIN fp.viewAdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID + WHERE slea.AdjustmentType = 4 + + ) AS res_inner + WHERE res_inner.RowNumber = 1 ) AS res + WHERE res.RowNumber = 1 + +---------------------------------------------------------------------- +-- Insert data to report cache table +---------------------------------------------------------------------- +;WITH TGT AS +( + SELECT BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted + FROM fp.FactReportAdjustmentHistory fr + WHERE fr.BudgetConfigID = @BudgetConfigID + AND fr.SectionID = @SectionID +) + MERGE TGT as target + USING #SRC AS source + ON ( + target.BudgetConfigID = source.BudgetConfigID + AND target.AdjustmentID = source.AdjustmentID + AND target.SectionID = source.SectionID + AND target.TimeClassID = source.TimeClassID + AND target.UnitTypeID = source.UnitTypeID + ) + WHEN MATCHED AND (target.LastModifiedDateUtc <> source.LastModifiedDateUtc) + THEN + UPDATE + SET target.LastModifiedDateUtc = source.LastModifiedDateUtc, + target.AdjustmentValue = source.AdjustmentValue, + target.IsErrored = source.IsErrored, + target.IsRecordDeleted = source.IsRecordDeleted, + target.ClassificationGroupID = source.ClassificationGroupID, + target.ClassificationCategoryID = source.ClassificationCategoryID, + target.Comment = source.Comment + + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted + ) + VALUES ( + source.BudgetConfigID, + source.SectionID, + source.AdjustmentID, + source.AdjustmentType, + source.Months, + source.AdjustmentValue, + source.AdjustedLevel, + source.UnitTypeID, + source.TimeClassID, + source.LastModifiedDateUtc, + source.DateCreatedUtc, + source.Comment, + source.AuthorFullName, + source.ClassificationGroupID, + source.ClassificationCategoryID, + source.IsErrored, + source.IsRecordDeleted + ); + + +END; +GO + + +--------------------------------------------- + +-- fp.procReportAdjustmentHistory_ReimbursementGeneralLedger +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2024-10-15 NH JAZZ-74988 Adjustment history report + *************************************************************/ +CREATE PROCEDURE fp.procReportAdjustmentHistory_ReimbursementGeneralLedger ( + @BudgetConfigID INT +) +AS +BEGIN + +EXEC [dbo].[procSysDropTempTable] '#src' +EXEC [dbo].[procSysDropTempTable] '#adjustments' +EXEC [dbo].[procSysDropTempTable] '#importAdjustments' + +CREATE TABLE #src ( + BudgetConfigID INT, + SectionID INT, + AdjustmentID INT, + AdjustmentType TINYINT, + Months NVARCHAR(50), + AdjustmentValue NVARCHAR(MAX), + AdjustedLevel NVARCHAR(MAX), + UnitTypeID TINYINT, + TimeClassID TINYINT, + LastModifiedDateUtc DATETIME, + DateCreatedUtc DATETIME, + Comment NVARCHAR(MAX), + AuthorFullName NVARCHAR(260), + ClassificationGroupID INT, + ClassificationCategoryID INT, + IsErrored BIT, + IsRecordDeleted BIT +) + +DECLARE @BudgetGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID) +DECLARE @SectionID INT = 10 +DECLARE @PlanSectionID INT = 7 + +---------------------------------------------------------------------- +--Get all adjustments +---------------------------------------------------------------------- +SELECT rgla.AdjustmentID +INTO #adjustments +FROM fp.ReimbursementGeneralLedgerAdjustment AS rgla WITH (NOLOCK) +LEFT JOIN fp.FactReportAdjustmentHistory frah ON rgla.AdjustmentID = frah.AdjustmentID AND frah.SectionID = @SectionID +WHERE rgla.BudgetConfigGUID = @budgetGUID + AND (rgla.GroupingGUID = '00000000-0000-0000-0000-000000000000' + OR rgla.AdjustmentType = 4) + AND (rgla.LastModifiedDateUtc <> frah.LastModifiedDateUtc + OR frah.LastModifiedDateUtc is NULL) + +CREATE CLUSTERED INDEX PK_Adjustment ON #adjustments (AdjustmentID) + +---------------------------------------------------------------------- +--Get import adjustments +---------------------------------------------------------------------- +SELECT impAdj.AdjustmentID, PayourGroupCount, PayorGroupID, TimeClassID, BudgetPhaseID, FiscalMonthCount, FiscalMonthName, RecordsCount +INTO #importAdjustments +FROM (SELECT AdjustmentID, + COUNT(DISTINCT PayorGroupID) AS PayourGroupCount, + MAX(PayorGroupID) AS PayorGroupID, + TimeClassID, + BudgetPhaseID, + COUNT(DISTINCT Name) AS FiscalMonthCount, + MAX(Name) AS FiscalMonthName, + COUNT(DISTINCT ROWID) AS RecordsCount, + SUM(Value) AS RecordValue + FROM fp.ReimbursementGeneralLedgerAdjustmentImport rglai WITH (NOLOCK) + UNPIVOT (Value For FiscalMonth IN (Value01, Value02, Value03,Value04, Value05, Value06, Value07,Value08, Value09, Value10, Value11, Value12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'Value', 'Month') + GROUP BY AdjustmentID, + TimeClassID, + BudgetPhaseID + ) impAdj +JOIN #adjustments adj ON impAdj.AdjustmentID = adj.AdjustmentID + +CREATE CLUSTERED INDEX PK_ImportAdjustmen ON #importAdjustments (AdjustmentID) +---------------------------------------------------------------------- +--Build dto +---------------------------------------------------------------------- + +INSERT INTO #src + (BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted) + SELECT @BudgetConfigID, + @SectionID, + res.AdjustmentID, + res.AdjustmentType, + res.Months, + res.Value, + AdjustedLevel, + 34, -- Dollars + fp.GetAdjustmentTimeClass(res.TimeClassID, res.BudgetPhaseID), + res.LastModifiedDateUtc, + res.DateCreatedUtc, + res.Comment, + res.AuthorFullName, + res.ClassificationGroupID, + res.ClassificationCategoryID, + 0, -- IsErrored + res.IsRecordDeleted + FROM ( + SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount, * + FROM ( + SELECT + ROW_NUMBER() OVER (PARTITION BY rgla.AdjustmentID ORDER BY rgla.DateCreatedUtc DESC) AS RowNumber, + rgla.AdjustmentID, + fp.GetAdjustmentReportValue(rgla.Value, rgla.AdjustmentType) AS VALUE, + fp.GetAdjustmentPath(rgla.AdjustmentFilterJSON, rgla.GroupingHierarchyJSON, @PlanSectionID) AS AdjustedLevel, + ISNULL(dfm.Name, 'All') AS Months, + rgla.Comment, + rgla.AuthorFullName, + rgla.LastModifiedDateUtc, + rgla.DateCreatedUtc, + rgla.TimeClassID, + rgla.BudgetPhaseID, + rgla.ClassificationGroupID, + rgla.ClassificationCategoryID, + rgla.IsRecordDeleted, + rgla.AdjustmentType + FROM fp.ReimbursementGeneralLedgerAdjustment AS rgla WITH (NOLOCK) + JOIN #adjustments AS sleas ON sleas.AdjustmentID = rgla.AdjustmentID + LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) ON dfm.FiscalMonthID = TRY_CAST(SUBSTRING(AdjustedProperty, PATINDEX('%[0-9]%', AdjustedProperty), LEN(AdjustedProperty)) AS INT) + WHERE rgla.AdjustmentType <> 4 + + UNION ALL + + -- Import + SELECT + ROW_NUMBER() OVER (PARTITION BY rgla.AdjustmentID, iadj.TimeClassID, iadj.BudgetPhaseID ORDER BY rgla.DateCreatedUtc DESC) AS RowNumber, + rgla.AdjustmentID, + CASE WHEN iadj.RecordsCount = 1 THEN '1 record affected' + ELSE CAST(iadj.RecordsCount AS VARCHAR(30)) + ' records affected' + END AS [Value], + CASE WHEN iadj.PayourGroupCount = 1 THEN pg.Name + ELSE CAST(iadj.PayourGroupCount AS VARCHAR(30)) + ' payor groups' + END AS AdjustedLevel, + CASE WHEN iadj.FiscalMonthCount = 1 THEN FiscalMonthName + ELSE 'Multiple' + END AS Months, + ag.Description AS Comment, + rgla.AuthorFullName, + rgla.LastModifiedDateUtc, + rgla.DateCreatedUtc, + iadj.TimeClassID, + iadj.BudgetPhaseID, + rgla.ClassificationGroupID, + rgla.ClassificationCategoryID, + rgla.IsRecordDeleted, + rgla.AdjustmentType + FROM fp.ReimbursementGeneralLedgerAdjustment AS rgla WITH (NOLOCK) + JOIN #importAdjustments AS iadj ON iadj.AdjustmentID = rgla.AdjustmentID + JOIN fw.DimPayorGroup AS pg WITH (NOLOCK) ON pg.PayorGroupID = iadj.PayorGroupID + LEFT JOIN fp.viewAdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = rgla.GroupingGUID + WHERE rgla.AdjustmentType = 4 + + ) AS res_inner + WHERE res_inner.RowNumber = 1) AS res + WHERE res.RowNumber = 1 + ORDER BY res.DateCreatedUtc DESC + +---------------------------------------------------------------------- +-- Insert data to reportTable +---------------------------------------------------------------------- +;WITH TGT AS +( + SELECT BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted + FROM fp.FactReportAdjustmentHistory fr + WHERE fr.BudgetConfigID = @BudgetConfigID + AND fr.SectionID = @SectionID +) + MERGE TGT AS target + USING #src AS source + ON ( + target.BudgetConfigID = source.BudgetConfigID + AND target.AdjustmentID = source.AdjustmentID + AND target.SectionID = source.SectionID + AND target.TimeClassID = source.TimeClassID + ) + WHEN MATCHED AND (target.LastModifiedDateUtc <> source.LastModifiedDateUtc) + THEN + UPDATE + SET target.LastModifiedDateUtc = source.LastModifiedDateUtc, + target.AdjustmentValue = source.AdjustmentValue, + target.IsErrored = source.IsErrored, + target.IsRecordDeleted = source.IsRecordDeleted, + target.ClassificationGroupID = source.ClassificationGroupID, + target.ClassificationCategoryID = source.ClassificationCategoryID, + target.Comment = source.Comment + + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted + ) + VALUES ( + source.BudgetConfigID, + source.SectionID, + source.AdjustmentID, + source.AdjustmentType, + source.Months, + source.AdjustmentValue, + source.AdjustedLevel, + source.UnitTypeID, + source.TimeClassID, + source.LastModifiedDateUtc, + source.DateCreatedUtc, + source.Comment, + source.AuthorFullName, + source.ClassificationGroupID, + source.ClassificationCategoryID, + source.IsErrored, + source.IsRecordDeleted + ); + +END +GO + + +--------------------------------------------- + +-- fp.procReportAdjustmentHistory_ServiceLine +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2024-10-15 NH JAZZ-74988 Adjustment history report + *************************************************************/ +CREATE PROCEDURE fp.procReportAdjustmentHistory_ServiceLine ( + @BudgetConfigID INT +) +AS +BEGIN + +EXEC [dbo].[procSysDropTempTable] '#src' +EXEC [dbo].[procSysDropTempTable] '#adjustments' +EXEC [dbo].[procSysDropTempTable] '#importAdjustments' + +CREATE TABLE #SRC ( + BudgetConfigID INT, + SectionID INT, + AdjustmentID INT, + AdjustmentType TINYINT, + Months NVARCHAR(50), + AdjustmentValue NVARCHAR(MAX), + AdjustedLevel NVARCHAR(MAX), + UnitTypeID TINYINT, + TimeClassID TINYINT, + LastModifiedDateUtc DATETIME, + DateCreatedUtc DATETIME, + Comment NVARCHAR(MAX), + AuthorFullName NVARCHAR(260), + ClassificationGroupID INT, + ClassificationCategoryID INT, + IsErrored BIT, + IsRecordDeleted BIT +) + +CREATE TABLE #adjustments ( + AdjustmentID INT +) + +DECLARE @BudgetGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID) +DECLARE @SectionID INT = 1 +DECLARE @PlanSectionID INT = 1 + +---------------------------------------------------------------------- +-- Get all adjustments +---------------------------------------------------------------------- +INSERT INTO #adjustments +SELECT slea.AdjustmentID +FROM fp.ServiceLineEncounterAdjustment slea WITH (NOLOCK) +LEFT JOIN fp.FactReportAdjustmentHistory frah ON slea.AdjustmentID = frah.AdjustmentID AND frah.SectionID = @SectionID +WHERE slea.BudgetConfigGUID = @BudgetGUID + AND ((slea.GroupingGUID = '00000000-0000-0000-0000-000000000000' AND slea.AdjustmentType IN (0, 2, 3)) -- filter roll up adjustments + OR slea.AdjustmentType IN (1, 4, 10, 11, 12, 13, 14, 15)) + AND (slea.LastModifiedDateUtc <> frah.LastModifiedDateUtc + OR frah.LastModifiedDateUtc is NULL) + +CREATE CLUSTERED INDEX PK_SecuredAdjustments ON #adjustments (AdjustmentID) + +---------------------------------------------------------------------- +-- Get import adjustments +---------------------------------------------------------------------- +SELECT AdjustmentID, + COUNT(DISTINCT DepartmentID) AS DepartmentCount, + MAX(DepartmentID) AS DepartmentID, + TimeClassID, + UnitTypeID, + BudgetPhaseID, + COUNT(DISTINCT FiscalMonthID) AS FiscalMonthCount, + MAX(FiscalMonthID) AS FiscalMonthID, + COUNT(*) AS RecordsCount, + SUM(RecordValue) AS TotalValue + INTO #importAdjustments + FROM (SELECT iadj.AdjustmentID, + TimeClassID, + BudgetPhaseID, + UnitTypeID, + DepartmentID, + CASE WHEN COUNT(DISTINCT FiscalMonthID) > 1 THEN 13 + ELSE MAX(FiscalMonthID) + END AS FiscalMonthID, + SUM(Value) AS RecordValue + FROM fp.ServiceLineEncounterAdjustmentImport AS iadj WITH (NOLOCK) + JOIN #adjustments AS sadj ON sadj.AdjustmentID = iadj.AdjustmentID + GROUP BY iadj.AdjustmentID, + TimeClassID, + BudgetPhaseID, + EntityID, + PatientClassID, + ServiceLineID, + --ServiceLineRollupID, taken from ServiceLineID + AgeCohortID, + MedicalSurgicalID, + DepartmentID, + PayorID, + --PayorGroupID, taken from PayorID + MSDRGID, + CPTID, + ProviderID, + --PhysicianSpecialtyID, taken from Provider + UnitTypeID) AS ImportRecord + GROUP BY AdjustmentID, + TimeClassID, + BudgetPhaseID, + UnitTypeID + + +CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentID) + +INSERT INTO #SRC + (BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted) + SELECT @BudgetConfigID, + @SectionID, + res.AdjustmentID, + res.AdjustmentType, + res.Months, + res.Value, + res.AdjustedLevel, + res.UnitTypeID, + fp.GetAdjustmentTimeClass(res.TimeClassID, res.BudgetPhaseID), + res.LastModifiedDateUtc, + res.DateCreatedUtc, + res.Comment, + res.AuthorFullName, + res.ClassificationGroupID, + res.ClassificationCategoryID, + res.IsErrored, + res.IsRecordDeleted + FROM ( + SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount, + * + FROM ( + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber, + slea.AdjustmentID, + slea.AdjustmentType, + fp.GetAdjustmentReportValue(slea.Value, slea.AdjustmentType) AS Value, + fp.GetAdjustmentPath(slea.AdjustmentFilterJSON, slea.GroupingHierarchyJSON, @PlanSectionID) AS AdjustedLevel, + ISNULL(dfm.Name, 'All') AS Months, + slea.Comment, + slea.AuthorFullName, + slea.LastModifiedDateUtc, + slea.DateCreatedUtc, + slea.TimeClassID, + slea.BudgetPhaseID, + slea.ClassificationGroupID, + slea.ClassificationCategoryID, + CAST(140 AS TINYINT) AS UnitTypeID, + slea.IsRecordDeleted, + slea.IsErrored + FROM fp.ServiceLineEncounterAdjustment AS slea WITH (NOLOCK) + JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID + LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) ON dfm.FiscalMonthID = TRY_CAST(SUBSTRING(AdjustedProperty, PATINDEX('%[0-9]%', AdjustedProperty), LEN(AdjustedProperty)) AS INT) + WHERE slea.AdjustmentType NOT IN (4, 15) + + UNION ALL + + -- Import Adjustments + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID, sai.TimeClassID, sai.BudgetPhaseID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber, + slea.AdjustmentID, + slea.AdjustmentType, + CASE WHEN sai.RecordsCount = 1 THEN fp.GetAdjustmentReportValue(TotalValue, slea.AdjustmentType) + ELSE CAST(sai.RecordsCount AS VARCHAR(30)) + ' records affected' + END AS [Value], + CASE WHEN sai.DepartmentCount = 1 THEN d.Name + ELSE CAST(sai.DepartmentCount AS VARCHAR(30)) + ' departments' + END AS AdjustedLevel, + CASE WHEN sai.FiscalMonthCount = 1 THEN ISNULL(dfm.Name, 'Multiple') + ELSE 'Multiple' + END AS Months, + ag.Description AS Comment, + slea.AuthorFullName, + slea.LastModifiedDateUtc, + slea.DateCreatedUtc, + sai.TimeClassID, + sai.BudgetPhaseID, + slea.ClassificationGroupID, + slea.ClassificationCategoryID, + CAST(140 AS TINYINT) AS UnitTypeID, + slea.IsRecordDeleted, + slea.IsErrored + FROM fp.ServiceLineEncounterAdjustment AS slea WITH (NOLOCK) + JOIN #importAdjustments AS sai ON sai.AdjustmentID = slea.AdjustmentID + JOIN fw.DimDepartment AS d WITH (NOLOCK) ON sai.DepartmentID = d.DepartmentID + LEFT JOIN fp.AdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID + LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) on sai.FiscalMonthID = dfm.FiscalMonthID + WHERE slea.AdjustmentType = 4 + + -- Add Provider adjustments + UNION ALL + + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID, aps.TimeClassID ORDER BY slea.DateCreatedUTC DESC) AS RowNumber, + slea.AdjustmentID, + slea.AdjustmentType, + fp.GetAdjustmentReportValue(aps.Total, slea.AdjustmentType) AS Value, + phys.Physician AS AdjustedLevel, + 'Multiple', + aps.Comment, + slea.AuthorFullName, + slea.LastModifiedDateUtc, + slea.DateCreatedUTC, + aps.TimeClassID, + 2 AS BudgetPhaseID, + aps.ClassificationGroupID, + aps.ClassificationCategoryID, + 140 AS UnitTypeID, + slea.IsRecordDeleted, + slea.IsErrored + FROM fp.ServiceLineEncounterAdjustment AS slea WITH (NOLOCK) + JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID + JOIN (SELECT SLEncounterAdjustmentGUID, + ProviderID, + Comment, + ClassificationGroupID, + ClassificationCategoryID, + ProjectionTotal AS Total, + 12 AS TimeClassID + FROM fp.AddProviderSummary WITH (NOLOCK) + UNION ALL + SELECT SLEncounterAdjustmentGUID, + ProviderID, + Comment, + ClassificationGroupID, + ClassificationCategoryID, + BudgetTotal AS Total, + 2 AS TimeClassID + FROM fp.AddProviderSummary WITH (NOLOCK)) AS aps ON aps.SLEncounterAdjustmentGUID = slea.AdjustmentGUID + JOIN dss.DimPhysician AS phys ON phys.PhysicianID = aps.ProviderID + WHERE slea.AdjustmentType = 15 + ) AS res_inner + WHERE res_inner.RowNumber = 1 ) AS res + ORDER BY res.DateCreatedUtc DESC + +---------------------------------------------------------------------- +-- Insert data to report Table +---------------------------------------------------------------------- +;WITH TGT AS +( + SELECT BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted + FROM fp.FactReportAdjustmentHistory fr + WHERE fr.BudgetConfigID = @BudgetConfigID + AND fr.SectionID = @SectionID +) + MERGE TGT as target + USING #src AS source + ON ( + target.BudgetConfigID = source.BudgetConfigID + AND target.AdjustmentID = source.AdjustmentID + AND target.SectionID = source.SectionID + AND target.TimeClassID = source.TimeClassID + ) + WHEN MATCHED AND (target.LastModifiedDateUtc <> source.LastModifiedDateUtc) + THEN + UPDATE + SET target.LastModifiedDateUtc = source.LastModifiedDateUtc, + target.AdjustmentValue = source.AdjustmentValue, + target.IsErrored = source.IsErrored, + target.IsRecordDeleted = source.IsRecordDeleted, + target.ClassificationGroupID = source.ClassificationGroupID, + target.ClassificationCategoryID = source.ClassificationCategoryID, + target.Comment = source.Comment + + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted + ) + VALUES ( + source.BudgetConfigID, + source.SectionID, + source.AdjustmentID, + source.AdjustmentType, + source.Months, + source.AdjustmentValue, + source.AdjustedLevel, + source.UnitTypeID, + source.TimeClassID, + source.LastModifiedDateUtc, + source.DateCreatedUtc, + source.Comment, + source.AuthorFullName, + source.ClassificationGroupID, + source.ClassificationCategoryID, + source.IsErrored, + source.IsRecordDeleted + ); + +END +GO + + +--------------------------------------------- + +-- fp.procReportAdjustmentHistory_Staffing +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2024-10-15 NH JAZZ-74988 Adjustment history report + *************************************************************/ + +CREATE PROCEDURE fp.procReportAdjustmentHistory_Staffing ( + @BudgetConfigID INT +) +AS +BEGIN + +EXEC [dbo].[procSysDropTempTable] '#src' +EXEC [dbo].[procSysDropTempTable] '#adjustments' +EXEC [dbo].[procSysDropTempTable] '#importAdjustments' + +CREATE TABLE #src ( + BudgetConfigID INT, + SectionID INT, + AdjustmentID INT, + AdjustmentType TINYINT, + Months NVARCHAR(50), + AdjustmentValue NVARCHAR(MAX), + AdjustedLevel NVARCHAR(MAX), + UnitTypeID TINYINT, + TimeClassID TINYINT, + LastModifiedDateUtc DATETIME, + DateCreatedUtc DATETIME, + Comment NVARCHAR(MAX), + AuthorFullName NVARCHAR(260), + ClassificationGroupID INT, + ClassificationCategoryID INT, + IsErrored BIT, + IsRecordDeleted BIT +) + +CREATE TABLE #adjustments ( + AdjustmentID INT +) + +DECLARE @BudgetGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID) +DECLARE @SectionID INT = 5 +DECLARE @PlanSectionID INT = 4 + +---------------------------------------------------------------------- +--Get all adjustments +---------------------------------------------------------------------- +INSERT INTO #adjustments +SELECT slea.AdjustmentID +FROM fp.StaffingAdjustment slea WITH (NOLOCK) +LEFT JOIN fp.FactReportAdjustmentHistory frah ON slea.AdjustmentID = frah.AdjustmentID AND frah.SectionID = @SectionID +WHERE slea.BudgetConfigGUID = @budgetGUID + AND slea.SubsectionID = 3 + AND (slea.AdjustmentType = 6 + OR ( + ((slea.GroupingGUID = '00000000-0000-0000-0000-000000000000' AND slea.AdjustmentType IN (0, 2, 3)) -- filter roll up adjustments + OR slea.AdjustmentType IN (1, 4, 5, 8,10, 11, 12, 13, 14, 17, 20)) + AND (slea.LastModifiedDateUtc <> frah.LastModifiedDateUtc OR frah.LastModifiedDateUtc is NULL)) + ) + +CREATE CLUSTERED INDEX PK_Adjustmnets ON #adjustments (AdjustmentID) + +---------------------------------------------------------------------- +--Get import adjustments +---------------------------------------------------------------------- +SELECT AdjustmentID, + COUNT(DISTINCT DepartmentID) AS DepartmentCount, + MAX(DepartmentID) AS DepartmentID, + TimeClassID, + UnitTypeID, + BudgetPhaseID, + COUNT(DISTINCT FiscalMonthID) AS FiscalMonthCount, + MAX(FiscalMonthID) AS FiscalMonthID, + COUNT(*) AS RecordsCount, + SUM(RecordValue) AS TotalValue + INTO #importAdjustments + FROM (SELECT iadj.AdjustmentID, + TimeClassID, + BudgetPhaseID, + ISNULL(ORIGINALUNITTYPEID, UnitTypeID) AS UnitTypeID, + DepartmentID, + CASE WHEN COUNT(DISTINCT FiscalMonthID) > 1 THEN 13 + ELSE MAX(FiscalMonthID) + END AS FiscalMonthID, + SUM(Value) AS RecordValue + FROM fp.StaffingAdjustmentImport AS iadj WITH (NOLOCK) + JOIN #adjustments AS sadj ON sadj.AdjustmentID = iadj.AdjustmentID + GROUP BY iadj.AdjustmentID, + TimeClassID, + BudgetPhaseID, + DepartmentID, + JobCodeID, + PayCodeGroupID, + --ProductiveClassID, Taken from PayCodeGroupID + VariabilityID, + --EntityID, Taken from Department + EmployeeID, + --ProviderID, not used in Staffing + --ProviderTypeID, not used in Staffing + --ProviderLineItemID, not used in Staffing + --ProviderSpecialtyID, not used in Staffing + ISNULL(ORIGINALUNITTYPEID, UnitTypeID) + ) AS ImportRecord + GROUP BY AdjustmentID, + TimeClassID, + BudgetPhaseID, + UnitTypeID + +-- Creating indexes for faster selection +CREATE CLUSTERED INDEX PK_ImportAdjustmets ON #importAdjustments (AdjustmentID, UnitTypeID) + +INSERT INTO #src + (BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted) + SELECT @BudgetConfigID, + @SectionID, + res.AdjustmentID, + res.AdjustmentType, + res.Months, + res.[Value], + res.AdjustedLevel, + res.UnitTypeID, + fp.GetAdjustmentTimeClass(res.TimeClassID, res.BudgetPhaseID), + res.LastModifiedDateUtc, + res.DateCreatedUtc, + res.Comment, + res.AuthorFullName, + res.ClassificationGroupID, + res.ClassificationCategoryID, + res.IsErrored, + res.IsRecordDeleted + FROM ( + SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount, + * + FROM ( + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber, + slea.AdjustmentID, + slea.AdjustmentType, + fp.GetAdjustmentReportValue(slea.Value, slea.AdjustmentType) AS Value, + fp.GetAdjustmentPath(slea.AdjustmentFilterJSON, slea.GroupingHierarchyJSON, @PlanSectionID) AS AdjustedLevel, + ISNULL(dfm.Name, 'All') AS Months, + slea.Comment, + slea.AuthorFullName, + slea.LastModifiedDateUtc, + slea.DateCreatedUtc, + slea.TimeClassID, + slea.BudgetPhaseID, + slea.ClassificationGroupID, + slea.ClassificationCategoryID, + slea.UnitTypeID, + slea.IsRecordDeleted, + slea.IsErrored + FROM fp.StaffingAdjustment AS slea WITH (NOLOCK) + JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID + LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) ON dfm.FiscalMonthID = TRY_CAST(SUBSTRING(AdjustedProperty, PATINDEX('%[0-9]%', AdjustedProperty), LEN(AdjustedProperty)) AS INT) + WHERE slea.AdjustmentType NOT IN (4,6, 17, 20) + + UNION ALL + + -- IMPORT + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID, sai.TimeClassID, sai.BudgetPhaseID, sai.UnitTypeID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber, + slea.AdjustmentID, + slea.AdjustmentType, + CASE WHEN sai.RecordsCount = 1 AND sai.UnitTypeID IN (144, 159, 172) THEN '1 record affected' + WHEN sai.RecordsCount = 1 THEN fp.GetAdjustmentReportValue(TotalValue, slea.AdjustmentType) + ELSE CAST(sai.RecordsCount AS VARCHAR(30)) + ' records affected' + END AS [Value], + CASE WHEN sai.DepartmentCount = 1 THEN d.Name + ELSE CAST(sai.DepartmentCount AS VARCHAR(30)) + ' departments' + END AS AdjustedLevel, + CASE WHEN sai.FiscalMonthCount = 1 THEN ISNULL(dfm.Name, 'Multiple') + ELSE 'Multiple' + END AS Months, + ISNULL(ag.[Description], slea.Comment) AS Comment, + slea.AuthorFullName, + slea.LastModifiedDateUtc, + slea.DateCreatedUtc, + sai.TimeClassID, + sai.BudgetPhaseID, + slea.ClassificationGroupID, + slea.ClassificationCategoryID, + sai.UnitTypeID, + slea.IsRecordDeleted, + slea.IsErrored + FROM fp.StaffingAdjustment AS slea WITH (NOLOCK) + JOIN #importAdjustments AS sai ON sai.AdjustmentID = slea.AdjustmentID + JOIN fw.DimDepartment AS d WITH (NOLOCK) ON sai.DepartmentID = d.DepartmentID + LEFT JOIN fp.AdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID + LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) on sai.FiscalMonthID = dfm.FiscalMonthID + WHERE slea.AdjustmentType = 4 + + UNION ALL + + SELECT ROW_NUMBER() OVER (PARTITION BY slea.GroupingGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber, + slea.AdjustmentID, + slea.AdjustmentType, + CAST(fte.FTEAmount AS VARCHAR(30)) + ' FTEs Added' AS [Value], + CASE WHEN DepartmentCount = 1 THEN DepartmentName + ELSE CAST(DepartmentCount AS VARCHAR(30)) + ' departments' + END AS AdjustedLevel, + 'Multiple' AS Months, + CASE WHEN CommentCount = 0 THEN fte.FTEComment + WHEN CommentCount = 1 THEN fte.FTEComment + ELSE 'Multiple Comments' + END AS Comment, + slea.AuthorFullName, + slea.LastModifiedDateUtc, + slea.DateCreatedUtc, + slea.TimeClassID, + slea.BudgetPhaseID, + 0 AS ClassificationGroupID, + 0 AS ClassificationCategoryID, + 144 AS UnitTypeID, + slea.IsRecordDeleted, + slea.IsErrored + FROM ( + SELECT + slea_inner.GroupingGUID AS AdjustmentGUID, + MIN(slea_inner.AdjustmentID) AS AdjustmentID, + slea_inner.AdjustmentType, + slea_inner.AuthorFullName, + MAX(slea_inner.LastModifiedDateUtc) AS LastModifiedDateUtc, + MIN(slea_inner.DateCreatedUtc) AS DateCreatedUtc, + slea_inner.GroupingGUID, + slea_inner.TimeClassID, + slea_inner.BudgetPhaseID, + slea_inner.IsRecordDeleted, + slea_inner.IsErrored + FROM fp.StaffingAdjustment AS slea_inner WITH (NOLOCK) + JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea_inner.AdjustmentID + WHERE AdjustmentType = 6 + GROUP BY + slea_inner.GroupingGUID, + slea_inner.AdjustmentType, + slea_inner.AuthorFullName, + slea_inner.DateCreatedUtc, + slea_inner.GroupingGUID, + slea_inner.TimeClassID, + slea_inner.BudgetPhaseID, + slea_inner.IsRecordDeleted, + slea_inner.IsErrored + ) AS slea + JOIN ( + SELECT + MIN(dept.[Name]) AS DepartmentName, + OBJ.GroupingGUID, + COUNT(DISTINCT OBJ.DepartmentID) AS DepartmentCount, + CAST(SUM(OBJ.FTEAmount) AS DECIMAL(19,2)) AS FTEAmount, + MAX(OBJ.Comment) AS FTEComment, + SUM(CASE WHEN Comment <> '' THEN 1 ELSE 0 END) AS CommentCount + FROM fp.FTERequest AS OBJ WITH (NOLOCK) + JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = OBJ.DepartmentID + GROUP BY + OBJ.GroupingGUID + ) AS fte ON fte.GroupingGUID = slea.GroupingGUID + + UNION ALL + + -- ManagerSet (new My Budgets) Adjustments + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID, adjComment.TimeClassID, adjComment.UnitTypeID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber, + slea.AdjustmentID, + slea.AdjustmentType, + CASE WHEN adjComment.RecordsChanged = 1 THEN fp.GetAdjustmentReportValue(TotalValue, slea.AdjustmentType) + ELSE CAST(adjComment.RecordsChanged AS VARCHAR(30)) + ' records affected' + END AS [Value], + dept.Name AS AdjustedLevel, + 'All' AS Months, + CASE WHEN adjComment.CommentCount = 0 THEN adjComment.CommentTotal + WHEN adjComment.CommentCount = 1 THEN adjComment.CommentTotal + ELSE 'Multiple Comments' + END AS Comment, + slea.AuthorFullName, + slea.LastModifiedDateUtc, + slea.DateCreatedUtc, + adjComment.TimeClassID, + slea.BudgetPhaseID, + slea.ClassificationGroupID, + slea.ClassificationCategoryID, + adjComment.UnitTypeId, + slea.IsRecordDeleted, + slea.IsErrored + FROM fp.StaffingAdjustment AS slea WITH (NOLOCK) + JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID + JOIN (SELECT AdjustmentID, + DepartmentID, + UnitTypeID, + TimeClassID, + MAX(Comment) AS CommentTotal, + SUM(CASE WHEN Comment <> '' THEN 1 ELSE 0 END) AS CommentCount, + SUM(Value) AS TotalValue, + COUNT(*) AS RecordsChanged + FROM fp.StaffingManagerSetAdjustmentComment + GROUP BY AdjustmentID, + DepartmentID, + UnitTypeID, + TimeClassID + ) AS adjComment ON slea.AdjustmentID = adjComment.AdjustmentID + JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = adjComment.DepartmentID + WHERE slea.AdjustmentType = 20 + + UNION ALL + + -- NPE Add Employee Adjustments + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber, + slea.AdjustmentID, + slea.AdjustmentType, + emp.Name AS [Value], + dept.Name AS AdjustedLevel, + 'Multiple' AS Months, + slea.Comment AS Comment, + slea.AuthorFullName, + slea.LastModifiedDateUtc, + slea.DateCreatedUtc, + smad.TimeClassID, + slea.BudgetPhaseID, + slea.ClassificationGroupID, + slea.ClassificationCategoryID, + 144 AS UnitTypeID, + slea.IsRecordDeleted, + slea.IsErrored + FROM fp.StaffingAdjustment AS slea WITH (NOLOCK) + JOIN #adjustments AS sleas ON sleas.AdjustmentID = slea.AdjustmentID + JOIN fp.StaffingManagerAdjustmentData smad WITH (NOLOCK) ON slea.AdjustmentGUID = smad.AdjustmentGUID + JOIN fw.DimDepartment AS dept WITH (NOLOCK) ON dept.DepartmentID = smad.DepartmentID + JOIN fw.DimEmployee AS emp WITH (NOLOCK) ON smad.EmployeeID = emp.EmployeeID + WHERE slea.AdjustmentType = 17 + ) AS res_inner + -- Selecting only unique adjustments + WHERE res_inner.RowNumber = 1) AS res + ORDER BY res.DateCreatedUtc DESC + + -- Insert data to reportTable + + ;WITH TGT AS + ( + SELECT BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted + FROM fp.FactReportAdjustmentHistory fr + WHERE fr.BudgetConfigID = @BudgetConfigID + AND fr.SectionID = @SectionID + ) + MERGE TGT AS target + USING #src AS source + ON ( + target.BudgetConfigID = source.BudgetConfigID + AND target.AdjustmentID = source.AdjustmentID + AND target.SectionID = source.SectionID + AND target.TimeClassID = source.TimeClassID + AND target.UnitTypeID = source.UnitTypeID + ) + WHEN MATCHED AND (target.LastModifiedDateUtc <> source.LastModifiedDateUtc) + THEN + UPDATE + SET target.LastModifiedDateUtc = source.LastModifiedDateUtc, + target.AdjustmentValue = source.AdjustmentValue, + target.IsErrored = source.IsErrored, + target.IsRecordDeleted = source.IsRecordDeleted, + target.ClassificationGroupID = source.ClassificationGroupID, + target.ClassificationCategoryID = source.ClassificationCategoryID, + target.Comment = source.Comment + + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted + ) + VALUES ( + source.BudgetConfigID, + source.SectionID, + source.AdjustmentID, + source.AdjustmentType, + source.Months, + source.AdjustmentValue, + source.AdjustedLevel, + source.UnitTypeID, + source.TimeClassID, + source.LastModifiedDateUtc, + source.DateCreatedUtc, + source.Comment, + source.AuthorFullName, + source.ClassificationGroupID, + source.ClassificationCategoryID, + source.IsErrored, + source.IsRecordDeleted + ); + +-- clean up Add FTE +DELETE frah FROM fp.FactReportAdjustmentHistory frah +LEFT JOIN fp.StaffingAdjustment slea ON slea.AdjustmentID = frah.AdjustmentID AND frah.SectionID = @SectionID +WHERE frah.AdjustmentType = 6 AND slea.AdjustmentID IS NULL +END +GO + + +--------------------------------------------- + +-- fp.procReportAdjustmentHistory_Statistics +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2024-10-15 NH JAZZ-74988 Adjustment history report + *************************************************************/ +CREATE PROCEDURE fp.procReportAdjustmentHistory_Statistics ( + @BudgetConfigID INT +) +AS +BEGIN + +EXEC [dbo].[procSysDropTempTable] '#src' +EXEC [dbo].[procSysDropTempTable] '#adjustments' +EXEC [dbo].[procSysDropTempTable] '#importAdjustments' + +DECLARE @BudgetGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID) +DECLARE @SectionID_Driver INT = 3 +DECLARE @SectionID_Dependent INT = 4 +DECLARE @PlanSectionID INT = 3 + +CREATE TABLE #src ( + BudgetConfigID INT, + SectionID INT, + AdjustmentID INT, + AdjustmentType TINYINT, + Months NVARCHAR(50), + AdjustmentValue NVARCHAR(MAX), + AdjustedLevel NVARCHAR(MAX), + UnitTypeID TINYINT, + TimeClassID TINYINT, + LastModifiedDateUtc DATETIME, + DateCreatedUtc DATETIME, + Comment NVARCHAR(MAX), + AuthorFullName NVARCHAR(260), + ClassificationGroupID INT, + ClassificationCategoryID INT, + IsErrored BIT, + IsRecordDeleted BIT +) + +---------------------------------------------------------------------- +--Get all adjustments +---------------------------------------------------------------------- +SELECT sa.AdjustmentID +INTO #adjustments +FROM fp.StatisticsAdjustment sa WITH (NOLOCK) +LEFT JOIN fp.FactReportAdjustmentHistory frah ON sa.AdjustmentID = frah.AdjustmentID AND frah.SectionID IN (@SectionID_Driver, @SectionID_Dependent) +WHERE sa.BudgetConfigGUID = @BudgetGUID + AND ( + (sa.GroupingGUID = '00000000-0000-0000-0000-000000000000' AND sa.AdjustmentType IN (0, 2, 3)) -- filter roll up adjustments + OR sa.AdjustmentType IN (1, 4, 10, 11, 12, 13, 14, 15) + ) + AND (sa.LastModifiedDateUtc <> frah.LastModifiedDateUtc + OR frah.LastModifiedDateUtc IS NULL) + +CREATE CLUSTERED INDEX PK_Adjustments ON #adjustments (AdjustmentID) + +---------------------------------------------------------------------- +--Get import adjustments +---------------------------------------------------------------------- +SELECT AdjustmentID, + COUNT(DISTINCT DepartmentID) AS DepartmentCount, + MAX(DepartmentID) AS DepartmentID, + TimeClassID, + BudgetPhaseID, + UnitTypeID, + COUNT(DISTINCT FiscalMonthID) AS FiscalMonthCount, + MAX(FiscalMonthID) AS FiscalMonthID, + COUNT(*) AS RecordsCount, + SUM(RecordValue) AS TotalValue + INTO #importAdjustments + FROM (SELECT iadj.AdjustmentID, + TimeClassID, + BudgetPhaseID, + UnitTypeID, + DepartmentID, + SUM(Value) AS RecordValue, + CASE WHEN COUNT(DISTINCT FiscalMonthID)> 1 THEN 13 + ELSE MIN(FiscalMonthID) + END AS FiscalMonthID + FROM fp.StatisticsAdjustmentImport AS iadj WITH (NOLOCK) + JOIN #adjustments AS sadj ON sadj.AdjustmentID = iadj.AdjustmentID + GROUP BY iadj.AdjustmentID, + TimeClassID, + BudgetPhaseID, + DepartmentID, + EntityID, + AccountID, + FinancialReportingID, + PayorID, + PatientClassID, + UnitTypeID, + ProviderID, + ProviderLineItemID, + ProviderSpecialtyID, + ProviderTypeID) AS ImportRecord + GROUP BY AdjustmentID, + TimeClassID, + BudgetPhaseID, + UnitTypeID + +CREATE CLUSTERED INDEX PK_ImportAdjustments ON #importAdjustments (AdjustmentID, UnitTypeID) + +INSERT INTO #src + (BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted) + SELECT @BudgetConfigID, + CASE WHEN res.SubsectionID = 1 THEN @SectionID_Driver + ELSE @SectionID_Dependent + END, + res.AdjustmentID, + res.AdjustmentType, + res.Months, + res.[Value], + res.AdjustedLevel, + 140, + fp.GetAdjustmentTimeClass(res.TimeClassID, res.BudgetPhaseID), + res.LastModifiedDateUtc, + res.DateCreatedUtc, + res.Comment, + res.AuthorFullName, + res.ClassificationGroupID, + res.ClassificationCategoryID, + res.IsErrored, + res.IsRecordDeleted + FROM ( + SELECT COUNT(res_inner.AdjustmentID) OVER () AS TotalRowsCount, + * + FROM ( + SELECT ROW_NUMBER() OVER (PARTITION BY sa.AdjustmentID ORDER BY sa.DateCreatedUtc DESC) AS RowNumber, + sa.AdjustmentID, + sa.AdjustmentType, + fp.GetAdjustmentReportValue(sa.Value, sa.AdjustmentType) AS Value, + fp.GetAdjustmentPath(sa.AdjustmentFilterJSON, sa.GroupingHierarchyJSON, @PlanSectionID) AS AdjustedLevel, + ISNULL(dfm.Name, 'All') AS Months, + sa.Comment, + sa.AuthorFullName, + sa.LastModifiedDateUtc, + sa.DateCreatedUtc, + sa.SubsectionID, + sa.TimeClassID, + sa.BudgetPhaseID, + sa.ClassificationGroupID, + sa.ClassificationCategoryID, + CAST(140 AS TINYINT) AS UnitTypeID, + sa.IsErrored, + sa.IsRecordDeleted + FROM fp.StatisticsAdjustment AS sa WITH (NOLOCK) + JOIN #adjustments AS sadj ON sadj.AdjustmentID = sa.AdjustmentID + LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) ON dfm.FiscalMonthID = TRY_CAST(SUBSTRING(AdjustedProperty, PATINDEX('%[0-9]%', AdjustedProperty), LEN(AdjustedProperty)) AS INT) + WHERE sa.AdjustmentType IN (0, 1, 2, 3, 10, 11, 12, 13, 14) + + UNION ALL + + -- Import Adjustments + SELECT ROW_NUMBER() OVER (PARTITION BY sa.AdjustmentID, iadj.BudgetPhaseID ORDER BY sa.DateCreatedUtc DESC) AS RowNumber, + sa.AdjustmentID, + sa.AdjustmentType, + CASE WHEN iadj.RecordsCount = 1 THEN fp.GetAdjustmentReportValue(TotalValue, sa.AdjustmentType) + ELSE CAST(iadj.RecordsCount AS VARCHAR(30)) + ' records affected' + END AS [Value], + CASE WHEN iadj.DepartmentCount = 1 THEN d.Name + ELSE CAST(iadj.DepartmentCount AS VARCHAR(30)) + ' departments' + END AS AdjustedLevel, + CASE WHEN iadj.FiscalMonthCount = 1 THEN ISNULL(dfm.Name, 'Multiple') + ELSE 'Multiple' + END AS Months, + ag.Description AS Comment, + sa.AuthorFullName, + sa.LastModifiedDateUtc, + sa.DateCreatedUtc, + sa.SubsectionID, + iadj.TimeClassID, + iadj.BudgetPhaseID, + sa.ClassificationGroupID, + sa.ClassificationCategoryID, + iadj.UnitTypeID, + sa.IsErrored, + sa.IsRecordDeleted + FROM fp.StatisticsAdjustment AS sa WITH (NOLOCK) + JOIN #importAdjustments AS iadj ON iadj.AdjustmentID = sa.AdjustmentID + JOIN fp.viewAdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = sa.GroupingGUID + JOIN fw.DimDepartment AS d WITH (NOLOCK) ON iadj.DepartmentID = d.DepartmentID + LEFT JOIN fw.DimFiscalMonth dfm WITH(NOLOCK) on iadj.FiscalMonthID = dfm.FiscalMonthID + WHERE sa.AdjustmentType = 4 + + -- Add Provider adjustments + UNION ALL + + SELECT ROW_NUMBER() OVER (PARTITION BY sa.AdjustmentID, apsd.TimeClassID, apsd.BudgetPhaseID ORDER BY sa.DateCreatedUtc DESC) AS RowNumber, + sa.AdjustmentID, + sa.AdjustmentType, + fp.GetAdjustmentReportValue(apsd.Impact, sa.AdjustmentType) AS Value, + phys.Physician AS AdjustedLevel, + 'Multiple' AS Months, + aps.Comment, + sa.AuthorFullName, + sa.LastModifiedDateUtc, + sa.DateCreatedUtc, + sa.SubsectionID, + apsd.TimeClassID, + apsd.BudgetPhaseID, + aps.ClassificationGroupID, + aps.ClassificationCategoryID, + 140 AS UnitTypeID, + sa.IsErrored, + sa.IsRecordDeleted + FROM fp.StatisticsAdjustment AS sa WITH (NOLOCK) + JOIN #adjustments AS adj ON adj.AdjustmentID = sa.AdjustmentID + JOIN fp.StatisticAddProviderSummary AS aps ON aps.DriverAdjustmentGUID = sa.AdjustmentGUID + JOIN (SELECT SummaryID, + SUM(ProjectionImpact) AS Impact, + 12 AS TimeClassID, + 2 AS BudgetPhaseID + FROM fp.StatisticAddProviderSummaryDetails WITH (NOLOCK) + GROUP BY SummaryID + UNION ALL + SELECT SummaryID, + SUM(TargetImpact) AS Impact, + 2 AS TimeClassID, + 2 AS BudgetPhaseID + FROM fp.StatisticAddProviderSummaryDetails WITH (NOLOCK) + GROUP BY SummaryID + UNION ALL + SELECT SummaryID, + SUM(BudgetImpact) AS Impact, + 2 AS TimeClassID, + 3 AS BudgetPhaseID + FROM fp.StatisticAddProviderSummaryDetails WITH (NOLOCK) + GROUP BY SummaryID) AS apsd ON aps.SummaryID = apsd.SummaryID + JOIN dss.DimPhysician AS phys WITH (NOLOCK) ON phys.PhysicianID = aps.ProviderID + WHERE sa.AdjustmentType = 15 AND Impact <> 0 + ) AS res_inner + WHERE res_inner.RowNumber = 1 ) AS res + ORDER BY res.DateCreatedUtc DESC + +---------------------------------------------------------------------- +-- Insert data to reportTable +---------------------------------------------------------------------- +;WITH TGT AS +( + SELECT BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted + FROM fp.FactReportAdjustmentHistory fr + WHERE fr.BudgetConfigID = @BudgetConfigID + AND fr.SectionID IN (@SectionID_Driver, @SectionID_Dependent) +) + MERGE TGT AS target + USING #src AS source + ON ( + target.BudgetConfigID = source.BudgetConfigID + AND target.AdjustmentID = source.AdjustmentID + AND target.SectionID = source.SectionID + AND target.TimeClassID = source.TimeClassID + ) + WHEN MATCHED AND (target.LastModifiedDateUtc <> source.LastModifiedDateUtc) + THEN + UPDATE + SET target.LastModifiedDateUtc = source.LastModifiedDateUtc, + target.AdjustmentValue = source.AdjustmentValue, + target.IsErrored = source.IsErrored, + target.IsRecordDeleted = source.IsRecordDeleted, + target.ClassificationGroupID = source.ClassificationGroupID, + target.ClassificationCategoryID = source.ClassificationCategoryID, + target.Comment = source.Comment + + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + BudgetConfigID, + SectionID, + AdjustmentID, + AdjustmentType, + Months, + AdjustmentValue, + AdjustedLevel, + UnitTypeID, + TimeClassID, + LastModifiedDateUtc, + DateCreatedUtc, + Comment, + AuthorFullName, + ClassificationGroupID, + ClassificationCategoryID, + IsErrored, + IsRecordDeleted + ) + VALUES ( + source.BudgetConfigID, + source.SectionID, + source.AdjustmentID, + source.AdjustmentType, + source.Months, + source.AdjustmentValue, + source.AdjustedLevel, + source.UnitTypeID, + source.TimeClassID, + source.LastModifiedDateUtc, + source.DateCreatedUtc, + source.Comment, + source.AuthorFullName, + source.ClassificationGroupID, + source.ClassificationCategoryID, + source.IsErrored, + source.IsRecordDeleted + ); + + +END +GO + + +--------------------------------------------- + +-- fp.procReportCacheToggle +CREATE proc fp.procReportCacheToggle + @isEnabled bit +as + --disable proc logic + update fp.SystemSetting set Value = @isEnabled where Name = 'AP Report Cache Auto-Refresh'; + + if (@isEnabled = 0) begin + --make report datasources pull data live + exec('ALTER VIEW fp.viewFactGeneralLedger_Unpivoted AS SELECT * FROM fp.viewFactGeneralLedger_Unpivoted_source WHERE UnitTypeID = 34'); + exec('ALTER VIEW fp.viewFactGeneralLedgerHistory_Unpivoted AS SELECT * FROM fp.viewFactGeneralLedgerHistory_Unpivoted_source WHERE UnitTypeID = 34'); + exec('ALTER VIEW fp.viewFactStaffing_Unpivoted AS SELECT * FROM fp.viewFactStaffing_Unpivoted_source'); + exec('ALTER VIEW fp.viewFactStaffingHistory_Unpivoted AS SELECT * FROM fp.viewFactStaffingHistory_Unpivoted_source'); + exec('ALTER VIEW fp.viewFactStatistics_Unpivoted AS SELECT * FROM fp.viewFactStatistics_Unpivoted_source'); + exec('ALTER VIEW fp.viewFactStatisticsHistory_Unpivoted AS SELECT * FROM fp.viewFactStatisticsHistory_Unpivoted_source'); + exec('ALTER VIEW fp.viewFactGeneralLedger_Unpivoted_archive AS SELECT * FROM fp.viewFactGeneralLedger_Unpivoted_source WHERE UnitTypeID = 34'); + exec('ALTER VIEW fp.viewFactGeneralLedgerHistory_Unpivoted_archive AS SELECT * FROM fp.viewFactGeneralLedgerHistory_Unpivoted_source WHERE UnitTypeID = 34'); + exec('ALTER VIEW fp.viewFactStaffing_Unpivoted_archive AS SELECT * FROM fp.viewFactStaffing_Unpivoted_source'); + exec('ALTER VIEW fp.viewFactStaffingHistory_Unpivoted_archive AS SELECT * FROM fp.viewFactStaffingHistory_Unpivoted_source'); + exec('ALTER VIEW fp.viewFactStatistics_Unpivoted_archive AS SELECT * FROM fp.viewFactStatistics_Unpivoted_source'); + exec('ALTER VIEW fp.viewFactStatisticsHistory_Unpivoted_archive AS SELECT * FROM fp.viewFactStatisticsHistory_Unpivoted_source'); + + --make built-in IS report available, hide ad hoc IS report + update dbo.REReport set Name = 'Advanced Planning Income Statement' where ReportGUID = 'B58061D1-B9AB-446D-8C19-2545B2E5C190'; + update fp.SystemSetting set Value = 'B58061D1-B9AB-446D-8C19-2545B2E5C190' where Name ='AP Income Statement Report'; + update dbo.REReport set Name = '(Archived) Advanced Planning Income Statement' where ReportGUID = '04B7FB79-05D3-4DC4-BA44-9EC64990DF3D'; + delete from dbo.S3SimplePermission where LootID in('B58061D1-B9AB-446D-8C19-2545B2E5C190', '04B7FB79-05D3-4DC4-BA44-9EC64990DF3D'); + insert into dbo.S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) values('B58061D1-B9AB-446D-8C19-2545B2E5C190', 'F27A1CAA-8C07-4093-8990-A865BD82EDF2', 1, 0, 0); + insert into dbo.S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) values('B58061D1-B9AB-446D-8C19-2545B2E5C190', 'F314A324-D974-4F50-B26A-C89B8C1C5138', 1, 1, 0); + end else begin + --make report datasources pull data from cache + exec('ALTER VIEW fp.viewFactGeneralLedger_Unpivoted AS SELECT * FROM fp.FactReportGeneralLedger WHERE UnitTypeID = 34'); + exec('ALTER VIEW fp.viewFactGeneralLedgerHistory_Unpivoted AS SELECT * FROM fp.FactReportGeneralLedgerHistory WHERE UnitTypeID = 34'); + exec('ALTER VIEW fp.viewFactStaffing_Unpivoted AS SELECT * FROM fp.FactReportStaffing'); + exec('ALTER VIEW fp.viewFactStaffingHistory_Unpivoted AS SELECT * FROM fp.FactReportStaffingHistory'); + exec('ALTER VIEW fp.viewFactStatistics_Unpivoted AS SELECT * FROM fp.FactReportStatistics'); + exec('ALTER VIEW fp.viewFactStatisticsHistory_Unpivoted AS SELECT * FROM fp.FactReportStatisticsHistory'); + exec('ALTER VIEW fp.viewFactGeneralLedger_Unpivoted_archive AS SELECT * FROM fp.FactReportGeneralLedger_archive WHERE UnitTypeID = 34'); + exec('ALTER VIEW fp.viewFactGeneralLedgerHistory_Unpivoted_archive AS SELECT * FROM fp.FactReportGeneralLedgerHistory_archive WHERE UnitTypeID = 34'); + exec('ALTER VIEW fp.viewFactStaffing_Unpivoted_archive AS SELECT * FROM fp.FactReportStaffing_archive'); + exec('ALTER VIEW fp.viewFactStaffingHistory_Unpivoted_archive AS SELECT * FROM fp.FactReportStaffingHistory_archive'); + exec('ALTER VIEW fp.viewFactStatistics_Unpivoted_archive AS SELECT * FROM fp.FactReportStatistics_archive'); + exec('ALTER VIEW fp.viewFactStatisticsHistory_Unpivoted_archive AS SELECT * FROM fp.FactReportStatisticsHistory_archive'); + + --make ad hoc IS report available, hide built-in IS report + update dbo.REReport set Name = 'Advanced Planning Income Statement' where ReportGUID = '04B7FB79-05D3-4DC4-BA44-9EC64990DF3D'; + update fp.SystemSetting set Value = '04B7FB79-05D3-4DC4-BA44-9EC64990DF3D' where Name ='AP Income Statement Report'; + update dbo.REReport set Name = '(Archived) Advanced Planning Income Statement' where ReportGUID = 'B58061D1-B9AB-446D-8C19-2545B2E5C190'; + delete from dbo.S3SimplePermission where LootID in('B58061D1-B9AB-446D-8C19-2545B2E5C190', '04B7FB79-05D3-4DC4-BA44-9EC64990DF3D'); + insert into dbo.S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) values('04B7FB79-05D3-4DC4-BA44-9EC64990DF3D', 'F27A1CAA-8C07-4093-8990-A865BD82EDF2', 1, 0, 0); + insert into dbo.S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) values('04B7FB79-05D3-4DC4-BA44-9EC64990DF3D', 'F314A324-D974-4F50-B26A-C89B8C1C5138', 1, 1, 0); + + print 'WARNING: Report data will be incorrect until a full engine run completes or you manually run fp.procFactReportFinancialStatementInsert' + end + + --ad hoc history report security should always match the base report + delete from dbo.S3SimplePermission where LootID = '5A864BEA-D27E-435E-B192-05283781EA30'; + insert into dbo.S3SimplePermission (LootID, IdentityGUID, ReadValue, WriteValue, SecureValue) + select LootID, IdentityGUID, ReadValue, WriteValue, SecureValue from dbo.S3SimplePermission where LootID = '04B7FB79-05D3-4DC4-BA44-9EC64990DF3D'; +GO + + +--------------------------------------------- + +-- fp.procReportFactReimbursementHistory +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-10-13 MD JAZZ-32897 Adding union all for data transfer table + ** 2 2024-09-18 BW JAZZ-75453 Updated merge ON Clause to include ServiceLineRollupID +*************************************************************/ +CREATE PROCEDURE fp.procReportFactReimbursementHistory ( + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +) +WITH RECOMPILE +AS +BEGIN + +exec [dbo].[procSysDropTempTable] '#SRC' +exec [dbo].[procSysDropTempTable] '#rawChargeData' +exec [dbo].[procSysDropTempTable] '#rawEncounterData' +exec [dbo].[procSysDropTempTable] '#calculatedData' + +CREATE TABLE #SRC ( + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + PatientClassID INT, + ServiceLineID INT, + ServiceLineRollupID INT, + MedicalSurgicalID INT, + PayorID INT, + PayorGroupID INT, + MSDRGID INT, + PrimaryCPTID INT, + TimeClassID INT, + FiscalYearID INT, + FiscalMonthID TINYINT, + UnitTypeID INT, + Value DECIMAL(19,8) +) + +CREATE TABLE #rawChargeData ( + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + PatientClassID INT, + ServiceLineID INT, + ServiceLineRollupID INT, + MedicalSurgicalID INT, + PayorID INT, + PayorGroupID INT, + MSDRGID INT, + PrimaryCPTID INT, + TimeClassID INT, + FiscalYearID INT, + NetReimbursement01 DECIMAL (19,8), + NetReimbursement02 DECIMAL (19,8), + NetReimbursement03 DECIMAL (19,8), + NetReimbursement04 DECIMAL (19,8), + NetReimbursement05 DECIMAL (19,8), + NetReimbursement06 DECIMAL (19,8), + NetReimbursement07 DECIMAL (19,8), + NetReimbursement08 DECIMAL (19,8), + NetReimbursement09 DECIMAL (19,8), + NetReimbursement10 DECIMAL (19,8), + NetReimbursement11 DECIMAL (19,8), + NetReimbursement12 DECIMAL (19,8), + GrossCharges01 DECIMAL (19,8), + GrossCharges02 DECIMAL (19,8), + GrossCharges03 DECIMAL (19,8), + GrossCharges04 DECIMAL (19,8), + GrossCharges05 DECIMAL (19,8), + GrossCharges06 DECIMAL (19,8), + GrossCharges07 DECIMAL (19,8), + GrossCharges08 DECIMAL (19,8), + GrossCharges09 DECIMAL (19,8), + GrossCharges10 DECIMAL (19,8), + GrossCharges11 DECIMAL (19,8), + GrossCharges12 DECIMAL (19,8) +) + +CREATE TABLE #rawEncounterData ( + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + PatientClassID INT, + ServiceLineID INT, + ServiceLineRollupID INT, + MedicalSurgicalID INT, + PayorID INT, + PayorGroupID INT, + MSDRGID INT, + PrimaryCPTID INT, + TimeClassID INT, + FiscalYearID INT, + NetReimbursement01 DECIMAL (19,8), + NetReimbursement02 DECIMAL (19,8), + NetReimbursement03 DECIMAL (19,8), + NetReimbursement04 DECIMAL (19,8), + NetReimbursement05 DECIMAL (19,8), + NetReimbursement06 DECIMAL (19,8), + NetReimbursement07 DECIMAL (19,8), + NetReimbursement08 DECIMAL (19,8), + NetReimbursement09 DECIMAL (19,8), + NetReimbursement10 DECIMAL (19,8), + NetReimbursement11 DECIMAL (19,8), + NetReimbursement12 DECIMAL (19,8) +) + +CREATE TABLE #calculatedData ( + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + PatientClassID INT, + ServiceLineID INT, + ServiceLineRollupID INT, + MedicalSurgicalID INT, + PayorID INT, + PayorGroupID INT, + MSDRGID INT, + PrimaryCPTID INT, + TimeClassID INT, + FiscalYearID INT, + GrossCharges01 DECIMAL (19,8), + GrossCharges02 DECIMAL (19,8), + GrossCharges03 DECIMAL (19,8), + GrossCharges04 DECIMAL (19,8), + GrossCharges05 DECIMAL (19,8), + GrossCharges06 DECIMAL (19,8), + GrossCharges07 DECIMAL (19,8), + GrossCharges08 DECIMAL (19,8), + GrossCharges09 DECIMAL (19,8), + GrossCharges10 DECIMAL (19,8), + GrossCharges11 DECIMAL (19,8), + GrossCharges12 DECIMAL (19,8), + NetReimbursement01 DECIMAL (19,8), + NetReimbursement02 DECIMAL (19,8), + NetReimbursement03 DECIMAL (19,8), + NetReimbursement04 DECIMAL (19,8), + NetReimbursement05 DECIMAL (19,8), + NetReimbursement06 DECIMAL (19,8), + NetReimbursement07 DECIMAL (19,8), + NetReimbursement08 DECIMAL (19,8), + NetReimbursement09 DECIMAL (19,8), + NetReimbursement10 DECIMAL (19,8), + NetReimbursement11 DECIMAL (19,8), + NetReimbursement12 DECIMAL (19,8), + ContractualAllowance01 DECIMAL (19,8), + ContractualAllowance02 DECIMAL (19,8), + ContractualAllowance03 DECIMAL (19,8), + ContractualAllowance04 DECIMAL (19,8), + ContractualAllowance05 DECIMAL (19,8), + ContractualAllowance06 DECIMAL (19,8), + ContractualAllowance07 DECIMAL (19,8), + ContractualAllowance08 DECIMAL (19,8), + ContractualAllowance09 DECIMAL (19,8), + ContractualAllowance10 DECIMAL (19,8), + ContractualAllowance11 DECIMAL (19,8), + ContractualAllowance12 DECIMAL (19,8) +) + +-------------------------------------------------------------- +--Get reimbursement encounter data +-------------------------------------------------------------- +INSERT INTO #rawEncounterData (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, + MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID, + NetReimbursement01, NetReimbursement02, NetReimbursement03, NetReimbursement04, + NetReimbursement05, NetReimbursement06, NetReimbursement07, NetReimbursement08, + NetReimbursement09, NetReimbursement10, NetReimbursement11, NetReimbursement12) +SELECT + fre.BudgetConfigID, + fre.EntityGroupConfigID, + fre.EntityID, + fre.PatientClassID, + fre.ServiceLineID, + fre.ServiceLineRollupID, + fre.MedicalSurgicalID, + fre.PayorID, + fre.PayorGroupID, + fre.MSDRGID, + fre.CPTID, + fre.TimeClassID, + fre.FiscalYearID, + fre.NetReimbursementValue01, + fre.NetReimbursementValue02, + fre.NetReimbursementValue03, + fre.NetReimbursementValue04, + fre.NetReimbursementValue05, + fre.NetReimbursementValue06, + fre.NetReimbursementValue07, + fre.NetReimbursementValue08, + fre.NetReimbursementValue09, + fre.NetReimbursementValue10, + fre.NetReimbursementValue11, + fre.NetReimbursementValue12 +FROM fp.viewFactReimbursementEncountersHistory_Unpivoted_source fre +WHERE + fre.BudgetConfigID = @BudgetConfigID + +-------------------------------------------------------------- +--Get reimbursement charge data +-------------------------------------------------------------- +INSERT INTO #rawChargeData (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, + MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID, + GrossCharges01, GrossCharges02, GrossCharges03, GrossCharges04, + GrossCharges05, GrossCharges06, GrossCharges07, GrossCharges08, + GrossCharges09, GrossCharges10, GrossCharges11, GrossCharges12, + NetReimbursement01, NetReimbursement02, NetReimbursement03, NetReimbursement04, + NetReimbursement05, NetReimbursement06, NetReimbursement07, NetReimbursement08, + NetReimbursement09, NetReimbursement10, NetReimbursement11, NetReimbursement12) +SELECT + frc.BudgetConfigID, + frc.EntityGroupConfigID, + frc.EntityID, + frc.PatientClassID, + frc.ServiceLineID, + frc.ServiceLineRollupID, + frc.MedicalSurgicalID, + frc.PayorID, + frc.PayorGroupID, + frc.MSDRGID, + frc.PrimaryCPTID, + frc.TimeClassID, + frc.FiscalYearID, + frc.ChargeDollarsValue01, + frc.ChargeDollarsValue02, + frc.ChargeDollarsValue03, + frc.ChargeDollarsValue04, + frc.ChargeDollarsValue05, + frc.ChargeDollarsValue06, + frc.ChargeDollarsValue07, + frc.ChargeDollarsValue08, + frc.ChargeDollarsValue09, + frc.ChargeDollarsValue10, + frc.ChargeDollarsValue11, + frc.ChargeDollarsValue12, + frc.NetReimbursementValue01, + frc.NetReimbursementValue02, + frc.NetReimbursementValue03, + frc.NetReimbursementValue04, + frc.NetReimbursementValue05, + frc.NetReimbursementValue06, + frc.NetReimbursementValue07, + frc.NetReimbursementValue08, + frc.NetReimbursementValue09, + frc.NetReimbursementValue10, + frc.NetReimbursementValue11, + frc.NetReimbursementValue12 +FROM fp.viewFactReimbursementChargesHistory_Unpivoted_source frc +WHERE + frc.BudgetConfigID = @BudgetConfigID + +-------------------------------------------------------------- +--Do allocation calculation +--ChargeDollarsXX - ChargeNetReimbursementXX - EncounterNetReimbursementXX +-------------------------------------------------------------- +INSERT INTO #calculatedData (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, + MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID, + GrossCharges01, GrossCharges02, GrossCharges03, GrossCharges04, + GrossCharges05, GrossCharges06, GrossCharges07, GrossCharges08, + GrossCharges09, GrossCharges10, GrossCharges11, GrossCharges12, + NetReimbursement01, NetReimbursement02, NetReimbursement03, NetReimbursement04, + NetReimbursement05, NetReimbursement06, NetReimbursement07, NetReimbursement08, + NetReimbursement09, NetReimbursement10, NetReimbursement11, NetReimbursement12, + ContractualAllowance01, ContractualAllowance02, ContractualAllowance03, ContractualAllowance04, + ContractualAllowance05, ContractualAllowance06, ContractualAllowance07, ContractualAllowance08, + ContractualAllowance09, ContractualAllowance10, ContractualAllowance11, ContractualAllowance12 +) +SELECT + ISNULL(frc.BudgetConfigID, fre.BudgetConfigID), + ISNULL(frc.EntityGroupConfigID, fre.EntityGroupConfigID), + ISNULL(frc.EntityID, fre.EntityID), + ISNULL(frc.PatientClassID, fre.PatientClassID), + ISNULL(frc.ServiceLineID, fre.ServiceLineID), + ISNULL(frc.ServiceLineRollupID, fre.ServiceLineRollupID), + ISNULL(frc.MedicalSurgicalID, fre.MedicalSurgicalID), + ISNULL(frc.PayorID, fre.PayorID), + ISNULL(frc.PayorGroupID, fre.PayorGroupID), + ISNULL(frc.MSDRGID, fre.MSDRGID), + ISNULL(frc.PrimaryCPTID, fre.PrimaryCPTID), + ISNULL(frc.TimeClassID, fre.TimeClassID), + ISNULL(frc.FiscalYearID, fre.FiscalYearID), + ISNULL(frc.GrossCharges01,0), + ISNULL(frc.GrossCharges02,0), + ISNULL(frc.GrossCharges03,0), + ISNULL(frc.GrossCharges04,0), + ISNULL(frc.GrossCharges05,0), + ISNULL(frc.GrossCharges06,0), + ISNULL(frc.GrossCharges07,0), + ISNULL(frc.GrossCharges08,0), + ISNULL(frc.GrossCharges09,0), + ISNULL(frc.GrossCharges10,0), + ISNULL(frc.GrossCharges11,0), + ISNULL(frc.GrossCharges12,0), + ISNULL(ISNULL(frc.NetReimbursement01,0) + ISNULL(fre.NetReimbursement01,0),0), + ISNULL(ISNULL(frc.NetReimbursement02,0) + ISNULL(fre.NetReimbursement02,0),0), + ISNULL(ISNULL(frc.NetReimbursement03,0) + ISNULL(fre.NetReimbursement03,0),0), + ISNULL(ISNULL(frc.NetReimbursement04,0) + ISNULL(fre.NetReimbursement04,0),0), + ISNULL(ISNULL(frc.NetReimbursement05,0) + ISNULL(fre.NetReimbursement05,0),0), + ISNULL(ISNULL(frc.NetReimbursement06,0) + ISNULL(fre.NetReimbursement06,0),0), + ISNULL(ISNULL(frc.NetReimbursement07,0) + ISNULL(fre.NetReimbursement07,0),0), + ISNULL(ISNULL(frc.NetReimbursement08,0) + ISNULL(fre.NetReimbursement08,0),0), + ISNULL(ISNULL(frc.NetReimbursement09,0) + ISNULL(fre.NetReimbursement09,0),0), + ISNULL(ISNULL(frc.NetReimbursement10,0) + ISNULL(fre.NetReimbursement10,0),0), + ISNULL(ISNULL(frc.NetReimbursement11,0) + ISNULL(fre.NetReimbursement11,0),0), + ISNULL(ISNULL(frc.NetReimbursement12,0) + ISNULL(fre.NetReimbursement12,0),0), + ISNULL(ISNULL(frc.GrossCharges01,0) - (ISNULL(frc.NetReimbursement01,0) + ISNULL(fre.NetReimbursement01,0)),0), + ISNULL(ISNULL(frc.GrossCharges02,0) - (ISNULL(frc.NetReimbursement02,0) + ISNULL(fre.NetReimbursement02,0)),0), + ISNULL(ISNULL(frc.GrossCharges03,0) - (ISNULL(frc.NetReimbursement03,0) + ISNULL(fre.NetReimbursement03,0)),0), + ISNULL(ISNULL(frc.GrossCharges04,0) - (ISNULL(frc.NetReimbursement04,0) + ISNULL(fre.NetReimbursement04,0)),0), + ISNULL(ISNULL(frc.GrossCharges05,0) - (ISNULL(frc.NetReimbursement05,0) + ISNULL(fre.NetReimbursement05,0)),0), + ISNULL(ISNULL(frc.GrossCharges06,0) - (ISNULL(frc.NetReimbursement06,0) + ISNULL(fre.NetReimbursement06,0)),0), + ISNULL(ISNULL(frc.GrossCharges07,0) - (ISNULL(frc.NetReimbursement07,0) + ISNULL(fre.NetReimbursement07,0)),0), + ISNULL(ISNULL(frc.GrossCharges08,0) - (ISNULL(frc.NetReimbursement08,0) + ISNULL(fre.NetReimbursement08,0)),0), + ISNULL(ISNULL(frc.GrossCharges09,0) - (ISNULL(frc.NetReimbursement09,0) + ISNULL(fre.NetReimbursement09,0)),0), + ISNULL(ISNULL(frc.GrossCharges10,0) - (ISNULL(frc.NetReimbursement10,0) + ISNULL(fre.NetReimbursement10,0)),0), + ISNULL(ISNULL(frc.GrossCharges11,0) - (ISNULL(frc.NetReimbursement11,0) + ISNULL(fre.NetReimbursement11,0)),0), + ISNULL(ISNULL(frc.GrossCharges12,0) - (ISNULL(frc.NetReimbursement12,0) + ISNULL(fre.NetReimbursement12,0)),0) +FROM #rawChargeData frc +FULL JOIN #rawEncounterData fre + ON frc.BudgetConfigID = fre.BudgetConfigID + AND frc.EntityGroupConfigID = fre.EntityGroupConfigID + AND frc.EntityID = fre.EntityID + AND frc.PatientClassID = fre.PatientClassID + AND frc.ServiceLineID = fre.ServiceLineID + AND frc.ServiceLineRollupID = fre.ServiceLineRollupID + AND frc.MedicalSurgicalID = fre.MedicalSurgicalID + AND frc.PayorID = fre.PayorID + AND frc.PayorGroupID = fre.PayorGroupID + AND frc.MSDRGID = fre.MSDRGID + AND frc.PrimaryCPTID = fre.PrimaryCPTID + AND frc.TimeClassID = fre.TimeClassID + AND frc.FiscalYearID = frc.FiscalYearID + +CREATE CLUSTERED INDEX inx_src ON #SRC ( + BudgetConfigID, + EntityGroupConfigID, + EntityID, + PatientClassID, + ServiceLineID, + ServiceLineRollupID, + MedicalSurgicalID, + PayorID, + PayorGroupID, + MSDRGID, + PrimaryCPTID, + TimeClassID, + FiscalYearID, + FiscalMonthID +) + +-------------------------------------------------------------- +--Pivot data into #SRC table +-------------------------------------------------------------- +INSERT INTO #SRC (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, + MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID, FiscalMonthID, UnitTypeID, Value) +SELECT + cv.BudgetConfigID, + cv.EntityGroupConfigID, + cv.EntityID, + cv.PatientClassID, + cv.ServiceLineID, + cv.ServiceLineRollupID, + cv.MedicalSurgicalID, + cv.PayorID, + cv.PayorGroupID, + cv.MSDRGID, + cv.PrimaryCPTID, + cv.TimeClassID, + cv.FiscalYearID, + m.FiscalMonthID, + cv.UnitTypeID, + SUM(cv.Value) AS Value +FROM ( + SELECT + BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, + ServiceLineID, ServiceLineRollupID, MedicalSurgicalID, PayorID, + PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID, + FiscalMonth, UnitTypeID, Value + FROM #calculatedData cd + CROSS APPLY ( + VALUES + ('Month01', GrossCharges01, 177), + ('Month02', GrossCharges02, 177), + ('Month03', GrossCharges03, 177), + ('Month04', GrossCharges04, 177), + ('Month05', GrossCharges05, 177), + ('Month06', GrossCharges06, 177), + ('Month07', GrossCharges07, 177), + ('Month08', GrossCharges08, 177), + ('Month09', GrossCharges09, 177), + ('Month10', GrossCharges10, 177), + ('Month11', GrossCharges11, 177), + ('Month12', GrossCharges12, 177), + ('Month01', NetReimbursement01, 179), + ('Month02', NetReimbursement02, 179), + ('Month03', NetReimbursement03, 179), + ('Month04', NetReimbursement04, 179), + ('Month05', NetReimbursement05, 179), + ('Month06', NetReimbursement06, 179), + ('Month07', NetReimbursement07, 179), + ('Month08', NetReimbursement08, 179), + ('Month09', NetReimbursement09, 179), + ('Month10', NetReimbursement10, 179), + ('Month11', NetReimbursement11, 179), + ('Month12', NetReimbursement12, 179), + ('Month01', ContractualAllowance01, 178), + ('Month02', ContractualAllowance02, 178), + ('Month03', ContractualAllowance03, 178), + ('Month04', ContractualAllowance04, 178), + ('Month05', ContractualAllowance05, 178), + ('Month06', ContractualAllowance06, 178), + ('Month07', ContractualAllowance07, 178), + ('Month08', ContractualAllowance08, 178), + ('Month09', ContractualAllowance09, 178), + ('Month10', ContractualAllowance10, 178), + ('Month11', ContractualAllowance11, 178), + ('Month12', ContractualAllowance12, 178)) X (FiscalMonth, Value, UnitTypeID) +) cv +INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = cv.FiscalMonth +GROUP BY cv.BudgetConfigID, + cv.EntityGroupConfigID, + cv.EntityID, + cv.PatientClassID, + cv.ServiceLineID, + cv.ServiceLineRollupID, + cv.MedicalSurgicalID, + cv.PayorID, + cv.PayorGroupID, + cv.MSDRGID, + cv.PrimaryCPTID, + cv.TimeClassID, + cv.FiscalYearID, + m.FiscalMonthID, + cv.UnitTypeID + +;WITH TGT AS +( + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, + MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID, FiscalMonthID, UnitTypeID, Value + FROM fp.FactReportReimbursement fr + WHERE fr.BudgetConfigID = @BudgetConfigID +) + MERGE TGT as target + USING #SRC AS source + ON ( + target.BudgetConfigID = source.BudgetConfigID + AND target.EntityGroupConfigID = source.EntityGroupConfigID + AND target.EntityID = source.EntityID + AND target.PatientClassID = source.PatientClassID + AND target.ServiceLineID = source.ServiceLineID + AND target.ServiceLineRollupID = source.ServiceLineRollupID + AND target.MedicalSurgicalID = source.MedicalSurgicalID + AND target.PayorID = source.PayorID + AND target.PayorGroupID = source.PayorGroupID + AND target.MSDRGID = source.MSDRGID + AND target.PrimaryCPTID = source.PrimaryCPTID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalYearID = source.FiscalYearID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.UnitTypeID = source.UnitTypeID + ) + WHEN MATCHED AND (target.Value <> source.Value) + THEN + UPDATE + SET target.Value = ISNULL(source.Value, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + BudgetConfigID, + EntityGroupConfigID, + EntityID, + PatientClassID, + ServiceLineID, + ServiceLineRollupID, + MedicalSurgicalID, + PayorID, + PayorGroupID, + MSDRGID, + PrimaryCPTID, + TimeClassID, + FiscalYearID, + FiscalMonthID, + UnitTypeID, + Value + ) + VALUES ( + source.BudgetConfigID, + source.EntityGroupConfigID, + source.EntityID, + source.PatientClassID, + source.ServiceLineID, + source.ServiceLineRollupID, + source.MedicalSurgicalID, + source.PayorID, + source.PayorGroupID, + source.MSDRGID, + source.PrimaryCPTID, + source.TimeClassID, + source.FiscalYearID, + source.FiscalMonthID, + source.UnitTypeID, + ISNULL(source.Value, 0) + ); +END; +GO + + +--------------------------------------------- + +-- fp.procReportFactReimbursement_ProjectionAndBudget +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-10-13 MD JAZZ-32897 Adding union all for data transfer table + ** 2 2024-09-18 BW JAZZ-75453 Updated merge ON Clause to include ServiceLineRollupID +*************************************************************/ +CREATE PROCEDURE fp.procReportFactReimbursement_ProjectionAndBudget ( + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +) +WITH RECOMPILE +AS +BEGIN + +exec [dbo].[procSysDropTempTable] '#SRC' +exec [dbo].[procSysDropTempTable] '#rawChargeData' +exec [dbo].[procSysDropTempTable] '#rawEncounterData' +exec [dbo].[procSysDropTempTable] '#calculatedData' + +CREATE TABLE #SRC ( + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + PatientClassID INT, + ServiceLineID INT, + ServiceLineRollupID INT, + MedicalSurgicalID INT, + PayorID INT, + PayorGroupID INT, + MSDRGID INT, + PrimaryCPTID INT, + TimeClassID INT, + FiscalYearID INT, + FiscalMonthID TINYINT, + UnitTypeID INT, + Value DECIMAL(19,8) +) + +CREATE TABLE #rawChargeData ( + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + PatientClassID INT, + ServiceLineID INT, + ServiceLineRollupID INT, + MedicalSurgicalID INT, + PayorID INT, + PayorGroupID INT, + MSDRGID INT, + PrimaryCPTID INT, + TimeClassID INT, + FiscalYearID INT, + NetReimbursement01 DECIMAL (19,8), + NetReimbursement02 DECIMAL (19,8), + NetReimbursement03 DECIMAL (19,8), + NetReimbursement04 DECIMAL (19,8), + NetReimbursement05 DECIMAL (19,8), + NetReimbursement06 DECIMAL (19,8), + NetReimbursement07 DECIMAL (19,8), + NetReimbursement08 DECIMAL (19,8), + NetReimbursement09 DECIMAL (19,8), + NetReimbursement10 DECIMAL (19,8), + NetReimbursement11 DECIMAL (19,8), + NetReimbursement12 DECIMAL (19,8), + GrossCharges01 DECIMAL (19,8), + GrossCharges02 DECIMAL (19,8), + GrossCharges03 DECIMAL (19,8), + GrossCharges04 DECIMAL (19,8), + GrossCharges05 DECIMAL (19,8), + GrossCharges06 DECIMAL (19,8), + GrossCharges07 DECIMAL (19,8), + GrossCharges08 DECIMAL (19,8), + GrossCharges09 DECIMAL (19,8), + GrossCharges10 DECIMAL (19,8), + GrossCharges11 DECIMAL (19,8), + GrossCharges12 DECIMAL (19,8) +) + +CREATE TABLE #rawEncounterData ( + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + PatientClassID INT, + ServiceLineID INT, + ServiceLineRollupID INT, + MedicalSurgicalID INT, + PayorID INT, + PayorGroupID INT, + MSDRGID INT, + PrimaryCPTID INT, + TimeClassID INT, + FiscalYearID INT, + NetReimbursement01 DECIMAL (19,8), + NetReimbursement02 DECIMAL (19,8), + NetReimbursement03 DECIMAL (19,8), + NetReimbursement04 DECIMAL (19,8), + NetReimbursement05 DECIMAL (19,8), + NetReimbursement06 DECIMAL (19,8), + NetReimbursement07 DECIMAL (19,8), + NetReimbursement08 DECIMAL (19,8), + NetReimbursement09 DECIMAL (19,8), + NetReimbursement10 DECIMAL (19,8), + NetReimbursement11 DECIMAL (19,8), + NetReimbursement12 DECIMAL (19,8) +) + +CREATE TABLE #calculatedData ( + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + PatientClassID INT, + ServiceLineID INT, + ServiceLineRollupID INT, + MedicalSurgicalID INT, + PayorID INT, + PayorGroupID INT, + MSDRGID INT, + PrimaryCPTID INT, + TimeClassID INT, + FiscalYearID INT, + GrossCharges01 DECIMAL (19,8), + GrossCharges02 DECIMAL (19,8), + GrossCharges03 DECIMAL (19,8), + GrossCharges04 DECIMAL (19,8), + GrossCharges05 DECIMAL (19,8), + GrossCharges06 DECIMAL (19,8), + GrossCharges07 DECIMAL (19,8), + GrossCharges08 DECIMAL (19,8), + GrossCharges09 DECIMAL (19,8), + GrossCharges10 DECIMAL (19,8), + GrossCharges11 DECIMAL (19,8), + GrossCharges12 DECIMAL (19,8), + NetReimbursement01 DECIMAL (19,8), + NetReimbursement02 DECIMAL (19,8), + NetReimbursement03 DECIMAL (19,8), + NetReimbursement04 DECIMAL (19,8), + NetReimbursement05 DECIMAL (19,8), + NetReimbursement06 DECIMAL (19,8), + NetReimbursement07 DECIMAL (19,8), + NetReimbursement08 DECIMAL (19,8), + NetReimbursement09 DECIMAL (19,8), + NetReimbursement10 DECIMAL (19,8), + NetReimbursement11 DECIMAL (19,8), + NetReimbursement12 DECIMAL (19,8), + ContractualAllowance01 DECIMAL (19,8), + ContractualAllowance02 DECIMAL (19,8), + ContractualAllowance03 DECIMAL (19,8), + ContractualAllowance04 DECIMAL (19,8), + ContractualAllowance05 DECIMAL (19,8), + ContractualAllowance06 DECIMAL (19,8), + ContractualAllowance07 DECIMAL (19,8), + ContractualAllowance08 DECIMAL (19,8), + ContractualAllowance09 DECIMAL (19,8), + ContractualAllowance10 DECIMAL (19,8), + ContractualAllowance11 DECIMAL (19,8), + ContractualAllowance12 DECIMAL (19,8) +) + +-------------------------------------------------------------- +--Get reimbursement encounter data +-------------------------------------------------------------- +INSERT INTO #rawEncounterData (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, + MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID, + NetReimbursement01, NetReimbursement02, NetReimbursement03, NetReimbursement04, + NetReimbursement05, NetReimbursement06, NetReimbursement07, NetReimbursement08, + NetReimbursement09, NetReimbursement10, NetReimbursement11, NetReimbursement12) +SELECT + fre.BudgetConfigID, + fre.EntityGroupConfigID, + fre.EntityID, + fre.PatientClassID, + fre.ServiceLineID, + fre.ServiceLineRollupID, + fre.MedicalSurgicalID, + fre.PayorID, + fre.PayorGroupID, + fre.MSDRGID, + fre.CPTID, + fre.TimeClassID, + fre.FiscalYearID, + fre.NetReimbursementValue01, + fre.NetReimbursementValue02, + fre.NetReimbursementValue03, + fre.NetReimbursementValue04, + fre.NetReimbursementValue05, + fre.NetReimbursementValue06, + fre.NetReimbursementValue07, + fre.NetReimbursementValue08, + fre.NetReimbursementValue09, + fre.NetReimbursementValue10, + fre.NetReimbursementValue11, + fre.NetReimbursementValue12 +FROM fp.viewFactReimbursementEncounters_Unpivoted_source fre +WHERE + fre.BudgetConfigID = @BudgetConfigID + +-------------------------------------------------------------- +--Get reimbursement charge data +-------------------------------------------------------------- +INSERT INTO #rawChargeData (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, + MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID, + GrossCharges01, GrossCharges02, GrossCharges03, GrossCharges04, + GrossCharges05, GrossCharges06, GrossCharges07, GrossCharges08, + GrossCharges09, GrossCharges10, GrossCharges11, GrossCharges12, + NetReimbursement01, NetReimbursement02, NetReimbursement03, NetReimbursement04, + NetReimbursement05, NetReimbursement06, NetReimbursement07, NetReimbursement08, + NetReimbursement09, NetReimbursement10, NetReimbursement11, NetReimbursement12) +SELECT + frc.BudgetConfigID, + frc.EntityGroupConfigID, + frc.EntityID, + frc.PatientClassID, + frc.ServiceLineID, + frc.ServiceLineRollupID, + frc.MedicalSurgicalID, + frc.PayorID, + frc.PayorGroupID, + frc.MSDRGID, + frc.PrimaryCPTID, + frc.TimeClassID, + frc.FiscalYearID, + frc.ChargeDollarsValue01, + frc.ChargeDollarsValue02, + frc.ChargeDollarsValue03, + frc.ChargeDollarsValue04, + frc.ChargeDollarsValue05, + frc.ChargeDollarsValue06, + frc.ChargeDollarsValue07, + frc.ChargeDollarsValue08, + frc.ChargeDollarsValue09, + frc.ChargeDollarsValue10, + frc.ChargeDollarsValue11, + frc.ChargeDollarsValue12, + frc.NetReimbursementValue01, + frc.NetReimbursementValue02, + frc.NetReimbursementValue03, + frc.NetReimbursementValue04, + frc.NetReimbursementValue05, + frc.NetReimbursementValue06, + frc.NetReimbursementValue07, + frc.NetReimbursementValue08, + frc.NetReimbursementValue09, + frc.NetReimbursementValue10, + frc.NetReimbursementValue11, + frc.NetReimbursementValue12 +FROM fp.viewFactReimbursementCharges_Unpivoted_source frc +WHERE + frc.BudgetConfigID = @BudgetConfigID + +-------------------------------------------------------------- +--Do allocation calculation +--ChargeDollarsXX - ChargeNetReimbursementXX - EncounterNetReimbursementXX +-------------------------------------------------------------- +INSERT INTO #calculatedData (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, + MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID, + GrossCharges01, GrossCharges02, GrossCharges03, GrossCharges04, + GrossCharges05, GrossCharges06, GrossCharges07, GrossCharges08, + GrossCharges09, GrossCharges10, GrossCharges11, GrossCharges12, + NetReimbursement01, NetReimbursement02, NetReimbursement03, NetReimbursement04, + NetReimbursement05, NetReimbursement06, NetReimbursement07, NetReimbursement08, + NetReimbursement09, NetReimbursement10, NetReimbursement11, NetReimbursement12, + ContractualAllowance01, ContractualAllowance02, ContractualAllowance03, ContractualAllowance04, + ContractualAllowance05, ContractualAllowance06, ContractualAllowance07, ContractualAllowance08, + ContractualAllowance09, ContractualAllowance10, ContractualAllowance11, ContractualAllowance12 +) +SELECT + ISNULL(frc.BudgetConfigID, fre.BudgetConfigID), + ISNULL(frc.EntityGroupConfigID, fre.EntityGroupConfigID), + ISNULL(frc.EntityID, fre.EntityID), + ISNULL(frc.PatientClassID, fre.PatientClassID), + ISNULL(frc.ServiceLineID, fre.ServiceLineID), + ISNULL(frc.ServiceLineRollupID, fre.ServiceLineRollupID), + ISNULL(frc.MedicalSurgicalID, fre.MedicalSurgicalID), + ISNULL(frc.PayorID, fre.PayorID), + ISNULL(frc.PayorGroupID, fre.PayorGroupID), + ISNULL(frc.MSDRGID, fre.MSDRGID), + ISNULL(frc.PrimaryCPTID, fre.PrimaryCPTID), + ISNULL(frc.TimeClassID, fre.TimeClassID), + ISNULL(frc.FiscalYearID, fre.FiscalYearID), + ISNULL(frc.GrossCharges01,0), + ISNULL(frc.GrossCharges02,0), + ISNULL(frc.GrossCharges03,0), + ISNULL(frc.GrossCharges04,0), + ISNULL(frc.GrossCharges05,0), + ISNULL(frc.GrossCharges06,0), + ISNULL(frc.GrossCharges07,0), + ISNULL(frc.GrossCharges08,0), + ISNULL(frc.GrossCharges09,0), + ISNULL(frc.GrossCharges10,0), + ISNULL(frc.GrossCharges11,0), + ISNULL(frc.GrossCharges12,0), + ISNULL(ISNULL(frc.NetReimbursement01,0) + ISNULL(fre.NetReimbursement01,0),0), + ISNULL(ISNULL(frc.NetReimbursement02,0) + ISNULL(fre.NetReimbursement02,0),0), + ISNULL(ISNULL(frc.NetReimbursement03,0) + ISNULL(fre.NetReimbursement03,0),0), + ISNULL(ISNULL(frc.NetReimbursement04,0) + ISNULL(fre.NetReimbursement04,0),0), + ISNULL(ISNULL(frc.NetReimbursement05,0) + ISNULL(fre.NetReimbursement05,0),0), + ISNULL(ISNULL(frc.NetReimbursement06,0) + ISNULL(fre.NetReimbursement06,0),0), + ISNULL(ISNULL(frc.NetReimbursement07,0) + ISNULL(fre.NetReimbursement07,0),0), + ISNULL(ISNULL(frc.NetReimbursement08,0) + ISNULL(fre.NetReimbursement08,0),0), + ISNULL(ISNULL(frc.NetReimbursement09,0) + ISNULL(fre.NetReimbursement09,0),0), + ISNULL(ISNULL(frc.NetReimbursement10,0) + ISNULL(fre.NetReimbursement10,0),0), + ISNULL(ISNULL(frc.NetReimbursement11,0) + ISNULL(fre.NetReimbursement11,0),0), + ISNULL(ISNULL(frc.NetReimbursement12,0) + ISNULL(fre.NetReimbursement12,0),0), + ISNULL(ISNULL(frc.GrossCharges01,0) - (ISNULL(frc.NetReimbursement01,0) + ISNULL(fre.NetReimbursement01,0)),0), + ISNULL(ISNULL(frc.GrossCharges02,0) - (ISNULL(frc.NetReimbursement02,0) + ISNULL(fre.NetReimbursement02,0)),0), + ISNULL(ISNULL(frc.GrossCharges03,0) - (ISNULL(frc.NetReimbursement03,0) + ISNULL(fre.NetReimbursement03,0)),0), + ISNULL(ISNULL(frc.GrossCharges04,0) - (ISNULL(frc.NetReimbursement04,0) + ISNULL(fre.NetReimbursement04,0)),0), + ISNULL(ISNULL(frc.GrossCharges05,0) - (ISNULL(frc.NetReimbursement05,0) + ISNULL(fre.NetReimbursement05,0)),0), + ISNULL(ISNULL(frc.GrossCharges06,0) - (ISNULL(frc.NetReimbursement06,0) + ISNULL(fre.NetReimbursement06,0)),0), + ISNULL(ISNULL(frc.GrossCharges07,0) - (ISNULL(frc.NetReimbursement07,0) + ISNULL(fre.NetReimbursement07,0)),0), + ISNULL(ISNULL(frc.GrossCharges08,0) - (ISNULL(frc.NetReimbursement08,0) + ISNULL(fre.NetReimbursement08,0)),0), + ISNULL(ISNULL(frc.GrossCharges09,0) - (ISNULL(frc.NetReimbursement09,0) + ISNULL(fre.NetReimbursement09,0)),0), + ISNULL(ISNULL(frc.GrossCharges10,0) - (ISNULL(frc.NetReimbursement10,0) + ISNULL(fre.NetReimbursement10,0)),0), + ISNULL(ISNULL(frc.GrossCharges11,0) - (ISNULL(frc.NetReimbursement11,0) + ISNULL(fre.NetReimbursement11,0)),0), + ISNULL(ISNULL(frc.GrossCharges12,0) - (ISNULL(frc.NetReimbursement12,0) + ISNULL(fre.NetReimbursement12,0)),0) +FROM #rawChargeData frc +FULL JOIN #rawEncounterData fre + ON frc.BudgetConfigID = fre.BudgetConfigID + AND frc.EntityGroupConfigID = fre.EntityGroupConfigID + AND frc.EntityID = fre.EntityID + AND frc.PatientClassID = fre.PatientClassID + AND frc.ServiceLineID = fre.ServiceLineID + AND frc.ServiceLineRollupID = fre.ServiceLineRollupID + AND frc.MedicalSurgicalID = fre.MedicalSurgicalID + AND frc.PayorID = fre.PayorID + AND frc.PayorGroupID = fre.PayorGroupID + AND frc.MSDRGID = fre.MSDRGID + AND frc.PrimaryCPTID = fre.PrimaryCPTID + AND frc.TimeClassID = fre.TimeClassID + AND frc.FiscalYearID = frc.FiscalYearID + +CREATE CLUSTERED INDEX inx_src ON #SRC ( + BudgetConfigID, + EntityGroupConfigID, + EntityID, + PatientClassID, + ServiceLineID, + ServiceLineRollupID, + MedicalSurgicalID, + PayorID, + PayorGroupID, + MSDRGID, + PrimaryCPTID, + TimeClassID, + FiscalYearID, + FiscalMonthID +) + +-------------------------------------------------------------- +--Pivot data into #SRC table +-------------------------------------------------------------- +INSERT INTO #SRC (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, + MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID, FiscalMonthID, UnitTypeID, Value) +SELECT + cv.BudgetConfigID, + cv.EntityGroupConfigID, + cv.EntityID, + cv.PatientClassID, + cv.ServiceLineID, + cv.ServiceLineRollupID, + cv.MedicalSurgicalID, + cv.PayorID, + cv.PayorGroupID, + cv.MSDRGID, + cv.PrimaryCPTID, + cv.TimeClassID, + cv.FiscalYearID, + m.FiscalMonthID, + cv.UnitTypeID, + SUM(cv.Value) AS Value +FROM ( + SELECT + BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, + ServiceLineID, ServiceLineRollupID, MedicalSurgicalID, PayorID, + PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID, + FiscalMonth, UnitTypeID, Value + FROM #calculatedData cd + CROSS APPLY ( + VALUES + ('Month01', GrossCharges01, 177), + ('Month02', GrossCharges02, 177), + ('Month03', GrossCharges03, 177), + ('Month04', GrossCharges04, 177), + ('Month05', GrossCharges05, 177), + ('Month06', GrossCharges06, 177), + ('Month07', GrossCharges07, 177), + ('Month08', GrossCharges08, 177), + ('Month09', GrossCharges09, 177), + ('Month10', GrossCharges10, 177), + ('Month11', GrossCharges11, 177), + ('Month12', GrossCharges12, 177), + ('Month01', NetReimbursement01, 179), + ('Month02', NetReimbursement02, 179), + ('Month03', NetReimbursement03, 179), + ('Month04', NetReimbursement04, 179), + ('Month05', NetReimbursement05, 179), + ('Month06', NetReimbursement06, 179), + ('Month07', NetReimbursement07, 179), + ('Month08', NetReimbursement08, 179), + ('Month09', NetReimbursement09, 179), + ('Month10', NetReimbursement10, 179), + ('Month11', NetReimbursement11, 179), + ('Month12', NetReimbursement12, 179), + ('Month01', ContractualAllowance01, 178), + ('Month02', ContractualAllowance02, 178), + ('Month03', ContractualAllowance03, 178), + ('Month04', ContractualAllowance04, 178), + ('Month05', ContractualAllowance05, 178), + ('Month06', ContractualAllowance06, 178), + ('Month07', ContractualAllowance07, 178), + ('Month08', ContractualAllowance08, 178), + ('Month09', ContractualAllowance09, 178), + ('Month10', ContractualAllowance10, 178), + ('Month11', ContractualAllowance11, 178), + ('Month12', ContractualAllowance12, 178)) X (FiscalMonth, Value, UnitTypeID) +) cv +INNER JOIN fw.DimFiscalMonth m ON m.MonthColumnName = cv.FiscalMonth +GROUP BY cv.BudgetConfigID, + cv.EntityGroupConfigID, + cv.EntityID, + cv.PatientClassID, + cv.ServiceLineID, + cv.ServiceLineRollupID, + cv.MedicalSurgicalID, + cv.PayorID, + cv.PayorGroupID, + cv.MSDRGID, + cv.PrimaryCPTID, + cv.TimeClassID, + cv.FiscalYearID, + m.FiscalMonthID, + cv.UnitTypeID + +;WITH TGT AS +( + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, + MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, TimeClassID, FiscalYearID, FiscalMonthID, UnitTypeID, Value + FROM fp.FactReportReimbursement fr + WHERE fr.BudgetConfigID = @BudgetConfigID +) + MERGE TGT as target + USING #SRC AS source + ON ( + target.BudgetConfigID = source.BudgetConfigID + AND target.EntityGroupConfigID = source.EntityGroupConfigID + AND target.EntityID = source.EntityID + AND target.PatientClassID = source.PatientClassID + AND target.ServiceLineID = source.ServiceLineID + AND target.ServiceLineRollupID = source.ServiceLineRollupID + AND target.MedicalSurgicalID = source.MedicalSurgicalID + AND target.PayorID = source.PayorID + AND target.PayorGroupID = source.PayorGroupID + AND target.MSDRGID = source.MSDRGID + AND target.PrimaryCPTID = source.PrimaryCPTID + AND target.TimeClassID = source.TimeClassID + AND target.FiscalYearID = source.FiscalYearID + AND target.FiscalMonthID = source.FiscalMonthID + AND target.UnitTypeID = source.UnitTypeID + ) + WHEN MATCHED AND (target.Value <> source.Value) + THEN + UPDATE + SET target.Value = ISNULL(source.Value, 0) + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + BudgetConfigID, + EntityGroupConfigID, + EntityID, + PatientClassID, + ServiceLineID, + ServiceLineRollupID, + MedicalSurgicalID, + PayorID, + PayorGroupID, + MSDRGID, + PrimaryCPTID, + TimeClassID, + FiscalYearID, + FiscalMonthID, + UnitTypeID, + Value + ) + VALUES ( + source.BudgetConfigID, + source.EntityGroupConfigID, + source.EntityID, + source.PatientClassID, + source.ServiceLineID, + source.ServiceLineRollupID, + source.MedicalSurgicalID, + source.PayorID, + source.PayorGroupID, + source.MSDRGID, + source.PrimaryCPTID, + source.TimeClassID, + source.FiscalYearID, + source.FiscalMonthID, + source.UnitTypeID, + ISNULL(source.Value, 0) + ); + +END; +GO + + +--------------------------------------------- + +-- fp.procReportFactStatisticsISBackup +CREATE PROCEDURE [fp].[procReportFactStatisticsISBackup] ( + @BudgetConfigID INT, + @AnnualizationFactor DECIMAL(19,8), + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +) +AS +BEGIN + + /************************************************************** +** Change History +** CID Date Author WI Description +** 1 2022-10-10 MD JAZZ-1162 Update IS proc to populate annual days in period for all time classes +** 2 2022-11-18 BK JAZZ-46281 Use temp table and filter +** 3 2022-11-29 MD JAZZ-6207 Update IS proc to populate primary stat drivers for revenue only stats +** 4 2022-11-30 NT JAZZ-30106 Fix Working Hours calculation as they are getting rolled up across Job Codes +** 5 2023-06-26 MD JAZZ-54581 Update current year actual FTEs to calculate with only loaded working hours +** 6 2024-01-08 MY JAZZ-63564 Final Pass Of Fact References (SQL) +** 7 2024-10-15 MY JAZZ-78155 Recommendation to add index on temp tables within fp.ProcReportFactStatisticsISBackup +** 8 2024-12-05 MY JAZZ-80822 Add Option Recompile +*************************************************************/ + + SET NOCOUNT ON; + + EXEC [dbo].[procSysDropTempTable] '#SRC' + EXEC [dbo].[procSysDropTempTable] '#SourceDimensionality' + EXEC [dbo].[procSysDropTempTable] '#FactStatisticsDriversAccountsStaffing' + EXEC [dbo].[procSysDropTempTable] '#FactStatisticsDriversAccountsNonStaffing' + EXEC [dbo].[procSysDropTempTable] '#FactStatisticsDriversAccountsRevenueOnly' + EXEC [dbo].[procSysDropTempTable] '#StagingCandidates' + EXEC [dbo].[procSysDropTempTable] '#StagingCandidatesPlusDrivers' + EXEC [dbo].[procSysDropTempTable] '#StagingCandidatesPlusDriversPlusUOS' + EXEC [dbo].[procSysDropTempTable] '#StagingCandidatesPlusDriversPlusUOSPlusWorkingDays' + EXEC [dbo].[procSysDropTempTable] '#SRC' + EXEC [dbo].[procSysDropTempTable] '#rolledUpHours' + EXEC [dbo].[procSysDropTempTable] '#Dimensionality' + EXEC [dbo].[procSysDropTempTable] '#DaysInYear' + EXEC [dbo].[procSysDropTempTable] '#Yr' + EXEC [dbo].[procSysDropTempTable] '#DimensionalityForActuals' + + DECLARE @fiscalYearEndMonth INT + SELECT @fiscalYearEndMonth = Setting FROM DBSetting WHERE Name = 'GENERAL_FISCALYEARENDMONTH' + + -- Cleanup non-active configs + DELETE fs + FROM [fp].[FactISReportStatistics] fs + INNER JOIN [fp].[BudgetConfig] bc ON fs.BudgetConfigID = bc.BudgetConfigID + WHERE bc.IsActive != 1 + + -- Build the department filter + SELECT DISTINCT DepartmentID + INTO #SourceDimensionality + FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + -- if this ends up being slow, well, then we'll have to duplicate a bunch of statements + IF NOT EXISTS(SELECT 1 FROM #SourceDimensionality WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #SourceDimensionality (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fw].[DimDepartment] d WITH (READUNCOMMITTED) + END + + SELECT DISTINCT a.AccountID, + a.PatientClass, c.DepartmentID + INTO #FactStatisticsDriversAccountsStaffing + FROM [fp].[PrimaryStatisticsConfig] c WITH (READUNCOMMITTED) + INNER JOIN #SourceDimensionality src ON c.DepartmentID = src.DepartmentID + INNER JOIN [fw].[DimAccount] a WITH (READUNCOMMITTED) ON a.AccountID = c.AccountID + INNER JOIN [fp].[EntityGroupConfig] egc WITH (READUNCOMMITTED) ON c.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + INNER JOIN [fp].[BudgetConfig] bc WITH (READUNCOMMITTED) ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsStaffing = 1 + AND bc.BudgetConfigID = @BudgetConfigID + + SELECT DISTINCT a.AccountID, + a.PatientClass, c.DepartmentID + INTO #FactStatisticsDriversAccountsNonStaffing + FROM [fp].[PrimaryStatisticsConfig] c WITH (READUNCOMMITTED) + INNER JOIN #SourceDimensionality src ON c.DepartmentID = src.DepartmentID + INNER JOIN [fw].[DimAccount] a WITH (READUNCOMMITTED) ON a.AccountID = c.AccountID + INNER JOIN [fp].[EntityGroupConfig] egc WITH (READUNCOMMITTED) ON c.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + INNER JOIN [fp].[BudgetConfig] bc WITH (READUNCOMMITTED) ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsNonStaffing = 1 + AND bc.BudgetConfigID = @BudgetConfigID + + SELECT DISTINCT a.AccountID, + a.PatientClass, c.DepartmentID + INTO #FactStatisticsDriversAccountsRevenueOnly + FROM [fp].[PrimaryStatisticsConfig] c WITH (READUNCOMMITTED) + INNER JOIN #SourceDimensionality src ON c.DepartmentID = src.DepartmentID + INNER JOIN [fw].[DimAccount] a WITH (READUNCOMMITTED) ON a.AccountID = c.AccountID + INNER JOIN [fp].[EntityGroupConfig] egc WITH (READUNCOMMITTED) ON c.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + INNER JOIN [fp].[BudgetConfig] bc WITH (READUNCOMMITTED) ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsRevenue = 1 AND IsStaffing = 0 AND IsNonStaffing = 0 + AND bc.BudgetConfigID = @BudgetConfigID + + CREATE TABLE #StagingCandidates (BudgetConfigID INT, DepartmentID INT, JobCodeID INT DEFAULT(0), AccountID INT, FinancialReportingID INT, FiscalYearID INT, + FiscalMonthID INT, TimeClassID INT, Amount DECIMAL(38, 4), YTD DECIMAL(38, 4), Yearly DECIMAL(38, 4), Total DECIMAL(38, 4)) + + CREATE TABLE #StagingCandidatesPlusDrivers (BudgetConfigID INT, DepartmentID INT, JobCodeID INT DEFAULT(0), AccountID INT, FinancialReportingID INT, FiscalYearID INT, + FiscalMonthID INT, TimeClassID INT, Amount DECIMAL(38, 4), YTD DECIMAL(38, 4), Yearly DECIMAL(38, 4), Total DECIMAL(38, 4)) + + CREATE TABLE #StagingCandidatesPlusDriversPlusUOS (BudgetConfigID INT, DepartmentID INT, JobCodeID INT DEFAULT(0), AccountID INT, FinancialReportingID INT, FiscalYearID INT, + FiscalMonthID INT, TimeClassID INT, Amount DECIMAL(38, 4), YTD DECIMAL(38, 4), Yearly DECIMAL(38, 4), Total DECIMAL(38, 4), + INDEX BASE CLUSTERED ([FinancialReportingID],[FiscalMonthID]) /* JAZZ-78155: Recommendation from CS */ + ) + + CREATE TABLE #StagingCandidatesPlusDriversPlusUOSPlusWorkingDays (BudgetConfigID INT, DepartmentID INT, AccountID INT, FinancialReportingID INT, FiscalYearID INT, + FiscalMonthID INT, TimeClassID INT, Amount DECIMAL(38, 4), YTD DECIMAL(38, 4), Yearly DECIMAL(38, 4), Total DECIMAL(38, 4)) + + CREATE TABLE #SRC (BudgetConfigID INT, DepartmentID INT, AccountID INT, FinancialReportingID INT, FiscalYearID INT, + FiscalMonthID INT, TimeClassID INT, Amount DECIMAL(38, 4), YTD DECIMAL(38, 4), Yearly DECIMAL(38, 4), Total DECIMAL(38, 4), + INDEX BASE CLUSTERED ([BudgetConfigID],[DepartmentID],[AccountID],[FinancialReportingID],[FiscalYearID],[FiscalMonthID],[TimeClassID]) /* JAZZ-78155: Recommendation from CS */ + ) + + CREATE TABLE #Dimensionality (DepartmentID INT, JobCodeID INT) + + CREATE TABLE #DimensionalityForActuals (FiscalYearID INT, FiscalMonthID INT, TimeClassID INT, DepartmentID INT, JobCodeID INT) --JAZZ-54581 + + CREATE TABLE #DaysInYear (FiscalYearID SMALLINT, TimeClassID TINYINT, DaysInYear INT) + + CREATE TABLE #rolledUpHours (BudgetConfigID INT, DepartmentID INT, JobCodeID INT, AccountID INT, FinancialReportingID INT, FiscalYearID INT, + FiscalMonthID INT, TimeClassID INT, Amount DECIMAL(38, 4), YTD DECIMAL(38, 4), Yearly DECIMAL(38, 4), Total DECIMAL(38, 4)) + + DECLARE @FiscalYearID SMALLINT; + SET @FiscalYearID = (SELECT TOP 1 FiscalYearID FROM [fp].[BudgetConfig] WHERE BudgetConfigID = @BudgetConfigID) + CREATE TABLE #Yr (FiscalYearID SMALLINT) + + INSERT INTO #Yr SELECT @FiscalYearID -- budget year + INSERT INTO #Yr SELECT @FiscalYearID - 1 -- projection (current year) + INSERT INTO #Yr SELECT @FiscalYearID - 2 -- prior year + + INSERT INTO #Dimensionality (DepartmentID, JobCodeID) + SELECT DISTINCT data.DepartmentID, JobCodeID + FROM [fp].[Staffing] data + INNER JOIN #SourceDimensionality src ON data.DepartmentID = src.DepartmentID + WHERE BudgetConfigID = @BudgetConfigID + AND VariabilityID = 1 -- Simply limiting rows here, this has no significance other than that. + + INSERT INTO #DaysInYear (FiscalYearID, TimeClassID, DaysInYear) + SELECT + fy.FiscalYearID, + tc.TimeClassID, + DaysInYear = + SUM( + CASE WHEN + ( + (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 4 = 0 + AND (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 100 <> 0 + ) + OR + (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 400 = 0 + THEN fm.DaysInLeapYearMonth ELSE fm.DaysInMonth END) + FROM fw.DimFiscalMonth fm + CROSS JOIN #Yr fy + CROSS JOIN (SELECT TimeClassID FROM fw.DimTimeClass WHERE TimeClassID IN (1, 2, 12, 20) ) tc + WHERE fm.FiscalMonthID <> 0 + AND fy.FiscalYearID <> 0 + GROUP BY + fy.FiscalYearID, + tc.TimeClassID + + --JAZZ-54581 + INSERT INTO #DaysInYear (FiscalYearID, TimeClassID, DaysInYear) + SELECT + FiscalYearID, + 19 AS TimeClassID, + DaysInYear + FROM #DaysInYear + WHERE + FiscalYearID = @FiscalYearID - 1 + AND TimeClassID = 1 + + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + ----------------------------------------------------------------------------- Statistics ------------------------------------------------------------------------------------ + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + -- Statistics, Projection + INSERT INTO #StagingCandidates (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT data.BudgetConfigID, + data.DepartmentID, + data.AccountID, + FinancialReportingID = CASE WHEN a.PatientClass = 'Inpatient' THEN 497 + WHEN a.PatientClass = 'Outpatient' THEN 498 + WHEN a.PatientClass = 'Other' THEN 499 + WHEN a.PatientClass = 'Observation' THEN 1000 + WHEN a.PatientClass = 'ED' THEN 1001 + WHEN a.PatientClass = 'Clinic' THEN 1002 + END, + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID, + SUM(data.ManagerValue) AS Amount, + SUM(CASE WHEN fm.SortOrder <= bc.MonthsLoaded THEN data.ManagerValue ELSE 0 END) AS YTD, + SUM(data.ManagerValue) AS Yearly, + SUM(data.ManagerValue) AS Total + FROM fp.viewFactStatistics_UnPivoted data WITH (READUNCOMMITTED) + INNER JOIN #SourceDimensionality src ON data.DepartmentID = src.DepartmentID + INNER JOIN fp.BudgetConfig bc WITH (READUNCOMMITTED) ON bc.BudgetConfigID = data.BudgetConfigID + INNER JOIN [fw].[DimFiscalMonth] fm WITH (READUNCOMMITTED) ON fm.FiscalMonthID = data.FiscalMonthID + INNER JOIN fw.DimAccount a ON a.AccountID = data.AccountID + WHERE data.TimeClassID = 12 + AND data.BudgetConfigID = @BudgetConfigID + AND a.PatientClass IN ( + 'Inpatient', --UOS Inpatient + 'Outpatient', --UOS Outpatient + 'Other', --UOS Other + 'Observation', --UOS Observation + 'ED', --UOS ED + 'Clinic' --UOS Clinic + ) + GROUP BY data.BudgetConfigID, data.DepartmentID, data.AccountID, FinancialReportingID, data.FiscalYearID, data.FiscalMonthID, data.TimeClassID, a.PatientClass + + -- Statistics, Target/Budget + INSERT INTO #StagingCandidates (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT data.BudgetConfigID, + data.DepartmentID, + data.AccountID, + FinancialReportingID = CASE WHEN a.PatientClass = 'Inpatient' THEN 497 + WHEN a.PatientClass = 'Outpatient' THEN 498 + WHEN a.PatientClass = 'Other' THEN 499 + WHEN a.PatientClass = 'Observation' THEN 1000 + WHEN a.PatientClass = 'ED' THEN 1001 + WHEN a.PatientClass = 'Clinic' THEN 1002 + END, + data.FiscalYearID, + data.FiscalMonthID, + tc.TimeClassID, + SUM(CASE WHEN tc.TimeClassID = 2 THEN data.ManagerValue ELSE data.Value END) AS Amount, + SUM(CASE WHEN fm.SortOrder <= bc.MonthsLoaded + AND tc.TimeClassID = 2 THEN data.ManagerValue WHEN fm.SortOrder <= bc.MonthsLoaded + AND tc.TimeClassID = 20 THEN data.Value ELSE 0 END) AS YTD, + SUM(CASE WHEN tc.TimeClassID = 2 THEN data.ManagerValue ELSE data.Value END) AS Yearly, + SUM(CASE WHEN tc.TimeClassID = 2 THEN data.ManagerValue ELSE data.Value END) AS Total + FROM fp.viewFactStatistics_UnPivoted data WITH (READUNCOMMITTED) + INNER JOIN #SourceDimensionality src ON data.DepartmentID = src.DepartmentID + INNER JOIN fp.BudgetConfig bc WITH (READUNCOMMITTED) ON bc.BudgetConfigID = data.BudgetConfigID + INNER JOIN [fw].[DimFiscalMonth] fm WITH (READUNCOMMITTED) ON fm.FiscalMonthID = data.FiscalMonthID + INNER JOIN fw.DimAccount a WITH (READUNCOMMITTED) ON a.AccountID = data.AccountID + CROSS JOIN fw.DimTimeClass tc WITH (READUNCOMMITTED) + WHERE data.TimeClassID = 2 + AND data.BudgetConfigID = @BudgetConfigID + AND tc.TimeClassID IN (2, 20) + AND a.PatientClass IN ( + 'Inpatient', --UOS Inpatient + 'Outpatient', --UOS Outpatient + 'Other', --UOS Other + 'Observation', --UOS Observation + 'ED', --UOS ED + 'Clinic' --UOS Clinic + ) + GROUP BY data.BudgetConfigID, data.DepartmentID, data.AccountID, FinancialReportingID, data.FiscalYearID, data.FiscalMonthID, tc.TimeClassID, a.PatientClass + + -- Statistics, Actual + INSERT INTO #StagingCandidates (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT data.BudgetConfigID, + data.DepartmentID, + data.AccountID, + FinancialReportingID = CASE WHEN a.PatientClass = 'Inpatient' THEN 497 + WHEN a.PatientClass = 'Outpatient' THEN 498 + WHEN a.PatientClass = 'Other' THEN 499 + WHEN a.PatientClass = 'Observation' THEN 1000 + WHEN a.PatientClass = 'ED' THEN 1001 + WHEN a.PatientClass = 'Clinic' THEN 1002 + END, + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID, + SUM(data.Value) AS Amount, + SUM(CASE WHEN fm.SortOrder <= bc.MonthsLoaded THEN data.Value ELSE 0 END) AS YTD, + SUM(data.Value) AS Yearly, + SUM(data.Value) AS Total + FROM [fp].[viewFactStatisticsHistory_Unpivoted] data WITH (READUNCOMMITTED) + INNER JOIN #SourceDimensionality src ON data.DepartmentID = src.DepartmentID + INNER JOIN fp.BudgetConfig bc WITH (READUNCOMMITTED) ON bc.BudgetConfigID = data.BudgetConfigID + INNER JOIN [fw].[DimFiscalMonth] fm WITH (READUNCOMMITTED) ON fm.FiscalMonthID = data.FiscalMonthID + INNER JOIN fw.DimAccount a WITH (READUNCOMMITTED) ON a.AccountID = data.AccountID + WHERE 1=1 + AND data.BudgetConfigID = @BudgetConfigID + AND a.PatientClass IN ( + 'Inpatient',--UOS Inpatient + 'Outpatient',--UOS Outpatient + 'Other',--UOS Other + 'Observation',--UOS Observation + 'ED',--UOS ED + 'Clinic'--UOS Clinic + ) + GROUP BY data.BudgetConfigID, data.DepartmentID, data.AccountID, FinancialReportingID, data.FiscalYearID, data.FiscalMonthID, data.TimeClassID, a.PatientClass + +-- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +-- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +-- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +-- ------------------------------------------------------------------------------ Staffing ------------------------------------------------------------------------------------- +-- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +-- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +-- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + -- Staffing Hours,Non-Productive Hours,Contract Labor Hours - Projection + INSERT INTO #StagingCandidates (BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT data.BudgetConfigID, + data.DepartmentID, + data.JobCodeID, + 0 AS AccountID, + X.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID, + SUM(data.ManagerValue) AS Amount, + SUM(CASE WHEN fm.SortOrder <= bc.MonthsLoaded THEN data.ManagerValue ELSE 0 END) AS YTD, + SUM(data.ManagerValue) AS Yearly, + SUM(data.ManagerValue) AS Total + FROM fp.viewFactStaffing_UnPivoted data WITH (READUNCOMMITTED) + INNER JOIN #SourceDimensionality src ON data.DepartmentID = src.DepartmentID + INNER JOIN fp.BudgetConfig bc WITH (READUNCOMMITTED) ON bc.BudgetConfigID = data.BudgetConfigID + INNER JOIN [fw].[DimFiscalMonth] fm WITH (READUNCOMMITTED) ON fm.FiscalMonthID = data.FiscalMonthID + INNER JOIN fw.DimPayCodeGroup pcg WITH (READUNCOMMITTED) ON pcg.PayCodeGroupID = data.PayCodeGroupID + INNER JOIN fw.DimProductiveClass pc WITH (READUNCOMMITTED) ON pc.ProductiveClassID = pcg.ProductiveClassID + INNER JOIN fw.DimJobCode jc WITH (READUNCOMMITTED) ON jc.JobCodeID = data.JobCodeID + INNER JOIN fw.DimJobCodeGroup jcg WITH (READUNCOMMITTED) ON jcg.JobCodeGroupID = jc.JobCodeGroupID + CROSS APPLY ( + SELECT FinancialReportingID = 590 WHERE pc.NAME = 'Non-Productive' + UNION ALL + SELECT FinancialReportingID = 589 WHERE pc.NAME = 'Productive' + UNION ALL + SELECT FinancialReportingID = 1011 WHERE jcg.NAME = 'Contract Labor' + ) X + WHERE 1=1 + AND data.BudgetConfigID = @BudgetConfigID + AND ( + pc.NAME IN ('Non-Productive', 'Productive') + OR jcg.NAME = 'Contract Labor' + ) + AND data.UnitTypeID = 51 + AND data.TimeClassID = 12 + GROUP BY data.BudgetConfigID, + data.DepartmentID, + data.JobCodeID, + X.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID + + -- Staffing Hours,Non-Productive Hours,Contract Labor Hours, Target/Budget + INSERT INTO #StagingCandidates (BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT data.BudgetConfigID, + data.DepartmentID, + data.JobCodeID, + 0 AS AccountID, + X.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + tc.TimeClassID, + SUM(CASE WHEN tc.TimeClassID = 2 THEN data.ManagerValue ELSE data.Value END) AS Amount, + SUM(CASE WHEN fm.SortOrder <= bc.MonthsLoaded + AND tc.TimeClassID = 2 THEN data.ManagerValue WHEN fm.SortOrder <= bc.MonthsLoaded + AND tc.TimeClassID = 20 THEN data.Value ELSE 0 END) AS YTD, + SUM(CASE WHEN tc.TimeClassID = 2 THEN data.ManagerValue ELSE data.Value END) AS Yearly, + SUM(CASE WHEN tc.TimeClassID = 2 THEN data.ManagerValue ELSE data.Value END) AS Total + FROM fp.viewFactStaffing_UnPivoted data WITH (READUNCOMMITTED) + INNER JOIN #SourceDimensionality src ON data.DepartmentID = src.DepartmentID + INNER JOIN fp.BudgetConfig bc WITH (READUNCOMMITTED) ON bc.BudgetConfigID = data.BudgetConfigID + INNER JOIN [fw].[DimFiscalMonth] fm WITH (READUNCOMMITTED) ON fm.FiscalMonthID = data.FiscalMonthID + INNER JOIN fw.DimPayCodeGroup pcg WITH (READUNCOMMITTED) ON pcg.PayCodeGroupID = data.PayCodeGroupID + INNER JOIN fw.DimProductiveClass pc WITH (READUNCOMMITTED) ON pc.ProductiveClassID = pcg.ProductiveClassID + INNER JOIN fw.DimJobCode jc WITH (READUNCOMMITTED) ON jc.JobCodeID = data.JobCodeID + INNER JOIN fw.DimJobCodeGroup jcg WITH (READUNCOMMITTED) ON jcg.JobCodeGroupID = jc.JobCodeGroupID + CROSS JOIN fw.DimTimeClass tc WITH (READUNCOMMITTED) + CROSS APPLY ( + SELECT FinancialReportingID = 590 WHERE pc.NAME = 'Non-Productive' + UNION ALL + SELECT FinancialReportingID = 589 WHERE pc.NAME = 'Productive' + UNION ALL + SELECT FinancialReportingID = 1011 WHERE jcg.NAME = 'Contract Labor' + ) X + WHERE 1=1 + AND data.BudgetConfigID = @BudgetConfigID + AND ( + pc.NAME IN ('Non-Productive', 'Productive') + OR jcg.NAME = 'Contract Labor' + ) + AND data.UnitTypeID = 51 + AND data.TimeClassID = 2 + AND tc.TimeClassID IN (2, 20) + GROUP BY data.BudgetConfigID, + data.DepartmentID, + data.JobCodeID, + X.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + tc.TimeClassID + + -- Staffing Hours,Non-Productive Hours,Contract Labor Hours, Actual + INSERT INTO #StagingCandidates (BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT data.BudgetConfigID, + data.DepartmentID, + data.JobCodeID, + 0 AS AccountID, + X.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID, + SUM(data.Value) AS Amount, + SUM(CASE WHEN fm.SortOrder <= bc.MonthsLoaded THEN data.Value ELSE 0 END) AS YTD, + SUM(data.Value) AS Yearly, + SUM(data.Value) AS Total + FROM [fp].[viewFactStaffingHistory_Unpivoted] data WITH (READUNCOMMITTED) + INNER JOIN #SourceDimensionality src ON data.DepartmentID = src.DepartmentID + INNER JOIN fp.BudgetConfig bc WITH (READUNCOMMITTED) ON bc.BudgetConfigID = data.BudgetConfigID + INNER JOIN [fw].[DimFiscalMonth] fm WITH (READUNCOMMITTED) ON fm.FiscalMonthID = data.FiscalMonthID + INNER JOIN fw.DimPayCodeGroup pcg WITH (READUNCOMMITTED) ON pcg.PayCodeGroupID = data.PayCodeGroupID + INNER JOIN fw.DimProductiveClass pc WITH (READUNCOMMITTED) ON pc.ProductiveClassID = pcg.ProductiveClassID + INNER JOIN fw.DimJobCode jc WITH (READUNCOMMITTED) ON jc.JobCodeID = data.JobCodeID + INNER JOIN fw.DimJobCodeGroup jcg WITH (READUNCOMMITTED) ON jcg.JobCodeGroupID = jc.JobCodeGroupID + CROSS APPLY ( + SELECT FinancialReportingID = 590 WHERE pc.NAME = 'Non-Productive' + UNION ALL + SELECT FinancialReportingID = 589 WHERE pc.NAME = 'Productive' + UNION ALL + SELECT FinancialReportingID = 1011 WHERE jcg.NAME = 'Contract Labor' + ) X + WHERE 1=1 + AND data.BudgetConfigID = @BudgetConfigID + AND ( + pc.NAME IN ('Non-Productive', 'Productive') + OR jcg.NAME = 'Contract Labor' + ) + AND data.UnitTypeID = 51 + GROUP BY data.BudgetConfigID, + data.DepartmentID, + data.JobCodeID, + X.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID + + + UNION ALL + --JAZZ-54581 - added current year actual data again, but with TimeClassID=19 (Annualized) + SELECT data.BudgetConfigID, + data.DepartmentID, + data.JobCodeID, + 0 AS AccountID, + X.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID, + 19 AS TimeClassID, + SUM(data.Value) AS Amount, + SUM(CASE WHEN fm.SortOrder <= bc.MonthsLoaded THEN data.Value ELSE 0 END) AS YTD, + SUM(data.Value) AS Yearly, + SUM(data.Value) AS Total + FROM [fp].[viewFactStaffingHistory_Unpivoted] data WITH (READUNCOMMITTED) + INNER JOIN #SourceDimensionality src ON data.DepartmentID = src.DepartmentID + INNER JOIN fp.BudgetConfig bc WITH (READUNCOMMITTED) ON bc.BudgetConfigID = data.BudgetConfigID + INNER JOIN [fw].[DimFiscalMonth] fm WITH (READUNCOMMITTED) ON fm.FiscalMonthID = data.FiscalMonthID + INNER JOIN fw.DimPayCodeGroup pcg WITH (READUNCOMMITTED) ON pcg.PayCodeGroupID = data.PayCodeGroupID + INNER JOIN fw.DimProductiveClass pc WITH (READUNCOMMITTED) ON pc.ProductiveClassID = pcg.ProductiveClassID + INNER JOIN fw.DimJobCode jc WITH (READUNCOMMITTED) ON jc.JobCodeID = data.JobCodeID + INNER JOIN fw.DimJobCodeGroup jcg WITH (READUNCOMMITTED) ON jcg.JobCodeGroupID = jc.JobCodeGroupID + CROSS APPLY ( + SELECT FinancialReportingID = 590 WHERE pc.NAME = 'Non-Productive' + UNION ALL + SELECT FinancialReportingID = 589 WHERE pc.NAME = 'Productive' + UNION ALL + SELECT FinancialReportingID = 1011 WHERE jcg.NAME = 'Contract Labor' + ) X + WHERE 1=1 + AND data.BudgetConfigID = @BudgetConfigID + AND ( + pc.NAME IN ('Non-Productive', 'Productive') + OR jcg.NAME = 'Contract Labor' + ) + AND data.UnitTypeID = 51 + AND data.TimeClassID = 1 + AND data.FiscalYearID = @FiscalYearID - 1 + GROUP BY data.BudgetConfigID, + data.DepartmentID, + data.JobCodeID, + X.FinancialReportingID, + data.FiscalYearID, + data.FiscalMonthID + + --JAZZ-54581 + INSERT INTO #DimensionalityForActuals (FiscalYearID, FiscalMonthID, TimeClassID, DepartmentID, JobCodeID) + SELECT DISTINCT sc.FiscalYearID, sc.FiscalMonthID, sc.TimeClassID, sc.DepartmentID, sc.JobCodeID + FROM #StagingCandidates sc + WHERE sc.TimeClassID = 1 + AND sc.FiscalYearID = @FiscalYearID - 1 + + -- Working Hours - Monthly + -- We will be storing JobCodeID in Account as Working Hours are otherwise getting summarized across JobCodes and skewing FTE numbers on the IS report (JAZZ-30106) + INSERT INTO #StagingCandidates (BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT + bc.BudgetConfigID, + d.DepartmentID, + jc.JobCodeID, + jc.JobCodeID as AccountID, --storing JobCodeID in Account as we do not have JobCodeID in fp.FactISReportStatistics and we need this detail for WorkingHours + 1015 as FinancialReportingID, --Stats - Other - Working Hours + WH.FiscalYearID, + WH.FiscalMonthID, + tc.TimeClassID, + WH.Hours as Amount, + WH.YTDHours as AmountYTD, + WH.Hours as Yearly, + WH.Hours as Total + FROM + #Dimensionality data -- Using the staffing data to get the unique departments/job codes currently in use + INNER JOIN [fw].[DimDepartment] d with (READUNCOMMITTED) ON data.DepartmentID = d.DepartmentID + INNER JOIN [fw].[DimJobCode] jc with (READUNCOMMITTED) ON data.JobCodeID = jc.JobCodeID + INNER JOIN #SourceDimensionality src ON d.DepartmentID = src.DepartmentID + INNER JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] WH WITH (READUNCOMMITTED) ON WH.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END) + INNER JOIN fp.BudgetConfig bc with (readuncommitted) ON bc.FiscalYearID = WH.FiscalYearID or bc.FiscalYearID - 1 = WH.FiscalYearID or bc.FiscalYearID - 2 = WH.FiscalYearID + CROSS JOIN [fw].[DimTimeClass] tc with (readuncommitted) + WHERE + tc.TimeClassID in(1, 2, 12, 19, 20) --JAZZ-54581 - added TimeClassID 19 + AND bc.BudgetConfigID = @BudgetConfigID + + -- Working Hours - Annual + INSERT INTO #StagingCandidates (BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT + bc.BudgetConfigID, + d.DepartmentID, + jc.JobCodeID, + jc.JobCodeID as AccountID, --storing JobCodeID in Account as we do not have JobCodeID in fp.FactISReportStatistics and we need this detail for WorkingHours + 1015 as FinancialReportingID, --Stats - Other - Working Hours + WH.FiscalYearID, + 0 as FiscalMonthID, + tc.TimeClassID, + SUM(WH.Hours) as Amount, + SUM(WH.Hours) as AmountYTD, + SUM(WH.Hours) as Yearly, + SUM(WH.Hours) as Total + FROM + #Dimensionality data -- Using the staffing data to get the unique departments/job codes currently in use + INNER JOIN [fw].[DimDepartment] d with (READUNCOMMITTED) ON data.DepartmentID = d.DepartmentID + INNER JOIN [fw].[DimJobCode] jc with (READUNCOMMITTED) ON data.JobCodeID = jc.JobCodeID + INNER JOIN #SourceDimensionality src ON d.DepartmentID = src.DepartmentID + INNER JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] WH WITH (READUNCOMMITTED) ON WH.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END) + INNER JOIN fp.BudgetConfig bc with (readuncommitted) ON bc.FiscalYearID = WH.FiscalYearID or bc.FiscalYearID - 1 = WH.FiscalYearID or bc.FiscalYearID - 2 = WH.FiscalYearID + CROSS JOIN [fw].[DimTimeClass] tc with (readuncommitted) + WHERE + tc.TimeClassID in(1, 2, 12, 19, 20) --JAZZ-54581 - added TimeClassID 19 + AND bc.BudgetConfigID = @BudgetConfigID + GROUP BY + bc.BudgetConfigID, + d.DepartmentID, + jc.JobCodeID, + WH.FiscalYearID, + tc.TimeClassID + + +-- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +-- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +-- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +-- ------------------------------------------------------------------------------ Drivers -------------------------------------------------------------------------------------- +-- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +-- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +-- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + INSERT INTO #StagingCandidatesPlusDrivers (BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total + FROM #StagingCandidates + + --Inpatient/Outpatient/Observation/ED/Clinic/Other/Staffing/Non-Staffing Driver + INSERT INTO #StagingCandidatesPlusDrivers (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT BudgetConfigID, + s.DepartmentID, + s.AccountID, + FinancialReportingID = CASE WHEN PatientClass = 'Inpatient' THEN 1003 + WHEN PatientClass = 'Outpatient' THEN 1004 + WHEN PatientClass = 'Other' THEN 1008 + WHEN PatientClass = 'Observation' THEN 1005 + WHEN PatientClass = 'ED' THEN 1006 + WHEN PatientClass = 'Clinic' THEN 1007 + END, + FiscalYearID, + FiscalMonthID, + TimeClassID, + Amount, + YTD, + Yearly, + Total + FROM #StagingCandidates s + INNER JOIN #FactStatisticsDriversAccountsStaffing a ON a.AccountID = s.AccountID AND a.DepartmentID = s.DepartmentID + WHERE FinancialReportingID IN ( + 497, -- Stats - UOS - Inpatient + 498, --Stats - UOS - Outpatient + 499, --Stats - UOS - Other + 1000, --Stats - UOS - Observation + 1001, --Stats - UOS - ED + 1002 --Stats - UOS - Clinic + ) + + + INSERT INTO #StagingCandidatesPlusDrivers (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT BudgetConfigID, + s.DepartmentID, + s.AccountID, + FinancialReportingID = 1009, -- Stats - Primary UOS - Staffing Driver + FiscalYearID, + FiscalMonthID, + TimeClassID, + Amount, + YTD, + Yearly, + Total + FROM #StagingCandidates s + INNER JOIN #FactStatisticsDriversAccountsStaffing a ON a.AccountID = s.AccountID AND a.DepartmentID = s.DepartmentID + WHERE FinancialReportingID IN ( + 497, -- Stats - UOS - Inpatient + 498, --Stats - UOS - Outpatient + 499,--Stats - UOS - Other + 1000,--Stats - UOS - Observation + 1001,--Stats - UOS - ED + 1002--Stats - UOS - Clinic + ) + + INSERT INTO #StagingCandidatesPlusDrivers (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT BudgetConfigID, + s.DepartmentID, + s.AccountID, + FinancialReportingID = 1010, -- Stats - Primary UOS - Non-Staffing Driver + FiscalYearID, + FiscalMonthID, + TimeClassID, + Amount, + YTD, + Yearly, + Total + FROM #StagingCandidates s + INNER JOIN #FactStatisticsDriversAccountsNonStaffing a ON a.AccountID = s.AccountID AND a.DepartmentID = s.DepartmentID + WHERE FinancialReportingID IN ( + 497, -- Stats - UOS - Inpatient + 498, --Stats - UOS - Outpatient + 499,--Stats - UOS - Other + 1000,--Stats - UOS - Observation + 1001,--Stats - UOS - ED + 1002--Stats - UOS - Clinic + ) + + INSERT INTO #StagingCandidatesPlusDrivers (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT BudgetConfigID, + s.DepartmentID, + s.AccountID, + FinancialReportingID = 1008, -- Stats - Primary UOS - Non-Staffing Driver + FiscalYearID, + FiscalMonthID, + TimeClassID, + Amount, + YTD, + Yearly, + Total + FROM #StagingCandidates s + INNER JOIN #FactStatisticsDriversAccountsRevenueOnly a ON a.AccountID = s.AccountID AND a.DepartmentID = s.DepartmentID + WHERE FinancialReportingID IN ( + 497, -- Stats - UOS - Inpatient + 498, --Stats - UOS - Outpatient + 499,--Stats - UOS - Other + 1000,--Stats - UOS - Observation + 1001,--Stats - UOS - ED + 1002--Stats - UOS - Clinic + ) + + + INSERT INTO #StagingCandidatesPlusDriversPlusUOS (BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total + FROM #StagingCandidatesPlusDrivers + + --Hours per UOS Standard + INSERT INTO #StagingCandidatesPlusDriversPlusUOS (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT a.BudgetConfigID, + a.DepartmentID, + a.AccountID, + 1012 AS FinancialReportingID, --Stats - Hours - Hours per UOS Standard + a.FiscalYearID, + a.FiscalMonthID, + a.TimeClassID, + Amount = CASE WHEN ISNULL(b.Amount, 0) = 0 THEN 0 ELSE a.Amount / b.Amount END, + YTD = CASE WHEN ISNULL(b.YTD, 0) = 0 THEN 0 ELSE a.YTD / b.YTD END, + Yearly = CASE WHEN ISNULL(b.Yearly, 0) = 0 THEN 0 ELSE a.Yearly / b.Yearly END, + Total = CASE WHEN ISNULL(b.Total, 0) = 0 THEN 0 ELSE a.Total / b.Total END + FROM #StagingCandidatesPlusDrivers a + INNER JOIN #StagingCandidatesPlusDrivers b ON a.BudgetConfigID = b.BudgetConfigID + AND a.DepartmentID = b.DepartmentID + AND a.FiscalYearID = b.FiscalYearID + AND a.FiscalMonthID = b.FiscalMonthID + AND a.TimeClassID = b.TimeClassID + AND a.FinancialReportingID = 589 --Productive Hours + AND b.FinancialReportingID = 1009 -- Staffing Driver + +-- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +-- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +-- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +-- -------------------------------------------------------------------------------- FTES --------------------------------------------------------------------------------------- +-- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +-- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +-- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- + + -- Roll Up all of the Hours at the job code level so we can correctly calculate the FTE + INSERT INTO #rolledUpHours (BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, + Amount, YTD, Yearly, Total) + SELECT a.BudgetConfigID, + a.DepartmentID, + a.JobCodeID, + a.AccountID, + a.FinancialReportingID, + a.FiscalYearID, + a.FiscalMonthID, + a.TimeClassID, + SUM(a.Amount) AS Amount, + SUM(a.YTD) AS YTD, + SUM(a.Yearly) AS Yearly, + SUM(a.Total) AS Total + FROM #StagingCandidatesPlusDrivers a + WHERE a.FinancialReportingID IN ( + 589, -- Stats - Productive Hours + 590, -- Stats- Non-Productive Hours + 2591, -- Stats - Hours - GL Physician Hours + 2590 -- Stats - GL Hours + ) + OR (a.FiscalYearID <> @FiscalYearID - 1 AND a.TimeClassID <> 1) + GROUP BY a.BudgetConfigID, + a.DepartmentID, + a.JobCodeID, + a.FinancialReportingID, + a.AccountID, + a.FiscalYearID, + a.FiscalMonthID, + a.TimeClassID + + UNION ALL + --JAZZ-54581 - Pull in current year actuals differently, joining on dimensionality to make sure we're calculating FTEs correctly + SELECT a.BudgetConfigID, + a.DepartmentID, + a.JobCodeID, + a.AccountID, + a.FinancialReportingID, + a.FiscalYearID, + a.FiscalMonthID, + a.TimeClassID, + SUM(a.Amount) AS Amount, + SUM(a.YTD) AS YTD, + SUM(a.Yearly) AS Yearly, + SUM(a.Total) AS Total + FROM #StagingCandidatesPlusDrivers a + JOIN #DimensionalityForActuals dim + ON a.DepartmentID = dim.DepartmentID + AND a.JobCodeID = dim.JobCodeID + AND a.FiscalYearID = dim.FiscalYearID + AND a.FiscalMonthID = dim.FiscalMonthID + AND a.TimeClassID = dim.TimeClassID + WHERE a.FinancialReportingID IN ( + 589, -- Stats - Productive Hours + 590, -- Stats- Non-Productive Hours + 2591, -- Stats - Hours - GL Physician Hours + 2590 -- Stats - GL Hours + ) + AND a.FiscalYearID = @FiscalYearID - 1 + AND a.TimeClassID = 1 + GROUP BY a.BudgetConfigID, + a.DepartmentID, + a.JobCodeID, + a.FinancialReportingID, + a.AccountID, + a.FiscalYearID, + a.FiscalMonthID, + a.TimeClassID + + --Productive FTEs + INSERT INTO #StagingCandidatesPlusDriversPlusUOS (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT a.BudgetConfigID, + a.DepartmentID, + a.AccountID, + 591 AS FinancialReportingID, -- Stats - FTEs - Productive FTEs + a.FiscalYearID, + a.FiscalMonthID, + a.TimeClassID, + Amount = SUM(CASE WHEN ISNULL(b.Amount, 0) = 0 THEN 0 ELSE a.Amount / b.Amount END), + YTD = SUM(CASE WHEN ISNULL(b.YTD, 0) = 0 THEN 0 ELSE a.YTD / b.YTD END), + Yearly = SUM(CASE WHEN ISNULL(yearly.Yearly, 0) = 0 THEN 0 ELSE a.Yearly / yearly.Yearly END), + Total = SUM(CASE WHEN ISNULL(yearly.Total, 0) = 0 THEN 0 ELSE a.Total / yearly.Total END) + FROM #rolledUpHours a + INNER JOIN #StagingCandidatesPlusDrivers b ON a.BudgetConfigID = b.BudgetConfigID + AND a.DepartmentID = b.DepartmentID + AND a.JobCodeID = b.JobCodeID + AND a.FiscalYearID = b.FiscalYearID + AND a.FiscalMonthID = b.FiscalMonthID + AND a.TimeClassID = b.TimeClassID + AND a.FinancialReportingID = 589 -- Stats - Productive Hours + AND b.FinancialReportingID = 1015 -- Stats - Other - Working Hours + LEFT JOIN #StagingCandidatesPlusDrivers yearly ON a.BudgetConfigID = yearly.BudgetConfigID + AND a.DepartmentID = yearly.DepartmentID + AND a.JobCodeID = yearly.JobCodeID + AND a.FiscalYearID = yearly.FiscalYearID + AND a.TimeClassID = yearly.TimeClassID + AND a.FinancialReportingID = 589 -- Stats - Productive Hours + AND yearly.FinancialReportingID = 1015 -- Stats - Other - Working Hours + AND yearly.FiscalMonthID = 0 + GROUP BY a.BudgetConfigID, + a.DepartmentID, + a.AccountID, + a.FiscalYearID, + a.FiscalMonthID, + a.TimeClassID +OPTION (RECOMPILE) -- JAZZ-80822 + + + --Non-Productive FTEs + INSERT INTO #StagingCandidatesPlusDriversPlusUOS (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT a.BudgetConfigID, + a.DepartmentID, + a.AccountID, + 592 AS FinancialReportingID, -- Stats - FTEs - Non-Productive FTEs + a.FiscalYearID, + a.FiscalMonthID, + a.TimeClassID, + Amount = SUM(CASE WHEN ISNULL(b.Amount, 0) = 0 THEN 0 ELSE a.Amount / b.Amount END), + YTD = SUM(CASE WHEN ISNULL(b.YTD, 0) = 0 THEN 0 ELSE a.YTD / b.YTD END), + Yearly = SUM(CASE WHEN ISNULL(yearly.Yearly, 0) = 0 THEN 0 ELSE a.Yearly / yearly.Yearly END), + Total = SUM(CASE WHEN ISNULL(yearly.Total, 0) = 0 THEN 0 ELSE a.Total / yearly.Total END) + FROM #rolledUpHours a + INNER JOIN #StagingCandidatesPlusDrivers b ON a.BudgetConfigID = b.BudgetConfigID + AND a.DepartmentID = b.DepartmentID + AND a.JobCodeID = b.JobCodeID + AND a.FiscalYearID = b.FiscalYearID + AND a.FiscalMonthID = b.FiscalMonthID + AND a.TimeClassID = b.TimeClassID + AND a.FinancialReportingID = 590 -- Stats- Non-Productive Hours + AND b.FinancialReportingID = 1015 -- Stats - Other - Working Hours + LEFT JOIN #StagingCandidatesPlusDrivers yearly ON a.BudgetConfigID = yearly.BudgetConfigID + AND a.DepartmentID = yearly.DepartmentID + AND a.JobCodeID = yearly.JobCodeID + AND a.FiscalYearID = yearly.FiscalYearID + AND a.TimeClassID = yearly.TimeClassID + AND a.FinancialReportingID = 590 -- Stats - Non-Productive Hours + AND yearly.FinancialReportingID = 1015 -- Stats - Other - Working Hours + AND yearly.FiscalMonthID = 0 + GROUP BY a.BudgetConfigID, + a.DepartmentID, + a.AccountID, + a.FiscalYearID, + a.FiscalMonthID, + a.TimeClassID +OPTION (RECOMPILE) -- JAZZ-80822 + + + --Physician FTEs + INSERT INTO #StagingCandidatesPlusDriversPlusUOS (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT a.BudgetConfigID, + a.DepartmentID, + a.AccountID, + 1 AS FinancialReportingID, + a.FiscalYearID, + a.FiscalMonthID, + a.TimeClassID, + Amount = SUM(CASE WHEN ISNULL(b.Amount, 0) = 0 THEN 0 ELSE a.Amount / b.Amount END), + YTD = SUM(CASE WHEN ISNULL(b.YTD, 0) = 0 THEN 0 ELSE a.YTD / b.YTD END), + Yearly = SUM(CASE WHEN ISNULL(yearly.Yearly, 0) = 0 THEN 0 ELSE a.Yearly / yearly.Yearly END), + Total = SUM(CASE WHEN ISNULL(yearly.Total, 0) = 0 THEN 0 ELSE a.Total / yearly.Total END) + FROM #rolledUpHours a + INNER JOIN #StagingCandidatesPlusDrivers b ON a.BudgetConfigID = b.BudgetConfigID + AND a.DepartmentID = b.DepartmentID + AND a.JobCodeID = b.JobCodeID + AND a.FiscalYearID = b.FiscalYearID + AND a.FiscalMonthID = b.FiscalMonthID + AND a.TimeClassID = b.TimeClassID + AND a.FinancialReportingID = 2591 -- Stats - Hours - GL Physician Hours + AND b.FinancialReportingID = 1015 -- Stats - Other - Working Hours + LEFT JOIN #StagingCandidatesPlusDrivers yearly ON a.BudgetConfigID = yearly.BudgetConfigID + AND a.DepartmentID = yearly.DepartmentID + AND a.JobCodeID = yearly.JobCodeID + AND a.FiscalYearID = yearly.FiscalYearID + AND a.TimeClassID = yearly.TimeClassID + AND a.FinancialReportingID = 2591 -- Stats - Hours - GL Physciain Hours + AND yearly.FinancialReportingID = 1015 -- Stats - Other - Working Hours + AND yearly.FiscalMonthID = 0 + GROUP BY a.BudgetConfigID, + a.DepartmentID, + a.AccountID, + a.FiscalYearID, + a.FiscalMonthID, + a.TimeClassID +OPTION (RECOMPILE) -- JAZZ-80822 + + + --Non-Physician Provider FTEs + INSERT INTO #StagingCandidatesPlusDriversPlusUOS (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT a.BudgetConfigID, + a.DepartmentID, + a.AccountID, + 2 AS FinancialReportingID, + a.FiscalYearID, + a.FiscalMonthID, + a.TimeClassID, + Amount = SUM(CASE WHEN ISNULL(b.Amount, 0) = 0 THEN 0 ELSE a.Amount / b.Amount END), + YTD = SUM(CASE WHEN ISNULL(b.YTD, 0) = 0 THEN 0 ELSE a.YTD / b.YTD END), + Yearly = SUM(CASE WHEN ISNULL(yearly.Yearly, 0) = 0 THEN 0 ELSE a.Yearly / yearly.Yearly END), + Total = SUM(CASE WHEN ISNULL(yearly.Total, 0) = 0 THEN 0 ELSE a.Total / yearly.Total END) + FROM #rolledUpHours a + INNER JOIN #StagingCandidatesPlusDrivers b ON a.BudgetConfigID = b.BudgetConfigID + AND a.DepartmentID = b.DepartmentID + AND a.JobCodeID = b.JobCodeID + AND a.FiscalYearID = b.FiscalYearID + AND a.FiscalMonthID = b.FiscalMonthID + AND a.TimeClassID = b.TimeClassID + AND a.FinancialReportingID = 2590 -- Stats - GL Hours + AND b.FinancialReportingID = 1015 -- Stats - Other - Working Hours + LEFT JOIN #StagingCandidatesPlusDrivers yearly ON a.BudgetConfigID = yearly.BudgetConfigID + AND a.DepartmentID = yearly.DepartmentID + AND a.JobCodeID = yearly.JobCodeID + AND a.FiscalYearID = yearly.FiscalYearID + AND a.TimeClassID = yearly.TimeClassID + AND a.FinancialReportingID = 2590 -- Stats - GL Hours + AND yearly.FinancialReportingID = 1015 -- Stats - Other - Working Hours + AND yearly.FiscalMonthID = 0 + GROUP BY a.BudgetConfigID, + a.DepartmentID, + a.AccountID, + a.FiscalYearID, + a.FiscalMonthID, + a.TimeClassID +OPTION (RECOMPILE) -- JAZZ-80822 + + INSERT INTO #StagingCandidatesPlusDriversPlusUOSPlusWorkingDays (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total + FROM #StagingCandidatesPlusDriversPlusUOS + + INSERT INTO #StagingCandidatesPlusDriversPlusUOSPlusWorkingDays (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT DISTINCT BudgetConfigID, + fs.DepartmentID, + CASE WHEN FinancialReportingID = 1015 THEN 0 ELSE AccountID END AS AccountID, --JAZZ-30106 we put JobCodeID in AccountID for 1015 but we need to ignore that here + 1014 AS FinancialReportingID, --Stats - Other - Days in Period + FiscalYearID = CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END, + fm.FiscalMonthID, + TimeClassID, + Amount = CASE WHEN ( + (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 4 = 0 + AND (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 100 <> 0 + ) + OR (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 400 = 0 THEN fm.DaysInLeapYearMonth ELSE fm.DaysInMonth END, + YTD = CASE WHEN ( + (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 4 = 0 + AND (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 100 <> 0 + ) + OR (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 400 = 0 THEN fm.DaysInLeapYearMonth ELSE fm.DaysInMonth END, + Yearly = CASE WHEN ( + (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 4 = 0 + AND (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 100 <> 0 + ) + OR (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 400 = 0 THEN fm.DaysInLeapYearMonth ELSE fm.DaysInMonth END, + Total = CASE WHEN ( + (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 4 = 0 + AND (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 100 <> 0 + ) + OR (CASE WHEN fm.FiscalMonthID > @fiscalYearEndMonth THEN fy.FiscalYearID - 1 ELSE fy.FiscalYearID END) % 400 = 0 THEN fm.DaysInLeapYearMonth ELSE fm.DaysInMonth END + FROM fw.DimFiscalMonth fm WITH (READUNCOMMITTED) + CROSS JOIN fw.DimFiscalYear fy WITH (READUNCOMMITTED) + INNER JOIN #StagingCandidatesPlusDriversPlusUOS fs ON fs.FiscalYearID = fy.FiscalYearID --JAZZ-46281 changed this to use the temp table and not fp.FactISReportStatistics + AND fs.FiscalMonthID = fm.FiscalMonthID + INNER JOIN #SourceDimensionality src ON fs.DepartmentID = src.DepartmentID + WHERE fm.FiscalMonthID != 0 + AND fy.FiscalYearID != 0 + AND fs.BudgetConfigID = @BudgetConfigID + + --JAZZ-1162 - INSERT "Days in Period" at annual level + INSERT INTO #StagingCandidatesPlusDriversPlusUOSPlusWorkingDays (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT DISTINCT + fs.BudgetConfigID, + fs.DepartmentID, + 0 as AccountID, + 1014 AS FinancialReportingID, --Stats - Other - Days in Period + diy.FiscalYearID, + 0 as FiscalMonthID, + diy.TimeClassID, + Amount = diy.DaysInYear, + YTD = diy.DaysInYear, + Yearly = diy.DaysInYear, + Total = diy.DaysInYear + FROM #StagingCandidatesPlusDriversPlusUOS fs + INNER JOIN #SourceDimensionality src ON fs.DepartmentID = src.DepartmentID --JAZZ-46281 this should be unnecessary but am leaving here as a safeguard + INNER JOIN #DaysInYear diy + on diy.FiscalYearID = fs.FiscalYearID + AND diy.TimeClassID = fs.TimeClassID + WHERE fs.FiscalYearID <> 0 + GROUP BY + fs.BudgetConfigID, + fs.DepartmentID, + diy.FiscalYearID, + diy.TimeClassID, + diy.DaysInYear + + --JAZZ-54581 - Annualize all data + UPDATE #StagingCandidatesPlusDriversPlusUOSPlusWorkingDays + SET + Amount = Amount * @AnnualizationFactor, + YTD = YTD * @AnnualizationFactor, + Yearly = Yearly * @AnnualizationFactor, + Total = Total * @AnnualizationFactor + WHERE + FiscalYearID = @FiscalYearID - 1 + AND TimeClassID = 19 + + --JAZZ-54581 - delete all TimeClass=19 data for all fiscal years not current year + DELETE FROM #StagingCandidatesPlusDriversPlusUOSPlusWorkingDays + WHERE + FiscalYearID != @FiscalYearID - 1 + AND TimeClassID = 19 + + INSERT INTO #SRC (BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total) + SELECT + cte.BudgetConfigID, + cte.DepartmentID, + cte.AccountID, + cte.FinancialReportingID, + cte.FiscalYearID, + cte.FiscalMonthID, + cte.TimeClassID, + SUM(cte.Amount) as Amount, + SUM(cte.YTD) as YTD, + SUM(cte.Yearly) as Yearly, + SUM(cte.Total) as Total + FROM #StagingCandidatesPlusDriversPlusUOSPlusWorkingDays cte + WHERE cte.BudgetConfigID = @BudgetConfigID + GROUP BY cte.BudgetConfigID, + cte.DepartmentID, + cte.AccountID, + cte.FinancialReportingID, + cte.FiscalYearID, + cte.FiscalMonthID, + cte.TimeClassID + + + IF (@IsDebug = 1) + BEGIN + + SELECT '#SourceDimensionality', DepartmentID FROM #SourceDimensionality + SELECT '#FactStatisticsDriversAccountsStaffing', AccountID, DepartmentID FROM #FactStatisticsDriversAccountsStaffing + SELECT '#FactStatisticsDriversAccountsNonStaffing', AccountID, DepartmentID FROM #FactStatisticsDriversAccountsNonStaffing + SELECT '#FactStatisticsDriversAccountsRevenueOnly', AccountID, DepartmentID FROM #FactStatisticsDriversAccountsRevenueOnly + SELECT '#StagingCandidates', BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total FROM #StagingCandidates + SELECT '#StagingCandidatesPlusDrivers', BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total FROM #StagingCandidatesPlusDrivers + SELECT '#StagingCandidatesPlusDriversPlusUOS', BudgetConfigID, DepartmentID, JobCodeID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total FROM #StagingCandidatesPlusDriversPlusUOS + SELECT '#StagingCandidatesPlusDriversPlusUOSPlusWorkingDays', BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total FROM #StagingCandidatesPlusDriversPlusUOSPlusWorkingDays + SELECT '#SRC', BudgetConfigID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total FROM #SRC + + END ELSE + BEGIN + + WITH TGT AS + ( + SELECT BudgetConfigID, s.DepartmentID, AccountID, FinancialReportingID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, YTD, Yearly, Total + FROM fp.FactISReportStatistics s + INNER JOIN #SourceDimensionality sd ON s.DepartmentID = sd.DepartmentID + WHERE s.BudgetConfigID = @BudgetConfigID + ) + MERGE TGT AS target + USING #SRC AS source + ON source.BudgetConfigID = target.BudgetConfigID + AND source.DepartmentID = target.DepartmentID + AND source.AccountID = target.AccountID + AND source.FinancialReportingID = target.FinancialReportingID + AND source.FiscalYearID = target.FiscalYearID + AND source.FiscalMonthID = target.FiscalMonthID + AND source.TimeClassID = target.TimeClassID + WHEN MATCHED + AND ( + source.Amount <> target.Amount + OR source.YTD <> target.YTD + OR source.Yearly <> target.Yearly + OR source.Total <> target.Total + ) + THEN + UPDATE + SET Amount = source.Amount, + YTD = source.YTD, + Yearly = source.Yearly, + Total = source.Total + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + BudgetConfigID, + DepartmentID, + AccountID, + FinancialReportingID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + Amount, + YTD, + Yearly, + Total + ) + VALUES ( + source.BudgetConfigID, + source.DepartmentID, + source.AccountID, + source.FinancialReportingID, + source.FiscalYearID, + source.FiscalMonthID, + source.TimeClassID, + source.Amount, + source.YTD, + source.Yearly, + source.Total + ) + WHEN NOT MATCHED BY Source + THEN + DELETE; + END + + END +GO + + +--------------------------------------------- + +-- fp.procReprocessEncountersAddProviderTask +/************************************************************** +** CID Date Author WI Description +** 1 2022-11-28 NH,OA JAZZ-38339 Encounters Add Provider: reprocess provider +** 2 2023-05-18 MY JAZZ-55153 Update to new structure +*************************************************************/ +CREATE PROCEDURE [fp].[procReprocessEncountersAddProviderTask] + @ServiceProviderID INT + AS + BEGIN + +--Select AdjustmentGUID +DECLARE @adjGuid UNIQUEIDENTIFIER; + +SELECT DISTINCT @adjGuid = AdjustmentGUID +FROM fp.AddProviderEncountersDataForCharges +WHERE IsProcessed = 0 AND ServiceProviderID = @ServiceProviderID + +-- Insert all dimensionality by adjGuid to identify records in ChargeVolume +SELECT * + INTO #addProvEncDataForChargesToRemove + FROM fp.AddProviderEncountersDataForCharges + WHERE AdjustmentGUID = @adjGuid + +-- Identifying records which we want to remove in FactChargeVolume +SELECT DISTINCT fcv.* INTO #FactChargeVolumesToRemove +FROM fp.ChargeVolume fcv + INNER JOIN #addProvEncDataForChargesToRemove apetr ON fcv.BudgetConfigID = apetr.BudgetConfigID + AND fcv.EntityID = apetr.EntityID + AND fcv.DepartmentID = apetr.DepartmentID + AND fcv.ServiceLineID = apetr.ServiceLineID + AND fcv.PatientClassID = apetr.PatientClassID + AND fcv.AgeCohortID = apetr.AgeCohortID + AND fcv.MedicalSurgicalID = apetr.MedicalSurgicalID + AND fcv.UnitTypeID = apetr.UnitTypeID + AND fcv.ServiceEntityID = apetr.ServiceEntityID + AND fcv.MSDRGID = apetr.MSDRGID + AND fcv.UBRevCodeID = apetr.UBRevCodeID + AND fcv.PrimaryCPTID = apetr.PrimaryCPTID + AND fcv.ServiceProviderID = apetr.ServiceProviderID + AND fcv.ServiceProviderSpecialtyID = apetr.ServiceProviderSpecialtyID + AND fcv.PerformingProviderID = apetr.PerformingProviderID + AND fcv.PerformingProviderSpecialtyID = apetr.PerformingProviderSpecialtyID + AND fcv.BillingCPTID = apetr.BillingCPTID + +BEGIN TRY + BEGIN TRAN + + --Clean up additional table from proc padChargeVolume + DELETE fcvh + FROM [fp].[ChargeVolumeHistory] fcvh + INNER JOIN #FactChargeVolumesToRemove fcvtr ON fcvh.ChargeVolumeID = fcvtr.ChargeVolumeID + + --Clean up ChargeVolume + DELETE fcv + FROM fp.ChargeVolume fcv + INNER JOIN #FactChargeVolumesToRemove fcvtr ON fcv.ChargeVolumeID = fcvtr.ChargeVolumeID + + IF @@TRANCOUNT > 0 COMMIT TRAN +END TRY +BEGIN CATCH + IF @@TRANCOUNT > 0 ROLLBACK TRAN +END CATCH; + + +DROP TABLE IF EXISTS #addProvEncDataForChargesToRemove +DROP TABLE IF EXISTS #FactChargeVolumesToRemove + +--Reprocess +DECLARE @AssemblyQualifiedName varchar(1024); +DECLARE @SLEncounterAdjGUID UNIQUEIDENTIFIER; + +SET @AssemblyQualifiedName = 'Strata.CS.Jazz.ABB.PlanEditor.Provider.EncountersAddProviderTask, Strata.CS.Jazz.ABB'; + +--xmlContent for EncountersAddProviderTask is @SLEncounterAdjGUID +--SHOULD BE in "" +SELECT @SLEncounterAdjGUID = SLEncounterAdjustmentGUID +FROM fp.AddProviderSummary +WHERE DCVolumeAdjustmentGUID = @adjGuid + +DECLARE @xmlContent VARCHAR(50) = '"' + CAST(@SLEncounterAdjGUID AS VARCHAR(50)) + '"'; + +DECLARE @statusCode INT; +EXEC dbo.procCreateTask + @taskTypeName = @AssemblyQualifiedName, + @contextXML = @xmlContent, + @userName = 'HangfireMigration', + @taskSource = 'Migration', + @statusCode = @statusCode OUTPUT; + +END +GO + + +--------------------------------------------- + +-- fp.procResetBenefitsFixedAccountRateAndDrivers +/************************************************************** +** Change History +** CID Date Author WI Description +** 1 2020-05-28 BK D-08014 Created proc to reset all driver and rate data for fixed benefits accounts to 0 +*************************************************************/ +CREATE PROCEDURE [fp].[procResetBenefitsFixedAccountRateAndDrivers] + @EntityGroupConfigGUID UNIQUEIDENTIFIER, + @EntityGroupConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + WITH RECOMPILE + AS + BEGIN + + CREATE TABLE #FixedAccounts (AccountID int) + + + INSERT INTO #FixedAccounts + SELECT AccountID FROM fp.AccountFlexConfig WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID AND FlexMethodClassName = '' + + IF NOT EXISTS (SELECT * FROM #FixedAccounts) + BEGIN + RETURN; + END + + CREATE TABLE #FilterByDepartment (DepartmentID int,BudgetPhaseID int) + INSERT INTO #FilterByDepartment (DepartmentID,BudgetPhaseID) + SELECT DepartmentID,BudgetPhaseID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[FactBenefits] d WITH (READUNCOMMITTED) + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + UPDATE ben + SET SampledBudget01 = 0 + , SampledBudget02 = 0 + , SampledBudget03 = 0 + , SampledBudget04 = 0 + , SampledBudget05 = 0 + , SampledBudget06 = 0 + , SampledBudget07 = 0 + , SampledBudget08 = 0 + , SampledBudget09 = 0 + , SampledBudget10 = 0 + , SampledBudget11 = 0 + , SampledBudget12 = 0 + , SampledProjection01 = 0 + , SampledProjection02 = 0 + , SampledProjection03 = 0 + , SampledProjection04 = 0 + , SampledProjection05 = 0 + , SampledProjection06 = 0 + , SampledProjection07 = 0 + , SampledProjection08 = 0 + , SampledProjection09 = 0 + , SampledProjection10 = 0 + , SampledProjection11 = 0 + , SampledProjection12 = 0 + , InitialBudget01 = 0 + , InitialBudget02 = 0 + , InitialBudget03 = 0 + , InitialBudget04 = 0 + , InitialBudget05 = 0 + , InitialBudget06 = 0 + , InitialBudget07 = 0 + , InitialBudget08 = 0 + , InitialBudget09 = 0 + , InitialBudget10 = 0 + , InitialBudget11 = 0 + , InitialBudget12 = 0 + , InitialProjection01 = 0 + , InitialProjection02 = 0 + , InitialProjection03 = 0 + , InitialProjection04 = 0 + , InitialProjection05 = 0 + , InitialProjection06 = 0 + , InitialProjection07 = 0 + , InitialProjection08 = 0 + , InitialProjection09 = 0 + , InitialProjection10 = 0 + , InitialProjection11 = 0 + , InitialProjection12 = 0 + FROM fp.FactBenefits ben INNER JOIN #FilterByDepartment dept ON ben.DepartmentID = dept.DepartmentID + INNER JOIN #FixedAccounts acct ON ben.AccountID = acct.AccountID + WHERE EntityGroupConfigID = @EntityGroupConfigID AND ben.UnitTypeID IN (144, 169, 170, 171) + + UPDATE budget + SET budget.FlexedValue01 = 0 + , budget.FlexedValue02 = 0 + , budget.FlexedValue03 = 0 + , budget.FlexedValue04 = 0 + , budget.FlexedValue05 = 0 + , budget.FlexedValue06 = 0 + , budget.FlexedValue07 = 0 + , budget.FlexedValue08 = 0 + , budget.FlexedValue09 = 0 + , budget.FlexedValue10 = 0 + , budget.FlexedValue11 = 0 + , budget.FlexedValue12 = 0 + , budget.AdjustedValue01 = 0 + , budget.AdjustedValue02 = 0 + , budget.AdjustedValue03 = 0 + , budget.AdjustedValue04 = 0 + , budget.AdjustedValue05 = 0 + , budget.AdjustedValue06 = 0 + , budget.AdjustedValue07 = 0 + , budget.AdjustedValue08 = 0 + , budget.AdjustedValue09 = 0 + , budget.AdjustedValue10 = 0 + , budget.AdjustedValue11 = 0 + , budget.AdjustedValue12 = 0 + FROM [fp].[FactBenefits] ben + INNER JOIN [fp].[FactBenefitsBudget] budget ON ben.BenefitsID = budget.BenefitsID + INNER JOIN #FilterByDepartment dept ON ben.DepartmentID = dept.DepartmentID + INNER JOIN #FixedAccounts acct ON ben.AccountID = acct.AccountID + WHERE EntityGroupConfigID = @EntityGroupConfigID AND ben.UnitTypeID IN (144, 169, 170, 171) + + UPDATE proj + SET proj.FlexedValue01 = 0 + , proj.FlexedValue02 = 0 + , proj.FlexedValue03 = 0 + , proj.FlexedValue04 = 0 + , proj.FlexedValue05 = 0 + , proj.FlexedValue06 = 0 + , proj.FlexedValue07 = 0 + , proj.FlexedValue08 = 0 + , proj.FlexedValue09 = 0 + , proj.FlexedValue10 = 0 + , proj.FlexedValue11 = 0 + , proj.FlexedValue12 = 0 + , proj.AdjustedValue01 = 0 + , proj.AdjustedValue02 = 0 + , proj.AdjustedValue03 = 0 + , proj.AdjustedValue04 = 0 + , proj.AdjustedValue05 = 0 + , proj.AdjustedValue06 = 0 + , proj.AdjustedValue07 = 0 + , proj.AdjustedValue08 = 0 + , proj.AdjustedValue09 = 0 + , proj.AdjustedValue10 = 0 + , proj.AdjustedValue11 = 0 + , proj.AdjustedValue12 = 0 + FROM [fp].[FactBenefits] ben + INNER JOIN [fp].[FactBenefitsProjection] proj ON ben.BenefitsID = proj.BenefitsID + INNER JOIN #FilterByDepartment dept ON ben.DepartmentID = dept.DepartmentID + INNER JOIN #FixedAccounts acct ON ben.AccountID = acct.AccountID + WHERE EntityGroupConfigID = @EntityGroupConfigID AND ben.UnitTypeID IN (144, 169, 170, 171) + + UPDATE hist + SET hist.PriorYearActualValue01 = 0 + , hist.PriorYearActualValue02 = 0 + , hist.PriorYearActualValue03 = 0 + , hist.PriorYearActualValue04 = 0 + , hist.PriorYearActualValue05 = 0 + , hist.PriorYearActualValue06 = 0 + , hist.PriorYearActualValue07 = 0 + , hist.PriorYearActualValue08 = 0 + , hist.PriorYearActualValue09 = 0 + , hist.PriorYearActualValue10 = 0 + , hist.PriorYearActualValue11 = 0 + , hist.PriorYearActualValue12 = 0 + , hist.ActualYTDValue01 = 0 + , hist.ActualYTDValue02 = 0 + , hist.ActualYTDValue03 = 0 + , hist.ActualYTDValue04 = 0 + , hist.ActualYTDValue05 = 0 + , hist.ActualYTDValue06 = 0 + , hist.ActualYTDValue07 = 0 + , hist.ActualYTDValue08 = 0 + , hist.ActualYTDValue09 = 0 + , hist.ActualYTDValue10 = 0 + , hist.ActualYTDValue11 = 0 + , hist.ActualYTDValue12 = 0 + , hist.CurrentYearBudget01 = 0 + , hist.CurrentYearBudget02 = 0 + , hist.CurrentYearBudget03 = 0 + , hist.CurrentYearBudget04 = 0 + , hist.CurrentYearBudget05 = 0 + , hist.CurrentYearBudget06 = 0 + , hist.CurrentYearBudget07 = 0 + , hist.CurrentYearBudget08 = 0 + , hist.CurrentYearBudget09 = 0 + , hist.CurrentYearBudget10 = 0 + , hist.CurrentYearBudget11 = 0 + , hist.CurrentYearBudget12 = 0 + FROM [fp].[FactBenefits] ben + INNER JOIN [fp].[FactBenefitsHistory] hist ON ben.BenefitsID = hist.BenefitsID + INNER JOIN #FilterByDepartment dept ON ben.DepartmentID = dept.DepartmentID + INNER JOIN #FixedAccounts acct ON ben.AccountID = acct.AccountID + WHERE EntityGroupConfigID = @EntityGroupConfigID AND ben.UnitTypeID IN (144, 169, 170, 171) + + + END +GO + + +--------------------------------------------- + +-- fp.procResetBenefitsFlexMethod +CREATE PROCEDURE [fp].[procResetBenefitsFlexMethod] + @EntityGroupConfigID INT + ,@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table + ** 2 2021-02-16 NN JAZZ-466 Remove null joins + *************************************************************/ + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[FactBenefits] d WITH (READUNCOMMITTED) + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + UPDATE fb + SET FlexMethodID = 0 + FROM [fp].[FactBenefits] fb + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fb.DepartmentID + INNER JOIN [fp].[EntityGroupConfig] egc + ON fb.EntityGroupConfigID = egc.EntityGroupConfigID + INNER JOIN [fp].[AccountFlexConfig] afc + ON fb.AccountID = afc.AccountID + AND egc.EntityGroupConfigGUID = afc.EntityGroupConfigGUID + WHERE fb.EntityGroupConfigID = @EntityGroupConfigID + AND FlexMethodID <> 0 + AND FlexMethodClassName = '' + + UPDATE fb + SET FlexMethodID = 1 + FROM [fp].[FactBenefits] fb + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fb.DepartmentID + INNER JOIN [fp].[EntityGroupConfig] egc + ON fb.EntityGroupConfigID = egc.EntityGroupConfigID + INNER JOIN [fp].[AccountFlexConfig] afc + ON fb.AccountID = afc.AccountID + AND egc.EntityGroupConfigGUID = afc.EntityGroupConfigGUID + WHERE fb.EntityGroupConfigID = @EntityGroupConfigID + AND FlexMethodID <> 1 + AND FlexMethodClassName = 'FlexAccountByFTEs' + + UPDATE fb + SET FlexMethodID = 2 + FROM [fp].[FactBenefits] fb + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fb.DepartmentID + INNER JOIN [fp].[EntityGroupConfig] egc + ON fb.EntityGroupConfigID = egc.EntityGroupConfigID + INNER JOIN [fp].[AccountFlexConfig] afc + ON fb.AccountID = afc.AccountID + AND egc.EntityGroupConfigGUID = afc.EntityGroupConfigGUID + WHERE fb.EntityGroupConfigID = @EntityGroupConfigID + AND FlexMethodID <> 2 + AND FlexMethodClassName = 'FlexAccountBySalaries' + +END +GO + + +--------------------------------------------- + +-- fp.procResetBenefitsManager +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-08-09 JB JAZZ-23177 Switch usages of funcGetSourceDimensionalityAsTable to a temp table. Combined separate budget staffing temp tables. +*************************************************************/ +CREATE PROCEDURE [fp].[procResetBenefitsManager] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + IF OBJECT_ID('tempdb..#tmpResetBenefitsItems') IS NOT NULL DROP TABLE #tmpResetBenefitsItems + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment; + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #tmpResetBenefitsItems ( + BenefitsID INT + ) + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) BEGIN + INSERT INTO #tmpResetBenefitsItems (BenefitsID) + SELECT BenefitsID + FROM [fp].[FactBenefits] data + INNER JOIN #FilterByDepartment SD ON (SD.DepartmentID = data.DepartmentID) + WHERE data.BudgetConfigID = @BudgetConfigID + END + ELSE BEGIN + INSERT INTO #tmpResetBenefitsItems (BenefitsID) + SELECT BenefitsID + FROM [fp].[FactBenefits] + WHERE BudgetConfigID = @BudgetConfigID + END + + UPDATE mgr + SET + mgr.AdjustedValue01 = admin.AdjustedValue01, + mgr.AdjustedValue02 = admin.AdjustedValue02, + mgr.AdjustedValue03 = admin.AdjustedValue03, + mgr.AdjustedValue04 = admin.AdjustedValue04, + mgr.AdjustedValue05 = admin.AdjustedValue05, + mgr.AdjustedValue06 = admin.AdjustedValue06, + mgr.AdjustedValue07 = admin.AdjustedValue07, + mgr.AdjustedValue08 = admin.AdjustedValue08, + mgr.AdjustedValue09 = admin.AdjustedValue09, + mgr.AdjustedValue10 = admin.AdjustedValue10, + mgr.AdjustedValue11 = admin.AdjustedValue11, + mgr.AdjustedValue12 = admin.AdjustedValue12, + mgr.LockType = admin.LockType, + mgr.LockFlag = admin.LockFlag + FROM [fp].[FactBenefitsBudget] mgr + INNER JOIN [fp].[FactBenefits] fgl ON mgr.BenefitsID = fgl.BenefitsID + INNER JOIN [fp].[FactBenefitsBudget] admin ON admin.BenefitsID = mgr.BenefitsID + INNER JOIN #tmpResetBenefitsItems filter ON fgl.BenefitsID = filter.BenefitsID + WHERE fgl.BudgetConfigID = @BudgetConfigID + AND mgr.LockType NOT IN (2, 3) + AND admin.BudgetPhaseID = 2 + AND mgr.BudgetPhaseID = 3 + AND ( + mgr.AdjustedValue01 != admin.AdjustedValue01 OR + mgr.AdjustedValue02 != admin.AdjustedValue02 OR + mgr.AdjustedValue03 != admin.AdjustedValue03 OR + mgr.AdjustedValue04 != admin.AdjustedValue04 OR + mgr.AdjustedValue05 != admin.AdjustedValue05 OR + mgr.AdjustedValue06 != admin.AdjustedValue06 OR + mgr.AdjustedValue07 != admin.AdjustedValue07 OR + mgr.AdjustedValue08 != admin.AdjustedValue08 OR + mgr.AdjustedValue09 != admin.AdjustedValue09 OR + mgr.AdjustedValue10 != admin.AdjustedValue10 OR + mgr.AdjustedValue11 != admin.AdjustedValue11 OR + mgr.AdjustedValue12 != admin.AdjustedValue12) + + UPDATE mgr + SET + mgr.AdjustedValue01 = admin.AdjustedValue01, + mgr.AdjustedValue02 = admin.AdjustedValue02, + mgr.AdjustedValue03 = admin.AdjustedValue03, + mgr.AdjustedValue04 = admin.AdjustedValue04, + mgr.AdjustedValue05 = admin.AdjustedValue05, + mgr.AdjustedValue06 = admin.AdjustedValue06, + mgr.AdjustedValue07 = admin.AdjustedValue07, + mgr.AdjustedValue08 = admin.AdjustedValue08, + mgr.AdjustedValue09 = admin.AdjustedValue09, + mgr.AdjustedValue10 = admin.AdjustedValue10, + mgr.AdjustedValue11 = admin.AdjustedValue11, + mgr.AdjustedValue12 = admin.AdjustedValue12, + mgr.LockType = admin.LockType, + mgr.LockFlag = admin.LockFlag + FROM [fp].[FactBenefitsProjection] mgr + INNER JOIN [fp].[FactBenefits] fgl ON mgr.BenefitsID = fgl.BenefitsID + INNER JOIN [fp].[FactBenefitsProjection] admin ON admin.BenefitsID = mgr.BenefitsID + INNER JOIN #tmpResetBenefitsItems filter ON fgl.BenefitsID = filter.BenefitsID + WHERE fgl.BudgetConfigID = @BudgetConfigID + AND mgr.LockType NOT IN (2, 3) + AND admin.BudgetPhaseID = 2 + AND mgr.BudgetPhaseID = 3 + AND ( + mgr.AdjustedValue01 != admin.AdjustedValue01 OR + mgr.AdjustedValue02 != admin.AdjustedValue02 OR + mgr.AdjustedValue03 != admin.AdjustedValue03 OR + mgr.AdjustedValue04 != admin.AdjustedValue04 OR + mgr.AdjustedValue05 != admin.AdjustedValue05 OR + mgr.AdjustedValue06 != admin.AdjustedValue06 OR + mgr.AdjustedValue07 != admin.AdjustedValue07 OR + mgr.AdjustedValue08 != admin.AdjustedValue08 OR + mgr.AdjustedValue09 != admin.AdjustedValue09 OR + mgr.AdjustedValue10 != admin.AdjustedValue10 OR + mgr.AdjustedValue11 != admin.AdjustedValue11 OR + mgr.AdjustedValue12 != admin.AdjustedValue12) + +END +GO + + +--------------------------------------------- + +-- fp.procResetBenefitsManagerFixedAccounts +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-08-09 JB JAZZ-23177 Switch usages of funcGetSourceDimensionalityAsTable to a temp table. Combined separate budget staffing temp tables. +*************************************************************/ + + CREATE PROCEDURE [fp].[procResetBenefitsManagerFixedAccounts] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + AS + BEGIN + IF OBJECT_ID('tempdb..#tmpResetBenefitsItems') IS NOT NULL DROP TABLE #tmpResetBenefitsItems + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment; + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #tmpResetBenefitsItems ( + BenefitsID INT + ) + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #tmpResetBenefitsItems (BenefitsID) + SELECT BenefitsID + FROM [fp].[FactBenefits] data + INNER JOIN #FilterByDepartment SD ON (SD.DepartmentID = data.DepartmentID) + WHERE data.FlexMethodID = 0 and data.BudgetConfigID = @BudgetConfigID + END + ELSE BEGIN + INSERT INTO #tmpResetBenefitsItems (BenefitsID) + SELECT BenefitsID + FROM [fp].[FactBenefits] + WHERE FlexMethodID = 0 and BudgetConfigID = @BudgetConfigID + END + + UPDATE mgr + SET + mgr.AdjustedValue01 = admin.AdjustedValue01, + mgr.AdjustedValue02 = admin.AdjustedValue02, + mgr.AdjustedValue03 = admin.AdjustedValue03, + mgr.AdjustedValue04 = admin.AdjustedValue04, + mgr.AdjustedValue05 = admin.AdjustedValue05, + mgr.AdjustedValue06 = admin.AdjustedValue06, + mgr.AdjustedValue07 = admin.AdjustedValue07, + mgr.AdjustedValue08 = admin.AdjustedValue08, + mgr.AdjustedValue09 = admin.AdjustedValue09, + mgr.AdjustedValue10 = admin.AdjustedValue10, + mgr.AdjustedValue11 = admin.AdjustedValue11, + mgr.AdjustedValue12 = admin.AdjustedValue12, + mgr.LockType = admin.LockType, + mgr.LockFlag = admin.LockFlag + FROM [fp].[FactBenefitsBudget] mgr + INNER JOIN [fp].[FactBenefits] fgl ON mgr.BenefitsID = fgl.BenefitsID + INNER JOIN [fp].[FactBenefitsBudget] admin ON admin.BenefitsID = mgr.BenefitsID + INNER JOIN #tmpResetBenefitsItems filter ON fgl.BenefitsID = filter.BenefitsID + WHERE fgl.BudgetConfigID = @BudgetConfigID + AND mgr.LockType NOT IN (2, 3) + AND admin.BudgetPhaseID = 2 + AND mgr.BudgetPhaseID = 3 + AND ( + mgr.AdjustedValue01 != admin.AdjustedValue01 OR + mgr.AdjustedValue02 != admin.AdjustedValue02 OR + mgr.AdjustedValue03 != admin.AdjustedValue03 OR + mgr.AdjustedValue04 != admin.AdjustedValue04 OR + mgr.AdjustedValue05 != admin.AdjustedValue05 OR + mgr.AdjustedValue06 != admin.AdjustedValue06 OR + mgr.AdjustedValue07 != admin.AdjustedValue07 OR + mgr.AdjustedValue08 != admin.AdjustedValue08 OR + mgr.AdjustedValue09 != admin.AdjustedValue09 OR + mgr.AdjustedValue10 != admin.AdjustedValue10 OR + mgr.AdjustedValue11 != admin.AdjustedValue11 OR + mgr.AdjustedValue12 != admin.AdjustedValue12) + + UPDATE mgr + SET + mgr.AdjustedValue01 = admin.AdjustedValue01, + mgr.AdjustedValue02 = admin.AdjustedValue02, + mgr.AdjustedValue03 = admin.AdjustedValue03, + mgr.AdjustedValue04 = admin.AdjustedValue04, + mgr.AdjustedValue05 = admin.AdjustedValue05, + mgr.AdjustedValue06 = admin.AdjustedValue06, + mgr.AdjustedValue07 = admin.AdjustedValue07, + mgr.AdjustedValue08 = admin.AdjustedValue08, + mgr.AdjustedValue09 = admin.AdjustedValue09, + mgr.AdjustedValue10 = admin.AdjustedValue10, + mgr.AdjustedValue11 = admin.AdjustedValue11, + mgr.AdjustedValue12 = admin.AdjustedValue12, + mgr.LockType = admin.LockType, + mgr.LockFlag = admin.LockFlag + FROM [fp].[FactBenefitsProjection] mgr + INNER JOIN [fp].[FactBenefits] fgl ON mgr.BenefitsID = fgl.BenefitsID + INNER JOIN [fp].[FactBenefitsProjection] admin ON admin.BenefitsID = mgr.BenefitsID + INNER JOIN #tmpResetBenefitsItems filter ON fgl.BenefitsID = filter.BenefitsID + WHERE fgl.BudgetConfigID = @BudgetConfigID + AND mgr.LockType NOT IN (2, 3) + AND admin.BudgetPhaseID = 2 + AND mgr.BudgetPhaseID = 3 + AND ( + mgr.AdjustedValue01 != admin.AdjustedValue01 OR + mgr.AdjustedValue02 != admin.AdjustedValue02 OR + mgr.AdjustedValue03 != admin.AdjustedValue03 OR + mgr.AdjustedValue04 != admin.AdjustedValue04 OR + mgr.AdjustedValue05 != admin.AdjustedValue05 OR + mgr.AdjustedValue06 != admin.AdjustedValue06 OR + mgr.AdjustedValue07 != admin.AdjustedValue07 OR + mgr.AdjustedValue08 != admin.AdjustedValue08 OR + mgr.AdjustedValue09 != admin.AdjustedValue09 OR + mgr.AdjustedValue10 != admin.AdjustedValue10 OR + mgr.AdjustedValue11 != admin.AdjustedValue11 OR + mgr.AdjustedValue12 != admin.AdjustedValue12) + END +GO + + +--------------------------------------------- + +-- fp.procResetChargeVolume +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-02-15 BK JAZZ-48305 Create proc for new structure +** 2 2023-05-25 MY JAZZ-55544 Add Projection Lock Cols +*************************************************************/ +CREATE PROCEDURE [fp].[procResetChargeVolume] + @EntityGroupConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + AS + BEGIN + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + + -- Build the department filter + SELECT DISTINCT DepartmentID + INTO #FilterByDepartment + FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + --Unfiltered + UPDATE cv + SET + cv.TargetAdjusted01 = cv.InitialBudget01, cv.TargetAdjusted02 = cv.InitialBudget02, cv.TargetAdjusted03 = cv.InitialBudget03, cv.TargetAdjusted04 = cv.InitialBudget04, cv.TargetAdjusted05 = cv.InitialBudget05, cv.TargetAdjusted06 = cv.InitialBudget06, cv.TargetAdjusted07 = cv.InitialBudget07, cv.TargetAdjusted08 = cv.InitialBudget08, cv.TargetAdjusted09 = cv.InitialBudget09, cv.TargetAdjusted10 = cv.InitialBudget10, cv.TargetAdjusted11 = cv.InitialBudget11, cv.TargetAdjusted12 = cv.InitialBudget12, + cv.BudgetAdjusted01 = cv.InitialBudget01, cv.BudgetAdjusted02 = cv.InitialBudget02, cv.BudgetAdjusted03 = cv.InitialBudget03, cv.BudgetAdjusted04 = cv.InitialBudget04, cv.BudgetAdjusted05 = cv.InitialBudget05, cv.BudgetAdjusted06 = cv.InitialBudget06, cv.BudgetAdjusted07 = cv.InitialBudget07, cv.BudgetAdjusted08 = cv.InitialBudget08, cv.BudgetAdjusted09 = cv.InitialBudget09, cv.BudgetAdjusted10 = cv.InitialBudget10, cv.BudgetAdjusted11 = cv.InitialBudget11, cv.BudgetAdjusted12 = cv.InitialBudget12, + cv.ProjectionAdjusted01 = cv.InitialProjection01, cv.ProjectionAdjusted02 = cv.InitialProjection02, cv.ProjectionAdjusted03 = cv.InitialProjection03, cv.ProjectionAdjusted04 = cv.InitialProjection04, cv.ProjectionAdjusted05 = cv.InitialProjection05, cv.ProjectionAdjusted06 = cv.InitialProjection06, cv.ProjectionAdjusted07 = cv.InitialProjection07, cv.ProjectionAdjusted08 = cv.InitialProjection08, cv.ProjectionAdjusted09 = cv.InitialProjection09, cv.ProjectionAdjusted10 = cv.InitialProjection10, cv.ProjectionAdjusted11 = cv.InitialProjection11, cv.ProjectionAdjusted12 = cv.InitialProjection12, + cv.TargetUnitsPerEncounterAdjusted01 = cv.InitialBudgetUnitsPerEncounter01, cv.TargetUnitsPerEncounterAdjusted02 = cv.InitialBudgetUnitsPerEncounter02, cv.TargetUnitsPerEncounterAdjusted03 = cv.InitialBudgetUnitsPerEncounter03, cv.TargetUnitsPerEncounterAdjusted04 = cv.InitialBudgetUnitsPerEncounter04, cv.TargetUnitsPerEncounterAdjusted05 = cv.InitialBudgetUnitsPerEncounter05, cv.TargetUnitsPerEncounterAdjusted06 = cv.InitialBudgetUnitsPerEncounter06, cv.TargetUnitsPerEncounterAdjusted07 = cv.InitialBudgetUnitsPerEncounter07, cv.TargetUnitsPerEncounterAdjusted08 = cv.InitialBudgetUnitsPerEncounter08, cv.TargetUnitsPerEncounterAdjusted09 = cv.InitialBudgetUnitsPerEncounter09, cv.TargetUnitsPerEncounterAdjusted10 = cv.InitialBudgetUnitsPerEncounter10, cv.TargetUnitsPerEncounterAdjusted11 = cv.InitialBudgetUnitsPerEncounter11, cv.TargetUnitsPerEncounterAdjusted12 = cv.InitialBudgetUnitsPerEncounter12, + cv.BudgetUnitsPerEncounterAdjusted01 = cv.InitialBudgetUnitsPerEncounter01, cv.BudgetUnitsPerEncounterAdjusted02 = cv.InitialBudgetUnitsPerEncounter02, cv.BudgetUnitsPerEncounterAdjusted03 = cv.InitialBudgetUnitsPerEncounter03, cv.BudgetUnitsPerEncounterAdjusted04 = cv.InitialBudgetUnitsPerEncounter04, cv.BudgetUnitsPerEncounterAdjusted05 = cv.InitialBudgetUnitsPerEncounter05, cv.BudgetUnitsPerEncounterAdjusted06 = cv.InitialBudgetUnitsPerEncounter06, cv.BudgetUnitsPerEncounterAdjusted07 = cv.InitialBudgetUnitsPerEncounter07, cv.BudgetUnitsPerEncounterAdjusted08 = cv.InitialBudgetUnitsPerEncounter08, cv.BudgetUnitsPerEncounterAdjusted09 = cv.InitialBudgetUnitsPerEncounter09, cv.BudgetUnitsPerEncounterAdjusted10 = cv.InitialBudgetUnitsPerEncounter10, cv.BudgetUnitsPerEncounterAdjusted11 = cv.InitialBudgetUnitsPerEncounter11, cv.BudgetUnitsPerEncounterAdjusted12 = cv.InitialBudgetUnitsPerEncounter12, + cv.ProjectionUnitsPerEncounterAdjusted01 = cv.InitialProjectionUnitsPerEncounter01, cv.ProjectionUnitsPerEncounterAdjusted02 = cv.InitialProjectionUnitsPerEncounter02, cv.ProjectionUnitsPerEncounterAdjusted03 = cv.InitialProjectionUnitsPerEncounter03, cv.ProjectionUnitsPerEncounterAdjusted04 = cv.InitialProjectionUnitsPerEncounter04, cv.ProjectionUnitsPerEncounterAdjusted05 = cv.InitialProjectionUnitsPerEncounter05, cv.ProjectionUnitsPerEncounterAdjusted06 = cv.InitialProjectionUnitsPerEncounter06, cv.ProjectionUnitsPerEncounterAdjusted07 = cv.InitialProjectionUnitsPerEncounter07, cv.ProjectionUnitsPerEncounterAdjusted08 = cv.InitialProjectionUnitsPerEncounter08, cv.ProjectionUnitsPerEncounterAdjusted09 = cv.InitialProjectionUnitsPerEncounter09, cv.ProjectionUnitsPerEncounterAdjusted10 = cv.InitialProjectionUnitsPerEncounter10, cv.ProjectionUnitsPerEncounterAdjusted11 = cv.InitialProjectionUnitsPerEncounter11, cv.ProjectionUnitsPerEncounterAdjusted12 = cv.InitialProjectionUnitsPerEncounter12, + cv.TargetLockType = 0, + cv.TargetLockFlag = 0, + cv.BudgetLockType = 0, + cv.BudgetLockFlag = 0, + cv.ProjectionLockType = 0, + cv.ProjectionLockFlag = 0 + FROM [fp].[ChargeVolume] cv + WHERE cv.EntityGroupConfigID = @EntityGroupConfigID + + END ELSE BEGIN + --Filtered + UPDATE cv + SET + cv.TargetAdjusted01 = cv.InitialBudget01, cv.TargetAdjusted02 = cv.InitialBudget02, cv.TargetAdjusted03 = cv.InitialBudget03, cv.TargetAdjusted04 = cv.InitialBudget04, cv.TargetAdjusted05 = cv.InitialBudget05, cv.TargetAdjusted06 = cv.InitialBudget06, cv.TargetAdjusted07 = cv.InitialBudget07, cv.TargetAdjusted08 = cv.InitialBudget08, cv.TargetAdjusted09 = cv.InitialBudget09, cv.TargetAdjusted10 = cv.InitialBudget10, cv.TargetAdjusted11 = cv.InitialBudget11, cv.TargetAdjusted12 = cv.InitialBudget12, + cv.BudgetAdjusted01 = cv.InitialBudget01, cv.BudgetAdjusted02 = cv.InitialBudget02, cv.BudgetAdjusted03 = cv.InitialBudget03, cv.BudgetAdjusted04 = cv.InitialBudget04, cv.BudgetAdjusted05 = cv.InitialBudget05, cv.BudgetAdjusted06 = cv.InitialBudget06, cv.BudgetAdjusted07 = cv.InitialBudget07, cv.BudgetAdjusted08 = cv.InitialBudget08, cv.BudgetAdjusted09 = cv.InitialBudget09, cv.BudgetAdjusted10 = cv.InitialBudget10, cv.BudgetAdjusted11 = cv.InitialBudget11, cv.BudgetAdjusted12 = cv.InitialBudget12, + cv.ProjectionAdjusted01 = cv.InitialProjection01, cv.ProjectionAdjusted02 = cv.InitialProjection02, cv.ProjectionAdjusted03 = cv.InitialProjection03, cv.ProjectionAdjusted04 = cv.InitialProjection04, cv.ProjectionAdjusted05 = cv.InitialProjection05, cv.ProjectionAdjusted06 = cv.InitialProjection06, cv.ProjectionAdjusted07 = cv.InitialProjection07, cv.ProjectionAdjusted08 = cv.InitialProjection08, cv.ProjectionAdjusted09 = cv.InitialProjection09, cv.ProjectionAdjusted10 = cv.InitialProjection10, cv.ProjectionAdjusted11 = cv.InitialProjection11, cv.ProjectionAdjusted12 = cv.InitialProjection12, + cv.TargetUnitsPerEncounterAdjusted01 = cv.InitialBudgetUnitsPerEncounter01, cv.TargetUnitsPerEncounterAdjusted02 = cv.InitialBudgetUnitsPerEncounter02, cv.TargetUnitsPerEncounterAdjusted03 = cv.InitialBudgetUnitsPerEncounter03, cv.TargetUnitsPerEncounterAdjusted04 = cv.InitialBudgetUnitsPerEncounter04, cv.TargetUnitsPerEncounterAdjusted05 = cv.InitialBudgetUnitsPerEncounter05, cv.TargetUnitsPerEncounterAdjusted06 = cv.InitialBudgetUnitsPerEncounter06, cv.TargetUnitsPerEncounterAdjusted07 = cv.InitialBudgetUnitsPerEncounter07, cv.TargetUnitsPerEncounterAdjusted08 = cv.InitialBudgetUnitsPerEncounter08, cv.TargetUnitsPerEncounterAdjusted09 = cv.InitialBudgetUnitsPerEncounter09, cv.TargetUnitsPerEncounterAdjusted10 = cv.InitialBudgetUnitsPerEncounter10, cv.TargetUnitsPerEncounterAdjusted11 = cv.InitialBudgetUnitsPerEncounter11, cv.TargetUnitsPerEncounterAdjusted12 = cv.InitialBudgetUnitsPerEncounter12, + cv.BudgetUnitsPerEncounterAdjusted01 = cv.InitialBudgetUnitsPerEncounter01, cv.BudgetUnitsPerEncounterAdjusted02 = cv.InitialBudgetUnitsPerEncounter02, cv.BudgetUnitsPerEncounterAdjusted03 = cv.InitialBudgetUnitsPerEncounter03, cv.BudgetUnitsPerEncounterAdjusted04 = cv.InitialBudgetUnitsPerEncounter04, cv.BudgetUnitsPerEncounterAdjusted05 = cv.InitialBudgetUnitsPerEncounter05, cv.BudgetUnitsPerEncounterAdjusted06 = cv.InitialBudgetUnitsPerEncounter06, cv.BudgetUnitsPerEncounterAdjusted07 = cv.InitialBudgetUnitsPerEncounter07, cv.BudgetUnitsPerEncounterAdjusted08 = cv.InitialBudgetUnitsPerEncounter08, cv.BudgetUnitsPerEncounterAdjusted09 = cv.InitialBudgetUnitsPerEncounter09, cv.BudgetUnitsPerEncounterAdjusted10 = cv.InitialBudgetUnitsPerEncounter10, cv.BudgetUnitsPerEncounterAdjusted11 = cv.InitialBudgetUnitsPerEncounter11, cv.BudgetUnitsPerEncounterAdjusted12 = cv.InitialBudgetUnitsPerEncounter12, + cv.ProjectionUnitsPerEncounterAdjusted01 = cv.InitialProjectionUnitsPerEncounter01, cv.ProjectionUnitsPerEncounterAdjusted02 = cv.InitialProjectionUnitsPerEncounter02, cv.ProjectionUnitsPerEncounterAdjusted03 = cv.InitialProjectionUnitsPerEncounter03, cv.ProjectionUnitsPerEncounterAdjusted04 = cv.InitialProjectionUnitsPerEncounter04, cv.ProjectionUnitsPerEncounterAdjusted05 = cv.InitialProjectionUnitsPerEncounter05, cv.ProjectionUnitsPerEncounterAdjusted06 = cv.InitialProjectionUnitsPerEncounter06, cv.ProjectionUnitsPerEncounterAdjusted07 = cv.InitialProjectionUnitsPerEncounter07, cv.ProjectionUnitsPerEncounterAdjusted08 = cv.InitialProjectionUnitsPerEncounter08, cv.ProjectionUnitsPerEncounterAdjusted09 = cv.InitialProjectionUnitsPerEncounter09, cv.ProjectionUnitsPerEncounterAdjusted10 = cv.InitialProjectionUnitsPerEncounter10, cv.ProjectionUnitsPerEncounterAdjusted11 = cv.InitialProjectionUnitsPerEncounter11, cv.ProjectionUnitsPerEncounterAdjusted12 = cv.InitialProjectionUnitsPerEncounter12, + cv.TargetLockType = 0, + cv.TargetLockFlag = 0, + cv.BudgetLockType = 0, + cv.BudgetLockFlag = 0, + cv.ProjectionLockType = 0, + cv.ProjectionLockFlag = 0 + FROM [fp].[ChargeVolume] cv + INNER JOIN #FilterByDepartment f on f.DepartmentID = cv.DepartmentID + WHERE cv.EntityGroupConfigID = @EntityGroupConfigID + END + + END +GO + + +--------------------------------------------- + +-- fp.procResetDriverAndDependentSection +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 12-14-2020 MY JAZZ-11324 Initial +** 2 10-23-2023 MY JAZZ-62535 SPIKE - Updating what data appears on the Stats pages +*************************************************************/ +CREATE PROCEDURE [fp].[procResetDriverAndDependentSection] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + AS + BEGIN + + DECLARE @Driver INT = (SELECT SubSectionID FROM [fp].[PlanSubsection] sub INNER JOIN [fp].[PlanSection] pe ON sub.PlanSectionID = pe.PlanSectionID WHERE pe.Description = 'Statistics' AND sub.Subsection = 'Driver'), + @Dependent INT = (SELECT SubSectionID FROM [fp].[PlanSubsection] sub INNER JOIN [fp].[PlanSection] pe ON sub.PlanSectionID = pe.PlanSectionID WHERE pe.Description = 'Statistics' AND sub.Subsection = 'Dependent') + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #departments (DepartmentID INT); + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #departments(DepartmentID) + SELECT DISTINCT stat.DepartmentID + FROM fp.FactStatistics stat + INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = stat.DepartmentID + WHERE stat.BudgetConfigID = @BudgetConfigID + END ELSE BEGIN + INSERT INTO #departments(DepartmentID) + SELECT DISTINCT stat.DepartmentID + FROM fp.FactStatistics stat + WHERE stat.BudgetConfigID = @BudgetConfigID + END + + -- We need to reset the sub section for a given record so it not only shows in the correct screen + -- but also works with flexing and other areas. This will update the fp.FactStatistics record with the proper + -- subsection in case it were to change after sampling. + -- An account cannot be both a driver and dependent, so we don't have to worry about this case. + + -------------------------------------------------------------------------------------------------------------------- + -- Dependent Statistic is flexed by a Driver Statistic, Source and Dependent Department Fields left blank + -------------------------------------------------------------------------------------------------------------------- + + -- Driver Statistic Account should appear on the Statistics page for all departments that have data for this statistic (Driver Stat can’t be a primary stat) + UPDATE stat + SET stat.SubSectionID = @Driver + FROM fp.FactStatistics stat + INNER JOIN #departments dept ON stat.DepartmentID = dept.DepartmentID + LEFT JOIN fp.DependentStatisticsAccount dsa ON stat.BudgetConfigID = dsa.BudgetConfigID AND stat.AccountID = dsa.DependentAccountID + WHERE stat.BudgetConfigID = @BudgetConfigID + AND dsa.DependentAccountID IS NULL + AND stat.SubSectionID != @Driver + + -- Dependent Statistic Account should appear on the Dependent Statistics page for all departments that have data for this statistic + UPDATE stat + SET stat.SubSectionID = @Dependent + FROM fp.FactStatistics stat + INNER JOIN #departments dept ON stat.DepartmentID = dept.DepartmentID + INNER JOIN fp.DependentStatisticsAccount dsa ON stat.BudgetConfigID = dsa.BudgetConfigID AND stat.AccountID = dsa.DependentAccountID + LEFT JOIN fp.DependentStatisticsAccountDepartment dsad ON dsa.DependentStatisticsAccountID = dsad.DependentStatisticsAccountID + WHERE stat.BudgetConfigID = @BudgetConfigID + AND dsad.RowID IS NULL + AND stat.SubSectionID != @Dependent + + -------------------------------------------------------------------------------------------------------------------- + -- Dependent Statistic is flexed by a Driver Statistic, Source and Dependent Department Fields are both filled out + -------------------------------------------------------------------------------------------------------------------- + + -- Driver Statistic Account should appear on the Statistics page for all departments that have data for this statistic (Driver Stat can’t be a primary stat) + -- Check for department level dependent accounts. Accounts not in the table will be covered in the first check. + UPDATE stat + SET stat.SubSectionID = @Driver + FROM fp.FactStatistics stat + INNER JOIN #departments dept ON stat.DepartmentID = dept.DepartmentID + INNER JOIN fp.DependentStatisticsAccount dsa ON stat.BudgetConfigID = dsa.BudgetConfigID AND stat.AccountID = dsa.DependentAccountID + LEFT JOIN fp.DependentStatisticsAccountDepartment dsad ON dsa.DependentStatisticsAccountID = dsad.DependentStatisticsAccountID AND stat.DepartmentID = dsad.DepartmentID + WHERE stat.BudgetConfigID = @BudgetConfigID + AND dsa.SourceDepartmentID != -1 -- -1 Means this isn't using Cross Department Flexing + AND dsad.RowID IS NULL + AND stat.SubSectionID != @Driver + + -- Dependent Statistic Account should appear on the Dependent Statistics page only if departments were configured and selected on the Statistics Account mapping. + -- If the dependent statistics account has departments that weren’t configured as dependent departments, then these department/account combinations should appear on the Statistics page + UPDATE stat + SET stat.SubSectionID = @Dependent + FROM fp.FactStatistics stat + INNER JOIN #departments dept ON stat.DepartmentID = dept.DepartmentID + INNER JOIN fp.DependentStatisticsAccount dsa ON stat.BudgetConfigID = dsa.BudgetConfigID AND stat.AccountID = dsa.DependentAccountID + INNER JOIN fp.DependentStatisticsAccountDepartment dsad ON dsa.DependentStatisticsAccountID = dsad.DependentStatisticsAccountID AND stat.DepartmentID = dsad.DepartmentID + WHERE stat.BudgetConfigID = @BudgetConfigID + AND stat.SubSectionID != @Dependent + + -- Find anything that doesn't have a sub-section for some reason and assign it to driver. + UPDATE stat + SET stat.SubSectionID = @Driver + FROM fp.FactStatistics stat + INNER JOIN #departments dept ON stat.DepartmentID = dept.DepartmentID + WHERE stat.BudgetConfigID = @BudgetConfigID + AND stat.SubSectionID = 0 + END +GO + + +--------------------------------------------- + +-- fp.procResetFactBenefitsTables +CREATE PROCEDURE [fp].[procResetFactBenefitsTables] + @EntityGroupConfigID INT, + @UnitTypeIds dbo.SqlInt32ListTableType READONLY, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table + *************************************************************/ + + CREATE TABLE #UnitTypeIds (Value int) + INSERT INTO #UnitTypeIds (VALUE) + SELECT Value from @UnitTypeIds + + + CREATE TABLE #FilterByDepartment (DepartmentID int,BudgetPhaseID int) + INSERT INTO #FilterByDepartment (DepartmentID,BudgetPhaseID) + SELECT DepartmentID,BudgetPhaseID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + -- reset the data in the budget table + UPDATE tbl + SET + tbl.AdjustedValue01 = fgl.InitialBudget01, tbl.AdjustedValue02 = fgl.InitialBudget02, tbl.AdjustedValue03 = fgl.InitialBudget03, tbl.AdjustedValue04 = fgl.InitialBudget04, tbl.AdjustedValue05 = fgl.InitialBudget05, tbl.AdjustedValue06 = fgl.InitialBudget06, tbl.AdjustedValue07 = fgl.InitialBudget07, tbl.AdjustedValue08 = fgl.InitialBudget08, tbl.AdjustedValue09 = fgl.InitialBudget09, tbl.AdjustedValue10 = fgl.InitialBudget10, tbl.AdjustedValue11 = fgl.InitialBudget11, tbl.AdjustedValue12 = fgl.InitialBudget12, + tbl.FlexedValue01 = fgl.InitialBudget01, tbl.FlexedValue02 = fgl.InitialBudget02, tbl.FlexedValue03 = fgl.InitialBudget03, tbl.FlexedValue04 = fgl.InitialBudget04, tbl.FlexedValue05 = fgl.InitialBudget05, tbl.FlexedValue06 = fgl.InitialBudget06, tbl.FlexedValue07 = fgl.InitialBudget07, tbl.FlexedValue08 = fgl.InitialBudget08, tbl.FlexedValue09 = fgl.InitialBudget09, tbl.FlexedValue10 = fgl.InitialBudget10, tbl.FlexedValue11 = fgl.InitialBudget11, tbl.FlexedValue12 = fgl.InitialBudget12, + tbl.LockType = 0, + tbl.LockFlag = 0 + FROM [fp].[FactBenefitsBudget] tbl + INNER JOIN [fp].[FactBenefits] fgl ON tbl.BenefitsID = fgl.BenefitsID + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = fgl.DepartmentID or ft.DepartmentID is null) + WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID + AND fgl.UnitTypeID IN (SELECT value FROM #UnitTypeIds) + AND (tbl.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL) + + -- reset the data in the projection table + UPDATE tbl + SET + tbl.AdjustedValue01 = fgl.InitialProjection01, tbl.AdjustedValue02 = fgl.InitialProjection02, tbl.AdjustedValue03 = fgl.InitialProjection03, tbl.AdjustedValue04 = fgl.InitialProjection04, tbl.AdjustedValue05 = fgl.InitialProjection05, tbl.AdjustedValue06 = fgl.InitialProjection06, tbl.AdjustedValue07 = fgl.InitialProjection07, tbl.AdjustedValue08 = fgl.InitialProjection08, tbl.AdjustedValue09 = fgl.InitialProjection09, tbl.AdjustedValue10 = fgl.InitialProjection10, tbl.AdjustedValue11 = fgl.InitialProjection11, tbl.AdjustedValue12 = fgl.InitialProjection12, + tbl.FlexedValue01 = fgl.InitialProjection01, tbl.FlexedValue02 = fgl.InitialProjection02, tbl.FlexedValue03 = fgl.InitialProjection03, tbl.FlexedValue04 = fgl.InitialProjection04, tbl.FlexedValue05 = fgl.InitialProjection05, tbl.FlexedValue06 = fgl.InitialProjection06, tbl.FlexedValue07 = fgl.InitialProjection07, tbl.FlexedValue08 = fgl.InitialProjection08, tbl.FlexedValue09 = fgl.InitialProjection09, tbl.FlexedValue10 = fgl.InitialProjection10, tbl.FlexedValue11 = fgl.InitialProjection11, tbl.FlexedValue12 = fgl.InitialProjection12, + tbl.LockType = 0, + tbl.LockFlag = 0 + FROM [fp].[FactBenefitsProjection] tbl + INNER JOIN [fp].[FactBenefits] fgl ON tbl.BenefitsID = fgl.BenefitsID + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = fgl.DepartmentID or ft.DepartmentID is null) + WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID + AND fgl.UnitTypeID IN (SELECT value FROM #UnitTypeIds) + AND (tbl.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL) + +END +GO + + +--------------------------------------------- + +-- fp.procResetFactReimbursementChargesTables +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-16-05 MY JAZZ-32944 Initial +*************************************************************/ +CREATE PROCEDURE [fp].[procResetFactReimbursementChargesTables] + @EntityGroupConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + AS + BEGIN + + CREATE TABLE #FilteringTable ( + EntityID INT, + INDEX ix_1 NONCLUSTERED (EntityID) + ) + + INSERT INTO #FilteringTable (EntityID) + SELECT src.EntityID + FROM @SourceDimensionality src + INNER JOIN fw.DimDepartment dept ON src.DepartmentID = dept.DepartmentID + UNION + SELECT d.EntityID + FROM fw.DimDepartment d + INNER JOIN @SourceDimensionality sd + ON sd.EntityID = d.EntityID + WHERE sd.DepartmentID IS NULL -- filter rows, where particular DepartmentID is set as specification of EntityID + + DECLARE @isFilterPresent int = (SELECT COUNT(*) FROM #FilteringTable) + + IF (@isFilterPresent = 0) + INSERT INTO #FilteringTable (EntityID) VALUES (NULL) + + UPDATE tbl + SET + tbl.AdjustedNetAsPercentOfCharge01 = fgl.InitialBudgetNetAsPercentOfCharge01, tbl.AdjustedNetAsPercentOfCharge02 = fgl.InitialBudgetNetAsPercentOfCharge02, tbl.AdjustedNetAsPercentOfCharge03 = fgl.InitialBudgetNetAsPercentOfCharge03, + tbl.AdjustedNetAsPercentOfCharge04 = fgl.InitialBudgetNetAsPercentOfCharge04, tbl.AdjustedNetAsPercentOfCharge05 = fgl.InitialBudgetNetAsPercentOfCharge05, tbl.AdjustedNetAsPercentOfCharge06 = fgl.InitialBudgetNetAsPercentOfCharge06, + tbl.AdjustedNetAsPercentOfCharge07 = fgl.InitialBudgetNetAsPercentOfCharge07, tbl.AdjustedNetAsPercentOfCharge08 = fgl.InitialBudgetNetAsPercentOfCharge08, tbl.AdjustedNetAsPercentOfCharge09 = fgl.InitialBudgetNetAsPercentOfCharge09, + tbl.AdjustedNetAsPercentOfCharge10 = fgl.InitialBudgetNetAsPercentOfCharge10, tbl.AdjustedNetAsPercentOfCharge11 = fgl.InitialBudgetNetAsPercentOfCharge11, tbl.AdjustedNetAsPercentOfCharge12 = fgl.InitialBudgetNetAsPercentOfCharge12, + + tbl.AdjustedNetPerDiem01 = fgl.InitialBudgetNetPerDiem01, tbl.AdjustedNetPerDiem02 = fgl.InitialBudgetNetPerDiem02, tbl.AdjustedNetPerDiem03 = fgl.InitialBudgetNetPerDiem03, + tbl.AdjustedNetPerDiem04 = fgl.InitialBudgetNetPerDiem04, tbl.AdjustedNetPerDiem05 = fgl.InitialBudgetNetPerDiem05, tbl.AdjustedNetPerDiem06 = fgl.InitialBudgetNetPerDiem06, + tbl.AdjustedNetPerDiem07 = fgl.InitialBudgetNetPerDiem07, tbl.AdjustedNetPerDiem08 = fgl.InitialBudgetNetPerDiem08, tbl.AdjustedNetPerDiem09 = fgl.InitialBudgetNetPerDiem09, + tbl.AdjustedNetPerDiem10 = fgl.InitialBudgetNetPerDiem10, tbl.AdjustedNetPerDiem11 = fgl.InitialBudgetNetPerDiem11, tbl.AdjustedNetPerDiem12 = fgl.InitialBudgetNetPerDiem12, + + tbl.LockType = 0, + tbl.LockFlag = 0 + FROM [fp].[FactReimbursementChargesBudget] tbl + INNER JOIN [fp].[FactReimbursementCharges] fgl ON tbl.ReimbursementChargesID = fgl.ReimbursementChargesID + INNER JOIN #FilteringTable ft on (@isFilterPresent = 0 OR ft.EntityID = fgl.EntityID) + WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID + + UPDATE tbl + SET + tbl.AdjustedNetAsPercentOfCharge01 = fgl.InitialProjectionNetAsPercentOfCharge01, tbl.AdjustedNetAsPercentOfCharge02 = fgl.InitialProjectionNetAsPercentOfCharge02, tbl.AdjustedNetAsPercentOfCharge03 = fgl.InitialProjectionNetAsPercentOfCharge03, + tbl.AdjustedNetAsPercentOfCharge04 = fgl.InitialProjectionNetAsPercentOfCharge04, tbl.AdjustedNetAsPercentOfCharge05 = fgl.InitialProjectionNetAsPercentOfCharge05, tbl.AdjustedNetAsPercentOfCharge06 = fgl.InitialProjectionNetAsPercentOfCharge06, + tbl.AdjustedNetAsPercentOfCharge07 = fgl.InitialProjectionNetAsPercentOfCharge07, tbl.AdjustedNetAsPercentOfCharge08 = fgl.InitialProjectionNetAsPercentOfCharge08, tbl.AdjustedNetAsPercentOfCharge09 = fgl.InitialProjectionNetAsPercentOfCharge09, + tbl.AdjustedNetAsPercentOfCharge10 = fgl.InitialProjectionNetAsPercentOfCharge10, tbl.AdjustedNetAsPercentOfCharge11 = fgl.InitialProjectionNetAsPercentOfCharge11, tbl.AdjustedNetAsPercentOfCharge12 = fgl.InitialProjectionNetAsPercentOfCharge12, + + tbl.AdjustedNetPerDiem01 = fgl.InitialProjectionNetPerDiem01, tbl.AdjustedNetPerDiem02 = fgl.InitialProjectionNetPerDiem02, tbl.AdjustedNetPerDiem03 = fgl.InitialProjectionNetPerDiem03, + tbl.AdjustedNetPerDiem04 = fgl.InitialProjectionNetPerDiem04, tbl.AdjustedNetPerDiem05 = fgl.InitialProjectionNetPerDiem05, tbl.AdjustedNetPerDiem06 = fgl.InitialProjectionNetPerDiem06, + tbl.AdjustedNetPerDiem07 = fgl.InitialProjectionNetPerDiem07, tbl.AdjustedNetPerDiem08 = fgl.InitialProjectionNetPerDiem08, tbl.AdjustedNetPerDiem09 = fgl.InitialProjectionNetPerDiem09, + tbl.AdjustedNetPerDiem10 = fgl.InitialProjectionNetPerDiem10, tbl.AdjustedNetPerDiem11 = fgl.InitialProjectionNetPerDiem11, tbl.AdjustedNetPerDiem12 = fgl.InitialProjectionNetPerDiem12, + + tbl.LockType = 0, + tbl.LockFlag = 0 + FROM [fp].[FactReimbursementChargesProjection] tbl + INNER JOIN [fp].[FactReimbursementCharges] fgl ON tbl.ReimbursementChargesID = fgl.ReimbursementChargesID + INNER JOIN #FilteringTable ft on (@isFilterPresent = 0 OR ft.EntityID = fgl.EntityID) + WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID + + END +GO + + +--------------------------------------------- + +-- fp.procResetFactReimbursementEncounterTables +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-16-05 MY JAZZ-32944 Initial +*************************************************************/ +CREATE PROCEDURE [fp].[procResetFactReimbursementEncounterTables] + @EntityGroupConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + AS + BEGIN + + CREATE TABLE #FilteringTable ( + EntityID INT, + INDEX ix_1 NONCLUSTERED (EntityID) + ) + + INSERT INTO #FilteringTable (EntityID) + SELECT src.EntityID + FROM @SourceDimensionality src + INNER JOIN fw.DimDepartment dept ON src.DepartmentID = dept.DepartmentID + UNION + SELECT d.EntityID + FROM fw.DimDepartment d + INNER JOIN @SourceDimensionality sd + ON sd.EntityID = d.EntityID + WHERE sd.DepartmentID IS NULL -- filter rows, where particular DepartmentID is set as specification of EntityID + + DECLARE @isFilterPresent int = (SELECT COUNT(*) FROM #FilteringTable) + + IF (@isFilterPresent = 0) + INSERT INTO #FilteringTable (EntityID) VALUES (NULL) + + UPDATE tbl + SET + tbl.AdjustedNetPerEncounterValue01 = fgl.InitialBudgetNetPerEncounter01, tbl.AdjustedNetPerEncounterValue02 = fgl.InitialBudgetNetPerEncounter02, tbl.AdjustedNetPerEncounterValue03 = fgl.InitialBudgetNetPerEncounter03, + tbl.AdjustedNetPerEncounterValue04 = fgl.InitialBudgetNetPerEncounter04, tbl.AdjustedNetPerEncounterValue05 = fgl.InitialBudgetNetPerEncounter05, tbl.AdjustedNetPerEncounterValue06 = fgl.InitialBudgetNetPerEncounter06, + tbl.AdjustedNetPerEncounterValue07 = fgl.InitialBudgetNetPerEncounter07, tbl.AdjustedNetPerEncounterValue08 = fgl.InitialBudgetNetPerEncounter08, tbl.AdjustedNetPerEncounterValue09 = fgl.InitialBudgetNetPerEncounter09, + tbl.AdjustedNetPerEncounterValue10 = fgl.InitialBudgetNetPerEncounter10, tbl.AdjustedNetPerEncounterValue11 = fgl.InitialBudgetNetPerEncounter11, tbl.AdjustedNetPerEncounterValue12 = fgl.InitialBudgetNetPerEncounter12, + + tbl.LockType = 0, + tbl.LockFlag = 0 + FROM [fp].[FactReimbursementEncounterBudget] tbl + INNER JOIN [fp].[FactReimbursementEncounter] fgl ON tbl.ReimbursementEncounterID = fgl.ReimbursementEncounterID + INNER JOIN #FilteringTable ft on (@isFilterPresent = 0 OR ft.EntityID = fgl.EntityID) + WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID + + UPDATE tbl + SET + tbl.AdjustedNetPerEncounterValue01 = fgl.InitialProjectionNetPerEncounter01, tbl.AdjustedNetPerEncounterValue02 = fgl.InitialProjectionNetPerEncounter02, tbl.AdjustedNetPerEncounterValue03 = fgl.InitialProjectionNetPerEncounter03, + tbl.AdjustedNetPerEncounterValue04 = fgl.InitialProjectionNetPerEncounter04, tbl.AdjustedNetPerEncounterValue05 = fgl.InitialProjectionNetPerEncounter05, tbl.AdjustedNetPerEncounterValue06 = fgl.InitialProjectionNetPerEncounter06, + tbl.AdjustedNetPerEncounterValue07 = fgl.InitialProjectionNetPerEncounter07, tbl.AdjustedNetPerEncounterValue08 = fgl.InitialProjectionNetPerEncounter08, tbl.AdjustedNetPerEncounterValue09 = fgl.InitialProjectionNetPerEncounter09, + tbl.AdjustedNetPerEncounterValue10 = fgl.InitialProjectionNetPerEncounter10, tbl.AdjustedNetPerEncounterValue11 = fgl.InitialProjectionNetPerEncounter11, tbl.AdjustedNetPerEncounterValue12 = fgl.InitialProjectionNetPerEncounter12, + + tbl.LockType = 0, + tbl.LockFlag = 0 + FROM [fp].[FactReimbursementEncounterProjection] tbl + INNER JOIN [fp].[FactReimbursementEncounter] fgl ON tbl.ReimbursementEncounterID = fgl.ReimbursementEncounterID + INNER JOIN #FilteringTable ft on (@isFilterPresent = 0 OR ft.EntityID = fgl.EntityID) + WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID + END +GO + + +--------------------------------------------- + +-- fp.procResetGeneralLedgerFromSnapshot +CREATE PROCEDURE [fp].[procResetGeneralLedgerFromSnapshot] + @EntityGroupConfigID INT, + @SnapshotID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 07-18-2024 MY JAZZ-77735 Initial Creation + *************************************************************/ + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fw].[DimDepartment] d WITH (READUNCOMMITTED) + INNER JOIN [fp].[EntityGroupConfigMapping] egcm on egcm.EntityID = d.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID + WHERE egc.EntityGroupConfigID = @EntityGroupConfigID + END + + UPDATE gl + SET + gl.TargetAdjusted01 = ISNULL(gls.TargetAdjusted01, 0), + gl.TargetAdjusted02 = ISNULL(gls.TargetAdjusted02, 0), + gl.TargetAdjusted03 = ISNULL(gls.TargetAdjusted03, 0), + gl.TargetAdjusted04 = ISNULL(gls.TargetAdjusted04, 0), + gl.TargetAdjusted05 = ISNULL(gls.TargetAdjusted05, 0), + gl.TargetAdjusted06 = ISNULL(gls.TargetAdjusted06, 0), + gl.TargetAdjusted07 = ISNULL(gls.TargetAdjusted07, 0), + gl.TargetAdjusted08 = ISNULL(gls.TargetAdjusted08, 0), + gl.TargetAdjusted09 = ISNULL(gls.TargetAdjusted09, 0), + gl.TargetAdjusted10 = ISNULL(gls.TargetAdjusted10, 0), + gl.TargetAdjusted11 = ISNULL(gls.TargetAdjusted11, 0), + gl.TargetAdjusted12 = ISNULL(gls.TargetAdjusted12, 0), + + gl.BudgetAdjusted01 = ISNULL(gls.BudgetAdjusted01, 0), + gl.BudgetAdjusted02 = ISNULL(gls.BudgetAdjusted02, 0), + gl.BudgetAdjusted03 = ISNULL(gls.BudgetAdjusted03, 0), + gl.BudgetAdjusted04 = ISNULL(gls.BudgetAdjusted04, 0), + gl.BudgetAdjusted05 = ISNULL(gls.BudgetAdjusted05, 0), + gl.BudgetAdjusted06 = ISNULL(gls.BudgetAdjusted06, 0), + gl.BudgetAdjusted07 = ISNULL(gls.BudgetAdjusted07, 0), + gl.BudgetAdjusted08 = ISNULL(gls.BudgetAdjusted08, 0), + gl.BudgetAdjusted09 = ISNULL(gls.BudgetAdjusted09, 0), + gl.BudgetAdjusted10 = ISNULL(gls.BudgetAdjusted10, 0), + gl.BudgetAdjusted11 = ISNULL(gls.BudgetAdjusted11, 0), + gl.BudgetAdjusted12 = ISNULL(gls.BudgetAdjusted12, 0), + + gl.ProjectionAdjusted01 = ISNULL(gls.ProjectionAdjusted01, 0), + gl.ProjectionAdjusted02 = ISNULL(gls.ProjectionAdjusted02, 0), + gl.ProjectionAdjusted03 = ISNULL(gls.ProjectionAdjusted03, 0), + gl.ProjectionAdjusted04 = ISNULL(gls.ProjectionAdjusted04, 0), + gl.ProjectionAdjusted05 = ISNULL(gls.ProjectionAdjusted05, 0), + gl.ProjectionAdjusted06 = ISNULL(gls.ProjectionAdjusted06, 0), + gl.ProjectionAdjusted07 = ISNULL(gls.ProjectionAdjusted07, 0), + gl.ProjectionAdjusted08 = ISNULL(gls.ProjectionAdjusted08, 0), + gl.ProjectionAdjusted09 = ISNULL(gls.ProjectionAdjusted09, 0), + gl.ProjectionAdjusted10 = ISNULL(gls.ProjectionAdjusted10, 0), + gl.ProjectionAdjusted11 = ISNULL(gls.ProjectionAdjusted11, 0), + gl.ProjectionAdjusted12 = ISNULL(gls.ProjectionAdjusted12, 0), + + gl.TargetPercentAdjustmentFactor01 = ISNULL(gls.TargetPercentAdjustmentFactor01, 1), + gl.TargetPercentAdjustmentFactor02 = ISNULL(gls.TargetPercentAdjustmentFactor02, 1), + gl.TargetPercentAdjustmentFactor03 = ISNULL(gls.TargetPercentAdjustmentFactor03, 1), + gl.TargetPercentAdjustmentFactor04 = ISNULL(gls.TargetPercentAdjustmentFactor04, 1), + gl.TargetPercentAdjustmentFactor05 = ISNULL(gls.TargetPercentAdjustmentFactor05, 1), + gl.TargetPercentAdjustmentFactor06 = ISNULL(gls.TargetPercentAdjustmentFactor06, 1), + gl.TargetPercentAdjustmentFactor07 = ISNULL(gls.TargetPercentAdjustmentFactor07, 1), + gl.TargetPercentAdjustmentFactor08 = ISNULL(gls.TargetPercentAdjustmentFactor08, 1), + gl.TargetPercentAdjustmentFactor09 = ISNULL(gls.TargetPercentAdjustmentFactor09, 1), + gl.TargetPercentAdjustmentFactor10 = ISNULL(gls.TargetPercentAdjustmentFactor10, 1), + gl.TargetPercentAdjustmentFactor11 = ISNULL(gls.TargetPercentAdjustmentFactor11, 1), + gl.TargetPercentAdjustmentFactor12 = ISNULL(gls.TargetPercentAdjustmentFactor12, 1), + + gl.BudgetPercentAdjustmentFactor01 = ISNULL(gls.BudgetPercentAdjustmentFactor01, 1), + gl.BudgetPercentAdjustmentFactor02 = ISNULL(gls.BudgetPercentAdjustmentFactor02, 1), + gl.BudgetPercentAdjustmentFactor03 = ISNULL(gls.BudgetPercentAdjustmentFactor03, 1), + gl.BudgetPercentAdjustmentFactor04 = ISNULL(gls.BudgetPercentAdjustmentFactor04, 1), + gl.BudgetPercentAdjustmentFactor05 = ISNULL(gls.BudgetPercentAdjustmentFactor05, 1), + gl.BudgetPercentAdjustmentFactor06 = ISNULL(gls.BudgetPercentAdjustmentFactor06, 1), + gl.BudgetPercentAdjustmentFactor07 = ISNULL(gls.BudgetPercentAdjustmentFactor07, 1), + gl.BudgetPercentAdjustmentFactor08 = ISNULL(gls.BudgetPercentAdjustmentFactor08, 1), + gl.BudgetPercentAdjustmentFactor09 = ISNULL(gls.BudgetPercentAdjustmentFactor09, 1), + gl.BudgetPercentAdjustmentFactor10 = ISNULL(gls.BudgetPercentAdjustmentFactor10, 1), + gl.BudgetPercentAdjustmentFactor11 = ISNULL(gls.BudgetPercentAdjustmentFactor11, 1), + gl.BudgetPercentAdjustmentFactor12 = ISNULL(gls.BudgetPercentAdjustmentFactor12, 1), + + gl.ProjectionPercentAdjustmentFactor01 = ISNULL(gls.ProjectionPercentAdjustmentFactor01, 1), + gl.ProjectionPercentAdjustmentFactor02 = ISNULL(gls.ProjectionPercentAdjustmentFactor02, 1), + gl.ProjectionPercentAdjustmentFactor03 = ISNULL(gls.ProjectionPercentAdjustmentFactor03, 1), + gl.ProjectionPercentAdjustmentFactor04 = ISNULL(gls.ProjectionPercentAdjustmentFactor04, 1), + gl.ProjectionPercentAdjustmentFactor05 = ISNULL(gls.ProjectionPercentAdjustmentFactor05, 1), + gl.ProjectionPercentAdjustmentFactor06 = ISNULL(gls.ProjectionPercentAdjustmentFactor06, 1), + gl.ProjectionPercentAdjustmentFactor07 = ISNULL(gls.ProjectionPercentAdjustmentFactor07, 1), + gl.ProjectionPercentAdjustmentFactor08 = ISNULL(gls.ProjectionPercentAdjustmentFactor08, 1), + gl.ProjectionPercentAdjustmentFactor09 = ISNULL(gls.ProjectionPercentAdjustmentFactor09, 1), + gl.ProjectionPercentAdjustmentFactor10 = ISNULL(gls.ProjectionPercentAdjustmentFactor10, 1), + gl.ProjectionPercentAdjustmentFactor11 = ISNULL(gls.ProjectionPercentAdjustmentFactor11, 1), + gl.ProjectionPercentAdjustmentFactor12 = ISNULL(gls.ProjectionPercentAdjustmentFactor12, 1), + + gl.TargetDollarsPerUOSAdjusted01 = ISNULL(gls.TargetDollarsPerUOSAdjusted01, 0), + gl.TargetDollarsPerUOSAdjusted02 = ISNULL(gls.TargetDollarsPerUOSAdjusted02, 0), + gl.TargetDollarsPerUOSAdjusted03 = ISNULL(gls.TargetDollarsPerUOSAdjusted03, 0), + gl.TargetDollarsPerUOSAdjusted04 = ISNULL(gls.TargetDollarsPerUOSAdjusted04, 0), + gl.TargetDollarsPerUOSAdjusted05 = ISNULL(gls.TargetDollarsPerUOSAdjusted05, 0), + gl.TargetDollarsPerUOSAdjusted06 = ISNULL(gls.TargetDollarsPerUOSAdjusted06, 0), + gl.TargetDollarsPerUOSAdjusted07 = ISNULL(gls.TargetDollarsPerUOSAdjusted07, 0), + gl.TargetDollarsPerUOSAdjusted08 = ISNULL(gls.TargetDollarsPerUOSAdjusted08, 0), + gl.TargetDollarsPerUOSAdjusted09 = ISNULL(gls.TargetDollarsPerUOSAdjusted09, 0), + gl.TargetDollarsPerUOSAdjusted10 = ISNULL(gls.TargetDollarsPerUOSAdjusted10, 0), + gl.TargetDollarsPerUOSAdjusted11 = ISNULL(gls.TargetDollarsPerUOSAdjusted11, 0), + gl.TargetDollarsPerUOSAdjusted12 = ISNULL(gls.TargetDollarsPerUOSAdjusted12, 0), + + gl.BudgetDollarsPerUOSAdjusted01 = ISNULL(gls.BudgetDollarsPerUOSAdjusted01, 0), + gl.BudgetDollarsPerUOSAdjusted02 = ISNULL(gls.BudgetDollarsPerUOSAdjusted02, 0), + gl.BudgetDollarsPerUOSAdjusted03 = ISNULL(gls.BudgetDollarsPerUOSAdjusted03, 0), + gl.BudgetDollarsPerUOSAdjusted04 = ISNULL(gls.BudgetDollarsPerUOSAdjusted04, 0), + gl.BudgetDollarsPerUOSAdjusted05 = ISNULL(gls.BudgetDollarsPerUOSAdjusted05, 0), + gl.BudgetDollarsPerUOSAdjusted06 = ISNULL(gls.BudgetDollarsPerUOSAdjusted06, 0), + gl.BudgetDollarsPerUOSAdjusted07 = ISNULL(gls.BudgetDollarsPerUOSAdjusted07, 0), + gl.BudgetDollarsPerUOSAdjusted08 = ISNULL(gls.BudgetDollarsPerUOSAdjusted08, 0), + gl.BudgetDollarsPerUOSAdjusted09 = ISNULL(gls.BudgetDollarsPerUOSAdjusted09, 0), + gl.BudgetDollarsPerUOSAdjusted10 = ISNULL(gls.BudgetDollarsPerUOSAdjusted10, 0), + gl.BudgetDollarsPerUOSAdjusted11 = ISNULL(gls.BudgetDollarsPerUOSAdjusted11, 0), + gl.BudgetDollarsPerUOSAdjusted12 = ISNULL(gls.BudgetDollarsPerUOSAdjusted12, 0), + + gl.ProjectionDollarsPerUOSAdjusted01 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted01, 0), + gl.ProjectionDollarsPerUOSAdjusted02 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted02, 0), + gl.ProjectionDollarsPerUOSAdjusted03 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted03, 0), + gl.ProjectionDollarsPerUOSAdjusted04 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted04, 0), + gl.ProjectionDollarsPerUOSAdjusted05 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted05, 0), + gl.ProjectionDollarsPerUOSAdjusted06 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted06, 0), + gl.ProjectionDollarsPerUOSAdjusted07 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted07, 0), + gl.ProjectionDollarsPerUOSAdjusted08 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted08, 0), + gl.ProjectionDollarsPerUOSAdjusted09 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted09, 0), + gl.ProjectionDollarsPerUOSAdjusted10 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted10, 0), + gl.ProjectionDollarsPerUOSAdjusted11 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted11, 0), + gl.ProjectionDollarsPerUOSAdjusted12 = ISNULL(gls.ProjectionDollarsPerUOSAdjusted12, 0), + + gl.TargetPercentOfChargeAdjusted01 = ISNULL(gls.TargetPercentOfChargeAdjusted01, 0), + gl.TargetPercentOfChargeAdjusted02 = ISNULL(gls.TargetPercentOfChargeAdjusted02, 0), + gl.TargetPercentOfChargeAdjusted03 = ISNULL(gls.TargetPercentOfChargeAdjusted03, 0), + gl.TargetPercentOfChargeAdjusted04 = ISNULL(gls.TargetPercentOfChargeAdjusted04, 0), + gl.TargetPercentOfChargeAdjusted05 = ISNULL(gls.TargetPercentOfChargeAdjusted05, 0), + gl.TargetPercentOfChargeAdjusted06 = ISNULL(gls.TargetPercentOfChargeAdjusted06, 0), + gl.TargetPercentOfChargeAdjusted07 = ISNULL(gls.TargetPercentOfChargeAdjusted07, 0), + gl.TargetPercentOfChargeAdjusted08 = ISNULL(gls.TargetPercentOfChargeAdjusted08, 0), + gl.TargetPercentOfChargeAdjusted09 = ISNULL(gls.TargetPercentOfChargeAdjusted09, 0), + gl.TargetPercentOfChargeAdjusted10 = ISNULL(gls.TargetPercentOfChargeAdjusted10, 0), + gl.TargetPercentOfChargeAdjusted11 = ISNULL(gls.TargetPercentOfChargeAdjusted11, 0), + gl.TargetPercentOfChargeAdjusted12 = ISNULL(gls.TargetPercentOfChargeAdjusted12, 0), + + gl.BudgetPercentOfChargeAdjusted01 = ISNULL(gls.BudgetPercentOfChargeAdjusted01, 0), + gl.BudgetPercentOfChargeAdjusted02 = ISNULL(gls.BudgetPercentOfChargeAdjusted02, 0), + gl.BudgetPercentOfChargeAdjusted03 = ISNULL(gls.BudgetPercentOfChargeAdjusted03, 0), + gl.BudgetPercentOfChargeAdjusted04 = ISNULL(gls.BudgetPercentOfChargeAdjusted04, 0), + gl.BudgetPercentOfChargeAdjusted05 = ISNULL(gls.BudgetPercentOfChargeAdjusted05, 0), + gl.BudgetPercentOfChargeAdjusted06 = ISNULL(gls.BudgetPercentOfChargeAdjusted06, 0), + gl.BudgetPercentOfChargeAdjusted07 = ISNULL(gls.BudgetPercentOfChargeAdjusted07, 0), + gl.BudgetPercentOfChargeAdjusted08 = ISNULL(gls.BudgetPercentOfChargeAdjusted08, 0), + gl.BudgetPercentOfChargeAdjusted09 = ISNULL(gls.BudgetPercentOfChargeAdjusted09, 0), + gl.BudgetPercentOfChargeAdjusted10 = ISNULL(gls.BudgetPercentOfChargeAdjusted10, 0), + gl.BudgetPercentOfChargeAdjusted11 = ISNULL(gls.BudgetPercentOfChargeAdjusted11, 0), + gl.BudgetPercentOfChargeAdjusted12 = ISNULL(gls.BudgetPercentOfChargeAdjusted12, 0), + + gl.ProjectionPercentOfChargeAdjusted01 = ISNULL(gls.ProjectionPercentOfChargeAdjusted01, 0), + gl.ProjectionPercentOfChargeAdjusted02 = ISNULL(gls.ProjectionPercentOfChargeAdjusted02, 0), + gl.ProjectionPercentOfChargeAdjusted03 = ISNULL(gls.ProjectionPercentOfChargeAdjusted03, 0), + gl.ProjectionPercentOfChargeAdjusted04 = ISNULL(gls.ProjectionPercentOfChargeAdjusted04, 0), + gl.ProjectionPercentOfChargeAdjusted05 = ISNULL(gls.ProjectionPercentOfChargeAdjusted05, 0), + gl.ProjectionPercentOfChargeAdjusted06 = ISNULL(gls.ProjectionPercentOfChargeAdjusted06, 0), + gl.ProjectionPercentOfChargeAdjusted07 = ISNULL(gls.ProjectionPercentOfChargeAdjusted07, 0), + gl.ProjectionPercentOfChargeAdjusted08 = ISNULL(gls.ProjectionPercentOfChargeAdjusted08, 0), + gl.ProjectionPercentOfChargeAdjusted09 = ISNULL(gls.ProjectionPercentOfChargeAdjusted09, 0), + gl.ProjectionPercentOfChargeAdjusted10 = ISNULL(gls.ProjectionPercentOfChargeAdjusted10, 0), + gl.ProjectionPercentOfChargeAdjusted11 = ISNULL(gls.ProjectionPercentOfChargeAdjusted11, 0), + gl.ProjectionPercentOfChargeAdjusted12 = ISNULL(gls.ProjectionPercentOfChargeAdjusted12, 0), + + gl.TargetLockType = ISNULL(gls.TargetLockType, 0), + gl.TargetLockFlag = ISNULL(gls.TargetLockFlag, 0), + gl.BudgetLockType = ISNULL(gls.BudgetLockType, 0), + gl.BudgetLockFlag = ISNULL(gls.BudgetLockFlag, 0), + gl.ProjectionLockType = ISNULL(gls.ProjectionLockType, 0), + gl.ProjectionLockFlag = ISNULL(gls.ProjectionLockFlag, 0) + FROM + [fp].[GeneralLedger] gl + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = gl.DepartmentID + -- Need to be a LEFT JOIN to handle cases where there was something new added. In this case, it's new + -- and would be 0, until adjusted later in the process. + LEFT JOIN [fp].[GeneralLedgerSnapshot] gls ON gl.GeneralLedgerID = gls.GeneralLedgerID + WHERE gl.EntityGroupConfigID = @EntityGroupConfigID + AND gls.SnapshotID = @SnapshotID +END +GO + + +--------------------------------------------- + +-- fp.procResetInitialBenefitsFromSampled +/************************************************************** +** Change History +************************************************************** +** 1 2019-03-08 IP B-22295 Removed using table variables, small optimizations +** 2 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table +** 3 2019-06-03 PA D-08525 Updates to ensure query optimizer doesn't timeout +*************************************************************/ +CREATE PROCEDURE [fp].[procResetInitialBenefitsFromSampled] + @EntityGroupConfigID INT, + @MonthsLoaded INT, + @UnitTypeIds dbo.SqlInt32ListTableType READONLY, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +WITH RECOMPILE +AS +BEGIN + DECLARE @BudgetConfigID INT = ( + SELECT TOP 1 BudgetConfigID + FROM fp.BudgetConfig + WHERE BudgetConfigGUID = ( + SELECT BudgetConfigGUID + FROM fp.EntityGroupConfig + WHERE EntityGroupConfigID = @EntityGroupConfigID)) + + CREATE TABLE #UnitTypeIds (Value INT PRIMARY KEY CLUSTERED) + INSERT INTO #UnitTypeIds (VALUE) + SELECT Value from @UnitTypeIds + + CREATE TABLE #FilterByDepartment (DepartmentID INT) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + +;WITH spreadBudget AS ( + SELECT + BenefitsID, + SampledBudgetTotal / 12 AS InitialBudget01, + SampledBudgetTotal / 12 AS InitialBudget02, + SampledBudgetTotal / 12 AS InitialBudget03, + SampledBudgetTotal / 12 AS InitialBudget04, + SampledBudgetTotal / 12 AS InitialBudget05, + SampledBudgetTotal / 12 AS InitialBudget06, + SampledBudgetTotal / 12 AS InitialBudget07, + SampledBudgetTotal / 12 AS InitialBudget08, + SampledBudgetTotal / 12 AS InitialBudget09, + SampledBudgetTotal / 12 AS InitialBudget10, + SampledBudgetTotal / 12 AS InitialBudget11, + SampledBudgetTotal - (SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12) AS InitialBudget12 + FROM [fp].[FactBenefits] tbl + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = tbl.DepartmentID or ft.DepartmentID is null) + WHERE + BudgetConfigID = @BudgetConfigID + AND EntityGroupConfigID = @EntityGroupConfigID + AND UnitTypeID IN (SELECT value FROM #UnitTypeIds) + + ),Totals as ( + SELECT *, NewValue = SampledProjectionTotal / (12.0 - @MonthsLoaded) FROM ( + SELECT BenefitsID, + CASE WHEN @MonthsLoaded = 11 THEN ben.SampledProjection12 + WHEN @MonthsLoaded = 10 THEN ben.SampledProjection11 + ben.SampledProjection12 + WHEN @MonthsLoaded = 9 THEN ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12 + WHEN @MonthsLoaded = 8 THEN ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12 + WHEN @MonthsLoaded = 7 THEN ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12 + WHEN @MonthsLoaded = 6 THEN ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12 + WHEN @MonthsLoaded = 5 THEN ben.SampledProjection06 + ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12 + WHEN @MonthsLoaded = 4 THEN ben.SampledProjection05 + ben.SampledProjection06 + ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12 + WHEN @MonthsLoaded = 3 THEN ben.SampledProjection04 + ben.SampledProjection05 + ben.SampledProjection06 + ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12 + WHEN @MonthsLoaded = 2 THEN ben.SampledProjection03 + ben.SampledProjection04 + ben.SampledProjection05 + ben.SampledProjection06 + ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12 + WHEN @MonthsLoaded = 1 THEN ben.SampledProjection02 + ben.SampledProjection03 + ben.SampledProjection04 + ben.SampledProjection05 + ben.SampledProjection06 + ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12 + ELSE 0 + END as SampledProjectionTotal + FROM [fp].[FactBenefits] ben + WHERE + ben.BudgetConfigID = @BudgetConfigID + AND ben.EntityGroupConfigID = @EntityGroupConfigID + AND ben.UnitTypeID = 34 + )x ) + + UPDATE + ben + SET + InitialProjection01 = CASE WHEN @MonthsLoaded >= 1 THEN ben.SampledProjection01 ELSE t.NewValue END, + InitialProjection02 = CASE WHEN @MonthsLoaded >= 2 THEN ben.SampledProjection02 ELSE t.NewValue END, + InitialProjection03 = CASE WHEN @MonthsLoaded >= 3 THEN ben.SampledProjection03 ELSE t.NewValue END, + InitialProjection04 = CASE WHEN @MonthsLoaded >= 4 THEN ben.SampledProjection04 ELSE t.NewValue END, + InitialProjection05 = CASE WHEN @MonthsLoaded >= 5 THEN ben.SampledProjection05 ELSE t.NewValue END, + InitialProjection06 = CASE WHEN @MonthsLoaded >= 6 THEN ben.SampledProjection06 ELSE t.NewValue END, + InitialProjection07 = CASE WHEN @MonthsLoaded >= 7 THEN ben.SampledProjection07 ELSE t.NewValue END, + InitialProjection08 = CASE WHEN @MonthsLoaded >= 8 THEN ben.SampledProjection08 ELSE t.NewValue END, + InitialProjection09 = CASE WHEN @MonthsLoaded >= 9 THEN ben.SampledProjection09 ELSE t.NewValue END, + InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN ben.SampledProjection10 ELSE t.NewValue END, + InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN ben.SampledProjection11 ELSE t.NewValue END, + InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN ben.SampledProjection12 ELSE t.NewValue END, + InitialBudget01 = bdgt.InitialBudget01, + InitialBudget02 = bdgt.InitialBudget02, + InitialBudget03 = bdgt.InitialBudget03, + InitialBudget04 = bdgt.InitialBudget04, + InitialBudget05 = bdgt.InitialBudget05, + InitialBudget06 = bdgt.InitialBudget06, + InitialBudget07 = bdgt.InitialBudget07, + InitialBudget08 = bdgt.InitialBudget08, + InitialBudget09 = bdgt.InitialBudget09, + InitialBudget10 = bdgt.InitialBudget10, + InitialBudget11 = bdgt.InitialBudget11, + InitialBudget12 = bdgt.InitialBudget12 + FROM [fp].[FactBenefits] ben + INNER JOIN Totals t on ben.BenefitsID = t.BenefitsID + INNER JOIN spreadBudget bdgt ON ben.BenefitsID = bdgt.BenefitsID + WHERE + ben.BudgetConfigID = @BudgetConfigID + AND ben.EntityGroupConfigID = @EntityGroupConfigID +END +GO + + +--------------------------------------------- + +-- fp.procResetProjectionValuesForRoster +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 03-27-2023 MY JAZZ-51328 Initial +** 2 01-03-2023 MY JAZZ-63564 Final Pass Of Fact References (SQL) +*************************************************************/ +CREATE PROC [fp].[procResetProjectionValuesForRoster] + @EntityGroupConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + + DECLARE @BudgetConfigGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM fp.EntityGroupConfig WHERE EntityGroupConfigID = @EntityGroupConfigID) + DECLARE @IsFTEHidden BIT = (SELECT IsFTEHidden FROM [fp].[BudgetConfig] WHERE BudgetConfigGUID = @BudgetConfigGUID) + + EXEC dbo.procSysDropTempTable '#Filter' + EXEC dbo.procSysDropTempTable '#entityFilter' + EXEC dbo.procSysDropTempTable '#rosterDimensionality' + EXEC dbo.procSysDropTempTable '#factStaffingRolledUp' + + -- Load up the entities for the selected entity group so we only process what is needed + SELECT EntityID + INTO #entityFilter + FROM fp.EntityGroupConfigMapping egcm + INNER JOIN fp.EntityGroupConfig egc ON egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE egc.EntityGroupConfigID = @EntityGroupConfigID + + -- Pull the departments from the targeting filter, but then only load up the entities for the given EGC. + -- This is unique because we don't have EGC or that concept in roster so rather than passing in 2 different filters. + SELECT DISTINCT tgt.DepartmentID + INTO #Filter + FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) tgt + INNER JOIN [fw].[DimDepartment] dept WITH (READUNCOMMITTED) ON tgt.DepartmentID = dept.DepartmentID + INNER JOIN #entityFilter ent ON dept.EntityID = ent.EntityID + + IF NOT EXISTS(SELECT 1 FROM #Filter WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #Filter (DepartmentID) + SELECT DISTINCT rbbr.DepartmentID + FROM [fp].[RosterBudgetBasisResult] rbbr + INNER JOIN [fw].[DimDepartment] dept WITH (READUNCOMMITTED) ON rbbr.DepartmentID = dept.DepartmentID + INNER JOIN #entityFilter ent ON dept.EntityID = ent.EntityID + WHERE BudgetConfigGUID = @BudgetConfigGUID + END + + -- Note: When transfering roster to Staffing, we don't include EmployeeID + SELECT DISTINCT + dept.EntityID, + rb.DepartmentID, + rb.JobCodeID, + rb.PayCodeGroupID + INTO #rosterDimensionality + FROM [fp].[RosterBudgetBasisResult] rb + INNER JOIN [fp].[BudgetConfig] bc WITH (READUNCOMMITTED) ON bc.BudgetConfigGUID = rb.BudgetConfigGUID + INNER JOIN [fw].[DimDepartment] dept WITH (READUNCOMMITTED) ON rb.DepartmentID = dept.DepartmentID + INNER JOIN #Filter Filter ON dept.DepartmentID = Filter.DepartmentID + WHERE 1=1 + AND rb.BudgetConfigGUID = @BudgetConfigGUID + + -- Pull out the staffing data for sampled projection data above variability, we'll put anything coming from roster as 100% fixed. + SELECT + fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + SUM(fs.SampledProjectionDollars01) AS SampledProjectionDollars01, + SUM(fs.SampledProjectionDollars02) AS SampledProjectionDollars02, + SUM(fs.SampledProjectionDollars03) AS SampledProjectionDollars03, + SUM(fs.SampledProjectionDollars04) AS SampledProjectionDollars04, + SUM(fs.SampledProjectionDollars05) AS SampledProjectionDollars05, + SUM(fs.SampledProjectionDollars06) AS SampledProjectionDollars06, + SUM(fs.SampledProjectionDollars07) AS SampledProjectionDollars07, + SUM(fs.SampledProjectionDollars08) AS SampledProjectionDollars08, + SUM(fs.SampledProjectionDollars09) AS SampledProjectionDollars09, + SUM(fs.SampledProjectionDollars10) AS SampledProjectionDollars10, + SUM(fs.SampledProjectionDollars11) AS SampledProjectionDollars11, + SUM(fs.SampledProjectionDollars12) AS SampledProjectionDollars12, + SUM(fs.SampledProjectionHours01) AS SampledProjectionHours01, + SUM(fs.SampledProjectionHours02) AS SampledProjectionHours02, + SUM(fs.SampledProjectionHours03) AS SampledProjectionHours03, + SUM(fs.SampledProjectionHours04) AS SampledProjectionHours04, + SUM(fs.SampledProjectionHours05) AS SampledProjectionHours05, + SUM(fs.SampledProjectionHours06) AS SampledProjectionHours06, + SUM(fs.SampledProjectionHours07) AS SampledProjectionHours07, + SUM(fs.SampledProjectionHours08) AS SampledProjectionHours08, + SUM(fs.SampledProjectionHours09) AS SampledProjectionHours09, + SUM(fs.SampledProjectionHours10) AS SampledProjectionHours10, + SUM(fs.SampledProjectionHours11) AS SampledProjectionHours11, + SUM(fs.SampledProjectionHours12) AS SampledProjectionHours12, + SUM(fs.SampledProjectionFTEs01) AS SampledProjectionFTEs01, + SUM(fs.SampledProjectionFTEs02) AS SampledProjectionFTEs02, + SUM(fs.SampledProjectionFTEs03) AS SampledProjectionFTEs03, + SUM(fs.SampledProjectionFTEs04) AS SampledProjectionFTEs04, + SUM(fs.SampledProjectionFTEs05) AS SampledProjectionFTEs05, + SUM(fs.SampledProjectionFTEs06) AS SampledProjectionFTEs06, + SUM(fs.SampledProjectionFTEs07) AS SampledProjectionFTEs07, + SUM(fs.SampledProjectionFTEs08) AS SampledProjectionFTEs08, + SUM(fs.SampledProjectionFTEs09) AS SampledProjectionFTEs09, + SUM(fs.SampledProjectionFTEs10) AS SampledProjectionFTEs10, + SUM(fs.SampledProjectionFTEs11) AS SampledProjectionFTEs11, + SUM(fs.SampledProjectionFTEs12) AS SampledProjectionFTEs12 + INTO #factStaffingRolledUp + FROM fp.Staffing fs + INNER JOIN #rosterDimensionality roster ON roster.EntityID = fs.EntityID + AND roster.DepartmentID = fs.DepartmentID + AND roster.JobCodeID = fs.JobCodeID + AND roster.PayCodeGroupID = fs.PayCodeGroupID + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND fs.SubsectionID = 3 -- Staffing + GROUP BY fs.EntityID, + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID + + IF (@IsDebug = 1) + BEGIN + + SELECT @BudgetConfigGUID AS '@BudgetConfigGUID', @IsFTEHidden AS '@IsFTEHidden' + SELECT '#Filter' AS '#Filter', * FROM #Filter + SELECT '#entityFilter' AS '#entityFilter', * FROM #entityFilter + SELECT '#rosterDimensionality' AS '#rosterDimensionality', * FROM #rosterDimensionality + SELECT '#factStaffingRolledUp' AS '#factStaffingRolledUp', * FROM #factStaffingRolledUp + + END ELSE + BEGIN + + -- Roster only gets loaded into Fixed so we need to 0 out all of Variable + UPDATE fs + SET + fs.InitialProjectionDollars01 = 0, + fs.InitialProjectionDollars02 = 0, + fs.InitialProjectionDollars03 = 0, + fs.InitialProjectionDollars04 = 0, + fs.InitialProjectionDollars05 = 0, + fs.InitialProjectionDollars06 = 0, + fs.InitialProjectionDollars07 = 0, + fs.InitialProjectionDollars08 = 0, + fs.InitialProjectionDollars09 = 0, + fs.InitialProjectionDollars10 = 0, + fs.InitialProjectionDollars11 = 0, + fs.InitialProjectionDollars12 = 0, + fs.InitialProjectionHours01 = 0, + fs.InitialProjectionHours02 = 0, + fs.InitialProjectionHours03 = 0, + fs.InitialProjectionHours04 = 0, + fs.InitialProjectionHours05 = 0, + fs.InitialProjectionHours06 = 0, + fs.InitialProjectionHours07 = 0, + fs.InitialProjectionHours08 = 0, + fs.InitialProjectionHours09 = 0, + fs.InitialProjectionHours10 = 0, + fs.InitialProjectionHours11 = 0, + fs.InitialProjectionHours12 = 0 + FROM fp.Staffing fs + INNER JOIN #factStaffingRolledUp roll ON fs.EntityID = roll.EntityID + AND fs.DepartmentID = roll.DepartmentID + AND fs.JobCodeID = roll.JobCodeID + AND fs.PayCodeGroupID = roll.PayCodeGroupID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.SubsectionID = 3 -- Staffing + AND fs.VariabilityID = 2 -- Roster only gets loaded into Fixed + + -- Update FactStaffing to set InitialProjection for all Unit Types + IF (@IsFTEHidden = 1) + BEGIN + UPDATE fs + SET + fs.InitialProjectionDollars01 = roll.SampledProjectionDollars01, + fs.InitialProjectionDollars02 = roll.SampledProjectionDollars02, + fs.InitialProjectionDollars03 = roll.SampledProjectionDollars03, + fs.InitialProjectionDollars04 = roll.SampledProjectionDollars04, + fs.InitialProjectionDollars05 = roll.SampledProjectionDollars05, + fs.InitialProjectionDollars06 = roll.SampledProjectionDollars06, + fs.InitialProjectionDollars07 = roll.SampledProjectionDollars07, + fs.InitialProjectionDollars08 = roll.SampledProjectionDollars08, + fs.InitialProjectionDollars09 = roll.SampledProjectionDollars09, + fs.InitialProjectionDollars10 = roll.SampledProjectionDollars10, + fs.InitialProjectionDollars11 = roll.SampledProjectionDollars11, + fs.InitialProjectionDollars12 = roll.SampledProjectionDollars12 + FROM fp.Staffing fs + INNER JOIN #factStaffingRolledUp roll ON fs.EntityID = roll.EntityID + AND fs.DepartmentID = roll.DepartmentID + AND fs.JobCodeID = roll.JobCodeID + AND fs.PayCodeGroupID = roll.PayCodeGroupID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.SubsectionID = 3 -- Staffing + AND fs.VariabilityID = 1 -- Roster only gets loaded into Fixed + END ELSE BEGIN + + UPDATE fs + SET + fs.InitialProjectionDollars01 = roll.SampledProjectionDollars01, + fs.InitialProjectionDollars02 = roll.SampledProjectionDollars02, + fs.InitialProjectionDollars03 = roll.SampledProjectionDollars03, + fs.InitialProjectionDollars04 = roll.SampledProjectionDollars04, + fs.InitialProjectionDollars05 = roll.SampledProjectionDollars05, + fs.InitialProjectionDollars06 = roll.SampledProjectionDollars06, + fs.InitialProjectionDollars07 = roll.SampledProjectionDollars07, + fs.InitialProjectionDollars08 = roll.SampledProjectionDollars08, + fs.InitialProjectionDollars09 = roll.SampledProjectionDollars09, + fs.InitialProjectionDollars10 = roll.SampledProjectionDollars10, + fs.InitialProjectionDollars11 = roll.SampledProjectionDollars11, + fs.InitialProjectionDollars12 = roll.SampledProjectionDollars12, + fs.InitialProjectionHours01 = roll.SampledProjectionHours01, + fs.InitialProjectionHours02 = roll.SampledProjectionHours02, + fs.InitialProjectionHours03 = roll.SampledProjectionHours03, + fs.InitialProjectionHours04 = roll.SampledProjectionHours04, + fs.InitialProjectionHours05 = roll.SampledProjectionHours05, + fs.InitialProjectionHours06 = roll.SampledProjectionHours06, + fs.InitialProjectionHours07 = roll.SampledProjectionHours07, + fs.InitialProjectionHours08 = roll.SampledProjectionHours08, + fs.InitialProjectionHours09 = roll.SampledProjectionHours09, + fs.InitialProjectionHours10 = roll.SampledProjectionHours10, + fs.InitialProjectionHours11 = roll.SampledProjectionHours11, + fs.InitialProjectionHours12 = roll.SampledProjectionHours12, + fs.InitialProjectionFTEs01 = roll.SampledProjectionFTEs01, + fs.InitialProjectionFTEs02 = roll.SampledProjectionFTEs02, + fs.InitialProjectionFTEs03 = roll.SampledProjectionFTEs03, + fs.InitialProjectionFTEs04 = roll.SampledProjectionFTEs04, + fs.InitialProjectionFTEs05 = roll.SampledProjectionFTEs05, + fs.InitialProjectionFTEs06 = roll.SampledProjectionFTEs06, + fs.InitialProjectionFTEs07 = roll.SampledProjectionFTEs07, + fs.InitialProjectionFTEs08 = roll.SampledProjectionFTEs08, + fs.InitialProjectionFTEs09 = roll.SampledProjectionFTEs09, + fs.InitialProjectionFTEs10 = roll.SampledProjectionFTEs10, + fs.InitialProjectionFTEs11 = roll.SampledProjectionFTEs11, + fs.InitialProjectionFTEs12 = roll.SampledProjectionFTEs12 + FROM fp.Staffing fs + INNER JOIN #factStaffingRolledUp roll ON fs.EntityID = roll.EntityID + AND fs.DepartmentID = roll.DepartmentID + AND fs.JobCodeID = roll.JobCodeID + AND fs.PayCodeGroupID = roll.PayCodeGroupID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.SubsectionID = 3 -- Staffing + AND fs.VariabilityID = 1 -- Roster only gets loaded into Fixed + + END + + UPDATE swr + SET + swr.InitialProjection01 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars01 / NULLIF(roll.SampledProjectionHours01, 0), 0) END, + swr.InitialProjection02 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars02 / NULLIF(roll.SampledProjectionHours02, 0), 0) END, + swr.InitialProjection03 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars03 / NULLIF(roll.SampledProjectionHours03, 0), 0) END, + swr.InitialProjection04 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars04 / NULLIF(roll.SampledProjectionHours04, 0), 0) END, + swr.InitialProjection05 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars05 / NULLIF(roll.SampledProjectionHours05, 0), 0) END, + swr.InitialProjection06 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars06 / NULLIF(roll.SampledProjectionHours06, 0), 0) END, + swr.InitialProjection07 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars07 / NULLIF(roll.SampledProjectionHours07, 0), 0) END, + swr.InitialProjection08 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars08 / NULLIF(roll.SampledProjectionHours08, 0), 0) END, + swr.InitialProjection09 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars09 / NULLIF(roll.SampledProjectionHours09, 0), 0) END, + swr.InitialProjection10 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars10 / NULLIF(roll.SampledProjectionHours10, 0), 0) END, + swr.InitialProjection11 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars11 / NULLIF(roll.SampledProjectionHours11, 0), 0) END, + swr.InitialProjection12 = CASE WHEN @IsFTEHidden = 1 THEN 0 ELSE ISNULL(roll.SampledProjectionDollars12 / NULLIF(roll.SampledProjectionHours12, 0), 0) END + FROM fp.StaffingWageRate swr + INNER JOIN fp.Staffing fs ON fs.StaffingWageRateID = swr.StaffingWageRateID + INNER JOIN #factStaffingRolledUp roll ON fs.EntityID = roll.EntityID + AND fs.DepartmentID = roll.DepartmentID + AND fs.JobCodeID = roll.JobCodeID + AND fs.PayCodeGroupID = roll.PayCodeGroupID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.SubsectionID = 3 -- Staffing + END +END +GO + + +--------------------------------------------- + +-- fp.procResetReimbursementGeneralLedger +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-03-08 VZ JAZZ-57724 Initial +*************************************************************/ +CREATE PROCEDURE [fp].[procResetReimbursementGeneralLedger] + @EntityGroupConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + CREATE TABLE #FilteringTable ( + EntityID INT, + INDEX ix_1 NONCLUSTERED (EntityID) + ) + + INSERT INTO #FilteringTable (EntityID) + SELECT src.EntityID + FROM @SourceDimensionality src + INNER JOIN fw.DimDepartment dept ON src.DepartmentID = dept.DepartmentID + UNION + SELECT d.EntityID + FROM fw.DimDepartment d + INNER JOIN @SourceDimensionality sd + ON sd.EntityID = d.EntityID + WHERE sd.DepartmentID IS NULL -- filter rows, where particular DepartmentID is set as specification of EntityID + + DECLARE @isFilterPresent int = (SELECT COUNT(*) FROM #FilteringTable) + + if(@isFilterPresent = 0) + INSERT INTO #FilteringTable (EntityID) VALUES (NULL) + + UPDATE tbl + SET + tbl.BudgetAdjustedNetAsPercentOfCharge01 = tbl.InitialBudgetNetAsPercentOfCharge01, tbl.BudgetAdjustedNetAsPercentOfCharge02 = tbl.InitialBudgetNetAsPercentOfCharge02, tbl.BudgetAdjustedNetAsPercentOfCharge03 = tbl.InitialBudgetNetAsPercentOfCharge03, + tbl.BudgetAdjustedNetAsPercentOfCharge04 = tbl.InitialBudgetNetAsPercentOfCharge04, tbl.BudgetAdjustedNetAsPercentOfCharge05 = tbl.InitialBudgetNetAsPercentOfCharge05, tbl.BudgetAdjustedNetAsPercentOfCharge06 = tbl.InitialBudgetNetAsPercentOfCharge06, + tbl.BudgetAdjustedNetAsPercentOfCharge07 = tbl.InitialBudgetNetAsPercentOfCharge07, tbl.BudgetAdjustedNetAsPercentOfCharge08 = tbl.InitialBudgetNetAsPercentOfCharge08, tbl.BudgetAdjustedNetAsPercentOfCharge09 = tbl.InitialBudgetNetAsPercentOfCharge09, + tbl.BudgetAdjustedNetAsPercentOfCharge10 = tbl.InitialBudgetNetAsPercentOfCharge10, tbl.BudgetAdjustedNetAsPercentOfCharge11 = tbl.InitialBudgetNetAsPercentOfCharge11, tbl.BudgetAdjustedNetAsPercentOfCharge12 = tbl.InitialBudgetNetAsPercentOfCharge12, + + tbl.TargetAdjustedNetAsPercentOfCharge01 = tbl.InitialBudgetNetAsPercentOfCharge01, tbl.TargetAdjustedNetAsPercentOfCharge02 = tbl.InitialBudgetNetAsPercentOfCharge02, tbl.TargetAdjustedNetAsPercentOfCharge03 = tbl.InitialBudgetNetAsPercentOfCharge03, + tbl.TargetAdjustedNetAsPercentOfCharge04 = tbl.InitialBudgetNetAsPercentOfCharge04, tbl.TargetAdjustedNetAsPercentOfCharge05 = tbl.InitialBudgetNetAsPercentOfCharge05, tbl.TargetAdjustedNetAsPercentOfCharge06 = tbl.InitialBudgetNetAsPercentOfCharge06, + tbl.TargetAdjustedNetAsPercentOfCharge07 = tbl.InitialBudgetNetAsPercentOfCharge07, tbl.TargetAdjustedNetAsPercentOfCharge08 = tbl.InitialBudgetNetAsPercentOfCharge08, tbl.TargetAdjustedNetAsPercentOfCharge09 = tbl.InitialBudgetNetAsPercentOfCharge09, + tbl.TargetAdjustedNetAsPercentOfCharge10 = tbl.InitialBudgetNetAsPercentOfCharge10, tbl.TargetAdjustedNetAsPercentOfCharge11 = tbl.InitialBudgetNetAsPercentOfCharge11, tbl.TargetAdjustedNetAsPercentOfCharge12 = tbl.InitialBudgetNetAsPercentOfCharge12, + + tbl.ProjectionAdjustedNetAsPercentOfCharge01 = tbl.InitialProjectionNetAsPercentOfCharge01, tbl.ProjectionAdjustedNetAsPercentOfCharge02 = tbl.InitialProjectionNetAsPercentOfCharge02, tbl.ProjectionAdjustedNetAsPercentOfCharge03 = tbl.InitialProjectionNetAsPercentOfCharge03, + tbl.ProjectionAdjustedNetAsPercentOfCharge04 = tbl.InitialProjectionNetAsPercentOfCharge04, tbl.ProjectionAdjustedNetAsPercentOfCharge05 = tbl.InitialProjectionNetAsPercentOfCharge05, tbl.ProjectionAdjustedNetAsPercentOfCharge06 = tbl.InitialProjectionNetAsPercentOfCharge06, + tbl.ProjectionAdjustedNetAsPercentOfCharge07 = tbl.InitialProjectionNetAsPercentOfCharge07, tbl.ProjectionAdjustedNetAsPercentOfCharge08 = tbl.InitialProjectionNetAsPercentOfCharge08, tbl.ProjectionAdjustedNetAsPercentOfCharge09 = tbl.InitialProjectionNetAsPercentOfCharge09, + tbl.ProjectionAdjustedNetAsPercentOfCharge10 = tbl.InitialProjectionNetAsPercentOfCharge10, tbl.ProjectionAdjustedNetAsPercentOfCharge11 = tbl.InitialProjectionNetAsPercentOfCharge11, tbl.ProjectionAdjustedNetAsPercentOfCharge12 = tbl.InitialProjectionNetAsPercentOfCharge12, + + tbl.BudgetLockType = 0, tbl.BudgetLockFlag = 0, + tbl.TargetLockType = 0, tbl.TargetLockFlag = 0, + tbl.ProjectionLockType = 0, tbl.ProjectionLockFlag = 0 + FROM [fp].[ReimbursementGeneralLedger] tbl + INNER JOIN #FilteringTable ft on (@isFilterPresent = 0 OR ft.EntityID = tbl.EntityID) + WHERE tbl.EntityGroupConfigID = @EntityGroupConfigID +END +GO + + +--------------------------------------------- + +-- fp.procResetStatisticsManager +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2021-03-03 NN Jazz-466 Remove null joins on dept +*************************************************************/ +CREATE PROCEDURE [fp].[procResetStatisticsManager] + @BudgetConfigID int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + IF OBJECT_ID('tempdb..##tmpResetStatisticsItems') IS NOT NULL DROP TABLE #tmpResetStatisticsItems + + CREATE TABLE #tmpResetStatisticsItems (StatisticsID INT); + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[FactStatistics] WITH (READUNCOMMITTED) + WHERE BudgetConfigID = @BudgetConfigID + END + + + INSERT INTO #tmpResetStatisticsItems (StatisticsID) + SELECT StatisticsID + FROM [fp].[FactStatistics] data + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = data.DepartmentID + WHERE data.BudgetConfigID = @BudgetConfigID + + UPDATE mgr + SET + mgr.AdjustedValue01 = admin.AdjustedValue01, + mgr.AdjustedValue02 = admin.AdjustedValue02, + mgr.AdjustedValue03 = admin.AdjustedValue03, + mgr.AdjustedValue04 = admin.AdjustedValue04, + mgr.AdjustedValue05 = admin.AdjustedValue05, + mgr.AdjustedValue06 = admin.AdjustedValue06, + mgr.AdjustedValue07 = admin.AdjustedValue07, + mgr.AdjustedValue08 = admin.AdjustedValue08, + mgr.AdjustedValue09 = admin.AdjustedValue09, + mgr.AdjustedValue10 = admin.AdjustedValue10, + mgr.AdjustedValue11 = admin.AdjustedValue11, + mgr.AdjustedValue12 = admin.AdjustedValue12, + mgr.LockType = admin.LockType, + mgr.LockFlag = admin.LockFlag + FROM [fp].[FactStatisticsBudget] mgr + INNER JOIN [fp].[FactStatistics] fgl ON mgr.StatisticsID = fgl.StatisticsID + INNER JOIN [fp].[FactStatisticsBudget] admin ON admin.StatisticsID = mgr.StatisticsID + INNER JOIN #tmpResetStatisticsItems filter ON fgl.StatisticsID = filter.StatisticsID + WHERE fgl.BudgetConfigID = @BudgetConfigID + AND mgr.LockType <> 3 + AND admin.BudgetPhaseID = 2 + AND mgr.BudgetPhaseID = 3 + AND ( + mgr.AdjustedValue01 != admin.AdjustedValue01 OR + mgr.AdjustedValue02 != admin.AdjustedValue02 OR + mgr.AdjustedValue03 != admin.AdjustedValue03 OR + mgr.AdjustedValue04 != admin.AdjustedValue04 OR + mgr.AdjustedValue05 != admin.AdjustedValue05 OR + mgr.AdjustedValue06 != admin.AdjustedValue06 OR + mgr.AdjustedValue07 != admin.AdjustedValue07 OR + mgr.AdjustedValue08 != admin.AdjustedValue08 OR + mgr.AdjustedValue09 != admin.AdjustedValue09 OR + mgr.AdjustedValue10 != admin.AdjustedValue10 OR + mgr.AdjustedValue11 != admin.AdjustedValue11 OR + mgr.AdjustedValue12 != admin.AdjustedValue12) +END +GO + + +--------------------------------------------- + +-- fp.procResetVariablePatientActivityGLBudgetData +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-05-19 MY JAZZ-36661 Add Option Recompile to Inserts +** 2 2022-08-16 BW JAZZ-41928 Add reset logic for projection, put behind flag +** 3 2023-08-09 BW JAZZ-58199 Data model restructure for GL +*************************************************************/ +CREATE PROCEDURE [fp].[procResetVariablePatientActivityGLBudgetData] + @EntityGroupConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS + BEGIN + + CREATE TABLE #filterTable (GeneralLedgerID INT PRIMARY KEY CLUSTERED) + + DECLARE @IsProjectionFlexingEnabled bit + SELECT @IsProjectionFlexingEnabled = CAST(Value AS BIT) + FROM fp.SystemSetting + WHERE Name = 'Is Baseline And Projection PAF Enabled' + + IF EXISTS (SELECT 1 FROM @SourceDimensionality WHERE DepartmentID IS NOT NULL) + BEGIN + CREATE TABLE #filterByDepartment (DepartmentID INT PRIMARY KEY CLUSTERED) + + INSERT INTO #filterByDepartment (DepartmentID) + SELECT DepartmentID FROM [fp].[funcGetSourceDimensionalityAsTable](@SourceDimensionality) + + INSERT INTO #filterTable (GeneralLedgerID) + SELECT DISTINCT GeneralLedgerID + FROM [fp].[GeneralLedger] fgl + INNER JOIN #filterByDepartment filter ON fgl.DepartmentID = filter.DepartmentID + INNER JOIN [fp].[viewNonStaffingExpenseAccounts] acc ON fgl.AccountID = acc.AccountID -- Patient Activity Flexing for GL can only affect non-staffing accounts + INNER JOIN [fp].[BudgetedCostPerRVU_Sampled] rvu + ON fgl.BudgetConfigID = rvu.BudgetConfigID + AND fgl.DepartmentID = rvu.DepartmentID + AND fgl.AccountID = rvu.AccountID + INNER JOIN [fp].[EntityGroupConfig] egc ON fgl.EntityGroupConfigID = egc.EntityGroupConfigID + LEFT JOIN [fp].[FlexConfigMapping] map + ON fgl.DepartmentID = map.DepartmentID + AND fgl.AccountID = map.GLAccountID + AND fgl.EntityGroupConfigID = map.EntityGroupConfigID + LEFT JOIN [fp].[viewNonStaffingExpenseFlexingConfig] fc + ON fgl.DepartmentID = fc.DepartmentID + AND fgl.AccountID = fc.AccountID + AND fc.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + fgl.EntityGroupConfigID = @EntityGroupConfigID + AND fgl.VariabilityID = 2 + AND map.FlexingTypeID IS NULL + AND (fc.FlexMethodID != 6 OR fc.FlexMethodID IS NULL) + option (recompile) + + END + ELSE BEGIN + + INSERT INTO #filterTable (GeneralLedgerID) + SELECT DISTINCT GeneralLedgerID + FROM [fp].[GeneralLedger] fgl + INNER JOIN [fp].[viewNonStaffingExpenseAccounts] acc ON fgl.AccountID = acc.AccountID -- Patient Activity Flexing for GL can only affect non-staffing accounts + INNER JOIN [fp].[BudgetedCostPerRVU_Sampled] rvu + ON fgl.BudgetConfigID = rvu.BudgetConfigID + AND fgl.DepartmentID = rvu.DepartmentID + AND fgl.AccountID = rvu.AccountID + INNER JOIN [fp].[EntityGroupConfig] egc ON fgl.EntityGroupConfigID = egc.EntityGroupConfigID + LEFT JOIN [fp].[FlexConfigMapping] map + ON fgl.DepartmentID = map.DepartmentID + AND fgl.AccountID = map.GLAccountID + AND fgl.EntityGroupConfigID = map.EntityGroupConfigID + LEFT JOIN [fp].[viewNonStaffingExpenseFlexingConfig] fc + ON fgl.DepartmentID = fc.DepartmentID + AND fgl.AccountID = fc.AccountID + AND fc.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + fgl.EntityGroupConfigID = @EntityGroupConfigID + AND fgl.VariabilityID = 2 + AND map.FlexingTypeID IS NULL + AND (fc.FlexMethodID != 6 OR fc.FlexMethodID IS NULL) + option (recompile) + + END + + -- update the budget data + UPDATE gl + SET + [TargetAdjusted01] = [InitialBudget01], + [TargetAdjusted02] = [InitialBudget02], + [TargetAdjusted03] = [InitialBudget03], + [TargetAdjusted04] = [InitialBudget04], + [TargetAdjusted05] = [InitialBudget05], + [TargetAdjusted06] = [InitialBudget06], + [TargetAdjusted07] = [InitialBudget07], + [TargetAdjusted08] = [InitialBudget08], + [TargetAdjusted09] = [InitialBudget09], + [TargetAdjusted10] = [InitialBudget10], + [TargetAdjusted11] = [InitialBudget11], + [TargetAdjusted12] = [InitialBudget12] + FROM [fp].[GeneralLedger] gl + INNER JOIN #filterTable filter ON filter.GeneralLedgerID = gl.GeneralLedgerID + + IF(@IsProjectionFlexingEnabled = 1) + BEGIN + UPDATE gl + SET + [ProjectionAdjusted01] = [InitialProjection01], + [ProjectionAdjusted02] = [InitialProjection02], + [ProjectionAdjusted03] = [InitialProjection03], + [ProjectionAdjusted04] = [InitialProjection04], + [ProjectionAdjusted05] = [InitialProjection05], + [ProjectionAdjusted06] = [InitialProjection06], + [ProjectionAdjusted07] = [InitialProjection07], + [ProjectionAdjusted08] = [InitialProjection08], + [ProjectionAdjusted09] = [InitialProjection09], + [ProjectionAdjusted10] = [InitialProjection10], + [ProjectionAdjusted11] = [InitialProjection11], + [ProjectionAdjusted12] = [InitialProjection12] + FROM [fp].[GeneralLedger] gl + INNER JOIN #filterTable filter ON gl.GeneralLedgerID = filter.GeneralLedgerID + END + + END +GO + + +--------------------------------------------- + +-- fp.procResetVariablePatientActivityStaffingBudgetData +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-05-19 MY JAZZ-36661 Add Option Recompile to Inserts +** 2 2022-07-20 MD JAZZ-38981 Add reset logic for projection, put behind flag +** 3 2023-11-01 MY JAZZ-61705 Support PAF for the new data model - Staffing +*************************************************************/ +CREATE PROCEDURE [fp].[procResetVariablePatientActivityStaffingBudgetData] + @EntityGroupConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS + BEGIN + + CREATE TABLE #filterTable (StaffingID INT PRIMARY KEY CLUSTERED) + + DECLARE @IsProjectionFlexingEnabled bit + + SELECT @IsProjectionFlexingEnabled = CAST(Value AS BIT) + FROM fp.SystemSetting + WHERE Name = 'Is Baseline And Projection PAF Enabled' + + IF EXISTS (SELECT 1 FROM @SourceDimensionality WHERE DepartmentID IS NOT NULL) + BEGIN + + CREATE TABLE #filterByDepartment (DepartmentID INT PRIMARY KEY CLUSTERED) + + INSERT INTO #filterByDepartment (DepartmentID) + SELECT DepartmentID FROM [fp].[funcGetSourceDimensionalityAsTable](@SourceDimensionality) + + INSERT INTO #filterTable (StaffingID) + SELECT DISTINCT StaffingID + FROM [fp].[Staffing] fs + INNER JOIN #filterByDepartment filter ON fs.DepartmentID = filter.DepartmentID + INNER JOIN [fp].[BudgetedCostPerRVU_Sampled] rvu + ON fs.BudgetConfigID = rvu.BudgetConfigID + AND fs.DepartmentID = rvu.DepartmentID + AND fs.JobCodeID = rvu.JobCodeID + AND fs.PayCodeGroupID = rvu.PayCodeGroupID + AND 34 = rvu.UnitTypeID + INNER JOIN [fp].[EntityGroupConfig] egc ON fs.EntityGroupConfigID = egc.EntityGroupConfigID + LEFT JOIN [fp].[FlexConfigMapping] map + ON fs.DepartmentID = map.DepartmentID + AND fs.JobCodeID = map.PRJobCodeID + AND fs.EntityGroupConfigID = map.EntityGroupConfigID + LEFT JOIN ( + SELECT + EntityGroupConfigGUID, + DepartmentID, + JobCodeID, + FlexMethodID + FROM [fp].[viewStaffingExpenseFlexingConfig] fc) fc + ON fs.DepartmentID = fc.DepartmentID + AND fs.JobCodeID = fc.JobCodeID + AND fc.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE fs.VariabilityID = 2 + AND fs.EntityGroupConfigID = @EntityGroupConfigID + AND map.FlexingTypeID IS NULL + AND (fc.FlexMethodID != 6 OR fc.FlexMethodID IS NULL) + option (recompile) + + END + ELSE BEGIN + + INSERT INTO #filterTable (StaffingID) + SELECT DISTINCT StaffingID + FROM [fp].[Staffing] fs + INNER JOIN [fp].[BudgetedCostPerRVU_Sampled] rvu + ON fs.BudgetConfigID = rvu.BudgetConfigID + AND fs.DepartmentID = rvu.DepartmentID + AND fs.JobCodeID = rvu.JobCodeID + AND fs.PayCodeGroupID = rvu.PayCodeGroupID + AND 34 = rvu.UnitTypeID + INNER JOIN [fp].[EntityGroupConfig] egc ON fs.EntityGroupConfigID = egc.EntityGroupConfigID + LEFT JOIN [fp].[FlexConfigMapping] map + ON fs.DepartmentID = map.DepartmentID + AND fs.JobCodeID = map.PRJobCodeID + AND fs.EntityGroupConfigID = map.EntityGroupConfigID + LEFT JOIN ( + SELECT + EntityGroupConfigGUID, + DepartmentID, + JobCodeID, + FlexMethodID + FROM [fp].[viewStaffingExpenseFlexingConfig] fc) fc + ON fs.DepartmentID = fc.DepartmentID + AND fs.JobCodeID = fc.JobCodeID + AND fc.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE fs.VariabilityID = 2 + AND fs.EntityGroupConfigID = @EntityGroupConfigID + AND map.FlexingTypeID IS NULL + AND (fc.FlexMethodID != 6 OR fc.FlexMethodID IS NULL) + option (recompile) + + END + + IF(@IsProjectionFlexingEnabled = 1) + BEGIN + UPDATE fs + SET + [TargetAdjustedDollars01] = [InitialBudgetDollars01], + [TargetAdjustedDollars02] = [InitialBudgetDollars02], + [TargetAdjustedDollars03] = [InitialBudgetDollars03], + [TargetAdjustedDollars04] = [InitialBudgetDollars04], + [TargetAdjustedDollars05] = [InitialBudgetDollars05], + [TargetAdjustedDollars06] = [InitialBudgetDollars06], + [TargetAdjustedDollars07] = [InitialBudgetDollars07], + [TargetAdjustedDollars08] = [InitialBudgetDollars08], + [TargetAdjustedDollars09] = [InitialBudgetDollars09], + [TargetAdjustedDollars10] = [InitialBudgetDollars10], + [TargetAdjustedDollars11] = [InitialBudgetDollars11], + [TargetAdjustedDollars12] = [InitialBudgetDollars12], + [ProjectionAdjustedDollars01] = [InitialProjectionDollars01], + [ProjectionAdjustedDollars02] = [InitialProjectionDollars02], + [ProjectionAdjustedDollars03] = [InitialProjectionDollars03], + [ProjectionAdjustedDollars04] = [InitialProjectionDollars04], + [ProjectionAdjustedDollars05] = [InitialProjectionDollars05], + [ProjectionAdjustedDollars06] = [InitialProjectionDollars06], + [ProjectionAdjustedDollars07] = [InitialProjectionDollars07], + [ProjectionAdjustedDollars08] = [InitialProjectionDollars08], + [ProjectionAdjustedDollars09] = [InitialProjectionDollars09], + [ProjectionAdjustedDollars10] = [InitialProjectionDollars10], + [ProjectionAdjustedDollars11] = [InitialProjectionDollars11], + [ProjectionAdjustedDollars12] = [InitialProjectionDollars12] + FROM [fp].[Staffing] fs + INNER JOIN #filterTable filter ON fs.StaffingID = filter.StaffingID + END ELSE + BEGIN + UPDATE fs + SET + [TargetAdjustedDollars01] = [InitialBudgetDollars01], + [TargetAdjustedDollars02] = [InitialBudgetDollars02], + [TargetAdjustedDollars03] = [InitialBudgetDollars03], + [TargetAdjustedDollars04] = [InitialBudgetDollars04], + [TargetAdjustedDollars05] = [InitialBudgetDollars05], + [TargetAdjustedDollars06] = [InitialBudgetDollars06], + [TargetAdjustedDollars07] = [InitialBudgetDollars07], + [TargetAdjustedDollars08] = [InitialBudgetDollars08], + [TargetAdjustedDollars09] = [InitialBudgetDollars09], + [TargetAdjustedDollars10] = [InitialBudgetDollars10], + [TargetAdjustedDollars11] = [InitialBudgetDollars11], + [TargetAdjustedDollars12] = [InitialBudgetDollars12] + FROM [fp].[Staffing] fs + INNER JOIN #filterTable filter ON fs.StaffingID = filter.StaffingID + END + + END +GO + + +--------------------------------------------- + +-- fp.procRevenueByChargeDollarsFlexConfigPopulation +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-06-12 IP B-19913 APE Data Refresh - Flex Mappings, add parameter to process particular departments +** 2 2018-07-03 IP TK-59678 fix case when @SourceDimensionality is empty +** 3 2018-09-25 GF E-02313 Simplify source dimensionality to only department +** 4 2019-03-08 IP B-22295 Removed using table variables, small optimizations +** 5 2021-03-12 BK Jazz-16331 Don't include crosswalked dimensionality if Dollars are stored in fp.FactChargeVolumeDollars +** 6 2021-06-06 MY JAZZ-34224 Fix proc to properly populate when using new crosswalk +** 7 2023-04-06 MD JAZZ-52587 Update to use new CV data structure +** 8 2023-04-13 BW JAZZ-51383 Remove IsDollarsRemovedFromCharges +** 9 2023-05-16 MY JAZZ-54812 Missed FactChargeVolume Reference +*************************************************************/ +CREATE PROCEDURE [fp].[procRevenueByChargeDollarsFlexConfigPopulation] + @EntityGroupConfigGUID UNIQUEIDENTIFIER, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + DECLARE @BudgetConfigID INT, + @EntityGroupConfigID INT, + @ChargeCodeBudget INT = 5, + @FlexTypeID INT = 4; + + SELECT @BudgetConfigID = bc.BudgetConfigID, + @EntityGroupConfigID = egc.EntityGroupConfigID + FROM [fp].[EntityGroupConfig] egc + INNER JOIN [fp].[BudgetConfig] bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID + + IF OBJECT_ID('tempdb..#FilteringTable') IS NOT NULL DROP TABLE #FilteringTable; + IF OBJECT_ID('tempdb..#flexMap') IS NOT NULL DROP TABLE #flexMap; + + CREATE TABLE #FilteringTable (DepartmentID INT, INDEX ix_1 NONCLUSTERED (DepartmentID)) + CREATE TABLE #flexMap (DepartmentID int NOT NULL, GLAccountID int NOT NULL); + + -- Get Targeting + IF (SELECT COUNT(*) FROM @SourceDimensionality) = 0 BEGIN + INSERT INTO #FilteringTable (DepartmentID) + SELECT DISTINCT DepartmentID FROM fp.ChargeVolume WHERE EntityGroupConfigID = @EntityGroupConfigID + END + ELSE BEGIN + INSERT INTO #FilteringTable (DepartmentID) + SELECT DepartmentID + FROM @SourceDimensionality + END + + -- In this case we are using the new crosswalk logic which only looks at the configuration table. + -- We populate the flex config mapping still, but can pull straight from the configuration table itself for this purpose. + -- We leverage this still so we don't have to add additional checks everywhere we are checking if something is flexed/crosswalked or not + -- https://confluence.sdt.local/display/DD/Charge+Dollar+To+General+Ledger+Crosswalk++-+4 + INSERT INTO #flexMap(DepartmentID, GLAccountID) + SELECT DISTINCT xwalk.DepartmentID, AccountID AS GLAccountID + FROM fp.ChargeToGeneralLedgerCrosswalkConfiguration xwalk + INNER JOIN #FilteringTable ft on ft.DepartmentID = xwalk.DepartmentID + WHERE xwalk.EntityGroupConfigID = @EntityGroupConfigID + + IF (@IsDebug = 1) + BEGIN + SELECT fcm.EntityGroupConfigID,fcm.DepartmentID,fcm.GLAccountID,fcm.FlexingTypeID + FROM [fp].[FlexConfigMapping] fcm + INNER JOIN #FilteringTable ft on ft.DepartmentID = fcm.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND FlexingTypeID = @FlexTypeID + END ELSE + BEGIN + ;WITH TRG AS ( + SELECT fcm.EntityGroupConfigID,fcm.DepartmentID,fcm.GLAccountID,fcm.FlexingTypeID + FROM [fp].[FlexConfigMapping] fcm + INNER JOIN #FilteringTable ft on ft.DepartmentID = fcm.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND FlexingTypeID = @FlexTypeID + ) + + MERGE TRG + USING (SELECT @EntityGroupConfigID AS EntityGroupConfigID, + DepartmentID, + GLAccountID, + @FlexTypeID AS FlexingTypeID + FROM #flexMap) AS Src ON TRG.DepartmentID = SRC.DepartmentID and TRG.GLAccountID = SRC.GLAccountID + WHEN NOT MATCHED BY TARGET THEN + INSERT VALUES (src.EntityGroupConfigID,src.DepartmentID,src.GLAccountID,src.FlexingTypeID) + WHEN NOT MATCHED BY SOURCE THEN DELETE; + END + + END +GO + + +--------------------------------------------- + +-- fp.procRevenueByStatisticsFlexConfigPopulation +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-06-12 IP B-19913 APE Data Refresh - Flex Mappings, add parameter to process particular departments +** 2 2018-07-03 IP TK-59678 fix case when @SourceDimensionality is empty +** 3 2018-09-11 apukii TK-62350 fixed typo in code +** 4 2018-09-25 GF E-02313 Simplify source dimensionality to only department +** 5 2019-03-08 IP B-22295 Removed using table variables, small optimizations +** 6 2021-03-26 NT JAZZ-14122 Simplify code to remove null joins +** 7 2023-02-06 MY JAZZ-48980 Update flexing to support x-department flexing +** 8 2023-05-01 MY JAZZ-54277 Flex Config Mapping is not taking handling Cross Department Flexing properly +** 9 2023-08-01 MY JAZZ-58153 Update to new structure +*************************************************************/ +CREATE PROCEDURE [fp].[procRevenueByStatisticsFlexConfigPopulation] + @EntityGroupConfigGUID UNIQUEIDENTIFIER , + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + DECLARE @BudgetConfigID INT, + @EntityGroupConfigID INT; + + SET @BudgetConfigID = (SELECT bc.BudgetConfigID + FROM [fp].[EntityGroupConfig] egc + INNER JOIN [fp].[BudgetConfig] bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID) + SET @EntityGroupConfigID = (SELECT EntityGroupConfigID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID) + + CREATE TABLE #flexMap ( + DepartmentID INT NOT NULL, + GLAccountID INT NOT NULL, + StatAccountID INT NOT NULL, + SourceDepartmentID INT NOT NULL + ); + + IF OBJECT_ID('tempdb..#FilterFGL') IS NOT NULL DROP TABLE #FilterFGL + IF OBJECT_ID('tempdb..#FilteringTable') IS NOT NULL DROP TABLE #FilteringTable + + CREATE TABLE #FilterFGL (DepartmentID int, AccountID int, BudgetConfigID int) + + CREATE TABLE #FilteringTable ( + DepartmentID INT, + INDEX ix_1 NONCLUSTERED (DepartmentID) + ) + + IF (SELECT COUNT(*) FROM @SourceDimensionality) = 0 + BEGIN + -- In the event targeting is empty, populate all departments that currently are in GL for the selected config + INSERT INTO #FilteringTable + SELECT DISTINCT DepartmentID + FROM [fp].[PrimaryStatisticsConfig] + WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID + AND IsRevenue = 1 + END ELSE BEGIN + INSERT INTO #FilteringTable (DepartmentID) + SELECT DepartmentID + FROM @SourceDimensionality + END + + -- Build a list of Department / Revenue Account combinations + -- Only department/account combinations in GL are populated in the fp.FlexConfigMapping table. New records will be added as new dimensionality is imported in. + INSERT INTO #FilterFGL (DepartmentID, AccountID, BudgetConfigID) + SELECT fgl.DepartmentID,fgl.AccountID,fgl.BudgetConfigID + FROM [fp].[GeneralLedger] fgl + INNER JOIN #FilteringTable SD on SD.DepartmentID = fgl.DepartmentID + WHERE + fgl.VariabilityID = 2 -- Variable Only (used for filtering the data down) + and fgl.BudgetConfigID = @BudgetConfigID + and fgl.APEModelSectionID = 1 -- Revenue + + -- Populate all overrides for the revenue accounts. Overrides ignore traditional logic and override anything set at the department level. + INSERT INTO #flexMap(DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID) + SELECT DISTINCT stat.DepartmentID, fgl.AccountID AS GLAccountID, nso.AccountID AS StatAccountID, stat.DepartmentID + FROM [fp].[FactStatistics] stat + INNER JOIN #FilterFGL fgl ON fgl.DepartmentID = stat.DepartmentID and fgl.BudgetConfigID = stat.BudgetConfigID + INNER JOIN [fp].[RevenueFlexingOverrideConfig] ns ON ns.DepartmentID = fgl.DepartmentID AND ns.AccountID = fgl.AccountID + INNER JOIN [fp].[RevenueFlexingOverrideConfigAssignment] nso ON nso.OverrideFlexConfigGUID = ns.OverrideFlexConfigGUID + WHERE ns.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND ns.FlexMethodID IN ( + 3, -- Statistic Accounts By Patient Class + 4 -- Total Statistic Accounts + ) + + -- Process department level configuration changes that are not overriden. We also will exclude Department/Account combos + -- that have multiple source departments here as that is handled in the statement below. + -- Aka: Process the Department/Account combinations that have primary stats of "Same as Department" in the Primary Stat Config + INSERT INTO #flexMap(DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID) + SELECT DISTINCT stat.DepartmentID, fgl.AccountID AS GLAccountID, stat.AccountID AS StatAccountID, stat.DepartmentID + FROM #FilterFGL fgl + INNER JOIN [fw].[DimAccount] a ON fgl.AccountID = a.AccountID + INNER JOIN [fp].[FactStatistics] stat ON fgl.DepartmentID = stat.DepartmentID and fgl.BudgetConfigID = stat.BudgetConfigID + INNER JOIN [fp].[PrimaryStatisticsConfig] fsc ON fsc.DepartmentID = stat.DepartmentID AND fsc.AccountID = stat.AccountID + INNER JOIN [fp].[RevenueExpenseFlexingConfig] ns ON ns.DepartmentID = fgl.DepartmentID AND fsc.EntityGroupConfigGUID = ns.EntityGroupConfigGUID + LEFT JOIN [fp].[RevenueFlexingOverrideConfig] OVR ON OVR.EntityGroupConfigGUID = fsc.EntityGroupConfigGUID + AND ovr.DepartmentID = stat.DepartmentID + AND ovr.AccountID = fgl.AccountID + LEFT JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscsd ON fsc.RowID = pscsd.PrimaryStatisticsConfigID + WHERE fsc.IsRevenue = 1 + AND fsc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND ( + ( + a.PatientClassID = stat.PatientClassID + AND ns.FlexMethodID = 3 -- Statistic Accounts By Patient Class + ) + OR + ( + ns.FlexMethodID = 4 -- Total Statistic Accounts + AND fsc.AccountID = stat.AccountID + ) + ) + AND ovr.DepartmentID IS NULL -- We only want records that are not overridden + AND pscsd.DepartmentID IS NULL; -- We want records where there is no source department specified. When no source department is specified, it's the same as the regular department + + -- Process departments with multiple source departments + INSERT INTO #flexMap(DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID) + SELECT DISTINCT fsc.DepartmentID, fgl.AccountID AS GLAccountID, stat.AccountID AS StatAccountID, pscsd.DepartmentID + FROM [fp].[PrimaryStatisticsConfig] fsc + INNER JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscsd ON fsc.RowID = pscsd.PrimaryStatisticsConfigID + INNER JOIN #FilterFGL fgl ON fsc.DepartmentID = fgl.DepartmentID + INNER JOIN [fw].[DimAccount] a ON fgl.AccountID = a.AccountID + INNER JOIN [fp].[FactStatistics] stat ON pscsd.DepartmentID = stat.DepartmentID AND stat.AccountID = fsc.AccountID AND fgl.BudgetConfigID = stat.BudgetConfigID + INNER JOIN [fp].[RevenueExpenseFlexingConfig] ns ON ns.DepartmentID = fsc.DepartmentID AND fsc.EntityGroupConfigGUID = ns.EntityGroupConfigGUID + -- Note: we allow departments OUTSIDE of the entity group config for this. We also want to include things out of the department filter + LEFT JOIN [fp].[RevenueFlexingOverrideConfig] OVR ON OVR.EntityGroupConfigGUID = fsc.EntityGroupConfigGUID + AND ovr.DepartmentID = fsc.DepartmentID + AND ovr.AccountID = fgl.AccountID + WHERE fsc.IsRevenue = 1 + AND fsc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND ( + ( + a.PatientClassID = stat.PatientClassID + AND ns.FlexMethodID = 3 -- Statistic Accounts By Patient Class + ) + OR + ( + ns.FlexMethodID = 4 -- Total Statistic Accounts + AND fsc.AccountID = stat.AccountID + ) + ) + AND ovr.DepartmentID IS NULL -- We only want records that are not overridden + + IF @IsDebug = 1 + BEGIN + SELECT '#FilteringTable', DepartmentID FROM #FilteringTable + SELECT '#flexMap', @EntityGroupConfigID AS EntityGroupConfigID, DepartmentID, GLAccountID, StatAccountID, SourceDepartmentID, 2 AS FlexingTypeID FROM #flexMap + END ELSE + BEGIN + + WITH TRG + AS ( + SELECT fcm.EntityGroupConfigID, + fcm.DepartmentID, + fcm.GLAccountID, + fcm.StatAccountID, + fcm.FlexingTypeID, + fcm.SourceDepartmentID + FROM [fp].[FlexConfigMapping] fcm + INNER JOIN #FilteringTable SD ON SD.DepartmentID = fcm.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND FlexingTypeID = 2 -- Revenue + ) + MERGE TRG + USING ( + SELECT @EntityGroupConfigID AS EntityGroupConfigID, + DepartmentID, + GLAccountID, + StatAccountID, + 2 AS FlexingTypeID, -- Revenue + SourceDepartmentID + FROM #flexMap + ) AS Src ON TRG.DepartmentID = SRC.DepartmentID + AND TRG.GLAccountID = SRC.GLAccountID + AND TRG.StatAccountID = SRC.StatAccountID + AND TRG.SourceDepartmentID = SRC.SourceDepartmentID + WHEN NOT MATCHED BY TARGET THEN + INSERT VALUES (src.EntityGroupConfigID, src.DepartmentID, src.GLAccountID, src.StatAccountID, src.FlexingTypeID, src.SourceDepartmentID) + WHEN NOT MATCHED BY SOURCE THEN DELETE; + + END + + END +GO + + +--------------------------------------------- + +-- fp.procRunBudgetEngine +CREATE PROCEDURE fp.procRunBudgetEngine + @BudgetConfigID INT = 0 -- If it's 0, we'll set it to the active +AS +BEGIN + + IF (@BudgetConfigID = 0) + BEGIN + SELECT @BudgetConfigID = BudgetConfigID FROM fp.BudgetConfig WHERE IsActive = 1 AND IsEngineDisabled = 0; + END + + IF (@BudgetConfigID IS NOT NULL) + BEGIN + -- Requests must be done outside of the proc and in a seperate migration to avoid transction weirdness. + + DECLARE @AssemblyQualifiedName varchar(1024); + SET @AssemblyQualifiedName = 'Strata.CS.Jazz.ABB.Tasks.APEngineTask, Strata.CS.Jazz.ABB'; + + --This will be xml if your task context is in xml. In this example, the context is in json + DECLARE @json VARCHAR(1000) = '' + CAST(@BudgetConfigID AS NVARCHAR(100)) + ''; + + DECLARE @statusCode INT; + EXEC dbo.procCreateTask + @taskTypeName = @AssemblyQualifiedName, + @contextXML = @json, + @userName = 'HangfireMigration', + @taskSource = 'Migration', + @statusCode = @statusCode; + + --We get back http status code + IF (@statusCode < 200 OR @statusCode > 299) + BEGIN + -- Task Creation failed + RAISERROR ('Task Creation failed', 50, 0); + END + END + +END +GO + + +--------------------------------------------- + +-- fp.procRunBudgetTargetSplitUpgrade +CREATE PROCEDURE fp.procRunBudgetTargetSplitUpgrade + @BudgetConfigID INT +AS +BEGIN + + IF EXISTS ( + SELECT TOP 1 1 FROM [fp].[StatisticsAdjustment] adj + INNER JOIN [fp].[BudgetConfig] bc ON adj.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE Comment LIKE '%Target/Budget Upgrade.%' AND bc.BudgetConfigID = @BudgetConfigID + ) + BEGIN + PRINT 'The upgrade has already been completed for this budget' + RETURN; + END + + IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'AdjustmentGrouping_PreSplitUpgrade')) + DROP TABLE [bak].[AdjustmentGrouping_PreSplitUpgrade] + + IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'StatisticsAdjustment_PreSplitUpgrade')) + DROP TABLE [bak].[StatisticsAdjustment_PreSplitUpgrade] + + IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'StatisticsAdjustmentRate_PreSplitUpgrade')) + DROP TABLE [bak].[StatisticsAdjustmentRate_PreSplitUpgrade] + + IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'StatisticsAdjustmentImport_PreSplitUpgrade')) + DROP TABLE [bak].[StatisticsAdjustmentImport_PreSplitUpgrade] + + IF (EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME = 'StatisticsAddProviderAdjustment_PreSplitUpgrade')) + DROP TABLE [bak].[StatisticsAddProviderAdjustment_PreSplitUpgrade] + + SELECT * INTO [bak].[AdjustmentGrouping_PreSplitUpgrade] FROM [fp].[AdjustmentGrouping] + SELECT * INTO [bak].[StatisticsAdjustment_PreSplitUpgrade] FROM [fp].[StatisticsAdjustment] + SELECT * INTO [bak].[StatisticsAdjustmentRate_PreSplitUpgrade] FROM [fp].[StatisticsAdjustmentRate] + SELECT * INTO [bak].[StatisticsAdjustmentImport_PreSplitUpgrade] FROM [fp].[StatisticsAdjustmentImport] + SELECT * INTO [bak].[StatisticsAddProviderAdjustment_PreSplitUpgrade] FROM [fp].[StatisticAddProviderAdjustment] + + EXEC fp.procBudgetTargetSplitUpgrade_Statistics @BudgetConfigID + +END +GO + + +--------------------------------------------- + +-- fp.procSampleBenefitRates_InitialAndSampled +/************************************************************** +** Change History +** CID Date Author WI Description +** 1 2019-02-12 MY TK-74715 Moved Benefits Rate Sampling from code to Proc +** 2 2019-11-12 MY B-24221 Removed FF for Benefits Rate Sampling +** 3 2020-03-31 LR B-24089 Removed check for null within join conditions +*************************************************************/ +CREATE PROCEDURE [fp].[procSampleBenefitRates_InitialAndSampled] + @EntityGroupConfigID INT, + @BudgetConfigID INT, + @AccountID INT, + @BenefitsValueTotalType INT, + @BenefitsValueRateType INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[FactBenefits] d WITH (READUNCOMMITTED) + WHERE BudgetConfigID = @BudgetConfigID + END + + + -- This is using the new logic for sampling benefit rates, we cannot independently sample rates the way we are doing. Rates are always calculated using the + -- int data, and this cannot ever be calculated (well for flexing's sake) using anything else. The old logic was taking the initial values which is basically taking the post flexed + -- staffing dollars / post flexed staffing X for example which we don't want. + -- IMPORTANT NOTE: This is behind a feature flag because this will cause numbers to change so we want to make sure that numbers don't change for clients mid-budget. + + UPDATE fb SET + SampledBudget01 = CASE WHEN COALESCE(driver.SampledBudget01, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget01, 0) / NULLIF(driver.SampledBudget01, 0), 0) END, + SampledBudget02 = CASE WHEN COALESCE(driver.SampledBudget02, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget02, 0) / NULLIF(driver.SampledBudget02, 0), 0) END, + SampledBudget03 = CASE WHEN COALESCE(driver.SampledBudget03, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget03, 0) / NULLIF(driver.SampledBudget03, 0), 0) END, + SampledBudget04 = CASE WHEN COALESCE(driver.SampledBudget04, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget04, 0) / NULLIF(driver.SampledBudget04, 0), 0) END, + SampledBudget05 = CASE WHEN COALESCE(driver.SampledBudget05, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget05, 0) / NULLIF(driver.SampledBudget05, 0), 0) END, + SampledBudget06 = CASE WHEN COALESCE(driver.SampledBudget06, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget06, 0) / NULLIF(driver.SampledBudget06, 0), 0) END, + SampledBudget07 = CASE WHEN COALESCE(driver.SampledBudget07, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget07, 0) / NULLIF(driver.SampledBudget07, 0), 0) END, + SampledBudget08 = CASE WHEN COALESCE(driver.SampledBudget08, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget08, 0) / NULLIF(driver.SampledBudget08, 0), 0) END, + SampledBudget09 = CASE WHEN COALESCE(driver.SampledBudget09, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget09, 0) / NULLIF(driver.SampledBudget09, 0), 0) END, + SampledBudget10 = CASE WHEN COALESCE(driver.SampledBudget10, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget10, 0) / NULLIF(driver.SampledBudget10, 0), 0) END, + SampledBudget11 = CASE WHEN COALESCE(driver.SampledBudget11, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget11, 0) / NULLIF(driver.SampledBudget11, 0), 0) END, + SampledBudget12 = CASE WHEN COALESCE(driver.SampledBudget12, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledBudget12, 0) / NULLIF(driver.SampledBudget12, 0), 0) END, + SampledProjection01 = CASE WHEN COALESCE(driver.SampledProjection01, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection01, 0) / NULLIF(driver.SampledProjection01, 0), 0) END, + SampledProjection02 = CASE WHEN COALESCE(driver.SampledProjection02, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection02, 0) / NULLIF(driver.SampledProjection02, 0), 0) END, + SampledProjection03 = CASE WHEN COALESCE(driver.SampledProjection03, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection03, 0) / NULLIF(driver.SampledProjection03, 0), 0) END, + SampledProjection04 = CASE WHEN COALESCE(driver.SampledProjection04, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection04, 0) / NULLIF(driver.SampledProjection04, 0), 0) END, + SampledProjection05 = CASE WHEN COALESCE(driver.SampledProjection05, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection05, 0) / NULLIF(driver.SampledProjection05, 0), 0) END, + SampledProjection06 = CASE WHEN COALESCE(driver.SampledProjection06, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection06, 0) / NULLIF(driver.SampledProjection06, 0), 0) END, + SampledProjection07 = CASE WHEN COALESCE(driver.SampledProjection07, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection07, 0) / NULLIF(driver.SampledProjection07, 0), 0) END, + SampledProjection08 = CASE WHEN COALESCE(driver.SampledProjection08, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection08, 0) / NULLIF(driver.SampledProjection08, 0), 0) END, + SampledProjection09 = CASE WHEN COALESCE(driver.SampledProjection09, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection09, 0) / NULLIF(driver.SampledProjection09, 0), 0) END, + SampledProjection10 = CASE WHEN COALESCE(driver.SampledProjection10, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection10, 0) / NULLIF(driver.SampledProjection10, 0), 0) END, + SampledProjection11 = CASE WHEN COALESCE(driver.SampledProjection11, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection11, 0) / NULLIF(driver.SampledProjection11, 0), 0) END, + SampledProjection12 = CASE WHEN COALESCE(driver.SampledProjection12, 0) = 0 then 0 else COALESCE(NULLIF(dollars.SampledProjection12, 0) / NULLIF(driver.SampledProjection12, 0), 0) END + FROM fp.FactBenefits fb + INNER JOIN + (SELECT SampledBudget01, SampledBudget02, SampledBudget03, SampledBudget04, SampledBudget05, SampledBudget06, SampledBudget07, SampledBudget08, SampledBudget09, SampledBudget10, SampledBudget11, SampledBudget12, + SampledProjection01, SampledProjection02, SampledProjection03, SampledProjection04, SampledProjection05, SampledProjection06, SampledProjection07, SampledProjection08, SampledProjection09, SampledProjection10, SampledProjection11, SampledProjection12, + DepartmentID + FROM fp.FactBenefits WHERE EntityGroupConfigID = @EntityGroupConfigID AND UnitTypeID = 34 AND AccountID = @AccountID) dollars + ON fb.DepartmentID = dollars.DepartmentID + INNER JOIN + (SELECT SampledBudget01, SampledBudget02, SampledBudget03, SampledBudget04, SampledBudget05, SampledBudget06, SampledBudget07, SampledBudget08, SampledBudget09, SampledBudget10, SampledBudget11, SampledBudget12, + SampledProjection01, SampledProjection02, SampledProjection03, SampledProjection04, SampledProjection05, SampledProjection06, SampledProjection07, SampledProjection08, SampledProjection09, SampledProjection10, SampledProjection11, SampledProjection12, + DepartmentID + FROM fp.FactBenefits WHERE EntityGroupConfigID = @EntityGroupConfigID AND UnitTypeID = @BenefitsValueTotalType AND AccountID = @AccountID) driver + ON fb.DepartmentID = driver.DepartmentID + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = fb.DepartmentID) + WHERE + fb.BudgetConfigID = @BudgetConfigID + and fb.EntityGroupConfigID = @EntityGroupConfigID + and fb.AccountID = @AccountID + AND fb.UnitTypeID = @BenefitsValueRateType + + -- Copy the sampled rates to the initial rates + UPDATE fb SET + InitialBudget01 = SampledBudget01, + InitialBudget02 = SampledBudget02, + InitialBudget03 = SampledBudget03, + InitialBudget04 = SampledBudget04, + InitialBudget05 = SampledBudget05, + InitialBudget06 = SampledBudget06, + InitialBudget07 = SampledBudget07, + InitialBudget08 = SampledBudget08, + InitialBudget09 = SampledBudget09, + InitialBudget10 = SampledBudget10, + InitialBudget11 = SampledBudget11, + InitialBudget12 = SampledBudget12, + InitialProjection01 = SampledProjection01, + InitialProjection02 = SampledProjection02, + InitialProjection03 = SampledProjection03, + InitialProjection04 = SampledProjection04, + InitialProjection05 = SampledProjection05, + InitialProjection06 = SampledProjection06, + InitialProjection07 = SampledProjection07, + InitialProjection08 = SampledProjection08, + InitialProjection09 = SampledProjection09, + InitialProjection10 = SampledProjection10, + InitialProjection11 = SampledProjection11, + InitialProjection12 = SampledProjection12 + FROM fp.FactBenefits fb + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = fb.DepartmentID) + WHERE + fb.BudgetConfigID = @BudgetConfigID + AND fb.EntityGroupConfigID = @EntityGroupConfigID + AND fb.AccountID = @AccountID + AND fb.UnitTypeID = @BenefitsValueRateType + + +END +GO + + +--------------------------------------------- + +-- fp.procSampleBenefitsBudgetData +CREATE PROCEDURE [fp].[procSampleBenefitsBudgetData] +@EntityGroupConfigID int +AS +BEGIN + + -- update the budget data + INSERT INTO [fp].[FactBenefitsBudget]([BenefitsID], [BudgetPhaseID], + [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], + [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12]) + SELECT [BenefitsID], [BudgetPhaseID], + [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], + [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12] + FROM [fp].[FactBenefits] fs + CROSS APPLY (VALUES (2),(3)) bp(BudgetPhaseID) + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND IsNew = 0 + +END +GO + + +--------------------------------------------- + +-- fp.procSampleBenefitsClearData +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2021-02-24 lrenadesouza JAZZ-12907 Added rolling deletes for all tables +** 2 2023-04-18 mdeboer JAZZ-53496 Remove adjustment delete logic +** 3 2023-07-05 mdeboer JAZZ-55672 Add remove config logic +***************************************************************/ +CREATE PROCEDURE [fp].[procSampleBenefitsClearData] + @BudgetConfigGUID uniqueidentifier, + @EntityGroupConfigID int, + @IsRemoveConfig BIT = 0 +AS +BEGIN + DECLARE @ChunkCount INT; + DECLARE @r INT; + + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 400000 END + + CREATE TABLE #BenefitsToDelete (BenefitsID INT) + + IF @IsRemoveConfig = 1 + BEGIN + INSERT #BenefitsToDelete with (tablock) (BenefitsID) + SELECT BenefitsID FROM fp.FactBenefits + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + ELSE + BEGIN + INSERT #BenefitsToDelete with (tablock) (BenefitsID) + SELECT BenefitsID FROM fp.FactBenefits + WHERE EntityGroupConfigID = @EntityGroupConfigID AND IsNew = 0 + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) bch FROM [fp].[BenefitsChangeHistory] bch INNER JOIN [fp].[FactBenefits] fb on fb.BenefitsID = bch.BenefitsID WHERE fb.EntityGroupConfigID = @EntityGroupConfigID; + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + -- delete existing data (have to do value tables first so that we still have EntityGroupConfigID) + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) bb + FROM [fp].[FactBenefitsBudget] bb + INNER JOIN [fp].[FactBenefits] fb on fb.BenefitsID = bb.BenefitsID + INNER JOIN #BenefitsToDelete btd on bb.BenefitsID = btd.BenefitsID + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) bb + FROM [fp].[FactBenefitsProjection] bb + INNER JOIN [fp].[FactBenefits] fb on fb.BenefitsID = bb.BenefitsID + INNER JOIN #BenefitsToDelete btd on bb.BenefitsID = btd.BenefitsID + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) bb + FROM [fp].[FactBenefitsHistory] bb + INNER JOIN [fp].[FactBenefits] fb on fb.BenefitsID = bb.BenefitsID + INNER JOIN #BenefitsToDelete btd on bb.BenefitsID = btd.BenefitsID + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) fb + FROM [fp].[FactBenefits] fb + INNER JOIN #BenefitsToDelete btd on fb.BenefitsID = btd.BenefitsID + WHERE fb.EntityGroupConfigID = @EntityGroupConfigID; + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END +END; +GO + + +--------------------------------------------- + +-- fp.procSampleBenefitsDimensionality +CREATE PROCEDURE [fp].[procSampleBenefitsDimensionality] + @BudgetConfigID int, + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @SourceFiscalYearID smallint, + @SourceTimeClassID tinyint +AS +BEGIN + + INSERT INTO [fp].[FactBenefits]([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [UnitTypeID], [FlexMethodID]) + SELECT + DISTINCT + @BudgetConfigID, + @EntityGroupConfigID, + dept.EntityID, + gl.DepartmentID, + gl.AccountID, + acc.OBDollarsFinancialReportingID, + ut.UnitTypeID, + 0 AS FlexMethodID + FROM + [int].[FactGL] gl + INNER JOIN [fw].[DimDepartment] dept ON gl.DepartmentID = dept.DepartmentID + INNER JOIN [fw].[DimAccount] acc on gl.AccountID = acc.AccountID + INNER JOIN [fp].[ModelSectionMap] msm ON msm.OBModelSectionName = acc.OBModelSectionName + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + LEFT JOIN ( + SELECT DISTINCT DepartmentID, AccountID + FROM [fp].[FactBenefits] + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND IsNew = 1 + ) ben + ON gl.DepartmentID = ben.DepartmentID + AND gl.AccountID = ben.AccountID + CROSS APPLY (VALUES (34),(144),(169),(170),(171)) ut(UnitTypeID) + WHERE + ((gl.FiscalYearID = @SourceFiscalYearID AND gl.TimeclassID = @SourceTimeClassID) -- baseline + OR (gl.FiscalYearID = @CurrentFiscalYearID) -- projection (current year actuals) + OR (gl.FiscalYearID = @CurrentFiscalYearID - 1 AND gl.TimeClassID = 1)) -- prior year, actual & budget + AND gl.IsDeleted = 0 + AND gl.FiscalMonthID != 0 + AND acc.OBDollarsFinancialReportingID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND msm.APEModelSectionID = 5 + AND ben.DepartmentID IS NULL + +END +GO + + +--------------------------------------------- + +-- fp.procSampleBenefitsFTEDriverValues +/************************************************************** +** Change History +** CID Date Author WI Description +** 1 2019-02-14 IP B-22020 Added AccountID as CSV +** 2 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table +** 3 2019-06-02 MY TK-74658 Removing remaining table variable functions +** 4 2020-03-31 LR B-24089 Removed check for null within join conditions +** 5 2022-08-31 BW JAZZ-41678 Insert the assignment config's jc/pcg detail into a temp table for the @PayrollFilterSQL to join on +** 6 2023-10-31 BK JAZZ-62801 Update for staffing restructure +*************************************************************/ +CREATE PROCEDURE [fp].[procSampleBenefitsFTEDriverValues] + @EntityGroupConfigID INT, + @AccountID VARCHAR(MAX), + @FinancialReportingID INT, + @TimeClassID INT, + @FiscalYearID INT, + @PayrollFilterSql NVARCHAR(MAX), + @PayrollFilterTempTableSQL VARCHAR(MAX), + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + WITH RECOMPILE + AS + BEGIN + + CREATE TABLE #FilterByDepartment (DepartmentID int,BudgetPhaseID int) + INSERT INTO #FilterByDepartment (DepartmentID,BudgetPhaseID) + SELECT DepartmentID,BudgetPhaseID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[FactBenefits] d WITH (READUNCOMMITTED) + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + DECLARE @DynamicSql NVARCHAR(MAX) + + IF object_id('tempdb..#basisIDs') IS NOT NULL + BEGIN + DROP TABLE #basisIDs + END + IF object_id('tempdb..#StaffingFtes') IS NOT NULL + BEGIN + DROP TABLE #StaffingFtes + END + + CREATE TABLE #basisIDs (BenefitsID INT); + CREATE TABLE #StaffingFtes (EntityID INT, DepartmentID INT, AccountID INT, FinancialReportingID INT, BudgetPhaseID INT, + Value01 DECIMAL(19, 8), Value02 DECIMAL(19, 8), Value03 DECIMAL(19, 8), Value04 DECIMAL(19, 8), + Value05 DECIMAL(19, 8), Value06 DECIMAL(19, 8), Value07 DECIMAL(19, 8), Value08 DECIMAL(19, 8), + Value09 DECIMAL(19, 8), Value10 DECIMAL(19, 8), Value11 DECIMAL(19, 8), Value12 DECIMAL(19, 8)) + + IF (@TimeClassID = 2) + BEGIN + + set @DynamicSql = ' + ' + @PayrollFilterTempTableSQL + ' + + CREATE TABLE #AccountIDs (AccountID int) + INSERT INTO #AccountIDs (AccountID) + SELECT DISTINCT value as AccountID FROM STRING_SPLIT('''+@AccountID+''','','') + + INSERT INTO #StaffingFtes + SELECT + pr.EntityID, + pr.DepartmentID, + AccLst.AccountID, + ' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID, + CAST(2 as TINYINT), + SUM(pr.TargetAdjustedHours01) / MAX(wh.Month01) AS Value01, + SUM(pr.TargetAdjustedHours02) / MAX(wh.Month02) AS Value02, + SUM(pr.TargetAdjustedHours03) / MAX(wh.Month03) AS Value03, + SUM(pr.TargetAdjustedHours04) / MAX(wh.Month04) AS Value04, + SUM(pr.TargetAdjustedHours05) / MAX(wh.Month05) AS Value05, + SUM(pr.TargetAdjustedHours06) / MAX(wh.Month06) AS Value06, + SUM(pr.TargetAdjustedHours07) / MAX(wh.Month07) AS Value07, + SUM(pr.TargetAdjustedHours08) / MAX(wh.Month08) AS Value08, + SUM(pr.TargetAdjustedHours09) / MAX(wh.Month09) AS Value09, + SUM(pr.TargetAdjustedHours10) / MAX(wh.Month10) AS Value10, + SUM(pr.TargetAdjustedHours11) / MAX(wh.Month11) AS Value11, + SUM(pr.TargetAdjustedHours12) / MAX(wh.Month12) AS Value12 + FROM [fp].[Staffing] pr + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on pr.PayCodeGroupID = exc.PayCodeGroupID + INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID + INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh ON wh.FiscalYearID = ' + CAST(@FiscalYearID as nvarchar(50)) + ' + AND wh.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END) + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = pr.DepartmentID) + CROSS APPLY (SELECT AccountID FROM #AccountIDs) AccLst + WHERE + pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + AND exc.PayCodeGroupID IS NULL + AND (ft.BudgetPhaseID IS NULL OR 2 = ft.BudgetPhaseID) + AND ' + @PayrollFilterSql + ' + GROUP BY + pr.DepartmentID, + pr.EntityID, + AccLst.AccountID + + INSERT INTO #StaffingFtes + SELECT + pr.EntityID, + pr.DepartmentID, + AccLst.AccountID, + ' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID, + CAST(3 as TINYINT), + SUM(pr.BudgetAdjustedHours01) / MAX(wh.Month01) AS Value01, + SUM(pr.BudgetAdjustedHours02) / MAX(wh.Month02) AS Value02, + SUM(pr.BudgetAdjustedHours03) / MAX(wh.Month03) AS Value03, + SUM(pr.BudgetAdjustedHours04) / MAX(wh.Month04) AS Value04, + SUM(pr.BudgetAdjustedHours05) / MAX(wh.Month05) AS Value05, + SUM(pr.BudgetAdjustedHours06) / MAX(wh.Month06) AS Value06, + SUM(pr.BudgetAdjustedHours07) / MAX(wh.Month07) AS Value07, + SUM(pr.BudgetAdjustedHours08) / MAX(wh.Month08) AS Value08, + SUM(pr.BudgetAdjustedHours09) / MAX(wh.Month09) AS Value09, + SUM(pr.BudgetAdjustedHours10) / MAX(wh.Month10) AS Value10, + SUM(pr.BudgetAdjustedHours11) / MAX(wh.Month11) AS Value11, + SUM(pr.BudgetAdjustedHours12) / MAX(wh.Month12) AS Value12 + FROM [fp].[Staffing] pr + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on pr.PayCodeGroupID = exc.PayCodeGroupID + INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID + INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh ON wh.FiscalYearID = ' + CAST(@FiscalYearID as nvarchar(50)) + ' + AND wh.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END) + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = pr.DepartmentID + CROSS APPLY (SELECT AccountID FROM #AccountIDs) AccLst + WHERE + pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + AND exc.PayCodeGroupID IS NULL + AND (ft.BudgetPhaseID IS NULL OR 3 = ft.BudgetPhaseID) + AND ' + @PayrollFilterSql + ' + GROUP BY + pr.DepartmentID, + pr.EntityID, + AccLst.AccountID + + + -- Update Value + UPDATE budg + SET + AdjustedValue01 = Value01, AdjustedValue02 = Value02, AdjustedValue03 = Value03, AdjustedValue04 = Value04, + AdjustedValue05 = Value05, AdjustedValue06 = Value06, AdjustedValue07 = Value07, AdjustedValue08 = Value08, + AdjustedValue09 = Value09, AdjustedValue10 = Value10, AdjustedValue11 = Value11, AdjustedValue12 = Value12, + FlexedValue01 = Value01, FlexedValue02 = Value02, FlexedValue03 = Value03, FlexedValue04 = Value04, + FlexedValue05 = Value05, FlexedValue06 = Value06, FlexedValue07 = Value07, FlexedValue08 = Value08, + FlexedValue09 = Value09, FlexedValue10 = Value10, FlexedValue11 = Value11, FlexedValue12 = Value12 + FROM [fp].[FactBenefits] benefits + INNER JOIN [fp].[FactBenefitsBudget] budg ON benefits.BenefitsID = budg.BenefitsID + INNER JOIN #StaffingFtes staffing ON + staffing.EntityID = benefits.EntityID + AND staffing.DepartmentID = benefits.DepartmentID + AND staffing.AccountID = benefits.AccountID + AND staffing.FinancialReportingID = benefits.FinancialReportingID + AND staffing.BudgetPhaseID = budg.BudgetPhaseID + WHERE benefits.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + AND benefits.UnitTypeID = 144 + + '; + + END ELSE BEGIN + + set @DynamicSql = ' + ' + @PayrollFilterTempTableSQL + ' + + DECLARE @MonthsLoaded INT + SELECT @MonthsLoaded = bc.MonthsLoaded from [fp].[BudgetConfig] bc inner join [fp].[EntityGroupConfig] egc on egc.BudgetConfigGUID = bc.BudgetConfigGUID where egc.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + + CREATE TABLE #AccountIDs (AccountID int) + INSERT INTO #AccountIDs (AccountID) + SELECT DISTINCT value as AccountID FROM STRING_SPLIT('''+@AccountID+''','','') + + INSERT INTO #StaffingFtes + SELECT + pr.EntityID, + pr.DepartmentID, + AccLst.AccountID, + ' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID, + CAST(3 as TINYINT), + SUM(pr.ProjectionAdjustedHours01) / MAX(wh.Month01) AS Value01, + SUM(pr.ProjectionAdjustedHours02) / MAX(wh.Month02) AS Value02, + SUM(pr.ProjectionAdjustedHours03) / MAX(wh.Month03) AS Value03, + SUM(pr.ProjectionAdjustedHours04) / MAX(wh.Month04) AS Value04, + SUM(pr.ProjectionAdjustedHours05) / MAX(wh.Month05) AS Value05, + SUM(pr.ProjectionAdjustedHours06) / MAX(wh.Month06) AS Value06, + SUM(pr.ProjectionAdjustedHours07) / MAX(wh.Month07) AS Value07, + SUM(pr.ProjectionAdjustedHours08) / MAX(wh.Month08) AS Value08, + SUM(pr.ProjectionAdjustedHours09) / MAX(wh.Month09) AS Value09, + SUM(pr.ProjectionAdjustedHours10) / MAX(wh.Month10) AS Value10, + SUM(pr.ProjectionAdjustedHours11) / MAX(wh.Month11) AS Value11, + SUM(pr.ProjectionAdjustedHours12) / MAX(wh.Month12) AS Value12 + FROM [fp].[Staffing] pr + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on pr.PayCodeGroupID = exc.PayCodeGroupID + INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID + INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh ON wh.FiscalYearID = ' + CAST(@FiscalYearID as nvarchar(50)) + ' + AND wh.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END) + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = pr.DepartmentID + CROSS APPLY (SELECT AccountID FROM #AccountIDs) AccLst + WHERE + pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + AND exc.PayCodeGroupID IS NULL + AND ' + @PayrollFilterSql + ' + GROUP BY + pr.DepartmentID, + pr.EntityID, + AccLst.AccountID + + -- Update Value + UPDATE proj + SET + proj.AdjustedValue01 = CASE WHEN 1 <= @MonthsLoaded THEN InitialProjection01 ELSE Value01 END, + proj.AdjustedValue02 = CASE WHEN 2 <= @MonthsLoaded THEN InitialProjection02 ELSE Value02 END, + proj.AdjustedValue03 = CASE WHEN 3 <= @MonthsLoaded THEN InitialProjection03 ELSE Value03 END, + proj.AdjustedValue04 = CASE WHEN 4 <= @MonthsLoaded THEN InitialProjection04 ELSE Value04 END, + proj.AdjustedValue05 = CASE WHEN 5 <= @MonthsLoaded THEN InitialProjection05 ELSE Value05 END, + proj.AdjustedValue06 = CASE WHEN 6 <= @MonthsLoaded THEN InitialProjection06 ELSE Value06 END, + proj.AdjustedValue07 = CASE WHEN 7 <= @MonthsLoaded THEN InitialProjection07 ELSE Value07 END, + proj.AdjustedValue08 = CASE WHEN 8 <= @MonthsLoaded THEN InitialProjection08 ELSE Value08 END, + proj.AdjustedValue09 = CASE WHEN 9 <= @MonthsLoaded THEN InitialProjection09 ELSE Value09 END, + proj.AdjustedValue10 = CASE WHEN 10 <= @MonthsLoaded THEN InitialProjection10 ELSE Value10 END, + proj.AdjustedValue11 = CASE WHEN 11 <= @MonthsLoaded THEN InitialProjection11 ELSE Value11 END, + proj.AdjustedValue12 = CASE WHEN 12 <= @MonthsLoaded THEN InitialProjection12 ELSE Value12 END, + proj.FlexedValue01 = CASE WHEN 1 <= @MonthsLoaded THEN InitialProjection01 ELSE Value01 END, + proj.FlexedValue02 = CASE WHEN 2 <= @MonthsLoaded THEN InitialProjection02 ELSE Value02 END, + proj.FlexedValue03 = CASE WHEN 3 <= @MonthsLoaded THEN InitialProjection03 ELSE Value03 END, + proj.FlexedValue04 = CASE WHEN 4 <= @MonthsLoaded THEN InitialProjection04 ELSE Value04 END, + proj.FlexedValue05 = CASE WHEN 5 <= @MonthsLoaded THEN InitialProjection05 ELSE Value05 END, + proj.FlexedValue06 = CASE WHEN 6 <= @MonthsLoaded THEN InitialProjection06 ELSE Value06 END, + proj.FlexedValue07 = CASE WHEN 7 <= @MonthsLoaded THEN InitialProjection07 ELSE Value07 END, + proj.FlexedValue08 = CASE WHEN 8 <= @MonthsLoaded THEN InitialProjection08 ELSE Value08 END, + proj.FlexedValue09 = CASE WHEN 9 <= @MonthsLoaded THEN InitialProjection09 ELSE Value09 END, + proj.FlexedValue10 = CASE WHEN 10 <= @MonthsLoaded THEN InitialProjection10 ELSE Value10 END, + proj.FlexedValue11 = CASE WHEN 11 <= @MonthsLoaded THEN InitialProjection11 ELSE Value11 END, + proj.FlexedValue12 = CASE WHEN 12 <= @MonthsLoaded THEN InitialProjection12 ELSE Value12 END + FROM [fp].[FactBenefits] benefits + INNER JOIN [fp].[FactBenefitsProjection] proj ON benefits.BenefitsID = proj.BenefitsID + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = benefits.DepartmentID /* adding this here so that the BudgetPhase will be respected - once we convert benefits to new structure, this can go away since the filter is applied on #staffingSalaries table */ + INNER JOIN #StaffingFtes staffing ON + staffing.EntityID = benefits.EntityID + AND staffing.DepartmentID = benefits.DepartmentID + AND staffing.AccountID = benefits.AccountID + AND staffing.FinancialReportingID = benefits.FinancialReportingID + AND (proj.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL) /* also remove this when converting benfits */ + WHERE benefits.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + AND benefits.UnitTypeID = 144 + '; + + END + + EXECUTE sp_executesql @DynamicSql, N'@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY', @SourceDimensionality = @SourceDimensionality; + END +GO + + +--------------------------------------------- + +-- fp.procSampleBenefitsFTEDriverValues_InitialValue +/************************************************************** +** Change History +** CID Date Author WI Description +** 1 2019-02-14 IP B-22020 Added AccountID as CSV +** 2 2019-06-02 MY TK-74658 Removing remaining table variable functions +** 3 2020-03-31 LR B-24089 Removed check for null within join conditions +** 4 2022-08-31 BW JAZZ-41678 Insert the assignment config's jc/pcg detail into a temp table for the @PayrollFilterSQL to join on +** 5 2023-10-31 BK JAZZ-62801 Insert the assignment config's jc/pcg detail into a temp table for the @PayrollFilterSQL to join on +**************************************************************/ +CREATE PROCEDURE [fp].[procSampleBenefitsFTEDriverValues_InitialValue] + @EntityGroupConfigID INT, + @AccountID VARCHAR(MAX), + @FinancialReportingID INT, + @TimeClassID INT, + @FiscalYearID INT, + @PayrollFilterSql NVARCHAR(MAX), + @PayrollFilterTempTableSQL VARCHAR(MAX), + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + AS + BEGIN + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[FactBenefits] d WITH (READUNCOMMITTED) + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + DECLARE @DynamicSql NVARCHAR(MAX) + + IF object_id('tempdb..#StaffingFtes') IS NOT NULL + BEGIN + DROP TABLE #StaffingFtes + END + + CREATE TABLE #StaffingFtes (EntityID INT, DepartmentID INT, AccountID INT, FinancialReportingID INT, + Value01 DECIMAL(19, 8), Value02 DECIMAL(19, 8), Value03 DECIMAL(19, 8), Value04 DECIMAL(19, 8), + Value05 DECIMAL(19, 8), Value06 DECIMAL(19, 8), Value07 DECIMAL(19, 8), Value08 DECIMAL(19, 8), + Value09 DECIMAL(19, 8), Value10 DECIMAL(19, 8), Value11 DECIMAL(19, 8), Value12 DECIMAL(19, 8)) + + IF (@TimeClassID = 2) + BEGIN + + set @DynamicSql = ' + ' + @PayrollFilterTempTableSQL + ' + + CREATE TABLE #AccountIDs (AccountID int) + INSERT INTO #AccountIDs (AccountID) + SELECT DISTINCT value as AccountID FROM STRING_SPLIT('''+@AccountID+''','','') + INSERT INTO #StaffingFtes + SELECT + pr.EntityID, + pr.DepartmentID, + AccLst.AccountID, + ' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID, + SUM(pr.InitialBudgetHours01) / MAX(wh.Month01) AS Value01, + SUM(pr.InitialBudgetHours02) / MAX(wh.Month02) AS Value02, + SUM(pr.InitialBudgetHours03) / MAX(wh.Month03) AS Value03, + SUM(pr.InitialBudgetHours04) / MAX(wh.Month04) AS Value04, + SUM(pr.InitialBudgetHours05) / MAX(wh.Month05) AS Value05, + SUM(pr.InitialBudgetHours06) / MAX(wh.Month06) AS Value06, + SUM(pr.InitialBudgetHours07) / MAX(wh.Month07) AS Value07, + SUM(pr.InitialBudgetHours08) / MAX(wh.Month08) AS Value08, + SUM(pr.InitialBudgetHours09) / MAX(wh.Month09) AS Value09, + SUM(pr.InitialBudgetHours10) / MAX(wh.Month10) AS Value10, + SUM(pr.InitialBudgetHours11) / MAX(wh.Month11) AS Value11, + SUM(pr.InitialBudgetHours12) / MAX(wh.Month12) AS Value12 + FROM [fp].[Staffing] pr + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on pr.PayCodeGroupID = exc.PayCodeGroupID + INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID + INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh ON wh.FiscalYearID = ' + CAST(@FiscalYearID as nvarchar(50)) + ' + AND wh.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END) + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = pr.DepartmentID) + CROSS APPLY (SELECT AccountID FROM #AccountIDs) AccLst + WHERE + pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + AND exc.PayCodeGroupID IS NULL + AND ' + @PayrollFilterSql + ' + GROUP BY + pr.DepartmentID, + pr.EntityID, + AccLst.AccountID + + + + -- Update Original Value + UPDATE benefits + SET + InitialBudget01 = Value01, InitialBudget02 = Value02, InitialBudget03 = Value03, InitialBudget04 = Value04, + InitialBudget05 = Value05, InitialBudget06 = Value06, InitialBudget07 = Value07, InitialBudget08 = Value08, + InitialBudget09 = Value09, InitialBudget10 = Value10, InitialBudget11 = Value11, InitialBudget12 = Value12 + FROM [fp].[FactBenefits] benefits + INNER JOIN #StaffingFtes staffing ON + staffing.EntityID = benefits.EntityID + AND staffing.DepartmentID = benefits.DepartmentID + AND staffing.AccountID = benefits.AccountID + AND staffing.FinancialReportingID = benefits.FinancialReportingID + WHERE benefits.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + AND benefits.UnitTypeID = 144 + + '; + + END ELSE BEGIN + + set @DynamicSql = ' + ' + @PayrollFilterTempTableSQL + ' + + DECLARE @MonthsLoaded INT + SELECT @MonthsLoaded = bc.MonthsLoaded from [fp].[BudgetConfig] bc inner join [fp].[EntityGroupConfig] egc on egc.BudgetConfigGUID = bc.BudgetConfigGUID where egc.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + + CREATE TABLE #AccountIDs (AccountID int) + INSERT INTO #AccountIDs (AccountID) + SELECT DISTINCT value as AccountID FROM STRING_SPLIT('''+@AccountID+''','','') + + + INSERT INTO #StaffingFtes + SELECT + pr.EntityID, + pr.DepartmentID, + AccLst.AccountID, + ' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID, + SUM(pr.InitialProjectionHours01) / MAX(wh.Month01) AS Value01, + SUM(pr.InitialProjectionHours02) / MAX(wh.Month02) AS Value02, + SUM(pr.InitialProjectionHours03) / MAX(wh.Month03) AS Value03, + SUM(pr.InitialProjectionHours04) / MAX(wh.Month04) AS Value04, + SUM(pr.InitialProjectionHours05) / MAX(wh.Month05) AS Value05, + SUM(pr.InitialProjectionHours06) / MAX(wh.Month06) AS Value06, + SUM(pr.InitialProjectionHours07) / MAX(wh.Month07) AS Value07, + SUM(pr.InitialProjectionHours08) / MAX(wh.Month08) AS Value08, + SUM(pr.InitialProjectionHours09) / MAX(wh.Month09) AS Value09, + SUM(pr.InitialProjectionHours10) / MAX(wh.Month10) AS Value10, + SUM(pr.InitialProjectionHours11) / MAX(wh.Month11) AS Value11, + SUM(pr.InitialProjectionHours12) / MAX(wh.Month12) AS Value12 + FROM [fp].[Staffing] pr + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on pr.PayCodeGroupID = exc.PayCodeGroupID + INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID + INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh ON wh.FiscalYearID = ' + CAST(@FiscalYearID as nvarchar(50)) + ' + AND wh.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END) + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = pr.DepartmentID + CROSS APPLY (SELECT AccountID FROM #AccountIDs) AccLst + WHERE + pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + AND exc.PayCodeGroupID IS NULL + AND ' + @PayrollFilterSql + ' + GROUP BY + pr.DepartmentID, + pr.EntityID, + AccLst.AccountID + + + -- Update Original Value + UPDATE benefits + SET + InitialProjection01 = CASE WHEN 1 <= @MonthsLoaded THEN SampledProjection01 ELSE Value01 END, + InitialProjection02 = CASE WHEN 2 <= @MonthsLoaded THEN SampledProjection02 ELSE Value02 END, + InitialProjection03 = CASE WHEN 3 <= @MonthsLoaded THEN SampledProjection03 ELSE Value03 END, + InitialProjection04 = CASE WHEN 4 <= @MonthsLoaded THEN SampledProjection04 ELSE Value04 END, + InitialProjection05 = CASE WHEN 5 <= @MonthsLoaded THEN SampledProjection05 ELSE Value05 END, + InitialProjection06 = CASE WHEN 6 <= @MonthsLoaded THEN SampledProjection06 ELSE Value06 END, + InitialProjection07 = CASE WHEN 7 <= @MonthsLoaded THEN SampledProjection07 ELSE Value07 END, + InitialProjection08 = CASE WHEN 8 <= @MonthsLoaded THEN SampledProjection08 ELSE Value08 END, + InitialProjection09 = CASE WHEN 9 <= @MonthsLoaded THEN SampledProjection09 ELSE Value09 END, + InitialProjection10 = CASE WHEN 10 <= @MonthsLoaded THEN SampledProjection10 ELSE Value10 END, + InitialProjection11 = CASE WHEN 11 <= @MonthsLoaded THEN SampledProjection11 ELSE Value11 END, + InitialProjection12 = CASE WHEN 12 <= @MonthsLoaded THEN SampledProjection12 ELSE Value12 END + FROM [fp].[FactBenefits] benefits + INNER JOIN #StaffingFtes staffing ON + staffing.EntityID = benefits.EntityID + AND staffing.DepartmentID = benefits.DepartmentID + AND staffing.AccountID = benefits.AccountID + AND staffing.FinancialReportingID = benefits.FinancialReportingID + WHERE benefits.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + AND benefits.UnitTypeID = 144 + + '; + END + + EXECUTE sp_executesql @DynamicSql, N'@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY', @SourceDimensionality = @SourceDimensionality; + + END +GO + + +--------------------------------------------- + +-- fp.procSampleBenefitsHistoricalData +CREATE PROCEDURE [fp].[procSampleBenefitsHistoricalData] + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @MonthsLoaded int +AS +BEGIN + + -- pad all of the data + INSERT INTO [fp].[FactBenefitsHistory] ([BenefitsID]) + SELECT fb.[BenefitsID] + FROM [fp].[FactBenefits] fb + LEFT JOIN fp.FactBenefitsHistory h ON fb.BenefitsID = h.BenefitsID + WHERE fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.IsNew = 0 AND h.BenefitsID IS NULL + + + -- set all of the values for prior year actual + UPDATE + fbh + SET + PriorYearActualValue01 = ISNULL(Month01, 0), + PriorYearActualValue02 = ISNULL(Month02, 0), + PriorYearActualValue03 = ISNULL(Month03, 0), + PriorYearActualValue04 = ISNULL(Month04, 0), + PriorYearActualValue05 = ISNULL(Month05, 0), + PriorYearActualValue06 = ISNULL(Month06, 0), + PriorYearActualValue07 = ISNULL(Month07, 0), + PriorYearActualValue08 = ISNULL(Month08, 0), + PriorYearActualValue09 = ISNULL(Month09, 0), + PriorYearActualValue10 = ISNULL(Month10, 0), + PriorYearActualValue11 = ISNULL(Month11, 0), + PriorYearActualValue12 = ISNULL(Month12, 0) + FROM + [fp].[FactBenefitsHistory] fbh + INNER JOIN [fp].[FactBenefits] fb ON fb.BenefitsID = fbh.BenefitsID + INNER JOIN + (SELECT gl.DepartmentID, gl.AccountID, fm.MonthColumnName, SUM(Value * acc.Inversion) as Value + FROM [int].[FactGL] gl + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = gl.FiscalMonthID + INNER JOIN [fw].[DimAccount] acc on acc.AccountID = gl.AccountID + WHERE gl.FiscalYearID = (@CurrentFiscalYearID - 1) AND gl.TimeclassID = 1 AND gl.IsDeleted = 0 AND gl.FiscalMonthID != 0 + GROUP BY gl.DepartmentID, gl.AccountID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv + ON fb.DepartmentID = pv.DepartmentID + AND fb.AccountID = pv.AccountID + INNER JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID + WHERE + fb.EntityGroupConfigID = @EntityGroupConfigID + AND fb.UnitTypeID = 34 + + + -- set all of the values for current year actual/annualized + UPDATE + fbh + SET + ActualYTDValue01 = ISNULL(Month01, 0), + ActualYTDValue02 = ISNULL(Month02, 0), + ActualYTDValue03 = ISNULL(Month03, 0), + ActualYTDValue04 = ISNULL(Month04, 0), + ActualYTDValue05 = ISNULL(Month05, 0), + ActualYTDValue06 = ISNULL(Month06, 0), + ActualYTDValue07 = ISNULL(Month07, 0), + ActualYTDValue08 = ISNULL(Month08, 0), + ActualYTDValue09 = ISNULL(Month09, 0), + ActualYTDValue10 = ISNULL(Month10, 0), + ActualYTDValue11 = ISNULL(Month11, 0), + ActualYTDValue12 = ISNULL(Month12, 0) + FROM + [fp].[FactBenefitsHistory] fbh + INNER JOIN [fp].[FactBenefits] fb ON fb.BenefitsID = fbh.BenefitsID + INNER JOIN + (SELECT gl.DepartmentID, gl.AccountID, fm.MonthColumnName, SUM(Value * acc.Inversion) as Value + FROM [int].[FactGL] gl + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = gl.FiscalMonthID + INNER JOIN [fw].[DimAccount] acc on acc.AccountID = gl.AccountID + WHERE gl.FiscalYearID = @CurrentFiscalYearID AND gl.TimeclassID = 1 AND gl.IsDeleted = 0 AND gl.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded + GROUP BY gl.DepartmentID, gl.AccountID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv + ON fb.DepartmentID = pv.DepartmentID + AND fb.AccountID = pv.AccountID + INNER JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID + WHERE + fb.EntityGroupConfigID = @EntityGroupConfigID + AND fb.UnitTypeID = 34 + + + -- set all of the values for current year budget + UPDATE + fbh + SET + CurrentYearBudget01 = ISNULL(Month01, 0), + CurrentYearBudget02 = ISNULL(Month02, 0), + CurrentYearBudget03 = ISNULL(Month03, 0), + CurrentYearBudget04 = ISNULL(Month04, 0), + CurrentYearBudget05 = ISNULL(Month05, 0), + CurrentYearBudget06 = ISNULL(Month06, 0), + CurrentYearBudget07 = ISNULL(Month07, 0), + CurrentYearBudget08 = ISNULL(Month08, 0), + CurrentYearBudget09 = ISNULL(Month09, 0), + CurrentYearBudget10 = ISNULL(Month10, 0), + CurrentYearBudget11 = ISNULL(Month11, 0), + CurrentYearBudget12 = ISNULL(Month12, 0) + FROM + [fp].[FactBenefitsHistory] fbh + INNER JOIN [fp].[FactBenefits] fb ON fb.BenefitsID = fbh.BenefitsID + INNER JOIN + (SELECT gl.DepartmentID, gl.AccountID, fm.MonthColumnName, SUM(Value * acc.Inversion) as Value + FROM [int].[FactGL] gl + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = gl.FiscalMonthID + INNER JOIN [fw].[DimAccount] acc on acc.AccountID = gl.AccountID + WHERE gl.FiscalYearID = @CurrentFiscalYearID AND gl.TimeclassID = 2 AND gl.IsDeleted = 0 AND gl.FiscalMonthID != 0 + GROUP BY gl.DepartmentID, gl.AccountID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv + ON fb.DepartmentID = pv.DepartmentID + AND fb.AccountID = pv.AccountID + INNER JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID + WHERE + fb.EntityGroupConfigID = @EntityGroupConfigID + AND fb.UnitTypeID = 34 + + +END +GO + + +--------------------------------------------- + +-- fp.procSampleBenefitsHistoricalFTEs +/************************************************************** +** Change History +** CID Date Author WI Description +** 1 2022-09-08 BW JAZZ-41678 Insert the assignment config's jc/pcg detail into a temp table for the @PayrollFilterSQL to join on +*************************************************************/ +CREATE PROCEDURE fp.procSampleBenefitsHistoricalFTEs + @EntityGroupConfigID INT, + @AccountID INT, + @FinancialReportingID INT, + @CurrentYearID INT, + @MonthsLoaded INT, + @PayrollFilterSql NVARCHAR(MAX), + @PayrollFilterTempTableSQL VARCHAR(MAX) + WITH RECOMPILE + AS + BEGIN + + DECLARE @PreviousYear INT + DECLARE @DriverUnitTypeID INT + DECLARE @SourceUnitTypeID INT + + SET @PreviousYear = @CurrentYearID - 1 + SET @SourceUnitTypeID = 51 -- hours + SET @DriverUnitTypeID = 144 -- ftes + + IF object_id('tempdb..#basisIDs') IS NOT NULL + BEGIN + DROP TABLE #basisIDs + END + IF object_id('tempdb..#StaffingFtes') IS NOT NULL + BEGIN + DROP TABLE #StaffingFtes + END + + CREATE TABLE #basisIDs (BenefitsID INT); + CREATE TABLE #StaffingFtes (EntityID INT, DepartmentID INT, AccountID INT, FinancialReportingID INT, UnitTypeID INT, + Value01 DECIMAL(19, 8), Value02 DECIMAL(19, 8), Value03 DECIMAL(19, 8), Value04 DECIMAL(19, 8), + Value05 DECIMAL(19, 8), Value06 DECIMAL(19, 8), Value07 DECIMAL(19, 8), Value08 DECIMAL(19, 8), + Value09 DECIMAL(19, 8), Value10 DECIMAL(19, 8), Value11 DECIMAL(19, 8), Value12 DECIMAL(19, 8)) + EXEC [dbo].[procSysDropTempTable] '#jcpcgFilterTable' + CREATE TABLE #jcpcgFilterTable (JobCodeID INT, JobCodeGroupID INT, PayCodeGroupID INT, ProductiveClassID INT ) + + EXEC(' ' + @PayrollFilterTempTableSQL + ' ') + + -- PriorYearActual + EXEC(' + INSERT INTO #StaffingFtes + SELECT + d.EntityID, + pr.DepartmentID, + ' + @AccountID + ' as AccountID, + ' + @FinancialReportingID + ' as FinancialReportingID, + ' + @DriverUnitTypeID + ' as UnitTypeID, + SUM(pr.Month01) / MAX(wh.Month01) AS Value01, + SUM(pr.Month02) / MAX(wh.Month02) AS Value02, + SUM(pr.Month03) / MAX(wh.Month03) AS Value03, + SUM(pr.Month04) / MAX(wh.Month04) AS Value04, + SUM(pr.Month05) / MAX(wh.Month05) AS Value05, + SUM(pr.Month06) / MAX(wh.Month06) AS Value06, + SUM(pr.Month07) / MAX(wh.Month07) AS Value07, + SUM(pr.Month08) / MAX(wh.Month08) AS Value08, + SUM(pr.Month09) / MAX(wh.Month09) AS Value09, + SUM(pr.Month10) / MAX(wh.Month10) AS Value10, + SUM(pr.Month11) / MAX(wh.Month11) AS Value11, + SUM(pr.Month12) / MAX(wh.Month12) AS Value12 + FROM [int].[viewFactStaffingValuesPivoted] pr + INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID + INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID + INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = pr.PayCodeID + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on pc.PayCodeGroupID = exc.PayCodeGroupID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh + ON wh.FiscalYearID = ' + @PreviousYear + ' + AND wh.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END) + WHERE + pr.UnitTypeID = ' + @SourceUnitTypeID + ' -- Hours + AND pr.FiscalYearID = ' + @PreviousYear + ' + AND pr.TimeClassID = 1 + AND exc.PayCodeGroupID IS NULL + AND pc.IsHoursIgnored = 0 + AND ' + @PayrollFilterSql + ' + GROUP BY + pr.DepartmentID, + d.EntityID + + -- Update Original Value + UPDATE hist + SET + PriorYearActualValue01 = Value01, PriorYearActualValue02 = Value02, PriorYearActualValue03 = Value03, PriorYearActualValue04 = Value04, + PriorYearActualValue05 = Value05, PriorYearActualValue06 = Value06, PriorYearActualValue07 = Value07, PriorYearActualValue08 = Value08, + PriorYearActualValue09 = Value09, PriorYearActualValue10 = Value10, PriorYearActualValue11 = Value11, PriorYearActualValue12 = Value12 + OUTPUT INSERTED.BenefitsID + INTO #basisIDs(BenefitsID) + FROM [fp].[FactBenefitsHistory] hist + INNER JOIN [fp].[FactBenefits] benefits ON hist.BenefitsID = benefits.BenefitsID + INNER JOIN #StaffingFtes staffing ON + staffing.EntityID = benefits.EntityID + AND staffing.DepartmentID = benefits.DepartmentID + AND staffing.AccountID = benefits.AccountID + AND staffing.FinancialReportingID = benefits.FinancialReportingID + AND staffing.UnitTypeID = benefits.UnitTypeID + WHERE benefits.EntityGroupConfigID = ' + @EntityGroupConfigID + ' + '); + + TRUNCATE TABLE #StaffingFtes + + -- ActualYTD + EXEC(' + INSERT INTO #StaffingFtes + SELECT + d.EntityID, + pr.DepartmentID, + ' + @AccountID + ' as AccountID, + ' + @FinancialReportingID + ' as FinancialReportingID, + ' + @DriverUnitTypeID + ' as UnitTypeID, + SUM(pr.Month01) / MAX(wh.Month01) AS Value01, + SUM(pr.Month02) / MAX(wh.Month02) AS Value02, + SUM(pr.Month03) / MAX(wh.Month03) AS Value03, + SUM(pr.Month04) / MAX(wh.Month04) AS Value04, + SUM(pr.Month05) / MAX(wh.Month05) AS Value05, + SUM(pr.Month06) / MAX(wh.Month06) AS Value06, + SUM(pr.Month07) / MAX(wh.Month07) AS Value07, + SUM(pr.Month08) / MAX(wh.Month08) AS Value08, + SUM(pr.Month09) / MAX(wh.Month09) AS Value09, + SUM(pr.Month10) / MAX(wh.Month10) AS Value10, + SUM(pr.Month11) / MAX(wh.Month11) AS Value11, + SUM(pr.Month12) / MAX(wh.Month12) AS Value12 + FROM [int].[viewFactStaffingYTDValuesPivoted] (' + @MonthsLoaded + ') pr + INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID + INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID + INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = pr.PayCodeID + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on pc.PayCodeGroupID = exc.PayCodeGroupID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh + ON wh.FiscalYearID = ' + @CurrentYearID + ' + AND wh.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END) + WHERE + pr.UnitTypeID = ' + @SourceUnitTypeID + ' -- Hours + AND pr.FiscalYearID = ' + @CurrentYearID + ' + AND pr.TimeClassID = 1 + AND exc.PayCodeGroupID IS NULL + AND pc.IsHoursIgnored = 0 + AND ' + @PayrollFilterSql + ' + GROUP BY + pr.DepartmentID, + d.EntityID + + -- Update Original Value + UPDATE hist + SET + ActualYTDValue01 = Value01, ActualYTDValue02 = Value02, ActualYTDValue03 = Value03, ActualYTDValue04 = Value04, + ActualYTDValue05 = Value05, ActualYTDValue06 = Value06, ActualYTDValue07 = Value07, ActualYTDValue08 = Value08, + ActualYTDValue09 = Value09, ActualYTDValue10 = Value10, ActualYTDValue11 = Value11, ActualYTDValue12 = Value12 + OUTPUT INSERTED.BenefitsID + INTO #basisIDs(BenefitsID) + FROM [fp].[FactBenefitsHistory] hist + INNER JOIN [fp].[FactBenefits] benefits ON hist.BenefitsID = benefits.BenefitsID + INNER JOIN #StaffingFtes staffing ON + staffing.EntityID = benefits.EntityID + AND staffing.DepartmentID = benefits.DepartmentID + AND staffing.AccountID = benefits.AccountID + AND staffing.FinancialReportingID = benefits.FinancialReportingID + AND staffing.UnitTypeID = benefits.UnitTypeID + WHERE benefits.EntityGroupConfigID = ' + @EntityGroupConfigID + ' + '); + + TRUNCATE TABLE #StaffingFtes + + -- CurrentYearBudget + EXEC(' + INSERT INTO #StaffingFtes + SELECT + d.EntityID, + pr.DepartmentID, + ' + @AccountID + ' as AccountID, + ' + @FinancialReportingID + ' as FinancialReportingID, + ' + @DriverUnitTypeID + ' as UnitTypeID, + SUM(pr.Month01) / MAX(wh.Month01) AS Value01, + SUM(pr.Month02) / MAX(wh.Month02) AS Value02, + SUM(pr.Month03) / MAX(wh.Month03) AS Value03, + SUM(pr.Month04) / MAX(wh.Month04) AS Value04, + SUM(pr.Month05) / MAX(wh.Month05) AS Value05, + SUM(pr.Month06) / MAX(wh.Month06) AS Value06, + SUM(pr.Month07) / MAX(wh.Month07) AS Value07, + SUM(pr.Month08) / MAX(wh.Month08) AS Value08, + SUM(pr.Month09) / MAX(wh.Month09) AS Value09, + SUM(pr.Month10) / MAX(wh.Month10) AS Value10, + SUM(pr.Month11) / MAX(wh.Month11) AS Value11, + SUM(pr.Month12) / MAX(wh.Month12) AS Value12 + FROM [int].[viewFactStaffingValuesPivoted] pr + INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID + INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID + INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = pr.PayCodeID + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on pc.PayCodeGroupID = exc.PayCodeGroupID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh + ON wh.FiscalYearID = ' + @CurrentYearID + ' + AND wh.WorkWeekID = (CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID ELSE d.WorkWeekID END) + WHERE + pr.UnitTypeID = ' + @SourceUnitTypeID + ' -- Hours + AND pr.FiscalYearID = ' + @CurrentYearID + ' + AND pr.TimeClassID = 2 + AND exc.PayCodeGroupID IS NULL + AND pc.IsHoursIgnored = 0 + AND ' + @PayrollFilterSql + ' + GROUP BY + pr.DepartmentID, + d.EntityID + + -- Update Original Value + UPDATE hist + SET + CurrentYearBudget01 = Value01, CurrentYearBudget02 = Value02, CurrentYearBudget03 = Value03, CurrentYearBudget04 = Value04, + CurrentYearBudget05 = Value05, CurrentYearBudget06 = Value06, CurrentYearBudget07 = Value07, CurrentYearBudget08 = Value08, + CurrentYearBudget09 = Value09, CurrentYearBudget10 = Value10, CurrentYearBudget11 = Value11, CurrentYearBudget12 = Value12 + OUTPUT INSERTED.BenefitsID + INTO #basisIDs(BenefitsID) + FROM [fp].[FactBenefitsHistory] hist + INNER JOIN [fp].[FactBenefits] benefits ON hist.BenefitsID = benefits.BenefitsID + INNER JOIN #StaffingFtes staffing ON + staffing.EntityID = benefits.EntityID + AND staffing.DepartmentID = benefits.DepartmentID + AND staffing.AccountID = benefits.AccountID + AND staffing.FinancialReportingID = benefits.FinancialReportingID + AND staffing.UnitTypeID = benefits.UnitTypeID + WHERE benefits.EntityGroupConfigID = ' + @EntityGroupConfigID + ' + '); + + END +GO + + +--------------------------------------------- + +-- fp.procSampleBenefitsHistoricalSalaries +/************************************************************** +** Change History +** CID Date Author WI Description +** 1 2022-09-07 BW JAZZ-41678 Insert the assignment config's jc/pcg detail into a temp table for the @PayrollFilterSQL to join on +*************************************************************/ +CREATE PROCEDURE fp.procSampleBenefitsHistoricalSalaries + @EntityGroupConfigID INT, + @AccountID INT, + @FinancialReportingID INT, + @CurrentYearID INT, + @MonthsLoaded INT, + @PayrollFilterSql NVARCHAR(MAX), + @PayrollFilterTempTableSQL VARCHAR(MAX) + AS + BEGIN + + DECLARE @PreviousYear INT + DECLARE @DriverUnitTypeID INT + DECLARE @SourceUnitTypeID INT + + SET @PreviousYear = @CurrentYearID - 1 + SET @SourceUnitTypeID = 34 -- dollars + SET @DriverUnitTypeID = 169 -- salaries + + + IF object_id('tempdb..#basisIDs') IS NOT NULL + BEGIN + DROP TABLE #basisIDs + END + IF object_id('tempdb..#StaffingSalaries') IS NOT NULL + BEGIN + DROP TABLE #StaffingSalaries + END + + CREATE TABLE #basisIDs (BenefitsID INT); + CREATE TABLE #StaffingSalaries (EntityID INT, DepartmentID INT, AccountID INT, FinancialReportingID INT, UnitTypeID INT, + Value01 DECIMAL(19, 8), Value02 DECIMAL(19, 8), Value03 DECIMAL(19, 8), Value04 DECIMAL(19, 8), + Value05 DECIMAL(19, 8), Value06 DECIMAL(19, 8), Value07 DECIMAL(19, 8), Value08 DECIMAL(19, 8), + Value09 DECIMAL(19, 8), Value10 DECIMAL(19, 8), Value11 DECIMAL(19, 8), Value12 DECIMAL(19, 8)) + + EXEC [dbo].[procSysDropTempTable] '#jcpcgFilterTable' + CREATE TABLE #jcpcgFilterTable (JobCodeID INT, JobCodeGroupID INT, PayCodeGroupID INT, ProductiveClassID INT ) + + EXEC(' ' + @PayrollFilterTempTableSQL + ' ') + + -- PriorYearActual + EXEC(' + INSERT INTO #StaffingSalaries + SELECT + d.EntityID, + pr.DepartmentID, + ' + @AccountID + ' as AccountID, + ' + @FinancialReportingID + ' as FinancialReportingID, + ' + @DriverUnitTypeID + ' as UnitTypeID, + SUM(pr.Month01) AS Value01, + SUM(pr.Month02) AS Value02, + SUM(pr.Month03) AS Value03, + SUM(pr.Month04) AS Value04, + SUM(pr.Month05) AS Value05, + SUM(pr.Month06) AS Value06, + SUM(pr.Month07) AS Value07, + SUM(pr.Month08) AS Value08, + SUM(pr.Month09) AS Value09, + SUM(pr.Month10) AS Value10, + SUM(pr.Month11) AS Value11, + SUM(pr.Month12) AS Value12 + FROM [int].[viewFactStaffingValuesPivoted] pr + INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID + INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID + INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = pr.PayCodeID + WHERE + pr.UnitTypeID = ' + @SourceUnitTypeID + ' -- Hours + AND pr.FiscalYearID = ' + @PreviousYear + ' + AND pr.TimeClassID = 1 + AND ' + @PayrollFilterSql + ' + GROUP BY + pr.DepartmentID, + d.EntityID + + -- Update Original Value + UPDATE hist + SET + PriorYearActualValue01 = Value01, PriorYearActualValue02 = Value02, PriorYearActualValue03 = Value03, PriorYearActualValue04 = Value04, + PriorYearActualValue05 = Value05, PriorYearActualValue06 = Value06, PriorYearActualValue07 = Value07, PriorYearActualValue08 = Value08, + PriorYearActualValue09 = Value09, PriorYearActualValue10 = Value10, PriorYearActualValue11 = Value11, PriorYearActualValue12 = Value12 + OUTPUT INSERTED.BenefitsID + INTO #basisIDs(BenefitsID) + FROM [fp].[FactBenefitsHistory] hist + INNER JOIN [fp].[FactBenefits] benefits ON hist.BenefitsID = benefits.BenefitsID + INNER JOIN #StaffingSalaries staffing ON + staffing.EntityID = benefits.EntityID + AND staffing.DepartmentID = benefits.DepartmentID + AND staffing.AccountID = benefits.AccountID + AND staffing.FinancialReportingID = benefits.FinancialReportingID + AND staffing.UnitTypeID = benefits.UnitTypeID + WHERE benefits.EntityGroupConfigID = ' + @EntityGroupConfigID + ' + '); + + TRUNCATE TABLE #StaffingSalaries + + -- ActualYTD + EXEC(' + INSERT INTO #StaffingSalaries + SELECT + d.EntityID, + pr.DepartmentID, + ' + @AccountID + ' as AccountID, + ' + @FinancialReportingID + ' as FinancialReportingID, + ' + @DriverUnitTypeID + ' as UnitTypeID, + SUM(pr.Month01) AS Value01, + SUM(pr.Month02) AS Value02, + SUM(pr.Month03) AS Value03, + SUM(pr.Month04) AS Value04, + SUM(pr.Month05) AS Value05, + SUM(pr.Month06) AS Value06, + SUM(pr.Month07) AS Value07, + SUM(pr.Month08) AS Value08, + SUM(pr.Month09) AS Value09, + SUM(pr.Month10) AS Value10, + SUM(pr.Month11) AS Value11, + SUM(pr.Month12) AS Value12 + FROM [int].[viewFactStaffingYTDValuesPivoted] (' + @MonthsLoaded + ') pr + INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID + INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID + INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = pr.PayCodeID + WHERE + pr.UnitTypeID = ' + @SourceUnitTypeID + ' -- Hours + AND pr.FiscalYearID = ' + @CurrentYearID + ' + AND pr.TimeClassID = 1 + AND ' + @PayrollFilterSql + ' + GROUP BY + pr.DepartmentID, + d.EntityID + + -- Update Original Value + UPDATE hist + SET + ActualYTDValue01 = Value01, ActualYTDValue02 = Value02, ActualYTDValue03 = Value03, ActualYTDValue04 = Value04, + ActualYTDValue05 = Value05, ActualYTDValue06 = Value06, ActualYTDValue07 = Value07, ActualYTDValue08 = Value08, + ActualYTDValue09 = Value09, ActualYTDValue10 = Value10, ActualYTDValue11 = Value11, ActualYTDValue12 = Value12 + OUTPUT INSERTED.BenefitsID + INTO #basisIDs(BenefitsID) + FROM [fp].[FactBenefitsHistory] hist + INNER JOIN [fp].[FactBenefits] benefits ON hist.BenefitsID = benefits.BenefitsID + INNER JOIN #StaffingSalaries staffing ON + staffing.EntityID = benefits.EntityID + AND staffing.DepartmentID = benefits.DepartmentID + AND staffing.AccountID = benefits.AccountID + AND staffing.FinancialReportingID = benefits.FinancialReportingID + AND staffing.UnitTypeID = benefits.UnitTypeID + WHERE benefits.EntityGroupConfigID = ' + @EntityGroupConfigID + ' + '); + + TRUNCATE TABLE #StaffingSalaries + + -- CurrentYearBudget + EXEC(' + INSERT INTO #StaffingSalaries + SELECT + d.EntityID, + pr.DepartmentID, + ' + @AccountID + ' as AccountID, + ' + @FinancialReportingID + ' as FinancialReportingID, + ' + @DriverUnitTypeID + ' as UnitTypeID, + SUM(pr.Month01) AS Value01, + SUM(pr.Month02) AS Value02, + SUM(pr.Month03) AS Value03, + SUM(pr.Month04) AS Value04, + SUM(pr.Month05) AS Value05, + SUM(pr.Month06) AS Value06, + SUM(pr.Month07) AS Value07, + SUM(pr.Month08) AS Value08, + SUM(pr.Month09) AS Value09, + SUM(pr.Month10) AS Value10, + SUM(pr.Month11) AS Value11, + SUM(pr.Month12) AS Value12 + FROM [int].[viewFactStaffingValuesPivoted] pr + INNER JOIN [fw].[DimDepartment] d on d.DepartmentID = pr.DepartmentID + INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = pr.JobCodeID + INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = pr.PayCodeID + WHERE + pr.UnitTypeID = ' + @SourceUnitTypeID + ' -- Hours + AND pr.FiscalYearID = ' + @CurrentYearID + ' + AND pr.TimeClassID = 2 + AND ' + @PayrollFilterSql + ' + GROUP BY + pr.DepartmentID, + d.EntityID + + -- Update Original Value + UPDATE hist + SET + CurrentYearBudget01 = Value01, CurrentYearBudget02 = Value02, CurrentYearBudget03 = Value03, CurrentYearBudget04 = Value04, + CurrentYearBudget05 = Value05, CurrentYearBudget06 = Value06, CurrentYearBudget07 = Value07, CurrentYearBudget08 = Value08, + CurrentYearBudget09 = Value09, CurrentYearBudget10 = Value10, CurrentYearBudget11 = Value11, CurrentYearBudget12 = Value12 + OUTPUT INSERTED.BenefitsID + INTO #basisIDs(BenefitsID) + FROM [fp].[FactBenefitsHistory] hist + INNER JOIN [fp].[FactBenefits] benefits ON hist.BenefitsID = benefits.BenefitsID + INNER JOIN #StaffingSalaries staffing ON + staffing.EntityID = benefits.EntityID + AND staffing.DepartmentID = benefits.DepartmentID + AND staffing.AccountID = benefits.AccountID + AND staffing.FinancialReportingID = benefits.FinancialReportingID + AND staffing.UnitTypeID = benefits.UnitTypeID + WHERE benefits.EntityGroupConfigID = ' + @EntityGroupConfigID + ' + '); + + END +GO + + +--------------------------------------------- + +-- fp.procSampleBenefitsOriginalBudgetDollars +CREATE PROCEDURE [fp].[procSampleBenefitsOriginalBudgetDollars] + @BudgetConfigID int, + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @SourceFiscalYearID smallint, + @SourceTimeClassID tinyint, + @MonthsLoaded int +AS +BEGIN + + DECLARE @IsAnnualized bit = (CASE WHEN @SourceFiscalYearID = @CurrentFiscalYearID AND @SourceTimeClassID = 1 THEN 1 ELSE 0 END) + + UPDATE fb SET + SampledBudget01 = ISNULL(Month01, 0), + SampledBudget02 = ISNULL(Month02, 0), + SampledBudget03 = ISNULL(Month03, 0), + SampledBudget04 = ISNULL(Month04, 0), + SampledBudget05 = ISNULL(Month05, 0), + SampledBudget06 = ISNULL(Month06, 0), + SampledBudget07 = ISNULL(Month07, 0), + SampledBudget08 = ISNULL(Month08, 0), + SampledBudget09 = ISNULL(Month09, 0), + SampledBudget10 = ISNULL(Month10, 0), + SampledBudget11 = ISNULL(Month11, 0), + SampledBudget12 = ISNULL(Month12, 0) + FROM [fp].[FactBenefits] fb INNER JOIN + (SELECT gl.DepartmentID, gl.AccountID, fm.MonthColumnName, SUM(Value * acc.Inversion) as Value + FROM [int].[FactGL] gl + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = gl.FiscalMonthID + INNER JOIN [fw].[DimAccount] acc on acc.AccountID = gl.AccountID + WHERE gl.FiscalYearID = @SourceFiscalYearID AND gl.TimeClassID = @SourceTimeClassID + AND gl.IsDeleted = 0 AND gl.FiscalMonthID != 0 + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + GROUP BY gl.DepartmentID, gl.AccountID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON fb.DepartmentID = pv.DepartmentID + AND fb.AccountID = pv.AccountID + WHERE fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.UnitTypeID = 34 + + +-- if the source fiscal year = current fiscal year and timeclass is actual, we need to annualize the data + IF(@IsAnnualized = 1 AND @MonthsLoaded < 12) + BEGIN + -- per stackoverflow (per MY) + DECLARE @IsLeapYear BIT = (CASE WHEN (@SourceFiscalYearID % 4 = 0 AND @SourceFiscalYearID % 100 <> 0) OR @SourceFiscalYearID % 400 = 0 THEN 1 ELSE 0 END) + DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded) + DECLARE @DaysInMonthsNotLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder > @MonthsLoaded) + + UPDATE + fb + SET + SampledBudget02 = CASE WHEN @MonthsLoaded >= 2 THEN SampledBudget02 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END, + SampledBudget03 = CASE WHEN @MonthsLoaded >= 3 THEN SampledBudget03 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END, + SampledBudget04 = CASE WHEN @MonthsLoaded >= 4 THEN SampledBudget04 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END, + SampledBudget05 = CASE WHEN @MonthsLoaded >= 5 THEN SampledBudget05 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END, + SampledBudget06 = CASE WHEN @MonthsLoaded >= 6 THEN SampledBudget06 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END, + SampledBudget07 = CASE WHEN @MonthsLoaded >= 7 THEN SampledBudget07 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END, + SampledBudget08 = CASE WHEN @MonthsLoaded >= 8 THEN SampledBudget08 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END, + SampledBudget09 = CASE WHEN @MonthsLoaded >= 9 THEN SampledBudget09 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END, + SampledBudget10 = CASE WHEN @MonthsLoaded >= 10 THEN SampledBudget10 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END, + SampledBudget11 = CASE WHEN @MonthsLoaded >= 11 THEN SampledBudget11 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END, + SampledBudget12 = CASE WHEN @MonthsLoaded >= 12 THEN SampledBudget12 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END + FROM [fp].[FactBenefits] fb + WHERE fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.UnitTypeID = 34 + + + END + + -- update the initial values to be equal to the sampled values + UPDATE + fb + SET + InitialBudget01 = SampledBudgetTotal / 12, + InitialBudget02 = SampledBudgetTotal / 12, + InitialBudget03 = SampledBudgetTotal / 12, + InitialBudget04 = SampledBudgetTotal / 12, + InitialBudget05 = SampledBudgetTotal / 12, + InitialBudget06 = SampledBudgetTotal / 12, + InitialBudget07 = SampledBudgetTotal / 12, + InitialBudget08 = SampledBudgetTotal / 12, + InitialBudget09 = SampledBudgetTotal / 12, + InitialBudget10 = SampledBudgetTotal / 12, + InitialBudget11 = SampledBudgetTotal / 12, + InitialBudget12 = SampledBudgetTotal - (SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12) + FROM + [fp].[FactBenefits] fb + WHERE + fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.UnitTypeID = 34 +END +GO + + +--------------------------------------------- + +-- fp.procSampleBenefitsOriginalBudgetDollars_WithNewAnnualization +CREATE PROCEDURE [fp].[procSampleBenefitsOriginalBudgetDollars_WithNewAnnualization] + @BudgetConfigID int, + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @SourceFiscalYearID smallint, + @SourceTimeClassID tinyint, + @MonthsLoaded int +AS +BEGIN +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2024-07-24 BK JAZZ-74600 Create new proc that is used when BudgetConfig FF is on +**************************************************************/ + + DECLARE @IsAnnualized bit = (CASE WHEN @SourceFiscalYearID = @CurrentFiscalYearID AND @SourceTimeClassID = 1 THEN 1 ELSE 0 END) + + UPDATE fb SET + SampledBudget01 = ISNULL(Month01, 0), + SampledBudget02 = ISNULL(Month02, 0), + SampledBudget03 = ISNULL(Month03, 0), + SampledBudget04 = ISNULL(Month04, 0), + SampledBudget05 = ISNULL(Month05, 0), + SampledBudget06 = ISNULL(Month06, 0), + SampledBudget07 = ISNULL(Month07, 0), + SampledBudget08 = ISNULL(Month08, 0), + SampledBudget09 = ISNULL(Month09, 0), + SampledBudget10 = ISNULL(Month10, 0), + SampledBudget11 = ISNULL(Month11, 0), + SampledBudget12 = ISNULL(Month12, 0) + FROM [fp].[FactBenefits] fb INNER JOIN + (SELECT gl.DepartmentID, gl.AccountID, fm.MonthColumnName, SUM(Value * acc.Inversion) as Value + FROM [int].[FactGL] gl + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = gl.FiscalMonthID + INNER JOIN [fw].[DimAccount] acc on acc.AccountID = gl.AccountID + WHERE gl.FiscalYearID = @SourceFiscalYearID AND gl.TimeClassID = @SourceTimeClassID + AND gl.IsDeleted = 0 AND gl.FiscalMonthID != 0 + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + GROUP BY gl.DepartmentID, gl.AccountID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON fb.DepartmentID = pv.DepartmentID + AND fb.AccountID = pv.AccountID + WHERE fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.UnitTypeID = 34 + + +-- if the source fiscal year = current fiscal year and timeclass is actual, we need to annualize the data + IF(@IsAnnualized = 1 AND @MonthsLoaded < 12) + BEGIN + -- per stackoverflow (per MY) + DECLARE @IsLeapYear BIT = (CASE WHEN (@SourceFiscalYearID % 4 = 0 AND @SourceFiscalYearID % 100 <> 0) OR @SourceFiscalYearID % 400 = 0 THEN 1 ELSE 0 END) + + DECLARE @IsBudgetLeapYear BIT = (CASE WHEN ((@CurrentFiscalYearID + 1) % 4 = 0 AND (@CurrentFiscalYearID + 1) % 100 <> 0) OR (@CurrentFiscalYearID + 1) % 400 = 0 THEN 1 ELSE 0 END) + DECLARE @DaysBudgetYear decimal = (SELECT (CASE WHEN @IsBudgetLeapYear = 1 THEN YTDDaysInLeapYearMonth ELSE YTDDaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder = 12) + + DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded) + DECLARE @DaysInMonthsNotLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder > @MonthsLoaded) + + UPDATE + fb + SET + SampledBudget01 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget02 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget03 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget04 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget05 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget06 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget07 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget08 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget09 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget10 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget11 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget12 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget01 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget02 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget03 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget04 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget05 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget06 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget07 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget08 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget09 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget10 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget11 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget12 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12 + FROM [fp].[FactBenefits] fb + WHERE fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.UnitTypeID = 34 + + + END + ELSE BEGIN + -- update the initial values to be equal to the sampled values - only if not annualized, since we are doing that above in the same sql stmt + UPDATE + fb + SET + InitialBudget01 = SampledBudgetTotal / 12, + InitialBudget02 = SampledBudgetTotal / 12, + InitialBudget03 = SampledBudgetTotal / 12, + InitialBudget04 = SampledBudgetTotal / 12, + InitialBudget05 = SampledBudgetTotal / 12, + InitialBudget06 = SampledBudgetTotal / 12, + InitialBudget07 = SampledBudgetTotal / 12, + InitialBudget08 = SampledBudgetTotal / 12, + InitialBudget09 = SampledBudgetTotal / 12, + InitialBudget10 = SampledBudgetTotal / 12, + InitialBudget11 = SampledBudgetTotal / 12, + InitialBudget12 = SampledBudgetTotal - (SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12 + SampledBudgetTotal/12) + FROM + [fp].[FactBenefits] fb + WHERE + fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.UnitTypeID = 34 + + END + +END +GO + + +--------------------------------------------- + +-- fp.procSampleBenefitsOriginalProjectionDollars +CREATE PROCEDURE [fp].[procSampleBenefitsOriginalProjectionDollars] + @BudgetConfigID int, + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @SourceFiscalYearID smallint, + @SourceTimeClassID tinyint, + @MonthsLoaded int +AS +BEGIN + + UPDATE fb SET + SampledProjection01 = ISNULL(Month01, 0), + SampledProjection02 = ISNULL(Month02, 0), + SampledProjection03 = ISNULL(Month03, 0), + SampledProjection04 = ISNULL(Month04, 0), + SampledProjection05 = ISNULL(Month05, 0), + SampledProjection06 = ISNULL(Month06, 0), + SampledProjection07 = ISNULL(Month07, 0), + SampledProjection08 = ISNULL(Month08, 0), + SampledProjection09 = ISNULL(Month09, 0), + SampledProjection10 = ISNULL(Month10, 0), + SampledProjection11 = ISNULL(Month11, 0), + SampledProjection12 = ISNULL(Month12, 0) + FROM [fp].[FactBenefits] fb INNER JOIN + (SELECT gl.DepartmentID, gl.AccountID, fm.MonthColumnName, SUM(Value * acc.Inversion) as Value + FROM [int].[FactGL] gl + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = gl.FiscalMonthID + INNER JOIN [fw].[DimAccount] acc on acc.AccountID = gl.AccountID + WHERE gl.FiscalYearID = @SourceFiscalYearID AND gl.TimeClassID = @SourceTimeClassID AND gl.IsDeleted = 0 AND gl.FiscalMonthID != 0 + AND fm.SortOrder <= @MonthsLoaded + GROUP BY gl.DepartmentID, gl.AccountID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON fb.DepartmentID = pv.DepartmentID + AND fb.AccountID = pv.AccountID + WHERE fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.UnitTypeID = 34 + + + + -- copy the baseline data over for months without data (month sort order > @MonthsLoaded) + -- if the baseline is current year actual YTD, then the data would already have been annualized, if not, then we don't need to annualize + UPDATE + fb + SET + SampledProjection02 = CASE WHEN @MonthsLoaded < 2 THEN SampledBudget02 ELSE SampledProjection02 END, + SampledProjection03 = CASE WHEN @MonthsLoaded < 3 THEN SampledBudget03 ELSE SampledProjection03 END, + SampledProjection04 = CASE WHEN @MonthsLoaded < 4 THEN SampledBudget04 ELSE SampledProjection04 END, + SampledProjection05 = CASE WHEN @MonthsLoaded < 5 THEN SampledBudget05 ELSE SampledProjection05 END, + SampledProjection06 = CASE WHEN @MonthsLoaded < 6 THEN SampledBudget06 ELSE SampledProjection06 END, + SampledProjection07 = CASE WHEN @MonthsLoaded < 7 THEN SampledBudget07 ELSE SampledProjection07 END, + SampledProjection08 = CASE WHEN @MonthsLoaded < 8 THEN SampledBudget08 ELSE SampledProjection08 END, + SampledProjection09 = CASE WHEN @MonthsLoaded < 9 THEN SampledBudget09 ELSE SampledProjection09 END, + SampledProjection10 = CASE WHEN @MonthsLoaded < 10 THEN SampledBudget10 ELSE SampledProjection10 END, + SampledProjection11 = CASE WHEN @MonthsLoaded < 11 THEN SampledBudget11 ELSE SampledProjection11 END, + SampledProjection12 = CASE WHEN @MonthsLoaded < 12 THEN SampledBudget12 ELSE SampledProjection12 END + FROM + [fp].[FactBenefits] fb + WHERE + fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.UnitTypeID = 34 + + -- Get total for months loaded + CREATE TABLE #Totals (BenefitsID INT, SampledProjectionTotal DECIMAL(19,8), NewValue DECIMAL(19,8)); + INSERT INTO #Totals (BenefitsID, SampledProjectionTotal) + SELECT BenefitsID, + CASE WHEN @MonthsLoaded = 11 THEN ben.SampledProjection12 + WHEN @MonthsLoaded = 10 THEN ben.SampledProjection11 + ben.SampledProjection12 + WHEN @MonthsLoaded = 9 THEN ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12 + WHEN @MonthsLoaded = 8 THEN ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12 + WHEN @MonthsLoaded = 7 THEN ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12 + WHEN @MonthsLoaded = 6 THEN ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12 + WHEN @MonthsLoaded = 5 THEN ben.SampledProjection06 + ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12 + WHEN @MonthsLoaded = 4 THEN ben.SampledProjection05 + ben.SampledProjection06 + ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12 + WHEN @MonthsLoaded = 3 THEN ben.SampledProjection04 + ben.SampledProjection05 + ben.SampledProjection06 + ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12 + WHEN @MonthsLoaded = 2 THEN ben.SampledProjection03 + ben.SampledProjection04 + ben.SampledProjection05 + ben.SampledProjection06 + ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12 + WHEN @MonthsLoaded = 1 THEN ben.SampledProjection02 + ben.SampledProjection03 + ben.SampledProjection04 + ben.SampledProjection05 + ben.SampledProjection06 + ben.SampledProjection07 + ben.SampledProjection08 + ben.SampledProjection09 + ben.SampledProjection10 + ben.SampledProjection11 + ben.SampledProjection12 + ELSE 0 + END + FROM [fp].[FactBenefits] ben + WHERE ben.EntityGroupConfigID = @EntityGroupConfigID AND ben.UnitTypeID = 34 + + + UPDATE a SET NewValue = SampledProjectionTotal / (12.0 - @MonthsLoaded) + FROM #Totals a + + UPDATE + ben + SET + InitialProjection01 = CASE WHEN @MonthsLoaded >= 1 THEN ben.SampledProjection01 ELSE t.NewValue END, + InitialProjection02 = CASE WHEN @MonthsLoaded >= 2 THEN ben.SampledProjection02 ELSE t.NewValue END, + InitialProjection03 = CASE WHEN @MonthsLoaded >= 3 THEN ben.SampledProjection03 ELSE t.NewValue END, + InitialProjection04 = CASE WHEN @MonthsLoaded >= 4 THEN ben.SampledProjection04 ELSE t.NewValue END, + InitialProjection05 = CASE WHEN @MonthsLoaded >= 5 THEN ben.SampledProjection05 ELSE t.NewValue END, + InitialProjection06 = CASE WHEN @MonthsLoaded >= 6 THEN ben.SampledProjection06 ELSE t.NewValue END, + InitialProjection07 = CASE WHEN @MonthsLoaded >= 7 THEN ben.SampledProjection07 ELSE t.NewValue END, + InitialProjection08 = CASE WHEN @MonthsLoaded >= 8 THEN ben.SampledProjection08 ELSE t.NewValue END, + InitialProjection09 = CASE WHEN @MonthsLoaded >= 9 THEN ben.SampledProjection09 ELSE t.NewValue END, + InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN ben.SampledProjection10 ELSE t.NewValue END, + InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN ben.SampledProjection11 ELSE t.NewValue END, + InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN ben.SampledProjection12 ELSE t.NewValue END + FROM [fp].[FactBenefits] ben INNER JOIN #Totals t on ben.BenefitsID = t.BenefitsID + WHERE ben.EntityGroupConfigID = @EntityGroupConfigID + + +END +GO + + +--------------------------------------------- + +-- fp.procSampleBenefitsOriginalProjectionDollars_WithNewAnnualization +CREATE PROCEDURE [fp].[procSampleBenefitsOriginalProjectionDollars_WithNewAnnualization] + @BudgetConfigID int, + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @SourceFiscalYearID smallint, + @SourceTimeClassID tinyint, + @MonthsLoaded int +AS +BEGIN +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2024-07-24 BK JAZZ-74600 Create new proc that is used when BudgetConfig FF is on +** 2 2024-08-07 BK JAZZ-75213 Add check if using annualization +**************************************************************/ + + UPDATE fb SET + SampledProjection01 = ISNULL(Month01, 0), + SampledProjection02 = ISNULL(Month02, 0), + SampledProjection03 = ISNULL(Month03, 0), + SampledProjection04 = ISNULL(Month04, 0), + SampledProjection05 = ISNULL(Month05, 0), + SampledProjection06 = ISNULL(Month06, 0), + SampledProjection07 = ISNULL(Month07, 0), + SampledProjection08 = ISNULL(Month08, 0), + SampledProjection09 = ISNULL(Month09, 0), + SampledProjection10 = ISNULL(Month10, 0), + SampledProjection11 = ISNULL(Month11, 0), + SampledProjection12 = ISNULL(Month12, 0) + FROM [fp].[FactBenefits] fb INNER JOIN + (SELECT gl.DepartmentID, gl.AccountID, fm.MonthColumnName, SUM(Value * acc.Inversion) as Value + FROM [int].[FactGL] gl + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = gl.FiscalMonthID + INNER JOIN [fw].[DimAccount] acc on acc.AccountID = gl.AccountID + WHERE gl.FiscalYearID = @SourceFiscalYearID AND gl.TimeClassID = @SourceTimeClassID AND gl.IsDeleted = 0 AND gl.FiscalMonthID != 0 + AND fm.SortOrder <= @MonthsLoaded + GROUP BY gl.DepartmentID, gl.AccountID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON fb.DepartmentID = pv.DepartmentID + AND fb.AccountID = pv.AccountID + WHERE fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.UnitTypeID = 34 + + DECLARE @IsLeapYear BIT = (CASE WHEN ( @CurrentFiscalYearID % 4 = 0 AND @CurrentFiscalYearID % 100 <> 0) OR @CurrentFiscalYearID % 400 = 0 THEN 1 ELSE 0 END) + DECLARE @DaysInYear decimal = (SELECT (CASE WHEN @IsLeapYear = 1 THEN YTDDaysInLeapYearMonth ELSE YTDDaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder = 12) + DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded) + DECLARE @MonthsNotLoaded decimal = 12 - @MonthsLoaded + DECLARE @DaysRemaining decimal = @DaysInYear - @DaysInMonthsLoaded + DECLARE @TimeClassID TINYINT /* we are passing in Actual for the TimeClass regardless so we need to retrieve the real one here */ + SELECT @TimeClassID = BenefitsTimeClassID FROM fp.EntityGroupConfig WHERE EntityGroupConfigID = @EntityGroupConfigID + +IF @CurrentFiscalYearID = @SourceFiscalYearID AND @TimeClassID = 1 BEGIN + -- copy the baseline data over for months without data (month sort order > @MonthsLoaded) + -- if the baseline is current year actual YTD, then the data would already have been annualized, if not, then we don't need to annualize + UPDATE + fb + SET + SampledProjection02 = CASE WHEN @MonthsLoaded < 2 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection02 END, + SampledProjection03 = CASE WHEN @MonthsLoaded < 3 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection03 END, + SampledProjection04 = CASE WHEN @MonthsLoaded < 4 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection04 END, + SampledProjection05 = CASE WHEN @MonthsLoaded < 5 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection05 END, + SampledProjection06 = CASE WHEN @MonthsLoaded < 6 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection06 END, + SampledProjection07 = CASE WHEN @MonthsLoaded < 7 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection07 END, + SampledProjection08 = CASE WHEN @MonthsLoaded < 8 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection08 END, + SampledProjection09 = CASE WHEN @MonthsLoaded < 9 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection09 END, + SampledProjection10 = CASE WHEN @MonthsLoaded < 10 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection10 END, + SampledProjection11 = CASE WHEN @MonthsLoaded < 11 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection11 END, + SampledProjection12 = ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded + FROM + [fp].[FactBenefits] fb + WHERE + fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.UnitTypeID = 34 +END ELSE BEGIN + +-- copy the baseline data over for months without data (month sort order > @MonthsLoaded) + -- if the baseline is current year actual YTD, then the data would already have been annualized, if not, then we don't need to annualize + UPDATE + fb + SET + SampledProjection02 = CASE WHEN @MonthsLoaded < 2 THEN SampledBudget02 ELSE SampledProjection02 END, + SampledProjection03 = CASE WHEN @MonthsLoaded < 3 THEN SampledBudget03 ELSE SampledProjection03 END, + SampledProjection04 = CASE WHEN @MonthsLoaded < 4 THEN SampledBudget04 ELSE SampledProjection04 END, + SampledProjection05 = CASE WHEN @MonthsLoaded < 5 THEN SampledBudget05 ELSE SampledProjection05 END, + SampledProjection06 = CASE WHEN @MonthsLoaded < 6 THEN SampledBudget06 ELSE SampledProjection06 END, + SampledProjection07 = CASE WHEN @MonthsLoaded < 7 THEN SampledBudget07 ELSE SampledProjection07 END, + SampledProjection08 = CASE WHEN @MonthsLoaded < 8 THEN SampledBudget08 ELSE SampledProjection08 END, + SampledProjection09 = CASE WHEN @MonthsLoaded < 9 THEN SampledBudget09 ELSE SampledProjection09 END, + SampledProjection10 = CASE WHEN @MonthsLoaded < 10 THEN SampledBudget10 ELSE SampledProjection10 END, + SampledProjection11 = CASE WHEN @MonthsLoaded < 11 THEN SampledBudget11 ELSE SampledProjection11 END, + SampledProjection12 = CASE WHEN @MonthsLoaded < 12 THEN SampledBudget12 ELSE SampledProjection12 END + FROM + [fp].[FactBenefits] fb + WHERE + fb.EntityGroupConfigID = @EntityGroupConfigID AND fb.UnitTypeID = 34 +END + + + UPDATE + ben + SET + InitialProjection01 = ben.SampledProjection01, + InitialProjection02 = ben.SampledProjection02, + InitialProjection03 = ben.SampledProjection03, + InitialProjection04 = ben.SampledProjection04, + InitialProjection05 = ben.SampledProjection05, + InitialProjection06 = ben.SampledProjection06, + InitialProjection07 = ben.SampledProjection07, + InitialProjection08 = ben.SampledProjection08, + InitialProjection09 = ben.SampledProjection09, + InitialProjection10 = ben.SampledProjection10, + InitialProjection11 = ben.SampledProjection11, + InitialProjection12 = ben.SampledProjection12 + FROM [fp].[FactBenefits] ben + WHERE ben.EntityGroupConfigID = @EntityGroupConfigID + + +END +GO + + +--------------------------------------------- + +-- fp.procSampleBenefitsProjectionData +CREATE PROCEDURE [fp].[procSampleBenefitsProjectionData] +@EntityGroupConfigID int +AS +BEGIN + + -- update the budget data + INSERT INTO [fp].[FactBenefitsProjection]([BenefitsID], [BudgetPhaseID], + [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12], + [FlexedValue01], [FlexedValue02], [FlexedValue03], [FlexedValue04], [FlexedValue05], [FlexedValue06], [FlexedValue07], [FlexedValue08], [FlexedValue09], [FlexedValue10], [FlexedValue11], [FlexedValue12]) + SELECT [BenefitsID], [BudgetPhaseID], + [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12], + [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12] + FROM [fp].[FactBenefits] fs + CROSS APPLY (VALUES (2),(3)) bp(BudgetPhaseID) + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND IsNew = 0 + +END +GO + + +--------------------------------------------- + +-- fp.procSampleBenefitsSalaryDriverValues +/************************************************************** +** Change History +** CID Date Author WI Description +** 1 2019-02-14 IP B-22020 Added AccountID as CSV +** 2 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table +** 3 2019-06-02 MY TK-74658 Removing remaining table variable functions +** 4 2020-03-31 LR B-24089 Removed check for null within join conditions +** 5 2022-08-31 BW JAZZ-41678 Insert the assignment config's jc/pcg detail into a temp table for the @PayrollFilterSQL to join on +** 6 2023-10-31 BK JAZZ-62801 Update for staffing restructure +*************************************************************/ +CREATE PROCEDURE [fp].[procSampleBenefitsSalaryDriverValues] + @EntityGroupConfigID INT, + @AccountID VARCHAR(MAX), + @FinancialReportingID INT, + @TimeClassID INT, + @PayrollFilterSql NVARCHAR(MAX), + @PayrollFilterTempTableSQL VARCHAR(MAX), + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + WITH RECOMPILE + AS + BEGIN + + CREATE TABLE #FilterByDepartment (DepartmentID int,BudgetPhaseID int) + INSERT INTO #FilterByDepartment (DepartmentID,BudgetPhaseID) + SELECT DepartmentID,BudgetPhaseID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[FactBenefits] d WITH (READUNCOMMITTED) + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + DECLARE @DynamicSql NVARCHAR(MAX) + IF object_id('tempdb..#basisIDs') IS NOT NULL + BEGIN + DROP TABLE #basisIDs + END + IF object_id('tempdb..#StaffingSalaries') IS NOT NULL + BEGIN + DROP TABLE #StaffingSalaries + END + + CREATE TABLE #StaffingSalaries (EntityID INT, DepartmentID INT, AccountID INT, FinancialReportingID INT, BudgetPhaseID INT, + Value01 DECIMAL(19, 8), Value02 DECIMAL(19, 8), Value03 DECIMAL(19, 8), Value04 DECIMAL(19, 8), + Value05 DECIMAL(19, 8), Value06 DECIMAL(19, 8), Value07 DECIMAL(19, 8), Value08 DECIMAL(19, 8), + Value09 DECIMAL(19, 8), Value10 DECIMAL(19, 8), Value11 DECIMAL(19, 8), Value12 DECIMAL(19, 8)) + + IF (@TimeClassID = 2) + BEGIN + + set @DynamicSql = ' + ' + @PayrollFilterTempTableSQL + ' + + CREATE TABLE #AccountIDs (AccountID int) + INSERT INTO #AccountIDs (AccountID) + SELECT DISTINCT value as AccountID FROM STRING_SPLIT('''+@AccountID+''','','') + + INSERT INTO #StaffingSalaries + SELECT + pr.EntityID, + pr.DepartmentID, + AccLst.AccountID, + ' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID, + CAST(2 as TINYINT) BudgetPhaseID, + SUM(pr.TargetAdjustedDollars01) AS Value01, + SUM(pr.TargetAdjustedDollars02) AS Value02, + SUM(pr.TargetAdjustedDollars03) AS Value03, + SUM(pr.TargetAdjustedDollars04) AS Value04, + SUM(pr.TargetAdjustedDollars05) AS Value05, + SUM(pr.TargetAdjustedDollars06) AS Value06, + SUM(pr.TargetAdjustedDollars07) AS Value07, + SUM(pr.TargetAdjustedDollars08) AS Value08, + SUM(pr.TargetAdjustedDollars09) AS Value09, + SUM(pr.TargetAdjustedDollars10) AS Value10, + SUM(pr.TargetAdjustedDollars11) AS Value11, + SUM(pr.TargetAdjustedDollars12) AS Value12 + FROM [fp].[Staffing] pr + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = pr.DepartmentID) + CROSS APPLY (SELECT AccountID FROM #AccountIDs) AccLst + WHERE + pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + AND (2 = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL) + AND ' + @PayrollFilterSql + ' + GROUP BY + pr.DepartmentID, + pr.EntityID, + AccLst.AccountID + + INSERT INTO #StaffingSalaries + SELECT + pr.EntityID, + pr.DepartmentID, + AccLst.AccountID, + ' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID, + CAST(3 as TINYINT) BudgetPhaseID, + SUM(pr.BudgetAdjustedDollars01) AS Value01, + SUM(pr.BudgetAdjustedDollars02) AS Value02, + SUM(pr.BudgetAdjustedDollars03) AS Value03, + SUM(pr.BudgetAdjustedDollars04) AS Value04, + SUM(pr.BudgetAdjustedDollars05) AS Value05, + SUM(pr.BudgetAdjustedDollars06) AS Value06, + SUM(pr.BudgetAdjustedDollars07) AS Value07, + SUM(pr.BudgetAdjustedDollars08) AS Value08, + SUM(pr.BudgetAdjustedDollars09) AS Value09, + SUM(pr.BudgetAdjustedDollars10) AS Value10, + SUM(pr.BudgetAdjustedDollars11) AS Value11, + SUM(pr.BudgetAdjustedDollars12) AS Value12 + FROM [fp].[Staffing] pr + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = pr.DepartmentID) + CROSS APPLY (SELECT AccountID FROM #AccountIDs) AccLst + WHERE + pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + AND (3 = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL) + AND ' + @PayrollFilterSql + ' + GROUP BY + pr.DepartmentID, + pr.EntityID, + AccLst.AccountID + + + -- Update Value + UPDATE budg + SET + AdjustedValue01 = Value01, AdjustedValue02 = Value02, AdjustedValue03 = Value03, AdjustedValue04 = Value04, + AdjustedValue05 = Value05, AdjustedValue06 = Value06, AdjustedValue07 = Value07, AdjustedValue08 = Value08, + AdjustedValue09 = Value09, AdjustedValue10 = Value10, AdjustedValue11 = Value11, AdjustedValue12 = Value12, + FlexedValue01 = Value01, FlexedValue02 = Value02, FlexedValue03 = Value03, FlexedValue04 = Value04, + FlexedValue05 = Value05, FlexedValue06 = Value06, FlexedValue07 = Value07, FlexedValue08 = Value08, + FlexedValue09 = Value09, FlexedValue10 = Value10, FlexedValue11 = Value11, FlexedValue12 = Value12 + FROM [fp].[FactBenefits] benefits + INNER JOIN [fp].[FactBenefitsBudget] budg ON benefits.BenefitsID = budg.BenefitsID + INNER JOIN #StaffingSalaries staffing ON + staffing.EntityID = benefits.EntityID + AND staffing.DepartmentID = benefits.DepartmentID + AND staffing.AccountID = benefits.AccountID + AND staffing.FinancialReportingID = benefits.FinancialReportingID + AND staffing.BudgetPhaseID = budg.BudgetPhaseID + WHERE benefits.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + AND benefits.UnitTypeID = 169 + + '; + + END ELSE BEGIN + + declare @i int + + set @DynamicSql = ' + ' + @PayrollFilterTempTableSQL + ' + + DECLARE @ML INT + SELECT @ML = bc.MonthsLoaded from [fp].[BudgetConfig] bc inner join [fp].[EntityGroupConfig] egc on egc.BudgetConfigGUID = bc.BudgetConfigGUID where egc.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + + + CREATE TABLE #AccountIDs (AccountID int) + INSERT INTO #AccountIDs (AccountID) + SELECT DISTINCT value as AccountID FROM STRING_SPLIT('''+@AccountID+''','','') + + INSERT INTO #StaffingSalaries + SELECT + pr.EntityID, + pr.DepartmentID, + AccLst.AccountID, + ' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID, + CAST(3 as TINYINT) BudgetPhaseID, + SUM(pr.ProjectionAdjustedDollars01) AS Value01, + SUM(pr.ProjectionAdjustedDollars02) AS Value02, + SUM(pr.ProjectionAdjustedDollars03) AS Value03, + SUM(pr.ProjectionAdjustedDollars04) AS Value04, + SUM(pr.ProjectionAdjustedDollars05) AS Value05, + SUM(pr.ProjectionAdjustedDollars06) AS Value06, + SUM(pr.ProjectionAdjustedDollars07) AS Value07, + SUM(pr.ProjectionAdjustedDollars08) AS Value08, + SUM(pr.ProjectionAdjustedDollars09) AS Value09, + SUM(pr.ProjectionAdjustedDollars10) AS Value10, + SUM(pr.ProjectionAdjustedDollars11) AS Value11, + SUM(pr.ProjectionAdjustedDollars12) AS Value12 + FROM [fp].[Staffing] pr + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = pr.DepartmentID + CROSS APPLY (SELECT AccountID FROM #AccountIDs) AccLst + WHERE + pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + AND ' + @PayrollFilterSql + ' + GROUP BY + pr.DepartmentID, + pr.EntityID, + AccLst.AccountID + + -- Update Value + UPDATE proj + SET + proj.AdjustedValue01 = CASE WHEN 1 <= @ML THEN InitialProjection01 ELSE Value01 END, + proj.AdjustedValue02 = CASE WHEN 2 <= @ML THEN InitialProjection02 ELSE Value02 END, + proj.AdjustedValue03 = CASE WHEN 3 <= @ML THEN InitialProjection03 ELSE Value03 END, + proj.AdjustedValue04 = CASE WHEN 4 <= @ML THEN InitialProjection04 ELSE Value04 END, + proj.AdjustedValue05 = CASE WHEN 5 <= @ML THEN InitialProjection05 ELSE Value05 END, + proj.AdjustedValue06 = CASE WHEN 6 <= @ML THEN InitialProjection06 ELSE Value06 END, + proj.AdjustedValue07 = CASE WHEN 7 <= @ML THEN InitialProjection07 ELSE Value07 END, + proj.AdjustedValue08 = CASE WHEN 8 <= @ML THEN InitialProjection08 ELSE Value08 END, + proj.AdjustedValue09 = CASE WHEN 9 <= @ML THEN InitialProjection09 ELSE Value09 END, + proj.AdjustedValue10 = CASE WHEN 10 <= @ML THEN InitialProjection10 ELSE Value10 END, + proj.AdjustedValue11 = CASE WHEN 11 <= @ML THEN InitialProjection11 ELSE Value11 END, + proj.AdjustedValue12 = CASE WHEN 12 <= @ML THEN InitialProjection12 ELSE Value12 END, + proj.FlexedValue01 = CASE WHEN 1 <= @ML THEN InitialProjection01 ELSE Value01 END, + proj.FlexedValue02 = CASE WHEN 2 <= @ML THEN InitialProjection02 ELSE Value02 END, + proj.FlexedValue03 = CASE WHEN 3 <= @ML THEN InitialProjection03 ELSE Value03 END, + proj.FlexedValue04 = CASE WHEN 4 <= @ML THEN InitialProjection04 ELSE Value04 END, + proj.FlexedValue05 = CASE WHEN 5 <= @ML THEN InitialProjection05 ELSE Value05 END, + proj.FlexedValue06 = CASE WHEN 6 <= @ML THEN InitialProjection06 ELSE Value06 END, + proj.FlexedValue07 = CASE WHEN 7 <= @ML THEN InitialProjection07 ELSE Value07 END, + proj.FlexedValue08 = CASE WHEN 8 <= @ML THEN InitialProjection08 ELSE Value08 END, + proj.FlexedValue09 = CASE WHEN 9 <= @ML THEN InitialProjection09 ELSE Value09 END, + proj.FlexedValue10 = CASE WHEN 10 <= @ML THEN InitialProjection10 ELSE Value10 END, + proj.FlexedValue11 = CASE WHEN 11 <= @ML THEN InitialProjection11 ELSE Value11 END, + proj.FlexedValue12 = CASE WHEN 12 <= @ML THEN InitialProjection12 ELSE Value12 END + FROM [fp].[FactBenefits] benefits + INNER JOIN [fp].[FactBenefitsProjection] proj ON benefits.BenefitsID = proj.BenefitsID + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = benefits.DepartmentID /* adding this here so that the BudgetPhase will be respected - once we convert benefits to new structure, this can go away since the filter is applied on #staffingSalaries table */ + INNER JOIN #StaffingSalaries staffing ON + staffing.EntityID = benefits.EntityID + AND staffing.DepartmentID = benefits.DepartmentID + AND staffing.AccountID = benefits.AccountID + AND staffing.FinancialReportingID = benefits.FinancialReportingID + AND (proj.BudgetPhaseID = ft.BudgetPhaseID OR ft.BudgetPhaseID IS NULL) /* also remove this when converting benfits */ + WHERE benefits.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + AND benefits.UnitTypeID = 169 + + '; + + + END + + EXECUTE sp_executesql @DynamicSql, N'@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY', @SourceDimensionality = @SourceDimensionality; + + END +GO + + +--------------------------------------------- + +-- fp.procSampleBenefitsSalaryDriverValues_InitialValue +/************************************************************** +** Change History +** CID Date Author WI Description +** 1 2019-02-14 IP B-22020 Added AccountID as CSV +** 2 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table +** 3 2019-06-02 MY TK-74658 Removing remaining table variable functions +** 4 2020-03-31 LR B-24089 Removed check for null within join conditions +** 5 2022-08-31 BW JAZZ-41678 Insert the assignment config's jc/pcg detail into a temp table for the @PayrollFilterSQL to join on +** 6 2023-10-31 BK JAZZ-62801 Update for staffing restructure + *************************************************************/ +CREATE PROCEDURE [fp].[procSampleBenefitsSalaryDriverValues_InitialValue] + @EntityGroupConfigID INT, + @AccountID VARCHAR(MAX), + @FinancialReportingID INT, + @TimeClassID INT, + @PayrollFilterSql NVARCHAR(MAX), + @PayrollFilterTempTableSQL VARCHAR(MAX), + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + AS + BEGIN + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[FactBenefits] d WITH (READUNCOMMITTED) + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + DECLARE @DynamicSql NVARCHAR(MAX) + + IF object_id('tempdb..#StaffingSalaries') IS NOT NULL + BEGIN + DROP TABLE #StaffingSalaries + END + + CREATE TABLE #StaffingSalaries (EntityID INT, DepartmentID INT, AccountID INT, FinancialReportingID INT, UnitTypeID INT, + Value01 DECIMAL(19, 8), Value02 DECIMAL(19, 8), Value03 DECIMAL(19, 8), Value04 DECIMAL(19, 8), + Value05 DECIMAL(19, 8), Value06 DECIMAL(19, 8), Value07 DECIMAL(19, 8), Value08 DECIMAL(19, 8), + Value09 DECIMAL(19, 8), Value10 DECIMAL(19, 8), Value11 DECIMAL(19, 8), Value12 DECIMAL(19, 8)) + + IF (@TimeClassID = 2) + BEGIN + + set @DynamicSql = ' + ' + @PayrollFilterTempTableSQL + ' + + CREATE TABLE #AccountIDs (AccountID int) + INSERT INTO #AccountIDs (AccountID) + SELECT DISTINCT value as AccountID FROM STRING_SPLIT('''+@AccountID+''','','') + + INSERT INTO #StaffingSalaries + SELECT + pr.EntityID, + pr.DepartmentID, + AccLst.AccountID, + ' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID, + 169 as UnitTypeID, + SUM(pr.InitialBudgetDollars01) AS Value01, + SUM(pr.InitialBudgetDollars02) AS Value02, + SUM(pr.InitialBudgetDollars03) AS Value03, + SUM(pr.InitialBudgetDollars04) AS Value04, + SUM(pr.InitialBudgetDollars05) AS Value05, + SUM(pr.InitialBudgetDollars06) AS Value06, + SUM(pr.InitialBudgetDollars07) AS Value07, + SUM(pr.InitialBudgetDollars08) AS Value08, + SUM(pr.InitialBudgetDollars09) AS Value09, + SUM(pr.InitialBudgetDollars10) AS Value10, + SUM(pr.InitialBudgetDollars11) AS Value11, + SUM(pr.InitialBudgetDollars12) AS Value12 + FROM [fp].[Staffing] pr + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = pr.DepartmentID) + CROSS APPLY (SELECT AccountID FROM #AccountIDs) AccLst + WHERE + pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + AND ' + @PayrollFilterSql + ' + GROUP BY + pr.DepartmentID, + pr.EntityID, + AccLst.AccountID + + + -- Update Original Value + UPDATE benefits + SET + InitialBudget01 = Value01, InitialBudget02 = Value02, InitialBudget03 = Value03, InitialBudget04 = Value04, + InitialBudget05 = Value05, InitialBudget06 = Value06, InitialBudget07 = Value07, InitialBudget08 = Value08, + InitialBudget09 = Value09, InitialBudget10 = Value10, InitialBudget11 = Value11, InitialBudget12 = Value12 + FROM [fp].[FactBenefits] benefits + INNER JOIN #StaffingSalaries staffing ON + staffing.EntityID = benefits.EntityID + AND staffing.DepartmentID = benefits.DepartmentID + AND staffing.AccountID = benefits.AccountID + AND staffing.FinancialReportingID = benefits.FinancialReportingID + AND staffing.UnitTypeID = benefits.UnitTypeID + WHERE benefits.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + + '; + + END ELSE BEGIN + + set @DynamicSql = ' + ' + @PayrollFilterTempTableSQL + ' + + DECLARE @MonthsLoaded INT + SELECT @MonthsLoaded = bc.MonthsLoaded from [fp].[BudgetConfig] bc inner join [fp].[EntityGroupConfig] egc on egc.BudgetConfigGUID = bc.BudgetConfigGUID where egc.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + + CREATE TABLE #AccountIDs (AccountID int) + INSERT INTO #AccountIDs (AccountID) + SELECT DISTINCT value as AccountID FROM STRING_SPLIT('''+@AccountID+''','','') + + INSERT INTO #StaffingSalaries + SELECT + pr.EntityID, + pr.DepartmentID, + AccLst.AccountID, + ' + CAST(@FinancialReportingID as nvarchar(50)) + ' as FinancialReportingID, + 169 as UnitTypeID, + SUM(pr.InitialProjectionDollars01) AS Value01, + SUM(pr.InitialProjectionDollars02) AS Value02, + SUM(pr.InitialProjectionDollars03) AS Value03, + SUM(pr.InitialProjectionDollars04) AS Value04, + SUM(pr.InitialProjectionDollars05) AS Value05, + SUM(pr.InitialProjectionDollars06) AS Value06, + SUM(pr.InitialProjectionDollars07) AS Value07, + SUM(pr.InitialProjectionDollars08) AS Value08, + SUM(pr.InitialProjectionDollars09) AS Value09, + SUM(pr.InitialProjectionDollars10) AS Value10, + SUM(pr.InitialProjectionDollars11) AS Value11, + SUM(pr.InitialProjectionDollars12) AS Value12 + FROM [fp].[Staffing] pr + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = pr.DepartmentID) + CROSS APPLY (SELECT AccountID FROM #AccountIDs) AccLst + WHERE + pr.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + AND ' + @PayrollFilterSql + ' + GROUP BY + pr.DepartmentID, + pr.EntityID, + AccLst.AccountID + + -- Update Initial Value + UPDATE benefits + SET + InitialProjection01 = CASE WHEN 1 <= @MonthsLoaded THEN SampledProjection01 ELSE Value01 END, + InitialProjection02 = CASE WHEN 2 <= @MonthsLoaded THEN SampledProjection02 ELSE Value02 END, + InitialProjection03 = CASE WHEN 3 <= @MonthsLoaded THEN SampledProjection03 ELSE Value03 END, + InitialProjection04 = CASE WHEN 4 <= @MonthsLoaded THEN SampledProjection04 ELSE Value04 END, + InitialProjection05 = CASE WHEN 5 <= @MonthsLoaded THEN SampledProjection05 ELSE Value05 END, + InitialProjection06 = CASE WHEN 6 <= @MonthsLoaded THEN SampledProjection06 ELSE Value06 END, + InitialProjection07 = CASE WHEN 7 <= @MonthsLoaded THEN SampledProjection07 ELSE Value07 END, + InitialProjection08 = CASE WHEN 8 <= @MonthsLoaded THEN SampledProjection08 ELSE Value08 END, + InitialProjection09 = CASE WHEN 9 <= @MonthsLoaded THEN SampledProjection09 ELSE Value09 END, + InitialProjection10 = CASE WHEN 10 <= @MonthsLoaded THEN SampledProjection10 ELSE Value10 END, + InitialProjection11 = CASE WHEN 11 <= @MonthsLoaded THEN SampledProjection11 ELSE Value11 END, + InitialProjection12 = CASE WHEN 12 <= @MonthsLoaded THEN SampledProjection12 ELSE Value12 END + FROM [fp].[FactBenefits] benefits + INNER JOIN #StaffingSalaries staffing ON + staffing.EntityID = benefits.EntityID + AND staffing.DepartmentID = benefits.DepartmentID + AND staffing.AccountID = benefits.AccountID + AND staffing.FinancialReportingID = benefits.FinancialReportingID + AND staffing.UnitTypeID = benefits.UnitTypeID + WHERE benefits.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID as nvarchar(50)) + ' + + '; + END + print @DynamicSql + EXECUTE sp_executesql @DynamicSql, N'@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY', @SourceDimensionality = @SourceDimensionality; + END +GO + + +--------------------------------------------- + +-- fp.procSampleChargeDollarsToReimbursement +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-01-11 MY JAZZ-31850 Initial +** 2 2022-02-15 BW JAZZ-33266 Pulling in configuration via Plan Config > Section Setup +** 3 2022-06-15 MY JAZZ-37901 Create Fix Change History Process for Reimbursement +** 4 2023-01-31 NT JAZZ-48268 Make change to use the new fp.ChargeVolume (data restructure) +** 5 2023-04-04 BK JAZZ-50751 Fix wrong column names +** 6 2024-01-11 AO JAZZ-64530 Data transfer for SLE is based on selected Model in Plan Config +*************************************************************/ +CREATE PROCEDURE [fp].[procSampleChargeDollarsToReimbursement] + @BudgetConfigID INT, + @IsReimbursementGLEnabled BIT = 0, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + + DECLARE @IsMedicalSurgicalUsed BIT = 0, + @IsMsdrgUsed BIT = 0, + @IsCptUsed BIT = 0, + @IsUBRevCodeUsed BIT = 0; + + IF OBJECT_ID('tempdb..#projectionBasisIDs') IS NOT NULL DROP TABLE #projectionBasisIDs + IF OBJECT_ID('tempdb..#budgetBasisIDs') IS NOT NULL DROP TABLE #budgetBasisIDs + CREATE TABLE #budgetBasisIDs (ReimbursementChargesID INT); + CREATE TABLE #projectionBasisIDs (ReimbursementChargesID INT); + + SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'MedicalSurgicalID' + + SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'MSDRGID' + + SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'PrimaryCPTID' + + SELECT @IsUBRevCodeUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'UBRevCodeID' + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + IF OBJECT_ID('tempdb..#factReimbursementCharges') IS NOT NULL DROP TABLE #factReimbursementCharges; + + CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT); + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED) + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = d.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE d.BudgetConfigID = @BudgetConfigID + AND ((@IsReimbursementGLEnabled = 1 + AND (bc.DefaultReimbursementNetRevenueModelID = 1 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model + OR rnrm.NetRevenueModelID = 1) + OR @IsReimbursementGLEnabled = 0) + END + + SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, + sd.PayorID, sd.PayorGroupID, + CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, + CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID, + CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID, + + -- Target + SUM(cv.TargetDollarsAdjusted01 * sd.BudgetMixPercentage) AS TargetChargeDollars01, SUM(cv.TargetDollarsAdjusted02 * sd.BudgetMixPercentage) AS TargetChargeDollars02, SUM(cv.TargetDollarsAdjusted03 * sd.BudgetMixPercentage) AS TargetChargeDollars03, + SUM(cv.TargetDollarsAdjusted04 * sd.BudgetMixPercentage) AS TargetChargeDollars04, SUM(cv.TargetDollarsAdjusted05 * sd.BudgetMixPercentage) AS TargetChargeDollars05, SUM(cv.TargetDollarsAdjusted06 * sd.BudgetMixPercentage) AS TargetChargeDollars06, + SUM(cv.TargetDollarsAdjusted07 * sd.BudgetMixPercentage) AS TargetChargeDollars07, SUM(cv.TargetDollarsAdjusted08 * sd.BudgetMixPercentage) AS TargetChargeDollars08, SUM(cv.TargetDollarsAdjusted09 * sd.BudgetMixPercentage) AS TargetChargeDollars09, + SUM(cv.TargetDollarsAdjusted10 * sd.BudgetMixPercentage) AS TargetChargeDollars10, SUM(cv.TargetDollarsAdjusted11 * sd.BudgetMixPercentage) AS TargetChargeDollars11, SUM(cv.TargetDollarsAdjusted12 * sd.BudgetMixPercentage) AS TargetChargeDollars12, + + --Budget + SUM(cv.BudgetDollarsAdjusted01 * sd.BudgetMixPercentage) AS BudgetChargeDollars01, SUM(cv.BudgetDollarsAdjusted02 * sd.BudgetMixPercentage) AS BudgetChargeDollars02, SUM(cv.BudgetDollarsAdjusted03 * sd.BudgetMixPercentage) AS BudgetChargeDollars03, + SUM(cv.BudgetDollarsAdjusted04 * sd.BudgetMixPercentage) AS BudgetChargeDollars04, SUM(cv.BudgetDollarsAdjusted05 * sd.BudgetMixPercentage) AS BudgetChargeDollars05, SUM(cv.BudgetDollarsAdjusted06 * sd.BudgetMixPercentage) AS BudgetChargeDollars06, + SUM(cv.BudgetDollarsAdjusted07 * sd.BudgetMixPercentage) AS BudgetChargeDollars07, SUM(cv.BudgetDollarsAdjusted08 * sd.BudgetMixPercentage) AS BudgetChargeDollars08, SUM(cv.BudgetDollarsAdjusted09 * sd.BudgetMixPercentage) AS BudgetChargeDollars09, + SUM(cv.BudgetDollarsAdjusted10 * sd.BudgetMixPercentage) AS BudgetChargeDollars10, SUM(cv.BudgetDollarsAdjusted11 * sd.BudgetMixPercentage) AS BudgetChargeDollars11, SUM(cv.BudgetDollarsAdjusted12 * sd.BudgetMixPercentage) AS BudgetChargeDollars12, + + -- Projection + SUM(cv.ProjectionDollarsAdjusted01 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars01, SUM(cv.ProjectionDollarsAdjusted02 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars02, SUM(cv.ProjectionDollarsAdjusted03 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars03, + SUM(cv.ProjectionDollarsAdjusted04 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars04, SUM(cv.ProjectionDollarsAdjusted05 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars05, SUM(cv.ProjectionDollarsAdjusted06 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars06, + SUM(cv.ProjectionDollarsAdjusted07 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars07, SUM(cv.ProjectionDollarsAdjusted08 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars08, SUM(cv.ProjectionDollarsAdjusted09 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars09, + SUM(cv.ProjectionDollarsAdjusted10 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars10, SUM(cv.ProjectionDollarsAdjusted11 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars11, SUM(cv.ProjectionDollarsAdjusted12 * sd.ProjectionMixPercentage) AS ProjectionChargeDollars12 + INTO #factReimbursementCharges + FROM fp.ChargeVolume cv + INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID + INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID + INNER JOIN fp.ServiceLineEncounterToChargePayorMix sd ON cv.ServiceEntityID = sd.EntityID + AND cv.PatientClassID = sd.PatientClassID + AND cv.ServiceLineID = sd.ServiceLineID + AND cv.AgeCohortID = sd.AgeCohortID + AND cv.MedicalSurgicalID = sd.MedicalSurgicalID + AND cv.MSDRGID = sd.MSDRGID + AND cv.PrimaryCPTID = sd.CPTID + AND cv.ServiceProviderID = sd.ProviderID + AND cv.EntityGroupConfigID = sd.EntityGroupConfigID + WHERE cv.BudgetConfigID = @BudgetConfigID + GROUP BY cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.ServiceLineID, roll.RollupID, cv.PatientClassID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END, + CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END, + CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END, + CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END, + sd.PayorID, sd.PayorGroupID + + -- For Charges Only Data, we want to stick it in non-specified for Payor and PayorGroup + INSERT INTO #factReimbursementCharges (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, + MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, UBRevCodeID, + TargetChargeDollars01, TargetChargeDollars02, TargetChargeDollars03, TargetChargeDollars04, TargetChargeDollars05, TargetChargeDollars06, + TargetChargeDollars07, TargetChargeDollars08, TargetChargeDollars09, TargetChargeDollars10, TargetChargeDollars11, TargetChargeDollars12, + BudgetChargeDollars01, BudgetChargeDollars02, BudgetChargeDollars03, BudgetChargeDollars04, BudgetChargeDollars05, BudgetChargeDollars06, + BudgetChargeDollars07, BudgetChargeDollars08, BudgetChargeDollars09, BudgetChargeDollars10, BudgetChargeDollars11, BudgetChargeDollars12, + ProjectionChargeDollars01, ProjectionChargeDollars02, ProjectionChargeDollars03, ProjectionChargeDollars04, ProjectionChargeDollars05, ProjectionChargeDollars06, + ProjectionChargeDollars07, ProjectionChargeDollars08, ProjectionChargeDollars09, ProjectionChargeDollars10, ProjectionChargeDollars11, ProjectionChargeDollars12) + SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, + 0 AS PayorID, 0 AS PayorGroupID, + CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, + CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID, + CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID, + + -- Target + SUM(cv.TargetDollarsAdjusted01) AS TargetChargeDollars01, SUM(cv.TargetDollarsAdjusted02) AS TargetChargeDollars02, SUM(cv.TargetDollarsAdjusted03) AS TargetChargeDollars03, + SUM(cv.TargetDollarsAdjusted04) AS TargetChargeDollars04, SUM(cv.TargetDollarsAdjusted05) AS TargetChargeDollars05, SUM(cv.TargetDollarsAdjusted06) AS TargetChargeDollars06, + SUM(cv.TargetDollarsAdjusted07) AS TargetChargeDollars07, SUM(cv.TargetDollarsAdjusted08) AS TargetChargeDollars08, SUM(cv.TargetDollarsAdjusted09) AS TargetChargeDollars09, + SUM(cv.TargetDollarsAdjusted10) AS TargetChargeDollars10, SUM(cv.TargetDollarsAdjusted11) AS TargetChargeDollars11, SUM(cv.TargetDollarsAdjusted12) AS TargetChargeDollars12, + + --Budget + SUM(cv.BudgetDollarsAdjusted01) AS BudgetChargeDollars01, SUM(cv.BudgetDollarsAdjusted02) AS BudgetChargeDollars02, SUM(cv.BudgetDollarsAdjusted03) AS BudgetChargeDollars03, + SUM(cv.BudgetDollarsAdjusted04) AS BudgetChargeDollars04, SUM(cv.BudgetDollarsAdjusted05) AS BudgetChargeDollars05, SUM(cv.BudgetDollarsAdjusted06) AS BudgetChargeDollars06, + SUM(cv.BudgetDollarsAdjusted07) AS BudgetChargeDollars07, SUM(cv.BudgetDollarsAdjusted08) AS BudgetChargeDollars08, SUM(cv.BudgetDollarsAdjusted09) AS BudgetChargeDollars09, + SUM(cv.BudgetDollarsAdjusted10) AS BudgetChargeDollars10, SUM(cv.BudgetDollarsAdjusted11) AS BudgetChargeDollars11, SUM(cv.BudgetDollarsAdjusted12) AS BudgetChargeDollars12, + + -- Projection + SUM(cv.ProjectionDollarsAdjusted01) AS ProjectionChargeDollars01, SUM(cv.ProjectionDollarsAdjusted02) AS ProjectionChargeDollars02, SUM(cv.ProjectionDollarsAdjusted03) AS ProjectionChargeDollars03, + SUM(cv.ProjectionDollarsAdjusted04) AS ProjectionChargeDollars04, SUM(cv.ProjectionDollarsAdjusted05) AS ProjectionChargeDollars05, SUM(cv.ProjectionDollarsAdjusted06) AS ProjectionChargeDollars06, + SUM(cv.ProjectionDollarsAdjusted07) AS ProjectionChargeDollars07, SUM(cv.ProjectionDollarsAdjusted08) AS ProjectionChargeDollars08, SUM(cv.ProjectionDollarsAdjusted09) AS ProjectionChargeDollars09, + SUM(cv.ProjectionDollarsAdjusted10) AS ProjectionChargeDollars10, SUM(cv.ProjectionDollarsAdjusted11) AS ProjectionChargeDollars11, SUM(cv.ProjectionDollarsAdjusted12) AS ProjectionChargeDollars12 + FROM fp.ChargeVolume cv + INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID + INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID + LEFT JOIN fp.ServiceLineEncounterToChargePayorMix sd ON cv.ServiceEntityID = sd.EntityID + AND cv.PatientClassID = sd.PatientClassID + AND cv.ServiceLineID = sd.ServiceLineID + AND cv.AgeCohortID = sd.AgeCohortID + AND cv.MedicalSurgicalID = sd.MedicalSurgicalID + AND cv.MSDRGID = sd.MSDRGID + AND cv.PrimaryCPTID = sd.CPTID + AND cv.ServiceProviderID = sd.ProviderID + AND cv.EntityGroupConfigID = sd.EntityGroupConfigID + WHERE cv.BudgetConfigID = @BudgetConfigID + AND sd.EntityID IS NULL + GROUP BY cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.ServiceLineID, roll.RollupID, cv.PatientClassID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END, + CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END, + CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END, + CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END + + IF (@IsDebug = 1) + BEGIN + SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments + SELECT '#factReimbursementCharges', [BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [MedicalSurgicalID], + [PayorID], [PayorGroupID], [MSDRGID], [PrimaryCPTID], [UBRevCodeID], + [TargetChargeDollars01], [TargetChargeDollars02], [TargetChargeDollars03], [TargetChargeDollars04], [TargetChargeDollars05], [TargetChargeDollars06], + [TargetChargeDollars07], [TargetChargeDollars08], [TargetChargeDollars09], [TargetChargeDollars10], [TargetChargeDollars11], [TargetChargeDollars12] + [BudgetChargeDollars01], [BudgetChargeDollars02], [BudgetChargeDollars03], [BudgetChargeDollars04], [BudgetChargeDollars05], [BudgetChargeDollars06], + [BudgetChargeDollars07], [BudgetChargeDollars08], [BudgetChargeDollars09], [BudgetChargeDollars10], [BudgetChargeDollars11], [BudgetChargeDollars12] + [ProjectionChargeDollars01], [ProjectionChargeDollars02], [ProjectionChargeDollars03], [ProjectionChargeDollars04], [ProjectionChargeDollars05], [ProjectionChargeDollars06], + [ProjectionChargeDollars07], [ProjectionChargeDollars08], [ProjectionChargeDollars09], [ProjectionChargeDollars10], [ProjectionChargeDollars11], [ProjectionChargeDollars12] + FROM #factReimbursementCharges + END ELSE + BEGIN + -- Update Target Values + UPDATE budg + SET + budg.AdjustedChargeDollars01 = tmp.TargetChargeDollars01, + budg.AdjustedChargeDollars02 = tmp.TargetChargeDollars02, + budg.AdjustedChargeDollars03 = tmp.TargetChargeDollars03, + budg.AdjustedChargeDollars04 = tmp.TargetChargeDollars04, + budg.AdjustedChargeDollars05 = tmp.TargetChargeDollars05, + budg.AdjustedChargeDollars06 = tmp.TargetChargeDollars06, + budg.AdjustedChargeDollars07 = tmp.TargetChargeDollars07, + budg.AdjustedChargeDollars08 = tmp.TargetChargeDollars08, + budg.AdjustedChargeDollars09 = tmp.TargetChargeDollars09, + budg.AdjustedChargeDollars10 = tmp.TargetChargeDollars10, + budg.AdjustedChargeDollars11 = tmp.TargetChargeDollars11, + budg.AdjustedChargeDollars12 = tmp.TargetChargeDollars12 + OUTPUT + INSERTED.ReimbursementChargesID + INTO + #budgetBasisIDs (ReimbursementChargesID) + FROM fp.FactReimbursementChargesBudget budg + INNER JOIN fp.FactReimbursementCharges fact ON fact.ReimbursementChargesID = budg.ReimbursementChargesID + INNER JOIN #factReimbursementCharges tmp ON + fact.BudgetConfigID = tmp.BudgetConfigID + AND fact.EntityGroupConfigID = tmp.EntityGroupConfigID + AND fact.EntityID = tmp.EntityID + AND fact.PatientClassID = tmp.PatientClassID + AND fact.ServiceLineID = tmp.ServiceLineID + AND fact.ServiceLineRollupID = tmp.ServiceLineRollupID + AND fact.MedicalSurgicalID = tmp.MedicalSurgicalID + AND fact.MSDRGID = tmp.MSDRGID + AND fact.PrimaryCPTID = tmp.PrimaryCPTID + AND fact.UBRevCodeID = tmp.UBRevCodeID + AND fact.PayorID = tmp.PayorID + AND fact.PayorGroupID = tmp.PayorGroupID + AND budg.BudgetPhaseID = 2 + WHERE ( + budg.AdjustedChargeDollars01 != tmp.BudgetChargeDollars01 OR + budg.AdjustedChargeDollars02 != tmp.BudgetChargeDollars02 OR + budg.AdjustedChargeDollars03 != tmp.BudgetChargeDollars03 OR + budg.AdjustedChargeDollars04 != tmp.BudgetChargeDollars04 OR + budg.AdjustedChargeDollars05 != tmp.BudgetChargeDollars05 OR + budg.AdjustedChargeDollars06 != tmp.BudgetChargeDollars06 OR + budg.AdjustedChargeDollars07 != tmp.BudgetChargeDollars07 OR + budg.AdjustedChargeDollars08 != tmp.BudgetChargeDollars08 OR + budg.AdjustedChargeDollars09 != tmp.BudgetChargeDollars09 OR + budg.AdjustedChargeDollars10 != tmp.BudgetChargeDollars10 OR + budg.AdjustedChargeDollars11 != tmp.BudgetChargeDollars11 OR + budg.AdjustedChargeDollars12 != tmp.BudgetChargeDollars12 + ) + + -- Update Budget Values + UPDATE budg + SET + budg.AdjustedChargeDollars01 = tmp.BudgetChargeDollars01, + budg.AdjustedChargeDollars02 = tmp.BudgetChargeDollars02, + budg.AdjustedChargeDollars03 = tmp.BudgetChargeDollars03, + budg.AdjustedChargeDollars04 = tmp.BudgetChargeDollars04, + budg.AdjustedChargeDollars05 = tmp.BudgetChargeDollars05, + budg.AdjustedChargeDollars06 = tmp.BudgetChargeDollars06, + budg.AdjustedChargeDollars07 = tmp.BudgetChargeDollars07, + budg.AdjustedChargeDollars08 = tmp.BudgetChargeDollars08, + budg.AdjustedChargeDollars09 = tmp.BudgetChargeDollars09, + budg.AdjustedChargeDollars10 = tmp.BudgetChargeDollars10, + budg.AdjustedChargeDollars11 = tmp.BudgetChargeDollars11, + budg.AdjustedChargeDollars12 = tmp.BudgetChargeDollars12 + OUTPUT + INSERTED.ReimbursementChargesID + INTO + #budgetBasisIDs (ReimbursementChargesID) + FROM fp.FactReimbursementChargesBudget budg + INNER JOIN fp.FactReimbursementCharges fact ON fact.ReimbursementChargesID = budg.ReimbursementChargesID + INNER JOIN #factReimbursementCharges tmp ON + fact.BudgetConfigID = tmp.BudgetConfigID + AND fact.EntityGroupConfigID = tmp.EntityGroupConfigID + AND fact.EntityID = tmp.EntityID + AND fact.PatientClassID = tmp.PatientClassID + AND fact.ServiceLineID = tmp.ServiceLineID + AND fact.ServiceLineRollupID = tmp.ServiceLineRollupID + AND fact.MedicalSurgicalID = tmp.MedicalSurgicalID + AND fact.MSDRGID = tmp.MSDRGID + AND fact.PrimaryCPTID = tmp.PrimaryCPTID + AND fact.UBRevCodeID = tmp.UBRevCodeID + AND fact.PayorID = tmp.PayorID + AND fact.PayorGroupID = tmp.PayorGroupID + AND budg.BudgetPhaseID = 3 + WHERE ( + budg.AdjustedChargeDollars01 != tmp.BudgetChargeDollars01 OR + budg.AdjustedChargeDollars02 != tmp.BudgetChargeDollars02 OR + budg.AdjustedChargeDollars03 != tmp.BudgetChargeDollars03 OR + budg.AdjustedChargeDollars04 != tmp.BudgetChargeDollars04 OR + budg.AdjustedChargeDollars05 != tmp.BudgetChargeDollars05 OR + budg.AdjustedChargeDollars06 != tmp.BudgetChargeDollars06 OR + budg.AdjustedChargeDollars07 != tmp.BudgetChargeDollars07 OR + budg.AdjustedChargeDollars08 != tmp.BudgetChargeDollars08 OR + budg.AdjustedChargeDollars09 != tmp.BudgetChargeDollars09 OR + budg.AdjustedChargeDollars10 != tmp.BudgetChargeDollars10 OR + budg.AdjustedChargeDollars11 != tmp.BudgetChargeDollars11 OR + budg.AdjustedChargeDollars12 != tmp.BudgetChargeDollars12 + ) + + -- Update Projection Values + UPDATE proj + SET + proj.AdjustedChargeDollars01 = tmp.ProjectionChargeDollars01, + proj.AdjustedChargeDollars02 = tmp.ProjectionChargeDollars02, + proj.AdjustedChargeDollars03 = tmp.ProjectionChargeDollars03, + proj.AdjustedChargeDollars04 = tmp.ProjectionChargeDollars04, + proj.AdjustedChargeDollars05 = tmp.ProjectionChargeDollars05, + proj.AdjustedChargeDollars06 = tmp.ProjectionChargeDollars06, + proj.AdjustedChargeDollars07 = tmp.ProjectionChargeDollars07, + proj.AdjustedChargeDollars08 = tmp.ProjectionChargeDollars08, + proj.AdjustedChargeDollars09 = tmp.ProjectionChargeDollars09, + proj.AdjustedChargeDollars10 = tmp.ProjectionChargeDollars10, + proj.AdjustedChargeDollars11 = tmp.ProjectionChargeDollars11, + proj.AdjustedChargeDollars12 = tmp.ProjectionChargeDollars12 + OUTPUT + INSERTED.ReimbursementChargesID + INTO + #projectionBasisIDs (ReimbursementChargesID) + FROM fp.FactReimbursementChargesProjection proj + INNER JOIN fp.FactReimbursementCharges fact ON fact.ReimbursementChargesID = proj.ReimbursementChargesID + INNER JOIN #factReimbursementCharges tmp ON + fact.BudgetConfigID = tmp.BudgetConfigID + AND fact.EntityGroupConfigID = tmp.EntityGroupConfigID + AND fact.EntityID = tmp.EntityID + AND fact.PatientClassID = tmp.PatientClassID + AND fact.ServiceLineID = tmp.ServiceLineID + AND fact.ServiceLineRollupID = tmp.ServiceLineRollupID + AND fact.MedicalSurgicalID = tmp.MedicalSurgicalID + AND fact.MSDRGID = tmp.MSDRGID + AND fact.PrimaryCPTID = tmp.PrimaryCPTID + AND fact.UBRevCodeID = tmp.UBRevCodeID + AND fact.PayorID = tmp.PayorID + AND fact.PayorGroupID = tmp.PayorGroupID + --AND proj.BudgetPhaseID = 2 + WHERE ( + proj.AdjustedChargeDollars01 != tmp.ProjectionChargeDollars01 OR + proj.AdjustedChargeDollars02 != tmp.ProjectionChargeDollars02 OR + proj.AdjustedChargeDollars03 != tmp.ProjectionChargeDollars03 OR + proj.AdjustedChargeDollars04 != tmp.ProjectionChargeDollars04 OR + proj.AdjustedChargeDollars05 != tmp.ProjectionChargeDollars05 OR + proj.AdjustedChargeDollars06 != tmp.ProjectionChargeDollars06 OR + proj.AdjustedChargeDollars07 != tmp.ProjectionChargeDollars07 OR + proj.AdjustedChargeDollars08 != tmp.ProjectionChargeDollars08 OR + proj.AdjustedChargeDollars09 != tmp.ProjectionChargeDollars09 OR + proj.AdjustedChargeDollars10 != tmp.ProjectionChargeDollars10 OR + proj.AdjustedChargeDollars11 != tmp.ProjectionChargeDollars11 OR + proj.AdjustedChargeDollars12 != tmp.ProjectionChargeDollars12 + ) + + -- Find out what was changed. We can cross apply all 12 months in this case because months are on rows. If we change + -- projection to only update the months not loaded, we'll want to update this. Unlike other procs that are similar, + -- we don't care about the value because when we fix the change history, we take the stored rate in the change history + -- times the volume in the DB, we don't actually care what the value was we flexed to like in the past. + SELECT DISTINCT ReimbursementChargesID AS BasisID, m.FiscalMonthID, cast(3 as tinyint) AS BudgetPhaseID, cast(2 as tinyint) AS TimeClassID + FROM #budgetBasisIDs + CROSS JOIN fw.DimFiscalMonth m + WHERE m.FiscalMonthID != 0 + UNION ALL + SELECT DISTINCT ReimbursementChargesID AS BasisID, m.FiscalMonthID, cast(3 as tinyint) AS BudgetPhaseID, cast(12 as tinyint) AS TimeClassID + FROM #projectionBasisIDs + CROSS JOIN fw.DimFiscalMonth m + WHERE m.FiscalMonthID != 0 + + END +END +GO + + +--------------------------------------------- + +-- fp.procSampleChargeDollarsToReimbursement_History +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-01-11 MY JAZZ-31850 Initial +** 2 2022-02-15 BW JAZZ-33266 Pulling in configuration via Plan Config > Section Setup +** 3 2023-01-26 NT JAZZ-48268 Make change to use the new fp.ChargeVolume (data restructure) +** 4 2023-04-03 BK JAZZ-50751 Fix bad column names +** 5 2024-01-11 AO JAZZ-64530 Data transfer for SLE is based on selected Model in Plan Config +*************************************************************/ +CREATE PROCEDURE [fp].[procSampleChargeDollarsToReimbursement_History] + @BudgetConfigID INT, + @IsReimbursementGLEnabled BIT = 0, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + + DECLARE @IsMedicalSurgicalUsed BIT = 0, + @IsMsdrgUsed BIT = 0, + @IsCptUsed BIT = 0, + @IsUBRevCodeUsed BIT = 0; + + SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'MedicalSurgicalID' + + SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'MSDRGID' + + SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'PrimaryCPTID' + + SELECT @IsUBRevCodeUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'UBRevCodeID' + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + IF OBJECT_ID('tempdb..#factReimbursementCharges') IS NOT NULL DROP TABLE #factReimbursementCharges; + + + CREATE TABLE #factReimbursementCharges (BudgetConfigID INT, EntityGroupConfigID INT, EntityID INT, PatientClassID INT, ServiceLineID INT, ServiceLineRollupID INT, + MedicalSurgicalID INT, PayorID INT, PayorGroupID INT, MSDRGID INT, PrimaryCPTID INT, UBRevCodeID INT, + ActualYTDDollarValue01 DECIMAL(19,8), ActualYTDDollarValue02 DECIMAL(19,8), ActualYTDDollarValue03 DECIMAL(19,8), ActualYTDDollarValue04 DECIMAL(19,8), ActualYTDDollarValue05 DECIMAL(19,8), ActualYTDDollarValue06 DECIMAL(19,8), + ActualYTDDollarValue07 DECIMAL(19,8), ActualYTDDollarValue08 DECIMAL(19,8), ActualYTDDollarValue09 DECIMAL(19,8), ActualYTDDollarValue10 DECIMAL(19,8), ActualYTDDollarValue11 DECIMAL(19,8), ActualYTDDollarValue12 DECIMAL(19,8), + + PriorYearActualDollarValue01 DECIMAL(19,8), PriorYearActualDollarValue02 DECIMAL(19,8), PriorYearActualDollarValue03 DECIMAL(19,8), PriorYearActualDollarValue04 DECIMAL(19,8), PriorYearActualDollarValue05 DECIMAL(19,8), PriorYearActualDollarValue06 DECIMAL(19,8), + PriorYearActualDollarValue07 DECIMAL(19,8), PriorYearActualDollarValue08 DECIMAL(19,8), PriorYearActualDollarValue09 DECIMAL(19,8), PriorYearActualDollarValue10 DECIMAL(19,8), PriorYearActualDollarValue11 DECIMAL(19,8), PriorYearActualDollarValue12 DECIMAL(19,8), + + CurrentYearBudgetDollar01 DECIMAL(19,8), CurrentYearBudgetDollar02 DECIMAL(19,8), CurrentYearBudgetDollar03 DECIMAL(19,8), CurrentYearBudgetDollar04 DECIMAL(19,8), CurrentYearBudgetDollar05 DECIMAL(19,8), CurrentYearBudgetDollar06 DECIMAL(19,8), + CurrentYearBudgetDollar07 DECIMAL(19,8), CurrentYearBudgetDollar08 DECIMAL(19,8), CurrentYearBudgetDollar09 DECIMAL(19,8), CurrentYearBudgetDollar10 DECIMAL(19,8), CurrentYearBudgetDollar11 DECIMAL(19,8), CurrentYearBudgetDollar12 DECIMAL(19,8), + + ); + + + CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT); + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED) + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = d.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE d.BudgetConfigID = @BudgetConfigID + AND ((@IsReimbursementGLEnabled = 1 + AND (bc.DefaultReimbursementNetRevenueModelID = 1 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model + OR rnrm.NetRevenueModelID = 1) + OR @IsReimbursementGLEnabled = 0) + + END + + INSERT INTO #factReimbursementCharges + SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, + sd.PayorID, sd.PayorGroupID, + CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, + CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID, + CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID, + + -- Current Year Actuals + SUM(hist.ActualYTDDollarValue01 * sd.ActualYTDMixPercentage) AS ActualYTDValue01, SUM(hist.ActualYTDDollarValue02 * sd.ActualYTDMixPercentage) AS ActualYTDValue02, SUM(hist.ActualYTDDollarValue03 * sd.ActualYTDMixPercentage) AS ActualYTDValue03, + SUM(hist.ActualYTDDollarValue04 * sd.ActualYTDMixPercentage) AS ActualYTDValue04, SUM(hist.ActualYTDDollarValue05 * sd.ActualYTDMixPercentage) AS ActualYTDValue05, SUM(hist.ActualYTDDollarValue06 * sd.ActualYTDMixPercentage) AS ActualYTDValue06, + SUM(hist.ActualYTDDollarValue07 * sd.ActualYTDMixPercentage) AS ActualYTDValue07, SUM(hist.ActualYTDDollarValue08 * sd.ActualYTDMixPercentage) AS ActualYTDValue08, SUM(hist.ActualYTDDollarValue09 * sd.ActualYTDMixPercentage) AS ActualYTDValue09, + SUM(hist.ActualYTDDollarValue10 * sd.ActualYTDMixPercentage) AS ActualYTDValue10, SUM(hist.ActualYTDDollarValue11 * sd.ActualYTDMixPercentage) AS ActualYTDValue11, SUM(hist.ActualYTDDollarValue12 * sd.ActualYTDMixPercentage) AS ActualYTDValue12, + + -- Prior Year Actuals + SUM(hist.PriorYearActualDollarValue01 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue01, SUM(hist.PriorYearActualDollarValue02 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue02, SUM(hist.PriorYearActualDollarValue03 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue03, + SUM(hist.PriorYearActualDollarValue04 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue04, SUM(hist.PriorYearActualDollarValue05 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue05, SUM(hist.PriorYearActualDollarValue06 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue06, + SUM(hist.PriorYearActualDollarValue07 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue07, SUM(hist.PriorYearActualDollarValue08 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue08, SUM(hist.PriorYearActualDollarValue09 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue09, + SUM(hist.PriorYearActualDollarValue10 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue10, SUM(hist.PriorYearActualDollarValue11 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue11, SUM(hist.PriorYearActualDollarValue12 * sd.PriorYearActualMixPercentage) AS PriorYearActualValue12, + + -- Current Year Budget + SUM(hist.CurrentYearBudgetDollar01 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue01, SUM(hist.CurrentYearBudgetDollar02 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue02, SUM(hist.CurrentYearBudgetDollar03 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue03, + SUM(hist.CurrentYearBudgetDollar04 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue04, SUM(hist.CurrentYearBudgetDollar05 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue05, SUM(hist.CurrentYearBudgetDollar06 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue06, + SUM(hist.CurrentYearBudgetDollar07 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue07, SUM(hist.CurrentYearBudgetDollar08 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue08, SUM(hist.CurrentYearBudgetDollar09 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue09, + SUM(hist.CurrentYearBudgetDollar10 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue10, SUM(hist.CurrentYearBudgetDollar11 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue11, SUM(hist.CurrentYearBudgetDollar12 * sd.CurrentYearBudgetMixPercentage) AS CurrentYearBudgetValue12 + FROM fp.ChargeVolume cv + INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID + INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID + INNER JOIN fp.ChargeVolumeHistory hist ON cv.ChargeVolumeID = hist.ChargeVolumeID + INNER JOIN fp.ServiceLineEncounterToChargePayorMix sd ON cv.ServiceEntityID = sd.EntityID + AND cv.PatientClassID = sd.PatientClassID + AND cv.ServiceLineID = sd.ServiceLineID + AND cv.AgeCohortID = sd.AgeCohortID + AND cv.MedicalSurgicalID = sd.MedicalSurgicalID + AND cv.MSDRGID = sd.MSDRGID + AND cv.PrimaryCPTID = sd.CPTID + AND cv.ServiceProviderID = sd.ProviderID + AND cv.EntityGroupConfigID = sd.EntityGroupConfigID + WHERE cv.BudgetConfigID = @BudgetConfigID + GROUP BY cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.ServiceLineID, roll.RollupID, cv.PatientClassID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END, + CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END, + CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END, + CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END, + sd.PayorID, sd.PayorGroupID + + -- For Charges Only Data, we want to stick it in non-specified for Payor and PayorGroup + INSERT INTO #factReimbursementCharges (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, + MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, UBRevCodeID, + ActualYTDDollarValue01, ActualYTDDollarValue02, ActualYTDDollarValue03, ActualYTDDollarValue04, ActualYTDDollarValue05, ActualYTDDollarValue06, + ActualYTDDollarValue07, ActualYTDDollarValue08, ActualYTDDollarValue09, ActualYTDDollarValue10, ActualYTDDollarValue11, ActualYTDDollarValue12, + PriorYearActualDollarValue01, PriorYearActualDollarValue02, PriorYearActualDollarValue03, PriorYearActualDollarValue04, PriorYearActualDollarValue05, PriorYearActualDollarValue06, + PriorYearActualDollarValue07, PriorYearActualDollarValue08, PriorYearActualDollarValue09, PriorYearActualDollarValue10, PriorYearActualDollarValue11, PriorYearActualDollarValue12, + CurrentYearBudgetDollar01, CurrentYearBudgetDollar02, CurrentYearBudgetDollar03, CurrentYearBudgetDollar04, CurrentYearBudgetDollar05, CurrentYearBudgetDollar06, + CurrentYearBudgetDollar07, CurrentYearBudgetDollar08, CurrentYearBudgetDollar09, CurrentYearBudgetDollar10, CurrentYearBudgetDollar11, CurrentYearBudgetDollar12) + SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, + 0 AS PayorID, 0 AS PayorGroupID, + CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, + CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID, + CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID, + + -- Current Year Actuals + SUM(hist.ActualYTDDollarValue01), SUM(hist.ActualYTDDollarValue02), SUM(hist.ActualYTDDollarValue03), + SUM(hist.ActualYTDDollarValue04), SUM(hist.ActualYTDDollarValue05), SUM(hist.ActualYTDDollarValue06), + SUM(hist.ActualYTDDollarValue07), SUM(hist.ActualYTDDollarValue08), SUM(hist.ActualYTDDollarValue09), + SUM(hist.ActualYTDDollarValue10), SUM(hist.ActualYTDDollarValue11), SUM(hist.ActualYTDDollarValue12), + + -- Prior Year Actuals + SUM(hist.PriorYearActualDollarValue01), SUM(hist.PriorYearActualDollarValue02), SUM(hist.PriorYearActualDollarValue03), + SUM(hist.PriorYearActualDollarValue04), SUM(hist.PriorYearActualDollarValue05), SUM(hist.PriorYearActualDollarValue06), + SUM(hist.PriorYearActualDollarValue07), SUM(hist.PriorYearActualDollarValue08), SUM(hist.PriorYearActualDollarValue09), + SUM(hist.PriorYearActualDollarValue10), SUM(hist.PriorYearActualDollarValue11), SUM(hist.PriorYearActualDollarValue12), + + -- Current Year Budget + SUM(hist.CurrentYearBudgetDollar01), SUM(hist.CurrentYearBudgetDollar02), SUM(hist.CurrentYearBudgetDollar03), + SUM(hist.CurrentYearBudgetDollar04), SUM(hist.CurrentYearBudgetDollar05), SUM(hist.CurrentYearBudgetDollar06), + SUM(hist.CurrentYearBudgetDollar07), SUM(hist.CurrentYearBudgetDollar08), SUM(hist.CurrentYearBudgetDollar09), + SUM(hist.CurrentYearBudgetDollar10), SUM(hist.CurrentYearBudgetDollar11), SUM(hist.CurrentYearBudgetDollar12) + FROM fp.ChargeVolume cv + INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID + INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID + INNER JOIN fp.ChargeVolumeHistory hist ON cv.ChargeVolumeID = hist.ChargeVolumeID + LEFT JOIN fp.ServiceLineEncounterToChargePayorMix sd ON cv.ServiceEntityID = sd.EntityID + AND cv.PatientClassID = sd.PatientClassID + AND cv.ServiceLineID = sd.ServiceLineID + AND cv.AgeCohortID = sd.AgeCohortID + AND cv.MedicalSurgicalID = sd.MedicalSurgicalID + AND cv.MSDRGID = sd.MSDRGID + AND cv.PrimaryCPTID = sd.CPTID + AND cv.ServiceProviderID = sd.ProviderID + AND cv.EntityGroupConfigID = sd.EntityGroupConfigID + WHERE cv.BudgetConfigID = @BudgetConfigID + AND sd.EntityID IS NULL + GROUP BY cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.ServiceLineID, roll.RollupID, cv.PatientClassID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END, + CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END, + CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END, + CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END + + IF (@IsDebug = 1) + BEGIN + SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments + SELECT '#factReimbursementCharges', [BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [MedicalSurgicalID], + [PayorID], [PayorGroupID], [MSDRGID], [PrimaryCPTID], [UBRevCodeID], + [ActualYTDDollarValue01], [ActualYTDDollarValue02], [ActualYTDDollarValue03], [ActualYTDDollarValue04], [ActualYTDDollarValue05], [ActualYTDDollarValue06], + [ActualYTDDollarValue07], [ActualYTDDollarValue08], [ActualYTDDollarValue09], [ActualYTDDollarValue10], [ActualYTDDollarValue11], [ActualYTDDollarValue12], + [PriorYearActualDollarValue01], [PriorYearActualDollarValue02], [PriorYearActualDollarValue03], [PriorYearActualDollarValue04], [PriorYearActualDollarValue05], [PriorYearActualDollarValue06], + [PriorYearActualDollarValue07], [PriorYearActualDollarValue08], [PriorYearActualDollarValue09], [PriorYearActualDollarValue10], [PriorYearActualDollarValue11], [PriorYearActualDollarValue12], + [CurrentYearBudgetDollar01], [CurrentYearBudgetDollar02], [CurrentYearBudgetDollar03], [CurrentYearBudgetDollar04], [CurrentYearBudgetDollar05], [CurrentYearBudgetDollar06], + [CurrentYearBudgetDollar07], [CurrentYearBudgetDollar08], [CurrentYearBudgetDollar09], [CurrentYearBudgetDollar10], [CurrentYearBudgetDollar11], [CurrentYearBudgetDollar12] + FROM #factReimbursementCharges + END ELSE + BEGIN + -- Update History Values + UPDATE hist + SET + hist.ActualYTDChargeDollars01 = tmp.ActualYTDDollarValue01, + hist.ActualYTDChargeDollars02 = tmp.ActualYTDDollarValue02, + hist.ActualYTDChargeDollars03 = tmp.ActualYTDDollarValue03, + hist.ActualYTDChargeDollars04 = tmp.ActualYTDDollarValue04, + hist.ActualYTDChargeDollars05 = tmp.ActualYTDDollarValue05, + hist.ActualYTDChargeDollars06 = tmp.ActualYTDDollarValue06, + hist.ActualYTDChargeDollars07 = tmp.ActualYTDDollarValue07, + hist.ActualYTDChargeDollars08 = tmp.ActualYTDDollarValue08, + hist.ActualYTDChargeDollars09 = tmp.ActualYTDDollarValue09, + hist.ActualYTDChargeDollars10 = tmp.ActualYTDDollarValue10, + hist.ActualYTDChargeDollars11 = tmp.ActualYTDDollarValue11, + hist.ActualYTDChargeDollars12 = tmp.ActualYTDDollarValue12, + + hist.PriorYearActualChargeDollars01 = tmp.PriorYearActualDollarValue01, + hist.PriorYearActualChargeDollars02 = tmp.PriorYearActualDollarValue02, + hist.PriorYearActualChargeDollars03 = tmp.PriorYearActualDollarValue03, + hist.PriorYearActualChargeDollars04 = tmp.PriorYearActualDollarValue04, + hist.PriorYearActualChargeDollars05 = tmp.PriorYearActualDollarValue05, + hist.PriorYearActualChargeDollars06 = tmp.PriorYearActualDollarValue06, + hist.PriorYearActualChargeDollars07 = tmp.PriorYearActualDollarValue07, + hist.PriorYearActualChargeDollars08 = tmp.PriorYearActualDollarValue08, + hist.PriorYearActualChargeDollars09 = tmp.PriorYearActualDollarValue09, + hist.PriorYearActualChargeDollars10 = tmp.PriorYearActualDollarValue10, + hist.PriorYearActualChargeDollars11 = tmp.PriorYearActualDollarValue11, + hist.PriorYearActualChargeDollars12 = tmp.PriorYearActualDollarValue12, + + hist.CurrentYearBudgetChargeDollars01 = tmp.CurrentYearBudgetDollar01, + hist.CurrentYearBudgetChargeDollars02 = tmp.CurrentYearBudgetDollar02, + hist.CurrentYearBudgetChargeDollars03 = tmp.CurrentYearBudgetDollar03, + hist.CurrentYearBudgetChargeDollars04 = tmp.CurrentYearBudgetDollar04, + hist.CurrentYearBudgetChargeDollars05 = tmp.CurrentYearBudgetDollar05, + hist.CurrentYearBudgetChargeDollars06 = tmp.CurrentYearBudgetDollar06, + hist.CurrentYearBudgetChargeDollars07 = tmp.CurrentYearBudgetDollar07, + hist.CurrentYearBudgetChargeDollars08 = tmp.CurrentYearBudgetDollar08, + hist.CurrentYearBudgetChargeDollars09 = tmp.CurrentYearBudgetDollar09, + hist.CurrentYearBudgetChargeDollars10 = tmp.CurrentYearBudgetDollar10, + hist.CurrentYearBudgetChargeDollars11 = tmp.CurrentYearBudgetDollar11, + hist.CurrentYearBudgetChargeDollars12 = tmp.CurrentYearBudgetDollar12 + FROM fp.FactReimbursementChargesHistory hist + INNER JOIN fp.FactReimbursementCharges fact ON fact.ReimbursementChargesID = hist.ReimbursementChargesID + INNER JOIN #factReimbursementCharges tmp ON + fact.BudgetConfigID = tmp.BudgetConfigID + AND fact.EntityGroupConfigID = tmp.EntityGroupConfigID + AND fact.EntityID = tmp.EntityID + AND fact.PatientClassID = tmp.PatientClassID + AND fact.ServiceLineID = tmp.ServiceLineID + AND fact.ServiceLineRollupID = tmp.ServiceLineRollupID + AND fact.MedicalSurgicalID = tmp.MedicalSurgicalID + AND fact.MSDRGID = tmp.MSDRGID + AND fact.PrimaryCPTID = tmp.PrimaryCPTID + AND fact.UBRevCodeID = tmp.UBRevCodeID + AND fact.PayorID = tmp.PayorID + AND fact.PayorGroupID = tmp.PayorGroupID + WHERE ( + hist.ActualYTDChargeDollars01 != tmp.ActualYTDDollarValue01 OR + hist.ActualYTDChargeDollars02 != tmp.ActualYTDDollarValue02 OR + hist.ActualYTDChargeDollars03 != tmp.ActualYTDDollarValue03 OR + hist.ActualYTDChargeDollars04 != tmp.ActualYTDDollarValue04 OR + hist.ActualYTDChargeDollars05 != tmp.ActualYTDDollarValue05 OR + hist.ActualYTDChargeDollars06 != tmp.ActualYTDDollarValue06 OR + hist.ActualYTDChargeDollars07 != tmp.ActualYTDDollarValue07 OR + hist.ActualYTDChargeDollars08 != tmp.ActualYTDDollarValue08 OR + hist.ActualYTDChargeDollars09 != tmp.ActualYTDDollarValue09 OR + hist.ActualYTDChargeDollars10 != tmp.ActualYTDDollarValue10 OR + hist.ActualYTDChargeDollars11 != tmp.ActualYTDDollarValue11 OR + hist.ActualYTDChargeDollars12 != tmp.ActualYTDDollarValue12 OR + hist.PriorYearActualChargeDollars01 != tmp.PriorYearActualDollarValue01 OR + hist.PriorYearActualChargeDollars02 != tmp.PriorYearActualDollarValue02 OR + hist.PriorYearActualChargeDollars03 != tmp.PriorYearActualDollarValue03 OR + hist.PriorYearActualChargeDollars04 != tmp.PriorYearActualDollarValue04 OR + hist.PriorYearActualChargeDollars05 != tmp.PriorYearActualDollarValue05 OR + hist.PriorYearActualChargeDollars06 != tmp.PriorYearActualDollarValue06 OR + hist.PriorYearActualChargeDollars07 != tmp.PriorYearActualDollarValue07 OR + hist.PriorYearActualChargeDollars08 != tmp.PriorYearActualDollarValue08 OR + hist.PriorYearActualChargeDollars09 != tmp.PriorYearActualDollarValue09 OR + hist.PriorYearActualChargeDollars10 != tmp.PriorYearActualDollarValue10 OR + hist.PriorYearActualChargeDollars11 != tmp.PriorYearActualDollarValue11 OR + hist.PriorYearActualChargeDollars12 != tmp.PriorYearActualDollarValue12 OR + hist.CurrentYearBudgetChargeDollars01 != tmp.CurrentYearBudgetDollar01 OR + hist.CurrentYearBudgetChargeDollars02 != tmp.CurrentYearBudgetDollar02 OR + hist.CurrentYearBudgetChargeDollars03 != tmp.CurrentYearBudgetDollar03 OR + hist.CurrentYearBudgetChargeDollars04 != tmp.CurrentYearBudgetDollar04 OR + hist.CurrentYearBudgetChargeDollars05 != tmp.CurrentYearBudgetDollar05 OR + hist.CurrentYearBudgetChargeDollars06 != tmp.CurrentYearBudgetDollar06 OR + hist.CurrentYearBudgetChargeDollars07 != tmp.CurrentYearBudgetDollar07 OR + hist.CurrentYearBudgetChargeDollars08 != tmp.CurrentYearBudgetDollar08 OR + hist.CurrentYearBudgetChargeDollars09 != tmp.CurrentYearBudgetDollar09 OR + hist.CurrentYearBudgetChargeDollars10 != tmp.CurrentYearBudgetDollar10 OR + hist.CurrentYearBudgetChargeDollars11 != tmp.CurrentYearBudgetDollar11 OR + hist.CurrentYearBudgetChargeDollars12 != tmp.CurrentYearBudgetDollar12 + ) + END +END +GO + + +--------------------------------------------- + +-- fp.procSampleChargeDollarsToReimbursement_Initial +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-01-11 MY JAZZ-31850 Initial +** 2 2022-02-15 BW JAZZ-33266 Pulling in configuration via Plan Config > Section Setup +** 3 2022-06-06 MD JAZZ-37249 Making charge temp table dimensionality unique +** 4 2023-01-31 NT JAZZ-48268 Make change to use the new fp.ChargeVolume (data restructure) +** 5 2023-04-04 BK JAZZ-50751 Fix wrong column names +** 6 2024-01-11 AO JAZZ-64530 Data transfer for SLE is based on selected Model in Plan Config +*************************************************************/ +CREATE PROCEDURE [fp].[procSampleChargeDollarsToReimbursement_Initial] + @BudgetConfigID INT, + @IsReimbursementGLEnabled BIT = 0, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + + DECLARE @IsMedicalSurgicalUsed BIT = 0, + @IsMsdrgUsed BIT = 0, + @IsCptUsed BIT = 0, + @IsUBRevCodeUsed BIT = 0; + + SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'MedicalSurgicalID' + + SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'MSDRGID' + + SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'PrimaryCPTID' + + SELECT @IsUBRevCodeUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 6 -- Reimbursement - Charges + AND ss.LevelID = 'UBRevCodeID' + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + IF OBJECT_ID('tempdb..#factReimbursementCharges') IS NOT NULL DROP TABLE #factReimbursementCharges; + IF OBJECT_ID('tempdb..#reimbursementTargeting') IS NOT NULL DROP TABLE #reimbursementTargeting; + + CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT); + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[ChargeVolume] d WITH (READUNCOMMITTED) + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = d.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE d.BudgetConfigID = @BudgetConfigID + AND ((@IsReimbursementGLEnabled = 1 + AND (bc.DefaultReimbursementNetRevenueModelID = 1 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model + OR rnrm.NetRevenueModelID = 1) + OR @IsReimbursementGLEnabled = 0) + END + + CREATE TABLE #factReimbursementCharges ( + BudgetConfigID INT, + EntityGroupConfigID INT, + EntityID INT, + PatientClassID INT, + ServiceLineID INT, + ServiceLineRollupID INT, + MedicalSurgicalID INT, + PayorID INT, + PayorGroupID INT, + MSDRGID INT, + PrimaryCPTID INT, + UBRevCodeID INT, + InitialBudgetChargeDollars01 DECIMAL (19,8), InitialBudgetChargeDollars02 DECIMAL (19,8), InitialBudgetChargeDollars03 DECIMAL (19,8), + InitialBudgetChargeDollars04 DECIMAL (19,8), InitialBudgetChargeDollars05 DECIMAL (19,8), InitialBudgetChargeDollars06 DECIMAL (19,8), + InitialBudgetChargeDollars07 DECIMAL (19,8), InitialBudgetChargeDollars08 DECIMAL (19,8), InitialBudgetChargeDollars09 DECIMAL (19,8), + InitialBudgetChargeDollars10 DECIMAL (19,8), InitialBudgetChargeDollars11 DECIMAL (19,8), InitialBudgetChargeDollars12 DECIMAL (19,8) + ) + + SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, + CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, + CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID, + CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID + INTO #reimbursementTargeting + FROM fp.ChargeVolume cv + INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID + INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID + WHERE cv.BudgetConfigID = @BudgetConfigID + + INSERT INTO #factReimbursementCharges (BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, + MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, UBRevCodeID, InitialBudgetChargeDollars01, InitialBudgetChargeDollars02, InitialBudgetChargeDollars03, InitialBudgetChargeDollars04, InitialBudgetChargeDollars05, InitialBudgetChargeDollars06, + InitialBudgetChargeDollars07, InitialBudgetChargeDollars08, InitialBudgetChargeDollars09, InitialBudgetChargeDollars10, InitialBudgetChargeDollars11, InitialBudgetChargeDollars12) + SELECT BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, + MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, UBRevCodeID, + SUM(InitialBudgetChargeDollars01) as InitialBudgetChargeDollars01, SUM(InitialBudgetChargeDollars02) as InitialBudgetChargeDollars01, + SUM(InitialBudgetChargeDollars03) as InitialBudgetChargeDollars01, SUM(InitialBudgetChargeDollars04) as InitialBudgetChargeDollars01, + SUM(InitialBudgetChargeDollars05) as InitialBudgetChargeDollars01, SUM(InitialBudgetChargeDollars06) as InitialBudgetChargeDollars01, + SUM(InitialBudgetChargeDollars07) as InitialBudgetChargeDollars01, SUM(InitialBudgetChargeDollars08) as InitialBudgetChargeDollars01, + SUM(InitialBudgetChargeDollars09) as InitialBudgetChargeDollars01, SUM(InitialBudgetChargeDollars10) as InitialBudgetChargeDollars01, + SUM(InitialBudgetChargeDollars11) as InitialBudgetChargeDollars01, SUM(InitialBudgetChargeDollars12) as InitialBudgetChargeDollars01 + FROM ( + -- We are only moving Budget over and not projection because we don't display the baseline for projection so we don't need it. If we do ever need it, we'll need to add it to the mix table as well. + SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, sd.PayorID, sd.PayorGroupID, + CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, + CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID, + CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID, + -- Initial Budget + SUM(cv.InitialBudgetDollars01 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars01, SUM(cv.InitialBudgetDollars02 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars02, SUM(cv.InitialBudgetDollars03 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars03, + SUM(cv.InitialBudgetDollars04 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars04, SUM(cv.InitialBudgetDollars05 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars05, SUM(cv.InitialBudgetDollars06 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars06, + SUM(cv.InitialBudgetDollars07 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars07, SUM(cv.InitialBudgetDollars08 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars08, SUM(cv.InitialBudgetDollars09 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars09, + SUM(cv.InitialBudgetDollars10 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars10, SUM(cv.InitialBudgetDollars11 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars11, SUM(cv.InitialBudgetDollars12 * sd.InitialMixPercentage) AS InitialBudgetChargeDollars12 + FROM fp.ChargeVolume cv + INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID + INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID + INNER JOIN fp.ServiceLineEncounterToChargePayorMix sd ON cv.ServiceEntityID = sd.EntityID + AND cv.PatientClassID = sd.PatientClassID + AND cv.ServiceLineID = sd.ServiceLineID + AND cv.AgeCohortID = sd.AgeCohortID + AND cv.MedicalSurgicalID = sd.MedicalSurgicalID + AND cv.MSDRGID = sd.MSDRGID + AND cv.PrimaryCPTID = sd.CPTID + AND cv.ServiceProviderID = sd.ProviderID + AND cv.EntityGroupConfigID = sd.EntityGroupConfigID + WHERE cv.BudgetConfigID = @BudgetConfigID + GROUP BY cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.ServiceLineID, roll.RollupID, cv.PatientClassID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END, + CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END, + CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END, + CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END, + sd.PayorID, sd.PayorGroupID + + UNION + + -- For Charges Only Data, we want to stick it in non-specified for Payor and PayorGroup + SELECT DISTINCT cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.PatientClassID, cv.ServiceLineID, roll.RollupID AS ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, + 0 AS PayorID, 0 AS PayorGroupID, + CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END AS MSDRGID, + CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END AS PrimaryCPTID, + CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END AS UBRevCodeID, + -- Initial Budget + SUM(cv.InitialBudgetDollars01) AS InitialBudgetChargeDollars01, SUM(cv.InitialBudgetDollars02) AS InitialBudgetChargeDollars02, SUM(cv.InitialBudgetDollars03) AS InitialBudgetChargeDollars03, + SUM(cv.InitialBudgetDollars04) AS InitialBudgetChargeDollars04, SUM(cv.InitialBudgetDollars05) AS InitialBudgetChargeDollars05, SUM(cv.InitialBudgetDollars06) AS InitialBudgetChargeDollars06, + SUM(cv.InitialBudgetDollars07) AS InitialBudgetChargeDollars07, SUM(cv.InitialBudgetDollars08) AS InitialBudgetChargeDollars08, SUM(cv.InitialBudgetDollars09) AS InitialBudgetChargeDollars09, + SUM(cv.InitialBudgetDollars10) AS InitialBudgetChargeDollars10, SUM(cv.InitialBudgetDollars11) AS InitialBudgetChargeDollars11, SUM(cv.InitialBudgetDollars12) AS InitialBudgetChargeDollars12 + FROM fp.ChargeVolume cv + INNER JOIN #ChargeVolumeDepartments targeting ON cv.DepartmentID = targeting.DepartmentID + INNER JOIN fp.ChargeVolumeHistory hist ON cv.ChargeVolumeID = hist.ChargeVolumeID + INNER JOIN fw.DimServiceLine roll ON cv.ServiceLineID = roll.ServiceLineID + LEFT JOIN fp.ServiceLineEncounterToChargePayorMix sd ON cv.ServiceEntityID = sd.EntityID + AND cv.PatientClassID = sd.PatientClassID + AND cv.ServiceLineID = sd.ServiceLineID + AND cv.AgeCohortID = sd.AgeCohortID + AND cv.MedicalSurgicalID = sd.MedicalSurgicalID + AND cv.MSDRGID = sd.MSDRGID + AND cv.PrimaryCPTID = sd.CPTID + AND cv.ServiceProviderID = sd.ProviderID + AND cv.EntityGroupConfigID = sd.EntityGroupConfigID + WHERE cv.BudgetConfigID = @BudgetConfigID + AND sd.EntityID IS NULL + GROUP BY cv.[BudgetConfigID], cv.[EntityGroupConfigID], cv.EntityID, cv.ServiceLineID, roll.RollupID, cv.PatientClassID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN cv.MedicalSurgicalID ELSE 0 END, + CASE WHEN @IsMsdrgUsed = 1 THEN cv.MSDRGID ELSE 0 END, + CASE WHEN @IsUBRevCodeUsed = 1 THEN cv.UBRevCodeID ELSE 0 END, + CASE WHEN @IsCptUsed = 1 THEN cv.PrimaryCPTID ELSE 0 END + ) t + GROUP BY BudgetConfigID, EntityGroupConfigID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, + MedicalSurgicalID, PayorID, PayorGroupID, MSDRGID, PrimaryCPTID, UBRevCodeID + + IF (@IsDebug = 1) + BEGIN + SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments + SELECT '#factReimbursementCharges', [BudgetConfigID], [EntityGroupConfigID], [EntityID], [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [MedicalSurgicalID], + [PayorID], [PayorGroupID], [MSDRGID], [PrimaryCPTID], [UBRevCodeID], + [InitialBudgetChargeDollars01], [InitialBudgetChargeDollars02], [InitialBudgetChargeDollars03], [InitialBudgetChargeDollars04], [InitialBudgetChargeDollars05], [InitialBudgetChargeDollars06], + [InitialBudgetChargeDollars07], [InitialBudgetChargeDollars08], [InitialBudgetChargeDollars09], [InitialBudgetChargeDollars10], [InitialBudgetChargeDollars11], [InitialBudgetChargeDollars12] + FROM #factReimbursementCharges + END ELSE + BEGIN + -- Publish + ;WITH TGT AS + ( + SELECT fact.[BudgetConfigID], fact.[EntityGroupConfigID], fact.[EntityID], fact.[PatientClassID], fact.[ServiceLineID], fact.[ServiceLineRollupID], fact.[MedicalSurgicalID], + fact.[PayorID], fact.[PayorGroupID], fact.[MSDRGID], fact.[PrimaryCPTID], fact.[UBRevCodeID], + [InitialBudgetChargeDollars01], [InitialBudgetChargeDollars02], [InitialBudgetChargeDollars03], [InitialBudgetChargeDollars04], [InitialBudgetChargeDollars05], [InitialBudgetChargeDollars06], + [InitialBudgetChargeDollars07], [InitialBudgetChargeDollars08], [InitialBudgetChargeDollars09], [InitialBudgetChargeDollars10], [InitialBudgetChargeDollars11], [InitialBudgetChargeDollars12] + FROM [fp].[FactReimbursementCharges] fact + INNER JOIN #reimbursementTargeting targeting ON + fact.BudgetConfigID = targeting.BudgetConfigID + AND fact.EntityGroupConfigID = targeting.EntityGroupConfigID + AND fact.EntityID = targeting.EntityID + AND fact.PatientClassID = targeting.PatientClassID + AND fact.ServiceLineID = targeting.ServiceLineID + AND fact.ServiceLineRollupID = targeting.ServiceLineRollupID + AND fact.MedicalSurgicalID = targeting.MedicalSurgicalID + AND fact.MSDRGID = targeting.MSDRGID + AND fact.PrimaryCPTID = targeting.PrimaryCPTID + AND fact.UBRevCodeID = targeting.UBRevCodeID + WHERE fact.BudgetConfigID = @BudgetConfigID + ) + + MERGE TGT AS target + USING #factReimbursementCharges AS src + ON ( + target.BudgetConfigID = src.BudgetConfigID + AND target.EntityGroupConfigID = src.EntityGroupConfigID + AND target.EntityID = src.EntityID + AND target.PatientClassID = src.PatientClassID + AND target.ServiceLineID = src.ServiceLineID + AND target.ServiceLineRollupID = src.ServiceLineRollupID + AND target.MedicalSurgicalID = src.MedicalSurgicalID + AND target.MSDRGID = src.MSDRGID + AND target.PrimaryCPTID = src.PrimaryCPTID + AND target.UBRevCodeID = src.UBRevCodeID + AND target.PayorID = src.PayorID + AND target.PayorGroupID = src.PayorGroupID + ) + WHEN MATCHED AND ( + target.InitialBudgetChargeDollars01 <> src.InitialBudgetChargeDollars01 OR + target.InitialBudgetChargeDollars02 <> src.InitialBudgetChargeDollars02 OR + target.InitialBudgetChargeDollars03 <> src.InitialBudgetChargeDollars03 OR + target.InitialBudgetChargeDollars04 <> src.InitialBudgetChargeDollars04 OR + target.InitialBudgetChargeDollars05 <> src.InitialBudgetChargeDollars05 OR + target.InitialBudgetChargeDollars06 <> src.InitialBudgetChargeDollars06 OR + target.InitialBudgetChargeDollars07 <> src.InitialBudgetChargeDollars07 OR + target.InitialBudgetChargeDollars08 <> src.InitialBudgetChargeDollars08 OR + target.InitialBudgetChargeDollars09 <> src.InitialBudgetChargeDollars09 OR + target.InitialBudgetChargeDollars10 <> src.InitialBudgetChargeDollars10 OR + target.InitialBudgetChargeDollars11 <> src.InitialBudgetChargeDollars11 OR + target.InitialBudgetChargeDollars12 <> src.InitialBudgetChargeDollars12 + ) + THEN + UPDATE SET target.InitialBudgetChargeDollars01 = src.InitialBudgetChargeDollars01, + target.InitialBudgetChargeDollars02 = src.InitialBudgetChargeDollars02, + target.InitialBudgetChargeDollars03 = src.InitialBudgetChargeDollars03, + target.InitialBudgetChargeDollars04 = src.InitialBudgetChargeDollars04, + target.InitialBudgetChargeDollars05 = src.InitialBudgetChargeDollars05, + target.InitialBudgetChargeDollars06 = src.InitialBudgetChargeDollars06, + target.InitialBudgetChargeDollars07 = src.InitialBudgetChargeDollars07, + target.InitialBudgetChargeDollars08 = src.InitialBudgetChargeDollars08, + target.InitialBudgetChargeDollars09 = src.InitialBudgetChargeDollars09, + target.InitialBudgetChargeDollars10 = src.InitialBudgetChargeDollars10, + target.InitialBudgetChargeDollars11 = src.InitialBudgetChargeDollars11, + target.InitialBudgetChargeDollars12 = src.InitialBudgetChargeDollars12; + + END +END +GO + + +--------------------------------------------- + +-- fp.procSampleChargeMaster +CREATE PROCEDURE [fp].[procSampleChargeMaster] + @BudgetConfigID INT, + @SourceFiscalYearID SMALLINT, + @SourceTimeClassID TINYINT, + @IsEntityUsed BIT, + @IsPatientClassUsed BIT +AS +BEGIN + + -- Note: The charge master is at the budget level, not the entity (well it can be, but we can't rely on + -- entityId being in the data set. + + DELETE FROM fp.FactChargeMaster WHERE BudgetConfigID = @BudgetConfigID + + + DECLARE @CurrentFiscalYearID INT; + SET @CurrentFiscalYearID = (Select (FiscalYearID - 1) as CurrentYear from fp.BudgetConfig where BudgetConfigID = @BudgetConfigID); + DECLARE @monthsLoaded NVARCHAR(100); + SET @monthsLoaded = (CASE WHEN @SourceFiscalYearID = @CurrentFiscalYearID AND @SourceTimeClassID = 1 THEN 'AND fm.SortOrder <= bc.MonthsLoaded' ELSE '' END); + + DECLARE @SelectStatement NVARCHAR(MAX), + @GroupByStatement NVARCHAR(MAX); + + SET @SelectStatement = (CASE WHEN @IsEntityUsed = 1 THEN 'EntityID, ' ELSE '0 As EntityID, ' END + + CASE WHEN @IsPatientClassUsed = 1 THEN 'PatientClassID, ' ELSE '0 As PatientClassID, ' END); + + SET @GroupByStatement =(CASE WHEN @IsEntityUsed = 1 THEN ', EntityID' ELSE '' END + + CASE WHEN @IsPatientClassUsed = 1 THEN ', PatientClassID' ELSE '' END); + + EXEC(' + + INSERT INTO fp.FactChargeMaster (BudgetConfigID, BaselineChargeRate, ChargeRate1, ChargeCodeID, EntityID, PatientClassID, TimeClassID) + SELECT ' + @BudgetConfigID + ' AS BudgetConfigID, + CASE WHEN SUM(ISNULL(Units, 0)) = 0 THEN 0 ELSE SUM(ISNULL(Dollars, 0)) / SUM(ISNULL(Units, 0)) END AS BaselineChargeRate, + CASE WHEN SUM(ISNULL(Units, 0)) = 0 THEN 0 ELSE SUM(ISNULL(Dollars, 0)) / SUM(ISNULL(Units, 0)) END AS ChargeRate1, + ChargeCodeID, + ' + @SelectStatement + + 'PaddedTimeClassID + FROM ( SELECT md.EntityID , + f.FiscalYearID , + f.FiscalMonthID , + TimeClassID , + PatientClassID , + ChargeCodeID , + ut.Name AS UnitTypeName , + Value + FROM [int].[FactCDM] f + INNER JOIN [fw].[DimUnitType] ut ON f.UnitTypeID = ut.UnitTypeID + INNER JOIN [fw].[DimFiscalMonth] fm ON f.FiscalMonthID = fm.FiscalMonthID + INNER JOIN [fw].[DimDepartment] md ON md.DepartmentID = f.DepartmentID + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = ' + @BudgetConfigID + ' + WHERE IsDeleted = 0 + AND f.FiscalYearID = ' + @SourceFiscalYearID + ' + AND f.TimeClassID = ' + @SourceTimeClassID + ' + ' + @monthsLoaded + ' + ) AS data PIVOT + ( SUM(Value) FOR UnitTypeName IN ( [Dollars], [Units] ) ) AS pvt + CROSS APPLY (VALUES (2),(12)) tc(PaddedTimeClassID) + GROUP BY ChargeCodeID, PaddedTimeClassID' + @GroupByStatement); + +END +GO + + +--------------------------------------------- + +-- fp.procSampleChargeVolumeBudgetData +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-01-31 NT JAZZ-48268 Make change to use the new fp.ChargeVolume (data restructure) +*************************************************************/ +CREATE PROCEDURE [fp].[procSampleChargeVolumeBudgetData] + @EntityGroupConfigID int +AS +BEGIN + + UPDATE + cv + SET + TargetAdjusted01 = InitialBudget01, + TargetAdjusted02 = InitialBudget02, + TargetAdjusted03 = InitialBudget03, + TargetAdjusted04 = InitialBudget04, + TargetAdjusted05 = InitialBudget05, + TargetAdjusted06 = InitialBudget06, + TargetAdjusted07 = InitialBudget07, + TargetAdjusted08 = InitialBudget08, + TargetAdjusted09 = InitialBudget09, + TargetAdjusted10 = InitialBudget10, + TargetAdjusted11 = InitialBudget11, + TargetAdjusted12 = InitialBudget12, + BudgetAdjusted01 = InitialBudget01, + BudgetAdjusted02 = InitialBudget02, + BudgetAdjusted03 = InitialBudget03, + BudgetAdjusted04 = InitialBudget04, + BudgetAdjusted05 = InitialBudget05, + BudgetAdjusted06 = InitialBudget06, + BudgetAdjusted07 = InitialBudget07, + BudgetAdjusted08 = InitialBudget08, + BudgetAdjusted09 = InitialBudget09, + BudgetAdjusted10 = InitialBudget10, + BudgetAdjusted11 = InitialBudget11, + BudgetAdjusted12 = InitialBudget12 + FROM [fp].[ChargeVolume] cv + WHERE cv.EntityGroupConfigID = @EntityGroupConfigID + AND cv.UnitTypeID = 145 + AND IsNew = 0 +END +GO + + +--------------------------------------------- + +-- fp.procSampleChargeVolumeClearData +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2021-03-02 LR JAZZ-12907 Fixing FactChargeVolume deletes for KeepAdjustments = 0 +** 2 2021-03-24 LR JAZZ-16329 Including delete for ChargeVolumeDollars tables +** 3 2023-01-26 NT JAZZ-48268 Replace by new fp.ChargeVolume table for data re-structure and delete only what will be sampled by left joining to the source +** 4 2023-06-30 MD JAZZ-55672 Remove adjustment delete logic, add remove entity config logic +** 5 2024-01-29 MY JAZZ-65493 1Plan sampled historical data isn't updated in FP tables if import table data is changed +** 6 2024-09-06 MZ JAZZ-75639 Referencing to @BudgetConfigGUID when querying fp.SectionSetup table. +***************************************************************/ +CREATE PROCEDURE [fp].[procSampleChargeVolumeClearData] + @EntityGroupConfigID INT, + @CurrentFiscalYearID smallint, + @SourceFiscalYearID smallint, + @SourceTimeClassID tinyint, + @IsRemoveConfig BIT = 0 +AS +BEGIN + + DECLARE @ChunkCount INT + + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 400000 END + DECLARE @r INT; + DECLARE @BudgetConfigGUID UNIQUEIDENTIFIER = (SELECT BudgetConfigGUID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID) + + DECLARE @IsAgeCohortDisabled BIT; + SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigGUID = @BudgetConfigGUID AND LevelID = 'AgeCohortID' AND PlanSectionID = 2 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + DECLARE @IsMedicalSurgicalDisabled BIT; + SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigGUID = @BudgetConfigGUID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 2 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + /*Create temp table that will contain ChargeVolumeID not matching the source data from int.FactCDM. These are the ones that will be deleted. + Rest will be have their values reset to 0 to be sampled */ + CREATE TABLE #ChargeVolumeToDelete (ChargeVolumeID INT) + + IF @IsRemoveConfig = 1 + BEGIN + INSERT #ChargeVolumeToDelete with (tablock) (ChargeVolumeID) + SELECT ChargeVolumeID FROM fp.ChargeVolume + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + ELSE + BEGIN + INSERT #ChargeVolumeToDelete with (tablock) (ChargeVolumeID) + SELECT ChargeVolumeID + FROM + (SELECT DISTINCT ChargeVolumeID, DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID + FROM [fp].[ChargeVolume] + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND IsNew = 0 + ) dest + LEFT JOIN + (SELECT DISTINCT + dept.EntityID, + cv.DepartmentID, + cv.ServiceLineID, + cv.PatientClassID, + CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cv.AgeCohortID END AS AgeCohortID, + CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cv.MedicalSurgicalID END AS MedicalSurgicalID, + cv.ChargeCodeID + FROM [int].[FactCDM] cv + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cv.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dept ON cv.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + ((cv.FiscalYearID = @SourceFiscalYearID AND cv.TimeclassID = @SourceTimeClassID) -- baseline + OR (cv.FiscalYearID = @CurrentFiscalYearID) -- projection (current year actuals) + OR (cv.FiscalYearID = @CurrentFiscalYearID - 1 AND cv.TimeClassID = 1)) -- prior year, actual & budget + AND cv.IsDeleted = 0 + AND cv.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + ) src + ON src.DepartmentID = dest.DepartmentID + AND src.ServiceLineID = dest.ServiceLineID + AND src.PatientClassID = dest.PatientClassID + AND src.AgeCohortID = dest.AgeCohortID + AND src.MedicalSurgicalID = dest.MedicalSurgicalID + AND src.ChargeCodeID = dest.ChargeCodeID + WHERE src.DepartmentID IS NULL + END + + CREATE INDEX IX_1 on #ChargeVolumeToDelete(ChargeVolumeID) + + SET @r = 1; + -- We need to wipe the history so that the adjustments can be re-applied aferwards + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) cvch FROM [fp].[ChargeVolumeChangeHistory] cvch INNER JOIN [fp].[ChargeVolume] cv on cv.ChargeVolumeID = cvch.ChargeVolumeID WHERE EntityGroupConfigID = @EntityGroupConfigID; + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + /*delete data matching that of #ChargeVolumeToDelete */ + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) cvh FROM [fp].[ChargeVolumeHistory] cvh INNER JOIN #ChargeVolumeToDelete tt on cvh.ChargeVolumeID=tt.ChargeVolumeID + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION + DELETE TOP (@ChunkCount) fcv FROM [fp].[ChargeVolume] fcv INNER JOIN #ChargeVolumeToDelete tt on fcv.ChargeVolumeID=tt.ChargeVolumeID; + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + IF @IsRemoveConfig = 0 + BEGIN + UPDATE cv + SET + SampledBudget01 = 0, + SampledBudget02 = 0, + SampledBudget03 = 0, + SampledBudget04 = 0, + SampledBudget05 = 0, + SampledBudget06 = 0, + SampledBudget07 = 0, + SampledBudget08 = 0, + SampledBudget09 = 0, + SampledBudget10 = 0, + SampledBudget11 = 0, + SampledBudget12 = 0, + SampledProjection01 = 0, + SampledProjection02 = 0, + SampledProjection03 = 0, + SampledProjection04 = 0, + SampledProjection05 = 0, + SampledProjection06 = 0, + SampledProjection07 = 0, + SampledProjection08 = 0, + SampledProjection09 = 0, + SampledProjection10 = 0, + SampledProjection11 = 0, + SampledProjection12 = 0, + InitialBudget01 = 0, + InitialBudget02 = 0, + InitialBudget03 = 0, + InitialBudget04 = 0, + InitialBudget05 = 0, + InitialBudget06 = 0, + InitialBudget07 = 0, + InitialBudget08 = 0, + InitialBudget09 = 0, + InitialBudget10 = 0, + InitialBudget11 = 0, + InitialBudget12 = 0, + InitialProjection01 = 0, + InitialProjection02 = 0, + InitialProjection03 = 0, + InitialProjection04 = 0, + InitialProjection05 = 0, + InitialProjection06 = 0, + InitialProjection07 = 0, + InitialProjection08 = 0, + InitialProjection09 = 0, + InitialProjection10 = 0, + InitialProjection11 = 0, + InitialProjection12 = 0, + TargetAdjusted01 = 0, + TargetAdjusted02 = 0, + TargetAdjusted03 = 0, + TargetAdjusted04 = 0, + TargetAdjusted05 = 0, + TargetAdjusted06 = 0, + TargetAdjusted07 = 0, + TargetAdjusted08 = 0, + TargetAdjusted09 = 0, + TargetAdjusted10 = 0, + TargetAdjusted11 = 0, + TargetAdjusted12 = 0, + BudgetAdjusted01 = 0, + BudgetAdjusted02 = 0, + BudgetAdjusted03 = 0, + BudgetAdjusted04 = 0, + BudgetAdjusted05 = 0, + BudgetAdjusted06 = 0, + BudgetAdjusted07 = 0, + BudgetAdjusted08 = 0, + BudgetAdjusted09 = 0, + BudgetAdjusted10 = 0, + BudgetAdjusted11 = 0, + BudgetAdjusted12 = 0, + ProjectionAdjusted01 = 0, + ProjectionAdjusted02 = 0, + ProjectionAdjusted03 = 0, + ProjectionAdjusted04 = 0, + ProjectionAdjusted05 = 0, + ProjectionAdjusted06 = 0, + ProjectionAdjusted07 = 0, + ProjectionAdjusted08 = 0, + ProjectionAdjusted09 = 0, + ProjectionAdjusted10 = 0, + ProjectionAdjusted11 = 0, + ProjectionAdjusted12 = 0, + InitialBudgetDollars01 = 0, + InitialBudgetDollars02 = 0, + InitialBudgetDollars03 = 0, + InitialBudgetDollars04 = 0, + InitialBudgetDollars05 = 0, + InitialBudgetDollars06 = 0, + InitialBudgetDollars07 = 0, + InitialBudgetDollars08 = 0, + InitialBudgetDollars09 = 0, + InitialBudgetDollars10 = 0, + InitialBudgetDollars11 = 0, + InitialBudgetDollars12 = 0, + InitialProjectionDollars01 = 0, + InitialProjectionDollars02 = 0, + InitialProjectionDollars03 = 0, + InitialProjectionDollars04 = 0, + InitialProjectionDollars05 = 0, + InitialProjectionDollars06 = 0, + InitialProjectionDollars07 = 0, + InitialProjectionDollars08 = 0, + InitialProjectionDollars09 = 0, + InitialProjectionDollars10 = 0, + InitialProjectionDollars11 = 0, + InitialProjectionDollars12 = 0, + BudgetPrice01 = 0, + BudgetPrice02 = 0, + BudgetPrice03 = 0, + BudgetPrice04 = 0, + BudgetPrice05 = 0, + BudgetPrice06 = 0, + BudgetPrice07 = 0, + BudgetPrice08 = 0, + BudgetPrice09 = 0, + BudgetPrice10 = 0, + BudgetPrice11 = 0, + BudgetPrice12 = 0, + TargetPrice01 = 0, + TargetPrice02 = 0, + TargetPrice03 = 0, + TargetPrice04 = 0, + TargetPrice05 = 0, + TargetPrice06 = 0, + TargetPrice07 = 0, + TargetPrice08 = 0, + TargetPrice09 = 0, + TargetPrice10 = 0, + TargetPrice11 = 0, + TargetPrice12 = 0, + ProjectionPrice01 = 0, + ProjectionPrice02 = 0, + ProjectionPrice03 = 0, + ProjectionPrice04 = 0, + ProjectionPrice05 = 0, + ProjectionPrice06 = 0, + ProjectionPrice07 = 0, + ProjectionPrice08 = 0, + ProjectionPrice09 = 0, + ProjectionPrice10 = 0, + ProjectionPrice11 = 0, + ProjectionPrice12 = 0 + FROM + [fp].[ChargeVolume] cv + WHERE cv.EntityGroupConfigID = @EntityGroupConfigID + + UPDATE hist + SET + [ActualYTDValue01] = 0, + [ActualYTDValue02] = 0, + [ActualYTDValue03] = 0, + [ActualYTDValue04] = 0, + [ActualYTDValue05] = 0, + [ActualYTDValue06] = 0, + [ActualYTDValue07] = 0, + [ActualYTDValue08] = 0, + [ActualYTDValue09] = 0, + [ActualYTDValue10] = 0, + [ActualYTDValue11] = 0, + [ActualYTDValue12] = 0, + [PriorYearActualValue01] = 0, + [PriorYearActualValue02] = 0, + [PriorYearActualValue03] = 0, + [PriorYearActualValue04] = 0, + [PriorYearActualValue05] = 0, + [PriorYearActualValue06] = 0, + [PriorYearActualValue07] = 0, + [PriorYearActualValue08] = 0, + [PriorYearActualValue09] = 0, + [PriorYearActualValue10] = 0, + [PriorYearActualValue11] = 0, + [PriorYearActualValue12] = 0, + [CurrentYearBudget01] = 0, + [CurrentYearBudget02] = 0, + [CurrentYearBudget03] = 0, + [CurrentYearBudget04] = 0, + [CurrentYearBudget05] = 0, + [CurrentYearBudget06] = 0, + [CurrentYearBudget07] = 0, + [CurrentYearBudget08] = 0, + [CurrentYearBudget09] = 0, + [CurrentYearBudget10] = 0, + [CurrentYearBudget11] = 0, + [CurrentYearBudget12] = 0, + [ActualYTDDollarValue01] = 0, + [ActualYTDDollarValue02] = 0, + [ActualYTDDollarValue03] = 0, + [ActualYTDDollarValue04] = 0, + [ActualYTDDollarValue05] = 0, + [ActualYTDDollarValue06] = 0, + [ActualYTDDollarValue07] = 0, + [ActualYTDDollarValue08] = 0, + [ActualYTDDollarValue09] = 0, + [ActualYTDDollarValue10] = 0, + [ActualYTDDollarValue11] = 0, + [ActualYTDDollarValue12] = 0, + [PriorYearActualDollarValue01] = 0, + [PriorYearActualDollarValue02] = 0, + [PriorYearActualDollarValue03] = 0, + [PriorYearActualDollarValue04] = 0, + [PriorYearActualDollarValue05] = 0, + [PriorYearActualDollarValue06] = 0, + [PriorYearActualDollarValue07] = 0, + [PriorYearActualDollarValue08] = 0, + [PriorYearActualDollarValue09] = 0, + [PriorYearActualDollarValue10] = 0, + [PriorYearActualDollarValue11] = 0, + [PriorYearActualDollarValue12] = 0, + [CurrentYearBudgetDollar01] = 0, + [CurrentYearBudgetDollar02] = 0, + [CurrentYearBudgetDollar03] = 0, + [CurrentYearBudgetDollar04] = 0, + [CurrentYearBudgetDollar05] = 0, + [CurrentYearBudgetDollar06] = 0, + [CurrentYearBudgetDollar07] = 0, + [CurrentYearBudgetDollar08] = 0, + [CurrentYearBudgetDollar09] = 0, + [CurrentYearBudgetDollar10] = 0, + [CurrentYearBudgetDollar11] = 0, + [CurrentYearBudgetDollar12] = 0 + FROM [fp].[ChargeVolumeHistory] hist + INNER JOIN [fp].[ChargeVolume] cv ON hist.ChargeVolumeID = cv.ChargeVolumeID + WHERE cv.EntityGroupConfigID = @EntityGroupConfigID + END +END; +GO + + +--------------------------------------------- + +-- fp.procSampleChargeVolumeDimensionality +CREATE PROCEDURE [fp].[procSampleChargeVolumeDimensionality] + @BudgetConfigID int, + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @SourceFiscalYearID smallint, + @SourceTimeClassID tinyint +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** 1 2021-08-24 NT JAZZ-24593 Pad data for UnitType 34 (Dollars) only when IsDollarsRemovedFromCharges parameter is false + ** 2 2022-12-12 DM JAZZ-46455 Samplimg of Age Cohort and Medical/Surgical is linked to Section Setup + ** 3 2023-01-26 NT JAZZ-48268 Make change to sample charge volume dimensionality into the new fp.ChargeVolume (data restructure) + ** 4 2024-09-03 BW JAZZ-75631 Fix for duplicate key insert + *************************************************************/ + + DECLARE @IsAgeCohortDisabled BIT; + SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'AgeCohortID' AND PlanSectionID = 2 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + DECLARE @IsMedicalSurgicalDisabled BIT; + SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 2 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + INSERT INTO [fp].[ChargeVolume]([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID], [ChargeCodeID], [UnitTypeID], [ServiceEntityID]) + SELECT DISTINCT + @BudgetConfigID, + @EntityGroupConfigID, + cdm.EntityID, + cdm.DepartmentID, + cdm.ServiceLineID, + cdm.PatientClassID, + cdm.AgeCohortID, + cdm.MedicalSurgicalID, + cdm.ChargeCodeID, + UnitTypeID, + cdm.ServiceEntityID + FROM( + SELECT + dept.EntityID, -- TO BE REPLACED WITH int.FactCDM.EntityID when available + cdm.DepartmentID, + cdm.ServiceLineID, + cdm.PatientClassID, + CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cdm.AgeCohortID END AS AgeCohortID, + CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cdm.MedicalSurgicalID END AS MedicalSurgicalID, + cdm.ChargeCodeID, + 145 AS UnitTypeID, + dept.EntityID as ServiceEntityID, + cdm.IsDeleted, + cdm.FiscalMonthID + FROM [int].[FactCDM] cdm + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cdm.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dept ON cdm.DepartmentID = dept.DepartmentID + WHERE + ((cdm.FiscalYearID = @SourceFiscalYearID AND cdm.TimeclassID = @SourceTimeClassID) -- baseline + OR (cdm.FiscalYearID = @CurrentFiscalYearID) -- projection (current year actuals) + OR (cdm.FiscalYearID = @CurrentFiscalYearID - 1 AND cdm.TimeClassID = 1)) -- prior year, actual & budget + AND cdm.IsDeleted = 0 + AND cdm.FiscalMonthID != 0 + ) cdm + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = cdm.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + LEFT JOIN ( + -- Check for existing dimensionality so we only insert needed dimensionality + SELECT Distinct DepartmentID, ServiceLineID, PatientClassID, AgeCohortID, MedicalSurgicalID, ChargeCodeID + FROM [fp].[ChargeVolume] + WHERE EntityGroupConfigID = @EntityGroupConfigID + ) existing + ON cdm.DepartmentID = existing.DepartmentID + AND cdm.ServiceLineID = existing.ServiceLineID + AND cdm.PatientClassID = existing.PatientClassID + AND cdm.AgeCohortID = existing.AgeCohortID + AND cdm.MedicalSurgicalID = existing.MedicalSurgicalID + AND cdm.ChargeCodeID = existing.ChargeCodeID + WHERE + egc.EntityGroupConfigID = @EntityGroupConfigID + AND existing.DepartmentID IS NULL + AND cdm.IsDeleted = 0 + AND cdm.FiscalMonthID != 0 +END +GO + + +--------------------------------------------- + +-- fp.procSampleChargeVolumeDollarsHistory +CREATE PROCEDURE [fp].[procSampleChargeVolumeDollarsHistory] + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @MonthsLoaded int + AS + BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-08-24 NT JAZZ-24593 Populate ChargeVolume Dollars Historical Data + ** 2 2022-12-12 DM JAZZ-46455 Age Cohort and Medical/Seurgical is linked to Section Setup checkboxes + ** 3 2023-01-31 NT JAZZ-48268 Make change to use the new fp.ChargeVolume (data restructure) + *************************************************************/ + + DECLARE @IsAgeCohortDisabled BIT; + SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'AgeCohortID' AND PlanSectionID = 2 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + DECLARE @IsMedicalSurgicalDisabled BIT; + SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 2 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + -- set all of the values for current year actual/annualized + --Update actual dollars + UPDATE + cvh + SET + ActualYTDDollarValue01 = ISNULL(Month01, 0), + ActualYTDDollarValue02 = ISNULL(Month02, 0), + ActualYTDDollarValue03 = ISNULL(Month03, 0), + ActualYTDDollarValue04 = ISNULL(Month04, 0), + ActualYTDDollarValue05 = ISNULL(Month05, 0), + ActualYTDDollarValue06 = ISNULL(Month06, 0), + ActualYTDDollarValue07 = ISNULL(Month07, 0), + ActualYTDDollarValue08 = ISNULL(Month08, 0), + ActualYTDDollarValue09 = ISNULL(Month09, 0), + ActualYTDDollarValue10 = ISNULL(Month10, 0), + ActualYTDDollarValue11 = ISNULL(Month11, 0), + ActualYTDDollarValue12 = ISNULL(Month12, 0) + FROM + [fp].[ChargeVolumeHistory] cvh + INNER JOIN [fp].[ChargeVolume] cv ON cv.ChargeVolumeID = cvh.ChargeVolumeID + INNER JOIN + (SELECT cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, + CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cdm.AgeCohortID END AS AgeCohortID, + CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cdm.MedicalSurgicalID END AS MedicalSurgicalID, + cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName, SUM(Value) AS Value + FROM [int].[FactCDM] cdm + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cdm.FiscalMonthID + WHERE cdm.FiscalYearID = @CurrentFiscalYearID AND cdm.TimeclassID = 1 AND cdm.IsDeleted = 0 AND cdm.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded AND cdm.UnitTypeID IN (34) --dollars + GROUP BY cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, cdm.AgeCohortID, cdm.MedicalSurgicalID, cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv + ON cv.DepartmentID = pv.DepartmentID + AND cv.ServiceLineID = pv.ServiceLineID + AND cv.PatientClassID = pv.PatientClassID + AND cv.AgeCohortID = pv.AgeCohortID + AND cv.MedicalSurgicalID = pv.MedicalSurgicalID + AND cv.ChargeCodeID = pv.ChargeCodeID + AND cv.UnitTypeID = 145 --dollars and units are on the same row with UnitTypeID = 145. we will get rid of UnitTypeID eventually + WHERE + cv.EntityGroupConfigID = @EntityGroupConfigID + + --Update Prior Year Dollars + UPDATE + cvh + SET + PriorYearActualDollarValue01 = ISNULL(Month01, 0), + PriorYearActualDollarValue02 = ISNULL(Month02, 0), + PriorYearActualDollarValue03 = ISNULL(Month03, 0), + PriorYearActualDollarValue04 = ISNULL(Month04, 0), + PriorYearActualDollarValue05 = ISNULL(Month05, 0), + PriorYearActualDollarValue06 = ISNULL(Month06, 0), + PriorYearActualDollarValue07 = ISNULL(Month07, 0), + PriorYearActualDollarValue08 = ISNULL(Month08, 0), + PriorYearActualDollarValue09 = ISNULL(Month09, 0), + PriorYearActualDollarValue10 = ISNULL(Month10, 0), + PriorYearActualDollarValue11 = ISNULL(Month11, 0), + PriorYearActualDollarValue12 = ISNULL(Month12, 0) + FROM + [fp].[ChargeVolumeHistory] cvh + INNER JOIN [fp].[ChargeVolume] cv ON cv.ChargeVolumeID = cvh.ChargeVolumeID + INNER JOIN + (SELECT cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, + CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cdm.AgeCohortID END AS AgeCohortID, + CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cdm.MedicalSurgicalID END AS MedicalSurgicalID, + cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName, SUM(Value) AS Value + FROM [int].[FactCDM] cdm + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cdm.FiscalMonthID + WHERE cdm.FiscalYearID = @CurrentFiscalYearID - 1 AND cdm.TimeclassID = 1 AND cdm.IsDeleted = 0 AND cdm.FiscalMonthID != 0 + AND cdm.UnitTypeID IN (34) + GROUP BY cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, cdm.AgeCohortID, cdm.MedicalSurgicalID, cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv + ON cv.DepartmentID = pv.DepartmentID + AND cv.ServiceLineID = pv.ServiceLineID + AND cv.PatientClassID = pv.PatientClassID + AND cv.AgeCohortID = pv.AgeCohortID + AND cv.MedicalSurgicalID = pv.MedicalSurgicalID + AND cv.ChargeCodeID = pv.ChargeCodeID + AND cv.UnitTypeID = 145 --dollars and units are on the same row with UnitTypeID = 145. we will get rid of UnitTypeID eventually + WHERE + cv.EntityGroupConfigID = @EntityGroupConfigID + + --Update CYB dollars + UPDATE + cvh + SET + CurrentYearBudgetDollar01 = ISNULL(Month01, 0), + CurrentYearBudgetDollar02 = ISNULL(Month02, 0), + CurrentYearBudgetDollar03 = ISNULL(Month03, 0), + CurrentYearBudgetDollar04 = ISNULL(Month04, 0), + CurrentYearBudgetDollar05 = ISNULL(Month05, 0), + CurrentYearBudgetDollar06 = ISNULL(Month06, 0), + CurrentYearBudgetDollar07 = ISNULL(Month07, 0), + CurrentYearBudgetDollar08 = ISNULL(Month08, 0), + CurrentYearBudgetDollar09 = ISNULL(Month09, 0), + CurrentYearBudgetDollar10 = ISNULL(Month10, 0), + CurrentYearBudgetDollar11 = ISNULL(Month11, 0), + CurrentYearBudgetDollar12 = ISNULL(Month12, 0) + FROM + [fp].[ChargeVolumeHistory] cvh + INNER JOIN [fp].[ChargeVolume] cv ON cv.ChargeVolumeID = cvh.ChargeVolumeID + INNER JOIN + (SELECT cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, + CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cdm.AgeCohortID END AS AgeCohortID, + CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cdm.MedicalSurgicalID END AS MedicalSurgicalID, + cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName, SUM(Value) AS Value + FROM [int].[FactCDM] cdm + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cdm.FiscalMonthID + WHERE cdm.FiscalYearID = @CurrentFiscalYearID AND cdm.TimeclassID = 2 AND cdm.IsDeleted = 0 AND cdm.FiscalMonthID != 0 + AND cdm.UnitTypeID IN (34) --dollars + GROUP BY cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, cdm.AgeCohortID, cdm.MedicalSurgicalID, cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv + ON cv.DepartmentID = pv.DepartmentID + AND cv.ServiceLineID = pv.ServiceLineID + AND cv.PatientClassID = pv.PatientClassID + AND cv.AgeCohortID = pv.AgeCohortID + AND cv.MedicalSurgicalID = pv.MedicalSurgicalID + AND cv.ChargeCodeID = pv.ChargeCodeID + AND cv.UnitTypeID = 145 --dollars and units are on the same row with UnitTypeID = 145. we will get rid of UnitTypeID eventually + WHERE + cv.EntityGroupConfigID = @EntityGroupConfigID + +END +GO + + +--------------------------------------------- + +-- fp.procSampleChargeVolumeHistoricalData +CREATE PROCEDURE [fp].[procSampleChargeVolumeHistoricalData] + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @MonthsLoaded int +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** 1 2021-08-24 NT JAZZ-24593 Pad data for Unit Type 34 (Dollars) only when IsDollarsRemovedFromCharge flag is false + ** 2 2022-12-12 DM JAZZ-46455 Age Cohort and Medical/Seurgical is linked to Section Setup checkboxes + ** 3 2023-01-31 NT JAZZ-48268 Make change to use the new fp.ChargeVolume (data restructure) + *************************************************************/ + + -- Reset all values to 0 + UPDATE + cvh + SET + PriorYearActualValue01 = 0, + PriorYearActualValue02 = 0, + PriorYearActualValue03 = 0, + PriorYearActualValue04 = 0, + PriorYearActualValue05 = 0, + PriorYearActualValue06 = 0, + PriorYearActualValue07 = 0, + PriorYearActualValue08 = 0, + PriorYearActualValue09 = 0, + PriorYearActualValue10 = 0, + PriorYearActualValue11 = 0, + PriorYearActualValue12 = 0, + ActualYTDValue01 = 0, + ActualYTDValue02 = 0, + ActualYTDValue03 = 0, + ActualYTDValue04 = 0, + ActualYTDValue05 = 0, + ActualYTDValue06 = 0, + ActualYTDValue07 = 0, + ActualYTDValue08 = 0, + ActualYTDValue09 = 0, + ActualYTDValue10 = 0, + ActualYTDValue11 = 0, + ActualYTDValue12 = 0, + CurrentYearBudget01 = 0, + CurrentYearBudget02 = 0, + CurrentYearBudget03 = 0, + CurrentYearBudget04 = 0, + CurrentYearBudget05 = 0, + CurrentYearBudget06 = 0, + CurrentYearBudget07 = 0, + CurrentYearBudget08 = 0, + CurrentYearBudget09 = 0, + CurrentYearBudget10 = 0, + CurrentYearBudget11 = 0, + CurrentYearBudget12 = 0 + FROM + [fp].[ChargeVolumeHistory] cvh + INNER JOIN [fp].[ChargeVolume] cv ON cv.ChargeVolumeID = cvh.ChargeVolumeID + WHERE cv.EntityGroupConfigID = @EntityGroupConfigID + + -- Add any new records as needed + INSERT INTO [fp].[ChargeVolumeHistory] ([ChargeVolumeID]) + SELECT cv.ChargeVolumeID + FROM [fp].[ChargeVolume] cv + LEFT JOIN [fp].[ChargeVolumeHistory] cvh + ON cv.ChargeVolumeID = cvh.ChargeVolumeID + WHERE cv.EntityGroupConfigID = @EntityGroupConfigID + AND cvh.ChargeVolumeID IS NULL + + DECLARE @IsAgeCohortDisabled BIT; + SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'AgeCohortID' AND PlanSectionID = 2 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + DECLARE @IsMedicalSurgicalDisabled BIT; + SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 2 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + -- set all of the UNITs for current year actual/annualized + UPDATE + cvh + SET + ActualYTDValue01 = ISNULL(Month01, 0), + ActualYTDValue02 = ISNULL(Month02, 0), + ActualYTDValue03 = ISNULL(Month03, 0), + ActualYTDValue04 = ISNULL(Month04, 0), + ActualYTDValue05 = ISNULL(Month05, 0), + ActualYTDValue06 = ISNULL(Month06, 0), + ActualYTDValue07 = ISNULL(Month07, 0), + ActualYTDValue08 = ISNULL(Month08, 0), + ActualYTDValue09 = ISNULL(Month09, 0), + ActualYTDValue10 = ISNULL(Month10, 0), + ActualYTDValue11 = ISNULL(Month11, 0), + ActualYTDValue12 = ISNULL(Month12, 0) + FROM + [fp].[ChargeVolumeHistory] cvh + INNER JOIN [fp].[ChargeVolume] cv ON cv.ChargeVolumeID = cvh.ChargeVolumeID + INNER JOIN + (SELECT cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, + CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cdm.AgeCohortID END AS AgeCohortID, + CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cdm.MedicalSurgicalID END AS MedicalSurgicalID, + cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName, SUM(Value) AS Value + FROM [int].[FactCDM] cdm + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cdm.FiscalMonthID + WHERE cdm.FiscalYearID = @CurrentFiscalYearID AND cdm.TimeclassID = 1 + AND cdm.IsDeleted = 0 AND cdm.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded + AND cdm.UnitTypeID IN (145) --units + GROUP BY cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, cdm.AgeCohortID, cdm.MedicalSurgicalID, cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv + ON cv.DepartmentID = pv.DepartmentID + AND cv.ServiceLineID = pv.ServiceLineID + AND cv.PatientClassID = pv.PatientClassID + AND cv.AgeCohortID = pv.AgeCohortID + AND cv.MedicalSurgicalID = pv.MedicalSurgicalID + AND cv.ChargeCodeID = pv.ChargeCodeID + AND cv.UnitTypeID = pv.UnitTypeID + WHERE + cv.EntityGroupConfigID = @EntityGroupConfigID + + --Update Prior Year units + UPDATE + cvh + SET + PriorYearActualValue01 = ISNULL(Month01, 0), + PriorYearActualValue02 = ISNULL(Month02, 0), + PriorYearActualValue03 = ISNULL(Month03, 0), + PriorYearActualValue04 = ISNULL(Month04, 0), + PriorYearActualValue05 = ISNULL(Month05, 0), + PriorYearActualValue06 = ISNULL(Month06, 0), + PriorYearActualValue07 = ISNULL(Month07, 0), + PriorYearActualValue08 = ISNULL(Month08, 0), + PriorYearActualValue09 = ISNULL(Month09, 0), + PriorYearActualValue10 = ISNULL(Month10, 0), + PriorYearActualValue11 = ISNULL(Month11, 0), + PriorYearActualValue12 = ISNULL(Month12, 0) + FROM + [fp].[ChargeVolumeHistory] cvh + INNER JOIN [fp].[ChargeVolume] cv ON cv.ChargeVolumeID = cvh.ChargeVolumeID + INNER JOIN + (SELECT cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, + CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cdm.AgeCohortID END AS AgeCohortID, + CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cdm.MedicalSurgicalID END AS MedicalSurgicalID, + cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName, SUM(Value) AS Value + FROM [int].[FactCDM] cdm + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cdm.FiscalMonthID + WHERE cdm.FiscalYearID = @CurrentFiscalYearID - 1 AND cdm.TimeclassID = 1 AND cdm.IsDeleted = 0 AND cdm.FiscalMonthID != 0 + AND cdm.UnitTypeID IN (145) + GROUP BY cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, cdm.AgeCohortID, cdm.MedicalSurgicalID, cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv + ON cv.DepartmentID = pv.DepartmentID + AND cv.ServiceLineID = pv.ServiceLineID + AND cv.PatientClassID = pv.PatientClassID + AND cv.AgeCohortID = pv.AgeCohortID + AND cv.MedicalSurgicalID = pv.MedicalSurgicalID + AND cv.ChargeCodeID = pv.ChargeCodeID + AND cv.UnitTypeID = pv.UnitTypeID + WHERE + cv.EntityGroupConfigID = @EntityGroupConfigID + + --update CYB units + UPDATE + cvh + SET + CurrentYearBudget01 = ISNULL(Month01, 0), + CurrentYearBudget02 = ISNULL(Month02, 0), + CurrentYearBudget03 = ISNULL(Month03, 0), + CurrentYearBudget04 = ISNULL(Month04, 0), + CurrentYearBudget05 = ISNULL(Month05, 0), + CurrentYearBudget06 = ISNULL(Month06, 0), + CurrentYearBudget07 = ISNULL(Month07, 0), + CurrentYearBudget08 = ISNULL(Month08, 0), + CurrentYearBudget09 = ISNULL(Month09, 0), + CurrentYearBudget10 = ISNULL(Month10, 0), + CurrentYearBudget11 = ISNULL(Month11, 0), + CurrentYearBudget12 = ISNULL(Month12, 0) + FROM + [fp].[ChargeVolumeHistory] cvh + INNER JOIN [fp].[ChargeVolume] cv ON cv.ChargeVolumeID = cvh.ChargeVolumeID + INNER JOIN + (SELECT cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, + CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cdm.AgeCohortID END AS AgeCohortID, + CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cdm.MedicalSurgicalID END AS MedicalSurgicalID, + cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName, SUM(Value) AS Value + FROM [int].[FactCDM] cdm + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cdm.FiscalMonthID + WHERE cdm.FiscalYearID = @CurrentFiscalYearID AND cdm.TimeclassID = 2 AND cdm.IsDeleted = 0 AND cdm.FiscalMonthID != 0 + AND cdm.UnitTypeID = 145 --units + GROUP BY cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, cdm.AgeCohortID, cdm.MedicalSurgicalID, cdm.ChargeCodeID, cdm.UnitTypeID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv + ON cv.DepartmentID = pv.DepartmentID + AND cv.ServiceLineID = pv.ServiceLineID + AND cv.PatientClassID = pv.PatientClassID + AND cv.AgeCohortID = pv.AgeCohortID + AND cv.MedicalSurgicalID = pv.MedicalSurgicalID + AND cv.ChargeCodeID = pv.ChargeCodeID + AND cv.UnitTypeID = pv.UnitTypeID + WHERE + cv.EntityGroupConfigID = @EntityGroupConfigID + +END +GO + + +--------------------------------------------- + +-- fp.procSampleChargeVolumeInitialDollars +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-02-02 NT JAZZ-48268 Make change to use the new fp.ChargeVolume (data restructure) +*************************************************************/ +CREATE PROCEDURE fp.procSampleChargeVolumeInitialDollars + @EntityGroupConfigID int, + @IsEntityUsed BIT, + @IsPatientClassUsed BIT, + @MonthsLoaded INT +AS +BEGIN + + UPDATE cv + SET + -- Initial Budget + cv.InitialBudgetDollars01 = cv.InitialBudget01 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars02 = cv.InitialBudget02 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars03 = cv.InitialBudget03 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars04 = cv.InitialBudget04 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars05 = cv.InitialBudget05 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars06 = cv.InitialBudget06 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars07 = cv.InitialBudget07 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars08 = cv.InitialBudget08 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars09 = cv.InitialBudget09 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars10 = cv.InitialBudget10 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars11 = cv.InitialBudget11 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars12 = cv.InitialBudget12 * ISNULL(budgCm.BaselineChargeRate, 0), + + -- Initial Projection + cv.InitialProjectionDollars01 = CASE WHEN @MonthsLoaded < 1 THEN cv.InitialProjection01 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars01 END, + cv.InitialProjectionDollars02 = CASE WHEN @MonthsLoaded < 2 THEN cv.InitialProjection02 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars02 END, + cv.InitialProjectionDollars03 = CASE WHEN @MonthsLoaded < 3 THEN cv.InitialProjection03 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars03 END, + cv.InitialProjectionDollars04 = CASE WHEN @MonthsLoaded < 4 THEN cv.InitialProjection04 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars04 END, + cv.InitialProjectionDollars05 = CASE WHEN @MonthsLoaded < 5 THEN cv.InitialProjection05 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars05 END, + cv.InitialProjectionDollars06 = CASE WHEN @MonthsLoaded < 6 THEN cv.InitialProjection06 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars06 END, + cv.InitialProjectionDollars07 = CASE WHEN @MonthsLoaded < 7 THEN cv.InitialProjection07 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars07 END, + cv.InitialProjectionDollars08 = CASE WHEN @MonthsLoaded < 8 THEN cv.InitialProjection08 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars08 END, + cv.InitialProjectionDollars09 = CASE WHEN @MonthsLoaded < 9 THEN cv.InitialProjection09 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars09 END, + cv.InitialProjectionDollars10 = CASE WHEN @MonthsLoaded < 10 THEN cv.InitialProjection10 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars10 END, + cv.InitialProjectionDollars11 = CASE WHEN @MonthsLoaded < 11 THEN cv.InitialProjection11 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars11 END, + cv.InitialProjectionDollars12 = CASE WHEN @MonthsLoaded < 12 THEN cv.InitialProjection12 * ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars12 END, + + --Update ProjectionPrice** (ProjectionDollarsAdjusted** are a computed columns and will automatically reflect this update to ProjectionPrice**) + cv.ProjectionPrice01 = CASE WHEN @MonthsLoaded < 1 THEN ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice01 END, + cv.ProjectionPrice02 = CASE WHEN @MonthsLoaded < 2 THEN ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice02 END, + cv.ProjectionPrice03 = CASE WHEN @MonthsLoaded < 3 THEN ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice03 END, + cv.ProjectionPrice04 = CASE WHEN @MonthsLoaded < 4 THEN ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice04 END, + cv.ProjectionPrice05 = CASE WHEN @MonthsLoaded < 5 THEN ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice05 END, + cv.ProjectionPrice06 = CASE WHEN @MonthsLoaded < 6 THEN ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice06 END, + cv.ProjectionPrice07 = CASE WHEN @MonthsLoaded < 7 THEN ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice07 END, + cv.ProjectionPrice08 = CASE WHEN @MonthsLoaded < 8 THEN ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice08 END, + cv.ProjectionPrice09 = CASE WHEN @MonthsLoaded < 9 THEN ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice09 END, + cv.ProjectionPrice10 = CASE WHEN @MonthsLoaded < 10 THEN ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice10 END, + cv.ProjectionPrice11 = CASE WHEN @MonthsLoaded < 11 THEN ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice11 END, + cv.ProjectionPrice12 = CASE WHEN @MonthsLoaded < 12 THEN ISNULL(budgCm.BaselineChargeRate, 0) ELSE cv.ProjectionPrice12 END + FROM [fp].[ChargeVolume] cv + LEFT JOIN [fp].[FactChargeMaster] budgCm + ON budgCm.BudgetConfigID = cv.BudgetConfigID + AND budgCm.ChargeCodeID = cv.ChargeCodeID + AND budgCm.TimeClassID = 2 + AND ((@IsEntityUsed = 1 AND budgCm.EntityID = cv.EntityID) OR @IsEntityUsed = 0) + AND ((@IsPatientClassUsed = 1 AND budgCm.PatientClassID = cv.PatientClassID) OR @IsPatientClassUsed = 0); + + /* Commenting this out, instead updating ProijectionPrice** columns up above as these columsn are now computed + -- Update adjusted values for DollarsProjection table, so that it can be used for months loaded + UPDATE cv + SET + AdjustedValue01 = cvd.InitialProjection01, + AdjustedValue02 = cvd.InitialProjection02, + AdjustedValue03 = cvd.InitialProjection03, + AdjustedValue04 = cvd.InitialProjection04, + AdjustedValue05 = cvd.InitialProjection05, + AdjustedValue06 = cvd.InitialProjection06, + AdjustedValue07 = cvd.InitialProjection07, + AdjustedValue08 = cvd.InitialProjection08, + AdjustedValue09 = cvd.InitialProjection09, + AdjustedValue10 = cvd.InitialProjection10, + AdjustedValue11 = cvd.InitialProjection11, + AdjustedValue12 = cvd.InitialProjection12 + FROM [fp].[ChargeVolume] cv + WHERE cv.EntityGroupConfigID = @EntityGroupConfigID*/ + +END +GO + + +--------------------------------------------- + +-- fp.procSampleChargeVolumeOriginalBudgetDollars +CREATE PROCEDURE [fp].[procSampleChargeVolumeOriginalBudgetDollars] + @EntityGroupConfigID int, + @IsEntityUsed BIT, + @IsPatientClassUsed BIT +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-09-01 JB JAZZ-32095 Remove Payor and PayorGroupID from joins. + ** 2 2023-01-26 NT JAZZ-48268 Make change to sample charge volume budget data into the new fp.ChargeVolume (data restructure) + *************************************************************/ + -- update the initial values, need to do this separately because initial has already been flexed + UPDATE cv + SET + cv.InitialBudgetDollars01 = cv.InitialBudget01 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars02 = cv.InitialBudget02 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars03 = cv.InitialBudget03 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars04 = cv.InitialBudget04 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars05 = cv.InitialBudget05 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars06 = cv.InitialBudget06 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars07 = cv.InitialBudget07 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars08 = cv.InitialBudget08 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars09 = cv.InitialBudget09 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars10 = cv.InitialBudget10 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars11 = cv.InitialBudget11 * ISNULL(budgCm.BaselineChargeRate, 0), + cv.InitialBudgetDollars12 = cv.InitialBudget12 * ISNULL(budgCm.BaselineChargeRate, 0) + FROM [fp].[ChargeVolume] cv + LEFT JOIN [fp].[FactChargeMaster] budgCm + ON budgCm.BudgetConfigID = cv.BudgetConfigID + AND budgCm.ChargeCodeID = cv.ChargeCodeID + AND budgCm.TimeClassID = 2 + AND ((@IsEntityUsed = 1 AND budgCm.EntityID =cv.EntityID) OR @IsEntityUsed = 0) + AND ((@IsPatientClassUsed = 1 AND budgCm.PatientClassID = cv.PatientClassID) OR @IsPatientClassUsed = 0) + WHERE cv.EntityGroupConfigID = @EntityGroupConfigID +END +GO + + +--------------------------------------------- + +-- fp.procSampleChargeVolumeOriginalBudgetUnits +CREATE PROCEDURE [fp].[procSampleChargeVolumeOriginalBudgetUnits] + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @SourceFiscalYearID smallint, + @SourceTimeClassID tinyint, + @MonthsLoaded int +AS +BEGIN +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-06-06 BK JAZZ-37271 Add casting so that Initial and Adjusted values match, there were rounding issues before +** 2 2022-07-28 BK JAZZ-40950 Remove "Is Service Lines Used" feature flag and use Stats Model on EGC instead +** 3 2022-12-12 DM JAZZ-46455 Age Cohort and Medical/Seurgical is linked to Section Setup checkboxes +** 4 2023-01-26 NT JAZZ-48268 Make change to sample charge volume budget data into the new fp.ChargeVolume (data restructure) +*************************************************************/ + + DECLARE @IsAnnualized BIT = (CASE WHEN @SourceFiscalYearID = @CurrentFiscalYearID AND @SourceTimeClassID = 1 AND @MonthsLoaded < 12 THEN 1 ELSE 0 END) + + DECLARE @IsAgeCohortDisabled BIT; + SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'AgeCohortID' AND PlanSectionID = 2 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + DECLARE @IsMedicalSurgicalDisabled BIT; + SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 2 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + -- set all of the values from the source fy/tc + UPDATE + cv + SET + SampledBudget01 = ISNULL(Month01, 0), + SampledBudget02 = ISNULL(Month02, 0), + SampledBudget03 = ISNULL(Month03, 0), + SampledBudget04 = ISNULL(Month04, 0), + SampledBudget05 = ISNULL(Month05, 0), + SampledBudget06 = ISNULL(Month06, 0), + SampledBudget07 = ISNULL(Month07, 0), + SampledBudget08 = ISNULL(Month08, 0), + SampledBudget09 = ISNULL(Month09, 0), + SampledBudget10 = ISNULL(Month10, 0), + SampledBudget11 = ISNULL(Month11, 0), + SampledBudget12 = ISNULL(Month12, 0) + FROM + [fp].[ChargeVolume] cv + INNER JOIN + (SELECT cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, + CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cdm.AgeCohortID END AS AgeCohortID, + CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cdm.MedicalSurgicalID END AS MedicalSurgicalID, + cdm.ChargeCodeID, fm.MonthColumnName, SUM(Value) AS Value + FROM [int].[FactCDM] cdm + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cdm.FiscalMonthID + WHERE cdm.FiscalYearID = @SourceFiscalYearID + AND cdm.TimeclassID = @SourceTimeClassID + AND cdm.IsDeleted = 0 + AND cdm.FiscalMonthID != 0 + AND cdm.UnitTypeID = 145 + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + GROUP BY cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, cdm.AgeCohortID, cdm.MedicalSurgicalID, cdm.ChargeCodeID, fm.MonthColumnName + ) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS pv + ON cv.DepartmentID = pv.DepartmentID + AND cv.ServiceLineID = pv.ServiceLineID + AND cv.PatientClassID = pv.PatientClassID + AND cv.AgeCohortID = pv.AgeCohortID + AND cv.MedicalSurgicalID = pv.MedicalSurgicalID + AND cv.ChargeCodeID = pv.ChargeCodeID + WHERE cv.EntityGroupConfigID = @EntityGroupConfigID + AND cv.UnitTypeID = 145 + + -- if the source fiscal year = current fiscal year and timeclass is actual, we need to annualize the data + IF(@IsAnnualized = 1) + BEGIN + + DECLARE @IsLeapYear BIT = (CASE WHEN (@SourceFiscalYearID % 4 = 0 AND @SourceFiscalYearID % 100 <> 0) OR @SourceFiscalYearID % 400 = 0 THEN 1 ELSE 0 END) + DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded) + DECLARE @DaysInMonthsNotLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder > @MonthsLoaded) + + UPDATE + cv + SET + SampledBudget02 = CASE WHEN @MonthsLoaded >= 2 THEN SampledBudget02 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END, + SampledBudget03 = CASE WHEN @MonthsLoaded >= 3 THEN SampledBudget03 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END, + SampledBudget04 = CASE WHEN @MonthsLoaded >= 4 THEN SampledBudget04 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END, + SampledBudget05 = CASE WHEN @MonthsLoaded >= 5 THEN SampledBudget05 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END, + SampledBudget06 = CASE WHEN @MonthsLoaded >= 6 THEN SampledBudget06 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END, + SampledBudget07 = CASE WHEN @MonthsLoaded >= 7 THEN SampledBudget07 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END, + SampledBudget08 = CASE WHEN @MonthsLoaded >= 8 THEN SampledBudget08 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END, + SampledBudget09 = CASE WHEN @MonthsLoaded >= 9 THEN SampledBudget09 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END, + SampledBudget10 = CASE WHEN @MonthsLoaded >= 10 THEN SampledBudget10 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END, + SampledBudget11 = CASE WHEN @MonthsLoaded >= 11 THEN SampledBudget11 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END, + SampledBudget12 = CASE WHEN @MonthsLoaded >= 12 THEN SampledBudget12 ELSE ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) END + FROM [fp].[ChargeVolume] cv + WHERE cv.EntityGroupConfigID = @EntityGroupConfigID + AND cv.UnitTypeID = 145 + END + + IF ((SELECT StatisticsModel FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigID = @EntityGroupConfigID) = 0) -- StatisticsModel "0" is SL->CV->Stats, so using Service Lines + BEGIN + -- If we're using Service Lines we need to update the baseline. + DECLARE @BudgetConfigID INT = (SELECT bc.BudgetConfigID + FROM [fp].[EntityGroupConfig] ec + INNER JOIN [fp].[BudgetConfig] bc ON ec.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE EntityGroupConfigID = @EntityGroupConfigID) + + ;WITH ServiceLineEncounters AS ( + SELECT + EntityID, + PatientClassID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + SUM(TargetAdjusted01) AS TargetAdjusted01, + SUM(TargetAdjusted02) AS TargetAdjusted02, + SUM(TargetAdjusted03) AS TargetAdjusted03, + SUM(TargetAdjusted04) AS TargetAdjusted04, + SUM(TargetAdjusted05) AS TargetAdjusted05, + SUM(TargetAdjusted06) AS TargetAdjusted06, + SUM(TargetAdjusted07) AS TargetAdjusted07, + SUM(TargetAdjusted08) AS TargetAdjusted08, + SUM(TargetAdjusted09) AS TargetAdjusted09, + SUM(TargetAdjusted10) AS TargetAdjusted10, + SUM(TargetAdjusted11) AS TargetAdjusted11, + SUM(TargetAdjusted12) AS TargetAdjusted12, + SUM(InitialBudgetTotal) AS InitialBudgetTotal + FROM [fp].[ServiceLineEncounter] fsle + WHERE + fsle.BudgetConfigID = @BudgetConfigID + GROUP BY + EntityID, + PatientClassID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID + ) + UPDATE fcv + SET -- note that I tried other combinations of not using this ridiculous casting and they did not return the same rate value as the saved rate, so this is required. For more info see https://jira.sdt.local/browse/JAZZ-37271 + fcv.InitialBudget01 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted01), 0), + fcv.InitialBudget02 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted02), 0), + fcv.InitialBudget03 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted03), 0), + fcv.InitialBudget04 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted04), 0), + fcv.InitialBudget05 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted05), 0), + fcv.InitialBudget06 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted06), 0), + fcv.InitialBudget07 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted07), 0), + fcv.InitialBudget08 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted08), 0), + fcv.InitialBudget09 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted09), 0), + fcv.InitialBudget10 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted10), 0), + fcv.InitialBudget11 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted11), 0), + fcv.InitialBudget12 = IIF(sle.InitialBudgetTotal != 0, cast(cast(fcv.SampledBudgetTotal as decimal(19,8)) / cast(sle.InitialBudgetTotal as decimal(19,8))as decimal(19,8)) * (sle.TargetAdjusted12), 0) + FROM [fp].[ChargeVolume] fcv + INNER JOIN ServiceLineEncounters sle + ON fcv.AgeCohortID = sle.AgeCohortID + AND fcv.MedicalSurgicalID = sle.MedicalSurgicalID + AND fcv.PatientClassID = sle.PatientClassID + AND fcv.ServiceLineID = sle.ServiceLineID + AND fcv.EntityID = sle.EntityID + WHERE + fcv.BudgetConfigID = @BudgetConfigID + AND fcv.UnitTypeID = 145 + + END ELSE BEGIN + -- update the initial values to be equal to the sampled values + UPDATE + cv + SET + InitialBudget01 = SampledBudgetTotal / 12, + InitialBudget02 = SampledBudgetTotal / 12, + InitialBudget03 = SampledBudgetTotal / 12, + InitialBudget04 = SampledBudgetTotal / 12, + InitialBudget05 = SampledBudgetTotal / 12, + InitialBudget06 = SampledBudgetTotal / 12, + InitialBudget07 = SampledBudgetTotal / 12, + InitialBudget08 = SampledBudgetTotal / 12, + InitialBudget09 = SampledBudgetTotal / 12, + InitialBudget10 = SampledBudgetTotal / 12, + InitialBudget11 = SampledBudgetTotal / 12, + InitialBudget12 = SampledBudgetTotal - ((SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + + (SampledBudgetTotal / 12)) + FROM [fp].[ChargeVolume] cv + WHERE cv.EntityGroupConfigID = @EntityGroupConfigID AND cv.UnitTypeID = 145 + END +END +GO + + +--------------------------------------------- + +-- fp.procSampleChargeVolumeOriginalProjectionDollars +CREATE PROCEDURE [fp].[procSampleChargeVolumeOriginalProjectionDollars] + @EntityGroupConfigID int, + @IsEntityUsed BIT, + @IsPatientClassUsed BIT, + @CurrentYear INT, + @MonthsLoaded INT +AS +BEGIN +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-12-12 DM JAZZ-46455 Age Cohort and Medical/Seurgical is linked to Section Setup checkboxes +** 2 2023-01-26 NT JAZZ-48268 Make change to sample charge volume budget data into the new fp.ChargeVolume (data restructure) +*************************************************************/ + + DECLARE @IsAgeCohortDisabled BIT; + SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'AgeCohortID' AND PlanSectionID = 2 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + DECLARE @IsMedicalSurgicalDisabled BIT; + SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 2 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + -- Need to set the dollars based on the actual YTD + UPDATE + cv + SET + InitialProjectionDollars01 = ISNULL(Month01, 0), + InitialProjectionDollars02 = ISNULL(Month02, 0), + InitialProjectionDollars03 = ISNULL(Month03, 0), + InitialProjectionDollars04 = ISNULL(Month04, 0), + InitialProjectionDollars05 = ISNULL(Month05, 0), + InitialProjectionDollars06 = ISNULL(Month06, 0), + InitialProjectionDollars07 = ISNULL(Month07, 0), + InitialProjectionDollars08 = ISNULL(Month08, 0), + InitialProjectionDollars09 = ISNULL(Month09, 0), + InitialProjectionDollars10 = ISNULL(Month10, 0), + InitialProjectionDollars11 = ISNULL(Month11, 0), + InitialProjectionDollars12 = ISNULL(Month12, 0) + FROM + [fp].[ChargeVolume] cv + INNER JOIN + (SELECT cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, + CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cdm.AgeCohortID END AS AgeCohortID, + CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cdm.MedicalSurgicalID END AS MedicalSurgicalID, + cdm.ChargeCodeID, fm.MonthColumnName, SUM(Value) AS Value + FROM [int].[FactCDM] cdm + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cdm.FiscalMonthID + WHERE cdm.FiscalYearID = @CurrentYear + AND cdm.TimeclassID = 1 + AND cdm.IsDeleted = 0 + AND cdm.FiscalMonthID != 0 + AND cdm.UnitTypeID = 34 + GROUP BY cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, cdm.AgeCohortID, cdm.MedicalSurgicalID, cdm.ChargeCodeID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON cv.DepartmentID = pv.DepartmentID + AND cv.ServiceLineID = pv.ServiceLineID + AND cv.PatientClassID = pv.PatientClassID + AND cv.AgeCohortID = pv.AgeCohortID + AND cv.MedicalSurgicalID = pv.MedicalSurgicalID + AND cv.ChargeCodeID = pv.ChargeCodeID + WHERE cv.EntityGroupConfigID = @EntityGroupConfigID + + -- update the initial values. Need to do this separate because Initial could have already been flexed by SLV + UPDATE cv + SET + cv.InitialProjectionDollars01 = CASE WHEN @MonthsLoaded < 1 THEN cv.InitialProjection01 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars01 END, + cv.InitialProjectionDollars02 = CASE WHEN @MonthsLoaded < 2 THEN cv.InitialProjection02 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars02 END, + cv.InitialProjectionDollars03 = CASE WHEN @MonthsLoaded < 3 THEN cv.InitialProjection03 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars03 END, + cv.InitialProjectionDollars04 = CASE WHEN @MonthsLoaded < 4 THEN cv.InitialProjection04 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars04 END, + cv.InitialProjectionDollars05 = CASE WHEN @MonthsLoaded < 5 THEN cv.InitialProjection05 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars05 END, + cv.InitialProjectionDollars06 = CASE WHEN @MonthsLoaded < 6 THEN cv.InitialProjection06 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars06 END, + cv.InitialProjectionDollars07 = CASE WHEN @MonthsLoaded < 7 THEN cv.InitialProjection07 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars07 END, + cv.InitialProjectionDollars08 = CASE WHEN @MonthsLoaded < 8 THEN cv.InitialProjection08 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars08 END, + cv.InitialProjectionDollars09 = CASE WHEN @MonthsLoaded < 9 THEN cv.InitialProjection09 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars09 END, + cv.InitialProjectionDollars10 = CASE WHEN @MonthsLoaded < 10 THEN cv.InitialProjection10 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars10 END, + cv.InitialProjectionDollars11 = CASE WHEN @MonthsLoaded < 11 THEN cv.InitialProjection11 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars11 END, + cv.InitialProjectionDollars12 = CASE WHEN @MonthsLoaded < 12 THEN cv.InitialProjection12 * ISNULL(projCm.BaselineChargeRate, 0) ELSE cv.InitialProjectionDollars12 END + FROM [fp].[ChargeVolume] cv + LEFT JOIN [fp].[FactChargeMaster] projCm + ON projCm.BudgetConfigID = cv.BudgetConfigID + AND projCm.ChargeCodeID = cv.ChargeCodeID + AND projCm.TimeClassID = 12 + AND ((@IsEntityUsed = 1 AND projCm.EntityID = cv.EntityID) OR @IsEntityUsed = 0) + AND ((@IsPatientClassUsed = 1 AND projCm.PatientClassID = cv.PatientClassID) OR @IsPatientClassUsed = 0) + WHERE cv.EntityGroupConfigID = @EntityGroupConfigID + +END +GO + + +--------------------------------------------- + +-- fp.procSampleChargeVolumeOriginalProjectionUnits +CREATE PROCEDURE [fp].[procSampleChargeVolumeOriginalProjectionUnits] + @EntityGroupConfigID INT, + @CurrentFiscalYearID SMALLINT, + @MonthsLoaded INT +AS +BEGIN +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-12-12 DM JAZZ-46455 Age Cohort and Medical/Seurgical is linked to Section Setup checkboxes +** 2 2023-01-27 NT JAZZ-48268 Make change to sample charge volume projection data into the new fp.ChargeVolume (data restructure) +** 3 2023-07-27 MY JAZZ-58113 Update non-DSS CV sampling to flex InitialProjection by SLE if using +*************************************************************/ + + DECLARE @IsAgeCohortDisabled BIT; + SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'AgeCohortID' AND PlanSectionID = 2 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + DECLARE @IsMedicalSurgicalDisabled BIT; + SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 2 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + DECLARE @BudgetConfigID INT = (SELECT BudgetConfigID FROM fp.EntityGroupConfig egc INNER JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID WHERE egc.EntityGroupConfigID = @EntityGroupConfigID) + DECLARE @IsFlexInitialProjectionByEncounter BIT = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting WHERE Name = 'Flex Initial Projection ChargeVolume by Encounters' AND BudgetConfigID = @BudgetConfigID), 0) + + -- set the orig values for the months where we have data (month sort order <= @MonthsLoaded) + UPDATE + cv + SET + SampledProjection01 = ISNULL(Month01, 0), + SampledProjection02 = ISNULL(Month02, 0), + SampledProjection03 = ISNULL(Month03, 0), + SampledProjection04 = ISNULL(Month04, 0), + SampledProjection05 = ISNULL(Month05, 0), + SampledProjection06 = ISNULL(Month06, 0), + SampledProjection07 = ISNULL(Month07, 0), + SampledProjection08 = ISNULL(Month08, 0), + SampledProjection09 = ISNULL(Month09, 0), + SampledProjection10 = ISNULL(Month10, 0), + SampledProjection11 = ISNULL(Month11, 0), + SampledProjection12 = ISNULL(Month12, 0) + FROM + [fp].[ChargeVolume] cv + INNER JOIN + (SELECT cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, + CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE cdm.AgeCohortID END AS AgeCohortID, + CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE cdm.MedicalSurgicalID END AS MedicalSurgicalID, + cdm.ChargeCodeID, fm.MonthColumnName, SUM(Value) AS Value + FROM [int].[FactCDM] cdm + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = cdm.FiscalMonthID + WHERE cdm.FiscalYearID = @CurrentFiscalYearID AND cdm.TimeclassID = 1 AND cdm.IsDeleted = 0 AND cdm.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded AND cdm.UnitTypeID = 145 + GROUP BY cdm.DepartmentID, cdm.ServiceLineID, cdm.PatientClassID, cdm.AgeCohortID, cdm.MedicalSurgicalID, cdm.ChargeCodeID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON cv.DepartmentID = pv.DepartmentID + AND cv.ServiceLineID = pv.ServiceLineID + AND cv.PatientClassID = pv.PatientClassID + AND cv.AgeCohortID = pv.AgeCohortID + AND cv.MedicalSurgicalID = pv.MedicalSurgicalID + AND cv.ChargeCodeID = pv.ChargeCodeID + WHERE + cv.EntityGroupConfigID = @EntityGroupConfigID + AND cv.UnitTypeID = 145 + + -- copy the baseline data over for months without data (month sort order > @MonthsLoaded) + -- if the baseline is current year actual YTD, then the data would already have been annualized, if not, then we don't need to annualize + UPDATE + cv + SET + SampledProjection02 = CASE WHEN @MonthsLoaded < 2 THEN SampledBudget02 ELSE SampledProjection02 END, + SampledProjection03 = CASE WHEN @MonthsLoaded < 3 THEN SampledBudget03 ELSE SampledProjection03 END, + SampledProjection04 = CASE WHEN @MonthsLoaded < 4 THEN SampledBudget04 ELSE SampledProjection04 END, + SampledProjection05 = CASE WHEN @MonthsLoaded < 5 THEN SampledBudget05 ELSE SampledProjection05 END, + SampledProjection06 = CASE WHEN @MonthsLoaded < 6 THEN SampledBudget06 ELSE SampledProjection06 END, + SampledProjection07 = CASE WHEN @MonthsLoaded < 7 THEN SampledBudget07 ELSE SampledProjection07 END, + SampledProjection08 = CASE WHEN @MonthsLoaded < 8 THEN SampledBudget08 ELSE SampledProjection08 END, + SampledProjection09 = CASE WHEN @MonthsLoaded < 9 THEN SampledBudget09 ELSE SampledProjection09 END, + SampledProjection10 = CASE WHEN @MonthsLoaded < 10 THEN SampledBudget10 ELSE SampledProjection10 END, + SampledProjection11 = CASE WHEN @MonthsLoaded < 11 THEN SampledBudget11 ELSE SampledProjection11 END, + SampledProjection12 = CASE WHEN @MonthsLoaded < 12 THEN SampledBudget12 ELSE SampledProjection12 END + FROM + [fp].[ChargeVolume] cv + WHERE + cv.EntityGroupConfigID = @EntityGroupConfigID AND cv.UnitTypeID = 145 + + IF @IsFlexInitialProjectionByEncounter = 1 + BEGIN -- FF On + IF OBJECT_ID('tempdb..#tbl_entitygroup') IS NOT NULL DROP TABLE #tbl_entitygroup; + IF OBJECT_ID('tempdb..#sle') IS NOT NULL DROP TABLE #sle; + + CREATE TABLE #tbl_entitygroup (EntityGroupConfigID INT, IsAnnualized INT); + + CREATE TABLE #sle (EntityID INT, PatientClassID INT, ServiceLineID INT, AgeCohortID INT, MedicalSurgicalID INT, MSDRGID INT, CPTID INT, ProviderID INT, + InitialProjection01 DECIMAL(19,8),InitialProjection02 DECIMAL(19,8), InitialProjection03 DECIMAL(19,8), InitialProjection04 DECIMAL(19,8), InitialProjection05 DECIMAL(19,8), InitialProjection06 DECIMAL(19,8), + InitialProjection07 DECIMAL(19,8),InitialProjection08 DECIMAL(19,8), InitialProjection09 DECIMAL(19,8), InitialProjection10 DECIMAL(19,8), InitialProjection11 DECIMAL(19,8), InitialProjection12 DECIMAL(19,8), + InitialProjectionTotal DECIMAL(30,8), MonthsLoadedTotal DECIMAL(30,8)); + + INSERT INTO #tbl_entitygroup (EntityGroupConfigID, IsAnnualized) + SELECT EntityGroupConfigID, CASE WHEN ServiceLineEncounterTimeClassID = 1 AND ServiceLineEncounterFiscalYearID = @CurrentFiscalYearID THEN 1 ELSE 0 END + FROM [fp].[EntityGroupConfig] egc + INNER JOIN [fp].[BudgetConfig] bc on egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + + -- Set Initial to Sampled values + UPDATE + cv + SET + InitialProjection01 = SampledProjection01, + InitialProjection02 = SampledProjection02, + InitialProjection03 = SampledProjection03, + InitialProjection04 = SampledProjection04, + InitialProjection05 = SampledProjection05, + InitialProjection06 = SampledProjection06, + InitialProjection07 = SampledProjection07, + InitialProjection08 = SampledProjection08, + InitialProjection09 = SampledProjection09, + InitialProjection10 = SampledProjection10, + InitialProjection11 = SampledProjection11, + InitialProjection12 = SampledProjection12 + FROM [fp].[ChargeVolume] cv + WHERE cv.EntityGroupConfigID = @EntityGroupConfigID; + + -- Now update months not loaded using SLE flexing + INSERT INTO #sle (EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, + InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, + InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12, + InitialProjectionTotal, MonthsLoadedTotal) + SELECT EntityID, PatientClassID, ServiceLineID, AgeCohortID, MedicalSurgicalID, MSDRGID, CPTID, ProviderID, + SUM(InitialProjection01) AS InitialProjection01, SUM(InitialProjection02) AS InitialProjection02, SUM(InitialProjection03) AS InitialProjection03, + SUM(InitialProjection04) AS InitialProjection04, SUM(InitialProjection05) AS InitialProjection05, SUM(InitialProjection06) AS InitialProjection06, + SUM(InitialProjection07) AS InitialProjection07, SUM(InitialProjection08) AS InitialProjection08, SUM(InitialProjection09) AS InitialProjection09, + SUM(InitialProjection10) AS InitialProjection10, SUM(InitialProjection11) AS InitialProjection11, SUM(InitialProjection12) AS InitialProjection12, + SUM(InitialProjectionTotal) AS InitialProjectionTotal, + CASE WHEN @MonthsLoaded = 1 THEN SUM(sle.InitialProjection01) + WHEN @MonthsLoaded = 2 THEN SUM(sle.InitialProjection01 + sle.InitialProjection02) + WHEN @MonthsLoaded = 3 THEN SUM(sle.InitialProjection01 + sle.InitialProjection02 + sle.InitialProjection03) + WHEN @MonthsLoaded = 4 THEN SUM(sle.InitialProjection01 + sle.InitialProjection02 + sle.InitialProjection03 + sle.InitialProjection04) + WHEN @MonthsLoaded = 5 THEN SUM(sle.InitialProjection01 + sle.InitialProjection02 + sle.InitialProjection03 + sle.InitialProjection04 + sle.InitialProjection05) + WHEN @MonthsLoaded = 6 THEN SUM(sle.InitialProjection01 + sle.InitialProjection02 + sle.InitialProjection03 + sle.InitialProjection04 + sle.InitialProjection05 + sle.InitialProjection06) + WHEN @MonthsLoaded = 7 THEN SUM(sle.InitialProjection01 + sle.InitialProjection02 + sle.InitialProjection03 + sle.InitialProjection04 + sle.InitialProjection05 + sle.InitialProjection06 + sle.InitialProjection07) + WHEN @MonthsLoaded = 8 THEN SUM(sle.InitialProjection01 + sle.InitialProjection02 + sle.InitialProjection03 + sle.InitialProjection04 + sle.InitialProjection05 + sle.InitialProjection06 + sle.InitialProjection07 + sle.InitialProjection08) + WHEN @MonthsLoaded = 9 THEN SUM(sle.InitialProjection01 + sle.InitialProjection02 + sle.InitialProjection03 + sle.InitialProjection04 + sle.InitialProjection05 + sle.InitialProjection06 + sle.InitialProjection07 + sle.InitialProjection08 + sle.InitialProjection09) + WHEN @MonthsLoaded = 10 THEN SUM(sle.InitialProjection01 + sle.InitialProjection02 + sle.InitialProjection03 + sle.InitialProjection04 + sle.InitialProjection05 + sle.InitialProjection06 + sle.InitialProjection07 + sle.InitialProjection08 + sle.InitialProjection09 + sle.InitialProjection10) + WHEN @MonthsLoaded = 11 THEN SUM(sle.InitialProjection01 + sle.InitialProjection02 + sle.InitialProjection03 + sle.InitialProjection04 + sle.InitialProjection05 + sle.InitialProjection06 + sle.InitialProjection07 + sle.InitialProjection08 + sle.InitialProjection09 + sle.InitialProjection10 + sle.InitialProjection11) + WHEN @MonthsLoaded = 12 THEN SUM(sle.InitialProjection01 + sle.InitialProjection02 + sle.InitialProjection03 + sle.InitialProjection04 + sle.InitialProjection05 + sle.InitialProjection06 + sle.InitialProjection07 + sle.InitialProjection08 + sle.InitialProjection09 + sle.InitialProjection10 + sle.InitialProjection11 + sle.InitialProjection12) + END AS MonthsLoadedTotal + FROM [fp].[ServiceLineEncounter] sle + WHERE + sle.BudgetConfigID = @BudgetConfigID + GROUP BY + EntityID, + PatientClassID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + MSDRGID, + CPTID, + ProviderID + + -- Non-annualized + IF EXISTS (SELECT 1 FROM #tbl_entitygroup WHERE IsAnnualized = 0) + BEGIN + -- Next we need to flex the Initial Projection months not loaded + -- Calculation: (Charges (Months Loaded) / Encounters (Months Loaded)) * Initial Projection Charges by Month + -- This is essentially calculating the Charge Per Encounter and the flexing it. This is similar to how we'd do it in Statistics or other sections + -- except we aren't storing the rate (in the future we probably should update this to be like stats) + UPDATE cv + SET + cv.InitialProjection01 = cv.InitialProjection01, + cv.InitialProjection02 = CASE WHEN @MonthsLoaded < 2 THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection02), 0) ELSE cv.InitialProjection02 END, + cv.InitialProjection03 = CASE WHEN @MonthsLoaded < 3 THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection03), 0) ELSE cv.InitialProjection03 END, + cv.InitialProjection04 = CASE WHEN @MonthsLoaded < 4 THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection04), 0) ELSE cv.InitialProjection04 END, + cv.InitialProjection05 = CASE WHEN @MonthsLoaded < 5 THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection05), 0) ELSE cv.InitialProjection05 END, + cv.InitialProjection06 = CASE WHEN @MonthsLoaded < 6 THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection06), 0) ELSE cv.InitialProjection06 END, + cv.InitialProjection07 = CASE WHEN @MonthsLoaded < 7 THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection07), 0) ELSE cv.InitialProjection07 END, + cv.InitialProjection08 = CASE WHEN @MonthsLoaded < 8 THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection08), 0) ELSE cv.InitialProjection08 END, + cv.InitialProjection09 = CASE WHEN @MonthsLoaded < 9 THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection09), 0) ELSE cv.InitialProjection09 END, + cv.InitialProjection10 = CASE WHEN @MonthsLoaded < 10 THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection10), 0) ELSE cv.InitialProjection10 END, + cv.InitialProjection11 = CASE WHEN @MonthsLoaded < 11 THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection11), 0) ELSE cv.InitialProjection11 END, + cv.InitialProjection12 = CASE WHEN @MonthsLoaded < 12 THEN IIF(sle.InitialProjectionTotal != 0, CAST(CAST(cv.SampledProjectionTotal AS DECIMAL(19,8)) / CAST(sle.InitialProjectionTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection12), 0) ELSE cv.InitialProjection12 END + FROM [fp].[ChargeVolume] cv + INNER JOIN #sle sle + ON cv.ServiceEntityID = sle.EntityID + AND cv.PatientClassID = sle.PatientClassID + AND cv.ServiceLineID = sle.ServiceLineID + AND cv.AgeCohortID = sle.AgeCohortID + AND cv.MedicalSurgicalID = sle.MedicalSurgicalID + AND cv.MSDRGID = sle.MSDRGID + AND cv.PrimaryCPTID = sle.CPTID + AND cv.ServiceProviderID = sle.ProviderID + INNER JOIN #tbl_entitygroup egc ON cv.EntityGroupConfigID = egc.EntityGroupConfigID + WHERE cv.BudgetConfigID = @BudgetConfigID + AND egc.IsAnnualized = 0; + END + + -- Annualized + IF EXISTS (SELECT 1 FROM #tbl_entitygroup WHERE IsAnnualized = 1) + BEGIN + + EXEC [dbo].[procSysDropTempTable] '#chargeMonthsLoaded' + + SELECT + cv.ChargeVolumeID, + CASE WHEN @MonthsLoaded = 1 THEN SUM(cv.InitialProjection01) + WHEN @MonthsLoaded = 2 THEN SUM(cv.InitialProjection01 + cv.InitialProjection02) + WHEN @MonthsLoaded = 3 THEN SUM(cv.InitialProjection01 + cv.InitialProjection02 + cv.InitialProjection03) + WHEN @MonthsLoaded = 4 THEN SUM(cv.InitialProjection01 + cv.InitialProjection02 + cv.InitialProjection03 + cv.InitialProjection04) + WHEN @MonthsLoaded = 5 THEN SUM(cv.InitialProjection01 + cv.InitialProjection02 + cv.InitialProjection03 + cv.InitialProjection04 + cv.InitialProjection05) + WHEN @MonthsLoaded = 6 THEN SUM(cv.InitialProjection01 + cv.InitialProjection02 + cv.InitialProjection03 + cv.InitialProjection04 + cv.InitialProjection05 + cv.InitialProjection06) + WHEN @MonthsLoaded = 7 THEN SUM(cv.InitialProjection01 + cv.InitialProjection02 + cv.InitialProjection03 + cv.InitialProjection04 + cv.InitialProjection05 + cv.InitialProjection06 + cv.InitialProjection07) + WHEN @MonthsLoaded = 8 THEN SUM(cv.InitialProjection01 + cv.InitialProjection02 + cv.InitialProjection03 + cv.InitialProjection04 + cv.InitialProjection05 + cv.InitialProjection06 + cv.InitialProjection07 + cv.InitialProjection08) + WHEN @MonthsLoaded = 9 THEN SUM(cv.InitialProjection01 + cv.InitialProjection02 + cv.InitialProjection03 + cv.InitialProjection04 + cv.InitialProjection05 + cv.InitialProjection06 + cv.InitialProjection07 + cv.InitialProjection08 + cv.InitialProjection09) + WHEN @MonthsLoaded = 10 THEN SUM(cv.InitialProjection01 + cv.InitialProjection02 + cv.InitialProjection03 + cv.InitialProjection04 + cv.InitialProjection05 + cv.InitialProjection06 + cv.InitialProjection07 + cv.InitialProjection08 + cv.InitialProjection09 + cv.InitialProjection10) + WHEN @MonthsLoaded = 11 THEN SUM(cv.InitialProjection01 + cv.InitialProjection02 + cv.InitialProjection03 + cv.InitialProjection04 + cv.InitialProjection05 + cv.InitialProjection06 + cv.InitialProjection07 + cv.InitialProjection08 + cv.InitialProjection09 + cv.InitialProjection10 + cv.InitialProjection11) + WHEN @MonthsLoaded = 12 THEN SUM(cv.InitialProjection01 + cv.InitialProjection02 + cv.InitialProjection03 + cv.InitialProjection04 + cv.InitialProjection05 + cv.InitialProjection06 + cv.InitialProjection07 + cv.InitialProjection08 + cv.InitialProjection09 + cv.InitialProjection10 + cv.InitialProjection11 + cv.InitialProjection12) + END AS MonthsLoadedTotal + INTO #chargeMonthsLoaded + FROM [fp].[ChargeVolume] cv + INNER JOIN #sle sle + ON cv.ServiceEntityID = sle.EntityID + AND cv.PatientClassID = sle.PatientClassID + AND cv.ServiceLineID = sle.ServiceLineID + AND cv.AgeCohortID = sle.AgeCohortID + AND cv.MedicalSurgicalID = sle.MedicalSurgicalID + AND cv.MSDRGID = sle.MSDRGID + AND cv.PrimaryCPTID = sle.CPTID + AND cv.ServiceProviderID = sle.ProviderID + INNER JOIN #tbl_entitygroup egc ON cv.EntityGroupConfigID = egc.EntityGroupConfigID + WHERE cv.BudgetConfigID = @BudgetConfigID + AND egc.IsAnnualized = 1 + GROUP BY cv.ChargeVolumeID; + + -- Next we need to flex the Initial Projection months not loaded + -- Calculation: (Initial Charges (Months Loaded) / Initial Encounters (Months Loaded)) * Initial Projection Charges by Month + -- This is essentially calculating the Charge Per Encounter and the flexing it. This is similar to how we'd do it in Statistics or other sections + -- except we aren't storing the rate (in the future we probably should update this to be like stats) + UPDATE cv + SET + cv.InitialProjection01 = cv.InitialProjection01, + cv.InitialProjection02 = CASE WHEN @MonthsLoaded < 2 THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection02), 0) ELSE cv.InitialProjection02 END, + cv.InitialProjection03 = CASE WHEN @MonthsLoaded < 3 THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection03), 0) ELSE cv.InitialProjection03 END, + cv.InitialProjection04 = CASE WHEN @MonthsLoaded < 4 THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection04), 0) ELSE cv.InitialProjection04 END, + cv.InitialProjection05 = CASE WHEN @MonthsLoaded < 5 THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection05), 0) ELSE cv.InitialProjection05 END, + cv.InitialProjection06 = CASE WHEN @MonthsLoaded < 6 THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection06), 0) ELSE cv.InitialProjection06 END, + cv.InitialProjection07 = CASE WHEN @MonthsLoaded < 7 THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection07), 0) ELSE cv.InitialProjection07 END, + cv.InitialProjection08 = CASE WHEN @MonthsLoaded < 8 THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection08), 0) ELSE cv.InitialProjection08 END, + cv.InitialProjection09 = CASE WHEN @MonthsLoaded < 9 THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection09), 0) ELSE cv.InitialProjection09 END, + cv.InitialProjection10 = CASE WHEN @MonthsLoaded < 10 THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection10), 0) ELSE cv.InitialProjection10 END, + cv.InitialProjection11 = CASE WHEN @MonthsLoaded < 11 THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection11), 0) ELSE cv.InitialProjection11 END, + cv.InitialProjection12 = CASE WHEN @MonthsLoaded < 12 THEN IIF(sle.MonthsLoadedTotal != 0, CAST(CAST(cml.MonthsLoadedTotal AS DECIMAL(19,8)) / CAST(sle.MonthsLoadedTotal AS DECIMAL(19,8)) AS DECIMAL(19,8)) * (sle.InitialProjection12), 0) ELSE cv.InitialProjection12 END + FROM [fp].[ChargeVolume] cv + INNER JOIN #chargeMonthsLoaded cml ON cv.ChargeVolumeID = cml.ChargeVolumeID + INNER JOIN #sle sle + ON cv.ServiceEntityID = sle.EntityID + AND cv.PatientClassID = sle.PatientClassID + AND cv.ServiceLineID = sle.ServiceLineID + AND cv.AgeCohortID = sle.AgeCohortID + AND cv.MedicalSurgicalID = sle.MedicalSurgicalID + AND cv.MSDRGID = sle.MSDRGID + AND cv.PrimaryCPTID = sle.CPTID + AND cv.ServiceProviderID = sle.ProviderID + INNER JOIN #tbl_entitygroup egc + ON cv.EntityGroupConfigID = egc.EntityGroupConfigID + WHERE + cv.BudgetConfigID = @BudgetConfigID AND egc.IsAnnualized = 1; + END + END ELSE + BEGIN -- FF Off + + CREATE TABLE #Totals (ChargeVolumeID INT, SampledProjectionTotal DECIMAL(19,8), NewValue DECIMAL(19,8)); + INSERT INTO #Totals (ChargeVolumeID, SampledProjectionTotal) + SELECT ChargeVolumeID, + CASE WHEN @MonthsLoaded = 11 THEN cv.SampledProjection12 + WHEN @MonthsLoaded = 10 THEN cv.SampledProjection11 + cv.SampledProjection12 + WHEN @MonthsLoaded = 9 THEN cv.SampledProjection10 + cv.SampledProjection11 + cv.SampledProjection12 + WHEN @MonthsLoaded = 8 THEN cv.SampledProjection09 + cv.SampledProjection10 + cv.SampledProjection11 + cv.SampledProjection12 + WHEN @MonthsLoaded = 7 THEN cv.SampledProjection08 + cv.SampledProjection09 + cv.SampledProjection10 + cv.SampledProjection11 + cv.SampledProjection12 + WHEN @MonthsLoaded = 6 THEN cv.SampledProjection07 + cv.SampledProjection08 + cv.SampledProjection09 + cv.SampledProjection10 + cv.SampledProjection11 + cv.SampledProjection12 + WHEN @MonthsLoaded = 5 THEN cv.SampledProjection06 + cv.SampledProjection07 + cv.SampledProjection08 + cv.SampledProjection09 + cv.SampledProjection10 + cv.SampledProjection11 + cv.SampledProjection12 + WHEN @MonthsLoaded = 4 THEN cv.SampledProjection05 + cv.SampledProjection06 + cv.SampledProjection07 + cv.SampledProjection08 + cv.SampledProjection09 + cv.SampledProjection10 + cv.SampledProjection11 + cv.SampledProjection12 + WHEN @MonthsLoaded = 3 THEN cv.SampledProjection04 + cv.SampledProjection05 + cv.SampledProjection06 + cv.SampledProjection07 + cv.SampledProjection08 + cv.SampledProjection09 + cv.SampledProjection10 + cv.SampledProjection11 + cv.SampledProjection12 + WHEN @MonthsLoaded = 2 THEN cv.SampledProjection03 + cv.SampledProjection04 + cv.SampledProjection05 + cv.SampledProjection06 + cv.SampledProjection07 + cv.SampledProjection08 + cv.SampledProjection09 + cv.SampledProjection10 + cv.SampledProjection11 + cv.SampledProjection12 + WHEN @MonthsLoaded = 1 THEN cv.SampledProjection02 + cv.SampledProjection03 + cv.SampledProjection04 + cv.SampledProjection05 + cv.SampledProjection06 + cv.SampledProjection07 + cv.SampledProjection08 + cv.SampledProjection09 + cv.SampledProjection10 + cv.SampledProjection11 + cv.SampledProjection12 + ELSE 0 + END + FROM [fp].[ChargeVolume] cv + WHERE cv.EntityGroupConfigID = @EntityGroupConfigID + AND cv.UnitTypeID = 145 + + UPDATE a + SET NewValue = SampledProjectionTotal / (12.0 - @MonthsLoaded) + FROM #Totals a + + UPDATE cv + SET + InitialProjection01 = CASE WHEN @MonthsLoaded >= 1 THEN cv.SampledProjection01 ELSE NewValue END, + InitialProjection02 = CASE WHEN @MonthsLoaded >= 2 THEN cv.SampledProjection02 ELSE NewValue END, + InitialProjection03 = CASE WHEN @MonthsLoaded >= 3 THEN cv.SampledProjection03 ELSE NewValue END, + InitialProjection04 = CASE WHEN @MonthsLoaded >= 4 THEN cv.SampledProjection04 ELSE NewValue END, + InitialProjection05 = CASE WHEN @MonthsLoaded >= 5 THEN cv.SampledProjection05 ELSE NewValue END, + InitialProjection06 = CASE WHEN @MonthsLoaded >= 6 THEN cv.SampledProjection06 ELSE NewValue END, + InitialProjection07 = CASE WHEN @MonthsLoaded >= 7 THEN cv.SampledProjection07 ELSE NewValue END, + InitialProjection08 = CASE WHEN @MonthsLoaded >= 8 THEN cv.SampledProjection08 ELSE NewValue END, + InitialProjection09 = CASE WHEN @MonthsLoaded >= 9 THEN cv.SampledProjection09 ELSE NewValue END, + InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN cv.SampledProjection10 ELSE NewValue END, + InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN cv.SampledProjection11 ELSE NewValue END, + InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN cv.SampledProjection12 ELSE NewValue END + FROM [fp].[ChargeVolume] cv INNER JOIN #Totals t on cv.ChargeVolumeID = t.ChargeVolumeID + WHERE cv.EntityGroupConfigID = @EntityGroupConfigID + AND cv.UnitTypeID = 145 + + END + +END +GO + + +--------------------------------------------- + +-- fp.procSampleChargeVolumeProjectionData +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-01-31 NT JAZZ-48268 Make change to use the new fp.ChargeVolume (data restructure) +*************************************************************/ +CREATE PROCEDURE [fp].[procSampleChargeVolumeProjectionData] + @EntityGroupConfigID int +AS +BEGIN + + UPDATE + cv + SET + ProjectionAdjusted01 = InitialProjection01, + ProjectionAdjusted02 = InitialProjection02, + ProjectionAdjusted03 = InitialProjection03, + ProjectionAdjusted04 = InitialProjection04, + ProjectionAdjusted05 = InitialProjection05, + ProjectionAdjusted06 = InitialProjection06, + ProjectionAdjusted07 = InitialProjection07, + ProjectionAdjusted08 = InitialProjection08, + ProjectionAdjusted09 = InitialProjection09, + ProjectionAdjusted10 = InitialProjection10, + ProjectionAdjusted11 = InitialProjection11, + ProjectionAdjusted12 = InitialProjection12 + FROM [fp].[ChargeVolume] cv + WHERE cv.EntityGroupConfigID = @EntityGroupConfigID + AND cv.UnitTypeID = 145 + AND IsNew = 0 + +END +GO + + +--------------------------------------------- + +-- fp.procSampleDependentStatisticsByDriverStatisticsRates +CREATE PROCEDURE [fp].[procSampleDependentStatisticsByDriverStatisticsRates] + @BudgetConfigID INT, + @CurrentFiscalYearID SMALLINT, + @MonthsLoaded INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 12-14-2020 MY JAZZ-11324 Initial + ** 2 2021-02-18 BK JAZZ-15007 Add distinct to fix flexing inflation problem + ** 3 2022-09-12 BK JAZZ-43016 Add provider FF to sample rates + ** 4 2022-06-20 MY JAZZ-53443 Update stats sampling for cross department stats flexing + ** 5 2023-09-19 JB JAZZ-59196 Remove FF Dependent Statistics Flex By Provider + ** 6 2024-10-01 MY JAZZ-77827 Dependent Stat with multiple Drivers is causing inflated rates + *************************************************************/ + + IF OBJECT_ID('tempdb..#entityGroupConfig') IS NOT NULL DROP TABLE #entityGroupConfig + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#filteredFlexConfigTable') IS NOT NULL DROP TABLE #filteredFlexConfigTable + IF OBJECT_ID('tempdb..#drivers') IS NOT NULL DROP TABLE #drivers + IF OBJECT_ID('tempdb..#rolledUpDrivers') IS NOT NULL DROP TABLE #rolledUpDrivers + IF OBJECT_ID('tempdb..#dependents') IS NOT NULL DROP TABLE #dependents + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + DECLARE @Driver INT = (SELECT SubSectionID FROM [fp].[PlanSubsection] sub INNER JOIN [fp].[PlanSection] pe ON sub.PlanSectionID = pe.PlanSectionID WHERE pe.Description = 'Statistics' AND sub.Subsection = 'Driver'), + @Dependent INT = (SELECT SubSectionID FROM [fp].[PlanSubsection] sub INNER JOIN [fp].[PlanSection] pe ON sub.PlanSectionID = pe.PlanSectionID WHERE pe.Description = 'Statistics' AND sub.Subsection = 'Dependent') + + -- JAZZ-77827: Dependent Stat with multiple Drivers not working as expected + DECLARE @IsDriverCalculationFixEnabled BIT = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting + WHERE BudgetConfigID = @BudgetConfigID AND Name = 'Enabled Multiple Driver Fix for Dependent Statistics Flexing'), 0) + + -- Unlike other rate sampling, we can just use the sampled values. In other rates, we need to typically use the baseline of what we're flexing + -- so we can compare apples to apples. You wouldn't want to compare 2018 Actuals to 2017 Budget for example. Stats is unique because we're doing + -- stats to stats so they'll always have the same baseline because flexing is inter-department. Because of this, we need to break out annualization based + -- on the entity group config since if one department uses annualization, it doesn't mean another one would. + CREATE TABLE #entityGroupConfig ( + EntityGroupConfigID INT NOT NULL, + IsAnnualized BIT NOT NULL + ); + + INSERT INTO #entityGroupConfig (EntityGroupConfigID, IsAnnualized) + SELECT + EntityGroupConfigID, + CASE WHEN egc.StatisticsFiscalYearID = @CurrentFiscalYearID AND egc.StatisticsTimeClassID = 1 THEN 1 ELSE 0 END + FROM fp.EntityGroupConfig egc + INNER JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + + CREATE TABLE #filteredFlexConfigTable ( + DepartmentID INT NOT NULL, + DriverAccountID INT NOT NULL, + DependentAccountID INT NOT NULL, + SourceDepartmentID INT NOT NULL + ); + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #filteredFlexConfigTable (DepartmentID, DriverAccountID, DependentAccountID, SourceDepartmentID) + SELECT DISTINCT + fcm.DepartmentID, + StatAccountID, + DependentStatisticAccountID, + fcm.SourceDepartmentID + FROM fp.FlexConfigMapping fcm + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = fcm.DepartmentID + INNER JOIN fp.EntityGroupConfig egc ON fcm.EntityGroupConfigID = egc.EntityGroupConfigID + INNER JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE BudgetConfigID = @BudgetConfigID + AND FlexingTypeID = 8 + END ELSE BEGIN + INSERT INTO #filteredFlexConfigTable (DepartmentID, DriverAccountID, DependentAccountID, SourceDepartmentID) + SELECT DISTINCT + fcm.DepartmentID, + StatAccountID, + DependentStatisticAccountID, + fcm.SourceDepartmentID + FROM fp.FlexConfigMapping fcm + INNER JOIN fp.EntityGroupConfig egc ON fcm.EntityGroupConfigID = egc.EntityGroupConfigID + INNER JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE BudgetConfigID = @BudgetConfigID + AND FlexingTypeID = 8 + END + + -- 1. For statistics rates we calculate it by taking the total dependent stats / driver stats. We do it to the initial budget so that + -- it can be used within the engine after a configuration change. Sampled $/UOS doesn't really matter as it can change with each configuration change. + -- 2. Projection rates should match the budget rates (this is the same for other flexing types) + -- 3. Calculate the stats for each Department/Account that is setup to be flexed by stats + -- 4. Rates DO NOT vary by month + + -- Drivers + -- Calculate the stats for each Department/Account that is setup to be flexed by stats + CREATE TABLE #drivers (DepartmentID INT, SourceDepartmentID INT, DependentAccountID INT, ProviderID INT, SampledBudgetTotal DECIMAL(19,8)) + CREATE TABLE #dependents (DepartmentID INT, DependentAccountID INT, ProviderID INT, SampledBudgetTotal DECIMAL(19,8)) + + INSERT INTO #drivers (DepartmentID, SourceDepartmentID, DependentAccountID, ProviderID, SampledBudgetTotal) + SELECT + map.DepartmentID, + map.SourceDepartmentID, + map.DependentAccountID, + stat.ProviderID, + (SUM(CASE WHEN 1 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget01 ELSE 0 END + + CASE WHEN 2 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget02 ELSE 0 END + + CASE WHEN 3 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget03 ELSE 0 END + + CASE WHEN 4 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget04 ELSE 0 END + + CASE WHEN 5 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget05 ELSE 0 END + + CASE WHEN 6 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget06 ELSE 0 END + + CASE WHEN 7 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget07 ELSE 0 END + + CASE WHEN 8 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget08 ELSE 0 END + + CASE WHEN 9 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget09 ELSE 0 END + + CASE WHEN 10 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget10 ELSE 0 END + + CASE WHEN 11 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget11 ELSE 0 END + + CASE WHEN 12 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget12 ELSE 0 END)) AS SampledBudgetTotal -- If it's annualized we still only want the months loaded. + FROM #filteredFlexConfigTable map + INNER JOIN fp.FactStatistics stat ON map.SourceDepartmentID = stat.DepartmentID AND map.DriverAccountID = stat.AccountID AND stat.SubsectionID = @Driver + INNER JOIN #entityGroupConfig egc ON stat.EntityGroupConfigID = egc.EntityGroupConfigID + GROUP BY + map.DepartmentID, map.SourceDepartmentID, map.DependentAccountID, stat.ProviderID + + CREATE TABLE #dependentMapping ( + DepartmentID INT, + DriverAccountID INT, + DependentAccountID INT + ) + + IF @IsDriverCalculationFixEnabled = 1 + BEGIN + INSERT INTO #dependentMapping (DepartmentID, DriverAccountID, DependentAccountID) + SELECT DISTINCT DepartmentID, 0 AS DriverAccountID, DependentAccountID FROM #filteredFlexConfigTable + END ELSE BEGIN + INSERT INTO #dependentMapping (DepartmentID, DriverAccountID, DependentAccountID) + SELECT DISTINCT DepartmentID, DriverAccountID, DependentAccountID FROM #filteredFlexConfigTable + END + + -- Dependents + -- We just need to find the specific dependent values so we can take the previous temp table to calculate a rate + INSERT INTO #dependents (DepartmentID, DependentAccountID, ProviderID, SampledBudgetTotal) + SELECT + map.DepartmentID, + map.DependentAccountID, stat.ProviderID, + (SUM(CASE WHEN 1 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget01 ELSE 0 END + + CASE WHEN 2 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget02 ELSE 0 END + + CASE WHEN 3 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget03 ELSE 0 END + + CASE WHEN 4 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget04 ELSE 0 END + + CASE WHEN 5 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget05 ELSE 0 END + + CASE WHEN 6 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget06 ELSE 0 END + + CASE WHEN 7 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget07 ELSE 0 END + + CASE WHEN 8 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget08 ELSE 0 END + + CASE WHEN 9 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget09 ELSE 0 END + + CASE WHEN 10 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget10 ELSE 0 END + + CASE WHEN 11 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget11 ELSE 0 END + + CASE WHEN 12 <= @MonthsLoaded OR egc.IsAnnualized = 0 THEN SampledBudget12 ELSE 0 END)) AS SampledBudgetTotal -- If it's annualized we still only wants the months loaded. + FROM #dependentMapping map + INNER JOIN fp.FactStatistics stat ON map.DepartmentID = stat.DepartmentID AND map.DependentAccountID = stat.AccountID AND stat.SubsectionID = @Dependent + INNER JOIN #entityGroupConfig egc ON stat.EntityGroupConfigID = egc.EntityGroupConfigID + GROUP BY + map.DepartmentID, map.DependentAccountID, stat.ProviderID + + -- Once we get the driver data by source department, we need to roll it up for regular department so the calculation works correctly + SELECT + DepartmentID, + DependentAccountID, + ProviderID, + SUM(SampledBudgetTotal) AS SampledBudgetTotal + INTO #rolledUpDrivers + FROM #drivers + GROUP BY + DepartmentID, + DependentAccountID, + ProviderID + + IF (@IsDebug = 0) + BEGIN + -- Set the rate values on statistics table + UPDATE + stat + SET + InitialBudgetRate01 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialBudgetRate02 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialBudgetRate03 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialBudgetRate04 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialBudgetRate05 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialBudgetRate06 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialBudgetRate07 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialBudgetRate08 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialBudgetRate09 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialBudgetRate10 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialBudgetRate11 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialBudgetRate12 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + + -- Projection rates should match the budget rates and use the budget baseline to calculate + InitialProjectionRate01 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialProjectionRate02 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialProjectionRate03 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialProjectionRate04 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialProjectionRate05 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialProjectionRate06 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialProjectionRate07 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialProjectionRate08 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialProjectionRate09 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialProjectionRate10 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialProjectionRate11 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0), + InitialProjectionRate12 = COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) + FROM + [fp].[FactStatistics] stat + INNER JOIN #rolledUpDrivers driver ON stat.DepartmentID = driver.DepartmentID AND stat.AccountID = driver.DependentAccountID and stat.ProviderID = driver.ProviderID + INNER JOIN #dependents [dependent] ON stat.DepartmentID = [dependent].DepartmentID AND stat.AccountID = [dependent].DependentAccountID and stat.ProviderID = [dependent].ProviderID + WHERE driver.ProviderID = [dependent].ProviderID + AND stat.UnitTypeID = 140 + AND stat.BudgetConfigID = @BudgetConfigID + AND ( + stat.InitialBudgetRate01 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialBudgetRate02 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialBudgetRate03 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialBudgetRate04 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialBudgetRate05 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialBudgetRate06 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialBudgetRate07 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialBudgetRate08 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialBudgetRate09 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialBudgetRate10 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialBudgetRate11 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialBudgetRate12 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialProjectionRate01 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialProjectionRate02 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialProjectionRate03 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialProjectionRate04 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialProjectionRate05 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialProjectionRate06 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialProjectionRate07 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialProjectionRate08 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialProjectionRate09 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialProjectionRate10 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialProjectionRate11 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0) OR + stat.InitialProjectionRate12 != COALESCE(dependent.SampledBudgetTotal / NULLIF(driver.SampledBudgetTotal, 0), 0)) + END ELSE BEGIN + SELECT 'filteredFlexConfigTable', * FROM #filteredFlexConfigTable + SELECT 'entityGroupConfig', * FROM #entityGroupConfig + SELECT 'drivers', * FROM #drivers + SELECT 'FilterByDepartment', * FROM #FilterByDepartment + SELECT 'dependents', * FROM #dependents + SELECT 'rolledUpDrivers', * FROM #rolledUpDrivers + END + +END +GO + + +--------------------------------------------- + +-- fp.procSampleEncountersToReimbursement +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-02-04 MY JAZZ-31904 Initial +** 2 2022-06-15 MY JAZZ-37901 Create Fix Change History Process for Reimbursement +** 3 2022-09-29 BW JAZZ-43894 Update to join on projection with budget phase 2 +** 4 2023-01-17 BK JAZZ-48267 New data structure +** 5 2023-11-15 BK JAZZ-62974 Fix issue with Encounters not being pushed to Reimbursement because of missing Charges data +** 6 2024-01-11 AO JAZZ-64530 Data transfer for SLE is based on selected Model in Plan Config +*************************************************************/ +CREATE PROCEDURE [fp].[procSampleEncountersToReimbursement] + @BudgetConfigID INT, + @IsReimbursementGLEnabled BIT = 0, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + DECLARE @IsMedicalSurgicalUsed BIT, + @IsMsdrgUsed BIT, + @IsCptUsed BIT + + SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 5 -- Reimbursement - Encounters + AND ss.LevelID = 'MedicalSurgicalID' + + SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 5 -- Reimbursement - Encounters + AND ss.LevelID = 'MSDRGID' + + SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 5 -- Reimbursement - Encounters + AND ss.LevelID = 'PrimaryCPTID' + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + IF OBJECT_ID('tempdb..#factReimbursementEncounters') IS NOT NULL DROP TABLE #factReimbursementEncounters; + IF OBJECT_ID('tempdb..#projectionBasisIDs') IS NOT NULL DROP TABLE #projectionBasisIDs + IF OBJECT_ID('tempdb..#budgetBasisIDs') IS NOT NULL DROP TABLE #budgetBasisIDs + + CREATE TABLE #budgetBasisIDs (ReimbursementEncounterID INT); + CREATE TABLE #projectionBasisIDs (ReimbursementEncounterID INT); + + CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT); + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #encounterTargeting (EntityID INT, ServiceLineID INT); + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #encounterTargeting (EntityID, ServiceLineID) + SELECT DISTINCT map.EntityID, map.ServiceLineID + FROM fp.ServiceLineEncounterChargeVolumeMapping map WITH (READUNCOMMITTED) + INNER JOIN #ChargeVolumeDepartments targeting ON map.DepartmentID = targeting.DepartmentID + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = map.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE map.BudgetConfigID = @BudgetConfigID + AND ((@IsReimbursementGLEnabled = 1 + AND (bc.DefaultReimbursementNetRevenueModelID = 1 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model + OR rnrm.NetRevenueModelID = 1) + OR @IsReimbursementGLEnabled = 0) + UNION + SELECT DISTINCT sle.EntityID, sle.ServiceLineID + FROM fp.ServiceLineEncounter sle + LEFT JOIN fp.ChargeVolume cv on sle.BudgetConfigID = cv.BudgetConfigID AND sle.EntityID = cv.EntityID AND sle.ServiceLineID = cv.ServiceLineID + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = sle.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE sle.BudgetConfigID = @BudgetConfigID AND cv.EntityID IS NULL + AND ((@IsReimbursementGLEnabled = 1 + AND (bc.DefaultReimbursementNetRevenueModelID = 1 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model + OR rnrm.NetRevenueModelID = 1) + OR @IsReimbursementGLEnabled = 0) + + END ELSE + BEGIN + INSERT INTO #encounterTargeting (EntityID, ServiceLineID) + SELECT DISTINCT map.EntityID, map.ServiceLineID + FROM fp.ServiceLineEncounter map WITH (READUNCOMMITTED) + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = map.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE map.BudgetConfigID = @BudgetConfigID + AND ((@IsReimbursementGLEnabled = 1 + AND (bc.DefaultReimbursementNetRevenueModelID = 1 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model + OR rnrm.NetRevenueModelID = 1) + OR @IsReimbursementGLEnabled = 0) + END + + -- We are only moving Budget over and not projection because we don't display the baseline for projection so we don't need it. If we do ever need it, we'll need to add it to the mix table as well. + SELECT DISTINCT sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN sle.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, + sle.PayorID, sle.PayorGroupID, + CASE WHEN @IsMsdrgUsed = 1 THEN sle.MSDRGID ELSE 0 END AS MSDRGID, + CASE WHEN @IsCptUsed = 1 THEN sle.CPTID ELSE 0 END AS CPTID, + SUM(TargetAdjusted01) AS Target01, SUM(TargetAdjusted02) AS Target02, SUM(TargetAdjusted03) AS Target03, + SUM(TargetAdjusted04) AS Target04, SUM(TargetAdjusted05) AS Target05, SUM(TargetAdjusted06) AS Target06, + SUM(TargetAdjusted07) AS Target07, SUM(TargetAdjusted08) AS Target08, SUM(TargetAdjusted09) AS Target09, + SUM(TargetAdjusted10) AS Target10, SUM(TargetAdjusted11) AS Target11, SUM(TargetAdjusted12) AS Target12, + + SUM(BudgetAdjusted01) AS Budget01, SUM(BudgetAdjusted02) AS Budget02, SUM(BudgetAdjusted03) AS Budget03, + SUM(BudgetAdjusted04) AS Budget04, SUM(BudgetAdjusted05) AS Budget05, SUM(BudgetAdjusted06) AS Budget06, + SUM(BudgetAdjusted07) AS Budget07, SUM(BudgetAdjusted08) AS Budget08, SUM(BudgetAdjusted09) AS Budget09, + SUM(BudgetAdjusted10) AS Budget10, SUM(BudgetAdjusted11) AS Budget11, SUM(BudgetAdjusted12) AS Budget12, + + SUM(ProjectionAdjusted01) AS Projection01, SUM(ProjectionAdjusted02) AS Projection02, SUM(ProjectionAdjusted03) AS Projection03, + SUM(ProjectionAdjusted04) AS Projection04, SUM(ProjectionAdjusted05) AS Projection05, SUM(ProjectionAdjusted06) AS Projection06, + SUM(ProjectionAdjusted07) AS Projection07, SUM(ProjectionAdjusted08) AS Projection08, SUM(ProjectionAdjusted09) AS Projection09, + SUM(ProjectionAdjusted10) AS Projection10, SUM(ProjectionAdjusted11) AS Projection11, SUM(ProjectionAdjusted12) AS Projection12 + INTO #factReimbursementEncounters + FROM fp.ServiceLineEncounter sle + INNER JOIN #encounterTargeting targeting ON sle.EntityID = targeting.EntityID AND sle.ServiceLineID = targeting.ServiceLineID + WHERE sle.BudgetConfigID = @BudgetConfigID + GROUP BY sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN sle.MedicalSurgicalID ELSE 0 END, sle.PayorID, sle.PayorGroupID, CASE WHEN @IsMsdrgUsed = 1 THEN sle.MSDRGID ELSE 0 END, CASE WHEN @IsCptUsed = 1 THEN sle.CPTID ELSE 0 END + + IF (@IsDebug = 1) + BEGIN + SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments + SELECT '#factReimbursementEncounters', sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, + sle.MedicalSurgicalID, sle.PayorID, sle.PayorGroupID, sle.MSDRGID, sle.CPTID + FROM #factReimbursementEncounters sle + END ELSE + BEGIN + -- Publish Target + ;WITH TGT AS + ( + SELECT fact.BudgetConfigID, fact.EntityGroupConfigID, fact.EntityID, fact.PatientClassID, fact.ServiceLineID, fact.ServiceLineRollupID, + fact.MedicalSurgicalID, fact.PayorID, fact.PayorGroupID, fact.MSDRGID, fact.CPTID, tgt.BudgetPhaseID, + tgt.AdjustedEncounters01, tgt.AdjustedEncounters02, tgt.AdjustedEncounters03, + tgt.AdjustedEncounters04, tgt.AdjustedEncounters05, tgt.AdjustedEncounters06, + tgt.AdjustedEncounters07, tgt.AdjustedEncounters08, tgt.AdjustedEncounters09, + tgt.AdjustedEncounters10, tgt.AdjustedEncounters11, tgt.AdjustedEncounters12 + FROM [fp].[FactReimbursementEncounter] fact + INNER JOIN #encounterTargeting targeting ON fact.EntityID = targeting.EntityID AND fact.ServiceLineID = targeting.ServiceLineID + INNER JOIN fp.FactReimbursementEncounterBudget tgt ON fact.ReimbursementEncounterID = tgt.ReimbursementEncounterID AND tgt.BudgetPhaseID = 2 + WHERE fact.BudgetConfigID = @BudgetConfigID + ) + + MERGE TGT AS target + USING #factReimbursementEncounters AS src + ON ( + target.BudgetConfigID = src.BudgetConfigID + AND target.EntityGroupConfigID = src.EntityGroupConfigID + AND target.EntityID = src.EntityID + AND target.PatientClassID = src.PatientClassID + AND target.ServiceLineID = src.ServiceLineID + AND target.ServiceLineRollupID = src.ServiceLineRollupID + AND target.MedicalSurgicalID = src.MedicalSurgicalID + AND target.MSDRGID = src.MSDRGID + AND target.CPTID = src.CPTID + AND target.PayorID = src.PayorID + AND target.PayorGroupID = src.PayorGroupID + AND target.BudgetPhaseID = 2 + ) + WHEN MATCHED AND ( + target.AdjustedEncounters01 <> src.Target01 OR + target.AdjustedEncounters02 <> src.Target02 OR + target.AdjustedEncounters03 <> src.Target03 OR + target.AdjustedEncounters04 <> src.Target04 OR + target.AdjustedEncounters05 <> src.Target05 OR + target.AdjustedEncounters06 <> src.Target06 OR + target.AdjustedEncounters07 <> src.Target07 OR + target.AdjustedEncounters08 <> src.Target08 OR + target.AdjustedEncounters09 <> src.Target09 OR + target.AdjustedEncounters10 <> src.Target10 OR + target.AdjustedEncounters11 <> src.Target11 OR + target.AdjustedEncounters12 <> src.Target12 + ) + THEN + UPDATE SET target.AdjustedEncounters01 = src.Target01, + target.AdjustedEncounters02 = src.Target02, + target.AdjustedEncounters03 = src.Target03, + target.AdjustedEncounters04 = src.Target04, + target.AdjustedEncounters05 = src.Target05, + target.AdjustedEncounters06 = src.Target06, + target.AdjustedEncounters07 = src.Target07, + target.AdjustedEncounters08 = src.Target08, + target.AdjustedEncounters09 = src.Target09, + target.AdjustedEncounters10 = src.Target10, + target.AdjustedEncounters11 = src.Target11, + target.AdjustedEncounters12 = src.Target12; + + -- Publish Budget + ;WITH TGT AS + ( + SELECT fact.BudgetConfigID, fact.EntityGroupConfigID, fact.EntityID, fact.PatientClassID, fact.ServiceLineID, fact.ServiceLineRollupID, + fact.MedicalSurgicalID, fact.PayorID, fact.PayorGroupID, fact.MSDRGID, fact.CPTID, budg.ReimbursementEncounterID, budg.BudgetPhaseID, + budg.AdjustedEncounters01, budg.AdjustedEncounters02, budg.AdjustedEncounters03, + budg.AdjustedEncounters04, budg.AdjustedEncounters05, budg.AdjustedEncounters06, + budg.AdjustedEncounters07, budg.AdjustedEncounters08, budg.AdjustedEncounters09, + budg.AdjustedEncounters10, budg.AdjustedEncounters11, budg.AdjustedEncounters12 + FROM [fp].[FactReimbursementEncounter] fact + INNER JOIN #encounterTargeting targeting ON fact.EntityID = targeting.EntityID AND fact.ServiceLineID = targeting.ServiceLineID + INNER JOIN fp.FactReimbursementEncounterBudget budg ON fact.ReimbursementEncounterID = budg.ReimbursementEncounterID AND budg.BudgetPhaseID = 3 + WHERE fact.BudgetConfigID = @BudgetConfigID + ) + + MERGE TGT AS target + USING #factReimbursementEncounters AS src + ON ( + target.BudgetConfigID = src.BudgetConfigID + AND target.EntityGroupConfigID = src.EntityGroupConfigID + AND target.EntityID = src.EntityID + AND target.PatientClassID = src.PatientClassID + AND target.ServiceLineID = src.ServiceLineID + AND target.ServiceLineRollupID = src.ServiceLineRollupID + AND target.MedicalSurgicalID = src.MedicalSurgicalID + AND target.MSDRGID = src.MSDRGID + AND target.CPTID = src.CPTID + AND target.PayorID = src.PayorID + AND target.PayorGroupID = src.PayorGroupID + AND target.BudgetPhaseID = 3 + ) + WHEN MATCHED AND ( + target.AdjustedEncounters01 <> src.Budget01 OR + target.AdjustedEncounters02 <> src.Budget02 OR + target.AdjustedEncounters03 <> src.Budget03 OR + target.AdjustedEncounters04 <> src.Budget04 OR + target.AdjustedEncounters05 <> src.Budget05 OR + target.AdjustedEncounters06 <> src.Budget06 OR + target.AdjustedEncounters07 <> src.Budget07 OR + target.AdjustedEncounters08 <> src.Budget08 OR + target.AdjustedEncounters09 <> src.Budget09 OR + target.AdjustedEncounters10 <> src.Budget10 OR + target.AdjustedEncounters11 <> src.Budget11 OR + target.AdjustedEncounters12 <> src.Budget12 + ) + THEN + UPDATE SET target.AdjustedEncounters01 = src.Budget01, + target.AdjustedEncounters02 = src.Budget02, + target.AdjustedEncounters03 = src.Budget03, + target.AdjustedEncounters04 = src.Budget04, + target.AdjustedEncounters05 = src.Budget05, + target.AdjustedEncounters06 = src.Budget06, + target.AdjustedEncounters07 = src.Budget07, + target.AdjustedEncounters08 = src.Budget08, + target.AdjustedEncounters09 = src.Budget09, + target.AdjustedEncounters10 = src.Budget10, + target.AdjustedEncounters11 = src.Budget11, + target.AdjustedEncounters12 = src.Budget12 + OUTPUT + INSERTED.ReimbursementEncounterID + INTO + #budgetBasisIDs (ReimbursementEncounterID); + + -- Publish Projection + ;WITH TGT AS + ( + SELECT fact.BudgetConfigID, fact.EntityGroupConfigID, fact.EntityID, fact.PatientClassID, fact.ServiceLineID, fact.ServiceLineRollupID, + fact.MedicalSurgicalID, fact.PayorID, fact.PayorGroupID, fact.MSDRGID, fact.CPTID, proj.ReimbursementEncounterID, + proj.AdjustedEncounters01, proj.AdjustedEncounters02, proj.AdjustedEncounters03, + proj.AdjustedEncounters04, proj.AdjustedEncounters05, proj.AdjustedEncounters06, + proj.AdjustedEncounters07, proj.AdjustedEncounters08, proj.AdjustedEncounters09, + proj.AdjustedEncounters10, proj.AdjustedEncounters11, proj.AdjustedEncounters12 + FROM [fp].[FactReimbursementEncounter] fact + INNER JOIN #encounterTargeting targeting ON fact.EntityID = targeting.EntityID AND fact.ServiceLineID = targeting.ServiceLineID + INNER JOIN fp.FactReimbursementEncounterProjection proj ON fact.ReimbursementEncounterID = proj.ReimbursementEncounterID + WHERE fact.BudgetConfigID = @BudgetConfigID + ) + + MERGE TGT AS target + USING #factReimbursementEncounters AS src + ON ( + target.BudgetConfigID = src.BudgetConfigID + AND target.EntityGroupConfigID = src.EntityGroupConfigID + AND target.EntityID = src.EntityID + AND target.PatientClassID = src.PatientClassID + AND target.ServiceLineID = src.ServiceLineID + AND target.ServiceLineRollupID = src.ServiceLineRollupID + AND target.MedicalSurgicalID = src.MedicalSurgicalID + AND target.MSDRGID = src.MSDRGID + AND target.CPTID = src.CPTID + AND target.PayorID = src.PayorID + AND target.PayorGroupID = src.PayorGroupID + ) + WHEN MATCHED AND ( + target.AdjustedEncounters01 <> src.Projection01 OR + target.AdjustedEncounters02 <> src.Projection02 OR + target.AdjustedEncounters03 <> src.Projection03 OR + target.AdjustedEncounters04 <> src.Projection04 OR + target.AdjustedEncounters05 <> src.Projection05 OR + target.AdjustedEncounters06 <> src.Projection06 OR + target.AdjustedEncounters07 <> src.Projection07 OR + target.AdjustedEncounters08 <> src.Projection08 OR + target.AdjustedEncounters09 <> src.Projection09 OR + target.AdjustedEncounters10 <> src.Projection10 OR + target.AdjustedEncounters11 <> src.Projection11 OR + target.AdjustedEncounters12 <> src.Projection12 + ) + THEN + UPDATE SET target.AdjustedEncounters01 = src.Projection01, + target.AdjustedEncounters02 = src.Projection02, + target.AdjustedEncounters03 = src.Projection03, + target.AdjustedEncounters04 = src.Projection04, + target.AdjustedEncounters05 = src.Projection05, + target.AdjustedEncounters06 = src.Projection06, + target.AdjustedEncounters07 = src.Projection07, + target.AdjustedEncounters08 = src.Projection08, + target.AdjustedEncounters09 = src.Projection09, + target.AdjustedEncounters10 = src.Projection10, + target.AdjustedEncounters11 = src.Projection11, + target.AdjustedEncounters12 = src.Projection12 + OUTPUT + INSERTED.ReimbursementEncounterID + INTO + #projectionBasisIDs (ReimbursementEncounterID); + + -- Find out what was changed. We can cross apply all 12 months in this case because months are on rows. If we change + -- projection to only update the months not loaded, we'll want to update this. Unlike other procs that are similar, + -- we don't care about the value because when we fix the change history, we take the stored rate in the change history + -- times the volume in the DB, we don't actually care what the value was we flexed to like in the past. + SELECT DISTINCT ReimbursementEncounterID AS BasisID, m.FiscalMonthID, cast(3 as tinyint) AS BudgetPhaseID, cast(2 as tinyint) AS TimeClassID + FROM #budgetBasisIDs + CROSS JOIN fw.DimFiscalMonth m + WHERE m.FiscalMonthID != 0 + UNION ALL + SELECT DISTINCT ReimbursementEncounterID AS BasisID, m.FiscalMonthID, cast(3 as tinyint) AS BudgetPhaseID, cast(12 as tinyint) AS TimeClassID + FROM #projectionBasisIDs + CROSS JOIN fw.DimFiscalMonth m + WHERE m.FiscalMonthID != 0 + END +END +GO + + +--------------------------------------------- + +-- fp.procSampleEncountersToReimbursement_History +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-02-04 MY JAZZ-31904 Initial +** 2 2023-01-17 BK JAZZ-48267 New data structure +** 3 2023-05-18 MY JAZZ-55153 Updated History table +** 4 2023-11-15 BK JAZZ-62974 Fix issue with Encounters not being pushed to Reimbursement because of missing Charges data +** 5 2024-01-11 AO JAZZ-64530 Data transfer for SLE is based on selected Model in Plan Config +*************************************************************/ +CREATE PROCEDURE [fp].[procSampleEncountersToReimbursement_History] + @BudgetConfigID INT, + @IsReimbursementGLEnabled BIT = 0, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + DECLARE @IsMedicalSurgicalUsed BIT, + @IsMsdrgUsed BIT, + @IsCptUsed BIT + + SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 5 -- Reimbursement - Encounters + AND ss.LevelID = 'MedicalSurgicalID' + + SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 5 -- Reimbursement - Encounters + AND ss.LevelID = 'MSDRGID' + + SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 5 -- Reimbursement - Encounters + AND ss.LevelID = 'PrimaryCPTID' + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + IF OBJECT_ID('tempdb..#factReimbursementEncounters') IS NOT NULL DROP TABLE #factReimbursementEncounters; + + CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT); + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #encounterTargeting (EntityID INT, ServiceLineID INT); + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #encounterTargeting (EntityID, ServiceLineID) + SELECT DISTINCT map.EntityID, map.ServiceLineID + FROM fp.ServiceLineEncounterChargeVolumeMapping map WITH (READUNCOMMITTED) + INNER JOIN #ChargeVolumeDepartments targeting ON map.DepartmentID = targeting.DepartmentID + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = map.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE map.BudgetConfigID = @BudgetConfigID + AND ((@IsReimbursementGLEnabled = 1 + AND (bc.DefaultReimbursementNetRevenueModelID = 1 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model + OR rnrm.NetRevenueModelID = 1) + OR @IsReimbursementGLEnabled = 0) + UNION + SELECT DISTINCT sle.EntityID, sle.ServiceLineID + FROM fp.ServiceLineEncounter sle + LEFT JOIN fp.ChargeVolume cv on sle.BudgetConfigID = cv.BudgetConfigID AND sle.EntityID = cv.EntityID AND sle.ServiceLineID = cv.ServiceLineID + LEFT JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON rnrm.EntityID = sle.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE sle.BudgetConfigID = @BudgetConfigID AND cv.EntityID IS NULL + AND ((@IsReimbursementGLEnabled = 1 + AND (bc.DefaultReimbursementNetRevenueModelID = 1 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model + OR rnrm.NetRevenueModelID = 1) + OR @IsReimbursementGLEnabled = 0) + + END ELSE + BEGIN + INSERT INTO #encounterTargeting (EntityID, ServiceLineID) + SELECT DISTINCT map.EntityID, map.ServiceLineID + FROM fp.ServiceLineEncounter map WITH (READUNCOMMITTED) + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = map.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE map.BudgetConfigID = @BudgetConfigID + AND ((@IsReimbursementGLEnabled = 1 + AND (bc.DefaultReimbursementNetRevenueModelID = 1 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model + OR rnrm.NetRevenueModelID = 1) + OR @IsReimbursementGLEnabled = 0) + END + + -- We are only moving Budget over and not projection because we don't display the baseline for projection so we don't need it. If we do ever need it, we'll need to add it to the mix table as well. + SELECT DISTINCT sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN sle.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, + sle.PayorID, sle.PayorGroupID, + CASE WHEN @IsMsdrgUsed = 1 THEN sle.MSDRGID ELSE 0 END AS MSDRGID, + CASE WHEN @IsCptUsed = 1 THEN sle.CPTID ELSE 0 END AS CPTID, + SUM(hist.PriorYearActualValue01) AS PriorYearActualValue01, SUM(hist.PriorYearActualValue02) AS PriorYearActualValue02, SUM(hist.PriorYearActualValue03) AS PriorYearActualValue03, + SUM(hist.PriorYearActualValue04) AS PriorYearActualValue04, SUM(hist.PriorYearActualValue05) AS PriorYearActualValue05, SUM(hist.PriorYearActualValue06) AS PriorYearActualValue06, + SUM(hist.PriorYearActualValue07) AS PriorYearActualValue07, SUM(hist.PriorYearActualValue08) AS PriorYearActualValue08, SUM(hist.PriorYearActualValue09) AS PriorYearActualValue09, + SUM(hist.PriorYearActualValue10) AS PriorYearActualValue10, SUM(hist.PriorYearActualValue11) AS PriorYearActualValue11, SUM(hist.PriorYearActualValue12) AS PriorYearActualValue12, + + SUM(hist.ActualYTDValue01) AS ActualYTDValue01, SUM(hist.ActualYTDValue02) AS ActualYTDValue02, SUM(hist.ActualYTDValue03) AS ActualYTDValue03, + SUM(hist.ActualYTDValue04) AS ActualYTDValue04, SUM(hist.ActualYTDValue05) AS ActualYTDValue05, SUM(hist.ActualYTDValue06) AS ActualYTDValue06, + SUM(hist.ActualYTDValue07) AS ActualYTDValue07, SUM(hist.ActualYTDValue08) AS ActualYTDValue08, SUM(hist.ActualYTDValue09) AS ActualYTDValue09, + SUM(hist.ActualYTDValue10) AS ActualYTDValue10, SUM(hist.ActualYTDValue11) AS ActualYTDValue11, SUM(hist.ActualYTDValue12) AS ActualYTDValue12, + + SUM(hist.CurrentYearBudget01) AS CurrentYearBudget01, SUM(hist.CurrentYearBudget02) AS CurrentYearBudget02, SUM(hist.CurrentYearBudget03) AS CurrentYearBudget03, + SUM(hist.CurrentYearBudget04) AS CurrentYearBudget04, SUM(hist.CurrentYearBudget05) AS CurrentYearBudget05, SUM(hist.CurrentYearBudget06) AS CurrentYearBudget06, + SUM(hist.CurrentYearBudget07) AS CurrentYearBudget07, SUM(hist.CurrentYearBudget08) AS CurrentYearBudget08, SUM(hist.CurrentYearBudget09) AS CurrentYearBudget09, + SUM(hist.CurrentYearBudget10) AS CurrentYearBudget10, SUM(hist.CurrentYearBudget11) AS CurrentYearBudget11, SUM(hist.CurrentYearBudget12) AS CurrentYearBudget12 + INTO #factReimbursementEncounters + FROM fp.ServiceLineEncounter sle + INNER JOIN #encounterTargeting targeting ON sle.EntityID = targeting.EntityID AND sle.ServiceLineID = targeting.ServiceLineID + INNER JOIN fp.ServiceLineEncounterHistory hist ON sle.ServiceLineEncounterID = hist.ServiceLineEncounterID + WHERE sle.BudgetConfigID = @BudgetConfigID + GROUP BY sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN sle.MedicalSurgicalID ELSE 0 END, sle.PayorID, sle.PayorGroupID, CASE WHEN @IsMsdrgUsed = 1 THEN sle.MSDRGID ELSE 0 END, CASE WHEN @IsCptUsed = 1 THEN sle.CPTID ELSE 0 END + + IF (@IsDebug = 1) + BEGIN + SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments + SELECT '#factReimbursementEncounters', sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, + sle.MedicalSurgicalID, sle.PayorID, sle.PayorGroupID, sle.MSDRGID, sle.CPTID + FROM #factReimbursementEncounters sle + END ELSE + BEGIN + -- Publish + ;WITH TGT AS + ( + SELECT fact.BudgetConfigID, fact.EntityGroupConfigID, fact.EntityID, fact.PatientClassID, fact.ServiceLineID, fact.ServiceLineRollupID, + fact.MedicalSurgicalID, fact.PayorID, fact.PayorGroupID, fact.MSDRGID, fact.CPTID, + hist.ActualYTDEncounters01, hist.ActualYTDEncounters02, hist.ActualYTDEncounters03, + hist.ActualYTDEncounters04, hist.ActualYTDEncounters05, hist.ActualYTDEncounters06, + hist.ActualYTDEncounters07, hist.ActualYTDEncounters08, hist.ActualYTDEncounters09, + hist.ActualYTDEncounters10, hist.ActualYTDEncounters11, hist.ActualYTDEncounters12, + + hist.PriorYearActualEncounters01, hist.PriorYearActualEncounters02, hist.PriorYearActualEncounters03, + hist.PriorYearActualEncounters04, hist.PriorYearActualEncounters05, hist.PriorYearActualEncounters06, + hist.PriorYearActualEncounters07, hist.PriorYearActualEncounters08, hist.PriorYearActualEncounters09, + hist.PriorYearActualEncounters10, hist.PriorYearActualEncounters11, hist.PriorYearActualEncounters12, + + hist.CurrentYearBudgetEncounters01, hist.CurrentYearBudgetEncounters02, hist.CurrentYearBudgetEncounters03, + hist.CurrentYearBudgetEncounters04, hist.CurrentYearBudgetEncounters05, hist.CurrentYearBudgetEncounters06, + hist.CurrentYearBudgetEncounters07, hist.CurrentYearBudgetEncounters08, hist.CurrentYearBudgetEncounters09, + hist.CurrentYearBudgetEncounters10, hist.CurrentYearBudgetEncounters11, hist.CurrentYearBudgetEncounters12 + FROM [fp].[FactReimbursementEncounter] fact + INNER JOIN #encounterTargeting targeting ON fact.EntityID = targeting.EntityID AND fact.ServiceLineID = targeting.ServiceLineID + INNER JOIN fp.FactReimbursementEncounterHistory hist ON fact.ReimbursementEncounterID = hist.ReimbursementEncounterID + WHERE fact.BudgetConfigID = @BudgetConfigID + ) + + MERGE TGT AS target + USING #factReimbursementEncounters AS src + ON ( + target.BudgetConfigID = src.BudgetConfigID + AND target.EntityGroupConfigID = src.EntityGroupConfigID + AND target.EntityID = src.EntityID + AND target.PatientClassID = src.PatientClassID + AND target.ServiceLineID = src.ServiceLineID + AND target.ServiceLineRollupID = src.ServiceLineRollupID + AND target.MedicalSurgicalID = src.MedicalSurgicalID + AND target.MSDRGID = src.MSDRGID + AND target.CPTID = src.CPTID + AND target.PayorID = src.PayorID + AND target.PayorGroupID = src.PayorGroupID + ) + WHEN MATCHED AND ( + target.ActualYTDEncounters01 <> src.ActualYTDValue01 OR + target.ActualYTDEncounters02 <> src.ActualYTDValue02 OR + target.ActualYTDEncounters03 <> src.ActualYTDValue03 OR + target.ActualYTDEncounters04 <> src.ActualYTDValue04 OR + target.ActualYTDEncounters05 <> src.ActualYTDValue05 OR + target.ActualYTDEncounters06 <> src.ActualYTDValue06 OR + target.ActualYTDEncounters07 <> src.ActualYTDValue07 OR + target.ActualYTDEncounters08 <> src.ActualYTDValue08 OR + target.ActualYTDEncounters09 <> src.ActualYTDValue09 OR + target.ActualYTDEncounters10 <> src.ActualYTDValue10 OR + target.ActualYTDEncounters11 <> src.ActualYTDValue11 OR + target.ActualYTDEncounters12 <> src.ActualYTDValue12 OR + + target.PriorYearActualEncounters01 <> src.PriorYearActualValue01 OR + target.PriorYearActualEncounters02 <> src.PriorYearActualValue02 OR + target.PriorYearActualEncounters03 <> src.PriorYearActualValue03 OR + target.PriorYearActualEncounters04 <> src.PriorYearActualValue04 OR + target.PriorYearActualEncounters05 <> src.PriorYearActualValue05 OR + target.PriorYearActualEncounters06 <> src.PriorYearActualValue06 OR + target.PriorYearActualEncounters07 <> src.PriorYearActualValue07 OR + target.PriorYearActualEncounters08 <> src.PriorYearActualValue08 OR + target.PriorYearActualEncounters09 <> src.PriorYearActualValue09 OR + target.PriorYearActualEncounters10 <> src.PriorYearActualValue10 OR + target.PriorYearActualEncounters11 <> src.PriorYearActualValue11 OR + target.PriorYearActualEncounters12 <> src.PriorYearActualValue12 OR + + target.CurrentYearBudgetEncounters01 <> src.CurrentYearBudget01 OR + target.CurrentYearBudgetEncounters02 <> src.CurrentYearBudget02 OR + target.CurrentYearBudgetEncounters03 <> src.CurrentYearBudget03 OR + target.CurrentYearBudgetEncounters04 <> src.CurrentYearBudget04 OR + target.CurrentYearBudgetEncounters05 <> src.CurrentYearBudget05 OR + target.CurrentYearBudgetEncounters06 <> src.CurrentYearBudget06 OR + target.CurrentYearBudgetEncounters07 <> src.CurrentYearBudget07 OR + target.CurrentYearBudgetEncounters08 <> src.CurrentYearBudget08 OR + target.CurrentYearBudgetEncounters09 <> src.CurrentYearBudget09 OR + target.CurrentYearBudgetEncounters10 <> src.CurrentYearBudget10 OR + target.CurrentYearBudgetEncounters11 <> src.CurrentYearBudget11 OR + target.CurrentYearBudgetEncounters12 <> src.CurrentYearBudget12 + ) + THEN + UPDATE SET target.ActualYTDEncounters01 = src.ActualYTDValue01, + target.ActualYTDEncounters02 = src.ActualYTDValue02, + target.ActualYTDEncounters03 = src.ActualYTDValue03, + target.ActualYTDEncounters04 = src.ActualYTDValue04, + target.ActualYTDEncounters05 = src.ActualYTDValue05, + target.ActualYTDEncounters06 = src.ActualYTDValue06, + target.ActualYTDEncounters07 = src.ActualYTDValue07, + target.ActualYTDEncounters08 = src.ActualYTDValue08, + target.ActualYTDEncounters09 = src.ActualYTDValue09, + target.ActualYTDEncounters10 = src.ActualYTDValue10, + target.ActualYTDEncounters11 = src.ActualYTDValue11, + target.ActualYTDEncounters12 = src.ActualYTDValue12, + + target.PriorYearActualEncounters01 = src.PriorYearActualValue01, + target.PriorYearActualEncounters02 = src.PriorYearActualValue02, + target.PriorYearActualEncounters03 = src.PriorYearActualValue03, + target.PriorYearActualEncounters04 = src.PriorYearActualValue04, + target.PriorYearActualEncounters05 = src.PriorYearActualValue05, + target.PriorYearActualEncounters06 = src.PriorYearActualValue06, + target.PriorYearActualEncounters07 = src.PriorYearActualValue07, + target.PriorYearActualEncounters08 = src.PriorYearActualValue08, + target.PriorYearActualEncounters09 = src.PriorYearActualValue09, + target.PriorYearActualEncounters10 = src.PriorYearActualValue10, + target.PriorYearActualEncounters11 = src.PriorYearActualValue11, + target.PriorYearActualEncounters12 = src.PriorYearActualValue12, + + target.CurrentYearBudgetEncounters01 = src.CurrentYearBudget01, + target.CurrentYearBudgetEncounters02 = src.CurrentYearBudget02, + target.CurrentYearBudgetEncounters03 = src.CurrentYearBudget03, + target.CurrentYearBudgetEncounters04 = src.CurrentYearBudget04, + target.CurrentYearBudgetEncounters05 = src.CurrentYearBudget05, + target.CurrentYearBudgetEncounters06 = src.CurrentYearBudget06, + target.CurrentYearBudgetEncounters07 = src.CurrentYearBudget07, + target.CurrentYearBudgetEncounters08 = src.CurrentYearBudget08, + target.CurrentYearBudgetEncounters09 = src.CurrentYearBudget09, + target.CurrentYearBudgetEncounters10 = src.CurrentYearBudget10, + target.CurrentYearBudgetEncounters11 = src.CurrentYearBudget11, + target.CurrentYearBudgetEncounters12 = src.CurrentYearBudget12; + + END +END +GO + + +--------------------------------------------- + +-- fp.procSampleEncountersToReimbursement_Initial +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-02-04 MY JAZZ-31904 Initial +** 2 2023-01-17 BK JAZZ-48267 New data structure +** 3 2023-11-15 BK JAZZ-62974 Fix issue with Encounters not being pushed to Reimbursement because of missing Charges data +** 4 2024-01-11 AO JAZZ-64530 Data transfer for SLE is based on selected Model in Plan Config +*************************************************************/ +CREATE PROCEDURE [fp].[procSampleEncountersToReimbursement_Initial] + @BudgetConfigID INT, + @IsReimbursementGLEnabled BIT = 0, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + DECLARE @IsMedicalSurgicalUsed BIT, + @IsMsdrgUsed BIT, + @IsCptUsed BIT + + SELECT @IsMedicalSurgicalUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 5 -- Reimbursement - Encounters + AND ss.LevelID = 'MedicalSurgicalID' + + SELECT @IsMsdrgUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 5 -- Reimbursement - Encounters + AND ss.LevelID = 'MSDRGID' + + SELECT @IsCptUsed = CASE WHEN ss.IsHidden = 1 THEN 0 ELSE 1 END + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigGUID = ss.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + AND ss.PlanSectionID = 7 -- Reimbursement + AND ss.SubSectionID = 5 -- Reimbursement - Encounters + AND ss.LevelID = 'PrimaryCPTID' + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#ChargeVolumeDepartments') IS NOT NULL DROP TABLE #ChargeVolumeDepartments; + IF OBJECT_ID('tempdb..#factReimbursementEncounters') IS NOT NULL DROP TABLE #factReimbursementEncounters; + + CREATE TABLE #ChargeVolumeDepartments (DepartmentID INT); + INSERT INTO #ChargeVolumeDepartments (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #encounterTargeting (EntityID INT, ServiceLineID INT); + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF EXISTS(SELECT 1 FROM #ChargeVolumeDepartments WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #encounterTargeting (EntityID, ServiceLineID) + SELECT DISTINCT map.EntityID, map.ServiceLineID + FROM fp.ServiceLineEncounterChargeVolumeMapping map WITH (READUNCOMMITTED) + INNER JOIN #ChargeVolumeDepartments targeting ON map.DepartmentID = targeting.DepartmentID + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = map.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE map.BudgetConfigID = @BudgetConfigID + AND ((@IsReimbursementGLEnabled = 1 + AND (bc.DefaultReimbursementNetRevenueModelID = 1 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model + OR rnrm.NetRevenueModelID = 1) + OR @IsReimbursementGLEnabled = 0) + UNION + SELECT DISTINCT sle.EntityID, sle.ServiceLineID + FROM fp.ServiceLineEncounter sle + LEFT JOIN fp.ChargeVolume cv on sle.BudgetConfigID = cv.BudgetConfigID AND sle.EntityID = cv.EntityID AND sle.ServiceLineID = cv.ServiceLineID + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = sle.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE sle.BudgetConfigID = @BudgetConfigID AND cv.EntityID IS NULL + AND ((@IsReimbursementGLEnabled = 1 + AND (bc.DefaultReimbursementNetRevenueModelID = 1 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model + OR rnrm.NetRevenueModelID = 1) + OR @IsReimbursementGLEnabled = 0) + + END ELSE + BEGIN + INSERT INTO #encounterTargeting (EntityID, ServiceLineID) + SELECT DISTINCT map.EntityID, map.ServiceLineID + FROM fp.ServiceLineEncounter map WITH (READUNCOMMITTED) + LEFT JOIN fp.BudgetConfig bc ON @IsReimbursementGLEnabled = 1 AND bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON @IsReimbursementGLEnabled = 1 AND rnrm.EntityID = map.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE map.BudgetConfigID = @BudgetConfigID + AND ((@IsReimbursementGLEnabled = 1 + AND (bc.DefaultReimbursementNetRevenueModelID = 1 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,1))) -- SLE Model + OR rnrm.NetRevenueModelID = 1) + OR @IsReimbursementGLEnabled = 0) + END + + -- We are only moving Budget over and not projection because we don't display the baseline for projection so we don't need it. If we do ever need it, we'll need to add it to the mix table as well. + SELECT DISTINCT sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN sle.MedicalSurgicalID ELSE 0 END AS MedicalSurgicalID, sle.PayorID, sle.PayorGroupID, + CASE WHEN @IsMsdrgUsed = 1 THEN sle.MSDRGID ELSE 0 END AS MSDRGID, + CASE WHEN @IsCptUsed = 1 THEN sle.CPTID ELSE 0 END AS CPTID, + SUM(sle.InitialBudget01) AS InitialBudget01, SUM(sle.InitialBudget02) AS InitialBudget02, SUM(sle.InitialBudget03) AS InitialBudget03, SUM(sle.InitialBudget04) AS InitialBudget04, SUM(sle.InitialBudget05) AS InitialBudget05, SUM(sle.InitialBudget06) AS InitialBudget06, + SUM(sle.InitialBudget07) AS InitialBudget07, SUM(sle.InitialBudget08) AS InitialBudget08, SUM(sle.InitialBudget09) AS InitialBudget09, SUM(sle.InitialBudget10) AS InitialBudget10, SUM(sle.InitialBudget11) AS InitialBudget11, SUM(sle.InitialBudget12) AS InitialBudget12 + INTO #factReimbursementEncounters + FROM fp.ServiceLineEncounter sle + INNER JOIN #encounterTargeting targeting ON sle.EntityID = targeting.EntityID AND sle.ServiceLineID = targeting.ServiceLineID + WHERE sle.BudgetConfigID = @BudgetConfigID + GROUP BY sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalUsed = 1 THEN sle.MedicalSurgicalID ELSE 0 END, sle.PayorID, sle.PayorGroupID, CASE WHEN @IsMsdrgUsed = 1 THEN sle.MSDRGID ELSE 0 END, CASE WHEN @IsCptUsed = 1 THEN sle.CPTID ELSE 0 END + + IF (@IsDebug = 1) + BEGIN + SELECT '#ChargeVolumeDepartments', DepartmentID FROM #ChargeVolumeDepartments + SELECT '#factReimbursementEncounters', sle.BudgetConfigID, sle.EntityGroupConfigID, sle.EntityID, sle.PatientClassID, sle.ServiceLineID, sle.ServiceLineRollupID, + sle.MedicalSurgicalID, sle.PayorID, sle.PayorGroupID, sle.MSDRGID, sle.CPTID + FROM #factReimbursementEncounters sle + END ELSE + BEGIN + -- Publish + ;WITH TGT AS + ( + SELECT fact.[BudgetConfigID], fact.[EntityGroupConfigID], fact.[EntityID], fact.[PatientClassID], fact.[ServiceLineID], fact.[ServiceLineRollupID], fact.[MedicalSurgicalID], + fact.[PayorID], fact.[PayorGroupID], fact.[MSDRGID], fact.[CPTID], + [InitialBudgetEncounters01], [InitialBudgetEncounters02], [InitialBudgetEncounters03], [InitialBudgetEncounters04], [InitialBudgetEncounters05], [InitialBudgetEncounters06], + [InitialBudgetEncounters07], [InitialBudgetEncounters08], [InitialBudgetEncounters09], [InitialBudgetEncounters10], [InitialBudgetEncounters11], [InitialBudgetEncounters12] + FROM [fp].[FactReimbursementEncounter] fact + INNER JOIN #encounterTargeting targeting ON fact.EntityID = targeting.EntityID AND fact.ServiceLineID = targeting.ServiceLineID + WHERE fact.BudgetConfigID = @BudgetConfigID + ) + + MERGE TGT AS target + USING #factReimbursementEncounters AS src + ON ( + target.BudgetConfigID = src.BudgetConfigID + AND target.EntityGroupConfigID = src.EntityGroupConfigID + AND target.EntityID = src.EntityID + AND target.PatientClassID = src.PatientClassID + AND target.ServiceLineID = src.ServiceLineID + AND target.ServiceLineRollupID = src.ServiceLineRollupID + AND target.MedicalSurgicalID = src.MedicalSurgicalID + AND target.MSDRGID = src.MSDRGID + AND target.CPTID = src.CPTID + AND target.PayorID = src.PayorID + AND target.PayorGroupID = src.PayorGroupID + ) + WHEN MATCHED AND ( + target.InitialBudgetEncounters01 <> src.InitialBudget01 OR + target.InitialBudgetEncounters02 <> src.InitialBudget02 OR + target.InitialBudgetEncounters03 <> src.InitialBudget03 OR + target.InitialBudgetEncounters04 <> src.InitialBudget04 OR + target.InitialBudgetEncounters05 <> src.InitialBudget05 OR + target.InitialBudgetEncounters06 <> src.InitialBudget06 OR + target.InitialBudgetEncounters07 <> src.InitialBudget07 OR + target.InitialBudgetEncounters08 <> src.InitialBudget08 OR + target.InitialBudgetEncounters09 <> src.InitialBudget09 OR + target.InitialBudgetEncounters10 <> src.InitialBudget10 OR + target.InitialBudgetEncounters11 <> src.InitialBudget11 OR + target.InitialBudgetEncounters12 <> src.InitialBudget12 + ) + THEN + UPDATE SET target.InitialBudgetEncounters01 = src.InitialBudget01, + target.InitialBudgetEncounters02 = src.InitialBudget02, + target.InitialBudgetEncounters03 = src.InitialBudget03, + target.InitialBudgetEncounters04 = src.InitialBudget04, + target.InitialBudgetEncounters05 = src.InitialBudget05, + target.InitialBudgetEncounters06 = src.InitialBudget06, + target.InitialBudgetEncounters07 = src.InitialBudget07, + target.InitialBudgetEncounters08 = src.InitialBudget08, + target.InitialBudgetEncounters09 = src.InitialBudget09, + target.InitialBudgetEncounters10 = src.InitialBudget10, + target.InitialBudgetEncounters11 = src.InitialBudget11, + target.InitialBudgetEncounters12 = src.InitialBudget12; + + END +END +GO + + +--------------------------------------------- + +-- fp.procSampleGLDollarsPerUOS +CREATE PROCEDURE [fp].[procSampleGLDollarsPerUOS] + @EntityGroupConfigID INT, + @CurrentFiscalYearID SMALLINT, + @SourceFiscalYearID SMALLINT, + @SourceTimeClassID TINYINT, + @MonthsLoaded INT, + @APEModelSectionIDs SqlByteListTableType READONLY, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table + ** 2 2021-03-24 NN Jazz-14123 Remove null joins + ** 3 2021-12-09 BK Jazz-30703 Use fp.FactStatistics historicals instead of int.FactStatistic + ** 4 2023-03-13 MY JAZZ-48981 Update sampling for cross department flexing + ** 5 5-9-2023 NT JAZZ-54290 Data restructure changes to use new fp.GeneralLedger table + ** 6 2024-08-26 MY JAZZ-76040 Adjust Statistics for Leap Year + *************************************************************/ + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[GeneralLedger] d WITH (READUNCOMMITTED) + WHERE d.EntityGroupConfigID = @EntityGroupConfigID + AND d.FlexingTypeID IN (1, 2) + END + + DECLARE @IdsCount TINYINT; + SELECT @IdsCount = COUNT(value) FROM @APEModelSectionIDs; + + DECLARE @IsAnnualized BIT = (CASE WHEN (@SourceFiscalYearID = @CurrentFiscalYearID AND @SourceTimeClassID = 1) THEN 1 ELSE 0 END); + DECLARE @IsCurrentYearALeapYear BIT = (CASE WHEN (@CurrentFiscalYearID % 4 = 0 AND @CurrentFiscalYearID % 100 <> 0) OR @CurrentFiscalYearID % 400 = 0 THEN 1 ELSE 0 END) + + DECLARE @EnableLeapYearAdjustedStatistics BIT = ISNULL((SELECT bcs.Value + FROM fp.viewBudgetConfigSetting bcs + INNER JOIN fp.BudgetConfig bc ON bcs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN fp.EntityGroupConfig egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID + WHERE bcs.Name = 'Enable Leap Year Adjusted Statistics for Calculating Rates' + AND egc.EntityGroupConfigID = @EntityGroupConfigID), 0); + + -- JAZZ-76040: Adjust Statistics for Leap Year. This only needs to be applied for Annualized and if the current year is a leap year. + DECLARE @AdjustStatisticsForLeapYear BIT = CASE WHEN @EnableLeapYearAdjustedStatistics = 1 AND @IsAnnualized = 1 AND @IsCurrentYearALeapYear = 1 THEN 1 ELSE 0 END; + + -- For $/UOS we calculate it by taking the total variable dollars / total stats. We do it to the initial budget so that + -- it can be used within the engine after a configuration change. Sampled $/UOS doesn't really matter as it can change with each configuration change. + + -- Projection rates should match the budget rates + + -- Calculate the stats for each Department/GL Account that is setup to be flexed by stats + + DECLARE @UsePriorYear BIT = 0; + DECLARE @UseActualYTD BIT = 0; + DECLARE @UseCurrentYearBudget BIT = 0; + + IF @SourceTimeClassID = 2 BEGIN + SET @UseCurrentYearBudget = 1; + END ELSE BEGIN + IF @CurrentFiscalYearID = @SourceFiscalYearID BEGIN + SET @UseActualYTD = 1; + END ELSE BEGIN + SET @UsePriorYear = 1 + END + END + + SELECT + map.DepartmentID, + map.GLAccountID as AccountID, + CASE + WHEN @UseActualYTD = 1 THEN ISNULL(SUM(statHist.ActualYTDValueTotal), 0) + WHEN @UseCurrentYearBudget = 1 THEN ISNULL(SUM(statHist.CurrentYearBudgetTotal), 0) + WHEN @UsePriorYear = 1 THEN ISNULL(SUM(statHist.PriorYearActualValueTotal), 0) + END + AS StatTotal + INTO #budgetStats + FROM [fp].[FlexConfigMapping] map + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = map.DepartmentID + INNER JOIN fp.EntityGroupConfig egc ON egc.EntityGroupConfigID = map.EntityGroupConfigID + INNER JOIN fp.BudgetConfig bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + LEFT JOIN fp.[FactStatistics] stat ON stat.DepartmentID = map.SourceDepartmentID AND stat.AccountID = map.StatAccountID AND stat.BudgetConfigID = bc.BudgetConfigID + LEFT JOIN fp.[FactStatisticsHistory] statHist ON stat.StatisticsID = statHist.StatisticsID + WHERE map.EntityGroupConfigID = @EntityGroupConfigID + AND map.GLAccountID != 0 + AND map.FlexingTypeID IN (1, 2) + GROUP BY + map.DepartmentID, + map.GLAccountID + + -- JAZZ-76040: Adjust Statistics for Leap Year + IF (@AdjustStatisticsForLeapYear = 1) + BEGIN + + -- per stackoverflow (per MY) + DECLARE @BudgetFiscalYearID INT = @CurrentFiscalYearID + 1; + DECLARE @IsBudgetLeapYear BIT = (CASE WHEN (@BudgetFiscalYearID % 4 = 0 AND @BudgetFiscalYearID % 100 <> 0) OR @BudgetFiscalYearID % 400 = 0 THEN 1 ELSE 0 END) + DECLARE @DaysBudgetYear decimal = (SELECT (CASE WHEN @IsBudgetLeapYear = 1 THEN YTDDaysInLeapYearMonth ELSE YTDDaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder = 12) + DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsCurrentYearALeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded) + + UPDATE #budgetStats + SET StatTotal = ((StatTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) + + END + + -- We need to recalculate the variable dollars on the fly because InitialBudget/Projection Dollars will get flexed, otherwise if we don't + -- the rate will rise each time. + SELECT + fgl.DepartmentID, + fgl.AccountID, + fgl.EntityGroupConfigID, + COALESCE(1 - fv.FixedPercentage, 0) * total.SampledBudgetTotal AS BudgetDollarTotal + INTO #variableDollars + FROM [fp].[GeneralLedger] fgl + LEFT JOIN @APEModelSectionIDs ids ON ids.value = fgl.APEModelSectionID + INNER JOIN ( + SELECT + fgl.DepartmentID, + fgl.AccountID, + (SUM(CASE WHEN 1 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget01 ELSE 0 END + + CASE WHEN 2 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget02 ELSE 0 END + + CASE WHEN 3 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget03 ELSE 0 END + + CASE WHEN 4 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget04 ELSE 0 END + + CASE WHEN 5 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget05 ELSE 0 END + + CASE WHEN 6 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget06 ELSE 0 END + + CASE WHEN 7 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget07 ELSE 0 END + + CASE WHEN 8 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget08 ELSE 0 END + + CASE WHEN 9 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget09 ELSE 0 END + + CASE WHEN 10 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget10 ELSE 0 END + + CASE WHEN 11 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget11 ELSE 0 END + + CASE WHEN 12 <= @MonthsLoaded OR @IsAnnualized = 0 OR @AdjustStatisticsForLeapYear = 1 THEN SampledBudget12 ELSE 0 END)) AS SampledBudgetTotal + FROM + [fp].[GeneralLedger] fgl + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fgl.DepartmentID + WHERE + fgl.EntityGroupConfigID = @EntityGroupConfigID + GROUP BY + fgl.DepartmentID, + fgl.AccountID + ) as total + ON total.DepartmentID = fgl.DepartmentID + AND total.AccountID = fgl.AccountID + LEFT JOIN ( + SELECT fav.DepartmentID, fav.AccountID, MAX(FixedPercentage) AS FixedPercentage + FROM [fp].[FactAccountVariability] fav + INNER JOIN [fp].[EntityGroupConfig] egc ON + egc.EntityGroupConfigID = @EntityGroupConfigID + AND egc.EntityGroupConfigGUID = fav.EntityGroupConfigGUID + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fav.DepartmentID + GROUP BY fav.DepartmentID, fav.AccountID + ) fv + ON fv.DepartmentID = fgl.DepartmentID + AND fv.AccountID = fgl.AccountID + WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID + AND fgl.VariabilityID = 2 + AND (@IdsCount = 0 OR ids.value IS NOT NULL) + + + -- set the Dollars/UOS values on GL table + UPDATE + fgl + SET + InitialBudgetDollarsPerUOS01 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetDollarsPerUOS02 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetDollarsPerUOS03 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetDollarsPerUOS04 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetDollarsPerUOS05 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetDollarsPerUOS06 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetDollarsPerUOS07 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetDollarsPerUOS08 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetDollarsPerUOS09 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetDollarsPerUOS10 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetDollarsPerUOS11 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetDollarsPerUOS12 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + + -- Projection rates should match the budget rates and use the budget baseline to calculate + InitialProjectionDollarsPerUOS01 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionDollarsPerUOS02 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionDollarsPerUOS03 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionDollarsPerUOS04 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionDollarsPerUOS05 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionDollarsPerUOS06 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionDollarsPerUOS07 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionDollarsPerUOS08 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionDollarsPerUOS09 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionDollarsPerUOS10 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionDollarsPerUOS11 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionDollarsPerUOS12 = COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) + + FROM + [fp].[GeneralLedger] fgl + INNER JOIN #variableDollars fglDollars + ON fgl.DepartmentID = fglDollars.DepartmentID + AND fgl.AccountID = fglDollars.AccountID + AND fgl.EntityGroupConfigID = fglDollars.EntityGroupConfigID + INNER JOIN #budgetStats stat + ON stat.DepartmentID = fgl.DepartmentID + AND stat.AccountID = fgl.AccountID + WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID + AND ( + fgl.InitialBudgetDollarsPerUOS01 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialBudgetDollarsPerUOS02 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialBudgetDollarsPerUOS03 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialBudgetDollarsPerUOS04 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialBudgetDollarsPerUOS05 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialBudgetDollarsPerUOS06 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialBudgetDollarsPerUOS07 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialBudgetDollarsPerUOS08 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialBudgetDollarsPerUOS09 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialBudgetDollarsPerUOS10 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialBudgetDollarsPerUOS11 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialBudgetDollarsPerUOS12 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + + fgl.InitialProjectionDollarsPerUOS01 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialProjectionDollarsPerUOS02 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialProjectionDollarsPerUOS03 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialProjectionDollarsPerUOS04 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialProjectionDollarsPerUOS05 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialProjectionDollarsPerUOS06 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialProjectionDollarsPerUOS07 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialProjectionDollarsPerUOS08 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialProjectionDollarsPerUOS09 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialProjectionDollarsPerUOS10 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialProjectionDollarsPerUOS11 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fgl.InitialProjectionDollarsPerUOS12 != COALESCE(fglDollars.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0)) + +END +GO + + +--------------------------------------------- + +-- fp.procSampleGeneralLedgerToReimbursement +CREATE PROCEDURE [fp].[procSampleGeneralLedgerToReimbursement] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsUpdatePerOfCharge BIT, + @IsDebug BIT = 0 +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 05-23-2023 MZ JAZZ-54503 Initial Creation + ** 2 07-04-2023 AO JAZZ-57174 Adjusted formula NetAsPercentOfCharge + ** 3 08-08-2023 MZ JAZZ-55099 Added IsUpdatePerOfCharge + ** 4 08-11-2023 MZ JAZZ-55099 Fix targeting + ** 5 10-04-2023 MZ JAZZ-61634 Fix % of charge calculation when revenue stays the same but new deductions were found + ** 6 10-12-2023 NH JAZZ-59310 GL Reimbursement/ Adjustments - update Change history when edit past adjustment in Plan Editor + ** 7 01-03-2024 AO JAZZ-65384 Data transfer for GL is based on selected Model in Plan Config + ** 8 08-12-2024 VZ JAZZ-74434 Data transfer for GL based on excluded departments + *************************************************************/ + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment; + IF OBJECT_ID('tempdb..#ReimbursementGL') IS NOT NULL DROP TABLE #ReimbursementGL; + IF OBJECT_ID('tempdb..#ReimbursementTargeting') IS NOT NULL DROP TABLE #ReimbursementTargeting; + IF OBJECT_ID('tempdb..#RevenueData') IS NOT NULL DROP TABLE #RevenueData; + IF OBJECT_ID('tempdb..#DeductionData') IS NOT NULL DROP TABLE #DeductionData; + IF OBJECT_ID('tempdb..#projectionBasisIDs') IS NOT NULL DROP TABLE #projectionBasisIDs + IF OBJECT_ID('tempdb..#budgetBasisIDs') IS NOT NULL DROP TABLE #budgetBasisIDs + IF OBJECT_ID('tempdb..#targetBasisIDs') IS NOT NULL DROP TABLE #targetBasisIDs + + CREATE TABLE #projectionBasisIDs (ReimbursementGeneralLedgerID INT) + CREATE TABLE #budgetBasisIDs (ReimbursementGeneralLedgerID INT); + CREATE TABLE #targetBasisIDs (ReimbursementGeneralLedgerID INT); + + CREATE TABLE #FilterByDepartment (DepartmentID INT); + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #ReimbursementTargeting (EntityID INT); + + CREATE TABLE #RevenueData ( + [BudgetConfigID] [int], + [EntityGroupConfigID] [int], + [EntityID] [int], + [PayorGroupID] [int], + [PatientClassID] [int], + + [Target01] [decimal](19, 8), + [Target02] [decimal](19, 8), + [Target03] [decimal](19, 8), + [Target04] [decimal](19, 8), + [Target05] [decimal](19, 8), + [Target06] [decimal](19, 8), + [Target07] [decimal](19, 8), + [Target08] [decimal](19, 8), + [Target09] [decimal](19, 8), + [Target10] [decimal](19, 8), + [Target11] [decimal](19, 8), + [Target12] [decimal](19, 8), + + [Budget01] [decimal](19, 8), + [Budget02] [decimal](19, 8), + [Budget03] [decimal](19, 8), + [Budget04] [decimal](19, 8), + [Budget05] [decimal](19, 8), + [Budget06] [decimal](19, 8), + [Budget07] [decimal](19, 8), + [Budget08] [decimal](19, 8), + [Budget09] [decimal](19, 8), + [Budget10] [decimal](19, 8), + [Budget11] [decimal](19, 8), + [Budget12] [decimal](19, 8), + + [Projection01] [decimal](19, 8), + [Projection02] [decimal](19, 8), + [Projection03] [decimal](19, 8), + [Projection04] [decimal](19, 8), + [Projection05] [decimal](19, 8), + [Projection06] [decimal](19, 8), + [Projection07] [decimal](19, 8), + [Projection08] [decimal](19, 8), + [Projection09] [decimal](19, 8), + [Projection10] [decimal](19, 8), + [Projection11] [decimal](19, 8), + [Projection12] [decimal](19, 8) + ) + + CREATE TABLE #DeductionData ( + [BudgetConfigID] [int], + [EntityGroupConfigID] [int], + [EntityID] [int], + [PayorGroupID] [int], + [PatientClassID] [int], + + [Target01] [decimal](19, 8), + [Target02] [decimal](19, 8), + [Target03] [decimal](19, 8), + [Target04] [decimal](19, 8), + [Target05] [decimal](19, 8), + [Target06] [decimal](19, 8), + [Target07] [decimal](19, 8), + [Target08] [decimal](19, 8), + [Target09] [decimal](19, 8), + [Target10] [decimal](19, 8), + [Target11] [decimal](19, 8), + [Target12] [decimal](19, 8), + + [Budget01] [decimal](19, 8), + [Budget02] [decimal](19, 8), + [Budget03] [decimal](19, 8), + [Budget04] [decimal](19, 8), + [Budget05] [decimal](19, 8), + [Budget06] [decimal](19, 8), + [Budget07] [decimal](19, 8), + [Budget08] [decimal](19, 8), + [Budget09] [decimal](19, 8), + [Budget10] [decimal](19, 8), + [Budget11] [decimal](19, 8), + [Budget12] [decimal](19, 8), + + [Projection01] [decimal](19, 8), + [Projection02] [decimal](19, 8), + [Projection03] [decimal](19, 8), + [Projection04] [decimal](19, 8), + [Projection05] [decimal](19, 8), + [Projection06] [decimal](19, 8), + [Projection07] [decimal](19, 8), + [Projection08] [decimal](19, 8), + [Projection09] [decimal](19, 8), + [Projection10] [decimal](19, 8), + [Projection11] [decimal](19, 8), + [Projection12] [decimal](19, 8) + ) + + CREATE TABLE #ReimbursementGL ( + [BudgetConfigID] [int], + [EntityGroupConfigID] [int], + [EntityID] [int], + [PayorGroupID] [int], + [PatientClassID] [int], + + [TargetAdjusted01] [decimal](19, 8), + [TargetAdjusted02] [decimal](19, 8), + [TargetAdjusted03] [decimal](19, 8), + [TargetAdjusted04] [decimal](19, 8), + [TargetAdjusted05] [decimal](19, 8), + [TargetAdjusted06] [decimal](19, 8), + [TargetAdjusted07] [decimal](19, 8), + [TargetAdjusted08] [decimal](19, 8), + [TargetAdjusted09] [decimal](19, 8), + [TargetAdjusted10] [decimal](19, 8), + [TargetAdjusted11] [decimal](19, 8), + [TargetAdjusted12] [decimal](19, 8), + + [TargetAdjustedNetAsPercentOfCharge01] [decimal](19, 8), + [TargetAdjustedNetAsPercentOfCharge02] [decimal](19, 8), + [TargetAdjustedNetAsPercentOfCharge03] [decimal](19, 8), + [TargetAdjustedNetAsPercentOfCharge04] [decimal](19, 8), + [TargetAdjustedNetAsPercentOfCharge05] [decimal](19, 8), + [TargetAdjustedNetAsPercentOfCharge06] [decimal](19, 8), + [TargetAdjustedNetAsPercentOfCharge07] [decimal](19, 8), + [TargetAdjustedNetAsPercentOfCharge08] [decimal](19, 8), + [TargetAdjustedNetAsPercentOfCharge09] [decimal](19, 8), + [TargetAdjustedNetAsPercentOfCharge10] [decimal](19, 8), + [TargetAdjustedNetAsPercentOfCharge11] [decimal](19, 8), + [TargetAdjustedNetAsPercentOfCharge12] [decimal](19, 8), + + [BudgetAdjusted01] [decimal](19, 8), + [BudgetAdjusted02] [decimal](19, 8), + [BudgetAdjusted03] [decimal](19, 8), + [BudgetAdjusted04] [decimal](19, 8), + [BudgetAdjusted05] [decimal](19, 8), + [BudgetAdjusted06] [decimal](19, 8), + [BudgetAdjusted07] [decimal](19, 8), + [BudgetAdjusted08] [decimal](19, 8), + [BudgetAdjusted09] [decimal](19, 8), + [BudgetAdjusted10] [decimal](19, 8), + [BudgetAdjusted11] [decimal](19, 8), + [BudgetAdjusted12] [decimal](19, 8), + + [BudgetAdjustedNetAsPercentOfCharge01] [decimal](19, 8), + [BudgetAdjustedNetAsPercentOfCharge02] [decimal](19, 8), + [BudgetAdjustedNetAsPercentOfCharge03] [decimal](19, 8), + [BudgetAdjustedNetAsPercentOfCharge04] [decimal](19, 8), + [BudgetAdjustedNetAsPercentOfCharge05] [decimal](19, 8), + [BudgetAdjustedNetAsPercentOfCharge06] [decimal](19, 8), + [BudgetAdjustedNetAsPercentOfCharge07] [decimal](19, 8), + [BudgetAdjustedNetAsPercentOfCharge08] [decimal](19, 8), + [BudgetAdjustedNetAsPercentOfCharge09] [decimal](19, 8), + [BudgetAdjustedNetAsPercentOfCharge10] [decimal](19, 8), + [BudgetAdjustedNetAsPercentOfCharge11] [decimal](19, 8), + [BudgetAdjustedNetAsPercentOfCharge12] [decimal](19, 8), + + [ProjectionAdjusted01] [decimal](19, 8), + [ProjectionAdjusted02] [decimal](19, 8), + [ProjectionAdjusted03] [decimal](19, 8), + [ProjectionAdjusted04] [decimal](19, 8), + [ProjectionAdjusted05] [decimal](19, 8), + [ProjectionAdjusted06] [decimal](19, 8), + [ProjectionAdjusted07] [decimal](19, 8), + [ProjectionAdjusted08] [decimal](19, 8), + [ProjectionAdjusted09] [decimal](19, 8), + [ProjectionAdjusted10] [decimal](19, 8), + [ProjectionAdjusted11] [decimal](19, 8), + [ProjectionAdjusted12] [decimal](19, 8), + + [ProjectionAdjustedNetAsPercentOfCharge01] [decimal](19, 8), + [ProjectionAdjustedNetAsPercentOfCharge02] [decimal](19, 8), + [ProjectionAdjustedNetAsPercentOfCharge03] [decimal](19, 8), + [ProjectionAdjustedNetAsPercentOfCharge04] [decimal](19, 8), + [ProjectionAdjustedNetAsPercentOfCharge05] [decimal](19, 8), + [ProjectionAdjustedNetAsPercentOfCharge06] [decimal](19, 8), + [ProjectionAdjustedNetAsPercentOfCharge07] [decimal](19, 8), + [ProjectionAdjustedNetAsPercentOfCharge08] [decimal](19, 8), + [ProjectionAdjustedNetAsPercentOfCharge09] [decimal](19, 8), + [ProjectionAdjustedNetAsPercentOfCharge10] [decimal](19, 8), + [ProjectionAdjustedNetAsPercentOfCharge11] [decimal](19, 8), + [ProjectionAdjustedNetAsPercentOfCharge12] [decimal](19, 8) + ) + + DECLARE @Revenue INT = 1; + DECLARE @Deduction INT = 4; + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #ReimbursementTargeting (gl.EntityID) + SELECT DISTINCT gl.EntityID + FROM [fp].[GeneralLedger] gl WITH (READUNCOMMITTED) + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON rnrm.EntityID = gl.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN #FilterByDepartment d ON gl.DepartmentID = d.DepartmentID + WHERE gl.BudgetConfigID = @BudgetConfigID + AND ((bc.DefaultReimbursementNetRevenueModelID = 2 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,2))) + OR rnrm.NetRevenueModelID = 2) -- GL Model + END ELSE + BEGIN + INSERT INTO #ReimbursementTargeting (gl.EntityID) + SELECT DISTINCT gl.EntityID + FROM [fp].[GeneralLedger] gl WITH (READUNCOMMITTED) + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON rnrm.EntityID = gl.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE gl.BudgetConfigID = @BudgetConfigID AND + ((bc.DefaultReimbursementNetRevenueModelID = 2 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,2))) + OR rnrm.NetRevenueModelID = 2) -- GL Model + END + + --#RevenueData + INSERT INTO #RevenueData( + BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, + Target01, Target02, Target03, Target04, Target05, Target06, Target07, Target08, Target09, Target10, Target11, Target12, + Budget01, Budget02, Budget03, Budget04, Budget05, Budget06, Budget07, Budget08, Budget09, Budget10, Budget11, Budget12, + Projection01, Projection02, Projection03, Projection04, Projection05, Projection06, Projection07, Projection08, Projection09, Projection10, Projection11, Projection12 + ) + SELECT DISTINCT gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID AS PayorGroupID, a.PatientClassID, + SUM(gl.TargetAdjusted01) AS Target01, SUM(gl.TargetAdjusted02) AS Target02, SUM(gl.TargetAdjusted03) AS Target03, SUM(gl.TargetAdjusted04) AS Target04, SUM(gl.TargetAdjusted05) AS Target05, SUM(gl.TargetAdjusted06) AS Target06, + SUM(gl.TargetAdjusted07) AS Target07, SUM(gl.TargetAdjusted08) AS Target08, SUM(gl.TargetAdjusted09) AS Target09, SUM(gl.TargetAdjusted10) AS Target10, SUM(gl.TargetAdjusted11) AS Target11, SUM(gl.TargetAdjusted12) AS Target12, + + SUM(gl.BudgetAdjusted01) AS Budget01, SUM(gl.BudgetAdjusted02) AS Budget02, SUM(gl.BudgetAdjusted03) AS Budget03, SUM(gl.BudgetAdjusted04) AS Budget04, SUM(gl.BudgetAdjusted05) AS Budget05, SUM(gl.BudgetAdjusted06) AS Budget06, + SUM(gl.BudgetAdjusted07) AS Budget07, SUM(gl.BudgetAdjusted08) AS Budget08, SUM(gl.BudgetAdjusted09) AS Budget09, SUM(gl.BudgetAdjusted10) AS Budget10, SUM(gl.BudgetAdjusted11) AS Budget11, SUM(gl.BudgetAdjusted12) AS Budget12, + + SUM(gl.ProjectionAdjusted01) AS Projection01, SUM(gl.ProjectionAdjusted02) AS Projection02, SUM(gl.ProjectionAdjusted03) AS Projection03, SUM(gl.ProjectionAdjusted04) AS Projection04, SUM(gl.ProjectionAdjusted05) AS Projection05, SUM(gl.ProjectionAdjusted06) AS Projection06, + SUM(gl.ProjectionAdjusted07) AS Projection07, SUM(gl.ProjectionAdjusted08) AS Projection08, SUM(gl.ProjectionAdjusted09) AS Projection09, SUM(gl.ProjectionAdjusted10) AS Projection10, SUM(gl.ProjectionAdjusted11) AS Projection11, SUM(gl.ProjectionAdjusted12) AS Projection12 + FROM fp.GeneralLedger gl + INNER JOIN #ReimbursementTargeting rt ON rt.EntityID = gl.EntityID + INNER JOIN [fw].[DimAccount] a ON gl.AccountID = a.AccountID + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = @BudgetConfigID + WHERE gl.BudgetConfigID = @BudgetConfigID + AND gl.APEModelSectionID = @Revenue + AND gl.DepartmentID NOT IN (SELECT DepartmentID FROM fp.GeneralLedgerReimbursementExcludedDepartments + WHERE BudgetConfigGUID = bc.BudgetConfigGUID) + GROUP BY gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID, gl.APEModelSectionID, a.PatientClassID + + --#DeductionData + INSERT INTO #DeductionData( + BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, + Target01, Target02, Target03, Target04, Target05, Target06, Target07, Target08, Target09, Target10, Target11, Target12, + Budget01, Budget02, Budget03, Budget04, Budget05, Budget06, Budget07, Budget08, Budget09, Budget10, Budget11, Budget12, + Projection01, Projection02, Projection03, Projection04, Projection05, Projection06, Projection07, Projection08, Projection09, Projection10, Projection11, Projection12 + ) + SELECT DISTINCT gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID AS PayorGroupID, a.PatientClassID, + SUM(gl.TargetAdjusted01) AS Target01, SUM(gl.TargetAdjusted02) AS Target02, SUM(gl.TargetAdjusted03) AS Target03, SUM(gl.TargetAdjusted04) AS Target04, SUM(gl.TargetAdjusted05) AS Target05, SUM(gl.TargetAdjusted06) AS Target06, + SUM(gl.TargetAdjusted07) AS Target07, SUM(gl.TargetAdjusted08) AS Target08, SUM(gl.TargetAdjusted09) AS Target09, SUM(gl.TargetAdjusted10) AS Target10, SUM(gl.TargetAdjusted11) AS Target11, SUM(gl.TargetAdjusted12) AS Target12, + + SUM(gl.BudgetAdjusted01) AS Budget01, SUM(gl.BudgetAdjusted02) AS Budget02, SUM(gl.BudgetAdjusted03) AS Budget03, SUM(gl.BudgetAdjusted04) AS Budget04, SUM(gl.BudgetAdjusted05) AS Budget05, SUM(gl.BudgetAdjusted06) AS Budget06, + SUM(gl.BudgetAdjusted07) AS Budget07, SUM(gl.BudgetAdjusted08) AS Budget08, SUM(gl.BudgetAdjusted09) AS Budget09, SUM(gl.BudgetAdjusted10) AS Budget10, SUM(gl.BudgetAdjusted11) AS Budget11, SUM(gl.BudgetAdjusted12) AS Budget12, + + SUM(gl.ProjectionAdjusted01) AS Projection01, SUM(gl.ProjectionAdjusted02) AS Projection02, SUM(gl.ProjectionAdjusted03) AS Projection03, SUM(gl.ProjectionAdjusted04) AS Projection04, SUM(gl.ProjectionAdjusted05) AS Projection05, SUM(gl.ProjectionAdjusted06) AS Projection06, + SUM(gl.ProjectionAdjusted07) AS Projection07, SUM(gl.ProjectionAdjusted08) AS Projection08, SUM(gl.ProjectionAdjusted09) AS Projection09, SUM(gl.ProjectionAdjusted10) AS Projection10, SUM(gl.ProjectionAdjusted11) AS Projection11, SUM(gl.ProjectionAdjusted12) AS Projection12 + FROM fp.GeneralLedger gl + INNER JOIN #ReimbursementTargeting rt ON rt.EntityID = gl.EntityID + INNER JOIN [fw].[DimAccount] a ON gl.AccountID = a.AccountID + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = @BudgetConfigID + WHERE gl.BudgetConfigID = @BudgetConfigID + AND gl.APEModelSectionID = @Deduction + AND a.OBModelSectionName = 'Deductions - Reimbursement' + AND gl.DepartmentID NOT IN (SELECT DepartmentID FROM fp.GeneralLedgerReimbursementExcludedDepartments + WHERE BudgetConfigGUID = bc.BudgetConfigGUID) + GROUP BY gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID, gl.APEModelSectionID, a.PatientClassID + + + INSERT INTO #ReimbursementGL( + BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, + + [TargetAdjusted01], [TargetAdjusted02], [TargetAdjusted03], [TargetAdjusted04], [TargetAdjusted05], [TargetAdjusted06], + [TargetAdjusted07], [TargetAdjusted08], [TargetAdjusted09], [TargetAdjusted10], [TargetAdjusted11], [TargetAdjusted12], + + [TargetAdjustedNetAsPercentOfCharge01], [TargetAdjustedNetAsPercentOfCharge02], [TargetAdjustedNetAsPercentOfCharge03], [TargetAdjustedNetAsPercentOfCharge04], + [TargetAdjustedNetAsPercentOfCharge05], [TargetAdjustedNetAsPercentOfCharge06], [TargetAdjustedNetAsPercentOfCharge07], [TargetAdjustedNetAsPercentOfCharge08], + [TargetAdjustedNetAsPercentOfCharge09], [TargetAdjustedNetAsPercentOfCharge10], [TargetAdjustedNetAsPercentOfCharge11], [TargetAdjustedNetAsPercentOfCharge12], + + [BudgetAdjusted01], [BudgetAdjusted02], [BudgetAdjusted03], [BudgetAdjusted04], [BudgetAdjusted05], [BudgetAdjusted06], + [BudgetAdjusted07], [BudgetAdjusted08], [BudgetAdjusted09], [BudgetAdjusted10], [BudgetAdjusted11], [BudgetAdjusted12], + + [BudgetAdjustedNetAsPercentOfCharge01], [BudgetAdjustedNetAsPercentOfCharge02], [BudgetAdjustedNetAsPercentOfCharge03], [BudgetAdjustedNetAsPercentOfCharge04], + [BudgetAdjustedNetAsPercentOfCharge05], [BudgetAdjustedNetAsPercentOfCharge06], [BudgetAdjustedNetAsPercentOfCharge07], [BudgetAdjustedNetAsPercentOfCharge08], + [BudgetAdjustedNetAsPercentOfCharge09], [BudgetAdjustedNetAsPercentOfCharge10], [BudgetAdjustedNetAsPercentOfCharge11], [BudgetAdjustedNetAsPercentOfCharge12], + + [ProjectionAdjusted01], [ProjectionAdjusted02], [ProjectionAdjusted03], [ProjectionAdjusted04], [ProjectionAdjusted05], [ProjectionAdjusted06], + [ProjectionAdjusted07], [ProjectionAdjusted08], [ProjectionAdjusted09], [ProjectionAdjusted10], [ProjectionAdjusted11], [ProjectionAdjusted12], + + [ProjectionAdjustedNetAsPercentOfCharge01], [ProjectionAdjustedNetAsPercentOfCharge02], [ProjectionAdjustedNetAsPercentOfCharge03], [ProjectionAdjustedNetAsPercentOfCharge04], + [ProjectionAdjustedNetAsPercentOfCharge05], [ProjectionAdjustedNetAsPercentOfCharge06], [ProjectionAdjustedNetAsPercentOfCharge07], [ProjectionAdjustedNetAsPercentOfCharge08], + [ProjectionAdjustedNetAsPercentOfCharge09], [ProjectionAdjustedNetAsPercentOfCharge10], [ProjectionAdjustedNetAsPercentOfCharge11], [ProjectionAdjustedNetAsPercentOfCharge12] + ) + SELECT DISTINCT + r.BudgetConfigID, r.EntityGroupConfigID, r.EntityID, r.PayorGroupID, r.PatientClassID, + + --Target + -- %ofCharge = NetReimbursement/revenue = (revenue - deduction) / revenue + + r.Target01, r.Target02, r.Target03, r.Target04, r.Target05, r.Target06, r.Target07, r.Target08, r.Target09, r.Target10, r.Target11, r.Target12, + + CASE WHEN r.Target01 IS NULL OR r.Target01 = 0 THEN 0 WHEN d.Target01 IS NULL THEN 1 + ELSE (r.Target01 - d.Target01) / r.Target01 END AS TargetAdjustedNetAsPercentOfCharge01, + CASE WHEN r.Target02 IS NULL OR r.Target02 = 0 THEN 0 WHEN d.Target02 IS NULL THEN 1 + ELSE (r.Target02 - d.Target02) / r.Target02 END AS TargetAdjustedNetAsPercentOfCharge02, + CASE WHEN r.Target03 IS NULL OR r.Target03 = 0 THEN 0 WHEN d.Target03 IS NULL THEN 1 + ELSE (r.Target03 - d.Target03) / r.Target03 END AS TargetAdjustedNetAsPercentOfCharge03, + CASE WHEN r.Target04 IS NULL OR r.Target04 = 0 THEN 0 WHEN d.Target04 IS NULL THEN 1 + ELSE (r.Target04 - d.Target04) / r.Target04 END AS TargetAdjustedNetAsPercentOfCharge04, + CASE WHEN r.Target05 IS NULL OR r.Target05 = 0 THEN 0 WHEN d.Target05 IS NULL THEN 1 + ELSE (r.Target05 - d.Target05) / r.Target05 END AS TargetAdjustedNetAsPercentOfCharge05, + CASE WHEN r.Target06 IS NULL OR r.Target06 = 0 THEN 0 WHEN d.Target06 IS NULL THEN 1 + ELSE (r.Target06 - d.Target06) / r.Target06 END AS TargetAdjustedNetAsPercentOfCharge06, + CASE WHEN r.Target07 IS NULL OR r.Target07 = 0 THEN 0 WHEN d.Target07 IS NULL THEN 1 + ELSE (r.Target07 - d.Target07) / r.Target07 END AS TargetAdjustedNetAsPercentOfCharge07, + CASE WHEN r.Target08 IS NULL OR r.Target08 = 0 THEN 0 WHEN d.Target08 IS NULL THEN 1 + ELSE (r.Target08 - d.Target08) / r.Target08 END AS TargetAdjustedNetAsPercentOfCharge08, + CASE WHEN r.Target09 IS NULL OR r.Target09 = 0 THEN 0 WHEN d.Target09 IS NULL THEN 1 + ELSE (r.Target09 - d.Target09) / r.Target09 END AS TargetAdjustedNetAsPercentOfCharge09, + CASE WHEN r.Target10 IS NULL OR r.Target10 = 0 THEN 0 WHEN d.Target10 IS NULL THEN 1 + ELSE (r.Target10 - d.Target10) / r.Target10 END AS TargetAdjustedNetAsPercentOfCharge10, + CASE WHEN r.Target11 IS NULL OR r.Target11 = 0 THEN 0 WHEN d.Target11 IS NULL THEN 1 + ELSE (r.Target11 - d.Target11) / r.Target11 END AS TargetAdjustedNetAsPercentOfCharge11, + CASE WHEN r.Target12 IS NULL OR r.Target12 = 0 THEN 0 WHEN d.Target12 IS NULL THEN 1 + ELSE (r.Target12 - d.Target12) / r.Target12 END AS TargetAdjustedNetAsPercentOfCharge12, + + --Budget + r.Budget01, r.Budget02, r.Budget03, r.Budget04, r.Budget05, r.Budget06, r.Budget07, r.Budget08, r.Budget09, r.Budget10, r.Budget11, r.Budget12, + + CASE WHEN r.Budget01 IS NULL OR r.Budget01 = 0 THEN 0 WHEN d.Budget01 IS NULL THEN 1 + ELSE (r.Budget01 - d.Budget01) / r.Budget01 END AS BudgetAdjustedNetAsPercentOfCharge01, + CASE WHEN r.Budget02 IS NULL OR r.Budget02 = 0 THEN 0 WHEN d.Budget02 IS NULL THEN 1 + ELSE (r.Budget02 - d.Budget02) / r.Budget02 END AS BudgetAdjustedNetAsPercentOfCharge02, + CASE WHEN r.Budget03 IS NULL OR r.Budget03 = 0 THEN 0 WHEN d.Budget03 IS NULL THEN 1 + ELSE (r.Budget03 - d.Budget03) / r.Budget03 END AS BudgetAdjustedNetAsPercentOfCharge03, + CASE WHEN r.Budget04 IS NULL OR r.Budget04 = 0 THEN 0 WHEN d.Budget04 IS NULL THEN 1 + ELSE (r.Budget04 - d.Budget04) / r.Budget04 END AS BudgetAdjustedNetAsPercentOfCharge04, + CASE WHEN r.Budget05 IS NULL OR r.Budget05 = 0 THEN 0 WHEN d.Budget05 IS NULL THEN 1 + ELSE (r.Budget05 - d.Budget05) / r.Budget05 END AS BudgetAdjustedNetAsPercentOfCharge05, + CASE WHEN r.Budget06 IS NULL OR r.Budget06 = 0 THEN 0 WHEN d.Budget06 IS NULL THEN 1 + ELSE (r.Budget06 - d.Budget06) / r.Budget06 END AS BudgetAdjustedNetAsPercentOfCharge06, + CASE WHEN r.Budget07 IS NULL OR r.Budget07 = 0 THEN 0 WHEN d.Budget07 IS NULL THEN 1 + ELSE (r.Budget07 - d.Budget07) / r.Budget07 END AS BudgetAdjustedNetAsPercentOfCharge07, + CASE WHEN r.Budget08 IS NULL OR r.Budget08 = 0 THEN 0 WHEN d.Budget08 IS NULL THEN 1 + ELSE (r.Budget08 - d.Budget08) / r.Budget08 END AS BudgetAdjustedNetAsPercentOfCharge08, + CASE WHEN r.Budget09 IS NULL OR r.Budget09 = 0 THEN 0 WHEN d.Budget09 IS NULL THEN 1 + ELSE (r.Budget09 - d.Budget09) / r.Budget09 END AS BudgetAdjustedNetAsPercentOfCharge09, + CASE WHEN r.Budget10 IS NULL OR r.Budget10 = 0 THEN 0 WHEN d.Budget10 IS NULL THEN 1 + ELSE (r.Budget10 - d.Budget10) / r.Budget10 END AS BudgetAdjustedNetAsPercentOfCharge10, + CASE WHEN r.Budget11 IS NULL OR r.Budget11 = 0 THEN 0 WHEN d.Budget11 IS NULL THEN 1 + ELSE (r.Budget11 - d.Budget11) / r.Budget11 END AS BudgetAdjustedNetAsPercentOfCharge11, + CASE WHEN r.Budget12 IS NULL OR r.Budget12 = 0 THEN 0 WHEN d.Budget12 IS NULL THEN 1 + ELSE (r.Budget12 - d.Budget12) / r.Budget12 END AS BudgetAdjustedNetAsPercentOfCharge12, + + --Projection + r.Projection01, r.Projection02, r.Projection03, r.Projection04, r.Projection05, r.Projection06, r.Projection07, r.Projection08, r.Projection09, r.Projection10, r.Projection11, r.Projection12, + + CASE WHEN r.Projection01 IS NULL OR r.Projection01 = 0 THEN 0 WHEN d.Projection01 IS NULL THEN 1 + ELSE (r.Projection01 - d.Projection01) / r.Projection01 END AS ProjectionAdjustedNetAsPercentOfCharge01, + CASE WHEN r.Projection02 IS NULL OR r.Projection02 = 0 THEN 0 WHEN d.Projection02 IS NULL THEN 1 + ELSE (r.Projection02 - d.Projection02) / r.Projection02 END AS ProjectionAdjustedNetAsPercentOfCharge02, + CASE WHEN r.Projection03 IS NULL OR r.Projection03 = 0 THEN 0 WHEN d.Projection03 IS NULL THEN 1 + ELSE (r.Projection03 - d.Projection03) / r.Projection03 END AS ProjectionAdjustedNetAsPercentOfCharge03, + CASE WHEN r.Projection04 IS NULL OR r.Projection04 = 0 THEN 0 WHEN d.Projection04 IS NULL THEN 1 + ELSE (r.Projection04 - d.Projection04) / r.Projection04 END AS ProjectionAdjustedNetAsPercentOfCharge04, + CASE WHEN r.Projection05 IS NULL OR r.Projection05 = 0 THEN 0 WHEN d.Projection05 IS NULL THEN 1 + ELSE (r.Projection05 - d.Projection05) / r.Projection05 END AS ProjectionAdjustedNetAsPercentOfCharge05, + CASE WHEN r.Projection06 IS NULL OR r.Projection06 = 0 THEN 0 WHEN d.Projection06 IS NULL THEN 1 + ELSE (r.Projection06 - d.Projection06) / r.Projection06 END AS ProjectionAdjustedNetAsPercentOfCharge06, + CASE WHEN r.Projection07 IS NULL OR r.Projection07 = 0 THEN 0 WHEN d.Projection07 IS NULL THEN 1 + ELSE (r.Projection07 - d.Projection07) / r.Projection07 END AS ProjectionAdjustedNetAsPercentOfCharge07, + CASE WHEN r.Projection08 IS NULL OR r.Projection08 = 0 THEN 0 WHEN d.Projection08 IS NULL THEN 1 + ELSE (r.Projection08 - d.Projection08) / r.Projection08 END AS ProjectionAdjustedNetAsPercentOfCharge08, + CASE WHEN r.Projection09 IS NULL OR r.Projection09 = 0 THEN 0 WHEN d.Projection09 IS NULL THEN 1 + ELSE (r.Projection09 - d.Projection09) / r.Projection09 END AS ProjectionAdjustedNetAsPercentOfCharge09, + CASE WHEN r.Projection10 IS NULL OR r.Projection10 = 0 THEN 0 WHEN d.Projection10 IS NULL THEN 1 + ELSE (r.Projection10 - d.Projection10) / r.Projection10 END AS ProjectionAdjustedNetAsPercentOfCharge10, + CASE WHEN r.Projection11 IS NULL OR r.Projection11 = 0 THEN 0 WHEN d.Projection11 IS NULL THEN 1 + ELSE (r.Projection11 - d.Projection11) / r.Projection11 END AS ProjectionAdjustedNetAsPercentOfCharge11, + CASE WHEN r.Projection12 IS NULL OR r.Projection12 = 0 THEN 0 WHEN d.Projection12 IS NULL THEN 1 + ELSE (r.Projection12 - d.Projection12) / r.Projection12 END AS ProjectionAdjustedNetAsPercentOfCharge12 + + FROM #RevenueData r + LEFT JOIN #DeductionData d ON d.BudgetConfigID = r.BudgetConfigID + AND d.EntityGroupConfigID = r.EntityGroupConfigID + AND d.EntityID = r.EntityID + AND d.PayorGroupID = r.PayorGroupID + AND d.PatientClassID = r.PatientClassID + WHERE r.BudgetConfigID = @BudgetConfigID + + IF (@IsDebug = 1) + BEGIN + SELECT '#FilterByDepartment', DepartmentID FROM #FilterByDepartment + SELECT '#ReimbursementTargeting', EntityID FROM #ReimbursementTargeting + SELECT '#RevenueData', * FROM #RevenueData + SELECT '#DeductionData', * FROM #DeductionData + SELECT '#ReimbursementGL', * FROM #ReimbursementGL + END ELSE + BEGIN + -- Publish Target + ;WITH TGT AS + ( + SELECT rgl.ReimbursementGeneralLedgerID, rgl.BudgetConfigID, rgl.EntityGroupConfigID, rgl.EntityID, rgl.PayorGroupID, rgl.PatientClassID, + [TargetAdjusted01], [TargetAdjusted02], [TargetAdjusted03], [TargetAdjusted04], [TargetAdjusted05], [TargetAdjusted06], + [TargetAdjusted07], [TargetAdjusted08], [TargetAdjusted09], [TargetAdjusted10], [TargetAdjusted11], [TargetAdjusted12], + + [TargetAdjustedNetAsPercentOfCharge01], [TargetAdjustedNetAsPercentOfCharge02], [TargetAdjustedNetAsPercentOfCharge03], [TargetAdjustedNetAsPercentOfCharge04], + [TargetAdjustedNetAsPercentOfCharge05], [TargetAdjustedNetAsPercentOfCharge06], [TargetAdjustedNetAsPercentOfCharge07], [TargetAdjustedNetAsPercentOfCharge08], + [TargetAdjustedNetAsPercentOfCharge09], [TargetAdjustedNetAsPercentOfCharge10], [TargetAdjustedNetAsPercentOfCharge11], [TargetAdjustedNetAsPercentOfCharge12] + FROM [fp].[ReimbursementGeneralLedger] rgl + WHERE rgl.BudgetConfigID = @BudgetConfigID + ) + + MERGE TGT AS target + USING #ReimbursementGL AS src + ON ( + target.BudgetConfigID = src.BudgetConfigID + AND target.EntityGroupConfigID = src.EntityGroupConfigID + AND target.EntityID = src.EntityID + AND target.PayorGroupID = src.PayorGroupID + AND target.PatientClassID = src.PatientClassID + ) + WHEN MATCHED AND ( + target.TargetAdjusted01 <> src.TargetAdjusted01 OR + target.TargetAdjusted02 <> src.TargetAdjusted02 OR + target.TargetAdjusted03 <> src.TargetAdjusted03 OR + target.TargetAdjusted04 <> src.TargetAdjusted04 OR + target.TargetAdjusted05 <> src.TargetAdjusted05 OR + target.TargetAdjusted06 <> src.TargetAdjusted06 OR + target.TargetAdjusted07 <> src.TargetAdjusted07 OR + target.TargetAdjusted08 <> src.TargetAdjusted08 OR + target.TargetAdjusted09 <> src.TargetAdjusted09 OR + target.TargetAdjusted10 <> src.TargetAdjusted10 OR + target.TargetAdjusted11 <> src.TargetAdjusted11 OR + target.TargetAdjusted12 <> src.TargetAdjusted12 OR + ( @IsUpdatePerOfCharge = 1 AND ( + target.TargetAdjustedNetAsPercentOfCharge01 <> src.TargetAdjustedNetAsPercentOfCharge01 OR + target.TargetAdjustedNetAsPercentOfCharge02 <> src.TargetAdjustedNetAsPercentOfCharge02 OR + target.TargetAdjustedNetAsPercentOfCharge03 <> src.TargetAdjustedNetAsPercentOfCharge03 OR + target.TargetAdjustedNetAsPercentOfCharge04 <> src.TargetAdjustedNetAsPercentOfCharge04 OR + target.TargetAdjustedNetAsPercentOfCharge05 <> src.TargetAdjustedNetAsPercentOfCharge05 OR + target.TargetAdjustedNetAsPercentOfCharge06 <> src.TargetAdjustedNetAsPercentOfCharge06 OR + target.TargetAdjustedNetAsPercentOfCharge07 <> src.TargetAdjustedNetAsPercentOfCharge07 OR + target.TargetAdjustedNetAsPercentOfCharge08 <> src.TargetAdjustedNetAsPercentOfCharge08 OR + target.TargetAdjustedNetAsPercentOfCharge09 <> src.TargetAdjustedNetAsPercentOfCharge09 OR + target.TargetAdjustedNetAsPercentOfCharge10 <> src.TargetAdjustedNetAsPercentOfCharge10 OR + target.TargetAdjustedNetAsPercentOfCharge11 <> src.TargetAdjustedNetAsPercentOfCharge11 OR + target.TargetAdjustedNetAsPercentOfCharge12 <> src.TargetAdjustedNetAsPercentOfCharge12 ) + ) + ) + THEN + UPDATE SET target.TargetAdjusted01 = src.TargetAdjusted01, + target.TargetAdjusted02 = src.TargetAdjusted02, + target.TargetAdjusted03 = src.TargetAdjusted03, + target.TargetAdjusted04 = src.TargetAdjusted04, + target.TargetAdjusted05 = src.TargetAdjusted05, + target.TargetAdjusted06 = src.TargetAdjusted06, + target.TargetAdjusted07 = src.TargetAdjusted07, + target.TargetAdjusted08 = src.TargetAdjusted08, + target.TargetAdjusted09 = src.TargetAdjusted09, + target.TargetAdjusted10 = src.TargetAdjusted10, + target.TargetAdjusted11 = src.TargetAdjusted11, + target.TargetAdjusted12 = src.TargetAdjusted12, + + target.TargetAdjustedNetAsPercentOfCharge01 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge01 ELSE target.TargetAdjustedNetAsPercentOfCharge01 END, + target.TargetAdjustedNetAsPercentOfCharge02 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge02 ELSE target.TargetAdjustedNetAsPercentOfCharge02 END, + target.TargetAdjustedNetAsPercentOfCharge03 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge03 ELSE target.TargetAdjustedNetAsPercentOfCharge03 END, + target.TargetAdjustedNetAsPercentOfCharge04 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge04 ELSE target.TargetAdjustedNetAsPercentOfCharge04 END, + target.TargetAdjustedNetAsPercentOfCharge05 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge05 ELSE target.TargetAdjustedNetAsPercentOfCharge05 END, + target.TargetAdjustedNetAsPercentOfCharge06 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge06 ELSE target.TargetAdjustedNetAsPercentOfCharge06 END, + target.TargetAdjustedNetAsPercentOfCharge07 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge07 ELSE target.TargetAdjustedNetAsPercentOfCharge07 END, + target.TargetAdjustedNetAsPercentOfCharge08 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge08 ELSE target.TargetAdjustedNetAsPercentOfCharge08 END, + target.TargetAdjustedNetAsPercentOfCharge09 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge09 ELSE target.TargetAdjustedNetAsPercentOfCharge09 END, + target.TargetAdjustedNetAsPercentOfCharge10 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge10 ELSE target.TargetAdjustedNetAsPercentOfCharge10 END, + target.TargetAdjustedNetAsPercentOfCharge11 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge11 ELSE target.TargetAdjustedNetAsPercentOfCharge11 END, + target.TargetAdjustedNetAsPercentOfCharge12 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.TargetAdjustedNetAsPercentOfCharge12 ELSE target.TargetAdjustedNetAsPercentOfCharge12 END + OUTPUT + INSERTED.ReimbursementGeneralLedgerID + INTO + #targetBasisIDs (ReimbursementGeneralLedgerID); + + -- Publish Budget + ;WITH TGT AS + ( + SELECT rgl.ReimbursementGeneralLedgerID, rgl.BudgetConfigID, rgl.EntityGroupConfigID, rgl.EntityID, rgl.PayorGroupID, rgl.PatientClassID, + [BudgetAdjusted01], [BudgetAdjusted02], [BudgetAdjusted03], [BudgetAdjusted04], [BudgetAdjusted05], [BudgetAdjusted06], + [BudgetAdjusted07], [BudgetAdjusted08], [BudgetAdjusted09], [BudgetAdjusted10], [BudgetAdjusted11], [BudgetAdjusted12], + + [BudgetAdjustedNetAsPercentOfCharge01], [BudgetAdjustedNetAsPercentOfCharge02], [BudgetAdjustedNetAsPercentOfCharge03], [BudgetAdjustedNetAsPercentOfCharge04], + [BudgetAdjustedNetAsPercentOfCharge05], [BudgetAdjustedNetAsPercentOfCharge06], [BudgetAdjustedNetAsPercentOfCharge07], [BudgetAdjustedNetAsPercentOfCharge08], + [BudgetAdjustedNetAsPercentOfCharge09], [BudgetAdjustedNetAsPercentOfCharge10], [BudgetAdjustedNetAsPercentOfCharge11], [BudgetAdjustedNetAsPercentOfCharge12] + FROM [fp].[ReimbursementGeneralLedger] rgl + WHERE rgl.BudgetConfigID = @BudgetConfigID + ) + + MERGE TGT AS target + USING #ReimbursementGL AS src + ON ( + target.BudgetConfigID = src.BudgetConfigID + AND target.EntityGroupConfigID = src.EntityGroupConfigID + AND target.EntityID = src.EntityID + AND target.PayorGroupID = src.PayorGroupID + AND target.PatientClassID = src.PatientClassID + ) + WHEN MATCHED AND ( + target.BudgetAdjusted01 <> src.BudgetAdjusted01 OR + target.BudgetAdjusted02 <> src.BudgetAdjusted02 OR + target.BudgetAdjusted03 <> src.BudgetAdjusted03 OR + target.BudgetAdjusted04 <> src.BudgetAdjusted04 OR + target.BudgetAdjusted05 <> src.BudgetAdjusted05 OR + target.BudgetAdjusted06 <> src.BudgetAdjusted06 OR + target.BudgetAdjusted07 <> src.BudgetAdjusted07 OR + target.BudgetAdjusted08 <> src.BudgetAdjusted08 OR + target.BudgetAdjusted09 <> src.BudgetAdjusted09 OR + target.BudgetAdjusted10 <> src.BudgetAdjusted10 OR + target.BudgetAdjusted11 <> src.BudgetAdjusted11 OR + target.BudgetAdjusted12 <> src.BudgetAdjusted12 OR + ( @IsUpdatePerOfCharge = 1 AND ( + target.BudgetAdjustedNetAsPercentOfCharge01 <> src.BudgetAdjustedNetAsPercentOfCharge01 OR + target.BudgetAdjustedNetAsPercentOfCharge02 <> src.BudgetAdjustedNetAsPercentOfCharge02 OR + target.BudgetAdjustedNetAsPercentOfCharge03 <> src.BudgetAdjustedNetAsPercentOfCharge03 OR + target.BudgetAdjustedNetAsPercentOfCharge04 <> src.BudgetAdjustedNetAsPercentOfCharge04 OR + target.BudgetAdjustedNetAsPercentOfCharge05 <> src.BudgetAdjustedNetAsPercentOfCharge05 OR + target.BudgetAdjustedNetAsPercentOfCharge06 <> src.BudgetAdjustedNetAsPercentOfCharge06 OR + target.BudgetAdjustedNetAsPercentOfCharge07 <> src.BudgetAdjustedNetAsPercentOfCharge07 OR + target.BudgetAdjustedNetAsPercentOfCharge08 <> src.BudgetAdjustedNetAsPercentOfCharge08 OR + target.BudgetAdjustedNetAsPercentOfCharge09 <> src.BudgetAdjustedNetAsPercentOfCharge09 OR + target.BudgetAdjustedNetAsPercentOfCharge10 <> src.BudgetAdjustedNetAsPercentOfCharge10 OR + target.BudgetAdjustedNetAsPercentOfCharge11 <> src.BudgetAdjustedNetAsPercentOfCharge11 OR + target.BudgetAdjustedNetAsPercentOfCharge12 <> src.BudgetAdjustedNetAsPercentOfCharge12 ) + ) + ) + THEN + UPDATE SET target.BudgetAdjusted01 = src.BudgetAdjusted01, + target.BudgetAdjusted02 = src.BudgetAdjusted02, + target.BudgetAdjusted03 = src.BudgetAdjusted03, + target.BudgetAdjusted04 = src.BudgetAdjusted04, + target.BudgetAdjusted05 = src.BudgetAdjusted05, + target.BudgetAdjusted06 = src.BudgetAdjusted06, + target.BudgetAdjusted07 = src.BudgetAdjusted07, + target.BudgetAdjusted08 = src.BudgetAdjusted08, + target.BudgetAdjusted09 = src.BudgetAdjusted09, + target.BudgetAdjusted10 = src.BudgetAdjusted10, + target.BudgetAdjusted11 = src.BudgetAdjusted11, + target.BudgetAdjusted12 = src.BudgetAdjusted12, + + target.BudgetAdjustedNetAsPercentOfCharge01 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge01 ELSE target.BudgetAdjustedNetAsPercentOfCharge01 END, + target.BudgetAdjustedNetAsPercentOfCharge02 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge02 ELSE target.BudgetAdjustedNetAsPercentOfCharge02 END, + target.BudgetAdjustedNetAsPercentOfCharge03 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge03 ELSE target.BudgetAdjustedNetAsPercentOfCharge03 END, + target.BudgetAdjustedNetAsPercentOfCharge04 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge04 ELSE target.BudgetAdjustedNetAsPercentOfCharge04 END, + target.BudgetAdjustedNetAsPercentOfCharge05 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge05 ELSE target.BudgetAdjustedNetAsPercentOfCharge05 END, + target.BudgetAdjustedNetAsPercentOfCharge06 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge06 ELSE target.BudgetAdjustedNetAsPercentOfCharge06 END, + target.BudgetAdjustedNetAsPercentOfCharge07 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge07 ELSE target.BudgetAdjustedNetAsPercentOfCharge07 END, + target.BudgetAdjustedNetAsPercentOfCharge08 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge08 ELSE target.BudgetAdjustedNetAsPercentOfCharge08 END, + target.BudgetAdjustedNetAsPercentOfCharge09 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge09 ELSE target.BudgetAdjustedNetAsPercentOfCharge09 END, + target.BudgetAdjustedNetAsPercentOfCharge10 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge10 ELSE target.BudgetAdjustedNetAsPercentOfCharge10 END, + target.BudgetAdjustedNetAsPercentOfCharge11 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge11 ELSE target.BudgetAdjustedNetAsPercentOfCharge11 END, + target.BudgetAdjustedNetAsPercentOfCharge12 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.BudgetAdjustedNetAsPercentOfCharge12 ELSE target.BudgetAdjustedNetAsPercentOfCharge12 END + OUTPUT + INSERTED.ReimbursementGeneralLedgerID + INTO + #budgetBasisIDs (ReimbursementGeneralLedgerID); + + + + -- Publish Projection + ;WITH TGT AS + ( + SELECT rgl.ReimbursementGeneralLedgerID, rgl.BudgetConfigID, rgl.EntityGroupConfigID, rgl.EntityID, rgl.PayorGroupID, rgl.PatientClassID, + [ProjectionAdjusted01], [ProjectionAdjusted02], [ProjectionAdjusted03], [ProjectionAdjusted04], [ProjectionAdjusted05], [ProjectionAdjusted06], + [ProjectionAdjusted07], [ProjectionAdjusted08], [ProjectionAdjusted09], [ProjectionAdjusted10], [ProjectionAdjusted11], [ProjectionAdjusted12], + + [ProjectionAdjustedNetAsPercentOfCharge01], [ProjectionAdjustedNetAsPercentOfCharge02], [ProjectionAdjustedNetAsPercentOfCharge03], [ProjectionAdjustedNetAsPercentOfCharge04], + [ProjectionAdjustedNetAsPercentOfCharge05], [ProjectionAdjustedNetAsPercentOfCharge06], [ProjectionAdjustedNetAsPercentOfCharge07], [ProjectionAdjustedNetAsPercentOfCharge08], + [ProjectionAdjustedNetAsPercentOfCharge09], [ProjectionAdjustedNetAsPercentOfCharge10], [ProjectionAdjustedNetAsPercentOfCharge11], [ProjectionAdjustedNetAsPercentOfCharge12] + FROM [fp].[ReimbursementGeneralLedger] rgl + WHERE rgl.BudgetConfigID = @BudgetConfigID + ) + + MERGE TGT AS target + USING #ReimbursementGL AS src + ON ( + target.BudgetConfigID = src.BudgetConfigID + AND target.EntityGroupConfigID = src.EntityGroupConfigID + AND target.EntityID = src.EntityID + AND target.PayorGroupID = src.PayorGroupID + AND target.PatientClassID = src.PatientClassID + ) + WHEN MATCHED AND ( + target.ProjectionAdjusted01 <> src.ProjectionAdjusted01 OR + target.ProjectionAdjusted02 <> src.ProjectionAdjusted02 OR + target.ProjectionAdjusted03 <> src.ProjectionAdjusted03 OR + target.ProjectionAdjusted04 <> src.ProjectionAdjusted04 OR + target.ProjectionAdjusted05 <> src.ProjectionAdjusted05 OR + target.ProjectionAdjusted06 <> src.ProjectionAdjusted06 OR + target.ProjectionAdjusted07 <> src.ProjectionAdjusted07 OR + target.ProjectionAdjusted08 <> src.ProjectionAdjusted08 OR + target.ProjectionAdjusted09 <> src.ProjectionAdjusted09 OR + target.ProjectionAdjusted10 <> src.ProjectionAdjusted10 OR + target.ProjectionAdjusted11 <> src.ProjectionAdjusted11 OR + target.ProjectionAdjusted12 <> src.ProjectionAdjusted12 OR + ( @IsUpdatePerOfCharge = 1 AND ( + target.ProjectionAdjustedNetAsPercentOfCharge01 <> src.ProjectionAdjustedNetAsPercentOfCharge01 OR + target.ProjectionAdjustedNetAsPercentOfCharge02 <> src.ProjectionAdjustedNetAsPercentOfCharge02 OR + target.ProjectionAdjustedNetAsPercentOfCharge03 <> src.ProjectionAdjustedNetAsPercentOfCharge03 OR + target.ProjectionAdjustedNetAsPercentOfCharge04 <> src.ProjectionAdjustedNetAsPercentOfCharge04 OR + target.ProjectionAdjustedNetAsPercentOfCharge05 <> src.ProjectionAdjustedNetAsPercentOfCharge05 OR + target.ProjectionAdjustedNetAsPercentOfCharge06 <> src.ProjectionAdjustedNetAsPercentOfCharge06 OR + target.ProjectionAdjustedNetAsPercentOfCharge07 <> src.ProjectionAdjustedNetAsPercentOfCharge07 OR + target.ProjectionAdjustedNetAsPercentOfCharge08 <> src.ProjectionAdjustedNetAsPercentOfCharge08 OR + target.ProjectionAdjustedNetAsPercentOfCharge09 <> src.ProjectionAdjustedNetAsPercentOfCharge09 OR + target.ProjectionAdjustedNetAsPercentOfCharge10 <> src.ProjectionAdjustedNetAsPercentOfCharge10 OR + target.ProjectionAdjustedNetAsPercentOfCharge11 <> src.ProjectionAdjustedNetAsPercentOfCharge11 OR + target.ProjectionAdjustedNetAsPercentOfCharge12 <> src.ProjectionAdjustedNetAsPercentOfCharge12 ) + ) + ) + THEN + UPDATE SET target.ProjectionAdjusted01 = src.ProjectionAdjusted01, + target.ProjectionAdjusted02 = src.ProjectionAdjusted02, + target.ProjectionAdjusted03 = src.ProjectionAdjusted03, + target.ProjectionAdjusted04 = src.ProjectionAdjusted04, + target.ProjectionAdjusted05 = src.ProjectionAdjusted05, + target.ProjectionAdjusted06 = src.ProjectionAdjusted06, + target.ProjectionAdjusted07 = src.ProjectionAdjusted07, + target.ProjectionAdjusted08 = src.ProjectionAdjusted08, + target.ProjectionAdjusted09 = src.ProjectionAdjusted09, + target.ProjectionAdjusted10 = src.ProjectionAdjusted10, + target.ProjectionAdjusted11 = src.ProjectionAdjusted11, + target.ProjectionAdjusted12 = src.ProjectionAdjusted12, + + target.ProjectionAdjustedNetAsPercentOfCharge01 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge01 ELSE target.ProjectionAdjustedNetAsPercentOfCharge01 END, + target.ProjectionAdjustedNetAsPercentOfCharge02 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge02 ELSE target.ProjectionAdjustedNetAsPercentOfCharge02 END, + target.ProjectionAdjustedNetAsPercentOfCharge03 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge03 ELSE target.ProjectionAdjustedNetAsPercentOfCharge03 END, + target.ProjectionAdjustedNetAsPercentOfCharge04 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge04 ELSE target.ProjectionAdjustedNetAsPercentOfCharge04 END, + target.ProjectionAdjustedNetAsPercentOfCharge05 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge05 ELSE target.ProjectionAdjustedNetAsPercentOfCharge05 END, + target.ProjectionAdjustedNetAsPercentOfCharge06 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge06 ELSE target.ProjectionAdjustedNetAsPercentOfCharge06 END, + target.ProjectionAdjustedNetAsPercentOfCharge07 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge07 ELSE target.ProjectionAdjustedNetAsPercentOfCharge07 END, + target.ProjectionAdjustedNetAsPercentOfCharge08 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge08 ELSE target.ProjectionAdjustedNetAsPercentOfCharge08 END, + target.ProjectionAdjustedNetAsPercentOfCharge09 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge09 ELSE target.ProjectionAdjustedNetAsPercentOfCharge09 END, + target.ProjectionAdjustedNetAsPercentOfCharge10 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge10 ELSE target.ProjectionAdjustedNetAsPercentOfCharge10 END, + target.ProjectionAdjustedNetAsPercentOfCharge11 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge11 ELSE target.ProjectionAdjustedNetAsPercentOfCharge11 END, + target.ProjectionAdjustedNetAsPercentOfCharge12 = CASE WHEN @IsUpdatePerOfCharge = 1 THEN src.ProjectionAdjustedNetAsPercentOfCharge12 ELSE target.ProjectionAdjustedNetAsPercentOfCharge12 END + OUTPUT + INSERTED.ReimbursementGeneralLedgerID + INTO + #projectionBasisIDs (ReimbursementGeneralLedgerID); + + -- Find out what was changed. We can cross apply all 12 months in this case because months are on rows. If we change + -- projection to only update the months not loaded, we'll want to update this. Unlike other procs that are similar, + -- we don't care about the value because when we fix the change history, we take the stored rate in the change history + -- times the volume in the DB, we don't actually care what the value was we flexed to like in the past. + SELECT DISTINCT ReimbursementGeneralLedgerID AS BasisID, m.FiscalMonthID, cast(3 as tinyint) AS BudgetPhaseID, cast(2 as tinyint) AS TimeClassID + FROM #budgetBasisIDs + CROSS JOIN fw.DimFiscalMonth m + WHERE m.FiscalMonthID != 0 + UNION ALL + SELECT DISTINCT ReimbursementGeneralLedgerID AS BasisID, m.FiscalMonthID, cast(2 as tinyint) AS BudgetPhaseID, cast(2 as tinyint) AS TimeClassID + FROM #targetBasisIDs + CROSS JOIN fw.DimFiscalMonth m + WHERE m.FiscalMonthID != 0 + UNION ALL + SELECT DISTINCT ReimbursementGeneralLedgerID AS BasisID, m.FiscalMonthID, cast(3 as tinyint) AS BudgetPhaseID, cast(12 as tinyint) AS TimeClassID + FROM #projectionBasisIDs + CROSS JOIN fw.DimFiscalMonth m + WHERE m.FiscalMonthID != 0 + END +END +GO + + +--------------------------------------------- + +-- fp.procSampleGeneralLedgerToReimbursement_History +CREATE PROCEDURE [fp].[procSampleGeneralLedgerToReimbursement_History] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 05-23-2023 MZ JAZZ-54503 Initial Creation + ** 2 07-04-2023 AO JAZZ-57174 Adjusted formula NetAsPercentOfCharge + ** 3 10-04-2023 MZ JAZZ-61634  Fix % of charge calculation when revenue stays the same but new deductions were found + ** 4 01-03-2024 AO JAZZ-65384 Data transfer for GL is based on selected Model in Plan Config + ** 5 08-12-2024 VZ JAZZ-74434 Data transfer for GL based on excluded departments + *************************************************************/ + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment; + IF OBJECT_ID('tempdb..#ReimbursementGL') IS NOT NULL DROP TABLE #ReimbursementGL; + IF OBJECT_ID('tempdb..#glTargeting') IS NOT NULL DROP TABLE #glTargeting; + IF OBJECT_ID('tempdb..#RevenueData') IS NOT NULL DROP TABLE #RevenueData; + IF OBJECT_ID('tempdb..#DeductionData') IS NOT NULL DROP TABLE #DeductionData; + + CREATE TABLE #FilterByDepartment (DepartmentID INT); + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #glTargeting (EntityID INT, GeneralLedgerID INT); + + DECLARE @Revenue INT = 1; + DECLARE @Deduction INT = 4; + + CREATE TABLE #RevenueData ( + [BudgetConfigID] [int], + [EntityGroupConfigID] [int], + [EntityID] [int], + [PayorGroupID] [int], + [PatientClassID] [int], + [PriorYearActualValue01] [decimal](19, 8), + [PriorYearActualValue02] [decimal](19, 8), + [PriorYearActualValue03] [decimal](19, 8), + [PriorYearActualValue04] [decimal](19, 8), + [PriorYearActualValue05] [decimal](19, 8), + [PriorYearActualValue06] [decimal](19, 8), + [PriorYearActualValue07] [decimal](19, 8), + [PriorYearActualValue08] [decimal](19, 8), + [PriorYearActualValue09] [decimal](19, 8), + [PriorYearActualValue10] [decimal](19, 8), + [PriorYearActualValue11] [decimal](19, 8), + [PriorYearActualValue12] [decimal](19, 8) + ) + + CREATE TABLE #DeductionData ( + [BudgetConfigID] [int], + [EntityGroupConfigID] [int], + [EntityID] [int], + [PayorGroupID] [int], + [PatientClassID] [int], + [PriorYearActualValue01] [decimal](19, 8), + [PriorYearActualValue02] [decimal](19, 8), + [PriorYearActualValue03] [decimal](19, 8), + [PriorYearActualValue04] [decimal](19, 8), + [PriorYearActualValue05] [decimal](19, 8), + [PriorYearActualValue06] [decimal](19, 8), + [PriorYearActualValue07] [decimal](19, 8), + [PriorYearActualValue08] [decimal](19, 8), + [PriorYearActualValue09] [decimal](19, 8), + [PriorYearActualValue10] [decimal](19, 8), + [PriorYearActualValue11] [decimal](19, 8), + [PriorYearActualValue12] [decimal](19, 8) + ) + + CREATE TABLE #ReimbursementGL ( + [BudgetConfigID] [int], + [EntityGroupConfigID] [int], + [EntityID] [int], + [PayorGroupID] [int], + [PatientClassID] [int], + [PriorYearActualValue01] [decimal](19, 8), + [PriorYearActualValue02] [decimal](19, 8), + [PriorYearActualValue03] [decimal](19, 8), + [PriorYearActualValue04] [decimal](19, 8), + [PriorYearActualValue05] [decimal](19, 8), + [PriorYearActualValue06] [decimal](19, 8), + [PriorYearActualValue07] [decimal](19, 8), + [PriorYearActualValue08] [decimal](19, 8), + [PriorYearActualValue09] [decimal](19, 8), + [PriorYearActualValue10] [decimal](19, 8), + [PriorYearActualValue11] [decimal](19, 8), + [PriorYearActualValue12] [decimal](19, 8), + + [PriorYearActualValueNetAsPercentOfCharge01] [decimal](19, 8), + [PriorYearActualValueNetAsPercentOfCharge02] [decimal](19, 8), + [PriorYearActualValueNetAsPercentOfCharge03] [decimal](19, 8), + [PriorYearActualValueNetAsPercentOfCharge04] [decimal](19, 8), + [PriorYearActualValueNetAsPercentOfCharge05] [decimal](19, 8), + [PriorYearActualValueNetAsPercentOfCharge06] [decimal](19, 8), + [PriorYearActualValueNetAsPercentOfCharge07] [decimal](19, 8), + [PriorYearActualValueNetAsPercentOfCharge08] [decimal](19, 8), + [PriorYearActualValueNetAsPercentOfCharge09] [decimal](19, 8), + [PriorYearActualValueNetAsPercentOfCharge10] [decimal](19, 8), + [PriorYearActualValueNetAsPercentOfCharge11] [decimal](19, 8), + [PriorYearActualValueNetAsPercentOfCharge12] [decimal](19, 8) + ) + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[GeneralLedger] gl WITH (READUNCOMMITTED) + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON rnrm.EntityID = gl.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE gl.BudgetConfigID = @BudgetConfigID + AND ((bc.DefaultReimbursementNetRevenueModelID = 2 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,2))) + OR rnrm.NetRevenueModelID = 2) -- GL Model + END + + DELETE #FilterByDepartment + WHERE DepartmentID IN ( + SELECT DepartmentID + FROM fp.GeneralLedgerReimbursementExcludedDepartments glred + JOIN fp.BudgetConfig bc ON glred.BudgetConfigGuid = bc.BudgetConfigGuid + WHERE bc.BudgetConfigID = @BudgetConfigID) + + --Revenue + INSERT INTO #RevenueData( + BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, + PriorYearActualValue01, PriorYearActualValue02, PriorYearActualValue03, PriorYearActualValue04, PriorYearActualValue05, PriorYearActualValue06, + PriorYearActualValue07, PriorYearActualValue08, PriorYearActualValue09, PriorYearActualValue10, PriorYearActualValue11, PriorYearActualValue12 + ) + SELECT DISTINCT gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID AS PayorGroupID, a.PatientClassID, + SUM(hist.PriorYearActualValue01) AS PriorYearActualValue01, SUM(hist.PriorYearActualValue02) AS PriorYearActualValue02, SUM(hist.PriorYearActualValue03) AS PriorYearActualValue03, + SUM(hist.PriorYearActualValue04) AS PriorYearActualValue04, SUM(hist.PriorYearActualValue05) AS PriorYearActualValue05, SUM(hist.PriorYearActualValue06) AS PriorYearActualValue06, + SUM(hist.PriorYearActualValue07) AS PriorYearActualValue07, SUM(hist.PriorYearActualValue08) AS PriorYearActualValue08, SUM(hist.PriorYearActualValue09) AS PriorYearActualValue09, + SUM(hist.PriorYearActualValue10) AS PriorYearActualValue10, SUM(hist.PriorYearActualValue11) AS PriorYearActualValue11, SUM(hist.PriorYearActualValue12) AS PriorYearActualValue12 + FROM fp.GeneralLedger gl + JOIN #FilterByDepartment ft ON ft.DepartmentID = gl.DepartmentID + INNER JOIN [fw].[DimAccount] a ON gl.AccountID = a.AccountID + INNER JOIN [fp].[GeneralLedgerHistory] hist ON gl.GeneralLedgerID = hist.GeneralLedgerID + WHERE gl.BudgetConfigID = @BudgetConfigID + AND gl.APEModelSectionID in (@Revenue) + GROUP BY gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID, a.PatientClassID, gl.APEModelSectionID + + --Deduction + INSERT INTO #DeductionData( + BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, + PriorYearActualValue01, PriorYearActualValue02, PriorYearActualValue03, PriorYearActualValue04, PriorYearActualValue05, PriorYearActualValue06, + PriorYearActualValue07, PriorYearActualValue08, PriorYearActualValue09, PriorYearActualValue10, PriorYearActualValue11, PriorYearActualValue12 + ) + SELECT DISTINCT gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID AS PayorGroupID, a.PatientClassID, + SUM(hist.PriorYearActualValue01) AS PriorYearActualValue01, SUM(hist.PriorYearActualValue02) AS PriorYearActualValue02, SUM(hist.PriorYearActualValue03) AS PriorYearActualValue03, + SUM(hist.PriorYearActualValue04) AS PriorYearActualValue04, SUM(hist.PriorYearActualValue05) AS PriorYearActualValue05, SUM(hist.PriorYearActualValue06) AS PriorYearActualValue06, + SUM(hist.PriorYearActualValue07) AS PriorYearActualValue07, SUM(hist.PriorYearActualValue08) AS PriorYearActualValue08, SUM(hist.PriorYearActualValue09) AS PriorYearActualValue09, + SUM(hist.PriorYearActualValue10) AS PriorYearActualValue10, SUM(hist.PriorYearActualValue11) AS PriorYearActualValue11, SUM(hist.PriorYearActualValue12) AS PriorYearActualValue12 + FROM fp.GeneralLedger gl + JOIN #FilterByDepartment ft ON ft.DepartmentID = gl.DepartmentID + INNER JOIN [fw].[DimAccount] a ON gl.AccountID = a.AccountID + INNER JOIN [fp].[GeneralLedgerHistory] hist ON gl.GeneralLedgerID = hist.GeneralLedgerID + WHERE gl.BudgetConfigID = @BudgetConfigID + AND gl.APEModelSectionID in (@Deduction) + AND a.OBModelSectionName = 'Deductions - Reimbursement' + GROUP BY gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID, a.PatientClassID, gl.APEModelSectionID + + + INSERT INTO #ReimbursementGL( + BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, + + PriorYearActualValue01, PriorYearActualValue02, PriorYearActualValue03, PriorYearActualValue04, PriorYearActualValue05, PriorYearActualValue06, + PriorYearActualValue07, PriorYearActualValue08, PriorYearActualValue09, PriorYearActualValue10, PriorYearActualValue11, PriorYearActualValue12, + + PriorYearActualValueNetAsPercentOfCharge01, PriorYearActualValueNetAsPercentOfCharge02, PriorYearActualValueNetAsPercentOfCharge03, PriorYearActualValueNetAsPercentOfCharge04, + PriorYearActualValueNetAsPercentOfCharge05, PriorYearActualValueNetAsPercentOfCharge06, PriorYearActualValueNetAsPercentOfCharge07, PriorYearActualValueNetAsPercentOfCharge08, + PriorYearActualValueNetAsPercentOfCharge09, PriorYearActualValueNetAsPercentOfCharge10, PriorYearActualValueNetAsPercentOfCharge11, PriorYearActualValueNetAsPercentOfCharge12 + ) + SELECT DISTINCT r.BudgetConfigID, r.EntityGroupConfigID, r.EntityID, r.PayorGroupID, r.PatientClassID, + r.PriorYearActualValue01, r.PriorYearActualValue02, r.PriorYearActualValue03, r.PriorYearActualValue04, r.PriorYearActualValue05, r.PriorYearActualValue06, + r.PriorYearActualValue07, r.PriorYearActualValue08, r.PriorYearActualValue09, r.PriorYearActualValue10, r.PriorYearActualValue11, r.PriorYearActualValue12, + --PriorYearActualValueNetAsPercentOfCharge + -- %ofCharge = NetReimbursement/revenue = (revenue - deduction) / revenue + CASE + WHEN r.PriorYearActualValue01 IS NULL OR r.PriorYearActualValue01 = 0 THEN 0 + WHEN d.PriorYearActualValue01 IS NULL THEN 1 + ELSE (r.PriorYearActualValue01 - d.PriorYearActualValue01) / r.PriorYearActualValue01 + END AS PriorYearActualValueNetAsPercentOfCharge01, + CASE + WHEN r.PriorYearActualValue02 IS NULL OR r.PriorYearActualValue02 = 0 THEN 0 + WHEN d.PriorYearActualValue02 IS NULL THEN 1 + ELSE (r.PriorYearActualValue02 - d.PriorYearActualValue02) / r.PriorYearActualValue02 + END AS PriorYearActualValueNetAsPercentOfCharge02, + CASE + WHEN r.PriorYearActualValue03 IS NULL OR r.PriorYearActualValue03 = 0 THEN 0 + WHEN d.PriorYearActualValue03 IS NULL THEN 1 + ELSE (r.PriorYearActualValue03 - d.PriorYearActualValue03) / r.PriorYearActualValue03 + END AS PriorYearActualValueNetAsPercentOfCharge03, + CASE + WHEN r.PriorYearActualValue04 IS NULL OR r.PriorYearActualValue04 = 0 THEN 0 + WHEN d.PriorYearActualValue04 IS NULL THEN 1 + ELSE (r.PriorYearActualValue04 - d.PriorYearActualValue04) / r.PriorYearActualValue04 + END AS PriorYearActualValueNetAsPercentOfCharge04, + CASE + WHEN r.PriorYearActualValue05 IS NULL OR r.PriorYearActualValue05 = 0 THEN 0 + WHEN d.PriorYearActualValue05 IS NULL THEN 1 + ELSE (r.PriorYearActualValue05 - d.PriorYearActualValue05) / r.PriorYearActualValue05 + END AS PriorYearActualValueNetAsPercentOfCharge05, + CASE + WHEN r.PriorYearActualValue06 IS NULL OR r.PriorYearActualValue06 = 0 THEN 0 + WHEN d.PriorYearActualValue06 IS NULL THEN 1 + ELSE (r.PriorYearActualValue06 - d.PriorYearActualValue06) / r.PriorYearActualValue06 + END AS PriorYearActualValueNetAsPercentOfCharge06, + CASE + WHEN r.PriorYearActualValue07 IS NULL OR r.PriorYearActualValue07 = 0 THEN 0 + WHEN d.PriorYearActualValue07 IS NULL THEN 1 + ELSE (r.PriorYearActualValue07 - d.PriorYearActualValue07) / r.PriorYearActualValue07 + END AS PriorYearActualValueNetAsPercentOfCharge07, + CASE + WHEN r.PriorYearActualValue08 IS NULL OR r.PriorYearActualValue08 = 0 THEN 0 + WHEN d.PriorYearActualValue08 IS NULL THEN 1 + ELSE (r.PriorYearActualValue08 - d.PriorYearActualValue08) / r.PriorYearActualValue08 + END AS PriorYearActualValueNetAsPercentOfCharge08, + CASE + WHEN r.PriorYearActualValue09 IS NULL OR r.PriorYearActualValue09 = 0 THEN 0 + WHEN d.PriorYearActualValue09 IS NULL THEN 1 + ELSE (r.PriorYearActualValue09 - d.PriorYearActualValue09) / r.PriorYearActualValue09 + END AS PriorYearActualValueNetAsPercentOfCharge09, + CASE + WHEN r.PriorYearActualValue10 IS NULL OR r.PriorYearActualValue10 = 0 THEN 0 + WHEN d.PriorYearActualValue10 IS NULL THEN 1 + ELSE (r.PriorYearActualValue10 - d.PriorYearActualValue10) / r.PriorYearActualValue10 + END AS PriorYearActualValueNetAsPercentOfCharge10, + CASE + WHEN r.PriorYearActualValue11 IS NULL OR r.PriorYearActualValue11 = 0 THEN 0 + WHEN d.PriorYearActualValue11 IS NULL THEN 1 + ELSE (r.PriorYearActualValue11 - d.PriorYearActualValue11) / r.PriorYearActualValue11 + END AS PriorYearActualValueNetAsPercentOfCharge11, + CASE + WHEN r.PriorYearActualValue12 IS NULL OR r.PriorYearActualValue12 = 0 THEN 0 + WHEN d.PriorYearActualValue12 IS NULL THEN 1 + ELSE (r.PriorYearActualValue12 - d.PriorYearActualValue12) / r.PriorYearActualValue12 + END AS PriorYearActualValueNetAsPercentOfCharge12 + FROM #RevenueData r + LEFT JOIN #DeductionData d ON d.BudgetConfigID = r.BudgetConfigID AND d.EntityGroupConfigID = r.EntityGroupConfigID AND d.EntityID = r.EntityID + AND d.PayorGroupID = r.PayorGroupID AND d.PatientClassID = r.PatientClassID + WHERE r.BudgetConfigID = @BudgetConfigID + + + IF (@IsDebug = 1) + BEGIN + SELECT '#FilterByDepartment', DepartmentID FROM #FilterByDepartment + SELECT '#ReimbursementGL', * FROM #ReimbursementGL + SELECT '#DeductionData', * FROM #DeductionData + SELECT '#RevenueData', * FROM #RevenueData + END ELSE + BEGIN + -- Publish + ;WITH TGT AS + ( + SELECT rgl.BudgetConfigID, rgl.EntityGroupConfigID, rgl.EntityID, rgl.PayorGroupID, rgl.PatientClassID, + [PriorYearActualValue01], [PriorYearActualValue02], [PriorYearActualValue03], [PriorYearActualValue04], [PriorYearActualValue05], [PriorYearActualValue06], + [PriorYearActualValue07], [PriorYearActualValue08], [PriorYearActualValue09], [PriorYearActualValue10], [PriorYearActualValue11], [PriorYearActualValue12], + + [PriorYearActualValueNetAsPercentOfCharge01], [PriorYearActualValueNetAsPercentOfCharge02], [PriorYearActualValueNetAsPercentOfCharge03], [PriorYearActualValueNetAsPercentOfCharge04], + [PriorYearActualValueNetAsPercentOfCharge05], [PriorYearActualValueNetAsPercentOfCharge06], [PriorYearActualValueNetAsPercentOfCharge07], [PriorYearActualValueNetAsPercentOfCharge08], + [PriorYearActualValueNetAsPercentOfCharge09], [PriorYearActualValueNetAsPercentOfCharge10], [PriorYearActualValueNetAsPercentOfCharge11], [PriorYearActualValueNetAsPercentOfCharge12] + + FROM [fp].[ReimbursementGeneralLedger] rgl + INNER JOIN [fp].[ReimbursementGeneralLedgerHistory] hist ON rgl.ReimbursementGeneralLedgerID = hist.ReimbursementGeneralLedgerID + WHERE rgl.BudgetConfigID = @BudgetConfigID + ) + + MERGE TGT AS target + USING #ReimbursementGL AS src + ON ( + target.BudgetConfigID = src.BudgetConfigID + AND target.EntityGroupConfigID = src.EntityGroupConfigID + AND target.EntityID = src.EntityID + AND target.PayorGroupID = src.PayorGroupID + AND target.PatientClassID = src.PatientClassID + ) + WHEN MATCHED AND ( + target.PriorYearActualValue01 <> src.PriorYearActualValue01 OR + target.PriorYearActualValue02 <> src.PriorYearActualValue02 OR + target.PriorYearActualValue03 <> src.PriorYearActualValue03 OR + target.PriorYearActualValue04 <> src.PriorYearActualValue04 OR + target.PriorYearActualValue05 <> src.PriorYearActualValue05 OR + target.PriorYearActualValue06 <> src.PriorYearActualValue06 OR + target.PriorYearActualValue07 <> src.PriorYearActualValue07 OR + target.PriorYearActualValue08 <> src.PriorYearActualValue08 OR + target.PriorYearActualValue09 <> src.PriorYearActualValue09 OR + target.PriorYearActualValue10 <> src.PriorYearActualValue10 OR + target.PriorYearActualValue11 <> src.PriorYearActualValue11 OR + target.PriorYearActualValue12 <> src.PriorYearActualValue12 OR + + target.PriorYearActualValueNetAsPercentOfCharge01 <> src.PriorYearActualValueNetAsPercentOfCharge01 OR + target.PriorYearActualValueNetAsPercentOfCharge02 <> src.PriorYearActualValueNetAsPercentOfCharge02 OR + target.PriorYearActualValueNetAsPercentOfCharge03 <> src.PriorYearActualValueNetAsPercentOfCharge03 OR + target.PriorYearActualValueNetAsPercentOfCharge04 <> src.PriorYearActualValueNetAsPercentOfCharge04 OR + target.PriorYearActualValueNetAsPercentOfCharge05 <> src.PriorYearActualValueNetAsPercentOfCharge05 OR + target.PriorYearActualValueNetAsPercentOfCharge06 <> src.PriorYearActualValueNetAsPercentOfCharge06 OR + target.PriorYearActualValueNetAsPercentOfCharge07 <> src.PriorYearActualValueNetAsPercentOfCharge07 OR + target.PriorYearActualValueNetAsPercentOfCharge08 <> src.PriorYearActualValueNetAsPercentOfCharge08 OR + target.PriorYearActualValueNetAsPercentOfCharge09 <> src.PriorYearActualValueNetAsPercentOfCharge09 OR + target.PriorYearActualValueNetAsPercentOfCharge10 <> src.PriorYearActualValueNetAsPercentOfCharge10 OR + target.PriorYearActualValueNetAsPercentOfCharge11 <> src.PriorYearActualValueNetAsPercentOfCharge11 OR + target.PriorYearActualValueNetAsPercentOfCharge12 <> src.PriorYearActualValueNetAsPercentOfCharge12 + ) + THEN + UPDATE SET target.PriorYearActualValue01 = src.PriorYearActualValue01, + target.PriorYearActualValue02 = src.PriorYearActualValue02, + target.PriorYearActualValue03 = src.PriorYearActualValue03, + target.PriorYearActualValue04 = src.PriorYearActualValue04, + target.PriorYearActualValue05 = src.PriorYearActualValue05, + target.PriorYearActualValue06 = src.PriorYearActualValue06, + target.PriorYearActualValue07 = src.PriorYearActualValue07, + target.PriorYearActualValue08 = src.PriorYearActualValue08, + target.PriorYearActualValue09 = src.PriorYearActualValue09, + target.PriorYearActualValue10 = src.PriorYearActualValue10, + target.PriorYearActualValue11 = src.PriorYearActualValue11, + target.PriorYearActualValue12 = src.PriorYearActualValue12, + + target.PriorYearActualValueNetAsPercentOfCharge01 = src.PriorYearActualValueNetAsPercentOfCharge01, + target.PriorYearActualValueNetAsPercentOfCharge02 = src.PriorYearActualValueNetAsPercentOfCharge02, + target.PriorYearActualValueNetAsPercentOfCharge03 = src.PriorYearActualValueNetAsPercentOfCharge03, + target.PriorYearActualValueNetAsPercentOfCharge04 = src.PriorYearActualValueNetAsPercentOfCharge04, + target.PriorYearActualValueNetAsPercentOfCharge05 = src.PriorYearActualValueNetAsPercentOfCharge05, + target.PriorYearActualValueNetAsPercentOfCharge06 = src.PriorYearActualValueNetAsPercentOfCharge06, + target.PriorYearActualValueNetAsPercentOfCharge07 = src.PriorYearActualValueNetAsPercentOfCharge07, + target.PriorYearActualValueNetAsPercentOfCharge08 = src.PriorYearActualValueNetAsPercentOfCharge08, + target.PriorYearActualValueNetAsPercentOfCharge09 = src.PriorYearActualValueNetAsPercentOfCharge09, + target.PriorYearActualValueNetAsPercentOfCharge10 = src.PriorYearActualValueNetAsPercentOfCharge10, + target.PriorYearActualValueNetAsPercentOfCharge11 = src.PriorYearActualValueNetAsPercentOfCharge11, + target.PriorYearActualValueNetAsPercentOfCharge12 = src.PriorYearActualValueNetAsPercentOfCharge12; + + END +END +GO + + +--------------------------------------------- + +-- fp.procSampleGeneralLedgerToReimbursement_Initial +CREATE PROCEDURE [fp].[procSampleGeneralLedgerToReimbursement_Initial] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 05-23-2023 MZ JAZZ-54503 Initial Creation + ** 2 07-04-2023 AO JAZZ-57174 Adjusted formula NetAsPercentOfCharge + ** 3 10-04-2023 MZ JAZZ-61634  Fix % of charge calculation when revenue stays the same but new deductions were found + ** 4 01-03-2024 AO JAZZ-65384 Data transfer for GL is based on selected Model in Plan Config + ** 5 08-12-2024 VZ JAZZ-74434 Data transfer for GL based on excluded departments + *************************************************************/ + + -- Clean up old tables (and so SSMS is happy) + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment; + IF OBJECT_ID('tempdb..#ReimbursementGL') IS NOT NULL DROP TABLE #ReimbursementGL; + IF OBJECT_ID('tempdb..#glTargeting') IS NOT NULL DROP TABLE #glTargeting; + IF OBJECT_ID('tempdb..#RevenueData') IS NOT NULL DROP TABLE #RevenueData; + IF OBJECT_ID('tempdb..#DeductionData') IS NOT NULL DROP TABLE #DeductionData; + + CREATE TABLE #FilterByDepartment (DepartmentID INT); + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #glTargeting (EntityID INT, GeneralLedgerID INT); + + CREATE TABLE #RevenueData ( + [BudgetConfigID] [int], + [EntityGroupConfigID] [int], + [EntityID] [int], + [PayorGroupID] [int], + [PatientClassID] [int], + [InitialBudget01] [decimal](19, 8), + [InitialBudget02] [decimal](19, 8), + [InitialBudget03] [decimal](19, 8), + [InitialBudget04] [decimal](19, 8), + [InitialBudget05] [decimal](19, 8), + [InitialBudget06] [decimal](19, 8), + [InitialBudget07] [decimal](19, 8), + [InitialBudget08] [decimal](19, 8), + [InitialBudget09] [decimal](19, 8), + [InitialBudget10] [decimal](19, 8), + [InitialBudget11] [decimal](19, 8), + [InitialBudget12] [decimal](19, 8), + + [InitialProjection01] [decimal](19, 8), + [InitialProjection02] [decimal](19, 8), + [InitialProjection03] [decimal](19, 8), + [InitialProjection04] [decimal](19, 8), + [InitialProjection05] [decimal](19, 8), + [InitialProjection06] [decimal](19, 8), + [InitialProjection07] [decimal](19, 8), + [InitialProjection08] [decimal](19, 8), + [InitialProjection09] [decimal](19, 8), + [InitialProjection10] [decimal](19, 8), + [InitialProjection11] [decimal](19, 8), + [InitialProjection12] [decimal](19, 8) + ) + + CREATE TABLE #DeductionData ( + [BudgetConfigID] [int], + [EntityGroupConfigID] [int], + [EntityID] [int], + [PayorGroupID] [int], + [PatientClassID] [int], + [InitialBudget01] [decimal](19, 8), + [InitialBudget02] [decimal](19, 8), + [InitialBudget03] [decimal](19, 8), + [InitialBudget04] [decimal](19, 8), + [InitialBudget05] [decimal](19, 8), + [InitialBudget06] [decimal](19, 8), + [InitialBudget07] [decimal](19, 8), + [InitialBudget08] [decimal](19, 8), + [InitialBudget09] [decimal](19, 8), + [InitialBudget10] [decimal](19, 8), + [InitialBudget11] [decimal](19, 8), + [InitialBudget12] [decimal](19, 8), + + [InitialProjection01] [decimal](19, 8), + [InitialProjection02] [decimal](19, 8), + [InitialProjection03] [decimal](19, 8), + [InitialProjection04] [decimal](19, 8), + [InitialProjection05] [decimal](19, 8), + [InitialProjection06] [decimal](19, 8), + [InitialProjection07] [decimal](19, 8), + [InitialProjection08] [decimal](19, 8), + [InitialProjection09] [decimal](19, 8), + [InitialProjection10] [decimal](19, 8), + [InitialProjection11] [decimal](19, 8), + [InitialProjection12] [decimal](19, 8) + ) + + CREATE TABLE #ReimbursementGL ( + [BudgetConfigID] [int], + [EntityGroupConfigID] [int], + [EntityID] [int], + [PayorGroupID] [int], + [PatientClassID] [int], + [InitialBudget01] [decimal](19, 8), + [InitialBudget02] [decimal](19, 8), + [InitialBudget03] [decimal](19, 8), + [InitialBudget04] [decimal](19, 8), + [InitialBudget05] [decimal](19, 8), + [InitialBudget06] [decimal](19, 8), + [InitialBudget07] [decimal](19, 8), + [InitialBudget08] [decimal](19, 8), + [InitialBudget09] [decimal](19, 8), + [InitialBudget10] [decimal](19, 8), + [InitialBudget11] [decimal](19, 8), + [InitialBudget12] [decimal](19, 8), + + [InitialProjection01] [decimal](19, 8), + [InitialProjection02] [decimal](19, 8), + [InitialProjection03] [decimal](19, 8), + [InitialProjection04] [decimal](19, 8), + [InitialProjection05] [decimal](19, 8), + [InitialProjection06] [decimal](19, 8), + [InitialProjection07] [decimal](19, 8), + [InitialProjection08] [decimal](19, 8), + [InitialProjection09] [decimal](19, 8), + [InitialProjection10] [decimal](19, 8), + [InitialProjection11] [decimal](19, 8), + [InitialProjection12] [decimal](19, 8), + + [InitialBudgetNetAsPercentOfCharge01] [decimal](19, 8), + [InitialBudgetNetAsPercentOfCharge02] [decimal](19, 8), + [InitialBudgetNetAsPercentOfCharge03] [decimal](19, 8), + [InitialBudgetNetAsPercentOfCharge04] [decimal](19, 8), + [InitialBudgetNetAsPercentOfCharge05] [decimal](19, 8), + [InitialBudgetNetAsPercentOfCharge06] [decimal](19, 8), + [InitialBudgetNetAsPercentOfCharge07] [decimal](19, 8), + [InitialBudgetNetAsPercentOfCharge08] [decimal](19, 8), + [InitialBudgetNetAsPercentOfCharge09] [decimal](19, 8), + [InitialBudgetNetAsPercentOfCharge10] [decimal](19, 8), + [InitialBudgetNetAsPercentOfCharge11] [decimal](19, 8), + [InitialBudgetNetAsPercentOfCharge12] [decimal](19, 8), + + [InitialProjectionNetAsPercentOfCharge01] [decimal](19, 8), + [InitialProjectionNetAsPercentOfCharge02] [decimal](19, 8), + [InitialProjectionNetAsPercentOfCharge03] [decimal](19, 8), + [InitialProjectionNetAsPercentOfCharge04] [decimal](19, 8), + [InitialProjectionNetAsPercentOfCharge05] [decimal](19, 8), + [InitialProjectionNetAsPercentOfCharge06] [decimal](19, 8), + [InitialProjectionNetAsPercentOfCharge07] [decimal](19, 8), + [InitialProjectionNetAsPercentOfCharge08] [decimal](19, 8), + [InitialProjectionNetAsPercentOfCharge09] [decimal](19, 8), + [InitialProjectionNetAsPercentOfCharge10] [decimal](19, 8), + [InitialProjectionNetAsPercentOfCharge11] [decimal](19, 8), + [InitialProjectionNetAsPercentOfCharge12] [decimal](19, 8) + ) + + DECLARE @Revenue INT = 1; + DECLARE @Deduction INT = 4; + + -- If the filter is empty, passing in all to avoid a bunch of duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[GeneralLedger] gl WITH (READUNCOMMITTED) + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = @BudgetConfigID + LEFT JOIN fp.ReimbursementNetRevenueModel rnrm ON rnrm.EntityID = gl.EntityID AND rnrm.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE gl.BudgetConfigID = @BudgetConfigID + AND ((bc.DefaultReimbursementNetRevenueModelID = 2 + AND (rnrm.EntityID IS NULL OR rnrm.NetRevenueModelID IN (0,2))) + OR rnrm.NetRevenueModelID = 2) -- GL Model + END + + DELETE #FilterByDepartment + WHERE DepartmentID IN ( + SELECT DepartmentID + FROM fp.GeneralLedgerReimbursementExcludedDepartments glred + JOIN fp.BudgetConfig bc ON glred.BudgetConfigGuid = bc.BudgetConfigGuid + WHERE bc.BudgetConfigID = @BudgetConfigID) + + --Revenue + INSERT INTO #RevenueData( + BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, + + InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, + InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, + + InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, + InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12 + ) + SELECT DISTINCT gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID AS PayorGroupID, a.PatientClassID, + SUM(gl.InitialBudget01) AS InitialBudget01, SUM(gl.InitialBudget02) AS InitialBudget02, SUM(gl.InitialBudget03) AS InitialBudget03, SUM(gl.InitialBudget04) AS InitialBudget04, SUM(gl.InitialBudget05) AS InitialBudget05, SUM(gl.InitialBudget06) AS InitialBudget06, SUM(gl.InitialBudget07) AS InitialBudget07, SUM(gl.InitialBudget08) AS InitialBudget08, SUM(gl.InitialBudget09) AS InitialBudget09, SUM(gl.InitialBudget10) AS InitialBudget10, SUM(gl.InitialBudget11) AS InitialBudget11, SUM(gl.InitialBudget12) AS InitialBudget12, + SUM(gl.InitialProjection01) AS InitialProjection01, SUM(gl.InitialProjection02) AS InitialProjection02, SUM(gl.InitialProjection03) AS InitialProjection03, SUM(gl.InitialProjection04) AS InitialProjection04, SUM(gl.InitialProjection05) AS InitialProjection05, SUM(gl.InitialProjection06) AS InitialProjection06, SUM(gl.InitialProjection07) AS InitialProjection07, SUM(gl.InitialProjection08) AS InitialProjection08, SUM(gl.InitialProjection09) AS InitialProjection09, SUM(gl.InitialProjection10) AS InitialProjection10, SUM(gl.InitialProjection11) AS InitialProjection11, SUM(gl.InitialProjection12) AS InitialProjection12 + FROM fp.GeneralLedger gl + JOIN #FilterByDepartment ft ON ft.DepartmentID = gl.DepartmentID + INNER JOIN [fw].[DimAccount] a ON gl.AccountID = a.AccountID + WHERE gl.BudgetConfigID = @BudgetConfigID + AND gl.APEModelSectionID in (@Revenue) + GROUP BY gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID, a.PatientClassID, gl.APEModelSectionID + + --Deduction + INSERT INTO #DeductionData( + BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, + + InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, + InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, + + InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, + InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12 + ) + SELECT DISTINCT gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID AS PayorGroupID, a.PatientClassID, + SUM(gl.InitialBudget01) AS InitialBudget01, SUM(gl.InitialBudget02) AS InitialBudget02, SUM(gl.InitialBudget03) AS InitialBudget03, SUM(gl.InitialBudget04) AS InitialBudget04, SUM(gl.InitialBudget05) AS InitialBudget05, SUM(gl.InitialBudget06) AS InitialBudget06, SUM(gl.InitialBudget07) AS InitialBudget07, SUM(gl.InitialBudget08) AS InitialBudget08, SUM(gl.InitialBudget09) AS InitialBudget09, SUM(gl.InitialBudget10) AS InitialBudget10, SUM(gl.InitialBudget11) AS InitialBudget11, SUM(gl.InitialBudget12) AS InitialBudget12, + SUM(gl.InitialProjection01) AS InitialProjection01, SUM(gl.InitialProjection02) AS InitialProjection02, SUM(gl.InitialProjection03) AS InitialProjection03, SUM(gl.InitialProjection04) AS InitialProjection04, SUM(gl.InitialProjection05) AS InitialProjection05, SUM(gl.InitialProjection06) AS InitialProjection06, SUM(gl.InitialProjection07) AS InitialProjection07, SUM(gl.InitialProjection08) AS InitialProjection08, SUM(gl.InitialProjection09) AS InitialProjection09, SUM(gl.InitialProjection10) AS InitialProjection10, SUM(gl.InitialProjection11) AS InitialProjection11, SUM(gl.InitialProjection12) AS InitialProjection12 + FROM fp.GeneralLedger gl + JOIN #FilterByDepartment ft ON ft.DepartmentID = gl.DepartmentID + INNER JOIN [fw].[DimAccount] a ON gl.AccountID = a.AccountID + WHERE gl.BudgetConfigID = @BudgetConfigID + AND gl.APEModelSectionID in (@Deduction) + AND a.OBModelSectionName = 'Deductions - Reimbursement' + GROUP BY gl.BudgetConfigID, gl.EntityGroupConfigID, gl.EntityID, a.OBPayorGroupID, a.PatientClassID, gl.APEModelSectionID + + + + INSERT INTO #ReimbursementGL( + BudgetConfigID, EntityGroupConfigID, EntityID, PayorGroupID, PatientClassID, + + InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, + InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, + + InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, + InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12, + + InitialBudgetNetAsPercentOfCharge01, InitialBudgetNetAsPercentOfCharge02, InitialBudgetNetAsPercentOfCharge03, InitialBudgetNetAsPercentOfCharge04, + InitialBudgetNetAsPercentOfCharge05, InitialBudgetNetAsPercentOfCharge06, InitialBudgetNetAsPercentOfCharge07, InitialBudgetNetAsPercentOfCharge08, + InitialBudgetNetAsPercentOfCharge09, InitialBudgetNetAsPercentOfCharge10, InitialBudgetNetAsPercentOfCharge11, InitialBudgetNetAsPercentOfCharge12, + + InitialProjectionNetAsPercentOfCharge01, InitialProjectionNetAsPercentOfCharge02, InitialProjectionNetAsPercentOfCharge03, InitialProjectionNetAsPercentOfCharge04, + InitialProjectionNetAsPercentOfCharge05, InitialProjectionNetAsPercentOfCharge06, InitialProjectionNetAsPercentOfCharge07, InitialProjectionNetAsPercentOfCharge08, + InitialProjectionNetAsPercentOfCharge09, InitialProjectionNetAsPercentOfCharge10, InitialProjectionNetAsPercentOfCharge11, InitialProjectionNetAsPercentOfCharge12 + ) + SELECT DISTINCT r.BudgetConfigID, r.EntityGroupConfigID, r.EntityID, r.PayorGroupID, r.PatientClassID, + r.InitialBudget01, r.InitialBudget02, r.InitialBudget03, r.InitialBudget04, r.InitialBudget05, r.InitialBudget06, r.InitialBudget07, r.InitialBudget08, r.InitialBudget09, r.InitialBudget10, r.InitialBudget11, r.InitialBudget12, + r.InitialProjection01, r.InitialProjection02, r.InitialProjection03, r.InitialProjection04, r.InitialProjection05, r.InitialProjection06, r.InitialProjection07, r.InitialProjection08, r.InitialProjection09, r.InitialProjection10, r.InitialProjection11, r.InitialProjection12, + + --InitialBudgetNetAsPercentOfCharge + -- %ofCharge = NetReimbursement/revenue = (revenue - deduction) / revenue + CASE WHEN r.InitialBudget01 IS NULL OR r.InitialBudget01 = 0 THEN 0 WHEN d.InitialBudget01 IS NULL THEN 1 + ELSE (r.InitialBudget01 - d.InitialBudget01) / r.InitialBudget01 END AS InitialBudgetNetAsPercentOfCharge01, + CASE WHEN r.InitialBudget02 IS NULL OR r.InitialBudget02 = 0 THEN 0 WHEN d.InitialBudget02 IS NULL THEN 1 + ELSE (r.InitialBudget02 - d.InitialBudget02) / r.InitialBudget02 END AS InitialBudgetNetAsPercentOfCharge02, + CASE WHEN r.InitialBudget03 IS NULL OR r.InitialBudget03 = 0 THEN 0 WHEN d.InitialBudget03 IS NULL THEN 1 + ELSE (r.InitialBudget03 - d.InitialBudget03) / r.InitialBudget03 END AS InitialBudgetNetAsPercentOfCharge03, + CASE WHEN r.InitialBudget04 IS NULL OR r.InitialBudget04 = 0 THEN 0 WHEN d.InitialBudget04 IS NULL THEN 1 + ELSE (r.InitialBudget04 - d.InitialBudget04) / r.InitialBudget04 END AS InitialBudgetNetAsPercentOfCharge04, + CASE WHEN r.InitialBudget05 IS NULL OR r.InitialBudget05 = 0 THEN 0 WHEN d.InitialBudget05 IS NULL THEN 1 + ELSE (r.InitialBudget05 - d.InitialBudget05) / r.InitialBudget05 END AS InitialBudgetNetAsPercentOfCharge05, + CASE WHEN r.InitialBudget06 IS NULL OR r.InitialBudget06 = 0 THEN 0 WHEN d.InitialBudget06 IS NULL THEN 1 + ELSE (r.InitialBudget06 - d.InitialBudget06) / r.InitialBudget06 END AS InitialBudgetNetAsPercentOfCharge06, + CASE WHEN r.InitialBudget07 IS NULL OR r.InitialBudget07 = 0 THEN 0 WHEN d.InitialBudget07 IS NULL THEN 1 + ELSE (r.InitialBudget07 - d.InitialBudget07) / r.InitialBudget07 END AS InitialBudgetNetAsPercentOfCharge07, + CASE WHEN r.InitialBudget08 IS NULL OR r.InitialBudget08 = 0 THEN 0 WHEN d.InitialBudget08 IS NULL THEN 1 + ELSE (r.InitialBudget08 - d.InitialBudget08) / r.InitialBudget08 END AS InitialBudgetNetAsPercentOfCharge08, + CASE WHEN r.InitialBudget09 IS NULL OR r.InitialBudget09 = 0 THEN 0 WHEN d.InitialBudget09 IS NULL THEN 1 + ELSE (r.InitialBudget09 - d.InitialBudget09) / r.InitialBudget09 END AS InitialBudgetNetAsPercentOfCharge09, + CASE WHEN r.InitialBudget10 IS NULL OR r.InitialBudget10 = 0 THEN 0 WHEN d.InitialBudget10 IS NULL THEN 1 + ELSE (r.InitialBudget10 - d.InitialBudget10) / r.InitialBudget10 END AS InitialBudgetNetAsPercentOfCharge10, + CASE WHEN r.InitialBudget11 IS NULL OR r.InitialBudget11 = 0 THEN 0 WHEN d.InitialBudget11 IS NULL THEN 1 + ELSE (r.InitialBudget11 - d.InitialBudget11) / r.InitialBudget11 END AS InitialBudgetNetAsPercentOfCharge11, + CASE WHEN r.InitialBudget12 IS NULL OR r.InitialBudget12 = 0 THEN 0 WHEN d.InitialBudget12 IS NULL THEN 1 + ELSE (r.InitialBudget12 - d.InitialBudget12) / r.InitialBudget12 END AS InitialBudgetNetAsPercentOfCharge12, + --InitialProjectionNetAsPercentOfCharge + CASE WHEN r.InitialProjection01 IS NULL OR r.InitialProjection01 = 0 THEN 0 WHEN d.InitialProjection01 IS NULL THEN 1 + ELSE (r.InitialProjection01 - d.InitialProjection01) / r.InitialProjection01 END AS InitialProjectionNetAsPercentOfCharge01, + CASE WHEN r.InitialProjection02 IS NULL OR r.InitialProjection02 = 0 THEN 0 WHEN d.InitialProjection02 IS NULL THEN 1 + ELSE (r.InitialProjection02 - d.InitialProjection02) / r.InitialProjection02 END AS InitialProjectionNetAsPercentOfCharge02, + CASE WHEN r.InitialProjection03 IS NULL OR r.InitialProjection03 = 0 THEN 0 WHEN d.InitialProjection03 IS NULL THEN 1 + ELSE (r.InitialProjection03 - d.InitialProjection03) / r.InitialProjection03 END AS InitialProjectionNetAsPercentOfCharge03, + CASE WHEN r.InitialProjection04 IS NULL OR r.InitialProjection04 = 0 THEN 0 WHEN d.InitialProjection04 IS NULL THEN 1 + ELSE (r.InitialProjection04 - d.InitialProjection04) / r.InitialProjection04 END AS InitialProjectionNetAsPercentOfCharge04, + CASE WHEN r.InitialProjection05 IS NULL OR r.InitialProjection05 = 0 THEN 0 WHEN d.InitialProjection05 IS NULL THEN 1 + ELSE (r.InitialProjection05 - d.InitialProjection05) / r.InitialProjection05 END AS InitialProjectionNetAsPercentOfCharge05, + CASE WHEN r.InitialProjection06 IS NULL OR r.InitialProjection06 = 0 THEN 0 WHEN d.InitialProjection06 IS NULL THEN 1 + ELSE (r.InitialProjection06 - d.InitialProjection06) / r.InitialProjection06 END AS InitialProjectionNetAsPercentOfCharge06, + CASE WHEN r.InitialProjection07 IS NULL OR r.InitialProjection07 = 0 THEN 0 WHEN d.InitialProjection07 IS NULL THEN 1 + ELSE (r.InitialProjection07 - d.InitialProjection07) / r.InitialProjection07 END AS InitialProjectionNetAsPercentOfCharge07, + CASE WHEN r.InitialProjection08 IS NULL OR r.InitialProjection08 = 0 THEN 0 WHEN d.InitialProjection08 IS NULL THEN 1 + ELSE (r.InitialProjection08 - d.InitialProjection08) / r.InitialProjection08 END AS InitialProjectionNetAsPercentOfCharge08, + CASE WHEN r.InitialProjection09 IS NULL OR r.InitialProjection09 = 0 THEN 0 WHEN d.InitialProjection09 IS NULL THEN 1 + ELSE (r.InitialProjection09 - d.InitialProjection09) / r.InitialProjection09 END AS InitialProjectionNetAsPercentOfCharge09, + CASE WHEN r.InitialProjection10 IS NULL OR r.InitialProjection10 = 0 THEN 0 WHEN d.InitialProjection10 IS NULL THEN 1 + ELSE (r.InitialProjection10 - d.InitialProjection10) / r.InitialProjection10 END AS InitialProjectionNetAsPercentOfCharge10, + CASE WHEN r.InitialProjection11 IS NULL OR r.InitialProjection11 = 0 THEN 0 WHEN d.InitialProjection11 IS NULL THEN 1 + ELSE (r.InitialProjection11 - d.InitialProjection11) / r.InitialProjection11 END AS InitialProjectionNetAsPercentOfCharge11, + CASE WHEN r.InitialProjection12 IS NULL OR r.InitialProjection12 = 0 THEN 0 WHEN d.InitialProjection12 IS NULL THEN 1 + ELSE (r.InitialProjection12 - d.InitialProjection12) / r.InitialProjection12 END AS InitialProjectionNetAsPercentOfCharge12 + FROM #RevenueData r + LEFT JOIN #DeductionData d ON d.BudgetConfigID = r.BudgetConfigID AND d.EntityGroupConfigID = r.EntityGroupConfigID AND d.EntityID = r.EntityID + AND d.PayorGroupID = r.PayorGroupID AND d.PatientClassID = r.PatientClassID + WHERE r.BudgetConfigID = @BudgetConfigID + + + IF (@IsDebug = 1) + BEGIN + SELECT '#FilterByDepartment', DepartmentID FROM #FilterByDepartment + SELECT '#ReimbursementGL', * FROM #ReimbursementGL + SELECT '#DeductionData', * FROM #DeductionData + SELECT '#RevenueData', * FROM #RevenueData + END ELSE + BEGIN + -- Publish + ;WITH TGT AS + ( + SELECT rgl.BudgetConfigID, rgl.EntityGroupConfigID, rgl.EntityID, rgl.PayorGroupID, rgl.PatientClassID, + [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], + [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12], + + [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], + [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12], + + [InitialBudgetNetAsPercentOfCharge01], [InitialBudgetNetAsPercentOfCharge02], [InitialBudgetNetAsPercentOfCharge03], [InitialBudgetNetAsPercentOfCharge04], + [InitialBudgetNetAsPercentOfCharge05], [InitialBudgetNetAsPercentOfCharge06], [InitialBudgetNetAsPercentOfCharge07], [InitialBudgetNetAsPercentOfCharge08], + [InitialBudgetNetAsPercentOfCharge09], [InitialBudgetNetAsPercentOfCharge10], [InitialBudgetNetAsPercentOfCharge11], [InitialBudgetNetAsPercentOfCharge12], + + [InitialProjectionNetAsPercentOfCharge01], [InitialProjectionNetAsPercentOfCharge02], [InitialProjectionNetAsPercentOfCharge03], [InitialProjectionNetAsPercentOfCharge04], + [InitialProjectionNetAsPercentOfCharge05], [InitialProjectionNetAsPercentOfCharge06], [InitialProjectionNetAsPercentOfCharge07], [InitialProjectionNetAsPercentOfCharge08], + [InitialProjectionNetAsPercentOfCharge09], [InitialProjectionNetAsPercentOfCharge10], [InitialProjectionNetAsPercentOfCharge11], [InitialProjectionNetAsPercentOfCharge12] + FROM [fp].[ReimbursementGeneralLedger] rgl + WHERE rgl.BudgetConfigID = @BudgetConfigID + ) + + MERGE TGT AS target + USING #ReimbursementGL AS src + ON ( + target.BudgetConfigID = src.BudgetConfigID + AND target.EntityGroupConfigID = src.EntityGroupConfigID + AND target.EntityID = src.EntityID + AND target.PayorGroupID = src.PayorGroupID + AND target.PatientClassID = src.PatientClassID + ) + WHEN MATCHED AND ( + target.InitialBudget01 <> src.InitialBudget01 OR + target.InitialBudget02 <> src.InitialBudget02 OR + target.InitialBudget03 <> src.InitialBudget03 OR + target.InitialBudget04 <> src.InitialBudget04 OR + target.InitialBudget05 <> src.InitialBudget05 OR + target.InitialBudget06 <> src.InitialBudget06 OR + target.InitialBudget07 <> src.InitialBudget07 OR + target.InitialBudget08 <> src.InitialBudget08 OR + target.InitialBudget09 <> src.InitialBudget09 OR + target.InitialBudget10 <> src.InitialBudget10 OR + target.InitialBudget11 <> src.InitialBudget11 OR + target.InitialBudget12 <> src.InitialBudget12 OR + + target.InitialProjection01 <> src.InitialProjection01 OR + target.InitialProjection02 <> src.InitialProjection02 OR + target.InitialProjection03 <> src.InitialProjection03 OR + target.InitialProjection04 <> src.InitialProjection04 OR + target.InitialProjection05 <> src.InitialProjection05 OR + target.InitialProjection06 <> src.InitialProjection06 OR + target.InitialProjection07 <> src.InitialProjection07 OR + target.InitialProjection08 <> src.InitialProjection08 OR + target.InitialProjection09 <> src.InitialProjection09 OR + target.InitialProjection10 <> src.InitialProjection10 OR + target.InitialProjection11 <> src.InitialProjection11 OR + target.InitialProjection12 <> src.InitialProjection12 OR + + target.InitialBudgetNetAsPercentOfCharge01 <> src.InitialBudgetNetAsPercentOfCharge01 OR + target.InitialBudgetNetAsPercentOfCharge02 <> src.InitialBudgetNetAsPercentOfCharge02 OR + target.InitialBudgetNetAsPercentOfCharge03 <> src.InitialBudgetNetAsPercentOfCharge03 OR + target.InitialBudgetNetAsPercentOfCharge04 <> src.InitialBudgetNetAsPercentOfCharge04 OR + target.InitialBudgetNetAsPercentOfCharge05 <> src.InitialBudgetNetAsPercentOfCharge05 OR + target.InitialBudgetNetAsPercentOfCharge06 <> src.InitialBudgetNetAsPercentOfCharge06 OR + target.InitialBudgetNetAsPercentOfCharge07 <> src.InitialBudgetNetAsPercentOfCharge07 OR + target.InitialBudgetNetAsPercentOfCharge08 <> src.InitialBudgetNetAsPercentOfCharge08 OR + target.InitialBudgetNetAsPercentOfCharge09 <> src.InitialBudgetNetAsPercentOfCharge09 OR + target.InitialBudgetNetAsPercentOfCharge10 <> src.InitialBudgetNetAsPercentOfCharge10 OR + target.InitialBudgetNetAsPercentOfCharge11 <> src.InitialBudgetNetAsPercentOfCharge11 OR + target.InitialBudgetNetAsPercentOfCharge12 <> src.InitialBudgetNetAsPercentOfCharge12 OR + + target.InitialProjectionNetAsPercentOfCharge01 <> src.InitialProjectionNetAsPercentOfCharge01 OR + target.InitialProjectionNetAsPercentOfCharge02 <> src.InitialProjectionNetAsPercentOfCharge02 OR + target.InitialProjectionNetAsPercentOfCharge03 <> src.InitialProjectionNetAsPercentOfCharge03 OR + target.InitialProjectionNetAsPercentOfCharge04 <> src.InitialProjectionNetAsPercentOfCharge04 OR + target.InitialProjectionNetAsPercentOfCharge05 <> src.InitialProjectionNetAsPercentOfCharge05 OR + target.InitialProjectionNetAsPercentOfCharge06 <> src.InitialProjectionNetAsPercentOfCharge06 OR + target.InitialProjectionNetAsPercentOfCharge07 <> src.InitialProjectionNetAsPercentOfCharge07 OR + target.InitialProjectionNetAsPercentOfCharge08 <> src.InitialProjectionNetAsPercentOfCharge08 OR + target.InitialProjectionNetAsPercentOfCharge09 <> src.InitialProjectionNetAsPercentOfCharge09 OR + target.InitialProjectionNetAsPercentOfCharge10 <> src.InitialProjectionNetAsPercentOfCharge10 OR + target.InitialProjectionNetAsPercentOfCharge11 <> src.InitialProjectionNetAsPercentOfCharge11 OR + target.InitialProjectionNetAsPercentOfCharge12 <> src.InitialProjectionNetAsPercentOfCharge12 + ) + THEN + UPDATE SET target.InitialBudget01 = src.InitialBudget01, + target.InitialBudget02 = src.InitialBudget02, + target.InitialBudget03 = src.InitialBudget03, + target.InitialBudget04 = src.InitialBudget04, + target.InitialBudget05 = src.InitialBudget05, + target.InitialBudget06 = src.InitialBudget06, + target.InitialBudget07 = src.InitialBudget07, + target.InitialBudget08 = src.InitialBudget08, + target.InitialBudget09 = src.InitialBudget09, + target.InitialBudget10 = src.InitialBudget10, + target.InitialBudget11 = src.InitialBudget11, + target.InitialBudget12 = src.InitialBudget12, + + target.InitialProjection01 = src.InitialProjection01, + target.InitialProjection02 = src.InitialProjection02, + target.InitialProjection03 = src.InitialProjection03, + target.InitialProjection04 = src.InitialProjection04, + target.InitialProjection05 = src.InitialProjection05, + target.InitialProjection06 = src.InitialProjection06, + target.InitialProjection07 = src.InitialProjection07, + target.InitialProjection08 = src.InitialProjection08, + target.InitialProjection09 = src.InitialProjection09, + target.InitialProjection10 = src.InitialProjection10, + target.InitialProjection11 = src.InitialProjection11, + target.InitialProjection12 = src.InitialProjection12, + + target.InitialBudgetNetAsPercentOfCharge01 = src.InitialBudgetNetAsPercentOfCharge01, + target.InitialBudgetNetAsPercentOfCharge02 = src.InitialBudgetNetAsPercentOfCharge02, + target.InitialBudgetNetAsPercentOfCharge03 = src.InitialBudgetNetAsPercentOfCharge03, + target.InitialBudgetNetAsPercentOfCharge04 = src.InitialBudgetNetAsPercentOfCharge04, + target.InitialBudgetNetAsPercentOfCharge05 = src.InitialBudgetNetAsPercentOfCharge05, + target.InitialBudgetNetAsPercentOfCharge06 = src.InitialBudgetNetAsPercentOfCharge06, + target.InitialBudgetNetAsPercentOfCharge07 = src.InitialBudgetNetAsPercentOfCharge07, + target.InitialBudgetNetAsPercentOfCharge08 = src.InitialBudgetNetAsPercentOfCharge08, + target.InitialBudgetNetAsPercentOfCharge09 = src.InitialBudgetNetAsPercentOfCharge09, + target.InitialBudgetNetAsPercentOfCharge10 = src.InitialBudgetNetAsPercentOfCharge10, + target.InitialBudgetNetAsPercentOfCharge11 = src.InitialBudgetNetAsPercentOfCharge11, + target.InitialBudgetNetAsPercentOfCharge12 = src.InitialBudgetNetAsPercentOfCharge12, + + target.InitialProjectionNetAsPercentOfCharge01 = src.InitialProjectionNetAsPercentOfCharge01, + target.InitialProjectionNetAsPercentOfCharge02 = src.InitialProjectionNetAsPercentOfCharge02, + target.InitialProjectionNetAsPercentOfCharge03 = src.InitialProjectionNetAsPercentOfCharge03, + target.InitialProjectionNetAsPercentOfCharge04 = src.InitialProjectionNetAsPercentOfCharge04, + target.InitialProjectionNetAsPercentOfCharge05 = src.InitialProjectionNetAsPercentOfCharge05, + target.InitialProjectionNetAsPercentOfCharge06 = src.InitialProjectionNetAsPercentOfCharge06, + target.InitialProjectionNetAsPercentOfCharge07 = src.InitialProjectionNetAsPercentOfCharge07, + target.InitialProjectionNetAsPercentOfCharge08 = src.InitialProjectionNetAsPercentOfCharge08, + target.InitialProjectionNetAsPercentOfCharge09 = src.InitialProjectionNetAsPercentOfCharge09, + target.InitialProjectionNetAsPercentOfCharge10 = src.InitialProjectionNetAsPercentOfCharge10, + target.InitialProjectionNetAsPercentOfCharge11 = src.InitialProjectionNetAsPercentOfCharge11, + target.InitialProjectionNetAsPercentOfCharge12 = src.InitialProjectionNetAsPercentOfCharge12; + + END +END +GO + + +--------------------------------------------- + +-- fp.procSamplePercentOfChargeData +CREATE PROCEDURE [fp].[procSamplePercentOfChargeData] + @EntityGroupConfigID INT, + @MonthsLoaded INT, + @IsAnnualized BIT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table + ** 2 2021-03-25 NN Jazz-14123 Remove null joins + ** 7 2022-09-07 NT JAZZ-40956 Include all gross charges accounts and not just variable revenue accounts when calculating percent of charges + ** 8 12-01-2022 MY JAZZ-46294 Deductions not calculating when department is set to flex off Total Gross Charges + ** 9 03-17-2022 MY JAZZ-51319 Deductions % Not Calculating Appropriately + ** 10 05-09-2023 NT JAZZ-54290 Data restructure changes to use new fp.GeneralLedger table + ** 11 09-13-2023 MY JAZZ-60768 Add EGC Filter to Update clause + ** 12 01-18-2024 NT JAZZ-64955 Add ROUND() function to mitigate really large numbers during final division calculation to prevent arithmetic overflow + ** 13 08-28-2024 MD JAZZ-75083 Pull precision from fp.SystemSetting for ROUND() functions + *************************************************************/ + + IF OBJECT_ID('tempdb..#dollars') IS NOT NULL DROP TABLE #dollars + IF OBJECT_ID('tempdb..#deductions') IS NOT NULL DROP TABLE #deductions + IF OBJECT_ID('tempdb..#grossCharges') IS NOT NULL DROP TABLE #grossCharges + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#calculatedPercentOfCharge') IS NOT NULL DROP TABLE #calculatedPercentOfCharge + IF OBJECT_ID('tempdb..#totals') IS NOT NULL DROP TABLE #totals + IF OBJECT_ID('tempdb..#variability') IS NOT NULL DROP TABLE #variability + + --JAZZ-75083 + --Allows for setting of custom precision as defined by the customer + --DO NOT UPDATE THIS SETTING WITHOUT EXPRESS PERMISSION FROM THE CUSTOMER + --We need to make sure the client is okay with the loss in precision before updating this setting + DECLARE @Precision INT = 8 + SELECT @Precision = CAST(Value AS INT) from fp.SystemSetting + where Name = 'Set custom precision for select stored procedures' + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + -- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[GeneralLedger] d WITH (READUNCOMMITTED) + WHERE d.EntityGroupConfigID = @EntityGroupConfigID + END + DECLARE @BudgetConfigID INT + SELECT @BudgetConfigID = BudgetConfigID + FROM fp.EntityGroupConfig egc INNER JOIN fp.BudgetConfig b on egc.BudgetConfigGUID = b.BudgetConfigGUID + WHERE egc.EntityGroupConfigID = @EntityGroupConfigID + DECLARE @IncludeAllGrossChargesFlag BIT = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting WHERE Name = 'Include All Gross Charges Accounts' AND BudgetConfigID = @BudgetConfigID), 0) + -- Important note: Revenue and Deductions both are either 100% variable or 100% fixed, they do not contain mixed variability like other sections + -- so we only care about variable deductions. Revenue we want to pull regardless of variability assuming the 'Include All Gross Charges Accounts' is enabled + -- Calculate the totals at the department/account/variability level. In the event baseline is set to annualized, only pull in months loaded + -- if the baseline is not annualized, we pull in everything. + -- For projection, we will only look at months loaded (aka actuals) regardless of baseline setting + SELECT + fgl.DepartmentID, + fgl.AccountID, + fgl.VariabilityID, + ( + SUM(CASE WHEN 1 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget01 ELSE 0 END + + CASE WHEN 2 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget02 ELSE 0 END + + CASE WHEN 3 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget03 ELSE 0 END + + CASE WHEN 4 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget04 ELSE 0 END + + CASE WHEN 5 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget05 ELSE 0 END + + CASE WHEN 6 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget06 ELSE 0 END + + CASE WHEN 7 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget07 ELSE 0 END + + CASE WHEN 8 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget08 ELSE 0 END + + CASE WHEN 9 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget09 ELSE 0 END + + CASE WHEN 10 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget10 ELSE 0 END + + CASE WHEN 11 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget11 ELSE 0 END + + CASE WHEN 12 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget12 ELSE 0 END)) AS SampledBudgetTotal, + (SUM(CASE WHEN 1 <= @MonthsLoaded THEN SampledProjection01 ELSE 0 END + + CASE WHEN 2 <= @MonthsLoaded THEN SampledProjection02 ELSE 0 END + + CASE WHEN 3 <= @MonthsLoaded THEN SampledProjection03 ELSE 0 END + + CASE WHEN 4 <= @MonthsLoaded THEN SampledProjection04 ELSE 0 END + + CASE WHEN 5 <= @MonthsLoaded THEN SampledProjection05 ELSE 0 END + + CASE WHEN 6 <= @MonthsLoaded THEN SampledProjection06 ELSE 0 END + + CASE WHEN 7 <= @MonthsLoaded THEN SampledProjection07 ELSE 0 END + + CASE WHEN 8 <= @MonthsLoaded THEN SampledProjection08 ELSE 0 END + + CASE WHEN 9 <= @MonthsLoaded THEN SampledProjection09 ELSE 0 END + + CASE WHEN 10 <= @MonthsLoaded THEN SampledProjection10 ELSE 0 END + + CASE WHEN 11 <= @MonthsLoaded THEN SampledProjection11 ELSE 0 END + + CASE WHEN 12 <= @MonthsLoaded THEN SampledProjection12 ELSE 0 END )) AS SampledProjectionTotal + INTO #totals + FROM [fp].[GeneralLedger] fgl + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fgl.DepartmentID + WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID + GROUP BY + fgl.DepartmentID, + fgl.AccountID, + fgl.VariabilityID + -- Pull the variability from the variability tables, this is used in the legacy way of calculating Percent of Charge where we only look at the variable portion of the dollars + -- In the new way, we do not use this table as we want all of the dollars for Revenue whether it's fixed or variable. + SELECT fav.DepartmentID, + fav.AccountID, + MAX(FixedPercentage) AS FixedPercentage + INTO #variability + FROM [fp].[FactAccountVariability] fav + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fav.DepartmentID + INNER JOIN [fp].[EntityGroupConfig] egc ON + egc.EntityGroupConfigID = @EntityGroupConfigID + AND egc.EntityGroupConfigGUID = fav.EntityGroupConfigGUID + GROUP BY fav.DepartmentID, fav.AccountID + -- We need to recalculate the dollars on the fly because InitialBudget/Projection Dollars will get flexed, otherwise if we don't + -- the rate will rise each time. + SELECT + fgl.DepartmentID, + fgl.AccountID, + fgl.EntityGroupConfigID, + fgl.APEModelSectionID, + fgl.VariabilityID, --will apply variability filter later when splitting into deductions and gross charges + CASE WHEN @IncludeAllGrossChargesFlag = 1 THEN total.SampledBudgetTotal ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledBudgetTotal END AS BudgetDollarTotal, + CASE WHEN @IncludeAllGrossChargesFlag = 1 THEN total.SampledProjectionTotal ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionTotal END AS ProjectionDollarTotal + INTO #dollars + FROM [fp].[GeneralLedger] fgl + INNER JOIN #totals AS total ON total.DepartmentID = fgl.DepartmentID + AND total.AccountID = fgl.AccountID + AND total.VariabilityID = fgl.VariabilityID + LEFT JOIN #variability fv ON fv.DepartmentID = fgl.DepartmentID + AND fv.AccountID = fgl.AccountID + WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID + + -- Find the deductions baseline for variable budget data by department & account + SELECT fgl.DepartmentID, fgl.AccountID, SUM(fgl.BudgetDollarTotal) AS TotalDeductionsBudget, SUM(fgl.ProjectionDollarTotal) AS TotalDeductionsProjection + INTO #deductions + FROM #dollars fgl + WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID + AND fgl.APEModelSectionID = 4 -- Deductions + AND (@IncludeAllGrossChargesFlag = 1 OR fgl.VariabilityID = 2) + GROUP BY fgl.DepartmentID, fgl.AccountID + + -- Find the gross charges baseline for budget data by department. + -- Please note that all accounts (variable & fixed) are included if FF (@IncludeAllGrossChargesFlag) is ON + SELECT fgl.DepartmentID, ROUND((SUM(BudgetDollarTotal)),@Precision,0) AS TotalGrossChargesBudget, ROUND((SUM(ProjectionDollarTotal)),@Precision,0) AS TotalGrossChargesProjection + INTO #grossCharges + FROM #dollars fgl + WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID + AND fgl.APEModelSectionID = 1 -- Revenue + AND (@IncludeAllGrossChargesFlag = 1 OR fgl.VariabilityID = 2) + GROUP BY fgl.DepartmentID + + SELECT GeneralLedgerID, + CASE WHEN c.TotalGrossChargesBudget = 0 THEN 0 ELSE d.TotalDeductionsBudget / c.TotalGrossChargesBudget END AS CalculatedBudget, + CASE WHEN c.TotalGrossChargesProjection = 0 THEN 0 ELSE d.TotalDeductionsProjection / c.TotalGrossChargesProjection END as CalculatedProjection + INTO #calculatedPercentOfCharge + FROM [fp].[GeneralLedger] fgl + INNER JOIN #deductions d ON d.DepartmentID = fgl.DepartmentID AND d.AccountID = fgl.AccountID + INNER JOIN #grossCharges c ON d.DepartmentID = c.DepartmentID + WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID + IF @IsDebug = 1 + BEGIN + SELECT 'Include All Gross Charges Accounts', @IncludeAllGrossChargesFlag + SELECT '#totals', DepartmentID, AccountID, VariabilityID, SampledBudgetTotal, SampledProjectionTotal FROM #totals + SELECT '#variability', DepartmentID, AccountID, FixedPercentage FROM #variability + SELECT '#dollars', DepartmentID, AccountID, EntityGroupConfigID, APEModelSectionID, VariabilityID, BudgetDollarTotal, ProjectionDollarTotal FROM #dollars + SELECT '#deductions', DepartmentID, AccountID, TotalDeductionsBudget, TotalDeductionsProjection FROM #deductions + SELECT '#grossCharges', DepartmentID, TotalGrossChargesBudget, TotalGrossChargesProjection FROM #grossCharges + SELECT '#calculatedPercentOfCharge', GeneralLedgerID, CalculatedBudget, CalculatedProjection, 'TotalDeductions / TotalGrossCharges' AS Calculation FROM #calculatedPercentOfCharge + END ELSE + BEGIN + -- Use already imported values for percentage of charge + UPDATE fgl + SET + InitialBudgetPercentOfCharge01 = i.Value01, + InitialBudgetPercentOfCharge02 = i.Value02, + InitialBudgetPercentOfCharge03 = i.Value03, + InitialBudgetPercentOfCharge04 = i.Value04, + InitialBudgetPercentOfCharge05 = i.Value05, + InitialBudgetPercentOfCharge06 = i.Value06, + InitialBudgetPercentOfCharge07 = i.Value07, + InitialBudgetPercentOfCharge08 = i.Value08, + InitialBudgetPercentOfCharge09 = i.Value09, + InitialBudgetPercentOfCharge10 = i.Value10, + InitialBudgetPercentOfCharge11 = i.Value11, + InitialBudgetPercentOfCharge12 = i.Value12 + FROM [fp].[GeneralLedger] fgl + INNER JOIN fp.PercentageOfChargeImport i ON i.BudgetConfigID = fgl.BudgetConfigID + AND i.DepartmentID = fgl.DepartmentID + AND i.AccountID = fgl.AccountID + AND i.TimeClassID = 2 + WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID + + UPDATE fgl + SET + InitialProjectionPercentOfCharge01 = IIF(1 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value01), + InitialProjectionPercentOfCharge02 = IIF(2 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value02), + InitialProjectionPercentOfCharge03 = IIF(3 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value03), + InitialProjectionPercentOfCharge04 = IIF(4 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value04), + InitialProjectionPercentOfCharge05 = IIF(5 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value05), + InitialProjectionPercentOfCharge06 = IIF(6 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value06), + InitialProjectionPercentOfCharge07 = IIF(7 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value07), + InitialProjectionPercentOfCharge08 = IIF(8 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value08), + InitialProjectionPercentOfCharge09 = IIF(9 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value09), + InitialProjectionPercentOfCharge10 = IIF(10 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value10), + InitialProjectionPercentOfCharge11 = IIF(11 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value11), + InitialProjectionPercentOfCharge12 = IIF(12 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value12) + FROM [fp].[GeneralLedger] fgl + INNER JOIN fp.PercentageOfChargeImport i ON i.BudgetConfigID = fgl.BudgetConfigID + AND i.DepartmentID = fgl.DepartmentID + AND i.AccountID = fgl.AccountID + AND i.TimeClassID = 12 + LEFT JOIN #calculatedPercentOfCharge c ON fgl.GeneralLedgerID = c.GeneralLedgerID + WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID + -- Percent of charge is calculated by taking the Sum(Deduction Baseline) / Sum(Gross Charge Baseline) + UPDATE fgl + SET + InitialBudgetPercentOfCharge01 = c.CalculatedBudget, + InitialBudgetPercentOfCharge02 = c.CalculatedBudget, + InitialBudgetPercentOfCharge03 = c.CalculatedBudget, + InitialBudgetPercentOfCharge04 = c.CalculatedBudget, + InitialBudgetPercentOfCharge05 = c.CalculatedBudget, + InitialBudgetPercentOfCharge06 = c.CalculatedBudget, + InitialBudgetPercentOfCharge07 = c.CalculatedBudget, + InitialBudgetPercentOfCharge08 = c.CalculatedBudget, + InitialBudgetPercentOfCharge09 = c.CalculatedBudget, + InitialBudgetPercentOfCharge10 = c.CalculatedBudget, + InitialBudgetPercentOfCharge11 = c.CalculatedBudget, + InitialBudgetPercentOfCharge12 = c.CalculatedBudget + FROM [fp].[GeneralLedger] fgl + INNER JOIN #calculatedPercentOfCharge c ON fgl.GeneralLedgerID = c.GeneralLedgerID + LEFT JOIN fp.PercentageOfChargeImport i ON i.BudgetConfigID = fgl.BudgetConfigID + AND i.DepartmentID = fgl.DepartmentID + AND i.AccountID = fgl.AccountID + AND i.TimeClassID = 2 + WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID + AND i.BudgetConfigID IS NULL + + UPDATE fgl + SET + InitialProjectionPercentOfCharge01 = c.CalculatedProjection, + InitialProjectionPercentOfCharge02 = c.CalculatedProjection, + InitialProjectionPercentOfCharge03 = c.CalculatedProjection, + InitialProjectionPercentOfCharge04 = c.CalculatedProjection, + InitialProjectionPercentOfCharge05 = c.CalculatedProjection, + InitialProjectionPercentOfCharge06 = c.CalculatedProjection, + InitialProjectionPercentOfCharge07 = c.CalculatedProjection, + InitialProjectionPercentOfCharge08 = c.CalculatedProjection, + InitialProjectionPercentOfCharge09 = c.CalculatedProjection, + InitialProjectionPercentOfCharge10 = c.CalculatedProjection, + InitialProjectionPercentOfCharge11 = c.CalculatedProjection, + InitialProjectionPercentOfCharge12 = c.CalculatedProjection + FROM [fp].[GeneralLedger] fgl + INNER JOIN #calculatedPercentOfCharge c ON fgl.GeneralLedgerID = c.GeneralLedgerID + LEFT JOIN fp.PercentageOfChargeImport i ON i.BudgetConfigID = fgl.BudgetConfigID + AND i.DepartmentID = fgl.DepartmentID + AND i.AccountID = fgl.AccountID + AND i.TimeClassID = 12 + WHERE fgl.EntityGroupConfigID = @EntityGroupConfigID + AND i.BudgetConfigID IS NULL + + END +END +GO + + +--------------------------------------------- + +-- fp.procSamplePercentOfChargeData_InitialPlan +CREATE PROCEDURE [fp].[procSamplePercentOfChargeData_InitialPlan] + @BudgetConfigGUID UNIQUEIDENTIFIER, + @BudgetConfigID SMALLINT, + @EntityGroupConfigIDs VARCHAR(MAX), + @MonthsLoaded INT, + @IsAnnualized BIT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2024-05-27 MV JAZZ-71177 Create SP for Initial plan method baseed on [fp].[procSamplePercentOfChargeData] + ** 2 08-28-2024 MD JAZZ-75083 Pull precision from fp.SystemSetting for ROUND() functions + *************************************************************/ + + IF OBJECT_ID('tempdb..#dollars') IS NOT NULL DROP TABLE #dollars + IF OBJECT_ID('tempdb..#deductions') IS NOT NULL DROP TABLE #deductions + IF OBJECT_ID('tempdb..#grossCharges') IS NOT NULL DROP TABLE #grossCharges + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#calculatedPercentOfCharge') IS NOT NULL DROP TABLE #calculatedPercentOfCharge + IF OBJECT_ID('tempdb..#totals') IS NOT NULL DROP TABLE #totals + IF OBJECT_ID('tempdb..#variability') IS NOT NULL DROP TABLE #variability + IF OBJECT_ID('tempdb..#FilterByEntityGroupConfig') IS NOT NULL DROP TABLE #FilterByEntityGroupConfig + + --JAZZ-75083 + --Allows for setting of custom precision as defined by the customer + --DO NOT UPDATE THIS SETTING WITHOUT EXPRESS PERMISSION FROM THE CUSTOMER + --We need to make sure the client is okay with the loss in precision before updating this setting + DECLARE @Precision INT = 8 + SELECT @Precision = CAST(Value AS INT) from fp.SystemSetting + where Name = 'Set custom precision for select stored procedures' + + CREATE TABLE #FilterByEntityGroupConfig (EntityGroupConfigID int) + + IF @EntityGroupConfigIDs IS NOT NULL AND @EntityGroupConfigIDs <> '' + BEGIN + INSERT INTO #FilterByEntityGroupConfig (EntityGroupConfigID) + SELECT TRIM([value]) AS EntityGroupConfigID FROM STRING_SPLIT(@EntityGroupConfigIDs, ',' ) + END + ELSE BEGIN + INSERT INTO #FilterByEntityGroupConfig (EntityGroupConfigID) + SELECT EntityGroupConfigID FROM [fp].[EntityGroupConfig] + WHERE BudgetConfigGUID = @BudgetConfigGUID + END + + + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + -- If the FilterByDepartment is empty, pass all dept to avoid duplicate statements + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[GeneralLedger] d WITH (READUNCOMMITTED) + INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = d.EntityGroupConfigID + WHERE d.BudgetConfigID = @BudgetConfigID + END + + DECLARE @IncludeAllGrossChargesFlag BIT = ISNULL((SELECT Value FROM fp.viewBudgetConfigSetting WHERE Name = 'Include All Gross Charges Accounts' AND BudgetConfigID = @BudgetConfigID), 0) + -- Important note: Revenue and Deductions both are either 100% variable or 100% fixed, they do not contain mixed variability like other sections + -- so we only care about variable deductions. Revenue we want to pull regardless of variability assuming the 'Include All Gross Charges Accounts' is enabled + -- Calculate the totals at the department/account/variability level. In the event baseline is set to annualized, only pull in months loaded + -- if the baseline is not annualized, we pull in everything. + -- For projection, we will only look at months loaded (aka actuals) regardless of baseline setting + SELECT + fgl.DepartmentID, + fgl.AccountID, + fgl.VariabilityID, + ( + SUM(CASE WHEN 1 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget01 ELSE 0 END + + CASE WHEN 2 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget02 ELSE 0 END + + CASE WHEN 3 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget03 ELSE 0 END + + CASE WHEN 4 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget04 ELSE 0 END + + CASE WHEN 5 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget05 ELSE 0 END + + CASE WHEN 6 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget06 ELSE 0 END + + CASE WHEN 7 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget07 ELSE 0 END + + CASE WHEN 8 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget08 ELSE 0 END + + CASE WHEN 9 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget09 ELSE 0 END + + CASE WHEN 10 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget10 ELSE 0 END + + CASE WHEN 11 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget11 ELSE 0 END + + CASE WHEN 12 <= @MonthsLoaded OR @IsAnnualized = 0 THEN SampledBudget12 ELSE 0 END)) AS SampledBudgetTotal, + (SUM(CASE WHEN 1 <= @MonthsLoaded THEN SampledProjection01 ELSE 0 END + + CASE WHEN 2 <= @MonthsLoaded THEN SampledProjection02 ELSE 0 END + + CASE WHEN 3 <= @MonthsLoaded THEN SampledProjection03 ELSE 0 END + + CASE WHEN 4 <= @MonthsLoaded THEN SampledProjection04 ELSE 0 END + + CASE WHEN 5 <= @MonthsLoaded THEN SampledProjection05 ELSE 0 END + + CASE WHEN 6 <= @MonthsLoaded THEN SampledProjection06 ELSE 0 END + + CASE WHEN 7 <= @MonthsLoaded THEN SampledProjection07 ELSE 0 END + + CASE WHEN 8 <= @MonthsLoaded THEN SampledProjection08 ELSE 0 END + + CASE WHEN 9 <= @MonthsLoaded THEN SampledProjection09 ELSE 0 END + + CASE WHEN 10 <= @MonthsLoaded THEN SampledProjection10 ELSE 0 END + + CASE WHEN 11 <= @MonthsLoaded THEN SampledProjection11 ELSE 0 END + + CASE WHEN 12 <= @MonthsLoaded THEN SampledProjection12 ELSE 0 END )) AS SampledProjectionTotal + INTO #totals + FROM [fp].[GeneralLedger] fgl + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fgl.DepartmentID + INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = fgl.EntityGroupConfigID + WHERE fgl.BudgetConfigID = @BudgetConfigID + GROUP BY + fgl.DepartmentID, + fgl.AccountID, + fgl.VariabilityID + -- Pull the variability from the variability tables, this is used in the legacy way of calculating Percent of Charge where we only look at the variable portion of the dollars + -- In the new way, we do not use this table as we want all of the dollars for Revenue whether it's fixed or variable. + SELECT fav.DepartmentID, + fav.AccountID, + MAX(FixedPercentage) AS FixedPercentage + INTO #variability + FROM [fp].[FactAccountVariability] fav + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = fav.DepartmentID + INNER JOIN [fp].[EntityGroupConfig] egc ON + egc.EntityGroupConfigGUID = fav.EntityGroupConfigGUID + INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = egc.EntityGroupConfigID + GROUP BY fav.DepartmentID, fav.AccountID + -- We need to recalculate the dollars on the fly because InitialBudget/Projection Dollars will get flexed, otherwise if we don't + -- the rate will rise each time. + SELECT + fgl.DepartmentID, + fgl.AccountID, + fgl.EntityGroupConfigID, + fgl.APEModelSectionID, + fgl.VariabilityID, --will apply variability filter later when splitting into deductions and gross charges + CASE WHEN @IncludeAllGrossChargesFlag = 1 THEN total.SampledBudgetTotal ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledBudgetTotal END AS BudgetDollarTotal, + CASE WHEN @IncludeAllGrossChargesFlag = 1 THEN total.SampledProjectionTotal ELSE COALESCE(1 - fv.FixedPercentage, 0) * total.SampledProjectionTotal END AS ProjectionDollarTotal + INTO #dollars + FROM [fp].[GeneralLedger] fgl + INNER JOIN #totals AS total ON total.DepartmentID = fgl.DepartmentID + AND total.AccountID = fgl.AccountID + AND total.VariabilityID = fgl.VariabilityID + INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = fgl.EntityGroupConfigID + LEFT JOIN #variability fv ON fv.DepartmentID = fgl.DepartmentID + AND fv.AccountID = fgl.AccountID + WHERE fgl.BudgetConfigID = @BudgetConfigID + + -- Find the deductions baseline for variable budget data by department & account + SELECT fgl.DepartmentID, fgl.AccountID, SUM(fgl.BudgetDollarTotal) AS TotalDeductionsBudget, SUM(fgl.ProjectionDollarTotal) AS TotalDeductionsProjection + INTO #deductions + FROM #dollars fgl + INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = fgl.EntityGroupConfigID + WHERE + fgl.APEModelSectionID = 4 -- Deductions + AND (@IncludeAllGrossChargesFlag = 1 OR fgl.VariabilityID = 2) + GROUP BY fgl.DepartmentID, fgl.AccountID + + -- Find the gross charges baseline for budget data by department. + -- Please note that all accounts (variable & fixed) are included if FF (@IncludeAllGrossChargesFlag) is ON + SELECT fgl.DepartmentID, ROUND((SUM(BudgetDollarTotal)),@Precision,0) AS TotalGrossChargesBudget, ROUND((SUM(ProjectionDollarTotal)),@Precision,0) AS TotalGrossChargesProjection + INTO #grossCharges + FROM #dollars fgl + WHERE + fgl.APEModelSectionID = 1 -- Revenue + AND (@IncludeAllGrossChargesFlag = 1 OR fgl.VariabilityID = 2) + GROUP BY fgl.DepartmentID + + SELECT GeneralLedgerID, + CASE WHEN c.TotalGrossChargesBudget = 0 THEN 0 ELSE d.TotalDeductionsBudget / c.TotalGrossChargesBudget END AS CalculatedBudget, + CASE WHEN c.TotalGrossChargesProjection = 0 THEN 0 ELSE d.TotalDeductionsProjection / c.TotalGrossChargesProjection END as CalculatedProjection + INTO #calculatedPercentOfCharge + FROM [fp].[GeneralLedger] fgl + INNER JOIN #deductions d ON d.DepartmentID = fgl.DepartmentID AND d.AccountID = fgl.AccountID + INNER JOIN #grossCharges c ON d.DepartmentID = c.DepartmentID + INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = fgl.EntityGroupConfigID + WHERE fgl.BudgetConfigID = @BudgetConfigID + IF @IsDebug = 1 + BEGIN + SELECT 'Include All Gross Charges Accounts', @IncludeAllGrossChargesFlag + SELECT '#totals', DepartmentID, AccountID, VariabilityID, SampledBudgetTotal, SampledProjectionTotal FROM #totals + SELECT '#variability', DepartmentID, AccountID, FixedPercentage FROM #variability + SELECT '#dollars', DepartmentID, AccountID, EntityGroupConfigID, APEModelSectionID, VariabilityID, BudgetDollarTotal, ProjectionDollarTotal FROM #dollars + SELECT '#deductions', DepartmentID, AccountID, TotalDeductionsBudget, TotalDeductionsProjection FROM #deductions + SELECT '#grossCharges', DepartmentID, TotalGrossChargesBudget, TotalGrossChargesProjection FROM #grossCharges + SELECT '#calculatedPercentOfCharge', GeneralLedgerID, CalculatedBudget, CalculatedProjection, 'TotalDeductions / TotalGrossCharges' AS Calculation FROM #calculatedPercentOfCharge + END ELSE + BEGIN + -- Use already imported values for percentage of charge + UPDATE fgl + SET + InitialBudgetPercentOfCharge01 = i.Value01, + InitialBudgetPercentOfCharge02 = i.Value02, + InitialBudgetPercentOfCharge03 = i.Value03, + InitialBudgetPercentOfCharge04 = i.Value04, + InitialBudgetPercentOfCharge05 = i.Value05, + InitialBudgetPercentOfCharge06 = i.Value06, + InitialBudgetPercentOfCharge07 = i.Value07, + InitialBudgetPercentOfCharge08 = i.Value08, + InitialBudgetPercentOfCharge09 = i.Value09, + InitialBudgetPercentOfCharge10 = i.Value10, + InitialBudgetPercentOfCharge11 = i.Value11, + InitialBudgetPercentOfCharge12 = i.Value12 + FROM [fp].[GeneralLedger] fgl + INNER JOIN fp.PercentageOfChargeImport i ON i.BudgetConfigID = fgl.BudgetConfigID + AND i.DepartmentID = fgl.DepartmentID + AND i.AccountID = fgl.AccountID + AND i.TimeClassID = 2 + INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = fgl.EntityGroupConfigID + WHERE fgl.BudgetConfigID = @BudgetConfigID + + UPDATE fgl + SET + InitialProjectionPercentOfCharge01 = IIF(1 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value01), + InitialProjectionPercentOfCharge02 = IIF(2 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value02), + InitialProjectionPercentOfCharge03 = IIF(3 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value03), + InitialProjectionPercentOfCharge04 = IIF(4 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value04), + InitialProjectionPercentOfCharge05 = IIF(5 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value05), + InitialProjectionPercentOfCharge06 = IIF(6 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value06), + InitialProjectionPercentOfCharge07 = IIF(7 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value07), + InitialProjectionPercentOfCharge08 = IIF(8 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value08), + InitialProjectionPercentOfCharge09 = IIF(9 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value09), + InitialProjectionPercentOfCharge10 = IIF(10 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value10), + InitialProjectionPercentOfCharge11 = IIF(11 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value11), + InitialProjectionPercentOfCharge12 = IIF(12 <= @MonthsLoaded, ISNULL(c.CalculatedProjection, 0), i.Value12) + FROM [fp].[GeneralLedger] fgl + INNER JOIN fp.PercentageOfChargeImport i ON i.BudgetConfigID = fgl.BudgetConfigID + AND i.DepartmentID = fgl.DepartmentID + AND i.AccountID = fgl.AccountID + AND i.TimeClassID = 12 + INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = fgl.EntityGroupConfigID + LEFT JOIN #calculatedPercentOfCharge c ON fgl.GeneralLedgerID = c.GeneralLedgerID + WHERE fgl.BudgetConfigID = @BudgetConfigID + -- Percent of charge is calculated by taking the Sum(Deduction Baseline) / Sum(Gross Charge Baseline) + UPDATE fgl + SET + InitialBudgetPercentOfCharge01 = c.CalculatedBudget, + InitialBudgetPercentOfCharge02 = c.CalculatedBudget, + InitialBudgetPercentOfCharge03 = c.CalculatedBudget, + InitialBudgetPercentOfCharge04 = c.CalculatedBudget, + InitialBudgetPercentOfCharge05 = c.CalculatedBudget, + InitialBudgetPercentOfCharge06 = c.CalculatedBudget, + InitialBudgetPercentOfCharge07 = c.CalculatedBudget, + InitialBudgetPercentOfCharge08 = c.CalculatedBudget, + InitialBudgetPercentOfCharge09 = c.CalculatedBudget, + InitialBudgetPercentOfCharge10 = c.CalculatedBudget, + InitialBudgetPercentOfCharge11 = c.CalculatedBudget, + InitialBudgetPercentOfCharge12 = c.CalculatedBudget + FROM [fp].[GeneralLedger] fgl + INNER JOIN #calculatedPercentOfCharge c ON fgl.GeneralLedgerID = c.GeneralLedgerID + INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = fgl.EntityGroupConfigID + LEFT JOIN fp.PercentageOfChargeImport i ON i.BudgetConfigID = fgl.BudgetConfigID + AND i.DepartmentID = fgl.DepartmentID + AND i.AccountID = fgl.AccountID + AND i.TimeClassID = 2 + WHERE fgl.BudgetConfigID = @BudgetConfigID + AND i.BudgetConfigID IS NULL + + UPDATE fgl + SET + InitialProjectionPercentOfCharge01 = c.CalculatedProjection, + InitialProjectionPercentOfCharge02 = c.CalculatedProjection, + InitialProjectionPercentOfCharge03 = c.CalculatedProjection, + InitialProjectionPercentOfCharge04 = c.CalculatedProjection, + InitialProjectionPercentOfCharge05 = c.CalculatedProjection, + InitialProjectionPercentOfCharge06 = c.CalculatedProjection, + InitialProjectionPercentOfCharge07 = c.CalculatedProjection, + InitialProjectionPercentOfCharge08 = c.CalculatedProjection, + InitialProjectionPercentOfCharge09 = c.CalculatedProjection, + InitialProjectionPercentOfCharge10 = c.CalculatedProjection, + InitialProjectionPercentOfCharge11 = c.CalculatedProjection, + InitialProjectionPercentOfCharge12 = c.CalculatedProjection + FROM [fp].[GeneralLedger] fgl + INNER JOIN #calculatedPercentOfCharge c ON fgl.GeneralLedgerID = c.GeneralLedgerID + INNER JOIN #FilterByEntityGroupConfig fegc ON fegc.EntityGroupConfigID = fgl.EntityGroupConfigID + LEFT JOIN fp.PercentageOfChargeImport i ON i.BudgetConfigID = fgl.BudgetConfigID + AND i.DepartmentID = fgl.DepartmentID + AND i.AccountID = fgl.AccountID + AND i.TimeClassID = 12 + WHERE fgl.BudgetConfigID = @BudgetConfigID + AND i.BudgetConfigID IS NULL + + END +END +GO + + +--------------------------------------------- + +-- fp.procSampleReimbursementChargesClearData +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-03-29 MD JAZZ-33794 Initial +***************************************************************/ + +CREATE PROCEDURE fp.procSampleReimbursementChargesClearData + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + DECLARE @ChunkCount INT; + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 400000 END; + DECLARE @r INT; + + -- delete existing data (have to do value tables first so that we still have EntityGroupConfigID) + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) frcb + FROM [fp].[FactReimbursementChargesBudget] frcb + INNER JOIN [fp].[FactReimbursementCharges] frc on frcb.ReimbursementChargesID = frc.ReimbursementChargesID + WHERE frc.BudgetConfigID = @BudgetConfigID + + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) frcp + FROM [fp].[FactReimbursementChargesProjection] frcp + INNER JOIN [fp].[FactReimbursementCharges] frc on frcp.ReimbursementChargesID = frc.ReimbursementChargesID + WHERE frc.BudgetConfigID = @BudgetConfigID + + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) frch + FROM [fp].[FactReimbursementChargesHistory] frch + INNER JOIN [fp].[FactReimbursementCharges] frc on frch.ReimbursementChargesID = frc.ReimbursementChargesID + WHERE frc.BudgetConfigID = @BudgetConfigID + + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) frc + FROM [fp].[FactReimbursementCharges] frc + WHERE frc.BudgetConfigID = @BudgetConfigID + + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + +END +GO + + +--------------------------------------------- + +-- fp.procSampleReimbursementEncounterClearData +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-03-29 MD JAZZ-33794 Initial +***************************************************************/ + +CREATE PROCEDURE fp.procSampleReimbursementEncounterClearData + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + DECLARE @ChunkCount INT; + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 400000 END; + DECLARE @r INT; + + -- delete existing data (have to do value tables first so that we still have EntityGroupConfigID) + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) frcb + FROM [fp].[FactReimbursementEncounterBudget] frcb + INNER JOIN [fp].[FactReimbursementEncounter] frc on frcb.ReimbursementEncounterID = frc.ReimbursementEncounterID + WHERE frc.BudgetConfigID = @BudgetConfigID + + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) frcp + FROM [fp].[FactReimbursementEncounterProjection] frcp + INNER JOIN [fp].[FactReimbursementEncounter] frc on frcp.ReimbursementEncounterID = frc.ReimbursementEncounterID + WHERE frc.BudgetConfigID = @BudgetConfigID + + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) frch + FROM [fp].[FactReimbursementEncounterHistory] frch + INNER JOIN [fp].[FactReimbursementEncounter] frc on frch.ReimbursementEncounterID = frc.ReimbursementEncounterID + WHERE frc.BudgetConfigID = @BudgetConfigID + + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) frc + FROM [fp].[FactReimbursementEncounter] frc + WHERE frc.BudgetConfigID = @BudgetConfigID + + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + +END +GO + + +--------------------------------------------- + +-- fp.procSampleServiceLineEncounterClearData +CREATE PROCEDURE [fp].[procSampleServiceLineEncounterClearData] + @BudgetConfigGUID uniqueidentifier, + @EntityGroupConfigID int, + @CurrentFiscalYearID SMALLINT, + @SourceFiscalYearID SMALLINT, + @SourceTimeClassID TINYINT, + @IsRemoveEntityConfig BIT = 0 +AS +BEGIN +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2021-02-25 lrenadesouza JAZZ-12907 Added rolling deletes for all tables +** 2 2023-01-17 bkrehl JAZZ-48267 New data structure and only delete unneeded records +** 3 2023-06-30 mdeboer JAZZ-55672 Remove adjustment delete logic, add remove entity config logic +** 4 2024-08-30 bwells JAZZ-75594 Reset historical values to zero +***************************************************************/ + IF OBJECT_ID('tempdb..#toDelete') IS NOT NULL DROP TABLE #toDelete + + DECLARE @ChunkCount INT; + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 400000 END + DECLARE @r INT; + + DECLARE @IsAgeCohortDisabled BIT; + SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + WHERE IsHidden = 1 AND BudgetConfigGUID = @BudgetConfigGUID AND LevelID = 'AgeCohortID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + DECLARE @IsMedicalSurgicalDisabled BIT; + SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + WHERE IsHidden = 1 AND BudgetConfigGUID = @BudgetConfigGUID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + + CREATE TABLE #toDelete (ServiceLineEncounterID INT) + + IF @IsRemoveEntityConfig = 1 + BEGIN + INSERT INTO #toDelete with (tablock) (ServiceLineEncounterID) + SELECT ServiceLineEncounterID + FROM fp.ServiceLineEncounter + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + ELSE + BEGIN + INSERT INTO #toDelete with (tablock) (ServiceLineEncounterID) + SELECT ServiceLineEncounterID FROM + ( + SELECT DISTINCT ServiceLineEncounterID, EntityID, PatientClassID, ServiceLineID, ServiceLineRollupID, MedicalSurgicalID, AgeCohortID--, --leave MedicalSurgicalID and AgeCohortID as they are in the tables + --DepartmentID, PayorID, PayorGroupID + FROM [fp].[ServiceLineEncounter] + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND IsNew = 0 + ) sle LEFT JOIN + (SELECT EntityID, PatientClassID, sl.ServiceLineID, sl.RollupID AS ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE MedicalSurgicalID END AS MedicalSurgicalID, + CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE AgeCohortID END AS AgeCohortID FROM + [int].[FactServiceLine] fsl inner join fw.DimServiceLine sl on fsl.ServiceLineID = sl.ServiceLineID + WHERE + ((fsl.FiscalYearID = @SourceFiscalYearID AND fsl.TimeclassID = @SourceTimeClassID) -- baseline + OR (fsl.FiscalYearID = @CurrentFiscalYearID) -- projection (current year actuals) + OR (fsl.FiscalYearID = @CurrentFiscalYearID - 1 AND fsl.TimeClassID = 1)) -- prior year, actual & budget + AND fsl.IsDeleted = 0 + AND fsl.FiscalMonthID != 0 + ) src + ON sle.EntityID = src.EntityID + AND sle.PatientClassID = src.PatientClassID + AND sle.ServiceLineID = src.ServiceLineID + AND sle.MedicalSurgicalID = src.MedicalSurgicalID + AND sle.AgeCohortID = src.AgeCohortID + WHERE + src.EntityID IS NULL + END + + -- We need to wipe the history so that the adjustments can be re-applied aferwards + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) fsch FROM [fp].[ServiceLineEncounterChangeHistory] fsch INNER JOIN [fp].[ServiceLineEncounter] fs on fs.ServiceLineEncounterID = fsch.ServiceLineEncounterID WHERE fs.EntityGroupConfigID = @EntityGroupConfigID; + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + + -- delete existing data (have to do value tables first so that we still have EntityGroupConfigID) + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) sleh FROM [fp].[ServiceLineEncounterHistory] sleh INNER JOIN #toDelete tt on sleh.ServiceLineEncounterID=tt.ServiceLineEncounterID + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) sle FROM [fp].[ServiceLineEncounter] sle INNER JOIN #toDelete tt on sle.ServiceLineEncounterID=tt.ServiceLineEncounterID + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + IF @IsRemoveEntityConfig = 0 + BEGIN + -- Reset all values to 0 + UPDATE + sle + SET + SampledBudget01 = 0, + SampledBudget02 = 0, + SampledBudget03 = 0, + SampledBudget04 = 0, + SampledBudget05 = 0, + SampledBudget06 = 0, + SampledBudget07 = 0, + SampledBudget08 = 0, + SampledBudget09 = 0, + SampledBudget10 = 0, + SampledBudget11 = 0, + SampledBudget12 = 0, + SampledProjection01 = 0, + SampledProjection02 = 0, + SampledProjection03 = 0, + SampledProjection04 = 0, + SampledProjection05 = 0, + SampledProjection06 = 0, + SampledProjection07 = 0, + SampledProjection08 = 0, + SampledProjection09 = 0, + SampledProjection10 = 0, + SampledProjection11 = 0, + SampledProjection12 = 0, + InitialBudget01 = 0, + InitialBudget02 = 0, + InitialBudget03 = 0, + InitialBudget04 = 0, + InitialBudget05 = 0, + InitialBudget06 = 0, + InitialBudget07 = 0, + InitialBudget08 = 0, + InitialBudget09 = 0, + InitialBudget10 = 0, + InitialBudget11 = 0, + InitialBudget12 = 0, + InitialProjection01 = 0, + InitialProjection02 = 0, + InitialProjection03 = 0, + InitialProjection04 = 0, + InitialProjection05 = 0, + InitialProjection06 = 0, + InitialProjection07 = 0, + InitialProjection08 = 0, + InitialProjection09 = 0, + InitialProjection10 = 0, + InitialProjection11 = 0, + InitialProjection12 = 0, + TargetAdjusted01 = 0, + TargetAdjusted02 = 0, + TargetAdjusted03 = 0, + TargetAdjusted04 = 0, + TargetAdjusted05 = 0, + TargetAdjusted06 = 0, + TargetAdjusted07 = 0, + TargetAdjusted08 = 0, + TargetAdjusted09 = 0, + TargetAdjusted10 = 0, + TargetAdjusted11 = 0, + TargetAdjusted12 = 0, + BudgetAdjusted01 = 0, + BudgetAdjusted02 = 0, + BudgetAdjusted03 = 0, + BudgetAdjusted04 = 0, + BudgetAdjusted05 = 0, + BudgetAdjusted06 = 0, + BudgetAdjusted07 = 0, + BudgetAdjusted08 = 0, + BudgetAdjusted09 = 0, + BudgetAdjusted10 = 0, + BudgetAdjusted11 = 0, + BudgetAdjusted12 = 0, + ProjectionAdjusted01 = 0, + ProjectionAdjusted02 = 0, + ProjectionAdjusted03 = 0, + ProjectionAdjusted04 = 0, + ProjectionAdjusted05 = 0, + ProjectionAdjusted06 = 0, + ProjectionAdjusted07 = 0, + ProjectionAdjusted08 = 0, + ProjectionAdjusted09 = 0, + ProjectionAdjusted10 = 0, + ProjectionAdjusted11 = 0, + ProjectionAdjusted12 = 0 + FROM + [fp].[ServiceLineEncounter] sle + WHERE sle.EntityGroupConfigID = @EntityGroupConfigID + + UPDATE + sleh + SET + ActualYTDValue01 = 0, + ActualYTDValue02 = 0, + ActualYTDValue03 = 0, + ActualYTDValue04 = 0, + ActualYTDValue05 = 0, + ActualYTDValue06 = 0, + ActualYTDValue07 = 0, + ActualYTDValue08 = 0, + ActualYTDValue09 = 0, + ActualYTDValue10 = 0, + ActualYTDValue11 = 0, + ActualYTDValue12 = 0, + PriorYearActualValue01 = 0, + PriorYearActualValue02 = 0, + PriorYearActualValue03 = 0, + PriorYearActualValue04 = 0, + PriorYearActualValue05 = 0, + PriorYearActualValue06 = 0, + PriorYearActualValue07 = 0, + PriorYearActualValue08 = 0, + PriorYearActualValue09 = 0, + PriorYearActualValue10 = 0, + PriorYearActualValue11 = 0, + PriorYearActualValue12 = 0, + CurrentYearBudget01 = 0, + CurrentYearBudget02 = 0, + CurrentYearBudget03 = 0, + CurrentYearBudget04 = 0, + CurrentYearBudget05 = 0, + CurrentYearBudget06 = 0, + CurrentYearBudget07 = 0, + CurrentYearBudget08 = 0, + CurrentYearBudget09 = 0, + CurrentYearBudget10 = 0, + CurrentYearBudget11 = 0, + CurrentYearBudget12 = 0 + FROM + [fp].[ServiceLineEncounterHistory] sleh + INNER JOIN fp.ServiceLineEncounter sle ON sleh.ServiceLineEncounterID = sle.ServiceLineEncounterID + WHERE sle.EntityGroupConfigID = @EntityGroupConfigID + END +END; +GO + + +--------------------------------------------- + +-- fp.procSampleServiceLineEncounterDimensionality +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-12-12 DM JAZZ-46455 Age Cohort and Medical/Seurgical is linked to Section Setup checkboxes +** 2 2023-01-17 bkrehl JAZZ-48267 New data structure and only delete unneeded records +** 3 2023-01-31 MD JAZZ-48529 Update non-DS client sampling for encounters +** 4 2023-05-30 JB JAZZ-49631 Section set up update for non-DS clients for encounters +***************************************************************/ +CREATE PROCEDURE [fp].[procSampleServiceLineEncounterDimensionality] + @BudgetConfigID int, + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @SourceFiscalYearID smallint, + @SourceTimeClassID tinyint +AS +BEGIN + + DECLARE @IsPayorDisabled BIT; + SELECT @IsPayorDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'PayorID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + DECLARE @IsPayorGroupDisabled BIT; + SELECT @IsPayorGroupDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'PayorGroupID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + DECLARE @IsDepartmentDisabled BIT; + SELECT @IsDepartmentDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'DepartmentID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + DECLARE @IsAgeCohortDisabled BIT; + SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'AgeCohortID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + DECLARE @IsMedicalSurgicalDisabled BIT; + SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + INSERT INTO + [fp].[ServiceLineEncounter] ([BudgetConfigID], [EntityGroupConfigID], [EntityID], + [PatientClassID], [ServiceLineID], [ServiceLineRollupID], [MedicalSurgicalID], [AgeCohortID], + [PayorID], [PayorGroupID], [DepartmentID], [UnitTypeID], + BudgetLockType, BudgetLockFlag, TargetLockType, TargetLockFlag, ProjectionLockType, ProjectionLockFlag, IsNew) + SELECT DISTINCT + @BudgetConfigID, + @EntityGroupConfigID, + fsl.EntityID, + fsl.PatientClassID, + fsl.ServiceLineID, + dsl.RollupID AS ServiceLineRollupID, + fsl.MedicalSurgicalID, -- if this is hidden per settings, the select from int.FactServiceLine already has this set to 0 if needed + fsl.AgeCohortID, -- same as MedicalSurgicalID + fsl.PayorID, + fsl.PayorGroupID, + fsl.DepartmentID, + 140 AS UnitTypeID, + 0, 0, 0, 0, 0, 0, 0 + FROM( + SELECT EntityID, PatientClassID, sl.ServiceLineID, sl.RollupID AS ServiceLineRollupID, + CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE MedicalSurgicalID END AS MedicalSurgicalID, + CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE AgeCohortID END AS AgeCohortID, + CASE WHEN @IsPayorDisabled = 1 THEN 0 ELSE PayorID END AS PayorID, + CASE WHEN @IsPayorGroupDisabled = 1 THEN 0 ELSE PayorGroupID END AS PayorGroupID, + CASE WHEN @IsDepartmentDisabled = 1 THEN 0 ELSE DepartmentID END AS DepartmentID + FROM [int].[FactServiceLine] fsl + INNER JOIN fw.DimServiceLine sl on fsl.ServiceLineID = sl.ServiceLineID + WHERE + ((fsl.FiscalYearID = @SourceFiscalYearID AND fsl.TimeclassID = @SourceTimeClassID) -- baseline + OR (fsl.FiscalYearID = @CurrentFiscalYearID) -- projection (current year actuals) + OR (fsl.FiscalYearID = @CurrentFiscalYearID - 1 AND fsl.TimeClassID = 1)) -- prior year, actual & budget + AND fsl.IsDeleted = 0 + AND fsl.FiscalMonthID != 0 + ) fsl + + INNER JOIN [fw].[DimServiceLine] dsl ON fsl.ServiceLineID = dsl.ServiceLineID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON fsl.EntityID = egcm.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc ON egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + LEFT JOIN ( + -- Check for existing dimensionality so we only insert needed dimensionality + SELECT DISTINCT EntityID, PatientClassID, ServiceLineID, MedicalSurgicalID, AgeCohortID, PayorID, PayorGroupID, DepartmentID + FROM [fp].[ServiceLineEncounter] + WHERE EntityGroupConfigID = @EntityGroupConfigID + ) existing + ON fsl.EntityID = existing.EntityID + AND fsl.PatientClassID = existing.PatientClassID + AND fsl.ServiceLineID = existing.ServiceLineID + AND fsl.MedicalSurgicalID = existing.MedicalSurgicalID + AND fsl.AgeCohortID = existing.AgeCohortID + AND fsl.PayorID = existing.PayorID + AND fsl.PayorGroupID = existing.PayorGroupID + AND fsl.DepartmentID = existing.DepartmentID + WHERE + egc.EntityGroupConfigID = @EntityGroupConfigID + AND existing.EntityID IS NULL +END +GO + + +--------------------------------------------- + +-- fp.procSampleServiceLineEncounterHistoricalData +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-12-12 DM JAZZ-46455 Age Cohort and Medical/Seurgical is linked to Section Setup checkboxes +** 2 2023-01-17 bkrehl JAZZ-48267 New data structure +** 3 2023-01-31 MD JAZZ-48529 Update non-DS client sampling for encounters +** 4 2023-05-30 JB JAZZ-49631 Section set up update for non-DS clients for encounters +***************************************************************/ +CREATE PROCEDURE [fp].[procSampleServiceLineEncounterHistoricalData] + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @MonthsLoaded int +AS +BEGIN + + -- Reset all values to 0 + UPDATE + sleh + SET + PriorYearActualValue01 = 0, + PriorYearActualValue02 = 0, + PriorYearActualValue03 = 0, + PriorYearActualValue04 = 0, + PriorYearActualValue05 = 0, + PriorYearActualValue06 = 0, + PriorYearActualValue07 = 0, + PriorYearActualValue08 = 0, + PriorYearActualValue09 = 0, + PriorYearActualValue10 = 0, + PriorYearActualValue11 = 0, + PriorYearActualValue12 = 0, + ActualYTDValue01 = 0, + ActualYTDValue02 = 0, + ActualYTDValue03 = 0, + ActualYTDValue04 = 0, + ActualYTDValue05 = 0, + ActualYTDValue06 = 0, + ActualYTDValue07 = 0, + ActualYTDValue08 = 0, + ActualYTDValue09 = 0, + ActualYTDValue10 = 0, + ActualYTDValue11 = 0, + ActualYTDValue12 = 0, + CurrentYearBudget01 = 0, + CurrentYearBudget02 = 0, + CurrentYearBudget03 = 0, + CurrentYearBudget04 = 0, + CurrentYearBudget05 = 0, + CurrentYearBudget06 = 0, + CurrentYearBudget07 = 0, + CurrentYearBudget08 = 0, + CurrentYearBudget09 = 0, + CurrentYearBudget10 = 0, + CurrentYearBudget11 = 0, + CurrentYearBudget12 = 0 + FROM [fp].[ServiceLineEncounterHistory] sleh INNER JOIN [fp].[ServiceLineEncounter] sle on sle.ServiceLineEncounterID = sleh.ServiceLineEncounterID + WHERE sle.EntityGroupConfigID = @EntityGroupConfigID + + -- Add any new records as needed + INSERT INTO [fp].[ServiceLineEncounterHistory]([ServiceLineEncounterID]) + SELECT sle.[ServiceLineEncounterID] + FROM [fp].[ServiceLineEncounter] sle LEFT JOIN [fp].[ServiceLineEncounterHistory] sleh on sle.ServiceLineEncounterID = sleh.ServiceLineEncounterID + WHERE sle.EntityGroupConfigID = @EntityGroupConfigID AND sleh.ServiceLineEncounterID IS NULL + + DECLARE @IsPayorDisabled BIT; + SELECT @IsPayorDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'PayorID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + DECLARE @IsPayorGroupDisabled BIT; + SELECT @IsPayorGroupDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'PayorGroupID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + DECLARE @IsDepartmentDisabled BIT; + SELECT @IsDepartmentDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'DepartmentID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + DECLARE @IsAgeCohortDisabled BIT; + SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'AgeCohortID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + DECLARE @IsMedicalSurgicalDisabled BIT; + SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + + + + -- set all of the values for prior year actual + UPDATE + sleh + SET + PriorYearActualValue01 = ISNULL(Month01, 0), + PriorYearActualValue02 = ISNULL(Month02, 0), + PriorYearActualValue03 = ISNULL(Month03, 0), + PriorYearActualValue04 = ISNULL(Month04, 0), + PriorYearActualValue05 = ISNULL(Month05, 0), + PriorYearActualValue06 = ISNULL(Month06, 0), + PriorYearActualValue07 = ISNULL(Month07, 0), + PriorYearActualValue08 = ISNULL(Month08, 0), + PriorYearActualValue09 = ISNULL(Month09, 0), + PriorYearActualValue10 = ISNULL(Month10, 0), + PriorYearActualValue11 = ISNULL(Month11, 0), + PriorYearActualValue12 = ISNULL(Month12, 0) + FROM + [fp].[ServiceLineEncounterHistory] sleh + INNER JOIN [fp].[ServiceLineEncounter] sle ON sleh.ServiceLineEncounterID = sle.ServiceLineEncounterID + INNER JOIN ( + SELECT * + FROM ( + SELECT + EntityID, + PatientClassID, + ServiceLineID, + CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE MedicalSurgicalID END AS MedicalSurgicalID, + CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE AgeCohortID END AS AgeCohortID, + CASE WHEN @IsPayorDisabled = 1 THEN 0 ELSE PayorGroupID END AS PayorGroupID, + CASE WHEN @IsPayorGroupDisabled = 1 THEN 0 ELSE PayorID END AS PayorID, + CASE WHEN @IsDepartmentDisabled = 1 THEN 0 ELSE DepartmentID END AS DepartmentID, + fm.MonthColumnName, + SUM(Value) as Value + FROM [int].[FactServiceLine] src + INNER JOIN [fw].[dimFiscalMonth] fm ON src.FiscalMonthID = fm.FiscalMonthID + WHERE + FiscalYearID = (@CurrentFiscalYearID - 1) + AND TimeClassID = 1 + AND src.FiscalMonthID != 0 + GROUP BY + EntityID, + PatientClassID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + PayorGroupID, + PayorID, + DepartmentID, + fm.MonthColumnName + ) data + PIVOT (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ) src + ON sle.EntityID = src.EntityID + AND sle.PatientClassID = src.PatientClassID + AND sle.ServiceLineID = src.ServiceLineID + AND sle.AgeCohortID = src.AgeCohortID + AND sle.MedicalSurgicalID = src.MedicalSurgicalID + AND sle.PayorGroupID = src.PayorGroupID + AND sle.PayorID = src.PayorID + AND sle.DepartmentID = src.DepartmentID + WHERE + sle.EntityGroupConfigID = @EntityGroupConfigID + + + -- set all of the values for current year actual/annualized + UPDATE + sleh + SET + ActualYTDValue01 = ISNULL(Month01, 0), + ActualYTDValue02 = ISNULL(Month02, 0), + ActualYTDValue03 = ISNULL(Month03, 0), + ActualYTDValue04 = ISNULL(Month04, 0), + ActualYTDValue05 = ISNULL(Month05, 0), + ActualYTDValue06 = ISNULL(Month06, 0), + ActualYTDValue07 = ISNULL(Month07, 0), + ActualYTDValue08 = ISNULL(Month08, 0), + ActualYTDValue09 = ISNULL(Month09, 0), + ActualYTDValue10 = ISNULL(Month10, 0), + ActualYTDValue11 = ISNULL(Month11, 0), + ActualYTDValue12 = ISNULL(Month12, 0) + FROM + [fp].[ServiceLineEncounterHistory] sleh + INNER JOIN [fp].[ServiceLineEncounter] sle ON sleh.ServiceLineEncounterID = sle.ServiceLineEncounterID + INNER JOIN ( + SELECT * + FROM ( + SELECT + EntityID, + PatientClassID, + ServiceLineID, + CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE MedicalSurgicalID END AS MedicalSurgicalID, + CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE AgeCohortID END AS AgeCohortID, + CASE WHEN @IsPayorDisabled = 1 THEN 0 ELSE PayorGroupID END AS PayorGroupID, + CASE WHEN @IsPayorGroupDisabled = 1 THEN 0 ELSE PayorID END AS PayorID, + CASE WHEN @IsDepartmentDisabled = 1 THEN 0 ELSE DepartmentID END AS DepartmentID, + fm.MonthColumnName, + SUM(Value) as Value + FROM [int].[FactServiceLine] src + INNER JOIN [fw].[dimFiscalMonth] fm ON src.FiscalMonthID = fm.FiscalMonthID + WHERE + FiscalYearID = @CurrentFiscalYearID + AND TimeClassID = 1 + AND src.FiscalMonthID != 0 + AND fm.SortOrder <= @MonthsLoaded + GROUP BY + EntityID, + PatientClassID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + PayorGroupID, + PayorID, + DepartmentID, + fm.MonthColumnName + ) data + PIVOT (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ) src + ON sle.EntityID = src.EntityID + AND sle.PatientClassID = src.PatientClassID + AND sle.ServiceLineID = src.ServiceLineID + AND sle.AgeCohortID = src.AgeCohortID + AND sle.MedicalSurgicalID = src.MedicalSurgicalID + AND sle.PayorGroupID = src.PayorGroupID + AND sle.PayorID = src.PayorID + AND sle.DepartmentID = src.DepartmentID + WHERE + sle.EntityGroupConfigID = @EntityGroupConfigID + + + -- set all of the values for current year budget + UPDATE + sleh + SET + CurrentYearBudget01 = ISNULL(Month01, 0), + CurrentYearBudget02 = ISNULL(Month02, 0), + CurrentYearBudget03 = ISNULL(Month03, 0), + CurrentYearBudget04 = ISNULL(Month04, 0), + CurrentYearBudget05 = ISNULL(Month05, 0), + CurrentYearBudget06 = ISNULL(Month06, 0), + CurrentYearBudget07 = ISNULL(Month07, 0), + CurrentYearBudget08 = ISNULL(Month08, 0), + CurrentYearBudget09 = ISNULL(Month09, 0), + CurrentYearBudget10 = ISNULL(Month10, 0), + CurrentYearBudget11 = ISNULL(Month11, 0), + CurrentYearBudget12 = ISNULL(Month12, 0) + FROM + [fp].[ServiceLineEncounterHistory] sleh + INNER JOIN [fp].[ServiceLineEncounter] sle ON sleh.ServiceLineEncounterID = sle.ServiceLineEncounterID + INNER JOIN ( + SELECT * + FROM ( + SELECT + EntityID, + PatientClassID, + ServiceLineID, + CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE MedicalSurgicalID END AS MedicalSurgicalID, + CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE AgeCohortID END AS AgeCohortID, + CASE WHEN @IsPayorDisabled = 1 THEN 0 ELSE PayorGroupID END AS PayorGroupID, + CASE WHEN @IsPayorGroupDisabled = 1 THEN 0 ELSE PayorID END AS PayorID, + CASE WHEN @IsDepartmentDisabled = 1 THEN 0 ELSE DepartmentID END AS DepartmentID, + fm.MonthColumnName, + SUM(Value) as Value + FROM [int].[FactServiceLine] src + INNER JOIN [fw].[dimFiscalMonth] fm ON src.FiscalMonthID = fm.FiscalMonthID + WHERE + FiscalYearID = @CurrentFiscalYearID + AND TimeClassID = 2 + AND src.FiscalMonthID != 0 + GROUP BY + EntityID, + PatientClassID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + PayorGroupID, + PayorID, + DepartmentID, + fm.MonthColumnName + ) data + PIVOT (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ) src + ON sle.EntityID = src.EntityID + AND sle.PatientClassID = src.PatientClassID + AND sle.ServiceLineID = src.ServiceLineID + AND sle.AgeCohortID = src.AgeCohortID + AND sle.MedicalSurgicalID = src.MedicalSurgicalID + AND sle.PayorGroupID = src.PayorGroupID + AND sle.PayorID = src.PayorID + AND sle.DepartmentID = src.DepartmentID + WHERE + sle.EntityGroupConfigID = @EntityGroupConfigID + + +END +GO + + +--------------------------------------------- + +-- fp.procSampleServiceLineEncounterOriginalBudgetVolume +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-12-12 DM JAZZ-46455 Age Cohort and Medical/Surgical is linked to Section Setup checkboxes +** 2 2023-01-17 bkrehl JAZZ-48267 New data structure and only delete unneeded records +** 3 2023-01-31 MD JAZZ-48529 Update non-DS client sampling for encounters +** 4 2023-05-30 JB JAZZ-49631 Section set up update for non-DS clients for encounters +***************************************************************/ +CREATE PROCEDURE [fp].[procSampleServiceLineEncounterOriginalBudgetVolume] + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @SourceFiscalYearID smallint, + @SourceTimeClassID tinyint, + @MonthsLoaded int +AS +BEGIN + +DECLARE @IsAnnualized bit = (CASE WHEN @SourceFiscalYearID = @CurrentFiscalYearID AND @SourceTimeClassID = 1 THEN 1 ELSE 0 END) + +DECLARE @IsPayorDisabled BIT; + SELECT @IsPayorDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'PayorID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + DECLARE @IsPayorGroupDisabled BIT; + SELECT @IsPayorGroupDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'PayorGroupID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + DECLARE @IsDepartmentDisabled BIT; + SELECT @IsDepartmentDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'DepartmentID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + +DECLARE @IsAgeCohortDisabled BIT; +SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'AgeCohortID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + +DECLARE @IsMedicalSurgicalDisabled BIT; +SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + UPDATE sle + SET + SampledBudget01 = ISNULL(Month01, 0), + SampledBudget02 = ISNULL(Month02, 0), + SampledBudget03 = ISNULL(Month03, 0), + SampledBudget04 = ISNULL(Month04, 0), + SampledBudget05 = ISNULL(Month05, 0), + SampledBudget06 = ISNULL(Month06, 0), + SampledBudget07 = ISNULL(Month07, 0), + SampledBudget08 = ISNULL(Month08, 0), + SampledBudget09 = ISNULL(Month09, 0), + SampledBudget10 = ISNULL(Month10, 0), + SampledBudget11 = ISNULL(Month11, 0), + SampledBudget12 = ISNULL(Month12, 0) + FROM [fp].[ServiceLineEncounter] sle + INNER JOIN ( + SELECT * + FROM ( + SELECT + EntityID, + PatientClassID, + ServiceLineID, + CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE MedicalSurgicalID END AS MedicalSurgicalID, + CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE AgeCohortID END AS AgeCohortID, + CASE WHEN @IsPayorDisabled = 1 THEN 0 ELSE PayorID END AS PayorID, + CASE WHEN @IsPayorGroupDisabled = 1 THEN 0 ELSE PayorGroupID END AS PayorGroupID, + CASE WHEN @IsDepartmentDisabled = 1 THEN 0 ELSE DepartmentID END AS DepartmentID, + fm.MonthColumnName, + SUM(Value) as Value + FROM [int].[FactServiceLine] src + INNER JOIN [fw].[dimFiscalMonth] fm ON src.FiscalMonthID = fm.FiscalMonthID + WHERE + FiscalYearID = @SourceFiscalYearID + AND TimeClassID = @SourceTimeClassID + AND src.FiscalMonthID != 0 + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + GROUP BY + EntityID, + PatientClassID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + PayorGroupID, + PayorID, + DepartmentID, + fm.MonthColumnName + ) data + PIVOT (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ) src + ON sle.EntityID = src.EntityID + AND sle.PatientClassID = src.PatientClassID + AND sle.ServiceLineID = src.ServiceLineID + AND sle.AgeCohortID = src.AgeCohortID + AND sle.MedicalSurgicalID = src.MedicalSurgicalID + AND sle.PayorGroupID = src.PayorGroupID + AND sle.PayorID = src.PayorID + AND sle.DepartmentID = src.DepartmentID + WHERE + sle.EntityGroupConfigID = @EntityGroupConfigID + + + -- if the source fiscal year = current fiscal year and timeclass is actual, we need to annualize the data + IF(@IsAnnualized = 1 AND @MonthsLoaded < 12) + BEGIN + -- per stackoverflow + DECLARE @IsLeapYear BIT = (CASE WHEN (@SourceFiscalYearID % 4 = 0 AND @SourceFiscalYearID % 100 <> 0) OR @SourceFiscalYearID % 400 = 0 THEN 1 ELSE 0 END) + DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded) + DECLARE @DaysInMonthsNotLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder > @MonthsLoaded) + + UPDATE fs + SET + -- not doing month 1 because it wouldn't really make sense to annualize without at least 1 month of actual data + SampledBudget02 = CASE WHEN @MonthsLoaded < 2 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget02 END, + SampledBudget03 = CASE WHEN @MonthsLoaded < 3 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget03 END, + SampledBudget04 = CASE WHEN @MonthsLoaded < 4 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget04 END, + SampledBudget05 = CASE WHEN @MonthsLoaded < 5 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget05 END, + SampledBudget06 = CASE WHEN @MonthsLoaded < 6 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget06 END, + SampledBudget07 = CASE WHEN @MonthsLoaded < 7 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget07 END, + SampledBudget08 = CASE WHEN @MonthsLoaded < 8 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget08 END, + SampledBudget09 = CASE WHEN @MonthsLoaded < 9 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget09 END, + SampledBudget10 = CASE WHEN @MonthsLoaded < 10 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget10 END, + SampledBudget11 = CASE WHEN @MonthsLoaded < 11 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget11 END, + SampledBudget12 = CASE WHEN @MonthsLoaded < 12 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget12 END + FROM [fp].[ServiceLineEncounter] fs + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + END + + -- update the initial values to be equal to the sampled values on the dimensionality table + UPDATE + fs + SET + InitialBudget01 = SampledBudgetTotal / 12, + InitialBudget02 = SampledBudgetTotal / 12, + InitialBudget03 = SampledBudgetTotal / 12, + InitialBudget04 = SampledBudgetTotal / 12, + InitialBudget05 = SampledBudgetTotal / 12, + InitialBudget06 = SampledBudgetTotal / 12, + InitialBudget07 = SampledBudgetTotal / 12, + InitialBudget08 = SampledBudgetTotal / 12, + InitialBudget09 = SampledBudgetTotal / 12, + InitialBudget10 = SampledBudgetTotal / 12, + InitialBudget11 = SampledBudgetTotal / 12, + InitialBudget12 = SampledBudgetTotal - ((SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12)) + FROM [fp].[ServiceLineEncounter] fs + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + +END +GO + + +--------------------------------------------- + +-- fp.procSampleServiceLineEncounterOriginalProjectionVolume +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-12-12 DM JAZZ-46455 Age Cohort and Medical/Seurgical is linked to Section Setup checkboxes +** 2 2023-01-17 bkrehl JAZZ-48267 New data structure and only delete unneeded records +** 3 2023-01-31 MD JAZZ-48529 Update non-DS client sampling for encounters +** 4 2023-05-30 JB JAZZ-49631 Section set up update for non-DS clients for encounters +***************************************************************/ +CREATE PROCEDURE [fp].[procSampleServiceLineEncounterOriginalProjectionVolume] + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @MonthsLoaded int +AS +BEGIN + +IF OBJECT_ID('tempdb..#Totals') IS NOT NULL DROP TABLE #Totals + +DECLARE @IsPayorDisabled BIT; +SELECT @IsPayorDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'PayorID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + +DECLARE @IsPayorGroupDisabled BIT; +SELECT @IsPayorGroupDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'PayorGroupID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + +DECLARE @IsDepartmentDisabled BIT; +SELECT @IsDepartmentDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'DepartmentID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + +DECLARE @IsAgeCohortDisabled BIT; +SELECT @IsAgeCohortDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'AgeCohortID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + +DECLARE @IsMedicalSurgicalDisabled BIT; +SELECT @IsMedicalSurgicalDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN fp.EntityGroupConfig egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND egc.EntityGroupConfigID = @EntityGroupConfigID AND LevelID = 'MedicalSurgicalID' AND PlanSectionID = 1 AND SubSectionID = 0 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + UPDATE sle + SET + SampledProjection01 = ISNULL(Month01, 0), + SampledProjection02 = ISNULL(Month02, 0), + SampledProjection03 = ISNULL(Month03, 0), + SampledProjection04 = ISNULL(Month04, 0), + SampledProjection05 = ISNULL(Month05, 0), + SampledProjection06 = ISNULL(Month06, 0), + SampledProjection07 = ISNULL(Month07, 0), + SampledProjection08 = ISNULL(Month08, 0), + SampledProjection09 = ISNULL(Month09, 0), + SampledProjection10 = ISNULL(Month10, 0), + SampledProjection11 = ISNULL(Month11, 0), + SampledProjection12 = ISNULL(Month12, 0) + FROM [fp].[ServiceLineEncounter] sle + INNER JOIN ( + SELECT * + FROM ( + SELECT + EntityID, + PatientClassID, + ServiceLineID, + CASE WHEN @IsMedicalSurgicalDisabled = 1 THEN 0 ELSE MedicalSurgicalID END AS MedicalSurgicalID, + CASE WHEN @IsAgeCohortDisabled = 1 THEN 0 ELSE AgeCohortID END AS AgeCohortID, + CASE WHEN @IsPayorDisabled = 1 THEN 0 ELSE PayorID END AS PayorID, + CASE WHEN @IsPayorGroupDisabled = 1 THEN 0 ELSE PayorGroupID END AS PayorGroupID, + CASE WHEN @IsDepartmentDisabled = 1 THEN 0 ELSE DepartmentID END AS DepartmentID, + fm.MonthColumnName, + SUM(Value) as Value + FROM [int].[FactServiceLine] src + INNER JOIN [fw].[dimFiscalMonth] fm ON src.FiscalMonthID = fm.FiscalMonthID + WHERE + FiscalYearID = @CurrentFiscalYearID + AND TimeClassID = 1 + AND src.FiscalMonthID != 0 + AND fm.SortOrder <= @MonthsLoaded + GROUP BY + EntityID, + PatientClassID, + ServiceLineID, + AgeCohortID, + MedicalSurgicalID, + PayorGroupID, + PayorID, + DepartmentID, + fm.MonthColumnName + ) data + PIVOT (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ) src + ON sle.EntityID = src.EntityID + AND sle.PatientClassID = src.PatientClassID + AND sle.ServiceLineID = src.ServiceLineID + AND sle.AgeCohortID = src.AgeCohortID + AND sle.MedicalSurgicalID = src.MedicalSurgicalID + AND sle.PayorGroupID = src.PayorGroupID + AND sle.PayorID = src.PayorID + AND sle.DepartmentID = src.DepartmentID + WHERE + sle.EntityGroupConfigID = @EntityGroupConfigID + + + -- copy the baseline data over for months without data (month sort order > @MonthsLoaded) + -- if the baseline is current year actual YTD, then the data would already have been annualized, if not, then we don't need to annualize + UPDATE + sle + SET + SampledProjection02 = CASE WHEN @MonthsLoaded < 2 THEN SampledBudget02 ELSE SampledProjection02 END, + SampledProjection03 = CASE WHEN @MonthsLoaded < 3 THEN SampledBudget03 ELSE SampledProjection03 END, + SampledProjection04 = CASE WHEN @MonthsLoaded < 4 THEN SampledBudget04 ELSE SampledProjection04 END, + SampledProjection05 = CASE WHEN @MonthsLoaded < 5 THEN SampledBudget05 ELSE SampledProjection05 END, + SampledProjection06 = CASE WHEN @MonthsLoaded < 6 THEN SampledBudget06 ELSE SampledProjection06 END, + SampledProjection07 = CASE WHEN @MonthsLoaded < 7 THEN SampledBudget07 ELSE SampledProjection07 END, + SampledProjection08 = CASE WHEN @MonthsLoaded < 8 THEN SampledBudget08 ELSE SampledProjection08 END, + SampledProjection09 = CASE WHEN @MonthsLoaded < 9 THEN SampledBudget09 ELSE SampledProjection09 END, + SampledProjection10 = CASE WHEN @MonthsLoaded < 10 THEN SampledBudget10 ELSE SampledProjection10 END, + SampledProjection11 = CASE WHEN @MonthsLoaded < 11 THEN SampledBudget11 ELSE SampledProjection11 END, + SampledProjection12 = CASE WHEN @MonthsLoaded < 12 THEN SampledBudget12 ELSE SampledProjection12 END + FROM + [fp].[ServiceLineEncounter] sle + WHERE + sle.EntityGroupConfigID = @EntityGroupConfigID + + CREATE TABLE #Totals (ServiceLineEncounterID INT, SampledProjectionTotal DECIMAL(19,8), NewValue DECIMAL(19,8)); + INSERT INTO #Totals (ServiceLineEncounterID, SampledProjectionTotal) + SELECT ServiceLineEncounterID, + CASE WHEN @MonthsLoaded = 11 THEN sle.SampledProjection12 + WHEN @MonthsLoaded = 10 THEN sle.SampledProjection11 + sle.SampledProjection12 + WHEN @MonthsLoaded = 9 THEN sle.SampledProjection10 + sle.SampledProjection11 + sle.SampledProjection12 + WHEN @MonthsLoaded = 8 THEN sle.SampledProjection09 + sle.SampledProjection10 + sle.SampledProjection11 + sle.SampledProjection12 + WHEN @MonthsLoaded = 7 THEN sle.SampledProjection08 + sle.SampledProjection09 + sle.SampledProjection10 + sle.SampledProjection11 + sle.SampledProjection12 + WHEN @MonthsLoaded = 6 THEN sle.SampledProjection07 + sle.SampledProjection08 + sle.SampledProjection09 + sle.SampledProjection10 + sle.SampledProjection11 + sle.SampledProjection12 + WHEN @MonthsLoaded = 5 THEN sle.SampledProjection06 + sle.SampledProjection07 + sle.SampledProjection08 + sle.SampledProjection09 + sle.SampledProjection10 + sle.SampledProjection11 + sle.SampledProjection12 + WHEN @MonthsLoaded = 4 THEN sle.SampledProjection05 + sle.SampledProjection06 + sle.SampledProjection07 + sle.SampledProjection08 + sle.SampledProjection09 + sle.SampledProjection10 + sle.SampledProjection11 + sle.SampledProjection12 + WHEN @MonthsLoaded = 3 THEN sle.SampledProjection04 + sle.SampledProjection05 + sle.SampledProjection06 + sle.SampledProjection07 + sle.SampledProjection08 + sle.SampledProjection09 + sle.SampledProjection10 + sle.SampledProjection11 + sle.SampledProjection12 + WHEN @MonthsLoaded = 2 THEN sle.SampledProjection03 + sle.SampledProjection04 + sle.SampledProjection05 + sle.SampledProjection06 + sle.SampledProjection07 + sle.SampledProjection08 + sle.SampledProjection09 + sle.SampledProjection10 + sle.SampledProjection11 + sle.SampledProjection12 + WHEN @MonthsLoaded = 1 THEN sle.SampledProjection02 + sle.SampledProjection03 + sle.SampledProjection04 + sle.SampledProjection05 + sle.SampledProjection06 + sle.SampledProjection07 + sle.SampledProjection08 + sle.SampledProjection09 + sle.SampledProjection10 + sle.SampledProjection11 + sle.SampledProjection12 + ELSE 0 + END + FROM [fp].[ServiceLineEncounter] sle + WHERE sle.EntityGroupConfigID = @EntityGroupConfigID + + + UPDATE a SET NewValue = SampledProjectionTotal / (12.0 - @MonthsLoaded) + FROM #Totals a + + UPDATE + sle + SET + InitialProjection01 = CASE WHEN @MonthsLoaded >= 1 THEN sle.SampledProjection01 ELSE t.NewValue END, + InitialProjection02 = CASE WHEN @MonthsLoaded >= 2 THEN sle.SampledProjection02 ELSE t.NewValue END, + InitialProjection03 = CASE WHEN @MonthsLoaded >= 3 THEN sle.SampledProjection03 ELSE t.NewValue END, + InitialProjection04 = CASE WHEN @MonthsLoaded >= 4 THEN sle.SampledProjection04 ELSE t.NewValue END, + InitialProjection05 = CASE WHEN @MonthsLoaded >= 5 THEN sle.SampledProjection05 ELSE t.NewValue END, + InitialProjection06 = CASE WHEN @MonthsLoaded >= 6 THEN sle.SampledProjection06 ELSE t.NewValue END, + InitialProjection07 = CASE WHEN @MonthsLoaded >= 7 THEN sle.SampledProjection07 ELSE t.NewValue END, + InitialProjection08 = CASE WHEN @MonthsLoaded >= 8 THEN sle.SampledProjection08 ELSE t.NewValue END, + InitialProjection09 = CASE WHEN @MonthsLoaded >= 9 THEN sle.SampledProjection09 ELSE t.NewValue END, + InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN sle.SampledProjection10 ELSE t.NewValue END, + InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN sle.SampledProjection11 ELSE t.NewValue END, + InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN sle.SampledProjection12 ELSE t.NewValue END + FROM [fp].[ServiceLineEncounter] sle INNER JOIN #Totals t on sle.ServiceLineEncounterID = t.ServiceLineEncounterID + WHERE sle.EntityGroupConfigID = @EntityGroupConfigID + +END +GO + + +--------------------------------------------- + +-- fp.procSampleStaffingAdjustedData +CREATE PROCEDURE [fp].[procSampleStaffingAdjustedData] + @EntityGroupConfigID int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + EXEC [dbo].[procSysDropTempTable] '#filterTable' + + CREATE TABLE #filterTable (DepartmentID int) + INSERT INTO #filterTable (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #filterTable (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fp.Staffing + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + -- Update all target, budget, and projection adjusted + UPDATE staff + SET + TargetAdjustedDollars01 = InitialBudgetDollars01 + , TargetAdjustedDollars02 = InitialBudgetDollars02 + , TargetAdjustedDollars03 = InitialBudgetDollars03 + , TargetAdjustedDollars04 = InitialBudgetDollars04 + , TargetAdjustedDollars05 = InitialBudgetDollars05 + , TargetAdjustedDollars06 = InitialBudgetDollars06 + , TargetAdjustedDollars07 = InitialBudgetDollars07 + , TargetAdjustedDollars08 = InitialBudgetDollars08 + , TargetAdjustedDollars09 = InitialBudgetDollars09 + , TargetAdjustedDollars10 = InitialBudgetDollars10 + , TargetAdjustedDollars11 = InitialBudgetDollars11 + , TargetAdjustedDollars12 = InitialBudgetDollars12 + , BudgetAdjustedDollars01 = InitialBudgetDollars01 + , BudgetAdjustedDollars02 = InitialBudgetDollars02 + , BudgetAdjustedDollars03 = InitialBudgetDollars03 + , BudgetAdjustedDollars04 = InitialBudgetDollars04 + , BudgetAdjustedDollars05 = InitialBudgetDollars05 + , BudgetAdjustedDollars06 = InitialBudgetDollars06 + , BudgetAdjustedDollars07 = InitialBudgetDollars07 + , BudgetAdjustedDollars08 = InitialBudgetDollars08 + , BudgetAdjustedDollars09 = InitialBudgetDollars09 + , BudgetAdjustedDollars10 = InitialBudgetDollars10 + , BudgetAdjustedDollars11 = InitialBudgetDollars11 + , BudgetAdjustedDollars12 = InitialBudgetDollars12 + , ProjectionAdjustedDollars01 = InitialProjectionDollars01 + , ProjectionAdjustedDollars02 = InitialProjectionDollars02 + , ProjectionAdjustedDollars03 = InitialProjectionDollars03 + , ProjectionAdjustedDollars04 = InitialProjectionDollars04 + , ProjectionAdjustedDollars05 = InitialProjectionDollars05 + , ProjectionAdjustedDollars06 = InitialProjectionDollars06 + , ProjectionAdjustedDollars07 = InitialProjectionDollars07 + , ProjectionAdjustedDollars08 = InitialProjectionDollars08 + , ProjectionAdjustedDollars09 = InitialProjectionDollars09 + , ProjectionAdjustedDollars10 = InitialProjectionDollars10 + , ProjectionAdjustedDollars11 = InitialProjectionDollars11 + , ProjectionAdjustedDollars12 = InitialProjectionDollars12 + + , TargetAdjustedHours01 = InitialBudgetHours01 + , TargetAdjustedHours02 = InitialBudgetHours02 + , TargetAdjustedHours03 = InitialBudgetHours03 + , TargetAdjustedHours04 = InitialBudgetHours04 + , TargetAdjustedHours05 = InitialBudgetHours05 + , TargetAdjustedHours06 = InitialBudgetHours06 + , TargetAdjustedHours07 = InitialBudgetHours07 + , TargetAdjustedHours08 = InitialBudgetHours08 + , TargetAdjustedHours09 = InitialBudgetHours09 + , TargetAdjustedHours10 = InitialBudgetHours10 + , TargetAdjustedHours11 = InitialBudgetHours11 + , TargetAdjustedHours12 = InitialBudgetHours12 + , BudgetAdjustedHours01 = InitialBudgetHours01 + , BudgetAdjustedHours02 = InitialBudgetHours02 + , BudgetAdjustedHours03 = InitialBudgetHours03 + , BudgetAdjustedHours04 = InitialBudgetHours04 + , BudgetAdjustedHours05 = InitialBudgetHours05 + , BudgetAdjustedHours06 = InitialBudgetHours06 + , BudgetAdjustedHours07 = InitialBudgetHours07 + , BudgetAdjustedHours08 = InitialBudgetHours08 + , BudgetAdjustedHours09 = InitialBudgetHours09 + , BudgetAdjustedHours10 = InitialBudgetHours10 + , BudgetAdjustedHours11 = InitialBudgetHours11 + , BudgetAdjustedHours12 = InitialBudgetHours12 + , ProjectionAdjustedHours01 = InitialProjectionHours01 + , ProjectionAdjustedHours02 = InitialProjectionHours02 + , ProjectionAdjustedHours03 = InitialProjectionHours03 + , ProjectionAdjustedHours04 = InitialProjectionHours04 + , ProjectionAdjustedHours05 = InitialProjectionHours05 + , ProjectionAdjustedHours06 = InitialProjectionHours06 + , ProjectionAdjustedHours07 = InitialProjectionHours07 + , ProjectionAdjustedHours08 = InitialProjectionHours08 + , ProjectionAdjustedHours09 = InitialProjectionHours09 + , ProjectionAdjustedHours10 = InitialProjectionHours10 + , ProjectionAdjustedHours11 = InitialProjectionHours11 + , ProjectionAdjustedHours12 = InitialProjectionHours12 + + , TargetAdjustedFTEs01 = InitialBudgetFTEs01 + , TargetAdjustedFTEs02 = InitialBudgetFTEs02 + , TargetAdjustedFTEs03 = InitialBudgetFTEs03 + , TargetAdjustedFTEs04 = InitialBudgetFTEs04 + , TargetAdjustedFTEs05 = InitialBudgetFTEs05 + , TargetAdjustedFTEs06 = InitialBudgetFTEs06 + , TargetAdjustedFTEs07 = InitialBudgetFTEs07 + , TargetAdjustedFTEs08 = InitialBudgetFTEs08 + , TargetAdjustedFTEs09 = InitialBudgetFTEs09 + , TargetAdjustedFTEs10 = InitialBudgetFTEs10 + , TargetAdjustedFTEs11 = InitialBudgetFTEs11 + , TargetAdjustedFTEs12 = InitialBudgetFTEs12 + , BudgetAdjustedFTEs01 = InitialBudgetFTEs01 + , BudgetAdjustedFTEs02 = InitialBudgetFTEs02 + , BudgetAdjustedFTEs03 = InitialBudgetFTEs03 + , BudgetAdjustedFTEs04 = InitialBudgetFTEs04 + , BudgetAdjustedFTEs05 = InitialBudgetFTEs05 + , BudgetAdjustedFTEs06 = InitialBudgetFTEs06 + , BudgetAdjustedFTEs07 = InitialBudgetFTEs07 + , BudgetAdjustedFTEs08 = InitialBudgetFTEs08 + , BudgetAdjustedFTEs09 = InitialBudgetFTEs09 + , BudgetAdjustedFTEs10 = InitialBudgetFTEs10 + , BudgetAdjustedFTEs11 = InitialBudgetFTEs11 + , BudgetAdjustedFTEs12 = InitialBudgetFTEs12 + , ProjectionAdjustedFTEs01 = InitialProjectionFTEs01 + , ProjectionAdjustedFTEs02 = InitialProjectionFTEs02 + , ProjectionAdjustedFTEs03 = InitialProjectionFTEs03 + , ProjectionAdjustedFTEs04 = InitialProjectionFTEs04 + , ProjectionAdjustedFTEs05 = InitialProjectionFTEs05 + , ProjectionAdjustedFTEs06 = InitialProjectionFTEs06 + , ProjectionAdjustedFTEs07 = InitialProjectionFTEs07 + , ProjectionAdjustedFTEs08 = InitialProjectionFTEs08 + , ProjectionAdjustedFTEs09 = InitialProjectionFTEs09 + , ProjectionAdjustedFTEs10 = InitialProjectionFTEs10 + , ProjectionAdjustedFTEs11 = InitialProjectionFTEs11 + , ProjectionAdjustedFTEs12 = InitialProjectionFTEs12 + + , TargetAdjustedRate01 = InitialBudgetRate01 + , TargetAdjustedRate02 = InitialBudgetRate02 + , TargetAdjustedRate03 = InitialBudgetRate03 + , TargetAdjustedRate04 = InitialBudgetRate04 + , TargetAdjustedRate05 = InitialBudgetRate05 + , TargetAdjustedRate06 = InitialBudgetRate06 + , TargetAdjustedRate07 = InitialBudgetRate07 + , TargetAdjustedRate08 = InitialBudgetRate08 + , TargetAdjustedRate09 = InitialBudgetRate09 + , TargetAdjustedRate10 = InitialBudgetRate10 + , TargetAdjustedRate11 = InitialBudgetRate11 + , TargetAdjustedRate12 = InitialBudgetRate12 + , BudgetAdjustedRate01 = InitialBudgetRate01 + , BudgetAdjustedRate02 = InitialBudgetRate02 + , BudgetAdjustedRate03 = InitialBudgetRate03 + , BudgetAdjustedRate04 = InitialBudgetRate04 + , BudgetAdjustedRate05 = InitialBudgetRate05 + , BudgetAdjustedRate06 = InitialBudgetRate06 + , BudgetAdjustedRate07 = InitialBudgetRate07 + , BudgetAdjustedRate08 = InitialBudgetRate08 + , BudgetAdjustedRate09 = InitialBudgetRate09 + , BudgetAdjustedRate10 = InitialBudgetRate10 + , BudgetAdjustedRate11 = InitialBudgetRate11 + , BudgetAdjustedRate12 = InitialBudgetRate12 + , ProjectionAdjustedRate01 = InitialProjectionRate01 + , ProjectionAdjustedRate02 = InitialProjectionRate02 + , ProjectionAdjustedRate03 = InitialProjectionRate03 + , ProjectionAdjustedRate04 = InitialProjectionRate04 + , ProjectionAdjustedRate05 = InitialProjectionRate05 + , ProjectionAdjustedRate06 = InitialProjectionRate06 + , ProjectionAdjustedRate07 = InitialProjectionRate07 + , ProjectionAdjustedRate08 = InitialProjectionRate08 + , ProjectionAdjustedRate09 = InitialProjectionRate09 + , ProjectionAdjustedRate10 = InitialProjectionRate10 + , ProjectionAdjustedRate11 = InitialProjectionRate11 + , ProjectionAdjustedRate12 = InitialProjectionRate12 + + FROM [fp].[Staffing] staff + INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID AND IsNew = 0 + +END; +GO + + +--------------------------------------------- + +-- fp.procSampleStaffingClearData +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2021-02-24 lrenadesouza JAZZ-12907 Added FTERequest clean up and rolling deletes +** 2 2023-04-18 mdeboer JAZZ-53496 Remove adjustment delete logic +** 3 2023-07-05 mdeboer JAZZ-55672 Add remove config logic +** 4 2023-09-20 bkrehl JAZZ-60973 Staffing restructure +** 5 2023-12-11 nthomas JAZZ-64522 Add missing fp.StaffingWageRate table +***************************************************************/ +CREATE PROCEDURE [fp].[procSampleStaffingClearData] + @BudgetConfigGUID UNIQUEIDENTIFIER, + @EntityGroupConfigID INT, + @IsRemoveConfig BIT = 0, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + DECLARE @ChunkCount INT; + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 400000 END; + DECLARE @r INT; + + CREATE TABLE #filterTable (DepartmentID int) + INSERT INTO #filterTable (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #filterTable (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[Staffing] + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + CREATE TABLE #StaffingToDelete(StaffingID INT) + + IF @IsRemoveConfig = 1 + BEGIN + INSERT #StaffingToDelete with (tablock) (StaffingID) + SELECT StaffingID FROM fp.Staffing + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + ELSE + BEGIN + INSERT #StaffingToDelete with (tablock) (StaffingID) + SELECT StaffingID + FROM fp.Staffing fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID AND IsNew = 0 + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + --Delete all change history for reapply adjustments + DELETE hist FROM [fp].[StaffingChangeHistory] hist + INNER JOIN [fp].[Staffing] staff on hist.StaffingID = staff.StaffingID + INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID + WHERE staff.EntityGroupConfigID = @EntityGroupConfigID; + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) hist + FROM [fp].[StaffingHistory] hist + INNER JOIN [fp].[Staffing] staff on staff.StaffingID = hist.StaffingID + INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID + INNER JOIN #StaffingToDelete std on hist.StaffingID = std.StaffingID + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) wg + FROM [fp].[StaffingWageRate] wg + INNER JOIN [fp].[Staffing] staff on staff.StaffingWageRateID = wg.StaffingWageRateID + INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID + INNER JOIN #StaffingToDelete std on staff.StaffingID = std.StaffingID + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) staff + FROM [fp].[Staffing] staff + INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID + INNER JOIN #StaffingToDelete std on staff.StaffingID = std.StaffingID + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END +END +GO + + +--------------------------------------------- + +-- fp.procSampleStaffingClearData_InitialPlan +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2024-05-01 MD JAZZ-63557 Initial +***************************************************************/ +CREATE PROCEDURE [fp].[procSampleStaffingClearData_InitialPlan] + @BudgetConfigGUID UNIQUEIDENTIFIER, + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + DECLARE @ChunkCount INT; + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 400000 END; + DECLARE @r INT; + + CREATE TABLE #filterTable (DepartmentID int) + INSERT INTO #filterTable (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #filterTable (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[Staffing] + WHERE BudgetConfigID = @BudgetConfigID + END + + CREATE TABLE #StaffingToDelete(StaffingID INT) + + INSERT #StaffingToDelete with (tablock) (StaffingID) + SELECT StaffingID + FROM fp.Staffing fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + WHERE fs.BudgetConfigID = @BudgetConfigID AND IsNew = 0 + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + --Delete all change history for reapply adjustments + DELETE hist FROM [fp].[StaffingChangeHistory] hist + INNER JOIN [fp].[Staffing] staff on hist.StaffingID = staff.StaffingID + INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID + WHERE staff.BudgetConfigID = @BudgetConfigID; + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) hist + FROM [fp].[StaffingHistory] hist + INNER JOIN [fp].[Staffing] staff on staff.StaffingID = hist.StaffingID + INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID + INNER JOIN #StaffingToDelete std on hist.StaffingID = std.StaffingID + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) wg + FROM [fp].[StaffingWageRate] wg + INNER JOIN [fp].[Staffing] staff on staff.StaffingWageRateID = wg.StaffingWageRateID + INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID + INNER JOIN #StaffingToDelete std on staff.StaffingID = std.StaffingID + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) staff + FROM [fp].[Staffing] staff + INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID + INNER JOIN #StaffingToDelete std on staff.StaffingID = std.StaffingID + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END +END +GO + + +--------------------------------------------- + +-- fp.procSampleStaffingCollapseVariableData +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-11-07 MY JAZZ-35951 Add EmployeeID to FactStaffingVariabilityDetail +** 2 2023-09-20 BK JAZZ-60973 Update for new data structure +*************************************************************/ +CREATE PROCEDURE [fp].[procSampleStaffingCollapseVariableData] +@BudgetConfigID int, +@EntityGroupConfigID int, +@EntityGroupConfigGUID uniqueidentifier, +@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS + + SET NOCOUNT ON; + + CREATE TABLE #filterTable (DepartmentID int) + INSERT INTO #filterTable (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #filterTable (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fp.Staffing + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + SELECT fs.BudgetConfigID, fs.EntityGroupConfigID, fs.EntityID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.ProductiveClassID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, fs.VariabilityID, min(fs.EmployeeID) as MinEmployeeID + INTO #tempData + FROM fp.Staffing fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + INNER JOIN fp.EntityGroupConfig egc ON fs.EntityGroupConfigID = egc.EntityGroupConfigID + INNER JOIN fw.DimPayCode pc ON fs.PayCodeGroupID = pc.PayCodeGroupID + LEFT JOIN fp.FactStaffingVariabilityDetail fsvd ON fs.DepartmentID = fsvd.DepartmentID + AND fs.JobCodeID = fsvd.JobCodeID + AND fsvd.PayCodeID = pc.PayCodeID + AND fs.EmployeeID = fsvd.EmployeeID + AND fsvd.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE fs.BudgetConfigID = @BudgetConfigID + AND fs.EntityGroupConfigID = @EntityGroupConfigID + AND fsvd.FixedPercentage < 1 + GROUP BY fs.BudgetConfigID,fs.EntityGroupConfigID, fs.EntityID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.ProductiveClassID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, fs.VariabilityID + + DELETE fs + FROM fp.Staffing fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + INNER JOIN #tempData td ON fs.BudgetConfigID = td.BudgetConfigID + AND fs.EntityGroupConfigID = td.EntityGroupConfigID + AND fs.EntityID = td.EntityID + AND fs.DepartmentID = td.DepartmentID + AND fs.JobCodeID = td.JobCodeID + AND fs.PayCodeGroupID = td.PayCodeGroupID + AND fs.ProductiveClassID = td.ProductiveClassID + AND fs.VariabilityID = td.VariabilityID + AND fs.ProviderID = td.ProviderID + AND fs.ProviderTypeID = td.ProviderTypeID + AND fs.ProviderSpecialtyID = td.ProviderSpecialtyID + AND fs.ProviderLineItemID = td.ProviderLineItemID + AND fs.SubsectionID = td.SubsectionID + AND fs.EmployeeID > td.MinEmployeeID + + UPDATE fs + SET EmployeeID = 0 + FROM fp.Staffing fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + INNER JOIN #tempData td ON fs.BudgetConfigID = td.BudgetConfigID + AND fs.EntityGroupConfigID = td.EntityGroupConfigID + AND fs.EntityID = td.EntityID + AND fs.DepartmentID = td.DepartmentID + AND fs.JobCodeID = td.JobCodeID + AND fs.PayCodeGroupID = td.PayCodeGroupID + AND fs.ProductiveClassID = td.ProductiveClassID + AND fs.VariabilityID = td.VariabilityID + AND fs.ProviderID = td.ProviderID + AND fs.ProviderTypeID = td.ProviderTypeID + AND fs.ProviderSpecialtyID = td.ProviderSpecialtyID + AND fs.ProviderLineItemID = td.ProviderLineItemID + AND fs.SubsectionID = td.SubsectionID + WHERE EmployeeID <> 0 + AND fs.ProviderID = 0 -- Provider sampling will include EmployeeID, so we need to exclude provider records from this +GO + + +--------------------------------------------- + +-- fp.procSampleStaffingCollapseVariableData_InitialPlan +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-11-07 MY JAZZ-35951 Add EmployeeID to FactStaffingVariabilityDetail +** 2 2023-09-20 BK JAZZ-60973 Update for new data structure +** 3 2024-04-26 MD JAZZ-63557 Update to be at budget config level +*************************************************************/ +CREATE PROCEDURE [fp].[procSampleStaffingCollapseVariableData_InitialPlan] +@BudgetConfigGUID UNIQUEIDENTIFIER, +@BudgetConfigID INT, +@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS + + SET NOCOUNT ON; + + CREATE TABLE #filterTable (DepartmentID int) + INSERT INTO #filterTable (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #filterTable (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fp.Staffing + WHERE BudgetConfigID = @BudgetConfigID + END + + SELECT fs.BudgetConfigID, fs.EntityGroupConfigID, fs.EntityID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.ProductiveClassID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, fs.VariabilityID, min(fs.EmployeeID) as MinEmployeeID + INTO #tempData + FROM fp.Staffing fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + INNER JOIN fp.EntityGroupConfig egc + ON egc.BudgetConfigGUID = @BudgetConfigGUID + AND fs.EntityGroupConfigID = egc.EntityGroupConfigID + INNER JOIN fw.DimPayCode pc ON fs.PayCodeGroupID = pc.PayCodeGroupID + LEFT JOIN fp.FactStaffingVariabilityDetail fsvd ON fs.DepartmentID = fsvd.DepartmentID + AND fs.JobCodeID = fsvd.JobCodeID + AND fsvd.PayCodeID = pc.PayCodeID + AND fs.EmployeeID = fsvd.EmployeeID + AND fsvd.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE fs.BudgetConfigID = @BudgetConfigID + AND fsvd.FixedPercentage < 1 + GROUP BY fs.BudgetConfigID,fs.EntityGroupConfigID, fs.EntityID, fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID, fs.ProductiveClassID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID, fs.VariabilityID + + DELETE fs + FROM fp.Staffing fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + INNER JOIN #tempData td ON fs.BudgetConfigID = td.BudgetConfigID + AND fs.EntityGroupConfigID = td.EntityGroupConfigID + AND fs.EntityID = td.EntityID + AND fs.DepartmentID = td.DepartmentID + AND fs.JobCodeID = td.JobCodeID + AND fs.PayCodeGroupID = td.PayCodeGroupID + AND fs.ProductiveClassID = td.ProductiveClassID + AND fs.VariabilityID = td.VariabilityID + AND fs.ProviderID = td.ProviderID + AND fs.ProviderTypeID = td.ProviderTypeID + AND fs.ProviderSpecialtyID = td.ProviderSpecialtyID + AND fs.ProviderLineItemID = td.ProviderLineItemID + AND fs.SubsectionID = td.SubsectionID + AND fs.EmployeeID > td.MinEmployeeID + + UPDATE fs + SET EmployeeID = 0 + FROM fp.Staffing fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + INNER JOIN #tempData td ON fs.BudgetConfigID = td.BudgetConfigID + AND fs.EntityGroupConfigID = td.EntityGroupConfigID + AND fs.EntityID = td.EntityID + AND fs.DepartmentID = td.DepartmentID + AND fs.JobCodeID = td.JobCodeID + AND fs.PayCodeGroupID = td.PayCodeGroupID + AND fs.ProductiveClassID = td.ProductiveClassID + AND fs.VariabilityID = td.VariabilityID + AND fs.ProviderID = td.ProviderID + AND fs.ProviderTypeID = td.ProviderTypeID + AND fs.ProviderSpecialtyID = td.ProviderSpecialtyID + AND fs.ProviderLineItemID = td.ProviderLineItemID + AND fs.SubsectionID = td.SubsectionID + WHERE EmployeeID <> 0 + AND fs.ProviderID = 0 -- Provider sampling will include EmployeeID, so we need to exclude provider records from this +GO + + +--------------------------------------------- + +-- fp.procSampleStaffingDimensionality +CREATE PROCEDURE [fp].[procSampleStaffingDimensionality] + @BudgetConfigID int, + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @SourceFiscalYearID smallint, + @SourceTimeClassID tinyint, + @IsEmployeeBudgeting bit, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 4 2021-03-22 NT JAZZ-15374 Use NPI instead of EmployeID for Provider Comp Sampling + ** 5 2021-06-30 BW JAZZ-21627 Update selects for EmployeID for variablity + ** 6 2021-09-07 BW JAZZ-25863 Check for dept. usage of Employee Budgeting when sampling + ** 7 2021-12-01 OP JAZZ-29466 removed empty users check for prov comp data + ** 8 2022-03-02 MZ JAZZ-30547 improved checks in order to sample valid Employees with valid NPI + ** 9 2022-05-31 BW JAZZ-37832 If IsHoursIgnored and IsDollarsIgnored are both true, then the dimensionality should not be pulled in + ** 10 2022-08-08 BK JAZZ-38357 Make sure IsFP records are correctly sampled depending on if true or false + ** 11 2022-10-07 AO JAZZ-42868 Non-provider department samples correct staffing values when provider sampling feature is turned on. + ** 12 2022-10-26 MZ JAZZ-42873 Departments and employees extended by projection (current year actuals) and prior year, actual + ** 13 2022-11-07 MZ JAZZ-35344 improved checks in order to sample valid Employees with valid NPI from FactProvider + ** 14 11-7-2022 MY JAZZ-35951 Add EmployeeID to FactStaffingVariabilityDetail + ** 15 2022-12-12 DM JAZZ-46455 Samplimg of Provider Type and Provider Specialty is linked to Section Setup + ** 16 2023-09-26 BK JAZZ-61239 Fix variable dept/job code incorrectly ignoring data that has EmployeeID in int.FactStaffing + ** 17 2023-09-30 BK JAZZ-60973 Update for new data structure + ** 18 2023-12-07 NT JAZZ-64522 Fix INSERT into fp.StaffingWageRate that is causing Sampling to fail + ** 19 2024-02-01 MD JAZZ-67072 Fix INSERT into fp.StaffingWageRate that is causing Sampling to fail - Part 2: Electric Boogaloo + ** 20 2024-02-02 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config + ** 21 2024-03-25 MY JAZZ-69661 Duplicated data for non-Provider departments in client dbs who utilize Provider Planning + ** 22 2024-06-18 AO JAZZ-72231 Added Source Provider Sampling + ** 23 2024-10-22 VZ JAZZ-76243 Extended condition for int.factStaffing for populating provider compensation data + *************************************************************/ + + --D-09416 + --Updated data pull to be two separate temp tables so I can join them on EmployeeID after the case statement is run + IF OBJECT_ID('tempdb..#rawStaffingData') IS NOT NULL DROP TABLE #rawStaffingData + IF OBJECT_ID('tempdb..#newStaffingData') IS NOT NULL DROP TABLE #newStaffingData + IF OBJECT_ID('tempdb..#dimensions') IS NOT NULL DROP TABLE #dimensions + IF OBJECT_ID('tempdb..#filterTable') IS NOT NULL DROP TABLE #filterTable + IF OBJECT_ID('tempdb..#provDims') IS NOT NULL DROP TABLE #provDims + + + CREATE TABLE #rawStaffingData (EntityID INT, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, ProductiveClassID INT, EmployeeID INT, ProviderID INT, ProviderTypeID INT, ProviderSpecialtyID INT, ProviderLineItemID INT, SubsectionID INT) + CREATE TABLE #newStaffingData (DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, ProductiveClassID INT, EmployeeID INT, ProviderID INT, ProviderTypeID INT, ProviderSpecialtyID INT, ProviderLineItemID INT, SubsectionID INT) + CREATE TABLE #dimensions (EntityID INT, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, ProductiveClassID INT, EmployeeID INT, ProviderID INT, ProviderTypeID INT, ProviderSpecialtyID INT, ProviderLineItemID INT, SubsectionID INT) + + CREATE TABLE #filterTable (DepartmentID int) + INSERT INTO #filterTable (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #filterTable (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fw].[DimDepartment] d WITH (READUNCOMMITTED) + INNER JOIN [fp].[EntityGroupConfigMapping] egcm on egcm.EntityID = d.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID + WHERE egc.EntityGroupConfigID = @EntityGroupConfigID + END + + DECLARE @StaffingSubsectionID INT = 3; + DECLARE @ProviderSubsectionID INT = 4; + + DECLARE @IsProviderPlanningEnabled BIT; + DECLARE @UseProviderSource BIT; + DECLARE @SampleProviderEitherFromStaffingOrProviderIntTable BIT; + + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled, @UseProviderSource = UseProviderSource FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID; + + SELECT @SampleProviderEitherFromStaffingOrProviderIntTable = Value FROM fp.BudgetConfigSetting bcs + INNER JOIN fp.BudgetConfigDefaultSetting bcds ON bcs.SettingID = bcds.SettingID + WHERE Name = 'Sample Provider either from Staffing or Provider int tables' AND BudgetConfigID = @BudgetConfigID + + + INSERT INTO #newStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID) + SELECT DISTINCT + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.ProductiveClassID, + CASE WHEN @IsEmployeeBudgeting = 0 THEN 0 ELSE fs.EmployeeID END AS EmployeeID, + fs.ProviderID, + fs.ProviderTypeID, + fs.ProviderSpecialtyID, + fs.ProviderLineItemID, + fs.SubsectionID + FROM [fp].[Staffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.IsNew = 1 + + DECLARE @EntityGroupConfigGUID UNIQUEIDENTIFIER; + SELECT @EntityGroupConfigGUID = EntityGroupConfigGUID FROM fp.EntityGroupConfig WHERE EntityGroupConfigID = @EntityGroupConfigID + + IF @IsProviderPlanningEnabled = 0 -- Is Provider Sampling Enabled + BEGIN + ------------------------------------------------------- + -- Provider is disabled + ------------------------------------------------------- + + INSERT INTO #rawStaffingData (EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, ProviderID, ProviderTypeID, + ProviderSpecialtyID, ProviderLineItemID, SubsectionID) + SELECT DISTINCT + dept.EntityID, + fs.DepartmentID, + fs.JobCodeID, + pcg.PayCodeGroupID, + pcg.ProductiveClassID, + CASE + WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 + ELSE CASE + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE fs.EmployeeID + END + END as EmployeeID, + 0, + 0, + 0, + 0, + 3 -- Staffing + FROM + [int].[FactStaffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + INNER JOIN [fw].[DimJobCode] dj on dj.JobCodeID = fs.JobCodeID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fs.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dept ON fs.DepartmentID = dept.DepartmentID + INNER JOIN [fw].[DimPayCode] pc ON fs.PayCodeID = pc.PayCodeID + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = fs.DepartmentID + AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = fs.DepartmentID + AND fv.JobCodeID = fs.JobCodeID + AND fv.PayCodeID = fs.PayCodeID + AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0. + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE fs.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not. + END = fv.EmployeeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE + ((fs.FiscalYearID = @SourceFiscalYearID AND fs.TimeclassID = @SourceTimeClassID) -- baseline + OR (fs.FiscalYearID = @CurrentFiscalYearID) -- projection (current year actuals) + OR (fs.FiscalYearID = @CurrentFiscalYearID - 1 AND fs.TimeClassID = 1)) -- prior year, actual + AND fs.IsDeleted = 0 + AND fs.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND (pc.IsHoursIgnored = 0 OR pc.IsDollarsIgnored = 0) + + END ELSE BEGIN + + ------------------------------------------------------- + -- Provider is enabled + ------------------------------------------------------- + + IF OBJECT_ID('tempdb..#emp') IS NOT NULL DROP TABLE #emp + IF OBJECT_ID('tempdb..#dept') IS NOT NULL DROP TABLE #dept + CREATE TABLE #emp (DepartmentID INT, EmployeeID INT, ProviderID INT, ProviderTypeID INT, ProviderSpecialtyID INT, IsFP BIT) + CREATE TABLE #dept (DepartmentID INT, EntityID INT, UseProvider BIT) + CREATE TABLE #provDims (DepartmentID INT, ProviderID INT, ProviderLineItemID INT) + + DECLARE @IsProviderTypeDisabled BIT; + SELECT @IsProviderTypeDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderTypeID' AND PlanSectionID = 3 AND SubSectionID = 1 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + + DECLARE @IsProviderSpecialtyDisabled BIT; + SELECT @IsProviderSpecialtyDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderSpecialtyID' AND PlanSectionID = 3 AND SubSectionID = 1 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + -- JAZZ-69661: Duplicated data for non-Provider departments in client dbs who utilize Provider Planning + DECLARE @EnableDepartmentLevelProviderForSampling BIT = ISNULL((SELECT 1 + FROM fp.BudgetConfigSetting setting + INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON setting.SettingID = def.SettingID + WHERE def.Name = 'Enable Department Level Provider For Sampling' + AND setting.BudgetConfigID = @BudgetConfigID + AND setting.Value = 1), 0) + + IF @SampleProviderEitherFromStaffingOrProviderIntTable = 0 + BEGIN + + ------------------------------------------------------- + -- BudgetConfigSetting is disabled + ------------------------------------------------------- + + -- Get all departments that use Provider Staffing + -- Get all employees that are providers + -- Sample provider data from int.FactStaffing for employees in departments that are configured to use provider sampling + -- Sample regular data for non provider employees and departments that are not configured to use provider sampling + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + ((staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeClassID = @SourceTimeClassID) + OR (staff.FiscalYearID = @CurrentFiscalYearID) + OR (staff.FiscalYearID = @CurrentFiscalYearID - 1 AND staff.TimeClassID = 1)) + AND staff.IsDeleted = 0 + AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + UNION + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + ((prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID) -- baseline + OR (prov.FiscalYearID = @CurrentFiscalYearID) -- projection (current year actuals) + OR (prov.FiscalYearID = @CurrentFiscalYearID - 1 AND prov.TimeClassID = 1)) -- prior year, actual + AND prov.IsDeleted = 0 + AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND (@EnableDepartmentLevelProviderForSampling = 0 OR prov.UnitTypeID IN (34, 51)) -- Only pull in Hours and Dollars since that's all we pull in later + + -- 2. all employees that are providers + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END, + emp.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID + INNER JOIN [dss].[DimPhysician] phys ON emp.NPI = phys.NPI + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + ((staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeClassID = @SourceTimeClassID) + OR (staff.FiscalYearID = @CurrentFiscalYearID) + OR (staff.FiscalYearID = @CurrentFiscalYearID - 1 AND staff.TimeClassID = 1)) + AND staff.IsDeleted = 0 + AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND staff.EmployeeID > 0 + AND emp.NPI NOT IN ('Not Specified', '0', '') + UNION + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, + phys.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + ((prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID) -- baseline + OR (prov.FiscalYearID = @CurrentFiscalYearID) -- projection (current year actuals) + OR (prov.FiscalYearID = @CurrentFiscalYearID - 1 AND prov.TimeClassID = 1)) -- prior year, actual + AND prov.IsDeleted = 0 + AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND phys.NPI NOT IN ('Not Specified', '0', '') + AND (@EnableDepartmentLevelProviderForSampling = 0 OR prov.UnitTypeID IN (34, 51)) -- Only pull in Hours and Dollars since that's all we pull in later + + -- Provider from int.FactProvider + INSERT INTO #rawStaffingData (EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID) + SELECT + DISTINCT + dept.EntityID, + fs.DepartmentID, + 0 as JobCodeID, + 0 as PayCodeGroupID, + 0 as ProductiveClassID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + fs.ProviderLineItemID, + @ProviderSubsectionID + FROM + [int].[FactProvider] fs + INNER JOIN #dept dept ON fs.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON fs.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fs.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fs.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fs.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + WHERE + ((fs.FiscalYearID = @SourceFiscalYearID AND fs.TimeclassID = @SourceTimeClassID) -- baseline + OR (fs.FiscalYearID = @CurrentFiscalYearID) -- projection (current year actuals) + OR (fs.FiscalYearID = @CurrentFiscalYearID - 1 AND fs.TimeClassID = 1)) -- prior year, actual + AND fs.IsDeleted = 0 + AND fs.FiscalMonthID != 0 + AND ps.Description = 'Staffing' + AND emp.IsFP = 1 + AND fs.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later + + INSERT INTO #provDims (DepartmentID, ProviderID, ProviderLineItemID) SELECT DISTINCT DepartmentID, ProviderID, ProviderLineItemID FROM #rawStaffingData + + -- Provider from int.FactStaffing + INSERT INTO #rawStaffingData (EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID) + SELECT + DISTINCT + dept.EntityID, + fs.DepartmentID, + fs.JobCodeID, + pcg.PayCodeGroupID, + pcg.ProductiveClassID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + pc.ProviderLineItemID, + @ProviderSubsectionID + FROM + [int].[FactStaffing] fs + INNER JOIN #dept dept ON fs.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON fs.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fs.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fs.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON fs.PayCodeID = pc.PayCodeID + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + LEFT JOIN #provDims pd ON fs.DepartmentID = pd.DepartmentID AND emp.ProviderID = pd.ProviderID and pd.ProviderLineItemID = pli.ProviderLineItemID + WHERE + ((fs.FiscalYearID = @SourceFiscalYearID AND fs.TimeclassID = @SourceTimeClassID) -- baseline + OR (fs.FiscalYearID = @CurrentFiscalYearID) -- projection (current year actuals) + OR (fs.FiscalYearID = @CurrentFiscalYearID - 1 AND fs.TimeClassID = 1)) -- prior year, actual + AND fs.IsDeleted = 0 + AND fs.FiscalMonthID != 0 + AND ps.Description = 'Staffing' + AND pd.DepartmentID IS NULL + AND emp.IsFP = 1 + AND (pc.IsHoursIgnored = 0 OR pc.IsDollarsIgnored = 0) + END ELSE BEGIN + + ------------------------------------------------------- + -- BudgetConfigSetting is enabled + ------------------------------------------------------- + + IF @UseProviderSource = 0 + BEGIN + + ------------------------------------------------------- + -- BudgetConfig UseProviderSource is disabled + ------------------------------------------------------- + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use staffing + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + ((staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeClassID = @SourceTimeClassID) + OR (staff.FiscalYearID = @CurrentFiscalYearID) + OR (staff.FiscalYearID = @CurrentFiscalYearID - 1 AND staff.TimeClassID = 1)) + AND staff.IsDeleted = 0 + AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + + -- 2. Employees from staffing + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END, + emp.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID + INNER JOIN [dss].[DimPhysician] phys ON emp.NPI = phys.NPI + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + ((staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeClassID = @SourceTimeClassID) + OR (staff.FiscalYearID = @CurrentFiscalYearID) + OR (staff.FiscalYearID = @CurrentFiscalYearID - 1 AND staff.TimeClassID = 1)) + AND staff.IsDeleted = 0 + AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND staff.EmployeeID > 0 + AND emp.NPI NOT IN ('Not Specified', '0', '') + + + -- Provider from int.FactStaffing + INSERT INTO #rawStaffingData (EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID) + SELECT + DISTINCT + dept.EntityID, + fs.DepartmentID, + fs.JobCodeID, + pcg.PayCodeGroupID, + pcg.ProductiveClassID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + pc.ProviderLineItemID, + @ProviderSubsectionID + FROM + [int].[FactStaffing] fs + INNER JOIN #dept dept ON fs.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON fs.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fs.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fs.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON fs.PayCodeID = pc.PayCodeID + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + WHERE + ((fs.FiscalYearID = @SourceFiscalYearID AND fs.TimeclassID = @SourceTimeClassID) -- baseline + OR (fs.FiscalYearID = @CurrentFiscalYearID) -- projection (current year actuals) + OR (fs.FiscalYearID = @CurrentFiscalYearID - 1 AND fs.TimeClassID = 1)) -- prior year, actual + AND fs.IsDeleted = 0 + AND fs.FiscalMonthID != 0 + AND ps.Description = 'Staffing' + AND emp.IsFP = 1 + AND (pc.IsHoursIgnored = 0 OR pc.IsDollarsIgnored = 0) + + END ELSE BEGIN + + ------------------------------------------------------- + -- BudgetConfig UseProviderSource is enabled + ------------------------------------------------------- + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + ((prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID) -- baseline + OR (prov.FiscalYearID = @CurrentFiscalYearID) -- projection (current year actuals) + OR (prov.FiscalYearID = @CurrentFiscalYearID - 1 AND prov.TimeClassID = 1)) -- prior year, actual + AND prov.IsDeleted = 0 + AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND (@EnableDepartmentLevelProviderForSampling = 0 OR prov.UnitTypeID IN (34, 51)) -- Only pull in Hours and Dollars since that's all we pull in later + + -- 2. Employees from provider + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, + phys.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + ((prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID) -- baseline + OR (prov.FiscalYearID = @CurrentFiscalYearID) -- projection (current year actuals) + OR (prov.FiscalYearID = @CurrentFiscalYearID - 1 AND prov.TimeClassID = 1)) -- prior year, actual + AND prov.IsDeleted = 0 + AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND phys.NPI NOT IN ('Not Specified', '0', '') + AND (@EnableDepartmentLevelProviderForSampling = 0 OR prov.UnitTypeID IN (34, 51)) -- Only pull in Hours and Dollars since that's all we pull in later + + -- Provider from int.FactProvider + INSERT INTO #rawStaffingData (EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID) + SELECT + DISTINCT + dept.EntityID, + fs.DepartmentID, + 0 as JobCodeID, + 0 as PayCodeGroupID, + 0 as ProductiveClassID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + fs.ProviderLineItemID, + @ProviderSubsectionID + FROM + [int].[FactProvider] fs + INNER JOIN #dept dept ON fs.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON fs.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fs.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fs.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fs.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + WHERE + ((fs.FiscalYearID = @SourceFiscalYearID AND fs.TimeclassID = @SourceTimeClassID) -- baseline + OR (fs.FiscalYearID = @CurrentFiscalYearID) -- projection (current year actuals) + OR (fs.FiscalYearID = @CurrentFiscalYearID - 1 AND fs.TimeClassID = 1)) -- prior year, actual + AND fs.IsDeleted = 0 + AND fs.FiscalMonthID != 0 + AND ps.Description = 'Staffing' + AND emp.IsFP = 1 + AND fs.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later + END + END + + -- All non-provider records here, regular staffing + INSERT INTO #rawStaffingData (EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID) + SELECT + DISTINCT + d.EntityID, + fs.DepartmentID, + fs.JobCodeID, + pcg.PayCodeGroupID, + pcg.ProductiveClassID, + CASE + WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 + ELSE CASE + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE fs.EmployeeID + END + END as EmployeeID, + 0, --ProviderID + 0, --ProviderTypeID + 0, --ProviderSpecialtyID + 0, --ProviderLineItemID + @StaffingSubsectionID + FROM + [int].[FactStaffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + LEFT JOIN #dept dept ON tmp.DepartmentID = dept.DepartmentID + LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 1) emp ON fs.EmployeeID = emp.EmployeeID + LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 0) NotFpEmp ON fs.EmployeeID = NotFpEmp.EmployeeID + INNER JOIN [fw].[DimDepartment] d ON tmp.DepartmentID = d.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fs.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON fs.PayCodeID = pc.PayCodeID + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg ON sefg.DepartmentID = fs.DepartmentID + AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = fs.DepartmentID + AND fv.JobCodeID = fs.JobCodeID + AND fv.PayCodeID = fs.PayCodeID + AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0. + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE fs.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not. + END = fv.EmployeeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE + ((fs.FiscalYearID = @SourceFiscalYearID AND fs.TimeclassID = @SourceTimeClassID) -- baseline + OR (fs.FiscalYearID = @CurrentFiscalYearID) -- projection (current year actuals) + OR (fs.FiscalYearID = @CurrentFiscalYearID - 1 AND fs.TimeClassID = 1)) -- prior year, actual + AND fs.IsDeleted = 0 + AND fs.FiscalMonthID != 0 + AND (dept.DepartmentID IS NULL OR (emp.EmployeeID IS NULL AND (NotFpEmp.EmployeeID IS NULL OR NotFpEmp.IsFP = 0))) + AND (pc.IsHoursIgnored = 0 OR pc.IsDollarsIgnored = 0) + END + + INSERT INTO #dimensions (EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID) + SELECT rs.EntityID, + rs.DepartmentID, + rs.JobCodeID, + rs.PayCodeGroupID, + rs.ProductiveClassID, + rs.EmployeeID, + rs.ProviderID, + rs.ProviderTypeID, + rs.ProviderSpecialtyID, + rs.ProviderLineItemID, + rs.SubsectionID + FROM #rawStaffingData rs + LEFT JOIN #newStaffingData ns ON rs.DepartmentID = ns.DepartmentID + AND rs.JobCodeID = ns.JobCodeID + AND rs.PayCodeGroupID = ns.PayCodeGroupID + AND rs.ProductiveClassID = ns.ProductiveClassID + AND rs.EmployeeID = ns.EmployeeID + AND rs.ProviderID = ns.ProviderID + AND rs.ProviderTypeID = ns.ProviderTypeID + AND rs.ProviderSpecialtyID = ns.ProviderSpecialtyID + AND rs.ProviderLineItemID = ns.ProviderLineItemID + AND rs.SubsectionID = ns.SubsectionID + WHERE ns.DepartmentID IS NULL + + INSERT INTO [fp].[Staffing]([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [JobCodeID], [PayCodeGroupID], [ProductiveClassID], [EmployeeID], [VariabilityID], + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID) + SELECT DISTINCT + @BudgetConfigID, + @EntityGroupConfigID, + d.EntityID, + d.DepartmentID, + d.JobCodeID, + d.PayCodeGroupID, + d.ProductiveClassID, + d.EmployeeID, + vari.VariabilityID, + d.ProviderID, + d.ProviderTypeID, + d.ProviderSpecialtyID, + d.ProviderLineItemID, + d.SubsectionID + FROM + #dimensions d + CROSS APPLY (VALUES (1),(2)) vari(VariabilityID) + + --Wage Rate + INSERT INTO [fp].[StaffingWageRate] (StaffingWageRateID) + SELECT StaffingID + FROM fp.Staffing staff + JOIN #filterTable ft on staff.DepartmentID = ft.DepartmentID + WHERE BudgetConfigID = @BudgetConfigID + AND EntityGroupConfigID = @EntityGroupConfigID + AND VariabilityID = 1 + AND IsNew = 0 + + UPDATE staff + SET StaffingWageRateID = StaffingID + FROM fp.Staffing staff + JOIN #filterTable ft on staff.DepartmentID = ft.DepartmentID + WHERE BudgetConfigID = @BudgetConfigID + AND EntityGroupConfigID = @EntityGroupConfigID + AND VariabilityID = 1 + AND IsNew = 0 + + UPDATE a SET StaffingWageRateID = fixed.StaffingID + FROM fp.Staffing a + JOIN #filterTable ft on a.DepartmentID = ft.DepartmentID + INNER JOIN fp.Staffing fixed + ON a.DepartmentID = fixed.DepartmentID + AND a.JobCodeID = fixed.JobCodeID + AND a.PayCodeGroupID = fixed.PayCodeGroupID + AND a.BudgetConfigID = fixed.BudgetConfigID + AND a.EntityGroupConfigID = fixed.EntityGroupConfigID + AND a.EntityID = fixed.EntityID + AND a.ProductiveClassID = fixed.ProductiveClassID + AND a.ProviderID = fixed.ProviderID + AND a.ProviderLineItemID = fixed.ProviderLineItemID + AND a.ProviderTypeID = fixed.ProviderTypeID + AND a.ProviderSpecialtyID = fixed.ProviderSpecialtyID + AND a.EmployeeID = fixed.EmployeeID + WHERE a.VariabilityID = 2 AND fixed.VariabilityID = 1 + AND a.IsNew = 0 + +END +GO + + +--------------------------------------------- + +-- fp.procSampleStaffingDollarsPerUOS +CREATE PROCEDURE [fp].[procSampleStaffingDollarsPerUOS] + @BudgetConfigID INT, + @EntityGroupConfigID INT, + @EntityGroupConfigGUID UNIQUEIDENTIFIER, + @StaffingFiscalYearID INT, + @StaffingTimeClassID INT, + @CurrentFiscalYearID INT, + @MonthsLoaded INT, + @IsEmployeeBudgeting BIT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-01-14 MY JAZZ-12607 Initial + ** 2 2021-12-09 BK JAZZ-30703 Use fp.FactStatisticsHistory historicals instead of int.FactStatistic + ** 3 2022-03-02 MZ JAZZ-30547 improved checks in order to sample valid Employees with valid NPI + ** 4 2022-05-17 OP JAZZ-34114 improved sampling in order to support Dollars per UOS for Provider Comp + ** 5 2022-11-07 MZ JAZZ-35344 improved checks in order to sample valid Employees with valid NPI from FactProvider + ** 6 2022-12-12 DM JAZZ-46455 Sampling of Provider Type and Provider Specialty is linked to Section Setup + ** 7 2023-03-13 MY JAZZ-48981 Update sampling for cross department flexing + ** 8 2023-09-20 BK JAZZ-60973 Update for new data structure + ** 9 2024-08-19 AO JAZZ-75410 Added Source Provider Sampling + *************************************************************/ + + -- Clearing temp tables for next run + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment; + IF OBJECT_ID('tempdb..#TempIntStaffingData') IS NOT NULL DROP TABLE #TempIntStaffingData; + IF OBJECT_ID('tempdb..#IntStaffingData') IS NOT NULL DROP TABLE #IntStaffingData; + IF OBJECT_ID('tempdb..#departmentsConfiguredToFlex') IS NOT NULL DROP TABLE #departmentsConfiguredToFlex; + IF OBJECT_ID('tempdb..#flexConfigMapping') IS NOT NULL DROP TABLE #flexConfigMapping; + IF OBJECT_ID('tempdb..#provDims') IS NOT NULL DROP TABLE #provDims; + IF OBJECT_ID('tempdb..#staffingConfiguredToFlex') IS NOT NULL DROP TABLE #staffingConfiguredToFlex; + IF OBJECT_ID('tempdb..#uniqueStatMapping') IS NOT NULL DROP TABLE #uniqueStatMapping; + IF OBJECT_ID('tempdb..#statsBudget') IS NOT NULL DROP TABLE #statsBudget; + + -- Create temp tables to store manipulated data + CREATE TABLE #TempIntStaffingData ( + DepartmentID INT, + JobCodeID INT, + PayCodeGroupID INT, + EmployeeID INT, + ProviderID INT, + ProviderTypeID INT, + ProviderSpecialtyID INT, + ProviderLineItemID INT, + Value DECIMAL (19,4) + ) + + CREATE TABLE #IntStaffingData ( + DepartmentID INT, + JobCodeID INT, + PayCodeGroupID INT, + EmployeeID INT, + ProviderID INT, + ProviderTypeID INT, + ProviderSpecialtyID INT, + ProviderLineItemID INT, + BudgetDollarTotal DECIMAL (19,4) + ) + + CREATE TABLE #FilterByDepartment (DepartmentID int) + CREATE TABLE #departmentsConfiguredToFlex (DepartmentID int) + CREATE TABLE #provDims (DepartmentID INT, ProviderID INT, ProviderLineItemID INT) + CREATE TABLE #flexConfigMapping(DepartmentID INT, PRJobCodeID INT, StatAccountID INT, ProviderLineItemID INT, SourceDepartmentID INT) + CREATE TABLE #staffingConfiguredToFlex(DepartmentID INT, PRJobCodeID INT, ProviderLineItemID INT) + CREATE TABLE #uniqueStatMapping(DepartmentID INT, StatAccountID INT, ProviderLineItemID INT, SourceDepartmentID INT) + CREATE TABLE #statsBudget (DepartmentID INT, ProviderLineItemID INT, ProviderID INT, StatTotal INT) + + DECLARE @IsAnnualized BIT = (CASE WHEN @StaffingFiscalYearID = @CurrentFiscalYearID AND @StaffingTimeClassID = 1 AND @MonthsLoaded < 12 THEN 1 ELSE 0 END) + DECLARE @ProviderSubsection INT = 4 + + -- Convert source dim to temp table for performance + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- Build out #FilterByDepartment if targeting is empty + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT d.DepartmentID + FROM [fp].[Staffing] d WITH (READUNCOMMITTED) + WHERE d.BudgetConfigID = @BudgetConfigID + AND d.SubsectionID = @ProviderSubSection + AND d.FlexingTypeID = 9 + END + + -- Load mapping from flex config mapping table. FlexingType is 9 for Provider By Stats + INSERT INTO #flexConfigMapping (DepartmentID, PRJobCodeID, StatAccountID, ProviderLineItemID, SourceDepartmentID) + SELECT DISTINCT mapping.DepartmentID, mapping.PRJobCodeID, StatAccountID, ProviderLineItemID, SourceDepartmentID + FROM [fp].[FlexConfigMapping] mapping + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = mapping.DepartmentID + WHERE mapping.FlexingTypeID = 9 + AND mapping.EntityGroupConfigID = @EntityGroupConfigID + + -- Build a temp table to quickly get just the departments that are being flexed + INSERT INTO #departmentsConfiguredToFlex + SELECT DISTINCT mapping.DepartmentID + FROM #flexConfigMapping mapping + + -- Get all of the department/jobcode/providerLineItem Combinations + INSERT INTO #staffingConfiguredToFlex + SELECT DISTINCT mapping.DepartmentID, mapping.PRJobCodeID, mapping.ProviderLineItemID + FROM #flexConfigMapping mapping + + ------------------------------------- + -- Get statistic data + ------------------------------------- + INSERT INTO #uniqueStatMapping (DepartmentID, StatAccountID, ProviderLineItemID, SourceDepartmentID) + SELECT DISTINCT mapping.DepartmentID, StatAccountID, ProviderLineItemID, SourceDepartmentID + FROM #flexConfigMapping mapping + + DECLARE @UsePriorYear BIT = 0; + DECLARE @UseActualYTD BIT = 0; + DECLARE @UseCurrentYearBudget BIT = 0; + + IF @StaffingTimeClassID = 2 BEGIN + SET @UseCurrentYearBudget = 1; + END ELSE BEGIN + IF @CurrentFiscalYearID = @StaffingFiscalYearID BEGIN + SET @UseActualYTD = 1; + END ELSE BEGIN + SET @UsePriorYear = 1 + END + END + + INSERT INTO #statsBudget (DepartmentID, ProviderLineItemID, ProviderID, StatTotal) + SELECT + map.DepartmentID, + map.ProviderLineItemID, -- this is the ProviderLineItemID for staffing flexing (not stats) - we will use this later to flex staffing + stat.ProviderID, + CASE + WHEN @UseActualYTD = 1 THEN ISNULL(SUM(statHist.ActualYTDValueTotal), 0) + WHEN @UseCurrentYearBudget = 1 THEN ISNULL(SUM(statHist.CurrentYearBudgetTotal), 0) + WHEN @UsePriorYear = 1 THEN ISNULL(SUM(statHist.PriorYearActualValueTotal), 0) + END AS StatTotal + FROM #uniqueStatMapping map + LEFT JOIN fp.[FactStatistics] stat ON stat.DepartmentID = map.SourceDepartmentID AND stat.AccountID = map.StatAccountID + LEFT JOIN fp.[FactStatisticsHistory] statHist ON stat.StatisticsID = statHist.StatisticsID + WHERE stat.BudgetConfigID = @BudgetConfigID -- We need the entire budget, not just EGC because stats can be cross EGC for X Department flexing + GROUP BY + map.DepartmentID, + map.ProviderLineItemID, + stat.ProviderID + + ------------------------------------- + -- Get staffing data + ------------------------------------- + + DECLARE @ProviderSubsectionID INT = 4; + + DECLARE @UseProviderSource BIT; + DECLARE @SampleProviderEitherFromStaffingOrProviderIntTable BIT; + + SELECT @UseProviderSource = UseProviderSource FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID; + + SELECT @SampleProviderEitherFromStaffingOrProviderIntTable = Value FROM fp.BudgetConfigSetting bcs + INNER JOIN fp.BudgetConfigDefaultSetting bcds ON bcs.SettingID = bcds.SettingID + WHERE Name = 'Sample Provider either from Staffing or Provider int tables' AND BudgetConfigID = @BudgetConfigID + + IF OBJECT_ID('tempdb..#emp') IS NOT NULL DROP TABLE #emp + IF OBJECT_ID('tempdb..#dept') IS NOT NULL DROP TABLE #dept + + CREATE TABLE #emp (EmployeeID INT, ProviderID INT, ProviderTypeID INT, ProviderSpecialtyID INT) + CREATE TABLE #dept (DepartmentID INT, EntityID INT, UseProvider BIT) + + DECLARE @IsProviderTypeDisabled BIT; + SELECT @IsProviderTypeDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderTypeID' AND PlanSectionID = 3 AND SubsectionID = 1 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + + DECLARE @IsProviderSpecialtyDisabled BIT; + SELECT @IsProviderSpecialtyDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderSpecialtyID' AND PlanSectionID = 3 AND SubSectionID = 1 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + -- NOTE: THIS SHOULD MATCH WHAT IS PULLED FROM STAFFING DOLLARS SAMPLING TO GET THE DOLLARS. THIS IS BECAUSE + -- WE CAN GET DOLLARS FROM MULTIPLE PLACES AND NEED TO MAKE SURE WE'RE GRABBING EVERYTHING CORRECTLY. + + -- Get all departments that use Provider Staffing + -- Get all employees that are providers + -- (not doing this step for anything other than dollars yet) Sample provider data from int.FactStaffing for employees in departments that are configured to use provider sampling + -- Sample regular data for non provider employees and departments that are not configured to use provider sampling + + IF @SampleProviderEitherFromStaffingOrProviderIntTable = 0 + BEGIN + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT staff.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #departmentsConfiguredToFlex fcm ON config.DepartmentID = fcm.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = staff.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON staff.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @StaffingFiscalYearID AND staff.TimeclassID = @StaffingTimeClassID + AND staff.IsDeleted = 0 + AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND staff.UnitTypeID = 34 + UNION + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #departmentsConfiguredToFlex fcm ON config.DepartmentID = fcm.DepartmentID + INNER JOIN #FilterByDepartment tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @StaffingFiscalYearID AND prov.TimeclassID = @StaffingTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND prov.UnitTypeID = 34 + + -- 2. all employees that are providers + INSERT INTO #emp (EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID) + SELECT DISTINCT + emp.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #departmentsConfiguredToFlex fcm ON config.DepartmentID = fcm.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID + INNER JOIN [dss].[DimPhysician] phys ON emp.NPI = phys.NPI + INNER JOIN #FilterByDepartment tmp on staff.DepartmentID = tmp.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @StaffingFiscalYearID AND staff.TimeclassID = @StaffingTimeClassID + AND staff.IsDeleted = 0 + AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND staff.EmployeeID > 0 + AND staff.UnitTypeID = 34 + AND emp.NPI NOT IN ('Not Specified', '0', '') + UNION + SELECT DISTINCT + phys.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #departmentsConfiguredToFlex fcm ON config.DepartmentID = fcm.DepartmentID + INNER JOIN #FilterByDepartment tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + LEFT JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @StaffingFiscalYearID AND prov.TimeclassID = @StaffingTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND prov.UnitTypeID = 34 + AND phys.NPI NOT IN ('Not Specified', '0', '') + + -- Provider from int.FactProvider + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, Value) + SELECT + DISTINCT + fp.DepartmentID, + 0 as JobCodeID, + 0 as PayCodeGroupID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + fp.ProviderLineItemID, + SUM(ISNULL(fp.Value, 0)) as Value + FROM + [int].[FactProvider] fp + INNER JOIN #staffingConfiguredToFlex fcm ON fp.DepartmentID = fcm.DepartmentID AND fp.ProviderLineItemID = fcm.ProviderLineItemID -- We only want the things configured to flex + INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + WHERE + fp.FiscalYearID = @StaffingFiscalYearID + AND fp.TimeclassID = @StaffingTimeClassID + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + AND fp.IsDeleted = 0 + AND fp.FiscalMonthID != 0 + AND fp.UnitTypeID = 34 + AND ps.Description = 'Staffing' + GROUP BY fp.DepartmentID, emp.EmployeeID, + emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID + + INSERT INTO #provDims (DepartmentID, ProviderID, ProviderLineItemID) SELECT DISTINCT DepartmentID, ProviderID, ProviderLineItemID FROM #TempIntStaffingData + + -- Provider from int.FactStaffing + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, Value) + SELECT + DISTINCT + src.DepartmentID, + src.JobCodeID, + pcg.PayCodeGroupID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + pc.ProviderLineItemID, + SUM(ISNULL(src.Value, 0)) as Value + FROM + [int].[FactStaffing] src + INNER JOIN #dept dept ON src.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON src.EmployeeID = emp.EmployeeID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON src.PayCodeID = pc.PayCodeID + INNER JOIN #staffingConfiguredToFlex fcm ON src.DepartmentID = fcm.DepartmentID AND pc.ProviderLineItemID = fcm.ProviderLineItemID -- We only want the things configured to flex + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + LEFT JOIN #provDims pd ON src.DepartmentID = pd.DepartmentID AND emp.ProviderID = pd.ProviderID and pd.ProviderLineItemID = pli.ProviderLineItemID + WHERE + src.FiscalYearID = @StaffingFiscalYearID + AND src.TimeclassID = @StaffingTimeClassID + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 34 + AND pc.IsDollarsIgnored = 0 + AND ps.Description = 'Staffing' + AND pd.DepartmentID IS NULL + GROUP BY src.DepartmentID, + src.JobCodeID, + pcg.PayCodeGroupID, + emp.EmployeeID, + emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID + + END ELSE BEGIN + IF @UseProviderSource = 0 + BEGIN + + ------------------------------------------------------- + -- BudgetConfig UseProviderSource is disabled + ------------------------------------------------------- + + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT staff.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #departmentsConfiguredToFlex fcm ON config.DepartmentID = fcm.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = staff.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON staff.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @StaffingFiscalYearID AND staff.TimeclassID = @StaffingTimeClassID + AND staff.IsDeleted = 0 + AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND staff.UnitTypeID = 34 + + INSERT INTO #emp (EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID) + SELECT DISTINCT + emp.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #departmentsConfiguredToFlex fcm ON config.DepartmentID = fcm.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID + INNER JOIN [dss].[DimPhysician] phys ON emp.NPI = phys.NPI + INNER JOIN #FilterByDepartment tmp on staff.DepartmentID = tmp.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @StaffingFiscalYearID AND staff.TimeclassID = @StaffingTimeClassID + AND staff.IsDeleted = 0 + AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND staff.EmployeeID > 0 + AND staff.UnitTypeID = 34 + AND emp.NPI NOT IN ('Not Specified', '0', '') + + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, Value) + SELECT + DISTINCT + src.DepartmentID, + src.JobCodeID, + pcg.PayCodeGroupID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + pc.ProviderLineItemID, + SUM(ISNULL(src.Value, 0)) as Value + FROM + [int].[FactStaffing] src + INNER JOIN #dept dept ON src.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON src.EmployeeID = emp.EmployeeID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON src.PayCodeID = pc.PayCodeID + INNER JOIN #staffingConfiguredToFlex fcm ON src.DepartmentID = fcm.DepartmentID AND pc.ProviderLineItemID = fcm.ProviderLineItemID -- We only want the things configured to flex + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + WHERE + src.FiscalYearID = @StaffingFiscalYearID + AND src.TimeclassID = @StaffingTimeClassID + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 34 + AND pc.IsDollarsIgnored = 0 + AND ps.Description = 'Staffing' + GROUP BY src.DepartmentID, + src.JobCodeID, + pcg.PayCodeGroupID, + emp.EmployeeID, + emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID + + END ELSE BEGIN + + ------------------------------------------------------- + -- BudgetConfig UseProviderSource is enabled + ------------------------------------------------------- + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #departmentsConfiguredToFlex fcm ON config.DepartmentID = fcm.DepartmentID + INNER JOIN #FilterByDepartment tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @StaffingFiscalYearID AND prov.TimeclassID = @StaffingTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND prov.UnitTypeID = 34 + + -- 2. all employees that are providers + INSERT INTO #emp (EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID) + SELECT DISTINCT + phys.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #departmentsConfiguredToFlex fcm ON config.DepartmentID = fcm.DepartmentID + INNER JOIN #FilterByDepartment tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + LEFT JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @StaffingFiscalYearID AND prov.TimeclassID = @StaffingTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND prov.UnitTypeID = 34 + AND phys.NPI NOT IN ('Not Specified', '0', '') + + -- Provider from int.FactProvider + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, Value) + SELECT + DISTINCT + fp.DepartmentID, + 0 as JobCodeID, + 0 as PayCodeGroupID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + fp.ProviderLineItemID, + SUM(ISNULL(fp.Value, 0)) as Value + FROM + [int].[FactProvider] fp + INNER JOIN #staffingConfiguredToFlex fcm ON fp.DepartmentID = fcm.DepartmentID AND fp.ProviderLineItemID = fcm.ProviderLineItemID -- We only want the things configured to flex + INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + WHERE + fp.FiscalYearID = @StaffingFiscalYearID + AND fp.TimeclassID = @StaffingTimeClassID + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + AND fp.IsDeleted = 0 + AND fp.FiscalMonthID != 0 + AND fp.UnitTypeID = 34 + AND ps.Description = 'Staffing' + GROUP BY fp.DepartmentID, emp.EmployeeID, + emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID + END + END + -- Get any of the variable dollars, we don't care about fixed dollars for this. This should already be filtered to Variable based on the join with + -- flex config mapping. + INSERT INTO #IntStaffingData + SELECT DepartmentID, JobCodeID, PayCodeGroupID, + CASE WHEN @IsEmployeeBudgeting = 0 AND ProviderID = 0 THEN 0 ELSE EmployeeID END AS EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SUM(ISNULL(Value, 0)) AS BudgetDollarTotal + FROM #TempIntStaffingData + GROUP BY DepartmentID, JobCodeID, PayCodeGroupID, ProviderID, + ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, + CASE WHEN @IsEmployeeBudgeting = 0 AND ProviderID = 0 THEN 0 ELSE EmployeeID END + + IF @IsDebug = 1 + BEGIN + + SELECT @UsePriorYear AS '@UsePriorYear', @UseActualYTD AS '@UseActualYTD', @UseCurrentYearBudget AS '@UseCurrentYearBudget' + SELECT '#FilterByDepartment', * FROM #FilterByDepartment + SELECT '#flexConfigMapping', * FROM #flexConfigMapping + SELECT '#staffingConfiguredToFlex', * FROM #staffingConfiguredToFlex + SELECT '#departmentsConfiguredToFlex', * FROM #departmentsConfiguredToFlex + SELECT '#uniqueStatMapping', * FROM #uniqueStatMapping + SELECT '#statsBudget', * FROM #statsBudget + SELECT '#dept', * FROM #dept + SELECT '#emp', * FROM #emp + SELECT '#provDims', * FROM #provDims + SELECT '#TempIntStaffingData', * FROM #TempIntStaffingData + SELECT '#IntStaffingData', * FROM #IntStaffingData + + SELECT staffing.DepartmentID, staffing.JobCodeID, staffing.PayCodeGroupID, staffing.ProviderID, + staffing.ProviderTypeID, staffing.ProviderSpecialtyID, staffing.ProviderLineItemID, staffing.EmployeeID, + COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) AS Calculation, + staffing.BudgetDollarTotal AS BudgetDollarTotal, + stat.StatTotal AS StatTotal + FROM [fp].[Staffing] fs + INNER JOIN #IntStaffingData staffing ON + staffing.DepartmentID = fs.DepartmentID + AND staffing.JobCodeID = fs.JobCodeID + AND staffing.PayCodeGroupID = FS.PayCodeGroupID + AND staffing.ProviderID = fs.ProviderID + AND staffing.ProviderTypeID = fs.ProviderTypeID + AND staffing.ProviderSpecialtyID = fs.ProviderSpecialtyID + AND staffing.ProviderLineItemID = fs.ProviderLineItemID + AND staffing.EmployeeID = fs.EmployeeID + INNER JOIN #statsBudget stat + ON stat.DepartmentID = fs.DepartmentID + AND stat.ProviderID = fs.ProviderID + AND stat.ProviderLineItemID = fs.ProviderLineItemID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID + + END ELSE BEGIN + + -- set the Dollars/UOS values on Staffing table + UPDATE + fs + SET + InitialBudgetRate01 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate02 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate03 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate04 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate05 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate06 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate07 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate08 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate09 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate10 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate11 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate12 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + + + -- Projection rates should match the budget rates and use the budget baseline to calculate + InitialProjectionRate01 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate02 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate03 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate04 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate05 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate06 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate07 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate08 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate09 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate10 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate11 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate12 = COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) + FROM [fp].[Staffing] fs + INNER JOIN #IntStaffingData staffing ON + staffing.DepartmentID = fs.DepartmentID + AND staffing.JobCodeID = fs.JobCodeID + AND staffing.PayCodeGroupID = FS.PayCodeGroupID + AND staffing.ProviderID = fs.ProviderID + AND staffing.ProviderTypeID = fs.ProviderTypeID + AND staffing.ProviderSpecialtyID = fs.ProviderSpecialtyID + AND staffing.ProviderLineItemID = fs.ProviderLineItemID + AND staffing.EmployeeID = fs.EmployeeID + INNER JOIN #statsBudget stat + ON stat.DepartmentID = fs.DepartmentID + AND stat.ProviderID = fs.ProviderID + AND stat.ProviderLineItemID = fs.ProviderLineItemID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID + AND ( + + fs.InitialBudgetRate01 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate02 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate03 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate04 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate05 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate06 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate07 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate08 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate09 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate10 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate11 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate12 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate01 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate02 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate03 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate04 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate05 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate06 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate07 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate08 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate09 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate10 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate11 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate12 != COALESCE(staffing.BudgetDollarTotal/NULLIF(stat.StatTotal, 0), 0)) + + END + +END +GO + + +--------------------------------------------- + +-- fp.procSampleStaffingFTE +CREATE PROCEDURE [fp].[procSampleStaffingFTE] + @EntityGroupConfigID int, + @FiscalYearID int, + @ProjectionFiscalYearID int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +WITH RECOMPILE +AS +BEGIN +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-02-16 BK JAZZ-50052 Update to copy SampledProjecton to InitialProjection for MonthsNotLoaded when baseline is Current Year Budget + ** instead of getting average of MonthsNotLoaded dollars and hours and flattening the wage rate + ** 2 2023-09-20 BK JAZZ-60973 Update for new data structure + *************************************************************/ + + +CREATE TABLE #filterTable (DepartmentID int) + INSERT INTO #filterTable (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #filterTable (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fp.Staffing + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + IF OBJECT_ID('tempdb..#StaffFteTotal') IS NOT NULL DROP TABLE #StaffFteTotal + + DECLARE @MonthsLoaded INT, @StaffingTimeClassID INT, @StaffingFiscalYearID INT; + + SELECT @MonthsLoaded = MonthsLoaded, @StaffingTimeClassID = PayrollTimeClassID, @StaffingFiscalYearID = PayrollFiscalYearID + FROM fp.EntityGroupConfig egc + INNER JOIN fp.BudgetConfig bc on egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE EntityGroupConfigID = @EntityGroupConfigID + + + UPDATE fte SET + fte.SampledBudgetFTEs01 = fte.SampledBudgetHours01 / wh.Month01 + , fte.SampledBudgetFTEs02 = fte.SampledBudgetHours02 / wh.Month02 + , fte.SampledBudgetFTEs03 = fte.SampledBudgetHours03 / wh.Month03 + , fte.SampledBudgetFTEs04 = fte.SampledBudgetHours04 / wh.Month04 + , fte.SampledBudgetFTEs05 = fte.SampledBudgetHours05 / wh.Month05 + , fte.SampledBudgetFTEs06 = fte.SampledBudgetHours06 / wh.Month06 + , fte.SampledBudgetFTEs07 = fte.SampledBudgetHours07 / wh.Month07 + , fte.SampledBudgetFTEs08 = fte.SampledBudgetHours08 / wh.Month08 + , fte.SampledBudgetFTEs09 = fte.SampledBudgetHours09 / wh.Month09 + , fte.SampledBudgetFTEs10 = fte.SampledBudgetHours10 / wh.Month10 + , fte.SampledBudgetFTEs11 = fte.SampledBudgetHours11 / wh.Month11 + , fte.SampledBudgetFTEs12 = fte.SampledBudgetHours12 / wh.Month12 + + , fte.InitialBudgetFTEs01 = fte.InitialBudgetHours01 / wh.Month01 + , fte.InitialBudgetFTEs02 = fte.InitialBudgetHours02 / wh.Month02 + , fte.InitialBudgetFTEs03 = fte.InitialBudgetHours03 / wh.Month03 + , fte.InitialBudgetFTEs04 = fte.InitialBudgetHours04 / wh.Month04 + , fte.InitialBudgetFTEs05 = fte.InitialBudgetHours05 / wh.Month05 + , fte.InitialBudgetFTEs06 = fte.InitialBudgetHours06 / wh.Month06 + , fte.InitialBudgetFTEs07 = fte.InitialBudgetHours07 / wh.Month07 + , fte.InitialBudgetFTEs08 = fte.InitialBudgetHours08 / wh.Month08 + , fte.InitialBudgetFTEs09 = fte.InitialBudgetHours09 / wh.Month09 + , fte.InitialBudgetFTEs10 = fte.InitialBudgetHours10 / wh.Month10 + , fte.InitialBudgetFTEs11 = fte.InitialBudgetHours11 / wh.Month11 + , fte.InitialBudgetFTEs12 = fte.InitialBudgetHours12 / wh.Month12 + --- + , fte.SampledProjectionFTEs01 = fte.SampledProjectionHours01 / pwh.Month01 + , fte.SampledProjectionFTEs02 = fte.SampledProjectionHours02 / pwh.Month02 + , fte.SampledProjectionFTEs03 = fte.SampledProjectionHours03 / pwh.Month03 + , fte.SampledProjectionFTEs04 = fte.SampledProjectionHours04 / pwh.Month04 + , fte.SampledProjectionFTEs05 = fte.SampledProjectionHours05 / pwh.Month05 + , fte.SampledProjectionFTEs06 = fte.SampledProjectionHours06 / pwh.Month06 + , fte.SampledProjectionFTEs07 = fte.SampledProjectionHours07 / pwh.Month07 + , fte.SampledProjectionFTEs08 = fte.SampledProjectionHours08 / pwh.Month08 + , fte.SampledProjectionFTEs09 = fte.SampledProjectionHours09 / pwh.Month09 + , fte.SampledProjectionFTEs10 = fte.SampledProjectionHours10 / pwh.Month10 + , fte.SampledProjectionFTEs11 = fte.SampledProjectionHours11 / pwh.Month11 + , fte.SampledProjectionFTEs12 = fte.SampledProjectionHours12 / pwh.Month12 + + FROM [fp].[Staffing] fte + INNER JOIN #filterTable tmp on fte.DepartmentID = tmp.DepartmentID + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fte.PayCodeGroupID = exc.PayCodeGroupID + INNER JOIN [fw].[DimJobCode] jc on fte.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on fte.DepartmentID = dept.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @FiscalYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + INNER JOIN [client].[FactWorkingHoursPerMonth] pwh on pwh.FiscalYearID = @ProjectionFiscalYearID and pwh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + WHERE fte.EntityGroupConfigID = @EntityGroupConfigID AND exc.PayCodeGroupID IS NULL + + + IF @StaffingTimeClassID = 2 AND @StaffingFiscalYearID = @ProjectionFiscalYearID BEGIN + -- Current Year Budget only + UPDATE fs + SET + InitialProjectionFTEs01 = fs.SampledProjectionFTEs01, + InitialProjectionFTEs02 = fs.SampledProjectionFTEs02, + InitialProjectionFTEs03 = fs.SampledProjectionFTEs03, + InitialProjectionFTEs04 = fs.SampledProjectionFTEs04, + InitialProjectionFTEs05 = fs.SampledProjectionFTEs05, + InitialProjectionFTEs06 = fs.SampledProjectionFTEs06, + InitialProjectionFTEs07 = fs.SampledProjectionFTEs07, + InitialProjectionFTEs08 = fs.SampledProjectionFTEs08, + InitialProjectionFTEs09 = fs.SampledProjectionFTEs09, + InitialProjectionFTEs10 = fs.SampledProjectionFTEs10, + InitialProjectionFTEs11 = fs.SampledProjectionFTEs11, + InitialProjectionFTEs12 = fs.SampledProjectionFTEs12 + FROM [fp].[Staffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + + END ELSE BEGIN + + CREATE TABLE #StaffFteTotal (StaffingID INT, SampledProjectionTotal DECIMAL(19,8), NewValue DECIMAL(19,8)) + + INSERT INTO #StaffFteTotal (StaffingID, SampledProjectionTotal) + SELECT fs.StaffingID, + CASE WHEN @MonthsLoaded = 11 THEN fs.SampledProjectionFTEs12 + WHEN @MonthsLoaded = 10 THEN fs.SampledProjectionFTEs11 + fs.SampledProjectionFTEs12 + WHEN @MonthsLoaded = 9 THEN fs.SampledProjectionFTEs10 + fs.SampledProjectionFTEs11 + fs.SampledProjectionFTEs12 + WHEN @MonthsLoaded = 8 THEN fs.SampledProjectionFTEs09 + fs.SampledProjectionFTEs10 + fs.SampledProjectionFTEs11 + fs.SampledProjectionFTEs12 + WHEN @MonthsLoaded = 7 THEN fs.SampledProjectionFTEs08 + fs.SampledProjectionFTEs09 + fs.SampledProjectionFTEs10 + fs.SampledProjectionFTEs11 + fs.SampledProjectionFTEs12 + WHEN @MonthsLoaded = 6 THEN fs.SampledProjectionFTEs07 + fs.SampledProjectionFTEs08 + fs.SampledProjectionFTEs09 + fs.SampledProjectionFTEs10 + fs.SampledProjectionFTEs11 + fs.SampledProjectionFTEs12 + WHEN @MonthsLoaded = 5 THEN fs.SampledProjectionFTEs06 + fs.SampledProjectionFTEs07 + fs.SampledProjectionFTEs08 + fs.SampledProjectionFTEs09 + fs.SampledProjectionFTEs10 + fs.SampledProjectionFTEs11 + fs.SampledProjectionFTEs12 + WHEN @MonthsLoaded = 4 THEN fs.SampledProjectionFTEs05 + fs.SampledProjectionFTEs06 + fs.SampledProjectionFTEs07 + fs.SampledProjectionFTEs08 + fs.SampledProjectionFTEs09 + fs.SampledProjectionFTEs10 + fs.SampledProjectionFTEs11 + fs.SampledProjectionFTEs12 + WHEN @MonthsLoaded = 3 THEN fs.SampledProjectionFTEs04 + fs.SampledProjectionFTEs05 + fs.SampledProjectionFTEs06 + fs.SampledProjectionFTEs07 + fs.SampledProjectionFTEs08 + fs.SampledProjectionFTEs09 + fs.SampledProjectionFTEs10 + fs.SampledProjectionFTEs11 + fs.SampledProjectionFTEs12 + + WHEN @MonthsLoaded = 2 THEN fs.SampledProjectionFTEs03 + fs.SampledProjectionFTEs04 + fs.SampledProjectionFTEs05 + fs.SampledProjectionFTEs06 + fs.SampledProjectionFTEs07 + fs.SampledProjectionFTEs08 + fs.SampledProjectionFTEs09 + fs.SampledProjectionFTEs10 + fs.SampledProjectionFTEs11 + + fs.SampledProjectionFTEs12 + WHEN @MonthsLoaded = 1 THEN fs.SampledProjectionFTEs02 + fs.SampledProjectionFTEs03 + fs.SampledProjectionFTEs04 + fs.SampledProjectionFTEs05 + fs.SampledProjectionFTEs06 + fs.SampledProjectionFTEs07 + fs.SampledProjectionFTEs08 + fs.SampledProjectionFTEs09 + fs.SampledProjectionFTEs10 + + fs.SampledProjectionFTEs11 + fs.SampledProjectionFTEs12 + ELSE 0 + END + FROM [fp].[Staffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fs.PayCodeGroupID = exc.PayCodeGroupID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND exc.PayCodeGroupID IS NULL + + + UPDATE a SET NewValue = SampledProjectionTotal / (12.0 - @MonthsLoaded) + FROM #StaffFteTotal a + + -- update the initial projection values + UPDATE + fs + SET + InitialProjectionFTEs01 = CASE WHEN @MonthsLoaded >= 1 THEN SampledProjectionFTEs01 ELSE NewValue END, + InitialProjectionFTEs02 = CASE WHEN @MonthsLoaded >= 2 THEN SampledProjectionFTEs02 ELSE NewValue END, + InitialProjectionFTEs03 = CASE WHEN @MonthsLoaded >= 3 THEN SampledProjectionFTEs03 ELSE NewValue END, + InitialProjectionFTEs04 = CASE WHEN @MonthsLoaded >= 4 THEN SampledProjectionFTEs04 ELSE NewValue END, + InitialProjectionFTEs05 = CASE WHEN @MonthsLoaded >= 5 THEN SampledProjectionFTEs05 ELSE NewValue END, + InitialProjectionFTEs06 = CASE WHEN @MonthsLoaded >= 6 THEN SampledProjectionFTEs06 ELSE NewValue END, + InitialProjectionFTEs07 = CASE WHEN @MonthsLoaded >= 7 THEN SampledProjectionFTEs07 ELSE NewValue END, + InitialProjectionFTEs08 = CASE WHEN @MonthsLoaded >= 8 THEN SampledProjectionFTEs08 ELSE NewValue END, + InitialProjectionFTEs09 = CASE WHEN @MonthsLoaded >= 9 THEN SampledProjectionFTEs09 ELSE NewValue END, + InitialProjectionFTEs10 = CASE WHEN @MonthsLoaded >= 10 THEN SampledProjectionFTEs10 ELSE NewValue END, + InitialProjectionFTEs11 = CASE WHEN @MonthsLoaded >= 11 THEN SampledProjectionFTEs11 ELSE NewValue END, + InitialProjectionFTEs12 = CASE WHEN @MonthsLoaded >= 12 THEN SampledProjectionFTEs12 ELSE NewValue END + FROM [fp].[Staffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + INNER JOIN #StaffFteTotal IPA ON IPA.StaffingID = fs.StaffingID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + END + +END +GO + + +--------------------------------------------- + +-- fp.procSampleStaffingHistoricalData +CREATE PROCEDURE [fp].[procSampleStaffingHistoricalData] + @EntityGroupConfigGUID uniqueidentifier, + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @MonthsLoaded int, + @IsEmployeeBudgeting bit, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 4 2021-03-22 NT JAZZ-15374 Use NPI instead of EmployeID for Provider Comp Sampling +** 5 2021-06-30 BW JAZZ-21627 Update selects and group by for EmployeID for variablity +** 6 2021-12-01 OP JAZZ-29466 removed empty users check for prov comp data +** 7 2022-01-12 OP JAZZ-30834 sample provider data +** 8 2022-02-09 BK JAZZ-33248 respect department setting for employee budgeting +** 9 2022-03-02 MZ JAZZ-30547 improved checks in order to sample valid Employees with valid NPI +** 10 2022-03-18 AO JAZZ-33623 hours always sample fixed +** 11 2022-06-30 MY JAZZ-39047 Added Option Recompile +** 12 2022-08-08 BK JAZZ-38357 make sure IsFP records are sampled to correct Subsection +** 13 2022-09-13 MZ JAZZ-41652 Restricted Prov Comp Wage Rate sampling +** 14 2022-10-07 AO JAZZ-42868 Non-provider department samples correct Actual YTD staffing values when provider sampling feature is turned on. +** 15 2022-11-07 MZ JAZZ-35344 improved checks in order to sample valid Employees with valid NPI from FactProvider +** 16 2022-11-07 MY JAZZ-35951 Add EmployeeID to FactStaffingVariabilityDetail +** 17 2022-12-12 DM JAZZ-46455 Samplimg of Provider Type and Provider Specialty is linked to Section Setup +** 18 2023-04-11 MZ JAZZ-53130 Used NPI for PY Actuals and CY Budget instead of EmployeeID as a join to DimPhysician +** 19 2023-09-26 BK JAZZ-61239 Fix variable dept/job code incorrectly ignoring data that has EmployeeID in int.FactStaffing +** 20 2023-09-30 BK JAZZ-60973 Update for new data structure +** 21 2023-12-07 NT JAZZ-64522 Fix column CurrentBudgetFTE column names +** 22 2023-12-26 NH/NT JAZZ-64324 Remove 'Use Hours and FTE on Provider Compensation' (doing this in restructure branch on behalf of Softserve) +** 23 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config +** 24 2024-03-25 MY JAZZ-69661 Duplicated data for non-Provider departments in client dbs who utilize Provider Planning +** 25 2024-06-19 AO JAZZ-72231 Added Source Provider Sampling +*************************************************************/ + + CREATE TABLE #filterTable (DepartmentID int) + INSERT INTO #filterTable (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #filterTable (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fp.Staffing + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + INSERT INTO [fp].[StaffingHistory] ([StaffingID]) + SELECT [fs].[StaffingID] + FROM [fp].[Staffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND IsNew = 0 + + IF OBJECT_ID('tempdb..#IntStaffingDataRolledUp') IS NOT NULL DROP TABLE #IntStaffingDataRolledUp + IF OBJECT_ID('tempdb..#IntStaffingDataRolledUpRaw') IS NOT NULL DROP TABLE #IntStaffingDataRolledUpRaw + IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolved') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolved + IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolvedForProviderCurrentYearActuals') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolvedForProviderCurrentYearActuals + IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolvedForProviderPriorYearActuals') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolvedForProviderPriorYearActuals + IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolvedForProviderCurrentYearBudget') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolvedForProviderCurrentYearBudget + + CREATE TABLE #IntStaffingDataRolledUpRaw ( + DepartmentID int, + JobCodeID int, + PayCodeGroupID int, + EmployeeID int, + UnitTypeID int, + ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int, + MonthColumnName varchar(50), + FixedPercentage decimal(38,6), + Value decimal (19,4) + ) + + CREATE TABLE #IntStaffingDataRolledUp ( + DepartmentID int, + JobCodeID int, + PayCodeGroupID int, + EmployeeID int, + UnitTypeID int, + ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int, + MonthColumnName varchar(50), + FixedPercentage decimal(38,6), + Value decimal (19,4) + ) + + IF OBJECT_ID('tempdb..#emp') IS NOT NULL DROP TABLE #emp + IF OBJECT_ID('tempdb..#dept') IS NOT NULL DROP TABLE #dept + IF OBJECT_ID('tempdb..#provDims') IS NOT NULL DROP TABLE #provDims + + CREATE TABLE #emp (DepartmentID INT, EmployeeID INT, ProviderID INT, ProviderTypeID INT, ProviderSpecialtyID INT, IsFP BIT) + CREATE TABLE #dept (DepartmentID INT, EntityID INT, UseProvider BIT) + CREATE TABLE #provDims (DepartmentID INT, ProviderID INT, ProviderLineItemID INT) + + DECLARE @StaffingSubsectionID INT = 3; + DECLARE @ProviderSubsectionID INT = 4; + + DECLARE @BudgetConfigID INT = (SELECT BudgetConfigID FROM fp.EntityGroupConfig a INNER JOIN fp.BudgetConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID) + + DECLARE @IsProviderPlanningEnabled BIT; + DECLARE @UseProviderSource BIT; + DECLARE @SampleProviderEitherFromStaffingOrProviderIntTable BIT; + + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled, @UseProviderSource = UseProviderSource FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID; + + SELECT @SampleProviderEitherFromStaffingOrProviderIntTable = Value FROM fp.BudgetConfigSetting bcs + INNER JOIN fp.BudgetConfigDefaultSetting bcds ON bcs.SettingID = bcds.SettingID + WHERE Name = 'Sample Provider either from Staffing or Provider int tables' AND BudgetConfigID = @BudgetConfigID + + DECLARE @IsProviderTypeDisabled BIT; + SELECT @IsProviderTypeDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderTypeID' AND PlanSectionID = 3 AND SubSectionID = 1 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + + DECLARE @IsProviderSpecialtyDisabled BIT; + SELECT @IsProviderSpecialtyDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderSpecialtyID' AND PlanSectionID = 3 AND SubSectionID = 1 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + -- JAZZ-69661: Duplicated data for non-Provider departments in client dbs who utilize Provider Planning + DECLARE @EnableDepartmentLevelProviderForSampling BIT = ISNULL((SELECT 1 + FROM fp.BudgetConfigSetting setting + INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON setting.SettingID = def.SettingID + WHERE def.Name = 'Enable Department Level Provider For Sampling' + AND setting.BudgetConfigID = @BudgetConfigID + AND setting.Value = 1), 0) + + IF @IsProviderPlanningEnabled = 0 + BEGIN + + ---------------------------------------------------- + -- Provider is disabled + ---------------------------------------------------- + + -- Resolve EmployeeID up front so we don't have to do it every time. + SELECT + src.DepartmentID, + src.JobCodeID, + src.PayCodeID, + pc.PayCodeGroupID, + pc.IsDollarsIgnored, + pc.IsHoursIgnored, + CASE + WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 + ELSE CASE + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE src.EmployeeID + END + END as EmployeeID, + 0 AS ProviderID, + 0 AS ProviderTypeID, + 0 AS ProviderSpecialtyID, + 0 AS ProviderLineItemID, + src.FiscalYearID, + src.TimeClassID, + src.UnitTypeID, + src.FiscalMonthID, + fm.MonthColumnName, + fm.SortOrder, + src.IsDeleted, + Value + INTO #intFactStaffingWithEmployeeResolved + FROM [int].[FactStaffing] src + INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = src.PayCodeID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND CASE WHEN @IsEmployeeBudgeting = 0 OR ISNULL(sefg.IsUsingEmployeeBudgeting, 0) = 0 THEN 0 -- When not using EB, we can just set it to 0. + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not. + END = fv.EmployeeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE 1 = 1 + AND ( -- Need all 3 for the different time class/years we sample in. This is used more than just the following statement + (src.FiscalYearID = @CurrentFiscalYearID AND src.TimeClassID = 1) OR + (src.FiscalYearID = @CurrentFiscalYearID - 1 AND src.TimeClassID = 1) OR + (src.FiscalYearID = @CurrentFiscalYearID AND src.TimeClassID = 2) + ) + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + + INSERT INTO #IntStaffingDataRolledUpRaw + (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + hist.DepartmentID, + hist.JobCodeID, + hist.PayCodeGroupID, + hist.EmployeeID, + hist.UnitTypeID, + 0 as ProviderID, + 0 as ProviderTypeID, + 0 as ProviderSpecialtyID, + 0 as ProviderLineItemID, + 3 as SubsectionID, + hist.MonthColumnName, + ISNULL(fv.FixedPercentage,1) as FixedPercentage, + SUM(ISNULL(hist.Value, 0)) as Value + FROM #intFactStaffingWithEmployeeResolved hist + INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = hist.DepartmentID + AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv ON fv.DepartmentID = hist.DepartmentID + AND fv.JobCodeID = hist.JobCodeID + AND fv.PayCodeID = hist.PayCodeID + AND fv.EmployeeID = hist.EmployeeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE hist.FiscalYearID = @CurrentFiscalYearID + AND hist.TimeClassID = 1 + AND hist.SortOrder <= @MonthsLoaded + AND ((hist.UnitTypeID = 34 AND hist.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND hist.IsHoursIgnored = 0)) + GROUP BY hist.DepartmentID, + hist.JobCodeID, + hist.PayCodeGroupID, + hist.EmployeeID, + hist.UnitTypeID, + hist.MonthColumnName, + FixedPercentage + END ELSE + BEGIN + + ---------------------------------------------------- + -- Provider is enabled + ---------------------------------------------------- + IF @SampleProviderEitherFromStaffingOrProviderIntTable = 0 + BEGIN + + ------------------------------------------------------- + -- BudgetConfigSetting is disabled + ------------------------------------------------------- + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + UNION + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later + + -- 2. all employees that are providers + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END, + emp.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID + INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID + INNER JOIN [dss].[DimPhysician] phys ON phys.NPI = emp.NPI + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND staff.EmployeeID > 0 + AND emp.NPI NOT IN ('Not Specified', '0', '') + UNION + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, + phys.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID + INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND phys.NPI NOT IN ('Not Specified', '0', '') + AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later + + -- Provider from int.FactProvider + INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + fp.DepartmentID, + 0 as JobCodeID, + 0 as PayCodeGroupID, + 0 as EmployeeID, + fp.UnitTypeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + fp.ProviderLineItemID, + @ProviderSubsectionID, + fm.MonthColumnName, + 1 as FixedPercentage, + CASE WHEN fp.UnitTypeID = 34 OR UnitTypeID = 51 THEN SUM(ISNULL(fp.Value, 0)) ELSE 0 END AS Value + FROM + [int].[FactProvider] fp + INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + WHERE + fp.FiscalYearID = @CurrentFiscalYearID + AND fp.TimeClassID = 1 + AND fp.IsDeleted = 0 + AND fp.FiscalMonthID != 0 + AND fm.SortOrder <= @MonthsLoaded + AND ps.Description = 'Staffing' + AND emp.IsFP = 1 + AND fp.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later + GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName, fp.UnitTypeID, + emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID + + INSERT INTO #provDims (DepartmentID, ProviderID, ProviderLineItemID) SELECT DISTINCT DepartmentID, ProviderID, ProviderLineItemID FROM #IntStaffingDataRolledUpRaw + + -- Provider from int.FactStaffing + INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + hist.DepartmentID, + hist.JobCodeID, + pc.PayCodeGroupID, + 0 as EmployeeID, + hist.UnitTypeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + pc.ProviderLineItemID, + @ProviderSubsectionID, + fm.MonthColumnName, + CASE WHEN hist.UnitTypeID = 34 THEN ISNULL(fv.FixedPercentage,1) WHEN hist.UnitTypeID = 51 THEN 1 ELSE 0 END AS FixedPercentage, + CASE WHEN hist.UnitTypeID = 34 OR hist.UnitTypeID = 51 THEN SUM(ISNULL(hist.Value, 0)) ELSE 0 END AS Value + FROM [int].[FactStaffing] hist + INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID + INNER JOIN #dept dept ON hist.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON hist.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR hist.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = hist.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON hist.PayCodeID = pc.PayCodeID + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID + AND fv.JobCodeID = hist.JobCodeID + AND fv.PayCodeID = hist.PayCodeID + AND fv.EmployeeID = 0 + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN #provDims pd ON hist.DepartmentID = pd.DepartmentID + AND emp.ProviderID = pd.ProviderID + AND pd.ProviderLineItemID = pli.ProviderLineItemID + WHERE hist.FiscalYearID = @CurrentFiscalYearID AND hist.TimeClassID = 1 AND hist.IsDeleted = 0 AND hist.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded + AND ((hist.UnitTypeID = 34 AND pc.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND pc.IsHoursIgnored = 0)) + AND emp.IsFP = 1 + GROUP BY hist.DepartmentID, + hist.JobCodeID, + pc.PayCodeGroupID, + emp.EmployeeID, + hist.UnitTypeID, + fm.MonthColumnName, + FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID + + END ELSE BEGIN + + ------------------------------------------------------- + -- BudgetConfigSetting is enabled + ------------------------------------------------------- + IF @UseProviderSource = 0 + BEGIN + + ------------------------------------------------------- + -- BudgetConfig UseProviderSource is disabled + ------------------------------------------------------- + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use staffing + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + + -- 2. all employees from staffing + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END, + emp.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID + INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID + INNER JOIN [dss].[DimPhysician] phys ON phys.NPI = emp.NPI + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND staff.EmployeeID > 0 + AND emp.NPI NOT IN ('Not Specified', '0', '') + + INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + hist.DepartmentID, + hist.JobCodeID, + pc.PayCodeGroupID, + 0 as EmployeeID, + hist.UnitTypeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + pc.ProviderLineItemID, + @ProviderSubsectionID, + fm.MonthColumnName, + CASE WHEN hist.UnitTypeID = 34 THEN ISNULL(fv.FixedPercentage,1) WHEN hist.UnitTypeID = 51 THEN 1 ELSE 0 END AS FixedPercentage, + CASE WHEN hist.UnitTypeID = 34 OR hist.UnitTypeID = 51 THEN SUM(ISNULL(hist.Value, 0)) ELSE 0 END AS Value + FROM [int].[FactStaffing] hist + INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID + INNER JOIN #dept dept ON hist.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON hist.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR hist.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = hist.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON hist.PayCodeID = pc.PayCodeID + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID + AND fv.JobCodeID = hist.JobCodeID + AND fv.PayCodeID = hist.PayCodeID + AND fv.EmployeeID = 0 + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE hist.FiscalYearID = @CurrentFiscalYearID AND hist.TimeClassID = 1 AND hist.IsDeleted = 0 AND hist.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded + AND ((hist.UnitTypeID = 34 AND pc.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND pc.IsHoursIgnored = 0)) + AND emp.IsFP = 1 + GROUP BY hist.DepartmentID, + hist.JobCodeID, + pc.PayCodeGroupID, + emp.EmployeeID, + hist.UnitTypeID, + fm.MonthColumnName, + FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID + + END ELSE BEGIN + + ------------------------------------------------------- + -- BudgetConfig UseProviderSource is enabled + ------------------------------------------------------- + + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later + + -- 2. all employees that are providers + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, + phys.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID + INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND phys.NPI NOT IN ('Not Specified', '0', '') + AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later + + -- Provider from int.FactProvider + INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + fp.DepartmentID, + 0 as JobCodeID, + 0 as PayCodeGroupID, + 0 as EmployeeID, + fp.UnitTypeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + fp.ProviderLineItemID, + @ProviderSubsectionID, + fm.MonthColumnName, + 1 as FixedPercentage, + CASE WHEN fp.UnitTypeID = 34 OR UnitTypeID = 51 THEN SUM(ISNULL(fp.Value, 0)) ELSE 0 END AS Value + FROM + [int].[FactProvider] fp + INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + WHERE + fp.FiscalYearID = @CurrentFiscalYearID + AND fp.TimeClassID = 1 + AND fp.IsDeleted = 0 + AND fp.FiscalMonthID != 0 + AND fm.SortOrder <= @MonthsLoaded + AND ps.Description = 'Staffing' + AND emp.IsFP = 1 + AND fp.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later + GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName, fp.UnitTypeID, + emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID + + END + END + + -- Non-Provider from int.FactStaffing + -- Populate into a temp table before summing up to deal with issues with the dynamic employee join + SELECT + hist.DepartmentID, + hist.JobCodeID, + hist.PayCodeID, + pc.PayCodeGroupID, + CASE + WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 + ELSE CASE + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE hist.EmployeeID + END + END as EmployeeID, + hist.UnitTypeID, + 0 as ProviderID, + 0 as ProviderTypeID, + 0 as ProviderSpecialtyID, + 0 as ProviderLineItemID, + @StaffingSubsectionID as SubsectionID, + fm.MonthColumnName, + ISNULL(fv.FixedPercentage, 1) as FixedPercentage, + ISNULL(hist.Value, 0) as Value + INTO #intFactStaffingWithEmployeeResolvedForProviderCurrentYearActuals + FROM [int].[FactStaffing] hist + INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID + LEFT JOIN #dept dept ON hist.DepartmentID = dept.DepartmentID + LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 1) emp ON hist.EmployeeID = emp.EmployeeID + LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 0) NotFpEmp ON hist.EmployeeID = NotFpEmp.EmployeeID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = hist.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON hist.PayCodeID = pc.PayCodeID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = hist.DepartmentID + AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND fv.JobCodeID = hist.JobCodeID + AND fv.PayCodeID = hist.PayCodeID + AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0. + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE hist.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not. + END = fv.EmployeeID + WHERE hist.FiscalYearID = @CurrentFiscalYearID + AND hist.TimeClassID = 1 + AND hist.IsDeleted = 0 + AND hist.FiscalMonthID != 0 + AND fm.SortOrder <= @MonthsLoaded + AND ((hist.UnitTypeID = 34 AND pc.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND pc.IsHoursIgnored = 0)) + AND (dept.DepartmentID IS NULL OR (emp.EmployeeID IS NULL AND (NotFpEmp.EmployeeID IS NULL OR NotFpEmp.IsFP = 0))) + + -- Provider from int.FactStaffing + INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + hist.DepartmentID, + hist.JobCodeID, + hist.PayCodeGroupID, + hist.EmployeeID, + hist.UnitTypeID, + 0 as ProviderID, + 0 as ProviderTypeID, + 0 as ProviderSpecialtyID, + 0 as ProviderLineItemID, + @StaffingSubsectionID as SubsectionID, + hist.MonthColumnName, + ISNULL(fv.FixedPercentage, 1) as FixedPercentage, + SUM(ISNULL(hist.Value, 0)) as Value + FROM #intFactStaffingWithEmployeeResolvedForProviderCurrentYearActuals hist + INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = hist.DepartmentID + AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND fv.JobCodeID = hist.JobCodeID + AND fv.PayCodeID = hist.PayCodeID + AND fv.EmployeeID = hist.EmployeeID + GROUP BY hist.DepartmentID, + hist.JobCodeID, + hist.PayCodeGroupID, + hist.EmployeeID, + hist.UnitTypeID, + hist.MonthColumnName, + fv.FixedPercentage + END + + INSERT INTO #IntStaffingDataRolledUp + ( DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value + FROM #IntStaffingDataRolledUpRaw + WHERE FixedPercentage = 1 + + INSERT INTO #IntStaffingDataRolledUp + ( DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT DepartmentID, JobCodeID, PayCodeGroupID, CASE WHEN @IsEmployeeBudgeting = 1 AND ProviderID = 0 THEN 0 ELSE EmployeeID END AS EmployeeID, + UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, MAX(ISNULL(FixedPercentage, 1)), SUM(ISNULL(Value, 0)) + FROM #IntStaffingDataRolledUpRaw + WHERE FixedPercentage <> 1 + GROUP BY DepartmentID, JobCodeID, PayCodeGroupID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, + CASE WHEN @IsEmployeeBudgeting = 1 AND ProviderID = 0 THEN 0 ELSE EmployeeID END + + -- set all of the values for current year actual/annualized + UPDATE + fsh + SET + ActualYTDHours01 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month01, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month01, 0) + END, + ActualYTDHours02 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month02, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month02, 0) + END, + ActualYTDHours03 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month03, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month03, 0) + END, + ActualYTDHours04 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month04, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month04, 0) + END, + ActualYTDHours05 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month05, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month05, 0) + END, + ActualYTDHours06 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month06, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month06, 0) + END, + ActualYTDHours07 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month07, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month07, 0) + END, + ActualYTDHours08 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month08, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month08, 0) + END, + ActualYTDHours09 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month09, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month09, 0) + END, + ActualYTDHours10 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month10, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month10, 0) + END, + ActualYTDHours11 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month11, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month11, 0) + END, + ActualYTDHours12 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month12, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month12, 0) + END + FROM [fp].[StaffingHistory] fsh + INNER JOIN [fp].[Staffing] fs ON fs.StaffingID = fsh.StaffingID + INNER JOIN + (SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderSpecialtyID, ProviderLineItemID, ProviderTypeID, SubsectionID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingDataRolledUp) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.JobCodeID = pv.JobCodeID + AND fs.PayCodeGroupID = pv.PayCodeGroupID + AND fs.EmployeeID = pv.EmployeeID + AND fs.ProviderID = pv.ProviderID and fs.ProviderSpecialtyID = pv.ProviderSpecialtyID and fs.ProviderLineItemID = pv.ProviderLineItemID and fs.ProviderTypeID = pv.ProviderTypeID and fs.SubsectionID = pv.SubsectionID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND pv.UnitTypeID = 51 + + UPDATE + fsh + SET + ActualYTDDollars01 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month01, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month01, 0) + END, + ActualYTDDollars02 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month02, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month02, 0) + END, + ActualYTDDollars03 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month03, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month03, 0) + END, + ActualYTDDollars04 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month04, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month04, 0) + END, + ActualYTDDollars05 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month05, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month05, 0) + END, + ActualYTDDollars06 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month06, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month06, 0) + END, + ActualYTDDollars07 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month07, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month07, 0) + END, + ActualYTDDollars08 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month08, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month08, 0) + END, + ActualYTDDollars09 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month09, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month09, 0) + END, + ActualYTDDollars10 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month10, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month10, 0) + END, + ActualYTDDollars11 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month11, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month11, 0) + END, + ActualYTDDollars12 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month12, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month12, 0) + END + FROM [fp].[StaffingHistory] fsh + INNER JOIN [fp].[Staffing] fs ON fs.StaffingID = fsh.StaffingID + INNER JOIN + (SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderSpecialtyID, ProviderLineItemID, ProviderTypeID, SubsectionID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingDataRolledUp) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.JobCodeID = pv.JobCodeID + AND fs.PayCodeGroupID = pv.PayCodeGroupID + AND fs.EmployeeID = pv.EmployeeID + AND fs.ProviderID = pv.ProviderID and fs.ProviderSpecialtyID = pv.ProviderSpecialtyID and fs.ProviderLineItemID = pv.ProviderLineItemID and fs.ProviderTypeID = pv.ProviderTypeID and fs.SubsectionID = pv.SubsectionID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND pv.UnitTypeID = 34 + + + DELETE FROM #IntStaffingDataRolledUpRaw + DELETE FROM #IntStaffingDataRolledUp + DELETE FROM #dept + DELETE FROM #emp + DELETE FROM #provDims + + IF @IsProviderPlanningEnabled = 0 + BEGIN + + ---------------------------------------------------- + -- Provider is disabled + ---------------------------------------------------- + + INSERT INTO #IntStaffingDataRolledUpRaw + SELECT + hist.DepartmentID, + hist.JobCodeID, + hist.PayCodeGroupID, + hist.EmployeeID, + hist.UnitTypeID, + 0 as ProviderID, + 0 as ProviderTypeID, + 0 as ProviderSpecialtyID, + 0 as ProviderLineItemID, + 3 as SubsectionID, + hist.MonthColumnName, + ISNULL(fv.FixedPercentage,1) as FixedPercentage, + SUM(ISNULL(hist.Value, 0)) as Value + FROM #intFactStaffingWithEmployeeResolved hist + INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = hist.DepartmentID + AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND fv.JobCodeID = hist.JobCodeID + AND fv.PayCodeID = hist.PayCodeID + AND fv.EmployeeID = hist.EmployeeID + WHERE hist.FiscalYearID = @CurrentFiscalYearID - 1 + AND hist.TimeclassID = 1 + AND hist.IsDeleted = 0 + AND hist.FiscalMonthID != 0 + AND ((hist.UnitTypeID = 34 AND hist.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND hist.IsHoursIgnored = 0)) + GROUP BY hist.DepartmentID, + hist.JobCodeID, + hist.PayCodeGroupID, + hist.EmployeeID, + hist.UnitTypeID, + hist.MonthColumnName, + FixedPercentage + END ELSE BEGIN + + ---------------------------------------------------- + -- Provider is enabled + ---------------------------------------------------- + IF @SampleProviderEitherFromStaffingOrProviderIntTable = 0 + BEGIN + + ------------------------------------------------------- + -- BudgetConfigSetting is disabled + ------------------------------------------------------- + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @CurrentFiscalYearID - 1 AND staff.TimeclassID = 1 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + UNION + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @CurrentFiscalYearID - 1 AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later + + -- 2. all employees that are providers + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + staff.DepartmentID, + emp.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID + INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID + INNER JOIN [dss].[DimPhysician] phys ON emp.NPI = phys.NPI + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @CurrentFiscalYearID - 1 AND staff.TimeclassID = 1 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND staff.EmployeeID > 0 + AND emp.NPI NOT IN ('Not Specified', '0', '') + UNION + SELECT DISTINCT + prov.DepartmentID, + phys.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID + LEFT JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @CurrentFiscalYearID - 1 AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND phys.NPI NOT IN ('Not Specified', '0', '') + AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later + + -- Provider from int.FactProvider + INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + fp.DepartmentID, + 0 as JobCodeID, + 0 as PayCodeGroupID, + 0 as EmployeeID, + fp.UnitTypeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + fp.ProviderLineItemID, + @ProviderSubsectionID, + fm.MonthColumnName, + 1 as FixedPercentage, + CASE WHEN fp.UnitTypeID = 34 OR UnitTypeID = 51 THEN SUM(ISNULL(fp.Value, 0)) ELSE 0 END AS Value + FROM + [int].[FactProvider] fp + INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + WHERE + fp.FiscalYearID = @CurrentFiscalYearID - 1 + AND fp.TimeClassID = 1 + AND fp.IsDeleted = 0 + AND fp.FiscalMonthID != 0 + AND ps.Description = 'Staffing' + AND emp.IsFP = 1 + AND fp.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later + GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName, fp.UnitTypeID, + emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID + + INSERT INTO #provDims (DepartmentID, ProviderID, ProviderLineItemID) SELECT DISTINCT DepartmentID, ProviderID, ProviderLineItemID FROM #IntStaffingDataRolledUpRaw + + -- Provider from int.FactStaffing + INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + hist.DepartmentID, + hist.JobCodeID, + pc.PayCodeGroupID, + 0 as EmployeeID, + hist.UnitTypeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + pc.ProviderLineItemID, + @ProviderSubsectionID, + fm.MonthColumnName, + CASE WHEN hist.UnitTypeID = 34 THEN ISNULL(fv.FixedPercentage,1) WHEN hist.UnitTypeID = 51 THEN 1 ELSE 0 END AS FixedPercentage, + CASE WHEN hist.UnitTypeID = 34 OR hist.UnitTypeID = 51 THEN SUM(ISNULL(hist.Value, 0)) ELSE 0 END AS Value + FROM [int].[FactStaffing] hist + INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID + INNER JOIN #dept dept ON hist.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON hist.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR hist.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = hist.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON hist.PayCodeID = pc.PayCodeID + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID + AND fv.JobCodeID = hist.JobCodeID + AND fv.PayCodeID = hist.PayCodeID + AND fv.EmployeeID = 0 + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN #provDims pd ON hist.DepartmentID = pd.DepartmentID AND emp.ProviderID = pd.ProviderID and pd.ProviderLineItemID = pli.ProviderLineItemID + WHERE hist.FiscalYearID = @CurrentFiscalYearID - 1 AND hist.TimeClassID = 1 AND hist.IsDeleted = 0 AND hist.FiscalMonthID != 0 + AND ((hist.UnitTypeID = 34 AND pc.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND pc.IsHoursIgnored = 0)) + AND emp.IsFP = 1 + GROUP BY hist.DepartmentID, + hist.JobCodeID, + pc.PayCodeGroupID, + emp.EmployeeID, + hist.UnitTypeID, + fm.MonthColumnName, + FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID + + END ELSE BEGIN + + ------------------------------------------------------- + -- BudgetConfigSetting is enabled + ------------------------------------------------------- + IF @UseProviderSource = 0 + BEGIN + + ------------------------------------------------------- + -- BudgetConfig UseProviderSource is disabled + ------------------------------------------------------- + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use staffing + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @CurrentFiscalYearID - 1 AND staff.TimeclassID = 1 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + + -- 2. all employees from staffing + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + staff.DepartmentID, + emp.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID + INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID + INNER JOIN [dss].[DimPhysician] phys ON emp.NPI = phys.NPI + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @CurrentFiscalYearID - 1 AND staff.TimeclassID = 1 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND staff.EmployeeID > 0 + AND emp.NPI NOT IN ('Not Specified', '0', '') + + -- Provider from int.FactStaffing + INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + hist.DepartmentID, + hist.JobCodeID, + pc.PayCodeGroupID, + 0 as EmployeeID, + hist.UnitTypeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + pc.ProviderLineItemID, + @ProviderSubsectionID, + fm.MonthColumnName, + CASE WHEN hist.UnitTypeID = 34 THEN ISNULL(fv.FixedPercentage,1) WHEN hist.UnitTypeID = 51 THEN 1 ELSE 0 END AS FixedPercentage, + CASE WHEN hist.UnitTypeID = 34 OR hist.UnitTypeID = 51 THEN SUM(ISNULL(hist.Value, 0)) ELSE 0 END AS Value + FROM [int].[FactStaffing] hist + INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID + INNER JOIN #dept dept ON hist.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON hist.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR hist.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = hist.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON hist.PayCodeID = pc.PayCodeID + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID + AND fv.JobCodeID = hist.JobCodeID + AND fv.PayCodeID = hist.PayCodeID + AND fv.EmployeeID = 0 + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE hist.FiscalYearID = @CurrentFiscalYearID - 1 AND hist.TimeClassID = 1 AND hist.IsDeleted = 0 AND hist.FiscalMonthID != 0 + AND ((hist.UnitTypeID = 34 AND pc.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND pc.IsHoursIgnored = 0)) + AND emp.IsFP = 1 + GROUP BY hist.DepartmentID, + hist.JobCodeID, + pc.PayCodeGroupID, + emp.EmployeeID, + hist.UnitTypeID, + fm.MonthColumnName, + FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID + + END ELSE BEGIN + + ------------------------------------------------------- + -- BudgetConfig UseProviderSource is enabled + ------------------------------------------------------- + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @CurrentFiscalYearID - 1 AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later + + -- 2. all employees that are providers + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + prov.DepartmentID, + phys.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID + LEFT JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @CurrentFiscalYearID - 1 AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND phys.NPI NOT IN ('Not Specified', '0', '') + AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later + + -- Provider from int.FactProvider + INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + fp.DepartmentID, + 0 as JobCodeID, + 0 as PayCodeGroupID, + 0 as EmployeeID, + fp.UnitTypeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + fp.ProviderLineItemID, + @ProviderSubsectionID, + fm.MonthColumnName, + 1 as FixedPercentage, + CASE WHEN fp.UnitTypeID = 34 OR UnitTypeID = 51 THEN SUM(ISNULL(fp.Value, 0)) ELSE 0 END AS Value + FROM + [int].[FactProvider] fp + INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + WHERE + fp.FiscalYearID = @CurrentFiscalYearID - 1 + AND fp.TimeClassID = 1 + AND fp.IsDeleted = 0 + AND fp.FiscalMonthID != 0 + AND ps.Description = 'Staffing' + AND emp.IsFP = 1 + AND fp.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later + GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName, fp.UnitTypeID, + emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID + + END + + END + + -- Non-Provider from int.FactStaffing + -- Populate into a temp table before summing up to deal with issues with the dynamic employee join + SELECT + hist.DepartmentID, + hist.JobCodeID, + hist.PayCodeID, + pc.PayCodeGroupID, + CASE + WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 + ELSE CASE + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE hist.EmployeeID + END + END as EmployeeID, + hist.UnitTypeID, + 0 as ProviderID, + 0 as ProviderTypeID, + 0 as ProviderSpecialtyID, + 0 as ProviderLineItemID, + @StaffingSubsectionID as SubsectionID, + fm.MonthColumnName, + ISNULL(fv.FixedPercentage, 1) as FixedPercentage, + ISNULL(hist.Value, 0) as Value + INTO #intFactStaffingWithEmployeeResolvedForProviderPriorYearActuals + FROM [int].[FactStaffing] hist + INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID + LEFT JOIN #dept dept ON hist.DepartmentID = dept.DepartmentID + LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 1) emp ON hist.EmployeeID = emp.EmployeeID + LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 0) NotFpEmp ON hist.EmployeeID = NotFpEmp.EmployeeID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = hist.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON hist.PayCodeID = pc.PayCodeID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = hist.DepartmentID + AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND fv.JobCodeID = hist.JobCodeID + AND fv.PayCodeID = hist.PayCodeID + AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0. + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE hist.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not. + END = fv.EmployeeID + WHERE hist.FiscalYearID = @CurrentFiscalYearID - 1 + AND hist.TimeClassID = 1 + AND hist.IsDeleted = 0 + AND hist.FiscalMonthID != 0 + AND ((hist.UnitTypeID = 34 AND pc.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND pc.IsHoursIgnored = 0)) + AND (dept.DepartmentID IS NULL OR (emp.EmployeeID IS NULL AND (NotFpEmp.EmployeeID IS NULL OR NotFpEmp.IsFP = 0))) + + INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + hist.DepartmentID, + hist.JobCodeID, + hist.PayCodeGroupID, + hist.EmployeeID, + hist.UnitTypeID, + 0 as ProviderID, + 0 as ProviderTypeID, + 0 as ProviderSpecialtyID, + 0 as ProviderLineItemID, + @StaffingSubsectionID as SubsectionID, + hist.MonthColumnName, + ISNULL(fv.FixedPercentage,1) as FixedPercentage, + SUM(ISNULL(hist.Value, 0)) as Value + FROM #intFactStaffingWithEmployeeResolvedForProviderPriorYearActuals hist + INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = hist.DepartmentID + AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID + AND fv.JobCodeID = hist.JobCodeID + AND fv.PayCodeID = hist.PayCodeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND fv.EmployeeID = hist.EmployeeID + GROUP BY hist.DepartmentID, + hist.JobCodeID, + hist.PayCodeGroupID, + hist.EmployeeID, + hist.UnitTypeID, + hist.MonthColumnName, + fv.FixedPercentage + + END + + INSERT INTO #IntStaffingDataRolledUp + ( DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value + FROM #IntStaffingDataRolledUpRaw + WHERE FixedPercentage = 1 + + INSERT INTO #IntStaffingDataRolledUp + ( DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT DepartmentID, JobCodeID, PayCodeGroupID, CASE WHEN @IsEmployeeBudgeting = 1 AND ProviderID = 0 THEN 0 ELSE EmployeeID END AS EmployeeID, + UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, MAX(ISNULL(FixedPercentage, 1)), SUM(ISNULL(Value, 0)) + FROM #IntStaffingDataRolledUpRaw + WHERE FixedPercentage <> 1 + GROUP BY DepartmentID, JobCodeID, PayCodeGroupID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, + CASE WHEN @IsEmployeeBudgeting = 1 AND ProviderID = 0 THEN 0 ELSE EmployeeID END + + UPDATE + fsh + SET + PriorYearActualHours01 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month01, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month01, 0) + END, + PriorYearActualHours02 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month02, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month02, 0) + END, + PriorYearActualHours03 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month03, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month03, 0) + END, + PriorYearActualHours04 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month04, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month04, 0) + END, + PriorYearActualHours05 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month05, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month05, 0) + END, + PriorYearActualHours06 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month06, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month06, 0) + END, + PriorYearActualHours07 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month07, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month07, 0) + END, + PriorYearActualHours08 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month08, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month08, 0) + END, + PriorYearActualHours09 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month09, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month09, 0) + END, + PriorYearActualHours10 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month10, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month10, 0) + END, + PriorYearActualHours11 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month11, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month11, 0) + END, + PriorYearActualHours12 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month12, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month12, 0) + END + FROM + [fp].[StaffingHistory] fsh + INNER JOIN [fp].[Staffing] fs ON fs.StaffingID = fsh.StaffingID + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + INNER JOIN + (SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderSpecialtyID, ProviderLineItemID, ProviderTypeID, SubsectionID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingDataRolledUp) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.JobCodeID = pv.JobCodeID + AND fs.PayCodeGroupID = pv.PayCodeGroupID + AND fs.EmployeeID = pv.EmployeeID + and fs.ProviderID = pv.ProviderID and fs.ProviderSpecialtyID = pv.ProviderSpecialtyID and fs.ProviderLineItemID = pv.ProviderLineItemID and fs.ProviderTypeID = pv.ProviderTypeID and fs.SubsectionID = pv.SubsectionID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND pv.UnitTypeID = 51 + + UPDATE + fsh + SET + PriorYearActualDollars01 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month01, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month01, 0) + END, + PriorYearActualDollars02 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month02, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month02, 0) + END, + PriorYearActualDollars03 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month03, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month03, 0) + END, + PriorYearActualDollars04 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month04, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month04, 0) + END, + PriorYearActualDollars05 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month05, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month05, 0) + END, + PriorYearActualDollars06 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month06, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month06, 0) + END, + PriorYearActualDollars07 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month07, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month07, 0) + END, + PriorYearActualDollars08 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month08, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month08, 0) + END, + PriorYearActualDollars09 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month09, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month09, 0) + END, + PriorYearActualDollars10 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month10, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month10, 0) + END, + PriorYearActualDollars11 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month11, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month11, 0) + END, + PriorYearActualDollars12 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month12, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month12, 0) + END + FROM + [fp].[StaffingHistory] fsh + INNER JOIN [fp].[Staffing] fs ON fs.StaffingID = fsh.StaffingID + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + INNER JOIN + (SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderSpecialtyID, ProviderLineItemID, ProviderTypeID, SubsectionID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingDataRolledUp) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.JobCodeID = pv.JobCodeID + AND fs.PayCodeGroupID = pv.PayCodeGroupID + AND fs.EmployeeID = pv.EmployeeID + and fs.ProviderID = pv.ProviderID and fs.ProviderSpecialtyID = pv.ProviderSpecialtyID and fs.ProviderLineItemID = pv.ProviderLineItemID and fs.ProviderTypeID = pv.ProviderTypeID and fs.SubsectionID = pv.SubsectionID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND pv.UnitTypeID = 34 + + DELETE FROM #IntStaffingDataRolledUpRaw + DELETE FROM #IntStaffingDataRolledUp + DELETE FROM #dept + DELETE FROM #emp + DELETE FROM #provDims + + IF @IsProviderPlanningEnabled = 0 BEGIN + + ---------------------------------------------------- + -- Provider is disabled + ---------------------------------------------------- + + INSERT INTO #IntStaffingDataRolledUpRaw + SELECT + hist.DepartmentID, + hist.JobCodeID, + hist.PayCodeGroupID, + hist.EmployeeID, + hist.UnitTypeID, + 0 as ProviderID, + 0 as ProviderTypeID, + 0 as ProviderSpecialtyID, + 0 as ProviderLineItemID, + 3 as SubsectionID, + hist.MonthColumnName, + ISNULL(fv.FixedPercentage, 1) as FixedPercentage, + SUM(ISNULL(hist.Value, 0)) as Value + FROM #intFactStaffingWithEmployeeResolved hist + INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = hist.DepartmentID + AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID + AND fv.JobCodeID = hist.JobCodeID + AND fv.PayCodeID = hist.PayCodeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND fv.EmployeeID = hist.EmployeeID + WHERE hist.FiscalYearID = @CurrentFiscalYearID + AND hist.TimeclassID = 2 + AND hist.IsDeleted = 0 + AND hist.FiscalMonthID != 0 + AND ((hist.UnitTypeID = 34 AND hist.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND hist.IsHoursIgnored = 0)) + GROUP BY hist.DepartmentID, + hist.JobCodeID, + hist.PayCodeGroupID, + hist.EmployeeID, + hist.UnitTypeID, + hist.MonthColumnName, + FixedPercentage + END ELSE BEGIN + + ---------------------------------------------------- + -- Provider is enabled + ---------------------------------------------------- + + IF @SampleProviderEitherFromStaffingOrProviderIntTable = 0 + BEGIN + + ------------------------------------------------------- + -- BudgetConfigSetting is disabled + ------------------------------------------------------- + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 2 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + UNION + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 2 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later + + -- 2. all employees that are providers + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + staff.DepartmentID, + emp.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID + INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID + INNER JOIN [dss].[DimPhysician] phys ON emp.NPI = phys.NPI + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 2 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND staff.EmployeeID > 0 + AND emp.NPI NOT IN ('Not Specified', '0', '') + UNION + SELECT DISTINCT + prov.DepartmentID, + phys.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID + LEFT JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 2 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND phys.NPI NOT IN ('Not Specified', '0', '') + AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later + + -- Provider from int.FactProvider + INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + fp.DepartmentID, + 0 as JobCodeID, + 0 as PayCodeGroupID, + 0 as EmployeeID, + fp.UnitTypeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + fp.ProviderLineItemID, + @ProviderSubsectionID, + fm.MonthColumnName, + 1 as FixedPercentage, + CASE WHEN fp.UnitTypeID = 34 OR UnitTypeID = 51 THEN SUM(ISNULL(fp.Value, 0)) ELSE 0 END AS Value + FROM + [int].[FactProvider] fp + INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + WHERE + fp.FiscalYearID = @CurrentFiscalYearID + AND fp.TimeClassID = 2 + AND fp.IsDeleted = 0 + AND fp.FiscalMonthID != 0 + AND ps.Description = 'Staffing' + AND emp.IsFP = 1 + AND fp.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later + GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName, fp.UnitTypeID, + emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID + + + INSERT INTO #provDims (DepartmentID, ProviderID, ProviderLineItemID) SELECT DISTINCT DepartmentID, ProviderID, ProviderLineItemID FROM #IntStaffingDataRolledUpRaw + + -- Provider from int.FactStaffing + INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + hist.DepartmentID, + hist.JobCodeID, + pc.PayCodeGroupID, + 0 as EmployeeID, + hist.UnitTypeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + pc.ProviderLineItemID, + @ProviderSubsectionID, + fm.MonthColumnName, + CASE WHEN hist.UnitTypeID = 34 THEN ISNULL(fv.FixedPercentage,1) WHEN hist.UnitTypeID = 51 THEN 1 ELSE 0 END AS FixedPercentage, + CASE WHEN hist.UnitTypeID = 34 OR hist.UnitTypeID = 51 THEN SUM(ISNULL(hist.Value, 0)) ELSE 0 END AS Value + FROM [int].[FactStaffing] hist + INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID + INNER JOIN #dept dept ON hist.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON hist.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR hist.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = hist.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON hist.PayCodeID = pc.PayCodeID + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID + AND fv.JobCodeID = hist.JobCodeID + AND fv.PayCodeID = hist.PayCodeID + AND fv.EmployeeID = 0 + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN #provDims pd ON hist.DepartmentID = pd.DepartmentID + AND emp.ProviderID = pd.ProviderID + and pd.ProviderLineItemID = pli.ProviderLineItemID + WHERE hist.FiscalYearID = @CurrentFiscalYearID + AND hist.TimeClassID = 2 + AND hist.IsDeleted = 0 + AND hist.FiscalMonthID != 0 + AND ((hist.UnitTypeID = 34 AND pc.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND pc.IsHoursIgnored = 0)) + AND emp.IsFP = 1 + GROUP BY hist.DepartmentID, + hist.JobCodeID, + pc.PayCodeGroupID, + emp.EmployeeID, + hist.UnitTypeID, + fm.MonthColumnName, + FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID + + END ELSE BEGIN + + ------------------------------------------------------- + -- BudgetConfigSetting is enabled + ------------------------------------------------------- + IF @UseProviderSource = 0 + BEGIN + + ------------------------------------------------------- + -- BudgetConfig UseProviderSource is disabled + ------------------------------------------------------- + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use staffing + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 2 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + + -- 2. all employees from staffing + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + staff.DepartmentID, + emp.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = staff.FiscalMonthID + INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID + INNER JOIN [dss].[DimPhysician] phys ON emp.NPI = phys.NPI + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 2 AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND staff.EmployeeID > 0 + AND emp.NPI NOT IN ('Not Specified', '0', '') + + -- Provider from int.FactStaffing + INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + hist.DepartmentID, + hist.JobCodeID, + pc.PayCodeGroupID, + 0 as EmployeeID, + hist.UnitTypeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + pc.ProviderLineItemID, + @ProviderSubsectionID, + fm.MonthColumnName, + CASE WHEN hist.UnitTypeID = 34 THEN ISNULL(fv.FixedPercentage,1) WHEN hist.UnitTypeID = 51 THEN 1 ELSE 0 END AS FixedPercentage, + CASE WHEN hist.UnitTypeID = 34 OR hist.UnitTypeID = 51 THEN SUM(ISNULL(hist.Value, 0)) ELSE 0 END AS Value + FROM [int].[FactStaffing] hist + INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID + INNER JOIN #dept dept ON hist.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON hist.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR hist.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = hist.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON hist.PayCodeID = pc.PayCodeID + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID + AND fv.JobCodeID = hist.JobCodeID + AND fv.PayCodeID = hist.PayCodeID + AND fv.EmployeeID = 0 + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE hist.FiscalYearID = @CurrentFiscalYearID + AND hist.TimeClassID = 2 + AND hist.IsDeleted = 0 + AND hist.FiscalMonthID != 0 + AND ((hist.UnitTypeID = 34 AND pc.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND pc.IsHoursIgnored = 0)) + AND emp.IsFP = 1 + GROUP BY hist.DepartmentID, + hist.JobCodeID, + pc.PayCodeGroupID, + emp.EmployeeID, + hist.UnitTypeID, + fm.MonthColumnName, + FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID + + END ELSE BEGIN + + ------------------------------------------------------- + -- BudgetConfig UseProviderSource is enabled + ------------------------------------------------------- + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 2 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later + + -- 2. all employees that are providers + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + prov.DepartmentID, + phys.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = prov.FiscalMonthID + LEFT JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 2 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND phys.NPI NOT IN ('Not Specified', '0', '') + AND prov.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later + + -- Provider from int.FactProvider + INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + fp.DepartmentID, + 0 as JobCodeID, + 0 as PayCodeGroupID, + 0 as EmployeeID, + fp.UnitTypeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + fp.ProviderLineItemID, + @ProviderSubsectionID, + fm.MonthColumnName, + 1 as FixedPercentage, + CASE WHEN fp.UnitTypeID = 34 OR UnitTypeID = 51 THEN SUM(ISNULL(fp.Value, 0)) ELSE 0 END AS Value + FROM + [int].[FactProvider] fp + INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + WHERE + fp.FiscalYearID = @CurrentFiscalYearID + AND fp.TimeClassID = 2 + AND fp.IsDeleted = 0 + AND fp.FiscalMonthID != 0 + AND ps.Description = 'Staffing' + AND emp.IsFP = 1 + AND fp.UnitTypeID IN (34, 51) -- Only pull in Hours and Dollars since that's all we pull in later + GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName, fp.UnitTypeID, + emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID + + END + + END + + -- Non-Provider from int.FactStaffing + -- Populate into a temp table before summing up to deal with issues with the dynamic employee join + SELECT + hist.DepartmentID, + hist.JobCodeID, + hist.PayCodeID, + pc.PayCodeGroupID, + CASE + WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 + ELSE CASE + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE hist.EmployeeID + END + END as EmployeeID, + hist.UnitTypeID, + 0 as ProviderID, + 0 as ProviderTypeID, + 0 as ProviderSpecialtyID, + 0 as ProviderLineItemID, + @StaffingSubsectionID as SubsectionID, + fm.MonthColumnName, + ISNULL(fv.FixedPercentage, 1) as FixedPercentage, + ISNULL(hist.Value, 0) as Value + INTO #intFactStaffingWithEmployeeResolvedForProviderCurrentYearBudget + FROM [int].[FactStaffing] hist + INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID + LEFT JOIN #dept dept ON hist.DepartmentID = dept.DepartmentID + LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 1) emp ON hist.EmployeeID = emp.EmployeeID + LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 0) NotFpEmp ON hist.EmployeeID = NotFpEmp.EmployeeID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = hist.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON hist.PayCodeID = pc.PayCodeID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = hist.DepartmentID + AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND fv.JobCodeID = hist.JobCodeID + AND fv.PayCodeID = hist.PayCodeID + AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0. + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE hist.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not. + END = fv.EmployeeID + WHERE hist.FiscalYearID = @CurrentFiscalYearID + AND hist.TimeClassID = 2 + AND hist.IsDeleted = 0 + AND hist.FiscalMonthID != 0 + AND ((hist.UnitTypeID = 34 AND pc.IsDollarsIgnored = 0) OR (hist.UnitTypeID = 51 AND pc.IsHoursIgnored = 0)) + AND (dept.DepartmentID IS NULL OR (emp.EmployeeID IS NULL AND (NotFpEmp.EmployeeID IS NULL OR NotFpEmp.IsFP = 0))) + + INSERT INTO #IntStaffingDataRolledUpRaw (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + hist.DepartmentID, + hist.JobCodeID, + hist.PayCodeGroupID, + hist.EmployeeID, + hist.UnitTypeID, + 0 as ProviderID, + 0 as ProviderTypeID, + 0 as ProviderSpecialtyID, + 0 as ProviderLineItemID, + @StaffingSubsectionID as SubsectionID, + hist.MonthColumnName, + ISNULL(fv.FixedPercentage,1) as FixedPercentage, + SUM(ISNULL(hist.Value, 0)) as Value + FROM #intFactStaffingWithEmployeeResolvedForProviderCurrentYearBudget hist + INNER JOIN #filterTable tmp on hist.DepartmentID = tmp.DepartmentID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = hist.DepartmentID + AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = hist.DepartmentID + AND fv.JobCodeID = hist.JobCodeID + AND fv.PayCodeID = hist.PayCodeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND fv.EmployeeID = hist.EmployeeID + GROUP BY hist.DepartmentID, + hist.JobCodeID, + hist.PayCodeGroupID, + hist.EmployeeID, + hist.UnitTypeID, + hist.MonthColumnName, + fv.FixedPercentage, + hist.UnitTypeID + END + + INSERT INTO #IntStaffingDataRolledUp + ( DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value + FROM #IntStaffingDataRolledUpRaw + WHERE FixedPercentage = 1 + + INSERT INTO #IntStaffingDataRolledUp + ( DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT DepartmentID, JobCodeID, PayCodeGroupID, CASE WHEN @IsEmployeeBudgeting = 1 AND ProviderID = 0 THEN 0 ELSE EmployeeID END AS EmployeeID, + UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, MAX(ISNULL(FixedPercentage, 1)), SUM(ISNULL(Value, 0)) + FROM #IntStaffingDataRolledUpRaw + WHERE FixedPercentage <> 1 + GROUP BY DepartmentID, JobCodeID, PayCodeGroupID, UnitTypeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, + CASE WHEN @IsEmployeeBudgeting = 1 AND ProviderID = 0 THEN 0 ELSE EmployeeID END + + + UPDATE + fsh + SET + CurrentYearBudgetHours01 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month01, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month01, 0) + END, + CurrentYearBudgetHours02 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month02, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month02, 0) + END, + CurrentYearBudgetHours03 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month03, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month03, 0) + END, + CurrentYearBudgetHours04 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month04, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month04, 0) + END, + CurrentYearBudgetHours05 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month05, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month05, 0) + END, + CurrentYearBudgetHours06 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month06, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month06, 0) + END, + CurrentYearBudgetHours07 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month07, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month07, 0) + END, + CurrentYearBudgetHours08 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month08, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month08, 0) + END, + CurrentYearBudgetHours09 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month09, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month09, 0) + END, + CurrentYearBudgetHours10 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month10, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month10, 0) + END, + CurrentYearBudgetHours11 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month11, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month11, 0) + END, + CurrentYearBudgetHours12 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month12, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month12, 0) + END + FROM + [fp].[StaffingHistory] fsh + INNER JOIN [fp].[Staffing] fs ON fs.StaffingID = fsh.StaffingID + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + INNER JOIN + (SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderSpecialtyID, ProviderLineItemID, ProviderTypeID, SubsectionID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingDataRolledUp) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.JobCodeID = pv.JobCodeID + AND fs.PayCodeGroupID = pv.PayCodeGroupID + AND fs.EmployeeID = pv.EmployeeID + and fs.ProviderID = pv.ProviderID and fs.ProviderSpecialtyID = pv.ProviderSpecialtyID and fs.ProviderLineItemID = pv.ProviderLineItemID and fs.ProviderTypeID = pv.ProviderTypeID and fs.SubsectionID = pv.SubsectionID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND pv.UnitTypeID = 51 + + + UPDATE + fsh + SET + CurrentYearBudgetDollars01 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month01, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month01, 0) + END, + CurrentYearBudgetDollars02 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month02, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month02, 0) + END, + CurrentYearBudgetDollars03 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month03, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month03, 0) + END, + CurrentYearBudgetDollars04 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month04, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month04, 0) + END, + CurrentYearBudgetDollars05 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month05, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month05, 0) + END, + CurrentYearBudgetDollars06 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month06, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month06, 0) + END, + CurrentYearBudgetDollars07 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month07, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month07, 0) + END, + CurrentYearBudgetDollars08 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month08, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month08, 0) + END, + CurrentYearBudgetDollars09 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month09, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month09, 0) + END, + CurrentYearBudgetDollars10 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month10, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month10, 0) + END, + CurrentYearBudgetDollars11 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month11, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month11, 0) + END, + CurrentYearBudgetDollars12 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month12, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month12, 0) + END + FROM + [fp].[StaffingHistory] fsh + INNER JOIN [fp].[Staffing] fs ON fs.StaffingID = fsh.StaffingID + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + INNER JOIN + (SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, UnitTypeID, ProviderID, ProviderSpecialtyID, ProviderLineItemID, ProviderTypeID, SubsectionID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingDataRolledUp) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.JobCodeID = pv.JobCodeID + AND fs.PayCodeGroupID = pv.PayCodeGroupID + AND fs.EmployeeID = pv.EmployeeID + and fs.ProviderID = pv.ProviderID and fs.ProviderSpecialtyID = pv.ProviderSpecialtyID and fs.ProviderLineItemID = pv.ProviderLineItemID and fs.ProviderTypeID = pv.ProviderTypeID and fs.SubsectionID = pv.SubsectionID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND pv.UnitTypeID = 34 + + -- After the dollars and hours have been sampled in, need to recalculate the FTEs + UPDATE fteHist + SET + fteHist.ActualYTDFTEs01 = fteHist.ActualYTDHours01 / currentWorkingHours.Month01 + , fteHist.ActualYTDFTEs02 = fteHist.ActualYTDHours02 / currentWorkingHours.Month02 + , fteHist.ActualYTDFTEs03 = fteHist.ActualYTDHours03 / currentWorkingHours.Month03 + , fteHist.ActualYTDFTEs04 = fteHist.ActualYTDHours04 / currentWorkingHours.Month04 + , fteHist.ActualYTDFTEs05 = fteHist.ActualYTDHours05 / currentWorkingHours.Month05 + , fteHist.ActualYTDFTEs06 = fteHist.ActualYTDHours06 / currentWorkingHours.Month06 + , fteHist.ActualYTDFTEs07 = fteHist.ActualYTDHours07 / currentWorkingHours.Month07 + , fteHist.ActualYTDFTEs08 = fteHist.ActualYTDHours08 / currentWorkingHours.Month08 + , fteHist.ActualYTDFTEs09 = fteHist.ActualYTDHours09 / currentWorkingHours.Month09 + , fteHist.ActualYTDFTEs10 = fteHist.ActualYTDHours10 / currentWorkingHours.Month10 + , fteHist.ActualYTDFTEs11 = fteHist.ActualYTDHours11 / currentWorkingHours.Month11 + , fteHist.ActualYTDFTEs12 = fteHist.ActualYTDHours12 / currentWorkingHours.Month12 + + , fteHist.PriorYearActualFTEs01 = fteHist.PriorYearActualHours01 / priorWorkingHours.Month01 + , fteHist.PriorYearActualFTEs02 = fteHist.PriorYearActualHours02 / priorWorkingHours.Month02 + , fteHist.PriorYearActualFTEs03 = fteHist.PriorYearActualHours03 / priorWorkingHours.Month03 + , fteHist.PriorYearActualFTEs04 = fteHist.PriorYearActualHours04 / priorWorkingHours.Month04 + , fteHist.PriorYearActualFTEs05 = fteHist.PriorYearActualHours05 / priorWorkingHours.Month05 + , fteHist.PriorYearActualFTEs06 = fteHist.PriorYearActualHours06 / priorWorkingHours.Month06 + , fteHist.PriorYearActualFTEs07 = fteHist.PriorYearActualHours07 / priorWorkingHours.Month07 + , fteHist.PriorYearActualFTEs08 = fteHist.PriorYearActualHours08 / priorWorkingHours.Month08 + , fteHist.PriorYearActualFTEs09 = fteHist.PriorYearActualHours09 / priorWorkingHours.Month09 + , fteHist.PriorYearActualFTEs10 = fteHist.PriorYearActualHours10 / priorWorkingHours.Month10 + , fteHist.PriorYearActualFTEs11 = fteHist.PriorYearActualHours11 / priorWorkingHours.Month11 + , fteHist.PriorYearActualFTEs12 = fteHist.PriorYearActualHours12 / priorWorkingHours.Month12 + + , fteHist.CurrentYearBudgetFTEs01 = fteHist.CurrentYearBudgetHours01 / currentWorkingHours.Month01 + , fteHist.CurrentYearBudgetFTEs02 = fteHist.CurrentYearBudgetHours02 / currentWorkingHours.Month02 + , fteHist.CurrentYearBudgetFTEs03 = fteHist.CurrentYearBudgetHours03 / currentWorkingHours.Month03 + , fteHist.CurrentYearBudgetFTEs04 = fteHist.CurrentYearBudgetHours04 / currentWorkingHours.Month04 + , fteHist.CurrentYearBudgetFTEs05 = fteHist.CurrentYearBudgetHours05 / currentWorkingHours.Month05 + , fteHist.CurrentYearBudgetFTEs06 = fteHist.CurrentYearBudgetHours06 / currentWorkingHours.Month06 + , fteHist.CurrentYearBudgetFTEs07 = fteHist.CurrentYearBudgetHours07 / currentWorkingHours.Month07 + , fteHist.CurrentYearBudgetFTEs08 = fteHist.CurrentYearBudgetHours08 / currentWorkingHours.Month08 + , fteHist.CurrentYearBudgetFTEs09 = fteHist.CurrentYearBudgetHours09 / currentWorkingHours.Month09 + , fteHist.CurrentYearBudgetFTEs10 = fteHist.CurrentYearBudgetHours10 / currentWorkingHours.Month10 + , fteHist.CurrentYearBudgetFTEs11 = fteHist.CurrentYearBudgetHours11 / currentWorkingHours.Month11 + , fteHist.CurrentYearBudgetFTEs12 = fteHist.CurrentYearBudgetHours12 / currentWorkingHours.Month12 + + FROM [fp].[Staffing] fte + INNER JOIN #filterTable tmp on fte.DepartmentID = tmp.DepartmentID + INNER JOIN [fp].[StaffingHistory] fteHist ON fte.StaffingID = fteHist.StaffingID + INNER JOIN [fw].[DimJobCode] jc on fte.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on fte.DepartmentID = dept.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] currentWorkingHours on currentWorkingHours.FiscalYearID = @CurrentFiscalYearID and currentWorkingHours.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + INNER JOIN [client].[FactWorkingHoursPerMonth] priorWorkingHours on priorWorkingHours.FiscalYearID = @CurrentFiscalYearID - 1 and priorWorkingHours.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fte.PayCodeGroupID = exc.PayCodeGroupID + WHERE fte.EntityGroupConfigID = @EntityGroupConfigID AND exc.PayCodeGroupID IS NULL + option (recompile) + + -- No longer storing historical wage rates + + +END; +GO + + +--------------------------------------------- + +-- fp.procSampleStaffingHistoryFTETotals +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-01-21 BK JAZZ-61724 Convert logic from old procSampleFactStaffingHistoryFTETotals + ** 2 2024-05-22 VZ JAZZ-71605 Performance Optimization + *************************************************************/ + +CREATE PROCEDURE [fp].[procSampleStaffingHistoryFTETotals] + + @BudgetConfigID INT, + @EntityGroupConfigID INT, + @CurrentFiscalYearID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + IF OBJECT_ID('tempdb..#FilteredData') IS NOT NULL DROP TABLE #FilteredData + + CREATE TABLE #FilterByDepartment (DepartmentID INT) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID + FROM @SourceDimensionality + + --JAZZ-3774 + --Updated insert statement to pull in DepartmentID and JobCodeID for joining purposes in the update statement + CREATE TABLE #FilteredData (StaffingID INT PRIMARY KEY CLUSTERED, DepartmentID INT, JobCodeID INT, PayCodeGroupID INT) + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilteredData + SELECT [staff].[StaffingID], [staff].[DepartmentID], [staff].[JobCodeID], [staff].[PayCodeGroupID] + FROM [fp].[Staffing] staff + INNER JOIN #FilterByDepartment ft ON ft.DepartmentID = staff.DepartmentID + INNER JOIN [fw].[DimDepartment] dd ON ft.DepartmentID = dd.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON dd.EntityID = egcm.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + AND egc.EntityGroupConfigID = staff.EntityGroupConfigID + WHERE staff.EntityGroupConfigID = @EntityGroupConfigID + END + ELSE + BEGIN + INSERT INTO #FilteredData + SELECT [staff].[StaffingID], [staff].[DepartmentID], [staff].[JobCodeID], [staff].[PayCodeGroupID] + FROM [fp].[Staffing] staff + WHERE staff.EntityGroupConfigID = @EntityGroupConfigID + END + + --If no records, don't even go into the next part + IF(EXISTS(SELECT 1 FROM #FilteredData)) + BEGIN + + + UPDATE fte + SET fte.ActualYTDFTEsTotal = fte.ActualYTDHoursTotal / currentWorkingHours.MonthYearly, + fte.PriorYearActualFTEsTotal = fte.PriorYearActualHoursTotal / priorWorkingHours.MonthYearly, + fte.CurrentYearBudgetFTEsTotal = fte.CurrentYearBudgetHoursTotal / currentWorkingHours.MonthYearly + FROM [fp].[StaffingHistory] fte + INNER JOIN #FilteredData fdata ON fte.StaffingID = fdata.StaffingID + INNER JOIN [fw].[DimJobCode] jc ON fdata.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept ON fdata.DepartmentID = dept.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] currentWorkingHours ON currentWorkingHours.FiscalYearID = @CurrentFiscalYearID + AND currentWorkingHours.WorkWeekID = + ( + CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID + ELSE dept.WorkWeekID END + ) + INNER JOIN [client].[FactWorkingHoursPerMonth] priorWorkingHours ON priorWorkingHours.FiscalYearID = @CurrentFiscalYearID - 1 + AND priorWorkingHours.WorkWeekID = + ( + CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID + ELSE dept.WorkWeekID END + ) + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc ON fdata.PayCodeGroupID = exc.PayCodeGroupID + WHERE exc.PayCodeGroupID IS NULL + AND EXISTS ( + SELECT fte.ActualYTDFTEsTotal,fte.PriorYearActualFTEsTotal,fte.CurrentYearBudgetFTEsTotal + EXCEPT + SELECT CAST(fte.ActualYTDHoursTotal / currentWorkingHours.MonthYearly AS DECIMAL(19,8)), CAST(fte.PriorYearActualHoursTotal / priorWorkingHours.MonthYearly AS DECIMAL(19,8)),CAST(fte.CurrentYearBudgetHoursTotal / currentWorkingHours.MonthYearly AS DECIMAL(19,8)) + ) + END +END +GO + + +--------------------------------------------- + +-- fp.procSampleStaffingHoursPerUOS +CREATE PROCEDURE [fp].[procSampleStaffingHoursPerUOS] + @BudgetConfigID INT, + @EntityGroupConfigID INT, + @EntityGroupConfigGUID UNIQUEIDENTIFIER, + @StaffingFiscalYearID INT, + @StaffingTimeClassID INT, + @CurrentFiscalYearID INT, + @ActualTimeClassID INT, + @MonthsLoaded INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table + ** 2 2019-04-08 BK Failing Test Fix previous update of proc that incorrectly included old projection code + ** 3 2020-05-12 BK D-09757 Change projection hours/uos calc to use int.FactStaffing so that we don't use variable staffing hours that used working hours to potential leap year adjustment (what is in fp.FactStaffing) + ** 4 2021-02-10 BK ------- Found incorrect reference to SubsectionID = 0 + ** 5 2021-06-08 LR JAZZ-20116 Moving feature flag to plan config level + ** 6 2021-12-09 BK JAZZ-30703 Use fp.FactStatisticsHistory historicals instead of int.FactStatistic + ** 7 2022-03-14 NT JAZZ-33622 Improve performance by replacing LEFT by INNER join and add missing FlexingTypeID filter + ** 8 2022-04-29 MY JAZZ-28395 Cache Variability Percentage on FactStaffing + ** 9 2022-10-04 MY JAZZ-37262 Remove Feature Flag 'Use Variability From FactStaffing Table' + ** 10 11-7-2022 MY JAZZ-35951 Add EmployeeID to FactStaffingVariabilityDetail + ** 11 2023-03-13 MY JAZZ-48981 Update sampling for cross department flexing + ** 12 2023-09-19 JB JAZZ-59196 Remove FF Use int.FactStaffing to calculate Hours Per UOS + ** 13 2023-09-20 BK JAZZ-60973 Update for new data structure + ** 14 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config + ** 15 2024-08-26 MY JAZZ-76040 Adjust Statistics for Leap Year + ** 16 2024-08-28 NH JAZZ-74968 JobCodeID updates + *************************************************************/ + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment; + IF OBJECT_ID('tempdb..#variableHours') IS NOT NULL DROP TABLE #variableHours; + IF OBJECT_ID('tempdb..#statsBudget') IS NOT NULL DROP TABLE #statsBudget; + + DECLARE @EnableLeapYearAdjustedStatistics BIT = ISNULL((SELECT bcs.Value + FROM fp.viewBudgetConfigSetting bcs + INNER JOIN fp.BudgetConfig bc ON bcs.BudgetConfigID = bc.BudgetConfigID + INNER JOIN fp.EntityGroupConfig egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID + WHERE bcs.Name = 'Enable Leap Year Adjusted Statistics for Calculating Rates' + AND egc.EntityGroupConfigID = @EntityGroupConfigID), 0); + + CREATE TABLE #FilterByDepartment (DepartmentID int) + CREATE TABLE #statsBudget (DepartmentID INT, JobCodeID INT, StatTotal DECIMAL(19,8)) + + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[Staffing] d WITH (READUNCOMMITTED) + WHERE BudgetConfigID = @BudgetConfigID + AND FlexingTypeID = 3 -- Staffing + END + + DECLARE @IsAnnualized BIT = (CASE WHEN @StaffingFiscalYearID = @CurrentFiscalYearID AND @StaffingTimeClassID = 1 AND @MonthsLoaded < 12 THEN 1 ELSE 0 END) + DECLARE @UsePriorYear BIT = 0; + DECLARE @UseActualYTD BIT = 0; + DECLARE @UseCurrentYearBudget BIT = 0; + DECLARE @IsCurrentYearALeapYear BIT = (CASE WHEN (@CurrentFiscalYearID % 4 = 0 AND @CurrentFiscalYearID % 100 <> 0) OR @CurrentFiscalYearID % 400 = 0 THEN 1 ELSE 0 END) + DECLARE @AdjustStatisticsForLeapYear BIT = CASE WHEN @EnableLeapYearAdjustedStatistics = 1 AND @IsAnnualized = 1 AND @IsCurrentYearALeapYear = 1 THEN 1 ELSE 0 END; + + IF @StaffingTimeClassID = 2 BEGIN + SET @UseCurrentYearBudget = 1; + END ELSE BEGIN + IF @CurrentFiscalYearID = @StaffingFiscalYearID BEGIN + SET @UseActualYTD = 1; + END ELSE BEGIN + SET @UsePriorYear = 1 + END + END + + + INSERT INTO #statsBudget + SELECT + map.DepartmentID, + map.PRJobCodeID as JobCodeID, + CASE + WHEN @UseActualYTD = 1 AND @EnableLeapYearAdjustedStatistics = 1 THEN ISNULL(SUM(statHist.ActualYTDValueTotal), 0) + WHEN @UseCurrentYearBudget = 1 AND @EnableLeapYearAdjustedStatistics = 1 THEN ISNULL(SUM(statHist.CurrentYearBudgetTotal), 0) + WHEN @UsePriorYear = 1 AND @EnableLeapYearAdjustedStatistics = 1 THEN ISNULL(SUM(statHist.PriorYearActualValueTotal), 0) + -- JAZZ-76040: This isn't really related, but it was fixed as part of this story. Wrapping this in a feature flag + -- because otherwise rates will change + WHEN @UseActualYTD = 1 AND @EnableLeapYearAdjustedStatistics = 0 THEN CAST(ISNULL(SUM(statHist.ActualYTDValueTotal), 0) AS INT) + WHEN @UseCurrentYearBudget = 1 AND @EnableLeapYearAdjustedStatistics = 0 THEN CAST(ISNULL(SUM(statHist.CurrentYearBudgetTotal), 0) AS INT) + WHEN @UsePriorYear = 1 AND @EnableLeapYearAdjustedStatistics = 0 THEN CAST(ISNULL(SUM(statHist.PriorYearActualValueTotal), 0) AS INT) + END AS StatTotal + FROM [fp].[FlexConfigMapping] map + INNER JOIN fp.[FactStatistics] stat ON stat.DepartmentID = map.SourceDepartmentID AND stat.AccountID = map.StatAccountID AND stat.BudgetConfigID = @BudgetConfigID + INNER JOIN fp.[FactStatisticsHistory] statHist ON stat.StatisticsID = statHist.StatisticsID + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = map.DepartmentID + WHERE map.EntityGroupConfigID = @EntityGroupConfigID + AND map.FlexingTypeID = 3 -- Staffing + GROUP BY + map.DepartmentID, + map.PRJobCodeID + + CREATE TABLE #variableHours (StaffingID int, --DepartmentID int, JobCodeID smallint, PayCodeGroupID int, EntityGroupConfigID int, ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int, + BudgetHourTotal decimal(19,8)) + + CREATE TABLE #staffingVariability (DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, EmployeeID INT, FixedPercentage DECIMAL(38, 6)) + + INSERT INTO #staffingVariability (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, FixedPercentage) + SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, MAX(FixedPercentage) AS FixedPercentage + FROM [fp].[viewFactStaffingVariability] fav + INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigID = @EntityGroupConfigID AND egc.EntityGroupConfigGUID = fav.EntityGroupConfigGUID + WHERE ProviderLineItemID = 0 -- ProviderLineItems do not have + GROUP BY DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID + + + DECLARE @IsProviderPlanningEnabled BIT; + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID; + DECLARE @ProviderSubsectionID INT = 4; + + INSERT INTO #variableHours + SELECT fs.StaffingID, + /*fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeGroupID, + fs.EntityGroupConfigID, + fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, fs.SubsectionID,*/ + COALESCE(1 - fv.FixedPercentage, 0) * total.SampledBudgetTotal AS BudgetHourTotal + FROM [fp].[Staffing] fs + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = fs.DepartmentID) + INNER JOIN ( + SELECT + src.DepartmentID, src.JobCodeID, pc.PayCodeGroupID, 0 as ProviderID, 0 as ProviderTypeID, 0 as ProviderSpecialtyID, 0 as ProviderLineItemID, 3 as SubsectionID, SUM(ISNULL(src.Value, 0)) as SampledBudgetTotal + FROM [int].[FactStaffing] src + INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = src.PayCodeID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID + WHERE src.FiscalYearID = @StaffingFiscalYearID + AND src.TimeClassID = @StaffingTimeClassID + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 51 + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + AND pc.IsHoursIgnored = 0 + GROUP BY src.DepartmentID, src.JobCodeID, pc.PayCodeGroupID + ) as total + ON total.DepartmentID = fs.DepartmentID + AND total.JobCodeID = fs.JobCodeID + AND total.PayCodeGroupID = fs.PayCodeGroupID + AND total.ProviderID = fs.ProviderID + AND total.ProviderTypeID = fs.ProviderTypeID + AND total.ProviderSpecialtyID = fs.ProviderSpecialtyID + AND total.ProviderLineItemID = fs.ProviderLineItemID + AND total.SubsectionID = fs.SubsectionID + LEFT JOIN #staffingVariability fv + ON fv.DepartmentID = fs.DepartmentID + AND fv.JobCodeID = fs.JobCodeID + AND fv.PayCodeGroupID = fs.PayCodeGroupID + AND fv.EmployeeID = fs.EmployeeID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.VariabilityID = 2 + AND (@IsProviderPlanningEnabled = 0 OR fs.SubSectionID <> @ProviderSubsectionID) + + -- JAZZ-76040: Adjust Statistics and Hours for Leap Year + IF (@AdjustStatisticsForLeapYear = 1) + BEGIN + + -- per stackoverflow (per MY) + DECLARE @BudgetFiscalYearID INT = @CurrentFiscalYearID + 1; + DECLARE @IsBudgetLeapYear BIT = (CASE WHEN (@BudgetFiscalYearID % 4 = 0 AND @BudgetFiscalYearID % 100 <> 0) OR @BudgetFiscalYearID % 400 = 0 THEN 1 ELSE 0 END) + DECLARE @DaysBudgetYear decimal = (SELECT (CASE WHEN @IsBudgetLeapYear = 1 THEN YTDDaysInLeapYearMonth ELSE YTDDaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder = 12) + DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsCurrentYearALeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded) + + UPDATE #statsBudget + SET StatTotal = ((StatTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) + + UPDATE #variableHours + SET BudgetHourTotal = ((BudgetHourTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) + + END + + -- set the Dollars/UOS values on Staffing table + UPDATE + fs + SET + InitialBudgetRate01 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate02 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate03 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate04 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate05 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate06 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate07 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate08 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate09 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate10 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate11 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialBudgetRate12 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + + + -- Projection rates should match the budget rates and use the budget baseline to calculate + InitialProjectionRate01 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate02 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate03 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate04 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate05 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate06 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate07 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate08 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate09 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate10 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate11 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0), + InitialProjectionRate12 = COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) + + FROM + [fp].[Staffing] fs + INNER JOIN #variableHours fsHours + ON fs.StaffingID = fsHours.StaffingID /*fs.DepartmentID = fsHours.DepartmentID + AND fs.JobCodeID = fsHours.JobCodeID + AND fs.PayCodeGroupID = fsHours.PayCodeGroupID + AND fs.EntityGroupConfigID = fsHours.EntityGroupConfigID */ + INNER JOIN #statsBudget stat + ON stat.DepartmentID = fs.DepartmentID + AND stat.JobCodeID = fs.JobCodeID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID + AND ( + + fs.InitialBudgetRate01 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate02 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate03 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate04 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate05 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate06 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate07 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate08 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate09 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate10 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate11 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialBudgetRate12 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + + fs.InitialProjectionRate01 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate02 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate03 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate04 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate05 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate06 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate07 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate08 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate09 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate10 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate11 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0) OR + fs.InitialProjectionRate12 != COALESCE(fsHours.BudgetHourTotal/NULLIF(stat.StatTotal, 0), 0)) + + +END +GO + + +--------------------------------------------- + +-- fp.procSampleStaffingInitialBudgetDollars +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-09-20 BK JAZZ-60973 Update for data restructure +** 2 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config +** 3 2024-03-20 MY JAZZ-69388 Migration to resolve JAZZ-59251 was reverted by the next migration to the proc for new data structure. +*************************************************************/ +CREATE PROCEDURE [fp].[procSampleStaffingInitialBudgetDollars] + @EntityGroupConfigID int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + DECLARE @IsProviderPlanningEnabled BIT; + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID; + DECLARE @ProviderSubsectionID INT; + SELECT @ProviderSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Provider' + + + CREATE TABLE #filterTable (DepartmentID int) + INSERT INTO #filterTable (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #filterTable (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fp.Staffing + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + -- Spread Dollars-Only evenly + UPDATE + fs + SET + InitialBudgetDollars01 = SampledBudgetDollarsTotal/12, + InitialBudgetDollars02 = SampledBudgetDollarsTotal/12, + InitialBudgetDollars03 = SampledBudgetDollarsTotal/12, + InitialBudgetDollars04 = SampledBudgetDollarsTotal/12, + InitialBudgetDollars05 = SampledBudgetDollarsTotal/12, + InitialBudgetDollars06 = SampledBudgetDollarsTotal/12, + InitialBudgetDollars07 = SampledBudgetDollarsTotal/12, + InitialBudgetDollars08 = SampledBudgetDollarsTotal/12, + InitialBudgetDollars09 = SampledBudgetDollarsTotal/12, + InitialBudgetDollars10 = SampledBudgetDollarsTotal/12, + InitialBudgetDollars11 = SampledBudgetDollarsTotal/12, + InitialBudgetDollars12 = SampledBudgetDollarsTotal - ((SampledBudgetDollarsTotal / 12) + (SampledBudgetDollarsTotal / 12) + (SampledBudgetDollarsTotal / 12) + (SampledBudgetDollarsTotal / 12) + (SampledBudgetDollarsTotal / 12) + + (SampledBudgetDollarsTotal / 12) + (SampledBudgetDollarsTotal / 12) + (SampledBudgetDollarsTotal / 12) + (SampledBudgetDollarsTotal / 12) + (SampledBudgetDollarsTotal / 12) + (SampledBudgetDollarsTotal / 12) ) + FROM [fp].[Staffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND (fs.ProductiveClassID = 4 OR (@IsProviderPlanningEnabled = 1 AND SubsectionID = @ProviderSubsectionID)) + + + -- Now do all non Dollars-Only + + -- All other productive classes should be hours * wage rate + -- Known issue to resolve, if no hours/wage rate, then all dollars will be put in month 12 + UPDATE + fs + SET + fs.InitialBudgetDollars01 = fs.InitialBudgetHours01 * wr.InitialBudget01, + fs.InitialBudgetDollars02 = fs.InitialBudgetHours02 * wr.InitialBudget02, + fs.InitialBudgetDollars03 = fs.InitialBudgetHours03 * wr.InitialBudget03, + fs.InitialBudgetDollars04 = fs.InitialBudgetHours04 * wr.InitialBudget04, + fs.InitialBudgetDollars05 = fs.InitialBudgetHours05 * wr.InitialBudget05, + fs.InitialBudgetDollars06 = fs.InitialBudgetHours06 * wr.InitialBudget06, + fs.InitialBudgetDollars07 = fs.InitialBudgetHours07 * wr.InitialBudget07, + fs.InitialBudgetDollars08 = fs.InitialBudgetHours08 * wr.InitialBudget08, + fs.InitialBudgetDollars09 = fs.InitialBudgetHours09 * wr.InitialBudget09, + fs.InitialBudgetDollars10 = fs.InitialBudgetHours10 * wr.InitialBudget10, + fs.InitialBudgetDollars11 = fs.InitialBudgetHours11 * wr.InitialBudget11, + fs.InitialBudgetDollars12 = fs.InitialBudgetHours12 * wr.InitialBudget12 + FROM [fp].[Staffing] fs + INNER JOIN fp.StaffingWageRate wr on fs.StaffingWageRateID = wr.StaffingWageRateID + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.ProductiveClassID <> 4 AND (fs.SubsectionID <> @ProviderSubsectionID OR @IsProviderPlanningEnabled = 0) + +END +GO + + +--------------------------------------------- + +-- fp.procSampleStaffingInitialProjectionDollars +CREATE PROCEDURE [fp].[procSampleStaffingInitialProjectionDollars] + @EntityGroupConfigID int, + @MonthsLoaded int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +WITH RECOMPILE +AS +BEGIN +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-03-20 BK JAZZ-50830 Fix issue with Provider not being updated for BudgetPhaseID = 2 +** 2 2023-09-20 BK JAZZ-60973 Update for data restructure +** 3 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config +** 4 2024-03-20 MY JAZZ-69388 Migration to resolve JAZZ-59251 was reverted by the next migration to the proc for new data structure. +************************************************************** +*/ + DECLARE @IsProviderPlanningEnabled BIT, @StaffingTimeClassID INT, @StaffingFiscalYearID INT, @ProjectionFiscalYearID INT; + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID; + DECLARE @ProviderSubsectionID INT; + SELECT @ProviderSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Provider' + + SELECT @StaffingTimeClassID = PayrollTimeClassID, @StaffingFiscalYearID = PayrollFiscalYearID, @ProjectionFiscalYearID = FiscalYearID - 1 + FROM fp.EntityGroupConfig egc INNER JOIN fp.BudgetConfig bc on egc.BudgetConfigGUID = bc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID + + + CREATE TABLE #filterTable (DepartmentID int) + INSERT INTO #filterTable (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #filterTable (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fp.Staffing + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + + -- Update all Non Dollars-Only Productive Classes + UPDATE + fs + SET + InitialProjectionDollars01 = CASE WHEN @MonthsLoaded >= 1 THEN fs.SampledProjectionDollars01 ELSE fs.InitialProjectionHours01 * wr.InitialProjection01 END, + InitialProjectionDollars02 = CASE WHEN @MonthsLoaded >= 2 THEN fs.SampledProjectionDollars02 ELSE fs.InitialProjectionHours02 * wr.InitialProjection02 END, + InitialProjectionDollars03 = CASE WHEN @MonthsLoaded >= 3 THEN fs.SampledProjectionDollars03 ELSE fs.InitialProjectionHours03 * wr.InitialProjection03 END, + InitialProjectionDollars04 = CASE WHEN @MonthsLoaded >= 4 THEN fs.SampledProjectionDollars04 ELSE fs.InitialProjectionHours04 * wr.InitialProjection04 END, + InitialProjectionDollars05 = CASE WHEN @MonthsLoaded >= 5 THEN fs.SampledProjectionDollars05 ELSE fs.InitialProjectionHours05 * wr.InitialProjection05 END, + InitialProjectionDollars06 = CASE WHEN @MonthsLoaded >= 6 THEN fs.SampledProjectionDollars06 ELSE fs.InitialProjectionHours06 * wr.InitialProjection06 END, + InitialProjectionDollars07 = CASE WHEN @MonthsLoaded >= 7 THEN fs.SampledProjectionDollars07 ELSE fs.InitialProjectionHours07 * wr.InitialProjection07 END, + InitialProjectionDollars08 = CASE WHEN @MonthsLoaded >= 8 THEN fs.SampledProjectionDollars08 ELSE fs.InitialProjectionHours08 * wr.InitialProjection08 END, + InitialProjectionDollars09 = CASE WHEN @MonthsLoaded >= 9 THEN fs.SampledProjectionDollars09 ELSE fs.InitialProjectionHours09 * wr.InitialProjection09 END, + InitialProjectionDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.SampledProjectionDollars10 ELSE fs.InitialProjectionHours10 * wr.InitialProjection10 END, + InitialProjectionDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.SampledProjectionDollars11 ELSE fs.InitialProjectionHours11 * wr.InitialProjection11 END, + InitialProjectionDollars12 = CASE WHEN @MonthsLoaded = 12 THEN fs.SampledProjectionDollars12 ELSE fs.InitialProjectionHours12 * wr.InitialProjection12 END + FROM [fp].[Staffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + INNER JOIN [fp].[StaffingWageRate] wr on fs.StaffingWageRateID = wr.StaffingWageRateID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.ProductiveClassID <> 4 -- not 'Dollars-Only' + AND (fs.SubsectionID <> @ProviderSubsectionID OR @IsProviderPlanningEnabled = 0) -- not provider data + + + -- Dollars-Only Productive Class + -- Spread Dollars-Only evenly when not using Current Year Budget as baseline + + IF @StaffingTimeClassID = 2 AND @StaffingFiscalYearID = @ProjectionFiscalYearID + BEGIN + UPDATE + fs + SET + InitialProjectionDollars01 = SampledProjectionDollars01, + InitialProjectionDollars02 = SampledProjectionDollars02, + InitialProjectionDollars03 = SampledProjectionDollars03, + InitialProjectionDollars04 = SampledProjectionDollars04, + InitialProjectionDollars05 = SampledProjectionDollars05, + InitialProjectionDollars06 = SampledProjectionDollars06, + InitialProjectionDollars07 = SampledProjectionDollars07, + InitialProjectionDollars08 = SampledProjectionDollars08, + InitialProjectionDollars09 = SampledProjectionDollars09, + InitialProjectionDollars10 = SampledProjectionDollars10, + InitialProjectionDollars11 = SampledProjectionDollars11, + InitialProjectionDollars12 = SampledProjectionDollars12 + FROM [fp].[Staffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND (fs.ProductiveClassID = 4 OR (@IsProviderPlanningEnabled = 1 AND SubsectionID = @ProviderSubsectionID)) + + END ELSE + BEGIN + CREATE TABLE #DollarTotals (StaffingID INT, ProjectionTotal DECIMAL(19,8), NewValue DECIMAL(19,8), + INDEX ix_dol_1 NONCLUSTERED (StaffingID)) + + INSERT INTO #DollarTotals (StaffingID, ProjectionTotal) + SELECT staff.StaffingID, + CASE WHEN @MonthsLoaded = 11 THEN staff.SampledProjectionDollars12 + WHEN @MonthsLoaded = 10 THEN staff.SampledProjectionDollars11 + staff.SampledProjectionDollars12 + WHEN @MonthsLoaded = 9 THEN staff.SampledProjectionDollars10 + staff.SampledProjectionDollars11 + staff.SampledProjectionDollars12 + WHEN @MonthsLoaded = 8 THEN staff.SampledProjectionDollars09 + staff.SampledProjectionDollars10 + staff.SampledProjectionDollars11 + staff.SampledProjectionDollars12 + WHEN @MonthsLoaded = 7 THEN staff.SampledProjectionDollars08 + staff.SampledProjectionDollars09 + staff.SampledProjectionDollars10 + staff.SampledProjectionDollars11 + staff.SampledProjectionDollars12 + WHEN @MonthsLoaded = 6 THEN staff.SampledProjectionDollars07 + staff.SampledProjectionDollars08 + staff.SampledProjectionDollars09 + staff.SampledProjectionDollars10 + staff.SampledProjectionDollars11 + staff.SampledProjectionDollars12 + WHEN @MonthsLoaded = 5 THEN staff.SampledProjectionDollars06 + staff.SampledProjectionDollars07 + staff.SampledProjectionDollars08 + staff.SampledProjectionDollars09 + staff.SampledProjectionDollars10 + staff.SampledProjectionDollars11 + staff.SampledProjectionDollars12 + WHEN @MonthsLoaded = 4 THEN staff.SampledProjectionDollars05 + staff.SampledProjectionDollars06 + staff.SampledProjectionDollars07 + staff.SampledProjectionDollars08 + staff.SampledProjectionDollars09 + staff.SampledProjectionDollars10 + staff.SampledProjectionDollars11 + staff.SampledProjectionDollars12 + WHEN @MonthsLoaded = 3 THEN staff.SampledProjectionDollars04 + staff.SampledProjectionDollars05 + staff.SampledProjectionDollars06 + staff.SampledProjectionDollars07 + staff.SampledProjectionDollars08 + staff.SampledProjectionDollars09 + staff.SampledProjectionDollars10 + staff.SampledProjectionDollars11 + staff.SampledProjectionDollars12 + WHEN @MonthsLoaded = 2 THEN staff.SampledProjectionDollars03 + staff.SampledProjectionDollars04 + staff.SampledProjectionDollars05 + staff.SampledProjectionDollars06 + staff.SampledProjectionDollars07 + staff.SampledProjectionDollars08 + staff.SampledProjectionDollars09 + staff.SampledProjectionDollars10 + staff.SampledProjectionDollars11 + staff.SampledProjectionDollars12 + WHEN @MonthsLoaded = 1 THEN staff.SampledProjectionDollars02 + staff.SampledProjectionDollars03 + staff.SampledProjectionDollars04 + staff.SampledProjectionDollars05 + staff.SampledProjectionDollars06 + staff.SampledProjectionDollars07 + staff.SampledProjectionDollars08 + staff.SampledProjectionDollars09 + staff.SampledProjectionDollars10 + staff.SampledProjectionDollars11 + staff.SampledProjectionDollars12 + ELSE 0 + END + FROM [fp].[Staffing] staff + INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID + WHERE staff.EntityGroupConfigID = @EntityGroupConfigID AND (staff.ProductiveClassID = 4 OR (@IsProviderPlanningEnabled = 1 AND SubsectionID = @ProviderSubsectionID)) + + + UPDATE a + SET NewValue = ProjectionTotal / (12.0 - @MonthsLoaded) + FROM #DollarTotals a + + + -- update initial projection for dollars and hours + UPDATE fs + SET + fs.InitialProjectionDollars01 = CASE WHEN @MonthsLoaded >= 1 THEN fs.SampledProjectionDollars01 ELSE t.NewValue END, + fs.InitialProjectionDollars02 = CASE WHEN @MonthsLoaded >= 2 THEN fs.SampledProjectionDollars02 ELSE t.NewValue END, + fs.InitialProjectionDollars03 = CASE WHEN @MonthsLoaded >= 3 THEN fs.SampledProjectionDollars03 ELSE t.NewValue END, + fs.InitialProjectionDollars04 = CASE WHEN @MonthsLoaded >= 4 THEN fs.SampledProjectionDollars04 ELSE t.NewValue END, + fs.InitialProjectionDollars05 = CASE WHEN @MonthsLoaded >= 5 THEN fs.SampledProjectionDollars05 ELSE t.NewValue END, + fs.InitialProjectionDollars06 = CASE WHEN @MonthsLoaded >= 6 THEN fs.SampledProjectionDollars06 ELSE t.NewValue END, + fs.InitialProjectionDollars07 = CASE WHEN @MonthsLoaded >= 7 THEN fs.SampledProjectionDollars07 ELSE t.NewValue END, + fs.InitialProjectionDollars08 = CASE WHEN @MonthsLoaded >= 8 THEN fs.SampledProjectionDollars08 ELSE t.NewValue END, + fs.InitialProjectionDollars09 = CASE WHEN @MonthsLoaded >= 9 THEN fs.SampledProjectionDollars09 ELSE t.NewValue END, + fs.InitialProjectionDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.SampledProjectionDollars10 ELSE t.NewValue END, + fs.InitialProjectionDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.SampledProjectionDollars11 ELSE t.NewValue END, + fs.InitialProjectionDollars12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.SampledProjectionDollars12 ELSE t.NewValue END + FROM + [fp].[Staffing] fs INNER JOIN #DollarTotals t on fs.StaffingID = t.StaffingID + + END + + +END +GO + + +--------------------------------------------- + +-- fp.procSampleStaffingOriginalBudgetDollars +CREATE PROCEDURE [fp].[procSampleStaffingOriginalBudgetDollars] + @EntityGroupConfigGUID uniqueidentifier, + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @BudgetYearID smallint, + @SourceFiscalYearID smallint, + @SourceTimeClassID tinyint, + @MonthsLoaded int, + @IsEmployeeBudgeting bit, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 4 2021-03-22 NT JAZZ-15374 Use NPI instead of EmployeID for Provider Comp Sampling + ** 5 2021-06-30 BW JAZZ-21627 Update selects and group by for EmployeID for variablity + ** 6 2021-12-01 OP JAZZ-29466 removed empty users check for prov comp data + ** 7 2022-02-14 BK JAZZ-33248 respect department setting for employee budgeting + ** 8 2022-03-02 MZ JAZZ-30547 improved checks in order to sample valid Employees with valid NPI + ** 9 2022-05-27 OP JAZZ-30811 sample prov comp data + ** 10 2022-08-08 BK JAZZ-38357 Make sure IsFP records are correctly sampled depending on if true or false + ** 11 2022-10-07 AO JAZZ-42868 Non-provider department samples correct staffing values when provider sampling feature is turned on. + ** 12 2022-11-07 MZ JAZZ-35344 improved checks in order to sample valid Employees with valid NPI from FactProvider + ** 13 2022-11-07 MY JAZZ-35951 Add EmployeeID to FactStaffingVariabilityDetail + ** 14 2022-12-12 DM JAZZ-46455 Sampling of Provider Type and Provider Specialty is linked to Section Setup + ** 15 2023-09-26 BK JAZZ-61239 Fix variable dept/job code incorrectly ignoring data that has EmployeeID in int.FactStaffing + ** 16 2023-09-30 BK JAZZ-60973 Update for data restructure + ** 17 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config + ** 18 2024-03-25 MY JAZZ-69661 Duplicated data for non-Provider departments in client dbs who utilize Provider Planning + ** 19 2024-06-18 MZ JAZZ-72231 Added Source Provider Sampling + ** 20 2024-08-12 MD JAZZ-75302 Adjust dollars for leap year + *************************************************************/ + + IF OBJECT_ID('tempdb..#filterTable') IS NOT NULL DROP TABLE #filterTable + IF OBJECT_ID('tempdb..#IntStaffingData') IS NOT NULL DROP TABLE #IntStaffingData + IF OBJECT_ID('tempdb..#TempIntStaffingData') IS NOT NULL DROP TABLE #TempIntStaffingData + IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolved') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolved + IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolvedForProvider') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolvedForProvider + IF OBJECT_ID('tempdb..#WorkingHoursRatioData') IS NOT NULL DROP TABLE #WorkingHoursRatioData + + DECLARE @IsAnnualized BIT = (CASE WHEN @SourceFiscalYearID = @CurrentFiscalYearID AND @SourceTimeClassID = 1 AND @MonthsLoaded < 12 THEN 1 ELSE 0 END) + DECLARE @IsProviderPlanningEnabled BIT; + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID; + + DECLARE @UseProviderSource BIT; + DECLARE @SampleProviderEitherFromStaffingOrProviderIntTable BIT; + DECLARE @AdjustWageRateByDaysInYear BIT = 0; + DECLARE @BudgetConfigID INT = (SELECT BudgetConfigID FROM fp.EntityGroupConfig a INNER JOIN fp.BudgetConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID) + + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled, @UseProviderSource = UseProviderSource FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID; + + SELECT @SampleProviderEitherFromStaffingOrProviderIntTable = Value FROM fp.BudgetConfigSetting bcs + INNER JOIN fp.BudgetConfigDefaultSetting bcds ON bcs.SettingID = bcds.SettingID + WHERE Name = 'Sample Provider either from Staffing or Provider int tables' AND BudgetConfigID = @BudgetConfigID + + SELECT @AdjustWageRateByDaysInYear = ISNULL(Value,0) FROM fp.BudgetConfigSetting bcs + INNER JOIN fp.BudgetConfigDefaultSetting bcds ON bcs.SettingID = bcds.SettingID + WHERE Name = 'Adjust Wage Rate by Days in Year' AND BudgetConfigID = @BudgetConfigID + + CREATE TABLE #filterTable (DepartmentID int) + INSERT INTO #filterTable (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #filterTable (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fp.Staffing + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + CREATE TABLE #IntStaffingData ( + DepartmentID int, + JobCodeID int, + PayCodeGroupID int, + EmployeeID int, + ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int, + MonthColumnName varchar(50), + FixedPercentage decimal(19,8), + Value decimal (19,8) + ) + + CREATE TABLE #TempIntStaffingData ( + DepartmentID int, + JobCodeID int, + PayCodeGroupID int, + EmployeeID int, + ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int, + MonthColumnName varchar(50), + FixedPercentage decimal(19,8), + Value decimal (19,8) + ) + + CREATE TABLE #WorkingHoursRatioData ( + DepartmentID int, + JobCodeID int, + PayCodeGroupID int, + MonthRatio01 decimal(19,8), + MonthRatio02 decimal (19,8), + MonthRatio03 decimal (19,8), + MonthRatio04 decimal (19,8), + MonthRatio05 decimal (19,8), + MonthRatio06 decimal (19,8), + MonthRatio07 decimal (19,8), + MonthRatio08 decimal (19,8), + MonthRatio09 decimal (19,8), + MonthRatio10 decimal (19,8), + MonthRatio11 decimal (19,8), + MonthRatio12 decimal (19,8) + ) + + IF @IsProviderPlanningEnabled = 0 + BEGIN + + ------------------------------------ + -- Provider disabled + ------------------------------------ + + -- Resolve EmployeeID up front so we don't have to do it every time. + SELECT + src.DepartmentID, + src.JobCodeID, + src.PayCodeID, + CASE + WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 + ELSE CASE + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE src.EmployeeID + END + END as EmployeeID, + 0 AS ProviderID, + 0 AS ProviderTypeID, + 0 AS ProviderSpecialtyID, + 0 AS ProviderLineItemID, + src.FiscalYearID, + src.TimeClassID, + src.UnitTypeID, + src.FiscalMonthID, + src.IsDeleted, + Value + INTO #intFactStaffingWithEmployeeResolved + FROM [int].[FactStaffing] src + INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND CASE WHEN @IsEmployeeBudgeting = 0 OR ISNULL(sefg.IsUsingEmployeeBudgeting, 0) = 0 THEN 0 -- When not using EB, we can just set it to 0. + -- int.FactStaffing that has variable dept/job code may have employee data due to how they populate data + -- see Jazz-61239 for more details + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 + ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not. + END = fv.EmployeeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE src.FiscalYearID = @SourceFiscalYearID + AND src.TimeClassID = @SourceTimeClassID + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 34 + + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID,MonthColumnName, FixedPercentage, Value) + SELECT + src.DepartmentID, + src.JobCodeID, + pc.PayCodeGroupID, + src.EmployeeID, + 0 as ProviderID, + 0 as ProviderTypeID, + 0 as ProviderSpecialtyID, + 0 as ProviderLineItemID, + 0 as SubsectionID, + fm.MonthColumnName, + ISNULL(fv.FixedPercentage,1) as FixedPercentage, + SUM(ISNULL(src.Value, 0)) as Value + FROM #intFactStaffingWithEmployeeResolved src + INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = src.PayCodeID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0. + -- int.FactStaffing that has variable dept/job code may have employee data due to how they populate data + -- the employeeID should be resolved to 0 from the code above this populating #intFactStaffingWithEmployeeResolved + -- see Jazz-61239 for more details + ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not. + END = fv.EmployeeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE src.FiscalYearID = @SourceFiscalYearID + AND src.TimeClassID = @SourceTimeClassID + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 34 + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + AND pc.IsDollarsIgnored = 0 + GROUP BY src.DepartmentID, + src.JobCodeID, + pc.PayCodeGroupID, + src.EmployeeID, + fm.MonthColumnName, + FixedPercentage + + END ELSE BEGIN + + ------------------------------------ + -- Provider enabled + ------------------------------------ + + IF OBJECT_ID('tempdb..#emp') IS NOT NULL DROP TABLE #emp + IF OBJECT_ID('tempdb..#dept') IS NOT NULL DROP TABLE #dept + IF OBJECT_ID('tempdb..#provDims') IS NOT NULL DROP TABLE #provDims + CREATE TABLE #emp (DepartmentID INT, EmployeeID INT, ProviderID INT, ProviderTypeID INT, ProviderSpecialtyID INT, IsFP BIT) + CREATE TABLE #dept (DepartmentID INT, EntityID INT, UseProvider BIT) + CREATE TABLE #provDims (DepartmentID INT, ProviderID INT, ProviderLineItemID INT) + DECLARE @StaffingSubsectionID INT; + DECLARE @ProviderSubsectionID INT; + SELECT @StaffingSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Staffing' + SELECT @ProviderSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Provider' + + DECLARE @IsProviderTypeDisabled BIT; + SELECT @IsProviderTypeDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderTypeID' AND PlanSectionID = 3 AND SubSectionID = 1 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + + DECLARE @IsProviderSpecialtyDisabled BIT; + SELECT @IsProviderSpecialtyDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderSpecialtyID' AND PlanSectionID = 3 AND SubSectionID = 1 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + -- JAZZ-69661: Duplicated data for non-Provider departments in client dbs who utilize Provider Planning + DECLARE @EnableDepartmentLevelProviderForSampling BIT = ISNULL((SELECT 1 + FROM fp.BudgetConfigSetting setting + INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON setting.SettingID = def.SettingID + WHERE def.Name = 'Enable Department Level Provider For Sampling' + AND setting.BudgetConfigID = @BudgetConfigID + AND setting.Value = 1), 0) + + IF @SampleProviderEitherFromStaffingOrProviderIntTable = 0 + BEGIN + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeclassID = @SourceTimeClassID AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + UNION + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + + -- 2. all employees that are providers + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END, + emp.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID + INNER JOIN [dss].[DimPhysician] phys ON phys.NPI = emp.NPI + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeclassID = @SourceTimeClassID AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND staff.EmployeeID > 0 + AND emp.NPI NOT IN ('Not Specified', '0', '') + UNION + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, + phys.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND phys.NPI NOT IN ('Not Specified', '0', '') + + -- Provider from int.FactProvider + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + fp.DepartmentID, + 0 as JobCodeID, + 0 as PayCodeGroupID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + fp.ProviderLineItemID, + @ProviderSubsectionID, + fm.MonthColumnName, + 1 as FixedPercentage, + SUM(ISNULL(fp.Value, 0)) as Value + FROM + [int].[FactProvider] fp + INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + WHERE + fp.FiscalYearID = @SourceFiscalYearID + AND fp.TimeClassID = @SourceTimeClassID + AND fp.IsDeleted = 0 + AND fp.FiscalMonthID != 0 + AND fp.UnitTypeID = 34 + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + AND ps.Description = 'Staffing' + AND emp.IsFP = 1 + GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName, + emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID + + + INSERT INTO #provDims (DepartmentID, ProviderID, ProviderLineItemID) SELECT DISTINCT DepartmentID, ProviderID, ProviderLineItemID FROM #TempIntStaffingData + + -- Provider from int.FactStaffing + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + src.DepartmentID, + src.JobCodeID, + pcg.PayCodeGroupID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + pc.ProviderLineItemID, + @ProviderSubsectionID, + fm.MonthColumnName, + ISNULL(fv.FixedPercentage,1) as FixedPercentage, + SUM(ISNULL(src.Value, 0)) as Value + FROM + [int].[FactStaffing] src + INNER JOIN #dept dept ON src.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON src.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR src.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON src.PayCodeID = pc.PayCodeID + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND fv.EmployeeID = 0 + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN #provDims pd ON src.DepartmentID = pd.DepartmentID AND emp.ProviderID = pd.ProviderID and pd.ProviderLineItemID = pli.ProviderLineItemID + WHERE + src.FiscalYearID = @SourceFiscalYearID + AND src.TimeClassID = @SourceTimeClassID + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 34 + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + AND pc.IsDollarsIgnored = 0 + AND ps.Description = 'Staffing' + AND pd.DepartmentID IS NULL + AND emp.IsFP = 1 + GROUP BY src.DepartmentID, + src.JobCodeID, + pcg.PayCodeGroupID, + emp.EmployeeID, + fm.MonthColumnName, + FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID + + + + END ELSE BEGIN + + IF @UseProviderSource = 0 + BEGIN + + ------------------------------------------------------- + -- BudgetConfig UseProviderSource is disabled + ------------------------------------------------------- + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeclassID = @SourceTimeClassID AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + + -- 2. Employees from staffing + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END, + emp.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID + INNER JOIN [dss].[DimPhysician] phys ON phys.NPI = emp.NPI + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeclassID = @SourceTimeClassID AND staff.IsDeleted = 0 AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND staff.EmployeeID > 0 + AND emp.NPI NOT IN ('Not Specified', '0', '') + + -- Provider from int.FactStaffing + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + src.DepartmentID, + src.JobCodeID, + pcg.PayCodeGroupID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + pc.ProviderLineItemID, + @ProviderSubsectionID, + fm.MonthColumnName, + ISNULL(fv.FixedPercentage,1) as FixedPercentage, + SUM(ISNULL(src.Value, 0)) as Value + FROM + [int].[FactStaffing] src + INNER JOIN #dept dept ON src.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON src.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR src.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON src.PayCodeID = pc.PayCodeID + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND fv.EmployeeID = 0 + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE + src.FiscalYearID = @SourceFiscalYearID + AND src.TimeClassID = @SourceTimeClassID + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 34 + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + AND pc.IsDollarsIgnored = 0 + AND ps.Description = 'Staffing' + AND emp.IsFP = 1 + GROUP BY src.DepartmentID, + src.JobCodeID, + pcg.PayCodeGroupID, + emp.EmployeeID, + fm.MonthColumnName, + FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID + + + + END ELSE BEGIN + + ------------------------------------------------------- + -- BudgetConfig UseProviderSource is enabled + ------------------------------------------------------- + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + + -- 2. all employees that are providers + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, + phys.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND phys.NPI NOT IN ('Not Specified', '0', '') + + -- Provider from int.FactProvider + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + fp.DepartmentID, + 0 as JobCodeID, + 0 as PayCodeGroupID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + fp.ProviderLineItemID, + @ProviderSubsectionID, + fm.MonthColumnName, + 1 as FixedPercentage, + SUM(ISNULL(fp.Value, 0)) as Value + FROM + [int].[FactProvider] fp + INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + WHERE + fp.FiscalYearID = @SourceFiscalYearID + AND fp.TimeClassID = @SourceTimeClassID + AND fp.IsDeleted = 0 + AND fp.FiscalMonthID != 0 + AND fp.UnitTypeID = 34 + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + AND ps.Description = 'Staffing' + AND emp.IsFP = 1 + GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName, + emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID + + END + + END + + -- regular staffing + -- Populate into a temp table before summing up to deal with issues with the dynamic employee join + SELECT + src.DepartmentID, + src.JobCodeID, + pc.PayCodeID, + pc.PayCodeGroupID, + CASE + WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 + ELSE CASE + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE src.EmployeeID + END + END as EmployeeID, + 0 AS ProviderID, + 0 AS ProviderTypeID, + 0 AS ProviderSpecialtyID, + 0 AS ProviderLineItemID, + fm.FiscalMonthID, + fm.MonthColumnName, + ISNULL(fv.FixedPercentage, 1) as FixedPercentage, + ISNULL(src.Value, 0) as Value + INTO #intFactStaffingWithEmployeeResolvedForProvider + FROM [int].[FactStaffing] src + INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = src.PayCodeID + LEFT JOIN #dept dept ON tmp.DepartmentID = dept.DepartmentID + LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 1) emp ON src.EmployeeID = emp.EmployeeID + LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 0) NotFpEmp ON src.EmployeeID = NotFpEmp.EmployeeID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0. + -- int.FactStaffing that has variable dept/job code may have employee data due to how they populate data + -- see Jazz-61239 for more details + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 + ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not. + END = fv.EmployeeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE src.FiscalYearID = @SourceFiscalYearID + AND src.TimeClassID = @SourceTimeClassID + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 34 + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + AND pc.IsDollarsIgnored = 0 + AND (dept.DepartmentID IS NULL OR (emp.EmployeeID IS NULL AND (NotFpEmp.EmployeeID IS NULL OR NotFpEmp.IsFP = 0))) + + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID,MonthColumnName, FixedPercentage, Value) + SELECT + src.DepartmentID, + src.JobCodeID, + src.PayCodeGroupID, + src.EmployeeID, + 0 as ProviderID, + 0 as ProviderTypeID, + 0 as ProviderSpecialtyID, + 0 as ProviderLineItemID, + @StaffingSubsectionID as SubsectionID, + src.MonthColumnName, + ISNULL(fv.FixedPercentage,1) as FixedPercentage, + SUM(ISNULL(src.Value, 0)) as Value + FROM #intFactStaffingWithEmployeeResolvedForProvider src + INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND fv.EmployeeID = src.EmployeeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + GROUP BY src.DepartmentID, + src.JobCodeID, + src.PayCodeGroupID, + src.EmployeeID, + src.MonthColumnName, + fv.FixedPercentage + + END + + INSERT INTO #IntStaffingData + SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value + FROM #TempIntStaffingData + WHERE FixedPercentage = 1 + + INSERT INTO #IntStaffingData + SELECT DepartmentID, JobCodeID, PayCodeGroupID, + CASE WHEN @IsEmployeeBudgeting = 1 AND ProviderID = 0 THEN 0 ELSE EmployeeID END AS EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, MAX(ISNULL(FixedPercentage, 1)), SUM(ISNULL(Value, 0)) + FROM #TempIntStaffingData + WHERE FixedPercentage <> 1 + GROUP BY DepartmentID, JobCodeID, PayCodeGroupID, MonthColumnName, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, CASE WHEN @IsEmployeeBudgeting = 1 AND ProviderID = 0 THEN 0 ELSE EmployeeID END + + --JAZZ-75302 - Adjusted dollars for leap year like we already do with hours + -- We need this in case we are dealing with leap years to make sure that the number of hours is correctly adjusted between projection and budget + -- for this proc that is when Months Not Loaded are set to Sampled Values for the corresponding months + INSERT INTO #WorkingHoursRatioData + SELECT fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID + , (wh.Month01 / whSourceYear.Month01) + , (wh.Month02 / whSourceYear.Month02) + , (wh.Month03 / whSourceYear.Month03) + , (wh.Month04 / whSourceYear.Month04) + , (wh.Month05 / whSourceYear.Month05) + , (wh.Month06 / whSourceYear.Month06) + , (wh.Month07 / whSourceYear.Month07) + , (wh.Month08 / whSourceYear.Month08) + , (wh.Month09 / whSourceYear.Month09) + , (wh.Month10 / whSourceYear.Month10) + , (wh.Month11 / whSourceYear.Month11) + , (wh.Month12 / whSourceYear.Month12) + FROM #IntStaffingData fs + INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @BudgetYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + INNER JOIN [client].[FactWorkingHoursPerMonth] whSourceYear on whSourceYear.FiscalYearID = @SourceFiscalYearID and whSourceYear.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + + UPDATE + fs + SET + SampledBudgetDollars01 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month01, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month01, 0) + END, + SampledBudgetDollars02 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month02, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month02, 0) + END, + SampledBudgetDollars03 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month03, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month03, 0) + END, + SampledBudgetDollars04 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month04, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month04, 0) + END, + SampledBudgetDollars05 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month05, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month05, 0) + END, + SampledBudgetDollars06 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month06, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month06, 0) + END, + SampledBudgetDollars07 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month07, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month07, 0) + END, + SampledBudgetDollars08 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month08, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month08, 0) + END, + SampledBudgetDollars09 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month09, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month09, 0) + END, + SampledBudgetDollars10 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month10, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month10, 0) + END, + SampledBudgetDollars11 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month11, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month11, 0) + END, + SampledBudgetDollars12 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month12, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month12, 0) + END + FROM [fp].[Staffing] fs + INNER JOIN + (SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingData) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.JobCodeID = pv.JobCodeID + AND fs.PayCodeGroupID = pv.PayCodeGroupID + AND fs.EmployeeID = pv.EmployeeID + AND fs.ProviderID = pv.ProviderID + AND fs.ProviderTypeID = pv.ProviderTypeID + AND fs.ProviderSpecialtyID = pv.ProviderSpecialtyID + AND fs.ProviderLineItemID = pv.ProviderLineItemID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID + + IF(@AdjustWageRateByDaysInYear = 1) + BEGIN + UPDATE fs + SET + SampledBudgetDollars01 = SampledBudgetDollars01 * wh.MonthRatio01, + SampledBudgetDollars02 = SampledBudgetDollars02 * wh.MonthRatio02, + SampledBudgetDollars03 = SampledBudgetDollars03 * wh.MonthRatio03, + SampledBudgetDollars04 = SampledBudgetDollars04 * wh.MonthRatio04, + SampledBudgetDollars05 = SampledBudgetDollars05 * wh.MonthRatio05, + SampledBudgetDollars06 = SampledBudgetDollars06 * wh.MonthRatio06, + SampledBudgetDollars07 = SampledBudgetDollars07 * wh.MonthRatio07, + SampledBudgetDollars08 = SampledBudgetDollars08 * wh.MonthRatio08, + SampledBudgetDollars09 = SampledBudgetDollars09 * wh.MonthRatio09, + SampledBudgetDollars10 = SampledBudgetDollars10 * wh.MonthRatio10, + SampledBudgetDollars11 = SampledBudgetDollars11 * wh.MonthRatio11, + SampledBudgetDollars12 = SampledBudgetDollars12 * wh.MonthRatio12 + FROM [fp].[Staffing] fs + INNER JOIN #WorkingHoursRatioData wh on wh.DepartmentID = fs.DepartmentID AND wh.JobCodeID = fs.JobCodeID AND wh.PayCodeGroupID = fs.PayCodeGroupID + INNER JOIN + (SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingData) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.JobCodeID = pv.JobCodeID + AND fs.PayCodeGroupID = pv.PayCodeGroupID + AND fs.EmployeeID = pv.EmployeeID + AND fs.ProviderID = pv.ProviderID + AND fs.ProviderTypeID = pv.ProviderTypeID + AND fs.ProviderSpecialtyID = pv.ProviderSpecialtyID + AND fs.ProviderLineItemID = pv.ProviderLineItemID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID + END + + -- if the source fiscal year = current fiscal year and timeclass is actual, we need to annualize the data + IF(@IsAnnualized = 1) + BEGIN + + SELECT fs.StaffingID, + CASE + WHEN @MonthsLoaded = 12 THEN SampledBudgetDollars01 + SampledBudgetDollars02 + SampledBudgetDollars03 + SampledBudgetDollars04 + SampledBudgetDollars05 + SampledBudgetDollars06 + SampledBudgetDollars07 + SampledBudgetDollars08 + SampledBudgetDollars09 + SampledBudgetDollars10 + SampledBudgetDollars11 + SampledBudgetDollars12 + WHEN @MonthsLoaded >= 11 THEN SampledBudgetDollars01 + SampledBudgetDollars02 + SampledBudgetDollars03 + SampledBudgetDollars04 + SampledBudgetDollars05 + SampledBudgetDollars06 + SampledBudgetDollars07 + SampledBudgetDollars08 + SampledBudgetDollars09 + SampledBudgetDollars10 + SampledBudgetDollars11 + WHEN @MonthsLoaded >= 10 THEN SampledBudgetDollars01 + SampledBudgetDollars02 + SampledBudgetDollars03 + SampledBudgetDollars04 + SampledBudgetDollars05 + SampledBudgetDollars06 + SampledBudgetDollars07 + SampledBudgetDollars08 + SampledBudgetDollars09 + SampledBudgetDollars10 + WHEN @MonthsLoaded >= 9 THEN SampledBudgetDollars01 + SampledBudgetDollars02 + SampledBudgetDollars03 + SampledBudgetDollars04 + SampledBudgetDollars05 + SampledBudgetDollars06 + SampledBudgetDollars07 + SampledBudgetDollars08 + SampledBudgetDollars09 + WHEN @MonthsLoaded >= 8 THEN SampledBudgetDollars01 + SampledBudgetDollars02 + SampledBudgetDollars03 + SampledBudgetDollars04 + SampledBudgetDollars05 + SampledBudgetDollars06 + SampledBudgetDollars07 + SampledBudgetDollars08 + WHEN @MonthsLoaded >= 7 THEN SampledBudgetDollars01 + SampledBudgetDollars02 + SampledBudgetDollars03 + SampledBudgetDollars04 + SampledBudgetDollars05 + SampledBudgetDollars06 + SampledBudgetDollars07 + WHEN @MonthsLoaded >= 6 THEN SampledBudgetDollars01 + SampledBudgetDollars02 + SampledBudgetDollars03 + SampledBudgetDollars04 + SampledBudgetDollars05 + SampledBudgetDollars06 + WHEN @MonthsLoaded >= 5 THEN SampledBudgetDollars01 + SampledBudgetDollars02 + SampledBudgetDollars03 + SampledBudgetDollars04 + SampledBudgetDollars05 + WHEN @MonthsLoaded >= 4 THEN SampledBudgetDollars01 + SampledBudgetDollars02 + SampledBudgetDollars03 + SampledBudgetDollars04 + WHEN @MonthsLoaded >= 3 THEN SampledBudgetDollars01 + SampledBudgetDollars02 + SampledBudgetDollars03 + WHEN @MonthsLoaded >= 2 THEN SampledBudgetDollars01 + SampledBudgetDollars02 + ELSE SampledBudgetDollars01 + END AS SampledBudgetDollarsTotal + INTO #MonthsLoadedTotal + FROM [fp].[Staffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + + -- Staffing section + + SELECT h.DepartmentID, h.JobCodeID, h.PayCodeGroupID, h.EmployeeID, h.EntityGroupConfigID, h.VariabilityID, + mnlt.SampledBudgetDollarsTotal / ytd.YTDHours AS AverageDollars + INTO #dolTemp + FROM [fp].[Staffing] h + INNER JOIN #MonthsLoadedTotal mnlt on h.StaffingID = mnlt.StaffingID + INNER JOIN [fw].[DimJobCode] jc on h.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on h.DepartmentID = dept.DepartmentID + INNER JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] ytd on ytd.FiscalYearID = @BudgetYearID and ytd.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.SortOrder = @MonthsLoaded AND ytd.FiscalMonthID = fm.FiscalMonthID + WHERE h.EntityGroupConfigID = @EntityGroupConfigID + AND h.SubsectionID = 3 -- Staffing + + UPDATE + fs + SET + SampledBudgetDollars02 = CASE WHEN @MonthsLoaded >= 2 THEN fs.SampledBudgetDollars02 ELSE AverageDollars * wh.Month02 END, + SampledBudgetDollars03 = CASE WHEN @MonthsLoaded >= 3 THEN fs.SampledBudgetDollars03 ELSE AverageDollars * wh.Month03 END, + SampledBudgetDollars04 = CASE WHEN @MonthsLoaded >= 4 THEN fs.SampledBudgetDollars04 ELSE AverageDollars * wh.Month04 END, + SampledBudgetDollars05 = CASE WHEN @MonthsLoaded >= 5 THEN fs.SampledBudgetDollars05 ELSE AverageDollars * wh.Month05 END, + SampledBudgetDollars06 = CASE WHEN @MonthsLoaded >= 6 THEN fs.SampledBudgetDollars06 ELSE AverageDollars * wh.Month06 END, + SampledBudgetDollars07 = CASE WHEN @MonthsLoaded >= 7 THEN fs.SampledBudgetDollars07 ELSE AverageDollars * wh.Month07 END, + SampledBudgetDollars08 = CASE WHEN @MonthsLoaded >= 8 THEN fs.SampledBudgetDollars08 ELSE AverageDollars * wh.Month08 END, + SampledBudgetDollars09 = CASE WHEN @MonthsLoaded >= 9 THEN fs.SampledBudgetDollars09 ELSE AverageDollars * wh.Month09 END, + SampledBudgetDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.SampledBudgetDollars10 ELSE AverageDollars * wh.Month10 END, + SampledBudgetDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.SampledBudgetDollars11 ELSE AverageDollars * wh.Month11 END, + SampledBudgetDollars12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.SampledBudgetDollars12 ELSE AverageDollars * wh.Month12 END + FROM [fp].[Staffing] fs + INNER JOIN #dolTemp fte ON fs.DepartmentID = fte.DepartmentID and fs.JobCodeID = fte.JobCodeID and fs.PayCodeGroupID = fte.PayCodeGroupID and fs.EmployeeID = fte.EmployeeID and fs.EntityGroupConfigID = fte.EntityGroupConfigID AND fs.VariabilityID = fte.VariabilityID + INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @BudgetYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.SubsectionID = 3 -- Staffing + + -- Provider Compensation section + + -- per stackoverflow (per MY) + DECLARE @IsLeapYear BIT = (CASE WHEN (@SourceFiscalYearID % 4 = 0 AND @SourceFiscalYearID % 100 <> 0) OR @SourceFiscalYearID % 400 = 0 THEN 1 ELSE 0 END) + DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded) + DECLARE @DaysInMonthsNotLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder > @MonthsLoaded) + + UPDATE fs + SET + -- not doing month 1 because it wouldn't really make sense to annualize without at least 1 month of actual data + SampledBudgetDollars02 = CASE WHEN @MonthsLoaded < 2 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars02 END, + SampledBudgetDollars03 = CASE WHEN @MonthsLoaded < 3 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars03 END, + SampledBudgetDollars04 = CASE WHEN @MonthsLoaded < 4 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars04 END, + SampledBudgetDollars05 = CASE WHEN @MonthsLoaded < 5 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars05 END, + SampledBudgetDollars06 = CASE WHEN @MonthsLoaded < 6 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars06 END, + SampledBudgetDollars07 = CASE WHEN @MonthsLoaded < 7 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars07 END, + SampledBudgetDollars08 = CASE WHEN @MonthsLoaded < 8 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars08 END, + SampledBudgetDollars09 = CASE WHEN @MonthsLoaded < 9 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars09 END, + SampledBudgetDollars10 = CASE WHEN @MonthsLoaded < 10 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars10 END, + SampledBudgetDollars11 = CASE WHEN @MonthsLoaded < 11 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars11 END, + SampledBudgetDollars12 = CASE WHEN @MonthsLoaded < 12 THEN ((dt.SampledBudgetDollarsTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudgetDollars12 END + FROM [fp].[Staffing] fs + INNER JOIN #MonthsLoadedTotal dt ON dt.StaffingID = fs.StaffingID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.SubsectionID = 4 -- Provider Compensation + + END + + +END +GO + + +--------------------------------------------- + +-- fp.procSampleStaffingOriginalBudgetHours +CREATE PROCEDURE [fp].[procSampleStaffingOriginalBudgetHours] + @EntityGroupConfigGUID uniqueidentifier, + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @BudgetYearID smallint, + @SourceFiscalYearID smallint, + @SourceTimeClassID tinyint, + @MonthsLoaded int, + @IsEmployeeBudgeting bit, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 4 2021-03-22 NT JAZZ-15374 Use NPI instead of EmployeID for Provider Comp Sampling +** 5 2021-06-30 BW JAZZ-21627 Update selects and group by for EmployeID for variablity +** 6 2021-12-01 OP JAZZ-29466 removed empty users check for prov comp data +** 7 2022-01-11 OP JAZZ-30834 sampling provider data +** 8 2022-02-14 BK JAZZ-33248 respect department setting for employee budgeting +** 9 2022-03-02 MZ JAZZ-30547 improved checks in order to sample valid Employees with valid NPI +** 10 2022-03-18 AO JAZZ-33623 hours always sample fixed +** 11 2022-08-08 BK JAZZ-38357 Make sure IsFP records are correctly sampled depending on if true or false +** 12 2022-10-07 AO JAZZ-42868 Non-provider department samples correct staffing values when provider sampling feature is turned on. +** 13 2022-11-07 MZ JAZZ-35951 Add EmployeeID to FactStaffingVariabilityDetail +** 15 2022-12-12 DM JAZZ-46455 Samplimg of Provider Type and Provider Specialty is linked to Section Setup + +** 16 2023-08-22 JB JAZZ-59251 Use ProductiveClassID = 4 instead of Dollars-Only string to accommodate internationalization +** 17 2023-09-26 BK JAZZ-61239 Fix variable dept/job code incorrectly ignoring data that has EmployeeID in int.FactStaffing +** 18 2023-09-27 BK JAZZ-61239 Fix incorrect ProductiveClass = 4 +** 19 2023-09-30 BK JAZZ-60973 Update for new data structure +** 20 2023-12-26 NH/NT JAZZ-64324 Remove 'Use Hours and FTE on Provider Compensation (doing this in restructure branch on behalf of Softserve) +** 21 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config +** 22 2024-03-25 MY JAZZ-69661 Duplicated data for non-Provider departments in client dbs who utilize Provider Planning +** 23 2024-06-18 MZ JAZZ-72231 Added Source Provider Sampling +*************************************************************/ + +/*********************************************************************************************** + +NOTE----Any change to this proc likely will need to be changed in procApplyVariabilityToStaffing + +************************************************************************************************/ + + DECLARE @IsAnnualized BIT = (CASE WHEN @SourceFiscalYearID = @CurrentFiscalYearID AND @SourceTimeClassID = 1 AND @MonthsLoaded < 12 THEN 1 ELSE 0 END) + DECLARE @IsProviderPlanningEnabled BIT; + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID; + + DECLARE @UseProviderSource BIT; + DECLARE @SampleProviderEitherFromStaffingOrProviderIntTable BIT; + DECLARE @BudgetConfigID INT = (SELECT BudgetConfigID FROM fp.EntityGroupConfig a INNER JOIN fp.BudgetConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID) + + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled, @UseProviderSource = UseProviderSource FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID; + + SELECT @SampleProviderEitherFromStaffingOrProviderIntTable = Value FROM fp.BudgetConfigSetting bcs + INNER JOIN fp.BudgetConfigDefaultSetting bcds ON bcs.SettingID = bcds.SettingID + WHERE Name = 'Sample Provider either from Staffing or Provider int tables' AND BudgetConfigID = @BudgetConfigID + + DECLARE @ProviderSubsectionID INT; + SELECT @ProviderSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Provider' + + IF OBJECT_ID('tempdb..#TempIntStaffingData') IS NOT NULL DROP TABLE #TempIntStaffingData + IF OBJECT_ID('tempdb..#flatFteTemp') IS NOT NULL DROP TABLE #flatFteTemp + IF OBJECT_ID('tempdb..#filterTable') IS NOT NULL DROP TABLE #filterTable + IF OBJECT_ID('tempdb..#IntStaffingData') IS NOT NULL DROP TABLE #IntStaffingData + IF OBJECT_ID('tempdb..#TempIntStaffingData') IS NOT NULL DROP TABLE #TempIntStaffingData + IF OBJECT_ID('tempdb..#WorkingHoursRatioData') IS NOT NULL DROP TABLE #WorkingHoursRatioData + IF OBJECT_ID('tempdb..#MonthsLoadedTotal') IS NOT NULL DROP TABLE #MonthsLoadedTotal + IF OBJECT_ID('tempdb..#fteTemp') IS NOT NULL DROP TABLE #fteTemp + IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolved') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolved + IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolvedForProvider') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolvedForProvider + + CREATE TABLE #TempIntStaffingData ( + DepartmentID int, + JobCodeID int, + PayCodeGroupID int, + EmployeeID int, + ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, + MonthColumnName varchar(50), + FixedPercentage decimal(19,4), + Value decimal (19,4) + ) + + CREATE TABLE #IntStaffingData ( + DepartmentID int, + JobCodeID int, + PayCodeGroupID int, + EmployeeID int, + ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, -- we'll need this eventually, plus we should make sure we're joining on it + MonthColumnName varchar(50), + FixedPercentage decimal(19,4), + Value decimal (19,4) + ) + + CREATE TABLE #WorkingHoursRatioData ( + DepartmentID int, + JobCodeID int, + PayCodeGroupID int, + MonthRatio01 decimal(19,8), + MonthRatio02 decimal (19,8), + MonthRatio03 decimal (19,8), + MonthRatio04 decimal (19,8), + MonthRatio05 decimal (19,8), + MonthRatio06 decimal (19,8), + MonthRatio07 decimal (19,8), + MonthRatio08 decimal (19,8), + MonthRatio09 decimal (19,8), + MonthRatio10 decimal (19,8), + MonthRatio11 decimal (19,8), + MonthRatio12 decimal (19,8) + ) + + CREATE TABLE #filterTable (DepartmentID int) + INSERT INTO #filterTable (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #filterTable (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fp.Staffing + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + IF @IsProviderPlanningEnabled = 0 + BEGIN + + -------------------------------------- + -- Provider Disabled + -------------------------------------- + -- Resolve EmployeeID up front so we don't have to do it every time. + SELECT + src.DepartmentID, + src.JobCodeID, + src.PayCodeID, + CASE + WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 + ELSE CASE + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE src.EmployeeID + END + END as EmployeeID, + 0 AS ProviderID, + 0 AS ProviderTypeID, + 0 AS ProviderSpecialtyID, + 0 AS ProviderLineItemID, + src.FiscalYearID, + src.TimeClassID, + src.UnitTypeID, + src.FiscalMonthID, + src.IsDeleted, + Value + INTO #intFactStaffingWithEmployeeResolved + FROM [int].[FactStaffing] src + INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND CASE WHEN @IsEmployeeBudgeting = 0 OR ISNULL(sefg.IsUsingEmployeeBudgeting, 0) = 0 THEN 0 -- When not using EB, we can just set it to 0. + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 + ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not. + END = fv.EmployeeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE src.FiscalYearID = @SourceFiscalYearID + AND src.TimeClassID = @SourceTimeClassID + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 51 + + INSERT INTO #TempIntStaffingData + SELECT + src.DepartmentID, + src.JobCodeID, + pc.PayCodeGroupID, + src.EmployeeID, + 0 AS ProviderID, + 0 AS ProviderTypeID, + 0 AS ProviderSpecialtyID, + 0 AS ProviderLineItemID, + fm.MonthColumnName, + ISNULL(fv.FixedPercentage, 1) as FixedPercentage, + SUM(ISNULL(src.Value, 0)) as Value + FROM #intFactStaffingWithEmployeeResolved src + INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = src.PayCodeID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0. + -- int.FactStaffing that has variable dept/job code may have employee data due to how they populate data + -- the employeeID should be resolved to 0 from the code above this populating #intFactStaffingWithEmployeeResolved + -- see Jazz-61239 for more details + ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not. + END = fv.EmployeeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE src.FiscalYearID = @SourceFiscalYearID + AND src.TimeClassID = @SourceTimeClassID + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 51 + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + AND pc.IsHoursIgnored = 0 + GROUP BY src.DepartmentID, + src.JobCodeID, + pc.PayCodeGroupID, + src.EmployeeID, + fm.MonthColumnName, + FixedPercentage + + END ELSE BEGIN + + -------------------------------------- + -- Provider Enabled + -------------------------------------- + + IF OBJECT_ID('tempdb..#emp') IS NOT NULL DROP TABLE #emp + IF OBJECT_ID('tempdb..#dept') IS NOT NULL DROP TABLE #dept + IF OBJECT_ID('tempdb..#provDims') IS NOT NULL DROP TABLE #provDims + CREATE TABLE #emp (DepartmentID INT, EmployeeID INT, ProviderID INT, ProviderTypeID INT, ProviderSpecialtyID INT, IsFP BIT) + CREATE TABLE #dept (DepartmentID INT, EntityID INT, UseProvider BIT) + CREATE TABLE #provDims (DepartmentID INT, ProviderID INT, ProviderLineItemID INT) + + DECLARE @IsProviderTypeDisabled BIT; + SELECT @IsProviderTypeDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderTypeID' AND PlanSectionID = 3 AND SubSectionID = 1 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + + DECLARE @IsProviderSpecialtyDisabled BIT; + SELECT @IsProviderSpecialtyDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderSpecialtyID' AND PlanSectionID = 3 AND SubSectionID = 1 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + -- JAZZ-69661: Duplicated data for non-Provider departments in client dbs who utilize Provider Planning + DECLARE @EnableDepartmentLevelProviderForSampling BIT = ISNULL((SELECT 1 + FROM fp.BudgetConfigSetting setting + INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON setting.SettingID = def.SettingID + WHERE def.Name = 'Enable Department Level Provider For Sampling' + AND setting.BudgetConfigID = @BudgetConfigID + AND setting.Value = 1), 0) + + IF @SampleProviderEitherFromStaffingOrProviderIntTable = 0 + BEGIN + -- Get all departments that use Provider Staffing + -- Get all employees that are providers + -- (not doing this step for anything other than dollars yet) Sample provider data from int.FactStaffing for employees in departments that are configured to use provider sampling + -- Sample regular data for non provider employees and departments that are not configured to use provider sampling + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT staff.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON staff.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeclassID = @SourceTimeClassID + AND staff.IsDeleted = 0 + AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + UNION + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + + -- 2. all employees that are providers + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END, + emp.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID + INNER JOIN [dss].[DimPhysician] phys ON phys.NPI = emp.NPI + INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigGUID = egc.BudgetConfigGUID + WHERE + staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeclassID = @SourceTimeClassID + AND staff.IsDeleted = 0 + AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = bc.BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND staff.EmployeeID > 0 + AND emp.NPI NOT IN ('Not Specified', '0', '') + UNION + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, + phys.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND phys.NPI NOT IN ('Not Specified', '0', '') + + -- Provider from int.FactProvider + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + fp.DepartmentID, + 0 as JobCodeID, + 0 as PayCodeGroupID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + fp.ProviderLineItemID, + fm.MonthColumnName, + 1 as FixedPercentage, + SUM(ISNULL(fp.Value, 0)) as Value + FROM + [int].[FactProvider] fp + INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + WHERE + fp.FiscalYearID = @SourceFiscalYearID + AND fp.TimeClassID = @SourceTimeClassID + AND fp.IsDeleted = 0 + AND fp.FiscalMonthID != 0 + AND fp.UnitTypeID = 51 + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + AND ps.Description = 'Staffing' + AND emp.IsFP = 1 + GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName, + emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID + + + INSERT INTO #provDims (DepartmentID, ProviderID, ProviderLineItemID) SELECT DISTINCT DepartmentID, ProviderID, ProviderLineItemID FROM #TempIntStaffingData + + -- Provider from int.FactStaffing + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + src.DepartmentID, + src.JobCodeID, + pcg.PayCodeGroupID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + pc.ProviderLineItemID, + fm.MonthColumnName, + 1 as FixedPercentage, + SUM(ISNULL(src.Value, 0)) as Value + FROM + [int].[FactStaffing] src + INNER JOIN #dept dept ON src.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON src.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR src.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON src.PayCodeID = pc.PayCodeID + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND fv.EmployeeID = 0 + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN #provDims pd ON src.DepartmentID = pd.DepartmentID AND emp.ProviderID = pd.ProviderID and pd.ProviderLineItemID = pli.ProviderLineItemID + WHERE + src.FiscalYearID = @SourceFiscalYearID + AND src.TimeClassID = @SourceTimeClassID + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 51 + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + AND pc.IsHoursIgnored = 0 + AND ps.Description = 'Staffing' + AND pd.DepartmentID IS NULL + AND emp.IsFP = 1 + GROUP BY src.DepartmentID, + src.JobCodeID, + pcg.PayCodeGroupID, + emp.EmployeeID, + fm.MonthColumnName, + FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID + + END ELSE BEGIN + + ------------------------------------------------------- + -- BudgetConfigSetting is enabled + ------------------------------------------------------- + + IF @UseProviderSource = 0 + BEGIN + ------------------------------------------------------- + -- BudgetConfig UseProviderSource is disabled + ------------------------------------------------------- + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT staff.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON staff.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeclassID = @SourceTimeClassID + AND staff.IsDeleted = 0 + AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + + -- 2. Employees from staffing + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END, + emp.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID + INNER JOIN [dss].[DimPhysician] phys ON phys.NPI = emp.NPI + INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigGUID = egc.BudgetConfigGUID + WHERE + staff.FiscalYearID = @SourceFiscalYearID AND staff.TimeclassID = @SourceTimeClassID + AND staff.IsDeleted = 0 + AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = bc.BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND staff.EmployeeID > 0 + AND emp.NPI NOT IN ('Not Specified', '0', '') + + -- Provider from int.FactStaffing + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + src.DepartmentID, + src.JobCodeID, + pcg.PayCodeGroupID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + pc.ProviderLineItemID, + fm.MonthColumnName, + 1 as FixedPercentage, + SUM(ISNULL(src.Value, 0)) as Value + FROM + [int].[FactStaffing] src + INNER JOIN #dept dept ON src.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON src.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR src.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON src.PayCodeID = pc.PayCodeID + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND fv.EmployeeID = 0 + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE + src.FiscalYearID = @SourceFiscalYearID + AND src.TimeClassID = @SourceTimeClassID + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 51 + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + AND pc.IsHoursIgnored = 0 + AND ps.Description = 'Staffing' + AND emp.IsFP = 1 + GROUP BY src.DepartmentID, + src.JobCodeID, + pcg.PayCodeGroupID, + emp.EmployeeID, + fm.MonthColumnName, + FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID + + END ELSE BEGIN + + ------------------------------------------------------- + -- BudgetConfig UseProviderSource is enabled + ------------------------------------------------------- + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + + -- 2. all employees that are providers + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, + phys.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND phys.NPI NOT IN ('Not Specified', '0', '') + + + -- Provider from int.FactProvider + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + fp.DepartmentID, + 0 as JobCodeID, + 0 as PayCodeGroupID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + fp.ProviderLineItemID, + fm.MonthColumnName, + 1 as FixedPercentage, + SUM(ISNULL(fp.Value, 0)) as Value + FROM + [int].[FactProvider] fp + INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + WHERE + fp.FiscalYearID = @SourceFiscalYearID + AND fp.TimeClassID = @SourceTimeClassID + AND fp.IsDeleted = 0 + AND fp.FiscalMonthID != 0 + AND fp.UnitTypeID = 51 + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + AND ps.Description = 'Staffing' + AND emp.IsFP = 1 + GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName, + emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID + + END + + END + + + + + -- Populate into a temp table before summing up to deal with issues with the dynamic employee join + SELECT + src.DepartmentID, + src.JobCodeID, + pc.PayCodeID, + pc.PayCodeGroupID, + CASE + WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 + ELSE CASE + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE src.EmployeeID + END + END as EmployeeID, + 0 AS ProviderID, + 0 AS ProviderTypeID, + 0 AS ProviderSpecialtyID, + 0 AS ProviderLineItemID, + fm.FiscalMonthID, + fm.MonthColumnName, + ISNULL(fv.FixedPercentage, 1) as FixedPercentage, + ISNULL(src.Value, 0) as Value + INTO #intFactStaffingWithEmployeeResolvedForProvider + FROM [int].[FactStaffing] src + INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = src.PayCodeID + LEFT JOIN #dept dept ON tmp.DepartmentID = dept.DepartmentID + LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 1) emp ON src.EmployeeID = emp.EmployeeID + LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 0) NotFpEmp ON src.EmployeeID = NotFpEmp.EmployeeID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0. + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 + ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not. + END = fv.EmployeeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE src.FiscalYearID = @SourceFiscalYearID + AND src.TimeClassID = @SourceTimeClassID + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 51 + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + AND pc.IsHoursIgnored = 0 + AND (dept.DepartmentID IS NULL OR (emp.EmployeeID IS NULL AND (NotFpEmp.EmployeeID IS NULL OR NotFpEmp.IsFP = 0))) + + -- any other staffing data that doesn't meet previous requirements comes from int.FactStaffing + INSERT INTO #TempIntStaffingData + SELECT + src.DepartmentID, + src.JobCodeID, + src.PayCodeGroupID, + src.EmployeeID, + 0 AS ProviderID, + 0 AS ProviderTypeID, + 0 AS ProviderSpecialtyID, + 0 AS ProviderLineItemID, + src.MonthColumnName, + ISNULL(fv.FixedPercentage, 1) as FixedPercentage, + SUM(ISNULL(src.Value, 0)) as Value + FROM #intFactStaffingWithEmployeeResolvedForProvider src + INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND fv.EmployeeID = src.EmployeeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + GROUP BY src.DepartmentID, + src.JobCodeID, + src.PayCodeGroupID, + src.EmployeeID, + src.MonthColumnName, + fv.FixedPercentage + + END + + INSERT INTO #IntStaffingData + SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, FixedPercentage, Value + FROM #TempIntStaffingData + WHERE FixedPercentage = 1 + + INSERT INTO #IntStaffingData + SELECT DepartmentID, JobCodeID, PayCodeGroupID, + CASE WHEN @IsEmployeeBudgeting = 0 AND ProviderID = 0 THEN 0 ELSE EmployeeID END AS EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, MAX(ISNULL(FixedPercentage, 1)), SUM(ISNULL(Value, 0)) + FROM #TempIntStaffingData + WHERE FixedPercentage <> 1 + GROUP BY DepartmentID, JobCodeID, PayCodeGroupID, MonthColumnName, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, CASE WHEN @IsEmployeeBudgeting = 0 AND ProviderID = 0 THEN 0 ELSE EmployeeID END + + -- We need this in case we are dealing with leap years to make sure that the number of hours is correctly adjusted between projection and budget + -- for this proc that is when Months Not Loaded are set to Sampled Values for the corresponding months + INSERT INTO #WorkingHoursRatioData + SELECT fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID + , (wh.Month01 / whSourceYear.Month01) + , (wh.Month02 / whSourceYear.Month02) + , (wh.Month03 / whSourceYear.Month03) + , (wh.Month04 / whSourceYear.Month04) + , (wh.Month05 / whSourceYear.Month05) + , (wh.Month06 / whSourceYear.Month06) + , (wh.Month07 / whSourceYear.Month07) + , (wh.Month08 / whSourceYear.Month08) + , (wh.Month09 / whSourceYear.Month09) + , (wh.Month10 / whSourceYear.Month10) + , (wh.Month11 / whSourceYear.Month11) + , (wh.Month12 / whSourceYear.Month12) + FROM #IntStaffingData fs + INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @BudgetYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + INNER JOIN [client].[FactWorkingHoursPerMonth] whSourceYear on whSourceYear.FiscalYearID = @SourceFiscalYearID and whSourceYear.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + + -- Make sure to multiply by the ratio of working hours for the target year / working hours for the source year to ensure that hours are adjusted properly for leap year + -- Only February should ever have a difference (unless the client defines the working hours for another month as varying between years) + UPDATE fs + SET + SampledBudgetHours01 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month01, 0) * wh.MonthRatio01 + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month01, 0) * wh.MonthRatio01 + END, + SampledBudgetHours02 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month02, 0) * wh.MonthRatio02 + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month02, 0) * wh.MonthRatio02 + END, + SampledBudgetHours03 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month03, 0) * wh.MonthRatio03 + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month03, 0) * wh.MonthRatio03 + END, + SampledBudgetHours04 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month04, 0) * wh.MonthRatio04 + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month04, 0) * wh.MonthRatio04 + END, + SampledBudgetHours05 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month05, 0) * wh.MonthRatio05 + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month05, 0) * wh.MonthRatio05 + END, + SampledBudgetHours06 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month06, 0) * wh.MonthRatio06 + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month06, 0) * wh.MonthRatio06 + END, + SampledBudgetHours07 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month07, 0) * wh.MonthRatio07 + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month07, 0) * wh.MonthRatio07 + END, + SampledBudgetHours08 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month08, 0) * wh.MonthRatio08 + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month08, 0) * wh.MonthRatio08 + END, + SampledBudgetHours09 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month09, 0) * wh.MonthRatio09 + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month09, 0) * wh.MonthRatio09 + END, + SampledBudgetHours10 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month10, 0) * wh.MonthRatio10 + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month10, 0) * wh.MonthRatio10 + END, + SampledBudgetHours11 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month11, 0) * wh.MonthRatio11 + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month11, 0) * wh.MonthRatio11 + END, + SampledBudgetHours12 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(pv.Month12, 0) * wh.MonthRatio12 + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(pv.Month12, 0) * wh.MonthRatio12 + END + FROM + [fp].[Staffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + INNER JOIN #WorkingHoursRatioData wh on wh.DepartmentID = fs.DepartmentID AND wh.JobCodeID = fs.JobCodeID AND wh.PayCodeGroupID = fs.PayCodeGroupID + INNER JOIN + (SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingData) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.JobCodeID = pv.JobCodeID + AND fs.PayCodeGroupID = pv.PayCodeGroupID + AND fs.EmployeeID = pv.EmployeeID + AND fs.ProviderID = pv.ProviderID + AND fs.ProviderTypeID = pv.ProviderTypeID + AND fs.ProviderSpecialtyID = pv.ProviderSpecialtyID + AND fs.ProviderLineItemID = pv.ProviderLineItemID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.ProductiveClassID <> 4 + + -- if the source fiscal year = current fiscal year and timeclass is actual, we need to annualize the data + IF(@IsAnnualized = 1) + BEGIN + + + SELECT fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.VariabilityID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, + CASE + WHEN @MonthsLoaded = 12 THEN SampledBudgetHours01 + SampledBudgetHours02 + SampledBudgetHours03 + SampledBudgetHours04 + SampledBudgetHours05 + SampledBudgetHours06 + SampledBudgetHours07 + SampledBudgetHours08 + SampledBudgetHours09 + SampledBudgetHours10 + SampledBudgetHours11 + SampledBudgetHours12 + WHEN @MonthsLoaded >= 11 THEN SampledBudgetHours01 + SampledBudgetHours02 + SampledBudgetHours03 + SampledBudgetHours04 + SampledBudgetHours05 + SampledBudgetHours06 + SampledBudgetHours07 + SampledBudgetHours08 + SampledBudgetHours09 + SampledBudgetHours10 + SampledBudgetHours11 + WHEN @MonthsLoaded >= 10 THEN SampledBudgetHours01 + SampledBudgetHours02 + SampledBudgetHours03 + SampledBudgetHours04 + SampledBudgetHours05 + SampledBudgetHours06 + SampledBudgetHours07 + SampledBudgetHours08 + SampledBudgetHours09 + SampledBudgetHours10 + WHEN @MonthsLoaded >= 9 THEN SampledBudgetHours01 + SampledBudgetHours02 + SampledBudgetHours03 + SampledBudgetHours04 + SampledBudgetHours05 + SampledBudgetHours06 + SampledBudgetHours07 + SampledBudgetHours08 + SampledBudgetHours09 + WHEN @MonthsLoaded >= 8 THEN SampledBudgetHours01 + SampledBudgetHours02 + SampledBudgetHours03 + SampledBudgetHours04 + SampledBudgetHours05 + SampledBudgetHours06 + SampledBudgetHours07 + SampledBudgetHours08 + WHEN @MonthsLoaded >= 7 THEN SampledBudgetHours01 + SampledBudgetHours02 + SampledBudgetHours03 + SampledBudgetHours04 + SampledBudgetHours05 + SampledBudgetHours06 + SampledBudgetHours07 + WHEN @MonthsLoaded >= 6 THEN SampledBudgetHours01 + SampledBudgetHours02 + SampledBudgetHours03 + SampledBudgetHours04 + SampledBudgetHours05 + SampledBudgetHours06 + WHEN @MonthsLoaded >= 5 THEN SampledBudgetHours01 + SampledBudgetHours02 + SampledBudgetHours03 + SampledBudgetHours04 + SampledBudgetHours05 + WHEN @MonthsLoaded >= 4 THEN SampledBudgetHours01 + SampledBudgetHours02 + SampledBudgetHours03 + SampledBudgetHours04 + WHEN @MonthsLoaded >= 3 THEN SampledBudgetHours01 + SampledBudgetHours02 + SampledBudgetHours03 + WHEN @MonthsLoaded >= 2 THEN SampledBudgetHours01 + SampledBudgetHours02 + ELSE SampledBudgetHours01 + END AS SampledBudgetTotal + INTO #MonthsLoadedTotal + FROM [fp].[Staffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + + -- figure out ftes... + SELECT h.DepartmentID, h.JobCodeID, h.PayCodeGroupID, h.EmployeeID, h.ProviderID, h.ProviderTypeID, h.ProviderSpecialtyID, h.ProviderLineItemID, h.EntityGroupConfigID, h.VariabilityID, + mnlt.SampledBudgetTotal / ytd.YTDHours AS AverageFTE + INTO #fteTemp + FROM [fp].[Staffing] h + INNER JOIN #MonthsLoadedTotal mnlt on h.StaffingID = mnlt.StaffingID -- don't need to join #filterTable here because #MonthsLoadedTotal already has that filtered + INNER JOIN [fw].[DimJobCode] jc on h.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on h.DepartmentID = dept.DepartmentID + INNER JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] ytd on ytd.FiscalYearID = @BudgetYearID and ytd.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.SortOrder = @MonthsLoaded AND ytd.FiscalMonthID = fm.FiscalMonthID + WHERE h.EntityGroupConfigID = @EntityGroupConfigID + + UPDATE + fs + SET + SampledBudgetHours02 = CASE WHEN @MonthsLoaded >= 2 THEN fs.SampledBudgetHours02 ELSE AverageFTE * wh.Month02 END, + SampledBudgetHours03 = CASE WHEN @MonthsLoaded >= 3 THEN fs.SampledBudgetHours03 ELSE AverageFTE * wh.Month03 END, + SampledBudgetHours04 = CASE WHEN @MonthsLoaded >= 4 THEN fs.SampledBudgetHours04 ELSE AverageFTE * wh.Month04 END, + SampledBudgetHours05 = CASE WHEN @MonthsLoaded >= 5 THEN fs.SampledBudgetHours05 ELSE AverageFTE * wh.Month05 END, + SampledBudgetHours06 = CASE WHEN @MonthsLoaded >= 6 THEN fs.SampledBudgetHours06 ELSE AverageFTE * wh.Month06 END, + SampledBudgetHours07 = CASE WHEN @MonthsLoaded >= 7 THEN fs.SampledBudgetHours07 ELSE AverageFTE * wh.Month07 END, + SampledBudgetHours08 = CASE WHEN @MonthsLoaded >= 8 THEN fs.SampledBudgetHours08 ELSE AverageFTE * wh.Month08 END, + SampledBudgetHours09 = CASE WHEN @MonthsLoaded >= 9 THEN fs.SampledBudgetHours09 ELSE AverageFTE * wh.Month09 END, + SampledBudgetHours10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.SampledBudgetHours10 ELSE AverageFTE * wh.Month10 END, + SampledBudgetHours11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.SampledBudgetHours11 ELSE AverageFTE * wh.Month11 END, + SampledBudgetHours12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.SampledBudgetHours12 ELSE AverageFTE * wh.Month12 END + FROM [fp].[Staffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + INNER JOIN #fteTemp fte ON fs.DepartmentID = fte.DepartmentID and fs.JobCodeID = fte.JobCodeID and fs.PayCodeGroupID = fte.PayCodeGroupID and fs.EmployeeID = fte.EmployeeID + AND fs.EntityGroupConfigID = fte.EntityGroupConfigID AND fs.VariabilityID = fte.VariabilityID AND fs.ProviderID = fte.ProviderID + AND fs.ProviderTypeID = fte.ProviderTypeID + AND fs.ProviderSpecialtyID = fte.ProviderSpecialtyID + AND fs.ProviderLineItemID = fte.ProviderLineItemID + INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @BudgetYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + + END + + -- spread hours so that FTEs remain flat for fixed job codes + -- figure out ftes... + SELECT h.DepartmentID, h.JobCodeID, h.PayCodeGroupID, h.EmployeeID, h.ProviderID, h.ProviderTypeID, h.ProviderSpecialtyID, h.ProviderLineItemID, h.EntityGroupConfigID, h.VariabilityID, --h.SampledBudgetTotal / wh.MonthYearly AS AverageFTE + ((h.SampledBudgetHours01 / wh.MonthYearly) + + (h.SampledBudgetHours02 / wh.MonthYearly) + + (h.SampledBudgetHours03 / wh.MonthYearly) + + (h.SampledBudgetHours04 / wh.MonthYearly) + + (h.SampledBudgetHours05 / wh.MonthYearly) + + (h.SampledBudgetHours06 / wh.MonthYearly) + + (h.SampledBudgetHours07 / wh.MonthYearly) + + (h.SampledBudgetHours08 / wh.MonthYearly) + + (h.SampledBudgetHours09 / wh.MonthYearly) + + (h.SampledBudgetHours10 / wh.MonthYearly) + + (h.SampledBudgetHours11 / wh.MonthYearly) + + (h.SampledBudgetHours12 / wh.MonthYearly)) AS AverageFTE + INTO #flatFteTemp + FROM [fp].[Staffing] h + INNER JOIN #filterTable tmp on h.DepartmentID = tmp.DepartmentID + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on h.PayCodeGroupID = exc.PayCodeGroupID + INNER JOIN [fw].[DimJobCode] jc on h.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on h.DepartmentID = dept.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @BudgetYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + WHERE h.EntityGroupConfigID = @EntityGroupConfigID AND (h.VariabilityID = 1 OR exc.PayCodeGroupID IS NOT NULL) + + -- now back into hours + UPDATE + fs + SET + InitialBudgetHours01 = AverageFTE * wh.Month01, + InitialBudgetHours02 = AverageFTE * wh.Month02, + InitialBudgetHours03 = AverageFTE * wh.Month03, + InitialBudgetHours04 = AverageFTE * wh.Month04, + InitialBudgetHours05 = AverageFTE * wh.Month05, + InitialBudgetHours06 = AverageFTE * wh.Month06, + InitialBudgetHours07 = AverageFTE * wh.Month07, + InitialBudgetHours08 = AverageFTE * wh.Month08, + InitialBudgetHours09 = AverageFTE * wh.Month09, + InitialBudgetHours10 = AverageFTE * wh.Month10, + InitialBudgetHours11 = AverageFTE * wh.Month11, + InitialBudgetHours12 = AverageFTE * wh.Month12 + FROM [fp].[Staffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fs.PayCodeGroupID = exc.PayCodeGroupID + INNER JOIN #flatFteTemp fte ON fs.DepartmentID = fte.DepartmentID and fs.JobCodeID = fte.JobCodeID and fs.PayCodeGroupID = fte.PayCodeGroupID and fs.EmployeeID = fte.EmployeeID + and fs.VariabilityID = fte.VariabilityID and fs.EntityGroupConfigID = fte.EntityGroupConfigID + AND fs.ProviderID = fte.ProviderID + AND fs.ProviderTypeID = fte.ProviderTypeID + AND fs.ProviderSpecialtyID = fte.ProviderSpecialtyID + AND fs.ProviderLineItemID = fte.ProviderLineItemID + INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @BudgetYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND (fs.VariabilityID = 1 OR exc.PayCodeGroupID IS NOT NULL) + + + -- update the initial values to be equal to the sampled values for variable job codes + UPDATE + fs + SET + InitialBudgetHours01 = SampledBudgetHoursTotal/12, + InitialBudgetHours02 = SampledBudgetHoursTotal/12, + InitialBudgetHours03 = SampledBudgetHoursTotal/12, + InitialBudgetHours04 = SampledBudgetHoursTotal/12, + InitialBudgetHours05 = SampledBudgetHoursTotal/12, + InitialBudgetHours06 = SampledBudgetHoursTotal/12, + InitialBudgetHours07 = SampledBudgetHoursTotal/12, + InitialBudgetHours08 = SampledBudgetHoursTotal/12, + InitialBudgetHours09 = SampledBudgetHoursTotal/12, + InitialBudgetHours10 = SampledBudgetHoursTotal/12, + InitialBudgetHours11 = SampledBudgetHoursTotal/12, + InitialBudgetHours12 = SampledBudgetHoursTotal - (SampledBudgetHoursTotal/12 * 11) + FROM [fp].[Staffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fs.PayCodeGroupID = exc.PayCodeGroupID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.VariabilityID = 2 AND exc.PayCodeGroupID IS NULL + + +END +GO + + +--------------------------------------------- + +-- fp.procSampleStaffingOriginalProjectionDollars +CREATE PROCEDURE [fp].[procSampleStaffingOriginalProjectionDollars] + @EntityGroupConfigGUID uniqueidentifier, + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @MonthsLoaded int, + @IsEmployeeBudgeting bit, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +WITH RECOMPILE +AS +BEGIN +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 4 2021-03-22 NT JAZZ-15374 Use NPI instead of EmployeID for Provider Comp Sampling +** 5 2021-06-30 BW JAZZ-21627 Update selects and group by for EmployeID for variablity +** 6 2021-12-01 OP JAZZ-29466 removed empty users check for prov comp data +** 7 2022-02-14 BK JAZZ-33248 respect department setting for employee budgeting +** 8 2022-03-02 MZ JAZZ-30547 improved checks in order to sample valid Employees with valid NPI +** 9 2022-08-08 BK JAZZ-38357 Make sure IsFP records are correctly sampled depending on if true or false +** 10 2022-10-07 AO JAZZ-42868 Non-provider department samples correct staffing values when provider sampling feature is turned on. +** 11 2022-11-07 MZ JAZZ-35344 improved checks in order to sample valid Employees with valid NPI from FactProvider +** 12 11-7-2022 MY JAZZ-35951 Add EmployeeID to FactStaffingVariabilityDetail +** 13 2022-12-12 DM JAZZ-46455 Samplimg of Provider Type and Provider Specialty is linked to Section Setup +** 14 2023-09-26 BK JAZZ-61239 Fix variable dept/job code incorrectly ignoring data that has EmployeeID in int.FactStaffing +** 15 2023-09-30 BK JAZZ-60973 Update for new data structure +** 16 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config +** 17 2024-03-25 MY JAZZ-69661 Duplicated data for non-Provider departments in client dbs who utilize Provider Planning +** 18 2024-06-18 MZ JAZZ-72231 Added Source Provider Sampling +** 19 2024-08-12 MD JAZZ-75302 Adjust dollars for leap year +*************************************************************/ + + IF OBJECT_ID('tempdb..#filterTable') IS NOT NULL DROP TABLE #filterTable + IF OBJECT_ID('tempdb..#IntStaffingData') IS NOT NULL DROP TABLE #IntStaffingData + IF OBJECT_ID('tempdb..#TempIntStaffingData') IS NOT NULL DROP TABLE #TempIntStaffingData + IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolved') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolved + IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolvedForProvider') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolvedForProvider + IF OBJECT_ID('tempdb..#WorkingHoursRatioData') IS NOT NULL DROP TABLE #WorkingHoursRatioData + + CREATE TABLE #filterTable (DepartmentID int) + INSERT INTO #filterTable (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #filterTable (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fp.Staffing + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + DECLARE @IsProviderPlanningEnabled BIT; + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID; + + DECLARE @UseProviderSource BIT; + DECLARE @SampleProviderEitherFromStaffingOrProviderIntTable BIT; + DECLARE @AdjustWageRateByDaysInYear BIT = 0; + DECLARE @BudgetConfigID INT = (SELECT BudgetConfigID FROM fp.EntityGroupConfig a INNER JOIN fp.BudgetConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID) + + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled, @UseProviderSource = UseProviderSource FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID; + + SELECT @SampleProviderEitherFromStaffingOrProviderIntTable = Value FROM fp.BudgetConfigSetting bcs + INNER JOIN fp.BudgetConfigDefaultSetting bcds ON bcs.SettingID = bcds.SettingID + WHERE Name = 'Sample Provider either from Staffing or Provider int tables' AND BudgetConfigID = @BudgetConfigID + + SELECT @AdjustWageRateByDaysInYear = ISNULL(Value,0) FROM fp.BudgetConfigSetting bcs + INNER JOIN fp.BudgetConfigDefaultSetting bcds ON bcs.SettingID = bcds.SettingID + WHERE Name = 'Adjust Wage Rate by Days in Year' AND BudgetConfigID = @BudgetConfigID + + CREATE TABLE #IntStaffingData ( + DepartmentID int, + JobCodeID int, + PayCodeGroupID int, + EmployeeID int, + ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int, + MonthColumnName varchar(50), + FixedPercentage decimal(19,4), + Value decimal (19,4) + ) + CREATE TABLE #TempIntStaffingData ( + DepartmentID int, + JobCodeID int, + PayCodeGroupID int, + EmployeeID int, + ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, SubsectionID int, + MonthColumnName varchar(50), + FixedPercentage decimal(19,4), + Value decimal (19,4) + ) + + CREATE TABLE #WorkingHoursRatioData ( + DepartmentID int, + JobCodeID int, + PayCodeGroupID int, + MonthRatio01 decimal(19,8), + MonthRatio02 decimal (19,8), + MonthRatio03 decimal (19,8), + MonthRatio04 decimal (19,8), + MonthRatio05 decimal (19,8), + MonthRatio06 decimal (19,8), + MonthRatio07 decimal (19,8), + MonthRatio08 decimal (19,8), + MonthRatio09 decimal (19,8), + MonthRatio10 decimal (19,8), + MonthRatio11 decimal (19,8), + MonthRatio12 decimal (19,8) + ) + + IF @IsProviderPlanningEnabled = 0 + BEGIN + + ----------------------------------- + -- Provider Disabled + ----------------------------------- + -- Resolve EmployeeID up front so we don't have to do it every time. + SELECT + src.DepartmentID, + src.JobCodeID, + src.PayCodeID, + CASE + WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 + ELSE CASE + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE src.EmployeeID + END + END as EmployeeID, + 0 AS ProviderID, + 0 AS ProviderTypeID, + 0 AS ProviderSpecialtyID, + 0 AS ProviderLineItemID, + src.FiscalYearID, + src.TimeClassID, + src.UnitTypeID, + src.FiscalMonthID, + src.IsDeleted, + Value + INTO #intFactStaffingWithEmployeeResolved + FROM [int].[FactStaffing] src + INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND CASE WHEN @IsEmployeeBudgeting = 0 OR ISNULL(sefg.IsUsingEmployeeBudgeting, 0) = 0 THEN 0 -- When not using EB, we can just set it to 0. + -- int.FactStaffing that has variable dept/job code may have employee data due to how they populate data + -- see Jazz-61239 for more details + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not. + END = fv.EmployeeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE src.FiscalYearID = @CurrentFiscalYearID + AND src.TimeClassID = 1 + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 34 + + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID,MonthColumnName, FixedPercentage, Value) + SELECT + src.DepartmentID, + src.JobCodeID, + pc.PayCodeGroupID, + src.EmployeeID, + 0 as ProviderID, + 0 as ProviderTypeID, + 0 as ProviderSpecialtyID, + 0 as ProviderLineItemID, + 0 as SubsectionID, + fm.MonthColumnName, + ISNULL(fv.FixedPercentage, 1) as FixedPercentage, + SUM(ISNULL(src.Value, 0)) as Value + FROM #intFactStaffingWithEmployeeResolved src + INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = src.PayCodeID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0. + -- int.FactStaffing that has variable dept/job code may have employee data due to how they populate data + -- the employeeID should be resolved to 0 from the code above this populating #intFactStaffingWithEmployeeResolved + -- see Jazz-61239 for more details + ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not. + END = fv.EmployeeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE src.FiscalYearID = @CurrentFiscalYearID + AND src.TimeClassID = 1 + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 34 + AND fm.SortOrder <= @MonthsLoaded + AND pc.IsDollarsIgnored = 0 + GROUP BY src.DepartmentID, + src.JobCodeID, + pc.PayCodeGroupID, + src.EmployeeID, + fm.MonthColumnName, + FixedPercentage + + END ELSE BEGIN + + ----------------------------------- + -- Provider Enabled + ----------------------------------- + + IF OBJECT_ID('tempdb..#emp') IS NOT NULL DROP TABLE #emp + IF OBJECT_ID('tempdb..#dept') IS NOT NULL DROP TABLE #dept + IF OBJECT_ID('tempdb..#provDims') IS NOT NULL DROP TABLE #provDims + + CREATE TABLE #emp (DepartmentID INT, EmployeeID INT, ProviderID INT, ProviderTypeID INT, ProviderSpecialtyID INT, IsFP BIT) + CREATE TABLE #dept (DepartmentID INT, EntityID INT, UseProvider BIT) + CREATE TABLE #provDims (DepartmentID INT, ProviderID INT, ProviderLineItemID INT) + DECLARE @StaffingSubsectionID INT; + DECLARE @ProviderSubsectionID INT; + SELECT @StaffingSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Staffing' + SELECT @ProviderSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Provider' + + DECLARE @IsProviderTypeDisabled BIT; + SELECT @IsProviderTypeDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderTypeID' AND PlanSectionID = 3 AND SubSectionID = 1 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + + DECLARE @IsProviderSpecialtyDisabled BIT; + SELECT @IsProviderSpecialtyDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderSpecialtyID' AND PlanSectionID = 3 AND SubSectionID = 1 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + -- JAZZ-69661: Duplicated data for non-Provider departments in client dbs who utilize Provider Planning + DECLARE @EnableDepartmentLevelProviderForSampling BIT = ISNULL((SELECT 1 + FROM fp.BudgetConfigSetting setting + INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON setting.SettingID = def.SettingID + WHERE def.Name = 'Enable Department Level Provider For Sampling' + AND setting.BudgetConfigID = @BudgetConfigID + AND setting.Value = 1), 0) + + IF @SampleProviderEitherFromStaffingOrProviderIntTable = 0 + BEGIN + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT staff.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON staff.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 + AND staff.IsDeleted = 0 + AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + UNION + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + + -- 2. all employees that are providers + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END, + emp.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID + INNER JOIN [dss].[DimPhysician] phys ON phys.NPI = emp.NPI + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 + AND staff.IsDeleted = 0 + AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND staff.EmployeeID > 0 + AND emp.NPI NOT IN ('Not Specified', '0', '') + UNION + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, + phys.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND phys.NPI NOT IN ('Not Specified', '0', '') + + -- Provider from int.FactProvider + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + fp.DepartmentID, + 0 as JobCodeID, + 0 as PayCodeGroupID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + fp.ProviderLineItemID, + @ProviderSubsectionID, + fm.MonthColumnName, + 1 as FixedPercentage, + SUM(ISNULL(fp.Value, 0)) as Value + FROM + [int].[FactProvider] fp + INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + WHERE + fp.FiscalYearID = @CurrentFiscalYearID + AND fp.TimeClassID = 1 + AND fp.IsDeleted = 0 + AND fp.FiscalMonthID != 0 + AND fp.UnitTypeID = 34 + AND fm.SortOrder <= @MonthsLoaded + AND ps.Description = 'Staffing' + AND emp.IsFP = 1 + GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName, + emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID + + INSERT INTO #provDims (DepartmentID, ProviderID, ProviderLineItemID) SELECT DISTINCT DepartmentID, ProviderID, ProviderLineItemID FROM #TempIntStaffingData + + -- Provider from int.FactStaffing + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + src.DepartmentID, + src.JobCodeID, + pcg.PayCodeGroupID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + pc.ProviderLineItemID, + @ProviderSubsectionID, + fm.MonthColumnName, + ISNULL(fv.FixedPercentage,1) as FixedPercentage, + SUM(ISNULL(src.Value, 0)) as Value + FROM + [int].[FactStaffing] src + INNER JOIN #dept dept ON src.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON src.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR src.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON src.PayCodeID = pc.PayCodeID + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND fv.EmployeeID = 0 + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN #provDims pd ON src.DepartmentID = pd.DepartmentID AND emp.ProviderID = pd.ProviderID and pd.ProviderLineItemID = pli.ProviderLineItemID + WHERE + src.FiscalYearID = @CurrentFiscalYearID + AND src.TimeClassID = 1 + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 34 + AND fm.SortOrder <= @MonthsLoaded + AND pc.IsDollarsIgnored = 0 + AND ps.Description = 'Staffing' + AND pd.DepartmentID IS NULL + AND emp.IsFP = 1 + GROUP BY src.DepartmentID, + src.JobCodeID, + pcg.PayCodeGroupID, + emp.EmployeeID, + fm.MonthColumnName, + FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID + + END ELSE BEGIN + + IF @UseProviderSource = 0 + BEGIN + + ------------------------------------------------------- + -- BudgetConfig UseProviderSource is disabled + ------------------------------------------------------- + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT staff.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON staff.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 + AND staff.IsDeleted = 0 + AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + + -- 2. Employees from staffing + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END, + emp.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID + INNER JOIN [dss].[DimPhysician] phys ON phys.NPI = emp.NPI + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 + AND staff.IsDeleted = 0 + AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND staff.EmployeeID > 0 + AND emp.NPI NOT IN ('Not Specified', '0', '') + + + -- Provider from int.FactStaffing + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + src.DepartmentID, + src.JobCodeID, + pcg.PayCodeGroupID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + pc.ProviderLineItemID, + @ProviderSubsectionID, + fm.MonthColumnName, + ISNULL(fv.FixedPercentage,1) as FixedPercentage, + SUM(ISNULL(src.Value, 0)) as Value + FROM + [int].[FactStaffing] src + INNER JOIN #dept dept ON src.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON src.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR src.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON src.PayCodeID = pc.PayCodeID + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND fv.EmployeeID = 0 + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE + src.FiscalYearID = @CurrentFiscalYearID + AND src.TimeClassID = 1 + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 34 + AND fm.SortOrder <= @MonthsLoaded + AND pc.IsDollarsIgnored = 0 + AND ps.Description = 'Staffing' + AND emp.IsFP = 1 + GROUP BY src.DepartmentID, + src.JobCodeID, + pcg.PayCodeGroupID, + emp.EmployeeID, + fm.MonthColumnName, + FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID + + + END ELSE BEGIN + + ------------------------------------------------------- + -- BudgetConfig UseProviderSource is enabled + ------------------------------------------------------- + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + + -- 2. all employees that are providers + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, + phys.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND phys.NPI NOT IN ('Not Specified', '0', '') + + -- Provider from int.FactProvider + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + fp.DepartmentID, + 0 as JobCodeID, + 0 as PayCodeGroupID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + fp.ProviderLineItemID, + @ProviderSubsectionID, + fm.MonthColumnName, + 1 as FixedPercentage, + SUM(ISNULL(fp.Value, 0)) as Value + FROM + [int].[FactProvider] fp + INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + WHERE + fp.FiscalYearID = @CurrentFiscalYearID + AND fp.TimeClassID = 1 + AND fp.IsDeleted = 0 + AND fp.FiscalMonthID != 0 + AND fp.UnitTypeID = 34 + AND fm.SortOrder <= @MonthsLoaded + AND ps.Description = 'Staffing' + AND emp.IsFP = 1 + GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName, + emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID + + END + + END + + + + -- Populate into a temp table before summing up to deal with issues with the dynamic employee join + SELECT + src.DepartmentID, + src.JobCodeID, + pc.PayCodeID, + pc.PayCodeGroupID, + CASE + WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 + ELSE CASE + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE src.EmployeeID + END + END as EmployeeID, + 0 AS ProviderID, + 0 AS ProviderTypeID, + 0 AS ProviderSpecialtyID, + 0 AS ProviderLineItemID, + fm.FiscalMonthID, + fm.MonthColumnName, + ISNULL(fv.FixedPercentage, 1) as FixedPercentage, + ISNULL(src.Value, 0) as Value + INTO #intFactStaffingWithEmployeeResolvedForProvider + FROM [int].[FactStaffing] src + INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID + LEFT JOIN #dept dept ON tmp.DepartmentID = dept.DepartmentID + LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 1) emp ON src.EmployeeID = emp.EmployeeID + LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 0) NotFpEmp ON src.EmployeeID = NotFpEmp.EmployeeID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = src.PayCodeID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0. + -- int.FactStaffing that has variable dept/job code may have employee data due to how they populate data + -- see Jazz-61239 for more details + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not. + END = fv.EmployeeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE src.FiscalYearID = @CurrentFiscalYearID + AND src.TimeClassID = 1 + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 34 + AND fm.SortOrder <= @MonthsLoaded + AND pc.IsDollarsIgnored = 0 + AND (dept.DepartmentID IS NULL OR (emp.EmployeeID IS NULL AND (NotFpEmp.EmployeeID IS NULL OR NotFpEmp.IsFP = 0))) + + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID,MonthColumnName, FixedPercentage, Value) + SELECT + src.DepartmentID, + src.JobCodeID, + src.PayCodeGroupID, + src.EmployeeID, + 0 as ProviderID, + 0 as ProviderTypeID, + 0 as ProviderSpecialtyID, + 0 as ProviderLineItemID, + @StaffingSubsectionID as SubsectionID, + src.MonthColumnName, + ISNULL(fv.FixedPercentage,1) as FixedPercentage, + SUM(ISNULL(src.Value, 0)) as Value + FROM #intFactStaffingWithEmployeeResolvedForProvider src + INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0. + -- int.FactStaffing that has variable dept/job code may have employee data due to how they populate data + -- the employeeID should be resolved to 0 from the code above this populating #intFactStaffingWithEmployeeResolved + -- see Jazz-61239 for more details + ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not. + END = fv.EmployeeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + GROUP BY src.DepartmentID, + src.JobCodeID, + src.PayCodeGroupID, + src.EmployeeID, + src.MonthColumnName, + fv.FixedPercentage + END + + INSERT INTO #IntStaffingData + SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, FixedPercentage, Value + FROM #TempIntStaffingData + WHERE FixedPercentage = 1 + + INSERT INTO #IntStaffingData + SELECT DepartmentID, JobCodeID, PayCodeGroupID, + CASE WHEN @IsEmployeeBudgeting = 0 AND ProviderID = 0 THEN 0 ELSE EmployeeID END AS EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, MonthColumnName, MAX(ISNULL(FixedPercentage, 1)), SUM(ISNULL(Value, 0)) + FROM #TempIntStaffingData + WHERE FixedPercentage <> 1 + GROUP BY DepartmentID, JobCodeID, PayCodeGroupID, MonthColumnName, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, SubsectionID, CASE WHEN @IsEmployeeBudgeting = 0 AND ProviderID = 0 THEN 0 ELSE EmployeeID END + + -- Get Budget Year, since that is what we will need to check against for the ratio + -- in the main Original Hours proc, Sampled values were adjusted to reflect any difference in leap year/not leap year hours, so we need to adjust again + DECLARE @BudgetYearID INT + SELECT TOP 1 @BudgetYearID = FiscalYearID FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID + WHERE egc.EntityGroupConfigID = @EntityGroupConfigID + + -- We need this in case we are dealing with leap years to make sure that the number of hours is correctly adjusted between projection and budget + -- for this proc that is when Months Not Loaded are set to Sampled Values for the corresponding months + INSERT INTO #WorkingHoursRatioData + SELECT fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID + , (wh.Month01 / whSourceYear.Month01) + , (wh.Month02 / whSourceYear.Month02) + , (wh.Month03 / whSourceYear.Month03) + , (wh.Month04 / whSourceYear.Month04) + , (wh.Month05 / whSourceYear.Month05) + , (wh.Month06 / whSourceYear.Month06) + , (wh.Month07 / whSourceYear.Month07) + , (wh.Month08 / whSourceYear.Month08) + , (wh.Month09 / whSourceYear.Month09) + , (wh.Month10 / whSourceYear.Month10) + , (wh.Month11 / whSourceYear.Month11) + , (wh.Month12 / whSourceYear.Month12) + FROM + (SELECT DISTINCT f.DepartmentID, JobCodeID, PayCodeGroupID FROM fp.Staffing f + INNER JOIN #filterTable tmp on f.DepartmentID = tmp.DepartmentID + WHERE f.EntityGroupConfigID = @EntityGroupConfigID + ) fs + INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @CurrentFiscalYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + INNER JOIN [client].[FactWorkingHoursPerMonth] whSourceYear on whSourceYear.FiscalYearID = @BudgetYearID and whSourceYear.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + + + -- set all of the values from the source fy/tc + UPDATE + fs + SET + SampledProjectionDollars01 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month01, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month01, 0) + END, + SampledProjectionDollars02 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month02, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month02, 0) + END, + SampledProjectionDollars03 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month03, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month03, 0) + END, + SampledProjectionDollars04 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month04, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month04, 0) + END, + SampledProjectionDollars05 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month05, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month05, 0) + END, + SampledProjectionDollars06 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month06, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month06, 0) + END, + SampledProjectionDollars07 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month07, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month07, 0) + END, + SampledProjectionDollars08 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month08, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month08, 0) + END, + SampledProjectionDollars09 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month09, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month09, 0) + END, + SampledProjectionDollars10 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month10, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month10, 0) + END, + SampledProjectionDollars11 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month11, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month11, 0) + END, + SampledProjectionDollars12 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month12, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month12, 0) + END + FROM + [fp].[Staffing] fs + INNER JOIN + (SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingData) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.JobCodeID = pv.JobCodeID + AND fs.PayCodeGroupID = pv.PayCodeGroupID + AND fs.EmployeeID = pv.EmployeeID + AND fs.ProviderID = pv.ProviderID + AND fs.ProviderTypeID = pv.ProviderTypeID + AND fs.ProviderSpecialtyID = pv.ProviderSpecialtyID + AND fs.ProviderLineItemID = pv.ProviderLineItemID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID + + IF(@AdjustWageRateByDaysInYear = 1) + BEGIN + UPDATE + fs + SET + SampledProjectionDollars02 = CASE WHEN @MonthsLoaded < 2 THEN SampledBudgetDollars02 * wh.MonthRatio02 ELSE SampledProjectionDollars02 END, + SampledProjectionDollars03 = CASE WHEN @MonthsLoaded < 3 THEN SampledBudgetDollars03 * wh.MonthRatio03 ELSE SampledProjectionDollars03 END, + SampledProjectionDollars04 = CASE WHEN @MonthsLoaded < 4 THEN SampledBudgetDollars04 * wh.MonthRatio04 ELSE SampledProjectionDollars04 END, + SampledProjectionDollars05 = CASE WHEN @MonthsLoaded < 5 THEN SampledBudgetDollars05 * wh.MonthRatio05 ELSE SampledProjectionDollars05 END, + SampledProjectionDollars06 = CASE WHEN @MonthsLoaded < 6 THEN SampledBudgetDollars06 * wh.MonthRatio06 ELSE SampledProjectionDollars06 END, + SampledProjectionDollars07 = CASE WHEN @MonthsLoaded < 7 THEN SampledBudgetDollars07 * wh.MonthRatio07 ELSE SampledProjectionDollars07 END, + SampledProjectionDollars08 = CASE WHEN @MonthsLoaded < 8 THEN SampledBudgetDollars08 * wh.MonthRatio08 ELSE SampledProjectionDollars08 END, + SampledProjectionDollars09 = CASE WHEN @MonthsLoaded < 9 THEN SampledBudgetDollars09 * wh.MonthRatio09 ELSE SampledProjectionDollars09 END, + SampledProjectionDollars10 = CASE WHEN @MonthsLoaded < 10 THEN SampledBudgetDollars10 * wh.MonthRatio10 ELSE SampledProjectionDollars10 END, + SampledProjectionDollars11 = CASE WHEN @MonthsLoaded < 11 THEN SampledBudgetDollars11 * wh.MonthRatio11 ELSE SampledProjectionDollars11 END, + SampledProjectionDollars12 = CASE WHEN @MonthsLoaded < 12 THEN SampledBudgetDollars12 * wh.MonthRatio12 ELSE SampledProjectionDollars12 END + FROM [fp].[Staffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + INNER JOIN #WorkingHoursRatioData wh ON fs.DepartmentID = wh.DepartmentID AND fs.JobCodeID = wh.JobCodeID AND fs.PayCodeGroupID = wh.PayCodeGroupID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + END + ELSE + BEGIN + -- copy the baseline data over for months without data (month sort order > @MonthsLoaded) + UPDATE + fs + SET + SampledProjectionDollars02 = CASE WHEN @MonthsLoaded < 2 THEN SampledBudgetDollars02 ELSE SampledProjectionDollars02 END, + SampledProjectionDollars03 = CASE WHEN @MonthsLoaded < 3 THEN SampledBudgetDollars03 ELSE SampledProjectionDollars03 END, + SampledProjectionDollars04 = CASE WHEN @MonthsLoaded < 4 THEN SampledBudgetDollars04 ELSE SampledProjectionDollars04 END, + SampledProjectionDollars05 = CASE WHEN @MonthsLoaded < 5 THEN SampledBudgetDollars05 ELSE SampledProjectionDollars05 END, + SampledProjectionDollars06 = CASE WHEN @MonthsLoaded < 6 THEN SampledBudgetDollars06 ELSE SampledProjectionDollars06 END, + SampledProjectionDollars07 = CASE WHEN @MonthsLoaded < 7 THEN SampledBudgetDollars07 ELSE SampledProjectionDollars07 END, + SampledProjectionDollars08 = CASE WHEN @MonthsLoaded < 8 THEN SampledBudgetDollars08 ELSE SampledProjectionDollars08 END, + SampledProjectionDollars09 = CASE WHEN @MonthsLoaded < 9 THEN SampledBudgetDollars09 ELSE SampledProjectionDollars09 END, + SampledProjectionDollars10 = CASE WHEN @MonthsLoaded < 10 THEN SampledBudgetDollars10 ELSE SampledProjectionDollars10 END, + SampledProjectionDollars11 = CASE WHEN @MonthsLoaded < 11 THEN SampledBudgetDollars11 ELSE SampledProjectionDollars11 END, + SampledProjectionDollars12 = CASE WHEN @MonthsLoaded < 12 THEN SampledBudgetDollars12 ELSE SampledProjectionDollars12 END + FROM [fp].[Staffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + END + +END +GO + + +--------------------------------------------- + +-- fp.procSampleStaffingOriginalProjectionHours +CREATE PROCEDURE [fp].[procSampleStaffingOriginalProjectionHours] + @EntityGroupConfigGUID uniqueidentifier, + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @MonthsLoaded int, + @IsEmployeeBudgeting bit, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 4 2021-03-22 NT JAZZ-15374 Use NPI instead of EmployeID for Provider Comp Sampling + ** 5 2021-06-30 BW JAZZ-21627 Update selects and group by for EmployeID for variablity + ** 6 2021-12-01 OP JAZZ-29466 removed empty users check for prov comp data + ** 7 2022-01-11 OP JAZZ-30834 sampled provider data for hours + ** 8 2022-02-14 BK JAZZ-33248 respect department setting for employee budgeting + ** 9 2022-03-02 MZ JAZZ-30547 improved checks in order to sample valid Employees with valid NPI + ** 10 2022-03-18 AO JAZZ-33623 hours always sample fixed + ** 11 2022-08-08 BK JAZZ-38357 Make sure IsFP records are correctly sampled depending on if true or false + ** 12 2022-10-07 AO JAZZ-42868 Non-provider department samples correct staffing values when provider sampling feature is turned on. + ** 13 2022-11-07 MZ JAZZ-35344 improved checks in order to sample valid Employees with valid NPI from FactProvider + ** 14 11-7-2022 MY JAZZ-35951 Add EmployeeID to FactStaffingVariabilityDetail + ** 15 2022-12-12 DM JAZZ-46455 Samplimg of Provider Type and Provider Specialty is linked to Section Setup + ** 16 2023-02-16 BK JAZZ-50052 Fix for if no Current Year Actuals exist for dimensionality that was sampled from another baseline + ** the working hour ratio was missing when copying SampledBudget to Proj for Months Not Loaded + ** We are also not flattening the SampledProjection Months Not Loaded data when updating InitialProjecton + ** 17 2023-08-22 BK JAZZ-59251 Use ProductiveClassID = 4 instead of Dollars-Only string to accommodate internationalization + ** 18 2023-09-26 BK JAZZ-61239 Fix variable dept/job code incorrectly ignoring data that has EmployeeID in int.FactStaffing + ** 19 2023-09-30 BK JAZZ-60973 Update for data restructure + ** 20 2023-12-26 NH/NT JAZZ-64324 Remove 'Use Hours and FTE on Provider Compensation (doing this in restructure branch on behalf of Softserve) + ** 21 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config + ** 22 2024-03-25 MY JAZZ-69661 Duplicated data for non-Provider departments in client dbs who utilize Provider Planning + ** 23 2024-06-19 AO JAZZ-72231 Added Source Provider Sampling + *************************************************************/ + + DECLARE @IsProviderPlanningEnabled BIT, @BaselineTimeClassID INT, @BaselineFiscalYearID INT; + DECLARE @UseProviderSource BIT; + DECLARE @SampleProviderEitherFromStaffingOrProviderIntTable BIT; + + SELECT @SampleProviderEitherFromStaffingOrProviderIntTable = Value FROM fp.BudgetConfigSetting bcs + INNER JOIN fp.BudgetConfigDefaultSetting bcds ON bcs.SettingID = bcds.SettingID + INNER JOIN fp.BudgetConfig bc ON bc.BudgetConfigID = bcs.BudgetConfigID + INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID + WHERE bcds.Name = 'Sample Provider either from Staffing or Provider int tables' AND egc.EntityGroupConfigID = @EntityGroupConfigID + + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled, @UseProviderSource = UseProviderSource FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID; + + SELECT @BaselineTimeClassID = PayrollTimeClassID, @BaselineFiscalYearID = PayrollFiscalYearID FROM fp.EntityGroupConfig WHERE EntityGroupConfigID = @EntityGroupConfigID; + + DECLARE @StaffingSubsectionID INT; + DECLARE @ProviderSubsectionID INT; + SELECT @StaffingSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Staffing' + SELECT @ProviderSubsectionID = SubsectionID FROM fp.PlanSubsection WHERE Subsection = 'Provider' + + IF OBJECT_ID('tempdb..#TempIntStaffingData') IS NOT NULL DROP TABLE #TempIntStaffingData + IF OBJECT_ID('tempdb..#flatFteTemp') IS NOT NULL DROP TABLE #flatFteTemp + IF OBJECT_ID('tempdb..#filterTable') IS NOT NULL DROP TABLE #filterTable + IF OBJECT_ID('tempdb..#IntStaffingData') IS NOT NULL DROP TABLE #IntStaffingData + IF OBJECT_ID('tempdb..#TempIntStaffingData') IS NOT NULL DROP TABLE #TempIntStaffingData + IF OBJECT_ID('tempdb..#WorkingHoursRatioData') IS NOT NULL DROP TABLE #WorkingHoursRatioData + IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolved') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolved + IF OBJECT_ID('tempdb..#intFactStaffingWithEmployeeResolvedForProvider') IS NOT NULL DROP TABLE #intFactStaffingWithEmployeeResolvedForProvider + + CREATE TABLE #TempIntStaffingData ( + DepartmentID int, + JobCodeID int, + PayCodeGroupID int, + EmployeeID int, + ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, -- we'll need this eventually, plus we should make sure we're joining on it + MonthColumnName varchar(50), + FixedPercentage decimal(19,4), + Value decimal (19,4) + ) + + CREATE TABLE #IntStaffingData ( + DepartmentID int, + JobCodeID int, + PayCodeGroupID int, + EmployeeID int, + ProviderID int, ProviderTypeID int, ProviderSpecialtyID int, ProviderLineItemID int, + MonthColumnName varchar(50), + FixedPercentage decimal(19,4), + Value decimal (19,4) + ) + + CREATE TABLE #WorkingHoursRatioData ( + DepartmentID int, + JobCodeID int, + PayCodeGroupID int, + MonthRatio01 decimal(19,8), + MonthRatio02 decimal (19,8), + MonthRatio03 decimal (19,8), + MonthRatio04 decimal (19,8), + MonthRatio05 decimal (19,8), + MonthRatio06 decimal (19,8), + MonthRatio07 decimal (19,8), + MonthRatio08 decimal (19,8), + MonthRatio09 decimal (19,8), + MonthRatio10 decimal (19,8), + MonthRatio11 decimal (19,8), + MonthRatio12 decimal (19,8) + ) + + CREATE TABLE #filterTable (DepartmentID int) + INSERT INTO #filterTable (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #filterTable (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fp.Staffing + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + + IF @IsProviderPlanningEnabled = 0 + BEGIN + + ----------------------------------------- + -- Provider Disabled + ----------------------------------------- + -- Resolve EmployeeID up front so we don't have to do it every time. + SELECT + src.DepartmentID, + src.JobCodeID, + src.PayCodeID, + CASE + WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 + ELSE CASE + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE src.EmployeeID + END + END as EmployeeID, + 0 AS ProviderID, + 0 AS ProviderTypeID, + 0 AS ProviderSpecialtyID, + 0 AS ProviderLineItemID, + src.FiscalYearID, + src.TimeClassID, + src.UnitTypeID, + src.FiscalMonthID, + src.IsDeleted, + Value + INTO #intFactStaffingWithEmployeeResolved + FROM [int].[FactStaffing] src + INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND CASE WHEN @IsEmployeeBudgeting = 0 OR ISNULL(sefg.IsUsingEmployeeBudgeting, 0) = 0 THEN 0 -- When not using EB, we can just set it to 0. + -- int.FactStaffing that has variable dept/job code may have employee data due to how they populate data + -- the employeeID should be resolved to 0 from the code above this populating #intFactStaffingWithEmployeeResolved + -- see Jazz-61239 for more details + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 + ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not. + END = fv.EmployeeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + + INSERT INTO #TempIntStaffingData + SELECT + src.DepartmentID, + src.JobCodeID, + pc.PayCodeGroupID, + src.EmployeeID, + 0 AS ProviderID, 0 AS ProviderTypeID, 0 AS ProviderSpecialtyID, 0 AS ProviderLineItemID, + fm.MonthColumnName, + ISNULL(fv.FixedPercentage, 1) as FixedPercentage, + SUM(ISNULL(src.Value, 0)) as Value + FROM #intFactStaffingWithEmployeeResolved src + INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = src.PayCodeID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND src.EmployeeID = fv.EmployeeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE src.FiscalYearID = @CurrentFiscalYearID + AND src.TimeClassID = 1 + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 51 + AND fm.SortOrder <= @MonthsLoaded + AND pc.IsHoursIgnored = 0 + GROUP BY src.DepartmentID, + src.JobCodeID, + pc.PayCodeGroupID, + src.EmployeeID, + fm.MonthColumnName, + FixedPercentage + + END ELSE BEGIN + + ----------------------------------------- + -- Provider Enabled + ----------------------------------------- + + IF OBJECT_ID('tempdb..#provDims') IS NOT NULL DROP TABLE #provDims + IF OBJECT_ID('tempdb..#emp') IS NOT NULL DROP TABLE #emp + IF OBJECT_ID('tempdb..#dept') IS NOT NULL DROP TABLE #dept + + CREATE TABLE #emp (DepartmentID INT, EmployeeID INT, ProviderID INT, ProviderTypeID INT, ProviderSpecialtyID INT, IsFP BIT) + CREATE TABLE #dept (DepartmentID INT, EntityID INT, UseProvider BIT) + CREATE TABLE #provDims (DepartmentID INT, ProviderID INT, ProviderLineItemID INT) + + DECLARE @BudgetConfigID INT = (SELECT BudgetConfigID FROM fp.EntityGroupConfig a INNER JOIN fp.BudgetConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID) + + DECLARE @IsProviderTypeDisabled BIT; + SELECT @IsProviderTypeDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderTypeID' AND PlanSectionID = 3 AND SubSectionID = 1 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + + DECLARE @IsProviderSpecialtyDisabled BIT; + SELECT @IsProviderSpecialtyDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderSpecialtyID' AND PlanSectionID = 3 AND SubSectionID = 1 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + -- JAZZ-69661: Duplicated data for non-Provider departments in client dbs who utilize Provider Planning + DECLARE @EnableDepartmentLevelProviderForSampling BIT = ISNULL((SELECT 1 + FROM fp.BudgetConfigSetting setting + INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON setting.SettingID = def.SettingID + WHERE def.Name = 'Enable Department Level Provider For Sampling' + AND setting.BudgetConfigID = @BudgetConfigID + AND setting.Value = 1), 0) + + -- Get all departments that use Provider Staffing + -- Get all employees that are providers + -- This step is only for dollars for now - Sample provider data from int.FactStaffing for employees in departments that are configured to use provider sampling + -- Sample regular data for non provider employees and departments that are not configured to use provider sampling + + IF @SampleProviderEitherFromStaffingOrProviderIntTable = 0 + BEGIN + + ------------------------------------------------------- + -- BudgetConfigSetting is disabled + ------------------------------------------------------- + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider staffing + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT staff.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON staff.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigGUID = egc.BudgetConfigGUID + WHERE + staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 + AND staff.IsDeleted = 0 + AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = bc.BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + UNION + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + + -- 2. all employees that are providers + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END, + emp.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID + INNER JOIN [dss].[DimPhysician] phys ON phys.NPI = emp.NPI + INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigGUID = egc.BudgetConfigGUID + WHERE + staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 + AND staff.IsDeleted = 0 + AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = bc.BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND staff.EmployeeID > 0 + AND emp.NPI NOT IN ('Not Specified', '0', '') + UNION + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, + phys.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND phys.NPI NOT IN ('Not Specified', '0', '') + + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + fp.DepartmentID, + 0 as JobCodeID, + 0 as PayCodeGroupID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + fp.ProviderLineItemID, + fm.MonthColumnName, + 1 as FixedPercentage, + SUM(ISNULL(fp.Value, 0)) as Value + FROM + [int].[FactProvider] fp + INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + WHERE + fp.FiscalYearID = @CurrentFiscalYearID + AND fp.TimeClassID = 1 + AND fp.IsDeleted = 0 + AND fp.FiscalMonthID != 0 + AND fp.UnitTypeID = 51 + AND fm.SortOrder <= @MonthsLoaded + AND ps.Description = 'Staffing' + AND emp.IsFP = 1 + GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName, + emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID + + INSERT INTO #provDims (DepartmentID, ProviderID, ProviderLineItemID) SELECT DISTINCT DepartmentID, ProviderID, ProviderLineItemID FROM #TempIntStaffingData + + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + src.DepartmentID, + src.JobCodeID, + pcg.PayCodeGroupID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + pc.ProviderLineItemID, + fm.MonthColumnName, + 1 as FixedPercentage, + SUM(ISNULL(src.Value, 0)) as Value + FROM + [int].[FactStaffing] src + INNER JOIN #dept dept ON src.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON src.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR src.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON src.PayCodeID = pc.PayCodeID + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND fv.EmployeeID = 0 + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN #provDims pd ON src.DepartmentID = pd.DepartmentID AND emp.ProviderID = pd.ProviderID and pd.ProviderLineItemID = pli.ProviderLineItemID + WHERE + src.FiscalYearID = @CurrentFiscalYearID + AND src.TimeClassID = 1 + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 51 + AND fm.SortOrder <= @MonthsLoaded + AND pc.IsHoursIgnored = 0 + AND ps.Description = 'Staffing' + AND pd.DepartmentID IS NULL + AND emp.IsFP = 1 + GROUP BY src.DepartmentID, + src.JobCodeID, + pcg.PayCodeGroupID, + emp.EmployeeID, + fm.MonthColumnName, + FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID + END ELSE BEGIN + + ------------------------------------------------------- + -- BudgetConfigSetting is enabled + ------------------------------------------------------- + IF @UseProviderSource = 0 + BEGIN + + ------------------------------------------------------- + -- BudgetConfig UseProviderSource is disabled + ------------------------------------------------------- + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use staffing + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT staff.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON staff.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigGUID = egc.BudgetConfigGUID + WHERE + staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 + AND staff.IsDeleted = 0 + AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = bc.BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + + -- 2. all employees that are providers + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN staff.DepartmentID ELSE 0 END, + emp.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN [int].[FactStaffing] staff ON staff.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimEmployee] emp ON staff.EmployeeID = emp.EmployeeID + INNER JOIN [dss].[DimPhysician] phys ON phys.NPI = emp.NPI + INNER JOIN #filterTable tmp on staff.DepartmentID = tmp.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fw.DimPayCode pc on staff.PayCodeID = pc.PayCodeID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + INNER JOIN [fp].[BudgetConfig] bc on bc.BudgetConfigGUID = egc.BudgetConfigGUID + WHERE + staff.FiscalYearID = @CurrentFiscalYearID AND staff.TimeclassID = 1 + AND staff.IsDeleted = 0 + AND staff.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = bc.BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND staff.EmployeeID > 0 + AND emp.NPI NOT IN ('Not Specified', '0', '') + + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + src.DepartmentID, + src.JobCodeID, + pcg.PayCodeGroupID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + pc.ProviderLineItemID, + fm.MonthColumnName, + 1 as FixedPercentage, + SUM(ISNULL(src.Value, 0)) as Value + FROM + [int].[FactStaffing] src + INNER JOIN #dept dept ON src.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON src.EmployeeID = emp.EmployeeID AND (@EnableDepartmentLevelProviderForSampling = 0 OR src.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc ON src.PayCodeID = pc.PayCodeID + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = pc.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND fv.EmployeeID = 0 + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE + src.FiscalYearID = @CurrentFiscalYearID + AND src.TimeClassID = 1 + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 51 + AND fm.SortOrder <= @MonthsLoaded + AND pc.IsHoursIgnored = 0 + AND ps.Description = 'Staffing' + AND emp.IsFP = 1 + GROUP BY src.DepartmentID, + src.JobCodeID, + pcg.PayCodeGroupID, + emp.EmployeeID, + fm.MonthColumnName, + FixedPercentage, emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, pc.ProviderLineItemID + + END ELSE BEGIN + + ------------------------------------------------------- + -- BudgetConfig UseProviderSource is enabled + ------------------------------------------------------- + -- 1. Depts that are in fp.DepartmentLevelConfiguration table that do use provider + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT dept.DepartmentID, dept.EntityID, IsUsingProviderStaffing + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + + -- 2. all employees from staffing + INSERT INTO #emp (DepartmentID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, IsFP) + SELECT DISTINCT + CASE WHEN @EnableDepartmentLevelProviderForSampling = 1 THEN prov.DepartmentID ELSE 0 END, + phys.EmployeeID, + phys.PhysicianID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE ProviderTypeID END AS ProviderTypeID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE PhysicianSpecialtyID END AS ProviderSpecialtyID, + phys.IsFP + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN #filterTable tmp on config.DepartmentID = tmp.DepartmentID + INNER JOIN [int].[FactProvider] prov ON prov.DepartmentID = config.DepartmentID + INNER JOIN [dss].[DimPhysician] phys ON prov.PhysicianID = phys.PhysicianID + INNER JOIN [fw].[DimDepartment] dept ON tmp.DepartmentID = dept.DepartmentID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + prov.FiscalYearID = @CurrentFiscalYearID AND prov.TimeclassID = 1 AND prov.IsDeleted = 0 AND prov.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStaffing = 1 + AND ps.Description = 'Staffing' + AND phys.NPI NOT IN ('Not Specified', '0', '') + + INSERT INTO #TempIntStaffingData (DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, FixedPercentage, Value) + SELECT + DISTINCT + fp.DepartmentID, + 0 as JobCodeID, + 0 as PayCodeGroupID, + 0 as EmployeeID, + emp.ProviderID, + emp.ProviderTypeID, + emp.ProviderSpecialtyID, + fp.ProviderLineItemID, + fm.MonthColumnName, + 1 as FixedPercentage, + SUM(ISNULL(fp.Value, 0)) as Value + FROM + [int].[FactProvider] fp + INNER JOIN #dept dept ON fp.DepartmentID = dept.DepartmentID + INNER JOIN #emp emp ON fp.PhysicianID = emp.ProviderID AND (@EnableDepartmentLevelProviderForSampling = 0 OR fp.DepartmentID = emp.DepartmentID) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fp.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = fp.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + WHERE + fp.FiscalYearID = @CurrentFiscalYearID + AND fp.TimeClassID = 1 + AND fp.IsDeleted = 0 + AND fp.FiscalMonthID != 0 + AND fp.UnitTypeID = 51 + AND fm.SortOrder <= @MonthsLoaded + AND ps.Description = 'Staffing' + AND emp.IsFP = 1 + GROUP BY fp.DepartmentID, emp.EmployeeID, fm.MonthColumnName, + emp.ProviderID, ProviderTypeID, ProviderSpecialtyID, fp.ProviderLineItemID + + END + END + + -- Regular staffing + -- Populate into a temp table before summing up to deal with issues with the dynamic employee join + SELECT + src.DepartmentID, + src.JobCodeID, + pc.PayCodeID, + pc.PayCodeGroupID, + CASE + WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 + ELSE CASE + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE src.EmployeeID + END + END as EmployeeID, + 0 AS ProviderID, + 0 AS ProviderTypeID, + 0 AS ProviderSpecialtyID, + 0 AS ProviderLineItemID, + fm.FiscalMonthID, + fm.MonthColumnName, + ISNULL(fv.FixedPercentage, 1) as FixedPercentage, + ISNULL(src.Value, 0) as Value + INTO #intFactStaffingWithEmployeeResolvedForProvider + FROM [int].[FactStaffing] src + INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = src.FiscalMonthID + INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = src.PayCodeID + LEFT JOIN #dept dept ON tmp.DepartmentID = dept.DepartmentID + LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 1) emp ON src.EmployeeID = emp.EmployeeID + LEFT JOIN (SELECT DISTINCT EmployeeID, IsFP FROM #emp WHERE IsFP = 0) NotFpEmp ON src.EmployeeID = NotFpEmp.EmployeeID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND CASE WHEN @IsEmployeeBudgeting = 0 OR sefg.IsUsingEmployeeBudgeting = 0 THEN 0 -- When not using EB, we can just set it to 0. + WHEN ISNULL(fv.FixedPercentage, 1) < 1 THEN 0 -- If no record exists in FactStaffingVariabilityDetail, it's treated as 100% fixed + ELSE src.EmployeeID -- If we are using Employee Budgeting, use the EmployeeID from FS to see if the record is Fixed or not. + END = fv.EmployeeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE src.FiscalYearID = @CurrentFiscalYearID + AND src.TimeClassID = 1 + AND src.IsDeleted = 0 + AND src.FiscalMonthID != 0 + AND src.UnitTypeID = 51 + AND fm.SortOrder <= @MonthsLoaded + AND pc.IsHoursIgnored = 0 + AND (dept.DepartmentID IS NULL OR (emp.EmployeeID IS NULL AND (NotFpEmp.EmployeeID IS NULL OR NotFpEmp.IsFP = 0))) + + INSERT INTO #TempIntStaffingData + SELECT + src.DepartmentID, + src.JobCodeID, + src.PayCodeGroupID, + src.EmployeeID, + 0 AS ProviderID, + 0 AS ProviderTypeID, + 0 AS ProviderSpecialtyID, + 0 AS ProviderLineItemID, + src.MonthColumnName, + ISNULL(fv.FixedPercentage, 1) as FixedPercentage, + SUM(ISNULL(src.Value, 0)) as Value + FROM #intFactStaffingWithEmployeeResolvedForProvider src + INNER JOIN #filterTable tmp on src.DepartmentID = tmp.DepartmentID + LEFT JOIN [fp].[StaffingExpenseFlexingConfig] sefg on sefg.DepartmentID = src.DepartmentID AND sefg.EntityGroupConfigGUID = @EntityGroupConfigGUID + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv on fv.DepartmentID = src.DepartmentID + AND fv.JobCodeID = src.JobCodeID + AND fv.PayCodeID = src.PayCodeID + AND fv.EmployeeID = src.EmployeeID + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + GROUP BY src.DepartmentID, + src.JobCodeID, + src.PayCodeGroupID, + src.EmployeeID, + src.MonthColumnName, + fv.FixedPercentage + END + + INSERT INTO #IntStaffingData + SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, FixedPercentage, Value + FROM #TempIntStaffingData + WHERE FixedPercentage = 1 + + INSERT INTO #IntStaffingData + SELECT DepartmentID, JobCodeID, PayCodeGroupID, + CASE WHEN @IsEmployeeBudgeting = 0 AND ProviderID = 0 THEN 0 ELSE EmployeeID END AS EmployeeID, + ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, MAX(ISNULL(FixedPercentage, 1)), SUM(ISNULL(Value, 0)) + FROM #TempIntStaffingData + WHERE FixedPercentage <> 1 + GROUP BY DepartmentID, JobCodeID, PayCodeGroupID, MonthColumnName, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, CASE WHEN @IsEmployeeBudgeting = 0 AND ProviderID = 0 THEN 0 ELSE EmployeeID END + + -- Get Budget Year, since that is what we will need to check against for the ratio + -- in the main Original Hours proc, Sampled values were adjusted to reflect any difference in leap year/not leap year hours, so we need to adjust again + DECLARE @BudgetYearID INT + SELECT TOP 1 @BudgetYearID = FiscalYearID FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID + WHERE egc.EntityGroupConfigID = @EntityGroupConfigID + + -- We need this in case we are dealing with leap years to make sure that the number of hours is correctly adjusted between projection and budget + -- for this proc that is when Months Not Loaded are set to Sampled Values for the corresponding months + INSERT INTO #WorkingHoursRatioData + SELECT fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID + , (wh.Month01 / whSourceYear.Month01) + , (wh.Month02 / whSourceYear.Month02) + , (wh.Month03 / whSourceYear.Month03) + , (wh.Month04 / whSourceYear.Month04) + , (wh.Month05 / whSourceYear.Month05) + , (wh.Month06 / whSourceYear.Month06) + , (wh.Month07 / whSourceYear.Month07) + , (wh.Month08 / whSourceYear.Month08) + , (wh.Month09 / whSourceYear.Month09) + , (wh.Month10 / whSourceYear.Month10) + , (wh.Month11 / whSourceYear.Month11) + , (wh.Month12 / whSourceYear.Month12) + FROM + (SELECT DISTINCT f.DepartmentID, JobCodeID, PayCodeGroupID FROM fp.Staffing f + INNER JOIN #filterTable tmp on f.DepartmentID = tmp.DepartmentID + WHERE f.EntityGroupConfigID = @EntityGroupConfigID + ) fs + INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @CurrentFiscalYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + INNER JOIN [client].[FactWorkingHoursPerMonth] whSourceYear on whSourceYear.FiscalYearID = @BudgetYearID and whSourceYear.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + + + -- set all of the values from the source fy/tc + UPDATE + fs + SET + SampledProjectionHours01 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month01, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month01, 0) + END, + SampledProjectionHours02 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month02, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month02, 0) + END, + SampledProjectionHours03 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month03, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month03, 0) + END, + SampledProjectionHours04 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month04, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month04, 0) + END, + SampledProjectionHours05 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month05, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month05, 0) + END, + SampledProjectionHours06 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month06, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month06, 0) + END, + SampledProjectionHours07 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month07, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month07, 0) + END, + SampledProjectionHours08 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month08, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month08, 0) + END, + SampledProjectionHours09 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month09, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month09, 0) + END, + SampledProjectionHours10 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month10, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month10, 0) + END, + SampledProjectionHours11 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month11, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month11, 0) + END, + SampledProjectionHours12 = CASE + WHEN VariabilityID = 1 + THEN ISNULL((FixedPercentage), 1.0) * ISNULL(Month12, 0) + ELSE ISNULL(((1 - FixedPercentage)), 0) * ISNULL(Month12, 0) + END + FROM + [fp].[Staffing] fs + INNER JOIN + (SELECT DepartmentID, JobCodeID, PayCodeGroupID, EmployeeID, ProviderID, ProviderTypeID, ProviderSpecialtyID, ProviderLineItemID, MonthColumnName, Value, FixedPercentage FROM #IntStaffingData) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.JobCodeID = pv.JobCodeID + AND fs.PayCodeGroupID = pv.PayCodeGroupID + AND fs.EmployeeID = pv.EmployeeID + AND fs.ProviderID = pv.ProviderID + AND fs.ProviderTypeID = pv.ProviderTypeID + AND fs.ProviderSpecialtyID = pv.ProviderSpecialtyID + AND fs.ProviderLineItemID = pv.ProviderLineItemID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.ProductiveClassID <> 4 + + -- copy the baseline data over for months without data (month sort order > @MonthsLoaded) + -- make sure we apply the ratio of projection year / source year to get the correct valu + UPDATE + fs + SET + SampledProjectionHours02 = CASE WHEN @MonthsLoaded < 2 THEN SampledBudgetHours02 * wh.MonthRatio02 ELSE SampledProjectionHours02 END, + SampledProjectionHours03 = CASE WHEN @MonthsLoaded < 3 THEN SampledBudgetHours03 * wh.MonthRatio03 ELSE SampledProjectionHours03 END, + SampledProjectionHours04 = CASE WHEN @MonthsLoaded < 4 THEN SampledBudgetHours04 * wh.MonthRatio04 ELSE SampledProjectionHours04 END, + SampledProjectionHours05 = CASE WHEN @MonthsLoaded < 5 THEN SampledBudgetHours05 * wh.MonthRatio05 ELSE SampledProjectionHours05 END, + SampledProjectionHours06 = CASE WHEN @MonthsLoaded < 6 THEN SampledBudgetHours06 * wh.MonthRatio06 ELSE SampledProjectionHours06 END, + SampledProjectionHours07 = CASE WHEN @MonthsLoaded < 7 THEN SampledBudgetHours07 * wh.MonthRatio07 ELSE SampledProjectionHours07 END, + SampledProjectionHours08 = CASE WHEN @MonthsLoaded < 8 THEN SampledBudgetHours08 * wh.MonthRatio08 ELSE SampledProjectionHours08 END, + SampledProjectionHours09 = CASE WHEN @MonthsLoaded < 9 THEN SampledBudgetHours09 * wh.MonthRatio09 ELSE SampledProjectionHours09 END, + SampledProjectionHours10 = CASE WHEN @MonthsLoaded < 10 THEN SampledBudgetHours10 * wh.MonthRatio10 ELSE SampledProjectionHours10 END, + SampledProjectionHours11 = CASE WHEN @MonthsLoaded < 11 THEN SampledBudgetHours11 * wh.MonthRatio11 ELSE SampledProjectionHours11 END, + SampledProjectionHours12 = CASE WHEN @MonthsLoaded < 12 THEN SampledBudgetHours12 * wh.MonthRatio12 ELSE SampledProjectionHours12 END + FROM + [fp].[Staffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + INNER JOIN #WorkingHoursRatioData wh ON fs.DepartmentID = wh.DepartmentID AND fs.JobCodeID = wh.JobCodeID AND fs.PayCodeGroupID = wh.PayCodeGroupID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID + + + IF @BaselineTimeClassID = 2 AND @BaselineFiscalYearID = @CurrentFiscalYearID BEGIN + -- We are leaving Months Not Loaded Projection values what the Current Year Budget values are and not flattening the data + -- But we do have to potentially readjust for hours if Budget Year is leap year or current year is a leap year + IF EXISTS (SELECT 1 FROM #WorkingHoursRatioData WHERE MonthRatio01 <> 1.0 OR MonthRatio02 <> 1.0 OR MonthRatio03 <> 1.0 OR MonthRatio04 <> 1.0 OR MonthRatio05 <> 1.0 OR MonthRatio06<> 1.0 OR + MonthRatio07 <> 1.0 OR MonthRatio08 <> 1.0 OR MonthRatio09 <> 1.0 OR MonthRatio10 <> 1.0 OR MonthRatio11 <> 1.0 OR MonthRatio12 <> 1.0) + BEGIN + TRUNCATE TABLE #WorkingHoursRatioData + + INSERT INTO #WorkingHoursRatioData + SELECT fs.DepartmentID, fs.JobCodeID, fs.PayCodeGroupID + , (wh.Month01 / whSourceYear.Month01) + , (wh.Month02 / whSourceYear.Month02) + , (wh.Month03 / whSourceYear.Month03) + , (wh.Month04 / whSourceYear.Month04) + , (wh.Month05 / whSourceYear.Month05) + , (wh.Month06 / whSourceYear.Month06) + , (wh.Month07 / whSourceYear.Month07) + , (wh.Month08 / whSourceYear.Month08) + , (wh.Month09 / whSourceYear.Month09) + , (wh.Month10 / whSourceYear.Month10) + , (wh.Month11 / whSourceYear.Month11) + , (wh.Month12 / whSourceYear.Month12) + FROM + (SELECT DISTINCT f.DepartmentID, JobCodeID, PayCodeGroupID FROM fp.Staffing f + INNER JOIN #filterTable tmp on f.DepartmentID = tmp.DepartmentID + WHERE f.EntityGroupConfigID = @EntityGroupConfigID + ) fs + INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID + -- We switch the budget and source here because if the hours were adjusted for leap year when updating SampledBudget then they would need to be set back to the + -- values for the current year - see example below this statement + INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @BudgetYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + INNER JOIN [client].[FactWorkingHoursPerMonth] whSourceYear on whSourceYear.FiscalYearID = @CurrentFiscalYearID and whSourceYear.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + + /* + + Budget Year is 2017, Current Year is 2016 (leap year) + Baseline is Current Year Budget + February is in MonthsNotLoaded + Sampled February data for TimeClassID = 2/FiscalYearID = 2016 is 90 for hours + When we sample, February data for SampledBudget is adjusted to 86.8965 to account for difference in hours between years (so that FTE value is same for both) + Now we copy Feb's SampledBudget to SampledProjection since we're using CYB + If we didn't account for leap year, we'd copy 86.8965, but it should be 90 + So we need to apply the ratio back to February's value when copying SampledBudget to SampledProjection for MonthsNotLoaded + -- Extra note that this will only matter if February is in Months NOT Loaded + + */ + + END + + UPDATE + fs + SET + InitialProjectionHours01 = fs.SampledProjectionHours01, + InitialProjectionHours02 = fs.SampledProjectionHours02, + InitialProjectionHours03 = fs.SampledProjectionHours03, + InitialProjectionHours04 = fs.SampledProjectionHours04, + InitialProjectionHours05 = fs.SampledProjectionHours05, + InitialProjectionHours06 = fs.SampledProjectionHours06, + InitialProjectionHours07 = fs.SampledProjectionHours07, + InitialProjectionHours08 = fs.SampledProjectionHours08, + InitialProjectionHours09 = fs.SampledProjectionHours09, + InitialProjectionHours10 = fs.SampledProjectionHours10, + InitialProjectionHours11 = fs.SampledProjectionHours11, + InitialProjectionHours12 = fs.SampledProjectionHours12 + FROM [fp].[Staffing] fs + -- filter is implicit in #WorkingHoursRatioData so don't need to join on #filterTable + INNER JOIN #WorkingHoursRatioData wh on fs.DepartmentID = wh.DepartmentID AND wh.JobCodeID = fs.JobCodeID AND wh.PayCodeGroupID = fs.PayCodeGroupID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + + END ELSE BEGIN + SELECT fs.StaffingID, fs.DepartmentID, fs.JobCodeID, fs.VariabilityID, fs.ProviderID, fs.ProviderTypeID, fs.ProviderSpecialtyID, fs.ProviderLineItemID, + CASE + WHEN @MonthsLoaded = 12 THEN SampledProjectionHours01 + SampledProjectionHours02 + SampledProjectionHours03 + SampledProjectionHours04 + SampledProjectionHours05 + SampledProjectionHours06 + SampledProjectionHours07 + SampledProjectionHours08 + SampledProjectionHours09 + SampledProjectionHours10 + + SampledProjectionHours11 + SampledProjectionHours12 + WHEN @MonthsLoaded >= 11 THEN SampledProjectionHours01 + SampledProjectionHours02 + SampledProjectionHours03 + SampledProjectionHours04 + SampledProjectionHours05 + SampledProjectionHours06 + SampledProjectionHours07 + SampledProjectionHours08 + SampledProjectionHours09 + SampledProjectionHours10 + + SampledProjectionHours11 + WHEN @MonthsLoaded >= 10 THEN SampledProjectionHours01 + SampledProjectionHours02 + SampledProjectionHours03 + SampledProjectionHours04 + SampledProjectionHours05 + SampledProjectionHours06 + SampledProjectionHours07 + SampledProjectionHours08 + SampledProjectionHours09 + SampledProjectionHours10 + WHEN @MonthsLoaded >= 9 THEN SampledProjectionHours01 + SampledProjectionHours02 + SampledProjectionHours03 + SampledProjectionHours04 + SampledProjectionHours05 + SampledProjectionHours06 + SampledProjectionHours07 + SampledProjectionHours08 + SampledProjectionHours09 + WHEN @MonthsLoaded >= 8 THEN SampledProjectionHours01 + SampledProjectionHours02 + SampledProjectionHours03 + SampledProjectionHours04 + SampledProjectionHours05 + SampledProjectionHours06 + SampledProjectionHours07 + SampledProjectionHours08 + WHEN @MonthsLoaded >= 7 THEN SampledProjectionHours01 + SampledProjectionHours02 + SampledProjectionHours03 + SampledProjectionHours04 + SampledProjectionHours05 + SampledProjectionHours06 + SampledProjectionHours07 + WHEN @MonthsLoaded >= 6 THEN SampledProjectionHours01 + SampledProjectionHours02 + SampledProjectionHours03 + SampledProjectionHours04 + SampledProjectionHours05 + SampledProjectionHours06 + WHEN @MonthsLoaded >= 5 THEN SampledProjectionHours01 + SampledProjectionHours02 + SampledProjectionHours03 + SampledProjectionHours04 + SampledProjectionHours05 + WHEN @MonthsLoaded >= 4 THEN SampledProjectionHours01 + SampledProjectionHours02 + SampledProjectionHours03 + SampledProjectionHours04 + WHEN @MonthsLoaded >= 3 THEN SampledProjectionHours01 + SampledProjectionHours02 + SampledProjectionHours03 + WHEN @MonthsLoaded >= 2 THEN SampledProjectionHours01 + SampledProjectionHours02 + ELSE SampledProjectionHours01 + END AS SampledProjectionHoursTotal + INTO #MonthsLoadedTotal + FROM [fp].[Staffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + + -- spread hours so that FTEs remain flat for fixed job codes + -- figure out ftes... + SELECT h.DepartmentID, h.JobCodeID, h.PayCodeGroupID, h.EmployeeID, h.ProviderID, h.ProviderTypeID, h.ProviderSpecialtyID, h.ProviderLineItemID, h.EntityGroupConfigID, h.VariabilityID, + mnlt.SampledProjectionHoursTotal / ytd.YTDHours AS AverageFTE + INTO #fteTemp + FROM [fp].[Staffing] h + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on h.PayCodeGroupID = exc.PayCodeGroupID + INNER JOIN #MonthsLoadedTotal mnlt on h.StaffingID = mnlt.StaffingID -- don't need to join #filterTable here because #MonthsLoadedTotal already has that filtered + INNER JOIN [fw].[DimJobCode] jc on h.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on h.DepartmentID = dept.DepartmentID + INNER JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] ytd on ytd.FiscalYearID = @CurrentFiscalYearID and ytd.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + INNER JOIN [fw].[DimFiscalMonth] fm on fm.SortOrder = @MonthsLoaded AND ytd.FiscalMonthID = fm.FiscalMonthID + WHERE h.EntityGroupConfigID = @EntityGroupConfigID AND (exc.PayCodeGroupID IS NOT NULL OR h.VariabilityID = 1) + + -- Projected hours should vary by working hours for fixed JobCodes + UPDATE + fs + SET + InitialProjectionHours01 = CASE WHEN @MonthsLoaded >= 1 THEN fs.SampledProjectionHours01 ELSE AverageFTE * wh.Month01 END, + InitialProjectionHours02 = CASE WHEN @MonthsLoaded >= 2 THEN fs.SampledProjectionHours02 ELSE AverageFTE * wh.Month02 END, + InitialProjectionHours03 = CASE WHEN @MonthsLoaded >= 3 THEN fs.SampledProjectionHours03 ELSE AverageFTE * wh.Month03 END, + InitialProjectionHours04 = CASE WHEN @MonthsLoaded >= 4 THEN fs.SampledProjectionHours04 ELSE AverageFTE * wh.Month04 END, + InitialProjectionHours05 = CASE WHEN @MonthsLoaded >= 5 THEN fs.SampledProjectionHours05 ELSE AverageFTE * wh.Month05 END, + InitialProjectionHours06 = CASE WHEN @MonthsLoaded >= 6 THEN fs.SampledProjectionHours06 ELSE AverageFTE * wh.Month06 END, + InitialProjectionHours07 = CASE WHEN @MonthsLoaded >= 7 THEN fs.SampledProjectionHours07 ELSE AverageFTE * wh.Month07 END, + InitialProjectionHours08 = CASE WHEN @MonthsLoaded >= 8 THEN fs.SampledProjectionHours08 ELSE AverageFTE * wh.Month08 END, + InitialProjectionHours09 = CASE WHEN @MonthsLoaded >= 9 THEN fs.SampledProjectionHours09 ELSE AverageFTE * wh.Month09 END, + InitialProjectionHours10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.SampledProjectionHours10 ELSE AverageFTE * wh.Month10 END, + InitialProjectionHours11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.SampledProjectionHours11 ELSE AverageFTE * wh.Month11 END, + InitialProjectionHours12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.SampledProjectionHours12 ELSE AverageFTE * wh.Month12 END + FROM [fp].[Staffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fs.PayCodeGroupID = exc.PayCodeGroupID + INNER JOIN #fteTemp fte ON fs.DepartmentID = fte.DepartmentID AND fs.JobCodeID = fte.JobCodeID AND fs.PayCodeGroupID = fte.PayCodeGroupID AND fs.EmployeeID = fte.EmployeeID + AND fs.EntityGroupConfigID = fte.EntityGroupConfigID AND fs.VariabilityID = fte.VariabilityID AND fs.ProviderID = fte.ProviderID + AND fs.ProviderTypeID = fte.ProviderTypeID + AND fs.ProviderSpecialtyID = fte.ProviderSpecialtyID + AND fs.ProviderLineItemID = fte.ProviderLineItemID + INNER JOIN [fw].[DimJobCode] jc on fs.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimDepartment] dept on fs.DepartmentID = dept.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh on wh.FiscalYearID = @CurrentFiscalYearID and wh.WorkWeekID = (case when jc.WorkWeekOverrideID != -1 then jc.WorkWeekOverrideID else dept.WorkWeekID end) + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND (exc.PayCodeGroupID IS NOT NULL OR fs.VariabilityID = 1) + + -- Projected hours should be flat for variable Job Codes or PayCodeGroups that have ProductiveClass that is excluded from FTE calcs + UPDATE + fs + SET + InitialProjectionHours01 = CASE WHEN @MonthsLoaded >= 1 THEN fs.SampledProjectionHours01 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours02 = CASE WHEN @MonthsLoaded >= 2 THEN fs.SampledProjectionHours02 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours03 = CASE WHEN @MonthsLoaded >= 3 THEN fs.SampledProjectionHours03 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours04 = CASE WHEN @MonthsLoaded >= 4 THEN fs.SampledProjectionHours04 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours05 = CASE WHEN @MonthsLoaded >= 5 THEN fs.SampledProjectionHours05 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours06 = CASE WHEN @MonthsLoaded >= 6 THEN fs.SampledProjectionHours06 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours07 = CASE WHEN @MonthsLoaded >= 7 THEN fs.SampledProjectionHours07 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours08 = CASE WHEN @MonthsLoaded >= 8 THEN fs.SampledProjectionHours08 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours09 = CASE WHEN @MonthsLoaded >= 9 THEN fs.SampledProjectionHours09 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.SampledProjectionHours10 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.SampledProjectionHours11 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END, + InitialProjectionHours12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.SampledProjectionHours12 ELSE (fs.SampledProjectionHoursTotal - t.SampledProjectionHoursTotal) / (12.0 - @MonthsLoaded) END + FROM [fp].[Staffing] fs INNER JOIN #MonthsLoadedTotal t on fs.StaffingID = t.StaffingID + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + LEFT JOIN [fp].[viewExcludedProductiveClassesForFTE] exc on fs.PayCodeGroupID = exc.PayCodeGroupID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.VariabilityID = 2 AND exc.PayCodeGroupID IS NULL + END +END +GO + + +--------------------------------------------- + +-- fp.procSampleStaffingWageRate +CREATE PROCEDURE [fp].[procSampleStaffingWageRate] + @EntityGroupConfigID int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY + WITH RECOMPILE +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-08-25 BW JAZZ-13122 Performance update per DBA re-write + ** 2 2022-01-20 OP JAZZ-31481 Restricted Prov Comp Wage Rate sampling + ** 3 2023-02-16 BK JAZZ-50052 Update to copy SampledProjecton to InitialProjection for MonthsNotLoaded when baseline is Current Year Budget + ** instead of getting average of MonthsNotLoaded dollars and hours and flattening the wage rate + ** 4 2023-09-20 BK JAZZ-60973 Update for data restructure + *************************************************************/ + + CREATE TABLE #filterTable (DepartmentID int) + INSERT INTO #filterTable (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #filterTable WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #filterTable (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fp.Staffing + WHERE EntityGroupConfigID = @EntityGroupConfigID + + END + + DECLARE @MonthsLoaded INT, @StaffingTimeClassID INT, @StaffingFiscalYearID INT, @CurrentFiscalYearID INT + + SELECT @MonthsLoaded = MonthsLoaded, @StaffingTimeClassID = PayrollTimeClassID, @StaffingFiscalYearID = PayrollFiscalYearID, @CurrentFiscalYearID = bc.FiscalYearID - 1 FROM fp.EntityGroupConfig egc + INNER JOIN fp.BudgetConfig bc on egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE EntityGroupConfigID = @EntityGroupConfigID + + + UPDATE wr SET + wr.SampledBudget01 = COALESCE(NULLIF(fs.SampledBudgetDollars01, 0) / NULLIF(fs.SampledBudgetHours01, 0), 0) + , wr.SampledBudget02 = COALESCE(NULLIF(fs.SampledBudgetDollars02, 0) / NULLIF(fs.SampledBudgetHours02, 0), 0) + , wr.SampledBudget03 = COALESCE(NULLIF(fs.SampledBudgetDollars03, 0) / NULLIF(fs.SampledBudgetHours03, 0), 0) + , wr.SampledBudget04 = COALESCE(NULLIF(fs.SampledBudgetDollars04, 0) / NULLIF(fs.SampledBudgetHours04, 0), 0) + , wr.SampledBudget05 = COALESCE(NULLIF(fs.SampledBudgetDollars05, 0) / NULLIF(fs.SampledBudgetHours05, 0), 0) + , wr.SampledBudget06 = COALESCE(NULLIF(fs.SampledBudgetDollars06, 0) / NULLIF(fs.SampledBudgetHours06, 0), 0) + , wr.SampledBudget07 = COALESCE(NULLIF(fs.SampledBudgetDollars07, 0) / NULLIF(fs.SampledBudgetHours07, 0), 0) + , wr.SampledBudget08 = COALESCE(NULLIF(fs.SampledBudgetDollars08, 0) / NULLIF(fs.SampledBudgetHours08, 0), 0) + , wr.SampledBudget09 = COALESCE(NULLIF(fs.SampledBudgetDollars09, 0) / NULLIF(fs.SampledBudgetHours09, 0), 0) + , wr.SampledBudget10 = COALESCE(NULLIF(fs.SampledBudgetDollars10, 0) / NULLIF(fs.SampledBudgetHours10, 0), 0) + , wr.SampledBudget11 = COALESCE(NULLIF(fs.SampledBudgetDollars11, 0) / NULLIF(fs.SampledBudgetHours11, 0), 0) + , wr.SampledBudget12 = COALESCE(NULLIF(fs.SampledBudgetDollars12, 0) / NULLIF(fs.SampledBudgetHours12, 0), 0) + --- + , wr.SampledProjection01 = COALESCE(NULLIF(fs.SampledProjectionDollars01, 0) / NULLIF(fs.SampledProjectionHours01, 0), 0) + , wr.SampledProjection02 = COALESCE(NULLIF(fs.SampledProjectionDollars02, 0) / NULLIF(fs.SampledProjectionHours02, 0), 0) + , wr.SampledProjection03 = COALESCE(NULLIF(fs.SampledProjectionDollars03, 0) / NULLIF(fs.SampledProjectionHours03, 0), 0) + , wr.SampledProjection04 = COALESCE(NULLIF(fs.SampledProjectionDollars04, 0) / NULLIF(fs.SampledProjectionHours04, 0), 0) + , wr.SampledProjection05 = COALESCE(NULLIF(fs.SampledProjectionDollars05, 0) / NULLIF(fs.SampledProjectionHours05, 0), 0) + , wr.SampledProjection06 = COALESCE(NULLIF(fs.SampledProjectionDollars06, 0) / NULLIF(fs.SampledProjectionHours06, 0), 0) + , wr.SampledProjection07 = COALESCE(NULLIF(fs.SampledProjectionDollars07, 0) / NULLIF(fs.SampledProjectionHours07, 0), 0) + , wr.SampledProjection08 = COALESCE(NULLIF(fs.SampledProjectionDollars08, 0) / NULLIF(fs.SampledProjectionHours08, 0), 0) + , wr.SampledProjection09 = COALESCE(NULLIF(fs.SampledProjectionDollars09, 0) / NULLIF(fs.SampledProjectionHours09, 0), 0) + , wr.SampledProjection10 = COALESCE(NULLIF(fs.SampledProjectionDollars10, 0) / NULLIF(fs.SampledProjectionHours10, 0), 0) + , wr.SampledProjection11 = COALESCE(NULLIF(fs.SampledProjectionDollars11, 0) / NULLIF(fs.SampledProjectionHours11, 0), 0) + , wr.SampledProjection12 = COALESCE(NULLIF(fs.SampledProjectionDollars12, 0) / NULLIF(fs.SampledProjectionHours12, 0), 0) + -- + , wr.InitialBudget01 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0) + , wr.InitialBudget02 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0) + , wr.InitialBudget03 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0) + , wr.InitialBudget04 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0) + , wr.InitialBudget05 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0) + , wr.InitialBudget06 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0) + , wr.InitialBudget07 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0) + , wr.InitialBudget08 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0) + , wr.InitialBudget09 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0) + , wr.InitialBudget10 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0) + , wr.InitialBudget11 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0) + , wr.InitialBudget12 = COALESCE(NULLIF(fs.SampledBudgetDollarsTotal, 0) / NULLIF(fs.SampledBudgetHoursTotal, 0), 0) + FROM [fp].[StaffingWageRate] wr + INNER JOIN (SELECT StaffingWageRateID, + SUM(SampledBudgetDollars01) as SampledBudgetDollars01, SUM(SampledBudgetDollars02) as SampledBudgetDollars02, SUM(SampledBudgetDollars03) as SampledBudgetDollars03, SUM(SampledBudgetDollars04) as SampledBudgetDollars04, + SUM(SampledBudgetDollars05) as SampledBudgetDollars05, SUM(SampledBudgetDollars06) as SampledBudgetDollars06, SUM(SampledBudgetDollars07) as SampledBudgetDollars07, SUM(SampledBudgetDollars08) as SampledBudgetDollars08, + SUM(SampledBudgetDollars09) as SampledBudgetDollars09, SUM(SampledBudgetDollars10) as SampledBudgetDollars10, SUM(SampledBudgetDollars11) as SampledBudgetDollars11, SUM(SampledBudgetDollars12) as SampledBudgetDollars12, + SUM(SampledBudgetDollarsTotal) as SampledBudgetDollarsTotal, + SUM(SampledBudgetHours01) as SampledBudgetHours01, SUM(SampledBudgetHours02) as SampledBudgetHours02, SUM(SampledBudgetHours03) as SampledBudgetHours03, SUM(SampledBudgetHours04) as SampledBudgetHours04, + SUM(SampledBudgetHours05) as SampledBudgetHours05, SUM(SampledBudgetHours06) as SampledBudgetHours06, SUM(SampledBudgetHours07) as SampledBudgetHours07, SUM(SampledBudgetHours08) as SampledBudgetHours08, + SUM(SampledBudgetHours09) as SampledBudgetHours09, SUM(SampledBudgetHours10) as SampledBudgetHours10, SUM(SampledBudgetHours11) as SampledBudgetHours11, SUM(SampledBudgetHours12) as SampledBudgetHours12, + SUM(SampledBudgetHoursTotal) as SampledBudgetHoursTotal , + SUM(SampledProjectionDollars01) as SampledProjectionDollars01, SUM(SampledProjectionDollars02) as SampledProjectionDollars02, SUM(SampledProjectionDollars03) as SampledProjectionDollars03, SUM(SampledProjectionDollars04) as SampledProjectionDollars04, + SUM(SampledProjectionDollars05) as SampledProjectionDollars05, SUM(SampledProjectionDollars06) as SampledProjectionDollars06, SUM(SampledProjectionDollars07) as SampledProjectionDollars07, SUM(SampledProjectionDollars08) as SampledProjectionDollars08, + SUM(SampledProjectionDollars09) as SampledProjectionDollars09, SUM(SampledProjectionDollars10) as SampledProjectionDollars10, SUM(SampledProjectionDollars11) as SampledProjectionDollars11, SUM(SampledProjectionDollars12) as SampledProjectionDollars12, + SUM(SampledProjectionDollarsTotal) as SampledProjectionDollarsTotal, + SUM(SampledProjectionHours01) as SampledProjectionHours01, SUM(SampledProjectionHours02) as SampledProjectionHours02, SUM(SampledProjectionHours03) as SampledProjectionHours03, SUM(SampledProjectionHours04) as SampledProjectionHours04, + SUM(SampledProjectionHours05) as SampledProjectionHours05, SUM(SampledProjectionHours06) as SampledProjectionHours06, SUM(SampledProjectionHours07) as SampledProjectionHours07, SUM(SampledProjectionHours08) as SampledProjectionHours08, + SUM(SampledProjectionHours09) as SampledProjectionHours09, SUM(SampledProjectionHours10) as SampledProjectionHours10, SUM(SampledProjectionHours11) as SampledProjectionHours11, SUM(SampledProjectionHours12) as SampledProjectionHours12, + SUM(SampledProjectionHoursTotal) as SampledProjectionHoursTotal + FROM fp.Staffing fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + AND fs.SubsectionID = 3 -- Staffing + GROUP BY StaffingWageRateID) fs ON fs.StaffingWageRateID = wr.StaffingWageRateID + + + + IF @StaffingTimeClassID = 2 AND @StaffingFiscalYearID = @CurrentFiscalYearID BEGIN + -- Current Year Budget only + UPDATE wr + SET + InitialProjection01 = wr.SampledProjection01, + InitialProjection02 = wr.SampledProjection02, + InitialProjection03 = wr.SampledProjection03, + InitialProjection04 = wr.SampledProjection04, + InitialProjection05 = wr.SampledProjection05, + InitialProjection06 = wr.SampledProjection06, + InitialProjection07 = wr.SampledProjection07, + InitialProjection08 = wr.SampledProjection08, + InitialProjection09 = wr.SampledProjection09, + InitialProjection10 = wr.SampledProjection10, + InitialProjection11 = wr.SampledProjection11, + InitialProjection12 = wr.SampledProjection12 + FROM [fp].[StaffingWageRate] wr + INNER JOIN fp.Staffing fs ON fs.StaffingWageRateID = wr.StaffingWageRateID + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + + END ELSE BEGIN + + CREATE TABLE #Totals (StaffingWageRateID INT, SampledProjectionDollarsTotal DECIMAL(19,8), SampledProjectionHoursTotal DECIMAL(19,8), NewDollars DECIMAL(19,8), NewHours DECIMAL(19,8)) + INSERT INTO #Totals (StaffingWageRateID, SampledProjectionDollarsTotal, SampledProjectionHoursTotal) + SELECT fs.StaffingWageRateID, + CASE + WHEN @MonthsLoaded = 11 THEN SUM(fs.SampledProjectionDollars12) + WHEN @MonthsLoaded = 10 THEN SUM(fs.SampledProjectionDollars11) + SUM(fs.SampledProjectionDollars12) + WHEN @MonthsLoaded = 9 THEN SUM(fs.SampledProjectionDollars10) + SUM(fs.SampledProjectionDollars11) + SUM(fs.SampledProjectionDollars12) + WHEN @MonthsLoaded = 8 THEN SUM(fs.SampledProjectionDollars09) + SUM(fs.SampledProjectionDollars10) + SUM(fs.SampledProjectionDollars11) + SUM(fs.SampledProjectionDollars12) + WHEN @MonthsLoaded = 7 THEN SUM(fs.SampledProjectionDollars08) + SUM(fs.SampledProjectionDollars09) + SUM(fs.SampledProjectionDollars10) + SUM(fs.SampledProjectionDollars11) + SUM(fs.SampledProjectionDollars12) + WHEN @MonthsLoaded = 6 THEN SUM(fs.SampledProjectionDollars07) + SUM(fs.SampledProjectionDollars08) + SUM(fs.SampledProjectionDollars09) + SUM(fs.SampledProjectionDollars10) + SUM(fs.SampledProjectionDollars11) + SUM(fs.SampledProjectionDollars12) + WHEN @MonthsLoaded = 5 THEN SUM(fs.SampledProjectionDollars06) + SUM(fs.SampledProjectionDollars07) + SUM(fs.SampledProjectionDollars08) + SUM(fs.SampledProjectionDollars09) + SUM(fs.SampledProjectionDollars10) + SUM(fs.SampledProjectionDollars11) + SUM(fs.SampledProjectionDollars12) + WHEN @MonthsLoaded = 4 THEN SUM(fs.SampledProjectionDollars05) + SUM(fs.SampledProjectionDollars06) + SUM(fs.SampledProjectionDollars07) + SUM(fs.SampledProjectionDollars08) + SUM(fs.SampledProjectionDollars09) + SUM(fs.SampledProjectionDollars10) + SUM(fs.SampledProjectionDollars11) + SUM(fs.SampledProjectionDollars12) + WHEN @MonthsLoaded = 3 THEN SUM(fs.SampledProjectionDollars04) + SUM(fs.SampledProjectionDollars05) + SUM(fs.SampledProjectionDollars06) + SUM(fs.SampledProjectionDollars07) + SUM(fs.SampledProjectionDollars08) + SUM(fs.SampledProjectionDollars09) + SUM(fs.SampledProjectionDollars10 ) + SUM(fs.SampledProjectionDollars11) + SUM(fs.SampledProjectionDollars12) + WHEN @MonthsLoaded = 2 THEN SUM(fs.SampledProjectionDollars03) + SUM(fs.SampledProjectionDollars04) + SUM(fs.SampledProjectionDollars05) + SUM(fs.SampledProjectionDollars06) + SUM(fs.SampledProjectionDollars07) + SUM(fs.SampledProjectionDollars08) + SUM(fs.SampledProjectionDollars09) + SUM(fs.SampledProjectionDollars10) + SUM(fs.SampledProjectionDollars11) + SUM(fs.SampledProjectionDollars12) + WHEN @MonthsLoaded = 1 THEN SUM(fs.SampledProjectionDollars02) + SUM(fs.SampledProjectionDollars03) + SUM(fs.SampledProjectionDollars04) + SUM(fs.SampledProjectionDollars05) + SUM(fs.SampledProjectionDollars06) + SUM(fs.SampledProjectionDollars07) + SUM(fs.SampledProjectionDollars08) + SUM(fs.SampledProjectionDollars09) + SUM(fs.SampledProjectionDollars10) + SUM(fs.SampledProjectionDollars11) + SUM(fs.SampledProjectionDollars12) + ELSE 0 + END, + CASE + WHEN @MonthsLoaded = 11 THEN SUM(fs.SampledProjectionHours12) + WHEN @MonthsLoaded = 10 THEN SUM(fs.SampledProjectionHours11) + SUM(fs.SampledProjectionHours12) + WHEN @MonthsLoaded = 9 THEN SUM(fs.SampledProjectionHours10) + SUM(fs.SampledProjectionHours11) + SUM(fs.SampledProjectionHours12) + WHEN @MonthsLoaded = 8 THEN SUM(fs.SampledProjectionHours09) + SUM(fs.SampledProjectionHours10) + SUM(fs.SampledProjectionHours11) + SUM(fs.SampledProjectionHours12) + WHEN @MonthsLoaded = 7 THEN SUM(fs.SampledProjectionHours08) + SUM(fs.SampledProjectionHours09) + SUM(fs.SampledProjectionHours10) + SUM(fs.SampledProjectionHours11) + SUM(fs.SampledProjectionHours12) + WHEN @MonthsLoaded = 6 THEN SUM(fs.SampledProjectionHours07) + SUM(fs.SampledProjectionHours08) + SUM(fs.SampledProjectionHours09) + SUM(fs.SampledProjectionHours10) + SUM(fs.SampledProjectionHours11) + SUM(fs.SampledProjectionHours12) + WHEN @MonthsLoaded = 5 THEN SUM(fs.SampledProjectionHours06) + SUM(fs.SampledProjectionHours07) + SUM(fs.SampledProjectionHours08) + SUM(fs.SampledProjectionHours09) + SUM(fs.SampledProjectionHours10) + SUM(fs.SampledProjectionHours11) + SUM(fs.SampledProjectionHours12) + WHEN @MonthsLoaded = 4 THEN SUM(fs.SampledProjectionHours05) + SUM(fs.SampledProjectionHours06) + SUM(fs.SampledProjectionHours07) + SUM(fs.SampledProjectionHours08) + SUM(fs.SampledProjectionHours09) + SUM(fs.SampledProjectionHours10) + SUM(fs.SampledProjectionHours11) + SUM(fs.SampledProjectionHours12) + WHEN @MonthsLoaded = 3 THEN SUM(fs.SampledProjectionHours04) + SUM(fs.SampledProjectionHours05) + SUM(fs.SampledProjectionHours06) + SUM(fs.SampledProjectionHours07) + SUM(fs.SampledProjectionHours08) + SUM(fs.SampledProjectionHours09) + SUM(fs.SampledProjectionHours10 ) + SUM(fs.SampledProjectionHours11) + SUM(fs.SampledProjectionHours12) + WHEN @MonthsLoaded = 2 THEN SUM(fs.SampledProjectionHours03) + SUM(fs.SampledProjectionHours04) + SUM(fs.SampledProjectionHours05) + SUM(fs.SampledProjectionHours06) + SUM(fs.SampledProjectionHours07) + SUM(fs.SampledProjectionHours08) + SUM(fs.SampledProjectionHours09) + SUM(fs.SampledProjectionHours10) + SUM(fs.SampledProjectionHours11) + SUM(fs.SampledProjectionHours12) + WHEN @MonthsLoaded = 1 THEN SUM(fs.SampledProjectionHours02) + SUM(fs.SampledProjectionHours03) + SUM(fs.SampledProjectionHours04) + SUM(fs.SampledProjectionHours05) + SUM(fs.SampledProjectionHours06) + SUM(fs.SampledProjectionHours07) + SUM(fs.SampledProjectionHours08) + SUM(fs.SampledProjectionHours09) + SUM(fs.SampledProjectionHours10) + SUM(fs.SampledProjectionHours11) + SUM(fs.SampledProjectionHours12) + ELSE 0 + END + + FROM [fp].[Staffing] fs + INNER JOIN #filterTable tmp on fs.DepartmentID = tmp.DepartmentID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 3 -- Staffing Subsection + GROUP BY StaffingWageRateID + + UPDATE a SET + NewHours = SampledProjectionHoursTotal / (12.0 - @MonthsLoaded), + NewDollars = SampledProjectionDollarsTotal / (12.0 - @MonthsLoaded) + FROM #Totals a + + UPDATE wr + SET + InitialProjection01 = CASE WHEN @MonthsLoaded >= 1 THEN wr.SampledProjection01 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END + , InitialProjection02 = CASE WHEN @MonthsLoaded >= 2 THEN wr.SampledProjection02 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END + , InitialProjection03 = CASE WHEN @MonthsLoaded >= 3 THEN wr.SampledProjection03 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END + , InitialProjection04 = CASE WHEN @MonthsLoaded >= 4 THEN wr.SampledProjection04 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END + , InitialProjection05 = CASE WHEN @MonthsLoaded >= 5 THEN wr.SampledProjection05 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END + , InitialProjection06 = CASE WHEN @MonthsLoaded >= 6 THEN wr.SampledProjection06 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END + , InitialProjection07 = CASE WHEN @MonthsLoaded >= 7 THEN wr.SampledProjection07 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END + , InitialProjection08 = CASE WHEN @MonthsLoaded >= 8 THEN wr.SampledProjection08 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END + , InitialProjection09 = CASE WHEN @MonthsLoaded >= 9 THEN wr.SampledProjection09 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END + , InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN wr.SampledProjection10 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END + , InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN wr.SampledProjection11 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END + , InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN wr.SampledProjection12 ELSE COALESCE(NULLIF(fs.NewDollars,0) / NULLIF(fs.NewHours,0), 0) END + FROM [fp].[StaffingWageRate] wr + INNER JOIN #Totals fs ON fs.StaffingWageRateID = wr.StaffingWageRateID + END + + -- Update all target, budget, and projection adjusted + UPDATE wr + SET + TargetAdjusted01 = InitialBudget01 + , TargetAdjusted02 = InitialBudget02 + , TargetAdjusted03 = InitialBudget03 + , TargetAdjusted04 = InitialBudget04 + , TargetAdjusted05 = InitialBudget05 + , TargetAdjusted06 = InitialBudget06 + , TargetAdjusted07 = InitialBudget07 + , TargetAdjusted08 = InitialBudget08 + , TargetAdjusted09 = InitialBudget09 + , TargetAdjusted10 = InitialBudget10 + , TargetAdjusted11 = InitialBudget11 + , TargetAdjusted12 = InitialBudget12 + , BudgetAdjusted01 = InitialBudget01 + , BudgetAdjusted02 = InitialBudget02 + , BudgetAdjusted03 = InitialBudget03 + , BudgetAdjusted04 = InitialBudget04 + , BudgetAdjusted05 = InitialBudget05 + , BudgetAdjusted06 = InitialBudget06 + , BudgetAdjusted07 = InitialBudget07 + , BudgetAdjusted08 = InitialBudget08 + , BudgetAdjusted09 = InitialBudget09 + , BudgetAdjusted10 = InitialBudget10 + , BudgetAdjusted11 = InitialBudget11 + , BudgetAdjusted12 = InitialBudget12 + , ProjectionAdjusted01 = InitialProjection01 + , ProjectionAdjusted02 = InitialProjection02 + , ProjectionAdjusted03 = InitialProjection03 + , ProjectionAdjusted04 = InitialProjection04 + , ProjectionAdjusted05 = InitialProjection05 + , ProjectionAdjusted06 = InitialProjection06 + , ProjectionAdjusted07 = InitialProjection07 + , ProjectionAdjusted08 = InitialProjection08 + , ProjectionAdjusted09 = InitialProjection09 + , ProjectionAdjusted10 = InitialProjection10 + , ProjectionAdjusted11 = InitialProjection11 + , ProjectionAdjusted12 = InitialProjection12 + FROM [fp].[StaffingWageRate] wr + INNER JOIN (SELECT StaffingWageRateID + FROM fp.Staffing s + INNER JOIN #filterTable ft on s.DepartmentID = ft.DepartmentID + WHERE VariabilityID = 1 AND IsNew = 0) fs on wr.StaffingWageRateID = fs.StaffingWageRateID +END +GO + + +--------------------------------------------- + +-- fp.procSampleStatsBudgetData +CREATE PROCEDURE [fp].[procSampleStatsBudgetData] + @EntityGroupConfigID int +AS +BEGIN +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-09-30 JB JAZZ-43489 Remove FlexedValue references + *************************************************************/ + -- update the budget data + INSERT INTO [fp].[FactStatisticsBudget]([StatisticsID], [BudgetPhaseID], + [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12]) + SELECT [StatisticsID], [BudgetPhaseID], + [InitialBudget01], [InitialBudget02], [InitialBudget03], [InitialBudget04], [InitialBudget05], [InitialBudget06], [InitialBudget07], [InitialBudget08], [InitialBudget09], [InitialBudget10], [InitialBudget11], [InitialBudget12] + FROM [fp].[FactStatistics] fs + CROSS APPLY (VALUES (2),(3)) bp(BudgetPhaseID) + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND IsNew = 0 + +END +GO + + +--------------------------------------------- + +-- fp.procSampleStatsClearData +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2021-02-25 lrenadesouza JAZZ-12907 Added rolling deletes +** 2 2021-06-09 NThomas JAZZ-20639 Add new table StatisticsAdjustmentRate +** 3 2023-04-19 mdeboer JAZZ-53496 Remove adjustment delete logic +** 4 2023-07-05 mdeboer JAZZ-55672 Add remove config logic +***************************************************************/ + +CREATE PROCEDURE [fp].[procSampleStatsClearData] + @BudgetConfigGUID uniqueidentifier, + @EntityGroupConfigID int, + @IsRemoveConfig BIT = 0 +AS +BEGIN + + DECLARE @ChunkCount INT; + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 400000 END; + DECLARE @r INT; + + CREATE TABLE #StatsToDelete (StatisticsID INT) + + IF @IsRemoveConfig = 1 + BEGIN + INSERT #StatsToDelete with (tablock) (StatisticsID) + SELECT StatisticsID FROM fp.FactStatistics + WHERE EntityGroupConfigID = @EntityGroupConfigID + END + ELSE + BEGIN + INSERT #StatsToDelete with (tablock) (StatisticsID) + SELECT StatisticsID FROM fp.FactStatistics + WHERE EntityGroupConfigID = @EntityGroupConfigID AND IsNew = 0 + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) fsch + FROM [fp].[StatisticsChangeHistory] fsch + INNER JOIN [fp].[FactStatistics] fs on fs.StatisticsID = fsch.StatisticsID + INNER JOIN #StatsToDelete std on fsch.StatisticsID = std.StatisticsID; + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + -- delete existing data (have to do value tables first so that we still have EntityGroupConfigID) + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) fsb + FROM [fp].[FactStatisticsBudget] fsb + INNER JOIN [fp].[FactStatistics] fs on fs.StatisticsID = fsb.StatisticsID + INNER JOIN #StatsToDelete std on fsb.StatisticsID = std.StatisticsID; + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) fsb + FROM [fp].[FactStatisticsProjection] fsb + INNER JOIN [fp].[FactStatistics] fs on fs.StatisticsID = fsb.StatisticsID + INNER JOIN #StatsToDelete std on fsb.StatisticsID = std.StatisticsID; + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) fsb + FROM [fp].[FactStatisticsHistory] fsb + INNER JOIN [fp].[FactStatistics] fs on fs.StatisticsID = fsb.StatisticsID + INNER JOIN #StatsToDelete std on fsb.StatisticsID = std.StatisticsID; + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + SET @r = 1; + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) fs + FROM [fp].[FactStatistics] fs + INNER JOIN #StatsToDelete std on fs.StatisticsID = std.StatisticsID; + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + +END; +GO + + +--------------------------------------------- + +-- fp.procSampleStatsDimensionality +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-06-05 Created +** 2 2018-11-01 OV B-20952 Add new budget config sampling sources (Statistics only) +** 3 2018-11-05 OV B-20952 Filtered by ParentBudgetConfigID +** 4 2018-11-30 BK D-07892 Limit prior year dimensionality to TimeClassID = 1 +** 5 2018-12-13 GF B-20952 Revert MR changes +** 6 2019-08-12 CB B-23990 Filter accounts to stat accounts only +** 7 2020-10-27 BK JAZZ-2905 Add support for provider sampling +** 8 2021-02-01 MY JAZZ-14416 Update driver subsection = 1 +** 9 2022-01-18 BK JAZZ-32267 Add support for charge based stats +** 9 2022-04-04 BK JAZZ-35385 Add Patient Type to join for Charge-Based stats sampling +** 10 2022-04-07 BW JAZZ-35906 Add entity group config filter for Charge-Based stats sampling +** 11 2022-12-12 DM JAZZ-46455 Sampling of Provider Type and Provider Specialty is linked to Section Setup +** 12 2023-02-17 MY JAZZ-49985 Provider Statistics will NOT sample if there is no YTD data for a dept/provider +** 13 2023-03-30 MZ JAZZ-51398 Extended left join by ProviderID for departments configured to use provider stats data +** 14 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config +***************************************************************/ +CREATE PROCEDURE [fp].[procSampleStatsDimensionality] + @BudgetConfigID INT, + @EntityGroupConfigID INT, + @CurrentFiscalYearID SMALLINT, + @SourceFiscalYearID SMALLINT, + @SourceTimeClassID TINYINT +AS +BEGIN + + DECLARE @IsProviderPlanningEnabled BIT; + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc WHERE BudgetConfigID = @BudgetConfigID; + + DECLARE @IsUsingSystemGeneratedStats BIT; + SELECT @IsUsingSystemGeneratedStats = IsUsingSystemGeneratedHistoricalStats FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID; + + DECLARE @IsProviderTypeDisabled BIT; + SELECT @IsProviderTypeDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderTypeID' AND PlanSectionID = 3 AND SubSectionID = 1 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + + DECLARE @IsProviderSpecialtyDisabled BIT; + SELECT @IsProviderSpecialtyDisabled = CASE WHEN EXISTS ( + SELECT * + FROM fp.SectionSetup ss + INNER JOIN fp.BudgetConfig bc ON ss.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE IsHidden = 1 AND bc.BudgetConfigID = @BudgetConfigID AND LevelID = 'ProviderSpecialtyID' AND PlanSectionID = 3 AND SubSectionID = 1 + ) + THEN CAST(1 AS BIT) + ELSE CAST(0 AS BIT) END; + + IF @IsProviderPlanningEnabled = 0 BEGIN + INSERT INTO [fp].[FactStatistics]([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], + [FinancialReportingID], [PayorID], [PatientClassID], [UnitTypeID], [SubsectionID]) + SELECT + DISTINCT + @BudgetConfigID, + @EntityGroupConfigID, + dept.EntityID, + stat.DepartmentID, + stat.AccountID, + acc.OBUnitsFinancialReportingID, + acc.OBPayorID, + acc.PatientClassID, + acc.OBStatUnitTypeID, + 1 + FROM + [int].[FactStatistic] stat + INNER JOIN [fw].[DimDepartment] dept ON stat.DepartmentID = dept.DepartmentID + INNER JOIN [fw].[DimAccount] acc on stat.AccountID = acc.AccountID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + LEFT JOIN ( + SELECT DISTINCT DepartmentID, AccountID + FROM [fp].[FactStatistics] + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND IsNew = 1 + ) fs + ON stat.DepartmentID = fs.DepartmentID + AND stat.AccountID = fs.AccountID + WHERE + ((stat.FiscalYearID = @SourceFiscalYearID AND stat.TimeclassID = @SourceTimeClassID) -- baseline + OR (stat.FiscalYearID = @CurrentFiscalYearID) -- projection (current year actuals) + OR (stat.FiscalYearID = @CurrentFiscalYearID - 1 AND stat.TimeClassID = 1)) -- prior year, actual & budget + AND stat.IsDeleted = 0 + AND stat.FiscalMonthID != 0 + AND acc.IsStat = 1 -- CID 6 - filter to stat accounts only - this needs to be updated once we have a separate AP account config + AND acc.OBStatUnitTypeID = 140 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND fs.DepartmentID IS NULL + END ELSE BEGIN + IF OBJECT_ID('tempdb..#dept') IS NOT NULL DROP TABLE #dept + CREATE TABLE #dept (DepartmentID INT, EntityID INT, UseProvider BIT) + + -- Three steps to make sure we get all departments to sample + -- 1. Departments in DepartmentLevelConfiguration and do not use Provider Stats + -- 2. Departments in DepartmentLevelConfiguration and do use Provider Stats + -- 3. Departments not in DepartmentLevelConfiguration + + -- 1. Depts that are in fp.DepartmentLevelConfiguration table + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT stat.DepartmentID, dept.EntityID, IsUsingProviderStats + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN [int].[FactStatistic] stat ON stat.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON stat.DepartmentID = dept.DepartmentID + INNER JOIN [fw].[DimAccount] acc on stat.AccountID = acc.AccountID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + ( + (stat.FiscalYearID = @SourceFiscalYearID AND stat.TimeclassID = @SourceTimeClassID) -- baseline + OR (stat.FiscalYearID = @CurrentFiscalYearID) -- projection (current year actuals) + OR (stat.FiscalYearID = @CurrentFiscalYearID - 1 AND stat.TimeClassID = 1) -- prior year, actual & budget + ) + AND stat.IsDeleted = 0 + AND stat.FiscalMonthID != 0 + AND acc.IsStat = 1 -- CID 6 - filter to stat accounts only - this needs to be updated once we have a separate AP account config + AND acc.OBStatUnitTypeID = 140 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStats = 0 + + -- 2. depts in DepartmentLevelConfiguration that use provider stats + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT stat.DepartmentID, dept.EntityID, IsUsingProviderStats + FROM [fp].[DepartmentLevelConfiguration] config + INNER JOIN [int].[FactProvider] stat ON stat.DepartmentID = config.DepartmentID + INNER JOIN [fw].[DimDepartment] dept ON dept.DepartmentID = config.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE + ( + (stat.FiscalYearID = @SourceFiscalYearID AND stat.TimeclassID = @SourceTimeClassID) -- baseline + OR (stat.FiscalYearID = @CurrentFiscalYearID) -- projection (current year actuals) + OR (stat.FiscalYearID = @CurrentFiscalYearID - 1 AND stat.TimeClassID = 1) -- prior year, actual & budget + ) + AND stat.IsDeleted = 0 + AND stat.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.BudgetConfigID = @BudgetConfigID + AND config.IsUsingProviderStats = 1 + + -- 3. get any departments that aren't in the fp.DepartmentLevelConfiguration table for the Budget + INSERT INTO #dept (DepartmentID, EntityID, UseProvider) + SELECT DISTINCT stat.DepartmentID, dept.EntityID, ISNULL(IsUsingProviderStats, 0) + FROM [int].[FactStatistic] stat + INNER JOIN [fw].[DimAccount] acc on stat.AccountID = acc.AccountID + INNER JOIN [fw].[DimDepartment] dept ON stat.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + LEFT JOIN (SELECT DepartmentID, IsUsingProviderStats FROM [fp].[DepartmentLevelConfiguration] WHERE BudgetConfigID = @BudgetConfigID) config ON stat.DepartmentID = config.DepartmentID + LEFT JOIN #dept d on stat.DepartmentID = d.DepartmentID + WHERE + ( + (stat.FiscalYearID = @SourceFiscalYearID AND stat.TimeclassID = @SourceTimeClassID) -- baseline + OR (stat.FiscalYearID = @CurrentFiscalYearID) -- projection (current year actuals) + OR (stat.FiscalYearID = @CurrentFiscalYearID - 1 AND stat.TimeClassID = 1) -- prior year, actual & budget + ) + AND stat.IsDeleted = 0 + AND stat.FiscalMonthID != 0 + AND acc.IsStat = 1 -- CID 6 - filter to stat accounts only - this needs to be updated once we have a separate AP account config + AND acc.OBStatUnitTypeID = 140 + AND egc.EntityGroupConfigID = @EntityGroupConfigID + AND config.IsUsingProviderStats IS NULL + AND d.DepartmentID IS NULL + + -- sample actual dimensionality + INSERT INTO [fp].[FactStatistics]([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID], [UnitTypeID], + ProviderID, ProviderLineItemID, ProviderSpecialtyID, ProviderTypeID, SubsectionID) + SELECT + DISTINCT + @BudgetConfigID, + @EntityGroupConfigID, + dept.EntityID, + stat.DepartmentID, + stat.AccountID, + acc.OBUnitsFinancialReportingID, + acc.OBPayorID, + acc.PatientClassID, + acc.OBStatUnitTypeID, 0, 0, 0, 0, 1 + FROM + [int].[FactStatistic] stat + INNER JOIN #dept dept ON stat.DepartmentID = dept.DepartmentID + INNER JOIN [fw].[DimAccount] acc on stat.AccountID = acc.AccountID + LEFT JOIN ( + SELECT DISTINCT DepartmentID, AccountID + FROM [fp].[FactStatistics] + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND IsNew = 1 + ) fs + ON stat.DepartmentID = fs.DepartmentID + AND stat.AccountID = fs.AccountID + WHERE + ( + (stat.FiscalYearID = @SourceFiscalYearID AND stat.TimeclassID = @SourceTimeClassID) -- baseline + OR (stat.FiscalYearID = @CurrentFiscalYearID) -- projection (current year actuals) + OR (stat.FiscalYearID = @CurrentFiscalYearID - 1 AND stat.TimeClassID = 1) -- prior year, actual & budget + ) + AND stat.IsDeleted = 0 + AND stat.FiscalMonthID != 0 + AND acc.IsStat = 1 -- CID 6 - filter to stat accounts only - this needs to be updated once we have a separate AP account config + AND acc.OBStatUnitTypeID = 140 + AND fs.DepartmentID IS NULL + AND dept.UseProvider = 0 + + -- departments configured to use provider stats data + INSERT INTO [fp].[FactStatistics]([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID], [UnitTypeID], + ProviderID, ProviderLineItemID, ProviderSpecialtyID, ProviderTypeID, SubsectionID) + SELECT + DISTINCT + @BudgetConfigID, + @EntityGroupConfigID, + dept.EntityID, + prov.DepartmentID, + acc.AccountID, + acc.OBUnitsFinancialReportingID, + acc.OBPayorID, + acc.PatientClassID, + acc.OBStatUnitTypeID, + prov.PhysicianID, + prov.ProviderLineItemID, + CASE WHEN @IsProviderSpecialtyDisabled = 1 THEN 0 ELSE phys.PhysicianSpecialtyID END AS ProviderSpecialtyID, + CASE WHEN @IsProviderTypeDisabled = 1 THEN 0 ELSE phys.ProviderTypeID END AS ProviderTypeID, + 1 + FROM + [int].[FactProvider] prov + INNER JOIN #dept dept ON prov.DepartmentID = dept.DepartmentID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = prov.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN fp.ProviderStatisticsConfig config on prov.ProviderLineItemID = config.ProviderLineItemID + INNER JOIN [fw].[DimAccount] acc on config.AccountID = acc.AccountID + INNER JOIN dss.DimPhysician phys on prov.PhysicianID = phys.PhysicianID + LEFT JOIN ( + SELECT DISTINCT DepartmentID, AccountID, ProviderID + FROM [fp].[FactStatistics] + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND IsNew = 1 + ) fs + ON prov.DepartmentID = fs.DepartmentID + AND acc.AccountID = fs.AccountID + AND phys.PhysicianID = fs.ProviderID + WHERE + ( + (prov.FiscalYearID = @SourceFiscalYearID AND prov.TimeclassID = @SourceTimeClassID) -- baseline + OR (prov.FiscalYearID = @CurrentFiscalYearID) -- projection (current year actuals) + OR (prov.FiscalYearID = @CurrentFiscalYearID - 1 AND prov.TimeClassID = 1) -- prior year, actual & budget + ) + AND prov.FiscalMonthID != 0 + AND acc.IsStat = 1 -- CID 6 - filter to stat accounts only - this needs to be updated once we have a separate AP account config + AND acc.OBStatUnitTypeID = 140 + AND fs.DepartmentID IS NULL + AND dept.UseProvider = 1 + AND ps.Description = 'Statistics' + AND config.BudgetConfigID = @BudgetConfigID + + END + + --If flag is true, for dimensionality (DeptID, AcctID, FiscalYearID, TimeClassID) that exists in fw.FactChargeBasedStatisticsMonthly, + --attempt to set historical stats from fw.FactChargeBasedStatisticsMonthly + + IF(@IsUsingSystemGeneratedStats = 1) + BEGIN + IF OBJECT_ID('tempdb..#existingStats') IS NOT NULL DROP TABLE #existingStats + CREATE TABLE #existingStats (DepartmentID INT, AccountID INT, PatientClassID INT) + + --Pull existing stats data so we know what not to touch + INSERT INTO #existingStats (DepartmentID, AccountID, PatientClassID ) + SELECT stat.DepartmentID, stat.AccountID, stat.PatientClassID + FROM fp.FactStatistics stat WHERE EntityGroupConfigID = @EntityGroupConfigID + + + -- sample dimensionality that does not exist in int.FactStatistic + INSERT INTO [fp].[FactStatistics]([BudgetConfigID], [EntityGroupConfigID], [EntityID], [DepartmentID], [AccountID], [FinancialReportingID], [PayorID], [PatientClassID], [UnitTypeID], + ProviderID, ProviderLineItemID, ProviderSpecialtyID, ProviderTypeID, SubsectionID) + SELECT @BudgetConfigID, + @EntityGroupConfigID, + dept.EntityID, + cbs.DepartmentID, + cbs.AccountID, + cbs.OBUnitsFinancialReportingID, + cbs.OBPayorID, + cbs.PatientClassID, + cbs.OBStatUnitTypeID, 0, 0, 0, 0, 1 + FROM (SELECT DISTINCT stat.DepartmentID, stat.AccountID, acc.OBUnitsFinancialReportingID, acc.OBPayorID, acc.PatientClassID, acc.OBStatUnitTypeID + FROM fw.FactChargeBasedStatisticsMonthly stat + INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID + INNER JOIN [fw].[DimDepartment] dept ON stat.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm ON egcm.EntityID = dept.EntityID + INNER JOIN [fp].[EntityGroupConfig] egc on egcm.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE stat.FiscalYearID IN (@CurrentFiscalYearID, @CurrentFiscalYearID - 1) + AND stat.IsDeleted = 0 + AND stat.FiscalMonthID != 0 + AND egc.EntityGroupConfigID = @EntityGroupConfigID -- Filter for the targeted config + ) as cbs -- Charge Based Stats + INNER JOIN fw.DimDepartment dept ON cbs.DepartmentID = dept.DepartmentID + LEFT JOIN #existingStats intData ON cbs.DepartmentID = intData.DepartmentID + AND cbs.AccountID = intData.AccountID + AND cbs.PatientClassID = intData.PatientClassID + WHERE intData.DepartmentID is null + END + +END +GO + + +--------------------------------------------- + +-- fp.procSampleStatsHistoricalData +CREATE PROCEDURE [fp].[procSampleStatsHistoricalData] + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @MonthsLoaded int +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-12-08 MD JAZZ-67 Update AP Stat sampling to leverage charge based stats + ** 2 2022-03-07 NT JAZZ-34087 Add FiscalMonthID in the JOIN when generating system generated stats + ** 3 2022-06-09 AO JAZZ-32943 Replaced INNER JOIN to LEFT, to set value to 0 if it isn't exist in int.FactProvider, but it is in fp.FactStatistics + ** 4 2022-07-18 NT JAZZ-40469 Fix the filter on FiscalYearID when calculating CurrentYear values + ** 5 2023-07-14 BK JAZZ-56315 If using provider do not use overwrite with System Generate Stats + ** 6 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config + *************************************************************/ + + -- pad all of the data + INSERT INTO [fp].[FactStatisticsHistory]([StatisticsID]) + SELECT [StatisticsID] + FROM [fp].[FactStatistics] fs + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND IsNew = 0 + + DECLARE @IsProviderPlanningEnabled BIT; + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID; + + DECLARE @BudgetConfigID INT + SELECT @BudgetConfigID = BudgetConfigID FROM fp.EntityGroupConfig a INNER JOIN fp.BudgetConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID + + DECLARE @IsUsingSystemGeneratedStats BIT; + SELECT @IsUsingSystemGeneratedStats = IsUsingSystemGeneratedHistoricalStats FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID; + IF @IsUsingSystemGeneratedStats = NULL BEGIN SET @IsUsingSystemGeneratedStats = 0 END + + -- set all of the values for prior year actual + UPDATE + fsh + SET + PriorYearActualValue01 = ISNULL(Month01, 0), + PriorYearActualValue02 = ISNULL(Month02, 0), + PriorYearActualValue03 = ISNULL(Month03, 0), + PriorYearActualValue04 = ISNULL(Month04, 0), + PriorYearActualValue05 = ISNULL(Month05, 0), + PriorYearActualValue06 = ISNULL(Month06, 0), + PriorYearActualValue07 = ISNULL(Month07, 0), + PriorYearActualValue08 = ISNULL(Month08, 0), + PriorYearActualValue09 = ISNULL(Month09, 0), + PriorYearActualValue10 = ISNULL(Month10, 0), + PriorYearActualValue11 = ISNULL(Month11, 0), + PriorYearActualValue12 = ISNULL(Month12, 0) + FROM + [fp].[FactStatisticsHistory] fsh + INNER JOIN [fp].[FactStatistics] fs ON fs.StatisticsID = fsh.StatisticsID + INNER JOIN + (SELECT stat.DepartmentID, stat.AccountID, fm.MonthColumnName, SUM(Value) as Value + FROM [int].[FactStatistic] stat + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID + INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID + WHERE stat.FiscalYearID = (@CurrentFiscalYearID - 1) AND stat.TimeclassID = 1 AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 + GROUP BY stat.DepartmentID, stat.AccountID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.AccountID = pv.AccountID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID = 1) + + + -- set all of the values for current year actual/annualized + UPDATE + fsh + SET + ActualYTDValue01 = ISNULL(Month01, 0), + ActualYTDValue02 = ISNULL(Month02, 0), + ActualYTDValue03 = ISNULL(Month03, 0), + ActualYTDValue04 = ISNULL(Month04, 0), + ActualYTDValue05 = ISNULL(Month05, 0), + ActualYTDValue06 = ISNULL(Month06, 0), + ActualYTDValue07 = ISNULL(Month07, 0), + ActualYTDValue08 = ISNULL(Month08, 0), + ActualYTDValue09 = ISNULL(Month09, 0), + ActualYTDValue10 = ISNULL(Month10, 0), + ActualYTDValue11 = ISNULL(Month11, 0), + ActualYTDValue12 = ISNULL(Month12, 0) + FROM + [fp].[FactStatisticsHistory] fsh + INNER JOIN [fp].[FactStatistics] fs ON fs.StatisticsID = fsh.StatisticsID + INNER JOIN + (SELECT stat.DepartmentID, stat.AccountID, fm.MonthColumnName, SUM(Value) as Value + FROM [int].[FactStatistic] stat + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID + INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID + WHERE stat.FiscalYearID = @CurrentFiscalYearID AND stat.TimeclassID = 1 AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded + GROUP BY stat.DepartmentID, stat.AccountID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.AccountID = pv.AccountID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID = 1) + + + -- set all of the values for current year budget + UPDATE + fsh + SET + CurrentYearBudget01 = ISNULL(Month01, 0), + CurrentYearBudget02 = ISNULL(Month02, 0), + CurrentYearBudget03 = ISNULL(Month03, 0), + CurrentYearBudget04 = ISNULL(Month04, 0), + CurrentYearBudget05 = ISNULL(Month05, 0), + CurrentYearBudget06 = ISNULL(Month06, 0), + CurrentYearBudget07 = ISNULL(Month07, 0), + CurrentYearBudget08 = ISNULL(Month08, 0), + CurrentYearBudget09 = ISNULL(Month09, 0), + CurrentYearBudget10 = ISNULL(Month10, 0), + CurrentYearBudget11 = ISNULL(Month11, 0), + CurrentYearBudget12 = ISNULL(Month12, 0) + FROM + [fp].[FactStatisticsHistory] fsh + INNER JOIN [fp].[FactStatistics] fs ON fs.StatisticsID = fsh.StatisticsID + INNER JOIN + (SELECT stat.DepartmentID, stat.AccountID, fm.MonthColumnName, SUM(Value) as Value + FROM [int].[FactStatistic] stat + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID + INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID + WHERE stat.FiscalYearID = @CurrentFiscalYearID AND stat.TimeclassID = 2 AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 + GROUP BY stat.DepartmentID, stat.AccountID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.AccountID = pv.AccountID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND (@IsProviderPlanningEnabled = 0 OR fs.SubsectionID = 1) + + ----------------------------------------------------------------------------------------------------------------------------------------------- + ----------------------------------------------------------------------------------------------------------------------------------------------- + ----------------------------------------------------------------------------------------------------------------------------------------------- + + --If flag is true, for dimensionality (DeptID, AcctID, FiscalYearID, TimeClassID) that doesn't exist in int.FactStatistic, + --attempt to set historical stats from fw.FactChargeBasedStatisticsMonthly + + IF(@IsUsingSystemGeneratedStats = 1) + BEGIN + IF OBJECT_ID('tempdb..#existingStats') IS NOT NULL DROP TABLE #existingStats + CREATE TABLE #existingStats (DepartmentID INT, AccountID INT, PatientClassID INT, TimeClassID INT, FiscalYearID INT, FiscalMonthID INT) + + --Pull existing stats data so we know what not to touch + INSERT INTO #existingStats (DepartmentID, AccountID, PatientClassID, TimeClassID, FiscalYearID, FiscalMonthID) + SELECT DISTINCT stat.DepartmentID, stat.AccountID, acc.PatientClassID, stat.TimeClassID, stat.FiscalYearID, stat.FiscalMonthID + FROM int.FactStatistic stat + INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID + WHERE 1=1 + AND stat.TimeClassID in (1,2) + AND stat.FiscalYearID in (@CurrentFiscalYearID, @CurrentFiscalYearID - 1) + AND stat.IsDeleted = 0 + AND stat.FiscalMonthID != 0 + + -- set all of the values for prior year actual that do not exist in int.FactStatistic + UPDATE + fsh + SET + PriorYearActualValue01 = ISNULL(Month01, PriorYearActualValue01), + PriorYearActualValue02 = ISNULL(Month02, PriorYearActualValue02), + PriorYearActualValue03 = ISNULL(Month03, PriorYearActualValue03), + PriorYearActualValue04 = ISNULL(Month04, PriorYearActualValue04), + PriorYearActualValue05 = ISNULL(Month05, PriorYearActualValue05), + PriorYearActualValue06 = ISNULL(Month06, PriorYearActualValue06), + PriorYearActualValue07 = ISNULL(Month07, PriorYearActualValue07), + PriorYearActualValue08 = ISNULL(Month08, PriorYearActualValue08), + PriorYearActualValue09 = ISNULL(Month09, PriorYearActualValue09), + PriorYearActualValue10 = ISNULL(Month10, PriorYearActualValue10), + PriorYearActualValue11 = ISNULL(Month11, PriorYearActualValue11), + PriorYearActualValue12 = ISNULL(Month12, PriorYearActualValue12) + FROM + [fp].[FactStatisticsHistory] fsh + INNER JOIN [fp].[FactStatistics] fs ON fs.StatisticsID = fsh.StatisticsID + INNER JOIN + (SELECT stat.DepartmentID, + stat.AccountID, + acc.PatientClassID, + fm.MonthColumnName, + SUM(Value) AS Value + FROM fw.FactChargeBasedStatisticsMonthly stat + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID + INNER JOIN [fw].[DimAccount] acc on stat.AccountID = acc.AccountID + LEFT JOIN (SELECT exStats.DepartmentID, exStats.AccountID, exStats.PatientClassID, exStats.TimeClassID, exStats.FiscalYearID, exStats.FiscalMonthID + FROM #existingStats exStats + WHERE exStats.FiscalYearID = (@CurrentFiscalYearID - 1) + AND exStats.TimeclassID = 1 + ) intData + ON stat.DepartmentID = intData.DepartmentID + AND stat.AccountID = intData.AccountID + AND stat.FiscalMonthID = intdata.FiscalMonthID + AND acc.PatientClassID = intData.PatientClassID + WHERE stat.FiscalYearID = (@CurrentFiscalYearID - 1) + AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 + AND intData.DepartmentID IS NULL + GROUP BY stat.DepartmentID, stat.AccountID, acc.PatientClassID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.AccountID = pv.AccountID + AND fs.PatientClassID = pv.PatientClassID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID = 0 AND fs.ProviderLineItemID = 0 + + -- set all of the values for current year actual/annualized that do not exist in int.FactStatistic + UPDATE + fsh + SET + ActualYTDValue01 = ISNULL(Month01, ActualYTDValue01), + ActualYTDValue02 = ISNULL(Month02, ActualYTDValue02), + ActualYTDValue03 = ISNULL(Month03, ActualYTDValue03), + ActualYTDValue04 = ISNULL(Month04, ActualYTDValue04), + ActualYTDValue05 = ISNULL(Month05, ActualYTDValue05), + ActualYTDValue06 = ISNULL(Month06, ActualYTDValue06), + ActualYTDValue07 = ISNULL(Month07, ActualYTDValue07), + ActualYTDValue08 = ISNULL(Month08, ActualYTDValue08), + ActualYTDValue09 = ISNULL(Month09, ActualYTDValue09), + ActualYTDValue10 = ISNULL(Month10, ActualYTDValue10), + ActualYTDValue11 = ISNULL(Month11, ActualYTDValue11), + ActualYTDValue12 = ISNULL(Month12, ActualYTDValue12) + FROM + [fp].[FactStatisticsHistory] fsh + INNER JOIN [fp].[FactStatistics] fs ON fs.StatisticsID = fsh.StatisticsID + INNER JOIN + (SELECT stat.DepartmentID, stat.AccountID, acc.PatientClassID, fm.MonthColumnName, SUM(Value) as Value + FROM fw.FactChargeBasedStatisticsMonthly stat + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID + INNER JOIN [fw].[DimAccount] acc on stat.AccountID = acc.AccountID + LEFT JOIN (SELECT exStats.DepartmentID, exStats.AccountID, exStats.PatientClassID, exStats.TimeClassID, exStats.FiscalYearID, exStats.FiscalMonthID + FROM #existingStats exStats + WHERE exStats.FiscalYearID = (@CurrentFiscalYearID) + AND exStats.TimeclassID = 1 + ) intData + ON stat.DepartmentID = intData.DepartmentID + AND stat.AccountID = intData.AccountID + AND stat.FiscalMonthID = intdata.FiscalMonthID + AND acc.PatientClassID = intData.PatientClassID + WHERE stat.FiscalYearID = @CurrentFiscalYearID + AND stat.IsDeleted = 0 + AND stat.FiscalMonthID != 0 + AND fm.SortOrder <= @MonthsLoaded + AND intData.DepartmentID IS NULL + GROUP BY stat.DepartmentID, stat.AccountID, acc.PatientClassID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.AccountID = pv.AccountID + AND fs.PatientClassID = pv.PatientClassID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID = 0 AND fs.ProviderLineItemID = 0 + + -- We do not populate Current Year Budget with this process + + END + + ----------------------------------------------------------------------------------------------------------------------------------------------- + ----------------------------------------------------------------------------------------------------------------------------------------------- + ----------------------------------------------------------------------------------------------------------------------------------------------- + -- sample provider historicals + + IF @IsProviderPlanningEnabled = 1 BEGIN + + + -- set all of the values for prior year actual + UPDATE + fsh + SET + PriorYearActualValue01 = ISNULL(Month01, 0), + PriorYearActualValue02 = ISNULL(Month02, 0), + PriorYearActualValue03 = ISNULL(Month03, 0), + PriorYearActualValue04 = ISNULL(Month04, 0), + PriorYearActualValue05 = ISNULL(Month05, 0), + PriorYearActualValue06 = ISNULL(Month06, 0), + PriorYearActualValue07 = ISNULL(Month07, 0), + PriorYearActualValue08 = ISNULL(Month08, 0), + PriorYearActualValue09 = ISNULL(Month09, 0), + PriorYearActualValue10 = ISNULL(Month10, 0), + PriorYearActualValue11 = ISNULL(Month11, 0), + PriorYearActualValue12 = ISNULL(Month12, 0) + FROM + [fp].[FactStatisticsHistory] fsh + INNER JOIN [fp].[FactStatistics] fs ON fs.StatisticsID = fsh.StatisticsID + LEFT JOIN + (SELECT stat.DepartmentID, config.AccountID, fm.MonthColumnName, SUM(Value) as Value, stat.ProviderLineItemID, stat.PhysicianID as ProviderID + FROM [int].[FactProvider] stat + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = stat.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN fp.ProviderStatisticsConfig config on stat.ProviderLineItemID = config.ProviderLineItemID + INNER JOIN [fw].[DimAccount] acc on config.AccountID = acc.AccountID + WHERE stat.FiscalYearID = (@CurrentFiscalYearID - 1) AND stat.TimeclassID = 1 AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 AND ps.Description = 'Statistics' AND BudgetConfigID = @BudgetConfigID + GROUP BY stat.DepartmentID, config.AccountID, fm.MonthColumnName, stat.ProviderLineItemID, stat.PhysicianID) pv + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.AccountID = pv.AccountID + AND fs.ProviderID = pv.ProviderID + AND fs.ProviderLineItemID = pv.ProviderLineItemID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID <> 0 + + + -- set all of the values for current year actual/annualized + UPDATE + fsh + SET + ActualYTDValue01 = ISNULL(Month01, 0), + ActualYTDValue02 = ISNULL(Month02, 0), + ActualYTDValue03 = ISNULL(Month03, 0), + ActualYTDValue04 = ISNULL(Month04, 0), + ActualYTDValue05 = ISNULL(Month05, 0), + ActualYTDValue06 = ISNULL(Month06, 0), + ActualYTDValue07 = ISNULL(Month07, 0), + ActualYTDValue08 = ISNULL(Month08, 0), + ActualYTDValue09 = ISNULL(Month09, 0), + ActualYTDValue10 = ISNULL(Month10, 0), + ActualYTDValue11 = ISNULL(Month11, 0), + ActualYTDValue12 = ISNULL(Month12, 0) + FROM + [fp].[FactStatisticsHistory] fsh + INNER JOIN [fp].[FactStatistics] fs ON fs.StatisticsID = fsh.StatisticsID + LEFT JOIN + (SELECT stat.DepartmentID, config.AccountID, fm.MonthColumnName, SUM(Value) as Value, stat.ProviderLineItemID, stat.PhysicianID as ProviderID + FROM [int].[FactProvider] stat + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = stat.ProviderLineItemID + INNER JOIN fp.ProviderStatisticsConfig config on stat.ProviderLineItemID = config.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fw].[DimAccount] acc on config.AccountID = acc.AccountID + WHERE stat.FiscalYearID = @CurrentFiscalYearID AND stat.TimeclassID = 1 AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded AND ps.Description = 'Statistics' AND BudgetConfigID = @BudgetConfigID + GROUP BY stat.DepartmentID, config.AccountID, fm.MonthColumnName, stat.ProviderLineItemID, stat.PhysicianID) pv + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.AccountID = pv.AccountID + AND fs.ProviderID = pv.ProviderID + AND fs.ProviderLineItemID = pv.ProviderLineItemID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID <> 0 + + + -- set all of the values for current year budget + UPDATE + fsh + SET + CurrentYearBudget01 = ISNULL(Month01, 0), + CurrentYearBudget02 = ISNULL(Month02, 0), + CurrentYearBudget03 = ISNULL(Month03, 0), + CurrentYearBudget04 = ISNULL(Month04, 0), + CurrentYearBudget05 = ISNULL(Month05, 0), + CurrentYearBudget06 = ISNULL(Month06, 0), + CurrentYearBudget07 = ISNULL(Month07, 0), + CurrentYearBudget08 = ISNULL(Month08, 0), + CurrentYearBudget09 = ISNULL(Month09, 0), + CurrentYearBudget10 = ISNULL(Month10, 0), + CurrentYearBudget11 = ISNULL(Month11, 0), + CurrentYearBudget12 = ISNULL(Month12, 0) + FROM + [fp].[FactStatisticsHistory] fsh + INNER JOIN [fp].[FactStatistics] fs ON fs.StatisticsID = fsh.StatisticsID + LEFT JOIN + (SELECT stat.DepartmentID, config.AccountID, fm.MonthColumnName, SUM(Value) as Value, stat.ProviderLineItemID, stat.PhysicianID as ProviderID + FROM [int].[FactProvider] stat + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = stat.ProviderLineItemID + INNER JOIN fp.ProviderStatisticsConfig config on stat.ProviderLineItemID = config.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN [fw].[DimAccount] acc on config.AccountID = acc.AccountID + WHERE stat.FiscalYearID = @CurrentFiscalYearID AND stat.TimeclassID = 2 AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 AND ps.Description = 'Statistics' AND BudgetConfigID = @BudgetConfigID + GROUP BY stat.DepartmentID, config.AccountID, fm.MonthColumnName, stat.ProviderLineItemID, stat.PhysicianID) pv + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.AccountID = pv.AccountID + AND fs.ProviderID = pv.ProviderID + AND fs.ProviderLineItemID = pv.ProviderLineItemID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID <> 0 + + END +END +GO + + +--------------------------------------------- + +-- fp.procSampleStatsOriginalBudgetVolume +CREATE PROCEDURE [fp].[procSampleStatsOriginalBudgetVolume] + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @SourceFiscalYearID smallint, + @SourceTimeClassID tinyint, + @MonthsLoaded int +AS +BEGIN + +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-05-06 Created +** 2 2018-11-05 OV B-20952 Add new budget config sampling sources (Statistics only) +** 3 2018-11-07 BK B-21035 Spread InitialValue evenly across months +** 4 2020-10-27 BK JAZZ-2905 Add provider data +** 5 2021-04-21 BK JAZZ-18500 Fix subsection +** 6 2022-02-17 MD JAZZ-33345 Add code to handle projection of system generated stats +** 7 2022-03-08 NT JAZZ-34087 Add FiscalMonthID in the JOIN when generating charge based stats +** 8 2022-04-04 BK JAZZ-35385 Add Patient Type to join for Charge-Based stats sampling +** 9 2022-06-09 AO JAZZ-32943 Replaced INNER JOIN to LEFT, to set value to 0 if it isn't exist in int.FactProvider, but it is in fp.FactStatistics +** 10 2023-07-15 BK JAZZ-35385 Add Patient Type to join for Charge-Based stats sampling +** 11 2023-07-14 BK JAZZ-56315 If using provider do not use overwrite with System Generate Stats +** 12 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config +***************************************************************/ + +DECLARE @IsAnnualized bit = (CASE WHEN @SourceFiscalYearID = @CurrentFiscalYearID AND @SourceTimeClassID = 1 THEN 1 ELSE 0 END) + + +declare @ParentEntityConfigID int = ( +select EntityGroupConfigID +from fp.EntityGroupConfig +where EntityGroupConfigGUID = ( +select ParentEntityGroupConfigGuid +from fp.EntityGroupConfig ecg +inner join fp.BudgetConfig bc on bc.BudgetConfigGUID = ecg.BudgetConfigGUID and bc.IsMRTracking = 1 +where ecg.EntityGroupConfigID = @EntityGroupConfigID) +) + +IF @ParentEntityConfigID > 0 + + UPDATE + fs + SET + SampledBudget01 = fsb.AdjustedValue01, + SampledBudget02 = fsb.AdjustedValue02, + SampledBudget03 = fsb.AdjustedValue03, + SampledBudget04 = fsb.AdjustedValue04, + SampledBudget05 = fsb.AdjustedValue05, + SampledBudget06 = fsb.AdjustedValue06, + SampledBudget07 = fsb.AdjustedValue07, + SampledBudget08 = fsb.AdjustedValue08, + SampledBudget09 = fsb.AdjustedValue09, + SampledBudget10 = fsb.AdjustedValue10, + SampledBudget11 = fsb.AdjustedValue11, + SampledBudget12 = fsb.AdjustedValue12 + FROM + [fp].[FactStatistics] fs + INNER JOIN fp.[FactStatistics] fs_parent on fs.EntityGroupConfigID = @EntityGroupConfigID and fs_parent.EntityGroupConfigID = @ParentEntityConfigID + and fs.DepartmentID = fs_parent.DepartmentID + and fs.AccountID = fs_parent.AccountID + and fs.EntityID = fs_parent.EntityID + and fs.FinancialReportingID = fs_parent.FinancialReportingID + and fs.PayorID = fs_parent.PayorID + and fs.PatientClassID = fs_parent.PatientClassID + and fs.UnitTypeID = fs_parent.UnitTypeID + and fs.ProviderID = fs_parent.ProviderID + and fs.ProviderTypeID = fs_parent.ProviderTypeID + and fs.ProviderSpecialtyID = fs_parent.ProviderSpecialtyID + and fs.ProviderLineItemID = fs_parent.ProviderLineItemID + INNER JOIN fp.FactStatisticsBudget fsb on fsb.StatisticsID = fs_parent.StatisticsID and fsb.BudgetPhaseID = 3 +ELSE + -- set all of the values from the source fy/tc +BEGIN + DECLARE @IsProviderPlanningEnabled BIT; + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID; + + -- Non provider stats + UPDATE + fs + SET + SampledBudget01 = ISNULL(Month01, 0), + SampledBudget02 = ISNULL(Month02, 0), + SampledBudget03 = ISNULL(Month03, 0), + SampledBudget04 = ISNULL(Month04, 0), + SampledBudget05 = ISNULL(Month05, 0), + SampledBudget06 = ISNULL(Month06, 0), + SampledBudget07 = ISNULL(Month07, 0), + SampledBudget08 = ISNULL(Month08, 0), + SampledBudget09 = ISNULL(Month09, 0), + SampledBudget10 = ISNULL(Month10, 0), + SampledBudget11 = ISNULL(Month11, 0), + SampledBudget12 = ISNULL(Month12, 0) + FROM + [fp].[FactStatistics] fs + INNER JOIN + (SELECT stat.DepartmentID, stat.AccountID, fm.MonthColumnName, SUM(Value) as Value + FROM [int].[FactStatistic] stat + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID + INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID + WHERE stat.FiscalYearID = @SourceFiscalYearID AND stat.TimeclassID = @SourceTimeClassID AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + GROUP BY stat.DepartmentID, stat.AccountID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.AccountID = pv.AccountID + INNER JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND (fs.SubsectionID = 1 OR @IsProviderPlanningEnabled = 0) + + DECLARE @IsUsingSystemGeneratedStats BIT; + SELECT @IsUsingSystemGeneratedStats = IsUsingSystemGeneratedHistoricalStats FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID; + IF @IsUsingSystemGeneratedStats IS NULL BEGIN SET @IsUsingSystemGeneratedStats = 0 END + + IF(@IsUsingSystemGeneratedStats = 1) + BEGIN + IF OBJECT_ID('tempdb..#existingStats') IS NOT NULL DROP TABLE #existingStats + CREATE TABLE #existingStats (DepartmentID INT, AccountID INT, PatientClassID INT, FiscalMonthID INT) + + --Pull existing stats data so we know what not to touch + INSERT INTO #existingStats (DepartmentID, AccountID, PatientClassID, FiscalMonthID) + SELECT stat.DepartmentID, stat.AccountID, acc.PatientClassID, stat.FiscalMonthID + FROM int.FactStatistic stat + INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID + WHERE stat.IsDeleted = 0 + AND stat.FiscalMonthID != 0 + AND stat.FiscalYearID = @SourceFiscalYearID + AND stat.TimeClassID = @SourceTimeClassID + GROUP BY stat.DepartmentID, stat.AccountID, PatientClassID, stat.FiscalMonthID + + UPDATE fs SET + SampledBudget01 = ISNULL(Month01, SampledBudget01), + SampledBudget02 = ISNULL(Month02, SampledBudget02), + SampledBudget03 = ISNULL(Month03, SampledBudget03), + SampledBudget04 = ISNULL(Month04, SampledBudget04), + SampledBudget05 = ISNULL(Month05, SampledBudget05), + SampledBudget06 = ISNULL(Month06, SampledBudget06), + SampledBudget07 = ISNULL(Month07, SampledBudget07), + SampledBudget08 = ISNULL(Month08, SampledBudget08), + SampledBudget09 = ISNULL(Month09, SampledBudget09), + SampledBudget10 = ISNULL(Month10, SampledBudget10), + SampledBudget11 = ISNULL(Month11, SampledBudget11), + SampledBudget12 = ISNULL(Month12, SampledBudget12) + FROM + [fp].[FactStatistics] fs + INNER JOIN + (SELECT stat.DepartmentID, stat.AccountID, fm.MonthColumnName, SUM(Value) as Value, stat.PatientClassID + FROM + ( + SELECT stat.DepartmentID, stat.AccountID, acc.PatientClassID, stat.FiscalYearID, stat.FiscalMonthID, stat.Value + FROM fw.FactChargeBasedStatisticsMonthly stat + INNER JOIN fw.DimAccount acc ON stat.AccountID = acc.AccountID + WHERE stat.FiscalYearID = @SourceFiscalYearID and stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 + ) stat + + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID + + LEFT JOIN #existingStats intData + ON stat.DepartmentID = intData.DepartmentID + AND stat.AccountID = intData.AccountID + AND stat.FiscalMonthID = intData.FiscalMonthID + AND stat.PatientClassID = intData.PatientClassID + WHERE stat.FiscalYearID = @SourceFiscalYearID + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + AND intData.DepartmentID IS NULL + GROUP BY stat.DepartmentID, stat.AccountID, stat.PatientClassID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) + ) as pv + ON fs.DepartmentID = pv.DepartmentID AND fs.AccountID = pv.AccountID AND fs.PatientClassID = pv.PatientClassID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID = 0 AND fs.ProviderLineItemID = 0 + + + END + +IF @IsProviderPlanningEnabled = 1 BEGIN + + DECLARE @BudgetConfigID INT + SELECT @BudgetConfigID = BudgetConfigID FROM fp.EntityGroupConfig a INNER JOIN fp.BudgetConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID + + -- Update Provider Stats + + UPDATE + fs + SET + SampledBudget01 = ISNULL(Month01, 0), + SampledBudget02 = ISNULL(Month02, 0), + SampledBudget03 = ISNULL(Month03, 0), + SampledBudget04 = ISNULL(Month04, 0), + SampledBudget05 = ISNULL(Month05, 0), + SampledBudget06 = ISNULL(Month06, 0), + SampledBudget07 = ISNULL(Month07, 0), + SampledBudget08 = ISNULL(Month08, 0), + SampledBudget09 = ISNULL(Month09, 0), + SampledBudget10 = ISNULL(Month10, 0), + SampledBudget11 = ISNULL(Month11, 0), + SampledBudget12 = ISNULL(Month12, 0) + FROM [fp].[FactStatistics] fs + LEFT JOIN + (SELECT stat.DepartmentID, config.AccountID, fm.MonthColumnName, SUM(Value) as Value, stat.ProviderLineItemID, stat.PhysicianID as ProviderID + FROM [int].[FactProvider] stat + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = stat.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN fp.ProviderStatisticsConfig config on stat.ProviderLineItemID = config.ProviderLineItemID + INNER JOIN [fw].[DimAccount] acc on config.AccountID = acc.AccountID + WHERE stat.FiscalYearID = @SourceFiscalYearID AND stat.TimeclassID = @SourceTimeClassID AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + AND ps.Description = 'Statistics' AND BudgetConfigID = @BudgetConfigID + GROUP BY stat.DepartmentID, config.AccountID, fm.MonthColumnName, stat.ProviderLineItemID, stat.PhysicianID) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.AccountID = pv.AccountID + AND fs.ProviderID = pv.ProviderID + AND fs.ProviderLineItemID = pv.ProviderLineItemID + LEFT JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID <> 0 -- we will want to update this when we add the actual SubSection stuff + + END + + -- if the source fiscal year = current fiscal year and timeclass is actual, we need to annualize the data + IF(@IsAnnualized = 1 AND @MonthsLoaded < 12) + BEGIN + -- per stackoverflow (per MY) + DECLARE @IsLeapYear BIT = (CASE WHEN (@SourceFiscalYearID % 4 = 0 AND @SourceFiscalYearID % 100 <> 0) OR @SourceFiscalYearID % 400 = 0 THEN 1 ELSE 0 END) + DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded) + DECLARE @DaysInMonthsNotLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder > @MonthsLoaded) + + UPDATE fs + SET + -- not doing month 1 because it wouldn't really make sense to annualize without at least 1 month of actual data + SampledBudget02 = CASE WHEN @MonthsLoaded < 2 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget02 END, + SampledBudget03 = CASE WHEN @MonthsLoaded < 3 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget03 END, + SampledBudget04 = CASE WHEN @MonthsLoaded < 4 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget04 END, + SampledBudget05 = CASE WHEN @MonthsLoaded < 5 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget05 END, + SampledBudget06 = CASE WHEN @MonthsLoaded < 6 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget06 END, + SampledBudget07 = CASE WHEN @MonthsLoaded < 7 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget07 END, + SampledBudget08 = CASE WHEN @MonthsLoaded < 8 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget08 END, + SampledBudget09 = CASE WHEN @MonthsLoaded < 9 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget09 END, + SampledBudget10 = CASE WHEN @MonthsLoaded < 10 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget10 END, + SampledBudget11 = CASE WHEN @MonthsLoaded < 11 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget11 END, + SampledBudget12 = CASE WHEN @MonthsLoaded < 12 THEN ((SampledBudgetTotal/@DaysInMonthsLoaded) * @DaysInMonthsNotLoaded) / (12 - @MonthsLoaded) ELSE SampledBudget12 END + FROM [fp].[FactStatistics] fs + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + + END + END + + -- update the initial values to be equal to the sampled values on the dimensionality table + UPDATE + fs + SET + InitialBudget01 = SampledBudgetTotal / 12, + InitialBudget02 = SampledBudgetTotal / 12, + InitialBudget03 = SampledBudgetTotal / 12, + InitialBudget04 = SampledBudgetTotal / 12, + InitialBudget05 = SampledBudgetTotal / 12, + InitialBudget06 = SampledBudgetTotal / 12, + InitialBudget07 = SampledBudgetTotal / 12, + InitialBudget08 = SampledBudgetTotal / 12, + InitialBudget09 = SampledBudgetTotal / 12, + InitialBudget10 = SampledBudgetTotal / 12, + InitialBudget11 = SampledBudgetTotal / 12, + InitialBudget12 = SampledBudgetTotal - ((SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12)) + FROM [fp].[FactStatistics] fs + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID +END +GO + + +--------------------------------------------- + +-- fp.procSampleStatsOriginalBudgetVolume_WithNewAnnualization +CREATE PROCEDURE [fp].[procSampleStatsOriginalBudgetVolume_WithNewAnnualization] + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @SourceFiscalYearID smallint, + @SourceTimeClassID tinyint, + @MonthsLoaded int +AS +BEGIN + +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-05-06 Created +** 2 2018-11-05 OV B-20952 Add new budget config sampling sources (Statistics only) +** 3 2018-11-07 BK B-21035 Spread InitialValue evenly across months +** 4 2020-10-27 BK JAZZ-2905 Add provider data +** 5 2021-04-21 BK JAZZ-18500 Fix subsection +** 6 2022-02-17 MD JAZZ-33345 Add code to handle projection of system generated stats +** 7 2022-03-08 NT JAZZ-34087 Add FiscalMonthID in the JOIN when generating charge based stats +** 8 2022-04-04 BK JAZZ-35385 Add Patient Type to join for Charge-Based stats sampling +** 9 2022-06-09 AO JAZZ-32943 Replaced INNER JOIN to LEFT, to set value to 0 if it isn't exist in int.FactProvider, but it is in fp.FactStatistics +** 10 2023-07-15 BK JAZZ-35385 Add Patient Type to join for Charge-Based stats sampling +** 11 2023-07-14 BK JAZZ-56315 If using provider do not use overwrite with System Generate Stats +** 12 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config +** 13 2024-07-24 BK JAZZ-74600 Change Annualization to use daily 'rate' +***************************************************************/ + +DECLARE @IsAnnualized bit = (CASE WHEN @SourceFiscalYearID = @CurrentFiscalYearID AND @SourceTimeClassID = 1 THEN 1 ELSE 0 END) + + +declare @ParentEntityConfigID int = ( +select EntityGroupConfigID +from fp.EntityGroupConfig +where EntityGroupConfigGUID = ( +select ParentEntityGroupConfigGuid +from fp.EntityGroupConfig ecg +inner join fp.BudgetConfig bc on bc.BudgetConfigGUID = ecg.BudgetConfigGUID and bc.IsMRTracking = 1 +where ecg.EntityGroupConfigID = @EntityGroupConfigID) +) + +IF @ParentEntityConfigID > 0 + + UPDATE + fs + SET + SampledBudget01 = fsb.AdjustedValue01, + SampledBudget02 = fsb.AdjustedValue02, + SampledBudget03 = fsb.AdjustedValue03, + SampledBudget04 = fsb.AdjustedValue04, + SampledBudget05 = fsb.AdjustedValue05, + SampledBudget06 = fsb.AdjustedValue06, + SampledBudget07 = fsb.AdjustedValue07, + SampledBudget08 = fsb.AdjustedValue08, + SampledBudget09 = fsb.AdjustedValue09, + SampledBudget10 = fsb.AdjustedValue10, + SampledBudget11 = fsb.AdjustedValue11, + SampledBudget12 = fsb.AdjustedValue12 + FROM + [fp].[FactStatistics] fs + INNER JOIN fp.[FactStatistics] fs_parent on fs.EntityGroupConfigID = @EntityGroupConfigID and fs_parent.EntityGroupConfigID = @ParentEntityConfigID + and fs.DepartmentID = fs_parent.DepartmentID + and fs.AccountID = fs_parent.AccountID + and fs.EntityID = fs_parent.EntityID + and fs.FinancialReportingID = fs_parent.FinancialReportingID + and fs.PayorID = fs_parent.PayorID + and fs.PatientClassID = fs_parent.PatientClassID + and fs.UnitTypeID = fs_parent.UnitTypeID + and fs.ProviderID = fs_parent.ProviderID + and fs.ProviderTypeID = fs_parent.ProviderTypeID + and fs.ProviderSpecialtyID = fs_parent.ProviderSpecialtyID + and fs.ProviderLineItemID = fs_parent.ProviderLineItemID + INNER JOIN fp.FactStatisticsBudget fsb on fsb.StatisticsID = fs_parent.StatisticsID and fsb.BudgetPhaseID = 3 +ELSE + -- set all of the values from the source fy/tc +BEGIN + DECLARE @IsProviderPlanningEnabled BIT; + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID; + + -- Non provider stats + UPDATE + fs + SET + SampledBudget01 = ISNULL(Month01, 0), + SampledBudget02 = ISNULL(Month02, 0), + SampledBudget03 = ISNULL(Month03, 0), + SampledBudget04 = ISNULL(Month04, 0), + SampledBudget05 = ISNULL(Month05, 0), + SampledBudget06 = ISNULL(Month06, 0), + SampledBudget07 = ISNULL(Month07, 0), + SampledBudget08 = ISNULL(Month08, 0), + SampledBudget09 = ISNULL(Month09, 0), + SampledBudget10 = ISNULL(Month10, 0), + SampledBudget11 = ISNULL(Month11, 0), + SampledBudget12 = ISNULL(Month12, 0) + FROM + [fp].[FactStatistics] fs + INNER JOIN + (SELECT stat.DepartmentID, stat.AccountID, fm.MonthColumnName, SUM(Value) as Value + FROM [int].[FactStatistic] stat + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID + INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID + WHERE stat.FiscalYearID = @SourceFiscalYearID AND stat.TimeclassID = @SourceTimeClassID AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + GROUP BY stat.DepartmentID, stat.AccountID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.AccountID = pv.AccountID + INNER JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND (fs.SubsectionID = 1 OR @IsProviderPlanningEnabled = 0) + + DECLARE @IsUsingSystemGeneratedStats BIT; + SELECT @IsUsingSystemGeneratedStats = IsUsingSystemGeneratedHistoricalStats FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID; + IF @IsUsingSystemGeneratedStats IS NULL BEGIN SET @IsUsingSystemGeneratedStats = 0 END + + IF(@IsUsingSystemGeneratedStats = 1) + BEGIN + IF OBJECT_ID('tempdb..#existingStats') IS NOT NULL DROP TABLE #existingStats + CREATE TABLE #existingStats (DepartmentID INT, AccountID INT, PatientClassID INT, FiscalMonthID INT) + + --Pull existing stats data so we know what not to touch + INSERT INTO #existingStats (DepartmentID, AccountID, PatientClassID, FiscalMonthID) + SELECT stat.DepartmentID, stat.AccountID, acc.PatientClassID, stat.FiscalMonthID + FROM int.FactStatistic stat + INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID + WHERE stat.IsDeleted = 0 + AND stat.FiscalMonthID != 0 + AND stat.FiscalYearID = @SourceFiscalYearID + AND stat.TimeClassID = @SourceTimeClassID + GROUP BY stat.DepartmentID, stat.AccountID, PatientClassID, stat.FiscalMonthID + + UPDATE fs SET + SampledBudget01 = ISNULL(Month01, SampledBudget01), + SampledBudget02 = ISNULL(Month02, SampledBudget02), + SampledBudget03 = ISNULL(Month03, SampledBudget03), + SampledBudget04 = ISNULL(Month04, SampledBudget04), + SampledBudget05 = ISNULL(Month05, SampledBudget05), + SampledBudget06 = ISNULL(Month06, SampledBudget06), + SampledBudget07 = ISNULL(Month07, SampledBudget07), + SampledBudget08 = ISNULL(Month08, SampledBudget08), + SampledBudget09 = ISNULL(Month09, SampledBudget09), + SampledBudget10 = ISNULL(Month10, SampledBudget10), + SampledBudget11 = ISNULL(Month11, SampledBudget11), + SampledBudget12 = ISNULL(Month12, SampledBudget12) + FROM + [fp].[FactStatistics] fs + INNER JOIN + (SELECT stat.DepartmentID, stat.AccountID, fm.MonthColumnName, SUM(Value) as Value, stat.PatientClassID + FROM + ( + SELECT stat.DepartmentID, stat.AccountID, acc.PatientClassID, stat.FiscalYearID, stat.FiscalMonthID, stat.Value + FROM fw.FactChargeBasedStatisticsMonthly stat + INNER JOIN fw.DimAccount acc ON stat.AccountID = acc.AccountID + WHERE stat.FiscalYearID = @SourceFiscalYearID and stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 + ) stat + + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID + + LEFT JOIN #existingStats intData + ON stat.DepartmentID = intData.DepartmentID + AND stat.AccountID = intData.AccountID + AND stat.FiscalMonthID = intData.FiscalMonthID + AND stat.PatientClassID = intData.PatientClassID + WHERE stat.FiscalYearID = @SourceFiscalYearID + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + AND intData.DepartmentID IS NULL + GROUP BY stat.DepartmentID, stat.AccountID, stat.PatientClassID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) + ) as pv + ON fs.DepartmentID = pv.DepartmentID AND fs.AccountID = pv.AccountID AND fs.PatientClassID = pv.PatientClassID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID = 0 AND fs.ProviderLineItemID = 0 + + + END + +IF @IsProviderPlanningEnabled = 1 BEGIN + + DECLARE @BudgetConfigID INT + SELECT @BudgetConfigID = BudgetConfigID FROM fp.EntityGroupConfig a INNER JOIN fp.BudgetConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID + + -- Update Provider Stats + + UPDATE + fs + SET + SampledBudget01 = ISNULL(Month01, 0), + SampledBudget02 = ISNULL(Month02, 0), + SampledBudget03 = ISNULL(Month03, 0), + SampledBudget04 = ISNULL(Month04, 0), + SampledBudget05 = ISNULL(Month05, 0), + SampledBudget06 = ISNULL(Month06, 0), + SampledBudget07 = ISNULL(Month07, 0), + SampledBudget08 = ISNULL(Month08, 0), + SampledBudget09 = ISNULL(Month09, 0), + SampledBudget10 = ISNULL(Month10, 0), + SampledBudget11 = ISNULL(Month11, 0), + SampledBudget12 = ISNULL(Month12, 0) + FROM [fp].[FactStatistics] fs + LEFT JOIN + (SELECT stat.DepartmentID, config.AccountID, fm.MonthColumnName, SUM(Value) as Value, stat.ProviderLineItemID, stat.PhysicianID as ProviderID + FROM [int].[FactProvider] stat + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = stat.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN fp.ProviderStatisticsConfig config on stat.ProviderLineItemID = config.ProviderLineItemID + INNER JOIN [fw].[DimAccount] acc on config.AccountID = acc.AccountID + WHERE stat.FiscalYearID = @SourceFiscalYearID AND stat.TimeclassID = @SourceTimeClassID AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + AND ps.Description = 'Statistics' AND BudgetConfigID = @BudgetConfigID + GROUP BY stat.DepartmentID, config.AccountID, fm.MonthColumnName, stat.ProviderLineItemID, stat.PhysicianID) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.AccountID = pv.AccountID + AND fs.ProviderID = pv.ProviderID + AND fs.ProviderLineItemID = pv.ProviderLineItemID + LEFT JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID <> 0 -- we will want to update this when we add the actual SubSection stuff + + END + + -- if the source fiscal year = current fiscal year and timeclass is actual, we need to annualize the data + IF(@IsAnnualized = 1 AND @MonthsLoaded < 12) + BEGIN + -- per stackoverflow (per MY) + DECLARE @IsLeapYear BIT = (CASE WHEN (@SourceFiscalYearID % 4 = 0 AND @SourceFiscalYearID % 100 <> 0) OR @SourceFiscalYearID % 400 = 0 THEN 1 ELSE 0 END) + DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded) + DECLARE @DaysInMonthsNotLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder > @MonthsLoaded) + DECLARE @IsBudgetLeapYear BIT = (CASE WHEN ((@CurrentFiscalYearID + 1) % 4 = 0 AND (@CurrentFiscalYearID + 1) % 100 <> 0) OR (@CurrentFiscalYearID + 1) % 400 = 0 THEN 1 ELSE 0 END) + DECLARE @DaysBudgetYear decimal = (SELECT (CASE WHEN @IsBudgetLeapYear = 1 THEN YTDDaysInLeapYearMonth ELSE YTDDaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder = 12) + + UPDATE fs + SET + SampledBudget01 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget02 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget03 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget04 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget05 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget06 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget07 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget08 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget09 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget10 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget11 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + SampledBudget12 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget01 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget02 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget03 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget04 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget05 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget06 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget07 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget08 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget09 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget10 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget11 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12, + InitialBudget12 = ((SampledBudgetTotal / @DaysInMonthsLoaded) * @DaysBudgetYear) / 12 + FROM [fp].[FactStatistics] fs + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + + END + ELSE BEGIN + -- update the initial values to be equal to the sampled values on the dimensionality table + UPDATE + fs + SET + InitialBudget01 = SampledBudgetTotal / 12, + InitialBudget02 = SampledBudgetTotal / 12, + InitialBudget03 = SampledBudgetTotal / 12, + InitialBudget04 = SampledBudgetTotal / 12, + InitialBudget05 = SampledBudgetTotal / 12, + InitialBudget06 = SampledBudgetTotal / 12, + InitialBudget07 = SampledBudgetTotal / 12, + InitialBudget08 = SampledBudgetTotal / 12, + InitialBudget09 = SampledBudgetTotal / 12, + InitialBudget10 = SampledBudgetTotal / 12, + InitialBudget11 = SampledBudgetTotal / 12, + InitialBudget12 = SampledBudgetTotal - ((SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12) + (SampledBudgetTotal / 12)) + FROM [fp].[FactStatistics] fs + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + END + END +END +GO + + +--------------------------------------------- + +-- fp.procSampleStatsOriginalProjectionVolume +CREATE PROCEDURE [fp].[procSampleStatsOriginalProjectionVolume] + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @MonthsLoaded int +AS +BEGIN + +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2012-02-17 MD JAZZ-33345 Move system generated stats sql to before copying of baseline to initial projection +** 2 2022-03-09 NT JAZZ-34087 Add FiscalMonthID in the JOIN when generating charge based stats +** 3 2022-04-04 BK JAZZ-35385 Add Patient Type to join for Charge-Based stats sampling +** 4 2022-06-09 AO JAZZ-32943 Replaced INNER JOIN to LEFT, to set value to 0 if it isn't exist in int.FactProvider, but it is in fp.FactStatistics +** 5 2023-07-13 BK JAZZ-56315 If using provider do not use overwrite with System Generate Stats +** 6 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config +***************************************************************/ + + IF OBJECT_ID('tempdb..#Totals') IS NOT NULL DROP TABLE #Totals + + DECLARE @IsProviderPlanningEnabled BIT; + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID; + + DECLARE @IsUsingSystemGeneratedStats BIT; + SELECT @IsUsingSystemGeneratedStats = IsUsingSystemGeneratedHistoricalStats FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID; + + -- set the orig values for the months where we have data (month sort order <= @MonthsLoaded) + UPDATE + fs + SET + SampledProjection01 = ISNULL(Month01, 0), + SampledProjection02 = ISNULL(Month02, 0), + SampledProjection03 = ISNULL(Month03, 0), + SampledProjection04 = ISNULL(Month04, 0), + SampledProjection05 = ISNULL(Month05, 0), + SampledProjection06 = ISNULL(Month06, 0), + SampledProjection07 = ISNULL(Month07, 0), + SampledProjection08 = ISNULL(Month08, 0), + SampledProjection09 = ISNULL(Month09, 0), + SampledProjection10 = ISNULL(Month10, 0), + SampledProjection11 = ISNULL(Month11, 0), + SampledProjection12 = ISNULL(Month12, 0) + FROM + [fp].[FactStatistics] fs + INNER JOIN + (SELECT stat.DepartmentID, stat.AccountID, fm.MonthColumnName, SUM(Value) as Value + FROM [int].[FactStatistic] stat + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID + INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID + WHERE stat.FiscalYearID = @CurrentFiscalYearID AND stat.TimeclassID = 1 AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded + GROUP BY stat.DepartmentID, stat.AccountID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.AccountID = pv.AccountID + INNER JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND (fs.SubsectionID = 1 OR @IsProviderPlanningEnabled = 0) + + IF @IsProviderPlanningEnabled = 1 BEGIN + DECLARE @BudgetConfigID INT + SELECT @BudgetConfigID = BudgetConfigID FROM fp.EntityGroupConfig a INNER JOIN fp.BudgetConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID + + -- Update Provider Stats + UPDATE + fs + SET + SampledProjection01 = ISNULL(Month01, 0), + SampledProjection02 = ISNULL(Month02, 0), + SampledProjection03 = ISNULL(Month03, 0), + SampledProjection04 = ISNULL(Month04, 0), + SampledProjection05 = ISNULL(Month05, 0), + SampledProjection06 = ISNULL(Month06, 0), + SampledProjection07 = ISNULL(Month07, 0), + SampledProjection08 = ISNULL(Month08, 0), + SampledProjection09 = ISNULL(Month09, 0), + SampledProjection10 = ISNULL(Month10, 0), + SampledProjection11 = ISNULL(Month11, 0), + SampledProjection12 = ISNULL(Month12, 0) + FROM [fp].[FactStatistics] fs + LEFT JOIN + (SELECT stat.DepartmentID, config.AccountID, fm.MonthColumnName, SUM(Value) as Value, stat.ProviderLineItemID, stat.PhysicianID as ProviderID + FROM [int].[FactProvider] stat + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = stat.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN fp.ProviderStatisticsConfig config on stat.ProviderLineItemID = config.ProviderLineItemID + INNER JOIN [fw].[DimAccount] acc on config.AccountID = acc.AccountID + WHERE stat.FiscalYearID = @CurrentFiscalYearID AND stat.TimeclassID = 1 AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded + AND ps.Description = 'Statistics' AND BudgetConfigID = @BudgetConfigID + GROUP BY stat.DepartmentID, config.AccountID, fm.MonthColumnName, stat.ProviderLineItemID, stat.PhysicianID) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.AccountID = pv.AccountID + AND fs.ProviderID = pv.ProviderID + AND fs.ProviderLineItemID = pv.ProviderLineItemID + LEFT JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID <> 0 -- as long as we haven't updated the driver/dependent SubsectionID yet this should be fine + + END + + -- We do not want to annualize projection from fw.FactChargeBasedStatisticsMonthly, months not loaded should be crosswalked from ChargeVolumes + IF(@IsUsingSystemGeneratedStats = 1) + BEGIN + IF OBJECT_ID('tempdb..#existingStats') IS NOT NULL DROP TABLE #existingStats + CREATE TABLE #existingStats (DepartmentID INT, AccountID INT, PatientClassID INT, FiscalMonthID INT) + + --Pull existing stats data so we know what not to touch + INSERT INTO #existingStats (DepartmentID, AccountID, PatientClassID, FiscalMonthID) + SELECT stat.DepartmentID, stat.AccountID, acc.PatientClassID, stat.FiscalMonthID + FROM int.FactStatistic stat + INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID + WHERE stat.IsDeleted = 0 + AND stat.FiscalMonthID != 0 + AND stat.FiscalYearID = @CurrentFiscalYearID + AND stat.TimeClassID = 1 + GROUP BY stat.DepartmentID, stat.AccountID, PatientClassID, stat.FiscalMonthID + + UPDATE fs SET + SampledProjection01 = ISNULL(Month01, SampledProjection01), + SampledProjection02 = ISNULL(Month02, SampledProjection02), + SampledProjection03 = ISNULL(Month03, SampledProjection03), + SampledProjection04 = ISNULL(Month04, SampledProjection04), + SampledProjection05 = ISNULL(Month05, SampledProjection05), + SampledProjection06 = ISNULL(Month06, SampledProjection06), + SampledProjection07 = ISNULL(Month07, SampledProjection07), + SampledProjection08 = ISNULL(Month08, SampledProjection08), + SampledProjection09 = ISNULL(Month09, SampledProjection09), + SampledProjection10 = ISNULL(Month10, SampledProjection10), + SampledProjection11 = ISNULL(Month11, SampledProjection11), + SampledProjection12 = ISNULL(Month12, SampledProjection12) + FROM + [fp].[FactStatistics] fs + INNER JOIN + (SELECT stat.DepartmentID, stat.AccountID, stat.PatientClassID, fm.MonthColumnName, SUM(Value) as Value + FROM + ( + + SELECT stat.DepartmentID, stat.AccountID, acc.PatientClassID, stat.FiscalYearID, stat.FiscalMonthID, stat.Value + FROM fw.FactChargeBasedStatisticsMonthly stat + INNER JOIN fw.DimAccount acc ON stat.AccountID = acc.AccountID + WHERE stat.FiscalYearID = @CurrentFiscalYearID and stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 + + ) stat + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID + LEFT JOIN #existingStats intData + ON stat.DepartmentID = intData.DepartmentID + AND stat.AccountID = intData.AccountID + AND stat.FiscalMonthID = intData.FiscalMonthID + AND stat.PatientClassID = intData.PatientClassID + WHERE stat.FiscalYearID = @CurrentFiscalYearID + AND fm.SortOrder <= @MonthsLoaded + AND intData.DepartmentID IS NULL + GROUP BY stat.DepartmentID, stat.AccountID, stat.PatientClassID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) + ) as pv + ON fs.DepartmentID = pv.DepartmentID AND fs.AccountID = pv.AccountID AND fs.PatientClassID = pv.PatientClassID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID = 0 AND fs.ProviderLineItemID = 0 + + + END + + -- copy the baseline data over for months without data (month sort order > @MonthsLoaded) + -- if the baseline is current year actual YTD, then the data would already have been annualized, if not, then we don't need to annualize + UPDATE + fs + SET + SampledProjection02 = CASE WHEN @MonthsLoaded < 2 THEN SampledBudget02 ELSE SampledProjection02 END, + SampledProjection03 = CASE WHEN @MonthsLoaded < 3 THEN SampledBudget03 ELSE SampledProjection03 END, + SampledProjection04 = CASE WHEN @MonthsLoaded < 4 THEN SampledBudget04 ELSE SampledProjection04 END, + SampledProjection05 = CASE WHEN @MonthsLoaded < 5 THEN SampledBudget05 ELSE SampledProjection05 END, + SampledProjection06 = CASE WHEN @MonthsLoaded < 6 THEN SampledBudget06 ELSE SampledProjection06 END, + SampledProjection07 = CASE WHEN @MonthsLoaded < 7 THEN SampledBudget07 ELSE SampledProjection07 END, + SampledProjection08 = CASE WHEN @MonthsLoaded < 8 THEN SampledBudget08 ELSE SampledProjection08 END, + SampledProjection09 = CASE WHEN @MonthsLoaded < 9 THEN SampledBudget09 ELSE SampledProjection09 END, + SampledProjection10 = CASE WHEN @MonthsLoaded < 10 THEN SampledBudget10 ELSE SampledProjection10 END, + SampledProjection11 = CASE WHEN @MonthsLoaded < 11 THEN SampledBudget11 ELSE SampledProjection11 END, + SampledProjection12 = CASE WHEN @MonthsLoaded < 12 THEN SampledBudget12 ELSE SampledProjection12 END + FROM + [fp].[FactStatistics] fs + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID + + + + CREATE TABLE #Totals (StatisticsID INT, SampledProjectionTotal DECIMAL(19,8), NewValue DECIMAL(19,8)) + + INSERT INTO #Totals (StatisticsID, SampledProjectionTotal) + SELECT StatisticsID, + CASE WHEN @MonthsLoaded = 11 THEN stat.SampledProjection12 + WHEN @MonthsLoaded = 10 THEN stat.SampledProjection11 + stat.SampledProjection12 + WHEN @MonthsLoaded = 9 THEN stat.SampledProjection10 + stat.SampledProjection11 + stat.SampledProjection12 + WHEN @MonthsLoaded = 8 THEN stat.SampledProjection09 + stat.SampledProjection10 + stat.SampledProjection11 + stat.SampledProjection12 + WHEN @MonthsLoaded = 7 THEN stat.SampledProjection08 + stat.SampledProjection09 + stat.SampledProjection10 + stat.SampledProjection11 + stat.SampledProjection12 + WHEN @MonthsLoaded = 6 THEN stat.SampledProjection07 + stat.SampledProjection08 + stat.SampledProjection09 + stat.SampledProjection10 + stat.SampledProjection11 + stat.SampledProjection12 + WHEN @MonthsLoaded = 5 THEN stat.SampledProjection06 + stat.SampledProjection07 + stat.SampledProjection08 + stat.SampledProjection09 + stat.SampledProjection10 + stat.SampledProjection11 + stat.SampledProjection12 + WHEN @MonthsLoaded = 4 THEN stat.SampledProjection05 + stat.SampledProjection06 + stat.SampledProjection07 + stat.SampledProjection08 + stat.SampledProjection09 + stat.SampledProjection10 + stat.SampledProjection11 + stat.SampledProjection12 + WHEN @MonthsLoaded = 3 THEN stat.SampledProjection04 + stat.SampledProjection05 + stat.SampledProjection06 + stat.SampledProjection07 + stat.SampledProjection08 + stat.SampledProjection09 + stat.SampledProjection10 + stat.SampledProjection11 + stat.SampledProjection12 + WHEN @MonthsLoaded = 2 THEN stat.SampledProjection03 + stat.SampledProjection04 + stat.SampledProjection05 + stat.SampledProjection06 + stat.SampledProjection07 + stat.SampledProjection08 + stat.SampledProjection09 + stat.SampledProjection10 + stat.SampledProjection11 + stat.SampledProjection12 + WHEN @MonthsLoaded = 1 THEN stat.SampledProjection02 + stat.SampledProjection03 + stat.SampledProjection04 + stat.SampledProjection05 + stat.SampledProjection06 + stat.SampledProjection07 + stat.SampledProjection08 + stat.SampledProjection09 + stat.SampledProjection10 + stat.SampledProjection11 + stat.SampledProjection12 + ELSE 0 + END + FROM [fp].[FactStatistics] stat + WHERE stat.EntityGroupConfigID = @EntityGroupConfigID + + UPDATE a SET NewValue = SampledProjectionTotal / (12.0 - @MonthsLoaded) FROM #Totals a + + UPDATE + fs + SET + InitialProjection01 = CASE WHEN @MonthsLoaded >= 1 THEN fs.SampledProjection01 ELSE t.NewValue END, + InitialProjection02 = CASE WHEN @MonthsLoaded >= 2 THEN fs.SampledProjection02 ELSE t.NewValue END, + InitialProjection03 = CASE WHEN @MonthsLoaded >= 3 THEN fs.SampledProjection03 ELSE t.NewValue END, + InitialProjection04 = CASE WHEN @MonthsLoaded >= 4 THEN fs.SampledProjection04 ELSE t.NewValue END, + InitialProjection05 = CASE WHEN @MonthsLoaded >= 5 THEN fs.SampledProjection05 ELSE t.NewValue END, + InitialProjection06 = CASE WHEN @MonthsLoaded >= 6 THEN fs.SampledProjection06 ELSE t.NewValue END, + InitialProjection07 = CASE WHEN @MonthsLoaded >= 7 THEN fs.SampledProjection07 ELSE t.NewValue END, + InitialProjection08 = CASE WHEN @MonthsLoaded >= 8 THEN fs.SampledProjection08 ELSE t.NewValue END, + InitialProjection09 = CASE WHEN @MonthsLoaded >= 9 THEN fs.SampledProjection09 ELSE t.NewValue END, + InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.SampledProjection10 ELSE t.NewValue END, + InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.SampledProjection11 ELSE t.NewValue END, + InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.SampledProjection12 ELSE t.NewValue END + FROM [fp].[FactStatistics] fs INNER JOIN #Totals t on fs.StatisticsID = t.StatisticsID + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + + + +END +GO + + +--------------------------------------------- + +-- fp.procSampleStatsOriginalProjectionVolume_WithNewAnnualization +CREATE PROCEDURE [fp].[procSampleStatsOriginalProjectionVolume_WithNewAnnualization] + @EntityGroupConfigID int, + @CurrentFiscalYearID smallint, + @MonthsLoaded int +AS +BEGIN + +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2012-02-17 MD JAZZ-33345 Move system generated stats sql to before copying of baseline to initial projection +** 2 2022-03-09 NT JAZZ-34087 Add FiscalMonthID in the JOIN when generating charge based stats +** 3 2022-04-04 BK JAZZ-35385 Add Patient Type to join for Charge-Based stats sampling +** 4 2022-06-09 AO JAZZ-32943 Replaced INNER JOIN to LEFT, to set value to 0 if it isn't exist in int.FactProvider, but it is in fp.FactStatistics +** 5 2023-07-13 BK JAZZ-56315 If using provider do not use overwrite with System Generate Stats +** 6 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config +** 7 2024-07-24 BK JAZZ-74600 Update annualization logic to use daily 'rate' +** 8 2024-08-07 BK JAZZ-75213 Add check if using annualization +***************************************************************/ + + IF OBJECT_ID('tempdb..#Totals') IS NOT NULL DROP TABLE #Totals + + DECLARE @IsProviderPlanningEnabled BIT; + SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID; + + DECLARE @IsUsingSystemGeneratedStats BIT; + SELECT @IsUsingSystemGeneratedStats = IsUsingSystemGeneratedHistoricalStats FROM fp.BudgetConfig bc INNER JOIN fp.EntityGroupConfig egc on bc.BudgetConfigGUID = egc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID; + + -- set the orig values for the months where we have data (month sort order <= @MonthsLoaded) + UPDATE + fs + SET + SampledProjection01 = ISNULL(Month01, 0), + SampledProjection02 = ISNULL(Month02, 0), + SampledProjection03 = ISNULL(Month03, 0), + SampledProjection04 = ISNULL(Month04, 0), + SampledProjection05 = ISNULL(Month05, 0), + SampledProjection06 = ISNULL(Month06, 0), + SampledProjection07 = ISNULL(Month07, 0), + SampledProjection08 = ISNULL(Month08, 0), + SampledProjection09 = ISNULL(Month09, 0), + SampledProjection10 = ISNULL(Month10, 0), + SampledProjection11 = ISNULL(Month11, 0), + SampledProjection12 = ISNULL(Month12, 0) + FROM + [fp].[FactStatistics] fs + INNER JOIN + (SELECT stat.DepartmentID, stat.AccountID, fm.MonthColumnName, SUM(Value) as Value + FROM [int].[FactStatistic] stat + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID + INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID + WHERE stat.FiscalYearID = @CurrentFiscalYearID AND stat.TimeclassID = 1 AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded + GROUP BY stat.DepartmentID, stat.AccountID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.AccountID = pv.AccountID + INNER JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND (fs.SubsectionID = 1 OR @IsProviderPlanningEnabled = 0) + + IF @IsProviderPlanningEnabled = 1 BEGIN + DECLARE @BudgetConfigID INT + SELECT @BudgetConfigID = BudgetConfigID FROM fp.EntityGroupConfig a INNER JOIN fp.BudgetConfig b on a.BudgetConfigGUID = b.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID + + -- Update Provider Stats + UPDATE + fs + SET + SampledProjection01 = ISNULL(Month01, 0), + SampledProjection02 = ISNULL(Month02, 0), + SampledProjection03 = ISNULL(Month03, 0), + SampledProjection04 = ISNULL(Month04, 0), + SampledProjection05 = ISNULL(Month05, 0), + SampledProjection06 = ISNULL(Month06, 0), + SampledProjection07 = ISNULL(Month07, 0), + SampledProjection08 = ISNULL(Month08, 0), + SampledProjection09 = ISNULL(Month09, 0), + SampledProjection10 = ISNULL(Month10, 0), + SampledProjection11 = ISNULL(Month11, 0), + SampledProjection12 = ISNULL(Month12, 0) + FROM [fp].[FactStatistics] fs + LEFT JOIN + (SELECT stat.DepartmentID, config.AccountID, fm.MonthColumnName, SUM(Value) as Value, stat.ProviderLineItemID, stat.PhysicianID as ProviderID + FROM [int].[FactProvider] stat + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID + INNER JOIN fp.ProviderLineItem pli on pli.ProviderLineItemID = stat.ProviderLineItemID + INNER JOIN fp.PlanSection ps on pli.PlanSectionID = ps.PlanSectionID + INNER JOIN fp.ProviderStatisticsConfig config on stat.ProviderLineItemID = config.ProviderLineItemID + INNER JOIN [fw].[DimAccount] acc on config.AccountID = acc.AccountID + WHERE stat.FiscalYearID = @CurrentFiscalYearID AND stat.TimeclassID = 1 AND stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 AND fm.SortOrder <= @MonthsLoaded + AND ps.Description = 'Statistics' AND BudgetConfigID = @BudgetConfigID + GROUP BY stat.DepartmentID, config.AccountID, fm.MonthColumnName, stat.ProviderLineItemID, stat.PhysicianID) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv + ON fs.DepartmentID = pv.DepartmentID + AND fs.AccountID = pv.AccountID + AND fs.ProviderID = pv.ProviderID + AND fs.ProviderLineItemID = pv.ProviderLineItemID + LEFT JOIN [fw].[DimDepartment] dept ON pv.DepartmentID = dept.DepartmentID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID <> 0 -- as long as we haven't updated the driver/dependent SubsectionID yet this should be fine + + END + + -- We do not want to annualize projection from fw.FactChargeBasedStatisticsMonthly, months not loaded should be crosswalked from ChargeVolumes + IF(@IsUsingSystemGeneratedStats = 1) + BEGIN + IF OBJECT_ID('tempdb..#existingStats') IS NOT NULL DROP TABLE #existingStats + CREATE TABLE #existingStats (DepartmentID INT, AccountID INT, PatientClassID INT, FiscalMonthID INT) + + --Pull existing stats data so we know what not to touch + INSERT INTO #existingStats (DepartmentID, AccountID, PatientClassID, FiscalMonthID) + SELECT stat.DepartmentID, stat.AccountID, acc.PatientClassID, stat.FiscalMonthID + FROM int.FactStatistic stat + INNER JOIN [fw].[DimAccount] acc on acc.AccountID = stat.AccountID + WHERE stat.IsDeleted = 0 + AND stat.FiscalMonthID != 0 + AND stat.FiscalYearID = @CurrentFiscalYearID + AND stat.TimeClassID = 1 + GROUP BY stat.DepartmentID, stat.AccountID, PatientClassID, stat.FiscalMonthID + + UPDATE fs SET + SampledProjection01 = ISNULL(Month01, SampledProjection01), + SampledProjection02 = ISNULL(Month02, SampledProjection02), + SampledProjection03 = ISNULL(Month03, SampledProjection03), + SampledProjection04 = ISNULL(Month04, SampledProjection04), + SampledProjection05 = ISNULL(Month05, SampledProjection05), + SampledProjection06 = ISNULL(Month06, SampledProjection06), + SampledProjection07 = ISNULL(Month07, SampledProjection07), + SampledProjection08 = ISNULL(Month08, SampledProjection08), + SampledProjection09 = ISNULL(Month09, SampledProjection09), + SampledProjection10 = ISNULL(Month10, SampledProjection10), + SampledProjection11 = ISNULL(Month11, SampledProjection11), + SampledProjection12 = ISNULL(Month12, SampledProjection12) + FROM + [fp].[FactStatistics] fs + INNER JOIN + (SELECT stat.DepartmentID, stat.AccountID, stat.PatientClassID, fm.MonthColumnName, SUM(Value) as Value + FROM + ( + + SELECT stat.DepartmentID, stat.AccountID, acc.PatientClassID, stat.FiscalYearID, stat.FiscalMonthID, stat.Value + FROM fw.FactChargeBasedStatisticsMonthly stat + INNER JOIN fw.DimAccount acc ON stat.AccountID = acc.AccountID + WHERE stat.FiscalYearID = @CurrentFiscalYearID and stat.IsDeleted = 0 AND stat.FiscalMonthID != 0 + + ) stat + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = stat.FiscalMonthID + LEFT JOIN #existingStats intData + ON stat.DepartmentID = intData.DepartmentID + AND stat.AccountID = intData.AccountID + AND stat.FiscalMonthID = intData.FiscalMonthID + AND stat.PatientClassID = intData.PatientClassID + WHERE stat.FiscalYearID = @CurrentFiscalYearID + AND fm.SortOrder <= @MonthsLoaded + AND intData.DepartmentID IS NULL + GROUP BY stat.DepartmentID, stat.AccountID, stat.PatientClassID, fm.MonthColumnName) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) + ) as pv + ON fs.DepartmentID = pv.DepartmentID AND fs.AccountID = pv.AccountID AND fs.PatientClassID = pv.PatientClassID + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID AND fs.SubsectionID = 1 AND fs.ProviderID = 0 AND fs.ProviderLineItemID = 0 + + + END + + -- copy the baseline data over for months without data (month sort order > @MonthsLoaded) + DECLARE @IsLeapYear BIT = (CASE WHEN ( @CurrentFiscalYearID % 4 = 0 AND @CurrentFiscalYearID % 100 <> 0) OR @CurrentFiscalYearID % 400 = 0 THEN 1 ELSE 0 END) + DECLARE @DaysInYear decimal = (SELECT (CASE WHEN @IsLeapYear = 1 THEN YTDDaysInLeapYearMonth ELSE YTDDaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder = 12) + DECLARE @DaysInMonthsLoaded decimal = (SELECT SUM(CASE WHEN @IsLeapYear = 1 THEN DaysInLeapYearMonth ELSE DaysInMonth END) FROM [fw].[DimFiscalMonth] WHERE SortOrder <= @MonthsLoaded) + DECLARE @MonthsNotLoaded decimal = 12 - @MonthsLoaded + DECLARE @DaysRemaining decimal = @DaysInYear - @DaysInMonthsLoaded + DECLARE @SourceYear SMALLINT; + DECLARE @TimeClassID TINYINT + SELECT @SourceYear = StatisticsFiscalYearID, @TimeClassID = StatisticsTimeClassID FROM fp.EntityGroupConfig WHERE EntityGroupConfigID = @EntityGroupConfigID + +IF @CurrentFiscalYearID = @SourceYear AND @TimeClassID = 1 BEGIN + UPDATE + fs + SET + SampledProjection02 = CASE WHEN @MonthsLoaded < 2 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection02 END, + SampledProjection03 = CASE WHEN @MonthsLoaded < 3 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection03 END, + SampledProjection04 = CASE WHEN @MonthsLoaded < 4 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection04 END, + SampledProjection05 = CASE WHEN @MonthsLoaded < 5 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection05 END, + SampledProjection06 = CASE WHEN @MonthsLoaded < 6 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection06 END, + SampledProjection07 = CASE WHEN @MonthsLoaded < 7 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection07 END, + SampledProjection08 = CASE WHEN @MonthsLoaded < 8 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection08 END, + SampledProjection09 = CASE WHEN @MonthsLoaded < 9 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection09 END, + SampledProjection10 = CASE WHEN @MonthsLoaded < 10 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection10 END, + SampledProjection11 = CASE WHEN @MonthsLoaded < 11 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection11 END, + SampledProjection12 = CASE WHEN @MonthsLoaded < 12 THEN ((SampledProjectionTotal / @DaysInMonthsLoaded) * @DaysRemaining) / @MonthsNotLoaded ELSE SampledProjection12 END + FROM + [fp].[FactStatistics] fs + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID +END ELSE BEGIN +-- copy the baseline data over for months without data (month sort order > @MonthsLoaded) + -- if the baseline is current year actual YTD, then the data would already have been annualized, if not, then we don't need to annualize + UPDATE + fs + SET + SampledProjection02 = CASE WHEN @MonthsLoaded < 2 THEN SampledBudget02 ELSE SampledProjection02 END, + SampledProjection03 = CASE WHEN @MonthsLoaded < 3 THEN SampledBudget03 ELSE SampledProjection03 END, + SampledProjection04 = CASE WHEN @MonthsLoaded < 4 THEN SampledBudget04 ELSE SampledProjection04 END, + SampledProjection05 = CASE WHEN @MonthsLoaded < 5 THEN SampledBudget05 ELSE SampledProjection05 END, + SampledProjection06 = CASE WHEN @MonthsLoaded < 6 THEN SampledBudget06 ELSE SampledProjection06 END, + SampledProjection07 = CASE WHEN @MonthsLoaded < 7 THEN SampledBudget07 ELSE SampledProjection07 END, + SampledProjection08 = CASE WHEN @MonthsLoaded < 8 THEN SampledBudget08 ELSE SampledProjection08 END, + SampledProjection09 = CASE WHEN @MonthsLoaded < 9 THEN SampledBudget09 ELSE SampledProjection09 END, + SampledProjection10 = CASE WHEN @MonthsLoaded < 10 THEN SampledBudget10 ELSE SampledProjection10 END, + SampledProjection11 = CASE WHEN @MonthsLoaded < 11 THEN SampledBudget11 ELSE SampledProjection11 END, + SampledProjection12 = CASE WHEN @MonthsLoaded < 12 THEN SampledBudget12 ELSE SampledProjection12 END + FROM + [fp].[FactStatistics] fs + WHERE + fs.EntityGroupConfigID = @EntityGroupConfigID +END + + UPDATE + fs + SET + InitialProjection01 = fs.SampledProjection01, + InitialProjection02 = fs.SampledProjection02, + InitialProjection03 = fs.SampledProjection03, + InitialProjection04 = fs.SampledProjection04, + InitialProjection05 = fs.SampledProjection05, + InitialProjection06 = fs.SampledProjection06, + InitialProjection07 = fs.SampledProjection07, + InitialProjection08 = fs.SampledProjection08, + InitialProjection09 = fs.SampledProjection09, + InitialProjection10 = fs.SampledProjection10, + InitialProjection11 = fs.SampledProjection11, + InitialProjection12 = fs.SampledProjection12 + FROM [fp].[FactStatistics] fs + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID + + + +END +GO + + +--------------------------------------------- + +-- fp.procSampleStatsProjectionData +CREATE PROCEDURE [fp].[procSampleStatsProjectionData] + @EntityGroupConfigID int +AS +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2022-10-13 JB JAZZ-43489 Remove FlexedValue references + *************************************************************/ +BEGIN + + -- update the projection data + INSERT INTO [fp].[FactStatisticsProjection]([StatisticsID], [BudgetPhaseID], + [AdjustedValue01], [AdjustedValue02], [AdjustedValue03], [AdjustedValue04], [AdjustedValue05], [AdjustedValue06], [AdjustedValue07], [AdjustedValue08], [AdjustedValue09], [AdjustedValue10], [AdjustedValue11], [AdjustedValue12]) + + SELECT [StatisticsID], [BudgetPhaseID], + [InitialProjection01], [InitialProjection02], [InitialProjection03], [InitialProjection04], [InitialProjection05], [InitialProjection06], [InitialProjection07], [InitialProjection08], [InitialProjection09], [InitialProjection10], [InitialProjection11], [InitialProjection12] + FROM [fp].[FactStatistics] fs + CROSS APPLY (VALUES (2),(3)) bp(BudgetPhaseID) + WHERE fs.EntityGroupConfigID = @EntityGroupConfigID AND IsNew = 0 + +END +GO + + +--------------------------------------------- + +-- fp.procSampleUnitPerEncounterRates +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-01-31 NT JAZZ-48268 Make change to use the new fp.ChargeVolume (data restructure) +*************************************************************/ +CREATE PROCEDURE [fp].[procSampleUnitPerEncounterRates] + @BudgetConfigID INT, + @MonthsLoaded INT, + @CurrentYearID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +WITH RECOMPILE + AS + BEGIN + IF OBJECT_ID('tempdb..#tbl_ids') IS NOT NULL DROP TABLE #tbl_ids; + IF OBJECT_ID('tempdb..#units') IS NOT NULL DROP TABLE #units; + IF OBJECT_ID('tempdb..#proj_units') IS NOT NULL DROP TABLE #proj_units; + IF OBJECT_ID('tempdb..#unit') IS NOT NULL DROP TABLE #unit; + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment; + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #FilteredData (ChargeVolumeID INT PRIMARY KEY CLUSTERED) + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilteredData + SELECT cv.ChargeVolumeID + FROM [fp].[ChargeVolume] cv + INNER JOIN #FilterByDepartment ft on ft.DepartmentID = cv.DepartmentID + WHERE cv.BudgetConfigID = @BudgetConfigID + END ELSE BEGIN + INSERT INTO #FilteredData + SELECT ChargeVolumeID + FROM [fp].[ChargeVolume] cv + WHERE cv.BudgetConfigID = @BudgetConfigID + END + + CREATE TABLE #filterTable ( + ChargeVolumeID INT PRIMARY KEY CLUSTERED, + BudgetConfigID INT, + EntityGroupConfigID INT, + SampledBudgetChargeUnits DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledBudgetEncounters DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionChargeUnits DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionEncounters DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionUnits01 DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionUnits02 DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionUnits03 DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionUnits04 DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionUnits05 DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionUnits06 DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionUnits07 DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionUnits08 DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionUnits09 DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionUnits10 DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionUnits11 DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionEncounters01 DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionEncounters02 DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionEncounters03 DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionEncounters04 DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionEncounters05 DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionEncounters06 DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionEncounters07 DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionEncounters08 DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionEncounters09 DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionEncounters10 DECIMAL(19, 8) NOT NULL DEFAULT(0), + SampledProjectionEncounters11 DECIMAL(19, 8) NOT NULL DEFAULT(0) + ); + + INSERT INTO #filterTable ( + ChargeVolumeID, EntityGroupConfigID, BudgetConfigID, + SampledBudgetChargeUnits, SampledBudgetEncounters, SampledProjectionChargeUnits, SampledProjectionEncounters, + SampledProjectionUnits01, SampledProjectionUnits02, SampledProjectionUnits03, SampledProjectionUnits04, SampledProjectionUnits05, SampledProjectionUnits06, + SampledProjectionUnits07, SampledProjectionUnits08, SampledProjectionUnits09, SampledProjectionUnits10, SampledProjectionUnits11, + SampledProjectionEncounters01, SampledProjectionEncounters02, SampledProjectionEncounters03, SampledProjectionEncounters04, + SampledProjectionEncounters05, SampledProjectionEncounters06, SampledProjectionEncounters07, SampledProjectionEncounters08, + SampledProjectionEncounters09, SampledProjectionEncounters10, SampledProjectionEncounters11) + SELECT cv.ChargeVolumeID, cv.EntityGroupConfigID, cv.BudgetConfigID, + cv.SampledBudgetTotal AS SampledBudgetChargeUnits, SUM(sle.InitialBudgetTotal) AS SampledBudgetEncounters, + cv.SampledProjectionTotal AS SampledProjectionChargeUnits, SUM(sle.InitialProjectionTotal) AS SampledProjectionEncounters, + cv.SampledProjection01, cv.SampledProjection02, cv.SampledProjection03, cv.SampledProjection04, cv.SampledProjection05, cv.SampledProjection06, + cv.SampledProjection07, cv.SampledProjection08, cv.SampledProjection09, cv.SampledProjection10, cv.SampledProjection11, + SUM(sle.InitialProjection01) AS InitialProjection01, + SUM(sle.InitialProjection02) AS InitialProjection02, + SUM(sle.InitialProjection03) AS InitialProjection03, + SUM(sle.InitialProjection04) AS InitialProjection04, + SUM(sle.InitialProjection05) AS InitialProjection05, + SUM(sle.InitialProjection06) AS InitialProjection06, + SUM(sle.InitialProjection07) AS InitialProjection07, + SUM(sle.InitialProjection08) AS InitialProjection08, + SUM(sle.InitialProjection09) AS InitialProjection09, + SUM(sle.InitialProjection10) AS InitialProjection10, + SUM(sle.InitialProjection11) AS InitialProjection11 + FROM [fp].[ChargeVolume] cv + INNER JOIN #FilteredData filter ON cv.ChargeVolumeID = filter.ChargeVolumeID + INNER JOIN fp.ServiceLineEncounter sle + ON cv.BudgetConfigID = sle.BudgetConfigID + AND cv.AgeCohortID = sle.AgeCohortID + AND cv.MedicalSurgicalID = sle.MedicalSurgicalID + AND cv.PatientClassID = sle.PatientClassID + AND cv.ServiceLineID = sle.ServiceLineID + AND cv.ServiceEntityID = sle.EntityID + AND cv.MSDRGID = sle.MSDRGID + AND cv.PrimaryCPTID = sle.CPTID + AND cv.ServiceProviderID = sle.ProviderID + WHERE cv.BudgetConfigID = @BudgetConfigID + AND cv.UnitTypeID = 145 + GROUP BY cv.ChargeVolumeID, cv.EntityGroupConfigID, cv.BudgetConfigID, cv.SampledBudgetTotal, cv.SampledProjectionTotal, + cv.SampledProjection01, cv.SampledProjection02, cv.SampledProjection03, cv.SampledProjection04, cv.SampledProjection05, cv.SampledProjection06, cv.SampledProjection07, cv.SampledProjection08, cv.SampledProjection09, cv.SampledProjection10, cv.SampledProjection11 + + IF (@IsDebug = 1) + BEGIN + SELECT + 'Budget UnitsPerEncounter Calculation', + IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter01, + IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter02, + IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter03, + IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter04, + IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter05, + IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter06, + IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter07, + IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter08, + IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter09, + IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter10, + IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter11, + IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) AS InitialBudgetUnitsPerEncounter12, + cv.* + FROM [fp].[ChargeVolume] cv + INNER JOIN #filterTable ft + ON cv.BudgetConfigID = ft.BudgetConfigID -- Joining on Budget config first because it's the first in the clustered index + AND cv.ChargeVolumeID = ft.ChargeVolumeID + WHERE cv.BudgetConfigID = @BudgetConfigID + AND cv.UnitTypeID = 145 + END ELSE + BEGIN + UPDATE cv + SET + cv.InitialBudgetUnitsPerEncounter01 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0), + cv.InitialBudgetUnitsPerEncounter02 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0), + cv.InitialBudgetUnitsPerEncounter03 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0), + cv.InitialBudgetUnitsPerEncounter04 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0), + cv.InitialBudgetUnitsPerEncounter05 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0), + cv.InitialBudgetUnitsPerEncounter06 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0), + cv.InitialBudgetUnitsPerEncounter07 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0), + cv.InitialBudgetUnitsPerEncounter08 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0), + cv.InitialBudgetUnitsPerEncounter09 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0), + cv.InitialBudgetUnitsPerEncounter10 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0), + cv.InitialBudgetUnitsPerEncounter11 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0), + cv.InitialBudgetUnitsPerEncounter12 = IIF(ft.SampledBudgetEncounters != 0, (ft.SampledBudgetChargeUnits / ft.SampledBudgetEncounters ), 0) + FROM [fp].[ChargeVolume] cv + INNER JOIN #filterTable ft + ON cv.BudgetConfigID = ft.BudgetConfigID -- Joining on Budget config first because it's the first in the clustered index + AND cv.ChargeVolumeID = ft.ChargeVolumeID + WHERE cv.BudgetConfigID = @BudgetConfigID + AND cv.UnitTypeID = 145 + END + + IF OBJECT_ID('tempdb..#tbl_entitygroup') IS NOT NULL DROP TABLE #tbl_entitygroup; + CREATE TABLE #tbl_entitygroup (EntityGroupConfigID INT, IsAnnualized INT); + + INSERT INTO #tbl_entitygroup (EntityGroupConfigID, IsAnnualized) + SELECT EntityGroupConfigID, CASE WHEN ServiceLineEncounterTimeClassID = 1 AND ServiceLineEncounterFiscalYearID = @CurrentYearID THEN 1 ELSE 0 END + FROM [fp].[EntityGroupConfig] egc + INNER JOIN [fp].[BudgetConfig] bc on egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE bc.BudgetConfigID = @BudgetConfigID + + IF (@IsDebug = 1) + BEGIN + SELECT 'Entity Groups Sampled', EntityGroupConfigID, IsAnnualized FROM #tbl_entitygroup + END + + -- Process Entity Group Configs that are not annualized + IF EXISTS (SELECT 1 FROM #tbl_entitygroup WHERE IsAnnualized = 0) BEGIN + IF (@IsDebug = 1) + BEGIN + SELECT + 'Not Annualized Projection UnitsPerEncounter Calculation', + IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter01, + IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter02, + IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter03, + IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter04, + IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter05, + IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter06, + IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter07, + IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter08, + IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter09, + IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter10, + IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter11, + IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) AS InitialProjectionUnitsPerEncounter12, + cv.* + FROM [fp].[ChargeVolume] cv + INNER JOIN #tbl_entitygroup egc + ON cv.EntityGroupConfigID = egc.EntityGroupConfigID + INNER JOIN #filterTable ft + ON cv.BudgetConfigID = ft.BudgetConfigID -- Joining on Budget config first because it's the first in the clustered index + AND cv.ChargeVolumeID = ft.ChargeVolumeID + WHERE cv.BudgetConfigID = @BudgetConfigID + AND cv.UnitTypeID = 145 + AND egc.IsAnnualized = 0 + END ELSE + BEGIN + UPDATE cv + SET + cv.InitialProjectionUnitsPerEncounter01 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0), + cv.InitialProjectionUnitsPerEncounter02 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0), + cv.InitialProjectionUnitsPerEncounter03 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0), + cv.InitialProjectionUnitsPerEncounter04 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0), + cv.InitialProjectionUnitsPerEncounter05 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0), + cv.InitialProjectionUnitsPerEncounter06 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0), + cv.InitialProjectionUnitsPerEncounter07 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0), + cv.InitialProjectionUnitsPerEncounter08 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0), + cv.InitialProjectionUnitsPerEncounter09 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0), + cv.InitialProjectionUnitsPerEncounter10 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0), + cv.InitialProjectionUnitsPerEncounter11 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0), + cv.InitialProjectionUnitsPerEncounter12 = IIF(ft.SampledProjectionEncounters != 0, (ft.SampledProjectionChargeUnits / ft.SampledProjectionEncounters ), 0) + FROM [fp].[ChargeVolume] cv + INNER JOIN #tbl_entitygroup egc + ON cv.EntityGroupConfigID = egc.EntityGroupConfigID + INNER JOIN #filterTable ft + ON cv.BudgetConfigID = ft.BudgetConfigID -- Joining on Budget config first because it's the first in the clustered index + AND cv.ChargeVolumeID = ft.ChargeVolumeID + WHERE cv.BudgetConfigID = @BudgetConfigID + AND cv.UnitTypeID = 145 + AND egc.IsAnnualized = 0 + END + END + + -- Annualized + IF EXISTS (SELECT 1 FROM #tbl_entitygroup WHERE IsAnnualized = 1) BEGIN + + IF OBJECT_ID('tempdb..#tbl_UnitsPerEncounters') IS NOT NULL DROP TABLE #tbl_UnitsPerEncounters; + + CREATE TABLE #tbl_UnitsPerEncounters ( + ChargeVolumeID INT PRIMARY KEY CLUSTERED, + EntityGroupConfigID INT, + ChargeVolumeTotal DECIMAL(19,8), + ServiceLineTotal DECIMAL(19,8), + UnitsPerEncounter DECIMAL(19,8) + ); + + INSERT INTO #tbl_UnitsPerEncounters (ChargeVolumeID, EntityGroupConfigID, ChargeVolumeTotal, ServiceLineTotal, UnitsPerEncounter) + SELECT ChargeVolumeID, egc.EntityGroupConfigID, + CASE + WHEN @MonthsLoaded = 12 THEN ft.SampledProjectionChargeUnits + WHEN @MonthsLoaded >= 11 THEN ft.SampledProjectionUnits01 + ft.SampledProjectionUnits02 + ft.SampledProjectionUnits03 + ft.SampledProjectionUnits04 + ft.SampledProjectionUnits05 + ft.SampledProjectionUnits06 + ft.SampledProjectionUnits07 + ft.SampledProjectionUnits08 + ft.SampledProjectionUnits09 + ft.SampledProjectionUnits10 + ft.SampledProjectionUnits11 + WHEN @MonthsLoaded >= 10 THEN ft.SampledProjectionUnits01 + ft.SampledProjectionUnits02 + ft.SampledProjectionUnits03 + ft.SampledProjectionUnits04 + ft.SampledProjectionUnits05 + ft.SampledProjectionUnits06 + ft.SampledProjectionUnits07 + ft.SampledProjectionUnits08 + ft.SampledProjectionUnits09 + ft.SampledProjectionUnits10 + WHEN @MonthsLoaded >= 9 THEN ft.SampledProjectionUnits01 + ft.SampledProjectionUnits02 + ft.SampledProjectionUnits03 + ft.SampledProjectionUnits04 + ft.SampledProjectionUnits05 + ft.SampledProjectionUnits06 + ft.SampledProjectionUnits07 + ft.SampledProjectionUnits08 + ft.SampledProjectionUnits09 + WHEN @MonthsLoaded >= 8 THEN ft.SampledProjectionUnits01 + ft.SampledProjectionUnits02 + ft.SampledProjectionUnits03 + ft.SampledProjectionUnits04 + ft.SampledProjectionUnits05 + ft.SampledProjectionUnits06 + ft.SampledProjectionUnits07 + ft.SampledProjectionUnits08 + WHEN @MonthsLoaded >= 7 THEN ft.SampledProjectionUnits01 + ft.SampledProjectionUnits02 + ft.SampledProjectionUnits03 + ft.SampledProjectionUnits04 + ft.SampledProjectionUnits05 + ft.SampledProjectionUnits06 + ft.SampledProjectionUnits07 + WHEN @MonthsLoaded >= 6 THEN ft.SampledProjectionUnits01 + ft.SampledProjectionUnits02 + ft.SampledProjectionUnits03 + ft.SampledProjectionUnits04 + ft.SampledProjectionUnits05 + ft.SampledProjectionUnits06 + WHEN @MonthsLoaded >= 5 THEN ft.SampledProjectionUnits01 + ft.SampledProjectionUnits02 + ft.SampledProjectionUnits03 + ft.SampledProjectionUnits04 + ft.SampledProjectionUnits05 + WHEN @MonthsLoaded >= 4 THEN ft.SampledProjectionUnits01 + ft.SampledProjectionUnits02 + ft.SampledProjectionUnits03 + ft.SampledProjectionUnits04 + WHEN @MonthsLoaded >= 3 THEN ft.SampledProjectionUnits01 + ft.SampledProjectionUnits02 + ft.SampledProjectionUnits03 + WHEN @MonthsLoaded >= 2 THEN ft.SampledProjectionUnits01 + ft.SampledProjectionUnits02 + ELSE ft.SampledProjectionUnits01 + END AS ChargeVolumeTotal, + CASE + WHEN @MonthsLoaded = 12 THEN ft.SampledProjectionEncounters + WHEN @MonthsLoaded >= 11 THEN ft.SampledProjectionEncounters01 + ft.SampledProjectionEncounters02 + ft.SampledProjectionEncounters03 + ft.SampledProjectionEncounters04 + ft.SampledProjectionEncounters05 + ft.SampledProjectionEncounters06 + ft.SampledProjectionEncounters07 + ft.SampledProjectionEncounters08 + ft.SampledProjectionEncounters09 + ft.SampledProjectionEncounters10 + ft.SampledProjectionEncounters11 + WHEN @MonthsLoaded >= 10 THEN ft.SampledProjectionEncounters01 + ft.SampledProjectionEncounters02 + ft.SampledProjectionEncounters03 + ft.SampledProjectionEncounters04 + ft.SampledProjectionEncounters05 + ft.SampledProjectionEncounters06 + ft.SampledProjectionEncounters07 + ft.SampledProjectionEncounters08 + ft.SampledProjectionEncounters09 + ft.SampledProjectionEncounters10 + WHEN @MonthsLoaded >= 9 THEN ft.SampledProjectionEncounters01 + ft.SampledProjectionEncounters02 + ft.SampledProjectionEncounters03 + ft.SampledProjectionEncounters04 + ft.SampledProjectionEncounters05 + ft.SampledProjectionEncounters06 + ft.SampledProjectionEncounters07 + ft.SampledProjectionEncounters08 + ft.SampledProjectionEncounters09 + WHEN @MonthsLoaded >= 8 THEN ft.SampledProjectionEncounters01 + ft.SampledProjectionEncounters02 + ft.SampledProjectionEncounters03 + ft.SampledProjectionEncounters04 + ft.SampledProjectionEncounters05 + ft.SampledProjectionEncounters06 + ft.SampledProjectionEncounters07 + ft.SampledProjectionEncounters08 + WHEN @MonthsLoaded >= 7 THEN ft.SampledProjectionEncounters01 + ft.SampledProjectionEncounters02 + ft.SampledProjectionEncounters03 + ft.SampledProjectionEncounters04 + ft.SampledProjectionEncounters05 + ft.SampledProjectionEncounters06 + ft.SampledProjectionEncounters07 + WHEN @MonthsLoaded >= 6 THEN ft.SampledProjectionEncounters01 + ft.SampledProjectionEncounters02 + ft.SampledProjectionEncounters03 + ft.SampledProjectionEncounters04 + ft.SampledProjectionEncounters05 + ft.SampledProjectionEncounters06 + WHEN @MonthsLoaded >= 5 THEN ft.SampledProjectionEncounters01 + ft.SampledProjectionEncounters02 + ft.SampledProjectionEncounters03 + ft.SampledProjectionEncounters04 + ft.SampledProjectionEncounters05 + WHEN @MonthsLoaded >= 4 THEN ft.SampledProjectionEncounters01 + ft.SampledProjectionEncounters02 + ft.SampledProjectionEncounters03 + ft.SampledProjectionEncounters04 + WHEN @MonthsLoaded >= 3 THEN ft.SampledProjectionEncounters01 + ft.SampledProjectionEncounters02 + ft.SampledProjectionEncounters03 + WHEN @MonthsLoaded >= 2 THEN ft.SampledProjectionEncounters01 + ft.SampledProjectionEncounters02 + ELSE ft.SampledProjectionEncounters01 + END AS ServiceLineTotal, 0 + FROM #tbl_entitygroup egc + INNER JOIN #filterTable ft ON egc.EntityGroupConfigID = ft.EntityGroupConfigID + WHERE egc.IsAnnualized = 1 + + UPDATE #tbl_UnitsPerEncounters SET UnitsPerEncounter = ChargeVolumeTotal / ServiceLineTotal WHERE ServiceLineTotal <> 0; + + IF (@IsDebug = 1) + BEGIN + SELECT 'Annualized Projection UnitsPerEncounter Calculation', ChargeVolumeID, EntityGroupConfigID, ChargeVolumeTotal, ServiceLineTotal, UnitsPerEncounter + FROM #tbl_UnitsPerEncounters + + SELECT + UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter01, + UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter02, + UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter03, + UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter04, + UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter05, + UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter06, + UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter07, + UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter08, + UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter09, + UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter10, + UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter11, + UnitsPerEncounter.UnitsPerEncounter AS InitialProjectionUnitsPerEncounter12, + cv.ChargeVolumeID, + cv.EntityGroupConfigID, + UnitsPerEncounter.ChargeVolumeTotal, + UnitsPerEncounter.ServiceLineTotal + FROM [fp].[ChargeVolume] cv + INNER JOIN #tbl_entitygroup egc + ON cv.EntityGroupConfigID = egc.EntityGroupConfigID + INNER JOIN #tbl_UnitsPerEncounters UnitsPerEncounter + ON cv.EntityGroupConfigID = UnitsPerEncounter.EntityGroupConfigID + AND cv.ChargeVolumeID = UnitsPerEncounter.ChargeVolumeID + WHERE cv.BudgetConfigID = @BudgetConfigID + AND cv.UnitTypeID = 145 + AND egc.IsAnnualized = 1 + END ELSE + BEGIN + UPDATE cv + SET + cv.InitialProjectionUnitsPerEncounter01 = UnitsPerEncounter.UnitsPerEncounter, + cv.InitialProjectionUnitsPerEncounter02 = UnitsPerEncounter.UnitsPerEncounter, + cv.InitialProjectionUnitsPerEncounter03 = UnitsPerEncounter.UnitsPerEncounter, + cv.InitialProjectionUnitsPerEncounter04 = UnitsPerEncounter.UnitsPerEncounter, + cv.InitialProjectionUnitsPerEncounter05 = UnitsPerEncounter.UnitsPerEncounter, + cv.InitialProjectionUnitsPerEncounter06 = UnitsPerEncounter.UnitsPerEncounter, + cv.InitialProjectionUnitsPerEncounter07 = UnitsPerEncounter.UnitsPerEncounter, + cv.InitialProjectionUnitsPerEncounter08 = UnitsPerEncounter.UnitsPerEncounter, + cv.InitialProjectionUnitsPerEncounter09 = UnitsPerEncounter.UnitsPerEncounter, + cv.InitialProjectionUnitsPerEncounter10 = UnitsPerEncounter.UnitsPerEncounter, + cv.InitialProjectionUnitsPerEncounter11 = UnitsPerEncounter.UnitsPerEncounter, + cv.InitialProjectionUnitsPerEncounter12 = UnitsPerEncounter.UnitsPerEncounter + FROM [fp].[ChargeVolume] cv + INNER JOIN #tbl_entitygroup egc + ON cv.EntityGroupConfigID = egc.EntityGroupConfigID + INNER JOIN #tbl_UnitsPerEncounters UnitsPerEncounter + ON cv.EntityGroupConfigID = UnitsPerEncounter.EntityGroupConfigID + AND cv.ChargeVolumeID = UnitsPerEncounter.ChargeVolumeID + WHERE cv.BudgetConfigID = @BudgetConfigID + AND cv.UnitTypeID = 145 + AND egc.IsAnnualized = 1 + END + END + END +GO + + +--------------------------------------------- + +-- fp.procServiceLineEncountersApplySpread +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-02-18 MV JAZZ-33683 Spread Target and Budget +** 2 2022-09-13 SD JAZZ-42555 Skip newly added dimensionality records during Encounter spreads +** 3 2023-02-13 BW JAZZ-48306 Updated for new data model, use [fp].[ServiceLineEncounter] +** 4 2023-05-19 SD JAZZ-54066 Added changes for deleting 'Apply Encounter spread on Target and Budget' FF after restructure Service Line Encounters page +** 5 2024-01-22 MY JAZZ-64799 History Viewer does not handle Spread Impact for Monthly Values +*************************************************************/ +CREATE PROCEDURE [fp].[procServiceLineEncountersApplySpread] + @BudgetConfigID INT +AS +BEGIN + DECLARE @volumeUnitType INT = 140; + + IF OBJECT_ID('tempdb..#filterTable') IS NOT NULL DROP TABLE #filterTable; + IF OBJECT_ID('tempdb..#spreadsChangeHistory') IS NOT NULL DROP TABLE #spreadsChangeHistory; + + CREATE TABLE #spreadsChangeHistory ( + ServiceLineEncounterID INT, + OldValue01 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue02 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue03 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue04 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue05 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue06 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue07 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue08 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue09 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue10 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue11 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue12 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue01 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue02 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue03 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue04 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue05 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue06 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue07 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue08 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue09 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue10 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue11 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue12 DECIMAL(19, 8) NOT NULL DEFAULT(0), + ); + + CREATE TABLE #filterTable (ServiceLineEncounterID INT PRIMARY KEY CLUSTERED); + + IF EXISTS(SELECT 1 FROM [fp].[viewBudgetConfigSetting] setting WHERE setting.Name = 'Skip newly added dimensionality records during Encounter spreads' AND setting.BudgetConfigID = @BudgetConfigID AND setting.Value = 1) + BEGIN + INSERT INTO #filterTable (ServiceLineEncounterID) + SELECT DISTINCT basis.ServiceLineEncounterID + FROM [fp].[ServiceLineEncounter] basis + INNER JOIN [fp].[ServiceLineEncounterSpreads] spread ON spread.BudgetConfigID = basis.BudgetConfigID AND spread.EntityID = basis.EntityID AND spread.ServiceLineID = basis.ServiceLineID AND spread.PatientClassID = basis.PatientClassID + WHERE basis.BudgetConfigID = @BudgetConfigID + AND basis.UnitTypeID = @volumeUnitType + AND basis.BudgetLockType <> 1 AND basis.BudgetLockType <> 7 + AND basis.TargetLockType <> 1 AND basis.TargetLockType <> 7 AND basis.isNew = 0 + END + ELSE + BEGIN + INSERT INTO #filterTable (ServiceLineEncounterID) + SELECT DISTINCT basis.ServiceLineEncounterID + FROM [fp].[ServiceLineEncounter] basis + INNER JOIN [fp].[ServiceLineEncounterSpreads] spread ON spread.BudgetConfigID = basis.BudgetConfigID AND spread.EntityID = basis.EntityID AND spread.ServiceLineID = basis.ServiceLineID AND spread.PatientClassID = basis.PatientClassID + WHERE basis.BudgetConfigID = @BudgetConfigID + AND basis.UnitTypeID = @volumeUnitType + AND basis.BudgetLockType <> 1 AND basis.BudgetLockType <> 7 + AND basis.TargetLockType <> 1 AND basis.TargetLockType <> 7 + END + + --Apply spreads for target firstly + UPDATE sle + SET sle.TargetLockType = 6, sle.TargetLockFlag = 1 + , TargetAdjusted01 = CAST(TargetAdjustedTotal * SpreadPercentage01 AS DECIMAL(19,8)) + , TargetAdjusted02 = + CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN TargetAdjustedTotal - CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + ELSE CAST(TargetAdjustedTotal * SpreadPercentage02 AS DECIMAL(19,8)) END + , TargetAdjusted03 = + CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN TargetAdjustedTotal - (CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8))) + ELSE CAST(TargetAdjustedTotal * SpreadPercentage03 AS DECIMAL(19,8)) END + , TargetAdjusted04 = + CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN TargetAdjustedTotal - (CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8))) + ELSE CAST(TargetAdjustedTotal * SpreadPercentage04 AS DECIMAL(19,8)) END + , TargetAdjusted05 = + CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN TargetAdjustedTotal - (CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8))) + ELSE CAST(TargetAdjustedTotal * SpreadPercentage05 AS DECIMAL(19,8)) END + , TargetAdjusted06 = + CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN TargetAdjustedTotal - (CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8))) + ELSE CAST(TargetAdjustedTotal * SpreadPercentage06 AS DECIMAL(19,8)) END + , TargetAdjusted07 = + CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN TargetAdjustedTotal - (CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8))) + ELSE CAST(TargetAdjustedTotal * SpreadPercentage07 AS DECIMAL(19,8)) END + , TargetAdjusted08 = + CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN TargetAdjustedTotal - (CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8))) + ELSE CAST(TargetAdjustedTotal * SpreadPercentage08 AS DECIMAL(19,8)) END + , TargetAdjusted09 = + CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN TargetAdjustedTotal - (CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8))) + ELSE CAST(TargetAdjustedTotal * SpreadPercentage09 AS DECIMAL(19,8)) END + , TargetAdjusted10 = + CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN TargetAdjustedTotal - (CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8))) + ELSE CAST(TargetAdjustedTotal * SpreadPercentage10 AS DECIMAL(19,8)) END + , TargetAdjusted11 = + CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 + THEN TargetAdjustedTotal - (CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage10) AS DECIMAL(19, 8))) + ELSE CAST(TargetAdjustedTotal * SpreadPercentage11 AS DECIMAL(19,8)) END + , TargetAdjusted12 = + CASE WHEN SpreadPercentage12 != 0 + THEN TargetAdjustedTotal - (CAST((TargetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((TargetAdjustedTotal * SpreadPercentage11) AS DECIMAL(19, 8))) + ELSE CAST(TargetAdjustedTotal * SpreadPercentage12 AS DECIMAL(19,8)) END + FROM [fp].[viewServiceLineEncounterSpreads] encsp + INNER JOIN [fp].[ServiceLineEncounter] sle ON encsp.BudgetConfigID = sle.BudgetConfigID AND encsp.EntityID = sle.EntityID AND encsp.ServiceLineID = sle.ServiceLineID AND encsp.PatientClassID = sle.PatientClassID + INNER JOIN #filterTable tmp on sle.ServiceLineEncounterID = tmp.ServiceLineEncounterID + WHERE encsp.IsInactive = 0 + + --Apply spreads for budget + UPDATE sle + SET sle.BudgetLockType = 6, sle.BudgetLockFlag = 1 + , BudgetAdjusted01 = CAST(BudgetAdjustedTotal * SpreadPercentage01 AS DECIMAL(19,8)) + , BudgetAdjusted02 = + CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage02 AS DECIMAL(19,8)) END + , BudgetAdjusted03 = + CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage03 AS DECIMAL(19,8)) END + , BudgetAdjusted04 = + CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage04 AS DECIMAL(19,8)) END + , BudgetAdjusted05 = + CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage05 AS DECIMAL(19,8)) END + , BudgetAdjusted06 = + CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage06 AS DECIMAL(19,8)) END + , BudgetAdjusted07 = + CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage07 AS DECIMAL(19,8)) END + , BudgetAdjusted08 = + CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage08 AS DECIMAL(19,8)) END + , BudgetAdjusted09 = + CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage09 AS DECIMAL(19,8)) END + , BudgetAdjusted10 = + CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage10 AS DECIMAL(19,8)) END + , BudgetAdjusted11 = + CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage10) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage11 AS DECIMAL(19,8)) END + , BudgetAdjusted12 = + CASE WHEN SpreadPercentage12 != 0 + THEN BudgetAdjustedTotal - (CAST((BudgetAdjustedTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((BudgetAdjustedTotal * SpreadPercentage11) AS DECIMAL(19, 8))) + ELSE CAST(BudgetAdjustedTotal * SpreadPercentage12 AS DECIMAL(19,8)) END + OUTPUT -- Only doing budget here because Target and Budget are always the same value and when we make encounters like every other section this will help be one less thing to update + inserted.ServiceLineEncounterID, + deleted.BudgetAdjusted01, deleted.BudgetAdjusted02, deleted.BudgetAdjusted03, deleted.BudgetAdjusted04, deleted.BudgetAdjusted05, deleted.BudgetAdjusted06, + deleted.BudgetAdjusted07, deleted.BudgetAdjusted08, deleted.BudgetAdjusted09, deleted.BudgetAdjusted10, deleted.BudgetAdjusted11, deleted.BudgetAdjusted12, + inserted.BudgetAdjusted01, inserted.BudgetAdjusted02, inserted.BudgetAdjusted03, inserted.BudgetAdjusted04, inserted.BudgetAdjusted05, inserted.BudgetAdjusted06, + inserted.BudgetAdjusted07, inserted.BudgetAdjusted08, inserted.BudgetAdjusted09, inserted.BudgetAdjusted10, inserted.BudgetAdjusted11, inserted.BudgetAdjusted12 + INTO + #spreadsChangeHistory (ServiceLineEncounterID, + OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06, + OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12, + NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06, + NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) + FROM [fp].[viewServiceLineEncounterSpreads] encsp + INNER JOIN [fp].[ServiceLineEncounter] sle ON encsp.BudgetConfigID = sle.BudgetConfigID AND encsp.EntityID = sle.EntityID AND encsp.ServiceLineID = sle.ServiceLineID AND encsp.PatientClassID = sle.PatientClassID + INNER JOIN #filterTable tmp on sle.ServiceLineEncounterID = tmp.ServiceLineEncounterID + WHERE encsp.IsInactive = 0 + + -- Populate Change History + IF EXISTS(SELECT 1 + FROM fp.BudgetConfigSetting setting + INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON setting.SettingID = def.SettingID + WHERE def.Name = 'Spreads Change History Logic Is Enabled' + AND setting.Value = 1) + BEGIN + + INSERT INTO fp.ServiceLineEncounterSpreadsChangeHistory (ServiceLineEncounterID, BudgetConfigID, OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06, + OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12, NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06, + NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) + SELECT ServiceLineEncounterID, @BudgetConfigID, + ISNULL(OldValue01, 0), ISNULL(OldValue02, 0), ISNULL(OldValue03, 0), ISNULL(OldValue04, 0), ISNULL(OldValue05, 0), ISNULL(OldValue06, 0), + ISNULL(OldValue07, 0), ISNULL(OldValue08, 0), ISNULL(OldValue09, 0), ISNULL(OldValue10, 0), ISNULL(OldValue11, 0), ISNULL(OldValue12, 0), + ISNULL(NewValue01, 0), ISNULL(NewValue02, 0), ISNULL(NewValue03, 0), ISNULL(NewValue04, 0), ISNULL(NewValue05, 0), ISNULL(NewValue06, 0), + ISNULL(NewValue07, 0), ISNULL(NewValue08, 0), ISNULL(NewValue09, 0), ISNULL(NewValue10, 0), ISNULL(NewValue11, 0), ISNULL(NewValue12, 0) + FROM #spreadsChangeHistory + WHERE 1 = 1 + AND ( + OldValue01 != NewValue01 + OR OldValue02 != NewValue02 + OR OldValue03 != NewValue03 + OR OldValue04 != NewValue04 + OR OldValue05 != NewValue05 + OR OldValue06 != NewValue06 + OR OldValue07 != NewValue07 + OR OldValue08 != NewValue08 + OR OldValue09 != NewValue09 + OR OldValue10 != NewValue10 + OR OldValue11 != NewValue11 + OR OldValue12 != NewValue12 + ) + END + +END +GO + + +--------------------------------------------- + +-- fp.procSetupBudgetConfigDefaultHoursMix +CREATE PROCEDURE fp.procSetupBudgetConfigDefaultHoursMix + AS + BEGIN + + INSERT INTO fp.BudgetConfigDefaultHoursMix (BudgetConfigGUID, PayCodeGroupID) + + SELECT bc.BudgetConfigGUID, dpcg.PayCodeGroupID + FROM fp.BudgetConfig bc + CROSS JOIN fw.DimPayCodeGroup dpcg + WHERE dpcg.PayCodeGroupID != 0 + EXCEPT + SELECT bcdhm.BudgetConfigGUID, bcdhm.PayCodeGroupID + FROM fp.BudgetConfigDefaultHoursMix bcdhm; + + END +GO + + +--------------------------------------------- + +-- fp.procStaffingApplySpread +CREATE PROCEDURE [fp].[procStaffingApplySpread] + @BudgetConfigID int, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-01-21 BW JAZZ-13122 Performance update for employee budgeting; using option recompile on long running Update stmt: Dollars based on Hours and Wage Rate + ** 2 2021-04-12 OP JAZZ-18025 Filtered by subsection + ** 3 2022-01-28 NT JAZZ-32003 Add EmployeeID in the JOIN when recalculating FTEs and Dollars + ** 4 2023-02-07 MY JAZZ-63890 Added Change History to Spreads + ** 5 2023-12-13 BW JAZZ-62541 Update for new data structure - update to use the latest working hours view [fp].[viewWorkingHours] + ** 6 2024-01-02 MY JAZZ-64770 Upgrade JAZZ-63890 for Restructure Branch + ** 7 2024-01-02 BK JAZZ-xxxxx Fix with failing tests + *************************************************************/ + + DECLARE @dollarsUnitType INT = 34; + DECLARE @hoursUnitType INT = 51; + DECLARE @ftesUnitType INT = 144; + DECLARE @wageRateUnitType INT = 159; + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #filterTable (StaffingID INT PRIMARY KEY CLUSTERED); + + CREATE TABLE #spreadsChangeHistory ( + StaffingID INT, + UnitTypeID SMALLINT NOT NULL DEFAULT(0), + OldValue01 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue02 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue03 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue04 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue05 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue06 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue07 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue08 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue09 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue10 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue11 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue12 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue01 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue02 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue03 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue04 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue05 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue06 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue07 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue08 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue09 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue10 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue11 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue12 DECIMAL(19, 8) NOT NULL DEFAULT(0), + ); + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + + INSERT INTO #filterTable (StaffingID) + SELECT DISTINCT basis.StaffingID + FROM [fp].[Staffing] basis + INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = basis.DepartmentID + INNER JOIN [fp].[StaffingSpreads] spread ON spread.BudgetConfigID = basis.BudgetConfigID + AND spread.DepartmentID = basis.DepartmentID + AND spread.JobCodeID = basis.JobCodeID + AND spread.PayCodeGroupID = basis.PayCodeGroupID + WHERE basis.BudgetConfigID = @BudgetConfigID + AND basis.VariabilityID = 1 -- fixed + AND spread.IsInactive = 0 + AND ( + (basis.BudgetDollarsLockType <> 1 AND basis.BudgetDollarsLockType <> 7) -- Ignore Final Value and Locked Adjustments + OR (basis.BudgetHoursLockType <> 1 AND basis.BudgetHoursLockType <> 7) -- Ignore Final Value and Locked Adjustments + OR (basis.BudgetFTEsLockType <> 1 AND basis.BudgetFTEsLockType <> 7) -- Ignore Final Value and Locked Adjustments + ) + AND basis.SubsectionID = 3 -- Staffing Stuff + + END ELSE BEGIN + + -- If the table source dimensionality is unfiltered, we don't wanna join on the department filter. + INSERT INTO #filterTable (StaffingID) + SELECT DISTINCT basis.StaffingID + FROM [fp].[Staffing] basis + INNER JOIN [fp].[StaffingSpreads] spread ON spread.BudgetConfigID = basis.BudgetConfigID AND spread.DepartmentID = basis.DepartmentID AND spread.JobCodeID = basis.JobCodeID AND spread.PayCodeGroupID = basis.PayCodeGroupID + WHERE basis.BudgetConfigID = @BudgetConfigID + AND basis.VariabilityID = 1 -- fixed + AND spread.IsInactive = 0 + AND ( + (basis.BudgetDollarsLockType <> 1 AND basis.BudgetDollarsLockType <> 7) -- Ignore Final Value and Locked Adjustments + OR (basis.BudgetHoursLockType <> 1 AND basis.BudgetHoursLockType <> 7) -- Ignore Final Value and Locked Adjustments + OR (basis.BudgetFTEsLockType <> 1 AND basis.BudgetFTEsLockType <> 7) -- Ignore Final Value and Locked Adjustments + ) + AND basis.SubsectionID = 3 -- Staffing Stuff + + END + + -- Update dollars + UPDATE dollars + SET + dollars.BudgetAdjustedDollars01 = CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01 AS DECIMAL(19,8)) + , dollars.BudgetAdjustedDollars02 = + CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN dollars.BudgetAdjustedDollarsTotal - CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02 AS DECIMAL(19,8)) END + , dollars.BudgetAdjustedDollars03 = + CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8))) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03 AS DECIMAL(19,8)) END + , dollars.BudgetAdjustedDollars04 = + CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8))) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04 AS DECIMAL(19,8)) END + , dollars.BudgetAdjustedDollars05 = + CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8))) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05 AS DECIMAL(19,8)) END + , dollars.BudgetAdjustedDollars06 = + CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8))) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06 AS DECIMAL(19,8)) END + , dollars.BudgetAdjustedDollars07 = + CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8))) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07 AS DECIMAL(19,8)) END + , dollars.BudgetAdjustedDollars08 = + CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07) AS DECIMAL(19, 8))) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage08 AS DECIMAL(19,8)) END + , dollars.BudgetAdjustedDollars09 = + CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage08) AS DECIMAL(19, 8))) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage09 AS DECIMAL(19,8)) END + , dollars.BudgetAdjustedDollars10 = + CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage09) AS DECIMAL(19, 8))) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage10 AS DECIMAL(19,8)) END + , dollars.BudgetAdjustedDollars11 = + CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 + THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage10) AS DECIMAL(19, 8))) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage11 AS DECIMAL(19,8)) END + , dollars.BudgetAdjustedDollars12 = + CASE WHEN SpreadPercentage12 != 0 + THEN dollars.BudgetAdjustedDollarsTotal - (CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((dollars.BudgetAdjustedDollarsTotal * SpreadPercentage11) AS DECIMAL(19, 8))) + ELSE CAST(dollars.BudgetAdjustedDollarsTotal * SpreadPercentage12 AS DECIMAL(19,8)) END + , BudgetDollarsLockType = CASE WHEN dollars.BudgetDollarsLockType IN (1,4,5) THEN dollars.BudgetDollarsLockType ELSE 6 END + , BudgetDollarsLockFlag = 1 + OUTPUT + inserted.StaffingID, 34, + deleted.BudgetAdjustedDollars01, deleted.BudgetAdjustedDollars02, deleted.BudgetAdjustedDollars03, deleted.BudgetAdjustedDollars04, deleted.BudgetAdjustedDollars05, deleted.BudgetAdjustedDollars06, + deleted.BudgetAdjustedDollars07, deleted.BudgetAdjustedDollars08, deleted.BudgetAdjustedDollars09, deleted.BudgetAdjustedDollars10, deleted.BudgetAdjustedDollars11, deleted.BudgetAdjustedDollars12, + inserted.BudgetAdjustedDollars01, inserted.BudgetAdjustedDollars02, inserted.BudgetAdjustedDollars03, inserted.BudgetAdjustedDollars04, inserted.BudgetAdjustedDollars05, inserted.BudgetAdjustedDollars06, + inserted.BudgetAdjustedDollars07, inserted.BudgetAdjustedDollars08, inserted.BudgetAdjustedDollars09, inserted.BudgetAdjustedDollars10, inserted.BudgetAdjustedDollars11, inserted.BudgetAdjustedDollars12 + INTO + #spreadsChangeHistory (StaffingID, UnitTypeID, + OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06, + OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12, + NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06, + NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) + FROM [fp].[viewStaffingSpreads] spread + INNER JOIN [fp].[Staffing] dollars ON spread.BudgetConfigID = dollars.BudgetConfigID + AND spread.DepartmentID = dollars.DepartmentID + AND spread.JobCodeID = dollars.JobCodeID + AND spread.PayCodeGroupID = dollars.PayCodeGroupID + INNER JOIN #filterTable tmp on dollars.StaffingID = tmp.StaffingID + WHERE spread.IsInactive = 0 + AND ((BudgetAdjustedHours01 = 0 + AND BudgetAdjustedHours02 = 0 + AND BudgetAdjustedHours03 = 0 + AND BudgetAdjustedHours04 = 0 + AND BudgetAdjustedHours05 = 0 + AND BudgetAdjustedHours06 = 0 + AND BudgetAdjustedHours07 = 0 + AND BudgetAdjustedHours08 = 0 + AND BudgetAdjustedHours09 = 0 + AND BudgetAdjustedHours10 = 0 + AND BudgetAdjustedHours11 = 0 + AND BudgetAdjustedHours12 = 0)) + + -- Update hours + UPDATE hours + SET + hours.BudgetAdjustedHours01 = CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage01 AS DECIMAL(19,8)) + , hours.BudgetAdjustedHours02 = + CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN hours.BudgetAdjustedHoursTotal - CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage02 AS DECIMAL(19,8)) END + , hours.BudgetAdjustedHours03 = + CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8))) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage03 AS DECIMAL(19,8)) END + , hours.BudgetAdjustedHours04 = + CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8))) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage04 AS DECIMAL(19,8)) END + , hours.BudgetAdjustedHours05 = + CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8))) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage05 AS DECIMAL(19,8)) END + , hours.BudgetAdjustedHours06 = + CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8))) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage06 AS DECIMAL(19,8)) END + , hours.BudgetAdjustedHours07 = + CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8))) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage07 AS DECIMAL(19,8)) END + , hours.BudgetAdjustedHours08 = + CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage07) AS DECIMAL(19, 8))) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage08 AS DECIMAL(19,8)) END + , hours.BudgetAdjustedHours09 = + CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage08) AS DECIMAL(19, 8))) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage09 AS DECIMAL(19,8)) END + , hours.BudgetAdjustedHours10 = + CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage09) AS DECIMAL(19, 8))) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage10 AS DECIMAL(19,8)) END + , hours.BudgetAdjustedHours11 = + CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 + THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage10) AS DECIMAL(19, 8))) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage11 AS DECIMAL(19,8)) END + , hours.BudgetAdjustedHours12 = + CASE WHEN SpreadPercentage12 != 0 + THEN hours.BudgetAdjustedHoursTotal - (CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((hours.BudgetAdjustedHoursTotal * SpreadPercentage11) AS DECIMAL(19, 8))) + ELSE CAST(hours.BudgetAdjustedHoursTotal * SpreadPercentage12 AS DECIMAL(19,8)) END + , BudgetHoursLockType = CASE WHEN BudgetHoursLockType IN (1,4,5) THEN BudgetHoursLockType ELSE 6 END + , BudgetHoursLockFlag = 1 + OUTPUT + inserted.StaffingID, 51, + deleted.BudgetAdjustedHours01, deleted.BudgetAdjustedHours02, deleted.BudgetAdjustedHours03, deleted.BudgetAdjustedHours04, deleted.BudgetAdjustedHours05, deleted.BudgetAdjustedHours06, + deleted.BudgetAdjustedHours07, deleted.BudgetAdjustedHours08, deleted.BudgetAdjustedHours09, deleted.BudgetAdjustedHours10, deleted.BudgetAdjustedHours11, deleted.BudgetAdjustedHours12, + inserted.BudgetAdjustedHours01, inserted.BudgetAdjustedHours02, inserted.BudgetAdjustedHours03, inserted.BudgetAdjustedHours04, inserted.BudgetAdjustedHours05, inserted.BudgetAdjustedHours06, + inserted.BudgetAdjustedHours07, inserted.BudgetAdjustedHours08, inserted.BudgetAdjustedHours09, inserted.BudgetAdjustedHours10, inserted.BudgetAdjustedHours11, inserted.BudgetAdjustedHours12 + INTO + #spreadsChangeHistory (StaffingID, UnitTypeID, + OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06, + OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12, + NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06, + NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) + FROM [fp].[viewStaffingSpreads] spread + INNER JOIN [fp].[Staffing] hours ON spread.BudgetConfigID = hours.BudgetConfigID + AND spread.DepartmentID = hours.DepartmentID + AND spread.JobCodeID = hours.JobCodeID + AND spread.PayCodeGroupID = hours.PayCodeGroupID + INNER JOIN #filterTable tmp on hours.StaffingID = tmp.StaffingID + WHERE spread.IsInactive = 0 + AND (hours.BudgetAdjustedHours01 <> 0 + OR hours.BudgetAdjustedHours02 <> 0 + OR hours.BudgetAdjustedHours03 <> 0 + OR hours.BudgetAdjustedHours04 <> 0 + OR hours.BudgetAdjustedHours05 <> 0 + OR hours.BudgetAdjustedHours06 <> 0 + OR hours.BudgetAdjustedHours07 <> 0 + OR hours.BudgetAdjustedHours08 <> 0 + OR hours.BudgetAdjustedHours09 <> 0 + OR hours.BudgetAdjustedHours10 <> 0 + OR hours.BudgetAdjustedHours11 <> 0 + OR hours.BudgetAdjustedHours12 <> 0) + + -- Recalculate FTEs based on Hours + UPDATE ftes + SET + ftes.BudgetAdjustedFTEs01 = CASE WHEN hours.BudgetWorkingHours01 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours01 / hours.BudgetWorkingHours01 END, + ftes.BudgetAdjustedFTEs02 = CASE WHEN hours.BudgetWorkingHours02 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours02 / hours.BudgetWorkingHours02 END, + ftes.BudgetAdjustedFTEs03 = CASE WHEN hours.BudgetWorkingHours03 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours03 / hours.BudgetWorkingHours03 END, + ftes.BudgetAdjustedFTEs04 = CASE WHEN hours.BudgetWorkingHours04 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours04 / hours.BudgetWorkingHours04 END, + ftes.BudgetAdjustedFTEs05 = CASE WHEN hours.BudgetWorkingHours05 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours05 / hours.BudgetWorkingHours05 END, + ftes.BudgetAdjustedFTEs06 = CASE WHEN hours.BudgetWorkingHours06 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours06 / hours.BudgetWorkingHours06 END, + ftes.BudgetAdjustedFTEs07 = CASE WHEN hours.BudgetWorkingHours07 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours07 / hours.BudgetWorkingHours07 END, + ftes.BudgetAdjustedFTEs08 = CASE WHEN hours.BudgetWorkingHours08 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours08 / hours.BudgetWorkingHours08 END, + ftes.BudgetAdjustedFTEs09 = CASE WHEN hours.BudgetWorkingHours09 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours09 / hours.BudgetWorkingHours09 END, + ftes.BudgetAdjustedFTEs10 = CASE WHEN hours.BudgetWorkingHours10 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours10 / hours.BudgetWorkingHours10 END, + ftes.BudgetAdjustedFTEs11 = CASE WHEN hours.BudgetWorkingHours11 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours11 / hours.BudgetWorkingHours11 END, + ftes.BudgetAdjustedFTEs12 = CASE WHEN hours.BudgetWorkingHours12 = 0 THEN 0 ELSE ftes.BudgetAdjustedHours12 / hours.BudgetWorkingHours12 END, + ftes.BudgetFTEsLockType = CASE WHEN ftes.BudgetFTEsLockType IN (1,4,5) THEN ftes.BudgetFTEsLockType ELSE 6 END, + ftes.BudgetFTEsLockFlag = 1 + OUTPUT + inserted.StaffingID, 144, + deleted.BudgetAdjustedFTEs01, deleted.BudgetAdjustedFTEs02, deleted.BudgetAdjustedFTEs03, deleted.BudgetAdjustedFTEs04, deleted.BudgetAdjustedFTEs05, deleted.BudgetAdjustedFTEs06, + deleted.BudgetAdjustedFTEs07, deleted.BudgetAdjustedFTEs08, deleted.BudgetAdjustedFTEs09, deleted.BudgetAdjustedFTEs10, deleted.BudgetAdjustedFTEs11, deleted.BudgetAdjustedFTEs12, + inserted.BudgetAdjustedFTEs01, inserted.BudgetAdjustedFTEs02, inserted.BudgetAdjustedFTEs03, inserted.BudgetAdjustedFTEs04, inserted.BudgetAdjustedFTEs05, inserted.BudgetAdjustedFTEs06, + inserted.BudgetAdjustedFTEs07, inserted.BudgetAdjustedFTEs08, inserted.BudgetAdjustedFTEs09, inserted.BudgetAdjustedFTEs10, inserted.BudgetAdjustedFTEs11, inserted.BudgetAdjustedFTEs12 + INTO + #spreadsChangeHistory (StaffingID, UnitTypeID, + OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06, + OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12, + NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06, + NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) + FROM [fp].[Staffing] ftes + INNER JOIN [fp].[viewWorkingHours] hours + ON ftes.DepartmentID = hours.DepartmentID + AND ftes.EntityID = hours.EntityID + AND ftes.JobCodeID = hours.JobCodeID + AND ftes.PayCodeGroupID = hours.PayCodeGroupID + AND ftes.ProductiveClassID = hours.ProductiveClassID + AND ftes.EntityGroupConfigID = hours.EntityGroupConfigID + AND ftes.EmployeeID = hours.EmployeeID + AND ftes.VariabilityID = hours.VariabilityID + INNER JOIN #filterTable f ON f.StaffingID = ftes.StaffingID + WHERE + ftes.VariabilityID = 1 + AND ftes.ProductiveClassID NOT IN (4, 5, 6) -- Dollars-Only, Differential, Productive Non-FTE + AND (ftes.BudgetAdjustedHours01 <> 0 + OR ftes.BudgetAdjustedHours02 <> 0 + OR ftes.BudgetAdjustedHours03 <> 0 + OR ftes.BudgetAdjustedHours04 <> 0 + OR ftes.BudgetAdjustedHours05 <> 0 + OR ftes.BudgetAdjustedHours06 <> 0 + OR ftes.BudgetAdjustedHours07 <> 0 + OR ftes.BudgetAdjustedHours08 <> 0 + OR ftes.BudgetAdjustedHours09 <> 0 + OR ftes.BudgetAdjustedHours10 <> 0 + OR ftes.BudgetAdjustedHours11 <> 0 + OR ftes.BudgetAdjustedHours12 <> 0) + + -- Recalculate Dollars based on Hours and Wage Rate + UPDATE base + SET + base.BudgetAdjustedDollars01 = BudgetAdjustedHours01 * wageRate.BudgetAdjusted01, + base.BudgetAdjustedDollars02 = BudgetAdjustedHours02 * wageRate.BudgetAdjusted02, + base.BudgetAdjustedDollars03 = BudgetAdjustedHours03 * wageRate.BudgetAdjusted03, + base.BudgetAdjustedDollars04 = BudgetAdjustedHours04 * wageRate.BudgetAdjusted04, + base.BudgetAdjustedDollars05 = BudgetAdjustedHours05 * wageRate.BudgetAdjusted05, + base.BudgetAdjustedDollars06 = BudgetAdjustedHours06 * wageRate.BudgetAdjusted06, + base.BudgetAdjustedDollars07 = BudgetAdjustedHours07 * wageRate.BudgetAdjusted07, + base.BudgetAdjustedDollars08 = BudgetAdjustedHours08 * wageRate.BudgetAdjusted08, + base.BudgetAdjustedDollars09 = BudgetAdjustedHours09 * wageRate.BudgetAdjusted09, + base.BudgetAdjustedDollars10 = BudgetAdjustedHours10 * wageRate.BudgetAdjusted10, + base.BudgetAdjustedDollars11 = BudgetAdjustedHours11 * wageRate.BudgetAdjusted11, + base.BudgetAdjustedDollars12 = BudgetAdjustedHours12 * wageRate.BudgetAdjusted12 + OUTPUT + inserted.StaffingID, 34, + deleted.BudgetAdjustedDollars01, deleted.BudgetAdjustedDollars02, deleted.BudgetAdjustedDollars03, deleted.BudgetAdjustedDollars04, deleted.BudgetAdjustedDollars05, deleted.BudgetAdjustedDollars06, + deleted.BudgetAdjustedDollars07, deleted.BudgetAdjustedDollars08, deleted.BudgetAdjustedDollars09, deleted.BudgetAdjustedDollars10, deleted.BudgetAdjustedDollars11, deleted.BudgetAdjustedDollars12, + inserted.BudgetAdjustedDollars01, inserted.BudgetAdjustedDollars02, inserted.BudgetAdjustedDollars03, inserted.BudgetAdjustedDollars04, inserted.BudgetAdjustedDollars05, inserted.BudgetAdjustedDollars06, + inserted.BudgetAdjustedDollars07, inserted.BudgetAdjustedDollars08, inserted.BudgetAdjustedDollars09, inserted.BudgetAdjustedDollars10, inserted.BudgetAdjustedDollars11, inserted.BudgetAdjustedDollars12 + INTO + #spreadsChangeHistory (StaffingID, UnitTypeID, + OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06, + OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12, + NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06, + NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) + FROM [fp].[Staffing] base + INNER JOIN fp.StaffingWageRate wageRate on base.StaffingWageRateID = wageRate.StaffingWageRateID + INNER JOIN #filterTable f ON f.StaffingID = base.StaffingID + WHERE + base.VariabilityID = 1 + AND (BudgetAdjustedHours01 <> 0 + OR BudgetAdjustedHours02 <> 0 + OR BudgetAdjustedHours03 <> 0 + OR BudgetAdjustedHours04 <> 0 + OR BudgetAdjustedHours05 <> 0 + OR BudgetAdjustedHours06 <> 0 + OR BudgetAdjustedHours07 <> 0 + OR BudgetAdjustedHours08 <> 0 + OR BudgetAdjustedHours09 <> 0 + OR BudgetAdjustedHours10 <> 0 + OR BudgetAdjustedHours11 <> 0 + OR BudgetAdjustedHours12 <> 0) + OPTION(RECOMPILE) + + -- Populate Change History + IF EXISTS(SELECT 1 + FROM fp.BudgetConfigSetting setting + INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON setting.SettingID = def.SettingID + WHERE def.Name = 'Spreads Change History Logic Is Enabled' + AND setting.Value = 1 AND setting.BudgetConfigID = @BudgetConfigID) + BEGIN + + INSERT INTO fp.StaffingSpreadsChangeHistory (StaffingID, BudgetConfigID, SubsectionID, UnitTypeID, OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06, + OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12, NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06, + NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) + SELECT StaffingID, @BudgetConfigID, 3, UnitTypeID, + ISNULL(OldValue01, 0), ISNULL(OldValue02, 0), ISNULL(OldValue03, 0), ISNULL(OldValue04, 0), ISNULL(OldValue05, 0), ISNULL(OldValue06, 0), + ISNULL(OldValue07, 0), ISNULL(OldValue08, 0), ISNULL(OldValue09, 0), ISNULL(OldValue10, 0), ISNULL(OldValue11, 0), ISNULL(OldValue12, 0), + ISNULL(NewValue01, 0), ISNULL(NewValue02, 0), ISNULL(NewValue03, 0), ISNULL(NewValue04, 0), ISNULL(NewValue05, 0), ISNULL(NewValue06, 0), + ISNULL(NewValue07, 0), ISNULL(NewValue08, 0), ISNULL(NewValue09, 0), ISNULL(NewValue10, 0), ISNULL(NewValue11, 0), ISNULL(NewValue12, 0) + FROM #spreadsChangeHistory + WHERE 1 = 1 + AND ( + OldValue01 != NewValue01 + OR OldValue02 != NewValue02 + OR OldValue03 != NewValue03 + OR OldValue04 != NewValue04 + OR OldValue05 != NewValue05 + OR OldValue06 != NewValue06 + OR OldValue07 != NewValue07 + OR OldValue08 != NewValue08 + OR OldValue09 != NewValue09 + OR OldValue10 != NewValue10 + OR OldValue11 != NewValue11 + OR OldValue12 != NewValue12 + ) + + END + +END +GO + + +--------------------------------------------- + +-- fp.procStaffingBudgetStampOff +CREATE PROCEDURE [fp].[procStaffingBudgetStampOff] + @BudgetConfigID INT, + @TargetTimeClassID TINYINT +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 01-31-2023 MY JAZZ-48962 Initial Creation + ** 2 01-03-2024 MZ JAZZ-65385 Added Target TimeClass + ** 3 12-04-2023 BW/MZ JAZZ-63562 Data model restructure for Staffing/Merge with main + ** 4 03-18-2024 MZ JAZZ-68428 Deleting by Chunks & removed HistoryItemGUID parameter + ** 5 04-22-2024 NH JAZZ-69921 Provider Submission during Stamp-off: During Stamp-off process populate Employee ID in int.factstaffing when data comes from Provider Comp + ** 6 10-18-2024 VZ JAZZ-77158 Added join on jobcode to avoid duplication + *************************************************************/ + + -- Note: The original script was done here https://stratadecision.atlassian.net/wiki/spaces/DD/pages/3116205785/Moving+Data+from+a+Plan+Configuration+to+Int+Tables + + DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID ) + DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID) + + DECLARE @HistoryItemGUID UNIQUEIDENTIFIER + EXEC procLogScript 'StampOff: Transferring Budget Data from 1p', @HistoryItemGUID OUTPUT + PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36)) + PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID) + + -- Clear out existing records for the selected FiscalYear and Budgeted Time Class + DECLARE @ChunkCount INT + + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END + + DECLARE @r INT; + SET @r = 1; + + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) FROM [int].[FactStaffing] WHERE FiscalYearID = @FiscalYear and TimeClassID = @TargetTimeClassID + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + IF OBJECT_ID('tempdb..#emp') IS NOT NULL DROP TABLE #emp + CREATE TABLE #emp (PhysicianID INT, EmployeeID INT, EmployeeCode varchar(200), JobCodeID INT) + INSERT INTO #emp (PhysicianID, EmployeeID, EmployeeCode, JobCodeID) + SELECT + dp.PhysicianID, + de.EmployeeID, + de.Code EmployeeCode, + de.JobCodeID + FROM dss.DimPhysician dp + INNER JOIN fw.dimemployee de ON dp.npi = de.npi + WHERE de.NPI NOT IN ('Not Specified', '0', '') + AND isFP = 1 + INSERT INTO [int].[FactStaffing] (DepartmentID, DepartmentCode, JobCodeID, JobCode, PayCodeID, PayCode, FiscalYearID, FiscalYearCode, TimeClassID, + TimeClassCode, UnitTypeID, UnitType, FiscalMonthID, FiscalMonthCode, Value, IsDeleted, HistoryItemGUID, EmployeeID,EmployeeCode) + SELECT + d.DepartmentID, + d.DepartmentCode, + jc.JobCodeID, + jc.JobCode, + pc.PayCodeID, + pc.PayCode, + bc.FiscalYearID, + bc.FiscalYearID AS FiscalYearCode, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + UT.UnitTypeID, + UT.Name AS [UnitType], + m.FiscalMonthID, + m.FiscalMonthCode, + Value AS Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID, + CASE + WHEN pcemp.EmployeeID is NULL THEN emp.EmployeeID -- Valid Ids if employee budgeting enabled + ELSE pcemp.EmployeeID + END AS EmployeeID, + CASE + WHEN emp.EmployeeID > 0 OR pcemp.EmployeeID is NULL THEN emp.Code --Valid Code, if employee budgeting enabled + ELSE pcemp.EmployeeCode + END AS EmployeeCode + FROM [fp].[Staffing] staff (READUNCOMMITTED) + CROSS APPLY ( + VALUES + ( 1, 34, BudgetAdjustedDollars01), + ( 2, 34, BudgetAdjustedDollars02), + ( 3, 34, BudgetAdjustedDollars03), + ( 4, 34, BudgetAdjustedDollars04), + ( 5, 34, BudgetAdjustedDollars05), + ( 6, 34, BudgetAdjustedDollars06), + ( 7, 34, BudgetAdjustedDollars07), + ( 8, 34, BudgetAdjustedDollars08), + ( 9, 34, BudgetAdjustedDollars09), + ( 10, 34, BudgetAdjustedDollars10), + ( 11, 34, BudgetAdjustedDollars11), + ( 12, 34, BudgetAdjustedDollars12), + ( 1, 51, BudgetAdjustedHours01), + ( 2, 51, BudgetAdjustedHours02), + ( 3, 51, BudgetAdjustedHours03), + ( 4, 51, BudgetAdjustedHours04), + ( 5, 51, BudgetAdjustedHours05), + ( 6, 51, BudgetAdjustedHours06), + ( 7, 51, BudgetAdjustedHours07), + ( 8, 51, BudgetAdjustedHours08), + ( 9, 51, BudgetAdjustedHours09), + ( 10, 51, BudgetAdjustedHours10), + ( 11, 51, BudgetAdjustedHours11), + ( 12, 51, BudgetAdjustedHours12), + ( 1, 144, BudgetAdjustedFTEs01), + ( 2, 144, BudgetAdjustedFTEs02), + ( 3, 144, BudgetAdjustedFTEs03), + ( 4, 144, BudgetAdjustedFTEs04), + ( 5, 144, BudgetAdjustedFTEs05), + ( 6, 144, BudgetAdjustedFTEs06), + ( 7, 144, BudgetAdjustedFTEs07), + ( 8, 144, BudgetAdjustedFTEs08), + ( 9, 144, BudgetAdjustedFTEs09), + ( 10, 144, BudgetAdjustedFTEs10), + ( 11, 144, BudgetAdjustedFTEs11), + ( 12, 144, BudgetAdjustedFTEs12), + ( 1, 172, BudgetAdjustedRate01), + ( 2, 172, BudgetAdjustedRate02), + ( 3, 172, BudgetAdjustedRate03), + ( 4, 172, BudgetAdjustedRate04), + ( 5, 172, BudgetAdjustedRate05), + ( 6, 172, BudgetAdjustedRate06), + ( 7, 172, BudgetAdjustedRate07), + ( 8, 172, BudgetAdjustedRate08), + ( 9, 172, BudgetAdjustedRate09), + ( 10, 172, BudgetAdjustedRate10), + ( 11, 172, BudgetAdjustedRate11), + ( 12, 172, BudgetAdjustedRate12) + ) AS CrossApplied (FiscalMonth, UnitTypeID, Value) + LEFT JOIN [fw].[DimUnitType] ut ON ut.UnitTypeID = CrossApplied.UnitTypeID + LEFT JOIN [fw].[DimFiscalMonth] m ON m.SortOrder = CrossApplied.FiscalMonth + INNER JOIN [fw].[DimJobCode] jc ON jc.JobCodeID = staff.JobCodeID + INNER JOIN [fw].[DimPayCodeGroup] PCG ON PCG.PayCodeGroupID = staff.PayCodeGroupID + INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = PCG.DefaultPayCodeID + INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = staff.DepartmentID + INNER JOIN [fw].[DimEmployee] Emp ON emp.employeeid = staff.Employeeid -- Keeping employeeids for anyone with employee budgeting + INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID + LEFT JOIN #emp pcemp on staff.ProviderID = pcemp.PhysicianID AND staff.JobCodeID = pcemp.JobCodeID + WHERE staff.BudgetConfigID = @BudgetConfigID + AND Value <> 0 + UNION ALL + SELECT + d.DepartmentID, + d.DepartmentCode, + jc.JobCodeID, + jc.JobCode, + pc.PayCodeID, + pc.PayCode, + bc.FiscalYearID, + bc.FiscalYearID AS FiscalYearCode, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + UT.UnitTypeID, + UT.Name AS [UnitType], + m.FiscalMonthID, + m.FiscalMonthCode, + Value AS Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID, + CASE + WHEN pcemp.EmployeeID is NULL THEN emp.EmployeeID -- Valid Ids if employee budgeting enabled + ELSE pcemp.EmployeeID + END AS EmployeeID, + CASE + WHEN emp.EmployeeID > 0 OR pcemp.EmployeeID is NULL THEN emp.Code --Valid Code, if employee budgeting enabled + ELSE pcemp.EmployeeCode + END AS EmployeeCode + FROM [fp].[Staffing] staff (READUNCOMMITTED) + INNER JOIN [fp].[StaffingWageRate] wr (READUNCOMMITTED) + ON staff.StaffingWageRateID = wr.StaffingWageRateID + AND staff.VariabilityID = 1 + CROSS APPLY ( + VALUES + ( 1, 159, BudgetAdjusted01), + ( 2, 159, BudgetAdjusted02), + ( 3, 159, BudgetAdjusted03), + ( 4, 159, BudgetAdjusted04), + ( 5, 159, BudgetAdjusted05), + ( 6, 159, BudgetAdjusted06), + ( 7, 159, BudgetAdjusted07), + ( 8, 159, BudgetAdjusted08), + ( 9, 159, BudgetAdjusted09), + ( 10, 159, BudgetAdjusted10), + ( 11, 159, BudgetAdjusted11), + ( 12, 159, BudgetAdjusted12) + ) AS CrossApplied (FiscalMonth, UnitTypeID, Value) + LEFT JOIN [fw].[DimUnitType] ut ON ut.UnitTypeID = CrossApplied.UnitTypeID + LEFT JOIN [fw].[DimFiscalMonth] m ON m.SortOrder = CrossApplied.FiscalMonth + INNER JOIN [fw].[DimJobCode] jc ON jc.JobCodeID = staff.JobCodeID + INNER JOIN [fw].[DimPayCodeGroup] PCG ON PCG.PayCodeGroupID = staff.PayCodeGroupID + INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = PCG.DefaultPayCodeID + INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = staff.DepartmentID + INNER JOIN [fw].[DimEmployee] Emp ON emp.employeeid = staff.Employeeid -- Keeping employeeids for anyone with employee budgeting + INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID + LEFT JOIN #emp pcemp on staff.ProviderID = pcemp.PhysicianID AND staff.JobCodeID = pcemp.JobCodeID + WHERE staff.BudgetConfigID = @BudgetConfigID + AND Value <> 0 +END +GO + + +--------------------------------------------- + +-- fp.procStaffingByStatisticsFlexConfigPopulation +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-06-12 IP B-19913 APE Data Refresh - Flex Mappings, add parameter to process particular departments +** 2 2018-07-03 IP TK-59678 fix case when @SourceDimensionality is empty +** 3 2018-09-11 apukii TK-62350 fixed typo in code +** 4 2018-09-25 GF E-02313 Simplify source dimensionality to only department +** 5 2019-03-08 IP B-22295 Removed using table variables, small optimizations +** 6 2021-03-12 NT JAZZ-14118 simplify code and remove null joins on targeting object +** 7 2023-02-06 MY JAZZ-48980 Update flexing to support x-department flexing +** 8 2023-05-01 MY JAZZ-54277 Flex Config Mapping is not taking handling Cross Department Flexing properly +** 9 2023-11-07 MD JAZZ-62448 Update for staffing restructure +*************************************************************/ +CREATE PROCEDURE [fp].[procStaffingByStatisticsFlexConfigPopulation] + @EntityGroupConfigGUID UNIQUEIDENTIFIER , + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + DECLARE @BudgetConfigID INT, + @EntityGroupConfigID INT + + SET @BudgetConfigID = (SELECT bc.BudgetConfigID + FROM [fp].[EntityGroupConfig] egc + INNER JOIN [fp].[BudgetConfig] bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID) + SET @EntityGroupConfigID = (SELECT EntityGroupConfigID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID) + + CREATE TABLE #flexMap ( + DepartmentID INT NOT NULL, + PRJobCodeID INT NOT NULL, + StatAccountID INT NOT NULL, + SourceDepartmentID INT NOT NULL + ); + + IF OBJECT_ID('tempdb..#FilterPR') IS NOT NULL DROP TABLE #FilterPR + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + + CREATE TABLE #FilterPR (DepartmentID int, BudgetConfigID int, JobCodeID int) + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid OR NULL + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[PrimaryStatisticsConfig] + WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID + AND IsStaffing = 1 + END + + -- Build a list of Department / Job Code combinations + -- Only department/job code combinations in staffing are populated in the fp.FlexConfigMapping table. New records will be added as new dimensionality is imported in. + INSERT INTO #FilterPR + SELECT DISTINCT pr.DepartmentID, pr.BudgetConfigID, pr.JobCodeID FROM [fp].[Staffing] pr + INNER JOIN #FilterByDepartment SD on SD.DepartmentID = pr.DepartmentID + WHERE pr.VariabilityID = 2 -- Variable Only (used for filtering the data down) + + -- Populate all overrides for the revenue accounts. Overrides ignore traditional logic and override anything set at the department level. + INSERT INTO #flexMap (DepartmentID, PRJobCodeID, StatAccountID, SourceDepartmentID) + SELECT DISTINCT stat.DepartmentID, pr.JobCodeID AS PRJobCodeID, nso.AccountID AS StatAccountID, stat.DepartmentID + FROM [fp].[FactStatistics] stat + INNER JOIN #FilterPR pr ON pr.DepartmentID = stat.DepartmentID and pr.BudgetConfigID = stat.BudgetConfigID + INNER JOIN [fp].[StaffingFlexingOverrideConfig] ns ON ns.DepartmentID = pr.DepartmentID AND ns.JobCodeID = pr.JobCodeID + INNER JOIN [fp].[StaffingFlexingOverrideConfigAssignment] nso ON nso.OverrideFlexConfigGUID = ns.OverrideFlexConfigGUID and nso.AccountID = stat.AccountID + WHERE + ns.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND stat.BudgetConfigID = @BudgetConfigID + AND ns.FlexMethodID = 1 -- Statistic Accounts + + -- Process department level configuration changes that are not overriden. We also will exclude Department/job code combos + -- that have multiple source departments here as that is handled in the statement below. + -- Aka: Process the Department/job code combinations that have primary stats of "Same as Department" in the Primary Stat Config + INSERT INTO #flexMap (DepartmentID, PRJobCodeID, StatAccountID, SourceDepartmentID) + SELECT DISTINCT stat.DepartmentID, pr.JobCodeID AS PRJobCodeID, stat.AccountID AS StatAccountID, stat.DepartmentID + FROM [fp].[FactStatistics] stat + INNER JOIN [fp].[PrimaryStatisticsConfig] fsc ON fsc.DepartmentID = stat.DepartmentID AND fsc.AccountID = stat.AccountID + INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID = fsc.EntityGroupConfigGUID + INNER JOIN #FilterPR pr ON pr.DepartmentID = stat.DepartmentID and pr.BudgetConfigID = stat.BudgetConfigID + INNER JOIN [fp].[StaffingExpenseFlexingConfig] ns ON ns.DepartmentID = pr.DepartmentID + LEFT JOIN (SELECT DepartmentID, JobCodeID FROM [fp].[StaffingFlexingOverrideConfig] WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID) ovr + ON ovr.DepartmentID = stat.DepartmentID + AND ovr.JobCodeID = pr.JobCodeID + LEFT JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscsd ON fsc.RowID = pscsd.PrimaryStatisticsConfigID + WHERE + fsc.IsStaffing = 1 + AND fsc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND ns.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND stat.BudgetConfigID = @BudgetConfigID + AND ns.FlexMethodID = 1 -- Statistic Accounts + AND ovr.DepartmentID IS NULL -- We only want records that are not overridden + AND pscsd.DepartmentID IS NULL; -- We want records where there is no source department specified. When no source department is specified, it's the same as the regular department + + -- Process departments with multiple source departments + INSERT INTO #flexMap (DepartmentID, PRJobCodeID, StatAccountID, SourceDepartmentID) + SELECT DISTINCT fsc.DepartmentID, pr.JobCodeID AS PRJobCodeID, stat.AccountID AS StatAccountID, pscsd.DepartmentID + FROM [fp].[PrimaryStatisticsConfig] fsc + INNER JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscsd ON fsc.RowID = pscsd.PrimaryStatisticsConfigID + INNER JOIN [fp].[FactStatistics] stat ON pscsd.DepartmentID = stat.DepartmentID AND fsc.AccountID = stat.AccountID + INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID = fsc.EntityGroupConfigGUID + INNER JOIN #FilterPR pr ON pr.DepartmentID = fsc.DepartmentID and pr.BudgetConfigID = stat.BudgetConfigID + INNER JOIN [fp].[StaffingExpenseFlexingConfig] ns ON ns.DepartmentID = fsc.DepartmentID + LEFT JOIN ( + SELECT DepartmentID, JobCodeID + FROM [fp].[StaffingFlexingOverrideConfig] + WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID + ) ovr + ON ovr.DepartmentID = fsc.DepartmentID + AND ovr.JobCodeID = pr.JobCodeID + WHERE + fsc.IsStaffing = 1 + AND fsc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND ns.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND stat.BudgetConfigID = @BudgetConfigID + AND ns.FlexMethodID = 1 -- Statistic Accounts + AND ovr.DepartmentID IS NULL; -- We only want records that are not overridden + + IF @IsDebug = 1 + BEGIN + SELECT '#FilterByDepartment', DepartmentID FROM #FilterByDepartment + SELECT '#FilterPR', DepartmentID, BudgetConfigID, JobCodeID FROM #FilterPR + SELECT '#flexMap', @EntityGroupConfigID AS EntityGroupConfigID, DepartmentID, PRJobCodeID, StatAccountID, 3 AS FlexingTypeID, SourceDepartmentID FROM #flexMap + END ELSE + BEGIN + + ;WITH TRG AS + ( + SELECT EntityGroupConfigID, fcm.DepartmentID, fcm.PRJobCodeID, fcm.StatAccountID, fcm.FlexingTypeID, SourceDepartmentID + FROM [fp].[FlexConfigMapping] fcm + INNER JOIN #FilterByDepartment SD + ON SD.DepartmentID = fcm.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND FlexingTypeID = 3 -- Staffing Flexing Type + ) + + MERGE TRG + USING (SELECT @EntityGroupConfigID AS EntityGroupConfigID, + DepartmentID, + PRJobCodeID, + StatAccountID, + 3 AS FlexingTypeID, -- Staffing Flexing Type + SourceDepartmentID + FROM #flexMap) AS Src ON TRG.DepartmentID = SRC.DepartmentID + AND TRG.PRJobCodeID = SRC.PRJobCodeID + AND TRG.StatAccountID = SRC.StatAccountID + AND TRG.SourceDepartmentID = SRC.SourceDepartmentID + WHEN NOT MATCHED BY TARGET THEN + INSERT VALUES (src.EntityGroupConfigID, src.DepartmentID, src.PRJobCodeID, src.StatAccountID, src.FlexingTypeID, src.SourceDepartmentID) + WHEN NOT MATCHED BY SOURCE THEN DELETE; + + END + + END +GO + + +--------------------------------------------- + +-- fp.procStaffingCopyNewItems +CREATE PROCEDURE [fp].[procStaffingCopyNewItems] + @SourceBudgetConfigID INT, + @SourceEntityGroupConfigID INT, + @BudgetConfigID INT, + @EntityGroupConfigID INT +AS +BEGIN + +/************************************************************* +** Description +************************************************************** +** Copy the dimensionality of IsNew Staffing rows to the new +** plan. IsNew rows are not sourced from INT tables and need +** to be copied from the Copy From related budget to the +** Copy To related budget. +************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2021-06-28 NT JAZZ-21664 Add missing provider dimensions +** 2 2023-11-17 Matt Hayden JAZZ-63563 Staffing restructure change +*************************************************************/ +INSERT INTO [fp].[Staffing] +( + [BudgetConfigID] +, [EntityGroupConfigID] +, [EntityID] +, [DepartmentID] +, [JobCodeID] +, [PayCodeGroupID] +, [ProductiveClassID] +, [ProviderID] +, [ProviderLineItemID] +, [ProviderTypeID] +, [ProviderSpecialtyID] +, [EmployeeID] +, [VariabilityID] +, [AddDate] +, [IsNew] +, [SubsectionID] +, [FixedVariabilityPercentage] +, [FlexingTypeID] +) +SELECT + @BudgetConfigID +, @EntityGroupConfigID +, [EntityID] +, [DepartmentID] +, [JobCodeID] +, [PayCodeGroupID] +, [ProductiveClassID] +, [ProviderID] +, [ProviderLineItemID] +, [ProviderTypeID] +, [ProviderSpecialtyID] +, [EmployeeID] +, [VariabilityID] +, [AddDate] +, [IsNew] +, [SubsectionID] +, [FixedVariabilityPercentage] +, [FlexingTypeID] +FROM [fp].[Staffing] +WHERE BudgetConfigID = @SourceBudgetConfigID + AND EntityGroupConfigID = @SourceEntityGroupConfigID + AND IsNew = 1 + +END +GO + + +--------------------------------------------- + +-- fp.procStaffingProjectionStampOff +CREATE PROCEDURE [fp].[procStaffingProjectionStampOff] + @BudgetConfigID INT, + @TargetTimeClassID TINYINT, + @IsMonthsLoadedIncluded BIT +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 11-10-2023 AO JAZZ-62128 Initial Creation + ** 2 01-04-2024 MZ JAZZ-65385 Added Target TimeClass and IsMonthsLoadedIncluded + ** 3 01-24-2024 MZ JAZZ-64527 Fix Months Loaded + ** 4 12-04-2023 BW/MZ JAZZ-63562 Data model restructure for Staffing/Merge with main + ** 5 03-18-2024 MZ JAZZ-68428 Deleting by Chunks & removed HistoryItemGUID parameter + ** 6 04-03-2024 MZ JAZZ-70053 Fix Month Loaded excluding logic + ** 7 04-22-2024 NH JAZZ-69921 Provider Submission during Stamp-off: During Stamp-off process populate Employee ID in int.factstaffing when data comes from Provider Comp + ** 8 10-18-2024 VZ JAZZ-77158 Added join on jobcode to avoid duplication + *************************************************************/ + + -- Note: The original script was done here https://stratadecision.atlassian.net/wiki/spaces/DD/pages/3116205785/Moving+Data+from+a+Plan+Configuration+to+Int+Tables + + DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID - 1 FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID ) + DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID) + DECLARE @MonthsLoaded INT = (SELECT bc.MonthsLoaded FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID) + + DECLARE @HistoryItemGUID UNIQUEIDENTIFIER + EXEC procLogScript 'StampOff: Transferring Projection Data from 1p', @HistoryItemGUID OUTPUT + PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36)) + PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID) + + -- Clear out existing records for the selected FiscalYear and Projected Time Class + -- and all months if months loaded included otherwise only months NOT loaded will be cleared + DECLARE @ChunkCount INT + + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END + + DECLARE @r INT; + SET @r = 1; + + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) s FROM [int].[FactStaffing] s + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = s.FiscalMonthID + WHERE s.FiscalYearID = @FiscalYear + AND s.TimeClassID = @TargetTimeClassID + AND (@IsMonthsLoadedIncluded = 1 OR fm.SortOrder > @MonthsLoaded) + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + IF OBJECT_ID('tempdb..#emp') IS NOT NULL DROP TABLE #emp + CREATE TABLE #emp (PhysicianID INT, EmployeeID INT, EmployeeCode varchar(200), JobCodeID INT) + + INSERT INTO #emp (PhysicianID, EmployeeID, EmployeeCode, JobCodeID) + SELECT + dp.PhysicianID, + de.EmployeeID, + de.Code EmployeeCode, + de.JobCodeID + FROM dss.DimPhysician dp + INNER JOIN fw.dimemployee de ON dp.npi = de.npi + WHERE de.NPI NOT IN ('Not Specified', '0', '') + AND isFP = 1 + + INSERT INTO [int].[FactStaffing] (DepartmentID, DepartmentCode, JobCodeID, JobCode, PayCodeID, PayCode, FiscalYearID, FiscalYearCode, TimeClassID, + TimeClassCode, UnitTypeID, UnitType, FiscalMonthID, FiscalMonthCode, Value, IsDeleted, HistoryItemGUID, EmployeeID, EmployeeCode) + SELECT + d.DepartmentID, + d.DepartmentCode, + jc.JobCodeID, + jc.JobCode, + pc.PayCodeID, + pc.PayCode, + @FiscalYear, + @FiscalYear AS FiscalYearCode, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + UT.UnitTypeID, + UT.Name AS [UnitType], + m.FiscalMonthID, + m.FiscalMonthCode, + Value AS Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID, + CASE + WHEN pcemp.EmployeeID is NULL THEN emp.EmployeeID -- Valid Ids if employee budgeting enabled + ELSE pcemp.EmployeeID + END AS EmployeeID, + CASE + WHEN emp.EmployeeID > 0 OR pcemp.EmployeeID is NULL THEN emp.Code --Valid Code, if employee budgeting enabled + ELSE pcemp.EmployeeCode + END AS EmployeeCode + FROM [fp].[Staffing] staff (READUNCOMMITTED) + CROSS APPLY ( + VALUES + ( 1, 34, ProjectionAdjustedDollars01), + ( 2, 34, ProjectionAdjustedDollars02), + ( 3, 34, ProjectionAdjustedDollars03), + ( 4, 34, ProjectionAdjustedDollars04), + ( 5, 34, ProjectionAdjustedDollars05), + ( 6, 34, ProjectionAdjustedDollars06), + ( 7, 34, ProjectionAdjustedDollars07), + ( 8, 34, ProjectionAdjustedDollars08), + ( 9, 34, ProjectionAdjustedDollars09), + ( 10, 34, ProjectionAdjustedDollars10), + ( 11, 34, ProjectionAdjustedDollars11), + ( 12, 34, ProjectionAdjustedDollars12), + + ( 1, 51, ProjectionAdjustedHours01), + ( 2, 51, ProjectionAdjustedHours02), + ( 3, 51, ProjectionAdjustedHours03), + ( 4, 51, ProjectionAdjustedHours04), + ( 5, 51, ProjectionAdjustedHours05), + ( 6, 51, ProjectionAdjustedHours06), + ( 7, 51, ProjectionAdjustedHours07), + ( 8, 51, ProjectionAdjustedHours08), + ( 9, 51, ProjectionAdjustedHours09), + ( 10, 51, ProjectionAdjustedHours10), + ( 11, 51, ProjectionAdjustedHours11), + ( 12, 51, ProjectionAdjustedHours12), + + ( 1, 144, ProjectionAdjustedFTEs01), + ( 2, 144, ProjectionAdjustedFTEs02), + ( 3, 144, ProjectionAdjustedFTEs03), + ( 4, 144, ProjectionAdjustedFTEs04), + ( 5, 144, ProjectionAdjustedFTEs05), + ( 6, 144, ProjectionAdjustedFTEs06), + ( 7, 144, ProjectionAdjustedFTEs07), + ( 8, 144, ProjectionAdjustedFTEs08), + ( 9, 144, ProjectionAdjustedFTEs09), + ( 10, 144, ProjectionAdjustedFTEs10), + ( 11, 144, ProjectionAdjustedFTEs11), + ( 12, 144, ProjectionAdjustedFTEs12), + + ( 1, 172, ProjectionAdjustedRate01), + ( 2, 172, ProjectionAdjustedRate02), + ( 3, 172, ProjectionAdjustedRate03), + ( 4, 172, ProjectionAdjustedRate04), + ( 5, 172, ProjectionAdjustedRate05), + ( 6, 172, ProjectionAdjustedRate06), + ( 7, 172, ProjectionAdjustedRate07), + ( 8, 172, ProjectionAdjustedRate08), + ( 9, 172, ProjectionAdjustedRate09), + ( 10, 172, ProjectionAdjustedRate10), + ( 11, 172, ProjectionAdjustedRate11), + ( 12, 172, ProjectionAdjustedRate12) + + ) AS CrossApplied (FiscalMonth, UnitTypeID, Value) + LEFT JOIN [fw].[DimUnitType] ut ON ut.UnitTypeID = CrossApplied.UnitTypeID + LEFT JOIN [fw].[DimFiscalMonth] m ON m.SortOrder = CrossApplied.FiscalMonth + INNER JOIN [fw].[DimJobCode] jc ON jc.JobCodeID = staff.JobCodeID + INNER JOIN [fw].[DimPayCodeGroup] PCG ON PCG.PayCodeGroupID = staff.PayCodeGroupID + INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = PCG.DefaultPayCodeID + INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = staff.DepartmentID + INNER JOIN [fw].[DimEmployee] Emp ON emp.employeeid = staff.Employeeid -- Keeping employeeids for anyone with employee budgeting + INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID + LEFT JOIN #emp pcemp on staff.ProviderID = pcemp.PhysicianID AND staff.JobCodeID = pcemp.JobCodeID + WHERE staff.BudgetConfigID = @BudgetConfigID + AND Value <> 0 + AND (@IsMonthsLoadedIncluded = 1 OR CAST(m.FiscalMonthCode AS INT) > bc.MonthsLoaded) + + UNION ALL + + SELECT + d.DepartmentID, + d.DepartmentCode, + jc.JobCodeID, + jc.JobCode, + pc.PayCodeID, + pc.PayCode, + @FiscalYear, + @FiscalYear AS FiscalYearCode, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + UT.UnitTypeID, + UT.Name AS [UnitType], + m.FiscalMonthID, + m.FiscalMonthCode, + Value AS Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID, + CASE + WHEN pcemp.EmployeeID is NULL THEN emp.EmployeeID -- Valid Ids if employee budgeting enabled + ELSE pcemp.EmployeeID + END AS EmployeeID, + CASE + WHEN emp.EmployeeID > 0 OR pcemp.EmployeeID is NULL THEN emp.Code --Valid Code, if employee budgeting enabled + ELSE pcemp.EmployeeCode + END AS EmployeeCode + FROM [fp].[Staffing] staff (READUNCOMMITTED) + INNER JOIN [fp].[StaffingWageRate] wr (READUNCOMMITTED) + ON staff.StaffingWageRateID = wr.StaffingWageRateID + AND staff.VariabilityID = 1 + CROSS APPLY ( + VALUES + ( 1, 159, ProjectionAdjusted01), + ( 2, 159, ProjectionAdjusted02), + ( 3, 159, ProjectionAdjusted03), + ( 4, 159, ProjectionAdjusted04), + ( 5, 159, ProjectionAdjusted05), + ( 6, 159, ProjectionAdjusted06), + ( 7, 159, ProjectionAdjusted07), + ( 8, 159, ProjectionAdjusted08), + ( 9, 159, ProjectionAdjusted09), + ( 10, 159, ProjectionAdjusted10), + ( 11, 159, ProjectionAdjusted11), + ( 12, 159, ProjectionAdjusted12) + + ) AS CrossApplied (FiscalMonth, UnitTypeID, Value) + LEFT JOIN [fw].[DimUnitType] ut ON ut.UnitTypeID = CrossApplied.UnitTypeID + LEFT JOIN [fw].[DimFiscalMonth] m ON m.SortOrder = CrossApplied.FiscalMonth + INNER JOIN [fw].[DimJobCode] jc ON jc.JobCodeID = staff.JobCodeID + INNER JOIN [fw].[DimPayCodeGroup] PCG ON PCG.PayCodeGroupID = staff.PayCodeGroupID + INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = PCG.DefaultPayCodeID + INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = staff.DepartmentID + INNER JOIN [fw].[DimEmployee] Emp ON emp.employeeid = staff.Employeeid -- Keeping employeeids for anyone with employee budgeting + INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID + LEFT JOIN #emp pcemp on staff.ProviderID = pcemp.PhysicianID AND staff.JobCodeID = pcemp.JobCodeID + WHERE staff.BudgetConfigID = @BudgetConfigID + AND Value <> 0 + AND (@IsMonthsLoadedIncluded = 1 OR CAST(m.FiscalMonthCode AS INT) > bc.MonthsLoaded) +END +GO + + +--------------------------------------------- + +-- fp.procStaffingProviderByStatisticsFlexConfigPopulation +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2020-01-13 MY JAZZ-12607 Initial +** 2 2022-02-07 MY JAZZ-48980 Update flexing to support x-department flexing +** 3 2023-05-01 MY JAZZ-54277 Flex Config Mapping is not taking handling Cross Department Flexing properly +** 4 2023-11-08 MD JAZZ-62448 Update for staffing restructure +*************************************************************/ +CREATE PROCEDURE [fp].[procStaffingProviderByStatisticsFlexConfigPopulation] + @EntityGroupConfigGUID UNIQUEIDENTIFIER , + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + + DECLARE @BudgetConfigID INT, + @EntityGroupConfigID INT, + @StatisticAccounts INT; + + IF OBJECT_ID('tempdb..#flexMap') IS NOT NULL DROP TABLE #flexMap + IF OBJECT_ID('tempdb..#FilterPR') IS NOT NULL DROP TABLE #FilterPR + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + + SET @BudgetConfigID = (SELECT bc.BudgetConfigID + FROM [fp].[EntityGroupConfig] egc + INNER JOIN [fp].[BudgetConfig] bc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID) + SET @EntityGroupConfigID = (SELECT EntityGroupConfigID FROM [fp].[EntityGroupConfig] WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID) + + CREATE TABLE #flexMap ( + DepartmentID INT NOT NULL, + PRJobCodeID INT NOT NULL, + StatAccountID INT NOT NULL, + ProviderLineItemID INT NOT NULL, + SourceDepartmentID INT NOT NULL + ); + + CREATE TABLE #FilterPR (DepartmentID INT, BudgetConfigID INT, JobCodeID INT, ProviderLineItemID INT) + + CREATE TABLE #FilterByDepartment (DepartmentID INT) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + -- If the filter is empty, passing in all to avoid OR NULL + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[PrimaryStatisticsConfig] + WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID + AND IsStaffing = 1 + END + + -- Build a list of Department / Job Code combinations + -- Only department/job code combinations in staffing are populated in the fp.FlexConfigMapping table. New records will be added as new dimensionality is imported in. + INSERT INTO #FilterPR + SELECT pr.DepartmentID, pr.BudgetConfigID, pr.JobCodeID, pr.ProviderLineItemID + FROM [fp].[Staffing] pr + INNER JOIN #FilterByDepartment SD on SD.DepartmentID = pr.DepartmentID + INNER JOIN fp.ProviderStaffingConfig psc ON pr.BudgetConfigID = psc.BudgetConfigID + AND pr.ProviderLineItemID = psc.ProviderLineItemID + WHERE pr.VariabilityID = 2 -- Variable Only (used for filtering the data down) + AND pr.SubsectionID = 4 -- Provider + AND psc.VariabilityID = 2 -- We only want Variable Line Items + AND pr.EntityGroupConfigID = @EntityGroupConfigID + + -- NOTE: Provider Flexing Ignores overrides and only cares if the department itself is fixed. + + -- We want to get all of the records assuming that: + -- The Primary Statistic is setup to flex this account + -- The Provider Line Item is Variable + -- The Department is not fixed + -- The Statistics data exists + + -- Process department level configuration changes that are not overriden. We also will exclude Department/job code combos + -- that have multiple source departments here as that is handled in the statement below. + -- Aka: Process the Department/job code combinations that have primary stats of "Same as Department" in the Primary Stat Config + INSERT INTO #flexMap(DepartmentID, PRJobCodeID, StatAccountID, ProviderLineItemID, SourceDepartmentID) + SELECT DISTINCT stat.DepartmentID, pr.JobCodeID AS PRJobCodeID, stat.AccountID AS StatAccountID, pr.ProviderLineItemID, stat.DepartmentID + FROM [fp].[FactStatistics] stat + INNER JOIN [fp].[PrimaryStatisticsConfig] fsc ON fsc.DepartmentID = stat.DepartmentID AND fsc.AccountID = stat.AccountID + INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID = fsc.EntityGroupConfigGUID + INNER JOIN #FilterPR pr ON pr.DepartmentID = stat.DepartmentID and pr.BudgetConfigID = stat.BudgetConfigID + INNER JOIN [fp].[StaffingExpenseFlexingConfig] ns ON ns.DepartmentID = pr.DepartmentID + LEFT JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscsd ON fsc.RowID = pscsd.PrimaryStatisticsConfigID + WHERE + fsc.IsStaffing = 1 + AND fsc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND ns.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND stat.BudgetConfigID = @BudgetConfigID + AND ns.FlexMethodID != 0 -- 0 = Fixed + AND pscsd.DepartmentID IS NULL; -- We want records where there is no source department specified. When no source department is specified, it's the same as the regular department + + -- Process departments with multiple source departments + INSERT INTO #flexMap(DepartmentID, PRJobCodeID, StatAccountID, ProviderLineItemID, SourceDepartmentID) + SELECT DISTINCT fsc.DepartmentID, pr.JobCodeID AS PRJobCodeID, stat.AccountID AS StatAccountID, pr.ProviderLineItemID, pscsd.DepartmentID + FROM [fp].[PrimaryStatisticsConfig] fsc + INNER JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] pscsd ON fsc.RowID = pscsd.PrimaryStatisticsConfigID + INNER JOIN [fp].[FactStatistics] stat ON pscsd.DepartmentID = stat.DepartmentID AND fsc.AccountID = stat.AccountID + INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID = fsc.EntityGroupConfigGUID + INNER JOIN #FilterPR pr ON pr.DepartmentID = fsc.DepartmentID and pr.BudgetConfigID = stat.BudgetConfigID + INNER JOIN [fp].[StaffingExpenseFlexingConfig] ns ON ns.DepartmentID = fsc.DepartmentID + WHERE + fsc.IsStaffing = 1 + AND fsc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND ns.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND stat.BudgetConfigID = @BudgetConfigID + AND ns.FlexMethodID != 0 -- 0 = Fixed + + IF @IsDebug = 1 + BEGIN + SELECT '#FilterByDepartment', DepartmentID FROM #FilterByDepartment + SELECT '#FilterPR', DepartmentID, BudgetConfigID, JobCodeID, ProviderLineItemID FROM #FilterPR + SELECT '#flexMap', DepartmentID, PRJobCodeID, StatAccountID, ProviderLineItemID, SourceDepartmentID FROM #flexMap + END ELSE BEGIN + + ;WITH TRG AS + ( + SELECT EntityGroupConfigID, fcm.DepartmentID, fcm.PRJobCodeID, fcm.StatAccountID, fcm.ProviderLineItemID, fcm.FlexingTypeID, fcm.SourceDepartmentID + FROM [fp].[FlexConfigMapping] fcm + INNER JOIN #FilterByDepartment SD ON SD.DepartmentID = fcm.DepartmentID + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND FlexingTypeID = 9 -- Provider Flexing + ) + MERGE TRG + USING ( + SELECT @EntityGroupConfigID AS EntityGroupConfigID, + DepartmentID, + PRJobCodeID, + StatAccountID, + ProviderLineItemID, + 9 AS FlexingTypeID, -- Provider Flexing + SourceDepartmentID + FROM #flexMap + ) AS Src ON + TRG.DepartmentID = SRC.DepartmentID + AND TRG.PRJobCodeID = SRC.PRJobCodeID + AND TRG.StatAccountID = SRC.StatAccountID + AND TRG.ProviderLineItemID = SRC.ProviderLineItemID + AND TRG.SourceDepartmentID = SRC.SourceDepartmentID + WHEN NOT MATCHED BY TARGET THEN + INSERT VALUES (src.EntityGroupConfigID, src.DepartmentID, src.PRJobCodeID, src.StatAccountID, src.ProviderLineItemID, src.FlexingTypeID, src.SourceDepartmentID) + WHEN NOT MATCHED BY SOURCE THEN DELETE; + + END + + END +GO + + +--------------------------------------------- + +-- fp.procStaffingToGlCrosswalk +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-07-30 IP B-20351 Staffing to GL - Performance Improvements and roster targeted thing +** 2 2018-08-14 GF TK-62078 Limit targeted refresh to only filter by department to prevent zeroing other data +** 3 2018-09-25 GF E-02313 Simplify source dimensionality to only department +** 4 2018-12-14 BK B-19174 Add BudgetPhase to source dimensionality +** 5 2021-05-05 BK JAZZ-18217 Add Provider Compensation to crosswalk and clean up SQL +** 6 2023-07-31 BK JAZZ-58155 Update for GL data restructure +** 7 2023-10-31 Matt Hayden JAZZ-62450 Update for Staffing table restructure +** 8 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config +*************************************************************/ +CREATE PROCEDURE [fp].[procStaffingToGlCrosswalk] + @EntityGroupConfigID INT, + @BudgetConfigID INT, + @SqlJoin NVARCHAR(MAX), + @MonthsLoaded INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS +BEGIN + +IF OBJECT_ID('tempdb..#tmpStaffing') IS NOT NULL DROP TABLE #tmpStaffing +IF OBJECT_ID('tempdb..#tmpProvider') IS NOT NULL DROP TABLE #tmpProvider +IF OBJECT_ID('tempdb..#tmpAcct') IS NOT NULL DROP TABLE #tmpAcct +IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + +CREATE TABLE #tmpAcct (AccountID INT) + +CREATE TABLE #FilterByDepartment (DepartmentID INT) +INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + +IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) BEGIN + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DISTINCT DepartmentID + FROM [fp].[GeneralLedger] d WITH (READUNCOMMITTED) -- using GL here because ultimately we are updating GL and anything from Staffing should have been padded to GL + WHERE d.EntityGroupConfigID = @EntityGroupConfigID +END + +DECLARE @IsProviderPlanningEnabled BIT; +SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID; + +CREATE TABLE #tmpStaffing ( + DepartmentID INT, + AccountID INT, + VariabilityID INT, + EntityGroupConfigID INT, + TargetAdjustedDollars01 DECIMAL(19,8), TargetAdjustedDollars02 DECIMAL(19,8), TargetAdjustedDollars03 DECIMAL(19,8), TargetAdjustedDollars04 DECIMAL(19,8), TargetAdjustedDollars05 DECIMAL(19,8), TargetAdjustedDollars06 DECIMAL(19,8), + TargetAdjustedDollars07 DECIMAL(19,8), TargetAdjustedDollars08 DECIMAL(19,8), TargetAdjustedDollars09 DECIMAL(19,8), TargetAdjustedDollars10 DECIMAL(19,8), TargetAdjustedDollars11 DECIMAL(19,8), TargetAdjustedDollars12 DECIMAL(19,8), + + BudgetAdjustedDollars01 DECIMAL(19,8), BudgetAdjustedDollars02 DECIMAL(19,8), BudgetAdjustedDollars03 DECIMAL(19,8), BudgetAdjustedDollars04 DECIMAL(19,8), BudgetAdjustedDollars05 DECIMAL(19,8), BudgetAdjustedDollars06 DECIMAL(19,8), + BudgetAdjustedDollars07 DECIMAL(19,8), BudgetAdjustedDollars08 DECIMAL(19,8), BudgetAdjustedDollars09 DECIMAL(19,8), BudgetAdjustedDollars10 DECIMAL(19,8), BudgetAdjustedDollars11 DECIMAL(19,8), BudgetAdjustedDollars12 DECIMAL(19,8), + + ProjectionAdjustedDollars01 DECIMAL(19,8), ProjectionAdjustedDollars02 DECIMAL(19,8), ProjectionAdjustedDollars03 DECIMAL(19,8), ProjectionAdjustedDollars04 DECIMAL(19,8), ProjectionAdjustedDollars05 DECIMAL(19,8), ProjectionAdjustedDollars06 DECIMAL(19,8), + ProjectionAdjustedDollars07 DECIMAL(19,8), ProjectionAdjustedDollars08 DECIMAL(19,8), ProjectionAdjustedDollars09 DECIMAL(19,8), ProjectionAdjustedDollars10 DECIMAL(19,8), ProjectionAdjustedDollars11 DECIMAL(19,8), ProjectionAdjustedDollars12 DECIMAL(19,8) + ) + +INSERT INTO #tmpAcct (AccountID) +SELECT DISTINCT AccountID FROM [clientob].[FactPayrollToAccountCrosswalk] (readuncommitted) +WHERE UnitTypeID = 34 + +DECLARE @SqlStaffing NVARCHAR(MAX) +SET @SqlStaffing = ' + INSERT INTO #tmpStaffing ( + DepartmentID, AccountID, VariabilityID, EntityGroupConfigID, + + TargetAdjustedDollars01, TargetAdjustedDollars02, TargetAdjustedDollars03, TargetAdjustedDollars04, TargetAdjustedDollars05, TargetAdjustedDollars06, + TargetAdjustedDollars07, TargetAdjustedDollars08, TargetAdjustedDollars09, TargetAdjustedDollars10, TargetAdjustedDollars11, TargetAdjustedDollars12, + + BudgetAdjustedDollars01, BudgetAdjustedDollars02, BudgetAdjustedDollars03, BudgetAdjustedDollars04, BudgetAdjustedDollars05, BudgetAdjustedDollars06, + BudgetAdjustedDollars07, BudgetAdjustedDollars08, BudgetAdjustedDollars09, BudgetAdjustedDollars10, BudgetAdjustedDollars11, BudgetAdjustedDollars12, + + ProjectionAdjustedDollars01, ProjectionAdjustedDollars02, ProjectionAdjustedDollars03, ProjectionAdjustedDollars04, ProjectionAdjustedDollars05, ProjectionAdjustedDollars06, + ProjectionAdjustedDollars07, ProjectionAdjustedDollars08, ProjectionAdjustedDollars09, ProjectionAdjustedDollars10, ProjectionAdjustedDollars11, ProjectionAdjustedDollars12 + ) + SELECT + staff.DepartmentID, pax.AccountID, staff.VariabilityID, staff.EntityGroupConfigID, + + staff.TargetAdjustedDollars01, staff.TargetAdjustedDollars02, staff.TargetAdjustedDollars03, staff.TargetAdjustedDollars04, staff.TargetAdjustedDollars05, staff.TargetAdjustedDollars06, + staff.TargetAdjustedDollars07, staff.TargetAdjustedDollars08, staff.TargetAdjustedDollars09, staff.TargetAdjustedDollars10, staff.TargetAdjustedDollars11, staff.TargetAdjustedDollars12, + + staff.BudgetAdjustedDollars01, staff.BudgetAdjustedDollars02, staff.BudgetAdjustedDollars03, staff.BudgetAdjustedDollars04, staff.BudgetAdjustedDollars05, staff.BudgetAdjustedDollars06, + staff.BudgetAdjustedDollars07, staff.BudgetAdjustedDollars08, staff.BudgetAdjustedDollars09, staff.BudgetAdjustedDollars10, staff.BudgetAdjustedDollars11, staff.BudgetAdjustedDollars12, + + staff.ProjectionAdjustedDollars01, staff.ProjectionAdjustedDollars02, staff.ProjectionAdjustedDollars03, staff.ProjectionAdjustedDollars04, staff.ProjectionAdjustedDollars05, staff.ProjectionAdjustedDollars06, + staff.ProjectionAdjustedDollars07, staff.ProjectionAdjustedDollars08, staff.ProjectionAdjustedDollars09, staff.ProjectionAdjustedDollars10, staff.ProjectionAdjustedDollars11, staff.ProjectionAdjustedDollars12 + FROM [fp].[Staffing] staff (readuncommitted) + INNER JOIN #FilterByDepartment dept ON staff.DepartmentID = dept.DepartmentID + ' + @SqlJoin + ' + WHERE staff.SubsectionID = 3 + AND pax.UnitTypeID = 34 + AND staff.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS NVARCHAR(10)) + +EXEC (@SqlStaffing); -- populate #tmpStaffing + +IF @IsProviderPlanningEnabled = 1 BEGIN + CREATE TABLE #tmpProvider ( + ProviderLineItemID TINYINT, + AccountID INT, + ProviderTypeID INT, + VariabilityID INT + ) + INSERT INTO #tmpProvider (ProviderLineItemID, AccountID, ProviderTypeID, VariabilityID) + SELECT ProviderLineItemID, COALESCE(detail.AccountID, psc.AccountID) AS AccountID, ISNULL(ProviderTypeID, 0), VariabilityID + FROM fp.ProviderStaffingConfig psc + LEFT JOIN fp.ProviderStaffingConfigProviderType detail on psc.ProviderStaffingConfigID = detail.ProviderStaffingConfigID + WHERE BudgetConfigID = @BudgetConfigID + + INSERT INTO #tmpAcct (AccountID) + SELECT DISTINCT a.AccountID FROM #tmpProvider a + LEFT JOIN #tmpAcct t on a.AccountID = t.AccountID + WHERE t.AccountID IS NULL + + INSERT INTO #tmpStaffing ( + DepartmentID, AccountID, VariabilityID, EntityGroupConfigID, + + TargetAdjustedDollars01, TargetAdjustedDollars02, TargetAdjustedDollars03, TargetAdjustedDollars04, TargetAdjustedDollars05, TargetAdjustedDollars06, + TargetAdjustedDollars07, TargetAdjustedDollars08, TargetAdjustedDollars09, TargetAdjustedDollars10, TargetAdjustedDollars11, TargetAdjustedDollars12, + + BudgetAdjustedDollars01, BudgetAdjustedDollars02, BudgetAdjustedDollars03, BudgetAdjustedDollars04, BudgetAdjustedDollars05, BudgetAdjustedDollars06, + BudgetAdjustedDollars07, BudgetAdjustedDollars08, BudgetAdjustedDollars09, BudgetAdjustedDollars10, BudgetAdjustedDollars11, BudgetAdjustedDollars12, + + ProjectionAdjustedDollars01, ProjectionAdjustedDollars02, ProjectionAdjustedDollars03, ProjectionAdjustedDollars04, ProjectionAdjustedDollars05, ProjectionAdjustedDollars06, + ProjectionAdjustedDollars07, ProjectionAdjustedDollars08, ProjectionAdjustedDollars09, ProjectionAdjustedDollars10, ProjectionAdjustedDollars11, ProjectionAdjustedDollars12 + ) + SELECT + staff.DepartmentID, prov.AccountID, staff.VariabilityID, staff.EntityGroupConfigID, + + staff.TargetAdjustedDollars01, staff.TargetAdjustedDollars02, staff.TargetAdjustedDollars03, staff.TargetAdjustedDollars04, staff.TargetAdjustedDollars05, staff.TargetAdjustedDollars06, + staff.TargetAdjustedDollars07, staff.TargetAdjustedDollars08, staff.TargetAdjustedDollars09, staff.TargetAdjustedDollars10, staff.TargetAdjustedDollars11, staff.TargetAdjustedDollars12, + + staff.BudgetAdjustedDollars01, staff.BudgetAdjustedDollars02, staff.BudgetAdjustedDollars03, staff.BudgetAdjustedDollars04, staff.BudgetAdjustedDollars05, staff.BudgetAdjustedDollars06, + staff.BudgetAdjustedDollars07, staff.BudgetAdjustedDollars08, staff.BudgetAdjustedDollars09, staff.BudgetAdjustedDollars10, staff.BudgetAdjustedDollars11, staff.BudgetAdjustedDollars12, + + staff.ProjectionAdjustedDollars01, staff.ProjectionAdjustedDollars02, staff.ProjectionAdjustedDollars03, staff.ProjectionAdjustedDollars04, staff.ProjectionAdjustedDollars05, staff.ProjectionAdjustedDollars06, + staff.ProjectionAdjustedDollars07, staff.ProjectionAdjustedDollars08, staff.ProjectionAdjustedDollars09, staff.ProjectionAdjustedDollars10, staff.ProjectionAdjustedDollars11, staff.ProjectionAdjustedDollars12 + FROM [fp].[Staffing] staff (readuncommitted) + INNER JOIN #tmpProvider prov on staff.ProviderLineItemID = prov.ProviderLineItemID AND staff.VariabilityID = prov.VariabilityID + INNER JOIN #FilterByDepartment dept ON staff.DepartmentID = dept.DepartmentID + INNER JOIN #tmpAcct acc on prov.AccountID = acc.AccountID + WHERE staff.SubsectionID = 4 + AND staff.EntityGroupConfigID = @EntityGroupConfigID + AND (prov.ProviderTypeID = 0 OR prov.ProviderTypeID = staff.ProviderTypeID) +END + +IF (@IsDebug = 1) BEGIN + + WITH StaffingSubquery AS ( + SELECT + s.DepartmentID, + s.AccountID, + s.VariabilityID, + s.EntityGroupConfigID, + SUM(s.TargetAdjustedDollars01) AS TargetAdjustedDollars01, + SUM(s.TargetAdjustedDollars02) AS TargetAdjustedDollars02, + SUM(s.TargetAdjustedDollars03) AS TargetAdjustedDollars03, + SUM(s.TargetAdjustedDollars04) AS TargetAdjustedDollars04, + SUM(s.TargetAdjustedDollars05) AS TargetAdjustedDollars05, + SUM(s.TargetAdjustedDollars06) AS TargetAdjustedDollars06, + SUM(s.TargetAdjustedDollars07) AS TargetAdjustedDollars07, + SUM(s.TargetAdjustedDollars08) AS TargetAdjustedDollars08, + SUM(s.TargetAdjustedDollars09) AS TargetAdjustedDollars09, + SUM(s.TargetAdjustedDollars10) AS TargetAdjustedDollars10, + SUM(s.TargetAdjustedDollars11) AS TargetAdjustedDollars11, + SUM(s.TargetAdjustedDollars12) AS TargetAdjustedDollars12, + SUM(s.BudgetAdjustedDollars01) AS BudgetAdjustedDollars01, + SUM(s.BudgetAdjustedDollars02) AS BudgetAdjustedDollars02, + SUM(s.BudgetAdjustedDollars03) AS BudgetAdjustedDollars03, + SUM(s.BudgetAdjustedDollars04) AS BudgetAdjustedDollars04, + SUM(s.BudgetAdjustedDollars05) AS BudgetAdjustedDollars05, + SUM(s.BudgetAdjustedDollars06) AS BudgetAdjustedDollars06, + SUM(s.BudgetAdjustedDollars07) AS BudgetAdjustedDollars07, + SUM(s.BudgetAdjustedDollars08) AS BudgetAdjustedDollars08, + SUM(s.BudgetAdjustedDollars09) AS BudgetAdjustedDollars09, + SUM(s.BudgetAdjustedDollars10) AS BudgetAdjustedDollars10, + SUM(s.BudgetAdjustedDollars11) AS BudgetAdjustedDollars11, + SUM(s.BudgetAdjustedDollars12) AS BudgetAdjustedDollars12, + SUM(s.ProjectionAdjustedDollars01) AS ProjectionAdjustedDollars01, + SUM(s.ProjectionAdjustedDollars02) AS ProjectionAdjustedDollars02, + SUM(s.ProjectionAdjustedDollars03) AS ProjectionAdjustedDollars03, + SUM(s.ProjectionAdjustedDollars04) AS ProjectionAdjustedDollars04, + SUM(s.ProjectionAdjustedDollars05) AS ProjectionAdjustedDollars05, + SUM(s.ProjectionAdjustedDollars06) AS ProjectionAdjustedDollars06, + SUM(s.ProjectionAdjustedDollars07) AS ProjectionAdjustedDollars07, + SUM(s.ProjectionAdjustedDollars08) AS ProjectionAdjustedDollars08, + SUM(s.ProjectionAdjustedDollars09) AS ProjectionAdjustedDollars09, + SUM(s.ProjectionAdjustedDollars10) AS ProjectionAdjustedDollars10, + SUM(s.ProjectionAdjustedDollars11) AS ProjectionAdjustedDollars11, + SUM(s.ProjectionAdjustedDollars12) AS ProjectionAdjustedDollars12 + FROM #tmpStaffing s + GROUP BY + s.DepartmentID, + s.AccountID, + s.VariabilityID, + s.EntityGroupConfigID + ) + SELECT + gl.AccountID, gl.DepartmentID, gl.VariabilityID, gl.EntityGroupConfigID, + + staff.TargetAdjustedDollars01, staff.TargetAdjustedDollars02, staff.TargetAdjustedDollars03, staff.TargetAdjustedDollars04, staff.TargetAdjustedDollars05, staff.TargetAdjustedDollars06, + staff.TargetAdjustedDollars07, staff.TargetAdjustedDollars08, staff.TargetAdjustedDollars09, staff.TargetAdjustedDollars10, staff.TargetAdjustedDollars11, staff.TargetAdjustedDollars12, + + staff.BudgetAdjustedDollars01, staff.BudgetAdjustedDollars02, staff.BudgetAdjustedDollars03, staff.BudgetAdjustedDollars04, staff.BudgetAdjustedDollars05, staff.BudgetAdjustedDollars06, + staff.BudgetAdjustedDollars07, staff.BudgetAdjustedDollars08, staff.BudgetAdjustedDollars09, staff.BudgetAdjustedDollars10, staff.BudgetAdjustedDollars11, staff.BudgetAdjustedDollars12, + + staff.ProjectionAdjustedDollars01, staff.ProjectionAdjustedDollars02, staff.ProjectionAdjustedDollars03, staff.ProjectionAdjustedDollars04, staff.ProjectionAdjustedDollars05, staff.ProjectionAdjustedDollars06, + staff.ProjectionAdjustedDollars07, staff.ProjectionAdjustedDollars08, staff.ProjectionAdjustedDollars09, staff.ProjectionAdjustedDollars10, staff.ProjectionAdjustedDollars11, staff.ProjectionAdjustedDollars12, + + 1 AS LockFlag, 3 as LockType + FROM [fp].[GeneralLedger] gl + INNER JOIN #FilterByDepartment dept ON gl.DepartmentID = dept.DepartmentID --AND fglb.BudgetPhaseID = dept.BudgetPhaseID + INNER JOIN #tmpAcct fptac ON gl.AccountID = fptac.AccountID + LEFT JOIN StaffingSubquery staff ON staff.DepartmentID = gl.DepartmentID + AND staff.AccountID = gl.AccountID + AND staff.EntityGroupConfigID = gl.EntityGroupConfigID + AND staff.VariabilityID = gl.VariabilityID + WHERE gl.EntityGroupConfigID = @EntityGroupConfigID + AND ( + gl.TargetAdjusted01 != ISNULL(staff.TargetAdjustedDollars01, 0) OR + gl.TargetAdjusted02 != ISNULL(staff.TargetAdjustedDollars02, 0) OR + gl.TargetAdjusted03 != ISNULL(staff.TargetAdjustedDollars03, 0) OR + gl.TargetAdjusted04 != ISNULL(staff.TargetAdjustedDollars04, 0) OR + gl.TargetAdjusted05 != ISNULL(staff.TargetAdjustedDollars05, 0) OR + gl.TargetAdjusted06 != ISNULL(staff.TargetAdjustedDollars06, 0) OR + gl.TargetAdjusted07 != ISNULL(staff.TargetAdjustedDollars07, 0) OR + gl.TargetAdjusted08 != ISNULL(staff.TargetAdjustedDollars08, 0) OR + gl.TargetAdjusted09 != ISNULL(staff.TargetAdjustedDollars09, 0) OR + gl.TargetAdjusted10 != ISNULL(staff.TargetAdjustedDollars10, 0) OR + gl.TargetAdjusted11 != ISNULL(staff.TargetAdjustedDollars11, 0) OR + gl.TargetAdjusted12 != ISNULL(staff.TargetAdjustedDollars12, 0) OR + gl.TargetLockFlag != 1 OR + gl.BudgetAdjusted01 != ISNULL(staff.BudgetAdjustedDollars01, 0) OR + gl.BudgetAdjusted02 != ISNULL(staff.BudgetAdjustedDollars02, 0) OR + gl.BudgetAdjusted03 != ISNULL(staff.BudgetAdjustedDollars03, 0) OR + gl.BudgetAdjusted04 != ISNULL(staff.BudgetAdjustedDollars04, 0) OR + gl.BudgetAdjusted05 != ISNULL(staff.BudgetAdjustedDollars05, 0) OR + gl.BudgetAdjusted06 != ISNULL(staff.BudgetAdjustedDollars06, 0) OR + gl.BudgetAdjusted07 != ISNULL(staff.BudgetAdjustedDollars07, 0) OR + gl.BudgetAdjusted08 != ISNULL(staff.BudgetAdjustedDollars08, 0) OR + gl.BudgetAdjusted09 != ISNULL(staff.BudgetAdjustedDollars09, 0) OR + gl.BudgetAdjusted10 != ISNULL(staff.BudgetAdjustedDollars10, 0) OR + gl.BudgetAdjusted11 != ISNULL(staff.BudgetAdjustedDollars11, 0) OR + gl.BudgetAdjusted12 != ISNULL(staff.BudgetAdjustedDollars12, 0) OR + gl.BudgetLockFlag != 1 OR + gl.ProjectionAdjusted01 != CASE WHEN @MonthsLoaded < 1 THEN ISNULL(staff.ProjectionAdjustedDollars01, 0) ELSE gl.ProjectionAdjusted01 END OR + gl.ProjectionAdjusted02 != CASE WHEN @MonthsLoaded < 2 THEN ISNULL(staff.ProjectionAdjustedDollars02, 0) ELSE gl.ProjectionAdjusted02 END OR + gl.ProjectionAdjusted03 != CASE WHEN @MonthsLoaded < 3 THEN ISNULL(staff.ProjectionAdjustedDollars03, 0) ELSE gl.ProjectionAdjusted03 END OR + gl.ProjectionAdjusted04 != CASE WHEN @MonthsLoaded < 4 THEN ISNULL(staff.ProjectionAdjustedDollars04, 0) ELSE gl.ProjectionAdjusted04 END OR + gl.ProjectionAdjusted05 != CASE WHEN @MonthsLoaded < 5 THEN ISNULL(staff.ProjectionAdjustedDollars05, 0) ELSE gl.ProjectionAdjusted05 END OR + gl.ProjectionAdjusted06 != CASE WHEN @MonthsLoaded < 6 THEN ISNULL(staff.ProjectionAdjustedDollars06, 0) ELSE gl.ProjectionAdjusted06 END OR + gl.ProjectionAdjusted07 != CASE WHEN @MonthsLoaded < 7 THEN ISNULL(staff.ProjectionAdjustedDollars07, 0) ELSE gl.ProjectionAdjusted07 END OR + gl.ProjectionAdjusted08 != CASE WHEN @MonthsLoaded < 8 THEN ISNULL(staff.ProjectionAdjustedDollars08, 0) ELSE gl.ProjectionAdjusted08 END OR + gl.ProjectionAdjusted09 != CASE WHEN @MonthsLoaded < 9 THEN ISNULL(staff.ProjectionAdjustedDollars09, 0) ELSE gl.ProjectionAdjusted09 END OR + gl.ProjectionAdjusted10 != CASE WHEN @MonthsLoaded < 10 THEN ISNULL(staff.ProjectionAdjustedDollars10, 0) ELSE gl.ProjectionAdjusted10 END OR + gl.ProjectionAdjusted11 != CASE WHEN @MonthsLoaded < 11 THEN ISNULL(staff.ProjectionAdjustedDollars11, 0) ELSE gl.ProjectionAdjusted11 END OR + gl.ProjectionAdjusted12 != CASE WHEN @MonthsLoaded < 12 THEN ISNULL(staff.ProjectionAdjustedDollars12, 0) ELSE gl.ProjectionAdjusted12 END OR + gl.ProjectionLockFlag != 1 + ) + +END ELSE BEGIN + + WITH StaffingSubquery AS ( + SELECT + s.DepartmentID, + s.AccountID, + s.VariabilityID, + s.EntityGroupConfigID, + SUM(s.TargetAdjustedDollars01) AS TargetAdjustedDollars01, + SUM(s.TargetAdjustedDollars02) AS TargetAdjustedDollars02, + SUM(s.TargetAdjustedDollars03) AS TargetAdjustedDollars03, + SUM(s.TargetAdjustedDollars04) AS TargetAdjustedDollars04, + SUM(s.TargetAdjustedDollars05) AS TargetAdjustedDollars05, + SUM(s.TargetAdjustedDollars06) AS TargetAdjustedDollars06, + SUM(s.TargetAdjustedDollars07) AS TargetAdjustedDollars07, + SUM(s.TargetAdjustedDollars08) AS TargetAdjustedDollars08, + SUM(s.TargetAdjustedDollars09) AS TargetAdjustedDollars09, + SUM(s.TargetAdjustedDollars10) AS TargetAdjustedDollars10, + SUM(s.TargetAdjustedDollars11) AS TargetAdjustedDollars11, + SUM(s.TargetAdjustedDollars12) AS TargetAdjustedDollars12, + SUM(s.BudgetAdjustedDollars01) AS BudgetAdjustedDollars01, + SUM(s.BudgetAdjustedDollars02) AS BudgetAdjustedDollars02, + SUM(s.BudgetAdjustedDollars03) AS BudgetAdjustedDollars03, + SUM(s.BudgetAdjustedDollars04) AS BudgetAdjustedDollars04, + SUM(s.BudgetAdjustedDollars05) AS BudgetAdjustedDollars05, + SUM(s.BudgetAdjustedDollars06) AS BudgetAdjustedDollars06, + SUM(s.BudgetAdjustedDollars07) AS BudgetAdjustedDollars07, + SUM(s.BudgetAdjustedDollars08) AS BudgetAdjustedDollars08, + SUM(s.BudgetAdjustedDollars09) AS BudgetAdjustedDollars09, + SUM(s.BudgetAdjustedDollars10) AS BudgetAdjustedDollars10, + SUM(s.BudgetAdjustedDollars11) AS BudgetAdjustedDollars11, + SUM(s.BudgetAdjustedDollars12) AS BudgetAdjustedDollars12, + SUM(s.ProjectionAdjustedDollars01) AS ProjectionAdjustedDollars01, + SUM(s.ProjectionAdjustedDollars02) AS ProjectionAdjustedDollars02, + SUM(s.ProjectionAdjustedDollars03) AS ProjectionAdjustedDollars03, + SUM(s.ProjectionAdjustedDollars04) AS ProjectionAdjustedDollars04, + SUM(s.ProjectionAdjustedDollars05) AS ProjectionAdjustedDollars05, + SUM(s.ProjectionAdjustedDollars06) AS ProjectionAdjustedDollars06, + SUM(s.ProjectionAdjustedDollars07) AS ProjectionAdjustedDollars07, + SUM(s.ProjectionAdjustedDollars08) AS ProjectionAdjustedDollars08, + SUM(s.ProjectionAdjustedDollars09) AS ProjectionAdjustedDollars09, + SUM(s.ProjectionAdjustedDollars10) AS ProjectionAdjustedDollars10, + SUM(s.ProjectionAdjustedDollars11) AS ProjectionAdjustedDollars11, + SUM(s.ProjectionAdjustedDollars12) AS ProjectionAdjustedDollars12 + FROM #tmpStaffing s + GROUP BY + s.DepartmentID, + s.AccountID, + s.VariabilityID, + s.EntityGroupConfigID + ) + UPDATE gl + SET + gl.TargetAdjusted01 = ISNULL(ss.TargetAdjustedDollars01, 0), + gl.TargetAdjusted02 = ISNULL(ss.TargetAdjustedDollars02, 0), + gl.TargetAdjusted03 = ISNULL(ss.TargetAdjustedDollars03, 0), + gl.TargetAdjusted04 = ISNULL(ss.TargetAdjustedDollars04, 0), + gl.TargetAdjusted05 = ISNULL(ss.TargetAdjustedDollars05, 0), + gl.TargetAdjusted06 = ISNULL(ss.TargetAdjustedDollars06, 0), + gl.TargetAdjusted07 = ISNULL(ss.TargetAdjustedDollars07, 0), + gl.TargetAdjusted08 = ISNULL(ss.TargetAdjustedDollars08, 0), + gl.TargetAdjusted09 = ISNULL(ss.TargetAdjustedDollars09, 0), + gl.TargetAdjusted10 = ISNULL(ss.TargetAdjustedDollars10, 0), + gl.TargetAdjusted11 = ISNULL(ss.TargetAdjustedDollars11, 0), + gl.TargetAdjusted12 = ISNULL(ss.TargetAdjustedDollars12, 0), + gl.TargetLockFlag = 1, + gl.TargetLockType = 3, + gl.BudgetAdjusted01 = ISNULL(ss.BudgetAdjustedDollars01, 0), + gl.BudgetAdjusted02 = ISNULL(ss.BudgetAdjustedDollars02, 0), + gl.BudgetAdjusted03 = ISNULL(ss.BudgetAdjustedDollars03, 0), + gl.BudgetAdjusted04 = ISNULL(ss.BudgetAdjustedDollars04, 0), + gl.BudgetAdjusted05 = ISNULL(ss.BudgetAdjustedDollars05, 0), + gl.BudgetAdjusted06 = ISNULL(ss.BudgetAdjustedDollars06, 0), + gl.BudgetAdjusted07 = ISNULL(ss.BudgetAdjustedDollars07, 0), + gl.BudgetAdjusted08 = ISNULL(ss.BudgetAdjustedDollars08, 0), + gl.BudgetAdjusted09 = ISNULL(ss.BudgetAdjustedDollars09, 0), + gl.BudgetAdjusted10 = ISNULL(ss.BudgetAdjustedDollars10, 0), + gl.BudgetAdjusted11 = ISNULL(ss.BudgetAdjustedDollars11, 0), + gl.BudgetAdjusted12 = ISNULL(ss.BudgetAdjustedDollars12, 0), + gl.BudgetLockFlag = 1, + gl.BudgetLockType = 3, + gl.ProjectionAdjusted01 = CASE WHEN @MonthsLoaded < 1 THEN ISNULL(ss.ProjectionAdjustedDollars01, 0) ELSE gl.ProjectionAdjusted01 END, + gl.ProjectionAdjusted02 = CASE WHEN @MonthsLoaded < 2 THEN ISNULL(ss.ProjectionAdjustedDollars02, 0) ELSE gl.ProjectionAdjusted02 END, + gl.ProjectionAdjusted03 = CASE WHEN @MonthsLoaded < 3 THEN ISNULL(ss.ProjectionAdjustedDollars03, 0) ELSE gl.ProjectionAdjusted03 END, + gl.ProjectionAdjusted04 = CASE WHEN @MonthsLoaded < 4 THEN ISNULL(ss.ProjectionAdjustedDollars04, 0) ELSE gl.ProjectionAdjusted04 END, + gl.ProjectionAdjusted05 = CASE WHEN @MonthsLoaded < 5 THEN ISNULL(ss.ProjectionAdjustedDollars05, 0) ELSE gl.ProjectionAdjusted05 END, + gl.ProjectionAdjusted06 = CASE WHEN @MonthsLoaded < 6 THEN ISNULL(ss.ProjectionAdjustedDollars06, 0) ELSE gl.ProjectionAdjusted06 END, + gl.ProjectionAdjusted07 = CASE WHEN @MonthsLoaded < 7 THEN ISNULL(ss.ProjectionAdjustedDollars07, 0) ELSE gl.ProjectionAdjusted07 END, + gl.ProjectionAdjusted08 = CASE WHEN @MonthsLoaded < 8 THEN ISNULL(ss.ProjectionAdjustedDollars08, 0) ELSE gl.ProjectionAdjusted08 END, + gl.ProjectionAdjusted09 = CASE WHEN @MonthsLoaded < 9 THEN ISNULL(ss.ProjectionAdjustedDollars09, 0) ELSE gl.ProjectionAdjusted09 END, + gl.ProjectionAdjusted10 = CASE WHEN @MonthsLoaded < 10 THEN ISNULL(ss.ProjectionAdjustedDollars10, 0) ELSE gl.ProjectionAdjusted10 END, + gl.ProjectionAdjusted11 = CASE WHEN @MonthsLoaded < 11 THEN ISNULL(ss.ProjectionAdjustedDollars11, 0) ELSE gl.ProjectionAdjusted11 END, + gl.ProjectionAdjusted12 = CASE WHEN @MonthsLoaded < 12 THEN ISNULL(ss.ProjectionAdjustedDollars12, 0) ELSE gl.ProjectionAdjusted12 END, + gl.ProjectionLockFlag = 1, + gl.ProjectionLockType = 3 + FROM [fp].[GeneralLedger] gl + INNER JOIN #FilterByDepartment dept ON gl.DepartmentID = dept.DepartmentID + INNER JOIN #tmpAcct acct ON gl.AccountID = acct.AccountID + LEFT JOIN StaffingSubquery ss ON ss.DepartmentID = gl.DepartmentID + AND ss.AccountID = gl.AccountID + AND ss.EntityGroupConfigID = gl.EntityGroupConfigID + AND ss.VariabilityID = gl.VariabilityID + WHERE gl.EntityGroupConfigID = @EntityGroupConfigID + AND ( + gl.TargetAdjusted01 != ISNULL(ss.TargetAdjustedDollars01, 0) OR + gl.TargetAdjusted02 != ISNULL(ss.TargetAdjustedDollars02, 0) OR + gl.TargetAdjusted03 != ISNULL(ss.TargetAdjustedDollars03, 0) OR + gl.TargetAdjusted04 != ISNULL(ss.TargetAdjustedDollars04, 0) OR + gl.TargetAdjusted05 != ISNULL(ss.TargetAdjustedDollars05, 0) OR + gl.TargetAdjusted06 != ISNULL(ss.TargetAdjustedDollars06, 0) OR + gl.TargetAdjusted07 != ISNULL(ss.TargetAdjustedDollars07, 0) OR + gl.TargetAdjusted08 != ISNULL(ss.TargetAdjustedDollars08, 0) OR + gl.TargetAdjusted09 != ISNULL(ss.TargetAdjustedDollars09, 0) OR + gl.TargetAdjusted10 != ISNULL(ss.TargetAdjustedDollars10, 0) OR + gl.TargetAdjusted11 != ISNULL(ss.TargetAdjustedDollars11, 0) OR + gl.TargetAdjusted12 != ISNULL(ss.TargetAdjustedDollars12, 0) OR + gl.TargetLockFlag != 1 OR + gl.BudgetAdjusted01 != ISNULL(ss.BudgetAdjustedDollars01, 0) OR + gl.BudgetAdjusted02 != ISNULL(ss.BudgetAdjustedDollars02, 0) OR + gl.BudgetAdjusted03 != ISNULL(ss.BudgetAdjustedDollars03, 0) OR + gl.BudgetAdjusted04 != ISNULL(ss.BudgetAdjustedDollars04, 0) OR + gl.BudgetAdjusted05 != ISNULL(ss.BudgetAdjustedDollars05, 0) OR + gl.BudgetAdjusted06 != ISNULL(ss.BudgetAdjustedDollars06, 0) OR + gl.BudgetAdjusted07 != ISNULL(ss.BudgetAdjustedDollars07, 0) OR + gl.BudgetAdjusted08 != ISNULL(ss.BudgetAdjustedDollars08, 0) OR + gl.BudgetAdjusted09 != ISNULL(ss.BudgetAdjustedDollars09, 0) OR + gl.BudgetAdjusted10 != ISNULL(ss.BudgetAdjustedDollars10, 0) OR + gl.BudgetAdjusted11 != ISNULL(ss.BudgetAdjustedDollars11, 0) OR + gl.BudgetAdjusted12 != ISNULL(ss.BudgetAdjustedDollars12, 0) OR + gl.BudgetLockFlag != 1 OR + gl.ProjectionAdjusted01 != CASE WHEN @MonthsLoaded < 1 THEN ISNULL(ss.ProjectionAdjustedDollars01, 0) ELSE gl.ProjectionAdjusted01 END OR + gl.ProjectionAdjusted02 != CASE WHEN @MonthsLoaded < 2 THEN ISNULL(ss.ProjectionAdjustedDollars02, 0) ELSE gl.ProjectionAdjusted02 END OR + gl.ProjectionAdjusted03 != CASE WHEN @MonthsLoaded < 3 THEN ISNULL(ss.ProjectionAdjustedDollars03, 0) ELSE gl.ProjectionAdjusted03 END OR + gl.ProjectionAdjusted04 != CASE WHEN @MonthsLoaded < 4 THEN ISNULL(ss.ProjectionAdjustedDollars04, 0) ELSE gl.ProjectionAdjusted04 END OR + gl.ProjectionAdjusted05 != CASE WHEN @MonthsLoaded < 5 THEN ISNULL(ss.ProjectionAdjustedDollars05, 0) ELSE gl.ProjectionAdjusted05 END OR + gl.ProjectionAdjusted06 != CASE WHEN @MonthsLoaded < 6 THEN ISNULL(ss.ProjectionAdjustedDollars06, 0) ELSE gl.ProjectionAdjusted06 END OR + gl.ProjectionAdjusted07 != CASE WHEN @MonthsLoaded < 7 THEN ISNULL(ss.ProjectionAdjustedDollars07, 0) ELSE gl.ProjectionAdjusted07 END OR + gl.ProjectionAdjusted08 != CASE WHEN @MonthsLoaded < 8 THEN ISNULL(ss.ProjectionAdjustedDollars08, 0) ELSE gl.ProjectionAdjusted08 END OR + gl.ProjectionAdjusted09 != CASE WHEN @MonthsLoaded < 9 THEN ISNULL(ss.ProjectionAdjustedDollars09, 0) ELSE gl.ProjectionAdjusted09 END OR + gl.ProjectionAdjusted10 != CASE WHEN @MonthsLoaded < 10 THEN ISNULL(ss.ProjectionAdjustedDollars10, 0) ELSE gl.ProjectionAdjusted10 END OR + gl.ProjectionAdjusted11 != CASE WHEN @MonthsLoaded < 11 THEN ISNULL(ss.ProjectionAdjustedDollars11, 0) ELSE gl.ProjectionAdjusted11 END OR + gl.ProjectionAdjusted12 != CASE WHEN @MonthsLoaded < 12 THEN ISNULL(ss.ProjectionAdjustedDollars12, 0) ELSE gl.ProjectionAdjusted12 END OR + gl.ProjectionLockFlag != 1 + ); + +END +END +GO + + +--------------------------------------------- + +-- fp.procStaffingToGlCrosswalk_Initial +/************************************************************* + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2023-08-22 MY JAZZ-59505 Initial Creation + ** 2 2023-10-23 Matt Hayden JAZZ-62450 Update for Staffing table restructure + ** 3 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config + *************************************************************/ +CREATE PROCEDURE [fp].[procStaffingToGlCrosswalk_Initial] + @EntityGroupConfigID INT, + @BudgetConfigID INT, + @SqlJoin NVARCHAR(MAX), + @MonthsLoaded INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY, + @IsDebug BIT = 0 +AS BEGIN + +IF OBJECT_ID('tempdb..#tmpStaffing') IS NOT NULL DROP TABLE #tmpStaffing +IF OBJECT_ID('tempdb..#tmpProvider') IS NOT NULL DROP TABLE #tmpProvider +IF OBJECT_ID('tempdb..#tmpAcct') IS NOT NULL DROP TABLE #tmpAcct +IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment + +CREATE TABLE #tmpAcct (AccountID INT) +CREATE TABLE #FilterByDepartment (DepartmentID INT) + +INSERT INTO + #FilterByDepartment (DepartmentID) +SELECT + DepartmentID +FROM + fp.funcGetSourceDimensionalityAsTable(@SourceDimensionality) + +IF NOT EXISTS( + SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) BEGIN + + INSERT INTO + #FilterByDepartment (DepartmentID) + SELECT + DISTINCT DepartmentID + FROM + [fp].[GeneralLedger] d WITH (READUNCOMMITTED) -- using GL here because ultimately we are updating GL and anything from Staffing should have been padded to GL + WHERE + d.EntityGroupConfigID = @EntityGroupConfigID +END + +DECLARE @IsProviderPlanningEnabled BIT; +SELECT @IsProviderPlanningEnabled = IsProviderPlanningEnabled FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID; + +CREATE TABLE #tmpStaffing ( + DepartmentID INT, + AccountID INT, + VariabilityID INT, + EntityGroupConfigID INT, + InitialBudgetDollars01 DECIMAL(19, 8), + InitialBudgetDollars02 DECIMAL(19, 8), + InitialBudgetDollars03 DECIMAL(19, 8), + InitialBudgetDollars04 DECIMAL(19, 8), + InitialBudgetDollars05 DECIMAL(19, 8), + InitialBudgetDollars06 DECIMAL(19, 8), + InitialBudgetDollars07 DECIMAL(19, 8), + InitialBudgetDollars08 DECIMAL(19, 8), + InitialBudgetDollars09 DECIMAL(19, 8), + InitialBudgetDollars10 DECIMAL(19, 8), + InitialBudgetDollars11 DECIMAL(19, 8), + InitialBudgetDollars12 DECIMAL(19, 8), + InitialProjectionDollars01 DECIMAL(19, 8), + InitialProjectionDollars02 DECIMAL(19, 8), + InitialProjectionDollars03 DECIMAL(19, 8), + InitialProjectionDollars04 DECIMAL(19, 8), + InitialProjectionDollars05 DECIMAL(19, 8), + InitialProjectionDollars06 DECIMAL(19, 8), + InitialProjectionDollars07 DECIMAL(19, 8), + InitialProjectionDollars08 DECIMAL(19, 8), + InitialProjectionDollars09 DECIMAL(19, 8), + InitialProjectionDollars10 DECIMAL(19, 8), + InitialProjectionDollars11 DECIMAL(19, 8), + InitialProjectionDollars12 DECIMAL(19, 8) +) + +INSERT INTO + #tmpAcct (AccountID) +SELECT + DISTINCT AccountID +FROM + [clientob].[FactPayrollToAccountCrosswalk] (readuncommitted) +WHERE + UnitTypeID = 34 + + +DECLARE @SqlStaffing NVARCHAR(MAX) + +SET @SqlStaffing = ' + INSERT INTO #tmpStaffing ( + DepartmentID, + AccountID, + VariabilityID, + EntityGroupConfigID, + InitialBudgetDollars01, + InitialBudgetDollars02, + InitialBudgetDollars03, + InitialBudgetDollars04, + InitialBudgetDollars05, + InitialBudgetDollars06, + InitialBudgetDollars07, + InitialBudgetDollars08, + InitialBudgetDollars09, + InitialBudgetDollars10, + InitialBudgetDollars11, + InitialBudgetDollars12, + InitialProjectionDollars01, + InitialProjectionDollars02, + InitialProjectionDollars03, + InitialProjectionDollars04, + InitialProjectionDollars05, + InitialProjectionDollars06, + InitialProjectionDollars07, + InitialProjectionDollars08, + InitialProjectionDollars09, + InitialProjectionDollars10, + InitialProjectionDollars11, + InitialProjectionDollars12) + SELECT + staff.DepartmentID, + pax.AccountID, + staff.VariabilityID, + staff.EntityGroupConfigID, + ISNULL(staff.InitialBudgetDollars01, 0), + ISNULL(staff.InitialBudgetDollars02, 0), + ISNULL(staff.InitialBudgetDollars03, 0), + ISNULL(staff.InitialBudgetDollars04, 0), + ISNULL(staff.InitialBudgetDollars05, 0), + ISNULL(staff.InitialBudgetDollars06, 0), + ISNULL(staff.InitialBudgetDollars07, 0), + ISNULL(staff.InitialBudgetDollars08, 0), + ISNULL(staff.InitialBudgetDollars09, 0), + ISNULL(staff.InitialBudgetDollars10, 0), + ISNULL(staff.InitialBudgetDollars11, 0), + ISNULL(staff.InitialBudgetDollars12, 0), + ISNULL(staff.InitialProjectionDollars01, 0), + ISNULL(staff.InitialProjectionDollars02, 0), + ISNULL(staff.InitialProjectionDollars03, 0), + ISNULL(staff.InitialProjectionDollars04, 0), + ISNULL(staff.InitialProjectionDollars05, 0), + ISNULL(staff.InitialProjectionDollars06, 0), + ISNULL(staff.InitialProjectionDollars07, 0), + ISNULL(staff.InitialProjectionDollars08, 0), + ISNULL(staff.InitialProjectionDollars09, 0), + ISNULL(staff.InitialProjectionDollars10, 0), + ISNULL(staff.InitialProjectionDollars11, 0), + ISNULL(staff.InitialProjectionDollars12, 0) + FROM [fp].[Staffing] staff (readuncommitted) + INNER JOIN #FilterByDepartment dept ON staff.DepartmentID = dept.DepartmentID ' + + @SqlJoin + ' + WHERE staff.SubsectionID = 3 + AND pax.UnitTypeID = 34 + AND staff.EntityGroupConfigID = ' + CAST(@EntityGroupConfigID AS NVARCHAR(10)) + +EXEC (@SqlStaffing); + +IF @IsProviderPlanningEnabled = 1 BEGIN + + CREATE TABLE #tmpProvider ( + ProviderLineItemID TINYINT, + AccountID INT, + ProviderTypeID INT, + VariabilityID INT + ) + + INSERT INTO + #tmpProvider (ProviderLineItemID, AccountID, ProviderTypeID, VariabilityID) + SELECT + ProviderLineItemID, + COALESCE(detail.AccountID, psc.AccountID) AS AccountID, + ISNULL(ProviderTypeID, 0), + VariabilityID + FROM + fp.ProviderStaffingConfig psc + LEFT JOIN fp.ProviderStaffingConfigProviderType detail on psc.ProviderStaffingConfigID = detail.ProviderStaffingConfigID + WHERE + BudgetConfigID = @BudgetConfigID + + + INSERT INTO #tmpAcct (AccountID) + SELECT DISTINCT a.AccountID + FROM + #tmpProvider a + LEFT JOIN #tmpAcct t on a.AccountID = t.AccountID + WHERE + t.AccountID IS NULL + + INSERT INTO #tmpStaffing ( + DepartmentID, + AccountID, + VariabilityID, + EntityGroupConfigID, + InitialBudgetDollars01, + InitialBudgetDollars02, + InitialBudgetDollars03, + InitialBudgetDollars04, + InitialBudgetDollars05, + InitialBudgetDollars06, + InitialBudgetDollars07, + InitialBudgetDollars08, + InitialBudgetDollars09, + InitialBudgetDollars10, + InitialBudgetDollars11, + InitialBudgetDollars12, + InitialProjectionDollars01, + InitialProjectionDollars02, + InitialProjectionDollars03, + InitialProjectionDollars04, + InitialProjectionDollars05, + InitialProjectionDollars06, + InitialProjectionDollars07, + InitialProjectionDollars08, + InitialProjectionDollars09, + InitialProjectionDollars10, + InitialProjectionDollars11, + InitialProjectionDollars12) + SELECT + staff.DepartmentID, + prov.AccountID, + staff.VariabilityID, + staff.EntityGroupConfigID, + ISNULL(staff.InitialBudgetDollars01, 0), + ISNULL(staff.InitialBudgetDollars02, 0), + ISNULL(staff.InitialBudgetDollars03, 0), + ISNULL(staff.InitialBudgetDollars04, 0), + ISNULL(staff.InitialBudgetDollars05, 0), + ISNULL(staff.InitialBudgetDollars06, 0), + ISNULL(staff.InitialBudgetDollars07, 0), + ISNULL(staff.InitialBudgetDollars08, 0), + ISNULL(staff.InitialBudgetDollars09, 0), + ISNULL(staff.InitialBudgetDollars10, 0), + ISNULL(staff.InitialBudgetDollars11, 0), + ISNULL(staff.InitialBudgetDollars12, 0), + ISNULL(staff.InitialProjectionDollars01, 0), + ISNULL(staff.InitialProjectionDollars02, 0), + ISNULL(staff.InitialProjectionDollars03, 0), + ISNULL(staff.InitialProjectionDollars04, 0), + ISNULL(staff.InitialProjectionDollars05, 0), + ISNULL(staff.InitialProjectionDollars06, 0), + ISNULL(staff.InitialProjectionDollars07, 0), + ISNULL(staff.InitialProjectionDollars08, 0), + ISNULL(staff.InitialProjectionDollars09, 0), + ISNULL(staff.InitialProjectionDollars10, 0), + ISNULL(staff.InitialProjectionDollars11, 0), + ISNULL(staff.InitialProjectionDollars12, 0) + FROM [fp].[Staffing] staff (readuncommitted) + INNER JOIN #tmpProvider prov ON staff.ProviderLineItemID = prov.ProviderLineItemID AND staff.VariabilityID = prov.VariabilityID + INNER JOIN #FilterByDepartment dept ON staff.DepartmentID = dept.DepartmentID + INNER JOIN #tmpAcct acc ON prov.AccountID = acc.AccountID + WHERE staff.SubsectionID = 4 + AND staff.EntityGroupConfigID = @EntityGroupConfigID + AND (prov.ProviderTypeID = 0 OR prov.ProviderTypeID = staff.ProviderTypeID) +END + +IF (@IsDebug = 1) BEGIN + SELECT + gl.AccountID, + gl.DepartmentID, + gl.VariabilityID, + gl.EntityGroupConfigID, + ISNULL(staff.InitialBudgetDollars01, 0), + ISNULL(staff.InitialBudgetDollars02, 0), + ISNULL(staff.InitialBudgetDollars03, 0), + ISNULL(staff.InitialBudgetDollars04, 0), + ISNULL(staff.InitialBudgetDollars05, 0), + ISNULL(staff.InitialBudgetDollars06, 0), + ISNULL(staff.InitialBudgetDollars07, 0), + ISNULL(staff.InitialBudgetDollars08, 0), + ISNULL(staff.InitialBudgetDollars09, 0), + ISNULL(staff.InitialBudgetDollars10, 0), + ISNULL(staff.InitialBudgetDollars11, 0), + ISNULL(staff.InitialBudgetDollars12, 0), + ISNULL(staff.InitialProjectionDollars01, 0), + ISNULL(staff.InitialProjectionDollars02, 0), + ISNULL(staff.InitialProjectionDollars03, 0), + ISNULL(staff.InitialProjectionDollars04, 0), + ISNULL(staff.InitialProjectionDollars05, 0), + ISNULL(staff.InitialProjectionDollars06, 0), + ISNULL(staff.InitialProjectionDollars07, 0), + ISNULL(staff.InitialProjectionDollars08, 0), + ISNULL(staff.InitialProjectionDollars09, 0), + ISNULL(staff.InitialProjectionDollars10, 0), + ISNULL(staff.InitialProjectionDollars11, 0), + ISNULL(staff.InitialProjectionDollars12, 0) + FROM + [fp].[GeneralLedger] gl + INNER JOIN #FilterByDepartment dept ON gl.DepartmentID = dept.DepartmentID + INNER JOIN #tmpAcct fptac ON gl.AccountID = fptac.AccountID + LEFT JOIN ( + SELECT DepartmentID, AccountID, VariabilityID, EntityGroupConfigID + , SUM(InitialBudgetDollars01) as InitialBudgetDollars01 + , SUM(InitialBudgetDollars02) as InitialBudgetDollars02 + , SUM(InitialBudgetDollars03) as InitialBudgetDollars03 + , SUM(InitialBudgetDollars04) as InitialBudgetDollars04 + , SUM(InitialBudgetDollars05) as InitialBudgetDollars05 + , SUM(InitialBudgetDollars06) as InitialBudgetDollars06 + , SUM(InitialBudgetDollars07) as InitialBudgetDollars07 + , SUM(InitialBudgetDollars08) as InitialBudgetDollars08 + , SUM(InitialBudgetDollars09) as InitialBudgetDollars09 + , SUM(InitialBudgetDollars10) as InitialBudgetDollars10 + , SUM(InitialBudgetDollars11) as InitialBudgetDollars11 + , SUM(InitialBudgetDollars12) as InitialBudgetDollars12 + , SUM(InitialProjectionDollars01) as InitialProjectionDollars01 + , SUM(InitialProjectionDollars02) as InitialProjectionDollars02 + , SUM(InitialProjectionDollars03) as InitialProjectionDollars03 + , SUM(InitialProjectionDollars04) as InitialProjectionDollars04 + , SUM(InitialProjectionDollars05) as InitialProjectionDollars05 + , SUM(InitialProjectionDollars06) as InitialProjectionDollars06 + , SUM(InitialProjectionDollars07) as InitialProjectionDollars07 + , SUM(InitialProjectionDollars08) as InitialProjectionDollars08 + , SUM(InitialProjectionDollars09) as InitialProjectionDollars09 + , SUM(InitialProjectionDollars10) as InitialProjectionDollars10 + , SUM(InitialProjectionDollars11) as InitialProjectionDollars11 + , SUM(InitialProjectionDollars12) as InitialProjectionDollars12 + FROM #tmpStaffing + GROUP BY DepartmentID, AccountID, VariabilityID, EntityGroupConfigID + ) staff ON staff.DepartmentID = gl.DepartmentID + AND staff.AccountID = gl.AccountID + AND staff.EntityGroupConfigID = gl.EntityGroupConfigID + AND staff.VariabilityID = gl.VariabilityID + WHERE + gl.EntityGroupConfigID = @EntityGroupConfigID + AND ( + gl.InitialBudget01 != ISNULL(staff.InitialBudgetDollars01, 0) + OR gl.InitialBudget02 != ISNULL(staff.InitialBudgetDollars02, 0) + OR gl.InitialBudget03 != ISNULL(staff.InitialBudgetDollars03, 0) + OR gl.InitialBudget04 != ISNULL(staff.InitialBudgetDollars04, 0) + OR gl.InitialBudget05 != ISNULL(staff.InitialBudgetDollars05, 0) + OR gl.InitialBudget06 != ISNULL(staff.InitialBudgetDollars06, 0) + OR gl.InitialBudget07 != ISNULL(staff.InitialBudgetDollars07, 0) + OR gl.InitialBudget08 != ISNULL(staff.InitialBudgetDollars08, 0) + OR gl.InitialBudget09 != ISNULL(staff.InitialBudgetDollars09, 0) + OR gl.InitialBudget10 != ISNULL(staff.InitialBudgetDollars10, 0) + OR gl.InitialBudget11 != ISNULL(staff.InitialBudgetDollars11, 0) + OR gl.InitialBudget12 != ISNULL(staff.InitialBudgetDollars12, 0) + OR gl.InitialProjection01 != CASE WHEN @MonthsLoaded < 1 THEN ISNULL(staff.InitialProjectionDollars01, 0) ELSE gl.InitialProjection01 END + OR gl.InitialProjection02 != CASE WHEN @MonthsLoaded < 2 THEN ISNULL(staff.InitialProjectionDollars02, 0) ELSE gl.InitialProjection02 END + OR gl.InitialProjection03 != CASE WHEN @MonthsLoaded < 3 THEN ISNULL(staff.InitialProjectionDollars03, 0) ELSE gl.InitialProjection03 END + OR gl.InitialProjection04 != CASE WHEN @MonthsLoaded < 4 THEN ISNULL(staff.InitialProjectionDollars04, 0) ELSE gl.InitialProjection04 END + OR gl.InitialProjection05 != CASE WHEN @MonthsLoaded < 5 THEN ISNULL(staff.InitialProjectionDollars05, 0) ELSE gl.InitialProjection05 END + OR gl.InitialProjection06 != CASE WHEN @MonthsLoaded < 6 THEN ISNULL(staff.InitialProjectionDollars06, 0) ELSE gl.InitialProjection06 END + OR gl.InitialProjection07 != CASE WHEN @MonthsLoaded < 7 THEN ISNULL(staff.InitialProjectionDollars07, 0) ELSE gl.InitialProjection07 END + OR gl.InitialProjection08 != CASE WHEN @MonthsLoaded < 8 THEN ISNULL(staff.InitialProjectionDollars08, 0) ELSE gl.InitialProjection08 END + OR gl.InitialProjection09 != CASE WHEN @MonthsLoaded < 9 THEN ISNULL(staff.InitialProjectionDollars09, 0) ELSE gl.InitialProjection09 END + OR gl.InitialProjection10 != CASE WHEN @MonthsLoaded < 10 THEN ISNULL(staff.InitialProjectionDollars10, 0) ELSE gl.InitialProjection10 END + OR gl.InitialProjection11 != CASE WHEN @MonthsLoaded < 11 THEN ISNULL(staff.InitialProjectionDollars11, 0) ELSE gl.InitialProjection11 END + OR gl.InitialProjection12 != CASE WHEN @MonthsLoaded < 12 THEN ISNULL(staff.InitialProjectionDollars12, 0) ELSE gl.InitialProjection12 END + ) +END +ELSE BEGIN + + UPDATE gl + SET gl.InitialBudget01 = ISNULL(staff.InitialBudgetDollars01, 0), + gl.InitialBudget02 = ISNULL(staff.InitialBudgetDollars02, 0), + gl.InitialBudget03 = ISNULL(staff.InitialBudgetDollars03, 0), + gl.InitialBudget04 = ISNULL(staff.InitialBudgetDollars04, 0), + gl.InitialBudget05 = ISNULL(staff.InitialBudgetDollars05, 0), + gl.InitialBudget06 = ISNULL(staff.InitialBudgetDollars06, 0), + gl.InitialBudget07 = ISNULL(staff.InitialBudgetDollars07, 0), + gl.InitialBudget08 = ISNULL(staff.InitialBudgetDollars08, 0), + gl.InitialBudget09 = ISNULL(staff.InitialBudgetDollars09, 0), + gl.InitialBudget10 = ISNULL(staff.InitialBudgetDollars10, 0), + gl.InitialBudget11 = ISNULL(staff.InitialBudgetDollars11, 0), + gl.InitialBudget12 = ISNULL(staff.InitialBudgetDollars12, 0), + gl.InitialProjection01 = CASE WHEN @MonthsLoaded < 1 THEN ISNULL(staff.InitialProjectionDollars01, 0) ELSE gl.InitialProjection01 END, + gl.InitialProjection02 = CASE WHEN @MonthsLoaded < 2 THEN ISNULL(staff.InitialProjectionDollars02, 0) ELSE gl.InitialProjection02 END, + gl.InitialProjection03 = CASE WHEN @MonthsLoaded < 3 THEN ISNULL(staff.InitialProjectionDollars03, 0) ELSE gl.InitialProjection03 END, + gl.InitialProjection04 = CASE WHEN @MonthsLoaded < 4 THEN ISNULL(staff.InitialProjectionDollars04, 0) ELSE gl.InitialProjection04 END, + gl.InitialProjection05 = CASE WHEN @MonthsLoaded < 5 THEN ISNULL(staff.InitialProjectionDollars05, 0) ELSE gl.InitialProjection05 END, + gl.InitialProjection06 = CASE WHEN @MonthsLoaded < 6 THEN ISNULL(staff.InitialProjectionDollars06, 0) ELSE gl.InitialProjection06 END, + gl.InitialProjection07 = CASE WHEN @MonthsLoaded < 7 THEN ISNULL(staff.InitialProjectionDollars07, 0) ELSE gl.InitialProjection07 END, + gl.InitialProjection08 = CASE WHEN @MonthsLoaded < 8 THEN ISNULL(staff.InitialProjectionDollars08, 0) ELSE gl.InitialProjection08 END, + gl.InitialProjection09 = CASE WHEN @MonthsLoaded < 9 THEN ISNULL(staff.InitialProjectionDollars09, 0) ELSE gl.InitialProjection09 END, + gl.InitialProjection10 = CASE WHEN @MonthsLoaded < 10 THEN ISNULL(staff.InitialProjectionDollars10, 0) ELSE gl.InitialProjection10 END, + gl.InitialProjection11 = CASE WHEN @MonthsLoaded < 11 THEN ISNULL(staff.InitialProjectionDollars11, 0) ELSE gl.InitialProjection11 END, + gl.InitialProjection12 = CASE WHEN @MonthsLoaded < 12 THEN ISNULL(staff.InitialProjectionDollars12, 0) ELSE gl.InitialProjection12 END + FROM [fp].[GeneralLedger] gl + INNER JOIN #FilterByDepartment dept ON gl.DepartmentID = dept.DepartmentID + INNER JOIN #tmpAcct acct ON gl.AccountID = acct.AccountID + LEFT JOIN ( + SELECT DepartmentID, AccountID, VariabilityID, EntityGroupConfigID + , SUM(InitialBudgetDollars01) as InitialBudgetDollars01 + , SUM(InitialBudgetDollars02) as InitialBudgetDollars02 + , SUM(InitialBudgetDollars03) as InitialBudgetDollars03 + , SUM(InitialBudgetDollars04) as InitialBudgetDollars04 + , SUM(InitialBudgetDollars05) as InitialBudgetDollars05 + , SUM(InitialBudgetDollars06) as InitialBudgetDollars06 + , SUM(InitialBudgetDollars07) as InitialBudgetDollars07 + , SUM(InitialBudgetDollars08) as InitialBudgetDollars08 + , SUM(InitialBudgetDollars09) as InitialBudgetDollars09 + , SUM(InitialBudgetDollars10) as InitialBudgetDollars10 + , SUM(InitialBudgetDollars11) as InitialBudgetDollars11 + , SUM(InitialBudgetDollars12) as InitialBudgetDollars12 + , SUM(InitialProjectionDollars01) as InitialProjectionDollars01 + , SUM(InitialProjectionDollars02) as InitialProjectionDollars02 + , SUM(InitialProjectionDollars03) as InitialProjectionDollars03 + , SUM(InitialProjectionDollars04) as InitialProjectionDollars04 + , SUM(InitialProjectionDollars05) as InitialProjectionDollars05 + , SUM(InitialProjectionDollars06) as InitialProjectionDollars06 + , SUM(InitialProjectionDollars07) as InitialProjectionDollars07 + , SUM(InitialProjectionDollars08) as InitialProjectionDollars08 + , SUM(InitialProjectionDollars09) as InitialProjectionDollars09 + , SUM(InitialProjectionDollars10) as InitialProjectionDollars10 + , SUM(InitialProjectionDollars11) as InitialProjectionDollars11 + , SUM(InitialProjectionDollars12) as InitialProjectionDollars12 + FROM #tmpStaffing s + GROUP BY DepartmentID, AccountID, VariabilityID, EntityGroupConfigID + ) staff ON staff.DepartmentID = gl.DepartmentID + AND staff.AccountID = gl.AccountID + AND staff.EntityGroupConfigID = gl.EntityGroupConfigID + AND staff.VariabilityID = gl.VariabilityID + WHERE + gl.EntityGroupConfigID = @EntityGroupConfigID + AND ( + gl.InitialBudget01 != ISNULL(staff.InitialBudgetDollars01, 0) + OR gl.InitialBudget02 != ISNULL(staff.InitialBudgetDollars02, 0) + OR gl.InitialBudget03 != ISNULL(staff.InitialBudgetDollars03, 0) + OR gl.InitialBudget04 != ISNULL(staff.InitialBudgetDollars04, 0) + OR gl.InitialBudget05 != ISNULL(staff.InitialBudgetDollars05, 0) + OR gl.InitialBudget06 != ISNULL(staff.InitialBudgetDollars06, 0) + OR gl.InitialBudget07 != ISNULL(staff.InitialBudgetDollars07, 0) + OR gl.InitialBudget08 != ISNULL(staff.InitialBudgetDollars08, 0) + OR gl.InitialBudget09 != ISNULL(staff.InitialBudgetDollars09, 0) + OR gl.InitialBudget10 != ISNULL(staff.InitialBudgetDollars10, 0) + OR gl.InitialBudget11 != ISNULL(staff.InitialBudgetDollars11, 0) + OR gl.InitialBudget12 != ISNULL(staff.InitialBudgetDollars12, 0) + OR gl.InitialProjection01 != CASE WHEN @MonthsLoaded < 1 THEN ISNULL(staff.InitialProjectionDollars01, 0) ELSE gl.InitialProjection01 END + OR gl.InitialProjection02 != CASE WHEN @MonthsLoaded < 2 THEN ISNULL(staff.InitialProjectionDollars02, 0) ELSE gl.InitialProjection02 END + OR gl.InitialProjection03 != CASE WHEN @MonthsLoaded < 3 THEN ISNULL(staff.InitialProjectionDollars03, 0) ELSE gl.InitialProjection03 END + OR gl.InitialProjection04 != CASE WHEN @MonthsLoaded < 4 THEN ISNULL(staff.InitialProjectionDollars04, 0) ELSE gl.InitialProjection04 END + OR gl.InitialProjection05 != CASE WHEN @MonthsLoaded < 5 THEN ISNULL(staff.InitialProjectionDollars05, 0) ELSE gl.InitialProjection05 END + OR gl.InitialProjection06 != CASE WHEN @MonthsLoaded < 6 THEN ISNULL(staff.InitialProjectionDollars06, 0) ELSE gl.InitialProjection06 END + OR gl.InitialProjection07 != CASE WHEN @MonthsLoaded < 7 THEN ISNULL(staff.InitialProjectionDollars07, 0) ELSE gl.InitialProjection07 END + OR gl.InitialProjection08 != CASE WHEN @MonthsLoaded < 8 THEN ISNULL(staff.InitialProjectionDollars08, 0) ELSE gl.InitialProjection08 END + OR gl.InitialProjection09 != CASE WHEN @MonthsLoaded < 9 THEN ISNULL(staff.InitialProjectionDollars09, 0) ELSE gl.InitialProjection09 END + OR gl.InitialProjection10 != CASE WHEN @MonthsLoaded < 10 THEN ISNULL(staff.InitialProjectionDollars10, 0) ELSE gl.InitialProjection10 END + OR gl.InitialProjection11 != CASE WHEN @MonthsLoaded < 11 THEN ISNULL(staff.InitialProjectionDollars11, 0) ELSE gl.InitialProjection11 END + OR gl.InitialProjection12 != CASE WHEN @MonthsLoaded < 12 THEN ISNULL(staff.InitialProjectionDollars12, 0) ELSE gl.InitialProjection12 END + ) +END +END +GO + + +--------------------------------------------- + +-- fp.procStaffingToStatisticBudgetStampOff +CREATE PROCEDURE [fp].[procStaffingToStatisticBudgetStampOff] + @BudgetConfigID INT, + @TargetTimeClassID TINYINT +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 01-31-2023 MY JAZZ-48962 Initial Creation + ** 2 01-03-2024 MZ JAZZ-65385 Added Target TimeClass + ** 3 12-04-2023 BW/MZ JAZZ-63562 Data model restructure for Staffing/Merge with main + ** 4 01-30-2024 MZ JAZZ-66319 Fix Join on [clientob].[FactPayrollToAccountCrosswalk] with zero-JobCode records + ** 5 03-18-2024 MZ JAZZ-68428 Removed HistoryItemGUID parameter + *************************************************************/ + + -- Note: The original script was done here https://stratadecision.atlassian.net/wiki/spaces/DD/pages/3116205785/Moving+Data+from+a+Plan+Configuration+to+Int+Tables + + DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID ) + DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID) + + DECLARE @HistoryItemGUID UNIQUEIDENTIFIER + EXEC procLogScript 'StampOff: Transferring Budget Data from 1p', @HistoryItemGUID OUTPUT + PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36)) + PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID) + + INSERT INTO [int].[FactStatistic] ([DepartmentID], [DepartmentCode], [AccountID], [AccountCode], [FiscalYearID], [FiscalYearCode], + [TimeClassID], [TimeClassCode], [FiscalMonthID], [FiscalMonthCode], [Value], [IsDeleted], [HistoryItemGUID]) + SELECT + d.DepartmentID, + d.DepartmentCode, + cw.AccountID, + acc.AccountCode, + bc.FiscalYearID, + bc.FiscalYearID AS FiscalYearCode, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + m.FiscalMonthID, + m.FiscalMonthCode, + SUM(Value) AS Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID + FROM [fp].[Staffing] staff (READUNCOMMITTED) + CROSS APPLY ( + VALUES + ( 1, 51, BudgetAdjustedHours01), + ( 2, 51, BudgetAdjustedHours02), + ( 3, 51, BudgetAdjustedHours03), + ( 4, 51, BudgetAdjustedHours04), + ( 5, 51, BudgetAdjustedHours05), + ( 6, 51, BudgetAdjustedHours06), + ( 7, 51, BudgetAdjustedHours07), + ( 8, 51, BudgetAdjustedHours08), + ( 9, 51, BudgetAdjustedHours09), + ( 10, 51, BudgetAdjustedHours10), + ( 11, 51, BudgetAdjustedHours11), + ( 12, 51, BudgetAdjustedHours12) + + ) AS CrossApplied (FiscalMonth, UnitTypeID, Value) + LEFT JOIN [fw].[DimUnitType] ut ON ut.UnitTypeID = CrossApplied.UnitTypeID + LEFT JOIN [fw].[DimFiscalMonth] m ON m.SortOrder = CrossApplied.FiscalMonth + INNER JOIN [fw].[DimJobCode] jc ON jc.JobCodeID = staff.JobCodeID + INNER JOIN [fw].[DimPayCodeGroup] PCG ON PCG.PayCodeGroupID = staff.PayCodeGroupID + INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = PCG.DefaultPayCodeID + INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = staff.DepartmentID + INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID + INNER JOIN (SELECT JobCodeID, PayCodeGroupID, UnitTypeID, AccountID FROM [clientob].[FactPayrollToAccountCrosswalk] p + WHERE JobCodeID <> 0 OR (JobCodeID = 0 AND NOT EXISTS ( + SELECT 1 + FROM [clientob].[FactPayrollToAccountCrosswalk] + WHERE AccountID = p.AccountID AND PayCodeGroupID = p.PayCodeGroupID + AND JobCodeID <> 0)) + ) cw ON + (CASE WHEN cw.JobCodeID <> 0 THEN cw.JobCodeID ELSE 1 END) = (CASE WHEN cw.JobCodeID <> 0 THEN jc.JobCodeID ELSE 1 END) + AND cw.PayCodeGroupID = PCG.PayCodeGroupID + AND UT.UnitTypeID = cw.UnitTypeID + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = cw.AccountID + WHERE staff.BudgetConfigID = @BudgetConfigID + AND Value <> 0 + GROUP BY + d.DepartmentID, + d.DepartmentCode, + cw.AccountID, + acc.AccountCode, + bc.FiscalYearID, + bc.FiscalYearID, + m.FiscalMonthID, + m.FiscalMonthCode +END +GO + + +--------------------------------------------- + +-- fp.procStaffingToStatisticProjectionStampOff +CREATE PROCEDURE [fp].[procStaffingToStatisticProjectionStampOff] + @BudgetConfigID INT, + @TargetTimeClassID TINYINT, + @IsMonthsLoadedIncluded BIT +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 11-10-2023 AO JAZZ-62128 Initial Creation + ** 2 01-04-2024 MZ JAZZ-65385 Added Target TimeClass and IsMonthsLoadedIncluded + ** 3 01-24-2024 MZ JAZZ-64527 Fix Months Loaded + ** 4 12-04-2023 BW/MZ JAZZ-63562 Data model restructure for Staffing/Merge with main + ** 5 01-30-2024 MZ JAZZ-66319 Fix Join on [clientob].[FactPayrollToAccountCrosswalk] with zero-JobCode records + ** 6 03-18-2024 MZ JAZZ-68428 Removed HistoryItemGUID parameter + *************************************************************/ + + -- Note: The original script was done here https://stratadecision.atlassian.net/wiki/spaces/DD/pages/3116205785/Moving+Data+from+a+Plan+Configuration+to+Int+Tables + + DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID - 1 FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID ) + DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID) + + DECLARE @HistoryItemGUID UNIQUEIDENTIFIER + EXEC procLogScript 'StampOff: Transferring Projection Data from 1p', @HistoryItemGUID OUTPUT + PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36)) + PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID) + + INSERT INTO [int].[FactStatistic] ([DepartmentID], [DepartmentCode], [AccountID], [AccountCode], [FiscalYearID], [FiscalYearCode], + [TimeClassID], [TimeClassCode], [FiscalMonthID], [FiscalMonthCode], [Value], [IsDeleted], [HistoryItemGUID]) + SELECT + d.DepartmentID, + d.DepartmentCode, + cw.AccountID, + acc.AccountCode, + @FiscalYear, + @FiscalYear AS FiscalYearCode, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + m.FiscalMonthID, + m.FiscalMonthCode, + SUM(Value) AS Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID + FROM [fp].[Staffing] staff (READUNCOMMITTED) + CROSS APPLY ( + VALUES + ( 1, 51, ProjectionAdjustedHours01), + ( 2, 51, ProjectionAdjustedHours02), + ( 3, 51, ProjectionAdjustedHours03), + ( 4, 51, ProjectionAdjustedHours04), + ( 5, 51, ProjectionAdjustedHours05), + ( 6, 51, ProjectionAdjustedHours06), + ( 7, 51, ProjectionAdjustedHours07), + ( 8, 51, ProjectionAdjustedHours08), + ( 9, 51, ProjectionAdjustedHours09), + ( 10, 51, ProjectionAdjustedHours10), + ( 11, 51, ProjectionAdjustedHours11), + ( 12, 51, ProjectionAdjustedHours12) + + ) AS CrossApplied (FiscalMonth, UnitTypeID, Value) + LEFT JOIN [fw].[DimUnitType] ut ON ut.UnitTypeID = CrossApplied.UnitTypeID + LEFT JOIN [fw].[DimFiscalMonth] m ON m.SortOrder = CrossApplied.FiscalMonth + INNER JOIN [fw].[DimJobCode] jc ON jc.JobCodeID = staff.JobCodeID + INNER JOIN [fw].[DimPayCodeGroup] PCG ON PCG.PayCodeGroupID = staff.PayCodeGroupID + INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = PCG.DefaultPayCodeID + INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = staff.DepartmentID + INNER JOIN [fp].[BudgetConfig] bc ON staff.BudgetConfigID = bc.BudgetConfigID + INNER JOIN (SELECT JobCodeID, PayCodeGroupID, UnitTypeID, AccountID FROM [clientob].[FactPayrollToAccountCrosswalk] p + WHERE JobCodeID <> 0 OR (JobCodeID = 0 AND NOT EXISTS ( + SELECT 1 + FROM [clientob].[FactPayrollToAccountCrosswalk] + WHERE AccountID = p.AccountID AND PayCodeGroupID = p.PayCodeGroupID + AND JobCodeID <> 0)) + ) cw ON + (CASE WHEN cw.JobCodeID <> 0 THEN cw.JobCodeID ELSE 1 END) = (CASE WHEN cw.JobCodeID <> 0 THEN jc.JobCodeID ELSE 1 END) + AND cw.PayCodeGroupID = PCG.PayCodeGroupID + AND UT.UnitTypeID = cw.UnitTypeID + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = cw.AccountID + WHERE staff.BudgetConfigID = @BudgetConfigID + AND Value <> 0 + AND (@IsMonthsLoadedIncluded = 1 OR CAST(m.FiscalMonthCode AS INT) > bc.MonthsLoaded) + GROUP BY + d.DepartmentID, + d.DepartmentCode, + cw.AccountID, + acc.AccountCode, + bc.FiscalYearID, + bc.FiscalYearID, + m.FiscalMonthID, + m.FiscalMonthCode +END +GO + + +--------------------------------------------- + +-- fp.procStampOffBackup +CREATE PROCEDURE [fp].[procStampOffBackup] + @IsDebug BIT = 0 +AS +BEGIN + +/************************************************************** +** Change History +** CID Date Author WI Description +** 1 2024-02-20 AO JAZZ-67099 Initial +** 2 2024-03-07 AO JAZZ-68698 Drop and create tables before each submission +** 3 2024-03-21 MZ JAZZ-69490 Added [int].[FactStaffingByPayPeriod] +** 4 2024-03-21 AO JAZZ-73139 Added compression +** 4 2024-03-21 AO JAZZ-73869 Added [int].[FactStatisticsbyPayPeriod] +** 5 2024-08-29 NH JAZZ-76159 Updated JobCodeID type +*************************************************************/ + + IF OBJECT_ID('tempdb..#tableNamesToDelete') IS NOT NULL DROP TABLE #tableNamesToDelete; + CREATE TABLE #tableNamesToDelete (TableName NVARCHAR(255)); + + -- Insert previous backup table names into the temporary table (date is dynamic) + INSERT INTO #tableNamesToDelete (TableName) + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME LIKE 'intFactServiceLine_System_%' + UNION + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME LIKE 'intFactCDM_System_%' + UNION + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME LIKE 'intFactStatistic_System_%' + UNION + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME LIKE 'intFactGL_System_%' + UNION + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME LIKE 'intFactStaffing_System_%' + UNION + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME LIKE 'intFactProvider_System_%' + UNION + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME LIKE 'intFactImportProvider_System_%' + UNION + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME LIKE 'intFactStaffingByPayPeriod_System_%' + UNION + SELECT TABLE_NAME + FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = 'bak' AND TABLE_NAME LIKE 'intFactStatisticsByPayPeriod_System_%'; + + -- Delete previous backup tables + DECLARE @sqlDropTableStatement NVARCHAR(MAX); + SET @sqlDropTableStatement = ''; + + SELECT @sqlDropTableStatement = @sqlDropTableStatement + 'EXEC [dbo].[procSysDropTable] @schema = ''bak'', @table = ''' + TableName + ''';' + FROM #tableNamesToDelete; + + -- Execute dynamic-query + EXEC (@sqlDropTableStatement); + + DECLARE @datePostfix NVARCHAR(8) = REPLACE(CONVERT(Date, GETDATE()),'-',''); + + IF (@IsDebug = 1) + BEGIN + SET @datePostfix = 'test' + END + + DECLARE @bakTableName NVARCHAR(255) = N'[bak].[intFactServiceLine_System_' + @datePostfix + ']'; + DECLARE @sqlCreateTable NVARCHAR(MAX); + + SET @sqlCreateTable = ' + CREATE TABLE ' + @bakTableName + '( + [RowID] [bigint] NOT NULL DEFAULT 0, + [TimeClassID] [tinyint] NOT NULL DEFAULT '''', + [TimeClassCode] [nvarchar](100) NOT NULL DEFAULT '''', + [FiscalYearID] [smallint] NOT NULL DEFAULT 0, + [FiscalYearCode] [nvarchar](100) NOT NULL DEFAULT '''', + [FiscalMonthID] [tinyint] NOT NULL DEFAULT 0, + [FiscalMonthCode] [nvarchar](100) NOT NULL DEFAULT '''', + [EntityID] [int] NOT NULL DEFAULT 0, + [EntityCode] [nvarchar](100) NOT NULL DEFAULT '''', + [PatientClassID] [int] NOT NULL DEFAULT 0, + [PatientClassCode] [nvarchar](100) NOT NULL DEFAULT '''', + [ServiceLineID] [int] NOT NULL DEFAULT 0, + [ServiceLine] [nvarchar](100) NOT NULL DEFAULT '''', + [AgeCohortID] [int] NOT NULL DEFAULT 0, + [AgeCohort] [nvarchar](100) NOT NULL DEFAULT '''', + [MedicalSurgicalID] [int] NOT NULL DEFAULT 0, + [MedSurg] [nvarchar](100) NOT NULL DEFAULT '''', + [DepartmentID] [int] NOT NULL DEFAULT 0, + [DepartmentCode] [nvarchar](100) NOT NULL DEFAULT '''', + [OBForecastDetailID] [int] NOT NULL DEFAULT 0, + [ForecastDetail] [nvarchar](100) NOT NULL DEFAULT '''', + [PayorGroupID] [int] NOT NULL DEFAULT 0, + [PayorID] [int] NOT NULL DEFAULT 0, + [Value] [decimal](19, 4) NOT NULL DEFAULT 0, + [IsDeleted] [bit] NOT NULL DEFAULT 0, + [HistoryItemGUID] [uniqueidentifier] NOT NULL DEFAULT CAST(0x0 AS UNIQUEIDENTIFIER), + [Version] [varbinary](8) NOT NULL DEFAULT(0x), + [TransactionID] [int] NOT NULL DEFAULT 0, + [PayorGroupCode] [nvarchar](100) NOT NULL DEFAULT '''', + [PayorCode] [nvarchar](100) NOT NULL DEFAULT '''' + ); + + INSERT INTO ' + @bakTableName + ' WITH(TABLOCK) ( + RowID, + TimeClassID, + TimeClassCode, + FiscalYearID, + FiscalYearCode, + FiscalMonthID, + FiscalMonthCode, + EntityID, + EntityCode, + PatientClassID, + PatientClassCode, + ServiceLineID, + ServiceLine, + AgeCohortID, + AgeCohort, + MedicalSurgicalID, + MedSurg, + DepartmentID, + DepartmentCode, + OBForecastDetailID, + ForecastDetail, + PayorGroupID, + PayorID, + Value, + IsDeleted, + HistoryItemGUID, + Version, + TransactionID, + PayorGroupCode, + PayorCode) + SELECT + RowID, + TimeClassID, + TimeClassCode, + FiscalYearID, + FiscalYearCode, + FiscalMonthID, + FiscalMonthCode, + EntityID, + EntityCode, + PatientClassID, + PatientClassCode, + ServiceLineID, + ServiceLine, + AgeCohortID, + AgeCohort, + MedicalSurgicalID, + MedSurg, + DepartmentID, + DepartmentCode, + OBForecastDetailID, + ForecastDetail, + PayorGroupID, + PayorID, + Value, + IsDeleted, + HistoryItemGUID, + Version, + TransactionID, + PayorGroupCode, + PayorCode + FROM [int].[FactServiceLine]; + + ALTER TABLE ' + @bakTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE) + '; + EXEC (@sqlCreateTable); + + SET @bakTableName = N'[bak].[intFactCDM_System_' + @datePostfix + ']'; + + SET @sqlCreateTable = ' + CREATE TABLE ' + @bakTableName + '( + [RowID] [bigint] NOT NULL DEFAULT 0, + [TimeClassID] [tinyint] NOT NULL DEFAULT 0, + [TimeClassCode] [nvarchar](100) NOT NULL DEFAULT '''', + [FiscalYearID] [smallint] NOT NULL DEFAULT 0, + [FiscalYearCode] [nvarchar](100) NOT NULL DEFAULT '''', + [FiscalMonthID] [tinyint] NOT NULL DEFAULT 0, + [FiscalMonthCode] [nvarchar](100) NOT NULL DEFAULT '''', + [DepartmentID] [int] NOT NULL DEFAULT 0, + [DepartmentCode] [nvarchar](100) NOT NULL DEFAULT '''', + [PatientClassID] [int] NOT NULL DEFAULT 0, + [PatientClassCode] [nvarchar](100) NOT NULL DEFAULT '''', + [ChargeCodeID] [int] NOT NULL DEFAULT 0, + [ChargeCode] [nvarchar](100) NOT NULL DEFAULT '''', + [ServiceLineID] [int] NOT NULL DEFAULT 0, + [ServiceLine] [nvarchar](100) NOT NULL DEFAULT '''', + [MedicalSurgicalID] [int] NOT NULL DEFAULT 0, + [MedSurg] [nvarchar](100) NOT NULL DEFAULT '''', + [AgeCohortID] [int] NOT NULL DEFAULT 0, + [AgeCohort] [nvarchar](100) NOT NULL DEFAULT '''', + [UnitTypeID] [tinyint] NOT NULL DEFAULT 0, + [UnitType] [nvarchar](100) NOT NULL DEFAULT '''', + [Value] [decimal](19, 4) NOT NULL DEFAULT 0, + [IsDeleted] [bit] NOT NULL DEFAULT 0, + [HistoryItemGUID] [uniqueidentifier] NOT NULL DEFAULT CAST(0x0 AS UNIQUEIDENTIFIER), + [Version] [varbinary](8) NOT NULL DEFAULT(0x), + [TransactionID] [int] NOT NULL DEFAULT 0 + ); + + INSERT INTO ' + @bakTableName + ' WITH(TABLOCK) ( + RowID, + TimeClassID, + TimeClassCode, + FiscalYearID, + FiscalYearCode, + FiscalMonthID, + FiscalMonthCode, + DepartmentID, + DepartmentCode, + PatientClassID, + PatientClassCode, + ChargeCodeID, + ChargeCode, + ServiceLineID, + ServiceLine, + MedicalSurgicalID, + MedSurg, + AgeCohortID, + AgeCohort, + UnitTypeID, + UnitType, + Value, + IsDeleted, + HistoryItemGUID, + Version, + TransactionID) + SELECT + RowID, + TimeClassID, + TimeClassCode, + FiscalYearID, + FiscalYearCode, + FiscalMonthID, + FiscalMonthCode, + DepartmentID, + DepartmentCode, + PatientClassID, + PatientClassCode, + ChargeCodeID, + ChargeCode, + ServiceLineID, + ServiceLine, + MedicalSurgicalID, + MedSurg, + AgeCohortID, + AgeCohort, + UnitTypeID, + UnitType, + Value, + IsDeleted, + HistoryItemGUID, + Version, + TransactionID + FROM [int].[FactCDM]; + + ALTER TABLE ' + @bakTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE) + '; + EXEC (@sqlCreateTable); + + SET @bakTableName = N'[bak].[intFactStatistic_System_' + @datePostfix + ']'; + + SET @sqlCreateTable = ' + CREATE TABLE ' + @bakTableName + '( + [RowID] [bigint] NOT NULL DEFAULT 0, + [DepartmentID] [int] NOT NULL DEFAULT 0, + [DepartmentCode] [varchar](100) NOT NULL DEFAULT '''', + [AccountID] [int] NOT NULL DEFAULT 0, + [AccountCode] [varchar](50) NOT NULL DEFAULT '''', + [FiscalYearID] [smallint] NOT NULL DEFAULT 0, + [FiscalYearCode] [varchar](20) NOT NULL DEFAULT '''', + [TimeClassID] [tinyint] NOT NULL DEFAULT 0, + [TimeClassCode] [varchar](20) NOT NULL DEFAULT '''', + [FiscalMonthID] [tinyint] NOT NULL DEFAULT 0, + [FiscalMonthCode] [varchar](20) NOT NULL DEFAULT '''', + [Value] [decimal](19, 4) NOT NULL DEFAULT 0, + [IsDeleted] [bit] NOT NULL DEFAULT 0, + [HistoryItemGUID] [uniqueidentifier] NOT NULL DEFAULT CAST(0x0 AS UNIQUEIDENTIFIER), + [Version] [varbinary](8) NOT NULL DEFAULT(0x), + [TransactionID] [int] NULL DEFAULT 0 + ); + + INSERT INTO ' + @bakTableName + ' WITH(TABLOCK) ( + RowID, + DepartmentID, + DepartmentCode, + AccountID, + AccountCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + FiscalMonthID, + FiscalMonthCode, + Value, + IsDeleted, + HistoryItemGUID, + Version, + TransactionID) + SELECT + RowID, + DepartmentID, + DepartmentCode, + AccountID, + AccountCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + FiscalMonthID, + FiscalMonthCode, + Value, + IsDeleted, + HistoryItemGUID, + Version, + TransactionID + FROM [int].[FactStatistic]; + + ALTER TABLE ' + @bakTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE) + '; + EXEC (@sqlCreateTable); + + SET @bakTableName = N'[bak].[intFactGL_System_' + @datePostfix + ']'; + + SET @sqlCreateTable = ' + CREATE TABLE ' + @bakTableName + '( + [RowID] [bigint] NOT NULL DEFAULT 0, + [DepartmentID] [int] NOT NULL DEFAULT 0, + [DepartmentCode] [varchar](100) NOT NULL DEFAULT '''', + [AccountID] [int] NOT NULL DEFAULT 0, + [AccountCode] [varchar](50) NOT NULL DEFAULT '''', + [FiscalYearID] [smallint] NOT NULL DEFAULT 0, + [FiscalYearCode] [varchar](20) NOT NULL DEFAULT '''', + [TimeClassID] [tinyint] NOT NULL DEFAULT 0, + [TimeClassCode] [varchar](20) NOT NULL DEFAULT '''', + [FiscalMonthID] [tinyint] NOT NULL DEFAULT 0, + [FiscalMonthCode] [varchar](20) NOT NULL DEFAULT '''', + [Value] [decimal](19, 4) NOT NULL DEFAULT 0, + [IsDeleted] [bit] NOT NULL DEFAULT 0, + [HistoryItemGUID] [uniqueidentifier] NOT NULL DEFAULT CAST(0x0 AS UNIQUEIDENTIFIER), + [Version] [varbinary](8) NOT NULL DEFAULT(0x), + [TransactionID] [int] NULL DEFAULT 0 + ); + + INSERT INTO ' + @bakTableName + ' WITH(TABLOCK) ( + RowID, + DepartmentID, + DepartmentCode, + AccountID, + AccountCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + FiscalMonthID, + FiscalMonthCode, + Value, + IsDeleted, + HistoryItemGUID, + Version, + TransactionID) + SELECT + RowID, + DepartmentID, + DepartmentCode, + AccountID, + AccountCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + FiscalMonthID, + FiscalMonthCode, + Value, + IsDeleted, + HistoryItemGUID, + Version, + TransactionID + FROM [int].[FactGL]; + + ALTER TABLE ' + @bakTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE) + '; + EXEC (@sqlCreateTable); + + SET @bakTableName = N'[bak].[intFactStaffing_System_' + @datePostfix + ']'; + + SET @sqlCreateTable = ' + CREATE TABLE ' + @bakTableName + '( + [RowID] [bigint] NOT NULL DEFAULT 0, + [DepartmentID] [int] NOT NULL DEFAULT 0, + [DepartmentCode] [varchar](100) NOT NULL DEFAULT '''', + [JobCodeID] [int] NOT NULL DEFAULT 0, + [JobCode] [varchar](50) NOT NULL DEFAULT '''', + [EmployeeID] [int] NOT NULL DEFAULT 0, + [Employeecode] [nvarchar](2000) NOT NULL DEFAULT '''', + [PayCodeID] [smallint] NOT NULL DEFAULT 0, + [PayCode] [varchar](50) NOT NULL DEFAULT '''', + [FiscalYearID] [smallint] NOT NULL DEFAULT 0, + [FiscalYearCode] [varchar](20) NOT NULL DEFAULT '''', + [TimeClassID] [tinyint] NOT NULL DEFAULT 0, + [TimeClassCode] [varchar](20) NOT NULL DEFAULT '''', + [UnitTypeID] [tinyint] NOT NULL DEFAULT 0, + [UnitType] [varchar](20) NOT NULL DEFAULT '''', + [FiscalMonthID] [tinyint] NOT NULL DEFAULT 0, + [FiscalMonthCode] [varchar](20) NOT NULL DEFAULT '''', + [Value] [decimal](19, 4) NOT NULL DEFAULT 0, + [IsDeleted] [bit] NOT NULL DEFAULT 0, + [HistoryItemGUID] [uniqueidentifier] NOT NULL DEFAULT CAST(0x0 AS UNIQUEIDENTIFIER), + [Version] [varbinary](8) NOT NULL DEFAULT(0x), + [TransactionID] [int] NULL DEFAULT 0, + [GlPostDateID] [int] NOT NULL DEFAULT 0, + [GlPostDateTime] [datetime] NOT NULL DEFAULT 0 + ); + + INSERT INTO ' + @bakTableName + ' WITH(TABLOCK) ( + RowID, + DepartmentID, + DepartmentCode, + JobCodeID, + JobCode, + EmployeeID, + Employeecode, + PayCodeID, + PayCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + UnitTypeID, + UnitType, + FiscalMonthID, + FiscalMonthCode, + Value, + IsDeleted, + HistoryItemGUID, + Version, + TransactionID, + GlPostDateID, + GlPostDateTime) + SELECT + RowID, + DepartmentID, + DepartmentCode, + JobCodeID, + JobCode, + EmployeeID, + Employeecode, + PayCodeID, + PayCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + UnitTypeID, + UnitType, + FiscalMonthID, + FiscalMonthCode, + Value, + IsDeleted, + HistoryItemGUID, + Version, + TransactionID, + GlPostDateID, + GlPostDateTime + FROM [int].[FactStaffing]; + + ALTER TABLE ' + @bakTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE) + '; + EXEC (@sqlCreateTable); + + SET @bakTableName = N'[bak].[intFactProvider_System_' + @datePostfix + ']'; + + SET @sqlCreateTable = ' + CREATE TABLE ' + @bakTableName + '( + [RowID] [bigint] NOT NULL DEFAULT 0, + [IsDeleted] [bit] NOT NULL DEFAULT 0, + [HistoryItemGUID] [uniqueidentifier] NOT NULL DEFAULT CAST(0x0 AS UNIQUEIDENTIFIER), + [Version] [varbinary](8) NOT NULL DEFAULT(0x), + [TransactionID] [int] NOT NULL DEFAULT 0, + [TimeClassID] [tinyint] NOT NULL DEFAULT 0, + [PhysicianID] [int] NOT NULL DEFAULT 0, + [FiscalYearID] [smallint] NOT NULL DEFAULT 0, + [FiscalMonthID] [tinyint] NOT NULL DEFAULT 0, + [ProviderLineItemID] [int] NOT NULL DEFAULT 0, + [UnitTypeID] [tinyint] NOT NULL DEFAULT 0, + [DepartmentID] [int] NOT NULL DEFAULT 0, + [DepartmentCode] [nvarchar](2000) NOT NULL DEFAULT '''', + [FiscalMonthCode] [nvarchar](2000) NOT NULL DEFAULT '''', + [FiscalYearCode] [nvarchar](2000) NOT NULL DEFAULT '''', + [ProviderCode] [nvarchar](2000) NOT NULL DEFAULT '''', + [TimeClassCode] [nvarchar](2000) NOT NULL DEFAULT '''', + [UnitTypeName] [nvarchar](2000) NOT NULL DEFAULT '''', + [Value] [decimal](19, 4) NOT NULL DEFAULT 0 + ); + + INSERT INTO ' + @bakTableName + ' WITH(TABLOCK) ( + RowID, + IsDeleted, + HistoryItemGUID, + Version, + TransactionID, + TimeClassID, + PhysicianID, + FiscalYearID, + FiscalMonthID, + ProviderLineItemID, + UnitTypeID, + DepartmentID, + DepartmentCode, + FiscalMonthCode, + FiscalYearCode, + ProviderCode, + TimeClassCode, + UnitTypeName, + Value) + SELECT + RowID, + IsDeleted, + HistoryItemGUID, + Version, + TransactionID, + TimeClassID, + PhysicianID, + FiscalYearID, + FiscalMonthID, + ProviderLineItemID, + UnitTypeID, + DepartmentID, + DepartmentCode, + FiscalMonthCode, + FiscalYearCode, + ProviderCode, + TimeClassCode, + UnitTypeName, + Value + FROM [int].[FactProvider]; + + ALTER TABLE ' + @bakTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE) + '; + EXEC (@sqlCreateTable); + + SET @bakTableName = N'[bak].[intFactImportProvider_System_' + @datePostfix + ']'; + + SET @sqlCreateTable = ' + CREATE TABLE ' + @bakTableName + '( + [RowID] [bigint] NOT NULL DEFAULT 0, + [DepartmentID] [int] NOT NULL DEFAULT 0, + [ProviderID] [int] NOT NULL DEFAULT 0, + [FiscalMonthID] [tinyint] NOT NULL DEFAULT 0, + [FiscalYearID] [smallint] NOT NULL DEFAULT 0, + [OBForecastDetailID] [int] NOT NULL DEFAULT 0, + [TimeClassID] [tinyint] NOT NULL DEFAULT 0, + [AccountRollup] [nvarchar](2000) NOT NULL DEFAULT '''', + [DepartmentCode] [nvarchar](2000) NOT NULL DEFAULT '''', + [FiscalMonthCode] [nvarchar](2000) NOT NULL DEFAULT '''', + [FiscalYearCode] [nvarchar](2000) NOT NULL DEFAULT '''', + [ProviderCode] [nvarchar](2000) NOT NULL DEFAULT '''', + [TimeClassCode] [nvarchar](2000) NOT NULL DEFAULT '''', + [Value] [decimal](19, 4) NOT NULL DEFAULT 0, + [IsDeleted] [bit] NOT NULL DEFAULT 0, + [HistoryItemGUID] [uniqueidentifier] NOT NULL DEFAULT CAST(0x0 AS UNIQUEIDENTIFIER), + [Version] [varbinary](8) NOT NULL DEFAULT(0x), + [TransactionID] [int] NOT NULL DEFAULT 0 + ); + + INSERT INTO ' + @bakTableName + ' WITH(TABLOCK) ( + RowID, + DepartmentID, + ProviderID, + FiscalMonthID, + FiscalYearID, + OBForecastDetailID, + TimeClassID, + AccountRollup, + DepartmentCode, + FiscalMonthCode, + FiscalYearCode, + ProviderCode, + TimeClassCode, + Value, + IsDeleted, + HistoryItemGUID, + Version, + TransactionID) + SELECT + RowID, + DepartmentID, + ProviderID, + FiscalMonthID, + FiscalYearID, + OBForecastDetailID, + TimeClassID, + AccountRollup, + DepartmentCode, + FiscalMonthCode, + FiscalYearCode, + ProviderCode, + TimeClassCode, + Value, + IsDeleted, + HistoryItemGUID, + Version, + TransactionID + FROM [int].[FactImportProvider]; + + ALTER TABLE ' + @bakTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE) + '; + + EXEC (@sqlCreateTable); + + SET @bakTableName = N'[bak].[intFactStaffingByPayPeriod_System_' + @datePostfix + ']'; + + SET @sqlCreateTable = ' + CREATE TABLE ' + @bakTableName + '( + [RowID] [bigint] NOT NULL DEFAULT 0, + [DepartmentID] [int] NOT NULL DEFAULT 0, + [DepartmentCode] [varchar](100) NOT NULL DEFAULT '''', + [JobCodeID] [int] NOT NULL DEFAULT 0, + [JobCode] [varchar](50) NOT NULL DEFAULT '''', + [PayCodeID] [smallint] NOT NULL DEFAULT 0, + [PayCode] [varchar](50) NOT NULL DEFAULT '''', + [PayPeriodID] [smallint] NOT NULL DEFAULT 0, + [PayPeriodCode] [varchar](50) NOT NULL DEFAULT '''', + [FiscalYearID] [smallint] NOT NULL DEFAULT 0, + [FiscalYearCode] [varchar](20) NOT NULL DEFAULT '''', + [TimeClassID] [tinyint] NOT NULL DEFAULT 0, + [TimeClassCode] [varchar](20) NOT NULL DEFAULT '''', + [UnitTypeID] [tinyint] NOT NULL DEFAULT 0, + [UnitType] [varchar](20) NOT NULL DEFAULT '''', + [Value] [decimal](19, 4) NOT NULL DEFAULT 0, + [HistoryItemGUID] [uniqueidentifier] NOT NULL DEFAULT (''00000000-0000-0000-0000-000000000000''), + [Version] [varbinary](8) NOT NULL DEFAULT(0x), + [EmployeeID] [int] NOT NULL DEFAULT 0, + [Employeecode] [nvarchar](2000) NOT NULL DEFAULT '''', + [TransactionID] [int] NULL DEFAULT 0, + [IsDeleted] [bit] NOT NULL DEFAULT 0, + [GlPostDateID] [int] NOT NULL DEFAULT 0, + [GlPostDateTime] [datetime] NOT NULL DEFAULT (getdate()) + ); + + INSERT INTO ' + @bakTableName + ' WITH(TABLOCK) ( + RowID, + DepartmentID, + DepartmentCode, + JobCodeID, + JobCode, + PayCodeID, + PayCode, + PayPeriodID, + PayPeriodCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + UnitTypeID, + UnitType, + Value, + HistoryItemGUID, + Version, + EmployeeID, + Employeecode, + TransactionID, + IsDeleted, + GlPostDateID, + GlPostDateTime) + SELECT + RowID, + DepartmentID, + DepartmentCode, + JobCodeID, + JobCode, + PayCodeID, + PayCode, + PayPeriodID, + PayPeriodCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + UnitTypeID, + UnitType, + Value, + HistoryItemGUID, + Version, + EmployeeID, + Employeecode, + TransactionID, + IsDeleted, + GlPostDateID, + GlPostDateTime + FROM [int].[FactStaffingByPayPeriod]; + + ALTER TABLE ' + @bakTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE) + '; + + EXEC (@sqlCreateTable); + + SET @bakTableName = N'[bak].[intFactStatisticsByPayPeriod_System_' + @datePostfix + ']'; + + SET @sqlCreateTable = ' + CREATE TABLE ' + @bakTableName + '( + [RowID] [int] NOT NULL DEFAULT 0, + [TimeClassID] [tinyint] NOT NULL DEFAULT 0, + [TimeClassCode] [nvarchar](100) NOT NULL DEFAULT '''', + [FiscalYearID] [smallint] NOT NULL DEFAULT 0, + [FiscalYearCode] [nvarchar](100) NOT NULL DEFAULT '''', + [PayPeriodID] [smallint] NOT NULL DEFAULT 0, + [PayPeriodCode] [nvarchar](100) NOT NULL DEFAULT '''', + [FiscalMonthID] [tinyint] NOT NULL DEFAULT 0, + [EntityID] [int] NOT NULL DEFAULT 0, + [EntityDescription] [nvarchar](200) NOT NULL DEFAULT '''', + [DepartmentID] [int] NOT NULL DEFAULT 0, + [DepartmentCode] [nvarchar](100) NOT NULL DEFAULT '''', + [DepartmentDescription] [nvarchar](200) NOT NULL, + [AccountID] [int] NOT NULL DEFAULT 0, + [AccountCode] [nvarchar](100) NOT NULL DEFAULT '''', + [AccountDescription] [nvarchar](160) NOT NULL, + [GLRollup] [nvarchar](100) NOT NULL DEFAULT '''', + [Value] [decimal](19, 4) NOT NULL DEFAULT 0, + [IsDeleted] [bit] NOT NULL DEFAULT 0, + [HistoryItemGUID] [uniqueidentifier] NOT NULL DEFAULT (''00000000-0000-0000-0000-000000000000''), + [Version] [varbinary](8) NOT NULL DEFAULT(0x), + [TransactionID] [int] NOT NULL DEFAULT 0, + ); + + INSERT INTO ' + @bakTableName + ' WITH(TABLOCK) ( + RowID, + TimeClassID, + TimeClassCode, + FiscalYearID, + FiscalYearCode, + PayPeriodID, + PayPeriodCode, + FiscalMonthID, + EntityID, + EntityDescription, + DepartmentID, + DepartmentCode, + DepartmentDescription, + AccountID, + AccountCode, + AccountDescription, + GLRollup, + Value, + IsDeleted, + HistoryItemGUID, + Version, + TransactionID) + SELECT + RowID, + TimeClassID, + TimeClassCode, + FiscalYearID, + FiscalYearCode, + PayPeriodID, + PayPeriodCode, + FiscalMonthID, + EntityID, + EntityDescription, + DepartmentID, + DepartmentCode, + DepartmentDescription, + AccountID, + AccountCode, + AccountDescription, + GLRollup, + Value, + IsDeleted, + HistoryItemGUID, + Version, + TransactionID + FROM [int].[FactStatisticsbyPayPeriod]; + + ALTER TABLE ' + @bakTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE) + '; + + EXEC (@sqlCreateTable); + + +END +GO + + +--------------------------------------------- + +-- fp.procStatisticAdjustment_SEL_LIST +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2020-06-03 LR JAZZ-134 Now including deleted items to be displayed in the activity pane + ** 2 2020-07-01 OP JAZZ-635 Added AP Entity Config roles support + ** 3 2020-08-20 OP JAZZ-4123 Fixed import comment + ** 4 2021-04-23 NT JAZZ-18228 Renamed proc (originally StatisticAdjustment_SEL_LIST) and added SubsectionID parameter and related filter + ** 5 2021-12-07 MZ JAZZ-27414 Added Add provider adjustment + ** 6 2022-09-02 AO JAZZ-42931 Fixed search by Adjustment Type + ** 7 2023-01-06 NT JAZZ-45457 Include new IsErrored field in order to display "DELETED - ADJUSTMENT FAILED" in the activity card + ** 8 2023-01-04 MZ JAZZ-47034 Selected BudgetPhaseID from fp.StatisticsAdjustment instead of casting based on AdjustmentType + ** 9 2024-02-22 MY JAZZ-67143 Filters acting unexpectedly post-adjustment - Issue #2 + *************************************************************/ +CREATE PROCEDURE [fp].[procStatisticAdjustment_SEL_LIST] + @budgetGUID UNIQUEIDENTIFIER, + @start INT, + @end INT, + @search VARCHAR(MAX), + @filter VARCHAR(MAX), + @userGUID UNIQUEIDENTIFIER, + @isDataSecured BIT, + @dateTimeFormat VARCHAR(30), + @userTimeZone VARCHAR(50), + @SubsectionID int +AS + +BEGIN + + CREATE TABLE #departmentsSecurity ( + DepartmentID INT NULL, + EntityID INT NULL + ) + + CREATE TABLE #securedAdjustments ( + AdjustmentGUID UNIQUEIDENTIFIER + ) + + DECLARE @guidEmpty UNIQUEIDENTIFIER = [dbo].[ZeroGUID]() + DECLARE @pageSize INT = @end - @start; + + SET @search = LOWER(NULLIF('%' + @search+ '%', '%\%')) + SET @filter = LOWER(NULLIF(@filter, '')) + + SELECT AdjustmentGUID + ,GroupingHierarchyJSON + ,JSON_VALUE(AdjustmentFilterJSON, '$.Entity.ID') AS EntityID + ,JSON_VALUE(AdjustmentFilterJSON, '$.Department.ID') AS DepartmentID + ,AdjustmentType + ,GroupingGUID + INTO #adjustments + FROM fp.StatisticsAdjustment AS slea WITH (NOLOCK) + WHERE slea.AdjustmentType IN (0, 2, 1, 4, 3, 10, 11, 12, 13, 14, 15) -- Supported Adjustment types for Statistic Adjustments + AND slea.BudgetConfigGUID = @budgetGUID + AND slea.SubsectionID = @SubsectionID + + IF @isDataSecured = 1 + BEGIN + INSERT INTO #departmentsSecurity + EXEC fp.DepartmentsSecurity_SEL + @userGUID = @userGUID, + @pageName = 'Statistics' + + CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #departmentsSecurity (DepartmentID, EntityID) + + SELECT AdjustmentGUID + ,ahd.ID AS DepartmentID + INTO #adjustmentGroupingHierarchyDepartments + FROM ( + SELECT adj.AdjustmentGUID + ,adj.GroupingHierarchyJSON + FROM #adjustments AS adj + WHERE adj.EntityID IS NULL + AND adj.DepartmentID IS NULL) AS slea + OUTER APPLY fp.GetAdjustmentHierarchyIDs(slea.GroupingHierarchyJSON, 'Department') AS ahd + GROUP BY AdjustmentGUID + ,ahd.ID + + SELECT adj.AdjustmentGUID, + ahe.ID AS EntityID + INTO #adjustmentGroupingHierarchyEntities + FROM #adjustments AS adj + JOIN #adjustmentGroupingHierarchyDepartments AS adhd ON adhd.AdjustmentGUID = adj.AdjustmentGUID + AND adhd.DepartmentID IS NULL + OUTER APPLY fp.GetAdjustmentHierarchyIDs(adj.GroupingHierarchyJSON, 'Entity') AS ahe + GROUP BY adj.AdjustmentGUID + ,ahe.ID + + INSERT INTO #securedAdjustments + SELECT res.AdjustmentGUID + FROM ( + SELECT slea.AdjustmentGUID + FROM #adjustments AS slea + JOIN #departmentsSecurity AS ds ON ds.DepartmentID = slea.DepartmentID + GROUP BY slea.AdjustmentGUID + + UNION ALL + + SELECT slea.AdjustmentGUID + FROM #adjustments AS slea + JOIN #departmentsSecurity AS dse ON dse.EntityID = slea.EntityID + WHERE slea.DepartmentID IS NULL + GROUP BY slea.AdjustmentGUID + + UNION ALL + + SELECT aghd.AdjustmentGUID + FROM #adjustmentGroupingHierarchyDepartments AS aghd + JOIN #departmentsSecurity AS dshd ON dshd.DepartmentID = aghd.DepartmentID + WHERE dshd.DepartmentID IS NOT NULL + GROUP BY aghd.AdjustmentGUID + + UNION ALL + + SELECT aghe.AdjustmentGUID + FROM #adjustmentGroupingHierarchyEntities AS aghe + JOIN #departmentsSecurity AS dshd ON dshd.EntityID = aghe.EntityID + GROUP BY aghe.AdjustmentGUID + + UNION ALL + + SELECT adj.AdjustmentGUID + FROM #adjustments AS adj + JOIN #adjustmentGroupingHierarchyDepartments AS aghd ON aghd.AdjustmentGUID = adj.AdjustmentGUID + JOIN #adjustmentGroupingHierarchyEntities AS aghe ON aghe.AdjustmentGUID = adj.AdjustmentGUID + WHERE adj.DepartmentID IS NULL + AND adj.EntityID IS NULL + AND aghd.DepartmentID IS NULL + AND aghe.EntityID IS NULL + AND adj.AdjustmentType <> 15 -- Add provider adjustment, that has no grouping hierarchy, but has security + GROUP BY adj.AdjustmentGUID + + UNION ALL + + SELECT adj.AdjustmentGUID + FROM #adjustments AS adj + JOIN fp.StatisticAddProviderAdjustment AS sleapa ON adj.AdjustmentGUID = sleapa.AdjustmentGUID + JOIN #departmentsSecurity AS ds ON ds.DepartmentID = sleapa.DepartmentID + GROUP BY adj.AdjustmentGUID + ) AS res + + -- JAZZ-67143: Filters acting unexpectedly post-adjustment (Issue #2) + -- Essentially we had cases where a custom roll up would cause local admins to make an adjustment and the + -- adjustment would not show up in the pane. This is due to roll up adjustments as everything else seems to be fine. + -- Essentially what we are doing here is using the child adjustments to find if they fall in security. + -- In the event we have a child, populate the parent adjustment in the list. + -- Find all the GroupingGuid's for any child adjustments that fall into security. + + SELECT DISTINCT adj.GroupingGUID + INTO #groupingAdjustments + FROM #securedAdjustments secured + INNER JOIN #adjustments adj ON secured.AdjustmentGUID = adj.AdjustmentGUID + WHERE adj.GroupingGUID != '00000000-0000-0000-0000-000000000000' -- Only care about roll up adjustments. + + -- Once we have the GroupingGUIDs based on the security, we can insert the parent adjustment. + INSERT INTO #securedAdjustments + SELECT adj.AdjustmentGUID + FROM #adjustments adj + INNER JOIN #groupingAdjustments grp ON adj.GroupingGUID = grp.GroupingGUID + LEFT JOIN #securedAdjustments secured ON adj.AdjustmentGUID = secured.AdjustmentGUID + WHERE adj.AdjustmentType IN (12, 13, 14) -- Roll Up Adjustments + AND secured.AdjustmentGUID IS NULL + + END + ELSE + BEGIN + + INSERT INTO #securedAdjustments + SELECT AdjustmentGUID + FROM #adjustments + + END + + CREATE CLUSTERED INDEX PK_SecuredAdjustmnets ON #securedAdjustments (AdjustmentGUID) + + SELECT iadj.AdjustmentGuid, + iadj.UnitTypeID + INTO #importAdjustments + FROM fp.StatisticsAdjustmentImport AS iadj WITH (NOLOCK) + JOIN #securedAdjustments AS sadj ON sadj.AdjustmentGUID = iadj.AdjustmentGUID + LEFT JOIN #departmentsSecurity AS ds ON ds.DepartmentID = iadj.DepartmentID + WHERE ds.DepartmentID IS NOT NULL + OR @isDataSecured = 0 + GROUP BY iadj.AdjustmentGuid, + iadj.UnitTypeID + + CREATE CLUSTERED INDEX PK_ImportAdjustmnets ON #importAdjustments (AdjustmentGUID, UnitTypeID) + + SELECT res.TotalRowsCount + ,res.AdjustmentGUID + ,res.BudgetConfigGUID + ,res.AdjustmentType + ,res.[Value] + ,res.AdjustmentFilterJSON + ,res.GroupingHierarchyJSON + ,res.AdjustedProperty + ,res.Comment + ,res.AuthorGUID + ,res.AuthorFullName + ,res.LastModifiedDateUtc + ,res.DateCreatedUtc + ,res.GroupingGUID + ,res.TimeClassID + ,res.BudgetPhaseID + ,res.ClassificationGroupID + ,res.ClassificationCategoryID + ,res.JobCode + ,res.JobCodeCount + ,res.DepartmentCode + ,res.DepartmentCount + ,res.UnitTypeID + ,res.ImportUnitTypeIDs + ,res.AddProviderFirstName + ,res.AddProviderLastName + ,res.AddProviderType + ,res.IsRecordDeleted + ,res.IsErrored + FROM ( + SELECT COUNT(res_inner.AdjustmentGUID) OVER () AS TotalRowsCount, + * + FROM ( + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber + , slea.AdjustmentGUID + ,slea.BudgetConfigGUID + ,slea.AdjustmentType + ,slea.[Value] + ,slea.AdjustmentFilterJSON + ,slea.GroupingHierarchyJSON + ,slea.AdjustedProperty + ,ISNULL(ag.Description, slea.Comment) AS Comment + ,slea.AuthorGUID + ,slea.AuthorFullName + ,slea.LastModifiedDateUtc + ,slea.DateCreatedUtc + ,slea.GroupingGUID + ,slea.TimeClassID + ,slea.BudgetPhaseID + ,slea.ClassificationGroupID + ,slea.ClassificationCategoryID + ,slea.UnitTypeID + ,NULL AS JobCode + ,NULL AS JobCodeCount + ,NULL AS DepartmentCode + ,NULL AS DepartmentCount + ,sai.ImportUnitTypeIDs + ,NULL AS AddProviderFirstName + ,NULL AS AddProviderLastName + ,NULL AS AddProviderType + ,slea.IsRecordDeleted + ,slea.IsErrored + FROM ( SELECT + adj.* + ,CAST(140 AS TINYINT) AS UnitTypeID + ,JSON_VALUE(AdjustmentFilterJSON, '$.Entity.ID') AS EntityID + ,JSON_VALUE(AdjustmentFilterJSON, '$.Department.ID') AS DepartmentID + FROM fp.StatisticsAdjustment AS adj WITH (NOLOCK) + JOIN #securedAdjustments AS sadj ON sadj.AdjustmentGUID = adj.AdjustmentGUID + WHERE adj.SubsectionID = @SubsectionID + ) AS slea + LEFT JOIN ( + SELECT p.AdjustmentGUID, + ImportUnitTypeIDs = + TRIM(STUFF( + (SELECT N' ' + CAST(p2.UnitTypeID AS VARCHAR(5)) + FROM #importAdjustments AS p2 + WHERE p2.AdjustmentGUID = p.AdjustmentGUID + GROUP BY p2.AdjustmentGUID, + p2.UnitTypeID + FOR XML PATH(N'')) + , 1, 0, N'')) + FROM #importAdjustments AS p + GROUP BY p.AdjustmentGUID + ) AS sai ON sai.AdjustmentGUID = slea.AdjustmentGUID + LEFT JOIN fp.viewAdjustmentGrouping AS ag WITH (NOLOCK) ON ag.GroupingGUID = slea.GroupingGUID + LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = slea.ClassificationGroupID + LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acg.GroupID = acg.GroupID + AND slea.ClassificationCategoryID = acc.CategoryID + LEFT JOIN ( + SELECT nsa.GroupingGUID + FROM fp.StatisticsAdjustment as nsa WITH (NOLOCK) + WHERE nsa.AdjustmentType IN (12, 13, 14) + AND nsa.BudgetConfigGUID = @budgetGUID + AND nsa.SubsectionID = @SubsectionID + GROUP BY nsa.GroupingGUID + ) AS ra ON ra.GroupingGUID = slea.GroupingGUID + WHERE (slea.AdjustmentType <> 4 + OR sai.ImportUnitTypeIDs <> '') -- Check department security for import adjustment + AND slea.AdjustmentType IN (0, 2, 1, 4, 3, 10, 11, 12, 13, 14) -- Supported Adjustment types for Statistic Adjustments + AND (ra.GroupingGUID IS NULL + OR slea.AdjustmentType IN (12, 13, 14)) + AND (@search IS NULL + OR ( + LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(fp.GetAdjustmentValue(slea.Value, slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\' + OR LOWER(ISNULL(ag.Description, slea.Comment)) LIKE @search ESCAPE '\' + OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR acc.[Name] LIKE @search ESCAPE '\' + OR acg.[Name] LIKE @search ESCAPE '\' + OR fp.SearchHierarchyLevel(slea.AdjustmentFilterJSON, @search) = 1 + OR LOWER(fp.GetAdjustmentMeasure(slea.AdjustmentType, slea.UnitTypeID)) LIKE @search ESCAPE '\' + OR fp.SearchAdjustmentMeasureForImport(slea.AdjustmentType, sai.ImportUnitTypeIDs, @search) = 1 + ) + ) + AND (@filter IS NULL + OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, slea.BudgetPhaseID) IN ( + SELECT [value] + FROM STRING_SPLIT(@filter, ' ' ) + ) + ) + + -- Add Provider adjustments + UNION ALL + + SELECT ROW_NUMBER() OVER (PARTITION BY slea.AdjustmentGUID ORDER BY slea.DateCreatedUtc DESC) AS RowNumber + , slea.AdjustmentGUID + ,slea.BudgetConfigGUID + ,slea.AdjustmentType + ,slea.[Value] + ,slea.AdjustmentFilterJSON + ,slea.GroupingHierarchyJSON + ,slea.AdjustedProperty + ,aps.Comment + ,slea.AuthorGUID + ,slea.AuthorFullName + ,slea.LastModifiedDateUtc + ,slea.DateCreatedUtc + ,slea.GroupingGUID + ,slea.TimeClassID + ,2 AS BudgetPhaseID + ,aps.ClassificationGroupID + ,aps.ClassificationCategoryID + ,NULL AS UnitTypeID + ,NULL AS JobCode + ,NULL AS JobCodeCount + ,NULL AS DepartmentCode + ,NULL AS DepartmentCount + ,NULL AS ImportUnitTypeIDs + ,de.NameFirst AS AddProviderFirstName + ,de.NameLast AS AddProviderLastName + ,aps.EmployeeType AS AddProviderType + ,slea.IsRecordDeleted + ,slea.IsErrored + FROM fp.StatisticsAdjustment AS slea WITH (NOLOCK) + JOIN #securedAdjustments AS sleas ON sleas.AdjustmentGUID = slea.AdjustmentGUID + JOIN fp.StatisticAddProviderSummary AS aps ON aps.DriverAdjustmentGUID = slea.AdjustmentGUID + JOIN fw.DimEmployee AS de ON de.EmployeeID = aps.EmployeeID + LEFT JOIN fp.AdjustmentClassificationGroup AS acg WITH (NOLOCK) ON acg.GroupID = aps.ClassificationGroupID + LEFT JOIN fp.AdjustmentClassificationCategory AS acc WITH (NOLOCK) ON acc.GroupID = acg.GroupID + AND aps.ClassificationCategoryID = acc.CategoryID + WHERE slea.AdjustmentType = 15 -- add provider adjustments + AND (@search IS NULL + OR ( + LOWER(fp.GetAdjustmentType(slea.AdjustmentType)) LIKE @search ESCAPE '\' + OR LOWER(slea.AuthorFullName) LIKE @search ESCAPE '\' + OR LOWER(aps.Comment) LIKE @search ESCAPE '\' + OR fp.funcCompareAdjustmentDateTime(slea.DateCreatedUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR fp.funcCompareAdjustmentDateTime(slea.LastModifiedDateUtc, @search, @dateTimeFormat, @userTimeZone) = 1 + OR acc.[Name] LIKE @search ESCAPE '\' + OR acg.[Name] LIKE @search ESCAPE '\' + OR de.NameFull LIKE @search ESCAPE '\' + ) + ) + AND (@filter IS NULL + OR fp.GetAdjustmentTimeClassString(slea.AdjustmentType, slea.TimeClassID, 2) IN ( + SELECT [value] + FROM STRING_SPLIT(@filter, ' ' ) + ) + ) + ) AS res_inner + WHERE res_inner.RowNumber = 1 ) AS res + ORDER BY res.DateCreatedUtc DESC + OFFSET @start ROWS + FETCH NEXT @pageSize ROWS ONLY; +END +GO + + +--------------------------------------------- + +-- fp.procStatisticBudgetStampOff +CREATE PROCEDURE [fp].[procStatisticBudgetStampOff] + @BudgetConfigID INT, + @TargetTimeClassID TINYINT +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 1-31-2023 MY JAZZ-48962 Initial Creation + ** 2 01-03-2024 MZ JAZZ-65385 Added Target TimeClass + ** 3 03-18-2024 MZ JAZZ-68428 Deleting by Chunks & removed HistoryItemGUID parameter + *************************************************************/ + + -- Note: The original script was done here https://confluence.sdt.local/display/DD/Moving+Data+from+a+Plan+Configuration+to+Int+Tables + + DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID ) + DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID) + + DECLARE @HistoryItemGUID UNIQUEIDENTIFIER + EXEC procLogScript 'StampOff: Transferring Budget Data from 1p', @HistoryItemGUID OUTPUT + PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36)) + PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID) + + -- Clear out existing records for the selected FiscalYear and Budgeted Time Class + DECLARE @ChunkCount INT + + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END + + DECLARE @r INT; + SET @r = 1; + + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) FROM [int].[FactStatistic] WHERE FiscalYearID = @FiscalYear and TimeClassID = @TargetTimeClassID + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + INSERT INTO [int].[FactStatistic] ([DepartmentID], [DepartmentCode], [AccountID], [AccountCode], [FiscalYearID], [FiscalYearCode], + [TimeClassID], [TimeClassCode], [FiscalMonthID], [FiscalMonthCode], [Value], [IsDeleted], [HistoryItemGUID]) + SELECT + d.DepartmentID, + d.DepartmentCode, + acc.AccountID, + acc.AccountCode, + bc.FiscalYearID, + bc.FiscalYearID AS FiscalYearCode, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + fm.FiscalMonthID, + fm.FiscalMonthCode, + Value AS Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID + FROM ( + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT cv.StatisticsID, cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.AccountID, cv.PatientClassID, cv.PayorID, cv.FinancialReportingID, cv.UnitTypeID, + bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, + bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactStatistics cv + INNER JOIN fp.FactStatisticsBudget bdgt ON cv.StatisticsID = bdgt.StatisticsID + WHERE bdgt.BudgetPhaseID = 3 + AND cv.BudgetConfigID = @BudgetConfigID + ) cv + UNPIVOT (Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month') + ) BudgetedData + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = BudgetedData.BudgetConfigID + INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = BudgetedData.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = BudgetedData.FiscalMonthID + INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = BudgetedData.UnitTypeID + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = BudgetedData.AccountID + WHERE 1=1 + and BudgetedData.Value <> 0 + and bc.BudgetConfigID = @BudgetConfigID +END +GO + + +--------------------------------------------- + +-- fp.procStatisticProjectionStampOff +CREATE PROCEDURE [fp].[procStatisticProjectionStampOff] + @BudgetConfigID INT, + @TargetTimeClassID TINYINT, + @IsMonthsLoadedIncluded BIT +AS +BEGIN + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 11-10-2023 AO JAZZ-62128 Initial Creation + ** 2 01-04-2024 MZ JAZZ-65385 Added Target TimeClass and IsMonthsLoadedIncluded + ** 3 01-24-2024 MZ JAZZ-64527 Fix Months Loaded + ** 4 03-18-2024 MZ JAZZ-68428 Deleting by Chunks & removed HistoryItemGUID parameter + ** 5 04-03-2024 MZ JAZZ-70053 Fix Month Loaded excluding logic + *************************************************************/ + + -- Note: The original script was done here https://confluence.sdt.local/display/DD/Moving+Data+from+a+Plan+Configuration+to+Int+Tables + + DECLARE @FiscalYear INT = (SELECT bc.FiscalYearID - 1 FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID ) + DECLARE @TimeClassCode NVARCHAR(3) = (SELECT TimeClassCode FROM [fw].[DimTimeClass] WHERE TimeClassID = @TargetTimeClassID) + DECLARE @MonthsLoaded INT = (SELECT bc.MonthsLoaded FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID) + + DECLARE @HistoryItemGUID UNIQUEIDENTIFIER + EXEC procLogScript 'StampOff: Transferring Projection Data from 1p', @HistoryItemGUID OUTPUT + PRINT 'Beginning insert, historyitemguid: ' + CAST(@HistoryItemGUID AS VARCHAR(36)) + PRINT CONCAT('Target TimeClassID: ', @TargetTimeClassID) + + -- Clear out existing records for the selected FiscalYear and Projected Time Class + -- and all months if months loaded included otherwise only months NOT loaded will be cleared + DECLARE @ChunkCount INT + + SELECT @ChunkCount = Value FROM fp.SystemSetting WHERE Name = 'Batch Delete Chunk'; + IF @ChunkCount IS NULL BEGIN SET @ChunkCount = 100000 END + + DECLARE @r INT; + SET @r = 1; + + WHILE @r > 0 + BEGIN + BEGIN TRANSACTION; + DELETE TOP (@ChunkCount) s FROM [int].[FactStatistic] s + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = s.FiscalMonthID + WHERE s.FiscalYearID = @FiscalYear + AND s.TimeClassID = @TargetTimeClassID + AND (@IsMonthsLoadedIncluded = 1 OR fm.SortOrder > @MonthsLoaded) + SET @r = @@ROWCOUNT; + COMMIT TRANSACTION; + END + + INSERT INTO [int].[FactStatistic] ([DepartmentID], [DepartmentCode], [AccountID], [AccountCode], [FiscalYearID], [FiscalYearCode], + [TimeClassID], [TimeClassCode], [FiscalMonthID], [FiscalMonthCode], [Value], [IsDeleted], [HistoryItemGUID]) + SELECT + d.DepartmentID, + d.DepartmentCode, + acc.AccountID, + acc.AccountCode, + @FiscalYear, + @FiscalYear AS FiscalYearCode, + @TargetTimeClassID AS TimeClassID, + @TimeClassCode AS TimeClassCode, + fm.FiscalMonthID, + fm.FiscalMonthCode, + Value AS Value, + '0' AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID + FROM ( + SELECT StatisticsID, BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, PatientClassID, PayorID, FinancialReportingID, UnitTypeID, m.FiscalMonthID, f.Value, LockType + FROM ( + SELECT cv.StatisticsID, cv.BudgetConfigID, cv.EntityGroupConfigID, cv.EntityID, cv.DepartmentID, cv.AccountID, cv.PatientClassID, cv.PayorID, cv.FinancialReportingID, cv.UnitTypeID, + bdgt.LockType, bdgt.AdjustedValue01, bdgt.AdjustedValue02, bdgt.AdjustedValue03, bdgt.AdjustedValue04, bdgt.AdjustedValue05, bdgt.AdjustedValue06, bdgt.AdjustedValue07, + bdgt.AdjustedValue08, bdgt.AdjustedValue09, bdgt.AdjustedValue10, bdgt.AdjustedValue11, bdgt.AdjustedValue12 + FROM fp.FactStatistics cv + INNER JOIN fp.FactStatisticsProjection bdgt ON cv.StatisticsID = bdgt.StatisticsID + WHERE bdgt.BudgetPhaseID = 3 + AND cv.BudgetConfigID = @BudgetConfigID + ) cv + UNPIVOT (Value FOR FiscalMonth IN (AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12)) as f + LEFT JOIN fw.DimFiscalMonth m ON m.MonthColumnName = REPLACE(f.FiscalMonth, 'AdjustedValue', 'Month') + ) BudgetedData + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = BudgetedData.BudgetConfigID + INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = BudgetedData.DepartmentID + INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = BudgetedData.FiscalMonthID + INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = BudgetedData.UnitTypeID + INNER JOIN [fw].[DimAccount] acc ON acc.AccountID = BudgetedData.AccountID + WHERE 1=1 + AND BudgetedData.Value <> 0 + AND bc.BudgetConfigID = @BudgetConfigID + AND (@IsMonthsLoadedIncluded = 1 OR CAST(fm.FiscalMonthCode AS INT) > bc.MonthsLoaded) +END +GO + + +--------------------------------------------- + +-- fp.procStatisticsAddProviderDependentRecordsSelect +CREATE PROCEDURE [fp].[procStatisticsAddProviderDependentRecordsSelect] + @BudgetConfigID INT, + @SelectedProviders [dbo].[SqlInt32ListTableType] READONLY, + @DepartmentIds [dbo].[SqlInt32ListTableType] READONLY, + @AccountIds [dbo].[SqlInt32ListTableType] READONLY + AS + BEGIN + + SELECT [value] AS ProviderID + INTO #BenchProviders + FROM @SelectedProviders + + SELECT [value] AS DepartmentID + INTO #DepartmentSecurity + FROM @DepartmentIds + + SELECT [value] AS AccountID + INTO #AccountIds + FROM @AccountIds + + SELECT fs.AccountID, + fs.FinancialReportingID, + fs.PayorID, + fs.PatientClassID, + fs.ProviderLineItemID + FROM fp.FactStatistics fs + JOIN #DepartmentSecurity ds ON ds.DepartmentID = fs.DepartmentID + JOIN #BenchProviders bp ON bp.ProviderID = fs.ProviderID + JOIN #AccountIds acc ON acc.AccountID = fs.AccountID + WHERE SubsectionID = 2 -- Dependent + AND BudgetConfigID = @BudgetConfigID + AND UnitTypeID = 140 -- Volume + GROUP BY fs.AccountID, + fs.FinancialReportingID, + fs.PayorID, + fs.PatientClassID, + fs.ProviderLineItemID +END +GO + + +--------------------------------------------- + +-- fp.procStatisticsApplySpread +CREATE PROCEDURE [fp].[procStatisticsApplySpread] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +WITH RECOMPILE +AS +BEGIN + + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 03-06-2023 MZ JAZZ-3698 Added provider dimensions + ** 2 12-26-2023 NH JAZZ-59204 Remove Use Provider dimensions for Statistics Spreads + ** 3 2024-01-11 MY JAZZ-XXXXX Re-remove call to procStatisticsApplySpreadsFlexed + ** 4 2024-01-22 MY JAZZ-64799 History Viewer does not handle Spread Impact for Monthly Values + ** 5 2024-01-31 NH JAZZ-64064 Move Provider Planning FF as a setting in Plan Config + ** 6 2024-05-13 MY JAZZ-66920 Fix Feature Flag Check for History Viewer Check and add WITH RECOMPILE + *************************************************************/ + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment; + IF OBJECT_ID('tempdb..#spreadsChangeHistory') IS NOT NULL DROP TABLE #spreadsChangeHistory; + + DECLARE @volumeUnitType INT = 140; + + /*** added in scope of JAZZ-3698 ***/ + DECLARE @UseProviderDimensions bit + SELECT @UseProviderDimensions = IsProviderPlanningEnabled FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID; + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + CREATE TABLE #filterTable (StatisticsID INT PRIMARY KEY CLUSTERED); + + CREATE TABLE #spreadsChangeHistory ( + StatisticsID INT, + OldValue01 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue02 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue03 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue04 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue05 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue06 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue07 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue08 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue09 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue10 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue11 DECIMAL(19, 8) NOT NULL DEFAULT(0), + OldValue12 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue01 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue02 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue03 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue04 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue05 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue06 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue07 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue08 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue09 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue10 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue11 DECIMAL(19, 8) NOT NULL DEFAULT(0), + NewValue12 DECIMAL(19, 8) NOT NULL DEFAULT(0), + ); + + IF EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) + BEGIN + + IF(@UseProviderDimensions = 1) + BEGIN + INSERT INTO #filterTable (StatisticsID) + SELECT DISTINCT basis.StatisticsID + FROM [fp].[FactStatistics] basis + INNER JOIN #FilterByDepartment SD on SD.DepartmentID = basis.DepartmentID + INNER JOIN [fp].[StatisticsSpreads] spread ON spread.BudgetConfigID = basis.BudgetConfigID AND spread.DepartmentID = basis.DepartmentID AND spread.AccountID = basis.AccountID + AND spread.ProviderID = basis.ProviderID AND spread.ProviderLineItemID = basis.ProviderLineItemID + INNER JOIN [fp].[FactStatisticsBudget] fsb ON basis.StatisticsID = fsb.StatisticsID + WHERE basis.BudgetConfigID = @BudgetConfigID + AND basis.UnitTypeID = @volumeUnitType + AND fsb.LockType <> 1 AND fsb.LockType <> 3 AND fsb.LockType <> 7 + END + ELSE BEGIN + INSERT INTO #filterTable (StatisticsID) + SELECT DISTINCT basis.StatisticsID + FROM [fp].[FactStatistics] basis + INNER JOIN #FilterByDepartment SD on SD.DepartmentID = basis.DepartmentID + INNER JOIN [fp].[StatisticsSpreads] spread ON spread.BudgetConfigID = basis.BudgetConfigID AND spread.DepartmentID = basis.DepartmentID AND spread.AccountID = basis.AccountID + INNER JOIN [fp].[FactStatisticsBudget] fsb ON basis.StatisticsID = fsb.StatisticsID + WHERE basis.BudgetConfigID = @BudgetConfigID + AND basis.UnitTypeID = @volumeUnitType + AND fsb.LockType <> 1 AND fsb.LockType <> 3 AND fsb.LockType <> 7 + END + + END + ELSE BEGIN + + IF(@UseProviderDimensions = 1) + BEGIN + INSERT INTO #filterTable (StatisticsID) + SELECT DISTINCT basis.StatisticsID + FROM [fp].[FactStatistics] basis + INNER JOIN [fp].[StatisticsSpreads] spread ON spread.BudgetConfigID = basis.BudgetConfigID AND spread.DepartmentID = basis.DepartmentID AND spread.AccountID = basis.AccountID + AND spread.ProviderID = basis.ProviderID AND spread.ProviderLineItemID = basis.ProviderLineItemID + INNER JOIN [fp].[FactStatisticsBudget] fsb ON basis.StatisticsID = fsb.StatisticsID + WHERE basis.BudgetConfigID = @BudgetConfigID + AND basis.UnitTypeID = @volumeUnitType + AND fsb.LockType <> 1 AND fsb.LockType <> 3 AND fsb.LockType <> 7 + END + ELSE BEGIN + INSERT INTO #filterTable (StatisticsID) + SELECT DISTINCT basis.StatisticsID + FROM [fp].[FactStatistics] basis + INNER JOIN [fp].[StatisticsSpreads] spread ON spread.BudgetConfigID = basis.BudgetConfigID AND spread.DepartmentID = basis.DepartmentID AND spread.AccountID = basis.AccountID + INNER JOIN [fp].[FactStatisticsBudget] fsb ON basis.StatisticsID = fsb.StatisticsID + WHERE basis.BudgetConfigID = @BudgetConfigID + AND basis.UnitTypeID = @volumeUnitType + AND fsb.LockType <> 1 AND fsb.LockType <> 3 AND fsb.LockType <> 7 + END + + END + + IF(@UseProviderDimensions = 1) + BEGIN + + UPDATE fsb + SET LockType = 6, LockFlag = 1 + , AdjustedValue01 = CAST(AdjustedValueTotal * SpreadPercentage01 AS DECIMAL(19,8)) + , AdjustedValue02 = + CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + ELSE CAST(AdjustedValueTotal * SpreadPercentage02 AS DECIMAL(19,8)) END + , AdjustedValue03 = + CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage03 AS DECIMAL(19,8)) END + , AdjustedValue04 = + CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage04 AS DECIMAL(19,8)) END + , AdjustedValue05 = + CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage05 AS DECIMAL(19,8)) END + , AdjustedValue06 = + CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage06 AS DECIMAL(19,8)) END + , AdjustedValue07 = + CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage07 AS DECIMAL(19,8)) END + , AdjustedValue08 = + CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage08 AS DECIMAL(19,8)) END + , AdjustedValue09 = + CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage09 AS DECIMAL(19,8)) END + , AdjustedValue10 = + CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage09) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage10 AS DECIMAL(19,8)) END + , AdjustedValue11 = + CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage10) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage11 AS DECIMAL(19,8)) END + , AdjustedValue12 = + CASE WHEN SpreadPercentage12 != 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage11) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage12 AS DECIMAL(19,8)) END + OUTPUT + inserted.StatisticsID, + deleted.AdjustedValue01, deleted.AdjustedValue02, deleted.AdjustedValue03, deleted.AdjustedValue04, deleted.AdjustedValue05, deleted.AdjustedValue06, + deleted.AdjustedValue07, deleted.AdjustedValue08, deleted.AdjustedValue09, deleted.AdjustedValue10, deleted.AdjustedValue11, deleted.AdjustedValue12, + inserted.AdjustedValue01, inserted.AdjustedValue02, inserted.AdjustedValue03, inserted.AdjustedValue04, inserted.AdjustedValue05, inserted.AdjustedValue06, + inserted.AdjustedValue07, inserted.AdjustedValue08, inserted.AdjustedValue09, inserted.AdjustedValue10, inserted.AdjustedValue11, inserted.AdjustedValue12 + INTO + #spreadsChangeHistory (StatisticsID, + OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06, + OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12, + NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06, + NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) + FROM [fp].[viewStatisticsSpreads] statsp + INNER JOIN [fp].[FactStatistics] fs ON statsp.BudgetConfigID = fs.BudgetConfigID AND statsp.DepartmentID = fs.DepartmentID AND statsp.AccountID = fs.AccountID + AND statsp.ProviderID = fs.ProviderID AND statsp.ProviderLineItemID = fs.ProviderLineItemID + INNER JOIN #filterTable tmp on fs.StatisticsID = tmp.StatisticsID + INNER JOIN [fp].[FactStatisticsBudget] fsb on fs.StatisticsID = fsb.StatisticsID + WHERE fsb.BudgetPhaseID = 3 AND statsp.IsInactive = 0 AND fs.SubsectionID = 1 + + END + ELSE BEGIN + + UPDATE fsb + SET LockType = 6, LockFlag = 1 + , AdjustedValue01 = CAST(AdjustedValueTotal * SpreadPercentage01 AS DECIMAL(19,8)) + , AdjustedValue02 = + CASE WHEN SpreadPercentage02 != 0 AND SpreadPercentage03 = 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + ELSE CAST(AdjustedValueTotal * SpreadPercentage02 AS DECIMAL(19,8)) END + , AdjustedValue03 = + CASE WHEN SpreadPercentage03 != 0 AND SpreadPercentage04 = 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage03 AS DECIMAL(19,8)) END + , AdjustedValue04 = + CASE WHEN SpreadPercentage04 != 0 AND SpreadPercentage05 = 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage04 AS DECIMAL(19,8)) END + , AdjustedValue05 = + CASE WHEN SpreadPercentage05 != 0 AND SpreadPercentage06 = 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage05 AS DECIMAL(19,8)) END + , AdjustedValue06 = + CASE WHEN SpreadPercentage06 != 0 AND SpreadPercentage07 = 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage06 AS DECIMAL(19,8)) END + , AdjustedValue07 = + CASE WHEN SpreadPercentage07 != 0 AND SpreadPercentage08 = 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage07 AS DECIMAL(19,8)) END + , AdjustedValue08 = + CASE WHEN SpreadPercentage08 != 0 AND SpreadPercentage09 = 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage08 AS DECIMAL(19,8)) END + , AdjustedValue09 = + CASE WHEN SpreadPercentage09 != 0 AND SpreadPercentage10 = 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage09 AS DECIMAL(19,8)) END + , AdjustedValue10 = + CASE WHEN SpreadPercentage10 != 0 AND SpreadPercentage11 = 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage09) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage10 AS DECIMAL(19,8)) END + , AdjustedValue11 = + CASE WHEN SpreadPercentage11 != 0 AND SpreadPercentage12 = 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage10) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage11 AS DECIMAL(19,8)) END + , AdjustedValue12 = + CASE WHEN SpreadPercentage12 != 0 + THEN AdjustedValueTotal - (CAST((AdjustedValueTotal * SpreadPercentage01) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage02) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage03) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage04) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage05) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage06) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage07) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage08) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage09) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage10) AS DECIMAL(19, 8)) + CAST((AdjustedValueTotal * SpreadPercentage11) AS DECIMAL(19, 8))) + ELSE CAST(AdjustedValueTotal * SpreadPercentage12 AS DECIMAL(19,8)) END + OUTPUT + inserted.StatisticsID, + deleted.AdjustedValue01, deleted.AdjustedValue02, deleted.AdjustedValue03, deleted.AdjustedValue04, deleted.AdjustedValue05, deleted.AdjustedValue06, + deleted.AdjustedValue07, deleted.AdjustedValue08, deleted.AdjustedValue09, deleted.AdjustedValue10, deleted.AdjustedValue11, deleted.AdjustedValue12, + inserted.AdjustedValue01, inserted.AdjustedValue02, inserted.AdjustedValue03, inserted.AdjustedValue04, inserted.AdjustedValue05, inserted.AdjustedValue06, + inserted.AdjustedValue07, inserted.AdjustedValue08, inserted.AdjustedValue09, inserted.AdjustedValue10, inserted.AdjustedValue11, inserted.AdjustedValue12 + INTO + #spreadsChangeHistory (StatisticsID, + OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06, + OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12, + NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06, + NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) + FROM [fp].[viewStatisticsSpreads] statsp + INNER JOIN [fp].[FactStatistics] fs ON statsp.BudgetConfigID = fs.BudgetConfigID AND statsp.DepartmentID = fs.DepartmentID AND statsp.AccountID = fs.AccountID + INNER JOIN #filterTable tmp on fs.StatisticsID = tmp.StatisticsID + INNER JOIN [fp].[FactStatisticsBudget] fsb on fs.StatisticsID = fsb.StatisticsID + WHERE fsb.BudgetPhaseID = 3 AND statsp.IsInactive = 0 AND fs.SubsectionID = 1 + + END + + -- Populate Change History + IF EXISTS(SELECT 1 + FROM fp.BudgetConfigSetting setting + INNER JOIN [fp].[BudgetConfigDefaultSetting] def ON setting.SettingID = def.SettingID + WHERE def.Name = 'Spreads Change History Logic Is Enabled' + AND setting.Value = 1 + AND setting.BudgetConfigID = @BudgetConfigID) + BEGIN + + INSERT INTO fp.StatisticsSpreadsChangeHistory (StatisticsID, SubsectionID, BudgetConfigID, OldValue01, OldValue02, OldValue03, OldValue04, OldValue05, OldValue06, + OldValue07, OldValue08, OldValue09, OldValue10, OldValue11, OldValue12, NewValue01, NewValue02, NewValue03, NewValue04, NewValue05, NewValue06, + NewValue07, NewValue08, NewValue09, NewValue10, NewValue11, NewValue12) + SELECT StatisticsID, 1, @BudgetConfigID, + ISNULL(OldValue01, 0), ISNULL(OldValue02, 0), ISNULL(OldValue03, 0), ISNULL(OldValue04, 0), ISNULL(OldValue05, 0), ISNULL(OldValue06, 0), + ISNULL(OldValue07, 0), ISNULL(OldValue08, 0), ISNULL(OldValue09, 0), ISNULL(OldValue10, 0), ISNULL(OldValue11, 0), ISNULL(OldValue12, 0), + ISNULL(NewValue01, 0), ISNULL(NewValue02, 0), ISNULL(NewValue03, 0), ISNULL(NewValue04, 0), ISNULL(NewValue05, 0), ISNULL(NewValue06, 0), + ISNULL(NewValue07, 0), ISNULL(NewValue08, 0), ISNULL(NewValue09, 0), ISNULL(NewValue10, 0), ISNULL(NewValue11, 0), ISNULL(NewValue12, 0) + FROM #spreadsChangeHistory + WHERE 1 = 1 + AND ( + OldValue01 != NewValue01 + OR OldValue02 != NewValue02 + OR OldValue03 != NewValue03 + OR OldValue04 != NewValue04 + OR OldValue05 != NewValue05 + OR OldValue06 != NewValue06 + OR OldValue07 != NewValue07 + OR OldValue08 != NewValue08 + OR OldValue09 != NewValue09 + OR OldValue10 != NewValue10 + OR OldValue11 != NewValue11 + OR OldValue12 != NewValue12 + ) + END + +END +GO + + +--------------------------------------------- + +-- fp.procStatsCopyNewItems +CREATE PROCEDURE [fp].[procStatsCopyNewItems] + @SourceBudgetConfigID INT, + @SourceEntityGroupConfigID INT, + @BudgetConfigID INT, + @EntityGroupConfigID INT +AS +BEGIN +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-06-28 NT JAZZ-21664 Add missing provider dimensions + *************************************************************/ +INSERT INTO [fp].[FactStatistics] (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, PayorID, PatientClassID, AddDate, +ProviderLineItemID, ProviderID, ProviderSpecialtyID, ProviderTypeID, SubsectionID, +SampledBudget01, SampledBudget02, SampledBudget03, SampledBudget04, SampledBudget05, SampledBudget06, SampledBudget07, SampledBudget08, SampledBudget09, SampledBudget10, SampledBudget11, SampledBudget12, +SampledProjection01, SampledProjection02, SampledProjection03, SampledProjection04, SampledProjection05, SampledProjection06, SampledProjection07, SampledProjection08, SampledProjection09, SampledProjection10, SampledProjection11, SampledProjection12, +InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, +InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12, +IsNew) +SELECT @BudgetConfigID, @EntityGroupConfigID, EntityID, DepartmentID, AccountID, FinancialReportingID, UnitTypeID, PayorID, PatientClassID, AddDate, +ProviderLineItemID, ProviderID, ProviderSpecialtyID, ProviderTypeID, SubsectionID, +SampledBudget01, SampledBudget02, SampledBudget03, SampledBudget04, SampledBudget05, SampledBudget06, SampledBudget07, SampledBudget08, SampledBudget09, SampledBudget10, SampledBudget11, SampledBudget12, +SampledProjection01, SampledProjection02, SampledProjection03, SampledProjection04, SampledProjection05, SampledProjection06, SampledProjection07, SampledProjection08, SampledProjection09, SampledProjection10, SampledProjection11, SampledProjection12, +InitialBudget01, InitialBudget02, InitialBudget03, InitialBudget04, InitialBudget05, InitialBudget06, InitialBudget07, InitialBudget08, InitialBudget09, InitialBudget10, InitialBudget11, InitialBudget12, +InitialProjection01, InitialProjection02, InitialProjection03, InitialProjection04, InitialProjection05, InitialProjection06, InitialProjection07, InitialProjection08, InitialProjection09, InitialProjection10, InitialProjection11, InitialProjection12, +IsNew +FROM [fp].[FactStatistics] +WHERE BudgetConfigID = @SourceBudgetConfigID AND EntityGroupConfigID = @SourceEntityGroupConfigID AND IsNew = 1 + +END +GO + + +--------------------------------------------- + +-- fp.procTogglePreviewMode +create proc fp.procTogglePreviewMode + @isEnabled bit, + @isDebug bit = 0 +as + update fp.SystemSetting set Value = @isEnabled where Name = 'AP Preview Enabled' + + --set hangfire overrides to direct AP tasks to the lower priority preview queue + if (@isDebug = 1 or exists(select 1 from dbo.DBSetting where Name = 'SMC_PRIMARY_DATABASE' and Setting = 'smc prod')) begin + DELETE FROM dbo.HangfireJobQueueOverride where QueueName = 'advanced_planning_preview'; + + if (@isEnabled = 1) begin + ;with apTasks as ( + select 'Strata.CS.Jazz.ABB.Adjustments.TrackableImportTaskBase' as TypeName union all + select 'Strata.CS.Jazz.ABB.TestingTools.Tasks.RandomAdjustmentEngineTask' as TypeName union all + select 'Strata.CS.Jazz.ABB.Tasks.ABBFlexingReconciliationSamplingTask' as TypeName union all + select 'Strata.CS.Jazz.ABB.Tasks.APEngineTask' as TypeName union all + select 'Strata.CS.Jazz.ABB.Tasks.APReportCacheTask' as TypeName union all + select 'Strata.CS.Jazz.ABB.Tasks.APSamplingTask' as TypeName union all + select 'Strata.CS.Jazz.ABB.Tasks.APStartBudgetingTask' as TypeName union all + select 'Strata.CS.Jazz.ABB.Tasks.ArchiveBudgetTask' as TypeName + ) + INSERT dbo.HangfireJobQueueOverride (TypeName, MethodName, QueueName) + SELECT TypeName, 'InvokeWithContext' as MethodName, 'advanced_planning_preview' as QueueName + FROM apTasks; + end + end +GO + + +--------------------------------------------- + +-- fp.procTransferRosterToStaffing +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-07-30 IP B-20351 Staffing to GL - Performance Improvements and roster targeted thing +** 2 2018-08-10 MY B-20495 Fixes for flexed value not getting reset and locking unrelated PCGs +** 3 2018-08-14 MY B-20495 Fixed an issue with the filter filtering out when PCG is at a rollup level +** 4 2018-09-25 GF E-02313 Simplify source dimensionality to only department +** 5 2018-09-25 BK D-07796 Fix joins to use filtered table so that InitialBudget not cleared +** 6 2019-01-11 MY B-19995 Updated Projection Logic to only flow to months not loaded +** 7 2019-01-28 MY D-08049 Fixed Actual YTD calculation to only apply once +** 8 2019-05-07 BK D-08084 Fixed problem with duplicate new employees when more than one pcg is in RosterBudgetBasisResult +** 9 2022-09-02 MY JAZZ-18719 Improved Targeting Performance +** 10 2023-11-30 BK JAZZ-63467 Update for new data structure +*************************************************************/ +CREATE proc [fp].[procTransferRosterToStaffing] + @BudgetConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS + exec dbo.procSysDropTempTable '#tmpPaddedStaffingData' + exec dbo.procSysDropTempTable '#tmpRosterRolledUp' + exec dbo.procSysDropTempTable '#staffingGrouped' + exec dbo.procSysDropTempTable '#tmpRosterTotalsForExistingEmployees' + exec dbo.procSysDropTempTable '#tmpExistingEmployees' + exec dbo.procSysDropTempTable '#tmpNewRosterEmployees' + exec dbo.procSysDropTempTable '#tmpHoursRatio' + exec dbo.procSysDropTempTable '#tmpEntity' + exec dbo.procSysDropTempTable '#Filter' + + SELECT DISTINCT DepartmentID + INTO #Filter + FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF EXISTS(SELECT 1 FROM #Filter WHERE DepartmentID IS NULL) + BEGIN + INSERT INTO #Filter (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fw.DimDepartment -- We want to use dim department here instead of fp.Staffing because new departments added to roster need to flow over + END + + -- Set variables + DECLARE @BudgetConfigGUID UNIQUEIDENTIFIER + DECLARE @IsFTEHidden TINYINT + DECLARE @MonthsLoaded INT + DECLARE @BudgetYear SMALLINT + SELECT @BudgetConfigGUID = BudgetConfigGUID, @IsFTEHidden = IsFTEHidden, @BudgetYear = FiscalYearID, @MonthsLoaded = MonthsLoaded FROM [fp].[BudgetConfig] WHERE BudgetConfigID = @BudgetConfigID + + -- Used for projection, we only ever want to update the months NOT loaded. + DECLARE @MonthsNotLoaded INT = 12 - @MonthsLoaded; + DECLARE @ProjectedYear INT = @BudgetYear - 1 + + -- Gets the working hours to calculate FTEs + SELECT WorkWeekID, mnth.FiscalYearID, SUM(VALUE) as TotalHours + INTO #tmpHoursRatio + FROM [client].[viewFactWorkingHoursPerMonthUnpivoted] mnth WITH (READUNCOMMITTED) + WHERE FiscalYearID = @BudgetYear + GROUP BY WorkWeekID, mnth.FiscalYearID; + + INSERT INTO #tmpHoursRatio + SELECT WorkWeekID, mnth.FiscalYearID, SUM(RemainingAnnualHours) as TotalHours + FROM [fp].[viewWorkingHoursPerMonthWithBreakdown] mnth WITH (READUNCOMMITTED) + INNER JOIN [fw].[DimFiscalMonth] fm WITH (READUNCOMMITTED) ON fm.FiscalMonthID = mnth.FiscalMonthID AND @MonthsLoaded + 1 = fm.SortOrder + WHERE FiscalYearID = @ProjectedYear + GROUP BY WorkWeekID, mnth.FiscalYearID; + + -- Get all of the entities + SELECT EntityID + INTO #tmpEntity + FROM [fp].[EntityGroupConfig] ec + INNER JOIN [fp].[BudgetConfig] bc WITH (READUNCOMMITTED) ON ec.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN [fp].[EntityGroupConfigMapping] egcm WITH (READUNCOMMITTED) ON ec.EntityGroupConfigGUID = egcm.EntityGroupConfigGUID + WHERE BudgetConfigID = @BudgetConfigID AND ec.IsRosterUsed = 1; + + -- Get the total YTD actual dollars regardless of variability, we'll use these to caclulate the projection dollars (Roster Projection Dollars - Staffing YTD Actual Dollars) + SELECT + ph.BudgetConfigID, + ph.EntityID, + ph.DepartmentID, + ph.JobCodeID, + ph.PayCodeGroupID, + SUM(hist.ActualYTDDollarsTotal) AS ActualYTDValueTotal + INTO #staffingGrouped + FROM [fp].[Staffing] ph WITH (READUNCOMMITTED) + INNER JOIN [fp].[StaffingHistory] hist WITH (READUNCOMMITTED) ON ph.StaffingID = hist.StaffingID + INNER JOIN [fw].[DimDepartment] dept WITH (READUNCOMMITTED) ON ph.DepartmentID = dept.DepartmentID + INNER JOIN #tmpEntity ent WITH (READUNCOMMITTED) on dept.EntityID = ent.EntityID + INNER JOIN #Filter Filter ON ph.DepartmentID = Filter.DepartmentID + WHERE ph.BudgetConfigID = @BudgetConfigID + GROUP BY + ph.BudgetConfigID, + ph.EntityID, + ph.DepartmentID, + ph.JobCodeID, + ph.PayCodeGroupID + + -- Get the total in the UI, then for projection for non-new employees + -- Projection Dollars = (Roster Projection Dollars - Staffing YTD Actual Dollars) + -- We do this so we can take out the Actual YTD in the next step + SELECT + @BudgetConfigID AS BudgetConfigID + , dept.EntityID + , rb.DepartmentID + , rb.JobCodeID + , rb.PayCodeGroupID + , SUM(rb.Dollars) AS Dollars + , SUM(rb.InitialDollars) AS InitialDollars + , SUM(rb.ProjectedDollars) AS ProjectedDollars + , SUM(rb.FTEs) AS FTEs + , SUM(rb.InitialFTEs) AS InitialFTEs + , SUM(rb.ProjectedFTEs) AS ProjectedFTEs + INTO + #tmpRosterTotalsForExistingEmployees + FROM [fp].[RosterBudgetBasisResult] rb + INNER JOIN [fw].[DimDepartment] dept WITH (READUNCOMMITTED) ON rb.DepartmentID = dept.DepartmentID + INNER JOIN #tmpEntity ent on dept.EntityID = ent.EntityID + INNER JOIN #Filter Filter ON dept.DepartmentID = Filter.DepartmentID + LEFT JOIN [fp].[RosterBudgetNewEmployee] emp ON rb.EmployeeID = emp.EmployeeID AND rb.BudgetConfigGUID = emp.BudgetConfigGUID + LEFT JOIN #staffingGrouped staffing + ON dept.EntityID = staffing.EntityID + AND rb.DepartmentID = staffing.DepartmentID + AND rb.JobCodeID = staffing.JobCodeID + AND rb.PayCodeGroupID = staffing.PayCodeGroupID + WHERE 1=1 + AND rb.BudgetConfigGUID = @BudgetConfigGUID + AND emp.EmployeeID IS NULL + GROUP BY + rb.DepartmentID + , rb.JobCodeID + , rb.PayCodeGroupID + , dept.EntityID; + + -- Need to do this seperate for when there are multiple employees, we only want to do this math once. + UPDATE existing + SET + existing.ProjectedDollars = existing.ProjectedDollars - grp.ActualYTDValueTotal + FROM #tmpRosterTotalsForExistingEmployees existing + INNER JOIN #staffingGrouped grp ON + existing.BudgetConfigID = grp.BudgetConfigID + AND existing.EntityID = grp.EntityID + AND existing.DepartmentID = grp.DepartmentID + AND existing.JobCodeID = grp.JobCodeID + AND existing.PayCodeGroupID = grp.PayCodeGroupID + + -- Calculate the values for all existing employees, + SELECT + roster.BudgetConfigID + , roster.EntityID + , roster.DepartmentID + , roster.JobCodeID + , roster.PayCodeGroupID + , SUM(roster.Dollars * (wh.Month01/ NULLIF(hr.TotalHours, 0))) as DollarsMonth01 + , SUM(roster.Dollars * (wh.Month02/ NULLIF(hr.TotalHours, 0))) as DollarsMonth02 + , SUM(roster.Dollars * (wh.Month03/ NULLIF(hr.TotalHours, 0))) as DollarsMonth03 + , SUM(roster.Dollars * (wh.Month04/ NULLIF(hr.TotalHours, 0))) as DollarsMonth04 + , SUM(roster.Dollars * (wh.Month05/ NULLIF(hr.TotalHours, 0))) as DollarsMonth05 + , SUM(roster.Dollars * (wh.Month06/ NULLIF(hr.TotalHours, 0))) as DollarsMonth06 + , SUM(roster.Dollars * (wh.Month07/ NULLIF(hr.TotalHours, 0))) as DollarsMonth07 + , SUM(roster.Dollars * (wh.Month08/ NULLIF(hr.TotalHours, 0))) as DollarsMonth08 + , SUM(roster.Dollars * (wh.Month09/ NULLIF(hr.TotalHours, 0))) as DollarsMonth09 + , SUM(roster.Dollars * (wh.Month10/ NULLIF(hr.TotalHours, 0))) as DollarsMonth10 + , SUM(roster.Dollars * (wh.Month11/ NULLIF(hr.TotalHours, 0))) as DollarsMonth11 + , SUM(roster.Dollars * (wh.Month12/ NULLIF(hr.TotalHours, 0))) as DollarsMonth12 + + , SUM(roster.FTEs) as FTEsMonth01 + , SUM(roster.FTEs) as FTEsMonth02 + , SUM(roster.FTEs) as FTEsMonth03 + , SUM(roster.FTEs) as FTEsMonth04 + , SUM(roster.FTEs) as FTEsMonth05 + , SUM(roster.FTEs) as FTEsMonth06 + , SUM(roster.FTEs) as FTEsMonth07 + , SUM(roster.FTEs) as FTEsMonth08 + , SUM(roster.FTEs) as FTEsMonth09 + , SUM(roster.FTEs) as FTEsMonth10 + , SUM(roster.FTEs) as FTEsMonth11 + , SUM(roster.FTEs) as FTEsMonth12 + + , SUM(roster.InitialDollars * (wh.Month01/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth01 + , SUM(roster.InitialDollars * (wh.Month02/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth02 + , SUM(roster.InitialDollars * (wh.Month03/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth03 + , SUM(roster.InitialDollars * (wh.Month04/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth04 + , SUM(roster.InitialDollars * (wh.Month05/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth05 + , SUM(roster.InitialDollars * (wh.Month06/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth06 + , SUM(roster.InitialDollars * (wh.Month07/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth07 + , SUM(roster.InitialDollars * (wh.Month08/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth08 + , SUM(roster.InitialDollars * (wh.Month09/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth09 + , SUM(roster.InitialDollars * (wh.Month10/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth10 + , SUM(roster.InitialDollars * (wh.Month11/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth11 + , SUM(roster.InitialDollars * (wh.Month12/NULLIF(hr.TotalHours, 0))) as InitialDollarsMonth12 + + , SUM(roster.InitialFTEs) as InitialFTEsMonth01 + , SUM(roster.InitialFTEs) as InitialFTEsMonth02 + , SUM(roster.InitialFTEs) as InitialFTEsMonth03 + , SUM(roster.InitialFTEs) as InitialFTEsMonth04 + , SUM(roster.InitialFTEs) as InitialFTEsMonth05 + , SUM(roster.InitialFTEs) as InitialFTEsMonth06 + , SUM(roster.InitialFTEs) as InitialFTEsMonth07 + , SUM(roster.InitialFTEs) as InitialFTEsMonth08 + , SUM(roster.InitialFTEs) as InitialFTEsMonth09 + , SUM(roster.InitialFTEs) as InitialFTEsMonth10 + , SUM(roster.InitialFTEs) as InitialFTEsMonth11 + , SUM(roster.InitialFTEs) as InitialFTEsMonth12 + + , SUM(CASE WHEN @MonthsLoaded <= 1 THEN roster.ProjectedDollars * (whProj.Month01/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth01 + , SUM(CASE WHEN @MonthsLoaded <= 2 THEN roster.ProjectedDollars * (whProj.Month02/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth02 + , SUM(CASE WHEN @MonthsLoaded <= 3 THEN roster.ProjectedDollars * (whProj.Month03/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth03 + , SUM(CASE WHEN @MonthsLoaded <= 4 THEN roster.ProjectedDollars * (whProj.Month04/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth04 + , SUM(CASE WHEN @MonthsLoaded <= 5 THEN roster.ProjectedDollars * (whProj.Month05/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth05 + , SUM(CASE WHEN @MonthsLoaded <= 6 THEN roster.ProjectedDollars * (whProj.Month06/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth06 + , SUM(CASE WHEN @MonthsLoaded <= 7 THEN roster.ProjectedDollars * (whProj.Month07/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth07 + , SUM(CASE WHEN @MonthsLoaded <= 8 THEN roster.ProjectedDollars * (whProj.Month08/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth08 + , SUM(CASE WHEN @MonthsLoaded <= 9 THEN roster.ProjectedDollars * (whProj.Month09/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth09 + , SUM(CASE WHEN @MonthsLoaded <= 10 THEN roster.ProjectedDollars * (whProj.Month10/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth10 + , SUM(CASE WHEN @MonthsLoaded <= 11 THEN roster.ProjectedDollars * (whProj.Month11/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth11 + , SUM(CASE WHEN @MonthsLoaded <= 12 THEN roster.ProjectedDollars * (whProj.Month12/NULLIF(hrProj.TotalHours, 0)) ELSE 0 END) as ProjectedDollarsMonth12 + + , SUM(CASE WHEN @MonthsLoaded <= 1 THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth01 + , SUM(CASE WHEN @MonthsLoaded <= 2 THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth02 + , SUM(CASE WHEN @MonthsLoaded <= 3 THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth03 + , SUM(CASE WHEN @MonthsLoaded <= 4 THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth04 + , SUM(CASE WHEN @MonthsLoaded <= 5 THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth05 + , SUM(CASE WHEN @MonthsLoaded <= 6 THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth06 + , SUM(CASE WHEN @MonthsLoaded <= 7 THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth07 + , SUM(CASE WHEN @MonthsLoaded <= 8 THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth08 + , SUM(CASE WHEN @MonthsLoaded <= 9 THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth09 + , SUM(CASE WHEN @MonthsLoaded <= 10 THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth10 + , SUM(CASE WHEN @MonthsLoaded <= 11 THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth11 + , SUM(CASE WHEN @MonthsLoaded <= 12 THEN roster.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth12 + INTO #tmpExistingEmployees + FROM + #tmpRosterTotalsForExistingEmployees roster + INNER JOIN [fw].[DimDepartment] dept WITH (READUNCOMMITTED) ON dept.DepartmentID = roster.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh WITH (READUNCOMMITTED) ON wh.FiscalYearID = @BudgetYear AND wh.WorkWeekID = dept.WorkWeekID + INNER JOIN [client].[FactWorkingHoursPerMonth] whProj WITH (READUNCOMMITTED) ON whProj.FiscalYearID = @ProjectedYear AND whProj.WorkWeekID = dept.WorkWeekID + INNER JOIN #tmpEntity ent on dept.EntityID = ent.EntityID + INNER JOIN #tmpHoursRatio hr ON wh.FiscalYearID = hr.FiscalYearID AND hr.WorkWeekID = dept.WorkWeekID + INNER JOIN #tmpHoursRatio hrProj ON whProj.FiscalYearID = hrProj.FiscalYearID AND hrProj.WorkWeekID = dept.WorkWeekID + INNER JOIN #Filter Filter ON dept.DepartmentID = Filter.DepartmentID + GROUP BY + roster.BudgetConfigID + , roster.DepartmentID + , roster.JobCodeID + , roster.PayCodeGroupID + , hr.TotalHours + , hrProj.TotalHours + , roster.EntityID; + + -- rollup roster data (aggregate over employeeID) + -- We do new employees seperate because of it's unique logic and so that we can accurately take the Projection - Actual YTD accurately + ;WITH NewEmployees as ( + SELECT e.EmployeeID, f.SortOrder as StartMonthSortOrder, e.FiscalYearID, 13 - f.SortOrder AS WorkingMonths, result.DepartmentID, budg.RemainingAnnualHours AS BudgetRemainingAnnualHours, proj.RemainingAnnualHours AS ProjectionRemainingAnnualHours + FROM [fp].[RosterBudgetNewEmployee] e + INNER JOIN [fw].[DimFiscalMonth] f WITH (READUNCOMMITTED) ON e.FiscalMonthID = f.FiscalMonthID + INNER JOIN (SELECT DISTINCT BudgetConfigGUID, DepartmentID, EmployeeID FROM [fp].[RosterBudgetBasisResult]) result ON e.EmployeeID = result.EmployeeID + AND result.BudgetConfigGUID = e.BudgetConfigGUID + INNER JOIN [fw].[DimDepartment] dept WITH (READUNCOMMITTED) ON result.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[BudgetConfig] bc WITH (READUNCOMMITTED) ON e.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN [fp].[viewWorkingHoursPerMonthWithBreakdown] budg WITH (READUNCOMMITTED) + ON bc.FiscalYearID = budg.FiscalYearID + AND e.FiscalMonthID = budg.FiscalMonthID + AND dept.WorkWeekID = budg.WorkWeekID + INNER JOIN [fp].[viewWorkingHoursPerMonthWithBreakdown] proj WITH (READUNCOMMITTED) + ON bc.FiscalYearID - 1 = proj.FiscalYearID + AND e.FiscalMonthID = proj.FiscalMonthID + AND dept.WorkWeekID = proj.WorkWeekID + ) + SELECT + @BudgetConfigID AS BudgetConfigID + , dept.EntityID + , rb.DepartmentID + , rb.JobCodeID + , rb.PayCodeGroupID + -- To understand the new employee case, for new employees, if they started in 2018, but the budget was for 2019, spread it for the entire year. + -- If they however started in 2019 for the 2019 budget, only spread to the months after they started. It is also important, that for new employees we only spread over the remaining hours and not the total yearly hours. + + -- If you enter a year not in the scope of the budget, do not transfer this employee (maybe something we should block on the UI?) + + -- For projection, we only want to spread the dollars to the months NOT loaded, if that employee is new, make sure they started in the projected year + -- If they didn't, don't transfer these dollars. Currently you can still enter a value for these types of employees, but we will need to block that. + , SUM(CASE WHEN (1 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month01/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth01 + , SUM(CASE WHEN (2 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month02/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth02 + , SUM(CASE WHEN (3 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month03/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth03 + , SUM(CASE WHEN (4 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month04/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth04 + , SUM(CASE WHEN (5 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month05/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth05 + , SUM(CASE WHEN (6 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month06/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth06 + , SUM(CASE WHEN (7 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month07/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth07 + , SUM(CASE WHEN (8 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month08/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth08 + , SUM(CASE WHEN (9 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month09/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth09 + , SUM(CASE WHEN (10 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month10/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth10 + , SUM(CASE WHEN (11 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month11/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth11 + , SUM(CASE WHEN (12 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.Dollars * (wh.Month12/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as DollarsMonth12 + + , SUM(CASE WHEN (1 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth01 + , SUM(CASE WHEN (2 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth02 + , SUM(CASE WHEN (3 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth03 + , SUM(CASE WHEN (4 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth04 + , SUM(CASE WHEN (5 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth05 + , SUM(CASE WHEN (6 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth06 + , SUM(CASE WHEN (7 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth07 + , SUM(CASE WHEN (8 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth08 + , SUM(CASE WHEN (9 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth09 + , SUM(CASE WHEN (10 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth10 + , SUM(CASE WHEN (11 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth11 + , SUM(CASE WHEN (12 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.FTEs ELSE 0 END) as FTEsMonth12 + + , SUM(CASE WHEN (1 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month01/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth01 + , SUM(CASE WHEN (2 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month02/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth02 + , SUM(CASE WHEN (3 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month03/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth03 + , SUM(CASE WHEN (4 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month04/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth04 + , SUM(CASE WHEN (5 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month05/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth05 + , SUM(CASE WHEN (6 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month06/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth06 + , SUM(CASE WHEN (7 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month07/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth07 + , SUM(CASE WHEN (8 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month08/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth08 + , SUM(CASE WHEN (9 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month09/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth09 + , SUM(CASE WHEN (10 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month10/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth10 + , SUM(CASE WHEN (11 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month11/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth11 + , SUM(CASE WHEN (12 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialDollars * (wh.Month12/ CASE WHEN emp.FiscalYearID = @ProjectedYear THEN NULLIF(hr.TotalHours, 0) ELSE emp.BudgetRemainingAnnualHours END) ELSE 0 END) as InitialDollarsMonth12 + + , SUM(CASE WHEN (1 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth01 + , SUM(CASE WHEN (2 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth02 + , SUM(CASE WHEN (3 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth03 + , SUM(CASE WHEN (4 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth04 + , SUM(CASE WHEN (5 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth05 + , SUM(CASE WHEN (6 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth06 + , SUM(CASE WHEN (7 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth07 + , SUM(CASE WHEN (8 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth08 + , SUM(CASE WHEN (9 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth09 + , SUM(CASE WHEN (10 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth10 + , SUM(CASE WHEN (11 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth11 + , SUM(CASE WHEN (12 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @BudgetYear) OR emp.StartMonthSortOrder = 0 OR emp.FiscalYearID = @ProjectedYear THEN rb.InitialFTEs ELSE 0 END) as InitialFTEsMonth12 + + , SUM(CASE WHEN ((1 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 1 THEN rb.ProjectedDollars * (whProj.Month01/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth01 + , SUM(CASE WHEN ((2 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 2 THEN rb.ProjectedDollars * (whProj.Month02/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth02 + , SUM(CASE WHEN ((3 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 3 THEN rb.ProjectedDollars * (whProj.Month03/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth03 + , SUM(CASE WHEN ((4 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 4 THEN rb.ProjectedDollars * (whProj.Month04/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth04 + , SUM(CASE WHEN ((5 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 5 THEN rb.ProjectedDollars * (whProj.Month05/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth05 + , SUM(CASE WHEN ((6 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 6 THEN rb.ProjectedDollars * (whProj.Month06/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth06 + , SUM(CASE WHEN ((7 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 7 THEN rb.ProjectedDollars * (whProj.Month07/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth07 + , SUM(CASE WHEN ((8 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 8 THEN rb.ProjectedDollars * (whProj.Month08/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth08 + , SUM(CASE WHEN ((9 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 9 THEN rb.ProjectedDollars * (whProj.Month09/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth09 + , SUM(CASE WHEN ((10 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 10 THEN rb.ProjectedDollars * (whProj.Month10/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth10 + , SUM(CASE WHEN ((11 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 11 THEN rb.ProjectedDollars * (whProj.Month11/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth11 + , SUM(CASE WHEN ((12 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 12 THEN rb.ProjectedDollars * (whProj.Month12/emp.ProjectionRemainingAnnualHours) ELSE 0 END) as ProjectedDollarsMonth12 + + , SUM(CASE WHEN ((1 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 1 THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth01 + , SUM(CASE WHEN ((2 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 2 THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth02 + , SUM(CASE WHEN ((3 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 3 THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth03 + , SUM(CASE WHEN ((4 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 4 THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth04 + , SUM(CASE WHEN ((5 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 5 THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth05 + , SUM(CASE WHEN ((6 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 6 THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth06 + , SUM(CASE WHEN ((7 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 7 THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth07 + , SUM(CASE WHEN ((8 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 8 THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth08 + , SUM(CASE WHEN ((9 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 9 THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth09 + , SUM(CASE WHEN ((10 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 10 THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth10 + , SUM(CASE WHEN ((11 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 11 THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth11 + , SUM(CASE WHEN ((12 >= emp.StartMonthSortOrder AND emp.FiscalYearID = @ProjectedYear) OR emp.StartMonthSortOrder = 0) AND @MonthsLoaded <= 12 THEN rb.ProjectedFTEs ELSE 0 END) as ProjectedFTEsMonth12 + INTO + #tmpNewRosterEmployees + FROM [fp].[RosterBudgetBasisResult] rb + INNER JOIN NewEmployees emp ON rb.EmployeeID = emp.EmployeeID AND rb.DepartmentID = emp.DepartmentID + INNER JOIN [fw].[DimDepartment] dept WITH (READUNCOMMITTED) ON rb.DepartmentID = dept.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh WITH (READUNCOMMITTED) ON wh.FiscalYearID = @BudgetYear AND wh.WorkWeekID = dept.WorkWeekID + INNER JOIN [client].[FactWorkingHoursPerMonth] whProj WITH (READUNCOMMITTED) ON whProj.FiscalYearID = @ProjectedYear AND whProj.WorkWeekID = dept.WorkWeekID + INNER JOIN #tmpEntity ent on dept.EntityID = ent.EntityID + INNER JOIN #tmpHoursRatio hr ON wh.FiscalYearID = hr.FiscalYearID AND hr.WorkWeekID = dept.WorkWeekID + INNER JOIN #tmpHoursRatio hrProj ON whProj.FiscalYearID = hrProj.FiscalYearID AND hrProj.WorkWeekID = dept.WorkWeekID + INNER JOIN #Filter Filter ON dept.DepartmentID = Filter.DepartmentID + WHERE rb.BudgetConfigGUID = @BudgetConfigGUID + GROUP BY + rb.DepartmentID + , rb.JobCodeID + , rb.PayCodeGroupID + , hr.TotalHours + , hrProj.TotalHours + , dept.EntityID; + + -- Combine the existing and new employees + SELECT + COALESCE(existing.BudgetConfigID, new.BudgetConfigID) AS BudgetConfigID, + COALESCE(existing.EntityID, new.EntityID) AS EntityID, + COALESCE(existing.DepartmentID, new.DepartmentID) AS DepartmentID, + COALESCE(existing.JobCodeID, new.JobCodeID) AS JobCodeID, + COALESCE(existing.PayCodeGroupID, new.PayCodeGroupID) AS PayCodeGroupID, + SUM(ISNULL(existing.DollarsMonth01, 0)) + SUM(ISNULL(new.DollarsMonth01, 0)) AS DollarsMonth01, + SUM(ISNULL(existing.DollarsMonth02, 0)) + SUM(ISNULL(new.DollarsMonth02, 0)) AS DollarsMonth02, + SUM(ISNULL(existing.DollarsMonth03, 0)) + SUM(ISNULL(new.DollarsMonth03, 0)) AS DollarsMonth03, + SUM(ISNULL(existing.DollarsMonth04, 0)) + SUM(ISNULL(new.DollarsMonth04, 0)) AS DollarsMonth04, + SUM(ISNULL(existing.DollarsMonth05, 0)) + SUM(ISNULL(new.DollarsMonth05, 0)) AS DollarsMonth05, + SUM(ISNULL(existing.DollarsMonth06, 0)) + SUM(ISNULL(new.DollarsMonth06, 0)) AS DollarsMonth06, + SUM(ISNULL(existing.DollarsMonth07, 0)) + SUM(ISNULL(new.DollarsMonth07, 0)) AS DollarsMonth07, + SUM(ISNULL(existing.DollarsMonth08, 0)) + SUM(ISNULL(new.DollarsMonth08, 0)) AS DollarsMonth08, + SUM(ISNULL(existing.DollarsMonth09, 0)) + SUM(ISNULL(new.DollarsMonth09, 0)) AS DollarsMonth09, + SUM(ISNULL(existing.DollarsMonth10, 0)) + SUM(ISNULL(new.DollarsMonth10, 0)) AS DollarsMonth10, + SUM(ISNULL(existing.DollarsMonth11, 0)) + SUM(ISNULL(new.DollarsMonth11, 0)) AS DollarsMonth11, + SUM(ISNULL(existing.DollarsMonth12, 0)) + SUM(ISNULL(new.DollarsMonth12, 0)) AS DollarsMonth12, + + SUM(ISNULL(existing.FTEsMonth01, 0)) + SUM(ISNULL(new.FTEsMonth01, 0)) AS FTEsMonth01, + SUM(ISNULL(existing.FTEsMonth02, 0)) + SUM(ISNULL(new.FTEsMonth02, 0)) AS FTEsMonth02, + SUM(ISNULL(existing.FTEsMonth03, 0)) + SUM(ISNULL(new.FTEsMonth03, 0)) AS FTEsMonth03, + SUM(ISNULL(existing.FTEsMonth04, 0)) + SUM(ISNULL(new.FTEsMonth04, 0)) AS FTEsMonth04, + SUM(ISNULL(existing.FTEsMonth05, 0)) + SUM(ISNULL(new.FTEsMonth05, 0)) AS FTEsMonth05, + SUM(ISNULL(existing.FTEsMonth06, 0)) + SUM(ISNULL(new.FTEsMonth06, 0)) AS FTEsMonth06, + SUM(ISNULL(existing.FTEsMonth07, 0)) + SUM(ISNULL(new.FTEsMonth07, 0)) AS FTEsMonth07, + SUM(ISNULL(existing.FTEsMonth08, 0)) + SUM(ISNULL(new.FTEsMonth08, 0)) AS FTEsMonth08, + SUM(ISNULL(existing.FTEsMonth09, 0)) + SUM(ISNULL(new.FTEsMonth09, 0)) AS FTEsMonth09, + SUM(ISNULL(existing.FTEsMonth10, 0)) + SUM(ISNULL(new.FTEsMonth10, 0)) AS FTEsMonth10, + SUM(ISNULL(existing.FTEsMonth11, 0)) + SUM(ISNULL(new.FTEsMonth11, 0)) AS FTEsMonth11, + SUM(ISNULL(existing.FTEsMonth12, 0)) + SUM(ISNULL(new.FTEsMonth12, 0)) AS FTEsMonth12, + + SUM(ISNULL(existing.InitialDollarsMonth01, 0)) + SUM(ISNULL(new.InitialDollarsMonth01, 0)) AS InitialDollarsMonth01, + SUM(ISNULL(existing.InitialDollarsMonth02, 0)) + SUM(ISNULL(new.InitialDollarsMonth02, 0)) AS InitialDollarsMonth02, + SUM(ISNULL(existing.InitialDollarsMonth03, 0)) + SUM(ISNULL(new.InitialDollarsMonth03, 0)) AS InitialDollarsMonth03, + SUM(ISNULL(existing.InitialDollarsMonth04, 0)) + SUM(ISNULL(new.InitialDollarsMonth04, 0)) AS InitialDollarsMonth04, + SUM(ISNULL(existing.InitialDollarsMonth05, 0)) + SUM(ISNULL(new.InitialDollarsMonth05, 0)) AS InitialDollarsMonth05, + SUM(ISNULL(existing.InitialDollarsMonth06, 0)) + SUM(ISNULL(new.InitialDollarsMonth06, 0)) AS InitialDollarsMonth06, + SUM(ISNULL(existing.InitialDollarsMonth07, 0)) + SUM(ISNULL(new.InitialDollarsMonth07, 0)) AS InitialDollarsMonth07, + SUM(ISNULL(existing.InitialDollarsMonth08, 0)) + SUM(ISNULL(new.InitialDollarsMonth08, 0)) AS InitialDollarsMonth08, + SUM(ISNULL(existing.InitialDollarsMonth09, 0)) + SUM(ISNULL(new.InitialDollarsMonth09, 0)) AS InitialDollarsMonth09, + SUM(ISNULL(existing.InitialDollarsMonth10, 0)) + SUM(ISNULL(new.InitialDollarsMonth10, 0)) AS InitialDollarsMonth10, + SUM(ISNULL(existing.InitialDollarsMonth11, 0)) + SUM(ISNULL(new.InitialDollarsMonth11, 0)) AS InitialDollarsMonth11, + SUM(ISNULL(existing.InitialDollarsMonth12, 0)) + SUM(ISNULL(new.InitialDollarsMonth12, 0)) AS InitialDollarsMonth12, + + SUM(ISNULL(existing.InitialFTEsMonth01, 0)) + SUM(ISNULL(new.InitialFTEsMonth01, 0)) AS InitialFTEsMonth01, + SUM(ISNULL(existing.InitialFTEsMonth02, 0)) + SUM(ISNULL(new.InitialFTEsMonth02, 0)) AS InitialFTEsMonth02, + SUM(ISNULL(existing.InitialFTEsMonth03, 0)) + SUM(ISNULL(new.InitialFTEsMonth03, 0)) AS InitialFTEsMonth03, + SUM(ISNULL(existing.InitialFTEsMonth04, 0)) + SUM(ISNULL(new.InitialFTEsMonth04, 0)) AS InitialFTEsMonth04, + SUM(ISNULL(existing.InitialFTEsMonth05, 0)) + SUM(ISNULL(new.InitialFTEsMonth05, 0)) AS InitialFTEsMonth05, + SUM(ISNULL(existing.InitialFTEsMonth06, 0)) + SUM(ISNULL(new.InitialFTEsMonth06, 0)) AS InitialFTEsMonth06, + SUM(ISNULL(existing.InitialFTEsMonth07, 0)) + SUM(ISNULL(new.InitialFTEsMonth07, 0)) AS InitialFTEsMonth07, + SUM(ISNULL(existing.InitialFTEsMonth08, 0)) + SUM(ISNULL(new.InitialFTEsMonth08, 0)) AS InitialFTEsMonth08, + SUM(ISNULL(existing.InitialFTEsMonth09, 0)) + SUM(ISNULL(new.InitialFTEsMonth09, 0)) AS InitialFTEsMonth09, + SUM(ISNULL(existing.InitialFTEsMonth10, 0)) + SUM(ISNULL(new.InitialFTEsMonth10, 0)) AS InitialFTEsMonth10, + SUM(ISNULL(existing.InitialFTEsMonth11, 0)) + SUM(ISNULL(new.InitialFTEsMonth11, 0)) AS InitialFTEsMonth11, + SUM(ISNULL(existing.InitialFTEsMonth12, 0)) + SUM(ISNULL(new.InitialFTEsMonth12, 0)) AS InitialFTEsMonth12, + + SUM(ISNULL(existing.ProjectedDollarsMonth01, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth01, 0)) AS ProjectedDollarsMonth01, + SUM(ISNULL(existing.ProjectedDollarsMonth02, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth02, 0)) AS ProjectedDollarsMonth02, + SUM(ISNULL(existing.ProjectedDollarsMonth03, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth03, 0)) AS ProjectedDollarsMonth03, + SUM(ISNULL(existing.ProjectedDollarsMonth04, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth04, 0)) AS ProjectedDollarsMonth04, + SUM(ISNULL(existing.ProjectedDollarsMonth05, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth05, 0)) AS ProjectedDollarsMonth05, + SUM(ISNULL(existing.ProjectedDollarsMonth06, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth06, 0)) AS ProjectedDollarsMonth06, + SUM(ISNULL(existing.ProjectedDollarsMonth07, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth07, 0)) AS ProjectedDollarsMonth07, + SUM(ISNULL(existing.ProjectedDollarsMonth08, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth08, 0)) AS ProjectedDollarsMonth08, + SUM(ISNULL(existing.ProjectedDollarsMonth09, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth09, 0)) AS ProjectedDollarsMonth09, + SUM(ISNULL(existing.ProjectedDollarsMonth10, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth10, 0)) AS ProjectedDollarsMonth10, + SUM(ISNULL(existing.ProjectedDollarsMonth11, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth11, 0)) AS ProjectedDollarsMonth11, + SUM(ISNULL(existing.ProjectedDollarsMonth12, 0)) + SUM(ISNULL(new.ProjectedDollarsMonth12, 0)) AS ProjectedDollarsMonth12, + + SUM(ISNULL(existing.ProjectedFTEsMonth01, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth01, 0)) AS ProjectedFTEsMonth01, + SUM(ISNULL(existing.ProjectedFTEsMonth02, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth02, 0)) AS ProjectedFTEsMonth02, + SUM(ISNULL(existing.ProjectedFTEsMonth03, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth03, 0)) AS ProjectedFTEsMonth03, + SUM(ISNULL(existing.ProjectedFTEsMonth04, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth04, 0)) AS ProjectedFTEsMonth04, + SUM(ISNULL(existing.ProjectedFTEsMonth05, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth05, 0)) AS ProjectedFTEsMonth05, + SUM(ISNULL(existing.ProjectedFTEsMonth06, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth06, 0)) AS ProjectedFTEsMonth06, + SUM(ISNULL(existing.ProjectedFTEsMonth07, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth07, 0)) AS ProjectedFTEsMonth07, + SUM(ISNULL(existing.ProjectedFTEsMonth08, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth08, 0)) AS ProjectedFTEsMonth08, + SUM(ISNULL(existing.ProjectedFTEsMonth09, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth09, 0)) AS ProjectedFTEsMonth09, + SUM(ISNULL(existing.ProjectedFTEsMonth10, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth10, 0)) AS ProjectedFTEsMonth10, + SUM(ISNULL(existing.ProjectedFTEsMonth11, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth11, 0)) AS ProjectedFTEsMonth11, + SUM(ISNULL(existing.ProjectedFTEsMonth12, 0)) + SUM(ISNULL(new.ProjectedFTEsMonth12, 0)) AS ProjectedFTEsMonth12 + INTO #tmpRosterRolledUp + FROM #tmpExistingEmployees existing + FULL OUTER JOIN #tmpNewRosterEmployees new ON existing.BudgetConfigID = new.BudgetConfigID + AND existing.EntityID = new.EntityID + AND existing.DepartmentID = new.DepartmentID + AND existing.JobCodeID = new.JobCodeID + AND existing.PayCodeGroupID = new.PayCodeGroupID + GROUP BY existing.BudgetConfigID, + existing.EntityID, + existing.DepartmentID, + existing.JobCodeID, + existing.PayCodeGroupID, + new.BudgetConfigID, + new.EntityID, + new.DepartmentID, + new.JobCodeID, + new.PayCodeGroupID + + ------------------ + -- Padding Data -- + ------------------ + + -- Create temp table for all dimensionality that might need to be padded. Only Pad dollars, hours, and FTEs + SELECT DISTINCT + @BudgetConfigID as BudgetConfigID, egc.EntityGroupConfigID, dept.EntityID, rb.DepartmentID, rb.JobCodeID, rb.PayCodeGroupID, pcg.ProductiveClassID, vrb.VariabilityID + INTO #tmpPaddedStaffingData + FROM #tmpRosterRolledUp rb + INNER JOIN [fw].[DimDepartment] dept ON rb.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigID = @BudgetConfigID + INNER JOIN [fp].[EntityGroupConfig] egc ON bc.BudgetConfigGUID = egc.BudgetConfigGUID + INNER JOIN [fp].[EntityGroupConfigMapping] map ON egc.EntityGroupConfigGUID = map.EntityGroupConfigGUID AND map.EntityID = dept.EntityID + INNER JOIN #tmpEntity ent on dept.EntityID = ent.EntityID + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pcg.PayCodeGroupID = rb.PayCodeGroupID + CROSS APPLY (VALUES (1),(2)) vrb(VariabilityID) + LEFT JOIN [fp].[Staffing] ph + ON rb.EntityID = ph.EntityID + AND rb.DepartmentID = ph.DepartmentID + AND rb.JobCodeID = ph.JobCodeID + AND rb.PayCodeGroupID = ph.PayCodeGroupID + AND ph.BudgetConfigID = rb.BudgetConfigID + AND ph.VariabilityID = vrb.VariabilityID + WHERE ph.StaffingID IS NULL + + -- Pad data + INSERT INTO [fp].[Staffing] (BudgetConfigID, EntityGroupConfigID, EntityID, DepartmentID, JobCodeID, PayCodeGroupID, ProductiveClassID, VariabilityID) + SELECT DISTINCT + b.BudgetConfigID, b.EntityGroupConfigID, b.EntityID, b.DepartmentID, b.JobCodeID, b.PayCodeGroupID, b.ProductiveClassID, b.VariabilityID + FROM #tmpPaddedStaffingData b + LEFT JOIN [fp].[Staffing] ph ON + b.JobCodeID = ph.JobCodeID + AND b.PayCodeGroupID = ph.PayCodeGroupID + and b.EntityID = ph.EntityID + and b.DepartmentID = ph.DepartmentID + and b.BudgetConfigID = ph.BudgetConfigID + and b.VariabilityID = ph.VariabilityID + WHERE ph.StaffingID IS NULL + + -- Pad the wage rate and history tables + EXEC [fp].[procPadStaffing] @BudgetConfigID, @SourceDimensionality + + ----------------- + -- Update FTEs -- + ----------------- + IF @IsFTEHidden = 1 BEGIN -- Typically a U of IA only setting + + -- When FTE's are hidden, we don't care about transferring the FTEs, only the dollars + UPDATE fs + SET InitialBudgetFTEs01 = 0, InitialBudgetFTEs02 = 0, InitialBudgetFTEs03 = 0, InitialBudgetFTEs04 = 0, InitialBudgetFTEs05 = 0, InitialBudgetFTEs06 = 0, + InitialBudgetFTEs07 = 0, InitialBudgetFTEs08 = 0, InitialBudgetFTEs09 = 0, InitialBudgetFTEs10 = 0, InitialBudgetFTEs11 = 0, InitialBudgetFTEs12 = 0, + InitialProjectionFTEs01 = CASE WHEN @MonthsLoaded >= 1 THEN InitialProjectionFTEs01 ELSE 0 END, + InitialProjectionFTEs02 = CASE WHEN @MonthsLoaded >= 2 THEN InitialProjectionFTEs02 ELSE 0 END, + InitialProjectionFTEs03 = CASE WHEN @MonthsLoaded >= 3 THEN InitialProjectionFTEs03 ELSE 0 END, + InitialProjectionFTEs04 = CASE WHEN @MonthsLoaded >= 4 THEN InitialProjectionFTEs04 ELSE 0 END, + InitialProjectionFTEs05 = CASE WHEN @MonthsLoaded >= 5 THEN InitialProjectionFTEs05 ELSE 0 END, + InitialProjectionFTEs06 = CASE WHEN @MonthsLoaded >= 6 THEN InitialProjectionFTEs06 ELSE 0 END, + InitialProjectionFTEs07 = CASE WHEN @MonthsLoaded >= 7 THEN InitialProjectionFTEs07 ELSE 0 END, + InitialProjectionFTEs08 = CASE WHEN @MonthsLoaded >= 8 THEN InitialProjectionFTEs08 ELSE 0 END, + InitialProjectionFTEs09 = CASE WHEN @MonthsLoaded >= 9 THEN InitialProjectionFTEs09 ELSE 0 END, + InitialProjectionFTEs10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjectionFTEs10 ELSE 0 END, + InitialProjectionFTEs11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjectionFTEs11 ELSE 0 END, + InitialProjectionFTEs12 = CASE WHEN @MonthsLoaded >= 12 THEN InitialProjectionFTEs12 ELSE 0 END, + TargetAdjustedFTEs01 = 0, TargetAdjustedFTEs02 = 0, TargetAdjustedFTEs03 = 0, TargetAdjustedFTEs04 = 0, TargetAdjustedFTEs05 = 0, TargetAdjustedFTEs06 = 0, + TargetAdjustedFTEs07 = 0, TargetAdjustedFTEs08 = 0, TargetAdjustedFTEs09 = 0, TargetAdjustedFTEs10 = 0, TargetAdjustedFTEs11 = 0, TargetAdjustedFTEs12 = 0, + BudgetAdjustedFTEs01 = 0, BudgetAdjustedFTEs02 = 0, BudgetAdjustedFTEs03 = 0, BudgetAdjustedFTEs04 = 0, BudgetAdjustedFTEs05 = 0, BudgetAdjustedFTEs06 = 0, + BudgetAdjustedFTEs07 = 0, BudgetAdjustedFTEs08 = 0, BudgetAdjustedFTEs09 = 0, BudgetAdjustedFTEs10 = 0, BudgetAdjustedFTEs11 = 0, BudgetAdjustedFTEs12 = 0, + ProjectionAdjustedFTEs01 = CASE WHEN @MonthsLoaded >= 1 THEN ProjectionAdjustedFTEs01 ELSE 0 END, + ProjectionAdjustedFTEs02 = CASE WHEN @MonthsLoaded >= 2 THEN ProjectionAdjustedFTEs02 ELSE 0 END, + ProjectionAdjustedFTEs03 = CASE WHEN @MonthsLoaded >= 3 THEN ProjectionAdjustedFTEs03 ELSE 0 END, + ProjectionAdjustedFTEs04 = CASE WHEN @MonthsLoaded >= 4 THEN ProjectionAdjustedFTEs04 ELSE 0 END, + ProjectionAdjustedFTEs05 = CASE WHEN @MonthsLoaded >= 5 THEN ProjectionAdjustedFTEs05 ELSE 0 END, + ProjectionAdjustedFTEs06 = CASE WHEN @MonthsLoaded >= 6 THEN ProjectionAdjustedFTEs06 ELSE 0 END, + ProjectionAdjustedFTEs07 = CASE WHEN @MonthsLoaded >= 7 THEN ProjectionAdjustedFTEs07 ELSE 0 END, + ProjectionAdjustedFTEs08 = CASE WHEN @MonthsLoaded >= 8 THEN ProjectionAdjustedFTEs08 ELSE 0 END, + ProjectionAdjustedFTEs09 = CASE WHEN @MonthsLoaded >= 9 THEN ProjectionAdjustedFTEs09 ELSE 0 END, + ProjectionAdjustedFTEs10 = CASE WHEN @MonthsLoaded >= 10 THEN ProjectionAdjustedFTEs10 ELSE 0 END, + ProjectionAdjustedFTEs11 = CASE WHEN @MonthsLoaded >= 11 THEN ProjectionAdjustedFTEs11 ELSE 0 END, + ProjectionAdjustedFTEs12 = CASE WHEN @MonthsLoaded >= 12 THEN ProjectionAdjustedFTEs12 ELSE 0 END, + TargetFTEsLockFlag = 1, + TargetFTEsLockType = 4, + BudgetFTEsLockFlag = 1, + BudgetFTEsLockType = 4, + ProjectionFTEsLockFlag = 1, + ProjectionFTEsLockType = 4 + FROM [fp].[Staffing] fs + INNER JOIN #tmpRosterRolledUp rb + ON fs.JobCodeID = rb.JobCodeID + AND fs.DepartmentID = rb.DepartmentID + AND fs.PayCodeGroupID = rb.PayCodeGroupID + AND fs.EntityID = rb.EntityID + WHERE fs.BudgetConfigID = @BudgetConfigID + AND fs.VariabilityID = 1 + AND ( + TargetAdjustedFTEs01 != 0 OR TargetAdjustedFTEs02 != 0 OR TargetAdjustedFTEs03 != 0 OR TargetAdjustedFTEs04 != 0 OR TargetAdjustedFTEs05 != 0 OR TargetAdjustedFTEs06 != 0 OR + TargetAdjustedFTEs07 != 0 OR TargetAdjustedFTEs08 != 0 OR TargetAdjustedFTEs09 != 0 OR TargetAdjustedFTEs10 != 0 OR TargetAdjustedFTEs11 != 0 OR TargetAdjustedFTEs12 != 0 OR + BudgetAdjustedFTEs01 != 0 OR BudgetAdjustedFTEs02 != 0 OR BudgetAdjustedFTEs03 != 0 OR BudgetAdjustedFTEs04 != 0 OR BudgetAdjustedFTEs05 != 0 OR BudgetAdjustedFTEs06 != 0 OR + BudgetAdjustedFTEs07 != 0 OR BudgetAdjustedFTEs08 != 0 OR BudgetAdjustedFTEs09 != 0 OR BudgetAdjustedFTEs10 != 0 OR BudgetAdjustedFTEs11 != 0 OR BudgetAdjustedFTEs12 != 0 OR + TargetFTEsLockType != 4 OR + BudgetFTEsLockType != 4 + OR + (@MonthsLoaded < 1 AND ProjectionAdjustedFTEs01 != 0) OR + (@MonthsLoaded < 2 AND ProjectionAdjustedFTEs02 != 0) OR + (@MonthsLoaded < 3 AND ProjectionAdjustedFTEs03 != 0) OR + (@MonthsLoaded < 4 AND ProjectionAdjustedFTEs04 != 0) OR + (@MonthsLoaded < 5 AND ProjectionAdjustedFTEs05 != 0) OR + (@MonthsLoaded < 6 AND ProjectionAdjustedFTEs06 != 0) OR + (@MonthsLoaded < 7 AND ProjectionAdjustedFTEs07 != 0) OR + (@MonthsLoaded < 8 AND ProjectionAdjustedFTEs08 != 0) OR + (@MonthsLoaded < 9 AND ProjectionAdjustedFTEs09 != 0) OR + (@MonthsLoaded < 10 AND ProjectionAdjustedFTEs10 != 0) OR + (@MonthsLoaded < 11 AND ProjectionAdjustedFTEs11 != 0) OR + (@MonthsLoaded < 12 AND ProjectionAdjustedFTEs12 != 0) OR + ProjectionFTEsLockType != 4 + OR + InitialBudgetFTEs01 != 0 OR InitialBudgetFTEs02 != 0 OR InitialBudgetFTEs03 != 0 OR InitialBudgetFTEs04 != 0 OR InitialBudgetFTEs05 != 0 OR InitialBudgetFTEs06 != 0 OR + InitialBudgetFTEs07 != 0 OR InitialBudgetFTEs08 != 0 OR InitialBudgetFTEs09 != 0 OR InitialBudgetFTEs10 != 0 OR InitialBudgetFTEs11 != 0 OR InitialBudgetFTEs12 != 0 OR + (@MonthsLoaded < 1 AND InitialProjectionFTEs01 != 0) OR + (@MonthsLoaded < 2 AND InitialProjectionFTEs02 != 0) OR + (@MonthsLoaded < 3 AND InitialProjectionFTEs03 != 0) OR + (@MonthsLoaded < 4 AND InitialProjectionFTEs04 != 0) OR + (@MonthsLoaded < 5 AND InitialProjectionFTEs05 != 0) OR + (@MonthsLoaded < 6 AND InitialProjectionFTEs06 != 0) OR + (@MonthsLoaded < 7 AND InitialProjectionFTEs07 != 0) OR + (@MonthsLoaded < 8 AND InitialProjectionFTEs08 != 0) OR + (@MonthsLoaded < 9 AND InitialProjectionFTEs09 != 0) OR + (@MonthsLoaded < 10 AND InitialProjectionFTEs10 != 0) OR + (@MonthsLoaded < 11 AND InitialProjectionFTEs11 != 0) OR + (@MonthsLoaded < 12 AND InitialProjectionFTEs12 != 0) + + ) + END + ELSE + BEGIN + + -- When FTEs aren't hidden we need to populate them normally. + -- It's important to note that the way FTE's are done currently for Projection are wrong. <-- The old note said they'd be updated at another time but that person was lying + UPDATE fs + SET + InitialBudgetFTEs01 = InitialFTEsMonth01, InitialBudgetFTEs02 = InitialFTEsMonth02, InitialBudgetFTEs03 = InitialFTEsMonth03, InitialBudgetFTEs04 = InitialFTEsMonth04, + InitialBudgetFTEs05 = InitialFTEsMonth05, InitialBudgetFTEs06 = InitialFTEsMonth06, InitialBudgetFTEs07 = InitialFTEsMonth07, InitialBudgetFTEs08 = InitialFTEsMonth08, + InitialBudgetFTEs09 = InitialFTEsMonth09, InitialBudgetFTEs10 = InitialFTEsMonth10, InitialBudgetFTEs11 = InitialFTEsMonth11, InitialBudgetFTEs12 = InitialFTEsMonth12, + InitialProjectionFTEs01 = CASE WHEN @MonthsLoaded >= 1 THEN InitialProjectionFTEs01 ELSE ProjectedFTEsMonth01 END, + InitialProjectionFTEs02 = CASE WHEN @MonthsLoaded >= 2 THEN InitialProjectionFTEs02 ELSE ProjectedFTEsMonth02 END, + InitialProjectionFTEs03 = CASE WHEN @MonthsLoaded >= 3 THEN InitialProjectionFTEs03 ELSE ProjectedFTEsMonth03 END, + InitialProjectionFTEs04 = CASE WHEN @MonthsLoaded >= 4 THEN InitialProjectionFTEs04 ELSE ProjectedFTEsMonth04 END, + InitialProjectionFTEs05 = CASE WHEN @MonthsLoaded >= 5 THEN InitialProjectionFTEs05 ELSE ProjectedFTEsMonth05 END, + InitialProjectionFTEs06 = CASE WHEN @MonthsLoaded >= 6 THEN InitialProjectionFTEs06 ELSE ProjectedFTEsMonth06 END, + InitialProjectionFTEs07 = CASE WHEN @MonthsLoaded >= 7 THEN InitialProjectionFTEs07 ELSE ProjectedFTEsMonth07 END, + InitialProjectionFTEs08 = CASE WHEN @MonthsLoaded >= 8 THEN InitialProjectionFTEs08 ELSE ProjectedFTEsMonth08 END, + InitialProjectionFTEs09 = CASE WHEN @MonthsLoaded >= 9 THEN InitialProjectionFTEs09 ELSE ProjectedFTEsMonth09 END, + InitialProjectionFTEs10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjectionFTEs10 ELSE ProjectedFTEsMonth10 END, + InitialProjectionFTEs11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjectionFTEs11 ELSE ProjectedFTEsMonth11 END, + InitialProjectionFTEs12 = CASE WHEN @MonthsLoaded >= 12 THEN InitialProjectionFTEs12 ELSE ProjectedFTEsMonth12 END, + TargetAdjustedFTEs01 = FTEsMonth01, TargetAdjustedFTEs02 = FTEsMonth02, TargetAdjustedFTEs03 = FTEsMonth03, TargetAdjustedFTEs04 = FTEsMonth04, TargetAdjustedFTEs05 = FTEsMonth05, TargetAdjustedFTEs06 = FTEsMonth06, + TargetAdjustedFTEs07 = FTEsMonth07, TargetAdjustedFTEs08 = FTEsMonth08, TargetAdjustedFTEs09 = FTEsMonth09, TargetAdjustedFTEs10 = FTEsMonth10, TargetAdjustedFTEs11 = FTEsMonth11, TargetAdjustedFTEs12 = FTEsMonth12, + BudgetAdjustedFTEs01 = FTEsMonth01, BudgetAdjustedFTEs02 = FTEsMonth02, BudgetAdjustedFTEs03 = FTEsMonth03, BudgetAdjustedFTEs04 = FTEsMonth04, BudgetAdjustedFTEs05 = FTEsMonth05, BudgetAdjustedFTEs06 = FTEsMonth06, + BudgetAdjustedFTEs07 = FTEsMonth07, BudgetAdjustedFTEs08 = FTEsMonth08, BudgetAdjustedFTEs09 = FTEsMonth09, BudgetAdjustedFTEs10 = FTEsMonth10, BudgetAdjustedFTEs11 = FTEsMonth11, BudgetAdjustedFTEs12 = FTEsMonth12, + ProjectionAdjustedFTEs01 = CASE WHEN @MonthsLoaded >= 1 THEN ProjectionAdjustedFTEs01 ELSE ProjectedFTEsMonth01 END, + ProjectionAdjustedFTEs02 = CASE WHEN @MonthsLoaded >= 2 THEN ProjectionAdjustedFTEs02 ELSE ProjectedFTEsMonth02 END, + ProjectionAdjustedFTEs03 = CASE WHEN @MonthsLoaded >= 3 THEN ProjectionAdjustedFTEs03 ELSE ProjectedFTEsMonth03 END, + ProjectionAdjustedFTEs04 = CASE WHEN @MonthsLoaded >= 4 THEN ProjectionAdjustedFTEs04 ELSE ProjectedFTEsMonth04 END, + ProjectionAdjustedFTEs05 = CASE WHEN @MonthsLoaded >= 5 THEN ProjectionAdjustedFTEs05 ELSE ProjectedFTEsMonth05 END, + ProjectionAdjustedFTEs06 = CASE WHEN @MonthsLoaded >= 6 THEN ProjectionAdjustedFTEs06 ELSE ProjectedFTEsMonth06 END, + ProjectionAdjustedFTEs07 = CASE WHEN @MonthsLoaded >= 7 THEN ProjectionAdjustedFTEs07 ELSE ProjectedFTEsMonth07 END, + ProjectionAdjustedFTEs08 = CASE WHEN @MonthsLoaded >= 8 THEN ProjectionAdjustedFTEs08 ELSE ProjectedFTEsMonth08 END, + ProjectionAdjustedFTEs09 = CASE WHEN @MonthsLoaded >= 9 THEN ProjectionAdjustedFTEs09 ELSE ProjectedFTEsMonth09 END, + ProjectionAdjustedFTEs10 = CASE WHEN @MonthsLoaded >= 10 THEN ProjectionAdjustedFTEs10 ELSE ProjectedFTEsMonth10 END, + ProjectionAdjustedFTEs11 = CASE WHEN @MonthsLoaded >= 11 THEN ProjectionAdjustedFTEs11 ELSE ProjectedFTEsMonth11 END, + ProjectionAdjustedFTEs12 = CASE WHEN @MonthsLoaded >= 12 THEN ProjectionAdjustedFTEs12 ELSE ProjectedFTEsMonth12 END, + TargetFTEsLockFlag = 1, + TargetFTEsLockType = 4, + BudgetFTEsLockFlag = 1, + BudgetFTEsLockType = 4, + ProjectionFTEsLockFlag = 1, + ProjectionFTEsLockType = 4 + FROM [fp].[Staffing] fs + INNER JOIN #tmpRosterRolledUp rb + ON fs.JobCodeID = rb.JobCodeID + AND fs.DepartmentID = rb.DepartmentID + AND fs.PayCodeGroupID = rb.PayCodeGroupID + AND fs.EntityID = rb.EntityID + WHERE fs.BudgetConfigID = @BudgetConfigID + AND fs.VariabilityID = 1 + AND ( + InitialBudgetFTEs01 != InitialFTEsMonth01 OR + InitialBudgetFTEs02 != InitialFTEsMonth02 OR + InitialBudgetFTEs03 != InitialFTEsMonth03 OR + InitialBudgetFTEs04 != InitialFTEsMonth04 OR + InitialBudgetFTEs05 != InitialFTEsMonth05 OR + InitialBudgetFTEs06 != InitialFTEsMonth06 OR + InitialBudgetFTEs07 != InitialFTEsMonth07 OR + InitialBudgetFTEs08 != InitialFTEsMonth08 OR + InitialBudgetFTEs09 != InitialFTEsMonth09 OR + InitialBudgetFTEs10 != InitialFTEsMonth10 OR + InitialBudgetFTEs11 != InitialFTEsMonth11 OR + InitialBudgetFTEs12 != InitialFTEsMonth12 OR + TargetAdjustedFTEs01 != FTEsMonth01 OR TargetAdjustedFTEs02 != FTEsMonth02 OR TargetAdjustedFTEs03 != FTEsMonth03 OR TargetAdjustedFTEs04 != FTEsMonth04 OR + TargetAdjustedFTEs05 != FTEsMonth05 OR TargetAdjustedFTEs06 != FTEsMonth06 OR TargetAdjustedFTEs07 != FTEsMonth07 OR TargetAdjustedFTEs08 != FTEsMonth08 OR + TargetAdjustedFTEs09 != FTEsMonth09 OR TargetAdjustedFTEs10 != FTEsMonth10 OR TargetAdjustedFTEs11 != FTEsMonth11 OR TargetAdjustedFTEs12 != FTEsMonth12 OR + BudgetAdjustedFTEs01 != FTEsMonth01 OR BudgetAdjustedFTEs02 != FTEsMonth02 OR BudgetAdjustedFTEs03 != FTEsMonth03 OR BudgetAdjustedFTEs04 != FTEsMonth04 OR + BudgetAdjustedFTEs05 != FTEsMonth05 OR BudgetAdjustedFTEs06 != FTEsMonth06 OR BudgetAdjustedFTEs07 != FTEsMonth07 OR BudgetAdjustedFTEs08 != FTEsMonth08 OR + BudgetAdjustedFTEs09 != FTEsMonth09 OR BudgetAdjustedFTEs10 != FTEsMonth10 OR BudgetAdjustedFTEs11 != FTEsMonth11 OR BudgetAdjustedFTEs12 != FTEsMonth12 OR + TargetFTEsLockType != 4 OR + BudgetFTEsLockType != 4 + OR + (@MonthsLoaded < 1 AND ProjectionAdjustedFTEs01 != CASE WHEN @MonthsLoaded >= 1 THEN ProjectionAdjustedFTEs01 ELSE ProjectedFTEsMonth01 END) OR + (@MonthsLoaded < 2 AND ProjectionAdjustedFTEs02 != CASE WHEN @MonthsLoaded >= 2 THEN ProjectionAdjustedFTEs02 ELSE ProjectedFTEsMonth02 END) OR + (@MonthsLoaded < 3 AND ProjectionAdjustedFTEs03 != CASE WHEN @MonthsLoaded >= 3 THEN ProjectionAdjustedFTEs03 ELSE ProjectedFTEsMonth03 END) OR + (@MonthsLoaded < 4 AND ProjectionAdjustedFTEs04 != CASE WHEN @MonthsLoaded >= 4 THEN ProjectionAdjustedFTEs04 ELSE ProjectedFTEsMonth04 END) OR + (@MonthsLoaded < 5 AND ProjectionAdjustedFTEs05 != CASE WHEN @MonthsLoaded >= 5 THEN ProjectionAdjustedFTEs05 ELSE ProjectedFTEsMonth05 END) OR + (@MonthsLoaded < 6 AND ProjectionAdjustedFTEs06 != CASE WHEN @MonthsLoaded >= 6 THEN ProjectionAdjustedFTEs06 ELSE ProjectedFTEsMonth06 END) OR + (@MonthsLoaded < 7 AND ProjectionAdjustedFTEs07 != CASE WHEN @MonthsLoaded >= 7 THEN ProjectionAdjustedFTEs07 ELSE ProjectedFTEsMonth07 END) OR + (@MonthsLoaded < 8 AND ProjectionAdjustedFTEs08 != CASE WHEN @MonthsLoaded >= 8 THEN ProjectionAdjustedFTEs08 ELSE ProjectedFTEsMonth08 END) OR + (@MonthsLoaded < 9 AND ProjectionAdjustedFTEs09 != CASE WHEN @MonthsLoaded >= 9 THEN ProjectionAdjustedFTEs09 ELSE ProjectedFTEsMonth09 END) OR + (@MonthsLoaded < 10 AND ProjectionAdjustedFTEs10 != CASE WHEN @MonthsLoaded >= 10 THEN ProjectionAdjustedFTEs10 ELSE ProjectedFTEsMonth10 END) OR + (@MonthsLoaded < 11 AND ProjectionAdjustedFTEs11 != CASE WHEN @MonthsLoaded >= 11 THEN ProjectionAdjustedFTEs11 ELSE ProjectedFTEsMonth11 END) OR + (@MonthsLoaded < 12 AND ProjectionAdjustedFTEs12 != CASE WHEN @MonthsLoaded >= 12 THEN ProjectionAdjustedFTEs12 ELSE ProjectedFTEsMonth12 END) OR + ProjectionFTEsLockType != 4 + OR + (@MonthsLoaded < 1 AND InitialProjectionFTEs01 != ProjectedFTEsMonth01) OR + (@MonthsLoaded < 2 AND InitialProjectionFTEs02 != ProjectedFTEsMonth02) OR + (@MonthsLoaded < 3 AND InitialProjectionFTEs03 != ProjectedFTEsMonth03) OR + (@MonthsLoaded < 4 AND InitialProjectionFTEs04 != ProjectedFTEsMonth04) OR + (@MonthsLoaded < 5 AND InitialProjectionFTEs05 != ProjectedFTEsMonth05) OR + (@MonthsLoaded < 6 AND InitialProjectionFTEs06 != ProjectedFTEsMonth06) OR + (@MonthsLoaded < 7 AND InitialProjectionFTEs07 != ProjectedFTEsMonth07) OR + (@MonthsLoaded < 8 AND InitialProjectionFTEs08 != ProjectedFTEsMonth08) OR + (@MonthsLoaded < 9 AND InitialProjectionFTEs09 != ProjectedFTEsMonth09) OR + (@MonthsLoaded < 10 AND InitialProjectionFTEs10 != ProjectedFTEsMonth10) OR + (@MonthsLoaded < 11 AND InitialProjectionFTEs11 != ProjectedFTEsMonth11) OR + (@MonthsLoaded < 12 AND InitialProjectionFTEs12 != ProjectedFTEsMonth12) + ) + + END + + + ----------------------- + -- Recalculate Hours -- + ----------------------- + UPDATE fsHour + SET + InitialBudgetHours01 = InitialBudgetFTEs01 * wh.Month01, + InitialBudgetHours02 = InitialBudgetFTEs02 * wh.Month02, + InitialBudgetHours03 = InitialBudgetFTEs03 * wh.Month03, + InitialBudgetHours04 = InitialBudgetFTEs04 * wh.Month04, + InitialBudgetHours05 = InitialBudgetFTEs05 * wh.Month05, + InitialBudgetHours06 = InitialBudgetFTEs06 * wh.Month06, + InitialBudgetHours07 = InitialBudgetFTEs07 * wh.Month07, + InitialBudgetHours08 = InitialBudgetFTEs08 * wh.Month08, + InitialBudgetHours09 = InitialBudgetFTEs09 * wh.Month09, + InitialBudgetHours10 = InitialBudgetFTEs10 * wh.Month10, + InitialBudgetHours11 = InitialBudgetFTEs11 * wh.Month11, + InitialBudgetHours12 = InitialBudgetFTEs12 * wh.Month12, + InitialProjectionHours01 = CASE WHEN @MonthsLoaded >= 1 THEN InitialProjectionHours01 ELSE InitialProjectionFTEs01 * pwh.Month01 END, + InitialProjectionHours02 = CASE WHEN @MonthsLoaded >= 2 THEN InitialProjectionHours02 ELSE InitialProjectionFTEs02 * pwh.Month02 END, + InitialProjectionHours03 = CASE WHEN @MonthsLoaded >= 3 THEN InitialProjectionHours03 ELSE InitialProjectionFTEs03 * pwh.Month03 END, + InitialProjectionHours04 = CASE WHEN @MonthsLoaded >= 4 THEN InitialProjectionHours04 ELSE InitialProjectionFTEs04 * pwh.Month04 END, + InitialProjectionHours05 = CASE WHEN @MonthsLoaded >= 5 THEN InitialProjectionHours05 ELSE InitialProjectionFTEs05 * pwh.Month05 END, + InitialProjectionHours06 = CASE WHEN @MonthsLoaded >= 6 THEN InitialProjectionHours06 ELSE InitialProjectionFTEs06 * pwh.Month06 END, + InitialProjectionHours07 = CASE WHEN @MonthsLoaded >= 7 THEN InitialProjectionHours07 ELSE InitialProjectionFTEs07 * pwh.Month07 END, + InitialProjectionHours08 = CASE WHEN @MonthsLoaded >= 8 THEN InitialProjectionHours08 ELSE InitialProjectionFTEs08 * pwh.Month08 END, + InitialProjectionHours09 = CASE WHEN @MonthsLoaded >= 9 THEN InitialProjectionHours09 ELSE InitialProjectionFTEs09 * pwh.Month09 END, + InitialProjectionHours10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjectionHours10 ELSE InitialProjectionFTEs10 * pwh.Month10 END, + InitialProjectionHours11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjectionHours11 ELSE InitialProjectionFTEs11 * pwh.Month11 END, + InitialProjectionHours12 = CASE WHEN @MonthsLoaded >= 12 THEN InitialProjectionHours12 ELSE InitialProjectionFTEs12 * pwh.Month12 END, + TargetAdjustedHours01 = TargetAdjustedFTEs01 * wh.Month01, + TargetAdjustedHours02 = TargetAdjustedFTEs02 * wh.Month02, + TargetAdjustedHours03 = TargetAdjustedFTEs03 * wh.Month03, + TargetAdjustedHours04 = TargetAdjustedFTEs04 * wh.Month04, + TargetAdjustedHours05 = TargetAdjustedFTEs05 * wh.Month05, + TargetAdjustedHours06 = TargetAdjustedFTEs06 * wh.Month06, + TargetAdjustedHours07 = TargetAdjustedFTEs07 * wh.Month07, + TargetAdjustedHours08 = TargetAdjustedFTEs08 * wh.Month08, + TargetAdjustedHours09 = TargetAdjustedFTEs09 * wh.Month09, + TargetAdjustedHours10 = TargetAdjustedFTEs10 * wh.Month10, + TargetAdjustedHours11 = TargetAdjustedFTEs11 * wh.Month11, + TargetAdjustedHours12 = TargetAdjustedFTEs12 * wh.Month12, + BudgetAdjustedHours01 = BudgetAdjustedFTEs01 * wh.Month01, + BudgetAdjustedHours02 = BudgetAdjustedFTEs02 * wh.Month02, + BudgetAdjustedHours03 = BudgetAdjustedFTEs03 * wh.Month03, + BudgetAdjustedHours04 = BudgetAdjustedFTEs04 * wh.Month04, + BudgetAdjustedHours05 = BudgetAdjustedFTEs05 * wh.Month05, + BudgetAdjustedHours06 = BudgetAdjustedFTEs06 * wh.Month06, + BudgetAdjustedHours07 = BudgetAdjustedFTEs07 * wh.Month07, + BudgetAdjustedHours08 = BudgetAdjustedFTEs08 * wh.Month08, + BudgetAdjustedHours09 = BudgetAdjustedFTEs09 * wh.Month09, + BudgetAdjustedHours10 = BudgetAdjustedFTEs10 * wh.Month10, + BudgetAdjustedHours11 = BudgetAdjustedFTEs11 * wh.Month11, + BudgetAdjustedHours12 = BudgetAdjustedFTEs12 * wh.Month12, + ProjectionAdjustedHours01 = CASE WHEN @MonthsLoaded >= 1 THEN ProjectionAdjustedHours01 ELSE ProjectionAdjustedFTEs01 * pwh.Month01 END, + ProjectionAdjustedHours02 = CASE WHEN @MonthsLoaded >= 2 THEN ProjectionAdjustedHours02 ELSE ProjectionAdjustedFTEs02 * pwh.Month02 END, + ProjectionAdjustedHours03 = CASE WHEN @MonthsLoaded >= 3 THEN ProjectionAdjustedHours03 ELSE ProjectionAdjustedFTEs03 * pwh.Month03 END, + ProjectionAdjustedHours04 = CASE WHEN @MonthsLoaded >= 4 THEN ProjectionAdjustedHours04 ELSE ProjectionAdjustedFTEs04 * pwh.Month04 END, + ProjectionAdjustedHours05 = CASE WHEN @MonthsLoaded >= 5 THEN ProjectionAdjustedHours05 ELSE ProjectionAdjustedFTEs05 * pwh.Month05 END, + ProjectionAdjustedHours06 = CASE WHEN @MonthsLoaded >= 6 THEN ProjectionAdjustedHours06 ELSE ProjectionAdjustedFTEs06 * pwh.Month06 END, + ProjectionAdjustedHours07 = CASE WHEN @MonthsLoaded >= 7 THEN ProjectionAdjustedHours07 ELSE ProjectionAdjustedFTEs07 * pwh.Month07 END, + ProjectionAdjustedHours08 = CASE WHEN @MonthsLoaded >= 8 THEN ProjectionAdjustedHours08 ELSE ProjectionAdjustedFTEs08 * pwh.Month08 END, + ProjectionAdjustedHours09 = CASE WHEN @MonthsLoaded >= 9 THEN ProjectionAdjustedHours09 ELSE ProjectionAdjustedFTEs09 * pwh.Month09 END, + ProjectionAdjustedHours10 = CASE WHEN @MonthsLoaded >= 10 THEN ProjectionAdjustedHours10 ELSE ProjectionAdjustedFTEs10 * pwh.Month10 END, + ProjectionAdjustedHours11 = CASE WHEN @MonthsLoaded >= 11 THEN ProjectionAdjustedHours11 ELSE ProjectionAdjustedFTEs11 * pwh.Month11 END, + ProjectionAdjustedHours12 = CASE WHEN @MonthsLoaded >= 12 THEN ProjectionAdjustedHours12 ELSE ProjectionAdjustedFTEs12 * pwh.Month12 END, + ProjectionHoursLockType = 4, + ProjectionHoursLockFlag = 1, + TargetHoursLockType = 4, + TargetHoursLockFlag = 1, + BudgetHoursLockType = 4, + BudgetHoursLockFlag = 1 + FROM [fp].[Staffing] fsHour + INNER JOIN [fw].[DimDepartment] dept ON fsHour.DepartmentID = dept.DepartmentID + INNER JOIN [client].[FactWorkingHoursPerMonth] wh ON wh.FiscalYearID = @BudgetYear AND wh.WorkWeekID = dept.WorkWeekID + INNER JOIN [client].[FactWorkingHoursPerMonth] pwh ON pwh.FiscalYearID = @ProjectedYear AND pwh.WorkWeekID = dept.WorkWeekID + INNER JOIN #tmpRosterRolledUp Filter ON + fsHour.DepartmentID = Filter.DepartmentID + AND fsHour.JobCodeID = Filter.JobCodeID + AND fsHour.PayCodeGroupID = Filter.PayCodeGroupID + AND fsHour.EntityID = Filter.EntityID + WHERE fsHour.BudgetConfigID = @BudgetConfigID + AND fsHour.VariabilityID = 1 + AND ( + TargetAdjustedHours01 != TargetAdjustedFTEs01 * wh.Month01 OR + TargetAdjustedHours02 != TargetAdjustedFTEs02 * wh.Month02 OR + TargetAdjustedHours03 != TargetAdjustedFTEs03 * wh.Month03 OR + TargetAdjustedHours04 != TargetAdjustedFTEs04 * wh.Month04 OR + TargetAdjustedHours05 != TargetAdjustedFTEs05 * wh.Month05 OR + TargetAdjustedHours06 != TargetAdjustedFTEs06 * wh.Month06 OR + TargetAdjustedHours07 != TargetAdjustedFTEs07 * wh.Month07 OR + TargetAdjustedHours08 != TargetAdjustedFTEs08 * wh.Month08 OR + TargetAdjustedHours09 != TargetAdjustedFTEs09 * wh.Month09 OR + TargetAdjustedHours10 != TargetAdjustedFTEs10 * wh.Month10 OR + TargetAdjustedHours11 != TargetAdjustedFTEs11 * wh.Month11 OR + TargetAdjustedHours12 != TargetAdjustedFTEs12 * wh.Month12 OR + BudgetAdjustedHours01 != BudgetAdjustedFTEs01 * wh.Month01 OR + BudgetAdjustedHours02 != BudgetAdjustedFTEs02 * wh.Month02 OR + BudgetAdjustedHours03 != BudgetAdjustedFTEs03 * wh.Month03 OR + BudgetAdjustedHours04 != BudgetAdjustedFTEs04 * wh.Month04 OR + BudgetAdjustedHours05 != BudgetAdjustedFTEs05 * wh.Month05 OR + BudgetAdjustedHours06 != BudgetAdjustedFTEs06 * wh.Month06 OR + BudgetAdjustedHours07 != BudgetAdjustedFTEs07 * wh.Month07 OR + BudgetAdjustedHours08 != BudgetAdjustedFTEs08 * wh.Month08 OR + BudgetAdjustedHours09 != BudgetAdjustedFTEs09 * wh.Month09 OR + BudgetAdjustedHours10 != BudgetAdjustedFTEs10 * wh.Month10 OR + BudgetAdjustedHours11 != BudgetAdjustedFTEs11 * wh.Month11 OR + BudgetAdjustedHours12 != BudgetAdjustedFTEs12 * wh.Month12 OR + TargetHoursLockType != 4 OR + BudgetHoursLockType != 4 + OR + (@MonthsLoaded < 1 AND ProjectionAdjustedHours01 != ProjectionAdjustedFTEs01 * pwh.Month01) OR + (@MonthsLoaded < 2 AND ProjectionAdjustedHours02 != ProjectionAdjustedFTEs02 * pwh.Month02) OR + (@MonthsLoaded < 3 AND ProjectionAdjustedHours03 != ProjectionAdjustedFTEs03 * pwh.Month03) OR + (@MonthsLoaded < 4 AND ProjectionAdjustedHours04 != ProjectionAdjustedFTEs04 * pwh.Month04) OR + (@MonthsLoaded < 5 AND ProjectionAdjustedHours05 != ProjectionAdjustedFTEs05 * pwh.Month05) OR + (@MonthsLoaded < 6 AND ProjectionAdjustedHours06 != ProjectionAdjustedFTEs06 * pwh.Month06) OR + (@MonthsLoaded < 7 AND ProjectionAdjustedHours07 != ProjectionAdjustedFTEs07 * pwh.Month07) OR + (@MonthsLoaded < 8 AND ProjectionAdjustedHours08 != ProjectionAdjustedFTEs08 * pwh.Month08) OR + (@MonthsLoaded < 9 AND ProjectionAdjustedHours09 != ProjectionAdjustedFTEs09 * pwh.Month09) OR + (@MonthsLoaded < 10 AND ProjectionAdjustedHours10 != ProjectionAdjustedFTEs10 * pwh.Month10) OR + (@MonthsLoaded < 11 AND ProjectionAdjustedHours11 != ProjectionAdjustedFTEs11 * pwh.Month11) OR + (@MonthsLoaded < 12 AND ProjectionAdjustedHours12 != ProjectionAdjustedFTEs12 * pwh.Month12) OR + ProjectionHoursLockType != 4 + OR + InitialBudgetHours01 != InitialBudgetFTEs01 * wh.Month01 OR + InitialBudgetHours02 != InitialBudgetFTEs02 * wh.Month02 OR + InitialBudgetHours03 != InitialBudgetFTEs03 * wh.Month03 OR + InitialBudgetHours04 != InitialBudgetFTEs04 * wh.Month04 OR + InitialBudgetHours05 != InitialBudgetFTEs05 * wh.Month05 OR + InitialBudgetHours06 != InitialBudgetFTEs06 * wh.Month06 OR + InitialBudgetHours07 != InitialBudgetFTEs07 * wh.Month07 OR + InitialBudgetHours08 != InitialBudgetFTEs08 * wh.Month08 OR + InitialBudgetHours09 != InitialBudgetFTEs09 * wh.Month09 OR + InitialBudgetHours10 != InitialBudgetFTEs10 * wh.Month10 OR + InitialBudgetHours11 != InitialBudgetFTEs11 * wh.Month11 OR + InitialBudgetHours12 != InitialBudgetFTEs12 * wh.Month12 OR + (@MonthsLoaded < 1 AND InitialProjectionHours01 != InitialProjectionFTEs01 * pwh.Month01) OR + (@MonthsLoaded < 2 AND InitialProjectionHours02 != InitialProjectionFTEs02 * pwh.Month02) OR + (@MonthsLoaded < 3 AND InitialProjectionHours03 != InitialProjectionFTEs03 * pwh.Month03) OR + (@MonthsLoaded < 4 AND InitialProjectionHours04 != InitialProjectionFTEs04 * pwh.Month04) OR + (@MonthsLoaded < 5 AND InitialProjectionHours05 != InitialProjectionFTEs05 * pwh.Month05) OR + (@MonthsLoaded < 6 AND InitialProjectionHours06 != InitialProjectionFTEs06 * pwh.Month06) OR + (@MonthsLoaded < 7 AND InitialProjectionHours07 != InitialProjectionFTEs07 * pwh.Month07) OR + (@MonthsLoaded < 8 AND InitialProjectionHours08 != InitialProjectionFTEs08 * pwh.Month08) OR + (@MonthsLoaded < 9 AND InitialProjectionHours09 != InitialProjectionFTEs09 * pwh.Month09) OR + (@MonthsLoaded < 10 AND InitialProjectionHours10 != InitialProjectionFTEs10 * pwh.Month10) OR + (@MonthsLoaded < 11 AND InitialProjectionHours11 != InitialProjectionFTEs11 * pwh.Month11) OR + (@MonthsLoaded < 12 AND InitialProjectionHours12 != InitialProjectionFTEs12 * pwh.Month12) + ) + + + + -------------------- + -- Update Dollars -- + -------------------- + UPDATE fs + SET + InitialBudgetDollars01 = InitialDollarsMonth01, InitialBudgetDollars02 = InitialDollarsMonth02, InitialBudgetDollars03 = InitialDollarsMonth03, InitialBudgetDollars04 = InitialDollarsMonth04, + InitialBudgetDollars05 = InitialDollarsMonth05, InitialBudgetDollars06 = InitialDollarsMonth06, InitialBudgetDollars07 = InitialDollarsMonth07, InitialBudgetDollars08 = InitialDollarsMonth08, + InitialBudgetDollars09 = InitialDollarsMonth09, InitialBudgetDollars10 = InitialDollarsMonth10, InitialBudgetDollars11 = InitialDollarsMonth11, InitialBudgetDollars12 = InitialDollarsMonth12, + InitialProjectionDollars01 = CASE WHEN @MonthsLoaded >= 1 THEN InitialProjectionDollars01 ELSE ProjectedDollarsMonth01 END, + InitialProjectionDollars02 = CASE WHEN @MonthsLoaded >= 2 THEN InitialProjectionDollars02 ELSE ProjectedDollarsMonth02 END, + InitialProjectionDollars03 = CASE WHEN @MonthsLoaded >= 3 THEN InitialProjectionDollars03 ELSE ProjectedDollarsMonth03 END, + InitialProjectionDollars04 = CASE WHEN @MonthsLoaded >= 4 THEN InitialProjectionDollars04 ELSE ProjectedDollarsMonth04 END, + InitialProjectionDollars05 = CASE WHEN @MonthsLoaded >= 5 THEN InitialProjectionDollars05 ELSE ProjectedDollarsMonth05 END, + InitialProjectionDollars06 = CASE WHEN @MonthsLoaded >= 6 THEN InitialProjectionDollars06 ELSE ProjectedDollarsMonth06 END, + InitialProjectionDollars07 = CASE WHEN @MonthsLoaded >= 7 THEN InitialProjectionDollars07 ELSE ProjectedDollarsMonth07 END, + InitialProjectionDollars08 = CASE WHEN @MonthsLoaded >= 8 THEN InitialProjectionDollars08 ELSE ProjectedDollarsMonth08 END, + InitialProjectionDollars09 = CASE WHEN @MonthsLoaded >= 9 THEN InitialProjectionDollars09 ELSE ProjectedDollarsMonth09 END, + InitialProjectionDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN InitialProjectionDollars10 ELSE ProjectedDollarsMonth10 END, + InitialProjectionDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN InitialProjectionDollars11 ELSE ProjectedDollarsMonth11 END, + InitialProjectionDollars12 = CASE WHEN @MonthsLoaded >= 12 THEN InitialProjectionDollars12 ELSE ProjectedDollarsMonth12 END, + TargetAdjustedDollars01 = DollarsMonth01, TargetAdjustedDollars02 = DollarsMonth02, TargetAdjustedDollars03 = DollarsMonth03, TargetAdjustedDollars04 = DollarsMonth04, TargetAdjustedDollars05 = DollarsMonth05, TargetAdjustedDollars06 = DollarsMonth06, + TargetAdjustedDollars07 = DollarsMonth07, TargetAdjustedDollars08 = DollarsMonth08, TargetAdjustedDollars09 = DollarsMonth09, TargetAdjustedDollars10 = DollarsMonth10, TargetAdjustedDollars11 = DollarsMonth11, TargetAdjustedDollars12 = DollarsMonth12, + BudgetAdjustedDollars01 = DollarsMonth01, BudgetAdjustedDollars02 = DollarsMonth02, BudgetAdjustedDollars03 = DollarsMonth03, BudgetAdjustedDollars04 = DollarsMonth04, BudgetAdjustedDollars05 = DollarsMonth05, BudgetAdjustedDollars06 = DollarsMonth06, + BudgetAdjustedDollars07 = DollarsMonth07, BudgetAdjustedDollars08 = DollarsMonth08, BudgetAdjustedDollars09 = DollarsMonth09, BudgetAdjustedDollars10 = DollarsMonth10, BudgetAdjustedDollars11 = DollarsMonth11, BudgetAdjustedDollars12 = DollarsMonth12, + ProjectionAdjustedDollars01 = CASE WHEN @MonthsLoaded >= 1 THEN ProjectionAdjustedDollars01 ELSE ProjectedDollarsMonth01 END, + ProjectionAdjustedDollars02 = CASE WHEN @MonthsLoaded >= 2 THEN ProjectionAdjustedDollars02 ELSE ProjectedDollarsMonth02 END, + ProjectionAdjustedDollars03 = CASE WHEN @MonthsLoaded >= 3 THEN ProjectionAdjustedDollars03 ELSE ProjectedDollarsMonth03 END, + ProjectionAdjustedDollars04 = CASE WHEN @MonthsLoaded >= 4 THEN ProjectionAdjustedDollars04 ELSE ProjectedDollarsMonth04 END, + ProjectionAdjustedDollars05 = CASE WHEN @MonthsLoaded >= 5 THEN ProjectionAdjustedDollars05 ELSE ProjectedDollarsMonth05 END, + ProjectionAdjustedDollars06 = CASE WHEN @MonthsLoaded >= 6 THEN ProjectionAdjustedDollars06 ELSE ProjectedDollarsMonth06 END, + ProjectionAdjustedDollars07 = CASE WHEN @MonthsLoaded >= 7 THEN ProjectionAdjustedDollars07 ELSE ProjectedDollarsMonth07 END, + ProjectionAdjustedDollars08 = CASE WHEN @MonthsLoaded >= 8 THEN ProjectionAdjustedDollars08 ELSE ProjectedDollarsMonth08 END, + ProjectionAdjustedDollars09 = CASE WHEN @MonthsLoaded >= 9 THEN ProjectionAdjustedDollars09 ELSE ProjectedDollarsMonth09 END, + ProjectionAdjustedDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN ProjectionAdjustedDollars10 ELSE ProjectedDollarsMonth10 END, + ProjectionAdjustedDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN ProjectionAdjustedDollars11 ELSE ProjectedDollarsMonth11 END, + ProjectionAdjustedDollars12 = CASE WHEN @MonthsLoaded >= 12 THEN ProjectionAdjustedDollars12 ELSE ProjectedDollarsMonth12 END, + ProjectionDollarsLockFlag = 1, + ProjectionDollarsLockType = 4, + TargetDollarsLockFlag = 1, + TargetDollarsLockType = 4, + BudgetDollarsLockFlag = 1, + BudgetDollarsLockType = 4 + FROM [fp].[Staffing] fs + INNER JOIN #tmpRosterRolledUp rb + ON fs.JobCodeID = rb.JobCodeID + AND fs.DepartmentID = rb.DepartmentID + AND fs.PayCodeGroupID = rb.PayCodeGroupID + AND fs.EntityID = rb.EntityID + WHERE fs.BudgetConfigID = @BudgetConfigID + AND fs.VariabilityID = 1 + AND ( + TargetAdjustedDollars01 != DollarsMonth01 OR + TargetAdjustedDollars02 != DollarsMonth02 OR + TargetAdjustedDollars03 != DollarsMonth03 OR + TargetAdjustedDollars04 != DollarsMonth04 OR + TargetAdjustedDollars05 != DollarsMonth05 OR + TargetAdjustedDollars06 != DollarsMonth06 OR + TargetAdjustedDollars07 != DollarsMonth07 OR + TargetAdjustedDollars08 != DollarsMonth08 OR + TargetAdjustedDollars09 != DollarsMonth09 OR + TargetAdjustedDollars10 != DollarsMonth10 OR + TargetAdjustedDollars11 != DollarsMonth11 OR + TargetAdjustedDollars12 != DollarsMonth12 OR + BudgetAdjustedDollars01 != DollarsMonth01 OR + BudgetAdjustedDollars02 != DollarsMonth02 OR + BudgetAdjustedDollars03 != DollarsMonth03 OR + BudgetAdjustedDollars04 != DollarsMonth04 OR + BudgetAdjustedDollars05 != DollarsMonth05 OR + BudgetAdjustedDollars06 != DollarsMonth06 OR + BudgetAdjustedDollars07 != DollarsMonth07 OR + BudgetAdjustedDollars08 != DollarsMonth08 OR + BudgetAdjustedDollars09 != DollarsMonth09 OR + BudgetAdjustedDollars10 != DollarsMonth10 OR + BudgetAdjustedDollars11 != DollarsMonth11 OR + BudgetAdjustedDollars12 != DollarsMonth12 OR + TargetDollarsLockType != 4 OR + BudgetDollarsLockType != 4 + OR + (@MonthsLoaded < 1 AND ProjectionAdjustedDollars01 != ProjectedDollarsMonth01) OR + (@MonthsLoaded < 2 AND ProjectionAdjustedDollars02 != ProjectedDollarsMonth02) OR + (@MonthsLoaded < 3 AND ProjectionAdjustedDollars03 != ProjectedDollarsMonth03) OR + (@MonthsLoaded < 4 AND ProjectionAdjustedDollars04 != ProjectedDollarsMonth04) OR + (@MonthsLoaded < 5 AND ProjectionAdjustedDollars05 != ProjectedDollarsMonth05) OR + (@MonthsLoaded < 6 AND ProjectionAdjustedDollars06 != ProjectedDollarsMonth06) OR + (@MonthsLoaded < 7 AND ProjectionAdjustedDollars07 != ProjectedDollarsMonth07) OR + (@MonthsLoaded < 8 AND ProjectionAdjustedDollars08 != ProjectedDollarsMonth08) OR + (@MonthsLoaded < 9 AND ProjectionAdjustedDollars09 != ProjectedDollarsMonth09) OR + (@MonthsLoaded < 10 AND ProjectionAdjustedDollars10 != ProjectedDollarsMonth10) OR + (@MonthsLoaded < 11 AND ProjectionAdjustedDollars11 != ProjectedDollarsMonth11) OR + (@MonthsLoaded < 12 AND ProjectionAdjustedDollars12 != ProjectedDollarsMonth12) OR + ProjectionDollarsLockType != 4 + OR + InitialBudgetDollars01 != InitialDollarsMonth01 OR + InitialBudgetDollars02 != InitialDollarsMonth02 OR + InitialBudgetDollars03 != InitialDollarsMonth03 OR + InitialBudgetDollars04 != InitialDollarsMonth04 OR + InitialBudgetDollars05 != InitialDollarsMonth05 OR + InitialBudgetDollars06 != InitialDollarsMonth06 OR + InitialBudgetDollars07 != InitialDollarsMonth07 OR + InitialBudgetDollars08 != InitialDollarsMonth08 OR + InitialBudgetDollars09 != InitialDollarsMonth09 OR + InitialBudgetDollars10 != InitialDollarsMonth10 OR + InitialBudgetDollars11 != InitialDollarsMonth11 OR + InitialBudgetDollars12 != InitialDollarsMonth12 OR + (@MonthsLoaded < 1 AND InitialProjectionDollars01 != ProjectedDollarsMonth01) OR + (@MonthsLoaded < 2 AND InitialProjectionDollars02 != ProjectedDollarsMonth02) OR + (@MonthsLoaded < 3 AND InitialProjectionDollars03 != ProjectedDollarsMonth03) OR + (@MonthsLoaded < 4 AND InitialProjectionDollars04 != ProjectedDollarsMonth04) OR + (@MonthsLoaded < 5 AND InitialProjectionDollars05 != ProjectedDollarsMonth05) OR + (@MonthsLoaded < 6 AND InitialProjectionDollars06 != ProjectedDollarsMonth06) OR + (@MonthsLoaded < 7 AND InitialProjectionDollars07 != ProjectedDollarsMonth07) OR + (@MonthsLoaded < 8 AND InitialProjectionDollars08 != ProjectedDollarsMonth08) OR + (@MonthsLoaded < 9 AND InitialProjectionDollars09 != ProjectedDollarsMonth09) OR + (@MonthsLoaded < 10 AND InitialProjectionDollars10 != ProjectedDollarsMonth10) OR + (@MonthsLoaded < 11 AND InitialProjectionDollars11 != ProjectedDollarsMonth11) OR + (@MonthsLoaded < 12 AND InitialProjectionDollars12 != ProjectedDollarsMonth12) + ) + + + ---------------------- + -- Update Wage Rate -- (corresponds to line 1144 in rollback) + ---------------------- + UPDATE wageRate + SET + wageRate.InitialBudget01 = fs.InitialBudget01, + wageRate.InitialBudget02 = fs.InitialBudget02, + wageRate.InitialBudget03 = fs.InitialBudget03, + wageRate.InitialBudget04 = fs.InitialBudget04, + wageRate.InitialBudget05 = fs.InitialBudget05, + wageRate.InitialBudget06 = fs.InitialBudget06, + wageRate.InitialBudget07 = fs.InitialBudget07, + wageRate.InitialBudget08 = fs.InitialBudget08, + wageRate.InitialBudget09 = fs.InitialBudget09, + wageRate.InitialBudget10 = fs.InitialBudget10, + wageRate.InitialBudget11 = fs.InitialBudget11, + wageRate.InitialBudget12 = fs.InitialBudget12, + + wageRate.InitialProjection01 = CASE WHEN @MonthsLoaded >= 1 THEN WageRate.InitialProjection01 ELSE fs.InitialProjection01 END, + wageRate.InitialProjection02 = CASE WHEN @MonthsLoaded >= 2 THEN WageRate.InitialProjection02 ELSE fs.InitialProjection02 END, + wageRate.InitialProjection03 = CASE WHEN @MonthsLoaded >= 3 THEN WageRate.InitialProjection03 ELSE fs.InitialProjection03 END, + wageRate.InitialProjection04 = CASE WHEN @MonthsLoaded >= 4 THEN WageRate.InitialProjection04 ELSE fs.InitialProjection04 END, + wageRate.InitialProjection05 = CASE WHEN @MonthsLoaded >= 5 THEN WageRate.InitialProjection05 ELSE fs.InitialProjection05 END, + wageRate.InitialProjection06 = CASE WHEN @MonthsLoaded >= 6 THEN WageRate.InitialProjection06 ELSE fs.InitialProjection06 END, + wageRate.InitialProjection07 = CASE WHEN @MonthsLoaded >= 7 THEN WageRate.InitialProjection07 ELSE fs.InitialProjection07 END, + wageRate.InitialProjection08 = CASE WHEN @MonthsLoaded >= 8 THEN WageRate.InitialProjection08 ELSE fs.InitialProjection08 END, + wageRate.InitialProjection09 = CASE WHEN @MonthsLoaded >= 9 THEN WageRate.InitialProjection09 ELSE fs.InitialProjection09 END, + wageRate.InitialProjection10 = CASE WHEN @MonthsLoaded >= 10 THEN WageRate.InitialProjection10 ELSE fs.InitialProjection10 END, + wageRate.InitialProjection11 = CASE WHEN @MonthsLoaded >= 11 THEN WageRate.InitialProjection11 ELSE fs.InitialProjection11 END, + wageRate.InitialProjection12 = CASE WHEN @MonthsLoaded >= 12 THEN WageRate.InitialProjection12 ELSE fs.InitialProjection12 END, + + + TargetAdjusted01 = fs.TargetAdjusted01, + TargetAdjusted02 = fs.TargetAdjusted02, + TargetAdjusted03 = fs.TargetAdjusted03, + TargetAdjusted04 = fs.TargetAdjusted04, + TargetAdjusted05 = fs.TargetAdjusted05, + TargetAdjusted06 = fs.TargetAdjusted06, + TargetAdjusted07 = fs.TargetAdjusted07, + TargetAdjusted08 = fs.TargetAdjusted08, + TargetAdjusted09 = fs.TargetAdjusted09, + TargetAdjusted10 = fs.TargetAdjusted10, + TargetAdjusted11 = fs.TargetAdjusted11, + TargetAdjusted12 = fs.TargetAdjusted12, + + BudgetAdjusted01 = fs.BudgetAdjusted01, + BudgetAdjusted02 = fs.BudgetAdjusted02, + BudgetAdjusted03 = fs.BudgetAdjusted03, + BudgetAdjusted04 = fs.BudgetAdjusted04, + BudgetAdjusted05 = fs.BudgetAdjusted05, + BudgetAdjusted06 = fs.BudgetAdjusted06, + BudgetAdjusted07 = fs.BudgetAdjusted07, + BudgetAdjusted08 = fs.BudgetAdjusted08, + BudgetAdjusted09 = fs.BudgetAdjusted09, + BudgetAdjusted10 = fs.BudgetAdjusted10, + BudgetAdjusted11 = fs.BudgetAdjusted11, + BudgetAdjusted12 = fs.BudgetAdjusted12, + + ProjectionAdjusted01 = CASE WHEN @MonthsLoaded >= 1 THEN wageRate.ProjectionAdjusted01 ELSE fs.ProjectionAdjusted01 END, + ProjectionAdjusted02 = CASE WHEN @MonthsLoaded >= 2 THEN WageRate.ProjectionAdjusted02 ELSE fs.ProjectionAdjusted02 END, + ProjectionAdjusted03 = CASE WHEN @MonthsLoaded >= 3 THEN WageRate.ProjectionAdjusted03 ELSE fs.ProjectionAdjusted03 END, + ProjectionAdjusted04 = CASE WHEN @MonthsLoaded >= 4 THEN WageRate.ProjectionAdjusted04 ELSE fs.ProjectionAdjusted04 END, + ProjectionAdjusted05 = CASE WHEN @MonthsLoaded >= 5 THEN WageRate.ProjectionAdjusted05 ELSE fs.ProjectionAdjusted05 END, + ProjectionAdjusted06 = CASE WHEN @MonthsLoaded >= 6 THEN WageRate.ProjectionAdjusted06 ELSE fs.ProjectionAdjusted06 END, + ProjectionAdjusted07 = CASE WHEN @MonthsLoaded >= 7 THEN WageRate.ProjectionAdjusted07 ELSE fs.ProjectionAdjusted07 END, + ProjectionAdjusted08 = CASE WHEN @MonthsLoaded >= 8 THEN WageRate.ProjectionAdjusted08 ELSE fs.ProjectionAdjusted08 END, + ProjectionAdjusted09 = CASE WHEN @MonthsLoaded >= 9 THEN WageRate.ProjectionAdjusted09 ELSE fs.ProjectionAdjusted09 END, + ProjectionAdjusted10 = CASE WHEN @MonthsLoaded >= 10 THEN WageRate.ProjectionAdjusted10 ELSE fs.ProjectionAdjusted10 END, + ProjectionAdjusted11 = CASE WHEN @MonthsLoaded >= 11 THEN WageRate.ProjectionAdjusted11 ELSE fs.ProjectionAdjusted11 END, + ProjectionAdjusted12 = CASE WHEN @MonthsLoaded >= 12 THEN WageRate.ProjectionAdjusted12 ELSE fs.ProjectionAdjusted12 END, + + TargetWageRateLockFlag = 1, + TargetWageRateLockType = 4, + BudgetWageRateLockFlag = 1, + BudgetWageRateLockType = 4, + ProjectionWageRateLockFlag = 1, + ProjectionWageRateLockType = 4 + FROM [fp].[StaffingWageRate] wageRate + INNER JOIN ( + SELECT StaffingWageRateID, -- doing this here so we don't have to run the calcs twice, once in the set above, and once in the where below + + COALESCE((InitialBudgetDollars01) / (NULLIF(InitialBudgetHours01, 0)), 0) as InitialBudget01, COALESCE((InitialBudgetDollars02) / (NULLIF(InitialBudgetHours02, 0)), 0) as InitialBudget02, COALESCE((InitialBudgetDollars03) / (NULLIF(InitialBudgetHours03, 0)), 0) as InitialBudget03, COALESCE((InitialBudgetDollars04) / (NULLIF(InitialBudgetHours04, 0)), 0) as InitialBudget04, + COALESCE((InitialBudgetDollars05) / (NULLIF(InitialBudgetHours05, 0)), 0) as InitialBudget05, COALESCE((InitialBudgetDollars06) / (NULLIF(InitialBudgetHours06, 0)), 0) as InitialBudget06, COALESCE((InitialBudgetDollars07) / (NULLIF(InitialBudgetHours07, 0)), 0) as InitialBudget07, COALESCE((InitialBudgetDollars08) / (NULLIF(InitialBudgetHours08, 0)), 0) as InitialBudget08, + COALESCE((InitialBudgetDollars09) / (NULLIF(InitialBudgetHours09, 0)), 0) as InitialBudget09, COALESCE((InitialBudgetDollars10) / (NULLIF(InitialBudgetHours10, 0)), 0) as InitialBudget10, COALESCE((InitialBudgetDollars11) / (NULLIF(InitialBudgetHours11, 0)), 0) as InitialBudget11, COALESCE((InitialBudgetDollars12) / (NULLIF(InitialBudgetHours12, 0)), 0) as InitialBudget12, + + COALESCE((InitialProjectionDollars01) / (NULLIF(InitialProjectionHours01, 0)), 0) as InitialProjection01, COALESCE((InitialProjectionDollars02) / (NULLIF(InitialProjectionHours02, 0)), 0) as InitialProjection02, COALESCE((InitialProjectionDollars03) / (NULLIF(InitialProjectionHours03, 0)), 0) as InitialProjection03, COALESCE((InitialProjectionDollars04) / (NULLIF(InitialProjectionHours04, 0)), 0) as InitialProjection04, + COALESCE((InitialProjectionDollars05) / (NULLIF(InitialProjectionHours05, 0)), 0) as InitialProjection05, COALESCE((InitialProjectionDollars06) / (NULLIF(InitialProjectionHours06, 0)), 0) as InitialProjection06, COALESCE((InitialProjectionDollars07) / (NULLIF(InitialProjectionHours07, 0)), 0) as InitialProjection07, COALESCE((InitialProjectionDollars08) / (NULLIF(InitialProjectionHours08, 0)), 0) as InitialProjection08, + COALESCE((InitialProjectionDollars09) / (NULLIF(InitialProjectionHours09, 0)), 0) as InitialProjection09, COALESCE((InitialProjectionDollars10) / (NULLIF(InitialProjectionHours10, 0)), 0) as InitialProjection10, COALESCE((InitialProjectionDollars11) / (NULLIF(InitialProjectionHours11, 0)), 0) as InitialProjection11, COALESCE((InitialProjectionDollars12) / (NULLIF(InitialProjectionHours12, 0)), 0) as InitialProjection12, + + COALESCE((TargetAdjustedDollars01) / (NULLIF(TargetAdjustedHours01, 0)), 0) as TargetAdjusted01, COALESCE((TargetAdjustedDollars02 / NULLIF(TargetAdjustedHours02, 0)), 0) as TargetAdjusted02, COALESCE((TargetAdjustedDollars03 / NULLIF(TargetAdjustedHours03, 0)), 0) as TargetAdjusted03, COALESCE((TargetAdjustedDollars04 / NULLIF(TargetAdjustedHours04, 0)), 0) as TargetAdjusted04, + COALESCE((TargetAdjustedDollars05) / (NULLIF(TargetAdjustedHours05, 0)), 0) as TargetAdjusted05, COALESCE((TargetAdjustedDollars06 / NULLIF(TargetAdjustedHours06, 0)), 0) as TargetAdjusted06, COALESCE((TargetAdjustedDollars07 / NULLIF(TargetAdjustedHours07, 0)), 0) as TargetAdjusted07, COALESCE((TargetAdjustedDollars08 / NULLIF(TargetAdjustedHours08, 0)), 0) as TargetAdjusted08, + COALESCE((TargetAdjustedDollars09) / (NULLIF(TargetAdjustedHours09, 0)), 0) as TargetAdjusted09, COALESCE((TargetAdjustedDollars10 / NULLIF(TargetAdjustedHours10, 0)), 0) as TargetAdjusted10, COALESCE((TargetAdjustedDollars11 / NULLIF(TargetAdjustedHours11, 0)), 0) as TargetAdjusted11, COALESCE((TargetAdjustedDollars12 / NULLIF(TargetAdjustedHours12, 0)), 0) as TargetAdjusted12, + + COALESCE((BudgetAdjustedDollars01) / (NULLIF(BudgetAdjustedHours01, 0)), 0) as BudgetAdjusted01, COALESCE((BudgetAdjustedDollars02 / NULLIF(BudgetAdjustedHours02, 0)), 0) as BudgetAdjusted02, COALESCE((BudgetAdjustedDollars03 / NULLIF(BudgetAdjustedHours03, 0)), 0) as BudgetAdjusted03, COALESCE((BudgetAdjustedDollars04 / NULLIF(BudgetAdjustedHours04, 0)), 0) as BudgetAdjusted04, + COALESCE((BudgetAdjustedDollars05) / (NULLIF(BudgetAdjustedHours05, 0)), 0) as BudgetAdjusted05, COALESCE((BudgetAdjustedDollars06 / NULLIF(BudgetAdjustedHours06, 0)), 0) as BudgetAdjusted06, COALESCE((BudgetAdjustedDollars07 / NULLIF(BudgetAdjustedHours07, 0)), 0) as BudgetAdjusted07, COALESCE((BudgetAdjustedDollars08 / NULLIF(BudgetAdjustedHours08, 0)), 0) as BudgetAdjusted08, + COALESCE((BudgetAdjustedDollars09) / (NULLIF(BudgetAdjustedHours09, 0)), 0) as BudgetAdjusted09, COALESCE((BudgetAdjustedDollars10 / NULLIF(BudgetAdjustedHours10, 0)), 0) as BudgetAdjusted10, COALESCE((BudgetAdjustedDollars11 / NULLIF(BudgetAdjustedHours11, 0)), 0) as BudgetAdjusted11, COALESCE((BudgetAdjustedDollars12 / NULLIF(BudgetAdjustedHours12, 0)), 0) as BudgetAdjusted12, + + COALESCE((ProjectionAdjustedDollars01) / (NULLIF(ProjectionAdjustedHours01, 0)), 0) as ProjectionAdjusted01, COALESCE((ProjectionAdjustedDollars02 / NULLIF(ProjectionAdjustedHours02, 0)), 0) as ProjectionAdjusted02, COALESCE((ProjectionAdjustedDollars03 / NULLIF(ProjectionAdjustedHours03, 0)), 0) as ProjectionAdjusted03, COALESCE((ProjectionAdjustedDollars04 / NULLIF(ProjectionAdjustedHours04, 0)), 0) as ProjectionAdjusted04, + COALESCE((ProjectionAdjustedDollars05) / (NULLIF(ProjectionAdjustedHours05, 0)), 0) as ProjectionAdjusted05, COALESCE((ProjectionAdjustedDollars06 / NULLIF(ProjectionAdjustedHours06, 0)), 0) as ProjectionAdjusted06, COALESCE((ProjectionAdjustedDollars07 / NULLIF(ProjectionAdjustedHours07, 0)), 0) as ProjectionAdjusted07, COALESCE((ProjectionAdjustedDollars08 / NULLIF(ProjectionAdjustedHours08, 0)), 0) as ProjectionAdjusted08, + COALESCE((ProjectionAdjustedDollars09) / (NULLIF(ProjectionAdjustedHours09, 0)), 0) as ProjectionAdjusted09, COALESCE((ProjectionAdjustedDollars10 / NULLIF(ProjectionAdjustedHours10, 0)), 0) as ProjectionAdjusted10, COALESCE((ProjectionAdjustedDollars11 / NULLIF(ProjectionAdjustedHours11, 0)), 0) as ProjectionAdjusted11, COALESCE((ProjectionAdjustedDollars12 / NULLIF(ProjectionAdjustedHours12, 0)), 0) as ProjectionAdjusted12 + + FROM [fp].[Staffing] fs + INNER JOIN #tmpRosterRolledUp rb -- keep this here to make sure we only update wage rates related to roster + ON fs.JobCodeID = rb.JobCodeID + AND fs.DepartmentID = rb.DepartmentID + AND fs.PayCodeGroupID = rb.PayCodeGroupID + AND fs.EntityID = rb.EntityID + WHERE fs.BudgetConfigID = @BudgetConfigID AND fs.VariabilityID = 1 + ) fs ON wageRate.StaffingWageRateID = fs.StaffingWageRateID + WHERE + wageRate.TargetAdjusted01 != fs.TargetAdjusted01 OR + wageRate.TargetAdjusted02 != fs.TargetAdjusted02 OR + wageRate.TargetAdjusted03 != fs.TargetAdjusted03 OR + wageRate.TargetAdjusted04 != fs.TargetAdjusted04 OR + wageRate.TargetAdjusted05 != fs.TargetAdjusted05 OR + wageRate.TargetAdjusted06 != fs.TargetAdjusted06 OR + wageRate.TargetAdjusted07 != fs.TargetAdjusted07 OR + wageRate.TargetAdjusted01 != fs.TargetAdjusted01 OR + wageRate.TargetAdjusted08 != fs.TargetAdjusted08 OR + wageRate.TargetAdjusted09 != fs.TargetAdjusted09 OR + wageRate.TargetAdjusted10 != fs.TargetAdjusted10 OR + wageRate.TargetAdjusted11 != fs.TargetAdjusted11 OR + wageRate.TargetAdjusted12 != fs.TargetAdjusted12 OR + wageRate.BudgetAdjusted01 != fs.BudgetAdjusted01 OR + wageRate.BudgetAdjusted02 != fs.BudgetAdjusted02 OR + wageRate.BudgetAdjusted03 != fs.BudgetAdjusted03 OR + wageRate.BudgetAdjusted04 != fs.BudgetAdjusted04 OR + wageRate.BudgetAdjusted05 != fs.BudgetAdjusted05 OR + wageRate.BudgetAdjusted06 != fs.BudgetAdjusted06 OR + wageRate.BudgetAdjusted07 != fs.BudgetAdjusted07 OR + wageRate.BudgetAdjusted01 != fs.BudgetAdjusted01 OR + wageRate.BudgetAdjusted08 != fs.BudgetAdjusted08 OR + wageRate.BudgetAdjusted09 != fs.BudgetAdjusted09 OR + wageRate.BudgetAdjusted10 != fs.BudgetAdjusted10 OR + wageRate.BudgetAdjusted11 != fs.BudgetAdjusted11 OR + wageRate.BudgetAdjusted12 != fs.BudgetAdjusted12 OR + wageRate.TargetWageRateLockType != 4 OR + wageRate.BudgetWageRateLockType != 4 + OR + (@MonthsLoaded < 1 AND wageRate.ProjectionAdjusted01 != fs.ProjectionAdjusted01) OR + (@MonthsLoaded < 2 AND wageRate.ProjectionAdjusted02 != fs.ProjectionAdjusted02) OR + (@MonthsLoaded < 3 AND wageRate.ProjectionAdjusted03 != fs.ProjectionAdjusted03) OR + (@MonthsLoaded < 4 AND wageRate.ProjectionAdjusted04 != fs.ProjectionAdjusted04) OR + (@MonthsLoaded < 5 AND wageRate.ProjectionAdjusted05 != fs.ProjectionAdjusted05) OR + (@MonthsLoaded < 6 AND wageRate.ProjectionAdjusted06 != fs.ProjectionAdjusted06) OR + (@MonthsLoaded < 7 AND wageRate.ProjectionAdjusted07 != fs.ProjectionAdjusted07) OR + (@MonthsLoaded < 8 AND wageRate.ProjectionAdjusted08 != fs.ProjectionAdjusted08) OR + (@MonthsLoaded < 9 AND wageRate.ProjectionAdjusted09 != fs.ProjectionAdjusted09) OR + (@MonthsLoaded < 10 AND wageRate.ProjectionAdjusted10 != fs.ProjectionAdjusted10) OR + (@MonthsLoaded < 11 AND wageRate.ProjectionAdjusted11 != fs.ProjectionAdjusted11) OR + (@MonthsLoaded < 12 AND wageRate.ProjectionAdjusted12 != fs.ProjectionAdjusted12) OR + wageRate.ProjectionWageRateLockType != 4 + OR + wageRate.InitialBudget01 != fs.InitialBudget01 OR + wageRate.InitialBudget02 != fs.InitialBudget02 OR + wageRate.InitialBudget03 != fs.InitialBudget03 OR + wageRate.InitialBudget04 != fs.InitialBudget04 OR + wageRate.InitialBudget05 != fs.InitialBudget05 OR + wageRate.InitialBudget06 != fs.InitialBudget06 OR + wageRate.InitialBudget07 != fs.InitialBudget07 OR + wageRate.InitialBudget08 != fs.InitialBudget08 OR + wageRate.InitialBudget09 != fs.InitialBudget09 OR + wageRate.InitialBudget10 != fs.InitialBudget10 OR + wageRate.InitialBudget11 != fs.InitialBudget11 OR + wageRate.InitialBudget12 != fs.InitialBudget12 OR + (@MonthsLoaded < 1 AND wageRate.InitialProjection01 != fs.InitialProjection01) OR + (@MonthsLoaded < 2 AND wageRate.InitialProjection02 != fs.InitialProjection02) OR + (@MonthsLoaded < 3 AND wageRate.InitialProjection03 != fs.InitialProjection03) OR + (@MonthsLoaded < 4 AND wageRate.InitialProjection04 != fs.InitialProjection04) OR + (@MonthsLoaded < 5 AND wageRate.InitialProjection05 != fs.InitialProjection05) OR + (@MonthsLoaded < 6 AND wageRate.InitialProjection06 != fs.InitialProjection06) OR + (@MonthsLoaded < 7 AND wageRate.InitialProjection07 != fs.InitialProjection07) OR + (@MonthsLoaded < 8 AND wageRate.InitialProjection08 != fs.InitialProjection08) OR + (@MonthsLoaded < 9 AND wageRate.InitialProjection09 != fs.InitialProjection09) OR + (@MonthsLoaded < 10 AND wageRate.InitialProjection10 != fs.InitialProjection10) OR + (@MonthsLoaded < 11 AND wageRate.InitialProjection11 != fs.InitialProjection11) OR + (@MonthsLoaded < 12 AND wageRate.InitialProjection12 != fs.InitialProjection12) + + + + ------------------------------------------------------------------------ + -- Update all variable records to 0 where department and jobcode is in Roster -- (corresponds to line 1382 in rollback - was 3 updates before) + ------------------------------------------------------------------------ + UPDATE fs + SET + InitialBudgetHours01 = 0, InitialBudgetHours02 = 0, InitialBudgetHours03 = 0, InitialBudgetHours04 = 0, InitialBudgetHours05 = 0, InitialBudgetHours06 = 0, + InitialBudgetHours07 = 0, InitialBudgetHours08 = 0, InitialBudgetHours09 = 0, InitialBudgetHours10 = 0, InitialBudgetHours11 = 0, InitialBudgetHours12 = 0, + InitialProjectionHours01 = CASE WHEN @MonthsLoaded >= 1 THEN fs.InitialProjectionHours01 ELSE 0 END, + InitialProjectionHours02 = CASE WHEN @MonthsLoaded >= 2 THEN fs.InitialProjectionHours02 ELSE 0 END, + InitialProjectionHours03 = CASE WHEN @MonthsLoaded >= 3 THEN fs.InitialProjectionHours03 ELSE 0 END, + InitialProjectionHours04 = CASE WHEN @MonthsLoaded >= 4 THEN fs.InitialProjectionHours04 ELSE 0 END, + InitialProjectionHours05 = CASE WHEN @MonthsLoaded >= 5 THEN fs.InitialProjectionHours05 ELSE 0 END, + InitialProjectionHours06 = CASE WHEN @MonthsLoaded >= 6 THEN fs.InitialProjectionHours06 ELSE 0 END, + InitialProjectionHours07 = CASE WHEN @MonthsLoaded >= 7 THEN fs.InitialProjectionHours07 ELSE 0 END, + InitialProjectionHours08 = CASE WHEN @MonthsLoaded >= 8 THEN fs.InitialProjectionHours08 ELSE 0 END, + InitialProjectionHours09 = CASE WHEN @MonthsLoaded >= 9 THEN fs.InitialProjectionHours09 ELSE 0 END, + InitialProjectionHours10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.InitialProjectionHours10 ELSE 0 END, + InitialProjectionHours11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.InitialProjectionHours11 ELSE 0 END, + InitialProjectionHours12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.InitialProjectionHours12 ELSE 0 END, + TargetAdjustedHours01 = 0, TargetAdjustedHours02 = 0, TargetAdjustedHours03 = 0, TargetAdjustedHours04 = 0, TargetAdjustedHours05 = 0, TargetAdjustedHours06 = 0, + TargetAdjustedHours07 = 0, TargetAdjustedHours08 = 0, TargetAdjustedHours09 = 0, TargetAdjustedHours10 = 0, TargetAdjustedHours11 = 0, TargetAdjustedHours12 = 0, + BudgetAdjustedHours01 = 0, BudgetAdjustedHours02 = 0, BudgetAdjustedHours03 = 0, BudgetAdjustedHours04 = 0, BudgetAdjustedHours05 = 0, BudgetAdjustedHours06 = 0, + BudgetAdjustedHours07 = 0, BudgetAdjustedHours08 = 0, BudgetAdjustedHours09 = 0, BudgetAdjustedHours10 = 0, BudgetAdjustedHours11 = 0, BudgetAdjustedHours12 = 0, + ProjectionAdjustedHours01 = CASE WHEN @MonthsLoaded >= 1 THEN ProjectionAdjustedHours01 ELSE 0 END, + ProjectionAdjustedHours02 = CASE WHEN @MonthsLoaded >= 2 THEN ProjectionAdjustedHours02 ELSE 0 END, + ProjectionAdjustedHours03 = CASE WHEN @MonthsLoaded >= 3 THEN ProjectionAdjustedHours03 ELSE 0 END, + ProjectionAdjustedHours04 = CASE WHEN @MonthsLoaded >= 4 THEN ProjectionAdjustedHours04 ELSE 0 END, + ProjectionAdjustedHours05 = CASE WHEN @MonthsLoaded >= 5 THEN ProjectionAdjustedHours05 ELSE 0 END, + ProjectionAdjustedHours06 = CASE WHEN @MonthsLoaded >= 6 THEN ProjectionAdjustedHours06 ELSE 0 END, + ProjectionAdjustedHours07 = CASE WHEN @MonthsLoaded >= 7 THEN ProjectionAdjustedHours07 ELSE 0 END, + ProjectionAdjustedHours08 = CASE WHEN @MonthsLoaded >= 8 THEN ProjectionAdjustedHours08 ELSE 0 END, + ProjectionAdjustedHours09 = CASE WHEN @MonthsLoaded >= 9 THEN ProjectionAdjustedHours09 ELSE 0 END, + ProjectionAdjustedHours10 = CASE WHEN @MonthsLoaded >= 10 THEN ProjectionAdjustedHours10 ELSE 0 END, + ProjectionAdjustedHours11 = CASE WHEN @MonthsLoaded >= 11 THEN ProjectionAdjustedHours11 ELSE 0 END, + ProjectionAdjustedHours12 = CASE WHEN @MonthsLoaded >= 12 THEN ProjectionAdjustedHours12 ELSE 0 END, + TargetHoursLockFlag = 1, + TargetHoursLockType = 4, + BudgetHoursLockFlag = 1, + BudgetHoursLockType = 4, + ProjectionHoursLockFlag = 1, + ProjectionHoursLockType = 4, + + InitialBudgetDollars01 = 0, InitialBudgetDollars02 = 0, InitialBudgetDollars03 = 0, InitialBudgetDollars04 = 0, InitialBudgetDollars05 = 0, InitialBudgetDollars06 = 0, + InitialBudgetDollars07 = 0, InitialBudgetDollars08 = 0, InitialBudgetDollars09 = 0, InitialBudgetDollars10 = 0, InitialBudgetDollars11 = 0, InitialBudgetDollars12 = 0, + InitialProjectionDollars01 = CASE WHEN @MonthsLoaded >= 1 THEN fs.InitialProjectionDollars01 ELSE 0 END, + InitialProjectionDollars02 = CASE WHEN @MonthsLoaded >= 2 THEN fs.InitialProjectionDollars02 ELSE 0 END, + InitialProjectionDollars03 = CASE WHEN @MonthsLoaded >= 3 THEN fs.InitialProjectionDollars03 ELSE 0 END, + InitialProjectionDollars04 = CASE WHEN @MonthsLoaded >= 4 THEN fs.InitialProjectionDollars04 ELSE 0 END, + InitialProjectionDollars05 = CASE WHEN @MonthsLoaded >= 5 THEN fs.InitialProjectionDollars05 ELSE 0 END, + InitialProjectionDollars06 = CASE WHEN @MonthsLoaded >= 6 THEN fs.InitialProjectionDollars06 ELSE 0 END, + InitialProjectionDollars07 = CASE WHEN @MonthsLoaded >= 7 THEN fs.InitialProjectionDollars07 ELSE 0 END, + InitialProjectionDollars08 = CASE WHEN @MonthsLoaded >= 8 THEN fs.InitialProjectionDollars08 ELSE 0 END, + InitialProjectionDollars09 = CASE WHEN @MonthsLoaded >= 9 THEN fs.InitialProjectionDollars09 ELSE 0 END, + InitialProjectionDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.InitialProjectionDollars10 ELSE 0 END, + InitialProjectionDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.InitialProjectionDollars11 ELSE 0 END, + InitialProjectionDollars12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.InitialProjectionDollars12 ELSE 0 END, + TargetAdjustedDollars01 = 0, TargetAdjustedDollars02 = 0, TargetAdjustedDollars03 = 0, TargetAdjustedDollars04 = 0, TargetAdjustedDollars05 = 0, TargetAdjustedDollars06 = 0, + TargetAdjustedDollars07 = 0, TargetAdjustedDollars08 = 0, TargetAdjustedDollars09 = 0, TargetAdjustedDollars10 = 0, TargetAdjustedDollars11 = 0, TargetAdjustedDollars12 = 0, + BudgetAdjustedDollars01 = 0, BudgetAdjustedDollars02 = 0, BudgetAdjustedDollars03 = 0, BudgetAdjustedDollars04 = 0, BudgetAdjustedDollars05 = 0, BudgetAdjustedDollars06 = 0, + BudgetAdjustedDollars07 = 0, BudgetAdjustedDollars08 = 0, BudgetAdjustedDollars09 = 0, BudgetAdjustedDollars10 = 0, BudgetAdjustedDollars11 = 0, BudgetAdjustedDollars12 = 0, + ProjectionAdjustedDollars01 = CASE WHEN @MonthsLoaded >= 1 THEN ProjectionAdjustedDollars01 ELSE 0 END, + ProjectionAdjustedDollars02 = CASE WHEN @MonthsLoaded >= 2 THEN ProjectionAdjustedDollars02 ELSE 0 END, + ProjectionAdjustedDollars03 = CASE WHEN @MonthsLoaded >= 3 THEN ProjectionAdjustedDollars03 ELSE 0 END, + ProjectionAdjustedDollars04 = CASE WHEN @MonthsLoaded >= 4 THEN ProjectionAdjustedDollars04 ELSE 0 END, + ProjectionAdjustedDollars05 = CASE WHEN @MonthsLoaded >= 5 THEN ProjectionAdjustedDollars05 ELSE 0 END, + ProjectionAdjustedDollars06 = CASE WHEN @MonthsLoaded >= 6 THEN ProjectionAdjustedDollars06 ELSE 0 END, + ProjectionAdjustedDollars07 = CASE WHEN @MonthsLoaded >= 7 THEN ProjectionAdjustedDollars07 ELSE 0 END, + ProjectionAdjustedDollars08 = CASE WHEN @MonthsLoaded >= 8 THEN ProjectionAdjustedDollars08 ELSE 0 END, + ProjectionAdjustedDollars09 = CASE WHEN @MonthsLoaded >= 9 THEN ProjectionAdjustedDollars09 ELSE 0 END, + ProjectionAdjustedDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN ProjectionAdjustedDollars10 ELSE 0 END, + ProjectionAdjustedDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN ProjectionAdjustedDollars11 ELSE 0 END, + ProjectionAdjustedDollars12 = CASE WHEN @MonthsLoaded >= 12 THEN ProjectionAdjustedDollars12 ELSE 0 END, + TargetDollarsLockFlag = 1, + TargetDollarsLockType = 4, + BudgetDollarsLockFlag = 1, + BudgetDollarsLockType = 4, + ProjectionDollarsLockFlag = 1, + ProjectionDollarsLockType = 4, + + InitialBudgetFTEs01 = 0, InitialBudgetFTEs02 = 0, InitialBudgetFTEs03 = 0, InitialBudgetFTEs04 = 0, InitialBudgetFTEs05 = 0, InitialBudgetFTEs06 = 0, + InitialBudgetFTEs07 = 0, InitialBudgetFTEs08 = 0, InitialBudgetFTEs09 = 0, InitialBudgetFTEs10 = 0, InitialBudgetFTEs11 = 0, InitialBudgetFTEs12 = 0, + InitialProjectionFTEs01 = CASE WHEN @MonthsLoaded >= 1 THEN fs.InitialProjectionFTEs01 ELSE 0 END, + InitialProjectionFTEs02 = CASE WHEN @MonthsLoaded >= 2 THEN fs.InitialProjectionFTEs02 ELSE 0 END, + InitialProjectionFTEs03 = CASE WHEN @MonthsLoaded >= 3 THEN fs.InitialProjectionFTEs03 ELSE 0 END, + InitialProjectionFTEs04 = CASE WHEN @MonthsLoaded >= 4 THEN fs.InitialProjectionFTEs04 ELSE 0 END, + InitialProjectionFTEs05 = CASE WHEN @MonthsLoaded >= 5 THEN fs.InitialProjectionFTEs05 ELSE 0 END, + InitialProjectionFTEs06 = CASE WHEN @MonthsLoaded >= 6 THEN fs.InitialProjectionFTEs06 ELSE 0 END, + InitialProjectionFTEs07 = CASE WHEN @MonthsLoaded >= 7 THEN fs.InitialProjectionFTEs07 ELSE 0 END, + InitialProjectionFTEs08 = CASE WHEN @MonthsLoaded >= 8 THEN fs.InitialProjectionFTEs08 ELSE 0 END, + InitialProjectionFTEs09 = CASE WHEN @MonthsLoaded >= 9 THEN fs.InitialProjectionFTEs09 ELSE 0 END, + InitialProjectionFTEs10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.InitialProjectionFTEs10 ELSE 0 END, + InitialProjectionFTEs11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.InitialProjectionFTEs11 ELSE 0 END, + InitialProjectionFTEs12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.InitialProjectionFTEs12 ELSE 0 END, + TargetAdjustedFTEs01 = 0, TargetAdjustedFTEs02 = 0, TargetAdjustedFTEs03 = 0, TargetAdjustedFTEs04 = 0, TargetAdjustedFTEs05 = 0, TargetAdjustedFTEs06 = 0, + TargetAdjustedFTEs07 = 0, TargetAdjustedFTEs08 = 0, TargetAdjustedFTEs09 = 0, TargetAdjustedFTEs10 = 0, TargetAdjustedFTEs11 = 0, TargetAdjustedFTEs12 = 0, + BudgetAdjustedFTEs01 = 0, BudgetAdjustedFTEs02 = 0, BudgetAdjustedFTEs03 = 0, BudgetAdjustedFTEs04 = 0, BudgetAdjustedFTEs05 = 0, BudgetAdjustedFTEs06 = 0, + BudgetAdjustedFTEs07 = 0, BudgetAdjustedFTEs08 = 0, BudgetAdjustedFTEs09 = 0, BudgetAdjustedFTEs10 = 0, BudgetAdjustedFTEs11 = 0, BudgetAdjustedFTEs12 = 0, + ProjectionAdjustedFTEs01 = CASE WHEN @MonthsLoaded >= 1 THEN ProjectionAdjustedFTEs01 ELSE 0 END, + ProjectionAdjustedFTEs02 = CASE WHEN @MonthsLoaded >= 2 THEN ProjectionAdjustedFTEs02 ELSE 0 END, + ProjectionAdjustedFTEs03 = CASE WHEN @MonthsLoaded >= 3 THEN ProjectionAdjustedFTEs03 ELSE 0 END, + ProjectionAdjustedFTEs04 = CASE WHEN @MonthsLoaded >= 4 THEN ProjectionAdjustedFTEs04 ELSE 0 END, + ProjectionAdjustedFTEs05 = CASE WHEN @MonthsLoaded >= 5 THEN ProjectionAdjustedFTEs05 ELSE 0 END, + ProjectionAdjustedFTEs06 = CASE WHEN @MonthsLoaded >= 6 THEN ProjectionAdjustedFTEs06 ELSE 0 END, + ProjectionAdjustedFTEs07 = CASE WHEN @MonthsLoaded >= 7 THEN ProjectionAdjustedFTEs07 ELSE 0 END, + ProjectionAdjustedFTEs08 = CASE WHEN @MonthsLoaded >= 8 THEN ProjectionAdjustedFTEs08 ELSE 0 END, + ProjectionAdjustedFTEs09 = CASE WHEN @MonthsLoaded >= 9 THEN ProjectionAdjustedFTEs09 ELSE 0 END, + ProjectionAdjustedFTEs10 = CASE WHEN @MonthsLoaded >= 10 THEN ProjectionAdjustedFTEs10 ELSE 0 END, + ProjectionAdjustedFTEs11 = CASE WHEN @MonthsLoaded >= 11 THEN ProjectionAdjustedFTEs11 ELSE 0 END, + ProjectionAdjustedFTEs12 = CASE WHEN @MonthsLoaded >= 12 THEN ProjectionAdjustedFTEs12 ELSE 0 END, + TargetFTEsLockFlag = 1, + TargetFTEsLockType = 4, + BudgetFTEsLockFlag = 1, + BudgetFTEsLockType = 4, + ProjectionFTEsLockFlag = 1, + ProjectionFTEsLockType = 4 + FROM [fp].[Staffing] fs + INNER JOIN #tmpRosterRolledUp rb ON + fs.JobCodeID = rb.JobCodeID + AND fs.DepartmentID = rb.DepartmentID + AND fs.EntityID = rb.EntityID + WHERE fs.BudgetConfigID = @BudgetConfigID + AND fs.VariabilityID = 2 + AND ( + InitialBudgetHours01 != 0 OR InitialBudgetHours02 != 0 OR InitialBudgetHours03 != 0 OR InitialBudgetHours04 != 0 OR InitialBudgetHours05 != 0 OR InitialBudgetHours06 != 0 OR + InitialBudgetHours07 != 0 OR InitialBudgetHours08 != 0 OR InitialBudgetHours09 != 0 OR InitialBudgetHours10 != 0 OR InitialBudgetHours11 != 0 OR InitialBudgetHours12 != 0 OR + (@MonthsLoaded >= 1 AND InitialProjectionHours01 != 0) OR + (@MonthsLoaded >= 2 AND InitialProjectionHours02 != 0) OR + (@MonthsLoaded >= 3 AND InitialProjectionHours03 != 0) OR + (@MonthsLoaded >= 4 AND InitialProjectionHours04 != 0) OR + (@MonthsLoaded >= 5 AND InitialProjectionHours05 != 0) OR + (@MonthsLoaded >= 6 AND InitialProjectionHours06 != 0) OR + (@MonthsLoaded >= 7 AND InitialProjectionHours07 != 0) OR + (@MonthsLoaded >= 8 AND InitialProjectionHours08 != 0) OR + (@MonthsLoaded >= 9 AND InitialProjectionHours09 != 0) OR + (@MonthsLoaded >= 10 AND InitialProjectionHours10 != 0) OR + (@MonthsLoaded >= 11 AND InitialProjectionHours11 != 0) OR + (@MonthsLoaded >= 12 AND InitialProjectionHours12 != 0) OR + TargetAdjustedHours01 != 0 OR TargetAdjustedHours02 != 0 OR TargetAdjustedHours03 != 0 OR TargetAdjustedHours04 != 0 OR TargetAdjustedHours05 != 0 OR TargetAdjustedHours06 != 0 OR + TargetAdjustedHours07 != 0 OR TargetAdjustedHours08 != 0 OR TargetAdjustedHours09 != 0 OR TargetAdjustedHours10 != 0 OR TargetAdjustedHours11 != 0 OR TargetAdjustedHours12 != 0 OR + BudgetAdjustedHours01 != 0 OR BudgetAdjustedHours02 != 0 OR BudgetAdjustedHours03 != 0 OR BudgetAdjustedHours04 != 0 OR BudgetAdjustedHours05 != 0 OR BudgetAdjustedHours06 != 0 OR + BudgetAdjustedHours07 != 0 OR BudgetAdjustedHours08 != 0 OR BudgetAdjustedHours09 != 0 OR BudgetAdjustedHours10 != 0 OR BudgetAdjustedHours11 != 0 OR BudgetAdjustedHours12 != 0 OR + (@MonthsLoaded >= 1 AND ProjectionAdjustedHours01 != 0) OR + (@MonthsLoaded >= 2 AND ProjectionAdjustedHours02 != 0) OR + (@MonthsLoaded >= 3 AND ProjectionAdjustedHours03 != 0) OR + (@MonthsLoaded >= 4 AND ProjectionAdjustedHours04 != 0) OR + (@MonthsLoaded >= 5 AND ProjectionAdjustedHours05 != 0) OR + (@MonthsLoaded >= 6 AND ProjectionAdjustedHours06 != 0) OR + (@MonthsLoaded >= 7 AND ProjectionAdjustedHours07 != 0) OR + (@MonthsLoaded >= 8 AND ProjectionAdjustedHours08 != 0) OR + (@MonthsLoaded >= 9 AND ProjectionAdjustedHours09 != 0) OR + (@MonthsLoaded >= 10 AND ProjectionAdjustedHours10 != 0) OR + (@MonthsLoaded >= 11 AND ProjectionAdjustedHours11 != 0) OR + (@MonthsLoaded >= 12 AND ProjectionAdjustedHours12 != 0) OR + TargetHoursLockFlag != 1 OR + TargetHoursLockType != 4 OR + BudgetHoursLockFlag != 1 OR + BudgetHoursLockType != 4 OR + ProjectionHoursLockFlag != 1 OR + ProjectionHoursLockType != 4 + ) + + + ------------------------------------------------------------ + -- Update original values and manager values where needed -- (corresponds to line 1488 in rollback) + ------------------------------------------------------------ + -- I separated hours/dollars/ftes out into separate statements rather than have a big giant WHERE AND OR clause, feel free to doubt my choices + -- Update the baseline if it hasn't been yet. + UPDATE fs + SET + fs.InitialBudgetHours01 = fs.TargetAdjustedHours01, fs.InitialBudgetHours02 = fs.TargetAdjustedHours02, fs.InitialBudgetHours03 = fs.TargetAdjustedHours03, + fs.InitialBudgetHours04 = fs.TargetAdjustedHours04, fs.InitialBudgetHours05 = fs.TargetAdjustedHours05, fs.InitialBudgetHours06 = fs.TargetAdjustedHours06, + fs.InitialBudgetHours07 = fs.TargetAdjustedHours07, fs.InitialBudgetHours08 = fs.TargetAdjustedHours08, fs.InitialBudgetHours09 = fs.TargetAdjustedHours09, + fs.InitialBudgetHours10 = fs.TargetAdjustedHours10, fs.InitialBudgetHours11 = fs.TargetAdjustedHours11, fs.InitialBudgetHours12 = fs.TargetAdjustedHours12, + InitialProjectionHours01 = CASE WHEN @MonthsLoaded >= 1 THEN fs.InitialProjectionHours01 ELSE fs.ProjectionAdjustedHours01 END, + InitialProjectionHours02 = CASE WHEN @MonthsLoaded >= 2 THEN fs.InitialProjectionHours02 ELSE fs.ProjectionAdjustedHours02 END, + InitialProjectionHours03 = CASE WHEN @MonthsLoaded >= 3 THEN fs.InitialProjectionHours03 ELSE fs.ProjectionAdjustedHours03 END, + InitialProjectionHours04 = CASE WHEN @MonthsLoaded >= 4 THEN fs.InitialProjectionHours04 ELSE fs.ProjectionAdjustedHours04 END, + InitialProjectionHours05 = CASE WHEN @MonthsLoaded >= 5 THEN fs.InitialProjectionHours05 ELSE fs.ProjectionAdjustedHours05 END, + InitialProjectionHours06 = CASE WHEN @MonthsLoaded >= 6 THEN fs.InitialProjectionHours06 ELSE fs.ProjectionAdjustedHours06 END, + InitialProjectionHours07 = CASE WHEN @MonthsLoaded >= 7 THEN fs.InitialProjectionHours07 ELSE fs.ProjectionAdjustedHours07 END, + InitialProjectionHours08 = CASE WHEN @MonthsLoaded >= 8 THEN fs.InitialProjectionHours08 ELSE fs.ProjectionAdjustedHours08 END, + InitialProjectionHours09 = CASE WHEN @MonthsLoaded >= 9 THEN fs.InitialProjectionHours09 ELSE fs.ProjectionAdjustedHours09 END, + InitialProjectionHours10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.InitialProjectionHours10 ELSE fs.ProjectionAdjustedHours10 END, + InitialProjectionHours11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.InitialProjectionHours11 ELSE fs.ProjectionAdjustedHours11 END, + InitialProjectionHours12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.InitialProjectionHours12 ELSE fs.ProjectionAdjustedHours12 END + FROM [fp].[Staffing] fs + INNER JOIN #tmpRosterRolledUp Filter ON + fs.DepartmentID = Filter.DepartmentID + AND fs.JobCodeID = Filter.JobCodeID + AND fs.PayCodeGroupID = Filter.PayCodeGroupID + AND fs.EntityID = Filter.EntityID + WHERE TargetHoursLockFlag = 4 + AND ProjectionHoursLockFlag = 4 + -- Check to see if there's an initial budget already defined, if there's not, set it, if there is, ignore it. + AND (InitialBudgetHours01 = 0 AND InitialBudgetHours02 = 0 AND InitialBudgetHours03 = 0 AND InitialBudgetHours04 = 0 AND InitialBudgetHours05 = 0 AND InitialBudgetHours06 = 0 AND + InitialBudgetHours07 = 0 AND InitialBudgetHours08 = 0 AND InitialBudgetHours09 = 0 AND InitialBudgetHours10 = 0 AND InitialBudgetHours11 = 0 AND InitialBudgetHours12 = 0 ) + AND ( + (@MonthsLoaded < 1 AND InitialProjectionHours01 = 0) + AND (@MonthsLoaded < 2 AND InitialProjectionHours02 = 0) + AND (@MonthsLoaded < 3 AND InitialProjectionHours03 = 0) + AND (@MonthsLoaded < 4 AND InitialProjectionHours04 = 0) + AND (@MonthsLoaded < 5 AND InitialProjectionHours05 = 0) + AND (@MonthsLoaded < 6 AND InitialProjectionHours06 = 0) + AND (@MonthsLoaded < 7 AND InitialProjectionHours07 = 0) + AND (@MonthsLoaded < 8 AND InitialProjectionHours08 = 0) + AND (@MonthsLoaded < 9 AND InitialProjectionHours09 = 0) + AND (@MonthsLoaded < 10 AND InitialProjectionHours10 = 0) + AND (@MonthsLoaded < 11 AND InitialProjectionHours11 = 0) + AND (@MonthsLoaded < 12 AND InitialProjectionHours12 = 0) + ) AND ( + (@MonthsLoaded < 1 AND ProjectionAdjustedHours01 != 0) OR + (@MonthsLoaded < 2 AND ProjectionAdjustedHours02 != 0) OR + (@MonthsLoaded < 3 AND ProjectionAdjustedHours03 != 0) OR + (@MonthsLoaded < 4 AND ProjectionAdjustedHours04 != 0) OR + (@MonthsLoaded < 5 AND ProjectionAdjustedHours05 != 0) OR + (@MonthsLoaded < 6 AND ProjectionAdjustedHours06 != 0) OR + (@MonthsLoaded < 7 AND ProjectionAdjustedHours07 != 0) OR + (@MonthsLoaded < 8 AND ProjectionAdjustedHours08 != 0) OR + (@MonthsLoaded < 9 AND ProjectionAdjustedHours09 != 0) OR + (@MonthsLoaded < 10 AND ProjectionAdjustedHours10 != 0) OR + (@MonthsLoaded < 11 AND ProjectionAdjustedHours11 != 0) OR + (@MonthsLoaded < 12 AND ProjectionAdjustedHours12 != 0) OR + BudgetAdjustedHours01 != 0 OR BudgetAdjustedHours02 != 0 OR BudgetAdjustedHours03 != 0 OR BudgetAdjustedHours04 != 0 OR BudgetAdjustedHours05 != 0 OR + BudgetAdjustedHours06 != 0 OR BudgetAdjustedHours07 != 0 OR BudgetAdjustedHours08 != 0 OR BudgetAdjustedHours09 != 0 OR BudgetAdjustedHours10 != 0 OR + BudgetAdjustedHours11 != 0 OR BudgetAdjustedHours12 != 0 + ) + + AND fs.BudgetConfigID = @BudgetConfigID + + -- Update the Dollar baseline if it hasn't been yet. + UPDATE fs + SET + fs.InitialBudgetDollars01 = fs.TargetAdjustedDollars01, fs.InitialBudgetDollars02 = fs.TargetAdjustedDollars02, fs.InitialBudgetDollars03 = fs.TargetAdjustedDollars03, + fs.InitialBudgetDollars04 = fs.TargetAdjustedDollars04, fs.InitialBudgetDollars05 = fs.TargetAdjustedDollars05, fs.InitialBudgetDollars06 = fs.TargetAdjustedDollars06, + fs.InitialBudgetDollars07 = fs.TargetAdjustedDollars07, fs.InitialBudgetDollars08 = fs.TargetAdjustedDollars08, fs.InitialBudgetDollars09 = fs.TargetAdjustedDollars09, + fs.InitialBudgetDollars10 = fs.TargetAdjustedDollars10, fs.InitialBudgetDollars11 = fs.TargetAdjustedDollars11, fs.InitialBudgetDollars12 = fs.TargetAdjustedDollars12, + InitialProjectionDollars01 = CASE WHEN @MonthsLoaded >= 1 THEN fs.InitialProjectionDollars01 ELSE fs.ProjectionAdjustedDollars01 END, + InitialProjectionDollars02 = CASE WHEN @MonthsLoaded >= 2 THEN fs.InitialProjectionDollars02 ELSE fs.ProjectionAdjustedDollars02 END, + InitialProjectionDollars03 = CASE WHEN @MonthsLoaded >= 3 THEN fs.InitialProjectionDollars03 ELSE fs.ProjectionAdjustedDollars03 END, + InitialProjectionDollars04 = CASE WHEN @MonthsLoaded >= 4 THEN fs.InitialProjectionDollars04 ELSE fs.ProjectionAdjustedDollars04 END, + InitialProjectionDollars05 = CASE WHEN @MonthsLoaded >= 5 THEN fs.InitialProjectionDollars05 ELSE fs.ProjectionAdjustedDollars05 END, + InitialProjectionDollars06 = CASE WHEN @MonthsLoaded >= 6 THEN fs.InitialProjectionDollars06 ELSE fs.ProjectionAdjustedDollars06 END, + InitialProjectionDollars07 = CASE WHEN @MonthsLoaded >= 7 THEN fs.InitialProjectionDollars07 ELSE fs.ProjectionAdjustedDollars07 END, + InitialProjectionDollars08 = CASE WHEN @MonthsLoaded >= 8 THEN fs.InitialProjectionDollars08 ELSE fs.ProjectionAdjustedDollars08 END, + InitialProjectionDollars09 = CASE WHEN @MonthsLoaded >= 9 THEN fs.InitialProjectionDollars09 ELSE fs.ProjectionAdjustedDollars09 END, + InitialProjectionDollars10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.InitialProjectionDollars10 ELSE fs.ProjectionAdjustedDollars10 END, + InitialProjectionDollars11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.InitialProjectionDollars11 ELSE fs.ProjectionAdjustedDollars11 END, + InitialProjectionDollars12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.InitialProjectionDollars12 ELSE fs.ProjectionAdjustedDollars12 END + FROM [fp].[Staffing] fs + INNER JOIN #tmpRosterRolledUp Filter ON + fs.DepartmentID = Filter.DepartmentID + AND fs.JobCodeID = Filter.JobCodeID + AND fs.PayCodeGroupID = Filter.PayCodeGroupID + AND fs.EntityID = Filter.EntityID + WHERE TargetDollarsLockFlag = 4 + AND ProjectionDollarsLockFlag = 4 + -- Check to see if there's an initial budget already defined, if there's not, set it, if there is, ignore it. + AND (InitialBudgetDollars01 = 0 AND InitialBudgetDollars02 = 0 AND InitialBudgetDollars03 = 0 AND InitialBudgetDollars04 = 0 AND InitialBudgetDollars05 = 0 AND InitialBudgetDollars06 = 0 AND + InitialBudgetDollars07 = 0 AND InitialBudgetDollars08 = 0 AND InitialBudgetDollars09 = 0 AND InitialBudgetDollars10 = 0 AND InitialBudgetDollars11 = 0 AND InitialBudgetDollars12 = 0 ) + AND ( + (@MonthsLoaded < 1 AND InitialProjectionDollars01 = 0) + AND (@MonthsLoaded < 2 AND InitialProjectionDollars02 = 0) + AND (@MonthsLoaded < 3 AND InitialProjectionDollars03 = 0) + AND (@MonthsLoaded < 4 AND InitialProjectionDollars04 = 0) + AND (@MonthsLoaded < 5 AND InitialProjectionDollars05 = 0) + AND (@MonthsLoaded < 6 AND InitialProjectionDollars06 = 0) + AND (@MonthsLoaded < 7 AND InitialProjectionDollars07 = 0) + AND (@MonthsLoaded < 8 AND InitialProjectionDollars08 = 0) + AND (@MonthsLoaded < 9 AND InitialProjectionDollars09 = 0) + AND (@MonthsLoaded < 10 AND InitialProjectionDollars10 = 0) + AND (@MonthsLoaded < 11 AND InitialProjectionDollars11 = 0) + AND (@MonthsLoaded < 12 AND InitialProjectionDollars12 = 0) + ) AND ( + (@MonthsLoaded < 1 AND ProjectionAdjustedDollars01 != 0) OR + (@MonthsLoaded < 2 AND ProjectionAdjustedDollars02 != 0) OR + (@MonthsLoaded < 3 AND ProjectionAdjustedDollars03 != 0) OR + (@MonthsLoaded < 4 AND ProjectionAdjustedDollars04 != 0) OR + (@MonthsLoaded < 5 AND ProjectionAdjustedDollars05 != 0) OR + (@MonthsLoaded < 6 AND ProjectionAdjustedDollars06 != 0) OR + (@MonthsLoaded < 7 AND ProjectionAdjustedDollars07 != 0) OR + (@MonthsLoaded < 8 AND ProjectionAdjustedDollars08 != 0) OR + (@MonthsLoaded < 9 AND ProjectionAdjustedDollars09 != 0) OR + (@MonthsLoaded < 10 AND ProjectionAdjustedDollars10 != 0) OR + (@MonthsLoaded < 11 AND ProjectionAdjustedDollars11 != 0) OR + (@MonthsLoaded < 12 AND ProjectionAdjustedDollars12 != 0) OR + BudgetAdjustedDollars01 != 0 OR BudgetAdjustedDollars02 != 0 OR BudgetAdjustedDollars03 != 0 OR BudgetAdjustedDollars04 != 0 OR BudgetAdjustedDollars05 != 0 OR + BudgetAdjustedDollars06 != 0 OR BudgetAdjustedDollars07 != 0 OR BudgetAdjustedDollars08 != 0 OR BudgetAdjustedDollars09 != 0 OR BudgetAdjustedDollars10 != 0 OR + BudgetAdjustedDollars11 != 0 OR BudgetAdjustedDollars12 != 0 + ) + AND fs.BudgetConfigID = @BudgetConfigID + + -- Update the FTE baseline if it hasn't been yet. + UPDATE fs + SET + fs.InitialBudgetFTEs01 = fs.TargetAdjustedFTEs01, fs.InitialBudgetFTEs02 = fs.TargetAdjustedFTEs02, fs.InitialBudgetFTEs03 = fs.TargetAdjustedFTEs03, + fs.InitialBudgetFTEs04 = fs.TargetAdjustedFTEs04, fs.InitialBudgetFTEs05 = fs.TargetAdjustedFTEs05, fs.InitialBudgetFTEs06 = fs.TargetAdjustedFTEs06, + fs.InitialBudgetFTEs07 = fs.TargetAdjustedFTEs07, fs.InitialBudgetFTEs08 = fs.TargetAdjustedFTEs08, fs.InitialBudgetFTEs09 = fs.TargetAdjustedFTEs09, + fs.InitialBudgetFTEs10 = fs.TargetAdjustedFTEs10, fs.InitialBudgetFTEs11 = fs.TargetAdjustedFTEs11, fs.InitialBudgetFTEs12 = fs.TargetAdjustedFTEs12, + InitialProjectionFTEs01 = CASE WHEN @MonthsLoaded >= 1 THEN fs.InitialProjectionFTEs01 ELSE fs.ProjectionAdjustedFTEs01 END, + InitialProjectionFTEs02 = CASE WHEN @MonthsLoaded >= 2 THEN fs.InitialProjectionFTEs02 ELSE fs.ProjectionAdjustedFTEs02 END, + InitialProjectionFTEs03 = CASE WHEN @MonthsLoaded >= 3 THEN fs.InitialProjectionFTEs03 ELSE fs.ProjectionAdjustedFTEs03 END, + InitialProjectionFTEs04 = CASE WHEN @MonthsLoaded >= 4 THEN fs.InitialProjectionFTEs04 ELSE fs.ProjectionAdjustedFTEs04 END, + InitialProjectionFTEs05 = CASE WHEN @MonthsLoaded >= 5 THEN fs.InitialProjectionFTEs05 ELSE fs.ProjectionAdjustedFTEs05 END, + InitialProjectionFTEs06 = CASE WHEN @MonthsLoaded >= 6 THEN fs.InitialProjectionFTEs06 ELSE fs.ProjectionAdjustedFTEs06 END, + InitialProjectionFTEs07 = CASE WHEN @MonthsLoaded >= 7 THEN fs.InitialProjectionFTEs07 ELSE fs.ProjectionAdjustedFTEs07 END, + InitialProjectionFTEs08 = CASE WHEN @MonthsLoaded >= 8 THEN fs.InitialProjectionFTEs08 ELSE fs.ProjectionAdjustedFTEs08 END, + InitialProjectionFTEs09 = CASE WHEN @MonthsLoaded >= 9 THEN fs.InitialProjectionFTEs09 ELSE fs.ProjectionAdjustedFTEs09 END, + InitialProjectionFTEs10 = CASE WHEN @MonthsLoaded >= 10 THEN fs.InitialProjectionFTEs10 ELSE fs.ProjectionAdjustedFTEs10 END, + InitialProjectionFTEs11 = CASE WHEN @MonthsLoaded >= 11 THEN fs.InitialProjectionFTEs11 ELSE fs.ProjectionAdjustedFTEs11 END, + InitialProjectionFTEs12 = CASE WHEN @MonthsLoaded >= 12 THEN fs.InitialProjectionFTEs12 ELSE fs.ProjectionAdjustedFTEs12 END + + FROM [fp].[Staffing] fs + INNER JOIN #tmpRosterRolledUp Filter ON + fs.DepartmentID = Filter.DepartmentID + AND fs.JobCodeID = Filter.JobCodeID + AND fs.PayCodeGroupID = Filter.PayCodeGroupID + AND fs.EntityID = Filter.EntityID + WHERE TargetFTEsLockFlag = 4 + AND ProjectionFTEsLockFlag = 4 + -- Check to see if there's an initial budget already defined, if there's not, set it, if there is, ignore it. + AND (InitialBudgetFTEs01 = 0 AND InitialBudgetFTEs02 = 0 AND InitialBudgetFTEs03 = 0 AND InitialBudgetFTEs04 = 0 AND InitialBudgetFTEs05 = 0 AND InitialBudgetFTEs06 = 0 AND + InitialBudgetFTEs07 = 0 AND InitialBudgetFTEs08 = 0 AND InitialBudgetFTEs09 = 0 AND InitialBudgetFTEs10 = 0 AND InitialBudgetFTEs11 = 0 AND InitialBudgetFTEs12 = 0 ) + AND ( + (@MonthsLoaded < 1 AND InitialProjectionFTEs01 = 0) + AND (@MonthsLoaded < 2 AND InitialProjectionFTEs02 = 0) + AND (@MonthsLoaded < 3 AND InitialProjectionFTEs03 = 0) + AND (@MonthsLoaded < 4 AND InitialProjectionFTEs04 = 0) + AND (@MonthsLoaded < 5 AND InitialProjectionFTEs05 = 0) + AND (@MonthsLoaded < 6 AND InitialProjectionFTEs06 = 0) + AND (@MonthsLoaded < 7 AND InitialProjectionFTEs07 = 0) + AND (@MonthsLoaded < 8 AND InitialProjectionFTEs08 = 0) + AND (@MonthsLoaded < 9 AND InitialProjectionFTEs09 = 0) + AND (@MonthsLoaded < 10 AND InitialProjectionFTEs10 = 0) + AND (@MonthsLoaded < 11 AND InitialProjectionFTEs11 = 0) + AND (@MonthsLoaded < 12 AND InitialProjectionFTEs12 = 0) + ) + AND ( (@MonthsLoaded < 1 AND ProjectionAdjustedFTEs01 != 0) OR + (@MonthsLoaded < 2 AND ProjectionAdjustedFTEs02 != 0) OR + (@MonthsLoaded < 3 AND ProjectionAdjustedFTEs03 != 0) OR + (@MonthsLoaded < 4 AND ProjectionAdjustedFTEs04 != 0) OR + (@MonthsLoaded < 5 AND ProjectionAdjustedFTEs05 != 0) OR + (@MonthsLoaded < 6 AND ProjectionAdjustedFTEs06 != 0) OR + (@MonthsLoaded < 7 AND ProjectionAdjustedFTEs07 != 0) OR + (@MonthsLoaded < 8 AND ProjectionAdjustedFTEs08 != 0) OR + (@MonthsLoaded < 9 AND ProjectionAdjustedFTEs09 != 0) OR + (@MonthsLoaded < 10 AND ProjectionAdjustedFTEs10 != 0) OR + (@MonthsLoaded < 11 AND ProjectionAdjustedFTEs11 != 0) OR + (@MonthsLoaded < 12 AND ProjectionAdjustedFTEs12 != 0) OR + BudgetAdjustedFTEs01 != 0 OR BudgetAdjustedFTEs02 != 0 OR BudgetAdjustedFTEs03 != 0 OR BudgetAdjustedFTEs04 != 0 OR BudgetAdjustedFTEs05 != 0 OR + BudgetAdjustedFTEs06 != 0 OR BudgetAdjustedFTEs07 != 0 OR BudgetAdjustedFTEs08 != 0 OR BudgetAdjustedFTEs09 != 0 OR BudgetAdjustedFTEs10 != 0 OR + BudgetAdjustedFTEs11 != 0 OR BudgetAdjustedFTEs12 != 0) + + AND fs.BudgetConfigID = @BudgetConfigID + + -------------------------------------------------------------------------------------------------------------------------------- + -- corresponds to line 1555 in rollback + -------------------------------------------------------------------------------------------------------------------------------- + UPDATE fs + SET + BudgetAdjustedHours01 = TargetAdjustedHours01, + BudgetAdjustedHours02 = TargetAdjustedHours02, + BudgetAdjustedHours03 = TargetAdjustedHours03, + BudgetAdjustedHours04 = TargetAdjustedHours04, + BudgetAdjustedHours05 = TargetAdjustedHours05, + BudgetAdjustedHours06 = TargetAdjustedHours06, + BudgetAdjustedHours07 = TargetAdjustedHours07, + BudgetAdjustedHours08 = TargetAdjustedHours08, + BudgetAdjustedHours09 = TargetAdjustedHours09, + BudgetAdjustedHours10 = TargetAdjustedHours10, + BudgetAdjustedHours11 = TargetAdjustedHours11, + BudgetAdjustedHours12 = TargetAdjustedHours12, + + BudgetAdjustedDollars01 = TargetAdjustedDollars01, + BudgetAdjustedDollars02 = TargetAdjustedDollars02, + BudgetAdjustedDollars03 = TargetAdjustedDollars03, + BudgetAdjustedDollars04 = TargetAdjustedDollars04, + BudgetAdjustedDollars05 = TargetAdjustedDollars05, + BudgetAdjustedDollars06 = TargetAdjustedDollars06, + BudgetAdjustedDollars07 = TargetAdjustedDollars07, + BudgetAdjustedDollars08 = TargetAdjustedDollars08, + BudgetAdjustedDollars09 = TargetAdjustedDollars09, + BudgetAdjustedDollars10 = TargetAdjustedDollars10, + BudgetAdjustedDollars11 = TargetAdjustedDollars11, + BudgetAdjustedDollars12 = TargetAdjustedDollars12, + + BudgetAdjustedFTEs01 = TargetAdjustedFTEs01, + BudgetAdjustedFTEs02 = TargetAdjustedFTEs02, + BudgetAdjustedFTEs03 = TargetAdjustedFTEs03, + BudgetAdjustedFTEs04 = TargetAdjustedFTEs04, + BudgetAdjustedFTEs05 = TargetAdjustedFTEs05, + BudgetAdjustedFTEs06 = TargetAdjustedFTEs06, + BudgetAdjustedFTEs07 = TargetAdjustedFTEs07, + BudgetAdjustedFTEs08 = TargetAdjustedFTEs08, + BudgetAdjustedFTEs09 = TargetAdjustedFTEs09, + BudgetAdjustedFTEs10 = TargetAdjustedFTEs10, + BudgetAdjustedFTEs11 = TargetAdjustedFTEs11, + BudgetAdjustedFTEs12 = TargetAdjustedFTEs12 + FROM [fp].[Staffing] fs + INNER JOIN #tmpRosterRolledUp Filter ON + fs.DepartmentID = Filter.DepartmentID + AND fs.JobCodeID = Filter.JobCodeID + AND fs.PayCodeGroupID = Filter.PayCodeGroupID + AND fs.EntityID = Filter.EntityID + WHERE fs.BudgetConfigID = @BudgetConfigID + AND ( + (TargetHoursLockType = 4 + AND ( + BudgetAdjustedHours01 != TargetAdjustedHours01 OR + BudgetAdjustedHours02 != TargetAdjustedHours02 OR + BudgetAdjustedHours03 != TargetAdjustedHours03 OR + BudgetAdjustedHours04 != TargetAdjustedHours04 OR + BudgetAdjustedHours05 != TargetAdjustedHours05 OR + BudgetAdjustedHours06 != TargetAdjustedHours06 OR + BudgetAdjustedHours07 != TargetAdjustedHours07 OR + BudgetAdjustedHours08 != TargetAdjustedHours08 OR + BudgetAdjustedHours09 != TargetAdjustedHours09 OR + BudgetAdjustedHours10 != TargetAdjustedHours10 OR + BudgetAdjustedHours11 != TargetAdjustedHours11 OR + BudgetAdjustedHours12 != TargetAdjustedHours12)) + OR + (TargetDollarsLockType = 4 + AND ( + BudgetAdjustedDollars01 != TargetAdjustedDollars01 OR + BudgetAdjustedDollars02 != TargetAdjustedDollars02 OR + BudgetAdjustedDollars03 != TargetAdjustedDollars03 OR + BudgetAdjustedDollars04 != TargetAdjustedDollars04 OR + BudgetAdjustedDollars05 != TargetAdjustedDollars05 OR + BudgetAdjustedDollars06 != TargetAdjustedDollars06 OR + BudgetAdjustedDollars07 != TargetAdjustedDollars07 OR + BudgetAdjustedDollars08 != TargetAdjustedDollars08 OR + BudgetAdjustedDollars09 != TargetAdjustedDollars09 OR + BudgetAdjustedDollars10 != TargetAdjustedDollars10 OR + BudgetAdjustedDollars11 != TargetAdjustedDollars11 OR + BudgetAdjustedDollars12 != TargetAdjustedDollars12)) + OR + (TargetFTEsLockType = 4 + AND ( + BudgetAdjustedFTEs01 != TargetAdjustedFTEs01 OR + BudgetAdjustedFTEs02 != TargetAdjustedFTEs02 OR + BudgetAdjustedFTEs03 != TargetAdjustedFTEs03 OR + BudgetAdjustedFTEs04 != TargetAdjustedFTEs04 OR + BudgetAdjustedFTEs05 != TargetAdjustedFTEs05 OR + BudgetAdjustedFTEs06 != TargetAdjustedFTEs06 OR + BudgetAdjustedFTEs07 != TargetAdjustedFTEs07 OR + BudgetAdjustedFTEs08 != TargetAdjustedFTEs08 OR + BudgetAdjustedFTEs09 != TargetAdjustedFTEs09 OR + BudgetAdjustedFTEs10 != TargetAdjustedFTEs10 OR + BudgetAdjustedFTEs11 != TargetAdjustedFTEs11 OR + BudgetAdjustedFTEs12 != TargetAdjustedFTEs12)) + ) + + + -- Lock any related PCG's that aren't in Roster, but contains a job code managed by roster + UPDATE fs + SET + TargetHoursLockFlag = 1, + TargetHoursLockType = 4, + TargetDollarsLockFlag = 1, + TargetDollarsLockType = 4, + TargetFTEsLockFlag = 1, + TargetFTEsLockType = 4, + ProjectionHoursLockFlag = 1, + ProjectionHoursLockType = 4, + ProjectionDollarsLockFlag = 1, + ProjectionDollarsLockType = 4, + ProjectionFTEsLockFlag = 1, + ProjectionFTEsLockType = 4 + FROM [fp].[Staffing] fs + INNER JOIN #tmpRosterRolledUp rb ON + fs.JobCodeID = rb.JobCodeID + AND fs.DepartmentID = rb.DepartmentID + AND fs.EntityID = rb.EntityID + WHERE fs.BudgetConfigID = @BudgetConfigID + AND ( + fs.TargetHoursLockFlag = 0 OR + fs.TargetDollarsLockFlag = 0 OR + fs.TargetFTEsLockFlag = 0 OR + fs.ProjectionHoursLockFlag = 0 OR + fs.ProjectionDollarsLockFlag = 0 OR + fs.ProjectionFTEsLockFlag = 0 + ) + + + -------------- + -- Clean Up -- + -------------- + DROP TABLE #tmpPaddedStaffingData + DROP TABLE #tmpRosterRolledUp + DROP TABLE #tmpHoursRatio + DROP TABLE #tmpEntity + DROP TABLE #Filter +GO + + +--------------------------------------------- + +-- fp.procUpdateBenefitRatesTrailing12 +CREATE PROCEDURE [fp].[procUpdateBenefitRatesTrailing12] + @EntityGroupConfigID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS +BEGIN + DECLARE @EntityGroupConfigGUID UNIQUEIDENTIFIER; + DECLARE @MonthsLoaded INT; + + SELECT @MonthsLoaded = MonthsLoaded, + @EntityGroupConfigGUID = EntityGroupConfigGUID + FROM [fp].[BudgetConfig] b + INNER JOIN [fp].[EntityGroupConfig] e ON b.BudgetConfigGUID = e.BudgetConfigGUID + WHERE e.EntityGroupConfigID = @EntityGroupConfigID + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality); + + SELECT + BenefitsID = fb.BenefitsID, + PriorYearActualValue01 = bh.PriorYearActualValue01, + PriorYearActualValue02 = bh.PriorYearActualValue02, + PriorYearActualValue03 = bh.PriorYearActualValue03, + PriorYearActualValue04 = bh.PriorYearActualValue04, + PriorYearActualValue05 = bh.PriorYearActualValue05, + PriorYearActualValue06 = bh.PriorYearActualValue06, + PriorYearActualValue07 = bh.PriorYearActualValue07, + PriorYearActualValue08 = bh.PriorYearActualValue08, + PriorYearActualValue09 = bh.PriorYearActualValue09, + PriorYearActualValue10 = bh.PriorYearActualValue10, + PriorYearActualValue11 = bh.PriorYearActualValue11, + PriorYearActualValue12 = bh.PriorYearActualValue12, + ActualYTDValue01 = bh.ActualYTDValue01, + ActualYTDValue02 = bh.ActualYTDValue02, + ActualYTDValue03 = bh.ActualYTDValue03, + ActualYTDValue04 = bh.ActualYTDValue04, + ActualYTDValue05 = bh.ActualYTDValue05, + ActualYTDValue06 = bh.ActualYTDValue06, + ActualYTDValue07 = bh.ActualYTDValue07, + ActualYTDValue08 = bh.ActualYTDValue08, + ActualYTDValue09 = bh.ActualYTDValue09, + ActualYTDValue10 = bh.ActualYTDValue10, + ActualYTDValue11 = bh.ActualYTDValue11, + ActualYTDValue12 = bh.ActualYTDValue12 + INTO #YearValues + FROM [fp].[FactBenefitsHistory] bh + INNER JOIN [fp].[FactBenefits] fb on bh.BenefitsID = fb.BenefitsID + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = fb.DepartmentID or ft.DepartmentID is null) + INNER JOIN [fp].[AccountFlexConfig] fc on fb.AccountID = fc.AccountID and fc.EntityGroupConfigGUID = @EntityGroupConfigGUID + WHERE 1=1 + AND fc.IsUsingTrailing12 = 1 + AND fb.EntityGroupConfigID = @EntityGroupConfigID + AND fb.UnitTypeID in + ( + 171, --Dollars per FTE + 170 --Percent of Salaries + ) + AND fc.FlexMethodClassName in ('FlexAccountBySalaries','FlexAccountByFTEs') + AND ( + bh.PriorYearActualValue01 <> 0 OR + bh.PriorYearActualValue02 <> 0 OR + bh.PriorYearActualValue03 <> 0 OR + bh.PriorYearActualValue04 <> 0 OR + bh.PriorYearActualValue05 <> 0 OR + bh.PriorYearActualValue06 <> 0 OR + bh.PriorYearActualValue07 <> 0 OR + bh.PriorYearActualValue08 <> 0 OR + bh.PriorYearActualValue09 <> 0 OR + bh.PriorYearActualValue10 <> 0 OR + bh.PriorYearActualValue11 <> 0 OR + bh.PriorYearActualValue12 <> 0 + ) + + UPDATE fb + SET + InitialBudget01 = CASE WHEN @MonthsLoaded < 1 THEN v.PriorYearActualValue01 ELSE ActualYTDValue01 END, + InitialBudget02 = CASE WHEN @MonthsLoaded < 2 THEN v.PriorYearActualValue02 ELSE ActualYTDValue02 END, + InitialBudget03 = CASE WHEN @MonthsLoaded < 3 THEN v.PriorYearActualValue03 ELSE ActualYTDValue03 END, + InitialBudget04 = CASE WHEN @MonthsLoaded < 4 THEN v.PriorYearActualValue04 ELSE ActualYTDValue04 END, + InitialBudget05 = CASE WHEN @MonthsLoaded < 5 THEN v.PriorYearActualValue05 ELSE ActualYTDValue05 END, + InitialBudget06 = CASE WHEN @MonthsLoaded < 6 THEN v.PriorYearActualValue06 ELSE ActualYTDValue06 END, + InitialBudget07 = CASE WHEN @MonthsLoaded < 7 THEN v.PriorYearActualValue07 ELSE ActualYTDValue07 END, + InitialBudget08 = CASE WHEN @MonthsLoaded < 8 THEN v.PriorYearActualValue08 ELSE ActualYTDValue08 END, + InitialBudget09 = CASE WHEN @MonthsLoaded < 9 THEN v.PriorYearActualValue09 ELSE ActualYTDValue09 END, + InitialBudget10 = CASE WHEN @MonthsLoaded < 10 THEN v.PriorYearActualValue10 ELSE ActualYTDValue10 END, + InitialBudget11 = CASE WHEN @MonthsLoaded < 11 THEN v.PriorYearActualValue11 ELSE ActualYTDValue11 END, + InitialBudget12 = CASE WHEN @MonthsLoaded < 12 THEN v.PriorYearActualValue12 ELSE ActualYTDValue12 END, + SampledBudget01 = CASE WHEN @MonthsLoaded < 1 THEN v.PriorYearActualValue01 ELSE ActualYTDValue01 END, + SampledBudget02 = CASE WHEN @MonthsLoaded < 2 THEN v.PriorYearActualValue02 ELSE ActualYTDValue02 END, + SampledBudget03 = CASE WHEN @MonthsLoaded < 3 THEN v.PriorYearActualValue03 ELSE ActualYTDValue03 END, + SampledBudget04 = CASE WHEN @MonthsLoaded < 4 THEN v.PriorYearActualValue04 ELSE ActualYTDValue04 END, + SampledBudget05 = CASE WHEN @MonthsLoaded < 5 THEN v.PriorYearActualValue05 ELSE ActualYTDValue05 END, + SampledBudget06 = CASE WHEN @MonthsLoaded < 6 THEN v.PriorYearActualValue06 ELSE ActualYTDValue06 END, + SampledBudget07 = CASE WHEN @MonthsLoaded < 7 THEN v.PriorYearActualValue07 ELSE ActualYTDValue07 END, + SampledBudget08 = CASE WHEN @MonthsLoaded < 8 THEN v.PriorYearActualValue08 ELSE ActualYTDValue08 END, + SampledBudget09 = CASE WHEN @MonthsLoaded < 9 THEN v.PriorYearActualValue09 ELSE ActualYTDValue09 END, + SampledBudget10 = CASE WHEN @MonthsLoaded < 10 THEN v.PriorYearActualValue10 ELSE ActualYTDValue10 END, + SampledBudget11 = CASE WHEN @MonthsLoaded < 11 THEN v.PriorYearActualValue11 ELSE ActualYTDValue11 END, + SampledBudget12 = CASE WHEN @MonthsLoaded < 12 THEN v.PriorYearActualValue12 ELSE ActualYTDValue12 END, + InitialProjection01 = CASE WHEN @MonthsLoaded < 1 THEN v.PriorYearActualValue01 ELSE ActualYTDValue01 END, + InitialProjection02 = CASE WHEN @MonthsLoaded < 2 THEN v.PriorYearActualValue02 ELSE ActualYTDValue02 END, + InitialProjection03 = CASE WHEN @MonthsLoaded < 3 THEN v.PriorYearActualValue03 ELSE ActualYTDValue03 END, + InitialProjection04 = CASE WHEN @MonthsLoaded < 4 THEN v.PriorYearActualValue04 ELSE ActualYTDValue04 END, + InitialProjection05 = CASE WHEN @MonthsLoaded < 5 THEN v.PriorYearActualValue05 ELSE ActualYTDValue05 END, + InitialProjection06 = CASE WHEN @MonthsLoaded < 6 THEN v.PriorYearActualValue06 ELSE ActualYTDValue06 END, + InitialProjection07 = CASE WHEN @MonthsLoaded < 7 THEN v.PriorYearActualValue07 ELSE ActualYTDValue07 END, + InitialProjection08 = CASE WHEN @MonthsLoaded < 8 THEN v.PriorYearActualValue08 ELSE ActualYTDValue08 END, + InitialProjection09 = CASE WHEN @MonthsLoaded < 9 THEN v.PriorYearActualValue09 ELSE ActualYTDValue09 END, + InitialProjection10 = CASE WHEN @MonthsLoaded < 10 THEN v.PriorYearActualValue10 ELSE ActualYTDValue10 END, + InitialProjection11 = CASE WHEN @MonthsLoaded < 11 THEN v.PriorYearActualValue11 ELSE ActualYTDValue11 END, + InitialProjection12 = CASE WHEN @MonthsLoaded < 12 THEN v.PriorYearActualValue12 ELSE ActualYTDValue12 END, + SampledProjection01 = CASE WHEN @MonthsLoaded < 1 THEN v.PriorYearActualValue01 ELSE ActualYTDValue01 END, + SampledProjection02 = CASE WHEN @MonthsLoaded < 2 THEN v.PriorYearActualValue02 ELSE ActualYTDValue02 END, + SampledProjection03 = CASE WHEN @MonthsLoaded < 3 THEN v.PriorYearActualValue03 ELSE ActualYTDValue03 END, + SampledProjection04 = CASE WHEN @MonthsLoaded < 4 THEN v.PriorYearActualValue04 ELSE ActualYTDValue04 END, + SampledProjection05 = CASE WHEN @MonthsLoaded < 5 THEN v.PriorYearActualValue05 ELSE ActualYTDValue05 END, + SampledProjection06 = CASE WHEN @MonthsLoaded < 6 THEN v.PriorYearActualValue06 ELSE ActualYTDValue06 END, + SampledProjection07 = CASE WHEN @MonthsLoaded < 7 THEN v.PriorYearActualValue07 ELSE ActualYTDValue07 END, + SampledProjection08 = CASE WHEN @MonthsLoaded < 8 THEN v.PriorYearActualValue08 ELSE ActualYTDValue08 END, + SampledProjection09 = CASE WHEN @MonthsLoaded < 9 THEN v.PriorYearActualValue09 ELSE ActualYTDValue09 END, + SampledProjection10 = CASE WHEN @MonthsLoaded < 10 THEN v.PriorYearActualValue10 ELSE ActualYTDValue10 END, + SampledProjection11 = CASE WHEN @MonthsLoaded < 11 THEN v.PriorYearActualValue11 ELSE ActualYTDValue11 END, + SampledProjection12 = CASE WHEN @MonthsLoaded < 12 THEN v.PriorYearActualValue12 ELSE ActualYTDValue12 END + FROM [fp].[FactBenefits] fb + INNER JOIN #YearValues v ON fb.BenefitsID = v.BenefitsID + + UPDATE fbb + SET + AdjustedValue01 = fb.InitialBudget01, + AdjustedValue02 = fb.InitialBudget02, + AdjustedValue03 = fb.InitialBudget03, + AdjustedValue04 = fb.InitialBudget04, + AdjustedValue05 = fb.InitialBudget05, + AdjustedValue06 = fb.InitialBudget06, + AdjustedValue07 = fb.InitialBudget07, + AdjustedValue08 = fb.InitialBudget08, + AdjustedValue09 = fb.InitialBudget09, + AdjustedValue10 = fb.InitialBudget10, + AdjustedValue11 = fb.InitialBudget11, + AdjustedValue12 = fb.InitialBudget12, + FlexedValue01 = fb.InitialBudget01, + FlexedValue02 = fb.InitialBudget02, + FlexedValue03 = fb.InitialBudget03, + FlexedValue04 = fb.InitialBudget04, + FlexedValue05 = fb.InitialBudget05, + FlexedValue06 = fb.InitialBudget06, + FlexedValue07 = fb.InitialBudget07, + FlexedValue08 = fb.InitialBudget08, + FlexedValue09 = fb.InitialBudget09, + FlexedValue10 = fb.InitialBudget10, + FlexedValue11 = fb.InitialBudget11, + FlexedValue12 = fb.InitialBudget12 + FROM [fp].[FactBenefitsBudget] fbb + INNER JOIN [fp].[FactBenefits] fb ON fbb.BenefitsID = fb.BenefitsID + INNER JOIN #YearValues v ON v.BenefitsID = fb.BenefitsID + + UPDATE fbb + SET + AdjustedValue01 = CASE WHEN @MonthsLoaded < 1 THEN fb.InitialProjection01 ELSE ActualYTDValue01 END, + AdjustedValue02 = CASE WHEN @MonthsLoaded < 2 THEN fb.InitialProjection02 ELSE ActualYTDValue02 END, + AdjustedValue03 = CASE WHEN @MonthsLoaded < 3 THEN fb.InitialProjection03 ELSE ActualYTDValue03 END, + AdjustedValue04 = CASE WHEN @MonthsLoaded < 4 THEN fb.InitialProjection04 ELSE ActualYTDValue04 END, + AdjustedValue05 = CASE WHEN @MonthsLoaded < 5 THEN fb.InitialProjection05 ELSE ActualYTDValue05 END, + AdjustedValue06 = CASE WHEN @MonthsLoaded < 6 THEN fb.InitialProjection06 ELSE ActualYTDValue06 END, + AdjustedValue07 = CASE WHEN @MonthsLoaded < 7 THEN fb.InitialProjection07 ELSE ActualYTDValue07 END, + AdjustedValue08 = CASE WHEN @MonthsLoaded < 8 THEN fb.InitialProjection08 ELSE ActualYTDValue08 END, + AdjustedValue09 = CASE WHEN @MonthsLoaded < 9 THEN fb.InitialProjection09 ELSE ActualYTDValue09 END, + AdjustedValue10 = CASE WHEN @MonthsLoaded < 10 THEN fb.InitialProjection10 ELSE ActualYTDValue10 END, + AdjustedValue11 = CASE WHEN @MonthsLoaded < 11 THEN fb.InitialProjection11 ELSE ActualYTDValue11 END, + AdjustedValue12 = CASE WHEN @MonthsLoaded < 12 THEN fb.InitialProjection12 ELSE ActualYTDValue12 END, + FlexedValue01 = CASE WHEN @MonthsLoaded < 1 THEN fb.InitialProjection01 ELSE ActualYTDValue01 END, + FlexedValue02 = CASE WHEN @MonthsLoaded < 2 THEN fb.InitialProjection02 ELSE ActualYTDValue02 END, + FlexedValue03 = CASE WHEN @MonthsLoaded < 3 THEN fb.InitialProjection03 ELSE ActualYTDValue03 END, + FlexedValue04 = CASE WHEN @MonthsLoaded < 4 THEN fb.InitialProjection04 ELSE ActualYTDValue04 END, + FlexedValue05 = CASE WHEN @MonthsLoaded < 5 THEN fb.InitialProjection05 ELSE ActualYTDValue05 END, + FlexedValue06 = CASE WHEN @MonthsLoaded < 6 THEN fb.InitialProjection06 ELSE ActualYTDValue06 END, + FlexedValue07 = CASE WHEN @MonthsLoaded < 7 THEN fb.InitialProjection07 ELSE ActualYTDValue07 END, + FlexedValue08 = CASE WHEN @MonthsLoaded < 8 THEN fb.InitialProjection08 ELSE ActualYTDValue08 END, + FlexedValue09 = CASE WHEN @MonthsLoaded < 9 THEN fb.InitialProjection09 ELSE ActualYTDValue09 END, + FlexedValue10 = CASE WHEN @MonthsLoaded < 10 THEN fb.InitialProjection10 ELSE ActualYTDValue10 END, + FlexedValue11 = CASE WHEN @MonthsLoaded < 11 THEN fb.InitialProjection11 ELSE ActualYTDValue11 END, + FlexedValue12 = CASE WHEN @MonthsLoaded < 12 THEN fb.InitialProjection12 ELSE ActualYTDValue12 END + FROM [fp].[FactBenefitsProjection] fbb + INNER JOIN [fp].[FactBenefits] fb ON fbb.BenefitsID = fb.BenefitsID + INNER JOIN #YearValues v ON v.BenefitsID = fb.BenefitsID +END +GO + + +--------------------------------------------- + +-- fp.procUpdateProductivityTargets +/************************************************************************************************************************* +** Change History +************************************************************************************************************************** +** CID Date Author WI Description +** 1 10/30/17 MY B-17281 Updates Productivity Targets If used +** 2 12/04/17 MY B-18098 Populate the Original Value at Sampling +** 3 01/17/18 MY B-18464 Add Projection Logic +** 4 05/17/18 apukii B-19131 Replace FixVar sqlgen with a FixVar table +** 5 07/09/18 BK B-19488 Update for new structure +** 6 10/22/18 ipetriv B-19488 added source dimensionality +** 7 11/15/18 PA B-21059 filter by IsHoursIgnored=0 +** 8 2019-03-26 IP B-22466 Switch usages of funcGetSourceDimensionalityAsTable to a temp table +** 9 2019-07-22 MY B-23801 Productivity Target should only use productive class pay code groups +** 10 2020-04-28 BK D-09683 Productivity Target should use only use months loaded for annualized and projection +** 11 2020-08-26 MD JAZZ-20118 Remove Productivity Target Use MonthsLoaded Only FF +** 12 2022-11-07 MY JAZZ-35951 Add EmployeeID to FactStaffingVariabilityDetail +** 13 2023-09-20 BK JAZZ-60973 Update for new structure (again) +** 14 2024-06-14 SM JAZZ-71536 change JobCodeID from smallint to int +** 15 2024-09-19 MY JAZZ-76045 Missing Budget Config Filter +*************************************************************/ +CREATE PROCEDURE [fp].[procUpdateProductivityTargets] + -- Add the parameters for the stored procedure here + @BudgetConfigID INT, + @EntityGroupConfigID INT, + @EntityGroupConfigGUID UNIQUEIDENTIFIER, + @PayrollFiscalYearID SMALLINT, + @PayrollTimeClassID TINYINT, + @MonthsLoaded INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +AS + +BEGIN + + IF OBJECT_ID('tempdb..#FilterByDepartment') IS NOT NULL DROP TABLE #FilterByDepartment; + IF OBJECT_ID('tempdb..#GroupedByLowestLevel') IS NOT NULL DROP TABLE #GroupedByLowestLevel; + IF OBJECT_ID('tempdb..#GroupedByLowestLevelProj') IS NOT NULL DROP TABLE #GroupedByLowestLevelProj; + IF OBJECT_ID('tempdb..#GroupedByDepartmentTotal') IS NOT NULL DROP TABLE #GroupedByDepartmentTotal; + IF OBJECT_ID('tempdb..#GroupedByDepartmentTotalProj') IS NOT NULL DROP TABLE #GroupedByDepartmentTotalProj; + IF OBJECT_ID('tempdb..#ResultSet') IS NOT NULL DROP TABLE #ResultSet; + IF OBJECT_ID('tempdb..#ProjectionResultSet') IS NOT NULL DROP TABLE #ProjectionResultSet; + + CREATE TABLE #FilterByDepartment (DepartmentID int) + INSERT INTO #FilterByDepartment (DepartmentID) + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + + IF NOT EXISTS(SELECT 1 FROM #FilterByDepartment WHERE DepartmentID IS NOT NULL) BEGIN + INSERT INTO #FilterByDepartment + SELECT DISTINCT DepartmentID FROM fp.Staffing WHERE BudgetConfigID = @BudgetConfigID + END + + DECLARE @ProjectionFiscalYearID SMALLINT, @ProjectionTimeClassID INT + + SELECT @ProjectionTimeClassID = 1,@ProjectionFiscalYearID = bc.FiscalYearID - 1 + FROM [fp].[BudgetConfig] bc + WHERE BudgetConfigID = @BudgetConfigID + + CREATE TABLE #GroupedByLowestLevel (DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, [Value] DECIMAL(19,8)) + CREATE TABLE #GroupedByLowestLevelProj (DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, [Value] DECIMAL(19,8)) + CREATE TABLE #GroupedByDepartmentTotal (DepartmentID INT, [Value] DECIMAL(19,8)) + CREATE TABLE #GroupedByDepartmentTotalProj (DepartmentID INT, [Value] DECIMAL(19,8)) + CREATE TABLE #ResultSet (DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, ProductiveClassID INT, EntityID INT, BudgetConfigID INT, [Value] DECIMAL(19,8), EntityGroupConfigID INT) + CREATE TABLE #ProjectionResultSet (DepartmentID INT, JobCodeID INT, PayCodeGroupID INT, ProductiveClassID INT, EntityID INT, BudgetConfigID INT, [Value] DECIMAL(19,8), EntityGroupConfigID INT) + DECLARE @BudgetYear INT, @SourceYear INT + SELECT @BudgetYear = FiscalYearID FROM fp.EntityGroupConfig egc INNER JOIN fp.BudgetConfig bc on egc.BudgetConfigGUID = bc.BudgetConfigGUID WHERE EntityGroupConfigID = @EntityGroupConfigID + + DECLARE @IsAnnualized BIT = (CASE WHEN @PayrollFiscalYearID = @BudgetYear - 1 AND @PayrollTimeClassID = 1 AND @MonthsLoaded < 12 THEN 1 ELSE 0 END) + + INSERT INTO #GroupedByLowestLevel + SELECT st.DepartmentID, + st.JobCodeID, + pc.PayCodeGroupID, + CASE + WHEN SUM(ISNULL(st.Value, 0)) = 0 THEN 0 + ELSE (ISNULL(MAX((1 - fv.FixedPercentage)), 0) * SUM(st.Value)) + END AS Value + FROM [int].[FactStaffing] st -- As of May 2020, we can't use fp.FactStaffing because variable hours in fp.FactStaffing have the working hours ratio applied to them and may differ from the values in int.FactStaffing + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = st.DepartmentID) + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv ON fv.DepartmentID = st.DepartmentID + AND fv.JobCodeID = st.JobCodeID + AND fv.PayCodeID = st.PayCodeID + AND fv.EmployeeID = 0 -- Only Variable Employees are going to be using Productivity Targets + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = st.PayCodeID + INNER JOIN [fp].[FlexConfigMapping] fcm ON + st.DepartmentID = fcm.DepartmentID + AND st.JobCodeID = fcm.PRJobCodeID + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = st.FiscalMonthID + WHERE IsDeleted = 0 + AND st.UnitTypeID = 51 + AND st.FiscalYearID = @PayrollFiscalYearID AND st.TimeClassID = @PayrollTimeClassID + AND fcm.EntityGroupConfigID = @EntityGroupConfigID + AND fcm.FlexingTypeID = 3 + AND pc.IsHoursIgnored = 0 + AND pcg.ProductiveClassID = 3 -- Productive + AND (@IsAnnualized = 0 OR (@IsAnnualized = 1 AND fm.SortOrder <= @MonthsLoaded)) + GROUP BY st.DepartmentID, st.JobCodeID, pc.PayCodeGroupID + + INSERT INTO #GroupedByLowestLevelProj + SELECT st.DepartmentID, + st.JobCodeID, + pc.PayCodeGroupID, + CASE + WHEN SUM(ISNULL(st.Value, 0)) = 0 THEN 0 + ELSE (ISNULL(MAX((1 - fv.FixedPercentage)), 0) * SUM(st.Value)) + END AS Value + FROM [int].[FactStaffing] st + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = st.DepartmentID) + LEFT JOIN [fp].[FactStaffingVariabilityDetail] fv ON fv.DepartmentID = st.DepartmentID + AND fv.JobCodeID = st.JobCodeID + AND fv.PayCodeID = st.PayCodeID + AND fv.EmployeeID = 0 -- Only Variable Employees are going to be using Productivity Targets + AND fv.EntityGroupConfigGUID = @EntityGroupConfigGUID + INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = st.PayCodeID + INNER JOIN [fp].[FlexConfigMapping] fcm ON + st.DepartmentID = fcm.DepartmentID + AND st.JobCodeID = fcm.PRJobCodeID + INNER JOIN [fw].[DimPayCodeGroup] pcg ON pc.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = st.FiscalMonthID + WHERE IsDeleted = 0 + AND st.UnitTypeID = 51 + AND st.FiscalYearID = @ProjectionFiscalYearID AND st.TimeClassID = @ProjectionTimeClassID + AND fcm.EntityGroupConfigID = @EntityGroupConfigID + AND fcm.FlexingTypeID = 3 + AND pc.IsHoursIgnored = 0 + AND pcg.ProductiveClassID = 3 -- Productive + AND fm.SortOrder <= @MonthsLoaded + GROUP BY st.DepartmentID, st.JobCodeID, pc.PayCodeGroupID + + INSERT INTO #GroupedByDepartmentTotal + SELECT DepartmentID, SUM(ISNULL(Value, 0)) as Value + FROM #GroupedByLowestLevel + GROUP BY DepartmentID + + INSERT INTO #GroupedByDepartmentTotalProj + SELECT DepartmentID, SUM(ISNULL(Value, 0)) as Value + FROM #GroupedByLowestLevelProj + GROUP BY DepartmentID + + INSERT INTO #ResultSet + SELECT basis.DepartmentID, basis.JobCodeID, basis.PayCodeGroupID, basis.ProductiveClassID, basis.EntityID, + basis.BudgetConfigID, + CASE WHEN dept.Value = 0 THEN 0 ELSE + COALESCE(fc.ProductivityTarget * (jc.Value/dept.Value), 0) END + AS Value, + @EntityGroupConfigID AS EntityGroupConfigID + FROM [fp].[Staffing] basis + INNER JOIN #GroupedByLowestLevel jc ON basis.DepartmentID = jc.DepartmentID + AND basis.JobCodeID = jc.JobCodeID + AND basis.PayCodeGroupID = jc.PayCodeGroupID + INNER JOIN #GroupedByDepartmentTotal dept ON basis.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[StaffingExpenseFlexingConfig] fc ON fc.DepartmentID = basis.DepartmentID + WHERE fc.IsUsingProductivityTarget = 1 + AND basis.EntityGroupConfigID = @EntityGroupConfigID + AND fc.EntityGroupConfigGUID = @EntityGroupConfigGUID + + + INSERT INTO #ProjectionResultSet + SELECT basis.DepartmentID, basis.JobCodeID, basis.PayCodeGroupID, basis.ProductiveClassID, basis.EntityID, + basis.BudgetConfigID, + CASE WHEN dept.Value = 0 THEN 0 ELSE + COALESCE(fc.ProductivityTarget * (jc.Value/dept.Value), 0) END AS Value, + @EntityGroupConfigID AS EntityGroupConfigID + FROM [fp].[Staffing] basis --projection + INNER JOIN #GroupedByLowestLevelProj jc ON basis.DepartmentID = jc.DepartmentID + AND basis.JobCodeID = jc.JobCodeID + AND basis.PayCodeGroupID = jc.PayCodeGroupID + INNER JOIN #GroupedByDepartmentTotalProj dept ON basis.DepartmentID = dept.DepartmentID + INNER JOIN [fp].[StaffingExpenseFlexingConfig] fc ON fc.DepartmentID = basis.DepartmentID + WHERE fc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND fc.IsUsingProductivityTarget = 1 + AND basis.EntityGroupConfigID = @EntityGroupConfigID + + + UPDATE basis + SET InitialBudgetRate01 = result.Value + , InitialBudgetRate02 = result.Value + , InitialBudgetRate03 = result.Value + , InitialBudgetRate04 = result.Value + , InitialBudgetRate05 = result.Value + , InitialBudgetRate06 = result.Value + , InitialBudgetRate07 = result.Value + , InitialBudgetRate08 = result.Value + , InitialBudgetRate09 = result.Value + , InitialBudgetRate10 = result.Value + , InitialBudgetRate11 = result.Value + , InitialBudgetRate12 = result.Value + FROM [fp].[Staffing] basis + INNER JOIN #ResultSet result ON + basis.BudgetConfigID = result.BudgetConfigID + AND basis.DepartmentID = result.DepartmentID + AND basis.JobCodeID = result.JobCodeID + AND basis.PayCodeGroupID = result.PayCodeGroupID + AND basis.ProductiveClassID = result.ProductiveClassID + AND basis.EntityID = result.EntityID + + + UPDATE basis + SET InitialProjectionRate01 = CASE WHEN @MonthsLoaded < 1 THEN result.Value ELSE 0 END + , InitialProjectionRate02 = CASE WHEN @MonthsLoaded < 2 THEN result.Value ELSE 0 END + , InitialProjectionRate03 = CASE WHEN @MonthsLoaded < 3 THEN result.Value ELSE 0 END + , InitialProjectionRate04 = CASE WHEN @MonthsLoaded < 4 THEN result.Value ELSE 0 END + , InitialProjectionRate05 = CASE WHEN @MonthsLoaded < 5 THEN result.Value ELSE 0 END + , InitialProjectionRate06 = CASE WHEN @MonthsLoaded < 6 THEN result.Value ELSE 0 END + , InitialProjectionRate07 = CASE WHEN @MonthsLoaded < 7 THEN result.Value ELSE 0 END + , InitialProjectionRate08 = CASE WHEN @MonthsLoaded < 8 THEN result.Value ELSE 0 END + , InitialProjectionRate09 = CASE WHEN @MonthsLoaded < 9 THEN result.Value ELSE 0 END + , InitialProjectionRate10 = CASE WHEN @MonthsLoaded < 10 THEN result.Value ELSE 0 END + , InitialProjectionRate11 = CASE WHEN @MonthsLoaded < 11 THEN result.Value ELSE 0 END + , InitialProjectionRate12 = CASE WHEN @MonthsLoaded < 12 THEN result.Value ELSE 0 END + FROM [fp].[Staffing] basis + INNER JOIN #ProjectionResultSet result ON + basis.BudgetConfigID = result.BudgetConfigID + AND basis.DepartmentID = result.DepartmentID + AND basis.JobCodeID = result.JobCodeID + AND basis.PayCodeGroupID = result.PayCodeGroupID + AND basis.ProductiveClassID = result.ProductiveClassID + AND basis.EntityID = result.EntityID + + + UPDATE basis + SET TargetAdjustedRate01 = InitialBudgetRate01 + , TargetAdjustedRate02 = InitialBudgetRate02 + , TargetAdjustedRate03 = InitialBudgetRate03 + , TargetAdjustedRate04 = InitialBudgetRate04 + , TargetAdjustedRate05 = InitialBudgetRate05 + , TargetAdjustedRate06 = InitialBudgetRate06 + , TargetAdjustedRate07 = InitialBudgetRate07 + , TargetAdjustedRate08 = InitialBudgetRate08 + , TargetAdjustedRate09 = InitialBudgetRate09 + , TargetAdjustedRate10 = InitialBudgetRate10 + , TargetAdjustedRate11 = InitialBudgetRate11 + , TargetAdjustedRate12 = InitialBudgetRate12 + , BudgetAdjustedRate01 = InitialBudgetRate01 + , BudgetAdjustedRate02 = InitialBudgetRate02 + , BudgetAdjustedRate03 = InitialBudgetRate03 + , BudgetAdjustedRate04 = InitialBudgetRate04 + , BudgetAdjustedRate05 = InitialBudgetRate05 + , BudgetAdjustedRate06 = InitialBudgetRate06 + , BudgetAdjustedRate07 = InitialBudgetRate07 + , BudgetAdjustedRate08 = InitialBudgetRate08 + , BudgetAdjustedRate09 = InitialBudgetRate09 + , BudgetAdjustedRate10 = InitialBudgetRate10 + , BudgetAdjustedRate11 = InitialBudgetRate11 + , BudgetAdjustedRate12 = InitialBudgetRate12 + , ProjectionAdjustedRate01 = InitialProjectionRate01 + , ProjectionAdjustedRate02 = InitialProjectionRate02 + , ProjectionAdjustedRate03 = InitialProjectionRate03 + , ProjectionAdjustedRate04 = InitialProjectionRate04 + , ProjectionAdjustedRate05 = InitialProjectionRate05 + , ProjectionAdjustedRate06 = InitialProjectionRate06 + , ProjectionAdjustedRate07 = InitialProjectionRate07 + , ProjectionAdjustedRate08 = InitialProjectionRate08 + , ProjectionAdjustedRate09 = InitialProjectionRate09 + , ProjectionAdjustedRate10 = InitialProjectionRate10 + , ProjectionAdjustedRate11 = InitialProjectionRate11 + , ProjectionAdjustedRate12 = InitialProjectionRate12 + FROM [fp].[Staffing] basis + INNER JOIN #FilterByDepartment ft on (ft.DepartmentID = basis.DepartmentID) + WHERE basis.ProductiveClassID = 3 -- Productive + AND basis.BudgetConfigID = @BudgetConfigID + +END; +GO + + +--------------------------------------------- + +-- fp.procUpdateSystemCenterScreensSecurity +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2019-01-09 kzhuk B-21502 Created +** 2 2019-01-11 gforeman B-21502 Added roster +** 3 B-22226 SEE BELOW FOR PROPOSED CHANGES +** 4 2019-03-27 OV B-22369 leave screens enabled if "AP Preview Enabled" = 1 +** 5 2019-08-12 NL D-08644 fixing bug where stuff wasn't being enabled properly +** 6 2021-12-21 SD JAZZ-30939 Hide OB system center pages when OnePlan is enabled +** 7 2022-06-21 SD JAZZ-34197 Enable pages for new clients that use only PlanEditor +** 8 2023-08-22 LR JAZZ-54949 Hide\Show OB pages when OnePlan is enabled on Maintenance Mode +***************************************************************/ +CREATE procEDURE [fp].[procUpdateSystemCenterScreensSecurity] +AS +BEGIN + declare @groupObSysAdmin uniqueidentifier + select @groupObSysAdmin = UserGroupGUID from UserGroup where GlobalID = 'OB - System Administrator' + + DECLARE @isReadValue bit = 1 + + -- if the AP is enabled or the AP preview is enabled, then we want to make sure any dependent sys center pages are also enabled + IF (EXISTS (SELECT 1 FROM fp.SystemSetting WHERE Name = 'Is APE Enabled' AND Value = '1') /* We only want DBs with OnePlan functionality enabled */ + AND EXISTS (SELECT 1 FROM fp.SystemSetting WHERE Name = 'AP Preview Enabled' AND Value = '0'))/* Clients stil in Preview mode need to keep these pages enabled */ + BEGIN + SET @isReadValue = 0 + END + + UPDATE s3 SET ReadValue = @isReadValue + FROM [dbo].[S3SimplePermission] s3 + JOIN [dbo].[UserGroup] ug ON s3.IdentityGUID=ug.UserGroupGUID + JOIN [dbo].[SystemCenterSection] scsec ON s3.LootID = scsec.SectionGUID + JOIN [dbo].[SystemCenterCategory] sccat ON scsec.CategoryGUID=sccat.CategoryGUID + JOIN [dbo].[SystemCenterModule] scmod ON sccat.ModuleGUID=scmod.ModuleGUID + WHERE 1=1 + AND ug.GlobalID = 'OB - System Administrator' + /* Setup mode is for Strata users so it is lower priority, will update later */ + AND sccat.IsMaintenanceMode=1 + AND scmod.Name = 'Operating Budgeting' + /* Exceptions - The list of pages still used by OnePlan clients */ + AND scsec.Name NOT IN ( + 'Budgeted Department Setup', + 'Payroll to General Ledger Link', + 'Metrics Setup', + 'Primary Statistics Configuration', + 'Manage Plan Configurations', + 'Manage Roster Budgeting Configurations' + ) + +-- Enable pages for new clients that use only PlanEditor + UPDATE s3 SET ReadValue = 1 + FROM [dbo].[S3SimplePermission] s3 + JOIN [dbo].[UserGroup] ug ON s3.IdentityGUID=ug.UserGroupGUID + JOIN [dbo].[SystemCenterSection] scsec ON s3.LootID = scsec.SectionGUID + JOIN [dbo].[SystemCenterCategory] sccat ON scsec.CategoryGUID=sccat.CategoryGUID + JOIN [dbo].[SystemCenterModule] scmod ON sccat.ModuleGUID=scmod.ModuleGUID + WHERE ug.GlobalID = 'OB - System Administrator' + /* Setup mode is for Strata users so it is lower priority, will update later */ + AND sccat.IsMaintenanceMode=1 + AND scmod.Name = 'Operating Budgeting' + /* The list of pages still used by OnePlan clients */ + AND scsec.Name IN ( + 'Budgeted Department Setup', + 'Payroll to General Ledger Link', + 'Metrics Setup', + 'Primary Statistics Configuration', + 'Manage Plan Configurations', + 'Manage Roster Budgeting Configurations' + ) + + declare @isRosterEnabled bit + select @isRosterEnabled = Value from ob.SystemSetting where name='Is Roster Budgeting Enabled' + + UPDATE [dbo].[S3SimplePermission] SET ReadValue = @isRosterEnabled WHERE IdentityGuid = @groupObSysAdmin AND LootID = '1C04F259-8150-4909-A3F3-EBB23CDE6438' +END +GO + + +--------------------------------------------- + +-- fp.procVariableDirectCostPerUnitPopulate +-- ============================================= +-- Author: Michael Young +-- Create date: 4/5/2016 +-- Description: Populates VariableDirectCostPerUnit in fp.FactDepartmentChargeVolumeBasis +-- Change History: +-- *1 NL 1/28/19 Complete re-write +-- *2 BK 4/22/19 Add null check on update [TK-73046] +-- *3 BK 11/11/21 Limit to only the departments that use PAF +-- *4 NT 01/26/23 JAZZ-48268 Make change to update fp.ChargeVolume (data restructure) +-- ============================================= + +CREATE PROCEDURE [fp].[procVariableDirectCostPerUnitPopulate] + @LatestCostingResult AS INT, + @CostingTimeClassFromBudgetConfig AS TINYINT, + @BudgetConfigID AS SMALLINT + WITH RECOMPILE +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + IF OBJECT_ID('tempdb..#Dept') IS NOT NULL DROP TABLE #Dept + IF OBJECT_ID('tempdb..#UnitCostsPerRVU') IS NOT NULL DROP TABLE #UnitCostsPerRVU + IF OBJECT_ID('tempdb..#VariableDirectUnitCost') IS NOT NULL DROP TABLE #VariableDirectUnitCost + IF OBJECT_ID('tempdb..#Costing') IS NOT NULL DROP TABLE #Costing + + + DECLARE @CostingConfigGUID uniqueidentifier; + SELECT @CostingConfigGUID = CostingConfigGUID FROM [dss].[CostingResult] WHERE CostingResultID = @LatestCostingResult; + + CREATE TABLE #UnitCostsPerRVU (DepartmentID INT, CostComponentID INT, UnitCostPerRVU DECIMAL(19,8)) + CREATE TABLE #VariableDirectUnitCost (DepartmentID INT, ChargeCodeID INT, ServiceLineID INT, PatientClassID INT, VariableDirectUnitCostNew DECIMAL(19,8)) + + DECLARE @BudgetConfigGUID UNIQUEIDENTIFIER + SELECT @BudgetConfigGUID = BudgetConfigGUID FROM fp.BudgetConfig WHERE BudgetConfigID = @BudgetConfigID + + CREATE TABLE #Dept (DepartmentID INT) + INSERT INTO #Dept (DepartmentID) + SELECT DISTINCT DepartmentID + FROM fp.FlexConfigMapping fcm INNER JOIN fp.EntityGroupConfig ecg ON fcm.EntityGroupConfigID = ecg.EntityGroupConfigID + WHERE FlexingTypeID = 7 AND ecg.BudgetConfigGUID = @BudgetConfigGUID + + CREATE TABLE #Costing (DepartmentID INT, CostComponentID INT, ChargeCodeID INT, Volume DECIMAL(19,8), TotalVariableDirectCost DECIMAL(19,8)) + + INSERT INTO #Costing(DepartmentID, CostComponentID, ChargeCodeID, Volume, TotalVariableDirectCost) + SELECT gl.OriginalDepartmentID, gl.CostComponentID, gl.ChargeCodeID, gl.Volume, gl.VariableDirectUnitCost * gl.Volume as TotalVariableDirectCost + FROM [dss].[FactCostingOutDetailGL] gl INNER JOIN #Dept d on gl.DepartmentID = d.DepartmentID + WHERE gl.CostingResultID = @LatestCostingResult AND gl.TimeClassID = @CostingTimeClassFromBudgetConfig + UNION ALL + SELECT pr.OriginalDepartmentID, pr.CostComponentID, pr.ChargeCodeID, pr.Volume, pr.VariableDirectUnitCost * pr.Volume as TotalVariableDirectCost + FROM [dss].[FactCostingOutDetailPayroll] pr INNER JOIN #Dept d on pr.DepartmentID = d.DepartmentID + WHERE pr.CostingResultID = @LatestCostingResult AND pr.TimeClassID = @CostingTimeClassFromBudgetConfig + + INSERT INTO #UnitCostsPerRVU (DepartmentID, CostComponentID, UnitCostPerRVU) + SELECT cost.DepartmentID, cost.CostComponentID, sum(TotalCost/NULLIF(volume, 0))/NULLIF(sum(ca.RVU), 0) as UnitCostPerRVU + FROM + ( SELECT + co.DepartmentID, + co.CostComponentID, + co.ChargeCodeID, + sum(TotalVariableDirectCost) as TotalCost, Max(Volume) as Volume + FROM #Costing co + GROUP BY co.DepartmentID, co.CostComponentID, co.ChargeCodeID + ) cost + + INNER JOIN [dss].[ChargeAllocation] ca + ON cost.DepartmentID = ca.DepartmentID + AND cost.CostComponentID = ca.CostComponentID + AND cost.ChargeCodeID = ca.ChargeCodeID + WHERE ca.CostingConfigGuid = @CostingConfigGUID AND ca.AllocationType = 1 AND ca.IsFixed = 0 AND ca.IsIndirect = 0 + GROUP BY cost.DepartmentID, cost.CostComponentID + + + INSERT INTO #VariableDirectUnitCost (DepartmentID, ChargeCodeID, ServiceLineID, PatientClassID, VariableDirectUnitCostNew) + SELECT f.DepartmentID, f.ChargeCodeID, f.ServiceLineID, f.PatientClassID, SUM(UnitCostPerRVU * RVU) as VariableDirectUnitCostNew + FROM [fp].[ChargeVolume] f + INNER JOIN [dss].[ChargeAllocation] ca + ON f.ChargeCodeID = ca.ChargeCodeID + AND f.DepartmentID = ca.DepartmentID + INNER JOIN #UnitCostsPerRVU t + ON f.DepartmentID = t.DepartmentID + AND ca.CostComponentID = t.CostComponentID + WHERE f.BudgetConfigID = @BudgetConfigID + and ca.CostingConfigGuid = @CostingConfigGUID + AND ca.AllocationType = 1 AND ca.IsFixed = 0 AND ca.IsIndirect = 0 AND ca.RVU != 0 + and f.UnitTypeID = 145 + GROUP BY f.DepartmentID, f.ChargeCodeID, f.ServiceLineID, f.PatientClassID + + + + UPDATE f + SET f.VariableDirectUnitCost = COALESCE(VariableDirectUnitCostNew, 0) + FROM [fp].[ChargeVolume] f + INNER JOIN #VariableDirectUnitCost v + ON f.DepartmentID = v.DepartmentID + AND f.ChargeCodeID = v.ChargeCodeID + AND f.ServiceLineID = v.ServiceLineID + AND f.PatientClassID = v.PatientClassID + WHERE f.BudgetConfigID = @BudgetConfigID + and f.UnitTypeID = 145 + +END +GO + + +--------------------------------------------- + +--------------------------------------------- +-- FUNCTIONS +--------------------------------------------- + +-- fp.GetAdjustmentHierarchyEntityIDs +CREATE FUNCTION [fp].[GetAdjustmentHierarchyEntityIDs] +( + @groupingHierarchyJSON VARCHAR(MAX) +) +RETURNS @adjustmentHierarchyDepartmentIDs TABLE ( + EntityID INT +) +AS + BEGIN + DECLARE @level VARCHAR(MAX); + DECLARE @hierarchyPathArray VARCHAR(MAX); + + SELECT @level = gh.[value] + FROM OPENJSON(@groupingHierarchyJSON, '$.Levels') AS gh + CROSS APPLY OPENJSON(gh.[value]) AS ghr + WHERE ghr.[key] ='Name' AND ghr.[value] = 'Entity' + + SELECT @hierarchyPathArray = [value] + FROM OPENJSON(@level) + WHERE [key] ='HierarchyPaths' + + INSERT INTO @adjustmentHierarchyDepartmentIDs + SELECT CAST(RIGHT(hpi.[value], charindex('|', reverse(hpi.[value]) + '|') - 1) AS INT) AS EntitiyID + FROM OPENJSON(@hierarchyPathArray) AS hp + CROSS APPLY OPENJSON(hp.value) AS hpi + WHERE hpi.[key] = 'id' + + RETURN; + END +GO + + +--------------------------------------------- + +-- fp.GetAdjustmentHierarchyIDs +CREATE FUNCTION [fp].[GetAdjustmentHierarchyIDs] +( + @groupingHierarchyJSON VARCHAR(MAX), + @entityName VARCHAR(50) +) +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2021-07-28 OP JAZZ-8052 Handled case when there is no ID at the hierarchy end + *************************************************************/ +RETURNS @adjustmentHierarchyIDs TABLE ( + ID INT +) +AS + BEGIN + DECLARE @level VARCHAR(MAX); + DECLARE @hierarchyPathArray VARCHAR(MAX); + + SELECT @level = gh.[value] + FROM OPENJSON(@groupingHierarchyJSON, '$.Levels') AS gh + CROSS APPLY OPENJSON(gh.[value]) AS ghr + WHERE ghr.[key] ='Name' AND ghr.[value] = @entityName + + SELECT @hierarchyPathArray = [value] + FROM OPENJSON(@level) + WHERE [key] ='HierarchyPaths' + + INSERT INTO @adjustmentHierarchyIDs + SELECT TRY_CAST(RIGHT(hpi.[value], charindex('|', reverse(hpi.[value]) + '|') - 1) AS INT) AS ID + FROM OPENJSON(@hierarchyPathArray) AS hp + CROSS APPLY OPENJSON(hp.value) AS hpi + WHERE hpi.[key] = 'id' + + RETURN; + END +GO + + +--------------------------------------------- + +-- fp.GetAdjustmentMeasure +CREATE FUNCTION fp.GetAdjustmentMeasure +( + @AdjustmentType TINYINT, + @unitTypeId TINYINT +) +RETURNS VARCHAR(25) + BEGIN + DECLARE @adjustmentMeasureString VARCHAR(25); + + -- Keeping original 'logic' from C#: + + IF @AdjustmentType = 6 -- FTE + RETURN 'FTEs'; + + SET @adjustmentMeasureString = CASE + WHEN (@unitTypeId = 33 -- ID_DOLLARSPERUOS + OR @unitTypeId = 34) -- ID_DOLLARS + THEN 'Dollars$' + WHEN @unitTypeId = 51 -- ID_HOURS + THEN 'Hours' + WHEN @unitTypeId = 144 -- ID_FTES + THEN 'FTEs' + WHEN @unitTypeId = 140 -- ID_VOLUME + THEN 'Volume' + WHEN @unitTypeId = 159 -- ID_WAGERATE + THEN 'Wage Rate$' + WHEN @unitTypeId = 169 -- ID_SALARIES + THEN 'Salaries$' + WHEN @unitTypeId = 170 -- ID_PERCENTOFSALARIES + THEN '% of Salary' + WHEN @unitTypeId = 171 -- ID_DOLLARSPERFTE + THEN '$ Per FTE' + WHEN @unitTypeId = 172 -- ID_HOURSPERUOS + THEN 'Hours per UOS' + WHEN @unitTypeId = 145 -- ID_UNITS + THEN 'Units' + ELSE '' + END; + + RETURN @adjustmentMeasureString + END +GO + + +--------------------------------------------- + +-- fp.GetAdjustmentPath +CREATE FUNCTION [fp].[GetAdjustmentPath] +( + @adjustmentFilterJSON VARCHAR(MAX), + @hierarhyJSON VARCHAR(MAX), + @PlanSectionID TINYINT +) +RETURNS NVARCHAR(MAX) +BEGIN + +DECLARE @result NVARCHAR(max) +DECLARE @HierarhyParsed TABLE( + Name VARCHAR(50), + LevelID VARCHAR(50), + IsHidden BIT, + IsDisabled BIT, + Value VARCHAR(500) +) + +INSERT INTO @HierarhyParsed(Name, LevelID, IsHidden, isDisabled) +SELECT Name, LevelID, IsHidden, IsDisabled +FROM OPENJSON(@hierarhyJSON, '$.Levels') +WITH ( Name VARCHAR(50) '$.Name', + LevelID VARCHAR(50) '$.LevelID', + IsHidden BIT '$.IsHidden', + IsDisabled BIT '$.IsDisabled') + + +-------------- SERVICE LINE ----------------------------- +IF @PlanSectionID = 1 +BEGIN + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ServiceLineRollup.Name') WHERE Name = 'Service Line Rollup' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ServiceLine.Name') WHERE Name = 'Service Line' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.PatientClass.Name') WHERE Name = 'Patient Class' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Entity.Name') WHERE Name = 'Entity' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.MedicalSurgical.Name') WHERE Name = 'Medical/Surgical' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.AgeCohort.Name') WHERE Name = 'Age Cohort' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Department.Name') WHERE Name = 'Department' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Payor.Name') WHERE Name = 'Payor' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.PayorGroup.Name') WHERE Name = 'Payor Group' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.MSDRG.Name') WHERE Name = 'MSDRG' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.CPT.Name') WHERE Name = 'CPT' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Provider.Name') WHERE Name = 'Provider' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ProviderSpecialty.Name') WHERE Name = 'Provider Specialty' +END + +--------------- CHARGE VOLUME ------------- +IF @PlanSectionID = 2 +BEGIN + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Entity.Name') WHERE Name = 'Entity' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Department.Name') WHERE Name = 'Department' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ChargeCode.Name') WHERE Name = 'Charge Code' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.PatientClass.Name') WHERE Name = 'Patient Class' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ServiceLine.Name') WHERE Name = 'Service Line' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.MedicalSurgical.Name') WHERE Name = 'Medical/Surgical' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.AgeCohort.Name') WHERE Name = 'Age Cohort' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ServiceEntity.Name') WHERE Name = 'Service Entity' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.MSDRG.Name') WHERE Name = 'MSDRG' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.UBRevCode.Name') WHERE Name = 'Revenue Code' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.PrimaryCPT.Name') WHERE Name = 'Primary CPT' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ServiceProvider.Name') WHERE Name = 'Service Provider' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ServiceProviderSpecialty.Name') WHERE Name = 'Service Provider Specialty' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.PerformingProvider.Name') WHERE Name = 'Performing Provider' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.PerformingProviderSpecialty.Name') WHERE Name = 'Performing Provider Specialty' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.BillingCPT.Name') WHERE Name = 'Billing CPT' +END + +---------------------STATISTICS +IF @PlanSectionID = 3 +BEGIN + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Department.Name') WHERE Name = 'Department' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Account.Name') WHERE Name = 'Account' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Provider.Name') WHERE Name = 'Provider' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.PatientClass.Name') WHERE Name = 'Patient Class' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Entity.Name') WHERE Name = 'Entity' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.FinancialReporting.Name') WHERE Name = 'Financial Reporting Rollup' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Payor.Name') WHERE Name = 'Payor' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ProviderType.Name') WHERE Name = 'Provider Type' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ProviderLineItem.Name') WHERE Name = 'Provider Line Item' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ProviderSpecialty.Name') WHERE Name = 'Provider Specialty' +END + +----------------------STAFFFING +IF @PlanSectionID = 4 +BEGIN + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.PayCodeGroup.Name') WHERE Name = 'Pay Code Group' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Department.Name') WHERE Name = 'Department' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.JobCode.Name') WHERE Name = 'Job Code' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Variability.Name') WHERE Name = 'Fixed/Variable' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ProductiveClass.Name') WHERE Name = 'Productive Class' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Entity.Name') WHERE Name = 'Entity' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Employee.Name') WHERE Name = 'Employee' +-------------PROVIDER COMPENSATION + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ProviderSpecialty.Name') WHERE Name = 'Provider Specialty' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ProviderLineItem.Name') WHERE Name = 'Provider Line Item' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Provider.Name') WHERE Name = 'Provider' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.ProviderType.Name') WHERE Name = 'Provider Type' +END + +-----------------BENEFITS------- +IF @PlanSectionID = 5 +BEGIN + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.FinancialReporting.Name') WHERE Name = 'Financial Reporting Rollup' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Account.Name') WHERE Name = 'Account' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Entity.Name') WHERE Name = 'Entity' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Department.Name') WHERE Name = 'Department' +END + +-------------------GL ----------------------- +IF @PlanSectionID = 6 +BEGIN + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.FinancialReporting.Name') WHERE Name = 'Financial Reporting Rollup' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Account.Name') WHERE Name = 'Account' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Entity.Name') WHERE Name = 'Entity' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Variability.Name') WHERE Name = 'Fixed/Variable' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Department.Name') WHERE Name = 'Department' +END + +-------------------Reimbursement ----------------------- +IF @PlanSectionID = 7 +BEGIN + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Department.Name') WHERE Name = 'Department' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.Entity.Name') WHERE Name = 'Entity' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.PatientClass.Name') WHERE Name = 'Patient Class' + UPDATE @HierarhyParsed SET Value = JSON_VALUE(@adjustmentFilterJSON, '$.PayorGroup.Name') WHERE Name = 'Payor Group' +END + +SELECT @result = ( SELECT STRING_AGG(Value, ' => ') FROM @HierarhyParsed WHERE IsHidden = 0 AND IsDisabled = 0) + +RETURN COALESCE(@result, '') +END +GO + + +--------------------------------------------- + +-- fp.GetAdjustmentReportValue +CREATE FUNCTION [fp].[GetAdjustmentReportValue] +( + @AdjustmentValue DECIMAL(19,4), + @AdjustmentType TINYINT +) +RETURNS VARCHAR(25) + BEGIN + DECLARE @adjustmentValueString VARCHAR(25); + + SET @adjustmentValueString = CASE + WHEN @AdjustmentType = 1 -- Percentage + THEN CAST(CAST(@AdjustmentValue * 100 AS DECIMAL(19,2)) AS VARCHAR(23)) + '%' + WHEN @AdjustmentType = 10 + THEN 'Lock' + WHEN @AdjustmentType = 11 + THEN 'Unlock' + ELSE CONVERT(VARCHAR(25), CAST(ROUND(@AdjustmentValue, 2, 1) AS DECIMAL(19,2))) + END; + + RETURN @adjustmentValueString + END +GO + + +--------------------------------------------- + +-- fp.GetAdjustmentTimeClass +CREATE FUNCTION fp.GetAdjustmentTimeClass +( + @timeClassID TINYINT, + @budgetPhaseID TINYINT +) +RETURNS TINYINT + BEGIN + DECLARE @adjustmentTimeClass TINYINT; + + SET @adjustmentTimeClass = CASE + WHEN @timeClassID = 12 + THEN 12 + WHEN (@timeClassID = 2 + AND @budgetPhaseID = 2) -- Admin + THEN 20 + WHEN (@timeClassID = 2 + AND @budgetPhaseID = 3) -- Department + THEN 2 + ELSE 0 + END; + + RETURN @adjustmentTimeClass + END +GO + + +--------------------------------------------- + +-- fp.GetAdjustmentTimeClassString +CREATE FUNCTION fp.GetAdjustmentTimeClassString +( + @adjustmentType TINYINT, + @timeClassID TINYINT, + @budgetPhaseID TINYINT +) +RETURNS VARCHAR(25) + BEGIN + DECLARE @adjustmentTimeClassString VARCHAR(25); + + IF (@adjustmentType = 6 AND @timeClassID = 0) -- FTE + BEGIN + RETURN 'target' + END + + SET @adjustmentTimeClassString = CASE + WHEN @timeClassID = 12 + THEN 'projection' + WHEN (@timeClassID = 2 + AND @budgetPhaseID = 2) -- Admin + THEN 'target' + WHEN (@timeClassID = 2 + AND @budgetPhaseID = 3) -- Department + THEN 'budget' + ELSE '' + END; + + RETURN @adjustmentTimeClassString + END +GO + + +--------------------------------------------- + +-- fp.GetAdjustmentType +CREATE FUNCTION [fp].[GetAdjustmentType] +( + @AdjustmentType TINYINT +) +RETURNS VARCHAR(20) + BEGIN + DECLARE @adjustmentTypeString VARCHAR(20); + + SET @adjustmentTypeString = CASE + WHEN @AdjustmentType = 0 + THEN 'Incremental' + WHEN @AdjustmentType = 1 + THEN 'Percentage%' + WHEN @AdjustmentType = 2 + THEN 'Set Value' + WHEN @AdjustmentType = 3 + THEN 'Final' + WHEN @AdjustmentType = 4 + THEN 'Imported' + WHEN @AdjustmentType = 5 + THEN 'Mix' + WHEN @AdjustmentType = 6 + THEN 'FTE' + WHEN @AdjustmentType = 7 + THEN 'Manager' + WHEN @AdjustmentType = 8 + THEN 'Varuable Reset' + WHEN @AdjustmentType = 9 + THEN 'Spread Unlock' + WHEN @AdjustmentType = 10 + THEN 'Lock' + WHEN @AdjustmentType = 11 + THEN 'Unlock' + WHEN @AdjustmentType = 12 + THEN 'Set Value' + WHEN @AdjustmentType = 13 + THEN 'Final Value' + WHEN @AdjustmentType = 14 + THEN 'Incremental' + WHEN @AdjustmentType = 15 + THEN 'Add Provider' + WHEN @AdjustmentType = 20 + THEN 'Manager Set' + ELSE '' + END; + + RETURN @adjustmentTypeString + END +GO + + +--------------------------------------------- + +-- fp.GetAdjustmentValue +CREATE FUNCTION [fp].[GetAdjustmentValue] +( + @AdjustmentValue DECIMAL(19,4), + @AdjustmentType TINYINT +) +RETURNS VARCHAR(25) +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2020-01-15 OP JAZZ-12268 Now returning "5.00%" values for percentage adjustments + *************************************************************/ + BEGIN + DECLARE @adjustmentValueString VARCHAR(25); + + SET @adjustmentValueString = CASE + WHEN @AdjustmentType = 1 -- Percentage + --THEN @AdjustmentValue * 100 + THEN CAST(CAST(@AdjustmentValue * 100 AS DECIMAL(19,2)) AS VARCHAR(23)) + '%' + ELSE CAST(@AdjustmentValue AS VARCHAR(23)) + END; + + RETURN @adjustmentValueString + END +GO + + +--------------------------------------------- + +-- fp.GetIsNetRevenueModelLocked +CREATE FUNCTION [fp].[GetIsNetRevenueModelLocked] +(@budgetConfigGuid UNIQUEIDENTIFIER) + RETURNS BIT +AS +BEGIN + IF EXISTS( + SELECT 1 + FROM fp.ReimbursementGeneralLedgerAdjustment a + WHERE a.BudgetConfigGuid = @budgetConfigGuid + + UNION ALL + + SELECT 1 + FROM fp.ReimbursementAdjustment a + WHERE a.BudgetConfigGuid = @budgetConfigGuid + ) + BEGIN + RETURN CAST(1 AS BIT) + END + + RETURN CAST(0 AS BIT) +END +GO + + +--------------------------------------------- + +-- fp.GetIsSectionSetupLocked +CREATE FUNCTION [fp].[GetIsSectionSetupLocked] +(@budgetConfigGuid UNIQUEIDENTIFIER) + RETURNS BIT +AS +BEGIN + IF EXISTS( + SELECT 1 + FROM fp.StaffingAdjustment a + WHERE a.BudgetConfigGuid = @budgetConfigGuid + + UNION ALL + + SELECT 1 + FROM fp.BenefitsAdjustment a + WHERE a.BudgetConfigGuid = @budgetConfigGuid + + UNION ALL + + SELECT 1 + FROM fp.DepartmentChargeVolumeAdjustment a + WHERE a.BudgetConfigGuid = @budgetConfigGuid + + UNION ALL + + SELECT 1 + FROM fp.GeneralLedgerAdjustment a + WHERE a.BudgetConfigGuid = @budgetConfigGuid + + UNION ALL + + SELECT 1 + FROM fp.ServiceLineEncounterAdjustment a + WHERE a.BudgetConfigGuid = @budgetConfigGuid + + UNION ALL + + SELECT 1 + FROM fp.StatisticsAdjustment a + WHERE a.BudgetConfigGuid = @budgetConfigGuid + ) + BEGIN + RETURN CAST(0 AS BIT) + END + + RETURN CAST(1 AS BIT) +END +GO + + +--------------------------------------------- + +-- fp.SearchAdjustmentMeasureForImport +CREATE FUNCTION fp.SearchAdjustmentMeasureForImport +( + @AdjustmentType TINYINT, + @importUnitTypeIDs VARCHAR(MAX), + @search VARCHAR(MAX) +) +RETURNS BIT + BEGIN + DECLARE @result BIT = 0; + + IF EXISTS( + SELECT 1 + FROM ( + SELECT [value] + FROM STRING_SPLIT(@importUnitTypeIDs, ' ') + ) AS res + WHERE LOWER(fp.GetAdjustmentMeasure(@AdjustmentType, res.[value])) LIKE @search ESCAPE '\') + BEGIN + SET @result = 1 + END + + RETURN @result + END +GO + + +--------------------------------------------- + +-- fp.SearchHierarchyLevel +CREATE FUNCTION fp.SearchHierarchyLevel +( + @adjustmentFilterJSON VARCHAR(MAX), + @search VARCHAR(MAX) +) +RETURNS BIT + BEGIN + DECLARE @containsSearchString BIT = 0; + + IF ( + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.AgeCohort.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.Entity.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.MedicalSurgical.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.PatientClass.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.ServiceLine.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.ChargeCode.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.Department.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.Account.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.FinancialReporting.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.Payor.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.JobCode.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.JobCodeGroup.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.PayCodeGroup.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.ProductiveClass.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.Variability.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.ServiceLineRollup.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.BillingCPT.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.MSDRG.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.PerformingProvider.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.PerformingProviderSpecialty.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.PrimaryCPT.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.ServiceEntity.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.ServiceProvider.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.ServiceProviderSpecialty.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.UBRevCode.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.CPT.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.PayorGroup.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.PhysicianSpecialty.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.Provider.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.Employee.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.ProviderLineItem.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.ProviderType.Name')) LIKE @search ESCAPE '\' OR + LOWER(JSON_VALUE(@adjustmentFilterJSON, '$.ProviderSpecialty.Name')) LIKE @search ESCAPE '\' + ) + SET @containsSearchString = 1; + + RETURN @containsSearchString; + END +GO + + +--------------------------------------------- + +-- fp.funcCompareAdjustmentDateTime +CREATE FUNCTION [fp].[funcCompareAdjustmentDateTime] +( + @adjustmentDate DATETIME, + @search VARCHAR(MAX), + @dateTimeFormat VARCHAR(30), + @userTimeZone VARCHAR(50) +) +RETURNS BIT +/************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 2020-01-15 OP JAZZ-12268 Now skipping date check for search values that are containing "%" (that is modified into "\%" on backend) + *************************************************************/ + BEGIN + DECLARE @result BIT = 0 + + IF CHARINDEX('\%', @search) = 0 + BEGIN + + DECLARE @utcTimeZone VARCHAR(5) = 'UTC' + SET @adjustmentDate = @adjustmentDate AT TIME ZONE @utcTimeZone AT TIME ZONE @userTimeZone + + DECLARE @formatedAdjustmentDateTime VARCHAR(50) = FORMAT(@adjustmentDate, @dateTimeFormat) + DECLARE @pureSearchValue VARCHAR(50) + + SET @search = REPLACE(@search, '\', '') + SET @pureSearchValue = REPLACE(@search, '%', '') + + IF(@formatedAdjustmentDateTime LIKE @search + OR @formatedAdjustmentDateTime LIKE FORMAT(TRY_PARSE(@pureSearchValue AS DATETIME), @dateTimeFormat)) + BEGIN + SET @result = 1 + END + + END + + RETURN @result + END +GO + + +--------------------------------------------- + +-- fp.funcFindAdvancedPlanningTSQLPerformanceFlawsForMigration +CREATE FUNCTION [fp].[funcFindAdvancedPlanningTSQLPerformanceFlawsForMigration] ( + @MigrationName NVARCHAR(MAX) +) +RETURNS @Results TABLE ( + Name NVARCHAR(MAX), + ObjectType NVARCHAR(MAX), + Severity NVARCHAR(MAX), + Category NVARCHAR(MAX), + Description NVARCHAR(MAX) + ) +AS +BEGIN + + DECLARE @Sql NVARCHAR(MAX) = (SELECT ForwardScript FROM [migration].[MigrationLog] WHERE Name = @MigrationName AND SourceFolder = 'AP') + + INSERT INTO @Results(Name, Severity, ObjectType, Category, Description) + SELECT @MigrationName AS Name, CASE WHEN Severity = 3 THEN 'High' + WHEN Severity = 2 THEN 'Medium' + WHEN Severity = 1 THEN 'Low' ELSE 'N/A' END AS Severity, 'Migration' AS ObjectType, Category, Description + FROM [fp].[funcFindTSQLPerformanceFlaws_AdvancedPlanning] (@Sql) + + RETURN; +END +GO + + +--------------------------------------------- + +-- fp.funcFindRequestVersion +CREATE FUNCTION fp.funcFindRequestVersion(@date DATETIME) +RETURNS NVARCHAR(100) +AS +BEGIN + RETURN ( + SELECT TOP 1 [Version] + FROM [dbo].[UpgradeLog] + WHERE @date >= [LogDateUtc] + GROUP BY Version + ORDER BY Min([LogDateUtc]) DESC + ) +END +GO + + +--------------------------------------------- + +-- fp.funcFindTSQLPerformanceFlaws_AdvancedPlanning +CREATE FUNCTION [fp].[funcFindTSQLPerformanceFlaws_AdvancedPlanning] ( + @sql NVARCHAR(MAX) +) +RETURNS @Results TABLE ( + Severity SMALLINT, + Category NVARCHAR(MAX), + Description NVARCHAR(MAX) + ) +AS +BEGIN + + -- Rule 1 do not join on source dimensionality + IF (@sql LIKE '%INNER JOIN @SourceDimensionality%' OR + @sql LIKE '%INNER JOIN [fp].[funcGetSourceDimensionalityAsTable]%') + BEGIN + INSERT INTO @Results (Category, Description, Severity) VALUES ('Join on Targeting', 'Do not join on targeting obj, create a temporary table and join on that instead', 3) + END + + -- Rule 2 do not join with Department IS NULL + -- NOTE: This may have some false positives for real DepartmentID is null checks, but that shouldn't be many + IF (@sql LIKE '%DepartmentID IS NULL%') + BEGIN + INSERT INTO @Results (Category, Description, Severity) VALUES ('NULL Check on Department Targeting', 'Do not check for null within the join, seperate this out into 2 blocks', 3) + END + + RETURN; +END +GO + + +--------------------------------------------- + +-- fp.funcFormatColumnByMonth +CREATE FUNCTION fp.funcFormatColumnByMonth ( + @expression NVARCHAR(1000), + @month INT +) +RETURNS VARCHAR(2000) AS +BEGIN + -- if the month is less than 10, we need to add a 0 to the front of it. + RETURN @expression + CASE WHEN @month < 10 THEN '0' ELSE '' END + CAST(@month AS VARCHAR(2)) +END; +GO + + +--------------------------------------------- + +-- fp.funcGetChargeRate +CREATE FUNCTION [fp].[funcGetChargeRate] (@SelectedSortOrder INT, @BudgetConfigID INT) +RETURNS VARCHAR(250) +AS BEGIN + + DECLARE @ChargeMasterConfigJson NVARCHAR(MAX) = (SELECT ISNULL(ChargeMasterConfigJson, '') FROM [fp].[BudgetConfig] WHERE BudgetConfigID = @BudgetConfigID) + DECLARE @ChargeRateConfiguration TABLE (Name NVARCHAR(MAX), RateMonthID INT, FiscalMonthID INT) + + IF (@ChargeMasterConfigJson IS NOT NULL) + BEGIN + + -- Parse out the ChargeMasterJSON to a SQL readable format + INSERT INTO @ChargeRateConfiguration + SELECT REPLACE(NAME, 'EffectiveFiscalMonthID', '') as Name, REPLACE(REPLACE(NAME, 'EffectiveFiscalMonthID', ''), 'ChargeRate', '') AS RateMonthID, StringValue As FiscalMonthID + FROM dbo.parseJSON(@ChargeMasterConfigJson) + WHERE Name LIKE 'ChargeRate%' + + DECLARE @SortOrder INT, @FiscalMonthID INT, @CurrentRate INT = 1, @NextMonthEffective INT = 0; + DECLARE db_cursor CURSOR FOR SELECT SortOrder, FiscalMonthID FROM [fw].[DimFiscalMonth] WHERE FiscalMonthID != 0 ORDER BY SortOrder + + OPEN db_cursor + FETCH NEXT FROM db_cursor INTO @SortOrder, @FiscalMonthID + + WHILE @@FETCH_STATUS = 0 + BEGIN + + SET @NextMonthEffective = (SELECT FiscalMonthID FROM @ChargeRateConfiguration WHERE RateMonthID = @CurrentRate + 1); + + -- Need to check if the next month is 0, if it is all the rest of the months are going to be the current rate + -- If it is not 0, but not equal to the current fiscal month we can assume it's still the current rate. + IF (@NextMonthEffective = 0 OR @FiscalMonthID != @NextMonthEffective) + BEGIN + + -- We found the one we want, skip the rest and return + IF (@SelectedSortOrder = @SortOrder) + RETURN (SELECT Name FROM @ChargeRateConfiguration WHERE RateMonthID = @CurrentRate) + + -- Check if the current fiscal month matches the next effective FMID, if it does, that's now the current rate. + END ELSE IF (@FiscalMonthID = @NextMonthEffective) BEGIN + SET @CurrentRate = @CurrentRate + 1; + + -- We found the one we want, skip the rest and return + IF (@SelectedSortOrder = @SortOrder) + RETURN (SELECT Name FROM @ChargeRateConfiguration WHERE RateMonthID = @CurrentRate) + END + + FETCH NEXT FROM db_cursor INTO @SortOrder, @FiscalMonthID + END + + CLOSE db_cursor + DEALLOCATE db_cursor + + END + + -- Default + RETURN (SELECT TOP (1) Name FROM @ChargeRateConfiguration WHERE FiscalMonthID != 0 ORDER BY RateMonthID DESC) + +END +GO + + +--------------------------------------------- + +-- fp.funcGetClassificationsUsedOnAdjustments +CREATE FUNCTION [fp].[funcGetClassificationsUsedOnAdjustments] + (@budgetConfigGuid UNIQUEIDENTIFIER) +RETURNS @return_variable TABLE (ClassificationCategoryID INT, ClassificationGroupID INT) +as +BEGIN + + INSERT INTO @return_variable + SELECT ClassificationCategoryID, + ClassificationGroupID + FROM + ( + + SELECT ClassificationCategoryID, + ClassificationGroupID + FROM fp.ServiceLineEncounterAdjustment + WHERE BudgetConfigGUID = @budgetConfigGuid + AND ClassificationGroupID <> 0 + AND (GroupingGUID = '00000000-0000-0000-0000-000000000000' + OR AdjustmentType <> 0) + + UNION ALL + + SELECT ClassificationCategoryID, + ClassificationGroupID + FROM fp.DepartmentChargeVolumeAdjustment + WHERE BudgetConfigGUID = @budgetConfigGuid + AND ClassificationGroupID <> 0 + AND (GroupingGUID = '00000000-0000-0000-0000-000000000000' + OR AdjustmentType <> 0) + + UNION ALL + + SELECT ClassificationCategoryID, + ClassificationGroupID + FROM fp.StatisticsAdjustment + WHERE BudgetConfigGUID = @budgetConfigGuid + AND ClassificationGroupID <> 0 + AND (GroupingGUID = '00000000-0000-0000-0000-000000000000' + OR AdjustmentType <> 0) + + UNION ALL + + SELECT ClassificationCategoryID, + ClassificationGroupID + FROM fp.StaffingAdjustment + WHERE BudgetConfigGUID = @budgetConfigGuid + AND ClassificationGroupID <> 0 + AND (GroupingGUID = '00000000-0000-0000-0000-000000000000' + OR AdjustmentType <> 0) + + UNION ALL + + SELECT ClassificationCategoryID, + ClassificationGroupID + FROM fp.BenefitsAdjustment + WHERE BudgetConfigGUID = @budgetConfigGuid + AND ClassificationGroupID <> 0 + AND (GroupingGUID = '00000000-0000-0000-0000-000000000000' + OR AdjustmentType <> 0) + + UNION ALL + + SELECT ClassificationCategoryID, + ClassificationGroupID + FROM fp.GeneralLedgerAdjustment + WHERE BudgetConfigGUID = @budgetConfigGuid + AND ClassificationGroupID <> 0 + AND (GroupingGUID = '00000000-0000-0000-0000-000000000000' + OR AdjustmentType <> 0) + + UNION ALL + + -- Add Provider Adjustment's classification info (AdjustmentType = 15) is stored here + SELECT aps.ClassificationCategoryID, + aps.ClassificationGroupID + FROM fp.AddProviderSummary AS aps + JOIN fp.ServiceLineEncounterAdjustment AS slea ON slea.AdjustmentGUID = aps.SLEncounterAdjustmentGUID + WHERE slea.BudgetConfigGUID = @budgetConfigGuid + AND aps.ClassificationGroupID <> 0 + + UNION ALL + + SELECT saps.ClassificationCategoryID, + saps.ClassificationGroupID + FROM fp.StatisticAddProviderSummary AS saps + JOIN fp.StatisticsAdjustment AS sa ON sa.AdjustmentGUID = saps.DriverAdjustmentGUID + WHERE sa.BudgetConfigGUID = @budgetConfigGuid + AND saps.ClassificationGroupID <> 0 + ) res + GROUP BY ClassificationCategoryID, + ClassificationGroupID + + RETURN +END +GO + + +--------------------------------------------- + +-- fp.funcGetDifferencesBetweenConfigs_GeneralLedger +CREATE FUNCTION fp.funcGetDifferencesBetweenConfigs_GeneralLedger ( + @BudgetConfigBase INT, + @BudgetConfigComparer INT +) +RETURNS TABLE AS +RETURN SELECT + base.[GeneralLedgerID], + base.[BudgetConfigID], + base.[EntityGroupConfigID], + base.[EntityID], + e.Name AS Entity, + base.[DepartmentID], + d.Name AS Department, + base.[AccountID], + a.Name AS Account, + base.[FinancialReportingID], + fr.Name AS FinancialReporting, + base.[APEModelSectionID], + map.APEModelSectionName AS ModelSection, + base.[VariabilityID], + v.Name AS Variability, + base.[UnitTypeID], + ut.Name AS UnitType, + base.[TimeClassID], + base.[FiscalYearID], + base.[FiscalMonthID], + base.[LockType] AS SnapshotLockType, + comparer.OriginalValue AS SnapshotInitial, + comparer.Value AS SnapshotTarget, + comparer.ManagerValue AS SnapshotBudget, + comparer.[LockType] AS CurrentLockType, + base.OriginalValue AS CurrentInitial, + base.Value AS CurrentTarget, + base.ManagerValue AS CurrentBudget, + comparer.OriginalValue - base.OriginalValue As DifferenceInitial, + comparer.Value - base.Value As DifferenceTarget, + comparer.ManagerValue - base.ManagerValue As DifferenceBudget + FROM [fp].[viewFactGeneralLedger_Unpivoted_source] base + INNER JOIN [fp].[viewFactGeneralLedger_Unpivoted_source] comparer ON + base.DepartmentID = comparer.DepartmentID + AND base.EntityID = comparer.EntityID + AND base.AccountID = comparer.AccountID + AND base.FinancialReportingID = comparer.FinancialReportingID + AND base.VariabilityID = comparer.VariabilityID + AND base.FiscalMonthID = comparer.FiscalMonthID + AND base.TimeClassID = comparer.TimeClassID + AND base.UnitTypeID = comparer.UnitTypeID + INNER JOIN [fw].[DimEntity] e ON base.EntityID = e.EntityID + INNER JOIN [fw].[DimDepartment] d ON base.DepartmentID = d.DepartmentID + INNER JOIN [fw].[DimAccount] a ON base.AccountID = a.AccountID + INNER JOIN [ob].[DimFinancialReporting] fr ON base.FinancialReportingID = fr.FinancialReportingID + INNER JOIN [fw].[DimVariability] v ON base.VariabilityID = v.VariabilityID + INNER JOIN [fw].[DimUnitType] ut ON base.UnitTypeID = ut.UnitTypeID + INNER JOIN [fp].[ModelSectionMap] map ON base.APEModelSectionID = map.APEModelSectionID + WHERE base.BudgetConfigID = @BudgetConfigBase + AND comparer.BudgetConfigID = @BudgetConfigComparer +GO + + +--------------------------------------------- + +-- fp.funcGetDifferencesBetweenConfigs_Staffing +CREATE FUNCTION fp.funcGetDifferencesBetweenConfigs_Staffing ( + @BudgetConfigBase INT, + @BudgetConfigComparer INT +) +RETURNS TABLE AS +RETURN SELECT + base.[BudgetConfigID], + base.[EntityID], + e.Name AS Entity, + base.[DepartmentID], + d.Name AS Department, + base.[JobCodeID], + jc.Name AS JobCode, + base.[ProductiveClassID], + pc.Name AS ProductiveClass, + base.[PayCodeGroupID], + p.PayCodeGroupID AS PayCodeGroup, + base.[VariabilityID], + v.Name AS Variability, + base.[UnitTypeID], + ut.Name AS UnitType, + base.[TimeClassID], + base.[FiscalMonthID], + base.[FiscalYearID], + comparer.OriginalValue AS SnapshotInitial, + comparer.Value AS SnapshotTarget, + comparer.ManagerValue AS SnapshotBudget, + base.OriginalValue AS CurrentInitial, + base.Value AS CurrentTarget, + base.ManagerValue AS CurrentBudget, + comparer.OriginalValue - base.OriginalValue As DifferenceInitial, + comparer.Value - base.Value As DifferenceTarget, + comparer.ManagerValue - base.ManagerValue As DifferenceBudget + FROM [fp].[viewFactStaffing_Unpivoted_source] base + INNER JOIN [fp].[viewFactStaffing_Unpivoted_source] comparer ON + base.DepartmentID = comparer.DepartmentID + AND base.EntityID = comparer.EntityID + AND base.JobCodeID = comparer.JobCodeID + AND base.ProductiveClassID = comparer.ProductiveClassID + AND base.PayCodeGroupID = comparer.PayCodeGroupID + AND base.VariabilityID = comparer.VariabilityID + AND base.FiscalMonthID = comparer.FiscalMonthID + AND base.TimeClassID = comparer.TimeClassID + AND base.UnitTypeID = comparer.UnitTypeID + INNER JOIN [fw].[DimEntity] e ON base.EntityID = e.EntityID + INNER JOIN [fw].[DimDepartment] d ON base.DepartmentID = d.DepartmentID + INNER JOIN [fw].[DimJobCode] jc ON base.JobCodeID = jc.JobCodeID + INNER JOIN [fw].[DimProductiveClass] pc ON base.ProductiveClassID = pc.ProductiveClassID + INNER JOIN [fw].[DimPayCodeGroup] p ON base.PayCodeGroupID = p.PayCodeGroupID + INNER JOIN [fw].[DimVariability] v ON base.VariabilityID = v.VariabilityID + INNER JOIN [fw].[DimUnitType] ut ON base.UnitTypeID = ut.UnitTypeID + WHERE base.BudgetConfigID = @BudgetConfigBase + AND comparer.BudgetConfigID = @BudgetConfigComparer +GO + + +--------------------------------------------- + +-- fp.funcGetHistoryViewerGLFilter +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-12-13 IP B-20335 Created SP for Admin Plan - Details feature expansion - Backend +** 2 2018-08-29 IP fixed afetr clarification +*************************************************************/ +CREATE FUNCTION fp.funcGetHistoryViewerGLFilter (@StringToParse VARCHAR(max), @Prefix VARCHAR(50) = NULL) +RETURNS VARCHAR(MAX) +AS +BEGIN + DECLARE @ReturnLine VARCHAR(max) = '' + + SELECT @ReturnLine = @ReturnLine + ' AND ' + ISNULL(@Prefix+'.','')+ Component + FROM dbo.split(replace(@StringToParse, ' and ', '&'), '&') AS split + WHERE Component NOT LIKE '%FiscalMonthID%' and Component NOT LIKE '%UnitType%' + + RETURN @ReturnLine +END +GO + + +--------------------------------------------- + +-- fp.funcGetHistoryViewerMonthFilter +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-09-05 GF B-20335 Created +*************************************************************/ +CREATE FUNCTION fp.funcGetHistoryViewerMonthFilter (@FilterColumns VARCHAR(max)) +RETURNS INT +AS +BEGIN + declare @FilteredMonth int = 0 + SET @FilteredMonth = + ( + SELECT + MAX(ValueList) + FROM ( + SELECT + LTRIM(RTRIM(SUBSTRING(Component, CHARINDEX('=', Component, 1) + 1, 1000))) AS ValueList + FROM dbo.split(replace(@FilterColumns, ' and ', '&'), '&') AS split + WHERE Component LIKE '%FiscalMonthID%' + + UNION ALL + + SELECT 0 AS ValueList -- if Month is NOT present in filter + )X + ) + + RETURN @FilteredMonth +END +GO + + +--------------------------------------------- + +-- fp.funcGetMissingNonStaffingFlexConfigMappings +CREATE FUNCTION fp.funcGetMissingNonStaffingFlexConfigMappings (@EntityGroupConfigGUID UNIQUEIDENTIFIER, @DepartmentID INT, @AccountIDs SqlInt32ListTableType READONLY) + RETURNS @Result TABLE ( + DepartmentID INT, + GLAccountID INT, + StatAccountID INT ) + AS + BEGIN + DECLARE @BudgetConfigID INT; + SET @BudgetConfigID = (SELECT BudgetConfigID + FROM [fp].[EntityGroupConfig] ec + INNER JOIN [fp].[BudgetConfig] bc ON bc.BudgetConfigGUID = ec.BudgetConfigGUID + WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID) + + DECLARE @EntityGroupConfigID INT; + SET @EntityGroupConfigID = (SELECT EntityGroupConfigID + FROM [fp].[EntityGroupConfig] + WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID) + + INSERT INTO @Result(DepartmentID, GLAccountID, StatAccountID) + SELECT DISTINCT stat.DepartmentID, ns.AccountID AS GLAccountID, nso.AccountID AS StatAccountID + FROM [fp].[FactStatistics] stat + INNER JOIN [fp].[NonStaffingExpenseFlexingOverrideConfig] ns ON ns.DepartmentID = stat.DepartmentID + INNER JOIN [fp].[NSOverrideFlexConfigAssignment] nso ON nso.OverrideFlexConfigGUID = ns.OverrideFlexConfigGUID + INNER JOIN [fw].[DimAccount] a ON ns.AccountID = a.AccountID + INNER JOIN [ob].[DimAccountPH] aph ON a.OBAccountPHID = aph.AccountPHID + WHERE aph.Name = 'Expenses - Non-Staffing' + AND ns.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND stat.BudgetConfigID = @BudgetConfigID + AND ns.FlexMethodID = 1 + AND stat.DepartmentID = @DepartmentID + AND ns.AccountID IN ( Select value FROM @AccountIDs ) + + INSERT INTO @Result(DepartmentID, GLAccountID, StatAccountID) + SELECT DISTINCT stat.DepartmentID, acc.AccountID AS GLAccountID, stat.AccountID AS StatAccountID + FROM [fp].[FactStatistics] stat + INNER JOIN [fp].[PrimaryStatisticsConfig] fsc ON fsc.DepartmentID = stat.DepartmentID AND fsc.AccountID = stat.AccountID + INNER JOIN [fp].[EntityGroupConfig] egc ON egc.EntityGroupConfigGUID = fsc.EntityGroupConfigGUID + INNER JOIN [fp].[NonStaffingExpenseFlexingConfig] ns ON ns.DepartmentID = stat.DepartmentID + CROSS JOIN (SELECT AccountID FROM [fw].[DimAccount] WHERE OBModelSectionName LIKE '%Expenses - Non-Staffing%' AND AccountID IN ( Select value FROM @AccountIDs )) acc + LEFT JOIN (SELECT DepartmentID, AccountID FROM [fp].[NonStaffingExpenseFlexingOverrideConfig] WHERE EntityGroupConfigGUID = @EntityGroupConfigGUID) ovr + ON ovr.DepartmentID = stat.DepartmentID + AND ovr.AccountID = acc.AccountID + WHERE stat.DepartmentID = @DepartmentID + AND fsc.IsNonStaffing = 1 + AND fsc.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND ns.EntityGroupConfigGUID = @EntityGroupConfigGUID + AND stat.BudgetConfigID = @BudgetConfigID + AND ns.FlexMethodID = 1 + AND ovr.DepartmentID IS NULL; + + DELETE res + FROM @Result res + INNER JOIN [fp].[FlexConfigMapping] flex ON + res.DepartmentID = flex.DepartmentID + AND res.GLAccountID = flex.GLAccountID + AND res.StatAccountID = flex.StatAccountID + WHERE flex.FlexingTypeID = 1 -- NonStaffing + AND flex.DepartmentID = @DepartmentID + AND flex.EntityGroupConfigID = @EntityGroupConfigID + + RETURN + END +GO + + +--------------------------------------------- + +-- fp.funcGetSourceDimensionalityAsTable +CREATE FUNCTION fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY) +RETURNS @return_variable TABLE (DepartmentId int, EntityId int, BudgetPhaseId int) +as +BEGIN + INSERT INTO @return_variable (DepartmentID, BudgetPhaseID) + SELECT DepartmentID, BudgetPhaseID + FROM @SourceDimensionality + + UNION + + SELECT d.DepartmentID, sd.BudgetPhaseID + FROM fw.DimDepartment d + INNER JOIN @SourceDimensionality sd + ON sd.EntityID = d.EntityID + WHERE sd.DepartmentID IS NULL -- filter rows, where particular DepartmentID is set as specification of EntityID + + IF (select count(*) from @return_variable) = 0 + INSERT INTO @return_variable (DepartmentID) VALUES (NULL) + RETURN +END +GO + + +--------------------------------------------- + +-- fp.funcJSONUpdate_DeleteMeasureByName +CREATE FUNCTION fp.funcJSONUpdate_DeleteMeasureByName( + @configJSON NVARCHAR(MAX), + @measureNameToDelete NVARCHAR(MAX) + ) +RETURNS NVARCHAR(MAX) + +BEGIN + -- some variables that we would need + DECLARE + @oldMeasuresString NVARCHAR(MAX), + @key INT, + @newMeasure NVARCHAR(MAX) + + + DECLARE update_measures_cursor CURSOR FOR + SELECT tl.[value], tl.[key] + FROM OPENJSON(@configJSON, '$.measuresConfiguration.timeClassMeasures') AS tl + + + OPEN update_measures_cursor + + FETCH NEXT FROM update_measures_cursor INTO @oldMeasuresString, @key + + WHILE(@@FETCH_STATUS = 0) + BEGIN + + DECLARE @filteredMeasures NVARCHAR(MAX) = NULL + SELECT @filteredMeasures = CONCAT_WS(',', JSON_QUERY(@filteredMeasures), [value]) + FROM OPENJSON(@configJSON, '$.measuresConfiguration.timeClassMeasures[' + CAST(@key AS VARCHAR(3)) + '].measures') + CROSS APPLY OPENJSON([value]) + WITH(name NVARCHAR(100) '$.name') + WHERE name <> @measureNameToDelete + + SET @newMeasure = JSON_MODIFY(@oldMeasuresString, '$.measures', JSON_QUERY('['+ @filteredMeasures + ']')) + SET @configJSON = JSON_MODIFY(@configJSON, '$.measuresConfiguration.timeClassMeasures[' + CAST(@key AS VARCHAR(3)) + ']', JSON_QUERY(@newMeasure)) + + FETCH NEXT FROM update_measures_cursor into @oldMeasuresString, @key + END + + CLOSE update_measures_cursor + DEALLOCATE update_measures_cursor + + RETURN @configJSON + +END +GO + + +--------------------------------------------- + +-- fp.funcJSONUpdate_InsertNewMeasure +CREATE FUNCTION fp.funcJSONUpdate_InsertNewMeasure ( + @configJSON NVARCHAR(MAX), + @newMeasureObject NVARCHAR(MAX) +) +RETURNS NVARCHAR(MAX) + +BEGIN + + DECLARE + @oldMeasuresString NVARCHAR(MAX), + @key INT, + @newMeasure NVARCHAR(MAX), + @measureId INT + + + DECLARE update_measures_cursor CURSOR FOR + SELECT tl.[value], tl.[key] + FROM OPENJSON(@configJSON, '$.measuresConfiguration.timeClassMeasures') AS tl + + + OPEN update_measures_cursor + + FETCH NEXT FROM update_measures_cursor INTO @oldMeasuresString, @key + + WHILE(@@FETCH_STATUS = 0) + BEGIN + SELECT @measureId=MAX(tl.[id]) + FROM OPENJSON(@configJSON, '$.measuresConfiguration.timeClassMeasures[' + CAST(@key AS VARCHAR(3)) + '].measures') + WITH( + id int '$.id') AS tl + + SET @newMeasure= JSON_MODIFY(@oldMeasuresString, ' append $.measures', JSON_QUERY(JSON_MODIFY(@newMeasureObject, '$.id', @measureId+1))) + SET @configJSON = JSON_MODIFY(@configJSON, '$.measuresConfiguration.timeClassMeasures[' + CAST(@key AS VARCHAR(3)) + ']', JSON_QUERY(@newMeasure)) + FETCH NEXT FROM update_measures_cursor into @oldMeasuresString, @key + END + + CLOSE update_measures_cursor + DEALLOCATE update_measures_cursor + + RETURN @configJSON + +END +GO + + +--------------------------------------------- + +-- fp.viewDepartmentManagerNonStaffingUosQuery +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 3-30-2023 NT JAZZ-49042 Apply cross departmnet flexing change +*************************************************************/ +CREATE FUNCTION fp.viewDepartmentManagerNonStaffingUosQuery (@BudgetConfigID INT, @DepartmentID INT) + RETURNS @Result TABLE ( + BudgetConfigID INT, + EntityID INT, + DepartmentID INT, + AccountID INT, + BudgetPhaseID TINYINT, + AdjustedValue01 DECIMAL(19, 8), AdjustedValue02 DECIMAL(19, 8), AdjustedValue03 DECIMAL(19, 8), AdjustedValue04 DECIMAL(19, 8), AdjustedValue05 DECIMAL(19, 8), AdjustedValue06 DECIMAL(19, 8), AdjustedValue07 DECIMAL(19, 8), AdjustedValue08 DECIMAL(19, 8), AdjustedValue09 DECIMAL(19, 8), AdjustedValue10 DECIMAL(19, 8), AdjustedValue11 DECIMAL(19, 8), AdjustedValue12 DECIMAL(19, 8), AdjustedValueTotal DECIMAL(19, 8), + AdjustedProjectionValue01 DECIMAL(19, 8), AdjustedProjectionValue02 DECIMAL(19, 8), AdjustedProjectionValue03 DECIMAL(19, 8), AdjustedProjectionValue04 DECIMAL(19, 8), AdjustedProjectionValue05 DECIMAL(19, 8), AdjustedProjectionValue06 DECIMAL(19, 8), AdjustedProjectionValue07 DECIMAL(19, 8), AdjustedProjectionValue08 DECIMAL(19, 8), AdjustedProjectionValue09 DECIMAL(19, 8), AdjustedProjectionValue10 DECIMAL(19, 8), AdjustedProjectionValue11 DECIMAL(19, 8), AdjustedProjectionValue12 DECIMAL(19, 8), AdjustedProjectionValueTotal DECIMAL(19, 8)) + AS + BEGIN + +INSERT INTO @Result (BudgetConfigID, EntityID, DepartmentID, AccountID, BudgetPhaseID, + AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12, AdjustedValueTotal, + AdjustedProjectionValue01, AdjustedProjectionValue02, AdjustedProjectionValue03, AdjustedProjectionValue04, AdjustedProjectionValue05, AdjustedProjectionValue06, AdjustedProjectionValue07, AdjustedProjectionValue08, AdjustedProjectionValue09, AdjustedProjectionValue10, AdjustedProjectionValue11, AdjustedProjectionValue12, AdjustedProjectionValueTotal) + SELECT + sb.BudgetConfigID, sb.EntityID, psc.DepartmentID, fc.AccountID, dept.BudgetPhaseID, + ISNULL(SUM(sb.AdjustedValue01), 0) AS AdjustedValue01, ISNULL(SUM(sb.AdjustedValue02), 0) AS AdjustedValue02, ISNULL(SUM(sb.AdjustedValue03), 0) AS AdjustedValue03, ISNULL(SUM(sb.AdjustedValue04), 0) AS AdjustedValue04, ISNULL(SUM(sb.AdjustedValue05), 0) AS AdjustedValue05, ISNULL(SUM(sb.AdjustedValue06), 0) AS AdjustedValue06, ISNULL(SUM(sb.AdjustedValue07), 0) AS AdjustedValue07, ISNULL(SUM(sb.AdjustedValue08), 0) AS AdjustedValue08, ISNULL(SUM(sb.AdjustedValue09), 0) AS AdjustedValue09, ISNULL(SUM(sb.AdjustedValue10), 0) AS AdjustedValue10, ISNULL(SUM(sb.AdjustedValue11), 0) AS AdjustedValue11, ISNULL(SUM(sb.AdjustedValue12), 0) AS AdjustedValue12, ISNULL(SUM(sb.AdjustedValueTotal), 0) AS AdjustedValueTotal, + ISNULL(SUM(sb.AdjustedProjectionValue01), 0) AS AdjustedProjectionValue01, ISNULL(SUM(sb.AdjustedProjectionValue02), 0) AS AdjustedProjectionValue02, ISNULL(SUM(sb.AdjustedProjectionValue03), 0) AS AdjustedProjectionValue03, ISNULL(SUM(sb.AdjustedProjectionValue04), 0) AS AdjustedProjectionValue04, ISNULL(SUM(sb.AdjustedProjectionValue05), 0) AS AdjustedProjectionValue05, ISNULL(SUM(sb.AdjustedProjectionValue06), 0) AS AdjustedProjectionValue06, ISNULL(SUM(sb.AdjustedProjectionValue07), 0) AS AdjustedProjectionValue07, ISNULL(SUM(sb.AdjustedProjectionValue08), 0) AS AdjustedProjectionValue08, ISNULL(SUM(sb.AdjustedProjectionValue09), 0) AS AdjustedProjectionValue09, ISNULL(SUM(sb.AdjustedProjectionValue10), 0) AS AdjustedProjectionValue10, ISNULL(SUM(sb.AdjustedProjectionValue11), 0) AS AdjustedProjectionValue11, ISNULL(SUM(sb.AdjustedProjectionValue12), 0) AS AdjustedProjectionValue12, ISNULL(SUM(sb.AdjustedProjectionValueTotal), 0) AS AdjustedProjectionValueTotal + FROM fp.viewFactStatistics sb + INNER JOIN fp.viewFactStatistics dept on sb.StatisticsID = dept.StatisticsID + INNER JOIN [fp].[BudgetConfig] bc ON sb.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [fp].[EntityGroupConfig] egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN (SELECT primStats.DepartmentID, primStats.AccountID, COALESCE(src.DepartmentID, primStats.DepartmentID) AS SourceDepartmentID + FROM [fp].[PrimaryStatisticsConfig] primStats + LEFT JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] src + ON primStats.RowID = src.PrimaryStatisticsConfigID + WHERE primStats.IsNonStaffing = 1 + ) psc + ON psc.SourceDepartmentID = sb.DepartmentID + AND psc.AccountID = sb.AccountID + INNER JOIN [fp].[NonStaffingExpenseFlexingOverrideConfig] fc ON fc.DepartmentID = psc.DepartmentID AND fc.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + INNER JOIN [fp].[NSOverrideFlexConfigAssignment] assign ON fc.OverrideFlexConfigGUID = assign.OverrideFlexConfigGUID AND sb.AccountID = assign.AccountID + WHERE psc.DepartmentID = @DepartmentID + AND sb.BudgetConfigID = @BudgetConfigID + AND fc.FlexMethodID = 1 + AND dept.BudgetPhaseID = 3 + AND sb.BudgetPhaseID = 2 + GROUP BY sb.BudgetConfigID, sb.EntityID, psc.DepartmentID, fc.AccountID, dept.BudgetPhaseID + + + ;WITH groupedStats AS( + SELECT + sb.BudgetConfigID, sb.EntityID, psc.DepartmentID, dept.BudgetPhaseID, + ISNULL(SUM(sb.AdjustedValue01), 0) AS AdjustedValue01, ISNULL(SUM(sb.AdjustedValue02), 0) AS AdjustedValue02, ISNULL(SUM(sb.AdjustedValue03), 0) AS AdjustedValue03, ISNULL(SUM(sb.AdjustedValue04), 0) AS AdjustedValue04, ISNULL(SUM(sb.AdjustedValue05), 0) AS AdjustedValue05, ISNULL(SUM(sb.AdjustedValue06), 0) AS AdjustedValue06, ISNULL(SUM(sb.AdjustedValue07), 0) AS AdjustedValue07, ISNULL(SUM(sb.AdjustedValue08), 0) AS AdjustedValue08, ISNULL(SUM(sb.AdjustedValue09), 0) AS AdjustedValue09, ISNULL(SUM(sb.AdjustedValue10), 0) AS AdjustedValue10, ISNULL(SUM(sb.AdjustedValue11), 0) AS AdjustedValue11, ISNULL(SUM(sb.AdjustedValue12), 0) AS AdjustedValue12, ISNULL(SUM(sb.AdjustedValueTotal), 0) AS AdjustedValueTotal, + ISNULL(SUM(sb.AdjustedProjectionValue01), 0) AS AdjustedProjectionValue01, ISNULL(SUM(sb.AdjustedProjectionValue02), 0) AS AdjustedProjectionValue02, ISNULL(SUM(sb.AdjustedProjectionValue03), 0) AS AdjustedProjectionValue03, ISNULL(SUM(sb.AdjustedProjectionValue04), 0) AS AdjustedProjectionValue04, ISNULL(SUM(sb.AdjustedProjectionValue05), 0) AS AdjustedProjectionValue05, ISNULL(SUM(sb.AdjustedProjectionValue06), 0) AS AdjustedProjectionValue06, ISNULL(SUM(sb.AdjustedProjectionValue07), 0) AS AdjustedProjectionValue07, ISNULL(SUM(sb.AdjustedProjectionValue08), 0) AS AdjustedProjectionValue08, ISNULL(SUM(sb.AdjustedProjectionValue09), 0) AS AdjustedProjectionValue09, ISNULL(SUM(sb.AdjustedProjectionValue10), 0) AS AdjustedProjectionValue10, ISNULL(SUM(sb.AdjustedProjectionValue11), 0) AS AdjustedProjectionValue11, ISNULL(SUM(sb.AdjustedProjectionValue12), 0) AS AdjustedProjectionValue12, ISNULL(SUM(sb.AdjustedProjectionValueTotal), 0) AS AdjustedProjectionValueTotal + FROM fp.viewFactStatistics sb + INNER JOIN fp.viewFactStatistics dept on sb.StatisticsID = dept.StatisticsID + INNER JOIN [fp].[BudgetConfig] bc ON sb.BudgetConfigID = bc.BudgetConfigID + INNER JOIN [fp].[EntityGroupConfig] egc ON egc.BudgetConfigGUID = bc.BudgetConfigGUID + INNER JOIN (SELECT primStats.EntityGroupConfigGUID, primStats.DepartmentID, primStats.AccountID, COALESCE(src.DepartmentID, primStats.DepartmentID) AS SourceDepartmentID + FROM [fp].[PrimaryStatisticsConfig] primStats + LEFT JOIN [fp].[PrimaryStatisticsConfigSourceDepartments] src + ON primStats.RowID = src.PrimaryStatisticsConfigID + WHERE primStats.IsNonStaffing = 1 + ) psc + ON psc.SourceDepartmentID = sb.DepartmentID + AND psc.AccountID = sb.AccountID + AND psc.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + INNER JOIN [fp].[NonStaffingExpenseFlexingConfig] fc ON fc.DepartmentID = psc.DepartmentID AND fc.EntityGroupConfigGUID = egc.EntityGroupConfigGUID + WHERE psc.DepartmentID = @DepartmentID + AND sb.BudgetConfigID = @BudgetConfigID + AND fc.FlexMethodID = 1 + AND dept.BudgetPhaseID = 3 + AND sb.BudgetPhaseID = 2 + GROUP BY sb.BudgetConfigID, sb.EntityID, psc.DepartmentID, dept.BudgetPhaseID + ) + + INSERT INTO @Result (BudgetConfigID, EntityID, DepartmentID, AccountID, BudgetPhaseID, + AdjustedValue01, AdjustedValue02, AdjustedValue03, AdjustedValue04, AdjustedValue05, AdjustedValue06, AdjustedValue07, AdjustedValue08, AdjustedValue09, AdjustedValue10, AdjustedValue11, AdjustedValue12, AdjustedValueTotal, + AdjustedProjectionValue01, AdjustedProjectionValue02, AdjustedProjectionValue03, AdjustedProjectionValue04, AdjustedProjectionValue05, AdjustedProjectionValue06, AdjustedProjectionValue07, AdjustedProjectionValue08, AdjustedProjectionValue09, AdjustedProjectionValue10, AdjustedProjectionValue11, AdjustedProjectionValue12, AdjustedProjectionValueTotal) + SELECT + sb.BudgetConfigID, sb.EntityID, sb.DepartmentID, acc.AccountID, sb.BudgetPhaseID, + sb.AdjustedValue01, sb.AdjustedValue02, sb.AdjustedValue03, sb.AdjustedValue04, sb.AdjustedValue05, sb.AdjustedValue06, sb.AdjustedValue07, sb.AdjustedValue08, sb.AdjustedValue09, sb.AdjustedValue10, sb.AdjustedValue11, sb.AdjustedValue12, sb.AdjustedValueTotal, + sb.AdjustedProjectionValue01, sb.AdjustedProjectionValue02, sb.AdjustedProjectionValue03, sb.AdjustedProjectionValue04, sb.AdjustedProjectionValue05, sb.AdjustedProjectionValue06, sb.AdjustedProjectionValue07, sb.AdjustedProjectionValue08, sb.AdjustedProjectionValue09, sb.AdjustedProjectionValue10, sb.AdjustedProjectionValue11, sb.AdjustedProjectionValue12, sb.AdjustedProjectionValueTotal + FROM groupedStats sb + CROSS JOIN (SELECT AccountID FROM [fw].[DimAccount] WHERE OBModelSectionName LIKE '%Expenses - Non-Staffing%') acc + LEFT JOIN @Result uos ON uos.DepartmentID = sb.DepartmentID AND uos.BudgetConfigID = sb.BudgetConfigID + WHERE uos.BudgetConfigID IS NULL + + RETURN + END +GO + + +--------------------------------------------- + +-- fp.viewGetStatsByGeneralLedgerIDForFlexing +CREATE FUNCTION [fp].[viewGetStatsByGeneralLedgerIDForFlexing] ( + @EntityGroupConfigID INT, + @BudgetConfigID INT, + @FlexingTypeID INT, + @SourceDimensionality [fp].[BudgetRefreshSourceDimensionality] READONLY +) +RETURNS TABLE AS +RETURN ( + + /************************************************************** + ** Change History + ************************************************************** + ** CID Date Author WI Description + ** 1 02-28-2023 MY JAZZ-48980 Inital + ** 2 08-25-2023 MY JAZZ-59500 Updated view to restructure + *************************************************************/ + + -- Note, this was done so we didn't have to recreate the same logic in 3 different places + + WITH departmentFromTargeting AS ( + SELECT DepartmentID FROM fp.funcGetSourceDimensionalityAsTable (@SourceDimensionality) + ), departments AS ( + SELECT DepartmentID FROM departmentFromTargeting WHERE EXISTS (SELECT 1 FROM departmentFromTargeting WHERE DepartmentID IS NOT NULL) -- Targeted + UNION ALL + SELECT DISTINCT DepartmentID + FROM [fp].[GeneralLedger] d WITH (READUNCOMMITTED) + WHERE EntityGroupConfigID = @EntityGroupConfigID + AND FlexingTypeID = @FlexingTypeID + AND NOT EXISTS (SELECT 1 FROM departmentFromTargeting WHERE DepartmentID IS NOT NULL) -- Untargeted + ), glRecords AS ( + SELECT base.EntityGroupConfigID, base.GeneralLedgerID, base.DepartmentID, base.AccountID + FROM [fp].[GeneralLedger] base + INNER JOIN departments dept ON base.DepartmentID = dept.DepartmentID + WHERE base.EntityGroupConfigID = @EntityGroupConfigID + AND base.FlexingTypeID = @FlexingTypeID + AND base.VariabilityID = 2 + ), itemsToFlex AS ( + SELECT DISTINCT fsc.FlexingTypeID, fsc.DepartmentID, fsc.GLAccountID, fsc.StatAccountID, fsc.SourceDepartmentID + FROM [fp].[FlexConfigMapping] fsc + INNER JOIN glRecords fs ON fsc.DepartmentID = fs.DepartmentID AND fsc.GLAccountID = fs.AccountID + WHERE fsc.FlexingTypeID = @FlexingTypeID + AND fsc.EntityGroupConfigID = @EntityGroupConfigID + ), stats AS ( + -- Get the stats for each Source Department / Account combination + SELECT + fs.DepartmentID AS SourceDepartmentID, + fs.AccountID, + SUM(tgt.AdjustedValue01) AS TargetAdjustedValue01, + SUM(tgt.AdjustedValue02) AS TargetAdjustedValue02, + SUM(tgt.AdjustedValue03) AS TargetAdjustedValue03, + SUM(tgt.AdjustedValue04) AS TargetAdjustedValue04, + SUM(tgt.AdjustedValue05) AS TargetAdjustedValue05, + SUM(tgt.AdjustedValue06) AS TargetAdjustedValue06, + SUM(tgt.AdjustedValue07) AS TargetAdjustedValue07, + SUM(tgt.AdjustedValue08) AS TargetAdjustedValue08, + SUM(tgt.AdjustedValue09) AS TargetAdjustedValue09, + SUM(tgt.AdjustedValue10) AS TargetAdjustedValue10, + SUM(tgt.AdjustedValue11) AS TargetAdjustedValue11, + SUM(tgt.AdjustedValue12) AS TargetAdjustedValue12, + + SUM(bgt.AdjustedValue01) AS BudgetAdjustedValue01, + SUM(bgt.AdjustedValue02) AS BudgetAdjustedValue02, + SUM(bgt.AdjustedValue03) AS BudgetAdjustedValue03, + SUM(bgt.AdjustedValue04) AS BudgetAdjustedValue04, + SUM(bgt.AdjustedValue05) AS BudgetAdjustedValue05, + SUM(bgt.AdjustedValue06) AS BudgetAdjustedValue06, + SUM(bgt.AdjustedValue07) AS BudgetAdjustedValue07, + SUM(bgt.AdjustedValue08) AS BudgetAdjustedValue08, + SUM(bgt.AdjustedValue09) AS BudgetAdjustedValue09, + SUM(bgt.AdjustedValue10) AS BudgetAdjustedValue10, + SUM(bgt.AdjustedValue11) AS BudgetAdjustedValue11, + SUM(bgt.AdjustedValue12) AS BudgetAdjustedValue12, + + SUM(proj.AdjustedValue01) AS ProjectionAdjustedValue01, + SUM(proj.AdjustedValue02) AS ProjectionAdjustedValue02, + SUM(proj.AdjustedValue03) AS ProjectionAdjustedValue03, + SUM(proj.AdjustedValue04) AS ProjectionAdjustedValue04, + SUM(proj.AdjustedValue05) AS ProjectionAdjustedValue05, + SUM(proj.AdjustedValue06) AS ProjectionAdjustedValue06, + SUM(proj.AdjustedValue07) AS ProjectionAdjustedValue07, + SUM(proj.AdjustedValue08) AS ProjectionAdjustedValue08, + SUM(proj.AdjustedValue09) AS ProjectionAdjustedValue09, + SUM(proj.AdjustedValue10) AS ProjectionAdjustedValue10, + SUM(proj.AdjustedValue11) AS ProjectionAdjustedValue11, + SUM(proj.AdjustedValue12) AS ProjectionAdjustedValue12 + FROM [fp].[FactStatistics] fs + INNER JOIN (SELECT DISTINCT SourceDepartmentID, StatAccountID FROM itemsToFlex) fl ON fs.DepartmentID = fl.SourceDepartmentID + AND fl.StatAccountID = fs.AccountID + INNER JOIN [fp].[FactStatisticsBudget] tgt ON fs.StatisticsID = tgt.StatisticsID AND tgt.BudgetPhaseID = 2 + INNER JOIN [fp].[FactStatisticsBudget] bgt ON fs.StatisticsID = bgt.StatisticsID AND bgt.BudgetPhaseID = 3 + INNER JOIN [fp].[FactStatisticsProjection] proj ON fs.StatisticsID = proj.StatisticsID AND proj.BudgetPhaseID = 3 + WHERE fs.BudgetConfigID = @BudgetConfigID + GROUP BY fs.DepartmentID, + fs.AccountID + ), statsBySourceDept AS ( + -- Calculate the stats at an individual flex config level. + SELECT + fs.DepartmentID, + fs.SourceDepartmentID, + fs.StatAccountID, + fs.GLAccountID, + SUM(TargetAdjustedValue01) AS TargetAdjustedValue01, + SUM(TargetAdjustedValue02) AS TargetAdjustedValue02, + SUM(TargetAdjustedValue03) AS TargetAdjustedValue03, + SUM(TargetAdjustedValue04) AS TargetAdjustedValue04, + SUM(TargetAdjustedValue05) AS TargetAdjustedValue05, + SUM(TargetAdjustedValue06) AS TargetAdjustedValue06, + SUM(TargetAdjustedValue07) AS TargetAdjustedValue07, + SUM(TargetAdjustedValue08) AS TargetAdjustedValue08, + SUM(TargetAdjustedValue09) AS TargetAdjustedValue09, + SUM(TargetAdjustedValue10) AS TargetAdjustedValue10, + SUM(TargetAdjustedValue11) AS TargetAdjustedValue11, + SUM(TargetAdjustedValue12) AS TargetAdjustedValue12, + + SUM(BudgetAdjustedValue01) AS BudgetAdjustedValue01, + SUM(BudgetAdjustedValue02) AS BudgetAdjustedValue02, + SUM(BudgetAdjustedValue03) AS BudgetAdjustedValue03, + SUM(BudgetAdjustedValue04) AS BudgetAdjustedValue04, + SUM(BudgetAdjustedValue05) AS BudgetAdjustedValue05, + SUM(BudgetAdjustedValue06) AS BudgetAdjustedValue06, + SUM(BudgetAdjustedValue07) AS BudgetAdjustedValue07, + SUM(BudgetAdjustedValue08) AS BudgetAdjustedValue08, + SUM(BudgetAdjustedValue09) AS BudgetAdjustedValue09, + SUM(BudgetAdjustedValue10) AS BudgetAdjustedValue10, + SUM(BudgetAdjustedValue11) AS BudgetAdjustedValue11, + SUM(BudgetAdjustedValue12) AS BudgetAdjustedValue12, + + SUM(ProjectionAdjustedValue01) AS ProjectionAdjustedValue01, + SUM(ProjectionAdjustedValue02) AS ProjectionAdjustedValue02, + SUM(ProjectionAdjustedValue03) AS ProjectionAdjustedValue03, + SUM(ProjectionAdjustedValue04) AS ProjectionAdjustedValue04, + SUM(ProjectionAdjustedValue05) AS ProjectionAdjustedValue05, + SUM(ProjectionAdjustedValue06) AS ProjectionAdjustedValue06, + SUM(ProjectionAdjustedValue07) AS ProjectionAdjustedValue07, + SUM(ProjectionAdjustedValue08) AS ProjectionAdjustedValue08, + SUM(ProjectionAdjustedValue09) AS ProjectionAdjustedValue09, + SUM(ProjectionAdjustedValue10) AS ProjectionAdjustedValue10, + SUM(ProjectionAdjustedValue11) AS ProjectionAdjustedValue11, + SUM(ProjectionAdjustedValue12) AS ProjectionAdjustedValue12 + FROM itemsToFlex fs + INNER JOIN stats st ON fs.SourceDepartmentID = st.SourceDepartmentID AND fs.StatAccountID = st.AccountID + GROUP BY fs.DepartmentID, + fs.SourceDepartmentID, + fs.StatAccountID, + fs.GLAccountID + ) + SELECT + uos.GeneralLedgerID, + SUM(stat.TargetAdjustedValue01) As TargetStats01, + SUM(stat.TargetAdjustedValue02) As TargetStats02, + SUM(stat.TargetAdjustedValue03) As TargetStats03, + SUM(stat.TargetAdjustedValue04) As TargetStats04, + SUM(stat.TargetAdjustedValue05) As TargetStats05, + SUM(stat.TargetAdjustedValue06) As TargetStats06, + SUM(stat.TargetAdjustedValue07) As TargetStats07, + SUM(stat.TargetAdjustedValue08) As TargetStats08, + SUM(stat.TargetAdjustedValue09) As TargetStats09, + SUM(stat.TargetAdjustedValue10) As TargetStats10, + SUM(stat.TargetAdjustedValue11) As TargetStats11, + SUM(stat.TargetAdjustedValue12) As TargetStats12, + + SUM(stat.BudgetAdjustedValue01) As BudgetStats01, + SUM(stat.BudgetAdjustedValue02) As BudgetStats02, + SUM(stat.BudgetAdjustedValue03) As BudgetStats03, + SUM(stat.BudgetAdjustedValue04) As BudgetStats04, + SUM(stat.BudgetAdjustedValue05) As BudgetStats05, + SUM(stat.BudgetAdjustedValue06) As BudgetStats06, + SUM(stat.BudgetAdjustedValue07) As BudgetStats07, + SUM(stat.BudgetAdjustedValue08) As BudgetStats08, + SUM(stat.BudgetAdjustedValue09) As BudgetStats09, + SUM(stat.BudgetAdjustedValue10) As BudgetStats10, + SUM(stat.BudgetAdjustedValue11) As BudgetStats11, + SUM(stat.BudgetAdjustedValue12) As BudgetStats12, + + SUM(stat.ProjectionAdjustedValue01) As ProjectionStats01, + SUM(stat.ProjectionAdjustedValue02) As ProjectionStats02, + SUM(stat.ProjectionAdjustedValue03) As ProjectionStats03, + SUM(stat.ProjectionAdjustedValue04) As ProjectionStats04, + SUM(stat.ProjectionAdjustedValue05) As ProjectionStats05, + SUM(stat.ProjectionAdjustedValue06) As ProjectionStats06, + SUM(stat.ProjectionAdjustedValue07) As ProjectionStats07, + SUM(stat.ProjectionAdjustedValue08) As ProjectionStats08, + SUM(stat.ProjectionAdjustedValue09) As ProjectionStats09, + SUM(stat.ProjectionAdjustedValue10) As ProjectionStats10, + SUM(stat.ProjectionAdjustedValue11) As ProjectionStats11, + SUM(stat.ProjectionAdjustedValue12) As ProjectionStats12 + FROM (SELECT DISTINCT f.DepartmentID, f.GLAccountID, f.StatAccountID FROM itemsToFlex f) fm + INNER JOIN glRecords uos ON uos.DepartmentID = fm.DepartmentID AND uos.AccountID = fm.GLAccountID + INNER JOIN statsBySourceDept stat ON fm.StatAccountID = stat.StatAccountID + AND fm.DepartmentID = stat.DepartmentID + AND uos.AccountID = stat.GLAccountID + GROUP BY uos.GeneralLedgerID +) +GO + + +--------------------------------------------- + diff --git a/ef-migration/infrastructure/sql-server/schemas/fp_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/schemas/fp_schema_database_statements_small.sql new file mode 100644 index 0000000..fc7d130 --- /dev/null +++ b/ef-migration/infrastructure/sql-server/schemas/fp_schema_database_statements_small.sql @@ -0,0 +1,40 @@ +-- SCHEMA: fp + +--------------------------------------------- +-- TABLES +--------------------------------------------- + + +--------------------------------------------- +-- fp.APAdminPerformanceTest ------------------ +--------------------------------------------- +CREATE TABLE [fp].[APAdminPerformanceTest] ( + [TestID] uniqueidentifier NOT NULL, + [SortOrder] int NOT NULL, + [TestTypeID] tinyint NOT NULL, + [TestName] nvarchar(100) NOT NULL, + [Description] nvarchar(3000) NOT NULL, + [BudgetConfigID] int NOT NULL, + [SourceDimensionalityJSON] nvarchar(max) NOT NULL, + [TestDetailJSON] nvarchar(max) NOT NULL, + [IsActive] bit NOT NULL, + [CreatedBy] nvarchar(1000) NOT NULL, + [Target] int NOT NULL, + [MaximumTheshold] int NOT NULL, + [PickableDepartments] nvarchar(max) NOT NULL, + PRIMARY KEY ([TestID]) +); +GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Targe__5375AD4D] DEFAULT ((0)) FOR [Target]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Maxim__5469D186] DEFAULT ((0)) FOR [MaximumTheshold]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Picka__565219F8] DEFAULT ('') FOR [PickableDepartments]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__TestI__6B4249E6] DEFAULT (newid()) FOR [TestID]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__SortO__6C366E1F] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__TestT__6D2A9258] DEFAULT ((0)) FOR [TestTypeID]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__TestN__6E1EB691] DEFAULT ('') FOR [TestName]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Descr__6F12DACA] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Budge__70FB233C] DEFAULT ((0)) FOR [BudgetConfigID]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Sourc__71EF4775] DEFAULT ('') FOR [SourceDimensionalityJSON]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__TestD__72E36BAE] DEFAULT ('') FOR [TestDetailJSON]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__IsAct__73D78FE7] DEFAULT ((0)) FOR [IsActive]; GO +ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Creat__74CBB420] DEFAULT ('') FOR [CreatedBy]; GO diff --git a/ef-migration/infrastructure/sql-server/schemas/fw_schema_database_statements.sql b/ef-migration/infrastructure/sql-server/schemas/fw_schema_database_statements.sql new file mode 100644 index 0000000..e6c3023 --- /dev/null +++ b/ef-migration/infrastructure/sql-server/schemas/fw_schema_database_statements.sql @@ -0,0 +1,31821 @@ +-- SCHEMA: fw + +--------------------------------------------- +-- TABLES +--------------------------------------------- + + +--------------------------------------------- +-- fw.ABBBudgetedCostPerRVU ------------------ +--------------------------------------------- +CREATE TABLE [fw].[ABBBudgetedCostPerRVU] ( + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeID] int NOT NULL, + [CostComponentID] int NOT NULL, + [CostingConfigGuid] uniqueidentifier NOT NULL, + [VariableDirectUnitCostPerRVU] decimal NULL, + [TotalVariableDirectCost] decimal NULL, + [TotalCost] decimal NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.ABBFlexingReconciliation ------------------ +--------------------------------------------- +CREATE TABLE [fw].[ABBFlexingReconciliation] ( + [RowID] int NOT NULL, + [CostingConfigGUID] uniqueidentifier NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [AccountID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeID] int NOT NULL, + [CostComponentID] int NOT NULL, + [ActualChargeUnits] decimal NOT NULL, + [ActualChargeUnitsYTD] decimal NOT NULL, + [ActualVariableDirectCost] decimal NOT NULL, + [ActualVariableDirectCostYTD] decimal NOT NULL, + [ActualFixedDirectCost] decimal NOT NULL, + [ActualFixedDirectCostYTD] decimal NOT NULL, + [BudgetChargeUnits] decimal NOT NULL, + [BudgetChargeUnitsYTD] decimal NOT NULL, + [BudgetVariableDirectCost] decimal NOT NULL, + [BudgetVariableDirectCostYTD] decimal NOT NULL, + [BudgetFixedDirectCost] decimal NOT NULL, + [BudgetFixedDirectCostYTD] decimal NOT NULL, + [FlexedVariableDirectCost] decimal NOT NULL, + [FlexedVariableDirectCostYTD] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [IX_Unique] ON [fw].[ABBFlexingReconciliation] ([CostingConfigGUID], [FiscalYearID], [FiscalMonthID], [EntityID], [DepartmentID], [ChargeCodeID], [AccountID], [JobCodeID], [PayCodeID], [CostComponentID]); +GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Costi__2637F561] DEFAULT (newid()) FOR [CostingConfigGUID]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Fisca__272C199A] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Fisca__28203DD3] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Entit__2914620C] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Depar__2A088645] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Charg__2AFCAA7E] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Accou__2BF0CEB7] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__JobCo__2CE4F2F0] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__PayCo__2DD91729] DEFAULT ((0)) FOR [PayCodeID]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__CostC__2ECD3B62] DEFAULT ((0)) FOR [CostComponentID]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Actua__2FC15F9B] DEFAULT ((0)) FOR [ActualChargeUnits]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Actua__30B583D4] DEFAULT ((0)) FOR [ActualChargeUnitsYTD]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Actua__31A9A80D] DEFAULT ((0)) FOR [ActualVariableDirectCost]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Actua__329DCC46] DEFAULT ((0)) FOR [ActualVariableDirectCostYTD]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Actua__3391F07F] DEFAULT ((0)) FOR [ActualFixedDirectCost]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Actua__348614B8] DEFAULT ((0)) FOR [ActualFixedDirectCostYTD]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Budge__357A38F1] DEFAULT ((0)) FOR [BudgetChargeUnits]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Budge__366E5D2A] DEFAULT ((0)) FOR [BudgetChargeUnitsYTD]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Budge__37628163] DEFAULT ((0)) FOR [BudgetVariableDirectCost]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Budge__3856A59C] DEFAULT ((0)) FOR [BudgetVariableDirectCostYTD]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Budge__394AC9D5] DEFAULT ((0)) FOR [BudgetFixedDirectCost]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Budge__3A3EEE0E] DEFAULT ((0)) FOR [BudgetFixedDirectCostYTD]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Flexe__3B331247] DEFAULT ((0)) FOR [FlexedVariableDirectCost]; GO +ALTER TABLE [fw].[ABBFlexingReconciliation] ADD CONSTRAINT [DF__ABBFlexin__Flexe__3C273680] DEFAULT ((0)) FOR [FlexedVariableDirectCostYTD]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.ABBFlexingReconciliationCostingData ------------------ +--------------------------------------------- +CREATE TABLE [fw].[ABBFlexingReconciliationCostingData] ( + [CostingConfigGUID] uniqueidentifier NOT NULL, + [EntityID] int NOT NULL, + [OriginalDepartmentID] int NOT NULL, + [OriginalJobCodeID] int NOT NULL, + [OriginalPayCodeID] int NOT NULL, + [OriginalAccountID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [FiscalYearID] int NOT NULL, + [FiscalMonthID] int NOT NULL, + [CostComponentID] int NOT NULL, + [FixedDirectUnitCost] decimal NOT NULL, + [VariableDirectUnitCost] decimal NOT NULL, + [BudgetFixedDirectUnitCost] decimal NOT NULL, + [BudgetVariableDirectUnitCost] decimal NOT NULL, + [ActualMonthlyVolume] decimal NOT NULL, + [BudgetedMonthlyVolume] decimal NOT NULL, + [RVU] money NOT NULL +); + +CREATE NONCLUSTERED INDEX [IX_BudgetedMonthlyVolume] ON [fw].[ABBFlexingReconciliationCostingData] ([CostingConfigGUID], [OriginalDepartmentID], [OriginalJobCodeID], [OriginalPayCodeID], [OriginalAccountID], [ChargeCodeID], [FiscalYearID], [CostComponentID], [FiscalMonthID]) INCLUDE ([BudgetFixedDirectUnitCost], [BudgetedMonthlyVolume]); +CREATE NONCLUSTERED INDEX [IX_OriginalDepartmentID] ON [fw].[ABBFlexingReconciliationCostingData] ([OriginalDepartmentID]) INCLUDE ([CostingConfigGUID], [EntityID], [OriginalJobCodeID], [OriginalPayCodeID], [OriginalAccountID], [ChargeCodeID], [FiscalYearID], [FiscalMonthID], [CostComponentID], [FixedDirectUnitCost], [VariableDirectUnitCost], [BudgetFixedDirectUnitCost], [BudgetVariableDirectUnitCost], [ActualMonthlyVolume], [BudgetedMonthlyVolume]); +CREATE NONCLUSTERED INDEX [IX_viewABBFlexingReconciliation] ON [fw].[ABBFlexingReconciliationCostingData] ([EntityID], [OriginalDepartmentID], [ChargeCodeID], [FiscalYearID], [FiscalMonthID]) INCLUDE ([CostingConfigGUID], [OriginalJobCodeID], [OriginalPayCodeID], [OriginalAccountID], [CostComponentID], [FixedDirectUnitCost], [VariableDirectUnitCost], [BudgetFixedDirectUnitCost], [BudgetVariableDirectUnitCost], [ActualMonthlyVolume], [BudgetedMonthlyVolume]); +CREATE NONCLUSTERED INDEX [IX_ABBFlexingReconciliationCostingData_Perf1] ON [fw].[ABBFlexingReconciliationCostingData] ([CostingConfigGUID], [EntityID], [OriginalDepartmentID], [OriginalJobCodeID], [OriginalPayCodeID], [OriginalAccountID], [ChargeCodeID], [FiscalYearID], [CostComponentID], [FiscalMonthID]) INCLUDE ([BudgetFixedDirectUnitCost], [BudgetedMonthlyVolume]); +CREATE NONCLUSTERED INDEX [IX_ABBFlexingReconciliationCostingData_Perf2] ON [fw].[ABBFlexingReconciliationCostingData] ([CostingConfigGUID], [OriginalDepartmentID], [OriginalAccountID], [ChargeCodeID], [FiscalYearID]) INCLUDE ([EntityID], [OriginalJobCodeID], [OriginalPayCodeID], [FiscalMonthID], [CostComponentID], [FixedDirectUnitCost], [VariableDirectUnitCost], [BudgetFixedDirectUnitCost], [BudgetVariableDirectUnitCost], [ActualMonthlyVolume], [BudgetedMonthlyVolume], [RVU]); +GO +ALTER TABLE [fw].[ABBFlexingReconciliationCostingData] ADD CONSTRAINT [DF__ABBFlexingR__RVU__4C32B5C0] DEFAULT ((0.0)) FOR [RVU]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.ABBFlexingReconciliationEncounterInfoData ------------------ +--------------------------------------------- +CREATE TABLE [fw].[ABBFlexingReconciliationEncounterInfoData] ( + [DepartmentID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [FiscalYearID] int NOT NULL, + [PatientClassID] int NOT NULL, + [FiscalMonthID] int NOT NULL, + [EncounterCount] int NOT NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DepartmentChargeCodePrimaryStatisticMappingCache ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DepartmentChargeCodePrimaryStatisticMappingCache] ( + [RowID] bigint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [DepartmentID] int NOT NULL, + [OriginalDepartmentID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [PatientTypeRollupID] int NOT NULL, + [AccountID] int NOT NULL, + [Weight] decimal NOT NULL, + [IsStaffing] bit NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE NONCLUSTERED INDEX [CORE_OriginalDepartmentID_FiscalYearID_ChargeCodeID_PatientTypeRollupID_IsStaffing] ON [fw].[DepartmentChargeCodePrimaryStatisticMappingCache] ([OriginalDepartmentID], [FiscalYearID], [ChargeCodeID], [PatientTypeRollupID], [IsStaffing]); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DepartmentChargeCodeStatisticMapping ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DepartmentChargeCodeStatisticMapping] ( + [RowID] bigint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [DepartmentRollupLevelMemberID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [PatientTypeRollupID] tinyint NOT NULL, + [AccountID] int NOT NULL, + [Weight] decimal NOT NULL, + [IsReviewed] bit NOT NULL, + [DepartmentRollupLevelMemberColumnName] nvarchar(64) NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fw].[DepartmentChargeCodeStatisticMapping] ADD CONSTRAINT [FK__Departmen__Charg__67D1ABB5] FOREIGN KEY ([ChargeCodeID]) REFERENCES [fw].[DimChargeCode] ([ChargeCodeID]); GO +ALTER TABLE [fw].[DepartmentChargeCodeStatisticMapping] ADD CONSTRAINT [DF_DepartmentChargeCodeStatisticMapping_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fw].[DepartmentChargeCodeStatisticMapping] ADD CONSTRAINT [DF_DepartmentChargeCodeStatisticMapping_DepartmentID] DEFAULT ((0)) FOR [DepartmentRollupLevelMemberID]; GO +ALTER TABLE [fw].[DepartmentChargeCodeStatisticMapping] ADD CONSTRAINT [DF_DepartmentChargeCodeStatisticMapping_ChargeCodeID] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [fw].[DepartmentChargeCodeStatisticMapping] ADD CONSTRAINT [DF_DepartmentChargeCodeStatisticMapping_PatientTypeRollupID] DEFAULT ((0)) FOR [PatientTypeRollupID]; GO +ALTER TABLE [fw].[DepartmentChargeCodeStatisticMapping] ADD CONSTRAINT [DF_DepartmentChargeCodeStatisticMapping_AccountID] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fw].[DepartmentChargeCodeStatisticMapping] ADD CONSTRAINT [DF_DepartmentChargeCodeStatisticMapping_Weight] DEFAULT ((0)) FOR [Weight]; GO +ALTER TABLE [fw].[DepartmentChargeCodeStatisticMapping] ADD CONSTRAINT [DF_DepartmentChargeCodeStatisticMapping_DepartmentRollupLevelMemberColumnName] DEFAULT ('DepartmentID') FOR [DepartmentRollupLevelMemberColumnName]; GO +ALTER TABLE [fw].[DepartmentChargeCodeStatisticMapping] ADD CONSTRAINT [DF_DepartmentChargeCodeStatisticMapping_IsReviewed] DEFAULT ((0)) FOR [IsReviewed]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DepartmentChargeCodeStatisticMappingCache ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DepartmentChargeCodeStatisticMappingCache] ( + [FiscalYearID] smallint NOT NULL, + [DepartmentID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [PatientTypeRollupID] int NOT NULL, + [AccountID] int NOT NULL, + [Weight] decimal NOT NULL +); + +CREATE NONCLUSTERED INDEX [NCNU_DepartmentFisclaYearAccount] ON [fw].[DepartmentChargeCodeStatisticMappingCache] ([DepartmentID], [FiscalYearID], [AccountID]) INCLUDE ([ChargeCodeID], [PatientTypeRollupID], [Weight]); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DepartmentChargeCodeStatisticMappingStaffingCache ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DepartmentChargeCodeStatisticMappingStaffingCache] ( + [RowID] bigint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [DepartmentID] int NOT NULL, + [OriginalDepartmentID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [PatientTypeRollupID] int NOT NULL, + [AccountID] int NOT NULL, + [Weight] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE NONCLUSTERED INDEX [CORE_OriginalDepartmentID_FiscalYearID_ChargeCodeID_PatientTypeRollupID] ON [fw].[DepartmentChargeCodeStatisticMappingStaffingCache] ([OriginalDepartmentID], [FiscalYearID], [ChargeCodeID], [PatientTypeRollupID]); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DepartmentRollup ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DepartmentRollup] ( + [DepartmentRollupLevelID] tinyint NOT NULL, + [Description] nvarchar(100) NOT NULL, + PRIMARY KEY ([DepartmentRollupLevelID]) +); +GO +ALTER TABLE [fw].[DepartmentRollup] ADD CONSTRAINT [CHK_FW_DepartmentRollup_DepartmentRollupLevelID] CHECK ([DepartmentRollupLevelID]>=(1) AND [DepartmentRollupLevelID]<=(9)); GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimAccount ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimAccount] ( + [AccountID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [AccountCode] nvarchar(40) NULL, + [Description] nvarchar(80) NOT NULL, + [GLRollup] nvarchar(100) NOT NULL, + [IsInverted] bit NOT NULL, + [Inversion] int NOT NULL, + [PatientClassID] int NOT NULL, + [PatientClass] nvarchar(100) NOT NULL, + [CAPIsDefined] bit NOT NULL, + [DSSIsDefined] bit NOT NULL, + [DSSCostComponent] nvarchar(50) NOT NULL, + [DSSStatisticDriver] nvarchar(50) NOT NULL, + [DSSAccountRollup1ID] int NOT NULL, + [DSSAccountRollup1Name] nvarchar(100) NOT NULL, + [DSSAccountRollup1Category] nvarchar(100) NOT NULL, + [DSSAccountRollup2ID] int NOT NULL, + [DSSAccountRollup2Name] nvarchar(100) NOT NULL, + [DSSAccountRollup3ID] int NOT NULL, + [DSSAccountRollup3Name] nvarchar(100) NOT NULL, + [MRIsDefined] bit NOT NULL, + [FlexStatistic] nvarchar(100) NOT NULL, + [FlexValue] money NOT NULL, + [FlexBucketGUID] uniqueidentifier NOT NULL, + [OBIsDefined] bit NOT NULL, + [IsStat] bit NOT NULL, + [IsGlobal] bit NOT NULL, + [IsExpense] bit NOT NULL, + [Variability] money NOT NULL, + [OBDollarsFinancialReportingID] int NOT NULL, + [OBDollarsFinancialReporting] varchar(200) NOT NULL, + [OBDollarsFinancialReportingCategory] nvarchar(100) NOT NULL, + [OBDollarsFinancialReportingLineName] nvarchar(100) NOT NULL, + [OBDollarsFinancialReportingSortOrder] int NOT NULL, + [OBUnitsFinancialReportingID] int NOT NULL, + [OBUnitsFinancialReporting] varchar(200) NOT NULL, + [OBUnitsFinancialReportingCategory] nvarchar(100) NOT NULL, + [OBUnitsFinancialReportingLineName] nvarchar(100) NOT NULL, + [OBUnitsFinancialReportingSortOrder] int NOT NULL, + [OBAccountPHID] int NOT NULL, + [OBModelSectionName] nvarchar(100) NOT NULL, + [OBStatModelSectionID] int NOT NULL, + [OBStatModelSectionName] nvarchar(100) NOT NULL, + [OBStatUnitTypeID] tinyint NOT NULL, + [OBUnitType] nvarchar(100) NOT NULL, + [OBPayorID] int NOT NULL, + [OBPayor] nvarchar(100) NOT NULL, + [OBPayorGroupID] int NOT NULL, + [OBPayorGroup] nvarchar(100) NOT NULL, + [SPIsDefined] bit NOT NULL, + [PatientTypeRollupID] tinyint NOT NULL, + [PatientTypeRollupName] nvarchar(200) NOT NULL, + [SPAccountRollupID] int NOT NULL, + [SPAccountRollupName] nvarchar(200) NOT NULL, + [SPStatAccountRollup] int NOT NULL, + [SPStatAccountRollupName] nvarchar(100) NOT NULL, + [SPAccountRollupCategory] nvarchar(100) NOT NULL, + [SPPayorGroupID] int NOT NULL, + [SPPayorGroupName] nvarchar(200) NOT NULL, + [SPPhysicianGroupID] int NOT NULL, + [SPPhysicianGroupName] nvarchar(200) NOT NULL, + [SPJobCodeGroupID] int NOT NULL, + [SPJobCodeGroupName] nvarchar(200) NOT NULL, + [SPCapitalRollupID] int NOT NULL, + [SPCapitalRollupName] nvarchar(200) NOT NULL, + [SPDebtIssuanceID] int NOT NULL, + [SPDebtIssuanceName] nvarchar(200) NOT NULL, + [SPIsPhysicianOverride] bit NOT NULL, + [PatientTypeID] int NOT NULL, + [OBStaffing] nvarchar(100) NOT NULL, + [TransactionID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [DSSAccountRollup4ID] int NOT NULL, + [DSSAccountRollup4] varchar(100) NOT NULL, + [DSSAccountRollup4Name] varchar(200) NOT NULL, + [Name] nvarchar(123) NOT NULL, + [DSSAccountRollup2Category] nvarchar(100) NOT NULL, + [DSSAccountRollup3Category] nvarchar(100) NOT NULL, + [DSSAccountRollup4Category] varchar(200) NOT NULL, + [FWIsDefined] bit NOT NULL, + [AccountCodeRaw] nvarchar(100) NOT NULL, + [GMAccountRollup1] nvarchar(200) NOT NULL, + [GMAccountRollup2] nvarchar(200) NOT NULL, + [GMAccountRollup3] nvarchar(200) NOT NULL, + [GMAccountRollup4] nvarchar(200) NOT NULL, + [GMAccountRollup5] nvarchar(200) NOT NULL, + [GMAccountRollup6] nvarchar(200) NOT NULL, + [DSSAccountRollup5ID] int NOT NULL, + [DSSAccountRollup5Name] nvarchar(100) NOT NULL, + [DSSAccountRollup6ID] int NOT NULL, + [DSSAccountRollup6Name] nvarchar(100) NOT NULL, + [DSSAccountRollup7ID] int NOT NULL, + [DSSAccountRollup7Name] nvarchar(100) NOT NULL, + [SPHAccountRollupID] int NOT NULL, + [SPHAccountRollupName] varchar(606) NOT NULL, + [SPHAccountRollupConfidenceScore] float NOT NULL, + [SPHVariability] decimal NOT NULL, + [SPHCostComponent] nvarchar(400) NOT NULL, + [SPHCostComponentRollup] nvarchar(400) NOT NULL, + [GMAccountRollup7] nvarchar(200) NOT NULL, + [IsSPHCostModel] bit NOT NULL, + [SPHLineItem] nvarchar(200) NOT NULL, + [SPHStatement] nvarchar(200) NOT NULL, + [SPHCategory] nvarchar(200) NOT NULL, + [SPHSection] nvarchar(200) NOT NULL, + [SPHAccountRollupIsValidated] bit NOT NULL, + [IsCBP] bit NOT NULL, + PRIMARY KEY ([AccountID]) +); + +CREATE NONCLUSTERED INDEX [IX_AccountID_OBRollupIDs] ON [fw].[DimAccount] ([AccountID], [OBUnitsFinancialReportingID], [OBDollarsFinancialReportingID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_Name] ON [fw].[DimAccount] ([Name]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_AccountCode] ON [fw].[DimAccount] ([AccountCode]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_MemberGUID] ON [fw].[DimAccount] ([MemberGUID]); +CREATE NONCLUSTERED INDEX [IX_AccountID] ON [fw].[DimAccount] ([AccountID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_AccountCode] ON [fw].[DimAccount] ([AccountCode]) INCLUDE ([AccountID]); +GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [FK_DimAccount_DimPatientType] FOREIGN KEY ([PatientTypeID]) REFERENCES [fw].[DimPatientType] ([PatientTypeID]); GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBIsD__3981D270] DEFAULT ((0)) FOR [OBIsDefined]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__IsSta__3ECB39DB] DEFAULT ((0)) FOR [IsStat]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_IsGlobal] DEFAULT ((0)) FOR [IsGlobal]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__IsExp__4B7B9146] DEFAULT ((0)) FOR [IsExpense]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__FWIsD__053F7F3C] DEFAULT ((0)) FOR [FWIsDefined]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_Variability] DEFAULT ((1)) FOR [Variability]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBDol__6DE91709] DEFAULT ((0)) FOR [OBDollarsFinancialReportingID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBDol__77728143] DEFAULT ('') FOR [OBDollarsFinancialReporting]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPHAc__07AD771D] DEFAULT ((0)) FOR [SPHAccountRollupIsValidated]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SDSAc__08489CE8] DEFAULT ((0)) FOR [SPHAccountRollupID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBDol__7866A57C] DEFAULT ('') FOR [OBDollarsFinancialReportingCategory]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SDSAc__093CC121] DEFAULT ('') FOR [SPHAccountRollupName]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBDol__7A4EEDEE] DEFAULT ('') FOR [OBDollarsFinancialReportingLineName]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBDol__2AF88001] DEFAULT ((0)) FOR [OBDollarsFinancialReportingSortOrder]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__Confi__0B250993] DEFAULT ((0)) FOR [SPHAccountRollupConfidenceScore]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBUni__6EDD3B42] DEFAULT ((0)) FOR [OBUnitsFinancialReportingID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBUni__7B431227] DEFAULT ('') FOR [OBUnitsFinancialReporting]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBUni__7C373660] DEFAULT ('') FOR [OBUnitsFinancialReportingCategory]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBUni__7E1F7ED2] DEFAULT ('') FOR [OBUnitsFinancialReportingLineName]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBUni__2BECA43A] DEFAULT ((0)) FOR [OBUnitsFinancialReportingSortOrder]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBAcc__1178418C] DEFAULT ((0)) FOR [OBAccountPHID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBMod__6C52D8C0] DEFAULT ('') FOR [OBModelSectionName]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBSta__20484969] DEFAULT ((0)) FOR [OBStatModelSectionID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBSta__213C6DA2] DEFAULT ('') FOR [OBStatModelSectionName]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBSta__6A33241F] DEFAULT ((0)) FOR [OBStatUnitTypeID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_OBUnitType] DEFAULT ('') FOR [OBUnitType]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBPay__7CBCB405] DEFAULT ((0)) FOR [OBPayorID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_OBPayor] DEFAULT ('') FOR [OBPayor]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBPay__05F1E3DB] DEFAULT ((0)) FOR [OBPayorGroupID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__OBPay__06E60814] DEFAULT ('') FOR [OBPayorGroup]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPIsD__3A75F6A9] DEFAULT ((0)) FOR [SPIsDefined]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__Patie__6433C725] DEFAULT ((0)) FOR [PatientTypeRollupID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__Patie__7EB84298] DEFAULT ('') FOR [PatientTypeRollupName]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_FWDIMACCOUNTSPACCOUNTROLLUPID] DEFAULT ((0)) FOR [SPAccountRollupID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPAcc__7FAC66D1] DEFAULT ('') FOR [SPAccountRollupName]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPSta__171085C4] DEFAULT ((0)) FOR [SPStatAccountRollup]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPSta__1804A9FD] DEFAULT ('') FOR [SPStatAccountRollupName]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPAcc__568D8309] DEFAULT ('') FOR [SPAccountRollupCategory]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_FWDIMACCOUNTSPPAYORGROUPID] DEFAULT ((0)) FOR [SPPayorGroupID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPPay__00A08B0A] DEFAULT ('') FOR [SPPayorGroupName]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPPhy__431DB774] DEFAULT ((0)) FOR [SPPhysicianGroupID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPPhy__0194AF43] DEFAULT ('') FOR [SPPhysicianGroupName]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_FWDIMACCOUNTSPJOBCODEGROUPID] DEFAULT ((0)) FOR [SPJobCodeGroupID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPJob__0288D37C] DEFAULT ('') FOR [SPJobCodeGroupName]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__26C5CC2F] DEFAULT ((0)) FOR [DSSAccountRollup4ID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_FWDIMACCOUNTSPCAPITALROLLUPID] DEFAULT ((0)) FOR [SPCapitalRollupID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__27B9F068] DEFAULT ('') FOR [DSSAccountRollup4]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPCap__037CF7B5] DEFAULT ('') FOR [SPCapitalRollupName]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__Histo__1AB06CF4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__28AE14A1] DEFAULT ('') FOR [DSSAccountRollup4Name]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_FWDIMACCOUNTSPDEBTISSUANCEID] DEFAULT ((0)) FOR [SPDebtIssuanceID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPDeb__04711BEE] DEFAULT ('') FOR [SPDebtIssuanceName]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPIsP__6985EB4D] DEFAULT ((0)) FOR [SPIsPhysicianOverride]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_PatientTypeID] DEFAULT ((0)) FOR [PatientTypeID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_OBAccountRollup] DEFAULT ('') FOR [OBStaffing]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__FW_DimAccount_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__337C4859] DEFAULT ((0)) FOR [DSSAccountRollup5ID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_FlexMetricGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FlexBucketGUID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__34706C92] DEFAULT ('') FOR [DSSAccountRollup5Name]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__356490CB] DEFAULT ((0)) FOR [DSSAccountRollup6ID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__3658B504] DEFAULT ('') FOR [DSSAccountRollup6Name]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPHVa__36E526EE] DEFAULT ((0)) FOR [SPHVariability]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__3AE6977F] DEFAULT ('') FOR [DSSAccountRollup2Category]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__3BDABBB8] DEFAULT ('') FOR [DSSAccountRollup3Category]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__3CCEDFF1] DEFAULT ('') FOR [DSSAccountRollup4Category]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__IsSPH__490F8F78] DEFAULT ((1)) FOR [IsSPHCostModel]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPHCo__55F3BDF3] DEFAULT ('') FOR [SPHCostComponent]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPHCo__56E7E22C] DEFAULT ('') FOR [SPHCostComponentRollup]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__Accou__5B694101] DEFAULT ('') FOR [AccountCodeRaw]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPHLi__68FE0774] DEFAULT ('') FOR [SPHLineItem]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPHSt__69F22BAD] DEFAULT ('') FOR [SPHStatement]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPHCa__6AE64FE6] DEFAULT ('') FOR [SPHCategory]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__SPHSe__6BDA741F] DEFAULT ('') FOR [SPHSection]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__Membe__19BC48BB] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__GMAcc__6CDEB11D] DEFAULT ('') FOR [GMAccountRollup1]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_Code] DEFAULT ('') FOR [AccountCode]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__GMAcc__6DD2D556] DEFAULT ('') FOR [GMAccountRollup2]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_Description] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__GMAcc__6EC6F98F] DEFAULT ('') FOR [GMAccountRollup3]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__GLRol__7BA49B88] DEFAULT ('') FOR [GLRollup]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__GMAcc__6FBB1DC8] DEFAULT ('') FOR [GMAccountRollup4]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__GMAcc__6FF38718] DEFAULT ('') FOR [GMAccountRollup7]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_IsInverted_1] DEFAULT ((0)) FOR [IsInverted]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__GMAcc__70AF4201] DEFAULT ('') FOR [GMAccountRollup5]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__Patie__2765843A] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__GMAcc__71A3663A] DEFAULT ('') FOR [GMAccountRollup6]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__Patie__2859A873] DEFAULT ('') FOR [PatientClass]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__72F7AEF0] DEFAULT ((0)) FOR [DSSAccountRollup7ID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__CAPIs__36A565C5] DEFAULT ((0)) FOR [CAPIsDefined]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__73EBD329] DEFAULT ('') FOR [DSSAccountRollup7Name]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSIs__379989FE] DEFAULT ((0)) FOR [DSSIsDefined]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSCo__64355DD3] DEFAULT ('') FOR [DSSCostComponent]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSSt__1EBE2B32] DEFAULT ('') FOR [DSSStatisticDriver]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__07C9AFF4] DEFAULT ((0)) FOR [DSSAccountRollup1ID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__0AA61C9F] DEFAULT ('') FOR [DSSAccountRollup1Name]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__08BDD42D] DEFAULT ('') FOR [DSSAccountRollup1Category]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__09B1F866] DEFAULT ((0)) FOR [DSSAccountRollup2ID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__0B9A40D8] DEFAULT ('') FOR [DSSAccountRollup2Name]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__0D82894A] DEFAULT ((0)) FOR [DSSAccountRollup3ID]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__DSSAc__0C8E6511] DEFAULT ('') FOR [DSSAccountRollup3Name]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__MRIsD__388DAE37] DEFAULT ((0)) FOR [MRIsDefined]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__IsCBP__7E266EE8] DEFAULT ((0)) FOR [IsCBP]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF_DimAccount_FlexStatistic] DEFAULT ('') FOR [FlexStatistic]; GO +ALTER TABLE [fw].[DimAccount] ADD CONSTRAINT [DF__DimAccoun__FlexV__5CCDD875] DEFAULT ((0)) FOR [FlexValue]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimAgeCohort ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimAgeCohort] ( + [AgeCohortID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [Code] nvarchar(100) NOT NULL, + [SortOrder] int NOT NULL, + [TimeMin] int NOT NULL, + [TimeMax] int NOT NULL, + [TimeMinUnit] nvarchar(100) NOT NULL, + [TimeMaxUnit] nvarchar(100) NOT NULL, + PRIMARY KEY ([AgeCohortID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimAgeCohort] ([MemberGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimAgeCohort] ([Name]); +GO +ALTER TABLE [fw].[DimAgeCohort] ADD CONSTRAINT [DF__DimAgeCoh__Histo__6CAF9E17] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimAgeCohort] ADD CONSTRAINT [DF__DimAgeCoh__TimeM__12BB0C99] DEFAULT ((0)) FOR [TimeMin]; GO +ALTER TABLE [fw].[DimAgeCohort] ADD CONSTRAINT [DF__DimAgeCoh__TimeM__13AF30D2] DEFAULT ((0)) FOR [TimeMax]; GO +ALTER TABLE [fw].[DimAgeCohort] ADD CONSTRAINT [DF__DimAgeCoh__TimeM__177FC1B6] DEFAULT ('') FOR [TimeMinUnit]; GO +ALTER TABLE [fw].[DimAgeCohort] ADD CONSTRAINT [DF__DimAgeCoh__TimeM__1873E5EF] DEFAULT ('') FOR [TimeMaxUnit]; GO +ALTER TABLE [fw].[DimAgeCohort] ADD CONSTRAINT [DF__DimAgeCoho__Name__6AC755A5] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimAgeCohort] ADD CONSTRAINT [DF__DimAgeCoh__Membe__6BBB79DE] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimAgeCohort] ADD CONSTRAINT [DF__DimAgeCoh__Trans__6DA3C250] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimAgeCohort] ADD CONSTRAINT [DF__DimAgeCoho__Code__6E97E689] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimAgeCohort] ADD CONSTRAINT [DF__DimAgeCoh__SortO__6F8C0AC2] DEFAULT ((0)) FOR [SortOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimAssumption ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimAssumption] ( + [MemberGUID] uniqueidentifier NOT NULL, + [AssumptionID] int NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Category] nvarchar(100) NOT NULL, + [SubCategory] nvarchar(100) NOT NULL, + [Version] timestamp NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [DisplayFormat] nvarchar(200) NOT NULL, + [SPIsPastingValues] bit NOT NULL, + [SPIsProtectingRollingValues] bit NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([AssumptionID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [UQ__DimAssum__A67B3853390AD6E2] ON [fw].[DimAssumption] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimAssumption] ADD CONSTRAINT [DF__DimAssump__Histo__3EC3B038] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimAssumption] ADD CONSTRAINT [DF__DimAssump__SPIsP__0D3215CF] DEFAULT ((0)) FOR [SPIsProtectingRollingValues]; GO +ALTER TABLE [fw].[DimAssumption] ADD CONSTRAINT [DF__DimAssump__SPIsP__0FBE0EFF] DEFAULT ((0)) FOR [SPIsPastingValues]; GO +ALTER TABLE [fw].[DimAssumption] ADD CONSTRAINT [DF__DimAssump__Membe__3AF31F54] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimAssumption] ADD CONSTRAINT [DF__DimAssumpt__Name__3BE7438D] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimAssumption] ADD CONSTRAINT [DF__DimAssump__Categ__3CDB67C6] DEFAULT ('') FOR [Category]; GO +ALTER TABLE [fw].[DimAssumption] ADD CONSTRAINT [DF__DimAssump__SubCa__3DCF8BFF] DEFAULT ('') FOR [SubCategory]; GO +ALTER TABLE [fw].[DimAssumption] ADD CONSTRAINT [DF__FW_DimAssumption_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimAssumption] ADD CONSTRAINT [DF__DimAssump__Displ__7895EE7B] DEFAULT ('') FOR [DisplayFormat]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimCareSetting ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimCareSetting] ( + [CareSettingID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [Code] nvarchar(100) NOT NULL, + [SortOrder] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [IsActive] bit NOT NULL, + PRIMARY KEY ([CareSettingID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimCareSetting] ([MemberGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimCareSetting] ([Name]); +GO +ALTER TABLE [fw].[DimCareSetting] ADD CONSTRAINT [DF__DimCareSet__Name__2EBC8D3F] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimCareSetting] ADD CONSTRAINT [DF__DimCareSet__Code__2FB0B178] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimCareSetting] ADD CONSTRAINT [DF__DimCareSe__SortO__30A4D5B1] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimCareSetting] ADD CONSTRAINT [DF__DimCareSe__Membe__3198F9EA] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimCareSetting] ADD CONSTRAINT [DF__DimCareSe__Trans__3381425C] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimCareSetting] ADD CONSTRAINT [DF__DimCareSe__Histo__328D1E23] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimCareSetting] ADD CONSTRAINT [DF__DimCareSe__IsAct__77A48FDB] DEFAULT ((1)) FOR [IsActive]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimCareSettingPH ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimCareSettingPH] ( + [CareSettingPHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([CareSettingPHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimCareSettingPH] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimCareSettingPH] ADD CONSTRAINT [DF__DimCareSet__Name__3E5F8ED9] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimCareSettingPH] ADD CONSTRAINT [DF__DimCareSe__Membe__3F53B312] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimCareSettingPH] ADD CONSTRAINT [DF__DimCareSe__Trans__413BFB84] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimCareSettingPH] ADD CONSTRAINT [DF__DimCareSe__Histo__4047D74B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimChargeCode ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimChargeCode] ( + [ChargeCodeID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [ChargeCode] nvarchar(100) NOT NULL, + [Description] nvarchar(400) NOT NULL, + [IsDefined] bit NOT NULL, + [OBIsDefined] bit NOT NULL, + [IsRVU] bit NOT NULL, + [IsStatDriver] bit NOT NULL, + [ChargeIncrease] decimal NOT NULL, + [Category] nvarchar(200) NOT NULL, + [RVUWeight] decimal NOT NULL, + [StatType] nvarchar(50) NOT NULL, + [PatientTypeID] int NOT NULL, + [DSSIsDefined] bit NOT NULL, + [DayTypeID] int NOT NULL, + [DayType2ID] int NOT NULL, + [DayType3ID] int NOT NULL, + [UBRevenueCodeID] int NOT NULL, + [CPTID] int NOT NULL, + [IsActivityCost] bit NOT NULL, + [TransactionID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [CostDriver] nvarchar(100) NOT NULL, + [Rollup] nvarchar(200) NOT NULL, + [IsPatientSpecific] bit NOT NULL, + [FWIsDefined] bit NOT NULL, + [DayType] nvarchar(443) NOT NULL, + [DayType2] nvarchar(443) NOT NULL, + [DayType3] nvarchar(443) NOT NULL, + [TimeStampWeight] decimal NOT NULL, + [IsTimeStamp] bit NOT NULL, + [TimeStampPrecedent] int NOT NULL, + [Name] nvarchar(503) NOT NULL, + [IsSPHSupplyCosting] bit NOT NULL, + [IsSPHTDCosting] bit NOT NULL, + [SPHChargeCodePrefix] nvarchar(100) NOT NULL, + PRIMARY KEY ([ChargeCodeID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [NCU_ChargeCode] ON [fw].[DimChargeCode] ([ChargeCode]) INCLUDE ([ChargeCodeID]); +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimChargeCode] ([MemberGUID]); +CREATE NONCLUSTERED INDEX [NCNU_DateTypeID] ON [fw].[DimChargeCode] ([DayTypeID]); +CREATE NONCLUSTERED INDEX [NUNC_ChargeCodeID_Name] ON [fw].[DimChargeCode] ([ChargeCodeID]) INCLUDE ([Name]); +CREATE NONCLUSTERED INDEX [NC_IDX_ChargeCode_IsPatntSpecifc] ON [fw].[DimChargeCode] ([IsPatientSpecific]) INCLUDE ([ChargeCodeID]); +GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF_DimChargeCode_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF_DimChargeCode_Code] DEFAULT ('') FOR [ChargeCode]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF_DimChargeCode_IsDefined] DEFAULT ((1)) FOR [IsDefined]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__FWIsD__0727C7AE] DEFAULT ((0)) FOR [FWIsDefined]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__OBIsD__520432CE] DEFAULT ((0)) FOR [OBIsDefined]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__IsRVU__42B8672A] DEFAULT ((0)) FOR [IsRVU]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__IsSta__7A0C62FD] DEFAULT ((1)) FOR [IsStatDriver]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__Charg__7BF4AB6F] DEFAULT ((0)) FOR [ChargeIncrease]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__Categ__78241A8B] DEFAULT ('') FOR [Category]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__RVUWe__7ED1181A] DEFAULT ((1)) FOR [RVUWeight]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF_IsPatient_Specific] DEFAULT ((1)) FOR [IsPatientSpecific]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__StatT__43AC8B63] DEFAULT ('') FOR [StatType]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__Patie__745389A7] DEFAULT ((0)) FOR [PatientTypeID]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__DSSIs__52F85707] DEFAULT ((0)) FOR [DSSIsDefined]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__DayTy__19CCF6DE] DEFAULT ((0)) FOR [DayTypeID]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__DayTy__647D465B] DEFAULT ((0)) FOR [DayType2ID]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__DayTy__65716A94] DEFAULT ((0)) FOR [DayType3ID]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__UBRev__6B40E931] DEFAULT ((0)) FOR [UBRevenueCodeID]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__CPTID__6C350D6A] DEFAULT ((0)) FOR [CPTID]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__IsAct__481D061C] DEFAULT ((0)) FOR [IsActivityCost]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__FW_DimChargeCode_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__Descr__50D54340] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__IsSPH__36460870] DEFAULT ((0)) FOR [IsSPHSupplyCosting]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF_DimChargeCode_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__IsSPH__373A2CA9] DEFAULT ((0)) FOR [IsSPHTDCosting]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__SPHCh__382E50E2] DEFAULT ('') FOR [SPHChargeCodePrefix]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__TimeS__38FC1ED2] DEFAULT ((0)) FOR [TimeStampWeight]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__TimeS__39F0430B] DEFAULT ((0)) FOR [IsTimeStamp]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__TimeS__3AE46744] DEFAULT ((0)) FOR [TimeStampPrecedent]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF_DimChargeCode_Rollup] DEFAULT ('') FOR [Rollup]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__DayTy__6177EB69] DEFAULT ('') FOR [DayType]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__DayTy__626C0FA2] DEFAULT ('') FOR [DayType2]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__DayTy__636033DB] DEFAULT ('') FOR [DayType3]; GO +ALTER TABLE [fw].[DimChargeCode] ADD CONSTRAINT [DF__DimCharge__CostD__6D4D57B1] DEFAULT ('') FOR [CostDriver]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimChargeCodePH ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimChargeCodePH] ( + [ChargeCodePHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([ChargeCodePHID]) +); +GO +ALTER TABLE [fw].[DimChargeCodePH] ADD CONSTRAINT [DF__DimChargeCodePH_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimChargeCodePH] ADD CONSTRAINT [DF__DimChargeCodePH_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimChargeCodePH] ADD CONSTRAINT [DF__DimChargeCodePH_TransactionID] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimChargeCodePH] ADD CONSTRAINT [DF__DimChargeCodePH_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimColumnHider ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimColumnHider] ( + [ColumnHiderID] tinyint NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([ColumnHiderID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_DimColumnHider] ON [fw].[DimColumnHider] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimColumnHider] ADD CONSTRAINT [DF_DimColumnHider_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimColumnHider] ADD CONSTRAINT [DF_DimColumnHider_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimColumnHider] ADD CONSTRAINT [DF__FW_DimColumnHider_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimColumnHider] ADD CONSTRAINT [DF__fw_DimColumnHider_Name] DEFAULT ('') FOR [Name]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimCompAnDepartment ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimCompAnDepartment] ( + [HistoryItemGUID] uniqueidentifier NOT NULL, + [CompAnDepartmentID] int NOT NULL, + [CompAnDepartmentCode] nvarchar(10) NOT NULL, + [Description] nvarchar(200) NOT NULL, + [DescriptionLong] nvarchar(400) NOT NULL, + [CompAnDepartmentRollup1] nvarchar(200) NOT NULL, + [CompAnDepartmentRollup2] nvarchar(200) NOT NULL, + [CompAnDepartmentRollup3] nvarchar(200) NOT NULL, + [CompAnDepartmentRollup4] nvarchar(200) NOT NULL, + [CompAnPrimaryStat] nvarchar(200) NOT NULL, + [SPHDepartmentRollupID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([CompAnDepartmentID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [NCU_CompAnDepartmentCode] ON [fw].[DimCompAnDepartment] ([CompAnDepartmentCode]) INCLUDE ([CompAnDepartmentID]); +GO +ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__Histo__62E79D70] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__CompA__64CFE5E2] DEFAULT ('') FOR [CompAnDepartmentCode]; GO +ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__Descr__65C40A1B] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__Descr__66B82E54] DEFAULT ('') FOR [DescriptionLong]; GO +ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__CompA__67AC528D] DEFAULT ('') FOR [CompAnDepartmentRollup1]; GO +ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__CompA__68A076C6] DEFAULT ('') FOR [CompAnDepartmentRollup2]; GO +ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__CompA__69949AFF] DEFAULT ('') FOR [CompAnDepartmentRollup3]; GO +ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__CompA__6A88BF38] DEFAULT ('') FOR [CompAnDepartmentRollup4]; GO +ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__CompA__6B7CE371] DEFAULT ('') FOR [CompAnPrimaryStat]; GO +ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__SPHDe__6C7107AA] DEFAULT ((0)) FOR [SPHDepartmentRollupID]; GO +ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__Membe__6D652BE3] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimCompAnDepartment] ADD CONSTRAINT [DF__DimCompAn__Trans__6E59501C] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimCompAnPeerGroup ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimCompAnPeerGroup] ( + [HistoryItemGUID] uniqueidentifier NOT NULL, + [CompAnPeerGroupID] int NOT NULL, + [Name] nvarchar(300) NOT NULL, + [Description] nvarchar(500) NOT NULL, + [CompAnPeerGroupCode] nvarchar(10) NOT NULL, + [TransactionID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([CompAnPeerGroupID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [NCU_CompAnPeerGroupCode] ON [fw].[DimCompAnPeerGroup] ([CompAnPeerGroupCode]) INCLUDE ([CompAnPeerGroupID]); +GO +ALTER TABLE [fw].[DimCompAnPeerGroup] ADD CONSTRAINT [DF__DimCompAn__Histo__3793F66E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimCompAnPeerGroup] ADD CONSTRAINT [DF__DimCompAnP__Name__397C3EE0] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimCompAnPeerGroup] ADD CONSTRAINT [DF__DimCompAn__Descr__3A706319] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fw].[DimCompAnPeerGroup] ADD CONSTRAINT [DF__DimCompAn__CompA__3B648752] DEFAULT ('') FOR [CompAnPeerGroupCode]; GO +ALTER TABLE [fw].[DimCompAnPeerGroup] ADD CONSTRAINT [DF__DimCompAn__Trans__3C58AB8B] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimCompAnPeerGroup] ADD CONSTRAINT [DF__DimCompAn__Membe__3D4CCFC4] DEFAULT (newid()) FOR [MemberGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimConsolidatedFinancialReporting ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimConsolidatedFinancialReporting] ( + [ConsolidatedFinancialReportingID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Statement] nvarchar(100) NOT NULL, + [Section] nvarchar(100) NOT NULL, + [LineName] nvarchar(100) NOT NULL, + [SortOrder] int NOT NULL, + [Name] nvarchar(306) NOT NULL, + PRIMARY KEY ([ConsolidatedFinancialReportingID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimConsolidatedFinancialReporting] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimConsolidatedFinancialReporting] ADD CONSTRAINT [DF__DimConsol__Membe__24E2AF8A] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimConsolidatedFinancialReporting] ADD CONSTRAINT [DF__DimConsol__State__26CAF7FC] DEFAULT ('') FOR [Statement]; GO +ALTER TABLE [fw].[DimConsolidatedFinancialReporting] ADD CONSTRAINT [DF__DimConsol__Secti__27BF1C35] DEFAULT ('') FOR [Section]; GO +ALTER TABLE [fw].[DimConsolidatedFinancialReporting] ADD CONSTRAINT [DF__DimConsol__LineN__28B3406E] DEFAULT ('') FOR [LineName]; GO +ALTER TABLE [fw].[DimConsolidatedFinancialReporting] ADD CONSTRAINT [DF__DimConsol__SortO__29A764A7] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimConsolidatedFinancialReporting] ADD CONSTRAINT [DF__DimConsol__Histo__25D6D3C3] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimDataType ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimDataType] ( + [DataTypeID] tinyint NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [GlobalID] varchar(32) NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([DataTypeID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimDataType] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimDataType] ADD CONSTRAINT [DF__DimDataTyp__Name__363E1B39] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimDataType] ADD CONSTRAINT [DF__DimDataTy__Globa__3D40E9DA] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [fw].[DimDataType] ADD CONSTRAINT [DF__DimDataTy__Membe__37323F72] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimDataType] ADD CONSTRAINT [DF__DimDataTy__Histo__382663AB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimDataType] ADD CONSTRAINT [DF__FW_DimDataType_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimDate ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimDate] ( + [DateID] int NOT NULL, + [DayNumberOfWeek] tinyint NOT NULL, + [DayNameOfWeek] nvarchar(10) NOT NULL, + [DayNumberOfMonth] tinyint NOT NULL, + [DayNumberOfYear] smallint NOT NULL, + [WeekNumberOfYear] tinyint NOT NULL, + [IsWeekDay] bit NOT NULL, + [CalendarQuarter] tinyint NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [CalendarDateTime] smalldatetime NOT NULL, + [CalendarYear] smallint NOT NULL, + [CalendarMonth] tinyint NOT NULL, + [CalendarMonthName] varchar(100) NOT NULL, + [FiscalYear] smallint NOT NULL, + [FiscalYearName] varchar(6) NOT NULL, + [FiscalMonth] tinyint NOT NULL, + [TransactionID] int NOT NULL, + [FiscalQuarter] varchar(15) NOT NULL, + [YearMonth] nvarchar(25) NOT NULL, + [MonthYear] nvarchar(100) NOT NULL, + [PremierMapping] varchar(8000) NULL, + [DaysInMonth] int NOT NULL, + PRIMARY KEY ([DateID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimDate] ([MemberGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_CalendarDateTime] ON [fw].[DimDate] ([CalendarDateTime]); +GO +ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__DaysInM__0105A55B] DEFAULT ((0)) FOR [DaysInMonth]; GO +ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__FiscalQ__4E0FADA6] DEFAULT ('') FOR [FiscalQuarter]; GO +ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__YearMon__11882458] DEFAULT ('') FOR [YearMonth]; GO +ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__MonthYe__1CB7E171] DEFAULT ('Not Specified') FOR [MonthYear]; GO +ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__FiscalM__1F65094C] DEFAULT ((0)) FOR [FiscalMonth]; GO +ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__DayNumb__087F41EF] DEFAULT ((0)) FOR [DayNumberOfWeek]; GO +ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__DayName__09736628] DEFAULT ((0)) FOR [DayNameOfWeek]; GO +ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__DayNumb__0A678A61] DEFAULT ((0)) FOR [DayNumberOfMonth]; GO +ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__DayNumb__0B5BAE9A] DEFAULT ((0)) FOR [DayNumberOfYear]; GO +ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__WeekNum__0C4FD2D3] DEFAULT ((0)) FOR [WeekNumberOfYear]; GO +ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__IsWeekD__0D43F70C] DEFAULT ((0)) FOR [IsWeekDay]; GO +ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__Calenda__0E381B45] DEFAULT ((0)) FOR [CalendarQuarter]; GO +ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__History__102063B7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF_CalendarDateTime] DEFAULT ('1900-01-01 0:00') FOR [CalendarDateTime]; GO +ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__Calenda__7EC0CD8B] DEFAULT ((0)) FOR [CalendarYear]; GO +ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__Calenda__7FB4F1C4] DEFAULT ((1)) FOR [CalendarMonth]; GO +ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__Calenda__00A915FD] DEFAULT ('') FOR [CalendarMonthName]; GO +ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__DimDate__FiscalY__019D3A36] DEFAULT ((0)) FOR [FiscalYear]; GO +ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF__FW_DimDate_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimDate] ADD CONSTRAINT [DF_FWDIMDATEMEMBERGUID] DEFAULT (newid()) FOR [MemberGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimDayType ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimDayType] ( + [DayTypeID] int NOT NULL, + [DayTypeCode] nvarchar(40) NOT NULL, + [Description] nvarchar(400) NOT NULL, + [PrecedentOrder] int NOT NULL, + [GlobalID] nvarchar(50) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Rollup] nvarchar(100) NOT NULL, + [TransactionID] int NOT NULL, + [Name] nvarchar(443) NOT NULL, + PRIMARY KEY ([DayTypeID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimDayType] ([MemberGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_DayTypeCode] ON [fw].[DimDayType] ([DayTypeCode]) INCLUDE ([DayTypeID]); +GO +ALTER TABLE [fw].[DimDayType] ADD CONSTRAINT [DF__DimDayTyp__DayTy__15FC65FA] DEFAULT ('') FOR [DayTypeCode]; GO +ALTER TABLE [fw].[DimDayType] ADD CONSTRAINT [DF__DimDayTyp__Prece__17E4AE6C] DEFAULT ((0)) FOR [PrecedentOrder]; GO +ALTER TABLE [fw].[DimDayType] ADD CONSTRAINT [DF__DimDayTyp__Globa__18D8D2A5] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [fw].[DimDayType] ADD CONSTRAINT [DF__DimDayTyp__Descr__16F08A33] DEFAULT ('Not Specified') FOR [Description]; GO +ALTER TABLE [fw].[DimDayType] ADD CONSTRAINT [DF__DimDayTyp__Membe__5AA69602] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimDayType] ADD CONSTRAINT [DF__DimDayTyp__Rollu__69D3CAF9] DEFAULT ('') FOR [Rollup]; GO +ALTER TABLE [fw].[DimDayType] ADD CONSTRAINT [DF__DimDayTyp__Histo__5B9ABA3B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimDayType] ADD CONSTRAINT [DF__FW_DimDayType_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimDayofStay ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimDayofStay] ( + [DayofStayID] int NOT NULL, + [Name] nvarchar(50) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([DayofStayID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimDayofStay] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimDayofStay] ADD CONSTRAINT [DF__DimDayofS__Histo__60C0F8B9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimDayofStay] ADD CONSTRAINT [DF__DimDayofSt__Name__5ED8B047] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimDayofStay] ADD CONSTRAINT [DF__DimDayofS__Membe__5FCCD480] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimDayofStay] ADD CONSTRAINT [DF__FW_DimDayofStay_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimDepartment ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimDepartment] ( + [DepartmentID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [DepartmentCode] nvarchar(100) NOT NULL, + [Description] nvarchar(100) NOT NULL, + [SystemID] smallint NOT NULL, + [System] nvarchar(100) NOT NULL, + [SystemSortOrder] int NOT NULL, + [EntityID] int NOT NULL, + [Entity] nvarchar(303) NULL, + [EntitySortOrder] int NOT NULL, + [EntityTypeOverride] smallint NOT NULL, + [DepartmentRollup1ID] smallint NOT NULL, + [DepartmentRollup1] nvarchar(200) NOT NULL, + [DepartmentRollup1SortOrder] int NOT NULL, + [DepartmentRollup2ID] smallint NOT NULL, + [DepartmentRollup2] nvarchar(200) NOT NULL, + [DepartmentRollup2SortOrder] int NOT NULL, + [DepartmentRollup3ID] smallint NOT NULL, + [DepartmentRollup3] nvarchar(200) NOT NULL, + [DepartmentRollup3SortOrder] int NOT NULL, + [DepartmentRollup4ID] int NOT NULL, + [DepartmentRollup4] nvarchar(200) NOT NULL, + [DepartmentRollup4SortOrder] int NOT NULL, + [DepartmentRollup5ID] smallint NOT NULL, + [DepartmentRollup5] nvarchar(200) NOT NULL, + [DepartmentRollup5SortOrder] int NOT NULL, + [DepartmentRollup6ID] smallint NOT NULL, + [DepartmentRollup6] nvarchar(200) NOT NULL, + [DepartmentRollup6SortOrder] int NOT NULL, + [CareSettingID] int NOT NULL, + [CareSetting] nvarchar(100) NOT NULL, + [SortOrder] int NOT NULL, + [IsDepartmentRollup] bit NOT NULL, + [FunctionalAreaID] int NOT NULL, + [FunctionalArea] nvarchar(100) NOT NULL, + [ResearchDepartmentCategoryID] int NOT NULL, + [ResearchDepartmentCategoryName] nvarchar(100) NOT NULL, + [ResearchDepartmentCategorySortOrder] int NOT NULL, + [AttributionTypeID] int NOT NULL, + [AttributionType] nvarchar(200) NOT NULL, + [CAPIsDefined] bit NOT NULL, + [IsCAP] bit NOT NULL, + [DSSIsDefined] bit NOT NULL, + [IsDSS] bit NOT NULL, + [DepartmentTypeOLD] nvarchar(100) NOT NULL, + [DSSDeptGrouping] nvarchar(200) NOT NULL, + [DSSDepartmentRollup1ID] int NOT NULL, + [DSSDepartmentRollup1Name] nvarchar(100) NOT NULL, + [DSSDepartmentRollup2ID] int NOT NULL, + [DSSDepartmentRollup2Name] nvarchar(100) NOT NULL, + [DSSDepartmentRollup3ID] int NOT NULL, + [DSSDepartmentRollup3Name] nvarchar(100) NOT NULL, + [IsOverhead] bit NOT NULL, + [OBIsDefined] bit NOT NULL, + [IsOB] bit NOT NULL, + [IsMRPlan] bit NOT NULL, + [IsActive] bit NOT NULL, + [IsVariable] bit NOT NULL, + [IsAccountFlexing] bit NOT NULL, + [FlexingBucketGUID] uniqueidentifier NOT NULL, + [OBGlobalStatisticsPlanID] int NOT NULL, + [OBGlobalStatisticsPlan] nvarchar(1000) NOT NULL, + [OBReimbursementPlanID] int NOT NULL, + [OBReimbursementPlan] nvarchar(458) NOT NULL, + [OBServiceLinePlanID] int NOT NULL, + [OBServiceLinePlan] nvarchar(458) NOT NULL, + [SPIsDefined] bit NOT NULL, + [IsLRFP] bit NOT NULL, + [RollingPlanID] int NOT NULL, + [SPRollingForecastPlanName] nvarchar(200) NOT NULL, + [OpsPlanID] int NOT NULL, + [SPOperationsPlanName] nvarchar(200) NOT NULL, + [BalPlanID] int NOT NULL, + [SPBalanceSheetPlanName] nvarchar(200) NOT NULL, + [PatientTypeRollup] tinyint NOT NULL, + [PatientTypeRollupName] nvarchar(100) NOT NULL, + [SPJobCodeGroup] int NOT NULL, + [SPJobCodeGroupName] nvarchar(100) NOT NULL, + [SPPhysicianGroup] int NOT NULL, + [SPPhysicianGroupName] nvarchar(100) NOT NULL, + [SPAccountRollup] int NOT NULL, + [SPAccountRollupName] nvarchar(100) NOT NULL, + [SPServiceLineForecastType] smallint NOT NULL, + [ConsolidatedCode] nvarchar(100) NOT NULL, + [IsConsolidated] bit NOT NULL, + [TransactionID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [Name] nvarchar(203) NOT NULL, + [SecureGroupID] int NOT NULL, + [WorkWeekID] int NOT NULL, + [CAPDefaultSalesTax] float NOT NULL, + [EntityCode] nvarchar(100) NOT NULL, + [FundID] int NOT NULL, + [Fund] nvarchar(100) NOT NULL, + [FundSortOrder] int NOT NULL, + [ProjectID] int NOT NULL, + [Project] nvarchar(100) NOT NULL, + [ProjectSortOrder] int NOT NULL, + [HomeDepartmentID] int NOT NULL, + [HomeDepartment] nvarchar(100) NOT NULL, + [HomeDepartmentSortOrder] int NOT NULL, + [ProgramID] int NOT NULL, + [Program] nvarchar(100) NOT NULL, + [ProgramSortOrder] int NOT NULL, + [PayCycleID] int NOT NULL, + [FWIsDefined] bit NOT NULL, + [DepartmentTypeID] int NOT NULL, + [DepartmentType] nvarchar(200) NOT NULL, + [DepartmentCodeRaw] nvarchar(100) NOT NULL, + [IsPR] bit NOT NULL, + [MRVicePresident] nvarchar(400) NOT NULL, + [MRDirector] nvarchar(400) NOT NULL, + [MRManager] nvarchar(400) NOT NULL, + [IsMROrPR] int NOT NULL, + [IsMRMetricTracking] bit NOT NULL, + [IsHealthPlanAdmin] bit NOT NULL, + [DepartmentRollup1Code] nvarchar(200) NOT NULL, + [DepartmentRollup2Code] nvarchar(200) NOT NULL, + [DepartmentRollup3Code] nvarchar(200) NOT NULL, + [DepartmentRollup4Code] nvarchar(200) NOT NULL, + [DepartmentRollup5Code] nvarchar(200) NOT NULL, + [DepartmentRollup6Code] nvarchar(200) NOT NULL, + [DSSDepartmentRollup4Name] nvarchar(100) NOT NULL, + [DSSDepartmentRollup4ID] int NOT NULL, + [DSSDepartmentRollup5ID] int NOT NULL, + [DSSDepartmentRollup5Name] nvarchar(100) NOT NULL, + [DSSDepartmentRollup6ID] int NOT NULL, + [DSSDepartmentRollup6Name] nvarchar(200) NOT NULL, + [DSSDepartmentRollup7ID] int NOT NULL, + [DSSDepartmentRollup7Name] nvarchar(100) NOT NULL, + [SPHDepartmentRollupID] int NOT NULL, + [SPHDepartmentRollupName] nvarchar(200) NOT NULL, + [SPHDepartmentRollupConfidenceScore] float NOT NULL, + [SPHDepartmentTypeID] int NOT NULL, + [SPHDepartmentType] nvarchar(200) NOT NULL, + [IsClaimsCosting] bit NOT NULL, + [SPHDepartmentRollupIsValidated] bit NOT NULL, + [CompAnDepartmentID] int NOT NULL, + [ProductivityPercentileID] int NOT NULL, + [ProductivityPercentile] nvarchar(200) NOT NULL, + [CompAnDepartment] nvarchar(200) NOT NULL, + [SPHDepartmentID] int NOT NULL, + [SPHDepartmentConfidenceScore] float NOT NULL, + [SPHDepartmentIsValidated] bit NOT NULL, + [SPHDepartmentName] nvarchar(200) NOT NULL, + PRIMARY KEY ([DepartmentID]) +); + +CREATE NONCLUSTERED INDEX [IX_MemberGUID] ON [fw].[DimDepartment] ([MemberGUID]); +CREATE NONCLUSTERED INDEX [IX_Hierarchy] ON [fw].[DimDepartment] ([DepartmentID], [DepartmentRollup1ID], [DepartmentRollup2ID], [DepartmentRollup3ID], [DepartmentRollup4ID], [DepartmentRollup5ID], [DepartmentRollup6ID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_DepartmentCode] ON [fw].[DimDepartment] ([DepartmentCode]) INCLUDE ([DepartmentID]); +CREATE NONCLUSTERED INDEX [IX_DepartmentRollup1ID] ON [fw].[DimDepartment] ([DepartmentRollup1ID]); +CREATE NONCLUSTERED INDEX [IX_DepartmentRollup2ID] ON [fw].[DimDepartment] ([DepartmentRollup2ID]); +CREATE NONCLUSTERED INDEX [IX_DepartmentRollup3ID] ON [fw].[DimDepartment] ([DepartmentRollup3ID]); +CREATE NONCLUSTERED INDEX [IX_DepartmentRollup4ID] ON [fw].[DimDepartment] ([DepartmentRollup4ID]); +CREATE NONCLUSTERED INDEX [IX_DepartmentRollup5ID] ON [fw].[DimDepartment] ([DepartmentRollup5ID]); +CREATE NONCLUSTERED INDEX [IX_DepartmentRollup6ID] ON [fw].[DimDepartment] ([DepartmentRollup6ID]); +CREATE NONCLUSTERED INDEX [NCNU_EntityID] ON [fw].[DimDepartment] ([DepartmentID], [EntityID]); +CREATE NONCLUSTERED INDEX [NCNU_DimDepartment_IsMRorPR_DepartmentID] ON [fw].[DimDepartment] ([IsMROrPR], [DepartmentID]) INCLUDE ([Name]); +GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__CareS__459FF297] DEFAULT ('') FOR [CareSetting]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__PayCy__481E3507] DEFAULT ((0)) FOR [PayCycleID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__485769AE] DEFAULT ((0)) FOR [DSSDepartmentRollup4ID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Entit__485BCA24] DEFAULT ('') FOR [EntityCode]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SortO__71693472] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__494B8DE7] DEFAULT ((0)) FOR [DSSDepartmentRollup5ID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__IsDep__59BF8EFC] DEFAULT ((0)) FOR [IsDepartmentRollup]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__4A3FB220] DEFAULT ('') FOR [DSSDepartmentRollup5Name]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Funct__11FA2A12] DEFAULT ((0)) FOR [FunctionalAreaID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__FundI__4B24BEE4] DEFAULT ((0)) FOR [FundID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__4B33D659] DEFAULT ((0)) FOR [DSSDepartmentRollup6ID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Funct__12EE4E4B] DEFAULT ('') FOR [FunctionalArea]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepartm__Fund__4C18E31D] DEFAULT ('') FOR [Fund]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Resea__3B12E4EC] DEFAULT ((0)) FOR [ResearchDepartmentCategoryID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__FundS__4D0D0756] DEFAULT ((0)) FOR [FundSortOrder]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__4D1C1ECB] DEFAULT ((0)) FOR [DSSDepartmentRollup7ID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Resea__3C070925] DEFAULT ('') FOR [ResearchDepartmentCategoryName]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Proje__4E012B8F] DEFAULT ((0)) FOR [ProjectID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__4E104304] DEFAULT ('') FOR [DSSDepartmentRollup7Name]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Resea__3CFB2D5E] DEFAULT ((0)) FOR [ResearchDepartmentCategorySortOrder]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Proje__4EF54FC8] DEFAULT ('') FOR [Project]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Attri__4E4FD692] DEFAULT ((0)) FOR [AttributionTypeID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Proje__4FE97401] DEFAULT ((0)) FOR [ProjectSortOrder]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Attri__4F43FACB] DEFAULT ('') FOR [AttributionType]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__HomeD__50DD983A] DEFAULT ((0)) FOR [HomeDepartmentID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__CAPIs__3B6A1AE2] DEFAULT ((0)) FOR [CAPIsDefined]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__HomeD__51D1BC73] DEFAULT ('') FOR [HomeDepartment]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__HomeD__52C5E0AC] DEFAULT ((0)) FOR [HomeDepartmentSortOrder]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSIs__3C5E3F1B] DEFAULT ((0)) FOR [DSSIsDefined]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Progr__53BA04E5] DEFAULT ((0)) FOR [ProgramID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__IsDSS__3A68A7AC] DEFAULT ((0)) FOR [IsDSS]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Progr__54AE291E] DEFAULT ('') FOR [Program]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Entit__3D5D504C] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_FWDIMDEPARTMENTDEPARTMENTTYPE] DEFAULT ('Not Specified') FOR [DepartmentTypeOLD]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Progr__55A24D57] DEFAULT ((0)) FOR [ProgramSortOrder]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__6711CA7E] DEFAULT ('') FOR [DSSDeptGrouping]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__3C3D7833] DEFAULT ((0)) FOR [DSSDepartmentRollup1ID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__3D319C6C] DEFAULT ('') FOR [DSSDepartmentRollup1Name]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__3E25C0A5] DEFAULT ((0)) FOR [DSSDepartmentRollup2ID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__3F19E4DE] DEFAULT ('') FOR [DSSDepartmentRollup2Name]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__5A751CC8] DEFAULT ('') FOR [DepartmentCodeRaw]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__400E0917] DEFAULT ((0)) FOR [DSSDepartmentRollup3ID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__41022D50] DEFAULT ('') FOR [DSSDepartmentRollup3Name]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_DimDepartment_IsCAP] DEFAULT ((0)) FOR [IsCAP]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__IsOve__191A2EAB] DEFAULT ((0)) FOR [IsOverhead]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__OBIsD__3D526354] DEFAULT ((0)) FOR [OBIsDefined]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_FWDIMDEPARTMENTISOB] DEFAULT ((0)) FOR [IsOB]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_FWDIMDEPARTMENTISMRPLAN] DEFAULT ((0)) FOR [IsMRPlan]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__60630048] DEFAULT ((0)) FOR [DepartmentTypeID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_FWDIMDEPARTMENTISACTIVE] DEFAULT ((0)) FOR [IsActive]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__61572481] DEFAULT ('') FOR [DepartmentType]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__IsVar__5062D5C3] DEFAULT ((0)) FOR [IsVariable]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_DimDepartment_IsAcctFlexing] DEFAULT ((0)) FOR [IsAccountFlexing]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__OBGlo__69DEE9BB] DEFAULT ((0)) FOR [OBGlobalStatisticsPlanID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__MRVic__65137223] DEFAULT ('') FOR [MRVicePresident]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__OBGlo__6AD30DF4] DEFAULT ('') FOR [OBGlobalStatisticsPlan]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__MRDir__6607965C] DEFAULT ('') FOR [MRDirector]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__OBRei__6BC7322D] DEFAULT ((0)) FOR [OBReimbursementPlanID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__MRMan__66FBBA95] DEFAULT ('') FOR [MRManager]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__OBRei__6CBB5666] DEFAULT ('') FOR [OBReimbursementPlan]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__OBSer__6DAF7A9F] DEFAULT ((0)) FOR [OBServiceLinePlanID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__OBSer__6EA39ED8] DEFAULT ('') FOR [OBServiceLinePlan]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPIsD__3E46878D] DEFAULT ((0)) FOR [SPIsDefined]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_DimDepartment_FlexingBucketGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FlexingBucketGUID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_DimDepartment_IsLRFP] DEFAULT ((1)) FOR [IsLRFP]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_FWDIMDEPARTMENTROLLINGPLANID] DEFAULT ((0)) FOR [RollingPlanID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__IsCla__6CAD0619] DEFAULT ((0)) FOR [IsClaimsCosting]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPRol__22017ED5] DEFAULT ('') FOR [SPRollingForecastPlanName]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_FWDIMDEPARTMENTOPSPLANID] DEFAULT ((0)) FOR [OpsPlanID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPOpe__363D81AC] DEFAULT ('') FOR [SPOperationsPlanName]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__CompA__6F4D7455] DEFAULT ((0)) FOR [CompAnDepartmentID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_FWDIMDEPARTMENTBALPLANID] DEFAULT ((0)) FOR [BalPlanID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPBal__72526BB3] DEFAULT ('') FOR [SPBalanceSheetPlanName]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Patie__05630FEC] DEFAULT ((0)) FOR [PatientTypeRollup]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPHDe__46620409] DEFAULT ((0)) FOR [SPHDepartmentID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Patie__06573425] DEFAULT ('') FOR [PatientTypeRollupName]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPHDe__47562842] DEFAULT ((0)) FOR [SPHDepartmentConfidenceScore]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__JobCo__074B585E] DEFAULT ((0)) FOR [SPJobCodeGroup]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPHDe__484A4C7B] DEFAULT ((0)) FOR [SPHDepartmentIsValidated]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__JobCo__083F7C97] DEFAULT ('') FOR [SPJobCodeGroupName]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPPhy__0933A0D0] DEFAULT ((0)) FOR [SPPhysicianGroup]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPPhy__0A27C509] DEFAULT ('') FOR [SPPhysicianGroupName]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPAcc__0B1BE942] DEFAULT ((0)) FOR [SPAccountRollup]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPAcc__0C100D7B] DEFAULT ('') FOR [SPAccountRollupName]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPSer__595774EA] DEFAULT ((0)) FOR [SPServiceLineForecastType]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_DimDepartment_ConsolidatedCode] DEFAULT ('') FOR [ConsolidatedCode]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__IsHea__020F09F7] DEFAULT ((0)) FOR [IsHealthPlanAdmin]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_DimDepartment_IsConsolidated] DEFAULT ((0)) FOR [IsConsolidated]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__FWIsD__044B5B03] DEFAULT ((0)) FOR [FWIsDefined]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPHDe__4FEB6E43] DEFAULT ('') FOR [SPHDepartmentName]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__FW_DimDepartment_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPHDe__05C52EAB] DEFAULT ((0)) FOR [SPHDepartmentRollupIsValidated]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Produ__0BB4A8D9] DEFAULT ((0)) FOR [ProductivityPercentileID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPHDe__17CBA2F1] DEFAULT ((0)) FOR [SPHDepartmentRollupID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPHDe__18BFC72A] DEFAULT ('') FOR [SPHDepartmentRollupName]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__IsMRM__1988D110] DEFAULT ((0)) FOR [IsMRMetricTracking]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPHDe__19B3EB63] DEFAULT ((0)) FOR [SPHDepartmentRollupConfidenceScore]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__WorkW__20F64D92] DEFAULT ((0)) FOR [WorkWeekID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_datacap_DimCapitalDepartment_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_DimDepartment_IsPR] DEFAULT ((0)) FOR [IsPR]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_DimCapitalDepartment_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_DimDepartment_Code] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF_DimCapitalDepartment_Department] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Syste__3A80E3A1] DEFAULT ((0)) FOR [SystemID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Syste__3B7507DA] DEFAULT ('') FOR [System]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__30C9F8E0] DEFAULT ('') FOR [DepartmentRollup1Code]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Syste__3C692C13] DEFAULT ((0)) FOR [SystemSortOrder]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__4C27FA92] DEFAULT ('') FOR [DSSDepartmentRollup6Name]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__31BE1D19] DEFAULT ('') FOR [DepartmentRollup2Code]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__32B24152] DEFAULT ('') FOR [DepartmentRollup3Code]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Entit__3E517485] DEFAULT ('') FOR [Entity]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__33A6658B] DEFAULT ('') FOR [DepartmentRollup4Code]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Entit__3F4598BE] DEFAULT ((0)) FOR [EntitySortOrder]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__349A89C4] DEFAULT ('') FOR [DepartmentRollup5Code]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Entit__7898B414] DEFAULT ((-1)) FOR [EntityTypeOverride]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__358EADFD] DEFAULT ('') FOR [DepartmentRollup6Code]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__39DB38A1] DEFAULT ((0)) FOR [DepartmentRollup1ID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__3D2D71EF] DEFAULT ('') FOR [DepartmentRollup1]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Produ__37932B17] DEFAULT ('') FOR [ProductivityPercentile]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__5C6E178C] DEFAULT ((0)) FOR [DepartmentRollup1SortOrder]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPHDe__37D94B27] DEFAULT ((0)) FOR [SPHDepartmentTypeID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__CompA__38874F50] DEFAULT ('') FOR [CompAnDepartment]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__7313B5FD] DEFAULT ((0)) FOR [DepartmentRollup2ID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__3E219628] DEFAULT ('') FOR [DepartmentRollup2]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__5D623BC5] DEFAULT ((0)) FOR [DepartmentRollup2SortOrder]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__043E41FF] DEFAULT ((0)) FOR [DepartmentRollup3ID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__3F15BA61] DEFAULT ('') FOR [DepartmentRollup3]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__5E565FFE] DEFAULT ((0)) FOR [DepartmentRollup3SortOrder]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__05326638] DEFAULT ((0)) FOR [DepartmentRollup4ID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__4009DE9A] DEFAULT ('') FOR [DepartmentRollup4]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__5F4A8437] DEFAULT ((0)) FOR [DepartmentRollup4SortOrder]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__06268A71] DEFAULT ((0)) FOR [DepartmentRollup5ID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__40FE02D3] DEFAULT ('') FOR [DepartmentRollup5]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__603EA870] DEFAULT ((0)) FOR [DepartmentRollup5SortOrder]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__071AAEAA] DEFAULT ((0)) FOR [DepartmentRollup6ID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__41F2270C] DEFAULT ('') FOR [DepartmentRollup6]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__CAPDe__457F5D79] DEFAULT ((0)) FOR [CAPDefaultSalesTax]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__Depar__6132CCA9] DEFAULT ((0)) FOR [DepartmentRollup6SortOrder]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__CareS__44ABCE5E] DEFAULT ((0)) FOR [CareSettingID]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__SPHDe__471B8EB7] DEFAULT ('') FOR [SPHDepartmentType]; GO +ALTER TABLE [fw].[DimDepartment] ADD CONSTRAINT [DF__DimDepart__DSSDe__47634575] DEFAULT ('') FOR [DSSDepartmentRollup4Name]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimDepartmentPH ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimDepartmentPH] ( + [MemberGUID] uniqueidentifier NOT NULL, + [DepartmentPHID] tinyint NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Version] timestamp NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([DepartmentPHID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_DimDepartmentPH] ON [fw].[DimDepartmentPH] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimDepartmentPH] ADD CONSTRAINT [DF_DimDepartmentPH_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimDepartmentPH] ADD CONSTRAINT [DF_DimDepartmentPH_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimDepartmentPH] ADD CONSTRAINT [DF_DimDepartmentPH_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimDepartmentPH] ADD CONSTRAINT [DF__FW_DimDepartmentPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimDepartmentRollup1 ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimDepartmentRollup1] ( + [DepartmentRollup1ID] smallint NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Code] nvarchar(200) NOT NULL, + [SecureGroupID] int NOT NULL, + [SortOrder] int NOT NULL, + [TransactionID] int NOT NULL, + [Description] nvarchar(100) NOT NULL, + [Name] nvarchar(303) NOT NULL, + [EliminationsDepartmentID] int NOT NULL, + PRIMARY KEY ([DepartmentRollup1ID]) +); + +CREATE NONCLUSTERED INDEX [IX_DepartmentRollup1ID] ON [fw].[DimDepartmentRollup1] ([DepartmentRollup1ID]); +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimDepartmentRollup1] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimDepartmentRollup1] ADD CONSTRAINT [DF__DimDepart__Histo__0A612FA9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimDepartmentRollup1] ADD CONSTRAINT [DF__DimDepart__Elimi__518DFE68] DEFAULT ((0)) FOR [EliminationsDepartmentID]; GO +ALTER TABLE [fw].[DimDepartmentRollup1] ADD CONSTRAINT [DF__DimDepart__SortO__52E4AD52] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimDepartmentRollup1] ADD CONSTRAINT [DF__DimDepart__Membe__096D0B70] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimDepartmentRollup1] ADD CONSTRAINT [DF__DimDepartm__Code__0B5553E2] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimDepartmentRollup1] ADD CONSTRAINT [DF__FW_DimDepartmentRollup1_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimDepartmentRollup1] ADD CONSTRAINT [DF__DimDepart__Descr__780914CE] DEFAULT ('') FOR [Description]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimDepartmentRollup2 ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimDepartmentRollup2] ( + [DepartmentRollup2ID] smallint NOT NULL, + [Code] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [SecureGroupID] int NOT NULL, + [SortOrder] int NOT NULL, + [TransactionID] int NOT NULL, + [Description] nvarchar(100) NOT NULL, + [Name] nvarchar(303) NOT NULL, + [EliminationsDepartmentID] int NOT NULL, + PRIMARY KEY ([DepartmentRollup2ID]) +); + +CREATE NONCLUSTERED INDEX [IX_DepartmentRollup2ID] ON [fw].[DimDepartmentRollup2] ([DepartmentRollup2ID]); +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimDepartmentRollup2] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimDepartmentRollup2] ADD CONSTRAINT [DF__DimDepart__Histo__16C7068E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimDepartmentRollup2] ADD CONSTRAINT [DF__DimDepart__SortO__4A4F6751] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimDepartmentRollup2] ADD CONSTRAINT [DF__DimDepart__Elimi__528222A1] DEFAULT ((0)) FOR [EliminationsDepartmentID]; GO +ALTER TABLE [fw].[DimDepartmentRollup2] ADD CONSTRAINT [DF__DimDepartm__Code__14DEBE1C] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimDepartmentRollup2] ADD CONSTRAINT [DF__DimDepart__Membe__15D2E255] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimDepartmentRollup2] ADD CONSTRAINT [DF__FW_DimDepartmentRollup2_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimDepartmentRollup2] ADD CONSTRAINT [DF__DimDepart__Descr__78FD3907] DEFAULT ('') FOR [Description]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimDepartmentRollup3 ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimDepartmentRollup3] ( + [DepartmentRollup3ID] smallint NOT NULL, + [Code] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [SecureGroupID] int NOT NULL, + [SortOrder] int NOT NULL, + [TransactionID] int NOT NULL, + [Description] nvarchar(100) NOT NULL, + [Name] nvarchar(200) NOT NULL, + [EliminationsDepartmentID] int NOT NULL, + PRIMARY KEY ([DepartmentRollup3ID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimDepartmentRollup3] ([MemberGUID]); +CREATE NONCLUSTERED INDEX [IX_DepartmentRollup3ID] ON [fw].[DimDepartmentRollup3] ([DepartmentRollup3ID]); +GO +ALTER TABLE [fw].[DimDepartmentRollup3] ADD CONSTRAINT [DF__DimDepart__SortO__41BA2150] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimDepartmentRollup3] ADD CONSTRAINT [DF__DimDepart__Elimi__537646DA] DEFAULT ((0)) FOR [EliminationsDepartmentID]; GO +ALTER TABLE [fw].[DimDepartmentRollup3] ADD CONSTRAINT [DF__DimDepart__Histo__26FD6E57] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimDepartmentRollup3] ADD CONSTRAINT [DF__DimDepartm__Code__251525E5] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimDepartmentRollup3] ADD CONSTRAINT [DF__DimDepart__Membe__26094A1E] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimDepartmentRollup3] ADD CONSTRAINT [DF__FW_DimDepartmentRollup3_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimDepartmentRollup3] ADD CONSTRAINT [DF__DimDepart__Descr__79F15D40] DEFAULT ('') FOR [Description]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimDepartmentRollup4 ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimDepartmentRollup4] ( + [DepartmentRollup4ID] int NOT NULL, + [Code] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [SecureGroupID] int NOT NULL, + [SortOrder] int NOT NULL, + [TransactionID] int NOT NULL, + [Description] nvarchar(100) NOT NULL, + [Name] nvarchar(100) NOT NULL, + [EliminationsDepartmentID] int NOT NULL, + PRIMARY KEY ([DepartmentRollup4ID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimDepartmentRollup4] ([MemberGUID]); +CREATE NONCLUSTERED INDEX [IX_DepartmentRollup4ID] ON [fw].[DimDepartmentRollup4] ([DepartmentRollup4ID]); +GO +ALTER TABLE [fw].[DimDepartmentRollup4] ADD CONSTRAINT [DF__DimDepart__Histo__3363453C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimDepartmentRollup4] ADD CONSTRAINT [DF__DimDepart__SortO__3924DB4F] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimDepartmentRollup4] ADD CONSTRAINT [DF__DimDepart__Elimi__546A6B13] DEFAULT ((0)) FOR [EliminationsDepartmentID]; GO +ALTER TABLE [fw].[DimDepartmentRollup4] ADD CONSTRAINT [DF__DimDepartm__Code__317AFCCA] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimDepartmentRollup4] ADD CONSTRAINT [DF__DimDepart__Membe__326F2103] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimDepartmentRollup4] ADD CONSTRAINT [DF__FW_DimDepartmentRollup4_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimDepartmentRollup4] ADD CONSTRAINT [DF__DimDepart__Descr__7AE58179] DEFAULT ('') FOR [Description]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimDepartmentRollup5 ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimDepartmentRollup5] ( + [DepartmentRollup5ID] smallint NOT NULL, + [Code] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [SecureGroupID] int NOT NULL, + [SortOrder] int NOT NULL, + [TransactionID] int NOT NULL, + [Description] nvarchar(100) NOT NULL, + [Name] nvarchar(100) NOT NULL, + [EliminationsDepartmentID] int NOT NULL, + PRIMARY KEY ([DepartmentRollup5ID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimDepartmentRollup5] ([MemberGUID]); +CREATE NONCLUSTERED INDEX [IX_DepartmentRollup5ID] ON [fw].[DimDepartmentRollup5] ([DepartmentRollup5ID]); +GO +ALTER TABLE [fw].[DimDepartmentRollup5] ADD CONSTRAINT [DF__DimDepartm__Code__3DE0D3AF] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimDepartmentRollup5] ADD CONSTRAINT [DF__DimDepart__Membe__3ED4F7E8] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimDepartmentRollup5] ADD CONSTRAINT [DF__DimDepart__SortO__308F954E] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimDepartmentRollup5] ADD CONSTRAINT [DF__DimDepart__Elimi__555E8F4C] DEFAULT ((0)) FOR [EliminationsDepartmentID]; GO +ALTER TABLE [fw].[DimDepartmentRollup5] ADD CONSTRAINT [DF__DimDepart__Histo__3FC91C21] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimDepartmentRollup5] ADD CONSTRAINT [DF__FW_DimDepartmentRollup5_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimDepartmentRollup5] ADD CONSTRAINT [DF__DimDepart__Descr__7BD9A5B2] DEFAULT ('') FOR [Description]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimDepartmentRollup6 ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimDepartmentRollup6] ( + [DepartmentRollup6ID] smallint NOT NULL, + [Code] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [SecureGroupID] int NOT NULL, + [SortOrder] int NOT NULL, + [TransactionID] int NOT NULL, + [Description] nvarchar(100) NOT NULL, + [Name] nvarchar(100) NOT NULL, + [EliminationsDepartmentID] int NOT NULL, + PRIMARY KEY ([DepartmentRollup6ID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimDepartmentRollup6] ([MemberGUID]); +CREATE NONCLUSTERED INDEX [IX_DepartmentRollup6ID] ON [fw].[DimDepartmentRollup6] ([DepartmentRollup6ID]); +GO +ALTER TABLE [fw].[DimDepartmentRollup6] ADD CONSTRAINT [DF__DimDepartm__Code__4A46AA94] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimDepartmentRollup6] ADD CONSTRAINT [DF__DimDepart__Membe__4B3ACECD] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimDepartmentRollup6] ADD CONSTRAINT [DF__DimDepart__SortO__27FA4F4D] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimDepartmentRollup6] ADD CONSTRAINT [DF__DimDepart__Elimi__5652B385] DEFAULT ((0)) FOR [EliminationsDepartmentID]; GO +ALTER TABLE [fw].[DimDepartmentRollup6] ADD CONSTRAINT [DF__DimDepart__Histo__4C2EF306] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimDepartmentRollup6] ADD CONSTRAINT [DF__FW_DimDepartmentRollup6_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimDepartmentRollup6] ADD CONSTRAINT [DF__DimDepart__Descr__7CCDC9EB] DEFAULT ('') FOR [Description]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimDepartmentType ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimDepartmentType] ( + [HistoryItemGUID] uniqueidentifier NOT NULL, + [DepartmentTypeID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [TransactionID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [Rollup] nvarchar(1000) NOT NULL, + PRIMARY KEY ([DepartmentTypeID]) +); +GO +ALTER TABLE [fw].[DimDepartmentType] ADD CONSTRAINT [DF__DimDepart__Histo__59B602B9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimDepartmentType] ADD CONSTRAINT [DF__DimDepartm__Name__5B9E4B2B] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimDepartmentType] ADD CONSTRAINT [DF__DimDepart__Trans__5C926F64] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimDepartmentType] ADD CONSTRAINT [DF__DimDepart__Membe__5D86939D] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimDepartmentType] ADD CONSTRAINT [DF__DimDepart__Rollu__5E7AB7D6] DEFAULT ('') FOR [Rollup]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimEmployee ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimEmployee] ( + [EmployeeID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [NameLast] nvarchar(200) NOT NULL, + [NameFirst] nvarchar(200) NOT NULL, + [Number] nvarchar(200) NOT NULL, + [JobCodeID] int NOT NULL, + [JobCode] nvarchar(151) NOT NULL, + [JobCodeCode] nvarchar(100) NOT NULL, + [Code] nvarchar(200) NOT NULL, + [OBIsDefined] bit NOT NULL, + [WageRate] money NOT NULL, + [IsProvider] bit NOT NULL, + [ProviderID] int NOT NULL, + [IsVariable] bit NOT NULL, + [HireDate] datetime NOT NULL, + [IsActive] bit NOT NULL, + [Status] nvarchar(100) NOT NULL, + [NextReview] datetime NOT NULL, + [TransactionID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [WorkWeekOverrideID] int NOT NULL, + [HomeDepartmentID] int NOT NULL, + [HomeDepartment] nvarchar(203) NOT NULL, + [HomeDepartmentCode] nvarchar(100) NOT NULL, + [NameFull] nvarchar(401) NOT NULL, + [EmployeeCohortID] int NOT NULL, + [EmployeeCohortName] nvarchar(100) NOT NULL, + [EmployeeCohortContractDate] datetime NOT NULL, + [EmployeeCohortMeritType] nvarchar(100) NOT NULL, + [StandardHours] nvarchar(100) NOT NULL, + [FWIsDefined] bit NOT NULL, + [TerminationDate] datetime NOT NULL, + [AdjustedHireDate] datetime NOT NULL, + [FTETotal] float NOT NULL, + [HomeAccountID] int NOT NULL, + [HomeAccount] nvarchar(100) NOT NULL, + [HomeAccountCode] nvarchar(100) NOT NULL, + [EmployeeClass] nvarchar(100) NOT NULL, + [Name] nvarchar(707) NOT NULL, + [NPI] nvarchar(50) NOT NULL, + [PositionControlNumber] nvarchar(100) NOT NULL, + PRIMARY KEY ([EmployeeID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimEmployee] ([MemberGUID]); +CREATE NONCLUSTERED INDEX [NCNU_IsProvider] ON [fw].[DimEmployee] ([EmployeeID], [IsProvider]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Code] ON [fw].[DimEmployee] ([Code]) INCLUDE ([EmployeeID]); +CREATE NONCLUSTERED INDEX [CORE_HomeDepartmentID_inc] ON [fw].[DimEmployee] ([HomeDepartmentID]) INCLUDE ([Name]); +GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__FWIsD__081BEBE7] DEFAULT ((0)) FOR [FWIsDefined]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Emplo__100E1AB7] DEFAULT ((0)) FOR [EmployeeCohortID]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Emplo__11023EF0] DEFAULT ('') FOR [EmployeeCohortName]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Emplo__11F66329] DEFAULT (getdate()) FOR [EmployeeCohortContractDate]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Emplo__12EA8762] DEFAULT ('') FOR [EmployeeCohortMeritType]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Stand__13DEAB9B] DEFAULT ('40') FOR [StandardHours]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__WorkW__24C6DE76] DEFAULT ((0)) FOR [WorkWeekOverrideID]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF_DimEmployee_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__NameL__4D6EC6B0] DEFAULT ('') FOR [NameLast]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__NameF__4C7AA277] DEFAULT ('') FOR [NameFirst]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Numbe__574A0949] DEFAULT ('') FOR [Number]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__JobCo__59F6619E] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__JobCo__690C57C1] DEFAULT ('') FOR [JobCode]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Posit__454AB6E3] DEFAULT ('') FOR [PositionControlNumber]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__JobCo__150BA0E7] DEFAULT ('') FOR [JobCodeCode]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__CodeN__1170E584] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__OBIsD__18F14064] DEFAULT ((0)) FOR [OBIsDefined]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__WageR__58E0795C] DEFAULT ((0)) FOR [WageRate]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__IsPro__5C19DD28] DEFAULT ((0)) FOR [IsProvider]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Provi__72A7A338] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__IsVar__6A007BFA] DEFAULT ((0)) FOR [IsVariable]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF_FWDIMEMPLOYEEHIREDATE] DEFAULT (getdate()) FOR [HireDate]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__IsAct__5BBEE049] DEFAULT ((1)) FOR [IsActive]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF_DimEmployee_Status] DEFAULT ('') FOR [Status]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF_FWDIMEMPLOYEENEXTREVIEW] DEFAULT (getdate()) FOR [NextReview]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__FW_DimEmployee_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF_DimEmployee_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__HomeD__5F943537] DEFAULT ((0)) FOR [HomeDepartmentID]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__HomeD__60885970] DEFAULT ('') FOR [HomeDepartment]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Termi__61221A57] DEFAULT ('1900-01-01 0:00') FOR [TerminationDate]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__HomeD__617C7DA9] DEFAULT ('') FOR [HomeDepartmentCode]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Adjus__62163E90] DEFAULT ('1900-01-01 0:00') FOR [AdjustedHireDate]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__FTETo__630A62C9] DEFAULT ((0)) FOR [FTETotal]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__HomeA__63FE8702] DEFAULT ((0)) FOR [HomeAccountID]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmployee__NPI__648666AC] DEFAULT ('') FOR [NPI]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__HomeA__64F2AB3B] DEFAULT ('') FOR [HomeAccount]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__HomeA__65E6CF74] DEFAULT ('') FOR [HomeAccountCode]; GO +ALTER TABLE [fw].[DimEmployee] ADD CONSTRAINT [DF__DimEmploy__Emplo__66DAF3AD] DEFAULT ('') FOR [EmployeeClass]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimEmployeeCohort ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimEmployeeCohort] ( + [EmployeeCohortID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [Description] nvarchar(200) NOT NULL, + [Code] nvarchar(100) NOT NULL, + [SortOrder] nvarchar(100) NOT NULL, + [MeritType] nvarchar(100) NOT NULL, + [ContractDate] datetime NOT NULL, + PRIMARY KEY ([EmployeeCohortID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimEmployeeCohort] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimEmployeeCohort] ADD CONSTRAINT [DF__DimEmploy__Histo__755A247B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimEmployeeCohort] ADD CONSTRAINT [DF__DimEmploye__Name__7371DC09] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimEmployeeCohort] ADD CONSTRAINT [DF__DimEmploy__Membe__74660042] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimEmployeeCohort] ADD CONSTRAINT [DF__DimEmploy__Trans__764E48B4] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimEmployeeCohort] ADD CONSTRAINT [DF__DimEmploy__Descr__77426CED] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fw].[DimEmployeeCohort] ADD CONSTRAINT [DF__DimEmploye__Code__78369126] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimEmployeeCohort] ADD CONSTRAINT [DF__DimEmploy__SortO__792AB55F] DEFAULT ('') FOR [SortOrder]; GO +ALTER TABLE [fw].[DimEmployeeCohort] ADD CONSTRAINT [DF__DimEmploy__Merit__7A1ED998] DEFAULT ('') FOR [MeritType]; GO +ALTER TABLE [fw].[DimEmployeeCohort] ADD CONSTRAINT [DF__DimEmploy__Contr__7C07220A] DEFAULT (getdate()) FOR [ContractDate]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimEmployeePH ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimEmployeePH] ( + [EmployeePHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([EmployeePHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimEmployeePH] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimEmployeePH] ADD CONSTRAINT [DF__DimEmploy__Membe__64A40467] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimEmployeePH] ADD CONSTRAINT [DF__DimEmploye__Name__63AFE02E] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimEmployeePH] ADD CONSTRAINT [DF__FW_DimEmployeePH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimEntity ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimEntity] ( + [EntityID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [Code] nvarchar(200) NOT NULL, + [Description] nvarchar(100) NOT NULL, + [SortOrder] int NOT NULL, + [EntityType] smallint NOT NULL, + [IsActive] bit NOT NULL, + [CAPIsDefined] bit NOT NULL, + [DSSIsDefined] bit NOT NULL, + [OBIsDefined] bit NOT NULL, + [OBBenefitsDepartmentID] int NOT NULL, + [OBBenefitsDepartment] nvarchar(203) NOT NULL, + [OBHasGlobalStatisticsPlan] bit NOT NULL, + [OBHasReimbursementPlan] bit NOT NULL, + [OBHasServiceLinePlan] bit NOT NULL, + [OBIsUsingProviderComp] bit NOT NULL, + [SPIsDefined] bit NOT NULL, + [SPGrossChargesPatientTypeRollup] smallint NOT NULL, + [SPGrossChargesPayorGroup] smallint NOT NULL, + [SPContractualsPatientTypeRollup] smallint NOT NULL, + [SPContractualsPayorGroup] smallint NOT NULL, + [SPIPVolumesPatientTypeRollup] smallint NOT NULL, + [SPIPVolumesPayorGroup] smallint NOT NULL, + [SPIPDaysPatientTypeRollup] smallint NOT NULL, + [SPIPDaysPayorGroup] smallint NOT NULL, + [SPOPVolumesPatientTypeRollup] smallint NOT NULL, + [SPOPVolumesPayorGroup] smallint NOT NULL, + [SPFTEsJobCodeGroup] smallint NOT NULL, + [SPSalariesJobCodeGroup] smallint NOT NULL, + [SPClinicGrossChargesPayorGroup] smallint NOT NULL, + [SPClinicContractualsPayorGroup] smallint NOT NULL, + [SPClinicPrimaryVolumePhysicianGroup] smallint NOT NULL, + [SPClinicSecondaryVolumePhysicianGroup] smallint NOT NULL, + [SPClinicFTEsPhysicianGroup] smallint NOT NULL, + [SPClinicSalariesPhysicianGroup] smallint NOT NULL, + [SPServiceLineForecastType] smallint NOT NULL, + [SPOperationsSLDrivenModelID] int NOT NULL, + [SPRollingForecastSLDrivenModelID] int NOT NULL, + [TransactionID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(303) NOT NULL, + [SecureGroupID] int NOT NULL, + [WorkWeekID] int NOT NULL, + [CAPDefaultSalesTax] float NOT NULL, + [PayCycleID] int NOT NULL, + [FWIsDefined] bit NOT NULL, + [EliminationsDepartmentID] int NOT NULL, + [CompAnPeerGroupID] int NOT NULL, + PRIMARY KEY ([EntityID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimEntity] ([MemberGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [CORE_CodeUnique] ON [fw].[DimEntity] ([Code]); +GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__FWIsD__0633A375] DEFAULT ((0)) FOR [FWIsDefined]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__Membe__30F77967] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__Code__33D3E612] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__Descr__34C80A4B] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__Histo__31EB9DA0] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SortO__35BC2E84] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__Entit__0E6D5739] DEFAULT ((0)) FOR [EntityType]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__IsAct__56439C10] DEFAULT ((1)) FOR [IsActive]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__CAPIs__35F4660A] DEFAULT ((0)) FOR [CAPIsDefined]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__DSSIs__36E88A43] DEFAULT ((0)) FOR [DSSIsDefined]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__OBIsD__37DCAE7C] DEFAULT ((0)) FOR [OBIsDefined]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__OBBen__6A84FC7E] DEFAULT ('') FOR [OBBenefitsDepartment]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__OBHas__6F97C311] DEFAULT ((0)) FOR [OBHasGlobalStatisticsPlan]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__OBHas__337982C0] DEFAULT ((0)) FOR [OBHasReimbursementPlan]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__OBHas__346DA6F9] DEFAULT ((0)) FOR [OBHasServiceLinePlan]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__OBIsU__2E02373A] DEFAULT ((0)) FOR [OBIsUsingProviderComp]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPIsD__38D0D2B5] DEFAULT ((0)) FOR [SPIsDefined]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__WorkW__20022959] DEFAULT ((0)) FOR [WorkWeekID]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPGro__0F617B72] DEFAULT ((0)) FOR [SPGrossChargesPatientTypeRollup]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPGro__1149C3E4] DEFAULT ((0)) FOR [SPGrossChargesPayorGroup]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPCon__10559FAB] DEFAULT ((0)) FOR [SPContractualsPatientTypeRollup]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPCon__123DE81D] DEFAULT ((0)) FOR [SPContractualsPayorGroup]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPIPV__13320C56] DEFAULT ((0)) FOR [SPIPVolumesPatientTypeRollup]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPIPV__1426308F] DEFAULT ((0)) FOR [SPIPVolumesPayorGroup]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPIPD__151A54C8] DEFAULT ((0)) FOR [SPIPDaysPatientTypeRollup]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPIPD__160E7901] DEFAULT ((0)) FOR [SPIPDaysPayorGroup]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPOPV__17029D3A] DEFAULT ((0)) FOR [SPOPVolumesPatientTypeRollup]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPOPV__17F6C173] DEFAULT ((0)) FOR [SPOPVolumesPayorGroup]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPFTE__1EA3BF02] DEFAULT ((0)) FOR [SPFTEsJobCodeGroup]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPSal__1DAF9AC9] DEFAULT ((0)) FOR [SPSalariesJobCodeGroup]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPCli__1BC75257] DEFAULT ((0)) FOR [SPClinicGrossChargesPayorGroup]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPCli__1CBB7690] DEFAULT ((0)) FOR [SPClinicContractualsPayorGroup]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPCli__1F97E33B] DEFAULT ((0)) FOR [SPClinicPrimaryVolumePhysicianGroup]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPCli__208C0774] DEFAULT ((0)) FOR [SPClinicSecondaryVolumePhysicianGroup]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPCli__19DF09E5] DEFAULT ((0)) FOR [SPClinicFTEsPhysicianGroup]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPCli__1AD32E1E] DEFAULT ((0)) FOR [SPClinicSalariesPhysicianGroup]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPSer__52AA775B] DEFAULT ((0)) FOR [SPServiceLineForecastType]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPOpe__0CD7E447] DEFAULT ((0)) FOR [SPOperationsSLDrivenModelID]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__OBBen__5D2B0160] DEFAULT ((0)) FOR [OBBenefitsDepartmentID]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__SPRol__0DCC0880] DEFAULT ((0)) FOR [SPRollingForecastSLDrivenModelID]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__Trans__32DFC1D9] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__CompA__3E40F3FD] DEFAULT ((0)) FOR [CompAnPeerGroupID]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__CAPDe__448B3940] DEFAULT ((0)) FOR [CAPDefaultSalesTax]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__PayCy__472A10CE] DEFAULT ((0)) FOR [PayCycleID]; GO +ALTER TABLE [fw].[DimEntity] ADD CONSTRAINT [DF__DimEntity__Elimi__5099DA2F] DEFAULT ((0)) FOR [EliminationsDepartmentID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimEntityPH ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimEntityPH] ( + [EntityPHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([EntityPHID]) +); +GO +ALTER TABLE [fw].[DimEntityPH] ADD CONSTRAINT [DF__DimEntityPH_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimEntityPH] ADD CONSTRAINT [DF__DimEntityPH_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimEntityPH] ADD CONSTRAINT [DF__DimEntityPH_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimEntityPH] ADD CONSTRAINT [DF__DimEntityPH_TransactionID] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimFiscalMonth ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimFiscalMonth] ( + [MemberGUID] uniqueidentifier NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [SortOrder] tinyint NOT NULL, + [FiscalMonthCode] nvarchar(20) NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Abbreviation] nvarchar(3) NOT NULL, + [DaysInMonth] int NOT NULL, + [YTDDaysInMonth] int NOT NULL, + [QuarterID] tinyint NOT NULL, + [MonthColumnName] nvarchar(7) NOT NULL, + [Version] timestamp NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [DaysInLeapYearMonth] int NOT NULL, + [YTDDaysInLeapYearMonth] int NOT NULL, + [IsReal] bit NOT NULL, + PRIMARY KEY ([FiscalMonthID]) +); + +CREATE NONCLUSTERED INDEX [IX_Name] ON [fw].[DimFiscalMonth] ([Name]); +CREATE NONCLUSTERED INDEX [IX_FiscalMonthCode] ON [fw].[DimFiscalMonth] ([FiscalMonthCode]); +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimFiscalMonth] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF_DimFiscalMonth_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF_DimFiscalMonth_CalendarMonthID] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF_DimFiscalMonth_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF_DimFiscalMonth_Abbreviation] DEFAULT ('') FOR [Abbreviation]; GO +ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF_FWDIMFISCALMONTHFISCALMONTHCODE] DEFAULT ('0') FOR [FiscalMonthCode]; GO +ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF_DimFiscalMonth_DaysInMonth] DEFAULT ((0)) FOR [DaysInMonth]; GO +ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF_DimFiscalMonth_YTDDaysInMonth] DEFAULT ((0)) FOR [YTDDaysInMonth]; GO +ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF__DimFiscal__Quart__6B860C20] DEFAULT ((0)) FOR [QuarterID]; GO +ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF_DimFiscalMonth_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF__DimFiscal__IsRea__4EA04A0D] DEFAULT ((0)) FOR [IsReal]; GO +ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF__DimFiscal__DaysI__5551D9DC] DEFAULT ((0)) FOR [DaysInLeapYearMonth]; GO +ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF__DimFiscal__YTDDa__5645FE15] DEFAULT ((0)) FOR [YTDDaysInLeapYearMonth]; GO +ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF_FWDIMFISCALMONTHFISCALMONTHID] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fw].[DimFiscalMonth] ADD CONSTRAINT [DF__FW_DimFiscalMonth_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimFiscalTime ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimFiscalTime] ( + [FiscalTimeID] int NOT NULL, + [FiscalTime] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [YearMonth] nvarchar(25) NOT NULL, + [FiscalYearMonth] nvarchar(12) NOT NULL, + [CountFromCurrentMonth] int NOT NULL, + [StartDate] datetime NOT NULL, + [EndDate] datetime NOT NULL, + PRIMARY KEY ([FiscalTimeID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimFiscalTime] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__Fisca__07354875] DEFAULT ('') FOR [FiscalTime]; GO +ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__Membe__08296CAE] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__Trans__0A11B520] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__Fisca__0B05D959] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__Fisca__0BF9FD92] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__YearM__0CEE21CB] DEFAULT ('') FOR [YearMonth]; GO +ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__Histo__091D90E7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__Fisca__4F8782DD] DEFAULT ('') FOR [FiscalYearMonth]; GO +ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__Count__72BC7BD8] DEFAULT ((0)) FOR [CountFromCurrentMonth]; GO +ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__Start__73B0A011] DEFAULT (getdate()) FOR [StartDate]; GO +ALTER TABLE [fw].[DimFiscalTime] ADD CONSTRAINT [DF__DimFiscal__EndDa__74A4C44A] DEFAULT (getdate()) FOR [EndDate]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimFiscalYear ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimFiscalYear] ( + [MemberGUID] uniqueidentifier NOT NULL, + [FiscalYearID] smallint NOT NULL, + [Name] nvarchar(20) NOT NULL, + [SortOrder] nvarchar(10) NOT NULL, + [Version] timestamp NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [IsSP] bit NOT NULL, + [TransactionID] int NOT NULL, + [IsCAP] bit NOT NULL, + PRIMARY KEY ([FiscalYearID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_MemberGUID] ON [fw].[DimFiscalYear] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimFiscalYear] ADD CONSTRAINT [DF__DimFiscalY__IsSP__01014914] DEFAULT ((0)) FOR [IsSP]; GO +ALTER TABLE [fw].[DimFiscalYear] ADD CONSTRAINT [DF_FWDIMFISCALYEARFISCALYEARID] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fw].[DimFiscalYear] ADD CONSTRAINT [DF_DimFiscalYear_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimFiscalYear] ADD CONSTRAINT [DF_DimFiscalYear_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimFiscalYear] ADD CONSTRAINT [DF_DimFiscalYear_SortOrder] DEFAULT ('') FOR [SortOrder]; GO +ALTER TABLE [fw].[DimFiscalYear] ADD CONSTRAINT [DF_DimFiscalYear_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimFiscalYear] ADD CONSTRAINT [DF__DimFiscal__IsCAP__4F946E46] DEFAULT ((0)) FOR [IsCAP]; GO +ALTER TABLE [fw].[DimFiscalYear] ADD CONSTRAINT [DF__FW_DimFiscalYear_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimFiscalYearPH ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimFiscalYearPH] ( + [MemberGUID] uniqueidentifier NOT NULL, + [FiscalYearPHID] tinyint NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Version] timestamp NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([FiscalYearPHID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_DimFiscalYearPH] ON [fw].[DimFiscalYearPH] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimFiscalYearPH] ADD CONSTRAINT [DF__FW_DimFiscalYearPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimFiscalYearPH] ADD CONSTRAINT [DF_DimFiscalYearPH_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimFiscalYearPH] ADD CONSTRAINT [DF_DimFiscalYearPH_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimFiscalYearPH] ADD CONSTRAINT [DF_DimFiscalYearPH_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimFlag ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimFlag] ( + [FlagID] int NOT NULL, + [Name] nvarchar(203) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [Code] nvarchar(100) NOT NULL, + [Description] nvarchar(100) NOT NULL, + PRIMARY KEY ([FlagID]) +); + +CREATE NONCLUSTERED INDEX [NCU_Code] ON [fw].[DimFlag] ([Code]); +GO +ALTER TABLE [fw].[DimFlag] ADD CONSTRAINT [DF__DimFlag__MemberG__1A867D5D] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimFlag] ADD CONSTRAINT [DF__DimFlag__History__1B7AA196] DEFAULT (newid()) FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimFlag] ADD CONSTRAINT [DF__DimFlag__Transac__1C6EC5CF] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimFlag] ADD CONSTRAINT [DF__DimFlag__Code__1D62EA08] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimFlag] ADD CONSTRAINT [DF__DimFlag__Descrip__1E570E41] DEFAULT ('') FOR [Description]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimFlexJobCodeGroup ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimFlexJobCodeGroup] ( + [FlexJobCodeGroupID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [Code] nvarchar(100) NOT NULL, + [SortOrder] int NOT NULL, + PRIMARY KEY ([FlexJobCodeGroupID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimFlexJobCodeGroup] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimFlexJobCodeGroup] ADD CONSTRAINT [DF__DimFlexJo__Histo__3F076A14] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimFlexJobCodeGroup] ADD CONSTRAINT [DF__DimFlexJob__Name__3D1F21A2] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimFlexJobCodeGroup] ADD CONSTRAINT [DF__DimFlexJo__Membe__3E1345DB] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimFlexJobCodeGroup] ADD CONSTRAINT [DF__DimFlexJo__Trans__3FFB8E4D] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimFlexJobCodeGroup] ADD CONSTRAINT [DF__DimFlexJob__Code__40EFB286] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimFlexJobCodeGroup] ADD CONSTRAINT [DF__DimFlexJo__SortO__41E3D6BF] DEFAULT ((0)) FOR [SortOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimForecastDetail ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimForecastDetail] ( + [ForecastDetailID] int NOT NULL, + [ForecastDetailCode] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [Description] nvarchar(200) NOT NULL, + [Name] nvarchar(403) NOT NULL, + [OBForecastDetailID] int NOT NULL, + [CAPForecastDetailID] int NOT NULL, + [SPCostComponentID] int NOT NULL, + [SPAccountRollupID] int NOT NULL, + [SPIsDefined] bit NOT NULL, + [CPIsDefined] bit NOT NULL, + [OBIsDefined] bit NOT NULL, + PRIMARY KEY ([ForecastDetailID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimForecastDetail] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__Histo__790F4C0E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__CPIsD__6D695A8F] DEFAULT ((0)) FOR [CPIsDefined]; GO +ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__OBIsD__6E5D7EC8] DEFAULT ((0)) FOR [OBIsDefined]; GO +ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__Forec__7727039C] DEFAULT ('') FOR [ForecastDetailCode]; GO +ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__Membe__781B27D5] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__Trans__7A037047] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__Descr__7AF79480] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__OBFor__7BEBB8B9] DEFAULT ((0)) FOR [OBForecastDetailID]; GO +ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__CAPFo__7CDFDCF2] DEFAULT ((0)) FOR [CAPForecastDetailID]; GO +ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__SPCos__7DD4012B] DEFAULT ((0)) FOR [SPCostComponentID]; GO +ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__SPAcc__7EC82564] DEFAULT ((0)) FOR [SPAccountRollupID]; GO +ALTER TABLE [fw].[DimForecastDetail] ADD CONSTRAINT [DF__DimForeca__SPIsD__7FBC499D] DEFAULT ((0)) FOR [SPIsDefined]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimFramework ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimFramework] ( + [MemberGUID] uniqueidentifier NOT NULL, + [FrameworkID] tinyint NOT NULL, + [Name] nvarchar(100) NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [Abbreviation] nvarchar(10) NOT NULL, + [FrameworkSchemaName] nvarchar(10) NOT NULL, + [ClientSchemaName] nvarchar(10) NOT NULL, + [TransactionID] int NOT NULL, + [IsLatestDataModel] bit NOT NULL, + [Dependencies] nvarchar(100) NOT NULL, + PRIMARY KEY ([FrameworkID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimFramework] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimFramework] ADD CONSTRAINT [DF__FW_DimFramework_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimFramework] ADD CONSTRAINT [DF_DimFramework_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimFramework] ADD CONSTRAINT [DF_DimFramework_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimFramework] ADD CONSTRAINT [DF_DimFramework_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimFramework] ADD CONSTRAINT [DF_DimFramework_Dependencies] DEFAULT ('') FOR [Dependencies]; GO +ALTER TABLE [fw].[DimFramework] ADD CONSTRAINT [DF_DimFramework_Abbreviation] DEFAULT ('') FOR [Abbreviation]; GO +ALTER TABLE [fw].[DimFramework] ADD CONSTRAINT [DF_DimFramework_FrameworkSchemaName] DEFAULT ('') FOR [FrameworkSchemaName]; GO +ALTER TABLE [fw].[DimFramework] ADD CONSTRAINT [DF_DimFramework_ClientSchemaName] DEFAULT ('') FOR [ClientSchemaName]; GO +ALTER TABLE [fw].[DimFramework] ADD CONSTRAINT [DF_DimFramework_IsLatestDataModel] DEFAULT ((0)) FOR [IsLatestDataModel]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimFunctionalArea ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimFunctionalArea] ( + [FunctionalAreaID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([FunctionalAreaID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimFunctionalArea] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimFunctionalArea] ADD CONSTRAINT [DF__DimFunctio__Name__0A59084A] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimFunctionalArea] ADD CONSTRAINT [DF__DimFuncti__Membe__0B4D2C83] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimFunctionalArea] ADD CONSTRAINT [DF__DimFuncti__Trans__0D3574F5] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimFunctionalArea] ADD CONSTRAINT [DF__DimFuncti__Histo__0C4150BC] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimFund ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimFund] ( + [FundID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [SortOrder] int NOT NULL, + [Code] nvarchar(100) NOT NULL, + [Description] nvarchar(100) NOT NULL, + [Name] nvarchar(203) NOT NULL, + PRIMARY KEY ([FundID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimFund] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimFund] ADD CONSTRAINT [DF__DimFund__History__78B67F6A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimFund] ADD CONSTRAINT [DF__DimFund__MemberG__77C25B31] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimFund] ADD CONSTRAINT [DF__DimFund__Transac__79AAA3A3] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimFund] ADD CONSTRAINT [DF__DimFund__SortOrd__7A9EC7DC] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimFund] ADD CONSTRAINT [DF__DimFund__Code__7B92EC15] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimFund] ADD CONSTRAINT [DF__DimFund__Descrip__7C87104E] DEFAULT ('') FOR [Description]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimHomeDepartment ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimHomeDepartment] ( + [HomeDepartmentID] int NOT NULL, + [Name] nvarchar(203) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [SortOrder] int NOT NULL, + [Description] nvarchar(100) NOT NULL, + [Code] nvarchar(100) NOT NULL, + PRIMARY KEY ([HomeDepartmentID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimHomeDepartment] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimHomeDepartment] ADD CONSTRAINT [DF__DimHomeDe__Histo__466009C7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimHomeDepartment] ADD CONSTRAINT [DF__DimHomeDe__Membe__456BE58E] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimHomeDepartment] ADD CONSTRAINT [DF__DimHomeDe__Trans__47542E00] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimHomeDepartment] ADD CONSTRAINT [DF__DimHomeDe__SortO__48485239] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimHomeDepartment] ADD CONSTRAINT [DF__DimHomeDe__Descr__493C7672] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fw].[DimHomeDepartment] ADD CONSTRAINT [DF__DimHomeDep__Code__4A309AAB] DEFAULT ('') FOR [Code]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimInitiative ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimInitiative] ( + [InitiativeID] int NOT NULL, + [Name] nvarchar(400) NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [InitiativeStatusID] int NOT NULL, + [InitiativeStatus] nvarchar(200) NOT NULL, + [AuthorGUID] uniqueidentifier NOT NULL, + [Author] nvarchar(200) NOT NULL, + [CostLeaderGUID] uniqueidentifier NOT NULL, + [CostLeader] nvarchar(200) NOT NULL, + [OwnerGUID] uniqueidentifier NOT NULL, + [Owner] nvarchar(200) NOT NULL, + [ExecutiveSponsorGUID] uniqueidentifier NOT NULL, + [ExecutiveSponsor] nvarchar(200) NOT NULL, + [Workstream] nvarchar(200) NOT NULL, + [Description] nvarchar(max) NOT NULL, + [SourceOfSavingsId] int NOT NULL, + [SourceOfSavings] nvarchar(200) NOT NULL, + [DateCreated] datetime NOT NULL, + [EffectiveDate] datetime NOT NULL, + [GoalStartDate] datetime NOT NULL, + [GoalEndDate] datetime NOT NULL, + [AnnualGoal] decimal NOT NULL, + [SavingsEstimate] decimal NOT NULL, + [InitiativeRollup1] nvarchar(400) NOT NULL, + [InitiativeRollup1Id] int NOT NULL, + [InitiativeRollup2] nvarchar(400) NOT NULL, + [InitiativeRollup2Id] int NOT NULL, + [InitiativeRollup3] nvarchar(400) NOT NULL, + [InitiativeRollup3Id] int NOT NULL, + PRIMARY KEY ([InitiativeID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimInitiative] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitiat__Name__58137294] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Membe__590796CD] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Histo__59FBBB06] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Trans__5AEFDF3F] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Initi__5BE40378] DEFAULT ((0)) FOR [InitiativeStatusID]; GO +ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Initi__5CD827B1] DEFAULT ('') FOR [InitiativeStatus]; GO +ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Autho__5DCC4BEA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AuthorGUID]; GO +ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Autho__5EC07023] DEFAULT ('') FOR [Author]; GO +ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__CostL__5FB4945C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CostLeaderGUID]; GO +ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__CostL__60A8B895] DEFAULT ('') FOR [CostLeader]; GO +ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Owner__619CDCCE] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [OwnerGUID]; GO +ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Owner__62910107] DEFAULT ('') FOR [Owner]; GO +ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Execu__63852540] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ExecutiveSponsorGUID]; GO +ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Execu__64794979] DEFAULT ('') FOR [ExecutiveSponsor]; GO +ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Works__656D6DB2] DEFAULT ('') FOR [Workstream]; GO +ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Descr__666191EB] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Sourc__6755B624] DEFAULT ((0)) FOR [SourceOfSavingsId]; GO +ALTER TABLE [fw].[DimInitiative] ADD CONSTRAINT [DF__DimInitia__Sourc__6849DA5D] DEFAULT ('') FOR [SourceOfSavings]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimInitiativeStatus ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimInitiativeStatus] ( + [InitiativeStatusID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([InitiativeStatusID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimInitiativeStatus] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimInitiativeStatus] ADD CONSTRAINT [DF__DimInitia__Histo__4466DD39] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimInitiativeStatus] ADD CONSTRAINT [DF__DimInitiat__Name__427E94C7] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimInitiativeStatus] ADD CONSTRAINT [DF__DimInitia__Membe__4372B900] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimInitiativeStatus] ADD CONSTRAINT [DF__DimInitia__Trans__455B0172] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimJobCode ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimJobCode] ( + [JobCodeID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(151) NOT NULL, + [JobCode] nvarchar(20) NOT NULL, + [Description] nvarchar(128) NOT NULL, + [JobCodeGroupID] int NOT NULL, + [IsVariable] bit NOT NULL, + [IsActive] bit NOT NULL, + [IsProvider] bit NOT NULL, + [IsAgency] bit NOT NULL, + [DSSIsDefined] bit NOT NULL, + [DSSCostingRollup] nvarchar(100) NOT NULL, + [DSSRate] money NOT NULL, + [OBIsDefined] bit NOT NULL, + [FlexBucketGUID] uniqueidentifier NOT NULL, + [SPIsDefined] bit NOT NULL, + [Rollup] nvarchar(128) NOT NULL, + [Variability] float NOT NULL, + [TransactionID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [WorkWeekOverrideID] int NOT NULL, + [FlexJobCodeGroupID] int NOT NULL, + [DSSCostingRollup2] nvarchar(100) NOT NULL, + [DSSCostingRollup3] nvarchar(100) NOT NULL, + [FWIsDefined] bit NOT NULL, + [IsPatientCare] bit NOT NULL, + [IsBedside] bit NOT NULL, + [IsLicensed] bit NOT NULL, + [ManagementLevel] nvarchar(100) NOT NULL, + [SkillMix] nvarchar(100) NOT NULL, + [DSSJobCodeRollup1ID] int NOT NULL, + [DSSJobCodeRollup1] varchar(200) NOT NULL, + [DSSJobCodeRollup2] nvarchar(200) NOT NULL, + [DSSJobCodeRollup2ID] int NOT NULL, + [PRIsDefined] bit NOT NULL, + [CIIsDefined] bit NOT NULL, + [IsPR] bit NOT NULL, + [DSSCostComponent] varchar(200) NOT NULL, + [DSSJobCodeRollup3ID] int NOT NULL, + [DSSJobCodeRollup3] nvarchar(100) NOT NULL, + [IsDaily] bit NOT NULL, + [DSSCostComponentID] int NOT NULL, + [SPHJobCodeRollupID] int NOT NULL, + [SPHJobCodeRollupName] nvarchar(200) NOT NULL, + [SPHJobCodeRollupConfidenceScore] float NOT NULL, + [SPHVariability] decimal NOT NULL, + [SPHJobCodeRollupIsValidated] bit NOT NULL, + [StaffingCategoryID] int NOT NULL, + PRIMARY KEY ([JobCodeID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_MemberGUID_JC] ON [fw].[DimJobCode] ([MemberGUID]); +CREATE NONCLUSTERED INDEX [IX_JobCodeID] ON [fw].[DimJobCode] ([JobCodeID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_JobCode] ON [fw].[DimJobCode] ([JobCode]) INCLUDE ([JobCodeID]); +CREATE NONCLUSTERED INDEX [NCNU_StaffingReconciliation] ON [fw].[DimJobCode] ([JobCodeID], [JobCodeGroupID], [IsProvider]); +GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__Histo__54DD0E89] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__PRIsD__03C2E1CC] DEFAULT ((0)) FOR [PRIsDefined]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__CIIsD__04B70605] DEFAULT ((0)) FOR [CIIsDefined]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__Staff__055B1A57] DEFAULT ((0)) FOR [StaffingCategoryID]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__SPHJo__08A19B56] DEFAULT ((0)) FOR [SPHJobCodeRollupIsValidated]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__FWIsD__09101020] DEFAULT ((0)) FOR [FWIsDefined]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSJo__15C19676] DEFAULT ('') FOR [DSSJobCodeRollup2]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__WorkW__21EA71CB] DEFAULT ((-1)) FOR [WorkWeekOverrideID]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSJo__22276D5B] DEFAULT ((0)) FOR [DSSJobCodeRollup2ID]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSJo__28747837] DEFAULT ((0)) FOR [DSSJobCodeRollup1ID]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSJo__29689C70] DEFAULT ('') FOR [DSSJobCodeRollup1]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF_DimJobCode_FlexBucketGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FlexBucketGUID]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSCo__380A2AD4] DEFAULT ('') FOR [DSSCostingRollup2]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__SPHVa__38CD6F60] DEFAULT ((0)) FOR [SPHVariability]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSCo__38FE4F0D] DEFAULT ('') FOR [DSSCostingRollup3]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF_DimJobCode_IsPR] DEFAULT ((1)) FOR [IsPR]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSJo__431391A4] DEFAULT ((0)) FOR [DSSJobCodeRollup3ID]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__FlexJ__43CC1F31] DEFAULT ((0)) FOR [FlexJobCodeGroupID]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSJo__4407B5DD] DEFAULT ('') FOR [DSSJobCodeRollup3]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSCo__55674C09] DEFAULT ('') FOR [DSSCostComponent]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__IsPat__5C5D653A] DEFAULT ((0)) FOR [IsPatientCare]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__IsBed__5D518973] DEFAULT ((0)) FOR [IsBedside]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__IsLic__5E45ADAC] DEFAULT ((0)) FOR [IsLicensed]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSCo__5EA8342E] DEFAULT ((0)) FOR [DSSCostComponentID]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__Manag__5F39D1E5] DEFAULT ('') FOR [ManagementLevel]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__Skill__602DF61E] DEFAULT ('') FOR [SkillMix]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__SPHJo__616F9240] DEFAULT ((0)) FOR [SPHJobCodeRollupID]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__SPHJo__6263B679] DEFAULT ('Not Specified') FOR [SPHJobCodeRollupName]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__SPHJo__6357DAB2] DEFAULT ((0)) FOR [SPHJobCodeRollupConfidenceScore]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__Membe__53E8EA50] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCode__Code__5200A1DE] DEFAULT ('') FOR [JobCode]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCode__Name__510C7DA5] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__JobCo__7C53D2CB] DEFAULT ((0)) FOR [JobCodeGroupID]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__IsVar__47CD8FC2] DEFAULT ((0)) FOR [IsVariable]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF_DimJobCode_IsActive] DEFAULT ((1)) FOR [IsActive]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__IsPro__3C5A7832] DEFAULT ((0)) FOR [IsProvider]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__IsAge__3BF12F35] DEFAULT ((0)) FOR [IsAgency]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSIs__3F3AABC6] DEFAULT ((0)) FOR [DSSIsDefined]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSCo__0B332816] DEFAULT ('') FOR [DSSCostingRollup]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__DSSRa__0C274C4F] DEFAULT ((0)) FOR [DSSRate]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__OBIsD__402ECFFF] DEFAULT ((0)) FOR [OBIsDefined]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__DimJobCod__SPIsD__4122F438] DEFAULT ((0)) FOR [SPIsDefined]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF_DimJobCode_Category] DEFAULT ('') FOR [Rollup]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF_DimJobCode_Variability] DEFAULT ((0)) FOR [Variability]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF__FW_DimJobCode_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimJobCode] ADD CONSTRAINT [DF_DimJobCode_IsDaily] DEFAULT ((1)) FOR [IsDaily]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimJobCodeGroup ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimJobCodeGroup] ( + [JobCodeGroupID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Category] nvarchar(200) NOT NULL, + [SortOrder] int NOT NULL, + [IsCapital] bit NOT NULL, + [IsDSS] bit NOT NULL, + [IsMR] bit NOT NULL, + [IsOB] bit NOT NULL, + [IsSP] bit NOT NULL, + [SPStaffType] nvarchar(100) NOT NULL, + [SPSalariesFinancialReportingID] int NOT NULL, + [SPSalariesFinancialReporting] varchar(4000) NOT NULL, + [SPFTEsFinancialReportingID] int NOT NULL, + [SPFTEsFinancialReporting] varchar(200) NOT NULL, + [CAPFinancialReportingID] int NOT NULL, + [CAPFinancialReporting] nvarchar(2000) NOT NULL, + [TransactionID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [SPDefaultVolumeDriver] nvarchar(400) NOT NULL, + [WorkWeekOverrideID] int NOT NULL, + PRIMARY KEY ([JobCodeGroupID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimJobCodeGroup] ([MemberGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimJobCodeGroup] ([Name]); +GO +ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__FW_DimJobCodeGroup_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__Membe__70E2201F] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCode__Name__71D64458] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__Categ__178A1950] DEFAULT ('') FOR [Category]; GO +ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__SortO__187E3D89] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__IsCap__21B1D6B1] DEFAULT ((0)) FOR [IsCapital]; GO +ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__IsDSS__248E435C] DEFAULT ((0)) FOR [IsDSS]; GO +ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCode__IsMR__239A1F23] DEFAULT ((0)) FOR [IsMR]; GO +ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCode__IsOB__22A5FAEA] DEFAULT ((0)) FOR [IsOB]; GO +ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCode__IsSP__20BDB278] DEFAULT ((0)) FOR [IsSP]; GO +ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__SPSta__7685EADC] DEFAULT ('') FOR [SPStaffType]; GO +ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__SPFin__777A0F15] DEFAULT ((0)) FOR [SPSalariesFinancialReportingID]; GO +ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__SPSal__02AE5E6E] DEFAULT ('') FOR [SPSalariesFinancialReporting]; GO +ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__SPFTE__03A282A7] DEFAULT ((0)) FOR [SPFTEsFinancialReportingID]; GO +ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__SPFTE__0496A6E0] DEFAULT ('') FOR [SPFTEsFinancialReporting]; GO +ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__CAPFi__3291B063] DEFAULT ((0)) FOR [CAPFinancialReportingID]; GO +ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__SPDef__2232F3E0] DEFAULT ('') FOR [SPDefaultVolumeDriver]; GO +ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__CAPFi__3385D49C] DEFAULT ('') FOR [CAPFinancialReporting]; GO +ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__Histo__72CA6891] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimJobCodeGroup] ADD CONSTRAINT [DF__DimJobCod__WorkW__79340BA9] DEFAULT ((-1)) FOR [WorkWeekOverrideID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimJobCodeGroupPH ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimJobCodeGroupPH] ( + [JobCodeGroupPHID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([JobCodeGroupPHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimJobCodeGroupPH] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimJobCodeGroupPH] ADD CONSTRAINT [DF__FW_DimJobCodeGroupPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimJobCodeGroupPH] ADD CONSTRAINT [DF__DimJobCod__Membe__778F1DAE] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimJobCodeGroupPH] ADD CONSTRAINT [DF__DimJobCode__Name__788341E7] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimJobCodeGroupPH] ADD CONSTRAINT [DF__DimJobCod__Histo__79776620] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimJobCodePH ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimJobCodePH] ( + [JobCodePHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([JobCodePHID]) +); + +CREATE NONCLUSTERED INDEX [IX_JobCodePHID] ON [fw].[DimJobCodePH] ([JobCodePHID]); +CREATE NONCLUSTERED INDEX [IX_MemberGUID] ON [fw].[DimJobCodePH] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimJobCodePH] ADD CONSTRAINT [DF__FW_DimJobCodePH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimJobCodePH] ADD CONSTRAINT [DF__DimJobCode__Name__0DA619FA] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimJobCodePH] ADD CONSTRAINT [DF__DimJobCod__Membe__0E9A3E33] DEFAULT (newid()) FOR [MemberGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimLineNumber ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimLineNumber] ( + [LineNumberID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([LineNumberID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimLineNumber] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimLineNumber] ADD CONSTRAINT [DF__FW_DimLineNumber_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimLineNumber] ADD CONSTRAINT [DF__DimLineNu__Membe__36E78D22] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimLineNumber] ADD CONSTRAINT [DF__DimLineNu__Histo__37DBB15B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimManufacturer ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimManufacturer] ( + [ManufacturerID] int NOT NULL, + [Name] nvarchar(203) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [Code] nvarchar(100) NOT NULL, + [Description] nvarchar(100) NOT NULL, + PRIMARY KEY ([ManufacturerID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimManufacturer] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimManufacturer] ADD CONSTRAINT [DF__DimManufa__Membe__317C5D7F] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimManufacturer] ADD CONSTRAINT [DF__DimManufa__Trans__3364A5F1] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimManufacturer] ADD CONSTRAINT [DF__DimManufac__Code__3458CA2A] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimManufacturer] ADD CONSTRAINT [DF__DimManufa__Descr__354CEE63] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fw].[DimManufacturer] ADD CONSTRAINT [DF__DimManufa__Histo__327081B8] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimMedicalSurgical ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimMedicalSurgical] ( + [MedicalSurgicalID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [Code] nvarchar(100) NOT NULL, + [SortOrder] int NOT NULL, + PRIMARY KEY ([MedicalSurgicalID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimMedicalSurgical] ([MemberGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimMedicalSurgical] ([Name]); +GO +ALTER TABLE [fw].[DimMedicalSurgical] ADD CONSTRAINT [DF__DimMedica__Histo__7A099935] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimMedicalSurgical] ADD CONSTRAINT [DF__DimMedical__Name__782150C3] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimMedicalSurgical] ADD CONSTRAINT [DF__DimMedica__Membe__791574FC] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimMedicalSurgical] ADD CONSTRAINT [DF__DimMedica__Trans__7AFDBD6E] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimMedicalSurgical] ADD CONSTRAINT [DF__DimMedical__Code__7BF1E1A7] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimMedicalSurgical] ADD CONSTRAINT [DF__DimMedica__SortO__7CE605E0] DEFAULT ((0)) FOR [SortOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimModelingServiceLine ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimModelingServiceLine] ( + [ModelingServiceLineID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(912) NOT NULL, + [PatientClassID] int NOT NULL, + [PatientClass] nvarchar(200) NOT NULL, + [PatientClassCode] nvarchar(100) NOT NULL, + [PatientClassSortOrder] int NOT NULL, + [AgeCohortID] int NOT NULL, + [AgeCohort] nvarchar(200) NOT NULL, + [AgeCohortCode] nvarchar(100) NOT NULL, + [AgeCohortSortOrder] int NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLine] nvarchar(303) NOT NULL, + [ServiceLineCode] nvarchar(100) NOT NULL, + [ServiceLineSortOrder] int NOT NULL, + [ServiceLineRollup] nvarchar(200) NOT NULL, + [ServiceLineRollupSortOrder] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [MedicalSurgical] nvarchar(200) NOT NULL, + [MedicalSurgicalCode] nvarchar(100) NOT NULL, + [MedicalSurgicalSortOrder] int NOT NULL, + [SortOrder] varchar(49) NULL, + [TransactionID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([ModelingServiceLineID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimModelingServiceLine] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Membe__37D1C184] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Patie__3BA25268] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Patie__43437430] DEFAULT ('') FOR [PatientClass]; GO +ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Patie__44379869] DEFAULT ('') FOR [PatientClassCode]; GO +ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Patie__452BBCA2] DEFAULT ((0)) FOR [PatientClassSortOrder]; GO +ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__AgeCo__3C9676A1] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__AgeCo__4DC102A3] DEFAULT ('') FOR [AgeCohort]; GO +ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__AgeCo__4EB526DC] DEFAULT ('') FOR [AgeCohortCode]; GO +ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__AgeCo__4FA94B15] DEFAULT ((0)) FOR [AgeCohortSortOrder]; GO +ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Servi__3D8A9ADA] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Servi__461FE0DB] DEFAULT ('') FOR [ServiceLine]; GO +ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Servi__47140514] DEFAULT ('') FOR [ServiceLineCode]; GO +ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Servi__4808294D] DEFAULT ((0)) FOR [ServiceLineSortOrder]; GO +ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Servi__48FC4D86] DEFAULT ('') FOR [ServiceLineRollup]; GO +ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Histo__38C5E5BD] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Servi__49F071BF] DEFAULT ((0)) FOR [ServiceLineRollupSortOrder]; GO +ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Medic__3E7EBF13] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Medic__4AE495F8] DEFAULT ('') FOR [MedicalSurgical]; GO +ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Medic__4BD8BA31] DEFAULT ('') FOR [MedicalSurgicalCode]; GO +ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Medic__4CCCDE6A] DEFAULT ((0)) FOR [MedicalSurgicalSortOrder]; GO +ALTER TABLE [fw].[DimModelingServiceLine] ADD CONSTRAINT [DF__DimModeli__Trans__39BA09F6] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimModelingServiceLinePH ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimModelingServiceLinePH] ( + [ModelingServiceLinePHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([ModelingServiceLinePHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimModelingServiceLinePH] ([MemberGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimModelingServiceLinePH] ([Name]); +GO +ALTER TABLE [fw].[DimModelingServiceLinePH] ADD CONSTRAINT [DF__DimModelin__Name__09D5ECAA] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimModelingServiceLinePH] ADD CONSTRAINT [DF__DimModeli__Membe__0ACA10E3] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimModelingServiceLinePH] ADD CONSTRAINT [DF__DimModeli__Trans__0CB25955] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimModelingServiceLinePH] ADD CONSTRAINT [DF__DimModeli__Histo__0BBE351C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimOpportunity ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimOpportunity] ( + [OpportunityKey] nvarchar(20) NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [EntityID] int NOT NULL, + [SourceOfSavingsID] int NOT NULL, + [SourceOfSavings] nvarchar(200) NOT NULL, + [IsHidden] bit NOT NULL, + [HasInitiative] bit NOT NULL, + [InitiativeGUID] uniqueidentifier NOT NULL, + [Initiative] nvarchar(400) NOT NULL, + [InitiativeStatusID] int NOT NULL, + [InitiativeStatus] nvarchar(200) NOT NULL, + [Owner] nvarchar(130) NOT NULL, + [CostLeader] nvarchar(130) NOT NULL, + [ExecutiveSponsor] nvarchar(130) NOT NULL, + [Workstream] nvarchar(200) NOT NULL, + [DateCreated] datetime NOT NULL, + [BaselineStartDate] datetime NOT NULL, + [BaselineEndDate] datetime NOT NULL, + [SavingsIdentified] decimal NOT NULL, + [SavingsGoal] decimal NOT NULL, + [AnnualGoal] decimal NOT NULL, + [SavingsEstimate] decimal NOT NULL, + [InitiativeRollup1Id] int NOT NULL, + [InitiativeRollup1] nvarchar(400) NOT NULL, + [InitiativeRollup2Id] int NOT NULL, + [InitiativeRollup2] nvarchar(400) NOT NULL, + [InitiativeRollup3Id] int NOT NULL, + [InitiativeRollup3] nvarchar(400) NOT NULL, + PRIMARY KEY ([OpportunityKey]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimOpportunity] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Oppor__41300D3C] DEFAULT ('') FOR [OpportunityKey]; GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpportu__Name__42243175] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Membe__431855AE] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Histo__440C79E7] DEFAULT (CONVERT([uniqueidentifier],0x00)) FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Trans__45009E20] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Entit__45F4C259] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Sourc__46E8E692] DEFAULT ((0)) FOR [SourceOfSavingsID]; GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Sourc__47DD0ACB] DEFAULT ('') FOR [SourceOfSavings]; GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__IsHid__48D12F04] DEFAULT ((0)) FOR [IsHidden]; GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__HasIn__49C5533D] DEFAULT ((0)) FOR [HasInitiative]; GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Initi__4AB97776] DEFAULT (CONVERT([uniqueidentifier],0x00)) FOR [InitiativeGUID]; GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Initi__4BAD9BAF] DEFAULT ('') FOR [Initiative]; GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Initi__4CA1BFE8] DEFAULT ((0)) FOR [InitiativeStatusID]; GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Initi__4D95E421] DEFAULT ('') FOR [InitiativeStatus]; GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Owner__4E8A085A] DEFAULT ('') FOR [Owner]; GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__CostL__4F7E2C93] DEFAULT ('') FOR [CostLeader]; GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Execu__507250CC] DEFAULT ('') FOR [ExecutiveSponsor]; GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Works__51667505] DEFAULT ('') FOR [Workstream]; GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Savin__525A993E] DEFAULT ((0)) FOR [SavingsIdentified]; GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Savin__534EBD77] DEFAULT ((0)) FOR [SavingsGoal]; GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Annua__5442E1B0] DEFAULT ((0)) FOR [AnnualGoal]; GO +ALTER TABLE [fw].[DimOpportunity] ADD CONSTRAINT [DF__DimOpport__Savin__553705E9] DEFAULT ((0)) FOR [SavingsEstimate]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimPatientClass ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimPatientClass] ( + [PatientClassID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [Code] nvarchar(100) NOT NULL, + [SortOrder] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [IsActive] bit NOT NULL, + [IncludeInAdjustedCalculations] bit NOT NULL, + [OBServiceLinePrimaryVolumeAccountID] int NOT NULL, + PRIMARY KEY ([PatientClassID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPatientClass] ([MemberGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimPatientClass] ([Name]); +GO +ALTER TABLE [fw].[DimPatientClass] ADD CONSTRAINT [DF__DimPatient__Name__1DDC1A00] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimPatientClass] ADD CONSTRAINT [DF__DimPatient__Code__1ED03E39] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimPatientClass] ADD CONSTRAINT [DF__DimPatien__SortO__1FC46272] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimPatientClass] ADD CONSTRAINT [DF__DimPatien__OBSer__20890BE2] DEFAULT ((0)) FOR [OBServiceLinePrimaryVolumeAccountID]; GO +ALTER TABLE [fw].[DimPatientClass] ADD CONSTRAINT [DF__DimPatien__Membe__20B886AB] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimPatientClass] ADD CONSTRAINT [DF__DimPatien__Trans__22A0CF1D] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimPatientClass] ADD CONSTRAINT [DF__DimPatien__IsAct__554F77D7] DEFAULT ((0)) FOR [IsActive]; GO +ALTER TABLE [fw].[DimPatientClass] ADD CONSTRAINT [DF__DimPatien__Histo__21ACAAE4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimPatientClass] ADD CONSTRAINT [DF__DimPatien__Inclu__6AF4A033] DEFAULT ((0)) FOR [IncludeInAdjustedCalculations]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimPatientReimbursementGroup ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimPatientReimbursementGroup] ( + [PatientReimbursementGroupID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [PatientClassID] int NOT NULL, + [CareSettingID] int NOT NULL, + [PatientClass] nvarchar(200) NOT NULL, + [PatientClassCode] nvarchar(100) NOT NULL, + [PatientClassSortOrder] int NOT NULL, + [CareSetting] nvarchar(200) NOT NULL, + [CareSettingCode] nvarchar(100) NOT NULL, + [CareSettingSortOrder] int NOT NULL, + [Name] nvarchar(403) NOT NULL, + [Code] nvarchar(203) NOT NULL, + [SortOrder] varchar(203) NULL, + PRIMARY KEY ([PatientReimbursementGroupID]) +); + +CREATE NONCLUSTERED INDEX [NCNU_MemberGUID] ON [fw].[DimPatientReimbursementGroup] ([MemberGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_PreventDuplicates] ON [fw].[DimPatientReimbursementGroup] ([PatientClassID], [CareSettingID]); +GO +ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__Histo__57BEA2D2] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__Membe__56CA7E99] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__Trans__58B2C70B] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__Patie__5B8F33B6] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__CareS__5C8357EF] DEFAULT ((0)) FOR [CareSettingID]; GO +ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__Patie__660CC229] DEFAULT ('') FOR [PatientClass]; GO +ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__Patie__6700E662] DEFAULT ('') FOR [PatientClassCode]; GO +ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__Patie__67F50A9B] DEFAULT ((0)) FOR [PatientClassSortOrder]; GO +ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__CareS__68E92ED4] DEFAULT ('') FOR [CareSetting]; GO +ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__CareS__69DD530D] DEFAULT ('') FOR [CareSettingCode]; GO +ALTER TABLE [fw].[DimPatientReimbursementGroup] ADD CONSTRAINT [DF__DimPatien__CareS__6AD17746] DEFAULT ((0)) FOR [CareSettingSortOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimPatientReimbursementGroupPH ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimPatientReimbursementGroupPH] ( + [PatientReimbursementGroupPHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([PatientReimbursementGroupPHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPatientReimbursementGroupPH] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimPatientReimbursementGroupPH] ADD CONSTRAINT [DF__DimPatien__Histo__2E878315] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimPatientReimbursementGroupPH] ADD CONSTRAINT [DF__DimPatient__Name__2C9F3AA3] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimPatientReimbursementGroupPH] ADD CONSTRAINT [DF__DimPatien__Membe__2D935EDC] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimPatientReimbursementGroupPH] ADD CONSTRAINT [DF__DimPatien__Trans__2F7BA74E] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimPatientType ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimPatientType] ( + [Code] nvarchar(50) NOT NULL, + [PatientTypeID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [PatientTypeRollupID] tinyint NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [Description] nvarchar(100) NOT NULL, + [Name] nvarchar(153) NOT NULL, + [DSSRollup] nvarchar(100) NOT NULL, + PRIMARY KEY ([PatientTypeID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [NCU_PatientTypeCode] ON [fw].[DimPatientType] ([Code]) INCLUDE ([PatientTypeID]); +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPatientType] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimPatientType] ADD CONSTRAINT [DF__DimPatien__Descr__03F78862] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fw].[DimPatientType] ADD CONSTRAINT [DF__DimPatient__Code__0451B9EA] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimPatientType] ADD CONSTRAINT [DF__FW_DimPatientType_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimPatientType] ADD CONSTRAINT [DF__DimPatien__Membe__063A025C] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimPatientType] ADD CONSTRAINT [DF__DimPatien__DSSRo__54A1A578] DEFAULT ('') FOR [DSSRollup]; GO +ALTER TABLE [fw].[DimPatientType] ADD CONSTRAINT [DF__DimPatien__Histo__496564B9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimPatientType] ADD CONSTRAINT [DF__fw_DimPatientType_PatientTypeRollupID] DEFAULT ((0)) FOR [PatientTypeRollupID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimPatientTypeRollup ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimPatientTypeRollup] ( + [PatientTypeRollupID] tinyint NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Type] nvarchar(100) NOT NULL, + [SortOrder] int NOT NULL, + [IsCapital] bit NOT NULL, + [IsDSS] bit NOT NULL, + [IsMR] bit NOT NULL, + [IsOB] bit NOT NULL, + [IsSP] bit NOT NULL, + [SPChargesFinancialReportingID] int NOT NULL, + [SPChargesFinancialReporting] nvarchar(100) NOT NULL, + [SPContractualsFinancialReportingID] int NOT NULL, + [SPContractualsFinancialReporting] nvarchar(100) NOT NULL, + [SPPrimaryStatisticFinancialReportingID] int NOT NULL, + [SPPrimaryStatisticFinancialReporting] nvarchar(100) NOT NULL, + [SPPrimaryStatisticFinancialReportingLineName] nvarchar(100) NOT NULL, + [SPSecondaryStatisticFinancialReportingID] int NOT NULL, + [SPSecondaryStatisticFinancialReporting] nvarchar(100) NOT NULL, + [SPSecondaryStatisticFinancialReportingLineName] nvarchar(100) NOT NULL, + [SPTertiaryStatisticFinancialReportingID] int NOT NULL, + [SPTertiaryStatisticFinancialReporting] nvarchar(100) NOT NULL, + [SPTertiaryStatisticFinancialReportingLineName] nvarchar(100) NOT NULL, + [CAPChargesFinancialReportingID] int NOT NULL, + [CAPChargesFinancialReporting] nvarchar(100) NOT NULL, + [CAPContractualsFinancialReportingID] int NOT NULL, + [CAPContractualsFinancialReporting] nvarchar(100) NOT NULL, + [CAPPrimaryStatisticFinancialReportingID] int NOT NULL, + [CAPPrimaryStatisticFinancialReporting] nvarchar(100) NOT NULL, + [CAPSecondaryStatisticFinancialReportingID] int NOT NULL, + [CAPSecondaryStatisticFinancialReporting] nvarchar(100) NOT NULL, + [TransactionID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [CareSettingID] int NOT NULL, + [CareSettingName] nvarchar(200) NOT NULL, + [PatientClassID] int NOT NULL, + [PatientClassName] nvarchar(200) NOT NULL, + [CAPPrimaryStatisticFinancialReportingLineName] nvarchar(100) NOT NULL, + [CAPSecondaryStatisticFinancialReportingLineName] nvarchar(100) NOT NULL, + [Sg2PatientTypeRollup] nvarchar(400) NOT NULL, + PRIMARY KEY ([PatientTypeRollupID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPatientTypeRollup] ([MemberGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimPatientTypeRollup] ([Name]); +GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__FW_DimPatientTypeRollup_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Sg2Pa__184B9135] DEFAULT ('') FOR [Sg2PatientTypeRollup]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CareS__260DA665] DEFAULT ((0)) FOR [CareSettingID]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CareS__2701CA9E] DEFAULT ('') FOR [CareSettingName]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CAPPr__27C5A8B7] DEFAULT ('') FOR [CAPPrimaryStatisticFinancialReportingLineName]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Patie__27F5EED7] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CAPSe__28B9CCF0] DEFAULT ('') FOR [CAPSecondaryStatisticFinancialReportingLineName]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Patie__28EA1310] DEFAULT ('') FOR [PatientClassName]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__PatientTy__Membe__12B81536] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__PatientTyp__Name__11C3F0FD] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatient__Type__7714F095] DEFAULT ('') FOR [Type]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__SortO__047D9F94] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__IsCap__195BEE45] DEFAULT ((0)) FOR [IsCapital]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__IsDSS__1C385AF0] DEFAULT ((0)) FOR [IsDSS]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Histo__69D2344B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatient__IsMR__1B4436B7] DEFAULT ((0)) FOR [IsMR]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatient__IsOB__1A50127E] DEFAULT ((0)) FOR [IsOB]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatient__IsSP__1867CA0C] DEFAULT ((0)) FOR [IsSP]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Charg__22257319] DEFAULT ((0)) FOR [SPChargesFinancialReportingID]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Charg__26EA2836] DEFAULT ('') FOR [SPChargesFinancialReporting]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Contr__23199752] DEFAULT ((0)) FOR [SPContractualsFinancialReportingID]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Contr__27DE4C6F] DEFAULT ('') FOR [SPContractualsFinancialReporting]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Prima__240DBB8B] DEFAULT ((0)) FOR [SPPrimaryStatisticFinancialReportingID]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Prima__28D270A8] DEFAULT ('') FOR [SPPrimaryStatisticFinancialReporting]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Prima__0B4CFAB9] DEFAULT ('') FOR [SPPrimaryStatisticFinancialReportingLineName]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Secon__2501DFC4] DEFAULT ((0)) FOR [SPSecondaryStatisticFinancialReportingID]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Secon__29C694E1] DEFAULT ('') FOR [SPSecondaryStatisticFinancialReporting]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Secon__0C411EF2] DEFAULT ('') FOR [SPSecondaryStatisticFinancialReportingLineName]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Terti__25F603FD] DEFAULT ((0)) FOR [SPTertiaryStatisticFinancialReportingID]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Terti__2ABAB91A] DEFAULT ('') FOR [SPTertiaryStatisticFinancialReporting]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__Terti__0D35432B] DEFAULT ('') FOR [SPTertiaryStatisticFinancialReportingLineName]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CAPCh__271FFDB7] DEFAULT ((0)) FOR [CAPChargesFinancialReportingID]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CAPCh__2AF08E9B] DEFAULT ('') FOR [CAPChargesFinancialReporting]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CAPCo__281421F0] DEFAULT ((0)) FOR [CAPContractualsFinancialReportingID]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CAPCo__2BE4B2D4] DEFAULT ('') FOR [CAPContractualsFinancialReporting]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CAPPr__29084629] DEFAULT ((0)) FOR [CAPPrimaryStatisticFinancialReportingID]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CAPPr__2CD8D70D] DEFAULT ('') FOR [CAPPrimaryStatisticFinancialReporting]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CAPSe__29FC6A62] DEFAULT ((0)) FOR [CAPSecondaryStatisticFinancialReportingID]; GO +ALTER TABLE [fw].[DimPatientTypeRollup] ADD CONSTRAINT [DF__DimPatien__CAPSe__2DCCFB46] DEFAULT ('') FOR [CAPSecondaryStatisticFinancialReporting]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimPatientTypeRollupPH ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimPatientTypeRollupPH] ( + [PatientTypeRollupPHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([PatientTypeRollupPHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPatientTypeRollupPH] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimPatientTypeRollupPH] ADD CONSTRAINT [DF__FW_DimPatientTypeRollupPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimPatientTypeRollupPH] ADD CONSTRAINT [DF__DimPatien__Histo__1D60BDFC] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimPatientTypeRollupPH] ADD CONSTRAINT [DF__DimPatient__Name__1B78758A] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimPatientTypeRollupPH] ADD CONSTRAINT [DF__DimPatien__Membe__1C6C99C3] DEFAULT (newid()) FOR [MemberGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimPayCode ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimPayCode] ( + [PayCodeID] smallint NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(203) NOT NULL, + [Description] nvarchar(100) NOT NULL, + [PayCode] nvarchar(100) NOT NULL, + [PayCodeGroupID] int NOT NULL, + [PayCodeGroup] nvarchar(100) NOT NULL, + [PayCodeGroupSortOrder] int NOT NULL, + [PayClass] nvarchar(100) NOT NULL, + [ProductiveClass] nvarchar(200) NOT NULL, + [IsAccrued] bit NOT NULL, + [IsHoursIgnored] bit NOT NULL, + [IsDollarsIgnored] bit NOT NULL, + [DSSIsDefined] bit NOT NULL, + [DSSCostingRollup] nvarchar(50) NOT NULL, + [OBIsDefined] bit NOT NULL, + [OBForecastDetailID] int NOT NULL, + [SPIsDefined] bit NOT NULL, + [ImportIDAlt] nvarchar(100) NOT NULL, + [IsPayCodeGroup] bit NOT NULL, + [Rollup] nvarchar(100) NOT NULL, + [SubRollup] nvarchar(100) NOT NULL, + [FlexBucketGUID] uniqueidentifier NOT NULL, + [Variability] money NOT NULL, + [ReportingCategory] nvarchar(100) NOT NULL, + [TransactionID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [DSSCostingRollup2] nvarchar(100) NOT NULL, + [FWIsDefined] bit NOT NULL, + [DSSPayCodeRollup2ID] int NOT NULL, + [DSSPayCodeRollup2] nvarchar(100) NOT NULL, + [DSSPayCodeRollup1] nvarchar(200) NOT NULL, + [DSSPayCodeRollup1ID] int NOT NULL, + [ProviderLineItemID] int NOT NULL, + [SPHPayCodeRollupName] nvarchar(100) NOT NULL, + [SPHProductiveClass] nvarchar(100) NOT NULL, + [ProviderLineItem] nvarchar(200) NOT NULL, + [SPHPayCodeRollupIsValidated] bit NOT NULL, + [SPHPayCodeRollupID] int NOT NULL, + [SPHPayCodeRollupConfidenceScore] float NOT NULL, + PRIMARY KEY ([PayCodeID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_PayCode] ON [fw].[DimPayCode] ([PayCode]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_MemberGUID] ON [fw].[DimPayCode] ([MemberGUID]); +CREATE NONCLUSTERED INDEX [NCNU_StaffingReconciliation] ON [fw].[DimPayCode] ([PayCodeID], [PayCodeGroupID], [IsDollarsIgnored], [IsHoursIgnored]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_PayCode] ON [fw].[DimPayCode] ([PayCode]) INCLUDE ([PayCodeID]); +GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__Provi__0327EDCB] DEFAULT ('') FOR [ProviderLineItem]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__SPHPa__0995BF8F] DEFAULT ((0)) FOR [SPHPayCodeRollupIsValidated]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__FWIsD__0A043459] DEFAULT ((0)) FOR [FWIsDefined]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__Provi__0A8781C3] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__DSSPa__16B5BAAF] DEFAULT ('') FOR [DSSPayCodeRollup1]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__DSSPa__240FB5CD] DEFAULT ((0)) FOR [DSSPayCodeRollup1ID]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__DSSPa__31D2F9E8] DEFAULT ((0)) FOR [DSSPayCodeRollup2ID]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__DSSPa__32C71E21] DEFAULT ('') FOR [DSSPayCodeRollup2]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__DSSCo__39F27346] DEFAULT ('') FOR [DSSCostingRollup2]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__SPHPa__3BC08152] DEFAULT ('') FOR [SPHPayCodeRollupName]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__SPHPr__3CB4A58B] DEFAULT ('') FOR [SPHProductiveClass]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF_DimPayCode_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__SPHPa__3DD47DA4] DEFAULT ((0)) FOR [SPHPayCodeRollupID]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__SPHPa__3EC8A1DD] DEFAULT ((0)) FOR [SPHPayCodeRollupConfidenceScore]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF_DimPayCode_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF_DimPayCode_Description] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF_DimPayCode_ImportID1] DEFAULT ('') FOR [PayCode]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF_DimPayCode_PayCodeGroupID] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__PayCo__2ECB0F56] DEFAULT ('') FOR [PayCodeGroup]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__PayCo__2FBF338F] DEFAULT ((0)) FOR [PayCodeGroupSortOrder]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__PayCl__30B357C8] DEFAULT ('') FOR [PayClass]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__Produ__2DD6EB1D] DEFAULT ('') FOR [ProductiveClass]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__IsAcc__27BF4DFF] DEFAULT ((1)) FOR [IsAccrued]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF_DimPayCode_IsHoursIgnored] DEFAULT ((0)) FOR [IsHoursIgnored]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__IsDol__2451AB60] DEFAULT ((0)) FOR [IsDollarsIgnored]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__DSSIs__5DBF32E6] DEFAULT ((0)) FOR [DSSIsDefined]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__DSSCo__7377A163] DEFAULT ('') FOR [DSSCostingRollup]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__OBIsD__5EB3571F] DEFAULT ((0)) FOR [OBIsDefined]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__OBFor__1DC70B67] DEFAULT ((0)) FOR [OBForecastDetailID]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__SPIsD__5FA77B58] DEFAULT ((0)) FOR [SPIsDefined]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF_DimPayCode_ImportID2] DEFAULT ('') FOR [ImportIDAlt]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF_DimPayCode_IsPayCodeGroup] DEFAULT ((0)) FOR [IsPayCodeGroup]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF_DimPayCode_Rollup1] DEFAULT ('') FOR [Rollup]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF_DimPayCode_Rollup2] DEFAULT ('') FOR [SubRollup]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__FlexB__254BC6BD] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FlexBucketGUID]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__Varia__02228611] DEFAULT ((0)) FOR [Variability]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__DimPayCod__Repor__2B0CC343] DEFAULT ('') FOR [ReportingCategory]; GO +ALTER TABLE [fw].[DimPayCode] ADD CONSTRAINT [DF__FW_DimPayCode_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimPayCodeGroup ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimPayCodeGroup] ( + [PayCodeGroupID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [SortOrder] int NOT NULL, + [PayCodeGroupCode] nvarchar(100) NOT NULL, + [PayClass] nvarchar(100) NOT NULL, + [ProductiveClassID] int NOT NULL, + [IsVariable] bit NOT NULL, + [IsOvertime] bit NOT NULL, + [IsAgency] bit NOT NULL, + [IsExcludedFromBenefits] bit NOT NULL, + [WageRateMultiplier] decimal NOT NULL, + [DefaultPayCodeID] int NOT NULL, + [ReportingCategory] nvarchar(100) NOT NULL, + [AccountID] int NOT NULL, + [TransactionID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [IsDirect] bit NOT NULL, + [IsPremium] bit NOT NULL, + PRIMARY KEY ([PayCodeGroupID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [UQ__DimPayCo__A67B38530990CDEA] ON [fw].[DimPayCodeGroup] ([MemberGUID]); +CREATE NONCLUSTERED INDEX [IX_PayCodeGroupID] ON [fw].[DimPayCodeGroup] ([PayCodeGroupID]); +GO +ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__Histo__0D615ECE] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__IsDir__3A42B4F7] DEFAULT ((0)) FOR [IsDirect]; GO +ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__IsPre__5FA0B8DD] DEFAULT ((0)) FOR [IsPremium]; GO +ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__Membe__0B79165C] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCode__Name__0C6D3A95] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF_DimPayCodeGroup_PayCodeSortOrder] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF_DimPayCodeGroup_PayCodeGroupCode] DEFAULT ('') FOR [PayCodeGroupCode]; GO +ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF_DimPayCodeGroup_PayClass] DEFAULT ('') FOR [PayClass]; GO +ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__Produ__281D4670] DEFAULT ((0)) FOR [ProductiveClassID]; GO +ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__IsVar__1D17A25A] DEFAULT ((0)) FOR [IsVariable]; GO +ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__IsOve__38209E51] DEFAULT ((0)) FOR [IsOvertime]; GO +ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__IsAge__372C7A18] DEFAULT ((0)) FOR [IsAgency]; GO +ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__IsExc__46C2F80C] DEFAULT ((0)) FOR [IsExcludedFromBenefits]; GO +ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__WageR__58D2C29C] DEFAULT ((1)) FOR [WageRateMultiplier]; GO +ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__Defau__54D2B6EF] DEFAULT ((0)) FOR [DefaultPayCodeID]; GO +ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__DimPayCod__Repor__30C59C99] DEFAULT ('') FOR [ReportingCategory]; GO +ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF_DimPayCodeGroup_AccountID] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fw].[DimPayCodeGroup] ADD CONSTRAINT [DF__FW_DimPayCodeGroup_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimPayCodeGroupPH ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimPayCodeGroupPH] ( + [PayCodeGroupPHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([PayCodeGroupPHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPayCodeGroupPH] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimPayCodeGroupPH] ADD CONSTRAINT [DF__DimPayCod__Histo__5DB1E3E9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimPayCodeGroupPH] ADD CONSTRAINT [DF__DimPayCode__Name__5BC99B77] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimPayCodeGroupPH] ADD CONSTRAINT [DF__DimPayCod__Membe__5CBDBFB0] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimPayCodeGroupPH] ADD CONSTRAINT [DF__DimPayCod__Trans__5EA60822] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimPayCycle ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimPayCycle] ( + [PayCycleID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [Code] nvarchar(200) NOT NULL, + [SortOrder] int NOT NULL, + [AccrualMethod] nvarchar(100) NOT NULL, + [PeriodDays] tinyint NOT NULL, + [FirstPayPeriodStartDate] datetime NOT NULL, + [CurrentPayPeriodID] smallint NOT NULL, + PRIMARY KEY ([PayCycleID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPayCycle] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimPayCycle] ADD CONSTRAINT [DF__DimPayCyc__Curre__2D778DC8] DEFAULT ((0)) FOR [CurrentPayPeriodID]; GO +ALTER TABLE [fw].[DimPayCycle] ADD CONSTRAINT [DF__DimPayCyc__Histo__3F88EF06] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimPayCycle] ADD CONSTRAINT [DF__DimPayCycl__Name__3DA0A694] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimPayCycle] ADD CONSTRAINT [DF__DimPayCyc__Membe__3E94CACD] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimPayCycle] ADD CONSTRAINT [DF__DimPayCyc__Trans__407D133F] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimPayCycle] ADD CONSTRAINT [DF__DimPayCycl__Code__41713778] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimPayCycle] ADD CONSTRAINT [DF__DimPayCyc__SortO__42655BB1] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimPayCycle] ADD CONSTRAINT [DF__DimPayCyc__Accru__43597FEA] DEFAULT ('') FOR [AccrualMethod]; GO +ALTER TABLE [fw].[DimPayCycle] ADD CONSTRAINT [DF__DimPayCyc__Perio__444DA423] DEFAULT ((0)) FOR [PeriodDays]; GO +ALTER TABLE [fw].[DimPayCycle] ADD CONSTRAINT [DF__DimPayCyc__First__4541C85C] DEFAULT (getdate()) FOR [FirstPayPeriodStartDate]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimPayPeriod ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimPayPeriod] ( + [MemberGUID] uniqueidentifier NOT NULL, + [PayPeriodID] smallint NOT NULL, + [PayPeriodCode] nvarchar(100) NULL, + [PeriodNumber] tinyint NOT NULL, + [PeriodStartCalendarDate] datetime NULL, + [PeriodEndCalendarDate] datetime NOT NULL, + [PeriodDays] tinyint NOT NULL, + [FiscalMonthIDStart] int NULL, + [FiscalMonthIDSecond] int NULL, + [CalendarDaysStart] int NULL, + [CalendarDaysSecond] int NULL, + [PeriodDaysStart] int NULL, + [PeriodDaysSecond] int NULL, + [PeriodWeightStart] numeric NULL, + [PeriodWeightSecond] numeric NULL, + [DaysInPeriodWeightStart] numeric NULL, + [DaysInPeriodWeightSecond] numeric NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [FiscalYearIDStart] int NOT NULL, + [FiscalYearIDSecond] int NOT NULL, + [Name] nvarchar(350) NULL, + [TransactionID] int NOT NULL, + [WorkingDays] tinyint NOT NULL, + [WorkingDaysInPeriodStart] int NULL, + [WorkingDaysInPeriodSecond] int NULL, + [WorkingDaysInPeriodWeightStart] float NULL, + [WorkingDaysInPeriodWeightSecond] float NULL, + [PayCycleID] int NOT NULL, + [Code] nvarchar(350) NOT NULL, + [PayCycleName] nvarchar(200) NOT NULL, + [PayCycleCode] nvarchar(200) NOT NULL, + [PayCycleSortOrder] int NOT NULL, + [AccrualMethod] nvarchar(100) NOT NULL, + [IsCurrentPayPeriod] bit NOT NULL, + [CountFromCurrentPayPeriod] int NOT NULL, + PRIMARY KEY ([PayPeriodID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [UQ__DimDimPa__A67B38536BC073E1] ON [fw].[DimPayPeriod] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF_FWDIMPAYPERIODPERIODNUMBER] DEFAULT ((0)) FOR [PeriodNumber]; GO +ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF_FWDIMPAYPERIODWORKINGDAYS] DEFAULT ((10)) FOR [WorkingDays]; GO +ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__FW_DimPayPeriod_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPer__Count__290C08E3] DEFAULT ((0)) FOR [CountFromCurrentPayPeriod]; GO +ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPer__Fisca__2B38DEE6] DEFAULT ((0)) FOR [FiscalYearIDStart]; GO +ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPer__Fisca__2C2D031F] DEFAULT ((0)) FOR [FiscalYearIDSecond]; GO +ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF_DimPayPeriod_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPer__IsCur__48EEC890] DEFAULT ((0)) FOR [IsCurrentPayPeriod]; GO +ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPer__PayCy__49125940] DEFAULT ((0)) FOR [PayCycleID]; GO +ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPeri__Code__4A067D79] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF_DimPayPeriod_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF_DimPayPeriod_PeriodEndCalendarDate] DEFAULT (getdate()) FOR [PeriodEndCalendarDate]; GO +ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF_DimPayPeriod_DaysInPayPeriod] DEFAULT ((14)) FOR [PeriodDays]; GO +ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPeri__Name__627E58A2] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPer__PayCy__63C64F7C] DEFAULT ('') FOR [PayCycleName]; GO +ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPer__PayCy__64BA73B5] DEFAULT ('') FOR [PayCycleCode]; GO +ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPer__PayCy__65AE97EE] DEFAULT ((0)) FOR [PayCycleSortOrder]; GO +ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF__DimPayPer__Accru__66A2BC27] DEFAULT ('') FOR [AccrualMethod]; GO +ALTER TABLE [fw].[DimPayPeriod] ADD CONSTRAINT [DF_FWDIMPAYPERIODPAYPERIODCODE] DEFAULT ('') FOR [PayPeriodCode]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimPayor ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimPayor] ( + [PayorID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(253) NOT NULL, + [Description] nvarchar(200) NOT NULL, + [DescriptionLong] nvarchar(200) NOT NULL, + [PayorCode] nvarchar(50) NOT NULL, + [PayorGroupID] int NOT NULL, + [FinancialClassID] int NOT NULL, + [FinancialClass] nvarchar(30) NOT NULL, + [IsDSS] bit NOT NULL, + [IsOB] bit NOT NULL, + [TransactionID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [OBDefaultInpatientReimbursementMethod] nvarchar(100) NOT NULL, + [OBDefaultOutpatientReimbursementMethod] nvarchar(100) NOT NULL, + PRIMARY KEY ([PayorID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPayor] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [FK_DimPayor_PayorGroup] FOREIGN KEY ([PayorGroupID]) REFERENCES [fw].[DimPayorGroup] ([PayorGroupID]); GO +ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__Member__2B6B870B] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__Descri__777F9E76] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__Descri__7873C2AF] DEFAULT ('') FOR [DescriptionLong]; GO +ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__PayorC__7967E6E8] DEFAULT ('') FOR [PayorCode]; GO +ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__PayorG__7A6B8A59] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__Financ__7A5C0B21] DEFAULT ((0)) FOR [FinancialClassID]; GO +ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF_DimPayor_FinancialClass] DEFAULT ('') FOR [FinancialClass]; GO +ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__IsDSS__07A5ED7A] DEFAULT ((0)) FOR [IsDSS]; GO +ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__IsOB__06B1C941] DEFAULT ((0)) FOR [IsOB]; GO +ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__FW_DimPayor_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__OBDefa__42167EE4] DEFAULT ('Per IP Volume') FOR [OBDefaultInpatientReimbursementMethod]; GO +ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__OBDefa__430AA31D] DEFAULT ('Per OP Volume') FOR [OBDefaultOutpatientReimbursementMethod]; GO +ALTER TABLE [fw].[DimPayor] ADD CONSTRAINT [DF__DimPayor__Histor__7B502F5A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimPayorGroup ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimPayorGroup] ( + [PayorGroupID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Category] nvarchar(200) NOT NULL, + [ReimbursementType] nvarchar(200) NOT NULL, + [PayorGroupCode] nvarchar(100) NOT NULL, + [SortOrder] int NOT NULL, + [IsCapital] bit NOT NULL, + [CAPChargesFinancialReportingID] int NOT NULL, + [CAPChargesFinancialReporting] varchar(4000) NOT NULL, + [CAPContractualsFinancialReportingID] int NOT NULL, + [CAPContractualsFinancialReporting] varchar(200) NOT NULL, + [IsDSS] bit NOT NULL, + [IsOB] bit NOT NULL, + [IsMR] bit NOT NULL, + [IsSP] bit NOT NULL, + [SPHCRType] nvarchar(100) NOT NULL, + [SPHCRPayorID] int NOT NULL, + [SPHCRPayor] nvarchar(200) NOT NULL, + [SPChargesFinancialReportingID] int NOT NULL, + [SPChargesFinancialReporting] varchar(200) NOT NULL, + [SPContractualsFinancialReportingID] int NOT NULL, + [SPContractualsFinancialReporting] varchar(200) NOT NULL, + [SPDefaultInpatientReimbursementMethod] nvarchar(100) NOT NULL, + [SPDefaultOutpatientReimbursementMethod] nvarchar(100) NOT NULL, + [SPDefaultClinicReimbursementMethod] nvarchar(100) NOT NULL, + [SPCMISamplingSourceType] int NOT NULL, + [SPCMISamplingAccountID] int NOT NULL, + [TransactionID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [OBDefaultInpatientReimbursementMethod] nvarchar(100) NOT NULL, + [OBDefaultOutpatientReimbursementMethod] nvarchar(100) NOT NULL, + PRIMARY KEY ([PayorGroupID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPayorGroup] ([MemberGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimPayorGroup] ([Name]); +GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__Membe__4F812C54] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorGr__Name__5075508D] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__Categ__79059230] DEFAULT ('') FOR [Category]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__Reimb__79F9B669] DEFAULT ('') FOR [ReimbursementType]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__Payor__545B539E] DEFAULT ('') FOR [PayorGroupCode]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SortO__00A6B3F8] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__IsCap__2A471CB2] DEFAULT ((0)) FOR [IsCapital]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__CAPCh__665478E7] DEFAULT ((0)) FOR [CAPChargesFinancialReportingID]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__CAPCh__67489D20] DEFAULT ('') FOR [CAPChargesFinancialReporting]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__CAPCo__683CC159] DEFAULT ((0)) FOR [CAPContractualsFinancialReportingID]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__CAPCo__6930E592] DEFAULT ('') FOR [CAPContractualsFinancialReporting]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__IsDSS__2D23895D] DEFAULT ((0)) FOR [IsDSS]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorGr__IsOB__2B3B40EB] DEFAULT ((0)) FOR [IsOB]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorGr__IsMR__2C2F6524] DEFAULT ((0)) FOR [IsMR]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorGr__IsSP__2952F879] DEFAULT ((0)) FOR [IsSP]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPHCR__79625787] DEFAULT ('') FOR [SPHCRType]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPHCR__50158FA4] DEFAULT ((0)) FOR [SPHCRPayorID]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPHCR__4F216B6B] DEFAULT ('') FOR [SPHCRPayor]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPCha__262CA4D5] DEFAULT ((0)) FOR [SPChargesFinancialReportingID]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPCha__2AF159F2] DEFAULT ('') FOR [SPChargesFinancialReporting]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPCon__2720C90E] DEFAULT ((0)) FOR [SPContractualsFinancialReportingID]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPCon__2BE57E2B] DEFAULT ('') FOR [SPContractualsFinancialReporting]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPDef__18A989A6] DEFAULT ('Per Diem') FOR [SPDefaultInpatientReimbursementMethod]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPDef__199DADDF] DEFAULT ('% of Charge') FOR [SPDefaultOutpatientReimbursementMethod]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPDef__1A91D218] DEFAULT ('% of Charge') FOR [SPDefaultClinicReimbursementMethod]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPCMI__6A7A0F86] DEFAULT ((0)) FOR [SPCMISamplingSourceType]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__SPCMI__6B6E33BF] DEFAULT ((0)) FOR [SPCMISamplingAccountID]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__FW_DimPayorGroup_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__Histo__516974C6] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__OBDef__61CE5608] DEFAULT ('Per Diem') FOR [OBDefaultInpatientReimbursementMethod]; GO +ALTER TABLE [fw].[DimPayorGroup] ADD CONSTRAINT [DF__DimPayorG__OBDef__62C27A41] DEFAULT ('% of Charge') FOR [OBDefaultOutpatientReimbursementMethod]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimPayorGroupPH ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimPayorGroupPH] ( + [PayorGroupPHID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([PayorGroupPHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPayorGroupPH] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimPayorGroupPH] ADD CONSTRAINT [DF__FW_DimPayorGroupPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimPayorGroupPH] ADD CONSTRAINT [DF__DimPayorG__Membe__562E29E3] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimPayorGroupPH] ADD CONSTRAINT [DF__DimPayorGr__Name__57224E1C] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimPayorGroupPH] ADD CONSTRAINT [DF__DimPayorG__Histo__58167255] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimPayorPH ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimPayorPH] ( + [PayorPHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([PayorPHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPayorPH] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimPayorPH] ADD CONSTRAINT [DF__FW_DimPayorPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimPayorPH] ADD CONSTRAINT [DF__DimPayorPH__Name__31246061] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimPayorPH] ADD CONSTRAINT [DF__DimPayorP__Membe__3218849A] DEFAULT (newid()) FOR [MemberGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimPhysicianGroup ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimPhysicianGroup] ( + [PhysicianGroupID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Category] nvarchar(200) NOT NULL, + [Subcategory] nvarchar(200) NOT NULL, + [PhysicianType] nvarchar(100) NOT NULL, + [SortOrder] int NOT NULL, + [IsCapital] bit NOT NULL, + [IsDSS] bit NOT NULL, + [IsMR] bit NOT NULL, + [IsOB] bit NOT NULL, + [IsSP] bit NOT NULL, + [SPSalariesFinancialReportingID] int NOT NULL, + [SPSalariesFinancialReporting] nvarchar(100) NOT NULL, + [SPFTEsFinancialReportingID] int NOT NULL, + [SPFTEsFinancialReporting] varchar(200) NOT NULL, + [TransactionID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [SPSalariesVolumeDriverID] int NOT NULL, + [SPSalariesVolumeDriver] nvarchar(100) NOT NULL, + [SPPhysicianBenefitsTypeID] int NOT NULL, + [SPPhysicianBenefitsType] nvarchar(100) NOT NULL, + [WorkWeekOverrideID] int NOT NULL, + PRIMARY KEY ([PhysicianGroupID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPhysicianGroup] ([MemberGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimPhysicianGroup] ([Name]); +GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__FW_DimPhysicianGroup_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__SPSal__28CD1311] DEFAULT ((0)) FOR [SPSalariesVolumeDriverID]; GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__SPSal__29C1374A] DEFAULT ('') FOR [SPSalariesVolumeDriver]; GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__SPPhy__2AB55B83] DEFAULT ((0)) FOR [SPPhysicianBenefitsTypeID]; GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__SPPhy__2BA97FBC] DEFAULT ('') FOR [SPPhysicianBenefitsType]; GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__Membe__0F1C8E7C] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__Physi__3A7100D5] DEFAULT ('Not specified') FOR [Name]; GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__Categ__26CC5CE0] DEFAULT ('') FOR [Category]; GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__Subca__27C08119] DEFAULT ('') FOR [Subcategory]; GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__Physi__7B4A9FF9] DEFAULT ('') FOR [PhysicianType]; GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__SortO__28B4A552] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__IsCap__48BCEFF1] DEFAULT ((1)) FOR [IsCapital]; GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__IsDSS__4B995C9C] DEFAULT ((1)) FOR [IsDSS]; GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysici__IsMR__4AA53863] DEFAULT ((1)) FOR [IsMR]; GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysici__IsOB__49B1142A] DEFAULT ((1)) FOR [IsOB]; GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysici__IsSP__47C8CBB8] DEFAULT ((1)) FOR [IsSP]; GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__Salar__71F4DB05] DEFAULT ((0)) FOR [SPSalariesFinancialReportingID]; GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__Salar__72E8FF3E] DEFAULT ('') FOR [SPSalariesFinancialReporting]; GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__SPFTE__0773138B] DEFAULT ((0)) FOR [SPFTEsFinancialReportingID]; GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__SPFTE__086737C4] DEFAULT ('') FOR [SPFTEsFinancialReporting]; GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__Histo__3B65250E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimPhysicianGroup] ADD CONSTRAINT [DF__DimPhysic__WorkW__7A282FE2] DEFAULT ((-1)) FOR [WorkWeekOverrideID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimPhysicianGroupPH ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimPhysicianGroupPH] ( + [PhysicianGroupPHID] int NOT NULL, + [Name] nvarchar(100) NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([PhysicianGroupPHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPhysicianGroupPH] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimPhysicianGroupPH] ADD CONSTRAINT [DF__DimPhysic__Membe__1010B2B5] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimPhysicianGroupPH] ADD CONSTRAINT [DF__FW_DimPhysicianGroupPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimPhysicianGroupPH] ADD CONSTRAINT [DF__DimPhysic__Physi__4029DA2B] DEFAULT ('Not specified') FOR [Name]; GO +ALTER TABLE [fw].[DimPhysicianGroupPH] ADD CONSTRAINT [DF__DimPhysic__Histo__411DFE64] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimPhysicianPH ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimPhysicianPH] ( + [PhysicianPHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([PhysicianPHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPhysicianPH] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimPhysicianPH] ADD CONSTRAINT [DF__DimPhysic__Histo__4C8063A2] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimPhysicianPH] ADD CONSTRAINT [DF__DimPhysici__Name__4A981B30] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimPhysicianPH] ADD CONSTRAINT [DF__DimPhysic__Membe__4B8C3F69] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimPhysicianPH] ADD CONSTRAINT [DF__DimPhysic__Trans__4D7487DB] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimPhysicianSpecialty ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimPhysicianSpecialty] ( + [PhysicianSpecialtyID] int NOT NULL, + [Name] nvarchar(203) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [PhysicianSpecialtyCode] nvarchar(100) NOT NULL, + [SpecialtyGroup] nvarchar(100) NOT NULL, + [Description] nvarchar(100) NOT NULL, + [RVUTarget] nvarchar(100) NOT NULL, + PRIMARY KEY ([PhysicianSpecialtyID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimPhysicianSpecialty] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimPhysicianSpecialty] ADD CONSTRAINT [DF__DimPhysic__Membe__0F775562] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimPhysicianSpecialty] ADD CONSTRAINT [DF__DimPhysic__Trans__115F9DD4] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimPhysicianSpecialty] ADD CONSTRAINT [DF__DimPhysic__Physi__1253C20D] DEFAULT ('') FOR [PhysicianSpecialtyCode]; GO +ALTER TABLE [fw].[DimPhysicianSpecialty] ADD CONSTRAINT [DF__DimPhysic__Speci__1347E646] DEFAULT ('') FOR [SpecialtyGroup]; GO +ALTER TABLE [fw].[DimPhysicianSpecialty] ADD CONSTRAINT [DF__DimPhysic__Descr__143C0A7F] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fw].[DimPhysicianSpecialty] ADD CONSTRAINT [DF__DimPhysic__Histo__106B799B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimPhysicianSpecialty] ADD CONSTRAINT [DF__DimPhysic__RVUTa__5F933816] DEFAULT ('') FOR [RVUTarget]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimPositionType ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimPositionType] ( + [HistoryItemGUID] uniqueidentifier NOT NULL, + [PositionTypeID] int NOT NULL, + [Name] nvarchar(255) NOT NULL, + [TransactionID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [PositionTypeAssignmentTypeID] int NOT NULL, + PRIMARY KEY ([PositionTypeID]) +); +GO +ALTER TABLE [fw].[DimPositionType] ADD CONSTRAINT [DF__DimPositi__Histo__3F33B352] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimPositionType] ADD CONSTRAINT [DF__DimPositio__Name__411BFBC4] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimPositionType] ADD CONSTRAINT [DF__DimPositi__Trans__42101FFD] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimPositionType] ADD CONSTRAINT [DF__DimPositi__Membe__43044436] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimPositionType] ADD CONSTRAINT [DF__DimPositi__Posit__43F8686F] DEFAULT ((1)) FOR [PositionTypeAssignmentTypeID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimPositionTypeAssignmentType ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimPositionTypeAssignmentType] ( + [HistoryItemGUID] uniqueidentifier NOT NULL, + [PositionTypeAssignmentTypeID] int NOT NULL, + [Name] nvarchar(255) NOT NULL, + [TransactionID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([PositionTypeAssignmentTypeID]) +); +GO +ALTER TABLE [fw].[DimPositionTypeAssignmentType] ADD CONSTRAINT [DF__DimPositi__Histo__397AD9FC] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimPositionTypeAssignmentType] ADD CONSTRAINT [DF__DimPositio__Name__3B63226E] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimPositionTypeAssignmentType] ADD CONSTRAINT [DF__DimPositi__Trans__3C5746A7] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimPositionTypeAssignmentType] ADD CONSTRAINT [DF__DimPositi__Membe__3D4B6AE0] DEFAULT (newid()) FOR [MemberGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimProductiveClass ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimProductiveClass] ( + [ProductiveClassID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [SortOrder] int NOT NULL, + PRIMARY KEY ([ProductiveClassID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimProductiveClass] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimProductiveClass] ADD CONSTRAINT [DF__FW_DimProductiveClass_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimProductiveClass] ADD CONSTRAINT [DF__DimProduc__Histo__1D9FB7FD] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimProductiveClass] ADD CONSTRAINT [DF__DimProduct__Name__1BB76F8B] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimProductiveClass] ADD CONSTRAINT [DF__DimProduc__Membe__1CAB93C4] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimProductiveClass] ADD CONSTRAINT [DF_DimProductiveClass_SortOrder] DEFAULT ((0)) FOR [SortOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimProgram ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimProgram] ( + [ProgramID] int NOT NULL, + [Name] nvarchar(203) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [Code] nvarchar(100) NOT NULL, + [Description] nvarchar(100) NOT NULL, + [SortOrder] int NOT NULL, + PRIMARY KEY ([ProgramID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimProgram] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimProgram] ADD CONSTRAINT [DF__DimProgra__Membe__3629A1FE] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimProgram] ADD CONSTRAINT [DF__DimProgra__Histo__371DC637] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimProgram] ADD CONSTRAINT [DF__DimProgra__Trans__3811EA70] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimProgram] ADD CONSTRAINT [DF__DimProgram__Code__39060EA9] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimProgram] ADD CONSTRAINT [DF__DimProgra__Descr__39FA32E2] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fw].[DimProgram] ADD CONSTRAINT [DF__DimProgra__SortO__3AEE571B] DEFAULT ((0)) FOR [SortOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimProject ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimProject] ( + [ProjectID] int NOT NULL, + [Name] nvarchar(203) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [SortOrder] int NOT NULL, + [Code] nvarchar(100) NOT NULL, + [Description] nvarchar(100) NOT NULL, + PRIMARY KEY ([ProjectID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimProject] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimProject] ADD CONSTRAINT [DF__DimProjec__Histo__3EBEE7FF] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimProject] ADD CONSTRAINT [DF__DimProjec__Membe__3DCAC3C6] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimProject] ADD CONSTRAINT [DF__DimProjec__Trans__3FB30C38] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimProject] ADD CONSTRAINT [DF__DimProjec__SortO__40A73071] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimProject] ADD CONSTRAINT [DF__DimProject__Code__419B54AA] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimProject] ADD CONSTRAINT [DF__DimProjec__Descr__428F78E3] DEFAULT ('') FOR [Description]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimProvider ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimProvider] ( + [ProviderID] int NOT NULL, + [Type] nvarchar(100) NOT NULL, + [NameFirst] nvarchar(100) NOT NULL, + [NameLast] nvarchar(100) NOT NULL, + [ProviderName] nvarchar(202) NOT NULL, + [ProviderCode] nvarchar(100) NOT NULL, + [PhysicianSpecialtyID] int NOT NULL, + [StateLicenseNumber] nvarchar(100) NOT NULL, + [NPI] nvarchar(100) NOT NULL, + [GroupAffiliaition] nvarchar(100) NOT NULL, + [DSSIsDefined] bit NOT NULL, + [OBIsDefined] bit NOT NULL, + [OBIsActive] bit NOT NULL, + [IsEmployee] bit NOT NULL, + [OBVolumeTarget1] decimal NOT NULL, + [OBVolumeTarget2] decimal NOT NULL, + [OBTier1Threshold] decimal NOT NULL, + [OBTier2Threshold] decimal NOT NULL, + [OBTier3Threshold] decimal NOT NULL, + [OBTier4Threshold] int NOT NULL, + [OBTier5Threshold] int NOT NULL, + [OBTier6Threshold] int NOT NULL, + [OBTier1Rate] money NOT NULL, + [OBTier2Rate] money NOT NULL, + [OBTier3Rate] money NOT NULL, + [OBTier4Rate] money NOT NULL, + [OBTier5Rate] money NOT NULL, + [OBTier6Rate] money NOT NULL, + [BasePay] money NOT NULL, + [PayRate] money NOT NULL, + [CompensationMethod] nvarchar(100) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [WorkWeekOverrideID] int NOT NULL, + [IsPhysician] int NOT NULL, + [Name] nvarchar(304) NOT NULL, + [IsVariable] bit NOT NULL, + [OBVolumeTarget3] decimal NOT NULL, + PRIMARY KEY ([ProviderID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimProvider] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__Histo__2690903B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__WorkW__22DE9604] DEFAULT ((-1)) FOR [WorkWeekOverrideID]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBVol__46C02E44] DEFAULT ((0)) FOR [OBVolumeTarget3]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__IsVar__47BE741E] DEFAULT ((0)) FOR [IsVariable]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvide__Type__296CFCE6] DEFAULT ('') FOR [Type]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__NameF__423CA363] DEFAULT ('') FOR [NameFirst]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__NameL__4330C79C] DEFAULT ('') FOR [NameLast]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__Provi__2E31B203] DEFAULT ('') FOR [ProviderCode]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__Physi__310E1EAE] DEFAULT ((0)) FOR [PhysicianSpecialtyID]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__State__320242E7] DEFAULT ('') FOR [StateLicenseNumber]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvider__NPI__32F66720] DEFAULT ('') FOR [NPI]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__Group__33EA8B59] DEFAULT ('') FOR [GroupAffiliaition]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__DSSIs__00B5CB6D] DEFAULT ((0)) FOR [DSSIsDefined]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBIsD__7FC1A734] DEFAULT ((0)) FOR [OBIsDefined]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBIsA__2D3D8DCA] DEFAULT ((1)) FOR [OBIsActive]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__IsEmp__3019FA75] DEFAULT ((0)) FOR [IsEmployee]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBVol__2B6B1F48] DEFAULT ((0)) FOR [OBVolumeTarget1]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBVol__2C5F4381] DEFAULT ((0)) FOR [OBVolumeTarget2]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBTie__7CE53A89] DEFAULT ((0)) FOR [OBTier1Threshold]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBTie__7DD95EC2] DEFAULT ((0)) FOR [OBTier2Threshold]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBTie__7ECD82FB] DEFAULT ((0)) FOR [OBTier3Threshold]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBTie__55703EBF] DEFAULT ((0)) FOR [OBTier4Threshold]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBTie__566462F8] DEFAULT ((0)) FOR [OBTier5Threshold]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OTTie__57588731] DEFAULT ((0)) FOR [OBTier6Threshold]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__Thres__2B554558] DEFAULT ((0)) FOR [OBTier1Rate]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBTie__7AFCF217] DEFAULT ((0)) FOR [OBTier2Rate]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBTie__7BF11650] DEFAULT ((0)) FOR [OBTier3Rate]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBTie__5293D214] DEFAULT ((0)) FOR [OBTier4Rate]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBTie__5387F64D] DEFAULT ((0)) FOR [OBTier5Rate]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__OBTie__547C1A86] DEFAULT ((0)) FOR [OBTier6Rate]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__BaseP__2878D8AD] DEFAULT ((0)) FOR [BasePay]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__PayRa__2C496991] DEFAULT ((0)) FOR [PayRate]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__Compe__2A61211F] DEFAULT ('') FOR [CompensationMethod]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__Membe__259C6C02] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimProvider] ADD CONSTRAINT [DF__DimProvid__Trans__2784B474] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimProviderPH ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimProviderPH] ( + [ProviderPHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([ProviderPHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimProviderPH] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimProviderPH] ADD CONSTRAINT [DF__DimProvide__Name__39A364AF] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimProviderPH] ADD CONSTRAINT [DF__DimProvid__Membe__3A9788E8] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimProviderPH] ADD CONSTRAINT [DF__DimProvid__Trans__3C7FD15A] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimProviderPH] ADD CONSTRAINT [DF__DimProvid__Histo__3B8BAD21] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimQuarter ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimQuarter] ( + [MemberGUID] uniqueidentifier NOT NULL, + [QuarterID] tinyint NOT NULL, + [Name] nvarchar(100) NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([QuarterID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimQuarter] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimQuarter] ADD CONSTRAINT [DF__FW_DimQuarter_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimQuarter] ADD CONSTRAINT [DF_DimQuarter_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimQuarter] ADD CONSTRAINT [DF_DimQuarter_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimQuarter] ADD CONSTRAINT [DF_DimQuarter_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimReportDetailType ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimReportDetailType] ( + [ReportDetailTypeID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [TableName] nvarchar(200) NOT NULL, + PRIMARY KEY ([ReportDetailTypeID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimReportDetailType] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimReportDetailType] ADD CONSTRAINT [DF__DimReport__Histo__78A799BF] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimReportDetailType] ADD CONSTRAINT [DF__DimReportD__Name__76BF514D] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimReportDetailType] ADD CONSTRAINT [DF__DimReport__Membe__77B37586] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimReportDetailType] ADD CONSTRAINT [DF__DimReport__Trans__799BBDF8] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimReportDetailType] ADD CONSTRAINT [DF__DimReport__Table__7A8FE231] DEFAULT ('') FOR [TableName]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimResearchDepartmentCategory ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimResearchDepartmentCategory] ( + [ResearchDepartmentCategoryID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [SortOrder] int NOT NULL, + PRIMARY KEY ([ResearchDepartmentCategoryID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimResearchDepartmentCategory] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimResearchDepartmentCategory] ADD CONSTRAINT [DF__DimResear__Histo__7DD4CC82] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimResearchDepartmentCategory] ADD CONSTRAINT [DF__DimResearc__Name__7BEC8410] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimResearchDepartmentCategory] ADD CONSTRAINT [DF__DimResear__Membe__7CE0A849] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimResearchDepartmentCategory] ADD CONSTRAINT [DF__DimResear__Trans__7EC8F0BB] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimResearchDepartmentCategory] ADD CONSTRAINT [DF__DimResear__SortO__7FBD14F4] DEFAULT ((0)) FOR [SortOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimRowNumber ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimRowNumber] ( + [RowNumberID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowNumberID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimRowNumber] ([MemberGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimRowNumber] ([Name]); +GO +ALTER TABLE [fw].[DimRowNumber] ADD CONSTRAINT [DF__FW_DimRowNumber_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimRowNumber] ADD CONSTRAINT [DF__DimRowNumb__Name__58B36098] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimRowNumber] ADD CONSTRAINT [DF__DimRowNum__Membe__59A784D1] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimRowNumber] ADD CONSTRAINT [DF__DimRowNum__Histo__5A9BA90A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimSPHAccountRollup ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimSPHAccountRollup] ( + [SPHAccountRollupID] int NOT NULL, + [TransactionID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Statement] nvarchar(200) NOT NULL, + [Category] nvarchar(200) NOT NULL, + [Section] nvarchar(200) NOT NULL, + [SortOrder] int NOT NULL, + [IsStandard] bit NOT NULL, + [SPHCostComponent] nvarchar(400) NOT NULL, + [SPHCostComponentRollup] nvarchar(400) NOT NULL, + [SPHAccountRollupCode] nvarchar(100) NOT NULL, + [LineItem] nvarchar(200) NOT NULL, + [Name] nvarchar(606) NOT NULL, + PRIMARY KEY ([SPHAccountRollupID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimSPHAccountRollup] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__Trans__318AA99D] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__Membe__327ECDD6] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__State__34671648] DEFAULT ('Not Specified') FOR [Statement]; GO +ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__Categ__355B3A81] DEFAULT ('Not Specified') FOR [Category]; GO +ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__Secti__374382F3] DEFAULT ('') FOR [Section]; GO +ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__SortO__3837A72C] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__IsSta__392BCB65] DEFAULT ((0)) FOR [IsStandard]; GO +ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__SPHAc__2723C071] DEFAULT ('') FOR [SPHAccountRollupCode]; GO +ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__SPHCo__2A153BB5] DEFAULT ('') FOR [SPHCostComponent]; GO +ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__SPHCo__2B095FEE] DEFAULT ('') FOR [SPHCostComponentRollup]; GO +ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__LineI__6809E33B] DEFAULT ('Not Specified') FOR [LineItem]; GO +ALTER TABLE [fw].[DimSPHAccountRollup] ADD CONSTRAINT [DF__DimSPHAcc__Histo__3372F20F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimSPHDepartment ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimSPHDepartment] ( + [HistoryItemGUID] uniqueidentifier NOT NULL, + [SPHDepartmentID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [TransactionID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [SPHDepartmentCode] nvarchar(100) NOT NULL, + [SPHDepartmentRollup] nvarchar(200) NOT NULL, + PRIMARY KEY ([SPHDepartmentID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [NCU_SPHDepartmentCode] ON [fw].[DimSPHDepartment] ([SPHDepartmentCode]) INCLUDE ([SPHDepartmentID]); +GO +ALTER TABLE [fw].[DimSPHDepartment] ADD CONSTRAINT [DF__DimSPHDep__Histo__3FB5067A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimSPHDepartment] ADD CONSTRAINT [DF__DimSPHDepa__Name__419D4EEC] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimSPHDepartment] ADD CONSTRAINT [DF__DimSPHDep__Trans__42917325] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimSPHDepartment] ADD CONSTRAINT [DF__DimSPHDep__Membe__4385975E] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimSPHDepartment] ADD CONSTRAINT [DF__DimSPHDep__SPHDe__4479BB97] DEFAULT ('') FOR [SPHDepartmentCode]; GO +ALTER TABLE [fw].[DimSPHDepartment] ADD CONSTRAINT [DF__DimSPHDep__SPHDe__456DDFD0] DEFAULT ('') FOR [SPHDepartmentRollup]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimSPHDepartmentRollup ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimSPHDepartmentRollup] ( + [HistoryItemGUID] uniqueidentifier NOT NULL, + [SPHDepartmentRollupID] int NOT NULL, + [TransactionID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [SortOrder] int NOT NULL, + [IsStandard] bit NOT NULL, + [Name] nvarchar(200) NOT NULL, + [SPHDepartmentRollupCode] nvarchar(100) NOT NULL, + PRIMARY KEY ([SPHDepartmentRollupID]) +); +GO +ALTER TABLE [fw].[DimSPHDepartmentRollup] ADD CONSTRAINT [DF__DimSPHDep__Trans__1212C99B] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimSPHDepartmentRollup] ADD CONSTRAINT [DF__DimSPHDep__Membe__1306EDD4] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimSPHDepartmentRollup] ADD CONSTRAINT [DF__DimSPHDep__SortO__13FB120D] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimSPHDepartmentRollup] ADD CONSTRAINT [DF__DimSPHDep__IsSta__14EF3646] DEFAULT ((0)) FOR [IsStandard]; GO +ALTER TABLE [fw].[DimSPHDepartmentRollup] ADD CONSTRAINT [DF__DimSPHDepa__Name__15E35A7F] DEFAULT ('Not Specified') FOR [Name]; GO +ALTER TABLE [fw].[DimSPHDepartmentRollup] ADD CONSTRAINT [DF__DimSPHDep__Histo__102A8129] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimSPHDepartmentRollup] ADD CONSTRAINT [DF__DimSPHDep__SPHDe__5A195492] DEFAULT ('') FOR [SPHDepartmentRollupCode]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimSPHDepartmentType ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimSPHDepartmentType] ( + [HistoryItemGUID] uniqueidentifier NOT NULL, + [SPHDepartmentTypeID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [TransactionID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [SPHDepartmentTypeCode] nvarchar(100) NOT NULL, + [IsStandard] bit NOT NULL, + PRIMARY KEY ([SPHDepartmentTypeID]) +); +GO +ALTER TABLE [fw].[DimSPHDepartmentType] ADD CONSTRAINT [DF__DimSPHDepa__Name__3408BA43] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimSPHDepartmentType] ADD CONSTRAINT [DF__DimSPHDep__Trans__34FCDE7C] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimSPHDepartmentType] ADD CONSTRAINT [DF__DimSPHDep__Membe__35F102B5] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimSPHDepartmentType] ADD CONSTRAINT [DF__DimSPHDep__SPHDe__5B0D78CB] DEFAULT ('') FOR [SPHDepartmentTypeCode]; GO +ALTER TABLE [fw].[DimSPHDepartmentType] ADD CONSTRAINT [DF__DimSPHDep__Histo__322071D1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimSPHDepartmentType] ADD CONSTRAINT [DF__DimSPHDep__IsSta__5CF5C13D] DEFAULT ((0)) FOR [IsStandard]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimSPHJobCodeRollup ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimSPHJobCodeRollup] ( + [HistoryItemGUID] uniqueidentifier NOT NULL, + [SPHJobCodeRollupID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [TransactionID] int NOT NULL, + [SortOrder] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [IsStandard] bit NOT NULL, + [SPHJobCodeRollupCode] nvarchar(100) NOT NULL, + [SPHCostComponent] nvarchar(400) NOT NULL, + PRIMARY KEY ([SPHJobCodeRollupID]) +); +GO +ALTER TABLE [fw].[DimSPHJobCodeRollup] ADD CONSTRAINT [DF__DimSPHJob__SPHJo__2817E4AA] DEFAULT ('') FOR [SPHJobCodeRollupCode]; GO +ALTER TABLE [fw].[DimSPHJobCodeRollup] ADD CONSTRAINT [DF__DimSPHJob__SPHCo__47909003] DEFAULT ('') FOR [SPHCostComponent]; GO +ALTER TABLE [fw].[DimSPHJobCodeRollup] ADD CONSTRAINT [DF__DimSPHJob__Histo__59CE7078] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimSPHJobCodeRollup] ADD CONSTRAINT [DF__DimSPHJobC__Name__5BB6B8EA] DEFAULT ('Not Specified') FOR [Name]; GO +ALTER TABLE [fw].[DimSPHJobCodeRollup] ADD CONSTRAINT [DF__DimSPHJob__Trans__5CAADD23] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimSPHJobCodeRollup] ADD CONSTRAINT [DF__DimSPHJob__SortO__5D9F015C] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimSPHJobCodeRollup] ADD CONSTRAINT [DF__DimSPHJob__Membe__5E932595] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimSPHJobCodeRollup] ADD CONSTRAINT [DF__DimSPHJob__IsSta__5F8749CE] DEFAULT ((0)) FOR [IsStandard]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimSPHPayCodeRollup ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimSPHPayCodeRollup] ( + [HistoryItemGUID] uniqueidentifier NOT NULL, + [SPHPayCodeRollupID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [TransactionID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [SPHProductiveClass] nvarchar(200) NOT NULL, + [SortOrder] int NOT NULL, + [IsStandard] bit NOT NULL, + [SPHPayCodeRollupCode] nvarchar(100) NOT NULL, + PRIMARY KEY ([SPHPayCodeRollupID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [NCU_SPHPayCodeRollupCode] ON [fw].[DimSPHPayCodeRollup] ([SPHPayCodeRollupCode]) INCLUDE ([SPHPayCodeRollupID]); +GO +ALTER TABLE [fw].[DimSPHPayCodeRollup] ADD CONSTRAINT [DF__DimSPHPay__Histo__3142F2DF] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimSPHPayCodeRollup] ADD CONSTRAINT [DF__DimSPHPayC__Name__332B3B51] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimSPHPayCodeRollup] ADD CONSTRAINT [DF__DimSPHPay__Trans__341F5F8A] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimSPHPayCodeRollup] ADD CONSTRAINT [DF__DimSPHPay__Membe__351383C3] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimSPHPayCodeRollup] ADD CONSTRAINT [DF__DimSPHPay__SPHPr__3607A7FC] DEFAULT ('') FOR [SPHProductiveClass]; GO +ALTER TABLE [fw].[DimSPHPayCodeRollup] ADD CONSTRAINT [DF__DimSPHPay__SortO__36FBCC35] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimSPHPayCodeRollup] ADD CONSTRAINT [DF__DimSPHPay__IsSta__37EFF06E] DEFAULT ((0)) FOR [IsStandard]; GO +ALTER TABLE [fw].[DimSPHPayCodeRollup] ADD CONSTRAINT [DF__DimSPHPay__SPHPa__38E414A7] DEFAULT ('') FOR [SPHPayCodeRollupCode]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimSecureGroup ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimSecureGroup] ( + [SecureGroupID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([SecureGroupID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimSecureGroup] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimSecureGroup] ADD CONSTRAINT [DF__FW_DimSecureGroup_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimSecureGroup] ADD CONSTRAINT [DF__DimSecureG__Name__1BDFF60F] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimSecureGroup] ADD CONSTRAINT [DF__DimSecure__Membe__1CD41A48] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimSecureGroup] ADD CONSTRAINT [DF__DimSecure__Histo__1DC83E81] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimServiceLine ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimServiceLine] ( + [ServiceLineID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(303) NOT NULL, + [RollupID] int NOT NULL, + [Rollup] nvarchar(100) NOT NULL, + [RollupSortOrder] int NOT NULL, + [ProductLine] nvarchar(200) NOT NULL, + [Code] nvarchar(100) NOT NULL, + [SortOrder] int NOT NULL, + [TransactionID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([ServiceLineID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [NCU_PreventDuplicates] ON [fw].[DimServiceLine] ([RollupID], [ProductLine]); +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimServiceLine] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimServiceLine] ADD CONSTRAINT [DF__DimServic__Membe__3C4FF2FD] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimServiceLine] ADD CONSTRAINT [DF__DimServic__Rollu__1E11EF81] DEFAULT ((0)) FOR [RollupID]; GO +ALTER TABLE [fw].[DimServiceLine] ADD CONSTRAINT [DF__DimServic__Rollu__11669219] DEFAULT ('Not Specified') FOR [Rollup]; GO +ALTER TABLE [fw].[DimServiceLine] ADD CONSTRAINT [DF__DimServic__Rollu__23CAC8D7] DEFAULT ((0)) FOR [RollupSortOrder]; GO +ALTER TABLE [fw].[DimServiceLine] ADD CONSTRAINT [DF__DimServic__Produ__1F0613BA] DEFAULT ('') FOR [ProductLine]; GO +ALTER TABLE [fw].[DimServiceLine] ADD CONSTRAINT [DF__DimService__Code__288F7DF4] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimServiceLine] ADD CONSTRAINT [DF__DimServic__SortO__1FFA37F3] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimServiceLine] ADD CONSTRAINT [DF__FW_DimServiceLine_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimServiceLine] ADD CONSTRAINT [DF__DimServic__Histo__3D441736] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimServiceLine2 ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimServiceLine2] ( + [ServiceLine2ID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [PatientTypeID] int NOT NULL, + [TransactionID] int NOT NULL, + [Rollup] nvarchar(100) NOT NULL, + [Rollup2] nvarchar(100) NOT NULL, + [SortOrder] int NOT NULL, + PRIMARY KEY ([ServiceLine2ID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimServiceLine2] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimServiceLine2] ADD CONSTRAINT [DF__DimService__Name__7B78B5DE] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimServiceLine2] ADD CONSTRAINT [DF__DimServic__Membe__7C6CDA17] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimServiceLine2] ADD CONSTRAINT [DF__DimServic__Patie__7E552289] DEFAULT ((0)) FOR [PatientTypeID]; GO +ALTER TABLE [fw].[DimServiceLine2] ADD CONSTRAINT [DF__DimServic__Rollu__153722FD] DEFAULT ('Not Specified') FOR [Rollup]; GO +ALTER TABLE [fw].[DimServiceLine2] ADD CONSTRAINT [DF__DimServic__Rollu__17A9DEE8] DEFAULT ('Not Specified') FOR [Rollup2]; GO +ALTER TABLE [fw].[DimServiceLine2] ADD CONSTRAINT [DF__FW_DimServiceLine2_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimServiceLine2] ADD CONSTRAINT [DF__DimServic__SortO__25F7FE3F] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimServiceLine2] ADD CONSTRAINT [DF__DimServic__Histo__7D60FE50] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimServiceLine3 ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimServiceLine3] ( + [ServiceLine3ID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [PatientTypeID] int NOT NULL, + [TransactionID] int NOT NULL, + [Rollup] nvarchar(100) NOT NULL, + [SortOrder] int NOT NULL, + PRIMARY KEY ([ServiceLine3ID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimServiceLine3] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimServiceLine3] ADD CONSTRAINT [DF__DimServic__Histo__05F64451] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimServiceLine3] ADD CONSTRAINT [DF__DimService__Name__040DFBDF] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimServiceLine3] ADD CONSTRAINT [DF__DimServic__Membe__05022018] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimServiceLine3] ADD CONSTRAINT [DF__DimServic__Patie__06EA688A] DEFAULT ((0)) FOR [PatientTypeID]; GO +ALTER TABLE [fw].[DimServiceLine3] ADD CONSTRAINT [DF__DimServic__Rollu__1907B3E1] DEFAULT ('Not Specified') FOR [Rollup]; GO +ALTER TABLE [fw].[DimServiceLine3] ADD CONSTRAINT [DF__FW_DimServiceLine3_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimServiceLine3] ADD CONSTRAINT [DF__DimServic__SortO__26EC2278] DEFAULT ((0)) FOR [SortOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimServiceLine4 ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimServiceLine4] ( + [ServiceLine4ID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [PatientTypeID] int NOT NULL, + [TransactionID] int NOT NULL, + [Rollup] nvarchar(100) NOT NULL, + [SortOrder] int NOT NULL, + [Rollup2] nvarchar(100) NOT NULL, + PRIMARY KEY ([ServiceLine4ID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimServiceLine4] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimServiceLine4] ADD CONSTRAINT [DF__FW_DimServiceLine4_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimServiceLine4] ADD CONSTRAINT [DF__DimServic__Rollu__1CD844C5] DEFAULT ('Not Specified') FOR [Rollup]; GO +ALTER TABLE [fw].[DimServiceLine4] ADD CONSTRAINT [DF__DimService__Name__0CA341E0] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimServiceLine4] ADD CONSTRAINT [DF__DimServic__Membe__0D976619] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimServiceLine4] ADD CONSTRAINT [DF__DimServic__Patie__0F7FAE8B] DEFAULT ((0)) FOR [PatientTypeID]; GO +ALTER TABLE [fw].[DimServiceLine4] ADD CONSTRAINT [DF__DimServic__SortO__27E046B1] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimServiceLine4] ADD CONSTRAINT [DF__DimServic__Rollu__2BB0D795] DEFAULT ('Not Specified') FOR [Rollup2]; GO +ALTER TABLE [fw].[DimServiceLine4] ADD CONSTRAINT [DF__DimServic__Histo__0E8B8A52] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimServiceLine5 ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimServiceLine5] ( + [ServiceLine5ID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [PatientTypeID] int NOT NULL, + [TransactionID] int NOT NULL, + [Rollup] nvarchar(100) NOT NULL, + [SortOrder] int NOT NULL, + PRIMARY KEY ([ServiceLine5ID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimServiceLine5] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimServiceLine5] ADD CONSTRAINT [DF__FW_DimServiceLine5_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimServiceLine5] ADD CONSTRAINT [DF__DimServic__Rollu__20A8D5A9] DEFAULT ('Not Specified') FOR [Rollup]; GO +ALTER TABLE [fw].[DimServiceLine5] ADD CONSTRAINT [DF__DimServic__SortO__28D46AEA] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimServiceLine5] ADD CONSTRAINT [DF__DimService__Name__153887E1] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimServiceLine5] ADD CONSTRAINT [DF__DimServic__Membe__162CAC1A] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimServiceLine5] ADD CONSTRAINT [DF__DimServic__Patie__1814F48C] DEFAULT ((0)) FOR [PatientTypeID]; GO +ALTER TABLE [fw].[DimServiceLine5] ADD CONSTRAINT [DF__DimServic__Histo__1720D053] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimServiceLine6 ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimServiceLine6] ( + [ServiceLine6ID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [PatientTypeID] int NOT NULL, + [TransactionID] int NOT NULL, + [Rollup] nvarchar(100) NOT NULL, + [SortOrder] int NOT NULL, + PRIMARY KEY ([ServiceLine6ID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimServiceLine6] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimServiceLine6] ADD CONSTRAINT [DF__FW_DimServiceLine6_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimServiceLine6] ADD CONSTRAINT [DF__DimServic__SortO__29C88F23] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimServiceLine6] ADD CONSTRAINT [DF__DimService__Name__1DCDCDE2] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimServiceLine6] ADD CONSTRAINT [DF__DimServic__Membe__1EC1F21B] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimServiceLine6] ADD CONSTRAINT [DF__DimServic__Patie__20AA3A8D] DEFAULT ((0)) FOR [PatientTypeID]; GO +ALTER TABLE [fw].[DimServiceLine6] ADD CONSTRAINT [DF__DimServic__Rollu__2479668D] DEFAULT ('Not Specified') FOR [Rollup]; GO +ALTER TABLE [fw].[DimServiceLine6] ADD CONSTRAINT [DF__DimServic__Histo__1FB61654] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimServiceLineRollup ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimServiceLineRollup] ( + [ServiceLineRollupID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [SortOrder] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([ServiceLineRollupID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimServiceLineRollup] ([MemberGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [fw].[DimServiceLineRollup] ([Name]); +GO +ALTER TABLE [fw].[DimServiceLineRollup] ADD CONSTRAINT [DF__DimServic__Histo__3EF2F508] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimServiceLineRollup] ADD CONSTRAINT [DF__DimService__Name__3C16885D] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimServiceLineRollup] ADD CONSTRAINT [DF__DimServic__SortO__3D0AAC96] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimServiceLineRollup] ADD CONSTRAINT [DF__DimServic__Membe__3DFED0CF] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimServiceLineRollup] ADD CONSTRAINT [DF__DimServic__Trans__3FE71941] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimServiceLineRollupPH ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimServiceLineRollupPH] ( + [ServiceLineRollupPHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([ServiceLineRollupPHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimServiceLineRollupPH] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimServiceLineRollupPH] ADD CONSTRAINT [DF__DimService__Name__4F5F3252] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimServiceLineRollupPH] ADD CONSTRAINT [DF__DimServic__Membe__5053568B] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimServiceLineRollupPH] ADD CONSTRAINT [DF__DimServic__Trans__523B9EFD] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimServiceLineRollupPH] ADD CONSTRAINT [DF__DimServic__Histo__51477AC4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimSourceOfSavings ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimSourceOfSavings] ( + [SourceOfSavingsID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([SourceOfSavingsID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimSourceOfSavings] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimSourceOfSavings] ADD CONSTRAINT [DF__DimSourceO__Name__38F52A8D] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimSourceOfSavings] ADD CONSTRAINT [DF__DimSource__Membe__39E94EC6] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimSourceOfSavings] ADD CONSTRAINT [DF__DimSource__Trans__3BD19738] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimSourceOfSavings] ADD CONSTRAINT [DF__DimSource__Histo__3ADD72FF] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimStaffingCategory ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimStaffingCategory] ( + [HistoryItemGUID] uniqueidentifier NOT NULL, + [StaffingCategoryID] int NOT NULL, + [TransactionID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [StaffingCategoryCode] nvarchar(100) NOT NULL, + [Description] nvarchar(100) NOT NULL, + [Name] nvarchar(203) NOT NULL, + PRIMARY KEY ([StaffingCategoryID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [NCU_StaffingCategoryCode] ON [fw].[DimStaffingCategory] ([StaffingCategoryCode]) INCLUDE ([StaffingCategoryID]); +GO +ALTER TABLE [fw].[DimStaffingCategory] ADD CONSTRAINT [DF__DimStaffi__Trans__018A8973] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimStaffingCategory] ADD CONSTRAINT [DF__DimStaffi__Membe__027EADAC] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimStaffingCategory] ADD CONSTRAINT [DF__DimStaffi__Staff__0372D1E5] DEFAULT ((0)) FOR [StaffingCategoryCode]; GO +ALTER TABLE [fw].[DimStaffingCategory] ADD CONSTRAINT [DF__DimStaffi__Descr__0466F61E] DEFAULT ('Not Specified') FOR [Description]; GO +ALTER TABLE [fw].[DimStaffingCategory] ADD CONSTRAINT [DF__DimStaffi__Histo__7FA24101] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimStrataDecisionServiceLine ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimStrataDecisionServiceLine] ( + [StrataDecisionServiceLineID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [PatientTypeID] int NOT NULL, + PRIMARY KEY ([StrataDecisionServiceLineID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimStrataDecisionServiceLine] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimStrataDecisionServiceLine] ADD CONSTRAINT [DF__DimStrata__Histo__367EA7B9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimStrataDecisionServiceLine] ADD CONSTRAINT [DF__DimStrataD__Name__34965F47] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimStrataDecisionServiceLine] ADD CONSTRAINT [DF__DimStrata__Membe__358A8380] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimStrataDecisionServiceLine] ADD CONSTRAINT [DF__DimStrata__Trans__3772CBF2] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimStrataDecisionServiceLine] ADD CONSTRAINT [DF__DimStrata__Patie__3866F02B] DEFAULT ((0)) FOR [PatientTypeID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimSystem ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimSystem] ( + [SystemID] smallint NOT NULL, + [Name] nvarchar(100) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [Code] nvarchar(200) NOT NULL, + [Description] nvarchar(100) NOT NULL, + [SecureGroupID] int NOT NULL, + [SortOrder] int NOT NULL, + [EliminationsDepartmentID] int NOT NULL, + PRIMARY KEY ([SystemID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimSystem] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimSystem] ADD CONSTRAINT [DF__DimSystem__Histo__2491A282] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimSystem] ADD CONSTRAINT [DF__DimSystem__Membe__239D7E49] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimSystem] ADD CONSTRAINT [DF__DimSystem__Trans__2585C6BB] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimSystem] ADD CONSTRAINT [DF__DimSystem__Code__2679EAF4] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [fw].[DimSystem] ADD CONSTRAINT [DF__DimSystem__Descr__276E0F2D] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fw].[DimSystem] ADD CONSTRAINT [DF__DimSystem__SortO__28623366] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimSystem] ADD CONSTRAINT [DF__DimSystem__Elimi__4FA5B5F6] DEFAULT ((0)) FOR [EliminationsDepartmentID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimTime ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimTime] ( + [TimeID] int NOT NULL, + [Name] varchar(5) NOT NULL, + [Hour] varchar(2) NOT NULL, + [Minute] varchar(2) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [StandardTime] nvarchar(100) NOT NULL, + PRIMARY KEY ([TimeID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimTime] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimTime] ADD CONSTRAINT [DF__DimTime__MemberG__14E518D4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimTime] ADD CONSTRAINT [DF__DimTime__History__15D93D0D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimTime] ADD CONSTRAINT [DF__DimTime__Standar__1AB09A8F] DEFAULT ('12:00 AM') FOR [StandardTime]; GO +ALTER TABLE [fw].[DimTime] ADD CONSTRAINT [DF__FW_DimTime_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimTime] ADD CONSTRAINT [DF__fw_DimTime_Minute] DEFAULT ('') FOR [Minute]; GO +ALTER TABLE [fw].[DimTime] ADD CONSTRAINT [DF__fw_DimTime_Hour] DEFAULT ('') FOR [Hour]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimTimeClass ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimTimeClass] ( + [TimeClassID] tinyint NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [TimeClassCode] nvarchar(3) NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [GlobalID] varchar(64) NOT NULL, + [IsSP] bit NOT NULL, + [SortOrder] int NOT NULL, + [TransactionID] int NOT NULL, + [SPIsISForecast] bit NOT NULL, + PRIMARY KEY ([TimeClassID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_MemberGUID] ON [fw].[DimTimeClass] ([MemberGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [IX_TimeClassCode] ON [fw].[DimTimeClass] ([TimeClassCode]); +CREATE NONCLUSTERED INDEX [IX_Name] ON [fw].[DimTimeClass] ([Name]); +GO +ALTER TABLE [fw].[DimTimeClass] ADD CONSTRAINT [DF__DimTimeCla__IsSP__08A26ADC] DEFAULT ((0)) FOR [IsSP]; GO +ALTER TABLE [fw].[DimTimeClass] ADD CONSTRAINT [DF__FW_DimTimeClass_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimTimeClass] ADD CONSTRAINT [DF_DimTimeClass_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimTimeClass] ADD CONSTRAINT [DF__DimTimeCl__Globa__4C832D6A] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [fw].[DimTimeClass] ADD CONSTRAINT [DF_FWDIMTIMECLASSNAME] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimTimeClass] ADD CONSTRAINT [DF__DimTimeCl__SortO__6BD12204] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [fw].[DimTimeClass] ADD CONSTRAINT [DF__DimTimeCl__SPIsI__70E4B3EE] DEFAULT ((0)) FOR [SPIsISForecast]; GO +ALTER TABLE [fw].[DimTimeClass] ADD CONSTRAINT [DF_DimTimeClass_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimTimeClass] ADD CONSTRAINT [DF_DimTimeClass_Code] DEFAULT ('A') FOR [TimeClassCode]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimTimeClassPH ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimTimeClassPH] ( + [TimeClassPHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([TimeClassPHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimTimeClassPH] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimTimeClassPH] ADD CONSTRAINT [DF__DimTimeCla__Name__148821B3] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimTimeClassPH] ADD CONSTRAINT [DF__FW_DimTimeClassPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimTimeClassPH] ADD CONSTRAINT [DF__DimTimeCl__Membe__157C45EC] DEFAULT (newid()) FOR [MemberGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimUnit ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimUnit] ( + [MemberGUID] uniqueidentifier NOT NULL, + [UnitID] smallint NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Abbreviation] nvarchar(10) NOT NULL, + [Version] timestamp NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [SortOrder] nvarchar(5) NOT NULL, + [TransactionID] int NOT NULL, + [IsActive] bit NOT NULL, + PRIMARY KEY ([UnitID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [MGUID_Unit_data_DimUnit] ON [fw].[DimUnit] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimUnit] ADD CONSTRAINT [DF_data.DimUnit_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimUnit] ADD CONSTRAINT [DF__FW_DimUnit_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimUnit] ADD CONSTRAINT [DF__DimUnit__IsActiv__298B2BD0] DEFAULT ((1)) FOR [IsActive]; GO +ALTER TABLE [fw].[DimUnit] ADD CONSTRAINT [DF_FWDIMUNITSORTORDER] DEFAULT ('') FOR [SortOrder]; GO +ALTER TABLE [fw].[DimUnit] ADD CONSTRAINT [DF_DimUnit_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimUnit] ADD CONSTRAINT [DF_data.DimUnit_Name] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimUnit] ADD CONSTRAINT [DF_data.DimUnit_Abbreviation] DEFAULT ('') FOR [Abbreviation]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimUnitType ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimUnitType] ( + [MemberGUID] uniqueidentifier NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [Name] nvarchar(200) NOT NULL, + [DisplayFormat] nvarchar(50) NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [GlobalID] varchar(32) NOT NULL, + [SPDisplayFormat] nvarchar(100) NOT NULL, + [CapitalDisplayFormat] nvarchar(100) NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([UnitTypeID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimUnitType] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimUnitType] ADD CONSTRAINT [DF__FW_DimUnitType_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimUnitType] ADD CONSTRAINT [DF_DimUnitType_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimUnitType] ADD CONSTRAINT [DF__DimUnitTy__SPDis__2CAAC128] DEFAULT ('') FOR [SPDisplayFormat]; GO +ALTER TABLE [fw].[DimUnitType] ADD CONSTRAINT [DF__DimUnitTy__Capit__2D9EE561] DEFAULT ('') FOR [CapitalDisplayFormat]; GO +ALTER TABLE [fw].[DimUnitType] ADD CONSTRAINT [DF__DimUnitTy__Membe__7BBC73E9] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimUnitType] ADD CONSTRAINT [DF__DimUnitTy__Globa__5AD14CC1] DEFAULT ('') FOR [GlobalID]; GO +ALTER TABLE [fw].[DimUnitType] ADD CONSTRAINT [DF__DimUnitTyp__Name__7AC84FB0] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimUnitType] ADD CONSTRAINT [DF__DimUnitTy__Displ__79D42B77] DEFAULT ('') FOR [DisplayFormat]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimVariability ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimVariability] ( + [HistoryItemGUID] uniqueidentifier NOT NULL, + [VariabilityID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [TransactionID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([VariabilityID]) +); +GO +ALTER TABLE [fw].[DimVariability] ADD CONSTRAINT [DF__DimVariab__Membe__00F16219] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimVariability] ADD CONSTRAINT [DF__DimVariab__Histo__7D20D135] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimVariability] ADD CONSTRAINT [DF__DimVariabi__Name__7F0919A7] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimVariability] ADD CONSTRAINT [DF__DimVariab__Trans__7FFD3DE0] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimWorkWeek ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimWorkWeek] ( + [WorkWeekID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [WorkWeekCode] nvarchar(200) NOT NULL, + [Type] nvarchar(100) NOT NULL, + [SortOrder] nvarchar(100) NOT NULL, + [Hours] numeric NOT NULL, + PRIMARY KEY ([WorkWeekID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimWorkWeek] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimWorkWeek] ADD CONSTRAINT [DF__DimWorkWee__Name__0CEF54E5] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimWorkWeek] ADD CONSTRAINT [DF__DimWorkWe__Membe__0DE3791E] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimWorkWeek] ADD CONSTRAINT [DF__DimWorkWe__Trans__0FCBC190] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimWorkWeek] ADD CONSTRAINT [DF__DimWorkWe__WorkW__10BFE5C9] DEFAULT ('') FOR [WorkWeekCode]; GO +ALTER TABLE [fw].[DimWorkWeek] ADD CONSTRAINT [DF__DimWorkWe__Histo__0ED79D57] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[DimWorkWeek] ADD CONSTRAINT [DF__DimWorkWee__Type__6CA280E4] DEFAULT ('All') FOR [Type]; GO +ALTER TABLE [fw].[DimWorkWeek] ADD CONSTRAINT [DF_dimworkweek_hours] DEFAULT ((40)) FOR [Hours]; GO +ALTER TABLE [fw].[DimWorkWeek] ADD CONSTRAINT [DF__DimWorkWe__SortO__7D049C8D] DEFAULT ('') FOR [SortOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.DimWorkWeekPH ------------------ +--------------------------------------------- +CREATE TABLE [fw].[DimWorkWeekPH] ( + [WorkWeekPHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([WorkWeekPHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [fw].[DimWorkWeekPH] ([MemberGUID]); +GO +ALTER TABLE [fw].[DimWorkWeekPH] ADD CONSTRAINT [DF__DimWorkWee__Name__149076AD] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[DimWorkWeekPH] ADD CONSTRAINT [DF__DimWorkWe__Membe__15849AE6] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[DimWorkWeekPH] ADD CONSTRAINT [DF__DimWorkWe__Trans__176CE358] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[DimWorkWeekPH] ADD CONSTRAINT [DF__DimWorkWe__Histo__1678BF1F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactChargeBasedStatistics ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactChargeBasedStatistics] ( + [RowID] int NOT NULL, + [DateID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [Value] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [fw].[FactChargeBasedStatistics] ([IsDeleted], [DateID], [DepartmentID], [AccountID], [RowID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [fw].[FactChargeBasedStatistics] ([IsDeleted], [DateID], [DepartmentID], [AccountID], [RowID]); +GO +ALTER TABLE [fw].[FactChargeBasedStatistics] ADD CONSTRAINT [DF__FactCharg__Value__0786EF0A] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fw].[FactChargeBasedStatistics] ADD CONSTRAINT [DF__FactCharg__IsDel__087B1343] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactChargeBasedStatistics] ADD CONSTRAINT [DF__FactCharg__Trans__0A635BB5] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[FactChargeBasedStatistics] ADD CONSTRAINT [DF__FactCharg__Histo__096F377C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactChargeBasedStatisticsDailyKeys ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactChargeBasedStatisticsDailyKeys] ( + [DepartmentID] int NOT NULL, + [PayPeriodID] smallint NOT NULL, + [DateID] int NOT NULL, + [AccountID] int NOT NULL, + PRIMARY KEY ([DateID], [DepartmentID], [AccountID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactChargeBasedStatisticsMonthly ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactChargeBasedStatisticsMonthly] ( + [RowID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [Value] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [Version] timestamp NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fw].[FactChargeBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactChargeBasedStatisticsByPostDate_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[FactChargeBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactChargeBasedStatisticsByPostDate_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fw].[FactChargeBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactChargeBasedStatisticsByPostDate_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fw].[FactChargeBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactChargeBasedStatisticsByPostDate_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactChargeBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactChargeBasedStatisticsByPostDate_AccountID] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fw].[FactChargeBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactChargeBasedStatisticsByPostDate_Value] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fw].[FactChargeBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactChargeBasedStatisticsByPostDate_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactChargeBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactChargeBasedStatisticsByPostDate_TransactionID] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactChargeBasedStatisticsPayPeriodKeys ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactChargeBasedStatisticsPayPeriodKeys] ( + [DepartmentID] int NOT NULL, + [PayPeriodID] smallint NOT NULL, + [AccountID] int NOT NULL, + PRIMARY KEY ([PayPeriodID], [DepartmentID], [AccountID]) +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactClinicaltoGLDepartmentMapping ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactClinicaltoGLDepartmentMapping] ( + [RowID] int NOT NULL, + [ClinicalDepartmentID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ClinicalDepartmentCode] nvarchar(100) NOT NULL, + [GLDepartmentCode] nvarchar(100) NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fw].[FactClinicaltoGLDepartmentMapping] ADD CONSTRAINT [DF__FactClini__Histo__1572B9A9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[FactClinicaltoGLDepartmentMapping] ADD CONSTRAINT [DF__FactClini__Clini__12964CFE] DEFAULT ('') FOR [ClinicalDepartmentCode]; GO +ALTER TABLE [fw].[FactClinicaltoGLDepartmentMapping] ADD CONSTRAINT [DF__FactClini__GLDep__138A7137] DEFAULT ('') FOR [GLDepartmentCode]; GO +ALTER TABLE [fw].[FactClinicaltoGLDepartmentMapping] ADD CONSTRAINT [DF__FactClini__IsDel__147E9570] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactClinicaltoGLDepartmentMapping] ADD CONSTRAINT [DF__FactClini__Trans__1666DDE2] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactEliminationsAccountMapping ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactEliminationsAccountMapping] ( + [RowID] int NOT NULL, + [RevenueAccountCode] nvarchar(100) NOT NULL, + [ExpenseAccountCode] nvarchar(100) NOT NULL, + [PlugAccountID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fw].[FactEliminationsAccountMapping] ADD CONSTRAINT [DF__FactElimi__Reven__38233220] DEFAULT ('') FOR [RevenueAccountCode]; GO +ALTER TABLE [fw].[FactEliminationsAccountMapping] ADD CONSTRAINT [DF__FactElimi__Expen__39175659] DEFAULT ('') FOR [ExpenseAccountCode]; GO +ALTER TABLE [fw].[FactEliminationsAccountMapping] ADD CONSTRAINT [DF__FactElimi__PlugA__3A0B7A92] DEFAULT ((0)) FOR [PlugAccountID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactEncounterBasedStatistics ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactEncounterBasedStatistics] ( + [RowID] bigint NOT NULL, + [DateID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [Value] decimal NOT NULL, + [StatisticID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fw].[FactEncounterBasedStatistics] ADD CONSTRAINT [DF_FactEncounterBasedStatistics_DateID] DEFAULT ((0)) FOR [DateID]; GO +ALTER TABLE [fw].[FactEncounterBasedStatistics] ADD CONSTRAINT [DF_FactEncounterBasedStatistics_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactEncounterBasedStatistics] ADD CONSTRAINT [DF_FactEncounterBasedStatistics_AccountID] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fw].[FactEncounterBasedStatistics] ADD CONSTRAINT [DF_FactEncounterBasedStatistics_Value] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fw].[FactEncounterBasedStatistics] ADD CONSTRAINT [DF_FactEncounterBasedStatistics_StatisticID] DEFAULT ((0)) FOR [StatisticID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactEncounterBasedStatisticsMonthly ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactEncounterBasedStatisticsMonthly] ( + [RowID] bigint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [Value] decimal NOT NULL, + [StatisticID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fw].[FactEncounterBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactEncounterBasedStatisticsMonthly_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fw].[FactEncounterBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactEncounterBasedStatisticsMonthly_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fw].[FactEncounterBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactEncounterBasedStatisticsMonthly_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactEncounterBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactEncounterBasedStatisticsMonthly_AccountID] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fw].[FactEncounterBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactEncounterBasedStatisticsMonthly_Value] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [fw].[FactEncounterBasedStatisticsMonthly] ADD CONSTRAINT [DF_FactEncounterBasedStatisticsMonthly_StatisticID] DEFAULT ((0)) FOR [StatisticID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactGLSampled ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactGLSampled] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [Units] decimal NOT NULL, + [UnitsYTD] decimal NOT NULL, + [UnitsPriorYear] decimal NOT NULL, + [UnitsPriorYTD] decimal NOT NULL, + [Dollars] decimal NOT NULL, + [DollarsYTD] decimal NOT NULL, + [DollarsPriorYear] decimal NOT NULL, + [DollarsPriorYTD] decimal NOT NULL, + [TransactionID] int NULL, + [IsSystemGenerated] bit NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_FactGLSampled] ON [fw].[FactGLSampled] ([AccountID], [DepartmentID], [FiscalYearID], [FiscalMonthID], [TimeClassID]); +CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactGLSampled] ([IsDeleted]); +GO +ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [FK_FactGLSampled_DimAccount] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [FK_FactGLSampled_DimFiscalMonth] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO +ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [FK_FactGLSampled_DimFiscalYear] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [FK_FactGLSampled_DimTimeClass] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_DollarsPriorYTD] DEFAULT ((0)) FOR [DollarsPriorYTD]; GO +ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF__FW_FactGLSampled_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_Units] DEFAULT ((0)) FOR [Units]; GO +ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_UnitsYTD] DEFAULT ((0)) FOR [UnitsYTD]; GO +ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_UnitsPriorYear] DEFAULT ((0)) FOR [UnitsPriorYear]; GO +ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_UnitsPriorYTD] DEFAULT ((0)) FOR [UnitsPriorYTD]; GO +ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_AccountID] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO +ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_Dollars] DEFAULT ((0)) FOR [Dollars]; GO +ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_DollarsYTD] DEFAULT ((0)) FOR [DollarsYTD]; GO +ALTER TABLE [fw].[FactGLSampled] ADD CONSTRAINT [DF_FactGLSampled_DollarsPriorYear] DEFAULT ((0)) FOR [DollarsPriorYear]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactPatientBillingLineItemGroupedCache ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactPatientBillingLineItemGroupedCache] ( + [RowID] bigint NOT NULL, + [DepartmentID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [PatientTypeRollupID] tinyint NOT NULL, + [ServiceDateID] int NOT NULL, + [PostDateID] int NOT NULL, + [UnitsOfService] float NULL, + [FiscalYearID] smallint NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE NONCLUSTERED INDEX [CORE_PostDateID_DepartmentID_ChargeCodeID_PatientTypeRollupID_inc] ON [fw].[FactPatientBillingLineItemGroupedCache] ([PostDateID], [DepartmentID], [ChargeCodeID], [PatientTypeRollupID]) INCLUDE ([UnitsOfService]); +CREATE NONCLUSTERED INDEX [CORE_ServiceDateID_DepartmentID_ChargeCodeID_PatientTypeRollupID_inc] ON [fw].[FactPatientBillingLineItemGroupedCache] ([ServiceDateID], [DepartmentID], [ChargeCodeID], [PatientTypeRollupID]) INCLUDE ([UnitsOfService]); +GO +ALTER TABLE [fw].[FactPatientBillingLineItemGroupedCache] ADD CONSTRAINT [DF__FactPatie__Fisca__6D4E869C] DEFAULT ((0)) FOR [FiscalYearID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactPayrollSampledDaily ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactPayrollSampledDaily] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayPeriodID] smallint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [DateID] int NOT NULL, + [Hours] decimal NOT NULL, + [Dollars] decimal NOT NULL, + [FTEs] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + [IsFlexed] bit NOT NULL, + [PayCodeGroupID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE NONCLUSTERED INDEX [IDX_FactPayrollSampledDaily] ON [fw].[FactPayrollSampledDaily] ([DepartmentID], [JobCodeID], [PayCodeGroupID], [PayPeriodID], [DateID], [TimeClassID]) INCLUDE ([Dollars], [FTEs], [Hours]); +CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactPayrollSampledDaily] ([IsDeleted]); +GO +ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_JobCodeID] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_PayPeriodID] DEFAULT ((0)) FOR [PayPeriodID]; GO +ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_DateID] DEFAULT ((0)) FOR [DateID]; GO +ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_Hours] DEFAULT ((0)) FOR [Hours]; GO +ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_Dollars] DEFAULT ((0)) FOR [Dollars]; GO +ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_FTEs] DEFAULT ((0)) FOR [FTEs]; GO +ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_TransactionID] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_IsFlexed] DEFAULT ((0)) FOR [IsFlexed]; GO +ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_PayCodeGroupID] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fw].[FactPayrollSampledDaily] ADD CONSTRAINT [DF_FactPayrollSampledDaily_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactPayrollSampledDailyDetailed ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactPayrollSampledDailyDetailed] ( + [RowID] bigint NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeID] smallint NOT NULL, + [PayCodeGroupID] int NOT NULL, + [PayPeriodID] smallint NOT NULL, + [DateID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Dollars] decimal NOT NULL, + [FTEs] decimal NOT NULL, + [Hours] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [EmployeeID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactPayrollSampledDailyDetailed] ([IsDeleted]); +CREATE NONCLUSTERED INDEX [IDX_FactPayrollSampledDailyDetailed] ON [fw].[FactPayrollSampledDailyDetailed] ([DepartmentID], [JobCodeID], [PayCodeID], [PayCodeGroupID], [EmployeeID], [DateID], [TimeClassID]); +GO +ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__Depar__052B3BFA] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__JobCo__061F6033] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__PayCo__0713846C] DEFAULT ((0)) FOR [PayCodeID]; GO +ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__PayCo__0807A8A5] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__PayPe__08FBCCDE] DEFAULT ((0)) FOR [PayPeriodID]; GO +ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__DateI__09EFF117] DEFAULT ((0)) FOR [DateID]; GO +ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__TimeC__0AE41550] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__Dolla__0BD83989] DEFAULT ((0)) FOR [Dollars]; GO +ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayrol__FTEs__0CCC5DC2] DEFAULT ((0)) FOR [FTEs]; GO +ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__Hours__0DC081FB] DEFAULT ((0)) FOR [Hours]; GO +ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__IsDel__0EB4A634] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__Trans__109CEEA6] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__Emplo__119112DF] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fw].[FactPayrollSampledDailyDetailed] ADD CONSTRAINT [DF__FactPayro__Histo__0FA8CA6D] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactPayrollSampledMonthly ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactPayrollSampledMonthly] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeID] smallint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Hours] decimal NOT NULL, + [HoursYTD] decimal NOT NULL, + [HoursPriorYear] decimal NOT NULL, + [HoursPriorYTD] decimal NOT NULL, + [Dollars] decimal NOT NULL, + [DollarsYTD] decimal NOT NULL, + [DollarsPriorYear] decimal NOT NULL, + [DollarsPriorYTD] decimal NOT NULL, + [FTEs] decimal NOT NULL, + [FTEsYTD] decimal NOT NULL, + [FTEsPriorYear] decimal NOT NULL, + [FTEsPriorYTD] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + [PayCodeGroupID] int NOT NULL, + [IsSystemGenerated] bit NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_FactPayrollSampledMonthly] ON [fw].[FactPayrollSampledMonthly] ([DepartmentID], [JobCodeID], [PayCodeID], [FiscalYearID], [FiscalMonthID], [TimeClassID]); +CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactPayrollSampledMonthly] ([IsDeleted]); +GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF__FW_FactPayrollSampledMonthly_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_FTEs] DEFAULT ((0)) FOR [FTEs]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_FTEsYTD] DEFAULT ((0)) FOR [FTEsYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_FTEsPriorYear] DEFAULT ((0)) FOR [FTEsPriorYear]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_FTEsPriorYTD] DEFAULT ((0)) FOR [FTEsPriorYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF__FactPayrollSampledMonthly__IsDel__772804EC] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_Hours] DEFAULT ((0)) FOR [Hours]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_HoursYTD] DEFAULT ((0)) FOR [HoursYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_HoursPriorYear] DEFAULT ((0)) FOR [HoursPriorYear]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_HoursPriorYTD] DEFAULT ((0)) FOR [HoursPriorYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_Dollars] DEFAULT ((0)) FOR [Dollars]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_DollarsYTD] DEFAULT ((0)) FOR [DollarsYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_DollarsPriorYear] DEFAULT ((0)) FOR [DollarsPriorYear]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_DollarsPriorYTD] DEFAULT ((0)) FOR [DollarsPriorYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF__FactPayro__PayCo__23AF9150] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF__FactPayrollSampledMonthly__Histo__781C2925] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_JobCodeID] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_PayCodeID] DEFAULT ((0)) FOR [PayCodeID]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthly] ADD CONSTRAINT [DF_FactPayrollSampledMonthly_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactPayrollSampledMonthlyDetailed ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactPayrollSampledMonthlyDetailed] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeID] smallint NOT NULL, + [PayCodeGroupID] int NOT NULL, + [EmployeeID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Dollars] decimal NOT NULL, + [DollarsYTD] decimal NOT NULL, + [DollarsPriorYear] decimal NOT NULL, + [DollarsPriorYTD] decimal NOT NULL, + [Hours] decimal NOT NULL, + [HoursYTD] decimal NOT NULL, + [HoursPriorYear] decimal NOT NULL, + [HoursPriorYTD] decimal NOT NULL, + [FTEs] decimal NOT NULL, + [FTEsYTD] decimal NOT NULL, + [FTEsPriorYear] decimal NOT NULL, + [FTEsPriorYTD] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [IsSystemGenerated] bit NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [fw].[FactPayrollSampledMonthlyDetailed] ([IsDeleted], [DepartmentID], [TimeClassID], [FiscalYearID], [FiscalMonthID], [JobCodeID], [PayCodeGroupID], [PayCodeID], [EmployeeID], [RowID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [fw].[FactPayrollSampledMonthlyDetailed] ([IsDeleted], [DepartmentID], [TimeClassID], [FiscalYearID], [FiscalMonthID], [JobCodeID], [PayCodeGroupID], [PayCodeID], [EmployeeID], [RowID]); +GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__FTEsP__00072DB7] DEFAULT ((0)) FOR [FTEsPriorYear]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__FTEsP__00FB51F0] DEFAULT ((0)) FOR [FTEsPriorYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__IsDel__01EF7629] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Trans__03D7BE9B] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF_FactPayrollSampledMonthlyDetailed_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Histo__02E39A62] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Fisca__74957B0B] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Fisca__75899F44] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Dolla__767DC37D] DEFAULT ((0)) FOR [Dollars]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Dolla__7771E7B6] DEFAULT ((0)) FOR [DollarsYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Dolla__78660BEF] DEFAULT ((0)) FOR [DollarsPriorYear]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Dolla__795A3028] DEFAULT ((0)) FOR [DollarsPriorYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF_FactPayrollSampledMonthlyDetailed_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Hours__7A4E5461] DEFAULT ((0)) FOR [Hours]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF_FactPayrollSampledMonthlyDetailed_JobCodeID] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Hours__7B42789A] DEFAULT ((0)) FOR [HoursYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF_FactPayrollSampledMonthlyDetailed_PayCodeID] DEFAULT ((0)) FOR [PayCodeID]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Hours__7C369CD3] DEFAULT ((0)) FOR [HoursPriorYear]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF_FactPayrollSampledMonthlyDetailed_PayCodeGroupID] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__Hours__7D2AC10C] DEFAULT ((0)) FOR [HoursPriorYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF_FactPayrollSampledMonthlyDetailed_EmployeeID] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayrol__FTEs__7E1EE545] DEFAULT ((0)) FOR [FTEs]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF_FactPayrollSampledMonthlyDetailed_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fw].[FactPayrollSampledMonthlyDetailed] ADD CONSTRAINT [DF__FactPayro__FTEsY__7F13097E] DEFAULT ((0)) FOR [FTEsYTD]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactPayrollSampledPayPeriod ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactPayrollSampledPayPeriod] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayPeriodID] smallint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Hours] decimal NOT NULL, + [HoursYTD] decimal NOT NULL, + [HoursPriorYear] decimal NOT NULL, + [HoursPriorYTD] decimal NOT NULL, + [Dollars] decimal NOT NULL, + [DollarsYTD] decimal NOT NULL, + [DollarsPriorYear] decimal NOT NULL, + [DollarsPriorYTD] decimal NOT NULL, + [FTEs] decimal NOT NULL, + [FTEsYTD] decimal NOT NULL, + [FTEsPriorYear] decimal NOT NULL, + [FTEsPriorYTD] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + [IsFlexed] bit NOT NULL, + [PayCodeGroupID] int NOT NULL, + [IsSystemGenerated] bit NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE NONCLUSTERED INDEX [IDX_FactPayrollSampledPayPeriod] ON [fw].[FactPayrollSampledPayPeriod] ([DepartmentID], [JobCodeID], [PayCodeGroupID], [PayPeriodID], [TimeClassID]) INCLUDE ([Dollars], [DollarsPriorYear], [DollarsPriorYTD], [DollarsYTD], [FTEs], [FTEsPriorYear], [FTEsPriorYTD], [FTEsYTD], [Hours], [HoursPriorYear], [HoursPriorYTD], [HoursYTD]); +CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactPayrollSampledPayPeriod] ([IsDeleted]); +GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF__FW_FactPayrollSampledPayPeriod_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_JobCodeID] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_PayPeriodID] DEFAULT ((0)) FOR [PayPeriodID]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF__FactPayro__IsFle__1508738B] DEFAULT ((0)) FOR [IsFlexed]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_FTEs] DEFAULT ((0)) FOR [FTEs]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_FTEsYTD] DEFAULT ((0)) FOR [FTEsYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_FTEsPriorYear] DEFAULT ((0)) FOR [FTEsPriorYear]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_FTEsPriorYTD] DEFAULT ((0)) FOR [FTEsPriorYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF__FactPayroPP__IsDel__772804EC] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_Dollars] DEFAULT ((0)) FOR [Dollars]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_DollarsYTD] DEFAULT ((0)) FOR [DollarsYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_DollarsPriorYear] DEFAULT ((0)) FOR [DollarsPriorYear]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_DollarsPriorYTD] DEFAULT ((0)) FOR [DollarsPriorYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_Hours] DEFAULT ((0)) FOR [Hours]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_HoursYTD] DEFAULT ((0)) FOR [HoursYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_HoursPriorYear] DEFAULT ((0)) FOR [HoursPriorYear]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_HoursPriorYTD] DEFAULT ((0)) FOR [HoursPriorYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF__FactPayro__PayCo__3875A40C] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriod_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriod] ADD CONSTRAINT [DF__FactPayroPP__Histo__781C2925] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactPayrollSampledPayPeriodDetailed ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeID] smallint NOT NULL, + [PayCodeGroupID] int NOT NULL, + [PayPeriodID] smallint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Dollars] decimal NOT NULL, + [DollarsPriorYear] decimal NOT NULL, + [DollarsPriorYTD] decimal NOT NULL, + [DollarsYTD] decimal NOT NULL, + [FTEs] decimal NOT NULL, + [FTEsPriorYear] decimal NOT NULL, + [FTEsPriorYTD] decimal NOT NULL, + [FTEsYTD] decimal NOT NULL, + [Hours] decimal NOT NULL, + [HoursPriorYear] decimal NOT NULL, + [HoursPriorYTD] decimal NOT NULL, + [HoursYTD] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [EmployeeID] int NOT NULL, + [IsSystemGenerated] bit NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [NCNU_BASE] ON [fw].[FactPayrollSampledPayPeriodDetailed] ([PayPeriodID]); +CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactPayrollSampledPayPeriodDetailed] ([IsDeleted]); +CREATE NONCLUSTERED INDEX [IDX_FactPayrollSampledPayPeriodDetailed] ON [fw].[FactPayrollSampledPayPeriodDetailed] ([DepartmentID], [JobCodeID], [PayCodeID], [PayCodeGroupID], [EmployeeID], [PayPeriodID], [TimeClassID]) INCLUDE ([Hours]); +GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Dolla__3E2E7D62] DEFAULT ((0)) FOR [DollarsYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayrol__FTEs__3F22A19B] DEFAULT ((0)) FOR [FTEs]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__FTEsP__4016C5D4] DEFAULT ((0)) FOR [FTEsPriorYear]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__FTEsP__410AEA0D] DEFAULT ((0)) FOR [FTEsPriorYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__FTEsY__41FF0E46] DEFAULT ((0)) FOR [FTEsYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Hours__42F3327F] DEFAULT ((0)) FOR [Hours]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Hours__43E756B8] DEFAULT ((0)) FOR [HoursPriorYear]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Hours__44DB7AF1] DEFAULT ((0)) FOR [HoursPriorYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Hours__45CF9F2A] DEFAULT ((0)) FOR [HoursYTD]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__IsDel__46C3C363] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Trans__48AC0BD5] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriodDetailed_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Histo__47B7E79C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Emplo__5ACABC10] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriodDetailed_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriodDetailed_JobCodeID] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriodDetailed_PayCodeID] DEFAULT ((0)) FOR [PayCodeID]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriodDetailed_PayCodeGroupID] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriodDetailed_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF_FactPayrollSampledPayPeriodDetailed_PayPeriodID] DEFAULT ((0)) FOR [PayPeriodID]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Dolla__3B5210B7] DEFAULT ((0)) FOR [Dollars]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Dolla__3C4634F0] DEFAULT ((0)) FOR [DollarsPriorYear]; GO +ALTER TABLE [fw].[FactPayrollSampledPayPeriodDetailed] ADD CONSTRAINT [DF__FactPayro__Dolla__3D3A5929] DEFAULT ((0)) FOR [DollarsPriorYTD]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactProviderSampledMonthly ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactProviderSampledMonthly] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ProviderID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [OBForecastDetailID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Amount] decimal NOT NULL, + [AmountYTD] decimal NOT NULL, + [AmountPriorYear] decimal NOT NULL, + [AmountPriorYTD] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + [IsSystemGenerated] bit NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_FactProviderSampledMonthly] ON [fw].[FactProviderSampledMonthly] ([DepartmentID], [ProviderID], [OBForecastDetailID], [FiscalMonthID], [FiscalYearID], [TimeClassID]); +GO +ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_ProviderID] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_OBForecastDetailID] DEFAULT ((0)) FOR [OBForecastDetailID]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Amount] DEFAULT ((0)) FOR [Amount]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_AmountYTD] DEFAULT ((0)) FOR [AmountYTD]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_AmountPriorYear] DEFAULT ((0)) FOR [AmountPriorYear]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_AmountPriorYTD] DEFAULT ((0)) FOR [AmountPriorYTD]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_TransactionID] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly] ADD CONSTRAINT [DF_FactProviderSampledMonthly_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactProviderSampledMonthly_Pivoted ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactProviderSampledMonthly_Pivoted] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ProviderID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [OBForecastDetailID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Volume] decimal NOT NULL, + [VolumeYTD] decimal NOT NULL, + [VolumePriorYear] decimal NOT NULL, + [VolumePriorYTD] decimal NOT NULL, + [Dollars] decimal NOT NULL, + [DollarsYTD] decimal NOT NULL, + [DollarsPriorYear] decimal NOT NULL, + [DollarsPriorYTD] decimal NOT NULL, + [Hours] decimal NOT NULL, + [HoursYTD] decimal NOT NULL, + [HoursPriorYear] decimal NOT NULL, + [HoursPriorYTD] decimal NOT NULL, + [FTEs] decimal NOT NULL, + [FTEsYTD] decimal NOT NULL, + [FTEsPriorYear] decimal NOT NULL, + [FTEsPriorYTD] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + [IsSystemGenerated] bit NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_FactProviderSampledMonthly_Pivoted] ON [fw].[FactProviderSampledMonthly_Pivoted] ([DepartmentID], [ProviderID], [OBForecastDetailID], [FiscalMonthID], [FiscalYearID], [TimeClassID]); +GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_TransactionID] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_ProviderID] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_OBForecastDetailID] DEFAULT ((0)) FOR [OBForecastDetailID]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_Volume] DEFAULT ((0)) FOR [Volume]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_VolumeYTD] DEFAULT ((0)) FOR [VolumeYTD]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_VolumePriorYear] DEFAULT ((0)) FOR [VolumePriorYear]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_VolumePriorYTD] DEFAULT ((0)) FOR [VolumePriorYTD]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_Dollars] DEFAULT ((0)) FOR [Dollars]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_DollarsYTD] DEFAULT ((0)) FOR [DollarsYTD]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_DollarsPriorYear] DEFAULT ((0)) FOR [DollarsPriorYear]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_DollarsPriorYTD] DEFAULT ((0)) FOR [DollarsPriorYTD]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_Hours] DEFAULT ((0)) FOR [Hours]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_HoursYTD] DEFAULT ((0)) FOR [HoursYTD]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_HoursPriorYear] DEFAULT ((0)) FOR [HoursPriorYear]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_HoursPriorYTD] DEFAULT ((0)) FOR [HoursPriorYTD]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_FTEs] DEFAULT ((0)) FOR [FTEs]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_FTEsYTD] DEFAULT ((0)) FOR [FTEsYTD]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_FTEsPriorYear] DEFAULT ((0)) FOR [FTEsPriorYear]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_FTEsPriorYTD] DEFAULT ((0)) FOR [FTEsPriorYTD]; GO +ALTER TABLE [fw].[FactProviderSampledMonthly_Pivoted] ADD CONSTRAINT [DF_FactProviderSampledMonthly_Pivoted_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactReportException ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactReportException] ( + [RowID] int NOT NULL, + [ReportName] nvarchar(100) NOT NULL, + [ExceptionCount] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fw].[FactReportException] ADD CONSTRAINT [DF_FactReportException_ReportName] DEFAULT ('') FOR [ReportName]; GO +ALTER TABLE [fw].[FactReportException] ADD CONSTRAINT [DF_FactReportException_ExceptionCount] DEFAULT ((0)) FOR [ExceptionCount]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactRoleAssignmentImport ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactRoleAssignmentImport] ( + [RowID] int NOT NULL, + [PlanName] nvarchar(100) NOT NULL, + [RoleName] nvarchar(100) NOT NULL, + [UserNameCSV] nvarchar(max) NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fw].[FactRoleAssignmentImport] ADD CONSTRAINT [DF_RoleAssignmentImport_PlanName] DEFAULT ('') FOR [PlanName]; GO +ALTER TABLE [fw].[FactRoleAssignmentImport] ADD CONSTRAINT [DF_RoleAssignmentImport_RoleName] DEFAULT ('') FOR [RoleName]; GO +ALTER TABLE [fw].[FactRoleAssignmentImport] ADD CONSTRAINT [DF_RoleAssignmentImport_UserNameCSV] DEFAULT ('') FOR [UserNameCSV]; GO +ALTER TABLE [fw].[FactRoleAssignmentImport] ADD CONSTRAINT [DF_RoleAssignmentImport_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactRoleAssignmentImport] ADD CONSTRAINT [DF_RoleAssignmentImport_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactStagedDSModelingServiceLineRevenue ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ( + [RowID] int NOT NULL, + [EntityID] int NOT NULL, + [FiscalYearID] int NOT NULL, + [FiscalMonthID] int NOT NULL, + [TimeClassID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [SPAccountRollupID] int NOT NULL, + [OBForecastDetailID] int NOT NULL, + [UnitTypeID] int NOT NULL, + [Amount] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + [ServiceLineID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [PatientClassID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__Servi__0B0ECC0F] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__AgeCo__0C02F048] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__Patie__0CF71481] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__Medic__0DEB38BA] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__Entit__49AB1D06] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__Fisca__4B936578] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__Fisca__4C8789B1] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__TimeC__4D7BADEA] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__Payor__4E6FD223] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__Payor__4F63F65C] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__SPAcc__50581A95] DEFAULT ((0)) FOR [SPAccountRollupID]; GO +ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__OBFor__514C3ECE] DEFAULT ((0)) FOR [OBForecastDetailID]; GO +ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__UnitT__52406307] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__IsDel__53348740] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__Histo__5428AB79] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[FactStagedDSModelingServiceLineRevenue] ADD CONSTRAINT [DF__FactStage__Trans__551CCFB2] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactStatisticDriverDepartmentSampledDaily ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] ( + [RowID] bigint NOT NULL, + [DepartmentID] int NOT NULL, + [DriverDepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [PayPeriodID] smallint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [DateID] int NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [Units] decimal NOT NULL, + [TransactionID] int NULL, + PRIMARY KEY ([RowID]) +); + +CREATE NONCLUSTERED INDEX [CORE_DepartmentID_AccountID_inc] ON [fw].[FactStatisticDriverDepartmentSampledDaily] ([DepartmentID], [AccountID]) INCLUDE ([IsDeleted]); +CREATE NONCLUSTERED INDEX [CORE_DepartmentID_AccountID_IsDeleted_inc] ON [fw].[FactStatisticDriverDepartmentSampledDaily] ([DepartmentID], [AccountID], [IsDeleted]) INCLUDE ([PayPeriodID], [TimeClassID], [DateID], [Units]); +GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledDaily_DateID] DEFAULT ((0)) FOR [DateID]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledDaily_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledDaily_DriverDepartmentID] DEFAULT ((0)) FOR [DriverDepartmentID]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledDaily_AccountID] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledDaily_PayPeriodID] DEFAULT ((0)) FOR [PayPeriodID]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledDaily_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledDaily_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledDaily_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledDaily_Units] DEFAULT ((0)) FOR [Units]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledDaily] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledDaily_TransactionID] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactStatisticDriverDepartmentSampledMonthly ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [DriverDepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Amount] decimal NOT NULL, + [AmountYTD] decimal NOT NULL, + [AmountPriorYear] decimal NOT NULL, + [AmountPriorYTD] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampled_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampled_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampled_DriverDepartmentID] DEFAULT ((0)) FOR [DriverDepartmentID]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampled_StatisticID] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampled_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampled_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampled_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledMonthly_Amount] DEFAULT ((0)) FOR [Amount]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledMonthly_AmountYTD] DEFAULT ((0)) FOR [AmountYTD]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledMonthly_AmountPriorYear] DEFAULT ((0)) FOR [AmountPriorYear]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledMonthly_AmountPriorYTD] DEFAULT ((0)) FOR [AmountPriorYTD]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampled_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledMonthly] ADD CONSTRAINT [DF__FW_FactStatisticDriverDepartmentSampledMonthly_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactStatisticDriverDepartmentSampledPayPeriod ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [DriverDepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [PayPeriodID] smallint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [Units] decimal NOT NULL, + [UnitsYTD] decimal NOT NULL, + [UnitsPriorYear] decimal NOT NULL, + [UnitsPriorYTD] decimal NOT NULL, + [TransactionID] int NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledPayPeriod_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDeptSampledPP_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDeptSampledPP_DriverDepartmentID] DEFAULT ((0)) FOR [DriverDepartmentID]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledPayPeriod_AccountID] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDeptSampledPP_PayPeriodID] DEFAULT ((0)) FOR [PayPeriodID]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDeptSampledPP_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDeptSampledPP_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledPayPeriod_Units] DEFAULT ((0)) FOR [Units]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledPayPeriod_UnitsYTD] DEFAULT ((0)) FOR [UnitsYTD]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledPayPeriod_UnitsPriorYear] DEFAULT ((0)) FOR [UnitsPriorYear]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticDriverDepartmentSampledPayPeriod_UnitsPriorYTD] DEFAULT ((0)) FOR [UnitsPriorYTD]; GO +ALTER TABLE [fw].[FactStatisticDriverDepartmentSampledPayPeriod] ADD CONSTRAINT [DF__FW_FactStatisticDriverDepartmentSampledPayPeriod_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactStatisticPrimarySampledMonthly ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactStatisticPrimarySampledMonthly] ( + [RowID] int NOT NULL, + [AccountID] int NOT NULL, + [DepartmentID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Amount] decimal NOT NULL, + [AmountPriorYear] decimal NOT NULL, + [AmountPriorYTD] decimal NOT NULL, + [AmountYTD] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [IsSystemGenerated] bit NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [fw].[FactStatisticPrimarySampledMonthly] ([AccountID], [DepartmentID], [FiscalMonthID], [FiscalYearID], [TimeClassID], [IsDeleted]); +CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactStatisticPrimarySampledMonthly] ([IsDeleted]); +GO +ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF_FactStatisticPrimarySampledMonthly_AccountID] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF_FactStatisticPrimarySampledMonthly_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF_FactStatisticPrimarySampledMonthly_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO +ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Histo__7B1462B5] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Fisca__74676526] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Fisca__755B895F] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Amoun__764FAD98] DEFAULT ((0)) FOR [Amount]; GO +ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Amoun__7743D1D1] DEFAULT ((0)) FOR [AmountPriorYear]; GO +ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Amoun__7837F60A] DEFAULT ((0)) FOR [AmountPriorYTD]; GO +ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Amoun__792C1A43] DEFAULT ((0)) FOR [AmountYTD]; GO +ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF__FactStati__IsDel__7A203E7C] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Trans__7C0886EE] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[FactStatisticPrimarySampledMonthly] ADD CONSTRAINT [DF_FactStatisticPrimarySampledMonthly_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactStatisticSampledDaily ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactStatisticSampledDaily] ( + [RowID] bigint NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [PayPeriodID] smallint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [DateID] int NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [Units] decimal NOT NULL, + [TransactionID] int NULL, + [BigRowID] bigint NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_FactStatisticSampledDaily] ON [fw].[FactStatisticSampledDaily] ([AccountID], [DepartmentID], [PayPeriodID], [DateID], [TimeClassID]); +GO +ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [FK_FactStatisticSampledDaily_DimAccount] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [FK_FactStatisticSampledDaily_DimDate] FOREIGN KEY ([DateID]) REFERENCES [fw].[DimDate] ([DateID]); GO +ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [FK_FactStatisticSampledDaily_DimDepartment] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [FK_FactStatisticSampledDaily_DimPayPeriod] FOREIGN KEY ([PayPeriodID]) REFERENCES [fw].[DimPayPeriod] ([PayPeriodID]); GO +ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [FK_FactStatisticSampledDaily_DimTimeClass] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [DF_FactStatisticSampledDaily_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [DF_FactStatisticSampledDaily_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [DF_FactStatisticSampledDaily_AccountID] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [DF_FactStatisticSampledDaily_PayPeriodID] DEFAULT ((0)) FOR [PayPeriodID]; GO +ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [DF_FactStatisticSampledDaily_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [DF_FactStatisticSampledDaily_DateID] DEFAULT ((0)) FOR [DateID]; GO +ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [DF_FactStatisticSampledDaily_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [DF_FactStatisticSampledDaily_Units] DEFAULT ((0)) FOR [Units]; GO +ALTER TABLE [fw].[FactStatisticSampledDaily] ADD CONSTRAINT [DF_FactStatisticSampledDaily_TransactionID] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactStatisticSampledMonthly ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactStatisticSampledMonthly] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Amount] decimal NOT NULL, + [AmountYTD] decimal NOT NULL, + [AmountPriorYear] decimal NOT NULL, + [AmountPriorYTD] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + [IsSystemGenerated] bit NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_FactStatisticSampledMonthly] ON [fw].[FactStatisticSampledMonthly] ([AccountID], [DepartmentID], [FiscalYearID], [FiscalMonthID], [TimeClassID]); +CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactStatisticSampledMonthly] ([IsDeleted]); +GO +ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampled_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF__FW_FactStatisticSampledMonthly_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampledMonthly_Amount] DEFAULT ((0)) FOR [Amount]; GO +ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampledMonthly_AmountYTD] DEFAULT ((0)) FOR [AmountYTD]; GO +ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampledMonthly_AmountPriorYear] DEFAULT ((0)) FOR [AmountPriorYear]; GO +ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampledMonthly_AmountPriorYTD] DEFAULT ((0)) FOR [AmountPriorYTD]; GO +ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampledMonthly_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO +ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampled_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampled_StatisticID] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampled_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampled_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampled_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fw].[FactStatisticSampledMonthly] ADD CONSTRAINT [DF_FactStatisticSampled_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactStatisticSampledPayPeriod ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactStatisticSampledPayPeriod] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [PayPeriodID] smallint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [Units] decimal NOT NULL, + [UnitsYTD] decimal NOT NULL, + [UnitsPriorYear] decimal NOT NULL, + [UnitsPriorYTD] decimal NOT NULL, + [TransactionID] int NULL, + [IsSystemGenerated] bit NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_FactStatisticSampledPayPeriod] ON [fw].[FactStatisticSampledPayPeriod] ([AccountID], [DepartmentID], [PayPeriodID], [TimeClassID]); +CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactStatisticSampledPayPeriod] ([IsDeleted]); +GO +ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [FK_FactStatisticSampledPayPeriod_DimAccount] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [FK_FactStatisticSampledPayPeriod_FactStatisticSampledPayPeriod] FOREIGN KEY ([RowID]) REFERENCES [fw].[FactStatisticSampledPayPeriod] ([RowID]); GO +ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [FK_FactStatisticSampledPP_DimPayPeriod] FOREIGN KEY ([PayPeriodID]) REFERENCES [fw].[DimPayPeriod] ([PayPeriodID]); GO +ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [FK_FactStatisticSampledPP_DimTimeClass] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [FK_FactStatisticSampledPP_FactStatisticSampled] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF__FW_FactStatisticSampledPayPeriod_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPayPeriod_Units] DEFAULT ((0)) FOR [Units]; GO +ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPayPeriod_AccountID] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPayPeriod_UnitsYTD] DEFAULT ((0)) FOR [UnitsYTD]; GO +ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPP_PayPeriodID] DEFAULT ((0)) FOR [PayPeriodID]; GO +ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPayPeriod_UnitsPriorYear] DEFAULT ((0)) FOR [UnitsPriorYear]; GO +ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPP_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPayPeriod_UnitsPriorYTD] DEFAULT ((0)) FOR [UnitsPriorYTD]; GO +ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPP_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPayPeriod_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO +ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPP_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactStatisticSampledPayPeriod] ADD CONSTRAINT [DF_FactStatisticSampledPP_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactStatisticSecondarySampledMonthly ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactStatisticSecondarySampledMonthly] ( + [RowID] int NOT NULL, + [AccountID] int NOT NULL, + [DepartmentID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Amount] decimal NOT NULL, + [AmountPriorYear] decimal NOT NULL, + [AmountPriorYTD] decimal NOT NULL, + [AmountYTD] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [IsSystemGenerated] bit NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [fw].[FactStatisticSecondarySampledMonthly] ([AccountID], [DepartmentID], [FiscalMonthID], [FiscalYearID], [TimeClassID], [IsDeleted]); +CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactStatisticSecondarySampledMonthly] ([IsDeleted]); +GO +ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Fisca__02B5847D] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF_FactStatisticSecondarySampledMonthly_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Fisca__03A9A8B6] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF_FactStatisticSecondarySampledMonthly_AccountID] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Amoun__049DCCEF] DEFAULT ((0)) FOR [Amount]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF_FactStatisticSecondarySampledMonthly_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Amoun__0591F128] DEFAULT ((0)) FOR [AmountPriorYear]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Amoun__06861561] DEFAULT ((0)) FOR [AmountPriorYTD]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Amoun__077A399A] DEFAULT ((0)) FOR [AmountYTD]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF__FactStati__IsDel__086E5DD3] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Trans__0A56A645] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF_FactStatisticSecondarySampledMonthly_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledMonthly] ADD CONSTRAINT [DF__FactStati__Histo__0962820C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactStatisticSecondarySampledbyPayPeriod ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ( + [RowID] int NOT NULL, + [AccountID] int NOT NULL, + [DepartmentID] int NOT NULL, + [PayPeriodID] smallint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Units] decimal NOT NULL, + [UnitsPriorYear] decimal NOT NULL, + [UnitsPriorYTD] decimal NOT NULL, + [UnitsYTD] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [IsSystemGenerated] bit NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactStatisticSecondarySampledbyPayPeriod] ([IsDeleted]); +GO +ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF_FactStatisticSecondarySampledbyPayPeriod_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF_FactStatisticSecondarySampledbyPayPeriod_AccountID] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF_FactStatisticSecondarySampledbyPayPeriod_TimeClassID] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF_FactStatisticSecondarySampledbyPayPeriod_PayPeriodID] DEFAULT ((0)) FOR [PayPeriodID]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF_FactStatisticSecondarySampledbyPayPeriod_IsSystemGenerated] DEFAULT ((0)) FOR [IsSystemGenerated]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Units__541DBE81] DEFAULT ((0)) FOR [Units]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Units__5511E2BA] DEFAULT ((0)) FOR [UnitsPriorYear]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Units__560606F3] DEFAULT ((0)) FOR [UnitsPriorYTD]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Units__56FA2B2C] DEFAULT ((0)) FOR [UnitsYTD]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Histo__58E2739E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF__FactStati__IsDel__57EE4F65] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactStatisticSecondarySampledbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Trans__59D697D7] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactSystemGeneratedStatistics ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactSystemGeneratedStatistics] ( + [RowID] bigint NOT NULL, + [DateID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [Value] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fw].[FactSystemGeneratedStatistics] ADD CONSTRAINT [DF_FactSystemGeneratedStatistics_DateID] DEFAULT ((0)) FOR [DateID]; GO +ALTER TABLE [fw].[FactSystemGeneratedStatistics] ADD CONSTRAINT [DF_FactSystemGeneratedStatistics_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactSystemGeneratedStatistics] ADD CONSTRAINT [DF_FactSystemGeneratedStatistics_AccountID] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fw].[FactSystemGeneratedStatistics] ADD CONSTRAINT [DF_FactSystemGeneratedStatistics_Value] DEFAULT ((0)) FOR [Value]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactSystemGeneratedStatisticsMonthly ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactSystemGeneratedStatisticsMonthly] ( + [RowID] bigint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [Value] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fw].[FactSystemGeneratedStatisticsMonthly] ADD CONSTRAINT [DF_FactSystemGeneratedStatisticsMonthly_FiscalYearID] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [fw].[FactSystemGeneratedStatisticsMonthly] ADD CONSTRAINT [DF_FactSystemGeneratedStatisticsMonthly_FiscalMonthID] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [fw].[FactSystemGeneratedStatisticsMonthly] ADD CONSTRAINT [DF_FactSystemGeneratedStatisticsMonthly_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactSystemGeneratedStatisticsMonthly] ADD CONSTRAINT [DF_FactSystemGeneratedStatisticsMonthly_AccountID] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fw].[FactSystemGeneratedStatisticsMonthly] ADD CONSTRAINT [DF_FactSystemGeneratedStatisticsMonthly_Value] DEFAULT ((0)) FOR [Value]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.FactUserDeptXWalk ------------------ +--------------------------------------------- +CREATE TABLE [fw].[FactUserDeptXWalk] ( + [MemberGUID] uniqueidentifier NOT NULL, + [DepartmentID] int NOT NULL, + [Value] int NOT NULL, + [RowID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [IsDeleted] bit NOT NULL, + [UserGUID] uniqueidentifier NOT NULL, + [TransactionID] int NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [fw].[FactUserDeptXWalk] ADD CONSTRAINT [DF__FW_FactUserDeptXWalk_MemberGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MemberGUID]; GO +ALTER TABLE [fw].[FactUserDeptXWalk] ADD CONSTRAINT [DF__FW_FactUserDeptXWalk_Department] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [fw].[FactUserDeptXWalk] ADD CONSTRAINT [DF_FW_FactUserDeptXWalk_Value] DEFAULT ((1)) FOR [Value]; GO +ALTER TABLE [fw].[FactUserDeptXWalk] ADD CONSTRAINT [DF_FW_FactUserDeptXWalk_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [fw].[FactUserDeptXWalk] ADD CONSTRAINT [DF_FW_FactUserDeptXWalk_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [fw].[FactUserDeptXWalk] ADD CONSTRAINT [DF__FW_FactUserDeptXWalk_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [fw].[FactUserDeptXWalk] ADD CONSTRAINT [DF_FW_FactUserDeptXWalk_UserGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [UserGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.MRPRMetricMapping ------------------ +--------------------------------------------- +CREATE TABLE [fw].[MRPRMetricMapping] ( + [MappingID] int NOT NULL, + [PRMetricID] int NOT NULL, + [MRMetricGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([MappingID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [UK_MRPRMetricMapping] ON [fw].[MRPRMetricMapping] ([PRMetricID], [MRMetricGUID]); +GO +ALTER TABLE [fw].[MRPRMetricMapping] ADD CONSTRAINT [FK_MRPRMetricMapping_MetricGUID] FOREIGN KEY ([MRMetricGUID]) REFERENCES [dbo].[CMMetric] ([MetricGUID]); GO +ALTER TABLE [fw].[MRPRMetricMapping] ADD CONSTRAINT [FK_MRPRMetricMapping_PRMetricID] FOREIGN KEY ([PRMetricID]) REFERENCES [pi].[DimMetric] ([MetricID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.MrPrFeaturedMetric ------------------ +--------------------------------------------- +CREATE TABLE [fw].[MrPrFeaturedMetric] ( + [MrPrFeaturedMetricId] int NOT NULL, + [IsPr] bit NOT NULL, + [DisplayOrder] int NOT NULL, + [MetricGUID] uniqueidentifier NOT NULL, + [RollupLevelID] tinyint NOT NULL, + PRIMARY KEY ([MrPrFeaturedMetricId]) +); +GO +ALTER TABLE [fw].[MrPrFeaturedMetric] ADD CONSTRAINT [DF__MrPrFeatu__Rollu__2001F360] DEFAULT ((1)) FOR [RollupLevelID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.PrimaryStatisticsRollupsConfiguration ------------------ +--------------------------------------------- +CREATE TABLE [fw].[PrimaryStatisticsRollupsConfiguration] ( + [MemberGUID] uniqueidentifier NOT NULL, + [RollupLevel] varchar(250) NOT NULL, + [RollupMemberID] int NOT NULL, + [AccountID] int NOT NULL, + [Revenue] bit NOT NULL, + [Staffing] bit NOT NULL, + [NonStaffing] bit NOT NULL, + PRIMARY KEY ([MemberGUID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [AK_PrimaryStatisticsRollupsConfiguration] ON [fw].[PrimaryStatisticsRollupsConfiguration] ([RollupLevel], [RollupMemberID], [AccountID]); +GO +ALTER TABLE [fw].[PrimaryStatisticsRollupsConfiguration] ADD CONSTRAINT [FK_PrimaryStatisticsRollupsConfiguration_Account] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [fw].[PrimaryStatisticsRollupsConfiguration] ADD CONSTRAINT [CK_PrimaryStatisticsRollupsConfiguration_RollupLevel] CHECK ([RollupLevel]='DepartmentRollup6' OR [RollupLevel]='DepartmentRollup5' OR [RollupLevel]='DepartmentRollup4' OR [RollupLevel]='DepartmentRollup3' OR [RollupLevel]='DepartmentRollup2' OR [RollupLevel]='DepartmentRollup1' OR [RollupLevel]='Entity' OR [RollupLevel]='System'); GO +ALTER TABLE [fw].[PrimaryStatisticsRollupsConfiguration] ADD CONSTRAINT [DF__PrimarySt__Membe__3ACCF6A6] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[PrimaryStatisticsRollupsConfiguration] ADD CONSTRAINT [DF__PrimarySt__Rollu__3BC11ADF] DEFAULT ('') FOR [RollupLevel]; GO +ALTER TABLE [fw].[PrimaryStatisticsRollupsConfiguration] ADD CONSTRAINT [DF__PrimarySt__Rollu__3CB53F18] DEFAULT ((0)) FOR [RollupMemberID]; GO +ALTER TABLE [fw].[PrimaryStatisticsRollupsConfiguration] ADD CONSTRAINT [DF__PrimarySt__Accou__3DA96351] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [fw].[PrimaryStatisticsRollupsConfiguration] ADD CONSTRAINT [DF__PrimarySt__Reven__3E9D878A] DEFAULT ((0)) FOR [Revenue]; GO +ALTER TABLE [fw].[PrimaryStatisticsRollupsConfiguration] ADD CONSTRAINT [DF__PrimarySt__Staff__3F91ABC3] DEFAULT ((0)) FOR [Staffing]; GO +ALTER TABLE [fw].[PrimaryStatisticsRollupsConfiguration] ADD CONSTRAINT [DF__PrimarySt__NonSt__4085CFFC] DEFAULT ((0)) FOR [NonStaffing]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.SPHACTROLLUP_StandardCodesBackup ------------------ +--------------------------------------------- +CREATE TABLE [fw].[SPHACTROLLUP_StandardCodesBackup] ( + [Name] nvarchar(max) NOT NULL, + [SPHAccountRollupCode] nvarchar(max) NOT NULL +); +GO +ALTER TABLE [fw].[SPHACTROLLUP_StandardCodesBackup] ADD CONSTRAINT [DF__SPHACTROLL__Name__2FD86876] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[SPHACTROLLUP_StandardCodesBackup] ADD CONSTRAINT [DF__SPHACTROL__SPHAc__30CC8CAF] DEFAULT ('') FOR [SPHAccountRollupCode]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.SPHDEPARTMENTROLLUP_StandardCodesBackup ------------------ +--------------------------------------------- +CREATE TABLE [fw].[SPHDEPARTMENTROLLUP_StandardCodesBackup] ( + [Name] nvarchar(max) NOT NULL, + [SPHDepartmentRollupCode] nvarchar(max) NOT NULL +); +GO +ALTER TABLE [fw].[SPHDEPARTMENTROLLUP_StandardCodesBackup] ADD CONSTRAINT [DF__SPHDEPARTM__Name__39384F0B] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[SPHDEPARTMENTROLLUP_StandardCodesBackup] ADD CONSTRAINT [DF__SPHDEPART__SPHDe__3A2C7344] DEFAULT ('') FOR [SPHDepartmentRollupCode]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.SPHDEPARTMENTTYPE_StandardCodesBackup ------------------ +--------------------------------------------- +CREATE TABLE [fw].[SPHDEPARTMENTTYPE_StandardCodesBackup] ( + [Name] nvarchar(max) NOT NULL, + [SPHDepartmentTypeCode] nvarchar(max) NOT NULL +); +GO +ALTER TABLE [fw].[SPHDEPARTMENTTYPE_StandardCodesBackup] ADD CONSTRAINT [DF__SPHDEPARTM__Name__4A6CFCAE] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[SPHDEPARTMENTTYPE_StandardCodesBackup] ADD CONSTRAINT [DF__SPHDEPART__SPHDe__4B6120E7] DEFAULT ('') FOR [SPHDepartmentTypeCode]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.SPHJOBCODEROLLUP_StandardCodesBackup ------------------ +--------------------------------------------- +CREATE TABLE [fw].[SPHJOBCODEROLLUP_StandardCodesBackup] ( + [Name] nvarchar(max) NOT NULL, + [SPHJobCodeRollupCode] nvarchar(max) NOT NULL +); +GO +ALTER TABLE [fw].[SPHJOBCODEROLLUP_StandardCodesBackup] ADD CONSTRAINT [DF__SPHJOBCODE__Name__337F75B5] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[SPHJOBCODEROLLUP_StandardCodesBackup] ADD CONSTRAINT [DF__SPHJOBCOD__SPHJo__347399EE] DEFAULT ('') FOR [SPHJobCodeRollupCode]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.SPHPAYCODEROLLUP_StandardCodesBackup ------------------ +--------------------------------------------- +CREATE TABLE [fw].[SPHPAYCODEROLLUP_StandardCodesBackup] ( + [Name] nvarchar(max) NOT NULL, + [SPHPayCodeRollupCode] nvarchar(max) NOT NULL +); +GO +ALTER TABLE [fw].[SPHPAYCODEROLLUP_StandardCodesBackup] ADD CONSTRAINT [DF__SPHPAYCODE__Name__70F363A0] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[SPHPAYCODEROLLUP_StandardCodesBackup] ADD CONSTRAINT [DF__SPHPAYCOD__SPHPa__71E787D9] DEFAULT ('') FOR [SPHPayCodeRollupCode]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.SectionSecurityImport ------------------ +--------------------------------------------- +CREATE TABLE [fw].[SectionSecurityImport] ( + [ID] int NOT NULL, + [GroupName] varchar(255) NULL, + [BasicGUID] varchar(255) NULL, + [AdvancedGUID] varchar(255) NULL +); +GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.SystemSetting ------------------ +--------------------------------------------- +CREATE TABLE [fw].[SystemSetting] ( + [SystemSettingID] int NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Description] nvarchar(400) NOT NULL, + [Value] nvarchar(max) NOT NULL, + [IsEditable] bit NOT NULL, + [ColumnType] int NOT NULL, + [DefaultValue] nvarchar(100) NOT NULL, + [IsEncrypted] bit NOT NULL, + [SystemSettingCategoryID] int NOT NULL, + PRIMARY KEY ([SystemSettingID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [AK_Name] ON [fw].[SystemSetting] ([Name]); +GO +ALTER TABLE [fw].[SystemSetting] ADD CONSTRAINT [DF_SYSTEMSETTING_VALUE] DEFAULT ('') FOR [Value]; GO +ALTER TABLE [fw].[SystemSetting] ADD CONSTRAINT [DF__SystemSett__Name__6D80CB2D] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [fw].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__Descr__6E74EF66] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [fw].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__IsEdi__705D37D8] DEFAULT ((0)) FOR [IsEditable]; GO +ALTER TABLE [fw].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__Colum__71515C11] DEFAULT ((0)) FOR [ColumnType]; GO +ALTER TABLE [fw].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__Defau__7245804A] DEFAULT ('') FOR [DefaultValue]; GO +ALTER TABLE [fw].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__IsEnc__7339A483] DEFAULT ('0') FOR [IsEncrypted]; GO +ALTER TABLE [fw].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__Syste__7EAB572F] DEFAULT ((0)) FOR [SystemSettingCategoryID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.SystemSettingCategory ------------------ +--------------------------------------------- +CREATE TABLE [fw].[SystemSettingCategory] ( + [SystemSettingCategoryID] int NOT NULL, + [Name] nvarchar(100) NOT NULL, + PRIMARY KEY ([SystemSettingCategoryID]) +); +GO +ALTER TABLE [fw].[SystemSettingCategory] ADD CONSTRAINT [DF__SystemSett__Name__7DB732F6] DEFAULT ('') FOR [Name]; GO + +--------------------------------------------- + +--------------------------------------------- +-- fw.viewDimAccount_custom ------------------ +--------------------------------------------- +CREATE TABLE [fw].[viewDimAccount_custom] ( + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([MemberGUID]) +); +GO +ALTER TABLE [fw].[viewDimAccount_custom] ADD CONSTRAINT [DF__viewDimAc__Membe__2A065A39] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [fw].[viewDimAccount_custom] ADD CONSTRAINT [DF__viewDimAc__Histo__2AFA7E72] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- +--------------------------------------------- +-- VIEWS +--------------------------------------------- + +-- fw.BudgetReallocationWithDefinedType +/************************************************************ +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-01-17 IP B-16703 Omit archived budget adjustments +*************************************************************/ +CREATE view [fw].[BudgetReallocationWithDefinedType] +as +SELECT distinct +b.BudgetReallocationGUID, +Date, +SourceDepartmentID,SourceAccountID,TargetDepartmentID,TargetAccountID,UnitTypeID,FiscalMonthID,FiscalYearID,SourceJobCodeID,TargetJobCodeID,DataType, +ShouldUpply = case when Change = 0 then 0 else 1 end, +BudgetReallocationType = case + WHEN b.SourceDepartmentID <> 0 + and b.SourceAccountID <> 0 + and b.TargetDepartmentID <> 0 + and b.TargetAccountID <> 0 + and b.GroupGUID = '00000000-0000-0000-0000-000000000000' + THEN 'ReallocateSingle' + WHEN b.SourceDepartmentID <> 0 + and b.SourceAccountID <> 0 + and b.TargetDepartmentID <> 0 + and b.TargetAccountID <> 0 + and b.GroupGUID <> '00000000-0000-0000-0000-000000000000' + THEN 'ReallocateMulti' + WHEN b.SourceDepartmentID <> 0 + and b.SourceAccountID <> 0 + and b.TargetDepartmentID = 0 + and b.TargetAccountID = 0 + and b.GroupGUID = '00000000-0000-0000-0000-000000000000' + THEN 'AdjustMontly' + WHEN b.SourceDepartmentID <> 0 + and b.SourceAccountID <> 0 + and b.TargetDepartmentID = 0 + and b.TargetAccountID = 0 + and b.GroupGUID <> '00000000-0000-0000-0000-000000000000' + THEN 'ManualFile' + END +FROM [mr].[BudgetReallocation] b +INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID +WHERE Archived = 0 +GO + + +--------------------------------------------- + +-- fw.viewABBFlexingReconciliation +CREATE VIEW [fw].[viewABBFlexingReconciliation] + AS + + SELECT + CostingConfigGUID, + FiscalYearID, + FiscalMonthID, + EntityID, + DepartmentID, + ChargeCodeID, + AccountID, + JobCodeID, + PayCodeID, + CostComponentID, + ActualChargeUnits, + ActualChargeUnitsYTD, + ActualVariableDirectCost, + ActualVariableDirectCostYTD, + ActualFixedDirectCost, + ActualFixedDirectCostYTD, + BudgetChargeUnits, + BudgetChargeUnitsYTD, + BudgetVariableDirectCost, + BudgetVariableDirectCostYTD, + BudgetFixedDirectCost, + BudgetFixedDirectCostYTD, + FlexedVariableDirectCost, + FlexedVariableDirectCostYTD + FROM + [fw].[ABBFlexingReconciliation] +GO + + +--------------------------------------------- + +-- fw.viewDepartmentChargeCodeStatisticMapping +CREATE VIEW [fw].[viewDepartmentChargeCodeStatisticMapping] +AS +/* +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-05-04 IP B-19364 MRPR - Set Global Weights for Charge Codes - System Center Page +** 2 2018-06-07 IP TK-58757 Refactored view +************************************************************ +*/ +SELECT * +FROM ( + SELECT M.RowID, M.FiscalYearID, D.DepartmentID, M.ChargeCodeID, M.PatientTypeRollupID, M.AccountID, M.Weight, M.IsReviewed, ROW_NUMBER() OVER ( + PARTITION BY M.FiscalYearID, D.DepartmentID, M.ChargeCodeID, M.PatientTypeRollupID, M.AccountID ORDER BY L.SortOrder DESC + ) AS PriorityOrder + FROM ( + SELECT M.RowID, M.FiscalYearID, M.DepartmentRollupLevelMemberID, M.DepartmentRollupLevelMemberColumnName, M.ChargeCodeID, M.PatientTypeRollupID, M.AccountID, M.Weight, M.IsReviewed + FROM fw.DepartmentChargeCodeStatisticMapping M + WHERE M.DepartmentRollupLevelMemberID != 0 + ) M + INNER JOIN ( + SELECT L.ColumnName, L.SortOrder + FROM viewScoreHierarchyAttributeLinkCore30 L + JOIN ScoreDimension S + ON S.DefaultHierarchyGUID = L.HierarchyGUID + WHERE S.GlobalID = 'Department' + ) L + ON L.ColumnName = M.DepartmentRollupLevelMemberColumnName + JOIN ( + SELECT DepartmentID, DepartmentID AS DepartmentRollupLevelMemberID, DepartmentRollupLevelMemberColumnName = 'DepartmentID' + FROM fw.ViewDimDepartment_Real + + UNION ALL + + SELECT DepartmentID, DepartmentRollup1ID AS DepartmentRollupLevelMemberID, DepartmentRollupLevelMemberColumnName = 'DepartmentRollup1ID' + FROM fw.ViewDimDepartment_Real + + UNION ALL + + SELECT DepartmentID, DepartmentRollup2ID AS DepartmentRollupLevelMemberID, DepartmentRollupLevelMemberColumnName = 'DepartmentRollup2ID' + FROM fw.ViewDimDepartment_Real + + UNION ALL + + SELECT DepartmentID, DepartmentRollup3ID AS DepartmentRollupLevelMemberID, DepartmentRollupLevelMemberColumnName = 'DepartmentRollup3ID' + FROM fw.ViewDimDepartment_Real + + UNION ALL + + SELECT DepartmentID, DepartmentRollup4ID AS DepartmentRollupLevelMemberID, DepartmentRollupLevelMemberColumnName = 'DepartmentRollup4ID' + FROM fw.ViewDimDepartment_Real + + UNION ALL + + SELECT DepartmentID, DepartmentRollup5ID AS DepartmentRollupLevelMemberID, DepartmentRollupLevelMemberColumnName = 'DepartmentRollup5ID' + FROM fw.ViewDimDepartment_Real + + UNION ALL + + SELECT DepartmentID, DepartmentRollup6ID AS DepartmentRollupLevelMemberID, DepartmentRollupLevelMemberColumnName = 'DepartmentRollup6ID' + FROM fw.ViewDimDepartment_Real + + UNION ALL + + SELECT DepartmentID, EntityID AS DepartmentRollupLevelMemberID, DepartmentRollupLevelMemberColumnName = 'EntityID' + FROM fw.ViewDimDepartment_Real + + UNION ALL + + SELECT DepartmentID, SystemID AS DepartmentRollupLevelMemberID, DepartmentRollupLevelMemberColumnName = 'SystemID' + FROM fw.ViewDimDepartment_Real + ) D + ON D.DepartmentRollupLevelMemberID = M.DepartmentRollupLevelMemberID AND M.DepartmentRollupLevelMemberColumnName = D.DepartmentRollupLevelMemberColumnName + ) SUBSELECT +WHERE PriorityOrder = 1 +GO + + +--------------------------------------------- + +-- fw.viewDimAccount +CREATE VIEW [fw].[viewDimAccount] +AS +SELECT + +[AccountID], + COALESCE([Name],'') as [Name], +[AccountCode], +[Description], +[GLRollup], +[IsInverted], +[PatientClassID], +[CAPIsDefined], +[DSSIsDefined], +[DSSCostComponent], +[DSSStatisticDriver], +[DSSAccountRollup1ID], +[DSSAccountRollup2ID], +[DSSAccountRollup3ID], +[MRIsDefined], +[FlexStatistic], +[FlexValue], +[FlexBucketGUID], +[OBIsDefined], +[IsStat], +[IsGlobal], +[IsExpense], +[Variability], +[OBDollarsFinancialReportingID], + COALESCE([OBDollarsFinancialReportingCategory],'') as [OBDollarsFinancialReportingCategory], +[OBUnitsFinancialReportingID], + COALESCE([OBUnitsFinancialReportingCategory],'') as [OBUnitsFinancialReportingCategory], +[OBAccountPHID], +[OBStatModelSectionID], +[OBStatUnitTypeID], +[OBStaffing], +[OBPayorID], +[OBPayorGroupID], +[SPIsDefined], +[PatientTypeRollupID], +[SPAccountRollupID], + COALESCE([SPAccountRollupCategory],'') as [SPAccountRollupCategory], +[SPStatAccountRollup], +[SPPayorGroupID], +[SPPhysicianGroupID], +[SPJobCodeGroupID], +[SPCapitalRollupID], +[SPDebtIssuanceID], +[SPIsPhysicianOverride], +[PatientTypeID], +[Inversion], + COALESCE([PatientClass],'') as [PatientClass], + COALESCE([DSSAccountRollup1Name],'') as [DSSAccountRollup1Name], + COALESCE([DSSAccountRollup1Category],'') as [DSSAccountRollup1Category], + COALESCE([DSSAccountRollup2Name],'') as [DSSAccountRollup2Name], + COALESCE([DSSAccountRollup3Name],'') as [DSSAccountRollup3Name], + COALESCE([OBDollarsFinancialReporting],'') as [OBDollarsFinancialReporting], +[OBDollarsFinancialReportingSortOrder], + COALESCE([OBDollarsFinancialReportingLineName],'') as [OBDollarsFinancialReportingLineName], + COALESCE([OBUnitsFinancialReporting],'') as [OBUnitsFinancialReporting], +[OBUnitsFinancialReportingSortOrder], + COALESCE([OBUnitsFinancialReportingLineName],'') as [OBUnitsFinancialReportingLineName], + COALESCE([OBModelSectionName],'') as [OBModelSectionName], + COALESCE([OBStatModelSectionName],'') as [OBStatModelSectionName], + COALESCE([OBUnitType],'') as [OBUnitType], + COALESCE([OBPayor],'') as [OBPayor], + COALESCE([OBPayorGroup],'') as [OBPayorGroup], + COALESCE([PatientTypeRollupName],'') as [PatientTypeRollupName], + COALESCE([SPAccountRollupName],'') as [SPAccountRollupName], + COALESCE([SPStatAccountRollupName],'') as [SPStatAccountRollupName], + COALESCE([SPPayorGroupName],'') as [SPPayorGroupName], +[SPHAccountRollupID], + COALESCE([SPHAccountRollupName],'') as [SPHAccountRollupName], +[SPHAccountRollupConfidenceScore], + COALESCE([SPPhysicianGroupName],'') as [SPPhysicianGroupName], + COALESCE([SPJobCodeGroupName],'') as [SPJobCodeGroupName], + COALESCE([SPCapitalRollupName],'') as [SPCapitalRollupName], + COALESCE([SPDebtIssuanceName],'') as [SPDebtIssuanceName], +[MemberGUID], +[HistoryItemGUID], +[DSSAccountRollup4ID], +[DSSAccountRollup5ID], +[DSSAccountRollup6ID], +[DSSAccountRollup7ID], + COALESCE([DSSAccountRollup4],'') as [DSSAccountRollup4], + COALESCE([DSSAccountRollup4Name],'') as [DSSAccountRollup4Name], + COALESCE([DSSAccountRollup2Category],'') as [DSSAccountRollup2Category], + COALESCE([DSSAccountRollup5Name],'') as [DSSAccountRollup5Name], + COALESCE([DSSAccountRollup6Name],'') as [DSSAccountRollup6Name], + COALESCE([DSSAccountRollup7Name],'') as [DSSAccountRollup7Name], + COALESCE([DSSAccountRollup3Category],'') as [DSSAccountRollup3Category], + COALESCE([DSSAccountRollup4Category],'') as [DSSAccountRollup4Category], +[FWIsDefined], +[AccountCodeRaw], +[GMAccountRollup1], +[GMAccountRollup2], +[GMAccountRollup3], +[GMAccountRollup4], +[GMAccountRollup5], +[GMAccountRollup6], +[GMAccountRollup7], +[SPHVariability], + COALESCE([SPHCostComponent],'') as [SPHCostComponent], + COALESCE([SPHCostComponentRollup],'') as [SPHCostComponentRollup], +[IsSPHCostModel], + COALESCE([SPHLineItem],'') as [SPHLineItem], + COALESCE([SPHStatement],'') as [SPHStatement], + COALESCE([SPHCategory],'') as [SPHCategory], +[SPHAccountRollupIsValidated], + COALESCE([SPHSection],'') as [SPHSection], +[IsCBP] ,[Version] + +FROM [fw].[DimAccount] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimAccount_source +CREATE VIEW [fw].[viewDimAccount_source] +AS +SELECT + grp5D92C559C8004C18BF821C58E1977A6C.[AccountID] + ,grp5D92C559C8004C18BF821C58E1977A6C.[Name] + ,grp5D92C559C8004C18BF821C58E1977A6C.[PatientTypeID] + ,grp5D92C559C8004C18BF821C58E1977A6C.[Inversion] + ,grp5D92C559C8004C18BF821C58E1977A6C.[SPHAccountRollupID] + ,grp5D92C559C8004C18BF821C58E1977A6C.[MemberGUID] + ,grp5D92C559C8004C18BF821C58E1977A6C.[HistoryItemGUID] + ,ISNULL([PATIENTCLASS].[Name], 'Not Specified') as [PatientClass] + ,ISNULL([DSSACTROL1].[Name], 'Not Specified') as [DSSAccountRollup1Name] + ,ISNULL([DSSACTROL1].[Category], 'Not Specified') as [DSSAccountRollup1Category] + ,ISNULL([DSSACTROL2].[Name], 'Not Specified') as [DSSAccountRollup2Name] + ,ISNULL([DSSACTROL2].[Category], 'Not Specified') as [DSSAccountRollup2Category] + ,ISNULL([DSSACTROL3].[Name], 'Not Specified') as [DSSAccountRollup3Name] + ,ISNULL([DSSACTROL3].[Category], 'Not Specified') as [DSSAccountRollup3Category] + ,ISNULL([OBFINANCIALREP].[IsExpense], 0) as [IsExpense] + ,ISNULL([OBFINANCIALREP].[Section], 'Not Specified') as [OBDollarsFinancialReportingCategory] + ,ISNULL([OBFINANCIALREP].[Name], 'Not Specified') as [OBDollarsFinancialReporting] + ,ISNULL([OBFINANCIALREP].[SortOrder], 0) as [OBDollarsFinancialReportingSortOrder] + ,ISNULL([OBFINANCIALREP].[LineName], 'Not Specified') as [OBDollarsFinancialReportingLineName] + ,ISNULL([OBFINANCIALREP_1].[Section], 'Not Specified') as [OBUnitsFinancialReportingCategory] + ,ISNULL([OBFINANCIALREP_1].[Name], 'Not Specified') as [OBUnitsFinancialReporting] + ,ISNULL([OBFINANCIALREP_1].[SortOrder], 0) as [OBUnitsFinancialReportingSortOrder] + ,ISNULL([OBFINANCIALREP_1].[LineName], 'Not Specified') as [OBUnitsFinancialReportingLineName] + ,ISNULL([ACCOUNTPH].[Name], 'Not Specified') as [OBModelSectionName] + ,ISNULL([ACCOUNTPH_1].[Name], 'Not Specified') as [OBStatModelSectionName] + ,ISNULL([UNITTYPE].[Name], 'Not Specified') as [OBUnitType] + ,ISNULL([PAYOR].[Name], 'Not Specified') as [OBPayor] + ,ISNULL([PayorGroup].[Name], 'Not Specified') as [OBPayorGroup] + ,ISNULL([PayorGroup_1].[Name], 'Not Specified') as [SPPayorGroupName] + ,ISNULL([PatientTyRo].[Name], 'Not Specified') as [PatientTypeRollupName] + ,ISNULL([SPAccountRollup].[Category], 'Not Specified') as [SPAccountRollupCategory] + ,ISNULL([SPAccountRollup].[Name], 'Not Specified') as [SPAccountRollupName] + ,ISNULL([SPAccountRollup_1].[Name], 'Not Specified') as [SPStatAccountRollupName] + ,ISNULL([PhyGrp].[Name], 'Not Specified') as [SPPhysicianGroupName] + ,ISNULL([JobCodeGrp].[Name], 'Not Specified') as [SPJobCodeGroupName] + ,ISNULL([SPCAPITALROLLUP].[Name], 'Not Specified') as [SPCapitalRollupName] + ,ISNULL([SPDEBTISSUANCE].[Name], 'Not Specified') as [SPDebtIssuanceName] + ,ISNULL([SPHACTROLLUP].[Name], 'Not Specified') as [SPHAccountRollupName] + ,ISNULL([SPHACTROLLUP].[SPHCostComponent], 'Not Specified') as [SPHCostComponent] + ,ISNULL([SPHACTROLLUP].[SPHCostComponentRollup], 'Not Specified') as [SPHCostComponentRollup] + ,ISNULL([SPHACTROLLUP].[LineItem], 'Not Specified') as [SPHLineItem] + ,ISNULL([SPHACTROLLUP].[Statement], 'Not Specified') as [SPHStatement] + ,ISNULL([SPHACTROLLUP].[Category], 'Not Specified') as [SPHCategory] + ,ISNULL([SPHACTROLLUP].[Section], 'Not Specified') as [SPHSection] + ,ISNULL([DSSACCTROLL4].[Name], 'Not Specified') as [DSSAccountRollup4] + ,ISNULL([DSSACCTROLL4].[Name], 'Not Specified') as [DSSAccountRollup4Name] + ,ISNULL([DSSACCTROLL4].[Category], 'Not Specified') as [DSSAccountRollup4Category] + ,ISNULL([DSSACCOUNTROLLUP5].[Name], 'Not Specified') as [DSSAccountRollup5Name] + ,ISNULL([DSSACCOUNTROLLUP6].[Name], 'Not Specified') as [DSSAccountRollup6Name] + ,ISNULL([DSSACCOUNTROLLUP7].[Name], 'Not Specified') as [DSSAccountRollup7Name] +, [grp5D92C559C8004C18BF821C58E1977A6C].[Version]FROM [fw].[DimAccount] grp5D92C559C8004C18BF821C58E1977A6C (readuncommitted) + LEFT JOIN [fw].[viewDimPatientClass] [PATIENTCLASS] on [PATIENTCLASS].[PatientClassID] = [grp5D92C559C8004C18BF821C58E1977A6C].[PatientClassID] + LEFT JOIN [dss].[viewDimAccountRollup1] [DSSACTROL1] on [DSSACTROL1].[DSSAccountRollup1ID] = [grp5D92C559C8004C18BF821C58E1977A6C].[DSSAccountRollup1ID] + LEFT JOIN [dss].[viewDimAccountRollup2] [DSSACTROL2] on [DSSACTROL2].[DSSAccountRollup2ID] = [grp5D92C559C8004C18BF821C58E1977A6C].[DSSAccountRollup2ID] + LEFT JOIN [dss].[viewDimAccountRollup3] [DSSACTROL3] on [DSSACTROL3].[DSSAccountRollup3ID] = [grp5D92C559C8004C18BF821C58E1977A6C].[DSSAccountRollup3ID] + LEFT JOIN [ob].[viewDimFinancialReporting] [OBFINANCIALREP] on [OBFINANCIALREP].[FinancialReportingID] = [grp5D92C559C8004C18BF821C58E1977A6C].[OBDollarsFinancialReportingID] + LEFT JOIN [ob].[viewDimFinancialReporting] [OBFINANCIALREP_1] on [OBFINANCIALREP_1].[FinancialReportingID] = [grp5D92C559C8004C18BF821C58E1977A6C].[OBUnitsFinancialReportingID] + LEFT JOIN [ob].[viewDimAccountPH] [ACCOUNTPH] on [ACCOUNTPH].[AccountPHID] = [grp5D92C559C8004C18BF821C58E1977A6C].[OBAccountPHID] + INNER JOIN [ob].[viewDimAccountPH] [ACCOUNTPH_1] on [ACCOUNTPH_1].[AccountPHID] = [grp5D92C559C8004C18BF821C58E1977A6C].[OBStatModelSectionID] + LEFT JOIN [fw].[viewDimUnitType] [UNITTYPE] on [UNITTYPE].[UnitTypeID] = [grp5D92C559C8004C18BF821C58E1977A6C].[OBStatUnitTypeID] + LEFT JOIN [fw].[viewDimPayor] [PAYOR] on [PAYOR].[PayorID] = [grp5D92C559C8004C18BF821C58E1977A6C].[OBPayorID] + LEFT JOIN [fw].[viewDimPayorGroup] [PayorGroup] on [PayorGroup].[PayorGroupID] = [grp5D92C559C8004C18BF821C58E1977A6C].[OBPayorGroupID] + LEFT JOIN [fw].[viewDimPayorGroup] [PayorGroup_1] on [PayorGroup_1].[PayorGroupID] = [grp5D92C559C8004C18BF821C58E1977A6C].[SPPayorGroupID] + LEFT JOIN [fw].[viewDimPatientTypeRollup] [PatientTyRo] on [PatientTyRo].[PatientTypeRollupID] = [grp5D92C559C8004C18BF821C58E1977A6C].[PatientTypeRollupID] + LEFT JOIN [sp].[viewDimAccountRollup] [SPAccountRollup] on [SPAccountRollup].[AccountRollupID] = [grp5D92C559C8004C18BF821C58E1977A6C].[SPAccountRollupID] + LEFT JOIN [sp].[viewDimAccountRollup] [SPAccountRollup_1] on [SPAccountRollup_1].[AccountRollupID] = [grp5D92C559C8004C18BF821C58E1977A6C].[SPStatAccountRollup] + LEFT JOIN [fw].[viewDimPhysicianGroup] [PhyGrp] on [PhyGrp].[PhysicianGroupID] = [grp5D92C559C8004C18BF821C58E1977A6C].[SPPhysicianGroupID] + LEFT JOIN [fw].[viewDimJobCodeGroup] [JobCodeGrp] on [JobCodeGrp].[JobCodeGroupID] = [grp5D92C559C8004C18BF821C58E1977A6C].[SPJobCodeGroupID] + LEFT JOIN [sp].[viewDimSPCapitalRollup] [SPCAPITALROLLUP] on [SPCAPITALROLLUP].[SPCapitalRollupID] = [grp5D92C559C8004C18BF821C58E1977A6C].[SPCapitalRollupID] + LEFT JOIN [sp].[viewDimSPDebtIssuance] [SPDEBTISSUANCE] on [SPDEBTISSUANCE].[SPDebtIssuanceID] = [grp5D92C559C8004C18BF821C58E1977A6C].[SPDebtIssuanceID] + LEFT JOIN [fw].[viewDimSPHAccountRollup] [SPHACTROLLUP] on [SPHACTROLLUP].[SPHAccountRollupID] = [grp5D92C559C8004C18BF821C58E1977A6C].[SPHAccountRollupID] + LEFT JOIN [dss].[viewDimAccountRollup4] [DSSACCTROLL4] on [DSSACCTROLL4].[DSSAccountRollup4ID] = [grp5D92C559C8004C18BF821C58E1977A6C].[DSSAccountRollup4ID] + INNER JOIN [dss].[viewDimAccountRollup5] [DSSACCOUNTROLLUP5] on [DSSACCOUNTROLLUP5].[DSSAccountRollup5ID] = [grp5D92C559C8004C18BF821C58E1977A6C].[DSSAccountRollup5ID] + LEFT JOIN [dss].[viewDimAccountRollup6] [DSSACCOUNTROLLUP6] on [DSSACCOUNTROLLUP6].[DSSAccountRollup6ID] = [grp5D92C559C8004C18BF821C58E1977A6C].[DSSAccountRollup6ID] + LEFT JOIN [dss].[viewDimAccountRollup7] [DSSACCOUNTROLLUP7] on [DSSACCOUNTROLLUP7].[DSSAccountRollup7ID] = [grp5D92C559C8004C18BF821C58E1977A6C].[DSSAccountRollup7ID] +GO + + +--------------------------------------------- + +-- fw.viewDimAgeCohort +--Last Modified 10/17/2016 11:21 PM +CREATE VIEW [fw].[viewDimAgeCohort] +AS +SELECT + grpD86C7982BF714099989A70284B99EB36.[AgeCohortID] + ,grpD86C7982BF714099989A70284B99EB36.[Name] + ,grpD86C7982BF714099989A70284B99EB36.[Code] + ,grpD86C7982BF714099989A70284B99EB36.[SortOrder] + ,grpD86C7982BF714099989A70284B99EB36.[TransactionID] + ,grpD86C7982BF714099989A70284B99EB36.[MemberGUID] + ,grpD86C7982BF714099989A70284B99EB36.[HistoryItemGUID] + ,grpD86C7982BF714099989A70284B99EB36.[TimeMin] + ,grpD86C7982BF714099989A70284B99EB36.[TimeMax] + ,grpD86C7982BF714099989A70284B99EB36.[TimeMinUnit] + ,grpD86C7982BF714099989A70284B99EB36.[TimeMaxUnit] +FROM [fw].[DimAgeCohort] grpD86C7982BF714099989A70284B99EB36 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimAssumption_auto +CREATE VIEW [fw].[viewDimAssumption_auto] +AS +SELECT + grp2879736FA04A414EA76857E00A234FC5.[AssumptionID] + ,grp2879736FA04A414EA76857E00A234FC5.[Name] + ,grp2879736FA04A414EA76857E00A234FC5.[Category] + ,grp2879736FA04A414EA76857E00A234FC5.[SubCategory] + ,grp2879736FA04A414EA76857E00A234FC5.[DisplayFormat] + ,grp2879736FA04A414EA76857E00A234FC5.[SPIsPastingValues] + ,grp2879736FA04A414EA76857E00A234FC5.[SPIsProtectingRollingValues] + ,grp2879736FA04A414EA76857E00A234FC5.[MemberGUID] + ,grp2879736FA04A414EA76857E00A234FC5.[HistoryItemGUID] +, [grp2879736FA04A414EA76857E00A234FC5].[Version]FROM [fw].[DimAssumption] grp2879736FA04A414EA76857E00A234FC5 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimCICostLeader +CREATE VIEW [fw].[viewDimCICostLeader] +AS + SELECT + MemberGUID + ,UserName + ,NameFirst + ,NameLast + ,EmailAddress + ,PhoneNumber + ,IsSysAdmin + ,NameFull + ,UserGUID AS [CICostLeaderID] + FROM [fw].[viewDimUsers] + UNION + SELECT + dbo.ZeroGUID() MemberGUID + ,'' UserName + ,'' NameFirst + ,'' NameLast + ,'' EmailAddress + ,'' PhoneNumber + ,'' IsSysAdmin + ,'Not Specified' NameFull + ,dbo.ZeroGUID() AS [CIOwnerID]; +GO + + +--------------------------------------------- + +-- fw.viewDimCICostLeader_auto +--Last Modified 11/9/2018 5:03 PM +CREATE VIEW [fw].[viewDimCICostLeader_auto] +AS +SELECT + grp86039BDA00234558918C494FF9385A1C.[MemberGUID] + ,coalesce(grp86039BDA00234558918C494FF9385A1C.[UserName],'') as [UserName] + ,coalesce(grp86039BDA00234558918C494FF9385A1C.[NameFirst],'') as [NameFirst] + ,coalesce(grp86039BDA00234558918C494FF9385A1C.[NameLast],'') as [NameLast] + ,coalesce(grp86039BDA00234558918C494FF9385A1C.[EmailAddress],'') as [EmailAddress] + ,coalesce(grp86039BDA00234558918C494FF9385A1C.[PhoneNumber],'') as [PhoneNumber] + ,grp86039BDA00234558918C494FF9385A1C.[IsSysAdmin] + ,coalesce(grp86039BDA00234558918C494FF9385A1C.[NameFull],'') as [NameFull] + ,grp86039BDA00234558918C494FF9385A1C.[CICostLeaderID] +FROM [fw].[viewDimCICostLeader] grp86039BDA00234558918C494FF9385A1C +GO + + +--------------------------------------------- + +-- fw.viewDimCIExecutiveSponsor +CREATE VIEW [fw].[viewDimCIExecutiveSponsor] +AS + SELECT + MemberGUID + ,UserName + ,NameFirst + ,NameLast + ,EmailAddress + ,PhoneNumber + ,IsSysAdmin + ,NameFull + ,UserGUID AS [CIExecutiveSponsorID] + FROM [fw].[viewDimUsers] + UNION + SELECT + dbo.ZeroGUID() MemberGUID + ,'' UserName + ,'' NameFirst + ,'' NameLast + ,'' EmailAddress + ,'' PhoneNumber + ,'' IsSysAdmin + ,'Not Specified' NameFull + ,dbo.ZeroGUID() AS [CIOwnerID]; +GO + + +--------------------------------------------- + +-- fw.viewDimCIExecutiveSponsor_auto +--Last Modified 11/9/2018 5:03 PM +CREATE VIEW [fw].[viewDimCIExecutiveSponsor_auto] +AS +SELECT + grpF3B42BDB744145EC920F5404120C877D.[MemberGUID] + ,coalesce(grpF3B42BDB744145EC920F5404120C877D.[UserName],'') as [UserName] + ,coalesce(grpF3B42BDB744145EC920F5404120C877D.[NameFirst],'') as [NameFirst] + ,coalesce(grpF3B42BDB744145EC920F5404120C877D.[NameLast],'') as [NameLast] + ,coalesce(grpF3B42BDB744145EC920F5404120C877D.[EmailAddress],'') as [EmailAddress] + ,coalesce(grpF3B42BDB744145EC920F5404120C877D.[PhoneNumber],'') as [PhoneNumber] + ,grpF3B42BDB744145EC920F5404120C877D.[IsSysAdmin] + ,coalesce(grpF3B42BDB744145EC920F5404120C877D.[NameFull],'') as [NameFull] + ,grpF3B42BDB744145EC920F5404120C877D.[CIExecutiveSponsorID] +FROM [fw].[viewDimCIExecutiveSponsor] grpF3B42BDB744145EC920F5404120C877D +GO + + +--------------------------------------------- + +-- fw.viewDimCIOwner +CREATE VIEW [fw].[viewDimCIOwner] +AS + SELECT + MemberGUID + ,UserName + ,NameFirst + ,NameLast + ,EmailAddress + ,PhoneNumber + ,IsSysAdmin + ,NameFull + ,UserGUID AS [CIOwnerID] + FROM [fw].[viewDimUsers] + UNION + SELECT + dbo.ZeroGUID() MemberGUID + ,'' UserName + ,'' NameFirst + ,'' NameLast + ,'' EmailAddress + ,'' PhoneNumber + ,'' IsSysAdmin + ,'Not Specified' NameFull + ,dbo.ZeroGUID() AS [CIOwnerID]; +GO + + +--------------------------------------------- + +-- fw.viewDimCIOwner_auto +--Last Modified 11/9/2018 5:03 PM +CREATE VIEW [fw].[viewDimCIOwner_auto] +AS +SELECT + grpD4F1A9BB138B4232A3D704B1F74D6CBE.[MemberGUID] + ,coalesce(grpD4F1A9BB138B4232A3D704B1F74D6CBE.[UserName],'') as [UserName] + ,coalesce(grpD4F1A9BB138B4232A3D704B1F74D6CBE.[NameFirst],'') as [NameFirst] + ,coalesce(grpD4F1A9BB138B4232A3D704B1F74D6CBE.[NameLast],'') as [NameLast] + ,coalesce(grpD4F1A9BB138B4232A3D704B1F74D6CBE.[EmailAddress],'') as [EmailAddress] + ,coalesce(grpD4F1A9BB138B4232A3D704B1F74D6CBE.[PhoneNumber],'') as [PhoneNumber] + ,grpD4F1A9BB138B4232A3D704B1F74D6CBE.[IsSysAdmin] + ,coalesce(grpD4F1A9BB138B4232A3D704B1F74D6CBE.[NameFull],'') as [NameFull] + ,grpD4F1A9BB138B4232A3D704B1F74D6CBE.[CIOwnerID] +FROM [fw].[viewDimCIOwner] grpD4F1A9BB138B4232A3D704B1F74D6CBE +GO + + +--------------------------------------------- + +-- fw.viewDimCMBucket +CREATE VIEW [fw].[viewDimCMBucket] +AS +SELECT + grp14E4823F9B7A434C9E5390716DA1E83B.[MemberGUID] + ,grp14E4823F9B7A434C9E5390716DA1E83B.[CategoryGUID] + ,coalesce(grp14E4823F9B7A434C9E5390716DA1E83B.[Name],'') as [Name] + ,coalesce(grp14E4823F9B7A434C9E5390716DA1E83B.[Category],'') as [Category] +FROM [dbo].[viewCMBucket] grp14E4823F9B7A434C9E5390716DA1E83B +GO + + +--------------------------------------------- + +-- fw.viewDimCareSetting +CREATE VIEW [fw].[viewDimCareSetting] +AS +SELECT + grpCB4D1E3F1895456A8FAA1F3225FC314E.[CareSettingID] + ,grpCB4D1E3F1895456A8FAA1F3225FC314E.[Name] + ,grpCB4D1E3F1895456A8FAA1F3225FC314E.[Code] + ,grpCB4D1E3F1895456A8FAA1F3225FC314E.[SortOrder] + ,grpCB4D1E3F1895456A8FAA1F3225FC314E.[IsActive] + ,grpCB4D1E3F1895456A8FAA1F3225FC314E.[TransactionID] + ,grpCB4D1E3F1895456A8FAA1F3225FC314E.[MemberGUID] + ,grpCB4D1E3F1895456A8FAA1F3225FC314E.[HistoryItemGUID] +FROM [fw].[DimCareSetting] grpCB4D1E3F1895456A8FAA1F3225FC314E (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimCareSettingPH +CREATE VIEW [fw].[viewDimCareSettingPH] +AS +SELECT + grpF1AA6AEECFAB4BC783DD4937D6D780BC.[CareSettingPHID] + ,grpF1AA6AEECFAB4BC783DD4937D6D780BC.[Name] + ,grpF1AA6AEECFAB4BC783DD4937D6D780BC.[MemberGUID] + ,grpF1AA6AEECFAB4BC783DD4937D6D780BC.[HistoryItemGUID] + ,grpF1AA6AEECFAB4BC783DD4937D6D780BC.[TransactionID] +FROM [fw].[DimCareSettingPH] grpF1AA6AEECFAB4BC783DD4937D6D780BC (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimChargeCode +CREATE VIEW fw.viewDimChargeCode +AS + SELECT + ChargeCodeID, + ChargeCode, + MemberGUID, + Name, + HistoryItemGUID, + IsDefined + FROM + fw.DimChargeCode +GO + + +--------------------------------------------- + +-- fw.viewDimChargeCodePH +CREATE VIEW [fw].[viewDimChargeCodePH] +AS +SELECT + grp61106722392D44889DEE489AA9F62D29.[ChargeCodePHID] + ,grp61106722392D44889DEE489AA9F62D29.[Name] + ,grp61106722392D44889DEE489AA9F62D29.[MemberGUID] + ,grp61106722392D44889DEE489AA9F62D29.[HistoryItemGUID] +FROM [fw].[DimChargeCodePH] grp61106722392D44889DEE489AA9F62D29 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimChargeCode_auto +--Last Modified 11/16/2020 3:28 PM +CREATE VIEW [fw].[viewDimChargeCode_auto] +AS +SELECT + grp9F8A3E7BEB06485C914C72C4F66C593E.[ChargeCodeID] + ,coalesce(grp9F8A3E7BEB06485C914C72C4F66C593E.[Name],'') as [Name] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[ChargeCode] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[Description] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[IsDefined] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[OBIsDefined] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[IsRVU] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[IsStatDriver] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[ChargeIncrease] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[Category] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[RVUWeight] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[StatType] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[PatientTypeID] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[DSSIsDefined] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[DayTypeID] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[DayType2ID] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[DayType3ID] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[UBRevenueCodeID] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[CPTID] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[IsActivityCost] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[MemberGUID] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[HistoryItemGUID] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[CostDriver] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[Rollup] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[IsPatientSpecific] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[FWIsDefined] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[TimeStampWeight] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[IsTimeStamp] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[TimeStampPrecedent] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[TransactionID] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[IsSPHSupplyCosting] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[IsSPHTDCosting] + ,grp9F8A3E7BEB06485C914C72C4F66C593E.[SPHChargeCodePrefix] + ,ISNULL([PATIENTTYPE].[Name], 'Not Specified') as [PatientTypeName] + ,ISNULL([DimDayType].[Name], 'Not Specified') as [DayType] + ,ISNULL([DAYTYPE2].[Name], 'Not Specified') as [DayType2] + ,ISNULL([DAYTYPE3].[Name], 'Not Specified') as [DayType3] + ,ISNULL([DimUBRevenue].[UBRevenueCode], 'Not Specified') as [UBRevenueCode] + ,ISNULL([DimUBRevenue].[UBRevenueName], 'Not Specified') as [UBRevenueCodeName] + ,ISNULL([DimCPT].[CPTCode], 'Not Specified') as [CPTCode] + ,ISNULL([DimCPT].[CPTName], 'Not Specified') as [CPTName] +, [grp9F8A3E7BEB06485C914C72C4F66C593E].[Version]FROM [fw].[DimChargeCode] grp9F8A3E7BEB06485C914C72C4F66C593E (readuncommitted) + LEFT JOIN [fw].[viewDimPatientType] [PATIENTTYPE] on [PATIENTTYPE].[PatientTypeID] = [grp9F8A3E7BEB06485C914C72C4F66C593E].[PatientTypeID] + LEFT JOIN [fw].[viewDimDayType_auto] [DimDayType] on [DimDayType].[DayTypeID] = [grp9F8A3E7BEB06485C914C72C4F66C593E].[DayTypeID] + LEFT JOIN [fw].[viewDimDayType2_auto] [DAYTYPE2] on [DAYTYPE2].[DayType2ID] = [grp9F8A3E7BEB06485C914C72C4F66C593E].[DayType2ID] + LEFT JOIN [fw].[viewDimDayType3_auto] [DAYTYPE3] on [DAYTYPE3].[DayType3ID] = [grp9F8A3E7BEB06485C914C72C4F66C593E].[DayType3ID] + LEFT JOIN [dss].[viewDimUBRevenueCode_auto] [DimUBRevenue] on [DimUBRevenue].[UBRevenueCodeID] = [grp9F8A3E7BEB06485C914C72C4F66C593E].[UBRevenueCodeID] + LEFT JOIN [dss].[viewDimCPT_auto] [DimCPT] on [DimCPT].[CPTID] = [grp9F8A3E7BEB06485C914C72C4F66C593E].[CPTID] +GO + + +--------------------------------------------- + +-- fw.viewDimColumnHider_auto +CREATE VIEW [fw].[viewDimColumnHider_auto] +AS +SELECT + grpDB3AC50ADCA7400E918D0BF9DAA2A474.[Name] + ,grpDB3AC50ADCA7400E918D0BF9DAA2A474.[ColumnHiderID] + ,grpDB3AC50ADCA7400E918D0BF9DAA2A474.[MemberGUID] +, [grpDB3AC50ADCA7400E918D0BF9DAA2A474].[Version], [grpDB3AC50ADCA7400E918D0BF9DAA2A474].[HistoryItemGUID]FROM [fw].[DimColumnHider] grpDB3AC50ADCA7400E918D0BF9DAA2A474 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimCompAnDepartment +--Last Modified 11/15/2023 3:55 PM +CREATE VIEW [fw].[viewDimCompAnDepartment] +AS +SELECT + grp945F64DE366646BD8ACA55CDD45A8F1C.[CompAnDepartmentID] + ,grp945F64DE366646BD8ACA55CDD45A8F1C.[CompAnDepartmentCode] + ,grp945F64DE366646BD8ACA55CDD45A8F1C.[Description] + ,grp945F64DE366646BD8ACA55CDD45A8F1C.[DescriptionLong] + ,grp945F64DE366646BD8ACA55CDD45A8F1C.[CompAnDepartmentRollup1] + ,grp945F64DE366646BD8ACA55CDD45A8F1C.[CompAnDepartmentRollup2] + ,grp945F64DE366646BD8ACA55CDD45A8F1C.[CompAnDepartmentRollup3] + ,grp945F64DE366646BD8ACA55CDD45A8F1C.[CompAnDepartmentRollup4] + ,grp945F64DE366646BD8ACA55CDD45A8F1C.[CompAnPrimaryStat] + ,grp945F64DE366646BD8ACA55CDD45A8F1C.[SPHDepartmentRollupID] + ,grp945F64DE366646BD8ACA55CDD45A8F1C.[MemberGUID] + ,grp945F64DE366646BD8ACA55CDD45A8F1C.[TransactionID] + ,grp945F64DE366646BD8ACA55CDD45A8F1C.[HistoryItemGUID] + ,ISNULL([SPHDEPARTMENTROLLUP].[Name], 'Not Specified') as [SPHDepartmentRollup] +FROM [fw].[DimCompAnDepartment] grp945F64DE366646BD8ACA55CDD45A8F1C (readuncommitted) + INNER JOIN [fw].[viewDimSPHDepartmentRollup] [SPHDEPARTMENTROLLUP] on [SPHDEPARTMENTROLLUP].[SPHDepartmentRollupID] = [grp945F64DE366646BD8ACA55CDD45A8F1C].[SPHDepartmentRollupID] +GO + + +--------------------------------------------- + +-- fw.viewDimCompAnPeerGroup_auto +--Last Modified 3/20/2024 5:05 PM +CREATE VIEW [fw].[viewDimCompAnPeerGroup_auto] +AS +SELECT + grpE48D7237FE824CCE9822B88C3CAC7AB5.[CompAnPeerGroupID] + ,grpE48D7237FE824CCE9822B88C3CAC7AB5.[Name] + ,grpE48D7237FE824CCE9822B88C3CAC7AB5.[Description] + ,grpE48D7237FE824CCE9822B88C3CAC7AB5.[CompAnPeerGroupCode] + ,grpE48D7237FE824CCE9822B88C3CAC7AB5.[TransactionID] + ,grpE48D7237FE824CCE9822B88C3CAC7AB5.[MemberGUID] + ,grpE48D7237FE824CCE9822B88C3CAC7AB5.[HistoryItemGUID] +FROM [fw].[DimCompAnPeerGroup] grpE48D7237FE824CCE9822B88C3CAC7AB5 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimConsolidatedFinancialReporting +CREATE VIEW [fw].[viewDimConsolidatedFinancialReporting] +AS +SELECT + +[ConsolidatedFinancialReportingID], +[Statement], +[Section], +[LineName], + COALESCE([Name],'') as [Name], +[SortOrder], +[MemberGUID], +[HistoryItemGUID] +FROM [fw].[DimConsolidatedFinancialReporting] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimConsolidatedFinancialReporting_source +CREATE VIEW [fw].[viewDimConsolidatedFinancialReporting_source] +AS +SELECT + grpB839D1E3EA3544B1802E3D15F28F859E.[ConsolidatedFinancialReportingID] + ,grpB839D1E3EA3544B1802E3D15F28F859E.[MemberGUID] + ,grpB839D1E3EA3544B1802E3D15F28F859E.[HistoryItemGUID] + ,[grpB839D1E3EA3544B1802E3D15F28F859E].[Statement] + ' - ' + [grpB839D1E3EA3544B1802E3D15F28F859E].[Section] + ' - ' + [grpB839D1E3EA3544B1802E3D15F28F859E].[LineName] AS [Name] +FROM [fw].[DimConsolidatedFinancialReporting] grpB839D1E3EA3544B1802E3D15F28F859E (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimDataType +CREATE VIEW [fw].[viewDimDataType] +AS +SELECT + grp7931E63E49A84444B96A3473EF2E8342.[DataTypeID] + ,grp7931E63E49A84444B96A3473EF2E8342.[Name] + ,grp7931E63E49A84444B96A3473EF2E8342.[GlobalID] + ,grp7931E63E49A84444B96A3473EF2E8342.[MemberGUID] + ,grp7931E63E49A84444B96A3473EF2E8342.[HistoryItemGUID] +FROM [fw].[DimDataType] grp7931E63E49A84444B96A3473EF2E8342 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimDate_auto +--Last Modified 4/5/2019 11:00 PM +CREATE VIEW [fw].[viewDimDate_auto] +AS +SELECT + grpFE562A75A28047209619C1D86C699238.[DateID] + ,grpFE562A75A28047209619C1D86C699238.[TransactionID] + ,grpFE562A75A28047209619C1D86C699238.[DayNumberOfWeek] + ,grpFE562A75A28047209619C1D86C699238.[DayNameOfWeek] + ,grpFE562A75A28047209619C1D86C699238.[DayNumberOfMonth] + ,grpFE562A75A28047209619C1D86C699238.[DayNumberOfYear] + ,grpFE562A75A28047209619C1D86C699238.[WeekNumberOfYear] + ,grpFE562A75A28047209619C1D86C699238.[IsWeekDay] + ,grpFE562A75A28047209619C1D86C699238.[CalendarQuarter] + ,grpFE562A75A28047209619C1D86C699238.[CalendarDateTime] + ,grpFE562A75A28047209619C1D86C699238.[CalendarYear] + ,grpFE562A75A28047209619C1D86C699238.[CalendarMonth] + ,grpFE562A75A28047209619C1D86C699238.[CalendarMonthName] + ,grpFE562A75A28047209619C1D86C699238.[FiscalYear] + ,coalesce(grpFE562A75A28047209619C1D86C699238.[FiscalYearName],'') as [FiscalYearName] + ,grpFE562A75A28047209619C1D86C699238.[HistoryItemGUID] + ,grpFE562A75A28047209619C1D86C699238.[MemberGUID] + ,grpFE562A75A28047209619C1D86C699238.[FiscalMonth] + ,grpFE562A75A28047209619C1D86C699238.[FiscalQuarter] + ,grpFE562A75A28047209619C1D86C699238.[YearMonth] + ,grpFE562A75A28047209619C1D86C699238.[MonthYear] + ,grpFE562A75A28047209619C1D86C699238.[DaysInMonth] + ,coalesce(grpFE562A75A28047209619C1D86C699238.[PremierMapping],'') as [PremierMapping] +, [grpFE562A75A28047209619C1D86C699238].[Version]FROM [fw].[DimDate] grpFE562A75A28047209619C1D86C699238 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimDayType2 +CREATE VIEW fw.viewDimDayType2 + +AS + +SELECT + DayTypeID [DayType2ID] + ,DayTypeCode + ,Description + ,Name + ,PrecedentOrder + ,GlobalID + ,Rollup + ,MemberGUID + ,HistoryItemGUID +FROM + fw.DimDayType +GO + + +--------------------------------------------- + +-- fw.viewDimDayType2_auto +CREATE VIEW [fw].[viewDimDayType2_auto] +AS +SELECT + grp143B285CCD194B4EBEF270972EB02575.[DayType2ID] + ,grp143B285CCD194B4EBEF270972EB02575.[DayTypeCode] + ,grp143B285CCD194B4EBEF270972EB02575.[Description] + ,grp143B285CCD194B4EBEF270972EB02575.[Name] + ,grp143B285CCD194B4EBEF270972EB02575.[PrecedentOrder] + ,grp143B285CCD194B4EBEF270972EB02575.[GlobalID] + ,grp143B285CCD194B4EBEF270972EB02575.[Rollup] + ,grp143B285CCD194B4EBEF270972EB02575.[MemberGUID] + ,grp143B285CCD194B4EBEF270972EB02575.[HistoryItemGUID] +FROM [fw].[viewDimDayType2] grp143B285CCD194B4EBEF270972EB02575 +GO + + +--------------------------------------------- + +-- fw.viewDimDayType3 +CREATE VIEW fw.viewDimDayType3 + +AS + +SELECT + DayTypeID [DayType3ID] + ,DayTypeCode + ,Description + ,Name + ,PrecedentOrder + ,GlobalID + ,Rollup + ,MemberGUID + ,HistoryItemGUID +FROM + fw.DimDayType +GO + + +--------------------------------------------- + +-- fw.viewDimDayType3_auto +CREATE VIEW [fw].[viewDimDayType3_auto] +AS +SELECT + grp5B075EFFA79145A69E8B48E63306F374.[DayType3ID] + ,grp5B075EFFA79145A69E8B48E63306F374.[DayTypeCode] + ,grp5B075EFFA79145A69E8B48E63306F374.[Description] + ,grp5B075EFFA79145A69E8B48E63306F374.[Name] + ,grp5B075EFFA79145A69E8B48E63306F374.[PrecedentOrder] + ,grp5B075EFFA79145A69E8B48E63306F374.[GlobalID] + ,grp5B075EFFA79145A69E8B48E63306F374.[Rollup] + ,grp5B075EFFA79145A69E8B48E63306F374.[MemberGUID] + ,grp5B075EFFA79145A69E8B48E63306F374.[HistoryItemGUID] +FROM [fw].[viewDimDayType3] grp5B075EFFA79145A69E8B48E63306F374 +GO + + +--------------------------------------------- + +-- fw.viewDimDayType_auto +--Last Modified 3/8/2016 3:28 PM +CREATE VIEW [fw].[viewDimDayType_auto] +AS +SELECT + grpCCD1FA368B434C7B949582F5A942303E.[DayTypeID] + ,grpCCD1FA368B434C7B949582F5A942303E.[DayTypeCode] + ,grpCCD1FA368B434C7B949582F5A942303E.[Description] + ,coalesce(grpCCD1FA368B434C7B949582F5A942303E.[Name],'') as [Name] + ,grpCCD1FA368B434C7B949582F5A942303E.[PrecedentOrder] + ,grpCCD1FA368B434C7B949582F5A942303E.[GlobalID] + ,grpCCD1FA368B434C7B949582F5A942303E.[MemberGUID] + ,grpCCD1FA368B434C7B949582F5A942303E.[HistoryItemGUID] + ,grpCCD1FA368B434C7B949582F5A942303E.[Rollup] +FROM [fw].[DimDayType] grpCCD1FA368B434C7B949582F5A942303E (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimDayType_auto_0 +CREATE VIEW [fw].[viewDimDayType_auto_0] +AS +SELECT + grp78A73D3E10C0427BB8F87BD131D0742E.[DayTypeID] + ,grp78A73D3E10C0427BB8F87BD131D0742E.[DayTypeCode] + ,grp78A73D3E10C0427BB8F87BD131D0742E.[Description] + ,coalesce(grp78A73D3E10C0427BB8F87BD131D0742E.[Name],'') as [Name] + ,grp78A73D3E10C0427BB8F87BD131D0742E.[PrecedentOrder] + ,grp78A73D3E10C0427BB8F87BD131D0742E.[GlobalID] + ,grp78A73D3E10C0427BB8F87BD131D0742E.[MemberGUID] + ,grp78A73D3E10C0427BB8F87BD131D0742E.[HistoryItemGUID] + ,grp78A73D3E10C0427BB8F87BD131D0742E.[Rollup] +FROM [fw].[DimDayType] grp78A73D3E10C0427BB8F87BD131D0742E +GO + + +--------------------------------------------- + +-- fw.viewDimDayofStay +CREATE VIEW [fw].[viewDimDayofStay] +AS +SELECT + grp13B341BB37FF431BA7F941247BF19B9E.[DayofStayID] + ,grp13B341BB37FF431BA7F941247BF19B9E.[Name] + ,grp13B341BB37FF431BA7F941247BF19B9E.[MemberGUID] + ,grp13B341BB37FF431BA7F941247BF19B9E.[HistoryItemGUID] +FROM [fw].[DimDayofStay] grp13B341BB37FF431BA7F941247BF19B9E (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimDepartment +CREATE VIEW [fw].[viewDimDepartment] +AS +SELECT + +[DepartmentID], + COALESCE([Name],'') as [Name], +[DepartmentCode], +[Description], +[SystemID], +[EntityID], +[DepartmentRollup1ID], +[DepartmentRollup2ID], +[DepartmentRollup3ID], +[DepartmentRollup4ID], +[DepartmentRollup5ID], +[DepartmentRollup6ID], +[CareSettingID], +[SortOrder], +[FunctionalAreaID], +[ResearchDepartmentCategoryID], +[AttributionTypeID], +[CAPIsDefined], +[IsCAP], +[DSSIsDefined], +[IsDSS], +[DepartmentTypeOLD], +[DSSDeptGrouping], +[DSSDepartmentRollup1ID], +[DSSDepartmentRollup2ID], +[DSSDepartmentRollup3ID], +[DSSDepartmentRollup4ID], +[DSSDepartmentRollup5ID], +[DSSDepartmentRollup6ID], +[DSSDepartmentRollup7ID], +[IsOverhead], +[OBIsDefined], +[IsOB], +[IsMRPlan], +[IsMRMetricTracking], +[IsPR], +[IsActive], +[IsVariable], +[IsAccountFlexing], +[FlexingBucketGUID], +[OBGlobalStatisticsPlanID], +[OBReimbursementPlanID], +[OBServiceLinePlanID], +[SPIsDefined], +[IsLRFP], +[RollingPlanID], +[OpsPlanID], +[BalPlanID], +[PatientTypeRollup], +[SPJobCodeGroup], +[SPPhysicianGroup], +[SPAccountRollup], + COALESCE([System],'') as [System], +[SystemSortOrder], + COALESCE([Entity],'') as [Entity], +[EntitySortOrder], +[EntityTypeOverride], + COALESCE([EntityCode],'') as [EntityCode], + COALESCE([CareSetting],'') as [CareSetting], + COALESCE([DepartmentRollup1],'') as [DepartmentRollup1], +[DepartmentRollup1SortOrder], + COALESCE([DepartmentRollup2],'') as [DepartmentRollup2], +[DepartmentRollup2SortOrder], + COALESCE([DepartmentRollup3],'') as [DepartmentRollup3], +[DepartmentRollup3SortOrder], + COALESCE([DepartmentRollup4],'') as [DepartmentRollup4], +[DepartmentRollup4SortOrder], +[SPHDepartmentRollupID], + COALESCE([SPHDepartmentRollupName],'') as [SPHDepartmentRollupName], +[SPHDepartmentRollupConfidenceScore], + COALESCE([DepartmentRollup5],'') as [DepartmentRollup5], +[SPHDepartmentConfidenceScore], +[DepartmentRollup5SortOrder], + COALESCE([DepartmentRollup6],'') as [DepartmentRollup6], +[DepartmentRollup6SortOrder], + COALESCE([DSSDepartmentRollup1Name],'') as [DSSDepartmentRollup1Name], + COALESCE([DSSDepartmentRollup2Name],'') as [DSSDepartmentRollup2Name], + COALESCE([DSSDepartmentRollup3Name],'') as [DSSDepartmentRollup3Name], + COALESCE([DSSDepartmentRollup4Name],'') as [DSSDepartmentRollup4Name], + COALESCE([DSSDepartmentRollup5Name],'') as [DSSDepartmentRollup5Name], + COALESCE([DSSDepartmentRollup6Name],'') as [DSSDepartmentRollup6Name], + COALESCE([DSSDepartmentRollup7Name],'') as [DSSDepartmentRollup7Name], + COALESCE([FunctionalArea],'') as [FunctionalArea], + COALESCE([ResearchDepartmentCategoryName],'') as [ResearchDepartmentCategoryName], +[ResearchDepartmentCategorySortOrder], + COALESCE([AttributionType],'') as [AttributionType], +[IsConsolidated], +[ConsolidatedCode], + COALESCE([OBGlobalStatisticsPlan],'') as [OBGlobalStatisticsPlan], + COALESCE([OBReimbursementPlan],'') as [OBReimbursementPlan], + COALESCE([OBServiceLinePlan],'') as [OBServiceLinePlan], + COALESCE([SPRollingForecastPlanName],'') as [SPRollingForecastPlanName], + COALESCE([SPOperationsPlanName],'') as [SPOperationsPlanName], + COALESCE([SPBalanceSheetPlanName],'') as [SPBalanceSheetPlanName], +[IsDepartmentRollup], +[SPServiceLineForecastType], + COALESCE([PatientTypeRollupName],'') as [PatientTypeRollupName], +[DepartmentTypeID], + COALESCE([DepartmentType],'') as [DepartmentType], + COALESCE([SPJobCodeGroupName],'') as [SPJobCodeGroupName], + COALESCE([SPPhysicianGroupName],'') as [SPPhysicianGroupName], + COALESCE([SPAccountRollupName],'') as [SPAccountRollupName], +[SecureGroupID], +[MemberGUID], +[HistoryItemGUID], +[WorkWeekID], +[CAPDefaultSalesTax], +[FundID], + COALESCE([Fund],'') as [Fund], +[FundSortOrder], +[ProjectID], + COALESCE([Project],'') as [Project], +[ProjectSortOrder], +[HomeDepartmentID], + COALESCE([HomeDepartment],'') as [HomeDepartment], +[HomeDepartmentSortOrder], +[ProgramID], + COALESCE([Program],'') as [Program], +[ProgramSortOrder], +[PayCycleID], +[FWIsDefined], +[DepartmentCodeRaw], +[MRVicePresident], +[MRDirector], +[MRManager], +[IsMROrPR], +[IsHealthPlanAdmin], + COALESCE([DepartmentRollup1Code],'') as [DepartmentRollup1Code], + COALESCE([DepartmentRollup2Code],'') as [DepartmentRollup2Code], + COALESCE([DepartmentRollup3Code],'') as [DepartmentRollup3Code], + COALESCE([DepartmentRollup4Code],'') as [DepartmentRollup4Code], + COALESCE([DepartmentRollup5Code],'') as [DepartmentRollup5Code], + COALESCE([DepartmentRollup6Code],'') as [DepartmentRollup6Code], +[TransactionID], +[SPHDepartmentTypeID], +[SPHDepartmentRollupIsValidated], +[SPHDepartmentIsValidated], +[SPHDepartmentID], + COALESCE([SPHDepartmentName],'') as [SPHDepartmentName], +[SPHDepartmentType], +[IsClaimsCosting], +[ProductivityPercentileID], + COALESCE([ProductivityPercentile],'') as [ProductivityPercentile], +[CompAnDepartmentID], + COALESCE([CompAnDepartment],'') as [CompAnDepartment] ,[Version] + +FROM [fw].[DimDepartment] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimDepartmentPH_auto +CREATE VIEW [fw].[viewDimDepartmentPH_auto] +AS +SELECT + grpDC20824AF9C5477F9045CAAEF2A933B7.[Name] + ,grpDC20824AF9C5477F9045CAAEF2A933B7.[MemberGUID] + ,grpDC20824AF9C5477F9045CAAEF2A933B7.[DepartmentPHID] +, [grpDC20824AF9C5477F9045CAAEF2A933B7].[Version], [grpDC20824AF9C5477F9045CAAEF2A933B7].[HistoryItemGUID]FROM [fw].[DimDepartmentPH] grpDC20824AF9C5477F9045CAAEF2A933B7 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimDepartmentRollup1 +CREATE VIEW [fw].[viewDimDepartmentRollup1] +AS +SELECT + +[DepartmentRollup1ID], + COALESCE([Name],'') as [Name], +[Code], +[Description], +[SortOrder], +[SecureGroupID], +[MemberGUID], +[HistoryItemGUID], +[EliminationsDepartmentID] +FROM [fw].[DimDepartmentRollup1] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimDepartmentRollup1_source +CREATE VIEW [fw].[viewDimDepartmentRollup1_source] +AS +SELECT + grpFA10FD701D9D4868B178EDDF1FC3BABD.[DepartmentRollup1ID] + ,grpFA10FD701D9D4868B178EDDF1FC3BABD.[Name] + ,grpFA10FD701D9D4868B178EDDF1FC3BABD.[SecureGroupID] + ,grpFA10FD701D9D4868B178EDDF1FC3BABD.[MemberGUID] + ,grpFA10FD701D9D4868B178EDDF1FC3BABD.[HistoryItemGUID] +FROM [fw].[DimDepartmentRollup1] grpFA10FD701D9D4868B178EDDF1FC3BABD (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimDepartmentRollup2 +CREATE VIEW [fw].[viewDimDepartmentRollup2] +AS +SELECT + +[DepartmentRollup2ID], + COALESCE([Name],'') as [Name], +[Code], +[Description], +[SortOrder], +[SecureGroupID], +[MemberGUID], +[HistoryItemGUID], +[EliminationsDepartmentID] +FROM [fw].[DimDepartmentRollup2] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimDepartmentRollup2_source +CREATE VIEW [fw].[viewDimDepartmentRollup2_source] +AS +SELECT + grpB2EDCD6A7E5448C8912DE6279CA5303C.[DepartmentRollup2ID] + ,grpB2EDCD6A7E5448C8912DE6279CA5303C.[Name] + ,grpB2EDCD6A7E5448C8912DE6279CA5303C.[SecureGroupID] + ,grpB2EDCD6A7E5448C8912DE6279CA5303C.[MemberGUID] + ,grpB2EDCD6A7E5448C8912DE6279CA5303C.[HistoryItemGUID] +FROM [fw].[DimDepartmentRollup2] grpB2EDCD6A7E5448C8912DE6279CA5303C (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimDepartmentRollup3 +CREATE VIEW [fw].[viewDimDepartmentRollup3] +AS +SELECT + +[DepartmentRollup3ID], + COALESCE([Name],'') as [Name], +[Code], +[Description], +[SortOrder], +[SecureGroupID], +[MemberGUID], +[HistoryItemGUID], +[EliminationsDepartmentID] +FROM [fw].[DimDepartmentRollup3] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimDepartmentRollup3_source +CREATE VIEW [fw].[viewDimDepartmentRollup3_source] +AS +SELECT + grp0D6EBF23F8D6489DA85B11B8FF0DF237.[DepartmentRollup3ID] + ,grp0D6EBF23F8D6489DA85B11B8FF0DF237.[Name] + ,grp0D6EBF23F8D6489DA85B11B8FF0DF237.[SecureGroupID] + ,grp0D6EBF23F8D6489DA85B11B8FF0DF237.[MemberGUID] + ,grp0D6EBF23F8D6489DA85B11B8FF0DF237.[HistoryItemGUID] +FROM [fw].[DimDepartmentRollup3] grp0D6EBF23F8D6489DA85B11B8FF0DF237 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimDepartmentRollup4 +CREATE VIEW [fw].[viewDimDepartmentRollup4] +AS +SELECT + +[DepartmentRollup4ID], + COALESCE([Name],'') as [Name], +[Code], +[Description], +[SortOrder], +[SecureGroupID], +[MemberGUID], +[HistoryItemGUID], +[EliminationsDepartmentID] +FROM [fw].[DimDepartmentRollup4] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimDepartmentRollup4_source +CREATE VIEW [fw].[viewDimDepartmentRollup4_source] +AS +SELECT + grp2823DE836C9241B29F219400CAE92824.[SecureGroupID] + ,grp2823DE836C9241B29F219400CAE92824.[DepartmentRollup4ID] + ,grp2823DE836C9241B29F219400CAE92824.[Name] + ,grp2823DE836C9241B29F219400CAE92824.[MemberGUID] + ,grp2823DE836C9241B29F219400CAE92824.[HistoryItemGUID] +FROM [fw].[DimDepartmentRollup4] grp2823DE836C9241B29F219400CAE92824 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimDepartmentRollup5 +CREATE VIEW [fw].[viewDimDepartmentRollup5] +AS +SELECT + +[DepartmentRollup5ID], + COALESCE([Name],'') as [Name], +[Code], +[Description], +[SortOrder], +[SecureGroupID], +[MemberGUID], +[HistoryItemGUID], +[EliminationsDepartmentID] +FROM [fw].[DimDepartmentRollup5] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimDepartmentRollup5_source +CREATE VIEW [fw].[viewDimDepartmentRollup5_source] +AS +SELECT + grpFEF2ED58077B4941805CE8B84D4E763A.[SecureGroupID] + ,grpFEF2ED58077B4941805CE8B84D4E763A.[DepartmentRollup5ID] + ,grpFEF2ED58077B4941805CE8B84D4E763A.[Name] + ,grpFEF2ED58077B4941805CE8B84D4E763A.[MemberGUID] + ,grpFEF2ED58077B4941805CE8B84D4E763A.[HistoryItemGUID] +FROM [fw].[DimDepartmentRollup5] grpFEF2ED58077B4941805CE8B84D4E763A (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimDepartmentRollup6 +CREATE VIEW [fw].[viewDimDepartmentRollup6] +AS +SELECT + +[DepartmentRollup6ID], + COALESCE([Name],'') as [Name], +[Code], +[Description], +[SortOrder], +[SecureGroupID], +[MemberGUID], +[HistoryItemGUID], +[EliminationsDepartmentID] +FROM [fw].[DimDepartmentRollup6] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimDepartmentRollup6_source +CREATE VIEW [fw].[viewDimDepartmentRollup6_source] +AS +SELECT + grp43C5EF4D49654C9B9526374DD9E2FC93.[DepartmentRollup6ID] + ,grp43C5EF4D49654C9B9526374DD9E2FC93.[SecureGroupID] + ,grp43C5EF4D49654C9B9526374DD9E2FC93.[Name] + ,grp43C5EF4D49654C9B9526374DD9E2FC93.[MemberGUID] + ,grp43C5EF4D49654C9B9526374DD9E2FC93.[HistoryItemGUID] +FROM [fw].[DimDepartmentRollup6] grp43C5EF4D49654C9B9526374DD9E2FC93 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimDepartmentType +--Last Modified 1/20/2016 8:39 AM +CREATE VIEW [fw].[viewDimDepartmentType] +AS +SELECT + grpFC24FBAFBE8449659F87692015E8BC45.[DepartmentTypeID] + ,grpFC24FBAFBE8449659F87692015E8BC45.[Name] + ,grpFC24FBAFBE8449659F87692015E8BC45.[TransactionID] + ,grpFC24FBAFBE8449659F87692015E8BC45.[MemberGUID] + ,grpFC24FBAFBE8449659F87692015E8BC45.[HistoryItemGUID] + ,grpFC24FBAFBE8449659F87692015E8BC45.[Rollup] +FROM [fw].[DimDepartmentType] grpFC24FBAFBE8449659F87692015E8BC45 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimDepartment_Pseudo +CREATE view fw.viewDimDepartment_Pseudo AS +SELECT DepartmentID, Name, DepartmentCode, Description, SystemID, EntityID, DepartmentRollup1ID, DepartmentRollup2ID, DepartmentRollup3ID, DepartmentRollup4ID, + DepartmentRollup5ID, DepartmentRollup6ID, CareSettingID, SortOrder, FunctionalAreaID, ResearchDepartmentCategoryID, AttributionTypeID, CAPIsDefined, IsCAP, + DSSIsDefined, IsDSS, DepartmentTypeOLD, DSSDeptGrouping, DSSDepartmentRollup1ID, DSSDepartmentRollup2ID, DSSDepartmentRollup3ID, IsOverhead, + OBIsDefined, IsOB, IsMRPlan, IsActive, IsVariable, IsAccountFlexing, FlexingBucketGUID, OBGlobalStatisticsPlanID, OBReimbursementPlanID, + OBServiceLinePlanID, SPIsDefined, IsLRFP, RollingPlanID, OpsPlanID, BalPlanID, PatientTypeRollup, SPJobCodeGroup, SPPhysicianGroup, SPAccountRollup, + System, SystemSortOrder, Entity, EntitySortOrder, EntityTypeOverride, EntityCode, CareSetting, DepartmentRollup1, DepartmentRollup1SortOrder, + DepartmentRollup2, DepartmentRollup2SortOrder, DepartmentRollup3, DepartmentRollup3SortOrder, DepartmentRollup4, DepartmentRollup4SortOrder, + DepartmentRollup5, DepartmentRollup5SortOrder, DepartmentRollup6, DepartmentRollup6SortOrder, DSSDepartmentRollup1Name, DSSDepartmentRollup2Name, + DSSDepartmentRollup3Name, FunctionalArea, ResearchDepartmentCategoryName, ResearchDepartmentCategorySortOrder, AttributionType, IsConsolidated, + ConsolidatedCode, OBGlobalStatisticsPlan, OBReimbursementPlan, OBServiceLinePlan, SPRollingForecastPlanName, SPOperationsPlanName, + SPBalanceSheetPlanName, IsDepartmentRollup, SPServiceLineForecastType, PatientTypeRollupName, DepartmentTypeID, DepartmentType, + SPJobCodeGroupName, SPPhysicianGroupName, SPAccountRollupName, SecureGroupID, MemberGUID, HistoryItemGUID, WorkWeekID, CAPDefaultSalesTax, + FundID, Fund, FundSortOrder, ProjectID, Project, ProjectSortOrder, HomeDepartmentID, HomeDepartment, HomeDepartmentSortOrder, ProgramID, Program, + ProgramSortOrder, PayCycleID, FWIsDefined, DepartmentCodeRaw, IsPR, SPHDepartmentTypeID, SPHDepartmentType, Version +FROM fw.viewDimDepartment AS d +WHERE (IsDepartmentRollup = 1) OR + (DepartmentID = 0) +GO + + +--------------------------------------------- + +-- fw.viewDimDepartment_Real +CREATE view [fw].[viewDimDepartment_Real] +AS +SELECT + DepartmentID, Name, DepartmentCode, Description, SystemID, EntityID, DepartmentRollup1ID, DepartmentRollup2ID, DepartmentRollup3ID, DepartmentRollup4ID, + DepartmentRollup5ID, DepartmentRollup6ID, CareSettingID, SortOrder, FunctionalAreaID, ResearchDepartmentCategoryID, AttributionTypeID, CAPIsDefined, IsCAP, + DSSIsDefined, IsDSS, DSSDeptGrouping, DSSDepartmentRollup1ID, DSSDepartmentRollup2ID, DSSDepartmentRollup3ID,DSSDepartmentRollup4ID, DSSDepartmentRollup5ID, DSSDepartmentRollup6ID, DSSDepartmentRollup7ID, IsOverhead, + OBIsDefined, IsOB, IsMRPlan, IsMRMetricTracking, IsActive, IsVariable, IsAccountFlexing, FlexingBucketGUID, OBGlobalStatisticsPlanID, OBReimbursementPlanID, + OBServiceLinePlanID, SPIsDefined, IsLRFP, RollingPlanID, OpsPlanID, BalPlanID, PatientTypeRollup, SPJobCodeGroup, SPPhysicianGroup, SPAccountRollup, + System, SystemSortOrder, Entity, EntitySortOrder, EntityTypeOverride, EntityCode, CareSetting, DepartmentRollup1, DepartmentRollup1SortOrder, + DepartmentRollup2, DepartmentRollup2SortOrder, DepartmentRollup3, DepartmentRollup3SortOrder, DepartmentRollup4, DepartmentRollup4SortOrder, + DepartmentRollup5, DepartmentRollup5SortOrder, DepartmentRollup6, DepartmentRollup6SortOrder, DSSDepartmentRollup1Name, DSSDepartmentRollup2Name, + DSSDepartmentRollup3Name,DSSDepartmentRollup4Name,DSSDepartmentRollup5Name,DSSDepartmentRollup6Name,DSSDepartmentRollup7Name, FunctionalArea, ResearchDepartmentCategoryName, ResearchDepartmentCategorySortOrder, AttributionType, IsConsolidated, + ConsolidatedCode, OBGlobalStatisticsPlan, OBReimbursementPlan, OBServiceLinePlan, SPRollingForecastPlanName, SPOperationsPlanName, + SPBalanceSheetPlanName, IsDepartmentRollup, SPServiceLineForecastType, PatientTypeRollupName, DepartmentTypeID, DepartmentType, + SPJobCodeGroupName, SPPhysicianGroupName, SPAccountRollupName, SecureGroupID, MemberGUID, HistoryItemGUID, WorkWeekID, CAPDefaultSalesTax, + FundID, Fund, FundSortOrder, ProjectID, Project, ProjectSortOrder, HomeDepartmentID, HomeDepartment, HomeDepartmentSortOrder, ProgramID, Program, + ProgramSortOrder, PayCycleID, FWIsDefined, DepartmentCodeRaw, IsPR, SPHDepartmentTypeID, SPHDepartmentType, Version, SPHDepartmentID, SPHDepartmentName, SPHDepartmentConfidenceScore, SPHDepartmentIsValidated, SPHDepartmentRollupID, SPHDepartmentRollupName, SPHDepartmentRollupConfidenceScore +FROM + fw.viewDimDepartment d +WHERE + (IsDepartmentRollup = 0 OR DepartmentID = 0) +GO + + +--------------------------------------------- + +-- fw.viewDimDepartment_source +CREATE VIEW [fw].[viewDimDepartment_source] +AS +SELECT + grp34146F449F3140ECB03A8BC6153DE46F.[DepartmentID] + ,grp34146F449F3140ECB03A8BC6153DE46F.[Name] + ,grp34146F449F3140ECB03A8BC6153DE46F.[EntityTypeOverride] + ,grp34146F449F3140ECB03A8BC6153DE46F.[SPHDepartmentRollupID] + ,grp34146F449F3140ECB03A8BC6153DE46F.[SPHDepartmentConfidenceScore] + ,grp34146F449F3140ECB03A8BC6153DE46F.[SecureGroupID] + ,grp34146F449F3140ECB03A8BC6153DE46F.[MemberGUID] + ,grp34146F449F3140ECB03A8BC6153DE46F.[HistoryItemGUID] + ,grp34146F449F3140ECB03A8BC6153DE46F.[IsMROrPR] + ,grp34146F449F3140ECB03A8BC6153DE46F.[TransactionID] + ,ISNULL([SYSTEM].[Name], 'Not Specified') as [System] + ,ISNULL([SYSTEM].[SortOrder], 0) as [SystemSortOrder] + ,ISNULL([ENT].[Name], 'Not Specified') as [Entity] + ,ISNULL([ENT].[SortOrder], 0) as [EntitySortOrder] + ,ISNULL([ENT].[Code], 'Not Specified') as [EntityCode] + ,ISNULL([ENT].[SPServiceLineForecastType], 0) as [SPServiceLineForecastType] + ,ISNULL([ENT].[WorkWeekID], 0) as [WorkWeekID] + ,ISNULL([ENT].[CAPDefaultSalesTax], 0) as [CAPDefaultSalesTax] + ,ISNULL([ENT].[PayCycleID], 0) as [PayCycleID] + ,ISNULL([DeptRollup1].[Name], 'Not Specified') as [DepartmentRollup1] + ,ISNULL([DeptRollup1].[SortOrder], 0) as [DepartmentRollup1SortOrder] + ,ISNULL([DeptRollup1].[Code], 'Not Specified') as [DepartmentRollup1Code] + ,ISNULL([DeptRollup2].[Name], 'Not Specified') as [DepartmentRollup2] + ,ISNULL([DeptRollup2].[SortOrder], 0) as [DepartmentRollup2SortOrder] + ,ISNULL([DeptRollup2].[Code], 'Not Specified') as [DepartmentRollup2Code] + ,ISNULL([DeptRollup3].[Name], 'Not Specified') as [DepartmentRollup3] + ,ISNULL([DeptRollup3].[SortOrder], 0) as [DepartmentRollup3SortOrder] + ,ISNULL([DeptRollup3].[Code], 'Not Specified') as [DepartmentRollup3Code] + ,ISNULL([DeptRollup4].[Name], 'Not Specified') as [DepartmentRollup4] + ,ISNULL([DeptRollup4].[SortOrder], 0) as [DepartmentRollup4SortOrder] + ,ISNULL([DeptRollup4].[Code], 'Not Specified') as [DepartmentRollup4Code] + ,ISNULL([DeptRollup5].[Name], 'Not Specified') as [DepartmentRollup5] + ,ISNULL([DeptRollup5].[SortOrder], 0) as [DepartmentRollup5SortOrder] + ,ISNULL([DeptRollup5].[Code], 'Not Specified') as [DepartmentRollup5Code] + ,ISNULL([DeptRollup6].[Name], 'Not Specified') as [DepartmentRollup6] + ,ISNULL([DeptRollup6].[SortOrder], 0) as [DepartmentRollup6SortOrder] + ,ISNULL([DeptRollup6].[Code], 'Not Specified') as [DepartmentRollup6Code] + ,ISNULL([CARESETTING].[Name], 'Not Specified') as [CareSetting] + ,ISNULL([FUNCTIONALAREA].[Name], 'Not Specified') as [FunctionalArea] + ,ISNULL([RESEARCHDEPARTMENTCATEGORY].[Name], 'Not Specified') as [ResearchDepartmentCategoryName] + ,ISNULL([RESEARCHDEPARTMENTCATEGORY].[SortOrder], 0) as [ResearchDepartmentCategorySortOrder] + ,ISNULL([ATTRIBUTIONTYPE].[Name], 'Not Specified') as [AttributionType] + ,ISNULL([DSSDEPTROLLUP1].[Name], 'Not Specified') as [DSSDepartmentRollup1Name] + ,ISNULL([DSSDEPTROLLUP2].[Name], 'Not Specified') as [DSSDepartmentRollup2Name] + ,ISNULL([DSSDEPTROLLUP3].[Name], 'Not Specified') as [DSSDepartmentRollup3Name] + ,ISNULL([DSDEPTR4].[Name], 'Not Specified') as [DSSDepartmentRollup4Name] + ,ISNULL([DSSDEPT5].[Name], 'Not Specified') as [DSSDepartmentRollup5Name] + ,ISNULL([DSSDEPTROLL6].[Name], 'Not Specified') as [DSSDepartmentRollup6Name] + ,ISNULL([DSSDEPARTMENTROLLUP7].[Name], 'Not Specified') as [DSSDepartmentRollup7Name] + ,ISNULL([OBGLOBALSTATISTICSPLAN].[Name], 'Not Specified') as [OBGlobalStatisticsPlan] + ,ISNULL([OBREIMBURSEMENTPLAN].[Name], 'Not Specified') as [OBReimbursementPlan] + ,ISNULL([OBSERVICELINEPLAN].[Name], 'Not Specified') as [OBServiceLinePlan] + ,ISNULL([SPRFPLAN].[Name], 'Not Specified') as [SPRollingForecastPlanName] + ,ISNULL([SPLRPLAN].[Name], 'Not Specified') as [SPOperationsPlanName] + ,ISNULL([SPLRPLAN_1].[Name], 'Not Specified') as [SPBalanceSheetPlanName] + ,ISNULL([PatientTyRo].[Name], 'Not Specified') as [PatientTypeRollupName] + ,ISNULL([JobCodeGrp].[Name], 'Not Specified') as [SPJobCodeGroupName] + ,ISNULL([PhyGrp].[Name], 'Not Specified') as [SPPhysicianGroupName] + ,ISNULL([SPAccountRollup].[Name], 'Not Specified') as [SPAccountRollupName] + ,ISNULL([SPHDEPARTMENTROLLUP].[Name], 'Not Specified') as [SPHDepartmentRollupName] + ,ISNULL([DEPTTYPE].[Name], 'Not Specified') as [DepartmentType] + ,ISNULL([FUND].[Name], 'Not Specified') as [Fund] + ,ISNULL([FUND].[SortOrder], 0) as [FundSortOrder] + ,ISNULL([FWPROJECT].[Name], 'Not Specified') as [Project] + ,ISNULL([FWPROJECT].[SortOrder], 0) as [ProjectSortOrder] + ,ISNULL([FWPROJECT].[ProjectID], 0) as [HomeDepartmentID] + ,ISNULL([HOMEDEPARTMENT].[Name], 'Not Specified') as [HomeDepartment] + ,ISNULL([HOMEDEPARTMENT].[SortOrder], 0) as [HomeDepartmentSortOrder] + ,ISNULL([PROGRAM].[Name], 'Not Specified') as [Program] + ,ISNULL([PROGRAM].[SortOrder], 0) as [ProgramSortOrder] + ,ISNULL([SPHDEPARTMENT].[Name], 'Not Specified') as [SPHDepartmentName] + ,ISNULL([PRODUCTIVITYPERCENTILE].[Name], 'Not Specified') as [ProductivityPercentile] + ,ISNULL([COMPANDEPARTMENT].[Description], 'Not Specified') as [CompAnDepartment] +, [grp34146F449F3140ECB03A8BC6153DE46F].[Version]FROM [fw].[DimDepartment] grp34146F449F3140ECB03A8BC6153DE46F (readuncommitted) + LEFT JOIN [fw].[viewDimSystem] [SYSTEM] on [SYSTEM].[SystemID] = [grp34146F449F3140ECB03A8BC6153DE46F].[SystemID] + LEFT JOIN [fw].[viewDimEntity] [ENT] on [ENT].[EntityID] = [grp34146F449F3140ECB03A8BC6153DE46F].[EntityID] + LEFT JOIN [fw].[viewDimDepartmentRollup1] [DeptRollup1] on [DeptRollup1].[DepartmentRollup1ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DepartmentRollup1ID] + LEFT JOIN [fw].[viewDimDepartmentRollup2] [DeptRollup2] on [DeptRollup2].[DepartmentRollup2ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DepartmentRollup2ID] + LEFT JOIN [fw].[viewDimDepartmentRollup3] [DeptRollup3] on [DeptRollup3].[DepartmentRollup3ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DepartmentRollup3ID] + LEFT JOIN [fw].[viewDimDepartmentRollup4] [DeptRollup4] on [DeptRollup4].[DepartmentRollup4ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DepartmentRollup4ID] + LEFT JOIN [fw].[viewDimDepartmentRollup5] [DeptRollup5] on [DeptRollup5].[DepartmentRollup5ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DepartmentRollup5ID] + LEFT JOIN [fw].[viewDimDepartmentRollup6] [DeptRollup6] on [DeptRollup6].[DepartmentRollup6ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DepartmentRollup6ID] + LEFT JOIN [fw].[viewDimCareSetting] [CARESETTING] on [CARESETTING].[CareSettingID] = [grp34146F449F3140ECB03A8BC6153DE46F].[CareSettingID] + INNER JOIN [fw].[viewDimFunctionalArea] [FUNCTIONALAREA] on [FUNCTIONALAREA].[FunctionalAreaID] = [grp34146F449F3140ECB03A8BC6153DE46F].[FunctionalAreaID] + LEFT JOIN [fw].[viewDimResearchDepartmentCategory] [RESEARCHDEPARTMENTCATEGORY] on [RESEARCHDEPARTMENTCATEGORY].[ResearchDepartmentCategoryID] = [grp34146F449F3140ECB03A8BC6153DE46F].[ResearchDepartmentCategoryID] + INNER JOIN [dss].[viewDimAttributionType] [ATTRIBUTIONTYPE] on [ATTRIBUTIONTYPE].[AttributionTypeID] = [grp34146F449F3140ECB03A8BC6153DE46F].[AttributionTypeID] + LEFT JOIN [dss].[viewDimDepartmentRollup1] [DSSDEPTROLLUP1] on [DSSDEPTROLLUP1].[DSSDepartmentRollup1ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DSSDepartmentRollup1ID] + LEFT JOIN [dss].[viewDimDepartmentRollup2] [DSSDEPTROLLUP2] on [DSSDEPTROLLUP2].[DSSDepartmentRollup2ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DSSDepartmentRollup2ID] + LEFT JOIN [dss].[viewDimDepartmentRollup3] [DSSDEPTROLLUP3] on [DSSDEPTROLLUP3].[DSSDepartmentRollup3ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DSSDepartmentRollup3ID] + LEFT JOIN [dss].[viewDimDepartmentRollup4] [DSDEPTR4] on [DSDEPTR4].[DSSDepartmentRollup4ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DSSDepartmentRollup4ID] + LEFT JOIN [dss].[viewDimDepartmentRollup5] [DSSDEPT5] on [DSSDEPT5].[DSSDepartmentRollup5ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DSSDepartmentRollup5ID] + INNER JOIN [dss].[viewDimDepartmentRollup6] [DSSDEPTROLL6] on [DSSDEPTROLL6].[DSSDepartmentRollup6ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DSSDepartmentRollup6ID] + LEFT JOIN [dss].[viewDimDepartmentRollup7] [DSSDEPARTMENTROLLUP7] on [DSSDEPARTMENTROLLUP7].[DSSDepartmentRollup7ID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DSSDepartmentRollup7ID] + LEFT JOIN [ob].[viewDimOBGlobalStatisticsPlan] [OBGLOBALSTATISTICSPLAN] on [OBGLOBALSTATISTICSPLAN].[OBGlobalStatisticsPlanID] = [grp34146F449F3140ECB03A8BC6153DE46F].[OBGlobalStatisticsPlanID] + LEFT JOIN [ob].[viewDimOBReimbursementPlan] [OBREIMBURSEMENTPLAN] on [OBREIMBURSEMENTPLAN].[OBReimbursementPlanID] = [grp34146F449F3140ECB03A8BC6153DE46F].[OBReimbursementPlanID] + LEFT JOIN [ob].[viewDimOBServiceLinePlan] [OBSERVICELINEPLAN] on [OBSERVICELINEPLAN].[OBServiceLinePlanID] = [grp34146F449F3140ECB03A8BC6153DE46F].[OBServiceLinePlanID] + LEFT JOIN [sp].[viewDimSPRollingForecastPlan] [SPRFPLAN] on [SPRFPLAN].[SPRollingForecastPlanID] = [grp34146F449F3140ECB03A8BC6153DE46F].[RollingPlanID] + LEFT JOIN [sp].[viewDimSPLongRangePlan] [SPLRPLAN] on [SPLRPLAN].[SPLongRangePlanID] = [grp34146F449F3140ECB03A8BC6153DE46F].[OpsPlanID] + LEFT JOIN [sp].[viewDimSPLongRangePlan] [SPLRPLAN_1] on [SPLRPLAN_1].[SPLongRangePlanID] = [grp34146F449F3140ECB03A8BC6153DE46F].[BalPlanID] + LEFT JOIN [fw].[viewDimPatientTypeRollup] [PatientTyRo] on [PatientTyRo].[PatientTypeRollupID] = [grp34146F449F3140ECB03A8BC6153DE46F].[PatientTypeRollup] + LEFT JOIN [fw].[viewDimJobCodeGroup] [JobCodeGrp] on [JobCodeGrp].[JobCodeGroupID] = [grp34146F449F3140ECB03A8BC6153DE46F].[SPJobCodeGroup] + LEFT JOIN [fw].[viewDimPhysicianGroup] [PhyGrp] on [PhyGrp].[PhysicianGroupID] = [grp34146F449F3140ECB03A8BC6153DE46F].[SPPhysicianGroup] + LEFT JOIN [sp].[viewDimAccountRollup] [SPAccountRollup] on [SPAccountRollup].[AccountRollupID] = [grp34146F449F3140ECB03A8BC6153DE46F].[SPAccountRollup] + LEFT JOIN [fw].[viewDimSPHDepartmentRollup] [SPHDEPARTMENTROLLUP] on [SPHDEPARTMENTROLLUP].[SPHDepartmentRollupID] = [grp34146F449F3140ECB03A8BC6153DE46F].[SPHDepartmentRollupID] + INNER JOIN [fw].[viewDimDepartmentType] [DEPTTYPE] on [DEPTTYPE].[DepartmentTypeID] = [grp34146F449F3140ECB03A8BC6153DE46F].[DepartmentTypeID] + LEFT JOIN [fw].[viewDimFund] [FUND] on [FUND].[FundID] = [grp34146F449F3140ECB03A8BC6153DE46F].[FundID] + LEFT JOIN [fw].[viewDimProject] [FWPROJECT] on [FWPROJECT].[ProjectID] = [grp34146F449F3140ECB03A8BC6153DE46F].[ProjectID] + LEFT JOIN [fw].[viewDimHomeDepartment] [HOMEDEPARTMENT] on [HOMEDEPARTMENT].[HomeDepartmentID] = [grp34146F449F3140ECB03A8BC6153DE46F].[HomeDepartmentID] + LEFT JOIN [fw].[viewDimProgram] [PROGRAM] on [PROGRAM].[ProgramID] = [grp34146F449F3140ECB03A8BC6153DE46F].[ProgramID] + INNER JOIN [fw].[viewDimSPHDepartment_auto] [SPHDEPARTMENT] on [SPHDEPARTMENT].[SPHDepartmentID] = [grp34146F449F3140ECB03A8BC6153DE46F].[SPHDepartmentID] + INNER JOIN [pi].[viewDimProductivityPercentile] [PRODUCTIVITYPERCENTILE] on [PRODUCTIVITYPERCENTILE].[ProductivityPercentileID] = [grp34146F449F3140ECB03A8BC6153DE46F].[ProductivityPercentileID] + INNER JOIN [fw].[viewDimCompAnDepartment] [COMPANDEPARTMENT] on [COMPANDEPARTMENT].[CompAnDepartmentID] = [grp34146F449F3140ECB03A8BC6153DE46F].[CompAnDepartmentID] +GO + + +--------------------------------------------- + +-- fw.viewDimDepartment_triggers +CREATE view fw.viewDimDepartment_triggers +as +select + d.FriendlyName as RefreshDimension, + 'exec procScoreSetDimensionSecurity30 ''' + cast(d.DimensionGUID as nvarchar(36)) + ''',0,0' as RefreshSQL, + 'drop trigger fw.' + tg.Name as DropSQL +from + sys.triggers tg + inner join [dbo].[ScoreDimension] d on tg.name like '%' + replace(cast(d.DimensionGUID as nvarchar(36)),'-', '') + '%' where tg.parent_id in(select t.object_id from sys.tables t inner join sys.schemas s on s.schema_id = t.schema_id where t.name = 'DimDepartment' and s.name = 'fw') + and name like '%ScoreDimension%' +GO + + +--------------------------------------------- + +-- fw.viewDimEmployee +CREATE VIEW [fw].[viewDimEmployee] +AS +SELECT + +[EmployeeID], + COALESCE([Name],'') as [Name], +[NameLast], +[NameFirst], +[Number], +[JobCodeID], +[Code], +[OBIsDefined], +[WageRate], +[IsProvider], +[ProviderID], + COALESCE([JobCode],'') as [JobCode], + COALESCE([JobCodeCode],'') as [JobCodeCode], +[IsVariable], +[HireDate], +[IsActive], +[Status], +[NextReview], +[MemberGUID], +[HistoryItemGUID], +[WorkWeekOverrideID], +[HomeDepartmentID], + COALESCE([HomeDepartment],'') as [HomeDepartment], + COALESCE([HomeDepartmentCode],'') as [HomeDepartmentCode], + COALESCE([NameFull],'') as [NameFull], +[EmployeeCohortID], + COALESCE([EmployeeCohortName],'') as [EmployeeCohortName], +[EmployeeCohortContractDate], + COALESCE([EmployeeCohortMeritType],'') as [EmployeeCohortMeritType], +[StandardHours], +[FWIsDefined], +[TerminationDate], +[AdjustedHireDate], +[FTETotal], +[HomeAccountID], + COALESCE([HomeAccount],'') as [HomeAccount], + COALESCE([HomeAccountCode],'') as [HomeAccountCode], +[EmployeeClass], +[NPI], +[TransactionID], +[PositionControlNumber] ,[Version] + +FROM [fw].[DimEmployee] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimEmployeeCohort +--Last Modified 4/13/2015 3:16 PM +CREATE VIEW [fw].[viewDimEmployeeCohort] +AS +SELECT + grp62E0F8DE46CB42D18A44A996145E4741.[EmployeeCohortID] + ,grp62E0F8DE46CB42D18A44A996145E4741.[Name] + ,grp62E0F8DE46CB42D18A44A996145E4741.[Code] + ,grp62E0F8DE46CB42D18A44A996145E4741.[Description] + ,grp62E0F8DE46CB42D18A44A996145E4741.[MeritType] + ,grp62E0F8DE46CB42D18A44A996145E4741.[ContractDate] + ,grp62E0F8DE46CB42D18A44A996145E4741.[SortOrder] + ,grp62E0F8DE46CB42D18A44A996145E4741.[TransactionID] + ,grp62E0F8DE46CB42D18A44A996145E4741.[MemberGUID] + ,grp62E0F8DE46CB42D18A44A996145E4741.[HistoryItemGUID] +FROM [fw].[DimEmployeeCohort] grp62E0F8DE46CB42D18A44A996145E4741 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimEmployeePH +CREATE VIEW [fw].[viewDimEmployeePH] +AS +SELECT + grpAE7FA4E45FE14270A057580F39CDA6F1.[EmployeePHID] + ,grpAE7FA4E45FE14270A057580F39CDA6F1.[Name] + ,grpAE7FA4E45FE14270A057580F39CDA6F1.[MemberGUID] +FROM [fw].[DimEmployeePH] grpAE7FA4E45FE14270A057580F39CDA6F1 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimEmployee_source +CREATE VIEW [fw].[viewDimEmployee_source] +AS +SELECT + grp304BAC4BC73943CCBFF4E85B307B146A.[EmployeeID] + ,grp304BAC4BC73943CCBFF4E85B307B146A.[Name] + ,grp304BAC4BC73943CCBFF4E85B307B146A.[MemberGUID] + ,grp304BAC4BC73943CCBFF4E85B307B146A.[HistoryItemGUID] + ,grp304BAC4BC73943CCBFF4E85B307B146A.[NameFull] + ,grp304BAC4BC73943CCBFF4E85B307B146A.[TransactionID] + ,ISNULL([JOBCODE].[Name], 'Not Specified') as [JobCode] + ,ISNULL([JOBCODE].[JobCode], 'Not Specified') as [JobCodeCode] + ,ISNULL([JOBCODE].[IsVariable], 0) as [IsVariable] + ,ISNULL([JOBCODE].[WorkWeekOverrideID], 0) as [WorkWeekOverrideID] + ,ISNULL([DEPT].[Name], 'Not Specified') as [HomeDepartment] + ,ISNULL([DEPT].[DepartmentCode], 'Not Specified') as [HomeDepartmentCode] + ,ISNULL([EMPLOYEECOHORT].[Name], 'Not Specified') as [EmployeeCohortName] + ,ISNULL([EMPLOYEECOHORT].[ContractDate], getdate()) as [EmployeeCohortContractDate] + ,ISNULL([EMPLOYEECOHORT].[MeritType], 'Not Specified') as [EmployeeCohortMeritType] + ,ISNULL([ACCT].[Name], 'Not Specified') as [HomeAccount] + ,ISNULL([ACCT].[AccountCode], 'Not Specified') as [HomeAccountCode] +, [grp304BAC4BC73943CCBFF4E85B307B146A].[Version]FROM [fw].[DimEmployee] grp304BAC4BC73943CCBFF4E85B307B146A (readuncommitted) + LEFT JOIN [fw].[viewDimJobCode] [JOBCODE] on [JOBCODE].[JobCodeID] = [grp304BAC4BC73943CCBFF4E85B307B146A].[JobCodeID] + LEFT JOIN [fw].[viewDimDepartment] [DEPT] on [DEPT].[DepartmentID] = [grp304BAC4BC73943CCBFF4E85B307B146A].[HomeDepartmentID] + INNER JOIN [fw].[viewDimEmployeeCohort] [EMPLOYEECOHORT] on [EMPLOYEECOHORT].[EmployeeCohortID] = [grp304BAC4BC73943CCBFF4E85B307B146A].[EmployeeCohortID] + INNER JOIN [fw].[viewDimAccount] [ACCT] on [ACCT].[AccountID] = [grp304BAC4BC73943CCBFF4E85B307B146A].[HomeAccountID] +GO + + +--------------------------------------------- + +-- fw.viewDimEntity +CREATE VIEW [fw].[viewDimEntity] +AS +SELECT + +[EntityID], + COALESCE([Name],'') as [Name], +[Code], +[Description], +[SortOrder], +[EntityType], +[IsActive], +[CAPIsDefined], +[DSSIsDefined], +[OBIsDefined], +[OBBenefitsDepartmentID], + COALESCE([OBBenefitsDepartment],'') as [OBBenefitsDepartment], +[OBHasGlobalStatisticsPlan], +[OBHasReimbursementPlan], +[OBHasServiceLinePlan], +[OBIsUsingProviderComp], +[SPIsDefined], +[SPGrossChargesPatientTypeRollup], +[SPGrossChargesPayorGroup], +[SPContractualsPatientTypeRollup], +[SPContractualsPayorGroup], +[SPIPVolumesPatientTypeRollup], +[SPIPVolumesPayorGroup], +[SPIPDaysPatientTypeRollup], +[SPIPDaysPayorGroup], +[SPOPVolumesPatientTypeRollup], +[SPOPVolumesPayorGroup], +[SPFTEsJobCodeGroup], +[SPSalariesJobCodeGroup], +[SPClinicGrossChargesPayorGroup], +[SPClinicContractualsPayorGroup], +[SPClinicPrimaryVolumePhysicianGroup], +[SPClinicSecondaryVolumePhysicianGroup], +[SPClinicFTEsPhysicianGroup], +[SPClinicSalariesPhysicianGroup], +[SPOperationsSLDrivenModelID], +[SPRollingForecastSLDrivenModelID], +[SPServiceLineForecastType], +[SecureGroupID], +[WorkWeekID], +[TransactionID], +[PayCycleID], +[HistoryItemGUID], +[MemberGUID], +[CAPDefaultSalesTax], +[FWIsDefined], +[EliminationsDepartmentID], +[CompAnPeerGroupID] +FROM [fw].[DimEntity] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimEntityPH +Create VIEW [fw].[viewDimEntityPH] +AS +SELECT + [EntityPHID], + [Name], + [MemberGUID], + [HistoryItemGUID], + [TransactionID] +FROM [fw].[DimEntityPH] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimEntity_source +CREATE VIEW [fw].[viewDimEntity_source] +AS +SELECT + grpDE819FBD8CE84979B478F0E94260A8F7.[EntityID] + ,grpDE819FBD8CE84979B478F0E94260A8F7.[Name] + ,grpDE819FBD8CE84979B478F0E94260A8F7.[SecureGroupID] + ,grpDE819FBD8CE84979B478F0E94260A8F7.[TransactionID] + ,grpDE819FBD8CE84979B478F0E94260A8F7.[HistoryItemGUID] + ,grpDE819FBD8CE84979B478F0E94260A8F7.[MemberGUID] + ,ISNULL([DEPT].[Name], 'Not Specified') as [OBBenefitsDepartment] +FROM [fw].[DimEntity] grpDE819FBD8CE84979B478F0E94260A8F7 (readuncommitted) + INNER JOIN [fw].[viewDimDepartment] [DEPT] on [DEPT].[DepartmentID] = [grpDE819FBD8CE84979B478F0E94260A8F7].[OBBenefitsDepartmentID] +GO + + +--------------------------------------------- + +-- fw.viewDimFiscalMonth +--Last Modified 5/8/2015 5:50 PM +CREATE VIEW [fw].[viewDimFiscalMonth] +AS +SELECT + grpC5A4CCC2DC85403F8A1BD9849CF14E18.[FiscalMonthID] + ,coalesce(grpC5A4CCC2DC85403F8A1BD9849CF14E18.[Name],'') as [Name] + ,grpC5A4CCC2DC85403F8A1BD9849CF14E18.[FiscalMonthCode] + ,coalesce(grpC5A4CCC2DC85403F8A1BD9849CF14E18.[Abbreviation],'') as [Abbreviation] + ,grpC5A4CCC2DC85403F8A1BD9849CF14E18.[QuarterID] + ,grpC5A4CCC2DC85403F8A1BD9849CF14E18.[SortOrder] + ,grpC5A4CCC2DC85403F8A1BD9849CF14E18.[DaysInMonth] + ,grpC5A4CCC2DC85403F8A1BD9849CF14E18.[YTDDaysInMonth] + ,grpC5A4CCC2DC85403F8A1BD9849CF14E18.[MemberGUID] + ,coalesce(grpC5A4CCC2DC85403F8A1BD9849CF14E18.[MonthColumnName],'') as [MonthColumnName] + ,grpC5A4CCC2DC85403F8A1BD9849CF14E18.[HistoryItemGUID] + ,grpC5A4CCC2DC85403F8A1BD9849CF14E18.[IsReal] +, [grpC5A4CCC2DC85403F8A1BD9849CF14E18].[Version]FROM [fw].[DimFiscalMonth] grpC5A4CCC2DC85403F8A1BD9849CF14E18 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimFiscalTime +--Last Modified 3/15/2022 10:09 PM +CREATE VIEW [fw].[viewDimFiscalTime] +AS +SELECT + grp32094482DE9943D5832B9F8295DACBDF.[FiscalTimeID] + ,grp32094482DE9943D5832B9F8295DACBDF.[FiscalTime] + ,grp32094482DE9943D5832B9F8295DACBDF.[TransactionID] + ,grp32094482DE9943D5832B9F8295DACBDF.[MemberGUID] + ,grp32094482DE9943D5832B9F8295DACBDF.[HistoryItemGUID] + ,grp32094482DE9943D5832B9F8295DACBDF.[FiscalYearID] + ,grp32094482DE9943D5832B9F8295DACBDF.[FiscalMonthID] + ,grp32094482DE9943D5832B9F8295DACBDF.[YearMonth] + ,grp32094482DE9943D5832B9F8295DACBDF.[CountFromCurrentMonth] + ,grp32094482DE9943D5832B9F8295DACBDF.[StartDate] + ,grp32094482DE9943D5832B9F8295DACBDF.[EndDate] +FROM [fw].[DimFiscalTime] grp32094482DE9943D5832B9F8295DACBDF (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimFiscalYear +--Last Modified 5/8/2015 5:50 PM +CREATE VIEW [fw].[viewDimFiscalYear] +AS +SELECT + grp07DC08C1A3354C289D66B7FAF5CEC935.[FiscalYearID] + ,grp07DC08C1A3354C289D66B7FAF5CEC935.[MemberGUID] + ,grp07DC08C1A3354C289D66B7FAF5CEC935.[Name] + ,grp07DC08C1A3354C289D66B7FAF5CEC935.[SortOrder] + ,grp07DC08C1A3354C289D66B7FAF5CEC935.[IsSP] + ,grp07DC08C1A3354C289D66B7FAF5CEC935.[HistoryItemGUID] + ,grp07DC08C1A3354C289D66B7FAF5CEC935.[IsCAP] +, [grp07DC08C1A3354C289D66B7FAF5CEC935].[Version]FROM [fw].[DimFiscalYear] grp07DC08C1A3354C289D66B7FAF5CEC935 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimFiscalYearPH_auto +CREATE VIEW [fw].[viewDimFiscalYearPH_auto] +AS +SELECT + grp74AEECE5F9BE4AAFA6BADD6EF917266F.[Name] + ,grp74AEECE5F9BE4AAFA6BADD6EF917266F.[MemberGUID] + ,grp74AEECE5F9BE4AAFA6BADD6EF917266F.[FiscalYearPHID] + ,grp74AEECE5F9BE4AAFA6BADD6EF917266F.[HistoryItemGUID] +, [grp74AEECE5F9BE4AAFA6BADD6EF917266F].[Version]FROM [fw].[DimFiscalYearPH] grp74AEECE5F9BE4AAFA6BADD6EF917266F (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimFlag +--Last Modified 4/12/2019 11:35 AM +CREATE VIEW [fw].[viewDimFlag] +AS +SELECT + grp7ECC55FC3D4F41479EA1C29BC253029B.[FlagID] + ,grp7ECC55FC3D4F41479EA1C29BC253029B.[Code] + ,grp7ECC55FC3D4F41479EA1C29BC253029B.[Description] + ,coalesce(grp7ECC55FC3D4F41479EA1C29BC253029B.[Name],'') as [Name] + ,grp7ECC55FC3D4F41479EA1C29BC253029B.[TransactionID] + ,grp7ECC55FC3D4F41479EA1C29BC253029B.[MemberGUID] + ,grp7ECC55FC3D4F41479EA1C29BC253029B.[HistoryItemGUID] +FROM [fw].[DimFlag] grp7ECC55FC3D4F41479EA1C29BC253029B (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimFlexJobCodeGroup +--Last Modified 2/25/2015 11:46 AM +CREATE VIEW [fw].[viewDimFlexJobCodeGroup] +AS +SELECT + grp37D108FB34FF431799A3DD4B6EDB7CDC.[FlexJobCodeGroupID] + ,grp37D108FB34FF431799A3DD4B6EDB7CDC.[Name] + ,grp37D108FB34FF431799A3DD4B6EDB7CDC.[Code] + ,grp37D108FB34FF431799A3DD4B6EDB7CDC.[SortOrder] + ,grp37D108FB34FF431799A3DD4B6EDB7CDC.[TransactionID] + ,grp37D108FB34FF431799A3DD4B6EDB7CDC.[MemberGUID] + ,grp37D108FB34FF431799A3DD4B6EDB7CDC.[HistoryItemGUID] +FROM [fw].[DimFlexJobCodeGroup] grp37D108FB34FF431799A3DD4B6EDB7CDC (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimForecastDetail +CREATE VIEW [fw].[viewDimForecastDetail] +AS +SELECT + +[ForecastDetailID], + COALESCE([Name],'') as [Name], +[ForecastDetailCode], +[Description], +[CAPForecastDetailID], +[CPIsDefined], +[OBForecastDetailID], +[OBIsDefined], +[SPAccountRollupID], +[SPIsDefined], +[TransactionID], +[SPCostComponentID], +[MemberGUID], +[HistoryItemGUID] +FROM [fw].[DimForecastDetail] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimForecastDetail_source +CREATE VIEW [fw].[viewDimForecastDetail_source] +AS +SELECT + grp19542254A1554DCB89A76BAACAB6E162.[ForecastDetailID] + ,grp19542254A1554DCB89A76BAACAB6E162.[Name] + ,grp19542254A1554DCB89A76BAACAB6E162.[TransactionID] + ,grp19542254A1554DCB89A76BAACAB6E162.[MemberGUID] + ,grp19542254A1554DCB89A76BAACAB6E162.[HistoryItemGUID] +FROM [fw].[DimForecastDetail] grp19542254A1554DCB89A76BAACAB6E162 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimFramework +CREATE view [fw].[viewDimFramework] +as + select + fwk.FrameworkID, + fwk.Name, + fwk.Abbreviation, + fwk.FrameworkSchemaName, + fwk.ClientSchemaName, + fwk.IsLatestDataModel, + case when fwk.Name = 'General' then cast(1 as bit) else cast(max(cast(isnull(m.IsLicensed, 0) as int)) as bit) end as IsLicensed, + cast(max(cast(isnull(m.IsSetupComplete, 0) as int)) as bit) as IsSetupComplete + from + [fw].[DimFramework] fwk + left join [dbo].[SystemCenterSolution] s on s.Name = fwk.Name + left join [dbo].[SystemCenterModule] m on m.SolutionGUID = s.SolutionGUID or m.Name = fwk.Name + group by + fwk.FrameworkID, + fwk.Name, + fwk.Abbreviation, + fwk.FrameworkSchemaName, + fwk.ClientSchemaName, + fwk.IsLatestDataModel +GO + + +--------------------------------------------- + +-- fw.viewDimFramework_auto +CREATE VIEW [fw].[viewDimFramework_auto] +AS +SELECT + coalesce(grp67F5902643D4451785A9B828FC66FFFD.[Name],'') as [Name] + ,grp67F5902643D4451785A9B828FC66FFFD.[MemberGUID] + ,grp67F5902643D4451785A9B828FC66FFFD.[FrameworkID] +, [grp67F5902643D4451785A9B828FC66FFFD].[Version], [grp67F5902643D4451785A9B828FC66FFFD].[HistoryItemGUID]FROM [fw].[DimFramework] grp67F5902643D4451785A9B828FC66FFFD (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimFunctionalArea +CREATE VIEW [fw].[viewDimFunctionalArea] +AS +SELECT + grp6CD1220F54B84B4F9BA381B12A98DDB4.[FunctionalAreaID] + ,grp6CD1220F54B84B4F9BA381B12A98DDB4.[Name] + ,grp6CD1220F54B84B4F9BA381B12A98DDB4.[TransactionID] + ,grp6CD1220F54B84B4F9BA381B12A98DDB4.[MemberGUID] + ,grp6CD1220F54B84B4F9BA381B12A98DDB4.[HistoryItemGUID] +FROM [fw].[DimFunctionalArea] grp6CD1220F54B84B4F9BA381B12A98DDB4 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimFund +--Last Modified 5/27/2015 1:34 PM +CREATE VIEW [fw].[viewDimFund] +AS +SELECT + grp15688121574D4B38A25965FF7CA63FCE.[FundID] + ,coalesce(grp15688121574D4B38A25965FF7CA63FCE.[Name],'') as [Name] + ,grp15688121574D4B38A25965FF7CA63FCE.[Code] + ,grp15688121574D4B38A25965FF7CA63FCE.[Description] + ,grp15688121574D4B38A25965FF7CA63FCE.[SortOrder] + ,grp15688121574D4B38A25965FF7CA63FCE.[TransactionID] + ,grp15688121574D4B38A25965FF7CA63FCE.[MemberGUID] + ,grp15688121574D4B38A25965FF7CA63FCE.[HistoryItemGUID] +FROM [fw].[DimFund] grp15688121574D4B38A25965FF7CA63FCE (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimGLAndPayrollInitiative +--Last Modified 9/12/2022 9:10 PM +CREATE VIEW [fw].[viewDimGLAndPayrollInitiative] +AS +SELECT + grpBE8428F4CC9543D192CBE7EBD767DB6C.[GLAndPayrollInitiativeGUID] + ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[Name] + ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[Owner] + ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[Author] + ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[CostLeader] + ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[ExecutiveSponsor] + ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[EffectiveDate] + ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[AnnualGoal] + ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[DateCreated] + ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[GoalStartDate] + ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[GoalEndDate] + ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[SavingsEstimate] + ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[SourceOfSavings] + ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[Description] + ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[Workstream] + ,grpBE8428F4CC9543D192CBE7EBD767DB6C.[InitiativeStatus] +FROM [cci].[viewDimGLAndPayrollInitiative] grpBE8428F4CC9543D192CBE7EBD767DB6C +GO + + +--------------------------------------------- + +-- fw.viewDimGLAndPayrollOpportunity +--Last Modified 9/12/2022 9:10 PM +CREATE VIEW [fw].[viewDimGLAndPayrollOpportunity] +AS +SELECT + grp45B56B6F4F434F229DB3FA943E5107AE.[GLAndPayrollOpportunityGUID] + ,grp45B56B6F4F434F229DB3FA943E5107AE.[Name] + ,grp45B56B6F4F434F229DB3FA943E5107AE.[Owner] + ,grp45B56B6F4F434F229DB3FA943E5107AE.[AnnualGoal] + ,grp45B56B6F4F434F229DB3FA943E5107AE.[SavingsEstimate] + ,grp45B56B6F4F434F229DB3FA943E5107AE.[OpportunityKey] + ,grp45B56B6F4F434F229DB3FA943E5107AE.[DateCreated] + ,grp45B56B6F4F434F229DB3FA943E5107AE.[BaselineStartDate] + ,grp45B56B6F4F434F229DB3FA943E5107AE.[BaselineEndDate] + ,grp45B56B6F4F434F229DB3FA943E5107AE.[SavingsIdentified] + ,grp45B56B6F4F434F229DB3FA943E5107AE.[SavingsGoal] + ,grp45B56B6F4F434F229DB3FA943E5107AE.[HasInitiative] + ,grp45B56B6F4F434F229DB3FA943E5107AE.[SourceOfSavings] + ,grp45B56B6F4F434F229DB3FA943E5107AE.[IsHidden] +FROM [cci].[viewDimGLAndPayrollOpportunity] grp45B56B6F4F434F229DB3FA943E5107AE +GO + + +--------------------------------------------- + +-- fw.viewDimGLPostDate +CREATE VIEW [fw].[viewDimGLPostDate] +AS + SELECT + DateID AS [GLPostDateID] + ,TransactionID + ,DayNumberOfWeek + ,DayNameOfWeek + ,DayNumberOfMonth + ,DayNumberOfYear + ,WeekNumberOfYear + ,IsWeekDay + ,CalendarQuarter + ,CalendarDateTime + ,CalendarYear + ,CalendarMonth + ,CalendarMonthName + ,FiscalYear + ,FiscalYearName + ,HistoryItemGUID + ,MemberGUID + ,FiscalMonth + ,FiscalQuarter + ,YearMonth + ,MonthYear + ,DaysInMonth + ,PremierMapping + FROM [fw].[DimDate]; +GO + + +--------------------------------------------- + +-- fw.viewDimGLPostDate_auto +--Last Modified 6/8/2020 3:11 PM +CREATE VIEW [fw].[viewDimGLPostDate_auto] +AS +SELECT + grp5D0EB954A8774F2B9816D9D0814D3F9F.[GLPostDateID] + ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[TransactionID] + ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[DayNumberOfWeek] + ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[DayNameOfWeek] + ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[DayNumberOfMonth] + ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[DayNumberOfYear] + ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[WeekNumberOfYear] + ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[IsWeekDay] + ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[CalendarQuarter] + ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[CalendarDateTime] + ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[CalendarYear] + ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[CalendarMonth] + ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[CalendarMonthName] + ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[FiscalYear] + ,coalesce(grp5D0EB954A8774F2B9816D9D0814D3F9F.[FiscalYearName],'') as [FiscalYearName] + ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[HistoryItemGUID] + ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[MemberGUID] + ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[FiscalMonth] + ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[FiscalQuarter] + ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[YearMonth] + ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[MonthYear] + ,grp5D0EB954A8774F2B9816D9D0814D3F9F.[DaysInMonth] + ,coalesce(grp5D0EB954A8774F2B9816D9D0814D3F9F.[PremierMapping],'') as [PremierMapping] +FROM [fw].[viewDimGLPostDate] grp5D0EB954A8774F2B9816D9D0814D3F9F +GO + + +--------------------------------------------- + +-- fw.viewDimGMTestFWProj +CREATE VIEW [fw].[viewDimGMTestFWProj] +AS +SELECT + grpDB12BF7D35E34296A3CBFCDACB880F51.[GMTestFWDateCreated] + ,grpDB12BF7D35E34296A3CBFCDACB880F51.[GMTestFWName] + ,grpDB12BF7D35E34296A3CBFCDACB880F51.[MemberGUID] + ,grpDB12BF7D35E34296A3CBFCDACB880F51.[GMTestFWProjID] + ,ISNULL([DimXP].[PlanID], 0) as [PlanID] + ,ISNULL([DimXP].[Name], 'Not Specified') as [Name] +FROM [cap].[DimGMTestFWProj] grpDB12BF7D35E34296A3CBFCDACB880F51 (readuncommitted) + INNER JOIN [fw].[viewDimXPlan_auto] [DimXP] on [DimXP].[MemberGUID] = [grpDB12BF7D35E34296A3CBFCDACB880F51].[MemberGUID] +GO + + +--------------------------------------------- + +-- fw.viewDimHealthPlanRegion +CREATE VIEW [fw].[viewDimHealthPlanRegion] +AS + SELECT + DepartmentRollup1ID AS [HealthPlanRegionID] + ,Name + ,Code AS [Code] + ,Description + ,SortOrder + ,SecureGroupID + ,MemberGUID + ,HistoryItemGUID + ,EliminationsDepartmentID + FROM [fw].[DimDepartmentRollup1]; +GO + + +--------------------------------------------- + +-- fw.viewDimHealthPlanRegion_auto +--Last Modified 10/30/2018 9:41 AM +CREATE VIEW [fw].[viewDimHealthPlanRegion_auto] +AS +SELECT + grp59F984CE07874F708A1B24F9C8376E7D.[HealthPlanRegionID] + ,coalesce(grp59F984CE07874F708A1B24F9C8376E7D.[Name],'') as [Name] + ,grp59F984CE07874F708A1B24F9C8376E7D.[Code] + ,grp59F984CE07874F708A1B24F9C8376E7D.[Description] + ,grp59F984CE07874F708A1B24F9C8376E7D.[SortOrder] + ,grp59F984CE07874F708A1B24F9C8376E7D.[SecureGroupID] + ,grp59F984CE07874F708A1B24F9C8376E7D.[MemberGUID] + ,grp59F984CE07874F708A1B24F9C8376E7D.[HistoryItemGUID] + ,grp59F984CE07874F708A1B24F9C8376E7D.[EliminationsDepartmentID] +FROM [fw].[viewDimHealthPlanRegion] grp59F984CE07874F708A1B24F9C8376E7D +GO + + +--------------------------------------------- + +-- fw.viewDimHomeDepartment +--Last Modified 5/26/2015 10:11 AM +CREATE VIEW [fw].[viewDimHomeDepartment] +AS +SELECT + grp4A1ECAA1FE314B2F8C73E9A238625529.[HomeDepartmentID] + ,coalesce(grp4A1ECAA1FE314B2F8C73E9A238625529.[Name],'') as [Name] + ,grp4A1ECAA1FE314B2F8C73E9A238625529.[Code] + ,grp4A1ECAA1FE314B2F8C73E9A238625529.[Description] + ,grp4A1ECAA1FE314B2F8C73E9A238625529.[SortOrder] + ,grp4A1ECAA1FE314B2F8C73E9A238625529.[TransactionID] + ,grp4A1ECAA1FE314B2F8C73E9A238625529.[MemberGUID] + ,grp4A1ECAA1FE314B2F8C73E9A238625529.[HistoryItemGUID] +FROM [fw].[DimHomeDepartment] grp4A1ECAA1FE314B2F8C73E9A238625529 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimInitiative +CREATE VIEW [fw].[viewDimInitiative] +AS +SELECT + grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[Name] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[Description] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[MemberGUID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[MemberGUID] AS [InitiativeGUID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[HistoryItemGUID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[TransactionID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeStatusID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeStatus] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[AuthorGUID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[Author] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[CostLeaderGUID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[CostLeader] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[OwnerGUID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[Owner] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[ExecutiveSponsorGUID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[ExecutiveSponsor] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[SourceOfSavingsID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[SourceOfSavings] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[Workstream] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[DateCreated] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[EffectiveDate] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[GoalStartDate] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[GoalEndDate] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[AnnualGoal] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[SavingsEstimate] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeRollup1ID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeRollup1] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeRollup2ID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeRollup2] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeRollup3ID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeRollup3] +FROM [fw].[DimInitiative] grp63E2E9DC1F4747C7A31CA6E43ECE1FF4 +GO + + +--------------------------------------------- + +-- fw.viewDimInitiativeStatus +--Last Modified 10/31/2018 10:40 AM +CREATE VIEW [fw].[viewDimInitiativeStatus] +AS +SELECT + grpC9DC306912F4434CA7D806FB28CC0AF9.[InitiativeStatusID] + ,grpC9DC306912F4434CA7D806FB28CC0AF9.[Name] + ,grpC9DC306912F4434CA7D806FB28CC0AF9.[MemberGUID] + ,grpC9DC306912F4434CA7D806FB28CC0AF9.[HistoryItemGUID] + ,grpC9DC306912F4434CA7D806FB28CC0AF9.[TransactionID] +FROM [fw].[DimInitiativeStatus] grpC9DC306912F4434CA7D806FB28CC0AF9 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimInitiative_auto +--Last Modified 7/10/2024 5:05 PM +CREATE VIEW [fw].[viewDimInitiative_auto] +AS +SELECT + grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[Name] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[TransactionID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[MemberGUID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[HistoryItemGUID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeGUID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[Description] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[Workstream] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[DateCreated] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[Author] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[EffectiveDate] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[SourceOfSavingsId] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[SourceOfSavings] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[InitiativeStatusID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[GoalStartDate] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[GoalEndDate] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[CostLeaderGUID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[AnnualGoal] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[SavingsEstimate] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[OwnerGUID] + ,grp63E2E9DC1F4747C7A31CA6E43ECE1FF4.[ExecutiveSponsorGUID] + ,ISNULL([INITIATIVESTATUS].[Name], 'Not Specified') as [InitiativeStatus] + ,ISNULL([CICOSTLEADER].[NameFull], 'Not Specified') as [CostLeader] + ,ISNULL([CIOWNER].[NameFull], 'Not Specified') as [Owner] + ,ISNULL([CIEXECUTIVESPONSOR].[NameFull], 'Not Specified') as [ExecutiveSponsor] +FROM [fw].[viewDimInitiative] grp63E2E9DC1F4747C7A31CA6E43ECE1FF4 + INNER JOIN [fw].[viewDimInitiativeStatus] [INITIATIVESTATUS] on [INITIATIVESTATUS].[InitiativeStatusID] = [grp63E2E9DC1F4747C7A31CA6E43ECE1FF4].[InitiativeStatusID] + INNER JOIN [fw].[viewDimCICostLeader_auto] [CICOSTLEADER] on [CICOSTLEADER].[CICostLeaderID] = [grp63E2E9DC1F4747C7A31CA6E43ECE1FF4].[CostLeaderGUID] + INNER JOIN [fw].[viewDimCIOwner_auto] [CIOWNER] on [CIOWNER].[CIOwnerID] = [grp63E2E9DC1F4747C7A31CA6E43ECE1FF4].[OwnerGUID] + INNER JOIN [fw].[viewDimCIExecutiveSponsor_auto] [CIEXECUTIVESPONSOR] on [CIEXECUTIVESPONSOR].[CIExecutiveSponsorID] = [grp63E2E9DC1F4747C7A31CA6E43ECE1FF4].[ExecutiveSponsorGUID] +GO + + +--------------------------------------------- + +-- fw.viewDimJobCode +--Last Modified 8/21/2024 10:16 AM +CREATE VIEW [fw].[viewDimJobCode] +AS +SELECT + grpAAD69FC0ED76427EA52ED356470BFE0A.[JobCodeID] + ,coalesce(grpAAD69FC0ED76427EA52ED356470BFE0A.[Name],'') as [Name] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[JobCode] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[Description] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[JobCodeGroupID] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[IsVariable] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[IsPR] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[IsDaily] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[IsActive] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[IsProvider] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[IsAgency] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[DSSIsDefined] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[DSSCostingRollup] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[DSSRate] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[OBIsDefined] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[FlexBucketGUID] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[SPIsDefined] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[Rollup] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[Variability] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[MemberGUID] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[FlexJobCodeGroupID] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[HistoryItemGUID] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[WorkWeekOverrideID] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[DSSCostingRollup2] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[DSSCostingRollup3] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[FWIsDefined] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[PRIsDefined] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[CIIsDefined] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[IsPatientCare] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[IsBedside] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[IsLicensed] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[ManagementLevel] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[DSSCostComponentID] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[SkillMix] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[DSSJobCodeRollup1ID] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[DSSJobCodeRollup2ID] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[DSSJobCodeRollup3ID] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[SPHJobCodeRollupID] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[SPHJobCodeRollupIsValidated] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[TransactionID] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[SPHVariability] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[StaffingCategoryID] + ,grpAAD69FC0ED76427EA52ED356470BFE0A.[SPHJobCodeRollupConfidenceScore] + ,ISNULL([JobCodeGrp].[Name], 'Not Specified') as [JobCodeGroup] + ,ISNULL([FLEXJOBCODEGROUP].[Name], 'Not Specified') as [FlexJobCodeGroup] + ,ISNULL([DSJCROL].[Name], 'Not Specified') as [DSSCostComponent] + ,ISNULL([DSJCROL_1].[Name], 'Not Specified') as [DSSJobCodeRollup1] + ,ISNULL([DSSJOBCODEROLLUP2].[Name], 'Not Specified') as [DSSJobCodeRollup2] + ,ISNULL([DSSJOBCODEROLLUP3].[Name], 'Not Specified') as [DSSJobCodeRollup3] + ,ISNULL([SPHJOBCODEROLLUP].[Name], 'Not Specified') as [SPHJobCodeRollupName] + ,ISNULL([SPHJOBCODEROLLUP].[SPHCostComponent], 'Not Specified') as [SPHCostComponent] + ,ISNULL([STAFFINGCATEGORY].[Name], 'Not Specified') as [StaffingCategory] +, [grpAAD69FC0ED76427EA52ED356470BFE0A].[Version]FROM [fw].[DimJobCode] grpAAD69FC0ED76427EA52ED356470BFE0A (readuncommitted) + LEFT JOIN [fw].[viewDimJobCodeGroup] [JobCodeGrp] on [JobCodeGrp].[JobCodeGroupID] = [grpAAD69FC0ED76427EA52ED356470BFE0A].[JobCodeGroupID] + LEFT JOIN [fw].[viewDimFlexJobCodeGroup] [FLEXJOBCODEGROUP] on [FLEXJOBCODEGROUP].[FlexJobCodeGroupID] = [grpAAD69FC0ED76427EA52ED356470BFE0A].[FlexJobCodeGroupID] + INNER JOIN [dss].[viewDimDSSJobCodeRollup1] [DSJCROL] on [DSJCROL].[DSSJobCodeRollup1ID] = [grpAAD69FC0ED76427EA52ED356470BFE0A].[DSSCostComponentID] + INNER JOIN [dss].[viewDimDSSJobCodeRollup1] [DSJCROL_1] on [DSJCROL_1].[DSSJobCodeRollup1ID] = [grpAAD69FC0ED76427EA52ED356470BFE0A].[DSSJobCodeRollup1ID] + LEFT JOIN [dss].[viewDimJobCodeRollup2] [DSSJOBCODEROLLUP2] on [DSSJOBCODEROLLUP2].[DSSJobCodeRollup2ID] = [grpAAD69FC0ED76427EA52ED356470BFE0A].[DSSJobCodeRollup2ID] + INNER JOIN [dss].[viewDimJobCodeRollup3] [DSSJOBCODEROLLUP3] on [DSSJOBCODEROLLUP3].[DSSJobCodeRollup3ID] = [grpAAD69FC0ED76427EA52ED356470BFE0A].[DSSJobCodeRollup3ID] + INNER JOIN [fw].[viewDimSPHJobCodeRollup] [SPHJOBCODEROLLUP] on [SPHJOBCODEROLLUP].[SPHJobCodeRollupID] = [grpAAD69FC0ED76427EA52ED356470BFE0A].[SPHJobCodeRollupID] + INNER JOIN [fw].[viewDimStaffingCategory_auto] [STAFFINGCATEGORY] on [STAFFINGCATEGORY].[StaffingCategoryID] = [grpAAD69FC0ED76427EA52ED356470BFE0A].[StaffingCategoryID] +GO + + +--------------------------------------------- + +-- fw.viewDimJobCodeGroup +CREATE VIEW [fw].[viewDimJobCodeGroup] +AS +SELECT + +[JobCodeGroupID], +[Category], +[Name], +[SPStaffType], +[SPSalariesFinancialReportingID], +[SPFTEsFinancialReportingID], +[SPDefaultVolumeDriver], +[CAPFinancialReportingID], +[IsSP], +[IsCapital], +[IsOB], +[IsMR], +[IsDSS], +[SortOrder], + COALESCE([SPSalariesFinancialReporting],'') as [SPSalariesFinancialReporting], + COALESCE([SPFTEsFinancialReporting],'') as [SPFTEsFinancialReporting], + COALESCE([CAPFinancialReporting],'') as [CAPFinancialReporting], +[MemberGUID], +[WorkWeekOverrideID] ,[HistoryItemGUID] + +FROM [fw].[DimJobCodeGroup] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimJobCodeGroupPH +CREATE VIEW [fw].[viewDimJobCodeGroupPH] +AS +SELECT + +[JobCodeGroupPHID], +[MemberGUID], +[Name] ,[HistoryItemGUID] + +FROM [fw].[DimJobCodeGroupPH] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimJobCodeGroupPH_source +CREATE VIEW [fw].[viewDimJobCodeGroupPH_source] +AS +SELECT + grpDC670445EFFE4323B34B44C1C17F8B0C.[JobCodeGroupPHID] + ,grpDC670445EFFE4323B34B44C1C17F8B0C.[MemberGUID] +, [grpDC670445EFFE4323B34B44C1C17F8B0C].[HistoryItemGUID]FROM [fw].[DimJobCodeGroupPH] grpDC670445EFFE4323B34B44C1C17F8B0C (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimJobCodeGroup_source +CREATE VIEW [fw].[viewDimJobCodeGroup_source] +AS +SELECT + grpCC17B05111184E228AA364D935410A33.[JobCodeGroupID] + ,grpCC17B05111184E228AA364D935410A33.[MemberGUID] + ,ISNULL([SPFINANCIALREP].[Name], 'Not Specified') as [SPSalariesFinancialReporting] + ,ISNULL([SPFINANCIALREP_1].[Name], 'Not Specified') as [SPFTEsFinancialReporting] + ,ISNULL([CAPFINANCIALREP].[Name], 'Not Specified') as [CAPFinancialReporting] +, [grpCC17B05111184E228AA364D935410A33].[HistoryItemGUID]FROM [fw].[DimJobCodeGroup] grpCC17B05111184E228AA364D935410A33 (readuncommitted) + LEFT JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP] on [SPFINANCIALREP].[FinancialReportingID] = [grpCC17B05111184E228AA364D935410A33].[SPSalariesFinancialReportingID] + INNER JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP_1] on [SPFINANCIALREP_1].[FinancialReportingID] = [grpCC17B05111184E228AA364D935410A33].[SPFTEsFinancialReportingID] + INNER JOIN [cap].[viewDimFinancialReporting] [CAPFINANCIALREP] on [CAPFINANCIALREP].[FinancialReportingID] = [grpCC17B05111184E228AA364D935410A33].[CAPFinancialReportingID] +GO + + +--------------------------------------------- + +-- fw.viewDimJobCodePH +CREATE VIEW [fw].[viewDimJobCodePH] +AS +SELECT + grpB5738AC6D8C2411DAAA2747D17D10AC1.[JobCodePHID] + ,grpB5738AC6D8C2411DAAA2747D17D10AC1.[Name] + ,grpB5738AC6D8C2411DAAA2747D17D10AC1.[MemberGUID] +FROM [fw].[DimJobCodePH] grpB5738AC6D8C2411DAAA2747D17D10AC1 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimLineNumber +CREATE VIEW [fw].[viewDimLineNumber] +AS +SELECT + grpFF26C92DA42548758DE9652EF433A8D7.[LineNumberID] + ,grpFF26C92DA42548758DE9652EF433A8D7.[MemberGUID] + ,grpFF26C92DA42548758DE9652EF433A8D7.[HistoryItemGUID] +FROM [fw].[DimLineNumber] grpFF26C92DA42548758DE9652EF433A8D7 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimManufacturer +--Last Modified 8/11/2015 12:21 PM +CREATE VIEW [fw].[viewDimManufacturer] +AS +SELECT + grp4B506B64C5C141E3A75D30F00344E01C.[ManufacturerID] + ,coalesce(grp4B506B64C5C141E3A75D30F00344E01C.[Name],'') as [Name] + ,grp4B506B64C5C141E3A75D30F00344E01C.[Code] + ,grp4B506B64C5C141E3A75D30F00344E01C.[Description] + ,grp4B506B64C5C141E3A75D30F00344E01C.[MemberGUID] + ,grp4B506B64C5C141E3A75D30F00344E01C.[TransactionID] + ,grp4B506B64C5C141E3A75D30F00344E01C.[HistoryItemGUID] +FROM [fw].[DimManufacturer] grp4B506B64C5C141E3A75D30F00344E01C (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimMedicalSurgical +CREATE VIEW [fw].[viewDimMedicalSurgical] +AS +SELECT + grp78A79D4B760C4847814C610A03087D52.[MedicalSurgicalID] + ,grp78A79D4B760C4847814C610A03087D52.[Name] + ,grp78A79D4B760C4847814C610A03087D52.[MemberGUID] + ,grp78A79D4B760C4847814C610A03087D52.[HistoryItemGUID] + ,grp78A79D4B760C4847814C610A03087D52.[TransactionID] + ,grp78A79D4B760C4847814C610A03087D52.[Code] + ,grp78A79D4B760C4847814C610A03087D52.[SortOrder] +FROM [fw].[DimMedicalSurgical] grp78A79D4B760C4847814C610A03087D52 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimModelingServiceLine +CREATE VIEW [fw].[viewDimModelingServiceLine] +AS +SELECT + +[ModelingServiceLineID], + COALESCE([Name],'') as [Name], +[PatientClassID], +[ServiceLineID], +[MedicalSurgicalID], +[AgeCohortID], + COALESCE([SortOrder],'') as [SortOrder], + COALESCE([PatientClass],'') as [PatientClass], + COALESCE([PatientClassCode],'') as [PatientClassCode], +[PatientClassSortOrder], + COALESCE([ServiceLine],'') as [ServiceLine], + COALESCE([ServiceLineCode],'') as [ServiceLineCode], +[ServiceLineSortOrder], + COALESCE([ServiceLineRollup],'') as [ServiceLineRollup], +[ServiceLineRollupSortOrder], + COALESCE([MedicalSurgical],'') as [MedicalSurgical], + COALESCE([MedicalSurgicalCode],'') as [MedicalSurgicalCode], +[MedicalSurgicalSortOrder], + COALESCE([AgeCohort],'') as [AgeCohort], + COALESCE([AgeCohortCode],'') as [AgeCohortCode], +[AgeCohortSortOrder], +[TransactionID], +[MemberGUID], +[HistoryItemGUID] +FROM [fw].[DimModelingServiceLine] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimModelingServiceLinePH +CREATE VIEW [fw].[viewDimModelingServiceLinePH] +AS +SELECT + grp0760A281D6F040D39AF8F219869FCF1B.[ModelingServiceLinePHID] + ,grp0760A281D6F040D39AF8F219869FCF1B.[Name] + ,grp0760A281D6F040D39AF8F219869FCF1B.[MemberGUID] + ,grp0760A281D6F040D39AF8F219869FCF1B.[HistoryItemGUID] + ,grp0760A281D6F040D39AF8F219869FCF1B.[TransactionID] +FROM [fw].[DimModelingServiceLinePH] grp0760A281D6F040D39AF8F219869FCF1B (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimModelingServiceLine_source +CREATE VIEW [fw].[viewDimModelingServiceLine_source] +AS +SELECT + grpB6F9DA58A60D41B485FFBF15F95D40EF.[ModelingServiceLineID] + ,grpB6F9DA58A60D41B485FFBF15F95D40EF.[Name] + ,grpB6F9DA58A60D41B485FFBF15F95D40EF.[SortOrder] + ,grpB6F9DA58A60D41B485FFBF15F95D40EF.[TransactionID] + ,grpB6F9DA58A60D41B485FFBF15F95D40EF.[MemberGUID] + ,grpB6F9DA58A60D41B485FFBF15F95D40EF.[HistoryItemGUID] + ,ISNULL([PATIENTCLASS].[Name], 'Not Specified') as [PatientClass] + ,ISNULL([PATIENTCLASS].[Code], 'Not Specified') as [PatientClassCode] + ,ISNULL([PATIENTCLASS].[SortOrder], 0) as [PatientClassSortOrder] + ,ISNULL([SL].[Name], 'Not Specified') as [ServiceLine] + ,ISNULL([SL].[Code], 'Not Specified') as [ServiceLineCode] + ,ISNULL([SL].[SortOrder], 0) as [ServiceLineSortOrder] + ,ISNULL([SL].[Rollup], 'Not Specified') as [ServiceLineRollup] + ,ISNULL([SL].[RollupSortOrder], 0) as [ServiceLineRollupSortOrder] + ,ISNULL([MEDICALSURGICAL].[Name], 'Not Specified') as [MedicalSurgical] + ,ISNULL([MEDICALSURGICAL].[Code], 'Not Specified') as [MedicalSurgicalCode] + ,ISNULL([MEDICALSURGICAL].[SortOrder], 0) as [MedicalSurgicalSortOrder] + ,ISNULL([AGECOHORT].[Name], 'Not Specified') as [AgeCohort] + ,ISNULL([AGECOHORT].[Code], 'Not Specified') as [AgeCohortCode] + ,ISNULL([AGECOHORT].[SortOrder], 0) as [AgeCohortSortOrder] +FROM [fw].[DimModelingServiceLine] grpB6F9DA58A60D41B485FFBF15F95D40EF (readuncommitted) + INNER JOIN [fw].[viewDimPatientClass] [PATIENTCLASS] on [PATIENTCLASS].[PatientClassID] = [grpB6F9DA58A60D41B485FFBF15F95D40EF].[PatientClassID] + INNER JOIN [fw].[viewDimServiceLine] [SL] on [SL].[ServiceLineID] = [grpB6F9DA58A60D41B485FFBF15F95D40EF].[ServiceLineID] + INNER JOIN [fw].[viewDimMedicalSurgical] [MEDICALSURGICAL] on [MEDICALSURGICAL].[MedicalSurgicalID] = [grpB6F9DA58A60D41B485FFBF15F95D40EF].[MedicalSurgicalID] + INNER JOIN [fw].[viewDimAgeCohort] [AGECOHORT] on [AGECOHORT].[AgeCohortID] = [grpB6F9DA58A60D41B485FFBF15F95D40EF].[AgeCohortID] +GO + + +--------------------------------------------- + +-- fw.viewDimOpportunity +CREATE VIEW [fw].[viewDimOpportunity] +AS +SELECT + grpB205B5DB5DD943E7B55EB4AC84FCFF14.[OpportunityKey] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[Name] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[MemberGUID] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[MemberGUID] [OpportunityGUID] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[HistoryItemGUID] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[TransactionID] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[EntityID] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[SourceOfSavingsID] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[IsHidden] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[HasInitiative] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeGUID] + ,ISNULL([ENT].[Name], 'Not Specified') AS [Entity] + ,ISNULL([ENT].[Code], 'Not Specified') AS [Code] + ,ISNULL([ENT].[Description], 'Not Specified') AS [Description] + ,ISNULL([ENT].[SortOrder], 0) AS [SortOrder] + ,ISNULL([ENT].[EntityType], 0) AS [EntityType] + ,ISNULL([ENT].[IsActive], 0) AS [IsActive] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[SourceOfSavings] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[Initiative] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeStatus] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.Owner + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.CostLeader + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.ExecutiveSponsor + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.Workstream + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.DateCreated + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.BaselineStartDate + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.BaselineEndDate + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.SavingsIdentified + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.SavingsGoal + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.AnnualGoal + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.SavingsEstimate + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.InitiativeStatusID + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.InitiativeRollup1Id + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.InitiativeRollup1 + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.InitiativeRollup2Id + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.InitiativeRollup2 + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.InitiativeRollup3Id + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.InitiativeRollup3 +FROM [fw].[DimOpportunity] grpB205B5DB5DD943E7B55EB4AC84FCFF14 +LEFT OUTER JOIN [fw].[viewDimEntity] [ENT] ON [ENT].[EntityID] = [grpB205B5DB5DD943E7B55EB4AC84FCFF14].[EntityID] +GO + + +--------------------------------------------- + +-- fw.viewDimOpportunity_auto +--Last Modified 6/12/2024 5:33 PM +CREATE VIEW [fw].[viewDimOpportunity_auto] +AS +SELECT + grpB205B5DB5DD943E7B55EB4AC84FCFF14.[OpportunityKey] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[Name] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[TransactionID] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[MemberGUID] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[HistoryItemGUID] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[DateCreated] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[BaselineStartDate] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[OpportunityGUID] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[AnnualGoal] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[SavingsEstimate] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeRollup1] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeRollup2] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[BaselineEndDate] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[EntityID] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[SavingsIdentified] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeRollup3] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeRollup1Id] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[SavingsGoal] + ,coalesce(grpB205B5DB5DD943E7B55EB4AC84FCFF14.[Entity],'') as [Entity] + ,coalesce(grpB205B5DB5DD943E7B55EB4AC84FCFF14.[Code],'') as [Code] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeRollup2Id] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeRollup3Id] + ,coalesce(grpB205B5DB5DD943E7B55EB4AC84FCFF14.[Description],'') as [Description] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[SortOrder] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeStatusID] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[EntityType] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[IsActive] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[SourceOfSavingsID] + ,coalesce(grpB205B5DB5DD943E7B55EB4AC84FCFF14.[SourceOfSavings],'') as [SourceOfSavings] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[IsHidden] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[HasInitiative] + ,grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeGUID] + ,coalesce(grpB205B5DB5DD943E7B55EB4AC84FCFF14.[Initiative],'') as [Initiative] + ,coalesce(grpB205B5DB5DD943E7B55EB4AC84FCFF14.[InitiativeStatus],'') as [InitiativeStatus] + ,coalesce(grpB205B5DB5DD943E7B55EB4AC84FCFF14.[CostLeader],'') as [CostLeader] + ,coalesce(grpB205B5DB5DD943E7B55EB4AC84FCFF14.[Owner],'') as [Owner] + ,coalesce(grpB205B5DB5DD943E7B55EB4AC84FCFF14.[ExecutiveSponsor],'') as [ExecutiveSponsor] + ,coalesce(grpB205B5DB5DD943E7B55EB4AC84FCFF14.[Workstream],'') as [Workstream] +FROM [fw].[viewDimOpportunity] grpB205B5DB5DD943E7B55EB4AC84FCFF14 +GO + + +--------------------------------------------- + +-- fw.viewDimPatientClass +CREATE VIEW [fw].[viewDimPatientClass] +AS +SELECT + grp30F99B15877C4FA6B62ED8D6E563E438.[PatientClassID] + ,grp30F99B15877C4FA6B62ED8D6E563E438.[Name] + ,grp30F99B15877C4FA6B62ED8D6E563E438.[Code] + ,grp30F99B15877C4FA6B62ED8D6E563E438.[SortOrder] + ,grp30F99B15877C4FA6B62ED8D6E563E438.[IsActive] + ,grp30F99B15877C4FA6B62ED8D6E563E438.[IncludeInAdjustedCalculations] + ,grp30F99B15877C4FA6B62ED8D6E563E438.[TransactionID] + ,grp30F99B15877C4FA6B62ED8D6E563E438.[MemberGUID] + ,grp30F99B15877C4FA6B62ED8D6E563E438.[OBServiceLinePrimaryVolumeAccountID] + ,grp30F99B15877C4FA6B62ED8D6E563E438.[HistoryItemGUID] +FROM [fw].[DimPatientClass] grp30F99B15877C4FA6B62ED8D6E563E438 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimPatientReimbursementGroup +CREATE VIEW [fw].[viewDimPatientReimbursementGroup] +AS +SELECT + +[PatientReimbursementGroupID], + COALESCE([Name],'') as [Name], +[PatientClassID], +[CareSettingID], + COALESCE([Code],'') as [Code], + COALESCE([SortOrder],'') as [SortOrder], + COALESCE([PatientClass],'') as [PatientClass], + COALESCE([PatientClassCode],'') as [PatientClassCode], +[PatientClassSortOrder], + COALESCE([CareSetting],'') as [CareSetting], + COALESCE([CareSettingCode],'') as [CareSettingCode], +[CareSettingSortOrder], +[TransactionID], +[MemberGUID], +[HistoryItemGUID] +FROM [fw].[DimPatientReimbursementGroup] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimPatientReimbursementGroupPH +CREATE VIEW [fw].[viewDimPatientReimbursementGroupPH] +AS +SELECT + grp7A426BF8FC8F4EBF8A76AA76229A06F2.[PatientReimbursementGroupPHID] + ,grp7A426BF8FC8F4EBF8A76AA76229A06F2.[Name] + ,grp7A426BF8FC8F4EBF8A76AA76229A06F2.[MemberGUID] + ,grp7A426BF8FC8F4EBF8A76AA76229A06F2.[HistoryItemGUID] + ,grp7A426BF8FC8F4EBF8A76AA76229A06F2.[TransactionID] +FROM [fw].[DimPatientReimbursementGroupPH] grp7A426BF8FC8F4EBF8A76AA76229A06F2 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimPatientReimbursementGroup_source +CREATE VIEW [fw].[viewDimPatientReimbursementGroup_source] +AS +SELECT + grp795F9572D0D04ED390051C3D7CD34946.[PatientReimbursementGroupID] + ,grp795F9572D0D04ED390051C3D7CD34946.[Name] + ,grp795F9572D0D04ED390051C3D7CD34946.[Code] + ,grp795F9572D0D04ED390051C3D7CD34946.[SortOrder] + ,grp795F9572D0D04ED390051C3D7CD34946.[TransactionID] + ,grp795F9572D0D04ED390051C3D7CD34946.[MemberGUID] + ,grp795F9572D0D04ED390051C3D7CD34946.[HistoryItemGUID] + ,ISNULL([PATIENTCLASS].[Name], 'Not Specified') as [PatientClass] + ,ISNULL([PATIENTCLASS].[Code], 'Not Specified') as [PatientClassCode] + ,ISNULL([PATIENTCLASS].[SortOrder], 0) as [PatientClassSortOrder] + ,ISNULL([CARESETTING].[Name], 'Not Specified') as [CareSetting] + ,ISNULL([CARESETTING].[Code], 'Not Specified') as [CareSettingCode] + ,ISNULL([CARESETTING].[SortOrder], 0) as [CareSettingSortOrder] +FROM [fw].[DimPatientReimbursementGroup] grp795F9572D0D04ED390051C3D7CD34946 (readuncommitted) + LEFT JOIN [fw].[viewDimPatientClass] [PATIENTCLASS] on [PATIENTCLASS].[PatientClassID] = [grp795F9572D0D04ED390051C3D7CD34946].[PatientClassID] + LEFT JOIN [fw].[viewDimCareSetting] [CARESETTING] on [CARESETTING].[CareSettingID] = [grp795F9572D0D04ED390051C3D7CD34946].[CareSettingID] +GO + + +--------------------------------------------- + +-- fw.viewDimPatientType +--Last Modified 11/16/2020 3:28 PM +CREATE VIEW [fw].[viewDimPatientType] +AS +SELECT + grpF76658C4B97240B881CAF29A84373B98.[PatientTypeID] + ,coalesce(grpF76658C4B97240B881CAF29A84373B98.[Name],'') as [Name] + ,grpF76658C4B97240B881CAF29A84373B98.[Code] + ,grpF76658C4B97240B881CAF29A84373B98.[Description] + ,grpF76658C4B97240B881CAF29A84373B98.[PatientTypeRollupID] + ,grpF76658C4B97240B881CAF29A84373B98.[MemberGUID] + ,grpF76658C4B97240B881CAF29A84373B98.[HistoryItemGUID] + ,grpF76658C4B97240B881CAF29A84373B98.[DSSRollup] + ,grpF76658C4B97240B881CAF29A84373B98.[TransactionID] + ,ISNULL([PatientTyRo].[Name], 'Not Specified') as [PatientTypeRollupName] + ,ISNULL([PatientTyRo].[Sg2PatientTypeRollup], 'Not Specified') as [Sg2PatientTypeRollup] +FROM [fw].[DimPatientType] grpF76658C4B97240B881CAF29A84373B98 (readuncommitted) + LEFT JOIN [fw].[viewDimPatientTypeRollup] [PatientTyRo] on [PatientTyRo].[PatientTypeRollupID] = [grpF76658C4B97240B881CAF29A84373B98].[PatientTypeRollupID] +GO + + +--------------------------------------------- + +-- fw.viewDimPatientTypeRollup +CREATE VIEW [fw].[viewDimPatientTypeRollup] +AS +SELECT + +[PatientTypeRollupID], +[Type], +[Name], +[PatientClassID], +[SortOrder], +[IsSP], +[CareSettingID], +[IsCapital], +[IsOB], +[IsMR], +[IsDSS], +[SPChargesFinancialReportingID], +[SPContractualsFinancialReportingID], +[SPPrimaryStatisticFinancialReportingID], +[SPSecondaryStatisticFinancialReportingID], +[SPTertiaryStatisticFinancialReportingID], +[CAPChargesFinancialReportingID], +[CAPContractualsFinancialReportingID], +[CAPPrimaryStatisticFinancialReportingID], +[CAPSecondaryStatisticFinancialReportingID], + COALESCE([SPChargesFinancialReporting],'') as [SPChargesFinancialReporting], + COALESCE([SPContractualsFinancialReporting],'') as [SPContractualsFinancialReporting], + COALESCE([SPPrimaryStatisticFinancialReporting],'') as [SPPrimaryStatisticFinancialReporting], + COALESCE([PatientClassName],'') as [PatientClassName], + COALESCE([CareSettingName],'') as [CareSettingName], + COALESCE([SPSecondaryStatisticFinancialReporting],'') as [SPSecondaryStatisticFinancialReporting], + COALESCE([SPTertiaryStatisticFinancialReporting],'') as [SPTertiaryStatisticFinancialReporting], + COALESCE([SPPrimaryStatisticFinancialReportingLineName],'') as [SPPrimaryStatisticFinancialReportingLineName], + COALESCE([SPSecondaryStatisticFinancialReportingLineName],'') as [SPSecondaryStatisticFinancialReportingLineName], + COALESCE([SPTertiaryStatisticFinancialReportingLineName],'') as [SPTertiaryStatisticFinancialReportingLineName], + COALESCE([CAPChargesFinancialReporting],'') as [CAPChargesFinancialReporting], + COALESCE([CAPContractualsFinancialReporting],'') as [CAPContractualsFinancialReporting], + COALESCE([CAPPrimaryStatisticFinancialReporting],'') as [CAPPrimaryStatisticFinancialReporting], + COALESCE([CAPSecondaryStatisticFinancialReporting],'') as [CAPSecondaryStatisticFinancialReporting], +[MemberGUID], +[HistoryItemGUID], + COALESCE([CAPPrimaryStatisticFinancialReportingLineName],'') as [CAPPrimaryStatisticFinancialReportingLineName], + COALESCE([CAPSecondaryStatisticFinancialReportingLineName],'') as [CAPSecondaryStatisticFinancialReportingLineName], +[Sg2PatientTypeRollup] ,[Version] + +FROM [fw].[DimPatientTypeRollup] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimPatientTypeRollupPH +CREATE VIEW [fw].[viewDimPatientTypeRollupPH] +AS +SELECT + grpB3573F00604F4FA28AF6435494C52F6C.[PatientTypeRollupPHID] + ,grpB3573F00604F4FA28AF6435494C52F6C.[Name] + ,grpB3573F00604F4FA28AF6435494C52F6C.[MemberGUID] + ,grpB3573F00604F4FA28AF6435494C52F6C.[HistoryItemGUID] +FROM [fw].[DimPatientTypeRollupPH] grpB3573F00604F4FA28AF6435494C52F6C (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimPatientTypeRollup_source +CREATE VIEW [fw].[viewDimPatientTypeRollup_source] +AS +SELECT + grpFE81F461D5C6457B8209E3E5F86A30DB.[PatientTypeRollupID] + ,grpFE81F461D5C6457B8209E3E5F86A30DB.[MemberGUID] + ,grpFE81F461D5C6457B8209E3E5F86A30DB.[HistoryItemGUID] + ,ISNULL([PATIENTCLASS].[Name], 'Not Specified') as [PatientClassName] + ,ISNULL([CARESETTING].[Name], 'Not Specified') as [CareSettingName] + ,ISNULL([SPFINANCIALREP].[Name], 'Not Specified') as [SPChargesFinancialReporting] + ,ISNULL([SPFINANCIALREP_1].[Name], 'Not Specified') as [SPContractualsFinancialReporting] + ,ISNULL([SPFINANCIALREP_2].[Name], 'Not Specified') as [SPPrimaryStatisticFinancialReporting] + ,ISNULL([SPFINANCIALREP_2].[LineName], 'Not Specified') as [SPPrimaryStatisticFinancialReportingLineName] + ,ISNULL([SPFINANCIALREP_3].[Name], 'Not Specified') as [SPSecondaryStatisticFinancialReporting] + ,ISNULL([SPFINANCIALREP_3].[LineName], 'Not Specified') as [SPSecondaryStatisticFinancialReportingLineName] + ,ISNULL([SPFINANCIALREP_4].[Name], 'Not Specified') as [SPTertiaryStatisticFinancialReporting] + ,ISNULL([SPFINANCIALREP_4].[LineName], 'Not Specified') as [SPTertiaryStatisticFinancialReportingLineName] + ,ISNULL([CAPFINANCIALREP].[Name], 'Not Specified') as [CAPChargesFinancialReporting] + ,ISNULL([CAPFINANCIALREP_1].[Name], 'Not Specified') as [CAPContractualsFinancialReporting] + ,ISNULL([CAPFINANCIALREP_2].[Name], 'Not Specified') as [CAPPrimaryStatisticFinancialReporting] + ,ISNULL([CAPFINANCIALREP_2].[LineName], 'Not Specified') as [CAPPrimaryStatisticFinancialReportingLineName] + ,ISNULL([CAPFINANCIALREP_3].[Name], 'Not Specified') as [CAPSecondaryStatisticFinancialReporting] + ,ISNULL([CAPFINANCIALREP_3].[LineName], 'Not Specified') as [CAPSecondaryStatisticFinancialReportingLineName] +, [grpFE81F461D5C6457B8209E3E5F86A30DB].[Version]FROM [fw].[DimPatientTypeRollup] grpFE81F461D5C6457B8209E3E5F86A30DB (readuncommitted) + INNER JOIN [fw].[viewDimPatientClass] [PATIENTCLASS] on [PATIENTCLASS].[PatientClassID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[PatientClassID] + INNER JOIN [fw].[viewDimCareSetting] [CARESETTING] on [CARESETTING].[CareSettingID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[CareSettingID] + INNER JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP] on [SPFINANCIALREP].[FinancialReportingID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[SPChargesFinancialReportingID] + INNER JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP_1] on [SPFINANCIALREP_1].[FinancialReportingID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[SPContractualsFinancialReportingID] + INNER JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP_2] on [SPFINANCIALREP_2].[FinancialReportingID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[SPPrimaryStatisticFinancialReportingID] + INNER JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP_3] on [SPFINANCIALREP_3].[FinancialReportingID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[SPSecondaryStatisticFinancialReportingID] + INNER JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP_4] on [SPFINANCIALREP_4].[FinancialReportingID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[SPTertiaryStatisticFinancialReportingID] + INNER JOIN [cap].[viewDimFinancialReporting] [CAPFINANCIALREP] on [CAPFINANCIALREP].[FinancialReportingID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[CAPChargesFinancialReportingID] + INNER JOIN [cap].[viewDimFinancialReporting] [CAPFINANCIALREP_1] on [CAPFINANCIALREP_1].[FinancialReportingID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[CAPContractualsFinancialReportingID] + INNER JOIN [cap].[viewDimFinancialReporting] [CAPFINANCIALREP_2] on [CAPFINANCIALREP_2].[FinancialReportingID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[CAPPrimaryStatisticFinancialReportingID] + INNER JOIN [cap].[viewDimFinancialReporting] [CAPFINANCIALREP_3] on [CAPFINANCIALREP_3].[FinancialReportingID] = [grpFE81F461D5C6457B8209E3E5F86A30DB].[CAPSecondaryStatisticFinancialReportingID] +GO + + +--------------------------------------------- + +-- fw.viewDimPayCode +CREATE VIEW [fw].[viewDimPayCode] +AS +SELECT + +[PayCodeID], + COALESCE([Name],'') as [Name], +[Description], +[PayCode], +[PayCodeGroupID], +[IsAccrued], +[IsHoursIgnored], +[IsDollarsIgnored], +[DSSIsDefined], +[DSSPayCodeRollup1ID], +[DSSCostingRollup], + COALESCE([DSSPayCodeRollup1],'') as [DSSPayCodeRollup1], +[OBIsDefined], +[OBForecastDetailID], +[SPIsDefined], +[ImportIDAlt], +[IsPayCodeGroup], +[Rollup], +[SubRollup], + COALESCE([PayCodeGroup],'') as [PayCodeGroup], +[PayCodeGroupSortOrder], + COALESCE([PayClass],'') as [PayClass], + COALESCE([ProductiveClass],'') as [ProductiveClass], +[Variability], + COALESCE([ReportingCategory],'') as [ReportingCategory], +[MemberGUID], +[HistoryItemGUID], +[DSSCostingRollup2], +[FWIsDefined], +[DSSPayCodeRollup2ID], + COALESCE([DSSPayCodeRollup2],'') as [DSSPayCodeRollup2], +[TransactionID], +[SPHPayCodeRollupIsValidated], +[ProviderLineItemID], + COALESCE([ProviderLineItem],'') as [ProviderLineItem], + COALESCE([SPHProductiveClass],'') as [SPHProductiveClass], +[SPHPayCodeRollupID], + COALESCE([SPHPayCodeRollupName],'') as [SPHPayCodeRollupName], +[SPHPayCodeRollupConfidenceScore] ,[Version] + +FROM [fw].[DimPayCode] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimPayCodeGroup +--Last Modified 3/20/2024 5:05 PM +CREATE VIEW [fw].[viewDimPayCodeGroup] +AS +SELECT + grpB9F3A1C540C14A449028ADA57350A79D.[PayCodeGroupID] + ,grpB9F3A1C540C14A449028ADA57350A79D.[Name] + ,grpB9F3A1C540C14A449028ADA57350A79D.[SortOrder] + ,grpB9F3A1C540C14A449028ADA57350A79D.[PayCodeGroupCode] + ,grpB9F3A1C540C14A449028ADA57350A79D.[PayClass] + ,grpB9F3A1C540C14A449028ADA57350A79D.[ProductiveClassID] + ,grpB9F3A1C540C14A449028ADA57350A79D.[IsVariable] + ,grpB9F3A1C540C14A449028ADA57350A79D.[IsOvertime] + ,grpB9F3A1C540C14A449028ADA57350A79D.[IsAgency] + ,grpB9F3A1C540C14A449028ADA57350A79D.[IsExcludedFromBenefits] + ,grpB9F3A1C540C14A449028ADA57350A79D.[IsDirect] + ,grpB9F3A1C540C14A449028ADA57350A79D.[IsPremium] + ,grpB9F3A1C540C14A449028ADA57350A79D.[WageRateMultiplier] + ,grpB9F3A1C540C14A449028ADA57350A79D.[DefaultPayCodeID] + ,grpB9F3A1C540C14A449028ADA57350A79D.[ReportingCategory] + ,grpB9F3A1C540C14A449028ADA57350A79D.[MemberGUID] + ,grpB9F3A1C540C14A449028ADA57350A79D.[TransactionID] + ,grpB9F3A1C540C14A449028ADA57350A79D.[HistoryItemGUID] + ,ISNULL([PRODUCTIVECL].[Name], 'Not Specified') as [ProductiveClass] + ,ISNULL([PAYCODE].[Name], 'Not Specified') as [DefaultPayCode] +, [grpB9F3A1C540C14A449028ADA57350A79D].[Version]FROM [fw].[DimPayCodeGroup] grpB9F3A1C540C14A449028ADA57350A79D (readuncommitted) + LEFT JOIN [fw].[viewDimProductiveClass] [PRODUCTIVECL] on [PRODUCTIVECL].[ProductiveClassID] = [grpB9F3A1C540C14A449028ADA57350A79D].[ProductiveClassID] + LEFT JOIN [fw].[viewDimPayCode] [PAYCODE] on [PAYCODE].[PayCodeID] = [grpB9F3A1C540C14A449028ADA57350A79D].[DefaultPayCodeID] +GO + + +--------------------------------------------- + +-- fw.viewDimPayCodeGroupPH +CREATE VIEW [fw].[viewDimPayCodeGroupPH] +AS +SELECT + grpCAA5DF4BE5434757B51AD811109F16DB.[PayCodeGroupPHID] + ,grpCAA5DF4BE5434757B51AD811109F16DB.[Name] + ,grpCAA5DF4BE5434757B51AD811109F16DB.[TransactionID] + ,grpCAA5DF4BE5434757B51AD811109F16DB.[MemberGUID] + ,grpCAA5DF4BE5434757B51AD811109F16DB.[HistoryItemGUID] +FROM [fw].[DimPayCodeGroupPH] grpCAA5DF4BE5434757B51AD811109F16DB (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimPayCode_source +CREATE VIEW [fw].[viewDimPayCode_source] +AS +SELECT + grpB323F295F71F4248991D24C571ED8831.[PayCodeID] + ,grpB323F295F71F4248991D24C571ED8831.[Name] + ,grpB323F295F71F4248991D24C571ED8831.[MemberGUID] + ,grpB323F295F71F4248991D24C571ED8831.[HistoryItemGUID] + ,grpB323F295F71F4248991D24C571ED8831.[TransactionID] + ,ISNULL([PCG].[Name], 'Not Specified') as [PayCodeGroup] + ,ISNULL([PCG].[SortOrder], 0) as [PayCodeGroupSortOrder] + ,ISNULL([PCG].[PayClass], 'Not Specified') as [PayClass] + ,ISNULL([PCG].[ProductiveClass], 'Not Specified') as [ProductiveClass] + ,ISNULL([PCG].[ReportingCategory], 'Not Specified') as [ReportingCategory] + ,ISNULL([DSSPAYCODEROLLUP1].[Name], 'Not Specified') as [DSSPayCodeRollup1] + ,ISNULL([DSSPAYCODEROLLUP2].[Name], 'Not Specified') as [DSSPayCodeRollup2] + ,ISNULL([PROVIDERLI].[Description], 'Not Specified') as [ProviderLineItem] + ,ISNULL([SPHPAYCODEROLLUP].[SPHProductiveClass], 'Not Specified') as [SPHProductiveClass] + ,ISNULL([SPHPAYCODEROLLUP].[Name], 'Not Specified') as [SPHPayCodeRollupName] +, [grpB323F295F71F4248991D24C571ED8831].[Version]FROM [fw].[DimPayCode] grpB323F295F71F4248991D24C571ED8831 (readuncommitted) + LEFT JOIN [fw].[viewDimPayCodeGroup] [PCG] on [PCG].[PayCodeGroupID] = [grpB323F295F71F4248991D24C571ED8831].[PayCodeGroupID] + INNER JOIN [dss].[viewDimPayCodeRollup1] [DSSPAYCODEROLLUP1] on [DSSPAYCODEROLLUP1].[DSSPayCodeRollup1ID] = [grpB323F295F71F4248991D24C571ED8831].[DSSPayCodeRollup1ID] + INNER JOIN [dss].[viewDimPayCodeRollup2] [DSSPAYCODEROLLUP2] on [DSSPAYCODEROLLUP2].[DSSPayCodeRollup2ID] = [grpB323F295F71F4248991D24C571ED8831].[DSSPayCodeRollup2ID] + LEFT JOIN [fp].[viewProviderLineItem_auto] [PROVIDERLI] on [PROVIDERLI].[ProviderLineItemID] = [grpB323F295F71F4248991D24C571ED8831].[ProviderLineItemID] + INNER JOIN [fw].[viewDimSPHPayCodeRollup] [SPHPAYCODEROLLUP] on [SPHPAYCODEROLLUP].[SPHPayCodeRollupID] = [grpB323F295F71F4248991D24C571ED8831].[SPHPayCodeRollupID] +GO + + +--------------------------------------------- + +-- fw.viewDimPayCycle +--Last Modified 11/30/2015 12:22 PM +CREATE VIEW [fw].[viewDimPayCycle] +AS +SELECT + grp97FA080700B74428A51EDA0423536FBB.[PayCycleID] + ,grp97FA080700B74428A51EDA0423536FBB.[Name] + ,grp97FA080700B74428A51EDA0423536FBB.[Code] + ,grp97FA080700B74428A51EDA0423536FBB.[SortOrder] + ,grp97FA080700B74428A51EDA0423536FBB.[PeriodDays] + ,grp97FA080700B74428A51EDA0423536FBB.[FirstPayPeriodStartDate] + ,grp97FA080700B74428A51EDA0423536FBB.[AccrualMethod] + ,grp97FA080700B74428A51EDA0423536FBB.[TransactionID] + ,grp97FA080700B74428A51EDA0423536FBB.[MemberGUID] + ,grp97FA080700B74428A51EDA0423536FBB.[HistoryItemGUID] + ,grp97FA080700B74428A51EDA0423536FBB.[CurrentPayPeriodID] +FROM [fw].[DimPayCycle] grp97FA080700B74428A51EDA0423536FBB (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimPayPeriod +CREATE VIEW [fw].[viewDimPayPeriod] +AS +SELECT + +[PayPeriodID], +[Name], +[PeriodNumber], +[Code], +[PayPeriodCode], +[FiscalYearIDStart], +[FiscalYearIDSecond], +[PeriodStartCalendarDate], +[PeriodEndCalendarDate], +[PeriodDays], +[WorkingDays], +[FiscalMonthIDStart], +[FiscalMonthIDSecond], +[CalendarDaysStart], +[CalendarDaysSecond], +[PeriodDaysStart], +[PeriodDaysSecond], +[PeriodWeightStart], +[PeriodWeightSecond], +[DaysInPeriodWeightStart], +[DaysInPeriodWeightSecond], +[HistoryItemGUID], +[PayCycleID], + COALESCE([PayCycleName],'') as [PayCycleName], +[MemberGUID], +[TransactionID], + COALESCE([PayCycleCode],'') as [PayCycleCode], +[PayCycleSortOrder], + COALESCE([AccrualMethod],'') as [AccrualMethod], +[IsCurrentPayPeriod], +[CountFromCurrentPayPeriod] ,[Version] + +FROM [fw].[DimPayPeriod] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimPayPeriod_source +CREATE VIEW [fw].[viewDimPayPeriod_source] +AS +SELECT + grp90F54C2D43B54BE39642E686F8DE7839.[PayPeriodID] + ,grp90F54C2D43B54BE39642E686F8DE7839.[PeriodStartCalendarDate] + ,grp90F54C2D43B54BE39642E686F8DE7839.[FiscalMonthIDStart] + ,grp90F54C2D43B54BE39642E686F8DE7839.[FiscalMonthIDSecond] + ,grp90F54C2D43B54BE39642E686F8DE7839.[CalendarDaysStart] + ,grp90F54C2D43B54BE39642E686F8DE7839.[CalendarDaysSecond] + ,grp90F54C2D43B54BE39642E686F8DE7839.[PeriodDaysStart] + ,grp90F54C2D43B54BE39642E686F8DE7839.[PeriodDaysSecond] + ,grp90F54C2D43B54BE39642E686F8DE7839.[PeriodWeightStart] + ,grp90F54C2D43B54BE39642E686F8DE7839.[PeriodWeightSecond] + ,grp90F54C2D43B54BE39642E686F8DE7839.[DaysInPeriodWeightStart] + ,grp90F54C2D43B54BE39642E686F8DE7839.[DaysInPeriodWeightSecond] + ,grp90F54C2D43B54BE39642E686F8DE7839.[HistoryItemGUID] + ,grp90F54C2D43B54BE39642E686F8DE7839.[MemberGUID] + ,grp90F54C2D43B54BE39642E686F8DE7839.[TransactionID] + ,ISNULL([PAYCYCLE].[Name], 'Not Specified') as [PayCycleName] + ,ISNULL([PAYCYCLE].[Code], 'Not Specified') as [PayCycleCode] + ,ISNULL([PAYCYCLE].[SortOrder], 0) as [PayCycleSortOrder] + ,ISNULL([PAYCYCLE].[AccrualMethod], 'Not Specified') as [AccrualMethod] +, [grp90F54C2D43B54BE39642E686F8DE7839].[Version]FROM [fw].[DimPayPeriod] grp90F54C2D43B54BE39642E686F8DE7839 (readuncommitted) + INNER JOIN [fw].[viewDimPayCycle] [PAYCYCLE] on [PAYCYCLE].[PayCycleID] = [grp90F54C2D43B54BE39642E686F8DE7839].[PayCycleID] +GO + + +--------------------------------------------- + +-- fw.viewDimPayor +--Last Modified 6/8/2020 3:13 PM +CREATE VIEW [fw].[viewDimPayor] +AS +SELECT + grp0887B09C7E9342638431A42A05EA03B5.[PayorID] + ,coalesce(grp0887B09C7E9342638431A42A05EA03B5.[Name],'') as [Name] + ,grp0887B09C7E9342638431A42A05EA03B5.[Description] + ,grp0887B09C7E9342638431A42A05EA03B5.[DescriptionLong] + ,grp0887B09C7E9342638431A42A05EA03B5.[PayorCode] + ,grp0887B09C7E9342638431A42A05EA03B5.[PayorGroupID] + ,grp0887B09C7E9342638431A42A05EA03B5.[IsOB] + ,grp0887B09C7E9342638431A42A05EA03B5.[IsDSS] + ,grp0887B09C7E9342638431A42A05EA03B5.[FinancialClassID] + ,grp0887B09C7E9342638431A42A05EA03B5.[OBDefaultInpatientReimbursementMethod] + ,grp0887B09C7E9342638431A42A05EA03B5.[OBDefaultOutpatientReimbursementMethod] + ,grp0887B09C7E9342638431A42A05EA03B5.[MemberGUID] + ,grp0887B09C7E9342638431A42A05EA03B5.[HistoryItemGUID] + ,grp0887B09C7E9342638431A42A05EA03B5.[TransactionID] + ,ISNULL([PayorGroup].[Name], 'Not Specified') as [PayorGroup] + ,ISNULL([FINANCIALCLASS].[Name], 'Not Specified') as [FinancialClass] +FROM [fw].[DimPayor] grp0887B09C7E9342638431A42A05EA03B5 (readuncommitted) + LEFT JOIN [fw].[viewDimPayorGroup] [PayorGroup] on [PayorGroup].[PayorGroupID] = [grp0887B09C7E9342638431A42A05EA03B5].[PayorGroupID] + LEFT JOIN [clientdss].[viewDimFinancialClass] [FINANCIALCLASS] on [FINANCIALCLASS].[FinancialClassID] = [grp0887B09C7E9342638431A42A05EA03B5].[FinancialClassID] +GO + + +--------------------------------------------- + +-- fw.viewDimPayorGroup +CREATE VIEW [fw].[viewDimPayorGroup] +AS +SELECT + +[PayorGroupID], +[Name], +[Category], +[ReimbursementType], +[PayorGroupCode], +[SortOrder], +[IsCapital], +[CAPChargesFinancialReportingID], +[CAPContractualsFinancialReportingID], +[IsDSS], +[IsOB], +[IsMR], +[IsSP], +[SPHCRPayorID], +[SPChargesFinancialReportingID], +[SPContractualsFinancialReportingID], +[SPDefaultInpatientReimbursementMethod], +[SPDefaultOutpatientReimbursementMethod], +[SPDefaultClinicReimbursementMethod], +[OBDefaultInpatientReimbursementMethod], + COALESCE([CAPChargesFinancialReporting],'') as [CAPChargesFinancialReporting], + COALESCE([CAPContractualsFinancialReporting],'') as [CAPContractualsFinancialReporting], +[OBDefaultOutpatientReimbursementMethod], + COALESCE([SPHCRPayor],'') as [SPHCRPayor], + COALESCE([SPChargesFinancialReporting],'') as [SPChargesFinancialReporting], + COALESCE([SPContractualsFinancialReporting],'') as [SPContractualsFinancialReporting], +[SPCMISamplingSourceType], +[SPCMISamplingAccountID], +[MemberGUID] ,[HistoryItemGUID] + +FROM [fw].[DimPayorGroup] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimPayorGroupPH +CREATE VIEW [fw].[viewDimPayorGroupPH] +AS +SELECT + +[PayorGroupPHID], +[MemberGUID], +[Name] ,[HistoryItemGUID] + +FROM [fw].[DimPayorGroupPH] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimPayorGroupPH_source +CREATE VIEW [fw].[viewDimPayorGroupPH_source] +AS +SELECT + grp4D76CDC6FB8D4D8FB7B95C7CD71A1E5A.[PayorGroupPHID] + ,grp4D76CDC6FB8D4D8FB7B95C7CD71A1E5A.[MemberGUID] +, [grp4D76CDC6FB8D4D8FB7B95C7CD71A1E5A].[HistoryItemGUID]FROM [fw].[DimPayorGroupPH] grp4D76CDC6FB8D4D8FB7B95C7CD71A1E5A (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimPayorGroup_source +CREATE VIEW [fw].[viewDimPayorGroup_source] +AS +SELECT + grpEF15CAACBD154F79B68A2D4655C8489C.[PayorGroupID] + ,grpEF15CAACBD154F79B68A2D4655C8489C.[SPCMISamplingSourceType] + ,grpEF15CAACBD154F79B68A2D4655C8489C.[SPCMISamplingAccountID] + ,grpEF15CAACBD154F79B68A2D4655C8489C.[MemberGUID] + ,ISNULL([CAPFINANCIALREP].[Name], 'Not Specified') as [CAPChargesFinancialReporting] + ,ISNULL([CAPFINANCIALREP_1].[Name], 'Not Specified') as [CAPContractualsFinancialReporting] + ,ISNULL([SPHCRPAYOR].[Name], 'Not Specified') as [SPHCRPayor] + ,ISNULL([SPFINANCIALREP].[Name], 'Not Specified') as [SPChargesFinancialReporting] + ,ISNULL([SPFINANCIALREP_1].[Name], 'Not Specified') as [SPContractualsFinancialReporting] +, [grpEF15CAACBD154F79B68A2D4655C8489C].[HistoryItemGUID]FROM [fw].[DimPayorGroup] grpEF15CAACBD154F79B68A2D4655C8489C (readuncommitted) + INNER JOIN [cap].[viewDimFinancialReporting] [CAPFINANCIALREP] on [CAPFINANCIALREP].[FinancialReportingID] = [grpEF15CAACBD154F79B68A2D4655C8489C].[CAPChargesFinancialReportingID] + INNER JOIN [cap].[viewDimFinancialReporting] [CAPFINANCIALREP_1] on [CAPFINANCIALREP_1].[FinancialReportingID] = [grpEF15CAACBD154F79B68A2D4655C8489C].[CAPContractualsFinancialReportingID] + INNER JOIN [sp].[viewDimHCRPayor] [SPHCRPAYOR] on [SPHCRPAYOR].[SPHCRPayorID] = [grpEF15CAACBD154F79B68A2D4655C8489C].[SPHCRPayorID] + INNER JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP] on [SPFINANCIALREP].[FinancialReportingID] = [grpEF15CAACBD154F79B68A2D4655C8489C].[SPChargesFinancialReportingID] + INNER JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP_1] on [SPFINANCIALREP_1].[FinancialReportingID] = [grpEF15CAACBD154F79B68A2D4655C8489C].[SPContractualsFinancialReportingID] +GO + + +--------------------------------------------- + +-- fw.viewDimPayorPH +CREATE VIEW [fw].[viewDimPayorPH] +AS +SELECT + grpF3B83E94F08649FDBDD59852FB8C7C47.[PayorPHID] + ,grpF3B83E94F08649FDBDD59852FB8C7C47.[Name] + ,grpF3B83E94F08649FDBDD59852FB8C7C47.[MemberGUID] +FROM [fw].[DimPayorPH] grpF3B83E94F08649FDBDD59852FB8C7C47 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimPhysicianGroup +CREATE VIEW [fw].[viewDimPhysicianGroup] +AS +SELECT + +[PhysicianGroupID], +[Category], +[Subcategory], +[Name], +[PhysicianType], +[IsSP], +[IsCapital], +[IsOB], +[IsMR], +[IsDSS], +[SortOrder], +[SPSalariesFinancialReportingID], +[SPFTEsFinancialReportingID], + COALESCE([SPSalariesFinancialReporting],'') as [SPSalariesFinancialReporting], +[SPSalariesVolumeDriverID], +[SPPhysicianBenefitsTypeID], + COALESCE([SPFTEsFinancialReporting],'') as [SPFTEsFinancialReporting], + COALESCE([SPSalariesVolumeDriver],'') as [SPSalariesVolumeDriver], + COALESCE([SPPhysicianBenefitsType],'') as [SPPhysicianBenefitsType], +[MemberGUID], +[HistoryItemGUID], +[WorkWeekOverrideID] ,[Version] + +FROM [fw].[DimPhysicianGroup] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimPhysicianGroupPH +CREATE VIEW [fw].[viewDimPhysicianGroupPH] +AS +SELECT + +[PhysicianGroupPHID], +[Name], +[MemberGUID], +[HistoryItemGUID] ,[Version] + +FROM [fw].[DimPhysicianGroupPH] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimPhysicianGroupPH_source +CREATE VIEW [fw].[viewDimPhysicianGroupPH_source] +AS +SELECT + grpFA7033208877495E84B853F8157A91A4.[PhysicianGroupPHID] + ,grpFA7033208877495E84B853F8157A91A4.[MemberGUID] + ,grpFA7033208877495E84B853F8157A91A4.[HistoryItemGUID] +, [grpFA7033208877495E84B853F8157A91A4].[Version]FROM [fw].[DimPhysicianGroupPH] grpFA7033208877495E84B853F8157A91A4 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimPhysicianGroup_source +CREATE VIEW [fw].[viewDimPhysicianGroup_source] +AS +SELECT + grpF4583D1A174C47B999BA61480A7A4378.[PhysicianGroupID] + ,grpF4583D1A174C47B999BA61480A7A4378.[MemberGUID] + ,grpF4583D1A174C47B999BA61480A7A4378.[HistoryItemGUID] + ,ISNULL([SPFINANCIALREP].[Name], 'Not Specified') as [SPSalariesFinancialReporting] + ,ISNULL([SPFINANCIALREP_1].[Name], 'Not Specified') as [SPFTEsFinancialReporting] + ,ISNULL([SPAccountRollup].[Name], 'Not Specified') as [SPSalariesVolumeDriver] + ,ISNULL([SPAccountRollup_1].[Name], 'Not Specified') as [SPPhysicianBenefitsType] +, [grpF4583D1A174C47B999BA61480A7A4378].[Version]FROM [fw].[DimPhysicianGroup] grpF4583D1A174C47B999BA61480A7A4378 (readuncommitted) + INNER JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP] on [SPFINANCIALREP].[FinancialReportingID] = [grpF4583D1A174C47B999BA61480A7A4378].[SPSalariesFinancialReportingID] + INNER JOIN [sp].[viewDimFinancialReporting] [SPFINANCIALREP_1] on [SPFINANCIALREP_1].[FinancialReportingID] = [grpF4583D1A174C47B999BA61480A7A4378].[SPFTEsFinancialReportingID] + INNER JOIN [sp].[viewDimAccountRollup] [SPAccountRollup] on [SPAccountRollup].[AccountRollupID] = [grpF4583D1A174C47B999BA61480A7A4378].[SPSalariesVolumeDriverID] + INNER JOIN [sp].[viewDimAccountRollup] [SPAccountRollup_1] on [SPAccountRollup_1].[AccountRollupID] = [grpF4583D1A174C47B999BA61480A7A4378].[SPPhysicianBenefitsTypeID] +GO + + +--------------------------------------------- + +-- fw.viewDimPhysicianPH +CREATE VIEW [fw].[viewDimPhysicianPH] +AS +SELECT + grp085BA6AC2CB14AD4A83D611E7B1646B1.[PhysicianPHID] + ,grp085BA6AC2CB14AD4A83D611E7B1646B1.[Name] + ,grp085BA6AC2CB14AD4A83D611E7B1646B1.[MemberGUID] + ,grp085BA6AC2CB14AD4A83D611E7B1646B1.[HistoryItemGUID] + ,grp085BA6AC2CB14AD4A83D611E7B1646B1.[TransactionID] +FROM [fw].[DimPhysicianPH] grp085BA6AC2CB14AD4A83D611E7B1646B1 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimPhysicianSpecialty +CREATE VIEW [fw].[viewDimPhysicianSpecialty] +AS +SELECT + grp3091D7E63A5F4E09B9439680761F9990.[PhysicianSpecialtyID] + ,coalesce(grp3091D7E63A5F4E09B9439680761F9990.[Name],'') as [Name] + ,grp3091D7E63A5F4E09B9439680761F9990.[TransactionID] + ,grp3091D7E63A5F4E09B9439680761F9990.[MemberGUID] + ,grp3091D7E63A5F4E09B9439680761F9990.[HistoryItemGUID] + ,grp3091D7E63A5F4E09B9439680761F9990.[PhysicianSpecialtyCode] + ,grp3091D7E63A5F4E09B9439680761F9990.[SpecialtyGroup] + ,grp3091D7E63A5F4E09B9439680761F9990.[Description] + ,grp3091D7E63A5F4E09B9439680761F9990.[RVUTarget] +FROM [fw].[DimPhysicianSpecialty] grp3091D7E63A5F4E09B9439680761F9990 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimPositionType +--Last Modified 11/8/2024 12:46 AM +CREATE VIEW [fw].[viewDimPositionType] +AS +SELECT + grp69B5488AB512468F8B9002077835B307.[PositionTypeID] + ,grp69B5488AB512468F8B9002077835B307.[Name] + ,grp69B5488AB512468F8B9002077835B307.[TransactionID] + ,grp69B5488AB512468F8B9002077835B307.[MemberGUID] + ,grp69B5488AB512468F8B9002077835B307.[HistoryItemGUID] + ,grp69B5488AB512468F8B9002077835B307.[PositionTypeAssignmentTypeID] + ,ISNULL([POSITIONTYPEASSIGNMENTTYPE].[Name], 'Not Specified') as [PositionTypeAssignmentType] +FROM [fw].[DimPositionType] grp69B5488AB512468F8B9002077835B307 (readuncommitted) + INNER JOIN [fw].[viewDimPositionTypeAssignmentType] [POSITIONTYPEASSIGNMENTTYPE] on [POSITIONTYPEASSIGNMENTTYPE].[PositionTypeAssignmentTypeID] = [grp69B5488AB512468F8B9002077835B307].[PositionTypeAssignmentTypeID] +GO + + +--------------------------------------------- + +-- fw.viewDimPositionTypeAssignmentType +--Last Modified 11/8/2024 12:46 AM +CREATE VIEW [fw].[viewDimPositionTypeAssignmentType] +AS +SELECT + grp34DC76DCBD1B4EB7BB814C769354A3F5.[PositionTypeAssignmentTypeID] + ,grp34DC76DCBD1B4EB7BB814C769354A3F5.[Name] + ,grp34DC76DCBD1B4EB7BB814C769354A3F5.[TransactionID] + ,grp34DC76DCBD1B4EB7BB814C769354A3F5.[MemberGUID] + ,grp34DC76DCBD1B4EB7BB814C769354A3F5.[HistoryItemGUID] +FROM [fw].[DimPositionTypeAssignmentType] grp34DC76DCBD1B4EB7BB814C769354A3F5 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimProductiveClass +CREATE VIEW [fw].[viewDimProductiveClass] +AS +SELECT + grp6EF32EA816124EEF8860ED7A89141304.[ProductiveClassID] + ,grp6EF32EA816124EEF8860ED7A89141304.[Name] + ,grp6EF32EA816124EEF8860ED7A89141304.[MemberGUID] + ,grp6EF32EA816124EEF8860ED7A89141304.[HistoryItemGUID] +FROM [fw].[DimProductiveClass] grp6EF32EA816124EEF8860ED7A89141304 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimProgram +--Last Modified 5/26/2015 10:11 AM +CREATE VIEW [fw].[viewDimProgram] +AS +SELECT + grp7D067B54714C46E1927FF61AE552BEA9.[ProgramID] + ,coalesce(grp7D067B54714C46E1927FF61AE552BEA9.[Name],'') as [Name] + ,grp7D067B54714C46E1927FF61AE552BEA9.[Code] + ,grp7D067B54714C46E1927FF61AE552BEA9.[Description] + ,grp7D067B54714C46E1927FF61AE552BEA9.[SortOrder] + ,grp7D067B54714C46E1927FF61AE552BEA9.[TransactionID] + ,grp7D067B54714C46E1927FF61AE552BEA9.[MemberGUID] + ,grp7D067B54714C46E1927FF61AE552BEA9.[HistoryItemGUID] +FROM [fw].[DimProgram] grp7D067B54714C46E1927FF61AE552BEA9 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimProject +--Last Modified 5/26/2015 10:11 AM +CREATE VIEW [fw].[viewDimProject] +AS +SELECT + grp2CF09BEF8FF548EB995FA62246911542.[ProjectID] + ,coalesce(grp2CF09BEF8FF548EB995FA62246911542.[Name],'') as [Name] + ,grp2CF09BEF8FF548EB995FA62246911542.[Code] + ,grp2CF09BEF8FF548EB995FA62246911542.[Description] + ,grp2CF09BEF8FF548EB995FA62246911542.[SortOrder] + ,grp2CF09BEF8FF548EB995FA62246911542.[TransactionID] + ,grp2CF09BEF8FF548EB995FA62246911542.[MemberGUID] + ,grp2CF09BEF8FF548EB995FA62246911542.[HistoryItemGUID] +FROM [fw].[DimProject] grp2CF09BEF8FF548EB995FA62246911542 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimProvider +--Last Modified 9/4/2018 7:30 PM +CREATE VIEW [fw].[viewDimProvider] +AS +SELECT + grp1D2F3A2E50034A10A3B63D4C0CC69235.[ProviderID] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[Type] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[NameFirst] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[IsPhysician] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[NameLast] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[ProviderCode] + ,coalesce(grp1D2F3A2E50034A10A3B63D4C0CC69235.[Name],'') as [Name] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[PhysicianSpecialtyID] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[StateLicenseNumber] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[NPI] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[GroupAffiliaition] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[DSSIsDefined] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBIsDefined] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[IsEmployee] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBIsActive] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier1Rate] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier2Rate] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier3Rate] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier4Rate] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier5Rate] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier6Rate] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier1Threshold] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier2Threshold] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier3Threshold] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier4Threshold] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier5Threshold] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBTier6Threshold] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBVolumeTarget1] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBVolumeTarget2] + ,coalesce(grp1D2F3A2E50034A10A3B63D4C0CC69235.[ProviderName],'') as [ProviderName] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[PayRate] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[OBVolumeTarget3] + ,coalesce(grp1D2F3A2E50034A10A3B63D4C0CC69235.[CompensationMethod],'') as [CompensationMethod] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[BasePay] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[TransactionID] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[MemberGUID] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[HistoryItemGUID] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[WorkWeekOverrideID] + ,grp1D2F3A2E50034A10A3B63D4C0CC69235.[IsVariable] + ,ISNULL([PHYSICIANSPECIALTY].[Name], 'Not Specified') as [Specialty] +FROM [fw].[DimProvider] grp1D2F3A2E50034A10A3B63D4C0CC69235 (readuncommitted) + LEFT JOIN [fw].[viewDimPhysicianSpecialty] [PHYSICIANSPECIALTY] on [PHYSICIANSPECIALTY].[PhysicianSpecialtyID] = [grp1D2F3A2E50034A10A3B63D4C0CC69235].[PhysicianSpecialtyID] +GO + + +--------------------------------------------- + +-- fw.viewDimProviderPH +CREATE VIEW [fw].[viewDimProviderPH] +AS +SELECT + grp085BA6AC2CB14AD4A83D611E7B1646B1.[ProviderPHID] + ,grp085BA6AC2CB14AD4A83D611E7B1646B1.[Name] + ,grp085BA6AC2CB14AD4A83D611E7B1646B1.[TransactionID] + ,grp085BA6AC2CB14AD4A83D611E7B1646B1.[MemberGUID] + ,grp085BA6AC2CB14AD4A83D611E7B1646B1.[HistoryItemGUID] +FROM [fw].[DimProviderPH] grp085BA6AC2CB14AD4A83D611E7B1646B1 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimQuarter_auto +CREATE VIEW [fw].[viewDimQuarter_auto] +AS +SELECT + grp3CBAB808CE024FFBB6B5C2F2E6B7EC5E.[Name] + ,grp3CBAB808CE024FFBB6B5C2F2E6B7EC5E.[MemberGUID] + ,grp3CBAB808CE024FFBB6B5C2F2E6B7EC5E.[QuarterID] +, [grp3CBAB808CE024FFBB6B5C2F2E6B7EC5E].[Version], [grp3CBAB808CE024FFBB6B5C2F2E6B7EC5E].[HistoryItemGUID]FROM [fw].[DimQuarter] grp3CBAB808CE024FFBB6B5C2F2E6B7EC5E (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimReportDetailType +CREATE VIEW [fw].[viewDimReportDetailType] +AS +SELECT + grp280082C30690409ABF34E0DC53FEDC09.[ReportDetailTypeID] + ,grp280082C30690409ABF34E0DC53FEDC09.[Name] + ,grp280082C30690409ABF34E0DC53FEDC09.[TransactionID] + ,grp280082C30690409ABF34E0DC53FEDC09.[MemberGUID] + ,grp280082C30690409ABF34E0DC53FEDC09.[HistoryItemGUID] + ,grp280082C30690409ABF34E0DC53FEDC09.[TableName] +FROM [fw].[DimReportDetailType] grp280082C30690409ABF34E0DC53FEDC09 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimResearchDepartmentCategory +CREATE VIEW [fw].[viewDimResearchDepartmentCategory] +AS +SELECT + grpE9D662D6B156456CBA91AE99CF2DF414.[ResearchDepartmentCategoryID] + ,grpE9D662D6B156456CBA91AE99CF2DF414.[Name] + ,grpE9D662D6B156456CBA91AE99CF2DF414.[SortOrder] + ,grpE9D662D6B156456CBA91AE99CF2DF414.[TransactionID] + ,grpE9D662D6B156456CBA91AE99CF2DF414.[MemberGUID] + ,grpE9D662D6B156456CBA91AE99CF2DF414.[HistoryItemGUID] +FROM [fw].[DimResearchDepartmentCategory] grpE9D662D6B156456CBA91AE99CF2DF414 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimRowNumber +CREATE VIEW [fw].[viewDimRowNumber] +AS +SELECT + grpCEA161A7FFE24D2B90F4491D4C324B8D.[RowNumberID] + ,grpCEA161A7FFE24D2B90F4491D4C324B8D.[Name] + ,grpCEA161A7FFE24D2B90F4491D4C324B8D.[MemberGUID] + ,grpCEA161A7FFE24D2B90F4491D4C324B8D.[HistoryItemGUID] +FROM [fw].[DimRowNumber] grpCEA161A7FFE24D2B90F4491D4C324B8D (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimSPHAccountRollup +--Last Modified 3/15/2022 10:09 PM +CREATE VIEW [fw].[viewDimSPHAccountRollup] +AS +SELECT + grp0FB965B53015438FA55B5196CD9FEEC1.[SPHAccountRollupID] + ,coalesce(grp0FB965B53015438FA55B5196CD9FEEC1.[Name],'') as [Name] + ,grp0FB965B53015438FA55B5196CD9FEEC1.[TransactionID] + ,grp0FB965B53015438FA55B5196CD9FEEC1.[MemberGUID] + ,grp0FB965B53015438FA55B5196CD9FEEC1.[HistoryItemGUID] + ,grp0FB965B53015438FA55B5196CD9FEEC1.[Statement] + ,grp0FB965B53015438FA55B5196CD9FEEC1.[Category] + ,grp0FB965B53015438FA55B5196CD9FEEC1.[LineItem] + ,grp0FB965B53015438FA55B5196CD9FEEC1.[Section] + ,grp0FB965B53015438FA55B5196CD9FEEC1.[SortOrder] + ,grp0FB965B53015438FA55B5196CD9FEEC1.[IsStandard] + ,grp0FB965B53015438FA55B5196CD9FEEC1.[SPHCostComponent] + ,grp0FB965B53015438FA55B5196CD9FEEC1.[SPHCostComponentRollup] + ,grp0FB965B53015438FA55B5196CD9FEEC1.[SPHAccountRollupCode] +FROM [fw].[DimSPHAccountRollup] grp0FB965B53015438FA55B5196CD9FEEC1 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimSPHDepartmentRollup +--Last Modified 11/16/2020 3:28 PM +CREATE VIEW [fw].[viewDimSPHDepartmentRollup] +AS +SELECT + grp5181C574309B42B29625F6AA66F56763.[SPHDepartmentRollupID] + ,grp5181C574309B42B29625F6AA66F56763.[TransactionID] + ,coalesce(grp5181C574309B42B29625F6AA66F56763.[Name],'') as [Name] + ,grp5181C574309B42B29625F6AA66F56763.[MemberGUID] + ,grp5181C574309B42B29625F6AA66F56763.[HistoryItemGUID] + ,grp5181C574309B42B29625F6AA66F56763.[SPHDepartmentRollupCode] + ,grp5181C574309B42B29625F6AA66F56763.[SortOrder] + ,grp5181C574309B42B29625F6AA66F56763.[IsStandard] +FROM [fw].[DimSPHDepartmentRollup] grp5181C574309B42B29625F6AA66F56763 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimSPHDepartmentType_auto +--Last Modified 11/16/2020 3:28 PM +CREATE VIEW [fw].[viewDimSPHDepartmentType_auto] +AS +SELECT + grp0A011FEFFE0943ACA25C28B87AF8BB5E.[SPHDepartmentTypeID] + ,grp0A011FEFFE0943ACA25C28B87AF8BB5E.[Name] + ,grp0A011FEFFE0943ACA25C28B87AF8BB5E.[TransactionID] + ,grp0A011FEFFE0943ACA25C28B87AF8BB5E.[MemberGUID] + ,grp0A011FEFFE0943ACA25C28B87AF8BB5E.[HistoryItemGUID] + ,grp0A011FEFFE0943ACA25C28B87AF8BB5E.[SPHDepartmentTypeCode] + ,grp0A011FEFFE0943ACA25C28B87AF8BB5E.[IsStandard] +FROM [fw].[DimSPHDepartmentType] grp0A011FEFFE0943ACA25C28B87AF8BB5E (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimSPHDepartment_auto +--Last Modified 4/5/2024 9:49 AM +CREATE VIEW [fw].[viewDimSPHDepartment_auto] +AS +SELECT + grpBA529E3553234961A9B03E2BB2DE62D6.[SPHDepartmentID] + ,grpBA529E3553234961A9B03E2BB2DE62D6.[Name] + ,grpBA529E3553234961A9B03E2BB2DE62D6.[SPHDepartmentRollup] + ,grpBA529E3553234961A9B03E2BB2DE62D6.[TransactionID] + ,grpBA529E3553234961A9B03E2BB2DE62D6.[MemberGUID] + ,grpBA529E3553234961A9B03E2BB2DE62D6.[HistoryItemGUID] + ,grpBA529E3553234961A9B03E2BB2DE62D6.[SPHDepartmentCode] +FROM [fw].[DimSPHDepartment] grpBA529E3553234961A9B03E2BB2DE62D6 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimSPHJobCodeRollup +--Last Modified 12/15/2020 2:06 PM +CREATE VIEW [fw].[viewDimSPHJobCodeRollup] +AS +SELECT + grpCC5829E5D6334D34958CCF8057B6E850.[SPHJobCodeRollupID] + ,grpCC5829E5D6334D34958CCF8057B6E850.[Name] + ,grpCC5829E5D6334D34958CCF8057B6E850.[TransactionID] + ,grpCC5829E5D6334D34958CCF8057B6E850.[MemberGUID] + ,grpCC5829E5D6334D34958CCF8057B6E850.[HistoryItemGUID] + ,grpCC5829E5D6334D34958CCF8057B6E850.[SPHJobCodeRollupCode] + ,grpCC5829E5D6334D34958CCF8057B6E850.[SPHCostComponent] + ,grpCC5829E5D6334D34958CCF8057B6E850.[SortOrder] + ,grpCC5829E5D6334D34958CCF8057B6E850.[IsStandard] +FROM [fw].[DimSPHJobCodeRollup] grpCC5829E5D6334D34958CCF8057B6E850 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimSPHPayCodeRollup +--Last Modified 02/17/2022 3:49 PM +CREATE VIEW [fw].[viewDimSPHPayCodeRollup] +AS +SELECT + grpCD15C19FF64B4AE6B4AEF15FE3E938C8.[SPHPayCodeRollupID] + ,grpCD15C19FF64B4AE6B4AEF15FE3E938C8.[Name] + ,grpCD15C19FF64B4AE6B4AEF15FE3E938C8.[TransactionID] + ,grpCD15C19FF64B4AE6B4AEF15FE3E938C8.[MemberGUID] + ,grpCD15C19FF64B4AE6B4AEF15FE3E938C8.[HistoryItemGUID] + ,coalesce(grpCD15C19FF64B4AE6B4AEF15FE3E938C8.[SPHProductiveClass],'') as [SPHProductiveClass] + ,grpCD15C19FF64B4AE6B4AEF15FE3E938C8.[SortOrder] + ,grpCD15C19FF64B4AE6B4AEF15FE3E938C8.[IsStandard] + ,grpCD15C19FF64B4AE6B4AEF15FE3E938C8.[SPHPayCodeRollupCode] +FROM [fw].[DimSPHPayCodeRollup] grpCD15C19FF64B4AE6B4AEF15FE3E938C8 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimSecureGroup +CREATE VIEW [fw].[viewDimSecureGroup] +AS +SELECT + grpCD7483929A80421EB8FCB5F08DA13707.[SecureGroupID] + ,grpCD7483929A80421EB8FCB5F08DA13707.[Name] + ,grpCD7483929A80421EB8FCB5F08DA13707.[MemberGUID] + ,grpCD7483929A80421EB8FCB5F08DA13707.[HistoryItemGUID] +FROM [fw].[DimSecureGroup] grpCD7483929A80421EB8FCB5F08DA13707 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimServiceLine +CREATE VIEW [fw].[viewDimServiceLine] +AS +SELECT + +[ServiceLineID], + COALESCE([Name],'') as [Name], +[RollupID], +[ProductLine], +[Code], +[SortOrder], + COALESCE([Rollup],'') as [Rollup], +[RollupSortOrder], +[MemberGUID], +[HistoryItemGUID] +FROM [fw].[DimServiceLine] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimServiceLine2_auto +--Last Modified 8/1/2016 9:45 AM +CREATE VIEW [fw].[viewDimServiceLine2_auto] +AS +SELECT + grp49B904B3B0B047D8BE592BFC9B8A8AB5.[ServiceLine2ID] + ,grp49B904B3B0B047D8BE592BFC9B8A8AB5.[Name] + ,grp49B904B3B0B047D8BE592BFC9B8A8AB5.[MemberGUID] + ,grp49B904B3B0B047D8BE592BFC9B8A8AB5.[HistoryItemGUID] + ,grp49B904B3B0B047D8BE592BFC9B8A8AB5.[PatientTypeID] + ,grp49B904B3B0B047D8BE592BFC9B8A8AB5.[Rollup] + ,grp49B904B3B0B047D8BE592BFC9B8A8AB5.[Rollup2] + ,grp49B904B3B0B047D8BE592BFC9B8A8AB5.[SortOrder] +FROM [fw].[DimServiceLine2] grp49B904B3B0B047D8BE592BFC9B8A8AB5 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimServiceLine3_auto +--Last Modified 8/1/2016 9:45 AM +CREATE VIEW [fw].[viewDimServiceLine3_auto] +AS +SELECT + grp5974196196F64FC9A4F8AA9FACBDCD45.[ServiceLine3ID] + ,grp5974196196F64FC9A4F8AA9FACBDCD45.[Name] + ,grp5974196196F64FC9A4F8AA9FACBDCD45.[MemberGUID] + ,grp5974196196F64FC9A4F8AA9FACBDCD45.[HistoryItemGUID] + ,grp5974196196F64FC9A4F8AA9FACBDCD45.[PatientTypeID] + ,grp5974196196F64FC9A4F8AA9FACBDCD45.[Rollup] + ,grp5974196196F64FC9A4F8AA9FACBDCD45.[SortOrder] +FROM [fw].[DimServiceLine3] grp5974196196F64FC9A4F8AA9FACBDCD45 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimServiceLine4_auto +--Last Modified 8/1/2016 9:45 AM +CREATE VIEW [fw].[viewDimServiceLine4_auto] +AS +SELECT + grp569AFAF6B05343CD97F0CAAF28DC8F00.[ServiceLine4ID] + ,grp569AFAF6B05343CD97F0CAAF28DC8F00.[Name] + ,grp569AFAF6B05343CD97F0CAAF28DC8F00.[MemberGUID] + ,grp569AFAF6B05343CD97F0CAAF28DC8F00.[HistoryItemGUID] + ,grp569AFAF6B05343CD97F0CAAF28DC8F00.[PatientTypeID] + ,grp569AFAF6B05343CD97F0CAAF28DC8F00.[Rollup] + ,grp569AFAF6B05343CD97F0CAAF28DC8F00.[SortOrder] + ,grp569AFAF6B05343CD97F0CAAF28DC8F00.[Rollup2] +FROM [fw].[DimServiceLine4] grp569AFAF6B05343CD97F0CAAF28DC8F00 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimServiceLine5_auto +--Last Modified 8/1/2016 9:45 AM +CREATE VIEW [fw].[viewDimServiceLine5_auto] +AS +SELECT + grpC0586B9CF59342389C2043964523F713.[ServiceLine5ID] + ,grpC0586B9CF59342389C2043964523F713.[Name] + ,grpC0586B9CF59342389C2043964523F713.[MemberGUID] + ,grpC0586B9CF59342389C2043964523F713.[HistoryItemGUID] + ,grpC0586B9CF59342389C2043964523F713.[PatientTypeID] + ,grpC0586B9CF59342389C2043964523F713.[Rollup] + ,grpC0586B9CF59342389C2043964523F713.[SortOrder] +FROM [fw].[DimServiceLine5] grpC0586B9CF59342389C2043964523F713 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimServiceLine6_auto +--Last Modified 8/1/2016 9:45 AM +CREATE VIEW [fw].[viewDimServiceLine6_auto] +AS +SELECT + grpFAE2AC4E1DB34075B2113A9624D8EBDA.[ServiceLine6ID] + ,grpFAE2AC4E1DB34075B2113A9624D8EBDA.[Name] + ,grpFAE2AC4E1DB34075B2113A9624D8EBDA.[MemberGUID] + ,grpFAE2AC4E1DB34075B2113A9624D8EBDA.[HistoryItemGUID] + ,grpFAE2AC4E1DB34075B2113A9624D8EBDA.[PatientTypeID] + ,grpFAE2AC4E1DB34075B2113A9624D8EBDA.[Rollup] + ,grpFAE2AC4E1DB34075B2113A9624D8EBDA.[SortOrder] +FROM [fw].[DimServiceLine6] grpFAE2AC4E1DB34075B2113A9624D8EBDA (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimServiceLineRollup +CREATE VIEW [fw].[viewDimServiceLineRollup] +AS +SELECT + grp634CA27B835D4A18B1E58F8992F1B031.[ServiceLineRollupID] + ,grp634CA27B835D4A18B1E58F8992F1B031.[Name] + ,grp634CA27B835D4A18B1E58F8992F1B031.[MemberGUID] + ,grp634CA27B835D4A18B1E58F8992F1B031.[HistoryItemGUID] + ,grp634CA27B835D4A18B1E58F8992F1B031.[TransactionID] + ,grp634CA27B835D4A18B1E58F8992F1B031.[SortOrder] +FROM [fw].[DimServiceLineRollup] grp634CA27B835D4A18B1E58F8992F1B031 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimServiceLineRollupPH +CREATE VIEW [fw].[viewDimServiceLineRollupPH] +AS +SELECT + grp6617B9B078794F479D91C0708CEED4F0.[ServiceLineRollupPHID] + ,grp6617B9B078794F479D91C0708CEED4F0.[Name] + ,grp6617B9B078794F479D91C0708CEED4F0.[MemberGUID] + ,grp6617B9B078794F479D91C0708CEED4F0.[HistoryItemGUID] + ,grp6617B9B078794F479D91C0708CEED4F0.[TransactionID] +FROM [fw].[DimServiceLineRollupPH] grp6617B9B078794F479D91C0708CEED4F0 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimServiceLine_source +CREATE VIEW [fw].[viewDimServiceLine_source] +AS +SELECT + grpB9907EAC036D4FC5BFF43432DC038E7A.[ServiceLineID] + ,grpB9907EAC036D4FC5BFF43432DC038E7A.[Name] + ,grpB9907EAC036D4FC5BFF43432DC038E7A.[MemberGUID] + ,grpB9907EAC036D4FC5BFF43432DC038E7A.[HistoryItemGUID] + ,ISNULL([SERVICELINEROLLUP].[Name], 'Not Specified') as [Rollup] + ,ISNULL([SERVICELINEROLLUP].[SortOrder], 0) as [RollupSortOrder] +FROM [fw].[DimServiceLine] grpB9907EAC036D4FC5BFF43432DC038E7A (readuncommitted) + LEFT JOIN [fw].[viewDimServiceLineRollup] [SERVICELINEROLLUP] on [SERVICELINEROLLUP].[ServiceLineRollupID] = [grpB9907EAC036D4FC5BFF43432DC038E7A].[RollupID] +GO + + +--------------------------------------------- + +-- fw.viewDimSourceOfSavings +--Last Modified 10/31/2018 9:48 AM +CREATE VIEW [fw].[viewDimSourceOfSavings] +AS +SELECT + grp91260CC7FCE64FEE96459705BF43D6CB.[SourceOfSavingsID] + ,grp91260CC7FCE64FEE96459705BF43D6CB.[Name] + ,grp91260CC7FCE64FEE96459705BF43D6CB.[MemberGUID] + ,grp91260CC7FCE64FEE96459705BF43D6CB.[HistoryItemGUID] + ,grp91260CC7FCE64FEE96459705BF43D6CB.[TransactionID] +FROM [fw].[DimSourceOfSavings] grp91260CC7FCE64FEE96459705BF43D6CB (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimStaffingCategory_auto +--Last Modified 3/27/2023 4:41 PM +CREATE VIEW [fw].[viewDimStaffingCategory_auto] +AS +SELECT + grp14EBA885F7334C2AA07343FD9886CAF6.[StaffingCategoryID] + ,coalesce(grp14EBA885F7334C2AA07343FD9886CAF6.[Name],'') as [Name] + ,grp14EBA885F7334C2AA07343FD9886CAF6.[TransactionID] + ,grp14EBA885F7334C2AA07343FD9886CAF6.[MemberGUID] + ,grp14EBA885F7334C2AA07343FD9886CAF6.[HistoryItemGUID] + ,grp14EBA885F7334C2AA07343FD9886CAF6.[StaffingCategoryCode] + ,grp14EBA885F7334C2AA07343FD9886CAF6.[Description] +FROM [fw].[DimStaffingCategory] grp14EBA885F7334C2AA07343FD9886CAF6 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimStrataDecisionServiceLine +--Last Modified 6/3/2015 4:41 PM +CREATE VIEW [fw].[viewDimStrataDecisionServiceLine] +AS +SELECT + grp44649CCD9FB74ECF80BB88D6C5033A8C.[StrataDecisionServiceLineID] + ,grp44649CCD9FB74ECF80BB88D6C5033A8C.[Name] + ,grp44649CCD9FB74ECF80BB88D6C5033A8C.[TransactionID] + ,grp44649CCD9FB74ECF80BB88D6C5033A8C.[MemberGUID] + ,grp44649CCD9FB74ECF80BB88D6C5033A8C.[HistoryItemGUID] + ,grp44649CCD9FB74ECF80BB88D6C5033A8C.[PatientTypeID] +FROM [fw].[DimStrataDecisionServiceLine] grp44649CCD9FB74ECF80BB88D6C5033A8C (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimSystem +CREATE VIEW [fw].[viewDimSystem] +AS +SELECT + +[SystemID], + COALESCE([Name],'') as [Name], +[Code], +[Description], +[SortOrder], +[SecureGroupID], +[TransactionID], +[HistoryItemGUID], +[MemberGUID], +[EliminationsDepartmentID] +FROM [fw].[DimSystem] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimSystemSection +create view [fw].[viewDimSystemSection] + as + select + SS.SYSTEMSECTIONGUID as MemberGUID, + SS.Name, + SS.ImageName, + coalesce(nullif(replace(replace(replace(substring(replace(SS.FullPath, 'SYSTEM\', ''), 1, patindex('%\%', replace(SS.FullPath, 'SYSTEM\', ''))), '\', ''), 'TOOLBAR_', ''), 'MENU_', ''), ''), 'System') as Area, + coalesce(nullif(replace(substring(replace(SS.FullPath, 'SYSTEM\', ''), 1, patindex('%\%', replace(SS.FullPath, 'SYSTEM\', ''))), '\', ''), ''), 'System') as Section, + coalesce(nullif(replace(replace(replace(substring(replace(SS.FullPath, 'SYSTEM\', ''), 1, patindex('%\%', replace(SS.FullPath, 'SYSTEM\', ''))), '\', ''), 'TOOLBAR_', ''), 'MENU_', ''), ''), 'System') + + ' - ' + + coalesce(nullif(replace(substring(replace(SS.FullPath, 'SYSTEM\', ''), 1, patindex('%\%', replace(SS.FullPath, 'SYSTEM\', ''))), '\', ''), ''), 'System') + + ' - ' + SS.Name as [FullName], + SS.ID, + SS.LootID, + coalesce(PSS.Name, 'System') as Parent, + coalesce(PSS.LootID, '1F30ED4A-DFA5-4EA6-8457-20D23DB372C3') as ParentLootID, + cast(0 as bit) as IsDeleted, + dbo.ZeroGUID() as HistoryItemGUID + from SystemSection SS + left join SystemSection PSS on PSS.SystemSectionGUID = SS.ParentGUID + --inner join S3Loot L on L.LootID = SS.LootID + --inner join S3PermissionSet PS on PS.PermissionSetID = L.PermissionSetID --why do we do this? AJK + --where PS.Name like '%System%' +GO + + +--------------------------------------------- + +-- fw.viewDimSystem_source +CREATE VIEW [fw].[viewDimSystem_source] +AS +SELECT + grpF27719422C1141E2BDF4C0F24660B263.[SystemID] + ,grpF27719422C1141E2BDF4C0F24660B263.[Name] + ,grpF27719422C1141E2BDF4C0F24660B263.[SecureGroupID] + ,grpF27719422C1141E2BDF4C0F24660B263.[TransactionID] + ,grpF27719422C1141E2BDF4C0F24660B263.[HistoryItemGUID] + ,grpF27719422C1141E2BDF4C0F24660B263.[MemberGUID] +FROM [fw].[DimSystem] grpF27719422C1141E2BDF4C0F24660B263 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimTimeClass +CREATE VIEW [fw].[viewDimTimeClass] +AS +SELECT + grp5A23BD5828DE40AC868EBCB6F1CE3FF8.[MemberGUID] + ,grp5A23BD5828DE40AC868EBCB6F1CE3FF8.[TimeClassID] + ,grp5A23BD5828DE40AC868EBCB6F1CE3FF8.[Name] + ,grp5A23BD5828DE40AC868EBCB6F1CE3FF8.[TimeClassCode] + ,grp5A23BD5828DE40AC868EBCB6F1CE3FF8.[GlobalID] + ,grp5A23BD5828DE40AC868EBCB6F1CE3FF8.[IsSP] + ,grp5A23BD5828DE40AC868EBCB6F1CE3FF8.[SPIsISForecast] + ,grp5A23BD5828DE40AC868EBCB6F1CE3FF8.[HistoryItemGUID] + ,grp5A23BD5828DE40AC868EBCB6F1CE3FF8.[SortOrder] +, [grp5A23BD5828DE40AC868EBCB6F1CE3FF8].[Version]FROM [fw].[DimTimeClass] grp5A23BD5828DE40AC868EBCB6F1CE3FF8 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimTimeClassPH +CREATE VIEW [fw].[viewDimTimeClassPH] +AS +SELECT + +[TimeClassPHID], +[Name], +[MemberGUID] +FROM [fw].[DimTimeClassPH] (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimTimeClassPH_source +CREATE VIEW [fw].[viewDimTimeClassPH_source] +AS +SELECT + grp1132ACA8D57B494890AE52DD6857E83B.[TimeClassPHID] + ,grp1132ACA8D57B494890AE52DD6857E83B.[MemberGUID] +FROM [fw].[DimTimeClassPH] grp1132ACA8D57B494890AE52DD6857E83B (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimTime_auto +--Last Modified 1/8/2019 1:37 PM +CREATE VIEW [fw].[viewDimTime_auto] +AS +SELECT + grp35B3D1A6EEAC4E0CA47893B67CD0FD99.[TimeID] + ,grp35B3D1A6EEAC4E0CA47893B67CD0FD99.[TransactionID] + ,coalesce(grp35B3D1A6EEAC4E0CA47893B67CD0FD99.[Name],'') as [Name] + ,grp35B3D1A6EEAC4E0CA47893B67CD0FD99.[Hour] + ,grp35B3D1A6EEAC4E0CA47893B67CD0FD99.[Minute] + ,grp35B3D1A6EEAC4E0CA47893B67CD0FD99.[MemberGUID] + ,grp35B3D1A6EEAC4E0CA47893B67CD0FD99.[StandardTime] + ,grp35B3D1A6EEAC4E0CA47893B67CD0FD99.[HistoryItemGUID] +, [grp35B3D1A6EEAC4E0CA47893B67CD0FD99].[Version]FROM [fw].[DimTime] grp35B3D1A6EEAC4E0CA47893B67CD0FD99 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimUnitType +CREATE VIEW [fw].[viewDimUnitType] +AS +SELECT + grp7B1AFC84DBD346F9A5E90839ADF09065.[UnitTypeID] + ,grp7B1AFC84DBD346F9A5E90839ADF09065.[Name] + ,grp7B1AFC84DBD346F9A5E90839ADF09065.[GlobalID] + ,grp7B1AFC84DBD346F9A5E90839ADF09065.[DisplayFormat] + ,grp7B1AFC84DBD346F9A5E90839ADF09065.[SPDisplayFormat] + ,grp7B1AFC84DBD346F9A5E90839ADF09065.[CapitalDisplayFormat] + ,grp7B1AFC84DBD346F9A5E90839ADF09065.[MemberGUID] + ,grp7B1AFC84DBD346F9A5E90839ADF09065.[HistoryItemGUID] +, [grp7B1AFC84DBD346F9A5E90839ADF09065].[Version]FROM [fw].[DimUnitType] grp7B1AFC84DBD346F9A5E90839ADF09065 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimUnit_auto +--Last Modified 10/22/2020 5:41 PM +CREATE VIEW [fw].[viewDimUnit_auto] +AS +SELECT + grpB9BA9ECBC1214A079F252B81ED4DFE6F.[Name] + ,grpB9BA9ECBC1214A079F252B81ED4DFE6F.[Abbreviation] + ,grpB9BA9ECBC1214A079F252B81ED4DFE6F.[MemberGUID] + ,grpB9BA9ECBC1214A079F252B81ED4DFE6F.[UnitID] + ,grpB9BA9ECBC1214A079F252B81ED4DFE6F.[SortOrder] + ,grpB9BA9ECBC1214A079F252B81ED4DFE6F.[IsActive] +, [grpB9BA9ECBC1214A079F252B81ED4DFE6F].[Version], [grpB9BA9ECBC1214A079F252B81ED4DFE6F].[HistoryItemGUID]FROM [fw].[DimUnit] grpB9BA9ECBC1214A079F252B81ED4DFE6F (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimUserProfile +CREATE view [fw].[viewDimUserProfile] + as + select + up.UserGUID as MemberGUID, + up.UserGUID, + up.UserName, + up.NameFull, + ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0) AS IsSysAdmin, + CAST (0 as bit) as IsDeleted, + dbo.ZeroGUID() as HistoryItemGUID, + CAST(UserGUID as varchar(36)) as LootID + from UserProfile up + left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = 'GEN - User Administrator') + where up.IsDisabled = 0 +GO + + +--------------------------------------------- + +-- fw.viewDimUserRole +CREATE VIEW [fw].[viewDimUserRole] +AS +SELECT + grp35E4A606568B4382851EBD0183D9C8CF.[Description] + ,grp35E4A606568B4382851EBD0183D9C8CF.[Type] + ,grp35E4A606568B4382851EBD0183D9C8CF.[Category] + ,grp35E4A606568B4382851EBD0183D9C8CF.[RoleID] + ,grp35E4A606568B4382851EBD0183D9C8CF.[Name] + ,grp35E4A606568B4382851EBD0183D9C8CF.[MemberGUID] + ,grp35E4A606568B4382851EBD0183D9C8CF.[HistoryItemGUID] +FROM [fw].[viewDimUserRoleInfo] grp35E4A606568B4382851EBD0183D9C8CF +GO + + +--------------------------------------------- + +-- fw.viewDimUserRoleInfo +create view fw.viewDimUserRoleInfo +as + select + UserRoleGUID as MemberGUID, + RoleID, + Name, + Description, + Type, + Category, + dbo.ZeroGUID() as HistoryItemGUID + from + [dbo].[UserRole] with (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimUsers +CREATE view fw.viewDimUsers +AS +select + UP.UserGUID as [MemberGUID], + UP.UserGUID as [UserGUID], + UP.UserName, + UP.NameFirst, + UP.NameLast, + UP.NameFull, + UP.EmailAddress, + UP.PhoneNumber, + ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0) AS IsSysAdmin +from dbo.UserProfile UP +left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = 'GEN - User Administrator') +GO + + +--------------------------------------------- + +-- fw.viewDimUsers_auto +CREATE VIEW [fw].[viewDimUsers_auto] +AS +SELECT + grp1F25D2EFD624418E8482FEAB7BAE4841.[MemberGUID] + ,coalesce(grp1F25D2EFD624418E8482FEAB7BAE4841.[UserName],'') as [UserName] + ,coalesce(grp1F25D2EFD624418E8482FEAB7BAE4841.[NameFirst],'') as [NameFirst] + ,coalesce(grp1F25D2EFD624418E8482FEAB7BAE4841.[NameLast],'') as [NameLast] + ,coalesce(grp1F25D2EFD624418E8482FEAB7BAE4841.[EmailAddress],'') as [EmailAddress] + ,coalesce(grp1F25D2EFD624418E8482FEAB7BAE4841.[PhoneNumber],'') as [PhoneNumber] + ,grp1F25D2EFD624418E8482FEAB7BAE4841.[IsSysAdmin] + ,coalesce(grp1F25D2EFD624418E8482FEAB7BAE4841.[NameFull],'') as [NameFull] + ,grp1F25D2EFD624418E8482FEAB7BAE4841.[UserGUID] +FROM [fw].[viewDimUsers] grp1F25D2EFD624418E8482FEAB7BAE4841 +GO + + +--------------------------------------------- + +-- fw.viewDimVariability +--Last Modified 12/9/2016 2:10 PM +CREATE VIEW [fw].[viewDimVariability] +AS +SELECT + grp093B96C5E7324756BDD0329EB4A55B43.[VariabilityID] + ,grp093B96C5E7324756BDD0329EB4A55B43.[Name] + ,grp093B96C5E7324756BDD0329EB4A55B43.[TransactionID] + ,grp093B96C5E7324756BDD0329EB4A55B43.[MemberGUID] + ,grp093B96C5E7324756BDD0329EB4A55B43.[HistoryItemGUID] +FROM [fw].[DimVariability] grp093B96C5E7324756BDD0329EB4A55B43 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimVendor +CREATE VIEW [fw].[viewDimVendor] +AS + SELECT + VendorCode AS [VendorCode] + ,MemberGUID + ,VendorID AS [VendorID] + ,Name + ,VendorRollup + ,VendorDescription + ,IsActive + FROM [cap].[DimVendor]; +GO + + +--------------------------------------------- + +-- fw.viewDimVendor_auto +--Last Modified 7/18/2017 3:21 PM +CREATE VIEW [fw].[viewDimVendor_auto] +AS +SELECT + grpA3C8AA18CD8446948E36DB868059BC19.[VendorCode] + ,grpA3C8AA18CD8446948E36DB868059BC19.[MemberGUID] + ,grpA3C8AA18CD8446948E36DB868059BC19.[VendorID] + ,coalesce(grpA3C8AA18CD8446948E36DB868059BC19.[VendorRollup],'') as [VendorRollup] + ,grpA3C8AA18CD8446948E36DB868059BC19.[VendorDescription] + ,grpA3C8AA18CD8446948E36DB868059BC19.[IsActive] + ,[grpA3C8AA18CD8446948E36DB868059BC19].[VendorCode] + ' - ' + [grpA3C8AA18CD8446948E36DB868059BC19].[VendorDescription] AS [Name] +FROM [fw].[viewDimVendor] grpA3C8AA18CD8446948E36DB868059BC19 +GO + + +--------------------------------------------- + +-- fw.viewDimWorkWeek +--Last Modified 3/3/2015 10:40 AM +CREATE VIEW [fw].[viewDimWorkWeek] +AS +SELECT + grpFDAFCE80DC5344DA9680D20E7596BC98.[MemberGUID] + ,grpFDAFCE80DC5344DA9680D20E7596BC98.[WorkWeekID] + ,grpFDAFCE80DC5344DA9680D20E7596BC98.[Name] + ,grpFDAFCE80DC5344DA9680D20E7596BC98.[WorkWeekCode] + ,grpFDAFCE80DC5344DA9680D20E7596BC98.[Type] + ,grpFDAFCE80DC5344DA9680D20E7596BC98.[TransactionID] + ,grpFDAFCE80DC5344DA9680D20E7596BC98.[HistoryItemGUID] + ,grpFDAFCE80DC5344DA9680D20E7596BC98.[SortOrder] +FROM [fw].[DimWorkWeek] grpFDAFCE80DC5344DA9680D20E7596BC98 (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimWorkWeekPH +CREATE VIEW [fw].[viewDimWorkWeekPH] +AS +SELECT + grp5B25135186E54281B07A9C0128CEBF9E.[MemberGUID] + ,grp5B25135186E54281B07A9C0128CEBF9E.[WorkWeekPHID] + ,grp5B25135186E54281B07A9C0128CEBF9E.[Name] + ,grp5B25135186E54281B07A9C0128CEBF9E.[TransactionID] + ,grp5B25135186E54281B07A9C0128CEBF9E.[HistoryItemGUID] +FROM [fw].[DimWorkWeekPH] grp5B25135186E54281B07A9C0128CEBF9E (readuncommitted) +GO + + +--------------------------------------------- + +-- fw.viewDimXPlan +CREATE view [fw].[viewDimXPlan] +as + select + P.PlanGUID as MemberGUID, + ISNULL(case when P.IsDeletedPlan = 1 then 'DELETED ' + P.Name else P.Name end,'') as Name, + P.PlanID, + P.CachedLootID, + P.IsDeletedPlan as IsDeleted, + P.PlanTypeGUID, + PT.Name as PlanTypeName + from + XPlan P (readuncommitted) + inner join PlanType PT (readuncommitted) on PT.PlanTypeGUID = P.PlanTypeGUID +GO + + +--------------------------------------------- + +-- fw.viewDimXPlan_auto +CREATE VIEW [fw].[viewDimXPlan_auto] +AS +SELECT + grpF444702419784B9EB154D1C4369A77C8.[MemberGUID] + ,coalesce(grpF444702419784B9EB154D1C4369A77C8.[Name],'') as [Name] + ,grpF444702419784B9EB154D1C4369A77C8.[PlanID] + ,coalesce(grpF444702419784B9EB154D1C4369A77C8.[CachedLootID],'') as [CachedLootID] + ,grpF444702419784B9EB154D1C4369A77C8.[PlanTypeGUID] + ,grpF444702419784B9EB154D1C4369A77C8.[PlanTypeName] + ,grpF444702419784B9EB154D1C4369A77C8.[IsDeleted] +FROM [fw].[viewDimXPlan] grpF444702419784B9EB154D1C4369A77C8 +GO + + +--------------------------------------------- + +-- fw.viewEliminationsDepartment +create view fw.viewEliminationsDepartment +as + select + d.DepartmentID, + d.Name + from + fw.viewDimDepartment d + where + d.DepartmentID != 0 + and ( + exists(select 1 from fw.DimSystem s where s.EliminationsDepartmentID = d.DepartmentID) + or exists(select 1 from fw.DimEntity e where e.EliminationsDepartmentID = d.DepartmentID) + or exists(select 1 from fw.DimDepartmentRollup1 r1 where r1.EliminationsDepartmentID = d.DepartmentID) + or exists(select 1 from fw.DimDepartmentRollup2 r2 where r2.EliminationsDepartmentID = d.DepartmentID) + or exists(select 1 from fw.DimDepartmentRollup3 r3 where r3.EliminationsDepartmentID = d.DepartmentID) + or exists(select 1 from fw.DimDepartmentRollup4 r4 where r4.EliminationsDepartmentID = d.DepartmentID) + or exists(select 1 from fw.DimDepartmentRollup5 r5 where r5.EliminationsDepartmentID = d.DepartmentID) + or exists(select 1 from fw.DimDepartmentRollup6 r6 where r6.EliminationsDepartmentID = d.DepartmentID) + ) +GO + + +--------------------------------------------- + +-- fw.viewFactGLSampled +CREATE view [fw].[viewFactGLSampled] as +select + fact.DepartmentID, + dept.DepartmentCode, + fact.AccountID, + acc.AccountCode, + accrollup.LineName as AccountRollup, + accrollup.Section as AccountCategory, + accrollup.Name as FinancialReporting, + fact.TimeClassID, + tc.TimeClassCode, + fact.FiscalYearID, + fy.Name, + fact.FiscalMonthID, + fm.FiscalMonthCode, + fm.SortOrder as FiscalMonthSortOrder, + Dollars, + DollarsYTD, + DollarsPriorYear, + DollarsPriorYTD, + Units, + UnitsYTD, + UnitsPriorYear, + UnitsPriorYTD + +from + fw.FactGLSampled fact + left join fw.DimDepartment dept on dept.DepartmentID=fact.DepartmentID + left join fw.DimAccount acc on acc.AccountID=fact.AccountID + left join fw.DimTimeClass tc on tc.TimeClassID=fact.TimeClassID + left join fw.DimFiscalMonth fm on fm.FiscalMonthID=fact.FiscalMonthID + left join fw.DimFiscalYear fy on fy.FiscalYearID=fact.FiscalYearID + left join [ob].[DimFinancialReporting] accrollup on acc.OBDollarsFinancialReportingID = accrollup.FinancialReportingID +where + fact.IsDeleted = 0 +GO + + +--------------------------------------------- + +-- fw.viewFactPayrollSampledDailyDetailedHours +--recreate referenced view +CREATE VIEW fw.viewFactPayrollSampledDailyDetailedHours + WITH SCHEMABINDING + AS +SELECT + pr.RowID, + pr.PayCodeGroupID, + pr.DateID, + pr.DepartmentID, + pr.EmployeeID, + pr.JobCodeID, + pr.TimeClassID, + pr.PayPeriodID, + pr.Hours +FROM + fw.FactPayrollSampledDailyDetailed pr +WHERE + pr.TimeClassID IN (1, 4, 20) + AND pr.EmployeeID <> 0 + AND pr.Hours <> 0; +GO + + +--------------------------------------------- + +-- fw.viewFactPayrollSampledMonthly +CREATE view [fw].[viewFactPayrollSampledMonthly] as + + +select + fact.DepartmentID, + dept.DepartmentCode, + fact.JobCodeID, + jc.JobCode, + fact.PayCodeID, + pc.PayCode, + fact.TimeClassID, + tc.TimeClassCode, + fact.FiscalYearID, + fy.Name, + fact.FiscalMonthID, + fm.FiscalMonthCode, + fm.SortOrder as FiscalMonthSortOrder, + Dollars, + DollarsYTD, + DollarsPriorYear, + DollarsPriorYTD, + Hours, + HoursYTD, + HoursPriorYear, + HoursPriorYTD, + fact.FTEs, + fact.FTEsYTD, + fact.FTEsPriorYear, + fact.FTEsPriorYTD +from + fw.FactPayrollSampledMonthly fact + left join fw.DimDepartment dept on dept.DepartmentID=fact.DepartmentID + left join fw.DimJobCode jc on jc.JobCodeID=fact.JobCodeID + left join fw.DimPayCode pc on pc.PayCodeID=fact.PayCodeID + left join fw.DimTimeClass tc on tc.TimeClassID=fact.TimeClassID + left join fw.DimFiscalMonth fm on fm.FiscalMonthID=fact.FiscalMonthID + left join fw.DimFiscalYear fy on fy.FiscalYearID=fact.FiscalYearID + +where + fact.IsDeleted = 0 +GO + + +--------------------------------------------- + +-- fw.viewFactStatiscticDailyWithReallocaitonAdjustments +/************************************************************ +** Author: ipetriv +** Create Date: 2017-7-26 +** Description: View to append to int.FactStatistic PR statistic reallocation adjustments +** Last Modified: 2017-7-26 +** GM Release: 2018.1 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-7-26 IP B-16752 Added section for daily spread adjustments +*************************************************************/ +CREATE VIEW fw.[viewFactStatiscticDailyWithReallocaitonAdjustments] +as +SELECT + SubSelect.DepartmentID, + SubSelect.AccountID, + SubSelect.FiscalMonthID, + SubSelect.FiscalYearID, + DT.DateID, + SubSelect.TimeClassID, + SUM(SubSelect.Units) AS Units +FROM ( + select + STAT.DepartmentID, + STAT.AccountID, + STAT.FiscalYearID, + STAT.FiscalMonthID, + STAT.TimeClassID, + SUM(STAT.Value) AS Units + from + [int].[FactStatistic] STAT + inner join [fw].[DimDepartment] D on D.Departmentid = STAT.Departmentid + where + STAT.FiscalMonthID != 0 + and STAT.FiscalYearID != 0 + and STAT.IsDeleted = 0 + and STAT.Value != 0 + and (D.IsPR = 1 or exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache dc where dc.DriverDepartmentID = D.DepartmentID)) + and stat.TimeClassID = 2 + and stat.DepartmentID != 0 + group by + STAT.DepartmentID, + STAT.AccountID, + STAT.FiscalMonthID, + STAT.FiscalYearID, + STAT.TimeClassID + + UNION ALL + SELECT + SourceDepartmentID as DepartmentID, + SourceAccountID as AccountID, + FiscalYearID, + FiscalMonthID, + 2 as TimeclassID, + Change * -1 as Value + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID + inner join [fw].[DimDepartment] D on D.Departmentid = SourceDepartmentID and (D.IsPR = 1 or exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache dc where dc.DriverDepartmentID = D.DepartmentID)) + WHERE b.TargetDepartmentID<>0 AND b.TargetAccountID<>0 + and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/ +UNION All +SELECT + TargetDepartmentID as DepartmentID, + TargetAccountID as AccountID, + FiscalYearID, + FiscalMonthID, + 2 as TimeclassID, + Change as Value +FROM [mr].[BudgetReallocation] b +INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID +INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID +inner join [fw].[DimDepartment] D on D.Departmentid = TargetDepartmentID and (D.IsPR = 1 or exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache dc where dc.DriverDepartmentID = D.DepartmentID)) +WHERE b.TargetDepartmentID<>0 AND b.TargetAccountID<>0 +and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/ + +--Spread Adjustments within same Department/Account +UNION All +SELECT + SourceDepartmentID as DepartmentID, + SourceAccountID as AccountID, + FiscalYearID, + FiscalMonthID, + 2 as TimeclassID, + Change as Value +FROM [mr].[BudgetReallocation] b +INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID +INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID +inner join [fw].[DimDepartment] D on D.Departmentid = SourceDepartmentID and (D.IsPR = 1 or exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache dc where dc.DriverDepartmentID = D.DepartmentID)) +WHERE b.TargetDepartmentID=0 AND b.TargetAccountID=0 + and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/ +) SubSelect +inner join [fw].[DimDate] DT on DT.CalendarMonth = SubSelect.FiscalMonthID and DT.FiscalYear = SubSelect.FiscalYearID +GROUP BY + SubSelect.DepartmentID, + SubSelect.AccountID, + SubSelect.FiscalMonthID, + SubSelect.FiscalYearID, + DT.DateID, + SubSelect.TimeClassID +GO + + +--------------------------------------------- + +-- fw.viewFactStatiscticMonthlyWithReallocaitonAdjustments +CREATE View fw.[viewFactStatiscticMonthlyWithReallocaitonAdjustments] as +/************************************************************ +** Author: ipetriv +** Create Date: 2017-7-26 +** Description: View to append to int.FactStatistic MR statistic reallocation adjustments +** Last Modified: 2017-7-26 +** GM Release: 2018.1 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-7-26 IP B-16752 Added section for monthly spread adjustments +*************************************************************/ + +SELECT + DepartmentID, + AccountID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + SUM(Amount) as Amount +FROM ( + select + stat.DepartmentID, + stat.AccountID, + stat.FiscalYearID, + stat.FiscalMonthID, + stat.TimeClassID, + STAT.Value as Amount + from + int.FactStatistic stat + inner join fw.DimAccount A on A.Accountid = STAT.Accountid + inner join fw.DimDepartment D on D.Departmentid = STAT.Departmentid + where + A.IsStat = 1 + AND stat.IsDeleted = 0 + and stat.Value != 0 +UNION ALL + SELECT + SourceDepartmentID as DepartmentID, + SourceAccountID as AccountID, + FiscalYearID, + FiscalMonthID, + 2 as TimeclassID, + Change * -1 as Value + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID + WHERE b.TargetDepartmentID<>0 AND b.TargetAccountID<>0 + and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/ +UNION All +SELECT + TargetDepartmentID as DepartmentID, + TargetAccountID as AccountID, + FiscalYearID, + FiscalMonthID, + 2 as TimeclassID, + Change as Value +FROM [mr].[BudgetReallocation] b +INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID +INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID +WHERE b.TargetDepartmentID<>0 AND b.TargetAccountID<>0 +and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/ + +--Spread Adjustments within same Department/Account +UNION All +SELECT + SourceDepartmentID as DepartmentID, + SourceAccountID as AccountID, + FiscalYearID, + FiscalMonthID, + 2 as TimeclassID, + Change as Value +FROM [mr].[BudgetReallocation] b +INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID +INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID +WHERE b.TargetDepartmentID=0 AND b.TargetAccountID=0 + and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/ +) SubSelect +GROUP BY + DepartmentID, + AccountID, + FiscalYearID, + FiscalMonthID, + TimeClassID +GO + + +--------------------------------------------- + +-- fw.viewFactStatiscticPrimaryMonthlyWithReallocaitonAdjustments +CREATE View fw.[viewFactStatiscticPrimaryMonthlyWithReallocaitonAdjustments] as +/************************************************************ +** Author: ipetriv +** Create Date: 2017-7-26 +** Description: View to append to int.FactStatistic MR statistic reallocation adjustments +** Last Modified: 2017-7-26 +** GM Release: 2018.1 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-7-26 IP B-16752 Added section for monthly spread adjustments +*************************************************************/ + +SELECT + DepartmentID, + AccountID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + SUM(Amount) as Amount +FROM ( + select + stat.DepartmentID, + stat.AccountID, + stat.FiscalYearID, + stat.FiscalMonthID, + stat.TimeClassID, + STAT.Value as Amount + from + int.FactStatistic stat + inner join fw.DimAccount A on A.Accountid = STAT.Accountid + inner join fw.DimDepartment D on D.Departmentid = STAT.Departmentid + inner join [fw].[viewStatisticPrimaryConfiguration] V on V.AccountID=stat.AccountID and V.DepartmentID=stat.DepartmentID + where + A.IsStat = 1 + AND stat.IsDeleted = 0 + and stat.Value != 0 +UNION ALL + SELECT + SourceDepartmentID as DepartmentID, + SourceAccountID as AccountID, + FiscalYearID, + FiscalMonthID, + 2 as TimeclassID, + Change * -1 as Value + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID + inner join [fw].[viewStatisticPrimaryConfiguration] V on V.AccountID=A.AccountID and V.DepartmentID=SourceDepartmentID + WHERE b.TargetDepartmentID<>0 AND b.TargetAccountID<>0 + and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/ +UNION All +SELECT + TargetDepartmentID as DepartmentID, + TargetAccountID as AccountID, + FiscalYearID, + FiscalMonthID, + 2 as TimeclassID, + Change as Value +FROM [mr].[BudgetReallocation] b +INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID +INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID +inner join [fw].[viewStatisticPrimaryConfiguration] V on V.AccountID=A.AccountID and V.DepartmentID=TargetDepartmentID +WHERE b.TargetDepartmentID<>0 AND b.TargetAccountID<>0 +and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/ + +--Spread Adjustments within same Department/Account +UNION All +SELECT + SourceDepartmentID as DepartmentID, + SourceAccountID as AccountID, + FiscalYearID, + FiscalMonthID, + 2 as TimeclassID, + Change as Value +FROM [mr].[BudgetReallocation] b +INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID +INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID +inner join [fw].[viewStatisticPrimaryConfiguration] V on V.AccountID=A.AccountID and V.DepartmentID=SourceDepartmentID +WHERE b.TargetDepartmentID=0 AND b.TargetAccountID=0 + and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/ +) SubSelect +GROUP BY + DepartmentID, + AccountID, + FiscalYearID, + FiscalMonthID, + TimeClassID +GO + + +--------------------------------------------- + +-- fw.viewFactStatisticByPayPeriodWithReallocaitonAdjustments +CREATE VIEW fw.viewFactStatisticByPayPeriodWithReallocaitonAdjustments +/************************************************************ +** Author: ipetriv +** Create Date: 2017-7-26 +** Description: View to append to int.FactStatistic MR statistic reallocation adjustments +** Last Modified: 2017-7-26 +** GM Release: 2018.1 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-7-26 IP B-16752 Added section for monthly spread adjustments +*************************************************************/ + +AS +SELECT DepartmentID, + AccountID, + PayPeriodID, + TimeClassID, + sum(Value) AS Value +FROM ( + SELECT STAT.DepartmentID, + STAT.AccountID, + STAT.PayPeriodID, + STAT.TimeClassID, + STAT.Value + FROM [int].[FactStatisticsbyPayPeriod] STAT + INNER JOIN [fw].[DimDepartment] D + ON D.Departmentid = STAT.Departmentid + WHERE STAT.Value != 0 + AND STAT.Isdeleted = 0 + AND STAT.PayPeriodID != 0 + AND ( + D.IsPR = 1 + OR EXISTS ( + SELECT 1 + FROM client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache dc + WHERE dc.DriverDepartmentID = D.DepartmentID + ) + ) + AND STAT.TimeClassID IN (1,2) + AND stat.DepartmentID <> 0 + --ADD ADJUSTMENTS + + UNION ALL + + SELECT ADJ.DepartmentID, + ADJ.AccountID, + PP.PayPeriodID, + 2 AS TimeClassID, + Adj.Amount * PP.PreriodWeight AS Units + FROM ( + SELECT DepartmentID, + AccountID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + SUM(Value) AS Amount + FROM ( + SELECT SourceDepartmentID AS DepartmentID, + SourceAccountID AS AccountID, + FiscalYearID, + FiscalMonthID, + 2 AS TimeclassID, + Change * - 1 AS Value + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba + ON b.BudgetReallocationGUID = ba.BudgetReallocationGUID + INNER JOIN [fw].[DimAccount] A + ON SourceAccountID = A.AccountID + WHERE b.TargetDepartmentID <> 0 + AND b.TargetAccountID <> 0 + AND ba.UnitTypeID = 145 /*select * from fw.dimUnitType where Name = 'Units'*/ + + UNION ALL + + SELECT TargetDepartmentID AS DepartmentID, + TargetAccountID AS AccountID, + FiscalYearID, + FiscalMonthID, + 2 AS TimeclassID, + Change AS Value + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba + ON b.BudgetReallocationGUID = ba.BudgetReallocationGUID + INNER JOIN [fw].[DimAccount] A + ON SourceAccountID = A.AccountID + WHERE b.TargetDepartmentID <> 0 + AND b.TargetAccountID <> 0 + AND ba.UnitTypeID = 145 /*select * from fw.dimUnitType where Name = 'Units'*/ + --Spread Adjustments within same Department/Account + + UNION ALL + + SELECT SourceDepartmentID AS DepartmentID, + SourceAccountID AS AccountID, + FiscalYearID, + FiscalMonthID, + 2 AS TimeclassID, + Change AS Value + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba + ON b.BudgetReallocationGUID = ba.BudgetReallocationGUID + INNER JOIN [fw].[DimAccount] A + ON SourceAccountID = A.AccountID + WHERE b.TargetDepartmentID = 0 + AND b.TargetAccountID = 0 + AND ba.UnitTypeID = 145 /*select * from fw.dimUnitType where Name = 'Units'*/ + ) SubSelect + GROUP BY DepartmentID, + AccountID, + FiscalYearID, + FiscalMonthID, + TimeClassID + ) AS Adj + INNER JOIN fw.DimDepartment dd + ON adj.DepartmentID = dd.DepartmentID + INNER JOIN ( + SELECT [PayPeriodID], + PayCycleID, + [PeriodNumber], + [FiscalMonthIDStart] AS FiscalMonthID, + [FiscalYearIDStart] AS FiscalYearID, + [PeriodWeightStart] AS PreriodWeight + FROM [fw].[DimPayPeriod] + + UNION ALL + + SELECT [PayPeriodID], + PayCycleID, + [PeriodNumber], + FiscalMonthIDSecond AS FiscalMonthID, + FiscalYearIDSecond AS FiscalYearID, + PeriodWeightSecond AS PreriodWeight + FROM [fw].[DimPayPeriod] + ) PP + ON PP.FiscalYearID = Adj.FiscalYearID + AND pp.FiscalMonthID = adj.FiscalMonthID + AND pp.PayCycleID = dd.PayCycleID + AND Adj.Amount * PP.PreriodWeight <> 0 + ) SubSelect +GROUP BY DepartmentID, + AccountID, + PayPeriodID, + TimeClassID +GO + + +--------------------------------------------- + +-- fw.viewFactStatisticRollupPrimarySampledMonthly +CREATE VIEW [fw].[viewFactStatisticRollupPrimarySampledMonthly] +AS +SELECT + cfg.RollupLevel, + cfg.RollupMemberID, + fs.AccountID, + fs.FiscalYearID, + fs.FiscalMonthID, + fs.TimeClassID, + sum(fs.Amount) as Amount, + sum(fs.AmountYTD) as AmountYTD, + sum(fs.AmountPriorYear) as AmountPriorYear, + sum(fs.AmountPriorYTD) as AmountPriorYTD, + min(cast(fs.IsSystemGenerated AS INT)) AS IsSystemGenerated +FROM [fw].FactStatisticSampledMonthly fs +INNER JOIN fw.DimDepartment dd ON fs.DepartmentID = dd.DepartmentID +INNER JOIN fw.PrimaryStatisticsRollupsConfiguration cfg ON ( + (cfg.RollupLevel = 'DepartmentRollup1' AND cfg.RollupMemberID = dd.DepartmentRollup1ID) + OR (cfg.RollupLevel = 'DepartmentRollup2' AND cfg.RollupMemberID = dd.DepartmentRollup2ID) + OR (cfg.RollupLevel = 'DepartmentRollup3' AND cfg.RollupMemberID = dd.DepartmentRollup3ID) + OR (cfg.RollupLevel = 'DepartmentRollup4' AND cfg.RollupMemberID = dd.DepartmentRollup4ID) + OR (cfg.RollupLevel = 'DepartmentRollup5' AND cfg.RollupMemberID = dd.DepartmentRollup5ID) + OR (cfg.RollupLevel = 'DepartmentRollup6' AND cfg.RollupMemberID = dd.DepartmentRollup6ID) + OR (cfg.RollupLevel = 'Entity' AND cfg.RollupMemberID = dd.EntityID) + OR (cfg.RollupLevel = 'System' AND cfg.RollupMemberID = dd.SystemID) + ) AND fs.AccountID = cfg.AccountID +WHERE fs.IsDeleted = 0 +AND IsMRMetricTracking = 1 +GROUP BY + cfg.RollupLevel, + cfg.RollupMemberID, + fs.AccountID, + fs.FiscalYearID, + fs.FiscalMonthID, + fs.TimeClassID +GO + + +--------------------------------------------- + +-- fw.viewFactStatisticSampledMonthly +CREATE view [fw].[viewFactStatisticSampledMonthly] as +select + fact.DepartmentID, + dept.DepartmentCode, + fact.AccountID, + acc.AccountCode, + accrollup.LineName as AccountRollup, + accrollup.Section as AccountCategory, + accrollup.Name as FinancialReporting, + fact.TimeClassID, + tc.TimeClassCode, + fact.FiscalYearID, + fy.Name, + fact.FiscalMonthID, + fm.FiscalMonthCode, + fm.SortOrder as FiscalMonthSortOrder, + fact.Amount, + fact.AmountPriorYear, + fact.AmountPriorYTD, + fact.AmountYTD + +from + fw.FactStatisticSampledMonthly fact + left join fw.DimDepartment dept on dept.DepartmentID=fact.DepartmentID + left join fw.DimAccount acc on acc.AccountID=fact.AccountID + left join fw.DimTimeClass tc on tc.TimeClassID=fact.TimeClassID + left join fw.DimFiscalMonth fm on fm.FiscalMonthID=fact.FiscalMonthID + left join fw.DimFiscalYear fy on fy.FiscalYearID=fact.FiscalYearID + left join [ob].[DimFinancialReporting] accrollup on acc.OBDollarsFinancialReportingID = accrollup.FinancialReportingID +where + fact.IsDeleted = 0 +GO + + +--------------------------------------------- + +-- fw.viewFactStatisticSecondaryMonthlyWithReallocaitonAdjustments +CREATE View fw.[viewFactStatisticSecondaryMonthlyWithReallocaitonAdjustments] as +/************************************************************ +** Author: ipetriv +** Create Date: 2017-7-26 +** Description: View to append to int.FactStatistic MR statistic reallocation adjustments +** Last Modified: 2017-7-26 +** GM Release: 2018.1 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-7-26 IP B-16752 Added section for monthly spread adjustments +*************************************************************/ + + SELECT + DepartmentID, + AccountID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + SUM(Amount) as Amount +FROM ( + select + stat.DepartmentID, + stat.AccountID, + stat.FiscalYearID, + stat.FiscalMonthID, + stat.TimeClassID, + STAT.Value as Amount + from + int.FactStatistic stat + inner join fw.DimAccount A on A.Accountid = STAT.Accountid + inner join fw.DimDepartment D on D.Departmentid = STAT.Departmentid + inner join [fw].[viewStatisticSecondaryConfiguration] V on V.AccountID=stat.AccountID and V.DepartmentID=stat.DepartmentID + where + A.IsStat = 1 + AND stat.IsDeleted = 0 + and stat.Value != 0 +UNION ALL + SELECT + SourceDepartmentID as DepartmentID, + SourceAccountID as AccountID, + FiscalYearID, + FiscalMonthID, + 2 as TimeclassID, + Change * -1 as Value + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID + inner join [fw].[viewStatisticPrimaryConfiguration] V on V.AccountID=A.AccountID and V.DepartmentID=SourceDepartmentID + WHERE b.TargetDepartmentID<>0 AND b.TargetAccountID<>0 + and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/ +UNION All +SELECT + TargetDepartmentID as DepartmentID, + TargetAccountID as AccountID, + FiscalYearID, + FiscalMonthID, + 2 as TimeclassID, + Change as Value +FROM [mr].[BudgetReallocation] b +INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID +INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID +inner join [fw].[viewStatisticSecondaryConfiguration] V on V.AccountID=A.AccountID and V.DepartmentID=TargetDepartmentID +WHERE b.TargetDepartmentID<>0 AND b.TargetAccountID<>0 +and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/ + +--Spread Adjustments within same Department/Account +UNION All +SELECT + SourceDepartmentID as DepartmentID, + SourceAccountID as AccountID, + FiscalYearID, + FiscalMonthID, + 2 as TimeclassID, + Change as Value +FROM [mr].[BudgetReallocation] b +INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID +INNER JOIN [fw].[DimAccount] A on SourceAccountID=A.AccountID +inner join [fw].[viewStatisticSecondaryConfiguration] V on V.AccountID=A.AccountID and V.DepartmentID=SourceDepartmentID +WHERE b.TargetDepartmentID=0 AND b.TargetAccountID=0 + and ba.UnitTypeID =145 /*select * from fw.dimUnitType where Name = 'Units'*/ +) SubSelect +GROUP BY + DepartmentID, + AccountID, + FiscalYearID, + FiscalMonthID, + TimeClassID +GO + + +--------------------------------------------- + +-- fw.viewFiscalYearMonth +CREATE VIEW [fw].[viewFiscalYearMonth] AS + SELECT + ROW_NUMBER() over (order by y.fiscalyearid, m.sortorder) as FiscalTimeID, + FiscalMonthID, m.Name as [FiscalMonth], + y.FiscalYearID, y.Name as [FiscalYear] + FROM + fw.DimFiscalMonth m + CROSS JOIN + fw.DimFiscalYear y + WHERE + m.FiscalMonthID <> 0 AND y.FiscalYearID <> 0 +GO + + +--------------------------------------------- + +-- fw.viewLeapYearByFiscalYear +CREATE VIEW fw.viewLeapYearByFiscalYear +AS +SELECT DISTINCT + CalendarYear, + FiscalYear, + CASE WHEN (FiscalYear % 4 = 0 AND FiscalYear % 100 != 0) OR FiscalYear % 400 = 0 THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END AS IsLeapYear +FROM [fw].[DimDate] +WHERE CalendarMonth = 2 +GO + + +--------------------------------------------- + +-- fw.viewMRGLBudgetCostPerRVUbyMonth +CREATE VIEW [fw].[viewMRGLBudgetCostPerRVUbyMonth] AS + + SELECT + A.DepartmentID + ,B.AccountID + ,A.ChargeCodeID + ,A.CostComponentID + ,A.FiscalMonthID + ,A.FiscalYearID + ,A.ChargeVolume + ,B.CostingResultID + ,B.TimeClassID + ,(A.ChargeVolume * A.RVU * B.VariableDirectUnitCostPerRVU) as ExtendedVariableDirectCost + ,B.TotalCost + ,B.TotalVariableDirectCost + FROM + (SELECT + b.DepartmentID + , b.ChargeCodeID + , ca.CostComponentID + , b.FiscalMonthID + , b.FiscalYearID + , MAX(ca.RVU) as RVU + , SUM(Volume) as ChargeVolume + FROM [dss].[FactDepartmentChargeSummary] b + INNER JOIN [dss].[ChargeAllocation] ca + ON ca.ChargeCodeID = b.ChargeCodeID + and ca.DepartmentID = b.DepartmentID + and AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0 + GROUP BY + b.DepartmentID, b.ChargeCodeID, ca.CostComponentID, b.FiscalMonthID, b.FiscalYearID) A + + INNER JOIN + + (SELECT + OriginalAccountID as AccountID + , gl.OriginalDepartmentID as DepartmentID + , gl.FiscalYearID + , gl.CostComponentID + , gl.CostingResultID + , gl.TimeClassID + , SUM(gl.VariableDirectUnitCost)/SUM(ca.RVU) as VariableDirectUnitCostPerRVU + , SUM(gl.VariableDirectUnitCost * gl.Volume) as TotalVariableDirectCost + , SUM(gl.TotalCost) as TotalCost + FROM [dss].[FactCostingOutDetailGL] gl + INNER JOIN [dss].[CostingResult] cr on gl.CostingResultID = cr.CostingResultID + INNER JOIN [dss].[CostingConfig] con on cr.CostingConfigGuid = con.CostingConfigGuid + INNER JOIN [dss].[ChargeAllocation] ca on + ca.CostingConfigGuid = con.CostingConfigGUID + and ca.ChargeCodeID = gl.ChargeCodeID + and ca.DepartmentID = gl.OriginalDepartmentID + and ca.CostComponentID = gl.CostComponentID + and AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0 + WHERE + gl.CostingResultID in (select CostingResultID from + (select FiscalYearID, max(CostingResultID) as CostingResultID + from [dss].[CostingResult] cr3 + inner join [dss].[CostingConfig] cfg on cfg.CostingConfigGuid = cr3.CostingConfigGuid + where cr3.IsActivityBasedDetail = 1 and cr3.IsMarkedForDeletion = 0 and cr3.IsFailure = 0 + group by FiscalYearID) C) + GROUP BY + gl.OriginalAccountID + , gl.OriginalDepartmentID + , gl.FiscalYearID + , gl.CostComponentID + , gl.CostingResultID + , gl.TimeClassID) B + ON + A.DepartmentID = B.DepartmentID + and A.CostComponentID = B.CostComponentID + and A.FiscalYearID = b.FiscalYearID +GO + + +--------------------------------------------- + +-- fw.viewMRPayrollBudgetCostPerRVUbyMonth +CREATE VIEW [fw].[viewMRPayrollBudgetCostPerRVUbyMonth] AS + + SELECT + A.DepartmentID + ,B.JobCodeID + ,B.PayCodeGroupID + ,A.ChargeCodeID + ,A.CostComponentID + ,A.FiscalMonthID + ,A.FiscalYearID + ,A.ChargeVolume + ,B.CostingResultID + ,B.TimeClassID + ,(A.ChargeVolume * A.RVU * B.VariableDirectUnitCostPerRVU) as ExtendedVariableDirectCost + ,B.TotalCost + ,B.TotalVariableDirectCost + FROM + (SELECT + b.DepartmentID + , b.ChargeCodeID + , ca.CostComponentID + , b.FiscalMonthID + , b.FiscalYearID + , MAX(ca.RVU) as RVU + , SUM(Volume) as ChargeVolume + FROM [dss].[FactDepartmentChargeSummary] b + INNER JOIN [dss].[ChargeAllocation] ca + ON ca.ChargeCodeID = b.ChargeCodeID + and ca.DepartmentID = b.DepartmentID + and AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0 + GROUP BY + b.DepartmentID, b.ChargeCodeID, ca.CostComponentID, b.FiscalMonthID, b.FiscalYearID) A + + INNER JOIN + + (SELECT + OriginalJobCodeID as JobCodeID + , pc.PayCodeGroupID + , pay.OriginalDepartmentID as DepartmentID + , pay.FiscalYearID + , pay.CostComponentID + , pay.CostingResultID + , pay.TimeClassID + , SUM(pay.VariableDirectUnitCost)/SUM(ca.RVU) as VariableDirectUnitCostPerRVU + , SUM(pay.VariableDirectUnitCost * pay.Volume) as TotalVariableDirectCost + , SUM(pay.TotalCost) as TotalCost + FROM [dss].[FactCostingOutDetailPayroll] pay + INNER JOIN [dss].[CostingResult] cr on pay.CostingResultID = cr.CostingResultID + INNER JOIN [dss].[CostingConfig] con on cr.CostingConfigGuid = con.CostingConfigGuid + INNER JOIN [dss].[ChargeAllocation] ca on + ca.CostingConfigGuid = con.CostingConfigGUID + and ca.ChargeCodeID = pay.ChargeCodeID + and ca.DepartmentID = pay.OriginalDepartmentID + and ca.CostComponentID = pay.CostComponentID + and AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0 + INNER JOIN [fw].[DimPayCode] pc on pc.PayCodeID = pay.OriginalPayCodeID + WHERE + pay.CostingResultID in (select CostingResultID from + (select FiscalYearID, max(CostingResultID) as CostingResultID + from [dss].[CostingResult] cr3 + inner join [dss].[CostingConfig] cfg on cfg.CostingConfigGuid = cr3.CostingConfigGuid + where cr3.IsActivityBasedDetail = 1 and cr3.IsMarkedForDeletion = 0 and cr3.IsFailure = 0 + group by FiscalYearID) C) + GROUP BY + pay.OriginalJobCodeID + , pc.PayCodeGroupID + , pay.OriginalDepartmentID + , pay.FiscalYearID + , pay.CostComponentID + , pay.CostingResultID + , pay.TimeClassID) B + ON + A.DepartmentID = B.DepartmentID + and A.CostComponentID = B.CostComponentID + and A.FiscalYearID = B.FiscalYearID +GO + + +--------------------------------------------- + +-- fw.viewPrimaryStatisticsByPayPeriod +-- primary statistics (by pay period) driver accounts +CREATE view [fw].[viewPrimaryStatisticsByPayPeriod] as + SELECT [DepartmentID], [AccountID], [PayPeriodID], [TimeClassID], SUM([Units]) as Units, SUM([UnitsYTD]) as UnitsYTD, SUM([UnitsPriorYear]) as UnitsPriorYear, SUM([UnitsPriorYTD]) as UnitsPriorYTD, cast(MIN([IsSystemGenerated]) as bit) as IsSystemGenerated + FROM + + (SELECT fs.DepartmentID, fs.AccountID, fs.PayPeriodID, fs.TimeClassID, fs.Units, fs.UnitsYTD, fs.UnitsPriorYear, fs.UnitsPriorYTD, cast(fs.IsSystemGenerated as int) as IsSystemGenerated + FROM [fw].[FactStatisticSampledPayPeriod] fs + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID + WHERE fs.IsDeleted = 0 AND cfg.IsDeleted = 0 + AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID) + + UNION ALL + + SELECT pp.DepartmentID, pp.AccountID, pp.PayPeriodID, pp.TimeClassID, pp.Units, pp.UnitsYTD, pp.UnitsPriorYear, pp.UnitsPriorYTD, cast(0 as int) as IsSystemGenerated + FROM [fw].[FactStatisticDriverDepartmentSampledPayPeriod] pp + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON pp.DepartmentID = cfg.DepartmentID AND pp.AccountID = cfg.AccountID + WHERE pp.IsDeleted = 0 AND cfg.IsDeleted = 0) allData + + GROUP BY [DepartmentID], [AccountID], [PayPeriodID], [TimeClassID] +GO + + +--------------------------------------------- + +-- fw.viewPrimaryStatisticsDaily +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-09-13 HV JAZZ-38145 PR Metrics Definition - Calculate Configured Daily Metrics +*************************************************************/ + +CREATE view [fw].[viewPrimaryStatisticsDaily] +as + SELECT [DepartmentID], [AccountID], [PayPeriodID], [DateID], [TimeClassID], SUM([Units]) as Units + FROM + + (SELECT fs.DepartmentID, fs.AccountID, fs.PayPeriodID, fs.DateID, fs.TimeClassID, fs.Units + FROM [fw].[FactStatisticSampledDaily] fs + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID + WHERE fs.IsDeleted = 0 AND cfg.IsDeleted = 0 + AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID) + + UNION ALL + + SELECT pp.DepartmentID, pp.AccountID, pp.PayPeriodID, pp.DateID, pp.TimeClassID, pp.Units + FROM [fw].[FactStatisticDriverDepartmentSampledDaily] pp + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON pp.DepartmentID = cfg.DepartmentID AND pp.AccountID = cfg.AccountID + WHERE pp.IsDeleted = 0 AND cfg.IsDeleted = 0) allData + + GROUP BY [DepartmentID], [AccountID], [PayPeriodID], [DateID], [TimeClassID] +GO + + +--------------------------------------------- + +-- fw.viewPrimaryStatisticsNonStaffingExpenseByPayPeriod +-- primary statistics (by month) non-staffing driver accounts +CREATE view [fw].[viewPrimaryStatisticsNonStaffingExpenseByPayPeriod] as + + SELECT [DepartmentID], [AccountID], [PayPeriodID], [TimeClassID], SUM([Units]) as Units, SUM([UnitsYTD]) as UnitsYTD, SUM([UnitsPriorYear]) as UnitsPriorYear, SUM([UnitsPriorYTD]) as UnitsPriorYTD, MAX([RowID]) as RowID, cast(MAX(cast([IsDeleted] as int)) as bit) as IsDeleted, cast(MIN([IsSystemGenerated]) as bit) as IsSystemGenerated + FROM + + (SELECT fs.DepartmentID, fs.AccountID, fs.PayPeriodID, fs.TimeClassID, fs.Units, fs.UnitsYTD, fs.UnitsPriorYear, fs.UnitsPriorYTD, fs.RowID, fs.IsDeleted, cast(fs.IsSystemGenerated as int) as IsSystemGenerated + FROM [fw].[FactStatisticSampledPayPeriod] fs + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID + WHERE cfg.NonStaffingExpense = 1 AND fs.IsDeleted = 0 AND cfg.IsDeleted = 0 + AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID) + + UNION ALL + + SELECT pp.DepartmentID, pp.AccountID, pp.PayPeriodID, pp.TimeClassID, pp.Units, pp.UnitsYTD, pp.UnitsPriorYear, pp.UnitsPriorYTD, pp.RowID, pp.IsDeleted, cast(0 as int) as IsSystemGenerated + FROM [fw].[FactStatisticDriverDepartmentSampledPayPeriod] pp + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON pp.DepartmentID = cfg.DepartmentID AND pp.AccountID = cfg.AccountID + WHERE cfg.NonStaffingExpense = 1 AND pp.IsDeleted = 0 AND cfg.IsDeleted = 0) allData + + GROUP BY [DepartmentID], [AccountID], [PayPeriodID], [TimeClassID] +GO + + +--------------------------------------------- + +-- fw.viewPrimaryStatisticsNonStaffingExpenseDaily +CREATE view [fw].[viewPrimaryStatisticsNonStaffingExpenseDaily] +as + SELECT [DepartmentID], [AccountID], [PayPeriodID], [DateID], [TimeClassID], SUM([Units]) as Units + FROM + + (SELECT fs.DepartmentID, fs.AccountID, fs.PayPeriodID, fs.DateID, fs.TimeClassID, fs.Units + FROM [fw].[FactStatisticSampledDaily] fs + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID + WHERE cfg.NonStaffingExpense = 1 AND fs.IsDeleted = 0 AND cfg.IsDeleted = 0 + AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID) + + UNION ALL + + SELECT pp.DepartmentID, pp.AccountID, pp.PayPeriodID, pp.DateID, pp.TimeClassID, pp.Units + FROM [fw].[FactStatisticDriverDepartmentSampledDaily] pp + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON pp.DepartmentID = cfg.DepartmentID AND pp.AccountID = cfg.AccountID + WHERE cfg.NonStaffingExpense = 1 AND pp.IsDeleted = 0 AND cfg.IsDeleted = 0) allData + + GROUP BY [DepartmentID], [AccountID], [PayPeriodID], [DateID], [TimeClassID] +GO + + +--------------------------------------------- + +-- fw.viewPrimaryStatisticsNonStaffingExpenseMonthly +-- primary statistics (by month) non-staffing driver accounts +CREATE view [fw].[viewPrimaryStatisticsNonStaffingExpenseMonthly] as + + SELECT [RowID], [DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], [TimeClassID], SUM([Amount]) as Amount, SUM([AmountYTD]) as AmountYTD, SUM([AmountPriorYear]) as AmountPriorYear, SUM([AmountPriorYTD]) as AmountPriorYTD, cast(0 as bit) as IsDeleted, cast(MIN([IsSystemGenerated]) as bit) as IsSystemGenerated + FROM + + (SELECT fs.RowID, fs.DepartmentID, fs.AccountID, fs.FiscalYearID, fs.FiscalMonthID, fs.TimeClassID, fs.Amount, fs.AmountYTD, fs.AmountPriorYear, fs.AmountPriorYTD, cast(fs.IsSystemGenerated as int) as IsSystemGenerated + FROM [fw].[FactStatisticSampledMonthly] fs + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID + WHERE cfg.NonStaffingExpense = 1 AND fs.IsDeleted = 0 AND cfg.IsDeleted = 0 + AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID) + + UNION ALL + + SELECT mo.RowID, mo.DepartmentID, mo.AccountID, mo.FiscalYearID, mo.FiscalMonthID, mo.TimeClassID, mo.Amount, mo.AmountYTD, mo.AmountPriorYear, mo.AmountPriorYTD, cast(0 as int) as IsSystemGenerated + FROM [fw].[FactStatisticDriverDepartmentSampledMonthly] mo + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON mo.DepartmentID = cfg.DepartmentID AND mo.AccountID = cfg.AccountID + WHERE cfg.NonStaffingExpense = 1 AND mo.IsDeleted = 0 AND cfg.IsDeleted = 0) allData + + GROUP BY [RowID], [DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], [TimeClassID] +GO + + +--------------------------------------------- + +-- fw.viewPrimaryStatisticsRevenueByPayPeriod +-- primary statistics (by pay period) revenue driver accounts +CREATE view [fw].[viewPrimaryStatisticsRevenueByPayPeriod] as + + SELECT [DepartmentID], [AccountID], [PayPeriodID], [TimeClassID], SUM([Units]) as Units, SUM([UnitsYTD]) as UnitsYTD, SUM([UnitsPriorYear]) as UnitsPriorYear, SUM([UnitsPriorYTD]) as UnitsPriorYTD, MAX([RowID]) as RowID, cast(MAX(cast([IsDeleted] as int)) as bit) as IsDeleted, cast(MIN([IsSystemGenerated]) as bit) as IsSystemGenerated + FROM + + (SELECT fs.DepartmentID, fs.AccountID, fs.PayPeriodID, fs.TimeClassID, fs.Units, fs.UnitsYTD, fs.UnitsPriorYear, fs.UnitsPriorYTD, fs.RowID, fs.IsDeleted, cast(fs.IsSystemGenerated as int) as IsSystemGenerated + FROM [fw].[FactStatisticSampledPayPeriod] fs + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID + WHERE cfg.Revenue = 1 AND fs.IsDeleted = 0 AND cfg.IsDeleted = 0 + AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID) + + UNION ALL + + SELECT pp.DepartmentID, pp.AccountID, pp.PayPeriodID, pp.TimeClassID, pp.Units, pp.UnitsYTD, pp.UnitsPriorYear, pp.UnitsPriorYTD, pp.RowID, pp.IsDeleted, cast(0 as int) as IsSystemGenerated + FROM [fw].[FactStatisticDriverDepartmentSampledPayPeriod] pp + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON pp.DepartmentID = cfg.DepartmentID AND pp.AccountID = cfg.AccountID + WHERE cfg.Revenue = 1 AND pp.IsDeleted = 0 AND cfg.IsDeleted = 0) allData + + GROUP BY [DepartmentID], [AccountID], [PayPeriodID], [TimeClassID] +GO + + +--------------------------------------------- + +-- fw.viewPrimaryStatisticsRevenueDaily +CREATE view [fw].[viewPrimaryStatisticsRevenueDaily] +as + SELECT [DepartmentID], [AccountID], [PayPeriodID], [DateID], [TimeClassID], SUM([Units]) as Units + FROM + + (SELECT fs.DepartmentID, fs.AccountID, fs.PayPeriodID, fs.DateID, fs.TimeClassID, fs.Units + FROM [fw].[FactStatisticSampledDaily] fs + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID + WHERE cfg.Revenue = 1 AND fs.IsDeleted = 0 AND cfg.IsDeleted = 0 + AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID) + + UNION ALL + + SELECT pp.DepartmentID, pp.AccountID, pp.PayPeriodID, pp.DateID, pp.TimeClassID, pp.Units + FROM [fw].[FactStatisticDriverDepartmentSampledDaily] pp + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON pp.DepartmentID = cfg.DepartmentID AND pp.AccountID = cfg.AccountID + WHERE cfg.Revenue = 1 AND pp.IsDeleted = 0 AND cfg.IsDeleted = 0) allData + + GROUP BY [DepartmentID], [AccountID], [PayPeriodID], [DateID], [TimeClassID] +GO + + +--------------------------------------------- + +-- fw.viewPrimaryStatisticsRevenueMonthly +-- primary statistics (by month) revenue driver accounts +CREATE view [fw].[viewPrimaryStatisticsRevenueMonthly] as + + SELECT [RowID], [DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], [TimeClassID], SUM([Amount]) as Amount, SUM([AmountYTD]) as AmountYTD, SUM([AmountPriorYear]) as AmountPriorYear, SUM([AmountPriorYTD]) as AmountPriorYTD, cast(0 as bit) as IsDeleted, cast(MIN([IsSystemGenerated]) as bit) as IsSystemGenerated + FROM + + (SELECT fs.RowID, fs.DepartmentID, fs.AccountID, fs.FiscalYearID, fs.FiscalMonthID, fs.TimeClassID, fs.Amount, fs.AmountYTD, fs.AmountPriorYear, fs.AmountPriorYTD, cast(fs.IsSystemGenerated as int) as IsSystemGenerated + FROM [fw].[FactStatisticSampledMonthly] fs + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID + WHERE cfg.Revenue = 1 AND fs.IsDeleted = 0 AND cfg.IsDeleted = 0 + AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID) + + UNION ALL + + SELECT mo.RowID, mo.DepartmentID, mo.AccountID, mo.FiscalYearID, mo.FiscalMonthID, mo.TimeClassID, mo.Amount, mo.AmountYTD, mo.AmountPriorYear, mo.AmountPriorYTD, cast(0 as int) as IsSystemGenerated + FROM [fw].[FactStatisticDriverDepartmentSampledMonthly] mo + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON mo.DepartmentID = cfg.DepartmentID AND mo.AccountID = cfg.AccountID + WHERE cfg.Revenue = 1 AND mo.IsDeleted = 0 AND cfg.IsDeleted = 0) allData + + GROUP BY [RowID], [DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], [TimeClassID] +GO + + +--------------------------------------------- + +-- fw.viewPrimaryStatisticsRollupNonStaffingExpenseMonthly +CREATE VIEW [fw].[viewPrimaryStatisticsRollupNonStaffingExpenseMonthly] +AS + SELECT + cfg.RollupLevel, + cfg.RollupMemberID, + fs.AccountID, + fs.FiscalYearID, + fs.FiscalMonthID, + fs.TimeClassID, + sum(fs.Amount) as Amount, + sum(fs.AmountYTD) as AmountYTD, + sum(fs.AmountPriorYear) as AmountPriorYear, + sum(fs.AmountPriorYTD) as AmountPriorYTD, + min(cast(fs.IsSystemGenerated AS INT)) AS IsSystemGenerated + FROM [fw].[FactStatisticSampledMonthly] fs + INNER JOIN fw.DimDepartment dd ON fs.DepartmentID = dd.DepartmentID + INNER JOIN fw.PrimaryStatisticsRollupsConfiguration cfg ON ( + (cfg.RollupLevel = 'DepartmentRollup1' AND cfg.RollupMemberID = dd.DepartmentRollup1ID) + OR (cfg.RollupLevel = 'DepartmentRollup2' AND cfg.RollupMemberID = dd.DepartmentRollup2ID) + OR (cfg.RollupLevel = 'DepartmentRollup3' AND cfg.RollupMemberID = dd.DepartmentRollup3ID) + OR (cfg.RollupLevel = 'DepartmentRollup4' AND cfg.RollupMemberID = dd.DepartmentRollup4ID) + OR (cfg.RollupLevel = 'DepartmentRollup5' AND cfg.RollupMemberID = dd.DepartmentRollup5ID) + OR (cfg.RollupLevel = 'DepartmentRollup6' AND cfg.RollupMemberID = dd.DepartmentRollup6ID) + OR (cfg.RollupLevel = 'Entity' AND cfg.RollupMemberID = dd.EntityID) + OR (cfg.RollupLevel = 'System' AND cfg.RollupMemberID = dd.SystemID) + ) AND fs.AccountID = cfg.AccountID + WHERE cfg.NonStaffing = 1 + AND fs.IsDeleted = 0 + AND IsMRMetricTracking = 1 + GROUP BY + cfg.RollupLevel, + cfg.RollupMemberID, + fs.AccountID, + fs.FiscalYearID, + fs.FiscalMonthID, + fs.TimeClassID +GO + + +--------------------------------------------- + +-- fw.viewPrimaryStatisticsRollupRevenueMonthly +CREATE VIEW [fw].[viewPrimaryStatisticsRollupRevenueMonthly] +AS +SELECT cfg.RollupLevel, + cfg.RollupMemberID, + fs.AccountID, + fs.FiscalYearID, + fs.FiscalMonthID, + fs.TimeClassID, + sum(fs.Amount) as Amount, + sum(fs.AmountYTD) as AmountYTD, + sum(fs.AmountPriorYear) as AmountPriorYear, + sum(fs.AmountPriorYTD) as AmountPriorYTD, + min(cast(fs.IsSystemGenerated AS INT)) AS IsSystemGenerated +FROM [fw].[FactStatisticSampledMonthly] fs +INNER JOIN fw.DimDepartment dd ON fs.DepartmentID = dd.DepartmentID +INNER JOIN fw.PrimaryStatisticsRollupsConfiguration cfg ON ( + (cfg.RollupLevel = 'DepartmentRollup1' AND cfg.RollupMemberID = dd.DepartmentRollup1ID) + OR (cfg.RollupLevel = 'DepartmentRollup2' AND cfg.RollupMemberID = dd.DepartmentRollup2ID) + OR (cfg.RollupLevel = 'DepartmentRollup3' AND cfg.RollupMemberID = dd.DepartmentRollup3ID) + OR (cfg.RollupLevel = 'DepartmentRollup4' AND cfg.RollupMemberID = dd.DepartmentRollup4ID) + OR (cfg.RollupLevel = 'DepartmentRollup5' AND cfg.RollupMemberID = dd.DepartmentRollup5ID) + OR (cfg.RollupLevel = 'DepartmentRollup6' AND cfg.RollupMemberID = dd.DepartmentRollup6ID) + OR (cfg.RollupLevel = 'Entity' AND cfg.RollupMemberID = dd.EntityID) + OR (cfg.RollupLevel = 'System' AND cfg.RollupMemberID = dd.SystemID) + ) + AND fs.AccountID = cfg.AccountID +WHERE cfg.Revenue = 1 + AND fs.IsDeleted = 0 + AND IsMRMetricTracking = 1 +GROUP BY + cfg.RollupLevel, + cfg.RollupMemberID, + fs.AccountID, + fs.FiscalYearID, + fs.FiscalMonthID, + fs.TimeClassID +GO + + +--------------------------------------------- + +-- fw.viewPrimaryStatisticsRollupStaffingMonthly +CREATE VIEW [fw].[viewPrimaryStatisticsRollupStaffingMonthly] +AS + SELECT cfg.RollupLevel, + cfg.RollupMemberID, + fs.AccountID, + fs.FiscalYearID, + fs.FiscalMonthID, + fs.TimeClassID, + sum(fs.Amount) as Amount, + sum(fs.AmountYTD) as AmountYTD, + sum(fs.AmountPriorYear) as AmountPriorYear, + sum(fs.AmountPriorYTD) as AmountPriorYTD, + min(cast(fs.IsSystemGenerated AS INT)) AS IsSystemGenerated + FROM [fw].[FactStatisticSampledMonthly] fs + INNER JOIN fw.DimDepartment dd ON fs.DepartmentID = dd.DepartmentID + INNER JOIN fw.PrimaryStatisticsRollupsConfiguration cfg ON ( + (cfg.RollupLevel = 'DepartmentRollup1' AND cfg.RollupMemberID = dd.DepartmentRollup1ID) + OR (cfg.RollupLevel = 'DepartmentRollup2' AND cfg.RollupMemberID = dd.DepartmentRollup2ID) + OR (cfg.RollupLevel = 'DepartmentRollup3' AND cfg.RollupMemberID = dd.DepartmentRollup3ID) + OR (cfg.RollupLevel = 'DepartmentRollup4' AND cfg.RollupMemberID = dd.DepartmentRollup4ID) + OR (cfg.RollupLevel = 'DepartmentRollup5' AND cfg.RollupMemberID = dd.DepartmentRollup5ID) + OR (cfg.RollupLevel = 'DepartmentRollup6' AND cfg.RollupMemberID = dd.DepartmentRollup6ID) + OR (cfg.RollupLevel = 'Entity' AND cfg.RollupMemberID = dd.EntityID) + OR (cfg.RollupLevel = 'System' AND cfg.RollupMemberID = dd.SystemID) + ) + AND fs.AccountID = cfg.AccountID + WHERE cfg.Staffing = 1 + AND fs.IsDeleted = 0 + AND IsMRMetricTracking = 1 + GROUP BY + cfg.RollupLevel, + cfg.RollupMemberID, + fs.AccountID, + fs.FiscalYearID, + fs.FiscalMonthID, + fs.TimeClassID +GO + + +--------------------------------------------- + +-- fw.viewPrimaryStatisticsStaffingByPayPeriod +CREATE view [fw].[viewPrimaryStatisticsStaffingByPayPeriod] as + + SELECT [DepartmentID], [AccountID], [PayPeriodID], [TimeClassID], SUM([Units]) as Units, SUM([UnitsYTD]) as UnitsYTD, SUM([UnitsPriorYear]) as UnitsPriorYear, SUM([UnitsPriorYTD]) as UnitsPriorYTD, MAX([RowID]) as RowID, cast(MAX(cast([IsDeleted] as int)) as bit) as IsDeleted, cast(MIN([IsSystemGenerated]) as bit) as IsSystemGenerated + FROM + + (SELECT fs.DepartmentID, fs.AccountID, fs.PayPeriodID, fs.TimeClassID, fs.Units, fs.UnitsYTD, fs.UnitsPriorYear, fs.UnitsPriorYTD, fs.RowID, fs.IsDeleted, cast(fs.IsSystemGenerated as int) as IsSystemGenerated + FROM [fw].[FactStatisticSampledPayPeriod] fs + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID + WHERE cfg.Staffing = 1 AND fs.IsDeleted = 0 AND cfg.IsDeleted = 0 + AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID) + + UNION ALL + + SELECT pp.DepartmentID, pp.AccountID, pp.PayPeriodID, pp.TimeClassID, pp.Units, pp.UnitsYTD, pp.UnitsPriorYear, pp.UnitsPriorYTD, pp.RowID, pp.IsDeleted, cast(0 as int) as IsSystemGenerated + FROM [fw].[FactStatisticDriverDepartmentSampledPayPeriod] pp + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON pp.DepartmentID = cfg.DepartmentID AND pp.AccountID = cfg.AccountID + WHERE cfg.Staffing = 1 AND pp.IsDeleted = 0 AND cfg.IsDeleted = 0) allData + + GROUP BY [DepartmentID], [AccountID], [PayPeriodID], [TimeClassID] +GO + + +--------------------------------------------- + +-- fw.viewPrimaryStatisticsStaffingDaily +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-04-22 gforeman initial implementation +** 2 2022-07-28 BS JAZZ-39738 Daily flexing - Payroll Hours and Dollars +** 3 2024-02-16 KF JAZZ-67769 Add BigRowID to fw.FactStatisticSampledDaily and fw.viewPrimaryStatisticsStaffingDaily +*************************************************************/ +CREATE view [fw].[viewPrimaryStatisticsStaffingDaily] +as + SELECT [DepartmentID], [AccountID], [PayPeriodID], [DateID], [TimeClassID], SUM([Units]) as Units, MAX([RowID]) as RowID, cast(MAX(cast([IsDeleted] as int)) as bit) as IsDeleted, CAST(MAX(RowID) AS BIGINT) as BigRowID + FROM + + (SELECT fs.DepartmentID, fs.AccountID, fs.PayPeriodID, fs.DateID, fs.TimeClassID, fs.Units, fs.RowID, fs.IsDeleted + FROM [fw].[FactStatisticSampledDaily] fs + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID + WHERE cfg.Staffing = 1 AND fs.IsDeleted = 0 AND cfg.IsDeleted = 0 + AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID) + + UNION ALL + + SELECT pp.DepartmentID, pp.AccountID, pp.PayPeriodID, pp.DateID, pp.TimeClassID, pp.Units, pp.RowID, pp.IsDeleted + FROM [fw].[FactStatisticDriverDepartmentSampledDaily] pp + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON pp.DepartmentID = cfg.DepartmentID AND pp.AccountID = cfg.AccountID + WHERE cfg.Staffing = 1 AND pp.IsDeleted = 0 AND cfg.IsDeleted = 0) allData + + GROUP BY [DepartmentID], [AccountID], [PayPeriodID], [DateID], [TimeClassID] +GO + + +--------------------------------------------- + +-- fw.viewPrimaryStatisticsStaffingMonthly +-- primary statistics (by month) staffing driver accounts +CREATE view [fw].[viewPrimaryStatisticsStaffingMonthly] as + + SELECT [RowID], [DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], [TimeClassID], SUM([Amount]) as Amount, SUM([AmountYTD]) as AmountYTD, SUM([AmountPriorYear]) as AmountPriorYear, SUM([AmountPriorYTD]) as AmountPriorYTD, cast(0 as bit) as IsDeleted, cast(MIN([IsSystemGenerated]) as bit) as IsSystemGenerated + FROM + + (SELECT fs.RowID, fs.DepartmentID, fs.AccountID, fs.FiscalYearID, fs.FiscalMonthID, fs.TimeClassID, fs.Amount, fs.AmountYTD, fs.AmountPriorYear, fs.AmountPriorYTD, cast(fs.IsSystemGenerated as int) as IsSystemGenerated + FROM [fw].[FactStatisticSampledMonthly] fs + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON fs.DepartmentID = cfg.DepartmentID AND fs.AccountID = cfg.AccountID + WHERE cfg.Staffing = 1 AND fs.IsDeleted = 0 AND cfg.IsDeleted = 0 + AND not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.FactDepartmentPrimaryStatisticConfigurationID = cfg.RowID) + + UNION ALL + + SELECT mo.RowID, mo.DepartmentID, mo.AccountID, mo.FiscalYearID, mo.FiscalMonthID, mo.TimeClassID, mo.Amount, mo.AmountYTD, mo.AmountPriorYear, mo.AmountPriorYTD, cast(0 as int) as IsSystemGenerated + FROM [fw].[FactStatisticDriverDepartmentSampledMonthly] mo + INNER JOIN [client].[FactDepartmentPrimaryStatisticConfiguration] cfg ON mo.DepartmentID = cfg.DepartmentID AND mo.AccountID = cfg.AccountID + WHERE cfg.Staffing = 1 AND mo.IsDeleted = 0 AND cfg.IsDeleted = 0) allData + + GROUP BY [RowID], [DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], [TimeClassID] +GO + + +--------------------------------------------- + +-- fw.viewReportCurrentUsers +CREATE VIEW [fw].[viewReportCurrentUsers] AS + SELECT DISTINCT up.NameFirst, up.NameLast, up.PhoneNumber, CASE WHEN MIN(DATEDIFF(MI, LastActionStampUtc, GETUTCDATE())) < 0 THEN 0 ELSE MIN(DATEDIFF(MI, LastActionStampUtc, GETUTCDATE())) END AS InactiveMinutes + FROM CurrentUser cu INNER JOIN [dbo].[UserProfile] up + ON cu.UserGUID = up.UserGUID + WHERE tokentype = 0 + GROUP BY up.NameFirst, up.NameLast, up.PhoneNumber + HAVING up.NameFirst IS NOT NULL +GO + + +--------------------------------------------- + +-- fw.viewReportDimensionExceptions +CREATE VIEW [fw].[viewReportDimensionExceptions] +AS +select AccountCode As DataMember, 'Account' As Identifier, 'fw.DimAccount' As Source, 'Blank Description or Blank GL Rollup' As Explanation, trans.Files As FilePath, trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from fw.DimAccount acct inner join [dbo].[viewIntTransaction] trans on acct.TransactionID = trans.TransactionID +where Description='' or GLRollup='' +union +select AccountCode As DataMember, 'Account' As Identifier, 'fw.DimAccount' As Source, 'Blank Account Code' As Explanation, trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from fw.DimAccount acct inner join [dbo].[viewIntTransaction] trans on acct.TransactionID = trans.TransactionID +where AccountCode='' +union +select Description As DataMember, 'Account' As Identifier, 'fw.DimAccount' As Source, 'Modified Zero member Description' As Explanation, trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from fw.DimAccount acct inner join [dbo].[viewIntTransaction] trans on acct.TransactionID = trans.TransactionID +where AccountID=0 and Description<>'Not Specified' +union +select Code As DataMember, 'Entity' As Identifier, 'fw.DimEntity' As Source, 'Blank Description' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from fw.DimEntity Ent inner join [dbo].[viewIntTransaction] trans on Ent.TransactionID = trans.TransactionID +where Description='' +union +select Code As DataMember, 'Entity' As Identifier, 'fw.DimEntity' As Source, 'Blank Entity Code' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from fw.DimEntity Ent inner join [dbo].[viewIntTransaction] trans on Ent.TransactionID = trans.TransactionID +where Code='' +union +select Description As DataMember, 'Entity' As Identifier, 'fw.DimEntity' As Source, 'Modified Zero member Description' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from fw.DimEntity Ent inner join [dbo].[viewIntTransaction] trans on Ent.TransactionID = trans.TransactionID +where Ent.EntityID = 0 and ent.Description<>'Not Specified' +union +select DepartmentCode As DataMember, 'Department' As Identifier, 'fw.DimDepartment' As Source, 'Blank Description' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from fw.DimDepartment dept inner join [dbo].[viewIntTransaction] trans on dept.TransactionID = trans.TransactionID +where Dept.Description='' +union +select DepartmentCode As DataMember, 'Department' As Identifier, 'fw.DimDepartment' As Source, 'Blank Department Code' As Explanation , trans.Files As FilePath ,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from fw.DimDepartment dept inner join [dbo].[viewIntTransaction] trans on dept.TransactionID = trans.TransactionID +where Dept.Departmentcode='' +union +select DepartmentCode As DataMember, 'Department' As Identifier, 'fw.DimDepartment' As Source, 'Entity Not Assigned' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from fw.DimDepartment dept inner join [dbo].[viewIntTransaction] trans on dept.TransactionID = trans.TransactionID +where Dept.EntityID=0 and Dept.DepartmentID<>0 +union +select Description As DataMember, 'Department' As Identifier, 'fw.DimDepartment' As Source, 'Modified Zero member Description' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from fw.DimDepartment dept inner join [dbo].[viewIntTransaction] trans on dept.TransactionID = trans.TransactionID +where DepartmentID=0 and (Description<>'Not Specified' or EntityID<>0) +union +select JobCode As DataMember, 'Job Code' As Identifier, 'fw.DimJobCode' As Source, 'Blank Description' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from fw.DimJobCode JC inner join [dbo].[viewIntTransaction] trans on JC.TransactionID = trans.TransactionID +where Description='' +union +select JobCode As DataMember, 'Job Code' As Identifier, 'fw.DimJobCode' As Source, 'Blank Job Code' As Explanation , trans.Files As FilePath ,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from fw.DimJobCode JC inner join [dbo].[viewIntTransaction] trans on JC.TransactionID = trans.TransactionID +where JobCode='' +union +select Description As DataMember, 'Job Code' As Identifier, 'fw.DimJobCode' As Source, 'Modified Zero member Description' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from fw.DimJobCode JC inner join [dbo].[viewIntTransaction] trans on JC.TransactionID = trans.TransactionID +where JobCodeID=0 and Description<>'Not Specified' +union +select PayCode As DataMember, 'Pay Code' As Identifier, 'fw.DimPayCode' As Source, 'Blank Description' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from fw.DimPayCode PC inner join [dbo].[viewIntTransaction] trans on PC.TransactionID = trans.TransactionID +where Description='' +union +select PayCode As DataMember, 'Pay Code' As Identifier, 'fw.DimPayCode' As Source, 'Blank Pay Code' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from fw.DimPayCode PC inner join [dbo].[viewIntTransaction] trans on PC.TransactionID = trans.TransactionID +where PayCode='' +union +select Description As DataMember, 'Pay Code' As Identifier, 'fw.DimPayCode' As Source, 'Modified Zero member Description' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from fw.DimPayCode PC inner join [dbo].[viewIntTransaction] trans on PC.TransactionID = trans.TransactionID +where PayCodeID=0 and Description<>'Not Specified' +union +select Number As DataMember, 'Employee' As Identifier, 'fw.DimEmployee' As Source, 'Blank First Name or Blank Last Name' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from fw.DimEmployee emp inner join [dbo].[viewIntTransaction] trans on emp.TransactionID = trans.TransactionID +where NameFirst='' or NameLast='' +union +select Number As DataMember, 'Employee' As Identifier, 'fw.DimEmployee' As Source, 'Blank Employee Number' As Explanation, trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from fw.DimEmployee emp inner join [dbo].[viewIntTransaction] trans on emp.TransactionID = trans.TransactionID +where Number='' +union +select Number As DataMember, 'Employee' As Identifier, 'fw.DimEmployee' As Source, 'Job Code not set for Employee' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from fw.DimEmployee emp inner join [dbo].[viewIntTransaction] trans on emp.TransactionID = trans.TransactionID +where JobCodeID=0 and EmployeeID<>0 +union +select Name As DataMember, 'Employee' As Identifier, 'fw.DimEmployee' As Source, 'Modified Zero member Description' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from fw.DimEmployee emp inner join [dbo].[viewIntTransaction] trans on emp.TransactionID = trans.TransactionID +where EmployeeID=0 and Name<>'Not Specified [0] (UNKNWN)' +union +select Code As DataMember, 'Fund' As Identifier, 'fw.DimFund' As Source, 'Blank Description' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from [fw].[DimFund] DF inner join [dbo].[viewIntTransaction] trans on DF.TransactionID = trans.TransactionID +where Description='' +union +select Code As DataMember, 'Fund' As Identifier, 'fw.DimFund' As Source, 'Blank Fund Code' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from [fw].[DimFund] DF inner join [dbo].[viewIntTransaction] trans on DF.TransactionID = trans.TransactionID +where Code='' +union +select Description As DataMember, 'Fund' As Identifier, 'fw.DimFund' As Source, 'Modified Zero member Description' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from [fw].[DimFund] DF inner join [dbo].[viewIntTransaction] trans on DF.TransactionID = trans.TransactionID +where FundID=0 and (Description<>'Not Specified') +union +select Code As DataMember, 'Project' As Identifier, 'fw.DimProject' As Source, 'Blank Description' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from [fw].[DimProject] DP inner join [dbo].[viewIntTransaction] trans on DP.TransactionID = trans.TransactionID +where Description='' +union +select Code As DataMember, 'Project' As Identifier, 'fw.DimProject' As Source, 'Blank Project Code' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from [fw].[DimProject] DP inner join [dbo].[viewIntTransaction] trans on DP.TransactionID = trans.TransactionID +where Code='' +union +select Description As DataMember, 'Project' As Identifier, 'fw.DimProject' As Source, 'Modified Zero member Description' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from [fw].[DimProject] DP inner join [dbo].[viewIntTransaction] trans on DP.TransactionID = trans.TransactionID +where ProjectID=0 and (Description<>'Not Specified') +union +select Code As DataMember, 'Program' As Identifier, 'fw.DimProgram' As Source, 'Blank Description' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from [fw].DimProgram Prog inner join [dbo].[viewIntTransaction] trans on Prog.TransactionID = trans.TransactionID +where Description='' +union +select Code As DataMember, 'Program' As Identifier, 'fw.DimProgram' As Source, 'Blank Program Code' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from [fw].DimProgram Prog inner join [dbo].[viewIntTransaction] trans on Prog.TransactionID = trans.TransactionID +where Code='' +union +select Description As DataMember, 'Program' As Identifier, 'fw.DimProgram' As Source, 'Modified Zero member Description' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from [fw].DimProgram Prog inner join [dbo].[viewIntTransaction] trans on Prog.TransactionID = trans.TransactionID +where ProgramID=0 and (Description<>'Not Specified') +union +select Code As DataMember, 'Home Department' As Identifier, 'fw.DimHomeDepartment' As Source, 'Blank Description' As Explanation , trans.Files As FilePath ,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from [fw].[DimHomeDepartment] HD inner join [dbo].[viewIntTransaction] trans on HD.TransactionID = trans.TransactionID +where Description='' +union +select Code As DataMember, 'Home Department' As Identifier, 'fw.DimHomeDepartment' As Source, 'Blank Program Code' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from [fw].[DimHomeDepartment] HD inner join [dbo].[viewIntTransaction] trans on HD.TransactionID = trans.TransactionID +where Code='' +union +select Description As DataMember, 'Home Department' As Identifier, 'fw.DimHomeDepartment' As Source, 'Modified Zero member Description' As Explanation , trans.Files As FilePath,trans.TransactionID As TransactionID, trans.StartTimeUtc as ImportDate, trans.username As UserName, trans.ConfigName as IntegrationConfig +from [fw].[DimHomeDepartment] HD inner join [dbo].[viewIntTransaction] trans on HD.TransactionID = trans.TransactionID +where HomeDepartmentID=0 and (Description<>'Not Specified') +GO + + +--------------------------------------------- + +-- fw.viewReportDirectoryActionHistory +CREATE VIEW [fw].[viewReportDirectoryActionHistory] +AS + +select + case when SubAction like 'Initial Load -%' + then 'Initial Load' + else + replace(SubAction, 'Grid Action - ', '') + End as SubAction, + Username, + YEAR(datetimestamp) as [Year], + MONTH(datetimestamp) as [Month], + DateTimeStamp, + Duration, + 1 as [Count] +from ActionLog +where [Action] = 'Directory20' and SubAction not in ('RefreshTabNames', 'Grid Action - init') +GO + + +--------------------------------------------- + +-- fw.viewReportExceptionSummary +create view [fw].[viewReportExceptionSummary] +as + select + ReportName, + ExceptionCount + from + fw.FactReportException +GO + + +--------------------------------------------- + +-- fw.viewReportFactGLConsolidated +CREATE view [fw].[viewReportFactGLConsolidated] as + + + select + S.DepartmentID + ,S.AccountID + ,S.TimeClassID + ,S.FiscalYearID + ,S.FiscalMonthID + ,(s.Units) as Units + ,(s.UnitsYTD) as UnitsYTD + ,(s.UnitsPriorYear) as UnitsPriorYear + ,(S.UnitsPriorYTD) as UnitsPriorYTD + ,(s.Dollars) as Dollars + ,(S.DollarsYTD) as DollarsYTD + ,(S.DollarsPriorYear) as DollarsPriorYear + ,(S.DollarsPriorYTD) as DollarsPriorYTD + from + fw.FactGLSampled S + + where + s.IsDeleted = 0 +GO + + +--------------------------------------------- + +-- fw.viewReportFactPayrollMonthlyConsolidated +CREATE view [fw].[viewReportFactPayrollMonthlyConsolidated] as + + + select + DepartmentID, + JobCodeID, + PayCodeID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + (Hours) as Hours, + (HoursYTD) as HoursYTD, + (HoursPriorYear) as HoursPriorYear, + (HoursPriorYTD) as HoursPriorYTD, + (Dollars) as Dollars, + (DollarsYTD) as DollarsYTD, + (DollarsPriorYear) as DollarsPriorYear, + (DollarsPriorYTD) as DollarsPriorYTD + from + fw.FactPayrollSampledMonthly S + where + s.IsDeleted = 0 +GO + + +--------------------------------------------- + +-- fw.viewReportFactStatMonthlyConsolidated +CREATE view [fw].[viewReportFactStatMonthlyConsolidated] as + + + select + DepartmentID, + AccountID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + Amount, + AmountYTD, + AmountPriorYear, + AmountPriorYTD + from + fw.FactStatisticSampledMonthly S + where + s.IsDeleted = 0 + and (Amount <> 0 or AmountYTD <> 0 or AmountPriorYear <> 0 or AmountPriorYTD <> 0) +GO + + +--------------------------------------------- + +-- fw.viewReportFactStatPayPeriodConsolidated +CREATE view [fw].[viewReportFactStatPayPeriodConsolidated] as + + + select + DepartmentID, + AccountID, + TimeClassID, + PayPeriodID, + Units + from + fw.FactStatisticSampledPayPeriod S + where + s.IsDeleted = 0 + and Units <> 0 +GO + + +--------------------------------------------- + +-- fw.viewReportGeneralConsolidatedFinancialReporting +create view [fw].[viewReportGeneralConsolidatedFinancialReporting] as + +/************************************************************ +** Author: FW Dev +** Create Date: akowalski +** Description: Generates the list of Consolidated financial reporting members for expanding reports +** Last Modified: 2013-03-26 +** GM Release: Lightningbug +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + +select + ConsolidatedFinancialReportingID +from + [fw].[DimConsolidatedFinancialReporting] +GO + + +--------------------------------------------- + +-- fw.viewReportGroupAssignment +create view fw.viewReportGroupAssignment +as +select + UP.NameLast as [LastName], + UP.NameFirst as [FirstName], + UP.UserName as [UserName], + UP.EmailAddress as [EmailAddress], + G.UserGroupName +from UserProfile UP +inner join viewS3GroupAssignment G on G.UserGUID = UP.UserGUID +GO + + +--------------------------------------------- + +-- fw.viewReportLockedPlans +CREATE VIEW fw.viewReportLockedPlans +AS +SELECT + dbo.GetPlanName(L.ItemGUID) AS PlanName, + PT.Name As PlanType, + TEM.Name AS ModelTemplate, + CAST(L.DateLocked AS varchar(30)) AS LockDate, + CAST(L.DateLastActive AS varchar(30)) AS LastActive, + COALESCE (UP.NameFirst + ' ' + UP.NameLast, '') AS UserName +FROM + dbo.Lock AS L LEFT OUTER JOIN + dbo.UserProfile AS UP ON L.UserGUID = UP.UserGUID LEFT OUTER JOIN + dbo.XPlan AS X ON X.PlanGUID = L.ItemGUID LEFT OUTER JOIN + [dbo].[PlanType] as PT on PT.PlanTypeGUID=X.PlanTypeGUID LEFT OUTER JOIN + dbo.EMFModelTemplate AS TEM ON X.ModelTemplateGUID = TEM.ModelTemplateGUID +WHERE (L.LockGroup = 'PlanLock') and X.IsDeletedPlan=0 +GO + + +--------------------------------------------- + +-- fw.viewReportPayPeriod +CREATE VIEW [fw].[viewReportPayPeriod] AS + SELECT + m.CalendarDaysSecond, + m.CalendarDaysStart, + m.DaysInPeriodWeightSecond, + m.DaysInPeriodWeightStart, + m.FiscalMonthIDSecond, + m.FiscalMonthIDStart, + m.FiscalYearIDSecond, + m.FiscalYearIDStart, + m.PayPeriodCode, + m.Name as PayPeriod, + m.PayPeriodID, + m.PayPeriodID as ReportingPayPeriodID, + m.PeriodDays, + m.PeriodDaysSecond, + m.PeriodDaysStart, + m.PeriodEndCalendarDate, + m.PeriodEndCalendarDate as DateEnd, + m.PeriodNumber, + m.PeriodStartCalendarDate, + m.PeriodWeightSecond, + m.PeriodWeightStart + FROM + fw.DimPayPeriod m +GO + + +--------------------------------------------- + +-- fw.viewReportReportRunHistory +CREATE VIEW [fw].[viewReportReportRunHistory] +AS + +select + L.Username as [User Name], + case L.Action + when 'ZEROVIEWER' then 'Excel' + when 'Excel Reporter' then 'Excel' + when 'SQL Report' then 'SQL' + else 'Not Specified' + end as [Report Type], + replace(coalesce(R.Name, L.SubAction) , 'BATCH_', '')as [Report Name], + L.DatetimeStamp as [Launch Time], + L.Duration/1000 as [Duration in Seconds] +from + ActionLog L + inner join REReport R on RIGHT(L.SubAction, 36) = cast(R.ReportGUID as nvarchar(36)) or replace(L.SubAction, 'BATCH_', '')=R.Name +where + L.Action in ('ZEROVIEWER', 'Excel Reporter', 'SQL Report') + and L.SubAction not like 'DrillDown%' + +union all + +select + UserName as [User Name], + 'Excel' as [Report Type], + ReportName as [Report Name], + LaunchTime as [Launch Time], + datediff(ss, LaunchTime, FinishTime) as [Duration in Seconds] +from ( + select + modifierusername as UserName, + replace(usercomments, 'BATCH_', '') as ReportName, + max(case when [Description]='Report Created' then datetimestamp else null end) as LaunchTime, + max(case when [Description]='Report Deleted' then datetimestamp else null end) as FinishTime + from historyitem + where category='Report Action' and UserComments like 'BATCH_%' + group by modifierusername, usercomments + ) P +GO + + +--------------------------------------------- + +-- fw.viewReportSecurityDetail +--========================================================================================== + + +CREATE view [fw].[viewReportSecurityDetail] as + +SELECT + E.NAME AS ModelTemplate, + P.NAME AS Plans, + P.planguid, + U.NameFull as UserName, + ROLENAME AS UserRole, + DET.RoleID as UserRoleID, + CASE + WHEN IdentityName = U.NAMELAST+', '+U.NAMEFIRST THEN 'Direct' + ELSE IDENTITYNAME END AS GROUPNAME +FROM VIEWS3ROLEASSIGNMENTDETAIL DET +INNER JOIN VIEWPLANS P ON DET.LOOTID = P.CachedLootID +INNER JOIN EMFMODELTEMPLATE E ON P.MODELTEMPLATEGUID = E.MODELTEMPLATEGUID +INNER JOIN UserProfile U on U.UserGUID = DET.UserGUID +GO + + +--------------------------------------------- + +-- fw.viewReportSystemSectionSecurity +CREATE view [fw].[viewReportSystemSectionSecurity] as + + +SELECT + SS.NAME AS SYSTEMSECTION, + SS.FULLPATH, + DET.USERNAME, + ROLENAME AS USERROLE, + CASE + WHEN IdentityName = p.NAMELAST+', '+p.NAMEFIRST THEN '' + ELSE IDENTITYNAME END AS GROUPNAME +FROM VIEWS3ROLEASSIGNMENTDETAIL DET (readuncommitted) +INNER JOIN SystemSection SS(readuncommitted) ON DET.LOOTID = SS.LOOTID +inner join [dbo].[UserProfile] p on DET.UserGUID=p.UserGUID +GO + + +--------------------------------------------- + +-- fw.viewReportSystemSectionSecuritybySection +create view [fw].[viewReportSystemSectionSecuritybySection] as + +select + ss.Area, + ss.Section, + ss.Name as [System Section], + ur.NAME as Role, + case when G.NAME is null then u.NameFull else g.NAME end as [Group or User] +from [fw].[viewDimSystemSection] ss +inner join [dbo].[S3RoleAssignment] ra on ss.LootID=ra.LootGroupID +inner join [dbo].[UserRole] ur on ur.RoleID=ra.RoleID +left join [dbo].[UserGroup] G on G.USERGROUPGUID=ra.IdentityGUID +left join [dbo].[UserProfile] u on u.USERGUID=ra.IdentityGUID +GO + + +--------------------------------------------- + +-- fw.viewReportSystemUsers +CREATE VIEW [fw].[viewReportSystemUsers] AS + +SELECT UP.*, + ISNULL(CAST(CASE WHEN IL.GroupingGUID IS NULL THEN 0 ELSE 1 END AS bit),0) AS IsSysAdmin +from userprofile UP +left join [dbo].[S3IdentityLink] IL on UP.UserGUID = IL.MemberGUID and IL.GroupingGUID = (select UserGroupGUID from [dbo].[UserGroup] where GlobalID = 'GEN - User Administrator') +GO + + +--------------------------------------------- + +-- fw.viewReportUserLastLogin +create view [fw].[viewReportUserLastLogin] +as + select Name, LastLogin, NumLogins + from viewuserloginhistory + where lastlogin > '2010-01-01' +GO + + +--------------------------------------------- + +-- fw.viewReportUserLoginHistory +create view [fw].[viewReportUserLoginHistory] as + + +select +Name, +LastLogin, +cast(DATEDIFF(day,LastLogin,CURRENT_TIMESTAMP) as float) as DaysSinceLogin +from dbo.viewUserLoginHistory +where Name NOT LIKE '%zStrata%' +GO + + +--------------------------------------------- + +-- fw.viewReportWorkflowSignoffs +CREATE view [fw].[viewReportWorkflowSignoffs] +as + select + RV.EntityGUID as PlanGUID, + E.EntityName as Plans, + WFM.Name as WorkflowMapName, + WFS.Name as WorkflowStepName, + UP.NameFull as ReviewerName, + RVT.Name as ReviewValue, + RV.Comments, + cast(WFP.DisplayOrder as nvarchar(8)) + '\' + cast(WFS.DisplayOrder as nvarchar(8)) as DisplayOrder, + E.CachedLootID as LootID + from + WFReviewValue RV + inner join dbo.viewWFEntity E on E.EntityGUID = RV.EntityGUID + inner join UserProfile UP on UP.UserGUID = RV.IdentityGUID + inner join WFReviewValueType RVT on RVT.ReviewValueTypeGUID = RV.ReviewValueTypeGUID + inner join WFWorkflowStep WFS on WFS.WorkflowStepGUID = RV.WorkflowStepGUID + inner join WFProcessStepLink WFL on WFL.WorkflowStepGUID = WFS.WorkflowStepGUID + inner join WFProcess WFP on WFP.ProcessGUID = WFL.ProcessGUID + inner join WFWorkflowMap WFM on WFM.WorkflowMapGUID = WFS.WorkflowMapGUID +GO + + +--------------------------------------------- + +-- fw.viewSectionSecurityImport +CREATE VIEW [fw].[viewSectionSecurityImport] +as +select + case when SSI.GroupName = 'None' then 'Strata Administrator' else SSI.GroupName end as GroupName, + 'Basic' as SectionType, + 'Global' as Parent, + SS.Name, + SS.SystemSectionGUID +from + fw.SectionSecurityImport SSI + inner join SystemSection SS on SS.SystemSectionGUID = SSI.BasicGUID +union all +select + case when SSI.GroupName = 'None' then 'Strata Administrator' else SSI.GroupName end as GroupName, + 'Advanced' as SectionType, + SSP.Name as Parent, + SS.Name, + SS.SystemSectionGUID +from + fw.SectionSecurityImport SSI + inner join SystemSection SS on SS.SystemSectionGUID = SSI.AdvancedGUID + left join SystemSection SSP on SSP.SystemSectionGUID = SS.ParentGUID +GO + + +--------------------------------------------- + +-- fw.viewStatisticPrimaryConfiguration +/************************************************************ +** Author: jgerber +** Create Date: 2013-11-06 +** Description: View for Primary Statistic Driver (Defaults using the Primary Statistic Config) +** Last Modified: 2013-11-06 +** GM Release: 2013-11-18 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 01.08.16 MJS D-03823 Added filter: IsDeleted=0 +** 2 2020-01-30 KF D-09156 Accounts being excluded from metrics when using non staffing expenses +*************************************************************/ +CREATE VIEW [fw].[viewStatisticPrimaryConfiguration] + +as +select + DepartmentID, + AccountID +from + [client].[FactDepartmentPrimaryStatisticConfiguration] +where + (Revenue=1 OR Staffing=1 OR NonStaffingExpense=1) + and IsDeleted=0 +GO + + +--------------------------------------------- + +-- fw.viewStatisticSecondaryConfiguration +/************************************************************ +** Author: jgerber +** Create Date: 2013-11-06 +** Description: View for Secondary Statistic Driver (Defaults using the Secondary Statistic Config) +** Last Modified: 2013-11-06 +** GM Release: 2013-11-18 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 01.08.16 MJS D-03823 Added filter: IsDeleted=0 +** 2 2020-01-30 KF D-09156 Accounts being excluded from metrics when using non staffing expenses +*************************************************************/ +CREATE VIEW [fw].[viewStatisticSecondaryConfiguration] + +as +--THIS IS EDITABLE +select + DepartmentID, + AccountID +from + [client].[FactDepartmentPrimaryStatisticConfiguration] +where + (Revenue=1 OR Staffing=1 OR NonStaffingExpense=1) + and IsDeleted=0 +GO + + +--------------------------------------------- + +--------------------------------------------- +-- PROCEDURES +--------------------------------------------- + +-- fw.PrepareStatistics +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-06-04 IP TK-58587 re-applying changes (2018-05-16 D-07187 Budget adjustment effecting historical budget fiscal years) +** 2 2024-12-23 HV JAZZ-81810 [Spike] - Analyze and cover with integration tests for JAZZ-81233: MR - Budget Adj is getting applied to all prior years + Apply fix proposed by Scott Evens +*************************************************************/ +CREATE PROCEDURE [fw].[PrepareStatistics] (@FiscalYearID int =0, @StatisticType tinyint) +as + IF OBJECT_ID('tempdb..#StatisticTempTable') IS NOT NULL DROP TABLE #StatisticTempTable + declare @iteration int = 1 + create table #StatisticTempTable ( + DepartmentID int, + AccountID int, + FiscalYearID smallint, + FiscalMonthID tinyint, + TimeClassID tinyint, + Amount numeric(25,4), + ApplyDate datetime, + Src varchar(max), + UNIQUE NONCLUSTERED (DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID) +) + INSERT INTO #StatisticTempTable (DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,ApplyDate,Src) + SELECT + stat.DepartmentID, + stat.AccountID, + stat.FiscalYearID, + stat.FiscalMonthID, + stat.TimeClassID, + sum(STAT.Value) as Amount, + cast('1900-01-01' as datetime) as ApplyDate, + cast('int_1' as varchar(max))+'V' as src + from + int.FactStatistic stat + inner join fw.DimDepartment D on D.Departmentid = STAT.Departmentid + where + stat.IsDeleted = 0 + and stat.Value != 0 + and (stat.FiscalYearID = @FiscalYearID or @FiscalYearID = 0) + Group by stat.DepartmentID, + stat.AccountID, + stat.FiscalYearID, + stat.FiscalMonthID, + stat.TimeClassID + +--select count(*) from #StatisticTempTable + +DECLARE @BudgetReallocationGUID uniqueidentifier,@date datetime,@BudgetReallocationType varchar(50) + +PRINT '-------- Vendor Products Report --------'; + +DECLARE BRA_cursor CURSOR FOR +SELECT distinct BudgetReallocationGUID,date,BudgetReallocationType from fw.BudgetReallocationWithDefinedType +WHERE (FiscalYearID = @FiscalYearID or @FiscalYearID = 0) +ORDER BY date; + +OPEN BRA_cursor + +FETCH NEXT FROM BRA_cursor +INTO @BudgetReallocationGUID,@date,@BudgetReallocationType + +WHILE @@FETCH_STATUS = 0 +BEGIN + +--select @iteration,@BudgetReallocationGUID,@date,@BudgetReallocationType,* from #StatisticTempTable where DepartmentID = 359 and AccountID = 791 and FiscalYearID = 2015 and FiscalMonthID = 9 and TimeClassID = 2 + + IF @BudgetReallocationType = 'ReallocateSingle' + BEGIN -- Insert rows with "correcting" values + UPDATE STT + SET Amount = Amount + Change, + stt.ApplyDate = b.Date, + src = SRC + '[Added_'+cast(Change as varchar(50))+'_from_'+cast(SourceDepartmentID as varchar(10))+']' + FROM #StatisticTempTable STT + INNER JOIN [mr].[BudgetReallocation] b ON b.TargetDepartmentID = stt.DepartmentID and b.TargetAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID + WHERE Change <> 0 + and b.BudgetReallocationGUID = @BudgetReallocationGUID + and UnitTypeID = 145 + and TimeClassID = 2 + + UPDATE STT + SET Amount = Amount - Change, + stt.ApplyDate = b.Date, + src = SRC + '[Removed_'+cast(Change as varchar(50))+'_to_'+cast(TargetDepartmentID as varchar(10))+']' + FROM #StatisticTempTable STT + INNER JOIN [mr].[BudgetReallocation] b ON b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID + WHERE Change <> 0 + and b.BudgetReallocationGUID = @BudgetReallocationGUID + and UnitTypeID = 145 + and TimeClassID = 2 + + INSERT INTO #StatisticTempTable (DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,ApplyDate,Src) + SELECT + b.SourceDepartmentID as DepartmentID, + b.SourceAccountID as AccountID, + b.FiscalYearID, + ba.FiscalMonthID, + 2 as TimeclassID, + SUM(Change * -1) as Value, + max(b.Date) as ApplyDate, + 'ra_1_m' as src + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + LEFT JOIN (select DepartmentID,AccountID,FiscalYearID,FiscalMonthID,max(ApplyDate) as ApplyDate from #StatisticTempTable where TimeClassID = 2 group by DepartmentID,AccountID,FiscalYearID,FiscalMonthID) STT ON b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID and stt.FiscalMonthID = ba.FiscalMonthID + where Change <> 0 + and b.BudgetReallocationGUID = @BudgetReallocationGUID + and stt.DepartmentID is null + and UnitTypeID = 145 + GROUP BY b.SourceDepartmentID, + b.SourceAccountID, + b.FiscalYearID, + ba.FiscalMonthID + UNION All + SELECT + b.TargetDepartmentID as DepartmentID, + b.TargetAccountID as AccountID, + b.FiscalYearID, + ba.FiscalMonthID, + 2 as TimeclassID, + sum(Change) as Value, + max(b.Date) as ApplyDate, + 'ra_1_p' as src + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + LEFT JOIN (select DepartmentID,AccountID,FiscalYearID,FiscalMonthID,max(ApplyDate) as ApplyDate from #StatisticTempTable where TimeClassID = 2 group by DepartmentID,AccountID,FiscalYearID,FiscalMonthID) STT ON b.TargetDepartmentID = stt.DepartmentID and b.TargetAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID and stt.FiscalMonthID = ba.FiscalMonthID + where Change <> 0 + and b.BudgetReallocationGUID = @BudgetReallocationGUID + and stt.DepartmentID is null + and UnitTypeID = 145 + group by + b.TargetDepartmentID, + b.TargetAccountID, + b.FiscalYearID, + ba.FiscalMonthID + ------------------ + + + + END + ELSE +IF @BudgetReallocationType = 'ReallocateMulti' + BEGIN + Update stt + set + stt.Amount = stt.Amount + stt_src.Amount, + stt.ApplyDate = b.Date, + stt.Src = stt.Src + '[RealMulti_'+cast(stt_src.Amount as varchar(50))+'_from_'+cast(stt_src.DepartmentID as varchar(10))+']' + FROM #StatisticTempTable STT + INNER JOIN [mr].[BudgetReallocation] b on b.TargetDepartmentID = stt.DepartmentID and b.TargetAccountID = stt.AccountID and b.Date >= stt.ApplyDate and b.FiscalYearID = stt.FiscalYearID + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID + INNER JOIN #StatisticTempTable STT_SRC on STT_SRC.DepartmentID = b.SourceDepartmentID and STT_SRC.AccountID = b.SourceAccountID and STT_SRC.FiscalYearID = b.FiscalYearID and STT_SRC.FiscalMonthID = ba.FiscalMonthID and stt.TimeClassID = stt_src.TimeClassID + where + b.BudgetReallocationGUID = @BudgetReallocationGUID + and ba.UnitTypeID = 145 + and Change <> 0 + and stt.TimeClassID = 2 + --select 'X',* from #StatisticTempTable where DepartmentId = 279 and AccountID = 791 and FiscalYearID = 2015 and FiscalMonthID = 5 and TimeClassID = 2 + INSERT INTO #StatisticTempTable (DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,ApplyDate,Src) + SELECT --'Y', + b.TargetDepartmentID as DepartmentID, + b.TargetAccountID as AccountID, + b.FiscalYearID, + ba.FiscalMonthID, + 2 as TimeclassID, + sum(Change) as Value, + max(b.Date) as ApplyDate, + 'ReallocateMulti' as src + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + INNER JOIN #StatisticTempTable STT_SRC on STT_SRC.DepartmentID = b.SourceDepartmentID and STT_SRC.AccountID = b.SourceAccountID and STT_SRC.FiscalYearID = b.FiscalYearID and stt_src.FiscalMonthID = ba.FiscalMonthID and STT_SRC.TimeClassID = 2 + LEFT JOIN #StatisticTempTable STT on STT.DepartmentID = b.TargetDepartmentID and STT.AccountID = b.TargetAccountID and STT.FiscalYearID = b.FiscalYearID and stt.FiscalMonthID = ba.FiscalMonthID and STT.TimeClassID = 2 + where stt.DepartmentID is null + and Change <> 0 + and ba.UnitTypeID =145 + and b.Date >= isnull(stt.ApplyDate,'1900-01-01') + and b.BudgetReallocationGUID = @BudgetReallocationGUID + GROUP BY + b.TargetDepartmentID, + b.TargetAccountID, + b.FiscalYearID, + ba.FiscalMonthID + UPDATE STT_SRC + SET + stt_src.Amount = 0, + stt_src.ApplyDate = b.Date, + stt_src.Src = stt_src.Src + '[RealMulti_'+cast(stt_src.Amount as varchar(50))+'_to_'+cast(stt.DepartmentID as varchar(10))+']' + FROM #StatisticTempTable STT + INNER JOIN [mr].[BudgetReallocation] b on b.TargetDepartmentID = stt.DepartmentID and b.TargetAccountID = stt.AccountID and b.Date >= stt.ApplyDate and b.FiscalYearID = stt.FiscalYearID + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID + INNER JOIN #StatisticTempTable STT_SRC on STT_SRC.DepartmentID = b.SourceDepartmentID and STT_SRC.AccountID = b.SourceAccountID and STT_SRC.FiscalYearID = b.FiscalYearID and stt_SRC.FiscalMonthID = ba.FiscalMonthID and STT_SRC.TimeClassID = 2 + where + b.BudgetReallocationGUID = @BudgetReallocationGUID + and ba.UnitTypeID = 145 + and Change <> 0 + END + ELSE + IF @BudgetReallocationType = 'AdjustMontly' + BEGIN + + UPDATE STT + SET + stt.Amount = stt.Amount+Change, + stt.ApplyDate = b.Date, + stt.Src = stt.Src + '[AdjustMontly_'+cast(Change as varchar(50))+']' + FROM #StatisticTempTable STT + INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and b.Date >= stt.ApplyDate and b.FiscalYearID = stt.FiscalYearID + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID + where + b.BudgetReallocationGUID = @BudgetReallocationGUID + and ba.UnitTypeID = 145 + and Change <> 0 + and b.Date >= isnull(stt.ApplyDate,'1900-01-01') + and TimeClassID = 2 + + INSERT INTO #StatisticTempTable (DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,ApplyDate,Src) + SELECT + b.SourceDepartmentID as DepartmentID, + b.SourceAccountID as AccountID, + b.FiscalYearID, + ba.FiscalMonthID, + 2 as TimeclassID, + SUM(Change) as Value, + MAX(b.date) as ApplyDate, + 'ra_3' as src + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + LEFT JOIN #StatisticTempTable STT ON b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID and stt.FiscalMonthID = ba.FiscalMonthID and TimeClassID = 2 + where Change <> 0 + and stt.DepartmentID is null + and ba.UnitTypeID =145 + and b.Date >= isnull(stt.ApplyDate,'1900-01-01') + and b.BudgetReallocationGUID = @BudgetReallocationGUID + GROUP BY + b.SourceDepartmentID, + b.SourceAccountID, + b.FiscalYearID, + ba.FiscalMonthID + END + ELSE + IF @BudgetReallocationType = 'ManualFile' + BEGIN + UPDATE STT + SET + stt.Amount = ba.NewSourceValue, + stt.ApplyDate = b.Date, + stt.Src = stt.Src + '[ManualFile_'+cast(NewSourceValue as varchar(50))+']' + FROM #StatisticTempTable STT + INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and b.Date >= stt.ApplyDate and b.FiscalYearID = stt.FiscalYearID + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID + where + b.BudgetReallocationGUID = @BudgetReallocationGUID + and ba.UnitTypeID = 145 + and TimeClassID = 2 + --and Change <> 0 + + INSERT INTO #StatisticTempTable (DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,ApplyDate,Src) + SELECT + b.SourceDepartmentID as DepartmentID, + b.SourceAccountID as AccountID, + b.FiscalYearID, + ba.FiscalMonthID, + 2 as TimeclassID, + SUM(NewSourceValue) as Value, + MAX(b.date) as ApplyDate, + 'ManualFile' as src + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + LEFT JOIN #StatisticTempTable STT ON b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID and stt.FiscalMonthID = ba.FiscalMonthID and TimeClassID = 2 + where Change <> 0 + and stt.DepartmentID is null + and ba.UnitTypeID =145 + and b.Date >= isnull(stt.ApplyDate,'1900-01-01') + and b.BudgetReallocationGUID = @BudgetReallocationGUID + GROUP BY b.SourceDepartmentID, + b.SourceAccountID, + b.FiscalYearID, + ba.FiscalMonthID + END + + set @iteration = @iteration +1 + + FETCH NEXT FROM BRA_cursor + INTO @BudgetReallocationGUID,@date,@BudgetReallocationType +END +CLOSE BRA_cursor; +DEALLOCATE BRA_cursor; + +if @StatisticType = 1 +begin +SELECT DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,SUM(Amount) as Amount +FROM ( + SELECT stt.DepartmentID,stt.AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,src + from #StatisticTempTable stt + inner join [fw].[viewStatisticPrimaryConfiguration] V on V.AccountID=stt.AccountID and V.DepartmentID=stt.DepartmentID + UNION ALL + SELECT stat.DepartmentID,stat.AccountID,FiscalYearID,FiscalMonthID,stat.TimeClassID,0 as Amount,cast('just0' as varchar(max)) as src + from int.FactStatistic stat + inner join [fw].[viewStatisticPrimaryConfiguration] V on V.AccountID=stat.AccountID and V.DepartmentID=stat.DepartmentID + WHERE stat.IsDeleted = 0 + and stat.Value != 0 + and (stat.FiscalYearID = @FiscalYearID or @FiscalYearID = 0) +) SubSelect +GROUP BY DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID +end +else if @StatisticType = 2 +begin +SELECT DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,SUM(Amount) as Amount +FROM ( + SELECT stt.DepartmentID,stt.AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,src + from #StatisticTempTable stt + inner join [fw].[viewStatisticSecondaryConfiguration] V on V.AccountID=stt.AccountID and V.DepartmentID=stt.DepartmentID + UNION ALL + SELECT stat.DepartmentID,stat.AccountID,FiscalYearID,FiscalMonthID,stat.TimeClassID,0 as Amount,cast('just0' as varchar(max)) as src + from int.FactStatistic stat + inner join [fw].[viewStatisticSecondaryConfiguration] V on V.AccountID=stat.AccountID and V.DepartmentID=stat.DepartmentID + WHERE stat.IsDeleted = 0 + and stat.Value != 0 + and (stat.FiscalYearID = @FiscalYearID or @FiscalYearID = 0) +) SubSelect +GROUP BY DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID + +end +else +begin +SELECT DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,SUM(Amount) as Amount +FROM ( + SELECT stt.DepartmentID,stt.AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,src + from #StatisticTempTable stt + UNION ALL + SELECT stat.DepartmentID,stat.AccountID,FiscalYearID,FiscalMonthID,stat.TimeClassID,0 as Amount,cast('just0' as varchar(max)) as src + from int.FactStatistic stat + WHERE stat.IsDeleted = 0 + and stat.Value != 0 + and (stat.FiscalYearID = @FiscalYearID or @FiscalYearID = 0) +) SubSelect +GROUP BY DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID +IF OBJECT_ID('tempdb..#StatisticTempTable') IS NOT NULL DROP TABLE #StatisticTempTable +end +GO + + +--------------------------------------------- + +-- fw.PrepareStatisticsPayPeriod +CREATE PROCEDURE [fw].[PrepareStatisticsPayPeriod] ( + @FiscalYearID INT = 0, + @departmentIDs NVARCHAR(max) = NULL, + @StatisticType INT = 0, + @isPrMetricConfigurationOn BIT = 0 + ) +/************************************************************ +** Author: ipetriv +** Create Date: 2017-7-26 +** Description: procedure to append to [int].[FactStatisticsbyPayPeriod] MR statistic reallocation adjustments +** Last Modified: 2017-7-26 +** GM Release: 2018.1 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-7-26 IP B-16752 Added section for monthly spread adjustments +** 2 2017-10-11 IP D-06489 Fixed difference between "by year" and "all years" end numbers +** 3 2018-01-17 IP B-16703 Omit archived budget adjustments +** 4 2018-03-15 IP D-06997 Replaced table variable by temp tables +** 5 2018-04-27 IP TK-56559 Adding grouping to fix integration test +** 6 2018-05-14 IP TK-57807 Reallocate between departments fix +** 7 2019-02-12 IP D-06606 PR Statistics sampling with adjustments is incorrectly calculating first Pay Period values +** 8 2020-03-20 vfay D-08997 [fw].[PrepareStatisticsPayPeriod] is reporting incorrect adjustment amounts +** 9 2023-04-11 HV JAZZ-52032 Create and fill caching table for charge-based statistics pay period data +*************************************************************/ +AS + IF OBJECT_ID('tempdb..#StatisticSampledTempTable') IS NOT NULL DROP TABLE #StatisticSampledTempTable + IF OBJECT_ID('tempdb..#departments') IS NOT NULL DROP TABLE #departments + IF OBJECT_ID('tempdb..#departmentsBudgetAllocations') IS NOT NULL DROP TABLE #departmentsBudgetAllocations + IF OBJECT_ID('tempdb..#FDPSD') IS NOT NULL DROP TABLE #FDPSD + IF OBJECT_ID('tempdb..#StatisticInsertTempTable') IS NOT NULL DROP TABLE #StatisticInsertTempTable + IF OBJECT_ID('tempdb..#payperiods') IS NOT NULL DROP TABLE #payperiods + IF OBJECT_ID('tempdb..#StatisticTempTableBackup') IS NOT NULL DROP TABLE #StatisticTempTableBackup + + DECLARE @iteration INT = 1 + CREATE TABLE #FDPSD (DepartmentID INT PRIMARY KEY) + + INSERT INTO #FDPSD + SELECT DISTINCT DriverDepartmentID AS DepartmentID + FROM client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache + + CREATE TABLE #departments (val INT PRIMARY KEY) + CREATE TABLE #departmentsBudgetAllocations (val INT PRIMARY KEY) + + INSERT INTO #departments SELECT val FROM ConvertCSValuesToTable(@departmentIDs, ',') + + INSERT INTO #departments + SELECT + SourceDepartmentID AS DepartmentID + FROM + mr.BudgetReallocationAdjustment a + INNER JOIN mr.BudgetReallocation r ON r.BudgetReallocationGUID=a.BudgetReallocationGUID + INNER JOIN #departments d ON d.val = r.TargetDepartmentID -- Filtering all departments that move data TO selected + UNION -- unique + SELECT + TargetDepartmentID AS DepartmentID + FROM + mr.BudgetReallocationAdjustment a + INNER JOIN mr.BudgetReallocation r ON r.BudgetReallocationGUID=a.BudgetReallocationGUID + INNER JOIN #departments d ON d.val = r.SourceDepartmentID -- Filtering all departments that move data FROM selected + + INSERT INTO #departmentsBudgetAllocations (val) + SELECT + SourceDepartmentID AS DepartmentID + FROM + mr.BudgetReallocationAdjustment a + INNER JOIN mr.BudgetReallocation r ON r.BudgetReallocationGUID = a.BudgetReallocationGUID + INNER JOIN FW.DimDepartment d ON d.DepartmentID = r.TargetDepartmentID AND d.IsPR = 1 + WHERE SourceDepartmentID <> 0 + UNION -- unique + SELECT + TargetDepartmentID AS DepartmentID + FROM + mr.BudgetReallocationAdjustment a + INNER JOIN mr.BudgetReallocation r ON r.BudgetReallocationGUID=a.BudgetReallocationGUID + INNER JOIN FW.DimDepartment d ON d.DepartmentID = r.SourceDepartmentID and d.IsPR = 1 -- Filtering all departments that move data FROM selected + where TargetDepartmentID <> 0 + + CREATE TABLE #payperiods(val SMALLINT PRIMARY KEY, PayCycleID int, PeriodStartCalendarDate date, PeriodEndCalendarDate date) + INSERT INTO #payperiods (val, PayCycleID, PeriodStartCalendarDate, PeriodEndCalendarDate) + SELECT PayPeriodID, PayCycleID, PeriodStartCalendarDate, PeriodEndCalendarDate + FROM fw.DimPayPeriod + WHERE FiscalYearIDSecond = @fiscalYearID or @fiscalYearID = 0 + + --run custom scripts + EXEC [client].[procStatisticSampledInsertPayPeriodPreprocess] + + CREATE TABLE #StatisticSampledTempTable + ( + DepartmentID int, + AccountID int, + PayPeriodID int, + TimeClassID int, + Units decimal(18, 6) + ) + + --pull new data - Pay Period Actuals from GL + INSERT INTO #StatisticSampledTempTable (DepartmentID, AccountID, PayPeriodID, TimeClassID, Units) + SELECT + stat.[DepartmentID], + stat.[AccountID], + stat.[PayPeriodID], + stat.[TimeClassID], + SUM(stat.[Value]) AS Units + FROM + [int].[FactStatisticsbyPayPeriod] stat + inner join [fw].[DimDepartment] D on D.DepartmentID = stat.DepartmentID + left join #FDPSD FDPSD on FDPSD.DepartmentID = stat.DepartmentID + WHERE + stat.[Value] <> 0 AND stat.Isdeleted = 0 AND stat.PayPeriodID != 0 + AND (D.IsPR = 1 or exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache dc where dc.DriverDepartmentID = D.DepartmentID)) + AND stat.TimeClassID=1 + AND stat.DepartmentID <> 0 + AND (D.IsPR = 1 or FDPSD.DepartmentID is not null) + AND (@departmentIDs is null or stat.DepartmentID in (select val from #departments)) + AND (@fiscalYearID = 0 or stat.PayPeriodID in (select val from #payperiods)) + GROUP BY + stat.DepartmentID, + stat.AccountID, + stat.PayPeriodID, + stat.TimeClassID + + --pull new data - Aggregation of daily GL Actuals where not already sampled + INSERT INTO #StatisticSampledTempTable (DepartmentID, AccountID, PayPeriodID, TimeClassID, Units) + SELECT + stat.[DepartmentID], + stat.[AccountID], + PP.[PayPeriodID], + stat.[TimeClassID], + SUM(STAT.[Value]) as Units + FROM + [int].[FactSharedImportDailyStatistics] stat + inner join [fw].[DimDate] DATE on stat.DateID=DATE.DateID + inner join [fw].[DimDepartment] D on D.Departmentid = STAT.Departmentid + inner join [fw].[DimPayPeriod] PP on D.PayCycleID=PP.PayCycleID and DATE.CalendarDateTime between PP.PeriodStartCalendarDate and PP.PeriodEndCalendarDate + left join #FDPSD FDPSD ON FDPSD.DepartmentID = STAT.DepartmentID + left join #StatisticSampledTempTable ex on ex.DepartmentID = stat.DepartmentID and ex.AccountID = stat.AccountID and ex.PayPeriodID = PP.PayPeriodID and ex.TimeClassID = 1 + WHERE + stat.[Value] <> 0 and STAT.Isdeleted = 0 and PP.PayPeriodID != 0 + and (D.IsPR = 1 or FDPSD.DepartmentID is not null) + and stat.TimeClassID = 1 + and stat.DepartmentID <> 0 + and ex.DepartmentID IS NULL + and (@departmentIDs is null or stat.DepartmentID in (select val from #departments)) + and (@fiscalYearID = 0 or pp.FiscalYearIDSecond = @fiscalYearID) + GROUP BY + stat.DepartmentID, + stat.AccountID, + stat.TimeClassID, + PP.PayPeriodID + + --pull new data - Aggregation of daily charge-based Actuals where not already sampled + INSERT INTO #StatisticSampledTempTable (DepartmentID, AccountID, PayPeriodID, TimeClassID, Units) + SELECT + STAT.DepartmentID, + STAT.AccountID, + PP.PayPeriodID, + 1 as TimeClassID, + SUM(STAT.Value) AS Units + FROM + [fw].[FactChargeBasedStatistics] STAT + inner join [fw].[DimDate] DATE on STAT.DateID=DATE.DateID + inner join [fw].[DimDepartment] D on STAT.DepartmentID=D.DepartmentID + inner join [fw].[DimPayPeriod] PP on D.PayCycleID=PP.PayCycleID and DATE.CalendarDateTime between PP.PeriodStartCalendarDate and PP.PeriodEndCalendarDate + left join #FDPSD FDPSD ON FDPSD.DepartmentID = STAT.DepartmentID + left join #StatisticSampledTempTable ex on ex.DepartmentID = stat.DepartmentID and ex.AccountID = stat.AccountID and ex.PayPeriodID = PP.PayPeriodID and ex.TimeClassID = 1 + WHERE + STAT.Value != 0 and STAT.IsDeleted = 0 and PP.PayPeriodID != 0 + and (D.IsPR = 1 or FDPSD.DepartmentID is not null) + and ex.DepartmentID IS NULL + and (@departmentIDs is null or STAT.DepartmentID in (select val from #departments)) + and (@fiscalYearID = 0 or pp.FiscalYearIDSecond = @fiscalYearID) + GROUP BY + STAT.DepartmentID, + STAT.AccountID, + PP.PayPeriodID + + --pull new data - Pay Period Budget from GL for all Departments and Accounts + INSERT INTO #StatisticSampledTempTable (DepartmentID, AccountID, PayPeriodID, TimeClassID, Units) + SELECT + stat.[DepartmentID], + stat.[AccountID], + STAT.[PayPeriodID], + stat.[TimeClassID], + SUM(STAT.[Value]) as Units + FROM + [int].[FactStatisticsbyPayPeriod] stat + inner join [fw].[DimDepartment] D on D.Departmentid = STAT.[Departmentid] + left join #FDPSD FDPSD ON FDPSD.DepartmentID = STAT.[DepartmentID] + left join #departmentsBudgetAllocations dba on dba.val = d.DepartmentID + WHERE + STAT.[Value] != 0 and STAT.Isdeleted = 0 and STAT.PayPeriodID != 0 + and (D.IsPR = 1 or FDPSD.DepartmentID is not null or dba.val is not null) + and stat.TimeClassID = 2 + and stat.DepartmentID <> 0 + and (@departmentIDs is null or stat.DepartmentID in (select val from #departments)) + and (@fiscalYearID = 0 or stat.PayPeriodID in (select val from #payperiods)) + GROUP BY + stat.DepartmentID, + stat.AccountID, + STAT.PayPeriodID, + stat.TimeClassID + + CREATE TABLE #StatisticInsertTempTable + ( + DepartmentID int, + AccountID int, + PayPeriodID int, + TimeClassID int, + Units decimal(18, 6) + ) + + CREATE TABLE #StatisticTempTableBackup + ( + DepartmentID int, + AccountID int, + PayPeriodID int, + TimeClassID int, + Units decimal(18, 6) + ) + + INSERT INTO #StatisticTempTableBackup(DepartmentID, AccountID, PayPeriodID, TimeClassID, Units) + SELECT DepartmentID, AccountID, PayPeriodID, TimeClassID, Units from #StatisticSampledTempTable + + DECLARE @BudgetReallocationGUID UNIQUEIDENTIFIER, + @date DATETIME, + @BudgetReallocationType VARCHAR(50) + + PRINT '-------- Vendor Products Report --------'; + + DECLARE BRA_cursor CURSOR + FOR + SELECT DISTINCT + BudgetReallocationGUID, [DATE], BudgetReallocationType + FROM fw.BudgetReallocationWithDefinedType br + INNER JOIN [fw].DimPayPeriod pp ON ( + (br.FiscalMonthID = pp.FiscalMonthIDStart AND br.FiscalYearID = pp.FiscalYearIDStart) OR + (br.FiscalMonthID = pp.FiscalMonthIDSecond AND br.FiscalYearID = pp.FiscalYearIDSecond)) + INNER JOIN #payperiods pay ON pay.val = pp.PayPeriodID + WHERE br.BudgetReallocationType IS NOT NULL + ORDER BY DATE; + + OPEN BRA_cursor + + FETCH NEXT + FROM BRA_cursor + INTO @BudgetReallocationGUID, @date, @BudgetReallocationType + + WHILE @@FETCH_STATUS = 0 + BEGIN + IF @BudgetReallocationType = 'ReallocateSingle' + BEGIN + + --update target + UPDATE stt + SET + Units = Units + ba.Change * pp.PeriodWeightStart + FROM + #StatisticSampledTempTable stt + INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID + INNER JOIN [mr].[BudgetReallocation] b ON + b.TargetDepartmentID = stt.DepartmentID AND + b.TargetAccountID = stt.AccountID AND + b.FiscalYearID = pp.FiscalYearIDStart + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON + b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND + ba.FiscalMonthID = pp.FiscalMonthIDStart + WHERE + ba.Change <> 0 AND + b.BudgetReallocationGUID = @BudgetReallocationGUID AND + ba.UnitTypeID = 145 AND + stt.TimeClassID = 2 AND + b.Archived = 0 + + UPDATE stt + SET + Units = Units + ba.Change * pp.PeriodWeightSecond + FROM + #StatisticSampledTempTable stt + INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID + INNER JOIN [mr].[BudgetReallocation] b ON + b.TargetDepartmentID = stt.DepartmentID AND + b.TargetAccountID = stt.AccountID AND + b.FiscalYearID = pp.FiscalYearIDSecond + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON + b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND + ba.FiscalMonthID = pp.FiscalMonthIDSecond + WHERE + ba.Change <> 0 AND + b.BudgetReallocationGUID = @BudgetReallocationGUID AND + ba.UnitTypeID = 145 AND + stt.TimeClassID = 2 AND + b.Archived = 0 + + --update source + UPDATE stt + SET + Units = Units - ba.Change * pp.PeriodWeightStart + FROM + #StatisticSampledTempTable stt + INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID + INNER JOIN [mr].[BudgetReallocation] b ON + b.SourceDepartmentID = stt.DepartmentID AND + b.SourceAccountID = stt.AccountID AND + b.FiscalYearID = pp.FiscalYearIDStart + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON + b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND + ba.FiscalMonthID = pp.FiscalMonthIDStart + WHERE + ba.Change <> 0 AND + b.BudgetReallocationGUID = @BudgetReallocationGUID AND + ba.UnitTypeID = 145 AND + stt.TimeClassID = 2 AND + b.Archived = 0 + + UPDATE stt + SET + Units = Units - ba.Change * pp.PeriodWeightSecond + FROM + #StatisticSampledTempTable stt + INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID + INNER JOIN [mr].[BudgetReallocation] b ON + b.SourceDepartmentID = stt.DepartmentID AND + b.SourceAccountID = stt.AccountID AND + b.FiscalYearID = pp.FiscalYearIDSecond + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON + b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND + ba.FiscalMonthID = pp.FiscalMonthIDSecond + WHERE + ba.Change <> 0 AND + b.BudgetReallocationGUID = @BudgetReallocationGUID AND + ba.UnitTypeID = 145 AND + stt.TimeClassID = 2 AND + b.Archived = 0 + + --clear records in temp insert table + TRUNCATE TABLE #StatisticInsertTempTable + + -- insert missing source records + INSERT INTO #StatisticInsertTempTable(DepartmentID, AccountID, PayPeriodID, TimeClassID, Units) + SELECT + b.SourceDepartmentID AS DepartmentID, + b.SourceAccountID AS AccountID, + pp.PayPeriodID, + 2 AS TimeclassID, + SUM((ba.Change * pp.PeriodWeightStart)*-1) AS Units + FROM + [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON b.BudgetReallocationGUID=ba.BudgetReallocationGUID + INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = b.SourceDepartmentID + INNER JOIN [fw].[DimPayPeriod] pp ON + pp.PayCycleID = dep.PayCycleID AND + pp.FiscalMonthIDStart = ba.FiscalMonthID AND + pp.FiscalYearIDStart = b.FiscalYearID + INNER JOIN #payperiods pay on pp.PayPeriodID = pay.val + LEFT JOIN #StatisticSampledTempTable stt ON + b.SourceDepartmentID = stt.DepartmentID AND + b.SourceAccountID = stt.AccountID AND + pp.PayPeriodId = stt.PayPeriodID AND + stt.TimeClassID = 2 + WHERE + ba.Change <> 0 AND + b.BudgetReallocationGUID = @BudgetReallocationGUID AND + stt.DepartmentID IS NULL AND + ba.UnitTypeID = 145 AND + b.Archived = 0 + GROUP BY + b.SourceDepartmentID, + b.SourceAccountID, + pp.PayPeriodID + UNION ALL + SELECT + b.SourceDepartmentID AS DepartmentID, + b.SourceAccountID AS AccountID, + pp.PayPeriodID, + 2 AS TimeclassID, + SUM((ba.Change * pp.PeriodWeightSecond)*-1) AS Units + FROM + [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON b.BudgetReallocationGUID=ba.BudgetReallocationGUID + INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = b.SourceDepartmentID + INNER JOIN [fw].[DimPayPeriod] pp ON + pp.PayCycleID = dep.PayCycleID AND + pp.FiscalMonthIDSecond = ba.FiscalMonthID AND + pp.FiscalYearIDSecond = b.FiscalYearID + INNER JOIN #payperiods pay on pp.PayPeriodID = pay.val + LEFT JOIN #StatisticSampledTempTable stt ON + b.SourceDepartmentID = stt.DepartmentID AND + b.SourceAccountID = stt.AccountID AND + pp.PayPeriodId = stt.PayPeriodID AND + stt.TimeClassID = 2 + WHERE + ba.Change <> 0 AND + b.BudgetReallocationGUID = @BudgetReallocationGUID AND + stt.DepartmentID IS NULL AND + ba.UnitTypeID = 145 AND + b.Archived = 0 + GROUP BY + b.SourceDepartmentID, + b.SourceAccountID, + pp.PayPeriodID + + --insert missing target records + INSERT INTO #StatisticInsertTempTable(DepartmentID, AccountID, PayPeriodID, TimeClassID, Units) + SELECT + b.TargetDepartmentID AS DepartmentID, + b.TargetAccountID AS AccountID, + pp.PayPeriodID, + 2 AS TimeclassID, + SUM((ba.Change * pp.PeriodWeightStart)) AS Units + FROM + [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON b.BudgetReallocationGUID=ba.BudgetReallocationGUID + INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = b.TargetDepartmentID + INNER JOIN [fw].[DimPayPeriod] pp ON + pp.PayCycleID = dep.PayCycleID AND + pp.FiscalMonthIDStart = ba.FiscalMonthID AND + pp.FiscalYearIDStart = b.FiscalYearID + INNER JOIN #payperiods pay on pp.PayPeriodID = pay.val + LEFT JOIN #StatisticSampledTempTable stt ON + b.TargetDepartmentID = stt.DepartmentID AND + b.TargetAccountID = stt.AccountID AND + pp.PayPeriodId = stt.PayPeriodID AND + stt.TimeClassID = 2 + WHERE + ba.Change <> 0 AND + b.BudgetReallocationGUID = @BudgetReallocationGUID AND + stt.DepartmentID IS NULL AND + ba.UnitTypeID = 145 AND + b.Archived = 0 + GROUP BY + b.TargetDepartmentID, + b.TargetAccountID, + pp.PayPeriodID + UNION ALL + SELECT + b.TargetDepartmentID AS DepartmentID, + b.TargetAccountID AS AccountID, + pp.PayPeriodID, + 2 AS TimeclassID, + SUM((ba.Change * pp.PeriodWeightSecond)) AS Units + FROM + [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON b.BudgetReallocationGUID=ba.BudgetReallocationGUID + INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = b.TargetDepartmentID + INNER JOIN [fw].[DimPayPeriod] pp ON + pp.PayCycleID = dep.PayCycleID AND + pp.FiscalMonthIDSecond = ba.FiscalMonthID AND + pp.FiscalYearIDSecond = b.FiscalYearID + INNER JOIN #payperiods pay on pp.PayPeriodID = pay.val + LEFT JOIN #StatisticSampledTempTable stt ON + b.TargetDepartmentID = stt.DepartmentID AND + b.TargetAccountID = stt.AccountID AND + pp.PayPeriodId = stt.PayPeriodID AND + stt.TimeClassID = 2 + WHERE + ba.Change <> 0 AND + b.BudgetReallocationGUID = @BudgetReallocationGUID AND + stt.DepartmentID IS NULL AND + ba.UnitTypeID = 145 AND + b.Archived = 0 + GROUP BY + b.TargetDepartmentID, + b.TargetAccountID, + pp.PayPeriodID + + --insert to statistic temp table + INSERT INTO #StatisticSampledTempTable(DepartmentID, AccountID, PayPeriodID, TimeClassID, Units) + SELECT + DepartmentID, + AccountID, + PayPeriodID, + TimeClassID, + SUM(Units) + FROM #StatisticInsertTempTable + GROUP BY + DepartmentID, + AccountID, + PayPeriodID, + TimeClassID + END + + IF @BudgetReallocationType = 'ReallocateMulti' + BEGIN + --update target + UPDATE stt + SET + Units = stt.Units + stt_src_back.Units * pp.DaysInPeriodWeightStart + FROM + #StatisticSampledTempTable stt + INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID + INNER JOIN [mr].[BudgetReallocation] b ON + b.TargetDepartmentID = stt.DepartmentID AND + b.TargetAccountID = stt.AccountID AND + b.FiscalYearID = pp.FiscalYearIDStart + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON + b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND + ba.FiscalMonthID = pp.FiscalMonthIDStart + INNER JOIN #StatisticTempTableBackup stt_src_back ON + stt_src_back.DepartmentID = b.SourceDepartmentID AND + stt_src_back.AccountID = b.SourceAccountID AND + stt_src_back.PayPeriodID = stt.PayPeriodID AND + stt_src_back.TimeClassID = stt.TimeClassID + WHERE + ba.Change <> 0 AND + b.BudgetReallocationGUID = @BudgetReallocationGUID AND + ba.UnitTypeID = 145 AND + stt.TimeClassID = 2 AND + b.Archived = 0 + + UPDATE stt + SET + Units = stt.Units + stt_src_back.Units * pp.DaysInPeriodWeightSecond + FROM + #StatisticSampledTempTable stt + INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID + INNER JOIN [mr].[BudgetReallocation] b ON + b.TargetDepartmentID = stt.DepartmentID AND + b.TargetAccountID = stt.AccountID AND + b.FiscalYearID = pp.FiscalYearIDSecond + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON + b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND + ba.FiscalMonthID = pp.FiscalMonthIDSecond + INNER JOIN #StatisticTempTableBackup stt_src_back ON + stt_src_back.DepartmentID = b.SourceDepartmentID AND + stt_src_back.AccountID = b.SourceAccountID AND + stt_src_back.PayPeriodID = stt.PayPeriodID AND + stt_src_back.TimeClassID = stt.TimeClassID + WHERE + ba.Change <> 0 AND + b.BudgetReallocationGUID = @BudgetReallocationGUID AND + ba.UnitTypeID = 145 AND + stt.TimeClassID = 2 AND + b.Archived = 0 + + --clear records in temp insert table + TRUNCATE TABLE #StatisticInsertTempTable + + -- insert missing target records + INSERT INTO #StatisticInsertTempTable(DepartmentID, AccountID, PayPeriodID, TimeClassID, Units) + SELECT + b.TargetDepartmentID AS DepartmentID, + b.TargetAccountID AS AccountID, + pp.PayPeriodID, + 2 AS TimeclassID, + SUM(stt_src_back.Units * pp.DaysInPeriodWeightStart) AS Units + FROM + [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON b.BudgetReallocationGUID=ba.BudgetReallocationGUID + INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = b.TargetDepartmentID + INNER JOIN [fw].[DimPayPeriod] pp ON + pp.PayCycleID = dep.PayCycleID AND + pp.FiscalMonthIDStart = ba.FiscalMonthID AND + pp.FiscalYearIDStart = b.FiscalYearID + INNER JOIN #payperiods pay on pp.PayPeriodID = pay.val + INNER JOIN #StatisticTempTableBackup stt_src_back ON + stt_src_back.DepartmentID = b.SourceDepartmentID AND + stt_src_back.AccountID = b.SourceAccountID AND + stt_src_back.PayPeriodID = PP.PayPeriodID AND + stt_src_back.TimeClassID = 2 + LEFT JOIN #StatisticSampledTempTable stt ON + stt.DepartmentID = b.TargetDepartmentID AND + stt.AccountID = b.TargetAccountID AND + stt.PayPeriodID = pp.PayPeriodID AND + stt.TimeClassID = 2 + WHERE + stt.DepartmentID IS NULL AND + ba.Change <> 0 AND + b.BudgetReallocationGUID = @BudgetReallocationGUID AND + ba.UnitTypeID = 145 AND + b.Archived = 0 + GROUP BY + b.TargetDepartmentID, + b.TargetAccountID, + pp.PayPeriodID + UNION ALL + SELECT + b.TargetDepartmentID AS DepartmentID, + b.TargetAccountID AS AccountID, + pp.PayPeriodID, + 2 AS TimeclassID, + SUM(stt_src_back.Units * pp.DaysInPeriodWeightSecond) AS Units + FROM + [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON b.BudgetReallocationGUID=ba.BudgetReallocationGUID + INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = b.TargetDepartmentID + INNER JOIN [fw].[DimPayPeriod] pp ON + pp.PayCycleID = dep.PayCycleID AND + pp.FiscalMonthIDSecond = ba.FiscalMonthID AND + pp.FiscalYearIDSecond = b.FiscalYearID + INNER JOIN #payperiods pay on pp.PayPeriodID = pay.val + INNER JOIN #StatisticTempTableBackup stt_src_back ON + stt_src_back.DepartmentID = b.SourceDepartmentID AND + stt_src_back.AccountID = b.SourceAccountID AND + stt_src_back.PayPeriodID = PP.PayPeriodID AND + stt_src_back.TimeClassID = 2 + LEFT JOIN #StatisticSampledTempTable stt ON + stt.DepartmentID = b.TargetDepartmentID AND + stt.AccountID = b.TargetAccountID AND + stt.PayPeriodID = pp.PayPeriodID AND + stt.TimeClassID = 2 + WHERE + stt.DepartmentID IS NULL AND + ba.Change <> 0 AND + b.BudgetReallocationGUID = @BudgetReallocationGUID AND + ba.UnitTypeID = 145 AND + b.Archived = 0 + GROUP BY + b.TargetDepartmentID, + b.TargetAccountID, + pp.PayPeriodID + + --insert to statistic temp table + INSERT INTO #StatisticSampledTempTable(DepartmentID, AccountID, PayPeriodID, TimeClassID, Units) + SELECT + DepartmentID, + AccountID, + PayPeriodID, + TimeClassID, + SUM(Units) + FROM #StatisticInsertTempTable + GROUP BY + DepartmentID, + AccountID, + PayPeriodID, + TimeClassID + + --update source + UPDATE stt_src + SET + Units = stt_src.Units - stt_src_back.Units * DaysInPeriodWeightStart + FROM + #StatisticSampledTempTable stt_src + INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt_src.PayPeriodID + INNER JOIN [mr].[BudgetReallocation] b ON + b.SourceDepartmentID = stt_src.DepartmentID AND + b.SourceAccountID = stt_src.AccountID AND + b.FiscalYearID = pp.FiscalYearIDStart + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON + b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND + ba.FiscalMonthID = pp.FiscalMonthIDStart + INNER JOIN #StatisticTempTableBackup stt_src_back ON + stt_src.AccountID = stt_src_back.AccountID AND + stt_src.DepartmentID = stt_src_back.DepartmentID AND + stt_src.PayPeriodID = stt_src_back.PayPeriodID AND + stt_src.TimeClassID = stt_src_back.TimeClassID + LEFT JOIN #StatisticSampledTempTable stt ON + stt.DepartmentID = b.TargetDepartmentID and + stt.AccountID = b.TargetAccountID and + stt.TimeClassID = 2 and + stt.PayPeriodID = stt_src.PayPeriodID + WHERE + ba.Change <> 0 AND + b.BudgetReallocationGUID = @BudgetReallocationGUID AND + ba.UnitTypeID = 145 AND + b.Archived = 0 + + UPDATE stt_src + SET + Units = stt_src.Units - stt_src_back.Units * DaysInPeriodWeightSecond + FROM + #StatisticSampledTempTable stt_src + INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt_src.PayPeriodID + INNER JOIN [mr].[BudgetReallocation] b ON + b.SourceDepartmentID = stt_src.DepartmentID AND + b.SourceAccountID = stt_src.AccountID AND + b.FiscalYearID = pp.FiscalYearIDSecond + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON + b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND + ba.FiscalMonthID = pp.FiscalMonthIDSecond + INNER JOIN #StatisticTempTableBackup stt_src_back ON + stt_src.AccountID = stt_src_back.AccountID AND + stt_src.DepartmentID = stt_src_back.DepartmentID AND + stt_src.PayPeriodID = stt_src_back.PayPeriodID AND + stt_src.TimeClassID = stt_src_back.TimeClassID + LEFT JOIN #StatisticSampledTempTable stt ON + stt.DepartmentID = b.TargetDepartmentID and + stt.AccountID = b.TargetAccountID and + stt.TimeClassID = 2 and + stt.PayPeriodID = stt_src.PayPeriodID + WHERE + ba.Change <> 0 AND + b.BudgetReallocationGUID = @BudgetReallocationGUID AND + ba.UnitTypeID = 145 AND + b.Archived = 0 + + END + + IF @BudgetReallocationType = 'AdjustMontly' + BEGIN + + --update source + UPDATE stt + SET + Units = Units + ba.Change * pp.PeriodWeightStart + FROM + #StatisticSampledTempTable stt + INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID + INNER JOIN [mr].[BudgetReallocation] b ON + b.SourceDepartmentID = stt.DepartmentID AND + b.SourceAccountID = stt.AccountID AND + b.FiscalYearID = pp.FiscalYearIDStart + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON + b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND + ba.FiscalMonthID = pp.FiscalMonthIDStart + WHERE + ba.Change <> 0 AND + b.BudgetReallocationGUID = @BudgetReallocationGUID AND + ba.UnitTypeID = 145 AND + stt.TimeClassID = 2 AND + b.Archived = 0 + + UPDATE stt + SET + Units = Units + ba.Change * pp.PeriodWeightSecond + FROM + #StatisticSampledTempTable stt + INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID + INNER JOIN [mr].[BudgetReallocation] b ON + b.SourceDepartmentID = stt.DepartmentID AND + b.SourceAccountID = stt.AccountID AND + b.FiscalYearID = pp.FiscalYearIDSecond + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON + b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND + ba.FiscalMonthID = pp.FiscalMonthIDSecond + WHERE + ba.Change <> 0 AND + b.BudgetReallocationGUID = @BudgetReallocationGUID AND + ba.UnitTypeID = 145 AND + stt.TimeClassID = 2 AND + b.Archived = 0 + + --clear records in temp insert table + TRUNCATE TABLE #StatisticInsertTempTable + + -- insert missing source records + INSERT INTO #StatisticInsertTempTable(DepartmentID, AccountID, PayPeriodID, TimeClassID, Units) + SELECT + b.SourceDepartmentID AS DepartmentID, + b.SourceAccountID AS AccountID, + pp.PayPeriodID, + 2 AS TimeclassID, + SUM(ba.Change * pp.PeriodWeightStart) AS Units + FROM + [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON b.BudgetReallocationGUID=ba.BudgetReallocationGUID + INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = b.SourceDepartmentID + INNER JOIN [fw].[DimPayPeriod] pp ON + pp.PayCycleID = dep.PayCycleID AND + pp.FiscalMonthIDStart = ba.FiscalMonthID AND + pp.FiscalYearIDStart = b.FiscalYearID + INNER JOIN #payperiods pay on pp.PayPeriodID = pay.val + LEFT JOIN #StatisticSampledTempTable stt ON + b.SourceDepartmentID = stt.DepartmentID AND + b.SourceAccountID = stt.AccountID AND + pp.PayPeriodID = stt.PayPeriodID AND + stt.TimeClassID = 2 + WHERE + ba.Change <> 0 and + b.BudgetReallocationGUID = @BudgetReallocationGUID and + stt.DepartmentID is null and + ba.UnitTypeID = 145 and + b.Archived = 0 + GROUP BY + b.SourceDepartmentID, + b.SourceAccountID, + pp.PayPeriodID + UNION ALL + SELECT + b.SourceDepartmentID AS DepartmentID, + b.SourceAccountID AS AccountID, + pp.PayPeriodID, + 2 AS TimeclassID, + SUM(ba.Change * pp.PeriodWeightSecond) AS Units + FROM + [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON b.BudgetReallocationGUID=ba.BudgetReallocationGUID + INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = b.SourceDepartmentID + INNER JOIN [fw].[DimPayPeriod] pp ON + pp.PayCycleID = dep.PayCycleID AND + pp.FiscalMonthIDSecond = ba.FiscalMonthID AND + pp.FiscalYearIDSecond = b.FiscalYearID + INNER JOIN #payperiods pay on pp.PayPeriodID = pay.val + LEFT JOIN #StatisticSampledTempTable stt ON + b.SourceDepartmentID = stt.DepartmentID AND + b.SourceAccountID = stt.AccountID AND + pp.PayPeriodID = stt.PayPeriodID AND + stt.TimeClassID = 2 + WHERE + ba.Change <> 0 and + b.BudgetReallocationGUID = @BudgetReallocationGUID and + stt.DepartmentID is null and + ba.UnitTypeID = 145 and + b.Archived = 0 + GROUP BY + b.SourceDepartmentID, + b.SourceAccountID, + pp.PayPeriodID + + --insert to statistic temp table + INSERT INTO #StatisticSampledTempTable(DepartmentID, AccountID, PayPeriodID, TimeClassID, Units) + SELECT + DepartmentID, + AccountID, + PayPeriodID, + TimeClassID, + SUM(Units) + FROM #StatisticInsertTempTable + GROUP BY + DepartmentID, + AccountID, + PayPeriodID, + TimeClassID + END + + IF @BudgetReallocationType = 'ManualFile' + BEGIN + --update source + UPDATE stt + SET + stt.Units = stt.Units - stt_src_back.Units * pp.DaysInPeriodWeightStart + FROM + #StatisticSampledTempTable stt + INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID + INNER JOIN [mr].[BudgetReallocation] b ON + b.SourceDepartmentID = stt.DepartmentID AND + b.SourceAccountID = stt.AccountID AND + b.FiscalYearID = pp.FiscalYearIDStart + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON + b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND + ba.FiscalMonthID = pp.FiscalMonthIDStart + INNER JOIN #StatisticTempTableBackup stt_src_back ON + stt.AccountID = stt_src_back.AccountID AND + stt.DepartmentID = stt_src_back.DepartmentID AND + stt.PayPeriodID = stt_src_back.PayPeriodID AND + stt.TimeClassID = stt_src_back.TimeClassID + WHERE + ba.Change <> 0 AND + b.BudgetReallocationGUID = @BudgetReallocationGUID AND + ba.UnitTypeID = 145 AND + stt.TimeClassID = 2 AND + b.Archived = 0 + + UPDATE stt + SET + stt.Units = stt.Units - stt_src_back.Units * pp.DaysInPeriodWeightSecond + FROM + #StatisticSampledTempTable stt + INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID + INNER JOIN [mr].[BudgetReallocation] b ON + b.SourceDepartmentID = stt.DepartmentID AND + b.SourceAccountID = stt.AccountID AND + b.FiscalYearID = pp.FiscalYearIDSecond + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON + b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND + ba.FiscalMonthID = pp.FiscalMonthIDSecond + INNER JOIN #StatisticTempTableBackup stt_src_back ON + stt.AccountID = stt_src_back.AccountID AND + stt.DepartmentID = stt_src_back.DepartmentID AND + stt.PayPeriodID = stt_src_back.PayPeriodID AND + stt.TimeClassID = stt_src_back.TimeClassID + WHERE + ba.Change <> 0 AND + b.BudgetReallocationGUID = @BudgetReallocationGUID AND + ba.UnitTypeID = 145 AND + stt.TimeClassID = 2 AND + b.Archived = 0 + + UPDATE stt + SET + Units = Units + ba.NewSourceValue * pp.PeriodWeightStart + FROM + #StatisticSampledTempTable stt + INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID + INNER JOIN [mr].[BudgetReallocation] b ON + b.SourceDepartmentID = stt.DepartmentID AND + b.SourceAccountID = stt.AccountID AND + b.FiscalYearID = pp.FiscalYearIDStart + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON + b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND + ba.FiscalMonthID = pp.FiscalMonthIDStart + WHERE + ba.Change <> 0 AND + b.BudgetReallocationGUID = @BudgetReallocationGUID AND + ba.UnitTypeID = 145 AND + stt.TimeClassID = 2 AND + b.Archived = 0 + + UPDATE stt + SET + Units = Units + ba.NewSourceValue * pp.PeriodWeightSecond + FROM + #StatisticSampledTempTable stt + INNER JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID=stt.PayPeriodID + INNER JOIN [mr].[BudgetReallocation] b ON + b.SourceDepartmentID = stt.DepartmentID AND + b.SourceAccountID = stt.AccountID AND + b.FiscalYearID = pp.FiscalYearIDSecond + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON + b.BudgetReallocationGUID = ba.BudgetReallocationGUID AND + ba.FiscalMonthID = pp.FiscalMonthIDSecond + WHERE + ba.Change <> 0 AND + b.BudgetReallocationGUID = @BudgetReallocationGUID AND + ba.UnitTypeID = 145 AND + stt.TimeClassID = 2 AND + b.Archived = 0 + + --clear records in temp insert table + TRUNCATE TABLE #StatisticInsertTempTable + + -- insert missing source records + INSERT INTO #StatisticInsertTempTable(DepartmentID, AccountID, PayPeriodID, TimeClassID, Units) + SELECT + b.SourceDepartmentID AS DepartmentID, + b.SourceAccountID AS AccountID, + pp.PayPeriodID, + 2 AS TimeclassID, + SUM(ba.NewSourceValue * pp.PeriodWeightStart) AS Units + FROM + [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON b.BudgetReallocationGUID=ba.BudgetReallocationGUID + INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = b.SourceDepartmentID + INNER JOIN [fw].[DimPayPeriod] pp ON + pp.PayCycleID = dep.PayCycleID AND + pp.FiscalMonthIDStart = ba.FiscalMonthID AND + pp.FiscalYearIDStart = b.FiscalYearID + INNER JOIN #payperiods pay on pp.PayPeriodID = pay.val + LEFT JOIN #StatisticSampledTempTable stt ON + b.SourceDepartmentID = stt.DepartmentID AND + b.SourceAccountID = stt.AccountID AND + pp.PayPeriodID = stt.PayPeriodID AND + stt.TimeClassID = 2 + WHERE + ba.Change <> 0 and + b.BudgetReallocationGUID = @BudgetReallocationGUID and + stt.DepartmentID is null and + ba.UnitTypeID = 145 and + b.Archived = 0 + GROUP BY + b.SourceDepartmentID, + b.SourceAccountID, + pp.PayPeriodID + UNION ALL + SELECT + b.SourceDepartmentID AS DepartmentID, + b.SourceAccountID AS AccountID, + pp.PayPeriodID, + 2 AS TimeclassID, + SUM(ba.NewSourceValue * pp.PeriodWeightSecond) AS Units + FROM + [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba ON b.BudgetReallocationGUID=ba.BudgetReallocationGUID + INNER JOIN [fw].[DimDepartment] dep ON dep.DepartmentID = b.SourceDepartmentID + INNER JOIN [fw].[DimPayPeriod] pp ON + pp.PayCycleID = dep.PayCycleID AND + pp.FiscalMonthIDSecond = ba.FiscalMonthID AND + pp.FiscalYearIDSecond = b.FiscalYearID + INNER JOIN #payperiods pay on pp.PayPeriodID = pay.val + LEFT JOIN #StatisticSampledTempTable stt ON + b.SourceDepartmentID = stt.DepartmentID AND + b.SourceAccountID = stt.AccountID AND + pp.PayPeriodID = stt.PayPeriodID AND + stt.TimeClassID = 2 + WHERE + ba.Change <> 0 and + b.BudgetReallocationGUID = @BudgetReallocationGUID and + stt.DepartmentID is null and + ba.UnitTypeID = 145 and + b.Archived = 0 + GROUP BY + b.SourceDepartmentID, + b.SourceAccountID, + pp.PayPeriodID + + --insert to statistic temp table + INSERT INTO #StatisticSampledTempTable(DepartmentID, AccountID, PayPeriodID, TimeClassID, Units) + SELECT + DepartmentID, + AccountID, + PayPeriodID, + TimeClassID, + SUM(Units) + FROM #StatisticInsertTempTable + GROUP BY + DepartmentID, + AccountID, + PayPeriodID, + TimeClassID + END + + SET @iteration = @iteration + 1 + + FETCH NEXT + FROM BRA_cursor + INTO @BudgetReallocationGUID, + @date, + @BudgetReallocationType + END + + CLOSE BRA_cursor; + + DEALLOCATE BRA_cursor; + + IF @StatisticType = 2 + SELECT stat.* + FROM + #StatisticSampledTempTable stat + INNER JOIN [fw].[viewStatisticSecondaryConfiguration] V ON + V.AccountID = stat.AccountID AND + V.DepartmentID = stat.DepartmentID + ELSE IF @StatisticType = 1 + SELECT + stat.* + FROM + #StatisticSampledTempTable stat + INNER JOIN [fw].[viewStatisticPrimaryConfiguration] V ON + V.AccountID = stat.AccountID AND + V.DepartmentID = stat.DepartmentID + ELSE + SELECT stat.* + FROM #StatisticSampledTempTable stat + +-- Fill Charge Based Statistics Sampled Keys +IF @isPrMetricConfigurationOn = 1 +BEGIN + IF @FiscalYearID = 0 + BEGIN + TRUNCATE TABLE fw.FactChargeBasedStatisticsPayPeriodKeys + END + ELSE + BEGIN + DELETE F FROM fw.FactChargeBasedStatisticsPayPeriodKeys F + INNER JOIN #payperiods PP ON PP.val = F.PayPeriodID + END + + INSERT INTO fw.FactChargeBasedStatisticsPayPeriodKeys (DepartmentID, AccountID, PayPeriodID) + SELECT DISTINCT CB.DepartmentID, CB.AccountID, PP.val + FROM fw.FactChargeBasedStatistics CB + INNER JOIN fw.DimDate DT ON DT.DateID = CB.DateID + INNER JOIN fw.DimDepartment DEPT ON DEPT.DepartmentID = CB.DepartmentID + INNER JOIN #payperiods PP ON PP.PayCycleID = DEPT.PayCycleID AND DT.CalendarDateTime BETWEEN PP.PeriodStartCalendarDate and PP.PeriodEndCalendarDate + LEFT JOIN int.FactSharedImportDailyStatistics DS ON DS.DepartmentID = CB.DepartmentID AND DS.AccountID = CB.AccountID AND DS.DateID = CB.DateID AND DS.TimeClassID = 1 + LEFT JOIN int.FactStatisticsbyPayPeriod FS ON FS.DepartmentID = CB.DepartmentID AND FS.AccountID = CB.AccountID AND FS.PayPeriodID = PP.val AND FS.TimeClassID = 1 + LEFT JOIN #FDPSD FDPSD on FDPSD.DepartmentID = CB.DepartmentID + WHERE + CB.IsDeleted = 0 + AND CB.DepartmentID != 0 + AND PP.val != 0 + AND CB.Value != 0 + AND DS.RowID IS NULL + AND FS.RowID IS NULL + AND (DEPT.IsPR = 1 OR FDPSD.DepartmentID IS NOT NULL) +END + +IF OBJECT_ID('tempdb..#StatisticSampledTempTable') IS NOT NULL DROP TABLE #StatisticSampledTempTable +IF OBJECT_ID('tempdb..#departments') IS NOT NULL DROP TABLE #departments +IF OBJECT_ID('tempdb..#departmentsBudgetAllocations') IS NOT NULL DROP TABLE #departmentsBudgetAllocations +IF OBJECT_ID('tempdb..#FDPSD') IS NOT NULL DROP TABLE #FDPSD +IF OBJECT_ID('tempdb..#StatisticInsertTempTable') IS NOT NULL DROP TABLE #StatisticInsertTempTable +IF OBJECT_ID('tempdb..#payperiods') IS NOT NULL DROP TABLE #payperiods +IF OBJECT_ID('tempdb..#StatisticTempTableBackup') IS NOT NULL DROP TABLE #StatisticTempTableBackup +GO + + +--------------------------------------------- + +-- fw.procABBFlexingReconcilationSampling +CREATE PROCEDURE [fw].[procABBFlexingReconcilationSampling] + +AS +BEGIN + + BEGIN TRANSACTION + TRUNCATE TABLE [fw].[ABBFlexingReconciliationCostingData] + TRUNCATE TABLE [fw].[ABBBudgetedCostPerRVU] + COMMIT + + BEGIN TRANSACTION + INSERT INTO [fw].[ABBBudgetedCostPerRVU] + ([DepartmentID], [AccountID], [JobCodeID], [PayCodeID], [CostComponentID], [CostingConfigGuid], [VariableDirectUnitCostPerRVU], [TotalVariableDirectCost], [TotalCost]) + + SELECT + gl.DepartmentID + , OriginalAccountID as AccountID + , 0 as JobCodeID + , 0 as PayCodeID + , gl.CostComponentID + , cr.CostingConfigGuid + , SUM(gl.VariableDirectUnitCost)/SUM(ca.RVU) as VariableDirectUnitCostPerRVU + , SUM(gl.VariableDirectUnitCost * gl.Volume) as TotalVariableDirectCost + , SUM(gl.TotalCost) as TotalCost + FROM [dss].[FactCostingOutDetailGL] gl + INNER JOIN [dss].[CostingResult] cr on gl.CostingResultID = cr.CostingResultID + INNER JOIN [fp].[EntityGroupConfig] ec on cr.CostingConfigGuid = ec.CostingConfigGUID + INNER JOIN [dss].[ChargeAllocation] ca on + ca.CostingConfigGuid = cr.CostingConfigGUID + and ca.ChargeCodeID = gl.ChargeCodeID + and ca.DepartmentID = gl.DepartmentID + and ca.CostComponentID = gl.CostComponentID + and AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0 + WHERE + --[BL] need to only run this for the costing config specified on the system center MR page + gl.CostingResultID in (select max(cr2.CostingResultID) from [dss].[CostingResult] cr2 where cr2.CostingConfigGuid = '7f3c4d40-be55-4fde-88b5-93cdf8401090' and cr2.IsActivityBasedDetail = 1 and cr2.IsMarkedForDeletion = 0) + and gl.TimeClassID = ec.CostingConfigTimeClassID and gl.VariableDirectUnitCost<>0 + GROUP BY + gl.OriginalAccountID + , gl.DepartmentID + , gl.CostComponentID + , cr.CostingConfigGuid + + UNION ALL + + SELECT + pr.DepartmentID + , ISNULL(cw.AccountID,0) as AccountID + , pr.OriginalJobCodeID as JobCodeID + , pr.OriginalPayCodeID as PayCodeID + , pr.CostComponentID + , cr.CostingConfigGuid + , SUM(pr.VariableDirectUnitCost)/SUM(ca.RVU) as VariableDirectUnitCostPerRVU + , SUM(pr.VariableDirectUnitCost * pr.Volume) as TotalVariableDirectCost + , SUM(pr.TotalCost) as TotalCost + FROM [dss].[FactCostingOutDetailPayroll] pr + INNER JOIN [dss].[CostingResult] cr on pr.CostingResultID = cr.CostingResultID + INNER JOIN [fp].[EntityGroupConfig] ec on cr.CostingConfigGuid = ec.CostingConfigGUID + INNER JOIN [fw].[DimPayCode] pc on pr.OriginalPayCodeID=pc.PayCodeID + INNER JOIN [dss].[ChargeAllocation] ca on + ca.CostingConfigGuid = cr.CostingConfigGUID + and ca.ChargeCodeID = pr.ChargeCodeID + and ca.DepartmentID = pr.DepartmentID + and ca.CostComponentID = pr.CostComponentID + and AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0 + LEFT JOIN [clientob].[FactPayrollToAccountCrosswalk] cw on pr.OriginalJobCodeID = cw.JobCodeID AND pc.PayCodeGroupID = cw.PayCodeGroupID AND cw.UnitTypeID = 34 + WHERE + --[BL] need to only run this for the costing config specified on the system center MR page + pr.CostingResultID in (select max(cr2.CostingResultID) from [dss].[CostingResult] cr2 where cr2.CostingConfigGuid = '7f3c4d40-be55-4fde-88b5-93cdf8401090' and cr2.IsActivityBasedDetail = 1 and cr2.IsMarkedForDeletion = 0) + and pr.TimeClassID = ec.CostingConfigTimeClassID and pr.VariableDirectUnitCost<>0 + GROUP BY + cw.AccountID + , pr.OriginalJobCodeID + , pr.OriginalPayCodeID + , pr.DepartmentID + , pr.CostComponentID + , cr.CostingConfigGuid + + COMMIT + + DECLARE @DepartmentCursor CURSOR, + @DepartmentID INT, + @DepartmentName Nvarchar(200), + @TotalNumberDepts nvarchar(10), + @CurrentDepartment nvarchar(10), + @Message NvarChar(400), + @time char(8) + + SET @DepartmentCursor = CURSOR FOR (SELECT DISTINCT DepartmentID FROM (Select DepartmentID from [dss].[FactDepartmentChargeSummary] WHERE IsDeleted = 0 + UNION ALL + Select DepartmentID from [int].[FactCDM]) A + ) + SET @TotalNumberDepts = (SELECT COUNT(distinct DepartmentID) FROM (Select DepartmentID from [dss].[FactDepartmentChargeSummary] WHERE IsDeleted = 0 + UNION ALL + Select DepartmentID from [int].[FactCDM]) A + ) + SET @CurrentDepartment = 0 + OPEN @DepartmentCursor + FETCH NEXT FROM @DepartmentCursor + INTO @DepartmentID + + WHILE @@FETCH_STATUS = 0 + BEGIN + + SET @CurrentDepartment = @CurrentDepartment + 1 + SET @DepartmentName = (SELECT NAME FROM FW.DimDepartment WHERE DepartmentID=@DepartmentID) + Set @Message = 'Department: ' + @DepartmentName + ' ' + @CurrentDepartment + ' of ' + @TotalNumberDepts + SET @time= convert (varchar(30), getdate(), 8) + RAISERROR (@Message, 0, 1, @time) WITH NOWAIT + + BEGIN TRANSACTION + INSERT INTO [fw].[ABBFlexingReconciliationCostingData] + + SELECT + charge.CostingConfigGUID + , dept.EntityID + , Volume.DepartmentID AS OriginalDepartmentID + , ISNULL(cost.OriginalJobCodeID,0) AS OriginalJobCodeID + , ISNULL(cost.OriginalPayCodeID,0) AS OriginalPayCodeID + , ISNULL(cost.OriginalAccountID,0) AS OriginalAccountID + , Volume.ChargeCodeID + , Volume.FiscalYearID + , Volume.FiscalMonthID + , COALESCE(cost.CostComponentID, Charge.CostComponentID) AS CostComponentID + , CASE WHEN Volume.TimeClassID = 1 THEN ISNULL(cost.FixedDirectUnitCost,0) ELSE 0.0 END AS FixedDirectUnitCost + , CASE WHEN Volume.TimeClassID = 1 THEN ISNULL(cost.VariableDirectUnitCost,0) ELSE 0.0 END AS VariableDirectUnitCost + , CASE WHEN Volume.TimeClassID = 2 THEN ISNULL(cost.FixedDirectUnitCost,0) ELSE 0.0 END AS BudgetFixedDirectUnitCost + , CASE WHEN Volume.TimeClassID = 2 THEN ISNULL(cost.VariableDirectUnitCost,0) ELSE 0.0 END AS BudgetVariableDirectUnitCost + , CASE WHEN Volume.TimeClassID = 1 THEN volume.Volume ELSE 0.0 END AS ActualMonthlyVolume + , CASE WHEN Volume.TimeClassID = 2 THEN volume.Volume ELSE 0.0 END AS BudgetedMonthlyVolume + , ISNULL(charge.RVU, 0.0) as RVU + FROM + (SELECT fdcs.DepartmentID, fdcs.ChargeCodeID, fdcs.FiscalYearID, fdcs.TimeClassID, fdcs.FiscalMonthID, SUM(fdcs.Volume) AS Volume + FROM [dss].[FactDepartmentChargeSummary] fdcs + WHERE fdcs.IsDeleted = 0 and FiscalYearID=2017 --[BL] NEED TO UPDATE THIS JOIN TO ONLY INCL THE TARGET FISCAL YEAR + GROUP BY fdcs.DepartmentID, fdcs.ChargeCodeID, fdcs.FiscalYearID, fdcs.TimeClassID, fdcs.FiscalMonthID + UNION ALL + SELECT cdm.DepartmentID, cdm.ChargeCodeID, cdm.FiscalYearID, cdm.TimeClassID, cdm.FiscalMonthID, SUM(cdm.Value) as Volume + FROM [int].[FactCDM] cdm + WHERE cdm.UnitTypeID = 145 and TimeClassID = 2 and FiscalYearID=2017 --[BL] NEED TO UPDATE THIS JOIN TO ONLY INCL THE TARGET FISCAL YEAR + GROUP BY cdm.DepartmentID, cdm.ChargeCodeID, cdm.FiscalYearID, cdm.TimeClassID, cdm.FiscalMonthID + ) Volume + LEFT JOIN + (SELECT OriginalDepartmentID, CostingResultID, ChargeCodeID, FiscalYearID, TimeClassID, CostComponentID, OriginalAccountID, 0 as OriginalPayCodeID, 0 as OriginalJobCodeID, Volume, FixedDirectUnitCost, VariableDirectUnitCost FROM [dss].[FactCostingOutDetailGL] + UNION + SELECT OriginalDepartmentID, CostingResultID, ChargeCodeID, FiscalYearID, TimeClassID, CostComponentID, ISNULL(cw.AccountID,0.0) as OriginalAccountID, OriginalPayCodeID, OriginalJobCodeID, Volume, FixedDirectUnitCost, VariableDirectUnitCost + FROM [dss].[FactCostingOutDetailPayroll] p + INNER JOIN [fw].[DimPayCode] pc on p.OriginalPayCodeID=pc.PayCodeID + LEFT JOIN [clientob].[FactPayrollToAccountCrosswalk] cw on p.OriginalJobCodeID = cw.JobCodeID AND pc.PayCodeGroupID = cw.PayCodeGroupID AND cw.UnitTypeID = 34 + ) as cost + ON Volume.DepartmentID = cost.OriginalDepartmentID + AND Volume.ChargeCodeID = cost.ChargeCodeID + AND Volume.FiscalYearID = cost.FiscalYearID + AND Volume.TimeClassID = cost.TimeClassID + INNER JOIN [dss].[CostingResult] cr + ON cost.CostingResultID = cr.CostingResultID + INNER JOIN [fw].[DimDepartment] dept + ON dept.DepartmentID = Volume.DepartmentID + LEFT JOIN + (SELECT ca.DepartmentID, ca.ChargeCodeID, ca.CostComponentID, ca.CostingConfigGuid, ca.RVU + FROM [dss].[ChargeAllocation] ca + WHERE ca.AllocationType = 1 and ca.IsFixed = 0 and ca.IsIndirect = 0 and ca.RVU <> 0 + AND CostingConfigGuid='7f3c4d40-be55-4fde-88b5-93cdf8401090' + ) charge + ON Volume.DepartmentID = charge.DepartmentID + AND Volume.ChargeCodeID = charge.ChargeCodeID + AND cost.CostComponentID = charge.CostComponentID + AND cr.CostingConfigGuid = charge.CostingConfigGuid + WHERE cost.CostingResultID in (SELECT CostingResultID FROM (SELECT CostingConfigGuid, MAX(CostingResultID) as CostingResultID FROM [dss].[CostingResult] WHERE CostingConfigGuid='7f3c4d40-be55-4fde-88b5-93cdf8401090' and IsMarkedForDeletion = 0 AND IsActivityBasedDetail = 1 GROUP BY CostingConfigGuid) cr2) + AND (Volume.DepartmentID=@DepartmentID) + + COMMIT + + FETCH NEXT FROM @DepartmentCursor INTO @DepartmentID + END + + CLOSE @DepartmentCursor + DEALLOCATE @DepartmentCursor + END +GO + + +--------------------------------------------- + +-- fw.procABBMRTransferFlexedPayrollSampledMonthlyToFactGLSampled +CREATE PROC [fw].[procABBMRTransferFlexedPayrollSampledMonthlyToFactGLSampled] + @fiscalYearID int, + @CostingResultID int +AS +/* ************************************************************************************************************************ +** Author: BL/NL +** Create Date: 2016-08-05 +** Description: Runs GL flexing for MR +** Last Modified: 2016-08-05 +************************************************************************************************************************** +** Change History +************************************************************************************************************************** +** CID Date Author WI Description +** 1 2017-10-09 PA D-06466 Filter for ABB depts and IsDeleted +*************************************************************************************************************************/ + +DECLARE @higuid UNIQUEIDENTIFIER + +EXEC procLogScript 'Sampling Flexed Payroll Sample to GL Sample: See procABBMRTransferFlexedPayrollSampledMonthlytoFactGLSampled_NMC_CUSTOM_TEMP' , @higuid output + +SELECT DISTINCT DepartmentID +INTO #ABBDepts +FROM ( + SELECT DepartmentID FROM [dss].[FactCostingOutDetailGL] WHERE CostingResultID = @CostingResultID + UNION ALL + SELECT DepartmentID FROM [dss].[FactCostingOutDetailPayroll] WHERE CostingResultID = @CostingResultID) depts; + +SELECT + p.[DepartmentID] + , cw.[AccountID] + , p.[FiscalYearID] + , p.[FiscalMonthID] + , p.[TimeClassID] + , p.[IsDeleted] + , @higuid as [HistoryItemGUID] + , SUM(p.Hours) as [Units] + , SUM(p.HoursYTD) as [UnitsYTD] + , SUM(p.HoursPriorYear) as [UnitsPriorYear] + , SUM(p.HoursPriorYTD) as [UnitsPriorYTD] + , SUM(p.[Dollars]) as Dollars + , SUM(p.[DollarsYTD]) as DollarsYTD + , SUM(p.[DollarsPriorYear]) as DollarsPriorYear + , SUM(p.[DollarsPriorYTD]) as DollarsPriorYTD + , p.[TransactionID] +INTO #FlexPayroll +FROM [fw].[FactPayrollSampledMonthly] p +INNER JOIN [clientob].[FactPayrollToAccountCrosswalk] cw on p.JobCodeID = cw.JobCodeID AND p.PayCodeGroupID = cw.PayCodeGroupID AND cw.UnitTypeID = 34 +INNER JOIN [fw].[DimDepartment] dept on p.DepartmentID = dept.DepartmentID +INNER JOIN #ABBDepts abb ON p.DepartmentID = abb.DepartmentID +WHERE TimeClassID = 4 AND FiscalYearID = @fiscalYearID +AND cw.IsDeleted = 0 +GROUP BY + p.[DepartmentID] + , cw.[AccountID] + , p.[FiscalYearID] + , p.[FiscalMonthID] + , p.[TimeClassID] + , p.[IsDeleted] + , p.[TransactionID]; + +DELETE GL +FROM [fw].[FactGLSampled] GL + WHERE EXISTS + (SELECT 1 + FROM #FlexPayroll PR + WHERE GL.DepartmentID=PR.DepartmentID + AND GL.AccountID=PR.AccountID + AND GL.FiscalYearID=PR.FiscalYearID + AND GL.FiscalMonthID=PR.FiscalMonthID + AND GL.TimeClassID=PR.TimeClassID); + +INSERT INTO [fw].[FactGLSampled] +([DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], [TimeClassID], [IsDeleted], [HistoryItemGUID], [Units], [UnitsYTD], [UnitsPriorYear], [UnitsPriorYTD], [Dollars], [DollarsYTD], [DollarsPriorYear], [DollarsPriorYTD], [TransactionID]) +SELECT [DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], [TimeClassID], [IsDeleted], [HistoryItemGUID], [Units], [UnitsYTD], [UnitsPriorYear], [UnitsPriorYTD], [Dollars], [DollarsYTD], [DollarsPriorYear], [DollarsPriorYTD], [TransactionID] +FROM #FlexPayroll; + +DROP TABLE #FlexPayroll; +GO + + +--------------------------------------------- + +-- fw.procCopyFactGLBudgetToImport +CREATE PROCEDURE fw.procCopyFactGLBudgetToImport (@HistoryItemGUID uniqueidentifier) as +BEGIN +/************************************************************ +** Author: ipetriv +** Create Date: 2018-01-15 +** Description: Add procedure to calc EfficiencyFactor +** Last Modified: 2017-01-15 +** GM Release: 2018.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-01-15 IP B-18301 Created +*************************************************************/ + +DECLARE @FiscalYearId INT = ( + SELECT setting + FROM dbsetting + WHERE NAME = 'Current_GL_YearID' + ) + +IF OBJECT_ID('int.FactGLHistory', 'U') IS NOT NULL + DROP TABLE INT.FactGLHistory; + +SELECT RowID, + [DepartmentID], + [DepartmentCode], + [AccountID], + [AccountCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + [FiscalMonthID], + [FiscalMonthCode], + [Value], + [IsDeleted], + [HistoryItemGUID], + [Version], + [TransactionID], + getdate() AS BCP_DTTime +INTO INT.FactGLHistory +FROM INT.FactGL +WHERE FiscalYearID = @FiscalYearId + AND TimeClassID = 2 + +CREATE UNIQUE CLUSTERED INDEX IX_FactGLHistory ON [int].[FactGLHistory] ( + [FiscalMonthID] ASC, + [IsDeleted] ASC, + [FiscalYearID] ASC, + [TimeClassID] ASC, + [DepartmentID] ASC, + [AccountID] ASC, + [RowID] ASC + ) ON [PRIMARY] + +WHILE 1 = 1 +BEGIN + DELETE TOP (10000) iGL + FROM [int].FactGL iGL + INNER JOIN INT.FactGLHistory iGLH ON iGL.[FiscalMonthID] = iGLH.[FiscalMonthID] + AND iGL.[IsDeleted] = iGLH.[IsDeleted] + AND iGL.[FiscalYearID] = iGLH.[FiscalYearID] + AND iGL.[TimeClassID] = iGLH.[TimeClassID] + AND iGL.[DepartmentID] = iGLH.[DepartmentID] + AND iGL.[AccountID] = iGLH.[AccountID] + AND iGL.[RowID] = iGLH.[RowID] + + IF @@ROWCOUNT < 10000 + BREAK; +END + +INSERT INTO [int].FactGL ( + DepartmentID, + DepartmentCode, + AccountID, + AccountCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + FiscalMonthID, + FiscalMonthCode, + Value, + IsDeleted, + HistoryItemGUID, + TransactionID + ) +SELECT gl.DepartmentID, + dd.DepartmentCode, + gl.AccountID, + da.AccountCode, + gl.FiscalYearID, + gl.FiscalYearID AS FiscalYearCode, + gl.TimeClassID, + dtm.TimeClassCode, + gl.FiscalMonthID, + dfm.FiscalMonthCode, + sum(CASE + WHEN A.Inversion = - 1 + THEN GL.Dollars * - 1 + ELSE GL.Dollars + END) AS Value, + 0 IsDeleted, + @HistoryItemGUID AS HistoryItemGUID, + 0 AS TransactionID +FROM fw.FactGLSampled GL +INNER JOIN fw.DimAccount A ON A.AccountID = GL.AccountID +INNER JOIN fw.DimTimeClass dtm ON dtm.TimeClassID = gl.TimeClassID +INNER JOIN fw.DimDepartment dd ON dd.DepartmentID = gl.DepartmentID +INNER JOIN fw.DimAccount da ON da.AccountID = gl.AccountID +INNER JOIN fw.DimFiscalMonth dfm ON dfm.FiscalMonthID = gl.FiscalMonthID +WHERE gl.TimeClassID = 2 -- Data transferred will be the sampled budgeted data + AND FiscalYearID = @FiscalYearId + AND Dollars <> 0.0 +GROUP BY gl.DepartmentID, + dd.DepartmentCode, + gl.AccountID, + da.AccountCode, + gl.FiscalYearID, + gl.TimeClassID, + dtm.TimeClassCode, + gl.FiscalMonthID, + dfm.FiscalMonthCode +END +GO + + +--------------------------------------------- + +-- fw.procCopyFactPayrollDollarsToGLMonthly +CREATE PROCEDURE [fw].[procCopyFactPayrollDollarsToGLMonthly] +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 +** 2 2019-02-15 OV D-07848 In Management Reporting, salaries and wages metrics for fixed departments are flexing +** 3 2019-02-19 KF D-08138 MR Flexing: Flex GL values should be 0 for mapped accounts if there is no Payroll data +** 4 2019-03-19 OV D-08253 Used temp table for @DepartmentAccountVariabilityOverrides +** 5 2019-03-26 OV D-08253 Optimize procedure +*************************************************************/ +( + @FiscalYearID int = 0, + @PriorYearsCount int = 0, + @DepartmentAccountVariabilityOverrides [ob].[DepartmentAccountVariabilityOverride] READONLY +) +AS +BEGIN + +DECLARE @TimeClassID TINYINT = 4 --Flex +DECLARE @UnitTypeID TINYINT = 34 --Dollars +DECLARE @StartFiscalYear INT = @FiscalYearID - @PriorYearsCount +DECLARE @EndFiscalYear INT = @FiscalYearID + +IF @FiscalYearID = 0 +BEGIN + SELECT @StartFiscalYear = MIN(FiscalYearID) FROM ( + SELECT MIN(FiscalYearID) AS FiscalYearID FROM fw.FactPayrollSampledMonthly + UNION ALL + SELECT MIN(FiscalYearID) AS FiscalYearID FROM fw.FactGLSampled) S + + SELECT @EndFiscalYear = MAX(FiscalYearID) FROM ( + SELECT MAX(FiscalYearID) AS FiscalYearID FROM fw.FactPayrollSampledMonthly + UNION ALL + SELECT MAX(FiscalYearID) AS FiscalYearID FROM fw.FactGLSampled) S +END + +DECLARE @MappingMode INT +SELECT TOP 1 @MappingMode = CASE [PropertyXML].value('(/Properties//PayRollToGLLinkDollarsConfiguration/node())[1]', 'nvarchar(max)') + WHEN 'EachJobCode' THEN 1 + WHEN 'EachPayCodeGroup' THEN 2 + ELSE 0 END -- BothUnique or BothOverride +FROM SystemCenterStep WHERE GlobalID = 'PayrolltoGLLinkSelection' + +IF OBJECT_ID('tempdb..#department') IS NOT NULL DROP TABLE #department +IF OBJECT_ID('tempdb..#tempCrosswalk') IS NOT NULL DROP TABLE #tempCrosswalk +IF OBJECT_ID('tempdb..#DepAcc_P_GL') IS NOT NULL DROP TABLE #DepAcc_P_GL +IF OBJECT_ID('tempdb..#Source') IS NOT NULL drop table #Source +IF OBJECT_ID('tempdb..#FactGL_1') IS NOT NULL drop table #FactGL_1 +IF OBJECT_ID('tempdb..#FactGL_2 ') IS NOT NULL drop table #FactGL_2 +IF OBJECT_ID('tempdb..#Payroll_JC_PCG') IS NOT NULL drop table #Payroll_JC_PCG +IF OBJECT_ID('tempdb..#payroll') IS NOT NULL drop table #payroll + + +IF OBJECT_ID('tempdb..#DepartmentAccountVariabilityOverride') IS NOT NULL DROP TABLE #DepartmentAccountVariabilityOverride +CREATE TABLE #DepartmentAccountVariabilityOverride (AccountID int, DepartmentID int, Variability decimal(19,8)) + +INSERT INTO #DepartmentAccountVariabilityOverride (AccountID, DepartmentID, Variability) +select AccountID, DepartmentID, Variability FROM @DepartmentAccountVariabilityOverrides +---- +SELECT departmentID,AccountID +into #DepAcc_P_GL +FROM ( +select departmentID, AccountId +from fw.FactGLSampled +union +select DepartmentID, accountID +from fw.FactPayrollSampledMonthly +cross join clientob.FactPayrollToAccountCrosswalk c +) t + +----- +select d.DepartmentID,AccountID, isvariable +into #department +FROM #DepAcc_P_GL DepAcc_P_GL +inner join fw.DimDepartment d on DepAcc_P_GL.departmentID = d.departmentID +where d.IsMRPlan = 1 + +----- +SELECT aa.AccountID, cc.UnitTypeID, aa.Variability, FY.FiscalYearID, FM.FiscalMonthID, +CASE WHEN @MappingMode IN(0,1) then cc.JobCodeId else -10001 END AS JobCodeID, +CASE WHEN @MappingMode IN(0,2) then CC.payCodeGroupID else -10001 END AS PayCodeGroupID +into #tempCrosswalk +from clientob.FactPayrollToAccountCrosswalk cc +inner join fw.DimAccount aa on cc.AccountID = aa.AccountID + CROSS JOIN fw.DimFiscalYear FY + CROSS JOIN fw.DimFiscalMonth FM +where CC.UnitTypeID = @UnitTypeID and FY.FiscalYearID BETWEEN @StartFiscalYear AND @EndFiscalYear and FM.FiscalMonthID != 0 + +----- +select SUM(p.Dollars) as Dollars ,p.FiscalYearID, p.FiscalMonthID, +CASE WHEN @MappingMode IN(0,1) then JobCodeId else -10001 END AS JobCodeID, +CASE WHEN @MappingMode IN(0,2) then payCodeGroupID else -10001 END AS PayCodeGroupID, +DepartmentID +INTO #Payroll_JC_PCG +FROM fw.FactPayrollSampledMonthly P +WHERE P.TimeClassID = @TimeClassID + AND P.IsDeleted = 0 +GROUP BY p.FiscalYearID, p.FiscalMonthID, p.JobCodeID, p.PayCodeGroupID, p.DepartmentID + +----- +SELECT FactGL.FiscalYearID, FactGL.FiscalMonthId, FactGL.AccountID, FactGL.DepartmentID, FactGL.Dollars as Dollars +INTO #FactGL_1 +FROM fw.FactGLSampled FactGL +WHERE FactGL.TimeclassID = 20 AND FactGL.IsDeleted = 0 + +----- +select FactGl.DepartmentID, Cw.AccountID, cw.FiscalYearID, cw.FiscalMonthID, FactGL.Dollars,CW.Variability * D.IsVariable as Koef_var +INTO #FactGL_2 +from (SELECT distinct AccountId,FiscalYearID,FiscalMonthID,Variability FROM #tempCrosswalk) cw +INNER JOIN #FactGL_1 FactGL on + FactGL.FiscalYearID = CW.FiscalYearID + AND FactGL.FiscalMonthID = CW.FiscalMonthID + AND FactGL.AccountID = CW.AccountID + INNER JOIN fw.DimDepartment d on FactGL.departmentID = d.departmentID + +----- +SELECT DD.DepartmentID, X.AccountID, X.FiscalYearID, X.FiscalMonthID, X.Dollars, X.Variability * DD.IsVariable as Koef_var +INTO #payroll +FROM ( +select Cw.AccountID, cw.FiscalYearID, cw.FiscalMonthID, CW.Variability, SUM(ROUND(p.Dollars,6)) as Dollars, P.DepartmentID +from (SELECT distinct AccountId,JobCodeID,PayCodeGroupID,FiscalYearID,FiscalMonthID,Variability FROM #tempCrosswalk) cw +inner join #Payroll_JC_PCG P ON + P.FiscalYearID = CW.FiscalYearID + AND P.FiscalMonthID = CW.FiscalMonthID + AND CW.JobCodeID = P.JobCodeID + AND CW.PayCodeGroupID = P.PayCodeGroupID +GROUP BY Cw.AccountID, cw.FiscalYearID, cw.FiscalMonthID, cw.Variability, P.DepartmentID +) X +INNER JOIN #department dd on DD.AccountID = X.AccountID and X.DepartmentID = Dd.DepartmentID + +----- +SELECT ISNULL(GL.DepartmentID,p.DepartmentID) as DepartmentID, +ISNULL(GL.AccountId,p.AccountId) as AccountId, +ISNULL(GL.FiscalYearId,p.FiscalYearId) as FiscalYearId, +ISNULL(GL.FiscalMonthId,p.FiscalMonthId) as FiscalMonthId, +ISNULL(ISNULL(DAV.Variability,P.Koef_var) * P.Dollars, 0) + isnull((1-ISNULL(DAV.Variability,Gl.Koef_var)) *GL.Dollars,0) as Dollars +INTO #Source +FROM #FactGL_2 GL +FULL JOIN #payroll p on GL.AccountId = p.AccountId and GL.DepartmentID = p.DepartmentID and GL.FiscalYearId = p.FiscalYearId and GL.FiscalMonthId = p.FiscalMonthId +LEFT JOIN #DepartmentAccountVariabilityOverride DAV ON + ISNULL(GL.DepartmentID,p.DepartmentID) = DAV.DepartmentID + AND ISNULL(GL.AccountID,p.AccountId) = DAV.AccountID +---- +MERGE fw.FactGLSampled AS TARGET +USING #Source AS SOURCE ON + TARGET.DepartmentID = SOURCE.DepartmentID + AND TARGET.AccountID = SOURCE.AccountID + AND TARGET.FiscalYearID = SOURCE.FiscalYearID + AND TARGET.FiscalMonthID = SOURCE.FiscalMonthID + AND TARGET.TimeClassID = @TimeClassID + AND TARGET.IsDeleted = 0 +WHEN MATCHED AND TARGET.Dollars != SOURCE.Dollars THEN + UPDATE SET TARGET.Dollars = SOURCE.Dollars +WHEN NOT MATCHED BY TARGET THEN + INSERT (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Dollars) + VALUES (SOURCE.DepartmentID, SOURCE.AccountID, SOURCE.FiscalYearID, SOURCE.FiscalMonthID, @TimeClassID, SOURCE.Dollars); + +END +GO + + +--------------------------------------------- + +-- fw.procCopyFactPayrollHoursToStatisticsMonthly +CREATE PROCEDURE [fw].[procCopyFactPayrollHoursToStatisticsMonthly] +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 +** 2 2019-02-15 OV D-07848 In Management Reporting, salaries and wages metrics for fixed departments are flexing +** 3 2019-02-19 KF D-08138 MR Flexing: Flex GL values should be 0 for mapped accounts if there is no Payroll data +** 4 2019-03-19 OV D-08253 - used temp table for @DepartmentAccountVariabilityOverrides +** 5 2019-03-26 OV D-08253 - optimize proc +*************************************************************/ +( + @FiscalYearID int = 0, + @PriorYearsCount int = 0, + @DepartmentAccountVariabilityOverrides [ob].[DepartmentAccountVariabilityOverride] READONLY +) +AS +BEGIN +DECLARE @TimeClassID TINYINT = 4 --Flex +DECLARE @UnitTypeID TINYINT = 51 --Hours +DECLARE @StartFiscalYear INT = @FiscalYearID - @PriorYearsCount +DECLARE @EndFiscalYear INT = @FiscalYearID + +IF @FiscalYearID = 0 +BEGIN + SELECT @StartFiscalYear = MIN(FiscalYearID) FROM ( + SELECT MIN(FiscalYearID) AS FiscalYearID FROM fw.FactPayrollSampledMonthly + UNION ALL + SELECT MIN(FiscalYearID) AS FiscalYearID FROM fw.FactGLSampled) S + + SELECT @EndFiscalYear = MAX(FiscalYearID) FROM ( + SELECT MAX(FiscalYearID) AS FiscalYearID FROM fw.FactPayrollSampledMonthly + UNION ALL + SELECT MAX(FiscalYearID) AS FiscalYearID FROM fw.FactGLSampled) S +END + +DECLARE @MappingMode INT +SELECT TOP 1 @MappingMode = CASE [PropertyXML].value('(/Properties//PayRollToGLLinkHoursConfiguration/node())[1]', 'nvarchar(max)') + WHEN 'EachJobCode' THEN 1 + WHEN 'EachPayCodeGroup' THEN 2 + ELSE 0 END -- BothUnique or BothOverride +FROM SystemCenterStep WHERE GlobalID = 'PayrolltoGLLinkSelection' + +IF OBJECT_ID('tempdb..#department') IS NOT NULL DROP TABLE #department +IF OBJECT_ID('tempdb..#tempCrosswalk') IS NOT NULL DROP TABLE #tempCrosswalk +IF OBJECT_ID('tempdb..#DepAcc_P_Stat') IS NOT NULL DROP TABLE #DepAcc_P_Stat +IF OBJECT_ID('tempdb..#Source') IS NOT NULL drop table #Source +IF OBJECT_ID('tempdb..#Stat_1') IS NOT NULL drop table #Stat_1 +IF OBJECT_ID('tempdb..#Stat_2 ') IS NOT NULL drop table #Stat_2 +IF OBJECT_ID('tempdb..#Payroll_JC_PCG') IS NOT NULL drop table #Payroll_JC_PCG +IF OBJECT_ID('tempdb..#payroll') IS NOT NULL drop table #payroll + +IF OBJECT_ID('tempdb..#DepartmentAccountVariabilityOverride') IS NOT NULL DROP TABLE #DepartmentAccountVariabilityOverride +CREATE TABLE #DepartmentAccountVariabilityOverride (AccountID int, DepartmentID int, Variability decimal(19,8)) + +INSERT INTO #DepartmentAccountVariabilityOverride (AccountID, DepartmentID, Variability) +select AccountID, DepartmentID, Variability FROM @DepartmentAccountVariabilityOverrides +---- +SELECT departmentID,AccountID +into #DepAcc_P_Stat +FROM ( +select departmentID, AccountId +from fw.FactStatisticSampledMonthly +union +select DepartmentID, accountID +from fw.FactPayrollSampledMonthly +cross join clientob.FactPayrollToAccountCrosswalk c +) t + +----- +select d.DepartmentID, DepAcc_P_Stat.AccountID, d.isvariable +into #department +FROM #DepAcc_P_Stat DepAcc_P_Stat +inner join fw.DimDepartment d on DepAcc_P_Stat.departmentID = d.departmentID +where d.IsMRPlan = 1 + +----- +SELECT aa.AccountID, UnitTypeID, aa.Variability, FY.FiscalYearID, FM.FiscalMonthID, +CASE WHEN @MappingMode IN(0,1) then cc.JobCodeId else -10001 END AS JobCodeID, +CASE WHEN @MappingMode IN(0,2) then CC.payCodeGroupID else -10001 END AS PayCodeGroupID +into #tempCrosswalk +from clientob.FactPayrollToAccountCrosswalk cc +inner join fw.DimAccount aa on cc.AccountID = aa.AccountID + CROSS JOIN fw.DimFiscalYear FY + CROSS JOIN fw.DimFiscalMonth FM +where CC.UnitTypeID = @UnitTypeID and FY.FiscalYearID BETWEEN @StartFiscalYear AND @EndFiscalYear and FM.FiscalMonthID != 0 + +----- +select SUM(p.Hours) as Hours, p.FiscalYearID, p.FiscalMonthID, +CASE WHEN @MappingMode IN(0,1) then p.JobCodeId else -10001 END AS JobCodeID, +CASE WHEN @MappingMode IN(0,2) then p.payCodeGroupID else -10001 END AS PayCodeGroupID, +p.DepartmentID +INTO #Payroll_JC_PCG +FROM fw.FactPayrollSampledMonthly P +WHERE P.TimeClassID = @TimeClassID + AND P.IsDeleted = 0 +GROUP BY FiscalYearID,FiscalMonthID,JobCodeID,PayCodeGroupID, DepartmentID +----- +SELECT Stat.FiscalYearID, Stat.FiscalMonthId, Stat.AccountID, Stat.DepartmentID, Stat.Amount as Hours +INTO #Stat_1 +FROM fw.FactStatisticSampledMonthly Stat +WHERE Stat.TimeclassID = 20 AND Stat.IsDeleted = 0 + +----- +select Stat.DepartmentID, Cw.AccountID, cw.FiscalYearID, cw.FiscalMonthID, Hours, CW.Variability * D.IsVariable as Koef_var +INTO #Stat_2 +from (SELECT distinct AccountId,FiscalYearID,FiscalMonthID,Variability FROM #tempCrosswalk) cw +INNER JOIN #Stat_1 Stat on + Stat.FiscalYearID = CW.FiscalYearID + AND Stat.FiscalMonthID = CW.FiscalMonthID + AND Stat.AccountID = CW.AccountID + INNER JOIN fw.DimDepartment d on Stat.departmentID = d.departmentID + ----- +SELECT DD.DepartmentID, X.AccountID, X.FiscalYearID, X.FiscalMonthID, X.Hours, X.Variability * DD.IsVariable as Koef_var +INTO #payroll +FROM ( +select Cw.AccountID, cw.FiscalYearID, cw.FiscalMonthID, CW.Variability, SUM(ROUND(P.Hours,6)) as Hours, P.DepartmentID +from (SELECT distinct AccountId,JobCodeID,PayCodeGroupID,FiscalYearID,FiscalMonthID,Variability FROM #tempCrosswalk) cw +inner join #Payroll_JC_PCG P ON + P.FiscalYearID = CW.FiscalYearID + AND P.FiscalMonthID = CW.FiscalMonthID + AND CW.JobCodeID = P.JobCodeID + AND CW.PayCodeGroupID = P.PayCodeGroupID +GROUP BY Cw.AccountID, cw.FiscalYearID, cw.FiscalMonthID, CW.Variability, P.DepartmentID +) X +INNER JOIN #department dd on DD.AccountID = X.AccountID and dd.DepartmentID = X.DepartmentID + +----- +SELECT ISNULL(Stat.DepartmentID,p.DepartmentID) as DepartmentID, +ISNULL(Stat.AccountId,p.AccountId) as AccountId, +ISNULL(Stat.FiscalYearId,p.FiscalYearId) as FiscalYearId, +ISNULL(Stat.FiscalMonthId,p.FiscalMonthId) as FiscalMonthId, +ISNULL(ISNULL(DAV.Variability,p.Koef_var) * P.Hours, 0) + isnull((1-ISNULL(DAV.Variability,Stat.Koef_var)) *Stat.Hours,0) as Hours +INTO #Source +FROM #Stat_2 Stat +FULL JOIN #payroll p on Stat.AccountId = p.AccountId and Stat.DepartmentID = p.DepartmentID and Stat.FiscalYearId = p.FiscalYearId and Stat.FiscalMonthId = p.FiscalMonthId +LEFT JOIN #DepartmentAccountVariabilityOverride DAV ON + ISNULL(Stat.DepartmentID,p.DepartmentID) = DAV.DepartmentID + AND ISNULL(Stat.AccountID,p.AccountId) = DAV.AccountID + +---- +MERGE fw.FactStatisticSampledMonthly AS TARGET +USING #Source AS SOURCE ON + TARGET.DepartmentID = SOURCE.DepartmentID + AND TARGET.AccountID = SOURCE.AccountID + AND TARGET.FiscalYearID = SOURCE.FiscalYearID + AND TARGET.FiscalMonthID = SOURCE.FiscalMonthID + AND TARGET.TimeClassID = @TimeClassID + AND TARGET.IsDeleted = 0 +WHEN MATCHED AND TARGET.Amount != SOURCE.Hours THEN + UPDATE SET TARGET.Amount = SOURCE.Hours +WHEN NOT MATCHED BY TARGET THEN + INSERT (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Amount) + VALUES (SOURCE.DepartmentID, SOURCE.AccountID, SOURCE.FiscalYearID, SOURCE.FiscalMonthID, @TimeClassID, SOURCE.Hours); + + +END +GO + + +--------------------------------------------- + +-- fw.procCopyFactStaffingBudgetToImport +CREATE PROCEDURE fw.procCopyFactStaffingBudgetToImport (@HistoryItemGUID uniqueidentifier) +AS +BEGIN +/************************************************************ +** Author: ipetriv +** Create Date: 2018-01-15 +** Description: Add procedure to calc EfficiencyFactor +** Last Modified: 2017-01-15 +** GM Release: 2018.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-01-15 IP B-18301 Created +*************************************************************/ + DECLARE @FiscalYearId INT = ( + SELECT setting + FROM dbsetting + WHERE NAME = 'Current_GL_YearID' + ) + + IF OBJECT_ID('int.FactStaffingHistory', 'U') IS NOT NULL + DROP TABLE INT.FactStaffingHistory; + + SELECT RowID, + DepartmentID, + DepartmentCode, + JobCodeID, + JobCode, + EmployeeID, + Employeecode, + PayCodeID, + PayCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + UnitTypeID, + UnitType, + FiscalMonthID, + FiscalMonthCode, + Value, + IsDeleted, + HistoryItemGUID, + Version, + TransactionID, + getdate() AS BCP_DTTime + INTO INT.FactStaffingHistory + FROM INT.FactStaffing + WHERE FiscalYearID = @FiscalYearId + AND TimeClassID = 2 + + CREATE UNIQUE CLUSTERED INDEX IX_FactStaffingHistory ON [int].[FactStaffingHistory] ( + [FiscalMonthID] ASC, + [IsDeleted] ASC, + [FiscalYearID] ASC, + [TimeClassID] ASC, + [DepartmentID] ASC, + [JobCodeID] ASC, + [RowID] ASC + ) ON [PRIMARY] + + WHILE 1 = 1 + BEGIN + DELETE TOP (10000) iST + FROM [int].FactStaffing iST + INNER JOIN INT.FactStaffingHistory iSTH ON iST.[FiscalMonthID] = iSTH.[FiscalMonthID] + AND iST.[IsDeleted] = iSTH.[IsDeleted] + AND iST.[FiscalYearID] = iSTH.[FiscalYearID] + AND iST.[TimeClassID] = iSTH.[TimeClassID] + AND iST.[DepartmentID] = iSTH.[DepartmentID] + AND iST.[JobCodeID] = iSTH.[JobCodeID] + AND iST.[RowID] = iSTH.[RowID] + + IF @@ROWCOUNT < 10000 + BREAK; + END + + INSERT INTO [int].FactStaffing ( + DepartmentID, + DepartmentCode, + JobCodeID, + JobCode, + EmployeeID, + Employeecode, + PayCodeID, + PayCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + UnitTypeID, + UnitType, + FiscalMonthID, + FiscalMonthCode, + Value, + IsDeleted, + HistoryItemGUID, + TransactionID + ) + SELECT PR.DepartmentID, + dd.DepartmentCode, + pr.JobCodeID, + djc.JobCode, + pr.EmployeeID, + de.Code AS Employeecode, + pr.PayCodeID, + dpc.PayCode, + pr.FiscalYearID, + FiscalYearID AS FiscalYearCode, + pr.TimeClassID, + dtm.TimeClassCode, + UnitTypeID, + UnitType, + pr.FiscalMonthID, + dfm.FiscalMonthCode, + sum(Value), + 0 AS IsDeleted, + @HistoryItemGUID AS HistoryItemGUID, + 0 AS TransactionID + FROM ( + SELECT DepartmentID, + JobCodeID, + EmployeeID, + PayCodeID, + FiscalYearID, + TimeClassID, + CASE + WHEN UnitType = 'Dollars' + THEN 34 + WHEN UnitType = 'Hours' + THEN 51 + ELSE 0 + END AS UnitTypeID, + UnitType, + FiscalMonthID, + Value + FROM [fw].[FactPayrollSampledMonthlyDetailed] + UNPIVOT(Value FOR UnitType IN ( + Dollars, + Hours + )) AS unpvt + WHERE Value <> 0 + AND TimeClassID = 2 -- Data transferred will be the sampled budgeted data + AND FiscalYearID = @FiscalYearID + ) PR + INNER JOIN fw.DimTimeClass dtm ON dtm.TimeClassID = PR.TimeClassID + INNER JOIN fw.DimDepartment dd ON dd.DepartmentID = PR.DepartmentID + INNER JOIN fw.DimJobCode djc ON djc.JobCodeID = PR.JobCodeID + INNER JOIN fw.DimPayCode dpc ON dpc.PayCodeID = PR.PayCodeID + INNER JOIN fw.DimEmployee de ON de.EmployeeID = PR.EmployeeID + INNER JOIN fw.DimFiscalMonth dfm ON dfm.FiscalMonthID = PR.FiscalMonthID + GROUP BY PR.DepartmentID, + dd.DepartmentCode, + pr.JobCodeID, + djc.JobCode, + pr.EmployeeID, + de.code, + pr.PayCodeID, + dpc.PayCode, + pr.FiscalYearID, + pr.TimeClassID, + dtm.TimeClassCode, + UnitTypeID, + UnitType, + pr.FiscalMonthID, + dfm.FiscalMonthCode +END +GO + + +--------------------------------------------- + +-- fw.procCopyFactStatisticBudgetToImport +/************************************************************ +** Author: ipetriv +** Create Date: 2018-01-15 +** Description: Add procedure to calc EfficiencyFactor +** Last Modified: 2017-01-15 +** GM Release: 2018.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-01-15 IP B-18301 Created +** 2 2018-08-23 OV D-07498 Removed inversion logic +*************************************************************/ +CREATE PROCEDURE [fw].[procCopyFactStatisticBudgetToImport] (@HistoryItemGUID uniqueidentifier) as +BEGIN +DECLARE @FiscalYearId INT = ( + SELECT setting + FROM dbsetting + WHERE NAME = 'Current_GL_YearID' + ) + +IF OBJECT_ID('int.FactStatisticHistory', 'U') IS NOT NULL + DROP TABLE INT.FactStatisticHistory; + +SELECT RowID, + [DepartmentID], + [DepartmentCode], + [AccountID], + [AccountCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + [FiscalMonthID], + [FiscalMonthCode], + [Value], + [IsDeleted], + [HistoryItemGUID], + [Version], + [TransactionID], + getdate() AS BCP_DTTime +INTO INT.FactStatisticHistory +FROM INT.FactStatistic +WHERE FiscalYearID = @FiscalYearId + AND TimeClassID = 2 + +CREATE UNIQUE CLUSTERED INDEX IX_FactStatisticHistory ON [int].[FactStatisticHistory] ( + [FiscalMonthID] ASC, + [IsDeleted] ASC, + [FiscalYearID] ASC, + [TimeClassID] ASC, + [DepartmentID] ASC, + [AccountID] ASC, + [RowID] ASC + ) ON [PRIMARY] + +WHILE 1 = 1 +BEGIN + DELETE TOP (10000) iST + FROM [int].FactStatistic iST + INNER JOIN INT.FactStatisticHistory iSTH ON iST.[FiscalMonthID] = iSTH.[FiscalMonthID] + AND iST.[IsDeleted] = iSTH.[IsDeleted] + AND iST.[FiscalYearID] = iSTH.[FiscalYearID] + AND iST.[TimeClassID] = iSTH.[TimeClassID] + AND iST.[DepartmentID] = iSTH.[DepartmentID] + AND iST.[AccountID] = iSTH.[AccountID] + AND iST.[RowID] = iSTH.[RowID] + + IF @@ROWCOUNT < 10000 + BREAK; +END + +INSERT INTO [int].FactStatistic ( + DepartmentID, + DepartmentCode, + AccountID, + AccountCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + FiscalMonthID, + FiscalMonthCode, + Value, + IsDeleted, + HistoryItemGUID, + TransactionID + ) +SELECT ST.DepartmentID, + dd.DepartmentCode, + ST.AccountID, + da.AccountCode, + ST.FiscalYearID, + ST.FiscalYearID AS FiscalYearCode, + ST.TimeClassID, + dtm.TimeClassCode, + ST.FiscalMonthID, + dfm.FiscalMonthCode, + sum(ST.Amount) AS Value, + 0 IsDeleted, + @HistoryItemGUID AS HistoryItemGUID, + 0 AS TransactionID +FROM fw.FactStatisticSampledMonthly ST +INNER JOIN fw.DimAccount A ON A.AccountID = ST.AccountID +INNER JOIN fw.DimTimeClass dtm ON dtm.TimeClassID = ST.TimeClassID +INNER JOIN fw.DimDepartment dd ON dd.DepartmentID = ST.DepartmentID +INNER JOIN fw.DimAccount da ON da.AccountID = ST.AccountID +INNER JOIN fw.DimFiscalMonth dfm ON dfm.FiscalMonthID = ST.FiscalMonthID +WHERE ST.TimeClassID = 2 -- Data transferred will be the sampled budgeted data + AND FiscalYearID = @FiscalYearId + AND Amount <> 0.0 +GROUP BY ST.DepartmentID, + dd.DepartmentCode, + ST.AccountID, + da.AccountCode, + ST.FiscalYearID, + ST.TimeClassID, + dtm.TimeClassCode, + ST.FiscalMonthID, + dfm.FiscalMonthCode +END +GO + + +--------------------------------------------- + +-- fw.procCopySystemGeneratedStatistics +CREATE PROC fw.procCopySystemGeneratedStatistics + @departmentIds nvarchar(MAX) = NULL +AS +BEGIN + SET NOCOUNT ON + + DROP TABLE IF EXISTS #departments + + SELECT val AS DepartmentId + INTO #departments + FROM ConvertCSValuesToTable(@departmentIds, ',') + + DECLARE + @startRowId bigint, + @maxRowId bigint, + @endRowId bigint + + IF (@departmentIds IS NULL) + BEGIN + TRUNCATE TABLE fw.FactSystemGeneratedStatistics + + SELECT @startRowId = MIN(RowId), @maxRowId = MAX(RowId) + FROM fw.FactChargeBasedStatistics + + WHILE (@startRowId <= @maxRowId) + BEGIN + SELECT @endRowId = MAX(d.RowId) + FROM (SELECT TOP 1000000 RowId + FROM fw.FactChargeBasedStatistics + WHERE RowId >= @startRowId + ORDER BY RowID) as d + + INSERT INTO fw.FactSystemGeneratedStatistics (AccountID, DepartmentID, DateID, Value) + SELECT s.AccountID, s.DepartmentID, s.DateID, s.Value + FROM fw.FactChargeBasedStatistics s + WHERE s.RowId >= @startRowId + AND s.RowId <= @endRowId + + SELECT @startRowId = MIN(d.RowId) + FROM fw.FactChargeBasedStatistics d + WHERE RowId > @endRowId + END + END + ELSE + BEGIN + DELETE + FROM fw.FactSystemGeneratedStatistics + WHERE DepartmentID IN (SELECT DepartmentId FROM #departments) + + INSERT INTO fw.FactSystemGeneratedStatistics (AccountID, DepartmentID, DateID, Value) + SELECT s.AccountID, s.DepartmentID, s.DateID, s.Value + FROM fw.FactChargeBasedStatistics s + JOIN #departments d + ON s.DepartmentID = d.DepartmentID + END + +END +GO + + +--------------------------------------------- + +-- fw.procCopySystemGeneratedStatisticsMonthly +CREATE PROC fw.procCopySystemGeneratedStatisticsMonthly + @fiscalYearId smallint = 0 +AS +BEGIN + SET NOCOUNT ON + + IF (@fiscalYearID = 0) + BEGIN + TRUNCATE TABLE fw.FactSystemGeneratedStatisticsMonthly + + INSERT INTO fw.FactSystemGeneratedStatisticsMonthly (AccountID, DepartmentID, FiscalYearID, FiscalMonthID, Value) + SELECT s.AccountID, s.DepartmentID, s.FiscalYearID, s.FiscalMonthID, s.Value + FROM fw.FactChargeBasedStatisticsMonthly s + END + ELSE + BEGIN + WHILE EXISTS(SELECT NULL FROM fw.FactSystemGeneratedStatisticsMonthly (nolock) WHERE FiscalYearID = @fiscalYearID) + BEGIN + DELETE TOP (1000000) fw.FactSystemGeneratedStatisticsMonthly + WHERE FiscalYearID = @fiscalYearID + END + + INSERT INTO fw.FactSystemGeneratedStatisticsMonthly (AccountID, DepartmentID, FiscalYearID, FiscalMonthID, Value) + SELECT s.AccountID, s.DepartmentID, s.FiscalYearID, s.FiscalMonthID, s.Value + FROM fw.FactChargeBasedStatisticsMonthly s + WHERE s.FiscalYearID = @fiscalYearId + END +END +GO + + +--------------------------------------------- + +-- fw.procCreateCapandOBMissingRoles +create proc fw.procCreateCapandOBMissingRoles as + + --Check for Capital Management Permission Set + if (select COUNT(*) from S3PermissionSet where Name='Capital Management')=1 + begin + --Check for access - Read allow in Capital Management Permission Set + if(select COUNT(*) from S3Permission where PermissionSetID=(select PermissionSetID from S3PermissionSet where Name='Capital Management') and RoleID = (Select RoleID from UserRole where Name='Access - Read Allow'))=0 + begin + insert into S3Permission (PermissionSetID,RoleID,Weight,ReadValue) + select + (select PermissionSetID from S3PermissionSet where Name='Capital Management'), + RoleID, + 0 as weight, + 1 as ReadValue + from + UserRole + where + Name='Access - Read Allow' + end + + --Check for access - Write allow in Capital Management Permission Set + if(select COUNT(*) from S3Permission where PermissionSetID=(select PermissionSetID from S3PermissionSet where Name='Capital Management') and RoleID = (Select RoleID from UserRole where Name='Access - Write Allow'))=0 + begin + insert into S3Permission (PermissionSetID,RoleID,Weight,ReadValue,WriteValue) + select + (select PermissionSetID from S3PermissionSet where Name='Capital Management'), + RoleID, + 0 as weight, + 1 as ReadValue, + 1 as WriteValue + from + UserRole + where + Name='Access - Write Allow' + end + + end + + --Check for Operating Budgeting Permission Set + if (select COUNT(*) from S3PermissionSet where Name='Operating Budgeting')=1 + begin + --Check for access - Read allow in Capital Management Permission Set + if(select COUNT(*) from S3Permission where PermissionSetID=(select PermissionSetID from S3PermissionSet where Name='Operating Budgeting') and RoleID = (Select RoleID from UserRole where Name='Access - Read Allow'))=0 + begin + insert into S3Permission (PermissionSetID,RoleID,Weight,ReadValue) + select + (select PermissionSetID from S3PermissionSet where Name='Operating Budgeting'), + RoleID, + 0 as weight, + 1 as ReadValue + from + UserRole + where + Name='Access - Read Allow' + end + + --Check for access - Write allow in Capital Management Permission Set + if(select COUNT(*) from S3Permission where PermissionSetID=(select PermissionSetID from S3PermissionSet where Name='Operating Budgeting') and RoleID = (Select RoleID from UserRole where Name='Access - Write Allow'))=0 + begin + insert into S3Permission (PermissionSetID,RoleID,Weight,ReadValue,WriteValue) + select + (select PermissionSetID from S3PermissionSet where Name='Operating Budgeting'), + RoleID, + 0 as weight, + 1 as ReadValue, + 1 as WriteValue + from + UserRole + where + Name='Access - Write Allow' + end + + end +GO + + +--------------------------------------------- + +-- fw.procCreateUserProfile +Create proc fw.procCreateUserProfile + @username nvarchar(64) + ,@NameLast nvarchar(64) + ,@NameFirst nvarchar(64) + ,@EmailAddress nvarchar(450) + +as + + insert into UserProfile(UserName,NameFirst,NameLast,EmailAddress) + values(@username,@NameFirst,@NameLast,@EmailAddress) +GO + + +--------------------------------------------- + +-- fw.procDeleteDimensionData +/***************************************************************** +****** Author: unknown +****** Create Date: Unknown +****** Description: Deletes all FW dimensions that are specified by the client, used only for GM releases - NEVER RUN ON CLIENT DATABASES +****** Last Modified: 2022-03-22 +****** GM Release: 2022.22 +****** *********************************************************** +****** Change History +****** *********************************************************** +****** CID Date Author WI Description +****** 1 2013-10-02 akk 64597 Adding new dimensions +****** 2 2014-02-20 akk D-01398 Adding delete from scorefillin +****** 3 2014-06-13 akk D-01874 Adding payor dimension +****** 4 2016-03-22 akk Deleting additional service lines +****** 5 2017-09-07 gjf D-06351 Clean up security +****** 6 2018-06-19 jbm Changing DimAccount Delete +****** 7 2020-05-13 yxr B-26923 Adding DayType dimension +****** 8 2022-03-22 ljc JAZZ-37520 Adding post delete insert of Standard Codes into DayType dimension and definition reformat +*****************************************************************/ + +CREATE + + PROCEDURE [fw].[procDeleteDimensionData] + AS + BEGIN + --------- SET NOCOUNT ON added to prevent extra result sets from + --------- interfering with SELECT statements. + SET NOCOUNT ON; + + DECLARE @nextid int; + SELECT @nextid = 0; + + WHILE EXISTS ( SELECT TOP 1 1 FROM [fw].[DimAccount] WHERE [AccountID] != 0 ) + BEGIN + DELETE TOP (1000) + FROM [fw].[DimAccount] + WHERE [AccountID] != 0; + END; + + DBCC CHECKIDENT ('[fw].[DimAccount]', RESEED, @nextid); + + DELETE + FROM [fw].[DimDepartment] + WHERE [DepartmentID] != 0; + + DBCC CHECKIDENT ('[fw].[DimDepartment]', RESEED, @nextid); + + DELETE + FROM [fw].[DimEmployee] + WHERE [EmployeeID] != 0; + + DBCC CHECKIDENT ('[fw].[DimEmployee]', RESEED, @nextid); + + DELETE + FROM [fw].[DimDepartmentRollup6] + WHERE [DepartmentRollup6ID] != 0; + + DBCC CHECKIDENT ('[fw].[DimDepartmentRollup6]', RESEED, @nextid); + + DELETE + FROM [fw].[DimDepartmentRollup5] + WHERE [DepartmentRollup5ID] != 0; + + DBCC CHECKIDENT ('[fw].[DimDepartmentRollup5]', RESEED, @nextid); + + DELETE + FROM [fw].[DimDepartmentRollup4] + WHERE [DepartmentRollup4ID] != 0; + + DBCC CHECKIDENT ('[fw].[DimDepartmentRollup4]', RESEED, @nextid); + + DELETE + FROM [fw].[DimDepartmentRollup3] + WHERE [DepartmentRollup3ID] != 0; + + DBCC CHECKIDENT ('[fw].[DimDepartmentRollup3]', RESEED, @nextid); + + DELETE + FROM [fw].[DimDepartmentRollup2] + WHERE [DepartmentRollup2ID] != 0; + + DBCC CHECKIDENT ('[fw].[DimDepartmentRollup2]', RESEED, @nextid); + + DELETE + FROM [fw].[DimDepartmentRollup1] + WHERE [DepartmentRollup1ID] != 0; + + DBCC CHECKIDENT ('[fw].[DimDepartmentRollup1]', RESEED, @nextid); + + DELETE + FROM [fw].[DimEntity] + WHERE [EntityID] != 0; + + DBCC CHECKIDENT ('[fw].[DimEntity]', RESEED, @nextid); + + DELETE + FROM [fw].[DimSystem] + WHERE [SystemID] != 0; + + DBCC CHECKIDENT ('[fw].[DimSystem]', RESEED, @nextid); + + DELETE + FROM [fw].[DimJobCode] + WHERE [JobCodeID] != 0; + + DBCC CHECKIDENT ('[fw].[DimJobCode]', RESEED, @nextid); + + DELETE + FROM [fw].[DimPayCode] + WHERE [PayCodeID] != 0; + + DBCC CHECKIDENT ('[fw].[DimPayCode]', RESEED, @nextid); + + DELETE + FROM [fw].[DimChargeCode] + WHERE [ChargeCodeID] != 0; + + DBCC CHECKIDENT ('[fw].[DimChargeCode]', RESEED, @nextid); + + DELETE + FROM [fw].[DimPatientType] + WHERE [PatientTypeID] > 4; + + DBCC CHECKIDENT ('[fw].[DimPatientType]', RESEED, 4); + + --------- BEGIN CID 7 + DELETE + FROM [fw].[DimDayType] + WHERE [DayTypeID] > 1; + + DBCC CHECKIDENT ('[fw].[DimDayType]', RESEED, 1); + --------- END CID 7 + + --------- BEGIN CID 8 + INSERT INTO [fw].[DimDayType] ([DayTypeCode], [PrecedentOrder]) + SELECT --* + DISTINCT [Rollup], + CASE + WHEN [Rollup] = 'Observation' THEN 50 + ELSE DENSE_RANK() OVER (ORDER BY [Rollup] ASC) + END AS [PrecedentOrder] + FROM [dss].[DimUBRevenueCode] + WHERE [CostDriver] = 'LOS'; + --------- END CID 8 + + + --------- BEGIN CID 1 + DELETE + FROM [fw].[DimModelingServiceLine] + WHERE [ModelingServiceLineID] != 0; + + DBCC CHECKIDENT ('[fw].[DimModelingServiceLine]', RESEED, @nextid); + + DELETE + FROM [fw].[DimPatientReimbursementGroup] + WHERE [PatientReimbursementGroupID] != 0; + + DBCC CHECKIDENT ('[fw].[DimPatientReimbursementGroup]', RESEED, @nextid); + + DELETE + FROM [fw].[DimServiceLine] + WHERE [ServiceLineID] != 0; + + DBCC CHECKIDENT ('[fw].[DimServiceLine]', RESEED, @nextid); + + DELETE + FROM [fw].[DimServiceLineRollup] + WHERE [ServiceLineRollupID] != 0; + + DBCC CHECKIDENT ('[fw].[DimServiceLineRollup]', RESEED, @nextid); + + --------- BEGIN CID 4 + DELETE + FROM [dbo].[RuleSet] + WHERE [Category] IN + ( SELECT [RuleSetCategory] + FROM [dss].[ServiceLineDefinition] + WHERE [DimensionGUID] != '074b4b22-9824-40f5-aa2a-a7b32631e8a2' ); + + DELETE + FROM [fw].[DimServiceLine2] + WHERE [ServiceLine2ID] != 0; + + DBCC CHECKIDENT ('[fw].[DimServiceLine2]', RESEED, @nextid); + + DELETE + FROM [fw].[DimServiceLine3] + WHERE [ServiceLine3ID] != 0; + + DBCC CHECKIDENT ('[fw].[DimServiceLine3]', RESEED, @nextid); + + DELETE + FROM [fw].[DimServiceLine4] + WHERE [ServiceLine4ID] != 0; + + DBCC CHECKIDENT ('[fw].[DimServiceLine4]', RESEED, @nextid); + + DELETE + FROM [fw].[DimServiceLine5] + WHERE [ServiceLine5ID] != 0; + + DBCC CHECKIDENT ('[fw].[DimServiceLine5]', RESEED, @nextid); + + DELETE + FROM [fw].[DimServiceLine6] + WHERE [ServiceLine6ID] != 0; + + DBCC CHECKIDENT ('[fw].[DimServiceLine6]', RESEED, @nextid); + --------- END CID 4 + + DELETE + FROM [fw].[DimProvider] + WHERE [ProviderID] != 0; + + DBCC CHECKIDENT ('[fw].[DimProvider]', RESEED, @nextid); + --------- END CID 1 + + --------- BEGIN CID 3 + DELETE + FROM [fw].[DimPayor] + WHERE [PayorID] != 0; + + DBCC CHECKIDENT ('[fw].[DimPayor]', RESEED, @nextid); + --------- END CID 3 + + --------- BEGIN CID 2 + TRUNCATE TABLE [dbo].[ScoreFillin]; + + EXEC [dbo].[procScoreFillinTableRebuildAll]; + EXEC [dbo].[procScoreFillinTableRefreshAll]; + --------- END CID 2 + + EXEC [fw].[procInsertDimensionDefaults]; + + DELETE [l] + FROM [dbo].[S3Loot] AS [l] + WHERE [l].[LootID] LIKE 'DEPT|%' + AND NOT EXISTS + ( SELECT 1 + FROM [fw].[DimDepartment] AS [d] + WHERE [l].[LootID] = 'DEPT|' + CAST([d].[DepartmentID] AS nvarchar(16)) + ); + + DELETE [lg] + FROM [dbo].[S3Loot] AS [lg] + WHERE [lg].[LootID] LIKE 'DEPT|%' + AND NOT EXISTS + ( SELECT 1 + FROM [fw].[DimDepartment] AS [d] + WHERE [lg].[LootID] = 'DEPT|' + CAST([d].[DepartmentID] AS nvarchar(16)) + ); + + DELETE [l] + FROM [dbo].[S3Loot] AS [l] + WHERE [l].[LootID] LIKE 'MRDEPT|%' + AND NOT EXISTS + ( SELECT 1 + FROM [fw].[DimDepartment] AS [d] + WHERE [l].[LootID] = 'MRDEPT|' + CAST([d].[DepartmentID] AS nvarchar(16)) + ); + + DELETE [lg] + FROM [dbo].[S3Loot] AS [lg] + WHERE [lg].[LootID] LIKE 'MRDEPT|%' + AND NOT EXISTS + ( SELECT 1 + FROM [fw].[DimDepartment] AS [d] + WHERE [lg].[LootID] = 'MRDEPT|' + CAST([d].[DepartmentID] AS nvarchar(16)) + ); + END; + +RETURN; +GO + + +--------------------------------------------- + +-- fw.procDeleteFactData +CREATE PROCEDURE [fw].[procDeleteFactData] +AS + +/************************************************************ +** Author: akowalski +** Create Date: 2013-11-07 +** Description: Deletes FW and CLIENT schema tables that are populated by the client, used only for GM releases - NEVER RUN ON CLIENT DATABASES +** Last Modified: 2013-11-07 +** GM Release: 2013-11-19 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2015-06-18 akk Converting proc to cursor +** +*************************************************************/ +BEGIN + + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + DECLARE @SCHEMA nvarchar(256) + DECLARE @FactTableName nvarchar(256) + DECLARE @SQL nvarchar(1024) + DECLARE @SQL2 nvarchar(1024) + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t + where (t.schema_id in(select schema_id from sys.schemas where name in('fw', 'client')) and t.name like 'fact%' and t.name not like '%map' + and t.name<>'FactWorkingHoursPerMonth') + order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + set @SQL = 'truncate table ' + @SCHEMA + '.' + @FactTableName + set @SQL2='DBCC CHECKIDENT (''' + + @SCHEMA + '.' + @FactTableName + ''', RESEED, 1)' + --print @SQL + + EXECUTE sp_executesql @SQL + if exists ( select 1 from sys.columns c + inner join sys.tables t on t.object_id=c.object_ID + inner join sys.schemas s on t.schema_id=s.schema_id + where t.name=@FactTableName and s.name=@SCHEMA and is_identity=1) + begin + EXECUTE sp_executesql @SQL2 + end + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + + +END + +RETURN +GO + + +--------------------------------------------- + +-- fw.procDepartmentChargeCodePrimaryStatisticMappingCache +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-03-20 HV JAZZ-52052 Create and fill in cache table for Primary Statistics data source for Daily and Pay Period +*************************************************************/ +CREATE PROCEDURE fw.procDepartmentChargeCodePrimaryStatisticMappingCache +AS + +IF OBJECT_ID('tempdb..#drivers') IS NOT NULL DROP TABLE #drivers + +CREATE TABLE #drivers (OriginalDepartmentID INT NOT NULL, DriverDepartmentID INT NOT NULL, AccountID INT NULL, IsStaffing BIT NOT NULL) + +INSERT INTO #drivers (OriginalDepartmentID, DriverDepartmentID, AccountID, IsStaffing) +SELECT C.DepartmentID AS OriginalDepartmentID, COALESCE(DC.DriverDepartmentID, C.DepartmentID) AS DriverDepartmentID, C.AccountID, C.Staffing AS IsStaffing +FROM client.FactDepartmentPrimaryStatisticConfiguration C +LEFT JOIN client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache DC ON DC.FactDepartmentPrimaryStatisticConfigurationID = C.RowID +WHERE C.IsDeleted = 0 + +TRUNCATE TABLE fw.DepartmentChargeCodePrimaryStatisticMappingCache + +INSERT INTO fw.DepartmentChargeCodePrimaryStatisticMappingCache (DepartmentID, OriginalDepartmentID, FiscalYearID, AccountID, ChargeCodeID, PatientTypeRollupID, Weight, IsStaffing) +SELECT + D.DriverDepartmentID AS DepartmentID, + D.OriginalDepartmentID, + map.FiscalYearID, + map.AccountID, + map.ChargeCodeID, + map.PatientTypeRollupID, + map.Weight, + D.IsStaffing +FROM #drivers D +INNER JOIN fw.DepartmentChargeCodeStatisticMappingCache map ON map.DepartmentID = D.DriverDepartmentID AND map.AccountID = D.AccountID + +IF OBJECT_ID('tempdb..#drivers') IS NOT NULL DROP TABLE #drivers +GO + + +--------------------------------------------- + +-- fw.procDepartmentChargeCodeStatisticMappingCacheRefresh +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2020-12-08 KF JAZZ-10947 My Performance | Supplies UOS Detail +*************************************************************/ +CREATE PROCEDURE [fw].[procDepartmentChargeCodeStatisticMappingCacheRefresh] +AS + +TRUNCATE TABLE fw.DepartmentChargeCodeStatisticMappingCache + +INSERT INTO fw.DepartmentChargeCodeStatisticMappingCache (FiscalYearID, DepartmentID, ChargeCodeID, PatientTypeRollupID, AccountID, Weight) +SELECT FiscalYearID, DepartmentID, ChargeCodeID, PatientTypeRollupID, AccountID, Weight +FROM fw.viewDepartmentChargeCodeStatisticMapping +WHERE AccountID != 0 AND Weight != 0 +GO + + +--------------------------------------------- + +-- fw.procDepartmentChargeCodeStatisticMappingSetDefault +/* +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-09-14 GF Initial implementation +** 2 2018-05-08 KF B-19364 MRPR - Set Global Weights for Charge Codes - System Center Page +** 3 2018-02-28 OV D-06846 modify proc to not insert data for RollupID = 0 +************************************************************ +*/ + + +CREATE proc [fw].[procDepartmentChargeCodeStatisticMappingSetDefault] +as + set nocount on + + insert into fw.DepartmentChargeCodeStatisticMapping (FiscalYearID, DepartmentRollupLevelMemberID, ChargeCodeID, PatientTYpeRollupID, AccountID, Weight, IsReviewed, DepartmentRollupLevelMemberColumnName) + select distinct + pblid.FiscalYearID, + pblid.DepartmentID, + pblid.ChargeCodeID, + pt.PatientTypeRollupID, + 0 as AccountID, + 0 as Weight, + 0 as IsReviewed, + 'DepartmentID' + from + dss.FactPatientBillingLineItemDetail pblid with (readuncommitted) + inner join clientdss.FactPatientEncounterSummary es with (readuncommitted) on es.EncounterID = pblid.EncounterID + inner join [fw].[DimPatientType] PT with (readuncommitted) on es.PatientTypeID=PT.PatientTypeID + LEFT JOIN fw.DepartmentChargeCodeStatisticMapping ex on ex.FiscalYearID = pblid.FiscalYearID + and ex.DepartmentRollupLevelMemberID = pblid.DepartmentID + and ex.DepartmentRollupLevelMemberColumnName = 'DepartmentID' + and ex.ChargeCodeID = pblid.ChargeCodeID + and ex.PatientTypeRollupID = pt.PatientTypeRollupID + WHERE ex.FiscalYearID is null + and pt.PatientTypeRollupID != 0 +GO + + +--------------------------------------------- + +-- fw.procDepartmentChargeCodeStatisticMappingStaffingCache +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-02-02 KF JAZZ-48413 Charge Based Statistics Modals Performance Improvement- Bug Fixing +*************************************************************/ +CREATE PROCEDURE fw.procDepartmentChargeCodeStatisticMappingStaffingCache +AS + +IF OBJECT_ID('tempdb..#drivers') IS NOT NULL DROP TABLE #drivers + +CREATE TABLE #drivers (OriginalDepartmentID INT NOT NULL, DriverDepartmentID INT NOT NULL, AccountID INT NULL) + +INSERT INTO #drivers (OriginalDepartmentID, DriverDepartmentID, AccountID) +SELECT C.DepartmentID AS OriginalDepartmentID, COALESCE(DC.DriverDepartmentID, C.DepartmentID) AS DriverDepartmentID, C.AccountID +FROM client.FactDepartmentPrimaryStatisticConfiguration C +LEFT JOIN client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache DC ON DC.FactDepartmentPrimaryStatisticConfigurationID = C.RowID +WHERE C.IsDeleted = 0 AND C.Staffing = 1 + +TRUNCATE TABLE fw.DepartmentChargeCodeStatisticMappingStaffingCache + +INSERT INTO fw.DepartmentChargeCodeStatisticMappingStaffingCache (DepartmentID, OriginalDepartmentID, FiscalYearID, AccountID, ChargeCodeID, PatientTypeRollupID, Weight) +SELECT + D.DriverDepartmentID AS DepartmentID, + D.OriginalDepartmentID, + map.FiscalYearID, + map.AccountID, + map.ChargeCodeID, + map.PatientTypeRollupID, + map.Weight +FROM #drivers D +INNER JOIN fw.DepartmentChargeCodeStatisticMappingCache map ON map.DepartmentID = D.DriverDepartmentID AND map.AccountID = D.AccountID + +IF OBJECT_ID('tempdb..#drivers') IS NOT NULL DROP TABLE #drivers +GO + + +--------------------------------------------- + +-- fw.procDepartmentPrimaryStatisticConfigurationDriverDepartmentCacheRefresh +create proc fw.procDepartmentPrimaryStatisticConfigurationDriverDepartmentCacheRefresh +as + if (not exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment)) begin + return + end + + declare @sql nvarchar(max) + + set @sql = ' + truncate table [client].[FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache]; + + insert into [client].[FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache] (DriverDepartmentGUID, FactDepartmentPrimaryStatisticConfigurationID, DriverDepartmentID) + select + dd.DriverDepartmentGUID, + dd.FactDepartmentPrimaryStatisticConfigurationID, + sd.DepartmentID + from + client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd + inner join fw.DimDepartment sd on dd.Value = ''DEPT|KEY|af5b308b-7574-4769-b4e9-dcdeb617b1fc|'' + cast(sd.DepartmentID as nvarchar(8)) + ''|DEPTDepartmentID|'' + cast(sd.DepartmentID as nvarchar(8));' + + if (exists(select 1 from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd where dd.Value not like 'DEPT|KEY|%')) begin + declare @driverGUID uniqueidentifier + declare @configID int + declare @hpath nvarchar(max) + declare @where nvarchar(max) + declare crsHPaths cursor fast_forward for + select + dd.DriverDepartmentGUID, + dd.FactDepartmentPrimaryStatisticConfigurationID, + dd.Value + from + client.FactDepartmentPrimaryStatisticConfigurationDriverDepartment dd + where + dd.Value not like 'DEPT|KEY|%' + open crsHPaths + fetch next from crsHPaths into @driverGUID, @configID, @hpath + while (@@FETCH_STATUS = 0) begin + exec dbo.procScoreHierarchyPathGetQuery @hpath, 1, @where OUTPUT + set @sql = @sql + ' + + insert into [client].[FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache] (DriverDepartmentGUID, FactDepartmentPrimaryStatisticConfigurationID, DriverDepartmentID) + select ''' + CAST(@driverGUID as nvarchar(36)) + ''', ' + cast(@configID as nvarchar(8)) + ', DepartmentID from fw.viewDimDepartment where ' + @where + ';' + + fetch next from crsHPaths into @driverGUID, @configID, @hpath + end + close crsHPaths + deallocate crsHPaths + end + + exec(@sql) +GO + + +--------------------------------------------- + +-- fw.procDimDateAssignFiscalYear +CREATE proc [fw].[procDimDateAssignFiscalYear] +as +/************************************************************ +** Author: Unknown +** Create Date: Unknown +** Description: Assigns Fiscal Year to the Date Dimension +** Last Modified: 2015-11-25 +** GM Release: Unknown +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2015-11-25 JG Changing join to join on ID instead of Code +** 2 2016-10-17 MH D-04891 Updated FiscalQuarter +*************************************************************/ + +--Disable triggers on fw.DimDate or else this will be very slow + +begin + declare @yemonth int = (select dbo.GetDBSetting('GENERAL_FISCALYEARENDMONTH')) + print @yemonth + + update fw.dimdate + set FiscalYear = + CASE + WHEN calendarmonth <= @yemonth THEN calendaryear + else cast(calendaryear as int) + 1 + END +from fw.DimDate +end + +update d +set d.FiscalMonth = fm.SortOrder, d.FiscalQuarter = concat('Quarter ', fm.QuarterID) +from fw.DimDate d +inner join fw.DimFiscalMonth fm on d.CalendarMonth = fm.FiscalMonthID +where DateID <> 0 + +--exec [dbo].[procChangeDBSetting] @settingname = 'GENERAL_FISCALYEARENDMONTH', @value = 6 +GO + + +--------------------------------------------- + +-- fw.procDimDatePopulate +--Author: ekretzer +--Branch: DSS +--Forward + +create procedure fw.procDimDatePopulate + @StartDate datetime +as +begin + set nocount on + + -- Determine if the year has 365 or 366 days + declare @numDays smallint = 365; + declare @p_leap_date SMALLDATETIME = CONVERT(VARCHAR(4), YEAR(@StartDate)) + '0228' + declare @p_check_day TINYINT = DATEPART(d, DATEADD(d, 1, @p_leap_date)) + if (@p_check_day = 29) + set @numDays = 366; + + declare @i int = 0; + declare @CurrentDate datetime; + + while (@i < @numDays) + begin + set @CurrentDate = DATEADD(DAY, @i, @StartDate); + set @CurrentDate = DATEADD(DAY, DATEDIFF(Day, 0, @CurrentDate), 0); --round off to day + insert into fw.DimDate ( + CalendarDateTime, CalendarYear, CalendarMonth, CalendarMonthName, DayNumberOfWeek, DayNameOfWeek, DayNumberOfMonth, DayNumberOfYear, WeekNumberOfYear, IsWeekDay, CalendarQuarter) + values (@CurrentDate, YEAR(@CurrentDate), MONTH(@CurrentDate), DATENAME(month, @CurrentDate ), DATEPART(weekday, @CurrentDate), DATENAME(weekday, @CurrentDate) + ,DAY(@CurrentDate), DATEPART(dayofyear, @CurrentDate), DATEPART(week, @CurrentDate), + case when DATEPART(weekday, @CurrentDate) in (1,7) then 0 else 1 end, + DATENAME(quarter, @CurrentDate)) + set @i = @i + 1; + end + print 'Added ' + cast(@numDays as varchar(3)) + ' days for ' + cast(year(@StartDate) as varchar(4)) +end + +RETURN +GO + + +--------------------------------------------- + +-- fw.procDimFiscalMonthUpdateDaysInMonth +CREATE PROCEDURE [fw].[procDimFiscalMonthUpdateDaysInMonth] +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + declare @currentYear int = year(getdate()) + update fw.DimFiscalMonth + set DaysInMonth = dbo.GetDaysInMonth(cast(cast(@currentYear as varchar) + '-' + cast(fiscalmonthid as varchar) + '-1' as DateTime)) + where FiscalMonthID <> 0 + + update fw.dimfiscalmonth + set + ytddaysinmonth = + coalesce(fw.[GetYTDDaysInMonth](fiscalmonthid), 0) + where FiscalMonthID <> 0 +END +GO + + +--------------------------------------------- + +-- fw.procDimPayPeriodUpdateFiscalYear +CREATE PROCEDURE [fw].[procDimPayPeriodUpdateFiscalYear] +AS + + update + fw.dimpayperiod + set + fiscalyearidstart = [dbo].[GetFiscalYearForDate](dateadd(day,(1)-[perioddays],[periodendcalendardate])), + fiscalyearidsecond = [dbo].[GetFiscalYearForDate]([periodendcalendardate]) +GO + + +--------------------------------------------- + +-- fw.procDimTimePopulate +--Author: ekretzer +--Branch: DSS +--Forward + +create procedure fw.procDimTimePopulate +as +begin + -- We assume that the 0 record is 0:00 & not 0 - Not Specified + truncate table fw.DimTime + DBCC CHECKIDENT ('fw.DimTime', reseed, 0) + + declare @Hour tinyint = 0 + declare @Minute tinyint = 0 + + while @Hour < 24 + begin + set @Minute = 0 + while @Minute < 60 + begin + insert into fw.DimTime([Hour], [Minute], MemberGUID) values (@Hour, @Minute, newid()) + set @Minute = @Minute + 1 + end + set @Hour = @Hour + 1 + end --@Hour + +end + +RETURN +GO + + +--------------------------------------------- + +-- fw.procEMFFillInCreateAutoProc +CREATE proc [fw].[procEMFFillInCreateAutoProc] + @procschema sysname, + @procobject sysname, + @phdimensionguid uniqueidentifier, + @plantypeguid uniqueidentifier, + @attributename nvarchar(100) = 'AutomaticPHSection' + --@planguid uniqueidentifier = '00000000-0000-0000-0000-000000000000' +as +/* + +select + AutomaticPHSection +from + zzviewlist_masteraccount + +*/ +declare @phdimname nvarchar(100) +declare @fidimname nvarchar(100) +declare @phl1name nvarchar(100) + +select + @phdimname = replace(ph.Name, ' ', ''), + @fidimname = replace(fi.Name, ' ', ''), + @phl1name = replace(phl1.Name, ' ','') +from + SecureList ph + inner join SecureList fi on ph.FillInDimensionGUID = fi.ListGUID + inner join SecureListLevel phl1 on ph.ListGUID = phl1.ListGUID and phl1.LevelIndex = 0 +where + ph.ListGUID = @phdimensionguid + +declare @sql nvarchar(max) + +set @sql = ' + +if exists ( select 1 from viewSysProcedures where schemaname = ''' + @procschema + ''' and objectname = ''' + @procobject + ''' ) begin + drop proc [' + @procschema + '].[' + @procobject + '] +end +' + +exec (@sql) + +set @sql = ' + +create proc [' + @procschema + '].[' + @procobject + '] + @planguid uniqueidentifier = ''00000000-0000-0000-0000-000000000000'' +as + +declare @iguid uniqueidentifier +set @iguid = NEWID() + +insert into EMFFillInSetManyStaging ( InstanceGUID, ModelGUID, PHDimensionGUID, ParentPHMemberGUID, FillInGUID, SortOrder) +select + @iguid, + p.PlanGUID as ModelGUID, + ''' + cast(@phdimensionguid as varchar(36)) + ''' as PHDimensionGUID, --' + @phdimname + ' + ph.'+ @phdimname +'GUID as ParentPHMemberGUID, + fi.'+ @fidimname +'GUID as FillInGuid, + ROW_NUMBER() over (partition by p.planguid order by fi.'+ @fidimname +' asc) as SortOrder +from + [zzviewlist_'+ @fidimname +'] fi + inner join zzviewlist_'+ @phdimname +' ph on fi.'+ @attributename +' = ph.'+ @phl1name +' and ph.'+ @phdimname +' is null + cross join xplan p +where + p.plantypeguid = ''' + CAST(@plantypeguid as varchar(36)) + ''' + and (p.planguid = @planguid or @planguid = dbo.ZeroGUID()) + +exec procEMFFillInSetManyNoClear @iguid + +--select * from EMFFillInSetManyStaging where InstanceGUID = @iguid +delete from EMFFillInSetManyStaging where InstanceGUID = @iguid +' + +exec (@sql) +GO + + +--------------------------------------------- + +-- fw.procFactDailyMergeDuplicates +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-07-25 KF JAZZ-39738 Daily flexing - Payroll Hours and Dollars +*************************************************************/ +CREATE proc [fw].[procFactDailyMergeDuplicates] + @factTableName nvarchar(100), + @keyNameCSV nvarchar(450), + @measureNameCSV nvarchar(450), + @fiscalYearID smallint = 0, + @priorYearsCount smallint = 0, + @timeClassID tinyint = 0, + @onePayPeriodOnlyDate datetime = null, + @isDebugOnly bit = 0, + @departmentIDs nvarchar(max) = null +with recompile +as + set nocount on + + IF OBJECT_ID('tempdb..#DailyCalcPeriodsScope') IS NOT NULL DROP TABLE #DailyCalcPeriodsScope + CREATE TABLE #DailyCalcPeriodsScope (PayPeriodID int primary key) + + INSERT INTO #DailyCalcPeriodsScope (PayPeriodID) + SELECT PayPeriodID + FROM fw.DimPayPeriod + WHERE + (@onePayPeriodOnlyDate IS NOT NULL and @onePayPeriodOnlyDate BETWEEN PeriodStartCalendarDate and PeriodEndCalendarDate) + or + (@onePayPeriodOnlyDate IS NULL and ((FiscalYearIDSecond BETWEEN @fiscalYearID - @priorYearsCount AND @fiscalYearID) or @fiscalYearID = 0)) + + declare @sql nvarchar(max) + + declare @from nvarchar(max) = ' + FROM ' + @factTableName + ' data + INNER JOIN #DailyCalcPeriodsScope pp ON pp.PayPeriodID = data.PayPeriodID + INNER JOIN + ( + SELECT fd.DepartmentID, fd.' + replace(@keyNameCSV, ',', ', fd.') + ', fd.PayPeriodID, fd.DateID, fd.TimeClassID + FROM ' + @factTableName + ' fd + GROUP BY fd.DepartmentID, fd.' + replace(@keyNameCSV, ',', ', fd.') + ', fd.PayPeriodID, fd.DateID, fd.TimeClassID + HAVING COUNT(*) > 1 + ) dr ON dr.DepartmentID = data.DepartmentID and ' + (select dbo.straggr('dr.' + csv.val + ' = data.' + csv.val, ' and ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' and dr.PayPeriodID = data.PayPeriodID and dr.DateID = data.DateID and dr.TimeClassID = data.TimeClassID + WHERE (1 = 1)' + (case when @timeClassID > 0 then ' and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + + declare @fromForUpdate nvarchar(max) = REPLACE(@from, '#DailyCalcPeriodsScope', '#inputPayPeriods'); + + declare @delete nvarchar(max) = ' + WHILE (EXISTS (SELECT TOP 1 1 FROM ' + @factTableName + ' WHERE IsDeleted = 1)) + BEGIN + DELETE TOP(10000000) data FROM ' + @factTableName + ' data WHERE data.IsDeleted = 1 + END; + ' + + + --merge duplicate rows + set @sql = @delete +' + + IF OBJECT_ID(''tempdb..#inputPayPeriods'') IS NOT NULL DROP TABLE #inputPayPeriods + + SELECT data.PayPeriodID, COUNT(1) AS RecordsCount, 0 AS BatchID INTO #inputPayPeriods ' + @from + ' + GROUP BY data.PayPeriodID + + -- Split data into batches + DECLARE @BatchSize INT = 20000000 + + WHILE EXISTS (SELECT TOP 1 1 FROM #inputPayPeriods WHERE BatchID = 0) + BEGIN + ;WITH PayPeriodInfo AS + ( + SELECT IPP.PayPeriodID, ROW_NUMBER() OVER (ORDER BY IPP.PayPeriodID) AS RowNumber, SUM(RecordsCount) OVER (ORDER BY IPP.PayPeriodID) AS Total, M.MaxBatchID+1 AS BatchID + FROM #inputPayPeriods IPP + CROSS JOIN (SELECT MAX(BatchID) AS MaxBatchID FROM #inputPayPeriods) M + WHERE IPP.BatchID = 0 + ) + UPDATE IPP + SET IPP.BatchID = MI.BatchID + FROM #inputPayPeriods IPP + INNER JOIN PayPeriodInfo MI ON MI.PayPeriodID = IPP.PayPeriodID + WHERE MI.Total <= @BatchSize OR MI.RowNumber = 1 + END + + DECLARE @BatchID INT, @MaxBatchID INT + SELECT @MaxBatchID = MAX(BatchID) FROM #inputPayPeriods + + -- Loop thru batches and insert data + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + UPDATE data + SET data.IsDeleted = 1 ' + @fromForUpdate + ' and pp.BatchID = @BatchID + + INSERT INTO ' + @factTableName + ' (data.DepartmentID, ' + @keyNameCSV + ', PayPeriodID, DateID, TimeClassID, ' + @measureNameCSV + ') + SELECT data.DepartmentID, ' + replace(@keyNameCSV, ',', ', data.') + ', data.PayPeriodID, data.DateID, data.TimeClassID, sum(' + replace(@measureNameCSV, ',', '), sum(') + ') + FROM ' + @factTableName + ' data + INNER JOIN #inputPayPeriods pp ON pp.PayPeriodID = data.PayPeriodID + WHERE data.IsDeleted = 1 and pp.BatchID = @BatchID + GROUP BY data.DepartmentID, ' + replace(@keyNameCSV, ',', ', data.') + ', data.PayPeriodID, data.DateID, data.TimeClassID; + + SET @BatchID = @BatchID + 1 + END + ' + @delete; + + if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end + + IF OBJECT_ID('tempdb..#DailyCalcPeriodsScope') IS NOT NULL DROP TABLE #DailyCalcPeriodsScope + IF OBJECT_ID('tempdb..#inputPayPeriods') IS NOT NULL DROP TABLE #inputPayPeriods +GO + + +--------------------------------------------- + +-- fw.procFactGLSampledBaselineTargetUpdate +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-07-05 IP D-06023 Changing columns size to support values over 1 trillion +** 2 2018-05-16 IP D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values +** 3 2018-05-24 KF D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values +** 4 2018-06-01 IP D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values (one year part) +** 5 2018-06-05 IP TK-58643 added filetr for current year only and non-zero records in output +** 6 2024-06-05 ishah JAZZ-61244 [TrLog][High] Bug - Run Management Reporting Monthly Process (MR Sampling, all years run): Task failed on Inserting GL Sampled. +*************************************************************/ +----- #FactGLStaging should be created with specified columns(RowID bigint identity(1,1), DepartmentID int, AccountID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, Units decimal(21,6), Dollars decimal(21,6), FTEs decimal(21,6),isDeleted bit default 0, isSystemGenerated bit default 0) before calling the proc +CREATE PROCEDURE [fw].[procFactGLSampledBaselineTargetUpdate] + @targetType INT = NULL, + @numberOfMonths INT = NULL, + @fiscalYearID INT = 0 + + WITH RECOMPILE +AS + +IF (@targetType IS NULL) + SET @targetType = ( + SELECT Value + FROM mr.SystemSetting + WHERE NAME = 'Target Basis' + ) + +IF (@numberOfMonths IS NULL) + SET @numberOfMonths = ( + SELECT Value + FROM mr.SystemSetting + WHERE NAME = 'Number Of Rolling Average Months' + ) + +CREATE TABLE #temp (DepartmentID INT, AccountID INT, FiscalYearID SMALLINT, FiscalMonthID TINYINT, Dollars DECIMAL(21, 6), Units DECIMAL(21, 6)) +DECLARE + @declareParameters nvarchar(max), + @sql nvarchar(max), + @sqlJoin nvarchar(max), + @sqlWhere nvarchar(max), + @sqlFromForBatches nvarchar(max), + @batchSize INT, + @BatchID INT, + @MaxBatchID INT, + @sqlParam nvarchar(max), + @timeClassId int = 1 + +declare @maxCalculatingFiscalYear int = (select max(FiscalYearID) from #FactGLStaging) + +-- Split by batches +EXEC mr.procGetIntBatchSize + @DefaultBatchSize = 30000000, + @ResultBatchSize = @batchSize OUTPUT + +IF OBJECT_ID('tempdb..#inputDepartments') IS NOT NULL DROP TABLE #inputDepartments +CREATE TABLE #inputDepartments (DepartmentID INT, RecordsCount INT, BatchID INT) + +delete from #FactGLStaging where TimeClassID = 20 and (FiscalYearID = @FiscalYearID or @FiscalYearID = 0) + +IF (@targetType = 1) +BEGIN --Prior Year Actual + IF @fiscalYearID <> 0 + BEGIN + set @declareParameters = '@fiscalYearID INT = ' + cast(@fiscalYearID - 1 as NVARCHAR(4)) + ', @timeClassId INT = ' + cast(@timeClassId as nvarchar(max)) + set @sqlJoin = ' + ( + SELECT d.DepartmentID, d.AccountID, d.FiscalYearID + 1 as FiscalYearID, d.FiscalMonthID + FROM fw.FactGLSampled d + WHERE d.TimeClassID = @timeClassId AND d.FiscalYearID = @fiscalYearID + ) X + ' + + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'X', + @fromClause = @sqlJoin, + @whereClause = '', + @declareParameters = @declareParameters, + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + INSERT INTO #temp + SELECT d.DepartmentID, d.AccountID, d.FiscalYearID + 1, d.FiscalMonthID, d.Dollars, d.Units + FROM fw.FactGLSampled d + INNER JOIN #inputDepartments ID on ID.DepartmentID = d.DepartmentID + AND d.TimeClassID = @timeClassId AND d.FiscalYearID = @fiscalYearID - 1 AND ID.BatchID = @BatchID + + SET @BatchID = @BatchID + 1 + END + END + ELSE + BEGIN + set @declareParameters = '@timeClassId INT = ' + cast(@timeClassId as nvarchar(max)) + set @sqlJoin = ' + ( + SELECT d.DepartmentID, d.AccountID, d.FiscalYearID + 1 as FiscalYearID, d.FiscalMonthID + FROM #FactGLStaging d + WHERE d.TimeClassID = @timeClassId + ) X + ' + + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'X', + @fromClause = @sqlJoin, + @whereClause = '', + @declareParameters = @declareParameters, + @isDebug = 0 + + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + INSERT INTO #temp + SELECT d.DepartmentID, d.AccountID, d.FiscalYearID + 1, d.FiscalMonthID, d.Dollars, d.Units + FROM #FactGLStaging d + INNER JOIN #inputDepartments ID on ID.DepartmentID = d.DepartmentID + WHERE d.TimeClassID = @timeClassId AND ID.BatchID = @BatchID + + SET @BatchID = @BatchID + 1 + END + END +END +ELSE IF (@targetType = 10) +BEGIN --Rolling Average + IF OBJECT_ID('tempdb..#AllCombinations') IS NOT NULL DROP TABLE #AllCombinations + CREATE TABLE #AllCombinations ( + DepartmentID INT, + AccountID INT, + FiscalYearID INT, + SortOrder INT, + Units DECIMAL(21, 6), + Dollars DECIMAL(21, 6) + ); + + IF OBJECT_ID('tempdb..#FinalDataset') IS NOT NULL DROP TABLE #FinalDataset + CREATE TABLE #FinalDataset ( + DepartmentID INT, + AccountID INT, + FiscalYearID INT, + FiscalMonthID INT, + Dollars DECIMAL(21, 6), + Units DECIMAL(21, 6) + ); + + IF @fiscalYearID = 0 + BEGIN + IF OBJECT_ID('tempdb..#FiscalYearMonth') IS NOT NULL DROP TABLE #FiscalYearMonth + CREATE TABLE #FiscalYearMonth ( + FiscalYearID INT, + FiscalMonthID INT, + SortOrder INT, + ChronologicalOrder INT + ); + + INSERT INTO #FiscalYearMonth (FiscalYearID, FiscalMonthID, SortOrder, ChronologicalOrder) + SELECT fy.FiscalYearID, fm.FiscalMonthID, fm.SortOrder, fy.FiscalYearID * 12 + fm.SortOrder AS ChronologicalOrder + FROM fw.DimFiscalYear fy + CROSS JOIN fw.DimFiscalMonth fm + WHERE fy.FiscalYearID <> 0 AND fm.FiscalMonthID <> 0 + + IF OBJECT_ID('tempdb..#PrecomputedValues') IS NOT NULL DROP TABLE #PrecomputedValues + CREATE TABLE #PrecomputedValues ( + DepartmentID INT, + AccountID INT, + FiscalYearID INT, + FiscalMonthID INT, + SortOrder INT, + PrecomputedValue INT, + Units DECIMAL(21, 6), + Dollars DECIMAL(21, 6), + TimeClassID INT, + IsSystemGenerated BIT + ); + + SET @sqlFromForBatches = ' + ( + SELECT + p.DepartmentID as DepartmentID, + p.AccountID, + p.FiscalYearID, + p.FiscalMonthID, + m.SortOrder, + (p.FiscalYearID * 12 + m.SortOrder) AS PrecomputedValue, + p.Units, + p.Dollars, + p.TimeClassID, + ISNULL(p.IsSystemGenerated, 0) AS IsSystemGenerated + FROM #FactGLStaging p + INNER JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID + WHERE p.TimeClassID = 1 AND ISNULL(p.IsSystemGenerated, 0) = 0 + ) X + ' + + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'X', + @fromClause = @sqlFromForBatches, + @whereClause = '', + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + INSERT INTO #PrecomputedValues + SELECT + p.DepartmentID, + p.AccountID, + p.FiscalYearID, + p.FiscalMonthID, + m.SortOrder, + (p.FiscalYearID * 12 + m.SortOrder) AS PrecomputedValue, + p.Units, + p.Dollars, + p.TimeClassID, + ISNULL(p.IsSystemGenerated, 0) AS IsSystemGenerated + FROM #FactGLStaging p + INNER JOIN #inputDepartments ID ON ID.DepartmentID = p.DepartmentID + INNER JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID + WHERE p.TimeClassID = 1 AND ISNULL(p.IsSystemGenerated, 0) = 0 AND ID.BatchID = @BatchID + + SET @BatchID = @BatchID + 1 + END + + IF OBJECT_ID('tempdb..#ChronologicalDifferences') IS NOT NULL DROP TABLE #ChronologicalDifferences + CREATE TABLE #ChronologicalDifferences ( + DepartmentID INT, + AccountID INT, + FiscalYearID INT, + SortOrder INT, + ChronologicalDifference INT + ); + + DECLARE @MinYear INT = (SELECT MIN(FiscalYearID) FROM #PrecomputedValues) + DECLARE @MaxYear INT = (SELECT MAX(FiscalYearID) FROM #PrecomputedValues) + + WHILE @MinYear <= @MaxYear + BEGIN + SET @sqlFromForBatches = ' + ( + SELECT + pv.DepartmentID as DepartmentID, + pv.AccountID, + fy.FiscalYearID, + fy.SortOrder, + (fy.ChronologicalOrder - pv.PrecomputedValue) AS ChronologicalDifference + FROM #PrecomputedValues pv + INNER JOIN #FiscalYearMonth fy ON (fy.ChronologicalOrder - pv.PrecomputedValue) BETWEEN 1 AND ' + CAST(@numberOfMonths AS NVARCHAR(4)) + ' + WHERE pv.FiscalYearID = ' + cast(@MinYear as nvarchar(100)) + ' + ) X + ' + + TRUNCATE TABLE #inputDepartments + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'X', + @fromClause = @sqlFromForBatches, + @whereClause = '', + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + INSERT INTO #ChronologicalDifferences + SELECT + pv.DepartmentID, + pv.AccountID, + fy.FiscalYearID, + fy.SortOrder, + (fy.ChronologicalOrder - pv.PrecomputedValue) AS ChronologicalDifference + FROM #PrecomputedValues pv + INNER JOIN #inputDepartments ID ON ID.DepartmentID = pv.DepartmentID + INNER JOIN #FiscalYearMonth fy ON (fy.ChronologicalOrder - pv.PrecomputedValue) BETWEEN 1 AND @numberOfMonths + WHERE ID.BatchID = @BatchID AND pv.FiscalYearID = @MinYear + + SET @BatchID = @BatchID + 1 + END + + + SET @MinYear = @MinYear + 1 + END + + SET @sqlFromForBatches = ' + ( + SELECT + CombinedResults.DepartmentID as DepartmentID, + AccountID, + FiscalYearID, + SortOrder + FROM ( + SELECT + PV.DepartmentID as DepartmentID, + AccountID, + FiscalYearID, + SortOrder, + Units, + Dollars, + NULL AS ChronologicalDifference + FROM #PrecomputedValues PV + WHERE PV.FiscalMonthID <> 0 + + UNION ALL + + SELECT + CD.DepartmentID as DepartmentID, + AccountID, + FiscalYearID, + SortOrder, + 0 AS Units, + 0 AS Dollars, + ChronologicalDifference + FROM #ChronologicalDifferences CD + ) AS CombinedResults + GROUP BY CombinedResults.DepartmentID, AccountID, FiscalYearID, SortOrder + ) X + ' + + TRUNCATE TABLE #inputDepartments + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'X', + @fromClause = @sqlFromForBatches, + @whereClause = '', + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + INSERT INTO #AllCombinations + SELECT + CombinedResults.DepartmentID, + AccountID, + FiscalYearID, + SortOrder, + SUM(CASE WHEN ChronologicalDifference IS NULL THEN Units ELSE 0 END) AS Units, + SUM(CASE WHEN ChronologicalDifference IS NULL THEN Dollars ELSE 0 END) AS Dollars + FROM ( + SELECT + PV.DepartmentID, + AccountID, + FiscalYearID, + SortOrder, + Units, + Dollars, + NULL AS ChronologicalDifference + FROM #PrecomputedValues PV + WHERE PV.FiscalMonthID <> 0 + + UNION ALL + + SELECT + CD.DepartmentID, + AccountID, + FiscalYearID, + SortOrder, + 0 AS Units, + 0 AS Dollars, + ChronologicalDifference + FROM #ChronologicalDifferences CD + ) AS CombinedResults + INNER JOIN #inputDepartments ID ON ID.DepartmentID = CombinedResults.DepartmentID + WHERE ID.BatchID = @BatchID + GROUP BY CombinedResults.DepartmentID, AccountID, FiscalYearID, SortOrder + + SET @BatchID = @BatchID + 1 + END + + SET @sql = ' + SELECT DepartmentID, AccountID, FiscalYearID, SortOrder, Dollars, Units + FROM #AllCombinations + ' + SET @sqlWhere = 'WHERE (Dollars is not null or Units is not null)' + END + ELSE -- FiscalYearID != 0 + BEGIN + SET @sqlFromForBatches = ' + ( + SELECT + p.DepartmentID as DepartmentID, + AccountID, + FiscalYearID, + m.SortOrder as SortOrder, + Units, + Dollars + FROM #FactGLStaging p + JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID + WHERE m.FiscalMonthID <> 0 AND ISNULL(p.IsSystemGenerated, 0) = 0 AND TimeClassID = 1 AND FiscalYearID = ' + cast(@fiscalYearID AS NVARCHAR(4)) + ' + + UNION ALL + + SELECT + p.DepartmentID as DepartmentID, + AccountID, + FiscalYearID, + m.SortOrder as SortOrder, + Units, + Dollars + FROM fw.FactGLSampled p + JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID + WHERE m.FiscalMonthID <> 0 AND ISNULL(p.IsSystemGenerated, 0) = 0 AND TimeClassID = 1 AND FiscalYearID = ' + cast(@fiscalYearID - 1 AS NVARCHAR(4)) + ' + + UNION ALL + + SELECT + p.DepartmentID as DepartmentID, + AccountID, + FiscalYearID, + m.SortOrder as SortOrder, + 0 AS Units, + 0 AS Dollars + FROM #FactGLStaging p + CROSS APPLY fw.DimFiscalMonth m + WHERE m.FiscalMonthID <> 0 AND p.TimeClassID = 1 + + UNION ALL + + SELECT + p.DepartmentID as DepartmentID, + p.AccountID as AccountID, + fy.FiscalYearID as FiscalYearID, + m.SortOrder as SortOrder, + 0 AS Units, + 0 AS Dollars + FROM fw.FactGLSampled p + CROSS APPLY fw.DimFiscalMonth m + CROSS JOIN ( + SELECT FiscalYearID + FROM fw.DimFiscalYear dm + WHERE dm.FiscalYearID IN ('+cast(@fiscalYearID-1 as nvarchar(4))+','+cast(@fiscalYearID as nvarchar(4))+') + ) fy + WHERE m.FiscalMonthID <> 0 AND p.TimeClassID = 1 AND ISNULL(p.IsSystemGenerated, 0) = 0 AND p.FiscalYearID = ' + cast(@fiscalYearID - 1 AS NVARCHAR(4)) + ' + ) X + ' + + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'X', + @fromClause = @sqlFromForBatches, + @whereClause = '', + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + INSERT INTO #AllCombinations + SELECT + p.DepartmentID, + AccountID, + FiscalYearID, + m.SortOrder, + Units, + Dollars + FROM #FactGLStaging p + INNER JOIN #inputDepartments ID on ID.DepartmentID = p.DepartmentID + JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID + WHERE m.FiscalMonthID <> 0 AND ISNULL(p.IsSystemGenerated, 0) = 0 AND TimeClassID = 1 AND FiscalYearID = @fiscalYearID AND ID.BatchID = @BatchID + + UNION ALL + + SELECT + p.DepartmentID, + AccountID, + FiscalYearID, + m.SortOrder, + Units, + Dollars + FROM fw.FactGLSampled p + INNER JOIN #inputDepartments ID on ID.DepartmentID = p.DepartmentID + JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID + WHERE m.FiscalMonthID <> 0 AND ISNULL(p.IsSystemGenerated, 0) = 0 AND TimeClassID = 1 AND FiscalYearID = @fiscalYearID - 1 AND ID.BatchID = @BatchID + + UNION ALL + + SELECT + p.DepartmentID, + AccountID, + FiscalYearID, + m.SortOrder, + 0 AS Units, + 0 AS Dollars + FROM #FactGLStaging p + INNER JOIN #inputDepartments ID on ID.DepartmentID = p.DepartmentID + CROSS APPLY fw.DimFiscalMonth m + WHERE m.FiscalMonthID <> 0 AND p.TimeClassID = 1 AND ID.BatchID = @BatchID + + UNION ALL + + SELECT + p.DepartmentID, + p.AccountID, + fy.FiscalYearID, + m.SortOrder, + 0 AS Units, + 0 AS Dollars + FROM fw.FactGLSampled p + INNER JOIN #inputDepartments ID on ID.DepartmentID = p.DepartmentID + CROSS APPLY fw.DimFiscalMonth m + CROSS JOIN ( + SELECT FiscalYearID + FROM fw.DimFiscalYear dm + WHERE dm.FiscalYearID IN (@fiscalYearID - 1, @fiscalYearID) + ) fy + WHERE m.FiscalMonthID <> 0 AND p.TimeClassID = 1 AND ISNULL(p.IsSystemGenerated, 0) = 0 AND p.FiscalYearID = @fiscalYearID - 1 AND ID.BatchID = @BatchID + + SET @BatchID = @BatchID + 1 + END + + SET @sql = ' + SELECT DepartmentID, AccountID, FiscalYearID, SortOrder, SUM(Dollars) AS Dollars, SUM(Units) AS Units + FROM #AllCombinations + GROUP BY DepartmentID, AccountID, FiscalYearID, SortOrder + ' + SET @sqlWhere = 'WHERE (Dollars is not null or Units is not null) and FiscalYearID = ' + cast(@fiscalYearID AS NVARCHAR(4)) + ' ' + END + + SET @sqlJoin = ' + SELECT + FullScope.DepartmentID as DepartmentID, + FullScope.AccountID as AccountID, + FullScope.FiscalYearID as FiscalYearID, + m.FiscalMonthID as FiscalMonthID, + ISNULL( + (SUM(Dollars) OVER (PARTITION BY FullScope.DepartmentID, AccountID ORDER BY FiscalYearID * 12 + m.SortOrder ROWS BETWEEN ' + CAST(@numberOfMonths AS NVARCHAR(4)) + ' PRECEDING AND 1 PRECEDING)) / ' + CAST(@numberOfMonths AS NVARCHAR(4)) + ', 0 + ) AS Dollars, + ISNULL( + (SUM(Units) OVER (PARTITION BY FullScope.DepartmentID, AccountID ORDER BY FiscalYearID * 12 + m.SortOrder ROWS BETWEEN ' + CAST(@numberOfMonths AS NVARCHAR(4)) + ' PRECEDING AND 1 PRECEDING)) / ' + CAST(@numberOfMonths AS NVARCHAR(4)) + ', 0 + ) AS Units + FROM ( + ' + @sql + ' + ) AS FullScope + JOIN fw.DimFiscalMonth m ON FullScope.SortOrder = m.SortOrder + ' + + SET @sqlFromForBatches = ' + ( ' + @sqlJoin + ' + ) X + ' + + SET @sql = ' + INSERT INTO #FinalDataset + ' + @sqlJoin + ' + ' + 'INNER JOIN #inputDepartments IP ON IP.DepartmentID = FullScope.DepartmentID' + ' + WHERE IP.BatchID = @BatchID + ' + + TRUNCATE TABLE #inputDepartments + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias ='X', + @fromClause = @sqlFromForBatches, + @whereClause = '', + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + SET @SqlParam = '@BatchID INT' + -- Loop thru batches and insert data + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + EXEC sp_executesql @sql, @SqlParam, @BatchID = @BatchID; + SET @BatchID = @BatchID + 1 + END + + SET @sqlFromForBatches = ' + ( + SELECT + DepartmentID, + AccountID, + FiscalYearID, + FiscalMonthID, + ISNULL(Dollars, 0.0) AS Dollars, + ISNULL(Units, 0.0) AS Units + FROM #FinalDataset + ' + @sqlWhere + ' + ) X + ' + + SET @sql = ' + INSERT INTO #temp (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Dollars, Units) + SELECT + FDS.DepartmentID, + AccountID, + FiscalYearID, + FiscalMonthID, + ISNULL(Dollars, 0.0) AS Dollars, + ISNULL(Units, 0.0) AS Units + FROM #FinalDataset FDS + ' + 'INNER JOIN #inputDepartments IP ON IP.DepartmentID = FDS.DepartmentID' + ' + ' + @sqlWhere + ' and IP.BatchID = @BatchID + ' + + TRUNCATE TABLE #inputDepartments + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias ='X', + @fromClause = @sqlFromForBatches, + @whereClause = '', + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + SET @SqlParam = '@BatchID INT' + -- Loop thru batches and insert data + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + EXEC sp_executesql @sql, @SqlParam, @BatchID = @BatchID; + SET @BatchID = @BatchID + 1 + END +END +ELSE +BEGIN --Budget + SET @sqlWhere = 'TimeClassID = 2 and (FiscalYearID = ' + cast(@fiscalYearID AS NVARCHAR(4)) + ' or ' + cast(@fiscalYearID AS NVARCHAR(4)) + ' = 0) ' + + TRUNCATE TABLE #inputDepartments + + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'X', + @fromClause = '#FactGLStaging X', + @whereClause = @sqlWhere, + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + INSERT INTO #temp + SELECT GL.DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Dollars, Units + FROM #FactGLStaging GL + INNER JOIN #inputDepartments IP ON IP.DepartmentID = GL.DepartmentID + WHERE TimeClassID = 2 + and (FiscalYearID = @FiscalYearID or @FiscalYearID = 0) and IP.BatchID = @BatchID + + SET @BatchID = @BatchID + 1 + END +END + +SET @sqlWhere = '(FiscalYearID =' + cast(@fiscalYearID AS NVARCHAR(4)) + ' or ' + cast(@fiscalYearID AS NVARCHAR(4)) + ' = 0) and not (Dollars = 0 and Units = 0)' + +TRUNCATE TABLE #inputDepartments +INSERT INTO #inputDepartments +EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'X', + @fromClause = '#temp X', + @whereClause = @sqlWhere, + @isDebug = 0 + +SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments +SET @BatchID = 1 +WHILE @BatchID <= @MaxBatchID +BEGIN + INSERT INTO #FactGLStaging (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Dollars, Units) + SELECT source.DepartmentID, source.AccountID, source.FiscalYearID, source.FiscalMonthID, 20 as TimeClassID, source.Dollars, source.Units + FROM #temp source + INNER JOIN #inputDepartments ID on ID.DepartmentID = source.DepartmentID + WHERE (FiscalYearID = @fiscalYearID or @fiscalYearID = 0) and not (Dollars = 0 and Units = 0) AND ID.BatchID = @BatchID + + SET @BatchID = @BatchID + 1 +END + +IF OBJECT_ID('tempdb..#FiscalYearMonth') IS NOT NULL DROP TABLE #FiscalYearMonth +IF OBJECT_ID('tempdb..#AllCombinations') IS NOT NULL DROP TABLE #AllCombinations +IF OBJECT_ID('tempdb..#FinalDataset') IS NOT NULL DROP TABLE #FinalDataset +DROP TABLE #temp +GO + + +--------------------------------------------- + +-- fw.procFactMonthlyMergeDuplicates +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-02-20 gforeman D-05545 Created +*************************************************************/ +CREATE PROC [fw].[procFactMonthlyMergeDuplicates] + @factTableName nvarchar(100), + @keyNameCSV nvarchar(450), + @measureNameCSV nvarchar(450), + @fiscalYearID smallint = 0, + @timeClassID tinyint = 0, + @isDebugOnly bit = 0 +with recompile +as + set nocount on + + declare @sql nvarchar(max) + + --merge duplicate rows + set @sql = ' + while (exists (select top 1 1 from ' + @factTableName + ' where IsDeleted = 1)) begin delete top(10000) data from ' + @factTableName + ' data where data.IsDeleted = 1 end; + update data set data.IsDeleted = 1 from ' + @factTableName + ' data where ' + (case when @fiscalYearID > 0 then 'data.FiscalYearID between ' + cast((@fiscalYearID-1) as nvarchar(4)) + ' and ' + cast(@fiscalYearID as nvarchar(4)) + ' and ' else '' end) + (case when @timeClassID > 0 then 'data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) + ' and ' else '' end) + ' exists(select 1 from (select DepartmentID, ' + @keyNameCSV + ', FiscalYearID, FiscalMonthID, TimeClassID from ' + @factTableName + ' where (1 = 1)' + (case when @fiscalYearID > 0 then ' and FiscalYearID between ' + cast((@fiscalYearID-1) as nvarchar(4)) + ' and ' + cast(@fiscalYearID as nvarchar(4)) else '' end) + (case when @timeClassID > 0 then ' and TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + ' group by DepartmentID, ' + @keyNameCSV + ', FiscalYearID, FiscalMonthID, TimeClassID having count(*) > 1) dr where dr.DepartmentID = data.DepartmentID and ' + (select dbo.straggr('dr.' + csv.val + ' = data.' + csv.val, ' and ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' and dr.FiscalYearID = data.FiscalYearID and dr.FiscalMonthID = data.FiscalMonthID and dr.TimeClassID = data.TimeClassID); + insert into ' + @factTableName + ' (DepartmentID, ' + @keyNameCSV + ', FiscalYearID, FiscalMonthID, TimeClassID, ' + @measureNameCSV + ') select DepartmentID, ' + @keyNameCSV + ', FiscalYearID, FiscalMonthID, TimeClassID, sum(' + replace(@measureNameCSV, ',', '), sum(') + ') from ' + @factTableName + ' where IsDeleted = 1 group by DepartmentID, ' + @keyNameCSV + ', FiscalYearID, FiscalMonthID, TimeClassID; + while (exists (select top 1 1 from ' + @factTableName + ' where IsDeleted = 1)) begin delete top(10000) data from ' + @factTableName + ' data where data.IsDeleted = 1 end; + ' + if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end +GO + + +--------------------------------------------- + +-- fw.procFactMonthlyYTDPriorYearUpdate +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 +** 2 2018-07-17 KF B-20261 MR - Provider flexing - flexing +*************************************************************/ +CREATE PROC [fw].[procFactMonthlyYTDPriorYearUpdate] + @factTableName nvarchar(100), + @keyNameCSV nvarchar(450), + @measureNameCSV nvarchar(450), + @fiscalYearID smallint = 0, + @timeClassID tinyint = 0, + @isDebugOnly bit = 0 +with recompile +as +set nocount on + + declare @sql nvarchar(max) + + --insert missing records + set @sql = ' + declare @minYear int = ' + cast(@fiscalYearID as nvarchar(4)) + ' + declare @maxYear int = ' + cast(@fiscalYearID as nvarchar(4)) + ' + if (@minYear = 0 or @maxYear = 0) begin + select @minYear = min(data.FiscalYearID) from ' + @factTableName + ' data ' + (case when @timeClassID > 0 then 'where data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + ' + select @maxYear = max(data.FiscalYearID) from ' + @factTableName + ' data ' + (case when @timeClassID > 0 then 'where data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + ' + end + + --records for ytd + insert into ' + @factTableName + ' + ( + ' + @keyNameCSV + ', + DepartmentID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + IsSystemGenerated + ) + SELECT DISTINCT data.' + replace(@keyNameCSV, ',', ',data.') + ',data.DepartmentID,data.FiscalYearID,m.FiscalMonthID,data.TimeClassID,1 + FROM + ' + @factTableName + ' data + inner join fw.DimFiscalMonth mm on mm.FiscalMonthID = data.FiscalMonthID + inner join fw.DimFiscalMonth m on m.SortOrder > mm.SortOrder + where + data.FiscalYearID between @minYear and @maxYear + ' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + ' + and not exists ( --no existing reporting record for this tuple-month + select 1 + from + ' + @factTableName + ' datax + where + (1 = 1) + ' + (select dbo.straggr('AND datax.' + csv.val + ' = data.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' + AND datax.DepartmentID = data.DepartmentID + AND datax.FiscalYearID = data.FiscalYearID + AND datax.FiscalMonthID = m.FiscalMonthID + AND datax.TimeClassID = data.TimeClassID + ) + option (recompile) + + --records for prior year, prior ytd + DECLARE @currentYear INT, @maxYearForPriorYear INT + SELECT @currentYear = Setting FROM dbo.DBSetting WHERE Name = ''Current_GL_YearID'' + SELECT @maxYearForPriorYear = CASE WHEN @maxYear > @currentYear THEN @currentYear ELSE @maxYear END + + insert into ' + @factTableName + ' + ( + ' + @keyNameCSV + ', + DepartmentID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + IsSystemGenerated + ) + SELECT DISTINCT data.' + replace(@keyNameCSV, ',', ',data.') + ',data.DepartmentID,data.FiscalYearID+1,m.FiscalMonthID,data.TimeClassID,1 + FROM + ' + @factTableName + ' data + inner join fw.DimFiscalMonth mm on mm.FiscalMonthID = data.FiscalMonthID + inner join fw.DimFiscalMonth m on m.SortOrder >= mm.SortOrder + where + data.FiscalYearID between @minYear-1 and @maxYearForPriorYear + ' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + ' + and not exists ( --no existing reporting record for this tuple-month + select 1 + from + ' + @factTableName + ' datax + where + (1 = 1) + ' + (select dbo.straggr('AND datax.' + csv.val + ' = data.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' + AND datax.DepartmentID = data.DepartmentID + AND datax.FiscalYearID-1 = data.FiscalYearID + AND datax.FiscalMonthID = m.FiscalMonthID + AND datax.TimeClassID = data.TimeClassID + ) + option (recompile) + ' + if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end + + --populate YTD and prior year measures + set @sql = ' + select + data.DepartmentID, + data.' + replace(@keyNameCSV, ',', ', data.') + ', + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID, + ' + (select dbo.straggr('SUM(data.' + csv.val + ') OVER (PARTITION BY data.DepartmentID,' + @keyNameCSV + ',TimeClassID,FiscalYearID ORDER BY fm.SortOrder) AS ' + csv.val + 'YTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + ' + @measureNameCSV + ' + into #calculatedMeasures + from + ' + @factTableName + ' data + inner join fw.DimFiscalMonth fm on fm.FiscalMonthID=data.FiscalMonthID + where + (1 = 1) + ' + (case when @fiscalYearID > 0 then 'and data.FiscalYearID between ' + cast(@fiscalYearID as nvarchar(4)) + '-1 and ' + cast(@fiscalYearID as nvarchar(4)) else '' end) + ' + ' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + ' + option (recompile) + + CREATE UNIQUE CLUSTERED INDEX IX_calculatedMeasures ON #calculatedMeasures ( ' + @keyNameCSV + ', DepartmentID, FiscalYearID, FiscalMonthID, TimeClassID ) WITH ( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + + update M + set + ' + (select dbo.straggr('m.' + csv.val + 'YTD = cm.' + csv.val + 'YTD', ',', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + from + ' + @factTableName + ' m + INNER JOIN #calculatedMeasures cm ON + M.DepartmentID = cm.DepartmentID + ' + (select dbo.straggr('AND M.' + csv.val + ' = cm.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' + AND M.FiscalMonthID = cm.FiscalMonthID + AND M.TimeClassID = cm.TimeClassID + and m.FiscalYearID = cm.FiscalYearID + where + ' + (select dbo.straggr('m.' + csv.val + 'YTD <> cm.' + csv.val + 'YTD', ' or ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + option (recompile) + + update M + set + ' + (select dbo.straggr('m.' + csv.val + 'PriorYear = cm_py.' + csv.val, ',', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ', + ' + (select dbo.straggr('m.' + csv.val + 'PriorYTD = cm_py.' + csv.val + 'YTD', ',', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + from + ' + @factTableName + ' m + INNER JOIN #calculatedMeasures cm_py ON + M.DepartmentID = cm_py.DepartmentID + ' + (select dbo.straggr('AND M.' + csv.val + ' = cm_py.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' + AND M.FiscalMonthID = cm_py.FiscalMonthID + AND M.TimeClassID = cm_py.TimeClassID + and m.FiscalYearID = cm_py.FiscalYearID+1 + where + ' + (select dbo.straggr('m.' + csv.val + 'PriorYear <> cm_py.' + csv.val, ' or ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' or + ' + (select dbo.straggr('m.' + csv.val + 'PriorYTD <> cm_py.' + csv.val + 'YTD', ' or ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + option (recompile) + + drop table #calculatedMeasures + ' + if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end + + --delete zero records, possible only if YTD aggregates to zero due to negative values + set @sql = ' + delete data + from + ' + @factTableName + ' data + where + ' + (select dbo.straggr('data.' + csv.val + ' = 0 and data.' + csv.val + 'YTD = 0 and data.' + csv.val + 'PriorYear = 0 and data.' + csv.val + 'PriorYTD = 0', ' and ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + ' + if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end +GO + + +--------------------------------------------- + +-- fw.procFactMonthlyYTDPriorYearUpdateStaging +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-06-15 IP B-15086 Modify SP to use unique temp table +** 2 2017-07-13 IP TK-45395 fixed isSystemGenerated for generated records +** 3 2018-07-25 KF B-20342 MR - Update provider sampling to be in the appropriate format +** 4 2018-08-22 KF D-07561 MR Sampling: Provider FTEsYTD values are calculated incorrectly +** 5 2024-06-04 ishah JAZZ-61244 MR - Add batches to procFactMonthlyYTDPriorYearUpdateStaging +*************************************************************/ +CREATE PROCEDURE [fw].[procFactMonthlyYTDPriorYearUpdateStaging] + @factTableName nvarchar(100), + @stagingTableName nvarchar(100), + @keyNameCSV nvarchar(450), + @measureNameCSV nvarchar(450), + @fiscalYearID smallint = 0, + @timeClassID tinyint = 0, + @isDebugOnly bit = 0 +AS + declare @sql nvarchar(max), @sqlJoin nvarchar(max), @sqlClauseForBatches nvarchar(max), @sqlWhere nvarchar(max), @sqlGroupBy nvarchar(max), @sqlParam nvarchar(max), @batchSize INT, @BatchID INT, @MaxBatchID INT + declare @MaxYearForCalculation int= (select max(FiscalYearID) from int.FactStaffing), @maxFiscalYear int + + set @sql = N'SELECT @Output = max(FiscalYearID) FROM '+@stagingTableName+'' + + exec sp_executesql @sql, N'@Output INT OUTPUT', @Output=@maxFiscalYear OUTPUT; + + --insert missing records + set @sql = ' + alter table '+@stagingTableName+' + add SortOrder tinyint + ' + if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end + + declare @isFTEsColumnPresent BIT + IF EXISTS (SELECT val from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') WHERE val = 'FTEs') + SET @isFTEsColumnPresent = 1 + ELSE + SET @isFTEsColumnPresent = 0 + + EXEC mr.procGetIntBatchSize + @DefaultBatchSize = 30000000, + @ResultBatchSize = @batchSize OUTPUT + + SET @sqlClauseForBatches = @stagingTableName + ' X' + + set @sql = ' + UPDATE tp + SET tp.SortOrder = fm.SortOrder + FROM '+@stagingTableName+' tp + INNER JOIN fw.DimFiscalMonth fm ON tp.FiscalMonthID = fm.FiscalMonthID + INNER JOIN #inputDepartments IP ON IP.DepartmentID = tp.DepartmentID + WHERE IP.BatchID = @BatchID + ' + + IF OBJECT_ID('tempdb..#inputDepartments') IS NOT NULL DROP TABLE #inputDepartments + CREATE TABLE #inputDepartments (DepartmentID INT, RecordsCount INT, BatchID INT) + + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias ='X', + @fromClause = @sqlClauseForBatches, + @whereClause = '', + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + SET @SqlParam = '@BatchID INT' + -- Loop thru batches and insert data + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + EXEC sp_executesql @sql, @SqlParam, @BatchID = @BatchID; + SET @BatchID = @BatchID + 1 + END + + IF OBJECT_ID('tempdb..#dimMonth') IS NOT NULL DROP TABLE #dimMonth + CREATE TABLE #dimMonth (FiscalMonthID tinyInt INDEX IX1 CLUSTERED, SortOrder tinyint) + + insert into #dimMonth (FiscalMonthID, SortOrder) + select FiscalMonthID, SortOrder from fw.DimFiscalMonth where FiscalMonthID <> 0 + + --- forming #MinSoTemp table and split by batches + IF OBJECT_ID('tempdb..#MinSoTemp') IS NOT NULL DROP TABLE #MinSoTemp + CREATE TABLE #MinSoTemp (DepartmentID int, FiscalYearID int, TimeClassID int, MinSortOrder int) + + set @sql = ' + alter table #MinSoTemp + add '+ replace(@keyNameCSV, ',', ' INT, ') +' int + ' + + if (@isDebugOnly = 1) begin select @sql end else begin exec(@sql) end + + set @sqlClauseForBatches = ' + ( + '+(select case when @fiscalYearID > 0 THEN ' + SELECT '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID, + min(mm.SortOrder) as MinSortOrder + FROM ' + @factTableName + ' X + INNER JOIN #dimMonth mm + ON mm.FiscalMonthID = x.FiscalMonthID + WHERE FiscalYearID ='+cast(@fiscalYearID-1 as varchar(4))+' + group by '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID + UNION + SELECT '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID, + min(X.SortOrder) as MinSortOrder + FROM '+@stagingTableName+' X + WHERE FiscalYearID ='+cast(@fiscalYearID as varchar(4))+' + group by '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID + + ' else ' + SELECT '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID, + min(X.SortOrder) as MinSortOrder + FROM '+@stagingTableName+' X + group by '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID + ' end )+' + ) X + ' + + SET @sql = ' + INSERT INTO #MinSoTemp ('+ replace(@keyNameCSV, ',', ',') +', DepartmentID, FiscalYearID, TimeClassID, MinSortOrder) + '+(select case when @fiscalYearID > 0 THEN ' + SELECT '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID, + min(mm.SortOrder) as MinSortOrder + FROM ' + @factTableName + ' X + INNER JOIN #dimMonth mm + ON mm.FiscalMonthID = x.FiscalMonthID + ' + 'INNER JOIN #inputDepartments IP ON IP.DepartmentID = X.DepartmentID' + ' + WHERE IP.BatchID = @BatchID AND FiscalYearID ='+cast(@fiscalYearID-1 as varchar(4))+' + group by '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID + UNION + SELECT '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID, + min(X.SortOrder) as MinSortOrder + FROM '+@stagingTableName+' X + ' + 'INNER JOIN #inputDepartments IP ON IP.DepartmentID = X.DepartmentID' + ' + WHERE IP.BatchID = @BatchID AND FiscalYearID ='+cast(@fiscalYearID as varchar(4))+' + group by '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID + + ' else ' + SELECT '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID, + min(X.SortOrder) as MinSortOrder + FROM '+@stagingTableName+' X + ' + 'INNER JOIN #inputDepartments IP ON IP.DepartmentID = X.DepartmentID' + ' + WHERE IP.BatchID = @BatchID + group by '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID + ' end )+' + + ' + + TRUNCATE TABLE #inputDepartments + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias ='X', + @fromClause = @sqlClauseForBatches, + @whereClause = '', + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + SET @SqlParam = '@BatchID INT' + -- Loop thru batches and insert data + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + EXEC sp_executesql @sql, @SqlParam, @BatchID = @BatchID; + SET @BatchID = @BatchID + 1 + END + + --- forming #MinPresentTemp table and split by batches + IF OBJECT_ID('tempdb..#MinPresentTemp') IS NOT NULL DROP TABLE #MinPresentTemp + CREATE TABLE #MinPresentTemp (DepartmentID int, FiscalYearID int, TimeClassID int, MinSortOrder int) + + set @sql = ' + alter table #MinPresentTemp + add '+ replace(@keyNameCSV, ',', ' INT, ') +' int + ' + + if (@isDebugOnly = 1) begin select @sql end else begin exec(@sql) end + + set @sqlJoin = ' + SELECT '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID, + min(X.MinSortOrder) as MinSortOrder + FROM (SELECT '+replace(@keyNameCSV, ',', ',')+', + DepartmentID, + FiscalYearID, + TimeClassID, + MinSortOrder + FROM #MinSoTemp + UNION ALL + SELECT '+replace(@keyNameCSV, ',', ',')+', + DepartmentID, + FiscalYearID+1 as FiscalYearID, + TimeClassID, + MinSortOrder + FROM #MinSoTemp + ) X + ' + + set @sqlWhere = 'where FiscalYearID <= ' + cast(@maxFiscalYear as nvarchar(max)) + set @sqlGroupBy = ' + GROUP BY '+replace(@keyNameCSV, ',', ',')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID + ' + + SET @sqlClauseForBatches = ' + ( ' + @sqlJoin + ' + ' + @sqlWhere + ' + ' + @sqlGroupBy + ' + ) X + ' + + SET @sql = ' + INSERT INTO #MinPresentTemp ('+ replace(@keyNameCSV, ',', ',') +', DepartmentID, FiscalYearID, TimeClassID, MinSortOrder) + ' + @sqlJoin + ' + ' + 'INNER JOIN #inputDepartments IP ON IP.DepartmentID = X.DepartmentID' + ' + ' + @sqlWhere + ' and IP.BatchID = @BatchID + ' + @sqlGroupBy + ' + ' + + TRUNCATE TABLE #inputDepartments + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias ='X', + @fromClause = @sqlClauseForBatches, + @whereClause = '', + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + SET @SqlParam = '@BatchID INT' + -- Loop thru batches and insert data + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + EXEC sp_executesql @sql, @SqlParam, @BatchID = @BatchID; + SET @BatchID = @BatchID + 1 + END + + --- forming #MissingListTemp table and split by batches + IF OBJECT_ID('tempdb..#MissingListTemp') IS NOT NULL DROP TABLE #MissingListTemp + CREATE TABLE #MissingListTemp (DepartmentID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, SortOrder int) + + set @sql = ' + alter table #MissingListTemp + add '+ replace(@keyNameCSV, ',', ' INT, ') +' int + ' + + if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end + + set @sqlJoin = ' + SELECT '+replace(@keyNameCSV, ',', ',')+', + DepartmentID, + FiscalYearID, + mm.FiscalMonthID, + TimeClassID, + unpvt.SortOrder + FROM ( + SELECT '+replace(@keyNameCSV, ',', ',')+', + DepartmentID, + FiscalYearID, + TimeClassID, + [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12], + MinSortOrder + FROM ( + SELECT + isnull(TP.DepartmentID,MP.DepartmentID) as DepartmentID, + ' + (select dbo.straggr('isnull (TP.' + csv.val + ',MP.' + csv.val +') as ' + csv.val+',', ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' + isnull(TP.FiscalYearID,MP.FiscalYearID) as FiscalYearID, + TP.FiscalMonthID as FiscalMonthID, + isnull(TP.TimeClassID,MP.TimeClassID) as TimeClassID, + 0 as '+replace(@measureNameCSV, ',', ', 0 as ')+', + 0 as isDeleted, + 1 as isSystemGenerated, + MP.MinSortOrder, + TP.SortOrder + FROM '+@stagingTableName+' TP + FULL join #MinPresentTemp MP ON + TP.DepartmentID = mp.DepartmentID + ' + (select dbo.straggr('AND TP.' + csv.val + ' = MP.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' + and TP.TimeClassID = mp.TimeClassID + and TP.FiscalYearID = mp.FiscalYearID + where (TP.SortOrder >= mp.MinSortOrder) or TP.SortOrder is null) ss /* there can be a subquery here*/ + PIVOT /* formation of the pivot table*/ + (count(FiscalMonthID) /*is an aggregate function that forms the contents of a pivot table*/ + FOR sortorder IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) Pvt /*alias for the pivot table*/ + ) X + UNPIVOT (isPresent /*the header of the column that will contain the values + from the columns of the source table listed below*/ + FOR SortOrder IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) Unpvt + INNER JOIN #dimMonth mm + ON mm.SortOrder = Unpvt.SortOrder + ' + + set @sqlWhere = 'WHERE isPresent = 0 and Unpvt.SortOrder >= MinSortOrder' + + SET @sqlClauseForBatches = ' + ( ' + @sqlJoin + ' + ' + @sqlWhere + ' + ) X + ' + + SET @sql = ' + INSERT INTO #MissingListTemp ('+ replace(@keyNameCSV, ',', ',') +', DepartmentID, FiscalYearID, FiscalMonthID, TimeClassID, SortOrder) + SELECT '+replace(@keyNameCSV, ',', ',')+', + DepartmentID, + FiscalYearID, + mm.FiscalMonthID, + TimeClassID, + unpvt.SortOrder + FROM ( + SELECT '+replace(@keyNameCSV, ',', ',')+', + DepartmentID, + FiscalYearID, + TimeClassID, + [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12], + MinSortOrder + FROM ( + SELECT + isnull(TP.DepartmentID,MP.DepartmentID) as DepartmentID, + ' + (select dbo.straggr('isnull (TP.' + csv.val + ',MP.' + csv.val +') as ' + csv.val+',', ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' + isnull(TP.FiscalYearID,MP.FiscalYearID) as FiscalYearID, + TP.FiscalMonthID as FiscalMonthID, + isnull(TP.TimeClassID,MP.TimeClassID) as TimeClassID, + 0 as '+replace(@measureNameCSV, ',', ', 0 as ')+', + 0 as isDeleted, + 1 as isSystemGenerated, + MP.MinSortOrder, + TP.SortOrder + FROM '+@stagingTableName+' TP + FULL join #MinPresentTemp MP ON + TP.DepartmentID = mp.DepartmentID + ' + (select dbo.straggr('AND TP.' + csv.val + ' = MP.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' + and TP.TimeClassID = mp.TimeClassID + and TP.FiscalYearID = mp.FiscalYearID + INNER JOIN #inputDepartments IP ON IP.DepartmentID = MP.DepartmentID + where IP.BatchID = @BatchID and (TP.SortOrder >= mp.MinSortOrder) or TP.SortOrder is null) ss /* there can be a subquery here*/ + PIVOT /* formation of the pivot table*/ + (count(FiscalMonthID) /*is an aggregate function that forms the contents of a pivot table*/ + FOR sortorder IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) Pvt /*alias for the pivot table*/ + ) X + UNPIVOT (isPresent /*the header of the column that will contain the values + from the columns of the source table listed below*/ + FOR SortOrder IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) Unpvt + INNER JOIN #dimMonth mm + ON mm.SortOrder = Unpvt.SortOrder + ' + @sqlWhere + ' + ' + + TRUNCATE TABLE #inputDepartments + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias ='X', + @fromClause = @sqlClauseForBatches, + @whereClause = '', + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + SET @SqlParam = '@BatchID INT' + -- Loop thru batches and insert data + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + EXEC sp_executesql @sql, @SqlParam, @BatchID = @BatchID; + SET @BatchID = @BatchID + 1 + END + + --- forming #calculatedMeasuresTemp table and split by batches + IF OBJECT_ID('tempdb..#calculatedMeasuresTemp') IS NOT NULL DROP TABLE #calculatedMeasuresTemp + CREATE TABLE #calculatedMeasuresTemp (DepartmentID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, isSystemGenerated int) + + set @sql = ' + alter table #calculatedMeasuresTemp + add '+ replace(@keyNameCSV, ',', ' INT, ') +' int + ' + + if (@isDebugOnly = 1) begin select @sql end else begin exec(@sql) end + + set @sql = ' + alter table #calculatedMeasuresTemp + add ' + replace(@measureNameCSV, ',', 'YTD decimal (25, 6),') + 'YTD decimal (25, 6)' + ' + ' + + if (@isDebugOnly = 1) begin select @sql end else begin exec(@sql) end + + set @sql = ' + alter table #calculatedMeasuresTemp + add ' + replace(@measureNameCSV, ',', ' decimal (25, 6),') + ' decimal (25, 6)' + ' + ' + + if (@isDebugOnly = 1) begin select @sql end else begin exec(@sql) end + + set @sqlJoin = ' + select + uoag.DepartmentID, + uoag.' + replace(@keyNameCSV, ',', ', uoag.') + ', + uoag.FiscalYearID, + uoag.FiscalMonthID, + uoag.TimeClassID, + ' + (select dbo.straggr('SUM(uoag.' + csv.val + ') OVER (PARTITION BY uoag.DepartmentID,' + @keyNameCSV + ',TimeClassID,FiscalYearID ORDER BY fm.SortOrder) AS ' + csv.val + 'YTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + ' + @measureNameCSV + ', + uoag.isSystemGenerated + from + ( + SELECT + ML.DepartmentID, + ML.' + replace(@keyNameCSV, ',', ', ML.') + ', + ML.FiscalYearID, + ML.FiscalMonthID, + ML.TimeClassID, + 0 as '+replace(@measureNameCSV, ',', ', 0 as ')+', + 1 as isSystemGenerated + FROM #MissingListTemp ML ' + case when @fiscalYearID > 0 then ' where ML.FiscalYearID = ' + cast(@fiscalYearID as nvarchar(4)) else '' end +' + UNION + SELECT data.DepartmentID, + data.' + replace(@keyNameCSV, ',', ', data.') + ', + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID, + ' + @measureNameCSV + ', + data.isSystemGenerated + from '+@stagingTableName+' data + where + (1 = 1) + ' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + ' +' + case when @fiscalYearID > 0 then ' + UNION + SELECT data.DepartmentID, + data.' + replace(@keyNameCSV, ',', ', data.') + ', + data.FiscalYearID, + data.FiscalMonthID, + data.TimeClassID, + ' + @measureNameCSV + ', + 1 as isSystemGenerated + from ' + @factTableName + ' data + where data.FiscalYearID = ' + cast(@fiscalYearID-1 as nvarchar(4)) + case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end + else '' end + ' + + ) uoag -- union ald and generated + inner join #dimMonth fm on fm.FiscalMonthID=uoag.FiscalMonthID + ' + + SET @sqlClauseForBatches = ' + ( ' + @sqlJoin + ' + ) X + ' + + SET @sql = ' + INSERT INTO #calculatedMeasuresTemp (DepartmentID, '+ replace(@keyNameCSV, ',', ',') +', FiscalYearID, FiscalMonthID, TimeClassID, ' + replace(@measureNameCSV, ',', 'YTD,') + 'YTD' + ', ' + replace(@measureNameCSV, ',', ',') + ', isSystemGenerated) + ' + @sqlJoin + ' + ' + 'INNER JOIN #inputDepartments IP ON IP.DepartmentID = uoag.DepartmentID' + ' + WHERE IP.BatchID = @BatchID + ' + + TRUNCATE TABLE #inputDepartments + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias ='X', + @fromClause = @sqlClauseForBatches, + @whereClause = '', + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + SET @SqlParam = '@BatchID INT' + -- Loop thru batches and insert data + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + EXEC sp_executesql @sql, @SqlParam, @BatchID = @BatchID; + SET @BatchID = @BatchID + 1 + END + + -- insert into stagingTableName and spolit by bathes + set @sqlJoin = ' + SELECT + cm.DepartmentID, + cm.' + replace(@keyNameCSV, ',', ',cm.') + ', + cm.FiscalYearID, + cm.FiscalMonthID, + cm.TimeClassID, + ' + (select dbo.straggr('isnull(cm.' + csv.val+',0) as '+ csv.val+',', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) +' + ' + (select dbo.straggr(case when csv.val = 'FTEs' then 'cast(0 as decimal(19, 4))' else 'isnull(cm.' + csv.val+'YTD,0) ' end + 'as '+csv.val+'YTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + ' + (select dbo.straggr('isnull(cm_py.' + csv.val + ',0) as '+ csv.val+'PriorYear,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + ' + (select dbo.straggr(case when csv.val = 'FTEs' then 'cast(0 as decimal(19, 4))' else 'isnull(cm_py.' + csv.val + 'YTD,0) ' end + 'as ' + csv.val + 'PriorYTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + isnull(cm.isSystemGenerated,0) as isSystemGenerated + from #calculatedMeasuresTemp cm + LEFT JOIN #calculatedMeasuresTemp cm_py ON + cm.DepartmentID = cm_py.DepartmentID + ' + (select dbo.straggr('AND cm.' + csv.val + ' = cm_py.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' + AND cm.FiscalMonthID = cm_py.FiscalMonthID + AND cm.TimeClassID = cm_py.TimeClassID + and cm.FiscalYearID = cm_py.FiscalYearID+1 + ' + case when @fiscalYearID > 0 then ' WHERE cm.FiscalYearId = '+cast(@fiscalYearID as varchar(4)) else '' end+' + ' + + set @sqlWhere = ' + WHERE ( + ' + (select dbo.straggr(csv.val+'<>0 ', ' or ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) +' + or ' + (select dbo.straggr(csv.val+'YTD<>0', ' or ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + or ' + (select dbo.straggr(csv.val+'PriorYear<>0', ' or ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + or ' + (select dbo.straggr(csv.val+'PriorYTD<>0', ' or ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + ) + ' + + SET @sqlClauseForBatches = ' + ( + SELECT + PreSelect.*' + case when @isFTEsColumnPresent = 1 then '' else + ', + FTEs=cast(0 as decimal(19, 4)), + FTEsYTD=cast(0 as decimal(19, 4)), + FTEsPriorYear=cast(0 as decimal(19, 4)), + FTEsPriorYTD=cast(0 as decimal(19, 4))'end + + ' + FROM + ( + ' + @sqlJoin + ' + ) PreSelect + ' + @sqlWhere + ' + ) X + ' + + set @sql = ' + CREATE TABLE fw.'+replace(@stagingTableName,'#','')+'WithCalcs + ( + DepartmentID int, + '+ replace(@keyNameCSV, ',', ' INT, ') +' int, + FiscalYearID int, + FiscalMonthID int, + TimeClassID int, + '+ replace(@measureNameCSV, ',', ' decimal(25,6), ') +' decimal(25,6), + ' + (select dbo.straggr(case when csv.val = 'FTEs' then csv.val + 'YTD decimal(19,4),' else csv.val + 'YTD decimal(25,6),' end, '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + '+ replace(@measureNameCSV, ',', 'PriorYear decimal(25,6), ') +'PriorYear decimal(25,6), + ' + (select dbo.straggr(case when csv.val = 'FTEs' then csv.val + 'PriorYTD decimal(19,4),' else csv.val + 'PriorYTD decimal(25,6),' end, '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + isSystemGenerated int' + + case when @isFTEsColumnPresent = 1 then '' else + ', + FTEs decimal(19,4), + FTEsYTD decimal(19,4), + FTEsPriorYear decimal(19,4), + FTEsPriorYTD decimal(19,4)'end + + ' + ) + ' + + if (@isDebugOnly = 1) begin select @sql end else begin exec(@sql) end + + SET @sql = ' + INSERT INTO fw.'+replace(@stagingTableName,'#','')+'WithCalcs + SELECT + PreSelect.*' + case when @isFTEsColumnPresent = 1 then '' else + ', + FTEs=cast(0 as decimal(19, 4)), + FTEsYTD=cast(0 as decimal(19, 4)), + FTEsPriorYear=cast(0 as decimal(19, 4)), + FTEsPriorYTD=cast(0 as decimal(19, 4))'end+ + ' + FROM + ( + ' + @sqlJoin + ' + ) PreSelect + INNER JOIN #inputDepartments IP ON IP.DepartmentID = PreSelect.DepartmentID + ' + @sqlWhere + ' and IP.BatchID = @BatchID + ' + + TRUNCATE TABLE #inputDepartments + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias ='X', + @fromClause = @sqlClauseForBatches, + @whereClause = '', + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + SET @SqlParam = '@BatchID INT' + -- Loop thru batches and insert data + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + EXEC sp_executesql @sql, @SqlParam, @BatchID = @BatchID; + SET @BatchID = @BatchID + 1 + END + + set @sql = 'drop table '+@stagingTableName+' ' + + if (@isDebugOnly = 1) begin select @sql end else begin exec(@sql) end + + IF OBJECT_ID('tempdb..#dimMonth') IS NOT NULL DROP TABLE #dimMonth + IF OBJECT_ID('tempdb..#inputDepartments') IS NOT NULL DROP TABLE #inputDepartments + IF OBJECT_ID('tempdb..#MinSoTemp') IS NOT NULL DROP TABLE #MinSoTemp + IF OBJECT_ID('tempdb..#MinPresentTemp') IS NOT NULL DROP TABLE #MinPresentTemp + IF OBJECT_ID('tempdb..#MissingListTemp') IS NOT NULL DROP TABLE #MissingListTemp + IF OBJECT_ID('tempdb..#calculatedMeasuresTemp') IS NOT NULL DROP TABLE #calculatedMeasuresTemp +GO + + +--------------------------------------------- + +-- fw.procFactPayPeriodMergeDuplicates +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-10-56 gforeman D-05545 Created +*************************************************************/ +create proc [fw].[procFactPayPeriodMergeDuplicates] + @factTableName nvarchar(100), + @keyNameCSV nvarchar(450), + @measureNameCSV nvarchar(450), + @fiscalYearID smallint = 0, + @timeClassID tinyint = 0, + @isDebugOnly bit = 0, + @departmentIDs nvarchar(max) = null +with recompile +as + set nocount on + + declare @sql nvarchar(max) + + --merge duplicate rows + set @sql = ' + while (exists (select top 1 1 from ' + @factTableName + ' where IsDeleted = 1)) begin delete top(10000) data from ' + @factTableName + ' data where data.IsDeleted = 1 end; + update data set data.IsDeleted = 1 from ' + @factTableName + ' data inner join fw.DimPayPeriod pp on pp.PayPeriodID = data.PayPeriodID where ' + (case when @fiscalYearID > 0 then 'pp.FiscalYearIDSecond between ' + cast((@fiscalYearID-1) as nvarchar(4)) + ' and ' + cast(@fiscalYearID as nvarchar(4)) + ' and ' else '' end) + (case when @timeClassID > 0 then 'data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) + ' and ' else '' end) + ' exists(select 1 from (select fd.DepartmentID, fd.' + replace(@keyNameCSV, ',', ', fd.') + ', fd.PayPeriodID, fd.TimeClassID from ' + @factTableName + ' fd inner join fw.DimPayPeriod p on p.PayPeriodID = fd.PayPeriodID where (1 = 1)' + (case when @fiscalYearID > 0 then ' and p.FiscalYearIDSecond between ' + cast((@fiscalYearID-1) as nvarchar(4)) + ' and ' + cast(@fiscalYearID as nvarchar(4)) else '' end) + (case when @timeClassID > 0 then ' and fd.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + ' group by fd.DepartmentID, fd.' + replace(@keyNameCSV, ',', ', fd.') + ', fd.PayPeriodID, fd.TimeClassID having count(*) > 1) dr where dr.DepartmentID = data.DepartmentID and ' + (select dbo.straggr('dr.' + csv.val + ' = data.' + csv.val, ' and ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' and dr.PayPeriodID = data.PayPeriodID and dr.TimeClassID = data.TimeClassID); + insert into ' + @factTableName + ' (DepartmentID, ' + @keyNameCSV + ', PayPeriodID, TimeClassID, ' + @measureNameCSV + ') select DepartmentID, ' + @keyNameCSV + ', PayPeriodID, TimeClassID, sum(' + replace(@measureNameCSV, ',', '), sum(') + ') from ' + @factTableName + ' where IsDeleted = 1 group by DepartmentID, ' + @keyNameCSV + ', PayPeriodID, TimeClassID; + while (exists (select top 1 1 from ' + @factTableName + ' where IsDeleted = 1)) begin delete top(10000) data from ' + @factTableName + ' data where data.IsDeleted = 1 end; + ' + if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end +GO + + +--------------------------------------------- + +-- fw.procFactPayPeriodYTDPriorYearUpdate +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2014-09-09 gforeman B-02162 Added merge rows step +** 2 2014-09-09 gforeman B-02162 Run prior year when year specified +** 3 2014-09-18 gforeman B-02682 Additional speedups to insert missing step +** 4 2015-09-14 mschmitz B-08303 Added PayCycleID to partition and indexing +** 5 2015-10-13 nleroy D-03496 FTEsYTD fix +** 6 2015-10-20 mschmitz B-08303 Fixed bug found related to B-08303 change +** 7 2016-03-23 mholov D-04105 Added rolling delete on fact Table +** 8 2016-07-28 akozlov D-04262 Added IsSystemGenerated flag setting for inserted records +** 9 2016-09-48 gforeman D-04759 Optimize YTD calc +** 10 2016-09-26 akozlov D-04899 Reverted optimization +** 11 2016-09-26 akozlov D-04899 Fixed performance bug +** 12 2016-10-10 gforeman D-05000 Add IsSystemGenerated reset +** 13 2016-12-27 akozlov D-05183 Removed IsSystemGenerated reset +** 14 2017-01-23 gforeman D-05419 Misc perf improvements, add department parameter +** 15 2017-02-17 gforeman B-14308 Temp table tuning +** 16 2017-02-20 gforeman D-05545 Move duplicate record handling from YTD into sampling +** 17 2018-11-07 KF D-06432 PR - YTD Labor Expense PR Metrics Do Not Match Payroll +** 18 2022-03-01 KF JAZZ-13874 Stored procedure fw.procFactPayPeriodYTDPriorYearUpdate is timing out +** 19 2024-01-29 KF JAZZ-66821 Run PR Process Task: Some procs don't support non-consecutive pay period id (expect consecutive pay period id). It causes wrong YTD values & wrong Rolling Average Baseline Target values +*************************************************************/ +CREATE proc [fw].[procFactPayPeriodYTDPriorYearUpdate] + @factTableName nvarchar(100), + @keyNameCSV nvarchar(450), + @measureNameCSV nvarchar(450), + @fiscalYearID smallint = 0, + @timeClassID tinyint = 0, + @isDebugOnly bit = 0, + @departmentIDs nvarchar(max) = null +with recompile +as + set nocount on + + declare @sql nvarchar(max) + + --insert missing records + set @sql = ' + declare @minYear int = ' + cast(@fiscalYearID as nvarchar(4)) + ' + declare @maxYear int = ' + cast(@fiscalYearID as nvarchar(4)) + ' + if (@minYear <= 0 or @maxYear <= 0) begin + select @minYear = min(pp.FiscalYearIDSecond) from ' + @factTableName + ' data INNER JOIN fw.DimPayPeriod pp ON data.PayPeriodID = pp.PayPeriodID ' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + (case when @departmentIDs is not null then ' and data.DepartmentID in(select val from ConvertCSValuesToTable(''' + @departmentIDs + ''', '',''))' else '' end) + ' + select @maxYear = max(pp.FiscalYearIDSecond) from ' + @factTableName + ' data INNER JOIN fw.DimPayPeriod pp ON data.PayPeriodID = pp.PayPeriodID ' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + (case when @departmentIDs is not null then ' and data.DepartmentID in(select val from ConvertCSValuesToTable(''' + @departmentIDs + ''', '',''))' else '' end) + ' + end + + --records for ytd + insert into ' + @factTableName + ' + ( + DepartmentID, + ' + @keyNameCSV + ', + PayPeriodID, + TimeClassID, + IsSystemGenerated + ) + SELECT DISTINCT data.DepartmentID,data.' + replace(@keyNameCSV, ',', ',data.') + ',p.PayPeriodID,data.TimeClassID,1 + FROM + ' + @factTableName + ' data + ' + (case when @departmentIDs is not null then 'inner join (select val as DepartmentID from ConvertCSValuesToTable(''' + @departmentIDs + ''', '','')) dept on dept.DepartmentID = data.DepartmentID' else '' end) + ' + inner join fw.DimPayPeriod pp ON data.PayPeriodID = pp.PayPeriodID + inner join fw.DimPayCycle pc on pc.PayCycleID = pp.PayCycleID + inner join pi.viewNextAfterCurrentPayPeriod npp on npp.PayCycleID = pc.PayCycleID + inner join fw.DimPayPeriod p on p.FiscalYearIDSecond = pp.FiscalYearIDSecond and p.PayCycleID = pp.PayCycleID and p.PeriodNumber > pp.PeriodNumber and p.FiscalYearIDSecond <= npp.FiscalYearIDSecond + left join dbo.ColumnStoreIndex csi ON 1=0 -- tricky fix for JAZZ-13874 + where + pp.FiscalYearIDSecond between @minYear and @maxYear + ' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + ' + and not exists ( --existing record for this tuple-payperiod + select 1 + from + ' + @factTableName + ' datax + where + datax.DepartmentID = data.DepartmentID + ' + (select dbo.straggr('AND datax.' + csv.val + ' = data.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' + AND datax.PayPeriodID = p.PayPeriodID + AND datax.TimeClassID = data.TimeClassID + ) + option (recompile) + + --records for prior year, prior ytd + insert into ' + @factTableName + ' + ( + DepartmentID, + ' + @keyNameCSV + ', + PayPeriodID, + TimeClassID, + IsSystemGenerated + ) + SELECT DISTINCT data.DepartmentID,data.' + replace(@keyNameCSV, ',', ',data.') + ',p.PayPeriodID,data.TimeClassID,1 + FROM + ' + @factTableName + ' data + ' + (case when @departmentIDs is not null then 'inner join (select val as DepartmentID from ConvertCSValuesToTable(''' + @departmentIDs + ''', '','')) dept on dept.DepartmentID = data.DepartmentID' else '' end) + ' + inner join fw.DimPayPeriod pp ON data.PayPeriodID = pp.PayPeriodID + inner join fw.DimPayCycle pc on pc.PayCycleID = pp.PayCycleID + inner join pi.viewNextAfterCurrentPayPeriod npp on npp.PayCycleID = pc.PayCycleID + inner join fw.DimPayPeriod p on p.FiscalYearIDSecond = pp.FiscalYearIDSecond+1 and p.PayCycleID = pp.PayCycleID and p.PeriodNumber >= pp.PeriodNumber and p.FiscalYearIDSecond <= npp.FiscalYearIDSecond + left join dbo.ColumnStoreIndex csi ON 1=0 -- tricky fix for JAZZ-13874 + where + pp.FiscalYearIDSecond between @minYear-1 and @maxYear-1 + ' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + ' + and not exists ( --existing record for this tuple-payperiod + select 1 + from + ' + @factTableName + ' datax + where + datax.DepartmentID = data.DepartmentID + ' + (select dbo.straggr('AND datax.' + csv.val + ' = data.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' + AND datax.PayPeriodID = p.PayPeriodID + AND datax.TimeClassID = data.TimeClassID + ) + option (recompile) + ' + if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end + + --populate YTD and prior year measures + set @sql = ' + select + data.DepartmentID, + data.' + replace(@keyNameCSV, ',', ',data.') + ', + pp.PayCycleID, + pp.FiscalYearIDSecond, + pp.PeriodNumber, + data.TimeClassID, + ' + (select dbo.straggr('SUM(data.' + csv.val + ') OVER (PARTITION BY data.DepartmentID,' + @keyNameCSV + ',TimeClassID,pp.PayCycleID,FiscalYearIDSecond ORDER BY pp.PayCycleID, pp.FiscalYearIDSecond, pp.PeriodNumber) AS ' + csv.val + 'YTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + ' + @measureNameCSV + ' + into #calculatedMeasures + from + ' + @factTableName + ' data + ' + (case when @departmentIDs is not null then 'inner join (select val as DepartmentID from ConvertCSValuesToTable(''' + @departmentIDs + ''', '','')) dept on dept.DepartmentID = data.DepartmentID' else '' end) + ' + inner join fw.DimPayPeriod pp on pp.PayPeriodID=data.PayPeriodID + where + (1 = 1) + ' + (case when @fiscalYearID > 0 then 'and pp.FiscalYearIDSecond between ' + cast(@fiscalYearID as nvarchar(4)) + '-1 and ' + cast(@fiscalYearID as nvarchar(4)) else '' end) + ' + ' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + ' + option (recompile) + + CREATE UNIQUE CLUSTERED INDEX IX_calculatedMeasures ON #calculatedMeasures ( DepartmentID, ' + @keyNameCSV + ', PayCycleID, FiscalYearIDSecond, PeriodNumber, TimeClassID ) WITH ( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] + + update M + set + ' + (select dbo.straggr('m.' + csv.val + 'YTD = cm.' + csv.val + 'YTD', ',', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + from + ' + @factTableName + ' m + inner join fw.DimPayPeriod pp on pp.PayPeriodID=m.PayPeriodID + INNER JOIN #calculatedMeasures cm ON + M.DepartmentID = cm.DepartmentID + ' + (select dbo.straggr('AND M.' + csv.val + ' = cm.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' + AND pp.PayCycleID = cm.PayCycleID + AND pp.FiscalYearIDSecond = cm.FiscalYearIDSecond + AND pp.PeriodNumber = cm.PeriodNumber + AND M.TimeClassID = cm.TimeClassID + where + ' + (select dbo.straggr('m.' + csv.val + 'YTD <> cm.' + csv.val + 'YTD', ' or ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + option (recompile) + + update M + set + ' + (select dbo.straggr('m.' + csv.val + 'PriorYear = cm_py.' + csv.val, ',', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ', + ' + (select dbo.straggr('m.' + csv.val + 'PriorYTD = cm_py.' + csv.val + 'YTD', ',', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + from + ' + @factTableName + ' m + inner join fw.DimPayPeriod pp on pp.PayPeriodID=m.PayPeriodID + INNER JOIN #calculatedMeasures cm_py ON + M.DepartmentID = cm_py.DepartmentID + ' + (select dbo.straggr('AND M.' + csv.val + ' = cm_py.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' + AND pp.PayCycleID = cm_py.PayCycleID + AND pp.FiscalYearIDSecond = cm_py.FiscalYearIDSecond+1 + AND pp.PeriodNumber = cm_py.PeriodNumber + AND M.TimeClassID = cm_py.TimeClassID + where + ' + (select dbo.straggr('m.' + csv.val + 'PriorYear <> cm_py.' + csv.val, ' or ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' or + ' + (select dbo.straggr('m.' + csv.val + 'PriorYTD <> cm_py.' + csv.val + 'YTD', ' or ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + option (recompile) + + drop table #calculatedMeasures + ' + if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end + + --delete zero records, possible only if YTD aggregates to zero due to negative values + set @sql = ' + delete data + from + ' + @factTableName + ' data + where + ' + (select dbo.straggr('data.' + csv.val + ' = 0 and data.' + csv.val + 'YTD = 0 and data.' + csv.val + 'PriorYear = 0 and data.' + csv.val + 'PriorYTD = 0', ' and ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + ' + if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end +GO + + +--------------------------------------------- + +-- fw.procFactPayPeriodYTDPriorYearUpdate_AG +/*************************************************************** +** CID Date Author WI Description +** 1 2017-06-09 ipetriv TK-44047 fixing one-year integraion test for fw_procPayrollSampledDailyDetailedInsert +** 2 2017-06-15 IP B-15086 Modify SP to use unique temp table +** 3 2019-08-21 vfay D-08311 PR Sampling Proc : removed filtering out 0 Value Rows +** 4 2023-10-18 KF JAZZ-62485 Technical - Update procs to support 7 days pay periods for Pay Period and Daily +** 5 2024-01-29 KF JAZZ-66821 Run PR Process Task: Some procs don't support non-consecutive pay period id (expect consecutive pay period id). It causes wrong YTD values & wrong Rolling Average Baseline Target values +** 6 2024-02-08 KF JAZZ-67258 Current year runs of the Run PR Process Task have been failing. +** 7 2024-02-12 HV JAZZ-15888 [fw].[procPayrollSampledPayPeriodInsert]: YTD records are not sampled properly for TimeClassID=20 when run proc for all years and Target Basis=Rolling Average +**************************************************************/ +CREATE PROC [fw].[procFactPayPeriodYTDPriorYearUpdate_AG] + @factTableName nvarchar(100), + @stagingTableName varchar(100), + @keyNameCSV nvarchar(450), + @measureNameCSV nvarchar(450), + @fiscalYearID smallint = 0, + @timeClassID tinyint = 0, + @isDebugOnly bit = 0 +as +set nocount on + + declare @sql nvarchar(max) + declare @MaxYearForCalculation int= (select max(FiscalYearID) from int.FactStaffing) + declare @PeriodsList nvarchar(max) = '' + select @PeriodsList = @PeriodsList+',['+cast(PeriodNumber as varchar(3))+']' FROM (select distinct PeriodNumber from fw.DimPayPeriod where PeriodNumber <> 0) PN + set @PeriodsList = SUBSTRING(@PeriodsList,2,LEN(@PeriodsList)-1) + + /*insert missing records*/ + set @sql = ' + alter table '+@stagingTableName+' + add PeriodNumber int + + alter table '+@stagingTableName+' + add FiscalYearID int + + ALTER TABLE '+@stagingTableName+' + ADD PayCycleID int + ' + if (@isDebugOnly = 1) begin print @sql end else begin exec(@sql) end + + set @sql = ' + UPDATE tp + SET tp.PeriodNumber = fm.PeriodNumber, + tp.FiscalYearID = fm.FiscalYearIDSecond, + tp.PayCycleID = d.PayCycleID + FROM '+@stagingTableName+' tp + INNER JOIN fw.DimPayPeriod fm + ON tp.PayPeriodID = fm.PayPeriodID + INNER JOIN fw.DimDepartment d + ON tp.DepartmentID = d.DepartmentID + + CREATE TABLE #dimPayPeriod (PayPeriodID INT,FiscalYearID int, PeriodNumber TINYINT, PayCycleID int, UNIQUE CLUSTERED (PeriodNumber,FiscalYearID,PayCycleID)) + + INSERT INTO #dimPayPeriod + SELECT dpp.PayPeriodID, dpp.FiscalYearIDSecond, dpp.PeriodNumber, dpp.PayCycleID + FROM fw.DimPayPeriod dpp + inner join pi.viewNextAfterCurrentPayPeriod npp on dpp.PayCycleID = npp.PayCycleID and dpp.FiscalYearIDSecond <= npp.FiscalYearIDSecond + WHERE PayPeriodID <> 0; + + ;WITH MinSO as ('+(select case when @fiscalYearID > 0 THEN ' + SELECT '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + mm.FiscalYearID, + X.TimeClassID, + min(mm.PeriodNumber) as MinPeriodNumber + FROM ' + @factTableName + ' X + INNER JOIN #dimPayPeriod mm + ON mm.PayPeriodID = x.PayPeriodID + WHERE FiscalYearID ='+cast(@fiscalYearID-1 as varchar(4))+' + group by '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + mm.FiscalYearID, + X.TimeClassID + UNION + SELECT '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID, + min(X.PeriodNumber) as MinPeriodNumber + FROM '+@stagingTableName+' X + WHERE FiscalYearID ='+cast(@fiscalYearID as varchar(4))+' + group by '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID + + ' else ' + SELECT '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID, + min(X.PeriodNumber) as MinPeriodNumber + FROM '+@stagingTableName+' X + group by '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID + ' end )+') + ,MinPresent as ( + + SELECT '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID, + dd.PayCycleID, + min(X.MinPeriodNumber) as MinPeriodNumber + FROM (SELECT '+replace(@keyNameCSV, ',', ',')+', + DepartmentID, + FiscalYearID, + TimeClassID, + MinPeriodNumber + FROM MinSO + UNION ALL + SELECT '+replace(@keyNameCSV, ',', ',')+', + DepartmentID, + FiscalYearID+1 as FiscalYearID, + TimeClassID, + MinPeriodNumber + FROM MinSO + ) X + inner join fw.DimDepartment dd on dd.DepartmentID = x.DepartmentID + where FiscalYearID <= (SELECT max(FiscalYearID) FROM '+@stagingTableName+') + GROUP BY '+replace(@keyNameCSV, ',', ',')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID, + dd.PayCycleID + ) + + ,MissingList AS ( + SELECT '+replace(@keyNameCSV, ',', ',')+', + DepartmentID, + Unpvt.FiscalYearID, + mm.PayPeriodID, + TimeClassID, + unpvt.PeriodNumber + FROM ( + SELECT '+replace(@keyNameCSV, ',', ',')+', + DepartmentID, + FiscalYearID, + TimeClassID, + PayCycleID, + '+@PeriodsList+', + MinPeriodNumber + FROM ( + SELECT + isnull(TP.DepartmentID,MP.DepartmentID) as DepartmentID, + ' + (select dbo.straggr('isnull (TP.' + csv.val + ',MP.' + csv.val +') as ' + csv.val+',', ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' + isnull(TP.FiscalYearID,MP.FiscalYearID) as FiscalYearID, + TP.PayPeriodID as PayPeriodID, + isnull(TP.PayCycleID,MP.PayCycleID) as PayCycleID, + isnull(TP.TimeClassID,MP.TimeClassID) as TimeClassID, + 0 as '+replace(@measureNameCSV, ',', ', 0 as ')+', + 0 as isDeleted, + 1 as isSystemGenerated, + MP.MinPeriodNumber, + isnull(TP.PeriodNumber,mp.MinPeriodNumber) as PeriodNumber + FROM '+@stagingTableName+' TP + FULL join MinPresent MP ON + TP.DepartmentID = mp.DepartmentID + ' + (select dbo.straggr('AND TP.' + csv.val + ' = MP.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' + and TP.TimeClassID = mp.TimeClassID + and TP.FiscalYearID = mp.FiscalYearID + where (TP.PeriodNumber >= mp.MinPeriodNumber) or TP.PeriodNumber is null) ss /* there can be a subquery here*/ + PIVOT /*formation of the pivot table*/ + (count(PayPeriodID) /*is an aggregate function that forms the contents of a pivot table*/ + FOR PeriodNumber IN ('+@PeriodsList+')) Pvt /* alias for the pivot table*/ + ) X + UNPIVOT (isPresent /* the header of the column that will contain the values + from the columns of the source table listed below*/ + FOR PeriodNumber IN ('+@PeriodsList+')) Unpvt + INNER JOIN #dimPayPeriod mm + ON mm.PeriodNumber = Unpvt.PeriodNumber + and mm.FiscalYearID = Unpvt.FiscalYearID + and mm.PayCycleID = unpvt.PayCycleID + WHERE isPresent = 0 and Unpvt.PeriodNumber >= MinPeriodNumber) + + + , calculatedMeasures as ( + select + uoag.DepartmentID, + uoag.' + replace(@keyNameCSV, ',', ', uoag.') + ', + uoag.FiscalYearID, + uoag.PayPeriodID, + pp.PayCycleID, + uoag.TimeClassID, + pp.PeriodNumber, + ' + (select dbo.straggr('SUM(uoag.' + csv.val + ') OVER (PARTITION BY uoag.DepartmentID,' + @keyNameCSV + ',TimeClassID,FiscalYearID,pp.PayCycleID ORDER BY pp.PeriodNumber) AS ' + csv.val + 'YTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + ' + @measureNameCSV + ', + uoag.isSystemGenerated + from + ( + SELECT + ML.DepartmentID, + ML.' + replace(@keyNameCSV, ',', ', ML.') + ', + ML.FiscalYearID, + ML.PayPeriodID, + ML.TimeClassID, + 0 as '+replace(@measureNameCSV, ',', ', 0 as ')+', + 1 as isSystemGenerated + FROM MissingList ML ' + case when @fiscalYearID > 0 then ' where ML.FiscalYearID = ' + cast(@fiscalYearID as nvarchar(4)) else '' end +' + UNION + SELECT data.DepartmentID, + data.' + replace(@keyNameCSV, ',', ', data.') + ', + data.FiscalYearID, + data.PayPeriodID, + data.TimeClassID, + ' + @measureNameCSV + ', + data.isSystemGenerated + from '+@stagingTableName+' data + where + (1 = 1) + ' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + '' + case when @fiscalYearID > 0 then ' + UNION + SELECT data.DepartmentID, + data.' + replace(@keyNameCSV, ',', ', data.') + ', + mm.FiscalYearID, + data.PayPeriodID, + data.TimeClassID, + ' + @measureNameCSV + ', + data.isSystemGenerated + from ' + @factTableName + ' data + INNER JOIN #dimPayPeriod mm + ON mm.PayPeriodID = data.PayPeriodID + where mm.FiscalYearID = ' + cast(@fiscalYearID-1 as nvarchar(4)) + case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end + else '' end + ' + + ) uoag /* union ald and generated*/ + inner join fw.dimPayPeriod pp on uoag.PayPeriodID = pp.PayPeriodID + ) + + SELECT + PreSelect.* + INTO fw.'+replace(@stagingTableName,'#','')+'WithCalcs + FROM ( + SELECT + cm.DepartmentID, + cm.' + replace(@keyNameCSV, ',', ',cm.') + ', + cm.FiscalYearID, + cm.PayPeriodID, + cm.TimeClassID, + ' + (select dbo.straggr('isnull(cm.' + csv.val+',0) as '+ csv.val+',', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) +' + ' + (select dbo.straggr('isnull(cm.' + csv.val+'YTD,0) as '+csv.val+'YTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + ' + (select dbo.straggr('isnull(cm_py.' + csv.val + ',0) as '+ csv.val+'PriorYear,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + ' + (select dbo.straggr('isnull(cm_py.' + csv.val + 'YTD,0) as ' + csv.val + 'PriorYTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + isnull(cm.isSystemGenerated,0) as isSystemGenerated + from calculatedMeasures cm + LEFT JOIN calculatedMeasures cm_py ON + cm.DepartmentID = cm_py.DepartmentID + ' + (select dbo.straggr('AND cm.' + csv.val + ' = cm_py.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' + AND cm.PeriodNumber = cm_py.PeriodNumber + AND cm.PayCycleID = cm_py.PayCycleID + AND cm.TimeClassID = cm_py.TimeClassID + and cm.FiscalYearID = cm_py.FiscalYearID+1 + ' + case when @fiscalYearID > 0 then ' WHERE cm.FiscalYearId = '+cast(@fiscalYearID as varchar(4)) else '' end+' + ) PreSelect + WHERE NOT(' + (select dbo.straggr(csv.val+'=0', ' and ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) +' + and ' + (select dbo.straggr(csv.val + 'YTD=0', ' and ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + and ' + (select dbo.straggr(csv.val + 'PriorYear=0', ' and ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + and ' + (select dbo.straggr(csv.val + 'PriorYTD=0', ' and ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + and isSystemGenerated = 1) + UNION ALL + SELECT + data.DepartmentID, + data.' + replace(@keyNameCSV, ',', ', data.') + ', + data.FiscalYearID, + data.PayPeriodID, + data.TimeClassID, + ' + (select dbo.straggr(csv.val+',', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) +' + ' + (select dbo.straggr(csv.val+'YTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + ' + (select dbo.straggr(csv.val+'PriorYear,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + ' + (select dbo.straggr(csv.val+'PriorYTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + data.isSystemGenerated + from '+@stagingTableName+' data + WHERE TimeClassID <> 20 + + drop table '+@stagingTableName+' + ' + if (@isDebugOnly = 1) begin select @sql end else begin exec(@sql) end +GO + + +--------------------------------------------- + +-- fw.procFactPayPeriodYTDPriorYearUpdate_Staging +/************************************************************** +** Change History +************************************************************** +** 1 2017-06-15 IP B-15086 Modify SP to use unique temp table +** 2 2017-07-13 IP TK-45395 fixed isSystemGenerated for generated records +** 3 2017-09-20 IP TK-48127 fixed taking only Timeclasses 1,2,20 (excepted 4) +** 4 2018-08-10 OV B-19715 added condition IsPR = 1 for jobcode +** 5 2018-09-20 OV B-20797 fixed @isJobCodeIDColumnPresent value +** 6 2018-11-05 KF D-06432 PR - YTD Labor Expense PR Metrics Do Not Match Payroll +** 7 2019-08-21 vfay D-08586 PR Sampling Proc : removed filtering out 0 Value Rows +** 8 2020-12-09 HV JAZZ-11135 Remove table variable in procPayrollSampledPayPeriodDetailedInsert +** 9 2020-12-21 HV JAZZ-10222 Proc procPayrollSampledPayPeriodDetailedInsert is timing out +** 10 2022-04-12 HV JAZZ-35448 Remove PR Feature Flag +** 11 2023-10-18 KF JAZZ-62485 Technical - Update procs to support 7 days pay periods for Pay Period and Daily +** 12 2024-01-29 KF JAZZ-66821 Run PR Process Task: Some procs don't support non-consecutive pay period id (expect consecutive pay period id). It causes wrong YTD values & wrong Rolling Average Baseline Target values +** 13 2024-02-08 KF JAZZ-67258 Current year runs of the Run PR Process Task have been failing. +*************************************************************/ +CREATE PROC [fw].[procFactPayPeriodYTDPriorYearUpdate_Staging] + @factTableName nvarchar(100), + @stagingTableName nvarchar(100), + @keyNameCSV nvarchar(450), + @measureNameCSV nvarchar(450), + @fiscalYearID smallint = 0, + @timeClassID tinyint = 0, + @isDebugOnly bit = 0 +as +set nocount on + + declare @sql nvarchar(max) + declare @MaxYearForCalculation int= (select max(FiscalYearID) from int.FactStaffing) + declare @PeriodsList nvarchar(max) = '' + select @PeriodsList = @PeriodsList+',['+cast(PeriodNumber as varchar(3))+']' FROM (select distinct PeriodNumber from fw.DimPayPeriod where PeriodNumber <> 0 ) PN + set @PeriodsList = SUBSTRING(@PeriodsList,2,LEN(@PeriodsList)-1) + declare @isJobCodeIDColumnPresent BIT + IF EXISTS (SELECT val from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') WHERE val = 'JobCodeID') + SET @isJobCodeIDColumnPresent = 1 + ELSE + SET @isJobCodeIDColumnPresent = 0 + + set @sql = ' + IF OBJECT_ID(''tempdb..' + @stagingTableName + 'Updated'') IS NOT NULL DROP TABLE ' + @stagingTableName + 'Updated + create table ' + @stagingTableName + 'Updated ( + DepartmentID int, + '+replace(@keyNameCSV, ',', ' int,')+' int, + PayPeriodID int, + TimeClassID int, + '+replace(@measureNameCSV, ',', ' decimal(18, 6),')+' decimal(18, 6), + isDeleted bit default (0), + isSystemGenerated bit default(0), + PeriodNumber int, + FiscalYearID int, + PayCycleID int) + + insert INTO ' + @stagingTableName + 'Updated + SELECT + tp.DepartmentID, + tp.' + replace(@keyNameCSV, ',', ', tp.') + ', + tp.PayPeriodID, + tp.TimeClassID, + tp.' + replace(@measureNameCSV, ',', ', tp.') + ', + tp.isDeleted, + tp.isSystemGenerated, + fm.PeriodNumber, + fm.FiscalYearIDSecond, + d.PayCycleID + FROM ' + @stagingTableName + ' tp + INNER JOIN fw.DimPayPeriod fm ON tp.PayPeriodID = fm.PayPeriodID + INNER JOIN fw.DimDepartment d ON tp.DepartmentID = d.DepartmentID + + IF OBJECT_ID(''tempdb..' + @stagingTableName + ''') IS NOT NULL DROP TABLE ' + @stagingTableName + ' + + IF OBJECT_ID(''tempdb..#dimPayPeriod'') IS NOT NULL DROP TABLE #dimPayPeriod + CREATE TABLE #dimPayPeriod (PayPeriodID INT,FiscalYearID int, PeriodNumber TINYINT, PayCycleID int, UNIQUE CLUSTERED (PeriodNumber,FiscalYearID,PayCycleID)) + + INSERT INTO #dimPayPeriod + SELECT dpp.PayPeriodID, dpp.FiscalYearIDSecond, dpp.PeriodNumber, dpp.PayCycleID + FROM fw.DimPayPeriod dpp + INNER JOIN pi.viewNextAfterCurrentPayPeriod npp on npp.PayCycleID = dpp.PayCycleID + WHERE dpp.PayPeriodID <> 0 AND dpp.FiscalYearIDSecond <= npp.FiscalYearIDSecond + ORDER BY dpp.PayCycleID, dpp.FiscalYearIDSecond, dpp.PeriodNumber + + IF OBJECT_ID(''tempdb..#MinSO'') IS NOT NULL DROP TABLE #MinSO + CREATE TABLE #MinSO ( + '+replace(@keyNameCSV, ',', ' int,')+' int, + DepartmentID int, + FiscalYearID int, + TimeClassID int, + MinPeriodNumber int) + INSERT INTO #MinSO('+@keyNameCSV+', DepartmentID, FiscalYearID, TimeClassID, MinPeriodNumber)'+(select case when @fiscalYearID > 0 THEN ' + SELECT '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + mm.FiscalYearID, + X.TimeClassID, + min(mm.PeriodNumber) as MinPeriodNumber + FROM ' + @factTableName + ' X + INNER JOIN #dimPayPeriod mm + ON mm.PayPeriodID = x.PayPeriodID + WHERE FiscalYearID ='+cast(@fiscalYearID-1 as varchar(4))+' + group by '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + mm.FiscalYearID, + X.TimeClassID + UNION + SELECT '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID, + min(X.PeriodNumber) as MinPeriodNumber + FROM ' + @stagingTableName + 'Updated X + WHERE FiscalYearID ='+cast(@fiscalYearID as varchar(4))+' + group by '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID + + ' else ' + SELECT '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID, + min(X.PeriodNumber) as MinPeriodNumber + FROM ' + @stagingTableName + 'Updated X + group by '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID + ' end )+' + IF OBJECT_ID(''tempdb..#MinPresent'') IS NOT NULL DROP TABLE #MinPresent' + + set @sql = @sql + ' + create table #MinPresent ( + '+replace(@keyNameCSV, ',', ' int,')+' int, + DepartmentID int, + FiscalYearID int, + TimeClassID int, + PayCycleID int, + MinPeriodNumber int) + INSERT INTO #MinPresent('+@keyNameCSV+', DepartmentID, FiscalYearID, TimeClassID, PayCycleID, MinPeriodNumber) + SELECT '+replace(@keyNameCSV, ',', ',X.')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID, + dd.PayCycleID, + min(X.MinPeriodNumber) as MinPeriodNumber + FROM (SELECT '+replace(@keyNameCSV, ',', ',')+', + DepartmentID, + FiscalYearID, + TimeClassID, + MinPeriodNumber + FROM #MinSO + UNION ALL + SELECT '+replace(@keyNameCSV, ',', ',')+', + DepartmentID, + FiscalYearID+1 as FiscalYearID, + TimeClassID, + MinPeriodNumber + FROM #MinSO + ) X + inner join fw.DimDepartment dd on dd.DepartmentID = x.DepartmentID + where FiscalYearID <= (SELECT max(FiscalYearID) FROM ' + @stagingTableName + 'Updated) + and TimeClassID in (1,2,20) + GROUP BY '+replace(@keyNameCSV, ',', ',')+', + X.DepartmentID, + X.FiscalYearID, + X.TimeClassID, + dd.PayCycleID + + IF OBJECT_ID(''tempdb..#MinSO'') IS NOT NULL DROP TABLE #MinSO + IF OBJECT_ID(''tempdb..#MissingList'') IS NOT NULL DROP TABLE #MissingList + CREATE TABLE #MissingList ( + '+replace(@keyNameCSV, ',', ' int,')+' int, + DepartmentID int, + FiscalYearID int, + PayPeriodID int, + TimeClassID int, + PeriodNumber int) + INSERT INTO #MissingList ('+@keyNameCSV+', DepartmentID, FiscalYearID, PayPeriodID, TimeClassID, PeriodNumber) + SELECT '+replace(@keyNameCSV, ',', ',')+', + DepartmentID, + Unpvt.FiscalYearID, + mm.PayPeriodID, + TimeClassID, + unpvt.PeriodNumber + FROM ( + SELECT '+replace(@keyNameCSV, ',', ',')+', + DepartmentID, + FiscalYearID, + TimeClassID, + PayCycleID, + '+@PeriodsList+', + MinPeriodNumber + FROM ( + SELECT + isnull(TP.DepartmentID,MP.DepartmentID) as DepartmentID, + ' + (select dbo.straggr('isnull (TP.' + csv.val + ',MP.' + csv.val +') as ' + csv.val+',', ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' + isnull(TP.FiscalYearID,MP.FiscalYearID) as FiscalYearID, + TP.PayPeriodID as PayPeriodID, + isnull(TP.PayCycleID,MP.PayCycleID) as PayCycleID, + isnull(TP.TimeClassID,MP.TimeClassID) as TimeClassID, + 0 as '+replace(@measureNameCSV, ',', ', 0 as ')+', + 0 as isDeleted, + 1 as isSystemGenerated, + MP.MinPeriodNumber, + isnull(TP.PeriodNumber,mp.MinPeriodNumber) as PeriodNumber + FROM ' + @stagingTableName + 'Updated TP + FULL join #MinPresent MP ON + TP.DepartmentID = mp.DepartmentID + ' + (select dbo.straggr('AND TP.' + csv.val + ' = MP.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' + and TP.TimeClassID = mp.TimeClassID + and TP.FiscalYearID = mp.FiscalYearID + where (TP.PeriodNumber >= mp.MinPeriodNumber) or TP.PeriodNumber is null) ss /* there can be a subquery here*/ + PIVOT /*formation of the pivot table*/ + (count(PayPeriodID) /*is an aggregate function that forms the contents of a pivot table*/ + FOR PeriodNumber IN ('+@PeriodsList+')) Pvt /* alias for the pivot table*/ + ) X + UNPIVOT (isPresent /* the header of the column that will contain the values + from the columns of the source table listed below*/ + FOR PeriodNumber IN ('+@PeriodsList+')) Unpvt + INNER JOIN #dimPayPeriod mm + ON mm.PeriodNumber = Unpvt.PeriodNumber + and mm.FiscalYearID = Unpvt.FiscalYearID + and mm.PayCycleID = unpvt.PayCycleID + WHERE isPresent = 0 and Unpvt.PeriodNumber >= MinPeriodNumber + + IF OBJECT_ID(''tempdb..#MinPresent'') IS NOT NULL DROP TABLE #MinPresent + IF OBJECT_ID(''tempdb..#calculatedMeasures'') IS NOT NULL DROP TABLE #calculatedMeasures + CREATE TABLE #calculatedMeasures ( + DepartmentID int, + '+replace(@keyNameCSV, ',', ' int,')+' int, + FiscalYearID int, + PayPeriodID int, + PayCycleID int, + TimeClassID int, + PeriodNumber int, + '+replace(@measureNameCSV, ',', 'YTD decimal(18, 6),')+'YTD decimal(18, 6), + '+replace(@measureNameCSV, ',', ' decimal(18, 6),')+' decimal(18, 6), + isSystemGenerated int) + + insert into #calculatedMeasures(DepartmentID, '+@keyNameCSV+', FiscalYearID, PayPeriodID, PayCycleID, TimeClassID, PeriodNumber, ' + replace(@measureNameCSV, ',', 'YTD,') + 'YTD, ' + @measureNameCSV + ', isSystemGenerated) + select + uoag.DepartmentID, + uoag.' + replace(@keyNameCSV, ',', ', uoag.') + ', + uoag.FiscalYearID, + uoag.PayPeriodID, + pp.PayCycleID, + uoag.TimeClassID, + pp.PeriodNumber, + ' + (select dbo.straggr('SUM(uoag.' + csv.val + ') OVER (PARTITION BY uoag.DepartmentID,' + @keyNameCSV + ',TimeClassID,FiscalYearID,pp.PayCycleID ORDER BY pp.PeriodNumber) AS ' + csv.val + 'YTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + ' + @measureNameCSV + ', + uoag.isSystemGenerated + from + ( + SELECT + ML.DepartmentID, + ML.' + replace(@keyNameCSV, ',', ', ML.') + ', + ML.FiscalYearID, + ML.PayPeriodID, + ML.TimeClassID, + 0 as '+replace(@measureNameCSV, ',', ', 0 as ')+', + 1 as isSystemGenerated + FROM #MissingList ML ' + case when @fiscalYearID > 0 then ' where ML.FiscalYearID = ' + cast(@fiscalYearID as nvarchar(4)) else '' end +' + UNION + SELECT data.DepartmentID, + data.' + replace(@keyNameCSV, ',', ', data.') + ', + data.FiscalYearID, + data.PayPeriodID, + data.TimeClassID, + ' + @measureNameCSV + ', + data.isSystemGenerated + from ' + @stagingTableName + 'Updated data + where + (1 = 1) + ' + (case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else '' end) + '' + case when @fiscalYearID > 0 then ' + UNION + SELECT data.DepartmentID, + data.' + replace(@keyNameCSV, ',', ', data.') + ', + mm.FiscalYearID, + data.PayPeriodID, + data.TimeClassID, + ' + @measureNameCSV + ', + 1 as isSystemGenerated + from ' + @factTableName + ' data + INNER JOIN #dimPayPeriod mm + ON mm.PayPeriodID = data.PayPeriodID + where mm.FiscalYearID = ' + cast(@fiscalYearID-1 as nvarchar(4)) + case when @timeClassID > 0 then 'and data.TimeClassID = ' + cast(@timeClassID as nvarchar(2)) else ' and TimeClassID in (1,2,20) ' end + else '' end + ' + + ) uoag /* union ald and generated*/ + inner join fw.dimPayPeriod pp on uoag.PayPeriodID = pp.PayPeriodID' + + set @sql = @sql + ' + IF OBJECT_ID(''tempdb..#MissingList'') IS NOT NULL DROP TABLE #MissingList + + SELECT + PreSelect.*, + FTEs=cast(0 as decimal(19, 4)), + FTEsYTD=cast(0 as decimal(19, 4)), + FTEsPriorYear=cast(0 as decimal(19, 4)), + FTEsPriorYTD=cast(0 as decimal(19, 4)) + INTO fw.' + replace(@stagingTableName,'#','') + 'WithCalcs + FROM ( + SELECT + cm.DepartmentID, + cm.' + replace(@keyNameCSV, ',', ',cm.') + ', + cm.FiscalYearID, + cm.PayPeriodID, + cm.TimeClassID, + ' + (select dbo.straggr('isnull(cm.' + csv.val+',0) as '+ csv.val+',', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) +' + ' + (select dbo.straggr('isnull(cm.' + csv.val+'YTD,0) as '+csv.val+'YTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + ' + (select dbo.straggr('isnull(cm_py.' + csv.val + ',0) as '+ csv.val+'PriorYear,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + ' + (select dbo.straggr('isnull(cm_py.' + csv.val + 'YTD,0) as ' + csv.val + 'PriorYTD,', '', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + isnull(cm.isSystemGenerated,0) as isSystemGenerated + from #calculatedMeasures cm + LEFT JOIN #calculatedMeasures cm_py ON + cm.DepartmentID = cm_py.DepartmentID + ' + (select dbo.straggr('AND cm.' + csv.val + ' = cm_py.' + csv.val, ' ', '') from dbo.ConvertCSValuesToTable(@keyNameCSV, ',') csv) + ' + AND cm.PeriodNumber = cm_py.PeriodNumber + AND cm.PayCycleID = cm_py.PayCycleID + AND cm.TimeClassID = cm_py.TimeClassID + and cm.FiscalYearID = cm_py.FiscalYearID+1 + ' + case when @fiscalYearID > 0 then ' WHERE cm.FiscalYearId = '+cast(@fiscalYearID as varchar(4)) else '' end+' + ) PreSelect + + '+ case when @isJobCodeIDColumnPresent =1 then 'inner join fw.DimJobCode jc on jc.JobCodeID = PreSelect.JobCodeID and jc.IsPR = 1 ' else '' end + ' + + + WHERE NOT(' + (select dbo.straggr(csv.val+'= 0', ' and ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) +' + and ' + (select dbo.straggr(csv.val + 'YTD = 0', ' and ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + and ' + (select dbo.straggr(csv.val + 'PriorYear = 0', ' and ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + and ' + (select dbo.straggr(csv.val + 'PriorYTD = 0', ' and ', '') from dbo.ConvertCSValuesToTable(@measureNameCSV, ',') csv) + ' + and isSystemGenerated = 1) + + IF OBJECT_ID(''tempdb..' + @stagingTableName + 'Updated'') IS NOT NULL DROP TABLE ' + @stagingTableName + 'Updated + IF OBJECT_ID(''tempdb..#dimPayPeriod'') IS NOT NULL DROP TABLE #dimPayPeriod + IF OBJECT_ID(''tempdb..#calculatedMeasures'') IS NOT NULL DROP TABLE #calculatedMeasures + ' + + if (@isDebugOnly = 1) begin select @sql end else begin exec(@sql) end + + --delete zero records, possible only if YTD aggregates to zero due to negative values +GO + + +--------------------------------------------- + +-- fw.procFactPayrollSampledBaselineTargetUpdate +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-03-06 gforeman B-14693 Added year filter +** 2 2017-03-28 ipetriv D-05641 Logic for Prior and Actual was changed to simply copy actuals from previous year +** 3 2017-04-05 ipetriv D-05789 Changed algorithm for rolling average calculation +** 4 2018-05-16 IP D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values +** 5 2018-05-24 KF D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values +** 6 2018-06-05 IP TK-58643 added filetr for current year only and non-zero records in output +** 7 2024-06-14 SM JAZZ-71536 change JobCodeID from smallint to int +*************************************************************/ +CREATE proc [fw].[procFactPayrollSampledBaselineTargetUpdate] + @targetType int = null, + @numberOfMonths int = null, + @fiscalYearID int = 0 +with recompile +as + if (@targetType is null) set @targetType = (select Value from mr.SystemSetting where Name = 'Target Basis') + if (@numberOfMonths is null) set @numberOfMonths = (select Value from mr.SystemSetting where Name = 'Number Of Rolling Average Months') + declare @sql varchar(max) + create table #temp + ( + DepartmentID int, + JobCodeID int, + PayCodeID smallint, + PayCodeGroupID int, + FiscalYearID smallint, + FiscalMonthID tinyint, + Hours decimal (18, 6), + Dollars decimal (18, 6), + FTEs decimal (18, 6) + ) + + create table #YearsScope (FiscalYearID int) + + IF @fiscalYearID <> 0 + INSERT INTO #YearsScope (FiscalYearID) + select distinct FiscalYearID from fw.dimFiscalYear dm where dm.FiscalYearID in (@fiscalYearID-1,@fiscalYearID,@fiscalYearID+1) + UNION + SELECT @fiscalYearID+1 as FiscalYearID + ELSE + INSERT INTO #YearsScope (FiscalYearID) + select distinct FiscalYearID from fw.dimFiscalYear dm where FiscalYearID between (select min(FiscalYearID) FROM fw.FactPayrollSampledMonthly) and (select max(FiscalYearID)+1 FROM fw.FactPayrollSampledMonthly) + + if (@targetType = 1) begin --Prior Year Actual + insert into #temp + select d.DepartmentID, d.JobCodeID, d.PayCodeID, d.PayCodeGroupID, d.FiscalYearID+1, d.FiscalMonthID, d.Hours, d.Dollars, d.FTEs + FROM fw.FactPayrollSampledMonthly d WHERE d.TimeClassID = 1 and (@fiscalYearID = 0 or d.FiscalYearID = @fiscalYearID-1) + end else if (@targetType = 10) begin --Rolling Average + set @sql = ' + insert into #temp (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID,Dollars,Hours,FTEs) + select DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, isnull(Dollars,0.0), isnull(Hours,0.0),0 FROM ( + select FullScope.DepartmentID, FullScope.JobCodeID, FullScope.PayCodeID, FullScope.PayCodeGroupID, FullScope.FiscalYearID, m.FiscalMonthID, + Dollars = ISNULL((Sum(Dollars) over(PARTITION BY DepartmentID,JobCodeID,PayCodeID,PayCodeGroupID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/'+cast(@numberOfMonths as nvarchar(2))+', 0), + Hours = ISNULL((Sum(Hours) over(PARTITION BY DepartmentID,JobCodeID,PayCodeID,PayCodeGroupID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/'+cast(@numberOfMonths as nvarchar(2))+', 0) + FROM ( + select DepartmentID, /*records for months, which are absent in current year, but exist at least one month*/ + JobCodeID, + PayCodeID, + PayCodeGroupID, + FiscalYearID, + SortOrder, + SUM(Hours) as Hours, + SUM(Dollars) as Dollars + FROM ( + SELECT /*recods for months which are present in current year*/ + DepartmentID, + JobCodeID, + PayCodeID, + PayCodeGroupID, + FiscalYearID, + m.SortOrder, + Hours, + Dollars + FROM fw.FactPayrollSampledMonthly p + JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID + where m.FiscalMonthID <> 0 and p.TimeClassID = 1 and p.isSystemGenerated = 0 + ' + case when @fiscalYearID <> 0 then ' and FiscalYearID in ('+cast(@fiscalYearID-1 as nvarchar(4))+','+cast(@fiscalYearID as nvarchar(4))+')' else '' end +' + UNION ALL + SELECT /*combination of all for key columns months for (year-1). If some combination was in previous year - same should be in current, to receive baseline value*/ + p.DepartmentID, + p.JobCodeID, + p.PayCodeID, + p.PayCodeGroupID, + fy.FiscalYearID, + m.SortOrder, + 0 as Hours, + 0 as Dollars + FROM fw.FactPayrollSampledMonthly p + CROSS JOIN fw.DimFiscalMonth m + CROSS JOIN #YearsScope fy + WHERE m.FiscalMonthID <> 0 and p.TimeClassID = 1 and p.IsSystemGenerated = 0 + ' + case when @fiscalYearID <> 0 then ' and p.FiscalYearID in ('+cast(@fiscalYearID-1 as nvarchar(4))+','+cast(@fiscalYearID as nvarchar(4))+')' else '' end +' + ) AllCombinations + GROUP BY DepartmentID,JobCodeID,PayCodeID,PayCodeGroupID,FiscalYearID,SortOrder + ) FullScope + JOIN fw.DimFiscalMonth m ON FullScope.SortOrder = m.SortOrder + ) FinalDataset + WHERE (Dollars is not null + or Hours is not null) + ' + case when @fiscalYearID <> 0 then ' and FiscalYearID = '+cast(@fiscalYearID as nvarchar(4)) else '' end + print @sql + exec (@sql) + end else begin --Budget + insert into #temp + select DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, Hours, Dollars, FTEs + from fw.FactPayrollSampledMonthly + where TimeClassID = 2 and (@fiscalYearID = 0 or FiscalYearID = @fiscalYearID) + end + + merge + fw.FactPayrollSampledMonthly as fact + using + (select * from #temp where (@fiscalYearID = 0 or FiscalYearID = @fiscalYearID) and not (Hours = 0 and Dollars = 0)) as source + on + fact.DepartmentID = source.DepartmentID and fact.JobCodeID = source.JobCodeID and fact.PayCodeID = source.PayCodeID and fact.PayCodeGroupID = source.PayCodeGroupID and fact.FiscalYearID = source.FiscalYearID and + fact.FiscalMonthID = source.FiscalMonthID and fact.TimeClassID = 20 and (@fiscalYearID = 0 or fact.FiscalYearID = @fiscalYearID) + when not matched by target then + insert (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, TimeClassID, Hours, Dollars, FTEs) values + (source.DepartmentID, source.JobCodeID, source.PayCodeID, source.PayCodeGroupID, source.FiscalYearID, source.FiscalMonthID, 20, source.Hours, source.Dollars, source.FTEs) + when not matched by source and fact.TimeClassID = 20 and (@fiscalYearID = 0 or fact.FiscalYearID = @fiscalYearID) then + update set fact.IsDeleted = 1 + when matched then + update set fact.Hours = source.Hours, fact.Dollars = source.Dollars, fact.FTEs = source.FTEs, fact.IsSystemGenerated = 0; + + exec [dbo].[procRollingDeleteOnTable] 'fw', 'FactPayrollSampledMonthly', 'RowID', 'fw.FactPayrollSampledMonthly', 'TimeClassID = 20 and IsDeleted = 1', 10000, 0.5, 0 + + drop table #temp + drop table #YearsScope; +GO + + +--------------------------------------------- + +-- fw.procFactPayrollSampledDailyFTEsInsert +CREATE PROCEDURE [fw].[procFactPayrollSampledDailyFTEsInsert] + @departmentIDs NVARCHAR(max) = NULL, + @fiscalYearID INT = 0, + @onePayPeriodOnlyDate datetime = null, + @timeClassID INT = 4 +AS + +/* +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-08-16 ishah JAZZ-41955 Daily Flexing - Calculating Payroll FTEs +************************************************************ +*/ + +IF OBJECT_ID('tempdb..#departments') IS NOT NULL DROP TABLE #departments +SELECT val INTO #departments +FROM ConvertCSValuesToTable(@departmentIDs, ',') + +IF OBJECT_ID('tempdb..#WorkWeekHours') IS NOT NULL DROP TABLE #WorkWeekHours +SELECT DeptJobCode.DepartmentID, + DeptJobCode.JobCodeID, + WorkingHoursCoef = cast(dww.Hours AS NUMERIC(20, 6)) / 7 +INTO #WorkWeekHours +FROM ( + SELECT DepartmentID, + JobCodeID, + WorkWeekID = COALESCE(jc.WorkWeekID, de.WorkWeekID, - 1) + FROM ( + SELECT dp.DepartmentID, + WorkWeekID = CASE + WHEN e.WorkWeekID > - 1 THEN e.WorkWeekID + ELSE NULL + END + FROM fw.DimEntity e + INNER JOIN fw.DimDepartment dp on e.EntityID = dp.EntityID + ) DE + CROSS JOIN ( + SELECT djc.JobCodeID, + djcg.JobCodeGroupID, + WorkWeekID = CASE + WHEN djc.WorkWeekOverrideID > - 1 THEN djc.WorkWeekOverrideID + WHEN djc.WorkWeekOverrideID = - 1 AND djcg.WorkWeekOverrideID > - 1 + THEN djcg.WorkWeekOverrideID ELSE NULL + END + FROM fw.DimJobCode djc + INNER JOIN fw.DimJobCodeGroup djcg ON djc.JobCodeGroupID = djcg.JobCodeGroupID + WHERE djc.IsDaily = 1 and djc.IsPR = 1 + ) JC + ) DeptJobCode +LEFT JOIN fw.DimWorkWeek dww ON DeptJobCode.WorkWeekID = dww.WorkWeekID + +DECLARE @BatchSize INT = 100000000 + +IF OBJECT_ID('tempdb..#inputPayPeriods') IS NOT NULL DROP TABLE #inputPayPeriods + +-- Added support for one pay period only +SELECT fp.PayPeriodID, pp.WorkingDays as WorkingDays, pp.PeriodDays as PeriodDays, COUNT(*) AS RecordsCount, 0 AS BatchID INTO #inputPayPeriods +FROM fw.FactPayrollSampledDaily fp +INNER JOIN fw.DimPayPeriod pp ON fp.PayPeriodID = pp.PayPeriodID +WHERE fp.TimeClassID = @timeClassID AND pp.PeriodNumber != 0 AND +((@onePayPeriodOnlyDate IS NOT NULL AND @onePayPeriodOnlyDate BETWEEN pp.PeriodStartCalendarDate AND pp.PeriodEndCalendarDate) +OR +(@onePayPeriodOnlyDate IS NULL AND (pp.FiscalYearIDSecond = @fiscalYearID OR @fiscalYearID = 0))) +GROUP BY fp.PayPeriodID, pp.WorkingDays, pp.PeriodDays + +-- Split data into batches +WHILE EXISTS (SELECT TOP 1 1 FROM #inputPayPeriods WHERE BatchID = 0) +BEGIN + ;WITH PayPeriodInfo AS + ( + SELECT IPP.PayPeriodID, ROW_NUMBER() OVER (ORDER BY IPP.PayPeriodID) AS RowNumber, SUM(RecordsCount) OVER (ORDER BY IPP.PayPeriodID) AS Total, MaxBatchID+1 AS BatchID + FROM #inputPayPeriods IPP + CROSS JOIN (SELECT MAX(BatchID) AS MaxBatchID FROM #inputPayPeriods) M + WHERE IPP.BatchID = 0 + ) + UPDATE IPP + SET IPP.BatchID = MI.BatchID + FROM #inputPayPeriods IPP + INNER JOIN PayPeriodInfo MI ON MI.PayPeriodID = IPP.PayPeriodID + WHERE Total <= @BatchSize OR RowNumber = 1 +END + +DECLARE @BatchID INT, @MaxBatchID INT +SELECT @MaxBatchID = MAX(BatchID) FROM #inputPayPeriods + +-- Loop thru batches and insert data +SET @BatchID = 1 +WHILE @BatchID <= @MaxBatchID +BEGIN + UPDATE fact + SET fact.FTEs = CASE + WHEN WorkingHoursCoef IS NOT NULL + THEN (fact.Hours) / WorkingHoursCoef + ELSE fact.Hours / (IPP.WorkingDays * 8.0 / IPP.PeriodDays) + END + FROM fw.FactPayrollSampledDaily fact + INNER JOIN #inputPayPeriods IPP ON IPP.PayPeriodID = fact.PayPeriodID and IPP.BatchID = @BatchID + INNER JOIN fw.viewDimPayCodeGroup pcg ON fact.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN #WorkWeekHours ww ON ww.DepartmentID = fact.DepartmentID + AND fact.JobCodeID = ww.JobCodeID + WHERE pcg.ProductiveClass IN ( 'Productive', 'Non-Productive' ) + AND fact.TimeClassID = @timeClassID + AND ( + @departmentIDs IS NULL + OR fact.DepartmentID IN ( + SELECT val + FROM #departments + ) + ) + SET @BatchID = @BatchID + 1 +END +GO + + +--------------------------------------------- + +-- fw.procFactPayrollSampledDetailedBaselineTargetUpdate +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-03-06 gforeman B-14693 Added year filter +** 2 2017-03-28 IPetriv D-05641 Logic for Prior and Actual was changed to simply copy actuals from previous year +** 3 2017-04-11 IPetriv B-15086 Sampling Performance Improvements. Using temp tables insead of fw.FactPayrollSampledMonthlyDetailed. Update fw.FactPayrollSampledMonthlyDetailed only once by the final dataset. +** 4 2017-06-15 IP B-15086 Modify SP to use unique temp table +** 5 2018-05-16 IP D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values +** 6 2018-05-24 KF D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values +** 7 2018-06-01 IP D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values (one year part) +** 8 2018-06-05 IP TK-58643 added filetr for current year only and non-zero records in output +** 9 2024-06-14 SM JAZZ-71536 change JobCodeID from smallint to int +*************************************************************/ +CREATE proc [fw].[procFactPayrollSampledDetailedBaselineTargetUpdate] + @targetType int = null, + @numberOfMonths int = null, + @fiscalYearID int = 0 +as + if (@targetType is null) set @targetType = (select Value from mr.SystemSetting where Name = 'Target Basis') + if (@numberOfMonths is null) set @numberOfMonths = (select Value from mr.SystemSetting where Name = 'Number Of Rolling Average Months') + declare @maxCalculatingFiscalYear int = (select max(FiscalYearID) from #PayrollSampledMonthlyDetailedStaging) + + create table #temp + ( + DepartmentID int, + JobCodeID int, + PayCodeID smallint, + PayCodeGroupID int, + EmployeeID int, + FiscalYearID smallint, + FiscalMonthID tinyint, + Hours decimal (19, 4), + Dollars decimal (19, 4), + FTEs decimal (19, 4) + ) + + if (@targetType = 1) begin --Prior Year Actual + if (@fiscalYearID = 0) + insert into #temp + select d.DepartmentID, d.JobCodeID, d.PayCodeID, d.PayCodeGroupID, d.EmployeeID, d.FiscalYearID+1, d.FiscalMonthID, d.Hours, d.Dollars, d.FTEs + from #PayrollSampledMonthlyDetailedStaging d + where d.TimeClassID = 1 + else + insert into #temp + select d.DepartmentID, d.JobCodeID, d.PayCodeID, d.PayCodeGroupID, d.EmployeeID, d.FiscalYearID+1, d.FiscalMonthID, d.Hours, d.Dollars, d.FTEs + from fw.FactPayrollSampledMonthlyDetailed d + where (d.FiscalYearID = @fiscalYearID-1) and d.TimeClassID = 1 + end else if (@targetType = 10) begin --Rolling Average + declare @sql nvarchar(max) + if @fiscalYearID = 0 + set @sql = ' + insert into #temp (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, FiscalYearID, FiscalMonthID,Hours,Dollars) + select DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, FiscalYearID, FiscalMonthID,isnull(Hours,0.0),isnull(Dollars,0.0) FROM ( + select FullScope.DepartmentID, FullScope.JobCodeID, FullScope.PayCodeID, FullScope.PayCodeGroupID, FullScope.EmployeeID, FullScope.FiscalYearID, m.FiscalMonthID, + Dollars = ISNULL((Sum(Dollars) over(PARTITION BY DepartmentID,JobCodeID,EmployeeID,PayCodeID,PayCodeGroupID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfMonths AS NVARCHAR(2)) +', 0), + Hours = ISNULL((Sum(Hours) over(PARTITION BY DepartmentID,JobCodeID,EmployeeID,PayCodeID,PayCodeGroupID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfMonths AS NVARCHAR(2)) +', 0) + FROM ( + select DepartmentID, /*records for months, which are absent in current year, but exist at least one month*/ + JobCodeID, + EmployeeID, + PayCodeID, + PayCodeGroupID, + FiscalYearID, + SortOrder, + SUM(Hours) as Hours, + SUM(Dollars) as Dollars + FROM ( + SELECT /*recods for months which are present in current year*/ + DepartmentID, + JobCodeID, + EmployeeID, + PayCodeID, + PayCodeGroupID, + FiscalYearID, + m.SortOrder, + Hours, + Dollars + FROM #PayrollSampledMonthlyDetailedStaging p + JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID + where m.FiscalMonthID <> 0 and isnull(p.IsSystemGenerated,0) = 0 and p.TimeClassID = 1 + UNION ALL + SELECT /*combination of all for key columns months for (year-1). If some combination was in previous year - same should be in current, to receive baseline value*/ + p.DepartmentID, + p.JobCodeID, + p.EmployeeID, + p.PayCodeID, + p.PayCodeGroupID, + fy.FiscalYearID, + fy.SortOrder, + 0 AS Hours, + 0 AS Dollars + FROM #PayrollSampledMonthlyDetailedStaging p + INNER JOIN fw.DimFiscalMonth m on m.FiscalMonthID = p.FiscalMonthID + INNER JOIN (select FiscalYearID,FiscalMonthID,fm.sortOrder,fy.FiscalYearID*12+fm.SortOrder as ChronologicalOrder from fw.DimFiscalYear fy + full join fw.DimFiscalMonth fm on 1= 1 + where FiscalMonthID <> 0 and FiscalYearID <> 0) fy ON ChronologicalOrder - (p.FiscalYearID*12+m.SortOrder) between 1 and '+cast(@numberOfMonths as nvarchar(2))+' + WHERE p.TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0 + ) AllCombinations + GROUP BY DepartmentID,JobCodeID,EmployeeID,PayCodeID,PayCodeGroupID,FiscalYearID,SortOrder + ) FullScope + JOIN fw.DimFiscalMonth m ON FullScope.SortOrder = m.SortOrder + ) FinalDataset + WHERE Dollars is not null + or Hours is not null' + else + set @sql = ' + insert into #temp (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, FiscalYearID, FiscalMonthID,Hours,Dollars) + select DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, FiscalYearID, FiscalMonthID,isnull(Hours,0.0),isnull(Dollars,0.0) FROM ( + select FullScope.DepartmentID, FullScope.JobCodeID, FullScope.PayCodeID, FullScope.PayCodeGroupID, FullScope.EmployeeID, FullScope.FiscalYearID, m.FiscalMonthID, + Dollars = ISNULL((Sum(Dollars) over(PARTITION BY DepartmentID,JobCodeID,EmployeeID,PayCodeID,PayCodeGroupID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfMonths AS NVARCHAR(2)) +', 0), + Hours = ISNULL((Sum(Hours) over(PARTITION BY DepartmentID,JobCodeID,EmployeeID,PayCodeID,PayCodeGroupID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfMonths AS NVARCHAR(2)) +', 0) + FROM ( + select DepartmentID, /*records for months, which are absent in current year, but exist at least one month*/ + JobCodeID, + EmployeeID, + PayCodeID, + PayCodeGroupID, + FiscalYearID, + SortOrder, + SUM(Hours) as Hours, + SUM(Dollars) as Dollars + FROM ( + SELECT /*recods for months which are present in current year*/ + DepartmentID, + JobCodeID, + EmployeeID, + PayCodeID, + PayCodeGroupID, + FiscalYearID, + m.SortOrder, + Hours, + Dollars + FROM #PayrollSampledMonthlyDetailedStaging p + JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID + where m.FiscalMonthID <> 0 and isnull(p.IsSystemGenerated,0) = 0 and p.TimeClassID = 1 + UNION ALL + SELECT /*recods for months which are present in current year*/ + DepartmentID, + JobCodeID, + EmployeeID, + PayCodeID, + PayCodeGroupID, + FiscalYearID, + m.SortOrder, + Hours, + Dollars + FROM fw.FactPayrollSampledMonthlyDetailed p + JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID + where m.FiscalMonthID <> 0 and isnull(p.IsSystemGenerated,0) = 0 and p.TimeClassID = 1 and p.FiscalYearID = '+cast(@fiscalYearID-1 as nvarchar(4))+' + UNION ALL + SELECT /*combination of all for key columns months for current year*/ + DepartmentID, + JobCodeID, + EmployeeID, + PayCodeID, + PayCodeGroupID, + FiscalYearID, + m.SortOrder, + 0 AS Hours, + 0 AS Dollars + FROM #PayrollSampledMonthlyDetailedStaging p + CROSS APPLY fw.DimFiscalMonth m + where m.FiscalMonthID <> 0 and isnull(p.IsSystemGenerated,0) = 0 and p.TimeClassID = 1 + UNION ALL + SELECT /*combination of all for key columns months for (year-1). If some combination was in previous year - same should be in current, to receive baseline value*/ + p.DepartmentID, + p.JobCodeID, + p.EmployeeID, + p.PayCodeID, + p.PayCodeGroupID, + fy.FiscalYearID, + m.SortOrder, + 0 AS Hours, + 0 AS Dollars + FROM fw.FactPayrollSampledMonthlyDetailed p + CROSS JOIN fw.DimFiscalMonth m + CROSS JOIN (select distinct FiscalYearID from int.FactStaffing dm where dm.FiscalYearID in ('+cast(@fiscalYearID-1 as nvarchar(4))+','+cast(@fiscalYearID as nvarchar(4))+')) fy + WHERE m.FiscalMonthID <> 0 and p.TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0 and p.TimeClassID <> 20 and p.FiscalYearID = '+cast(@fiscalYearID-1 as nvarchar(4))+' + ) AllCombinations + GROUP BY DepartmentID,JobCodeID,EmployeeID,PayCodeID,PayCodeGroupID,FiscalYearID,SortOrder + ) FullScope + JOIN fw.DimFiscalMonth m ON FullScope.SortOrder = m.SortOrder + ) FinalDataset + WHERE Dollars is not null + or Hours is not null' + print @sql + exec (@sql) + end else begin --Budget + insert into #temp + select DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, FiscalYearID, FiscalMonthID, Hours, Dollars, FTEs + from #PayrollSampledMonthlyDetailedStaging + where TimeClassID = 2 + end + + delete from #PayrollSampledMonthlyDetailedStaging where TimeClassID = 20 and (@fiscalYearID = 0 or FiscalYearID = @fiscalYearID) + insert into #PayrollSampledMonthlyDetailedStaging(DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, FiscalYearID, FiscalMonthID, TimeClassID, Hours, Dollars, FTEs) + select DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, FiscalYearID, FiscalMonthID, 20, Hours, Dollars, FTEs from #temp + where (FiscalYearID = @fiscalYearID or @fiscalYearID = 0) and not (Hours =0 and Dollars = 0) + + drop table #temp; +GO + + +--------------------------------------------- + +-- fw.procFactPayrollSampledMonthlyUpdateFTEs +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2019-10-21 KF D-08819 FTE Baseline Calculation Issue +** 2 2020-09-03 KF JAZZ-4280 FTEs YTD logic for Rolling Methodology incorrectly calculating +** 3 2020-02-18 HV JAZZ-15496 Bug - Run Management Reporting Monthly Process is failed due to "Divide by zero error encountered..." error +** 4 2021-06-08 KF JAZZ-21092 Monthly FTE Factor for Rolling Average +** 5 2021-09-14 KF JAZZ-26273 Update Monthly FTE YTD Factor for Rolling Average +** 6 2024-04-23 HV JAZZ-68507 Inconsistencies in MR conversion factor used across TimeClasses +*************************************************************/ +CREATE PROCEDURE [fw].[procFactPayrollSampledMonthlyUpdateFTEs] +@fiscalYearID SMALLINT = 0, +@timeClassID TINYINT = 20 +AS + +DECLARE @targetType int = (select Value from mr.SystemSetting where Name = 'Target Basis') +IF(@targetType = 10) --Rolling Average + BEGIN + CREATE TABLE #workingHours (FiscalYearID smallint, FiscalMonthID tinyint, WorkWeekID INT, + WorkingHours Decimal(19,4), WorkingHoursYTD Decimal(38,4), + RollingWorkingHours Decimal(19,4), RollingWorkingHoursYTD Decimal(38,4)) + + DECLARE @useCurrentMonthFTEFactor bit = (SELECT Value FROM mr.SystemSetting WHERE Name = 'Use The Current Month FTE Factor Instead Of The Rolling Average') + DECLARE @numberOfMonths INT = (select Value from mr.SystemSetting where Name = 'Number Of Rolling Average Months') + DECLARE @sql nvarchar(max) + + SET @sql = ' + INSERT INTO #workingHours (FiscalYearID, FiscalMonthID, WorkWeekID, WorkingHours, WorkingHoursYTD, RollingWorkingHours, RollingWorkingHoursYTD) + SELECT FiscalYearID, FiscalMonthID, WorkWeekID, WorkingHours, WorkingHoursYTD, RollingWorkingHours, + COALESCE((Sum(RollingWorkingHours) over(PARTITION BY WorkWeekID, FiscalYearID ORDER BY SortOrder)), 0) AS RollingWorkingHoursYTD + FROM ( + SELECT FY.FiscalYearID, FM.FiscalMonthID, wpmCY.WorkWeekID, FM.SortOrder, wpmCY.Hours AS WorkingHours, wpmCY.YTDHours AS WorkingHoursYTD, + COALESCE((Sum(wpmCY.Hours) over(PARTITION BY wpmCY.WorkWeekID ORDER BY FY.FiscalYearID*12+FM.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/'+cast(@numberOfMonths as nvarchar(2))+', 0) AS RollingWorkingHours + FROM [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmCY + INNER JOIN fw.DimFiscalMonth FM ON FM.FiscalMonthID = wpmCY.FiscalMonthID + INNER JOIN fw.DimFiscalYear FY ON FY.FiscalYearID = wpmCY.FiscalYearID + ) S + ' + exec (@sql) + + IF(@useCurrentMonthFTEFactor = 1 AND @timeClassID IN (4, 20, 22)) + BEGIN + UPDATE fact + SET + fact.FTEs= CASE WHEN wpmCY.WorkingHours = 0 THEN 0 ELSE fact.Hours/wpmCY.WorkingHours END, + fact.FTEsYTD= CASE WHEN wpmCY.WorkingHoursYTD = 0 THEN 0 ELSE fact.HoursYTD/wpmCY.WorkingHoursYTD END, + fact.FTEsPriorYear = CASE WHEN COALESCE(wpmPY.WorkingHours, 0) = 0 THEN 0 ELSE fact.HoursPriorYear / wpmPY.WorkingHours END, + fact.FTEsPriorYTD = CASE WHEN COALESCE(wpmPY.WorkingHoursYTD, 0) = 0 THEN 0 ELSE fact.HoursPriorYTD / wpmPY.WorkingHoursYTD END + FROM + ( + SELECT fact.*, + CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID + WHEN jc.WorkWeekOverrideID = -1 AND jcg.WorkWeekOverrideID != -1 THEN jcg.WorkWeekOverrideID + WHEN jc.WorkWeekOverrideID = -1 and jcg.WorkWeekOverrideID =- 1 THEN D.WorkWeekID + END AS WorkWeekID + FROM fw.FactPayrollSampledMonthly fact + inner join fw.DimDepartment D on fact.DepartmentID= D.DepartmentID + inner join fw.DimJobCode JC on fact.JobCodeID= JC.JobCodeID + inner join fw.DimJobCodeGroup JCG on JC.jobCodeGroupID = JCG.JobCodeGroupID + inner join fw.DimPayCodeGroup PCG on fact.PayCodeGroupID = PCG.PayCodeGroupID + WHERE PCG.ProductiveClassID in ('3','2') --Productive and Non-Productive + and (fact.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0) + and fact.TimeClassID = @timeClassID + ) fact + inner join #workingHours wpmCY on fact.FiscalMonthID= wpmCY.FiscalMonthID and fact.FiscalYearID= wpmCY.FiscalYearID and wpmCY.WorkWeekID= fact.WorkWeekID + left join #workingHours wpmPY on fact.FiscalMonthID= wpmPY.FiscalMonthID and (fact.FiscalYearID-1)=wpmPY.FiscalYearID and wpmPY.WorkWeekID=fact.WorkWeekID + END + ELSE BEGIN + UPDATE fact + SET + fact.FTEs= CASE WHEN wpmCY.RollingWorkingHours = 0 THEN 0 ELSE fact.Hours/wpmCY.RollingWorkingHours END, + fact.FTEsYTD= CASE WHEN wpmCY.RollingWorkingHoursYTD = 0 THEN 0 ELSE fact.HoursYTD/wpmCY.RollingWorkingHoursYTD END, + fact.FTEsPriorYear = CASE WHEN COALESCE(wpmPY.RollingWorkingHours, 0) = 0 THEN 0 ELSE fact.HoursPriorYear / wpmPY.RollingWorkingHours END, + fact.FTEsPriorYTD = CASE WHEN COALESCE(wpmPY.RollingWorkingHoursYTD, 0) = 0 THEN 0 ELSE fact.HoursPriorYTD / (wpmPY.RollingWorkingHoursYTD) END + FROM + ( + SELECT fact.*, + CASE WHEN jc.WorkWeekOverrideID != -1 THEN jc.WorkWeekOverrideID + WHEN jc.WorkWeekOverrideID = -1 AND jcg.WorkWeekOverrideID != -1 THEN jcg.WorkWeekOverrideID + WHEN jc.WorkWeekOverrideID = -1 and jcg.WorkWeekOverrideID =- 1 THEN D.WorkWeekID + END AS WorkWeekID + FROM fw.FactPayrollSampledMonthly fact + inner join fw.DimDepartment D on fact.DepartmentID= D.DepartmentID + inner join fw.DimJobCode JC on fact.JobCodeID= JC.JobCodeID + inner join fw.DimJobCodeGroup JCG on JC.jobCodeGroupID = JCG.JobCodeGroupID + inner join fw.DimPayCodeGroup PCG on fact.PayCodeGroupID = PCG.PayCodeGroupID + WHERE + PCG.ProductiveClassID in ('3','2') --Productive and Non-Productive + and (fact.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0) + and fact.TimeClassID = @timeClassID + ) fact + inner join #workingHours wpmCY on fact.FiscalMonthID= wpmCY.FiscalMonthID and fact.FiscalYearID= wpmCY.FiscalYearID and wpmCY.WorkWeekID= fact.WorkWeekID + left join #workingHours wpmPY on fact.FiscalMonthID= wpmPY.FiscalMonthID and (fact.FiscalYearID-1)=wpmPY.FiscalYearID and wpmPY.WorkWeekID=fact.WorkWeekID + + IF OBJECT_ID('tempdb..#workingHours') IS NOT NULL DROP TABLE #workingHours + END + END +ELSE -- Not rolling average + BEGIN + update fact + set + fact.FTEs=fact.Hours / (wpmCY.Hours), + fact.FTEsYTD = fact.HoursYTD / (wpmCY.YTDHours), + fact.FTEsPriorYear = CASE WHEN COALESCE(wpmPY.Hours, 0) = 0 THEN 0 ELSE fact.HoursPriorYear / (wpmPY.Hours) END, + fact.FTEsPriorYTD = CASE WHEN COALESCE(wpmPY.YTDHours, 0) = 0 THEN 0 ELSE fact.HoursPriorYTD / (wpmPY.YTDHours) END + from + fw.FactPayrollSampledMonthly fact + inner join [fw].[DimDepartment] D on fact.DepartmentID=D.DepartmentID + inner join [fw].[DimJobCode] JC on fact.JobCodeID=JC.JobCodeID + inner join fw.DimJobCodeGroup JCG on JC.jobCodeGroupID = JCG.JobCodeGroupID + inner join [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmCY on fact.FiscalMonthID=wpmCY.FiscalMonthID and CASE WHEN @targetType = 1 AND TimeClassID in (20,4,22) THEN fact.FiscalYearID-1 ELSE fact.FiscalYearID END=wpmCY.FiscalYearID and wpmCY.WorkWeekID=D.WorkWeekID + left join [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmPY on fact.FiscalMonthID=wpmPY.FiscalMonthID and CASE WHEN @targetType = 1 AND TimeClassID in (20,4,22) THEN fact.FiscalYearID-2 ELSE fact.FiscalYearID-1 END=wpmPY.FiscalYearID and wpmPY.WorkWeekID=D.WorkWeekID + inner join fw.DimFiscalMonth fm on fact.FiscalMonthID=fm.FiscalMonthID + inner join [fw].[DimPayCodeGroup] pcg on fact.PayCodeGroupID = pcg.PayCodeGroupID + where + pcg.ProductiveClassID in ('3','2') --Productive and Non-Productive + and jc.WorkWeekOverrideID=-1 and jcg.WorkWeekOverrideID=-1 + and (fact.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0) + and fact.TimeClassID = @timeClassID + option (recompile) + + update fact + set + fact.FTEs=fact.Hours / (wpmCY.Hours), + fact.FTEsYTD = fact.HoursYTD / (wpmCY.YTDHours), + fact.FTEsPriorYear = CASE WHEN COALESCE(wpmPY.Hours, 0) = 0 THEN 0 ELSE fact.HoursPriorYear / (wpmPY.Hours) END, + fact.FTEsPriorYTD = CASE WHEN COALESCE(wpmPY.YTDHours, 0) = 0 THEN 0 ELSE fact.HoursPriorYTD / (wpmPY.YTDHours) END + from + fw.FactPayrollSampledMonthly fact + inner join [fw].[DimJobCode] JC on fact.JobCodeID=JC.JobCodeID + inner join fw.DimJobCodeGroup JCG on JC.jobCodeGroupID = JCG.JobCodeGroupID + inner join [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmCY on fact.FiscalMonthID=wpmCY.FiscalMonthID and CASE WHEN @targetType = 1 AND TimeClassID in (20,4,22) THEN fact.FiscalYearID-1 ELSE fact.FiscalYearID END=wpmCY.FiscalYearID and wpmCY.WorkWeekID=jcg.WorkWeekOverrideID + left join [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmPY on fact.FiscalMonthID=wpmPY.FiscalMonthID and CASE WHEN @targetType = 1 AND TimeClassID in (20,4,22) THEN fact.FiscalYearID-2 ELSE fact.FiscalYearID-1 END=wpmPY.FiscalYearID and wpmPY.WorkWeekID=jcg.WorkWeekOverrideID + inner join fw.DimFiscalMonth fm on fact.FiscalMonthID=fm.FiscalMonthID + inner join [fw].[DimPayCodeGroup] pcg on fact.PayCodeGroupID = pcg.PayCodeGroupID + where + pcg.ProductiveClassID in ('3','2') --Productive and Non-Productive + and jcg.WorkWeekOverrideID<>-1 and jc.WorkWeekOverrideID=-1 + and (fact.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0) + and fact.TimeClassID = @timeClassID + option (recompile) + + update fact + set + fact.FTEs=fact.Hours / (wpmCY.Hours), + fact.FTEsYTD = fact.HoursYTD / (wpmCY.YTDHours), + fact.FTEsPriorYear = CASE WHEN COALESCE(wpmPY.Hours, 0) = 0 THEN 0 ELSE fact.HoursPriorYear / (wpmPY.Hours) END, + fact.FTEsPriorYTD = CASE WHEN COALESCE(wpmPY.YTDHours, 0) = 0 THEN 0 ELSE fact.HoursPriorYTD / (wpmPY.YTDHours) END + from + fw.FactPayrollSampledMonthly fact + inner join [fw].[DimJobCode] JC on fact.JobCodeID=JC.JobCodeID + inner join [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmCY on fact.FiscalMonthID=wpmCY.FiscalMonthID and CASE WHEN @targetType = 1 AND TimeClassID in (20,4,22) THEN fact.FiscalYearID-1 ELSE fact.FiscalYearID END=wpmCY.FiscalYearID and wpmCY.WorkWeekID=jc.WorkWeekOverrideID + left join [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmPY on fact.FiscalMonthID=wpmPY.FiscalMonthID and CASE WHEN @targetType = 1 AND TimeClassID in (20,4,22) THEN fact.FiscalYearID-2 ELSE fact.FiscalYearID-1 END=wpmPY.FiscalYearID and wpmPY.WorkWeekID=jc.WorkWeekOverrideID + inner join fw.DimFiscalMonth fm on fact.FiscalMonthID=fm.FiscalMonthID + inner join [fw].[DimPayCodeGroup] pcg on fact.PayCodeGroupID = pcg.PayCodeGroupID + where + pcg.ProductiveClassID in ('3','2') --Productive and Non-Productive + and jc.WorkWeekOverrideID<>-1 + and (fact.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0) + and fact.TimeClassID = @timeClassID + option (recompile) + + END +GO + + +--------------------------------------------- + +-- fw.procFactPayrollSampledPayPeriodBaselineTargetOverridesUpdate +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2021-02-18 KF JAZZ-15158 Variable Productive Hours - Detailed Target Spread +*************************************************************/ +CREATE PROCEDURE [fw].[procFactPayrollSampledPayPeriodBaselineTargetOverridesUpdate] +-- #PayrollSampledPayPeriodStaging should be created before calling this procedure +AS + IF OBJECT_ID('tempdb..#VariableHours') IS NOT NULL DROP TABLE #VariableHours + IF OBJECT_ID('tempdb..#Spreads') IS NOT NULL DROP TABLE #Spreads + + DECLARE @ProductiveClassProductiveID INT = 3 + + SELECT FP.DepartmentID, FP.PayPeriodID, FP.JobCodeID, FP.PayCodeGroupID, CAST(FP.Hours AS decimal(21,6)) AS Hours, PT.VariableWorkedHoursPerUOS + INTO #VariableHours + FROM #PayrollSampledPayPeriodStaging FP + INNER JOIN fw.DimPayPeriod PP ON PP.PayPeriodID = FP.PayPeriodID + INNER JOIN clientpi.ProductivityTargetsByDepartment PT ON PT.FiscalYearID = PP.FiscalYearIDSecond AND PT.DepartmentID = FP.DepartmentID AND (PT.PeriodNumber = PP.PeriodNumber OR PT.PeriodNumber = 0) + LEFT JOIN + ( + SELECT VO.DepartmentID, VO.JobCodeID, VO.PayCodeGroupID, CASE WHEN VO.Variability > 0 THEN 1 ELSE 0 END AS IsVariable + FROM ob.PayrollVariabilityOverrideCache VO + INNER JOIN fw.DimPayCodeGroup PCG ON PCG.PayCodeGroupID = VO.PayCodeGroupID + WHERE PCG.ProductiveClassID = @ProductiveClassProductiveID + ) V1 ON V1.DepartmentID = FP.DepartmentID AND V1.JobCodeID = FP.JobCodeID AND V1.PayCodeGroupID = FP.PayCodeGroupID + LEFT JOIN + ( + SELECT D.DepartmentID, JC.JobCodeID, PCG.PayCodeGroupID, 1 AS IsVariable + FROM fw.DimDepartment D + CROSS JOIN fw.DimJobCode JC + CROSS JOIN fw.DimPayCodeGroup PCG + WHERE D.IsVariable = 1 AND JC.IsVariable = 1 AND PCG.IsVariable = 1 AND PCG.ProductiveClassID = @ProductiveClassProductiveID + ) V2 ON V2.DepartmentID = FP.DepartmentID AND V2.JobCodeID = FP.JobCodeID AND V2.PayCodeGroupID = FP.PayCodeGroupID + WHERE FP.TimeClassID = 20 AND COALESCE(V1.IsVariable, V2.IsVariable) = 1 AND (NOT (FP.IsSystemGenerated = 1 AND FP.Hours = 0)) + + SELECT VH.DepartmentID, VH.PayPeriodID, VH.JobCodeID, VH.PayCodeGroupID, (CASE WHEN D.IsZeroSum = 1 THEN 1.0 ELSE VH.Hours END)/D.Total AS Spread + INTO #Spreads + FROM #VariableHours VH + INNER JOIN + ( + SELECT DepartmentID, PayPeriodID, + CASE WHEN SUM(Hours) = 0 THEN 1 ELSE 0 END AS IsZeroSum, + CASE WHEN SUM(Hours) = 0 THEN COUNT(1) ELSE SUM(Hours) END AS Total + FROM #VariableHours + GROUP BY DepartmentID, PayPeriodID + ) D ON D.DepartmentID = VH.DepartmentID AND D.PayPeriodID = VH.PayPeriodID + + UPDATE ST + SET Hours = S.Spread * VH.VariableWorkedHoursPerUOS * COALESCE(FS.Units, 0) + FROM #VariableHours VH + INNER JOIN #Spreads S ON S.DepartmentID = VH.DepartmentID AND S.PayPeriodID = VH.PayPeriodID AND S.JobCodeID = VH.JobCodeID AND S.PayCodeGroupID = VH.PayCodeGroupID + INNER JOIN #PayrollSampledPayPeriodStaging ST ON ST.DepartmentID = VH.DepartmentID AND ST.PayPeriodID = VH.PayPeriodID AND ST.JobCodeID = VH.JobCodeID AND ST.PayCodeGroupID = VH.PayCodeGroupID + LEFT JOIN + ( + SELECT DepartmentID, PayPeriodID, SUM(Units) AS Units + FROM fw.viewPrimaryStatisticsStaffingByPayPeriod + WHERE TimeClassID = 20 AND IsDeleted = 0 + GROUP BY DepartmentID, PayPeriodID + ) FS ON FS.DepartmentID = VH.DepartmentID AND FS.PayPeriodID = VH.PayPeriodID + WHERE ST.TimeClassID = 20 + + IF OBJECT_ID('tempdb..#VariableHours') IS NOT NULL DROP TABLE #VariableHours + IF OBJECT_ID('tempdb..#Spreads') IS NOT NULL DROP TABLE #Spreads +GO + + +--------------------------------------------- + +-- fw.procFactPayrollSampledPayPeriodBaselineTargetUpdate +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-05-16 IP D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values +** 2 2018-05-24 KF D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values +** 3 2018-06-01 IP D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values (one year part) +** 4 2018-06-05 IP TK-58643 added filetr for current year only and non-zero records in output +** 5 2019-08-20 vfay D-08311 PR Sampling Proc : removed filtering out 0 Value Rows +** 6 2024-01-30 KF JAZZ-66821 Run PR Process Task: Some procs don't support non-consecutive pay period id (expect consecutive pay period id). It causes wrong YTD values & wrong Rolling Average Baseline Target values +** 7 2024-06-14 SM JAZZ-71536 change JobCodeID from smallint to int +*************************************************************/ +CREATE PROC [fw].[procFactPayrollSampledPayPeriodBaselineTargetUpdate] + @targetType tinyint = null, + @numberOfPayPeriods tinyint = null, + @departmentIDs nvarchar(max) = null, + @fiscalYearID int = 0 +as + if (@targetType is null) set @targetType = (select Value from pi.SystemSetting where Name = 'Target Basis') + if (@numberOfPayPeriods is null) set @numberOfPayPeriods = (select Value from pi.SystemSetting where Name = 'Number Of Rolling Average Pay Periods') + + create table #departments (val int primary key) + insert into #departments select val from ConvertCSValuesToTable(@departmentIDs, ',') + + create table #payperiods (val smallint primary key, PayCycleID int) + insert into #payperiods + select PayPeriodID, PayCycleID from fw.DimPayPeriod where FiscalYearIDSecond = @fiscalYearID + + create table #PayPeriodsPriorYear (val smallint primary key, PayCycleID int) + insert into #PayPeriodsPriorYear select PayPeriodID, PayCycleID from fw.DimPayPeriod where FiscalYearIDSecond = @fiscalYearID-1 + + declare @sql varchar(max) + + create table #temp + ( + DepartmentID int, + JobCodeID int, + PayCodeGroupID int, + PayPeriodID smallint, + Hours decimal (18, 6), + Dollars decimal (18, 6) + ) + + if (@targetType = 10) begin --Rolling Average + IF OBJECT_ID('tempdb..#fullscope') IS NOT NULL DROP TABLE #fullscope + IF OBJECT_ID('tempdb..#tempSortedPayPeriods') IS NOT NULL DROP TABLE #tempSortedPayPeriods + select PayCycleID, PayPeriodID, SortOrder into #tempSortedPayPeriods from pi.viewPayPeriodsSortedInPayCycles + + IF @fiscalYearID = 0 BEGIN + set @sql = ' + insert into #temp (DepartmentID, JobCodeID, PayCodeGroupID, PayPeriodID,Hours,Dollars) + select DepartmentID, JobCodeID, PayCodeGroupID, PayPeriodID, isnull(Hours,0.0),isnull(Dollars,0.0) + FROM ( + select FullScope.DepartmentID, FullScope.JobCodeID, FullScope.PayCodeGroupID, FullScope.PayPeriodID, + Dollars = ISNULL((SUM(Dollars) over(PARTITION BY DepartmentID, JobCodeID, PayCodeGroupID, t.PayCycleID ORDER BY t.SortOrder ROWS BETWEEN '+cast(@numberOfPayPeriods as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfPayPeriods AS NVARCHAR(2)) +', 0), + Hours = ISNULL((SUM(Hours) over(PARTITION BY DepartmentID, JobCodeID, PayCodeGroupID, t.PayCycleID ORDER BY t.SortOrder ROWS BETWEEN '+cast(@numberOfPayPeriods as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfPayPeriods AS NVARCHAR(2)) +', 0) + FROM ( + select DepartmentID, JobCodeID, PayCodeGroupID, PayPeriodID, /*records for months, which are absent in current year, but exist at least one month*/ + SUM(Dollars) as Dollars, + SUM(Hours) as Hours + FROM ( + SELECT /*recods for months which are present in current year*/ + p.DepartmentID, p.JobCodeID, p.PayCodeGroupID, p.PayPeriodID, + p.Hours, + p.Dollars + FROM #PayrollSampledPayPeriodStaging p + where p.TimeClassID = 1 and p.isSystemGenerated = 0 + + UNION ALL + + SELECT /*combination of all for key columns months for current year*/ + p.DepartmentID, p.JobCodeID, p.PayCodeGroupID, dpp.PayPeriodID, + 0 AS Hours, + 0 AS Dollars + FROM #PayrollSampledPayPeriodStaging p + inner join #tempSortedPayPeriods pp on pp.PayPeriodID = p.PayPeriodID + FULL join #tempSortedPayPeriods dpp on dpp.PayCycleID = pp.PayCycleID + where dpp.SortOrder - pp.SortOrder between 1 and '+cast(@numberOfPayPeriods as nvarchar(2))+' + and p.TimeClassID = 1 and p.isSystemGenerated = 0 + ) AllCombinations + GROUP BY DepartmentID, JobCodeID, PayCodeGroupID, PayPeriodID + ) FullScope + inner join #tempSortedPayPeriods t on t.PayPeriodID = FullScope.PayPeriodID + ) FinalDataset + WHERE (Dollars is not null + or Hours is not null)' + END + ELSE BEGIN -- @fiscalYearID != 0 + IF OBJECT_ID('tempdb..#PayPeriodsAllScope') IS NOT NULL DROP TABLE #PayPeriodsAllScope + select * into #PayPeriodsAllScope from #payperiods + + insert into #PayPeriodsAllScope + select pp.PayPeriodID, pp.PayCycleID + from fw.DimPayPeriod pp + inner join #tempSortedPayPeriods t on t.PayPeriodID = pp.PayPeriodID + inner join + ( + select s.PayCycleID, MIN(s.SortOrder-@numberOfPayPeriods) as MinSortOrder, MIN(s.SortOrder -1) as MaxSortOrder + from #payperiods pp + inner join #tempSortedPayPeriods s on s.PayPeriodID = pp.val + group by s.PayCycleID + ) r on r.PayCycleID = pp.PayCycleID and t.SortOrder between MinSortOrder and MaxSortOrder + + set @sql = ' + select C.DepartmentID, C.JobCodeID, C.PayCodeGroupID, C.PayPeriodID, /*records for months, which are absent in current year, but exist at least one month*/ + SUM(C.Dollars) as Dollars, + SUM(C.Hours) as Hours + into #fullscope + FROM ( + SELECT /*recods for months which are present in current year*/ + p.DepartmentID, p.JobCodeID, p.PayCodeGroupID , p.PayPeriodID, + p.Hours, + p.Dollars + FROM #PayrollSampledPayPeriodStaging p /*table contains only this particular actuals (filtered by Depts, Year) no need for additional filters*/ + where TimeClassID = 1 and isSystemGenerated = 0 + + UNION ALL + + SELECT /*recods for months which are present in current year*/ + p.DepartmentID, p.JobCodeID, p.PayCodeGroupID , p.PayPeriodID, + p.Hours, + p.Dollars + FROM fw.FactPayrollSampledPayPeriod p + inner join #PayPeriodsPriorYear pppy on p.PayPeriodID = pppy.val /*filtering only values for "prior year", in fact periods, which affects current year*/ + '+ case when @departmentIDs IS NULL then '' else ' INNER JOIN #departments dpt on dpt.val = p.DepartmentID' end+' + where p.TimeClassID = 1 and p.isSystemGenerated = 0 + + UNION ALL + + SELECT /*combination of all for key columns months for current year*/ + p.DepartmentID, p.JobCodeID, p.PayCodeGroupID, dpp.Val as PayPeriodID, + 0 AS Hours, + 0 AS Dollars + FROM #PayrollSampledPayPeriodStaging p + inner join fw.DimPayPeriod pp on pp.PayPeriodID = p.PayPeriodID + FULL join #PayPeriodsAllScope dpp on dpp.PayCycleID = pp.PayCycleID + where p.TimeClassID = 1 and p.isSystemGenerated = 0 + + UNION ALL + + SELECT /*combination of all for key columns months for current year*/ + p.DepartmentID, p.JobCodeID, p.PayCodeGroupID, dpp.PayPeriodID, + 0 AS Hours, + 0 AS Dollars + FROM fw.FactPayrollSampledPayPeriodDetailed p + INNER JOIN #PayPeriodsPriorYear pppy on p.PayPeriodID = pppy.val /*filtering only values for "prior year", in fact periods, which affects current year*/ + INNER JOIN fw.DimPayPeriod dpp ON dpp.PayCycleID = pppy.PayCycleID + '+ case when @departmentIDs IS NULL then '' else ' INNER JOIN #departments dpt on dpt.val = p.DepartmentID' end + +' where p.TimeClassID = 1 and p.isSystemGenerated = 0 + ) C + inner join #PayPeriodsAllScope P on p.val = C.PayPeriodID + GROUP BY C.DepartmentID, C.JobCodeID, C.PayCodeGroupID, C.PayPeriodID + + insert into #temp (DepartmentID, JobCodeID, PayCodeGroupID, PayPeriodID,Hours,Dollars) + select DepartmentID, JobCodeID, PayCodeGroupID, PayPeriodID, isnull(Hours,0.0),isnull(Dollars,0.0) + FROM + ( + select f.DepartmentID, f.JobCodeID, f.PayCodeGroupID, f.PayPeriodID, + Dollars = ISNULL((SUM(f.Dollars) over(PARTITION BY f.DepartmentID, f.JobCodeID, f.PayCodeGroupID, t.PayCycleID ORDER BY t.SortOrder ROWS BETWEEN '+cast(@numberOfPayPeriods as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfPayPeriods AS NVARCHAR(2)) +', 0), + Hours = ISNULL((SUM(f.Hours) over(PARTITION BY f.DepartmentID, f.JobCodeID, f.PayCodeGroupID, t.PayCycleID ORDER BY t.SortOrder ROWS BETWEEN '+cast(@numberOfPayPeriods as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfPayPeriods AS NVARCHAR(2)) +', 0) + FROM #fullscope f + inner join #tempSortedPayPeriods t on t.PayPeriodID = f.PayPeriodID + ) FinalDataset + INNER JOIN #PayPeriods PP on pp.Val = FinalDataset.PayPeriodID + WHERE (Dollars is not null + or Hours is not null)' + END + exec(@sql) + IF OBJECT_ID('tempdb..#fullscope') IS NOT NULL DROP TABLE #fullscope + + end else begin --Budget + insert into #temp + (DepartmentID, JobCodeID, PayCodeGroupID, PayPeriodID, Hours ,Dollars) + select DepartmentID, JobCodeID, PayCodeGroupID, PayPeriodID, isnull(Hours,0.0),isnull(Dollars,0.0) + from #PayrollSampledPayPeriodStaging + where TimeClassID = 2 and (@departmentIDs is null or DepartmentID in (select val from #departments)) and (@fiscalYearID = 0 or PayPeriodID in(select val from #payperiods)) + end + + insert into #PayrollSampledPayPeriodStaging (DepartmentID, JobCodeID, PayPeriodID, PayCodeGroupID, TimeClassID, Hours,Dollars,HoursYTD,HoursPriorYear,HoursPriorYTD,DollarsYTD,DollarsPriorYear,DollarsPriorYTD,FTEs,FTEsYTD,FTEsPriorYear,FTEsPriorYTD, isSystemGenerated) + SELECT DepartmentID, JobCodeID, PayPeriodID, PayCodeGroupID, 20 as TimeClassID, Hours,Dollars,0 as HoursYTD,0 as HoursPriorYear,0 as HoursPriorYTD,0 as DollarsYTD,0 as DollarsPriorYear,0 as DollarsPriorYTD,0 as FTEs,0 as FTEsYTD,0 as FTEsPriorYear,0 as FTEsPriorYTD, 0 as isSystemGenerated from #temp + where (@fiscalYearID = 0 or PayPeriodID in(select val from #payperiods)) + drop table #temp + drop table #departments + IF OBJECT_ID('tempdb..#PayPeriodsAllScope') IS NOT NULL DROP TABLE #PayPeriodsAllScope + IF OBJECT_ID('tempdb..#tempSortedPayPeriods') IS NOT NULL DROP TABLE #tempSortedPayPeriods; +GO + + +--------------------------------------------- + +-- fw.procFactPayrollSampledPayPeriodDetailedBaselineTargetUpdate +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-05-16 IP D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values +** 2 2018-05-16 KF D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values +** 3 2018-06-01 IP D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values (one year part) +** 4 2018-06-05 IP TK-58643 added filetr for current year only and non-zero records in output +** 5 2019-08-23 vfay D-08311 PR Sampling Proc : removed filtering out 0 Value Rows +** 6 2024-01-30 KF JAZZ-66821 Run PR Process Task: Some procs don't support non-consecutive pay period id (expect consecutive pay period id). It causes wrong YTD values & wrong Rolling Average Baseline Target values +** 7 2024-06-14 SM JAZZ-71536 change JobCodeID from smallint to int +*************************************************************/ +CREATE proc [fw].[procFactPayrollSampledPayPeriodDetailedBaselineTargetUpdate] + @targetType tinyint = null, + @numberOfPayPeriods tinyint = null, + @departmentIDs nvarchar(max) = null, + @fiscalYearID int = 0 +with recompile +as + if (@targetType is null) set @targetType = (select Value from pi.SystemSetting where Name = 'Target Basis') + if (@numberOfPayPeriods is null) set @numberOfPayPeriods = (select Value from pi.SystemSetting where Name = 'Number Of Rolling Average Pay Periods') + + create table #departments (val int primary key) + insert into #departments select val from ConvertCSValuesToTable(@departmentIDs, ',') + + create table #payperiods (val smallint primary key, PayCycleID int) + insert into #payperiods + select PayPeriodID, PayCycleID from fw.DimPayPeriod where FiscalYearIDSecond = @fiscalYearID + + create table #PayPeriodsPriorYear (val smallint primary key, PayCycleID int) + insert into #PayPeriodsPriorYear select PayPeriodID, PayCycleID from fw.DimPayPeriod where FiscalYearIDSecond = @fiscalYearID-1 + + declare @sql varchar(max) + + create table #temp + ( + DepartmentID int, + JobCodeID int, + PayCodeID int, + PayCodeGroupID int, + EmployeeID int, + PayPeriodID smallint, + Hours decimal (18, 6), + Dollars decimal (18, 6) + ) + + if (@targetType = 10) begin --Rolling Average + IF OBJECT_ID('tempdb..#fullscope') IS NOT NULL DROP TABLE #fullscope + IF OBJECT_ID('tempdb..#tempSortedPayPeriods') IS NOT NULL DROP TABLE #tempSortedPayPeriods + select PayCycleID, PayPeriodID, SortOrder into #tempSortedPayPeriods from pi.viewPayPeriodsSortedInPayCycles + + IF @fiscalYearID = 0 BEGIN + set @sql = ' + insert into #temp (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, Hours, Dollars) + select DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, isnull(Hours,0.0),isnull(Dollars,0.0) + FROM ( + select FullScope.DepartmentID, FullScope.JobCodeID, FullScope.PayCodeID, FullScope.PayCodeGroupID, FullScope.EmployeeId, FullScope.PayPeriodID, + Dollars = ISNULL((Sum(Dollars) over(PARTITION BY DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, t.PayCycleID ORDER BY t.SortOrder ROWS BETWEEN '+cast(@numberOfPayPeriods as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/'+cast(@numberOfPayPeriods as nvarchar(2))+', 0), + Hours = ISNULL((Sum(Hours) over(PARTITION BY DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, t.PayCycleID ORDER BY t.SortOrder ROWS BETWEEN '+cast(@numberOfPayPeriods as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/'+cast(@numberOfPayPeriods as nvarchar(2))+', 0) + FROM ( + select DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, /*records for months, which are absent in current year, but exist at least one month*/ + SUM(Dollars) as Dollars, + SUM(Hours) as Hours + FROM ( + SELECT /*recods for months which are present in current year*/ + p.DepartmentID, p.JobCodeID, p.PayCodeID, p.PayCodeGroupID, p.EmployeeID, p.PayPeriodID, + p.Hours, + p.Dollars + FROM #PayrollSampledPayPeriodDetailedStaging p + where p.TimeClassID = 1 and p.isSystemGenerated = 0 + + UNION ALL + + SELECT /*combination of all for key columns months for current year*/ + p.DepartmentID, p.JobCodeID, p.PayCodeID, p.PayCodeGroupID, p.EmployeeID, dpp.PayPeriodID, + 0 AS Hours, + 0 AS Dollars + FROM #PayrollSampledPayPeriodDetailedStaging p + inner join #tempSortedPayPeriods pp on pp.PayPeriodID = p.PayPeriodID + FULL join #tempSortedPayPeriods dpp on dpp.PayCycleID = pp.PayCycleID + where dpp.SortOrder - pp.SortOrder between 1 and '+cast(@numberOfPayPeriods as nvarchar(2))+' + and p.TimeClassID = 1 and p.isSystemGenerated = 0 + ) AllCombinations + GROUP BY DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, PayPeriodID, EmployeeID + ) FullScope + inner join #tempSortedPayPeriods t on t.PayPeriodID = FullScope.PayPeriodID + ) FinalDataset + WHERE (Dollars is not null + or Hours is not null)' + end + ELSE BEGIN -- @fiscalYearID != 0 + IF OBJECT_ID('tempdb..#PayPeriodsAllScope') IS NOT NULL DROP TABLE #PayPeriodsAllScope + select * into #PayPeriodsAllScope from #payperiods + + insert into #PayPeriodsAllScope + select pp.PayPeriodID, pp.PayCycleID + from fw.DimPayPeriod pp + inner join #tempSortedPayPeriods t on t.PayPeriodID = pp.PayPeriodID + inner join + ( + select s.PayCycleID, MIN(s.SortOrder-@numberOfPayPeriods) as MinSortOrder, MIN(s.SortOrder -1) as MaxSortOrder + from #payperiods pp + inner join #tempSortedPayPeriods s on s.PayPeriodID = pp.val + group by s.PayCycleID + ) r on r.PayCycleID = pp.PayCycleID and t.SortOrder between MinSortOrder and MaxSortOrder + + set @sql = ' + select C.DepartmentID, C.JobCodeID, C.PayCodeID, C.PayCodeGroupID, C.EmployeeID, C.PayPeriodID, /*records for months, which are absent in current year, but exist at least one month*/ + SUM(C.Dollars) as Dollars, + SUM(C.Hours) as Hours + into #fullscope + FROM ( + SELECT + p.DepartmentID, p.JobCodeID, p.PayCodeID, p.PayCodeGroupID , EmployeeID, p.PayPeriodID, + p.Hours, + p.Dollars + FROM #PayrollSampledPayPeriodDetailedStaging p /*table contains only this particular actuals (filtered by Depts, Year) no need for additional filters*/ + where TimeClassID = 1 and isSystemGenerated = 0 + + UNION ALL + + SELECT + p.DepartmentID, p.JobCodeID, p.PayCodeID, p.PayCodeGroupID, p.EmployeeID, p.PayPeriodID, + Hours, + Dollars + FROM fw.FactPayrollSampledPayPeriodDetailed p + inner join #PayPeriodsPriorYear pppy on p.PayPeriodID = pppy.val /*filtering only values for "prior year", in fact periods, which affects current year*/ + '+ case when @departmentIDs IS NULL then '' else ' INNER JOIN #departments dpt on dpt.val = p.DepartmentID' end+' + where p.TimeClassID = 1 and p.isSystemGenerated = 0 + + UNION ALL + + SELECT + p.DepartmentID, p.JobCodeID, p.PayCodeID, p.PayCodeGroupID, EmployeeID ,dpp.Val as PayPeriodID, + 0 AS Hours, + 0 AS Dollars + FROM #PayrollSampledPayPeriodDetailedStaging p + inner join fw.DimPayPeriod pp on pp.PayPeriodID = p.PayPeriodID + FULL join #PayPeriodsAllScope dpp on dpp.PayCycleID = pp.PayCycleID + where p.TimeClassID = 1 and p.isSystemGenerated = 0 + + UNION ALL + + SELECT + p.DepartmentID, p.JobCodeID, p.PayCodeID, p.PayCodeGroupID, p.EmployeeID, dpp.PayPeriodID, + 0 AS Hours, + 0 AS Dollars + FROM fw.FactPayrollSampledPayPeriodDetailed p + INNER JOIN #PayPeriodsPriorYear pppy on p.PayPeriodID = pppy.val /*filtering only values for "prior year", in fact periods, which affects current year*/ + INNER JOIN fw.DimPayPeriod dpp ON dpp.PayCycleID = pppy.PayCycleID + '+ case when @departmentIDs IS NULL then '' else ' INNER JOIN #departments dpt on dpt.val = p.DepartmentID' end + +' where p.TimeClassID = 1 and p.isSystemGenerated = 0 + ) C + inner join #PayPeriodsAllScope P on p.val = C.PayPeriodID + GROUP BY C.DepartmentID, C.JobCodeID, C.PayCodeID, C.PayCodeGroupID, C.EmployeeID, C.PayPeriodID + + insert into #temp (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, Hours, Dollars) + select DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, isnull(Hours,0.0), isnull(Dollars,0.0) + FROM ( + select f.DepartmentID, f.JobCodeID, f.PayCodeID, f.PayCodeGroupID, f.EmployeeID, f.PayPeriodID, + Dollars = ISNULL((Sum(f.Dollars) over(PARTITION BY f.DepartmentID, f.JobCodeID, f.PayCodeID, f.PayCodeGroupID, f.EmployeeID, t.PayCycleID ORDER BY t.SortOrder ROWS BETWEEN '+cast(@numberOfPayPeriods as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/'+cast(@numberOfPayPeriods as nvarchar(2))+', 0), + Hours = ISNULL((Sum(f.Hours) over(PARTITION BY f.DepartmentID, f.JobCodeID, f.PayCodeID, f.PayCodeGroupID, f.EmployeeID, t.PayCycleID ORDER BY t.SortOrder ROWS BETWEEN '+cast(@numberOfPayPeriods as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/'+cast(@numberOfPayPeriods as nvarchar(2))+', 0) + FROM #fullscope f + inner join #tempSortedPayPeriods t on t.PayPeriodID = f.PayPeriodID + ) FinalDataset + INNER JOIN #PayPeriods PP on pp.Val = FinalDataset.PayPeriodID + WHERE (Dollars is not null + or Hours is not null)' + END + exec(@sql) + + IF OBJECT_ID('tempdb..#fullscope') IS NOT NULL DROP TABLE #fullscope + + end else begin --Budget + insert into #temp + (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, Hours ,Dollars) + select DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, isnull(Hours,0.0),isnull(Dollars,0.0) + from #PayrollSampledPayPeriodDetailedStaging + where TimeClassID = 2 and (@departmentIDs is null or DepartmentID in (select val from #departments)) and (@fiscalYearID = 0 or PayPeriodID in(select val from #payperiods)) + end + + insert into #PayrollSampledPayPeriodDetailedStaging (DepartmentID, JobCodeID, PayPeriodID, PayCodeGroupID, PayCodeID, EmployeeID, TimeClassID, Hours, Dollars) + SELECT DepartmentID, JobCodeID, PayPeriodID, PayCodeGroupID, PayCodeID, EmployeeID, 20 as TimeClassID, Hours, Dollars from #temp + where (@fiscalYearID = 0 or PayPeriodID in(select val from #payperiods)) + + drop table #temp + drop table #departments + drop table #payperiods + IF OBJECT_ID('tempdb..#PayPeriodsAllScope') IS NOT NULL DROP TABLE #PayPeriodsAllScope + IF OBJECT_ID('tempdb..#tempSortedPayPeriods') IS NOT NULL DROP TABLE #tempSortedPayPeriods; +GO + + +--------------------------------------------- + +-- fw.procFactProviderSampledBaselineTargetUpdate +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-06-27 KF B-20195 MR - Provider calculate baseline target +** 2 2018-07-24 KF B-20342 MR - Update provider sampling to be in the appropriate format +*************************************************************/ +CREATE PROCEDURE [fw].[procFactProviderSampledBaselineTargetUpdate] + @fiscalYearID INT = 0 +AS + +CREATE TABLE #temp +( + DepartmentID INT, + ProviderID INT, + FiscalYearID INT, + FiscalMonthID INT, + OBForecastDetailID INT, + Dollars DECIMAL(18,6), + Hours DECIMAL(18,6), + Volume DECIMAL(18,6), + FTEs DECIMAL(18,6) +) + +--DECLARE @maxCalculatingFiscalYear INT = (SELECT MAX(FiscalYearID) FROM #ProviderSampledStaging) + +--TODO: if Prior Year YTD/Rolling Average types are added, @targetType initialization should be changed in proc client.procFactProviderSampledMonthlyFTEsInsert based on mr.SystemSetting +--Budget + INSERT INTO #temp + SELECT DepartmentID, ProviderID, FiscalYearID, FiscalMonthID, OBForecastDetailID, Dollars, Hours, Volume, FTEs + FROM #ProviderSampledStaging + WHERE TimeClassID = 2 + AND (FiscalYearID = @FiscalYearID OR @FiscalYearID = 0) + + +DELETE FROM #ProviderSampledStaging WHERE TimeClassID = 20 and (FiscalYearID = @FiscalYearID or @FiscalYearID = 0) +INSERT INTO #ProviderSampledStaging (DepartmentID, ProviderID, FiscalYearID, FiscalMonthID, TimeClassID, OBForecastDetailID, Dollars, Hours, Volume, FTEs) +SELECT source.DepartmentID, source.ProviderID, source.FiscalYearID, source.FiscalMonthID, 20, source.OBForecastDetailID, source.Dollars, source.Hours, source.Volume, source.FTEs FROM #temp source +WHERE NOT(Dollars = 0 AND Hours = 0 AND Volume = 0 AND FTEs = 0) + +DROP TABLE #temp +GO + + +--------------------------------------------- + +-- fw.procFactRoleAssignmentImportSample +CREATE proc [fw].[procFactRoleAssignmentImportSample] +as + declare @rowID int + declare @userGUID uniqueidentifier + declare @roleID smallint + declare @lootID nvarchar(16) + + declare crsRoleImport cursor fast_forward for select RowID, UserGUID, RoleID, LootGroupID from client.viewFactRoleAssignmentImport + + open crsRoleImport + fetch next from crsRoleImport into @rowID, @userGUID, @roleID, @lootID + + while(@@FETCH_STATUS = 0) begin + exec procS3AssignIdentityToRole @userGUID, @roleID, @lootID + update client.FactRoleAssignmentImport set ImportDate = GETDATE() where RowID = @rowID and SampleDate = '01/01/1900' + fetch next from crsRoleImport into @rowID, @userGUID, @roleID, @lootID + end + + close crsRoleImport + deallocate crsRoleImport +GO + + +--------------------------------------------- + +-- fw.procFactStatisticPrimarySampledBaselineTargetUpdate +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-03-06 gforeman B-14693 Added year filter +** 2 2017-03-28 ipetriv D-05641 Logic for Prior and Actual was changed to simply copy actuals from previous year +** 3 2017-04-05 ipetriv D-05789 Changed algorithm for rolling average calculation +** 4 2017-05-24 IPetriv B-15086 Sampling Performance Improvements. Using temp tables insead of fw.FactStatisticPrimarySampledMonthly. +** 5 2017-06-15 IP B-15086 Modify SP to use unique temp table +** 6 2018-05-16 IP D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values +** 7 2018-05-16 KF D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values +** 8 2018-06-01 IP D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values (one year part) +** 9 2018-06-05 IP TK-58643 added filetr for current year only and non-zero records in output +*************************************************************/ +CREATE proc [fw].[procFactStatisticPrimarySampledBaselineTargetUpdate] + @targetType int = null, + @numberOfMonths int = null, + @fiscalYearID int = 0 + +as + if (@targetType is null) set @targetType = (select Value from mr.SystemSetting where Name = 'Target Basis') + if (@numberOfMonths is null) set @numberOfMonths = (select Value from mr.SystemSetting where Name = 'Number Of Rolling Average Months') + + declare @sql varchar(max) + declare @maxCalculatingFiscalYear int = (select max(FiscalYearID) from #StatisticPrimarySampledStaging) + + create table #temp + ( + DepartmentID int, + AccountID int, + FiscalYearID smallint, + FiscalMonthID tinyint, + Amount decimal (19, 4) + ) + + if (@targetType = 1) begin --Prior Year Actual + if @fiscalYearID <> 0 + insert into #temp + select d.DepartmentID, d.AccountID, d.FiscalYearID+1, d.FiscalMonthID, d.Amount + from fw.FactStatisticPrimarySampledMonthly d WHERE d.TimeClassID = 1 and d.FiscalYearID = @fiscalYearID-1 + else + insert into #temp + select d.DepartmentID, d.AccountID, d.FiscalYearID+1, d.FiscalMonthID, d.Amount + from #StatisticPrimarySampledStaging d WHERE d.TimeClassID = 1 + end else if (@targetType = 10) begin --Rolling Average + IF @fiscalYearID = 0 + set @sql = ' + insert into #temp + select DepartmentID, AccountID, FiscalYearID, FiscalMonthID,isnull(Amount,0.0) FROM ( + select FullScope.DepartmentID, FullScope.AccountID, FullScope.FiscalYearID, m.FiscalMonthID, + Amount = ISNULL((Sum(Amount) over(PARTITION BY DepartmentID,AccountID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfMonths AS NVARCHAR(2)) +', 0) + FROM ( + select DepartmentID, /*records for months, which are absent in current year, but exist at least one month*/ + AccountID, + FiscalYearID, + SortOrder, + SUM(Amount) as Amount + FROM ( + SELECT /*recods for months which are present in current year*/ + DepartmentID, + AccountID, + FiscalYearID, + m.SortOrder, + Amount + FROM #StatisticPrimarySampledStaging p + JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID + where m.FiscalMonthID <> 0 and TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0 + UNION ALL + SELECT /*combination of all for key columns months which were present in prior year*/ + p.DepartmentID, + p.AccountID, + fy.FiscalYearID, + m.SortOrder, + 0 AS Amount + FROM #StatisticPrimarySampledStaging p + CROSS JOIN fw.DimFiscalMonth m + CROSS JOIN (select FiscalYearID + from fw.DimFiscalYear dm + ) fy + where m.FiscalMonthID <> 0 and p.TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0 + ) AllCombinations + GROUP BY DepartmentID,AccountID,FiscalYearID,SortOrder + ) FullScope + JOIN fw.DimFiscalMonth m ON FullScope.SortOrder = m.SortOrder + ) FinalDataset + WHERE Amount is not null + AND FiscalYearID <='+cast(@maxCalculatingFiscalYear as nvarchar(4)) + ELSE + SET @sql = ' + insert into #temp + select DepartmentID, AccountID, FiscalYearID, FiscalMonthID,isnull(Amount,0.0) FROM ( + select FullScope.DepartmentID, FullScope.AccountID, FullScope.FiscalYearID, m.FiscalMonthID, + Amount = ISNULL((Sum(Amount) over(PARTITION BY DepartmentID,AccountID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfMonths AS NVARCHAR(2)) +', 0) + FROM ( + select DepartmentID, /*records for months, which are absent in current year, but exist at least one month*/ + AccountID, + FiscalYearID, + SortOrder, + SUM(Amount) as Amount + FROM ( + SELECT /*recods for months which are present in current year*/ + DepartmentID, + AccountID, + FiscalYearID, + m.SortOrder, + Amount + FROM #StatisticPrimarySampledStaging p + JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID + where m.FiscalMonthID <> 0 and TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0 + UNION ALL + SELECT /*recods with amounts from previous year*/ + DepartmentID, + AccountID, + FiscalYearID, + m.SortOrder, + Amount + FROM fw.FactStatisticPrimarySampledMonthly p + JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID + where m.FiscalMonthID <> 0 and TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0 + and FiscalYearID = '+cast(@fiscalYearID-1 as nvarchar(4)) +' + UNION ALL + SELECT /*combination of all for key columns months for current year*/ + DepartmentID, + AccountID, + FiscalYearID, + m.SortOrder, + 0 AS Amount + FROM #StatisticPrimarySampledStaging p + CROSS APPLY fw.DimFiscalMonth m + where m.FiscalMonthID <> 0 and TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0 + UNION ALL + SELECT /*combination of all for key columns months which were present in prior year*/ + p.DepartmentID, + p.AccountID, + fy.FiscalYearID, + m.SortOrder, + 0 AS Amount + FROM fw.FactStatisticPrimarySampledMonthly p + CROSS JOIN fw.DimFiscalMonth m + CROSS JOIN (select FiscalYearID + from fw.DimFiscalYear dm + where FiscalYearID in ('+cast(@fiscalYearID-1 as nvarchar(4))+','+cast(@fiscalYearID as nvarchar(4))+')'+' + ) fy + where m.FiscalMonthID <> 0 and p.TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0 and p.FiscalYearID = '+cast(@fiscalYearID-1 as nvarchar(4)) +' + ) AllCombinations + GROUP BY DepartmentID,AccountID,FiscalYearID,SortOrder + ) FullScope + JOIN fw.DimFiscalMonth m ON FullScope.SortOrder = m.SortOrder + ) FinalDataset + WHERE Amount is not null + AND FiscalYearID ='+cast(@fiscalYearID as nvarchar(4)) + exec (@sql) + end else begin --Budget + insert into #temp + select DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Amount + from #StatisticPrimarySampledStaging + where TimeClassID = 2 and (@fiscalYearID = 0 or FiscalYearID = @fiscalYearID) + end + + insert into #StatisticPrimarySampledStaging (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Amount) + select DepartmentID, AccountID, FiscalYearID, FiscalMonthID, 20, Amount from #temp + where (@fiscalYearID = 0 or FiscalYearID = @fiscalYearID) and Amount !=0 + + drop table #temp +GO + + +--------------------------------------------- + +-- fw.procFactStatisticSampledBaselineTargetUpdate +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-03-06 gforeman B-14693 Added year filter +** 2 2017-03-28 ipetriv D-05641 Logic for Prior and Actual was changed to simply copy actuals from previous year +** 3 2017-04-05 ipetriv D-05789 Changed algorithm for rolling average calculation +** 4 2017-05-24 IPetriv B-15086 Sampling Performance Improvements. Using temp tables insead of fw.FactPayrollSampledMonthlyDetailed. +** 5 2017-06-07 IPetriv B-15086 Fixed after integration test fails +** 6 2017-06-15 IP B-15086 Modify SP to use unique temp table +** 7 2018-05-16 IP D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values +** 8 2018-05-16 KF D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values +** 9 2018-06-01 IP D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values (one year part) +** 10 2018-06-05 IP TK-58643 added filetr for current year only and non-zero records in output +*************************************************************/ +CREATE proc [fw].[procFactStatisticSampledBaselineTargetUpdate] + @targetType int = null, + @numberOfMonths int = null, + @fiscalYearID int = 0 +with recompile +as + + if (@targetType is null) set @targetType = (select Value from mr.SystemSetting where Name = 'Target Basis') + if (@numberOfMonths is null) set @numberOfMonths = (select Value from mr.SystemSetting where Name = 'Number Of Rolling Average Months') + + declare @sql varchar(max) + declare @maxCalculatingFiscalYear int = (select max(FiscalYearID) from #StatisticSampledMonthlyStaging) + + create table #temp + ( + DepartmentID int, + AccountID int, + FiscalYearID smallint, + FiscalMonthID tinyint, + Amount decimal (18, 6) + ) + + if (@targetType = 1) begin --Prior Year Actual + if @fiscalYearID <> 0 + insert into #temp + select d.DepartmentID, d.AccountID, d.FiscalYearID+1, d.FiscalMonthID, d.Amount + from fw.FactStatisticSampledMonthly d where d.TimeClassID = 1 and d.FiscalYearID = @fiscalYearID-1 + else + insert into #temp + select d.DepartmentID, d.AccountID, d.FiscalYearID+1, d.FiscalMonthID, d.Amount + from #StatisticSampledMonthlyStaging d where d.TimeClassID = 1 + end else if (@targetType = 10) begin --Rolling Average + IF @fiscalYearID = 0 + set @sql = ' + + insert into #temp + select DepartmentID, AccountID, FiscalYearID, FiscalMonthID,isnull(Amount,0.0) FROM ( + select FullScope.DepartmentID, FullScope.AccountID, FullScope.FiscalYearID, m.FiscalMonthID, + Amount = ISNULL((Sum(Amount) over(PARTITION BY DepartmentID,AccountID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfMonths AS NVARCHAR(2)) +', 0) + FROM ( + select DepartmentID, /*records for months, which are absent in current year, but exist at least one month*/ + AccountID, + FiscalYearID, + SortOrder, + SUM(Amount) as Amount + FROM ( + SELECT /*recods for months which are present in current year*/ + DepartmentID, + AccountID, + FiscalYearID, + m.SortOrder, + Amount + FROM #StatisticSampledMonthlyStaging p + JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID + where m.FiscalMonthID <> 0 and TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0 + UNION ALL + SELECT /*combination of all for key columns months for current year*/ + p.DepartmentID, + p.AccountID, + fy.FiscalYearID, + fy.SortOrder, + 0 AS Amount + FROM #StatisticSampledMonthlyStaging p + INNER JOIN fw.DimFiscalMonth m on m.FiscalMonthID = p.FiscalMonthID + INNER JOIN (select FiscalYearID,FiscalMonthID,fm.sortOrder,fy.FiscalYearID*12+fm.SortOrder as ChronologicalOrder from fw.DimFiscalYear fy + full join fw.DimFiscalMonth fm on 1= 1 + where FiscalMonthID <> 0 and FiscalYearID <> 0) fy ON ChronologicalOrder - (p.FiscalYearID*12+m.SortOrder) between 1 and '+cast(@numberOfMonths as nvarchar(2))+' + where m.FiscalMonthID <> 0 and p.TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0 + ) AllCombinations + GROUP BY DepartmentID,AccountID,FiscalYearID,SortOrder + ) FullScope + JOIN fw.DimFiscalMonth m ON FullScope.SortOrder = m.SortOrder + ) FinalDataset + WHERE Amount is not null + AND FiscalYearID <='+cast(@maxCalculatingFiscalYear as nvarchar(4)) + ELSE + set @sql = ' + + insert into #temp + select DepartmentID, AccountID, FiscalYearID, FiscalMonthID,isnull(Amount,0.0) FROM ( + select FullScope.DepartmentID, FullScope.AccountID, FullScope.FiscalYearID, m.FiscalMonthID, + Amount = ISNULL((Sum(Amount) over(PARTITION BY DepartmentID,AccountID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfMonths AS NVARCHAR(2)) +', 0) + FROM ( + select DepartmentID, /*records for months, which are absent in current year, but exist at least one month*/ + AccountID, + FiscalYearID, + SortOrder, + SUM(Amount) as Amount + FROM ( + SELECT /*recods for months which are present in current year*/ + DepartmentID, + AccountID, + FiscalYearID, + m.SortOrder, + Amount + FROM #StatisticSampledMonthlyStaging p + JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID + where m.FiscalMonthID <> 0 and TimeClassID = 1 and isnull(isSystemGenerated,0) = 0 + UNION ALL + SELECT /*recods with amounts from previous year*/ + DepartmentID, + AccountID, + FiscalYearID, + m.SortOrder, + Amount + FROM fw.FactStatisticSampledMonthly p + INNER JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID + where m.FiscalMonthID <> 0 and TimeClassID = 1 and isnull(isSystemGenerated,0) = 0 + and FiscalYearID = '+cast(@fiscalYearID-1 as nvarchar(4)) +' + UNION ALL + SELECT /*combination of all for key columns months for current year*/ + DepartmentID, + AccountID, + FiscalYearID, + m.SortOrder, + 0 AS Amount + FROM #StatisticSampledMonthlyStaging p + CROSS APPLY fw.DimFiscalMonth m + where m.FiscalMonthID <> 0 and TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0 + UNION ALL + SELECT /*combination of all for key columns months for current year*/ + p.DepartmentID, + p.AccountID, + fy.FiscalYearID, + m.SortOrder, + 0 AS Amount + FROM fw.FactStatisticSampledMonthly p + CROSS JOIN fw.DimFiscalMonth m + CROSS JOIN (select FiscalYearID + from fw.DimFiscalYear dm + where FiscalYearID in ('+cast(@fiscalYearID-1 as nvarchar(4))+','+cast(@fiscalYearID as nvarchar(4))+')'+' + ) fy + where m.FiscalMonthID <> 0 and p.TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0 and p.FiscalYearID ='+cast(@fiscalYearID-1 as nvarchar(4))+' + ) AllCombinations + GROUP BY DepartmentID,AccountID,FiscalYearID,SortOrder + ) FullScope + JOIN fw.DimFiscalMonth m ON FullScope.SortOrder = m.SortOrder + ) FinalDataset + WHERE Amount is not null + AND FiscalYearID ='+cast(@fiscalYearID as nvarchar(4)) + exec (@sql) + end else begin --Budget + insert into #temp + select DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Amount + from #StatisticSampledMonthlyStaging + where TimeClassID = 2 and (@fiscalYearID = 0 or FiscalYearID = @fiscalYearID) + end + + insert into #StatisticSampledMonthlyStaging (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, isSystemGenerated) + select DepartmentID, AccountID, FiscalYearID, FiscalMonthID, 20, Amount, 0 as isSystemGenerated from #temp + WHERE (@fiscalYearID = 0 or FiscalYearID = @fiscalYearID) and Amount !=0 + + drop table #temp +GO + + +--------------------------------------------- + +-- fw.procFactStatisticSampledPayPeriodBaselineTargetUpdate +/************************************************************ +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-02-08 GJF B-14308 Added year filter +** 2 2017-04-05 ipetriv D-05789 Changed algorithm for rolling average calculation +** 3 2017-05-29 ipetriv B-15994 Refactored sampling process and implemented using of staging tables +** 4 2017-06-15 IP B-15086 Modify SP to use unique temp table +** 5 2018-05-16 IP D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values +** 6 2018-05-16 KF D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values +** 7 2018-06-01 IP D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values (one year part) +** 8 2018-06-05 IP TK-58643 added filetr for current year only and non-zero records in output +** 9 2018-06-05 IP TK-58643 added filetr for current year only and non-zero records in output +** 10 2020-07-30 HV JAZZ-2302 YTD PR Calculations Incorrect when Processing Current Year Only +** 11 2024-01-30 KF JAZZ-66821 Run PR Process Task: Some procs don't support non-consecutive pay period id (expect consecutive pay period id). It causes wrong YTD values & wrong Rolling Average Baseline Target values +*************************************************************/ +CREATE PROCEDURE [fw].[procFactStatisticSampledPayPeriodBaselineTargetUpdate] + @targetType tinyint = null, + @numberOfPayPeriods tinyint = null, + @departmentIDs nvarchar(max) = null, + @fiscalYearID int = 0 +with recompile +as + if (@targetType is null) set @targetType = (select Value from pi.SystemSetting where Name = 'Target Basis') + if (@numberOfPayPeriods is null) set @numberOfPayPeriods = (select Value from pi.SystemSetting where Name = 'Number Of Rolling Average Pay Periods') + declare @sql varchar(max) + + create table #departments (val int primary key) + insert into #departments select val from ConvertCSValuesToTable(@departmentIDs, ',') + + create table #payperiods(val smallint primary key, PayCycleID int) + insert into #payperiods select PayPeriodID, PayCycleID from fw.DimPayPeriod where FiscalYearIDSecond = @fiscalYearID + + create table #PayPeriodsPriorYear (val smallint primary key, PayCycleID int) + insert into #PayPeriodsPriorYear select PayPeriodID, PayCycleID from fw.DimPayPeriod where FiscalYearIDSecond = @fiscalYearID-1 + + create table #temp + ( + DepartmentID int, + AccountID int, + PayPeriodID smallint, + Units decimal (18, 6) + ) + + if (@targetType = 10) begin --Rolling Average + IF OBJECT_ID('tempdb..#fullscope') IS NOT NULL DROP TABLE #fullscope + IF OBJECT_ID('tempdb..#tempSortedPayPeriods') IS NOT NULL DROP TABLE #tempSortedPayPeriods + SELECT PayCycleID, PayPeriodID, SortOrder INTO #tempSortedPayPeriods FROM pi.viewPayPeriodsSortedInPayCycles + + IF @fiscalYearID = 0 BEGIN + set @sql = ' + insert into #temp (DepartmentID, AccountID, PayPeriodID, Units) + select DepartmentID, AccountID, PayPeriodID, isnull(Units,0.0) + FROM ( + select FullScope.DepartmentID, FullScope.AccountID, FullScope.PayPeriodID, + Units = ISNULL((Sum(Units) over(PARTITION BY DepartmentID, AccountID, t.PayCycleID ORDER BY t.SortOrder ROWS BETWEEN '+cast(@numberOfPayPeriods as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/'+cast(@numberOfPayPeriods as nvarchar(2))+', 0) + FROM + ( + select DepartmentID, AccountID, PayPeriodID, /*records for months, which are absent in current year, but exist at least one month*/ + SUM(Units) as Units + FROM ( + SELECT /*recods for months which are present in current year*/ + p.DepartmentID, p.AccountID, p.PayPeriodID, + p.Units + FROM #StatisticSampledPayPeriod p + where TimeClassID = 1 and isSystemGenerated = 0 + UNION ALL + SELECT /*combination of all for key columns months for current year*/ + p.DepartmentID, p.AccountID, dpp.PayPeriodID, + 0 AS Units + FROM #StatisticSampledPayPeriod p + inner join #tempSortedPayPeriods pp on pp.PayPeriodID = p.PayPeriodID + FULL join #tempSortedPayPeriods dpp on dpp.PayCycleID = pp.PayCycleID + where dpp.SortOrder - pp.SortOrder between 1 and '+cast(@numberOfPayPeriods as nvarchar(2))+' + and p.TimeClassID = 1 and p.isSystemGenerated = 0 + ) AllCombinations + GROUP BY DepartmentID, AccountID, PayPeriodID + ) FullScope + inner join #tempSortedPayPeriods t on t.PayPeriodID = FullScope.PayPeriodID + ) FinalDataset + WHERE Units is not null' + END + ELSE BEGIN -- @fiscalYearID != 0 + IF OBJECT_ID('tempdb..#PayPeriodsAllScope') IS NOT NULL DROP TABLE #PayPeriodsAllScope + select * into #PayPeriodsAllScope from #payperiods + + insert into #PayPeriodsAllScope + select pp.PayPeriodID, pp.PayCycleID + from fw.DimPayPeriod pp + inner join #tempSortedPayPeriods t on t.PayPeriodID = pp.PayPeriodID + inner join + ( + select s.PayCycleID, MIN(s.SortOrder-@numberOfPayPeriods) as MinSortOrder, MIN(s.SortOrder -1) as MaxSortOrder + from #payperiods pp + inner join #tempSortedPayPeriods s on s.PayPeriodID = pp.val + group by s.PayCycleID + ) r on r.PayCycleID = pp.PayCycleID and t.SortOrder between MinSortOrder and MaxSortOrder + + set @sql = ' + select C.DepartmentID, C.AccountID, C.PayPeriodID, /*records for months, which are absent in current year, but exist at least one month*/ + SUM(C.Units) as Units + into #fullscope + FROM ( + SELECT /*recods for months which are present in current year*/ + p.DepartmentID, p.AccountID, p.PayPeriodID, + p.Units + FROM #StatisticSampledPayPeriod p /*table contains only this particular actuals (filtered by Depts, Year) no need for additional filters*/ + where TimeClassID = 1 and isSystemGenerated = 0 + + UNION ALL + + SELECT /*recods for months which are present in current year*/ + p.DepartmentID, p.AccountID, p.PayPeriodID, + p.Units + FROM fw.FactStatisticSampledPayPeriod p + inner join #PayPeriodsPriorYear pppy on p.PayPeriodID = pppy.val /*filtering only values for "prior year", in fact periods, which affects current year*/ + '+ case when @departmentIDs IS NULL then '' else ' INNER JOIN #departments dpt on dpt.val = p.DepartmentID' end+' + where p.TimeClassID = 1 and p.isSystemGenerated = 0 + + UNION ALL + + SELECT /*combination of all for key columns months for current year*/ + p.DepartmentID, p.AccountID, dpp.val as PayPeriodID, + 0 AS Units + FROM #StatisticSampledPayPeriod p + inner join fw.DimPayPeriod pp on pp.PayPeriodID = p.PayPeriodID + FULL join #PayPeriodsAllScope dpp on dpp.PayCycleID = pp.PayCycleID + where p.TimeClassID = 1 and p.isSystemGenerated = 0 + + UNION ALL + + SELECT /*combination of all for key columns months for current year*/ + p.DepartmentID, p.AccountID, dpp.PayPeriodID, + 0 AS Units + FROM fw.FactStatisticSampledPayPeriod p + INNER JOIN #PayPeriodsPriorYear pppy on p.PayPeriodID = pppy.val /*filtering only values for "prior year", in fact periods, which affects current year*/ + INNER JOIN fw.DimPayPeriod dpp ON dpp.PayCycleID = pppy.PayCycleID + '+ case when @departmentIDs IS NULL then '' else ' INNER JOIN #departments dpt on dpt.val = p.DepartmentID' end + +' where p.TimeClassID = 1 and p.isSystemGenerated = 0 + ) C + inner join #PayPeriodsAllScope P on p.val = C.PayPeriodID + GROUP BY C.DepartmentID, C.AccountID, C.PayPeriodID + + insert into #temp (DepartmentID, AccountID, PayPeriodID, Units) + select DepartmentID, AccountID, PayPeriodID, isnull(Units,0.0) + FROM + ( + select f.DepartmentID, f.AccountID, f.PayPeriodID, + Units = ISNULL((Sum(f.Units) over(PARTITION BY f.DepartmentID, f.AccountID, t.PayCycleID ORDER BY t.SortOrder ROWS BETWEEN '+cast(@numberOfPayPeriods as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/'+cast(@numberOfPayPeriods as nvarchar(2))+', 0) + FROM #fullscope f + inner join #tempSortedPayPeriods t on t.PayPeriodID = f.PayPeriodID + ) FinalDataset + INNER JOIN #PayPeriods PP on pp.Val = FinalDataset.PayPeriodID + WHERE Units is not null' + END + exec(@sql) + IF OBJECT_ID('tempdb..#fullscope') IS NOT NULL DROP TABLE #fullscope + + end else begin --Budget + insert into #temp (DepartmentID, AccountID, PayPeriodID, Units) + select DepartmentID, AccountID, PayPeriodID, Units + from #StatisticSampledPayPeriod + where TimeClassID = 2 and (@departmentIDs is null or DepartmentID in (select val from #departments)) and (@fiscalYearID = 0 or PayPeriodID in(select val from #payperiods)) + end + + insert into #StatisticSampledPayPeriod (DepartmentID, AccountID,PayPeriodID, TimeClassID, Units) + select source.DepartmentID, source.AccountID, source.PayPeriodID, 20, source.Units from #temp source + where (@fiscalYearID = 0 or PayPeriodID in(select val from #payperiods)) and Units !=0 + + + drop table #temp + drop table #departments + drop table #payperiods + drop table #PayPeriodsPriorYear + IF OBJECT_ID('tempdb..#PayPeriodsAllScope') IS NOT NULL DROP TABLE #PayPeriodsAllScope + IF OBJECT_ID('tempdb..#tempSortedPayPeriods') IS NOT NULL DROP TABLE #tempSortedPayPeriods +GO + + +--------------------------------------------- + +-- fw.procFactStatisticSecondarySampledBaselineTargetUpdate +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-03-07 gforeman B-14693 Added year filter +** 2 2017-03-28 ipetriv D-05641 Logic for Prior and Actual was changed to simply copy actuals from previous year +** 3 2017-04-05 ipetriv D-05789 Changed algorithm for rolling average calculation +** 4 2017-05-29 ipetriv B-15994 Refactored sampling process and implemented using of staging tables +** 5 2017-06-15 IP B-15086 Modify SP to use unique temp table +** 6 2017-07-20 IP D-06150 Fixed updating values for Target Type = 2 +** 7 2018-05-16 IP D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values +** 8 2018-05-16 KF D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values +** 9 2018-06-01 IP D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values (one year part) +** 10 2018-06-05 IP TK-58643 added filetr for current year only and non-zero records in output +*************************************************************/ +CREATE proc [fw].[procFactStatisticSecondarySampledBaselineTargetUpdate] + @targetType int = null, + @numberOfMonths int = null, + @fiscalYearID int = 0 + +as + if (@targetType is null) set @targetType = (select Value from mr.SystemSetting where Name = 'Target Basis') + if (@numberOfMonths is null) set @numberOfMonths = (select Value from mr.SystemSetting where Name = 'Number Of Rolling Average Months') + declare @sql varchar(max) + declare @maxCalculatingFiscalYear int = (select max(FiscalYearID) from #StatisticSecondarySampledMonthlyStaging) + create table #temp + ( + DepartmentID int, + AccountID int, + FiscalYearID smallint, + FiscalMonthID tinyint, + Amount decimal (19, 4) + ) + + if (@targetType = 1) begin --Prior Year Actual + insert into #temp + select d.DepartmentID, d.AccountID, d.FiscalYearID+1, d.FiscalMonthID, d.Amount + from fw.FactStatisticSecondarySampledMonthly d where d.TimeClassID = 1 and (@fiscalYearID = 0 or d.FiscalYearID = @fiscalYearID-1) + end else if (@targetType = 10) begin --Rolling Average + IF @fiscalYearID = 0 + set @sql = ' + insert into #temp + select DepartmentID, AccountID, FiscalYearID, FiscalMonthID,isnull(Amount,0.0) FROM ( + select FullScope.DepartmentID, FullScope.AccountID, FullScope.FiscalYearID, m.FiscalMonthID, + Amount = ISNULL((Sum(Amount) over(PARTITION BY DepartmentID,AccountID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfMonths AS NVARCHAR(2)) +', 0) + FROM ( + select DepartmentID, /*records for months, which are absent in current year, but exist at least one month*/ + AccountID, + FiscalYearID, + SortOrder, + SUM(Amount) as Amount + FROM ( + SELECT /*recods for months which are present in current year*/ + DepartmentID, + AccountID, + FiscalYearID, + m.SortOrder, + Amount + FROM #StatisticSecondarySampledMonthlyStaging p + JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID + where m.FiscalMonthID <> 0 and TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0 + UNION ALL + SELECT /*combination of all for key columns months for current year*/ + p.DepartmentID, + p.AccountID, + fy.FiscalYearID, + m.SortOrder, + 0 AS Amount + FROM #StatisticSecondarySampledMonthlyStaging p + CROSS JOIN fw.DimFiscalMonth m + CROSS JOIN (select FiscalYearID from fw.DimFiscalYear dm) fy + where m.FiscalMonthID <> 0 and p.TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0 + ) AllCombinations + GROUP BY DepartmentID,AccountID,FiscalYearID,SortOrder + ) FullScope + JOIN fw.DimFiscalMonth m ON FullScope.SortOrder = m.SortOrder + ) FinalDataset + WHERE Amount is not null + AND FiscalYearID <='+cast(@maxCalculatingFiscalYear as nvarchar(4)) + ELSE + SET @sql = ' + insert into #temp + select DepartmentID, AccountID, FiscalYearID, FiscalMonthID,isnull(Amount,0.0) FROM ( + select FullScope.DepartmentID, FullScope.AccountID, FullScope.FiscalYearID, m.FiscalMonthID, + Amount = ISNULL((Sum(Amount) over(PARTITION BY DepartmentID,AccountID ORDER BY FiscalYearID*12+m.SortOrder ROWS BETWEEN '+cast(@numberOfMonths as nvarchar(2))+' PRECEDING AND 1 PRECEDING))/' + cast(@numberOfMonths AS NVARCHAR(2)) +', 0) + FROM ( + select DepartmentID, /*records for months, which are absent in current year, but exist at least one month*/ + AccountID, + FiscalYearID, + SortOrder, + SUM(Amount) as Amount + FROM ( + SELECT /*recods for months which are present in current year*/ + DepartmentID, + AccountID, + FiscalYearID, + m.SortOrder, + Amount + FROM #StatisticSecondarySampledMonthlyStaging p + JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID + where m.FiscalMonthID <> 0 and TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0 + UNION ALL + SELECT /*combination of all for key columns months for current year*/ + DepartmentID, + AccountID, + FiscalYearID, + m.SortOrder, + Amount + FROM fw.FactStatisticSecondarySampledMonthly p + JOIN fw.DimFiscalMonth m ON p.FiscalMonthID = m.FiscalMonthID + where m.FiscalMonthID <> 0 and TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0 + and FiscalYearID = '+cast(@fiscalYearID-1 as nvarchar(4)) +' + UNION ALL + SELECT /*combination of all for key columns months for current year*/ + DepartmentID, + AccountID, + FiscalYearID, + m.SortOrder, + 0 AS Amount + FROM #StatisticSecondarySampledMonthlyStaging p + CROSS APPLY fw.DimFiscalMonth m + where m.FiscalMonthID <> 0 and TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0 + and FiscalYearID = '+cast(@fiscalYearID as nvarchar(4)) +' + UNION ALL + SELECT /*combination of all for key columns months for current year*/ + p.DepartmentID, + p.AccountID, + fy.FiscalYearID, + m.SortOrder, + 0 AS Amount + FROM fw.FactStatisticSecondarySampledMonthly p + CROSS JOIN fw.DimFiscalMonth m + CROSS JOIN (select FiscalYearID + from fw.DimFiscalYear dm + where dm.FiscalYearID in ('+cast(@fiscalYearID-1 as nvarchar(4))+','+cast(@fiscalYearID as nvarchar(4))+')'+' + ) fy + where m.FiscalMonthID <> 0 and p.TimeClassID = 1 and isnull(p.IsSystemGenerated,0) = 0 and p.FiscalYearID = '+cast(@fiscalYearID-1 as nvarchar(4))+' + ) AllCombinations + GROUP BY DepartmentID,AccountID,FiscalYearID,SortOrder + ) FullScope + JOIN fw.DimFiscalMonth m ON FullScope.SortOrder = m.SortOrder + ) FinalDataset + WHERE Amount is not null + AND FiscalYearID ='+cast(@fiscalYearID as nvarchar(4)) + exec (@sql) + end else begin --Budget + insert into #temp + select DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Amount + from #StatisticSecondarySampledMonthlyStaging + where TimeClassID = 2 and (@fiscalYearID = 0 or FiscalYearID = @fiscalYearID) + end + + INSERT INTO #StatisticSecondarySampledMonthlyStaging (DepartmentID,AccountID,FiscalYearID,FiscalMonthID,Amount,TimeClassID) + SELECT DepartmentID,AccountID,FiscalYearID,FiscalMonthID,Amount,20 FROM #temp + WHERE (@fiscalYearID = 0 or FiscalYearID = @fiscalYearID) and Amount !=0 + + exec [dbo].[procRollingDeleteOnTable] 'fw', 'FactStatisticSecondarySampledMonthly', 'RowID', 'fw.FactStatisticSecondarySampledMonthly', 'TimeClassID = 20 and IsDeleted = 1', 10000, 0.5, 0 + + drop table #temp +GO + + +--------------------------------------------- + +-- fw.procFillFactPatientBillingLineItemGroupedCache +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-10-13 KF JAZZ-44078 Charge Based Statistics Modals Performance Improvement +** 2 2022-02-01 KF JAZZ-48413 Charge Based Statistics Modals Performance Improvement- Bug Fixing +*************************************************************/ +CREATE PROC [fw].[procFillFactPatientBillingLineItemGroupedCache] +AS + -- Truncate table, drop indexes + TRUNCATE TABLE fw.FactPatientBillingLineItemGroupedCache + + EXEC dbo.procSysDropIndex @schema = 'fw', @table = 'FactPatientBillingLineItemGroupedCache', @indexName = 'CORE_PostDateID_DepartmentID_ChargeCodeID_PatientTypeRollupID_inc' + EXEC dbo.procSysDropIndex @schema = 'fw', @table = 'FactPatientBillingLineItemGroupedCache', @indexName = 'CORE_ServiceDateID_DepartmentID_ChargeCodeID_PatientTypeRollupID_inc' + + -- Split by batches + DECLARE @batchSize INT = 200000000 + + IF OBJECT_ID('tempdb..#inputDepartments') IS NOT NULL DROP TABLE #inputDepartments + CREATE TABLE #inputDepartments (DepartmentID INT, RecordsCount INT, BatchID INT) + + DECLARE + @fromClause nvarchar(max) = ' + dss.FactPatientBillingLineItemDetail fd + INNER JOIN fw.DimDepartment d ON d.DepartmentID = fd.DepartmentID', + @whereClause nvarchar(max) = '', + @declareParameters nvarchar(max) = '' + + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'fd', + @fromClause = @fromClause, + @whereClause = @whereClause, + @declareParameters = @declareParameters, + @isDebug = 0 + + DECLARE @BatchID INT, @MaxBatchID INT + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + -- Loop thru batches and insert data + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + INSERT INTO fw.FactPatientBillingLineItemGroupedCache (DepartmentID, ChargeCodeID, PatientTypeRollupID, ServiceDateID, PostDateID, FiscalYearID, UnitsOfService) + SELECT fd.DepartmentID, fd.ChargeCodeId, pt.PatientTypeRollupId, fd.ServiceDateId, fd.PostDateID, fd.FiscalYearID, COALESCE(SUM(fd.UnitsOfService), 0.0E0) AS UnitsOfService + FROM dss.FactPatientBillingLineItemDetail fd + INNER JOIN clientdss.FactPatientEncounterSummary fs ON fs.EncounterID = fd.EncounterID + INNER JOIN fw.DimPatientType pt ON pt.PatientTypeID = fs.PatientTypeID + INNER JOIN fw.DimChargeCode c ON c.ChargeCodeID = fd.ChargeCodeID + INNER JOIN fw.DimPatientTypeRollup ptr ON ptr.PatientTypeRollupId = pt.PatientTypeRollupId + INNER JOIN #inputDepartments ID ON ID.DepartmentID = fd.DepartmentID + WHERE ID.BatchID = @BatchID + GROUP BY fd.DepartmentID, fd.ChargeCodeId, pt.PatientTypeRollupId, fd.ServiceDateId, fd.PostDateID, fd.FiscalYearID + + SET @BatchID = @BatchID + 1 + END + + -- Recreate indexes + CREATE INDEX CORE_PostDateID_DepartmentID_ChargeCodeID_PatientTypeRollupID_inc + ON fw.FactPatientBillingLineItemGroupedCache (PostDateID, DepartmentID, ChargeCodeID, PatientTypeRollupID) + INCLUDE(UnitsOfService) + + CREATE INDEX CORE_ServiceDateID_DepartmentID_ChargeCodeID_PatientTypeRollupID_inc + ON fw.FactPatientBillingLineItemGroupedCache (ServiceDateID, DepartmentID, ChargeCodeID, PatientTypeRollupID) + INCLUDE(UnitsOfService) + + IF OBJECT_ID('tempdb..#inputDepartments') IS NOT NULL DROP TABLE #inputDepartments + IF OBJECT_ID('tempdb..#transactions') IS NOT NULL DROP TABLE #transactions +GO + + +--------------------------------------------- + +-- fw.procFlexProviderStatisticsMonthly +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-06-27 KZ B-19363 MR - Provider flexing - flexing +** 2 2018-06-28 KF B-19363 MR - Provider flexing - flexing +** 3 2018-07-10 KZ B-20342 MR - Update provider sampling to be in the appropriate format +*************************************************************/ +CREATE PROCEDURE [fw].[procFlexProviderStatisticsMonthly] + @fiscalYearID INT = 0, + @departmentIDs nvarchar(max) = null +AS + +declare @minYear int = @fiscalYearID - 1 +declare @maxYear int = @fiscalYearID +if (@minYear = 0 or @maxYear = 0) begin + select @minYear = min(FiscalYearID) from [fw].[FactProviderSampledMonthly_Pivoted] + select @maxYear = max(FiscalYearID) from [fw].[FactProviderSampledMonthly_Pivoted] +end + +declare @currentYear int +select @currentYear = Setting from [dbo].[DBSetting] where Name='Current_GL_YearID' + +declare @currentMonth int +select @currentMonth = Setting from [dbo].[DBSetting] where Name='Current_GL_MonthID' + +declare @month int +select @month = SortOrder + @currentYear * 12 from [fw].[DimFiscalMonth] where FiscalMonthID=@currentMonth + +DELETE FROM [fw].[FactProviderSampledMonthly_Pivoted] WHERE TimeClassID = 4 AND (FiscalYearID between @minYear AND @maxYear) +AND (@departmentIDs is null or DepartmentID in (select val from ConvertCSValuesToTable(@departmentIDs, ','))) + +INSERT INTO [fw].[FactProviderSampledMonthly_Pivoted] ([DepartmentID], [ProviderID], [OBForecastDetailID], [FiscalYearID], [FiscalMonthID], [TimeClassID], [Volume]) +SELECT F.[DepartmentID], F.[ProviderID], F.[OBForecastDetailID], F.[FiscalYearID], F.[FiscalMonthID], 4 as [TimeClassID], + iif(F.FiscalYearID * 12 + max(M.SortOrder) <= @month, + sum( + case when F.TimeClassID = 1 then F.[Volume] * cast(FD.IsVariable as decimal(18, 6)) * cast(D.IsVariable as decimal(18, 6)) * cast(P.IsVariable as decimal(18, 6)) + when F.TimeClassID = 20 then F.[Volume] * (1.0 - (cast(FD.IsVariable as decimal(18, 6)) * cast(D.IsVariable as decimal(18, 6)) * cast(P.IsVariable as decimal(18, 6)))) + else 0 end) + , coalesce(sum(case when F.TimeClassID = 20 then F.[Volume] end), 0)) as [Amount] +FROM [fw].[FactProviderSampledMonthly_Pivoted] F +INNER JOIN [fw].[DimDepartment] D on D.DepartmentID = F.DepartmentID +INNER JOIN [ob].[DimOBForecastDetail] FD on FD.OBForecastDetailID = F.OBForecastDetailID +INNER JOIN [fw].[DimProvider] P on P.ProviderID = F.ProviderID +INNER JOIN [fw].[DimFiscalMonth] M on M.FiscalMonthID = F.FiscalMonthID +WHERE F.IsDeleted = 0 and F.TimeClassID in(1, 20) AND (FiscalYearID between @minYear AND @maxYear) +AND (@departmentIDs is null or F.DepartmentID in (select val from ConvertCSValuesToTable(@departmentIDs, ','))) +GROUP BY F.[DepartmentID], F.[ProviderID], F.[OBForecastDetailID], F.[FiscalYearID], F.[FiscalMonthID] +GO + + +--------------------------------------------- + +-- fw.procFlexStatisticsDaily +CREATE PROCEDURE [fw].[procFlexStatisticsDaily] +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2019-03-19 KF D-08059 PR | Daily and pay period screens are calculating targets differently +** 2 2022-07-05 HV JAZZ-39736 PR Metrics Definition - Statistics Daily Flexing +** 3 2022-08-02 HV JAZZ-41284 Daily flexing - Payroll Hours and Dollars +** 4 2022-08-30 KF JAZZ-42568 Flex UOS not accounting for account variability for daily PR +** 5 2024-02-23 HV JAZZ-67657 [RowId] Convert fw.FactStatisticSampledDaily.Rowid to bigint +*************************************************************/ + @FiscalYearID INT = 0, + @DepartmentIDs NVARCHAR(MAX) = null, + @isOnlyOnePayPeriod BIT = 0 +AS + +DECLARE @currentDateOverride nvarchar(max) = (SELECT Value FROM [pi].[SystemSetting] WHERE Name = 'Current Date Override') +DECLARE @currentDate date = CASE + WHEN @currentDateOverride = '' THEN CAST(GETDATE() AS DATE) + ELSE CAST (@currentDateOverride AS date) + END +DECLARE @yesterdayDate date = DATEADD(DAY, - 1, @currentDate) +DECLARE @yesterdayDateID int = (SELECT DateID FROM fw.DimDate WHERE CalendarDateTime = @yesterdayDate) + +IF OBJECT_ID('tempdb..#DailyCalcPeriodsScope') IS NOT NULL DROP TABLE #DailyCalcPeriodsScope +CREATE TABLE #DailyCalcPeriodsScope (PayPeriodID int primary key,PayCycleID int,PeriodStartCalendarDate date,PeriodEndCalendarDate date) + +INSERT INTO #DailyCalcPeriodsScope (PayPeriodID,PayCycleID,PeriodStartCalendarDate,PeriodEndCalendarDate) +SELECT PayPeriodID,PayCycleID,PeriodStartCalendarDate,PeriodEndCalendarDate +FROM fw.DimPayPeriod +WHERE + (@isOnlyOnePayPeriod = 1 and @yesterdayDate BETWEEN PeriodStartCalendarDate and PeriodEndCalendarDate) + or + (@isOnlyOnePayPeriod = 0 and (FiscalYearIDSecond = @fiscalYearID or @fiscalYearID = 0)) + +IF OBJECT_ID('tempdb..#DepartmentIDs') IS NOT NULL DROP TABLE #DepartmentIDs +CREATE TABLE #DepartmentIDs (val int primary key) +INSERT INTO #DepartmentIDs select val from ConvertCSValuesToTable(@departmentIDs, ',') + +DECLARE @FromClause NVARCHAR(MAX) = 'fw.FactStatisticSampledDaily F INNER JOIN #DailyCalcPeriodsScope dcp on dcp.PayPeriodID = F.PayPeriodID' +DECLARE @WhereClause NVARCHAR(MAX) = 'F.TimeClassID = 4' + +IF(@DepartmentIDs IS NOT NULL) +BEGIN + SET @FromClause = @fromClause + ' INNER JOIN #DepartmentIDs TD ON TD.val = F.DepartmentID' +END + +exec [dbo].[procRollingDeleteOnTable] + @tableSchema = 'fw', + @tableName = 'FactStatisticSampledDaily', + @identityColumn = 'RowID', + @fromClause = @FromClause, + @whereClause = @WhereClause, + @deleteRecordCount = 10000000, + @truncateThreshold = 0.5, + @isPrintingStatement = 0 + +DECLARE @nextRowID BIGINT +SELECT @nextRowID = ISNULL((SELECT MAX(RowID) FROM fw.FactStatisticSampledDaily), 1) +DBCC CHECKIDENT('fw.FactStatisticSampledDaily','RESEED', @nextRowID); + +DECLARE @BatchSize INT = 30000000 + +IF OBJECT_ID('tempdb..#inputPayPeriods') IS NOT NULL DROP TABLE #inputPayPeriods + +SELECT F.PayPeriodID, COUNT(1) AS RecordsCount, 0 AS BatchID INTO #inputPayPeriods +FROM fw.FactStatisticSampledDaily F +INNER JOIN #DailyCalcPeriodsScope dcp on F.PayPeriodID = dcp.PayPeriodID +WHERE F.IsDeleted = 0 AND F.TimeClassID in(1, 20) +GROUP BY F.PayPeriodID + +-- Split data into batches +WHILE EXISTS (SELECT TOP 1 1 FROM #inputPayPeriods WHERE BatchID = 0) +BEGIN + ;WITH PayPeriodInfo AS + ( + SELECT DM.PayPeriodID, ROW_NUMBER() OVER (ORDER BY DM.PayPeriodID) AS RowNumber, SUM(RecordsCount) OVER (ORDER BY DM.PayPeriodID) AS Total, M.MaxBatchID+1 AS BatchID + FROM #inputPayPeriods IPP + INNER JOIN fw.DimPayPeriod DM ON DM.PayPeriodID = IPP.PayPeriodID + CROSS JOIN (SELECT MAX(BatchID) AS MaxBatchID FROM #inputPayPeriods) M + WHERE IPP.BatchID = 0 + ) + UPDATE IPP + SET IPP.BatchID = MI.BatchID + FROM #inputPayPeriods IPP + INNER JOIN PayPeriodInfo MI ON MI.PayPeriodID = IPP.PayPeriodID + WHERE MI.Total <= @BatchSize OR MI.RowNumber = 1 +END + +DECLARE @BatchID INT, @MaxBatchID INT +SELECT @MaxBatchID = MAX(BatchID) FROM #inputPayPeriods + +-- Loop thru batches and insert data +SET @BatchID = 1 +WHILE @BatchID <= @MaxBatchID +BEGIN + + INSERT INTO fw.FactStatisticSampledDaily (DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units) + SELECT S.DepartmentID, S.AccountID, S.PayPeriodID, S.DateID, S.TimeClassID, S.Units + FROM + ( + SELECT F.DepartmentID, F.AccountID, F.PayPeriodID, F.DateID, 4 AS TimeClassID, + CASE + WHEN F.DateID <= @yesterdayDateID + THEN + SUM(CASE + WHEN F.TimeClassID = 1 THEN F.Units * A.Variability * CAST(D.IsVariable as decimal(18, 6)) + WHEN F.TimeClassID = 20 THEN F.Units * (1.0 - (A.Variability * CAST(D.IsVariable as decimal(18, 6)))) + ELSE 0 + END) + ELSE + COALESCE(SUM(CASE WHEN F.TimeClassID = 20 THEN F.Units END), 0) + END + AS Units + FROM fw.FactStatisticSampledDaily F + INNER JOIN fw.DimDepartment D on D.DepartmentID = F.DepartmentID + INNER JOIN fw.DimAccount A on A.AccountID = F.AccountID + INNER JOIN fw.DimDate DD on DD.DateID = F.DateID + INNER JOIN #inputPayPeriods IPP ON IPP.PayPeriodID = F.PayPeriodID + LEFT JOIN #DepartmentIDs TD ON TD.val = D.DepartmentID + WHERE F.IsDeleted = 0 + AND F.TimeClassID in(1, 20) + AND (@DepartmentIDs IS NULL OR TD.val IS NOT NULL) + AND IPP.BatchID = @BatchID + GROUP BY F.DepartmentID, F.AccountID, F.DateID, F.PayPeriodID + ) S + +SET @BatchID = @BatchID + 1 +END + +IF OBJECT_ID('tempdb..#DepartmentIDs') IS NOT NULL DROP TABLE #DepartmentIDs +GO + + +--------------------------------------------- + +-- fw.procGLSampledAdjustedTargetMonthlyInsert +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-10-02 IP B-17596 Created +** 2 2018-11-19 OV D-06627 fix: GL Dollars Adjusted Target records are not added when there is only Actual data +** 3 2020-02-05 IH D-08896 Add handling of Units +** 4 2022-08-23 BC JAZZ-11498 Change Table Variable to Temporary Tables +*************************************************************/ +CREATE PROCEDURE [fw].[procGLSampledAdjustedTargetMonthlyInsert] (@FiscalYearID INT = 0) +AS +BEGIN + /* +Proposal + +If the client is not using flexing, this will be the target plus the efficiency factor +This should work regardless of the target basis (i.e. rolling avg or budget) +The factor will be applied after the inversion +If the factor type is percentage, the adjusted target will be the target*(1+factor) +i.e. if my target is 100 and my factor is 5%, the adjusted target will be 100*(1+0.05)=105 +i.e. if my target is 100 and my factor is -5%, the adjusted target will be 100*(1+-0.05)=95 +If the factor type is value, the adjusted value will be target + factor +i.e. if my target is 1000 and my factor is 200, the adjusted target will be will be 1000+200=1200 +i.e. if my target is 1000 and my factor is -200, the adjusted target will be 1000-200=800 +If there is more than one factor impacting a department and account or job code/pay code group combination, then the factors should layer on top of each other based on history order +If an efficiency factor does not exist for a particular account/job code, then the value in the new time class will be either flex or baseline target if flex is not used +This will happen after Flex is calculated +Include integration tests + +*/ DECLARE @IsFlexingEnabled INT = ( + SELECT VALUE + FROM [mr].[SystemSetting] + WHERE NAME = 'Is Target Flexed' + ) + + + IF OBJECT_ID('tempdb..#EfficiencyFactorScope') IS NOT NULL DROP TABLE #EfficiencyFactorScope + CREATE TABLE #EfficiencyFactorScope ( + EfficiencyFactorGUID [uniqueidentifier] NOT NULL + ,[DepartmentID] [int] NOT NULL + ,[AccountID] [int] NOT NULL + ,[FiscalYearID] [smallint] NOT NULL + ,[FiscalMonthID] [tinyint] NOT NULL + ,Value NUMERIC(25, 6) NOT NULL + ,Type TINYINT + ,FactorType CHAR(1) + ,DateCreated DATETIME + ,UNIQUE CLUSTERED ( + FiscalYearID + ,FiscalMonthID + ,DepartmentID + ,AccountID + ,EfficiencyFactorGUID + ) + ); + + IF EXISTS (SELECT TOP 1 * FROM [mr].[EfficiencyFactor]) BEGIN + WITH EfficiencyFactorScope + AS ( + SELECT * + ,rn = ROW_NUMBER() OVER ( + PARTITION BY FiscalYearID + ,FiscalMonthID + ,DepartmentID + ,AccountID + ,EfficiencyFactorGUID ORDER BY FiscalYearID + ,FiscalMonthID + ,DepartmentID + ,AccountID + ,EfficiencyFactorGUID + ) + FROM ( + SELECT DISTINCT ef.EfficiencyFactorGUID + ,ef.FiscalYearID + ,efgd.FiscalMonthID + ,efd.DepartmentID + ,isnull(efgd.AccountID, da.AccountID) AS AccountID + ,CASE + WHEN isnull(efgd.AccountID, - 999) = da.AccountID + THEN 0 + ELSE efgd.Value + END AS Value + ,ef.Type + ,ef.FactorType + ,ef.DateCreated + FROM mr.EfficiencyFactor ef + INNER JOIN mr.EfficiencyFactorDepartment efd ON ef.EfficiencyFactorGUID = efd.EfficiencyFactorGUID + INNER JOIN mr.EfficiencyFactorGLDetails efgd ON efgd.EfficiencyFactorGUID = ef.EfficiencyFactorGUID + LEFT JOIN fw.DimAccount da ON efgd.OBFinancialReportingID = da.OBDollarsFinancialReportingID + AND efgd.AccountID IS NULL + LEFT JOIN mr.EfficiencyFactorGLDetails efgd_exist ON efgd.EfficiencyFactorGUID = efgd_exist.EfficiencyFactorGUID + AND efgd_exist.AccountID = da.AccountID + AND efgd_exist.FiscalMonthID = efgd.FiscalMonthID + WHERE ( + @FiscalYearID = ef.FiscalYearID + OR @FiscalYearID = 0 + ) + AND ( + efgd_exist.AccountID IS NULL + OR da.AccountID IS NULL + ) + AND ef.Type = 0 + AND isnull(efgd.AccountID, da.AccountID) IS NOT NULL + ) X + ) + INSERT INTO #EfficiencyFactorScope ( + EfficiencyFactorGUID + ,[DepartmentID] + ,[AccountID] + ,[FiscalYearID] + ,[FiscalMonthID] + ,Value + ,Type + ,FactorType + ,DateCreated + ) + SELECT EfficiencyFactorGUID + ,[DepartmentID] + ,[AccountID] + ,[FiscalYearID] + ,[FiscalMonthID] + ,Value + ,Type + ,FactorType + ,DateCreated + FROM EfficiencyFactorScope + WHERE RN = 1 + + DELETE + FROM fw.FactGLSampled + WHERE ( + @FiscalYearID = FiscalYearID + OR @FiscalYearID = 0 + ) + AND TimeClassID = 22 + + INSERT INTO fw.FactGLSampled ( + DepartmentID + ,AccountID + ,FiscalYearID + ,FiscalMonthID + ,TimeClassID + ,IsDeleted + ,Dollars + ,Units + ) + SELECT DepartmentID + ,AccountID + ,FiscalYearID + ,FiscalMonthID + ,22 AS TimeClassID + ,0 AS IsDeleted + ,SUM(Dollars) + ,SUM(Units) + FROM ( + SELECT isnull(fact.DepartmentID, ToApply.DepartmentID) AS DepartmentID + ,isnull(fact.AccountID, toApply.AccountID) AS AccountID + ,isnull(fact.FiscalYearID, toApply.FiscalYearID) AS FiscalYearID + ,isnull(fact.FiscalMonthID, toApply.FiscalMonthID) AS FiscalMonthID + ,Dollars = CASE WHEN FactorType = 'P' THEN isnull(Dollars, 0.0) * isnull(Value, 0.0) / 100.00 + ELSE isnull(Value, 0.0) + END + ,Units = 0.0 + FROM #EfficiencyFactorScope ToApply + INNER JOIN ( + SELECT DISTINCT DepartmentID + ,AccountID + FROM fw.FactGLSampled + ) GenCand ON GenCand.DepartmentID = ToApply.DepartmentID + AND GenCand.AccountID = ToApply.AccountID + FULL JOIN (select DepartmentID + , AccountID + , FiscalYearID + , FiscalMonthID + , SUM(CASE WHEN (@IsFlexingEnabled = 1 and isnull(fact.TimeClassID, 0) = 4) OR (isnull(fact.TimeClassID, 0) = 20 AND @IsFlexingEnabled = 0) + THEN isnull(fact.Dollars,0.0) + ELSE 0.0 + END) as Dollars + FROM fw.FactGLSampled fact + WHERE fact.TimeClassID in (1, 4, 20) + and fact.FiscalYearID = @FiscalYearID OR @FiscalYearID = 0 + GROUP BY DepartmentID + ,AccountID + ,FiscalYearID + ,FiscalMonthID ) fact ON fact.DepartmentID = ToApply.DepartmentID + AND fact.AccountID = ToApply.AccountID + AND fact.FiscalYearID = ToApply.FiscalYearID + AND fact.FiscalMonthID = ToApply.FiscalMonthID + where value is not null + + UNION ALL + + SELECT DepartmentID + ,AccountID + ,FiscalYearID + ,FiscalMonthID + ,CASE WHEN (@IsFlexingEnabled = 1 and isnull(fact.TimeClassID, 0) = 4) OR (isnull(fact.TimeClassID, 0) = 20 AND @IsFlexingEnabled = 0) + THEN isnull(fact.Dollars,0.0) + ELSE 0.0 + END as Dollars + ,CASE WHEN (@IsFlexingEnabled = 1 and isnull(fact.TimeClassID, 0) = 4) OR (isnull(fact.TimeClassID, 0) = 20 AND @IsFlexingEnabled = 0) + THEN fact.Units + ELSE 0.0 + END as Units + FROM fw.FactGLSampled fact + WHERE fact.FiscalYearID = @FiscalYearID OR @FiscalYearID = 0 + ) X WHERE x.Dollars != 0 OR x.Units != 0 + GROUP BY DepartmentID + ,AccountID + ,FiscalYearID + ,FiscalMonthID + + + EXEC [fw].[procFactMonthlyYTDPriorYearUpdate] @factTableName = 'fw.FactGLSampled' + ,@keyNameCSV = 'AccountID' + ,@measureNameCSV = 'Dollars,Units' + ,@fiscalYearID = @FiscalYearID + ,@timeClassID = 22 + ,@isDebugOnly = 0 + END +END +IF OBJECT_ID('tempdb..#EfficiencyFactorScope') IS NOT NULL DROP TABLE #EfficiencyFactorScope +GO + + +--------------------------------------------- + +-- fw.procGLSampledFlexInsert +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 5/10/16 NL B-11692 Including FiscalYearID in delete +** 2 10/38/17 GF D-05545 Move duplicate record handling from YTD into sampling + general cleanup +*************************************************************/ +CREATE PROC [fw].[procGLSampledFlexInsert] + @fiscalyearid smallint +with recompile +as + --delete existing data + WHILE EXISTS(SELECT NULL FROM fw.FactGLSampled (nolock) WHERE FiscalYearID = @fiscalYearID and TimeClassID = 4) BEGIN + DELETE TOP (10000) fw.FactGLSampled WHERE FiscalYearID = @fiscalYearID and TimeClassID = 4 + END + + --push new data to fact table + INSERT INTO [fw].[FactGLSampled]([DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], [TimeClassID], [Units], [Dollars]) + SELECT + GL.DepartmentID, + GL.AccountID, + GL.FiscalYearID, + GL.FiscalMonthID, + 4, + SUM(0) as Units, + SUM(CASE + WHEN acc.Inversion = -1 THEN gl.value * -1 + ELSE gl.value + END) AS Dollars + FROM + [int].[FactGL] gl + INNER JOIN [fw].[DimAccount] acc on acc.AccountCode = gl.AccountCode + WHERE + gl.TimeClassID = 2 + AND gl.FiscalYearID = @fiscalyearid + AND (gl.value != 0) + GROUP BY + gl.DepartmentID, + gl.AccountID, + gl.FiscalYearID, + gl.FiscalMonthID, + gl.TimeClassID + + --run calculations + exec fw.procFactMonthlyMergeDuplicates 'fw.FactGLSampled', 'AccountID', 'Dollars,Units', @fiscalYearID, 4, 0 + exec fw.procFactMonthlyYTDPriorYearUpdate 'fw.FactGLSampled', 'AccountID', 'Dollars,Units', @fiscalYearID, 4, 0 +GO + + +--------------------------------------------- + +-- fw.procGLSampledInsert +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2014-01-13 AKK D-01370 Fixing order of operations for WHEN condition +** 2 2014-09-30 JG Kris updated proc to optimize performance +** 3 2015-07-15 NL D-02813 Removing parameter from YTD call +** 4 2016-12-27 AK D-05183 Added IsSystemGenerated reset +** 5 2017-02-20 GF D-05545 Move duplicate record handling from YTD into sampling + general cleanup +** 6 2017-02-21 GF D-05545 Add debug flag to disable output for standard run +** 7 2020-02-06 KF D-08896 FP/ MR / Flexing / Drivers - MR GL Hours Flexing doesn't work +*************************************************************/ +CREATE proc [fw].[procGLSampledInsert] + @fiscalyearid smallint, + @timeclassid tinyint, + @isDebug bit = 0 +with recompile +as + --this proc is obsolete, call All instead + exec fw.procGLSampledInsertAll @fiscalyearid, @isDebug +GO + + +--------------------------------------------- + +-- fw.procGLSampledInsertAll +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-07-05 IP D-06023 Changing columns size to support values over 1 trillion +** 2 2017-07-19 IP TK-45395 Fixed conditions of merge statement (include isSystemGenerated column) +** 3 2018-01-12 IP TK-53108 Fixed conditions of merge statement (include TimeClassID = 12 to target) +** 4 2018-01-12 IP TK-53108 Fixed conditions of merge statement (include TimeClassID = 4 to target and source) +** 5 2018-02-01 IP TK-53658 Re-applied stored procedure +** 6 2018-02-14 GF Apply account inversion fix +** 7 2019-02-05 OV D-07814 Optimize the proc to do truncate/insert for each year where @fiscalYearID = 0 +** 8 2020-02-05 KF D-08896 FP/ MR / Flexing / Drivers - MR GL Hours Flexing doesn't work +** 9 2020-02-18 KF B-26204 MR | GL Hour Flexing +** 10 2021-11-11 HV JAZZ-28155 Remove MR 3.0 Flag and all associated code +** 11 2023-09-14 BS JAZZ-55750 Remove filter to allow other time classes in MR reporting +** 12 2024-06-04 ishah JAZZ-61244 [TrLog][High] Bug - Run Management Reporting Monthly Process (MR Sampling, all years run): Task failed on Inserting GL Sampled. +*************************************************************/ + +CREATE PROC [fw].[procGLSampledInsertAll] + @fiscalYearID smallint = 0, + @isDebug bit = 0 + +as +print 'Starting calculating staging table --- '+convert(varchar(20),GETDATE(),113) + IF OBJECT_ID('tempdb..#FactGLStagingValue') IS NOT NULL DROP TABLE #FactGLStagingValue + IF OBJECT_ID('tempdb..#FactGLStaging') IS NOT NULL DROP TABLE #FactGLStaging + IF OBJECT_ID('tempdb..#StatisticSampledMonthlyStaging') IS NOT NULL DROP TABLE #StatisticSampledMonthlyStaging + IF OBJECT_ID('fw.FactGLStagingWithCalcs') IS NOT NULL DROP TABLE fw.FactGLStagingWithCalcs + IF OBJECT_ID('tempdb..#SummaryOfChanges') IS NOT NULL DROP TABLE #SummaryOfChanges + + exec client.procGLSampledInsertPreprocess + --push new data to fact table + CREATE TABLE #SummaryOfChanges (Change VARCHAR(20), FiscalYearID smallint, TimeClassID tinyint, IsDeleted bit); + + CREATE TABLE #FactGLStagingValue ( + DepartmentID int, + AccountID int, + FiscalYearID int, + FiscalMonthID int, + TimeClassID int, + Amount decimal(21,6), + ApplyDate datetime, + Src varchar(max), + UNIQUE NONCLUSTERED (DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID) + ) + + exec fw.procPrepareGL @fiscalYearID + + CREATE TABLE #FactGLStaging (RowID bigint identity(1,1), DepartmentID int, AccountID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, Units decimal(21,6), Dollars decimal(21,6), FTEs decimal(21,6),isDeleted bit default 0, isSystemGenerated bit default 0) + + DECLARE @batchSize INT + + IF OBJECT_ID('tempdb..#inputDepartments') IS NOT NULL DROP TABLE #inputDepartments + CREATE TABLE #inputDepartments (DepartmentID INT, RecordsCount INT, BatchID INT) + + -- Split by batches + EXEC mr.procGetIntBatchSize + @DefaultBatchSize = 30000000, + @ResultBatchSize = @batchSize OUTPUT + + DECLARE @fromClause nvarchar(max), @whereClause nvarchar(max) + + SET @fromClause = ' + ( + select + GL.DepartmentID, + GL.AccountID, + GL.FiscalYearID, + GL.FiscalMonthID, + GL.TimeClassID + from + #FactGLStagingValue GL + inner join fw.DimAccount A on A.AccountID = GL.AccountID + where + gl.Amount != 0 + group by + GL.DepartmentID, + GL.AccountID, + GL.FiscalYearID, + GL.FiscalMonthID, + GL.TimeClassID + ) X + ' + + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'X', + @fromClause = @fromClause, + @whereClause = '', + @isDebug = 0 + + DECLARE @BatchID INT, @MaxBatchID INT + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + INSERT INTO #FactGLStaging (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Units, Dollars) + select + GL.DepartmentID, + GL.AccountID, + GL.FiscalYearID, + GL.FiscalMonthID, + GL.TimeClassID, + sum(0) as Units, + sum(CASE + WHEN A.Inversion = -1 then GL.Amount * -1 + ELSE GL.Amount + END) AS Dollars + from + #FactGLStagingValue GL + inner join #inputDepartments IP on IP.DepartmentID = GL.DepartmentID + inner join fw.DimAccount A on A.AccountID = GL.AccountID + where + gl.Amount != 0 and IP.BatchID = @BatchID + group by + GL.DepartmentID, + GL.AccountID, + GL.FiscalYearID, + GL.FiscalMonthID, + GL.TimeClassID + + SET @BatchID = @BatchID + 1 + END + + IF OBJECT_ID('tempdb..#FactGLStagingValue') IS NOT NULL DROP TABLE #FactGLStagingValue + + exec fw.procFactMonthlyMergeDuplicates '#FactGLStaging', 'AccountID', 'Dollars,Units', @fiscalYearID, 0, 0 + + -- Statistics Hours to GL Units + IF EXISTS (SELECT * FROM mr.SystemSetting WHERE Name = 'Feature Flag Use GL Units' AND Value = 1) + BEGIN + + CREATE TABLE #StatisticSampledMonthlyStaging (RowID bigint identity(1,1),AccountID int, DepartmentID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, Amount decimal(19,4)) + insert into #StatisticSampledMonthlyStaging (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Amount) + exec fw.PrepareStatistics @FiscalYearID,0 + + SELECT + STAT.DepartmentID, + STAT.AccountID, + STAT.FiscalYearID, + STAT.FiscalMonthID, + STAT.TimeClassID, + SUM(STAT.Amount) AS Units + INTO #FactGLUnits + FROM #StatisticSampledMonthlyStaging STAT + INNER JOIN fw.DimAccount A ON A.AccountID = STAT.AccountID + WHERE A.OBStatUnitTypeID = 51 --Hours + GROUP BY + STAT.DepartmentID, + STAT.AccountID, + STAT.FiscalYearID, + STAT.FiscalMonthID, + STAT.TimeClassID + + SET @fromClause = ' + ( + SELECT GL.DepartmentID, GL.AccountID, GL.FiscalYearID, GL.FiscalMonthID, GL.TimeClassID + FROM #FactGLStaging GL + INNER JOIN #FactGLUnits U ON + U.DepartmentID = GL.DepartmentID AND + U.AccountID = GL.AccountID AND + U.FiscalYearID = GL.FiscalYearID AND + U.FiscalMonthID = GL.FiscalMonthID AND + U.TimeClassID = GL.TimeClassID + ) X + ' + + TRUNCATE TABLE #inputDepartments + + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'X', + @fromClause = @fromClause, + @whereClause = '', + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + UPDATE GL + SET GL.Units = U.Units + FROM #FactGLStaging GL + INNER JOIN #FactGLUnits U ON + U.DepartmentID = GL.DepartmentID AND + U.AccountID = GL.AccountID AND + U.FiscalYearID = GL.FiscalYearID AND + U.FiscalMonthID = GL.FiscalMonthID AND + U.TimeClassID = GL.TimeClassID + INNER JOIN #inputDepartments IP on IP.DepartmentID = U.DepartmentID + WHERE IP.BatchID = @BatchID + + SET @BatchID = @BatchID + 1 + END + + SET @fromClause = ' + ( + SELECT U.DepartmentID, U.AccountID, U.FiscalYearID, U.FiscalMonthID, U.TimeClassID, U.Units, 0 as Dollars + FROM #FactGLUnits U + LEFT JOIN #FactGLStaging GL ON + U.DepartmentID = GL.DepartmentID AND + U.AccountID = GL.AccountID AND + U.FiscalYearID = GL.FiscalYearID AND + U.FiscalMonthID = GL.FiscalMonthID AND + U.TimeClassID = GL.TimeClassID + WHERE GL.RowID IS NULL + ) X + ' + + TRUNCATE TABLE #inputDepartments + + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'X', + @fromClause = @fromClause, + @whereClause = '', + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + INSERT INTO #FactGLStaging (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Units, Dollars) + SELECT U.DepartmentID, U.AccountID, U.FiscalYearID, U.FiscalMonthID, U.TimeClassID, U.Units, 0 + FROM #FactGLUnits U + INNER JOIN #inputDepartments IP on IP.DepartmentID = U.DepartmentID + LEFT JOIN #FactGLStaging GL ON + U.DepartmentID = GL.DepartmentID AND + U.AccountID = GL.AccountID AND + U.FiscalYearID = GL.FiscalYearID AND + U.FiscalMonthID = GL.FiscalMonthID AND + U.TimeClassID = GL.TimeClassID + WHERE GL.RowID IS NULL AND IP.BatchID = @BatchID + + SET @BatchID = @BatchID + 1 + END + END --'Feature Flag Use GL Units' + -- + + --run calculations + exec fw.procFactGLSampledBaselineTargetUpdate @fiscalYearID = @fiscalYearID + exec fw.procFactMonthlyYTDPriorYearUpdateStaging 'fw.FactGLSampled','#FactGLStaging', 'AccountID', 'Dollars,Units', @fiscalYearID, 0, 0 + + if @FiscalYearID = 0 + BEGIN + truncate table fw.FactGLSampled + declare @maxYear int = (select max(FiscalYearID) from fw.FactGLStagingWithCalcs) + declare @minYear int = (select min(FiscalYearID) from fw.FactGLStagingWithCalcs) + + WHILE @minYear <= @maxYear + BEGIN + + SET @whereClause = 'FiscalYearID = ' + cast(@minYear as nvarchar(100)) + ' ' + + IF OBJECT_ID('tempdb..#inputDepartmentsForFactGLSampled') IS NOT NULL DROP TABLE #inputDepartmentsForFactGLSampled + CREATE TABLE #inputDepartmentsForFactGLSampled (DepartmentID INT, RecordsCount INT, BatchID INT) + + INSERT INTO #inputDepartmentsForFactGLSampled + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'X', + @fromClause = 'fw.FactGLStagingWithCalcs X', + @whereClause = @whereClause, + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartmentsForFactGLSampled + + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + INSERT INTO fw.FactGLSampled ( + DepartmentID + ,AccountID + ,FiscalYearID + ,FiscalMonthID + ,TimeClassID + ,Units + ,UnitsYTD + ,UnitsPriorYear + ,UnitsPriorYTD + ,Dollars + ,DollarsYTD + ,DollarsPriorYear + ,DollarsPriorYTD + ,TransactionID + ,IsSystemGenerated) + SELECT + FG.DepartmentID + ,FG.AccountID + ,FG.FiscalYearID + ,FG.FiscalMonthID + ,FG.TimeClassID + ,FG.Units + ,FG.UnitsYTD + ,FG.UnitsPriorYear + ,FG.UnitsPriorYTD + ,FG.Dollars + ,FG.DollarsYTD + ,FG.DollarsPriorYear + ,FG.DollarsPriorYTD + ,0 + ,FG.IsSystemGenerated + FROM fw.FactGLStagingWithCalcs FG + INNER JOIN #inputDepartmentsForFactGLSampled IP ON IP.DepartmentID = FG.DepartmentID + WHERE FiscalYearID = @minYear AND IP.BatchID = @BatchID + + SET @BatchID = @BatchID + 1 + END + + SET @minYear = @minYear + 1 + END + END + ELSE + BEGIN + + ;with tgt (DepartmentID, + AccountID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + Units, + UnitsYTD, + UnitsPriorYear, + UnitsPriorYTD, + Dollars, + DollarsYTD, + DollarsPriorYear, + DollarsPriorYTD, + IsDeleted, + IsSystemGenerated) as ( + select + DepartmentID, + AccountID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + Units, + UnitsYTD, + UnitsPriorYear, + UnitsPriorYTD, + Dollars, + DollarsYTD, + DollarsPriorYear, + DollarsPriorYTD, + IsDeleted, + IsSystemGenerated + from + fw.FactGLSampled + where + ( + TimeClassID != 4 + or + (TimeClassID = 4 and exists(select 1 from [mr].[SystemSetting] where Name = 'Is MR Flexing Manually Loaded' and Value = '1')) + ) + AND (FiscalYearID = @fiscalYearID) + ), + src (DepartmentID, + AccountID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + Units, + UnitsYTD, + UnitsPriorYear, + UnitsPriorYTD, + Dollars, + DollarsYTD, + DollarsPriorYear, + DollarsPriorYTD, + IsSystemGenerated) as ( + select + DepartmentID, + AccountID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + Units, + UnitsYTD, + UnitsPriorYear, + UnitsPriorYTD, + Dollars, + DollarsYTD, + DollarsPriorYear, + DollarsPriorYTD, + IsSystemGenerated + from + fw.FactGLStagingWithCalcs + where + ( + TimeClassID != 4 + or + (TimeClassID = 4 and exists(select 1 from [mr].[SystemSetting] where Name = 'Is MR Flexing Manually Loaded' and Value = '1')) + ) + AND (FiscalYearID = @fiscalYearID) + ) + + MERGE tgt as target + USING src as source + ON ( + target.departmentid = source.departmentid + and target.accountid = source.accountid + and target.fiscalyearid = source.fiscalyearid + and target.fiscalmonthid = source.fiscalmonthid + and target.timeclassid = source.timeclassid + ) + WHEN MATCHED AND ( + target.Units<> source.Units + or target.UnitsYTD<> source.UnitsYTD + or target.UnitsPriorYear<> source.UnitsPriorYear + or target.UnitsPriorYTD<> source.UnitsPriorYTD + or target.Dollars<> source.Dollars + or target.DollarsYTD<> source.DollarsYTD + or target.DollarsPriorYear<> source.DollarsPriorYear + or target.DollarsPriorYTD<> source.DollarsPriorYTD + or target.IsSystemGenerated <> source.IsSystemGenerated + ) THEN + UPDATE SET + target.Units = source.Units, + target.UnitsYTD= source.UnitsYTD, + target.UnitsPriorYear= source.UnitsPriorYear, + target.UnitsPriorYTD= source.UnitsPriorYTD, + target.Dollars= source.Dollars, + target.DollarsYTD= source.DollarsYTD, + target.DollarsPriorYear= source.DollarsPriorYear, + target.DollarsPriorYTD= source.DollarsPriorYTD, + target.IsSystemGenerated = source.IsSystemGenerated + WHEN NOT MATCHED BY TARGET THEN + INSERT (DepartmentID, + AccountID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + Units, + UnitsYTD, + UnitsPriorYear, + UnitsPriorYTD, + Dollars, + DollarsYTD, + DollarsPriorYear, + DollarsPriorYTD, + IsDeleted, + IsSystemGenerated) VALUES ( + source.DepartmentID, + source.AccountID, + source.FiscalYearID, + source.FiscalMonthID, + source.TimeClassID, + source.Units, + source.UnitsYTD, + source.UnitsPriorYear, + source.UnitsPriorYTD, + source.Dollars, + source.DollarsYTD, + source.DollarsPriorYear, + source.DollarsPriorYTD, + 0, + source.IsSystemGenerated) + WHEN NOT MATCHED BY SOURCE THEN + DELETE + OUTPUT $action, inserted.FiscalYearID, inserted.TimeClassID, inserted.isdeleted INTO #SummaryOfChanges; + END + + EXEC dbo.procRollingDeleteOnTable + 'fw', + 'fw.FactGLSampled', + 'RowID', + 'fw.FactGLSampled', + 'isDeleted = 1', + 10000000, + 0.5, + 0 + + DECLARE @nextRowID BIGINT + SELECT @nextRowID = ISNULL((SELECT MAX(RowID) FROM fw.FactGLSampled), 1) + DBCC CHECKIDENT('fw.FactGLSampled','RESEED', @nextRowID); + + --return summary of results + if (@isDebug = 1) begin + SELECT 'GL Sample' as SampleType, FiscalYearID, TimeClassID, Change, IsDeleted, COUNT(*) AS CountPerChange + FROM #SummaryOfChanges + GROUP BY Change, FiscalYearID, TimeClassID, IsDeleted; + end + + IF OBJECT_ID('tempdb..#inputDepartments') IS NOT NULL DROP TABLE #inputDepartments + IF OBJECT_ID('tempdb..#FactGLStaging') IS NOT NULL DROP TABLE #FactGLStaging + IF OBJECT_ID('tempdb..#StatisticSampledMonthlyStaging') IS NOT NULL DROP TABLE #StatisticSampledMonthlyStaging + IF OBJECT_ID('fw.FactGLStagingWithCalcs') IS NOT NULL DROP TABLE fw.FactGLStagingWithCalcs + IF OBJECT_ID('tempdb..#SummaryOfChanges') IS NOT NULL DROP TABLE #SummaryOfChanges +GO + + +--------------------------------------------- + +-- fw.procGLSampledPerformFlexing +CREATE PROC [fw].[procGLSampledPerformFlexing] + @CostingResultID int, + @CostingTimeClassID tinyint, + @FiscalYearID int +AS +/* ************************************************************************************************************************ +** Author: Nathan LeRoy +** Create Date: 2016-04-22 +** Description: Runs GL flexing for MR +** Last Modified: 2016-05-23 +************************************************************************************************************************** +** Change History +************************************************************************************************************************** +** CID Date Author WI Description +** 1 5/10/16 NL B-11692 Changed flexing to work like new ABB flexing procs +** 2 5/20/16 NL B-12055 Removed call to insert flexed data (handled in engine now) +** 3 8/05/16 NL Added call to procABBMRTransferFlexedPayrollSampledMonthlyToFactGLSampled +** 4 9/23/16 NL Adding copy from budget -> flex +** 5 1/30/16 NL MANUAL changing the way this handles NULL cost data +*************************************************************************************************************************/ + + +-- reset all of the flex data to budget (only data that should be flexed like ABB) + +SELECT DISTINCT DepartmentID +INTO #ABBDepts +FROM ( + SELECT DepartmentID FROM [dss].[FactCostingOutDetailGL] WHERE CostingResultID = @CostingResultID + UNION ALL + SELECT DepartmentID FROM [dss].[FactCostingOutDetailPayroll] WHERE CostingResultID = @CostingResultID) depts; + +INSERT INTO [fw].[FactGLSampled]([DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], [TimeClassID], [IsDeleted], [Units], [UnitsYTD], [UnitsPriorYear], [UnitsPriorYTD], [Dollars], [DollarsYTD], [DollarsPriorYear], [DollarsPriorYTD], [IsSystemGenerated]) +SELECT [DepartmentID], [AccountID], [FiscalYearID], [FiscalMonthID], 4, [IsDeleted], [Units], [UnitsYTD], [UnitsPriorYear], [UnitsPriorYTD], [Dollars], [DollarsYTD], [DollarsPriorYear], [DollarsPriorYTD], [IsSystemGenerated] +FROM [fw].[FactGLSampled] +WHERE TimeClassID = 2 and FiscalYearID = @FiscalYearID and DepartmentID in ( select DepartmentID from #ABBDepts ); + + +-- perform the flexing +UPDATE + ab +SET +-- BEG CID 5 -- + ab.Dollars = CASE WHEN ISNULL(ab.Variability, 0) = 0 + THEN ab.Dollars + ELSE ISNULL(((ab.Dollars * (1 - (cost.TotalVariableDirectCost / NULLIF(cost.TotalCost, 0.0)))) + cost.TotalExtendedVariableDirectCost), 0) + END +-- END CID 5 -- +FROM + (SELECT gl.DepartmentID, gl.AccountID, gl.FiscalYearID, gl.FiscalMonthID, gl.TimeClassID, gl.Dollars, ISNULL(avo.Variability, av.Variability) as Variability + FROM [fw].[FactGLSampled] gl + LEFT JOIN (SELECT AccountID, Variability FROM [dss].[AccountVariability] WHERE CostingConfigGuid = (SELECT CostingConfigGuid FROM [dss].[CostingResult] WHERE CostingResultID = @CostingResultID)) av ON gl.AccountID = av.AccountID + LEFT JOIN (SELECT DepartmentID, AccountID, Variability FROM [dss].[AccountVariabilityOverride] WHERE CostingConfigGuid = (SELECT CostingConfigGuid FROM [dss].[CostingResult] WHERE CostingResultID = @CostingResultID)) avo on gl.DepartmentID = avo.DepartmentID and gl.AccountID = avo.AccountID + WHERE TimeClassID = 4 AND FiscalYearID = @FiscalYearID) ab + INNER JOIN #ABBDepts abd on ab.DepartmentID = abd.DepartmentID + LEFT JOIN + (SELECT + DepartmentID, + AccountID, + FiscalMonthID, + FiscalYearID, + SUM(cost.ExtendedVariableDirectCost) as TotalExtendedVariableDirectCost, + SUM(cost.TotalVariableDirectCost) as TotalVariableDirectCost, + SUM(cost.TotalCost) as TotalCost + FROM + [fw].[viewMRGLBudgetCostPerRVUbyMonth] cost + WHERE + cost.CostingResultID = @CostingResultID + AND + cost.TimeClassID = @CostingTimeClassID + GROUP BY + DepartmentID, AccountID, FiscalMonthID, FiscalYearID + ) cost + ON ab.DepartmentID = cost.DepartmentID + AND ab.AccountID = cost.AccountID + AND ab.FiscalMonthID = cost.FiscalMonthID + AND ab.FiscalYearID = cost.FiscalYearID; + +DROP TABLE #ABBDepts; + +EXEC [fw].[procABBMRTransferFlexedPayrollSampledMonthlyToFactGLSampled] @fiscalYearID = @FiscalYearID, @CostingResultID = @CostingResultID; +GO + + +--------------------------------------------- + +-- fw.procGetSQLObjectsRelatedToDimension +CREATE PROCEDURE [fw].[procGetSQLObjectsRelatedToDimension] + @dimensionGlobalId NVARCHAR(50), + @dimensionIdValue INT +AS + --create temp table + CREATE TABLE #related_objects (Id int IDENTITY(1,1), FK_Schema VARCHAR(500) not null default(''), FK_Table VARCHAR(500) not null default(''), FK_Column VARCHAR(500) not null default(''),FriendlyName VARCHAR(200) DEFAULT('')) + + --create temp table + CREATE TABLE #result(FK_Schema VARCHAR(500) not null default(''), FK_Table VARCHAR(500) not null default(''), FK_Column VARCHAR(500) not null default(''),FriendlyName VARCHAR(200) DEFAULT('')) + + --fill table with related objects + INSERT INTO #related_objects(FK_Schema, FK_Table, FK_Column, FriendlyName) + SELECT g.SchemaName FK_Schema, g.ObjectName FK_Table, a.SQLColumnName FK_Column, d.FriendlyName FROM dbo.ScoreAttribute a + INNER JOIN dbo.ScoreDimensionGroup g ON g.DimensionGroupGUID = a.DimensionGroupGUID + INNER JOIN dbo.ScoreDimension d ON d.DimensionGUID = g.DimensionGUID + WHERE a.ForeignKeyGUID = (SELECT DefaultKeyGUID FROM dbo.ScoreDimension WHERE GlobalID = @dimensionGlobalId) + + INSERT INTO #related_objects(FK_Schema, FK_Table, FK_Column, FriendlyName) + SELECT dt.SQLSchemaName FK_Schema, dt.SQLObjectName FK_Table, a.SQLColumnName FK_Column ,dt.FriendlyName + FROM ScoreDataTable dt + INNER JOIN ScoreDataTableKeyLink kl ON kl.DataTableGUID = dt.DataTableGUID + INNER JOIN dbo.ScoreAttribute a ON a.AttributeGUID = kl.KeyGUID + WHERE a.AttributeGUID = (SELECT DefaultKeyGUID FROM dbo.ScoreDimension WHERE GlobalID = @dimensionGlobalId) + + INSERT INTO #related_objects(FK_Schema, FK_Table, FK_Column, FriendlyName) + SELECT fk.FK_Schema, fk.FK_Table, fk.FK_Column, fk.FK_Table + FROM dbo.ScoreDimension d + JOIN dbo.ScoreDimensionGroup dg ON d.DimensionGUID = dg.DimensionGUID + JOIN dbo.viewSysForeignKeys fk ON dg.ObjectName = PK_Table + LEFT JOIN #related_objects r ON r.FK_Schema = fk.FK_Schema AND r.FK_Table = fk.FK_Table AND r.FK_Column = fk.FK_Column + WHERE d.GlobalID = @dimensionGlobalId + AND r.FK_Schema IS NULL + + DECLARE @count INT = 1, @total INT = 0, @table VARCHAR(150), @schema VARCHAR(50), @column VARCHAR(50), @friendlyName VARCHAR(500), @sql VARCHAR(MAX) + + SELECT @total = COUNT(0) FROM #related_objects + + WHILE(@count <= @total) + BEGIN + + SELECT @schema = FK_Schema, @table = FK_Table, @column = FK_Column, @friendlyName = FriendlyName FROM #related_objects WHERE Id = @count + + SET @sql = 'IF EXISTS(SELECT TOP 1 1 FROM ['+@schema+'].['+@table+'] WHERE '+@column+'='''+CAST(@dimensionIdValue AS VARCHAR)+''') + BEGIN + INSERT INTO #result (FK_Schema, FK_Table, FK_Column,FriendlyName) VALUES ('''+@schema+''','''+@table+''','''+@column+''','''+@friendlyName+''') + END' + EXEC(@sql) + + SET @count = @count + 1 + END + + SELECT FK_Schema, FK_Table, FriendlyName FROM #result + + DROP TABLE #related_objects + DROP TABLE #result +GO + + +--------------------------------------------- + +-- fw.procGetStatisticsDrillIn +CREATE PROCEDURE [fw].[procGetStatisticsDrillIn]( + @DepartmentIDs VARCHAR(max) + ,@AccountIDs VARCHAR(max) + ,@PayPeriodIDs VARCHAR(max) + ,@isYTD bit + ) +AS +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-12-18 IP B-17582 created procedure +** 2 2018-05-08 KF B-19364 MRPR - Set Global Weights for Charge Codes - System Center Page +** 3 2018-10-20 IH D-07606 PR - Delete rounding charge code values +** 4 2019-04-19 OV B-20579 filtered by new column 'TimeClassID' from int.FactSharedImportDailyStatistics +** 5 2019-05-01 KF D-08230 [fw].[procGetStatisticsDrillIn] is not taking the actual weighted average +** 6 2022-05-11 HV JAZZ-36796 PR - Volume charge code data doesn't populate if loaded with real time stamp +** 7 2022-07-01 HV JAZZ-40032 Rollback to previous version +** 8 2022-07-19 HV JAZZ-39414 procGetStatisticsDrillIn timing out after 3 minutes + JAZZ-36796 PR - Volume charge code data doesn't populate if loaded with real time stamp +** 9 2023-02-17 IS JAZZ-49480 fw.procGetStatisticsDrillIn has excessive part looking at TimeClassID=2 data +*************************************************************/ +BEGIN + IF OBJECT_ID('tempdb..#filtering') IS NOT NULL DROP TABLE #filtering + IF OBJECT_ID('tempdb..#SubSelect') IS NOT NULL DROP TABLE #SubSelect + IF OBJECT_ID('tempdb..#FDPSD') IS NOT NULL DROP TABLE #FDPSD + IF OBJECT_ID('tempdb..#ConsolidatedParams') IS NOT NULL DROP TABLE #ConsolidatedParams + + CREATE TABLE #FDPSD (DepartmentID int primary key) + insert into #FDPSD + select distinct DriverDepartmentID as DepartmentID + from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache + + CREATE TABLE #ConsolidatedParams (DepartmentID int, AccountId int, PayPeriodID int) + CREATE TABLE #filtering ( + DepartmentID INT + ,AccountID INT + ,PayPeriodID INT + ,TimeClassID INT + ,SelectTable TINYINT + ) + +IF @isYTD = 1 + INSERT INTO #ConsolidatedParams (DepartmentID,AccountId,PayPeriodID) + SELECT DISTINCT d.DepartmentID,A.val as AccountID,pp_a.PayPeriodID + FROM ConvertCSValuesToTable(@departmentIDs, ',') csv + inner join fw.DimDepartment d on d.DepartmentID = csv.val + inner join fw.DimPayPeriod pp on pp.PayCycleID =d.PayCycleID + inner join ConvertCSValuesToTable(@PayPeriodIDs, ',') p on p.val = pp.PayPeriodCode + INNER JOIN fw.DimPayPeriod pp_a on pp_a.PeriodNumber <= pp.PeriodNumber and pp_a.FiscalYearIDSecond = pp.FiscalYearIDSecond and pp_a.PayCycleID = pp.PayCycleID + inner join ConvertCSValuesToTable(@AccountIDs, ',') a on 1=1 +ELSE + INSERT INTO #ConsolidatedParams (DepartmentID,AccountId,PayPeriodID) + SELECT DISTINCT d.DepartmentID,A.val as AccountID,pp.PayPeriodID + FROM ConvertCSValuesToTable(@departmentIDs, ',') csv + inner join fw.DimDepartment d on d.DepartmentID = csv.val + inner join fw.DimPayPeriod pp on pp.PayCycleID =d.PayCycleID + inner join ConvertCSValuesToTable(@PayPeriodIDs, ',') p on p.val = pp.PayPeriodCode + inner join ConvertCSValuesToTable(@AccountIDs, ',') a on 1=1 + +INSERT INTO #filtering ( + DepartmentID + ,AccountID + ,PayPeriodID + ,TimeClassID + ,SelectTable + ) + + SELECT STAT.DepartmentID + ,STAT.AccountID + ,STAT.PayPeriodID + ,STAT.TimeClassID + ,1 AS SelectTable + FROM [int].[FactStatisticsbyPayPeriod] STAT + INNER JOIN [fw].[DimDepartment] D ON D.Departmentid = STAT.Departmentid + inner join #ConsolidatedParams cp on cp.AccountId = STAT.AccountID and cp.DepartmentID = STAT.DepartmentID and cp.PayPeriodID = STAT.PayPeriodID + left join #FDPSD FDPSD ON FDPSD.DepartmentID = STAT.DepartmentID + WHERE STAT.Value != 0 + AND STAT.Isdeleted = 0 + AND STAT.PayPeriodID != 0 + and (D.IsPR = 1 or FDPSD.DepartmentID is not null) + AND STAT.TimeClassID = 1 + AND stat.DepartmentID <> 0 + +UNION + + SELECT stat.DepartmentID + ,stat.AccountID + ,PP.PayPeriodID + ,stat.TimeClassID + ,2 AS SelectTable + FROM [int].[FactSharedImportDailyStatistics] stat + INNER JOIN [fw].[DimDate] DATE ON stat.DateID = DATE.DateID + INNER JOIN [fw].[DimDepartment] D ON D.Departmentid = STAT.Departmentid + INNER JOIN [fw].[DimPayPeriod] PP ON D.PayCycleID = PP.PayCycleID + AND DATE.CalendarDateTime BETWEEN PP.PeriodStartCalendarDate + AND PP.PeriodEndCalendarDate + inner join #ConsolidatedParams cp on cp.AccountId = STAT.AccountID and cp.DepartmentID = STAT.DepartmentID and cp.PayPeriodID = pp.PayPeriodID + left join #FDPSD FDPSD ON FDPSD.DepartmentID = STAT.DepartmentID + WHERE stat.Value <> 0 + AND TimeClassID = 1 + AND STAT.Isdeleted = 0 + AND PP.PayPeriodID != 0 + and (D.IsPR = 1 or FDPSD.DepartmentID is not null) + AND stat.DepartmentID <> 0 + GROUP BY stat.DepartmentID + ,stat.AccountID + ,PP.PayPeriodID + ,stat.TimeClassID + +UNION + + SELECT STAT.DepartmentID + ,STAT.AccountID + ,PP.PayPeriodID + ,1 AS TimeClassID + ,3 AS SelectTable + FROM [fw].[FactChargeBasedStatistics] STAT + INNER JOIN [fw].[DimDate] DATE ON STAT.DateID = DATE.DateID + INNER JOIN [fw].[DimDepartment] DEPT ON STAT.DepartmentID = DEPT.DepartmentID + INNER JOIN [fw].[DimPayPeriod] PP ON DEPT.PayCycleID = PP.PayCycleID + AND DATE.CalendarDateTime BETWEEN PP.PeriodStartCalendarDate + AND PP.PeriodEndCalendarDate + inner join #ConsolidatedParams cp on cp.AccountId = STAT.AccountID and cp.DepartmentID = STAT.DepartmentID and cp.PayPeriodID = pp.PayPeriodID + left join #FDPSD FDPSD ON FDPSD.DepartmentID = STAT.DepartmentID + WHERE STAT.Value != 0 + AND STAT.IsDeleted = 0 + AND PP.PayPeriodID != 0 + and (DEPT.IsPR = 1 or FDPSD.DepartmentID is not null) + GROUP BY STAT.DepartmentID + ,STAT.AccountID + ,PP.PayPeriodID + + DELETE F FROM #filtering f + inner join ( + SELECT DepartmentID + ,AccountID + ,PayPeriodID + ,TimeClassID + ,SelectTable + ,max(SelectTable) OVER(PARTITION BY DepartmentID,AccountID,TimeClassID,PayPeriodID ORDER BY DepartmentID,AccountID,TimeClassID,PayPeriodID) AS SelectTableMax + ,count(SelectTable) OVER(PARTITION BY DepartmentID,AccountID,TimeClassID,PayPeriodID ORDER BY DepartmentID,AccountID,TimeClassID,PayPeriodID) AS SelectTableCount + FROM #filtering) d + on f.DepartmentID = d.DepartmentID + and f.AccountID = d.AccountID + and f.TimeClassID = d.TimeClassID + and f.PayPeriodID = d.PayPeriodID + and NOT (d.SelectTableCount = 1 and d.SelectTableMax = 3) + + SELECT + pt.PatientTypeRollupID, + bl.DepartmentID, + bl.FiscalYearID as FiscalYearID, + bl.ChargeCodeID, + sum(bl.UnitsOfService) AS ChargeCodeValue_UnitsOfService + INTO #SubSelect + FROM [dss].[FactPatientBillingLineItemDetail] bl + INNER JOIN clientdss.FactPatientEncounterSummary es WITH (READUNCOMMITTED) ON bl.EncounterID = es.EncounterID + INNER JOIN fw.DimPatientType pt WITH (READUNCOMMITTED) ON es.PatientTypeID = pt.PatientTypeID + INNER JOIN ( + SELECT DISTINCT DepartmentID, dpp.PeriodStartCalendarDate, dateadd(millisecond, -1, convert(datetime2(3),dateadd(day, 1, convert(date, dpp.PeriodEndCalendarDate)))) as PeriodEndCalendarDate from #filtering f + INNER JOIN fw.DimPayPeriod dpp on dpp.PayPeriodID = f.PayPeriodID + ) flt on flt.DepartmentID = bl.DepartmentID and bl.ServiceDateTime between flt.PeriodStartCalendarDate and flt.PeriodEndCalendarDate + GROUP BY pt.PatientTypeRollupID, + bl.ChargeCodeID, + bl.DepartmentID, + bl.FiscalYearID + option (recompile) + + SELECT + S.ChargeCode, + S.PatientTypeRollup, + round(S.ChargeCodeValue_UnitsOfService, 0) AS ChargeCodeValue_UnitsOfService, + CAST(S.StatisticValue/S.ChargeCodeValue_UnitsOfService AS Numeric(19,4)) AS Weight, + S.StatisticValue + FROM + ( SELECT + cc.NAME AS ChargeCode + ,ptr.NAME AS PatientTypeRollup + ,sum(subselect.ChargeCodeValue_UnitsOfService) as ChargeCodeValue_UnitsOfService + ,sum(subselect.ChargeCodeValue_UnitsOfService * map.Weight) AS StatisticValue + FROM #SubSelect subselect + INNER JOIN [fw].[viewDepartmentChargeCodeStatisticMapping] map WITH (READUNCOMMITTED) ON subselect.DepartmentID = map.DepartmentID + AND subselect.ChargeCodeID = map.ChargeCodeID + AND subselect.PatientTypeRollupID = map.PatientTypeRollupID + AND map.FiscalYearID = subselect.FiscalYearID + INNER JOIN fw.DimChargeCode cc ON cc.ChargeCodeID = map.ChargeCodeID + INNER JOIN fw.DimPatientTypeRollup ptr WITH (READUNCOMMITTED) ON ptr.PatientTypeRollupID = subselect.PatientTypeRollupID + INNER JOIN (select distinct AccountID from #filtering) flt ON flt.AccountID = map.AccountID + WHERE map.Weight <> 0 + GROUP BY cc.NAME, ptr.NAME + HAVING sum(subselect.ChargeCodeValue_UnitsOfService) <> 0 + ) S + + IF OBJECT_ID('tempdb..#filtering') IS NOT NULL DROP TABLE #filtering + IF OBJECT_ID('tempdb..#SubSelect') IS NOT NULL DROP TABLE #SubSelect + IF OBJECT_ID('tempdb..#FDPSD') IS NOT NULL DROP TABLE #FDPSD + IF OBJECT_ID('tempdb..#ConsolidatedParams') IS NOT NULL DROP TABLE #ConsolidatedParams +END +GO + + +--------------------------------------------- + +-- fw.procInsertDimensionDefaults +--Author: gforeman +--Branch: GoldenManMigr +--Forward +CREATE PROCEDURE [fw].[procInsertDimensionDefaults] +AS +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + DECLARE @DEFAULTID int + SET @DEFAULTID = 0 + + DECLARE @DEFAULTNAME nvarchar(100) + SET @DEFAULTNAME = 'Not Specified' + + IF NOT EXISTS (SELECT 1 FROM fw.DimAccount where AccountID = 0) + BEGIN + SET IDENTITY_INSERT fw.DimAccount ON + INSERT INTO fw.DimAccount (AccountID) VALUES (@DEFAULTID) + SET IDENTITY_INSERT fw.DimAccount OFF + END + + IF NOT EXISTS (SELECT 1 FROM fw.DimDepartment where DepartmentID = 0) + BEGIN + SET IDENTITY_INSERT fw.DimDepartment ON + INSERT INTO fw.DimDepartment (DepartmentID, Description) VALUES (@DEFAULTID, @DEFAULTNAME) + SET IDENTITY_INSERT fw.DimDepartment OFF + END + + IF NOT EXISTS (SELECT 1 FROM fw.DimEmployee where EmployeeID = 0) + BEGIN + SET IDENTITY_INSERT fw.DimEmployee ON + INSERT INTO fw.DimEmployee (EmployeeID, NameLast, NameFirst) VALUES (@DEFAULTID, @DEFAULTNAME, @DEFAULTNAME) + SET IDENTITY_INSERT fw.DimEmployee OFF + END + + IF NOT EXISTS (SELECT 1 FROM fw.DimJobCode where JobCodeID = 0) + BEGIN + SET IDENTITY_INSERT fw.DimJobCode ON + INSERT INTO fw.DimJobCode (JobCodeID) VALUES (@DEFAULTID) + SET IDENTITY_INSERT fw.DimJobCode OFF + END + +END +GO + + +--------------------------------------------- + +-- fw.procInsertPayPeriodsForPayCycle +CREATE PROC fw.procInsertPayPeriodsForPayCycle +@payCycleId INT, +@numOfYearsToAdd INT +AS + +----verify paycycle id exists if it does not exit out +IF NOT EXISTS (SELECT 1 FROM fw.DimPayCycle WHERE PayCycleID=@payCycleId) + BEGIN + EXEC [migration].[LogMigrationDetail] @Name = 'fw.procInsertPayPeriodsForPayCycle', + @Message = 'PayCycleId not found', + @AffectedObject = 'fw.DimPayPeriod', + @Status='Warning'; + Return + END + + --limiting this to at most 20 years into the future from today and 20 years at a time +IF ((@numOfYearsToAdd>20) OR (DATEDIFF(YEAR, GETDATE(), (SELECT DATEADD(YEAR, @numOfYearsToAdd , MAX(PeriodEndCalendarDate)) FROM fw.dimpayperiod WHERE PayCycleID = @payCycleId)) > 20)) + BEGIN + EXEC [migration].[LogMigrationDetail] @Name = 'fw.procInsertPayPeriodsForPayCycle', + @Message = 'Over limit of 20 for number of years to add at once or over 20 years from today for pay periods', + @AffectedObject = 'fw.DimPayPeriod', + @Status='Warning'; + Return + END + +DECLARE @lastPayPeriod INT; +DECLARE @paygap INT; +DECLARE @newStart DATETIME; +DECLARE @fiscalYear INT; +DECLARE @previousFiscalYear INT; +DECLARE @previousPeriodNum INT; +DECLARE @payCycleName VARCHAR(200); + +SELECT TOP 1 @lastPayPeriod = pp.PayPeriodID, @paygap = pp.PeriodDays, @newStart = DATEADD(DAY, 1, PeriodEndCalendarDate), + @FiscalYear = dbo.GetFiscalYearForDate(PeriodEndCalendarDate) + @numOfYearsToAdd, + @previousFiscalYear = dbo.GetFiscalYearForDate(PeriodEndCalendarDate), + @previousPeriodNum = pp.periodnumber, @payCycleName = pp.PayCycleName + FROM + fw.dimpayperiod pp + WHERE pp.PayCycleID = @payCycleId ORDER BY PayPeriodID desc + +DECLARE @endDate DATETIME SET @endDate = DATEFROMPARTS(@fiscalYear, (DATEPART(MONTH, dbo.GetFiscalYearEndDate())), DATEPART(DAY, dbo.GetFiscalYearEndDate())) +DECLARE @numOfEntries INT SET @numOfEntries = (SELECT FLOOR(DATEDIFF(day, @newStart, @endDate )/@paygap)) +DECLARE @historyItemGUID UNIQUEIDENTIFIER = (SELECT NEWID()); + +IF OBJECT_ID('tempdb..#tempTablePayPeriods') IS NOT NULL DROP TABLE #tempTablePayPeriods; +CREATE TABLE #tempTablePayPeriods (PeriodDays TINYINT, RowNumberID INT, WorkingDays TINYINT, PayCycleId INT, PayCycleSortOrder INT, + AccrualMethod NVARCHAR(100), PayCycleCode NVARCHAR(200), PeriodEndCalendarDate DATETIME, + FiscalYearIDStart INT, FiscalYearIDSecond INT, PeriodNumber TINYINT, PayPeriodCode NVARCHAR(100), + Code NVARCHAR(350), Name NVARCHAR(350), PayCycleName VARCHAR(200), HistoryItemGUID UNIQUEIDENTIFIER) + + INSERT into #tempTablePayPeriods + SELECT *,CONCAT(FiscalYearIdSecond, '-', PeriodNumber) PayPeriodCode, CONCAT(PayCycleCode, ' - ', finalCalculations.FiscalYearIdSecond,'-', PeriodNumber) Code, + CONCAT(@payCycleName, ' - ',finalCalculations.FiscalYearIdSecond, '-', PeriodNumber) Name, @payCycleName PayCycleName, @historyItemGUID HistoryItemGuid + FROM ( + SELECT PeriodDays, RowNumberID, WorkingDays, PayCycleId, PayCycleSortOrder, AccrualMethod, + PayCycleCode, PeriodEndCalendarDate, FiscalYearIDStart, FiscalYearIDSecond, IIF(FiscalYearIdSecond = @previousFiscalYear, PeriodNumberCalc + @previousPeriodNum, PeriodNumberCalc) AS 'PeriodNumber' + FROM ( + SELECT *, ROW_NUMBER() OVER (PARTITION BY FiscalYearIdSecond ORDER BY RowNumberID) AS 'PeriodNumberCalc' + FROM ( + SELECT *, dbo.GetFiscalYearForDate((dateadd(day,(1)-PeriodDays,PeriodEndCalendarDate))) FiscalYearIdStart, + dbo.GetFiscalYearForDate(PeriodEndCalendarDate) FiscalYearIdSecond + FROM + ( + SELECT + pp.PeriodDays, + rn.RowNumberID, + pp.WorkingDays, + pc.PayCycleID, + pc.SortOrder PayCycleSortOrder, + pc.AccrualMethod, + pc.Code PayCycleCode, + DATEADD(DAY, (@paygap * rn.RowNumberID), pp.PeriodEndCalendarDate) PeriodEndCalendarDate + FROM fw.DimPayPeriod pp + INNER JOIN fw.DimRowNumber rn ON rn.RowNumberID BETWEEN 1 AND @numOfEntries -- however many new entries are required + INNER JOIN fw.DimPayCycle pc ON pc.PayCycleID = pp.PayCycleID + WHERE pp.PayCycleID =@payCycleId + AND pp.PayPeriodID = @lastPayPeriod-- this whatever the last row in the current paycycle is + ) baseSelection + ) periodNumber + )periodNumberFilter + ) finalCalculations ORDER BY finalCalculations.RowNumberID + + INSERT INTO fw.dimpayperiod (PeriodDays, WorkingDays, PayCycleId, PayCycleSortOrder, AccrualMethod, PayCycleCode, PeriodEndCalendarDate, FiscalYearIDStart, + FiscalYearIDSecond, PeriodNumber, PayPeriodCode, Code, Name, PayCycleName, HistoryItemGUID) + SELECT PeriodDays, WorkingDays, PayCycleId, PayCycleSortOrder, AccrualMethod, PayCycleCode, PeriodEndCalendarDate, FiscalYearIDStart, + FiscalYearIDSecond, PeriodNumber, PayPeriodCode, Code, Name, PayCycleName, HistoryItemGUID + FROM #tempTablePayPeriods + + --insert into history item table + DECLARE @entityguid UNIQUEIDENTIFIER SET @entityguid = (SELECT DimensionGUID FROM dbo.ScoreDimension WHERE GlobalID='Pay Period') + EXEC dbo.procLogObjectHistoryItemGUIDObjectType 'Strata.Score.Config.Dimension.ScoreDimension, Strata.Score, Version=2024.33.0.0, Culture=neutral, PublicKeyToken=null', + @entityguid,'Adding Pay Period Ids for Pay Cycle', 0, @historyItemGUID + + DROP TABLE #tempTablePayPeriods; +GO + + +--------------------------------------------- + +-- fw.procMergeEncounterBasedStatistics +CREATE PROC fw.procMergeEncounterBasedStatistics + @statisticID int +AS +BEGIN + SET NOCOUNT ON + + CREATE TABLE #detailsToMerge + ( + RowID bigint identity(1,1), + DateID int, + DepartmentID int, + AccountID int, + Value decimal(19, 4) + ) + CREATE CLUSTERED INDEX CNU_RowId ON #detailsToMerge(RowId) + + INSERT #detailsToMerge (DepartmentID, AccountID, DateID, Value) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, SUM(ebs.Value) + FROM fw.FactEncounterBasedStatistics ebs + WHERE ebs.StatisticID = @statisticID + GROUP BY ebs.DepartmentID, ebs.AccountID, ebs.DateID + + CREATE TABLE #batch + ( + DateID int, + DepartmentID int, + AccountID int, + Value decimal(19, 4) + ) + + DECLARE + @startRowId bigint, + @maxRowId bigint, + @endRowId bigint + + SELECT @startRowId = MIN(RowId), @maxRowId = MAX(RowId) + FROM #detailsToMerge + + WHILE (@startRowId <= @maxRowId) + BEGIN + SELECT @endRowId = MAX(d.RowId) + FROM (SELECT TOP 1000000 RowId + FROM #detailsToMerge + WHERE RowId >= @startRowId + ORDER BY RowID) as d + + TRUNCATE TABLE #batch + + INSERT #batch (DepartmentID, AccountID, DateID, Value) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, ebs.Value + FROM #detailsToMerge ebs + WHERE ebs.RowId >= @startRowId + AND ebs.RowId <= @endRowId + + UPDATE fw.FactChargeBasedStatistics + SET Value = ebs.Value + FROM fw.FactChargeBasedStatistics cbs + JOIN #batch ebs + ON cbs.DepartmentID = ebs.DepartmentID + AND cbs.AccountID = ebs.AccountID + AND cbs.DateID = ebs.DateID + + INSERT fw.FactChargeBasedStatistics (DepartmentID, AccountID, DateID, Value) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, ebs.Value + FROM #batch ebs + WHERE NOT EXISTS + ( + SELECT cbs.RowID + FROM fw.FactChargeBasedStatistics cbs + WHERE ebs.DepartmentID = cbs.DepartmentID + AND ebs.AccountID = cbs.AccountID + AND ebs.DateID = cbs.DateID + ) + + SELECT @startRowId = MIN(d.RowId) + FROM #detailsToMerge d + WHERE RowId > @endRowId + END + + DROP TABLE IF EXISTS #detailsToMerge + DROP TABLE IF EXISTS #batch +END +GO + + +--------------------------------------------- + +-- fw.procMergeEncounterBasedStatisticsMonthly +CREATE PROC fw.procMergeEncounterBasedStatisticsMonthly + @statisticID int +AS +BEGIN + SET NOCOUNT ON + + DROP TABLE IF EXISTS #detailsToMerge + + CREATE TABLE #detailsToMerge + ( + FiscalYearID smallint, + FiscalMonthID tinyint, + DepartmentID int, + AccountID int, + Value decimal(19, 4) + ) + + INSERT #detailsToMerge (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.FiscalYearID, ebs.FiscalMonthID, ebs.Value + FROM fw.FactEncounterBasedStatisticsMonthly ebs + WHERE ebs.StatisticID = @statisticID + + UPDATE #detailsToMerge + SET Value = aggr.AggregatedValue + FROM + ( + SELECT ebs.FiscalYearID, ebs.FiscalMonthID, ebs.DepartmentID, ebs.AccountID, SUM(ebs.Value) AS AggregatedValue + FROM #detailsToMerge d + JOIN fw.FactEncounterBasedStatisticsMonthly ebs + ON ebs.DepartmentID = d.DepartmentID + AND ebs.AccountID = d.AccountID + AND ebs.FiscalYearID = d.FiscalYearID + AND ebs.FiscalMonthID = d.FiscalMonthID + GROUP BY ebs.FiscalYearID, ebs.FiscalMonthID, ebs.DepartmentID, ebs.AccountID + ) aggr + JOIN #detailsToMerge det + ON aggr.DepartmentID = det.DepartmentID + AND aggr.AccountID = det.AccountID + AND aggr.FiscalYearID = det.FiscalYearID + AND aggr.FiscalMonthID = det.FiscalMonthID + + UPDATE fw.FactChargeBasedStatisticsMonthly + SET Value = ebs.Value + FROM #detailsToMerge ebs + JOIN fw.FactChargeBasedStatisticsMonthly cbs + ON ebs.DepartmentID = cbs.DepartmentID + AND ebs.AccountID = cbs.AccountID + AND ebs.FiscalYearID = cbs.FiscalYearID + AND ebs.FiscalMonthID = cbs.FiscalMonthID + + INSERT fw.FactChargeBasedStatisticsMonthly (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.FiscalYearID, ebs.FiscalMonthID, ebs.Value + FROM #detailsToMerge ebs + WHERE NOT EXISTS + ( + SELECT cbs.RowID + FROM fw.FactChargeBasedStatisticsMonthly cbs + WHERE ebs.DepartmentID = cbs.DepartmentID + AND ebs.AccountID = cbs.AccountID + AND ebs.FiscalYearID = cbs.FiscalYearID + AND ebs.FiscalMonthID = cbs.FiscalMonthID + ) +END +GO + + +--------------------------------------------- + +-- fw.procOptimizationRebuildIndexesAll +CREATE proc [fw].[procOptimizationRebuildIndexesAll] + @AreYouSureYouWantToTakeDownTheSQLServer bit = 0 +as + +/************************************************************ +** Author: akowalski +** Create Date: 2015-12-08 +** Description: Rebuilds indexs and updates statistics on all tables in the database. Do not use unless you're sure you know what you're doing. It could take days to complete on platform customers. +** Last Modified: 2015-12-08 +** GM Release: 2015-12-08 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +*************************************************************/ + +if @AreYouSureYouWantToTakeDownTheSQLServer=1 +begin + +SET NOCOUNT ON; + + DECLARE @SCHEMA nvarchar(256) + DECLARE @FactTableName nvarchar(256) + DECLARE @SQL nvarchar(1024) + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t + where t.object_ID not in ( + select distinct t.object_id from sys.tables t + inner join sys.indexes i on t.object_id=i.object_id + inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id + where p.data_compression<>0 + ) order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + --=================== BEGIN CID 1 ===================== + set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD + update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN' + --=================== END CID 1 ======================= + --print @SQL + EXECUTE sp_executesql @SQL + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t + where t.object_ID not in ( + select distinct t.object_id from sys.tables t + inner join sys.indexes i on t.object_id=i.object_id + inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id + where p.data_compression=0 + ) order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + --=================== BEGIN CID 1 ===================== + set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE) + update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN' + --=================== END CID 1 ======================= + --print @SQL + EXECUTE sp_executesql @SQL + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor +end + + +RETURN +GO + + +--------------------------------------------- + +-- fw.procOptimizationRebuildIndexesDimensions +CREATE proc [fw].[procOptimizationRebuildIndexesDimensions] as + +/************************************************************ +** Author: akowalski +** Create Date: 2013-02-18 +** Description: Finds all dimension tables in the FW schemas and rebuilds indexes, for after dimension customization. +** Last Modified: 2013-02-18 +** GM Release: 2013-03-12 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2013-02-19 DK 56588 Adding update statistics command +** +*************************************************************/ + + +SET NOCOUNT ON; + + DECLARE @SCHEMA nvarchar(256) + DECLARE @FactTableName nvarchar(256) + DECLARE @SQL nvarchar(1024) + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t + where t.schema_id in(select schema_id from sys.schemas where name in('fw', 'client')) and t.name like 'dim%' + and t.object_ID not in ( + select distinct t.object_id from sys.tables t + inner join sys.indexes i on t.object_id=i.object_id + inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id + where p.data_compression<>0 + ) order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + --=================== BEGIN CID 1 ===================== + set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD + update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN' + --=================== END CID 1 ======================= + --print @SQL + EXECUTE sp_executesql @SQL + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t + where t.schema_id in(select schema_id from sys.schemas where name in('fw', 'client')) and t.name like 'dim%' + and t.object_ID not in ( + select distinct t.object_id from sys.tables t + inner join sys.indexes i on t.object_id=i.object_id + inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id + where p.data_compression=0 + ) order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + --=================== BEGIN CID 1 ===================== + set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE) + update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN' + --=================== END CID 1 ======================= + --print @SQL + EXECUTE sp_executesql @SQL + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor +RETURN +GO + + +--------------------------------------------- + +-- fw.procOptimizationRebuildIndexesFillins +CREATE proc fw.procOptimizationRebuildIndexesFillins as + +/************************************************************ +** Author: akowalski +** Create Date: 2013-02-18 +** Description: Finds all fillin tables rebuilds indexes, for after fillin refreshes. +** Last Modified: 2013-02-18 +** GM Release: 2013-03-12 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + + +SET NOCOUNT ON; + + DECLARE @SCHEMA nvarchar(256) + DECLARE @FactTableName nvarchar(256) + DECLARE @SQL nvarchar(1024) + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in ('data', 'dbo')) and t.name like 'ScoreFillin%' + and t.object_ID not in ( + select distinct t.object_id from sys.tables t + inner join sys.indexes i on t.object_id=i.object_id + inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id + where p.data_compression<>0 + ) order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD + update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN' + --print @SQL + EXECUTE sp_executesql @SQL + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in ('data', 'dbo')) and t.name like 'ScoreFillin%' + and t.object_ID not in ( + select distinct t.object_id from sys.tables t + inner join sys.indexes i on t.object_id=i.object_id + inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id + where p.data_compression=0 + ) order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE) + update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN' + --print @SQL + EXECUTE sp_executesql @SQL + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + +RETURN +GO + + +--------------------------------------------- + +-- fw.procOptimizationRebuildIndexesSecurity +CREATE proc fw.procOptimizationRebuildIndexesSecurity as +/************************************************************ +** Author: akowalski +** Create Date: 2014-04-23 +** Description: Finds all security related tables, for after mass security assignments. +** Last Modified: 2014-04-23 +** GM Release: 2014.3 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + + +SET NOCOUNT ON; + + DECLARE @SCHEMA nvarchar(256) + DECLARE @FactTableName nvarchar(256) + DECLARE @SQL nvarchar(1024) + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in ('dbo')) and t.name like 'S3%' + and t.object_ID not in ( + select distinct t.object_id from sys.tables t + inner join sys.indexes i on t.object_id=i.object_id + inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id + where p.data_compression<>0 + ) order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD + update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN' + --print @SQL + EXECUTE sp_executesql @SQL + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in ('dbo')) and t.name like 'S3%' + and t.object_ID not in ( + select distinct t.object_id from sys.tables t + inner join sys.indexes i on t.object_id=i.object_id + inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id + where p.data_compression=0 + ) order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE) + update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN' + --print @SQL + EXECUTE sp_executesql @SQL + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + +alter index all on dbo.xplan REBUILD +update statistics dbo.xplan WITH FULLSCAN + + +RETURN +GO + + +--------------------------------------------- + +-- fw.procOptimizationRebuildIndexesWorkflow +CREATE proc fw.procOptimizationRebuildIndexesWorkflow as +/************************************************************ +** Author: akowalski +** Create Date: 2014-04-23 +** Description: Finds all workflow related tables, for during heavy capital budgeting. +** Last Modified: 2014-04-23 +** GM Release: 2014.3 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + + +SET NOCOUNT ON; + + DECLARE @SCHEMA nvarchar(256) + DECLARE @FactTableName nvarchar(256) + DECLARE @SQL nvarchar(1024) + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in ('dbo')) and t.name like 'WF%' + and t.object_ID not in ( + select distinct t.object_id from sys.tables t + inner join sys.indexes i on t.object_id=i.object_id + inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id + where p.data_compression<>0 + ) order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD + update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN' + --print @SQL + EXECUTE sp_executesql @SQL + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in ('dbo')) and t.name like 'WF%' + and t.object_ID not in ( + select distinct t.object_id from sys.tables t + inner join sys.indexes i on t.object_id=i.object_id + inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id + where p.data_compression=0 + ) order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD WITH (DATA_COMPRESSION = PAGE) + update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN' + --print @SQL + EXECUTE sp_executesql @SQL + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + +RETURN +GO + + +--------------------------------------------- + +-- fw.procPayRollSampledAdjustedTargetMonthlyInsert +CREATE PROCEDURE [fw].[procPayRollSampledAdjustedTargetMonthlyInsert] (@FiscalYearID int = 0) +AS +BEGIN +/* +Proposal + +If the client is not using flexing, this will be the target plus the efficiency factor +This should work regardless of the target basis (i.e. rolling avg or budget) +The factor will be applied after the inversion +If the factor type is percentage, the adjusted target will be the target*(1+factor) +i.e. if my target is 100 and my factor is 5%, the adjusted target will be 100*(1+0.05)=105 +i.e. if my target is 100 and my factor is -5%, the adjusted target will be 100*(1+-0.05)=95 +If the factor type is value, the adjusted value will be target + factor +i.e. if my target is 1000 and my factor is 200, the adjusted target will be will be 1000+200=1200 +i.e. if my target is 1000 and my factor is -200, the adjusted target will be 1000-200=800 +If there is more than one factor impacting a department and account or job code/pay code group combination, then the factors should layer on top of each other based on history order +If an efficiency factor does not exist for a particular account/job code, then the value in the new time class will be either flex or baseline target if flex is not used +This will happen after Flex is calculated +Include integration tests +*/ +/* +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-04-18 IP TK-57807 Fixed issue PR Statistic Sampling: 'Reallocate between departments' adjustment is calculated incorrectly +** 2 2019-01-17 GF D-08031 Optimized PCG case +** 3 2019-06-14 OV D-08158 Added join to JobCodeGroup +** 4 2019-10-22 KF D-08819 FTE Baseline Calculation Issue +** 5 2022-08-23 BC JAZZ-11498 Change Table Variable to Temporary Tables +************************************************************ +*/ + +DECLARE @IsFlexingEnabled INT = ( + SELECT value + FROM [mr].[SystemSetting] + WHERE NAME = 'Is Target Flexed' + ) + +IF EXISTS (SELECT TOP 1 * FROM [mr].[EfficiencyFactor]) BEGIN +IF OBJECT_ID('tempdb..#EfficiencyFactorScope') IS NOT NULL DROP TABLE #EfficiencyFactorScope +CREATE TABLE #EfficiencyFactorScope ( + EfficiencyFactorGUID [uniqueidentifier] NOT NULL + ,[DepartmentID] [int] NOT NULL + ,[JobCodeID] [int] NOT NULL + ,[FiscalYearID] [smallint] NOT NULL + ,[FiscalMonthID] [tinyint] NOT NULL + ,Value NUMERIC(25, 6) NOT NULL + ,Type TINYINT + ,PayCodeGroupID [int] not null + ,FactorType CHAR(1) + ,DateCreated DATETIME + ,UNIQUE CLUSTERED ( + FiscalYearID + ,FiscalMonthID + ,DepartmentID + ,JobCodeID + ,EfficiencyFactorGUID + ,PayCodeGroupID + ) + ); + +WITH EfficiencyFactorScope +AS ( + SELECT * + ,rn = ROW_NUMBER() OVER ( + PARTITION BY FiscalYearID + ,FiscalMonthID + ,DepartmentID + ,JobCodeID + ,Type + ,PayCodeGroupID + ,EfficiencyFactorGUID ORDER BY FiscalYearID + ,FiscalMonthID + ,DepartmentID + ,JobCodeID + ,Type + ,PayCodeGroupID + ,EfficiencyFactorGUID + ) + FROM ( + SELECT DISTINCT ef.EfficiencyFactorGUID + ,ef.FiscalYearID + ,efgd.FiscalMonthID + ,efd.DepartmentID + ,isnull(efgd.JobCodeID, djc.JobCodeID) AS JobCodeID + ,efgd.Value + ,ef.Type + ,efgd.PayCodeGroupID + ,ef.FactorType + ,ef.DateCreated + FROM mr.EfficiencyFactor ef + INNER JOIN mr.EfficiencyFactorDepartment efd ON ef.EfficiencyFactorGUID = efd.EfficiencyFactorGUID + INNER JOIN mr.EfficiencyFactorPayrollDetails efgd ON efgd.EfficiencyFactorGUID = ef.EfficiencyFactorGUID + left JOIN fw.DimJobCode djc ON efgd.JobCodeGroupID = djc.JobCodeGroupID and efgd.JobCodeID is null + INNER JOIN (SELECT DISTINCT DepartmentID,JobCodeID FROM fw.FactPayRollSampledMonthly) scope on scope.JobCodeID = isnull(efgd.JobCodeID, djc.JobCodeID) and scope.DepartmentID = efd.DepartmentID + left JOIN mr.EfficiencyFactorPayrollDetails efgd_exist ON efgd.EfficiencyFactorGUID = efgd_exist.EfficiencyFactorGUID and efgd.PayCodeGroupID = efgd_exist.PayCodeGroupID and efgd_exist.JobCodeID = djc.JobCodeID and efgd_exist.FiscalMonthID = efgd.FiscalMonthID + WHERE (@FiscalYearID = ef.FiscalYearID or @FiscalYearID = 0) and (efgd_exist.JobCodeID is null or djc.JobCodeID is null) AND isnull(efgd.JobCodeID, djc.JobCodeID) IS NOT NULL + AND ef.Type in (2,3) --Payroll Dollars&Hours + ) X + ) +INSERT INTO #EfficiencyFactorScope ( + EfficiencyFactorGUID + ,[DepartmentID] + ,[JobCodeID] + ,[FiscalYearID] + ,[FiscalMonthID] + ,Value + ,Type + ,PayCodeGroupID + ,FactorType + ,DateCreated + ) +SELECT EfficiencyFactorGUID + ,[DepartmentID] + ,[JobCodeID] + ,[FiscalYearID] + ,[FiscalMonthID] + ,Value + ,Type + ,PayCodeGroupID + ,FactorType + ,DateCreated +FROM EfficiencyFactorScope +WHERE RN = 1 + +DELETE FROM fw.FactPayRollSampledMonthly WHERE (@FiscalYearID = FiscalYearID or @FiscalYearID = 0) and TimeClassID = 22 + +INSERT INTO fw.FactPayRollSampledMonthly (DepartmentID, +JobCodeID, +FiscalYearID, +FiscalMonthID, +TimeClassID, +PayCodeGroupID, +IsDeleted, +Hours, +Dollars) +SELECT + DepartmentID + ,JobCodeID + ,FiscalYearID + ,FiscalMonthID + ,22 as TimeClassID + ,PayCodeGroupID + ,0 as IsDeleted + ,SUM(H) as Hours + ,SUM(D) as Dollars +FROM ( +SELECT isnull(fact.DepartmentID,ToApply.DepartmentID) as DepartmentID + ,isnull(fact.JobCodeID,ToApply.JobCodeID) as JobCodeID + ,isnull(fact.FiscalYearID,ToApply.FiscalYearID) as FiscalYearID + ,isnull(fact.FiscalMonthID,ToApply.FiscalMonthID) as FiscalMonthID + ,isnull(fact.PayCodeGroupID,ToApply.PayCodeGroupID) as PayCodeGroupID + ,H = CASE WHEN Type = 3 and FactorType = 'P' THEN isnull(Hours,0.0)*isnull(Value,0.0)/100.00 + WHEN Type = 3 and FactorType = 'V' THEN isnull(Value,0.0) + ELSE 0.0 + END + ,D = CASE WHEN Type = 2 and FactorType = 'P' THEN isnull(Dollars,0.0)*isnull(Value,0.0)/100.00 + WHEN Type = 2 and FactorType = 'V' THEN isnull(Value,0.0) + ELSE 0.0 + END +FROM #EfficiencyFactorScope ToApply +INNER JOIN (SELECT DISTINCT DepartmentID,JobCodeID FROM fw.FactPayRollSampledMonthly) GenCand on + GenCand.DepartmentID = ToApply.DepartmentID + AND GenCand.JobCodeID = ToApply.JobCodeID +FULL JOIN + (select DepartmentID + ,JobCodeID + ,FiscalYearID + ,FiscalMonthID + ,PayCodeGroupID + ,Hours + ,Dollars + FROM + fw.FactPayRollSampledMonthly + + WHERE ( ( + isnull(TimeClassID,0) = 4 AND @IsFlexingEnabled = 1 + ) + OR ( isnull(TimeClassID,0) = 20 AND @IsFlexingEnabled = 0 + ) + ) + AND isnull(IsSystemGenerated,0) = 0 and (FiscalYearID = @FiscalYearID or @FiscalYearID = 0) + ) fact ON fact.DepartmentID = ToApply.DepartmentID + AND fact.JobCodeID = ToApply.JobCodeID + AND fact.FiscalYearID = ToApply.FiscalYearID + AND fact.FiscalMonthID = ToApply.FiscalMonthID + AND fact.PayCodeGroupID = ToApply.PayCodeGroupID +UNION ALL + select DepartmentID + ,JobCodeID + ,FiscalYearID + ,FiscalMonthID + ,PayCodeGroupID + ,Hours + ,Dollars + FROM + fw.FactPayRollSampledMonthly + + WHERE ( ( + isnull(TimeClassID,0) = 4 AND @IsFlexingEnabled = 1 + ) + OR ( isnull(TimeClassID,0) = 20 AND @IsFlexingEnabled = 0 + ) + ) + AND isnull(IsSystemGenerated,0) = 0 and (FiscalYearID = @FiscalYearID or @FiscalYearID = 0) +) X +GROUP BY +DepartmentID + ,JobCodeID + ,FiscalYearID + ,FiscalMonthID + ,PayCodeGroupID + +exec [fw].[procFactMonthlyYTDPriorYearUpdate] @factTableName = 'fw.FactPayRollSampledMonthly',@keyNameCSV = 'JobCodeID,PayCodeGroupID,PayCodeID',@measureNameCSV = 'Dollars,Hours',@fiscalYearID = 0,@timeClassID = 22,@isDebugOnly = 0 +exec [fw].[procFactPayrollSampledMonthlyUpdateFTEs] @fiscalYearID = @FiscalYearID, @timeClassID = 22 + +END +END +IF OBJECT_ID('tempdb..#EfficiencyFactorScope') IS NOT NULL DROP TABLE #EfficiencyFactorScope +GO + + +--------------------------------------------- + +-- fw.procPayrollSampledDailyDetailedInsert +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-02-16 GF B-14308 Created +** 2 2017-02-20 GF D-05613 Add tests for zero rows, FTEs +** 3 2017-03-06 GF B-14693 Ensure daily enabled +** 4 2017-04-04 IP TK-40663 Added test to compare general sums +** 5 2017-05-10 IP D-05913 Added testcase from rolling baseline target values +** 6 2017-06-07 IP Commented out baseline test +** 7 2017-06-15 IP B-15086 Modify SP to use unique temp table +** 8 2017-06-19 IP Modify SP to use unique temp table procPayrollSampledDailyDetailedInsert +** 9 2017-06-23 IP Fixed issue with transaction log out of memory procPayrollSampledDailyDetailedInsert +** 10 2017-09-08 IP Adding Budget Adjustments to fw_procPayrollSampledDailyDetailedInsert +** 11 2017-09-23 IP Adding Budget Adjustments to fw_procPayrollSampledDailyDetailedInsert +** 12 2018-02-15 IP Add react to archived FTE Adjutments in fw_procPayrollSampledDailyDetailedInsert +** 13 2018-02-22 IP D-06786 add department calculation for TC = 2 if dept is not in PR , Dept is in Budget Allocation +** 14 2018-03-08 ip B-18793 PR - Daily processing post action 2 week run +** 15 2018-05-17 IP D-07329 Returning fuctionality to include stats for departments using non-PR driver departments +** 16 2018-05-21 KF D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values +** 17 2018-05-17 IP TK-58509 reverting functionality of ignoring 0s +** 18 2018-05-17 IP TK-58523 reaplying changes for D-06786 +** 19 2018-08-27 OV D-07628 Fixed issu: PR Payroll Files Not Displaying in Data Sets +** 20 2018-08-28 IP D-07628 Fixed issu: PR Payroll Files Not Displaying in Data Sets (add ignoring @fiscalYearID if @isCalcDaily is set) +** 21 2018-09-11 kzhuk D-07649 PR Daily custom action calls procedures for wrong year +** 22 2018-10-05 OV D-07728 fix: PR Payroll Daily Sampling: isPR=0 departments and Job Codes are not filtered out during sampling for one year +** 23 2019-02-25 OV D-07697 fix: Daily custom action: FTEs are not calculated in case there was no data in the table before +** 24 2019-03-05 OV D-08020 table variables @departments converted to temp tables #departmentIDs +** 25 2019-03-29 OV D-07650 Payroll data are sampled for all Pay Period including after yesterday +** 26 2019-04-18 OV B-20571 Allow clients to input daily budget Payroll data +** 27 2019-04-23 OV B-20571 Take Dollars and Hours separately from different tables as Value, grouped by IDs and UnitType in the end +** 28 2019-05-14 OV B-22955 Filtered procedure by new 'isDaily' column from DimJobCode +** 29 2019-07-24 OV D-08629 FTEs are set to 0 for first Pay Period days belonging to previous year +** 30 2019-10-15 WR D-08686 Run PR Process Task is filling transaction log +** 31 2019-11-25 IH TK-80619 Rollback transaction log changes +** 32 2020-01-08 HV B-25788 procPayrollSampledDailyInsert DBA Enhancements +** 33 2021-12-10 HV JAZZ-23990 procPayrollSampledDailyDetailedInsert Filling Up Temp DB +** 34 2021-12-16 HV JAZZ-23990 procPayrollSampledDailyDetailedInsert Filling Up Temp DB +** 35 2022-01-20 HV JAZZ-32256 PR Department Productivity Daily Page Performance Improvements +** 36 2022-02-15 HV JAZZ-33795 PR Department Productivity Daily Page: Compress view index +** 37 2022-03-21 HV JAZZ-31812 PR - Daily budget hours doubled in certain pay periods + JAZZ-22706 Year Changeover In Daily Staffing is inflating Prior Year Days from Transfer Proc Update +** 38 2022-10-27 ishah JAZZ-45100 Reuse split by batches functionality in existing procedure +** 39 2022-11-22 HV JAZZ-44508 Automated Daily PR processing doesn't calculate future target, when system center processing does +** 40 2023-10-09 HV JAZZ-61830 PR - Index and department filter changes - fw.procPayrollSampledDailyDetailedInsert and client.procFactPayrollSampledDailyDetailedFTEsInsert_Staging +** 41 2023-11-09 BS JAZZ-62716 PR -Transaction Log is filled out: fw.procPayrollSampledDailyDetailedInsert and client.procFactPayrollSampledDailyDetailedFTEsInsert_Staging (insert by batches) +** 42 2024-06-14 SM JAZZ-71536 change JobCodeID from smallint to int +*************************************************************/ +CREATE proc [fw].[procPayrollSampledDailyDetailedInsert] + @fiscalYearID int = 0, + @isCalcDaily bit = 0, + @isFeatureFlagOn bit = 0 +with recompile +as + declare @yearOfSampling int = [fw].[GetPayPeriodSamplingYear] (@fiscalYearID, @isCalcDaily) + + DECLARE @currentDateOverride nvarchar(max) = (SELECT Value FROM [pi].[SystemSetting] WHERE Name = 'Current Date Override') + DECLARE @currentDate date = CASE + WHEN @currentDateOverride = '' THEN CAST(GETDATE() AS DATE) + ELSE CAST (@currentDateOverride AS DATE) + END + DECLARE @yesterday_date date = DATEADD(DAY, - 1, @currentDate) + + IF OBJECT_ID('tempdb..#PayrollSampledDailyDetailedStaging') IS NOT NULL DROP TABLE #PayrollSampledDailyDetailedStaging + declare @IterationFiscalYearID int + + IF OBJECT_ID('tempdb..#departmentsBudgetAllocations') IS NOT NULL DROP TABLE #departmentsBudgetAllocations + create table #departmentsBudgetAllocations (val int primary key) + insert into #departmentsBudgetAllocations (val) + select + SourceDepartmentID as DepartmentID + from mr.BudgetReallocationAdjustment a + inner join mr.BudgetReallocation r on r.BudgetReallocationGUID=a.BudgetReallocationGUID + inner join FW.DimDepartment d on d.DepartmentID = r.TargetDepartmentID and d.IsPR = 1 + where SourceDepartmentID <> 0 + union -- unique + select + TargetDepartmentID as DepartmentID + from mr.BudgetReallocationAdjustment a + inner join mr.BudgetReallocation r on r.BudgetReallocationGUID=a.BudgetReallocationGUID + inner join FW.DimDepartment d on d.DepartmentID = r.SourceDepartmentID and d.IsPR = 1 -- Filtering all departments that move data FROM selected + where TargetDepartmentID <> 0 + + IF OBJECT_ID('tempdb..#DailyCalcPeriodsScope') IS NOT NULL DROP TABLE #DailyCalcPeriodsScope + + select PayPeriodID,PayCycleID,PeriodStartCalendarDate,PeriodEndCalendarDate into #DailyCalcPeriodsScope + from fw.DimPayPeriod + where + (@isCalcDaily = 1 and @yesterday_date BETWEEN PeriodStartCalendarDate and PeriodEndCalendarDate) -- if @isCalcDaily = 1 is present we ignore what @yearOfSampling is passed to stored procedure (based on B-18793) + or + (@isCalcDaily = 0 AND (@fiscalYearID = FiscalYearIDSecond or @fiscalYearID = 0)) -- if @isCalcDaily = 0 we should react to what @fiscalYearID is set + + --cancel if not using daily + if (not exists(select 1 from pi.SystemSetting where Name = 'PR Daily Enabled' and Value = '1')) begin return end + + --pull new data - actuals + create table #PayrollSampledDailyDetailedStaging (DepartmentID int, JobCodeID int, PayCodeID int, PayCodeGroupID int, EmployeeID int, PayPeriodID int, DateID int, TimeClassID int, Hours decimal(18,4), Dollars decimal(18,4), FTEs decimal(18,4)) + + -- Split by batches + DECLARE @batchSize INT + + EXEC mr.procGetIntBatchSize + @DefaultBatchSize = 120000000, + @ResultBatchSize = @batchSize OUTPUT + + IF OBJECT_ID('tempdb..#inputDepartments') IS NOT NULL DROP TABLE #inputDepartments + CREATE TABLE #inputDepartments (DepartmentID INT, RecordsCount INT, BatchID INT) + + DECLARE + @fromClause nvarchar(max) = ' + ( + select + data.DepartmentID, + data.JobCodeID, + data.PayCodeID, + pc.PayCodeGroupID, + data.EmployeeID, + pp.PayPeriodID, + data.DateID, + data.TimeClassID, + sum(case when data.UnitTypeID = 51 and pc.IsHoursIgnored = 0 then data.Value else 0 end) as Hours, + sum(case when data.UnitTypeID = 34 and pc.IsDollarsIgnored = 0 then data.Value else 0 end) as Dollars, + 0 AS FTEs + from + int.FactStaffingDaily data + inner join [fw].[DimPayCode] pc on data.PayCodeID = pc.PayCodeID + inner join fw.DimDepartment d on d.DepartmentID = data.DepartmentID + inner join fw.DimDate dt on dt.DateID = data.DateID + inner join fw.DimPayPeriod pp on pp.PayCycleID = d.PayCycleID and dt.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate + inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID + where + pp.PayPeriodID != 0 + and data.IsDeleted = 0 + and data.Value != 0 + and d.IsPR = 1 + and TimeClassID = 1 + group by + data.DepartmentID, + data.JobCodeID, + data.PayCodeID, + pc.PayCodeGroupID, + data.EmployeeID, + pp.PayPeriodID, + data.DateID, + data.TimeClassID) X' + + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'X', + @fromClause = @fromClause, + @whereClause = '', + @isDebug = 0 + + DECLARE @BatchID INT, @MaxBatchID INT + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + -- Loop thru batches and insert data + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + insert into #PayrollSampledDailyDetailedStaging (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, DateID, TimeClassID, Hours, Dollars, FTEs) + select + data.DepartmentID, + data.JobCodeID, + data.PayCodeID, + pc.PayCodeGroupID, + data.EmployeeID, + pp.PayPeriodID, + data.DateID, + data.TimeClassID, + sum(case when data.UnitTypeID = 51 and pc.IsHoursIgnored = 0 then data.Value else 0 end) as Hours, + sum(case when data.UnitTypeID = 34 and pc.IsDollarsIgnored = 0 then data.Value else 0 end) as Dollars, + 0 AS FTEs + from + int.FactStaffingDaily data + inner join [fw].[DimPayCode] pc on data.PayCodeID = pc.PayCodeID + inner join fw.DimDepartment d on d.DepartmentID = data.DepartmentID + inner join fw.DimDate dt on dt.DateID = data.DateID + inner join fw.DimPayPeriod pp on pp.PayCycleID = d.PayCycleID and dt.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate + inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID + inner join #inputDepartments ID ON ID.DepartmentID = data.DepartmentID + where + pp.PayPeriodID != 0 + and data.IsDeleted = 0 + and data.Value != 0 + and d.IsPR = 1 + and TimeClassID = 1 + and ID.BatchID = @BatchID +-- and (@fiscalYearID = 0 or dt.FiscalYear = @fiscalYearID) -- #DailyCalcPeriodsScope already contains all Pay Periods that should be recalculated, so filtering by year could bring destructive effect in case @fisclaYearID <> 'calendar year' (conflict @FiscalYearID and @isCalcDaily) + group by + data.DepartmentID, + data.JobCodeID, + data.PayCodeID, + pc.PayCodeGroupID, + data.EmployeeID, + pp.PayPeriodID, + data.DateID, + data.TimeClassID + + SET @BatchID = @BatchID + 1 + END + --pull new data - budget from daily, payperiod, monthly data + IF OBJECT_ID('tempdb..#StaffingDaily') IS NOT NULL DROP TABLE #StaffingDaily + CREATE TABLE #StaffingDaily ( + DepartmentID INT, + JobCodeID int, + PayCodeID SMALLINT, + PayCodeGroupID INT, + DateID INT, + TimeClassID TINYINT, + PayPeriodID SMALLINT, + UnitTypeID TINYINT, + IsHoursIgnored BIT, + IsDollarsIgnored BIT, + Value DECIMAL(19,4)) + + -- Split by batches + TRUNCATE TABLE #inputDepartments + + SET @fromClause = ' + ( + SELECT + FACT.DepartmentID, + FACT.JobCodeID, + FACT.PayCodeID, + PC.PayCodeGroupID, + DT.DateID, + FACT.TimeClassID, + PP.PayPeriodID, + FACT.UnitTypeID, + pc.IsHoursIgnored, + pc.IsDollarsIgnored + FROM int.FactStaffingDaily FACT + inner join [fw].[DimPayCode] PC on PC.PayCodeID = FACT.PayCodeID + inner join [fw].[DimDepartment] D on D.Departmentid = FACT.DepartmentID + inner join [fw].[DimDate] DT on DT.DateID = FACT.dateID + inner join fw.dimpayPeriod PP on pp.PayCycleID = d.PayCycleID and dt.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate + inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID + left join #departmentsBudgetAllocations dba on dba.val = d.DepartmentID + + where + DT.FiscalMonth != 0 + and FACT.FiscalYearID != 0 + and FACT.IsDeleted = 0 + and (D.IsPR = 1 or dba.val IS NOT NULL) + and FACT.TimeClassID = 2 + and FACT.DepartmentID != 0 + group by + FACT.DepartmentID, + FACT.JobCodeID, + FACT.PayCodeID, + PC.PayCodeGroupID, + DT.DateID, + FACT.TimeClassID, + PP.PayPeriodID, + FACT.UnitTypeID, + pc.IsHoursIgnored, + pc.IsDollarsIgnored) X' + + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'X', + @fromClause = @fromClause, + @whereClause = '', + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + -- Loop thru batches and insert data + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + insert into #StaffingDaily(DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, DateID, TimeClassID, PayPeriodID, UnitTypeID, IsHoursIgnored, IsDollarsIgnored, Value) + select + FACT.DepartmentID, + FACT.JobCodeID, + FACT.PayCodeID, + PC.PayCodeGroupID, + DT.DateID, + FACT.TimeClassID, + PP.PayPeriodID, + FACT.UnitTypeID, + pc.IsHoursIgnored, + pc.IsDollarsIgnored, + sum(FACT.Value) AS Value + from + int.FactStaffingDaily FACT + inner join [fw].[DimPayCode] PC on PC.PayCodeID = FACT.PayCodeID + inner join [fw].[DimDepartment] D on D.Departmentid = FACT.DepartmentID + inner join [fw].[DimDate] DT on DT.DateID = FACT.dateID + inner join fw.dimpayPeriod PP on pp.PayCycleID = d.PayCycleID and dt.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate + inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID + inner join #inputDepartments ID ON ID.DepartmentID = FACT.DepartmentID + left join #departmentsBudgetAllocations dba on dba.val = d.DepartmentID + + where + DT.FiscalMonth != 0 + and FACT.FiscalYearID != 0 + and FACT.IsDeleted = 0 + and (D.IsPR = 1 or dba.val IS NOT NULL) + and FACT.TimeClassID = 2 + and FACT.DepartmentID != 0 + and ID.BatchID = @BatchID + + group by + FACT.DepartmentID, + FACT.JobCodeID, + FACT.PayCodeID, + PC.PayCodeGroupID, + DT.DateID, + FACT.TimeClassID, + PP.PayPeriodID, + FACT.UnitTypeID, + pc.IsHoursIgnored, + pc.IsDollarsIgnored + + SET @BatchID = @BatchID + 1 + END +------------------------------------------------------------------------------------------------------------------------------------- +-- Split by batches + + TRUNCATE TABLE #inputDepartments + + SET @fromClause = ' + ( + SELECT + FACT.DepartmentID, + FACT.JobCodeID, + FACT.PayCodeID, + PC.PayCodeGroupID, + DT.DateID, + FACT.TimeClassID, + PP.PayPeriodID, + FACT.UnitTypeID, + pc.IsHoursIgnored, + pc.IsDollarsIgnored + FROM int.FactStaffingByPayPeriod FACT + inner join [fw].[DimPayCode] PC on PC.PayCodeID = FACT.PayCodeID + inner join [fw].[DimDepartment] D on D.Departmentid = FACT.DepartmentID + inner join fw.DimPayPeriod pp on pp.PayPeriodID = FACT.PayPeriodID + inner join [fw].[DimDate] DT on dt.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate + left join #StaffingDaily spp on SPP.PayPeriodID = FACT.PayPeriodID and + SPP.DepartmentID = FACT.DepartmentID and + SPP.JobCodeID = FACT.JobCodeID and + SPP.PayCodeID = FACT.PayCodeID and + SPP.TimeClassID = FACT.TimeClassID and + SPP.UnitTypeID = FACT.UnitTypeID + inner join fw.DimPayCycle PCC on PCC.PayCycleID = PP.PayCycleID + inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID + left join #departmentsBudgetAllocations dba on dba.val = d.DepartmentID + where + spp.DepartmentID IS NULL + and DT.FiscalMonth != 0 + and FACT.FiscalYearID != 0 + and FACT.IsDeleted = 0 + and (D.IsPR = 1 or dba.val IS NOT NULL) + and FACT.TimeClassID = 2 + and FACT.DepartmentID != 0 + group by + FACT.DepartmentID, + FACT.JobCodeID, + FACT.PayCodeID, + PC.PayCodeGroupID, + DT.DateID, + FACT.TimeClassID, + PP.PayPeriodID, + FACT.UnitTypeID, + pc.IsHoursIgnored, + pc.IsDollarsIgnored ) X' + + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'X', + @fromClause = @fromClause, + @whereClause = '', + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + -- Loop thru batches and insert data + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + insert into #StaffingDaily(DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, DateID, TimeClassID, PayPeriodID, UnitTypeID, IsHoursIgnored, IsDollarsIgnored, Value) + select + FACT.DepartmentID, + FACT.JobCodeID, + FACT.PayCodeID, + PC.PayCodeGroupID, + DT.DateID, + FACT.TimeClassID, + PP.PayPeriodID, + FACT.UnitTypeID, + pc.IsHoursIgnored, + pc.IsDollarsIgnored, + sum(FACT.Value/PCC.PeriodDays) AS Value + from + int.FactStaffingByPayPeriod FACT + inner join [fw].[DimPayCode] PC on PC.PayCodeID = FACT.PayCodeID + inner join [fw].[DimDepartment] D on D.Departmentid = FACT.DepartmentID + inner join fw.DimPayPeriod pp on pp.PayPeriodID = FACT.PayPeriodID + inner join [fw].[DimDate] DT on dt.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate + left join #StaffingDaily spp on SPP.PayPeriodID = FACT.PayPeriodID and + SPP.DepartmentID = FACT.DepartmentID and + SPP.JobCodeID = FACT.JobCodeID and + SPP.PayCodeID = FACT.PayCodeID and + SPP.TimeClassID = FACT.TimeClassID and + SPP.UnitTypeID = FACT.UnitTypeID + inner join fw.DimPayCycle PCC on PCC.PayCycleID = PP.PayCycleID + inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID + left join #departmentsBudgetAllocations dba on dba.val = d.DepartmentID + inner join #inputDepartments ID ON ID.DepartmentID = FACT.DepartmentID + where + spp.DepartmentID IS NULL + and DT.FiscalMonth != 0 + and FACT.FiscalYearID != 0 + and FACT.IsDeleted = 0 + and (D.IsPR = 1 or dba.val IS NOT NULL) + and FACT.TimeClassID = 2 + and FACT.DepartmentID != 0 + and ID.BatchID = @BatchID + group by + FACT.DepartmentID, + FACT.JobCodeID, + FACT.PayCodeID, + PC.PayCodeGroupID, + DT.DateID, + FACT.TimeClassID, + PP.PayPeriodID, + FACT.UnitTypeID, + pc.IsHoursIgnored, + pc.IsDollarsIgnored + + SET @BatchID = @BatchID + 1 + END +-------------------------------------------------------------------------------------------------------------------- +TRUNCATE TABLE #inputDepartments + + SET @fromClause = ' + int.FactStaffing FACT + INNER JOIN fw.DimDepartment d ON d.DepartmentID = FACT.DepartmentID' + + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'FACT', + @fromClause = @fromClause, + @whereClause = '', + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + -- Loop thru batches and insert data + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + insert into #StaffingDaily(DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, DateID, TimeClassID, PayPeriodID, UnitTypeID, IsHoursIgnored, IsDollarsIgnored, Value) + select + FACT.DepartmentID, + FACT.JobCodeID, + FACT.PayCodeID, + PC.PayCodeGroupID, + DT.DateID, + FACT.TimeClassID, + PP.PayPeriodID, + FACT.UnitTypeID, + pc.IsHoursIgnored, + pc.IsDollarsIgnored, + sum(FACT.Value/ dbo.GetDaysInMonth(DT.CalendarDateTime)) as Value + from + [int].[FactStaffing] FACT + inner join [fw].[DimPayCode] PC on PC.PayCodeID = FACT.PayCodeID + inner join [fw].[DimDepartment] D on D.Departmentid = FACT.DepartmentID + inner join [fw].[DimDate] DT on DT.CalendarMonth = FACT.FiscalMonthID and DT.FiscalYear = FACT.FiscalYearID + inner join fw.DimPayperiod pp on pp.PayCycleID = d.PayCycleID and dt.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate + left join #StaffingDaily spp on SPP.PayPeriodID = PP.PayPeriodID and + SPP.DepartmentID = FACT.DepartmentID and + SPP.JobCodeID = FACT.JobCodeID and + SPP.PayCodeID = FACT.PayCodeID and + SPP.TimeClassID = FACT.TimeClassID and + SPP.UnitTypeID = FACT.UnitTypeID + inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID + left join #departmentsBudgetAllocations dba on dba.val = d.DepartmentID + inner join #inputDepartments ID ON ID.DepartmentID = FACT.DepartmentID + where + spp.DepartmentID is null + and FACT.FiscalMonthID != 0 + and FACT.FiscalYearID != 0 + and FACT.IsDeleted = 0 + and (D.IsPR = 1 or dba.val IS NOT NULL) + and FACT.TimeClassID = 2 + and FACT.DepartmentID != 0 + and ID.BatchID = @BatchID + group by + FACT.DepartmentID, + FACT.JobCodeID, + FACT.PayCodeID, + PC.PayCodeGroupID, + DT.DateID, + FACT.TimeClassID, + PP.PayPeriodID, + FACT.UnitTypeID, + pc.IsHoursIgnored, + pc.IsDollarsIgnored + + SET @BatchID = @BatchID + 1 + END + + + TRUNCATE TABLE #inputDepartments + + SET @fromClause = ' + (SELECT G.DepartmentID, G.JobCodeID, G.PayCodeID, G.PayCodeGroupID, G.PayPeriodID, G.DateID, G.TimeClassID FROM #StaffingDaily G + INNER JOIN fw.DimJobCode jc on G.jobCodeID = jc.JobCodeID + WHERE jc.IsPR = 1 and jc.IsDaily = 1 + GROUP BY G.DepartmentID, G.JobCodeID, G.PayCodeID, G.PayCodeGroupID, G.PayPeriodID, G.DateID, G.TimeClassID) X' + + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'X', + @fromClause = @fromClause, + @whereClause = '', + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + -- Loop thru batches and insert data + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + insert into #PayrollSampledDailyDetailedStaging (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, DateID, TimeClassID, Hours, Dollars, FTEs) + select G.DepartmentID, G.JobCodeID, G.PayCodeID, G.PayCodeGroupID, 0 as EmployeeID, G.PayPeriodID, G.DateID, G.TimeClassID, + SUM(case when G.UnitTypeID = 51 and G.IsHoursIgnored = 0 then G.Value else 0 end) as Hours, + SUM(case when G.UnitTypeID = 34 and G.IsDollarsIgnored = 0 then G.Value else 0 end) as Dollars, + 0 + from #StaffingDaily G + inner join #inputDepartments ID ON ID.DepartmentID = G.DepartmentID + inner join fw.DimJobCode jc on G.jobCodeID = jc.JobCodeID + WHERE jc.IsPR = 1 and jc.IsDaily = 1 and ID.BatchID = @BatchID + GROUP BY G.DepartmentID, G.JobCodeID, G.PayCodeID, G.PayCodeGroupID, G.PayPeriodID, G.DateID, G.TimeClassID + + SET @BatchID = @BatchID + 1 + END + + /*Budget adjustments FTE start*/ + --pull new data - adjustments + DECLARE @NonProdGroupID INT = ( + SELECT TOP 1 pcg.PayCodeGroupID + FROM fw.DimProductiveClass pc + INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID + WHERE pc.Name = 'Non-Productive' AND pcg.PayCodeGroupID != 0 + ORDER BY pcg.SortOrder) + + DECLARE @ProdGroupID INT = ( + SELECT TOP 1 pcg.PayCodeGroupID + FROM fw.DimProductiveClass pc + INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID + WHERE pc.Name = 'Productive' AND pcg.PayCodeGroupID != 0 + ORDER BY pcg.SortOrder) + + DECLARE @NonProdPayCodeID INT = ( + SELECT TOP 1 pcg.DefaultPayCodeID + FROM fw.DimProductiveClass pc + INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID + WHERE pc.Name = 'Non-Productive' AND pcg.PayCodeGroupID != 0 + ORDER BY pcg.SortOrder) + + DECLARE @ProdPayCodeID INT = ( + SELECT TOP 1 pcg.DefaultPayCodeID + FROM fw.DimProductiveClass pc + INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID + WHERE pc.Name = 'Productive' AND pcg.PayCodeGroupID != 0 + ORDER BY pcg.SortOrder) + + insert into #PayrollSampledDailyDetailedStaging (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, DateID, TimeClassID, Hours, Dollars) + SELECT + Adj.DepartmentID, + Adj.JobCodeID, + Adj.PayCodeId, + Adj.PayCodeGroupID, + 0 as EmployeeID, + PP.PayPeriodID, + dt.DateID, + 2 AS TimeClassID, -- always Budgeted + sum(Adj.Hours / dbo.GetDaysInMonth(DT.CalendarDateTime)) AS Hours, + 0 AS Dollars + FROM ( + SELECT + b.DepartmentID, + b.JobCodeID, + @ProdPayCodeID as PayCodeID, + @ProdGroupID AS PayCodeGroupID, + b.FiscalYearID, + ba.FiscalMonthID, + ba.ProductiveChange AS Hours + FROM mr.BudgetPayrollReallocationAdjustment ba + INNER JOIN mr.BudgetPayrollReallocation b ON b.BudgetPayrollReallocationGUID = ba.BudgetPayrollReallocationGUID + LEFT JOIN + (select SourceDepartmentID as DepartmentID, + SourceJobCodeID as JobCodeID, + FiscalYearID, + FiscalMonthID + FROM [mr].[BudgetReallocation] b + INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + WHERE DataType = 1 + UNION ALL + select TargetDepartmentID as DepartmentID, + TargetJobCodeID as JobCodeID, + FiscalYearID, + FiscalMonthID + FROM [mr].[BudgetReallocation] b + INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + WHERE DataType = 1 + ) fact on fact.DepartmentID = b.DepartmentID and fact.JobCodeID = b.JobCodeID and fact.FiscalYearID = b.FiscalYearID and fact.FiscalMonthID = ba.FiscalMonthID + WHERE (@yearOfSampling = 0 or b.FiscalYearID = @yearOfSampling) -- if @isCalcDaily = 1 we'll take calndar year, else - @FiscalYearId + and fact.DepartmentID is null and b.Archived = 0 + UNION ALL + SELECT b.DepartmentID, + b.JobCodeID, + @NonProdPayCodeID as PayCodeID, + @NonProdGroupID AS PayCodeGroupID, + b.FiscalYearID, + ba.FiscalMonthID, + ba.NonProductiveChange AS Hours + FROM mr.BudgetPayrollReallocationAdjustment ba + INNER JOIN mr.BudgetPayrollReallocation b ON b.BudgetPayrollReallocationGUID = ba.BudgetPayrollReallocationGUID + LEFT JOIN + (select SourceDepartmentID as DepartmentID, + SourceJobCodeID as JobCodeID, + FiscalYearID, + FiscalMonthID + FROM [mr].[BudgetReallocation] b + INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + WHERE DataType = 1 + UNION ALL + select TargetDepartmentID as DepartmentID, + TargetJobCodeID as JobCodeID, + FiscalYearID, + FiscalMonthID + FROM [mr].[BudgetReallocation] b + INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + WHERE DataType = 1 + ) fact on fact.DepartmentID = b.DepartmentID and fact.JobCodeID = b.JobCodeID and fact.FiscalYearID = b.FiscalYearID and fact.FiscalMonthID = ba.FiscalMonthID + WHERE (@yearOfSampling = 0 or b.FiscalYearID = @yearOfSampling) -- if @isCalcDaily = 1 we'll take calndar year, else - @FiscalYearId + and fact.DepartmentID is null and b.Archived = 0 + ) AS Adj + INNER JOIN fw.DimDepartment dd on adj.DepartmentID = dd.DepartmentID + INNER JOIN ( + SELECT + p.[PayPeriodID], + p.PayCycleID, + p.[PeriodNumber], + p.[FiscalMonthIDStart] AS FiscalMonthID, + p.[FiscalYearIDStart] AS FiscalYearID, + p.[PeriodWeightStart] AS PreriodWeight, + p.PeriodStartCalendarDate, + p.PeriodEndCalendarDate + FROM [fw].[DimPayPeriod] p inner join #DailyCalcPeriodsScope cp on cp.PayPeriodID = p.PayPeriodID + UNION ALL + SELECT + p.[PayPeriodID], + p.PayCycleID, + p.[PeriodNumber], + p.FiscalMonthIDSecond AS FiscalMonthID, + p.FiscalYearIDSecond AS FiscalYearID, + p.PeriodWeightSecond AS PreriodWeight, + p.PeriodStartCalendarDate, + p.PeriodEndCalendarDate + FROM [fw].[DimPayPeriod] p inner join #DailyCalcPeriodsScope cp on cp.PayPeriodID = p.PayPeriodID + ) PP ON PP.FiscalYearID = Adj.FiscalYearID + AND pp.FiscalMonthID = adj.FiscalMonthID + and pp.PayCycleID = dd.PayCycleID + inner join [fw].[DimDate] DT on DT.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate and dt.FiscalYear = pp.FiscalYearID + inner join #DailyCalcPeriodsScope dpc on dpc.PayPeriodID = pp.PayPeriodID + WHERE PP.PreriodWeight <> 0 + GROUP BY Adj.DepartmentID, + Adj.JobCodeID, + dt.dateID, + Adj.PayCodeID, + Adj.PayCodeGroupID, + PP.PayPeriodID + HAVING sum(Adj.Hours * PP.PreriodWeight) <> 0 + + + /*Budget adjustments FTE end*/ + + -- BudgetAdjustments Start + declare @iteration int = 1 + DECLARE @BudgetReallocationGUID uniqueidentifier,@date datetime,@BudgetReallocationType varchar(50) + + DECLARE BRA_cursor CURSOR FOR + SELECT distinct BudgetReallocationGUID,date,BudgetReallocationType from fw.BudgetReallocationWithDefinedType + WHERE (@yearOfSampling = 0 or FiscalYearID = @yearOfSampling) -- if @isCalcDaily = 1 we'll take calndar year, else - @FiscalYearId + and DataType = 1 + ORDER BY date; + + OPEN BRA_cursor + + FETCH NEXT FROM BRA_cursor + INTO @BudgetReallocationGUID,@date,@BudgetReallocationType + + WHILE @@FETCH_STATUS = 0 + BEGIN + BEGIN + INSERT INTO #PayrollSampledDailyDetailedStaging (DepartmentID, JobCodeID, EmployeeID, PayPeriodID, PayCodeID, PayCodeGroupID, DateID, TimeClassID, Hours, Dollars, FTEs) + SELECT TargetDepartmentID as DepartmentID,TargetJobCodeID as JobCodeID, stt.EmployeeID, PayPeriodID, stt.PayCodeID, stt.PayCodeGroupID, stt.DateID, stt.TimeClassID, stt.Hours, stt.Dollars, stt.FTEs + FROM #PayrollSampledDailyDetailedStaging STT + INNER JOIN fw.DimDate dt on dt.DateID = stt.DateID + INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceJobCodeID = stt.JobCodeID and b.FiscalYearID = dt.FiscalYear + INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and dt.CalendarMonth = ba.FiscalMonthID + where + b.BudgetReallocationGUID = @BudgetReallocationGUID + and TimeClassID = 2 + and DataType = 1 + + + UPDATE STT + SET Dollars = 0, + Hours = 0, + FTEs = 0 + FROM #PayrollSampledDailyDetailedStaging STT + INNER JOIN fw.DimDate dt on dt.DateID = stt.DateID + INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceJobCodeID = stt.JobCodeID and b.FiscalYearID = dt.FiscalYear + INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and dt.CalendarMonth = ba.FiscalMonthID + where + b.BudgetReallocationGUID = @BudgetReallocationGUID + and TimeClassID = 2 + and DataType = 1 + END + + set @iteration = @iteration +1 + + FETCH NEXT FROM BRA_cursor + INTO @BudgetReallocationGUID,@date,@BudgetReallocationType + END + CLOSE BRA_cursor; + DEALLOCATE BRA_cursor; + -- BudgetAdjustments END + + --calculate baseline target + declare @targetType int = (select Value from pi.SystemSetting where Name = 'Target Basis') + if (@targetType = 2) begin + --baseline target is based on budget, pull from monthly data + TRUNCATE TABLE #inputDepartments + + SET @fromClause = ' + #PayrollSampledDailyDetailedStaging X + WHERE X.TimeClassID = 2' + + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'X', + @fromClause = @fromClause, + @whereClause = '', + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + -- Loop thru batches and insert data + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + insert into #PayrollSampledDailyDetailedStaging (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, DateID, TimeClassID, Hours, Dollars, FTEs) + select PS.DepartmentID, PS.JobCodeID, PS.PayCodeID, PS.PayCodeGroupID, PS.EmployeeID, PS.PayPeriodID, PS.DateID, 20, PS.Hours, PS.Dollars, PS.FTEs + from #PayrollSampledDailyDetailedStaging PS + inner join #inputDepartments ID ON ID.DepartmentID = PS.DepartmentID + where PS.TimeClassID = 2 and ID.BatchID = @BatchID + + SET @BatchID = @BatchID + 1 + END + end else if(@targetType = 10) begin + --baseline target is based on rolling period average, pull from pay period data + + TRUNCATE TABLE #inputDepartments + + SET @fromClause = ' + ( + select + FACT.DepartmentID, + FACT.JobCodeID, + FACT.PayCodeID, + FACT.PayCodeGroupID, + FACT.EmployeeID, + FACT.PayPeriodID, + DT.DateID, + FACT.TimeClassID, + SUM(FACT.Hours) as Hours, + SUM(FACT.Dollars) as Dollars + from + fw.FactPayrollSampledPayPeriodDetailed FACT + inner join [fw].[DimPayPeriod] PP on PP.PayPeriodID = FACT.PayPeriodID + inner join [fw].[DimDate] DT on DT.CalendarDateTime between PP.PeriodStartCalendarDate and PP.PeriodEndCalendarDate + inner join [fw].[DimDepartment] D on D.DepartmentID = FACT.DepartmentID + inner join #DailyCalcPeriodsScope dpc on FACT.PayPeriodID = dpc.PayPeriodID + where + FACT.PayPeriodID != 0 + and FACT.IsDeleted = 0 + and (FACT.Hours != 0 or FACT.Dollars != 0) + and D.IsPR = 1 + and FACT.TimeClassID = 20 + and FACT.DepartmentID <> 0 + --and (@fiscalYearID = 0 or DT.FiscalYear = @fiscalYearID) + group by + FACT.DepartmentID, + FACT.JobCodeID, + FACT.PayCodeID, + FACT.PayCodeGroupID, + FACT.EmployeeID, + FACT.PayPeriodID, + DT.DateID, + FACT.TimeClassID) X' + + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'X', + @fromClause = @fromClause, + @whereClause = '', + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + -- Loop thru batches and insert data + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + ;with groupedBaselineTargetPayroll as( + select + FACT.DepartmentID, + FACT.JobCodeID, + FACT.PayCodeID, + FACT.PayCodeGroupID, + FACT.EmployeeID, + FACT.PayPeriodID, + DT.DateID, + FACT.TimeClassID, + SUM(FACT.Hours) as Hours, + SUM(FACT.Dollars) as Dollars + from + fw.FactPayrollSampledPayPeriodDetailed FACT + inner join [fw].[DimPayPeriod] PP on PP.PayPeriodID = FACT.PayPeriodID + inner join [fw].[DimDate] DT on DT.CalendarDateTime between PP.PeriodStartCalendarDate and PP.PeriodEndCalendarDate + inner join [fw].[DimDepartment] D on D.DepartmentID = FACT.DepartmentID + inner join #DailyCalcPeriodsScope dpc on FACT.PayPeriodID = dpc.PayPeriodID + where + FACT.PayPeriodID != 0 + and FACT.IsDeleted = 0 + and (FACT.Hours != 0 or FACT.Dollars != 0) + and D.IsPR = 1 + and FACT.TimeClassID = 20 + and FACT.DepartmentID <> 0 + --and (@fiscalYearID = 0 or DT.FiscalYear = @fiscalYearID) + group by + FACT.DepartmentID, + FACT.JobCodeID, + FACT.PayCodeID, + FACT.PayCodeGroupID, + FACT.EmployeeID, + FACT.PayPeriodID, + DT.DateID, + FACT.TimeClassID) + insert into #PayrollSampledDailyDetailedStaging (DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, DateID, TimeClassID, Hours, Dollars, FTEs) + select G.DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, EmployeeID, G.PayPeriodID, DateID, TimeClassID, Hours / PP.PeriodDays, Dollars / PP.PeriodDays, 0 + from groupedBaselineTargetPayroll G + inner join fw.DimPayPeriod PP on PP.PayPeriodID = G.PayPeriodID + inner join #inputDepartments ID ON ID.DepartmentID = G.DepartmentID + where ID.BatchID = @BatchID + + SET @BatchID = @BatchID + 1 + END + end + + --calculate FTEs + + IF @fiscalYearID = 0 and @isCalcDaily = 0 and @isFeatureFlagOn = 1 + BEGIN + IF OBJECT_ID('tempdb..#PayrollSampledDailyDetailedFTEs') IS NOT NULL DROP TABLE #PayrollSampledDailyDetailedFTEs + create table #PayrollSampledDailyDetailedFTEs (DepartmentID int, JobCodeID int, PayCodeID int, PayCodeGroupID int, EmployeeID int, PayPeriodID int, DateID int, TimeClassID int, FTEs decimal(18,4)) + exec client.procFactPayrollSampledDailyDetailedFTEsInsert_Staging @fiscalYearID = @yearOfSampling, @isFeatureFlagOn = @isFeatureFlagOn + END + ELSE + BEGIN + exec client.procFactPayrollSampledDailyDetailedFTEsInsert_Staging @fiscalYearID = @yearOfSampling + END + + --!!!Removing all records where Department is not PR + delete fact + from #PayrollSampledDailyDetailedStaging fact + inner join fw.dimDepartment d on d.DepartmentID = fact.DepartmentID and d.isPR = 0 + + + IF @fiscalYearID = 0 and @isCalcDaily = 0 -- if all parameters shows that we are recalculating everything + BEGIN + EXEC dbo.procSysDropIndex @schema = 'fw', @table = 'viewFactPayrollSampledDailyDetailedHours', @indexName = 'CU_viewFactPayrollSampledDailyDetailedHours', @isView = 1 + truncate table [fw].[FactPayrollSampledDailyDetailed] + DBCC CHECKIDENT('[fw].[FactPayrollSampledDailyDetailed]', RESEED, 0); + + CREATE CLUSTERED INDEX CORE_DepartmentID on #PayrollSampledDailyDetailedStaging (DepartmentID) with (data_compression = page) + + IF @isFeatureFlagOn = 1 + BEGIN + CREATE CLUSTERED INDEX CORE_DepartmentID on #PayrollSampledDailyDetailedFTEs (DepartmentID) with (data_compression = page) + + -- Drop Indexes + EXEC dbo.procSysDropIndex @schema = 'fw', @table = 'FactPayrollSampledDailyDetailed', @indexName = 'IDX_FactPayrollSampledDailyDetailed' + EXEC dbo.procSysDropIndex @schema = 'fw', @table = 'FactPayrollSampledDailyDetailed', @indexName = 'NCNU_IsDeleted' + + EXEC mr.procGetIntBatchSize + @DefaultBatchSize = 60000000, + @ResultBatchSize = @batchSize OUTPUT + + + SET @fromClause = ' + ( + select + f.DepartmentID, + f.JobCodeID, + f.PayCodeID, + f.PayCodeGroupID, + f.EmployeeID, + f.PayPeriodID, + f.DateID, + f.TimeClassID, + SUM(f.Hours) as Hours, + SUM(f.Dollars) as Dollars, + SUM(isnull(fte.FTEs,0)) as FTEs, + 0 as isDeleted + from + #PayrollSampledDailyDetailedStaging f + inner join fw.DimJobCode jc on f.JobCodeID = jc.JobCodeID + left join #PayrollSampledDailyDetailedFTEs fte on f.DepartmentID = fte.DepartmentID AND f.JobCodeID = fte.JobCodeID AND f.PayCodeID = fte.PayCodeID AND f.PayCodeGroupID = fte.PayCodeGroupID AND f.EmployeeID = fte.EmployeeID AND f.PayPeriodID = fte.PayPeriodID AND f.DateID = fte.DateID AND f.TimeClassID = fte.TimeClassID + where jc.IsPR = 1 and jc.IsDaily = 1 + group by + f.DepartmentID, + f.JobCodeID, + f.PayCodeID, + f.PayCodeGroupID, + f.EmployeeID, + f.PayPeriodID, + f.DateID, + f.TimeClassID) X' + -- Split data into batches + IF OBJECT_ID('tempdb..#inputPayPeriods') IS NOT NULL DROP TABLE #inputPayPeriods + + CREATE TABLE #inputPayPeriods (PayPeriodID INT, RecordsCount INT, BatchID INT) + INSERT INTO #inputPayPeriods + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'PayPeriodID', + @tableAlias = 'X', + @fromClause = @fromClause, + @whereClause = '', + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputPayPeriods + + -- Loop thru batches and insert data + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + INSERT INTO [fw].[FactPayrollSampledDailyDetailed] With (TABLOCKX) ( + DepartmentID, + JobCodeID, + PayCodeID, + PayCodeGroupID, + EmployeeID, + PayPeriodID, + DateID, + TimeClassID, + Hours, + Dollars, + FTEs, + IsDeleted + ) + select + f.DepartmentID, + f.JobCodeID, + f.PayCodeID, + f.PayCodeGroupID, + f.EmployeeID, + f.PayPeriodID, + f.DateID, + f.TimeClassID, + SUM(f.Hours) as Hours, + SUM(f.Dollars) as Dollars, + SUM(isnull(fte.FTEs,0)) as FTEs, + 0 as isDeleted + from + #PayrollSampledDailyDetailedStaging f + INNER JOIN #inputPayPeriods IPP ON IPP.PayPeriodID = f.PayPeriodID and IPP.BatchID = @BatchID + inner join fw.DimJobCode jc on f.JobCodeID = jc.JobCodeID + left join #PayrollSampledDailyDetailedFTEs fte on f.DepartmentID = fte.DepartmentID AND f.JobCodeID = fte.JobCodeID AND f.PayCodeID = fte.PayCodeID AND f.PayCodeGroupID = fte.PayCodeGroupID AND f.EmployeeID = fte.EmployeeID AND f.PayPeriodID = fte.PayPeriodID AND f.DateID = fte.DateID AND f.TimeClassID = fte.TimeClassID + where jc.IsPR = 1 and jc.IsDaily = 1 + group by + f.DepartmentID, + f.JobCodeID, + f.PayCodeID, + f.PayCodeGroupID, + f.EmployeeID, + f.PayPeriodID, + f.DateID, + f.TimeClassID + SET @BatchID = @BatchID + 1 + END + + CREATE NONCLUSTERED INDEX [IDX_FactPayrollSampledDailyDetailed] ON [fw].[FactPayrollSampledDailyDetailed] + ( + [DepartmentID] ASC, + [JobCodeID] ASC, + [PayCodeID] ASC, + [PayCodeGroupID] ASC, + [EmployeeID] ASC, + [DateID] ASC, + [TimeClassID] ASC + ) + WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY] + + CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactPayrollSampledDailyDetailed] + ( + [IsDeleted] ASC + )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY] + END + ELSE -- IF @isFeatureFlagOn = 0 + BEGIN + set @IterationFiscalYearID = (select min(dd.FiscalYear) from #PayrollSampledDailyDetailedStaging f + inner join fw.DimDate dd on dd.DateID = f.DateID) + WHILE @IterationFiscalYearID <= (select max(dd.FiscalYear) from #PayrollSampledDailyDetailedStaging f + inner join fw.DimDate dd on dd.DateID = f.DateID ) + BEGIN + INSERT INTO [fw].[FactPayrollSampledDailyDetailed] With (TABLOCKX) ( + DepartmentID, + JobCodeID, + PayCodeID, + PayCodeGroupID, + EmployeeID, + PayPeriodID, + DateID, + TimeClassID, + Hours, + Dollars, + FTEs, + IsDeleted + ) + select + f.DepartmentID, + f.JobCodeID, + f.PayCodeID, + f.PayCodeGroupID, + f.EmployeeID, + f.PayPeriodID, + f.DateID, + f.TimeClassID, + SUM(f.Hours) as Hours, + SUM(f.Dollars) as Dollars, + SUM(f.FTEs) as FTEs, + 0 as isDeleted + from + #PayrollSampledDailyDetailedStaging f + inner join fw.DimDate dd on dd.DateID = f.DateID + inner join fw.DimJobCode jc on f.JobCodeID = jc.JobCodeID + where dd.FiscalYear = @IterationFiscalYearID and jc.IsPR = 1 and jc.IsDaily = 1 + group by + f.DepartmentID, + f.JobCodeID, + f.PayCodeID, + f.PayCodeGroupID, + f.EmployeeID, + f.PayPeriodID, + f.DateID, + f.TimeClassID + set @iterationFiscalYearId = @iterationFiscalYearId + 1 + END + END + + CREATE UNIQUE CLUSTERED INDEX CU_viewFactPayrollSampledDailyDetailedHours + ON fw.viewFactPayrollSampledDailyDetailedHours (PayPeriodID, DepartmentID, EmployeeID, TimeClassID, RowID) + WITH (DATA_COMPRESSION = PAGE) + + END +ELSE + BEGIN + ;WITH TGT AS (SELECT t.* FROM + [fw].[FactPayrollSampledDailyDetailed] t With (TABLOCKX) + inner join #DailyCalcPeriodsScope dcps on dcps.PayPeriodID = t.PayPeriodID + --where (@fiscalYearID = 0 or pd.FiscalYear = @fiscalYearID) -- #DailyCalcPeriodsScope already contains all Pay Periods that should be recalculated, so filtering by year could bring destructive effect in case @fisclaYearID <> 'calendar year' (conflict @FiscalYearID and @isCalcDaily) + ) + MERGE + TGT AS target + USING ( + select DepartmentID,f.JobCodeID,PayCodeID,PayCodeGroupID,EmployeeID,PayPeriodID,DateID,TimeClassID, + SUM(Hours) as Hours, + SUM(Dollars) as Dollars, + SUM(FTEs) as FTEs + from + #PayrollSampledDailyDetailedStaging f + inner join fw.DimJobCode jc on f.JobCodeID = jc.JobCodeID + where jc.isPR = 1 and jc.IsDaily = 1 + group by DepartmentID,f.JobCodeID,PayCodeID,PayCodeGroupID,EmployeeID,PayPeriodID,DateID,TimeClassID + ) AS source + ON + SOURCE.DepartmentID=TARGET.DepartmentID + AND SOURCE.JobCodeID=TARGET.JobCodeID + AND SOURCE.PayCodeID = TARGET.PayCodeID + AND SOURCE.PayCodeGroupID=TARGET.PayCodeGroupID + AND SOURCE.EmployeeID=TARGET.EmployeeID + AND SOURCE.PayPeriodID=TARGET.PayPeriodID + AND SOURCE.TimeClassID=TARGET.TimeClassID + AND SOURCE.DateID=TARGET.DateID + WHEN MATCHED AND + (target.Hours <> source.Hours + or target.Dollars <> source.Dollars + or target.FTEs <> source.FTEs + ) + THEN + UPDATE + SET target.Hours = source.Hours, + target.Dollars = source.Dollars, + target.FTEs = source.FTEs + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + DepartmentID, + JobCodeID, + PayCodeID, + PayCodeGroupID, + EmployeeID, + PayPeriodID, + DateID, + TimeClassID, + Hours, + Dollars, + FTEs, + IsDeleted + ) + VALUES ( + + DepartmentID, + JobCodeID, + PayCodeID, + PayCodeGroupID, + EmployeeID, + PayPeriodID, + DateID, + TimeClassID, + Hours, + Dollars, + FTEs, + 0) + WHEN NOT MATCHED BY SOURCE + THEN + DELETE; + END + + IF @isCalcDaily = 1 + begin + delete from [fw].[FactPayrollSampledDailyDetailed] where dateID > (select MIN(dateID) from fw.dimDate where CalendarDateTime >= @yesterday_date )and TimeClassID = 1 + end + delete from [fw].[FactPayrollSampledDailyDetailed] where Hours = 0 and Dollars = 0 and TimeClassID = 1 + + IF OBJECT_ID('tempdb..#inputDepartments') IS NOT NULL DROP TABLE #inputDepartments + IF OBJECT_ID('tempdb..#PayrollSampledDailyDetailedStaging') IS NOT NULL DROP TABLE #PayrollSampledDailyDetailedStaging + IF OBJECT_ID('tempdb..#departmentsBudgetAllocations') IS NOT NULL DROP TABLE #departmentsBudgetAllocations + IF OBJECT_ID('tempdb..#DailyCalcPeriodsScope') IS NOT NULL DROP TABLE #DailyCalcPeriodsScope + IF OBJECT_ID('tempdb..#StaffingDaily') IS NOT NULL DROP TABLE #StaffingDaily + IF OBJECT_ID('tempdb..#PayrollSampledDailyDetailedFTEs') IS NOT NULL DROP TABLE #PayrollSampledDailyDetailedFTEs + + + -- UPDATE STATISTICS + UPDATE STATISTICS fw.FactPayrollSampledDailyDetailed; +GO + + +--------------------------------------------- + +-- fw.procPayrollSampledDailyInsert +/*************************************************************** +** CID Date Author WI Description +** 1 2016-12-17 mholov B-13509 Pull Budgeted amounts from monthly table +** 2 2017-01-11 akozlov D-05410 Minor fix +** 3 2017-01-31 akozlov B-13926 Added department filter +** 4 2017-02-08 gforeman B-14308 Added year filter +** 5 2017-02-20 gforeman D-05613 Prevent zero rows +** 6 2017-03-06 gforeman B-14693 Cancel sampling if daily disabled +** 7 2017-05-16 ipetriv D-05915 Added statistics recalculating to FactPayrollSampledDailyDetailed +** 8 2017-05-29 ipetriv B-15994 Refactored sampling process and implemented using of staging tables +** 9 2017-06-15 IP B-15086 Modify SP to use unique temp table +** 10 2017-06-20 IP B-15086 fixing issues: FTEs = 0 after recalculation for one year / duplicates appers for one year recalculation +** 11 2018-09-12 ipetriv B-16737 Allow job codes in PR to use 70-hour work weeks - Sampling Updates +** 12 2018-09-11 kzhuk D-07649 PR Daily custom action calls procedures for wrong year +** 13 2019-04-24 OV B-22924 Allow 0 data (except actual) in procPayrollSampledDailyInsert (B-20571) +** 14 2019-05-14 OV B-22955 Filtered by new 'isDaily' column from DimjobCode +** 15 2019-07-23 OV D-08628 Sampled data for first PayPeriod from previous year +** 16 2019-10-31 KF D-08926 PR Payroll Daily sampling: process fails due to full DB Transaction log +** 17 2019-11-25 IH TK-80619 Rollback transaction log changes +** 18 2020-01-08 HV B-25788 procPayrollSampledDailyInsert DBA Enhancements +** 19 2020-01-14 HV D-09150 Inflated 'Target FTE Daily' values caused by duplicates in FactPayrollSampledDaily +** 20 2021-12-21 HV JAZZ-31105 procPayrollSampledDailyInsert Filling Up DB For All Years Run (Rolling Average Target Basis) +** 21 2022-10-28 ishah JAZZ-45100 Reuse split by batches functionality in existing procedure +** 22 2024-06-14 SM JAZZ-71536 change JobCodeID from smallint to int +**************************************************************/ +CREATE PROCEDURE [fw].[procPayrollSampledDailyInsert] + @departmentIDs NVARCHAR(max) = NULL, + @fiscalYearID INT = 0, + @isCalcDaily bit = 0, + @isFeatureFlagOn bit = 0 + WITH RECOMPILE +AS + + IF OBJECT_ID('tempdb..#departments') IS NOT NULL DROP TABLE #departments +SELECT val INTO #departments +FROM ConvertCSValuesToTable(@departmentIDs, ',') + +SELECT DepartmentID, + JobCodeID, + WorkingHoursCoef = cast(dww.Hours AS NUMERIC(20, 6)) / 7 +INTO #WorkWeekHours +FROM ( + SELECT DepartmentID, + JobCodeID, + WorkWeekID = COALESCE(jc.WorkWeekID, de.WorkWeekID, - 1) + FROM ( + SELECT dp.DepartmentID, + WorkWeekID = CASE + WHEN e.WorkWeekID > - 1 + THEN e.WorkWeekID + ELSE NULL + END + FROM fw.DimEntity e + INNER JOIN fw.DimDepartment dp on e.EntityID = dp.EntityID + ) DE + CROSS JOIN ( + SELECT djc.JobCodeID, + djcg.JobCodeGroupID, + WorkWeekID = CASE + WHEN djc.WorkWeekOverrideID > - 1 + THEN djc.WorkWeekOverrideID + WHEN djc.WorkWeekOverrideID = - 1 + AND djcg.WorkWeekOverrideID > - 1 + THEN djcg.WorkWeekOverrideID + ELSE NULL + END + FROM fw.DimJobCode djc + INNER JOIN fw.DimJobCodeGroup djcg + ON djc.JobCodeGroupID = djcg.JobCodeGroupID + WHERE djc.IsDaily = 1 and djc.IsPR = 1 + ) JC + ) DeptJobCode +LEFT JOIN fw.DimWorkWeek dww + ON DeptJobCode.WorkWeekID = dww.WorkWeekID + +IF OBJECT_ID('tempdb..#dates') IS NOT NULL DROP TABLE #dates +SELECT DISTINCT DateID INTO #dates +FROM fw.DimDate dt +INNER JOIN fw.DimPayPeriod pp on dt.CalendarDateTime BETWEEN pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate + where + (@isCalcDaily = 1 and DATEADD(DAY,-1,CAST(GETDATE() as DATE)) BETWEEN pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate) -- if @isCalcDaily = 1 is present we ignore what @yearOfSampling is passed to stored procedure (based on B-18793) + or + (@isCalcDaily = 0 and (@fiscalYearID = pp.FiscalYearIDSecond or @fiscalYearID = 0)) + +--cancel if not using daily +IF ( + NOT EXISTS ( + SELECT 1 + FROM pi.SystemSetting + WHERE NAME = 'PR Daily Enabled' + AND Value = '1' + ) + ) +BEGIN + RETURN +END + +/*If target basis is rolling average then we can't calculate baseline as simple sum of detailed table. + in his case we should + 1)insert summed values for all timeclasses except baseline (TimeClassId = 20) + 2)recalculate baseline (including FTE for baseline records) +*/ +IF ( + SELECT Value + FROM pi.SystemSetting + WHERE NAME = 'Target Basis' + ) = 10 -- rolling average +BEGIN + IF @fiscalYearID = 0 AND @isCalcDaily = 0 + AND @departmentIDs IS NULL + BEGIN + TRUNCATE TABLE [fw].[FactPayrollSampledDaily] + IF @isFeatureFlagOn = 0 + BEGIN + /*recalculate baseline for just inserted values*/ + ; + + WITH groupedBaselineTargetPayroll + AS ( + SELECT FACT.DepartmentID, + FACT.JobCodeID, + FACT.PayCodeGroupID, + FACT.PayPeriodID, + DT.DateID, + FACT.TimeClassID, + SUM(FACT.Hours) AS Hours, + SUM(FACT.Dollars) AS Dollars + FROM fw.FactPayrollSampledPayPeriod FACT + INNER JOIN [fw].[DimPayPeriod] PP + ON PP.PayPeriodID = FACT.PayPeriodID + INNER JOIN [fw].[DimDate] DT + ON DT.CalendarDateTime BETWEEN PP.PeriodStartCalendarDate AND PP.PeriodEndCalendarDate + INNER JOIN [fw].[DimDepartment] D + ON D.DepartmentID = FACT.DepartmentID + WHERE FACT.PayPeriodID != 0 + AND FACT.IsDeleted = 0 + AND D.IsPR = 1 + AND FACT.TimeClassID = 20 + AND FACT.DepartmentID != 0 + GROUP BY FACT.DepartmentID, + FACT.JobCodeID, + FACT.PayCodeGroupID, + FACT.PayPeriodID, + DT.DateID, + FACT.TimeClassID + ) + INSERT INTO fw.FactPayrollSampledDaily ( + DepartmentID, + JobCodeID, + PayCodeGroupID, + PayPeriodID, + DateID, + TimeClassID, + Hours, + Dollars, + FTEs + ) + SELECT fact.DepartmentID, + fact.JobCodeID, + fact.PayCodeGroupID, + fact.PayPeriodID, + fact.DateID, + fact.TimeClassID, + SUM(fact.Hours), + SUM(fact.Dollars), + FTEs = SUM(isnull(CASE WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0 and ww.WorkingHoursCoef is null THEN fact.Hours / (WorkingDays * 8.0 / PeriodDays) + WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0 and ww.WorkingHoursCoef is not null THEN (fact.Hours) / WorkingHoursCoef + END, 0)) + FROM ( + SELECT DepartmentID, + JobCodeID, + PayCodeGroupID, + G.PayPeriodID, + DateID, + TimeClassID, + Hours / PP.PeriodDays AS Hours, + Dollars / PP.PeriodDays AS Dollars + FROM groupedBaselineTargetPayroll G + INNER JOIN fw.DimPayPeriod PP + ON PP.PayPeriodID = G.PayPeriodID + ) fact + INNER JOIN fw.DimPayPeriod pp + ON pp.PayPeriodID = fact.PayPeriodID + INNER JOIN [fw].[viewDimPayCodeGroup] pcg + ON fact.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN #WorkWeekHours ww ON ww.DepartmentID = fact.DepartmentID and fact.JobCodeID = ww.JobCodeID + GROUP BY fact.DepartmentID, + fact.JobCodeID, + fact.PayCodeGroupID, + fact.PayPeriodID, + fact.DateID, + fact.TimeClassID + UNION ALL + SELECT fact.DepartmentID, + fact.JobCodeID, + fact.PayCodeGroupID, + fact.PayPeriodID, + fact.DateID, + fact.TimeClassID, + fact.Hours, + fact.Dollars, + FTEs = isnull(CASE WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0 and ww.WorkingHoursCoef is null THEN fact.Hours / (WorkingDays * 8.0 / PeriodDays) + WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0 and ww.WorkingHoursCoef is not null THEN (fact.Hours) / WorkingHoursCoef + END, 0) + FROM ( + SELECT fact.[DepartmentID], + fact.[JobCodeID], + fact.[PayCodeGroupID], + fact.[PayPeriodID], + fact.[DateID], + fact.[TimeClassID], + sum(fact.[Dollars]) AS Dollars, + sum(fact.[Hours]) AS Hours + FROM [fw].[FactPayrollSampledDailyDetailed] fact + INNER JOIN fw.DimDate dt + ON dt.DateID = fact.DateID + WHERE TimeClassID <> 20 -- all timeclasses except baseline (TimeClassId = 20) + GROUP BY fact.[DepartmentID], + fact.[JobCodeID], + fact.[PayCodeGroupID], + fact.[PayPeriodID], + fact.[DateID], + fact.[TimeClassID] + ) FACT + INNER JOIN fw.DimPayPeriod pp + ON pp.PayPeriodID = fact.PayPeriodID + INNER JOIN [fw].[viewDimPayCodeGroup] pcg + ON fact.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN #WorkWeekHours ww ON ww.DepartmentID = fact.DepartmentID and fact.JobCodeID = ww.JobCodeID + END + ELSE --IF @isFeatureFlagOn = 1 + BEGIN + IF OBJECT_ID('tempdb..#groupedBaselineTargetPayroll') IS NOT NULL DROP TABLE #groupedBaselineTargetPayroll + CREATE TABLE #groupedBaselineTargetPayroll (DepartmentID int, JobCodeID int, PayCodeGroupID int, PayPeriodID int, DateID int, TimeClassID int, Hours decimal(19,4), Dollars decimal(19,4)) + + INSERT INTO #groupedBaselineTargetPayroll( + DepartmentID, + JobCodeID, + PayCodeGroupID, + PayPeriodID, + DateID, + TimeClassID, + Hours, + Dollars) + SELECT FACT.DepartmentID, + FACT.JobCodeID, + FACT.PayCodeGroupID, + FACT.PayPeriodID, + DT.DateID, + FACT.TimeClassID, + SUM(FACT.Hours) AS Hours, + SUM(FACT.Dollars) AS Dollars + FROM fw.FactPayrollSampledPayPeriod FACT + INNER JOIN [fw].[DimPayPeriod] PP + ON PP.PayPeriodID = FACT.PayPeriodID + INNER JOIN [fw].[DimDate] DT + ON DT.CalendarDateTime BETWEEN PP.PeriodStartCalendarDate AND PP.PeriodEndCalendarDate + INNER JOIN [fw].[DimDepartment] D + ON D.DepartmentID = FACT.DepartmentID + WHERE FACT.PayPeriodID != 0 + AND FACT.IsDeleted = 0 + AND D.IsPR = 1 + AND FACT.TimeClassID = 20 + AND FACT.DepartmentID != 0 + GROUP BY FACT.DepartmentID, + FACT.JobCodeID, + FACT.PayCodeGroupID, + FACT.PayPeriodID, + DT.DateID, + FACT.TimeClassID + + DECLARE @BatchSize INT = 30000000 + print 'By Batch'+convert(varchar(20),GETDATE(),113) + + -- Split data into batches + IF OBJECT_ID('tempdb..#inputPayPeriods') IS NOT NULL DROP TABLE #inputPayPeriods + + CREATE TABLE #inputPayPeriods (PayPeriodID INT, RecordsCount INT, BatchID INT) + INSERT INTO #inputPayPeriods + EXEC dbo.procGetInputDataByBatches + @batchSize = @BatchSize, + @columnName = 'PayPeriodID', + @tableAlias = 'gp', + @fromClause = '#groupedBaselineTargetPayroll gp', + @whereClause = '', + @isDebug = 0 + + DECLARE @BatchID INT, @MaxBatchID INT + SELECT @MaxBatchID = MAX(BatchID) FROM #inputPayPeriods + + -- Drop Indexes + EXEC dbo.procSysDropIndex @schema = 'fw', @table = 'FactPayrollSampledDaily', @indexName = 'IDX_FactPayrollSampledDaily' + EXEC dbo.procSysDropIndex @schema = 'fw', @table = 'FactPayrollSampledDaily', @indexName = 'NCNU_IsDeleted' + + -- Loop thru batches and insert data + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + INSERT INTO fw.FactPayrollSampledDaily ( + DepartmentID, + JobCodeID, + PayCodeGroupID, + PayPeriodID, + DateID, + TimeClassID, + Hours, + Dollars, + FTEs + ) + SELECT fact.DepartmentID, + fact.JobCodeID, + fact.PayCodeGroupID, + fact.PayPeriodID, + fact.DateID, + fact.TimeClassID, + SUM(fact.Hours), + SUM(fact.Dollars), + FTEs = SUM(isnull(CASE WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0 and ww.WorkingHoursCoef is null THEN fact.Hours / (WorkingDays * 8.0 / PeriodDays) + WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0 and ww.WorkingHoursCoef is not null THEN (fact.Hours) / WorkingHoursCoef + END, 0)) + FROM ( + SELECT DepartmentID, + JobCodeID, + PayCodeGroupID, + G.PayPeriodID, + DateID, + TimeClassID, + Hours / PP.PeriodDays AS Hours, + Dollars / PP.PeriodDays AS Dollars + FROM #groupedBaselineTargetPayroll G + INNER JOIN #inputPayPeriods IPP ON IPP.PayPeriodID = G.PayPeriodID and IPP.BatchID = @BatchID + INNER JOIN fw.DimPayPeriod PP + ON PP.PayPeriodID = G.PayPeriodID + ) fact + INNER JOIN fw.DimPayPeriod pp + ON pp.PayPeriodID = fact.PayPeriodID + INNER JOIN [fw].[viewDimPayCodeGroup] pcg + ON fact.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN #WorkWeekHours ww ON ww.DepartmentID = fact.DepartmentID and fact.JobCodeID = ww.JobCodeID + GROUP BY fact.DepartmentID, + fact.JobCodeID, + fact.PayCodeGroupID, + fact.PayPeriodID, + fact.DateID, + fact.TimeClassID + SET @BatchID = @BatchID + 1 + END + + INSERT INTO fw.FactPayrollSampledDaily ( + DepartmentID, + JobCodeID, + PayCodeGroupID, + PayPeriodID, + DateID, + TimeClassID, + Hours, + Dollars, + FTEs + ) + SELECT fact.DepartmentID, + fact.JobCodeID, + fact.PayCodeGroupID, + fact.PayPeriodID, + fact.DateID, + fact.TimeClassID, + fact.Hours, + fact.Dollars, + FTEs = isnull(CASE WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0 and ww.WorkingHoursCoef is null THEN fact.Hours / (WorkingDays * 8.0 / PeriodDays) + WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0 and ww.WorkingHoursCoef is not null THEN (fact.Hours) / WorkingHoursCoef + END, 0) + FROM ( + SELECT fact.[DepartmentID], + fact.[JobCodeID], + fact.[PayCodeGroupID], + fact.[PayPeriodID], + fact.[DateID], + fact.[TimeClassID], + sum(fact.[Dollars]) AS Dollars, + sum(fact.[Hours]) AS Hours + FROM [fw].[FactPayrollSampledDailyDetailed] fact + INNER JOIN fw.DimDate dt + ON dt.DateID = fact.DateID + WHERE TimeClassID <> 20 -- all timeclasses except baseline (TimeClassId = 20) + GROUP BY fact.[DepartmentID], + fact.[JobCodeID], + fact.[PayCodeGroupID], + fact.[PayPeriodID], + fact.[DateID], + fact.[TimeClassID] + ) FACT + INNER JOIN fw.DimPayPeriod pp + ON pp.PayPeriodID = fact.PayPeriodID + INNER JOIN [fw].[viewDimPayCodeGroup] pcg + ON fact.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN #WorkWeekHours ww ON ww.DepartmentID = fact.DepartmentID and fact.JobCodeID = ww.JobCodeID + + + CREATE NONCLUSTERED INDEX [IDX_FactPayrollSampledDaily] ON [fw].[FactPayrollSampledDaily] + ( + [DepartmentID] ASC, + [JobCodeID] ASC, + [PayCodeGroupID] ASC, + [PayPeriodID] ASC, + [DateID] ASC, + [TimeClassID] ASC + ) + INCLUDE ([Dollars], [FTEs], [Hours]) + WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 100) ON [PRIMARY] + + CREATE NONCLUSTERED INDEX [NCNU_IsDeleted] ON [fw].[FactPayrollSampledDaily] + ( + [IsDeleted] ASC + ) + WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 100) ON [PRIMARY] + + IF OBJECT_ID('tempdb..#groupedBaselineTargetPayroll') IS NOT NULL DROP TABLE #groupedBaselineTargetPayroll + END + END + ELSE + BEGIN + WITH TGT + AS ( + SELECT t.* + FROM [fw].[FactPayrollSampledDaily] t WITH (TABLOCKX) + INNER JOIN #dates pp on t.DateID = pp.DateID + WHERE ( + @departmentIDs IS NULL + OR t.DepartmentID IN ( + SELECT val + FROM #departments + ) + ) + ), + + groupedBaselineTargetPayrollFilteredByDates + AS ( + SELECT FACT.DepartmentID, + FACT.JobCodeID, + FACT.PayCodeGroupID, + FACT.PayPeriodID, + DT.DateID, + FACT.TimeClassID, + SUM(FACT.Hours) AS Hours, + SUM(FACT.Dollars) AS Dollars + FROM fw.FactPayrollSampledPayPeriod FACT + INNER JOIN [fw].[DimPayPeriod] PP + ON PP.PayPeriodID = FACT.PayPeriodID + INNER JOIN fw.DimDate DT + ON DT.CalendarDateTime BETWEEN PP.PeriodStartCalendarDate AND PP.PeriodEndCalendarDate + INNER JOIN #dates FD + ON FD.DateID = DT.DateID + INNER JOIN [fw].[DimDepartment] D + ON D.DepartmentID = FACT.DepartmentID + WHERE FACT.PayPeriodID != 0 + AND FACT.IsDeleted = 0 + AND D.IsPR = 1 + AND FACT.TimeClassID = 20 + AND FACT.DepartmentID != 0 + AND ( + @departmentIDs IS NULL + OR FACT.DepartmentID IN ( + SELECT val + FROM #departments + ) + ) + GROUP BY FACT.DepartmentID, + FACT.JobCodeID, + FACT.PayCodeGroupID, + FACT.PayPeriodID, + DT.DateID, + FACT.TimeClassID + ) + MERGE TGT AS target + USING ( + SELECT fact.DepartmentID, + fact.JobCodeID, + fact.PayCodeGroupID, + fact.PayPeriodID, + fact.DateID, + fact.TimeClassID, + fact.Hours, + fact.Dollars, + FTEs = isnull(CASE WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0 and ww.WorkingHoursCoef is null THEN fact.Hours / (WorkingDays * 8.0 / PeriodDays) + WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0 and ww.WorkingHoursCoef is not null THEN (fact.Hours) / WorkingHoursCoef + END, 0) + + FROM ( + SELECT fact.[DepartmentID], + fact.[JobCodeID], + fact.[PayCodeGroupID], + fact.[PayPeriodID], + fact.[DateID], + fact.[TimeClassID], + sum(fact.[Dollars]) AS Dollars, + sum(fact.[Hours]) AS Hours + FROM [fw].[FactPayrollSampledDailyDetailed] fact + INNER JOIN #dates dt + ON dt.DateID = fact.DateID + WHERE ( + @departmentIDs IS NULL + OR DepartmentID IN ( + SELECT val + FROM #departments + ) + ) + + AND TimeClassID <> 20 -- all timeclasses except baseline (TimeClassId = 20) + GROUP BY fact.[DepartmentID], + fact.[JobCodeID], + fact.[PayCodeGroupID], + fact.[PayPeriodID], + fact.[DateID], + fact.[TimeClassID] + ) FACT + INNER JOIN fw.DimPayPeriod pp + ON pp.PayPeriodID = fact.PayPeriodID + INNER JOIN [fw].[viewDimPayCodeGroup] pcg + ON fact.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN #WorkWeekHours ww ON ww.DepartmentID = fact.DepartmentID and fact.JobCodeID = ww.JobCodeID + + UNION ALL + + SELECT fact.DepartmentID, + fact.JobCodeID, + fact.PayCodeGroupID, + fact.PayPeriodID, + fact.DateID, + fact.TimeClassID, + SUM(fact.Hours), + SUM(fact.Dollars), + FTEs = SUM(isnull(CASE WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0 and ww.WorkingHoursCoef is null THEN fact.Hours / (WorkingDays * 8.0 / PeriodDays) + WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0 and ww.WorkingHoursCoef is not null THEN (fact.Hours) / WorkingHoursCoef + END, 0)) + + FROM ( + SELECT DepartmentID, + JobCodeID, + PayCodeGroupID, + G.PayPeriodID, + DateID, + TimeClassID, + Hours / PP.PeriodDays AS Hours, + Dollars / PP.PeriodDays AS Dollars + FROM groupedBaselineTargetPayrollFilteredByDates G + INNER JOIN fw.DimPayPeriod PP + ON PP.PayPeriodID = G.PayPeriodID + ) fact + INNER JOIN fw.DimPayPeriod pp + ON pp.PayPeriodID = fact.PayPeriodID + INNER JOIN [fw].[viewDimPayCodeGroup] pcg + ON fact.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN #WorkWeekHours ww ON ww.DepartmentID = fact.DepartmentID and fact.JobCodeID = ww.JobCodeID + GROUP BY fact.DepartmentID, + fact.JobCodeID, + fact.PayCodeGroupID, + fact.PayPeriodID, + fact.DateID, + fact.TimeClassID + ) AS source + ON SOURCE.DepartmentID = TARGET.DepartmentID + AND SOURCE.JobCodeID = TARGET.JobCodeID + --AND SOURCE.PayCodeID = TARGET.PayCodeID + AND SOURCE.PayCodeGroupID = TARGET.PayCodeGroupID + --AND SOURCE.EmployeeID = TARGET.EmployeeID + AND SOURCE.PayPeriodID = TARGET.PayPeriodID + AND SOURCE.TimeClassID = TARGET.TimeClassID + AND SOURCE.DateID = TARGET.DateID + WHEN MATCHED + AND ( + target.Hours <> source.Hours + OR target.Dollars <> source.Dollars + OR target.FTEs <> source.FTEs + ) + THEN + UPDATE + SET target.Hours = source.Hours, + target.Dollars = source.Dollars, + target.FTEs = source.FTEs + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + DepartmentID, + JobCodeID, + -- PayCodeID, + PayCodeGroupID, + -- EmployeeID, + PayPeriodID, + DateID, + TimeClassID, + Hours, + Dollars, + FTEs, + IsDeleted + ) + VALUES ( + DepartmentID, + JobCodeID, + --PayCodeID, + PayCodeGroupID, + --EmployeeID, + PayPeriodID, + DateID, + TimeClassID, + Hours, + Dollars, + FTEs, + 0 + ) + WHEN NOT MATCHED BY SOURCE + THEN + DELETE; + + END +END + ELSE /*Here is inserting aggregated rows in case when "Target Basis" is not rolling average*/ +BEGIN +IF @fiscalYearID = 0 AND @departmentIDs IS NULL AND @isCalcDaily = 0 +BEGIN +TRUNCATE TABLE [fw].[FactPayrollSampledDaily] +INSERT INTO [fw].[FactPayrollSampledDaily] ( + [DepartmentID], + [JobCodeID], + [PayPeriodID], + [TimeClassID], + [DateID], + [PayCodeGroupID], + [Hours], + [Dollars], + [FTEs] + ) +SELECT fact.[DepartmentID], + fact.[JobCodeID], + fact.[PayPeriodID], + fact.[TimeClassID], + fact.[DateID], + fact.[PayCodeGroupID], + fact.Hours, + fact.Dollars, + FTEs = isnull(CASE WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0 and ww.WorkingHoursCoef is null THEN fact.Hours / (WorkingDays * 8.0 / PeriodDays) + WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0 and ww.WorkingHoursCoef is not null THEN (fact.Hours) / WorkingHoursCoef + END, 0) + +FROM ( + SELECT fact.[DepartmentID], + fact.[JobCodeID], + fact.[PayCodeGroupID], + fact.[PayPeriodID], + fact.[DateID], + fact.[TimeClassID], + sum(fact.[Dollars]) AS Dollars, + sum(fact.[Hours]) AS Hours + FROM [fw].[FactPayrollSampledDailyDetailed] fact + WHERE ( + @departmentIDs IS NULL + OR DepartmentID IN ( + SELECT val + FROM #departments + ) + ) + + GROUP BY fact.[DepartmentID], + fact.[JobCodeID], + fact.[PayCodeGroupID], + fact.[PayPeriodID], + fact.[DateID], + fact.[TimeClassID] + ) FACT +INNER JOIN fw.DimPayPeriod pp + ON pp.PayPeriodID = fact.PayPeriodID +INNER JOIN [fw].[viewDimPayCodeGroup] pcg + ON fact.PayCodeGroupID = pcg.PayCodeGroupID +INNER JOIN #WorkWeekHours ww ON ww.DepartmentID = fact.DepartmentID and fact.JobCodeID = ww.JobCodeID + +END +ELSE +WITH TGT + AS ( + SELECT t.* + FROM [fw].[FactPayrollSampledDaily] t WITH (TABLOCKX) + INNER JOIN #dates pp + ON t.DateId = pp.DateID + WHERE ( + @departmentIDs IS NULL + OR t.DepartmentID IN ( + SELECT val + FROM #departments + ) + ) + ) + MERGE TGT AS target + USING ( + SELECT fact.[DepartmentID], + fact.[JobCodeID], + fact.[PayPeriodID], + fact.[TimeClassID], + fact.[DateID], + fact.[PayCodeGroupID], + fact.Hours, + fact.Dollars, + FTEs = isnull(CASE WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0 and ww.WorkingHoursCoef is null THEN fact.Hours / (WorkingDays * 8.0 / PeriodDays) + WHEN pcg.ProductiveClass IN ('Productive','Non-Productive') AND pp.PeriodNumber != 0 and ww.WorkingHoursCoef is not null THEN (fact.Hours) / WorkingHoursCoef + END, 0) + +FROM ( + SELECT fact.[DepartmentID], + fact.[JobCodeID], + fact.[PayCodeGroupID], + fact.[PayPeriodID], + fact.[DateID], + fact.[TimeClassID], + sum(fact.[Dollars]) AS Dollars, + sum(fact.[Hours]) AS Hours + FROM [fw].[FactPayrollSampledDailyDetailed] fact + INNER JOIN #dates dt + ON dt.DateID = fact.DateID + WHERE ( + @departmentIDs IS NULL + OR DepartmentID IN ( + SELECT val + FROM #departments + ) + ) + + GROUP BY fact.[DepartmentID], + fact.[JobCodeID], + fact.[PayCodeGroupID], + fact.[PayPeriodID], + fact.[DateID], + fact.[TimeClassID] + ) FACT +INNER JOIN fw.DimPayPeriod pp + ON pp.PayPeriodID = fact.PayPeriodID +INNER JOIN [fw].[viewDimPayCodeGroup] pcg + ON fact.PayCodeGroupID = pcg.PayCodeGroupID +INNER JOIN #WorkWeekHours ww ON ww.DepartmentID = fact.DepartmentID and fact.JobCodeID = ww.JobCodeID + ) AS source + ON SOURCE.DepartmentID = TARGET.DepartmentID + AND SOURCE.JobCodeID = TARGET.JobCodeID + --AND SOURCE.PayCodeID = TARGET.PayCodeID + AND SOURCE.PayCodeGroupID = TARGET.PayCodeGroupID + --AND SOURCE.EmployeeID = TARGET.EmployeeID + AND SOURCE.PayPeriodID = TARGET.PayPeriodID + AND SOURCE.TimeClassID = TARGET.TimeClassID + AND SOURCE.DateID = TARGET.DateID + WHEN MATCHED AND + (target.Hours <> source.Hours + or target.Dollars <> source.Dollars + or target.FTEs <> source.FTEs + ) + THEN + UPDATE + SET target.Hours = source.Hours, + target.Dollars = source.Dollars, + target.FTEs = source.FTEs + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + DepartmentID, + JobCodeID, + -- PayCodeID, + PayCodeGroupID, + -- EmployeeID, + PayPeriodID, + DateID, + TimeClassID, + Hours, + Dollars, + FTEs, + IsDeleted + ) + VALUES ( + DepartmentID, + JobCodeID, + --PayCodeID, + PayCodeGroupID, + --EmployeeID, + PayPeriodID, + DateID, + TimeClassID, + Hours, + Dollars, + FTEs, + 0 + ) + WHEN NOT MATCHED BY SOURCE + THEN + DELETE; + +DELETE FROM [fw].[FactPayrollSampledDaily] where TimeClassID = 1 and Dollars = 0 and Hours = 0 + +END + + IF OBJECT_ID('tempdb..#departments') IS NOT NULL DROP TABLE #departments + IF OBJECT_ID('tempdb..#dates') IS NOT NULL DROP TABLE #dates; +GO + + +--------------------------------------------- + +-- fw.procPayrollSampledMonthlyDetailedInsert +/************************************************************ +** Change History +************************************************************** +** CID Date Author WI Description +** 1 9.19.14 MJS B-02788 Excluding Budget data from the detailed sample since budgeting at Pay Code level is not supported +** 2 2015-10-28 MJS D-03587 Added logic to exclude ignored hours and dollars +** 3 2016-09-22 AK B-11845 Added procFactPayrollSampledDetailedBaselineTargetUpdate +** 4 2016-12-13 NL B-13759 Added fiscalYearID param and filtering +** 5 2017-02-22 GF D-05545 Move duplicate record handling from YTD into sampling + general cleanup +** 6 2017-02-22 IP B-14098 MR - Adjust Budgeted FTEs (Sampling). Added part that adds adjusted values to temp table #TEMPPAYROLL +** 7 2017-03-06 GF B-14693 Added baseline target year filter +** 8 2017-03-08 GF B-14693 Fix adjustment records year filter handling +** 9 2017-04-11 IP B-15086 Sampling Performance Improvements. Using temp tables insead of fw.FactPayrollSampledMonthlyDetailed. +** 10 2017-06-12 IP Changed type of hours/dollars fields to numeric instead of "money" +** 11 2017-06-15 IP B-15086 Modify SP to use unique temp table +** 12 2017-07-11 IP D-06150 Fixed conditions of merge statement (update part) +** 13 2017-07-13 IP TK-45395 Fixed conditions of merge statement (include isSystemGenerated column) +** 14 2017-08-29 ip B-16798 Add using of Budget Adjustment. +** 15 2018-01-17 IP B-16703 Omit archived budget adjustments +** 16 2018-02-07 IP B-18725 MR - Provider sampling from payroll +** 17 2018-02-09 IP B-18724 Omit archived Budgeted FTE Adjustments +** 18 2019-06-26 OV D-08576 FTEs are not calculated for first FY, deleted transaction +** 19 2023-09-13 KF JAZZ-55750 Remove filter to allow other time classes in MR reporting +*************************************************************/ +CREATE proc [fw].[procPayrollSampledMonthlyDetailedInsert] + @fiscalYearID smallint = 0 +as + print 'Starting calculating staging table --- '+convert(varchar(20),GETDATE(),113) + IF OBJECT_ID('tempdb..#PayrollSampledMonthlyDetailedStaging') IS NOT NULL DROP TABLE #PayrollSampledMonthlyDetailedStaging + IF OBJECT_ID('fw.PayrollSampledMonthlyDetailedStagingWithCalcs') IS NOT NULL DROP TABLE fw.PayrollSampledMonthlyDetailedStagingWithCalcs + + DECLARE + @fromClause nvarchar(max), + @whereClause nvarchar(max), + @MaxBatchID INT, + @BatchID INT, + @batchSize INT + + --pull new data - data integration + CREATE TABLE #PayrollSampledMonthlyDetailedStaging (RowID bigint identity(1,1), DepartmentID int, JobCodeID int, EmployeeID int, PayCodeID int, PayCodeGroupID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, Hours decimal(18,6), Dollars decimal(18,6), FTEs decimal(18,6),isDeleted bit, isSystemGenerated bit) + INSERT INTO #PayrollSampledMonthlyDetailedStaging(DepartmentID, JobCodeID, EmployeeID, PayCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, TimeClassID, Hours, Dollars, FTEs) + SELECT + pr.DepartmentID, + pr.JobCodeID, + pr.EmployeeID, + pr.PayCodeID, + pc.PayCodeGroupID, + PR.FiscalYearID, + pr.FiscalMonthID, + pr.TimeClassID, + SUM(CASE WHEN pr.unittypeID=51 and pc.IsHoursIgnored=0 then value ELSE 0 END) AS Hours, + SUM(CASE WHEN pr.unittypeID=34 and pc.IsDollarsIgnored=0 then value ELSE 0 END) AS Dollars, + 0 as FTEs + FROM + int.FactStaffing pr + INNER JOIN fw.DimPayCode pc on pc.PayCodeID = PR.PayCodeID + left join mr.viewFactProviderBasedOnPayroll vw on vw.RowID = pr.RowID + WHERE + pr.FiscalMonthCode not in('', '0') + and pr.IsDeleted = 0 + and pr.Value != 0 + AND (pr.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0) + and isnull(IsProvider,0) = 0 + GROUP BY + pr.DepartmentID, + pr.JobCodeID, + pr.EmployeeID, + pr.PayCodeID, + pc.PayCodeGroupID, + PR.FiscalYearID, + pr.FiscalMonthID, + pr.TimeClassID, + pr.PayCodeID + -- BudgetAdjustments Start + declare @iteration int = 1 + DECLARE @BudgetReallocationGUID uniqueidentifier,@date datetime,@BudgetReallocationType varchar(50) + + DECLARE BRA_cursor CURSOR FOR + SELECT distinct BudgetReallocationGUID,date,BudgetReallocationType from fw.BudgetReallocationWithDefinedType + WHERE (FiscalYearID = @FiscalYearID or @FiscalYearID = 0) and DataType = 1 + ORDER BY date; + + OPEN BRA_cursor + + FETCH NEXT FROM BRA_cursor + INTO @BudgetReallocationGUID,@date,@BudgetReallocationType + + WHILE @@FETCH_STATUS = 0 + BEGIN + + INSERT INTO #PayrollSampledMonthlyDetailedStaging(DepartmentID, JobCodeID, EmployeeID, PayCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, TimeClassID, Hours, Dollars, FTEs) + SELECT TargetDepartmentID as DepartmentID,TargetJobCodeID as JobCodeID, stt.EmployeeID, stt.PayCodeID, stt.PayCodeGroupID, stt.FiscalYearID, stt.FiscalMonthID, stt.TimeClassID, stt.Hours, stt.Dollars, stt.FTEs + FROM #PayrollSampledMonthlyDetailedStaging STT + INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceJobCodeID = stt.JobCodeID and b.FiscalYearID = stt.FiscalYearID + INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID + where + b.BudgetReallocationGUID = @BudgetReallocationGUID + and TimeClassID = 2 + and DataType = 1 + and Archived = 0 + + UPDATE STT + SET Dollars = 0, + Hours = 0, + FTEs = 0 + FROM #PayrollSampledMonthlyDetailedStaging STT + INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceJobCodeID = stt.JobCodeID and b.FiscalYearID = stt.FiscalYearID + INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID + where + b.BudgetReallocationGUID = @BudgetReallocationGUID + and TimeClassID = 2 + and DataType = 1 + and Archived = 0 + + set @iteration = @iteration +1 + + FETCH NEXT FROM BRA_cursor + INTO @BudgetReallocationGUID,@date,@BudgetReallocationType + END + CLOSE BRA_cursor; + DEALLOCATE BRA_cursor; + -- BudgetAdjustments END + + + --pull new data - adjustments + DECLARE @NonProdGroupID INT = ( + SELECT TOP 1 pcg.PayCodeGroupID + FROM fw.DimProductiveClass pc + INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID + WHERE pc.Name = 'Non-Productive' AND pcg.PayCodeGroupID != 0 + ORDER BY pcg.SortOrder) + + DECLARE @ProdGroupID INT = ( + SELECT TOP 1 pcg.PayCodeGroupID + FROM fw.DimProductiveClass pc + INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID + WHERE pc.Name = 'Productive' AND pcg.PayCodeGroupID != 0 + ORDER BY pcg.SortOrder) + + DECLARE @NonProdPayCodeID INT = ( + SELECT TOP 1 pcg.DefaultPayCodeID + FROM fw.DimProductiveClass pc + INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID + WHERE pc.Name = 'Non-Productive' AND pcg.PayCodeGroupID != 0 + ORDER BY pcg.SortOrder) + + DECLARE @ProdPayCodeID INT = ( + SELECT TOP 1 pcg.DefaultPayCodeID + FROM fw.DimProductiveClass pc + INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID + WHERE pc.Name = 'Productive' AND pcg.PayCodeGroupID != 0 + ORDER BY pcg.SortOrder) + + INSERT INTO #PayrollSampledMonthlyDetailedStaging(DepartmentID, JobCodeID, EmployeeID, PayCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, TimeClassID, Hours, Dollars, FTEs) + + SELECT b.DepartmentID, + b.JobCodeID, + 0 as EmployeeID, + @NonProdPayCodeID AS PayCodeID, + @NonProdGroupID AS PayCodeGroupID, + b.FiscalYearID, + ba.FiscalMonthID, + 2 AS TimeClassID, -- always Budgeted + ba.NonProductiveChange AS Hours, + 0 AS Dollars, + 0 AS FTEs + FROM mr.BudgetPayrollReallocationAdjustment ba + INNER JOIN mr.BudgetPayrollReallocation b ON b.BudgetPayrollReallocationGUID = ba.BudgetPayrollReallocationGUID + LEFT JOIN + (select SourceDepartmentID as DepartmentID, + SourceJobCodeID as JobCodeID, + FiscalYearID, + FiscalMonthID + FROM [mr].[BudgetReallocation] b + INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + WHERE DataType = 1 + UNION ALL + select TargetDepartmentID as DepartmentID, + TargetJobCodeID as JobCodeID, + FiscalYearID, + FiscalMonthID + FROM [mr].[BudgetReallocation] b + INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + WHERE DataType = 1 + ) fact on fact.DepartmentID = b.DepartmentID and fact.JobCodeID = b.JobCodeID and fact.FiscalYearID = b.FiscalYearID and fact.FiscalMonthID = ba.FiscalMonthID + WHERE (@fiscalYearID = 0 or b.FiscalYearID = @fiscalYearID) and fact.DepartmentID is null and b.Archived = 0 + UNION ALL + SELECT b.DepartmentID, + b.JobCodeID, + 0 as EmployeeID, + @ProdPayCodeID AS PayCodeID, + @ProdGroupID AS PayCodeGroupID, + b.FiscalYearID, + ba.FiscalMonthID, + 2 AS TimeClassID, -- always Budgeted + ba.ProductiveChange AS Hours, + 0 AS Dollars, + 0 AS FTEs + FROM mr.BudgetPayrollReallocationAdjustment ba + INNER JOIN mr.BudgetPayrollReallocation b ON b.BudgetPayrollReallocationGUID = ba.BudgetPayrollReallocationGUID + LEFT JOIN + (select SourceDepartmentID as DepartmentID, + SourceJobCodeID as JobCodeID, + FiscalYearID, + FiscalMonthID + FROM [mr].[BudgetReallocation] b + INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + WHERE DataType = 1 + UNION ALL + select TargetDepartmentID as DepartmentID, + TargetJobCodeID as JobCodeID, + FiscalYearID, + FiscalMonthID + FROM [mr].[BudgetReallocation] b + INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + WHERE DataType = 1 + ) fact on fact.DepartmentID = b.DepartmentID and fact.JobCodeID = b.JobCodeID and fact.FiscalYearID = b.FiscalYearID and fact.FiscalMonthID = ba.FiscalMonthID + WHERE (@fiscalYearID = 0 or b.FiscalYearID = @fiscalYearID) and fact.DepartmentID is null and b.Archived = 0 + + --run calculations + exec fw.procFactMonthlyMergeDuplicates '#PayrollSampledMonthlyDetailedStaging', 'JobCodeID,EmployeeID,PayCodeGroupID,PayCodeID', 'Dollars,Hours', @fiscalYearID, 0, 0 + --exec client.procPayrollMonthlyPostSampleAccrual --custom accrual process: customize it for different accruals, by default does nothing + exec fw.procFactPayrollSampledDetailedBaselineTargetUpdate @fiscalYearID = @fiscalYearID + exec fw.procFactMonthlyYTDPriorYearUpdateStaging 'fw.FactPayrollSampledMonthlyDetailed','#PayrollSampledMonthlyDetailedStaging','JobCodeID,EmployeeID,PayCodeGroupID,PayCodeID', 'Dollars,Hours', @fiscalYearID, 0, 0 + exec client.procFactPayrollSampledMonthlyDetailedFTEsInsertStaging + + print 'finish staging calculations --- '+convert(varchar(20),GETDATE(),113) + + -- insert result + IF @fiscalYearID = 0 + BEGIN + truncate table fw.FactPayrollSampledMonthlyDetailed + + -- split by batches + IF OBJECT_ID('tempdb..#inputDetails') IS NOT NULL DROP TABLE #inputDetails + SELECT + @fromClause = 'fw.PayrollSampledMonthlyDetailedStagingWithCalcs s', + @whereClause = '' + + EXEC mr.procGetIntBatchSize + @DefaultBatchSize = 60000000, + @ResultBatchSize = @batchSize OUTPUT + + CREATE TABLE #inputDetails (DepartmentID INT, RecordsCount INT, BatchID INT) + INSERT INTO #inputDetails + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 's', + @fromClause = @fromClause, + @whereClause = @whereClause, + @isDebug = 0 + + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDetails + + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + INSERT INTO fw.FactPayrollSampledMonthlyDetailed With (TABLOCKX) ( + DepartmentID, + FiscalMonthID, + FiscalYearID, + JobCodeID, + PayCodeID, + PayCodeGroupID, + EmployeeID, + TimeClassID, + Dollars, + DollarsYTD, + DollarsPriorYear, + DollarsPriorYTD, + Hours, + HoursYTD, + HoursPriorYear, + HoursPriorYTD, + FTEs, + FTEsYTD, + FTEsPriorYear, + FTEsPriorYTD, + IsDeleted, + IsSystemGenerated + ) + SELECT + S.DepartmentID, + S.FiscalMonthID, + S.FiscalYearID, + S.JobCodeID, + S.PayCodeID, + S.PayCodeGroupID, + S.EmployeeID, + S.TimeClassID, + S.Dollars, + S.DollarsYTD, + COALESCE(S.DollarsPriorYear,0), + S.DollarsPriorYTD, + S.Hours, + S.HoursYTD, + COALESCE(S.HoursPriorYear,0), + S.HoursPriorYTD, + S.FTEs, + S.FTEsYTD, + COALESCE(S.FTEsPriorYear,0), + COALESCE(S.FTEsPriorYTD,0), + 0 as IsDeleted, + isnull(S.IsSystemGenerated,0) as IsSystemGenerated + FROM fw.PayrollSampledMonthlyDetailedStagingWithCalcs S + INNER JOIN #inputDetails ISD ON ISD.DepartmentID = S.DepartmentID + WHERE ISD.BatchID = @BatchID + + SET @BatchID = @BatchID + 1 + END + END +ELSE + BEGIN + + print 'Starting creating index --- '+convert(varchar(20),GETDATE(),113) + CREATE CLUSTERED INDEX IDX_TempPayrollWithCalcs on fw.PayrollSampledMonthlyDetailedStagingWithCalcs (DepartmentID,JobCodeID,EmployeeID,PayCodeID,PayCodeGroupID,FiscalYearID,FiscalMonthID,TimeClassID) + print 'Starting transaction --- '+convert(varchar(20),GETDATE(),113) + + MERGE fw.FactPayrollSampledMonthlyDetailed With (TABLOCKX) AS target + USING fw.PayrollSampledMonthlyDetailedStagingWithCalcs AS source + ON source.DepartmentID = target.DepartmentID + AND source.JobCodeID = target.JobCodeID + AND source.EmployeeID = target.EmployeeID + AND source.PayCodeID = target.PayCodeID + AND source.PayCodeGroupID = target.PayCodeGroupID + AND source.FiscalYearID = target.FiscalYearID + AND source.FiscalMonthID = target.FiscalMonthID + AND source.TimeClassID = target.TimeClassID + AND source.PayCodeID = target.PayCodeID + WHEN MATCHED AND + (target.Dollars <> source.Dollars + or target.DollarsYTD <> source.DollarsYTD + or target.DollarsPriorYear <> COALESCE(source.DollarsPriorYear,0) + or target.DollarsPriorYTD <> COALESCE(source.DollarsPriorYTD,0) + or target.Hours <> source.Hours + or target.HoursYTD <> source.HoursYTD + or target.HoursPriorYear <> COALESCE(source.HoursPriorYear,0) + or target.HoursPriorYTD <> COALESCE(source.HoursPriorYTD,0) + or target.FTEs <> source.FTEs + or target.FTEsYTD <> source.FTEsYTD + or target.FTEsPriorYear <> COALESCE(source.FTEsPriorYear,0) + or target.FTEsPriorYTD <> COALESCE(source.FTEsPriorYTD,0) + or target.isSystemGenerated <> source.isSystemGenerated) + THEN + UPDATE + SET target.Dollars = source.Dollars, + target.DollarsYTD = source.DollarsYTD, + target.DollarsPriorYear = COALESCE(source.DollarsPriorYear,0), + target.DollarsPriorYTD = COALESCE(source.DollarsPriorYTD,0), + target.Hours = source.Hours, + target.HoursYTD = source.HoursYTD, + target.HoursPriorYear = COALESCE(source.HoursPriorYear,0), + target.HoursPriorYTD = COALESCE(source.HoursPriorYTD,0), + target.FTEs = source.FTEs, + target.FTEsYTD = source.FTEsYTD, + target.FTEsPriorYear = COALESCE(source.FTEsPriorYear,0), + target.FTEsPriorYTD = COALESCE(source.FTEsPriorYTD,0), + target.isSystemGenerated = source.isSystemGenerated + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + DepartmentID, + FiscalMonthID, + FiscalYearID, + JobCodeID, + PayCodeID, + PayCodeGroupID, + EmployeeID, + TimeClassID, + Dollars, + DollarsYTD, + DollarsPriorYear, + DollarsPriorYTD, + Hours, + HoursYTD, + HoursPriorYear, + HoursPriorYTD, + FTEs, + FTEsYTD, + FTEsPriorYear, + FTEsPriorYTD, + IsDeleted, + IsSystemGenerated + ) + VALUES ( + source.DepartmentID, + source.FiscalMonthID, + source.FiscalYearID, + source.JobCodeID, + source.PayCodeID, + source.PayCodeGroupID, + source.EmployeeID, + source.TimeClassID, + source.Dollars, + source.DollarsYTD, + COALESCE(source.DollarsPriorYear,0), + COALESCE(source.DollarsPriorYTD,0), + source.Hours, + source.HoursYTD, + COALESCE(source.HoursPriorYear,0), + COALESCE(source.HoursPriorYTD,0), + source.FTEs, + source.FTEsYTD, + COALESCE(source.FTEsPriorYear,0), + COALESCE(source.FTEsPriorYTD,0), + 0, + isnull(IsSystemGenerated,0) + ) + WHEN NOT MATCHED BY SOURCE + AND Target.FiscalYearID = @fiscalYearID + THEN + DELETE; + + END + + IF OBJECT_ID('tempdb..#PayrollSampledMonthlyDetailedStaging') IS NOT NULL DROP TABLE #PayrollSampledMonthlyDetailedStaging + IF OBJECT_ID('fw.PayrollSampledMonthlyDetailedStagingWithCalcs') IS NOT NULL DROP TABLE fw.PayrollSampledMonthlyDetailedStagingWithCalcs + IF OBJECT_ID('tempdb..#PayrollSampledMonthlyDetailedStaging') IS NOT NULL DROP TABLE #PayrollSampledMonthlyDetailedStaging +GO + + +--------------------------------------------- + +-- fw.procPayrollSampledMonthlyFlexInsert +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 5/10/16 NL B-11692 Including FiscalYearID in delete +** 2 02/20/2017 GF D-05545 Move duplicate record handling from YTD into sampling + general cleanup +*************************************************************/ +CREATE proc [fw].[procPayrollSampledMonthlyFlexInsert] + @fiscalyearid smallint +with recompile +AS + --delete existing data + WHILE EXISTS(SELECT NULL FROM fw.FactPayrollSampledMonthly (nolock) WHERE FiscalYearID = @fiscalYearID and TimeClassID = 4) BEGIN + DELETE TOP (10000) fw.FactPayrollSampledMonthly WHERE FiscalYearID = @fiscalYearID and TimeClassID = 4 + END + + --pull new data + CREATE TABLE #TEMPPAYROLL (DepartmentID int, JobCodeID int, PayCodeID int, PayCodeGroupID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, Hours money, Dollars money, FTEs decimal(18,6)); + INSERT INTO #TEMPPAYROLL(DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, TimeClassID, Hours, Dollars, FTEs) + SELECT + pr.DepartmentID, + pr.JobCodeID, + '0' as PayCodeID, + pc.PayCodeGroupID, + PR.FiscalYearID, + pr.FiscalMonthID, + pr.TimeClassID, + SUM(CASE WHEN pr.unittypeID = 51 and pc.IsHoursIgnored=0 then value ELSE 0 END) AS Hours, + SUM(CASE WHEN pr.unittypeID = 34 and pc.IsDollarsIgnored=0 then value ELSE 0 END) AS Dollars, + 0 as FTEs + FROM + int.FactStaffing pr + INNER JOIN fw.DimPayCode pc on pc.PayCodeID = PR.PayCodeID + WHERE + PR.FiscalMonthCode not in('', '0') + and pr.IsDeleted = 0 + and pr.Value != 0 + AND TimeClassID = 2 + AND FiscalYearID = @fiscalyearid + GROUP BY + pr.DepartmentID, + pr.JobCodeID, + pc.PayCodeGroupID, + PR.FiscalYearID, + pr.FiscalMonthID, + pr.TimeClassID + + --push to fact table + INSERT INTO fw.FactPayrollSampledMonthly(DepartmentID, JobCodeID, PayCodeID, PayCodeGroupID, FiscalYearID, FiscalMonthID, TimeClassID, Hours, Dollars, FTEs) + SELECT + DepartmentID, + JobCodeID, + PayCodeID, + PayCodeGroupID, + FiscalYearID, + FiscalMonthID, + 4, + SUM(Hours), + SUM(Dollars), + 0 as FTEs + FROM #TEMPPAYROLL + GROUP BY + DepartmentID, + JobCodeID, + PayCodeID, + PayCodeGroupID, + FiscalYearID, + FiscalMonthID, + TimeClassID + HAVING + SUM(Hours) != 0 + or SUM(Dollars) != 0 + + --run calculations + exec fw.procFactMonthlyMergeDuplicates 'fw.FactPayrollSampledMonthly', 'JobCodeID,PayCodeID,PayCodeGroupID', 'Dollars,Hours', @fiscalYearID, 4, 0 + exec fw.procFactMonthlyYTDPriorYearUpdate 'fw.FactPayrollSampledMonthly', 'JobCodeID,PayCodeID,PayCodeGroupID', 'Dollars,Hours', @fiscalYearID, 4, 0 +GO + + +--------------------------------------------- + +-- fw.procPayrollSampledMonthlyInsert +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2014-03-03 akk D-01526 Removing payroll import from sampling proc because it's redundant +** 2 2014-08-05 MJS B-02684 Updating sampling to include PayCodeGroupID +** 3 2014-09-03 MJS B-02863 Removing the parameter from the YTD proc call +** 4 2014-09-19 MJS B-02788 Setting PayCodeID to 0; Pay Code level data to be sourced from the PayrollSampledMonthlyDetailed data table +** 5 2015-10-28 MJS D-03587 Added logic to exclude ignored hours and dollars +** 6 2016-09-22 AK B-11845 Added procFactPayrollSampledBaselineTargetUpdate +** 7 2016-12-13 NL B-13759 Added fiscalYearID param and filtering +** 8 2017-02-20 GF D-05545 Move duplicate record handling from YTD into sampling + general cleanup +** 9 2017-02-22 IP B-14098 MR - Adjust Budgeted FTEs (Sampling). Added part that adds adjusted values to temp table #TEMPPAYROLL +** 10 2017-03-06 GF B-14693 Added baseline target year filter +** 11 2017-03-08 GF B-14693 Fix adjustment records year filter handling +** 12 2017-03-30 IP B-15085 Performace optimization by aggregating "detailed" data +** 13 2017-07-11 IP D-06150 Fixed conditions of merge statement (update part) +** 14 2017-07-25 IP B-17618 Applied logic for TimeClassID=20 when Target basis = "Prior Year" for FTE. Now it is equal to Prior Year hours divided by Prior Year FTE denominator. +** 15 2019-06-13 OV D-08158 Added join to jobcodegroup for Override +** 16 2019-06-19 OV TK-75157 FTEsPriorYear, FTEsPriorYTD are calculated incorrectly +** 17 2019-10-21 KF D-08819 FTE Baseline Calculation Issue +** 18 2023-09-14 KF JAZZ-55750 Remove filter to allow other time classes in MR reporting +*************************************************************/ +CREATE PROCEDURE [fw].[procPayrollSampledMonthlyInsert] @fiscalYearID SMALLINT = 0 +AS + --run custom scripts + exec [client].[procPayrollSampledInsertPreprocess] + + --delete existing data + IF(@fiscalYearID = 0) BEGIN + TRUNCATE TABLE fw.FactPayrollSampledMonthly + END ELSE BEGIN + DECLARE @batchSize INT + EXEC mr.procGetIntBatchSize + @DefaultBatchSize = 10000000, + @ResultBatchSize = @batchSize OUTPUT + + WHILE EXISTS(SELECT NULL FROM fw.FactPayrollSampledMonthly (nolock) WHERE FiscalYearID = @fiscalYearID) BEGIN + DELETE TOP (@batchSize) fw.FactPayrollSampledMonthly WHERE FiscalYearID = @fiscalYearID + END + END +/*If Target basis is rolling average then we can't calculate baseline as simple sum of detailed table. + in his case we should + 1)insert summed values for all timeclasses except baseline (TimeClassId = 20) + 2)recalculate baseline + 3)run stored procedure to update columns YTD, priorYear etc. +*/ +declare @TargetBasis int = (select Value from mr.SystemSetting where Name = 'Target Basis') +IF @TargetBasis = 10 -- rolling average +BEGIN +insert into fw.FactPayrollSampledMonthly ( + DepartmentID, + JobCodeID, + PayCodeID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + PayCodeGroupID, + IsSystemGenerated, + Hours, + HoursYTD, + HoursPriorYear, + HoursPriorYTD, + Dollars, + DollarsYTD, + DollarsPriorYear, + DollarsPriorYTD, + FTEs, + FTEsYTD, + FTEsPriorYear, + FTEsPriorYTD +) +SELECT fact.DepartmentID, + fact.JobCodeID, + fact.PayCodeID, + fact.FiscalYearID, + fact.FiscalMonthID, + fact.TimeClassID, + fact.PayCodeGroupID, + IsSystemGenerated = case when fact.Hours = 0 and fact.Dollars = 0 then 1 else 0 end, + fact.Hours, + fact.HoursYTD, + fact.HoursPriorYear, + fact.HoursPriorYTD, + fact.Dollars, + fact.DollarsYTD, + fact.DollarsPriorYear, + fact.DollarsPriorYTD, + FTEs = isnull(case when pcg.ProductiveClassID in ('3','2') then fact.Hours /wpmCY.Hours end,0), + FTEsYTD = isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursYTD /wpmCY.YTDHours end,0), + FTEsPriorYear = isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursPriorYear / wpmPY.Hours end,0), + FTEsPriorYTD = isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursPriorYTD / wpmPY.YTDHours end,0) +FROM ( + SELECT DepartmentID, + JobCodeID, + PayCodeID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + sum(Hours) AS Hours, + sum(HoursYTD) AS HoursYTD, + sum(HoursPriorYear) AS HoursPriorYear, + sum(HoursPriorYTD) AS HoursPriorYTD, + sum(Dollars) AS Dollars, + sum(DollarsYTD) AS DollarsYTD, + sum(DollarsPriorYear) AS DollarsPriorYear, + sum(DollarsPriorYTD) AS DollarsPriorYTD, + PayCodeGroupID, + IsSystemGenerated = min(cast(IsSystemGenerated as tinyint)) + FROM fw.FactPayrollSampledMonthlyDetailed + WHERE ( FiscalYearID = @fiscalYearID OR @fiscalYearID = 0) + and TimeClassID <> 20 -- all timeclasses except baseline (TimeClassId = 20) + GROUP BY DepartmentID, + JobCodeID, + PayCodeID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + PayCodeGroupID + ) fact + LEFT JOIN [fw].[DimDepartment] D + ON fact.DepartmentID = D.DepartmentID + LEFT JOIN [fw].[DimJobCode] JC + ON fact.JobCodeID = JC.JobCodeID + LEFT JOIN fw.DimJobCodeGroup JCG + ON JCG.JobCodeGroupID = JC.JobCodeGroupID + LEFT JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmCY + ON fact.FiscalMonthID = wpmCY.FiscalMonthID + AND fact.FiscalYearID = wpmCY.FiscalYearID + AND wpmCY.WorkWeekID = CASE WHEN jc.WorkWeekOverrideID = - 1 and jcg.WorkWeekOverrideID = - 1 THEN D.WorkWeekID ELSE + CASE WHEN jc.WorkWeekOverrideID = - 1 and jcg.WorkWeekOverrideID <> - 1 THEN jcg.WorkWeekOverrideID + ELSE jc.WorkWeekOverrideID END END + LEFT JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmPY + ON fact.FiscalMonthID = wpmPY.FiscalMonthID + AND (fact.FiscalYearID - 1) = wpmPY.FiscalYearID + AND wpmPY.WorkWeekID = CASE WHEN jc.WorkWeekOverrideID = - 1 and jcg.WorkWeekOverrideID = - 1 THEN D.WorkWeekID ELSE + CASE WHEN jc.WorkWeekOverrideID = - 1 and jcg.WorkWeekOverrideID <> - 1 THEN jcg.WorkWeekOverrideID + ELSE jc.WorkWeekOverrideID END END + LEFT JOIN fw.DimFiscalMonth fm + ON fact.FiscalMonthID = fm.FiscalMonthID + LEFT JOIN [fw].[DimPayCodeGroup] pcg + ON fact.PayCodeGroupID = pcg.PayCodeGroupID + WHERE fact.Hours <> 0 + or fact.HoursYTD <> 0 + or fact.HoursPriorYear <> 0 + or fact.HoursPriorYTD <> 0 + or fact.Dollars <> 0 + or fact.DollarsYTD <> 0 + or fact.DollarsPriorYear <> 0 + or fact.DollarsPriorYTD <> 0 + or isnull(case when pcg.ProductiveClassID in ('3','2') then fact.Hours /wpmCY.Hours end,0) <> 0 + or isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursYTD /wpmCY.YTDHours end,0) <> 0 + or isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursPriorYear / wpmPY.Hours end,0) <> 0 + or isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursPriorYTD / wpmPY.YTDHours end,0) <> 0 + + exec fw.procFactPayrollSampledBaselineTargetUpdate @fiscalYearID = @fiscalYearID -- recalculate baseline for just inserted values + exec fw.procFactMonthlyYTDPriorYearUpdate 'fw.FactPayrollSampledMonthly', 'JobCodeID,PayCodeGroupID,PayCodeID', 'Dollars,Hours', @fiscalYearID, 20, 0 -- update baseline records columns + + exec fw.procFactPayrollSampledMonthlyUpdateFTEs @fiscalYearID = @fiscalYearID, @timeClassID = 20 + +END +ELSE /*Here is inserting aggregated rows in case when "Target Basis" is not rolling average*/ +BEGIN +insert into fw.FactPayrollSampledMonthly ( + DepartmentID, + JobCodeID, + PayCodeID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + PayCodeGroupID, + IsSystemGenerated, + Hours, + HoursYTD, + HoursPriorYear, + HoursPriorYTD, + Dollars, + DollarsYTD, + DollarsPriorYear, + DollarsPriorYTD, + FTEs, + FTEsYTD, + FTEsPriorYear, + FTEsPriorYTD +) +SELECT fact.DepartmentID, + fact.JobCodeID, + fact.PayCodeID, + fact.FiscalYearID, + fact.FiscalMonthID, + fact.TimeClassID, + fact.PayCodeGroupID, + IsSystemGenerated = case when fact.Hours = 0 and fact.Dollars = 0 then 1 else 0 end, + fact.Hours, + fact.HoursYTD, + fact.HoursPriorYear, + fact.HoursPriorYTD, + fact.Dollars, + fact.DollarsYTD, + fact.DollarsPriorYear, + fact.DollarsPriorYTD, + FTEs = isnull(case when pcg.ProductiveClassID in ('3','2') then fact.Hours /wpmCY.Hours end,0), + FTEsYTD = isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursYTD /wpmCY.YTDHours end,0), + FTEsPriorYear = isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursPriorYear / wpmPY.Hours end,0), + FTEsPriorYTD = isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursPriorYTD / wpmPY.YTDHours end,0) +FROM ( + SELECT DepartmentID, + JobCodeID, + PayCodeID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + sum(Hours) AS Hours, + sum(HoursYTD) AS HoursYTD, + sum(HoursPriorYear) AS HoursPriorYear, + sum(HoursPriorYTD) AS HoursPriorYTD, + sum(Dollars) AS Dollars, + sum(DollarsYTD) AS DollarsYTD, + sum(DollarsPriorYear) AS DollarsPriorYear, + sum(DollarsPriorYTD) AS DollarsPriorYTD, + PayCodeGroupID, + IsSystemGenerated = min(cast(IsSystemGenerated as tinyint)) + FROM fw.FactPayrollSampledMonthlyDetailed + WHERE ( FiscalYearID = @fiscalYearID OR @fiscalYearID = 0) + GROUP BY DepartmentID, + JobCodeID, + PayCodeID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + PayCodeGroupID + ) fact + LEFT JOIN [fw].[DimDepartment] D + ON fact.DepartmentID = D.DepartmentID + LEFT JOIN [fw].[DimJobCode] JC + ON fact.JobCodeID = JC.JobCodeID + LEFT JOIN fw.DimJobCodeGroup JCG + ON JCG.JobCodeGroupID = JC.JobCodeGroupID + LEFT JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmCY + ON fact.FiscalMonthID = wpmCY.FiscalMonthID + AND ( + (@TargetBasis = 1 AND + ( + (fact.FiscalYearID-1 =wpmCY.FiscalYearID and TimeClassID = 20) + OR + (fact.FiscalYearID =wpmCY.FiscalYearID and TimeClassID <> 20) + ) + ) + OR + (@TargetBasis !=1 AND fact.FiscalYearID=wpmCY.FiscalYearID) + ) + AND wpmCY.WorkWeekID = CASE WHEN jc.WorkWeekOverrideID = - 1 and jcg.WorkWeekOverrideID = - 1 THEN D.WorkWeekID ELSE + CASE WHEN jc.WorkWeekOverrideID = - 1 and jcg.WorkWeekOverrideID <> - 1 THEN jcg.WorkWeekOverrideID + ELSE jc.WorkWeekOverrideID END END + LEFT JOIN [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmPY + ON fact.FiscalMonthID = wpmPY.FiscalMonthID + AND ( + (@TargetBasis = 1 AND + ( + (fact.FiscalYearID-2 =wpmPY.FiscalYearID and TimeClassID = 20) + OR + (fact.FiscalYearID-1 =wpmPY.FiscalYearID and TimeClassID <> 20) + ) + ) + OR + (@TargetBasis !=1 AND fact.FiscalYearID-1 = wpmPY.FiscalYearID) + ) + AND wpmPY.WorkWeekID = CASE WHEN jc.WorkWeekOverrideID = - 1 and jcg.WorkWeekOverrideID = - 1 THEN D.WorkWeekID ELSE + CASE WHEN jc.WorkWeekOverrideID = - 1 and jcg.WorkWeekOverrideID <> - 1 THEN jcg.WorkWeekOverrideID + ELSE jc.WorkWeekOverrideID END END + LEFT JOIN fw.DimFiscalMonth fm + ON fact.FiscalMonthID = fm.FiscalMonthID + LEFT JOIN [fw].[DimPayCodeGroup] pcg + ON fact.PayCodeGroupID = pcg.PayCodeGroupID + WHERE fact.Hours <> 0 + or fact.HoursYTD <> 0 + or fact.HoursPriorYear <> 0 + or fact.HoursPriorYTD <> 0 + or fact.Dollars <> 0 + or fact.DollarsYTD <> 0 + or fact.DollarsPriorYear <> 0 + or fact.DollarsPriorYTD <> 0 + or isnull(case when pcg.ProductiveClassID in ('3','2') then fact.Hours /wpmCY.Hours end,0) <> 0 + or isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursYTD /wpmCY.YTDHours end,0) <> 0 + or isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursPriorYear / wpmPY.Hours end,0) <> 0 + or isnull(case when pcg.ProductiveClassID in ('3','2') then fact.HoursPriorYTD / wpmPY.YTDHours end,0) <> 0 +END +GO + + +--------------------------------------------- + +-- fw.procPayrollSampledMonthlyPerformFlexing +/************************************************************************************************************************* +** Change History +************************************************************************************************************************** +** CID Date Author WI Description +** 1 5/10/2016 NL B-11692 Changed flexing to work like new ABB flexing procs +** 2 5/20/2016 NL B-12055 Removed call to insert flexed data (handled in engine now) +** 3 2/20/2017 GF D-05545 Move duplicate record handling from YTD into sampling + general cleanup +** 4 10/4/2017 NL D-06487 Fix some stuff that got lost including ABB dept join +** 5 10/22/2019 KF D-08819 FTE Baseline Calculation Issue +*************************************************************************************************************************/ +CREATE proc [fw].[procPayrollSampledMonthlyPerformFlexing] + @CostingResultID int, + @CostingTimeClassID tinyint, + @FiscalYearID int +with recompile +AS + + --reset all of the flex data to budget (only data that should be flexed like ABB) + SELECT DISTINCT DepartmentID + INTO #ABBDepts + from ( + SELECT DepartmentID FROM [dss].[FactCostingOutDetailGL] WHERE CostingResultID = @CostingResultID + UNION ALL + SELECT DepartmentID FROM [dss].[FactCostingOutDetailPayroll] WHERE CostingResultID = @CostingResultID) depts; + INSERT INTO [fw].[FactPayrollSampledMonthly]([DepartmentID], [JobCodeID], [PayCodeID], [FiscalYearID], [FiscalMonthID], [TimeClassID], [Hours], [HoursYTD], [HoursPriorYear], [HoursPriorYTD], [Dollars], [DollarsYTD], [DollarsPriorYear], [DollarsPriorYTD], [FTEs], [FTEsYTD], [FTEsPriorYear], [FTEsPriorYTD], [IsDeleted], [TransactionID], [PayCodeGroupID], [IsSystemGenerated]) + SELECT [DepartmentID], [JobCodeID], [PayCodeID], [FiscalYearID], [FiscalMonthID], 4, [Hours], [HoursYTD], [HoursPriorYear], [HoursPriorYTD], [Dollars], [DollarsYTD], [DollarsPriorYear], [DollarsPriorYTD], [FTEs], [FTEsYTD], [FTEsPriorYear], [FTEsPriorYTD], [IsDeleted], 12345, [PayCodeGroupID], [IsSystemGenerated] + FROM [fw].[FactPayrollSampledMonthly] + WHERE TimeClassID = 2 and FiscalYearID = @FiscalYearID and DepartmentID in ( select DepartmentID from #ABBDepts ); + + -- BEGIN CID 4 -- (this used to be right after the "run calculations" comment, before the other procs were called + exec [fw].[procFactMonthlyMergeDuplicates] 'fw.FactPayrollSampledMonthly', 'JobCodeID,PayCodeGroupID', 'Dollars,Hours', @fiscalYearID, 4, 0 + -- END CID 4 -- + + --perform flexing + UPDATE + pay + SET + pay.Dollars = CASE WHEN ISNULL(pay.Variability, 0) = 0 + THEN pay.Dollars + ELSE ISNULL(((pay.Dollars * (1 - (TotalVariableDirectCost / NULLIF(TotalCost, 0.0)))) + TotalExtendedVariableDirectCost), 0) + END + FROM + (SELECT pr.DepartmentID, pr.JobCodeID, pr.PayCodeGroupID, pr.FiscalYearID, pr.FiscalMonthID, pr.TimeClassID, pr.Dollars, ISNULL(jco.Variability, jc.Variability) as Variability + FROM [fw].[FactPayrollSampledMonthly] pr + LEFT JOIN (SELECT JobCodeID, Variability FROM [dss].[JobCodeVariability] WHERE CostingConfigGuid = (SELECT CostingConfigGuid FROM [dss].[CostingResult] WHERE CostingResultID = @CostingResultID)) jc ON pr.JobCodeID = jc.JobCodeID + LEFT JOIN (SELECT DepartmentID, JobCodeID, Variability FROM [dss].[PayCodeJobCodeVariabilityOverride] WHERE CostingConfigGuid = (SELECT CostingConfigGuid FROM [dss].[CostingResult] WHERE CostingResultID = @CostingResultID)) jco ON pr.DepartmentID = jco.DepartmentID AND pr.JobCodeID = jco.JobCodeID + WHERE TimeClassID = 4 AND FiscalYearID = @FiscalYearID) pay + INNER JOIN #ABBDepts abd on pay.DepartmentID = abd.DepartmentID + LEFT JOIN + (SELECT + DepartmentID, + JobCodeID, + PayCodeGroupID, + FiscalMonthID, + FiscalYearID, + SUM(cost.ExtendedVariableDirectCost) as TotalExtendedVariableDirectCost, + SUM(cost.TotalVariableDirectCost) as TotalVariableDirectCost, + SUM(cost.TotalCost) as TotalCost + FROM + [fw].[viewMRPayrollBudgetCostPerRVUbyMonth] cost + WHERE + cost.CostingResultID = @CostingResultID + AND + cost.TimeClassID = @CostingTimeClassID + GROUP BY + DepartmentID, JobCodeID, PayCodeGroupID, FiscalMonthID, FiscalYearID + ) cost + ON pay.DepartmentID = cost.DepartmentID + AND pay.JobCodeID = cost.JobCodeID + AND pay.PayCodeGroupID = cost.PayCodeGroupID + AND cost.FiscalMonthID = pay.FiscalMonthID + AND cost.FiscalYearID = pay.FiscalYearID + + DROP TABLE #ABBDepts; + + --run calculations + exec [fw].[procPayrollSampledMonthlyRecalcFlexedHours] @FiscalYearID = @FiscalYearID + exec [fw].[procFactMonthlyYTDPriorYearUpdate] 'fw.FactPayrollSampledMonthly', 'JobCodeID,PayCodeID,PayCodeGroupID', 'Dollars,Hours', @fiscalYearID, 4, 0 + exec [fw].[procFactPayrollSampledMonthlyUpdateFTEs] @fiscalYearID = @FiscalYearID, @timeClassID = 4 + + --delete blank rows + DELETE FROM [fw].[FactPayrollSampledMonthly] + WHERE + Hours = 0 + and HoursPriorYear = 0 + and HoursPriorYTD = 0 + and HoursYTD = 0 + and Dollars = 0 + and DollarsPriorYear = 0 + and DollarsPriorYTD = 0 + and DollarsYTD = 0 +GO + + +--------------------------------------------- + +-- fw.procPayrollSampledMonthlyRecalcFlexedHours +CREATE PROC [fw].[procPayrollSampledMonthlyRecalcFlexedHours] + @FiscalYearID smallint +AS + +/* ************************************************************************************************************************ +** Author: Nathan LeRoy +** Create Date: 2016-05-11 +** Description: Recalc payroll hours based on dollars flexing for MR +** Last Modified: 2016-05-11 +************************************************************************************************************************** +** Change History +************************************************************************************************************************** +** CID Date Author WI Description +** +*************************************************************************************************************************/ + +UPDATE + flex +SET + flex.Hours = COALESCE(flex.Dollars / NULLIF((orig.Dollars / NULLIF(orig.Hours, 0)), 0), 0) +FROM + [fw].[FactPayrollSampledMonthly] flex + LEFT JOIN + [fw].[FactPayrollSampledMonthly] orig + ON flex.DepartmentID = orig.DepartmentID + AND flex.JobCodeID = orig.JobCodeID + AND flex.PayCodeGroupID = orig.PayCodeGroupID + AND flex.PayCodeID = orig.PayCodeID + AND flex.FiscalYearID = orig.FiscalYearID + AND flex.FiscalMonthID = orig.FiscalMonthID +WHERE + orig.TimeClassID = 2 --budget + AND + flex.TimeClassID = 4 --flex + AND + orig.FiscalYearID = @FiscalYearID + AND + flex.FiscalYearID = @FiscalYearID +GO + + +--------------------------------------------- + +-- fw.procPayrollSampledPayPeriodDetailedInsert +/************************************************************ +** Change History +************************************************************** +** CID Date Author WI Description +** 1 9.19.14 MJS B-02788 Excluding Budget data from the detailed sample since budgeting at Pay Code level is not supported +** 2 2015-10-28 MJS D-03587 Added logic to exclude ignored hours and dollars +** 3 2016-09-22 AK B-11845 Added procFactPayrollSampledDetailedBaselineTargetUpdate +** 4 2016-12-13 NL B-13759 Added fiscalYearID param and filtering +** 5 2017-02-22 GF D-05545 Move duplicate record handling from YTD into sampling + general cleanup +** 6 2017-02-22 IP B-14098 MR - Adjust Budgeted FTEs (Sampling). Added part that adds adjusted values to temp table #TEMPPAYROLL +** 7 2017-03-06 GF B-14693 Added baseline target year filter +** 8 2017-03-08 GF B-14693 Fix adjustment records year filter handling +** 9 2017-04-11 IP B-15086 Sampling Performance Improvements. Using temp tables insead of fw.FactPayrollSampledMonthlyDetailed. +** 10 2017-06-12 IP Changed type of hours/dollars fields to numeric instead of "money" +** 11 2017-06-15 IP B-15086 Modify SP to use unique temp table +** 12 2017-07-11 IP D-06150 Fixed conditions of merge statement (update part) +** 13 2017-07-13 IP TK-45395 Fixed conditions of merge statement (include isSystemGenerated column) +** 14 2017-08-29 ip B-16798 Add using of Budget Adjustment. +** 15 2017-09-26 GF TK-48298 Fixed adjustments for all years case +** 16 2017-11-26 IP D-06490 Fixed splitting for first-last periods +** 17 2018-01-17 IP B-16703 Omit archived budget adjustments +** 18 2018-02-09 IP B-18724 Omit archived Budgeted FTE Adjustments +** 19 2018-02-22 IP D-06786 add department calculation for TC = 2 if dept is not in PR , Dept is in Budget Allocation +** 20 2018-05-17 IP D-07329 Returning fuctionality to include stats for departments using non-PR driver departments +** 21 2018-08-09 OV B-19715 added condition where IsPR = 1 for jobcode +** 22 2018-11-16 OV D-07714 fix: deleted rows where IsPR = 0 for department +** 23 2019-08-19 vfay D-08311 PR Sampling Proc : removed filtering out 0 Value Rows +** 24 2020-12-07 HV JAZZ-11135 Remove table variable in procPayrollSampledPayPeriodDetailedInsert +** 25 2020-12-15 HV JAZZ-11506 Bug - PR Sampling: data for beginning of future year is deleted when running Payroll Pay Period Detailed one year sampling +** 26 2020-12-21 HV JAZZ-10222 Proc procPayrollSampledPayPeriodDetailedInsert is timing out +** 27 2022-03-11 HV JAZZ-27781 Run PR Process Task can fail silently during Payroll Sampling +** 28 2022-10-25 HV JAZZ-45100 Reuse split by batches functionality in existing procedure +** 29 2023-12-04 ishah JAZZ-62485 Remove @departmentIDs param in procFactPayPeriodYTDPriorYearUpdate_Staging +*************************************************************/ +CREATE PROC [fw].[procPayrollSampledPayPeriodDetailedInsert] + @departmentIDs nvarchar(max) = null, + @fiscalYearID int = 0 +as + print 'Starting calculating staging table --- '+convert(varchar(20),GETDATE(),113) + IF OBJECT_ID('tempdb..#PayrollSampledPayPeriodDetailedStaging') IS NOT NULL DROP TABLE #PayrollSampledPayPeriodDetailedStaging + IF OBJECT_ID('tempdb..#PayrollSampledPayPeriodDetailedPreStaging') IS NOT NULL DROP TABLE #PayrollSampledPayPeriodDetailedPreStaging + IF OBJECT_ID('fw.PayrollSampledPayPeriodDetailedStagingWithCalcs') IS NOT NULL DROP TABLE fw.PayrollSampledPayPeriodDetailedStagingWithCalcs + + IF OBJECT_ID('tempdb..#DepartmentsBudgetAllocations') IS NOT NULL DROP TABLE #DepartmentsBudgetAllocations + CREATE table #DepartmentsBudgetAllocations (DepartmentID int) + insert into #DepartmentsBudgetAllocations + select + SourceDepartmentID as DepartmentID + from mr.BudgetReallocationAdjustment a + inner join mr.BudgetReallocation r on r.BudgetReallocationGUID=a.BudgetReallocationGUID + inner join FW.DimDepartment d on d.DepartmentID = r.TargetDepartmentID and d.IsPR = 1 + where SourceDepartmentID <> 0 + union -- unique + select + TargetDepartmentID as DepartmentID + from mr.BudgetReallocationAdjustment a + inner join mr.BudgetReallocation r on r.BudgetReallocationGUID=a.BudgetReallocationGUID + inner join FW.DimDepartment d on d.DepartmentID = r.SourceDepartmentID and d.IsPR = 1 -- Filtering all departments that move data FROM selected + where TargetDepartmentID <> 0 + + IF OBJECT_ID('tempdb..#PayPeriodIDs') IS NOT NULL DROP TABLE #PayPeriodIDs + CREATE TABLE #PayPeriodIDs (PayPeriodID smallint primary key) + insert into #PayPeriodIDs + select PayPeriodID from fw.DimPayPeriod where @fiscalYearID = 0 or FiscalYearIDSecond = @fiscalYearID + + IF OBJECT_ID('tempdb..#PayPeriodsToMonths') IS NOT NULL DROP TABLE #PayPeriodsToMonths + CREATE TABLE #PayPeriodsToMonths ( + PayPeriodID INT, + PayCycleID INT, + [PeriodNumber] INT, + [FiscalMonthID] INT, + [FiscalYearID] INT, + [PeriodWeight] NUMERIC(25, 10), + DaysinPeriodWeight NUMERIC(25, 10) + ) + + INSERT INTO #PayPeriodsToMonths + SELECT [PayPeriodID], + PayCycleID, + [PeriodNumber], + [FiscalMonthIDStart] AS FiscalMonthID, + [FiscalYearIDStart] AS FiscalYearID, + [PeriodWeightStart] AS PreriodWeight, + DaysinPeriodWeightStart as DaysinPeriodWeight + FROM [fw].[DimPayPeriod] + WHERE [PeriodWeightStart] <> 0.0 + UNION ALL + + SELECT [PayPeriodID], + PayCycleID, + [PeriodNumber], + FiscalMonthIDSecond AS FiscalMonthID, + FiscalYearIDSecond AS FiscalYearID, + PeriodWeightSecond AS PreriodWeight, + DaysinPeriodWeightSecond as DaysinPeriodWeight + FROM [fw].[DimPayPeriod] + WHERE PeriodWeightSecond <> 0.0 + + IF OBJECT_ID('tempdb..#PayrollPayPeriodTempTable') IS NOT NULL DROP TABLE #PayrollPayPeriodTempTable + CREATE TABLE #PayrollPayPeriodTempTable ( + DepartmentID INT, + JobCodeID INT, + PayCodeID INT, + PayCodeGroupID INT, + EmployeeID INT, + PayPeriodID int, + TimeClassID INT, + Hours NUMERIC(25, 10), + Dollars NUMERIC(25, 10), + ApplyDate DATETIME, + Src VARCHAR(max) + ) + + --pull new data - data integration + create table #PayrollSampledPayPeriodDetailedStaging (DepartmentID int, JobCodeID int, PayCodeID int, PayCodeGroupID int, EmployeeID int, PayPeriodID int, TimeClassID int, Hours decimal(18, 6), Dollars decimal(18, 6), isDeleted bit default (0), isSystemGenerated bit default(0)) + create table #PayrollSampledPayPeriodDetailedPreStaging (DepartmentID int, JobCodeID int, PayCodeID int, PayCodeGroupID int, EmployeeID int, PayPeriodID int, TimeClassID int, Hours decimal(18, 6), Dollars decimal(18, 6), isDeleted bit default (0), isSystemGenerated bit default(0)) + + insert into #PayrollSampledPayPeriodDetailedPreStaging (DepartmentID, JobCodeID,PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, TimeClassID, Hours, Dollars) + select + data.DepartmentID, + data.JobCodeID, + data.PayCodeID, + pc.PayCodeGroupID, + data.EmployeeID, + data.PayPeriodID, + data.TimeClassID, + sum(case when data.UnitTypeID = 51 then data.Value else 0 end) as Hours, + sum(case when data.UnitTypeID = 34 then data.Value else 0 end) as Dollars + from + int.FactStaffingByPayPeriod data + inner join [fw].[DimJobCode] jc on data.JobCodeID = jc.JobCodeID and IsPR = 1 + inner join [fw].[DimPayCode] pc on data.PayCodeID=pc.PayCodeID + inner join [fw].[DimPayPeriod] pp on data.PayPeriodID = pp.PayPeriodID + inner join [fw].[DimDepartment] d on d.DepartmentID = data.DepartmentID + where + data.PayPeriodID != 0 + and data.IsDeleted = 0 + and (d.IsPR = 1 or exists (select 1 from #DepartmentsBudgetAllocations dba where dba.DepartmentID = d.DepartmentID)) + and TimeClassID = 2 + and TimeClassID <> 20 + and (@fiscalYearID = 0 or pp.FiscalYearIDSecond = @fiscalYearID) + and ((data.UnitTypeID = 51 and pc.IsHoursIgnored = 0) or (data.UnitTypeID = 34 and pc.IsDollarsIgnored = 0)) + group by + data.DepartmentID, + data.JobCodeID, + data.PayCodeID, + pc.PayCodeGroupID, + data.EmployeeID, + data.PayPeriodID, + data.TimeClassID + + IF OBJECT_ID('tempdb..#DepartmentsBudgetAllocations') IS NOT NULL DROP TABLE #DepartmentsBudgetAllocations + + -- BudgetAdjustments Start + declare @iteration int = 1 + DECLARE @BudgetReallocationGUID uniqueidentifier,@date datetime,@BudgetReallocationType varchar(50) + + DECLARE BRA_cursor CURSOR FOR + SELECT distinct BudgetReallocationGUID,date,BudgetReallocationType from fw.BudgetReallocationWithDefinedType + WHERE (FiscalYearID = @FiscalYearID or @FiscalYearID = 0) and DataType = 1 + ORDER BY date; + + OPEN BRA_cursor + + FETCH NEXT FROM BRA_cursor + INTO @BudgetReallocationGUID,@date,@BudgetReallocationType + + WHILE @@FETCH_STATUS = 0 + BEGIN + + + BEGIN + INSERT INTO #PayrollPayPeriodTempTable(DepartmentID, JobCodeID, EmployeeID, PayCodeID, PayCodeGroupID, PayPeriodID, TimeClassID, Hours, Dollars) + SELECT TargetDepartmentID as DepartmentID,TargetJobCodeID as JobCodeID, stt.EmployeeID, stt.PayCodeID, stt.PayCodeGroupID, stt.PayPeriodID, stt.TimeClassID, + HOURS = STT.Hours*pptm.DaysinPeriodWeight, + Dollars = STT.Dollars*pptm.DaysinPeriodWeight + FROM #PayrollSampledPayPeriodDetailedPreStaging STT + inner join #PayPeriodsToMonths pptm on pptm.PayPeriodID = stt.PayPeriodID + INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceJobCodeID = stt.JobCodeID and b.FiscalYearID = pptm.FiscalYearID + INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and pptm.FiscalMonthID = ba.FiscalMonthID + where + b.BudgetReallocationGUID = @BudgetReallocationGUID + and TimeClassID = 2 + and DataType = 1 + and Archived = 0 + UNION + SELECT SourceDepartmentID as DepartmentID,SourceJobCodeID as JobCodeID, stt.EmployeeID, stt.PayCodeID, stt.PayCodeGroupID, stt.PayPeriodID, stt.TimeClassID, + HOURS = -STT.Hours*pptm.DaysinPeriodWeight, + Dollars = -STT.Dollars*pptm.DaysinPeriodWeight + FROM #PayrollSampledPayPeriodDetailedPreStaging STT + inner join #PayPeriodsToMonths pptm on pptm.PayPeriodID = stt.PayPeriodID + INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceJobCodeID = stt.JobCodeID and b.FiscalYearID = pptm.FiscalYearID + INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and pptm.FiscalMonthID = ba.FiscalMonthID + where + b.BudgetReallocationGUID = @BudgetReallocationGUID + and TimeClassID = 2 + and DataType = 1 + and Archived = 0 + + END + + set @iteration = @iteration +1 + + FETCH NEXT FROM BRA_cursor + INTO @BudgetReallocationGUID,@date,@BudgetReallocationType + END + CLOSE BRA_cursor; + DEALLOCATE BRA_cursor; + -- BudgetAdjustments END + --SplittingMonthsToPayPeriod + --insert into #PayrollSampledPayPeriodDetailedStaging (DepartmentID, JobCodeID,PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, TimeClassID, Hours, Dollars) + --SELECT fact.DepartmentID, JobCodeID,PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, TimeClassID, Hours*PeriodWeight, Dollars*PeriodWeight FROM #PayrollSampledMonthlyDetailedStaging fact + --INNER JOIN fw.DimDepartment dd on fact.DepartmentID = dd.DepartmentID + --INNER JOIN #PayPeriodsToMonths PP ON PP.FiscalYearID = fact.FiscalYearID + -- AND pp.FiscalMonthID = fact.FiscalMonthID + -- and pp.PayCycleID = dd.PayCycleID + + IF OBJECT_ID('tempdb..#PayPeriodsToMonths') IS NOT NULL DROP TABLE #PayPeriodsToMonths + +INSERT INTO #PayrollSampledPayPeriodDetailedStaging (DepartmentID, JobCodeID,PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, TimeClassID,Hours,Dollars) +SELECT DepartmentID,JobCodeID,PayCodeID,PayCodeGroupID,EmployeeID,PayPeriodID,TimeClassID,Hours,Dollars +FROM #PayrollPayPeriodTempTable + +IF OBJECT_ID('tempdb..#PayrollPayPeriodTempTable') IS NOT NULL DROP TABLE #PayrollPayPeriodTempTable + +insert into #PayrollSampledPayPeriodDetailedStaging (DepartmentID, JobCodeID,PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, TimeClassID, Hours, Dollars) +select + data.DepartmentID, + data.JobCodeID, + data.PayCodeID, + pc.PayCodeGroupID, + data.EmployeeID, + data.PayPeriodID, + data.TimeClassID, + sum(case when data.UnitTypeID = 51 then data.Value else 0 end) as Hours, + sum(case when data.UnitTypeID = 34 then data.Value else 0 end) as Dollars +from + int.FactStaffingByPayPeriod data + inner join [fw].[DimJobCode] jc on data.JobCodeID = jc.JobCodeID and IsPR = 1 + inner join [fw].[DimPayCode] pc on data.PayCodeID=pc.PayCodeID + inner join [fw].[DimPayPeriod] pp on data.PayPeriodID = pp.PayPeriodID + inner join [fw].[DimDepartment] d on d.DepartmentID = data.DepartmentID +where + data.PayPeriodID != 0 + and data.IsDeleted = 0 + and d.IsPR = 1 + and TimeClassID <> 20 + and (@fiscalYearID = 0 or pp.FiscalYearIDSecond = @fiscalYearID) + and ((data.UnitTypeID = 51 and pc.IsHoursIgnored = 0) or (data.UnitTypeID = 34 and pc.IsDollarsIgnored = 0)) +group by + data.DepartmentID, + data.JobCodeID, + data.PayCodeID, + pc.PayCodeGroupID, + data.EmployeeID, + data.PayPeriodID, + data.TimeClassID + + --pull new data - adjustments + DECLARE @NonProdGroupID INT = ( + SELECT TOP 1 pcg.PayCodeGroupID + FROM fw.DimProductiveClass pc + INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID + WHERE pc.Name = 'Non-Productive' AND pcg.PayCodeGroupID != 0 + ORDER BY pcg.SortOrder) + + DECLARE @ProdGroupID INT = ( + SELECT TOP 1 pcg.PayCodeGroupID + FROM fw.DimProductiveClass pc + INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID + WHERE pc.Name = 'Productive' AND pcg.PayCodeGroupID != 0 + ORDER BY pcg.SortOrder) + + DECLARE @NonProdPayCodeID INT = ( + SELECT TOP 1 pcg.DefaultPayCodeID + FROM fw.DimProductiveClass pc + INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID + WHERE pc.Name = 'Non-Productive' AND pcg.PayCodeGroupID != 0 + ORDER BY pcg.SortOrder) + + DECLARE @ProdPayCodeID INT = ( + SELECT TOP 1 pcg.DefaultPayCodeID + FROM fw.DimProductiveClass pc + INNER JOIN fw.DimPayCodeGroup pcg ON pcg.ProductiveClassID = pc.ProductiveClassID + WHERE pc.Name = 'Productive' AND pcg.PayCodeGroupID != 0 + ORDER BY pcg.SortOrder) + + INSERT INTO #PayrollSampledPayPeriodDetailedStaging (DepartmentID, JobCodeID,PayCodeID, PayCodeGroupID, EmployeeID, PayPeriodID, TimeClassID, Hours, Dollars) + SELECT + Adj.DepartmentID, + Adj.JobCodeID, + Adj.PayCodeId, + Adj.PayCodeGroupID, + 0 as EmployeeID, + PP.PayPeriodID, + 2 AS TimeClassID, -- always Budgeted + sum(Adj.Hours * PP.PreriodWeight) AS Hours, + 0 AS Dollars + FROM ( + SELECT + b.DepartmentID, + b.JobCodeID, + @ProdPayCodeID as PayCodeID, + @ProdGroupID AS PayCodeGroupID, + b.FiscalYearID, + ba.FiscalMonthID, + ba.ProductiveChange AS Hours + FROM mr.BudgetPayrollReallocationAdjustment ba + INNER JOIN mr.BudgetPayrollReallocation b ON b.BudgetPayrollReallocationGUID = ba.BudgetPayrollReallocationGUID + LEFT JOIN + (select SourceDepartmentID as DepartmentID, + SourceJobCodeID as JobCodeID, + FiscalYearID, + FiscalMonthID + FROM [mr].[BudgetReallocation] b + INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + WHERE DataType = 1 + UNION ALL + select TargetDepartmentID as DepartmentID, + TargetJobCodeID as JobCodeID, + FiscalYearID, + FiscalMonthID + FROM [mr].[BudgetReallocation] b + INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + WHERE DataType = 1 + ) fact on fact.DepartmentID = b.DepartmentID and fact.JobCodeID = b.JobCodeID and fact.FiscalYearID = b.FiscalYearID and fact.FiscalMonthID = ba.FiscalMonthID + WHERE (@fiscalYearID = 0 or b.FiscalYearID = @fiscalYearID) and fact.DepartmentID is null and b.Archived = 0 + UNION ALL + SELECT b.DepartmentID, + b.JobCodeID, + @NonProdPayCodeID as PayCodeID, + @NonProdGroupID AS PayCodeGroupID, + b.FiscalYearID, + ba.FiscalMonthID, + ba.NonProductiveChange AS Hours + FROM mr.BudgetPayrollReallocationAdjustment ba + INNER JOIN mr.BudgetPayrollReallocation b ON b.BudgetPayrollReallocationGUID = ba.BudgetPayrollReallocationGUID + LEFT JOIN + (select SourceDepartmentID as DepartmentID, + SourceJobCodeID as JobCodeID, + FiscalYearID, + FiscalMonthID + FROM [mr].[BudgetReallocation] b + INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + WHERE DataType = 1 + UNION ALL + select TargetDepartmentID as DepartmentID, + TargetJobCodeID as JobCodeID, + FiscalYearID, + FiscalMonthID + FROM [mr].[BudgetReallocation] b + INNER JOIN (select distinct FiscalMonthID,BudgetReallocationGUID from [mr].[BudgetReallocationAdjustment] where change <> 0) ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + WHERE DataType = 1 + ) fact on fact.DepartmentID = b.DepartmentID and fact.JobCodeID = b.JobCodeID and fact.FiscalYearID = b.FiscalYearID and fact.FiscalMonthID = ba.FiscalMonthID + WHERE (@fiscalYearID = 0 or b.FiscalYearID = @fiscalYearID) and fact.DepartmentID is null and b.Archived = 0 + ) AS Adj + INNER JOIN fw.DimJobCode jc ON jc.JobCodeID = Adj.JobCodeID and jc.IsPR = 1 + INNER JOIN fw.DimDepartment dd on adj.DepartmentID = dd.DepartmentID and dd.IsPR = 1 + INNER JOIN ( + SELECT + [PayPeriodID], + PayCycleID, + [PeriodNumber], + [FiscalMonthIDStart] AS FiscalMonthID, + [FiscalYearIDStart] AS FiscalYearID, + [PeriodWeightStart] AS PreriodWeight + FROM [fw].[DimPayPeriod] + WHERE (@fiscalYearID = 0 or [FiscalYearIDSecond] = @fiscalYearID) + UNION ALL + SELECT + [PayPeriodID], + PayCycleID, + [PeriodNumber], + FiscalMonthIDSecond AS FiscalMonthID, + FiscalYearIDSecond AS FiscalYearID, + PeriodWeightSecond AS PreriodWeight + FROM [fw].[DimPayPeriod] + WHERE (@fiscalYearID = 0 or [FiscalYearIDSecond] = @fiscalYearID) + ) PP ON PP.FiscalYearID = Adj.FiscalYearID + AND pp.FiscalMonthID = adj.FiscalMonthID + and pp.PayCycleID = dd.PayCycleID + GROUP BY Adj.DepartmentID, + Adj.JobCodeID, + Adj.PayCodeID, + Adj.PayCodeGroupID, + PP.PayPeriodID + + --run calculations on staging table + exec fw.procFactPayPeriodMergeDuplicates '#PayrollSampledPayPeriodDetailedStaging', 'JobCodeID,PayCodeID,PayCodeGroupID, EmployeeID', 'Dollars,Hours', @fiscalYearID, 0, 0, @departmentIDs + exec fw.procFactPayrollSampledPayPeriodDetailedBaselineTargetUpdate @departmentIDs = @departmentIDs, @fiscalYearID = @fiscalYearID + exec fw.procFactPayPeriodYTDPriorYearUpdate_Staging 'fw.FactPayrollSampledPayPeriodDetailed','#PayrollSampledPayPeriodDetailedStaging', 'JobCodeID,PayCodeID,PayCodeGroupID, EmployeeID', 'Dollars,Hours', @fiscalYearID, 0, 0 + + IF OBJECT_ID('tempdb..#PayrollSampledPayPeriodDetailedFTEs') IS NOT NULL DROP TABLE #PayrollSampledPayPeriodDetailedFTEs + CREATE TABLE #PayrollSampledPayPeriodDetailedFTEs (DepartmentID int,JobCodeID int,PayCodeID int,PayCodeGroupID int,EmployeeID int,PayPeriodID int,TimeClassID int, FTEs decimal(18, 6), FTEsYTD decimal(18, 6), FTEsPriorYear decimal(18, 6), FTEsPriorYTD decimal(18, 6)) + exec client.procFactPayrollSampledPayPeriodDetailedFTEsInsert_Staging @departmentIDs = @departmentIDs, @fiscalYearID = @fiscalYearID + + --!!!Removing all records where Department is not PR + delete fact + from fw.PayrollSampledPayPeriodDetailedStagingWithCalcs fact + inner join fw.dimDepartment d on d.DepartmentID = fact.DepartmentID and d.isPR = 0 + + IF @fiscalYearID = 0 and @departmentIDs is null + BEGIN + DECLARE @BatchSize INT = 50000000 + +-- Split data into batches + IF OBJECT_ID('tempdb..#inputPayPeriods') IS NOT NULL DROP TABLE #inputPayPeriods + + CREATE TABLE #inputPayPeriods (PayPeriodID INT, RecordsCount INT, BatchID INT) + INSERT INTO #inputPayPeriods + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'PayPeriodID', + @tableAlias = 'ps', + @fromClause = 'fw.PayrollSampledPayPeriodDetailedStagingWithCalcs ps', + @whereClause = '', + @isDebug = 0 + + DECLARE @BatchID INT, @MaxBatchID INT + SELECT @MaxBatchID = MAX(BatchID) FROM #inputPayPeriods + + truncate table fw.FactPayrollSampledPayPeriodDetailed + + IF @MaxBatchID >= 2 + BEGIN + CREATE CLUSTERED INDEX IDX_TempPayrollWithCalcs on fw.PayrollSampledPayPeriodDetailedStagingWithCalcs (PayPeriodID,DepartmentID,JobCodeID,EmployeeID,PayCodeID,PayCodeGroupID,TimeClassID) + END + + -- Loop thru batches and update data + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + INSERT INTO fw.FactPayrollSampledPayPeriodDetailed With (TABLOCKX) ( + DepartmentID, + PayPeriodID, + JobCodeID, + PayCodeID, + PayCodeGroupID, + EmployeeID, + TimeClassID, + Dollars, + DollarsYTD, + DollarsPriorYear, + DollarsPriorYTD, + Hours, + HoursYTD, + HoursPriorYear, + HoursPriorYTD, + FTEs, + FTEsYTD, + FTEsPriorYear, + FTEsPriorYTD, + IsDeleted, + IsSystemGenerated) + + SELECT fw.DepartmentID, + fw.PayPeriodID, + fw.JobCodeID, + fw.PayCodeID, + fw.PayCodeGroupID, + fw.EmployeeID, + fw.TimeClassID, + fw.Dollars, + fw.DollarsYTD, + fw.DollarsPriorYear, + fw.DollarsPriorYTD, + fw.Hours, + fw.HoursYTD, + fw.HoursPriorYear, + fw.HoursPriorYTD, + isnull(fte.FTEs,0) as FTEs, + isnull(fte.FTEsYTD,0) as FTEsYTD, + isnull(fte.FTEsPriorYear,0) as FTEsPriorYear, + isnull(fte.FTEsPriorYTD,0) as FTEsPriorYTD, + 0 as IsDeleted, + isnull(fw.IsSystemGenerated,0) as IsSystemGenerated + FROM fw.PayrollSampledPayPeriodDetailedStagingWithCalcs fw + inner join [fw].[DimJobCode] jc on fw.JobCodeID = jc.JobCodeID and IsPR = 1 + left join #PayrollSampledPayPeriodDetailedFTEs fte on fw.DepartmentID = fte.DepartmentID AND fw.JobCodeID = fte.JobCodeID AND fw.PayCodeID = fte.PayCodeID AND fw.PayCodeGroupID = fte.PayCodeGroupID AND fw.EmployeeID = fte.EmployeeID AND fw.PayPeriodID = fte.PayPeriodID AND fw.TimeClassID = fte.TimeClassID + INNER JOIN #inputPayPeriods IPP ON IPP.PayPeriodID = fw.PayPeriodID + WHERE IPP.BatchID = @BatchID + + SET @BatchID = @BatchID + 1 + END + END + ELSE + BEGIN + CREATE CLUSTERED INDEX IDX_TempPayrollWithCalcs on fw.PayrollSampledPayPeriodDetailedStagingWithCalcs (DepartmentID,JobCodeID,EmployeeID,PayCodeID,PayCodeGroupID,PayPeriodID,TimeClassID) + BEGIN TRANSACTION Sampling + BEGIN TRY + WITH TGT AS (SELECT t.* FROM + fw.FactPayrollSampledPayPeriodDetailed t With (TABLOCKX) + inner join #PayPeriodIDs ppt on t.PayPeriodID = ppt.PayPeriodID + ) + MERGE + TGT AS target + USING + (select + fw.DepartmentID, + fw.PayPeriodID, + fw.JobCodeID, + fw.PayCodeID, + fw.PayCodeGroupID, + fw.EmployeeID, + fw.TimeClassID, + fw.Dollars, + fw.DollarsYTD, + fw.DollarsPriorYear, + fw.DollarsPriorYTD, + fw.Hours, + fw.HoursYTD, + fw.HoursPriorYear, + fw.HoursPriorYTD, + isnull(fte.FTEs,0) as FTEs, + isnull(fte.FTEsYTD,0) as FTEsYTD, + isnull(fte.FTEsPriorYear,0) as FTEsPriorYear, + isnull(fte.FTEsPriorYTD,0) as FTEsPriorYTD, + 0 as IsDeleted, + isnull(fw.IsSystemGenerated,0) as IsSystemGenerated + from fw.PayrollSampledPayPeriodDetailedStagingWithCalcs fw + left join #PayrollSampledPayPeriodDetailedFTEs fte on fw.DepartmentID = fte.DepartmentID AND fw.JobCodeID = fte.JobCodeID AND fw.PayCodeID = fte.PayCodeID AND fw.PayCodeGroupID = fte.PayCodeGroupID AND fw.EmployeeID = fte.EmployeeID AND fw.PayPeriodID = fte.PayPeriodID AND fw.TimeClassID = fte.TimeClassID + ) AS source + ON source.DepartmentID = target.DepartmentID + AND source.JobCodeID = target.JobCodeID + AND source.EmployeeID = target.EmployeeID + AND source.PayCodeID = target.PayCodeID + AND source.PayCodeGroupID = target.PayCodeGroupID + AND source.PayPeriodID = target.PayPeriodID + AND source.TimeClassID = target.TimeClassID + AND source.PayCodeID = target.PayCodeID + WHEN MATCHED AND + (target.Dollars <> source.Dollars + or target.DollarsYTD <> source.DollarsYTD + or target.DollarsPriorYear <> source.DollarsPriorYear + or target.DollarsPriorYTD <> source.DollarsPriorYTD + or target.Hours <> source.Hours + or target.HoursYTD <> source.HoursYTD + or target.HoursPriorYear <> source.HoursPriorYear + or target.HoursPriorYTD <> source.HoursPriorYTD + or target.FTEs <> source.FTEs + or target.FTEsYTD <> source.FTEsYTD + or target.FTEsPriorYear <> source.FTEsPriorYear + or target.FTEsPriorYTD <> source.FTEsPriorYTD + or target.isSystemGenerated <> source.isSystemGenerated) + THEN + UPDATE + SET target.Dollars = source.Dollars, + target.DollarsYTD = source.DollarsYTD, + target.DollarsPriorYear = source.DollarsPriorYear, + target.DollarsPriorYTD = source.DollarsPriorYTD, + target.Hours = source.Hours, + target.HoursYTD = source.HoursYTD, + target.HoursPriorYear = source.HoursPriorYear, + target.HoursPriorYTD = source.HoursPriorYTD, + target.FTEs = source.FTEs, + target.FTEsYTD = source.FTEsYTD, + target.FTEsPriorYear = source.FTEsPriorYear, + target.FTEsPriorYTD = source.FTEsPriorYTD, + target.isSystemGenerated = source.isSystemGenerated + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + DepartmentID, + PayPeriodID, + JobCodeID, + PayCodeID, + PayCodeGroupID, + EmployeeID, + TimeClassID, + Dollars, + DollarsYTD, + DollarsPriorYear, + DollarsPriorYTD, + Hours, + HoursYTD, + HoursPriorYear, + HoursPriorYTD, + FTEs, + FTEsYTD, + FTEsPriorYear, + FTEsPriorYTD, + IsDeleted, + IsSystemGenerated + ) + VALUES ( + source.DepartmentID, + source.PayPeriodID, + source.JobCodeID, + source.PayCodeID, + source.PayCodeGroupID, + source.EmployeeID, + source.TimeClassID, + source.Dollars, + source.DollarsYTD, + source.DollarsPriorYear, + source.DollarsPriorYTD, + source.Hours, + source.HoursYTD, + source.HoursPriorYear, + source.HoursPriorYTD, + source.FTEs, + source.FTEsYTD, + source.FTEsPriorYear, + source.FTEsPriorYTD, + 0, + isnull(IsSystemGenerated,0) + ) + WHEN NOT MATCHED BY SOURCE + THEN + DELETE; + + COMMIT TRANSACTION Sampling + END TRY + BEGIN CATCH + ROLLBACK TRANSACTION Sampling; + THROW + END CATCH + END + + IF OBJECT_ID('tempdb..#PayrollSampledPayPeriodDetailedStaging') IS NOT NULL DROP TABLE #PayrollSampledPayPeriodDetailedStaging + IF OBJECT_ID('fw.PayrollSampledPayPeriodDetailedStagingWithCalcs') IS NOT NULL DROP TABLE fw.PayrollSampledPayPeriodDetailedStagingWithCalcs + IF OBJECT_ID('tempdb..#PayrollSampledMonthlyDetailedStaging') IS NOT NULL DROP TABLE #PayrollSampledMonthlyDetailedStaging + IF OBJECT_ID('tempdb..#PayrollSampledMonthlyDetailedPreStaging') IS NOT NULL DROP TABLE #PayrollSampledMonthlyDetailedPreStaging + IF OBJECT_ID('tempdb..#PayPeriodIDs') IS NOT NULL DROP TABLE #PayPeriodIDs +GO + + +--------------------------------------------- + +-- fw.procPayrollSampledPayPeriodInsert +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2013-09-19 AKK 64193 Changing source table to be int.FactStaffingByPayPeriod +** 2 2013-10-03 RA Updating proc to include db setting options +** 3 2014-06-24 JG B-02536 Updating Pay Code to be Pay Code Group +** 4 2014-09-03 MS B-02863 Removing the parameter from the YTD proc call +** 5 2014-11-23 JG Removing Flexing Piece +** 6 2015-02-19 JG Removing differential and non-fte pay code hours from the data +** 7 2015-04-20 MS Adding differential and non-fte pay code hours back. These hours are excluded from standard in pi.procCalculateProductivityMetrics and should be handled in report mappings. +** 8 2015-10-28 MJS D-03587 Added logic to exclude ignored hours and dollars +** 9 2016-02-29 MJS D-04023 Removed update of default payperiod +** 10 2016-04-28 AK B-11864 Added IsPR check +** 11 2016-10-04 MH B-13126 Added procFactPayrollSampledPayPeriodBaselineTargetUpdate +** 12 2017-01-31 AK B-13926 Added department filter +** 13 2017-02-08 GF B-14308 Added year filter +** 14 2017-02-20 GF D-05545 Move duplicate record handling from YTD into sampling +** 15 2017-02-20 GF D-05613 Prevent zero rows +** 16 2017-02-23 IP B-14063 Added functionality of adding rows with adjustment values to fw.FactPayrollSampledPayPeriod +** 17 2017-02-23 IP TK-39445 Fixed bug with incorrect accounting payperiod which belongs to 2 fiscal years +** 18 2017-03-08 GF B-14693 Fix adjustment records year filter handling +** 19 2017-03-30 IP B-15085 Performace optimization by aggregating "detailed" data +** 20 2017-04-11 IP D-05763 Replaced hardcoded value hours in pay period from 80.00 to (DimPayPeriod.WorkingDays * 8.0) +** 21 2017-05-29 ipetriv B-15994 Refactored sampling process and implemented using of staging tables +** 22 2017-06-15 IP B-15086 Modify SP to use unique temp table +** 23 2017-07-11 IP D-06152 Fixed conditions of merge statement (update part) +** 24 2017-10-04 GF D-06489 Fix pay period select when running all years +** 25 2018-02-02 GF TK-53716 Re-enable calculation of FTEs for non-standart work Weeks +** 26 2019-08-19 vfay D-08311 PR Sampling Proc : removed filtering out 0 Value Rows +** 27 2021-02-18 KF JAZZ-15158 Variable Productive Hours - Detailed Target Spread +** 28 2022-03-11 HV JAZZ-27781 Run PR Process Task can fail silently during Payroll Sampling +** 29 2023-12-04 ishah JAZZ-62485 Remove @departmentIDs param for procFactPayPeriodYTDPriorYearUpdate_AG +*************************************************************/ +CREATE proc [fw].[procPayrollSampledPayPeriodInsert] + @departmentIDs nvarchar(max) = null, + @fiscalYearID int = 0, + @useTargetOverrides bit = 0 +as + + IF OBJECT_ID('tempdb..#PayrollSampledPayPeriodStaging') IS NOT NULL DROP TABLE #PayrollSampledPayPeriodStaging + IF OBJECT_ID('fw.PayrollSampledPayPeriodStagingWithCalcs') IS NOT NULL DROP TABLE fw.PayrollSampledPayPeriodStagingWithCalcs + + declare @departments table(val int primary key) + insert into @departments select val from ConvertCSValuesToTable(@departmentIDs, ',') + + declare @payperiods table(val smallint primary key) + insert into @payperiods select PayPeriodID from fw.DimPayPeriod where FiscalYearIDSecond = @fiscalYearID or @fiscalYearID = 0 + + --run custom scripts + exec [client].[procPayrollSampledInsertPreprocess] + +/*If Target basis is rolling average then we can't calculate baseline as simple sum of detailed table. + in his case we should + 1)insert summed values for all timeclasses except baseline (TimeClassId = 20) + 2)recalculate baseline + 3)run stored procedure to update columns YTD, priorYear etc. +*/ + +SELECT DepartmentID, + JobCodeID, + WorkingHoursCoef = cast(dww.Hours AS NUMERIC(20, 6)) / 7 +INTO #WorkWeekHours +FROM ( + SELECT DepartmentID, + JobCodeID, + WorkWeekID = COALESCE(jc.WorkWeekID, de.WorkWeekID, - 1) + FROM ( + SELECT dp.DepartmentID, + WorkWeekID = CASE + WHEN e.WorkWeekID > - 1 + THEN e.WorkWeekID + ELSE NULL + END + FROM fw.DimEntity e + INNER JOIN fw.DimDepartment dp on e.EntityID = dp.EntityID + ) DE + CROSS JOIN ( + SELECT djc.JobCodeID, + djcg.JobCodeGroupID, + WorkWeekID = CASE + WHEN djc.WorkWeekOverrideID > - 1 + THEN djc.WorkWeekOverrideID + WHEN djc.WorkWeekOverrideID = - 1 + AND djcg.WorkWeekOverrideID > - 1 + THEN djcg.WorkWeekOverrideID + ELSE NULL + END + FROM fw.DimJobCode djc + INNER JOIN fw.DimJobCodeGroup djcg + ON djc.JobCodeGroupID = djcg.JobCodeGroupID + ) JC + ) DeptJobCode +LEFT JOIN fw.DimWorkWeek dww + ON DeptJobCode.WorkWeekID = dww.WorkWeekID + + +DECLARE @IsRollingAverage BIT +SELECT @IsRollingAverage = CASE WHEN Value = 10 THEN 1 ELSE 0 END from pi.SystemSetting where Name = 'Target Basis' + +IF (@IsRollingAverage = 1 OR @useTargetOverrides = 1) +BEGIN + CREATE TABLE #TimeClasses (TimeClassID tinyint Primary Key) + INSERT INTO #TimeClasses (TimeClassID) VALUES (1), (2) + IF(@IsRollingAverage = 0) + BEGIN + INSERT INTO #TimeClasses (TimeClassID) VALUES (20) + END + + SELECT fact.DepartmentID, + fact.JobCodeID, + fact.PayPeriodID, + fact.TimeClassID, + fact.PayCodeGroupID, + fact.IsSystemGenerated, + fact.Hours, + fact.HoursYTD, + fact.HoursPriorYear, + fact.HoursPriorYTD, + fact.Dollars, + fact.DollarsYTD, + fact.DollarsPriorYear, + fact.DollarsPriorYTD, + FTEs = isnull(CASE + WHEN pcg.ProductiveClassID IN ('3','2') AND pp.PeriodNumber != 0 + THEN CASE + WHEN WorkingHoursCoef IS NOT NULL + THEN (cast(fact.Hours AS NUMERIC(20, 6)) / cast(PeriodDays AS NUMERIC(20, 6))) -- fact hours per calendar day + / WorkingHoursCoef + ELSE fact.Hours / (WorkingDays * 8.0) + END + END, 0), + FTEsYTD = isnull(CASE + WHEN pcg.ProductiveClassID IN ('3','2') AND pp.PeriodNumber != 0 + THEN CASE + WHEN WorkingHoursCoef IS NOT NULL + THEN (cast(fact.HoursYTD AS NUMERIC(20, 6)) / (cast(PeriodDays AS NUMERIC(20, 6)) * cast(pp.PeriodNumber AS NUMERIC(20, 6)))) -- YTD hours / YTD days + / WorkingHoursCoef + ELSE fact.HoursYTD / (WorkingDays * 8.0 * pp.PeriodNumber) + END + END, 0), + FTEsPriorYear = isnull(CASE + WHEN pcg.ProductiveClassID IN ('3','2') AND pp.PeriodNumber != 0 + THEN CASE + WHEN WorkingHoursCoef IS NOT NULL + THEN (cast(fact.HoursPriorYear AS NUMERIC(20, 6)) / cast(PeriodDays AS NUMERIC(20, 6))) -- fact hours for Prior Year per calendar day + / WorkingHoursCoef + ELSE fact.HoursPriorYear / (WorkingDays * 8.0) + END + END, 0), + FTEsPriorYTD = isnull(CASE + WHEN pcg.ProductiveClassID IN ('3','2') AND pp.PeriodNumber != 0 + THEN CASE + WHEN WorkingHoursCoef IS NOT NULL + THEN (cast(fact.HoursPriorYTD AS NUMERIC(20, 6)) / (cast(PeriodDays AS NUMERIC(20, 6)) * cast(pp.PeriodNumber AS NUMERIC(20, 6)))) -- YTD for PY hours / YTD days + / WorkingHoursCoef + ELSE fact.HoursPriorYTD / (WorkingDays * 8.0 * pp.PeriodNumber) + END + END, 0) + INTO #PayrollSampledPayPeriodStaging + FROM ( + SELECT d.DepartmentID, + d.JobCodeID, + d.PayCodeGroupID, + d.PayPeriodID, + d.TimeClassID, + sum(d.Hours) AS Hours, + sum(d.HoursYTD) AS HoursYTD, + sum(d.HoursPriorYear) AS HoursPriorYear, + sum(d.HoursPriorYTD) AS HoursPriorYTD, + sum(d.Dollars) AS Dollars, + sum(d.DollarsYTD) AS DollarsYTD, + sum(d.DollarsPriorYear) AS DollarsPriorYear, + sum(d.DollarsPriorYTD) AS DollarsPriorYTD, + IsSystemGenerated = min(cast(IsSystemGenerated AS TINYINT)) + FROM fw.FactPayrollSampledPayPeriodDetailed d + INNER JOIN [fw].[DimPayPeriod] pp ON d.PayPeriodID = pp.PayPeriodID + INNER JOIN #TimeClasses TC ON TC.TimeClassID = d.TimeClassID + WHERE (@departmentIDs IS NULL OR d.DepartmentID IN (SELECT val FROM @departments)) + AND (@fiscalYearID = 0 OR pp.FiscalYearIDSecond = @fiscalYearID) + GROUP BY d.DepartmentID, + d.JobCodeID, + d.PayCodeGroupID, + d.PayPeriodID, + d.TimeClassID + ) fact + LEFT JOIN [fw].[DimPayPeriod] pp ON pp.PayPeriodID = fact.PayPeriodID + LEFT JOIN [fw].[DimPayCodeGroup] pcg ON fact.PayCodeGroupID = pcg.PayCodeGroupID + LEFT JOIN #WorkWeekHours ww ON ww.DepartmentID = fact.DepartmentID AND ww.JobCodeID = fact.JobCodeID + + IF(@IsRollingAverage = 1) exec fw.procFactPayrollSampledPayPeriodBaselineTargetUpdate @departmentIDs = @departmentIDs, @fiscalYearID = @fiscalYearID -- recalculate baseline + + IF(@useTargetOverrides = 1) exec fw.procFactPayrollSampledPayPeriodBaselineTargetOverridesUpdate + + exec fw.procFactPayPeriodYTDPriorYearUpdate_AG 'fw.FactPayrollSampledPayPeriod','#PayrollSampledPayPeriodStaging','JobCodeID,PayCodeGroupID', 'Dollars,Hours,FTEs', @fiscalYearID, 20, 0 -- recalculate for baseline rows + exec client.procFactPayrollSampledPayPeriodFTEsInsert_Staging @departmentIDs = @departmentIDs, @fiscalYearID = @fiscalYearID + + IF @fiscalYearID = 0 and @departmentIDs is null + BEGIN + truncate table fw.FactPayrollSampledPayPeriod + INSERT INTO fw.FactPayrollSampledPayPeriod With (TABLOCKX) ( + DepartmentID, + PayPeriodID, + JobCodeID, + PayCodeGroupID, + TimeClassID, + Dollars, + DollarsYTD, + DollarsPriorYear, + DollarsPriorYTD, + Hours, + HoursYTD, + HoursPriorYear, + HoursPriorYTD, + FTEs, + FTEsYTD, + FTEsPriorYear, + FTEsPriorYTD, + IsDeleted, + IsSystemGenerated) + + SELECT DepartmentID, + PayPeriodID, + JobCodeID, + PayCodeGroupID, + TimeClassID, + Dollars, + DollarsYTD, + DollarsPriorYear, + DollarsPriorYTD, + Hours, + HoursYTD, + HoursPriorYear, + HoursPriorYTD, + FTEs, + FTEsYTD, + FTEsPriorYear, + FTEsPriorYTD, + 0 as IsDeleted, + isnull(IsSystemGenerated,0) as IsSystemGenerated + FROM fw.PayrollSampledPayPeriodStagingWithCalcs + END + ELSE + BEGIN + print 'Starting creating index --- '+convert(varchar(20),GETDATE(),113) + CREATE CLUSTERED INDEX IDX_TempPayrollWithCalcs on fw.PayrollSampledPayPeriodStagingWithCalcs (DepartmentID,JobCodeID,PayCodeGroupID,PayPeriodID,TimeClassID) + print 'Starting transaction --- '+convert(varchar(20),GETDATE(),113) + BEGIN TRANSACTION Sampling + BEGIN TRY + WITH TGT AS (SELECT t.* FROM + fw.FactPayrollSampledPayPeriod t With (TABLOCKX) + inner join fw.DimPayPeriod pp on t.PayPeriodId = pp.PayPeriodID + where (@fiscalYearID = 0 or t.PayPeriodID in(select val from @payperiods)) + and (@departmentIDs is null or DepartmentID in(select val from @departments)) + ) + MERGE + TGT AS target + USING fw.PayrollSampledPayPeriodStagingWithCalcs AS source + ON source.DepartmentID = target.DepartmentID + AND source.JobCodeID = target.JobCodeID + AND source.PayCodeGroupID = target.PayCodeGroupID + AND source.PayPeriodID = target.PayPeriodID + AND source.TimeClassID = target.TimeClassID + WHEN MATCHED AND ( + target.Dollars <> source.Dollars + or target.DollarsYTD <> source.DollarsYTD + or target.DollarsPriorYear <> source.DollarsPriorYear + or target.DollarsPriorYTD <> source.DollarsPriorYTD + or target.Hours <> source.Hours + or target.HoursYTD <> source.HoursYTD + or target.HoursPriorYear <> source.HoursPriorYear + or target.HoursPriorYTD <> source.HoursPriorYTD + or target.FTEs <> source.FTEs + or target.FTEsYTD <> source.FTEsYTD + or target.FTEsPriorYear <> source.FTEsPriorYear + or target.FTEsPriorYTD <> source.FTEsPriorYTD + or target.isSystemGenerated <> source.isSystemGenerated) + THEN + UPDATE + SET target.Dollars = source.Dollars, + target.DollarsYTD = source.DollarsYTD, + target.DollarsPriorYear = source.DollarsPriorYear, + target.DollarsPriorYTD = source.DollarsPriorYTD, + target.Hours = source.Hours, + target.HoursYTD = source.HoursYTD, + target.HoursPriorYear = source.HoursPriorYear, + target.HoursPriorYTD = source.HoursPriorYTD, + target.FTEs = source.FTEs, + target.FTEsYTD = source.FTEsYTD, + target.FTEsPriorYear = source.FTEsPriorYear, + target.FTEsPriorYTD = source.FTEsPriorYTD, + target.isSystemGenerated = source.isSystemGenerated + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + DepartmentID, + PayPeriodID, + JobCodeID, + PayCodeGroupID, + TimeClassID, + Dollars, + DollarsYTD, + DollarsPriorYear, + DollarsPriorYTD, + Hours, + HoursYTD, + HoursPriorYear, + HoursPriorYTD, + FTEs, + FTEsYTD, + FTEsPriorYear, + FTEsPriorYTD, + IsDeleted, + IsSystemGenerated + ) + VALUES ( + source.DepartmentID, + source.PayPeriodID, + source.JobCodeID, + source.PayCodeGroupID, + source.TimeClassID, + source.Dollars, + source.DollarsYTD, + source.DollarsPriorYear, + source.DollarsPriorYTD, + source.Hours, + source.HoursYTD, + source.HoursPriorYear, + source.HoursPriorYTD, + source.FTEs, + source.FTEsYTD, + source.FTEsPriorYear, + source.FTEsPriorYTD, + 0, + isnull(IsSystemGenerated,0) + ) + WHEN NOT MATCHED BY SOURCE + THEN + DELETE; + + COMMIT TRANSACTION Sampling + END TRY + BEGIN CATCH + ROLLBACK TRANSACTION Sampling; + THROW + END CATCH + END + +END +ELSE /*Here is inserting aggregated rows in case when "Target Basis" is not rolling average and @useTargetOverrides = 0*/ +BEGIN + IF @fiscalYearID = 0 and @departmentIDs is null + BEGIN + truncate table fw.FactPayrollSampledPayPeriod + insert into fw.FactPayrollSampledPayPeriod ( + DepartmentID, + JobCodeID, + PayPeriodID, + TimeClassID, + PayCodeGroupID, + IsSystemGenerated, + Hours, + HoursYTD, + HoursPriorYear, + HoursPriorYTD, + Dollars, + DollarsYTD, + DollarsPriorYear, + DollarsPriorYTD, + FTEs, + FTEsYTD, + FTEsPriorYear, + FTEsPriorYTD + ) + SELECT fact.DepartmentID, + fact.JobCodeID, + fact.PayPeriodID, + fact.TimeClassID, + fact.PayCodeGroupID, + fact.IsSystemGenerated, + fact.Hours, + fact.HoursYTD, + fact.HoursPriorYear, + fact.HoursPriorYTD, + fact.Dollars, + fact.DollarsYTD, + fact.DollarsPriorYear, + fact.DollarsPriorYTD, + FTEs = isnull(CASE WHEN pcg.ProductiveClassID IN ('3','2') AND pp.PeriodNumber != 0 + THEN CASE + WHEN WorkingHoursCoef IS NOT NULL + THEN (cast(fact.Hours AS NUMERIC(20, 6)) / cast(PeriodDays AS NUMERIC(20, 6))) -- fact hours per calendar day + / WorkingHoursCoef + ELSE fact.Hours / (WorkingDays * 8.0) + END + END, 0), + FTEsYTD = isnull(CASE WHEN pcg.ProductiveClassID IN ('3','2') AND pp.PeriodNumber != 0 + THEN CASE + WHEN WorkingHoursCoef IS NOT NULL + THEN (cast(fact.HoursYTD AS NUMERIC(20, 6)) / (cast(PeriodDays AS NUMERIC(20, 6)) * cast(pp.PeriodNumber AS NUMERIC(20, 6)))) -- YTD hours / YTD days + / WorkingHoursCoef + ELSE fact.HoursYTD / (WorkingDays * 8.0 * pp.PeriodNumber) + END + END, 0), + FTEsPriorYear = isnull(CASE WHEN pcg.ProductiveClassID IN ('3','2') AND pp.PeriodNumber != 0 + THEN CASE + WHEN WorkingHoursCoef IS NOT NULL + THEN (cast(fact.HoursPriorYear AS NUMERIC(20, 6)) / cast(PeriodDays AS NUMERIC(20, 6))) -- fact hours for Prior Year per calendar day + / WorkingHoursCoef + ELSE fact.HoursPriorYear / (WorkingDays * 8.0) + END + END, 0), + FTEsPriorYTD = isnull(CASE WHEN pcg.ProductiveClassID IN ('3','2') AND pp.PeriodNumber != 0 + THEN CASE + WHEN WorkingHoursCoef IS NOT NULL + THEN (cast(fact.HoursPriorYTD AS NUMERIC(20, 6)) / (cast(PeriodDays AS NUMERIC(20, 6)) * cast(pp.PeriodNumber AS NUMERIC(20, 6)))) -- YTD for PY hours / YTD days + / WorkingHoursCoef + ELSE fact.HoursPriorYTD / (WorkingDays * 8.0 * pp.PeriodNumber) + END + END, 0) + FROM ( + SELECT + d.DepartmentID, + d.JobCodeID, + d.PayCodeGroupID, + d.PayPeriodID, + d.TimeClassID, + sum(d.Hours) AS Hours, + sum(d.HoursYTD) AS HoursYTD, + sum(d.HoursPriorYear) AS HoursPriorYear, + sum(d.HoursPriorYTD) AS HoursPriorYTD, + sum(d.Dollars) AS Dollars, + sum(d.DollarsYTD) AS DollarsYTD, + sum(d.DollarsPriorYear) AS DollarsPriorYear, + sum(d.DollarsPriorYTD) AS DollarsPriorYTD, + IsSystemGenerated = min(cast(IsSystemGenerated as tinyint)) + FROM fw.FactPayrollSampledPayPeriodDetailed d + INNER JOIN [fw].[DimPayPeriod] pp on d.PayPeriodID = pp.PayPeriodID + WHERE (@departmentIDs is null or d.DepartmentID in(select val from @departments)) + and (@fiscalYearID = 0 or pp.FiscalYearIDSecond = @fiscalYearID) + GROUP BY + d.DepartmentID, + d.JobCodeID, + d.PayCodeGroupID, + d.PayPeriodID, + d.TimeClassID + ) fact + left join [fw].[DimPayPeriod] pp on pp.PayPeriodID=fact.PayPeriodID + left join [fw].[DimPayCodeGroup] pcg on fact.PayCodeGroupID = pcg.PayCodeGroupID + left join #WorkWeekHours ww on ww.DepartmentID = fact.DepartmentID and ww.JobCodeID = fact.JobCodeID + END + ELSE + WITH TGT AS (SELECT t.* FROM + fw.FactPayrollSampledPayPeriod t With (TABLOCKX) + inner join fw.DimPayPeriod pp on t.PayPeriodId = pp.PayPeriodID + where (@fiscalYearID = 0 or t.PayPeriodID in(select val from @payperiods)) + and (@departmentIDs is null or DepartmentID in(select val from @departments)) + ) + MERGE + TGT AS target + USING ( + SELECT fact.DepartmentID, + fact.JobCodeID, + fact.PayPeriodID, + fact.TimeClassID, + fact.PayCodeGroupID, + fact.IsSystemGenerated, + fact.Hours, + fact.HoursYTD, + fact.HoursPriorYear, + fact.HoursPriorYTD, + fact.Dollars, + fact.DollarsYTD, + fact.DollarsPriorYear, + fact.DollarsPriorYTD, + FTEs = isnull(CASE WHEN pcg.ProductiveClassID IN ('3','2') AND pp.PeriodNumber != 0 + THEN CASE + WHEN WorkingHoursCoef IS NOT NULL + THEN (cast(fact.Hours AS NUMERIC(20, 6)) / cast(PeriodDays AS NUMERIC(20, 6))) -- fact hours per calendar day + / WorkingHoursCoef + ELSE fact.Hours / (WorkingDays * 8.0) + END + END, 0), + FTEsYTD = isnull(CASE WHEN pcg.ProductiveClassID IN ('3','2') AND pp.PeriodNumber != 0 + THEN CASE + WHEN WorkingHoursCoef IS NOT NULL + THEN (cast(fact.HoursYTD AS NUMERIC(20, 6)) / (cast(PeriodDays AS NUMERIC(20, 6)) * cast(pp.PeriodNumber AS NUMERIC(20, 6)))) -- YTD hours / YTD days + / WorkingHoursCoef + ELSE fact.HoursYTD / (WorkingDays * 8.0 * pp.PeriodNumber) + END + END, 0), + FTEsPriorYear = isnull(CASE WHEN pcg.ProductiveClassID IN ('3','2') AND pp.PeriodNumber != 0 + THEN CASE + WHEN WorkingHoursCoef IS NOT NULL + THEN (cast(fact.HoursPriorYear AS NUMERIC(20, 6)) / cast(PeriodDays AS NUMERIC(20, 6))) -- fact hours for Prior Year per calendar day + / WorkingHoursCoef + ELSE fact.HoursPriorYear / (WorkingDays * 8.0) + END + END, 0), + FTEsPriorYTD = isnull(CASE WHEN pcg.ProductiveClassID IN ('3','2') AND pp.PeriodNumber != 0 + THEN CASE + WHEN WorkingHoursCoef IS NOT NULL + THEN (cast(fact.HoursPriorYTD AS NUMERIC(20, 6)) / (cast(PeriodDays AS NUMERIC(20, 6)) * cast(pp.PeriodNumber AS NUMERIC(20, 6)))) -- YTD for PY hours / YTD days + / WorkingHoursCoef + ELSE fact.HoursPriorYTD / (WorkingDays * 8.0 * pp.PeriodNumber) + END + END, 0) + FROM ( + SELECT + d.DepartmentID, + d.JobCodeID, + d.PayCodeGroupID, + d.PayPeriodID, + d.TimeClassID, + sum(d.Hours) AS Hours, + sum(d.HoursYTD) AS HoursYTD, + sum(d.HoursPriorYear) AS HoursPriorYear, + sum(d.HoursPriorYTD) AS HoursPriorYTD, + sum(d.Dollars) AS Dollars, + sum(d.DollarsYTD) AS DollarsYTD, + sum(d.DollarsPriorYear) AS DollarsPriorYear, + sum(d.DollarsPriorYTD) AS DollarsPriorYTD, + IsSystemGenerated = min(cast(IsSystemGenerated as tinyint)) + FROM fw.FactPayrollSampledPayPeriodDetailed d + INNER JOIN [fw].[DimPayPeriod] pp on d.PayPeriodID = pp.PayPeriodID + WHERE (@departmentIDs is null or d.DepartmentID in(select val from @departments)) + and (@fiscalYearID = 0 or pp.FiscalYearIDSecond = @fiscalYearID) + GROUP BY + d.DepartmentID, + d.JobCodeID, + d.PayCodeGroupID, + d.PayPeriodID, + d.TimeClassID + ) fact + left join [fw].[DimPayPeriod] pp on pp.PayPeriodID=fact.PayPeriodID + left join [fw].[DimPayCodeGroup] pcg on fact.PayCodeGroupID = pcg.PayCodeGroupID + left join #WorkWeekHours ww on ww.DepartmentID = fact.DepartmentID and ww.JobCodeID = fact.JobCodeID + ) AS source + ON source.DepartmentID = target.DepartmentID + AND source.JobCodeID = target.JobCodeID + AND source.PayCodeGroupID = target.PayCodeGroupID + AND source.PayPeriodID = target.PayPeriodID + AND source.TimeClassID = target.TimeClassID + WHEN MATCHED AND ( + target.Dollars <> source.Dollars + or target.DollarsYTD <> source.DollarsYTD + or target.DollarsPriorYear <> source.DollarsPriorYear + or target.DollarsPriorYTD <> source.DollarsPriorYTD + or target.Hours <> source.Hours + or target.HoursYTD <> source.HoursYTD + or target.HoursPriorYear <> source.HoursPriorYear + or target.HoursPriorYTD <> source.HoursPriorYTD + or target.FTEs <> source.FTEs + or target.FTEsYTD <> source.FTEsYTD + or target.FTEsPriorYear <> source.FTEsPriorYear + or target.FTEsPriorYTD <> source.FTEsPriorYTD + or target.isSystemGenerated <> source.isSystemGenerated) + THEN + UPDATE + SET target.Dollars = source.Dollars, + target.DollarsYTD = source.DollarsYTD, + target.DollarsPriorYear = source.DollarsPriorYear, + target.DollarsPriorYTD = source.DollarsPriorYTD, + target.Hours = source.Hours, + target.HoursYTD = source.HoursYTD, + target.HoursPriorYear = source.HoursPriorYear, + target.HoursPriorYTD = source.HoursPriorYTD, + target.FTEs = source.FTEs, + target.FTEsYTD = source.FTEsYTD, + target.FTEsPriorYear = source.FTEsPriorYear, + target.FTEsPriorYTD = source.FTEsPriorYTD, + target.isSystemGenerated = source.isSystemGenerated + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + DepartmentID, + PayPeriodID, + JobCodeID, + PayCodeGroupID, + TimeClassID, + Dollars, + DollarsYTD, + DollarsPriorYear, + DollarsPriorYTD, + Hours, + HoursYTD, + HoursPriorYear, + HoursPriorYTD, + FTEs, + FTEsYTD, + FTEsPriorYear, + FTEsPriorYTD, + IsDeleted, + IsSystemGenerated + ) + VALUES ( + source.DepartmentID, + source.PayPeriodID, + source.JobCodeID, + source.PayCodeGroupID, + source.TimeClassID, + source.Dollars, + source.DollarsYTD, + source.DollarsPriorYear, + source.DollarsPriorYTD, + source.Hours, + source.HoursYTD, + source.HoursPriorYear, + source.HoursPriorYTD, + source.FTEs, + source.FTEsYTD, + source.FTEsPriorYear, + source.FTEsPriorYTD, + 0, + isnull(IsSystemGenerated,0) + ) + WHEN NOT MATCHED BY SOURCE + THEN + DELETE; +END +GO + + +--------------------------------------------- + +-- fw.procPlanTypeCreateMaintenanceCustomScriptStub +CREATE proc [fw].[procPlanTypeCreateMaintenanceCustomScriptStub] + @schema sysname, + @plantypename nvarchar(100) +as + +declare @ptguid uniqueidentifier +select @ptguid = plantypeguid from PlanType where Name = @plantypename + +if @ptguid is null begin + print 'invalid plantype name' + return +end + +declare @cs1guid uniqueidentifier +declare @cs2guid uniqueidentifier +declare @cnt int + +select + @cs1guid = cs.CustomScriptGUID, + @cs2guid = cs2.CustomScriptGUID, + @cnt = case when coalesce(cs.name,cs2.name) = @plantypename + ' Maintenance' then 1 else 0 end +from + PlanType pt + left join CustomScript cs on pt.OnSaveCustomScriptGUID = cs.CustomScriptGUID + left join CustomScript cs2 on pt.OnSaveCustomScript2GUID = cs2.CustomScriptGUID +where + pt.PlanTypeGUID = @ptguid + +if @cnt > 0 begin + print 'maintenance script already exists' + return +end + +if not @cs1guid is null and not @cs2guid is null begin + print 'no onsave slots left' + return +end + +declare @sql nvarchar(max) +set @sql = ' +create proc [' + @schema + '].[proc' + replace(@plantypename, ' ','') + 'Maintenance] + @planguid uniqueidentifier +as + + --do plan maintenance here +' +exec (@sql) + +declare @scriptguid uniqueidentifier +set @scriptguid = NEWID() + +insert into CustomScript ( CustomScriptGUID,Name, ScriptText, IsSynchronous) +values (@scriptguid,@plantypename + ' Maintenance', 'exec [' + @schema + '].[proc' + replace(@plantypename, ' ','') + 'Maintenance] @planGuidList',1) + +if @cs1guid is null begin + update PlanType set OnSaveCustomScriptGUID = @scriptguid where plantypeguid = @ptguid +end else begin + update PlanType set OnSaveCustomScript2GUID = @scriptguid where plantypeguid = @ptguid +end + +set @sql = ' +alter proc [' + @schema + '].[proc' + replace(@plantypename, ' ','') + 'Maintenance] + @planguid uniqueidentifier +as + + --do plan maintenance here +go +' + +print @sql +GO + + +--------------------------------------------- + +-- fw.procPostDiMergeEncounterBasedStatistics +CREATE PROC fw.procPostDiMergeEncounterBasedStatistics + @statisticId int, + @year int, + @months SqlInt32ListTableType READONLY +AS +BEGIN + SET NOCOUNT ON + + CREATE TABLE #detailsToMerge + ( + RowID bigint identity(1,1), + DateID int, + DepartmentID int, + AccountID int, + Value decimal(19, 4) + ) + CREATE CLUSTERED INDEX CNU_RowId ON #detailsToMerge(RowId) + + INSERT #detailsToMerge (DepartmentID, AccountID, DateID, Value) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, SUM(ebs.Value) + FROM fw.FactEncounterBasedStatistics ebs + JOIN fw.DimDate d ON ebs.DateID = d.DateID + JOIN @months m ON d.CalendarMonth = m.value + WHERE ebs.StatisticID = @statisticId + AND d.FiscalYear = @year + GROUP BY ebs.DepartmentID, ebs.AccountID, ebs.DateID + + CREATE TABLE #batch + ( + DateID int, + DepartmentID int, + AccountID int, + Value decimal(19, 4) + ) + + DECLARE + @startRowId bigint, + @maxRowId bigint, + @endRowId bigint + + SELECT @startRowId = MIN(RowId), @maxRowId = MAX(RowId) + FROM #detailsToMerge + + WHILE (@startRowId <= @maxRowId) + BEGIN + SELECT @endRowId = MAX(d.RowId) + FROM (SELECT TOP 1000000 RowId + FROM #detailsToMerge + WHERE RowId >= @startRowId + ORDER BY RowID) as d + + TRUNCATE TABLE #batch + + INSERT #batch (DepartmentID, AccountID, DateID, Value) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, ebs.Value + FROM #detailsToMerge ebs + WHERE ebs.RowId >= @startRowId + AND ebs.RowId <= @endRowId + + UPDATE fw.FactChargeBasedStatistics + SET Value = ebs.Value + FROM fw.FactChargeBasedStatistics cbs + JOIN #batch ebs + ON cbs.DepartmentID = ebs.DepartmentID + AND cbs.AccountID = ebs.AccountID + AND cbs.DateID = ebs.DateID + + INSERT fw.FactChargeBasedStatistics (DepartmentID, AccountID, DateID, Value) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, ebs.Value + FROM #batch ebs + WHERE NOT EXISTS + ( + SELECT cbs.RowID + FROM fw.FactChargeBasedStatistics cbs + WHERE ebs.DepartmentID = cbs.DepartmentID + AND ebs.AccountID = cbs.AccountID + AND ebs.DateID = cbs.DateID + ) + + SELECT @startRowId = MIN(d.RowId) + FROM #detailsToMerge d + WHERE RowId > @endRowId + END + + DROP TABLE IF EXISTS #detailsToMerge + DROP TABLE IF EXISTS #batch +END +GO + + +--------------------------------------------- + +-- fw.procPostDiMergeEncounterBasedStatisticsMonthly +CREATE PROC fw.procPostDiMergeEncounterBasedStatisticsMonthly + @statisticId int, + @year int, + @months SqlInt32ListTableType READONLY +AS +BEGIN + SET NOCOUNT ON + + DROP TABLE IF EXISTS #detailsToMerge + + CREATE TABLE #detailsToMerge + ( + FiscalYearID smallint, + FiscalMonthID tinyint, + DepartmentID int, + AccountID int, + Value decimal(19, 4) + ) + + INSERT #detailsToMerge (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.FiscalYearID, ebs.FiscalMonthID, ebs.Value + FROM fw.FactEncounterBasedStatisticsMonthly ebs + JOIN @months s ON ebs.FiscalMonthID = s.value + WHERE ebs.FiscalYearID = @year + AND ebs.StatisticID = @statisticId + + UPDATE #detailsToMerge + SET Value = aggr.AggregatedValue + FROM + ( + SELECT ebs.FiscalYearID, ebs.FiscalMonthID, ebs.DepartmentID, ebs.AccountID, SUM(ebs.Value) AS AggregatedValue + FROM #detailsToMerge d + JOIN fw.FactEncounterBasedStatisticsMonthly ebs + ON ebs.DepartmentID = d.DepartmentID + AND ebs.AccountID = d.AccountID + AND ebs.FiscalYearID = d.FiscalYearID + AND ebs.FiscalMonthID = d.FiscalMonthID + GROUP BY ebs.FiscalYearID, ebs.FiscalMonthID, ebs.DepartmentID, ebs.AccountID + ) aggr + JOIN #detailsToMerge det + ON aggr.DepartmentID = det.DepartmentID + AND aggr.AccountID = det.AccountID + AND aggr.FiscalYearID = det.FiscalYearID + AND aggr.FiscalMonthID = det.FiscalMonthID + + UPDATE fw.FactChargeBasedStatisticsMonthly + SET Value = ebs.Value + FROM #detailsToMerge ebs + JOIN fw.FactChargeBasedStatisticsMonthly cbs + ON ebs.DepartmentID = cbs.DepartmentID + AND ebs.AccountID = cbs.AccountID + AND ebs.FiscalYearID = cbs.FiscalYearID + AND ebs.FiscalMonthID = cbs.FiscalMonthID + + INSERT fw.FactChargeBasedStatisticsMonthly (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.FiscalYearID, ebs.FiscalMonthID, ebs.Value + FROM #detailsToMerge ebs + WHERE NOT EXISTS + ( + SELECT cbs.RowID + FROM fw.FactChargeBasedStatisticsMonthly cbs + WHERE ebs.DepartmentID = cbs.DepartmentID + AND ebs.AccountID = cbs.AccountID + AND ebs.FiscalYearID = cbs.FiscalYearID + AND ebs.FiscalMonthID = cbs.FiscalMonthID + ) +END +GO + + +--------------------------------------------- + +-- fw.procPostDiMergeEncounterBasedStatisticsMonthlyOpt +CREATE PROC fw.procPostDiMergeEncounterBasedStatisticsMonthlyOpt +AS +BEGIN + SET NOCOUNT ON + + DROP TABLE IF EXISTS #detailsToMerge + + CREATE TABLE #detailsToMerge + ( + FiscalYearID smallint, + FiscalMonthID tinyint, + DepartmentID int, + AccountID int, + Value decimal(19, 4) + ) + + INSERT #detailsToMerge (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.FiscalYearID, ebs.FiscalMonthID, ebs.Value + FROM fw.FactEncounterBasedStatisticsMonthly ebs + JOIN data.EbsPostDiCacheMonthly c + ON ebs.StatisticID = c.StatisticID + AND ebs.FiscalYearID = c.Year + AND ebs.FiscalMonthID = c.Month + + UPDATE #detailsToMerge + SET Value = aggr.AggregatedValue + FROM + ( + SELECT ebs.FiscalYearID, ebs.FiscalMonthID, ebs.DepartmentID, ebs.AccountID, SUM(ebs.Value) AS AggregatedValue + FROM #detailsToMerge d + JOIN fw.FactEncounterBasedStatisticsMonthly ebs + ON ebs.DepartmentID = d.DepartmentID + AND ebs.AccountID = d.AccountID + AND ebs.FiscalYearID = d.FiscalYearID + AND ebs.FiscalMonthID = d.FiscalMonthID + GROUP BY ebs.FiscalYearID, ebs.FiscalMonthID, ebs.DepartmentID, ebs.AccountID + ) aggr + JOIN #detailsToMerge det + ON aggr.DepartmentID = det.DepartmentID + AND aggr.AccountID = det.AccountID + AND aggr.FiscalYearID = det.FiscalYearID + AND aggr.FiscalMonthID = det.FiscalMonthID + + UPDATE fw.FactChargeBasedStatisticsMonthly + SET Value = ebs.Value + FROM #detailsToMerge ebs + JOIN fw.FactChargeBasedStatisticsMonthly cbs + ON ebs.DepartmentID = cbs.DepartmentID + AND ebs.AccountID = cbs.AccountID + AND ebs.FiscalYearID = cbs.FiscalYearID + AND ebs.FiscalMonthID = cbs.FiscalMonthID + + INSERT fw.FactChargeBasedStatisticsMonthly (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.FiscalYearID, ebs.FiscalMonthID, ebs.Value + FROM #detailsToMerge ebs + WHERE NOT EXISTS + ( + SELECT cbs.RowID + FROM fw.FactChargeBasedStatisticsMonthly cbs + WHERE ebs.DepartmentID = cbs.DepartmentID + AND ebs.AccountID = cbs.AccountID + AND ebs.FiscalYearID = cbs.FiscalYearID + AND ebs.FiscalMonthID = cbs.FiscalMonthID + ) +END +GO + + +--------------------------------------------- + +-- fw.procPostDiMergeEncounterBasedStatisticsOpt +CREATE PROC fw.procPostDiMergeEncounterBasedStatisticsOpt +AS +BEGIN + SET NOCOUNT ON + + CREATE TABLE #detailsToMerge + ( + RowID bigint identity(1,1), + DateID int, + DepartmentID int, + AccountID int, + Value decimal(19, 4) + ) + CREATE CLUSTERED INDEX CNU_RowId ON #detailsToMerge(RowId) + + INSERT #detailsToMerge (DepartmentID, AccountID, DateID, Value) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, SUM(ebs.Value) + FROM fw.FactEncounterBasedStatistics ebs + JOIN fw.DimDate d ON ebs.DateID = d.DateID + JOIN data.EbsPostDiCache c + ON ebs.StatisticID = c.StatisticID + AND d.FiscalYear = c.Year + AND d.CalendarMonth = c.Month + GROUP BY ebs.DepartmentID, ebs.AccountID, ebs.DateID + + CREATE TABLE #batch + ( + DateID int, + DepartmentID int, + AccountID int, + Value decimal(19, 4) + ) + + DECLARE + @startRowId bigint, + @maxRowId bigint, + @endRowId bigint + + SELECT @startRowId = MIN(RowId), @maxRowId = MAX(RowId) + FROM #detailsToMerge + + WHILE (@startRowId <= @maxRowId) + BEGIN + SELECT @endRowId = MAX(d.RowId) + FROM (SELECT TOP 1000000 RowId + FROM #detailsToMerge + WHERE RowId >= @startRowId + ORDER BY RowID) as d + + TRUNCATE TABLE #batch + + INSERT #batch (DepartmentID, AccountID, DateID, Value) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, ebs.Value + FROM #detailsToMerge ebs + WHERE ebs.RowId >= @startRowId + AND ebs.RowId <= @endRowId + + UPDATE fw.FactChargeBasedStatistics + SET Value = ebs.Value + FROM fw.FactChargeBasedStatistics cbs + JOIN #batch ebs + ON cbs.DepartmentID = ebs.DepartmentID + AND cbs.AccountID = ebs.AccountID + AND cbs.DateID = ebs.DateID + + INSERT fw.FactChargeBasedStatistics (DepartmentID, AccountID, DateID, Value) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, ebs.Value + FROM #batch ebs + WHERE NOT EXISTS + ( + SELECT cbs.RowID + FROM fw.FactChargeBasedStatistics cbs + WHERE ebs.DepartmentID = cbs.DepartmentID + AND ebs.AccountID = cbs.AccountID + AND ebs.DateID = cbs.DateID + ) + + SELECT @startRowId = MIN(d.RowId) + FROM #detailsToMerge d + WHERE RowId > @endRowId + END + + DROP TABLE IF EXISTS #detailsToMerge + DROP TABLE IF EXISTS #batch +END +GO + + +--------------------------------------------- + +-- fw.procPostDiRestoreChargeBasedStatistics +CREATE PROC fw.procPostDiRestoreChargeBasedStatistics + @statisticId int, + @year int, + @months SqlInt32ListTableType READONLY +AS +BEGIN + SET NOCOUNT ON + + CREATE TABLE #detailsToRestore + ( + RowID bigint identity(1,1), + DateID int, + DepartmentID int, + AccountID int + ) + CREATE CLUSTERED INDEX CNU_RowId ON #detailsToRestore(RowId) + + INSERT #detailsToRestore (DepartmentID, AccountID, DateID) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID + FROM fw.FactEncounterBasedStatistics ebs + JOIN fw.DimDate d ON ebs.DateID = d.DateID + JOIN @months m ON d.CalendarMonth = m.value + WHERE ebs.StatisticID = @statisticId + AND d.FiscalYear = @year + GROUP BY ebs.DepartmentID, ebs.AccountID, ebs.DateID + + DECLARE + @startRowId bigint, + @maxRowId bigint, + @endRowId bigint + + SELECT @startRowId = MIN(RowId), @maxRowId = MAX(RowId) + FROM #detailsToRestore + + WHILE (@startRowId <= @maxRowId) + BEGIN + SELECT @endRowId = MAX(d.RowId) + FROM (SELECT TOP 1000000 RowId + FROM #detailsToRestore + WHERE RowId >= @startRowId + ORDER BY RowID) as d + + DELETE cbs + FROM fw.FactChargeBasedStatistics cbs + JOIN #detailsToRestore ebs + ON cbs.DepartmentID = ebs.DepartmentID + AND cbs.AccountID = ebs.AccountID + AND cbs.DateID = ebs.DateID + WHERE ebs.RowId >= @startRowId + AND ebs.RowId <= @endRowId + + INSERT fw.FactChargeBasedStatistics (DepartmentID, AccountID, DateID, Value) + SELECT sgs.DepartmentID, sgs.AccountID, sgs.DateID, AVG(sgs.Value) + FROM fw.FactSystemGeneratedStatistics sgs + JOIN #detailsToRestore ebs + ON sgs.DepartmentID = ebs.DepartmentID + AND sgs.AccountID = ebs.AccountID + AND sgs.DateID = ebs.DateID + WHERE ebs.RowId >= @startRowId + AND ebs.RowId <= @endRowId + GROUP BY sgs.DepartmentID, sgs.AccountID, sgs.DateID + + SELECT @startRowId = MIN(d.RowId) + FROM #detailsToRestore d + WHERE RowId > @endRowId + END + + DROP TABLE IF EXISTS #detailsToRestore +END +GO + + +--------------------------------------------- + +-- fw.procPostDiRestoreChargeBasedStatisticsMonthly +CREATE PROC fw.procPostDiRestoreChargeBasedStatisticsMonthly + @statisticId int, + @year int, + @months SqlInt32ListTableType READONLY +AS +BEGIN + SET NOCOUNT ON + + DELETE cbs + FROM fw.FactEncounterBasedStatisticsMonthly ebs + JOIN @months m ON ebs.FiscalMonthID = m.value + JOIN fw.FactChargeBasedStatisticsMonthly cbs + ON ebs.DepartmentID = cbs.DepartmentID + AND ebs.AccountID = cbs.AccountID + AND ebs.FiscalYearID = cbs.FiscalYearID + AND ebs.FiscalMonthID = cbs.FiscalMonthID + WHERE ebs.FiscalYearID = @year + AND ebs.StatisticID = @statisticId + + INSERT fw.FactChargeBasedStatisticsMonthly (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value) + SELECT sgs.DepartmentID, sgs.AccountID, sgs.FiscalYearID, sgs.FiscalMonthID, AVG(sgs.Value) + FROM fw.FactEncounterBasedStatisticsMonthly ebs + JOIN @months m ON ebs.FiscalMonthID = m.value + JOIN fw.FactSystemGeneratedStatisticsMonthly sgs + ON ebs.DepartmentID = sgs.DepartmentID + AND ebs.AccountID = sgs.AccountID + AND ebs.FiscalYearID = sgs.FiscalYearID + AND ebs.FiscalMonthID = sgs.FiscalMonthID + WHERE ebs.FiscalYearID = @year + AND ebs.StatisticID = @statisticId + GROUP BY sgs.DepartmentID, sgs.AccountID, sgs.FiscalYearID, sgs.FiscalMonthID +END +GO + + +--------------------------------------------- + +-- fw.procPostDiRestoreChargeBasedStatisticsMonthlyOpt +CREATE PROC fw.procPostDiRestoreChargeBasedStatisticsMonthlyOpt +AS +BEGIN + SET NOCOUNT ON + + DELETE cbs + FROM fw.FactEncounterBasedStatisticsMonthly ebs + JOIN data.EbsPostDiCacheMonthly c + ON ebs.StatisticID = c.StatisticID + AND ebs.FiscalYearID = c.Year + AND ebs.FiscalMonthID = c.Month + JOIN fw.FactChargeBasedStatisticsMonthly cbs + ON ebs.DepartmentID = cbs.DepartmentID + AND ebs.AccountID = cbs.AccountID + AND ebs.FiscalYearID = cbs.FiscalYearID + AND ebs.FiscalMonthID = cbs.FiscalMonthID + + INSERT fw.FactChargeBasedStatisticsMonthly (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value) + SELECT sgs.DepartmentID, sgs.AccountID, sgs.FiscalYearID, sgs.FiscalMonthID, AVG(sgs.Value) + FROM fw.FactEncounterBasedStatisticsMonthly ebs + JOIN data.EbsPostDiCacheMonthly c + ON ebs.StatisticID = c.StatisticID + AND ebs.FiscalYearID = c.Year + AND ebs.FiscalMonthID = c.Month + JOIN fw.FactSystemGeneratedStatisticsMonthly sgs + ON ebs.DepartmentID = sgs.DepartmentID + AND ebs.AccountID = sgs.AccountID + AND ebs.FiscalYearID = sgs.FiscalYearID + AND ebs.FiscalMonthID = sgs.FiscalMonthID + GROUP BY sgs.DepartmentID, sgs.AccountID, sgs.FiscalYearID, sgs.FiscalMonthID +END +GO + + +--------------------------------------------- + +-- fw.procPostDiRestoreChargeBasedStatisticsOpt +CREATE PROC fw.procPostDiRestoreChargeBasedStatisticsOpt +AS +BEGIN + SET NOCOUNT ON + + CREATE TABLE #detailsToRestore + ( + RowID bigint identity(1,1), + DateID int, + DepartmentID int, + AccountID int + ) + CREATE CLUSTERED INDEX CNU_RowId ON #detailsToRestore(RowId) + + INSERT #detailsToRestore (DepartmentID, AccountID, DateID) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID + FROM fw.FactEncounterBasedStatistics ebs + JOIN fw.DimDate d ON ebs.DateID = d.DateID + JOIN data.EbsPostDiCache c + ON ebs.StatisticID = c.StatisticID + AND d.FiscalYear = c.Year + AND d.CalendarMonth = c.Month + GROUP BY ebs.DepartmentID, ebs.AccountID, ebs.DateID + + DECLARE + @startRowId bigint, + @maxRowId bigint, + @endRowId bigint + + SELECT @startRowId = MIN(RowId), @maxRowId = MAX(RowId) + FROM #detailsToRestore + + WHILE (@startRowId <= @maxRowId) + BEGIN + SELECT @endRowId = MAX(d.RowId) + FROM (SELECT TOP 1000000 RowId + FROM #detailsToRestore + WHERE RowId >= @startRowId + ORDER BY RowID) as d + + DELETE cbs + FROM fw.FactChargeBasedStatistics cbs + JOIN #detailsToRestore ebs + ON cbs.DepartmentID = ebs.DepartmentID + AND cbs.AccountID = ebs.AccountID + AND cbs.DateID = ebs.DateID + WHERE ebs.RowId >= @startRowId + AND ebs.RowId <= @endRowId + + INSERT fw.FactChargeBasedStatistics (DepartmentID, AccountID, DateID, Value) + SELECT sgs.DepartmentID, sgs.AccountID, sgs.DateID, AVG(sgs.Value) + FROM fw.FactSystemGeneratedStatistics sgs + JOIN #detailsToRestore ebs + ON sgs.DepartmentID = ebs.DepartmentID + AND sgs.AccountID = ebs.AccountID + AND sgs.DateID = ebs.DateID + WHERE ebs.RowId >= @startRowId + AND ebs.RowId <= @endRowId + GROUP BY sgs.DepartmentID, sgs.AccountID, sgs.DateID + + SELECT @startRowId = MIN(d.RowId) + FROM #detailsToRestore d + WHERE RowId > @endRowId + END + + DROP TABLE IF EXISTS #detailsToRestore +END +GO + + +--------------------------------------------- + +-- fw.procPrepareGL +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-03-19 IP D-06997 Replaced table variable by temp tables +** 2 2018-05-15 KF D-07006 Rolling Average method for metric target calculation doesn't include months with 0 values +** 3 2018-05-31 IP TK-58509 reverting part of migrations for D-07006 +** 4 2018-06-04 IP TK-58587 re-applying changes (2018-05-16 D-07187 Budget adjustment effecting historical budget fiscal years) +** 5 2019-09-03 vfay D-08704 Fix incorrectly adding previous year's data into the current year +** 6 2024-06-04 ishah JAZZ-61244 [TrLog][High] Bug - Run Management Reporting Monthly Process (MR Sampling, all years run): Task failed on Inserting GL Sampled. +***************************************************************/ +----- #FactGLStagingValue with specified columns(DepartmentID int, AccountID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, Amount decimal(21,6), ApplyDate datetime, Src varchar(max)) should be created before calling the proc +CREATE PROCEDURE [fw].[procPrepareGL] + @FiscalYearID int = 0 +AS +BEGIN + DECLARE + @iteration INT = 1, + @batchSize INT, + @applyDateString nvarchar(100) = '''' + '1900-01-01' + '''' + + -- Split by batches + EXEC mr.procGetIntBatchSize + @DefaultBatchSize = 30000000, + @ResultBatchSize = @batchSize OUTPUT + + IF OBJECT_ID('tempdb..#inputDepartments') IS NOT NULL DROP TABLE #inputDepartments + CREATE TABLE #inputDepartments (DepartmentID INT, RecordsCount INT, BatchID INT) + + DECLARE @fromClause nvarchar(max) = ' + ( + SELECT + stat.DepartmentID, + stat.AccountID, + stat.FiscalYearID, + stat.FiscalMonthID, + stat.TimeClassID + FROM + int.FactGL stat + inner join fw.DimDepartment D on D.Departmentid = STAT.Departmentid + WHERE + stat.IsDeleted = 0 + and stat.Value != 0 + and (stat.FiscalYearID = ' + cast(@FiscalYearID as nvarchar(100)) + ' or ' + cast(@FiscalYearID as nvarchar(100)) + ' = 0) + GROUP BY stat.DepartmentID, + stat.AccountID, + stat.FiscalYearID, + stat.FiscalMonthID, + stat.TimeClassID ) X + ' + + INSERT INTO #inputDepartments + EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'X', + @fromClause = @fromClause, + @whereClause = '', + @isDebug = 0 + + DECLARE @BatchID INT, @MaxBatchID INT + SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + + SET @BatchID = 1 + WHILE @BatchID <= @MaxBatchID + BEGIN + INSERT INTO #FactGLStagingValue (DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,ApplyDate,Src) + SELECT + stat.DepartmentID, + stat.AccountID, + stat.FiscalYearID, + stat.FiscalMonthID, + stat.TimeClassID, + sum(stat.Value) as Amount, + cast('1900-01-01' as datetime) as ApplyDate, + cast('int_1' as varchar(max))+'V' as src + from + int.FactGL stat + inner join fw.DimDepartment D on D.Departmentid = stat.Departmentid + inner join #inputDepartments ID ON ID.DepartmentID = D.DepartmentID + where + stat.IsDeleted = 0 + and stat.Value != 0 + and ID.BatchID = @BatchID + and (stat.FiscalYearID = @FiscalYearID or @FiscalYearID = 0) + Group by stat.DepartmentID, + stat.AccountID, + stat.FiscalYearID, + stat.FiscalMonthID, + stat.TimeClassID + + SET @BatchID = @BatchID + 1 + END + +DECLARE @BudgetReallocationGUID uniqueidentifier,@date datetime,@BudgetReallocationType varchar(50) + +PRINT '-------- Vendor Products Report --------'; + +DECLARE BRA_cursor CURSOR FOR +SELECT distinct BudgetReallocationGUID,date,BudgetReallocationType from fw.BudgetReallocationWithDefinedType +WHERE (FiscalYearID = @FiscalYearID or @FiscalYearID = 0) +ORDER BY date; + +OPEN BRA_cursor + +FETCH NEXT FROM BRA_cursor +INTO @BudgetReallocationGUID,@date,@BudgetReallocationType + +WHILE @@FETCH_STATUS = 0 +BEGIN + IF @BudgetReallocationType = 'ReallocateSingle' + BEGIN -- Insert rows with "correcting" values + UPDATE STT + SET Amount = Amount + Change, + stt.ApplyDate = b.Date, + src = SRC + '[Added_'+cast(Change as varchar(50))+'_from_'+cast(SourceDepartmentID as varchar(10))+']' + FROM #FactGLStagingValue STT + INNER JOIN [mr].[BudgetReallocation] b ON b.TargetDepartmentID = stt.DepartmentID and b.TargetAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID + WHERE Change <> 0 + and b.BudgetReallocationGUID = @BudgetReallocationGUID + and UnitTypeID = 34 + and TimeClassID = 2 + and b.Archived = 0 + + UPDATE STT + SET Amount = Amount - Change, + stt.ApplyDate = b.Date, + src = SRC + '[Removed_'+cast(Change as varchar(50))+'_to_'+cast(TargetDepartmentID as varchar(10))+']' + FROM #FactGLStagingValue STT + INNER JOIN [mr].[BudgetReallocation] b ON b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID + WHERE Change <> 0 + and b.BudgetReallocationGUID = @BudgetReallocationGUID + and UnitTypeID = 34 + and TimeClassID = 2 + and b.Archived = 0 + + INSERT INTO #FactGLStagingValue (DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,ApplyDate,Src) + SELECT + b.SourceDepartmentID as DepartmentID, + b.SourceAccountID as AccountID, + b.FiscalYearID, + ba.FiscalMonthID, + 2 as TimeclassID, + Change * -1 as Value, + b.Date as ApplyDate, + 'ra_1_m' as src + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + LEFT JOIN (select DepartmentID,AccountID,FiscalYearID,FiscalMonthID,max(ApplyDate) as ApplyDate from #FactGLStagingValue where TimeClassID = 2 group by DepartmentID,AccountID,FiscalYearID,FiscalMonthID) STT ON b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID and stt.FiscalMonthID = ba.FiscalMonthID + where Change <> 0 + and b.BudgetReallocationGUID = @BudgetReallocationGUID + and stt.DepartmentID is null + and UnitTypeID = 34 + and b.Archived = 0 + UNION All + SELECT + b.TargetDepartmentID as DepartmentID, + b.TargetAccountID as AccountID, + b.FiscalYearID, + ba.FiscalMonthID, + 2 as TimeclassID, + Change as Value, + b.Date as ApplyDate, + 'ra_1_p' as src + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + LEFT JOIN (select DepartmentID,AccountID,FiscalYearID,FiscalMonthID,max(ApplyDate) as ApplyDate from #FactGLStagingValue where TimeClassID = 2 group by DepartmentID,AccountID,FiscalYearID,FiscalMonthID) STT ON b.TargetDepartmentID = stt.DepartmentID and b.TargetAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID and stt.FiscalMonthID = ba.FiscalMonthID + where Change <> 0 + and b.BudgetReallocationGUID = @BudgetReallocationGUID + and stt.DepartmentID is null + and UnitTypeID = 34 + and b.Archived = 0 + END + ELSE + ---------------------- + IF @BudgetReallocationType = 'ReallocateMulti' + BEGIN + + UPDATE STT + set + STT.Amount = STT.Amount + STT_SRC.Amount, + STT.ApplyDate = b.[Date], + STT.Src = stt.Src + '[RealMulti_'+cast(stt_src.Amount as varchar(50))+'_from_'+cast(stt_src.DepartmentID as varchar(10))+']' + FROM #FactGLStagingValue STT + INNER JOIN [mr].[BudgetReallocation] b on + b.TargetDepartmentID = STT.DepartmentID and + b.TargetAccountID = STT.AccountID and + b.FiscalYearID = STT.FiscalYearID and + b.[Date] >= STT.ApplyDate + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on + ba.BudgetReallocationGUID = b.BudgetReallocationGUID and + ba.FiscalMonthID = STT.FiscalMonthID + INNER JOIN #FactGLStagingValue STT_SRC on + STT_SRC.DepartmentID = b.SourceDepartmentID and + STT_SRC.AccountID = b.SourceAccountID and + STT_SRC.FiscalYearID = b.FiscalYearID and + STT_SRC.FiscalMonthID = ba.FiscalMonthID and + STT_SRC.TimeClassID = STT.TimeClassID + where + b.BudgetReallocationGUID = @BudgetReallocationGUID and + ba.UnitTypeID = 34 and + ba.Change <> 0 and + STT.TimeClassID = 2 and + b.Archived = 0 + + INSERT INTO #FactGLStagingValue (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, ApplyDate, Src) + SELECT + b.TargetDepartmentID as DepartmentID, + b.TargetAccountID as AccountID, + b.FiscalYearID, + ba.FiscalMonthID, + 2 as TimeclassID, + STT_SRC.Amount as Value, + b.[Date] as ApplyDate, + 'ReallocateMulti' as src + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on + b.BudgetReallocationGUID = ba.BudgetReallocationGUID + INNER JOIN #FactGLStagingValue STT_SRC on + STT_SRC.DepartmentID = b.SourceDepartmentID and + STT_SRC.AccountID = b.SourceAccountID and + STT_SRC.FiscalYearID = b.FiscalYearID and + STT_SRC.FiscalMonthID = ba.FiscalMonthID and + STT_SRC.TimeClassID = 2 + LEFT JOIN #FactGLStagingValue STT on + STT.DepartmentID = b.TargetDepartmentID and + STT.AccountID = b.TargetAccountID and + STT.FiscalYearID = b.FiscalYearID and + STT.FiscalMonthID = ba.FiscalMonthID and + STT.TimeClassID = 2 + where + stt.DepartmentID is null and + ba.Change <> 0 and + ba.UnitTypeID = 34 and + b.[Date] >= isnull(stt.ApplyDate,'1900-01-01') and + b.BudgetReallocationGUID = @BudgetReallocationGUID and + b.Archived = 0 + + UPDATE STT_SRC + SET + STT_SRC.Amount = 0, + STT_SRC.ApplyDate = b.[Date], + STT_SRC.Src = stt_src.Src + '[RealMulti_'+cast(stt_src.Amount as varchar(50))+'_to_'+cast(stt.DepartmentID as varchar(10))+']' + FROM #FactGLStagingValue STT + INNER JOIN [mr].[BudgetReallocation] b on + b.TargetDepartmentID = STT.DepartmentID and + b.TargetAccountID = STT.AccountID and + b.FiscalYearID = STT.FiscalYearID and + b.[Date] >= STT.ApplyDate + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on + b.BudgetReallocationGUID = ba.BudgetReallocationGUID and + ba.FiscalMonthID = STT.FiscalMonthID + INNER JOIN #FactGLStagingValue STT_SRC on + b.SourceDepartmentID = STT_SRC.DepartmentID and + b.SourceAccountID = STT_SRC.AccountID and + b.FiscalYearID = STT_SRC.FiscalYearID and + ba.FiscalMonthID = STT_SRC.FiscalMonthID and + STT_SRC.TimeClassID = 2 + where + ba.Change <> 0 and + b.BudgetReallocationGUID = @BudgetReallocationGUID and + ba.UnitTypeID = 34 and + b.Archived = 0 + + END + ELSE + IF @BudgetReallocationType = 'AdjustMontly' + BEGIN + UPDATE STT + SET + stt.Amount = stt.Amount+Change, + stt.ApplyDate = b.Date, + stt.Src = stt.Src + '[AdjustMontly_'+cast(Change as varchar(50))+']' + FROM #FactGLStagingValue STT + INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and b.Date >= stt.ApplyDate and b.FiscalYearID = stt.FiscalYearID + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID + where + b.BudgetReallocationGUID = @BudgetReallocationGUID + and ba.UnitTypeID = 34 + and Change <> 0 + and b.Date >= isnull(stt.ApplyDate,'1900-01-01') + and TimeClassID = 2 + and b.Archived = 0 + + INSERT INTO #FactGLStagingValue (DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,ApplyDate,Src) + SELECT + b.SourceDepartmentID as DepartmentID, + b.SourceAccountID as AccountID, + b.FiscalYearID, + ba.FiscalMonthID, + 2 as TimeclassID, + Change as Value, + b.date as ApplyDate, + 'ra_3' as src + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + LEFT JOIN #FactGLStagingValue STT ON b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID and stt.FiscalMonthID = ba.FiscalMonthID and TimeClassID = 2 + where Change <> 0 + and stt.DepartmentID is null + and ba.UnitTypeID =34 + and b.Date >= isnull(stt.ApplyDate,'1900-01-01') + and b.BudgetReallocationGUID = @BudgetReallocationGUID + and b.Archived = 0 + END + ELSE + IF @BudgetReallocationType = 'ManualFile' + BEGIN + UPDATE STT + SET + stt.Amount = ba.NewSourceValue, + stt.ApplyDate = b.Date, + stt.Src = stt.Src + '[ManualFile_'+cast(NewSourceValue as varchar(50))+']' + FROM #FactGLStagingValue STT + INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and b.Date >= stt.ApplyDate and b.FiscalYearID = stt.FiscalYearID + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID + where + b.BudgetReallocationGUID = @BudgetReallocationGUID + and ba.UnitTypeID = 34 + and TimeClassID = 2 + and Change <> 0 + and b.Archived = 0 + + INSERT INTO #FactGLStagingValue (DepartmentID,AccountID,FiscalYearID,FiscalMonthID,TimeClassID,Amount,ApplyDate,Src) + SELECT + b.SourceDepartmentID as DepartmentID, + b.SourceAccountID as AccountID, + b.FiscalYearID, + ba.FiscalMonthID, + 2 as TimeclassID, + NewSourceValue as Value, + b.date as ApplyDate, + 'ManualFile' as src + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + LEFT JOIN #FactGLStagingValue STT ON b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and stt.FiscalYearID = b.FiscalYearID and stt.FiscalMonthID = ba.FiscalMonthID and TimeClassID = 2 + where Change <> 0 + and stt.DepartmentID is null + and ba.UnitTypeID =34 + and b.Date >= isnull(stt.ApplyDate,'1900-01-01') + and b.BudgetReallocationGUID = @BudgetReallocationGUID + and b.Archived = 0 + END + + set @iteration = @iteration +1 + + FETCH NEXT FROM BRA_cursor + INTO @BudgetReallocationGUID,@date,@BudgetReallocationType +END +CLOSE BRA_cursor; +DEALLOCATE BRA_cursor; + +SET @fromClause = ' +( + SELECT + STT.DepartmentID, + STT.AccountID, + STT.FiscalYearID, + STT.FiscalMonthID, + STT.TimeclassID, + 0 as Amount, + ' + '''' + 'none' + '''' + ' as src + FROM int.FactGL STT + INNER JOIN fw.DimDepartment D ON D.DepartmentID = STT.DepartmentID + LEFT JOIN #FactGLStagingValue fgs + ON fgs.DepartmentID = STT.DepartmentID + AND fgs.AccountID = STT.AccountID + AND fgs.FiscalYearID = STT.FiscalYearID + AND fgs.FiscalMonthID = STT.FiscalMonthID + AND fgs.TimeClassID = STT.TimeClassID + WHERE fgs.DepartmentID IS NULL AND STT.IsDeleted = 0 AND STT.Value != 0 AND (STT.FiscalYearID = ' + cast(@FiscalYearID as nvarchar(100)) + ' or ' + cast(@FiscalYearID as nvarchar(100)) + ' = 0) + ) X +' + +TRUNCATE TABLE #inputDepartments + +INSERT INTO #inputDepartments +EXEC dbo.procGetInputDataByBatches + @batchSize = @batchSize, + @columnName = 'DepartmentID', + @tableAlias = 'X', + @fromClause = @fromClause, + @whereClause = '', + @isDebug = 0 + +SELECT @MaxBatchID = MAX(BatchID) FROM #inputDepartments + +SET @BatchID = 1 +WHILE @BatchID <= @MaxBatchID +BEGIN + INSERT INTO #FactGLStagingValue (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Amount, Src) + SELECT stat.DepartmentID, stat.AccountID, stat.FiscalYearID, stat.FiscalMonthID, stat.TimeClassID, 0 as Amount, 'none' as src + FROM int.FactGL stat + INNER JOIN fw.DimDepartment D ON D.Departmentid = stat.Departmentid + LEFT JOIN #FactGLStagingValue fgs + ON fgs.DepartmentID = stat.DepartmentID + AND fgs.AccountID = stat.AccountID + AND fgs.FiscalYearID = stat.FiscalYearID + AND fgs.FiscalMonthID = stat.FiscalMonthID + AND fgs.TimeClassID = stat.TimeClassID + INNER JOIN #inputDepartments ID ON ID.DepartmentID = D.Departmentid + WHERE stat.IsDeleted = 0 + AND stat.Value != 0 + AND (stat.FiscalYearID = @FiscalYearID or @FiscalYearID = 0) + AND ID.BatchID = @BatchID + AND fgs.DepartmentID IS NULL + + SET @BatchID = @BatchID + 1 +END +END +GO + + +--------------------------------------------- + +-- fw.procPreparePayrollByMonth +CREATE PROC [fw].[procPreparePayrollByMonth] (@FiscalYearID int =0) +as +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-03-19 IP D-06997 Replaced table variable by temp tables +***************************************************************/ + IF OBJECT_ID('tempdb.dbo.#StatisticTempTable', 'U') IS NOT NULL DROP TABLE #StatisticTempTable; + declare @iteration int = 1 + create table #StatisticTempTable ( + DepartmentID int, + JobCodeID int, + EmployeeID int, + PayCodeID int, + PayCodeGroupID int, + FiscalYearID smallint, + FiscalMonthID tinyint, + TimeClassID tinyint, + Hours decimal(18,6), + Dollars decimal(18,6), + ApplyDate datetime, + Src varchar(max) +) + INSERT INTO #StatisticTempTable (DepartmentID,JobCodeID,EmployeeID,PayCodeID,PayCodeGroupID,FiscalYearID,FiscalMonthID,TimeClassID,Hours,Dollars,ApplyDate,Src) + SELECT + pr.DepartmentID, + pr.JobCodeID, + pr.EmployeeID, + pr.PayCodeID, + pc.PayCodeGroupID, + PR.FiscalYearID, + pr.FiscalMonthID, + pr.TimeClassID, + SUM(CASE WHEN pr.unittypeID=51 and pc.IsHoursIgnored=0 then value ELSE 0 END) AS Hours, + SUM(CASE WHEN pr.unittypeID=34 and pc.IsDollarsIgnored=0 then value ELSE 0 END) AS Dollars, + cast('1900-01-01' as date) as ApplyDate, + 'int' as Src + FROM + int.FactStaffing pr + INNER JOIN fw.DimPayCode pc on pc.PayCodeID = PR.PayCodeID + WHERE + pr.FiscalMonthCode not in('', '0') + and pr.IsDeleted = 0 + and pr.Value != 0 + AND (pr.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0) + GROUP BY + pr.DepartmentID, + pr.JobCodeID, + pr.EmployeeID, + pr.PayCodeID, + pc.PayCodeGroupID, + PR.FiscalYearID, + pr.FiscalMonthID, + pr.TimeClassID, + pr.PayCodeID + + +DECLARE @BudgetReallocationGUID uniqueidentifier,@date datetime,@BudgetReallocationType varchar(50) + +PRINT '-------- Vendor Products Report --------'; + +DECLARE BRA_cursor CURSOR FOR +SELECT distinct BudgetReallocationGUID,date,BudgetReallocationType from fw.BudgetReallocationWithDefinedType +WHERE (FiscalYearID = @FiscalYearID or @FiscalYearID = 0) +ORDER BY date; + +OPEN BRA_cursor + +FETCH NEXT FROM BRA_cursor +INTO @BudgetReallocationGUID,@date,@BudgetReallocationType + +WHILE @@FETCH_STATUS = 0 +BEGIN + +print @iteration + + IF @BudgetReallocationType = 'ReallocateMulti' + BEGIN + UPDATE STT + SET + stt.DepartmentID = b.TargetDepartmentID, + stt.JobCodeID = b.TargetJobCodeID, + stt.Src = stt.Src + ';RealMulti' + FROM #StatisticTempTable STT + INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceJobCodeID = stt.JobCodeID and b.Date >= stt.ApplyDate + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and stt.FiscalMonthID = ba.FiscalMonthID + where + b.BudgetReallocationGUID = @BudgetReallocationGUID + and ba.UnitTypeID = 34 + and change <> 0 + and TimeClassID = 2 + and DataType = 1 + END + + set @iteration = @iteration +1 + + FETCH NEXT FROM BRA_cursor + INTO @BudgetReallocationGUID,@date,@BudgetReallocationType +END +CLOSE BRA_cursor; +DEALLOCATE BRA_cursor; + +SELECT DepartmentID, + JobCodeID, + EmployeeID, + PayCodeID, + PayCodeGroupID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + sum(Hours) as Hours, + sum(Dollars) as Dollars +FROM ( + SELECT + DepartmentID, + JobCodeID, + EmployeeID, + PayCodeID, + PayCodeGroupID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + Hours, + Dollars + from #StatisticTempTable stt + UNION ALL + SELECT + pr.DepartmentID, + pr.JobCodeID, + pr.EmployeeID, + pr.PayCodeID, + pc.PayCodeGroupID, + PR.FiscalYearID, + pr.FiscalMonthID, + pr.TimeClassID, + 0 AS Hours, + 0 AS Dollars + FROM + int.FactStaffing pr + INNER JOIN fw.DimPayCode pc on pc.PayCodeID = PR.PayCodeID + WHERE + pr.FiscalMonthCode not in('', '0') + and pr.IsDeleted = 0 + and pr.Value != 0 + AND (pr.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0) +) SubSelect +GROUP BY DepartmentID, + JobCodeID, + EmployeeID, + PayCodeID, + PayCodeGroupID, + FiscalYearID, + FiscalMonthID, + TimeClassID +GO + + +--------------------------------------------- + +-- fw.procProviderSampledAdjustedTargetMonthlyInsert +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-10-30 KZ B-20910 Provider - Create adjusted target +*************************************************************/ +CREATE proc [fw].[procProviderSampledAdjustedTargetMonthlyInsert] (@FiscalYearID int = 0) +AS +BEGIN + DECLARE @IsFlexingEnabled INT = ( + SELECT VALUE + FROM [mr].[SystemSetting] + WHERE NAME = 'Is Target Flexed' + ) + DECLARE @IsEfficiencyFactorPresent INT = ( + SELECT count(*) + FROM mr.EfficiencyFactor + ) + + IF @IsEfficiencyFactorPresent > 0 BEGIN + DELETE FROM fw.FactProviderSampledMonthly_Pivoted WHERE (@FiscalYearID = FiscalYearID OR @FiscalYearID = 0) and TimeClassID = 22 + + INSERT INTO fw.FactProviderSampledMonthly_Pivoted (DepartmentID, + ProviderID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + OBForecastDetailID, + Volume, + Dollars, + Hours, + FTEs) + SELECT DepartmentID, + ProviderID, + FiscalYearID, + FiscalMonthID, + 22, + OBForecastDetailID, + SUM(Volume), + SUM(Dollars), + SUM(Hours), + SUM(FTEs) + FROM fw.FactProviderSampledMonthly_Pivoted fact + WHERE ( + ( + ISNULL(fact.TimeClassID,0) = 4 AND @IsFlexingEnabled = 1 + ) + OR ( + ( + ISNULL(fact.TimeClassID,0) = 20) AND @IsFlexingEnabled = 0 + ) + ) + AND (fact.FiscalYearID = @FiscalYearID OR @FiscalYearID = 0) + GROUP BY DepartmentID, + ProviderID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + OBForecastDetailID + + EXEC [fw].[procFactMonthlyYTDPriorYearUpdate] @factTableName = 'fw.FactProviderSampledMonthly_Pivoted', @keyNameCSV = 'OBForecastDetailID,ProviderID', + @measureNameCSV = 'Volume,Dollars,Hours,FTEs',@fiscalYearID = @FiscalYearID, @timeClassID = 22, @isDebugOnly = 0 + END +END +GO + + +--------------------------------------------- + +-- fw.procProviderSampledInsertMonthly +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-12-13 NL B-13759 Adding fiscalYearID param and filtering on it +** 2 2017-02-20 GF D-05545 Move duplicate record handling from YTD into sampling + general cleanup +** 3 2017-04-11 IP B-15086 Sampling Performance Improvements. Using temp tables insead of fw.FactProviderSampledMonthly. +** 4 2017-06-15 IP B-15086 odify SP to use unique temp table +** 5 2018-02-07 IP B-18725 MR - Provider sampling from payroll +** 6 2018-02-08 IP TK-53982 Fixed amount calculated as sum of Hours and Dollars +** 7 2018-02-28 IP B-18946 Update provider payroll sampling to be consistent with OB when there is duplicate data +** 8 2018-06-27 KF B-20195 MR - Provider calculate baseline target +** 9 2018-07-25 KF B-20342 MR - Update provider sampling to be in the appropriate format +**10 2018-08-22 KF D-07561 MR Sampling: Provider FTEsYTD values are calculated incorrectly +**11 2018-10-30 KF D-07727 MR Provider Sampling: FTEs and FTEsYTD are calculated based on different Work Week overrides +**12 2022-03-15 KF JAZZ-27781 Run PR Process Task can fail silently during Payroll Sampling +**13 2023-09-12 BS JAZZ-55750 Remove filter to allow other time classes in MR reporting +*************************************************************/ +CREATE proc [fw].[procProviderSampledInsertMonthly] + @fiscalYearID smallint = 0 +as + + IF OBJECT_ID('tempdb..#ProviderSampledStaging') IS NOT NULL DROP TABLE #ProviderSampledStaging + IF OBJECT_ID('fw.ProviderSampledStagingWithCalcs') IS NOT NULL DROP TABLE fw.ProviderSampledStagingWithCalcs + + CREATE TABLE #ProviderSampledStaging (RowID bigint identity(1,1), DepartmentID int, ProviderID int, FiscalYearID int, FiscalMonthID int, OBForecastDetailID int, TimeClassID int, + Dollars decimal(18,6), Hours decimal(18,6), Volume decimal(18,6), FTEs decimal(18,6), isDeleted bit, isSystemGenerated bit) + + --push new data to fact table + insert into #ProviderSampledStaging (DepartmentID, ProviderID, FiscalYearID, FiscalMonthID, OBForecastDetailID, TimeClassID, Dollars, Hours, Volume, FTEs) + select + p.DepartmentID, + p.ProviderID, + p.FiscalYearID, + p.FiscalMonthID, + p.OBForecastDetailID, + p.TimeClassID, + SUM(CASE WHEN fd.UnitTypeID=34 then value ELSE 0 END) AS Dollars, + SUM(CASE WHEN fd.UnitTypeID=51 then value ELSE 0 END) AS Hours, + SUM(CASE WHEN fd.UnitTypeID=140 then value ELSE 0 END) AS Volume, + SUM(CASE WHEN fd.UnitTypeID=144 then value ELSE 0 END) AS FTEs + from + int.FactImportProvider p + INNER JOIN ob.DimOBForecastDetail fd on fd.OBForecastDetailID = p.OBForecastDetailID + where + p.IsDeleted = 0 + and p.Value != 0 + AND (p.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0) + group by + p.DepartmentID, + p.ProviderID, + p.FiscalYearID, + p.FiscalMonthID, + p.OBForecastDetailID, + p.TimeClassID + + ;with ProviderHours as ( + SELECT data.DepartmentID, data.ProviderID, data.FiscalYearID, data.FiscalMonthID, data.TimeClassID, SUM(data.Amount) as Hours + FROM mr.viewFactProviderBasedOnPayroll data + LEFT JOIN #ProviderSampledStaging pss on pss.DepartmentID = data.DepartmentID and pss.ProviderID = data.ProviderID and pss.FiscalYearID = data.FiscalYearID and pss.FiscalMonthID = data.FiscalMonthID and pss.OBForecastDetailID = 1000 and pss.TimeClassID = data.TimeClassID + where data.UnitTypeID=51 --Hours + and data.IsProvider = 1 + and pss.DepartmentID is null --use the provider import data and ignore the payroll data + and data.ProductiveClass in + ( + 'Productive', + 'Productive Non-FTE', + 'Non-Productive' + ) + AND (data.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0) + group by + data.DepartmentID, data.ProviderID, data.FiscalYearID, data.FiscalMonthID,data.TimeClassID + ) + + INSERT INTO #ProviderSampledStaging + (DepartmentID, ProviderID, FiscalYearID, FiscalMonthID, OBForecastDetailID, TimeClassID, Dollars, Hours, Volume, FTEs) + SELECT + vw.DepartmentID, vw.ProviderID, vw.FiscalYearID, vw.FiscalMonthID, vw.OBForecastDetailID, vw.TimeClassID, SUM(vw.Amount) AS Dollars, 0 AS Hours, 0 AS Volume, 0 AS FTEs + FROM mr.viewFactProviderBasedOnPayroll vw + LEFT JOIN #ProviderSampledStaging pss on pss.DepartmentID = vw.DepartmentID and pss.ProviderID = vw.ProviderID and pss.FiscalYearID = vw.FiscalYearID and pss.FiscalMonthID = vw.FiscalMonthID and pss.OBForecastDetailID = vw.OBForecastDetailID and pss.TimeClassID = vw.TimeClassID + --If there is overlap for the same month, year, time class, provider, and forecastdetail between the provider import data and the payroll data, then the system should use the provider import data and ignore the payroll data + WHERE IsProvider = 1 + and pss.DepartmentID is null --use the provider import data and ignore the payroll data + and vw.UnitTypeID=34 --Dollars + and vw.Amount != 0 + AND (vw.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0) + GROUP BY + vw.DepartmentID, + vw.ProviderID, + vw.FiscalYearID, + vw.FiscalMonthID, + vw.OBForecastDetailID, + vw.TimeClassID + + UNION ALL + + SELECT + DepartmentID, ProviderID, FiscalYearID, FiscalMonthID,1000 as OBForecastDetailID, TimeClassID, 0 AS Dollars, Hours, 0 AS Volume, 0 AS FTEs + FROM ProviderHours + + UNION ALL + + SELECT fact.DepartmentID, fact.ProviderID, fact.FiscalYearID, fact.FiscalMonthID,1001 as OBForecastDetailID, TimeClassID, 0 AS Dollars, 0 AS Hours, 0 AS Volume, fact.Value / (wpmCY.Hours) AS FTEs + from int.FactImportProvider fact + inner join fw.dimProvider pr on pr.ProviderID = fact.ProviderID + inner join fw.DimDepartment D on fact.DepartmentID=D.DepartmentID + inner join fw.DimEntity de on de.EntityID = D.EntityID + inner join [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmCY on fact.FiscalMonthID=wpmCY.FiscalMonthID and fact.FiscalYearID = wpmCY.FiscalYearID + and wpmCY.WorkWeekID = case when pr.WorkWeekOverrideID != -1 then pr.WorkWeekOverrideID when pr.WorkWeekOverrideID = -1 AND D.WorkWeekID >= 0 then D.WorkWeekID else de.WorkWeekID end + where fact.IsDeleted = 0 and fact.Value != 0 AND (fact.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0) and 1000 = fact.OBForecastDetailID + + UNION ALL + + --Provider + SELECT fact.DepartmentID, fact.ProviderID, fact.FiscalYearID, fact.FiscalMonthID,1001 as OBForecastDetailID, TimeClassID, 0 AS Dollars, 0 AS Hours, 0 AS Volume, fact.Hours / (wpmCY.Hours) AS FTEs + from ProviderHours fact + inner join fw.dimProvider pr on pr.ProviderID = fact.ProviderID + inner join [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmCY on fact.FiscalMonthID=wpmCY.FiscalMonthID AND fact.FiscalYearID = wpmCY.FiscalYearID and wpmCY.WorkWeekID=pr.WorkWeekOverrideID + where pr.WorkWeekOverrideID!=-1 + + UNION ALL + + --Department + SELECT fact.DepartmentID, fact.ProviderID, fact.FiscalYearID, fact.FiscalMonthID,1001 as OBForecastDetailID, TimeClassID, 0 AS Dollars, 0 AS Hours, 0 AS Volume, fact.Hours / (wpmCY.Hours) AS FTEs + from ProviderHours fact + inner join fw.dimProvider pr on pr.ProviderID = fact.ProviderID + inner join fw.DimDepartment D on fact.DepartmentID=D.DepartmentID + inner join [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmCY on fact.FiscalMonthID=wpmCY.FiscalMonthID and fact.FiscalYearID = wpmCY.FiscalYearID and wpmCY.WorkWeekID=D.WorkWeekID + where pr.WorkWeekOverrideID=-1 AND D.WorkWeekID >= 0 + + UNION ALL + + --Entity + SELECT fact.DepartmentID, fact.ProviderID, fact.FiscalYearID, fact.FiscalMonthID,1001 as OBForecastDetailID, TimeClassID, 0 AS Dollars, 0 AS Hours, 0 AS Volume, fact.Hours / (wpmCY.Hours) AS FTEs + from ProviderHours fact + inner join fw.dimProvider pr on pr.ProviderID = fact.ProviderID + inner join fw.DimDepartment D on fact.DepartmentID=D.DepartmentID + inner join fw.DimEntity de on de.EntityID = D.EntityID + inner join [client].[viewFactWorkingHoursPerMonthWithYTDHoursPerMonth] wpmCY on fact.FiscalMonthID=wpmCY.FiscalMonthID and fact.FiscalYearID = wpmCY.FiscalYearID and wpmCY.WorkWeekID=de.WorkWeekID + where pr.WorkWeekOverrideID=-1 AND D.WorkWeekID < 0 + + --run calculations + exec fw.procFactMonthlyMergeDuplicates '#ProviderSampledStaging', 'ProviderID,OBForecastDetailID', 'Dollars,Hours,Volume,FTEs', @fiscalYearID, 0, 0 + exec fw.procFactProviderSampledBaselineTargetUpdate @fiscalYearID = @fiscalYearID + exec fw.procFactMonthlyYTDPriorYearUpdateStaging 'fw.FactProviderSampledMonthly_Pivoted','#ProviderSampledStaging','ProviderID,OBForecastDetailID', 'Dollars,Hours,Volume,FTEs', @fiscalYearID, 0, 0 + exec client.procFactProviderSampledMonthlyDetailedFTEsInsertStaging @fiscalYearID = @fiscalYearID + + print 'finish staging calculations --- '+convert(varchar(20),GETDATE(),113) + + IF @fiscalYearID = 0 + BEGIN + truncate table fw.FactProviderSampledMonthly_Pivoted + INSERT INTO fw.FactProviderSampledMonthly_Pivoted With (TABLOCKX) ( + DepartmentID, + FiscalMonthID, + FiscalYearID, + ProviderID, + OBForecastDetailID, + TimeClassID, + Dollars, + DollarsYTD, + DollarsPriorYear, + DollarsPriorYTD, + Hours, + HoursYTD, + HoursPriorYear, + HoursPriorYTD, + Volume, + VolumeYTD, + VolumePriorYear, + VolumePriorYTD, + FTEs, + FTEsYTD, + FTEsPriorYear, + FTEsPriorYTD, + IsDeleted, + IsSystemGenerated + ) + SELECT + DepartmentID, + FiscalMonthID, + FiscalYearID, + ProviderID, + OBForecastDetailID, + TimeClassID, + Dollars, + DollarsYTD, + DollarsPriorYear, + DollarsPriorYTD, + Hours, + HoursYTD, + HoursPriorYear, + HoursPriorYTD, + Volume, + VolumeYTD, + VolumePriorYear, + VolumePriorYTD, + FTEs, + FTEsYTD, + FTEsPriorYear, + FTEsPriorYTD, + 0 as IsDeleted, + isnull(IsSystemGenerated,0) as IsSystemGenerated + FROM fw.ProviderSampledStagingWithCalcs + END +ELSE + BEGIN + print 'Starting creating index --- '+convert(varchar(20),GETDATE(),113) + CREATE CLUSTERED INDEX IDX_TempPayrollWithCalcs on fw.ProviderSampledStagingWithCalcs (DepartmentID,FiscalMonthID,FiscalYearID,ProviderID,OBForecastDetailID,TimeClassID) + print 'Starting transaction --- '+convert(varchar(20),GETDATE(),113) + BEGIN TRANSACTION Sampling + BEGIN TRY + MERGE fw.FactProviderSampledMonthly_Pivoted With (TABLOCKX) AS target + USING fw.ProviderSampledStagingWithCalcs AS source + ON source.DepartmentID = target.DepartmentID + AND source.ProviderID = target.ProviderID + AND source.FiscalYearID = target.FiscalYearID + AND source.FiscalMonthID = target.FiscalMonthID + AND source.TimeClassID = target.TimeClassID + AND source.OBForecastDetailID = target.OBForecastDetailID + WHEN MATCHED AND NOT + (target.Dollars = source.Dollars + and target.DollarsYTD = source.DollarsYTD + and target.DollarsPriorYear = source.DollarsPriorYear + and target.DollarsPriorYTD = source.DollarsPriorYTD + and target.Hours = source.Hours + and target.HoursYTD = source.HoursYTD + and target.HoursPriorYear = source.HoursPriorYear + and target.HoursPriorYTD = source.HoursPriorYTD + and target.Volume = source.Volume + and target.VolumeYTD = source.VolumeYTD + and target.VolumePriorYear = source.VolumePriorYear + and target.VolumePriorYTD = source.VolumePriorYTD + and target.FTEs = source.FTEs + and target.FTEsYTD = source.FTEsYTD + and target.FTEsPriorYear = source.FTEsPriorYear + and target.FTEsPriorYTD = source.FTEsPriorYTD) + THEN + UPDATE + SET target.Dollars = source.Dollars, + target.DollarsYTD = source.DollarsYTD, + target.DollarsPriorYear = source.DollarsPriorYear, + target.DollarsPriorYTD = source.DollarsPriorYTD, + target.Hours = source.Hours, + target.HoursYTD = source.HoursYTD, + target.HoursPriorYear = source.HoursPriorYear, + target.HoursPriorYTD = source.HoursPriorYTD, + target.Volume = source.Volume, + target.VolumeYTD = source.VolumeYTD, + target.VolumePriorYear = source.VolumePriorYear, + target.VolumePriorYTD = source.VolumePriorYTD, + target.FTEs = source.FTEs, + target.FTEsYTD = source.FTEsYTD, + target.FTEsPriorYear = source.FTEsPriorYear, + target.FTEsPriorYTD = source.FTEsPriorYTD + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + DepartmentID, + ProviderID, + FiscalMonthID, + FiscalYearID, + OBForecastDetailID, + TimeClassID, + Dollars, + DollarsYTD, + DollarsPriorYear, + DollarsPriorYTD, + Hours, + HoursYTD, + HoursPriorYear, + HoursPriorYTD, + Volume, + VolumeYTD, + VolumePriorYear, + VolumePriorYTD, + FTEs, + FTEsYTD, + FTEsPriorYear, + FTEsPriorYTD, + IsDeleted, + IsSystemGenerated + ) + VALUES ( + source.DepartmentID, + source.ProviderID, + source.FiscalMonthID, + source.FiscalYearID, + source.OBForecastDetailID, + source.TimeClassID, + source.Dollars, + source.DollarsYTD, + source.DollarsPriorYear, + source.DollarsPriorYTD, + source.Hours, + source.HoursYTD, + source.HoursPriorYear, + source.HoursPriorYTD, + source.Volume, + source.VolumeYTD, + source.VolumePriorYear, + source.VolumePriorYTD, + source.FTEs, + source.FTEsYTD, + source.FTEsPriorYear, + source.FTEsPriorYTD, + 0, + isnull(IsSystemGenerated,0) + ) + WHEN NOT MATCHED BY SOURCE + AND Target.FiscalYearID = @fiscalYearID + THEN + DELETE; + + COMMIT TRANSACTION Sampling + END TRY + BEGIN CATCH + ROLLBACK TRANSACTION Sampling; + THROW + END CATCH + END + IF OBJECT_ID('tempdb..#ProviderSampledStaging') IS NOT NULL DROP TABLE #ProviderSampledStaging + IF OBJECT_ID('fw.ProviderSampledStagingWithCalcs') IS NOT NULL DROP TABLE fw.ProviderSampledStagingWithCalcs +GO + + +--------------------------------------------- + +-- fw.procRefreshEncounterBasedStatistics +CREATE PROC fw.procRefreshEncounterBasedStatistics + @departmentIds nvarchar(MAX) = NULL +AS +BEGIN + SET NOCOUNT ON + + DROP TABLE IF EXISTS #departments + + SELECT val AS DepartmentId + INTO #departments + FROM ConvertCSValuesToTable(@departmentIds, ',') + + DROP TABLE IF EXISTS #detailsToMerge + + CREATE TABLE #detailsToMerge + ( + RowID bigint identity(1,1), + DateID int, + DepartmentID int, + AccountID int, + Value decimal(19, 4) + ) + CREATE CLUSTERED INDEX CNU_RowId ON #detailsToMerge(RowId) + + IF (@departmentIds IS NULL) + BEGIN + INSERT #detailsToMerge (DepartmentID, AccountID, DateID, Value) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, SUM(ebs.Value) + FROM fw.FactEncounterBasedStatistics ebs + INNER JOIN fw.DimAccount a + ON a.AccountID = ebs.AccountID + INNER JOIN fw.DimDepartment dep + ON dep.DepartmentID = ebs.DepartmentID + GROUP BY ebs.DepartmentID, ebs.AccountID, ebs.DateID + END + ELSE + BEGIN + INSERT #detailsToMerge (DepartmentID, AccountID, DateID, Value) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, SUM(ebs.Value) + FROM fw.FactEncounterBasedStatistics ebs + INNER JOIN fw.DimAccount a + ON a.AccountID = ebs.AccountID + INNER JOIN fw.DimDepartment dep + ON dep.DepartmentID = ebs.DepartmentID + INNER JOIN #departments d + ON ebs.DepartmentID = d.DepartmentId + GROUP BY ebs.DepartmentID, ebs.AccountID, ebs.DateID + END + + DECLARE + @startRowId bigint, + @maxRowId bigint, + @endRowId bigint + + SELECT @startRowId = MIN(RowId), @maxRowId = MAX(RowId) + FROM #detailsToMerge + + WHILE (@startRowId <= @maxRowId) + BEGIN + SELECT @endRowId = MAX(d.RowId) + FROM (SELECT TOP 1000000 RowId + FROM #detailsToMerge + WHERE RowId >= @startRowId + ORDER BY RowID) AS d + + UPDATE fw.FactChargeBasedStatistics + SET Value = ebs.Value + FROM #detailsToMerge ebs + INNER JOIN fw.FactChargeBasedStatistics cbs + ON ebs.DepartmentID = cbs.DepartmentID + AND ebs.AccountID = cbs.AccountID + AND ebs.DateID = cbs.DateID + WHERE ebs.RowId >= @startRowId + AND ebs.RowId <= @endRowId + + INSERT fw.FactChargeBasedStatistics (DepartmentID, AccountID, DateID, Value) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID, ebs.Value + FROM #detailsToMerge ebs + WHERE ebs.RowId >= @startRowId + AND ebs.RowId <= @endRowId + AND NOT EXISTS + ( + SELECT cbs.RowID + FROM fw.FactChargeBasedStatistics cbs + WHERE ebs.DepartmentID = cbs.DepartmentID + AND ebs.AccountID = cbs.AccountID + AND ebs.DateID = cbs.DateID + ) + + SELECT @startRowId = MIN(d.RowId) + FROM #detailsToMerge d + WHERE RowId > @endRowId + END + + DROP TABLE IF EXISTS #departments + DROP TABLE IF EXISTS #detailsToMerge + +END +GO + + +--------------------------------------------- + +-- fw.procRefreshEncounterBasedStatisticsMonthly +CREATE PROC fw.procRefreshEncounterBasedStatisticsMonthly + @fiscalYearId smallint = 0 +AS +BEGIN + SET NOCOUNT ON + + DROP TABLE IF EXISTS #detailsToMerge + + CREATE TABLE #detailsToMerge + ( + RowID bigint identity(1,1), + FiscalYearID smallint, + FiscalMonthID tinyint, + DepartmentID int, + AccountID int, + Value decimal(19, 4) + ) + CREATE CLUSTERED INDEX CNU_RowId ON #detailsToMerge(RowId) + + INSERT #detailsToMerge (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.FiscalYearID, ebs.FiscalMonthID, SUM(ebs.Value) + FROM fw.FactEncounterBasedStatisticsMonthly ebs + INNER JOIN fw.DimAccount a + ON a.AccountID = ebs.AccountID + INNER JOIN fw.DimDepartment dep + ON dep.DepartmentID = ebs.DepartmentID + WHERE ebs.FiscalYearID = @fiscalYearId OR @fiscalYearId = 0 + GROUP BY ebs.DepartmentID, ebs.AccountID, ebs.FiscalYearID, ebs.FiscalMonthID + + DECLARE + @startRowId bigint, + @maxRowId bigint, + @endRowId bigint + + SELECT @startRowId = MIN(RowId), @maxRowId = MAX(RowId) + FROM #detailsToMerge + + WHILE (@startRowId <= @maxRowId) + BEGIN + SELECT @endRowId = MAX(d.RowId) + FROM (SELECT TOP 1000000 RowId + FROM #detailsToMerge + WHERE RowId >= @startRowId + ORDER BY RowID) AS d + + UPDATE fw.FactChargeBasedStatisticsMonthly + SET Value = ebs.Value + FROM #detailsToMerge ebs + INNER JOIN fw.FactChargeBasedStatisticsMonthly cbs + ON ebs.DepartmentID = cbs.DepartmentID + AND ebs.AccountID = cbs.AccountID + AND ebs.FiscalYearID = cbs.FiscalYearID + AND ebs.FiscalMonthID = cbs.FiscalMonthID + WHERE ebs.RowId >= @startRowId + AND ebs.RowId <= @endRowId + + INSERT fw.FactChargeBasedStatisticsMonthly (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.FiscalYearID, ebs.FiscalMonthID, ebs.Value + FROM #detailsToMerge ebs + WHERE ebs.RowId >= @startRowId + AND ebs.RowId <= @endRowId + AND NOT EXISTS + ( + SELECT cbs.RowID + FROM fw.FactChargeBasedStatisticsMonthly cbs + WHERE ebs.DepartmentID = cbs.DepartmentID + AND ebs.AccountID = cbs.AccountID + AND ebs.FiscalYearID = cbs.FiscalYearID + AND ebs.FiscalMonthID = cbs.FiscalMonthID + ) + + SELECT @startRowId = MIN(d.RowId) + FROM #detailsToMerge d + WHERE RowId > @endRowId + END + + DROP TABLE IF EXISTS #detailsToMerge + +END +GO + + +--------------------------------------------- + +-- fw.procRestoreChargeBasedStatistics +CREATE PROC fw.procRestoreChargeBasedStatistics + @statisticID int +AS +BEGIN + SET NOCOUNT ON + + CREATE TABLE #detailsToRestore + ( + RowID bigint identity(1,1), + DateID int, + DepartmentID int, + AccountID int + ) + CREATE CLUSTERED INDEX CNU_RowId ON #detailsToRestore(RowId) + + INSERT #detailsToRestore (DepartmentID, AccountID, DateID) + SELECT ebs.DepartmentID, ebs.AccountID, ebs.DateID + FROM fw.FactEncounterBasedStatistics ebs + WHERE ebs.StatisticID = @statisticID + GROUP BY ebs.DepartmentID, ebs.AccountID, ebs.DateID + + DECLARE + @startRowId bigint, + @maxRowId bigint, + @endRowId bigint + + SELECT @startRowId = MIN(RowId), @maxRowId = MAX(RowId) + FROM #detailsToRestore + + WHILE (@startRowId <= @maxRowId) + BEGIN + SELECT @endRowId = MAX(d.RowId) + FROM (SELECT TOP 1000000 RowId + FROM #detailsToRestore + WHERE RowId >= @startRowId + ORDER BY RowID) as d + + DELETE cbs + FROM fw.FactChargeBasedStatistics cbs + JOIN #detailsToRestore ebs + ON cbs.DepartmentID = ebs.DepartmentID + AND cbs.AccountID = ebs.AccountID + AND cbs.DateID = ebs.DateID + WHERE ebs.RowId >= @startRowId + AND ebs.RowId <= @endRowId + + INSERT fw.FactChargeBasedStatistics (DepartmentID, AccountID, DateID, Value) + SELECT sgs.DepartmentID, sgs.AccountID, sgs.DateID, AVG(sgs.Value) + FROM fw.FactSystemGeneratedStatistics sgs + JOIN #detailsToRestore ebs + ON sgs.DepartmentID = ebs.DepartmentID + AND sgs.AccountID = ebs.AccountID + AND sgs.DateID = ebs.DateID + WHERE ebs.RowId >= @startRowId + AND ebs.RowId <= @endRowId + GROUP BY sgs.DepartmentID, sgs.AccountID, sgs.DateID + + SELECT @startRowId = MIN(d.RowId) + FROM #detailsToRestore d + WHERE RowId > @endRowId + END + + DROP TABLE IF EXISTS #detailsToRestore +END +GO + + +--------------------------------------------- + +-- fw.procRestoreChargeBasedStatisticsMonthly +CREATE PROC fw.procRestoreChargeBasedStatisticsMonthly + @statisticID int +AS +BEGIN + SET NOCOUNT ON + + DELETE cbs + FROM fw.FactEncounterBasedStatisticsMonthly ebs + JOIN fw.FactChargeBasedStatisticsMonthly cbs + ON ebs.DepartmentID = cbs.DepartmentID + AND ebs.AccountID = cbs.AccountID + AND ebs.FiscalYearID = cbs.FiscalYearID + AND ebs.FiscalMonthID = cbs.FiscalMonthID + WHERE ebs.StatisticID = @statisticID + + INSERT fw.FactChargeBasedStatisticsMonthly (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value) + SELECT sgs.DepartmentID, sgs.AccountID, sgs.FiscalYearID, sgs.FiscalMonthID, AVG(sgs.Value) + FROM fw.FactEncounterBasedStatisticsMonthly ebs + JOIN fw.FactSystemGeneratedStatisticsMonthly sgs + ON ebs.DepartmentID = sgs.DepartmentID + AND ebs.AccountID = sgs.AccountID + AND ebs.FiscalYearID = sgs.FiscalYearID + AND ebs.FiscalMonthID = sgs.FiscalMonthID + WHERE ebs.StatisticID = @statisticID + GROUP BY sgs.DepartmentID, sgs.AccountID, sgs.FiscalYearID, sgs.FiscalMonthID +END +GO + + +--------------------------------------------- + +-- fw.procSampleChargeBasedStatistics +/************************************************************ +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-04-12 GF B-11831 Add fiscalyear to mapping join +** 2 2017-01-31 AK B-13926 Added department filter +** 3 2018-05-04 IPetriv B-17037 PR - Set Global Weights for Charge Codes - PR Stats +** 4 2019-05-08 OV B-22974 Performance improvements for fw.procSampleChargeBasedStatistics +** 5 2024-01-08 OK JAZZ-63102 Add EBS statistic support +** 6 2024-05-17 OK JAZZ-71350 Always fill out fw.SystemGeneratedStatistics +*************************************************************/ +CREATE PROCEDURE [fw].[procSampleChargeBasedStatistics] @departmentIDs NVARCHAR(max) = NULL +AS +BEGIN + IF OBJECT_ID('tempdb..#SampleChargeBasedStatisticsDepts') IS NOT NULL + DROP TABLE #SampleChargeBasedStatisticsDepts + + SET NOCOUNT ON + + CREATE TABLE #SampleChargeBasedStatisticsDepts (val INT PRIMARY KEY) + + INSERT INTO #SampleChargeBasedStatisticsDepts + SELECT val + FROM ConvertCSValuesToTable(@departmentIDs, ',') + + CREATE TABLE #DepartmentChargeCodeStatisticMapping ( + [FiscalYearID] SMALLINT + ,[DepartmentID] INT + ,[ChargeCodeID] INT + ,[PatientTypeRollupID] INT + ,[AccountID] INT + ,[Weight] DECIMAL(19, 8) + ,[IsReviewed] BIT + ,[PriorityOrder] BIGINT + ) + + CREATE CLUSTERED INDEX BASE ON #DepartmentChargeCodeStatisticMapping ( + DepartmentID + ,ChargeCodeID + ,FiscalYearID + ,PatientTypeRollupID + ) + + INSERT INTO #DepartmentChargeCodeStatisticMapping + SELECT [FiscalYearID] + ,[DepartmentID] + ,[ChargeCodeID] + ,[PatientTypeRollupID] + ,[AccountID] + ,[Weight] + ,[IsReviewed] + ,[PriorityOrder] + FROM fw.viewDepartmentChargeCodeStatisticMapping + + IF (@departmentIDs IS NULL) + BEGIN + TRUNCATE TABLE fw.FactChargeBasedStatistics + + INSERT INTO fw.FactChargeBasedStatistics ( + AccountID + ,DepartmentID + ,DateID + ,Value + ) + SELECT map.AccountID + ,bl.DepartmentID + ,bl.ServiceDateID + ,SUM(bl.UnitsOfService * map.Weight) AS Value + FROM [dss].[FactPatientBillingLineItemDetail] bl + INNER JOIN clientdss.FactPatientEncounterSummary es ON bl.EncounterID = es.EncounterID + INNER JOIN fw.DimPatientType pt ON es.PatientTypeID = pt.PatientTypeID + INNER JOIN #DepartmentChargeCodeStatisticMapping map ON bl.DepartmentID = map.DepartmentID + AND bl.ChargeCodeID = map.ChargeCodeID + AND pt.PatientTypeRollupID = map.PatientTypeRollupID + AND map.FiscalYearID = bl.FiscalYearID + WHERE map.AccountID <> 0 + AND map.Weight <> 0 + GROUP BY map.AccountID + ,bl.DepartmentID + ,bl.ServiceDateID + END + ELSE + BEGIN + WHILE EXISTS ( + SELECT NULL + FROM fw.FactChargeBasedStatistics(NOLOCK) + WHERE DepartmentID IN ( + SELECT val + FROM #SampleChargeBasedStatisticsDepts + ) + ) + BEGIN + DELETE TOP (10000) + FROM fw.FactChargeBasedStatistics + WHERE DepartmentID IN ( + SELECT val + FROM #SampleChargeBasedStatisticsDepts + ) + END + + INSERT INTO fw.FactChargeBasedStatistics ( + AccountID + ,DepartmentID + ,DateID + ,Value + ) + SELECT map.AccountID + ,bl.DepartmentID + ,bl.ServiceDateID + ,SUM(bl.UnitsOfService * map.Weight) AS Value + FROM [dss].[FactPatientBillingLineItemDetail] bl + INNER JOIN clientdss.FactPatientEncounterSummary es ON bl.EncounterID = es.EncounterID + INNER JOIN fw.DimPatientType pt ON es.PatientTypeID = pt.PatientTypeID + INNER JOIN #DepartmentChargeCodeStatisticMapping map ON bl.DepartmentID = map.DepartmentID + AND bl.ChargeCodeID = map.ChargeCodeID + AND pt.PatientTypeRollupID = map.PatientTypeRollupID + AND map.FiscalYearID = bl.FiscalYearID + WHERE map.AccountID <> 0 + AND map.Weight <> 0 + AND map.DepartmentID IN ( + SELECT val + FROM #SampleChargeBasedStatisticsDepts + ) + GROUP BY map.AccountID + ,bl.DepartmentID + ,bl.ServiceDateID + END + + DROP TABLE #DepartmentChargeCodeStatisticMapping + + DROP TABLE #SampleChargeBasedStatisticsDepts + + EXEC fw.procCopySystemGeneratedStatistics @departmentIDs + + IF EXISTS (SELECT 1 FROM dss.SystemSetting WHERE Name = 'Enable Persistent Encounter-based Statistics' AND Value = 1) + BEGIN + EXEC fw.procRefreshEncounterBasedStatistics @departmentIDs + END + +END +GO + + +--------------------------------------------- + +-- fw.procSampleChargeBasedStatisticsMonthly +/************************************************************ +** Author: unknown +** Create Date: unknown +** Description: Translates DS charge units into account-based statistics for use throughout StrataJazz system +** Last Modified: 2015-12-17 +** GM Release: 2016.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-05-04 IPetriv B-19365 PR - Set Global Weights for Charge Codes - MR Stats +** 2 2018-07-09 IPetriv esc-09659 relace direct join to view to temptable +** 3 2021-01-19 BS JAZZ-10854 MR - Charge Based Statistics Flag +** 4 2024-01-08 OK JAZZ-63102 Add EBS statistic support +** 5 2024-05-17 OK JAZZ-71350 Always fill out fw.SystemGeneratedStatisticsMonthly +*************************************************************/ +CREATE proc [fw].[procSampleChargeBasedStatisticsMonthly] + @fiscalYearID smallint = 0 +AS +BEGIN + IF (@fiscalYearID = 0) + BEGIN + TRUNCATE TABLE fw.FactChargeBasedStatisticsMonthly + END + ELSE + BEGIN + WHILE EXISTS(SELECT NULL FROM fw.FactChargeBasedStatisticsMonthly (nolock) WHERE FiscalYearID = @fiscalYearID) + DELETE top (1000000) fw.FactChargeBasedStatisticsMonthly WHERE FiscalYearID = @fiscalYearID + END + + IF (CAST((SELECT Value FROM mr.SystemSetting WHERE Name = 'Monthly Charged Based Statistics Enabled') AS bit) = 1) + BEGIN + exec [dbo].[procSysDropTempTable] '#Map' + + SELECT * + INTO #Map + FROM fw.viewDepartmentChargeCodeStatisticMapping map + WHERE map.AccountID <> 0 + AND map.Weight <> 0 + AND ( + FiscalYearID = @fiscalYearID + OR @fiscalYearID = 0 + ) + IF (CAST((SELECT Value FROM fw.SystemSetting WHERE Name = 'Charge Statistics Use Post Date') AS bit) = 1) + BEGIN + --use post date + + INSERT INTO fw.FactChargeBasedStatisticsMonthly (AccountID, DepartmentID, FiscalYearID, FiscalMonthID, Value) + SELECT + map.AccountID, + bl.DepartmentID, + d.FiscalYear, + d.CalendarMonth, + SUM(bl.UnitsOfService * map.Weight) AS Value + FROM + dss.[FactPatientBillingLineItemDetail] bl + INNER JOIN fw.DimDate d WITH (READUNCOMMITTED) ON d.DateID = bl.PostDateID + INNER JOIN clientdss.FactPatientEncounterSummary es WITH (READUNCOMMITTED) ON bl.EncounterID = es.EncounterID + INNER JOIN fw.DimPatientType pt WITH (READUNCOMMITTED) ON es.PatientTypeID = pt.PatientTypeID + INNER JOIN #Map map WITH (READUNCOMMITTED) ON bl.DepartmentID = map.DepartmentID AND bl.ChargeCodeID = map.ChargeCodeID AND pt.PatientTypeRollupID = map.PatientTypeRollupID AND map.FiscalYearID = d.FiscalYear + GROUP BY + map.AccountID, + bl.DepartmentID, + d.FiscalYear, + d.CalendarMonth + END + ELSE + BEGIN + --use service date + INSERT INTO fw.FactChargeBasedStatisticsMonthly (AccountID, DepartmentID, FiscalYearID, FiscalMonthID, Value) + SELECT + map.AccountID, + bl.DepartmentID, + d.FiscalYear, + d.CalendarMonth, + SUM(bl.UnitsOfService * map.Weight) AS Value + FROM + dss.[FactPatientBillingLineItemDetail] bl + INNER JOIN fw.DimDate d WITH (READUNCOMMITTED) ON d.DateID = bl.ServiceDateID + INNER JOIN clientdss.FactPatientEncounterSummary es WITH (READUNCOMMITTED) ON bl.EncounterID = es.EncounterID + INNER JOIN fw.DimPatientType pt WITH (READUNCOMMITTED) ON es.PatientTypeID = pt.PatientTypeID + INNER JOIN #Map map WITH (READUNCOMMITTED) ON bl.DepartmentID = map.DepartmentID AND bl.ChargeCodeID = map.ChargeCodeID AND pt.PatientTypeRollupID = map.PatientTypeRollupID AND map.FiscalYearID = d.FiscalYear + GROUP BY + map.AccountID, + bl.DepartmentID, + d.FiscalYear, + d.CalendarMonth + END + exec [dbo].[procSysDropTempTable] '#Map' + END + + EXEC fw.procCopySystemGeneratedStatisticsMonthly @fiscalYearID + + IF EXISTS (SELECT 1 FROM dss.SystemSetting WHERE Name = 'Enable Persistent Encounter-based Statistics' AND Value = 1) + BEGIN + EXEC fw.procRefreshEncounterBasedStatisticsMonthly @fiscalYearID + END + +END +GO + + +--------------------------------------------- + +-- fw.procScoreFillinSetYears +--/****** Object: StoredProcedure [dbo].[procCustomEMFSetYearFillins] Script Date: 11/09/2009 17:17:57 ******/ +--SET ANSI_NULLS ON +--GO + +--SET QUOTED_IDENTIFIER ON +--GO + + + + + + +CREATE proc [fw].[procScoreFillinSetYears] + @planguid uniqueidentifier + ,@PHSectionGUID uniqueidentifier + ,@FIDimensionGUID uniqueidentifier + ,@newFirstValue int + ,@newNumMembers int + ,@datatableGUIDList varchar(max) +as + + +--set @datatableGUIDList = '47413A00-1994-4606-8948-2BDFEDAC1FB9,63A2935D-EDB8-4DAF-863F-677831C6AC4E' +--set @planguid = 'DC0BC93A-F1D3-4BD1-B684-29DA5CBB8EEB' +--set @FIDimensionGUID = 'B383B29F-087E-4450-A216-3A3F03BB08D3' +--set @PHSectionGUID = '7696E505-7372-4D53-B6D5-5C8F95319C44' +--set @newFirstValue = 2009 +--set @newNumMembers= 5 + + +--record current first value for this section +declare @oldFirstValue int +declare @oldNumMembers int +select + @oldFirstValue = MIN(fy.fiscalyearid), + @oldNumMembers= COUNT(distinct fy.fiscalyearid) +from + ScoreFillin fi + inner join fw.DimFiscalYear fy on fi.FillinMemberGUID = fy.MemberGUID +where + fi.PlaceholderSectionMemberGUID = @PHSectionGUID + and fi.ModelGUID = @planguid + +if @oldFirstValue = @newFirstValue and @newNumMembers= @oldNumMembers begin + print 'Already set correctly.' + return +end + +--clear fillins for this section +delete from ScoreFillin +where + PlaceholderSectionMemberGUID = @PHSectionGUID + and ModelGUID = @planguid + +--set fillins for this section +insert into ScoreFillin (modelguid, PlaceholderSectionMemberGUID, PlaceholderIndex, FillinMemberGUID, FillinMemberName) +select + @planguid, @PHSectionGUID, ROW_NUMBER() over (order by fiscalyearid) - 1, MemberGUID, FiscalYearID +from + fw.DimFiscalYear +where + FiscalYearID between @newFirstValue and @newFirstValue + @newNumMembers- 1 +order by + FiscalYearID + +declare @offset int +set @offset = @newfirstvalue - @oldFirstValue + +declare @planDimensionGUID uniqueidentifier +select @planDimensionGUID = dimensionguid from PlanType where PlanTypeGUID = (select PlanTypeGUID from XPlan where PlanGUID = @planguid) + +declare @planDimensionSchema nvarchar(max) +declare @planDimensionObject nvarchar(max) +declare @planDimensionKeyColumnName nvarchar(max) + +select + @planDimensionSchema = sd.SQLSchemaName + ,@planDimensionObject = sd.SQLObjectName + ,@planDimensionKeyColumnName = dk.SQLColumnName --this is a touch hacky as it assumes default key is whats in the data tables +from + ScoreDimension sd + inner join ScoreAttribute dk on sd.DefaultKeyGUID = dk.AttributeGUID +where + sd.DimensionGUID = @planDimensionGUID + +declare @FIDimensionKeyColumnName nvarchar(max) +select + @FIDimensionKeyColumnName = dk.SQLColumnName --this is a touch hacky as it assumes default key is whats in the data tables +from + ScoreDimension sd + inner join ScoreAttribute dk on sd.DefaultKeyGUID = dk.AttributeGUID +where + sd.DimensionGUID = @FIDimensionGUID + + + +declare @sql nvarchar(max) + +set @sql = ' +declare @offset int +set @offset = ' + cast(@offset as varchar(max)) + ' + +declare @planguid uniqueidentifier +set @planguid = ''' + cast(@planguid as varchar(36)) + ''' + +--update data across all composites that use the specified placeholder dimension, and the specified plan dimension +update + [{schema}].[{object}] +set + [' + @FIDimensionKeyColumnName + '] = [' + @FIDimensionKeyColumnName + '] + @offset +where + [' + @planDimensionKeyColumnName + '] = (select [' + @planDimensionKeyColumnName + '] from [' + @planDimensionSchema + '].[' + @planDimensionObject + '] where MemberGUID = @planguid) + and [' + @FIDimensionKeyColumnName + '] <> 0 + and isdeleted = 0 + +--delete data where value is not in correct range (and is not unspecified year) +update + [{schema}].[{object}] +set + isdeleted = 1 +where + [' + @planDimensionKeyColumnName + '] = (select [' + @planDimensionKeyColumnName + '] from [' + @planDimensionSchema + '].[' + @planDimensionObject + '] where MemberGUID = @planguid) + and [' + @FIDimensionKeyColumnName + '] <> 0 + and not [' + @FIDimensionKeyColumnName + '] between ' + cast(@newFirstValue as varchar(36)) + ' and ' + cast(@newFirstValue + @newNumMembers - 1 as varchar(max)) + ' + + +' + + +declare @where varchar(max) +set @where = 'where datatableguid in (select guid from dbo.CSVGuidsToTable(''' + @datatableguidlist + '''))' + +exec [procScoreRunForManyStructures] @sql, @where,1,0 + + + +--set @FirstMemberGUID = dbo.GetModelFirstFillInSection(@planguid, @phsectionguid) + + +--if @FirstMemberGUID = '00000000-0000-0000-0000-000000000000' begin +-- exec procEMFFillInAddToEndSection @phsectionguid, @targetfirstmemberguid, @planguid +-- set @firstmemberguid = @targetfirstmemberguid +--end + +--DECLARE @OFFSET Int + +--SELECT @OFFSET = tfm.DisplayOrder - fm.DisplayOrder +--FROM +-- SecureListMember fm +-- inner join SecureListMember tfm on fm.ListMemberGUID = @FirstMemberGUID and tfm.ListMemberGUID = @TargetFirstMemberGUID + +--if @OFFSET is null return + +--DECLARE @ONEGUID UniqueIdentifier +--SET @ONEGUID = '11111111-1111-1111-1111-111111111111' + +--declare @PHDimGUID uniqueidentifier +--SELECT @PHDimGUID = listguid from SecureListMember where ListMemberGUID = @PHSectionGUID + +--if @PHDimGUID is null return + +--declare @fidimguid uniqueidentifier +--select @fidimguid = fillindimensionguid from SecureList where ListGUID = @PHDimGUID + +--if @fidimguid is null return + +--declare @higuid uniqueidentifier + +--declare @cnt int +--exec procLogObjectHistory @PlanGUID, 'Changing base fill-in', 0, @higuid output + +----FIX FILLINS +--UPDATE EMFFillIn SET FilledInMemberGUID = dbo.GetSecureListOffsetMember(FilledInMemberGUID,@offset) +--WHERE +-- ModelGUID = @PlanGUID +-- AND PlaceholderMemberGUID IN (SELECT ListMemberGUID FROM SecureListMember WHERE ParentListMemberGUID = @PHSectionGUID) + +----DELETE FILLINS PUSHED OFF THE END of possible members +--DELETE FROM EMFFillIn WHERE +-- MODELGUID = @PLANGUID +-- and FilledInMemberGUID = @ONEGUID + +----DELETE FILLINS PUSHED OFF THE END of # of members +--DELETE FROM EMFFillIn WHERE ModelGUID = @PlanGUID AND FilledInMemberGUID IN (SELECT GUID FROM dbo.getFillinMembersPastMaxIndex(@PLANGUID, @PHDimGUID, @NumMembers)) + +----add FILLINS to equal # of members +--exec procEMFFillInAdd @planguid, @PHDimGUID, @NumMembers + +--declare @sql varchar(max) +--declare @mdTableName varchar(max) + +--declare @phDimColumnName varchar(max) +--set @phDimColumnName = 'G' + REPLACE(cast(@phdimguid as varchar(36)),'-','_') + +--set @sql = ' +--declare @msg varchar(max) +--declare @cnt int +--declare @planguid uniqueidentifier +--set @planguid = ''' + cast(@planguid as varchar(36))+ ''' + +--declare @fidimguid uniqueidentifier +--set @fidimguid = ''' + cast(@fidimguid as varchar(36))+ ''' + +--declare @PHSectionGUID uniqueidentifier +--set @PHSectionGUID = ''' + cast(@PHSectionGUID as varchar(36))+ ''' + +--declare @oneguid uniqueidentifier +--set @oneguid = ''11111111-1111-1111-1111-111111111111'' + +--declare @higuid uniqueidentifier +--set @higuid = ''' + cast(@higuid as varchar(36)) + ''' + +--UPDATE zzemfmodeldata_{mdcguidfriendly} +--SET +-- zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' = dbo.GetSecureListOffsetMember(zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ',' + cast(@offset as varchar(4)) + ') +-- ,HISTORYITEMGUID = @higuid +--WHERE +-- MODELGUID = @planguid +-- --ONLY Update data who was previously assigned to a member that was filling in the section we are updating, altho this could cause a duplicate issue +-- AND zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' +-- IN ( SELECT FI.FilledInMemberGUID FROM EMFFillIn FI WHERE FI.PlaceholderMemberGUID +-- IN (SELECT ListMemberGUID FROM SecureListMember WHERE ParentListMemberGUID = @PHSectionGUID)) + +--DELETE FROM zzemfmodeldata_{mdcguidfriendly} WHERE VALUE = 0 AND MODELGUID = @PLANGUID and zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' = @ONEGUID +--DELETE FROM zzemfmodeldata_{mdcguidfriendly} WHERE MODELGUID = @PLANGUID and (zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' = @ONEGUID +-- OR ( +-- not zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' in (select filledinmemberguid from emffillin where modelguid = @planguid) --orphan cause not filled in +-- and +-- not zzemfmodeldata_{mdcguidfriendly}.' + @phDimColumnName + ' = ''00000000-0000-0000-0000-000000000000'' --not orphaned because emptyguid is ok +-- ) +-- ) + +--set @cnt = @@rowcount +--if @cnt > 0 begin +-- set @msg = ''Cleared orphaned nonzero cells from {mdcname} while changing Year configuration'' +-- exec procLogObjectHistory @PlanGUID, @msg, @cnt, @higuid +--end + +--' + + +--declare @mtguid uniqueidentifier +--select @mtguid = modeltemplateguid from XPlan where PlanGUID = @PLANGUID + +----FOR EACH MD TABLE USED BY THIS PLAN +--declare @where varchar(max) +--set @where = 'where modeldataconfigguid in (select modeldataconfigguid from viewEMFModelTemplateMDCs where modeltemplateguid = ''' + cast(@mtguid as varchar(36)) + ''') +-- and modeldataconfigguid in (select modeldataconfigguid from emfmodeldataconfigdimensionlink where dimensionguid = ''' + cast(@PHDimGUID as varchar(36)) + ''') +--' + +--exec procEMFRunForManyStructures @sql, @where, 1 +GO + + +--------------------------------------------- + +-- fw.procSetCurrentDataPayPeriodID +CREATE proc [fw].[procSetCurrentDataPayPeriodID] +as + +declare @currentPP int; + +set @currentPP = ( + select + MAX(pr.PayPeriodID) + from + fw.FactPayrollSampledPayPeriod pr + inner join fw.DimPayPeriod pp on pp.PayPeriodID = pr.PayPeriodID + where + pr.TimeClassID=1 + and (pr.Dollars <> 0 or pr.Hours <> 0) + and pp.PayCycleID=0 + ) + +if (@currentPP is null) set @currentPP = 0 + +exec procChangeDBSetting 'Current_Payroll_PayPeriodID', @currentPP + +--Update Default Report Parameter-------------------------------------------------------------- +exec [pi].[procReportDefaultParameterUpdateToCurrent] +GO + + +--------------------------------------------- + +-- fw.procStatisticPrimarySampledAdjustedTargetMonthlyInsert +CREATE PROCEDURE [fw].[procStatisticPrimarySampledAdjustedTargetMonthlyInsert] (@FiscalYearID int = 0) +AS +BEGIN +/* +Proposal + +If the client is not using flexing, this will be the target plus the efficiency factor +This should work regardless of the target basis (i.e. rolling avg or budget) +The factor will be applied after the inversion +If the factor type is percentage, the adjusted target will be the target*(1+factor) +i.e. if my target is 100 and my factor is 5%, the adjusted target will be 100*(1+0.05)=105 +i.e. if my target is 100 and my factor is -5%, the adjusted target will be 100*(1+-0.05)=95 +If the factor type is value, the adjusted value will be target + factor +i.e. if my target is 1000 and my factor is 200, the adjusted target will be will be 1000+200=1200 +i.e. if my target is 1000 and my factor is -200, the adjusted target will be 1000-200=800 +If there is more than one factor impacting a department and account or job code/pay code group combination, then the factors should layer on top of each other based on history order +If an efficiency factor does not exist for a particular account/job code, then the value in the new time class will be either flex or baseline target if flex is not used +This will happen after Flex is calculated +Include integration tests +*/ +/* +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-08-23 BC JAZZ-11498 Change Table Variable to Temporary Tables +************************************************************ +*/ +DECLARE @IsFlexingEnabled INT = ( + SELECT VALUE + FROM [mr].[SystemSetting] + WHERE NAME = 'Is Target Flexed' + ) + +IF OBJECT_ID('tempdb..#EfficiencyFactorScope') IS NOT NULL DROP TABLE #EfficiencyFactorScope +CREATE TABLE #EfficiencyFactorScope ( + EfficiencyFactorGUID [uniqueidentifier] NOT NULL + ,[DepartmentID] [int] NOT NULL + ,[AccountID] [int] NOT NULL + ,[FiscalYearID] [smallint] NOT NULL + ,[FiscalMonthID] [tinyint] NOT NULL + ,Value NUMERIC(25, 6) NOT NULL + ,Type TINYINT + ,FactorType CHAR(1) + ,DateCreated DATETIME + ,UNIQUE CLUSTERED ( + FiscalYearID + ,FiscalMonthID + ,DepartmentID + ,AccountID + ,EfficiencyFactorGUID + ) + ); +IF EXISTS (SELECT TOP 1 * FROM [mr].[EfficiencyFactor]) BEGIN +WITH EfficiencyFactorScope +AS ( + SELECT * + ,rn = ROW_NUMBER() OVER ( + PARTITION BY FiscalYearID + ,FiscalMonthID + ,DepartmentID + ,AccountID + ,EfficiencyFactorGUID ORDER BY FiscalYearID + ,FiscalMonthID + ,DepartmentID + ,AccountID + ,EfficiencyFactorGUID + ) + FROM ( + SELECT DISTINCT ef.EfficiencyFactorGUID + ,ef.FiscalYearID + ,efgd.FiscalMonthID + ,efd.DepartmentID + ,isnull(efgd.AccountID, da.AccountID) AS AccountID + ,CASE + WHEN isnull(efgd.AccountID, - 999) = da.AccountID + THEN 0 + ELSE efgd.Value + END AS Value + ,ef.Type + ,ef.FactorType + ,ef.DateCreated + FROM mr.EfficiencyFactor ef + INNER JOIN mr.EfficiencyFactorDepartment efd ON ef.EfficiencyFactorGUID = efd.EfficiencyFactorGUID + INNER JOIN mr.EfficiencyFactorGLDetails efgd ON efgd.EfficiencyFactorGUID = ef.EfficiencyFactorGUID + LEFT JOIN fw.DimAccount da ON efgd.OBFinancialReportingID = da.OBUnitsFinancialReportingID and efgd.AccountID IS NULL + LEFT JOIN mr.EfficiencyFactorGLDetails efgd_exist ON efgd.EfficiencyFactorGUID = efgd_exist.EfficiencyFactorGUID and efgd_exist.AccountID = da.AccountID and efgd_exist.FiscalMonthID = efgd.FiscalMonthID + WHERE (@FiscalYearID = ef.FiscalYearID or @FiscalYearID = 0) and (efgd_exist.AccountID is null or da.AccountID is null) AND ef.Type = 1 AND isnull(efgd.AccountID, da.AccountID) IS NOT NULL + ) X + ) +INSERT INTO #EfficiencyFactorScope ( + EfficiencyFactorGUID + ,[DepartmentID] + ,[AccountID] + ,[FiscalYearID] + ,[FiscalMonthID] + ,Value + ,Type + ,FactorType + ,DateCreated + ) +SELECT EfficiencyFactorGUID + ,[DepartmentID] + ,[AccountID] + ,[FiscalYearID] + ,[FiscalMonthID] + ,Value + ,Type + ,FactorType + ,DateCreated +FROM EfficiencyFactorScope +WHERE RN = 1 + +DELETE FROM fw.FactStatisticPrimarySampledMonthly WHERE (@FiscalYearID = FiscalYearID or @FiscalYearID = 0) and TimeClassID = 22 + +INSERT INTO fw.FactStatisticPrimarySampledMonthly (DepartmentID, +AccountID, +FiscalYearID, +FiscalMonthID, +TimeClassID, +IsDeleted, +Amount) +SELECT DepartmentID + ,AccountID + ,FiscalYearID + ,FiscalMonthID + ,22 as TimeClassID + ,0 as IsDeleted + ,SUM(Amount) as Amount +FROM ( +SELECT isnull(fact.DepartmentID,ToApply.DepartmentID) as DepartmentID + ,isnull(fact.AccountID,toApply.AccountID) as AccountID + ,isnull(fact.FiscalYearID,toApply.FiscalYearID) as FiscalYearID + ,isnull(fact.FiscalMonthID,toApply.FiscalMonthID) as FiscalMonthID + ,Amount = CASE + WHEN FactorType = 'P' + THEN isnull(fact.Amount,0.0) * isnull(Value,0.0) / 100 + WHEN FactorType = 'V' + THEN isnull(Value,0.0) + ELSE 0 + END +FROM #EfficiencyFactorScope ToApply + INNER JOIN (SELECT distinct DepartmentID,AccountID from fw.FactStatisticPrimarySampledMonthly) GenCand on + GenCand.DepartmentID = ToApply.DepartmentID + AND GenCand.AccountID = ToApply.AccountID + FULL JOIN fw.FactStatisticPrimarySampledMonthly fact ON + fact.DepartmentID = ToApply.DepartmentID + AND fact.AccountID = ToApply.AccountID + AND fact.FiscalYearID = ToApply.FiscalYearID + AND fact.FiscalMonthID = ToApply.FiscalMonthID + WHERE ( + ( + isnull(fact.TimeClassID,0) = 4 + AND @IsFlexingEnabled = 1 + ) + OR ( + isnull(fact.TimeClassID,0) = 20 + AND @IsFlexingEnabled = 0 + ) + ) + and (fact.FiscalYearID = @FiscalYearID or @FiscalYearID = 0) +UNION ALL + +SELECT DepartmentID + ,AccountID + ,FiscalYearID + ,FiscalMonthID + ,Amount +FROM fw.FactStatisticPrimarySampledMonthly fact +WHERE ( + ( + isnull(fact.TimeClassID,0) = 4 + AND @IsFlexingEnabled = 1 + ) + OR ( + isnull(fact.TimeClassID,0) = 20 + AND @IsFlexingEnabled = 0 + ) + ) + and (fact.FiscalYearID = @FiscalYearID or @FiscalYearID = 0) +) X +GROUP BY DepartmentID + ,AccountID + ,FiscalYearID + ,FiscalMonthID + +exec [fw].[procFactMonthlyYTDPriorYearUpdate] @factTableName = 'fw.FactStatisticPrimarySampledMonthly',@keyNameCSV = 'AccountID',@measureNameCSV = 'Amount',@fiscalYearID = 0,@timeClassID = 22,@isDebugOnly = 0 +END +END +IF OBJECT_ID('tempdb..#EfficiencyFactorScope') IS NOT NULL DROP TABLE #EfficiencyFactorScope +GO + + +--------------------------------------------- + +-- fw.procStatisticPrimarySampledInsertMonthly +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2014-09-03 MS B-02863 Removing the parameter from the YTD proc call +** 2 2016-09-22 AK B-11845 procFactStatisticPrimarySampledBaselineTargetUpdate +** 3 2016-12-13 NL B-13759 Adding fiscalYearID param and filtering +** 4 2017-02-20 GF D-05545 Move duplicate record handling from YTD into sampling + general cleanup +** 5 2017-03-06 GF B-14693 Added baseline target year filter +** 6 2017-04-11 IP B-15086 Sampling Performance Improvements. Using temp tables insead of fw.procStatisticPrimarySampledInsertMonthly +** 7 2017-06-15 IP B-15086 Modify SP to use unique temp table +** 8 2017-07-19 IP TK-45395 added isSystemGenerated to merge statement +** 9 2017-07-26 ipetriv B-16752 Added units Budget Adjustment +** 10 2017-08-29 ip B-16798 Add using of Budget Adjustment. +** 11 2022-03-15 KF JAZZ-27781 Run PR Process Task can fail silently during Payroll Sampling +*************************************************************/ +CREATE proc [fw].[procStatisticPrimarySampledInsertMonthly] + @fiscalYearID smallint = 0 +as + IF OBJECT_ID('tempdb..#StatisticPrimarySampledStaging') IS NOT NULL DROP TABLE #StatisticPrimarySampledStaging + IF OBJECT_ID('fw.StatisticPrimarySampledStagingWithCalcs') IS NOT NULL DROP TABLE fw.StatisticPrimarySampledStagingWithCalcs + + CREATE TABLE #StatisticPrimarySampledStaging (RowID bigint identity(1,1),AccountID int, DepartmentID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, Amount decimal(19,4), isDeleted bit, isSystemGenerated bit) + insert into #StatisticPrimarySampledStaging (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Amount) + exec fw.PrepareStatistics @FiscalYearID,1 + + --run calculations + exec fw.procFactMonthlyMergeDuplicates 'fw.FactStatisticPrimarySampledMonthly', 'AccountID', 'Amount', @fiscalYearID, 0, 0 + exec fw.procFactStatisticPrimarySampledBaselineTargetUpdate @fiscalYearID = @fiscalYearID + exec fw.procFactMonthlyYTDPriorYearUpdateStaging 'fw.FactStatisticPrimarySampledMonthly','#StatisticPrimarySampledStaging', 'AccountID', 'Amount', @fiscalYearID, 0, 0 + + IF @fiscalYearID = 0 + BEGIN + truncate table fw.FactStatisticPrimarySampledMonthly + INSERT INTO fw.FactStatisticPrimarySampledMonthly With (TABLOCKX) ( + DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, + Amount, + AmountYTD, + AmountPriorYear, + AmountPriorYTD, + IsDeleted, + IsSystemGenerated + ) + SELECT DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, + Amount, + AmountYTD, + AmountPriorYear, + AmountPriorYTD, + 0 as IsDeleted, + isnull(IsSystemGenerated,0) as IsSystemGenerated + FROM fw.StatisticPrimarySampledStagingWithCalcs + END +ELSE + BEGIN + print 'Starting creating index --- '+convert(varchar(20),GETDATE(),113) + CREATE CLUSTERED INDEX IDX_TempPayrollWithCalcs on fw.StatisticPrimarySampledStagingWithCalcs (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID) + print 'Starting transaction --- '+convert(varchar(20),GETDATE(),113) + BEGIN TRANSACTION Sampling + BEGIN TRY + MERGE fw.FactStatisticPrimarySampledMonthly With (TABLOCKX) AS target + USING fw.StatisticPrimarySampledStagingWithCalcs AS source + ON source.DepartmentID = target.DepartmentID + AND source.AccountID = target.AccountID + AND source.FiscalYearID = target.FiscalYearID + AND source.FiscalMonthID = target.FiscalMonthID + AND source.TimeClassID = target.TimeClassID + WHEN MATCHED AND + (target.Amount <> source.Amount + or target.AmountYTD <> source.AmountYTD + or target.AmountPriorYear <> source.AmountPriorYear + or target.AmountPriorYTD <> source.AmountPriorYTD + or target.IsSystemGenerated <> source.IsSystemGenerated + ) + THEN + UPDATE + SET target.Amount = source.Amount, + target.AmountYTD = source.AmountYTD, + target.AmountPriorYear = source.AmountPriorYear, + target.AmountPriorYTD = source.AmountPriorYTD, + target.IsSystemGenerated = source.IsSystemGenerated + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, + Amount, + AmountYTD, + AmountPriorYear, + AmountPriorYTD, + IsDeleted, + IsSystemGenerated + ) + VALUES ( + source.DepartmentID, + source.AccountID, + source.FiscalYearID, + source.FiscalMonthID, + source.TimeClassID, + source.Amount, + source.AmountYTD, + source.AmountPriorYear, + source.AmountPriorYTD, + 0, + isnull(IsSystemGenerated,0) + ) + WHEN NOT MATCHED BY SOURCE + AND Target.FiscalYearID = @fiscalYearID + THEN + DELETE; + + COMMIT TRANSACTION Sampling + END TRY + BEGIN CATCH + ROLLBACK TRANSACTION Sampling; + THROW + END CATCH + END + IF OBJECT_ID('tempdb..#StatisticPrimarySampledStaging') IS NOT NULL DROP TABLE #StatisticPrimarySampledStaging + IF OBJECT_ID('fw.StatisticPrimarySampledStagingWithCalcs') IS NOT NULL DROP TABLE fw.StatisticPrimarySampledStagingWithCalcs +GO + + +--------------------------------------------- + +-- fw.procStatisticSampledAdjustedTargetMonthlyInsert +CREATE PROCEDURE [fw].[procStatisticSampledAdjustedTargetMonthlyInsert] (@FiscalYearID int = 0) +AS +BEGIN +/* +Proposal + +If the client is not using flexing, this will be the target plus the efficiency factor +This should work regardless of the target basis (i.e. rolling avg or budget) +The factor will be applied after the inversion +If the factor type is percentage, the adjusted target will be the target*(1+factor) +i.e. if my target is 100 and my factor is 5%, the adjusted target will be 100*(1+0.05)=105 +i.e. if my target is 100 and my factor is -5%, the adjusted target will be 100*(1+-0.05)=95 +If the factor type is value, the adjusted value will be target + factor +i.e. if my target is 1000 and my factor is 200, the adjusted target will be will be 1000+200=1200 +i.e. if my target is 1000 and my factor is -200, the adjusted target will be 1000-200=800 +If there is more than one factor impacting a department and account or job code/pay code group combination, then the factors should layer on top of each other based on history order +If an efficiency factor does not exist for a particular account/job code, then the value in the new time class will be either flex or baseline target if flex is not used +This will happen after Flex is calculated +Include integration tests +*/ +/* +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-08-23 BC JAZZ-11498 Change Table Variable to Temporary Tables +************************************************************ +*/ +DECLARE @IsFlexingEnabled INT = ( + SELECT VALUE + FROM [mr].[SystemSetting] + WHERE NAME = 'Is Target Flexed' + ) +IF OBJECT_ID('tempdb..#EfficiencyFactorScope') IS NOT NULL DROP TABLE #EfficiencyFactorScope +CREATE TABLE #EfficiencyFactorScope ( + EfficiencyFactorGUID [uniqueidentifier] NOT NULL + ,[DepartmentID] [int] NOT NULL + ,[AccountID] [int] NOT NULL + ,[FiscalYearID] [smallint] NOT NULL + ,[FiscalMonthID] [tinyint] NOT NULL + ,Value NUMERIC(25, 6) NOT NULL + ,Type TINYINT + ,FactorType CHAR(1) + ,DateCreated DATETIME + ,UNIQUE CLUSTERED ( + FiscalYearID + ,FiscalMonthID + ,DepartmentID + ,AccountID + ,EfficiencyFactorGUID + ) + ); +IF EXISTS (SELECT TOP 1 * FROM [mr].[EfficiencyFactor]) BEGIN +WITH EfficiencyFactorScope +AS ( + SELECT * + ,rn = ROW_NUMBER() OVER ( + PARTITION BY FiscalYearID + ,FiscalMonthID + ,DepartmentID + ,AccountID + ,EfficiencyFactorGUID ORDER BY FiscalYearID + ,FiscalMonthID + ,DepartmentID + ,AccountID + ,EfficiencyFactorGUID + ) + FROM ( + SELECT DISTINCT ef.EfficiencyFactorGUID + ,ef.FiscalYearID + ,efgd.FiscalMonthID + ,efd.DepartmentID + ,isnull(efgd.AccountID, da.AccountID) AS AccountID + ,CASE + WHEN isnull(efgd.AccountID, - 999) = da.AccountID + THEN 0 + ELSE efgd.Value + END AS Value + ,ef.Type + ,ef.FactorType + ,ef.DateCreated + FROM mr.EfficiencyFactor ef + INNER JOIN mr.EfficiencyFactorDepartment efd ON ef.EfficiencyFactorGUID = efd.EfficiencyFactorGUID + INNER JOIN mr.EfficiencyFactorGLDetails efgd ON efgd.EfficiencyFactorGUID = ef.EfficiencyFactorGUID + LEFT JOIN fw.DimAccount da ON efgd.OBFinancialReportingID = da.OBUnitsFinancialReportingID and efgd.AccountID IS NULL + LEFT JOIN mr.EfficiencyFactorGLDetails efgd_exist ON efgd.EfficiencyFactorGUID = efgd_exist.EfficiencyFactorGUID and efgd_exist.AccountID = da.AccountID and efgd_exist.FiscalMonthID = efgd.FiscalMonthID + WHERE (@FiscalYearID = ef.FiscalYearID or @FiscalYearID = 0) and (efgd_exist.AccountID is null or da.AccountID is null) AND ef.Type = 1 AND isnull(efgd.AccountID, da.AccountID) IS NOT NULL + ) X + ) +INSERT INTO #EfficiencyFactorScope ( + EfficiencyFactorGUID + ,[DepartmentID] + ,[AccountID] + ,[FiscalYearID] + ,[FiscalMonthID] + ,Value + ,Type + ,FactorType + ,DateCreated + ) +SELECT EfficiencyFactorGUID + ,[DepartmentID] + ,[AccountID] + ,[FiscalYearID] + ,[FiscalMonthID] + ,Value + ,Type + ,FactorType + ,DateCreated +FROM EfficiencyFactorScope +WHERE RN = 1 + +DELETE FROM fw.FactStatisticSampledMonthly WHERE (@FiscalYearID = FiscalYearID or @FiscalYearID = 0) and TimeClassID = 22 + +INSERT INTO fw.FactStatisticSampledMonthly (DepartmentID, +AccountID, +FiscalYearID, +FiscalMonthID, +TimeClassID, +IsDeleted, +Amount) +SELECT DepartmentID + ,AccountID + ,FiscalYearID + ,FiscalMonthID + ,22 as TimeClassID + ,0 as IsDeleted + ,SUM(Amount) as Amount +FROM ( +SELECT isnull(fact.DepartmentID,ToApply.DepartmentID) as DepartmentID + ,isnull(fact.AccountID,toApply.AccountID) as AccountID + ,isnull(fact.FiscalYearID,toApply.FiscalYearID) as FiscalYearID + ,isnull(fact.FiscalMonthID,toApply.FiscalMonthID) as FiscalMonthID + ,Amount = CASE + WHEN FactorType = 'P' + THEN isnull(fact.Amount,0.0) * isnull(Value,0.0) / 100.00 + WHEN FactorType = 'V' + THEN isnull(Value,0) + ELSE 0 + END +FROM #EfficiencyFactorScope ToApply + INNER JOIN (SELECT distinct DepartmentID,AccountID from fw.FactStatisticSampledMonthly) GenCand on + GenCand.DepartmentID = ToApply.DepartmentID + AND GenCand.AccountID = ToApply.AccountID + FULL JOIN fw.FactStatisticSampledMonthly fact ON + fact.DepartmentID = ToApply.DepartmentID + AND fact.AccountID = ToApply.AccountID + AND fact.FiscalYearID = ToApply.FiscalYearID + AND fact.FiscalMonthID = ToApply.FiscalMonthID + WHERE ( + ( + isnull(fact.TimeClassID,0) = 4 + AND @IsFlexingEnabled = 1 + ) + OR ( + isnull(fact.TimeClassID,0) = 20 + AND @IsFlexingEnabled = 0 + ) + ) + and (fact.FiscalYearID = @FiscalYearID or @FiscalYearID = 0) +UNION ALL + +SELECT DepartmentID + ,AccountID + ,FiscalYearID + ,FiscalMonthID + ,Amount +FROM fw.FactStatisticSampledMonthly fact +WHERE ( + ( + isnull(fact.TimeClassID,0) = 4 + AND @IsFlexingEnabled = 1 + ) + OR ( + isnull(fact.TimeClassID,0) = 20 + AND @IsFlexingEnabled = 0 + ) + ) + and (fact.FiscalYearID = @FiscalYearID or @FiscalYearID = 0) +) X +GROUP BY DepartmentID + ,AccountID + ,FiscalYearID + ,FiscalMonthID + +exec [fw].[procFactMonthlyYTDPriorYearUpdate] @factTableName = 'fw.FactStatisticSampledMonthly',@keyNameCSV = 'AccountID',@measureNameCSV = 'Amount',@fiscalYearID = 0,@timeClassID = 22,@isDebugOnly = 0 +END +END +IF OBJECT_ID('tempdb..#EfficiencyFactorScope') IS NOT NULL DROP TABLE #EfficiencyFactorScope +GO + + +--------------------------------------------- + +-- fw.procStatisticSampledInsertDaily +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-07-11 gforeman B-12396 Handle stats that exist in multiple data sources (dupe handling) +** 2 2016-09-16 gforeman D-04861 Skip calculating actuals in certain cases +** 3 2016-10-12 mholov B-12970 Pull from Baseline Target time class +** 4 2016-12-13 mholov B-13783 Reversed actuals sampling order +** 5 2016-12-17 mholov B-13509 Pull Budgeted amounts from monthly table +** 6 2017-01-13 apukii D-05426 Removed filtering departments by mappings +** 7 2017-01-31 akozlov B-13926 Added department filter +** 8 2017-02-08 gforeman B-14308 Added year filter +** 9 2017-03-06 gforeman B-14693 Cancel sampling if daily disabled +** 10 2017-05-01 gforeman B-15551 Include non-PR driver departments in sampling +** 11 2017-05-02 gforeman B-15551 Remove primary statistics join so that all statistics are sampled +** 12 2017-06-14 ipetriv Added additional filter on values to omit 0 rows +** 13 2017-08-29 ipetriv B-16798 Add using of Budget Adjustment. +** 14 2018-02-22 ipetriv D-06786 add department calculation for TC = 2 if dept is not in PR , Dept is in Budget Allocation +** 15 2018-03-08 ipetriv B-18793 PR - Daily processing post action 2 week run +** 16 2018-03-08 ipetriv D-07329 removed part of code, that delete non PR department from staging table +** 17 2018-06-04 ipetriv TK-58558 added "distinct" selection of dates in case of recalcu;lation for 2 weeks +** 18 2018-10-18 OV D-07753 fix: daily and charged-based queries filtered by @dates (removed @FiscalYearID filter) +** 19 2018-10-23 OV D-07753 fix: PR fails to populate daily charge-based statistics on the first pay period of the fiscal year +** 20 2019-02-20 OV D-08116 fix: PR delete part ton filtered by PayPeriod +** 21 2019-03-12 OV TK-71197 Table variables replaced with temp tables +** 22 2019-04-23 OV B-20579 Allow clients to input daily budget - Statistics +** 23 2019-04-25 OV B-20579 sampled 0 data for Statistic (except actual) +** 24 2019-07-16 OV B-23482 Use Budget Adjustments for Daily and PayPeriod +** 25 2019-08-08 vfay D-08668 Add Joins on DateID in budget reallocation part +** 26 2020-01-28 IH TK-82833 Increase a deletion size from 10K to 100K +** 27 2020-03-10 HV D-09170 fw.procStatisticSampledInsertDaily is filling log file in tempdb caused by the use of temp variables +** 28 2020-03-18 HV TK-84583 PR Statistics Daily sampling: data is sampling incorrectly for first Pay Period days in some cases + D-09470 PR Statistics Daily sampling: budget adjustments are not applied for first Pay Period days if it belongs to 2 months + TK-84785 Statistics Sampling daily: Baseline Target values are calculated incorrectly for combinations with budget adjustments +** 29 2020-11-25 BS JAZZ-6398 PR Process is timing out due to long running proc fw.procStatisticSampledInsertDaily +** 30 2022-11-22 HV JAZZ-44508 Automated Daily PR processing doesn't calculate future target, when system center processing does +** 31 2023-02-03 KF JAZZ-48413 Charge Based Statistics Modals Performance Improvement- Bug Fixing +** 32 2023-02-21 KF JAZZ-50593 MBPR PHPUOS: Accounts with 0 charge based UOS are shown with link +** 33 2024-02-23 HV JAZZ-67657 [RowId] Convert fw.FactStatisticSampledDaily.Rowid to bigint +*************************************************************/ +CREATE proc [fw].[procStatisticSampledInsertDaily] + @departmentIDs nvarchar(max) = null, + @fiscalYearID int = 0, + @isCalcDaily bit = 0, + @isPrMetricConfigurationOn bit = 0 +with recompile +as + IF OBJECT_ID('tempdb..#DailyCalcPeriodsScope') IS NOT NULL DROP TABLE #DailyCalcPeriodsScope + + DECLARE @currentDateOverride nvarchar(max) = (SELECT Value FROM [pi].[SystemSetting] WHERE Name = 'Current Date Override') + DECLARE @currentDate date = CASE + WHEN @currentDateOverride = '' THEN CAST(GETDATE() AS DATE) + ELSE CAST (@currentDateOverride AS DATE) + END + DECLARE @yesterday_date date = DATEADD(DAY, - 1, @currentDate) + + create table #DailyCalcPeriodsScope (PayPeriodID int primary key,PayCycleID int,PeriodStartCalendarDate date,PeriodEndCalendarDate date) + + insert into #DailyCalcPeriodsScope (PayPeriodID,PayCycleID,PeriodStartCalendarDate,PeriodEndCalendarDate) + select PayPeriodID,PayCycleID,PeriodStartCalendarDate,PeriodEndCalendarDate + from fw.DimPayPeriod + where + (@isCalcDaily = 1 and @yesterday_date BETWEEN PeriodStartCalendarDate and PeriodEndCalendarDate) + or + (@isCalcDaily = 0 and (FiscalYearIDSecond = @fiscalYearID or @fiscalYearID = 0)) + + IF OBJECT_ID('tempdb..#departmentsBudgetAllocations') IS NOT NULL DROP TABLE #departmentsBudgetAllocations + create table #departmentsBudgetAllocations (val int primary key) + + IF OBJECT_ID('tempdb..#FDPSD') IS NOT NULL DROP TABLE #FDPSD + + CREATE TABLE #FDPSD (DepartmentID int primary key) + insert into #FDPSD + select distinct DriverDepartmentID as DepartmentID + from client.FactDepartmentPrimaryStatisticConfigurationDriverDepartmentCache + + insert into #departmentsBudgetAllocations (val) + select + SourceDepartmentID as DepartmentID + from mr.BudgetReallocationAdjustment a + inner join mr.BudgetReallocation r on r.BudgetReallocationGUID=a.BudgetReallocationGUID + inner join FW.DimDepartment d on d.DepartmentID = r.TargetDepartmentID and d.IsPR = 1 + where SourceDepartmentID <> 0 and r.Archived = 0 + union -- unique + select + TargetDepartmentID as DepartmentID + from mr.BudgetReallocationAdjustment a + inner join mr.BudgetReallocation r on r.BudgetReallocationGUID=a.BudgetReallocationGUID + inner join FW.DimDepartment d on d.DepartmentID = r.SourceDepartmentID and d.IsPR = 1 -- Filtering all departments that move data FROM selected + where TargetDepartmentID <> 0 and r.Archived = 0 + + --delete existing data + if (@fiscalYearID = 0 and @isCalcDaily = 0) begin + truncate table fw.FactStatisticSampledDaily + end else begin + while exists(select null from fw.FactStatisticSampledDaily fssd (nolock) + inner join #DailyCalcPeriodsScope ps on fssd.PayPeriodID = ps.PayPeriodID) begin + delete top (500000) fssd + from fw.FactStatisticSampledDaily fssd + inner join #DailyCalcPeriodsScope ps on fssd.PayPeriodID = ps.PayPeriodID + end + + DECLARE @nextRowID BIGINT + SELECT @nextRowID = ISNULL((SELECT MAX(RowID) FROM fw.FactStatisticSampledDaily), 1) + DBCC CHECKIDENT('fw.FactStatisticSampledDaily','RESEED', @nextRowID); + end + + --cancel if not using daily + if (not exists(select 1 from pi.SystemSetting where Name = 'PR Daily Enabled' and Value = '1')) begin return end + + --pull new data - daily statistics + IF OBJECT_ID('tempdb..#TEMPSTATISTIC') IS NOT NULL DROP TABLE #TEMPSTATISTIC + + create table #TEMPSTATISTIC (DepartmentID int, AccountID int, PayPeriodID int, DateID int, TimeClassID int, Units money) + insert into #TEMPSTATISTIC (DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units) + select + stat.DepartmentID, + stat.AccountID, + PP.PayPeriodID, + stat.DateID, + stat.TimeClassID, + SUM(STAT.Value) as Units + from + [int].[FactSharedImportDailyStatistics] stat + inner join [fw].[DimDate] DATE on stat.DateID=DATE.DateID + inner join [fw].[DimDepartment] D on D.Departmentid = STAT.DepartmentID + inner join [fw].[DimPayPeriod] PP on D.PayCycleID=PP.PayCycleID and DATE.CalendarDateTime between PP.PeriodStartCalendarDate and PP.PeriodEndCalendarDate + inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID and ((date.CalendarDateTime <= @yesterday_date and @isCalcDaily = 1) or @isCalcDaily = 0) + left join #FDPSD FDPSD on FDPSD.DepartmentID = STAT.DepartmentID + where + PP.PayPeriodID != 0 + and STAT.Isdeleted = 0 + and (D.IsPR = 1 or FDPSD.DepartmentID is not null) + and stat.DepartmentID != 0 + and stat.TimeClassID = 1 + + group by + stat.DepartmentID, + stat.AccountID, + PP.PayPeriodID, + stat.DateID, + stat.TimeClassID + + --pull new data - charge-based actuals where not already sampled + insert into #TEMPSTATISTIC (DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units) + select + STAT.DepartmentID, + STAT.AccountID, + pp.PayPeriodID, + STAT.DateID, + 1 as TimeClassID, + SUM(STAT.Value) AS Units + from + [fw].[FactChargeBasedStatistics] STAT + inner join [fw].[DimDate] DATE on STAT.DateID=DATE.DateID + inner join [fw].[DimDepartment] DEPT on STAT.DepartmentID=DEPT.DepartmentID + inner join [fw].[DimPayPeriod] PP on DEPT.PayCycleID=PP.PayCycleID and DATE.CalendarDateTime between PP.PeriodStartCalendarDate and PP.PeriodEndCalendarDate + inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID and ((date.CalendarDateTime <= @yesterday_date and @isCalcDaily = 1) or @isCalcDaily = 0) + left join #FDPSD FDPSD on FDPSD.DepartmentID = STAT.DepartmentID + left join #TEMPSTATISTIC ex ON ex.DepartmentID = STAT.DepartmentID and ex.AccountID = STAT.AccountID and ex.PayPeriodID = PP.PayPeriodID and ex.DateID = STAT.DateID and ex.TimeClassID = 1 + where + PP.PayPeriodID != 0 + and STAT.IsDeleted = 0 + and (DEPT.IsPR = 1 or FDPSD.DepartmentID is not null) + and STAT.DepartmentID != 0 + and ex.DepartmentID IS NULL + + group by + STAT.DepartmentID, + STAT.AccountID, + PP.PayPeriodID, + STAT.DateID; + + IF OBJECT_ID('tempdb..#StatisticSampledMonthlyStaging') IS NOT NULL DROP TABLE #StatisticSampledMonthlyStaging + CREATE TABLE #StatisticSampledMonthlyStaging (RowID bigint identity(1,1),AccountID int, DepartmentID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, Amount decimal(19,4), isDeleted bit, isSystemGenerated bit) + + IF OBJECT_ID('tempdb..#StatisticsDaily') IS NOT NULL DROP TABLE #StatisticsDaily + + select + FACT.DepartmentID, + FACT.AccountID, + DT.DateID, + FACT.TimeClassID, + PP.PayPeriodID, + SUM(FACT.Value) AS Units + into #StatisticsDaily + from + int.FactSharedImportDailyStatistics FACT + inner join [fw].[DimDepartment] D on D.Departmentid = FACT.DepartmentID + inner join [fw].[DimDate] DT on DT.DateID = FACT.dateID + inner join [fw].[DimPayPeriod] PP on pp.PayCycleID = d.PayCycleID and dt.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate + inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID + left join #FDPSD FDPSD ON FDPSD.DepartmentID = FACT.DepartmentID + left join #departmentsBudgetAllocations dba on dba.val = d.DepartmentID + where + DT.FiscalMonth != 0 + and DT.FiscalYear != 0 + and FACT.IsDeleted = 0 + and (D.IsPR = 1 or FDPSD.DepartmentID is not null or dba.val is not null) + and FACT.TimeClassID = 2 + and FACT.DepartmentID != 0 + + group by + FACT.DepartmentID, + FACT.AccountID, + DT.DateID, + FACT.TimeClassID, + PP.PayPeriodID +------------------------------------------------------------------------------------------------------------------------------------ +insert into #StatisticsDaily + select + FACT.DepartmentID, + FACT.AccountID, + DT.DateID, + FACT.TimeClassID, + PP.PayPeriodID, + SUM(FACT.Value/PCC.PeriodDays) AS Units + from + int.FactStatisticsByPayPeriod FACT + inner join [fw].[DimDepartment] D on D.Departmentid = FACT.DepartmentID + inner join fw.DimPayPeriod pp on pp.PayPeriodID = FACT.PayPeriodID + inner join [fw].[DimDate] DT on dt.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate + left join #StatisticsDaily spp on SPP.PayPeriodID = FACT.PayPeriodID and + SPP.AccountID = FACT.AccountID and + SPP.DepartmentID = FACT.DepartmentID and + SPP.TimeClassID = FACT.TimeClassID + inner join fw.DimPayCycle PCC on PCC.PayCycleID = PP.PayCycleID + inner join #DailyCalcPeriodsScope dcp on pp.PayPeriodID = dcp.PayPeriodID + left join #FDPSD FDPSD ON FDPSD.DepartmentID = FACT.DepartmentID + left join #departmentsBudgetAllocations dba on dba.val = d.DepartmentID + where + spp.DepartmentID IS NULL + and DT.FiscalMonth != 0 + and FACT.FiscalYearID != 0 + and FACT.IsDeleted = 0 + and (D.IsPR = 1 or FDPSD.DepartmentID is not null or dba.val is not null) + and FACT.TimeClassID = 2 + and FACT.DepartmentID != 0 + group by + FACT.DepartmentID, + FACT.AccountID, + DT.DateID, + FACT.TimeClassID, + PP.PayPeriodID +-------------------------------------------------------------------------------------------------------------------- + + + insert into #StatisticsDaily + select + STAT.DepartmentID, + STAT.AccountID, + DT.DateID, + STAT.TimeClassID, + DPC.PayPeriodID, + SUM(STAT.Value/ dbo.GetDaysInMonth(DT.CalendarDateTime)) AS Units + from + int.FactStatistic STAT + inner join [fw].[DimDepartment] D on D.Departmentid = STAT.Departmentid + inner join [fw].[DimDate] DT on DT.CalendarMonth = STAT.FiscalMonthID and DT.FiscalYear = STAT.FiscalYearID + inner join #DailyCalcPeriodsScope dpc on dpc.PayCycleID = d.PayCycleID and dt.CalendarDateTime between dpc.PeriodStartCalendarDate and dpc.PeriodEndCalendarDate + left join #StatisticsDaily spp on SPP.PayPeriodID = DPC.PayPeriodID and + SPP.AccountID = STAT.AccountID and + SPP.DepartmentID = STAT.DepartmentID and + SPP.TimeClassID = STAT.TimeClassID + left join #FDPSD FDPSD ON FDPSD.DepartmentID = STAT.DepartmentID + left join #departmentsBudgetAllocations dba on dba.val = d.DepartmentID + where + spp.DepartmentID is null + and + STAT.FiscalMonthID != 0 + and STAT.FiscalYearID != 0 + and STAT.isDeleted = 0 + and (D.IsPR = 1 or FDPSD.DepartmentID is not null or dba.val is not null) + and STAT.TimeClassID = 2 + and STAT.DepartmentID != 0 + + group by + STAT.DepartmentID, + STAT.AccountID, + DT.DateID, + STAT.TimeClassID, + DPC.PayPeriodID + + + +insert into #TEMPSTATISTIC (DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units) + select G.DepartmentID, AccountID, G.PayPeriodID, G.DateID, G.TimeClassID, G.Units + from #StatisticsDaily G + +--------------------------------------------------------------------------------------------------------------------- +declare @iteration int = 1 + + +DECLARE @BudgetReallocationGUID uniqueidentifier,@date datetime,@BudgetReallocationType varchar(50) + +PRINT '-------- Vendor Products Report --------'; + +DECLARE BRA_cursor CURSOR FOR +SELECT DISTINCT BudgetReallocationGUID,date,BudgetReallocationType +FROM fw.BudgetReallocationWithDefinedType BR + INNER JOIN [fw].[DimDate] DD ON DD.CalendarMonth = BR.FiscalMonthID AND DD.FiscalYear = BR.FiscalYearID + INNER JOIN #DailyCalcPeriodsScope DCPS ON DD.CalendarDateTime BETWEEN DCPS.PeriodStartCalendarDate AND DCPS.PeriodEndCalendarDate +WHERE BR.BudgetReallocationType IS NOT NULL +ORDER BY date + +OPEN BRA_cursor + +FETCH NEXT FROM BRA_cursor +INTO @BudgetReallocationGUID,@date,@BudgetReallocationType + +WHILE @@FETCH_STATUS = 0 +BEGIN + +IF @BudgetReallocationType = 'ReallocateSingle' + BEGIN -- Insert rows with "correcting" values + UPDATE STT + SET Units = STT.Units + Change/dbo.GetDaysInMonth(dd.CalendarDateTime) ---------------------- + FROM #TEMPSTATISTIC STT + INNER JOIN fw.dimDate dd on stt.DateID = dd.DateID + INNER JOIN [mr].[BudgetReallocation] b ON b.TargetDepartmentID = stt.DepartmentID and b.TargetAccountID = stt.AccountID and b.FiscalYearID = dd.FiscalYear + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and ba.FiscalMonthID = dd.CalendarMonth + WHERE ba.Change <> 0 + and b.BudgetReallocationGUID = @BudgetReallocationGUID + and ba.UnitTypeID = 145 + and STT.TimeClassID = 2 + and b.Archived = 0 + + UPDATE STT + SET Units = STT.Units - Change/dbo.GetDaysInMonth(dd.CalendarDateTime) --------------------------- + FROM #TEMPSTATISTIC STT + INNER JOIN fw.dimDate dd on stt.DateID = dd.DateID + INNER JOIN [mr].[BudgetReallocation] b ON b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and b.FiscalYearID = dd.FiscalYear + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and ba.FiscalMonthID = dd.CalendarMonth + WHERE ba.Change <> 0 + and b.BudgetReallocationGUID = @BudgetReallocationGUID + and ba.UnitTypeID = 145 + and STT.TimeClassID = 2 + and b.Archived = 0 + + INSERT INTO #TEMPSTATISTIC (DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units) + SELECT + b.SourceDepartmentID as DepartmentID, + b.SourceAccountID as AccountID, + pp.PayPeriodID as PayPeriodID, + dd.DateID as DateID, + 2 as TimeClassID, + SUM((Change/dbo.GetDaysInMonth(dd.CalendarDateTime)) * -1) as Units + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + INNER JOIN [fw].[DimDate] dd on dd.FiscalYear = b.FiscalYearID and dd.CalendarMonth = ba.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dep on b.SourceDepartmentID = dep.DepartmentID + INNER JOIN [fw].[DimPayPeriod] pp on pp.PayCycleID = dep.PayCycleID and dd.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate + INNER JOIN #DailyCalcPeriodsScope dcp on dcp.PayPeriodID = pp.PayPeriodID + LEFT JOIN #TEMPSTATISTIC stt + on b.SourceDepartmentID = stt.DepartmentID and + b.SourceAccountID = stt.AccountID and + stt.TimeClassID = 2 and + stt.DateID = dd.DateID + WHERE ba.Change <> 0 and + b.BudgetReallocationGUID = @BudgetReallocationGUID and + stt.DepartmentID is null and + ba.UnitTypeID = 145 and + b.Archived = 0 + GROUP BY b.SourceDepartmentID, + b.SourceAccountID, + pp.PayPeriodID, + dd.DateID +UNION All + SELECT + b.TargetDepartmentID as DepartmentID, + b.TargetAccountID as AccountID, + pp.PayPeriodID as PayPeriodID, + dd.DateID as DateID, + 2 as TimeClassID, + sum(Change/dbo.GetDaysInMonth(dd.CalendarDateTime)) as Units + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + INNER JOIN [fw].[DimDate] dd on dd.FiscalYear = b.FiscalYearID and dd.CalendarMonth = ba.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dep on b.TargetDepartmentID = dep.DepartmentID + INNER JOIN [fw].[DimPayPeriod] pp on pp.PayCycleID = dep.PayCycleID and dd.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate + INNER JOIN #DailyCalcPeriodsScope dcp on dcp.PayPeriodID = pp.PayPeriodID + LEFT JOIN #TEMPSTATISTIC stt + ON b.TargetDepartmentID = stt.DepartmentID and + b.TargetAccountID = stt.AccountID and + stt.TimeClassID = 2 and + stt.DateID = dd.DateID + WHERE ba.Change <> 0 and + b.BudgetReallocationGUID = @BudgetReallocationGUID and + stt.DepartmentID is null and + ba.UnitTypeID = 145 and + b.Archived = 0 + group by b.TargetDepartmentID, + b.TargetAccountID, + pp.PayPeriodID, + dd.DateID + ------------------ + + END + +IF @BudgetReallocationType = 'ReallocateMulti' + BEGIN + Update stt + set stt.Units = stt_src.Units + stt.Units + FROM #TEMPSTATISTIC STT + inner join fw.DimDate dd on dd.DateID = stt.DateID + INNER JOIN [mr].[BudgetReallocation] b on b.TargetDepartmentID = stt.DepartmentID and b.TargetAccountID = stt.AccountID and b.FiscalYearID = dd.FiscalYear + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and dd.CalendarMonth = ba.FiscalMonthID + INNER JOIN #TEMPSTATISTIC STT_SRC + ON STT_SRC.DepartmentID = b.SourceDepartmentID and + STT_SRC.AccountID = b.SourceAccountID and + stt.TimeClassID = stt_src.TimeClassID and + STT_SRC.DateID = stt.DateID + where + b.BudgetReallocationGUID = @BudgetReallocationGUID and + ba.UnitTypeID = 145 and + ba.Change <> 0 and + stt.TimeClassID = 2 and + b.Archived = 0 + +INSERT INTO #TEMPSTATISTIC (DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units) + SELECT --'Y', + b.TargetDepartmentID as DepartmentID, + b.TargetAccountID as AccountID, + pp.PayPeriodID as PayPeriodID, + dd.DateID as DateID, + 2 as TimeClassID, + SUM(STT_SRC.Units) as Units ----------------- + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + INNER JOIN [fw].[DimDate] dd on dd.FiscalYear = b.FiscalYearID and dd.CalendarMonth = ba.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dep on b.TargetDepartmentID = dep.DepartmentID + INNER JOIN [fw].[DimPayPeriod] pp on pp.PayCycleID = dep.PayCycleID and dd.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate + INNER JOIN #DailyCalcPeriodsScope dcp on dcp.PayPeriodID = pp.PayPeriodID + INNER JOIN #TEMPSTATISTIC STT_SRC + ON STT_SRC.DepartmentID = b.SourceDepartmentID and + STT_SRC.AccountID = b.SourceAccountID and + STT_SRC.TimeClassID = 2 and + STT_SRC.DateID = dd.DateID + LEFT JOIN #TEMPSTATISTIC STT + ON STT.DepartmentID = b.TargetDepartmentID and + STT.AccountID = b.TargetAccountID and + STT.TimeClassID = 2 and + STT.DateID = dd.DateID + where stt.DepartmentID is null and + ba.Change <> 0 and + ba.UnitTypeID = 145 and + b.BudgetReallocationGUID = @BudgetReallocationGUID and + b.Archived = 0 + GROUP BY + b.TargetDepartmentID, + b.TargetAccountID, + pp.PayPeriodID, + dd.DateID + + UPDATE STT_SRC + SET stt_src.Units = 0 + FROM #TEMPSTATISTIC STT_SRC + INNER JOIN fw.DimDate dd on dd.DateID = STT_SRC.DateID + INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = STT_SRC.DepartmentID and b.SourceAccountID = STT_SRC.AccountID and dd.FiscalYear = b.FiscalYearID + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and ba.FiscalMonthID = dd.CalendarMonth + LEFT JOIN #TEMPSTATISTIC STT + ON STT.DepartmentID = b.TargetDepartmentID and + STT.AccountID = b.TargetAccountID and + STT.TimeClassID = 2 and + STT.DateID = STT_SRC.DateID + where b.BudgetReallocationGUID = @BudgetReallocationGUID and + ba.UnitTypeID = 145 and + Change <> 0 and + b.Archived = 0 + END +-- ELSE + IF @BudgetReallocationType = 'AdjustMontly' + BEGIN + + UPDATE STT + SET stt.Units = stt.Units+Change/dbo.GetDaysInMonth(dd.CalendarDateTime) + FROM #TEMPSTATISTIC STT + inner join fw.DimDate dd on dd.DateID = stt.DateID + INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and dd.FiscalYear = b.FiscalYearID + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and ba.FiscalMonthID = dd.CalendarMonth + where + b.BudgetReallocationGUID = @BudgetReallocationGUID + and ba.UnitTypeID = 145 + and ba.Change <> 0 + and TimeClassID = 2 + and b.Archived = 0 + + INSERT INTO #TEMPSTATISTIC (DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units) + SELECT + b.SourceDepartmentID as DepartmentID, + b.SourceAccountID as AccountID, + pp.PayPeriodID as PayPeriodID, + dd.DateID as DateID, + 2 as TimeClassID, + SUM(Change/dbo.GetDaysInMonth(dd.CalendarDateTime)) as Units + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + INNER JOIN [fw].[DimDate] dd on dd.FiscalYear = b.FiscalYearID and dd.CalendarMonth = ba.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dep on b.SourceDepartmentID = dep.DepartmentID + INNER JOIN [fw].[DimPayPeriod] pp on pp.PayCycleID = dep.PayCycleID and dd.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate + INNER JOIN #DailyCalcPeriodsScope dcp on dcp.PayPeriodID = pp.PayPeriodID + LEFT JOIN #TEMPSTATISTIC stt + ON b.SourceDepartmentID = stt.DepartmentID and + b.SourceAccountID = stt.AccountID and + stt.TimeClassID = 2 and + stt.DateID = dd.DateID + where ba.Change <> 0 + and stt.DepartmentID is null + and ba.UnitTypeID = 145 + and b.BudgetReallocationGUID = @BudgetReallocationGUID + and b.Archived = 0 + GROUP BY + b.SourceDepartmentID, + b.SourceAccountID, + pp.PayPeriodID, + dd.DateID + END + + IF @BudgetReallocationType = 'ManualFile' + BEGIN + UPDATE STT + SET stt.Units = ba.NewSourceValue/dbo.GetDaysInMonth(dd.CalendarDateTime) + FROM #TEMPSTATISTIC STT + inner join fw.Dimdate dd on STT.DateID = dd.DateID + INNER JOIN [mr].[BudgetReallocation] b on b.SourceDepartmentID = stt.DepartmentID and b.SourceAccountID = stt.AccountID and b.FiscalYearID = dd.FiscalYear + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID and ba.FiscalMonthID = dd.CalendarMonth + where + b.BudgetReallocationGUID = @BudgetReallocationGUID + and ba.UnitTypeID = 145 + and b.Archived = 0 + and STT.TimeClassID = 2 + and ba.Change <> 0 + + INSERT INTO #TEMPSTATISTIC (DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units) + SELECT + b.SourceDepartmentID as DepartmentID, + b.SourceAccountID as AccountID, + pp.PayPeriodID as PayPeriodID, + dd.DateID as DateID, + 2 as TimeClassID, + SUM(NewSourceValue/dbo.GetDaysInMonth(dd.CalendarDateTime)) as Value --------------------------- + FROM [mr].[BudgetReallocation] b + INNER JOIN [mr].[BudgetReallocationAdjustment] ba on b.BudgetReallocationGUID=ba.BudgetReallocationGUID + INNER JOIN [fw].[DimDate] dd on dd.FiscalYear = b.FiscalYearID and dd.CalendarMonth = ba.FiscalMonthID + INNER JOIN [fw].[DimDepartment] dep on b.SourceDepartmentID = dep.DepartmentID + INNER JOIN [fw].[DimPayPeriod] pp on pp.PayCycleID = dep.PayCycleID and dd.CalendarDateTime between pp.PeriodStartCalendarDate and pp.PeriodEndCalendarDate + INNER JOIN #DailyCalcPeriodsScope dcp on dcp.PayPeriodID = pp.PayPeriodID + LEFT JOIN #TEMPSTATISTIC stt + ON b.SourceDepartmentID = stt.DepartmentID and + b.SourceAccountID = stt.AccountID and + stt.TimeClassID = 2 and + stt.DateID = dd.DateID + where ba.Change <> 0 and + stt.DepartmentID is null and + ba.UnitTypeID = 145 and + b.BudgetReallocationGUID = @BudgetReallocationGUID and + b.Archived = 0 + GROUP BY b.SourceDepartmentID, + b.SourceAccountID, + pp.PayPeriodID, + dd.DateID + END + + set @iteration = @iteration +1 + + FETCH NEXT FROM BRA_cursor + INTO @BudgetReallocationGUID,@date,@BudgetReallocationType +END +CLOSE BRA_cursor; +DEALLOCATE BRA_cursor; + + --calculate baseline target + declare @targetType int = (select Value from pi.SystemSetting where Name = 'Target Basis') + if (@targetType = 2) begin + --baseline target is based on budget, pull from monthly data + insert into #TEMPSTATISTIC (DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units) + select DepartmentID, AccountID, PayPeriodID, DateID, 20, Units + from #TEMPSTATISTIC + where TimeClassID = 2 + end else if(@targetType = 10) begin + --baseline target is based on rolling period average, pull from pay period data + with groupedBaselineTargetStats as( + select + STAT.DepartmentID, + STAT.AccountID, + STAT.PayPeriodID, + DT.DateID, + STAT.TimeClassID, + SUM(STAT.Units) AS Units + from + fw.FactStatisticSampledPayPeriod STAT + inner join [fw].[DimPayPeriod] PP on PP.PayPeriodID = STAT.PayPeriodID + inner join [fw].[DimDate] DT on DT.CalendarDateTime between PP.PeriodStartCalendarDate and PP.PeriodEndCalendarDate + inner join [fw].[DimDepartment] D on D.DepartmentID = STAT.DepartmentID + inner join #DailyCalcPeriodsScope DCPS on DCPS.PayPeriodID = PP.PayPeriodID + left join #FDPSD FDPSD ON FDPSD.DepartmentID = STAT.DepartmentID + left join #departmentsBudgetAllocations dba on dba.val = d.DepartmentID + where + STAT.PayPeriodID != 0 + and STAT.IsDeleted = 0 + and (D.IsPR = 1 or FDPSD.DepartmentID is not null or dba.val is not null) + and stat.TimeClassID = 20 + and stat.DepartmentID != 0 + group by + STAT.DepartmentID, + STAT.AccountID, + STAT.PayPeriodID, + DT.DateID, + STAT.TimeClassID + ) + insert into #TEMPSTATISTIC (DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units) + select DepartmentID, AccountID, G.PayPeriodID, DateID, TimeClassID, Units / PP.PeriodDays + from groupedBaselineTargetStats G + inner join fw.DimPayPeriod PP on PP.PayPeriodID = G.PayPeriodID + end + +IF OBJECT_ID('tempdb..#departmentsBudgetAllocations') IS NOT NULL DROP TABLE #departmentsBudgetAllocations + +-- Fill Charge Based Statistics Sampled Keys +IF @isPrMetricConfigurationOn = 1 +BEGIN + IF @FiscalYearID = 0 AND @yesterday_date IS NULL + BEGIN + TRUNCATE TABLE fw.FactChargeBasedStatisticsDailyKeys + END + ELSE + BEGIN + DELETE F FROM fw.FactChargeBasedStatisticsDailyKeys F + INNER JOIN #DailyCalcPeriodsScope PP ON PP.PayPeriodID = F.PayPeriodID + END + + INSERT INTO fw.FactChargeBasedStatisticsDailyKeys (DepartmentID, AccountID, PayPeriodID, DateID) + SELECT DISTINCT CB.DepartmentID, CB.AccountID, PP.PayPeriodID, CB.DateID + FROM fw.FactChargeBasedStatistics CB + INNER JOIN fw.DimDate DT ON DT.DateID = CB.DateID + INNER JOIN fw.DimDepartment DEPT ON DEPT.DepartmentID = CB.DepartmentID + INNER JOIN #DailyCalcPeriodsScope PP ON PP.PayCycleID = DEPT.PayCycleID AND DT.CalendarDateTime BETWEEN PP.PeriodStartCalendarDate and PP.PeriodEndCalendarDate + LEFT JOIN int.FactSharedImportDailyStatistics DS ON DS.DepartmentID = CB.DepartmentID AND DS.AccountID = CB.AccountID AND DS.DateID = CB.DateID AND DS.TimeClassID = 1 + LEFT JOIN #FDPSD FDPSD on FDPSD.DepartmentID = CB.DepartmentID + WHERE + CB.IsDeleted = 0 + AND CB.DepartmentID != 0 + AND PP.PayPeriodID != 0 + AND CB.Value != 0 + AND DS.RowID IS NULL + AND (DEPT.IsPR = 1 OR FDPSD.DepartmentID IS NOT NULL) +END + +IF OBJECT_ID('tempdb..#DailyCalcPeriodsScope') IS NOT NULL DROP TABLE #DailyCalcPeriodsScope + +IF OBJECT_ID('tempdb..#TEMPFINAL') IS NOT NULL DROP TABLE #TEMPFINAL +begin +SELECT DepartmentID, AccountID, TimeClassID, SUM(Units) as Units ,DateID, PayPeriodID into #TEMPFINAL +FROM ( + SELECT stt.DepartmentID,stt.AccountID,DateID,TimeClassID,Units, stt.PayPeriodID + from #TEMPSTATISTIC stt + UNION ALL + SELECT stat.DepartmentID,stat.AccountID, stat.DateID, stat.TimeClassID, 0 as Units, stat.PayPeriodID + from #StatisticsDaily stat + WHERE stat.Units != 0 +) SubSelect +GROUP BY DepartmentID,AccountID,TimeClassID, DateID, PayPeriodID +end + + --push to fact table + insert into fw.FactStatisticSampledDaily (DepartmentID, AccountID, PayPeriodID, DateID, TimeClassID, Units) + select + DepartmentID, + AccountID, + PayPeriodID, + DateID, + TimeClassID, + SUM(Units) + from + #TEMPFINAL temp + WHERE TimeClassID IS NOT NULL + group by + DepartmentID, + AccountID, + PayPeriodID, + DateID, + TimeClassID + +delete from fw.FactStatisticSampledDaily where TimeClassID = 1 and Units = 0 + +IF OBJECT_ID('tempdb..#TEMPSTATISTIC') IS NOT NULL DROP TABLE #TEMPSTATISTIC +IF OBJECT_ID('tempdb..#StatisticsDaily') IS NOT NULL DROP TABLE #StatisticsDaily +IF OBJECT_ID('tempdb..#TEMPFINAL') IS NOT NULL DROP TABLE #TEMPFINAL +GO + + +--------------------------------------------- + +-- fw.procStatisticSampledInsertMonthly +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2014-09-03 MS B-02863 Removing the parameter from the YTD proc call +** 2 2014-09-24 MS B-02191 Removing the IsStat=1 filter so that Units loaded on GL accounts shared with Dollars can be pulled in +** 3 2014-10-15 GF B-02951 Rollback CID 1 for backwards compatibility +** 4 2014-10-15 GF B-02951 Re-apply CID 1 only if latest data model for MR +** 5 2016-08-09 AK B-12405 Added merge with FactChargeBasedStatisticsByPostDate +** 6 2016-09-07 MH B-12791 Updated FactChargeBasedStatisticsByPostDate table name to FactChargeBasedStatisticsMonthly +** 7 2016-09-22 AK B-11845 Added procFactStatisticSampledBaselineTargetUpdate +** 8 2016-10-11 MH TK-33892 Fixed merge statement +** 9 2016-12-13 NL B-13759 Added fiscalYearID param and filtering +** 10 2017-02-20 GF D-05545 Move duplicate record handling from YTD into sampling + general cleanup +** 11 2017-03-06 GF B-14693 Added baseline target year filter +** 12 2017-05-24 IP B-15086 Sampling Performance Improvements. Using temp tables insead of fw.FactStatisticSampledMonthly. +** 13 2017-06-15 IP B-15086 Modify SP to use unique temp table +** 14 2017-07-19 IP TK-45395 Fixed conditions of merge statement (include isSystemGenerated column) +** 15 2017-27-26 IP B-16752 Added units Budget Adjustment +** 16 2017-08-02 IP D-06232 Fixed generated stats for MR (include charge-based statistics) +** 17 2017-08-29 ip B-16798 Add using of Budget Adjustment. +** 18 2017-08-29 ip D-06508 Preventing appearing duplicate rows in staging table +*************************************************************/ +CREATE proc [fw].[procStatisticSampledInsertMonthly] + @fiscalYearID smallint = 0 +as + IF OBJECT_ID('tempdb..#StatisticSampledMonthlyStaging') IS NOT NULL DROP TABLE ##StatisticSampledMonthlyStaging + IF OBJECT_ID('fw.StatisticSampledMonthlyStagingWithCalcs') IS NOT NULL DROP TABLE fw.StatisticSampledMonthlyStagingWithCalcs + --run custom scripts + exec client.procStatisticSampledInsertMonthlyPreprocess + + --push new data to fact table: statistics + + CREATE TABLE #StatisticSampledMonthlyStaging (RowID bigint identity(1,1),AccountID int, DepartmentID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, Amount decimal(19,4), isDeleted bit, isSystemGenerated bit) + insert into #StatisticSampledMonthlyStaging (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Amount) + exec fw.PrepareStatistics @FiscalYearID,0 + + --push new data to fact table: charge-based statistics + merge + #StatisticSampledMonthlyStaging as fact + using + (select DepartmentID, AccountID, FiscalYearID, FiscalMonthID, Value from fw.FactChargeBasedStatisticsMonthly where IsDeleted = 0 and Value != 0 and (FiscalYearID = @fiscalYearID OR @fiscalYearID = 0)) as source -- CID 9, added fiscalYearID filter + on + fact.DepartmentID = source.DepartmentID and fact.AccountID = source.AccountID and fact.FiscalYearID = source.FiscalYearID and fact.FiscalMonthID = source.FiscalMonthID and fact.TimeClassID = 1 and (fact.FiscalYearID = @fiscalYearID OR @fiscalYearID = 0) -- CID 9, added fiscalYearID filter + when not matched then + insert (FiscalYearID, FiscalMonthID, DepartmentID, AccountID, TimeClassID, Amount) values (source.FiscalYearID, source.FiscalMonthID, source.DepartmentID, source.AccountID, 1, source.Value); + + --run calculations + exec fw.procFactMonthlyMergeDuplicates '#StatisticSampledMonthlyStaging', 'AccountID', 'Amount', @fiscalYearID, 0, 0 + exec fw.procFactStatisticSampledBaselineTargetUpdate @fiscalYearID = @fiscalYearID + exec fw.procFactMonthlyYTDPriorYearUpdateStaging 'fw.FactStatisticSampledMonthly','#StatisticSampledMonthlyStaging', 'AccountID', 'Amount', @fiscalYearID, 0, 0 + + IF @fiscalYearID = 0 + BEGIN + truncate table fw.FactStatisticSampledMonthly + INSERT INTO fw.FactStatisticSampledMonthly With (TABLOCKX) ( + DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, + Amount, + AmountYTD, + AmountPriorYear, + AmountPriorYTD, + IsDeleted, + IsSystemGenerated + ) + SELECT + DepartmentID, + AccountID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + Amount=SUM(Amount), + AmountYTD=SUM(AmountYTD), + AmountPriorYear=SUM(AmountPriorYear), + AmountPriorYTD=SUM(AmountPriorYTD), + 0 as isDeleted, + isSystemGenerated=min(isnull(isSystemGenerated,0)) + FROM fw.StatisticSampledMonthlyStagingWithCalcs + GROUP BY + DepartmentID, + AccountID, + FiscalYearID, + FiscalMonthID, + TimeClassID + END +ELSE + BEGIN + print 'Starting creating index --- '+convert(varchar(20),GETDATE(),113) + CREATE CLUSTERED INDEX IDX_TempPayrollWithCalcs on fw.StatisticSampledMonthlyStagingWithCalcs (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID) + print 'Starting transaction --- '+convert(varchar(20),GETDATE(),113) + + ;With src as + ( + SELECT + DepartmentID, + AccountID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + Amount=SUM(Amount), + AmountYTD=SUM(AmountYTD), + AmountPriorYear=SUM(AmountPriorYear), + AmountPriorYTD=SUM(AmountPriorYTD), + isSystemGenerated=min(isSystemGenerated), + FTEs=SUM(FTEs), + FTEsYTD=SUM(FTEsYTD), + FTEsPriorYear=SUM(FTEsPriorYear), + FTEsPriorYTD=SUM(FTEsPriorYTD) + FROM fw.StatisticSampledMonthlyStagingWithCalcs + GROUP BY + DepartmentID, + AccountID, + FiscalYearID, + FiscalMonthID, + TimeClassID + ) + + MERGE fw.FactStatisticSampledMonthly With (TABLOCKX) AS target + USING src AS source + ON source.DepartmentID = target.DepartmentID + AND source.AccountID = target.AccountID + AND source.FiscalYearID = target.FiscalYearID + AND source.FiscalMonthID = target.FiscalMonthID + AND source.TimeClassID = target.TimeClassID + WHEN MATCHED AND + (target.Amount <> source.Amount + or target.AmountYTD <> source.AmountYTD + or target.AmountPriorYear <> source.AmountPriorYear + or target.AmountPriorYTD <> source.AmountPriorYTD + or target.IsSystemGenerated <> source.IsSystemGenerated) + THEN + UPDATE + SET target.Amount = source.Amount, + target.AmountYTD = source.AmountYTD, + target.AmountPriorYear = source.AmountPriorYear, + target.AmountPriorYTD = source.AmountPriorYTD, + target.IsSystemGenerated = source.IsSystemGenerated + + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, + Amount, + AmountYTD, + AmountPriorYear, + AmountPriorYTD, + IsDeleted, + IsSystemGenerated + ) + VALUES ( + source.DepartmentID, + source.AccountID, + source.FiscalYearID, + source.FiscalMonthID, + source.TimeClassID, + source.Amount, + source.AmountYTD, + source.AmountPriorYear, + source.AmountPriorYTD, + 0, + isnull(IsSystemGenerated,0) + ) + WHEN NOT MATCHED BY SOURCE + AND Target.FiscalYearID = @fiscalYearID + THEN + DELETE; + + END + IF OBJECT_ID('tempdb..##StatisticSampledMonthlyStaging') IS NOT NULL DROP TABLE ##StatisticSampledMonthlyStaging + IF OBJECT_ID('fw.StatisticSampledMonthlyStagingWithCalcs') IS NOT NULL DROP TABLE fw.StatisticSampledMonthlyStagingWithCalcs +GO + + +--------------------------------------------- + +-- fw.procStatisticSampledInsertPayPeriod +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2013-10-03 RA Changing source table to be [int].[FactStatisticsbyPayPeriod] +** and removing unnecessary lines +** 2 2014-08-20 JG Adding year filters for performance +** 3 2014-09-03 MS B-02863 Removing the parameter from the YTD proc call +** 4 2015-02-11 JG Adding Daily statistics +** 5 2016-01-22 MS D-03856 Calculate PayPeriodID in Daily section +** 6 2016-01-22 MS B-11082 Pull in Charge-based and Aggregated daily statistics and exclude GL statistics for these departments +** 7 2016-03-23 MS B-11274 Exclude list of departments in charge-based mapping table when AccountID=0 and Weight=0 +** 8 2016-04-28 AK B-11864 Added IsPR check +** 9 2016-07-11 GF B-12396 Handle stats that exist in multiple data sources (dupe handling) +** 10 2016-10-04 MH B-13126 Added procFactStatisticSampledPayPeriodBaselineTargetUpdate +** 11 2016-12-13 MH B-13783 Reversed actuals sampling order +** 12 2017-01-31 AK B-13926 Added department filter +** 13 2017-02-08 GF B-14308 Added year filter +** 14 2017-02-20 GF D-05545 Move duplicate record handling from YTD into sampling +** 15 2017-05-01 GF B-15551 Include non-PR driver departments in sampling +** 16 2017-05-02 GF B-15551 Remove primary statistics join so that all statistics are sampled +** 17 2017-05-29 ipetriv B-15994 Refactored sampling process and implemented using of staging tables +** 18 2017-06-15 IP B-15086 Modify SP to use unique temp table +** 19 2017-07-19 IP TK-45395 Fixed conditions of merge statement (include isSystemGenerated column) +** 20 2017-27-26 IP B-16752 Added units Budget Adjustment +** 21 2017-08-29 ip B-16798 Add using of Budget Adjustment. +** 22 2017-10-04 GF D-06489 Fix pay period select when running all years +** 23 2017-10-04 IP D-06489 Fix departments scope for cases when procedure run for one department (but adjustments could require more) +** 24 2018-02-22 IP D-06786 add department calculation for TC = 2 if dept is not in PR , Dept is in Budget Allocation +** 25 2018-05-17 IP D-07329 Returning fuctionality to include stats for departments using non-PR driver departments +** 26 2019-04-19 OV B-20579 Filtered by new column 'TimeClassID' from int.FactSharedImportDailyStatistics +** 27 2020-03-20 vfay D-08997 [fw].[PrepareStatisticsPayPeriod] is reporting incorrect adjustment amounts +** 28 2020-07-30 HV JAZZ-2302 YTD PR Calculations Incorrect when Processing Current Year Only +** 29 2020-11-26 KF JAZZ-7886 Stored procedure fw.procStatisticSampledInsertPayPeriod is timing out +** 30 2023-04-11 HV JAZZ-52032 Create and fill caching table for charge-based statistics pay period data +** 31 2023-12-04 ishah JAZZ-62485 Remove @departmentIDs param for procFactPayPeriodYTDPriorYearUpdate_Staging +*************************************************************/ +CREATE proc [fw].[procStatisticSampledInsertPayPeriod] + @fiscalYearID int = 0, + @isPrMetricConfigurationOn BIT = 0 +with recompile +as + IF OBJECT_ID('fw.StatisticSampledPayPeriodWithCalcs') IS NOT NULL DROP TABLE fw.StatisticSampledPayPeriodWithCalcs + IF OBJECT_ID('tempdb..#StatisticSampledPayPeriod') IS NOT NULL DROP TABLE #StatisticSampledPayPeriod + + create table #StatisticSampledPayPeriod (DepartmentID int, AccountID int, PayPeriodID int, TimeClassID int, Units decimal(18, 6), isDeleted bit default 0, isSystemGenerated bit default 0) + + create clustered columnstore index cci on #StatisticSampledPayPeriod + + insert into #StatisticSampledPayPeriod (DepartmentID, AccountID, PayPeriodID, TimeClassID, Units) + exec fw.PrepareStatisticsPayPeriod @FiscalYearID,null,0,@isPrMetricConfigurationOn -- Adding Adjustments! + + --run calculations + exec fw.procFactPayPeriodMergeDuplicates '#StatisticSampledPayPeriod', 'AccountID', 'Units', @fiscalYearID, 0, 0, null + exec fw.procFactStatisticSampledPayPeriodBaselineTargetUpdate @fiscalYearID = @fiscalYearID + exec fw.procFactPayPeriodYTDPriorYearUpdate_Staging 'fw.FactStatisticSampledPayPeriod','#StatisticSampledPayPeriod','AccountID', 'Units', @fiscalYearID, 0, 0 + + --Commented out due to D-07329 + /* + --!!!Removing all records where Department is not PR + delete fact + from fw.StatisticSampledPayPeriodWithCalcs fact + inner join fw.dimDepartment d on d.DepartmentID = fact.DepartmentID and d.isPR = 0 + */ + + IF @fiscalYearID = 0 + BEGIN + truncate table fw.FactStatisticSampledPayPeriod + INSERT INTO fw.FactStatisticSampledPayPeriod With (TABLOCKX) ( + DepartmentID, AccountID, PayPeriodID, TimeClassID, + Units, + UnitsYTD, + UnitsPriorYear, + UnitsPriorYTD, + IsDeleted, + IsSystemGenerated + ) + SELECT DepartmentID, AccountID, PayPeriodID, TimeClassID, + Units, + UnitsYTD, + UnitsPriorYear, + UnitsPriorYTD, + 0 as IsDeleted, + isnull(IsSystemGenerated,0) as IsSystemGenerated + FROM fw.StatisticSampledPayPeriodWithCalcs + END +ELSE + BEGIN + print 'Starting creating index --- '+convert(varchar(20),GETDATE(),113) + CREATE CLUSTERED INDEX IDX_TempPayrollWithCalcs on fw.StatisticSampledPayPeriodWithCalcs (DepartmentID, AccountID, PayPeriodID, TimeClassID) + print 'Starting transaction --- '+convert(varchar(20),GETDATE(),113) + ;WITH TGT AS (SELECT t.* FROM + fw.FactStatisticSampledPayPeriod t With (TABLOCKX) + inner join fw.DimPayPeriod pp on t.PayPeriodId = pp.PayPeriodID + and (@fiscalYearID = 0 or pp.FiscalYearIDSecond = @fiscalYearID) + and TimeclassID in (1,2,20) + ) + + MERGE + TGT AS target + USING fw.StatisticSampledPayPeriodWithCalcs AS source + ON source.DepartmentID = target.DepartmentID + AND source.AccountID = target.AccountID + AND source.PayPeriodID= target.PayPeriodID + AND source.TimeClassID = target.TimeClassID + WHEN MATCHED AND + (target.Units <> source.Units + or target.UnitsYTD <> source.UnitsYTD + or target.UnitsPriorYear <> source.UnitsPriorYear + or target.UnitsPriorYTD <> source.UnitsPriorYTD + or target.IsSystemGenerated <> source.IsSystemGenerated) + THEN + UPDATE + SET target.Units = source.Units, + target.UnitsYTD = source.UnitsYTD, + target.UnitsPriorYear = source.UnitsPriorYear, + target.UnitsPriorYTD = source.UnitsPriorYTD, + target.IsSystemGenerated = source.IsSystemGenerated + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + DepartmentID, AccountID, PayPeriodID, TimeClassID, + Units, + UnitsYTD, + UnitsPriorYear, + UnitsPriorYTD, + IsDeleted, + IsSystemGenerated + ) + VALUES ( + source.DepartmentID, + source.AccountID, + source.PayPeriodID, + source.TimeClassID, + source.Units, + source.UnitsYTD, + source.UnitsPriorYear, + source.UnitsPriorYTD, + 0, + isnull(IsSystemGenerated,0) + ) + WHEN NOT MATCHED BY SOURCE + THEN + DELETE; + END + + IF OBJECT_ID('fw.StatisticSampledPayPeriodWithCalcs') IS NOT NULL DROP TABLE fw.StatisticSampledPayPeriodWithCalcs + IF OBJECT_ID('tempdb..#StatisticSampledPayPeriod') IS NOT NULL DROP TABLE #StatisticSampledPayPeriod +GO + + +--------------------------------------------- + +-- fw.procStatisticSecondarySampledAdjustedTargetMonthlyInsert +CREATE PROCEDURE [fw].[procStatisticSecondarySampledAdjustedTargetMonthlyInsert] (@FiscalYearID int = 0) +AS +BEGIN +/* +Proposal + +If the client is not using flexing, this will be the target plus the efficiency factor +This should work regardless of the target basis (i.e. rolling avg or budget) +The factor will be applied after the inversion +If the factor type is percentage, the adjusted target will be the target*(1+factor) +i.e. if my target is 100 and my factor is 5%, the adjusted target will be 100*(1+0.05)=105 +i.e. if my target is 100 and my factor is -5%, the adjusted target will be 100*(1+-0.05)=95 +If the factor type is value, the adjusted value will be target + factor +i.e. if my target is 1000 and my factor is 200, the adjusted target will be will be 1000+200=1200 +i.e. if my target is 1000 and my factor is -200, the adjusted target will be 1000-200=800 +If there is more than one factor impacting a department and account or job code/pay code group combination, then the factors should layer on top of each other based on history order +If an efficiency factor does not exist for a particular account/job code, then the value in the new time class will be either flex or baseline target if flex is not used +This will happen after Flex is calculated +Include integration tests +*/ +/* +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-08-23 BC JAZZ-11498 Change Table Variable to Temporary Tables +************************************************************ +*/ +DECLARE @IsFlexingEnabled INT = ( + SELECT VALUE + FROM [mr].[SystemSetting] + WHERE NAME = 'Is Target Flexed' + ) +IF OBJECT_ID('tempdb..#EfficiencyFactorScope') IS NOT NULL DROP TABLE #EfficiencyFactorScope +CREATE TABLE #EfficiencyFactorScope ( + EfficiencyFactorGUID [uniqueidentifier] NOT NULL + ,[DepartmentID] [int] NOT NULL + ,[AccountID] [int] NOT NULL + ,[FiscalYearID] [smallint] NOT NULL + ,[FiscalMonthID] [tinyint] NOT NULL + ,Value NUMERIC(25, 6) NOT NULL + ,Type TINYINT + ,FactorType CHAR(1) + ,DateCreated DATETIME + ,UNIQUE CLUSTERED ( + FiscalYearID + ,FiscalMonthID + ,DepartmentID + ,AccountID + ,EfficiencyFactorGUID + ) + ); +IF EXISTS (SELECT TOP 1 * FROM [mr].[EfficiencyFactor]) BEGIN +WITH EfficiencyFactorScope +AS ( + SELECT * + ,rn = ROW_NUMBER() OVER ( + PARTITION BY FiscalYearID + ,FiscalMonthID + ,DepartmentID + ,AccountID + ,EfficiencyFactorGUID ORDER BY FiscalYearID + ,FiscalMonthID + ,DepartmentID + ,AccountID + ,EfficiencyFactorGUID + ) + FROM ( + SELECT DISTINCT ef.EfficiencyFactorGUID + ,ef.FiscalYearID + ,efgd.FiscalMonthID + ,efd.DepartmentID + ,isnull(efgd.AccountID, da.AccountID) AS AccountID + ,CASE + WHEN isnull(efgd.AccountID, - 999) = da.AccountID + THEN 0 + ELSE efgd.Value + END AS Value + ,ef.Type + ,ef.FactorType + ,ef.DateCreated + FROM mr.EfficiencyFactor ef + INNER JOIN mr.EfficiencyFactorDepartment efd ON ef.EfficiencyFactorGUID = efd.EfficiencyFactorGUID + INNER JOIN mr.EfficiencyFactorGLDetails efgd ON efgd.EfficiencyFactorGUID = ef.EfficiencyFactorGUID + LEFT JOIN fw.DimAccount da ON efgd.OBFinancialReportingID = da.OBUnitsFinancialReportingID and efgd.AccountID IS NULL + LEFT JOIN mr.EfficiencyFactorGLDetails efgd_exist ON efgd.EfficiencyFactorGUID = efgd_exist.EfficiencyFactorGUID and efgd_exist.AccountID = da.AccountID and efgd_exist.FiscalMonthID = efgd.FiscalMonthID + WHERE (@FiscalYearID = ef.FiscalYearID or @FiscalYearID = 0) and (efgd_exist.AccountID is null or da.AccountID is null) AND ef.Type = 1 AND isnull(efgd.AccountID, da.AccountID) IS NOT NULL + ) X + ) +INSERT INTO #EfficiencyFactorScope ( + EfficiencyFactorGUID + ,[DepartmentID] + ,[AccountID] + ,[FiscalYearID] + ,[FiscalMonthID] + ,Value + ,Type + ,FactorType + ,DateCreated + ) +SELECT EfficiencyFactorGUID + ,[DepartmentID] + ,[AccountID] + ,[FiscalYearID] + ,[FiscalMonthID] + ,Value + ,Type + ,FactorType + ,DateCreated +FROM EfficiencyFactorScope +WHERE RN = 1 + +DELETE FROM fw.FactStatisticSecondarySampledMonthly WHERE (@FiscalYearID = FiscalYearID or @FiscalYearID = 0) and TimeClassID = 22 + +INSERT INTO fw.FactStatisticSecondarySampledMonthly (DepartmentID, +AccountID, +FiscalYearID, +FiscalMonthID, +TimeClassID, +IsDeleted, +Amount) +SELECT DepartmentID + ,AccountID + ,FiscalYearID + ,FiscalMonthID + ,22 as TimeClassID + ,0 as IsDeleted + ,SUM(Amount) as Amount +FROM ( +SELECT isnull(fact.DepartmentID,ToApply.DepartmentID) as DepartmentID + ,isnull(fact.AccountID,toApply.AccountID) as AccountID + ,isnull(fact.FiscalYearID,toApply.FiscalYearID) as FiscalYearID + ,isnull(fact.FiscalMonthID,toApply.FiscalMonthID) as FiscalMonthID + ,Amount = CASE + WHEN FactorType = 'P' + THEN isnull(fact.Amount,0.0) * isnull(Value,0.0) / 100.00 + WHEN FactorType = 'V' + THEN isnull(Value,0.0) + ELSE 0.0 + END +FROM #EfficiencyFactorScope ToApply + INNER JOIN (SELECT distinct DepartmentID,AccountID from fw.FactStatisticSecondarySampledMonthly) GenCand on + GenCand.DepartmentID = ToApply.DepartmentID + AND GenCand.AccountID = ToApply.AccountID + FULL JOIN fw.FactStatisticSecondarySampledMonthly fact ON + fact.DepartmentID = ToApply.DepartmentID + AND fact.AccountID = ToApply.AccountID + AND fact.FiscalYearID = ToApply.FiscalYearID + AND fact.FiscalMonthID = ToApply.FiscalMonthID + WHERE ( + ( + isnull(fact.TimeClassID,0) = 4 + AND @IsFlexingEnabled = 1 + ) + OR ( + isnull(fact.TimeClassID,0) = 20 + AND @IsFlexingEnabled = 0 + ) + ) + and (fact.FiscalYearID = @FiscalYearID or @FiscalYearID = 0) +UNION ALL + +SELECT DepartmentID + ,AccountID + ,FiscalYearID + ,FiscalMonthID + ,Amount +FROM fw.FactStatisticSecondarySampledMonthly fact +WHERE ( + ( + isnull(fact.TimeClassID,0) = 4 + AND @IsFlexingEnabled = 1 + ) + OR ( + isnull(fact.TimeClassID,0) = 20 + AND @IsFlexingEnabled = 0 + ) + ) + and (fact.FiscalYearID = @FiscalYearID or @FiscalYearID = 0) +) X +GROUP BY DepartmentID + ,AccountID + ,FiscalYearID + ,FiscalMonthID + +exec [fw].[procFactMonthlyYTDPriorYearUpdate] @factTableName = 'fw.FactStatisticSecondarySampledMonthly',@keyNameCSV = 'AccountID',@measureNameCSV = 'Amount',@fiscalYearID = 0,@timeClassID = 22,@isDebugOnly = 0 +END +END +IF OBJECT_ID('tempdb..#EfficiencyFactorScope') IS NOT NULL DROP TABLE #EfficiencyFactorScope +GO + + +--------------------------------------------- + +-- fw.procStatisticSecondarySampledInsertMonthly +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2014-09-03 MS B-02863 Removing the parameter from the YTD proc call +** 2 2016-09-22 AK B-11845 Added procFactStatisticSecondarySampledBaselineTargetUpdate +** 3 2016-12-13 NL B-13759 Adding fiscalYearID param and filtering +** 4 2017-02-20 GF D-05545 Move duplicate record handling from YTD into sampling + general cleanup +** 5 2017-03-07 GF B-14693 Added baseline target year filter +** 6 2017-05-24 IP B-15086 Sampling Performance Improvements. Using temp tables insead of fw.FactPayrollSampledMonthlyDetailed. +** 7 2017-06-15 IP B-15086 Modify SP to use unique temp table +** 8 2017-07-19 IP TK-45395 Fixed conditions of merge statement (include isSystemGenerated column) +** 9 2017-27-26 ipetriv B-16752 Added units Budget Adjustment +** 10 2017-08-29 ip B-16798 Add using of Budget Adjustment. +*************************************************************/ +CREATE proc [fw].[procStatisticSecondarySampledInsertMonthly] + @fiscalYearID smallint = 0 +as + IF OBJECT_ID('tempdb..#StatisticSecondarySampledMonthlyStaging') IS NOT NULL DROP TABLE #StatisticSecondarySampledMonthlyStaging + IF OBJECT_ID('fw.StatisticSecondarySampledMonthlyStagingWithCalcs') IS NOT NULL DROP TABLE fw.StatisticSecondarySampledMonthlyStagingWithCalcs + + CREATE TABLE #StatisticSecondarySampledMonthlyStaging (RowID bigint identity(1,1),AccountID int, DepartmentID int, FiscalYearID int, FiscalMonthID int, TimeClassID int, Amount decimal(19,4), isDeleted bit, isSystemGenerated bit) + --push new data to fact table + insert into #StatisticSecondarySampledMonthlyStaging (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, Amount) + exec fw.PrepareStatistics @fiscalYearID,@StatisticType = 2 + + --run calculations + exec fw.procFactMonthlyMergeDuplicates '#StatisticSecondarySampledMonthlyStaging', 'AccountID', 'Amount', @fiscalYearID, 0, 0 + exec fw.procFactStatisticSecondarySampledBaselineTargetUpdate @fiscalYearID = @fiscalYearID + exec fw.procFactMonthlyYTDPriorYearUpdateStaging 'fw.FactStatisticSecondarySampledMonthly','#StatisticSecondarySampledMonthlyStaging','AccountID', 'Amount', @fiscalYearID, 0, 0 + + IF @fiscalYearID = 0 + BEGIN + truncate table fw.FactStatisticSecondarySampledMonthly + INSERT INTO fw.FactStatisticSecondarySampledMonthly With (TABLOCKX) ( + DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, + Amount, + AmountYTD, + AmountPriorYear, + AmountPriorYTD, + IsDeleted, + IsSystemGenerated + ) + SELECT DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, + Amount, + AmountYTD, + AmountPriorYear, + AmountPriorYTD, + 0 as IsDeleted, + isnull(IsSystemGenerated,0) as IsSystemGenerated + FROM fw.StatisticSecondarySampledMonthlyStagingWithCalcs + END +ELSE + BEGIN + print 'Starting creating index --- '+convert(varchar(20),GETDATE(),113) + CREATE CLUSTERED INDEX IDX_TempPayrollWithCalcs on fw.StatisticSecondarySampledMonthlyStagingWithCalcs (DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID) + print 'Starting transaction --- '+convert(varchar(20),GETDATE(),113) + MERGE fw.FactStatisticSecondarySampledMonthly With (TABLOCKX) AS target + USING fw.StatisticSecondarySampledMonthlyStagingWithCalcs AS source + ON source.DepartmentID = target.DepartmentID + AND source.AccountID = target.AccountID + AND source.FiscalYearID = target.FiscalYearID + AND source.FiscalMonthID = target.FiscalMonthID + AND source.TimeClassID = target.TimeClassID + WHEN MATCHED AND + (target.Amount <> source.Amount + or target.AmountYTD <> source.AmountYTD + or target.AmountPriorYear <> source.AmountPriorYear + or target.AmountPriorYTD <> source.AmountPriorYTD + or target.IsSystemGenerated <> source.IsSystemGenerated) + THEN + UPDATE + SET target.Amount = source.Amount, + target.AmountYTD = source.AmountYTD, + target.AmountPriorYear = source.AmountPriorYear, + target.AmountPriorYTD = source.AmountPriorYTD, + target.IsSystemGenerated = source.IsSystemGenerated + WHEN NOT MATCHED BY TARGET + THEN + INSERT ( + DepartmentID, AccountID, FiscalYearID, FiscalMonthID, TimeClassID, + Amount, + AmountYTD, + AmountPriorYear, + AmountPriorYTD, + IsDeleted, + IsSystemGenerated + ) + VALUES ( + source.DepartmentID, + source.AccountID, + source.FiscalYearID, + source.FiscalMonthID, + source.TimeClassID, + source.Amount, + source.AmountYTD, + source.AmountPriorYear, + source.AmountPriorYTD, + 0, + isnull(IsSystemGenerated,0) + ) + WHEN NOT MATCHED BY SOURCE + AND Target.FiscalYearID = @fiscalYearID + THEN + DELETE; + END + IF OBJECT_ID('tempdb..#StatisticSecondarySampledMonthlyStaging') IS NOT NULL DROP TABLE #StatisticSecondarySampledMonthlyStaging + IF OBJECT_ID('fw.StatisticSecondarySampledMonthlyStagingWithCalcs') IS NOT NULL DROP TABLE fw.StatisticSecondarySampledMonthlyStagingWithCalcs +GO + + +--------------------------------------------- + +-- fw.procStatisticSecondarySampledInsertPayPeriod +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-04-28 AK B-11864 Added IsPR check +** 2 2017-01-31 AK B-13926 Added department filter +** 3 2017-02-08 GF B-14308 Added year filter +** 4 2017-02-20 GF D-05545 Move duplicate record handling from YTD into sampling +** 5 2017-10-04 GF D-06489 Fix pay period select when running all years +*************************************************************/ +CREATE proc [fw].[procStatisticSecondarySampledInsertPayPeriod] + @isCalculatedYearMonth as bit = 1, + @departmentIDs nvarchar(max) = null, + @fiscalYearID int = 0 +with recompile +as + declare @departments table(val int primary key) + insert into @departments select val from ConvertCSValuesToTable(@departmentIDs, ',') + + declare @payperiods table(val smallint primary key) + insert into @payperiods select PayPeriodID from fw.DimPayPeriod where FiscalYearIDSecond = @fiscalYearID or @fiscalYearID = 0 + + if @isCalculatedYearMonth = 1 begin + --delete existing data + if (@departmentIDs is null and @fiscalYearID = 0) begin + truncate table fw.FactStatisticSecondarySampledbyPayPeriod + end else begin + while exists(select null from fw.FactStatisticSecondarySampledbyPayPeriod (nolock) where (@departmentIDs is null or DepartmentID in(select val from @departments)) and (@fiscalYearID = 0 or PayPeriodID in(select val from @payperiods))) begin + delete top (10000) from fw.FactStatisticSecondarySampledbyPayPeriod where (@departmentIDs is null or DepartmentID in(select val from @departments)) and (@fiscalYearID = 0 or PayPeriodID in(select val from @payperiods)) + end + end + + --sample rows with a valid pay period code, spreading across months + insert into [fw].[FactStatisticSecondarySampledbyPayPeriod] (DepartmentID, AccountID, PayPeriodID, TimeClassID, Units) + select + STAT.DepartmentID, + STAT.AccountID, + STAT.PayPeriodID, + STAT.TimeClassID, + SUM(STAT.Value) AS Units + from + [int].[FactStatisticsbyPayPeriod] STAT + inner join fw.DimAccount A on A.Accountid = STAT.Accountid + inner join fw.DimDepartment D on D.Departmentid = STAT.Departmentid + inner join [fw].[viewStatisticSecondaryConfiguration] V on V.AccountID=stat.AccountID and V.DepartmentID=stat.DepartmentID + where + STAT.Value != 0 and STAT.Isdeleted = 0 and STAT.PayPeriodID != 0 and A.IsStat=1 + and D.IsPR = 1 + and (@departmentIDs is null or STAT.DepartmentID in (select val from @departments)) + and (@fiscalYearID = 0 or STAT.PayPeriodID in(select val from @payperiods)) + group by + STAT.DepartmentID, + STAT.AccountID, + STAT.PayPeriodID, + STAT.TimeClassID + end else begin + print 'NOT SUPPORTED YET' + end + + --run calculations + exec fw.procFactPayPeriodMergeDuplicates 'fw.FactStatisticSecondarySampledbyPayPeriod', 'AccountID', 'Units', @fiscalYearID, 0, 0, @departmentIDs + exec fw.procFactPayPeriodYTDPriorYearUpdate 'fw.FactStatisticSecondarySampledbyPayPeriod', 'AccountID', 'Units', @fiscalYearID, 0, 0, @departmentIDs +GO + + +--------------------------------------------- + +-- fw.procTemplatePublishRequest_Insert +/************************************************************************************************************************ +** Author: cbecker +** Create Date: 2016-01-14 +** Description: Inserts template publish request and removes duplicates requests +** Last Modified: 2016-01-14 +** GM Release: 2016.1.3 +************************************************************************************************************************** +** Change History +************************************************************************************************************************** +** CID Date Author WI Description +** 01 2016-03-15 cbb n/a Delete duplicate publish requests +** 02 2017-04-24 gjf n/a Trigger profile rebuilds on publish +** 03 2019-03-18 gjf B-22412 Option to include template file +*************************************************************************************************************************/ +CREATE proc [fw].[procTemplatePublishRequest_Insert] + @frameworkID nvarchar(16)=0, + @includeTemplates bit=0, + @IsDebugOnly bit=0 +as +begin +-------------------------------------------------------------------------------------------------- +-- Logging +-------------------------------------------------------------------------------------------------- + declare @logdesc nvarchar(100) + select + @logdesc = case @IsDebugOnly + when 1 then 'Debug only - Insert template publish request for ' + else 'Insert template publish request for ' + end + +fw.Name + from [fw].[DimFramework] fw + where FrameworkID=@frameworkID + + declare @higuid uniqueidentifier + exec procLogScript @logdesc, @higuid output + + print N'select * from [dbo].[HistoryItem] where HISTORYITEMGUID=''' + +cast(@higuid as varchar(36)) + +N'''' + +-------------------------------------------------------------------------------------------------- +-- Set @sql string for inserting template publish request +-------------------------------------------------------------------------------------------------- + declare @RequestGUID nvarchar(36) = newid() + declare @IssuedAt nvarchar(36) = getdate() + declare @sql nvarchar(max) = +' +--Remove duplicate template publish requests +with duplicates +as +( +select + RequestGUID, + FrameworkID, + Num = row_number() over (PARTITION BY FrameworkID order by IssuedAt) +from [dbo].[TemplatePublishRequest] +) +delete +from duplicates +where Num>1 + +--Insert template publish request +if not exists +( +select 1 +from [dbo].[TemplatePublishRequest] +where FrameworkID=' ++ @frameworkID ++ ' +) +begin +insert into [dbo].[TemplatePublishRequest] + ([RequestGUID], [IssuedAt], [FrameworkID]) +values + (''' ++ @RequestGUID ++ ''', ''' ++ @IssuedAt ++ ''', ' ++ @frameworkID ++') +end +' + +-------------------------------------------------------------------------------------------------- +-- Ensure that OB publishes do a full rebuild on expansion profiles +-------------------------------------------------------------------------------------------------- +if (@frameworkID = 2) begin + set @sql = @sql + ' +--Ensure that OB publishes do a full rebuild on expansion profiles +update ob.SystemSetting set Value = ''1'' where Name = ''Template Publish Create Profiles''; +' +end + +-------------------------------------------------------------------------------------------------- +-- Optionally include template files +-------------------------------------------------------------------------------------------------- +if (@includeTemplates = 1) begin + set @sql = @sql + ' +--Include template files +insert into TemplatePublishRequestData (RequestGUID, ModelTemplateGUID, LastModified, Data) +select + ''' + @RequestGUID + ''', + mt.ModelTemplateGUID, + getdate(), + dp.Data +from + EMFModelTemplate mt + inner join DataPathFile_ModelTemplate dp on dp.FileName = cast(mt.ModelTemplateGUID as nvarchar(36)) + ''.xlsx.TAWithMappingFormulas'' +where + ' + @frameworkID + ' = (case when mt.Name like ''CAP %'' then 1 when mt.Name like ''OB %'' then 2 when mt.Name like ''SP %'' then 4 else 0 end) + and mt.ModelTemplateGUID not in(select ChildModelTemplateGUID from MEScoreExpansionProfile) +' +end + +-------------------------------------------------------------------------------------------------- +-- Print or execute @sql +-------------------------------------------------------------------------------------------------- + if @IsDebugOnly=1 + begin + print(@sql) + end + else + begin + exec(@sql) + end + +end +GO + + +--------------------------------------------- + +-- fw.procTransferStaffingToStaffingByPayPeriodCurrentYear +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-08-07 VO B-20238 Added condition where TimeClassID = 2 +** 2 2020-01-27 IH TK-82801 Increase a deletion size from 10K to 100K +** 3 2020-10-02 HV JAZZ-1487 MR "Transfer Budget Data" filtering on currently year, not transferring correctly to first/last pay periods +** 4 2022-12-12 BK JAZZ-47041 MR "Transfer Budget Data" increase temp table column size to prevent failing when int.FactStaffing EmployeeCode is longer than 50 characters +** 5 2024-06-14 SM JAZZ-71536 change JobCodeID from smallint to int +** 6 2024-09-13 SF JAZZ-72743 PayCode from varchar(50) to varchar(100) - Extend Field String Limit for Pay Code for Kaiser EPMS +*************************************************************/ +-- !!! If you modifying this proc, check [int].[procTransferStaffingToStaffingByPayPeriodFiscalYear] for updates !!! + +CREATE proc [fw].[procTransferStaffingToStaffingByPayPeriodCurrentYear] as + + /******** Variable Declaration **********/ + declare @TransactionID int = 1 + DECLARE @FiscalYearId INT = ( + SELECT setting + FROM dbsetting + WHERE NAME = 'Current_GL_YearID' + ) + + /******** Build Rows to Insert **********/ + + CREATE TABLE #TEMPSTAFFINGPAYPERIOD ( + [DepartmentID] [int] NOT NULL, + [DepartmentCode] [varchar](50) NOT NULL, + [JobCodeID] [int] NOT NULL, + [JobCode] [varchar](50) NOT NULL, + [PayCodeID] [smallint] NOT NULL, + [PayCode] [varchar](100) NOT NULL, + [FiscalYearID] [smallint] NOT NULL, + [FiscalYearCode] [varchar](20) NOT NULL, + [TimeClassID] [tinyint] NOT NULL, + [TimeClassCode] [varchar](20) NOT NULL, + [UnitTypeID] [smallint] NOT NULL, + [UnitType] [varchar](20) NOT NULL, + [PayPeriodID] [smallint] NOT NULL, + [PayPeriodCode] [varchar](20) NOT NULL, + [Value] [decimal](19, 4) NOT NULL, + [EmployeeID] [int] NOT NULL, + [Employeecode] [varchar](2000) NOT NULL, + [TransactionID] [int] NULL + ) + + + insert into #TEMPSTAFFINGPAYPERIOD ([DepartmentID], [DepartmentCode], [JobCodeID], [JobCode], [PayCodeID], [PayCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], [UnitTypeID], [UnitType], [PayPeriodID], [PayPeriodCode], [Value], [EmployeeID], [Employeecode], [TransactionID]) + select + fact.[DepartmentID], + fact.[DepartmentCode], + fact.[JobCodeID], + fact.[JobCode], + fact.[PayCodeID], + fact.[PayCode], + PP.[FiscalYearIDSecond], + PP.[FiscalYearIDSecond], + fact.[TimeClassID], + fact.[TimeClassCode], + fact.[UnitTypeID], + fact.[UnitType], + pp.[PayPeriodID], + pp.[PayPeriodCode], + SUM(cast(fact.value * PP.PeriodWeightStart as money)) AS Value, + fact.[EmployeeID], + fact.[Employeecode], + 1 as TransactionID + from + [int].[FactStaffing] fact + inner join [fw].[DimDepartment] D on fact.DepartmentID=D.DepartmentID + inner join [fw].[DimPayPeriod] PP on fact.FiscalMonthID = PP.FiscalMonthIDStart and fact.FiscalYearID = PP.FiscalYearIDStart and PP.PayCycleID=D.PayCycleID + where + fact.value != 0 + and fact.TimeclassID = 2 + and PP.PeriodDaysStart > 0 and fact.IsDeleted = 0 + --============= BEGIN CID 2 ================= + and fact.TransactionID<>@TransactionID + --============= END CID 2 =================== + and PP.FiscalYearIDSecond = @FiscalYearId + GROUP BY + fact.[DepartmentID], + fact.[DepartmentCode], + fact.[JobCodeID], + fact.[JobCode], + fact.[PayCodeID], + fact.[PayCode], + PP.[FiscalYearIDSecond], + fact.[TimeClassID], + fact.[TimeClassCode], + fact.[UnitTypeID], + fact.[UnitType], + fact.[EmployeeID], + fact.[Employeecode], + pp.[PayPeriodID], + pp.[PayPeriodCode] + + insert into #TEMPSTAFFINGPAYPERIOD ([DepartmentID], [DepartmentCode], [JobCodeID], [JobCode], [PayCodeID], [PayCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], [UnitTypeID], [UnitType], [PayPeriodID], [PayPeriodCode], [Value], [EmployeeID], [Employeecode], [TransactionID]) + select + fact.[DepartmentID], + fact.[DepartmentCode], + fact.[JobCodeID], + fact.[JobCode], + fact.[PayCodeID], + fact.[PayCode], + fact.[FiscalYearID], + fact.[FiscalYearCode], + fact.[TimeClassID], + fact.[TimeClassCode], + fact.[UnitTypeID], + fact.[UnitType], + pp.[PayPeriodID], + pp.[PayPeriodCode], + SUM(cast(fact.value * PP.PeriodWeightSecond as money)) AS Value, + fact.[EmployeeID], + fact.[Employeecode], + 1 as TransactionID + from + [int].[FactStaffing] fact + inner join [fw].[DimDepartment] D on fact.DepartmentID=D.DepartmentID + inner join [fw].[DimPayPeriod] PP on fact.FiscalMonthID = PP.FiscalMonthIDSecond and fact.FiscalYearID = PP.FiscalYearIDSecond and PP.PayCycleID=D.PayCycleID + where + fact.value != 0 + and fact.TimeclassID = 2 + and PP.PeriodDaysSecond > 0 and fact.IsDeleted = 0 + --============= BEGIN CID 2 ================= + and fact.TransactionID<>@TransactionID + --============= END CID 2 =================== + and PP.FiscalYearIDSecond = @FiscalYearId + GROUP BY + fact.[DepartmentID], + fact.[DepartmentCode], + fact.[JobCodeID], + fact.[JobCode], + fact.[PayCodeID], + fact.[PayCode], + fact.[FiscalYearID], + fact.[FiscalYearCode], + fact.[TimeClassID], + fact.[TimeClassCode], + fact.[UnitTypeID], + fact.[UnitType], + fact.[EmployeeID], + fact.[Employeecode], + pp.[PayPeriodID], + pp.[PayPeriodCode] + + /******** Delete previous transfered data **********/ +--============= BEGIN CID 3 ================= + while exists (select null from [int].[FactStaffingByPayPeriod] where TransactionID=@TransactionID and FiscalYearID = @FiscalYearId and TimeClassID = 2) + delete top (100000) from [int].[FactStaffingByPayPeriod] where TransactionID=@TransactionID and FiscalYearID = @FiscalYearId and TimeClassID = 2 +--============= END CID 3 =================== + + + /******** Insert into destination table *************/ + insert into [int].[FactStaffingByPayPeriod] ([DepartmentID], [DepartmentCode], [JobCodeID], [JobCode], [PayCodeID], [PayCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], [UnitTypeID], [UnitType], [PayPeriodID], [PayPeriodCode], [Value], [EmployeeID], [Employeecode], [TransactionID]) + select + [DepartmentID], + [DepartmentCode], + [JobCodeID], + [JobCode], + [PayCodeID], + [PayCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + [UnitTypeID], + [UnitType], + [PayPeriodID], + [PayPeriodCode], + SUM([Value]) AS VALUE, + [EmployeeID], + [Employeecode], + 1 as TransactionID + from + #TEMPSTAFFINGPAYPERIOD + group by + [DepartmentID], + [DepartmentCode], + [JobCodeID], + [JobCode], + [PayCodeID], + [PayCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + [UnitTypeID], + [UnitType], + [PayPeriodID], + [PayPeriodCode], + [EmployeeID], + [Employeecode] + +-- alter index all on [int].[FactStaffingbyPayPeriod] REBUILD WITH (FILLFACTOR=80) +-- update statistics [int].[FactStaffingbyPayPeriod] WITH FULLSCAN + +--cleanup +DROP TABLE #TEMPSTAFFINGPAYPERIOD + + + /******** Update record in IntTransaction **********/ + --TODO: Make the way it inserts to the IntTranaction much better; +GO + + +--------------------------------------------- + +-- fw.procTransferStatisticsMonthlyToPayPeriodCurrentYear +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-08-07 VO B-20238 added condition where TimeClassID = 2 +** 2 2020-10-02 HV JAZZ-1487 MR "Transfer Budget Data" filtering on currently year, not transferring correctly to first/last pay periods +*************************************************************/ +CREATE proc [fw].[procTransferStatisticsMonthlyToPayPeriodCurrentYear] as + /******** Variable Declaration **********/ + declare @TransactionID int = 1 + DECLARE @FiscalYearId INT = ( + SELECT setting + FROM dbsetting + WHERE NAME = 'Current_GL_YearID' + ) + + + /******** Build Rows to Insert **********/ + + CREATE TABLE #TEMPSTATISTICS ( + [AccountID] [int] NOT NULL, + [DepartmentID] [int] NOT NULL, + [FiscalYearID] [smallint] NOT NULL, + [PayPeriodID] [smallint] NOT NULL, + [TimeClassID] [tinyint] NOT NULL, + [Value] [decimal](19, 4) NOT NULL, + [AccountCode] [nvarchar](100) NOT NULL, + [DepartmentCode] [nvarchar](100) NOT NULL, + [FiscalYearCode] [nvarchar](100) NOT NULL, + [PayPeriodCode] [nvarchar](100) NOT NULL, + [TimeClassCode] [nvarchar](100) NOT NULL, + [TransactionID] [int] NOT NULL, + ) + + insert into #TEMPSTATISTICS (DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, PayPeriodID, PayPeriodCode, TimeClassID, TimeClassCode, Value, TransactionID) + select + fact.DepartmentID, + fact.DepartmentCode, + fact.AccountID, + fact.AccountCode, + PP.FiscalYearIDSecond, + PP.FiscalYearIDSecond, + PP.PayPeriodID, + PP.PayPeriodCode, + fact.TimeClassID, + fact.TimeClassCode, + SUM(cast(fact.value * PP.PeriodWeightStart as money)) AS Value, + 1 as TransactionID + from + [int].[FactStatistic] fact + inner join [fw].[DimDepartment] D on fact.DepartmentID=D.DepartmentID + inner join fw.DimPayPeriod PP on PP.FiscalMonthIDStart = fact.FiscalMonthID and PP.FiscalYearIDStart = fact.FiscalYearID and PP.PayCycleID=D.PayCycleID + where + fact.value != 0 + and fact.TimeClassID = 2 + and PP.PeriodDaysStart > 0 + --============= BEGIN CID 2 ================= + and fact.TransactionID<>@TransactionID + --============= END CID 2 =================== + and PP.FiscalYearIDSecond = @FiscalYearId + GROUP BY + fact.DepartmentID, + fact.DepartmentCode, + fact.AccountID, + fact.AccountCode, + PP.FiscalYearIDSecond, + PP.PayPeriodID, + PP.PayPeriodCode, + fact.TimeClassID, + fact.TimeClassCode + + insert into #TEMPSTATISTICS (DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, PayPeriodID, PayPeriodCode, TimeClassID, TimeClassCode, Value, TransactionID) + select + fact.DepartmentID, + fact.DepartmentCode, + fact.AccountID, + fact.AccountCode, + fact.FiscalYearID, + fact.FiscalYearCode, + PP.PayPeriodID, + PP.PayPeriodCode, + fact.TimeClassID, + fact.TimeClassCode, + SUM(cast(fact.value * PP.PeriodWeightSecond as money)) AS Value, + 1 as TransactionID + from + [int].[FactStatistic] fact + inner join [fw].[DimDepartment] D on fact.DepartmentID=D.DepartmentID + inner join fw.DimPayPeriod PP on PP.FiscalMonthIDSecond = fact.FiscalMonthID and PP.FiscalYearIDSecond = fact.FiscalYearID and PP.PayCycleID=D.PayCycleID + where + fact.value != 0 + and fact.TimeClassID = 2 + and PP.PeriodDaysSecond > 0 + --============= BEGIN CID 2 ================= + and fact.TransactionID<>@TransactionID + --============= END CID 2 =================== + and fact.FiscalYearID = @FiscalYearId + GROUP BY + fact.DepartmentID, + fact.DepartmentCode, + fact.AccountID, + fact.AccountCode, + fact.FiscalYearID, + fact.FiscalYearCode, + PP.PayPeriodID, + PP.PayPeriodCode, + fact.TimeClassID, + fact.TimeClassCode + + /******** Delete previous transfered data **********/ + delete from [int].[FactStatisticsbyPayPeriod] where TransactionID=@TransactionID and FiscalYearID = @FiscalYearId and TimeClassID = 2 + + + /******** Insert into destination table *************/ + insert into [int].[FactStatisticsbyPayPeriod] (DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, PayPeriodID, PayPeriodCode, TimeClassID, TimeClassCode, Value, TransactionID) + select + DepartmentID, + DepartmentCode, + AccountID, + AccountCode, + FiscalYearID, + FiscalYearCode, + PayPeriodID, + PayPeriodCode, + TimeClassID, + TimeClassCode, + sum(value), + TransactionID + from + #TEMPSTATISTICS + group by + DepartmentID, + DepartmentCode, + AccountID, + AccountCode, + FiscalYearID, + FiscalYearCode, + PayPeriodID, + PayPeriodCode, + TimeClassID, + TimeClassCode, + TransactionID + + alter index all on [int].[FactStatisticsbyPayPeriod] REBUILD WITH (FILLFACTOR=80) + update statistics [int].[FactStatisticsbyPayPeriod] WITH FULLSCAN + + + /******** Update record in IntTransaction **********/ + --TODO: Make the way it inserts to the IntTranaction much better +GO + + +--------------------------------------------- + +-- fw.procUpdateClientReportSectionAttributeFilter_PayPeriod +--Proc to set section attribute filter for Pay Periods-------------------------- +CREATE PROC [fw].[procUpdateClientReportSectionAttributeFilter_PayPeriod] + @TopCount int, + @MaxPayPeriodID int, + @ClientReportSectionAttributeGUID uniqueidentifier +AS + +BEGIN + CREATE TABLE #TempPeriods (PayPeriodID smallint, PayPeriodCode nvarchar(8)) + INSERT INTO #TempPeriods (PayPeriodID, PayPeriodCode) + SELECT TOP (@TopCount) + PayPeriodID, PayPeriodCode + FROM [fw].[DimPayPeriod] + WHERE PayPeriodID <= @MaxPayPeriodID + ORDER BY PayPeriodID DESC + + DECLARE @FilterMember nvarchar(100) + SET @FilterMember = ( + SELECT STUFF(( + select ','+ PayPeriodCode + from #TempPeriods + order by PayPeriodID asc + FOR XML PATH('') + ) + ,1,1,'') AS SortOrder + ) + UPDATE [dbo].[REClientReportSectionAttribute] + SET FilterMemberCSV=@FilterMember, SortOrderValue='-1' + WHERE ClientReportSectionAttributeGUID = @ClientReportSectionAttributeGUID + + DROP TABLE #TempPeriods +END +GO + + +--------------------------------------------- + +-- fw.procUpdateDataStudio20ViewYearStructure +CREATE procedure [fw].[procUpdateDataStudio20ViewYearStructure] +( + @FrameworkSchema Nvarchar(10) = 'sp', + @YearShift int = 1, + @isExecuting bit = 0 + --Schema= 'sp' or 'ob' (select SchemaName from fw.dimframework), YearShift #of Years to rollforward (positive integer) / back (negative integer), isExecuting 0 = print sql 1 = exec sql +) +AS + +/************************************************************ +** Author: blewis +** Create Date: 2015-01-23 +** Description: Rolls SP / OB DS2.0 Views forward and backward +** Last Modified: 2015-01-23 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +*************************************************************/ + +DECLARE TableEditorConfigGUID CURSOR FOR + select distinct st.TableEditorConfigGUID + from [dbo].[ScoreTableEditorConfig] st + inner join [dbo].[ScoreComposite] sc on st.DataSourceGUID=sc.CompositeGUID + inner join [dbo].[ScoreTableEditorColumn] ec on st.TableEditorConfigGUID=ec.TableEditorConfigGUID + inner join [fw].[DimFramework] fw on fw.FrameworkID=sc.FrameworkID + where fw.FrameworkSchemaName=@FrameworkSchema and ec.Type=2 + +Declare @TableEditorConfig Nvarchar(200) +open TableEditorConfigGUID + +FETCH NEXT FROM TableEditorConfigGUID + INTO @TableEditorConfig +WHILE (@@FETCH_STATUS = 0) +BEGIN + +Declare @DSViewName Nvarchar(400) = (select '--' + FriendlyName from [dbo].[ScoreTableEditorConfig] where TableEditorConfigGUID=@TableEditorConfig) +Print'' +Print'-------------------------------------------------------------------------------------------------------------------------------------------' +PRINT '--' + @DSViewName +PRINT '--'''+@TableEditorConfig+''' -TableEditorConfigGuid' +Print'-------------------------------------------------------------------------------------------------------------------------------------------' + + DECLARE @sqli varchar(max) + + DECLARE @TableEditorFirstColumnGuid Nvarchar(200) = + (select TableEditorColumnGUID + from [dbo].[ScoreTableEditorColumn] + where TableEditorConfigGUID=@TableEditorConfig and DisplayOrder= + (select Min(DisplayOrder) + from [dbo].[ScoreTableEditorColumn] + where Type=2 and TableEditorConfigGUID=@TableEditorConfig)) + + + DECLARE @XML Nvarchar(MAX) = (Select Cast(MetaData as nvarchar(max)) from [dbo].[ScoreTableEditorColumn] where TableEditorColumnGUID=@TableEditorFirstColumnGuid) + DECLARE @Start int = (select CharIndex('FISCAL_YEARFiscalYearID',@XML) + Len('FISCAL_YEARFiscalYearID')+1) + DECLARE @FiscalYear NvarChar(4) = Substring(@XML,@Start,4) + + IF IsNull( + (Select Case When CharIndex('.', @FiscalYear) > 0 + Then Case When Convert(int, ParseName(@FiscalYear, 1)) <> 0 + Then 0 + Else 1 + End + Else 1 + End + Where IsNumeric(@FiscalYear + 'e0') = 1), 0) = 1 Begin + + DECLARE TableEditorColumns CURSOR FOR + select TableEditorColumnGUID + from [dbo].[ScoreTableEditorColumn] e + where e.TableEditorConfigGUID=@TableEditorConfig and e.Type=2 + order by e.DisplayOrder + + Declare @TableEditorCol Nvarchar(200) + + open TableEditorColumns + + FETCH NEXT FROM TableEditorColumns + INTO @TableEditorCol + WHILE (@@FETCH_STATUS = 0) + BEGIN TRY + SET @sqli = + 'Update [dbo].[ScoreTableEditorColumn] set DisplayName=Replace(DisplayName,'+Cast(@FiscalYear as Nvarchar(4))+','+Cast((@FiscalYear + @YearShift) as Nvarchar(4))+'), MetaData = Replace(Cast(Metadata as Nvarchar(max)),' + Cast(@FiscalYear as Nvarchar(4)) + ','+ Cast((@FiscalYear + @YearShift) as Nvarchar(4))+') where TableEditorColumnGUID=''' + @TableEditorCol +'''' + + SET @FiscalYear= (Select @FiscalYear + 1) + + if @isExecuting = 1 begin + exec(@sqli) + end else begin + print @sqli + end + + FETCH NEXT FROM TableEditorColumns INTO @TableEditorCol + END TRY + Begin Catch + PRINT '--Error' + PRINT @sqli + PRINT '''' + @TableEditorCol +'''' +'--ErrorColumnGUID' + PRINT '' + End Catch + CLOSE TableEditorColumns + DEALLOCATE TableEditorColumns + + SET @sqli = + 'Update [dbo].[ScoreTableEditorFilter] + set HierarchyPath = Replace(HierarchyPath,Cast(RIGHT(HierarchyPath,4)as INT),Cast(RIGHT(HierarchyPath,4)as INT)+' + Cast(@YearShift as Nvarchar(4)) + '), + FriendlyName=Replace(FriendlyName,Cast(RIGHT(FriendlyName,4)as INT),Cast(RIGHT(FriendlyName,4)as INT)+' + Cast(@YearShift as Nvarchar(4)) + ') + where TableEditorConfigGUID='''+@TableEditorConfig+''' and KeyGUID=''84f7adb1-e680-4a23-b1ea-638120fbeadb''' + + if @isExecuting = 1 begin + exec(@sqli) + end else begin + print @sqli + end + + End + + +FETCH NEXT FROM TableEditorConfigGUID INTO @TableEditorConfig +END +CLOSE TableEditorConfigGUID +DEALLOCATE TableEditorConfigGUID +GO + + +--------------------------------------------- + +-- fw.procUpdateMinimumStaffingFlexPayrollSampledDaily +CREATE PROCEDURE [fw].[procUpdateMinimumStaffingFlexPayrollSampledDaily] + @fiscalYearID smallint = 0, + @onePayPeriodOnlyDate datetime = null +AS + +/* +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-08-05 BS JAZZ-41378 Daily Flexing - Payroll Minimum Staffing +************************************************************ +*/ +IF OBJECT_ID('tempdb..#inputPayPeriods') IS NOT NULL DROP TABLE #inputPayPeriods + +SELECT fp.PayPeriodID, COUNT(*) AS RecordsCount, 0 AS BatchID INTO #inputPayPeriods +FROM fw.FactPayrollSampledDaily fp +INNER JOIN pi.MinimumStaffingFlex ms ON fp.DepartmentID = ms.DepartmentID AND fp.JobCodeID = ms.JobCodeID AND fp.PayCodeGroupID = ms.PayCodeGroupID +INNER JOIN fw.DimPayPeriod pp ON fp.PayPeriodID = pp.PayPeriodID +WHERE fp.TimeClassID = 4 AND fp.Hours < ms.Hours AND +((@onePayPeriodOnlyDate IS NOT NULL AND @onePayPeriodOnlyDate BETWEEN pp.PeriodStartCalendarDate AND pp.PeriodEndCalendarDate) +OR +(@onePayPeriodOnlyDate IS NULL AND (pp.FiscalYearIDSecond = @fiscalYearID OR @fiscalYearID = 0))) +GROUP BY fp.PayPeriodID + +DECLARE @BatchSize INT = 30000000 + +-- Split data into batches +WHILE EXISTS (SELECT TOP 1 1 FROM #inputPayPeriods WHERE BatchID = 0) +BEGIN + ;WITH PayPeriodInfo AS + ( + SELECT DM.PayPeriodID, ROW_NUMBER() OVER (ORDER BY DM.PayPeriodID) AS RowNumber, SUM(RecordsCount) OVER (ORDER BY DM.PayPeriodID) AS Total, M.MaxBatchID+1 AS BatchID + FROM #inputPayPeriods IPP + INNER JOIN fw.DimPayPeriod DM ON DM.PayPeriodID = IPP.PayPeriodID + CROSS JOIN (SELECT MAX(BatchID) AS MaxBatchID FROM #inputPayPeriods) M + WHERE IPP.BatchID = 0 + ) + UPDATE IPP + SET IPP.BatchID = MI.BatchID + FROM #inputPayPeriods IPP + INNER JOIN PayPeriodInfo MI ON MI.PayPeriodID = IPP.PayPeriodID + WHERE MI.Total <= @BatchSize OR MI.RowNumber = 1 +END + +DECLARE @BatchID INT, @MaxBatchID INT +SELECT @MaxBatchID = MAX(BatchID) FROM #inputPayPeriods + +-- Loop thru batches and insert data +SET @BatchID = 1 +WHILE @BatchID <= @MaxBatchID +BEGIN + UPDATE fp + SET + Hours = h.Hours + FROM + fw.FactPayrollSampledDaily fp + INNER JOIN pi.MinimumStaffingFlex h ON fp.DepartmentID = h.DepartmentID AND fp.JobCodeID = h.JobCodeID AND fp.PayCodeGroupID = h.PayCodeGroupID + INNER JOIN #inputPayPeriods IPP ON IPP.PayPeriodID = fp.PayPeriodID + WHERE fp.TimeClassID = 4 AND IPP.BatchID = @BatchID AND fp.Hours < h.Hours +SET @BatchID = @BatchID + 1 +END +GO + + +--------------------------------------------- + +-- fw.procUpdateMinimumStaffingFlexPayrollSampledPayPeriod +CREATE PROCEDURE [fw].[procUpdateMinimumStaffingFlexPayrollSampledPayPeriod] + @fiscalYearID smallint = 0 +AS +/* +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2020-10-27 HV JAZZ-8174 PR | Minimum Staffing Flex +************************************************************ +*/ + ;WITH PayPeriodHours AS + ( + SELECT fp.DepartmentID, fp.JobCodeID, fp.PayCodeGroupID, fp.PayPeriodID, fp.TimeClassID, ms.Hours * pc.PeriodDays AS PayPeriodHours + FROM fw.FactPayrollSampledPayPeriod fp + INNER JOIN pi.MinimumStaffingFlex ms ON fp.DepartmentID = ms.DepartmentID AND fp.JobCodeID = ms.JobCodeID AND fp.PayCodeGroupID = ms.PayCodeGroupID + INNER JOIN fw.DimPayPeriod pp ON fp.PayPeriodID = pp.PayPeriodID + INNER JOIN fw.DimPayCycle pc ON pc.PayCycleID = pp.PayCycleID + WHERE fp.TimeClassID = 4 AND (pp.FiscalYearIDSecond = @fiscalYearID OR @fiscalYearID = 0) + ) + UPDATE fp + SET + Hours = h.PayPeriodHours + FROM + fw.FactPayrollSampledPayPeriod fp + INNER JOIN PayPeriodHours h ON fp.DepartmentID = h.DepartmentID AND fp.JobCodeID = h.JobCodeID AND fp.PayCodeGroupID = h.PayCodeGroupID AND fp.PayPeriodID = h.PayPeriodID AND fp.TimeClassID = h.TimeClassID + WHERE fp.Hours < h.PayPeriodHours +GO + + +--------------------------------------------- + +-- fw.procValidateClientSchema +CREATE proc fw.procValidateClientSchema as + +exec procValidateColumnsExists 'client', 'viewFactGLImport', 'DepartmentCode' +exec procValidateColumnsExists 'client', 'viewFactGLImport', 'AccountCode' +exec procValidateColumnsExists 'client', 'viewFactGLImport', 'FiscalYearID' +exec procValidateColumnsExists 'client', 'viewFactGLImport', 'FiscalMonthCode' +exec procValidateColumnsExists 'client', 'viewFactGLImport', 'TimeClassCode' +exec procValidateColumnsExists 'client', 'viewFactGLImport', 'Dollars' +exec procValidateColumnsExists 'client', 'viewFactGLImport', 'Units' + +/* +create view client.viewFactStatisticImportMonthly as + select + DepartmentCode, + AccountCode, + FiscalYearID, + FiscalMonthCode, + TimeClassCode, + Amount + from + client.FactStatisticImportMonthly +*/ +exec procValidateColumnsExists 'client', 'viewFactStatisticImportMonthly', 'DepartmentCode' +exec procValidateColumnsExists 'client', 'viewFactStatisticImportMonthly', 'AccountCode' +exec procValidateColumnsExists 'client', 'viewFactStatisticImportMonthly', 'FiscalYearID' +exec procValidateColumnsExists 'client', 'viewFactStatisticImportMonthly', 'FiscalMonthCode' +exec procValidateColumnsExists 'client', 'viewFactStatisticImportMonthly', 'TimeClassCode' +exec procValidateColumnsExists 'client', 'viewFactStatisticImportMonthly', 'Amount' + +/* +create view client.viewFactStatisticImportPayPeriod as +select + DepartmentCode, + AccountCode, + PayPeriodCode, + TimeClassCode, + ChargeCode, + PayCode, + FiscalYearID, + FiscalMonthCode, + Amount +from + client.FactStatisticImportPayPeriod +*/ +exec procValidateColumnsExists 'client', 'viewFactStatisticImportPayPeriod', 'DepartmentCode' +exec procValidateColumnsExists 'client', 'viewFactStatisticImportPayPeriod', 'AccountCode' +exec procValidateColumnsExists 'client', 'viewFactStatisticImportPayPeriod', 'PayPeriodCode' +exec procValidateColumnsExists 'client', 'viewFactStatisticImportPayPeriod', 'TimeClassCode' +exec procValidateColumnsExists 'client', 'viewFactStatisticImportPayPeriod', 'ChargeCode' +exec procValidateColumnsExists 'client', 'viewFactStatisticImportPayPeriod', 'PayCode' +exec procValidateColumnsExists 'client', 'viewFactStatisticImportPayPeriod', 'FiscalYearID' +exec procValidateColumnsExists 'client', 'viewFactStatisticImportPayPeriod', 'FiscalMonthCode' +exec procValidateColumnsExists 'client', 'viewFactStatisticImportPayPeriod', 'Amount' + +/* +create view client.viewFactPayrollImport as +select + DepartmentCode, + JobCode, + PayCode, + PayPeriodCode, + TimeClassCode, + Hours, + Dollars +from + client.FactPayrollImport +*/ +exec procValidateColumnsExists 'client', 'viewFactPayrollImport', 'DepartmentCode' +exec procValidateColumnsExists 'client', 'viewFactPayrollImport', 'JobCode' +exec procValidateColumnsExists 'client', 'viewFactPayrollImport', 'PayCode' +exec procValidateColumnsExists 'client', 'viewFactPayrollImport', 'PayPeriodCode' +exec procValidateColumnsExists 'client', 'viewFactPayrollImport', 'TimeClassCode' +exec procValidateColumnsExists 'client', 'viewFactPayrollImport', 'Hours' +exec procValidateColumnsExists 'client', 'viewFactPayrollImport', 'Dollars' +GO + + +--------------------------------------------- + +--------------------------------------------- +-- FUNCTIONS +--------------------------------------------- + +-- fw.GetCurrentDataPayPeriodID +CREATE FUNCTION [fw].[GetCurrentDataPayPeriodID]() +RETURNS smallint +AS +BEGIN + + +declare @currentPayPeriod int; +declare @currentPayPeriodStr nvarchar(4000); + +set @currentPayPeriodStr = ( + select setting from dbsetting where name = 'Current_Payroll_PayPeriodID' +) + +if ((@currentPayPeriodStr = '') or (@currentPayPeriodStr is null)) + set @currentPayPeriod = 0 +else + set @currentPayPeriod = ( select cast(@currentPayPeriodStr as int)) + +return @currentPayPeriod + + +END +GO + + +--------------------------------------------- + +-- fw.GetCurrentGLMonthID +CREATE FUNCTION [fw].[GetCurrentGLMonthID]() +RETURNS int +AS +BEGIN + +declare @currentMonth int; +declare @currentMonthStr nvarchar(4000); + +set @currentMonthStr = ( + select setting from dbsetting where name = 'Current_GL_MonthID' +) + +if ((@currentMonthStr = '') or (@currentMonthStr is null)) + set @currentMonth = 0 +else + set @currentMonth = ( select cast(@currentMonthStr as int)) + +return @currentMonth + +END +GO + + +--------------------------------------------- + +-- fw.GetCurrentGLYearID +CREATE FUNCTION [fw].[GetCurrentGLYearID]() +RETURNS int +AS +BEGIN + +declare @currentYear int; +declare @currentYearStr nvarchar(4000); + +set @currentYearStr = ( + select setting from dbsetting where name = 'Current_GL_YearID' +) + +if ((@currentYearStr = '') or (@currentYearStr is null)) + set @currentYear = 0 +else + set @currentYear = ( select cast(@currentYearStr as int)) + +return @currentYear + + +END +GO + + +--------------------------------------------- + +-- fw.GetCurrentPayPeriodID +CREATE FUNCTION [fw].[GetCurrentPayPeriodID]() +RETURNS smallint +AS +BEGIN + + +declare @Today datetime; +set @Today = GETDATE(); + +declare @CurrentPayPeriod smallint; +select @CurrentPayPeriod = PayPeriodID from fw.DimPayPeriod + where + @Today > PeriodStartCalendarDate + and + @Today < PeriodEndCalendarDate + order by PeriodStartCalendarDate DESC + +if (@CurrentPayPeriod is null) + set @CurrentPayPeriod = 0; + +return @CurrentPayPeriod + +END +GO + + +--------------------------------------------- + +-- fw.GetPayPeriodSamplingYear +/*************************************************************** +** CID Date Author WI Description +** 1 2018-09-11 kzhuk D-07649 PR Daily custom action calls procedures for wrong year +**************************************************************/ +CREATE FUNCTION [fw].[GetPayPeriodSamplingYear](@fiscalYearID int, @isCalcDaily bit) +RETURNS int +AS +BEGIN + +declare @previousDay DATE = DATEADD(DAY,-1,CAST(GETDATE() as DATE)) +declare @yearOfSampling int = CASE WHEN @isCalcDaily = 0 then @fiscalYearID else (SELECT MAX(FiscalYearIDSecond) +FROM fw.dimPayPeriod WHERE DATEADD(DAY,-1,CAST(GETDATE() as DATE)) BETWEEN PeriodStartCalendarDate and @previousDay) END +/* + @isCalcDaily = 0 & @fiscalYearID int = 0 == > @yearOfSampling = 0 + @isCalcDaily = 1 & @fiscalYearID int = 0 == > @yearOfSampling = 'CalendarYear' + @isCalcDaily = 1 & @fiscalYearID int = '1234' == > @yearOfSampling = 'CalendarYear' + @isCalcDaily = 0 & @fiscalYearID int = '1234' == > @yearOfSampling = '1234' + */ + +RETURN @yearOfSampling + +END +GO + + +--------------------------------------------- + +-- fw.GetUserRoleAssignmentCSV +CREATE FUNCTION [fw].[GetUserRoleAssignmentCSV] ( + @LootID nvarchar(200), + @RoleID int) + RETURNS NVARCHAR(MAX) +AS +BEGIN + +DECLARE @csv NVARCHAR(MAX) +SET @csv = '' +DECLARE @count int +SET @count = 0 +declare crsCursor CURSOR LOCAL FAST_FORWARD FOR + +select distinct + UP.NameFull +from + S3RoleAssignment RA (readuncommitted) + inner join S3IdentityLink IL (readuncommitted) + on RA.IdentityGUID = IL.GroupingGUID + inner join UserProfile UP (readuncommitted) + on IL.MemberGUID = UP.UserGUID +where + RA.RoleID = @RoleID + and RA.LootGroupID = @LootID + +order by NameFull +open crsCursor; + +DECLARE @NameFull nvarchar(100) + +FETCH NEXT FROM crsCursor into @NameFull +WHILE (@@FETCH_STATUS = 0) + BEGIN + + IF (@count = 0) BEGIN + select @csv = @csv + @NameFull + END ELSE BEGIN + select @csv = @csv + '; ' + @NameFull + END + set @count = @count +1 + FETCH NEXT FROM crsCursor into @NameFull + + END +close crsCursor; +DEALLOCATE crsCursor; + + RETURN @csv +END +GO + + +--------------------------------------------- + +-- fw.GetYTDDaysInMonth +CREATE FUNCTION [fw].[GetYTDDaysInMonth](@monthID int) +RETURNS int +AS +BEGIN + +declare @sortOrder int = (select sortOrder from fw.dimfiscalmonth where FiscalMonthID = @monthID) + +declare @ytdDays int = (select sum(DaysInMonth) from fw.dimfiscalmonth where sortorder <= @sortOrder) + +return @ytdDays + +END +GO + + +--------------------------------------------- + diff --git a/ef-migration/infrastructure/sql-server/schemas/fw_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/schemas/fw_schema_database_statements_small.sql new file mode 100644 index 0000000..89f581c --- /dev/null +++ b/ef-migration/infrastructure/sql-server/schemas/fw_schema_database_statements_small.sql @@ -0,0 +1,22 @@ +-- SCHEMA: fw + +--------------------------------------------- +-- TABLES +--------------------------------------------- + + +--------------------------------------------- +-- fw.ABBBudgetedCostPerRVU ------------------ +--------------------------------------------- +CREATE TABLE [fw].[ABBBudgetedCostPerRVU] ( + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeID] int NOT NULL, + [CostComponentID] int NOT NULL, + [CostingConfigGuid] uniqueidentifier NOT NULL, + [VariableDirectUnitCostPerRVU] decimal NULL, + [TotalVariableDirectCost] decimal NULL, + [TotalCost] decimal NULL +); +GO diff --git a/ef-migration/infrastructure/sql-server/schemas/int_schema_database_statements.sql b/ef-migration/infrastructure/sql-server/schemas/int_schema_database_statements.sql new file mode 100644 index 0000000..b654a6d --- /dev/null +++ b/ef-migration/infrastructure/sql-server/schemas/int_schema_database_statements.sql @@ -0,0 +1,14737 @@ +-- SCHEMA: int + +--------------------------------------------- +-- TABLES +--------------------------------------------- + + +--------------------------------------------- +-- int.AggregatePostDIHistory ------------------ +--------------------------------------------- +CREATE TABLE [int].[AggregatePostDIHistory] ( + [AggregatePostDIHistoryGuid] uniqueidentifier NOT NULL, + [CreatedAtUtc] datetime NOT NULL, + [LastRanUtc] datetime NOT NULL, + [AggregatePostDIStatus] int NOT NULL, + PRIMARY KEY ([AggregatePostDIHistoryGuid]) +); +GO +ALTER TABLE [int].[AggregatePostDIHistory] ADD CONSTRAINT [DF__Aggregate__Aggre__4EDF0E15] DEFAULT (newid()) FOR [AggregatePostDIHistoryGuid]; GO +ALTER TABLE [int].[AggregatePostDIHistory] ADD CONSTRAINT [DF__Aggregate__Creat__4FD3324E] DEFAULT (getutcdate()) FOR [CreatedAtUtc]; GO +ALTER TABLE [int].[AggregatePostDIHistory] ADD CONSTRAINT [DF__Aggregate__LastR__50C75687] DEFAULT ('1900-01-01 00:00:00.000') FOR [LastRanUtc]; GO +ALTER TABLE [int].[AggregatePostDIHistory] ADD CONSTRAINT [DF__Aggregate__Aggre__51BB7AC0] DEFAULT ((0)) FOR [AggregatePostDIStatus]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.AggregatePostDITransactionInfo ------------------ +--------------------------------------------- +CREATE TABLE [int].[AggregatePostDITransactionInfo] ( + [AggregatePostDITransactionInfoGuid] uniqueidentifier NOT NULL, + [AggregatePostDIHistoryGuid] uniqueidentifier NOT NULL, + [CreatedAtUtc] datetime NOT NULL, + [TransactionId] int NOT NULL, + PRIMARY KEY ([AggregatePostDITransactionInfoGuid]) +); +GO +ALTER TABLE [int].[AggregatePostDITransactionInfo] ADD CONSTRAINT [FK__Aggregate__Aggre__558C0BA4] FOREIGN KEY ([AggregatePostDIHistoryGuid]) REFERENCES [int].[AggregatePostDIHistory] ([AggregatePostDIHistoryGuid]); GO +ALTER TABLE [int].[AggregatePostDITransactionInfo] ADD CONSTRAINT [DF__Aggregate__Aggre__5497E76B] DEFAULT (newid()) FOR [AggregatePostDITransactionInfoGuid]; GO +ALTER TABLE [int].[AggregatePostDITransactionInfo] ADD CONSTRAINT [DF__Aggregate__Creat__56802FDD] DEFAULT (getutcdate()) FOR [CreatedAtUtc]; GO +ALTER TABLE [int].[AggregatePostDITransactionInfo] ADD CONSTRAINT [DF__Aggregate__Trans__57745416] DEFAULT ((0)) FOR [TransactionId]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.ClaimsPostDIHistory ------------------ +--------------------------------------------- +CREATE TABLE [int].[ClaimsPostDIHistory] ( + [ClaimsPostDIHistoryGuid] uniqueidentifier NOT NULL, + [CreatedAtUtc] datetime NOT NULL, + [LastRanUtc] datetime NOT NULL, + [ClaimsPostDIStatus] int NOT NULL, + PRIMARY KEY ([ClaimsPostDIHistoryGuid]) +); +GO +ALTER TABLE [int].[ClaimsPostDIHistory] ADD CONSTRAINT [DF__ClaimsPos__Claim__34801D94] DEFAULT (newid()) FOR [ClaimsPostDIHistoryGuid]; GO +ALTER TABLE [int].[ClaimsPostDIHistory] ADD CONSTRAINT [DF__ClaimsPos__Creat__357441CD] DEFAULT (getutcdate()) FOR [CreatedAtUtc]; GO +ALTER TABLE [int].[ClaimsPostDIHistory] ADD CONSTRAINT [DF__ClaimsPos__LastR__36686606] DEFAULT ('1900-01-01 00:00:00.000') FOR [LastRanUtc]; GO +ALTER TABLE [int].[ClaimsPostDIHistory] ADD CONSTRAINT [DF__ClaimsPos__Claim__375C8A3F] DEFAULT ((0)) FOR [ClaimsPostDIStatus]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.ClaimsPostDITransactionInfo ------------------ +--------------------------------------------- +CREATE TABLE [int].[ClaimsPostDITransactionInfo] ( + [ClaimsPostDITransactionInfoGuid] uniqueidentifier NOT NULL, + [ClaimsPostDIHistoryGuid] uniqueidentifier NOT NULL, + [CreatedAtUtc] datetime NOT NULL, + [TransactionId] int NOT NULL, + PRIMARY KEY ([ClaimsPostDITransactionInfoGuid]) +); +GO +ALTER TABLE [int].[ClaimsPostDITransactionInfo] ADD CONSTRAINT [FK__ClaimsPos__Claim__3B2D1B23] FOREIGN KEY ([ClaimsPostDIHistoryGuid]) REFERENCES [int].[ClaimsPostDIHistory] ([ClaimsPostDIHistoryGuid]); GO +ALTER TABLE [int].[ClaimsPostDITransactionInfo] ADD CONSTRAINT [DF__ClaimsPos__Claim__3A38F6EA] DEFAULT (newid()) FOR [ClaimsPostDITransactionInfoGuid]; GO +ALTER TABLE [int].[ClaimsPostDITransactionInfo] ADD CONSTRAINT [DF__ClaimsPos__Creat__3C213F5C] DEFAULT (getutcdate()) FOR [CreatedAtUtc]; GO +ALTER TABLE [int].[ClaimsPostDITransactionInfo] ADD CONSTRAINT [DF__ClaimsPos__Trans__3D156395] DEFAULT ((0)) FOR [TransactionId]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactADTDataImport ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactADTDataImport] ( + [RowID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [EncounterID] bigint NOT NULL, + [EntityCode] nvarchar(100) NOT NULL, + [DepartmentCode] nvarchar(100) NOT NULL, + [UnitCode] nvarchar(100) NOT NULL, + [AccommodationCode] nvarchar(100) NOT NULL, + [AccommodationDSC] nvarchar(100) NOT NULL, + [EncounterCode] nvarchar(100) NOT NULL, + [AdmitDateTime] datetime NOT NULL, + [DischargeDateTime] datetime NOT NULL, + [TransferDateTime] datetime NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [EventID] varchar(50) NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [int].[FactADTDataImport] ADD CONSTRAINT [FK__FactADTDa__Depar__12FD33F6] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [int].[FactADTDataImport] ADD CONSTRAINT [FK__FactADTDa__Encou__14E57C68] FOREIGN KEY ([EncounterID]) REFERENCES [dss].[DimPatientEncounter] ([EncounterID]); GO +ALTER TABLE [int].[FactADTDataImport] ADD CONSTRAINT [FK__FactADTDa__Entit__1114EB84] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [int].[FactADTDataImport] ADD CONSTRAINT [DF__FactADTDa__Entit__1020C74B] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [int].[FactADTDataImport] ADD CONSTRAINT [DF__FactADTDa__Depar__12090FBD] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [int].[FactADTDataImport] ADD CONSTRAINT [DF__FactADTDa__Encou__13F1582F] DEFAULT ((0)) FOR [EncounterID]; GO +ALTER TABLE [int].[FactADTDataImport] ADD CONSTRAINT [DF__FactADTDa__Entit__15D9A0A1] DEFAULT ('') FOR [EntityCode]; GO +ALTER TABLE [int].[FactADTDataImport] ADD CONSTRAINT [DF__FactADTDa__Depar__16CDC4DA] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactADTDataImport] ADD CONSTRAINT [DF__FactADTDa__UnitC__17C1E913] DEFAULT ('') FOR [UnitCode]; GO +ALTER TABLE [int].[FactADTDataImport] ADD CONSTRAINT [DF__FactADTDa__Accom__18B60D4C] DEFAULT ('') FOR [AccommodationCode]; GO +ALTER TABLE [int].[FactADTDataImport] ADD CONSTRAINT [DF__FactADTDa__Accom__19AA3185] DEFAULT ('') FOR [AccommodationDSC]; GO +ALTER TABLE [int].[FactADTDataImport] ADD CONSTRAINT [DF__FactADTDa__Encou__1A9E55BE] DEFAULT ('') FOR [EncounterCode]; GO +ALTER TABLE [int].[FactADTDataImport] ADD CONSTRAINT [DF__FactADTDa__Admit__1B9279F7] DEFAULT (getdate()) FOR [AdmitDateTime]; GO +ALTER TABLE [int].[FactADTDataImport] ADD CONSTRAINT [DF__FactADTDa__Disch__1C869E30] DEFAULT (getdate()) FOR [DischargeDateTime]; GO +ALTER TABLE [int].[FactADTDataImport] ADD CONSTRAINT [DF__FactADTDa__Trans__1D7AC269] DEFAULT (getdate()) FOR [TransferDateTime]; GO +ALTER TABLE [int].[FactADTDataImport] ADD CONSTRAINT [DF__FactADTDa__IsDel__1E6EE6A2] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactADTDataImport] ADD CONSTRAINT [DF__FactADTDa__Trans__20572F14] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactADTDataImport] ADD CONSTRAINT [DF__FactADTDa__Histo__1F630ADB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactADTDataImport] ADD CONSTRAINT [DF__FactADTDa__Event__58E8CE56] DEFAULT ('') FOR [EventID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactAPDetail ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactAPDetail] ( + [RowID] int NOT NULL, + [AccountID] int NOT NULL, + [ComponentID] smallint NOT NULL, + [ProjectID] int NOT NULL, + [RequisitionID] int NOT NULL, + [VendorID] int NOT NULL, + [DepartmentID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [ClientCapitalID] nvarchar(100) NOT NULL, + [ClientComponentID] nvarchar(100) NOT NULL, + [InvoiceNumber] nvarchar(100) NOT NULL, + [PONumber] nvarchar(100) NULL, + [LineDescription] nvarchar(100) NOT NULL, + [ClientDate] datetime NOT NULL, + [Quantity] decimal NOT NULL, + [CostPerItem] decimal NOT NULL, + [Total] decimal NULL, + [LineNumber] nvarchar(100) NOT NULL, + [VendorCode] nvarchar(100) NOT NULL, + [VendorName] nvarchar(100) NOT NULL, + [AccountCode] nvarchar(100) NOT NULL, + [ItemNumber] nvarchar(100) NOT NULL, + [FiscalMonthCode] nvarchar(100) NOT NULL, + [FiscalYearCode] nvarchar(100) NOT NULL, + [DepartmentCode] nvarchar(100) NOT NULL, + [CustomText1] nvarchar(100) NOT NULL, + [CustomText2] nvarchar(100) NOT NULL, + [CustomText3] nvarchar(100) NOT NULL, + [CustomText4] nvarchar(100) NOT NULL, + [CustomText5] nvarchar(100) NOT NULL, + [CustomDate1] datetime NOT NULL, + [CustomDate2] datetime NOT NULL, + [CustomNumeric1] decimal NOT NULL, + [CustomNumeric2] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [IsSampled] bit NOT NULL, + [SampleDate] datetime NOT NULL, + [TransID] nvarchar(100) NOT NULL, + [CustomLongText1] nvarchar(2000) NOT NULL, + [CustomLongText2] nvarchar(2000) NOT NULL, + [InvoiceImage] nvarchar(2000) NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [CNU_BASE] ON [int].[FactAPDetail] ([FiscalMonthID], [IsDeleted], [FiscalYearID], [DepartmentID], [AccountID], [ComponentID], [ProjectID], [RequisitionID], [VendorID]); +CREATE NONCLUSTERED INDEX [NCNU_SampleView] ON [int].[FactAPDetail] ([FiscalMonthID], [IsDeleted], [FiscalYearID], [DepartmentID], [AccountID], [ComponentID], [ProjectID], [RequisitionID], [VendorID]); +GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [FK__FactAPDet__Accou__0F3DB8F8] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [FK__FactAPDet__Compo__1126016A] FOREIGN KEY ([ComponentID]) REFERENCES [cap].[DimComponent] ([ComponentID]); GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [FK__FactAPDet__Depar__18C72332] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [FK__FactAPDet__Fisca__1AAF6BA4] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [FK__FactAPDet__Fisca__1C97B416] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [FK__FactAPDet__Proje__130E49DC] FOREIGN KEY ([ProjectID]) REFERENCES [cap].[DimProject] ([ProjectID]); GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [FK__FactAPDet__Requi__14F6924E] FOREIGN KEY ([RequisitionID]) REFERENCES [cap].[DimRequisition] ([RequisitionID]); GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [FK__FactAPDet__Vendo__16DEDAC0] FOREIGN KEY ([VendorID]) REFERENCES [cap].[DimVendor] ([VendorID]); GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Accou__0E4994BF] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Compo__1031DD31] DEFAULT ((0)) FOR [ComponentID]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Proje__121A25A3] DEFAULT ((0)) FOR [ProjectID]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Requi__14026E15] DEFAULT ((0)) FOR [RequisitionID]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Vendo__15EAB687] DEFAULT ((0)) FOR [VendorID]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Fisca__19BB476B] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Fisca__1BA38FDD] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Clien__1D8BD84F] DEFAULT ('') FOR [ClientCapitalID]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Clien__1E7FFC88] DEFAULT ('') FOR [ClientComponentID]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Invoi__1F7420C1] DEFAULT ('') FOR [InvoiceNumber]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__LineD__215C6933] DEFAULT ('') FOR [LineDescription]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Clien__22508D6C] DEFAULT (getdate()) FOR [ClientDate]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Quant__2344B1A5] DEFAULT ((0)) FOR [Quantity]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__CostP__2438D5DE] DEFAULT ((0)) FOR [CostPerItem]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__LineN__252CFA17] DEFAULT ('') FOR [LineNumber]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Vendo__26211E50] DEFAULT ('') FOR [VendorCode]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Vendo__27154289] DEFAULT ('') FOR [VendorName]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Histo__36578619] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Accou__280966C2] DEFAULT ('') FOR [AccountCode]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Invoi__289937D2] DEFAULT ('') FOR [InvoiceImage]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__ItemN__28FD8AFB] DEFAULT ('') FOR [ItemNumber]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Fisca__29F1AF34] DEFAULT ('') FOR [FiscalMonthCode]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Depar__17D2FEF9] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Fisca__2AE5D36D] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Depar__2BD9F7A6] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Custo__2CCE1BDF] DEFAULT ('') FOR [CustomText1]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Custo__2DC24018] DEFAULT ('') FOR [CustomText2]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Custo__2EB66451] DEFAULT ('') FOR [CustomText3]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Custo__2FAA888A] DEFAULT ('') FOR [CustomText4]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Custo__309EACC3] DEFAULT ('') FOR [CustomText5]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Custo__3192D0FC] DEFAULT (getdate()) FOR [CustomDate1]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Custo__3286F535] DEFAULT (getdate()) FOR [CustomDate2]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Custo__337B196E] DEFAULT ((0)) FOR [CustomNumeric1]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Custo__346F3DA7] DEFAULT ((0)) FOR [CustomNumeric2]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__IsDel__356361E0] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Trans__374BAA52] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__IsSam__3933F2C4] DEFAULT ((0)) FOR [IsSampled]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Sampl__3A2816FD] DEFAULT (getdate()) FOR [SampleDate]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Trans__69D72A1F] DEFAULT ('') FOR [TransID]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__PONum__7A89B943] DEFAULT ('') FOR [PONumber]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Custo__7B7DDD7C] DEFAULT ('') FOR [CustomLongText1]; GO +ALTER TABLE [int].[FactAPDetail] ADD CONSTRAINT [DF__FactAPDet__Custo__7C7201B5] DEFAULT ('') FOR [CustomLongText2]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactAssetWorkOrderDetail ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactAssetWorkOrderDetail] ( + [RowID] int NOT NULL, + [WorkOrderTypeID] int NOT NULL, + [DateID] int NOT NULL, + [AssetCode] nvarchar(100) NOT NULL, + [WorkOrderNumber] nvarchar(100) NOT NULL, + [LaborHours] decimal NOT NULL, + [PartsCost] decimal NOT NULL, + [LaborCost] decimal NOT NULL, + [CustomNumeric1] decimal NOT NULL, + [CustomNumeric2] decimal NOT NULL, + [CustomNumeric3] decimal NOT NULL, + [CustomNumeric4] decimal NOT NULL, + [CustomNumeric5] decimal NOT NULL, + [CustomText1] nvarchar(200) NOT NULL, + [CustomText2] nvarchar(200) NOT NULL, + [CustomText3] nvarchar(200) NOT NULL, + [CustomText4] nvarchar(200) NOT NULL, + [CustomText5] nvarchar(200) NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [FK__FactAsset__DateI__6A1E1157] FOREIGN KEY ([DateID]) REFERENCES [fw].[DimDate] ([DateID]); GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [FK__FactAsset__WorkO__6835C8E5] FOREIGN KEY ([WorkOrderTypeID]) REFERENCES [cap].[DimWorkOrderType] ([WorkOrderTypeID]); GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [DF__FactAsset__WorkO__6741A4AC] DEFAULT ((0)) FOR [WorkOrderTypeID]; GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [DF__FactAsset__DateI__6929ED1E] DEFAULT ((0)) FOR [DateID]; GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [DF__FactAsset__Asset__6B123590] DEFAULT ('') FOR [AssetCode]; GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [DF__FactAsset__WorkO__6C0659C9] DEFAULT ('') FOR [WorkOrderNumber]; GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [DF__FactAsset__Labor__6CFA7E02] DEFAULT ((0)) FOR [LaborHours]; GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [DF__FactAsset__Parts__6DEEA23B] DEFAULT ((0)) FOR [PartsCost]; GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [DF__FactAsset__Labor__6EE2C674] DEFAULT ((0)) FOR [LaborCost]; GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [DF__FactAsset__Custo__6FD6EAAD] DEFAULT ((0)) FOR [CustomNumeric1]; GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [DF__FactAsset__Custo__70CB0EE6] DEFAULT ((0)) FOR [CustomNumeric2]; GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [DF__FactAsset__Custo__71BF331F] DEFAULT ((0)) FOR [CustomNumeric3]; GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [DF__FactAsset__Custo__72B35758] DEFAULT ((0)) FOR [CustomNumeric4]; GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [DF__FactAsset__Custo__73A77B91] DEFAULT ((0)) FOR [CustomNumeric5]; GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [DF__FactAsset__Custo__749B9FCA] DEFAULT ('') FOR [CustomText1]; GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [DF__FactAsset__Custo__758FC403] DEFAULT ('') FOR [CustomText2]; GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [DF__FactAsset__Custo__7683E83C] DEFAULT ('') FOR [CustomText3]; GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [DF__FactAsset__Custo__77780C75] DEFAULT ('') FOR [CustomText4]; GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [DF__FactAsset__Custo__786C30AE] DEFAULT ('') FOR [CustomText5]; GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [DF__FactAsset__IsDel__796054E7] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [DF__FactAsset__Histo__7A547920] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactAssetWorkOrderDetail] ADD CONSTRAINT [DF__FactAsset__Trans__7B489D59] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactCDM ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactCDM] ( + [RowID] bigint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] nvarchar(100) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] nvarchar(100) NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalMonthCode] nvarchar(100) NOT NULL, + [DepartmentID] int NOT NULL, + [DepartmentCode] nvarchar(100) NOT NULL, + [PatientClassID] int NOT NULL, + [PatientClassCode] nvarchar(100) NOT NULL, + [ChargeCodeID] int NOT NULL, + [ChargeCode] nvarchar(100) NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLine] nvarchar(100) NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [MedSurg] nvarchar(100) NOT NULL, + [AgeCohortID] int NOT NULL, + [AgeCohort] nvarchar(100) NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [UnitType] nvarchar(100) NOT NULL, + [Value] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [CNU_BASE] ON [int].[FactCDM] ([FiscalMonthID], [IsDeleted], [FiscalYearID], [DepartmentID], [ChargeCodeID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID]); +CREATE NONCLUSTERED INDEX [NCNU_SampleView] ON [int].[FactCDM] ([FiscalMonthID], [IsDeleted], [FiscalYearID], [DepartmentID], [ChargeCodeID], [ServiceLineID], [PatientClassID], [AgeCohortID], [MedicalSurgicalID]); +CREATE NONCLUSTERED INDEX [IX_FactCDM_ForFlexingReconciliation] ON [int].[FactCDM] ([DepartmentID], [ChargeCodeID], [FiscalYearID], [UnitTypeID], [TimeClassID], [FiscalMonthID]) INCLUDE ([ServiceLineID]); +GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [FK__FactCDM__AgeCoho__604A9289] FOREIGN KEY ([AgeCohortID]) REFERENCES [fw].[DimAgeCohort] ([AgeCohortID]); GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [FK__FactCDM__ChargeC__6232DAFB] FOREIGN KEY ([ChargeCodeID]) REFERENCES [fw].[DimChargeCode] ([ChargeCodeID]); GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [FK__FactCDM__Departm__5E624A17] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [FK__FactCDM__FiscalM__641B236D] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [FK__FactCDM__FiscalY__66036BDF] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [FK__FactCDM__Medical__67EBB451] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [FK__FactCDM__Patient__69D3FCC3] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [FK__FactCDM__Service__6BBC4535] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [FK__FactCDM__UnitTyp__6DA48DA7] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__Departm__5D6E25DE] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__TimeCla__79170BAA] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__TimeCla__7A0B2FE3] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__FiscalY__650F47A6] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__FiscalY__735D66FD] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__History__79164053] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__FiscalM__6326FF34] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__FiscalM__726942C4] DEFAULT ('') FOR [FiscalMonthCode]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__Departm__6F8CD619] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__Patient__68DFD88A] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__Patient__74518B36] DEFAULT ('') FOR [PatientClassCode]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__ChargeC__613EB6C2] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__ChargeC__7080FA52] DEFAULT ('') FOR [ChargeCode]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__Service__6AC820FC] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__Service__71751E8B] DEFAULT ('') FOR [ServiceLine]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__Medical__66F79018] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__MedSurg__7639D3A8] DEFAULT ('') FOR [MedSurg]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__AgeCoho__5F566E50] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__AgeCoho__7545AF6F] DEFAULT ('') FOR [AgeCohort]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__UnitTyp__6CB0696E] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__UnitTyp__772DF7E1] DEFAULT ('') FOR [UnitType]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__Value__6E98B1E0] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__IsDelet__78221C1A] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactCDM] ADD CONSTRAINT [DF__FactCDM__Transac__7A0A648C] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactCDMImport ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactCDMImport] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [EntityID] int NOT NULL, + [Dollars] decimal NOT NULL, + [Units] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [int].[FactCDMImport] ([DepartmentID], [ChargeCodeID], [FiscalYearID], [FiscalMonthID], [TimeClassID], [EntityID], [IsDeleted]); +GO +ALTER TABLE [int].[FactCDMImport] ADD CONSTRAINT [FK__FactCDMIm__Charg__0FC60065] FOREIGN KEY ([ChargeCodeID]) REFERENCES [fw].[DimChargeCode] ([ChargeCodeID]); GO +ALTER TABLE [int].[FactCDMImport] ADD CONSTRAINT [FK__FactCDMIm__Depar__0DDDB7F3] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [int].[FactCDMImport] ADD CONSTRAINT [FK__FactCDMIm__Entit__1767222D] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [int].[FactCDMImport] ADD CONSTRAINT [FK__FactCDMIm__Fisca__11AE48D7] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [int].[FactCDMImport] ADD CONSTRAINT [FK__FactCDMIm__Fisca__13969149] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO +ALTER TABLE [int].[FactCDMImport] ADD CONSTRAINT [FK__FactCDMIm__TimeC__157ED9BB] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [int].[FactCDMImport] ADD CONSTRAINT [DF__FactCDMIm__Charg__0ED1DC2C] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [int].[FactCDMImport] ADD CONSTRAINT [DF__FactCDMIm__Fisca__10BA249E] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactCDMImport] ADD CONSTRAINT [DF__FactCDMIm__Fisca__12A26D10] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactCDMImport] ADD CONSTRAINT [DF__FactCDMIm__TimeC__148AB582] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactCDMImport] ADD CONSTRAINT [DF__FactCDMIm__Entit__1672FDF4] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [int].[FactCDMImport] ADD CONSTRAINT [DF__FactCDMIm__Dolla__185B4666] DEFAULT ((0)) FOR [Dollars]; GO +ALTER TABLE [int].[FactCDMImport] ADD CONSTRAINT [DF__FactCDMIm__Hours__194F6A9F] DEFAULT ((0)) FOR [Units]; GO +ALTER TABLE [int].[FactCDMImport] ADD CONSTRAINT [DF__FactCDMIm__IsDel__1A438ED8] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactCDMImport] ADD CONSTRAINT [DF__FactCDMIm__Depar__0CE993BA] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [int].[FactCDMImport] ADD CONSTRAINT [DF__INT_FactCDMImport_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactCDMImport] ADD CONSTRAINT [DF__FactCDMIm__Histo__1B37B311] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactCernerPatientADT ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactCernerPatientADT] ( + [RowID] int NOT NULL, + [EncounterNumber] nvarchar(100) NOT NULL, + [PatientType] nvarchar(100) NOT NULL, + [ChangeType] nvarchar(100) NOT NULL, + [ChangeTypeDescription] nvarchar(100) NOT NULL, + [Entity] nvarchar(100) NOT NULL, + [Service] nvarchar(100) NOT NULL, + [EffectiveDateTime] datetime NOT NULL, + [SourceNurseStation] nvarchar(100) NOT NULL, + [SourceBed] nvarchar(100) NOT NULL, + [SourceCostCenter] nvarchar(100) NOT NULL, + [TargetNurseStation] nvarchar(100) NOT NULL, + [TargetBed] nvarchar(100) NOT NULL, + [TargetCostCenter] nvarchar(100) NOT NULL, + [SequenceNumber] nvarchar(100) NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE NONCLUSTERED INDEX [IDX_PatType_HistGUID_Incl_Ern] ON [int].[FactCernerPatientADT] ([PatientType], [HistoryItemGUID]) INCLUDE ([EncounterNumber]); +CREATE NONCLUSTERED INDEX [IDX_ChType_INC_Ern_EffDt_Tcc_Scc_SeqN] ON [int].[FactCernerPatientADT] ([ChangeType]) INCLUDE ([EncounterNumber], [EffectiveDateTime], [TargetCostCenter], [SourceCostCenter], [SequenceNumber]); +CREATE NONCLUSTERED INDEX [IDX_Ern_Incl_CType_EffDate_Tcc_SeqNum] ON [int].[FactCernerPatientADT] ([EncounterNumber]) INCLUDE ([ChangeType], [EffectiveDateTime], [TargetCostCenter], [SequenceNumber]); +GO +ALTER TABLE [int].[FactCernerPatientADT] ADD CONSTRAINT [DF__FactCerne__Encou__200A1ABF] DEFAULT ('') FOR [EncounterNumber]; GO +ALTER TABLE [int].[FactCernerPatientADT] ADD CONSTRAINT [DF__FactCerne__Patie__20FE3EF8] DEFAULT ('') FOR [PatientType]; GO +ALTER TABLE [int].[FactCernerPatientADT] ADD CONSTRAINT [DF__FactCerne__Chang__21F26331] DEFAULT ('') FOR [ChangeType]; GO +ALTER TABLE [int].[FactCernerPatientADT] ADD CONSTRAINT [DF__FactCerne__Chang__22E6876A] DEFAULT ('') FOR [ChangeTypeDescription]; GO +ALTER TABLE [int].[FactCernerPatientADT] ADD CONSTRAINT [DF__FactCerne__Entit__23DAABA3] DEFAULT ('') FOR [Entity]; GO +ALTER TABLE [int].[FactCernerPatientADT] ADD CONSTRAINT [DF__FactCerne__Servi__24CECFDC] DEFAULT ('') FOR [Service]; GO +ALTER TABLE [int].[FactCernerPatientADT] ADD CONSTRAINT [DF__FactCerne__Effec__25C2F415] DEFAULT (getdate()) FOR [EffectiveDateTime]; GO +ALTER TABLE [int].[FactCernerPatientADT] ADD CONSTRAINT [DF__FactCerne__Histo__2E583A16] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactCernerPatientADT] ADD CONSTRAINT [DF__FactCerne__Sourc__26B7184E] DEFAULT ('') FOR [SourceNurseStation]; GO +ALTER TABLE [int].[FactCernerPatientADT] ADD CONSTRAINT [DF__FactCerne__Sourc__27AB3C87] DEFAULT ('') FOR [SourceBed]; GO +ALTER TABLE [int].[FactCernerPatientADT] ADD CONSTRAINT [DF__FactCerne__Sourc__289F60C0] DEFAULT ('') FOR [SourceCostCenter]; GO +ALTER TABLE [int].[FactCernerPatientADT] ADD CONSTRAINT [DF__FactCerne__Targe__299384F9] DEFAULT ('') FOR [TargetNurseStation]; GO +ALTER TABLE [int].[FactCernerPatientADT] ADD CONSTRAINT [DF__FactCerne__Targe__2A87A932] DEFAULT ('') FOR [TargetBed]; GO +ALTER TABLE [int].[FactCernerPatientADT] ADD CONSTRAINT [DF__FactCerne__Targe__2B7BCD6B] DEFAULT ('') FOR [TargetCostCenter]; GO +ALTER TABLE [int].[FactCernerPatientADT] ADD CONSTRAINT [DF__FactCerne__Seque__2C6FF1A4] DEFAULT ('') FOR [SequenceNumber]; GO +ALTER TABLE [int].[FactCernerPatientADT] ADD CONSTRAINT [DF__FactCerne__IsDel__2D6415DD] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactCernerPatientADT] ADD CONSTRAINT [DF__FactCerne__Trans__2F4C5E4F] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactEpicPatientADT ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactEpicPatientADT] ( + [RowID] int NOT NULL, + [EncounterRecordNumber] nvarchar(100) NOT NULL, + [AccommodationCode] nvarchar(100) NOT NULL, + [AccommodationCodeDescription] nvarchar(100) NOT NULL, + [EventID] nvarchar(100) NOT NULL, + [EventTypeCode] nvarchar(100) NOT NULL, + [EventTypeCodeDescription] nvarchar(100) NOT NULL, + [EventSubTypeCode] nvarchar(100) NOT NULL, + [DepartmentCode] nvarchar(100) NOT NULL, + [DepartmentDescription] nvarchar(100) NOT NULL, + [RoomNumber] nvarchar(100) NOT NULL, + [BedID] nvarchar(100) NOT NULL, + [EffectiveDateTimeStamp] datetime NOT NULL, + [TransferInEventID] nvarchar(100) NOT NULL, + [NextOutEventID] nvarchar(100) NOT NULL, + [LastInEventID] nvarchar(100) NOT NULL, + [EventSequenceNumber] nvarchar(100) NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [AcuityCode] nvarchar(100) NOT NULL, + [EpicDepartment] nvarchar(100) NULL, + PRIMARY KEY ([RowID]) +); + +CREATE NONCLUSTERED INDEX [NC_IDX_EpicADT_HistGUID_ERN] ON [int].[FactEpicPatientADT] ([HistoryItemGUID]) INCLUDE ([EncounterRecordNumber]); +CREATE NONCLUSTERED INDEX [NC_FactEpicADT_HistGUID_ERN] ON [int].[FactEpicPatientADT] ([HistoryItemGUID]) INCLUDE ([EncounterRecordNumber]); +CREATE NONCLUSTERED INDEX [NC_FactEpicADT_AC_HistGUID_ERN] ON [int].[FactEpicPatientADT] ([AccommodationCode], [HistoryItemGUID]) INCLUDE ([EncounterRecordNumber]); +CREATE NONCLUSTERED INDEX [NC_FactEpicADT_ERN] ON [int].[FactEpicPatientADT] ([EncounterRecordNumber]); +CREATE NONCLUSTERED INDEX [NC_Hist_EffectDateTime] ON [int].[FactEpicPatientADT] ([HistoryItemGUID]) INCLUDE ([EffectiveDateTimeStamp]); +CREATE NONCLUSTERED INDEX [NC_EpiAdt_AccDesc] ON [int].[FactEpicPatientADT] ([AccommodationCodeDescription]) INCLUDE ([EncounterRecordNumber], [EventTypeCode], [EventSubTypeCode], [DepartmentCode], [EffectiveDateTimeStamp]); +CREATE NONCLUSTERED INDEX [NC_IDX_EpicPatientADT_LastEventID] ON [int].[FactEpicPatientADT] ([LastInEventID]); +CREATE NONCLUSTERED INDEX [NC_IDX_EpicPatientADT_NextOutEventID] ON [int].[FactEpicPatientADT] ([NextOutEventID]); +GO +ALTER TABLE [int].[FactEpicPatientADT] ADD CONSTRAINT [DF__FactEpicP__Trans__0116BB41] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactEpicPatientADT] ADD CONSTRAINT [DF__FactEpicP__Histo__00229708] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactEpicPatientADT] ADD CONSTRAINT [DF__FactEpicP__EpicD__50CF1623] DEFAULT ('') FOR [EpicDepartment]; GO +ALTER TABLE [int].[FactEpicPatientADT] ADD CONSTRAINT [DF__FactEpicP__Acuit__67D24542] DEFAULT ('') FOR [AcuityCode]; GO +ALTER TABLE [int].[FactEpicPatientADT] ADD CONSTRAINT [DF__FactEpicP__Encou__6FEC2F3F] DEFAULT ('') FOR [EncounterRecordNumber]; GO +ALTER TABLE [int].[FactEpicPatientADT] ADD CONSTRAINT [DF__FactEpicP__Accom__70E05378] DEFAULT ('') FOR [AccommodationCode]; GO +ALTER TABLE [int].[FactEpicPatientADT] ADD CONSTRAINT [DF__FactEpicP__Accom__71D477B1] DEFAULT ('') FOR [AccommodationCodeDescription]; GO +ALTER TABLE [int].[FactEpicPatientADT] ADD CONSTRAINT [DF__FactEpicP__Event__72C89BEA] DEFAULT ('') FOR [EventID]; GO +ALTER TABLE [int].[FactEpicPatientADT] ADD CONSTRAINT [DF__FactEpicP__Event__73BCC023] DEFAULT ('') FOR [EventTypeCode]; GO +ALTER TABLE [int].[FactEpicPatientADT] ADD CONSTRAINT [DF__FactEpicP__Event__74B0E45C] DEFAULT ('') FOR [EventTypeCodeDescription]; GO +ALTER TABLE [int].[FactEpicPatientADT] ADD CONSTRAINT [DF__FactEpicP__Event__75A50895] DEFAULT ('') FOR [EventSubTypeCode]; GO +ALTER TABLE [int].[FactEpicPatientADT] ADD CONSTRAINT [DF__FactEpicP__Depar__76992CCE] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactEpicPatientADT] ADD CONSTRAINT [DF__FactEpicP__Depar__778D5107] DEFAULT ('') FOR [DepartmentDescription]; GO +ALTER TABLE [int].[FactEpicPatientADT] ADD CONSTRAINT [DF__FactEpicP__RoomN__78817540] DEFAULT ('') FOR [RoomNumber]; GO +ALTER TABLE [int].[FactEpicPatientADT] ADD CONSTRAINT [DF__FactEpicP__BedID__79759979] DEFAULT ('') FOR [BedID]; GO +ALTER TABLE [int].[FactEpicPatientADT] ADD CONSTRAINT [DF__FactEpicP__Effec__7A69BDB2] DEFAULT (getdate()) FOR [EffectiveDateTimeStamp]; GO +ALTER TABLE [int].[FactEpicPatientADT] ADD CONSTRAINT [DF__FactEpicP__Trans__7B5DE1EB] DEFAULT ('') FOR [TransferInEventID]; GO +ALTER TABLE [int].[FactEpicPatientADT] ADD CONSTRAINT [DF__FactEpicP__NextO__7C520624] DEFAULT ('') FOR [NextOutEventID]; GO +ALTER TABLE [int].[FactEpicPatientADT] ADD CONSTRAINT [DF__FactEpicP__LastI__7D462A5D] DEFAULT ('') FOR [LastInEventID]; GO +ALTER TABLE [int].[FactEpicPatientADT] ADD CONSTRAINT [DF__FactEpicP__Event__7E3A4E96] DEFAULT ('') FOR [EventSequenceNumber]; GO +ALTER TABLE [int].[FactEpicPatientADT] ADD CONSTRAINT [DF__FactEpicP__IsDel__7F2E72CF] DEFAULT ((0)) FOR [IsDeleted]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactFinancialServiceLineCost ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactFinancialServiceLineCost] ( + [RowID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [ForecastDetailID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [PatientClassID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [FiscalMonthCode] nvarchar(100) NOT NULL, + [TimeClassCode] nvarchar(100) NOT NULL, + [ForecastDetailCode] nvarchar(100) NOT NULL, + [EntityCode] nvarchar(100) NOT NULL, + [DepartmentCode] nvarchar(100) NOT NULL, + [ServiceLineCode] nvarchar(100) NOT NULL, + [PatientClassCode] nvarchar(100) NOT NULL, + [AgeCohortCode] nvarchar(100) NOT NULL, + [Value] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [MedicalSurgicalCode] nvarchar(100) NOT NULL, + [UnitTypeName] nvarchar(100) NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [FK__FactFinan__AgeCo__1210CF59] FOREIGN KEY ([AgeCohortID]) REFERENCES [fw].[DimAgeCohort] ([AgeCohortID]); GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [FK__FactFinan__Depar__0C57F603] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [FK__FactFinan__Entit__0A6FAD91] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [FK__FactFinan__Fisca__00E64357] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [FK__FactFinan__Fisca__02CE8BC9] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [FK__FactFinan__Forec__069F1CAD] FOREIGN KEY ([ForecastDetailID]) REFERENCES [fw].[DimForecastDetail] ([ForecastDetailID]); GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [FK__FactFinan__Medic__13F917CB] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [FK__FactFinan__Patie__102886E7] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [FK__FactFinan__Servi__0E403E75] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [FK__FactFinan__TimeC__04B6D43B] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [FK__FactFinan__UnitT__0887651F] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__Fisca__01DA6790] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__TimeC__03C2B002] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__Forec__05AAF874] DEFAULT ((0)) FOR [ForecastDetailID]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__UnitT__079340E6] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__Servi__0D4C1A3C] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__Patie__0F3462AE] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__AgeCo__111CAB20] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__Medic__1304F392] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__Fisca__14ED3C04] DEFAULT ('') FOR [FiscalMonthCode]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__TimeC__15E1603D] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__Forec__16D58476] DEFAULT ('') FOR [ForecastDetailCode]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__Entit__18BDCCE8] DEFAULT ('') FOR [EntityCode]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__Depar__19B1F121] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__Servi__1AA6155A] DEFAULT ('') FOR [ServiceLineCode]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__Patie__1B9A3993] DEFAULT ('') FOR [PatientClassCode]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__AgeCo__1C8E5DCC] DEFAULT ('') FOR [AgeCohortCode]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__Value__1D828205] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__IsDel__1E76A63E] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__Entit__097B8958] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__Depar__0B63D1CA] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__Trans__205EEEB0] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__Medic__333CB8FA] DEFAULT ('') FOR [MedicalSurgicalCode]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__Histo__1F6ACA77] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__UnitT__78DB0D3B] DEFAULT ('') FOR [UnitTypeName]; GO +ALTER TABLE [int].[FactFinancialServiceLineCost] ADD CONSTRAINT [DF__FactFinan__Fisca__7FF21F1E] DEFAULT ((0)) FOR [FiscalYearID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactFinancialServiceLineRevenue ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactFinancialServiceLineRevenue] ( + [RowID] bigint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [EntityID] int NOT NULL, + [ForecastDetailID] int NOT NULL, + [ServiceLineID] int NOT NULL, + [PatientClassID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [FiscalMonthCode] nvarchar(100) NOT NULL, + [TimeClassCode] nvarchar(100) NOT NULL, + [ServiceLineCode] nvarchar(100) NOT NULL, + [PatientClassCode] nvarchar(100) NOT NULL, + [AgeCohortCode] nvarchar(100) NOT NULL, + [MedSurgCode] nvarchar(100) NOT NULL, + [PayorCode] nvarchar(100) NOT NULL, + [PayorGroupCode] nvarchar(100) NOT NULL, + [Value] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [EntityCode] nvarchar(100) NOT NULL, + [ForecastDetailCode] nvarchar(100) NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [FK__FactFinan__AgeCo__6A02DDFF] FOREIGN KEY ([AgeCohortID]) REFERENCES [fw].[DimAgeCohort] ([AgeCohortID]); GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [FK__FactFinan__Entit__6261BC37] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [FK__FactFinan__Fisca__5CA8E2E1] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [FK__FactFinan__Fisca__5E912B53] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [FK__FactFinan__Forec__644A04A9] FOREIGN KEY ([ForecastDetailID]) REFERENCES [fw].[DimForecastDetail] ([ForecastDetailID]); GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [FK__FactFinan__Medic__6BEB2671] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [FK__FactFinan__Patie__681A958D] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [FK__FactFinan__Payor__6DD36EE3] FOREIGN KEY ([PayorID]) REFERENCES [fw].[DimPayor] ([PayorID]); GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [FK__FactFinan__Payor__6FBBB755] FOREIGN KEY ([PayorGroupID]) REFERENCES [fw].[DimPayorGroup] ([PayorGroupID]); GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [FK__FactFinan__Servi__66324D1B] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [FK__FactFinan__TimeC__607973C5] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__Fisca__70AFDB8E] DEFAULT ('') FOR [FiscalMonthCode]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__TimeC__71A3FFC7] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__Servi__74806C72] DEFAULT ('') FOR [ServiceLineCode]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__Patie__757490AB] DEFAULT ('') FOR [PatientClassCode]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__AgeCo__7668B4E4] DEFAULT ('') FOR [AgeCohortCode]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__MedSu__775CD91D] DEFAULT ('') FOR [MedSurgCode]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__Payor__7850FD56] DEFAULT ('') FOR [PayorCode]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__Payor__7945218F] DEFAULT ('') FOR [PayorGroupCode]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__Entit__616D97FE] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__Value__7A3945C8] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__Entit__7AC355AD] DEFAULT ('') FOR [EntityCode]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__IsDel__7B2D6A01] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__Trans__7D15B273] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__Histo__7C218E3A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__Forec__22CBE970] DEFAULT ('') FOR [ForecastDetailCode]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__Fisca__5BB4BEA8] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__Fisca__5D9D071A] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__TimeC__5F854F8C] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__Forec__6355E070] DEFAULT ((0)) FOR [ForecastDetailID]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__Servi__653E28E2] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__Patie__67267154] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__AgeCo__690EB9C6] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__Medic__6AF70238] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__Payor__6CDF4AAA] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [int].[FactFinancialServiceLineRevenue] ADD CONSTRAINT [DF__FactFinan__Payor__6EC7931C] DEFAULT ((0)) FOR [PayorGroupID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactGL ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactGL] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [DepartmentCode] varchar(100) NOT NULL, + [AccountID] int NOT NULL, + [AccountCode] varchar(50) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] varchar(20) NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] varchar(20) NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalMonthCode] varchar(20) NOT NULL, + [Value] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [int].[FactGL] ([FiscalMonthID], [IsDeleted], [FiscalYearID], [TimeClassID], [DepartmentID], [AccountID], [RowID]); +CREATE NONCLUSTERED INDEX [IX_FactGL_Covering_0] ON [int].[FactGL] ([AccountID]) INCLUDE ([DepartmentID], [FiscalMonthID], [FiscalYearID], [TimeClassID], [Value]); +GO +ALTER TABLE [int].[FactGL] ADD CONSTRAINT [DF__FactGL__TimeClas__5E3009B5] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactGL] ADD CONSTRAINT [DF__FactGL__FiscalMo__7AFE56FB] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactGL] ADD CONSTRAINT [DF_FactGL_FiscalMonthCode] DEFAULT ('') FOR [FiscalMonthCode]; GO +ALTER TABLE [int].[FactGL] ADD CONSTRAINT [DF_INTFACTGLVALUETOTAL] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [int].[FactGL] ADD CONSTRAINT [DF__FactGL__IsDelete__3FA88703] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactGL] ADD CONSTRAINT [DF__FactGL__HistoryI__6D724D45] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactGL] ADD CONSTRAINT [DF__FactGL__Departme__57830C26] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [int].[FactGL] ADD CONSTRAINT [DF__INT_FactGL_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactGL] ADD CONSTRAINT [DF__FactGL__Departme__5877305F] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactGL] ADD CONSTRAINT [DF__FactGL__AccountI__596B5498] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [int].[FactGL] ADD CONSTRAINT [DF__FactGL__AccountC__5A5F78D1] DEFAULT ('') FOR [AccountCode]; GO +ALTER TABLE [int].[FactGL] ADD CONSTRAINT [DF__FactGL__FiscalYe__5B539D0A] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactGL] ADD CONSTRAINT [DF__FactGL__FiscalYe__5C47C143] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactGL] ADD CONSTRAINT [DF__FactGL__TimeClas__5D3BE57C] DEFAULT ((0)) FOR [TimeClassID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactGLDetail ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactGLDetail] ( + [RowID] bigint NOT NULL, + [AccountID] int NOT NULL, + [ComponentID] smallint NOT NULL, + [ProjectID] int NOT NULL, + [DepartmentID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [AccountCode] nvarchar(100) NOT NULL, + [ClientCapitalID] nvarchar(100) NOT NULL, + [ClientComponentID] nvarchar(100) NOT NULL, + [ClientDate] datetime NOT NULL, + [Amount] decimal NOT NULL, + [DepartmentCode] nvarchar(100) NOT NULL, + [FiscalMonthCode] nvarchar(100) NOT NULL, + [FiscalYearCode] nvarchar(100) NOT NULL, + [IsSampled] bit NOT NULL, + [ItemDescription] nvarchar(100) NOT NULL, + [SampleDate] datetime NOT NULL, + [JournalNumber] nvarchar(100) NOT NULL, + [JournalLineNumber] nvarchar(100) NOT NULL, + [CustomText1] nvarchar(100) NOT NULL, + [CustomText2] nvarchar(100) NOT NULL, + [CustomText3] nvarchar(100) NOT NULL, + [CustomText4] nvarchar(100) NOT NULL, + [CustomText5] nvarchar(100) NOT NULL, + [CustomDate1] datetime NOT NULL, + [CustomDate2] datetime NOT NULL, + [CustomNumeric1] decimal NOT NULL, + [CustomNumeric2] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [TransID] nvarchar(100) NOT NULL, + [BigRowID] bigint NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [CNU_BASE] ON [int].[FactGLDetail] ([FiscalMonthID], [IsDeleted], [FiscalYearID], [DepartmentID], [AccountID], [ComponentID], [ProjectID]); +CREATE NONCLUSTERED INDEX [NCNU_SampleView] ON [int].[FactGLDetail] ([FiscalMonthID], [IsDeleted], [FiscalYearID], [DepartmentID], [AccountID], [ComponentID], [ProjectID]); +GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [FK__FactGLDet__Accou__741FAE68] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [FK__FactGLDet__Compo__7607F6DA] FOREIGN KEY ([ComponentID]) REFERENCES [cap].[DimComponent] ([ComponentID]); GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [FK__FactGLDet__Depar__79D887BE] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [FK__FactGLDet__Fisca__7BC0D030] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [FK__FactGLDet__Fisca__7DA918A2] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [FK__FactGLDet__Proje__77F03F4C] FOREIGN KEY ([ProjectID]) REFERENCES [cap].[DimProject] ([ProjectID]); GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Clien__0085854D] DEFAULT ('') FOR [ClientComponentID]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Clien__0179A986] DEFAULT (getdate()) FOR [ClientDate]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Amoun__026DCDBF] DEFAULT ((0)) FOR [Amount]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Depar__0361F1F8] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Fisca__04561631] DEFAULT ('') FOR [FiscalMonthCode]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Fisca__054A3A6A] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__IsSam__063E5EA3] DEFAULT ((0)) FOR [IsSampled]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__ItemD__073282DC] DEFAULT ('') FOR [ItemDescription]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Sampl__0826A715] DEFAULT (getdate()) FOR [SampleDate]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Journ__091ACB4E] DEFAULT ('') FOR [JournalNumber]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Journ__0A0EEF87] DEFAULT ('') FOR [JournalLineNumber]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Custo__0B0313C0] DEFAULT ('') FOR [CustomText1]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Custo__0BF737F9] DEFAULT ('') FOR [CustomText2]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Custo__0CEB5C32] DEFAULT ('') FOR [CustomText3]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Custo__0DDF806B] DEFAULT ('') FOR [CustomText4]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Depar__78E46385] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Custo__0ED3A4A4] DEFAULT ('') FOR [CustomText5]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Custo__0FC7C8DD] DEFAULT (getdate()) FOR [CustomDate1]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Custo__10BBED16] DEFAULT (getdate()) FOR [CustomDate2]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Custo__11B0114F] DEFAULT ((0)) FOR [CustomNumeric1]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Custo__12A43588] DEFAULT ((0)) FOR [CustomNumeric2]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__IsDel__139859C1] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Trans__1580A233] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Trans__415F2471] DEFAULT ('') FOR [TransID]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Accou__732B8A2F] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Compo__7513D2A1] DEFAULT ((0)) FOR [ComponentID]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Proje__76FC1B13] DEFAULT ((0)) FOR [ProjectID]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Fisca__7ACCABF7] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Fisca__7CB4F469] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Accou__7E9D3CDB] DEFAULT ('') FOR [AccountCode]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Histo__148C7DFA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactGLDetail] ADD CONSTRAINT [DF__FactGLDet__Clien__7F916114] DEFAULT ('') FOR [ClientCapitalID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactGlobalStatistics ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactGlobalStatistics] ( + [RowID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] nvarchar(2000) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] nvarchar(2000) NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalMonthCode] nvarchar(2000) NOT NULL, + [EntityID] int NOT NULL, + [EntityCode] nvarchar(2000) NOT NULL, + [DepartmentID] int NOT NULL, + [DepartmentCode] nvarchar(2000) NOT NULL, + [AccountID] int NOT NULL, + [AccountCode] nvarchar(2000) NOT NULL, + [Value] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [int].[FactGlobalStatistics] ADD CONSTRAINT [DF__FactGloba__TimeC__04F8FB98] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactGlobalStatistics] ADD CONSTRAINT [DF__FactGloba__Fisca__0034467B] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactGlobalStatistics] ADD CONSTRAINT [DF__FactGloba__Fisca__0404D75F] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactGlobalStatistics] ADD CONSTRAINT [DF__FactGloba__Fisca__7F402242] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactGlobalStatistics] ADD CONSTRAINT [DF__FactGloba__Fisca__0310B326] DEFAULT ('') FOR [FiscalMonthCode]; GO +ALTER TABLE [int].[FactGlobalStatistics] ADD CONSTRAINT [DF__FactGloba__Entit__7D97D0F2] DEFAULT ('') FOR [EntityCode]; GO +ALTER TABLE [int].[FactGlobalStatistics] ADD CONSTRAINT [DF__FactGloba__Depar__021C8EED] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactGlobalStatistics] ADD CONSTRAINT [DF__FactGloba__Accou__01286AB4] DEFAULT ('') FOR [AccountCode]; GO +ALTER TABLE [int].[FactGlobalStatistics] ADD CONSTRAINT [DF__FactGloba__Value__05ED1FD1] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [int].[FactGlobalStatistics] ADD CONSTRAINT [DF__FactGloba__IsDel__06E1440A] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactGlobalStatistics] ADD CONSTRAINT [DF__FactGloba__Trans__08C98C7C] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactGlobalStatistics] ADD CONSTRAINT [DF__FactGloba__Entit__7CA3ACB9] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [int].[FactGlobalStatistics] ADD CONSTRAINT [DF__FactGloba__Histo__07D56843] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactImportProvider ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactImportProvider] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [ProviderID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [OBForecastDetailID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [AccountRollup] nvarchar(2000) NOT NULL, + [DepartmentCode] nvarchar(2000) NOT NULL, + [FiscalMonthCode] nvarchar(2000) NOT NULL, + [FiscalYearCode] nvarchar(2000) NOT NULL, + [ProviderCode] nvarchar(2000) NOT NULL, + [TimeClassCode] nvarchar(2000) NOT NULL, + [Value] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE NONCLUSTERED INDEX [NCNU_SampleView] ON [int].[FactImportProvider] ([IsDeleted], [FiscalMonthID], [TimeClassID], [FiscalYearID], [DepartmentID], [ProviderID], [OBForecastDetailID]); +GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [FK__FactImpor__Depar__4CB63923] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [FK__FactImpor__Fisca__526F1279] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [FK__FactImpor__Fisca__54575AEB] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [FK__FactImpor__OBFor__563FA35D] FOREIGN KEY ([OBForecastDetailID]) REFERENCES [ob].[DimOBForecastDetail] ([OBForecastDetailID]); GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [FK__FactImpor__Provi__4E9E8195] FOREIGN KEY ([ProviderID]) REFERENCES [fw].[DimProvider] ([ProviderID]); GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [FK__FactImpor__TimeC__5827EBCF] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [DF__FactImpor__Provi__4DAA5D5C] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [DF__FactImpor__Fisca__517AEE40] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [DF__FactImpor__Fisca__536336B2] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [DF__FactImpor__Histo__61B15609] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [DF__FactImpor__OBFor__554B7F24] DEFAULT ((0)) FOR [OBForecastDetailID]; GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [DF__FactImpor__TimeC__5733C796] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [DF__FactImpor__Accou__591C1008] DEFAULT ('') FOR [AccountRollup]; GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [DF__FactImpor__Depar__5A103441] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [DF__FactImpor__Fisca__5B04587A] DEFAULT ('') FOR [FiscalMonthCode]; GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [DF__FactImpor__Fisca__5BF87CB3] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [DF__FactImpor__Provi__5CECA0EC] DEFAULT ('') FOR [ProviderCode]; GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [DF__FactImpor__TimeC__5DE0C525] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [DF__FactImpor__Value__5FC90D97] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [DF__FactImpor__IsDel__60BD31D0] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [DF__FactImpor__Trans__62A57A42] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactImportProvider] ADD CONSTRAINT [DF__FactImpor__Depar__4BC214EA] DEFAULT ((0)) FOR [DepartmentID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactIntERAsset ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactIntERAsset] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [VendorID] int NOT NULL, + [GlobalTypeID] int NOT NULL, + [AssetCode] nvarchar(100) NOT NULL, + [AssetName] nvarchar(100) NOT NULL, + [DepartmentCode] nvarchar(100) NOT NULL, + [DepartmentDescription] nvarchar(100) NOT NULL, + [EntityCode] nvarchar(100) NOT NULL, + [EntityName] nvarchar(100) NOT NULL, + [AssetCategory] nvarchar(100) NOT NULL, + [VendorCode] nvarchar(100) NOT NULL, + [VendorName] nvarchar(100) NOT NULL, + [Model] nvarchar(100) NOT NULL, + [Serial] nvarchar(100) NOT NULL, + [PurchaseDate] datetime NOT NULL, + [PurchaseCost] decimal NOT NULL, + [ReplacementCost] decimal NOT NULL, + [Downtime] decimal NOT NULL, + [MaintenanceCost] decimal NOT NULL, + [ServiceStatus] nvarchar(100) NOT NULL, + [Volume] decimal NOT NULL, + [CustomMetricText1] nvarchar(100) NOT NULL, + [CustomMetricText2] nvarchar(100) NOT NULL, + [CustomMetricNumeric1] decimal NOT NULL, + [CustomMetricNumeric2] decimal NOT NULL, + [CustomText1] nvarchar(100) NOT NULL, + [CustomText2] nvarchar(100) NOT NULL, + [CustomText3] nvarchar(100) NOT NULL, + [CustomText4] nvarchar(100) NOT NULL, + [CustomText5] nvarchar(100) NOT NULL, + [CustomNumeric1] decimal NOT NULL, + [CustomNumeric2] decimal NOT NULL, + [CustomNumeric3] decimal NOT NULL, + [CustomNumeric4] decimal NOT NULL, + [CustomNumeric5] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [AssetStatusID] int NOT NULL, + [AssetStatusCode] nvarchar(100) NOT NULL, + [ManufacturerID] int NOT NULL, + [ManufacturerCode] nvarchar(100) NOT NULL, + [ManufacturerDescription] nvarchar(100) NOT NULL, + [CustomMetricNumeric3] decimal NOT NULL, + [CustomMetricNumeric4] decimal NOT NULL, + [CustomMetricNumeric5] decimal NOT NULL, + [CustomMetricNumeric6] decimal NOT NULL, + [CustomMetricNumeric7] decimal NOT NULL, + [CustomMetricNumeric8] decimal NOT NULL, + [CustomMetricNumeric9] decimal NOT NULL, + [CustomMetricNumeric10] decimal NOT NULL, + [CustomMetricNumeric11] decimal NOT NULL, + [CustomMetricNumeric12] decimal NOT NULL, + [CustomMetricNumeric13] decimal NOT NULL, + [CustomMetricNumeric14] decimal NOT NULL, + [CustomMetricNumeric15] decimal NOT NULL, + [CustomMetricText3] nvarchar(100) NOT NULL, + [CustomMetricText4] nvarchar(100) NOT NULL, + [CustomMetricText5] nvarchar(100) NOT NULL, + [CustomMetricText6] nvarchar(100) NOT NULL, + [CustomMetricText7] nvarchar(100) NOT NULL, + [CustomMetricText8] nvarchar(100) NOT NULL, + [CustomMetricText9] nvarchar(100) NOT NULL, + [CustomMetricText10] nvarchar(100) NOT NULL, + [CustomMetricText11] nvarchar(100) NOT NULL, + [CustomMetricText12] nvarchar(100) NOT NULL, + [CustomMetricText13] nvarchar(100) NOT NULL, + [CustomMetricText14] nvarchar(100) NOT NULL, + [CustomMetricText15] nvarchar(100) NOT NULL, + [CriticalityStatus] nvarchar(100) NOT NULL, + [EndOfLifeSupportNotification] nvarchar(100) NOT NULL, + [EndOfLifeSupportDate] datetime NOT NULL, + [AssetOwnership] nvarchar(100) NOT NULL, + [SupportedBy] nvarchar(100) NOT NULL, + [CMWorkOrderCount] decimal NOT NULL, + [CMLaborHours] decimal NOT NULL, + [CMLaborCosts] decimal NOT NULL, + [CMPartsCosts] decimal NOT NULL, + [PMWorkOrderCount] decimal NOT NULL, + [PMLaborHours] decimal NOT NULL, + [PMLaborCosts] decimal NOT NULL, + [PMPartsCosts] decimal NOT NULL, + [LastUpdateDate] datetime NOT NULL, + [OperatingSystem] nvarchar(100) NOT NULL, + [NetworkTechnology] nvarchar(100) NOT NULL, + [FleetManaged] nvarchar(100) NOT NULL, + [EquipmentType] nvarchar(100) NOT NULL, + [IsCapital] bit NOT NULL, + [CustomText6] nvarchar(100) NOT NULL, + [CustomText7] nvarchar(100) NOT NULL, + [CustomText8] nvarchar(100) NOT NULL, + [CustomText9] nvarchar(100) NOT NULL, + [CustomText10] nvarchar(100) NOT NULL, + [CustomNumeric6] decimal NOT NULL, + [CustomNumeric7] decimal NOT NULL, + [CustomNumeric8] decimal NOT NULL, + [CustomNumeric9] decimal NOT NULL, + [CustomNumeric10] decimal NOT NULL, + [CustomDate1] datetime NOT NULL, + [CustomDate2] datetime NOT NULL, + [CustomDate3] datetime NOT NULL, + [CustomDate4] datetime NOT NULL, + [CustomDate5] datetime NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [FK__FactIntER__Depar__61F61135] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [FK__FactIntER__Globa__65C6A219] FOREIGN KEY ([GlobalTypeID]) REFERENCES [cap].[DimGlobalType] ([GlobalTypeID]); GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [FK__FactIntER__Vendo__63DE59A7] FOREIGN KEY ([VendorID]) REFERENCES [cap].[DimVendor] ([VendorID]); GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__007A9855] DEFAULT ('') FOR [CustomText5]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__00C050A2] DEFAULT ('') FOR [CustomMetricText8]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__016EBC8E] DEFAULT ((0)) FOR [CustomNumeric1]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__01B474DB] DEFAULT ('') FOR [CustomMetricText9]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__0262E0C7] DEFAULT ((0)) FOR [CustomNumeric2]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__02A89914] DEFAULT ('') FOR [CustomMetricText10]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Asset__02E9F51A] DEFAULT ((0)) FOR [AssetStatusID]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__03570500] DEFAULT ((0)) FOR [CustomNumeric3]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__039CBD4D] DEFAULT ('') FOR [CustomMetricText11]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__044B2939] DEFAULT ((0)) FOR [CustomNumeric4]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__0490E186] DEFAULT ('') FOR [CustomMetricText12]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__053F4D72] DEFAULT ((0)) FOR [CustomNumeric5]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__058505BF] DEFAULT ('') FOR [CustomMetricText13]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__IsDel__063371AB] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__067929F8] DEFAULT ('') FOR [CustomMetricText14]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__076D4E31] DEFAULT ('') FOR [CustomMetricText15]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Trans__081BBA1D] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Criti__0861726A] DEFAULT ('') FOR [CriticalityStatus]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__EndOf__095596A3] DEFAULT ('') FOR [EndOfLifeSupportNotification]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__EndOf__0A49BADC] DEFAULT (getdate()) FOR [EndOfLifeSupportDate]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Asset__0B3DDF15] DEFAULT ('') FOR [AssetOwnership]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Suppo__0C32034E] DEFAULT ('') FOR [SupportedBy]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__CMWor__0D262787] DEFAULT ((0)) FOR [CMWorkOrderCount]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__CMLab__0E1A4BC0] DEFAULT ((0)) FOR [CMLaborHours]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__CMLab__0F0E6FF9] DEFAULT ((0)) FOR [CMLaborCosts]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Histo__072795E4] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__CMPar__10029432] DEFAULT ((0)) FOR [CMPartsCosts]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__PMWor__10F6B86B] DEFAULT ((0)) FOR [PMWorkOrderCount]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__PMLab__11EADCA4] DEFAULT ((0)) FOR [PMLaborHours]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Asset__122C38AA] DEFAULT ('') FOR [AssetStatusCode]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__PMLab__12DF00DD] DEFAULT ((0)) FOR [PMLaborCosts]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__PMPar__13D32516] DEFAULT ((0)) FOR [PMPartsCosts]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__LastU__14C7494F] DEFAULT (getdate()) FOR [LastUpdateDate]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Opera__15BB6D88] DEFAULT ('') FOR [OperatingSystem]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Netwo__16AF91C1] DEFAULT ('') FOR [NetworkTechnology]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Fleet__17A3B5FA] DEFAULT ('') FOR [FleetManaged]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Equip__1897DA33] DEFAULT ('') FOR [EquipmentType]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__IsCap__198BFE6C] DEFAULT ((0)) FOR [IsCapital]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Manuf__391D7F47] DEFAULT ((0)) FOR [ManufacturerID]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Manuf__3A11A380] DEFAULT ('') FOR [ManufacturerCode]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Manuf__3B05C7B9] DEFAULT ('') FOR [ManufacturerDescription]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__56C7E69B] DEFAULT ('') FOR [CustomText6]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__57BC0AD4] DEFAULT ('') FOR [CustomText7]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__58B02F0D] DEFAULT ('') FOR [CustomText8]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__59A45346] DEFAULT ('') FOR [CustomText9]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__5A98777F] DEFAULT ('') FOR [CustomText10]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__5B8C9BB8] DEFAULT ((0)) FOR [CustomNumeric6]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__5C80BFF1] DEFAULT ((0)) FOR [CustomNumeric7]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__5D74E42A] DEFAULT ((0)) FOR [CustomNumeric8]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__5E690863] DEFAULT ((0)) FOR [CustomNumeric9]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__5F5D2C9C] DEFAULT ((0)) FOR [CustomNumeric10]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__605150D5] DEFAULT (getdate()) FOR [CustomDate1]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__6145750E] DEFAULT (getdate()) FOR [CustomDate2]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__62399947] DEFAULT (getdate()) FOR [CustomDate3]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Vendo__62EA356E] DEFAULT ((0)) FOR [VendorID]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__632DBD80] DEFAULT (getdate()) FOR [CustomDate4]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__6421E1B9] DEFAULT (getdate()) FOR [CustomDate5]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Globa__64D27DE0] DEFAULT ((0)) FOR [GlobalTypeID]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Asset__66BAC652] DEFAULT ('') FOR [AssetCode]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Asset__67AEEA8B] DEFAULT ('') FOR [AssetName]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Depar__68A30EC4] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Depar__699732FD] DEFAULT ('') FOR [DepartmentDescription]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Entit__6A8B5736] DEFAULT ('') FOR [EntityCode]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Entit__6B7F7B6F] DEFAULT ('') FOR [EntityName]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Asset__6C739FA8] DEFAULT ('') FOR [AssetCategory]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Vendo__6D67C3E1] DEFAULT ('') FOR [VendorCode]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Vendo__6E5BE81A] DEFAULT ('') FOR [VendorName]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__6F95C4A0] DEFAULT ((0)) FOR [CustomMetricNumeric3]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Model__7044308C] DEFAULT ('') FOR [Model]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__7089E8D9] DEFAULT ((0)) FOR [CustomMetricNumeric4]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Seria__713854C5] DEFAULT ('') FOR [Serial]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__717E0D12] DEFAULT ((0)) FOR [CustomMetricNumeric5]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Purch__722C78FE] DEFAULT (getdate()) FOR [PurchaseDate]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__7272314B] DEFAULT ((0)) FOR [CustomMetricNumeric6]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Purch__73209D37] DEFAULT ((0)) FOR [PurchaseCost]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__73665584] DEFAULT ((0)) FOR [CustomMetricNumeric7]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Repla__7414C170] DEFAULT ((0)) FOR [ReplacementCost]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__745A79BD] DEFAULT ((0)) FOR [CustomMetricNumeric8]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Downt__7508E5A9] DEFAULT ((0)) FOR [Downtime]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__754E9DF6] DEFAULT ((0)) FOR [CustomMetricNumeric9]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Maint__75FD09E2] DEFAULT ((0)) FOR [MaintenanceCost]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__7642C22F] DEFAULT ((0)) FOR [CustomMetricNumeric10]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Servi__76F12E1B] DEFAULT ('') FOR [ServiceStatus]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__7736E668] DEFAULT ((0)) FOR [CustomMetricNumeric11]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Volum__77E55254] DEFAULT ((0)) FOR [Volume]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__782B0AA1] DEFAULT ((0)) FOR [CustomMetricNumeric12]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__78D9768D] DEFAULT ('') FOR [CustomMetricText1]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__791F2EDA] DEFAULT ((0)) FOR [CustomMetricNumeric13]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__79CD9AC6] DEFAULT ('') FOR [CustomMetricText2]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__7A135313] DEFAULT ((0)) FOR [CustomMetricNumeric14]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__7AC1BEFF] DEFAULT ((0)) FOR [CustomMetricNumeric1]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__7B07774C] DEFAULT ((0)) FOR [CustomMetricNumeric15]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__7BB5E338] DEFAULT ((0)) FOR [CustomMetricNumeric2]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__7BFB9B85] DEFAULT ('') FOR [CustomMetricText3]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__7CAA0771] DEFAULT ('') FOR [CustomText1]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__7CEFBFBE] DEFAULT ('') FOR [CustomMetricText4]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Depar__6101ECFC] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__7D9E2BAA] DEFAULT ('') FOR [CustomText2]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__7DE3E3F7] DEFAULT ('') FOR [CustomMetricText5]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__7E924FE3] DEFAULT ('') FOR [CustomText3]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__7ED80830] DEFAULT ('') FOR [CustomMetricText6]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__7F86741C] DEFAULT ('') FOR [CustomText4]; GO +ALTER TABLE [int].[FactIntERAsset] ADD CONSTRAINT [DF__FactIntER__Custo__7FCC2C69] DEFAULT ('') FOR [CustomMetricText7]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactInventoryDetail ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactInventoryDetail] ( + [RowID] bigint NOT NULL, + [AccountID] int NOT NULL, + [DepartmentID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [AccountCode] nvarchar(100) NOT NULL, + [FiscalYearCode] nvarchar(100) NOT NULL, + [FiscalMonthCode] nvarchar(100) NOT NULL, + [DepartmentCode] nvarchar(100) NOT NULL, + [ItemNumber] nvarchar(100) NOT NULL, + [ItemDescription] nvarchar(100) NOT NULL, + [Quantity] decimal NOT NULL, + [InventoryCost] decimal NOT NULL, + [TransID] nvarchar(100) NOT NULL, + [IsSampled] bit NOT NULL, + [SampleDate] datetime NOT NULL, + [CustomText1] nvarchar(100) NOT NULL, + [CustomText2] nvarchar(100) NOT NULL, + [CustomText3] nvarchar(100) NOT NULL, + [CustomText4] nvarchar(100) NOT NULL, + [CustomText5] nvarchar(100) NOT NULL, + [CustomNumeric1] decimal NOT NULL, + [CustomNumeric2] decimal NOT NULL, + [CustomDate1] datetime NOT NULL, + [CustomDate2] datetime NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [CNU_BASE] ON [int].[FactInventoryDetail] ([FiscalMonthID], [IsDeleted], [FiscalYearID], [DepartmentID], [AccountID]); +CREATE NONCLUSTERED INDEX [NCNU_SampleView] ON [int].[FactInventoryDetail] ([FiscalMonthID], [IsDeleted], [FiscalYearID], [DepartmentID], [AccountID]); +GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [FK__FactInven__Accou__431262B9] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [FK__FactInven__Depar__44FAAB2B] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [FK__FactInven__Fisca__46E2F39D] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [FK__FactInven__Fisca__48CB3C0F] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Histo__5DC658F5] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Accou__421E3E80] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Fisca__45EECF64] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Fisca__47D717D6] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Accou__49BF6048] DEFAULT ('') FOR [AccountCode]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Fisca__4AB38481] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Fisca__4BA7A8BA] DEFAULT ('') FOR [FiscalMonthCode]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Depar__4C9BCCF3] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__ItemN__4D8FF12C] DEFAULT ('') FOR [ItemNumber]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__ItemD__4E841565] DEFAULT ('') FOR [ItemDescription]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Quant__4F78399E] DEFAULT ((0)) FOR [Quantity]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Inven__506C5DD7] DEFAULT ((0)) FOR [InventoryCost]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Trans__51608210] DEFAULT ('') FOR [TransID]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__IsSam__5254A649] DEFAULT ((0)) FOR [IsSampled]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Sampl__5348CA82] DEFAULT (getdate()) FOR [SampleDate]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Custo__543CEEBB] DEFAULT ('') FOR [CustomText1]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Custo__553112F4] DEFAULT ('') FOR [CustomText2]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Custo__5625372D] DEFAULT ('') FOR [CustomText3]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Custo__57195B66] DEFAULT ('') FOR [CustomText4]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Custo__580D7F9F] DEFAULT ('') FOR [CustomText5]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Custo__5901A3D8] DEFAULT ((0)) FOR [CustomNumeric1]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Custo__59F5C811] DEFAULT ((0)) FOR [CustomNumeric2]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Custo__5AE9EC4A] DEFAULT (getdate()) FOR [CustomDate1]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Custo__5BDE1083] DEFAULT (getdate()) FOR [CustomDate2]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__IsDel__5CD234BC] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Trans__5EBA7D2E] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactInventoryDetail] ADD CONSTRAINT [DF__FactInven__Depar__440686F2] DEFAULT ((0)) FOR [DepartmentID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactMRImportPODetail ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactMRImportPODetail] ( + [RowID] int NOT NULL, + [AccountID] int NOT NULL, + [DepartmentID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [LineNumber] nvarchar(100) NOT NULL, + [LineDescription] nvarchar(100) NOT NULL, + [ClientDate] datetime NOT NULL, + [Quantity] decimal NOT NULL, + [CostPerItem] decimal NOT NULL, + [Total] decimal NULL, + [VendorCode] nvarchar(100) NOT NULL, + [VendorName] nvarchar(100) NOT NULL, + [AccountCode] nvarchar(100) NOT NULL, + [FiscalYearCode] nvarchar(100) NOT NULL, + [FiscalMonthCode] nvarchar(100) NOT NULL, + [DepartmentCode] nvarchar(100) NOT NULL, + [PONumber] nvarchar(100) NOT NULL, + [ItemNumber] nvarchar(100) NOT NULL, + [CustomText1] nvarchar(100) NOT NULL, + [CustomText2] nvarchar(100) NOT NULL, + [CustomText3] nvarchar(100) NOT NULL, + [CustomText4] nvarchar(100) NOT NULL, + [CustomText5] nvarchar(100) NOT NULL, + [CustomDate1] datetime NOT NULL, + [CustomDate2] datetime NOT NULL, + [CustomNumeric1] decimal NOT NULL, + [CustomNumeric2] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [IsSampled] bit NOT NULL, + [SampleDate] datetime NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [CNU_BASE] ON [int].[FactMRImportPODetail] ([FiscalMonthID], [IsDeleted], [FiscalYearID], [DepartmentID], [AccountID]); +CREATE NONCLUSTERED INDEX [NCNU_SampleView] ON [int].[FactMRImportPODetail] ([FiscalMonthID], [IsDeleted], [FiscalYearID], [DepartmentID], [AccountID]); +GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [FK__FactMRImp__Accou__710E3793] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [FK__FactMRImp__Depar__72F68005] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [FK__FactMRImp__Fisca__74DEC877] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [FK__FactMRImp__Fisca__76C710E9] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Fisca__00507B23] DEFAULT ('') FOR [FiscalMonthCode]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Depar__01449F5C] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__PONum__0238C395] DEFAULT ('') FOR [PONumber]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__ItemN__032CE7CE] DEFAULT ('') FOR [ItemNumber]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Custo__04210C07] DEFAULT ('') FOR [CustomText1]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Custo__05153040] DEFAULT ('') FOR [CustomText2]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Custo__06095479] DEFAULT ('') FOR [CustomText3]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Custo__06FD78B2] DEFAULT ('') FOR [CustomText4]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Custo__07F19CEB] DEFAULT ('') FOR [CustomText5]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Custo__08E5C124] DEFAULT (getdate()) FOR [CustomDate1]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Custo__09D9E55D] DEFAULT (getdate()) FOR [CustomDate2]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Depar__72025BCC] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Custo__0ACE0996] DEFAULT ((0)) FOR [CustomNumeric1]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Custo__0BC22DCF] DEFAULT ((0)) FOR [CustomNumeric2]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__IsDel__0CB65208] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Trans__0E9E9A7A] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__IsSam__3E4DAD9C] DEFAULT ((0)) FOR [IsSampled]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Sampl__3F41D1D5] DEFAULT (getdate()) FOR [SampleDate]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Accou__701A135A] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Fisca__73EAA43E] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Fisca__75D2ECB0] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__LineN__77BB3522] DEFAULT ('') FOR [LineNumber]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__LineD__78AF595B] DEFAULT ('') FOR [LineDescription]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Histo__0DAA7641] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Clien__79A37D94] DEFAULT (getdate()) FOR [ClientDate]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Quant__7A97A1CD] DEFAULT ((0)) FOR [Quantity]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__CostP__7B8BC606] DEFAULT ((0)) FOR [CostPerItem]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Vendo__7C7FEA3F] DEFAULT ('') FOR [VendorCode]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Vendo__7D740E78] DEFAULT ('') FOR [VendorName]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Accou__7E6832B1] DEFAULT ('') FOR [AccountCode]; GO +ALTER TABLE [int].[FactMRImportPODetail] ADD CONSTRAINT [DF__FactMRImp__Fisca__7F5C56EA] DEFAULT ('') FOR [FiscalYearCode]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactMeditechPatientADT ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactMeditechPatientADT] ( + [RowID] bigint NOT NULL, + [EncounterRecordNumber] nvarchar(100) NOT NULL, + [PatientClass] nvarchar(100) NOT NULL, + [EventTypeCode] nvarchar(100) NOT NULL, + [EventTypeCodeDescription] nvarchar(100) NOT NULL, + [DepartmentCode] nvarchar(100) NOT NULL, + [DepartmentDescription] nvarchar(100) NOT NULL, + [RoomNumber] nvarchar(100) NOT NULL, + [BedNumber] nvarchar(100) NOT NULL, + [EffectiveDateTimeStamp] datetime NOT NULL, + [EventDate] datetime NOT NULL, + [EventSequenceNumber] int NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [int].[FactMeditechPatientADT] ADD CONSTRAINT [DF__FactMedit__Encou__1B9B36B4] DEFAULT ('') FOR [EncounterRecordNumber]; GO +ALTER TABLE [int].[FactMeditechPatientADT] ADD CONSTRAINT [DF__FactMedit__Patie__1C8F5AED] DEFAULT ('') FOR [PatientClass]; GO +ALTER TABLE [int].[FactMeditechPatientADT] ADD CONSTRAINT [DF__FactMedit__Event__1D837F26] DEFAULT ('') FOR [EventTypeCode]; GO +ALTER TABLE [int].[FactMeditechPatientADT] ADD CONSTRAINT [DF__FactMedit__Event__1E77A35F] DEFAULT ('') FOR [EventTypeCodeDescription]; GO +ALTER TABLE [int].[FactMeditechPatientADT] ADD CONSTRAINT [DF__FactMedit__Depar__1F6BC798] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactMeditechPatientADT] ADD CONSTRAINT [DF__FactMedit__Depar__205FEBD1] DEFAULT ('') FOR [DepartmentDescription]; GO +ALTER TABLE [int].[FactMeditechPatientADT] ADD CONSTRAINT [DF__FactMedit__RoomN__2154100A] DEFAULT ('') FOR [RoomNumber]; GO +ALTER TABLE [int].[FactMeditechPatientADT] ADD CONSTRAINT [DF__FactMedit__BedNu__22483443] DEFAULT ('') FOR [BedNumber]; GO +ALTER TABLE [int].[FactMeditechPatientADT] ADD CONSTRAINT [DF__FactMedit__Effec__233C587C] DEFAULT (getdate()) FOR [EffectiveDateTimeStamp]; GO +ALTER TABLE [int].[FactMeditechPatientADT] ADD CONSTRAINT [DF__FactMedit__Event__24307CB5] DEFAULT (getdate()) FOR [EventDate]; GO +ALTER TABLE [int].[FactMeditechPatientADT] ADD CONSTRAINT [DF__FactMedit__Event__2524A0EE] DEFAULT ((0)) FOR [EventSequenceNumber]; GO +ALTER TABLE [int].[FactMeditechPatientADT] ADD CONSTRAINT [DF__FactMedit__IsDel__2618C527] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactMeditechPatientADT] ADD CONSTRAINT [DF__FactMedit__Trans__28010D99] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactMeditechPatientADT] ADD CONSTRAINT [DF__FactMedit__Histo__270CE960] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactOBImportPayor ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactOBImportPayor] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [PayorID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [OBForecastDetailID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [DepartmentCode] nvarchar(2000) NOT NULL, + [PayorCode] nvarchar(2000) NOT NULL, + [FiscalYearCode] nvarchar(2000) NOT NULL, + [FiscalMonthCode] nvarchar(2000) NOT NULL, + [OBForecastDetailCode] nvarchar(2000) NOT NULL, + [TimeClassCode] nvarchar(2000) NOT NULL, + [Value] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [PatientClassID] int NOT NULL, + [EntityID] int NOT NULL, + [PatientClassCode] nvarchar(2000) NOT NULL, + [EntityCode] nvarchar(2000) NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [int].[FactOBImportPayor] ADD CONSTRAINT [DF__FactOBImp__Histo__2BA1C020] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactOBImportPayor] ADD CONSTRAINT [DF__FactOBImp__Fisca__221855E6] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactOBImportPayor] ADD CONSTRAINT [DF__FactOBImp__Fisca__230C7A1F] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactOBImportPayor] ADD CONSTRAINT [DF__FactOBImp__Depar__24009E58] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactOBImportPayor] ADD CONSTRAINT [DF__FactOBImp__Payor__24F4C291] DEFAULT ('') FOR [PayorCode]; GO +ALTER TABLE [int].[FactOBImportPayor] ADD CONSTRAINT [DF__FactOBImp__Fisca__25E8E6CA] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactOBImportPayor] ADD CONSTRAINT [DF__FactOBImp__Fisca__26DD0B03] DEFAULT ('') FOR [FiscalMonthCode]; GO +ALTER TABLE [int].[FactOBImportPayor] ADD CONSTRAINT [DF__FactOBImp__OBFor__27D12F3C] DEFAULT ('') FOR [OBForecastDetailCode]; GO +ALTER TABLE [int].[FactOBImportPayor] ADD CONSTRAINT [DF__FactOBImp__TimeC__28C55375] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactOBImportPayor] ADD CONSTRAINT [DF__FactOBImp__Value__29B977AE] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [int].[FactOBImportPayor] ADD CONSTRAINT [DF__FactOBImp__IsDel__2AAD9BE7] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactOBImportPayor] ADD CONSTRAINT [DF__FactOBImp__Trans__2C95E459] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactOBImportPayor] ADD CONSTRAINT [DF__FactOBImp__Entit__4EEAFC5D] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [int].[FactOBImportPayor] ADD CONSTRAINT [DF__FactOBImp__Patie__4DF6D824] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [int].[FactOBImportPayor] ADD CONSTRAINT [DF__FactOBImp__Patie__4FDF2096] DEFAULT ('') FOR [PatientClassCode]; GO +ALTER TABLE [int].[FactOBImportPayor] ADD CONSTRAINT [DF__FactOBImp__Entit__50D344CF] DEFAULT ('') FOR [EntityCode]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactOBImportPayorGroup ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactOBImportPayorGroup] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [OBForecastDetailID] int NOT NULL, + [DepartmentCode] nvarchar(2000) NOT NULL, + [PayorGroupCode] nvarchar(2000) NOT NULL, + [FiscalMonthCode] nvarchar(2000) NOT NULL, + [FiscalYearCode] nvarchar(2000) NOT NULL, + [TimeClassCode] nvarchar(2000) NOT NULL, + [OBForecastDetailCode] nvarchar(2000) NOT NULL, + [Value] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [PatientClassID] int NOT NULL, + [EntityID] int NOT NULL, + [PatientClassCode] nvarchar(2000) NOT NULL, + [EntityCode] nvarchar(2000) NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [int].[FactOBImportPayorGroup] ADD CONSTRAINT [DF__FactOBImp__Fisca__409CDD06] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactOBImportPayorGroup] ADD CONSTRAINT [DF__FactOBImp__Fisca__4191013F] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactOBImportPayorGroup] ADD CONSTRAINT [DF__FactOBImp__Depar__42852578] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactOBImportPayorGroup] ADD CONSTRAINT [DF__FactOBImp__Payor__437949B1] DEFAULT ('') FOR [PayorGroupCode]; GO +ALTER TABLE [int].[FactOBImportPayorGroup] ADD CONSTRAINT [DF__FactOBImp__Fisca__446D6DEA] DEFAULT ('') FOR [FiscalMonthCode]; GO +ALTER TABLE [int].[FactOBImportPayorGroup] ADD CONSTRAINT [DF__FactOBImp__Fisca__45619223] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactOBImportPayorGroup] ADD CONSTRAINT [DF__FactOBImp__TimeC__4655B65C] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactOBImportPayorGroup] ADD CONSTRAINT [DF__FactOBImp__OBFor__4749DA95] DEFAULT ('') FOR [OBForecastDetailCode]; GO +ALTER TABLE [int].[FactOBImportPayorGroup] ADD CONSTRAINT [DF__FactOBImp__Value__483DFECE] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [int].[FactOBImportPayorGroup] ADD CONSTRAINT [DF__FactOBImp__IsDel__49322307] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactOBImportPayorGroup] ADD CONSTRAINT [DF__FactOBImp__Trans__4B1A6B79] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactOBImportPayorGroup] ADD CONSTRAINT [DF__FactOBImp__Patie__51C76908] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [int].[FactOBImportPayorGroup] ADD CONSTRAINT [DF__FactOBImp__Patie__53AFB17A] DEFAULT ('') FOR [PatientClassCode]; GO +ALTER TABLE [int].[FactOBImportPayorGroup] ADD CONSTRAINT [DF__FactOBImp__Entit__54A3D5B3] DEFAULT ('') FOR [EntityCode]; GO +ALTER TABLE [int].[FactOBImportPayorGroup] ADD CONSTRAINT [DF__FactOBImp__Entit__52BB8D41] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [int].[FactOBImportPayorGroup] ADD CONSTRAINT [DF__FactOBImp__Histo__4A264740] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactOBPayor ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactOBPayor] ( + [RowID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] nvarchar(2000) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] nvarchar(2000) NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalMonthCode] nvarchar(2000) NOT NULL, + [OBReimbursementPlanID] int NOT NULL, + [ReimbursementPlan] nvarchar(2000) NOT NULL, + [CareSettingID] int NOT NULL, + [CareSettingCode] nvarchar(2000) NOT NULL, + [PatientClassID] int NOT NULL, + [PatientClassCode] nvarchar(2000) NOT NULL, + [PayorID] int NOT NULL, + [PayorCode] nvarchar(2000) NOT NULL, + [OBForecastDetailID] int NOT NULL, + [OBForecastDetailCode] nvarchar(2000) NOT NULL, + [Value] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [CNU_BASE] ON [int].[FactOBPayor] ([FiscalMonthID], [IsDeleted], [TimeClassID], [FiscalYearID], [PayorID], [OBReimbursementPlanID], [PatientClassID], [OBForecastDetailID], [RowID]); +CREATE NONCLUSTERED INDEX [NCNU_SampleViews] ON [int].[FactOBPayor] ([FiscalMonthID], [IsDeleted], [TimeClassID], [FiscalYearID], [PayorID], [OBReimbursementPlanID], [PatientClassID], [OBForecastDetailID]); +GO +ALTER TABLE [int].[FactOBPayor] ADD CONSTRAINT [DF__FactOBPay__Histo__7877ED2C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactOBPayor] ADD CONSTRAINT [DF__FactOBPay__TimeC__759B8081] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactOBPayor] ADD CONSTRAINT [DF__FactOBPay__Fisca__6D063A80] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactOBPayor] ADD CONSTRAINT [DF__FactOBPay__Fisca__72BF13D6] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactOBPayor] ADD CONSTRAINT [DF__FactOBPay__Fisca__6C121647] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactOBPayor] ADD CONSTRAINT [DF__FactOBPay__Fisca__71CAEF9D] DEFAULT ('') FOR [FiscalMonthCode]; GO +ALTER TABLE [int].[FactOBPayor] ADD CONSTRAINT [DF__FactOBPay__Reimb__70D6CB64] DEFAULT ('') FOR [ReimbursementPlan]; GO +ALTER TABLE [int].[FactOBPayor] ADD CONSTRAINT [DF__FactOBPay__CareS__217A02BF] DEFAULT ((0)) FOR [CareSettingID]; GO +ALTER TABLE [int].[FactOBPayor] ADD CONSTRAINT [DF__FactOBPay__CareS__226E26F8] DEFAULT ('') FOR [CareSettingCode]; GO +ALTER TABLE [int].[FactOBPayor] ADD CONSTRAINT [DF__FactOBPay__Patie__6DFA5EB9] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [int].[FactOBPayor] ADD CONSTRAINT [DF__FactOBPay__Patie__73B3380F] DEFAULT ('') FOR [PatientClassCode]; GO +ALTER TABLE [int].[FactOBPayor] ADD CONSTRAINT [DF__FactOBPay__Payor__74A75C48] DEFAULT ('') FOR [PayorCode]; GO +ALTER TABLE [int].[FactOBPayor] ADD CONSTRAINT [DF__FactOBPay__OBFor__6EEE82F2] DEFAULT ((0)) FOR [OBForecastDetailID]; GO +ALTER TABLE [int].[FactOBPayor] ADD CONSTRAINT [DF__FactOBPay__OBFor__6FE2A72B] DEFAULT ('') FOR [OBForecastDetailCode]; GO +ALTER TABLE [int].[FactOBPayor] ADD CONSTRAINT [DF__FactOBPay__Value__768FA4BA] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [int].[FactOBPayor] ADD CONSTRAINT [DF__FactOBPay__IsDel__7783C8F3] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactOBPayor] ADD CONSTRAINT [DF__FactOBPay__Trans__796C1165] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactOBPayorGroup ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactOBPayorGroup] ( + [RowID] int NOT NULL, + [OBForecastDetailID] int NOT NULL, + [OBReimbursementPlanID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [PatientClassID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [OBForecastDetailCode] nvarchar(2000) NOT NULL, + [ReimbursementPlan] nvarchar(2000) NOT NULL, + [FiscalMonthCode] nvarchar(2000) NOT NULL, + [FiscalYearCode] nvarchar(2000) NOT NULL, + [TimeClassCode] nvarchar(2000) NOT NULL, + [PatientClassCode] nvarchar(2000) NOT NULL, + [PayorGroupCode] nvarchar(2000) NOT NULL, + [Value] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [CareSettingID] int NOT NULL, + [CareSettingCode] nvarchar(2000) NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [CNU_BASE] ON [int].[FactOBPayorGroup] ([FiscalMonthID], [IsDeleted], [TimeClassID], [FiscalYearID], [PayorGroupID], [OBReimbursementPlanID], [PatientClassID], [OBForecastDetailID], [RowID]); +CREATE NONCLUSTERED INDEX [NCNU_SampleViews] ON [int].[FactOBPayorGroup] ([FiscalMonthID], [IsDeleted], [TimeClassID], [FiscalYearID], [PayorGroupID], [OBReimbursementPlanID], [PatientClassID], [OBForecastDetailID]); +GO +ALTER TABLE [int].[FactOBPayorGroup] ADD CONSTRAINT [DF__FactOBPay__Fisca__0C7EE5D9] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactOBPayorGroup] ADD CONSTRAINT [DF__FactOBPay__Fisca__0D730A12] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactOBPayorGroup] ADD CONSTRAINT [DF__FactOBPay__Patie__0E672E4B] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [int].[FactOBPayorGroup] ADD CONSTRAINT [DF__FactOBPay__OBFor__0F5B5284] DEFAULT ('') FOR [OBForecastDetailCode]; GO +ALTER TABLE [int].[FactOBPayorGroup] ADD CONSTRAINT [DF__FactOBPay__Reimb__104F76BD] DEFAULT ('') FOR [ReimbursementPlan]; GO +ALTER TABLE [int].[FactOBPayorGroup] ADD CONSTRAINT [DF__FactOBPay__Fisca__11439AF6] DEFAULT ('') FOR [FiscalMonthCode]; GO +ALTER TABLE [int].[FactOBPayorGroup] ADD CONSTRAINT [DF__FactOBPay__Fisca__1237BF2F] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactOBPayorGroup] ADD CONSTRAINT [DF__FactOBPay__TimeC__132BE368] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactOBPayorGroup] ADD CONSTRAINT [DF__FactOBPay__Patie__142007A1] DEFAULT ('') FOR [PatientClassCode]; GO +ALTER TABLE [int].[FactOBPayorGroup] ADD CONSTRAINT [DF__FactOBPay__Payor__15142BDA] DEFAULT ('') FOR [PayorGroupCode]; GO +ALTER TABLE [int].[FactOBPayorGroup] ADD CONSTRAINT [DF__FactOBPay__Value__16085013] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [int].[FactOBPayorGroup] ADD CONSTRAINT [DF__FactOBPay__IsDel__16FC744C] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactOBPayorGroup] ADD CONSTRAINT [DF__FactOBPay__Trans__18E4BCBE] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactOBPayorGroup] ADD CONSTRAINT [DF__FactOBPay__CareS__1F91BA4D] DEFAULT ((0)) FOR [CareSettingID]; GO +ALTER TABLE [int].[FactOBPayorGroup] ADD CONSTRAINT [DF__FactOBPay__CareS__2085DE86] DEFAULT ('') FOR [CareSettingCode]; GO +ALTER TABLE [int].[FactOBPayorGroup] ADD CONSTRAINT [DF_FactOBPayorGroup_OBForecastDetailID] DEFAULT ((0)) FOR [OBForecastDetailID]; GO +ALTER TABLE [int].[FactOBPayorGroup] ADD CONSTRAINT [DF_FactOBPayorGroup_OBReimbursementPlanID] DEFAULT ((0)) FOR [OBReimbursementPlanID]; GO +ALTER TABLE [int].[FactOBPayorGroup] ADD CONSTRAINT [DF__FactOBPay__Histo__17F09885] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactPayorSummary ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactPayorSummary] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [DepartmentCode] varchar(100) NOT NULL, + [PatientTypeRollupID] tinyint NOT NULL, + [PatientTypeRollupCode] varchar(50) NOT NULL, + [AccountRollupID] int NOT NULL, + [AccountRollupCode] varchar(50) NOT NULL, + [PayorGroupID] int NOT NULL, + [PayorGroupCode] varchar(50) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] varchar(20) NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] varchar(20) NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [UnitType] varchar(20) NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalMonthCode] varchar(20) NOT NULL, + [Value] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [int].[FactPayorSummary] ([FiscalMonthID], [IsDeleted], [FiscalYearID], [TimeClassID], [DepartmentID], [PatientTypeRollupID], [AccountRollupID], [PayorGroupID], [UnitTypeID], [RowID]); +GO +ALTER TABLE [int].[FactPayorSummary] ADD CONSTRAINT [DF__FactPayor__Depar__5A2A6EA7] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactPayorSummary] ADD CONSTRAINT [DF__FactPayor__Patie__5B1E92E0] DEFAULT ((0)) FOR [PatientTypeRollupID]; GO +ALTER TABLE [int].[FactPayorSummary] ADD CONSTRAINT [DF__FactPayor__Patie__5C12B719] DEFAULT ('') FOR [PatientTypeRollupCode]; GO +ALTER TABLE [int].[FactPayorSummary] ADD CONSTRAINT [DF__FactPayor__Accou__5D06DB52] DEFAULT ((0)) FOR [AccountRollupID]; GO +ALTER TABLE [int].[FactPayorSummary] ADD CONSTRAINT [DF__FactPayor__Accou__5DFAFF8B] DEFAULT ('') FOR [AccountRollupCode]; GO +ALTER TABLE [int].[FactPayorSummary] ADD CONSTRAINT [DF__FactPayor__Payor__5EEF23C4] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [int].[FactPayorSummary] ADD CONSTRAINT [DF__FactPayor__Payor__5FE347FD] DEFAULT ('') FOR [PayorGroupCode]; GO +ALTER TABLE [int].[FactPayorSummary] ADD CONSTRAINT [DF__FactPayor__Fisca__60D76C36] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactPayorSummary] ADD CONSTRAINT [DF__FactPayor__Fisca__61CB906F] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactPayorSummary] ADD CONSTRAINT [DF__FactPayor__TimeC__62BFB4A8] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactPayorSummary] ADD CONSTRAINT [DF__FactPayor__TimeC__63B3D8E1] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactPayorSummary] ADD CONSTRAINT [DF__FactPayor__UnitT__64A7FD1A] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [int].[FactPayorSummary] ADD CONSTRAINT [DF__FactPayor__UnitT__659C2153] DEFAULT ('') FOR [UnitType]; GO +ALTER TABLE [int].[FactPayorSummary] ADD CONSTRAINT [DF__FactPayor__Fisca__315A67AC] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactPayorSummary] ADD CONSTRAINT [DF__FactPayor__Fisca__409CAB3C] DEFAULT ('') FOR [FiscalMonthCode]; GO +ALTER TABLE [int].[FactPayorSummary] ADD CONSTRAINT [DF_INTFACTPAYORSUMMARYVALUE] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [int].[FactPayorSummary] ADD CONSTRAINT [DF__FactPayor__IsDel__4190CF75] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactPayorSummary] ADD CONSTRAINT [DF__FactPayor__Histo__72F61C71] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactPayorSummary] ADD CONSTRAINT [DF__FactPayor__Depar__0ECD49EC] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [int].[FactPayorSummary] ADD CONSTRAINT [DF__INT_FactPayorSummary_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactPhysicianSummary ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactPhysicianSummary] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [DepartmentCode] varchar(100) NOT NULL, + [PatientTypeRollupID] tinyint NOT NULL, + [PatientTypeRollupCode] varchar(50) NOT NULL, + [AccountRollupID] int NOT NULL, + [AccountRollupCode] varchar(50) NOT NULL, + [PhysicianGroupID] int NOT NULL, + [PhysicianGroupCode] varchar(50) NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [UnitType] varchar(20) NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] varchar(20) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] varchar(20) NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalMonthCode] varchar(20) NOT NULL, + [Value] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [int].[FactPhysicianSummary] ([FiscalMonthID], [IsDeleted], [FiscalYearID], [TimeClassID], [DepartmentID], [PatientTypeRollupID], [AccountRollupID], [PhysicianGroupID], [UnitTypeID], [RowID]); +GO +ALTER TABLE [int].[FactPhysicianSummary] ADD CONSTRAINT [DF__FactPhysi__Depar__6587DE11] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactPhysicianSummary] ADD CONSTRAINT [DF__FactPhysi__Patie__667C024A] DEFAULT ((0)) FOR [PatientTypeRollupID]; GO +ALTER TABLE [int].[FactPhysicianSummary] ADD CONSTRAINT [DF__FactPhysi__Patie__67702683] DEFAULT ('') FOR [PatientTypeRollupCode]; GO +ALTER TABLE [int].[FactPhysicianSummary] ADD CONSTRAINT [DF__FactPhysi__Accou__68644ABC] DEFAULT ((0)) FOR [AccountRollupID]; GO +ALTER TABLE [int].[FactPhysicianSummary] ADD CONSTRAINT [DF__FactPhysi__Accou__69586EF5] DEFAULT ('') FOR [AccountRollupCode]; GO +ALTER TABLE [int].[FactPhysicianSummary] ADD CONSTRAINT [DF__FactPhysi__Physi__6A4C932E] DEFAULT ((0)) FOR [PhysicianGroupID]; GO +ALTER TABLE [int].[FactPhysicianSummary] ADD CONSTRAINT [DF__FactPhysi__Physi__6B40B767] DEFAULT ('') FOR [PhysicianGroupCode]; GO +ALTER TABLE [int].[FactPhysicianSummary] ADD CONSTRAINT [DF__FactPhysi__UnitT__70056C84] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [int].[FactPhysicianSummary] ADD CONSTRAINT [DF__FactPhysi__UnitT__70F990BD] DEFAULT ('') FOR [UnitType]; GO +ALTER TABLE [int].[FactPhysicianSummary] ADD CONSTRAINT [DF__FactPhysi__TimeC__6E1D2412] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactPhysicianSummary] ADD CONSTRAINT [DF__FactPhysi__TimeC__6F11484B] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactPhysicianSummary] ADD CONSTRAINT [DF__FactPhysi__Fisca__6C34DBA0] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactPhysicianSummary] ADD CONSTRAINT [DF__FactPhysi__Fisca__6D28FFD9] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactPhysicianSummary] ADD CONSTRAINT [DF__FactPhysi__Fisca__352AF890] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactPhysicianSummary] ADD CONSTRAINT [DF__FactPhysi__Fisca__4284F3AE] DEFAULT ('') FOR [FiscalMonthCode]; GO +ALTER TABLE [int].[FactPhysicianSummary] ADD CONSTRAINT [DF_INTFACTPHYSICIANSUMMARYVALUE] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [int].[FactPhysicianSummary] ADD CONSTRAINT [DF__FactPhysi__IsDel__437917E7] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactPhysicianSummary] ADD CONSTRAINT [DF__FactPhysi__Histo__7E538BDB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactPhysicianSummary] ADD CONSTRAINT [DF__INT_FactPhysicianSummary_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactPhysicianSummary] ADD CONSTRAINT [DF__FactPhysi__Depar__6493B9D8] DEFAULT ((0)) FOR [DepartmentID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactProvider ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactProvider] ( + [RowID] int NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [PhysicianID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [ProviderLineItemID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [DepartmentID] int NOT NULL, + [DepartmentCode] nvarchar(2000) NOT NULL, + [FiscalMonthCode] nvarchar(2000) NOT NULL, + [FiscalYearCode] nvarchar(2000) NOT NULL, + [ProviderCode] nvarchar(2000) NOT NULL, + [TimeClassCode] nvarchar(2000) NOT NULL, + [UnitTypeName] nvarchar(2000) NOT NULL, + [Value] decimal NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [FK__FactProvi__Depar__4CB63923] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [FK__FactProvi__Fisca__03857E79] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [FK__FactProvi__Fisca__0479A2B2] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [FK__FactProvi__Provi__056DC6EB] FOREIGN KEY ([ProviderLineItemID]) REFERENCES [fp].[ProviderLineItem] ([ProviderLineItemID]); GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [FK__FactProvi__Provi__4E9E8195] FOREIGN KEY ([PhysicianID]) REFERENCES [dss].[DimPhysician] ([PhysicianID]); GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [FK__FactProvi__TimeC__07560F5D] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [FK__FactProvi__UnitT__084A3396] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [DF__FactProvi__UnitT__00A911CE] DEFAULT ('') FOR [UnitTypeName]; GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [DF__FactProvi__Value__019D3607] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [DF__FactProvi__IsDel__725AF277] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [DF__FactProvi__Trans__74433AE9] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [DF__FactProvi__Histo__734F16B0] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [DF__FactProvi__TimeC__75375F22] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [DF__FactProvi__Physi__762B835B] DEFAULT ((0)) FOR [PhysicianID]; GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [DF__FactProvi__Fisca__771FA794] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [DF__FactProvi__Fisca__7813CBCD] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [DF__FactProvi__Provi__7907F006] DEFAULT ((0)) FOR [ProviderLineItemID]; GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [DF__FactProvi__UnitT__79FC143F] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [DF__FactProvi__Depar__7AF03878] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [DF__FactProvi__Depar__7BE45CB1] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [DF__FactProvi__Fisca__7CD880EA] DEFAULT ('') FOR [FiscalMonthCode]; GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [DF__FactProvi__Fisca__7DCCA523] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [DF__FactProvi__Provi__7EC0C95C] DEFAULT ('') FOR [ProviderCode]; GO +ALTER TABLE [int].[FactProvider] ADD CONSTRAINT [DF__FactProvi__TimeC__7FB4ED95] DEFAULT ('') FOR [TimeClassCode]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactSPDirectBalAccount ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactSPDirectBalAccount] ( + [RowID] int NOT NULL, + [SPLongRangePlanID] int NOT NULL, + [SPLongRangePlanName] varchar(200) NOT NULL, + [AccountRollupID] int NOT NULL, + [SPAccountRollupName] varchar(200) NOT NULL, + [SPCapitalRollupID] int NOT NULL, + [SPCapitalRollupName] varchar(200) NOT NULL, + [SPDebtIssuanceID] int NOT NULL, + [SPDebtIssuanceName] varchar(400) NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [UnitType] varchar(20) NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] varchar(20) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] varchar(20) NOT NULL, + [Amount] decimal NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [int].[FactSPDirectBalAccount] ADD CONSTRAINT [DF__FactSPDir__SPLon__250E31A0] DEFAULT ((0)) FOR [SPLongRangePlanID]; GO +ALTER TABLE [int].[FactSPDirectBalAccount] ADD CONSTRAINT [DF__FactSPDir__SPLon__260255D9] DEFAULT ('') FOR [SPLongRangePlanName]; GO +ALTER TABLE [int].[FactSPDirectBalAccount] ADD CONSTRAINT [DF__FactSPDir__SPAcc__26F67A12] DEFAULT ((0)) FOR [AccountRollupID]; GO +ALTER TABLE [int].[FactSPDirectBalAccount] ADD CONSTRAINT [DF__FactSPDir__SPAcc__27EA9E4B] DEFAULT ('') FOR [SPAccountRollupName]; GO +ALTER TABLE [int].[FactSPDirectBalAccount] ADD CONSTRAINT [DF__FactSPDir__SPCap__28DEC284] DEFAULT ((0)) FOR [SPCapitalRollupID]; GO +ALTER TABLE [int].[FactSPDirectBalAccount] ADD CONSTRAINT [DF__FactSPDir__SPCap__29D2E6BD] DEFAULT ('') FOR [SPCapitalRollupName]; GO +ALTER TABLE [int].[FactSPDirectBalAccount] ADD CONSTRAINT [DF__FactSPDir__SPDeb__2AC70AF6] DEFAULT ((0)) FOR [SPDebtIssuanceID]; GO +ALTER TABLE [int].[FactSPDirectBalAccount] ADD CONSTRAINT [DF__FactSPDir__SPDeb__2BBB2F2F] DEFAULT ('') FOR [SPDebtIssuanceName]; GO +ALTER TABLE [int].[FactSPDirectBalAccount] ADD CONSTRAINT [DF__FactSPDir__UnitT__2CAF5368] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [int].[FactSPDirectBalAccount] ADD CONSTRAINT [DF__FactSPDir__UnitT__2DA377A1] DEFAULT ('') FOR [UnitType]; GO +ALTER TABLE [int].[FactSPDirectBalAccount] ADD CONSTRAINT [DF__FactSPDir__TimeC__2E979BDA] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactSPDirectBalAccount] ADD CONSTRAINT [DF__FactSPDir__TimeC__2F8BC013] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactSPDirectBalAccount] ADD CONSTRAINT [DF__FactSPDir__Fisca__307FE44C] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactSPDirectBalAccount] ADD CONSTRAINT [DF__FactSPDir__Fisca__31740885] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactSPDirectBalAccount] ADD CONSTRAINT [DF__FactSPDir__Amoun__32682CBE] DEFAULT ((0.0)) FOR [Amount]; GO +ALTER TABLE [int].[FactSPDirectBalAccount] ADD CONSTRAINT [DF__FactSPDir__Histo__335C50F7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactSPDirectBalAccount] ADD CONSTRAINT [DF__INT_FactSPDirectBalAccount_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactSPDirectISAccount ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactSPDirectISAccount] ( + [RowID] int NOT NULL, + [SPLongRangePlanID] int NOT NULL, + [SPLongRangePlanName] varchar(200) NOT NULL, + [AccountRollupID] int NOT NULL, + [SPAccountRollupName] varchar(200) NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [UnitType] varchar(20) NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] varchar(20) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] varchar(20) NOT NULL, + [Amount] decimal NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [int].[FactSPDirectISAccount] ADD CONSTRAINT [DF__FactSPDir__SPLon__38210614] DEFAULT ((0)) FOR [SPLongRangePlanID]; GO +ALTER TABLE [int].[FactSPDirectISAccount] ADD CONSTRAINT [DF__FactSPDir__SPLon__39152A4D] DEFAULT ('') FOR [SPLongRangePlanName]; GO +ALTER TABLE [int].[FactSPDirectISAccount] ADD CONSTRAINT [DF__FactSPDir__SPAcc__3A094E86] DEFAULT ((0)) FOR [AccountRollupID]; GO +ALTER TABLE [int].[FactSPDirectISAccount] ADD CONSTRAINT [DF__FactSPDir__SPAcc__3AFD72BF] DEFAULT ('') FOR [SPAccountRollupName]; GO +ALTER TABLE [int].[FactSPDirectISAccount] ADD CONSTRAINT [DF__FactSPDir__UnitT__3BF196F8] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [int].[FactSPDirectISAccount] ADD CONSTRAINT [DF__FactSPDir__UnitT__3CE5BB31] DEFAULT ('') FOR [UnitType]; GO +ALTER TABLE [int].[FactSPDirectISAccount] ADD CONSTRAINT [DF__FactSPDir__TimeC__3DD9DF6A] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactSPDirectISAccount] ADD CONSTRAINT [DF__FactSPDir__TimeC__3ECE03A3] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactSPDirectISAccount] ADD CONSTRAINT [DF__FactSPDir__Fisca__3FC227DC] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactSPDirectISAccount] ADD CONSTRAINT [DF__FactSPDir__Fisca__40B64C15] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactSPDirectISAccount] ADD CONSTRAINT [DF__FactSPDir__Amoun__41AA704E] DEFAULT ((0.0)) FOR [Amount]; GO +ALTER TABLE [int].[FactSPDirectISAccount] ADD CONSTRAINT [DF__FactSPDir__Histo__429E9487] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactSPDirectISAccount] ADD CONSTRAINT [DF__INT_FactSPDirectISAccount_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactSPDirectISPayor ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactSPDirectISPayor] ( + [RowID] int NOT NULL, + [SPLongRangePlanID] int NOT NULL, + [SPLongRangePlanName] varchar(200) NOT NULL, + [AccountRollupID] int NOT NULL, + [SPAccountRollupName] varchar(200) NOT NULL, + [PatientTypeRollupID] tinyint NOT NULL, + [PatientTypeRollupCode] varchar(200) NOT NULL, + [PayorGroupID] int NOT NULL, + [PayorGroupCode] varchar(200) NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [UnitType] varchar(20) NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] varchar(20) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] varchar(20) NOT NULL, + [Amount] decimal NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [int].[FactSPDirectISPayor] ADD CONSTRAINT [DF__INT_FactSPDirectISPayor_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactSPDirectISPayor] ADD CONSTRAINT [DF__FactSPDir__SPLon__476349A4] DEFAULT ((0)) FOR [SPLongRangePlanID]; GO +ALTER TABLE [int].[FactSPDirectISPayor] ADD CONSTRAINT [DF__FactSPDir__SPLon__48576DDD] DEFAULT ('') FOR [SPLongRangePlanName]; GO +ALTER TABLE [int].[FactSPDirectISPayor] ADD CONSTRAINT [DF__FactSPDir__SPAcc__494B9216] DEFAULT ((0)) FOR [AccountRollupID]; GO +ALTER TABLE [int].[FactSPDirectISPayor] ADD CONSTRAINT [DF__FactSPDir__SPAcc__4A3FB64F] DEFAULT ('') FOR [SPAccountRollupName]; GO +ALTER TABLE [int].[FactSPDirectISPayor] ADD CONSTRAINT [DF__FactSPDir__Patie__4B33DA88] DEFAULT ((0)) FOR [PatientTypeRollupID]; GO +ALTER TABLE [int].[FactSPDirectISPayor] ADD CONSTRAINT [DF__FactSPDir__Patie__4C27FEC1] DEFAULT ('') FOR [PatientTypeRollupCode]; GO +ALTER TABLE [int].[FactSPDirectISPayor] ADD CONSTRAINT [DF__FactSPDir__Payor__4D1C22FA] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [int].[FactSPDirectISPayor] ADD CONSTRAINT [DF__FactSPDir__Payor__4E104733] DEFAULT ('') FOR [PayorGroupCode]; GO +ALTER TABLE [int].[FactSPDirectISPayor] ADD CONSTRAINT [DF__FactSPDir__UnitT__4F046B6C] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [int].[FactSPDirectISPayor] ADD CONSTRAINT [DF__FactSPDir__UnitT__4FF88FA5] DEFAULT ('') FOR [UnitType]; GO +ALTER TABLE [int].[FactSPDirectISPayor] ADD CONSTRAINT [DF__FactSPDir__TimeC__50ECB3DE] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactSPDirectISPayor] ADD CONSTRAINT [DF__FactSPDir__TimeC__51E0D817] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactSPDirectISPayor] ADD CONSTRAINT [DF__FactSPDir__Fisca__52D4FC50] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactSPDirectISPayor] ADD CONSTRAINT [DF__FactSPDir__Fisca__53C92089] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactSPDirectISPayor] ADD CONSTRAINT [DF__FactSPDir__Amoun__54BD44C2] DEFAULT ((0.0)) FOR [Amount]; GO +ALTER TABLE [int].[FactSPDirectISPayor] ADD CONSTRAINT [DF__FactSPDir__Histo__55B168FB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactSPDirectISPhysician ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactSPDirectISPhysician] ( + [RowID] int NOT NULL, + [SPLongRangePlanID] int NOT NULL, + [SPLongRangePlanName] varchar(200) NOT NULL, + [AccountRollupID] int NOT NULL, + [SPAccountRollupName] varchar(200) NOT NULL, + [PatientTypeRollupID] tinyint NOT NULL, + [PatientTypeRollupCode] varchar(200) NOT NULL, + [PhysicianGroupID] int NOT NULL, + [PhysicianGroupCode] varchar(200) NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [UnitType] varchar(20) NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] varchar(20) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] varchar(20) NOT NULL, + [Amount] decimal NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [int].[FactSPDirectISPhysician] ADD CONSTRAINT [DF__FactSPDir__Fisca__66DBF4FD] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactSPDirectISPhysician] ADD CONSTRAINT [DF__FactSPDir__Amoun__67D01936] DEFAULT ((0.0)) FOR [Amount]; GO +ALTER TABLE [int].[FactSPDirectISPhysician] ADD CONSTRAINT [DF__FactSPDir__Histo__68C43D6F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactSPDirectISPhysician] ADD CONSTRAINT [DF__INT_FactSPDirectISPhysician_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactSPDirectISPhysician] ADD CONSTRAINT [DF__FactSPDir__SPLon__5A761E18] DEFAULT ((0)) FOR [SPLongRangePlanID]; GO +ALTER TABLE [int].[FactSPDirectISPhysician] ADD CONSTRAINT [DF__FactSPDir__SPLon__5B6A4251] DEFAULT ('') FOR [SPLongRangePlanName]; GO +ALTER TABLE [int].[FactSPDirectISPhysician] ADD CONSTRAINT [DF__FactSPDir__SPAcc__5C5E668A] DEFAULT ((0)) FOR [AccountRollupID]; GO +ALTER TABLE [int].[FactSPDirectISPhysician] ADD CONSTRAINT [DF__FactSPDir__SPAcc__5D528AC3] DEFAULT ('') FOR [SPAccountRollupName]; GO +ALTER TABLE [int].[FactSPDirectISPhysician] ADD CONSTRAINT [DF__FactSPDir__Patie__5E46AEFC] DEFAULT ((0)) FOR [PatientTypeRollupID]; GO +ALTER TABLE [int].[FactSPDirectISPhysician] ADD CONSTRAINT [DF__FactSPDir__Patie__5F3AD335] DEFAULT ('') FOR [PatientTypeRollupCode]; GO +ALTER TABLE [int].[FactSPDirectISPhysician] ADD CONSTRAINT [DF__FactSPDir__Physi__602EF76E] DEFAULT ((0)) FOR [PhysicianGroupID]; GO +ALTER TABLE [int].[FactSPDirectISPhysician] ADD CONSTRAINT [DF__FactSPDir__Physi__61231BA7] DEFAULT ('') FOR [PhysicianGroupCode]; GO +ALTER TABLE [int].[FactSPDirectISPhysician] ADD CONSTRAINT [DF__FactSPDir__UnitT__62173FE0] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [int].[FactSPDirectISPhysician] ADD CONSTRAINT [DF__FactSPDir__UnitT__630B6419] DEFAULT ('') FOR [UnitType]; GO +ALTER TABLE [int].[FactSPDirectISPhysician] ADD CONSTRAINT [DF__FactSPDir__TimeC__63FF8852] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactSPDirectISPhysician] ADD CONSTRAINT [DF__FactSPDir__TimeC__64F3AC8B] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactSPDirectISPhysician] ADD CONSTRAINT [DF__FactSPDir__Fisca__65E7D0C4] DEFAULT ((0)) FOR [FiscalYearID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactSPDirectISStaffing ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactSPDirectISStaffing] ( + [RowID] int NOT NULL, + [SPLongRangePlanID] int NOT NULL, + [SPLongRangePlanName] varchar(200) NOT NULL, + [AccountRollupID] int NOT NULL, + [SPAccountRollupName] varchar(200) NOT NULL, + [JobCodeGroupID] int NOT NULL, + [JobCodeGroup] varchar(200) NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [UnitType] varchar(20) NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] varchar(20) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] varchar(20) NOT NULL, + [Amount] decimal NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [int].[FactSPDirectISStaffing] ADD CONSTRAINT [DF__FactSPDir__SPLon__6D88F28C] DEFAULT ((0)) FOR [SPLongRangePlanID]; GO +ALTER TABLE [int].[FactSPDirectISStaffing] ADD CONSTRAINT [DF__FactSPDir__SPLon__6E7D16C5] DEFAULT ('') FOR [SPLongRangePlanName]; GO +ALTER TABLE [int].[FactSPDirectISStaffing] ADD CONSTRAINT [DF__FactSPDir__SPAcc__6F713AFE] DEFAULT ((0)) FOR [AccountRollupID]; GO +ALTER TABLE [int].[FactSPDirectISStaffing] ADD CONSTRAINT [DF__FactSPDir__SPAcc__70655F37] DEFAULT ('') FOR [SPAccountRollupName]; GO +ALTER TABLE [int].[FactSPDirectISStaffing] ADD CONSTRAINT [DF__FactSPDir__JobCo__71598370] DEFAULT ((0)) FOR [JobCodeGroupID]; GO +ALTER TABLE [int].[FactSPDirectISStaffing] ADD CONSTRAINT [DF__FactSPDir__JobCo__724DA7A9] DEFAULT ('') FOR [JobCodeGroup]; GO +ALTER TABLE [int].[FactSPDirectISStaffing] ADD CONSTRAINT [DF__FactSPDir__UnitT__7341CBE2] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [int].[FactSPDirectISStaffing] ADD CONSTRAINT [DF__FactSPDir__UnitT__7435F01B] DEFAULT ('') FOR [UnitType]; GO +ALTER TABLE [int].[FactSPDirectISStaffing] ADD CONSTRAINT [DF__FactSPDir__TimeC__752A1454] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactSPDirectISStaffing] ADD CONSTRAINT [DF__FactSPDir__TimeC__761E388D] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactSPDirectISStaffing] ADD CONSTRAINT [DF__FactSPDir__Fisca__77125CC6] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactSPDirectISStaffing] ADD CONSTRAINT [DF__FactSPDir__Fisca__780680FF] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactSPDirectISStaffing] ADD CONSTRAINT [DF__FactSPDir__Amoun__78FAA538] DEFAULT ((0.0)) FOR [Amount]; GO +ALTER TABLE [int].[FactSPDirectISStaffing] ADD CONSTRAINT [DF__FactSPDir__Histo__79EEC971] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactSPDirectISStaffing] ADD CONSTRAINT [DF__INT_FactSPDirectISStaffing_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactSPDirectRollingISAccount ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactSPDirectRollingISAccount] ( + [RowID] int NOT NULL, + [SPRollingForecastPlanID] int NOT NULL, + [SPRollingForecastPlanName] varchar(200) NOT NULL, + [AccountRollupID] int NOT NULL, + [SPAccountRollupName] varchar(200) NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [UnitType] varchar(20) NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] varchar(20) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] varchar(20) NOT NULL, + [ValueMonth01] decimal NOT NULL, + [ValueMonth02] decimal NOT NULL, + [ValueMonth03] decimal NOT NULL, + [ValueMonth04] decimal NOT NULL, + [ValueMonth05] decimal NOT NULL, + [ValueMonth06] decimal NOT NULL, + [ValueMonth07] decimal NOT NULL, + [ValueMonth08] decimal NOT NULL, + [ValueMonth09] decimal NOT NULL, + [ValueMonth10] decimal NOT NULL, + [ValueMonth11] decimal NOT NULL, + [ValueMonth12] decimal NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__Value__0066BCD6] DEFAULT ((0.0)) FOR [ValueMonth09]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__Value__015AE10F] DEFAULT ((0.0)) FOR [ValueMonth10]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__Value__024F0548] DEFAULT ((0.0)) FOR [ValueMonth11]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__Value__03432981] DEFAULT ((0.0)) FOR [ValueMonth12]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__Histo__04374DBA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__INT_FactSPDirectRollingISAccount_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__SPRol__6F3C30D4] DEFAULT ((0)) FOR [SPRollingForecastPlanID]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__SPRol__7030550D] DEFAULT ('') FOR [SPRollingForecastPlanName]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__SPAcc__71247946] DEFAULT ((0)) FOR [AccountRollupID]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__SPAcc__72189D7F] DEFAULT ('') FOR [SPAccountRollupName]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__UnitT__730CC1B8] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__UnitT__7400E5F1] DEFAULT ('') FOR [UnitType]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__TimeC__74F50A2A] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__TimeC__75E92E63] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__Fisca__76DD529C] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__Fisca__77D176D5] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__Value__78C59B0E] DEFAULT ((0.0)) FOR [ValueMonth01]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__Value__79B9BF47] DEFAULT ((0.0)) FOR [ValueMonth02]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__Value__7AADE380] DEFAULT ((0.0)) FOR [ValueMonth03]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__Value__7BA207B9] DEFAULT ((0.0)) FOR [ValueMonth04]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__Value__7C962BF2] DEFAULT ((0.0)) FOR [ValueMonth05]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__Value__7D8A502B] DEFAULT ((0.0)) FOR [ValueMonth06]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__Value__7E7E7464] DEFAULT ((0.0)) FOR [ValueMonth07]; GO +ALTER TABLE [int].[FactSPDirectRollingISAccount] ADD CONSTRAINT [DF__FactSPDir__Value__7F72989D] DEFAULT ((0.0)) FOR [ValueMonth08]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactSPDirectRollingISPayor ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactSPDirectRollingISPayor] ( + [RowID] int NOT NULL, + [SPRollingForecastPlanID] int NOT NULL, + [SPRollingForecastPlanName] varchar(200) NOT NULL, + [AccountRollupID] int NOT NULL, + [SPAccountRollupName] varchar(200) NOT NULL, + [PatientTypeRollupID] tinyint NOT NULL, + [PatientTypeRollupCode] varchar(200) NOT NULL, + [PayorGroupID] int NOT NULL, + [PayorGroupCode] varchar(200) NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [UnitType] varchar(20) NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] varchar(20) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] varchar(20) NOT NULL, + [ValueMonth01] decimal NOT NULL, + [ValueMonth02] decimal NOT NULL, + [ValueMonth03] decimal NOT NULL, + [ValueMonth04] decimal NOT NULL, + [ValueMonth05] decimal NOT NULL, + [ValueMonth06] decimal NOT NULL, + [ValueMonth07] decimal NOT NULL, + [ValueMonth08] decimal NOT NULL, + [ValueMonth09] decimal NOT NULL, + [ValueMonth10] decimal NOT NULL, + [ValueMonth11] decimal NOT NULL, + [ValueMonth12] decimal NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__SPRol__08FC02D7] DEFAULT ((0)) FOR [SPRollingForecastPlanID]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__SPRol__09F02710] DEFAULT ('') FOR [SPRollingForecastPlanName]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__SPAcc__0AE44B49] DEFAULT ((0)) FOR [AccountRollupID]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__SPAcc__0BD86F82] DEFAULT ('') FOR [SPAccountRollupName]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__Patie__0CCC93BB] DEFAULT ((0)) FOR [PatientTypeRollupID]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__Patie__0DC0B7F4] DEFAULT ('') FOR [PatientTypeRollupCode]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__Payor__0EB4DC2D] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__Payor__0FA90066] DEFAULT ('') FOR [PayorGroupCode]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__UnitT__109D249F] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__UnitT__119148D8] DEFAULT ('') FOR [UnitType]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__TimeC__12856D11] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__TimeC__1379914A] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__Fisca__146DB583] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__Fisca__1561D9BC] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__Value__1655FDF5] DEFAULT ((0.0)) FOR [ValueMonth01]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__Value__174A222E] DEFAULT ((0.0)) FOR [ValueMonth02]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__Value__183E4667] DEFAULT ((0.0)) FOR [ValueMonth03]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__Value__19326AA0] DEFAULT ((0.0)) FOR [ValueMonth04]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__Value__1A268ED9] DEFAULT ((0.0)) FOR [ValueMonth05]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__Value__1B1AB312] DEFAULT ((0.0)) FOR [ValueMonth06]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__Value__1C0ED74B] DEFAULT ((0.0)) FOR [ValueMonth07]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__Value__1D02FB84] DEFAULT ((0.0)) FOR [ValueMonth08]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__Value__1DF71FBD] DEFAULT ((0.0)) FOR [ValueMonth09]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__Value__1EEB43F6] DEFAULT ((0.0)) FOR [ValueMonth10]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__Value__1FDF682F] DEFAULT ((0.0)) FOR [ValueMonth11]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__Value__20D38C68] DEFAULT ((0.0)) FOR [ValueMonth12]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__FactSPDir__Histo__21C7B0A1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactSPDirectRollingISPayor] ADD CONSTRAINT [DF__INT_FactSPDirectRollingISPayor_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactSPDirectRollingISPhysician ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactSPDirectRollingISPhysician] ( + [RowID] int NOT NULL, + [SPRollingForecastPlanID] int NOT NULL, + [SPRollingForecastPlanName] varchar(200) NOT NULL, + [AccountRollupID] int NOT NULL, + [SPAccountRollupName] varchar(200) NOT NULL, + [PatientTypeRollupID] tinyint NOT NULL, + [PatientTypeRollupCode] varchar(200) NOT NULL, + [PhysicianGroupID] int NOT NULL, + [PhysicianGroupCode] varchar(200) NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [UnitType] varchar(20) NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] varchar(20) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] varchar(20) NOT NULL, + [ValueMonth01] decimal NOT NULL, + [ValueMonth02] decimal NOT NULL, + [ValueMonth03] decimal NOT NULL, + [ValueMonth04] decimal NOT NULL, + [ValueMonth05] decimal NOT NULL, + [ValueMonth06] decimal NOT NULL, + [ValueMonth07] decimal NOT NULL, + [ValueMonth08] decimal NOT NULL, + [ValueMonth09] decimal NOT NULL, + [ValueMonth10] decimal NOT NULL, + [ValueMonth11] decimal NOT NULL, + [ValueMonth12] decimal NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__SPRol__268C65BE] DEFAULT ((0)) FOR [SPRollingForecastPlanID]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__SPRol__278089F7] DEFAULT ('') FOR [SPRollingForecastPlanName]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__SPAcc__2874AE30] DEFAULT ((0)) FOR [AccountRollupID]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__SPAcc__2968D269] DEFAULT ('') FOR [SPAccountRollupName]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__Patie__2A5CF6A2] DEFAULT ((0)) FOR [PatientTypeRollupID]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__Patie__2B511ADB] DEFAULT ('') FOR [PatientTypeRollupCode]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__Physi__2C453F14] DEFAULT ((0)) FOR [PhysicianGroupID]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__Physi__2D39634D] DEFAULT ('') FOR [PhysicianGroupCode]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__UnitT__2E2D8786] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__UnitT__2F21ABBF] DEFAULT ('') FOR [UnitType]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__TimeC__3015CFF8] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__TimeC__3109F431] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__Fisca__31FE186A] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__Fisca__32F23CA3] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__Value__33E660DC] DEFAULT ((0.0)) FOR [ValueMonth01]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__Value__34DA8515] DEFAULT ((0.0)) FOR [ValueMonth02]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__Value__35CEA94E] DEFAULT ((0.0)) FOR [ValueMonth03]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__Value__36C2CD87] DEFAULT ((0.0)) FOR [ValueMonth04]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__Value__37B6F1C0] DEFAULT ((0.0)) FOR [ValueMonth05]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__Value__38AB15F9] DEFAULT ((0.0)) FOR [ValueMonth06]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__Value__399F3A32] DEFAULT ((0.0)) FOR [ValueMonth07]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__Value__3A935E6B] DEFAULT ((0.0)) FOR [ValueMonth08]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__Value__3B8782A4] DEFAULT ((0.0)) FOR [ValueMonth09]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__Value__3C7BA6DD] DEFAULT ((0.0)) FOR [ValueMonth10]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__Value__3D6FCB16] DEFAULT ((0.0)) FOR [ValueMonth11]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__Value__3E63EF4F] DEFAULT ((0.0)) FOR [ValueMonth12]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__FactSPDir__Histo__3F581388] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactSPDirectRollingISPhysician] ADD CONSTRAINT [DF__INT_FactSPDirectRollingISPhysician_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactSPDirectRollingISStaffing ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactSPDirectRollingISStaffing] ( + [RowID] int NOT NULL, + [SPRollingForecastPlanID] int NOT NULL, + [SPRollingForecastPlanName] varchar(200) NOT NULL, + [AccountRollupID] int NOT NULL, + [SPAccountRollupName] varchar(200) NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [UnitType] varchar(20) NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] varchar(20) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] varchar(20) NOT NULL, + [JobCodeGroupID] int NOT NULL, + [JobCodeGroup] varchar(200) NOT NULL, + [ValueMonth01] decimal NOT NULL, + [ValueMonth02] decimal NOT NULL, + [ValueMonth03] decimal NOT NULL, + [ValueMonth04] decimal NOT NULL, + [ValueMonth05] decimal NOT NULL, + [ValueMonth06] decimal NOT NULL, + [ValueMonth07] decimal NOT NULL, + [ValueMonth08] decimal NOT NULL, + [ValueMonth09] decimal NOT NULL, + [ValueMonth10] decimal NOT NULL, + [ValueMonth11] decimal NOT NULL, + [ValueMonth12] decimal NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__INT_FactSPDirectRollingISStaffing_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__SPRol__441CC8A5] DEFAULT ((0)) FOR [SPRollingForecastPlanID]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__SPRol__4510ECDE] DEFAULT ('') FOR [SPRollingForecastPlanName]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__SPAcc__46051117] DEFAULT ((0)) FOR [AccountRollupID]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__SPAcc__46F93550] DEFAULT ('') FOR [SPAccountRollupName]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__UnitT__47ED5989] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__UnitT__48E17DC2] DEFAULT ('') FOR [UnitType]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__TimeC__49D5A1FB] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__TimeC__4AC9C634] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__Fisca__4BBDEA6D] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__Fisca__4CB20EA6] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__JobCo__4DA632DF] DEFAULT ((0)) FOR [JobCodeGroupID]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__JobCo__4E9A5718] DEFAULT ('') FOR [JobCodeGroup]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__Value__4F8E7B51] DEFAULT ((0.0)) FOR [ValueMonth01]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__Value__50829F8A] DEFAULT ((0.0)) FOR [ValueMonth02]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__Value__5176C3C3] DEFAULT ((0.0)) FOR [ValueMonth03]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__Value__526AE7FC] DEFAULT ((0.0)) FOR [ValueMonth04]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__Value__535F0C35] DEFAULT ((0.0)) FOR [ValueMonth05]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__Value__5453306E] DEFAULT ((0.0)) FOR [ValueMonth06]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__Value__554754A7] DEFAULT ((0.0)) FOR [ValueMonth07]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__Value__563B78E0] DEFAULT ((0.0)) FOR [ValueMonth08]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__Value__572F9D19] DEFAULT ((0.0)) FOR [ValueMonth09]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__Value__5823C152] DEFAULT ((0.0)) FOR [ValueMonth10]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__Value__5917E58B] DEFAULT ((0.0)) FOR [ValueMonth11]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__Value__5A0C09C4] DEFAULT ((0.0)) FOR [ValueMonth12]; GO +ALTER TABLE [int].[FactSPDirectRollingISStaffing] ADD CONSTRAINT [DF__FactSPDir__Histo__5B002DFD] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactServiceLine ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactServiceLine] ( + [RowID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] nvarchar(100) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] nvarchar(100) NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalMonthCode] nvarchar(100) NOT NULL, + [EntityID] int NOT NULL, + [EntityCode] nvarchar(100) NOT NULL, + [PatientClassID] int NOT NULL, + [PatientClassCode] nvarchar(100) NOT NULL, + [ServiceLineID] int NOT NULL, + [ServiceLine] nvarchar(100) NOT NULL, + [AgeCohortID] int NOT NULL, + [AgeCohort] nvarchar(100) NOT NULL, + [MedicalSurgicalID] int NOT NULL, + [MedSurg] nvarchar(100) NOT NULL, + [DepartmentID] int NOT NULL, + [DepartmentCode] nvarchar(100) NOT NULL, + [OBForecastDetailID] int NOT NULL, + [ForecastDetail] nvarchar(100) NOT NULL, + [PayorGroupID] int NOT NULL, + [PayorID] int NOT NULL, + [Value] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [PayorGroupCode] nvarchar(100) NOT NULL, + [PayorCode] nvarchar(100) NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [FK__FactServi__AgeCo__7CB29264] FOREIGN KEY ([AgeCohortID]) REFERENCES [fw].[DimAgeCohort] ([AgeCohortID]); GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [FK__FactServi__Fisca__00832348] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [FK__FactServi__Fisca__026B6BBA] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [FK__FactServi__Medic__0453B42C] FOREIGN KEY ([MedicalSurgicalID]) REFERENCES [fw].[DimMedicalSurgical] ([MedicalSurgicalID]); GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [FK__FactServi__Patie__08244510] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [FK__FactServi__Servi__0A0C8D82] FOREIGN KEY ([ServiceLineID]) REFERENCES [fw].[DimServiceLine] ([ServiceLineID]); GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [FK__FactServi__TimeC__0BF4D5F4] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__Payor__14498B46] DEFAULT ('') FOR [PayorGroupCode]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__Payor__153DAF7F] DEFAULT ('') FOR [PayorCode]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__Histo__176688A0] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__TimeC__0B00B1BB] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__TimeC__148A1BF5] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__Fisca__01774781] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__Fisca__0FC566D8] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__Fisca__7F8EFF0F] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__Fisca__0ED1429F] DEFAULT ('') FOR [FiscalMonthCode]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__Entit__5156606F] DEFAULT ('') FOR [EntityCode]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__Patie__073020D7] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__Patie__12A1D383] DEFAULT ('') FOR [PatientClassCode]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__Servi__09186949] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__Servi__1395F7BC] DEFAULT ('') FOR [ServiceLine]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__AgeCo__7BBE6E2B] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__AgeCo__0CE8FA2D] DEFAULT ('') FOR [AgeCohort]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__Medic__035F8FF3] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__MedSu__10B98B11] DEFAULT ('') FOR [MedSurg]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__Depar__299CA979] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__OBFor__50623C36] DEFAULT ((0)) FOR [OBForecastDetailID]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__Forec__11ADAF4A] DEFAULT ('') FOR [ForecastDetail]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__Payor__2C791624] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__Payor__2B84F1EB] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__Value__157E402E] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__IsDel__16726467] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__Trans__185AACD9] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__Entit__4F6E17FD] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [int].[FactServiceLine] ADD CONSTRAINT [DF__FactServi__Depar__28A88540] DEFAULT ((0)) FOR [DepartmentID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactSharedImportDailyStatistics ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactSharedImportDailyStatistics] ( + [RowID] bigint NOT NULL, + [AccountID] int NOT NULL, + [DepartmentID] int NOT NULL, + [EntityID] int NOT NULL, + [StatDate] datetime NOT NULL, + [AccountCode] nvarchar(100) NOT NULL, + [DepartmentCode] nvarchar(100) NOT NULL, + [EntityCode] nvarchar(100) NOT NULL, + [Value] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [DateID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [int].[FactSharedImportDailyStatistics] ([IsDeleted], [DepartmentID], [AccountID], [DateID], [RowID]); +GO +ALTER TABLE [int].[FactSharedImportDailyStatistics] ADD CONSTRAINT [FK__FactShare__Accou__09156DB7] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [int].[FactSharedImportDailyStatistics] ADD CONSTRAINT [FK__FactShare__Depar__0AFDB629] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [int].[FactSharedImportDailyStatistics] ADD CONSTRAINT [FK__FactShare__Entit__0CE5FE9B] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [int].[FactSharedImportDailyStatistics] ADD CONSTRAINT [DF__FactShare__Trans__1FF8D30F] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactSharedImportDailyStatistics] ADD CONSTRAINT [DF_FactSharedImportDailyStatistics_TimeClassID] DEFAULT ((1)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactSharedImportDailyStatistics] ADD CONSTRAINT [DF__FactShare__Histo__1F04AED6] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactSharedImportDailyStatistics] ADD CONSTRAINT [DF__FactShare__DateI__4BC3DD62] DEFAULT ((0)) FOR [DateID]; GO +ALTER TABLE [int].[FactSharedImportDailyStatistics] ADD CONSTRAINT [DF__FactShare__Accou__0821497E] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [int].[FactSharedImportDailyStatistics] ADD CONSTRAINT [DF__FactShare__Depar__0A0991F0] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [int].[FactSharedImportDailyStatistics] ADD CONSTRAINT [DF__FactShare__Entit__0BF1DA62] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [int].[FactSharedImportDailyStatistics] ADD CONSTRAINT [DF__FactShare__StatD__157B449C] DEFAULT (getdate()) FOR [StatDate]; GO +ALTER TABLE [int].[FactSharedImportDailyStatistics] ADD CONSTRAINT [DF__FactShare__Accou__166F68D5] DEFAULT ('') FOR [AccountCode]; GO +ALTER TABLE [int].[FactSharedImportDailyStatistics] ADD CONSTRAINT [DF__FactShare__Depar__17638D0E] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactSharedImportDailyStatistics] ADD CONSTRAINT [DF__FactShare__Entit__1857B147] DEFAULT ('') FOR [EntityCode]; GO +ALTER TABLE [int].[FactSharedImportDailyStatistics] ADD CONSTRAINT [DF__FactShare__Value__1C28422B] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [int].[FactSharedImportDailyStatistics] ADD CONSTRAINT [DF__FactShare__IsDel__1E108A9D] DEFAULT ((0)) FOR [IsDeleted]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactStaffing ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactStaffing] ( + [RowID] bigint NOT NULL, + [DepartmentID] int NOT NULL, + [DepartmentCode] varchar(100) NOT NULL, + [JobCodeID] int NOT NULL, + [JobCode] varchar(50) NOT NULL, + [EmployeeID] int NOT NULL, + [Employeecode] nvarchar(2000) NOT NULL, + [PayCodeID] smallint NOT NULL, + [PayCode] varchar(100) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] varchar(20) NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] varchar(20) NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [UnitType] varchar(20) NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalMonthCode] varchar(20) NOT NULL, + [Value] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + [GlPostDateID] int NOT NULL, + [GlPostDateTime] datetime NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [int].[FactStaffing] ([FiscalMonthID], [IsDeleted], [FiscalYearID], [TimeClassID], [DepartmentID], [JobCodeID], [PayCodeID], [EmployeeID], [UnitTypeID], [RowID]); +CREATE NONCLUSTERED INDEX [NCNU_PayCodeID] ON [int].[FactStaffing] ([PayCodeID]) INCLUDE ([Value]); +CREATE NONCLUSTERED INDEX [NCNU_ReconciliationPerformance] ON [int].[FactStaffing] ([EmployeeID], [UnitTypeID], [FiscalYearID], [PayCodeID]); +CREATE NONCLUSTERED INDEX [NCNU_TransactionID] ON [int].[FactStaffing] ([TransactionID]); +CREATE NONCLUSTERED INDEX [IX_FactStaffing_1] ON [int].[FactStaffing] ([FiscalYearID], [TimeClassID], [UnitTypeID]) INCLUDE ([Value]); +GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF__FactStaff__GlPos__0D4E147E] DEFAULT ((0)) FOR [GlPostDateID]; GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF__FactStaff__GlPos__0E4238B7] DEFAULT ('01-01-1900') FOR [GlPostDateTime]; GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF__FactStaff__Depar__2B6F7FBE] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF__FactStaff__Depar__2C63A3F7] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF__FactStaff__JobCo__2D57C830] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF__FactStaff__JobCo__2E4BEC69] DEFAULT ('') FOR [JobCode]; GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF__FactStaff__Emplo__6C3C01AF] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF_INTFACTSTAFFINGEMPLOYEECODE] DEFAULT ('') FOR [Employeecode]; GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF__FactStaff__PayCo__2F4010A2] DEFAULT ((0)) FOR [PayCodeID]; GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF__FactStaff__PayCo__303434DB] DEFAULT ('') FOR [PayCode]; GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF__FactStaff__Fisca__31285914] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF__FactStaff__Fisca__321C7D4D] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF__FactStaff__TimeC__3310A186] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF__FactStaff__TimeC__3404C5BF] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF__FactStaff__UnitT__34F8E9F8] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF__FactStaff__UnitT__35ED0E31] DEFAULT ('') FOR [UnitType]; GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF__FactStaff__Fisca__3CCC1A58] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF__FactStaff__Fisca__46558492] DEFAULT ('') FOR [FiscalMonthCode]; GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF_INTFACTSTAFFINGVALUE] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF__FactStaff__IsDel__4749A8CB] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF__FactStaff__Histo__4347094F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactStaffing] ADD CONSTRAINT [DF__INT_FactStaffing_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactStaffingByPayPeriod ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactStaffingByPayPeriod] ( + [RowID] bigint NOT NULL, + [DepartmentID] int NOT NULL, + [DepartmentCode] varchar(100) NOT NULL, + [JobCodeID] int NOT NULL, + [JobCode] varchar(50) NOT NULL, + [PayCodeID] smallint NOT NULL, + [PayCode] varchar(100) NOT NULL, + [PayPeriodID] smallint NOT NULL, + [PayPeriodCode] varchar(50) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] varchar(20) NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] varchar(20) NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [UnitType] varchar(20) NOT NULL, + [Value] decimal NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [EmployeeID] int NOT NULL, + [Employeecode] nvarchar(2000) NOT NULL, + [TransactionID] int NULL, + [IsDeleted] bit NOT NULL, + [GlPostDateID] int NOT NULL, + [GlPostDateTime] datetime NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [int].[FactStaffingByPayPeriod] ([IsDeleted], [FiscalYearID], [TimeClassID], [PayPeriodID], [DepartmentID], [JobCodeID], [PayCodeID], [EmployeeID], [UnitTypeID], [RowID]); +GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [FK_FactStaff_DimPayPeriod] FOREIGN KEY ([PayPeriodID]) REFERENCES [fw].[DimPayPeriod] ([PayPeriodID]); GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF_INTFACTSTAFFINGBYPAYPERIODEMPLOYEECODE] DEFAULT ('') FOR [Employeecode]; GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF__FactStaff__GlPos__0B65CC0C] DEFAULT ((0)) FOR [GlPostDateID]; GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF__FactStaff__GlPos__0C59F045] DEFAULT (getdate()) FOR [GlPostDateTime]; GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF_FactStaffingByPayPeriod_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF__INT_FactStaffingByPayPeriod_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF__FactStaff__Depar__480BBE6C] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF__FactStaff__Depar__48FFE2A5] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF__FactStaff__JobCo__49F406DE] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF__FactStaff__JobCo__4AE82B17] DEFAULT ('') FOR [JobCode]; GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF__FactStaff__PayCo__4BDC4F50] DEFAULT ((0)) FOR [PayCodeID]; GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF__FactStaff__PayCo__4CD07389] DEFAULT ('') FOR [PayCode]; GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF_FactStaffingByPayPeriod_PayPeriodID] DEFAULT ((0)) FOR [PayPeriodID]; GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF_FactStaffingByPayPeriod_PayPeriodCode] DEFAULT ('') FOR [PayPeriodCode]; GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF__FactStaff__Fisca__4DC497C2] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF__FactStaff__Fisca__4EB8BBFB] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF__FactStaff__TimeC__4FACE034] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF__FactStaff__TimeC__50A1046D] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF__FactStaff__UnitT__519528A6] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF__FactStaff__UnitT__52894CDF] DEFAULT ('') FOR [UnitType]; GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF__FactStaff__Value__537D7118] DEFAULT ((0.0)) FOR [Value]; GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF__FactStaff__Histo__54719551] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactStaffingByPayPeriod] ADD CONSTRAINT [DF__FactStaff__Emplo__6D3025E8] DEFAULT ((0)) FOR [EmployeeID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactStaffingDaily ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactStaffingDaily] ( + [RowID] bigint NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeID] smallint NOT NULL, + [EmployeeID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [DateID] int NOT NULL, + [Value] decimal NOT NULL, + [DepartmentCode] nvarchar(2000) NOT NULL, + [JobCode] nvarchar(2000) NOT NULL, + [PayCode] nvarchar(2000) NOT NULL, + [EmployeeCode] nvarchar(2000) NOT NULL, + [FiscalYearCode] nvarchar(2000) NOT NULL, + [TimeClassCode] nvarchar(2000) NOT NULL, + [UnitType] nvarchar(2000) NOT NULL, + [PayrollDate] datetime NOT NULL, + [TransactionCode] nvarchar(2000) NOT NULL, + [CustomTextField] nvarchar(2000) NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [int].[FactStaffingDaily] ([IsDeleted], [DepartmentID], [JobCodeID], [PayCodeID], [EmployeeID], [FiscalYearID], [TimeClassID], [UnitTypeID], [DateID], [RowID]); +GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__IsDel__46FF2845] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__Trans__48E770B7] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__Depar__34E0780A] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__JobCo__35D49C43] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__PayCo__36C8C07C] DEFAULT ((0)) FOR [PayCodeID]; GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__Emplo__37BCE4B5] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__Fisca__38B108EE] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__TimeC__39A52D27] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__UnitT__3A995160] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__DateI__3B8D7599] DEFAULT ((0)) FOR [DateID]; GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__Value__3C8199D2] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__Depar__3D75BE0B] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__JobCo__3E69E244] DEFAULT ('') FOR [JobCode]; GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__PayCo__3F5E067D] DEFAULT ('') FOR [PayCode]; GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__Emplo__40522AB6] DEFAULT ('') FOR [EmployeeCode]; GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__Fisca__41464EEF] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__TimeC__423A7328] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__UnitT__432E9761] DEFAULT ('') FOR [UnitType]; GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__Payro__4422BB9A] DEFAULT ('1/1/1900 12:00:00 AM') FOR [PayrollDate]; GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__Trans__4516DFD3] DEFAULT ('') FOR [TransactionCode]; GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__Custo__460B040C] DEFAULT ('') FOR [CustomTextField]; GO +ALTER TABLE [int].[FactStaffingDaily] ADD CONSTRAINT [DF__FactStaff__Histo__47F34C7E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactStaffingSummary ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactStaffingSummary] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [DepartmentCode] varchar(100) NOT NULL, + [JobCodeGroupID] int NOT NULL, + [JobCodeGroup] varchar(50) NOT NULL, + [AccountRollupID] int NOT NULL, + [AccountRollupCode] varchar(50) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] varchar(20) NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] varchar(20) NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [UnitType] varchar(20) NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalMonthCode] varchar(20) NOT NULL, + [Value] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [int].[FactStaffingSummary] ([FiscalMonthID], [IsDeleted], [FiscalYearID], [TimeClassID], [DepartmentID], [JobCodeGroupID], [AccountRollupID], [UnitTypeID], [RowID]); +GO +ALTER TABLE [int].[FactStaffingSummary] ADD CONSTRAINT [DF__FactStaff__Depar__0FC76549] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactStaffingSummary] ADD CONSTRAINT [DF__FactStaff__JobCo__10BB8982] DEFAULT ((0)) FOR [JobCodeGroupID]; GO +ALTER TABLE [int].[FactStaffingSummary] ADD CONSTRAINT [DF__FactStaff__JobCo__11AFADBB] DEFAULT ('') FOR [JobCodeGroup]; GO +ALTER TABLE [int].[FactStaffingSummary] ADD CONSTRAINT [DF__FactStaff__Accou__12A3D1F4] DEFAULT ((0)) FOR [AccountRollupID]; GO +ALTER TABLE [int].[FactStaffingSummary] ADD CONSTRAINT [DF__FactStaff__Accou__1397F62D] DEFAULT ('') FOR [AccountRollupCode]; GO +ALTER TABLE [int].[FactStaffingSummary] ADD CONSTRAINT [DF__FactStaff__Fisca__148C1A66] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactStaffingSummary] ADD CONSTRAINT [DF__FactStaff__Fisca__15803E9F] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactStaffingSummary] ADD CONSTRAINT [DF__FactStaff__TimeC__167462D8] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactStaffingSummary] ADD CONSTRAINT [DF__FactStaff__TimeC__17688711] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactStaffingSummary] ADD CONSTRAINT [DF__FactStaff__UnitT__185CAB4A] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [int].[FactStaffingSummary] ADD CONSTRAINT [DF__FactStaff__UnitT__1950CF83] DEFAULT ('') FOR [UnitType]; GO +ALTER TABLE [int].[FactStaffingSummary] ADD CONSTRAINT [DF__FactStaff__Fisca__38FB8974] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactStaffingSummary] ADD CONSTRAINT [DF__INT_FactStaffingSummary_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactStaffingSummary] ADD CONSTRAINT [DF__FactStaff__Fisca__446D3C20] DEFAULT ('') FOR [FiscalMonthCode]; GO +ALTER TABLE [int].[FactStaffingSummary] ADD CONSTRAINT [DF_INTFACTSTAFFINGSUMMARYVALUE] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [int].[FactStaffingSummary] ADD CONSTRAINT [DF__FactStaff__IsDel__45616059] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactStaffingSummary] ADD CONSTRAINT [DF__FactStaff__Histo__26AACAA1] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactStaffingSummary] ADD CONSTRAINT [DF__FactStaff__Depar__0ED34110] DEFAULT ((0)) FOR [DepartmentID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactStarPatientADT ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactStarPatientADT] ( + [RowID] int NOT NULL, + [EventID] nvarchar(100) NOT NULL, + [PatientAccountNumber] nvarchar(100) NOT NULL, + [DateTimeIn] nvarchar(100) NOT NULL, + [DateTimeOut] nvarchar(100) NOT NULL, + [SequenceNumber] nvarchar(100) NOT NULL, + [Department] nvarchar(100) NOT NULL, + [RoomNumber] nvarchar(100) NOT NULL, + [BedNumber] nvarchar(100) NOT NULL, + [TransferInType] nvarchar(100) NOT NULL, + [TransferOutType] nvarchar(100) NOT NULL, + [PatientType] nvarchar(100) NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE NONCLUSTERED INDEX [NC_IDX_StarADT_HistGUID_TrnsInType] ON [int].[FactStarPatientADT] ([HistoryItemGUID], [TransferInType]) INCLUDE ([PatientAccountNumber]); +CREATE NONCLUSTERED INDEX [NC_IDX_Star_PatACN_AllColumns] ON [int].[FactStarPatientADT] ([PatientAccountNumber]) INCLUDE ([DateTimeIn], [DateTimeOut], [SequenceNumber], [Department], [RoomNumber], [TransferInType]); +GO +ALTER TABLE [int].[FactStarPatientADT] ADD CONSTRAINT [DF__FactStarP__Histo__2D01C125] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactStarPatientADT] ADD CONSTRAINT [DF__FactStarP__Event__21900E79] DEFAULT ('') FOR [EventID]; GO +ALTER TABLE [int].[FactStarPatientADT] ADD CONSTRAINT [DF__FactStarP__Patie__228432B2] DEFAULT ('') FOR [PatientAccountNumber]; GO +ALTER TABLE [int].[FactStarPatientADT] ADD CONSTRAINT [DF__FactStarP__DateT__237856EB] DEFAULT ('') FOR [DateTimeIn]; GO +ALTER TABLE [int].[FactStarPatientADT] ADD CONSTRAINT [DF__FactStarP__DateT__246C7B24] DEFAULT ('') FOR [DateTimeOut]; GO +ALTER TABLE [int].[FactStarPatientADT] ADD CONSTRAINT [DF__FactStarP__Seque__25609F5D] DEFAULT ('') FOR [SequenceNumber]; GO +ALTER TABLE [int].[FactStarPatientADT] ADD CONSTRAINT [DF__FactStarP__Depar__2654C396] DEFAULT ('') FOR [Department]; GO +ALTER TABLE [int].[FactStarPatientADT] ADD CONSTRAINT [DF__FactStarP__RoomN__2748E7CF] DEFAULT ('') FOR [RoomNumber]; GO +ALTER TABLE [int].[FactStarPatientADT] ADD CONSTRAINT [DF__FactStarP__BedNu__283D0C08] DEFAULT ('') FOR [BedNumber]; GO +ALTER TABLE [int].[FactStarPatientADT] ADD CONSTRAINT [DF__FactStarP__Trans__29313041] DEFAULT ('') FOR [TransferInType]; GO +ALTER TABLE [int].[FactStarPatientADT] ADD CONSTRAINT [DF__FactStarP__Trans__2A25547A] DEFAULT ('') FOR [TransferOutType]; GO +ALTER TABLE [int].[FactStarPatientADT] ADD CONSTRAINT [DF__FactStarP__Patie__2B1978B3] DEFAULT ('') FOR [PatientType]; GO +ALTER TABLE [int].[FactStarPatientADT] ADD CONSTRAINT [DF__FactStarP__IsDel__2C0D9CEC] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactStarPatientADT] ADD CONSTRAINT [DF__FactStarP__Trans__2DF5E55E] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactStatistic ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactStatistic] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [DepartmentCode] varchar(100) NOT NULL, + [AccountID] int NOT NULL, + [AccountCode] varchar(50) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] varchar(20) NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] varchar(20) NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalMonthCode] varchar(20) NOT NULL, + [Value] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [int].[FactStatistic] ([FiscalMonthID], [IsDeleted], [FiscalYearID], [TimeClassID], [DepartmentID], [AccountID], [RowID]); +CREATE NONCLUSTERED INDEX [IX_FactGL_Covering] ON [int].[FactStatistic] ([AccountID]) INCLUDE ([DepartmentID], [FiscalMonthID], [FiscalYearID], [TimeClassID], [Value]); +GO +ALTER TABLE [int].[FactStatistic] ADD CONSTRAINT [FK__FactStati__Accou__48DCEB82] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [int].[FactStatistic] ADD CONSTRAINT [FK__FactStati__Depar__4AC533F4] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [int].[FactStatistic] ADD CONSTRAINT [FK__FactStati__Fisca__4CAD7C66] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [int].[FactStatistic] ADD CONSTRAINT [FK__FactStati__TimeC__4E95C4D8] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [int].[FactStatistic] ADD CONSTRAINT [DF_FactStatistic_DepartmentCode] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactStatistic] ADD CONSTRAINT [DF_FactStatistic_AccountCode] DEFAULT ('') FOR [AccountCode]; GO +ALTER TABLE [int].[FactStatistic] ADD CONSTRAINT [DF_FactStatistic_FiscalYearCode] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactStatistic] ADD CONSTRAINT [DF__FactStati__Depar__49D10FBB] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [int].[FactStatistic] ADD CONSTRAINT [DF_FactStatistic_TimeClassCode] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactStatistic] ADD CONSTRAINT [DF__INT_FactStatistic_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactStatistic] ADD CONSTRAINT [DF__FactStati__Accou__47E8C749] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [int].[FactStatistic] ADD CONSTRAINT [DF__FactStati__Fisca__4BB9582D] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactStatistic] ADD CONSTRAINT [DF__FactStati__TimeC__4DA1A09F] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [int].[FactStatistic] ADD CONSTRAINT [DF__FactStati__Fisca__2D89D6C8] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactStatistic] ADD CONSTRAINT [DF__FactStati__Fisca__3EB462CA] DEFAULT ('') FOR [FiscalMonthCode]; GO +ALTER TABLE [int].[FactStatistic] ADD CONSTRAINT [DF_INTFACTSTATISTICVALUE] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [int].[FactStatistic] ADD CONSTRAINT [DF__FactStati__Histo__5CE3E42F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactStatistic] ADD CONSTRAINT [DF__FactStati__IsDel__5BEFBFF6] DEFAULT ((0)) FOR [IsDeleted]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactStatisticsbyPayPeriod ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactStatisticsbyPayPeriod] ( + [RowID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] nvarchar(100) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] nvarchar(100) NOT NULL, + [PayPeriodID] smallint NOT NULL, + [PayPeriodCode] nvarchar(100) NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [EntityID] int NOT NULL, + [EntityDescription] nvarchar(200) NOT NULL, + [DepartmentID] int NOT NULL, + [DepartmentCode] nvarchar(100) NOT NULL, + [DepartmentDescription] nvarchar(200) NOT NULL, + [AccountID] int NOT NULL, + [AccountCode] nvarchar(100) NOT NULL, + [AccountDescription] nvarchar(160) NOT NULL, + [GLRollup] nvarchar(100) NOT NULL, + [Value] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [CNU_Base] ON [int].[FactStatisticsbyPayPeriod] ([PayPeriodID], [FiscalYearID], [TimeClassID], [DepartmentID], [AccountID]); +CREATE NONCLUSTERED INDEX [NCNU_DepartmentAccount] ON [int].[FactStatisticsbyPayPeriod] ([DepartmentID], [AccountID], [PayPeriodID], [FiscalYearID], [TimeClassID]); +GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [FK__FactStati__Accou__0C4779AA] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [FK__FactStati__Depar__0E2FC21C] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [FK__FactStati__Fisca__10180A8E] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [FK__FactStati__PayPe__12005300] FOREIGN KEY ([PayPeriodID]) REFERENCES [fw].[DimPayPeriod] ([PayPeriodID]); GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [FK__FactStati__TimeC__13E89B72] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [DF__FactStati__TimeC__19A174C8] DEFAULT ('') FOR [TimeClassCode]; GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Fisca__0F23E655] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Fisca__17B92C56] DEFAULT ('') FOR [FiscalYearCode]; GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [DF__FactStati__PayPe__110C2EC7] DEFAULT ((0)) FOR [PayPeriodID]; GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [DF__FactStati__PayPe__18AD508F] DEFAULT ('') FOR [PayPeriodCode]; GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Fisca__52763888] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Entit__545E80FA] DEFAULT ('') FOR [EntityDescription]; GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Depar__16C5081D] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Depar__5552A533] DEFAULT ('') FOR [DepartmentDescription]; GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Accou__0B535571] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Accou__15D0E3E4] DEFAULT ('') FOR [AccountCode]; GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Accou__5646C96C] DEFAULT ('') FOR [AccountDescription]; GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [DF__FactStati__GLRol__536A5CC1] DEFAULT ('') FOR [GLRollup]; GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Value__14DCBFAB] DEFAULT ((0)) FOR [Value]; GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [DF__FactStati__IsDel__1A959901] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Trans__1C7DE173] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Entit__5182144F] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Depar__0D3B9DE3] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [DF__FactStati__Histo__1B89BD3A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactStatisticsbyPayPeriod] ADD CONSTRAINT [DF__FactStati__TimeC__12F47739] DEFAULT ((0)) FOR [TimeClassID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.FactSwipeDataImport ------------------ +--------------------------------------------- +CREATE TABLE [int].[FactSwipeDataImport] ( + [RowID] int NOT NULL, + [EntityID] int NOT NULL, + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeID] smallint NOT NULL, + [EmployeeID] int NOT NULL, + [EmployeeCode] nvarchar(100) NOT NULL, + [HomeDeptCode] nvarchar(100) NOT NULL, + [HomeJobCode] nvarchar(100) NOT NULL, + [WorkedDeptCode] nvarchar(100) NOT NULL, + [WorkedJobCode] nvarchar(100) NOT NULL, + [InDate] nvarchar(100) NOT NULL, + [InTime] nvarchar(100) NOT NULL, + [OutDate] nvarchar(100) NOT NULL, + [OutTime] nvarchar(100) NOT NULL, + [PayCode] nvarchar(100) NOT NULL, + [PayGroupCode] nvarchar(100) NOT NULL, + [WorkedEntityCode] nvarchar(100) NOT NULL, + [HomeEntityCode] nvarchar(100) NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [InDateTime] datetime NOT NULL, + [OutDateTime] datetime NOT NULL, + [IsShiftStart] nvarchar(100) NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [FK__FactSwipe__Depar__78493DBA] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [FK__FactSwipe__Emplo__7E021710] FOREIGN KEY ([EmployeeID]) REFERENCES [fw].[DimEmployee] ([EmployeeID]); GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [FK__FactSwipe__Entit__7660F548] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [FK__FactSwipe__JobCo__7A31862C] FOREIGN KEY ([JobCodeID]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [FK__FactSwipe__PayCo__7C19CE9E] FOREIGN KEY ([PayCodeID]) REFERENCES [fw].[DimPayCode] ([PayCodeID]); GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__Depar__77551981] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__JobCo__793D61F3] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__PayCo__7B25AA65] DEFAULT ((0)) FOR [PayCodeID]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__Emplo__7D0DF2D7] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__Emplo__7EF63B49] DEFAULT ('') FOR [EmployeeCode]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__HomeD__7FEA5F82] DEFAULT ('') FOR [HomeDeptCode]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__HomeJ__00DE83BB] DEFAULT ('') FOR [HomeJobCode]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__Worke__01D2A7F4] DEFAULT ('') FOR [WorkedDeptCode]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__Worke__02C6CC2D] DEFAULT ('') FOR [WorkedJobCode]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__InDat__03BAF066] DEFAULT ('') FOR [InDate]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__InTim__04AF149F] DEFAULT ('') FOR [InTime]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__OutDa__05A338D8] DEFAULT ('') FOR [OutDate]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__OutTi__06975D11] DEFAULT ('') FOR [OutTime]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__PayCo__078B814A] DEFAULT ('') FOR [PayCode]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__PayGr__087FA583] DEFAULT ('') FOR [PayGroupCode]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__Worke__0973C9BC] DEFAULT ('') FOR [WorkedEntityCode]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__HomeE__0A67EDF5] DEFAULT ('') FOR [HomeEntityCode]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__IsDel__0B5C122E] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__Trans__0D445AA0] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__InDat__29A238DA] DEFAULT (getdate()) FOR [InDateTime]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__OutDa__2A965D13] DEFAULT (getdate()) FOR [OutDateTime]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__IsShi__57EE812F] DEFAULT ('') FOR [IsShiftStart]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__Histo__0C503667] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [int].[FactSwipeDataImport] ADD CONSTRAINT [DF__FactSwipe__Entit__756CD10F] DEFAULT ((0)) FOR [EntityID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- int.PositionTypeJobCodeAssignments ------------------ +--------------------------------------------- +CREATE TABLE [int].[PositionTypeJobCodeAssignments] ( + [RowId] int NOT NULL, + [PositionTypeId] int NOT NULL, + [JobCodeId] int NOT NULL, + PRIMARY KEY ([RowId]) +); +GO +ALTER TABLE [int].[PositionTypeJobCodeAssignments] ADD CONSTRAINT [FK__PositionT__JobCo__47C8F953] FOREIGN KEY ([JobCodeId]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO +ALTER TABLE [int].[PositionTypeJobCodeAssignments] ADD CONSTRAINT [FK__PositionT__Posit__46D4D51A] FOREIGN KEY ([PositionTypeId]) REFERENCES [fw].[DimPositionType] ([PositionTypeID]); GO + +--------------------------------------------- + +--------------------------------------------- +-- int.QU_Physician_Time_Test_Data_xlsx_f8e654ea_85a1_4884_8db1_f91e3da5edc8 ------------------ +--------------------------------------------- +CREATE TABLE [int].[QU_Physician_Time_Test_Data_xlsx_f8e654ea_85a1_4884_8db1_f91e3da5edc8] ( + [RowID] varchar(max) NULL, + [departmentcode] varchar(max) NULL, + [departmentID] varchar(max) NULL, + [cptID] varchar(max) NULL, + [cptcode] varchar(max) NULL, + [encounterrecordnumber] varchar(max) NULL, + [CustomPhysicianOfficeTime] varchar(max) NULL +); +GO + +--------------------------------------------- +--------------------------------------------- +-- VIEWS +--------------------------------------------- + +-- int.viewFactCDMPivoted +/************************************************************ +** Author: Ramya Amancharla +** Create Date: 2013-10-25 +** Description: Pivoted view for sampling (Will only be used +** if Charge Code tab is being used without ServiceLine) +** Last Modified: 2016-12-12 +** GM Release: 2013-11 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-12-12 srk D04896 Filtering out months that are not part of YTD months loaded +** 2 2018-04-03 sdominsk D-06562 Add cast the setting as an integer. +*************************************************************/ +CREATE view [int].[viewFactCDMPivoted] as + +select + [DepartmentID], + [DepartmentCode], + ChargeCodeID, + ChargeCode, + ServiceLineID, + ServiceLine, + AgeCohortID, + AgeCohort, + MedicalSurgicalID, + MedSurg, + PatientClassID, + PatientClassCode, + FiscalYearID, + TimeClassID, + UnitTypeID, + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from +( SELECT [DepartmentID], [DepartmentCode], UnitTypeID,ChargeCodeID, ChargeCode, timeclassID, TimeClassCode,ServiceLine, ServiceLineID, AgeCohort, AgeCohortID, MedicalSurgicalID, MedSurg, [FiscalYearID], [FiscalYearCode],PatientClassID,PatientClassCode, m.MonthColumnName, [Value],f.[HistoryItemGUID] +FROM [int].[FactCDM] f +inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID +where f.IsDeleted = 0 +--CID 1 +and f.FiscalYearID = (select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year +and Cast(m.FiscalMonthCode as int) <= Cast((Select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '14cbd1a1-15e9-411d-9fea-78cecaadf7e7')as int) -- OB_Months_Loaded +and f.TimeClassID = 1 +--CID 1 +) as data +PIVOT +( +SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) +) as pvt + +UNION ALL + +select + [DepartmentID], + [DepartmentCode], + ChargeCodeID, + ChargeCode, + ServiceLineID, + ServiceLine, + AgeCohortID, + AgeCohort, + MedicalSurgicalID, + MedSurg, + PatientClassID, + PatientClassCode, + FiscalYearID, + TimeClassID, + UnitTypeID, + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from +( SELECT [DepartmentID], [DepartmentCode], UnitTypeID,ChargeCodeID, ChargeCode, timeclassID, TimeClassCode,ServiceLine, ServiceLineID, AgeCohort, AgeCohortID, MedicalSurgicalID, MedSurg, [FiscalYearID], [FiscalYearCode],PatientClassID,PatientClassCode, m.MonthColumnName, [Value],f.[HistoryItemGUID] +FROM [int].[FactCDM] f +inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID +where f.IsDeleted = 0 +--CID 1 +and f.FiscalYearID = (select dbs.setting - 1 from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year - 1 +or f.FiscalYearID = (select dbs.setting + 1 from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year + 1 +--CID 1 +) as data +PIVOT +( +SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) +) as pvt + +UNION ALL + +select + [DepartmentID], + [DepartmentCode], + ChargeCodeID, + ChargeCode, + ServiceLineID, + ServiceLine, + AgeCohortID, + AgeCohort, + MedicalSurgicalID, + MedSurg, + PatientClassID, + PatientClassCode, + FiscalYearID, + TimeClassID, + UnitTypeID, + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from +( SELECT [DepartmentID], [DepartmentCode], UnitTypeID,ChargeCodeID, ChargeCode, timeclassID, TimeClassCode,ServiceLine, ServiceLineID, AgeCohort, AgeCohortID, MedicalSurgicalID, MedSurg, [FiscalYearID], [FiscalYearCode],PatientClassID,PatientClassCode, m.MonthColumnName, [Value],f.[HistoryItemGUID] +FROM [int].[FactCDM] f +inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID +where f.IsDeleted = 0 +--CID 1 +and f.FiscalYearID = (select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year +and f.TimeClassID = 2 +--CID 1 +) as data +PIVOT +( +SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) +) as pvt +GO + + +--------------------------------------------- + +-- int.viewFactGLPivoted +/******************************************************************************************************* +** Author: unknown +** Create Date: NA +** Description: The pivoted view that is used by the GL account sampling view/proc +** Last Modified: 2016-12-12 +** GM Release: 2014.4 +******************************************************************************************************** +** Change History +******************************************************************************************************** +** CID Date Author WI Description +** 1 2016-12-12 SRK D-04896 Filtering out months that are not part of YTD months loaded +** 2 2018-04-03 sdominsk d-06562 Add cast the setting as an integer. +  +*******************************************************************************************************/ + +CREATE view [int].[viewFactGLPivoted] as + +--------------Actual YTD-------------------------- +select +[DepartmentID], + [DepartmentCode], + [AccountID], + [AccountCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from +( SELECT [DepartmentID], [DepartmentCode], [AccountID], [AccountCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], m.MonthColumnName, [Value],f.[HistoryItemGUID] +FROM [int].[FactGL] f +inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID +--CID 1 +where 1=1 +and f.FiscalYearID = (select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year +and Cast(m.FiscalMonthCode as int) <= Cast((Select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '14cbd1a1-15e9-411d-9fea-78cecaadf7e7')as int) -- OB_Months_Loaded +and f.TimeClassID = 1 +--CID 1 +) as data +PIVOT +( +SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) +) as pvt + +UNION ALL + +--------------Actual Prior Year and Budget for Next Year-------------------------- +select +[DepartmentID], + [DepartmentCode], + [AccountID], + [AccountCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from +( SELECT [DepartmentID], [DepartmentCode], [AccountID], [AccountCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], m.MonthColumnName, [Value],f.[HistoryItemGUID] +FROM [int].[FactGL] f +inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID +--CID 1 +where 1=1 +and f.FiscalYearID = (select dbs.setting - 1 from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year - 1 +or f.FiscalYearID = (select dbs.setting + 1 from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year + 1 +--CID 1 +) as data +PIVOT +( +SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) +) as pvt + +UNION ALL + +--------------Budget for Current Year-------------------------- +select +[DepartmentID], + [DepartmentCode], + [AccountID], + [AccountCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from +( SELECT [DepartmentID], [DepartmentCode], [AccountID], [AccountCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], m.MonthColumnName, [Value],f.[HistoryItemGUID] +FROM [int].[FactGL] f +inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID +--CID 1 +where 1=1 +and f.FiscalYearID = (select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year +and f.TimeClassID = 2 +--CID 1 +) as data +PIVOT +( +SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) +) as pvt +GO + + +--------------------------------------------- + +-- int.viewFactGlobalStatisticsPivoted +CREATE view [int].[viewFactGlobalStatisticsPivoted] as + +/******************************************************************************************************* +** Author: unknown +** Create Date: NA +** Description: The pivoted view that is used by the Global Statistics sampling view/proc +** Last Modified: 2016-12-12 +** GM Release: 2014.4 +******************************************************************************************************** +** Change History +******************************************************************************************************** +** CID Date Author WI Description +** 1 2016-12-12 SRK D-04896 Filtering out months that are not part of YTD months loaded +** 2 2018-04-03 sdominsk D-06562 Add cast the setting as an integer. +*******************************************************************************************************/ + +select + [EntityID], +[DepartmentID], + [DepartmentCode], + [AccountID], + [AccountCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from +( SELECT [EntityID],[DepartmentID], [DepartmentCode], [AccountID], [AccountCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], m.MonthColumnName, [Value],f.[HistoryItemGUID] +FROM [int].[FactGlobalStatistics] f +inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID +--CID 1 +where 1=1 +and f.FiscalYearID = (select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year +and Cast(m.FiscalMonthCode as int) <= Cast((Select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '14cbd1a1-15e9-411d-9fea-78cecaadf7e7')as int) -- OB_Months_Loaded +and f.TimeClassID = 1 +--CID 1 +) as data +PIVOT +( +SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) +) as pvt + +UNION ALL + +select + [EntityID], +[DepartmentID], + [DepartmentCode], + [AccountID], + [AccountCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from +( SELECT [EntityID],[DepartmentID], [DepartmentCode], [AccountID], [AccountCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], m.MonthColumnName, [Value],f.[HistoryItemGUID] +FROM [int].[FactGlobalStatistics] f +inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID +--CID 1 +where 1=1 +and f.FiscalYearID = (select dbs.setting - 1 from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year - 1 +or f.FiscalYearID = (select dbs.setting + 1 from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year + 1 +--CID 1 +) as data +PIVOT +( +SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) +) as pvt + +UNION ALL + +select + [EntityID], +[DepartmentID], + [DepartmentCode], + [AccountID], + [AccountCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from +( SELECT [EntityID],[DepartmentID], [DepartmentCode], [AccountID], [AccountCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], m.MonthColumnName, [Value],f.[HistoryItemGUID] +FROM [int].[FactGlobalStatistics] f +inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID +--CID 1 +where 1=1 +and f.FiscalYearID = (select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year +and f.TimeClassID = 2 +--CID 1 +) as data +PIVOT +( +SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) +) as pvt +GO + + +--------------------------------------------- + +-- int.viewFactOBPayorGroupPivoted +/************************************************************ +** Author: jgerber +** Create Date: 2013-10-14 +** Description: Pivoted view of Payor Group to allow for easy sampling into structure +** Last Modified: 2016-12-12 +** GM Release: 2013-11-18 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-12-12 srk D-04896 Filtering out months that are not part of YTD months loaded +** 2 2018-04-03 sdominsk D-06562 Add cast the setting as an integer. +*************************************************************/ +CREATE view [int].[viewFactOBPayorGroupPivoted] as + +select + [OBReimbursementPlanID], + [ReimbursementPlan], + [CareSettingID], + [CareSettingCode], + [PayorGroupID], + [PayorGroupCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + [OBForeCastDetailID], + [OBForeCastDetailCode], + [PatientClassID], + [PatientClassCode], + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from + ( + SELECT + [OBReimbursementPlanID], [ReimbursementPlan], + [CareSettingID],[CareSettingCode], + [PayorGroupID], [PayorGroupCode], + [FiscalYearID], [FiscalYearCode], + [TimeClassID], [TimeClassCode], + [OBForeCastDetailID], [OBForeCastDetailCode], + [PatientClassID], [PatientClassCode], + m.MonthColumnName, + [Value], + f.[HistoryItemGUID] + FROM + [int].[FactOBPayorGroup] f + inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID + --CID 1 + where 1=1 + and f.FiscalYearID = (select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year + and Cast(m.FiscalMonthCode as int) <= Cast((Select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '14cbd1a1-15e9-411d-9fea-78cecaadf7e7')as int) -- OB_Months_Loaded + and f.TimeClassID = 1 + --CID 1 + ) as data + PIVOT + ( + SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) + ) as pvt + + UNION ALL + + select + [OBReimbursementPlanID], + [ReimbursementPlan], + [CareSettingID], + [CareSettingCode], + [PayorGroupID], + [PayorGroupCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + [OBForeCastDetailID], + [OBForeCastDetailCode], + [PatientClassID], + [PatientClassCode], + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from + ( + SELECT + [OBReimbursementPlanID], [ReimbursementPlan], + [CareSettingID],[CareSettingCode], + [PayorGroupID], [PayorGroupCode], + [FiscalYearID], [FiscalYearCode], + [TimeClassID], [TimeClassCode], + [OBForeCastDetailID], [OBForeCastDetailCode], + [PatientClassID], [PatientClassCode], + m.MonthColumnName, + [Value], + f.[HistoryItemGUID] + FROM + [int].[FactOBPayorGroup] f + inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID + --CID 1 + where 1=1 + and f.FiscalYearID = (select dbs.setting - 1 from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year - 1 + or f.FiscalYearID = (select dbs.setting + 1 from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year + 1 + --CID 1 + ) as data + PIVOT + ( + SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) + ) as pvt + + UNION ALL + + select + [OBReimbursementPlanID], + [ReimbursementPlan], + [CareSettingID], + [CareSettingCode], + [PayorGroupID], + [PayorGroupCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + [OBForeCastDetailID], + [OBForeCastDetailCode], + [PatientClassID], + [PatientClassCode], + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from + ( + SELECT + [OBReimbursementPlanID], [ReimbursementPlan], + [CareSettingID],[CareSettingCode], + [PayorGroupID], [PayorGroupCode], + [FiscalYearID], [FiscalYearCode], + [TimeClassID], [TimeClassCode], + [OBForeCastDetailID], [OBForeCastDetailCode], + [PatientClassID], [PatientClassCode], + m.MonthColumnName, + [Value], + f.[HistoryItemGUID] + FROM + [int].[FactOBPayorGroup] f + inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID + --CID 1 + where 1=1 + and f.FiscalYearID = (select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year + and f.TimeClassID = 2 + --CID 1 + ) as data + PIVOT + ( + SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) + ) as pvt +GO + + +--------------------------------------------- + +-- int.viewFactOBPayorPivoted +/************************************************************ +** Author: jgerber +** Create Date: 2013-10-14 +** Description: Pivoted view of Payor to allow for easy sampling into structure +** Last Modified: 2016-12-12 +** GM Release: 2013-11-18 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-12-12 SRK D-04896 Filtering out months that are not part of YTD months loaded +** 2 2018-04-03 sdominsk D-06562 Add cast the setting as an integer. +*************************************************************/ +CREATE view [int].[viewFactOBPayorPivoted] as + +select + [OBReimbursementPlanID], + [ReimbursementPlan], + [CareSettingID], + [CareSettingCode], + [PayorID], + [PayorCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + [OBForeCastDetailID], + [OBForeCastDetailCode], + [PatientClassID], + [PatientClassCode], + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from + ( + SELECT + [OBReimbursementPlanID], [ReimbursementPlan], + [CareSettingID],[CareSettingCode], + [PayorID], [PayorCode], + [FiscalYearID], [FiscalYearCode], + [TimeClassID], [TimeClassCode], + [OBForeCastDetailID], [OBForeCastDetailCode], + [PatientClassID], [PatientClassCode], + m.MonthColumnName, + [Value], + f.[HistoryItemGUID] + FROM + [int].[FactOBPayor] f + inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID + --CID 1 + where 1=1 + and f.FiscalYearID = (select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year + and Cast(m.FiscalMonthCode as int) <= Cast((Select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '14cbd1a1-15e9-411d-9fea-78cecaadf7e7')as int) -- OB_Months_Loaded + and f.TimeClassID = 1 + --CID 1 + ) as data + PIVOT + ( + SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) + ) as pvt + + UNION ALL + +select + [OBReimbursementPlanID], + [ReimbursementPlan], + [CareSettingID], + [CareSettingCode], + [PayorID], + [PayorCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + [OBForeCastDetailID], + [OBForeCastDetailCode], + [PatientClassID], + [PatientClassCode], + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from + ( + SELECT + [OBReimbursementPlanID], [ReimbursementPlan], + [CareSettingID],[CareSettingCode], + [PayorID], [PayorCode], + [FiscalYearID], [FiscalYearCode], + [TimeClassID], [TimeClassCode], + [OBForeCastDetailID], [OBForeCastDetailCode], + [PatientClassID], [PatientClassCode], + m.MonthColumnName, + [Value], + f.[HistoryItemGUID] + FROM + [int].[FactOBPayor] f + inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID + --CID 1 + where 1=1 + and f.FiscalYearID = (select dbs.setting - 1 from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year - 1 + or f.FiscalYearID = (select dbs.setting + 1 from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year + 1 + --CID 1 + ) as data + PIVOT + ( + SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) + ) as pvt + + UNION ALL + + select + [OBReimbursementPlanID], + [ReimbursementPlan], + [CareSettingID], + [CareSettingCode], + [PayorID], + [PayorCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + [OBForeCastDetailID], + [OBForeCastDetailCode], + [PatientClassID], + [PatientClassCode], + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from + ( + SELECT + [OBReimbursementPlanID], [ReimbursementPlan], + [CareSettingID],[CareSettingCode], + [PayorID], [PayorCode], + [FiscalYearID], [FiscalYearCode], + [TimeClassID], [TimeClassCode], + [OBForeCastDetailID], [OBForeCastDetailCode], + [PatientClassID], [PatientClassCode], + m.MonthColumnName, + [Value], + f.[HistoryItemGUID] + FROM + [int].[FactOBPayor] f + inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID + --CID 1 + where 1=1 + and f.FiscalYearID = (select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year + and f.TimeClassID = 2 + --CID 1 + ) as data + PIVOT + ( + SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) + ) as pvt +GO + + +--------------------------------------------- + +-- int.viewFactPayorSummaryPivoted +create view int.viewFactPayorSummaryPivoted as + +select + [DepartmentID], + [DepartmentCode], + [AccountRollupID], + [AccountRollupCode], + [FiscalYearID], + [FiscalYearCode], + [PatientTypeRollupID], + [PatientTypeRollupCode], + [PayorGroupID], + [PayorGroupCode], + [UnitTypeID], + [UnitType], + [TimeClassID], + [TimeClassCode], + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from +( +SELECT + DepartmentID, + DepartmentCode, + AccountRollupID, + AccountRollupCode, + FiscalYearID, + FiscalYearCode, + PatientTypeRollupID, + PatientTypeRollupCode, + PayorGroupID, + PayorGroupCode, + TimeClassID, + TimeClassCode, + UnitTypeID, + UnitType, + m.MonthColumnName, + Value, + f.HistoryItemGUID +FROM [int].[FactPayorSummary] f +inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID ) as data +PIVOT +( +SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) +) as pvt +GO + + +--------------------------------------------- + +-- int.viewFactPhysicianSummaryPivoted +create view int.viewFactPhysicianSummaryPivoted as + +select + DepartmentID, + DepartmentCode, + PatientTypeRollupID, + PatientTypeRollupCode, + AccountRollupID, + AccountRollupCode, + PhysicianGroupID, + PhysicianGroupCode, + UnitTypeID, + UnitType, + TimeClassID, + TimeClassCode, + FiscalYearID, + FiscalYearCode, + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from +( +SELECT + DepartmentID, + DepartmentCode, + PatientTypeRollupID, + PatientTypeRollupCode, + AccountRollupID, + AccountRollupCode, + PhysicianGroupID, + PhysicianGroupCode, + UnitTypeID, + UnitType, + TimeClassID, + TimeClassCode, + FiscalYearID, + FiscalYearCode, + m.MonthColumnName, + Value, + f.HistoryItemGUID +FROM [int].[FactPhysicianSummary] f +inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID ) as data +PIVOT +( +SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) +) as pvt +GO + + +--------------------------------------------- + +-- int.viewFactProviderPivoted +/************************************************************ +** Author: Ramya Amancharla +** Create Date: 2013-08-26 +** Description: Pivoted view for sampling +** Last Modified: 2016-12-12 +** GM Release: 2013-11 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 11/12/2013 ramancharla Removing UnitTypeID +** 2 2016-12-12 skandimalla D04896 Filtering out months that are not part of YTD months loaded +** 3 2018-04-03 sdominsk D-06562 Add cast the setting as an integer.  +*************************************************************/ + +CREATE view [int].[viewFactProviderPivoted] as + +select + OBForecastDetailID, + ProviderID, + FiscalMonthID, + TimeClassID, + DepartmentID, + FiscalYearID, + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from +( SELECT OBForecastDetailID, ProviderID, f.FiscalMonthID, TimeClassID, DepartmentID, FiscalYearID,m.MonthColumnName, [Value],f.[HistoryItemGUID] +FROM [int].[FactImportProvider] f +inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID +--CID 2 +where 1=1 +and f.FiscalYearID = (select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year +and Cast(m.FiscalMonthCode as int) <= Cast((Select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '14cbd1a1-15e9-411d-9fea-78cecaadf7e7')as int)-- OB_Months_Loaded +and f.TimeClassID = 1 +--CID 2 +) as data +PIVOT +( +SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) +) as pvt + +UNION ALL + +select + OBForecastDetailID, + ProviderID, + FiscalMonthID, + TimeClassID, + DepartmentID, + FiscalYearID, + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from +( SELECT OBForecastDetailID, ProviderID, f.FiscalMonthID, TimeClassID, DepartmentID, FiscalYearID,m.MonthColumnName, [Value],f.[HistoryItemGUID] +FROM [int].[FactImportProvider] f +inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID +--CID 2 +where 1=1 +and f.FiscalYearID = (select dbs.setting - 1 from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year - 1 +or f.FiscalYearID = (select dbs.setting + 1 from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year + 1 +--CID 2 +) as data +PIVOT +( +SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) +) as pvt + +UNION ALL + +select + OBForecastDetailID, + ProviderID, + FiscalMonthID, + TimeClassID, + DepartmentID, + FiscalYearID, + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from +( SELECT OBForecastDetailID, ProviderID, f.FiscalMonthID, TimeClassID, DepartmentID, FiscalYearID,m.MonthColumnName, [Value],f.[HistoryItemGUID] +FROM [int].[FactImportProvider] f +inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID +--CID 2 +where 1=1 +and f.FiscalYearID = (select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year +and f.TimeClassID = 2 +--CID 2 +) as data +PIVOT +( +SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) +) as pvt +GO + + +--------------------------------------------- + +-- int.viewFactSPDirectRollingISAccountUnpivoted +create View [int].[viewFactSPDirectRollingISAccountUnpivoted] As +select + [SPRollingForecastPlanID] + , [SPRollingForecastPlanName] + , [AccountRollupID] + , [SPAccountRollupName] + , [UnitTypeID] + , [UnitType] + , [TimeClassID] + , [TimeClassCode] + , [FiscalYearID] + , [FiscalYearCode] + , fm.FiscalMonthID + , fm.FiscalMonthCode + , Value +FROM + (SELECT * FROM [int].[FactSPDirectRollingISAccount] source) As PIV + UNPIVOT(VALUE FOR MonthColumnName IN ([ValueMonth01], [ValueMonth02], [ValueMonth03], [ValueMonth04], [ValueMonth05], [ValueMonth06], [ValueMonth07], [ValueMonth08], [ValueMonth09], [ValueMonth10], [ValueMonth11], [ValueMonth12])) As f + inner join fw.DimFiscalMonth fm on f.MonthColumnName=fm.MonthColumnName +GO + + +--------------------------------------------- + +-- int.viewFactSPDirectRollingISPayorUnpivoted +create View [int].[viewFactSPDirectRollingISPayorUnpivoted] As +select + [SPRollingForecastPlanID] + , [SPRollingForecastPlanName] + , [AccountRollupID] + , [SPAccountRollupName] + , [PatientTypeRollupID] + , [PatientTypeRollupCode] + , [PayorGroupID] + , [PayorGroupCode] + , [UnitTypeID] + , [UnitType] + , [TimeClassID] + , [TimeClassCode] + , [FiscalYearID] + , [FiscalYearCode] + , fm.FiscalMonthID + , fm.FiscalMonthCode + , Value +FROM + (SELECT * FROM [int].[FactSPDirectRollingISPayor] source) As PIV + UNPIVOT(VALUE FOR MonthColumnName IN ([ValueMonth01], [ValueMonth02], [ValueMonth03], [ValueMonth04], [ValueMonth05], [ValueMonth06], [ValueMonth07], [ValueMonth08], [ValueMonth09], [ValueMonth10], [ValueMonth11], [ValueMonth12])) As f + inner join fw.DimFiscalMonth fm on f.MonthColumnName=fm.MonthColumnName +GO + + +--------------------------------------------- + +-- int.viewFactSPDirectRollingISPhysicianUnpivoted +Create View [int].[viewFactSPDirectRollingISPhysicianUnpivoted] As +select + [SPRollingForecastPlanID] + , [SPRollingForecastPlanName] + , [AccountRollupID] + , [SPAccountRollupName] + , [PatientTypeRollupID] + , [PatientTypeRollupCode] + , [PhysicianGroupID] + , [PhysicianGroupCode] + , [UnitTypeID] + , [UnitType] + , [TimeClassID] + , [TimeClassCode] + , [FiscalYearID] + , [FiscalYearCode] + , fm.FiscalMonthID + , fm.FiscalMonthCode + , Value +FROM + (SELECT * FROM [int].[FactSPDirectRollingISPhysician] source) As PIV + UNPIVOT(VALUE FOR MonthColumnName IN ([ValueMonth01], [ValueMonth02], [ValueMonth03], [ValueMonth04], [ValueMonth05], [ValueMonth06], [ValueMonth07], [ValueMonth08], [ValueMonth09], [ValueMonth10], [ValueMonth11], [ValueMonth12])) As f + inner join fw.DimFiscalMonth fm on f.MonthColumnName='Value'+fm.MonthColumnName +GO + + +--------------------------------------------- + +-- int.viewFactSPDirectRollingISStaffingUnpivoted +create View [int].[viewFactSPDirectRollingISStaffingUnpivoted] As +select + [SPRollingForecastPlanID] + , [SPRollingForecastPlanName] + , [AccountRollupID] + , [SPAccountRollupName] + , [JobCodeGroupID] + , [JobCodeGroup] + , [UnitTypeID] + , [UnitType] + , [TimeClassID] + , [TimeClassCode] + , [FiscalYearID] + , [FiscalYearCode] + , fm.FiscalMonthID + , fm.FiscalMonthCode + , Value +FROM + (SELECT * FROM [int].[FactSPDirectRollingISStaffing] source) As PIV + UNPIVOT(VALUE FOR MonthColumnName IN ([ValueMonth01], [ValueMonth02], [ValueMonth03], [ValueMonth04], [ValueMonth05], [ValueMonth06], [ValueMonth07], [ValueMonth08], [ValueMonth09], [ValueMonth10], [ValueMonth11], [ValueMonth12])) As f + inner join fw.DimFiscalMonth fm on f.MonthColumnName=fm.MonthColumnName +GO + + +--------------------------------------------- + +-- int.viewFactServiceLinePivoted +/************************************************************ +** Author: ramancharla +** Create Date: 2013-10-11 +** Description: Service Line view used to pivot the imported data to get it ready to sample into the Service Line Models +** Last Modified: 2016-12-12 +** GM Release: 2013-11-18 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 11/22/13 ramancharla removing unit type +** 2 05/29/13 bparrott removing entity, adding department, added payor, payor group, forecast detail , account rolup +** 3 10/14/2014 blewis removing payor, payor group, forecast detail , account rolup +** 4 2016-12-12 skandimalla D-04896 Filtering out months that are not part of YTD months loaded +** 5 2018-04-03 sdominsk D-06562 Add cast the setting as an integer. +*************************************************************/ + +CREATE view [int].[viewFactServiceLinePivoted] as + +--------------Actual YTD-------------------------- +select + --EntityID, + --EntityCode, + DepartmentID, + DepartmentCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + AgeCohortID, + AgeCohort, + PatientClassID, + PatientClassCode, + MedicalSurgicalID, + MedSurg, + ServiceLineID, + ServiceLine, +--added Payor, Payor Group, Forecast Detail, Account Rollup + --PayorID, + --PayorCode, + --PayorGroupID, + --PayorGroupCode, + OBForecastDetailID, + ForecastDetail, + --AccountRollupID, + --AccountRollupCode, + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from +( +SELECT +-- EntityID, +-- EntityCode, + DepartmentID, + DepartmentCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + AgeCohortID, + AgeCohort, + PatientClassID, + PatientClassCode, + MedicalSurgicalID, + MedSurg, + ServiceLineID, + ServiceLine, +--added Payor, Payor Group, Forecast Detail, Account Rollup + --PayorID, + --PayorCode, + --PayorGroupID, + --PayorGroupCode, + OBForecastDetailID, + ForecastDetail, + --AccountRollupID, + --AccountRollupCode, + m.MonthColumnName, + Value, + f.HistoryItemGUID +FROM [int].[FactServiceLine] f +inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID +--CID 4 +where 1=1 +and f.FiscalYearID = (select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year +and Cast(m.FiscalMonthCode as int) <= Cast((Select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '14cbd1a1-15e9-411d-9fea-78cecaadf7e7')as int) -- OB_Months_Loaded +and f.TimeClassID = 1 +--CID 4 +)as data + +PIVOT +( +SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) +) as pvt + +UNION ALL + +--------------Actual Prior Year and Budget for Next Year-------------------------- + +select + --EntityID, + --EntityCode, + DepartmentID, + DepartmentCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + AgeCohortID, + AgeCohort, + PatientClassID, + PatientClassCode, + MedicalSurgicalID, + MedSurg, + ServiceLineID, + ServiceLine, +--added Payor, Payor Group, Forecast Detail, Account Rollup + --PayorID, + --PayorCode, + --PayorGroupID, + --PayorGroupCode, + OBForecastDetailID, + ForecastDetail, + --AccountRollupID, + --AccountRollupCode, + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from +( +SELECT +-- EntityID, +-- EntityCode, + DepartmentID, + DepartmentCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + AgeCohortID, + AgeCohort, + PatientClassID, + PatientClassCode, + MedicalSurgicalID, + MedSurg, + ServiceLineID, + ServiceLine, +--added Payor, Payor Group, Forecast Detail, Account Rollup + --PayorID, + --PayorCode, + --PayorGroupID, + --PayorGroupCode, + OBForecastDetailID, + ForecastDetail, + --AccountRollupID, + --AccountRollupCode, + m.MonthColumnName, + Value, + f.HistoryItemGUID +FROM [int].[FactServiceLine] f +inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID +--CID 4 +where 1=1 +and f.FiscalYearID = (select dbs.setting - 1 from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year - 1 +or f.FiscalYearID = (select dbs.setting + 1 from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year + 1 +--CID 4 +)as data + +PIVOT +( +SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) +) as pvt + +UNION ALL + +--------------Budget for Current Year-------------------------- + +select + --EntityID, + --EntityCode, + DepartmentID, + DepartmentCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + AgeCohortID, + AgeCohort, + PatientClassID, + PatientClassCode, + MedicalSurgicalID, + MedSurg, + ServiceLineID, + ServiceLine, +--added Payor, Payor Group, Forecast Detail, Account Rollup + --PayorID, + --PayorCode, + --PayorGroupID, + --PayorGroupCode, + OBForecastDetailID, + ForecastDetail, + --AccountRollupID, + --AccountRollupCode, + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from +( +SELECT +-- EntityID, +-- EntityCode, + DepartmentID, + DepartmentCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + AgeCohortID, + AgeCohort, + PatientClassID, + PatientClassCode, + MedicalSurgicalID, + MedSurg, + ServiceLineID, + ServiceLine, +--added Payor, Payor Group, Forecast Detail, Account Rollup + --PayorID, + --PayorCode, + --PayorGroupID, + --PayorGroupCode, + OBForecastDetailID, + ForecastDetail, + --AccountRollupID, + --AccountRollupCode, + m.MonthColumnName, + Value, + f.HistoryItemGUID +FROM [int].[FactServiceLine] f +inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID +--CID 4 +where 1=1 +and f.FiscalYearID = (select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year +and f.TimeClassID = 2 +--CID 4 +)as data + +PIVOT +( +SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) +) as pvt +GO + + +--------------------------------------------- + +-- int.viewFactStaffPivoted +CREATE view [int].[viewFactStaffPivoted] as + +select +[DepartmentID], + [DepartmentCode], + [jobcodeID], + [jobCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from +( SELECT [DepartmentID], [DepartmentCode], [JobCodeID], [JobCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], m.MonthColumnName, [Value],f.[HistoryItemGUID] +FROM [int].[FactStaffing] f +inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID ) as data +PIVOT +( +SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) +) as pvt +GO + + +--------------------------------------------- + +-- int.viewFactStaffingPivoted +/** Change History +************************************************************************************************************************************** +** CID Date Author WI Description +** 1 2013-10-04 JG Should only pull from Staffing table since ByPayPeriod will be sampled into Staffing table +** 2 2016-12-12 SK D-04896 Filtering out months that are not part of YTD months loaded +** 3 2017-03-10 srk D-05679 Filtering out budget for next year. Budget for next year should be generated as output data + by the model so it does not need to be imported. +** 4 2017-04-26 srk D-05900 Include filter for next year's budget data so ABB Baseline data gets sampled +** 5 2017-11-16 sdominsk D-06589 Change script in the "Budget for Next Year -- ABB Only-" section. + Should looking for setting 'Baseline data source is loaded - GL' from [dbo].[TemplateSettings] but not from [ob].[SystemSetting]. + And should be pulled only Timeclass 18 (Baseline Budget). +** 5 2018-04-03 sdominsk D-06562 Add cast the setting as an integer. +** 6 2019-03-27 OV B-22369 Data from AP is pulled if both "Is ABB Enabled" = 1 and "AP Preview Enabled" = 0. +**************************************************************************************************************************************/ + +CREATE view [int].[viewFactStaffingPivoted] as + + +/*------------Actual YTD--------------------------*/ +SELECT DepartmentID + ,DepartmentCode + ,JobCodeID + ,JobCode + ,PayCodeID + ,PayCode + ,FiscalYearID + ,FiscalYearCode + ,TimeClassID + ,TimeClassCode + ,UnitTypeID + ,UnitType + ,EmployeeID + ,ISNULL(Month01, 0) [ValueMonth01] + ,ISNULL(Month02, 0) [ValueMonth02] + ,ISNULL(Month03, 0) [ValueMonth03] + ,ISNULL(Month04, 0) [ValueMonth04] + ,ISNULL(Month05, 0) [ValueMonth05] + ,ISNULL(Month06, 0) [ValueMonth06] + ,ISNULL(Month07, 0) [ValueMonth07] + ,ISNULL(Month08, 0) [ValueMonth08] + ,ISNULL(Month09, 0) [ValueMonth09] + ,ISNULL(Month10, 0) [ValueMonth10] + ,ISNULL(Month11, 0) [ValueMonth11] + ,ISNULL(Month12, 0) [ValueMonth12] + ,ISNULL(Month00, 0) [ValueYearly] + ,(ISNULL(Month01, 0) + ISNULL(Month02, 0) + ISNULL(Month03, 0) + ISNULL(Month04, 0) + ISNULL(Month05, 0) + ISNULL(Month06, 0) + ISNULL(Month07, 0) + ISNULL(Month08, 0) + ISNULL(Month09, 0) + ISNULL(Month10, 0) + ISNULL(Month11, 0) + ISNULL(Month12, 0) + ISNULL(Month00, 0)) AS [ValueTotal] + ,[HistoryItemGUID] +FROM ( + SELECT DepartmentID + ,DepartmentCode + ,JobCodeID + ,JobCode + ,PayCodeID + ,PayCode + ,FiscalYearID + ,FiscalYearCode + ,TimeClassID + ,TimeClassCode + ,UnitTypeID + ,UnitType + ,m.MonthColumnName + ,Value + ,EmployeeID + ,f.HistoryItemGUID + FROM [int].[FactStaffing] f + INNER JOIN fw.DimFiscalMonth m ON m.FiscalMonthID = f.FiscalMonthID + /*CID 2*/ WHERE 1 = 1 + AND f.FiscalYearID = ( + SELECT dbs.setting + FROM [dbo].[DBSetting] dbs + WHERE dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62' + ) /* OB_Current_Year*/ + AND Cast(m.FiscalMonthCode AS INT) <= Cast(( + SELECT dbs.setting + FROM [dbo].[DBSetting] dbs + WHERE dbs.DBSettingGUID = '14cbd1a1-15e9-411d-9fea-78cecaadf7e7' + ) AS INT) /* OB_Months_Loaded*/ + AND f.TimeClassID = 1 /*CID 2*/ + ) AS data +PIVOT(SUM(Value) FOR MonthColumnName IN ( + [Month01] + ,[Month02] + ,[Month03] + ,[Month04] + ,[Month05] + ,[Month06] + ,[Month07] + ,[Month08] + ,[Month09] + ,[Month10] + ,[Month11] + ,[Month12] + ,[Month00] + )) AS pvt + +UNION ALL + +/*------------Actual Prior Year--------------------------*/ +SELECT DepartmentID + ,DepartmentCode + ,JobCodeID + ,JobCode + ,PayCodeID + ,PayCode + ,FiscalYearID + ,FiscalYearCode + ,TimeClassID + ,TimeClassCode + ,UnitTypeID + ,UnitType + ,EmployeeID + ,ISNULL(Month01, 0) [ValueMonth01] + ,ISNULL(Month02, 0) [ValueMonth02] + ,ISNULL(Month03, 0) [ValueMonth03] + ,ISNULL(Month04, 0) [ValueMonth04] + ,ISNULL(Month05, 0) [ValueMonth05] + ,ISNULL(Month06, 0) [ValueMonth06] + ,ISNULL(Month07, 0) [ValueMonth07] + ,ISNULL(Month08, 0) [ValueMonth08] + ,ISNULL(Month09, 0) [ValueMonth09] + ,ISNULL(Month10, 0) [ValueMonth10] + ,ISNULL(Month11, 0) [ValueMonth11] + ,ISNULL(Month12, 0) [ValueMonth12] + ,ISNULL(Month00, 0) [ValueYearly] + ,(ISNULL(Month01, 0) + ISNULL(Month02, 0) + ISNULL(Month03, 0) + ISNULL(Month04, 0) + ISNULL(Month05, 0) + ISNULL(Month06, 0) + ISNULL(Month07, 0) + ISNULL(Month08, 0) + ISNULL(Month09, 0) + ISNULL(Month10, 0) + ISNULL(Month11, 0) + ISNULL(Month12, 0) + ISNULL(Month00, 0)) AS [ValueTotal] + ,[HistoryItemGUID] +FROM ( + SELECT DepartmentID + ,DepartmentCode + ,JobCodeID + ,JobCode + ,PayCodeID + ,PayCode + ,FiscalYearID + ,FiscalYearCode + ,TimeClassID + ,TimeClassCode + ,UnitTypeID + ,UnitType + ,m.MonthColumnName + ,Value + ,EmployeeID + ,f.HistoryItemGUID + FROM [int].[FactStaffing] f + INNER JOIN fw.DimFiscalMonth m ON m.FiscalMonthID = f.FiscalMonthID + /*CID 2*/ WHERE 1 = 1 + AND f.FiscalYearID = ( + SELECT dbs.setting - 1 + FROM [dbo].[DBSetting] dbs + WHERE dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62' + ) /*CID 2*/ + ) AS data +PIVOT(SUM(Value) FOR MonthColumnName IN ( + [Month01] + ,[Month02] + ,[Month03] + ,[Month04] + ,[Month05] + ,[Month06] + ,[Month07] + ,[Month08] + ,[Month09] + ,[Month10] + ,[Month11] + ,[Month12] + ,[Month00] + )) AS pvt + +UNION ALL + +/*------------Budget for Next Year -- ABB Only--------------------------*/ +SELECT DepartmentID + ,DepartmentCode + ,JobCodeID + ,JobCode + ,PayCodeID + ,PayCode + ,FiscalYearID + ,FiscalYearCode + ,TimeClassID + ,TimeClassCode + ,UnitTypeID + ,UnitType + ,EmployeeID + ,ISNULL(Month01, 0) [ValueMonth01] + ,ISNULL(Month02, 0) [ValueMonth02] + ,ISNULL(Month03, 0) [ValueMonth03] + ,ISNULL(Month04, 0) [ValueMonth04] + ,ISNULL(Month05, 0) [ValueMonth05] + ,ISNULL(Month06, 0) [ValueMonth06] + ,ISNULL(Month07, 0) [ValueMonth07] + ,ISNULL(Month08, 0) [ValueMonth08] + ,ISNULL(Month09, 0) [ValueMonth09] + ,ISNULL(Month10, 0) [ValueMonth10] + ,ISNULL(Month11, 0) [ValueMonth11] + ,ISNULL(Month12, 0) [ValueMonth12] + ,ISNULL(Month00, 0) [ValueYearly] + ,(ISNULL(Month01, 0) + ISNULL(Month02, 0) + ISNULL(Month03, 0) + ISNULL(Month04, 0) + ISNULL(Month05, 0) + ISNULL(Month06, 0) + ISNULL(Month07, 0) + ISNULL(Month08, 0) + ISNULL(Month09, 0) + ISNULL(Month10, 0) + ISNULL(Month11, 0) + ISNULL(Month12, 0) + ISNULL(Month00, 0)) AS [ValueTotal] + ,[HistoryItemGUID] +FROM ( + SELECT DepartmentID + ,DepartmentCode + ,JobCodeID + ,JobCode + ,PayCodeID + ,PayCode + ,FiscalYearID + ,FiscalYearCode + ,TimeClassID + ,TimeClassCode + ,UnitTypeID + ,UnitType + ,m.MonthColumnName + ,Value + ,EmployeeID + ,f.HistoryItemGUID + FROM [int].[FactStaffing] f + INNER JOIN fw.DimFiscalMonth m ON m.FiscalMonthID = f.FiscalMonthID + /*CID 2*/ WHERE 1 = 1 /*CID 3*/ + AND f.FiscalYearID = ( + SELECT dbs.setting + 1 + FROM [dbo].[DBSetting] dbs + WHERE dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62' + ) /* OB_Current_Year + 1*/ + AND ( + EXISTS ( + SELECT TOP 1 1 + FROM [dbo].[TemplateSettings] + WHERE SettingID = 'Baseline data source is loaded - GL' + AND TemplateGUID = 'C397FA93-F151-4751-AD36-7A34AA7EE3EF' + AND Value = 1 + ) + OR (EXISTS ( + SELECT TOP 1 1 + FROM [fp].[SystemSetting] + WHERE (Name = 'Is ABB Enabled' AND Value = '1') ) + AND + EXISTS ( + SELECT TOP 1 1 + FROM [fp].[SystemSetting] + WHERE (Name = 'AP Preview Enabled' AND Value = '0') ) + ) + ) + AND f.TimeClassID = 18 /*CID 2*/ + ) AS data +PIVOT(SUM(Value) FOR MonthColumnName IN ( + [Month01] + ,[Month02] + ,[Month03] + ,[Month04] + ,[Month05] + ,[Month06] + ,[Month07] + ,[Month08] + ,[Month09] + ,[Month10] + ,[Month11] + ,[Month12] + ,[Month00] + )) AS pvt +/*CID 4*/ + +UNION ALL + +/*------------Budget for Current Year--------------------------*/ +SELECT DepartmentID + ,DepartmentCode + ,JobCodeID + ,JobCode + ,PayCodeID + ,PayCode + ,FiscalYearID + ,FiscalYearCode + ,TimeClassID + ,TimeClassCode + ,UnitTypeID + ,UnitType + ,EmployeeID + ,ISNULL(Month01, 0) [ValueMonth01] + ,ISNULL(Month02, 0) [ValueMonth02] + ,ISNULL(Month03, 0) [ValueMonth03] + ,ISNULL(Month04, 0) [ValueMonth04] + ,ISNULL(Month05, 0) [ValueMonth05] + ,ISNULL(Month06, 0) [ValueMonth06] + ,ISNULL(Month07, 0) [ValueMonth07] + ,ISNULL(Month08, 0) [ValueMonth08] + ,ISNULL(Month09, 0) [ValueMonth09] + ,ISNULL(Month10, 0) [ValueMonth10] + ,ISNULL(Month11, 0) [ValueMonth11] + ,ISNULL(Month12, 0) [ValueMonth12] + ,ISNULL(Month00, 0) [ValueYearly] + ,(ISNULL(Month01, 0) + ISNULL(Month02, 0) + ISNULL(Month03, 0) + ISNULL(Month04, 0) + ISNULL(Month05, 0) + ISNULL(Month06, 0) + ISNULL(Month07, 0) + ISNULL(Month08, 0) + ISNULL(Month09, 0) + ISNULL(Month10, 0) + ISNULL(Month11, 0) + ISNULL(Month12, 0) + ISNULL(Month00, 0)) AS [ValueTotal] + ,[HistoryItemGUID] +FROM ( + SELECT DepartmentID + ,DepartmentCode + ,JobCodeID + ,JobCode + ,PayCodeID + ,PayCode + ,FiscalYearID + ,FiscalYearCode + ,TimeClassID + ,TimeClassCode + ,UnitTypeID + ,UnitType + ,m.MonthColumnName + ,Value + ,EmployeeID + ,f.HistoryItemGUID + FROM [int].[FactStaffing] f + INNER JOIN fw.DimFiscalMonth m ON m.FiscalMonthID = f.FiscalMonthID + /*CID 2*/ WHERE 1 = 1 + AND f.FiscalYearID = ( + SELECT dbs.setting + FROM [dbo].[DBSetting] dbs + WHERE dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62' + ) /* OB_Current_Year*/ + AND f.TimeClassID = 2 /*CID 2*/ + ) AS data +PIVOT(SUM(Value) FOR MonthColumnName IN ( + [Month01] + ,[Month02] + ,[Month03] + ,[Month04] + ,[Month05] + ,[Month06] + ,[Month07] + ,[Month08] + ,[Month09] + ,[Month10] + ,[Month11] + ,[Month12] + ,[Month00] + )) AS pvt +GO + + +--------------------------------------------- + +-- int.viewFactStaffingSummaryPivoted +CREATE view [int].[viewFactStaffingSummaryPivoted] as + +select + DepartmentID, + DepartmentCode, + JobCodeGroupID, + JobCodeGroup, + AccountRollupID, + AccountRollupCode, + FiscalYearID, + FiscalYearCode, + [TimeClassID], + [TimeClassCode], + UnitTypeID, + UnitType, + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + [HistoryItemGUID] +from +( +SELECT + DepartmentID, + DepartmentCode, + JobCodeGroupID, + JobCodeGroup, + AccountRollupID, + AccountRollupCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + UnitTypeID, + UnitType, + m.MonthColumnName, + Value, + f.HistoryItemGUID +FROM [int].[FactStaffingSummary] f +inner join fw.DimFiscalMonth m on m.FiscalMonthID=f.FiscalMonthID ) as data +PIVOT +( +SUM(Value) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) +) as pvt +GO + + +--------------------------------------------- + +-- int.viewFactStaffingValuesPivoted +CREATE VIEW int.viewFactStaffingValuesPivoted +AS +SELECT + pv.DepartmentID, + pv.JobCodeID, + pv.PayCodeID, + pv.FiscalYearID, + pv.TimeClassID, + pv.UnitTypeID, + ISNULL(pv.Month01, 0) as Month01, + ISNULL(pv.Month02, 0) as Month02, + ISNULL(pv.Month03, 0) as Month03, + ISNULL(pv.Month04, 0) as Month04, + ISNULL(pv.Month05, 0) as Month05, + ISNULL(pv.Month06, 0) as Month06, + ISNULL(pv.Month07, 0) as Month07, + ISNULL(pv.Month08, 0) as Month08, + ISNULL(pv.Month09, 0) as Month09, + ISNULL(pv.Month10, 0) as Month10, + ISNULL(pv.Month11, 0) as Month11, + ISNULL(pv.Month12, 0) as Month12 +FROM ( + SELECT + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeID, + fs.FiscalYearID, + fs.TimeClassID, + fs.UnitTypeID, + fm.MonthColumnName, + fs.Value + FROM [int].[FactStaffing] fs + INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = fs.FiscalMonthID + ) data +PIVOT +(SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv +GO + + +--------------------------------------------- + +-- int.viewFactStatisticPivoted +CREATE view [int].[viewFactStatisticPivoted] as +/************************************************************ +** Author: Unknown +** Create Date: +** Description: The pivoted view that is used by the Stat account sampling view/proc +** Last Modified: 2016-12-12 +** GM Release: 2016.2.3 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-06-01 cbb D-04383 Remove history item guid +** 2 2016-12-12 srk D-04896 Filtering out months that are not part of YTD months loaded +** 3 2018-03-0 sdominsk D-06562 Cast the setting as an integer for dbs.setting .  +*************************************************************/ +--------------Actual YTD-------------------------- +select + [DepartmentID], + [DepartmentCode], + [AccountID], + [AccountCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + '00000000-0000-0000-0000-000000000000' as [HistoryItemGUID] -- CID 1 +from + ( + SELECT + [DepartmentID], + [DepartmentCode], + [AccountID], + [AccountCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + m.MonthColumnName, + [Value] + --,f.[HistoryItemGUID] -- CID 1 + FROM [int].[FactStatistic] f + inner join fw.DimFiscalMonth m + on m.FiscalMonthID=f.FiscalMonthID +--CID 1 +where 1=1 +and f.FiscalYearID = (select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year +and Cast(m.FiscalMonthCode as int) <= Cast((Select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '14cbd1a1-15e9-411d-9fea-78cecaadf7e7')as int) -- OB_Months_Loaded +and f.TimeClassID = 1 +--CID 1 + ) as data + PIVOT + ( + SUM(Value) + for MonthColumnName in + ( + [Month01], + [Month02], + [Month03], + [Month04], + [Month05], + [Month06], + [Month07], + [Month08], + [Month09], + [Month10], + [Month11], + [Month12], + [Month00] + ) + ) as pvt + +UNION ALL + + +--------------Actual Prior Year and Budget for Next Year-------------------------- +select + [DepartmentID], + [DepartmentCode], + [AccountID], + [AccountCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + '00000000-0000-0000-0000-000000000000' as [HistoryItemGUID] -- CID 1 +from + ( + SELECT + [DepartmentID], + [DepartmentCode], + [AccountID], + [AccountCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + m.MonthColumnName, + [Value] + --,f.[HistoryItemGUID] -- CID 1 + FROM [int].[FactStatistic] f + inner join fw.DimFiscalMonth m + on m.FiscalMonthID=f.FiscalMonthID + --CID 2 + where 1=1 + and f.FiscalYearID = (select dbs.setting - 1 from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year - 1 + or f.FiscalYearID = (select dbs.setting + 1 from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year + 1 + --CID 2 + ) as data + PIVOT + ( + SUM(Value) + for MonthColumnName in + ( + [Month01], + [Month02], + [Month03], + [Month04], + [Month05], + [Month06], + [Month07], + [Month08], + [Month09], + [Month10], + [Month11], + [Month12], + [Month00] + ) + ) as pvt + +UNION ALL + +--------------Budget for Current Year-------------------------- + +select + [DepartmentID], + [DepartmentCode], + [AccountID], + [AccountCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + ISNULL(Month00, 0) [ValueYearly], + (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [ValueTotal], + '00000000-0000-0000-0000-000000000000' as [HistoryItemGUID] -- CID 1 +from + ( + SELECT + [DepartmentID], + [DepartmentCode], + [AccountID], + [AccountCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + m.MonthColumnName, + [Value] + --,f.[HistoryItemGUID] -- CID 1 + FROM [int].[FactStatistic] f + inner join fw.DimFiscalMonth m + on m.FiscalMonthID=f.FiscalMonthID + --CID 2 + where 1=1 + and f.FiscalYearID = (select dbs.setting from [dbo].[DBSetting] dbs where dbs.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') -- OB_Current_Year + and f.TimeClassID = 2 + --CID 2 + ) as data + PIVOT + ( + SUM(Value) + for MonthColumnName in + ( + [Month01], + [Month02], + [Month03], + [Month04], + [Month05], + [Month06], + [Month07], + [Month08], + [Month09], + [Month10], + [Month11], + [Month12], + [Month00] + ) + ) as pvt +GO + + +--------------------------------------------- + +-- int.viewImport_ADT_Data_Import_Accepted +CREATE VIEW [int].[viewImport_ADT_Data_Import_Accepted] AS + SELECT I.* from [int].[Import_93097e23_eabb_43f3_8f3d_c79ceb19edd9_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_ADT_Data_Import_Rejected +CREATE VIEW [int].[viewImport_ADT_Data_Import_Rejected] AS + SELECT I.* from [int].[Import_93097e23_eabb_43f3_8f3d_c79ceb19edd9_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_APC_Accepted +CREATE VIEW [int].[viewImport_APC_Accepted] AS + SELECT I.* from [int].[Import_91875e90_a5cb_4d45_a93f_bacaf3d6e5ab_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_APC_Rejected +CREATE VIEW [int].[viewImport_APC_Rejected] AS + SELECT I.* from [int].[Import_91875e90_a5cb_4d45_a93f_bacaf3d6e5ab_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_APR_DRG_Accepted +CREATE VIEW [int].[viewImport_APR_DRG_Accepted] AS + SELECT I.* from [int].[Import_a57ad3ab_478b_4682_8de1_eb11594a1e63_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_APR_DRG_Rejected +CREATE VIEW [int].[viewImport_APR_DRG_Rejected] AS + SELECT I.* from [int].[Import_a57ad3ab_478b_4682_8de1_eb11594a1e63_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_AP_Accepted +CREATE VIEW [int].[viewImport_AP_Accepted] AS + SELECT I.* from [int].[Import_FF885362_3CD2_49C1_9F71_34E52704459F_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_AP_Detail__Account__Accepted +CREATE VIEW [int].[viewImport_AP_Detail__Account__Accepted] AS + SELECT I.* from [int].[Import_a2170c4d_524b_43bf_ae0c_3dc41add37c7_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_AP_Detail__Account__Rejected +CREATE VIEW [int].[viewImport_AP_Detail__Account__Rejected] AS + SELECT I.* from [int].[Import_a2170c4d_524b_43bf_ae0c_3dc41add37c7_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_AP_Detail__Department_Accepted +CREATE VIEW [int].[viewImport_AP_Detail__Department_Accepted] AS + SELECT I.* from [int].[Import_31918c69_255b_4d8b_8466_2807769456f3_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_AP_Detail__Department_Rejected +CREATE VIEW [int].[viewImport_AP_Detail__Department_Rejected] AS + SELECT I.* from [int].[Import_31918c69_255b_4d8b_8466_2807769456f3_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_AP_Detail__Entity_Accepted +CREATE VIEW [int].[viewImport_AP_Detail__Entity_Accepted] AS + SELECT I.* from [int].[Import_ba58afbc_6795_44c2_b20f_d750b58352c7_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_AP_Detail__Entity_Rejected +CREATE VIEW [int].[viewImport_AP_Detail__Entity_Rejected] AS + SELECT I.* from [int].[Import_ba58afbc_6795_44c2_b20f_d750b58352c7_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_AP_Rejected +CREATE VIEW [int].[viewImport_AP_Rejected] AS + SELECT I.* from [int].[Import_ff885362_3cd2_49c1_9f71_34e52704459f_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Account_Class_Accepted +CREATE VIEW [int].[viewImport_Account_Class_Accepted] AS + SELECT I.* from [int].[Import_8d09af27_cbe4_4298_b143_82153df07736_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Account_Class_Rejected +CREATE VIEW [int].[viewImport_Account_Class_Rejected] AS + SELECT I.* from [int].[Import_8d09af27_cbe4_4298_b143_82153df07736_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Account_Dimension_Accepted +CREATE VIEW [int].[viewImport_Account_Dimension_Accepted] AS + SELECT I.* from [int].[Import_046c1e49_22d9_4307_9e6c_ddece0c81814_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Account_Dimension_Rejected +CREATE VIEW [int].[viewImport_Account_Dimension_Rejected] AS + SELECT I.* from [int].[Import_046c1e49_22d9_4307_9e6c_ddece0c81814_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Account_Status_Accepted +CREATE VIEW [int].[viewImport_Account_Status_Accepted] AS + SELECT I.* from [int].[Import_083e2fa5_387a_4303_b12d_e57fbecddaba_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Account_Status_Rejected +CREATE VIEW [int].[viewImport_Account_Status_Rejected] AS + SELECT I.* from [int].[Import_083e2fa5_387a_4303_b12d_e57fbecddaba_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Account_Type_Accepted +CREATE VIEW [int].[viewImport_Account_Type_Accepted] AS + SELECT I.* from [int].[Import_04ec6ca3_4c91_4618_a243_3fef8e4ae8a2_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Account_Type_Rejected +CREATE VIEW [int].[viewImport_Account_Type_Rejected] AS + SELECT I.* from [int].[Import_04ec6ca3_4c91_4618_a243_3fef8e4ae8a2_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Admit_Source_Accepted +CREATE VIEW [int].[viewImport_Admit_Source_Accepted] AS + SELECT I.* from [int].[Import_42301852_f1c6_4162_a412_4c138f64c24c_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Admit_Source_Rejected +CREATE VIEW [int].[viewImport_Admit_Source_Rejected] AS + SELECT I.* from [int].[Import_42301852_f1c6_4162_a412_4c138f64c24c_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Admit_Type_Accepted +CREATE VIEW [int].[viewImport_Admit_Type_Accepted] AS + SELECT I.* from [int].[Import_364e6242_32c1_4b1e_9bf1_4e73dbf75f81_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Admit_Type_Rejected +CREATE VIEW [int].[viewImport_Admit_Type_Rejected] AS + SELECT I.* from [int].[Import_364e6242_32c1_4b1e_9bf1_4e73dbf75f81_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Bill_Area_Accepted +CREATE VIEW [int].[viewImport_Bill_Area_Accepted] AS + SELECT I.* from [int].[Import_4062e0de_46b1_49fc_9ac4_edf3ffe20041_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Bill_Area_Rejected +CREATE VIEW [int].[viewImport_Bill_Area_Rejected] AS + SELECT I.* from [int].[Import_4062e0de_46b1_49fc_9ac4_edf3ffe20041_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Bill_Status_Accepted +CREATE VIEW [int].[viewImport_Bill_Status_Accepted] AS + SELECT I.* from [int].[Import_76b17c6b_646d_46af_83b1_fab576c5c95e_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Bill_Status_Rejected +CREATE VIEW [int].[viewImport_Bill_Status_Rejected] AS + SELECT I.* from [int].[Import_76b17c6b_646d_46af_83b1_fab576c5c95e_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_CAP_Manufacturer_Import_Accepted +CREATE VIEW [int].[viewImport_CAP_Manufacturer_Import_Accepted] AS + SELECT I.* from [int].[Import_d9774449_2043_4a3a_96c1_e94d4d84dd0d_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_CAP_Manufacturer_Import_Rejected +CREATE VIEW [int].[viewImport_CAP_Manufacturer_Import_Rejected] AS + SELECT I.* from [int].[Import_d9774449_2043_4a3a_96c1_e94d4d84dd0d_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_CAP_Vendor_Import_Accepted +CREATE VIEW [int].[viewImport_CAP_Vendor_Import_Accepted] AS + SELECT I.* from [int].[Import_b9234962_9264_4e66_9b23_0e36044a0680_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_CAP_Vendor_Import_Rejected +CREATE VIEW [int].[viewImport_CAP_Vendor_Import_Rejected] AS + SELECT I.* from [int].[Import_b9234962_9264_4e66_9b23_0e36044a0680_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_CPT_Accepted +CREATE VIEW [int].[viewImport_CPT_Accepted] AS + SELECT I.* from [int].[Import_4a72918d_ad78_49ea_987e_606968768bb7_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_CPT_Rejected +CREATE VIEW [int].[viewImport_CPT_Rejected] AS + SELECT I.* from [int].[Import_4a72918d_ad78_49ea_987e_606968768bb7_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Cerner_Patient_ADT_Accepted +CREATE VIEW [int].[viewImport_Cerner_Patient_ADT_Accepted] AS + SELECT I.* from [int].[Import_65bd3825_3026_4ea7_9f30_167f2203c7a8_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Cerner_Patient_ADT_Rejected +CREATE VIEW [int].[viewImport_Cerner_Patient_ADT_Rejected] AS + SELECT I.* from [int].[Import_65bd3825_3026_4ea7_9f30_167f2203c7a8_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Charge_Code_Accepted +CREATE VIEW [int].[viewImport_Charge_Code_Accepted] AS + SELECT I.* from [int].[Import_b95a048a_c805_48d4_b5b8_f9e7c3d7b2e1_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Charge_Code_Rejected +CREATE VIEW [int].[viewImport_Charge_Code_Rejected] AS + SELECT I.* from [int].[Import_b95a048a_c805_48d4_b5b8_f9e7c3d7b2e1_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Charge_Code_Type_Accepted +CREATE VIEW [int].[viewImport_Charge_Code_Type_Accepted] AS + SELECT I.* from [int].[Import_e3d00bc7_4bf4_4974_83d1_65f381fba65a_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Charge_Code_Type_Rejected +CREATE VIEW [int].[viewImport_Charge_Code_Type_Rejected] AS + SELECT I.* from [int].[Import_e3d00bc7_4bf4_4974_83d1_65f381fba65a_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Chart_String___Department_Accepted +CREATE VIEW [int].[viewImport_Chart_String___Department_Accepted] AS + SELECT I.* from [int].[Import_9e8131b0_aa80_4ddf_82cb_0a302b5c9ea6_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Chart_String___Department_Rejected +CREATE VIEW [int].[viewImport_Chart_String___Department_Rejected] AS + SELECT I.* from [int].[Import_9e8131b0_aa80_4ddf_82cb_0a302b5c9ea6_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Chart_String___Entity_Accepted +CREATE VIEW [int].[viewImport_Chart_String___Entity_Accepted] AS + SELECT I.* from [int].[Import_32dc9972_08dd_47a3_af0d_48656eef1ef4_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Chart_String___Entity_Rejected +CREATE VIEW [int].[viewImport_Chart_String___Entity_Rejected] AS + SELECT I.* from [int].[Import_32dc9972_08dd_47a3_af0d_48656eef1ef4_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Chart_String___Fund_Accepted +CREATE VIEW [int].[viewImport_Chart_String___Fund_Accepted] AS + SELECT I.* from [int].[Import_c8c7331d_d553_41e5_8987_df917c2653ea_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Chart_String___Fund_Rejected +CREATE VIEW [int].[viewImport_Chart_String___Fund_Rejected] AS + SELECT I.* from [int].[Import_c8c7331d_d553_41e5_8987_df917c2653ea_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Chart_String___Home_Department_Accepted +CREATE VIEW [int].[viewImport_Chart_String___Home_Department_Accepted] AS + SELECT I.* from [int].[Import_467c497f_8ff0_48a8_bc2c_81e557a0bf46_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Chart_String___Home_Department_Rejected +CREATE VIEW [int].[viewImport_Chart_String___Home_Department_Rejected] AS + SELECT I.* from [int].[Import_467c497f_8ff0_48a8_bc2c_81e557a0bf46_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Chart_String___Program_Accepted +CREATE VIEW [int].[viewImport_Chart_String___Program_Accepted] AS + SELECT I.* from [int].[Import_3c96d49a_097c_4eee_9f09_a4bf38c1ce90_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Chart_String___Program_Rejected +CREATE VIEW [int].[viewImport_Chart_String___Program_Rejected] AS + SELECT I.* from [int].[Import_3c96d49a_097c_4eee_9f09_a4bf38c1ce90_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Chart_String___Project_Accepted +CREATE VIEW [int].[viewImport_Chart_String___Project_Accepted] AS + SELECT I.* from [int].[Import_f8fc007c_d092_4b2b_ac8f_546453a60deb_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Chart_String___Project_Rejected +CREATE VIEW [int].[viewImport_Chart_String___Project_Rejected] AS + SELECT I.* from [int].[Import_f8fc007c_d092_4b2b_ac8f_546453a60deb_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Claim_ICD_10_Diagnostic_Detail_Accepted +CREATE VIEW [int].[viewImport_Claim_ICD_10_Diagnostic_Detail_Accepted] AS + SELECT I.* from [int].[Import_6707e9d7_b3b8_4c79_a81d_debcc0f5a9d5_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Claim_ICD_10_Diagnostic_Detail_Rejected +CREATE VIEW [int].[viewImport_Claim_ICD_10_Diagnostic_Detail_Rejected] AS + SELECT I.* from [int].[Import_6707e9d7_b3b8_4c79_a81d_debcc0f5a9d5_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Claim_ICD_10_Procedural_Detail_Accepted +CREATE VIEW [int].[viewImport_Claim_ICD_10_Procedural_Detail_Accepted] AS + SELECT I.* from [int].[Import_aa3d4fd6_2a9f_4c72_ab29_b4b8782aa034_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Claim_ICD_10_Procedural_Detail_Rejected +CREATE VIEW [int].[viewImport_Claim_ICD_10_Procedural_Detail_Rejected] AS + SELECT I.* from [int].[Import_aa3d4fd6_2a9f_4c72_ab29_b4b8782aa034_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Claim_Line_Item_Detail_Accepted +CREATE VIEW [int].[viewImport_Claim_Line_Item_Detail_Accepted] AS + SELECT I.* from [int].[Import_4ea3d011_7b53_4397_9c6b_998109c5f1a7_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Claim_Line_Item_Detail_Rejected +CREATE VIEW [int].[viewImport_Claim_Line_Item_Detail_Rejected] AS + SELECT I.* from [int].[Import_4ea3d011_7b53_4397_9c6b_998109c5f1a7_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Claim_Number_Accepted +CREATE VIEW [int].[viewImport_Claim_Number_Accepted] AS + SELECT I.* from [int].[Import_73cb6477_0c98_43b9_8b3e_afe758a3b795_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Claim_Number_Rejected +CREATE VIEW [int].[viewImport_Claim_Number_Rejected] AS + SELECT I.* from [int].[Import_73cb6477_0c98_43b9_8b3e_afe758a3b795_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Claim_Patient_Accepted +CREATE VIEW [int].[viewImport_Claim_Patient_Accepted] AS + SELECT I.* from [int].[Import_9d0bade3_2b6b_4133_a72e_251bf38688c4_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Claim_Patient_Encounter_Accepted +CREATE VIEW [int].[viewImport_Claim_Patient_Encounter_Accepted] AS + SELECT I.* from [int].[Import_ef55dbd6_a275_405f_8a96_7f27673dcf57_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Claim_Patient_Encounter_Rejected +CREATE VIEW [int].[viewImport_Claim_Patient_Encounter_Rejected] AS + SELECT I.* from [int].[Import_ef55dbd6_a275_405f_8a96_7f27673dcf57_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Claim_Patient_Rejected +CREATE VIEW [int].[viewImport_Claim_Patient_Rejected] AS + SELECT I.* from [int].[Import_9d0bade3_2b6b_4133_a72e_251bf38688c4_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Claim_Summary_Accepted +CREATE VIEW [int].[viewImport_Claim_Summary_Accepted] AS + SELECT I.* from [int].[Import_f582d6c6_e1af_48cb_8318_568324fe78d6_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Claim_Summary_Rejected +CREATE VIEW [int].[viewImport_Claim_Summary_Rejected] AS + SELECT I.* from [int].[Import_f582d6c6_e1af_48cb_8318_568324fe78d6_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Clinical_Department_Accepted +CREATE VIEW [int].[viewImport_Clinical_Department_Accepted] AS + SELECT I.* from [int].[Import_eb2c2315_5478_4cff_b902_fcda612bc338_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Clinical_Department_Rejected +CREATE VIEW [int].[viewImport_Clinical_Department_Rejected] AS + SELECT I.* from [int].[Import_eb2c2315_5478_4cff_b902_fcda612bc338_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Clinical_to_GL_Department_Crosswalk_Import_Accepted +CREATE VIEW [int].[viewImport_Clinical_to_GL_Department_Crosswalk_Import_Accepted] AS + SELECT I.* from [int].[Import_9ef0ee82_5e42_4b84_9021_f1db7565b167_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Clinical_to_GL_Department_Crosswalk_Import_Rejected +CREATE VIEW [int].[viewImport_Clinical_to_GL_Department_Crosswalk_Import_Rejected] AS + SELECT I.* from [int].[Import_9ef0ee82_5e42_4b84_9021_f1db7565b167_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Coding_Status_Accepted +CREATE VIEW [int].[viewImport_Coding_Status_Accepted] AS + SELECT I.* from [int].[Import_b4a931ce_95cd_4fe2_a527_4f0a8f4793e2_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Coding_Status_Rejected +CREATE VIEW [int].[viewImport_Coding_Status_Rejected] AS + SELECT I.* from [int].[Import_b4a931ce_95cd_4fe2_a527_4f0a8f4793e2_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_DSS_Charge_Detail_Update_Accepted +CREATE VIEW [int].[viewImport_DSS_Charge_Detail_Update_Accepted] AS + SELECT I.* from [int].[Import_84007eba_a8f5_4f76_84a1_bf028b6a9c93_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_DSS_Charge_Detail_Update_Rejected +CREATE VIEW [int].[viewImport_DSS_Charge_Detail_Update_Rejected] AS + SELECT I.* from [int].[Import_84007eba_a8f5_4f76_84a1_bf028b6a9c93_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_DSS_Encounter_Summary_Update_Accepted +CREATE VIEW [int].[viewImport_DSS_Encounter_Summary_Update_Accepted] AS + SELECT I.* from [int].[Import_97fd57ed_7fba_4c16_b253_75a0cc7cd7b8_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_DSS_Encounter_Summary_Update_Rejected +CREATE VIEW [int].[viewImport_DSS_Encounter_Summary_Update_Rejected] AS + SELECT I.* from [int].[Import_97fd57ed_7fba_4c16_b253_75a0cc7cd7b8_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_DSS_Membership_Accepted +CREATE VIEW [int].[viewImport_DSS_Membership_Accepted] AS + SELECT I.* from [int].[Import_098e5edc_7338_4abb_aa38_fd3b959ee894_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_DSS_Membership_Rejected +CREATE VIEW [int].[viewImport_DSS_Membership_Rejected] AS + SELECT I.* from [int].[Import_098e5edc_7338_4abb_aa38_fd3b959ee894_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_DSS_Order_Sets_Accepted +CREATE VIEW [int].[viewImport_DSS_Order_Sets_Accepted] AS + SELECT I.* from [int].[Import_2b3c65b9_1037_4ae6_9fa0_fcd8a7c004fa_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_DSS_Order_Sets_Rejected +CREATE VIEW [int].[viewImport_DSS_Order_Sets_Rejected] AS + SELECT I.* from [int].[Import_2b3c65b9_1037_4ae6_9fa0_fcd8a7c004fa_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_DSS_Physician_Charge_Update_Accepted +CREATE VIEW [int].[viewImport_DSS_Physician_Charge_Update_Accepted] AS + SELECT I.* from [int].[Import_736f6e77_ca1f_482f_aa51_8af8bdd8f7b9_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_DSS_Physician_Charge_Update_Rejected +CREATE VIEW [int].[viewImport_DSS_Physician_Charge_Update_Rejected] AS + SELECT I.* from [int].[Import_736f6e77_ca1f_482f_aa51_8af8bdd8f7b9_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_DSS_Physician_Encounter_Summary_Update_Accepted +CREATE VIEW [int].[viewImport_DSS_Physician_Encounter_Summary_Update_Accepted] AS + SELECT I.* from [int].[Import_97fd57ed_7fba_4c16_b253_75a0cc7cd7b8_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_DSS_Physician_Encounter_Summary_Update_Rejected +CREATE VIEW [int].[viewImport_DSS_Physician_Encounter_Summary_Update_Rejected] AS + SELECT I.* from [int].[Import_97fd57ed_7fba_4c16_b253_75a0cc7cd7b8_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_DSS_Statistic_Accounts_Accepted +CREATE VIEW [int].[viewImport_DSS_Statistic_Accounts_Accepted] AS + SELECT I.* from [int].[Import_58ea5959_ebae_446f_ab99_a6647d7a9158_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_DSS_Statistic_Accounts_Rejected +CREATE VIEW [int].[viewImport_DSS_Statistic_Accounts_Rejected] AS + SELECT I.* from [int].[Import_58ea5959_ebae_446f_ab99_a6647d7a9158_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_DSS_Stats_Accepted +CREATE VIEW [int].[viewImport_DSS_Stats_Accepted] AS + SELECT I.* from [int].[Import_36860a9f_b83d_4b5c_93b3_d4284899ef2f_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_DSS_Stats_Rejected +CREATE VIEW [int].[viewImport_DSS_Stats_Rejected] AS + SELECT I.* from [int].[Import_36860a9f_b83d_4b5c_93b3_d4284899ef2f_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Daily_Staffing_Hours_Import_Accepted +CREATE VIEW [int].[viewImport_Daily_Staffing_Hours_Import_Accepted] AS + SELECT I.* from [int].[Import_b63569de_9f6b_4b0d_afce_82c699ea16b0_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Daily_Staffing_Hours_Import_Rejected +CREATE VIEW [int].[viewImport_Daily_Staffing_Hours_Import_Rejected] AS + SELECT I.* from [int].[Import_b63569de_9f6b_4b0d_afce_82c699ea16b0_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Daily_Statistics___Account_Accepted +CREATE VIEW [int].[viewImport_Daily_Statistics___Account_Accepted] AS + SELECT I.* from [int].[Import_e17d2b59_cbe5_41da_9568_689d4e30f8d1_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Daily_Statistics___Account_Rejected +CREATE VIEW [int].[viewImport_Daily_Statistics___Account_Rejected] AS + SELECT I.* from [int].[Import_e17d2b59_cbe5_41da_9568_689d4e30f8d1_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Daily_Statistics___Department_Accepted +CREATE VIEW [int].[viewImport_Daily_Statistics___Department_Accepted] AS + SELECT I.* from [int].[Import_ad87cc47_84bd_4e70_818f_53878696245a_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Daily_Statistics___Department_Rejected +CREATE VIEW [int].[viewImport_Daily_Statistics___Department_Rejected] AS + SELECT I.* from [int].[Import_ad87cc47_84bd_4e70_818f_53878696245a_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Daily_Statistics___Entity_Accepted +CREATE VIEW [int].[viewImport_Daily_Statistics___Entity_Accepted] AS + SELECT I.* from [int].[Import_6c103280_bb57_41d4_9df2_9792244ed13e_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Daily_Statistics___Entity_Rejected +CREATE VIEW [int].[viewImport_Daily_Statistics___Entity_Rejected] AS + SELECT I.* from [int].[Import_6c103280_bb57_41d4_9df2_9792244ed13e_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Data_Accepted +CREATE VIEW [int].[viewImport_Data_Accepted] AS + SELECT I.* from [int].[Import_c9008ae4_d813_4daf_be6a_e60603ae4291_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Data_Rejected +CREATE VIEW [int].[viewImport_Data_Rejected] AS + SELECT I.* from [int].[Import_c9008ae4_d813_4daf_be6a_e60603ae4291_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Definitions___Charge_Code_Accepted +CREATE VIEW [int].[viewImport_Definitions___Charge_Code_Accepted] AS + SELECT I.* from [int].[Import_bac1cc6d_608a_4326_add4_510301e3dbed_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Definitions___Charge_Code_Rejected +CREATE VIEW [int].[viewImport_Definitions___Charge_Code_Rejected] AS + SELECT I.* from [int].[Import_bac1cc6d_608a_4326_add4_510301e3dbed_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Definitions___Provider_Accepted +CREATE VIEW [int].[viewImport_Definitions___Provider_Accepted] AS + SELECT I.* from [int].[Import_12358a20_dfb4_4557_b5d4_2754fb693e29_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Definitions___Provider_Rejected +CREATE VIEW [int].[viewImport_Definitions___Provider_Rejected] AS + SELECT I.* from [int].[Import_12358a20_dfb4_4557_b5d4_2754fb693e29_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Department_Dimension_Accepted +CREATE VIEW [int].[viewImport_Department_Dimension_Accepted] AS + SELECT I.* from [int].[Import_1a7c67ed_75c5_4f21_b25d_e61463b9e5e3_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Department_Dimension_Rejected +CREATE VIEW [int].[viewImport_Department_Dimension_Rejected] AS + SELECT I.* from [int].[Import_1a7c67ed_75c5_4f21_b25d_e61463b9e5e3_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Department_Rollup_1_Accepted +CREATE VIEW [int].[viewImport_Department_Rollup_1_Accepted] AS + SELECT I.* from [int].[Import_7253c618_9ae8_423b_9496_708b18842228_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Department_Rollup_1_Rejected +CREATE VIEW [int].[viewImport_Department_Rollup_1_Rejected] AS + SELECT I.* from [int].[Import_7253c618_9ae8_423b_9496_708b18842228_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Department_Rollup_2_Accepted +CREATE VIEW [int].[viewImport_Department_Rollup_2_Accepted] AS + SELECT I.* from [int].[Import_bdeff0f2_ed8f_416c_b5ab_ce916c12546c_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Department_Rollup_2_Rejected +CREATE VIEW [int].[viewImport_Department_Rollup_2_Rejected] AS + SELECT I.* from [int].[Import_bdeff0f2_ed8f_416c_b5ab_ce916c12546c_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Department_Rollup_3_Accepted +CREATE VIEW [int].[viewImport_Department_Rollup_3_Accepted] AS + SELECT I.* from [int].[Import_48e437e4_f553_4537_9619_d8d11b494860_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Department_Rollup_3_Rejected +CREATE VIEW [int].[viewImport_Department_Rollup_3_Rejected] AS + SELECT I.* from [int].[Import_48e437e4_f553_4537_9619_d8d11b494860_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Department_Rollup_4_Accepted +CREATE VIEW [int].[viewImport_Department_Rollup_4_Accepted] AS + SELECT I.* from [int].[Import_99caa082_e655_43ee_8ebf_29d1128e9c19_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Department_Rollup_4_Rejected +CREATE VIEW [int].[viewImport_Department_Rollup_4_Rejected] AS + SELECT I.* from [int].[Import_99caa082_e655_43ee_8ebf_29d1128e9c19_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Department_Rollup_5_Accepted +CREATE VIEW [int].[viewImport_Department_Rollup_5_Accepted] AS + SELECT I.* from [int].[Import_6a3ff17b_8b18_41ca_84a1_9006ec32c3ec_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Department_Rollup_5_Rejected +CREATE VIEW [int].[viewImport_Department_Rollup_5_Rejected] AS + SELECT I.* from [int].[Import_6a3ff17b_8b18_41ca_84a1_9006ec32c3ec_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Department_Rollup_6_Accepted +CREATE VIEW [int].[viewImport_Department_Rollup_6_Accepted] AS + SELECT I.* from [int].[Import_bed6f14e_3b4b_4d0e_8b1d_2e49984784b6_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Department_Rollup_6_Rejected +CREATE VIEW [int].[viewImport_Department_Rollup_6_Rejected] AS + SELECT I.* from [int].[Import_bed6f14e_3b4b_4d0e_8b1d_2e49984784b6_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Department___ADT_Accepted +CREATE VIEW [int].[viewImport_Department___ADT_Accepted] AS + SELECT I.* from [int].[Import_13a87531_818d_4bd6_8984_1022370bb34b_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Department___ADT_Rejected +CREATE VIEW [int].[viewImport_Department___ADT_Rejected] AS + SELECT I.* from [int].[Import_13a87531_818d_4bd6_8984_1022370bb34b_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Department___Swipe_Accepted +CREATE VIEW [int].[viewImport_Department___Swipe_Accepted] AS + SELECT I.* from [int].[Import_5a0dd3bd_e215_4507_a115_dfaa6d4dc144_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Department___Swipe_Rejected +CREATE VIEW [int].[viewImport_Department___Swipe_Rejected] AS + SELECT I.* from [int].[Import_5a0dd3bd_e215_4507_a115_dfaa6d4dc144_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Discharge_Destination_Accepted +CREATE VIEW [int].[viewImport_Discharge_Destination_Accepted] AS + SELECT I.* from [int].[Import_f611efd1_6c46_4890_a56c_5d16b62317ef_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Discharge_Destination_Rejected +CREATE VIEW [int].[viewImport_Discharge_Destination_Rejected] AS + SELECT I.* from [int].[Import_f611efd1_6c46_4890_a56c_5d16b62317ef_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Discharge_Status_Accepted +CREATE VIEW [int].[viewImport_Discharge_Status_Accepted] AS + SELECT I.* from [int].[Import_cd6af6f5_bef3_4c36_9d56_8184128dca8c_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Discharge_Status_Rejected +CREATE VIEW [int].[viewImport_Discharge_Status_Rejected] AS + SELECT I.* from [int].[Import_cd6af6f5_bef3_4c36_9d56_8184128dca8c_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_ER_Asset_Accepted +CREATE VIEW [int].[viewImport_ER_Asset_Accepted] AS + SELECT I.* from [int].[Import_ae7c40cc_a69b_4608_bbb1_2b0930874537_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_ER_Asset_Rejected +CREATE VIEW [int].[viewImport_ER_Asset_Rejected] AS + SELECT I.* from [int].[Import_ae7c40cc_a69b_4608_bbb1_2b0930874537_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Employee_Dimension_Accepted +CREATE VIEW [int].[viewImport_Employee_Dimension_Accepted] AS + SELECT I.* from [int].[Import_0c1a0c34_3971_4249_ae11_25f1e62483d3_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Employee_Dimension_Rejected +CREATE VIEW [int].[viewImport_Employee_Dimension_Rejected] AS + SELECT I.* from [int].[Import_0c1a0c34_3971_4249_ae11_25f1e62483d3_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Employee___Job_Code_Accepted +CREATE VIEW [int].[viewImport_Employee___Job_Code_Accepted] AS + SELECT I.* from [int].[Import_bd0795a0_27a1_4f98_9488_905a052059b8_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Employee___Job_Code_Rejected +CREATE VIEW [int].[viewImport_Employee___Job_Code_Rejected] AS + SELECT I.* from [int].[Import_bd0795a0_27a1_4f98_9488_905a052059b8_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Employee___Swipe_Accepted +CREATE VIEW [int].[viewImport_Employee___Swipe_Accepted] AS + SELECT I.* from [int].[Import_7bbbc308_b7ee_4e56_8294_453b090423a2_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Employee___Swipe_Rejected +CREATE VIEW [int].[viewImport_Employee___Swipe_Rejected] AS + SELECT I.* from [int].[Import_7bbbc308_b7ee_4e56_8294_453b090423a2_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Employer_Accepted +CREATE VIEW [int].[viewImport_Employer_Accepted] AS + SELECT I.* from [int].[Import_445b19c4_0c1f_4fa6_ab7d_1efc29601462_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Employer_Rejected +CREATE VIEW [int].[viewImport_Employer_Rejected] AS + SELECT I.* from [int].[Import_445b19c4_0c1f_4fa6_ab7d_1efc29601462_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Employment_Status_Accepted +CREATE VIEW [int].[viewImport_Employment_Status_Accepted] AS + SELECT I.* from [int].[Import_028edf9e_1237_40bc_b705_76fb89c062b2_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Employment_Status_Rejected +CREATE VIEW [int].[viewImport_Employment_Status_Rejected] AS + SELECT I.* from [int].[Import_028edf9e_1237_40bc_b705_76fb89c062b2_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Entity_Accepted +CREATE VIEW [int].[viewImport_Entity_Accepted] AS + SELECT I.* from [int].[Import_59034048_22d5_4297_bad6_711509824ef0_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Entity_Dimension_Accepted +CREATE VIEW [int].[viewImport_Entity_Dimension_Accepted] AS + SELECT I.* from [int].[Import_79987164_cfd1_4850_b843_633b11bbcfef_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Entity_Dimension_Rejected +CREATE VIEW [int].[viewImport_Entity_Dimension_Rejected] AS + SELECT I.* from [int].[Import_79987164_cfd1_4850_b843_633b11bbcfef_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Entity_Rejected +CREATE VIEW [int].[viewImport_Entity_Rejected] AS + SELECT I.* from [int].[Import_59034048_22d5_4297_bad6_711509824ef0_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Epic_Patient_ADT_Accepted +CREATE VIEW [int].[viewImport_Epic_Patient_ADT_Accepted] AS + SELECT I.* from [int].[Import_7f420ecd_81f7_4928_9375_67bc0e6a11d4_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Epic_Patient_ADT_Rejected +CREATE VIEW [int].[viewImport_Epic_Patient_ADT_Rejected] AS + SELECT I.* from [int].[Import_7f420ecd_81f7_4928_9375_67bc0e6a11d4_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Ethnicity_Accepted +CREATE VIEW [int].[viewImport_Ethnicity_Accepted] AS + SELECT I.* from [int].[Import_763b92b1_2509_40c4_b07b_6c8b944c0824_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Ethnicity_Rejected +CREATE VIEW [int].[viewImport_Ethnicity_Rejected] AS + SELECT I.* from [int].[Import_763b92b1_2509_40c4_b07b_6c8b944c0824_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_FP_Provider___Department_Accepted +CREATE VIEW [int].[viewImport_FP_Provider___Department_Accepted] AS + SELECT I.* from [int].[Import_46d6d617_a86b_469b_801e_ed98fc7e1095_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_FP_Provider___Department_Rejected +CREATE VIEW [int].[viewImport_FP_Provider___Department_Rejected] AS + SELECT I.* from [int].[Import_46d6d617_a86b_469b_801e_ed98fc7e1095_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_FP_Provider___Provider_Accepted +CREATE VIEW [int].[viewImport_FP_Provider___Provider_Accepted] AS + SELECT I.* from [int].[Import_4732ad1a_6e60_4d3b_85a4_d4e6b17cf656_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_FP_Provider___Provider_Data_Accepted +CREATE VIEW [int].[viewImport_FP_Provider___Provider_Data_Accepted] AS + SELECT I.* from [int].[Import_21624ee8_8626_4074_913a_803dccd3b257_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_FP_Provider___Provider_Data_Rejected +CREATE VIEW [int].[viewImport_FP_Provider___Provider_Data_Rejected] AS + SELECT I.* from [int].[Import_21624ee8_8626_4074_913a_803dccd3b257_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_FP_Provider___Provider_Line_Item_Accepted +CREATE VIEW [int].[viewImport_FP_Provider___Provider_Line_Item_Accepted] AS + SELECT I.* from [int].[Import_7d5a90f2_0697_4dd6_99b0_dc01ed097ed5_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_FP_Provider___Provider_Line_Item_Rejected +CREATE VIEW [int].[viewImport_FP_Provider___Provider_Line_Item_Rejected] AS + SELECT I.* from [int].[Import_7d5a90f2_0697_4dd6_99b0_dc01ed097ed5_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_FP_Provider___Provider_Rejected +CREATE VIEW [int].[viewImport_FP_Provider___Provider_Rejected] AS + SELECT I.* from [int].[Import_4732ad1a_6e60_4d3b_85a4_d4e6b17cf656_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Financial_Class_Accepted +CREATE VIEW [int].[viewImport_Financial_Class_Accepted] AS + SELECT I.* from [int].[Import_f135ce47_b163_466e_948a_d37edb01191f_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Financial_Class_Rejected +CREATE VIEW [int].[viewImport_Financial_Class_Rejected] AS + SELECT I.* from [int].[Import_f135ce47_b163_466e_948a_d37edb01191f_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Financial_Service_Line_Cost_Accepted +CREATE VIEW [int].[viewImport_Financial_Service_Line_Cost_Accepted] AS + SELECT I.* from [int].[Import_52e46d2d_2300_4763_b192_5b9b7a40c7b9_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Financial_Service_Line_Cost_Rejected +CREATE VIEW [int].[viewImport_Financial_Service_Line_Cost_Rejected] AS + SELECT I.* from [int].[Import_52e46d2d_2300_4763_b192_5b9b7a40c7b9_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Accepted +CREATE VIEW [int].[viewImport_GL_Accepted] AS + SELECT I.* from [int].[Import_c7524bbc_9670_4441_bbb6_f81ab44ffeb9_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Detail___Account_Accepted +CREATE VIEW [int].[viewImport_GL_Detail___Account_Accepted] AS + SELECT I.* from [int].[Import_30df7c2e_f1d8_4a95_a60e_d6cf45df5c63_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Detail___Account_Rejected +CREATE VIEW [int].[viewImport_GL_Detail___Account_Rejected] AS + SELECT I.* from [int].[Import_30df7c2e_f1d8_4a95_a60e_d6cf45df5c63_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Detail___Department_Accepted +CREATE VIEW [int].[viewImport_GL_Detail___Department_Accepted] AS + SELECT I.* from [int].[Import_848aaf1b_5270_4398_ba9e_196ba30e811a_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Detail___Department_Rejected +CREATE VIEW [int].[viewImport_GL_Detail___Department_Rejected] AS + SELECT I.* from [int].[Import_848aaf1b_5270_4398_ba9e_196ba30e811a_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Detail___Entity_Accepted +CREATE VIEW [int].[viewImport_GL_Detail___Entity_Accepted] AS + SELECT I.* from [int].[Import_727bbd93_6161_4798_9cd8_306c12310213_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Detail___Entity_Rejected +CREATE VIEW [int].[viewImport_GL_Detail___Entity_Rejected] AS + SELECT I.* from [int].[Import_727bbd93_6161_4798_9cd8_306c12310213_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Dollars___Account_Dimension_Accepted +CREATE VIEW [int].[viewImport_GL_Dollars___Account_Dimension_Accepted] AS + SELECT I.* from [int].[Import_74f78355_3946_4c0f_8258_3b4226e350ed_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Dollars___Account_Dimension_Rejected +CREATE VIEW [int].[viewImport_GL_Dollars___Account_Dimension_Rejected] AS + SELECT I.* from [int].[Import_74f78355_3946_4c0f_8258_3b4226e350ed_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Dollars___Department_Dimension_Accepted +CREATE VIEW [int].[viewImport_GL_Dollars___Department_Dimension_Accepted] AS + SELECT I.* from [int].[Import_6e6c926a_b0ed_4f08_b9c6_f8a34c7f3df6_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Dollars___Department_Dimension_Rejected +CREATE VIEW [int].[viewImport_GL_Dollars___Department_Dimension_Rejected] AS + SELECT I.* from [int].[Import_6e6c926a_b0ed_4f08_b9c6_f8a34c7f3df6_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Dollars___Entity_Dimension_Accepted +CREATE VIEW [int].[viewImport_GL_Dollars___Entity_Dimension_Accepted] AS + SELECT I.* from [int].[Import_8ee06a17_968c_4e98_a1ae_8675dba87259_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Dollars___Entity_Dimension_Rejected +CREATE VIEW [int].[viewImport_GL_Dollars___Entity_Dimension_Rejected] AS + SELECT I.* from [int].[Import_8ee06a17_968c_4e98_a1ae_8675dba87259_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Dollars_and_Stats___Account_Dimension_Accepted +CREATE VIEW [int].[viewImport_GL_Dollars_and_Stats___Account_Dimension_Accepted] AS + SELECT I.* from [int].[Import_651d7197_08e9_4d8a_a9dc_0d8b4ef9dbf4_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Dollars_and_Stats___Account_Dimension_Rejected +CREATE VIEW [int].[viewImport_GL_Dollars_and_Stats___Account_Dimension_Rejected] AS + SELECT I.* from [int].[Import_651d7197_08e9_4d8a_a9dc_0d8b4ef9dbf4_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Dollars_and_Stats___Department_Dimension_Accepted +CREATE VIEW [int].[viewImport_GL_Dollars_and_Stats___Department_Dimension_Accepted] AS + SELECT I.* from [int].[Import_88e8e3e7_a7b5_4623_bbea_865ed04889bc_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Dollars_and_Stats___Department_Dimension_Rejected +CREATE VIEW [int].[viewImport_GL_Dollars_and_Stats___Department_Dimension_Rejected] AS + SELECT I.* from [int].[Import_88e8e3e7_a7b5_4623_bbea_865ed04889bc_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Dollars_and_Stats___Entity_Dimension_Accepted +CREATE VIEW [int].[viewImport_GL_Dollars_and_Stats___Entity_Dimension_Accepted] AS + SELECT I.* from [int].[Import_6992d450_167c_49ef_acda_a244db67fa92_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Dollars_and_Stats___Entity_Dimension_Rejected +CREATE VIEW [int].[viewImport_GL_Dollars_and_Stats___Entity_Dimension_Rejected] AS + SELECT I.* from [int].[Import_6992d450_167c_49ef_acda_a244db67fa92_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Rejected +CREATE VIEW [int].[viewImport_GL_Rejected] AS + SELECT I.* from [int].[Import_c7524bbc_9670_4441_bbb6_f81ab44ffeb9_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Statistics___Account_Dimension_Accepted +CREATE VIEW [int].[viewImport_GL_Statistics___Account_Dimension_Accepted] AS + SELECT I.* from [int].[Import_fe8c3254_f36b_4517_a9dd_f1cba0ed8229_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Statistics___Account_Dimension_Rejected +CREATE VIEW [int].[viewImport_GL_Statistics___Account_Dimension_Rejected] AS + SELECT I.* from [int].[Import_fe8c3254_f36b_4517_a9dd_f1cba0ed8229_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Statistics___Department_Dimension_Accepted +CREATE VIEW [int].[viewImport_GL_Statistics___Department_Dimension_Accepted] AS + SELECT I.* from [int].[Import_f3346fe2_dde5_4558_8064_e69f635b3fe4_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Statistics___Department_Dimension_Rejected +CREATE VIEW [int].[viewImport_GL_Statistics___Department_Dimension_Rejected] AS + SELECT I.* from [int].[Import_f3346fe2_dde5_4558_8064_e69f635b3fe4_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Statistics___Entity_Dimension_Accepted +CREATE VIEW [int].[viewImport_GL_Statistics___Entity_Dimension_Accepted] AS + SELECT I.* from [int].[Import_634f38fc_9e5f_42f5_93ec_53364d283496_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_GL_Statistics___Entity_Dimension_Rejected +CREATE VIEW [int].[viewImport_GL_Statistics___Entity_Dimension_Rejected] AS + SELECT I.* from [int].[Import_634f38fc_9e5f_42f5_93ec_53364d283496_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_General_Ledger___Dollars_Accepted +CREATE VIEW [int].[viewImport_General_Ledger___Dollars_Accepted] AS + SELECT I.* from [int].[Import_acdc514d_78d3_454b_8cc7_100827da737b_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_General_Ledger___Dollars_Rejected +CREATE VIEW [int].[viewImport_General_Ledger___Dollars_Rejected] AS + SELECT I.* from [int].[Import_acdc514d_78d3_454b_8cc7_100827da737b_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_General_Ledger___Statistics_Accepted +CREATE VIEW [int].[viewImport_General_Ledger___Statistics_Accepted] AS + SELECT I.* from [int].[Import_0e1cffed_57a5_4e98_a7a6_f4d360516637_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_General_Ledger___Statistics_Rejected +CREATE VIEW [int].[viewImport_General_Ledger___Statistics_Rejected] AS + SELECT I.* from [int].[Import_0e1cffed_57a5_4e98_a7a6_f4d360516637_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Global_Statistics___Account_Dimension_Accepted +CREATE VIEW [int].[viewImport_Global_Statistics___Account_Dimension_Accepted] AS + SELECT I.* from [int].[Import_f36dc91e_9cbb_4f26_a8e5_3075af897c36_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Global_Statistics___Account_Dimension_Rejected +CREATE VIEW [int].[viewImport_Global_Statistics___Account_Dimension_Rejected] AS + SELECT I.* from [int].[Import_f36dc91e_9cbb_4f26_a8e5_3075af897c36_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Global_Statistics___Department_Dimension_Accepted +CREATE VIEW [int].[viewImport_Global_Statistics___Department_Dimension_Accepted] AS + SELECT I.* from [int].[Import_57cffafa_4d7c_483d_b53e_9d7dc1c0a2df_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Global_Statistics___Department_Dimension_Rejected +CREATE VIEW [int].[viewImport_Global_Statistics___Department_Dimension_Rejected] AS + SELECT I.* from [int].[Import_57cffafa_4d7c_483d_b53e_9d7dc1c0a2df_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Global_Statistics___Entity_Dimension_Accepted +CREATE VIEW [int].[viewImport_Global_Statistics___Entity_Dimension_Accepted] AS + SELECT I.* from [int].[Import_941043ef_cd41_407a_9829_5a48eeba9ed6_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Global_Statistics___Entity_Dimension_Rejected +CREATE VIEW [int].[viewImport_Global_Statistics___Entity_Dimension_Rejected] AS + SELECT I.* from [int].[Import_941043ef_cd41_407a_9829_5a48eeba9ed6_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Guarantor_Accepted +CREATE VIEW [int].[viewImport_Guarantor_Accepted] AS + SELECT I.* from [int].[Import_348e7530_aef5_4a94_a08d_a19d176fc3b4_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Guarantor_Rejected +CREATE VIEW [int].[viewImport_Guarantor_Rejected] AS + SELECT I.* from [int].[Import_348e7530_aef5_4a94_a08d_a19d176fc3b4_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Guarantor_Relation_to_Patient_Accepted +CREATE VIEW [int].[viewImport_Guarantor_Relation_to_Patient_Accepted] AS + SELECT I.* from [int].[Import_7a1c5935_8b9f_465d_aaaa_f396602a3f7c_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Guarantor_Relation_to_Patient_Rejected +CREATE VIEW [int].[viewImport_Guarantor_Relation_to_Patient_Rejected] AS + SELECT I.* from [int].[Import_7a1c5935_8b9f_465d_aaaa_f396602a3f7c_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_APC_Accepted +CREATE VIEW [int].[viewImport_HB_APC_Accepted] AS + SELECT I.* from [int].[Import_10d22f81_2a9d_40ce_b50e_b4e2979a1a7b_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_APC_Rejected +CREATE VIEW [int].[viewImport_HB_APC_Rejected] AS + SELECT I.* from [int].[Import_10d22f81_2a9d_40ce_b50e_b4e2979a1a7b_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_CPT_Accepted +CREATE VIEW [int].[viewImport_HB_CPT_Accepted] AS + SELECT I.* from [int].[Import_842beb71_e55e_4072_83f8_ae0e81fa3c83_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_CPT_Rejected +CREATE VIEW [int].[viewImport_HB_CPT_Rejected] AS + SELECT I.* from [int].[Import_842beb71_e55e_4072_83f8_ae0e81fa3c83_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_Charge_Accepted +CREATE VIEW [int].[viewImport_HB_Charge_Accepted] AS + SELECT I.* from [int].[Import_c9de651a_4a0f_45fa_97d3_2ff5c2a7c0a6_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_Charge_Rejected +CREATE VIEW [int].[viewImport_HB_Charge_Rejected] AS + SELECT I.* from [int].[Import_c9de651a_4a0f_45fa_97d3_2ff5c2a7c0a6_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_Department_Def_Accepted +CREATE VIEW [int].[viewImport_HB_Department_Def_Accepted] AS + SELECT I.* from [int].[Import_414ea8b5_e2eb_47b4_a184_3b0ba711eb65_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_Department_Def_Rejected +CREATE VIEW [int].[viewImport_HB_Department_Def_Rejected] AS + SELECT I.* from [int].[Import_414ea8b5_e2eb_47b4_a184_3b0ba711eb65_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_EAPG_Accepted +CREATE VIEW [int].[viewImport_HB_EAPG_Accepted] AS + SELECT I.* from [int].[Import_6518daae_02f6_463a_b0bb_46d5d2811690_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_EAPG_Rejected +CREATE VIEW [int].[viewImport_HB_EAPG_Rejected] AS + SELECT I.* from [int].[Import_6518daae_02f6_463a_b0bb_46d5d2811690_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_Encounter_Summary_Accepted +CREATE VIEW [int].[viewImport_HB_Encounter_Summary_Accepted] AS + SELECT I.* from [int].[Import_2258b00e_cbfa_4561_aa46_ccff5e6be9bc_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_Encounter_Summary_Rejected +CREATE VIEW [int].[viewImport_HB_Encounter_Summary_Rejected] AS + SELECT I.* from [int].[Import_2258b00e_cbfa_4561_aa46_ccff5e6be9bc_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_ICD10_Diagnosis_Accepted +CREATE VIEW [int].[viewImport_HB_ICD10_Diagnosis_Accepted] AS + SELECT I.* from [int].[Import_b3dd76aa_acdf_4af5_b5a6_5e2bc5f770a2_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_ICD10_Diagnosis_Rejected +CREATE VIEW [int].[viewImport_HB_ICD10_Diagnosis_Rejected] AS + SELECT I.* from [int].[Import_b3dd76aa_acdf_4af5_b5a6_5e2bc5f770a2_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_ICD10_Procedure_Accepted +CREATE VIEW [int].[viewImport_HB_ICD10_Procedure_Accepted] AS + SELECT I.* from [int].[Import_f7849bf9_92bc_4d1c_a391_7009e89c7a72_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_ICD10_Procedure_Rejected +CREATE VIEW [int].[viewImport_HB_ICD10_Procedure_Rejected] AS + SELECT I.* from [int].[Import_f7849bf9_92bc_4d1c_a391_7009e89c7a72_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_ICD9_Diagnosis_Accepted +CREATE VIEW [int].[viewImport_HB_ICD9_Diagnosis_Accepted] AS + SELECT I.* from [int].[Import_6612abe2_5105_4737_af57_62c4b75d9166_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_ICD9_Diagnosis_Rejected +CREATE VIEW [int].[viewImport_HB_ICD9_Diagnosis_Rejected] AS + SELECT I.* from [int].[Import_6612abe2_5105_4737_af57_62c4b75d9166_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_ICD9_Procedure_Accepted +CREATE VIEW [int].[viewImport_HB_ICD9_Procedure_Accepted] AS + SELECT I.* from [int].[Import_58ed0522_7856_4041_8c47_38b0fe07e16d_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_ICD9_Procedure_Rejected +CREATE VIEW [int].[viewImport_HB_ICD9_Procedure_Rejected] AS + SELECT I.* from [int].[Import_58ed0522_7856_4041_8c47_38b0fe07e16d_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_Newborn_Accepted +CREATE VIEW [int].[viewImport_HB_Newborn_Accepted] AS + SELECT I.* from [int].[Import_e6cea41d_96f3_4015_9531_9f428d7170a3_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_Newborn_Rejected +CREATE VIEW [int].[viewImport_HB_Newborn_Rejected] AS + SELECT I.* from [int].[Import_e6cea41d_96f3_4015_9531_9f428d7170a3_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_Patient_Accepted +CREATE VIEW [int].[viewImport_HB_Patient_Accepted] AS + SELECT I.* from [int].[Import_75171c9c_2114_432c_a3ac_af18a63e6e3e_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_Patient_Encounter_Accepted +CREATE VIEW [int].[viewImport_HB_Patient_Encounter_Accepted] AS + SELECT I.* from [int].[Import_20a65a06_4893_4ae9_a1c0_3745bfafecd3_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_Patient_Encounter_Rejected +CREATE VIEW [int].[viewImport_HB_Patient_Encounter_Rejected] AS + SELECT I.* from [int].[Import_20a65a06_4893_4ae9_a1c0_3745bfafecd3_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_Patient_Mother_Accepted +CREATE VIEW [int].[viewImport_HB_Patient_Mother_Accepted] AS + SELECT I.* from [int].[Import_338ed6bc_e68a_496f_a148_11c69faf86c2_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_Patient_Mother_Rejected +CREATE VIEW [int].[viewImport_HB_Patient_Mother_Rejected] AS + SELECT I.* from [int].[Import_338ed6bc_e68a_496f_a148_11c69faf86c2_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_Patient_Rejected +CREATE VIEW [int].[viewImport_HB_Patient_Rejected] AS + SELECT I.* from [int].[Import_75171c9c_2114_432c_a3ac_af18a63e6e3e_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_Payment_Accepted +CREATE VIEW [int].[viewImport_HB_Payment_Accepted] AS + SELECT I.* from [int].[Import_98503a8b_709f_451b_b076_e34ca12bce26_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_HB_Payment_Rejected +CREATE VIEW [int].[viewImport_HB_Payment_Rejected] AS + SELECT I.* from [int].[Import_98503a8b_709f_451b_b076_e34ca12bce26_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_ICD10_DX_Accepted +CREATE VIEW [int].[viewImport_ICD10_DX_Accepted] AS + SELECT I.* from [int].[Import_e825cfc3_dda8_4cc7_89e1_18f0b2981840_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_ICD10_DX_Rejected +CREATE VIEW [int].[viewImport_ICD10_DX_Rejected] AS + SELECT I.* from [int].[Import_e825cfc3_dda8_4cc7_89e1_18f0b2981840_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_ICD10_PX_Accepted +CREATE VIEW [int].[viewImport_ICD10_PX_Accepted] AS + SELECT I.* from [int].[Import_7da8cb8f_032f_4770_8ca5_eb99972911c3_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_ICD10_PX_Rejected +CREATE VIEW [int].[viewImport_ICD10_PX_Rejected] AS + SELECT I.* from [int].[Import_7da8cb8f_032f_4770_8ca5_eb99972911c3_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_ICD9_DX_Accepted +CREATE VIEW [int].[viewImport_ICD9_DX_Accepted] AS + SELECT I.* from [int].[Import_22765fae_27dd_4dc1_a62a_d956e1ffc411_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_ICD9_DX_Rejected +CREATE VIEW [int].[viewImport_ICD9_DX_Rejected] AS + SELECT I.* from [int].[Import_22765fae_27dd_4dc1_a62a_d956e1ffc411_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_ICD9_PX_Accepted +CREATE VIEW [int].[viewImport_ICD9_PX_Accepted] AS + SELECT I.* from [int].[Import_a3dda0eb_11dc_4de3_8e90_a187fc846769_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_ICD9_PX_Rejected +CREATE VIEW [int].[viewImport_ICD9_PX_Rejected] AS + SELECT I.* from [int].[Import_a3dda0eb_11dc_4de3_8e90_a187fc846769_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Insurance_Plan_Accepted +CREATE VIEW [int].[viewImport_Insurance_Plan_Accepted] AS + SELECT I.* from [int].[Import_c4f0937d_1cb5_4863_a392_6397b8d05286_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Insurance_Plan_Rejected +CREATE VIEW [int].[viewImport_Insurance_Plan_Rejected] AS + SELECT I.* from [int].[Import_c4f0937d_1cb5_4863_a392_6397b8d05286_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Inventory___Account_Accepted +CREATE VIEW [int].[viewImport_Inventory___Account_Accepted] AS + SELECT I.* from [int].[Import_9325dcb3_1392_44bc_ad7d_6ed528f5c1a4_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Inventory___Account_Rejected +CREATE VIEW [int].[viewImport_Inventory___Account_Rejected] AS + SELECT I.* from [int].[Import_9325dcb3_1392_44bc_ad7d_6ed528f5c1a4_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Inventory___Department_Accepted +CREATE VIEW [int].[viewImport_Inventory___Department_Accepted] AS + SELECT I.* from [int].[Import_07d9cafb_d6cb_4bbf_90ac_7046aa2f240a_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Inventory___Department_Rejected +CREATE VIEW [int].[viewImport_Inventory___Department_Rejected] AS + SELECT I.* from [int].[Import_07d9cafb_d6cb_4bbf_90ac_7046aa2f240a_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Inventory___Entity_Accepted +CREATE VIEW [int].[viewImport_Inventory___Entity_Accepted] AS + SELECT I.* from [int].[Import_4c0b1040_9202_42e6_8cc0_b488ac904805_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Inventory___Entity_Rejected +CREATE VIEW [int].[viewImport_Inventory___Entity_Rejected] AS + SELECT I.* from [int].[Import_4c0b1040_9202_42e6_8cc0_b488ac904805_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Job_Code_Dimension_Accepted +CREATE VIEW [int].[viewImport_Job_Code_Dimension_Accepted] AS + SELECT I.* from [int].[Import_d23efdc3_9d21_412e_a854_78044343b3da_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Job_Code_Dimension_Rejected +CREATE VIEW [int].[viewImport_Job_Code_Dimension_Rejected] AS + SELECT I.* from [int].[Import_d23efdc3_9d21_412e_a854_78044343b3da_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Language_Accepted +CREATE VIEW [int].[viewImport_Language_Accepted] AS + SELECT I.* from [int].[Import_20a3aede_fb89_4581_94af_8e1c876f9581_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Language_Rejected +CREATE VIEW [int].[viewImport_Language_Rejected] AS + SELECT I.* from [int].[Import_20a3aede_fb89_4581_94af_8e1c876f9581_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Location_Accepted +CREATE VIEW [int].[viewImport_Location_Accepted] AS + SELECT I.* from [int].[Import_6579b2fc_0c27_493c_bd5c_957512179500_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Location_Rejected +CREATE VIEW [int].[viewImport_Location_Rejected] AS + SELECT I.* from [int].[Import_6579b2fc_0c27_493c_bd5c_957512179500_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_MR_Import_PO_Detail_Accepted +CREATE VIEW [int].[viewImport_MR_Import_PO_Detail_Accepted] AS + SELECT I.* from [int].[Import_b6e47e1b_9e3a_41c3_954d_bf8e01e0939c_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_MR_Import_PO_Detail_Rejected +CREATE VIEW [int].[viewImport_MR_Import_PO_Detail_Rejected] AS + SELECT I.* from [int].[Import_b6e47e1b_9e3a_41c3_954d_bf8e01e0939c_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_MR___Import___Inventory_Detail_Accepted +CREATE VIEW [int].[viewImport_MR___Import___Inventory_Detail_Accepted] AS + SELECT I.* from [int].[Import_61e83a29_7616_4c97_b8e5_052ba9f2564d_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_MR___Import___Inventory_Detail_Rejected +CREATE VIEW [int].[viewImport_MR___Import___Inventory_Detail_Rejected] AS + SELECT I.* from [int].[Import_61e83a29_7616_4c97_b8e5_052ba9f2564d_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Marital_Status_Accepted +CREATE VIEW [int].[viewImport_Marital_Status_Accepted] AS + SELECT I.* from [int].[Import_6b471f1c_a562_47b8_ba15_f2838ef7612d_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Marital_Status_Rejected +CREATE VIEW [int].[viewImport_Marital_Status_Rejected] AS + SELECT I.* from [int].[Import_6b471f1c_a562_47b8_ba15_f2838ef7612d_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Method_of_Arrival_Accepted +CREATE VIEW [int].[viewImport_Method_of_Arrival_Accepted] AS + SELECT I.* from [int].[Import_14408ff3_5253_4210_b488_0c4d64f8ef29_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Method_of_Arrival_Rejected +CREATE VIEW [int].[viewImport_Method_of_Arrival_Rejected] AS + SELECT I.* from [int].[Import_14408ff3_5253_4210_b488_0c4d64f8ef29_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_NDC_Accepted +CREATE VIEW [int].[viewImport_NDC_Accepted] AS + SELECT I.* from [int].[Import_1552b55e_d263_4431_acfb_f37fd7c9607f_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_NDC_Charge_Code_Accepted +CREATE VIEW [int].[viewImport_NDC_Charge_Code_Accepted] AS + SELECT I.* from [int].[Import_c9f14a1c_353b_4e81_90f6_944c66ff2da7_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_NDC_Charge_Code_Rejected +CREATE VIEW [int].[viewImport_NDC_Charge_Code_Rejected] AS + SELECT I.* from [int].[Import_c9f14a1c_353b_4e81_90f6_944c66ff2da7_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_NDC_Rejected +CREATE VIEW [int].[viewImport_NDC_Rejected] AS + SELECT I.* from [int].[Import_1552b55e_d263_4431_acfb_f37fd7c9607f_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_New_Section_Accepted +CREATE VIEW [int].[viewImport_New_Section_Accepted] AS + SELECT I.* from [int].[Import_0b5e225a_c041_4c5d_a67d_1bbed0e8ed73_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_New_Section_Rejected +CREATE VIEW [int].[viewImport_New_Section_Rejected] AS + SELECT I.* from [int].[Import_0b5e225a_c041_4c5d_a67d_1bbed0e8ed73_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Nurse_Station_Accepted +CREATE VIEW [int].[viewImport_Nurse_Station_Accepted] AS + SELECT I.* from [int].[Import_0af75e75_cbfa_4771_a8e8_19f393d877cd_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Nurse_Station_Rejected +CREATE VIEW [int].[viewImport_Nurse_Station_Rejected] AS + SELECT I.* from [int].[Import_0af75e75_cbfa_4771_a8e8_19f393d877cd_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_CDM___CDM_Data_Accepted +CREATE VIEW [int].[viewImport_OB_CDM___CDM_Data_Accepted] AS + SELECT I.* from [int].[Import_16935f62_5386_4e1d_9b11_1d8d0039a787_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_CDM___CDM_Data_Rejected +CREATE VIEW [int].[viewImport_OB_CDM___CDM_Data_Rejected] AS + SELECT I.* from [int].[Import_16935f62_5386_4e1d_9b11_1d8d0039a787_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_CDM___Charge_Code_Dimension_Accepted +CREATE VIEW [int].[viewImport_OB_CDM___Charge_Code_Dimension_Accepted] AS + SELECT I.* from [int].[Import_9b8857e0_b5fd_432e_a7ea_eaeabfa03478_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_CDM___Charge_Code_Dimension_Rejected +CREATE VIEW [int].[viewImport_OB_CDM___Charge_Code_Dimension_Rejected] AS + SELECT I.* from [int].[Import_9b8857e0_b5fd_432e_a7ea_eaeabfa03478_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_CDM___Department_Dimension_Accepted +CREATE VIEW [int].[viewImport_OB_CDM___Department_Dimension_Accepted] AS + SELECT I.* from [int].[Import_7bce7227_e774_4bc7_9107_ab733ee26967_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_CDM___Department_Dimension_Rejected +CREATE VIEW [int].[viewImport_OB_CDM___Department_Dimension_Rejected] AS + SELECT I.* from [int].[Import_7bce7227_e774_4bc7_9107_ab733ee26967_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_CDM___Entity_Dimension_Accepted +CREATE VIEW [int].[viewImport_OB_CDM___Entity_Dimension_Accepted] AS + SELECT I.* from [int].[Import_648411fe_abe7_4f6e_898a_2f17dad277a1_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_CDM___Entity_Dimension_Rejected +CREATE VIEW [int].[viewImport_OB_CDM___Entity_Dimension_Rejected] AS + SELECT I.* from [int].[Import_648411fe_abe7_4f6e_898a_2f17dad277a1_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_Payor_Group___Payor_Data_Accepted +CREATE VIEW [int].[viewImport_OB_Payor_Group___Payor_Data_Accepted] AS + SELECT I.* from [int].[Import_64d37379_4a27_4762_a96d_db47c63e074a_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_Payor_Group___Payor_Data_Rejected +CREATE VIEW [int].[viewImport_OB_Payor_Group___Payor_Data_Rejected] AS + SELECT I.* from [int].[Import_64d37379_4a27_4762_a96d_db47c63e074a_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_Payor___Payor_Data_Accepted +CREATE VIEW [int].[viewImport_OB_Payor___Payor_Data_Accepted] AS + SELECT I.* from [int].[Import_016181a5_1e9a_4c1e_8876_f0644a86d574_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_Payor___Payor_Data_Rejected +CREATE VIEW [int].[viewImport_OB_Payor___Payor_Data_Rejected] AS + SELECT I.* from [int].[Import_016181a5_1e9a_4c1e_8876_f0644a86d574_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_Payor___Payor_Dimension_Accepted +CREATE VIEW [int].[viewImport_OB_Payor___Payor_Dimension_Accepted] AS + SELECT I.* from [int].[Import_c6d5c3a4_e558_490b_bbb5_7378fb1e597e_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_Payor___Payor_Dimension_Rejected +CREATE VIEW [int].[viewImport_OB_Payor___Payor_Dimension_Rejected] AS + SELECT I.* from [int].[Import_c6d5c3a4_e558_490b_bbb5_7378fb1e597e_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_Provider___Department_Accepted +CREATE VIEW [int].[viewImport_OB_Provider___Department_Accepted] AS + SELECT I.* from [int].[Import_ffc50184_d407_4e99_80f5_dba396459ac2_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_Provider___Department_Rejected +CREATE VIEW [int].[viewImport_OB_Provider___Department_Rejected] AS + SELECT I.* from [int].[Import_ffc50184_d407_4e99_80f5_dba396459ac2_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_Provider___Entity_Accepted +CREATE VIEW [int].[viewImport_OB_Provider___Entity_Accepted] AS + SELECT I.* from [int].[Import_566cab78_e8c0_4586_a6d8_dc0fd4995c08_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_Provider___Entity_Rejected +CREATE VIEW [int].[viewImport_OB_Provider___Entity_Rejected] AS + SELECT I.* from [int].[Import_566cab78_e8c0_4586_a6d8_dc0fd4995c08_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_Provider___Provider_Accepted +CREATE VIEW [int].[viewImport_OB_Provider___Provider_Accepted] AS + SELECT I.* from [int].[Import_a78b1a9d_9d2f_4173_acad_d65732645bfc_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_Provider___Provider_Data_Accepted +CREATE VIEW [int].[viewImport_OB_Provider___Provider_Data_Accepted] AS + SELECT I.* from [int].[Import_10a747b9_9726_4dc4_b1b2_7d79ab4820e3_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_Provider___Provider_Data_Rejected +CREATE VIEW [int].[viewImport_OB_Provider___Provider_Data_Rejected] AS + SELECT I.* from [int].[Import_10a747b9_9726_4dc4_b1b2_7d79ab4820e3_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_Provider___Provider_Rejected +CREATE VIEW [int].[viewImport_OB_Provider___Provider_Rejected] AS + SELECT I.* from [int].[Import_a78b1a9d_9d2f_4173_acad_d65732645bfc_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_Service_Line_Data_Accepted +CREATE VIEW [int].[viewImport_OB_Service_Line_Data_Accepted] AS + SELECT I.* from [int].[Import_aefa0c08_665a_4026_a197_f05b3ed47be8_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_OB_Service_Line_Data_Rejected +CREATE VIEW [int].[viewImport_OB_Service_Line_Data_Rejected] AS + SELECT I.* from [int].[Import_aefa0c08_665a_4026_a197_f05b3ed47be8_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PB_Charge_Accepted +CREATE VIEW [int].[viewImport_PB_Charge_Accepted] AS + SELECT I.* from [int].[Import_23adab15_9aa5_40a8_9244_57af97adc0c9_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PB_Charge_Rejected +CREATE VIEW [int].[viewImport_PB_Charge_Rejected] AS + SELECT I.* from [int].[Import_23adab15_9aa5_40a8_9244_57af97adc0c9_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PB_Department_Def_Accepted +CREATE VIEW [int].[viewImport_PB_Department_Def_Accepted] AS + SELECT I.* from [int].[Import_3cb89960_cb0c_49c4_b703_ce0bd34a336b_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PB_Department_Def_Rejected +CREATE VIEW [int].[viewImport_PB_Department_Def_Rejected] AS + SELECT I.* from [int].[Import_3cb89960_cb0c_49c4_b703_ce0bd34a336b_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PB_Encounter_Summary_Accepted +CREATE VIEW [int].[viewImport_PB_Encounter_Summary_Accepted] AS + SELECT I.* from [int].[Import_65b97fac_1748_4519_aac1_b01a30307411_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PB_Encounter_Summary_Rejected +CREATE VIEW [int].[viewImport_PB_Encounter_Summary_Rejected] AS + SELECT I.* from [int].[Import_65b97fac_1748_4519_aac1_b01a30307411_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PB_ICD10_DX_Accepted +CREATE VIEW [int].[viewImport_PB_ICD10_DX_Accepted] AS + SELECT I.* from [int].[Import_260807f0_9d60_45fd_8637_1fddea525a42_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PB_ICD10_DX_Rejected +CREATE VIEW [int].[viewImport_PB_ICD10_DX_Rejected] AS + SELECT I.* from [int].[Import_260807f0_9d60_45fd_8637_1fddea525a42_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PB_ICD_9_Diagnosis_Accepted +CREATE VIEW [int].[viewImport_PB_ICD_9_Diagnosis_Accepted] AS + SELECT I.* from [int].[Import_0e183be7_ca58_4b8f_99f4_7c8cf40712be_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PB_ICD_9_Diagnosis_Rejected +CREATE VIEW [int].[viewImport_PB_ICD_9_Diagnosis_Rejected] AS + SELECT I.* from [int].[Import_0e183be7_ca58_4b8f_99f4_7c8cf40712be_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PB_Patient_Accepted +CREATE VIEW [int].[viewImport_PB_Patient_Accepted] AS + SELECT I.* from [int].[Import_761ba260_dceb_43cd_8c14_3a6bb32b72aa_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PB_Patient_Encounter_Accepted +CREATE VIEW [int].[viewImport_PB_Patient_Encounter_Accepted] AS + SELECT I.* from [int].[Import_c4014baa_8c39_488e_aa81_c43adcf97537_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PB_Patient_Encounter_Rejected +CREATE VIEW [int].[viewImport_PB_Patient_Encounter_Rejected] AS + SELECT I.* from [int].[Import_c4014baa_8c39_488e_aa81_c43adcf97537_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PB_Patient_Rejected +CREATE VIEW [int].[viewImport_PB_Patient_Rejected] AS + SELECT I.* from [int].[Import_761ba260_dceb_43cd_8c14_3a6bb32b72aa_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PB_Payment_Accepted +CREATE VIEW [int].[viewImport_PB_Payment_Accepted] AS + SELECT I.* from [int].[Import_80d83f16_0bb5_4a5a_80d7_41bb50a3e541_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PB_Payment_Rejected +CREATE VIEW [int].[viewImport_PB_Payment_Rejected] AS + SELECT I.* from [int].[Import_80d83f16_0bb5_4a5a_80d7_41bb50a3e541_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PO_Accepted +CREATE VIEW [int].[viewImport_PO_Accepted] AS + SELECT I.* from [int].[Import_C46AB25F_C509_4D2C_A1A3_E267A37F74A1_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PO_Detail___Account_Accepted +CREATE VIEW [int].[viewImport_PO_Detail___Account_Accepted] AS + SELECT I.* from [int].[Import_a77fa9e4_cb34_423f_8d2b_0a2acd5ce480_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PO_Detail___Account_Rejected +CREATE VIEW [int].[viewImport_PO_Detail___Account_Rejected] AS + SELECT I.* from [int].[Import_a77fa9e4_cb34_423f_8d2b_0a2acd5ce480_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PO_Detail___Department_Accepted +CREATE VIEW [int].[viewImport_PO_Detail___Department_Accepted] AS + SELECT I.* from [int].[Import_98f86655_3c72_43ca_93ca_b8129bd7b892_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PO_Detail___Department_Rejected +CREATE VIEW [int].[viewImport_PO_Detail___Department_Rejected] AS + SELECT I.* from [int].[Import_98f86655_3c72_43ca_93ca_b8129bd7b892_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PO_Detail___Entity_Accepted +CREATE VIEW [int].[viewImport_PO_Detail___Entity_Accepted] AS + SELECT I.* from [int].[Import_b94afad7_d581_4554_8421_54186a8e57dc_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PO_Detail___Entity_Rejected +CREATE VIEW [int].[viewImport_PO_Detail___Entity_Rejected] AS + SELECT I.* from [int].[Import_b94afad7_d581_4554_8421_54186a8e57dc_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_PO_Rejected +CREATE VIEW [int].[viewImport_PO_Rejected] AS + SELECT I.* from [int].[Import_c46ab25f_c509_4d2c_a1a3_e267a37f74a1_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Patient_Type_Accepted +CREATE VIEW [int].[viewImport_Patient_Type_Accepted] AS + SELECT I.* from [int].[Import_d8b61020_2515_4740_a887_c4d533b8ebd6_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Patient_Type_Rejected +CREATE VIEW [int].[viewImport_Patient_Type_Rejected] AS + SELECT I.* from [int].[Import_d8b61020_2515_4740_a887_c4d533b8ebd6_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Pay_Code_Dimension_Accepted +CREATE VIEW [int].[viewImport_Pay_Code_Dimension_Accepted] AS + SELECT I.* from [int].[Import_f8ddbae5_cf68_45e8_9226_65c77cc598ba_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Pay_Code_Dimension_Rejected +CREATE VIEW [int].[viewImport_Pay_Code_Dimension_Rejected] AS + SELECT I.* from [int].[Import_f8ddbae5_cf68_45e8_9226_65c77cc598ba_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Payor_Accepted +CREATE VIEW [int].[viewImport_Payor_Accepted] AS + SELECT I.* from [int].[Import_f5bbaad9_d4db_4e30_bd53_7c750241a0e8_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Payor_Rejected +CREATE VIEW [int].[viewImport_Payor_Rejected] AS + SELECT I.* from [int].[Import_f5bbaad9_d4db_4e30_bd53_7c750241a0e8_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Physician_Accepted +CREATE VIEW [int].[viewImport_Physician_Accepted] AS + SELECT I.* from [int].[Import_453ea40e_995c_4ff3_86be_842479076a78_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Physician_Rejected +CREATE VIEW [int].[viewImport_Physician_Rejected] AS + SELECT I.* from [int].[Import_453ea40e_995c_4ff3_86be_842479076a78_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Physician_Specialty_Accepted +CREATE VIEW [int].[viewImport_Physician_Specialty_Accepted] AS + SELECT I.* from [int].[Import_88098b84_48f4_4a5f_b82f_ea4488a6f06a_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Physician_Specialty_Rejected +CREATE VIEW [int].[viewImport_Physician_Specialty_Rejected] AS + SELECT I.* from [int].[Import_88098b84_48f4_4a5f_b82f_ea4488a6f06a_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Physician_Taxonomy_Accepted +CREATE VIEW [int].[viewImport_Physician_Taxonomy_Accepted] AS + SELECT I.* from [int].[Import_4e10321a_6a92_4c18_8ee2_d6de7db7deb0_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Physician_Taxonomy_Rejected +CREATE VIEW [int].[viewImport_Physician_Taxonomy_Rejected] AS + SELECT I.* from [int].[Import_4e10321a_6a92_4c18_8ee2_d6de7db7deb0_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Place_of_Service_Accepted +CREATE VIEW [int].[viewImport_Place_of_Service_Accepted] AS + SELECT I.* from [int].[Import_26fe1011_4e1d_4cc5_a654_0511f30ad101_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Place_of_Service_Rejected +CREATE VIEW [int].[viewImport_Place_of_Service_Rejected] AS + SELECT I.* from [int].[Import_26fe1011_4e1d_4cc5_a654_0511f30ad101_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Present_on_Admission_Accepted +CREATE VIEW [int].[viewImport_Present_on_Admission_Accepted] AS + SELECT I.* from [int].[Import_1583023d_2bdb_47fc_a35c_58349fe260b2_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Present_on_Admission_Rejected +CREATE VIEW [int].[viewImport_Present_on_Admission_Rejected] AS + SELECT I.* from [int].[Import_1583023d_2bdb_47fc_a35c_58349fe260b2_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Race_Accepted +CREATE VIEW [int].[viewImport_Race_Accepted] AS + SELECT I.* from [int].[Import_8046deb4_8cf5_49a8_8416_bf27e282f4fe_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Race_Rejected +CREATE VIEW [int].[viewImport_Race_Rejected] AS + SELECT I.* from [int].[Import_8046deb4_8cf5_49a8_8416_bf27e282f4fe_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Religion_Accepted +CREATE VIEW [int].[viewImport_Religion_Accepted] AS + SELECT I.* from [int].[Import_48875bd8_0911_4801_8a7b_20863c859544_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Religion_Rejected +CREATE VIEW [int].[viewImport_Religion_Rejected] AS + SELECT I.* from [int].[Import_48875bd8_0911_4801_8a7b_20863c859544_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading_Combined___Physician___Ops_Accepted +CREATE VIEW [int].[viewImport_SP_Direct_Loading_Combined___Physician___Ops_Accepted] AS + SELECT I.* from [int].[Import_45bed270_56ba_4b59_ab31_d6055563f64f_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading_Combined___Physician___Ops_Rejected +CREATE VIEW [int].[viewImport_SP_Direct_Loading_Combined___Physician___Ops_Rejected] AS + SELECT I.* from [int].[Import_45bed270_56ba_4b59_ab31_d6055563f64f_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading_Combined___Physician___RF_Accepted +CREATE VIEW [int].[viewImport_SP_Direct_Loading_Combined___Physician___RF_Accepted] AS + SELECT I.* from [int].[Import_4789e844_91e6_429a_a09a_29d12bc2685d_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading_Combined___Physician___RF_Rejected +CREATE VIEW [int].[viewImport_SP_Direct_Loading_Combined___Physician___RF_Rejected] AS + SELECT I.* from [int].[Import_4789e844_91e6_429a_a09a_29d12bc2685d_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___Bal_Account_Accepted +CREATE VIEW [int].[viewImport_SP_Direct_Loading___Bal_Account_Accepted] AS + SELECT I.* from [int].[Import_72b01d2b_e4b9_4dc6_879c_e55104013e39_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___Bal_Account_Rejected +CREATE VIEW [int].[viewImport_SP_Direct_Loading___Bal_Account_Rejected] AS + SELECT I.* from [int].[Import_72b01d2b_e4b9_4dc6_879c_e55104013e39_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___Combined_Payor___Ops_Accepted +CREATE VIEW [int].[viewImport_SP_Direct_Loading___Combined_Payor___Ops_Accepted] AS + SELECT I.* from [int].[Import_a1551fab_31f9_450a_aa0b_d0a0b56a06f0_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___Combined_Payor___Ops_Rejected +CREATE VIEW [int].[viewImport_SP_Direct_Loading___Combined_Payor___Ops_Rejected] AS + SELECT I.* from [int].[Import_a1551fab_31f9_450a_aa0b_d0a0b56a06f0_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___Combined_Payor___RF_Accepted +CREATE VIEW [int].[viewImport_SP_Direct_Loading___Combined_Payor___RF_Accepted] AS + SELECT I.* from [int].[Import_598947bd_4660_4196_b08d_22860f7e753b_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___Combined_Payor___RF_Rejected +CREATE VIEW [int].[viewImport_SP_Direct_Loading___Combined_Payor___RF_Rejected] AS + SELECT I.* from [int].[Import_598947bd_4660_4196_b08d_22860f7e753b_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___Combined_Staffing___Ops_Accepted +CREATE VIEW [int].[viewImport_SP_Direct_Loading___Combined_Staffing___Ops_Accepted] AS + SELECT I.* from [int].[Import_d6265927_6239_4f63_95cc_ff7e37890e2d_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___Combined_Staffing___Ops_Rejected +CREATE VIEW [int].[viewImport_SP_Direct_Loading___Combined_Staffing___Ops_Rejected] AS + SELECT I.* from [int].[Import_d6265927_6239_4f63_95cc_ff7e37890e2d_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___Combined_Staffing___RF_Accepted +CREATE VIEW [int].[viewImport_SP_Direct_Loading___Combined_Staffing___RF_Accepted] AS + SELECT I.* from [int].[Import_b4074250_5ad3_41b3_a57d_778aa994f7ba_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___Combined_Staffing___RF_Rejected +CREATE VIEW [int].[viewImport_SP_Direct_Loading___Combined_Staffing___RF_Rejected] AS + SELECT I.* from [int].[Import_b4074250_5ad3_41b3_a57d_778aa994f7ba_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___IS_Account_Accepted +CREATE VIEW [int].[viewImport_SP_Direct_Loading___IS_Account_Accepted] AS + SELECT I.* from [int].[Import_27e99a35_500b_4ed0_9338_11f85c014142_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___IS_Account_Rejected +CREATE VIEW [int].[viewImport_SP_Direct_Loading___IS_Account_Rejected] AS + SELECT I.* from [int].[Import_27e99a35_500b_4ed0_9338_11f85c014142_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___IS_Payor_Accepted +CREATE VIEW [int].[viewImport_SP_Direct_Loading___IS_Payor_Accepted] AS + SELECT I.* from [int].[Import_2ecebb10_f896_468f_b907_840682d7b42d_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___IS_Payor_Rejected +CREATE VIEW [int].[viewImport_SP_Direct_Loading___IS_Payor_Rejected] AS + SELECT I.* from [int].[Import_2ecebb10_f896_468f_b907_840682d7b42d_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___IS_Physician_Accepted +CREATE VIEW [int].[viewImport_SP_Direct_Loading___IS_Physician_Accepted] AS + SELECT I.* from [int].[Import_885c8237_bb58_44cd_830f_0c86d7ef73d8_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___IS_Physician_Rejected +CREATE VIEW [int].[viewImport_SP_Direct_Loading___IS_Physician_Rejected] AS + SELECT I.* from [int].[Import_885c8237_bb58_44cd_830f_0c86d7ef73d8_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___IS_Staffing_Accepted +CREATE VIEW [int].[viewImport_SP_Direct_Loading___IS_Staffing_Accepted] AS + SELECT I.* from [int].[Import_6404089e_bb14_49ca_93df_64f21361602d_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___IS_Staffing_Rejected +CREATE VIEW [int].[viewImport_SP_Direct_Loading___IS_Staffing_Rejected] AS + SELECT I.* from [int].[Import_6404089e_bb14_49ca_93df_64f21361602d_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___Rolling_IS_Account_Accepted +CREATE VIEW [int].[viewImport_SP_Direct_Loading___Rolling_IS_Account_Accepted] AS + SELECT I.* from [int].[Import_a0b47498_722d_46c3_8c92_025f3238aefb_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___Rolling_IS_Account_Rejected +CREATE VIEW [int].[viewImport_SP_Direct_Loading___Rolling_IS_Account_Rejected] AS + SELECT I.* from [int].[Import_a0b47498_722d_46c3_8c92_025f3238aefb_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___Rolling_IS_Payor_Accepted +CREATE VIEW [int].[viewImport_SP_Direct_Loading___Rolling_IS_Payor_Accepted] AS + SELECT I.* from [int].[Import_690d6e05_8bb8_40b3_967b_5b2562dc74a5_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___Rolling_IS_Payor_Rejected +CREATE VIEW [int].[viewImport_SP_Direct_Loading___Rolling_IS_Payor_Rejected] AS + SELECT I.* from [int].[Import_690d6e05_8bb8_40b3_967b_5b2562dc74a5_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___Rolling_IS_Physician_Accepted +CREATE VIEW [int].[viewImport_SP_Direct_Loading___Rolling_IS_Physician_Accepted] AS + SELECT I.* from [int].[Import_c0602559_270a_4ad0_865e_de5ca87fb775_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___Rolling_IS_Physician_Rejected +CREATE VIEW [int].[viewImport_SP_Direct_Loading___Rolling_IS_Physician_Rejected] AS + SELECT I.* from [int].[Import_c0602559_270a_4ad0_865e_de5ca87fb775_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___Rolling_IS_Staffing_Accepted +CREATE VIEW [int].[viewImport_SP_Direct_Loading___Rolling_IS_Staffing_Accepted] AS + SELECT I.* from [int].[Import_89d2131c_400c_4336_b7ce_9d8c6ea97469_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Direct_Loading___Rolling_IS_Staffing_Rejected +CREATE VIEW [int].[viewImport_SP_Direct_Loading___Rolling_IS_Staffing_Rejected] AS + SELECT I.* from [int].[Import_89d2131c_400c_4336_b7ce_9d8c6ea97469_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Payor_Combined_Allocation_Percentage___Ops_Accepted +CREATE VIEW [int].[viewImport_SP_Payor_Combined_Allocation_Percentage___Ops_Accepted] AS + SELECT I.* from [int].[Import_555f13b5_ff0f_4b0d_98e2_a7a7db130aed_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Payor_Combined_Allocation_Percentage___Ops_Rejected +CREATE VIEW [int].[viewImport_SP_Payor_Combined_Allocation_Percentage___Ops_Rejected] AS + SELECT I.* from [int].[Import_555f13b5_ff0f_4b0d_98e2_a7a7db130aed_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Payor_Combined_Allocation_Percentage___RF_Accepted +CREATE VIEW [int].[viewImport_SP_Payor_Combined_Allocation_Percentage___RF_Accepted] AS + SELECT I.* from [int].[Import_caa46bcd_8369_4856_ab80_3948a4c02bac_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Payor_Combined_Allocation_Percentage___RF_Rejected +CREATE VIEW [int].[viewImport_SP_Payor_Combined_Allocation_Percentage___RF_Rejected] AS + SELECT I.* from [int].[Import_caa46bcd_8369_4856_ab80_3948a4c02bac_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Payor_Operations_Allocation_Percentage_Accepted +CREATE VIEW [int].[viewImport_SP_Payor_Operations_Allocation_Percentage_Accepted] AS + SELECT I.* from [int].[Import_1c6714b7_8f01_42ed_98a2_56e342ebbaea_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Payor_Operations_Allocation_Percentage_Rejected +CREATE VIEW [int].[viewImport_SP_Payor_Operations_Allocation_Percentage_Rejected] AS + SELECT I.* from [int].[Import_1c6714b7_8f01_42ed_98a2_56e342ebbaea_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Payor_Rolling_Forecast_Allocation_Percentage_Accepted +CREATE VIEW [int].[viewImport_SP_Payor_Rolling_Forecast_Allocation_Percentage_Accepted] AS + SELECT I.* from [int].[Import_383266e2_8965_427d_93d5_d60522fe8824_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Payor_Rolling_Forecast_Allocation_Percentage_Rejected +CREATE VIEW [int].[viewImport_SP_Payor_Rolling_Forecast_Allocation_Percentage_Rejected] AS + SELECT I.* from [int].[Import_383266e2_8965_427d_93d5_d60522fe8824_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Payor_Summary_Accepted +CREATE VIEW [int].[viewImport_SP_Payor_Summary_Accepted] AS + SELECT I.* from [int].[Import_6ae98a0d_7667_4d23_81c8_287a7c8ff9f3_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Payor_Summary_Rejected +CREATE VIEW [int].[viewImport_SP_Payor_Summary_Rejected] AS + SELECT I.* from [int].[Import_6ae98a0d_7667_4d23_81c8_287a7c8ff9f3_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Physician_Combined_Allocation_Percentage___Ops_Accepted +CREATE VIEW [int].[viewImport_SP_Physician_Combined_Allocation_Percentage___Ops_Accepted] AS + SELECT I.* from [int].[Import_2774d4ad_b858_47a2_b5e4_3375bd73d29d_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Physician_Combined_Allocation_Percentage___Ops_Rejected +CREATE VIEW [int].[viewImport_SP_Physician_Combined_Allocation_Percentage___Ops_Rejected] AS + SELECT I.* from [int].[Import_2774d4ad_b858_47a2_b5e4_3375bd73d29d_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Physician_Combined_Allocation_Percentage___RF_Accepted +CREATE VIEW [int].[viewImport_SP_Physician_Combined_Allocation_Percentage___RF_Accepted] AS + SELECT I.* from [int].[Import_ecb4800d_2106_4948_a4f7_c42b71f987a7_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Physician_Combined_Allocation_Percentage___RF_Rejected +CREATE VIEW [int].[viewImport_SP_Physician_Combined_Allocation_Percentage___RF_Rejected] AS + SELECT I.* from [int].[Import_ecb4800d_2106_4948_a4f7_c42b71f987a7_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Physician_Operations_Allocation_Percentage_Accepted +CREATE VIEW [int].[viewImport_SP_Physician_Operations_Allocation_Percentage_Accepted] AS + SELECT I.* from [int].[Import_25a6fbdd_672f_4b40_ae14_fc196f71a4dd_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Physician_Operations_Allocation_Percentage_Rejected +CREATE VIEW [int].[viewImport_SP_Physician_Operations_Allocation_Percentage_Rejected] AS + SELECT I.* from [int].[Import_25a6fbdd_672f_4b40_ae14_fc196f71a4dd_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Physician_Rolling_Forecast_Allocation_Percentage_Accepted +CREATE VIEW [int].[viewImport_SP_Physician_Rolling_Forecast_Allocation_Percentage_Accepted] AS + SELECT I.* from [int].[Import_0bc9c76c_e4f3_488a_9851_394b07eed375_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Physician_Rolling_Forecast_Allocation_Percentage_Rejected +CREATE VIEW [int].[viewImport_SP_Physician_Rolling_Forecast_Allocation_Percentage_Rejected] AS + SELECT I.* from [int].[Import_0bc9c76c_e4f3_488a_9851_394b07eed375_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Physician_Summary_Accepted +CREATE VIEW [int].[viewImport_SP_Physician_Summary_Accepted] AS + SELECT I.* from [int].[Import_04a46abd_cbaf_4a20_8d76_4e114d74c289_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Physician_Summary_Rejected +CREATE VIEW [int].[viewImport_SP_Physician_Summary_Rejected] AS + SELECT I.* from [int].[Import_04a46abd_cbaf_4a20_8d76_4e114d74c289_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Staffing_Combined_Allocation_Percentage___Ops_Accepted +CREATE VIEW [int].[viewImport_SP_Staffing_Combined_Allocation_Percentage___Ops_Accepted] AS + SELECT I.* from [int].[Import_f60feba4_4bfe_447b_a7f7_befd007ffcd1_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Staffing_Combined_Allocation_Percentage___Ops_Rejected +CREATE VIEW [int].[viewImport_SP_Staffing_Combined_Allocation_Percentage___Ops_Rejected] AS + SELECT I.* from [int].[Import_f60feba4_4bfe_447b_a7f7_befd007ffcd1_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Staffing_Combined_Allocation_Percentage___RF_Accepted +CREATE VIEW [int].[viewImport_SP_Staffing_Combined_Allocation_Percentage___RF_Accepted] AS + SELECT I.* from [int].[Import_fee9ab0a_eac6_4485_a270_15d465bf368d_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Staffing_Combined_Allocation_Percentage___RF_Rejected +CREATE VIEW [int].[viewImport_SP_Staffing_Combined_Allocation_Percentage___RF_Rejected] AS + SELECT I.* from [int].[Import_fee9ab0a_eac6_4485_a270_15d465bf368d_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Staffing_Operations_Allocation_Percentage_Accepted +CREATE VIEW [int].[viewImport_SP_Staffing_Operations_Allocation_Percentage_Accepted] AS + SELECT I.* from [int].[Import_29b44bab_4abe_43ae_acd4_3bb99d5dcb53_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Staffing_Operations_Allocation_Percentage_Rejected +CREATE VIEW [int].[viewImport_SP_Staffing_Operations_Allocation_Percentage_Rejected] AS + SELECT I.* from [int].[Import_29b44bab_4abe_43ae_acd4_3bb99d5dcb53_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Staffing_Rolling_Forecast_Allocation_Percentage_Accepted +CREATE VIEW [int].[viewImport_SP_Staffing_Rolling_Forecast_Allocation_Percentage_Accepted] AS + SELECT I.* from [int].[Import_2f7492bb_480f_4658_a865_b204ce4a7c93_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Staffing_Rolling_Forecast_Allocation_Percentage_Rejected +CREATE VIEW [int].[viewImport_SP_Staffing_Rolling_Forecast_Allocation_Percentage_Rejected] AS + SELECT I.* from [int].[Import_2f7492bb_480f_4658_a865_b204ce4a7c93_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Staffing_Summary_Accepted +CREATE VIEW [int].[viewImport_SP_Staffing_Summary_Accepted] AS + SELECT I.* from [int].[Import_730932c6_0239_46c2_a5c0_8ed31dde8ad5_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SP_Staffing_Summary_Rejected +CREATE VIEW [int].[viewImport_SP_Staffing_Summary_Rejected] AS + SELECT I.* from [int].[Import_730932c6_0239_46c2_a5c0_8ed31dde8ad5_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SUP_Charge_Code_Accepted +CREATE VIEW [int].[viewImport_SUP_Charge_Code_Accepted] AS + SELECT I.* from [int].[Import_5e2e18da_ff3c_40ab_b713_fa393f0bb3cd_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_SUP_Charge_Code_Rejected +CREATE VIEW [int].[viewImport_SUP_Charge_Code_Rejected] AS + SELECT I.* from [int].[Import_5e2e18da_ff3c_40ab_b713_fa393f0bb3cd_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Service_Accepted +CREATE VIEW [int].[viewImport_Service_Accepted] AS + SELECT I.* from [int].[Import_f94bf095_39cf_4c18_9c1f_80dd4476ec91_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Service_Line_Revenue_Accepted +CREATE VIEW [int].[viewImport_Service_Line_Revenue_Accepted] AS + SELECT I.* from [int].[Import_38e60101_6e90_4e2a_bcbf_77c84a1e9d04_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Service_Line_Revenue_Rejected +CREATE VIEW [int].[viewImport_Service_Line_Revenue_Rejected] AS + SELECT I.* from [int].[Import_38e60101_6e90_4e2a_bcbf_77c84a1e9d04_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Service_Rejected +CREATE VIEW [int].[viewImport_Service_Rejected] AS + SELECT I.* from [int].[Import_f94bf095_39cf_4c18_9c1f_80dd4476ec91_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Shared___General_Ledger_Accepted +CREATE VIEW [int].[viewImport_Shared___General_Ledger_Accepted] AS + SELECT I.* from [int].[Import_56db8dc7_31ee_4f79_a683_2e7bf0ab0d2b_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Shared___General_Ledger_Rejected +CREATE VIEW [int].[viewImport_Shared___General_Ledger_Rejected] AS + SELECT I.* from [int].[Import_56db8dc7_31ee_4f79_a683_2e7bf0ab0d2b_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Shared___Global_Statistics_Accepted +CREATE VIEW [int].[viewImport_Shared___Global_Statistics_Accepted] AS + SELECT I.* from [int].[Import_e623e263_bf35_4c9c_b256_510a766b8242_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Shared___Global_Statistics_Rejected +CREATE VIEW [int].[viewImport_Shared___Global_Statistics_Rejected] AS + SELECT I.* from [int].[Import_e623e263_bf35_4c9c_b256_510a766b8242_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Shared___Import___AP_Detail_Accepted +CREATE VIEW [int].[viewImport_Shared___Import___AP_Detail_Accepted] AS + SELECT I.* from [int].[Import_d5750d90_0ee2_443e_8a88_2f7370eee0ac_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Shared___Import___AP_Detail_Rejected +CREATE VIEW [int].[viewImport_Shared___Import___AP_Detail_Rejected] AS + SELECT I.* from [int].[Import_d5750d90_0ee2_443e_8a88_2f7370eee0ac_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Shared___Import___Daily_Statistics_Accepted +CREATE VIEW [int].[viewImport_Shared___Import___Daily_Statistics_Accepted] AS + SELECT I.* from [int].[Import_2ba30098_5a69_497b_a768_46a2a1c11e35_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Shared___Import___Daily_Statistics_Rejected +CREATE VIEW [int].[viewImport_Shared___Import___Daily_Statistics_Rejected] AS + SELECT I.* from [int].[Import_2ba30098_5a69_497b_a768_46a2a1c11e35_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Shared___Import___GL_Detail_Accepted +CREATE VIEW [int].[viewImport_Shared___Import___GL_Detail_Accepted] AS + SELECT I.* from [int].[Import_e2d145bc_120b_4d00_b59b_07de233aaedf_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Shared___Import___GL_Detail_Rejected +CREATE VIEW [int].[viewImport_Shared___Import___GL_Detail_Rejected] AS + SELECT I.* from [int].[Import_e2d145bc_120b_4d00_b59b_07de233aaedf_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Shared___Import___Staffing_Daily_Accepted +CREATE VIEW [int].[viewImport_Shared___Import___Staffing_Daily_Accepted] AS + SELECT I.* from [int].[Import_4f5655bc_33bc_452e_9da0_7326c2ba0363_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Shared___Import___Staffing_Daily_Rejected +CREATE VIEW [int].[viewImport_Shared___Import___Staffing_Daily_Rejected] AS + SELECT I.* from [int].[Import_4f5655bc_33bc_452e_9da0_7326c2ba0363_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Shared___Service_Line_Import_Accepted +CREATE VIEW [int].[viewImport_Shared___Service_Line_Import_Accepted] AS + SELECT I.* from [int].[Import_8d2bd278_6c37_427d_9cd1_b27e71341636_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Shared___Service_Line_Import_Rejected +CREATE VIEW [int].[viewImport_Shared___Service_Line_Import_Rejected] AS + SELECT I.* from [int].[Import_8d2bd278_6c37_427d_9cd1_b27e71341636_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Shared___Staffing_Accepted +CREATE VIEW [int].[viewImport_Shared___Staffing_Accepted] AS + SELECT I.* from [int].[Import_e1a1a312_32e8_4ee8_805f_61455f171001_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Shared___Staffing_By_Pay_Period_Accepted +CREATE VIEW [int].[viewImport_Shared___Staffing_By_Pay_Period_Accepted] AS + SELECT I.* from [int].[Import_cdc2ef8b_987e_4ca6_a06c_22827507f5f5_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Shared___Staffing_By_Pay_Period_Rejected +CREATE VIEW [int].[viewImport_Shared___Staffing_By_Pay_Period_Rejected] AS + SELECT I.* from [int].[Import_cdc2ef8b_987e_4ca6_a06c_22827507f5f5_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Shared___Staffing_Rejected +CREATE VIEW [int].[viewImport_Shared___Staffing_Rejected] AS + SELECT I.* from [int].[Import_e1a1a312_32e8_4ee8_805f_61455f171001_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Shared___Statistics_Accepted +CREATE VIEW [int].[viewImport_Shared___Statistics_Accepted] AS + SELECT I.* from [int].[Import_8a1ed204_bccc_4da6_b74e_20c0629b6431_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Shared___Statistics_Rejected +CREATE VIEW [int].[viewImport_Shared___Statistics_Rejected] AS + SELECT I.* from [int].[Import_8a1ed204_bccc_4da6_b74e_20c0629b6431_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffign_by_Pay_Period___Department_Dimension_Accepted +CREATE VIEW [int].[viewImport_Staffign_by_Pay_Period___Department_Dimension_Accepted] AS + SELECT I.* from [int].[Import_f4e4f855_b91e_4c8c_a621_20ff76e3832b_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffign_by_Pay_Period___Department_Dimension_Rejected +CREATE VIEW [int].[viewImport_Staffign_by_Pay_Period___Department_Dimension_Rejected] AS + SELECT I.* from [int].[Import_f4e4f855_b91e_4c8c_a621_20ff76e3832b_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_Daily___Department_Accepted +CREATE VIEW [int].[viewImport_Staffing_Daily___Department_Accepted] AS + SELECT I.* from [int].[Import_5a639f91_3e82_4bf6_94ce_aa2b17c1fa80_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_Daily___Department_Rejected +CREATE VIEW [int].[viewImport_Staffing_Daily___Department_Rejected] AS + SELECT I.* from [int].[Import_5a639f91_3e82_4bf6_94ce_aa2b17c1fa80_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_Daily___Employee_Accepted +CREATE VIEW [int].[viewImport_Staffing_Daily___Employee_Accepted] AS + SELECT I.* from [int].[Import_82f72e8d_78a5_4258_ac8a_05e331e2dffc_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_Daily___Employee_Rejected +CREATE VIEW [int].[viewImport_Staffing_Daily___Employee_Rejected] AS + SELECT I.* from [int].[Import_82f72e8d_78a5_4258_ac8a_05e331e2dffc_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_Daily___Entity_Accepted +CREATE VIEW [int].[viewImport_Staffing_Daily___Entity_Accepted] AS + SELECT I.* from [int].[Import_46f14f26_5df7_4519_8bdd_1a840936f00c_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_Daily___Entity_Rejected +CREATE VIEW [int].[viewImport_Staffing_Daily___Entity_Rejected] AS + SELECT I.* from [int].[Import_46f14f26_5df7_4519_8bdd_1a840936f00c_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_Daily___Job_Code_Accepted +CREATE VIEW [int].[viewImport_Staffing_Daily___Job_Code_Accepted] AS + SELECT I.* from [int].[Import_60cab422_84e9_490c_a37d_ba6955b2a6da_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_Daily___Job_Code_Rejected +CREATE VIEW [int].[viewImport_Staffing_Daily___Job_Code_Rejected] AS + SELECT I.* from [int].[Import_60cab422_84e9_490c_a37d_ba6955b2a6da_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_Daily___Pay_Code_Accepted +CREATE VIEW [int].[viewImport_Staffing_Daily___Pay_Code_Accepted] AS + SELECT I.* from [int].[Import_86796983_c8ab_4853_b417_1e116953658c_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_Daily___Pay_Code_Rejected +CREATE VIEW [int].[viewImport_Staffing_Daily___Pay_Code_Rejected] AS + SELECT I.* from [int].[Import_86796983_c8ab_4853_b417_1e116953658c_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_Detail_Accepted +CREATE VIEW [int].[viewImport_Staffing_Detail_Accepted] AS + SELECT I.* from [int].[Import_1cd9dc31_e651_46e0_8b9a_d7385891ae95_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_Detail_Rejected +CREATE VIEW [int].[viewImport_Staffing_Detail_Rejected] AS + SELECT I.* from [int].[Import_1cd9dc31_e651_46e0_8b9a_d7385891ae95_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing___Department_Dimension_Accepted +CREATE VIEW [int].[viewImport_Staffing___Department_Dimension_Accepted] AS + SELECT I.* from [int].[Import_5050eb0a_6146_4c2c_bef5_830e860d3f68_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing___Department_Dimension_Rejected +CREATE VIEW [int].[viewImport_Staffing___Department_Dimension_Rejected] AS + SELECT I.* from [int].[Import_5050eb0a_6146_4c2c_bef5_830e860d3f68_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing___Employee_Dimension_Accepted +CREATE VIEW [int].[viewImport_Staffing___Employee_Dimension_Accepted] AS + SELECT I.* from [int].[Import_5990705e_57d6_41a6_b97b_07f5cc5a67df_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing___Employee_Dimension_Rejected +CREATE VIEW [int].[viewImport_Staffing___Employee_Dimension_Rejected] AS + SELECT I.* from [int].[Import_5990705e_57d6_41a6_b97b_07f5cc5a67df_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing___Entity_Dimension_Accepted +CREATE VIEW [int].[viewImport_Staffing___Entity_Dimension_Accepted] AS + SELECT I.* from [int].[Import_fcc81949_ca89_4ab8_82ec_d00583464125_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing___Entity_Dimension_Rejected +CREATE VIEW [int].[viewImport_Staffing___Entity_Dimension_Rejected] AS + SELECT I.* from [int].[Import_fcc81949_ca89_4ab8_82ec_d00583464125_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing___Job_Code_Dimension_Accepted +CREATE VIEW [int].[viewImport_Staffing___Job_Code_Dimension_Accepted] AS + SELECT I.* from [int].[Import_6e8d8449_137c_4c04_9533_53cbed43e341_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing___Job_Code_Dimension_Rejected +CREATE VIEW [int].[viewImport_Staffing___Job_Code_Dimension_Rejected] AS + SELECT I.* from [int].[Import_6e8d8449_137c_4c04_9533_53cbed43e341_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing___Pay_Code_Accepted +CREATE VIEW [int].[viewImport_Staffing___Pay_Code_Accepted] AS + SELECT I.* from [int].[Import_35413d7f_3756_43b3_ad3a_54f12ba46ebc_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing___Pay_Code_Rejected +CREATE VIEW [int].[viewImport_Staffing___Pay_Code_Rejected] AS + SELECT I.* from [int].[Import_35413d7f_3756_43b3_ad3a_54f12ba46ebc_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_by_Pay_Period___Department_Dimension_Accepted +CREATE VIEW [int].[viewImport_Staffing_by_Pay_Period___Department_Dimension_Accepted] AS + SELECT I.* from [int].[Import_f4e4f855_b91e_4c8c_a621_20ff76e3832b_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_by_Pay_Period___Department_Dimension_Rejected +CREATE VIEW [int].[viewImport_Staffing_by_Pay_Period___Department_Dimension_Rejected] AS + SELECT I.* from [int].[Import_f4e4f855_b91e_4c8c_a621_20ff76e3832b_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_by_Pay_Period___Employee_Accepted +CREATE VIEW [int].[viewImport_Staffing_by_Pay_Period___Employee_Accepted] AS + SELECT I.* from [int].[Import_9edb7cd7_f8cd_4dda_9eb4_0fb4b8f1de81_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_by_Pay_Period___Employee_Rejected +CREATE VIEW [int].[viewImport_Staffing_by_Pay_Period___Employee_Rejected] AS + SELECT I.* from [int].[Import_9edb7cd7_f8cd_4dda_9eb4_0fb4b8f1de81_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_by_Pay_Period___Entity_Dimension_Accepted +CREATE VIEW [int].[viewImport_Staffing_by_Pay_Period___Entity_Dimension_Accepted] AS + SELECT I.* from [int].[Import_dee10748_f674_489d_8fa7_cf4a10da6a99_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_by_Pay_Period___Entity_Dimension_Rejected +CREATE VIEW [int].[viewImport_Staffing_by_Pay_Period___Entity_Dimension_Rejected] AS + SELECT I.* from [int].[Import_dee10748_f674_489d_8fa7_cf4a10da6a99_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_by_Pay_Period___Job_Code_Dimension_Accepted +CREATE VIEW [int].[viewImport_Staffing_by_Pay_Period___Job_Code_Dimension_Accepted] AS + SELECT I.* from [int].[Import_6ab7765c_8474_4b9a_b759_5b207f118a0e_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_by_Pay_Period___Job_Code_Dimension_Rejected +CREATE VIEW [int].[viewImport_Staffing_by_Pay_Period___Job_Code_Dimension_Rejected] AS + SELECT I.* from [int].[Import_6ab7765c_8474_4b9a_b759_5b207f118a0e_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_by_Pay_Period___Pay_Code_Dimension_Accepted +CREATE VIEW [int].[viewImport_Staffing_by_Pay_Period___Pay_Code_Dimension_Accepted] AS + SELECT I.* from [int].[Import_a67d8f1c_36c2_4d13_b6e1_3dae138bdff7_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Staffing_by_Pay_Period___Pay_Code_Dimension_Rejected +CREATE VIEW [int].[viewImport_Staffing_by_Pay_Period___Pay_Code_Dimension_Rejected] AS + SELECT I.* from [int].[Import_a67d8f1c_36c2_4d13_b6e1_3dae138bdff7_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Star_Patient_ADT_Accepted +CREATE VIEW [int].[viewImport_Star_Patient_ADT_Accepted] AS + SELECT I.* from [int].[Import_a3b197db_0e91_4efd_acec_cc071e9345dc_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Star_Patient_ADT_Rejected +CREATE VIEW [int].[viewImport_Star_Patient_ADT_Rejected] AS + SELECT I.* from [int].[Import_a3b197db_0e91_4efd_acec_cc071e9345dc_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Statistics_by_Pay_Period_Accepted +CREATE VIEW [int].[viewImport_Statistics_by_Pay_Period_Accepted] AS + SELECT I.* from [int].[Import_b1bf2582_5ddb_4a43_9dce_7c8b41aca4ba_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Statistics_by_Pay_Period_Rejected +CREATE VIEW [int].[viewImport_Statistics_by_Pay_Period_Rejected] AS + SELECT I.* from [int].[Import_b1bf2582_5ddb_4a43_9dce_7c8b41aca4ba_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Stats_by_Period___Account_Dimension_Accepted +CREATE VIEW [int].[viewImport_Stats_by_Period___Account_Dimension_Accepted] AS + SELECT I.* from [int].[Import_98292ff4_b580_4db7_9f43_7e15e07421a1_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Stats_by_Period___Account_Dimension_Rejected +CREATE VIEW [int].[viewImport_Stats_by_Period___Account_Dimension_Rejected] AS + SELECT I.* from [int].[Import_98292ff4_b580_4db7_9f43_7e15e07421a1_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Stats_by_Period___Department_Dimension_Accepted +CREATE VIEW [int].[viewImport_Stats_by_Period___Department_Dimension_Accepted] AS + SELECT I.* from [int].[Import_0ee07141_3103_4c56_bec3_2d1157da2ce6_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Stats_by_Period___Department_Dimension_Rejected +CREATE VIEW [int].[viewImport_Stats_by_Period___Department_Dimension_Rejected] AS + SELECT I.* from [int].[Import_0ee07141_3103_4c56_bec3_2d1157da2ce6_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Stats_by_Period___Entity_Dimension_Accepted +CREATE VIEW [int].[viewImport_Stats_by_Period___Entity_Dimension_Accepted] AS + SELECT I.* from [int].[Import_48b416a8_1b74_4343_803f_cd9f8a8d7c96_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Stats_by_Period___Entity_Dimension_Rejected +CREATE VIEW [int].[viewImport_Stats_by_Period___Entity_Dimension_Rejected] AS + SELECT I.* from [int].[Import_48b416a8_1b74_4343_803f_cd9f8a8d7c96_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Subscriber_Relationship_Accepted +CREATE VIEW [int].[viewImport_Subscriber_Relationship_Accepted] AS + SELECT I.* from [int].[Import_4a0480e2_2ae1_49c5_ad13_276303db067b_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Subscriber_Relationship_Rejected +CREATE VIEW [int].[viewImport_Subscriber_Relationship_Rejected] AS + SELECT I.* from [int].[Import_4a0480e2_2ae1_49c5_ad13_276303db067b_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Supply_Accepted +CREATE VIEW [int].[viewImport_Supply_Accepted] AS + SELECT I.* from [int].[Import_a6dc4c39_f907_4301_8776_7f7b78deef0e_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Supply_Rejected +CREATE VIEW [int].[viewImport_Supply_Rejected] AS + SELECT I.* from [int].[Import_a6dc4c39_f907_4301_8776_7f7b78deef0e_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Surgical_Detail_Accepted +CREATE VIEW [int].[viewImport_Surgical_Detail_Accepted] AS + SELECT I.* from [int].[Import_cf70c229_e22b_4e09_b64d_e609c358d4f0_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Surgical_Detail_Rejected +CREATE VIEW [int].[viewImport_Surgical_Detail_Rejected] AS + SELECT I.* from [int].[Import_cf70c229_e22b_4e09_b64d_e609c358d4f0_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Surgical_Staff_Accepted +CREATE VIEW [int].[viewImport_Surgical_Staff_Accepted] AS + SELECT I.* from [int].[Import_eef1997c_a3c0_4af9_a779_74ce72717249_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Surgical_Staff_Rejected +CREATE VIEW [int].[viewImport_Surgical_Staff_Rejected] AS + SELECT I.* from [int].[Import_eef1997c_a3c0_4af9_a779_74ce72717249_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Surgical_Staff_Type_Accepted +CREATE VIEW [int].[viewImport_Surgical_Staff_Type_Accepted] AS + SELECT I.* from [int].[Import_c493d8f4_6da4_4488_9ae9_3b5a4791d92a_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Surgical_Staff_Type_Category_Accepted +CREATE VIEW [int].[viewImport_Surgical_Staff_Type_Category_Accepted] AS + SELECT I.* from [int].[Import_26138873_9e4b_4298_8eb5_66ac7dfab5c5_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Surgical_Staff_Type_Category_Rejected +CREATE VIEW [int].[viewImport_Surgical_Staff_Type_Category_Rejected] AS + SELECT I.* from [int].[Import_26138873_9e4b_4298_8eb5_66ac7dfab5c5_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Surgical_Staff_Type_Rejected +CREATE VIEW [int].[viewImport_Surgical_Staff_Type_Rejected] AS + SELECT I.* from [int].[Import_c493d8f4_6da4_4488_9ae9_3b5a4791d92a_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Swipe_Data_Import_Accepted +CREATE VIEW [int].[viewImport_Swipe_Data_Import_Accepted] AS + SELECT I.* from [int].[Import_f04709bb_195b_4bba_8945_5e260800a269_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Swipe_Data_Import_Rejected +CREATE VIEW [int].[viewImport_Swipe_Data_Import_Rejected] AS + SELECT I.* from [int].[Import_f04709bb_195b_4bba_8945_5e260800a269_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Transaction_Code_Accepted +CREATE VIEW [int].[viewImport_Transaction_Code_Accepted] AS + SELECT I.* from [int].[Import_ceb9826b_aa15_465f_ab19_1d34ffa6f1c6_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Transaction_Code_Rejected +CREATE VIEW [int].[viewImport_Transaction_Code_Rejected] AS + SELECT I.* from [int].[Import_ceb9826b_aa15_465f_ab19_1d34ffa6f1c6_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Transaction_Source_Accepted +CREATE VIEW [int].[viewImport_Transaction_Source_Accepted] AS + SELECT I.* from [int].[Import_fd1dbdb7_48c2_46fd_a0e0_fc5ebc7d8f56_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Transaction_Source_Rejected +CREATE VIEW [int].[viewImport_Transaction_Source_Rejected] AS + SELECT I.* from [int].[Import_fd1dbdb7_48c2_46fd_a0e0_fc5ebc7d8f56_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_UB_Revenue_Code_Accepted +CREATE VIEW [int].[viewImport_UB_Revenue_Code_Accepted] AS + SELECT I.* from [int].[Import_2ea260c3_2e2d_4e1d_9271_f09ecd89bdbf_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_UB_Revenue_Code_Rejected +CREATE VIEW [int].[viewImport_UB_Revenue_Code_Rejected] AS + SELECT I.* from [int].[Import_2ea260c3_2e2d_4e1d_9271_f09ecd89bdbf_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Unit_Accepted +CREATE VIEW [int].[viewImport_Unit_Accepted] AS + SELECT I.* from [int].[Import_e71555c3_2e75_4f6e_9eef_056f9a8dc621_Accepted] I; +GO + + +--------------------------------------------- + +-- int.viewImport_Unit_Rejected +CREATE VIEW [int].[viewImport_Unit_Rejected] AS + SELECT I.* from [int].[Import_e71555c3_2e75_4f6e_9eef_056f9a8dc621_Rejected] I; +GO + + +--------------------------------------------- + +-- int.viewReportExceptionsFactGL +CREATE VIEW [int].[viewReportExceptionsFactGL] +AS +------------- int.FactGL exceptions ------------- + +SELECT DISTINCT + source.AccountCode as DataMember, + 'Account' as Identifier, + 'int.FactGL' as Source, + 'Account "'+source.AccountCode +'" is present in int.FactGL but is not present in the Account Dimension' as Explanation +FROM + int.FactGL source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimAccount WHERE AccountCode = source.AccountCode) + + +UNION ALL + + +SELECT DISTINCT + source.DepartmentCode as DataMember, + 'Department' as Identifier, + 'int.FactGL' as Source, + 'Department "'+ source.DepartmentCode +'" is present in int.FactGL but is not present in the Department Dimension' as Explanation +FROM + int.FactGL source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimDepartment WHERE DepartmentCode = source.DepartmentCode) + + +UNION ALL + + +SELECT DISTINCT + source.TimeClassCode as DataMember, + 'Time Class' as Identifier, + 'int.FactGL' as Source, + 'Time Class "'+ source.TimeClassCode +'" is present in int.FactGL but is not present in the Time Class Dimension' as Explanation +FROM + int.FactGL source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimTimeClass WHERE TimeClassCode = source.TimeClassCode) + + +UNION ALL + + +SELECT DISTINCT + source.FiscalYearCode as DataMember, + 'Fiscal Year' as Identifier, + 'int.FactGL' as Source, + 'Fiscal Year "'+ source.FiscalYearCode +'" is present in int.FactGL but is not present in the Fiscal Year Dimension' as Explanation +FROM + int.FactGL source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimFiscalYear WHERE Name = source.FiscalYearCode) + + +UNION ALL + + +SELECT DISTINCT + source.FiscalMonthCode as DataMember, + 'Fiscal Month' as Identifier, + 'int.FactGL' as Source, + 'Fiscal Month "'+ source.FiscalMonthCode +'" is present in int.FactGL but is not present in the Fiscal Month Dimension' as Explanation +FROM + int.FactGL source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimFiscalMonth WHERE FiscalMonthCode = source.FiscalMonthCode) +GO + + +--------------------------------------------- + +-- int.viewReportExceptionsFactPayorSummary +CREATE VIEW [int].[viewReportExceptionsFactPayorSummary] +AS +------------- int.FactPayorSummary exceptions ------------- + + +SELECT DISTINCT + source.DepartmentCode as DataMember, + 'Department' as Identifier, + 'int.FactPayorSummary' as Source, + 'Department "'+ source.DepartmentCode +'" is present in int.FactPayorSummary but is not present in the Department Dimension' as Explanation +FROM + int.FactPayorSummary source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimDepartment WHERE DepartmentCode = source.DepartmentCode) + + +UNION ALL + + +SELECT DISTINCT + source.AccountRollupCode as DataMember, + 'SP Account Rollup' as Identifier, + 'int.FactPayorSummary' as Source, + 'AccountRollup "'+source.AccountRollupCode +'" is present in int.FactPayorSummary but is not present in the SP Account Rollup Dimension' as Explanation +FROM + int.FactPayorSummary source + WHERE NOT EXISTS +(select 1 FROM sp.DimAccountRollup ar where ar.Name = source.AccountRollupCode) + + +UNION ALL + + +SELECT DISTINCT + source.PayorGroupCode as DataMember, + 'Payor Group' as Identifier, + 'int.FactPayorSummary' as Source, + 'PayorGroup "'+source.PayorGroupCode +'" is present in int.FactPayorSummary but is not present in the Payor Group Dimension' as Explanation +FROM + int.FactPayorSummary source +WHERE NOT EXISTS +(select 1 FROM fw.DimPayorGroup pr where source.PayorGroupCode=pr.Name) + + +UNION ALL + + +SELECT DISTINCT + source.PatientTypeRollupCode as DataMember, + 'Patient Type Rollup' as Identifier, + 'int.FactPayorSummary' as Source, + 'Patient Type Rollup "'+ source.TimeClassCode +'" is present in int.FactPayorSummary but is not present in the Patient Type Rollup Dimension' as Explanation +FROM + int.FactPayorSummary source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimPatientTypeRollup WHERE Name = source.PatientTypeRollupCode) + + +UNION ALL + + +SELECT DISTINCT + source.TimeClassCode as DataMember, + 'Time Class' as Identifier, + 'int.FactPayorSummary' as Source, + 'Time Class "'+ source.TimeClassCode +'" is present in int.FactPayorSummary but is not present in the Time Class Dimension' as Explanation +FROM + int.FactPayorSummary source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimTimeClass WHERE TimeClassCode = source.TimeClassCode) + + +UNION ALL + + +SELECT DISTINCT + source.FiscalYearCode as DataMember, + 'Fiscal Year' as Identifier, + 'int.FactPayorSummary' as Source, + 'Fiscal Year "'+ source.FiscalYearCode +'" is present in int.FactPayorSummary but is not present in the Fiscal Year Dimension' as Explanation +FROM + int.FactPayorSummary source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimFiscalYear WHERE Name = source.FiscalYearCode) + + +UNION ALL + + +SELECT DISTINCT + source.UnitType as DataMember, + 'Unit Type' as Identifier, + 'int.FactPayorSummary' as Source, + 'Unit Type "'+ source.UnitType +'" is present in int.FactPayorSummary but is not present in the Unit Type Dimension' as Explanation +FROM + int.FactPayorSummary source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimUnitType WHERE Name = source.UnitType) + +UNION ALL + + +SELECT DISTINCT + source.FiscalMonthCode as DataMember, + 'Fiscal Month' as Identifier, + 'int.FactPayorSummary' as Source, + 'Fiscal Month "'+ source.FiscalMonthCode +'" is present in int.FactPayorSummary but is not present in the Fiscal Month Dimension' as Explanation +FROM + int.FactPayorSummary source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimFiscalMonth WHERE FiscalMonthCode = source.FiscalMonthCode) +GO + + +--------------------------------------------- + +-- int.viewReportExceptionsFactPhysicianSummary +CREATE VIEW [int].[viewReportExceptionsFactPhysicianSummary] +AS +------------- int.FactPhysicianSummary exceptions ------------- + + +SELECT DISTINCT + source.DepartmentCode as DataMember, + 'Department' as Identifier, + 'int.FactPhysicianSummary' as Source, + 'Department "'+ source.DepartmentCode +'" is present in int.FactPhysicianSummary but is not present in the Department Dimension' as Explanation +FROM + int.FactPhysicianSummary source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimDepartment WHERE DepartmentCode = source.DepartmentCode) + + +UNION ALL + + +SELECT DISTINCT + source.AccountRollupCode as DataMember, + 'SP Account Rollup' as Identifier, + 'int.FactPhysicianSummary' as Source, + 'AccountRollup "'+source.AccountRollupCode +'" is present in int.FactPhysicianSummary but is not present in the SP Account Rollup Dimension' as Explanation +FROM + int.FactPhysicianSummary source + WHERE NOT EXISTS +(select 1 FROM sp.DimAccountRollup ar where ar.Name = source.AccountRollupCode) + + +UNION ALL + + +SELECT DISTINCT + source.PhysicianGroupCode as DataMember, + 'Physician Group' as Identifier, + 'int.FactPhysicianSummary' as Source, + 'Physician Group "'+source.PhysicianGroupCode +'" is present in int.FactPhysicianSummary but is not present in the Physician Group Dimension' as Explanation +FROM + int.FactPhysicianSummary source +WHERE NOT EXISTS +(select 1 FROM fw.DimPhysicianGroup pr where source.PhysicianGroupCode=pr.Name) + +UNION ALL + + +SELECT DISTINCT + source.PatientTypeRollupCode as DataMember, + 'Patient Type Rollup' as Identifier, + 'int.FactPhysicianSummary' as Source, + 'Patient Type Rollup "'+ source.TimeClassCode +'" is present in int.FactPhysicianSummary but is not present in the Patient Type Rollup Dimension' as Explanation +FROM + int.FactPhysicianSummary source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimPatientTypeRollup WHERE Name = source.PatientTypeRollupCode) + + +UNION ALL + + +SELECT DISTINCT + source.TimeClassCode as DataMember, + 'Time Class' as Identifier, + 'int.FactPhysicianSummary' as Source, + 'Time Class "'+ source.TimeClassCode +'" is present in int.FactPhysicianSummary but is not present in the Time Class Dimension' as Explanation +FROM + int.FactPhysicianSummary source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimTimeClass WHERE TimeClassCode = source.TimeClassCode) + + +UNION ALL + + +SELECT DISTINCT + source.FiscalYearCode as DataMember, + 'Fiscal Year' as Identifier, + 'int.FactPhysicianSummary' as Source, + 'Fiscal Year "'+ source.FiscalYearCode +'" is present in int.FactPhysicianSummary but is not present in the Fiscal Year Dimension' as Explanation +FROM + int.FactPhysicianSummary source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimFiscalYear WHERE Name = source.FiscalYearCode) + + +UNION ALL + + +SELECT DISTINCT + source.UnitType as DataMember, + 'Unit Type' as Identifier, + 'int.FactPhysicianSummary' as Source, + 'Unit Type "'+ source.UnitType +'" is present in int.FactPhysicianSummary but is not present in the Unit Type Dimension' as Explanation +FROM + int.FactPhysicianSummary source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimUnitType WHERE Name = source.UnitType) + +UNION ALL + + +SELECT DISTINCT + source.FiscalMonthCode as DataMember, + 'Fiscal Month' as Identifier, + 'int.FactPhysicianSummary' as Source, + 'Fiscal Month "'+ source.FiscalMonthCode +'" is present in int.FactPhysicianSummary but is not present in the Fiscal Month Dimension' as Explanation +FROM + int.FactPhysicianSummary source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimFiscalMonth WHERE FiscalMonthCode = source.FiscalMonthCode) +GO + + +--------------------------------------------- + +-- int.viewReportExceptionsFactSPDirectBalAccount +CREATE VIEW [int].[viewReportExceptionsFactSPDirectBalAccount] +AS +------------- int.FactSPDirectBalAccount exceptions ------------- + +SELECT DISTINCT + source.SPLongRangePlanName as DataMember, + 'Balance Sheet Plan' as Identifier, + 'int.FactSPDirectBalAccount' as Source, + 'Balance Sheet Plan "'+ source.SPLongRangePlanName +'" is present in int.FactSPDirectBalAccount but is not present in the SP Long Range Plan Dimension' as Explanation +FROM + [int].[FactSPDirectBalAccount] source +WHERE + source.SPLongRangePlanID=0 + + + +UNION ALL + + + +SELECT DISTINCT + source.SPLongRangePlanName as DataMember, + 'Account Rollup' as Identifier, + 'int.FactSPDirectBalAccount' as Source, + 'Account Rollup "'+ source.SPLongRangePlanName +'" is present in int.FactSPDirectBalAccount but is not present in the SP Account Rollup Dimension' as Explanation +FROM + [int].[FactSPDirectBalAccount] source +WHERE + source.AccountRollupID=0 + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Account Rollup related to a Debt Issuance' as Identifier, + 'int.FactSPDirectBalAccount' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectBalAccount but does not have a Debt Issuance which is defined in the SP Debt Issuance Dimension associated to it. Please review the data file to ensure that it looks accurate' as Explanation +FROM + [int].[FactSPDirectBalAccount] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Category='Debt - Long Term' and source.SPDebtIssuanceID=0) + + +UNION ALL + + +SELECT DISTINCT + source.SPCapitalRollupName as DataMember, + 'Capital Rollup' as Identifier, + 'int.FactSPDirectBalAccount' as Source, + 'Capital Rollup "'+ source.SPCapitalRollupName +'" is present in int.FactSPDirectBalAccount but is not present in the SP Capital Rollup Dimension' as Explanation +FROM + [int].[FactSPDirectBalAccount] source +WHERE + NOT EXISTS (select 1 FROM [sp].[viewDimSPCapitalRollup] cr where source.SPCapitalRollupName=cr.Name) + + +UNION ALL + + +SELECT DISTINCT + source.TimeClassCode as DataMember, + 'Time Class' as Identifier, + 'int.FactSPDirectBalAccount' as Source, + 'Time Class "'+ source.TimeClassCode +'" is present in int.FactSPDirectBalAccount but is not present in the Time Class Dimension' as Explanation +FROM + int.FactSPDirectBalAccount source +WHERE + source.TimeClassID=0 + + +UNION ALL + + +SELECT DISTINCT + source.FiscalYearCode as DataMember, + 'Fiscal Year' as Identifier, + 'int.FactSPDirectBalAccount' as Source, + 'Fiscal Year "'+ source.FiscalYearCode +'" is present in int.FactSPDirectBalAccount but is not present in the Fiscal Year Dimension' as Explanation +FROM + int.FactSPDirectBalAccount source +WHERE + source.FiscalYearID=0 + + +UNION ALL + + +SELECT DISTINCT + source.UnitType as DataMember, + 'Unit Type' as Identifier, + 'int.FactSPDirectBalAccount' as Source, + 'Unit Type "'+ source.UnitType +'" is present in int.FactSPDirectBalAccount but is not present in the Unit Type Dimension' as Explanation +FROM + int.FactSPDirectBalAccount source +WHERE + source.UnitTypeID=0 +GO + + +--------------------------------------------- + +-- int.viewReportExceptionsFactSPDirectISAccount +CREATE VIEW [int].[viewReportExceptionsFactSPDirectISAccount] +AS +------------- int.FactSPDirectISAccount exceptions ------------- + +SELECT DISTINCT + source.SPLongRangePlanName as DataMember, + 'Operations Plan' as Identifier, + 'int.FactSPDirectISAccount' as Source, + 'Operations Plan "'+ source.SPLongRangePlanName +'" is present in int.FactSPDirectISAccount but is not present in the SP Long Range Plan Dimension' as Explanation +FROM + [int].[FactSPDirectISAccount] source +WHERE + source.SPLongRangePlanID=0 + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Account Rollup' as Identifier, + 'int.FactSPDirectISAccount' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISAccount but is not present in the SP Account Rollup Dimension' as Explanation +FROM + [int].[FactSPDirectISAccount] source +WHERE + source.AccountRollupID=0 + + +UNION ALL + + +SELECT DISTINCT + source.TimeClassCode as DataMember, + 'Time Class' as Identifier, + 'int.FactSPDirectISAccount' as Source, + 'Time Class "'+ source.TimeClassCode +'" is present in int.FactSPDirectISAccount but is not present in the Time Class Dimension' as Explanation +FROM + int.FactSPDirectISAccount source +WHERE + source.TimeClassID=0 + + +UNION ALL + + +SELECT DISTINCT + source.FiscalYearCode as DataMember, + 'Fiscal Year' as Identifier, + 'int.FactSPDirectISAccount' as Source, + 'Fiscal Year "'+ source.FiscalYearCode +'" is present in int.FactSPDirectISAccount but is not present in the Fiscal Year Dimension' as Explanation +FROM + int.FactSPDirectISAccount source +WHERE + source.FiscalYearID=0 + + +UNION ALL + + +SELECT DISTINCT + source.UnitType as DataMember, + 'Unit Type' as Identifier, + 'int.FactSPDirectISAccount' as Source, + 'Unit Type "'+ source.UnitType +'" is present in int.FactSPDirectISAccount but is not present in the Unit Type Dimension' as Explanation +FROM + int.FactSPDirectISAccount source +WHERE + source.UnitTypeID=0 +GO + + +--------------------------------------------- + +-- int.viewReportExceptionsFactSPDirectISPayor +CREATE VIEW [int].[viewReportExceptionsFactSPDirectISPayor] +AS +------------- int.FactSPDirectISPayor exceptions ------------- + +SELECT DISTINCT + source.SPLongRangePlanName as DataMember, + 'Operations Plan' as Identifier, + 'int.FactSPDirectISPayor' as Source, + 'Operations Plan "'+ source.SPLongRangePlanName +'" is present in int.FactSPDirectISPayor but is not present in the SP Long Range Plan Dimension' as Explanation +FROM + [int].[FactSPDirectISPayor] source +WHERE + source.SPLongRangePlanID=0 + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Account Rollup' as Identifier, + 'int.FactSPDirectISPayor' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISPayor but is not present in the SP Account Rollup Dimension' as Explanation +FROM + [int].[FactSPDirectISPayor] source +WHERE + source.AccountRollupID=0 + + +UNION ALL + + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Account Rollup related to a Payor' as Identifier, + 'int.FactSPDirectISPayor' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISPayor but does not have a Payor which is defined in the Payor Group Dimension associated to it. Please review the data file to ensure that it looks accurate' as Explanation +FROM + [int].[FactSPDirectISPayor] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Category='Payor Related Accounts Category' and source.PayorGroupID=0) + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Account Rollup related to a Payor' as Identifier, + 'int.FactSPDirectISPayor' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISPayor but does not have a Patient Type Rollup which is defined in the Patient Type Rollup Dimension associated to it. Please review the data file to ensure that it looks accurate' as Explanation +FROM + [int].[FactSPDirectISPayor] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Category='Payor Related Accounts Category' and source.PatientTypeRollupID=0) + + +UNION ALL + + +SELECT DISTINCT + source.TimeClassCode as DataMember, + 'Time Class' as Identifier, + 'int.FactSPDirectISPayor' as Source, + 'Time Class "'+ source.TimeClassCode +'" is present in int.FactSPDirectISPayor but is not present in the Time Class Dimension' as Explanation +FROM + int.FactSPDirectISPayor source +WHERE + source.TimeClassID=0 + + +UNION ALL + + +SELECT DISTINCT + source.FiscalYearCode as DataMember, + 'Fiscal Year' as Identifier, + 'int.FactSPDirectISPayor' as Source, + 'Fiscal Year "'+ source.FiscalYearCode +'" is present in int.FactSPDirectISPayor but is not present in the Fiscal Year Dimension' as Explanation +FROM + int.FactSPDirectISPayor source +WHERE + source.FiscalYearID=0 + + +UNION ALL + + +SELECT DISTINCT + source.UnitType as DataMember, + 'Unit Type' as Identifier, + 'int.FactSPDirectISPayor' as Source, + 'Unit Type "'+ source.UnitType +'" is present in int.FactSPDirectISPayor but is not present in the Unit Type Dimension' as Explanation +FROM + int.FactSPDirectISPayor source +WHERE + source.UnitTypeID=0 + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectISPayor' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISPayor but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "CMI"' as Explanation +FROM + [int].[FactSPDirectISPayor] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='CMI' and source.UnitType<>'CMI') + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectISPayor' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISPayor but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Volume"' as Explanation +FROM + [int].[FactSPDirectISPayor] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Days' and source.UnitType<>'Volume') + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectISPayor' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISPayor but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Volume"' as Explanation +FROM + [int].[FactSPDirectISPayor] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Total RVUs' and source.UnitType<>'Volume') + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectISPayor' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISPayor but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Volume"' as Explanation +FROM + [int].[FactSPDirectISPayor] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Worked RVUs' and source.UnitType<>'Volume') + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectISPayor' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISPayor but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Volume"' as Explanation +FROM + [int].[FactSPDirectISPayor] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Volume' and source.UnitType<>'Volume') + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectISPayor' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISPayor but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Dollars"' as Explanation +FROM + [int].[FactSPDirectISPayor] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Gross Charges' and source.UnitType<>'Dollars') + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectISPayor' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISPayor but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Dollars"' as Explanation +FROM + [int].[FactSPDirectISPayor] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Contractuals' and source.UnitType<>'Dollars') +GO + + +--------------------------------------------- + +-- int.viewReportExceptionsFactSPDirectISPhysician +CREATE VIEW [int].[viewReportExceptionsFactSPDirectISPhysician] +AS +------------- int.FactSPDirectISPhysician exceptions ------------- + +SELECT DISTINCT + source.SPLongRangePlanName as DataMember, + 'Operations Plan' as Identifier, + 'int.FactSPDirectISPhysician' as Source, + 'Operations Plan "'+ source.SPLongRangePlanName +'" is present in int.FactSPDirectISPhysician but is not present in the SP Long Range Plan Dimension' as Explanation +FROM + [int].[FactSPDirectISPhysician] source +WHERE + source.SPLongRangePlanID=0 + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Account Rollup' as Identifier, + 'int.FactSPDirectISPhysician' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISPhysician but is not present in the SP Account Rollup Dimension' as Explanation +FROM + [int].[FactSPDirectISPhysician] source +WHERE + source.AccountRollupID=0 + + +UNION ALL + + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Account Rollup related to a Physician Group' as Identifier, + 'int.FactSPDirectISPhysician' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISPhysician but does not have a Physician Group which is defined in the Physician Group Dimension associated to it. Please review the data file to ensure that it looks accurate' as Explanation +FROM + [int].[FactSPDirectISPhysician] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Category='Payor Related Accounts Category' and source.PhysicianGroupID=0) + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Patient Type Rollup related to a Physician Group' as Identifier, + 'int.FactSPDirectISPhysician' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISPhysician but has the incorrect Patient Type Rollup associated to it. The suggested patient type rollup for this type of an account rollup is "Clinic"' as Explanation +FROM + [int].[FactSPDirectISPhysician] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Category='Payor Related Accounts Category' and source.PatientTypeRollupCode<>'Clinic') + + +UNION ALL + + +SELECT DISTINCT + source.TimeClassCode as DataMember, + 'Time Class' as Identifier, + 'int.FactSPDirectISPhysician' as Source, + 'Time Class "'+ source.TimeClassCode +'" is present in int.FactSPDirectISPhysician but is not present in the Time Class Dimension' as Explanation +FROM + int.FactSPDirectISPhysician source +WHERE + source.TimeClassID=0 + + +UNION ALL + + +SELECT DISTINCT + source.FiscalYearCode as DataMember, + 'Fiscal Year' as Identifier, + 'int.FactSPDirectISPhysician' as Source, + 'Fiscal Year "'+ source.FiscalYearCode +'" is present in int.FactSPDirectISPhysician but is not present in the Fiscal Year Dimension' as Explanation +FROM + int.FactSPDirectISPhysician source +WHERE + source.FiscalYearID=0 + + +UNION ALL + + +SELECT DISTINCT + source.UnitType as DataMember, + 'Unit Type' as Identifier, + 'int.FactSPDirectISPhysician' as Source, + 'Unit Type "'+ source.UnitType +'" is present in int.FactSPDirectISPhysician but is not present in the Unit Type Dimension' as Explanation +FROM + int.FactSPDirectISPhysician source +WHERE + source.UnitTypeID=0 + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectISPhysician' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISPhysician but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "CMI"' as Explanation +FROM + [int].[FactSPDirectISPhysician] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='CMI' and source.UnitType<>'CMI') + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectISPhysician' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISPhysician but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Volume"' as Explanation +FROM + [int].[FactSPDirectISPhysician] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Days' and source.UnitType<>'Volume') + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectISPhysician' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISPhysician but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Volume"' as Explanation +FROM + [int].[FactSPDirectISPhysician] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Total RVUs' and source.UnitType<>'Volume') + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectISPhysician' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISPhysician but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Volume"' as Explanation +FROM + [int].[FactSPDirectISPhysician] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Worked RVUs' and source.UnitType<>'Volume') + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectISPhysician' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISPhysician but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Volume"' as Explanation +FROM + [int].[FactSPDirectISPhysician] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Volume' and source.UnitType<>'Volume') + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectISPhysician' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISPhysician but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Dollars"' as Explanation +FROM + [int].[FactSPDirectISPhysician] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Gross Charges' and source.UnitType<>'Dollars') + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectISPhysician' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISPhysician but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Dollars"' as Explanation +FROM + [int].[FactSPDirectISPhysician] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Contractuals' and source.UnitType<>'Dollars') +GO + + +--------------------------------------------- + +-- int.viewReportExceptionsFactSPDirectISStaffing +CREATE VIEW [int].[viewReportExceptionsFactSPDirectISStaffing] +AS +------------- int.FactSPDirectISStaffing exceptions ------------- + +SELECT DISTINCT + source.SPLongRangePlanName as DataMember, + 'Operations Plan' as Identifier, + 'int.FactSPDirectISStaffing' as Source, + 'Operations Plan "'+ source.SPLongRangePlanName +'" is present in int.FactSPDirectISStaffing but is not present in the SP Long Range Plan Dimension' as Explanation +FROM + [int].[FactSPDirectISStaffing] source +WHERE + source.SPLongRangePlanID=0 + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Account Rollup' as Identifier, + 'int.FactSPDirectISStaffing' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISStaffing but is not present in the SP Account Rollup Dimension' as Explanation +FROM + [int].[FactSPDirectISStaffing] source +WHERE + source.AccountRollupID=0 + + +UNION ALL + + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Account Rollup related to a Job Code Group' as Identifier, + 'int.FactSPDirectISStaffing' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISStaffing but does not have a Job Code Group which is defined in the Job Code Group Dimension associated to it. Please review the data file to ensure that it looks accurate' as Explanation +FROM + [int].[FactSPDirectISStaffing] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Category='Staffing Related Accounts Category' and source.JobCodeGroupID=0) + + +UNION ALL + + +SELECT DISTINCT + source.TimeClassCode as DataMember, + 'Time Class' as Identifier, + 'int.FactSPDirectISStaffing' as Source, + 'Time Class "'+ source.TimeClassCode +'" is present in int.FactSPDirectISStaffing but is not present in the Time Class Dimension' as Explanation +FROM + int.FactSPDirectISStaffing source +WHERE + source.TimeClassID=0 + + +UNION ALL + + +SELECT DISTINCT + source.FiscalYearCode as DataMember, + 'Fiscal Year' as Identifier, + 'int.FactSPDirectISStaffing' as Source, + 'Fiscal Year "'+ source.FiscalYearCode +'" is present in int.FactSPDirectISStaffing but is not present in the Fiscal Year Dimension' as Explanation +FROM + int.FactSPDirectISStaffing source +WHERE + source.FiscalYearID=0 + + +UNION ALL + + +SELECT DISTINCT + source.UnitType as DataMember, + 'Unit Type' as Identifier, + 'int.FactSPDirectISStaffing' as Source, + 'Unit Type "'+ source.UnitType +'" is present in int.FactSPDirectISStaffing but is not present in the Unit Type Dimension' as Explanation +FROM + int.FactSPDirectISStaffing source +WHERE + source.UnitTypeID=0 + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectISStaffing' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISStaffing but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "FTEs"' as Explanation +FROM + [int].[FactSPDirectISStaffing] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='FTEs' and source.UnitType<>'FTEs') + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectISStaffing' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectISStaffing but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Dollars"' as Explanation +FROM + [int].[FactSPDirectISStaffing] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Salaries' and source.UnitType<>'Dollars') +GO + + +--------------------------------------------- + +-- int.viewReportExceptionsFactSPDirectRollingISAccount +CREATE VIEW [int].[viewReportExceptionsFactSPDirectRollingISAccount] +AS +------------- int.FactSPDirectRollingISAccount exceptions ------------- + +SELECT DISTINCT + source.SPRollingForecastPlanName as DataMember, + 'Rolling Forecast Plan' as Identifier, + 'int.FactSPDirectRollingISAccount' as Source, + 'Rolling Forecast Plan "'+ source.SPRollingForecastPlanName +'" is present in int.FactSPDirectRollingISAccount but is not present in the SP Rolling Forecast Plan Dimension' as Explanation +FROM + [int].[FactSPDirectRollingISAccount] source +WHERE + source.SPRollingForecastPlanID=0 + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Account Rollup' as Identifier, + 'int.FactSPDirectRollingISAccount' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISAccount but is not present in the SP Account Rollup Dimension' as Explanation +FROM + [int].[FactSPDirectRollingISAccount] source +WHERE + source.AccountRollupID=0 + + +UNION ALL + + +SELECT DISTINCT + source.TimeClassCode as DataMember, + 'Time Class' as Identifier, + 'int.FactSPDirectRollingISAccount' as Source, + 'Time Class "'+ source.TimeClassCode +'" is present in int.FactSPDirectRollingISAccount but is not present in the Time Class Dimension' as Explanation +FROM + int.FactSPDirectRollingISAccount source +WHERE + source.TimeClassID=0 + + +UNION ALL + + +SELECT DISTINCT + source.FiscalYearCode as DataMember, + 'Fiscal Year' as Identifier, + 'int.FactSPDirectRollingISAccount' as Source, + 'Fiscal Year "'+ source.FiscalYearCode +'" is present in int.FactSPDirectRollingISAccount but is not present in the Fiscal Year Dimension' as Explanation +FROM + int.FactSPDirectRollingISAccount source +WHERE + source.FiscalYearID=0 + + +UNION ALL + + +SELECT DISTINCT + source.UnitType as DataMember, + 'Unit Type' as Identifier, + 'int.FactSPDirectRollingISAccount' as Source, + 'Unit Type "'+ source.UnitType +'" is present in int.FactSPDirectRollingISAccount but is not present in the Unit Type Dimension' as Explanation +FROM + int.FactSPDirectRollingISAccount source +WHERE + source.UnitTypeID=0 +GO + + +--------------------------------------------- + +-- int.viewReportExceptionsFactSPDirectRollingISPayor +CREATE VIEW [int].[viewReportExceptionsFactSPDirectRollingISPayor] +AS +------------- int.FactSPDirectRollingISPayor exceptions ------------- + +SELECT DISTINCT + source.SPRollingForecastPlanName as DataMember, + 'Rolling Forecast Plan' as Identifier, + 'int.FactSPDirectRollingISPayor' as Source, + 'Rolling Forecast Plan "'+ source.SPRollingForecastPlanName +'" is present in int.FactSPDirectRollingISPayor but is not present in the SP Rolling Forecast Plan Dimension' as Explanation +FROM + [int].[FactSPDirectRollingISPayor] source +WHERE + source.SPRollingForecastPlanID=0 + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Account Rollup' as Identifier, + 'int.FactSPDirectRollingISPayor' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISPayor but is not present in the SP Account Rollup Dimension' as Explanation +FROM + [int].[FactSPDirectRollingISPayor] source +WHERE + source.AccountRollupID=0 + + +UNION ALL + + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Account Rollup related to a Payor' as Identifier, + 'int.FactSPDirectRollingISPayor' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISPayor but does not have a Payor which is defined in the Payor Group Dimension associated to it. Please review the data file to ensure that it looks accurate' as Explanation +FROM + [int].[FactSPDirectRollingISPayor] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Category='Payor Related Accounts Category' and source.PayorGroupID=0) + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Account Rollup related to a Payor' as Identifier, + 'int.FactSPDirectRollingISPayor' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISPayor but does not have a Patient Type Rollup which is defined in the Patient Type Rollup Dimension associated to it. Please review the data file to ensure that it looks accurate' as Explanation +FROM + [int].[FactSPDirectRollingISPayor] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Category='Payor Related Accounts Category' and source.PatientTypeRollupID=0) + + +UNION ALL + + +SELECT DISTINCT + source.TimeClassCode as DataMember, + 'Time Class' as Identifier, + 'int.FactSPDirectRollingISPayor' as Source, + 'Time Class "'+ source.TimeClassCode +'" is present in int.FactSPDirectRollingISPayor but is not present in the Time Class Dimension' as Explanation +FROM + int.FactSPDirectRollingISPayor source +WHERE + source.TimeClassID=0 + + +UNION ALL + + +SELECT DISTINCT + source.FiscalYearCode as DataMember, + 'Fiscal Year' as Identifier, + 'int.FactSPDirectRollingISPayor' as Source, + 'Fiscal Year "'+ source.FiscalYearCode +'" is present in int.FactSPDirectRollingISPayor but is not present in the Fiscal Year Dimension' as Explanation +FROM + int.FactSPDirectRollingISPayor source +WHERE + source.FiscalYearID=0 + + +UNION ALL + + +SELECT DISTINCT + source.UnitType as DataMember, + 'Unit Type' as Identifier, + 'int.FactSPDirectRollingISPayor' as Source, + 'Unit Type "'+ source.UnitType +'" is present in int.FactSPDirectRollingISPayor but is not present in the Unit Type Dimension' as Explanation +FROM + int.FactSPDirectRollingISPayor source +WHERE + source.UnitTypeID=0 + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectRollingISPayor' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISPayor but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "CMI"' as Explanation +FROM + [int].[FactSPDirectRollingISPayor] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='CMI' and source.UnitType<>'CMI') + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectRollingISPayor' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISPayor but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Volume"' as Explanation +FROM + [int].[FactSPDirectRollingISPayor] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Days' and source.UnitType<>'Volume') + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectRollingISPayor' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISPayor but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Volume"' as Explanation +FROM + [int].[FactSPDirectRollingISPayor] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Total RVUs' and source.UnitType<>'Volume') + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectRollingISPayor' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISPayor but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Volume"' as Explanation +FROM + [int].[FactSPDirectRollingISPayor] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Worked RVUs' and source.UnitType<>'Volume') + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectRollingISPayor' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISPayor but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Volume"' as Explanation +FROM + [int].[FactSPDirectRollingISPayor] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Volume' and source.UnitType<>'Volume') + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectRollingISPayor' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISPayor but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Dollars"' as Explanation +FROM + [int].[FactSPDirectRollingISPayor] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Gross Charges' and source.UnitType<>'Dollars') + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectRollingISPayor' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISPayor but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Dollars"' as Explanation +FROM + [int].[FactSPDirectRollingISPayor] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Contractuals' and source.UnitType<>'Dollars') +GO + + +--------------------------------------------- + +-- int.viewReportExceptionsFactSPDirectRollingISPhysician +CREATE VIEW [int].[viewReportExceptionsFactSPDirectRollingISPhysician] +AS +------------- int.FactSPDirectRollingISPhysician exceptions ------------- + +SELECT DISTINCT + source.SPRollingForecastPlanName as DataMember, + 'Rolling Forecast Plan' as Identifier, + 'int.FactSPDirectRollingISPhysician' as Source, + 'Rolling Forecast Plan "'+ source.SPRollingForecastPlanName +'" is present in int.FactSPDirectRollingISPhysician but is not present in the SP Rolling Forecast Plan Dimension' as Explanation +FROM + [int].[FactSPDirectRollingISPhysician] source +WHERE + source.SPRollingForecastPlanID=0 + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Account Rollup' as Identifier, + 'int.FactSPDirectRollingISPhysician' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISPhysician but is not present in the SP Account Rollup Dimension' as Explanation +FROM + [int].[FactSPDirectRollingISPhysician] source +WHERE + source.AccountRollupID=0 + + +UNION ALL + + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Account Rollup related to a Physician Group' as Identifier, + 'int.FactSPDirectRollingISPhysician' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISPhysician but does not have a Physician Group which is defined in the Physician Group Dimension associated to it. Please review the data file to ensure that it looks accurate' as Explanation +FROM + [int].[FactSPDirectRollingISPhysician] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Category='Payor Related Accounts Category' and source.PhysicianGroupID=0) + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Patient Type Rollup related to a Physician Group' as Identifier, + 'int.FactSPDirectRollingISPhysician' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISPhysician but has the incorrect Patient Type Rollup associated to it. The suggested patient type rollup for this type of an account rollup is "Clinic"' as Explanation +FROM + [int].[FactSPDirectRollingISPhysician] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Category='Payor Related Accounts Category' and source.PatientTypeRollupCode<>'Clinic') + + +UNION ALL + + +SELECT DISTINCT + source.TimeClassCode as DataMember, + 'Time Class' as Identifier, + 'int.FactSPDirectRollingISPhysician' as Source, + 'Time Class "'+ source.TimeClassCode +'" is present in int.FactSPDirectRollingISPhysician but is not present in the Time Class Dimension' as Explanation +FROM + int.FactSPDirectRollingISPhysician source +WHERE + source.TimeClassID=0 + + +UNION ALL + + +SELECT DISTINCT + source.FiscalYearCode as DataMember, + 'Fiscal Year' as Identifier, + 'int.FactSPDirectRollingISPhysician' as Source, + 'Fiscal Year "'+ source.FiscalYearCode +'" is present in int.FactSPDirectRollingISPhysician but is not present in the Fiscal Year Dimension' as Explanation +FROM + int.FactSPDirectRollingISPhysician source +WHERE + source.FiscalYearID=0 + + +UNION ALL + + +SELECT DISTINCT + source.UnitType as DataMember, + 'Unit Type' as Identifier, + 'int.FactSPDirectRollingISPhysician' as Source, + 'Unit Type "'+ source.UnitType +'" is present in int.FactSPDirectRollingISPhysician but is not present in the Unit Type Dimension' as Explanation +FROM + int.FactSPDirectRollingISPhysician source +WHERE + source.UnitTypeID=0 + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectRollingISPhysician' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISPhysician but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "CMI"' as Explanation +FROM + [int].[FactSPDirectRollingISPhysician] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='CMI' and source.UnitType<>'CMI') + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectRollingISPhysician' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISPhysician but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Volume"' as Explanation +FROM + [int].[FactSPDirectRollingISPhysician] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Days' and source.UnitType<>'Volume') + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectRollingISPhysician' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISPhysician but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Volume"' as Explanation +FROM + [int].[FactSPDirectRollingISPhysician] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Total RVUs' and source.UnitType<>'Volume') + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectRollingISPhysician' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISPhysician but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Volume"' as Explanation +FROM + [int].[FactSPDirectRollingISPhysician] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Worked RVUs' and source.UnitType<>'Volume') + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectRollingISPhysician' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISPhysician but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Volume"' as Explanation +FROM + [int].[FactSPDirectRollingISPhysician] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Volume' and source.UnitType<>'Volume') + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectRollingISPhysician' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISPhysician but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Dollars"' as Explanation +FROM + [int].[FactSPDirectRollingISPhysician] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Gross Charges' and source.UnitType<>'Dollars') + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectRollingISPhysician' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISPhysician but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Dollars"' as Explanation +FROM + [int].[FactSPDirectRollingISPhysician] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Contractuals' and source.UnitType<>'Dollars') +GO + + +--------------------------------------------- + +-- int.viewReportExceptionsFactSPDirectRollingISStaffing +CREATE VIEW [int].[viewReportExceptionsFactSPDirectRollingISStaffing] +AS +------------- int.FactSPDirectRollingISStaffing exceptions ------------- + +SELECT DISTINCT + source.SPRollingForecastPlanName as DataMember, + 'Operations Plan' as Identifier, + 'int.FactSPDirectRollingISStaffing' as Source, + 'Operations Plan "'+ source.SPRollingForecastPlanName +'" is present in int.FactSPDirectRollingISStaffing but is not present in the SP Rolling Forecast Plan Dimension' as Explanation +FROM + [int].[FactSPDirectRollingISStaffing] source +WHERE + source.SPRollingForecastPlanID=0 + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Account Rollup' as Identifier, + 'int.FactSPDirectRollingISStaffing' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISStaffing but is not present in the SP Account Rollup Dimension' as Explanation +FROM + [int].[FactSPDirectRollingISStaffing] source +WHERE + source.AccountRollupID=0 + + +UNION ALL + + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Account Rollup related to a Job Code Group' as Identifier, + 'int.FactSPDirectRollingISStaffing' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISStaffing but does not have a Job Code Group which is defined in the Job Code Group Dimension associated to it. Please review the data file to ensure that it looks accurate' as Explanation +FROM + [int].[FactSPDirectRollingISStaffing] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Category='Staffing Related Accounts Category' and source.JobCodeGroupID=0) + + +UNION ALL + + +SELECT DISTINCT + source.TimeClassCode as DataMember, + 'Time Class' as Identifier, + 'int.FactSPDirectRollingISStaffing' as Source, + 'Time Class "'+ source.TimeClassCode +'" is present in int.FactSPDirectRollingISStaffing but is not present in the Time Class Dimension' as Explanation +FROM + int.FactSPDirectRollingISStaffing source +WHERE + source.TimeClassID=0 + + +UNION ALL + + +SELECT DISTINCT + source.FiscalYearCode as DataMember, + 'Fiscal Year' as Identifier, + 'int.FactSPDirectRollingISStaffing' as Source, + 'Fiscal Year "'+ source.FiscalYearCode +'" is present in int.FactSPDirectRollingISStaffing but is not present in the Fiscal Year Dimension' as Explanation +FROM + int.FactSPDirectRollingISStaffing source +WHERE + source.FiscalYearID=0 + + +UNION ALL + + +SELECT DISTINCT + source.UnitType as DataMember, + 'Unit Type' as Identifier, + 'int.FactSPDirectRollingISStaffing' as Source, + 'Unit Type "'+ source.UnitType +'" is present in int.FactSPDirectRollingISStaffing but is not present in the Unit Type Dimension' as Explanation +FROM + int.FactSPDirectRollingISStaffing source +WHERE + source.UnitTypeID=0 + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectRollingISStaffing' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISStaffing but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "FTEs"' as Explanation +FROM + [int].[FactSPDirectRollingISStaffing] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='FTEs' and source.UnitType<>'FTEs') + + + +UNION ALL + + +SELECT DISTINCT + source.SPAccountRollupName as DataMember, + 'Unit Type related to an Account Rollup' as Identifier, + 'int.FactSPDirectRollingISStaffing' as Source, + 'Account Rollup "'+ source.SPAccountRollupName +'" is present in int.FactSPDirectRollingISStaffing but has the incorrect Unit Type associated to it. The suggested unit type for this type of an account rollup is "Dollars"' as Explanation +FROM + [int].[FactSPDirectRollingISStaffing] source +WHERE + EXISTS (select 1 FROM [sp].[viewDimAccountRollup] ar where source.SPAccountRollupName = ar.Name and ar.Name='Salaries' and source.UnitType<>'Dollars') +GO + + +--------------------------------------------- + +-- int.viewReportExceptionsFactStaffing +CREATE VIEW [int].[viewReportExceptionsFactStaffing] +AS +------------- int.FactStaffing exceptions ------------- + +SELECT DISTINCT source.DepartmentCode as DataMember, + 'Department' as Identifier, + 'int.FactStaffing' as Source, + 'Department "'+ source.DepartmentCode +'" is present in int.FactStaffing but is not present in the Department Dimension' as Explanation +FROM + int.FactStaffing source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimDepartment WHERE DepartmentCode = source.DepartmentCode) + + +UNION ALL + + +SELECT DISTINCT + source.JobCode as DataMember, + 'Job Code' as Identifier, + 'int.FactStaffing' as Source, + 'Job Code "'+source.JobCode +'" is present in int.FactStaffing but is not present in the Job Code Dimension' as Explanation +FROM + int.FactStaffing source + WHERE NOT EXISTS +(select 1 FROM fw.DimJobCode jcg where source.JobCode=jcg.JobCode) + + + +UNION ALL + + +SELECT DISTINCT + source.PayCode as DataMember, + 'Pay Code' as Identifier, + 'int.FactStaffing' as Source, + 'Pay Code "'+source.PayCode +'" is present in int.FactStaffing but is not present in the Pay Code Dimension' as Explanation +FROM + int.FactStaffing source + WHERE NOT EXISTS +(select 1 FROM fw.DimPayCode pc where pc.PayCode = source.PayCode) + + + +UNION ALL + + +SELECT DISTINCT + source.TimeClassCode as DataMember, + 'Time Class' as Identifier, + 'int.FactStaffing' as Source, + 'Time Class "'+ source.TimeClassCode +'" is present in int.FactStaffing but is not present in the Time Class Dimension' as Explanation +FROM + int.FactStaffing source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimTimeClass WHERE TimeClassCode = source.TimeClassCode) + + +UNION ALL + + +SELECT DISTINCT + source.FiscalYearCode as DataMember, + 'Fiscal Year' as Identifier, + 'int.FactStaffing' as Source, + 'Fiscal Year "'+ source.FiscalYearCode +'" is present in int.FactStaffing but is not present in the Fiscal Year Dimension' as Explanation +FROM + int.FactStaffing source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimFiscalYear WHERE Name = source.FiscalYearCode) + + +UNION ALL + + +SELECT DISTINCT + source.UnitType as DataMember, + 'Unit Type' as Identifier, + 'int.FactStaffing' as Source, + 'Unit Type "'+ source.UnitType +'" is present in int.FactStaffing but is not present in the Unit Type Dimension' as Explanation +FROM + int.FactStaffing source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimUnitType WHERE Name = source.UnitType) + +UNION ALL + + +SELECT DISTINCT + source.FiscalMonthCode as DataMember, + 'Fiscal Month' as Identifier, + 'int.FactStaffing' as Source, + 'Fiscal Month "'+ source.FiscalMonthCode +'" is present in int.FactStaffing but is not present in the Fiscal Month Dimension' as Explanation +FROM + int.FactStaffing source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimFiscalMonth WHERE FiscalMonthCode = source.FiscalMonthCode) + + + UNION ALL + + +SELECT DISTINCT + cast(source.EmployeeCode as nvarchar(20)) as DataMember, + 'Employee Code' as Identifier, + 'int.FactStaffing' as Source, + 'Employee Code "'+ source.EmployeeCode +'" is present in int.FactStaffing but is not present in the Employee Dimension' as Explanation +FROM + int.FactStaffing source +WHERE + NOT EXISTS (select 1 FROM [fw].[DimEmployee] WHERE Code = source.EmployeeCode) +GO + + +--------------------------------------------- + +-- int.viewReportExceptionsFactStaffingByPayPeriod +CREATE VIEW [int].[viewReportExceptionsFactStaffingByPayPeriod] +AS +------------- int.FactStaffingByPayPeriod exceptions ------------- + +SELECT DISTINCT source.DepartmentCode as DataMember, + 'Department' as Identifier, + 'int.FactStaffingByPayPeriod' as Source, + 'Department "'+ source.DepartmentCode +'" is present in int.FactStaffingByPayPeriod but not present in the Department Dimension' as Explanation +FROM + int.FactStaffingByPayPeriod source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimDepartment WHERE DepartmentCode = source.DepartmentCode) + + +UNION ALL + + +SELECT DISTINCT + source.JobCode as DataMember, + 'Job Code' as Identifier, + 'int.FactStaffingByPayPeriod' as Source, + 'Job Code "'+source.JobCode +'" is present in int.FactStaffingByPayPeriod but not present in the Job Code Dimension' as Explanation +FROM + int.FactStaffingByPayPeriod source + WHERE NOT EXISTS +(select 1 FROM fw.DimJobCode jcg where source.JobCode=jcg.JobCode) + + + +UNION ALL + + +SELECT DISTINCT + source.PayCode as DataMember, + 'Pay Code' as Identifier, + 'int.FactStaffingByPayPeriod' as Source, + 'Pay Code "'+source.PayCode +'" is present in int.FactStaffingByPayPeriod but not present in the Pay Code Dimension' as Explanation +FROM + int.FactStaffingByPayPeriod source + WHERE NOT EXISTS +(select 1 FROM fw.DimPayCode pc where pc.PayCode = source.PayCode) + + + +UNION ALL + + +SELECT DISTINCT + source.PayPeriodCode as DataMember, + 'Pay Period Code' as Identifier, + 'int.FactStaffingByPayPeriod' as Source, + 'Pay Period Code "'+source.PayPeriodCode +'" is present in int.FactStaffingByPayPeriod but not present in the Pay Period Code Dimension' as Explanation +FROM + int.FactStaffingByPayPeriod source + WHERE NOT EXISTS +(select 1 FROM fw.DimPayPeriod pp where pp.PayPeriodCode = source.PayPeriodCode) + + + +UNION ALL + + +SELECT DISTINCT + source.TimeClassCode as DataMember, + 'Time Class' as Identifier, + 'int.FactStaffingByPayPeriod' as Source, + 'Time Class "'+ source.TimeClassCode +'" is present in int.FactStaffingByPayPeriod but not present in the Time Class Dimension' as Explanation +FROM + int.FactStaffingByPayPeriod source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimTimeClass WHERE TimeClassCode = source.TimeClassCode) + + +UNION ALL + + +SELECT DISTINCT + source.FiscalYearCode as DataMember, + 'Fiscal Year' as Identifier, + 'int.FactStaffingByPayPeriod' as Source, + 'Fiscal Year "'+ source.FiscalYearCode +'" is present in int.FactStaffingByPayPeriod but not present in the Fiscal Year Dimension' as Explanation +FROM + int.FactStaffingByPayPeriod source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimFiscalYear WHERE Name = source.FiscalYearCode) + + +UNION ALL + + +SELECT DISTINCT + source.UnitType as DataMember, + 'Unit Type' as Identifier, + 'int.FactStaffingByPayPeriod' as Source, + 'Unit Type "'+ source.UnitType +'" is present in int.FactStaffingByPayPeriod but not present in the Unit Type Dimension' as Explanation +FROM + int.FactStaffingByPayPeriod source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimUnitType WHERE Name = source.UnitType) + + UNION ALL + + +SELECT DISTINCT + cast(source.EmployeeCode as nvarchar(20)) as DataMember, + 'Employee Code' as Identifier, + 'int.FactStaffingByPayPeriod' as Source, + 'Employee Code "'+ source.EmployeeCode +'" is present in int.FactStaffingByPayPeriod but not present in the Employee Dimension' as Explanation +FROM + int.FactStaffingByPayPeriod source +WHERE + NOT EXISTS (select 1 FROM [fw].[DimEmployee] WHERE Code = source.EmployeeCode) +GO + + +--------------------------------------------- + +-- int.viewReportExceptionsFactStaffingSummary +CREATE VIEW [int].[viewReportExceptionsFactStaffingSummary] +AS +------------- int.FactStaffingSummary exceptions ------------- + +SELECT DISTINCT source.DepartmentCode as DataMember, + 'Department' as Identifier, + 'int.FactStaffingSummary' as Source, + 'Department "'+ source.DepartmentCode +'" is present in int.FactStaffingSummary but not present in the Department Dimension' as Explanation +FROM + int.FactStaffingSummary source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimDepartment WHERE DepartmentCode = source.DepartmentCode) + + +UNION ALL + + +SELECT DISTINCT + source.AccountRollupCode as DataMember, + 'SP Account Rollup' as Identifier, + 'int.FactStaffingSummary' as Source, + 'AccountRollup "'+source.AccountRollupCode +'" is present in int.FactStaffingSummary but not present in the SP Account Rollup Dimension' as Explanation +FROM + int.FactStaffingSummary source + WHERE NOT EXISTS +(select 1 FROM sp.DimAccountRollup ar where ar.Name = source.AccountRollupCode) + + +UNION ALL + + +SELECT DISTINCT + source.JobCodeGroup as DataMember, + 'Job Code Group' as Identifier, + 'int.FactStaffingSummary' as Source, + 'JobCodeGroup "'+source.JobCodeGroup +'" is present in int.FactStaffingSummary but not present in the Job Code Group Dimension' as Explanation +FROM + int.FactStaffingSummary source + WHERE NOT EXISTS +(select 1 FROM fw.DimJobCodeGroup sr where source.JobCodeGroup=sr.Name) + +UNION ALL + + +SELECT DISTINCT + source.TimeClassCode as DataMember, + 'Time Class' as Identifier, + 'int.FactStaffingSummary' as Source, + 'Time Class "'+ source.TimeClassCode +'" is present in int.FactStaffingSummary but not present in the Time Class Dimension' as Explanation +FROM + int.FactStaffingSummary source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimTimeClass WHERE TimeClassCode = source.TimeClassCode) + + +UNION ALL + + +SELECT DISTINCT + source.FiscalYearCode as DataMember, + 'Fiscal Year' as Identifier, + 'int.FactStaffingSummary' as Source, + 'Fiscal Year "'+ source.FiscalYearCode +'" is present in int.FactStaffingSummary but not present in the Fiscal Year Dimension' as Explanation +FROM + int.FactStaffingSummary source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimFiscalYear WHERE Name = source.FiscalYearCode) + + +UNION ALL + + +SELECT DISTINCT + source.UnitType as DataMember, + 'Unit Type' as Identifier, + 'int.FactStaffingSummary' as Source, + 'Unit Type "'+ source.UnitType +'" is present in int.FactStaffingSummary but not present in the Unit Type Dimension' as Explanation +FROM + int.FactStaffingSummary source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimUnitType WHERE Name = source.UnitType) + +UNION ALL + + +SELECT DISTINCT + source.FiscalMonthCode as DataMember, + 'Fiscal Month' as Identifier, + 'int.FactStaffingSummary' as Source, + 'Fiscal Month "'+ source.FiscalMonthCode +'" is present in int.FactStaffingSummary but is not present in the Fiscal Month Dimension' as Explanation +FROM + int.FactStaffingSummary source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimFiscalMonth WHERE FiscalMonthCode = source.FiscalMonthCode) +GO + + +--------------------------------------------- + +-- int.viewReportExceptionsFactStatistic +CREATE VIEW [int].[viewReportExceptionsFactStatistic] +AS +------------- int.FactStatistic exceptions ------------- + +SELECT DISTINCT + source.AccountCode as DataMember, + 'Account' as Identifier, + 'int.FactStatistic' as Source, + 'Account "'+source.AccountCode +'" is present in int.FactStatistic but is not present in the Account Dimension' as Explanation +FROM + [int].[FactStatistic] source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimAccount WHERE AccountCode = source.AccountCode) + + +UNION ALL + + +SELECT DISTINCT + source.DepartmentCode as DataMember, + 'Department' as Identifier, + 'int.FactStatistic' as Source, + 'Department "'+ source.DepartmentCode +'" is present in int.FactStatistic but is not present in the Department Dimension' as Explanation +FROM + [int].[FactStatistic] source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimDepartment WHERE DepartmentCode = source.DepartmentCode) + + + +UNION ALL + + +SELECT DISTINCT + source.TimeClassCode as DataMember, + 'Time Class' as Identifier, + 'int.FactStatistic' as Source, + 'Time Class "'+ source.TimeClassCode +'" is present in int.FactStatistic but is not present in the Time Class Dimension' as Explanation +FROM + [int].[FactStatistic]source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimTimeClass WHERE TimeClassCode = source.TimeClassCode) + + +UNION ALL + + +SELECT DISTINCT + source.FiscalYearCode as DataMember, + 'Fiscal Year' as Identifier, + 'int.FactStatistic' as Source, + 'Fiscal Year "'+ source.FiscalYearCode +'" is present in int.FactStatistic but is not present in the Fiscal Year Dimension' as Explanation +FROM + [int].[FactStatistic] source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimFiscalYear WHERE Name = source.FiscalYearCode) + +UNION ALL + + +SELECT DISTINCT + source.FiscalMonthCode as DataMember, + 'Fiscal Month' as Identifier, + 'int.FactStatistic' as Source, + 'Fiscal Month "'+ source.FiscalMonthCode +'" is present in int.FactStatistic but is not present in the Fiscal Month Dimension' as Explanation +FROM + int.FactStatistic source +WHERE + NOT EXISTS (select 1 FROM fw.viewDimFiscalMonth WHERE FiscalMonthCode = source.FiscalMonthCode) +GO + + +--------------------------------------------- + +-- int.viewWeeklyINTStatus +CREATE view [int].[viewWeeklyINTStatus] +as + select + ConfigName, + EndTimeUtc as [Upload Date], + case when IsSuccess = 1 AND HasCompleted = 1 then 'SUCCESS' else 'FAILED' end as [Status], + RowsImported as NumberofRows, + UserNameFirst + ' ' + UserNameLast as ImportUser, + 'NA' as SumofItems + from [dbo].[viewIntTransaction] + where EndTimeUtc >= dateadd(dd, -7, getutcdate()) +GO + + +--------------------------------------------- + +--------------------------------------------- +-- PROCEDURES +--------------------------------------------- + +-- int.procDeleteAllUnusedIntTables +CREATE procedure [int].[procDeleteAllUnusedIntTables] + @AreYouReallySureYouWantToDoThis bit = 0 + --this will drop many tables, if you are unsure, do not run this. +AS + +IF @AreYouReallySureYouWantToDoThis = 1 +BEGIN + +declare @schema varchar(25) = 'int'; +declare @count int = 0; +declare crsCursor CURSOR LOCAL FAST_FORWARD FOR + select t.name from sys.tables t + inner join sys.schemas s on s.schema_id = t.schema_id + where s.name = @schema + +OPEN crsCursor; +DECLARE @tablename varchar(200) +FETCH NEXT FROM crsCursor into @tablename +WHILE (@@FETCH_STATUS = 0) + BEGIN + IF NOT EXISTS (SELECT * FROM [dbo].[IntDataInterfaceSection] WHERE @tablename LIKE '%' + REPLACE( DataInterfaceSectionID,'-','_') + '%') AND ((@tablename LIKE 'Import%' OR @tablename LIKE 'Temp%') AND (@tablename NOT LIKE 'Fact%' AND @tablename NOT LIKE 'QU%' )) + BEGIN + PRINT @tablename + SET @count = @count + 1 + exec procSysDropTable @schema, @tablename + END + FETCH NEXT FROM crsCursor into @tablename + END + PRINT CAST(@count AS varchar) + ' tables were droped.' +CLOSE crsCursor; +DEALLOCATE crsCursor; + +declare @viewschema varchar(25) = 'int'; +declare @viewcount int = 0; +declare crsCursor CURSOR LOCAL FAST_FORWARD FOR + select t.name from sys.views t + inner join sys.schemas s on s.schema_id = t.schema_id + where s.name = @viewschema + +OPEN crsCursor; +DECLARE @viewtablename varchar(200) +FETCH NEXT FROM crsCursor into @viewtablename +WHILE (@@FETCH_STATUS = 0) + BEGIN + IF NOT EXISTS + ( + SELECT top 1 1 + FROM [dbo].[IntDataInterfaceSection] + WHERE 1=1 + and ( + @viewtablename LIKE 'viewImport%' + REPLACE(REPLACE(Name,'-','_'), ' ', '_') + '\_Accepted' ESCAPE '\' + or @viewtablename LIKE 'viewImport%' + REPLACE(REPLACE(Name,'-','_'), ' ', '_') + '\_Rejected' ESCAPE '\' + ) + ) + and @viewtablename LIKE 'viewImport%' + BEGIN + PRINT @viewtablename + SET @viewcount = @viewcount + 1 + exec [dbo].[procSysDropView] @viewschema, @viewtablename + END + FETCH NEXT FROM crsCursor into @viewtablename + END + PRINT CAST(@viewcount AS varchar) + ' views were droped.' +CLOSE crsCursor; +DEALLOCATE crsCursor; + +END +GO + + +--------------------------------------------- + +-- int.procDeleteIntegrationConfig +/************************************************************ +** Author: +** Create Date: +** Description: deletes integration config and +** Last Modified: 2015-10-12 +** GM Release: 2016.1 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 001 2015.10.12 CBB B-08607 adding post action delete +*************************************************************/ + +CREATE proc int.procDeleteIntegrationConfig + @configID uniqueidentifier, + @isExecuting bit = 0 +as + +if @isExecuting = 1 + begin + -- This part could return multiple files + --declare @DataSourceID uniqueidentifier = (select SourceFileID from [dbo].[IntSourceFile] where ConfigID=@configID) + + delete from [dbo].[IntDataInterfaceMap] + where SourceColumnID in + ( + select SourceColumnID + from [dbo].[IntSourceField] + where + DataSourceID in + ( + select TransformationID + from [dbo].[IntTransformation] + where ConfigID=@configID + ) + or DataSourceID in + ( + select SourceFileID + from [dbo].[IntSourceFile] + where ConfigID=@configID + ) + ) + + delete from [dbo].[IntSourceField] + where + DataSourceID in + ( + select TransformationID + from [dbo].[IntTransformation] + where ConfigID=@configID + ) + or DataSourceID in + ( + select SourceFileID + from [dbo].[IntSourceFile] + where ConfigID=@configID + ) + + --CID 1 begin - delete post actions-------------------------------------------------- + delete from [dbo].[IntPostAction] + where ConfigID=@configID + --CID 1 end ------------------------------------------------------------------------- + + delete from [dbo].[IntTransformationLink] + where TargetDataSourceID in + ( + select TransformationID + from [dbo].[IntTransformation] + where ConfigID=@configID + ) + + delete from [dbo].[IntConfigFramework] + where ConfigID=@configID + + delete from [dbo].[IntConfigResponse] + where ConfigID=@configID + + delete from [dbo].[IntSourceFileLocation] + where + SourceFileID in + ( + select SourceFileID + from [dbo].[IntSourceFile] + where ConfigID=@configID + ) + + delete from [dbo].[IntTransformation] + where ConfigID=@configID + + delete from [dbo].[IntSourceFile] + where ConfigID=@configID + + delete from [dbo].[IntConfig] + where ConfigID=@configID + + end + +RETURN +GO + + +--------------------------------------------- + +-- int.procDeleteIntegrationData +create proc [int].[procDeleteIntegrationData] +AS +BEGIN + + --TRUNCATE ALL IMPORT TABLES + declare crsCursor CURSOR LOCAL FAST_FORWARD FOR + select 'truncate table ' + '[int].[' + ObjectName + ']; + DBCC CHECKIDENT (''int.' + ObjectName + ''', RESEED, 1)' + from viewsystables t where schemaname = 'int' and (objectname like '%Import%' or ObjectName like 'Fact%') + and t.ObjectID not in ( + select t.object_id from sys.tables t + inner join sys.schemas s on t.schema_id=s.schema_id + inner join sys.foreign_keys fk on t.object_id=fk.referenced_object_id + ) + order by objectname + open crsCursor; + + DECLARE @sql varchar(1000) --This was the wrong data type + + FETCH NEXT FROM crsCursor into @sql + WHILE (@@FETCH_STATUS = 0) + BEGIN + print @sql + exec (@sql); + FETCH NEXT FROM crsCursor into @sql + END + close crsCursor; + DEALLOCATE crsCursor; + + -- delete tables that have an FK reference to them + declare crsCursor CURSOR LOCAL FAST_FORWARD FOR + select 'delete from ' + '[int].[' + ObjectName + ']; + DBCC CHECKIDENT (''int.' + ObjectName + ''', RESEED, 1)' + from viewsystables t where schemaname = 'int' and (objectname like '%Import%' or ObjectName like 'Fact%') + and t.ObjectID in ( + select t.object_id from sys.tables t + inner join sys.schemas s on t.schema_id=s.schema_id + inner join sys.foreign_keys fk on t.object_id=fk.referenced_object_id + ) + order by objectname + open crsCursor; + FETCH NEXT FROM crsCursor into @sql + WHILE (@@FETCH_STATUS = 0) + BEGIN + print @sql + exec (@sql); + FETCH NEXT FROM crsCursor into @sql + END + close crsCursor; + DEALLOCATE crsCursor; + + --TRUNCATE DATA CONFIGURATION HISTORY + Truncate table [dbo].[IntTransaction] + Truncate table [dbo].[IntTransactionData] + Truncate table [dbo].[IntNotification] + + --Rebuild Indexes and Update Statistics + exec [int].[procOptimizationRebuildIndexesData] + +END +RETURN +GO + + +--------------------------------------------- + +-- int.procDropTempTables +Create procedure [int].[procDropTempTables] as + +declare @schema varchar(25) = 'int'; +declare @tablefilter varchar(50) = 'Temp%'; +declare crsCursor CURSOR LOCAL FAST_FORWARD FOR + select t.name from sys.tables t + inner join sys.schemas s on s.schema_id = t.schema_id + where s.name = @schema and t.name like @tablefilter + +OPEN crsCursor; +DECLARE @tablename varchar(200) +FETCH NEXT FROM crsCursor into @tablename +WHILE (@@FETCH_STATUS = 0) + BEGIN + PRINT @tablename + exec procSysDropTable @schema, @tablename + FETCH NEXT FROM crsCursor into @tablename + END +CLOSE crsCursor; +DEALLOCATE crsCursor; + +RETURN +GO + + +--------------------------------------------- + +-- int.procGetImportUnitsDollarsCalc +CREATE PROCEDURE [int].[procGetImportUnitsDollarsCalc]( + @TransactionID As Int, + @SchemaName As varchar(50), + @TableName As varchar(100) +) +AS +BEGIN + DECLARE @FinalScript NVARCHAR(MAX), + @Value VARCHAR(200) = '', + @Dollars decimal(19,4) = 0, + @Units decimal(19,4) = 0 + + + DECLARE @HasUnitType bit = dbo.ColumnExists(@SchemaName,@TableName,'UnitTypeID') + + DECLARE @DollarsType int + SELECT @DollarsType = UnitTypeID FROM fw.DimUnitType WHERE Name = 'Dollars' + + DECLARE @UnitsType int + SELECT @UnitsType = UnitTypeID FROM fw.DimUnitType WHERE Name = 'Units' + + IF(dbo.ColumnExists(@SchemaName,@TableName,'Value') = 1) + BEGIN + SET @Value = 'Value' + END + + IF(dbo.ColumnExists(@SchemaName,@TableName,'Amount') = 1 And @Value='') + BEGIN + SET @Value = 'Amount' + END + + IF(dbo.ColumnExists(@SchemaName,@TableName,'Total') = 1 And @Value='') + BEGIN + SET @Value = 'Total' + END + + IF(@Value = '') + BEGIN + Select 0 As 'Dollars', 0 As 'Units' + RETURN + END + + SELECT @FinalScript = 'SELECT @Result=sum(' + @Value + ') FROM ' + @SchemaName + '.' + @TableName + ' WHERE TransactionID=' + CAST(@TransactionID As varchar(20)) + + print @Dollars + + IF @Value = 'Total' + BEGIN + exec sp_executesql @FinalScript, N'@Result decimal(19,4) OUTPUT', @Dollars output + + IF(dbo.ColumnExists(@SchemaName,@TableName,'Quantity') = 0) + BEGIN + Select IsNull(@Dollars, 0) As 'Dollars', 0 As 'Units' + RETURN + END + + DECLARE @QuantityScript NVARCHAR(MAX) = 'SELECT @Result=sum(Quantity) FROM ' + @SchemaName + '.' + @TableName + ' WHERE TransactionID=' + CAST(@TransactionID As varchar(20)) + exec sp_executesql @QuantityScript, N'@Result decimal(19,4) OUTPUT', @Units output + + Select IsNull(@Dollars, 0) As 'Dollars', IsNull(@Units, 0) As 'Units' + RETURN + END + + IF (@HasUnitType = 1) + BEGIN + DECLARE @CurrScript NVARCHAR(MAX) = @FinalScript + ' AND UnitTypeID=' + CAST(@DollarsType As varchar(20)) + exec sp_executesql @CurrScript, N'@Result decimal(19,4) OUTPUT', @Dollars output + SET @CurrScript = @FinalScript + ' AND UnitTypeID<>' + CAST(@DollarsType As varchar(20)) + exec sp_executesql @CurrScript, N'@Result decimal(19,4) OUTPUT', @Units output + END + ELSE + BEGIN + exec sp_executesql @FinalScript, N'@Result decimal(19,4) OUTPUT', @Dollars output + END + + Select IsNull(@Dollars, 0) As 'Dollars', IsNull(@Units, 0) As 'Units' +END +GO + + +--------------------------------------------- + +-- int.procImportAcceptedTableDeleteDataForTransaction +/************************************************************ +** Author: lcorbeille +** Create Date: 2022-06-14 +** Description: Removes data out of accepted table to optimize New Member Creation and Sampling for Data loads +** Last Modified: 2022-06-14 +** GM Release: 2022.23 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2022-06-14 rbl Creating proc that can be used as post action to clean up accepted tables and optimize new member creation +*************************************************************/ +CREATE PROC [int].[procImportAcceptedTableDeleteDataForTransaction] + @TransactionGUID uniqueidentifier +AS + +DECLARE @TransactionID VARCHAR(10) = (SELECT TransactionID FROM dbo.IntTransaction WHERE TransactionGUID=@transactionguid); + +IF (@TransactionID IS NULL) RETURN; --shouldn't happen + +SELECT CAST(0 AS smallint) AS IsProcessed,'DELETE FROM ['+x.TABLE_SCHEMA+'].['+x.TABLE_NAME+'] WHERE TransactionID=' AS QueryTextStub +INTO #QueryStubs +FROM INFORMATION_SCHEMA.TABLES x +WHERE + x.TABLE_SCHEMA='int' + AND x.TABLE_NAME LIKE 'Import%Accepted' + AND LEN(x.TABLE_NAME)=52 + AND '['+x.TABLE_SCHEMA+'].['+x.TABLE_NAME+']' IN ( + SELECT '[int].[Import_'+REPLACE(CAST(s.DataInterfaceSectionID AS CHAR(36)),'-','_')+'_Accepted]' + FROM + dbo.IntTransaction t + INNER JOIN dbo.IntConfig c ON t.ConfigID=c.ConfigID + INNER JOIN dbo.IntDataInterfaceSection s ON c.DataInterfaceID=s.DataInterfaceID + WHERE t.TransactionGUID=@TransactionGUID + ) + +DECLARE @QueryStub VARCHAR(450); +DECLARE @SQL VARCHAR(450); + +WHILE EXISTS (SELECT TOP 1 NULL FROM #QueryStubs WHERE IsProcessed=0) +BEGIN + + SET @QueryStub = (SELECT TOP 1 QueryTextStub FROM #QueryStubs WHERE IsProcessed=0); + SET @SQL = @QueryStub+@TransactionID; + EXEC (@SQL); + --PRINT @SQL; + +UPDATE #QueryStubs SET IsProcessed=1 WHERE QueryTextStub=@QueryStub + +END +GO + + +--------------------------------------------- + +-- int.procImportCleanup +CREATE PROCEDURE [int].[procImportCleanup] + -- Add the parameters for the stored procedure here + @IsWeekly As Bit = 1 +AS +BEGIN + + DECLARE @BatchDeleteSQLTemplate VARCHAR(MAX) + DECLARE @FinalScript VARCHAR(MAX) + DECLARE @DateDiffNum INT + + SET @DateDiffNum = -90 + + IF @IsWeekly = 1 + BEGIN + SET @DateDiffNum = -21 + END + + SET @BatchDeleteSQLTemplate = ' + CREATE TABLE ##~CurrTempTable~# (TransactionGuid UNIQUEIDENTIFIER PRIMARY KEY) + + DECLARE @BatchSize_#~CurrTempTable~# INT + SET @BatchSize_#~CurrTempTable~# = 5000 + + INSERT INTO ##~CurrTempTable~# VALUES #~TransactionGUIDList~# + + WHILE @BatchSize_#~CurrTempTable~# <> 0 + BEGIN + DELETE TOP (@BatchSize_#~CurrTempTable~#) FROM #~CurrentImportTableName~# WHERE TransactionGUID IN ( SELECT * FROM ##~CurrTempTable~# ) + SET @BatchSize_#~CurrTempTable~# = @@ROWCOUNT + END + + DROP TABLE ##~CurrTempTable~#' + + SELECT @FinalScript = COALESCE(@FinalScript + ';', '') + TableDeleteScript + FROM + ( + SELECT REPLACE(REPLACE(REPLACE(@BatchDeleteSQLTemplate,'#~CurrTempTable~#',TempTableName),'#~TransactionGUIDList~#',InFilterList),'#~CurrentImportTableName~#',ImportTableName) As TableDeleteScript + FROM + ( + SELECT 'ImpTemp_' + REPLACE(NEWID(),'-','_') as TempTableName,'int.Import_' + REPLACE(dif.DataInterfaceSectionID,'-','_') + '_Accepted' AS ImportTableName , dbo.STRAGGR('(''' + CAST(vit.TransactionGUID AS VARCHAR(100)) + ''')', ',','') As InFilterList + FROM dbo.viewIntTransaction vit + INNER JOIN [dbo].[IntConfig] ic ON vit.ConfigID = ic.ConfigID + INNER JOIN [dbo].[IntDataInterfaceSection] dif ON dif.DataInterfaceID = ic.DataInterfaceID + WHERE vit.StartTimeUtc <= DATEADD(DAY,@DateDiffNum,GETUTCDATE()) + AND OBJECT_ID('int.Import_' + REPLACE(dif.DataInterfaceSectionID,'-','_') + '_Accepted', 'U') IS NOT NULL + GROUP BY DataInterfaceSectionID + ) A + ) B + + PRINT @FinalScript + + EXEC(@FinalScript) + +END + +RETURN +GO + + +--------------------------------------------- + +-- int.procManualIntFactGLTransactionDeletion +CREATE procedure int.procManualIntFactGLTransactionDeletion ( + @TransGUID uniqueidentifier +) +as +begin + + --Delete data from int.FactGL table + delete from [int].[FactGL] + where HistoryItemGUID=@TransGUID + + --Delete the transaction from the transaction tables + exec [dbo].[procIntTransactionDelete] @TransactionGUID = @TransGUID + -- @TransactionGUID (uniqueidentifier) + +end +GO + + +--------------------------------------------- + +-- int.procOptimizationRebuildIndexesData +CREATE proc [int].[procOptimizationRebuildIndexesData] as + +/************************************************************ +** Author: akowalski +** Create Date: 2013-02-18 +** Description: Finds all fact tables in the INT schemas and rebuilds indexes, for use after large imports/deletes +** Last Modified: 2013-02-18 +** GM Release: 2013-03-12 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2013-02-19 DK 56588 Adding update statistics command +** +*************************************************************/ + + +SET NOCOUNT ON; + + DECLARE @SCHEMA nvarchar(256) + DECLARE @FactTableName nvarchar(256) + DECLARE @SQL nvarchar(1024) + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in('int')) and (t.name like 'fact%' and t.name not like '%map') + and t.object_ID not in ( + select distinct t.object_id from sys.tables t + inner join sys.indexes i on t.object_id=i.object_id + inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id + where p.data_compression<>0 + ) order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + --=================== BEGIN CID 1 ===================== + set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD WITH (FILLFACTOR=80) + update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN' + --=================== END CID 1 ======================= + --print @SQL + EXECUTE sp_executesql @SQL + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in('int')) and (t.name like 'fact%' and t.name not like '%map') + and t.object_ID not in ( + select distinct t.object_id from sys.tables t + inner join sys.indexes i on t.object_id=i.object_id + inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id + where p.data_compression=0 + ) order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + --=================== BEGIN CID 1 ===================== + set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD WITH (FILLFACTOR=80,DATA_COMPRESSION = PAGE) + update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN' + --=================== END CID 1 ======================= + --print @SQL + EXECUTE sp_executesql @SQL + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor +RETURN +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableDimensionIDs +CREATE procedure [int].[procRefreshFactTableDimensionIDs] +as +/****************************************************************************** +** Author: unknown +** Create Date: unknown +** Description: Used to refresh dimension IDs as part of the Refresh Data Dimension Links custom action (MR/PR use) +** Last Modified: 2016-12-19 +** GM Release: 2017.1.1 +******************************************************************************* +** Change History +******************************************************************************* +** CID Date Author WI Description +** 1 2016-12-19 srk D-04980 Adding statistic by pay period section +*******************************************************************************/ + +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +-------------------------------------------------------------------FactGL table-------------------------------------------------------------------------------- +--------------------------------------------------------------------------------------------------------------------------------------------------------------- + +exec int.procRefreshFactTableIDsFactGL + +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +-------------------------------------------------------------------FactStatistic table-------------------------------------------------------------------------------- +--------------------------------------------------------------------------------------------------------------------------------------------------------------- + +exec int.procRefreshFactTableIDsFactStatistic + +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +-------------------------------------------------------------------FactStatisticsbyPayPeriod table------------------------------------------------------------- +--------------------------------------------------------------------------------------------------------------------------------------------------------------- + +exec int.procRefreshFactTableIDsFactStatisticByPayPeriod + +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +-------------------------------------------------------------FactPayorSummary table---------------------------------------------------------------------------- +--------------------------------------------------------------------------------------------------------------------------------------------------------------- + +exec int.procRefreshFactTableIDsFactPayorSummary + +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +-------------------------------------------------------------FactPhysicianSummary table------------------------------------------------------------------------ +--------------------------------------------------------------------------------------------------------------------------------------------------------------- + +exec int.procRefreshFactTableIDsFactPhysicianSummary + +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +-------------------------------------------------------------FactSPDirectBalAccount table---------------------------------------------------------------------- +--------------------------------------------------------------------------------------------------------------------------------------------------------------- + +exec int.procRefreshFactTableIDsFactSPDirectBalAccount + +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +-------------------------------------------------------------FactSPDirectISAccount table----------------------------------------------------------------------- +--------------------------------------------------------------------------------------------------------------------------------------------------------------- + +exec int.procRefreshFactTableIDsFactSPDirectISAccount + +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +-------------------------------------------------------------FactSPDirectISPayor table------------------------------------------------------------------------- +--------------------------------------------------------------------------------------------------------------------------------------------------------------- + +exec int.procRefreshFactTableIDsFactSPDirectISPayor + +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +-----------------------------------------------------------FactSPDirectISPhysician table----------------------------------------------------------------------- +--------------------------------------------------------------------------------------------------------------------------------------------------------------- + +exec int.procRefreshFactTableIDsFactSPDirectISPhysician + +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +-----------------------------------------------------------FactSPDirectISStaffing table------------------------------------------------------------------------ +--------------------------------------------------------------------------------------------------------------------------------------------------------------- + +exec int.procRefreshFactTableIDsFactSPDirectISStaffing + +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +-------------------------------------------------------------FactSPDirectISRollingAccount table---------------------------------------------------------------- +--------------------------------------------------------------------------------------------------------------------------------------------------------------- + +exec int.procRefreshFactTableIDsFactSPDirectRollingISAccount + +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +-------------------------------------------------------------FactSPDirectISRollingPayor table------------------------------------------------------------------ +--------------------------------------------------------------------------------------------------------------------------------------------------------------- + +exec int.procRefreshFactTableIDsFactSPDirectRollingISPayor + +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +-----------------------------------------------------------FactSPDirectISRollingPhysician table---------------------------------------------------------------- +--------------------------------------------------------------------------------------------------------------------------------------------------------------- + + +exec int.procRefreshFactTableIDsFactSPDirectRollingISPhysician + + +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +-----------------------------------------------------------FactSPDirectISRollingStaffing table----------------------------------------------------------------- +--------------------------------------------------------------------------------------------------------------------------------------------------------------- + +exec int.procRefreshFactTableIDsFactSPDirectRollingISStaffing + + +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +-------------------------------------------------------------------FactStaffing table-------------------------------------------------------------------------- +--------------------------------------------------------------------------------------------------------------------------------------------------------------- + +exec int.procRefreshFactTableIDsFactStaffing + + + +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +--------------------------------------------------------------FactStaffingByPayPeriod table-------------------------------------------------------------------- +--------------------------------------------------------------------------------------------------------------------------------------------------------------- + +exec int.procRefreshFactTableIDsFactStaffingByPayPeriod + + +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +----------------------------------------------------------------FactStaffingSummary table---------------------------------------------------------------------- +--------------------------------------------------------------------------------------------------------------------------------------------------------------- + +exec int.procRefreshFactTableIDsFactStaffingSummary + +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +----------------------------------------------------------------FactCDM table---------------------------------------------------------------------- +--------------------------------------------------------------------------------------------------------------------------------------------------------------- + +exec [int].[procRefreshFactTableIDsFactCDM] + +--------------------------------------------------------------------------------------------------------------------------------------------------------------- +----------------------------------------------------------------FactServiceLine table---------------------------------------------------------------------- +--------------------------------------------------------------------------------------------------------------------------------------------------------------- + +exec [int].[procRefreshFactTableIDsFactServiceLine] +-- +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactCDM +CREATE procedure int.procRefreshFactTableIDsFactCDM +as + +update + gl +set + gl.DepartmentID=isnull(d.departmentID,0), + gl.ChargeCodeID=isnull(cc.ChargeCodeID,0), + gl.AgeCohortID=isnull(ac.AgeCohortID,0), + gl.MedicalSurgicalID=isnull(ms.MedicalSurgicalID,0), + gl.PatientClassID=isnull(pc.PatientClassID,0), + gl.ServiceLineID=isnull(sl.ServiceLineID,0), + gl.UnitTypeID=isnull(ut.UnitTypeID,0), + gl.FiscalYearID=isnull(fy.FiscalYearID,0), + gl.TimeClassID=isnull(tc.TimeClassID,0), + gl.FiscalMonthID=isnull(fm.FiscalMonthID,0) +from + [int].[FactCDM] gl + left join [fw].[DimDepartment] d on gl.DepartmentCode=d.DepartmentCode + left join [fw].[DimChargeCode] cc on Gl.ChargeCode=cc.ChargeCode + left join [fw].[DimAgeCohort] ac on gl.AgeCohort=ac.code + left join [fw].[DimMedicalSurgical] ms on Gl.MedSurg=ms.Code + left join [fw].[DimPatientClass] pc on Gl.PatientClassCode=pc.Code + left join [fw].[DimServiceLine] sl on gl.ServiceLine=sl.code + left join [fw].[DimUnitType] ut on gl.UnitType=ut.name + left join [fw].[DimFiscalYear] fy on gl.FiscalYearCode = fy.Name + left join [fw].[DimTimeClass] tc on gl.TimeClassCode = tc.TimeClassCode + left join [fw].[DimFiscalMonth] fm on gl.FiscalMonthCode = fm.FiscalMonthCode + + +RETURN +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactFinancialServiceLineCost +/************************************************************ +** Author: blewis +** Create Date: 2015-04-22 +** Description: Refresh IDs on Table FactFinancialServiceLineCost +** Last Modified: 2015-04-22 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 +** +*************************************************************/ + + +Create Proc [int].[procRefreshFactTableIDsFactFinancialServiceLineCost] +as + +Update F +Set + ForecastDetailID=isnull(fd.ForecastDetailID,0) + , EntityID=isnull(e.entityid,0) + , FiscalMonthID=isnull(fm.FiscalMonthID,0) + , FiscalYearID=isnull(fy.FiscalYearID,0) + , ServiceLineID=isnull(sl.ServiceLineID,0) + , AgeCohortID=isnull(ac.AgeCohortID,0) + , PatientClassID=isnull(pc.PatientClassID,0) + , MedicalSurgicalID=isnull(ms.MedicalSurgicalID,0) + , TimeClassID=isnull(tc.TimeClassID,0) + , UnitTypeID=isnull(ut.UnitTypeID,0) + , DepartmentID=isnull(md.DepartmentID,0) +From [int].[FactFinancialServiceLineCost] F +left join [fw].[DimForecastDetail] fd on F.ForecastDetailCode=fd.ForecastDetailCode +left join [fw].[DimEntity] e on e.Code=f.EntityCode +left join [fw].[DimFiscalMonth] fm on fm.FiscalMonthCode=F.FiscalMonthCode +left join [fw].[DimFiscalYear] fy on fy.FiscalYearID=F.FiscalYearID +left join [fw].[DimServiceLine] sl on sl.Code=F.ServiceLineCode +left join [fw].[DimAgeCohort] ac on ac.Code=F.AgeCohortCode +left join [fw].[DimPatientClass] pc on pc.Code=F.PatientClassCode +left join [fw].[DimMedicalSurgical] ms on ms.Code=F.MedicalSurgicalCode +left join [fw].[DimTimeClass] tc on tc.TimeClassCode=F.TimeClassCode +left join [fw].[DimUnitType] ut on F.UnitTypeName=ut.Name +left join [fw].[DimDepartment] md on md.DepartmentCode=F.DepartmentCode +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactFinancialServiceLineRevenue +/************************************************************ +** Author: blewis +** Create Date: 2015-04-22 +** Description: Refresh IDs on Table FactFinancialServiceLineRevenue +** Last Modified: 2015-04-22 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 +** +*************************************************************/ + + +Create Proc [int].[procRefreshFactTableIDsFactFinancialServiceLineRevenue] +as + +Update F +Set + ForecastDetailID=isnull(fd.ForecastDetailID,0) + , EntityID=isnull(e.entityid,0) + , PayorGroupID=isnull(pg.PayorGroupID,0) + , PayorID=isnull(p.PayorID,0) + , FiscalMonthID=isnull(fm.FiscalMonthID,0) + , FiscalYearID=isnull(fy.FiscalYearID,0) + , ServiceLineID=isnull(sl.ServiceLineID,0) + , AgeCohortID=isnull(ac.AgeCohortID,0) + , PatientClassID=isnull(pc.PatientClassID,0) + , MedicalSurgicalID=isnull(ms.MedicalSurgicalID,0) + , TimeClassID=isnull(tc.TimeClassID,0) +From [int].[FactFinancialServiceLineRevenue] F +left join [fw].[DimForecastDetail] fd on F.ForecastDetailCode=fd.ForecastDetailCode +left join [fw].[DimEntity] e on e.Code=f.EntityCode +left join [fw].[DimPayorGroup] pg on pg.PayorGroupCode=F.PayorGroupCode +left join [fw].[DimPayor] p on p.PayorCode=F.PayorCode +left join [fw].[DimFiscalMonth] fm on fm.FiscalMonthCode=F.FiscalMonthCode +left join [fw].[DimFiscalYear] fy on fy.FiscalYearID=F.FiscalYearID +left join [fw].[DimServiceLine] sl on sl.Code=F.ServiceLineCode +left join [fw].[DimAgeCohort] ac on ac.Code=F.AgeCohortCode +left join [fw].[DimPatientClass] pc on pc.Code=F.PatientClassCode +left join [fw].[DimMedicalSurgical] ms on ms.Code=F.MedSurgCode +left join [fw].[DimTimeClass] tc on tc.TimeClassCode=F.TimeClassCode +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactGL +Create procedure int.procRefreshFactTableIDsFactGL +as + +update + gl +set + gl.DepartmentID=isnull(d.departmentID,0), + gl.AccountID=isnull(a.AccountID,0), + gl.FiscalYearID=isnull(fy.FiscalYearID,0), + gl.TimeClassID=isnull(tc.TimeClassID,0), + gl.FiscalMonthID=isnull(fm.FiscalMonthID,0) +from + [int].[FactGL] gl + left join [fw].[DimDepartment] d on gl.DepartmentCode=d.DepartmentCode + left join [fw].[DimAccount] a on gl.AccountCode=a.AccountCode + left join [fw].[DimFiscalYear] fy on gl.FiscalYearCode = fy.Name + left join [fw].[DimTimeClass] tc on gl.TimeClassCode = tc.TimeClassCode + left join [fw].[DimFiscalMonth] fm on gl.FiscalMonthCode = fm.FiscalMonthCode +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactImportProvider +Create procedure int.procRefreshFactTableIDsFactImportProvider +as + +update + p +set + p.DepartmentID=isnull(d.departmentID,0), + p.ProviderID=isnull(pt.ProviderID,0), + p.OBForecastDetailID=isnull(ob.OBForecastDetailID,0), + p.FiscalYearID=isnull(fy.FiscalYearID,0), + p.TimeClassID=isnull(tc.TimeClassID,0), + p.FiscalMonthID=isnull(fm.FiscalMonthID,0) +from + [int].[FactImportProvider] p + left join [fw].[DimDepartment] d on p.DepartmentCode=d.DepartmentCode + left join [fw].[DimProvider] pt on p.ProviderCode=pt.ProviderCode + left join [ob].[DimOBForecastDetail] ob on p.AccountRollup=ob.Code + left join [fw].[DimFiscalYear] fy on p.FiscalYearCode = fy.Name + left join [fw].[DimTimeClass] tc on p.TimeClassCode = tc.TimeClassCode + left join [fw].[DimFiscalMonth] fm on p.FiscalMonthCode = fm.FiscalMonthCode +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactPayorSummary +Create procedure int.procRefreshFactTableIDsFactPayorSummary +as + +update + payor +set + payor.DepartmentID=isnull(d.departmentID,0), + payor.PatientTypeRollupID=isnull(pt.PatientTypeRollupID,0), + payor.AccountRollupID=isnull(ar.AccountRollupID,0), + payor.PayorGroupID=isnull(p.PayorGroupID,0), + payor.FiscalYearID=isnull(fy.FiscalYearID,0), + payor.TimeClassID=isnull(tc.TimeClassID,0), + payor.UnitTypeID=isnull(ut.UnitTypeID,0), + payor.FiscalMonthID=isnull(fm.FiscalMonthID,0) +from + [int].[FactPayorSummary] payor + left join [fw].[DimDepartment] d on payor.DepartmentCode=d.DepartmentCode + left join [fw].[DimPatientTypeRollup] pt on payor.PatientTypeRollupCode=pt.Name + left join [sp].[DimAccountRollup] ar on payor.AccountRollupCode=ar.Name + left join [fw].[DimPayorGroup] p on payor.PayorGroupCode=p.Name + left join [fw].[DimFiscalYear] fy on payor.FiscalYearCode = fy.Name + left join [fw].[DimTimeClass] tc on payor.TimeClassCode = tc.TimeClassCode + left join [fw].[DimUnitType] ut on payor.UnitType = ut.Name + left join [fw].[DimFiscalMonth] fm on payor.FiscalMonthCode = fm.FiscalMonthCode +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactPhysicianSummary +Create procedure int.procRefreshFactTableIDsFactPhysicianSummary +as + +update + physician +set + physician.DepartmentID=isnull(d.departmentID,0), + physician.PatientTypeRollupID=isnull(pt.PatientTypeRollupID,0), + physician.AccountRollupID=isnull(ar.AccountRollupID,0), + physician.PhysicianGroupID=isnull(p.physicianGroupID,0), + physician.FiscalYearID=isnull(fy.FiscalYearID,0), + physician.TimeClassID=isnull(tc.TimeClassID,0), + physician.UnitTypeID=isnull(ut.UnitTypeID,0), + physician.FiscalMonthID=isnull(fm.FiscalMonthID,0) +from + [int].[FactPhysicianSummary] physician + left join [fw].[DimDepartment] d on physician.DepartmentCode=d.DepartmentCode + left join [fw].[DimPatientTypeRollup] pt on physician.PatientTypeRollupCode=pt.Name + left join [sp].[DimAccountRollup] ar on physician.AccountRollupCode=ar.Name + left join [fw].[DimPhysicianGroup] p on physician.PhysicianGroupCode=p.Name + left join [fw].[DimFiscalYear] fy on physician.FiscalYearCode = fy.Name + left join [fw].[DimTimeClass] tc on physician.TimeClassCode = tc.TimeClassCode + left join [fw].[DimUnitType] ut on physician.UnitType = ut.Name + left join [fw].[DimFiscalMonth] fm on physician.FiscalMonthCode = fm.FiscalMonthCode +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactSPDirectBalAccount +Create procedure int.procRefreshFactTableIDsFactSPDirectBalAccount +as + +update + dbal +set + dbal.SPLongRangePlanID=isnull(lrp.SPLongRangePlanID,0), + dbal.AccountRollupID=isnull(ar.AccountRollupID,0), + dbal.SPCapitalRollupID=isnull(cap.SPCapitalRollupID,0), + dbal.SPDebtIssuanceID=isnull(deb.SPDebtIssuanceID,0), + dbal.FiscalYearID=isnull(fy.FiscalYearID,0), + dbal.TimeClassID=isnull(tc.TimeClassID,0), + dbal.UnitTypeID=isnull(ut.UnitTypeID,0) +from + [int].[FactSPDirectBalAccount] dbal + left join [sp].[viewDimSPLongRangePlan] lrp on dbal.SPLongRangePlanName=lrp.Name + left join [sp].[DimAccountRollup] ar on dbal.SPAccountRollupName=ar.Name + left join [sp].[DimSPCapitalRollup] cap on dbal.SPCapitalRollupName=cap.Name + left join [sp].[DimSPDebtIssuance] deb on dbal.SPDebtIssuanceName=deb.Name + left join [fw].[DimFiscalYear] fy on dbal.FiscalYearCode = fy.Name + left join [fw].[DimTimeClass] tc on dbal.TimeClassCode = tc.TimeClassCode + left join [fw].[DimUnitType] ut on dbal.UnitType = ut.Name +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactSPDirectISAccount +Create procedure int.procRefreshFactTableIDsFactSPDirectISAccount +as + +update + disa +set + disa.SPLongRangePlanID=isnull(lrp.SPLongRangePlanID,0), + disa.AccountRollupID=isnull(ar.AccountRollupID,0), + disa.FiscalYearID=isnull(fy.FiscalYearID,0), + disa.TimeClassID=isnull(tc.TimeClassID,0), + disa.UnitTypeID=isnull(ut.UnitTypeID,0) +from + [int].[FactSPDirectISAccount] disa + left join [sp].[viewDimSPLongRangePlan] lrp on disa.SPLongRangePlanName=lrp.Name + left join [sp].[DimAccountRollup] ar on disa.SPAccountRollupName=ar.Name + left join [fw].[DimFiscalYear] fy on disa.FiscalYearCode = fy.Name + left join [fw].[DimTimeClass] tc on disa.TimeClassCode = tc.TimeClassCode + left join [fw].[DimUnitType] ut on disa.UnitType = ut.Name +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactSPDirectISPayor +Create procedure int.procRefreshFactTableIDsFactSPDirectISPayor +as + +update + disp +set + disp.SPLongRangePlanID=isnull(lrp.SPLongRangePlanID,0), + disp.PatientTypeRollupID=isnull(pt.PatientTypeRollupID,0), + disp.AccountRollupID=isnull(ar.AccountRollupID,0), + disp.PayorGroupID=isnull(p.PayorGroupID,0), + disp.FiscalYearID=isnull(fy.FiscalYearID,0), + disp.TimeClassID=isnull(tc.TimeClassID,0), + disp.UnitTypeID=isnull(ut.UnitTypeID,0) +from + [int].[FactSPDirectISPayor] disp + left join [sp].[viewDimSPLongRangePlan] lrp on disp.SPLongRangePlanName=lrp.Name + left join [fw].[DimPatientTypeRollup] pt on disp.PatientTypeRollupCode=pt.Name + left join [sp].[DimAccountRollup] ar on disp.SPAccountRollupName=ar.Name + left join [fw].[DimPayorGroup] p on disp.PayorGroupCode=p.Name + left join [fw].[DimFiscalYear] fy on disp.FiscalYearCode = fy.Name + left join [fw].[DimTimeClass] tc on disp.TimeClassCode = tc.TimeClassCode + left join [fw].[DimUnitType] ut on disp.UnitType = ut.Name +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactSPDirectISPhysician +Create procedure int.procRefreshFactTableIDsFactSPDirectISPhysician +as + +update + disph +set + disph.SPLongRangePlanID=isnull(lrp.SPLongRangePlanID,0), + disph.PatientTypeRollupID=isnull(pt.PatientTypeRollupID,0), + disph.AccountRollupID=isnull(ar.AccountRollupID,0), + disph.PhysicianGroupID=isnull(p.PhysicianGroupID,0), + disph.FiscalYearID=isnull(fy.FiscalYearID,0), + disph.TimeClassID=isnull(tc.TimeClassID,0), + disph.UnitTypeID=isnull(ut.UnitTypeID,0) +from + [int].[FactSPDirectISPhysician] disph + left join [sp].[viewDimSPLongRangePlan] lrp on disph.SPLongRangePlanName=lrp.Name + left join [fw].[DimPatientTypeRollup] pt on disph.PatientTypeRollupCode=pt.Name + left join [sp].[DimAccountRollup] ar on disph.SPAccountRollupName=ar.Name + left join [fw].[DimPhysicianGroup] p on disph.PhysicianGroupCode=p.Name + left join [fw].[DimFiscalYear] fy on disph.FiscalYearCode = fy.Name + left join [fw].[DimTimeClass] tc on disph.TimeClassCode = tc.TimeClassCode + left join [fw].[DimUnitType] ut on disph.UnitType = ut.Name +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactSPDirectISStaffing +Create procedure int.procRefreshFactTableIDsFactSPDirectISStaffing +as + +update + diss +set + diss.SPLongRangePlanID=isnull(lrp.SPLongRangePlanID,0), + diss.AccountRollupID=isnull(ar.AccountRollupID,0), + diss.JobCodeGroupID=isnull(p.JobCodeGroupID,0), + diss.FiscalYearID=isnull(fy.FiscalYearID,0), + diss.TimeClassID=isnull(tc.TimeClassID,0), + diss.UnitTypeID=isnull(ut.UnitTypeID,0) +from + [int].[FactSPDirectISStaffing] diss + left join [sp].[viewDimSPLongRangePlan] lrp on diss.SPLongRangePlanName=lrp.Name + left join [sp].[DimAccountRollup] ar on diss.SPAccountRollupName=ar.Name + left join [fw].[DimJobCodeGroup] p on diss.JobCodeGroup=p.Name + left join [fw].[DimFiscalYear] fy on diss.FiscalYearCode = fy.Name + left join [fw].[DimTimeClass] tc on diss.TimeClassCode = tc.TimeClassCode + left join [fw].[DimUnitType] ut on diss.UnitType = ut.Name +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactSPDirectRollingISAccount +Create procedure int.procRefreshFactTableIDsFactSPDirectRollingISAccount +as + +update + drola +set + drola.SPRollingForecastPlanID=isnull(lrp.SPRollingForecastPlanID,0), + drola.AccountRollupID=isnull(ar.AccountRollupID,0), + drola.FiscalYearID=isnull(fy.FiscalYearID,0), + drola.TimeClassID=isnull(tc.TimeClassID,0), + drola.UnitTypeID=isnull(ut.UnitTypeID,0) +from + [int].[FactSPDirectRollingISAccount] drola + left join [sp].[viewDimSPRollingForecastPlan] lrp on drola.SPRollingForecastPlanName=lrp.Name + left join [sp].[DimAccountRollup] ar on drola.SPAccountRollupName=ar.Name + left join [fw].[DimFiscalYear] fy on drola.FiscalYearCode = fy.Name + left join [fw].[DimTimeClass] tc on drola.TimeClassCode = tc.TimeClassCode + left join [fw].[DimUnitType] ut on drola.UnitType = ut.Name +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactSPDirectRollingISPayor +Create procedure int.procRefreshFactTableIDsFactSPDirectRollingISPayor +as + +update + drolp +set + drolp.SPRollingForecastPlanID=isnull(lrp.SPRollingForecastPlanID,0), + drolp.PatientTypeRollupID=isnull(pt.PatientTypeRollupID,0), + drolp.AccountRollupID=isnull(ar.AccountRollupID,0), + drolp.PayorGroupID=isnull(p.PayorGroupID,0), + drolp.FiscalYearID=isnull(fy.FiscalYearID,0), + drolp.TimeClassID=isnull(tc.TimeClassID,0), + drolp.UnitTypeID=isnull(ut.UnitTypeID,0) +from + [int].[FactSPDirectRollingISPayor] drolp + left join [sp].[viewDimSPRollingForecastPlan] lrp on drolp.SPRollingForecastPlanName=lrp.Name + left join [fw].[DimPatientTypeRollup] pt on drolp.PatientTypeRollupCode=pt.Name + left join [sp].[DimAccountRollup] ar on drolp.SPAccountRollupName=ar.Name + left join [fw].[DimPayorGroup] p on drolp.PayorGroupCode=p.Name + left join [fw].[DimFiscalYear] fy on drolp.FiscalYearCode = fy.Name + left join [fw].[DimTimeClass] tc on drolp.TimeClassCode = tc.TimeClassCode + left join [fw].[DimUnitType] ut on drolp.UnitType = ut.Name +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactSPDirectRollingISPhysician +Create procedure int.procRefreshFactTableIDsFactSPDirectRollingISPhysician +as + + +update + drolph +set + drolph.SPRollingForecastPlanID=isnull(lrp.SPRollingForecastPlanID,0), + drolph.PatientTypeRollupID=isnull(pt.PatientTypeRollupID,0), + drolph.AccountRollupID=isnull(ar.AccountRollupID,0), + drolph.PhysicianGroupID=isnull(p.PhysicianGroupID,0), + drolph.FiscalYearID=isnull(fy.FiscalYearID,0), + drolph.TimeClassID=isnull(tc.TimeClassID,0), + drolph.UnitTypeID=isnull(ut.UnitTypeID,0) +from + [int].[FactSPDirectRollingISPhysician] drolph + left join [sp].[viewDimSPRollingForecastPlan] lrp on drolph.SPRollingForecastPlanName=lrp.Name + left join [fw].[DimPatientTypeRollup] pt on drolph.PatientTypeRollupCode=pt.Name + left join [sp].[DimAccountRollup] ar on drolph.SPAccountRollupName=ar.Name + left join [fw].[DimPhysicianGroup] p on drolph.PhysicianGroupCode=p.Name + left join [fw].[DimFiscalYear] fy on drolph.FiscalYearCode = fy.Name + left join [fw].[DimTimeClass] tc on drolph.TimeClassCode = tc.TimeClassCode + left join [fw].[DimUnitType] ut on drolph.UnitType = ut.Name +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactSPDirectRollingISStaffing +Create procedure int.procRefreshFactTableIDsFactSPDirectRollingISStaffing +as + + +update + drols +set + drols.SPRollingForecastPlanID=isnull(lrp.SPRollingForecastPlanID,0), + drols.AccountRollupID=isnull(ar.AccountRollupID,0), + drols.JobCodeGroupID=isnull(p.JobCodeGroupID,0), + drols.FiscalYearID=isnull(fy.FiscalYearID,0), + drols.TimeClassID=isnull(tc.TimeClassID,0), + drols.UnitTypeID=isnull(ut.UnitTypeID,0) +from + [int].[FactSPDirectRollingISStaffing] drols + left join [sp].[viewDimSPRollingForecastPlan] lrp on drols.SPRollingForecastPlanName=lrp.Name + left join [sp].[DimAccountRollup] ar on drols.SPAccountRollupName=ar.Name + left join [fw].[DimJobCodeGroup] p on drols.JobCodeGroup=p.Name + left join [fw].[DimFiscalYear] fy on drols.FiscalYearCode = fy.Name + left join [fw].[DimTimeClass] tc on drols.TimeClassCode = tc.TimeClassCode + left join [fw].[DimUnitType] ut on drols.UnitType = ut.Name +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactServiceLine +CREATE procedure int.procRefreshFactTableIDsFactServiceLine +as + +update + gl +set + gl.AgeCohortID=isnull(ac.AgeCohortID,0), + gl.MedicalSurgicalID=isnull(ms.MedicalSurgicalID,0), + gl.PatientClassID=isnull(pc.PatientClassID,0), + gl.ServiceLineID=isnull(sl.ServiceLineID,0), + gl.OBForecastDetailID=isnull(fd.OBForecastDetailID,0), + gl.FiscalYearID=isnull(fy.FiscalYearID,0), + gl.TimeClassID=isnull(tc.TimeClassID,0), + gl.FiscalMonthID=isnull(fm.FiscalMonthID,0), + gl.PayorID =isnull(p.PayorID,0), + gl.PayorGroupID =isnull(pg.PayorGroupID,0), + gl.DepartmentID =isnull(d.DepartmentID,0) +from + [int].[FactServiceLine] gl + left join [fw].[DimAgeCohort] ac on gl.AgeCohort=ac.code + left join [fw].[DimMedicalSurgical] ms on Gl.MedSurg=ms.Code + left join [fw].[DimPatientClass] pc on Gl.PatientClassCode=pc.Code + left join [fw].[DimServiceLine] sl on gl.ServiceLine=sl.name + left join [ob].[DimOBForecastDetail] fd on fd.Name=gl.forecastdetail + left join [fw].[DimFiscalYear] fy on gl.FiscalYearCode = fy.Name + left join [fw].[DimTimeClass] tc on gl.TimeClassCode = tc.TimeClassCode + left join [fw].[DimFiscalMonth] fm on gl.FiscalMonthCode = fm.FiscalMonthCode + left join [fw].[DimPayor] p on gl.PayorCode = p.PayorCode + left join [fw].[DimPayorGroup] pg on gl.PayorGroupCode = pg.PayorGroupCode + left join [fw].[DimDepartment] d on gl.DepartmentCode = d.DepartmentCode +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactStaffing +CREATE procedure [int].[procRefreshFactTableIDsFactStaffing] +as + +update + staffing +set + staffing.DepartmentID=isnull(d.departmentID,0), + staffing.JobCodeID=isnull(j.JobCodeID,0), + staffing.PayCodeID=isnull(p.PayCodeID,0), + staffing.FiscalYearID=isnull(fy.FiscalYearID,0), + staffing.TimeClassID=isnull(tc.TimeClassID,0), + staffing.UnitTypeID=isnull(ut.UnitTypeID,0), + staffing.EmployeeID=isnull(e.EmployeeID,0), + staffing.FiscalMonthID=isnull(fm.FiscalMonthID,0) +from + [int].[FactStaffing] staffing + left join [fw].[DimDepartment] d on staffing.DepartmentCode=d.DepartmentCode + left join [fw].[DimJobCode] j on staffing.JobCode=j.JobCode + left join [fw].[DimPayCode] p on staffing.PayCode=p.PayCode + left join [fw].[DimFiscalYear] fy on staffing.FiscalYearCode = fy.Name + left join [fw].[DimTimeClass] tc on staffing.TimeClassCode = tc.TimeClassCode + left join [fw].[DimUnitType] ut on staffing.UnitType = ut.Name + left join [fw].[DimEmployee] e on staffing.EmployeeCode=e.Code + left join [fw].[DimFiscalMonth] fm on staffing.FiscalMonthCode = fm.FiscalMonthCode +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactStaffingByPayPeriod +CREATE procedure [int].[procRefreshFactTableIDsFactStaffingByPayPeriod] + @IsDebugOnly bit = 0 +as +begin + +-------------------------------------------------------------------------------------------------- +-- Logging +-------------------------------------------------------------------------------------------------- + declare @logdesc nvarchar(100) + select @logdesc = + case @IsDebugOnly + when 1 then 'Debug only - Refressh Staffing By Pay Period Fact table IDs' + else 'Refressh Staffing By Pay Period Fact table IDs' + end + + declare @higuid uniqueidentifier + exec procLogScript @logdesc, @higuid output + + print 'HistoryItemGUID = '''+cast(@higuid as varchar(36))+'''' + +-------------------------------------------------------------------------------------------------- +-- Set SQL Column +-------------------------------------------------------------------------------------------------- + declare @SQLColumn as nvarchar(200) + + select @SQLColumn=sa.SQLColumnName + from [dbo].[ScoreAttribute] sa + inner join [dbo].[IntDataInterfaceField] fld + on sa.AttributeGUID=fld.GivenScoreAttributeGUID + where 1=1 + and fld.ScoreKeyGUID = '8fc5efa1-e270-4e75-8add-6965c16ab295' + and fld.DataInterfaceSectionID='cdc2ef8b-987e-4ca6-a06c-22827507f5f5' + +-------------------------------------------------------------------------------------------------- +-- Create SQL script +-------------------------------------------------------------------------------------------------- + declare @sql nvarchar(max) = ' +update staffpayperiod +set staffpayperiod.DepartmentID = isnull(d.departmentID,0), + staffpayperiod.JobCodeID = isnull(j.JobCodeID,0), + staffpayperiod.PayCodeID = isnull(p.PayCodeID,0), + staffpayperiod.PayPeriodID = isnull(pp.PayPeriodID,0), + staffpayperiod.FiscalYearID = isnull(fy.FiscalYearID,0), + staffpayperiod.TimeClassID = isnull(tc.TimeClassID,0), + staffpayperiod.UnitTypeID = isnull(ut.UnitTypeID,0), + staffpayperiod.EmployeeID = isnull(e.EmployeeID,0) +from [int].[FactStaffingByPayPeriod] staffpayperiod + left join [fw].[DimDepartment] d + on staffpayperiod.DepartmentCode=d.DepartmentCode + left join [fw].[DimJobCode] j + on staffpayperiod.JobCode=j.JobCode + left join [fw].[DimPayCode] p + on staffpayperiod.PayCode=p.PayCode + left join [fw].[DimPayPeriod] pp + on staffpayperiod.PayPeriodCode = pp.' + + @SQLColumn + + ' + left join [fw].[DimFiscalYear] fy + on staffpayperiod.FiscalYearCode = fy.Name + left join [fw].[DimTimeClass] tc + on staffpayperiod.TimeClassCode = tc.TimeClassCode + left join [fw].[DimUnitType] ut + on staffpayperiod.UnitType = ut.Name + left join [fw].[DimEmployee] e + on staffpayperiod.EmployeeCode = e.Code' + + if @IsDebugOnly=1 + begin + print(@sql) + end + else + begin + exec(@sql) + end + +end +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactStaffingSummary +Create procedure int.procRefreshFactTableIDsFactStaffingSummary +as + + +update + staff +set + staff.DepartmentID=isnull(d.departmentID,0), + staff.AccountRollupID=isnull(ar.AccountRollupID,0), + staff.JobCodeGroupID=isnull(jc.JobCodeGroupID,0), + staff.FiscalYearID=isnull(fy.FiscalYearID,0), + staff.TimeClassID=isnull(tc.TimeClassID,0), + staff.UnitTypeID=isnull(ut.UnitTypeID,0), + staff.FiscalMonthID=isnull(fm.FiscalMonthID,0) +from + [int].[FactStaffingSummary] staff + left join [fw].[DimDepartment] d on staff.DepartmentCode=d.DepartmentCode + left join [sp].[DimAccountRollup] ar on staff.AccountRollupCode=ar.Name + left join [fw].[DimJobCodeGroup] jc on staff.JobCodeGroup=jc.Name + left join [fw].[DimFiscalYear] fy on staff.FiscalYearCode = fy.Name + left join [fw].[DimTimeClass] tc on staff.TimeClassCode = tc.TimeClassCode + left join [fw].[DimUnitType] ut on staff.UnitType = ut.Name + left join [fw].[DimFiscalMonth] fm on staff.FiscalMonthCode = fm.FiscalMonthCode +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactStatistic +Create procedure int.procRefreshFactTableIDsFactStatistic +as + +update + stat +set + stat.DepartmentID=isnull(d.departmentID,0), + stat.AccountID=isnull(a.AccountID,0), + stat.FiscalYearID=isnull(fy.FiscalYearID,0), + stat.TimeClassID=isnull(tc.TimeClassID,0), + stat.FiscalMonthID=isnull(fm.FiscalMonthID,0) +from + [int].[FactStatistic] stat + left join [fw].[DimDepartment] d on stat.DepartmentCode=d.DepartmentCode + left join [fw].[DimAccount] a on stat.AccountCode=a.AccountCode + left join [fw].[DimFiscalYear] fy on stat.FiscalYearCode = fy.Name + left join [fw].[DimTimeClass] tc on stat.TimeClassCode = tc.TimeClassCode + left join [fw].[DimFiscalMonth] fm on stat.FiscalMonthCode = fm.FiscalMonthCode +GO + + +--------------------------------------------- + +-- int.procRefreshFactTableIDsFactStatisticByPayPeriod +/****************************************************************************** +** Author: srk +** Create Date: 2016-12-19 +** Description: Used to refresh dimension IDs as part of the Refresh Data Dimension Links custom action (MR/PR use) +** Last Modified: 2016-12-19 +** GM Release: 2017.1.1 +******************************************************************************* +** Change History +******************************************************************************* +** CID Date Author WI Description +** 1 2016-12-19 srk D-04980 Creating script so it can be added to the Refresh Data Dimension Links custom action (MR/PR use) +*******************************************************************************/ + +CREATE procedure [int].[procRefreshFactTableIDsFactStatisticByPayPeriod] + @IsDebugOnly bit = 0 +as +begin + +-------------------------------------------------------------------------------------------------- +-- Logging +-------------------------------------------------------------------------------------------------- + declare @logdesc nvarchar(100) + select @logdesc = + case @IsDebugOnly + when 1 then 'Debug only - Refresh Statistic By Pay Period Fact table IDs' + else 'Refresh Statistic By Pay Period Fact table IDs' + end + + declare @higuid uniqueidentifier + exec procLogScript @logdesc, @higuid output + + print 'HistoryItemGUID = '''+cast(@higuid as varchar(36))+'''' + +-------------------------------------------------------------------------------------------------- +-- Set SQL Column +-------------------------------------------------------------------------------------------------- + declare @SQLColumn as nvarchar(200) + + select @SQLColumn=sa.SQLColumnName + from [dbo].[ScoreAttribute] sa + inner join [dbo].[IntDataInterfaceField] fld + on sa.AttributeGUID=fld.GivenScoreAttributeGUID + where 1=1 + and fld.ScoreKeyGUID = '8fc5efa1-e270-4e75-8add-6965c16ab295' -- Code (from Pay Period Dimension) + and fld.DataInterfaceSectionID='b1bf2582-5ddb-4a43-9dce-7c8b41aca4ba' -- Statistics by Pay Period + +-------------------------------------------------------------------------------------------------- +-- Create SQL script +-------------------------------------------------------------------------------------------------- + declare @sql nvarchar(max) = ' +update statpayperiod +set statpayperiod.DepartmentID = isnull(d.departmentID,0), + statpayperiod.AccountID = isnull(a.AccountID,0), + statpayperiod.PayPeriodID = isnull(pp.PayPeriodID,0), + statpayperiod.FiscalYearID = isnull(fy.FiscalYearID,0), + statpayperiod.TimeClassID = isnull(tc.TimeClassID,0) +from [int].[FactStatisticsByPayPeriod] statpayperiod + left join [fw].[DimDepartment] d + on statpayperiod.DepartmentCode=d.DepartmentCode + left join [fw].[DimAccount] a + on statpayperiod.AccountCode=A.AccountCode + left join [fw].[DimPayPeriod] pp + on statpayperiod.PayPeriodCode = pp.' + + @SQLColumn + + ' + left join [fw].[DimFiscalYear] fy + on statpayperiod.FiscalYearCode = fy.Name + left join [fw].[DimTimeClass] tc + on statpayperiod.TimeClassCode = tc.TimeClassCode' + + if @IsDebugOnly=1 + begin + print(@sql) + end + else + begin + exec(@sql) + end + +end +GO + + +--------------------------------------------- + +-- int.procTransferFactFinancialServiceLineRevenueToSPDirectRollingISPayor +CREATE PROC [int].[procTransferFactFinancialServiceLineRevenueToSPDirectRollingISPayor] as +/************************************************************ +** Author: Bart Lewis +** Create Date: 1/19/2015 +** Description: Transfer Fact Financial SL Revenue Data to Fact Direct Rolling IS Payor for Payor Mix +** Last Modified: 2017-04-06 +** GM Release: 2017.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-02-10 akk D-04826 Allowing additional timeclasses +** 2 2017-04-06 srk D-03689 Updated script to join on fiscalmonthid instead of sort order +*************************************************************/ +Delete from [int].[FactSPDirectRollingISPayor] where TransactionID=1 + +Insert into [int].[FactSPDirectRollingISPayor] +([SPRollingForecastPlanID], [SPRollingForecastPlanName], [AccountRollupID], [SPAccountRollupName], [PatientTypeRollupID], [PatientTypeRollupCode], [PayorGroupID], [PayorGroupCode], [UnitTypeID], [UnitType], [TimeClassID], [TimeClassCode], [FiscalYearID], [FiscalYearCode], [ValueMonth01], [ValueMonth02], [ValueMonth03], [ValueMonth04], [ValueMonth05], [ValueMonth06], [ValueMonth07], [ValueMonth08], [ValueMonth09], [ValueMonth10], [ValueMonth11], [ValueMonth12], [TransactionID]) + +select + [SPRollingForecastPlanID], + [SPRollingForecastPlanName], + [AccountRollupID], + [SPAccountRollupName], + [PatientTypeRollupID], + [PatientTypeRollupCode], + [PayorGroupID], + [PayorGroupCode], + [UnitTypeID], + [UnitType], + [TimeClassID], + [TimeClassCode], + [FiscalYearID], + [FiscalYearCode], + ISNULL(Month01, 0) [ValueMonth01], + ISNULL(Month02, 0) [ValueMonth02], + ISNULL(Month03, 0) [ValueMonth03], + ISNULL(Month04, 0) [ValueMonth04], + ISNULL(Month05, 0) [ValueMonth05], + ISNULL(Month06, 0) [ValueMonth06], + ISNULL(Month07, 0) [ValueMonth07], + ISNULL(Month08, 0) [ValueMonth08], + ISNULL(Month09, 0) [ValueMonth09], + ISNULL(Month10, 0) [ValueMonth10], + ISNULL(Month11, 0) [ValueMonth11], + ISNULL(Month12, 0) [ValueMonth12], + 1 as [TransactionID] + From + ( + SELECT + rs.[FiscalYearID] + , rs.[FiscalYearID] as [FiscalYearCode] + , pg.[PayorGroupID] + , pg.Name as [PayorGroupCode] + , ar.[UnitTypeID] as [UnitTypeID] + , ut.[Name] as [UnitType] + , ptr.[PatientTypeRollupID] + , ptr.Name as [PatientTypeRollupCode] + , ar.[AccountRollupID] + , ar.Name as [SPAccountRollupName] + , de.SPRollingForecastSLDrivenModelID [SPRollingForecastPlanID] + , rf.Name as [SPRollingForecastPlanName] + , tc.TimeClassID as [TimeClassID] + , tc.TimeClassCode as [TimeClassCode] + , m.[MonthColumnName] + , SUM(rs.[Value]) as [Amount] + , '00000000-0000-0000-0000-000000000000' as [HistoryItemGUID] + , 1 as [TransactionID] + FROM [int].[FactFinancialServiceLineRevenue] rs + inner join [fw].[DimEntity] de on rs.EntityID=de.EntityID + inner join [sp].[DimSPRollingForecastPlan] rf on de.SPRollingForecastSLDrivenModelID=rf.SPRollingForecastPlanID + inner join [fw].[DimModelingServiceLine] msl on msl.ServiceLineID=rs.ServiceLineID and msl.AgeCohortID=rs.AgeCohortID and msl.PatientClassID=rs.PatientClassID and msl.MedicalSurgicalID=rs.MedicalSurgicalID + inner join [fw].[DimPatientTypeRollup] ptr on msl.PatientClassID=ptr.PatientClassID and ptr.IsSP=1 and ptr.Type In('Inpatient','Outpatient') + inner join [fw].[DimForecastDetail] fd on rs.ForecastDetailCode=fd.ForecastDetailCode + inner join [sp].[DimAccountRollup] ar on fd.SPAccountRollupID=ar.AccountRollupID + inner join [fw].[DimUnitType] ut on ar.UnitTypeID=ut.UnitTypeID + inner join [fw].[DimPayorGroup] pg on pg.PayorGroupCode=rs.PayorGroupCode + -------------BEGIN CID 2----------------- + --inner join [fw].[DimFiscalMonth] m on rs.FiscalMonthID=m.SortOrder + inner join [fw].[DimFiscalMonth] m on rs.FiscalMonthID=m.FiscalMonthID + -------------END CID 2----------------- + inner join [fw].[DimTimeClass] tc on rs.TimeClassID=tc.TimeClassID + where rs.FiscalYearID<>0 and rs.FiscalMonthID<>0 and rs.TimeClassID<>0 + Group by + rs.[FiscalYearID] + , rs.[FiscalMonthID] + , pg.[Name] + , ptr.[PatientTypeRollupID] + , ptr.[Name] + , ar.[Name] + , ar.[UnitTypeID] + , ut.[Name] + , de.SPRollingForecastSLDrivenModelID + , rf.Name + , pg.[PayorGroupID] + , ar.[AccountRollupID] + , m.[MonthColumnName] + , tc.TimeClassID + , tc.TimeClassCode + ) as Data +PIVOT +( +SUM(Amount) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) +) as pvt + + +Update rp +Set + ValueMonth01=Case When rp2.ValueMonth01= 0 Then 0 Else rp.ValueMonth01/rp2.ValueMonth01 End, + ValueMonth02=Case When rp2.ValueMonth02= 0 Then 0 Else rp.ValueMonth02/rp2.ValueMonth02 End, + ValueMonth03=Case When rp2.ValueMonth03= 0 Then 0 Else rp.ValueMonth03/rp2.ValueMonth03 End, + ValueMonth04=Case When rp2.ValueMonth04= 0 Then 0 Else rp.ValueMonth04/rp2.ValueMonth04 End, + ValueMonth05=Case When rp2.ValueMonth05= 0 Then 0 Else rp.ValueMonth05/rp2.ValueMonth05 End, + ValueMonth06=Case When rp2.ValueMonth06= 0 Then 0 Else rp.ValueMonth06/rp2.ValueMonth06 End, + ValueMonth07=Case When rp2.ValueMonth07= 0 Then 0 Else rp.ValueMonth07/rp2.ValueMonth07 End, + ValueMonth08=Case When rp2.ValueMonth08= 0 Then 0 Else rp.ValueMonth08/rp2.ValueMonth08 End, + ValueMonth09=Case When rp2.ValueMonth09= 0 Then 0 Else rp.ValueMonth09/rp2.ValueMonth09 End, + ValueMonth10=Case When rp2.ValueMonth10= 0 Then 0 Else rp.ValueMonth10/rp2.ValueMonth10 End, + ValueMonth11=Case When rp2.ValueMonth11= 0 Then 0 Else rp.ValueMonth11/rp2.ValueMonth11 End, + ValueMonth12=Case When rp2.ValueMonth12= 0 Then 0 Else rp.ValueMonth12/rp2.ValueMonth12 End +from [int].[FactSPDirectRollingISPayor] rp +inner join [int].[FactSPDirectRollingISPayor] rp2 on rp.PayorGroupID=rp2.PayorGroupID + and rp.PatientTypeRollupID=rp2.PatientTypeRollupID + and rp.SPRollingForecastPlanID=rp2.SPRollingForecastPlanID + and rp.TimeClassID=rp2.TimeClassID + and rp.FiscalYearID=rp2.FiscalYearID +where rp.AccountRollupID=65 and rp2.AccountRollupID=3 and rp.TransactionID=1 +GO + + +--------------------------------------------- + +-- int.procTransferStaffingByPayPeriodToStaffing +/***** *********************************************************** +****** Author: akowalski +****** Create Date: 2013-09-19 +****** Description: Transfers Payroll By PayPeriod Data into the FactStaffing Table +****** Last Modified: 2024-10-15 +****** GM Release: 2024.41 +****** *********************************************************** +****** Notes: +****** +****** Run this query to view the configured PayPeriod Accural Method: +****** SELECT [Setting] FROM [dbo].[DBSetting] WHERE [Name] = 'GM_Accrual_Method'; +****** The configured PayPeriod Accural Method determines the logic carried out by this procedure. +****** Explanations of the three PayPeriod Accural Methods outlined below: +****** +****** PROJECTION WITH REVERSE ACCRUAL (DBSETTING='Reverse') +****** If the pay period starts in a month and ends in another, the data from the last pay period is used as a reference to accrue +****** for the remaining of the month based on the days in the current month of the current pay period. +****** The amount accrued for this month will then be subtracted out of the next month. +****** Non-Accrued PCs won't be accrued and will be put in the end month +****** +****** END MONTH ACCRUAL (DBSETTING='End Month') +****** The total value goes to the end month of a pay period +****** +****** DAYS IN MONTH ACCRUAL (DBSETTING='Days In Month') +****** If the end and start months are the same, the total value goes to that month. +****** If the end and start months are different, the data is distributed based on days in each month of the pay period. +****** Non-Accrued PCs won't be accrued and will be put in the end month +****** +****** *********************************************************** +****** Change History: +****** +****** 2024.23 - Removed CID update comments that are 10 years old +****** To see the old comments find CID 14 rollback script: +****** SELECT [RollbackScript] FROM [migration].[MigrationLog] WHERE [Name] = '2024-04-07-00-02 INT - JAZZ-66171 - Alter procTransferStaffingByPayPeriodToStaffing for GM'; +****** Moved PayPeriod Accrual Method explanations into Notes section above +****** +****** *********************************************************** +****** CID Date Author WI Description +****** 1 2014-02-04 akowalski D-01388 Fixing month code select +****** 2 2014-03-03 akowalski D-01526 Changing period days filter to look at perioddayssecond +****** 3 2014-06-12 jgerber B-02192 Adding reverse accrual and end month as options +****** 4 2014-06-12 jgerber Removed Indexing and Statistics for Staffing Table to improve performance +****** 5 2014-06-18 jgerber B-02192 Updating reverse accrual to not use PayPeriodCode +****** 6 2014-06-19 jgerber B-01892 Adding a filter for pay code is accrued attribute +****** 7 2014-07-09 akowalski D-02068 Filtering out transactionID 1 +****** 8 2014-11-03 akowalski Changing delete to chunk delete so it doesn't timeout +****** 9 2015-02-18 akowalski D-02733 Removing Value column from all the group bys +****** 10 2015-10-13 blewis B-08905 Updating to support multiple pay cycles +****** 11 2017-12-19 vyaremko D-04979 Add filter on pay period <> 0 +****** 12 2018-01-12 tparashchak D-06201 Perfomance improving +****** 13 2018-03-22 yrhee D-07041 Increase DepartmentCode field size on temp table +****** 14 2024-04-07 lcunningham JAZZ-66171 Definition reformat & clean up - see 2024.23 blurb above +****** 15 2024-06-14 smeyers JAZZ-71536 Change JobCodeID from smallint to int +****** 16 2024-09-13 sfritts JAZZ-72743 PayCode from varchar(50) to varchar(100) - Extend Field String Limit for Pay Code for Kaiser EPMS +****** 17 2024-10-15 lcunningham JAZZ-78576 Rolling back Part 2 & 3 #TempStaffing INSERT query joins (lines 165 & 236) and DELETE batching method (line 509) to pre-2024.23 logic +****** **********************************************************/ + +CREATE + + PROC [int].[procTransferStaffingByPayPeriodToStaffing] + AS + BEGIN + ------- INITIALIZE VARIABLES + DECLARE @TransactionID int = 1; + + ------ CREATE TEMP TABLE FOR INSERT + DROP TABLE IF EXISTS #TempStaffing; + + CREATE TABLE #TempStaffing ( + [DepartmentID] int NOT NULL, + [DepartmentCode] varchar(100) NOT NULL, + [JobCodeID] int NOT NULL, + [JobCode] varchar(50) NOT NULL, + [PayCodeID] smallint NOT NULL, + [PayCode] varchar(100) NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FiscalYearCode] varchar(20) NOT NULL, + [TimeClassID] tinyint NOT NULL, + [TimeClassCode] varchar(20) NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [UnitType] varchar(20) NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalMonthCode] varchar(20) NOT NULL, + [Value] decimal(19,4) NOT NULL, + [EmployeeID] int NOT NULL, + [Employeecode] nvarchar(2000) NOT NULL, + [TransactionID] int NULL + ); + + + ------ PART 1: PAY PERIOD ACTUAL DATA + ------ This puts all the data into the second month of the pay period + INSERT INTO #TempStaffing ([DepartmentID], [DepartmentCode], [JobCodeID], [JobCode], [PayCodeID], [PayCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], [UnitTypeID], [UnitType], [FiscalMonthID], [FiscalMonthCode], [Value], [EmployeeID], [Employeecode], [TransactionID]) + SELECT [fact].[DepartmentID], + [fact].[DepartmentCode], + [fact].[JobCodeID], + [fact].[JobCode], + [fact].[PayCodeID], + [fact].[PayCode], + [pp].[FiscalYearIDSecond] AS [FiscalYearID], + CAST([pp].[FiscalYearIDSecond] AS varchar(20)) AS [FiscalYearCode], + [fact].[TimeClassID], + [fact].[TimeClassCode], + [fact].[UnitTypeID], + [fact].[UnitType], + [pp].[FiscalMonthIDSecond] AS [FiscalMonthID], + [fm].[FiscalMonthCode] AS [FiscalMonthCode], + SUM([fact].[Value]) AS [Value], + [fact].[EmployeeID], + [fact].[Employeecode], + 1 AS [TransactionID] + + FROM [int].[FactStaffingByPayPeriod] AS [fact] + INNER JOIN [fw].[DimPayPeriod] AS [pp] + ON [pp].[PayPeriodID] = [fact].[PayPeriodID] + + INNER JOIN [fw].[DimFiscalMonth] AS [fm] + ON [pp].[FiscalMonthIDSecond] = [fm].[FiscalMonthID] + AND [pp].[AccrualMethod] = 'Reverse' + + WHERE [fact].[Value] <> 0 + AND [fact].[TransactionID] <> @TransactionID + AND [pp].[PayPeriodID] <> 0 + + GROUP BY + [fact].[DepartmentID], + [fact].[DepartmentCode], + [fact].[JobCodeID], + [fact].[JobCode], + [fact].[PayCodeID], + [fact].[PayCode], + [pp].[FiscalYearIDSecond], + [fact].[TimeClassID], + [fact].[TimeClassCode], + [fact].[UnitTypeID], + [fact].[UnitType], + [pp].[FiscalMonthIDSecond], + [fm].[FiscalMonthCode], + [fact].[EmployeeID], + [fact].[Employeecode]; + + + ------ PART 2: PAY PERIOD ACCRUAL + ------ Accrues data for pay periods that span across 2 months and calculates it based on the previous pay period and days in month + INSERT INTO #TempStaffing ([DepartmentID], [DepartmentCode], [JobCodeID], [JobCode], [PayCodeID], [PayCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], [UnitTypeID], [UnitType], [FiscalMonthID], [FiscalMonthCode], [Value], [EmployeeID], [Employeecode], [TransactionID]) + SELECT [fact].[DepartmentID], + [fact].[DepartmentCode], + [fact].[JobCodeID], + [fact].[JobCode], + [fact].[PayCodeID], + [fact].[PayCode], + [pp].[FiscalYearIDStart] AS [FiscalYearID], + CAST([pp].[FiscalYearIDStart] AS varchar(20)) AS [FiscalYearCode], + [fact].[TimeClassID], + [fact].[TimeClassCode], + [fact].[UnitTypeID], + [fact].[UnitType], + [pp].[FiscalMonthIDStart] AS [FiscalMonthID], + [fm].[FiscalMonthCode] AS [FiscalMonthCode], + SUM(CAST([fact].[Value] * [pp].[DaysInPeriodWeightStart] AS money)) AS [Value], + [fact].[EmployeeID], + [fact].[Employeecode], + 1 AS [TransactionID] + + FROM [fw].[DimPayPeriod] AS [pp] + INNER JOIN [fw].[DimPayPeriod] AS [PPprev] + ON [PPprev].[FiscalYearIDSecond] = CASE + WHEN [pp].[PeriodNumber] = 1 THEN [pp].[FiscalYearIDSecond] - 1 + ELSE [pp].[FiscalYearIDSecond] + END + AND [PPprev].[PeriodNumber] = CASE + WHEN [pp].[PeriodNumber] = 1 THEN ( SELECT MAX([ipp].[PeriodNumber]) + FROM [fw].[DimPayPeriod] AS [ipp] + WHERE [ipp].[FiscalYearIDSecond] = [pp].[FiscalYearIDSecond] - 1 + AND [pp].[PayCycleID] = [ipp].[PayCycleID] ) + ELSE [pp].[PeriodNumber] - 1 + END + AND [pp].[PayCycleID] = [PPprev].[PayCycleID] + + INNER JOIN [int].[FactStaffingByPayPeriod] AS [fact] + ON [PPprev].[PayPeriodID] = [fact].[PayPeriodID] + + INNER JOIN [fw].[DimFiscalMonth] AS [fm] + ON [pp].[FiscalMonthIDStart] = [fm].[FiscalMonthID] + + INNER JOIN [fw].[DimPayCode] AS [pc] + ON [fact].[PayCodeID] = [pc].[PayCodeID] + + WHERE [fact].[Value] <> 0 + AND [pp].[DaysInPeriodWeightSecond] < 1 + AND [pc].[IsAccrued] = 1 + AND [fact].[TransactionID] <> @TransactionID + AND [pp].[AccrualMethod] = 'Reverse' + AND [pp].[PayPeriodID] <> 0 + + GROUP BY + [fact].[DepartmentID], + [fact].[DepartmentCode], + [fact].[JobCodeID], + [fact].[JobCode], + [fact].[PayCodeID], + [fact].[PayCode], + [pp].[FiscalYearIDStart], + [fact].[TimeClassID], + [fact].[TimeClassCode], + [fact].[UnitTypeID], + [fact].[UnitType], + [pp].[FiscalMonthIDStart], + [fm].[FiscalMonthCode], + [fact].[EmployeeID], + [fact].[Employeecode]; + + + ------ PART 3: PAY PERIOD ACCRUAL REVERSE + ------ Adds negative value of accrual to the second month of the pay period for pay periods that span across 2 months + INSERT INTO #TempStaffing ([DepartmentID], [DepartmentCode], [JobCodeID], [JobCode], [PayCodeID], [PayCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], [UnitTypeID], [UnitType], [FiscalMonthID], [FiscalMonthCode], [Value], [EmployeeID], [Employeecode], [TransactionID]) + SELECT [fact].[DepartmentID], + [fact].[DepartmentCode], + [fact].[JobCodeID], + [fact].[JobCode], + [fact].[PayCodeID], + [fact].[PayCode], + [pp].[FiscalYearIDSecond] AS [FiscalYearID], + CAST([pp].[FiscalYearIDSecond] AS varchar(20)) AS [FiscalYearCode], + [fact].[TimeClassID], + [fact].[TimeClassCode], + [fact].[UnitTypeID], + [fact].[UnitType], + [pp].[FiscalMonthIDSecond] AS [FiscalMonthID], + [fm].[FiscalMonthCode] AS [FiscalMonthCode], + SUM(CAST(-[fact].[Value] * [pp].[DaysInPeriodWeightStart] AS money)) AS [Value], + [fact].[EmployeeID], + [fact].[Employeecode], + 1 AS [TransactionID] + + FROM [fw].[DimPayPeriod] AS [pp] + INNER JOIN [fw].[DimPayPeriod] AS [PPprev] + ON [PPprev].[FiscalYearIDSecond] = CASE + WHEN [pp].[PeriodNumber] = 1 THEN [pp].[FiscalYearIDSecond] - 1 + ELSE [pp].[FiscalYearIDSecond] + END + AND [PPprev].[PeriodNumber] = CASE + WHEN [pp].[PeriodNumber] = 1 THEN ( SELECT MAX([ipp].[PeriodNumber]) + FROM [fw].[DimPayPeriod] AS [ipp] + WHERE [ipp].[FiscalYearIDSecond] = [pp].[FiscalYearIDSecond] - 1 + AND [pp].[PayCycleID] = [ipp].[PayCycleID] ) + ELSE [pp].[PeriodNumber] - 1 + END + AND [pp].[PayCycleID] = [PPprev].[PayCycleID] + + INNER JOIN [int].[FactStaffingByPayPeriod] AS [fact] + ON [PPprev].[PayPeriodID] = [fact].[PayPeriodID] + + INNER JOIN [fw].[DimFiscalMonth] AS [fm] + ON [pp].[FiscalMonthIDSecond] = [fm].[FiscalMonthID] + + INNER JOIN [fw].[DimPayCode] AS [pc] + ON [fact].[PayCodeID] = [pc].[PayCodeID] + + WHERE [fact].[Value] <> 0 + AND [pp].[DaysInPeriodWeightSecond] < 1 + AND [pc].[IsAccrued] = 1 + AND [fact].[TransactionID] <> @TransactionID + AND [pp].[AccrualMethod] = 'Reverse' + AND [pp].[PayPeriodID] <> 0 + + GROUP BY + [fact].[DepartmentID], + [fact].[DepartmentCode], + [fact].[JobCodeID], + [fact].[JobCode], + [fact].[PayCodeID], + [fact].[PayCode], + [pp].[FiscalYearIDSecond], + [fact].[TimeClassID], + [fact].[TimeClassCode], + [fact].[UnitTypeID], + [fact].[UnitType], + [pp].[FiscalMonthIDSecond], + [fm].[FiscalMonthCode], + [fact].[EmployeeID], + [fact].[Employeecode]; + + + ------ PART 4: PAY PERIOD ACCRUAL END MONTH (DBSETTING='End Month') + ------ The total value goes to the end month of a pay period + INSERT INTO #TempStaffing ([DepartmentID], [DepartmentCode], [JobCodeID], [JobCode], [PayCodeID], [PayCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], [UnitTypeID], [UnitType], [FiscalMonthID], [FiscalMonthCode], [Value], [EmployeeID], [Employeecode], [TransactionID]) + SELECT [fact].[DepartmentID], + [fact].[DepartmentCode], + [fact].[JobCodeID], + [fact].[JobCode], + [fact].[PayCodeID], + [fact].[PayCode], + [pp].[FiscalYearIDSecond] AS [FiscalYearID], + CAST([pp].[FiscalYearIDSecond] AS varchar(20)) AS [FiscalYearCode], + [fact].[TimeClassID], + [fact].[TimeClassCode], + [fact].[UnitTypeID], + [fact].[UnitType], + [pp].[FiscalMonthIDSecond] AS [FiscalMonthID], + [fm].[FiscalMonthCode] AS [FiscalMonthCode], + SUM([fact].[Value]) AS [Value], + [fact].[EmployeeID], + [fact].[Employeecode], + 1 AS [TransactionID] + + FROM [int].[FactStaffingByPayPeriod] AS [fact] + INNER JOIN [fw].[DimPayPeriod] AS [pp] + ON [pp].[PayPeriodID] = [fact].[PayPeriodID] + + INNER JOIN [fw].[DimFiscalMonth] AS [fm] + ON [pp].[FiscalMonthIDSecond] = [fm].[FiscalMonthID] + + WHERE [fact].[Value] <> 0 + AND [fact].[TransactionID] <> @TransactionID + AND [pp].[AccrualMethod] = 'End Month' + AND [pp].[PayPeriodID] <> 0 + + GROUP BY + [fact].[DepartmentID], + [fact].[DepartmentCode], + [fact].[JobCodeID], + [fact].[JobCode], + [fact].[PayCodeID], + [fact].[PayCode], + [pp].[FiscalYearIDSecond], + [fact].[TimeClassID], + [fact].[TimeClassCode], + [fact].[UnitTypeID], + [fact].[UnitType], + [pp].[FiscalMonthIDSecond], + [fm].[FiscalMonthCode], + [fact].[EmployeeID], + [fact].[Employeecode]; + + + ------ PART 5: PAY PERIOD ACCRUAL DAYS IN MONTH (DBSETTING='Days In Month') + ------ If the end and start months are the same, the total value goes to that month. + ------ If the end and start months are different, the data is distributed based on days in each month of the pay period. + ------ Non-Accrued PCs won't be accrued and will be put in the end month. + + ------ PART 5a: FIRST MONTH + INSERT INTO #TempStaffing ([DepartmentID], [DepartmentCode], [JobCodeID], [JobCode], [PayCodeID], [PayCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], [UnitTypeID], [UnitType], [FiscalMonthID], [FiscalMonthCode], [Value], [EmployeeID], [Employeecode], [TransactionID]) + SELECT [fact].[DepartmentID], + [fact].[DepartmentCode], + [fact].[JobCodeID], + [fact].[JobCode], + [fact].[PayCodeID], + [fact].[PayCode], + [pp].[FiscalYearIDStart] AS [FiscalYearID], + CAST([pp].[FiscalYearIDStart] AS varchar(20)) AS [FiscalYearCode], + [fact].[TimeClassID], + [fact].[TimeClassCode], + [fact].[UnitTypeID], + [fact].[UnitType], + [pp].[FiscalMonthIDStart] AS [FiscalMonthID], + [fm].[FiscalMonthCode] AS [FiscalMonthCode], + SUM(CAST([fact].[Value] * [pp].[DaysInPeriodWeightStart] AS money)) AS [Value], + [fact].[EmployeeID], + [fact].[Employeecode], + 1 AS [TransactionID] + + FROM [int].[FactStaffingByPayPeriod] AS [fact] + INNER JOIN [fw].[DimPayPeriod] AS [pp] + ON [pp].[PayPeriodID] = [fact].[PayPeriodID] + + INNER JOIN [fw].[DimFiscalMonth] AS [fm] + ON [pp].[FiscalMonthIDStart] = [fm].[FiscalMonthID] + + INNER JOIN [fw].[DimPayCode] AS [pc] + ON [fact].[PayCodeID] = [pc].[PayCodeID] + + WHERE [fact].[Value] <> 0 + AND [pp].[PeriodDaysStart] > 0 + AND [pc].[IsAccrued] = 1 + AND [fact].[TransactionID] <> @TransactionID + AND [pp].[AccrualMethod] = 'Days In Month' + AND [pp].[PayPeriodID] <> 0 + + GROUP BY + [fact].[DepartmentID], + [fact].[DepartmentCode], + [fact].[JobCodeID], + [fact].[JobCode], + [fact].[PayCodeID], + [fact].[PayCode], + [pp].[FiscalYearIDStart], + [fact].[TimeClassID], + [fact].[TimeClassCode], + [fact].[UnitTypeID], + [fact].[UnitType], + [pp].[FiscalMonthIDStart], + [fm].[FiscalMonthCode], + [fact].[EmployeeID], + [fact].[Employeecode]; + + ------ PART 5b: SECOND MONTH + INSERT INTO #TempStaffing ([DepartmentID], [DepartmentCode], [JobCodeID], [JobCode], [PayCodeID], [PayCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], [UnitTypeID], [UnitType], [FiscalMonthID], [FiscalMonthCode], [Value], [EmployeeID], [Employeecode], [TransactionID]) + SELECT [fact].[DepartmentID], + [fact].[DepartmentCode], + [fact].[JobCodeID], + [fact].[JobCode], + [fact].[PayCodeID], + [fact].[PayCode], + [pp].[FiscalYearIDSecond] AS [FiscalYearID], + CAST([pp].[FiscalYearIDSecond] AS varchar(20)) AS [FiscalYearCode], + [fact].[TimeClassID], + [fact].[TimeClassCode], + [fact].[UnitTypeID], + [fact].[UnitType], + [pp].[FiscalMonthIDSecond] AS [FiscalMonthID], + [fm].[FiscalMonthCode] AS [FiscalMonthCode], + SUM(CAST([fact].[Value] * [pp].[DaysInPeriodWeightSecond] AS money)) AS [Value], + [fact].[EmployeeID], + [fact].[Employeecode], + 1 AS [TransactionID] + + FROM [int].[FactStaffingByPayPeriod] AS [fact] + INNER JOIN [fw].[DimPayPeriod] AS [pp] + ON [pp].[PayPeriodID] = [fact].[PayPeriodID] + + INNER JOIN [fw].[DimFiscalMonth] AS [fm] + ON [pp].[FiscalMonthIDSecond] = [fm].[FiscalMonthID] + + INNER JOIN [fw].[DimPayCode] AS [pc] + ON [fact].[PayCodeID] = [pc].[PayCodeID] + + WHERE [fact].[Value] <> 0 + AND [pp].[PeriodDaysSecond] > 0 + AND [pc].[IsAccrued] = 1 + AND [fact].[TransactionID] <> @TransactionID + AND [pp].[AccrualMethod] = 'Days In Month' + AND [pp].[PayPeriodID] <> 0 + + GROUP BY + [fact].[DepartmentID], + [fact].[DepartmentCode], + [fact].[JobCodeID], + [fact].[JobCode], + [fact].[PayCodeID], + [fact].[PayCode], + [pp].[FiscalYearIDSecond], + [fact].[TimeClassID], + [fact].[TimeClassCode], + [fact].[UnitTypeID], + [fact].[UnitType], + [pp].[FiscalMonthIDSecond], + [fm].[FiscalMonthCode], + [fact].[EmployeeID], + [fact].[Employeecode]; + + ------ PART 5c: NON-ACCRUED PCs + INSERT INTO #TempStaffing ([DepartmentID], [DepartmentCode], [JobCodeID], [JobCode], [PayCodeID], [PayCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], [UnitTypeID], [UnitType], [FiscalMonthID], [FiscalMonthCode], [Value], [EmployeeID], [Employeecode], [TransactionID]) + SELECT [fact].[DepartmentID], + [fact].[DepartmentCode], + [fact].[JobCodeID], + [fact].[JobCode], + [fact].[PayCodeID], + [fact].[PayCode], + [pp].[FiscalYearIDSecond] AS [FiscalYearID], + CAST([pp].[FiscalYearIDSecond] AS varchar(20)) AS [FiscalYearCode], + [fact].[TimeClassID], + [fact].[TimeClassCode], + [fact].[UnitTypeID], + [fact].[UnitType], + [pp].[FiscalMonthIDSecond] AS [FiscalMonthID], + [fm].[FiscalMonthCode] AS [FiscalMonthCode], + SUM([fact].[Value]) AS [Value], + [fact].[EmployeeID], + [fact].[Employeecode], + 1 AS [TransactionID] + + FROM [int].[FactStaffingByPayPeriod] AS [fact] + INNER JOIN [fw].[DimPayPeriod] AS [pp] + ON [pp].[PayPeriodID] = [fact].[PayPeriodID] + + INNER JOIN [fw].[DimFiscalMonth] AS [fm] + ON [pp].[FiscalMonthIDSecond] = [fm].[FiscalMonthID] + + INNER JOIN [fw].[DimPayCode] AS [pc] + ON [fact].[PayCodeID] = [pc].[PayCodeID] + + WHERE [fact].[Value] <> 0 + AND [pc].[IsAccrued] = 0 + AND [fact].[TransactionID] <> @TransactionID + AND [pp].[AccrualMethod] = 'Days In Month' + AND [pp].[PayPeriodID] <> 0 + + GROUP BY + [fact].[DepartmentID], + [fact].[DepartmentCode], + [fact].[JobCodeID], + [fact].[JobCode], + [fact].[PayCodeID], + [fact].[PayCode], + [pp].[FiscalYearIDSecond], + [fact].[TimeClassID], + [fact].[TimeClassCode], + [fact].[UnitTypeID], + [fact].[UnitType], + [pp].[FiscalMonthIDSecond], + [fm].[FiscalMonthCode], + [fact].[EmployeeID], + [fact].[Employeecode]; + + + ------ PART 6: DELETE PREVIOUSLY TRANSFERRED DATA + + IF EXISTS + ( SELECT NULL + FROM [int].[FactStaffing] + WHERE [TransactionID] <> @TransactionID + ) + BEGIN + WHILE 1 = 1 + BEGIN + DELETE TOP (100000) + FROM [int].[FactStaffing] + WHERE [TransactionID] = @TransactionID; + + IF @@ROWCOUNT < 100000 BREAK; + END; + END; + ELSE + BEGIN + TRUNCATE TABLE [int].[FactStaffing]; + END; + + + ------ PART 7: INSERT INTO DESTINATION TABLE + + INSERT INTO [int].[FactStaffing] ([DepartmentID], [DepartmentCode], [JobCodeID], [JobCode], [PayCodeID], [PayCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], [UnitTypeID], [UnitType], [FiscalMonthID], [FiscalMonthCode], [Value], [EmployeeID], [Employeecode], [TransactionID]) + SELECT [DepartmentID], + [DepartmentCode], + [JobCodeID], + [JobCode], + [PayCodeID], + [PayCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + [UnitTypeID], + [UnitType], + [FiscalMonthID], + [FiscalMonthCode], + SUM([Value]) AS [Value], + [EmployeeID], + [Employeecode], + 1 AS [TransactionID] + + FROM #TempStaffing + GROUP BY + [DepartmentID], + [DepartmentCode], + [JobCodeID], + [JobCode], + [PayCodeID], + [PayCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + [UnitTypeID], + [UnitType], + [FiscalMonthID], + [FiscalMonthCode], + [EmployeeID], + [Employeecode]; + END; +GO + + +--------------------------------------------- + +-- int.procTransferStaffingToStaffingByPayPeriod +CREATE proc [int].[procTransferStaffingToStaffingByPayPeriod] as +BEGIN +/************************************************************ +** Author: ramancharla +** Create Date: 2013-10-07 +** Description: Transfers FactStaffing Table into Payroll By PayPeriod Data +** Last Modified: 2014-11-03 +** GM Release: 2015.1 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 11/22/13 ramancharla Updating payperiod and unit type +** to smallint from tinyint +** 2 2014-07-09 akk D-02068 Filtering out transactionID 1 +** 3 2014-11-03 akk Changing delete to chunk delete so it doesn't timeout +** 4 2016-01-15 mjs D-03862 Adding check for PayCycleID +** 5 2018-03-22 yr D-07041 Increase DepartmentCode field size on temp table +** 6 2020-01-21 IH D-09186 Increase the deletion sizes from 10K to 100K +** 7 2020-10-05 HV JAZZ-1487 MR "Transfer Budget Data" filtering on currently year, not transferring correctly to first/last pay periods +** 8 2022-12-19 BK JAZZ-47041 MR "Transfer Budget Data" increase temp table column size to prevent failing when int.FactStaffing EmployeeCode is longer than 50 characters +** 9 2024-06-14 SM JAZZ-71536 change JobCodeID from smallint to int +** 10 2024-09-13 SF JAZZ-72743 PayCode from varchar(50) to varchar(100) - Extend Field String Limit for Pay Code for Kaiser EPMS +*************************************************************/ + + + /******** Variable Declaration **********/ + declare @TransactionID int = 1 + + /******** Build Rows to Insert **********/ + + CREATE TABLE #TEMPSTAFFINGPAYPERIOD ( + [DepartmentID] [int] NOT NULL, + [DepartmentCode] [varchar](100) NOT NULL, + [JobCodeID] [int] NOT NULL, + [JobCode] [varchar](50) NOT NULL, + [PayCodeID] [smallint] NOT NULL, + [PayCode] [varchar](100) NOT NULL, + [FiscalYearID] [smallint] NOT NULL, + [FiscalYearCode] [varchar](20) NOT NULL, + [TimeClassID] [tinyint] NOT NULL, + [TimeClassCode] [varchar](20) NOT NULL, + [UnitTypeID] [smallint] NOT NULL, + [UnitType] [varchar](20) NOT NULL, + [PayPeriodID] [smallint] NOT NULL, + [PayPeriodCode] [varchar](20) NOT NULL, + [Value] [decimal](19, 4) NOT NULL, + [EmployeeID] [int] NOT NULL, + [Employeecode] [varchar](2000) NOT NULL, + [TransactionID] [int] NULL + ) + + + insert into #TEMPSTAFFINGPAYPERIOD ([DepartmentID], [DepartmentCode], [JobCodeID], [JobCode], [PayCodeID], [PayCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], [UnitTypeID], [UnitType], [PayPeriodID], [PayPeriodCode], [Value], [EmployeeID], [Employeecode], [TransactionID]) + select + fact.[DepartmentID], + fact.[DepartmentCode], + fact.[JobCodeID], + fact.[JobCode], + fact.[PayCodeID], + fact.[PayCode], + PP.FiscalYearIDSecond, + PP.FiscalYearIDSecond, + fact.[TimeClassID], + fact.[TimeClassCode], + fact.[UnitTypeID], + fact.[UnitType], + pp.[PayPeriodID], + pp.[PayPeriodCode], + SUM(cast(fact.value * PP.PeriodWeightStart as money)) AS Value, + fact.[EmployeeID], + fact.[Employeecode], + 1 as TransactionID + from + [int].[FactStaffing] fact + inner join [fw].[DimDepartment] D on fact.DepartmentID=D.DepartmentID + inner join [fw].[DimPayPeriod] PP on fact.FiscalMonthID = PP.FiscalMonthIDStart and fact.FiscalYearID = PP.FiscalYearIDStart and PP.PayCycleID=D.PayCycleID + where + fact.value != 0 + and PP.PeriodDaysStart > 0 and fact.IsDeleted = 0 + --============= BEGIN CID 2 ================= + and fact.TransactionID<>@TransactionID + --============= END CID 2 =================== + GROUP BY + fact.[DepartmentID], + fact.[DepartmentCode], + fact.[JobCodeID], + fact.[JobCode], + fact.[PayCodeID], + fact.[PayCode], + PP.FiscalYearIDSecond, + fact.[TimeClassID], + fact.[TimeClassCode], + fact.[UnitTypeID], + fact.[UnitType], + fact.[EmployeeID], + fact.[Employeecode], + pp.[PayPeriodID], + pp.[PayPeriodCode] + + insert into #TEMPSTAFFINGPAYPERIOD ([DepartmentID], [DepartmentCode], [JobCodeID], [JobCode], [PayCodeID], [PayCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], [UnitTypeID], [UnitType], [PayPeriodID], [PayPeriodCode], [Value], [EmployeeID], [Employeecode], [TransactionID]) + select + fact.[DepartmentID], + fact.[DepartmentCode], + fact.[JobCodeID], + fact.[JobCode], + fact.[PayCodeID], + fact.[PayCode], + fact.[FiscalYearID], + fact.[FiscalYearCode], + fact.[TimeClassID], + fact.[TimeClassCode], + fact.[UnitTypeID], + fact.[UnitType], + pp.[PayPeriodID], + pp.[PayPeriodCode], + SUM(cast(fact.value * PP.PeriodWeightSecond as money)) AS Value, + fact.[EmployeeID], + fact.[Employeecode], + 1 as TransactionID + from + [int].[FactStaffing] fact + inner join [fw].[DimDepartment] D on fact.DepartmentID=D.DepartmentID + inner join [fw].[DimPayPeriod] PP on fact.FiscalMonthID = PP.FiscalMonthIDSecond and fact.FiscalYearID = PP.FiscalYearIDSecond and PP.PayCycleID=D.PayCycleID + where + fact.value != 0 + and PP.PeriodDaysSecond > 0 and fact.IsDeleted = 0 + --============= BEGIN CID 2 ================= + and fact.TransactionID<>@TransactionID + --============= END CID 2 =================== + GROUP BY + fact.[DepartmentID], + fact.[DepartmentCode], + fact.[JobCodeID], + fact.[JobCode], + fact.[PayCodeID], + fact.[PayCode], + fact.[FiscalYearID], + fact.[FiscalYearCode], + fact.[TimeClassID], + fact.[TimeClassCode], + fact.[UnitTypeID], + fact.[UnitType], + fact.[EmployeeID], + fact.[Employeecode], + pp.[PayPeriodID], + pp.[PayPeriodCode] + + /******** Delete previous transfered data **********/ +--============= BEGIN CID 3 ================= + while exists (select null from [int].[FactStaffingByPayPeriod] where TransactionID=@TransactionID) + delete top (100000) from [int].[FactStaffingByPayPeriod] where TransactionID=@TransactionID +--============= END CID 3 =================== + + + /******** Insert into destination table *************/ + insert into [int].[FactStaffingByPayPeriod] ([DepartmentID], [DepartmentCode], [JobCodeID], [JobCode], [PayCodeID], [PayCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], [UnitTypeID], [UnitType], [PayPeriodID], [PayPeriodCode], [Value], [EmployeeID], [Employeecode], [TransactionID]) + select + [DepartmentID], + [DepartmentCode], + [JobCodeID], + [JobCode], + [PayCodeID], + [PayCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + [UnitTypeID], + [UnitType], + [PayPeriodID], + [PayPeriodCode], + SUM([Value]) AS VALUE, + [EmployeeID], + [Employeecode], + 1 as TransactionID + from + #TEMPSTAFFINGPAYPERIOD + group by + [DepartmentID], + [DepartmentCode], + [JobCodeID], + [JobCode], + [PayCodeID], + [PayCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + [UnitTypeID], + [UnitType], + [PayPeriodID], + [PayPeriodCode], + [EmployeeID], + [Employeecode] + +-- alter index all on [int].[FactStaffingbyPayPeriod] REBUILD WITH (FILLFACTOR=80) +-- update statistics [int].[FactStaffingbyPayPeriod] WITH FULLSCAN + +--cleanup +DROP TABLE #TEMPSTAFFINGPAYPERIOD + + + /******** Update record in IntTransaction **********/ + --TODO: Make the way it inserts to the IntTranaction much better +END; +GO + + +--------------------------------------------- + +-- int.procTransferStaffingToStaffingByPayPeriodFiscalYear +CREATE PROC [int].[procTransferStaffingToStaffingByPayPeriodFiscalYear] + @BudgetConfigID INT, + @IsBudgetIncluded BIT = 0, + @IsProjectionIncluded BIT = 0 +AS + +BEGIN + +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2024-08-06 AO JAZZ-75144 Initial +** 2 2024-08-29 NH JAZZ-76159 JobCodeID smallint to int +** 3 2024-09-13 SF JAZZ-72743 PayCode from varchar(50) to varchar(100) - Extend Field String Limit for Pay Code for Kaiser EPMS +*************************************************************/ +-- !!! If you modifying this proc, check [fw].[procTransferStaffingToStaffingByPayPeriodCurrentYear] for updates !!! + + /******** Variable Declaration **********/ + DECLARE @TransactionID INT = 1 + + DECLARE @BudgetFiscalYear INT = -999; + DECLARE @ProjectionFiscalYear INT = -999; + + IF (@IsBudgetIncluded = 1) BEGIN SET @BudgetFiscalYear = (SELECT bc.FiscalYearID FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID ) END + IF (@IsProjectionIncluded = 1) BEGIN SET @ProjectionFiscalYear = (SELECT bc.FiscalYearID - 1 FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID ) END + + /******** Build Rows to Insert **********/ + + CREATE TABLE #TEMPSTAFFINGPAYPERIOD ( + [DepartmentID] [int] NOT NULL, + [DepartmentCode] [varchar](50) NOT NULL, + [JobCodeID] [int] NOT NULL, + [JobCode] [varchar](50) NOT NULL, + [PayCodeID] [smallint] NOT NULL, + [PayCode] [varchar](100) NOT NULL, + [FiscalYearID] [smallint] NOT NULL, + [FiscalYearCode] [varchar](20) NOT NULL, + [TimeClassID] [tinyint] NOT NULL, + [TimeClassCode] [varchar](20) NOT NULL, + [UnitTypeID] [smallint] NOT NULL, + [UnitType] [varchar](20) NOT NULL, + [PayPeriodID] [smallint] NOT NULL, + [PayPeriodCode] [varchar](20) NOT NULL, + [Value] [decimal](19, 4) NOT NULL, + [EmployeeID] [int] NOT NULL, + [Employeecode] [varchar](2000) NOT NULL, + [TransactionID] [int] NULL + ) + + + INSERT INTO #TEMPSTAFFINGPAYPERIOD ([DepartmentID], [DepartmentCode], [JobCodeID], [JobCode], [PayCodeID], [PayCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], [UnitTypeID], [UnitType], [PayPeriodID], [PayPeriodCode], [Value], [EmployeeID], [Employeecode], [TransactionID]) + SELECT + fact.[DepartmentID], + fact.[DepartmentCode], + fact.[JobCodeID], + fact.[JobCode], + fact.[PayCodeID], + fact.[PayCode], + PP.[FiscalYearIDSecond], + PP.[FiscalYearIDSecond], + fact.[TimeClassID], + fact.[TimeClassCode], + fact.[UnitTypeID], + fact.[UnitType], + pp.[PayPeriodID], + pp.[PayPeriodCode], + SUM(CAST(fact.value * PP.PeriodWeightStart as money)) AS Value, + fact.[EmployeeID], + fact.[Employeecode], + 1 AS TransactionID + FROM + [int].[FactStaffing] fact + INNER JOIN [fw].[DimDepartment] D ON fact.DepartmentID=D.DepartmentID + INNER JOIN [fw].[DimPayPeriod] PP ON fact.FiscalMonthID = PP.FiscalMonthIDStart AND fact.FiscalYearID = PP.FiscalYearIDStart AND PP.PayCycleID=D.PayCycleID + WHERE + fact.value != 0 + AND fact.TimeclassID = 2 + AND PP.PeriodDaysStart > 0 AND fact.IsDeleted = 0 + --============= BEGIN CID 2 ================= + AND fact.TransactionID <> @TransactionID + --============= END CID 2 =================== + AND PP.FiscalYearIDSecond IN (@BudgetFiscalYear, @ProjectionFiscalYear) + GROUP BY + fact.[DepartmentID], + fact.[DepartmentCode], + fact.[JobCodeID], + fact.[JobCode], + fact.[PayCodeID], + fact.[PayCode], + PP.[FiscalYearIDSecond], + fact.[TimeClassID], + fact.[TimeClassCode], + fact.[UnitTypeID], + fact.[UnitType], + fact.[EmployeeID], + fact.[Employeecode], + pp.[PayPeriodID], + pp.[PayPeriodCode] + + INSERT INTO #TEMPSTAFFINGPAYPERIOD ([DepartmentID], [DepartmentCode], [JobCodeID], [JobCode], [PayCodeID], [PayCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], [UnitTypeID], [UnitType], [PayPeriodID], [PayPeriodCode], [Value], [EmployeeID], [Employeecode], [TransactionID]) + SELECT + fact.[DepartmentID], + fact.[DepartmentCode], + fact.[JobCodeID], + fact.[JobCode], + fact.[PayCodeID], + fact.[PayCode], + fact.[FiscalYearID], + fact.[FiscalYearCode], + fact.[TimeClassID], + fact.[TimeClassCode], + fact.[UnitTypeID], + fact.[UnitType], + pp.[PayPeriodID], + pp.[PayPeriodCode], + SUM(CAST(fact.value * PP.PeriodWeightSecond as money)) AS Value, + fact.[EmployeeID], + fact.[Employeecode], + 1 AS TransactionID + FROM + [int].[FactStaffing] fact + INNER JOIN [fw].[DimDepartment] D ON fact.DepartmentID=D.DepartmentID + INNER JOIN [fw].[DimPayPeriod] PP ON fact.FiscalMonthID = PP.FiscalMonthIDSecond AND fact.FiscalYearID = PP.FiscalYearIDSecond AND PP.PayCycleID=D.PayCycleID + WHERE + fact.value != 0 + AND fact.TimeclassID = 2 + AND PP.PeriodDaysSecond > 0 AND fact.IsDeleted = 0 + --============= BEGIN CID 2 ================= + AND fact.TransactionID <> @TransactionID + --============= END CID 2 =================== + AND PP.FiscalYearIDSecond IN (@BudgetFiscalYear, @ProjectionFiscalYear) + GROUP BY + fact.[DepartmentID], + fact.[DepartmentCode], + fact.[JobCodeID], + fact.[JobCode], + fact.[PayCodeID], + fact.[PayCode], + fact.[FiscalYearID], + fact.[FiscalYearCode], + fact.[TimeClassID], + fact.[TimeClassCode], + fact.[UnitTypeID], + fact.[UnitType], + fact.[EmployeeID], + fact.[Employeecode], + pp.[PayPeriodID], + pp.[PayPeriodCode] + + /******** Delete previous transfered data **********/ +--============= BEGIN CID 3 ================= + WHILE EXISTS (SELECT NULL FROM [int].[FactStaffingByPayPeriod] WHERE TransactionID=@TransactionID AND FiscalYearID IN (@BudgetFiscalYear, @ProjectionFiscalYear) AND TimeClassID = 2) + DELETE TOP (100000) FROM [int].[FactStaffingByPayPeriod] WHERE TransactionID=@TransactionID AND FiscalYearID IN (@BudgetFiscalYear, @ProjectionFiscalYear) AND TimeClassID = 2 +--============= END CID 3 =================== + + + /******** Insert into destination table *************/ + INSERT INTO [int].[FactStaffingByPayPeriod] ([DepartmentID], [DepartmentCode], [JobCodeID], [JobCode], [PayCodeID], [PayCode], [FiscalYearID], [FiscalYearCode], [TimeClassID], [TimeClassCode], [UnitTypeID], [UnitType], [PayPeriodID], [PayPeriodCode], [Value], [EmployeeID], [Employeecode], [TransactionID]) + SELECT + [DepartmentID], + [DepartmentCode], + [JobCodeID], + [JobCode], + [PayCodeID], + [PayCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + [UnitTypeID], + [UnitType], + [PayPeriodID], + [PayPeriodCode], + SUM([Value]) AS VALUE, + [EmployeeID], + [Employeecode], + 1 AS TransactionID + FROM + #TEMPSTAFFINGPAYPERIOD + GROUP BY + [DepartmentID], + [DepartmentCode], + [JobCodeID], + [JobCode], + [PayCodeID], + [PayCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + [UnitTypeID], + [UnitType], + [PayPeriodID], + [PayPeriodCode], + [EmployeeID], + [Employeecode] + + +-- alter index all on [int].[FactStaffingbyPayPeriod] REBUILD WITH (FILLFACTOR=80) +-- update statistics [int].[FactStaffingbyPayPeriod] WITH FULLSCAN + +--cleanup +DROP TABLE #TEMPSTAFFINGPAYPERIOD + + + /******** Update record in IntTransaction **********/ + --TODO: Make the way it inserts to the IntTranaction much better +END +GO + + +--------------------------------------------- + +-- int.procTransferStatisticsMonthlyByPayPeriodFiscalYear +CREATE PROC [int].[procTransferStatisticsMonthlyByPayPeriodFiscalYear] + @BudgetConfigID INT, + @IsBudgetIncluded BIT = 0, + @IsProjectionIncluded BIT = 0 +AS +BEGIN + +/************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2024-07-11 AO JAZZ-73257 Initial +*************************************************************/ + + /******** Variable Declaration **********/ + DECLARE @TransactionID int = 1 + + DECLARE @BudgetFiscalYear INT = -999; + DECLARE @ProjectionFiscalYear INT = -999; + + IF (@IsBudgetIncluded = 1) BEGIN SET @BudgetFiscalYear = (SELECT bc.FiscalYearID FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID ) END + IF (@IsProjectionIncluded = 1) BEGIN SET @ProjectionFiscalYear = (SELECT bc.FiscalYearID - 1 FROM [fp].[BudgetConfig] bc WHERE BudgetConfigID = @BudgetConfigID ) END + + + /******** Build Rows to Insert **********/ + + CREATE TABLE #TEMPSTATISTICS ( + [AccountID] [int] NOT NULL, + [DepartmentID] [int] NOT NULL, + [FiscalYearID] [smallint] NOT NULL, + [PayPeriodID] [smallint] NOT NULL, + [TimeClassID] [tinyint] NOT NULL, + [Value] [decimal](19, 4) NOT NULL, + [AccountCode] [nvarchar](100) NOT NULL, + [DepartmentCode] [nvarchar](100) NOT NULL, + [FiscalYearCode] [nvarchar](100) NOT NULL, + [PayPeriodCode] [nvarchar](100) NOT NULL, + [TimeClassCode] [nvarchar](100) NOT NULL, + [TransactionID] [int] NOT NULL, + ) + + INSERT INTO #TEMPSTATISTICS (DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, PayPeriodID, PayPeriodCode, TimeClassID, TimeClassCode, Value, TransactionID) + SELECT + fact.DepartmentID, + fact.DepartmentCode, + fact.AccountID, + fact.AccountCode, + PP.FiscalYearIDSecond, + PP.FiscalYearIDSecond, + PP.PayPeriodID, + PP.PayPeriodCode, + fact.TimeClassID, + fact.TimeClassCode, + SUM(cast(fact.value * PP.PeriodWeightStart as money)) AS Value, + 1 as TransactionID + FROM + [int].[FactStatistic] fact + INNER JOIN [fw].[DimDepartment] D ON fact.DepartmentID=D.DepartmentID + INNER JOIN fw.DimPayPeriod PP ON PP.FiscalMonthIDStart = fact.FiscalMonthID and PP.FiscalYearIDStart = fact.FiscalYearID and PP.PayCycleID=D.PayCycleID + WHERE + fact.value != 0 + AND fact.TimeClassID = 2 + AND PP.PeriodDaysStart > 0 + --============= BEGIN CID 2 ================= + AND fact.TransactionID<>@TransactionID + --============= END CID 2 =================== + AND PP.FiscalYearIDSecond IN (@BudgetFiscalYear, @ProjectionFiscalYear) + GROUP BY + fact.DepartmentID, + fact.DepartmentCode, + fact.AccountID, + fact.AccountCode, + PP.FiscalYearIDSecond, + PP.PayPeriodID, + PP.PayPeriodCode, + fact.TimeClassID, + fact.TimeClassCode + + INSERT INTO #TEMPSTATISTICS (DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, PayPeriodID, PayPeriodCode, TimeClassID, TimeClassCode, Value, TransactionID) + SELECT + fact.DepartmentID, + fact.DepartmentCode, + fact.AccountID, + fact.AccountCode, + fact.FiscalYearID, + fact.FiscalYearCode, + PP.PayPeriodID, + PP.PayPeriodCode, + fact.TimeClassID, + fact.TimeClassCode, + SUM(cast(fact.value * PP.PeriodWeightSecond as money)) AS Value, + 1 AS TransactionID + FROM + [int].[FactStatistic] fact + INNER JOIN [fw].[DimDepartment] D ON fact.DepartmentID = D.DepartmentID + INNER JOIN fw.DimPayPeriod PP ON PP.FiscalMonthIDSecond = fact.FiscalMonthID AND PP.FiscalYearIDSecond = fact.FiscalYearID AND PP.PayCycleID=D.PayCycleID + WHERE + fact.value != 0 + AND fact.TimeClassID = 2 + AND PP.PeriodDaysSecond > 0 + --============= BEGIN CID 2 ================= + AND fact.TransactionID < >@TransactionID + --============= END CID 2 =================== + AND fact.FiscalYearID IN (@BudgetFiscalYear, @ProjectionFiscalYear) + GROUP BY + fact.DepartmentID, + fact.DepartmentCode, + fact.AccountID, + fact.AccountCode, + fact.FiscalYearID, + fact.FiscalYearCode, + PP.PayPeriodID, + PP.PayPeriodCode, + fact.TimeClassID, + fact.TimeClassCode + + /******** Delete previous transfered data **********/ + DELETE FROM [int].[FactStatisticsbyPayPeriod] + WHERE TransactionID = @TransactionID + AND FiscalYearID IN (@BudgetFiscalYear, @ProjectionFiscalYear) + AND TimeClassID = 2 + + + /******** Insert into destination table *************/ + INSERT INTO [int].[FactStatisticsbyPayPeriod] (DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, PayPeriodID, PayPeriodCode, TimeClassID, TimeClassCode, Value, TransactionID) + SELECT + DepartmentID, + DepartmentCode, + AccountID, + AccountCode, + FiscalYearID, + FiscalYearCode, + PayPeriodID, + PayPeriodCode, + TimeClassID, + TimeClassCode, + SUM(value), + TransactionID + FROM + #TEMPSTATISTICS + GROUP BY + DepartmentID, + DepartmentCode, + AccountID, + AccountCode, + FiscalYearID, + FiscalYearCode, + PayPeriodID, + PayPeriodCode, + TimeClassID, + TimeClassCode, + TransactionID + + ALTER INDEX ALL ON [int].[FactStatisticsbyPayPeriod] REBUILD WITH (FILLFACTOR=80) + UPDATE STATISTICS [int].[FactStatisticsbyPayPeriod] WITH FULLSCAN + + + /******** Update record in IntTransaction **********/ + --TODO: Make the way it inserts to the IntTranaction much better +END +GO + + +--------------------------------------------- + +-- int.procTransferStatisticsMonthlyToPayPeriod +CREATE proc [int].[procTransferStatisticsMonthlyToPayPeriod] as +/************************************************************ +** Author: akowalski +** Create Date: 2013-09-19 +** Description: Transfers Monthly statistics Data into the FactStatisticsByPayPeriod Table and does the accrual calculation (converts month to pay period) +** Last Modified: 2014-07-09 +** GM Release: 2014.3 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 10/29/2013 ramancharla Updating insert to PP.FiscalYearIDSecond instead of fact.FiscalYearID +** 2 2014-07-09 akk D-02068 Filtering out transactionID 1 +** 3 2016-01-15 mjs D-03862 Adding check for PayCycleID +** 4 2017-02-16 apukii TK-37995 Fixed DepartmentID type +*************************************************************/ + + + /******** Variable Declaration **********/ + declare @TransactionID int = 1 + + + + /******** Build Rows to Insert **********/ + + CREATE TABLE #TEMPSTATISTICS ( + [AccountID] [int] NOT NULL, + [DepartmentID] [int] NOT NULL, + [FiscalYearID] [smallint] NOT NULL, + [PayPeriodID] [smallint] NOT NULL, + [TimeClassID] [tinyint] NOT NULL, + [Value] [decimal](19, 4) NOT NULL, + [AccountCode] [nvarchar](100) NOT NULL, + [DepartmentCode] [nvarchar](100) NOT NULL, + [FiscalYearCode] [nvarchar](100) NOT NULL, + [PayPeriodCode] [nvarchar](100) NOT NULL, + [TimeClassCode] [nvarchar](100) NOT NULL, + [TransactionID] [int] NOT NULL, + ) + + insert into #TEMPSTATISTICS (DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, PayPeriodID, PayPeriodCode, TimeClassID, TimeClassCode, Value, TransactionID) + select + fact.DepartmentID, + fact.DepartmentCode, + fact.AccountID, + fact.AccountCode, + PP.FiscalYearIDSecond, + PP.FiscalYearIDSecond, + PP.PayPeriodID, + PP.PayPeriodCode, + fact.TimeClassID, + fact.TimeClassCode, + SUM(cast(fact.value * PP.PeriodWeightStart as money)) AS Value, + 1 as TransactionID + from + [int].[FactStatistic] fact + inner join [fw].[DimDepartment] D on fact.DepartmentID=D.DepartmentID + inner join fw.DimPayPeriod PP on PP.FiscalMonthIDStart = fact.FiscalMonthID and PP.FiscalYearIDStart = fact.FiscalYearID and PP.PayCycleID=D.PayCycleID + where + fact.value != 0 + and PP.PeriodDaysStart > 0 + --============= BEGIN CID 2 ================= + and fact.TransactionID<>@TransactionID + --============= END CID 2 =================== + GROUP BY + fact.DepartmentID, + fact.DepartmentCode, + fact.AccountID, + fact.AccountCode, + PP.FiscalYearIDSecond, + PP.PayPeriodID, + PP.PayPeriodCode, + fact.TimeClassID, + fact.TimeClassCode + + insert into #TEMPSTATISTICS (DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, PayPeriodID, PayPeriodCode, TimeClassID, TimeClassCode, Value, TransactionID) + select + fact.DepartmentID, + fact.DepartmentCode, + fact.AccountID, + fact.AccountCode, + fact.FiscalYearID, + fact.FiscalYearCode, + PP.PayPeriodID, + PP.PayPeriodCode, + fact.TimeClassID, + fact.TimeClassCode, + SUM(cast(fact.value * PP.PeriodWeightSecond as money)) AS Value, + 1 as TransactionID + from + [int].[FactStatistic] fact + inner join [fw].[DimDepartment] D on fact.DepartmentID=D.DepartmentID + inner join fw.DimPayPeriod PP on PP.FiscalMonthIDSecond = fact.FiscalMonthID and PP.FiscalYearIDSecond = fact.FiscalYearID and PP.PayCycleID=D.PayCycleID + where + fact.value != 0 + and PP.PeriodDaysSecond > 0 + --============= BEGIN CID 2 ================= + and fact.TransactionID<>@TransactionID + --============= END CID 2 =================== + GROUP BY + fact.DepartmentID, + fact.DepartmentCode, + fact.AccountID, + fact.AccountCode, + fact.FiscalYearID, + fact.FiscalYearCode, + PP.PayPeriodID, + PP.PayPeriodCode, + fact.TimeClassID, + fact.TimeClassCode + + /******** Delete previous transfered data **********/ + delete from [int].[FactStatisticsbyPayPeriod] where TransactionID=@TransactionID + + + /******** Insert into destination table *************/ + insert into [int].[FactStatisticsbyPayPeriod] (DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, PayPeriodID, PayPeriodCode, TimeClassID, TimeClassCode, Value, TransactionID) + select + DepartmentID, + DepartmentCode, + AccountID, + AccountCode, + FiscalYearID, + FiscalYearCode, + PayPeriodID, + PayPeriodCode, + TimeClassID, + TimeClassCode, + sum(value), + TransactionID + from + #TEMPSTATISTICS + group by + DepartmentID, + DepartmentCode, + AccountID, + AccountCode, + FiscalYearID, + FiscalYearCode, + PayPeriodID, + PayPeriodCode, + TimeClassID, + TimeClassCode, + TransactionID + + alter index all on [int].[FactStatisticsbyPayPeriod] REBUILD WITH (FILLFACTOR=80) + update statistics [int].[FactStatisticsbyPayPeriod] WITH FULLSCAN + + + /******** Update record in IntTransaction **********/ + --TODO: Make the way it inserts to the IntTranaction much better +GO + + +--------------------------------------------- + +-- int.procTransferStatisticsPayPeriodToMonthly +CREATE proc [int].[procTransferStatisticsPayPeriodToMonthly] as +/************************************************************ +** Author: ramancharla +** Create Date: 2013-10-07 +** Description: Transfers statistics by pay period Data into the FactStatistic Table(converts pay period to month) +** Last Modified: 2014-07-09 +** GM Release: 2014.3 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 11/22/13 ramancharla Updating group by to include fiscal month +** 2 2014-07-09 akk D-02068 Filtering out transactionID 1 +** 4 2017-02-16 apukii TK-37995 Fixed DepartmentID type +** 5 2017-12-13 ipetriv D-06594 Fixed Department Code +*************************************************************/ + /******** Variable Declaration **********/ + declare @TransactionID int = 1 + + /******** Build Rows to Insert **********/ + + CREATE TABLE #TEMPSTATISTICS ( + [AccountID] [int] NOT NULL, + [DepartmentID] [int] NOT NULL, + [FiscalYearID] [smallint] NOT NULL, + [FiscalMonthID] [smallint] NOT NULL, + [TimeClassID] [tinyint] NOT NULL, + [Value] [decimal](19, 4) NOT NULL, + [AccountCode] [nvarchar](100) NOT NULL, + [DepartmentCode] [nvarchar](100) NOT NULL, + [FiscalYearCode] [nvarchar](100) NOT NULL, + [FiscalMonthCode] [nvarchar](100) NOT NULL, + [TimeClassCode] [nvarchar](100) NOT NULL, + [TransactionID] [int] NOT NULL, + ) + insert into #TEMPSTATISTICS (DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, FiscalMonthID, FiscalMonthCode, TimeClassID, TimeClassCode, Value, TransactionID) + select + fact.DepartmentID, + fact.DepartmentCode, + fact.AccountID, + fact.AccountCode, + PP.FiscalYearIDStart as [FiscalYearID], + PP.FiscalYearIDStart as [FiscalYearCode], + PP.FiscalMonthIDStart as [FiscalMonthID], + FM.FiscalMonthCode as [FiscalMonthCode], + fact.TimeClassID, + fact.TimeClassCode, + SUM(cast(fact.value * PP.DaysinPeriodWeightStart as money)) AS Value, + 1 as TransactionID + from + [int].[FactStatisticsbyPayPeriod] fact + inner join fw.DimPayPeriod PP on PP.PayPeriodID = fact.PayPeriodID + inner join fw.DimFiscalMonth FM on FM.FiscalMonthID = PP.FiscalMonthIDStart + where + fact.value != 0 + and PP.PeriodDaysStart > 0 + and fact.isdeleted = 0 + --============= BEGIN CID 2 ================= + and fact.TransactionID<>@TransactionID + --============= END CID 2 =================== + GROUP BY + fact.DepartmentID, + fact.DepartmentCode, + fact.AccountID, + fact.AccountCode, + PP.FiscalYearIDStart, + PP.FiscalMonthIDStart, + fact.TimeClassID, + fact.TimeClassCode, + fm.FiscalMonthCode + + + insert into #TEMPSTATISTICS (DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, FiscalMonthID, FiscalMonthCode, TimeClassID, TimeClassCode, Value, TransactionID) + select + fact.DepartmentID, + fact.DepartmentCode, + fact.AccountID, + fact.AccountCode, + PP.FiscalYearIDSecond as [FiscalYearID], + PP.FiscalYearIDSecond as [FiscalYearCode], + PP.FiscalMonthIDSecond as [FiscalMonthID], + FM.FiscalMonthCode as [FiscalMonthCode], + fact.TimeClassID, + fact.TimeClassCode, + SUM(cast(fact.value * PP.DaysinPeriodWeightSecond as money)) AS Value, + 1 as TransactionID + from + [int].[FactStatisticsbyPayPeriod] fact + inner join fw.DimPayPeriod PP on PP.PayPeriodID = fact.PayPeriodID + inner join fw.DimFiscalMonth FM on FM.FiscalMonthID = PP.FiscalMonthIDSecond + where + fact.value != 0 + and PP.PeriodDaysSecond > 0 + and fact.isdeleted = 0 + --============= BEGIN CID 2 ================= + and fact.TransactionID<>@TransactionID + --============= END CID 2 =================== + GROUP BY + fact.DepartmentID, + fact.DepartmentCode, + fact.AccountID, + fact.AccountCode, + PP.FiscalYearIDSecond, + PP.FiscalMonthIDSecond, + fact.TimeClassID, + fact.TimeClassCode, + fm.FiscalMonthCode + + /******** Delete previous transfered data **********/ + delete from [int].[FactStatistic] where TransactionID=@TransactionID + + + /******** Insert into destination table *************/ + insert into [int].[FactStatistic] (DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, FiscalMonthID, FiscalMonthCode, TimeClassID, TimeClassCode, Value, TransactionID) + select + DepartmentID, + DepartmentCode, + AccountID, + AccountCode, + FiscalYearID, + FiscalYearCode, + FiscalMonthID, + FiscalMonthCode, + TimeClassID, + TimeClassCode, + SUM(Value), + TransactionID + from + #TEMPSTATISTICS + group by + DepartmentID, + DepartmentCode, + AccountID, + AccountCode, + FiscalYearID, + FiscalYearCode, + FiscalMonthID, + FiscalMonthCode, + TimeClassID, + TimeClassCode, + TransactionID + + alter index all on [int].[FactStatistic] REBUILD WITH (FILLFACTOR=80) + update statistics [int].[FactStatistic] WITH FULLSCAN + + + /******** Update record in IntTransaction **********/ + --TODO: Make the way it inserts to the IntTranaction much better +GO + + +--------------------------------------------- + +-- int.procTransferStatisticsToGlobalStatistics +CREATE proc [int].[procTransferStatisticsToGlobalStatistics] as +/************************************************************ +** Author: akowalski +** Create Date: 2014-07-16 +** Description: Transfers data from statistics to global statistics based on the current global statistics setup +** Last Modified: 2014-07-16 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 01 2018-04-17 sdominsk B-18563 Added PK WORKAROUND ESC-07594 +** +*************************************************************/ + + +/******** Variable Declaration **********/ +declare @TransactionID int = 1 + + + +/******** Build Rows to Insert **********/ + +CREATE TABLE #TEMPSTATISTICS ( +[AccountID] [int] NOT NULL, +[DepartmentID] [int] NOT NULL, +[FiscalYearID] [int] NOT NULL, +[FiscalMonthID] [smallint] NOT NULL, +[TimeClassID] [tinyint] NOT NULL, +[Value] [decimal](19, 4) NOT NULL, +[AccountCode] [nvarchar](100) NOT NULL, +[DepartmentCode] [nvarchar](100) NOT NULL, +[FiscalYearCode] [nvarchar](100) NOT NULL, +[FiscalMonthCode] [nvarchar](100) NOT NULL, +[TimeClassCode] [nvarchar](100) NOT NULL, +[TransactionID] [int] NOT NULL, +) + +-- Department level stats +insert into #TEMPSTATISTICS (DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, FiscalMonthID, FiscalMonthCode, TimeClassID, TimeClassCode, Value, TransactionID) +select +fct.DepartmentID, +fct.DepartmentCode, +fct.AccountID, +fct.AccountCode, +fct.[FiscalYearID], +fct.[FiscalYearCode], +fct.[FiscalMonthID], +fct.[FiscalMonthCode], +fct.TimeClassID, +fct.TimeClassCode, +fct.value AS Value, +1 as TransactionID +FROM +[int].[FactStatistic] fct with (readuncommitted) +inner join fw.DimDepartment d with (readuncommitted) on fct.DepartmentID=d.DepartmentID +inner join [fw].[DimAccount] a with (readuncommitted) on a.AccountID=fct.AccountID +inner join [ob].[DimOBGlobalStatisticsPlan] gsp with (readuncommitted) on gsp.OBGlobalStatisticsPlanID=d.OBGlobalStatisticsPlanID +inner join [ob].[DimOBGlobalStatistics] gs with (readuncommitted) on gs.AccountID=fct.AccountID and gs.DepartmentID=fct.DepartmentID +where a.IsGlobal=0 and a.isStat=1 +and gsp.OBGlobalStatisticsPlanID<>0 and d.IsOB=1 and d.IsActive=1 + +-- Entity level stats +insert into #TEMPSTATISTICS (DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, FiscalMonthID, FiscalMonthCode, TimeClassID, TimeClassCode, Value, TransactionID) +select +fct.DepartmentID, +fct.DepartmentCode, +fct.AccountID, +fct.AccountCode, +fct.[FiscalYearID], +fct.[FiscalYearCode], +fct.[FiscalMonthID], +fct.[FiscalMonthCode], +fct.TimeClassID, +fct.TimeClassCode, +fct.value AS Value, +1 as TransactionID +FROM +[int].[FactStatistic] fct with (readuncommitted) +inner join fw.DimDepartment d with (readuncommitted) on fct.DepartmentID=d.DepartmentID +inner join [fw].[DimAccount] a with (readuncommitted) on a.AccountID=fct.AccountID +inner join [ob].[DimOBGlobalStatisticsPlan] gsp with (readuncommitted) on gsp.OBGlobalStatisticsPlanID=d.OBGlobalStatisticsPlanID +inner join [ob].[DimOBGlobalStatistics] gs with (readuncommitted) on gs.AccountID=fct.AccountID and gs.DepartmentID=0 +where a.IsGlobal=1 and a.isStat=1 +and gsp.OBGlobalStatisticsPlanID<>0 and d.IsOB=1 and d.IsActive=1 + +--------------------------------- +--PK WORKAROUND ESC-07594 START-- +--------------------------------- + +CREATE TABLE #TEMPCHARGEBASEDSTATS ( +[AccountID] [int] NOT NULL, +[DepartmentID] [int] NOT NULL, +[FiscalYearID] [int] NOT NULL, +[FiscalMonthID] [smallint] NOT NULL, +[TimeClassID] [tinyint] NOT NULL, +[Value] [decimal](19, 4) NOT NULL, +[AccountCode] [nvarchar](100) NOT NULL, +[DepartmentCode] [nvarchar](100) NOT NULL, +[FiscalYearCode] [nvarchar](100) NOT NULL, +[FiscalMonthCode] [nvarchar](100) NOT NULL, +[TimeClassCode] [nvarchar](100) NOT NULL, +[TransactionID] [int] NOT NULL, +) + +-- Department level stats (charge-based statistics) +insert into #TEMPCHARGEBASEDSTATS (DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, FiscalMonthID, FiscalMonthCode, TimeClassID, TimeClassCode, Value, TransactionID) +select +fct.DepartmentID, +d.DepartmentCode, +fct.AccountID, +a.AccountCode, +fct.[FiscalYearID], +fy.Name as FiscalYearCode, +fct.[FiscalMonthID], +fm.[FiscalMonthCode], +1 as TimeClassID, +'A' as TimeClassCode, +fct.value AS Value, +1 as TransactionID +FROM +[fw].[FactChargeBasedStatisticsMonthly] fct +inner join fw.DimDepartment d on fct.DepartmentID=d.DepartmentID +inner join [fw].[DimAccount] a on a.AccountID=fct.AccountID +inner join [ob].[DimOBGlobalStatisticsPlan] gsp on gsp.OBGlobalStatisticsPlanID=d.OBGlobalStatisticsPlanID +inner join [ob].[DimOBGlobalStatistics] gs on gs.AccountID=fct.AccountID and gs.DepartmentID=fct.DepartmentID +inner join [fw].[DimFiscalYear] fy on fy.FiscalYearID = fct.FiscalYearID +inner join [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fct.FiscalMonthID +where a.IsGlobal=0 and a.isStat=1 +and gsp.OBGlobalStatisticsPlanID<>0 and d.IsOB=1 and d.IsActive=1 +and fct.IsDeleted=0 + +-- Entity level stats (charge-based statistics) +insert into #TEMPCHARGEBASEDSTATS (DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, FiscalMonthID, FiscalMonthCode, TimeClassID, TimeClassCode, Value, TransactionID) +select +fct.DepartmentID, +d.DepartmentCode, +fct.AccountID, +a.AccountCode, +fct.[FiscalYearID], +fy.Name as FiscalYearCode, +fct.[FiscalMonthID], +fm.[FiscalMonthCode], +1 as TimeClassID, +'A' as TimeClassCode, +fct.value AS Value, +1 as TransactionID +FROM +[fw].[FactChargeBasedStatisticsMonthly] fct +inner join fw.DimDepartment d on fct.DepartmentID=d.DepartmentID +inner join [fw].[DimAccount] a on a.AccountID=fct.AccountID +inner join [ob].[DimOBGlobalStatisticsPlan] gsp on gsp.OBGlobalStatisticsPlanID=d.OBGlobalStatisticsPlanID +inner join [ob].[DimOBGlobalStatistics] gs on gs.AccountID=fct.AccountID and gs.DepartmentID=fct.DepartmentID +inner join [fw].[DimFiscalYear] fy on fy.FiscalYearID = fct.FiscalYearID +inner join [fw].[DimFiscalMonth] fm on fm.FiscalMonthID = fct.FiscalMonthID +where a.IsGlobal=1 and a.isStat=1 +and gsp.OBGlobalStatisticsPlanID<>0 and d.IsOB=1 and d.IsActive=1 +and fct.IsDeleted=0 + +--Push charge-based statistics into stat temp table for rows not already loaded via DI + +merge +#TEMPSTATISTICS AS fact +using +(select DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, FiscalMonthID, FiscalMonthCode, TimeClassID, TimeClassCode, Value, TransactionID from #TEMPCHARGEBASEDSTATS where Value != 0) as source +on +fact.DepartmentID = source.DepartmentID and fact.AccountID = source.AccountID and fact.FiscalYearID = source.FiscalYearID and fact.FiscalMonthID = source.FiscalMonthID and fact.TimeClassID = source.TimeClassID +when not matched then +insert (DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, FiscalMonthID, FiscalMonthCode, TimeClassID, TimeClassCode, Value, TransactionID) +values (source.DepartmentID, source.DepartmentCode, source.AccountID, source.AccountCode, source.FiscalYearID, source.FiscalYearCode, source.FiscalMonthID, source.FiscalMonthCode, source.TimeClassID, source.TimeClassCode, source.Value, source.TransactionID); + +------------------------------- +--PK WORKAROUND ESC-07594 END-- +------------------------------- + +/******** Delete previous transfered data **********/ +delete from [int].[FactGlobalStatistics] where TransactionID=@TransactionID + + +/******** Insert into destination table *************/ +insert into [int].[FactGlobalStatistics] (DepartmentID, DepartmentCode, AccountID, AccountCode, FiscalYearID, FiscalYearCode, FiscalMonthID, FiscalMonthCode, TimeClassID, TimeClassCode, Value, TransactionID) +select +DepartmentID, +DepartmentCode, +AccountID, +AccountCode, +FiscalYearID, +FiscalYearCode, +FiscalMonthID, +FiscalMonthCode, +TimeClassID, +TimeClassCode, +SUM(Value), +TransactionID +from +#TEMPSTATISTICS +group by +DepartmentID, +DepartmentCode, +AccountID, +AccountCode, +FiscalYearID, +FiscalYearCode, +FiscalMonthID, +FiscalMonthCode, +TimeClassID, +TimeClassCode, +TransactionID + +alter index all on [int].[FactGlobalStatistics] REBUILD WITH (FILLFACTOR=80) +update statistics [int].[FactGlobalStatistics] WITH FULLSCAN + +/******** Update record in IntTransaction **********/ +--TODO: Make the way it inserts to the IntTranaction much better +GO + + +--------------------------------------------- + +-- int.procTruncateAllImportTables +CREATE PROC [int].[procTruncateAllImportTables] + @IncludeRejectedTables bit = 1 + AS + BEGIN + DECLARE @TruncQuery VARCHAR(MAX) + + SET @TruncQuery = (SELECT dbo.STRAGGR('TRUNCATE TABLE [' + SchemaName + '].[' + ObjectName + ']', CHAR(13) + CHAR(10),'') + FROM dbo.ViewSysTables + WHERE SchemaName = 'int' AND ObjectName LIKE 'Import______________________________________Accepted') + + EXEC (@TruncQuery) + + IF @IncludeRejectedTables = 1 + BEGIN + SET @TruncQuery = (SELECT dbo.STRAGGR('TRUNCATE TABLE [' + SchemaName + '].[' + ObjectName + ']', CHAR(13) + CHAR(10),'') + FROM dbo.ViewSysTables + WHERE SchemaName = 'int' AND ObjectName LIKE 'Import______________________________________Rejected') + + EXEC (@TruncQuery) + END + END +GO + + +--------------------------------------------- + +-- int.procUpdateMissingEmployeeNamesandHomeDepartments +/***** *********************************************************** +****** Author: dkondaveeti +****** Create Date: 2017-01-09 +****** Description: Updates missing employee name and home deparments after DI Import +****** Last Modified: 2024-04-07 +****** GM Release: 2024.23 +****** *********************************************************** +****** Change History +****** *********************************************************** +****** CID Date Author WI Description +****** 1 2017-04-25 ydemb Ensure that procUpdateMissingEmployeeNamesandHomeDepartments exists +****** 2 2017-04-25 ydemb Updated proc to refresh missing employee names after DI import +****** 3 2024-04-07 lcunningham JAZZ-66177 Updated proc to refresh missing employee names to Not Specified after DI import +****** **********************************************************/ + +CREATE + + PROC [int].[procUpdateMissingEmployeeNamesandHomeDepartments] + AS + BEGIN + UPDATE [de1] + SET [de1].[NameFirst] = [de2].[NameFirst], + [de1].[NameLast] = [de2].[NameLast] + ------ SELECT * + FROM [fw].[DimEmployee] AS [de1] + INNER JOIN [fw].[DimEmployee] AS [de2] + ON [de2].[EmployeeID] = ( SELECT TOP 1 [de3].[EmployeeID] + FROM [fw].[DimEmployee] AS [de3] + WHERE [de1].[Number] = [de3].[Number] + AND ( [de3].[NameLast] <> '' + OR [de3].[NameFirst] <> '' + ) + AND ( [de1].[NameFirst] <> 'Specified' + OR [de1].[NameLast] <> 'Not' + ) + ) + WHERE ( [de1].[NameFirst] = '' + OR [de1].[NameLast] = '' + ) + AND ( [de1].[NameFirst] = 'Specified' + OR [de1].[NameLast] = 'Not' + ); + + + UPDATE [e] + SET [e].[NameFirst] = 'Specified', + [e].[NameLast] = 'Not' + ------ SELECT * + FROM [fw].[DimEmployee] AS [e] + WHERE [e].[NameFirst] = '' + OR [e].[NameLast] = ''; + + + UPDATE [de1] + SET [de1].[HomeDepartmentID] = [de2].[HomeDepartmentID] + ------ SELECT * + FROM [fw].[DimEmployee] AS [de1] + INNER JOIN [fw].[DimEmployee] AS [de2] + ON [de1].[Number] = [de2].[Number] + + WHERE [de1].[HomeDepartmentID] = 0 + AND [de2].[HomeDepartmentID] <> 0; + + + EXEC [dbo].[procScoreDimensionCacheRefresh] 'FD66443C-1F8F-46EC-A074-0D5F6D8DFD29'; + END; +GO + + +--------------------------------------------- + +--------------------------------------------- +-- FUNCTIONS +--------------------------------------------- + +-- int.viewFactStaffingYTDValuesPivoted +CREATE FUNCTION int.viewFactStaffingYTDValuesPivoted (@MonthsLoaded INT) + RETURNS TABLE + AS + RETURN + SELECT + pv.DepartmentID, + pv.JobCodeID, + pv.PayCodeID, + pv.FiscalYearID, + pv.TimeClassID, + pv.UnitTypeID, + ISNULL(pv.Month01, 0) as Month01, + ISNULL(pv.Month02, 0) as Month02, + ISNULL(pv.Month03, 0) as Month03, + ISNULL(pv.Month04, 0) as Month04, + ISNULL(pv.Month05, 0) as Month05, + ISNULL(pv.Month06, 0) as Month06, + ISNULL(pv.Month07, 0) as Month07, + ISNULL(pv.Month08, 0) as Month08, + ISNULL(pv.Month09, 0) as Month09, + ISNULL(pv.Month10, 0) as Month10, + ISNULL(pv.Month11, 0) as Month11, + ISNULL(pv.Month12, 0) as Month12 + FROM ( + SELECT + fs.DepartmentID, + fs.JobCodeID, + fs.PayCodeID, + fs.FiscalYearID, + fs.TimeClassID, + fs.UnitTypeID, + fm.MonthColumnName, + fs.Value + FROM [int].[FactStaffing] fs + INNER JOIN [fw].[DimFiscalMonth] fm ON fm.FiscalMonthID = fs.FiscalMonthID + WHERE fm.SortOrder <= @MonthsLoaded + ) data + PIVOT + (SUM(Value) FOR MonthColumnName IN ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) as pv +GO + + +--------------------------------------------- + diff --git a/ef-migration/infrastructure/sql-server/schemas/int_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/schemas/int_schema_database_statements_small.sql new file mode 100644 index 0000000..872b1ac --- /dev/null +++ b/ef-migration/infrastructure/sql-server/schemas/int_schema_database_statements_small.sql @@ -0,0 +1,22 @@ +-- SCHEMA: int + +--------------------------------------------- +-- TABLES +--------------------------------------------- + + +--------------------------------------------- +-- int.AggregatePostDIHistory ------------------ +--------------------------------------------- +CREATE TABLE [int].[AggregatePostDIHistory] ( + [AggregatePostDIHistoryGuid] uniqueidentifier NOT NULL, + [CreatedAtUtc] datetime NOT NULL, + [LastRanUtc] datetime NOT NULL, + [AggregatePostDIStatus] int NOT NULL, + PRIMARY KEY ([AggregatePostDIHistoryGuid]) +); +GO +ALTER TABLE [int].[AggregatePostDIHistory] ADD CONSTRAINT [DF__Aggregate__Aggre__4EDF0E15] DEFAULT (newid()) FOR [AggregatePostDIHistoryGuid]; GO +ALTER TABLE [int].[AggregatePostDIHistory] ADD CONSTRAINT [DF__Aggregate__Creat__4FD3324E] DEFAULT (getutcdate()) FOR [CreatedAtUtc]; GO +ALTER TABLE [int].[AggregatePostDIHistory] ADD CONSTRAINT [DF__Aggregate__LastR__50C75687] DEFAULT ('1900-01-01 00:00:00.000') FOR [LastRanUtc]; GO +ALTER TABLE [int].[AggregatePostDIHistory] ADD CONSTRAINT [DF__Aggregate__Aggre__51BB7AC0] DEFAULT ((0)) FOR [AggregatePostDIStatus]; GO diff --git a/ef-migration/infrastructure/sql-server/schemas/ob_schema_database_statements.sql b/ef-migration/infrastructure/sql-server/schemas/ob_schema_database_statements.sql new file mode 100644 index 0000000..1159185 --- /dev/null +++ b/ef-migration/infrastructure/sql-server/schemas/ob_schema_database_statements.sql @@ -0,0 +1,24015 @@ +-- SCHEMA: ob + +--------------------------------------------- +-- TABLES +--------------------------------------------- + + +--------------------------------------------- +-- ob.AccountVariabilityOverride ------------------ +--------------------------------------------- +CREATE TABLE [ob].[AccountVariabilityOverride] ( + [AccountVariabilityOverrideID] int NOT NULL, + [DepartmentAssignment] nvarchar(800) NOT NULL, + [AccountAssignment] nvarchar(800) NOT NULL, + [PrecedentOrder] int NOT NULL, + [Variability] decimal NOT NULL, + PRIMARY KEY ([AccountVariabilityOverrideID]) +); +GO +ALTER TABLE [ob].[AccountVariabilityOverride] ADD CONSTRAINT [DF__AccountVa__Depar__0EB4746A] DEFAULT ('') FOR [DepartmentAssignment]; GO +ALTER TABLE [ob].[AccountVariabilityOverride] ADD CONSTRAINT [DF__AccountVa__Accou__0FA898A3] DEFAULT ('') FOR [AccountAssignment]; GO +ALTER TABLE [ob].[AccountVariabilityOverride] ADD CONSTRAINT [DF__AccountVa__Prece__109CBCDC] DEFAULT ((0)) FOR [PrecedentOrder]; GO +ALTER TABLE [ob].[AccountVariabilityOverride] ADD CONSTRAINT [DF__AccountVa__Varia__1190E115] DEFAULT ((0)) FOR [Variability]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.AssumptionImportHistory ------------------ +--------------------------------------------- +CREATE TABLE [ob].[AssumptionImportHistory] ( + [HistoryGUID] uniqueidentifier NOT NULL, + [BudgetModelType] nvarchar(30) NOT NULL, + [DataCategory] nvarchar(50) NOT NULL, + [ModelSection] nvarchar(100) NOT NULL, + [AssumptionType] nvarchar(100) NOT NULL, + [Models] nvarchar(max) NOT NULL, + [IsDetailedLevel] bit NULL, + [LineItems] nvarchar(max) NOT NULL, + [Status] tinyint NOT NULL, + PRIMARY KEY ([HistoryGUID]) +); +GO +ALTER TABLE [ob].[AssumptionImportHistory] ADD CONSTRAINT [FK_AssumptionImportHistory_SystemCenterImportHistory] FOREIGN KEY ([HistoryGUID]) REFERENCES [dbo].[SystemCenterImportHistory] ([HistoryGUID]); GO +ALTER TABLE [ob].[AssumptionImportHistory] ADD CONSTRAINT [CK_AssumptionImportHistory_Status] CHECK ([Status]=(3) OR [Status]=(2) OR [Status]=(1) OR [Status]=(0)); GO +ALTER TABLE [ob].[AssumptionImportHistory] ADD CONSTRAINT [DF_AssumptionImportHistory_IsDetailedLevel] DEFAULT (NULL) FOR [IsDetailedLevel]; GO +ALTER TABLE [ob].[AssumptionImportHistory] ADD CONSTRAINT [DF_AssumptionImportHistory_Status] DEFAULT ((0)) FOR [Status]; GO +ALTER TABLE [ob].[AssumptionImportHistory] ADD CONSTRAINT [DF_AssumptionImportHistory_BudgetModelType] DEFAULT ('') FOR [BudgetModelType]; GO +ALTER TABLE [ob].[AssumptionImportHistory] ADD CONSTRAINT [DF_AssumptionImportHistory_DataCategory] DEFAULT ('') FOR [DataCategory]; GO +ALTER TABLE [ob].[AssumptionImportHistory] ADD CONSTRAINT [DF_AssumptionImportHistory_ModelSection] DEFAULT ('') FOR [ModelSection]; GO +ALTER TABLE [ob].[AssumptionImportHistory] ADD CONSTRAINT [DF_AssumptionImportHistory_AssumptionType] DEFAULT ('') FOR [AssumptionType]; GO +ALTER TABLE [ob].[AssumptionImportHistory] ADD CONSTRAINT [DF_AssumptionImportHistory_Models] DEFAULT ('') FOR [Models]; GO +ALTER TABLE [ob].[AssumptionImportHistory] ADD CONSTRAINT [DF_AssumptionImportHistory_LineItems] DEFAULT ('') FOR [LineItems]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DefaultMethodList ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DefaultMethodList] ( + [ListID] int NOT NULL, + [ListName] nvarchar(200) NOT NULL, + [Template] nvarchar(100) NOT NULL, + [IncludeGlobal] bit NOT NULL, + [IsDynamic] bit NOT NULL, + [DescriptionOfDynamic] nvarchar(200) NOT NULL, + PRIMARY KEY ([ListID]) +); +GO +ALTER TABLE [ob].[DefaultMethodList] ADD CONSTRAINT [DF_DefaultMethodList_ListName] DEFAULT ('') FOR [ListName]; GO +ALTER TABLE [ob].[DefaultMethodList] ADD CONSTRAINT [DF_DefaultMethodList_Template] DEFAULT ('') FOR [Template]; GO +ALTER TABLE [ob].[DefaultMethodList] ADD CONSTRAINT [DF_DefaultMethodList_IncludeGlobal] DEFAULT ((0)) FOR [IncludeGlobal]; GO +ALTER TABLE [ob].[DefaultMethodList] ADD CONSTRAINT [DF_DefaultMethodList_IsDynamic] DEFAULT ((0)) FOR [IsDynamic]; GO +ALTER TABLE [ob].[DefaultMethodList] ADD CONSTRAINT [DF_DefaultMethodList_DescriptionOfDynamic] DEFAULT ('') FOR [DescriptionOfDynamic]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DefaultMethodListItem ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DefaultMethodListItem] ( + [ListItemID] int NOT NULL, + [ListItemName] nvarchar(200) NOT NULL, + [SortOrder] int NOT NULL, + [ListID] int NOT NULL, + [IsDynamic] bit NOT NULL, + [DescriptionOfDynamic] nvarchar(200) NOT NULL, + PRIMARY KEY ([ListItemID]) +); +GO +ALTER TABLE [ob].[DefaultMethodListItem] ADD CONSTRAINT [FK__DefaultMe__ListI__561CDE04] FOREIGN KEY ([ListID]) REFERENCES [ob].[DefaultMethodList] ([ListID]); GO +ALTER TABLE [ob].[DefaultMethodListItem] ADD CONSTRAINT [DF_DefaultMethodListItem_ListItemName] DEFAULT ('') FOR [ListItemName]; GO +ALTER TABLE [ob].[DefaultMethodListItem] ADD CONSTRAINT [DF_DefaultMethodListItem_SortOrder] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [ob].[DefaultMethodListItem] ADD CONSTRAINT [DF_DefaultMethodListItem_ListID] DEFAULT ((0)) FOR [ListID]; GO +ALTER TABLE [ob].[DefaultMethodListItem] ADD CONSTRAINT [DF_DefaultMethodListItem_IsDynamic] DEFAULT ((0)) FOR [IsDynamic]; GO +ALTER TABLE [ob].[DefaultMethodListItem] ADD CONSTRAINT [DF_DefaultMethodListItem_DescriptionOfDynamic] DEFAULT ('') FOR [DescriptionOfDynamic]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimAccountPH ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimAccountPH] ( + [AccountPHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([AccountPHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimAccountPH] ([MemberGUID]); +GO +ALTER TABLE [ob].[DimAccountPH] ADD CONSTRAINT [DF__DimAccoun__Histo__0EF1A5F3] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[DimAccountPH] ADD CONSTRAINT [DF__DimOBAccou__Name__1B351F42] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[DimAccountPH] ADD CONSTRAINT [DF__OB_DimAccountPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[DimAccountPH] ADD CONSTRAINT [DF__DimOBAcco__Membe__1C29437B] DEFAULT (newid()) FOR [MemberGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimAdjustmentCategory ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimAdjustmentCategory] ( + [HistoryItemGUID] uniqueidentifier NOT NULL, + [AdjustmentCategoryID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [Description] nvarchar(200) NOT NULL, + [AdjustmentCategoryRollup] nvarchar(200) NOT NULL, + [BudgetConfigGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([AdjustmentCategoryID]) +); +GO +ALTER TABLE [ob].[DimAdjustmentCategory] ADD CONSTRAINT [DF__DimAdjust__Budge__2405942C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [BudgetConfigGUID]; GO +ALTER TABLE [ob].[DimAdjustmentCategory] ADD CONSTRAINT [DF__DimAdjustm__Name__21292781] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[DimAdjustmentCategory] ADD CONSTRAINT [DF__DimAdjust__Descr__221D4BBA] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [ob].[DimAdjustmentCategory] ADD CONSTRAINT [DF__DimAdjust__Adjus__23116FF3] DEFAULT ('') FOR [AdjustmentCategoryRollup]; GO +ALTER TABLE [ob].[DimAdjustmentCategory] ADD CONSTRAINT [DF__DimAdjust__Trans__24F9B865] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[DimAdjustmentCategory] ADD CONSTRAINT [DF__DimAdjust__Membe__25EDDC9E] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [ob].[DimAdjustmentCategory] ADD CONSTRAINT [DF__DimAdjust__Histo__1F40DF0F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimDepartmentalBudget ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimDepartmentalBudget] ( + [MemberGUID] uniqueidentifier NOT NULL, + [DepartmentalBudgetID] int NOT NULL, + [Name] nvarchar(458) NOT NULL, + [DepartmentID] int NOT NULL, + [DepartmentName] nvarchar(203) NOT NULL, + [SystemID] smallint NOT NULL, + [System] nvarchar(100) NOT NULL, + [EntityID] int NOT NULL, + [Entity] nvarchar(100) NOT NULL, + [DepartmentRollup1ID] smallint NOT NULL, + [DepartmentRollup1] nvarchar(100) NOT NULL, + [DepartmentRollup2ID] smallint NOT NULL, + [DepartmentRollup2] nvarchar(100) NOT NULL, + [DepartmentRollup3ID] smallint NOT NULL, + [DepartmentRollup3] nvarchar(100) NOT NULL, + [DepartmentRollup4ID] int NOT NULL, + [DepartmentRollup4] nvarchar(100) NOT NULL, + [DepartmentRollup5ID] smallint NOT NULL, + [DepartmentRollup5] nvarchar(100) NOT NULL, + [DepartmentRollup6ID] smallint NOT NULL, + [DepartmentRollup6] nvarchar(100) NOT NULL, + [ResearchDepartmentCategoryID] int NOT NULL, + [ResearchDepartmentCategoryName] nvarchar(100) NOT NULL, + [Admin] nvarchar(400) NOT NULL, + [Finance] nvarchar(400) NOT NULL, + [VicePresident] nvarchar(400) NOT NULL, + [Director] nvarchar(400) NOT NULL, + [Manager] nvarchar(400) NOT NULL, + [BaseYear] float NOT NULL, + [BaseYear1] float NOT NULL, + [StartYear] float NOT NULL, + [NumberofYears] float NOT NULL, + [MonthsLoaded] nvarchar(200) NOT NULL, + [OBActivePlans] nvarchar(200) NOT NULL, + [BudgetStatus] nvarchar(100) NOT NULL, + [OpenDate] date NOT NULL, + [LastModified] nvarchar(200) NOT NULL, + [WorkedHrsperUOSProjection] float NOT NULL, + [WorkedHrsperUOSBudget] float NOT NULL, + [FTEApprovalOverride] nvarchar(100) NOT NULL, + [FrameworkID] int NOT NULL, + [LootID] int NOT NULL, + [HourTypeFixed] nvarchar(200) NOT NULL, + [HourType] nvarchar(200) NOT NULL, + [TargetType] nvarchar(200) NOT NULL, + [IsVariable] bit NOT NULL, + [VariableProjectionMethod] nvarchar(200) NOT NULL, + [ContractLaborSkillMix] nvarchar(200) NOT NULL, + [EntitySortOrder] int NOT NULL, + [SystemSortOrder] int NOT NULL, + [DepartmentRollup1SortOrder] int NOT NULL, + [DepartmentRollup2SortOrder] int NOT NULL, + [DepartmentRollup3SortOrder] int NOT NULL, + [DepartmentRollup4SortOrder] int NOT NULL, + [DepartmentRollup5SortOrder] int NOT NULL, + [DepartmentRollup6SortOrder] int NOT NULL, + [ResearchDepartmentCategorySortOrder] int NOT NULL, + [HasAttachments] nvarchar(200) NOT NULL, + [HideNotSpecified] nvarchar(400) NOT NULL, + [GMTestFWName] nvarchar(450) NOT NULL, + [GMTestFWDateCreated] nvarchar(200) NOT NULL, + [TransactionID] int NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [MRVicePresident] nvarchar(400) NOT NULL, + [MRDirector] nvarchar(400) NOT NULL, + [MRManager] nvarchar(400) NOT NULL, + [ReadOnly] nvarchar(400) NOT NULL, + [WriteDeny] nvarchar(400) NOT NULL, + [EntityDefaultWorkWeekID] int NOT NULL, + [OBDirector] nvarchar(400) NOT NULL, + [OBManager] nvarchar(400) NOT NULL, + [OBVicePresident] nvarchar(400) NOT NULL, + [SecureGroupID] int NOT NULL, + [DepartmentCode] nvarchar(100) NOT NULL, + [VariablehrsperUOSActualYTD] float NOT NULL, + [VariablehrsperUOStargetCurrentYr] float NOT NULL, + [VariablehrsperUOS] float NOT NULL, + [VariablehrsperUOStarget] float NOT NULL, + [BudgetedFixedFTEs] float NOT NULL, + [BudgetedVariableFTEs] float NOT NULL, + [UOSchangeyy] float NOT NULL, + [ExcessofRevandExpchangeyy] float NOT NULL, + PRIMARY KEY ([DepartmentalBudgetID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [IX_DepartmentID] ON [ob].[DimDepartmentalBudget] ([DepartmentID]); +CREATE NONCLUSTERED INDEX [IX_DepartmentalBudgetID] ON [ob].[DimDepartmentalBudget] ([DepartmentalBudgetID]); +CREATE NONCLUSTERED INDEX [IX_MemberGUID] ON [ob].[DimDepartmentalBudget] ([MemberGUID]); +GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Entit__11ECDB15] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__OBAct__7DF62CF7] DEFAULT ('') FOR [OBActivePlans]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Budge__068B72F8] DEFAULT ('Draft') FOR [BudgetStatus]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__OpenD__7EEA5130] DEFAULT ('') FOR [OpenDate]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__LastM__7B19C04C] DEFAULT ('') FOR [LastModified]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Worke__077F9731] DEFAULT ((0)) FOR [WorkedHrsperUOSProjection]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Worke__0873BB6A] DEFAULT ((0)) FOR [WorkedHrsperUOSBudget]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__FTEAp__0B502815] DEFAULT ('None') FOR [FTEApprovalOverride]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Frame__0C3401BF] DEFAULT ((0)) FOR [FrameworkID]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__LootI__0E1C4A31] DEFAULT ((0)) FOR [LootID]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__HourT__71591BAD] DEFAULT ('') FOR [HourTypeFixed]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__HourT__4F20D1DE] DEFAULT ('') FOR [HourType]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Secur__64849E34] DEFAULT ((0)) FOR [SecureGroupID]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Targe__03C9A447] DEFAULT ('') FOR [TargetType]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__IsVar__6CB396CA] DEFAULT ((0)) FOR [IsVariable]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Varia__06A610F2] DEFAULT ('') FOR [VariableProjectionMethod]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Contr__05B1ECB9] DEFAULT ('') FOR [ContractLaborSkillMix]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Entit__486CE00A] DEFAULT ((0)) FOR [EntitySortOrder]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Syste__49610443] DEFAULT ((0)) FOR [SystemSortOrder]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__OBDir__6A46CDD4] DEFAULT ('') FOR [OBDirector]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__4A55287C] DEFAULT ((0)) FOR [DepartmentRollup1SortOrder]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__OBMan__6B3AF20D] DEFAULT ('') FOR [OBManager]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__4B494CB5] DEFAULT ((0)) FOR [DepartmentRollup2SortOrder]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__OBVic__6C2F1646] DEFAULT ('') FOR [OBVicePresident]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__4C3D70EE] DEFAULT ((0)) FOR [DepartmentRollup3SortOrder]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__4D319527] DEFAULT ((0)) FOR [DepartmentRollup4SortOrder]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__4E25B960] DEFAULT ((0)) FOR [DepartmentRollup5SortOrder]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__4F19DD99] DEFAULT ((0)) FOR [DepartmentRollup6SortOrder]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Resea__43A82AED] DEFAULT ((0)) FOR [ResearchDepartmentCategorySortOrder]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__HasAt__7A259C13] DEFAULT ('') FOR [HasAttachments]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__HideN__1F9F094A] DEFAULT ('') FOR [HideNotSpecified]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__GMTes__6A243E74] DEFAULT ('') FOR [GMTestFWName]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__GMTes__6B1862AD] DEFAULT ('') FOR [GMTestFWDateCreated]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__MRVic__74A1FEB1] DEFAULT ('') FOR [MRVicePresident]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__OB_DimDepartmentalBudget_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__MRDir__7966B3CE] DEFAULT ('') FOR [MRDirector]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__MRMan__7E2B68EB] DEFAULT ('') FOR [MRManager]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__ReadO__03101999] DEFAULT ('') FOR [ReadOnly]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Write__04043DD2] DEFAULT ('') FOR [WriteDeny]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF_DimOBPlan_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__2B61FAC8] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Varia__2C1889E4] DEFAULT ((0)) FOR [VariablehrsperUOSActualYTD]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Varia__2D0CAE1D] DEFAULT ((0)) FOR [VariablehrsperUOStargetCurrentYr]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Varia__2E00D256] DEFAULT ((0)) FOR [VariablehrsperUOS]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Varia__2EF4F68F] DEFAULT ((0)) FOR [VariablehrsperUOStarget]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Budge__2FE91AC8] DEFAULT ((0)) FOR [BudgetedFixedFTEs]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Budge__30DD3F01] DEFAULT ((0)) FOR [BudgetedVariableFTEs]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__UOSch__31D1633A] DEFAULT ((0)) FOR [UOSchangeyy]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Exces__32C58773] DEFAULT ((0)) FOR [ExcessofRevandExpchangeyy]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF_OBDIMDEPARTMENTALBUDGETMEMBERGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepartm__Name__0D2825F8] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF_DimDepartmentalBudget_DepartmentID] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__0F106E6A] DEFAULT ('') FOR [DepartmentName]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Syste__100492A3] DEFAULT ((0)) FOR [SystemID]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Syste__10F8B6DC] DEFAULT ('') FOR [System]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Entit__12E0FF4E] DEFAULT ('') FOR [Entity]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__13D52387] DEFAULT ((0)) FOR [DepartmentRollup1ID]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__14C947C0] DEFAULT ('') FOR [DepartmentRollup1]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__15BD6BF9] DEFAULT ((0)) FOR [DepartmentRollup2ID]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__16B19032] DEFAULT ('') FOR [DepartmentRollup2]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__17A5B46B] DEFAULT ((0)) FOR [DepartmentRollup3ID]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__1899D8A4] DEFAULT ('') FOR [DepartmentRollup3]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Entit__489A2A98] DEFAULT ((0)) FOR [EntityDefaultWorkWeekID]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__198DFCDD] DEFAULT ((0)) FOR [DepartmentRollup4ID]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__1A822116] DEFAULT ('') FOR [DepartmentRollup4]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__1B76454F] DEFAULT ((0)) FOR [DepartmentRollup5ID]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__1C6A6988] DEFAULT ('') FOR [DepartmentRollup5]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__1D5E8DC1] DEFAULT ((0)) FOR [DepartmentRollup6ID]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Depar__1E52B1FA] DEFAULT ('') FOR [DepartmentRollup6]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Resea__41BFE27B] DEFAULT ((0)) FOR [ResearchDepartmentCategoryID]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Resea__42B406B4] DEFAULT ('') FOR [ResearchDepartmentCategoryName]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Admin__1DB6C0D8] DEFAULT ('') FOR [Admin]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Finan__1EAAE511] DEFAULT ('') FOR [Finance]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__ViceP__00D299A2] DEFAULT ('') FOR [VicePresident]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Direc__783D53A1] DEFAULT ('') FOR [Director]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Manag__7C0DE485] DEFAULT ('') FOR [Manager]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__BaseY__76550B2F] DEFAULT ((0)) FOR [BaseYear]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__BaseY__05974EBF] DEFAULT ((0)) FOR [BaseYear1]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Start__09179DF2] DEFAULT ((0)) FOR [StartYear]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Numbe__0A0BC22B] DEFAULT ((3)) FOR [NumberofYears]; GO +ALTER TABLE [ob].[DimDepartmentalBudget] ADD CONSTRAINT [DF__DimDepart__Month__7D0208BE] DEFAULT ('') FOR [MonthsLoaded]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimDepartmentalBudgetPH ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimDepartmentalBudgetPH] ( + [MemberGUID] uniqueidentifier NOT NULL, + [DepartmentalBudgetPHID] tinyint NOT NULL, + [Name] nvarchar(100) NOT NULL, + [IsConstant] bit NOT NULL, + [Version] timestamp NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([DepartmentalBudgetPHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimDepartmentalBudgetPH] ([MemberGUID]); +GO +ALTER TABLE [ob].[DimDepartmentalBudgetPH] ADD CONSTRAINT [DF_DimDepartmentalBudgetPH_MemberGUID] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [ob].[DimDepartmentalBudgetPH] ADD CONSTRAINT [DF_DimDepartmentalBudgetPH_IsConstant] DEFAULT ((0)) FOR [IsConstant]; GO +ALTER TABLE [ob].[DimDepartmentalBudgetPH] ADD CONSTRAINT [DF__OB_DimDepartmentalBudgetPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[DimDepartmentalBudgetPH] ADD CONSTRAINT [DF_DimDepartmentalBudgetPH_HistoryItemGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[DimDepartmentalBudgetPH] ADD CONSTRAINT [DF_OBDIMDEPARTMENTALBUDGETPHNAME] DEFAULT ('') FOR [Name]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimFinancialReporting ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimFinancialReporting] ( + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Statement] nvarchar(100) NOT NULL, + [Section] nvarchar(100) NOT NULL, + [LineName] nvarchar(100) NOT NULL, + [IsMappable] nvarchar(100) NOT NULL, + [ConsolidatedFinancialReportingID] int NOT NULL, + [ConsolidatedIsInverted] bit NOT NULL, + [ConsolidatedInversion] int NOT NULL, + [Name] varchar(4000) NOT NULL, + [StatementMappabilityFilterParameter] varchar(4000) NOT NULL, + [ConsolidatedFinancialReporting] varchar(4000) NOT NULL, + [ConsolidatedFinancialReportingSortOrder] int NOT NULL, + [IsExpense] bit NOT NULL, + [IsRequired] bit NOT NULL, + [IsVolume] bit NOT NULL, + [IsFTERollup] bit NOT NULL, + [IsEditable] bit NOT NULL, + [DisplayFormat] nvarchar(200) NOT NULL, + [SortOrder] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [ProjectionMethod] nvarchar(100) NOT NULL, + [SpreadMethod] nvarchar(100) NOT NULL, + [ToBeDeleted] bit NOT NULL, + PRIMARY KEY ([FinancialReportingID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimFinancialReporting] ([MemberGUID]); +GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Finan__012DFA15] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanci__Name__1FB3E619] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__State__20A80A52] DEFAULT ('') FOR [StatementMappabilityFilterParameter]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Conso__219C2E8B] DEFAULT ('') FOR [ConsolidatedFinancialReporting]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Conso__229052C4] DEFAULT ((0)) FOR [ConsolidatedFinancialReportingSortOrder]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__IsExp__68303DB3] DEFAULT ((0)) FOR [IsExpense]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__IsReq__41D8B7FD] DEFAULT ((0)) FOR [IsRequired]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__IsVol__42CCDC36] DEFAULT ((0)) FOR [IsVolume]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__IsFTE__43C1006F] DEFAULT ((0)) FOR [IsFTERollup]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__IsEdi__44B524A8] DEFAULT ((1)) FOR [IsEditable]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Displ__57E03511] DEFAULT ('') FOR [DisplayFormat]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__ToBeD__28645F72] DEFAULT ((0)) FOR [ToBeDeleted]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__SortO__2A045BC8] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Proje__66A68310] DEFAULT ('Annualized') FOR [ProjectionMethod]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Sprea__679AA749] DEFAULT ('Projected') FOR [SpreadMethod]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Membe__7D5ECE15] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__State__7F471687] DEFAULT ('') FOR [Statement]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Secti__003B3AC0] DEFAULT ('') FOR [Section]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Histo__7E52F24E] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__LineN__012F5EF9] DEFAULT ('') FOR [LineName]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__IsMap__0317A76B] DEFAULT ('') FOR [IsMappable]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Conso__040BCBA4] DEFAULT ((0)) FOR [ConsolidatedFinancialReportingID]; GO +ALTER TABLE [ob].[DimFinancialReporting] ADD CONSTRAINT [DF__DimFinanc__Conso__04FFEFDD] DEFAULT ((0)) FOR [ConsolidatedIsInverted]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimFinancialReportingPH ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimFinancialReportingPH] ( + [FinancialReportingPHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + PRIMARY KEY ([FinancialReportingPHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimFinancialReportingPH] ([MemberGUID]); +GO +ALTER TABLE [ob].[DimFinancialReportingPH] ADD CONSTRAINT [DF__DimFinanci__Name__171EA018] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[DimFinancialReportingPH] ADD CONSTRAINT [DF__DimFinanc__Membe__1812C451] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [ob].[DimFinancialReportingPH] ADD CONSTRAINT [DF__DimFinanc__Histo__1906E88A] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimGlobalStatisticRollup ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimGlobalStatisticRollup] ( + [StatisticRollupID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([StatisticRollupID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimGlobalStatisticRollup] ([MemberGUID]); +GO +ALTER TABLE [ob].[DimGlobalStatisticRollup] ADD CONSTRAINT [DF__DimStatist__Name__1823A86D] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[DimGlobalStatisticRollup] ADD CONSTRAINT [DF__OB_DimGlobalStatisticRollup_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[DimGlobalStatisticRollup] ADD CONSTRAINT [DF__DimStatis__Membe__1917CCA6] DEFAULT (newid()) FOR [MemberGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimGlobalStatisticsPlanPH ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimGlobalStatisticsPlanPH] ( + [OBGlobalStatsPlanPHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([OBGlobalStatsPlanPHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimGlobalStatisticsPlanPH] ([MemberGUID]); +GO +ALTER TABLE [ob].[DimGlobalStatisticsPlanPH] ADD CONSTRAINT [DF__OB_DimGlobalStatisticsPlanPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[DimGlobalStatisticsPlanPH] ADD CONSTRAINT [DF__DimOBGloba__Name__37082240] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[DimGlobalStatisticsPlanPH] ADD CONSTRAINT [DF__DimOBGlob__Membe__37FC4679] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [ob].[DimGlobalStatisticsPlanPH] ADD CONSTRAINT [DF__DimOBGlob__Histo__38F06AB2] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimOBAllocation ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimOBAllocation] ( + [OBAllocationID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [Type] nvarchar(100) NOT NULL, + [AlwaysUseBasis] bit NOT NULL, + [OBAllocationBasisID] int NOT NULL, + [ExecutionOrder] smallint NOT NULL, + PRIMARY KEY ([OBAllocationID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBAllocation] ([MemberGUID]); +GO +ALTER TABLE [ob].[DimOBAllocation] ADD CONSTRAINT [DF__DimOBAlloc__Name__4679AAA0] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[DimOBAllocation] ADD CONSTRAINT [DF__DimOBAllo__Membe__476DCED9] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [ob].[DimOBAllocation] ADD CONSTRAINT [DF__DimOBAllo__Trans__4956174B] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[DimOBAllocation] ADD CONSTRAINT [DF__DimOBAlloc__Type__4A4A3B84] DEFAULT ('') FOR [Type]; GO +ALTER TABLE [ob].[DimOBAllocation] ADD CONSTRAINT [DF__DimOBAllo__Histo__4861F312] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[DimOBAllocation] ADD CONSTRAINT [DF__DimOBAllo__Alway__60397CA3] DEFAULT ((0)) FOR [AlwaysUseBasis]; GO +ALTER TABLE [ob].[DimOBAllocation] ADD CONSTRAINT [DF__DimOBAllo__Alloc__70F9F451] DEFAULT ((0)) FOR [OBAllocationBasisID]; GO +ALTER TABLE [ob].[DimOBAllocation] ADD CONSTRAINT [DF__DimOBAllo__Execu__7BC101FA] DEFAULT ((0)) FOR [ExecutionOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimOBAllocationBasis ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimOBAllocationBasis] ( + [OBAllocationBasisID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [Category] nvarchar(100) NOT NULL, + [OBForecastDetailID] int NOT NULL, + PRIMARY KEY ([OBAllocationBasisID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBAllocationBasis] ([MemberGUID]); +GO +ALTER TABLE [ob].[DimOBAllocationBasis] ADD CONSTRAINT [DF__DimOBAllo__OBFor__1149F5AE] DEFAULT ((0)) FOR [OBForecastDetailID]; GO +ALTER TABLE [ob].[DimOBAllocationBasis] ADD CONSTRAINT [DF__DimOBAllo__Histo__667C65DE] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[DimOBAllocationBasis] ADD CONSTRAINT [DF__DimOBAlloc__Name__64941D6C] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[DimOBAllocationBasis] ADD CONSTRAINT [DF__DimOBAllo__Membe__658841A5] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [ob].[DimOBAllocationBasis] ADD CONSTRAINT [DF__DimOBAllo__Trans__67708A17] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[DimOBAllocationBasis] ADD CONSTRAINT [DF__DimOBAllo__Categ__6864AE50] DEFAULT ('Not Specified') FOR [Category]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimOBExceptions ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimOBExceptions] ( + [OBExceptionsID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [Severity] nvarchar(100) NOT NULL, + [Model] nvarchar(100) NOT NULL, + [ViewName] nvarchar(100) NOT NULL, + [SortOrder] smallint NOT NULL, + [Description] nvarchar(max) NOT NULL, + [Resolution] nvarchar(max) NOT NULL, + [FullName] nvarchar(303) NOT NULL, + [CustomActionGUID] uniqueidentifier NOT NULL, + [SystemCenterLink] nvarchar(400) NOT NULL, + [IsClientException] bit NOT NULL, + PRIMARY KEY ([OBExceptionsID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBExceptions] ([MemberGUID]); +GO +ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF_ob_DimOBExceptions_SystemCenterLink] DEFAULT ('') FOR [SystemCenterLink]; GO +ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF_ob_DimOBExceptions_IsClientException] DEFAULT ((1)) FOR [IsClientException]; GO +ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF__DimOBExce__Descr__21A8E3FB] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF__DimOBExce__Resol__229D0834] DEFAULT ('') FOR [Resolution]; GO +ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF__DimOBExce__Histo__68C30A55] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF_ob_DimOBExceptions_CustomActionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CustomActionGUID]; GO +ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF__DimOBExcep__Name__66DAC1E3] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF__DimOBExce__Membe__67CEE61C] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF__DimOBExce__Trans__69B72E8E] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF__DimOBExce__Sever__6AAB52C7] DEFAULT ('') FOR [Severity]; GO +ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF__DimOBExce__Model__6B9F7700] DEFAULT ('') FOR [Model]; GO +ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF__DimOBExce__ViewN__6C939B39] DEFAULT ('') FOR [ViewName]; GO +ALTER TABLE [ob].[DimOBExceptions] ADD CONSTRAINT [DF__DimOBExce__SortO__6D87BF72] DEFAULT ((0)) FOR [SortOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimOBForecastDetail ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimOBForecastDetail] ( + [OBForecastDetailID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [Category] nvarchar(200) NOT NULL, + [DriverID] int NOT NULL, + [IsSalaryDriver] bit NOT NULL, + [IsRevenueDriver] bit NOT NULL, + [AccountID] int NOT NULL, + [UnitTypeID] int NOT NULL, + [SortOrder] int NOT NULL, + [SecondaryAccountID] int NOT NULL, + [UnitType] nvarchar(200) NOT NULL, + [Driver] nvarchar(200) NOT NULL, + [Account] nvarchar(103) NOT NULL, + [SecondaryAccount] nvarchar(103) NOT NULL, + [Code] nvarchar(100) NOT NULL, + [ForecastDetailRollup] nvarchar(200) NOT NULL, + [VolumeTarget] nvarchar(200) NOT NULL, + [IsMROnly] bit NOT NULL, + [IsVariable] bit NOT NULL, + PRIMARY KEY ([OBForecastDetailID]) +); +GO +ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Histo__2D11D9EA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Accou__2322540F] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBForec__Code__27B46107] DEFAULT ('') FOR [Code]; GO +ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Volum__2821092A] DEFAULT ('Not Specified') FOR [VolumeTarget]; GO +ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBForec__Name__2B299178] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Membe__2C1DB5B1] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Trans__2E05FE23] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Categ__2EFA225C] DEFAULT ('') FOR [Category]; GO +ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Drive__3F7B6E3F] DEFAULT ((0)) FOR [DriverID]; GO +ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__IsMRO__421912B3] DEFAULT ((0)) FOR [IsMROnly]; GO +ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__SortO__45ED38B6] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__IsVar__46CA4FE5] DEFAULT ((0)) FOR [IsVariable]; GO +ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Forec__4B697A10] DEFAULT ('Not Specified') FOR [ForecastDetailRollup]; GO +ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__IsSal__56DEC1DB] DEFAULT ((0)) FOR [IsSalaryDriver]; GO +ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__IsRev__57D2E614] DEFAULT ((0)) FOR [IsRevenueDriver]; GO +ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__UnitT__6AFDF67D] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Secon__6E6609BB] DEFAULT ((0)) FOR [SecondaryAccountID]; GO +ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__UnitT__6F5A2DF4] DEFAULT ('') FOR [UnitType]; GO +ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Drive__704E522D] DEFAULT ('') FOR [Driver]; GO +ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Accou__71427666] DEFAULT ('') FOR [Account]; GO +ALTER TABLE [ob].[DimOBForecastDetail] ADD CONSTRAINT [DF__DimOBFore__Secon__72369A9F] DEFAULT ('') FOR [SecondaryAccount]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimOBForecastDetailPH ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimOBForecastDetailPH] ( + [OBForecastDetailPHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([OBForecastDetailPHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBForecastDetailPH] ([MemberGUID]); +GO +ALTER TABLE [ob].[DimOBForecastDetailPH] ADD CONSTRAINT [DF__DimOBForec__Name__021D5A44] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[DimOBForecastDetailPH] ADD CONSTRAINT [DF__DimOBFore__Membe__03117E7D] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [ob].[DimOBForecastDetailPH] ADD CONSTRAINT [DF__DimOBFore__Trans__04F9C6EF] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[DimOBForecastDetailPH] ADD CONSTRAINT [DF__DimOBFore__Histo__0405A2B6] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimOBGlobalStatistics ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimOBGlobalStatistics] ( + [OBGlobalStatisticID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [AccountDescription] nvarchar(100) NOT NULL, + [AccountCode] nvarchar(100) NOT NULL, + [DepartmentCode] nvarchar(100) NOT NULL, + [AccountID] int NOT NULL, + [DepartmentID] int NOT NULL, + [Account] nvarchar(103) NOT NULL, + [Department] nvarchar(203) NOT NULL, + [OBForecastDetailID] int NOT NULL, + [LOSLinkID] int NOT NULL, + [OBForecastDetail] nvarchar(200) NOT NULL, + [LOSLink] nvarchar(103) NOT NULL, + [PatientClass] nvarchar(100) NOT NULL, + [OBPayor] nvarchar(100) NOT NULL, + [OBPayorGroup] nvarchar(100) NOT NULL, + [OBUnitsFinancialReportingName] varchar(200) NOT NULL, + [OBUnitsFinancialReportingLineName] nvarchar(100) NOT NULL, + [FillinSection] nvarchar(120) NOT NULL, + [Name] nvarchar(304) NOT NULL, + PRIMARY KEY ([OBGlobalStatisticID]) +); + +CREATE UNIQUE NONCLUSTERED INDEX [NCU_AccountID_DepartmentID] ON [ob].[DimOBGlobalStatistics] ([DepartmentID], [AccountID]); +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBGlobalStatistics] ([MemberGUID]); +GO +ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Patie__0AB9C654] DEFAULT ('') FOR [PatientClass]; GO +ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__OBPay__0BADEA8D] DEFAULT ('') FOR [OBPayor]; GO +ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__OBPay__0CA20EC6] DEFAULT ('') FOR [OBPayorGroup]; GO +ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__OBUni__0D9632FF] DEFAULT ('') FOR [OBUnitsFinancialReportingName]; GO +ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Histo__15646D8B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__OBUni__0E8A5738] DEFAULT ('') FOR [OBUnitsFinancialReportingLineName]; GO +ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Accou__1272F247] DEFAULT ('') FOR [Account]; GO +ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Depar__13671680] DEFAULT ('') FOR [Department]; GO +ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Membe__14704952] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Trans__165891C4] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Accou__1B1D46E1] DEFAULT ('') FOR [AccountDescription]; GO +ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Accou__1C116B1A] DEFAULT ('') FOR [AccountCode]; GO +ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Depar__1D058F53] DEFAULT ('') FOR [DepartmentCode]; GO +ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Accou__20D62037] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__Depar__21CA4470] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__OBFor__33BED779] DEFAULT ((0)) FOR [OBForecastDetailID]; GO +ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__LOSLi__34B2FBB2] DEFAULT ((0)) FOR [LOSLinkID]; GO +ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__OBFor__7498769D] DEFAULT ('') FOR [OBForecastDetail]; GO +ALTER TABLE [ob].[DimOBGlobalStatistics] ADD CONSTRAINT [DF__DimOBGlob__LOSLi__758C9AD6] DEFAULT ('') FOR [LOSLink]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimOBGlobalStatisticsPH ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimOBGlobalStatisticsPH] ( + [OBGlobalStatisticsPHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([OBGlobalStatisticsPHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBGlobalStatisticsPH] ([MemberGUID]); +GO +ALTER TABLE [ob].[DimOBGlobalStatisticsPH] ADD CONSTRAINT [DF__DimOBGloba__Name__296B6638] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[DimOBGlobalStatisticsPH] ADD CONSTRAINT [DF__DimOBGlob__Membe__2A5F8A71] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [ob].[DimOBGlobalStatisticsPH] ADD CONSTRAINT [DF__DimOBGlob__Trans__2C47D2E3] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[DimOBGlobalStatisticsPH] ADD CONSTRAINT [DF__DimOBGlob__Histo__2B53AEAA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimOBGlobalStatisticsPlan ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimOBGlobalStatisticsPlan] ( + [OBGlobalStatisticsPlanID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [Name] nvarchar(1000) NOT NULL, + [BaseYear] float NOT NULL, + [MonthsLoaded] float NOT NULL, + [EntityID] int NOT NULL, + [SecureGroupID] int NOT NULL, + [StartYear] float NOT NULL, + [NumberofYears] float NOT NULL, + [Entity] nvarchar(100) NOT NULL, + [LootID] int NOT NULL, + [IsDeleted] bit NOT NULL, + [FrameworkID] int NOT NULL, + PRIMARY KEY ([OBGlobalStatisticsPlanID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBGlobalStatisticsPlan] ([MemberGUID]); +GO +ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__Membe__080A726D] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__Trans__09F2BADF] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__Start__1489509E] DEFAULT ((0)) FOR [StartYear]; GO +ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__Numbe__157D74D7] DEFAULT ((3)) FOR [NumberofYears]; GO +ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__Entit__23176717] DEFAULT ('') FOR [Entity]; GO +ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__Entit__76EAD363] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__LootI__240B8B50] DEFAULT ((0)) FOR [LootID]; GO +ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__IsDel__24FFAF89] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__Histo__08FE96A6] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF_OBDIMOBGLOBALSTATISTICSPLANSECUREGROUPID] DEFAULT ((2)) FOR [SecureGroupID]; GO +ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGloba__Name__5569E407] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__BaseY__5DFF2A08] DEFAULT ((0)) FOR [BaseYear]; GO +ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__Month__61CFBAEC] DEFAULT ((0)) FOR [MonthsLoaded]; GO +ALTER TABLE [ob].[DimOBGlobalStatisticsPlan] ADD CONSTRAINT [DF__DimOBGlob__Frame__6578C26D] DEFAULT ((0)) FOR [FrameworkID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimOBReimbursementPlan ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimOBReimbursementPlan] ( + [OBReimbursementPlanID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [FrameworkID] tinyint NOT NULL, + [TransactionID] int NOT NULL, + [NameCalc] nvarchar(450) NOT NULL, + [BaseYear] float NOT NULL, + [EntityID] int NOT NULL, + [StartYear] nvarchar(200) NOT NULL, + [NumberofYears] float NOT NULL, + [LootID] int NOT NULL, + [Entity] nvarchar(100) NOT NULL, + [EntitySortOrder] int NOT NULL, + [Name] nvarchar(1000) NOT NULL, + [SecureGroupID] int NOT NULL, + [MonthsLoaded] nvarchar(400) NOT NULL, + PRIMARY KEY ([OBReimbursementPlanID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBReimbursementPlan] ([MemberGUID]); +GO +ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__Start__1E12BAD8] DEFAULT ('') FOR [StartYear]; GO +ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__Numbe__1F06DF11] DEFAULT ((3)) FOR [NumberofYears]; GO +ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__NameN__22F836DD] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__Membe__28BD620F] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__LootI__29C464A6] DEFAULT ((0)) FOR [LootID]; GO +ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__Entit__2AB888DF] DEFAULT ('') FOR [Entity]; GO +ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__Entit__2BACAD18] DEFAULT ((0)) FOR [EntitySortOrder]; GO +ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__Frame__2E763B65] DEFAULT ((0)) FOR [FrameworkID]; GO +ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__OB_DimOBReimbursementPlan_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__Secur__38FD51EC] DEFAULT ((0)) FOR [SecureGroupID]; GO +ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__Entit__16F0BBFD] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__Histo__29B18648] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__NameC__72B98475] DEFAULT ('New Plan') FOR [NameCalc]; GO +ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__BaseY__73ADA8AE] DEFAULT ((0)) FOR [BaseYear]; GO +ALTER TABLE [ob].[DimOBReimbursementPlan] ADD CONSTRAINT [DF__DimOBReim__Month__7EFC6437] DEFAULT ('') FOR [MonthsLoaded]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimOBReimbursementPlanPH ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimOBReimbursementPlanPH] ( + [OBReimbursementPlanPHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([OBReimbursementPlanPHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBReimbursementPlanPH] ([MemberGUID]); +GO +ALTER TABLE [ob].[DimOBReimbursementPlanPH] ADD CONSTRAINT [DF__DimOBReimb__Name__1D4BAF63] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[DimOBReimbursementPlanPH] ADD CONSTRAINT [DF__DimOBReim__Membe__1E3FD39C] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [ob].[DimOBReimbursementPlanPH] ADD CONSTRAINT [DF__OB_DimOBReimbursementPlanPH_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[DimOBReimbursementPlanPH] ADD CONSTRAINT [DF__DimOBReim__Histo__1F33F7D5] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimOBServiceLinePlan ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimOBServiceLinePlan] ( + [OBServiceLinePlanID] int NOT NULL, + [EntityID] int NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [BaseYear] nvarchar(200) NOT NULL, + [MonthsLoaded] nvarchar(200) NOT NULL, + [StartYear] float NOT NULL, + [NumberofYears] float NOT NULL, + [FrameworkID] int NOT NULL, + [LootID] int NOT NULL, + [IsDeleted] bit NOT NULL, + [Entity] nvarchar(100) NOT NULL, + [EntitySortOrder] int NOT NULL, + [SecureGroupID] int NOT NULL, + [Name] nvarchar(1000) NOT NULL, + [OtherVolumeBudgetYear] float NOT NULL, + [OutpatientVolumeProjectedYear] float NOT NULL, + [OutpatientVolumeBudgetYear] float NOT NULL, + [ObservationVolumeBudgetYear] float NOT NULL, + [EDVolumeProjectedYear] float NOT NULL, + [ObservationVolumeProjectedYear] float NOT NULL, + [EDVolumeBudgetYear] float NOT NULL, + [InpatientVolumeBudgetYear] float NOT NULL, + [ClinicVolumeBudgetYear] float NOT NULL, + [OtherVolumeProjectedYear] float NOT NULL, + [ClinicVolumeProjectedYear] float NOT NULL, + [InpatientVolumeProjectedYear] float NOT NULL, + PRIMARY KEY ([OBServiceLinePlanID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBServiceLinePlan] ([MemberGUID]); +GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Histo__159BD9BA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Membe__14A7B581] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Trans__168FFDF3] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Start__194E05BB] DEFAULT ((0)) FOR [StartYear]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Numbe__1A4229F4] DEFAULT ((3)) FOR [NumberofYears]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Frame__3165866E] DEFAULT ((0)) FOR [FrameworkID]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Entit__13B39148] DEFAULT ((0)) FOR [EntityID]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__LootI__3259AAA7] DEFAULT ((0)) FOR [LootID]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__IsDel__334DCEE0] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Other__33B9ABAC] DEFAULT ((0)) FOR [OtherVolumeBudgetYear]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Entit__3441F319] DEFAULT ('') FOR [Entity]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Outpa__34ADCFE5] DEFAULT ((0)) FOR [OutpatientVolumeProjectedYear]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Entit__35361752] DEFAULT ((0)) FOR [EntitySortOrder]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Outpa__35A1F41E] DEFAULT ((0)) FOR [OutpatientVolumeBudgetYear]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Secur__362A3B8B] DEFAULT ((0)) FOR [SecureGroupID]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Obser__36961857] DEFAULT ((0)) FOR [ObservationVolumeBudgetYear]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__EDVol__378A3C90] DEFAULT ((0)) FOR [EDVolumeProjectedYear]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Obser__387E60C9] DEFAULT ((0)) FOR [ObservationVolumeProjectedYear]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__EDVol__39728502] DEFAULT ((0)) FOR [EDVolumeBudgetYear]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Inpat__3A66A93B] DEFAULT ((0)) FOR [InpatientVolumeBudgetYear]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Clini__3B5ACD74] DEFAULT ((0)) FOR [ClinicVolumeBudgetYear]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Other__3C4EF1AD] DEFAULT ((0)) FOR [OtherVolumeProjectedYear]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Clini__3D4315E6] DEFAULT ((0)) FOR [ClinicVolumeProjectedYear]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__NameN__3DAC2D19] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Inpat__3E373A1F] DEFAULT ((0)) FOR [InpatientVolumeProjectedYear]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__BaseY__426E8031] DEFAULT ('') FOR [BaseYear]; GO +ALTER TABLE [ob].[DimOBServiceLinePlan] ADD CONSTRAINT [DF__DimOBServ__Month__4362A46A] DEFAULT ('') FOR [MonthsLoaded]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimOBServiceLinePlanPH ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimOBServiceLinePlanPH] ( + [OBServiceLinePlanPHID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([OBServiceLinePlanPHID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBServiceLinePlanPH] ([MemberGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Name] ON [ob].[DimOBServiceLinePlanPH] ([Name]); +GO +ALTER TABLE [ob].[DimOBServiceLinePlanPH] ADD CONSTRAINT [DF__DimOBServi__Name__41262194] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[DimOBServiceLinePlanPH] ADD CONSTRAINT [DF__DimOBServ__Membe__421A45CD] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [ob].[DimOBServiceLinePlanPH] ADD CONSTRAINT [DF__DimOBServ__Trans__44028E3F] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[DimOBServiceLinePlanPH] ADD CONSTRAINT [DF__DimOBServ__Histo__430E6A06] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimOBSnapshot ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimOBSnapshot] ( + [OBSnapshotID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [Category] nvarchar(100) NOT NULL, + [Date] nvarchar(100) NOT NULL, + PRIMARY KEY ([OBSnapshotID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimOBSnapshot] ([MemberGUID]); +CREATE UNIQUE NONCLUSTERED INDEX [UK_DimOBSnapshot_CategoryName] ON [ob].[DimOBSnapshot] ([Category], [Name]); +GO +ALTER TABLE [ob].[DimOBSnapshot] ADD CONSTRAINT [DF__DimOBSnap__Histo__6CE96C4B] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[DimOBSnapshot] ADD CONSTRAINT [DF__DimOBSnaps__Name__6B0123D9] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[DimOBSnapshot] ADD CONSTRAINT [DF__DimOBSnap__Membe__6BF54812] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [ob].[DimOBSnapshot] ADD CONSTRAINT [DF__DimOBSnap__Trans__6DDD9084] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[DimOBSnapshot] ADD CONSTRAINT [DF__DimOBSnap__Categ__6ED1B4BD] DEFAULT ('Auto') FOR [Category]; GO +ALTER TABLE [ob].[DimOBSnapshot] ADD CONSTRAINT [DF__DimOBSnaps__Date__6FC5D8F6] DEFAULT ('') FOR [Date]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.DimSpread ------------------ +--------------------------------------------- +CREATE TABLE [ob].[DimSpread] ( + [SpreadID] int NOT NULL, + [Name] nvarchar(200) NOT NULL, + [MemberGUID] uniqueidentifier NOT NULL, + [TransactionID] int NOT NULL, + [IsBuiltIn] bit NOT NULL, + [SortOrder] int NOT NULL, + [Category] nvarchar(100) NOT NULL, + PRIMARY KEY ([SpreadID]) +); + +CREATE NONCLUSTERED INDEX [NUNC_MemberGUID] ON [ob].[DimSpread] ([MemberGUID]); +GO +ALTER TABLE [ob].[DimSpread] ADD CONSTRAINT [DF__OB_DimSpread_TransactionID ] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[DimSpread] ADD CONSTRAINT [DF__DimSpread__Name__36DD39B7] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[DimSpread] ADD CONSTRAINT [DF__DimSpread__Membe__37D15DF0] DEFAULT (newid()) FOR [MemberGUID]; GO +ALTER TABLE [ob].[DimSpread] ADD CONSTRAINT [DF_DimSpread_Category] DEFAULT ('') FOR [Category]; GO +ALTER TABLE [ob].[DimSpread] ADD CONSTRAINT [DF__DimSpread__IsBui__7A6BEDED] DEFAULT ((0)) FOR [IsBuiltIn]; GO +ALTER TABLE [ob].[DimSpread] ADD CONSTRAINT [DF__DimSpread__SortO__7B601226] DEFAULT ((0)) FOR [SortOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactAccountSnapshot ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactAccountSnapshot] ( + [RowID] int NOT NULL, + [AccountID] int NOT NULL, + [DataTypeID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [DepartmentalBudgetID] int NOT NULL, + [OBSnapshotID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [Month01] decimal NOT NULL, + [Month02] decimal NOT NULL, + [Month03] decimal NOT NULL, + [Month04] decimal NOT NULL, + [Month05] decimal NOT NULL, + [Month06] decimal NOT NULL, + [Month07] decimal NOT NULL, + [Month08] decimal NOT NULL, + [Month09] decimal NOT NULL, + [Month10] decimal NOT NULL, + [Month11] decimal NOT NULL, + [Month12] decimal NOT NULL, + [MonthsLoaded] int NOT NULL, + [Total] decimal NOT NULL, + [Yearly] decimal NOT NULL, + [YTD] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [ob].[FactAccountSnapshot] ([OBSnapshotID], [DepartmentalBudgetID], [FiscalYearID], [TimeClassID], [UnitTypeID], [AccountID], [IsDeleted], [DataTypeID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [ob].[FactAccountSnapshot] ([OBSnapshotID], [DepartmentalBudgetID], [FiscalYearID], [TimeClassID], [UnitTypeID], [AccountID], [IsDeleted], [DataTypeID]); +CREATE NONCLUSTERED INDEX [NCNU_DepartmentalBudget_OBSnapshotID] ON [ob].[FactAccountSnapshot] ([DepartmentalBudgetID], [OBSnapshotID]); +GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [FK__FactAccou__Accou__7672D685] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [FK__FactAccou__DataT__785B1EF7] FOREIGN KEY ([DataTypeID]) REFERENCES [fw].[DimDataType] ([DataTypeID]); GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [FK__FactAccou__Depar__7C2BAFDB] FOREIGN KEY ([DepartmentalBudgetID]) REFERENCES [ob].[DimDepartmentalBudget] ([DepartmentalBudgetID]); GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [FK__FactAccou__Fisca__7A436769] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [FK__FactAccou__OBSna__7E13F84D] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [FK__FactAccou__TimeC__01E48931] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [FK__FactAccou__UnitT__03CCD1A3] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__TimeC__00F064F8] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__UnitT__02D8AD6A] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Histo__14F75DA5] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__04C0F5DC] DEFAULT ((0)) FOR [Month01]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__05B51A15] DEFAULT ((0)) FOR [Month02]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__06A93E4E] DEFAULT ((0)) FOR [Month03]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__079D6287] DEFAULT ((0)) FOR [Month04]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__089186C0] DEFAULT ((0)) FOR [Month05]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__0985AAF9] DEFAULT ((0)) FOR [Month06]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__0A79CF32] DEFAULT ((0)) FOR [Month07]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__0B6DF36B] DEFAULT ((0)) FOR [Month08]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__0C6217A4] DEFAULT ((0)) FOR [Month09]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__0D563BDD] DEFAULT ((0)) FOR [Month10]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__0E4A6016] DEFAULT ((0)) FOR [Month11]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__0F3E844F] DEFAULT ((0)) FOR [Month12]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__1032A888] DEFAULT ((0)) FOR [MonthsLoaded]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Total__1126CCC1] DEFAULT ((0)) FOR [Total]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Yearl__121AF0FA] DEFAULT ((0)) FOR [Yearly]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccount__YTD__130F1533] DEFAULT ((0)) FOR [YTD]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__IsDel__1403396C] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Trans__15EB81DE] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__DataT__7766FABE] DEFAULT ((0)) FOR [DataTypeID]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Fisca__794F4330] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__Depar__7B378BA2] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO +ALTER TABLE [ob].[FactAccountSnapshot] ADD CONSTRAINT [DF__FactAccou__OBSna__7D1FD414] DEFAULT ((0)) FOR [OBSnapshotID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactAccountSubtableVarSnapshot ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactAccountSubtableVarSnapshot] ( + [RowID] int NOT NULL, + [AccountID] int NOT NULL, + [AdjustmentCategoryID] int NOT NULL, + [AssumptionID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [DepartmentalBudgetID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [OBSnapshotID] int NOT NULL, + [Comment] nvarchar(2000) NOT NULL, + [Comment_Comment] nvarchar(max) NOT NULL, + [Comment_Formula] nvarchar(max) NOT NULL, + [Month01] decimal NOT NULL, + [Month02] decimal NOT NULL, + [Month03] decimal NOT NULL, + [Month04] decimal NOT NULL, + [Month05] decimal NOT NULL, + [Month06] decimal NOT NULL, + [Month07] decimal NOT NULL, + [Month08] decimal NOT NULL, + [Month09] decimal NOT NULL, + [Month10] decimal NOT NULL, + [Month11] decimal NOT NULL, + [Month12] decimal NOT NULL, + [Total] decimal NULL, + [Yearly] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [FK_FactAccountSubtableVarSnapshot_OBSnapshotID] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Comme__001E04C8] DEFAULT ('') FOR [Comment_Comment]; GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Comme__01122901] DEFAULT ('d') FOR [Comment_Formula]; GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__02064D3A] DEFAULT ((0)) FOR [Month01]; GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__02FA7173] DEFAULT ((0)) FOR [Month02]; GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__03EE95AC] DEFAULT ((0)) FOR [Month03]; GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__04E2B9E5] DEFAULT ((0)) FOR [Month04]; GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__05D6DE1E] DEFAULT ((0)) FOR [Month05]; GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__06CB0257] DEFAULT ((0)) FOR [Month06]; GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__07BF2690] DEFAULT ((0)) FOR [Month07]; GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__08B34AC9] DEFAULT ((0)) FOR [Month08]; GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__09A76F02] DEFAULT ((0)) FOR [Month09]; GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__0A9B933B] DEFAULT ((0)) FOR [Month10]; GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__0B8FB774] DEFAULT ((0)) FOR [Month11]; GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Month__0C83DBAD] DEFAULT ((0)) FOR [Month12]; GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Yearl__0D77FFE6] DEFAULT ((0)) FOR [Yearly]; GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__IsDel__0E6C241F] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Trans__10546C91] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Histo__0F604858] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Fisca__7D41981D] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__OBSna__7E35BC56] DEFAULT ((0)) FOR [OBSnapshotID]; GO +ALTER TABLE [ob].[FactAccountSubtableVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Comme__7F29E08F] DEFAULT ('') FOR [Comment]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactAccountVarSnapshot ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactAccountVarSnapshot] ( + [RowID] int NOT NULL, + [AccountID] int NOT NULL, + [AssumptionID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [DepartmentalBudgetID] int NOT NULL, + [RowNumberID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [OBSnapshotID] int NOT NULL, + [Amount] decimal NOT NULL, + [Amount_Comment] nvarchar(max) NOT NULL, + [Amount_Formula] nvarchar(max) NOT NULL, + [Comment] nvarchar(2000) NOT NULL, + [Comment_Comment] nvarchar(max) NOT NULL, + [Comment_Formula] nvarchar(max) NOT NULL, + [TextValue] nvarchar(2000) NOT NULL, + [TextValue_Comment] nvarchar(max) NOT NULL, + [TextValue_Formula] nvarchar(max) NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [FK_FactAccountVarSnapshot_OBSnapshotID] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO +ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Histo__4D9284FB] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Fisca__412CAE16] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Fisca__4220D24F] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__OBSna__4314F688] DEFAULT ((0)) FOR [OBSnapshotID]; GO +ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Amoun__44091AC1] DEFAULT ((0)) FOR [Amount]; GO +ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Amoun__44FD3EFA] DEFAULT ('') FOR [Amount_Comment]; GO +ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Amoun__45F16333] DEFAULT ('d') FOR [Amount_Formula]; GO +ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Comme__46E5876C] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Comme__47D9ABA5] DEFAULT ('') FOR [Comment_Comment]; GO +ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Comme__48CDCFDE] DEFAULT ('d') FOR [Comment_Formula]; GO +ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__TextV__49C1F417] DEFAULT ('') FOR [TextValue]; GO +ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__TextV__4AB61850] DEFAULT ('') FOR [TextValue_Comment]; GO +ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__TextV__4BAA3C89] DEFAULT ('d') FOR [TextValue_Formula]; GO +ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__IsDel__4C9E60C2] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[FactAccountVarSnapshot] ADD CONSTRAINT [DF__FactAccou__Trans__4E86A934] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactAssumptionByAccount ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactAssumptionByAccount] ( + [RowID] int NOT NULL, + [GlobalAssumptionGUID] uniqueidentifier NOT NULL, + [AccountID] int NOT NULL, + [Month01] decimal NULL, + [Month02] decimal NULL, + [Month03] decimal NULL, + [Month04] decimal NULL, + [Month05] decimal NULL, + [Month06] decimal NULL, + [Month07] decimal NULL, + [Month08] decimal NULL, + [Month09] decimal NULL, + [Month10] decimal NULL, + [Month11] decimal NULL, + [Month12] decimal NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [ob].[FactAssumptionByAccount] ADD CONSTRAINT [FK_FactAssumptionByAccount_GlobalAssumption] FOREIGN KEY ([GlobalAssumptionGUID]) REFERENCES [dbo].[GlobalAssumption] ([GlobalAssumptionGUID]); GO +ALTER TABLE [ob].[FactAssumptionByAccount] ADD CONSTRAINT [DF_FactAssumptionByAccount_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionGUID]; GO +ALTER TABLE [ob].[FactAssumptionByAccount] ADD CONSTRAINT [DF_FactAssumptionByAccount_AccountID] DEFAULT ((0)) FOR [AccountID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactAssumptionByAccountFRLineNameDetail ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactAssumptionByAccountFRLineNameDetail] ( + [RowID] int NOT NULL, + [GlobalAssumptionGUID] uniqueidentifier NOT NULL, + [FinancialReportingID] int NOT NULL, + [AccountID] int NOT NULL, + [Month01] decimal NULL, + [Month02] decimal NULL, + [Month03] decimal NULL, + [Month04] decimal NULL, + [Month05] decimal NULL, + [Month06] decimal NULL, + [Month07] decimal NULL, + [Month08] decimal NULL, + [Month09] decimal NULL, + [Month10] decimal NULL, + [Month11] decimal NULL, + [Month12] decimal NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [ob].[FactAssumptionByAccountFRLineNameDetail] ADD CONSTRAINT [FK_FactAssumptionByAccountFRLineNameDetail_GlobalAssumption] FOREIGN KEY ([GlobalAssumptionGUID]) REFERENCES [dbo].[GlobalAssumption] ([GlobalAssumptionGUID]); GO +ALTER TABLE [ob].[FactAssumptionByAccountFRLineNameDetail] ADD CONSTRAINT [DF_FactAssumptionByAccountFRLineNameDetail_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionGUID]; GO +ALTER TABLE [ob].[FactAssumptionByAccountFRLineNameDetail] ADD CONSTRAINT [DF_FactAssumptionByAccountFRLineNameDetail_FinancialReportingID] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [ob].[FactAssumptionByAccountFRLineNameDetail] ADD CONSTRAINT [DF_FactAssumptionByAccountFRLineNameDetail_AccountID] DEFAULT ((0)) FOR [AccountID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactAssumptionByAccountFRLineNameRollup ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactAssumptionByAccountFRLineNameRollup] ( + [RowID] int NOT NULL, + [GlobalAssumptionGUID] uniqueidentifier NOT NULL, + [PHSectionGUID] uniqueidentifier NOT NULL, + [FinancialReportingID] int NOT NULL, + [Month01] decimal NULL, + [Month02] decimal NULL, + [Month03] decimal NULL, + [Month04] decimal NULL, + [Month05] decimal NULL, + [Month06] decimal NULL, + [Month07] decimal NULL, + [Month08] decimal NULL, + [Month09] decimal NULL, + [Month10] decimal NULL, + [Month11] decimal NULL, + [Month12] decimal NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [ob].[FactAssumptionByAccountFRLineNameRollup] ADD CONSTRAINT [FK_FactAssumptionByAccountFRLineNameRollup_GlobalAssumption] FOREIGN KEY ([GlobalAssumptionGUID]) REFERENCES [dbo].[GlobalAssumption] ([GlobalAssumptionGUID]); GO +ALTER TABLE [ob].[FactAssumptionByAccountFRLineNameRollup] ADD CONSTRAINT [DF_FactAssumptionByAccountFRLineNameRollup_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionGUID]; GO +ALTER TABLE [ob].[FactAssumptionByAccountFRLineNameRollup] ADD CONSTRAINT [DF_FactAssumptionByAccountFRLineNameRollup_PHSectionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PHSectionGUID]; GO +ALTER TABLE [ob].[FactAssumptionByAccountFRLineNameRollup] ADD CONSTRAINT [DF_FactAssumptionByAccountFRLineNameRollup_FinancialReportingID] DEFAULT ((0)) FOR [FinancialReportingID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactAssumptionByChargeCode ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactAssumptionByChargeCode] ( + [RowID] int NOT NULL, + [GlobalAssumptionGUID] uniqueidentifier NOT NULL, + [ChargeCodeID] int NOT NULL, + [Month01] decimal NULL, + [Month02] decimal NULL, + [Month03] decimal NULL, + [Month04] decimal NULL, + [Month05] decimal NULL, + [Month06] decimal NULL, + [Month07] decimal NULL, + [Month08] decimal NULL, + [Month09] decimal NULL, + [Month10] decimal NULL, + [Month11] decimal NULL, + [Month12] decimal NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [ob].[FactAssumptionByChargeCode] ADD CONSTRAINT [FK_FactAssumptionByChargeCode_GlobalAssumption] FOREIGN KEY ([GlobalAssumptionGUID]) REFERENCES [dbo].[GlobalAssumption] ([GlobalAssumptionGUID]); GO +ALTER TABLE [ob].[FactAssumptionByChargeCode] ADD CONSTRAINT [DF_FactAssumptionByChargeCode_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionGUID]; GO +ALTER TABLE [ob].[FactAssumptionByChargeCode] ADD CONSTRAINT [DF_FactAssumptionByChargeCode_ChargeCodeID] DEFAULT ((0)) FOR [ChargeCodeID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactAssumptionByChargeCodeRollup ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactAssumptionByChargeCodeRollup] ( + [RowID] int NOT NULL, + [GlobalAssumptionGUID] uniqueidentifier NOT NULL, + [PHSectionGUID] uniqueidentifier NOT NULL, + [Month01] decimal NULL, + [Month02] decimal NULL, + [Month03] decimal NULL, + [Month04] decimal NULL, + [Month05] decimal NULL, + [Month06] decimal NULL, + [Month07] decimal NULL, + [Month08] decimal NULL, + [Month09] decimal NULL, + [Month10] decimal NULL, + [Month11] decimal NULL, + [Month12] decimal NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [ob].[FactAssumptionByChargeCodeRollup] ADD CONSTRAINT [FK_FactAssumptionByChargeCodeRollup_GlobalAssumption] FOREIGN KEY ([GlobalAssumptionGUID]) REFERENCES [dbo].[GlobalAssumption] ([GlobalAssumptionGUID]); GO +ALTER TABLE [ob].[FactAssumptionByChargeCodeRollup] ADD CONSTRAINT [DF_FactAssumptionByChargeCodeRollup_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionGUID]; GO +ALTER TABLE [ob].[FactAssumptionByChargeCodeRollup] ADD CONSTRAINT [DF_FactAssumptionByChargeCodeRollup_PHSectionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PHSectionGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactAssumptionByJobCode ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactAssumptionByJobCode] ( + [RowID] int NOT NULL, + [GlobalAssumptionGUID] uniqueidentifier NOT NULL, + [JobCodeGroupID] int NOT NULL, + [JobCodeID] int NOT NULL, + [Month01] decimal NULL, + [Month02] decimal NULL, + [Month03] decimal NULL, + [Month04] decimal NULL, + [Month05] decimal NULL, + [Month06] decimal NULL, + [Month07] decimal NULL, + [Month08] decimal NULL, + [Month09] decimal NULL, + [Month10] decimal NULL, + [Month11] decimal NULL, + [Month12] decimal NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [ob].[FactAssumptionByJobCode] ADD CONSTRAINT [FK_FactAssumptionByJobCode_GlobalAssumption] FOREIGN KEY ([GlobalAssumptionGUID]) REFERENCES [dbo].[GlobalAssumption] ([GlobalAssumptionGUID]); GO +ALTER TABLE [ob].[FactAssumptionByJobCode] ADD CONSTRAINT [DF_FactAssumptionByJobCode_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionGUID]; GO +ALTER TABLE [ob].[FactAssumptionByJobCode] ADD CONSTRAINT [DF_FactAssumptionByJobCode_JobCodeGroupID] DEFAULT ((0)) FOR [JobCodeGroupID]; GO +ALTER TABLE [ob].[FactAssumptionByJobCode] ADD CONSTRAINT [DF_FactAssumptionByJobCode_JobCodeID] DEFAULT ((0)) FOR [JobCodeID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactAssumptionByJobCodeGroup ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactAssumptionByJobCodeGroup] ( + [RowID] int NOT NULL, + [GlobalAssumptionGUID] uniqueidentifier NOT NULL, + [PHSectionGUID] uniqueidentifier NOT NULL, + [JobCodeGroupID] int NOT NULL, + [Month01] decimal NULL, + [Month02] decimal NULL, + [Month03] decimal NULL, + [Month04] decimal NULL, + [Month05] decimal NULL, + [Month06] decimal NULL, + [Month07] decimal NULL, + [Month08] decimal NULL, + [Month09] decimal NULL, + [Month10] decimal NULL, + [Month11] decimal NULL, + [Month12] decimal NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [ob].[FactAssumptionByJobCodeGroup] ADD CONSTRAINT [FK_FactAssumptionByJobCodeGroup_GlobalAssumption] FOREIGN KEY ([GlobalAssumptionGUID]) REFERENCES [dbo].[GlobalAssumption] ([GlobalAssumptionGUID]); GO +ALTER TABLE [ob].[FactAssumptionByJobCodeGroup] ADD CONSTRAINT [DF_FactAssumptionByJobCodeGroup_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionGUID]; GO +ALTER TABLE [ob].[FactAssumptionByJobCodeGroup] ADD CONSTRAINT [DF_FactAssumptionByJobCodeGroup_PHSectionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PHSectionGUID]; GO +ALTER TABLE [ob].[FactAssumptionByJobCodeGroup] ADD CONSTRAINT [DF_FactAssumptionByJobCodeGroup_JobCodeGroupID] DEFAULT ((0)) FOR [JobCodeGroupID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactAssumptionByPHSection ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactAssumptionByPHSection] ( + [RowID] int NOT NULL, + [GlobalAssumptionGUID] uniqueidentifier NOT NULL, + [PHSectionGUID] uniqueidentifier NOT NULL, + [Month01] decimal NULL, + [Month02] decimal NULL, + [Month03] decimal NULL, + [Month04] decimal NULL, + [Month05] decimal NULL, + [Month06] decimal NULL, + [Month07] decimal NULL, + [Month08] decimal NULL, + [Month09] decimal NULL, + [Month10] decimal NULL, + [Month11] decimal NULL, + [Month12] decimal NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [ob].[FactAssumptionByPHSection] ADD CONSTRAINT [FK_FactAssumptionByPHSection_GlobalAssumption] FOREIGN KEY ([GlobalAssumptionGUID]) REFERENCES [dbo].[GlobalAssumption] ([GlobalAssumptionGUID]); GO +ALTER TABLE [ob].[FactAssumptionByPHSection] ADD CONSTRAINT [DF_FactAssumptionByPHSection_GlobalAssumptionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [GlobalAssumptionGUID]; GO +ALTER TABLE [ob].[FactAssumptionByPHSection] ADD CONSTRAINT [DF_FactAssumptionByPHSection_PHSectionGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [PHSectionGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactCDMSnapshot ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactCDMSnapshot] ( + [RowID] int NOT NULL, + [OBSnapshotID] int NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [ChargeCodeID] int NOT NULL, + [DataTypeID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [DepartmentalBudgetID] int NOT NULL, + [OBForecastDetailID] int NOT NULL, + [PatientClassID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Month01] decimal NOT NULL, + [Month02] decimal NOT NULL, + [Month03] decimal NOT NULL, + [Month04] decimal NOT NULL, + [Month05] decimal NOT NULL, + [Month06] decimal NOT NULL, + [Month07] decimal NOT NULL, + [Month08] decimal NOT NULL, + [Month09] decimal NOT NULL, + [Month10] decimal NOT NULL, + [Month11] decimal NOT NULL, + [Month12] decimal NOT NULL, + [Yearly] decimal NOT NULL, + [YTD] decimal NOT NULL, + [Total] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [ob].[FactCDMSnapshot] ([OBSnapshotID], [DepartmentalBudgetID], [FiscalYearID], [TimeClassID], [PatientClassID], [UnitTypeID], [ChargeCodeID], [OBForecastDetailID], [IsDeleted], [DataTypeID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [ob].[FactCDMSnapshot] ([OBSnapshotID], [DepartmentalBudgetID], [FiscalYearID], [TimeClassID], [PatientClassID], [UnitTypeID], [ChargeCodeID], [OBForecastDetailID], [IsDeleted], [DataTypeID]); +GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [FK__FactCDMSn__Charg__2C6FBFDA] FOREIGN KEY ([ChargeCodeID]) REFERENCES [fw].[DimChargeCode] ([ChargeCodeID]); GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [FK__FactCDMSn__DataT__2E58084C] FOREIGN KEY ([DataTypeID]) REFERENCES [fw].[DimDataType] ([DataTypeID]); GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [FK__FactCDMSn__Depar__32289930] FOREIGN KEY ([DepartmentalBudgetID]) REFERENCES [ob].[DimDepartmentalBudget] ([DepartmentalBudgetID]); GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [FK__FactCDMSn__Fisca__304050BE] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [FK__FactCDMSn__OBFor__3410E1A2] FOREIGN KEY ([OBForecastDetailID]) REFERENCES [ob].[DimOBForecastDetail] ([OBForecastDetailID]); GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [FK__FactCDMSn__OBSna__289F2EF6] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [FK__FactCDMSn__Patie__35F92A14] FOREIGN KEY ([PatientClassID]) REFERENCES [fw].[DimPatientClass] ([PatientClassID]); GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [FK__FactCDMSn__TimeC__37E17286] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [FK__FactCDMSn__UnitT__2A877768] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__OBSna__27AB0ABD] DEFAULT ((0)) FOR [OBSnapshotID]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__UnitT__2993532F] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Charg__2B7B9BA1] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__DataT__2D63E413] DEFAULT ((0)) FOR [DataTypeID]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Fisca__2F4C2C85] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Depar__313474F7] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__OBFor__331CBD69] DEFAULT ((0)) FOR [OBForecastDetailID]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Patie__350505DB] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__TimeC__36ED4E4D] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__38D596BF] DEFAULT ((0)) FOR [Month01]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__39C9BAF8] DEFAULT ((0)) FOR [Month02]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__3ABDDF31] DEFAULT ((0)) FOR [Month03]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__3BB2036A] DEFAULT ((0)) FOR [Month04]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__3CA627A3] DEFAULT ((0)) FOR [Month05]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__3D9A4BDC] DEFAULT ((0)) FOR [Month06]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__3E8E7015] DEFAULT ((0)) FOR [Month07]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__3F82944E] DEFAULT ((0)) FOR [Month08]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__4076B887] DEFAULT ((0)) FOR [Month09]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__416ADCC0] DEFAULT ((0)) FOR [Month10]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__425F00F9] DEFAULT ((0)) FOR [Month11]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Month__43532532] DEFAULT ((0)) FOR [Month12]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Yearl__4447496B] DEFAULT ((0)) FOR [Yearly]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSnap__YTD__453B6DA4] DEFAULT ((0)) FOR [YTD]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Total__462F91DD] DEFAULT ((0)) FOR [Total]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__IsDel__4723B616] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Trans__490BFE88] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[FactCDMSnapshot] ADD CONSTRAINT [DF__FactCDMSn__Histo__4817DA4F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactCDMVarSnapshot ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactCDMVarSnapshot] ( + [RowID] int NOT NULL, + [AssumptionID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [DataTypeID] tinyint NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [DepartmentalBudgetID] int NOT NULL, + [OBForecastDetailID] int NOT NULL, + [PatientClassID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [OBSnapshotID] int NOT NULL, + [Amount] decimal NOT NULL, + [Amount_Comment] nvarchar(max) NOT NULL, + [Amount_Formula] nvarchar(max) NOT NULL, + [Comment] nvarchar(2000) NOT NULL, + [TextValue] nvarchar(2000) NOT NULL, + [TextValue_Comment] nvarchar(max) NOT NULL, + [TextValue_Formula] nvarchar(max) NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [FK_FactCDMVarSnapshot_OBSnapshotID] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO +ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__Fisca__516315DF] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__Fisca__52573A18] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__OBSna__534B5E51] DEFAULT ((0)) FOR [OBSnapshotID]; GO +ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__Amoun__543F828A] DEFAULT ((0)) FOR [Amount]; GO +ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__Amoun__5533A6C3] DEFAULT ('') FOR [Amount_Comment]; GO +ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__Amoun__5627CAFC] DEFAULT ('d') FOR [Amount_Formula]; GO +ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__Comme__571BEF35] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__TextV__5810136E] DEFAULT ('') FOR [TextValue]; GO +ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__TextV__590437A7] DEFAULT ('') FOR [TextValue_Comment]; GO +ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__TextV__59F85BE0] DEFAULT ('d') FOR [TextValue_Formula]; GO +ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__IsDel__5AEC8019] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__Trans__5CD4C88B] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[FactCDMVarSnapshot] ADD CONSTRAINT [DF__FactCDMVa__Histo__5BE0A452] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactDepartmentBudgetExceptions ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactDepartmentBudgetExceptions] ( + [RowID] int NOT NULL, + [DepartmentalBudgetID] int NOT NULL, + [OBExceptionsID] int NOT NULL, + [Detail] nvarchar(2000) NOT NULL, + [Acknowledged] bit NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [ob].[FactDepartmentBudgetExceptions] ADD CONSTRAINT [FK__FactDepar__Depar__761D0573] FOREIGN KEY ([DepartmentalBudgetID]) REFERENCES [ob].[DimDepartmentalBudget] ([DepartmentalBudgetID]); GO +ALTER TABLE [ob].[FactDepartmentBudgetExceptions] ADD CONSTRAINT [FK__FactDepar__OBExc__78054DE5] FOREIGN KEY ([OBExceptionsID]) REFERENCES [ob].[DimOBExceptions] ([OBExceptionsID]); GO +ALTER TABLE [ob].[FactDepartmentBudgetExceptions] ADD CONSTRAINT [DF__FactDepar__Histo__7BD5DEC9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[FactDepartmentBudgetExceptions] ADD CONSTRAINT [DF__FactDepar__Depar__7528E13A] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO +ALTER TABLE [ob].[FactDepartmentBudgetExceptions] ADD CONSTRAINT [DF__FactDepar__OBExc__771129AC] DEFAULT ((0)) FOR [OBExceptionsID]; GO +ALTER TABLE [ob].[FactDepartmentBudgetExceptions] ADD CONSTRAINT [DF__FactDepar__Detai__78F9721E] DEFAULT ('') FOR [Detail]; GO +ALTER TABLE [ob].[FactDepartmentBudgetExceptions] ADD CONSTRAINT [DF__FactDepar__Ackno__79ED9657] DEFAULT ((0)) FOR [Acknowledged]; GO +ALTER TABLE [ob].[FactDepartmentBudgetExceptions] ADD CONSTRAINT [DF__FactDepar__IsDel__7AE1BA90] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[FactDepartmentBudgetExceptions] ADD CONSTRAINT [DF__FactDepar__Trans__7CCA0302] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactDepartmentPrimaryStatisticConfigurationSubTableMap ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] ( + [RowID] int NOT NULL, + [DepartmentalBudgetPHID] tinyint NOT NULL, + [AccountPHID] int NOT NULL, + [RowExpanded] int NOT NULL, + [CellGUID] uniqueidentifier NOT NULL, + [MeasureGUID] uniqueidentifier NOT NULL, + [IsUserMapped] bit NOT NULL, + [OBDepartmentalBudgetPHIndex] int NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + [OBAccountPHIndex] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] ([IsDeleted], [AccountPHID], [OBAccountPHIndex], [DepartmentalBudgetPHID], [OBDepartmentalBudgetPHIndex], [RowID]); +GO +ALTER TABLE [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] ADD CONSTRAINT [DF__FactDepar__Histo__656E6F02] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] ADD CONSTRAINT [DF__FactDepar__OBAcc__0E3B7A6B] DEFAULT ((0)) FOR [OBAccountPHIndex]; GO +ALTER TABLE [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] ADD CONSTRAINT [DF__FactDepar__CellG__5FB595AC] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CellGUID]; GO +ALTER TABLE [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] ADD CONSTRAINT [DF__FactDepar__Measu__60A9B9E5] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [MeasureGUID]; GO +ALTER TABLE [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] ADD CONSTRAINT [DF__FactDepar__RowEx__5EC17173] DEFAULT ((0)) FOR [RowExpanded]; GO +ALTER TABLE [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] ADD CONSTRAINT [DF__FactDepar__IsUse__619DDE1E] DEFAULT ((1)) FOR [IsUserMapped]; GO +ALTER TABLE [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] ADD CONSTRAINT [DF__FactDepar__OBDep__62920257] DEFAULT ((0)) FOR [OBDepartmentalBudgetPHIndex]; GO +ALTER TABLE [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] ADD CONSTRAINT [DF__FactDepar__IsDel__647A4AC9] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[FactDepartmentPrimaryStatisticConfigurationSubTableMap] ADD CONSTRAINT [DF__FactDepar__Trans__6662933B] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactGlobalStatisticExceptions ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactGlobalStatisticExceptions] ( + [RowID] int NOT NULL, + [OBGlobalStatisticsPlanID] int NOT NULL, + [OBExceptionsID] int NOT NULL, + [Acknowledged] bit NOT NULL, + [Detail] nvarchar(2000) NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [ob].[FactGlobalStatisticExceptions] ADD CONSTRAINT [FK__FactGloba__OBExc__0B1C1B0C] FOREIGN KEY ([OBExceptionsID]) REFERENCES [ob].[DimOBExceptions] ([OBExceptionsID]); GO +ALTER TABLE [ob].[FactGlobalStatisticExceptions] ADD CONSTRAINT [FK__FactGloba__OBGlo__0933D29A] FOREIGN KEY ([OBGlobalStatisticsPlanID]) REFERENCES [ob].[DimOBGlobalStatisticsPlan] ([OBGlobalStatisticsPlanID]); GO +ALTER TABLE [ob].[FactGlobalStatisticExceptions] ADD CONSTRAINT [DF__FactGloba__OBGlo__083FAE61] DEFAULT ((0)) FOR [OBGlobalStatisticsPlanID]; GO +ALTER TABLE [ob].[FactGlobalStatisticExceptions] ADD CONSTRAINT [DF__FactGloba__OBExc__0A27F6D3] DEFAULT ((0)) FOR [OBExceptionsID]; GO +ALTER TABLE [ob].[FactGlobalStatisticExceptions] ADD CONSTRAINT [DF__FactGloba__Ackno__0C103F45] DEFAULT ((0)) FOR [Acknowledged]; GO +ALTER TABLE [ob].[FactGlobalStatisticExceptions] ADD CONSTRAINT [DF__FactGloba__Detai__0D04637E] DEFAULT ('') FOR [Detail]; GO +ALTER TABLE [ob].[FactGlobalStatisticExceptions] ADD CONSTRAINT [DF__FactGloba__IsDel__0DF887B7] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[FactGlobalStatisticExceptions] ADD CONSTRAINT [DF__FactGloba__Trans__0FE0D029] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[FactGlobalStatisticExceptions] ADD CONSTRAINT [DF__FactGloba__Histo__0EECABF0] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactGlobalStatisticsLink ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactGlobalStatisticsLink] ( + [RowID] int NOT NULL, + [DepartmentalBudgetID] int NOT NULL, + [OBGlobalStatisticsPlanID] int NOT NULL, + [IsDeleted] bit NOT NULL, + [Version] timestamp NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [ob].[FactGlobalStatisticsLink] ADD CONSTRAINT [DF_FactGlobalStatisticsLink_DepartmentalBudgetID] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO +ALTER TABLE [ob].[FactGlobalStatisticsLink] ADD CONSTRAINT [DF_FactGlobalStatisticsLink_OBGlobalStatisticsPlanID] DEFAULT ((0)) FOR [OBGlobalStatisticsPlanID]; GO +ALTER TABLE [ob].[FactGlobalStatisticsLink] ADD CONSTRAINT [DF_FactGlobalStatisticsLink_IsDeleted] DEFAULT ((0)) FOR [IsDeleted]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactGlobalStatisticsSnapshot ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactGlobalStatisticsSnapshot] ( + [RowID] int NOT NULL, + [DataTypeID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [OBGlobalStatisticID] int NOT NULL, + [OBGlobalStatisticsPlanID] int NOT NULL, + [OBSnapshotID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [Month01] decimal NOT NULL, + [Month02] decimal NOT NULL, + [Month03] decimal NOT NULL, + [Month04] decimal NOT NULL, + [Month05] decimal NOT NULL, + [Month06] decimal NOT NULL, + [Month07] decimal NOT NULL, + [Month08] decimal NOT NULL, + [Month09] decimal NOT NULL, + [Month10] decimal NOT NULL, + [Month11] decimal NOT NULL, + [Month12] decimal NOT NULL, + [MonthsLoaded] int NOT NULL, + [Total] decimal NOT NULL, + [Yearly] decimal NOT NULL, + [YTD] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [ob].[FactGlobalStatisticsSnapshot] ([OBSnapshotID], [OBGlobalStatisticsPlanID], [FiscalYearID], [TimeClassID], [OBGlobalStatisticID], [UnitTypeID], [IsDeleted], [DataTypeID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [ob].[FactGlobalStatisticsSnapshot] ([OBSnapshotID], [OBGlobalStatisticsPlanID], [FiscalYearID], [TimeClassID], [OBGlobalStatisticID], [UnitTypeID], [IsDeleted], [DataTypeID]); +GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [FK__FactGloba__DataT__19BC12C2] FOREIGN KEY ([DataTypeID]) REFERENCES [fw].[DimDataType] ([DataTypeID]); GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [FK__FactGloba__Fisca__1BA45B34] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [FK__FactGloba__OBGlo__1D8CA3A6] FOREIGN KEY ([OBGlobalStatisticID]) REFERENCES [ob].[DimOBGlobalStatistics] ([OBGlobalStatisticID]); GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [FK__FactGloba__OBGlo__1F74EC18] FOREIGN KEY ([OBGlobalStatisticsPlanID]) REFERENCES [ob].[DimOBGlobalStatisticsPlan] ([OBGlobalStatisticsPlanID]); GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [FK__FactGloba__OBSna__215D348A] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [FK__FactGloba__TimeC__23457CFC] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [FK__FactGloba__UnitT__252DC56E] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__DataT__18C7EE89] DEFAULT ((0)) FOR [DataTypeID]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Fisca__1AB036FB] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__OBGlo__1C987F6D] DEFAULT ((0)) FOR [OBGlobalStatisticID]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__OBGlo__1E80C7DF] DEFAULT ((0)) FOR [OBGlobalStatisticsPlanID]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__OBSna__20691051] DEFAULT ((0)) FOR [OBSnapshotID]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__TimeC__225158C3] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__UnitT__2439A135] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__2621E9A7] DEFAULT ((0)) FOR [Month01]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__27160DE0] DEFAULT ((0)) FOR [Month02]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__280A3219] DEFAULT ((0)) FOR [Month03]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Histo__36585170] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__28FE5652] DEFAULT ((0)) FOR [Month04]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__29F27A8B] DEFAULT ((0)) FOR [Month05]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__2AE69EC4] DEFAULT ((0)) FOR [Month06]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__2BDAC2FD] DEFAULT ((0)) FOR [Month07]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__2CCEE736] DEFAULT ((0)) FOR [Month08]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__2DC30B6F] DEFAULT ((0)) FOR [Month09]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__2EB72FA8] DEFAULT ((0)) FOR [Month10]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__2FAB53E1] DEFAULT ((0)) FOR [Month11]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__309F781A] DEFAULT ((0)) FOR [Month12]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Month__31939C53] DEFAULT ((0)) FOR [MonthsLoaded]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Total__3287C08C] DEFAULT ((0)) FOR [Total]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Yearl__337BE4C5] DEFAULT ((0)) FOR [Yearly]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGlobalS__YTD__347008FE] DEFAULT ((0)) FOR [YTD]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__IsDel__35642D37] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[FactGlobalStatisticsSnapshot] ADD CONSTRAINT [DF__FactGloba__Trans__374C75A9] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactProviderSnapshot ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactProviderSnapshot] ( + [RowID] int NOT NULL, + [OBSnapshotID] int NOT NULL, + [DataTypeID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [DepartmentalBudgetID] int NOT NULL, + [OBForecastDetailID] int NOT NULL, + [ProviderID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [Month01] decimal NOT NULL, + [Month02] decimal NOT NULL, + [Month03] decimal NOT NULL, + [Month04] decimal NOT NULL, + [Month05] decimal NOT NULL, + [Month06] decimal NOT NULL, + [Month07] decimal NOT NULL, + [Month08] decimal NOT NULL, + [Month09] decimal NOT NULL, + [Month10] decimal NOT NULL, + [Month11] decimal NOT NULL, + [Month12] decimal NOT NULL, + [Yearly] decimal NOT NULL, + [Total] decimal NOT NULL, + [YTD] decimal NOT NULL, + [MonthsLoaded] int NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [ob].[FactProviderSnapshot] ([OBSnapshotID], [DepartmentalBudgetID], [FiscalYearID], [TimeClassID], [ProviderID], [OBForecastDetailID], [UnitTypeID], [IsDeleted], [DataTypeID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [ob].[FactProviderSnapshot] ([OBSnapshotID], [DepartmentalBudgetID], [FiscalYearID], [TimeClassID], [ProviderID], [OBForecastDetailID], [UnitTypeID], [IsDeleted], [DataTypeID]); +GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [FK__FactProvi__DataT__4EC4D7DE] FOREIGN KEY ([DataTypeID]) REFERENCES [fw].[DimDataType] ([DataTypeID]); GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [FK__FactProvi__Depar__529568C2] FOREIGN KEY ([DepartmentalBudgetID]) REFERENCES [ob].[DimDepartmentalBudget] ([DepartmentalBudgetID]); GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [FK__FactProvi__Fisca__50AD2050] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [FK__FactProvi__OBFor__547DB134] FOREIGN KEY ([OBForecastDetailID]) REFERENCES [ob].[DimOBForecastDetail] ([OBForecastDetailID]); GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [FK__FactProvi__OBSna__4CDC8F6C] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [FK__FactProvi__Provi__5665F9A6] FOREIGN KEY ([ProviderID]) REFERENCES [fw].[DimProvider] ([ProviderID]); GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [FK__FactProvi__TimeC__584E4218] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [FK__FactProvi__UnitT__5A368A8A] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__OBSna__4BE86B33] DEFAULT ((0)) FOR [OBSnapshotID]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__DataT__4DD0B3A5] DEFAULT ((0)) FOR [DataTypeID]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Fisca__4FB8FC17] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Depar__51A14489] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__OBFor__53898CFB] DEFAULT ((0)) FOR [OBForecastDetailID]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Provi__5571D56D] DEFAULT ((0)) FOR [ProviderID]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__TimeC__575A1DDF] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__UnitT__59426651] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__5B2AAEC3] DEFAULT ((0)) FOR [Month01]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__5C1ED2FC] DEFAULT ((0)) FOR [Month02]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__5D12F735] DEFAULT ((0)) FOR [Month03]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__5E071B6E] DEFAULT ((0)) FOR [Month04]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__5EFB3FA7] DEFAULT ((0)) FOR [Month05]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__5FEF63E0] DEFAULT ((0)) FOR [Month06]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__60E38819] DEFAULT ((0)) FOR [Month07]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__61D7AC52] DEFAULT ((0)) FOR [Month08]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__62CBD08B] DEFAULT ((0)) FOR [Month09]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__63BFF4C4] DEFAULT ((0)) FOR [Month10]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__64B418FD] DEFAULT ((0)) FOR [Month11]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__65A83D36] DEFAULT ((0)) FOR [Month12]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Yearl__669C616F] DEFAULT ((0)) FOR [Yearly]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Histo__6B61168C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Total__679085A8] DEFAULT ((0)) FOR [Total]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvide__YTD__6884A9E1] DEFAULT ((0)) FOR [YTD]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Month__6978CE1A] DEFAULT ((0)) FOR [MonthsLoaded]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__IsDel__6A6CF253] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[FactProviderSnapshot] ADD CONSTRAINT [DF__FactProvi__Trans__6C553AC5] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactProviderVarSnapshot ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactProviderVarSnapshot] ( + [RowID] int NOT NULL, + [AssumptionID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [DepartmentalBudgetID] int NOT NULL, + [OBForecastDetailID] int NOT NULL, + [ProviderID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [OBSnapshotID] int NOT NULL, + [Amount] decimal NOT NULL, + [Amount_Comment] nvarchar(max) NOT NULL, + [Amount_Formula] nvarchar(max) NOT NULL, + [TextValue] nvarchar(2000) NOT NULL, + [TextValue_Comment] nvarchar(max) NOT NULL, + [TextValue_Formula] nvarchar(max) NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [FK_FactProviderVarSnapshot_OBSnapshotID] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO +ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__Histo__693A9F70] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__Fisca__5FB13536] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__Fisca__60A5596F] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__OBSna__61997DA8] DEFAULT ((0)) FOR [OBSnapshotID]; GO +ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__Amoun__628DA1E1] DEFAULT ((0)) FOR [Amount]; GO +ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__Amoun__6381C61A] DEFAULT ('') FOR [Amount_Comment]; GO +ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__Amoun__6475EA53] DEFAULT ('d') FOR [Amount_Formula]; GO +ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__TextV__656A0E8C] DEFAULT ('') FOR [TextValue]; GO +ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__TextV__665E32C5] DEFAULT ('') FOR [TextValue_Comment]; GO +ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__TextV__675256FE] DEFAULT ('d') FOR [TextValue_Formula]; GO +ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__IsDel__68467B37] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[FactProviderVarSnapshot] ADD CONSTRAINT [DF__FactProvi__Trans__6A2EC3A9] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactReimbursementAccountSnapshot ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactReimbursementAccountSnapshot] ( + [RowID] int NOT NULL, + [OBSnapshotID] int NOT NULL, + [AccountID] int NOT NULL, + [DataTypeID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [OBReimbursementPlanID] int NOT NULL, + [PatientReimbursementGroupID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [Month01] decimal NOT NULL, + [Month02] decimal NOT NULL, + [Month03] decimal NOT NULL, + [Month04] decimal NOT NULL, + [Month05] decimal NOT NULL, + [Month06] decimal NOT NULL, + [Month07] decimal NOT NULL, + [Month08] decimal NOT NULL, + [Month09] decimal NOT NULL, + [Month10] decimal NOT NULL, + [Month11] decimal NOT NULL, + [Month12] decimal NOT NULL, + [YTD] decimal NOT NULL, + [Yearly] decimal NOT NULL, + [Total] decimal NOT NULL, + [MonthsLoaded] int NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [ob].[FactReimbursementAccountSnapshot] ([OBSnapshotID], [OBReimbursementPlanID], [FiscalYearID], [TimeClassID], [PatientReimbursementGroupID], [AccountID], [UnitTypeID], [IsDeleted], [DataTypeID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [ob].[FactReimbursementAccountSnapshot] ([OBSnapshotID], [OBReimbursementPlanID], [FiscalYearID], [TimeClassID], [PatientReimbursementGroupID], [AccountID], [UnitTypeID], [IsDeleted], [DataTypeID]); +GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [FK__FactReimb__Accou__720E141B] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [FK__FactReimb__DataT__73F65C8D] FOREIGN KEY ([DataTypeID]) REFERENCES [fw].[DimDataType] ([DataTypeID]); GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [FK__FactReimb__Fisca__75DEA4FF] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [FK__FactReimb__OBRei__77C6ED71] FOREIGN KEY ([OBReimbursementPlanID]) REFERENCES [ob].[DimOBReimbursementPlan] ([OBReimbursementPlanID]); GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [FK__FactReimb__OBSna__7025CBA9] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [FK__FactReimb__Patie__79AF35E3] FOREIGN KEY ([PatientReimbursementGroupID]) REFERENCES [fw].[DimPatientReimbursementGroup] ([PatientReimbursementGroupID]); GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [FK__FactReimb__TimeC__7B977E55] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [FK__FactReimb__UnitT__7D7FC6C7] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__005C3372] DEFAULT ((0)) FOR [Month03]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__015057AB] DEFAULT ((0)) FOR [Month04]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__02447BE4] DEFAULT ((0)) FOR [Month05]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__0338A01D] DEFAULT ((0)) FOR [Month06]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__042CC456] DEFAULT ((0)) FOR [Month07]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__0520E88F] DEFAULT ((0)) FOR [Month08]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__06150CC8] DEFAULT ((0)) FOR [Month09]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__07093101] DEFAULT ((0)) FOR [Month10]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__07FD553A] DEFAULT ((0)) FOR [Month11]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__08F17973] DEFAULT ((0)) FOR [Month12]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimbur__YTD__09E59DAC] DEFAULT ((0)) FOR [YTD]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Yearl__0AD9C1E5] DEFAULT ((0)) FOR [Yearly]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Total__0BCDE61E] DEFAULT ((0)) FOR [Total]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__0CC20A57] DEFAULT ((0)) FOR [MonthsLoaded]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Histo__0EAA52C9] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__IsDel__0DB62E90] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Trans__0F9E7702] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__OBSna__6F31A770] DEFAULT ((0)) FOR [OBSnapshotID]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Accou__7119EFE2] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__DataT__73023854] DEFAULT ((0)) FOR [DataTypeID]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Fisca__74EA80C6] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__OBRei__76D2C938] DEFAULT ((0)) FOR [OBReimbursementPlanID]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Patie__78BB11AA] DEFAULT ((0)) FOR [PatientReimbursementGroupID]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__TimeC__7AA35A1C] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__UnitT__7C8BA28E] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__7E73EB00] DEFAULT ((0)) FOR [Month01]; GO +ALTER TABLE [ob].[FactReimbursementAccountSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__7F680F39] DEFAULT ((0)) FOR [Month02]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactReimbursementExceptions ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactReimbursementExceptions] ( + [RowID] int NOT NULL, + [OBReimbursementPlanID] int NOT NULL, + [OBExceptionsID] int NOT NULL, + [Acknowledged] bit NOT NULL, + [Detail] nvarchar(2000) NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [ob].[FactReimbursementExceptions] ADD CONSTRAINT [FK__FactReimb__OBExc__1599A97F] FOREIGN KEY ([OBExceptionsID]) REFERENCES [ob].[DimOBExceptions] ([OBExceptionsID]); GO +ALTER TABLE [ob].[FactReimbursementExceptions] ADD CONSTRAINT [FK__FactReimb__OBRei__13B1610D] FOREIGN KEY ([OBReimbursementPlanID]) REFERENCES [ob].[DimOBReimbursementPlan] ([OBReimbursementPlanID]); GO +ALTER TABLE [ob].[FactReimbursementExceptions] ADD CONSTRAINT [DF__FactReimb__OBRei__12BD3CD4] DEFAULT ((0)) FOR [OBReimbursementPlanID]; GO +ALTER TABLE [ob].[FactReimbursementExceptions] ADD CONSTRAINT [DF__FactReimb__OBExc__14A58546] DEFAULT ((0)) FOR [OBExceptionsID]; GO +ALTER TABLE [ob].[FactReimbursementExceptions] ADD CONSTRAINT [DF__FactReimb__Ackno__168DCDB8] DEFAULT ((0)) FOR [Acknowledged]; GO +ALTER TABLE [ob].[FactReimbursementExceptions] ADD CONSTRAINT [DF__FactReimb__Detai__1781F1F1] DEFAULT ('') FOR [Detail]; GO +ALTER TABLE [ob].[FactReimbursementExceptions] ADD CONSTRAINT [DF__FactReimb__IsDel__1876162A] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[FactReimbursementExceptions] ADD CONSTRAINT [DF__FactReimb__Trans__1A5E5E9C] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[FactReimbursementExceptions] ADD CONSTRAINT [DF__FactReimb__Histo__196A3A63] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactReimbursementPayorSnapshot ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactReimbursementPayorSnapshot] ( + [RowID] int NOT NULL, + [OBSnapshotID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [OBForecastDetailID] int NOT NULL, + [OBReimbursementPlanID] int NOT NULL, + [PatientReimbursementGroupID] int NOT NULL, + [PayorID] int NOT NULL, + [PayorGroupID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [DataTypeID] tinyint NOT NULL, + [Month01] decimal NOT NULL, + [Month02] decimal NOT NULL, + [Month03] decimal NOT NULL, + [Month04] decimal NOT NULL, + [Month05] decimal NOT NULL, + [Month06] decimal NOT NULL, + [Month07] decimal NOT NULL, + [Month08] decimal NOT NULL, + [Month09] decimal NOT NULL, + [Month10] decimal NOT NULL, + [Month11] decimal NOT NULL, + [Month12] decimal NOT NULL, + [MonthsLoaded] int NOT NULL, + [YTD] decimal NOT NULL, + [Yearly] decimal NOT NULL, + [Total] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [ob].[FactReimbursementPayorSnapshot] ([OBSnapshotID], [OBReimbursementPlanID], [FiscalYearID], [TimeClassID], [PatientReimbursementGroupID], [OBForecastDetailID], [PayorGroupID], [PayorID], [UnitTypeID], [IsDeleted], [DataTypeID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [ob].[FactReimbursementPayorSnapshot] ([OBSnapshotID], [OBReimbursementPlanID], [FiscalYearID], [TimeClassID], [PatientReimbursementGroupID], [OBForecastDetailID], [PayorGroupID], [PayorID], [UnitTypeID], [IsDeleted], [DataTypeID]); +GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [FK__FactReimb__DataT__249993E8] FOREIGN KEY ([DataTypeID]) REFERENCES [fw].[DimDataType] ([DataTypeID]); GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [FK__FactReimb__Fisca__15575058] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [FK__FactReimb__OBFor__173F98CA] FOREIGN KEY ([OBForecastDetailID]) REFERENCES [ob].[DimOBForecastDetail] ([OBForecastDetailID]); GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [FK__FactReimb__OBRei__1927E13C] FOREIGN KEY ([OBReimbursementPlanID]) REFERENCES [ob].[DimOBReimbursementPlan] ([OBReimbursementPlanID]); GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [FK__FactReimb__OBSna__136F07E6] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [FK__FactReimb__Patie__1B1029AE] FOREIGN KEY ([PatientReimbursementGroupID]) REFERENCES [fw].[DimPatientReimbursementGroup] ([PatientReimbursementGroupID]); GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [FK__FactReimb__Payor__1CF87220] FOREIGN KEY ([PayorID]) REFERENCES [fw].[DimPayor] ([PayorID]); GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [FK__FactReimb__Payor__1EE0BA92] FOREIGN KEY ([PayorGroupID]) REFERENCES [fw].[DimPayorGroup] ([PayorGroupID]); GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [FK__FactReimb__TimeC__20C90304] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [FK__FactReimb__UnitT__22B14B76] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__OBSna__127AE3AD] DEFAULT ((0)) FOR [OBSnapshotID]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Fisca__14632C1F] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__OBFor__164B7491] DEFAULT ((0)) FOR [OBForecastDetailID]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Histo__35C41FEA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__OBRei__1833BD03] DEFAULT ((0)) FOR [OBReimbursementPlanID]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Patie__1A1C0575] DEFAULT ((0)) FOR [PatientReimbursementGroupID]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Payor__1C044DE7] DEFAULT ((0)) FOR [PayorID]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Payor__1DEC9659] DEFAULT ((0)) FOR [PayorGroupID]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__TimeC__1FD4DECB] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__UnitT__21BD273D] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__DataT__23A56FAF] DEFAULT ((0)) FOR [DataTypeID]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__258DB821] DEFAULT ((0)) FOR [Month01]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__2681DC5A] DEFAULT ((0)) FOR [Month02]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__27760093] DEFAULT ((0)) FOR [Month03]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__286A24CC] DEFAULT ((0)) FOR [Month04]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__295E4905] DEFAULT ((0)) FOR [Month05]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__2A526D3E] DEFAULT ((0)) FOR [Month06]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__2B469177] DEFAULT ((0)) FOR [Month07]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__2C3AB5B0] DEFAULT ((0)) FOR [Month08]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__2D2ED9E9] DEFAULT ((0)) FOR [Month09]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__2E22FE22] DEFAULT ((0)) FOR [Month10]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__2F17225B] DEFAULT ((0)) FOR [Month11]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__300B4694] DEFAULT ((0)) FOR [Month12]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Month__30FF6ACD] DEFAULT ((0)) FOR [MonthsLoaded]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimbur__YTD__31F38F06] DEFAULT ((0)) FOR [YTD]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Yearl__32E7B33F] DEFAULT ((0)) FOR [Yearly]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Total__33DBD778] DEFAULT ((0)) FOR [Total]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__IsDel__34CFFBB1] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[FactReimbursementPayorSnapshot] ADD CONSTRAINT [DF__FactReimb__Trans__36B84423] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactReportAccountWithStaffingDetail ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactReportAccountWithStaffingDetail] ( + [RowID] bigint NOT NULL, + [DepartmentalBudgetID] int NOT NULL, + [AccountID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeGroupID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [Month01] decimal NOT NULL, + [Month02] decimal NOT NULL, + [Month03] decimal NOT NULL, + [Month04] decimal NOT NULL, + [Month05] decimal NOT NULL, + [Month06] decimal NOT NULL, + [Month07] decimal NOT NULL, + [Month08] decimal NOT NULL, + [Month09] decimal NOT NULL, + [Month10] decimal NOT NULL, + [Month11] decimal NOT NULL, + [Month12] decimal NOT NULL, + [YTD] decimal NOT NULL, + [Total] decimal NOT NULL, + [ModifiedAt] datetime NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_FactReportAccountWithStaffingDetail_Clustered] ON [ob].[FactReportAccountWithStaffingDetail] ([DepartmentalBudgetID]); +GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__229C6EA7] DEFAULT ((0)) FOR [Month11]; GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__239092E0] DEFAULT ((0)) FOR [Month12]; GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactReportA__YTD__2484B719] DEFAULT ((0)) FOR [YTD]; GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Total__2578DB52] DEFAULT ((0)) FOR [Total]; GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Modif__266CFF8B] DEFAULT (getdate()) FOR [ModifiedAt]; GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Depar__126606DE] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Accou__135A2B17] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__JobCo__144E4F50] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__PayCo__15427389] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Fisca__163697C2] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__TimeC__172ABBFB] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__UnitT__181EE034] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__1913046D] DEFAULT ((0)) FOR [Month01]; GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__1A0728A6] DEFAULT ((0)) FOR [Month02]; GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__1AFB4CDF] DEFAULT ((0)) FOR [Month03]; GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__1BEF7118] DEFAULT ((0)) FOR [Month04]; GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__1CE39551] DEFAULT ((0)) FOR [Month05]; GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__1DD7B98A] DEFAULT ((0)) FOR [Month06]; GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__1ECBDDC3] DEFAULT ((0)) FOR [Month07]; GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__1FC001FC] DEFAULT ((0)) FOR [Month08]; GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__20B42635] DEFAULT ((0)) FOR [Month09]; GO +ALTER TABLE [ob].[FactReportAccountWithStaffingDetail] ADD CONSTRAINT [DF__FactRepor__Month__21A84A6E] DEFAULT ((0)) FOR [Month10]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactReportFinancialStatement ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactReportFinancialStatement] ( + [RowID] bigint NOT NULL, + [DepartmentalBudgetID] int NOT NULL, + [DepartmentID] int NOT NULL, + [AccountID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Month01] decimal NOT NULL, + [Month02] decimal NOT NULL, + [Month03] decimal NOT NULL, + [Month04] decimal NOT NULL, + [Month05] decimal NOT NULL, + [Month06] decimal NOT NULL, + [Month07] decimal NOT NULL, + [Month08] decimal NOT NULL, + [Month09] decimal NOT NULL, + [Month10] decimal NOT NULL, + [Month11] decimal NOT NULL, + [Month12] decimal NOT NULL, + [YTD] decimal NOT NULL, + [Yearly] decimal NOT NULL, + [Total] decimal NOT NULL, + [SnapshotID] int NOT NULL, + [ModifiedAt] datetime NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_FactReportFinancialStatement_Clustered] ON [ob].[FactReportFinancialStatement] ([FiscalYearID]); +CREATE NONCLUSTERED INDEX [IDX_FactReportFinancialStatement_AllKeys] ON [ob].[FactReportFinancialStatement] ([DepartmentalBudgetID], [SnapshotID], [TimeClassID], [FiscalYearID], [FinancialReportingID], [AccountID]); +GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [FK_FactReportFinancialStatement_SnapshotID] FOREIGN KEY ([SnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Depar__3EE3A79A] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Depar__3FD7CBD3] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Accou__40CBF00C] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Finan__41C01445] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Fisca__42B4387E] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__TimeC__43A85CB7] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__449C80F0] DEFAULT ((0)) FOR [Month01]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__4590A529] DEFAULT ((0)) FOR [Month02]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__4684C962] DEFAULT ((0)) FOR [Month03]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__4778ED9B] DEFAULT ((0)) FOR [Month04]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__486D11D4] DEFAULT ((0)) FOR [Month05]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__4961360D] DEFAULT ((0)) FOR [Month06]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__4A555A46] DEFAULT ((0)) FOR [Month07]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__4B497E7F] DEFAULT ((0)) FOR [Month08]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__4C3DA2B8] DEFAULT ((0)) FOR [Month09]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__4D31C6F1] DEFAULT ((0)) FOR [Month10]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__4E25EB2A] DEFAULT ((0)) FOR [Month11]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Month__4F1A0F63] DEFAULT ((0)) FOR [Month12]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactReportF__YTD__500E339C] DEFAULT ((0)) FOR [YTD]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Yearl__510257D5] DEFAULT ((0)) FOR [Yearly]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Total__51F67C0E] DEFAULT ((0)) FOR [Total]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Snaps__52EAA047] DEFAULT ((0)) FOR [SnapshotID]; GO +ALTER TABLE [ob].[FactReportFinancialStatement] ADD CONSTRAINT [DF__FactRepor__Modif__53DEC480] DEFAULT (getdate()) FOR [ModifiedAt]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactReportFinancialStatement_Pivoted ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactReportFinancialStatement_Pivoted] ( + [RowID] bigint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [DepartmentalBudgetID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [AccountID] int NOT NULL, + [SnapshotID] int NOT NULL, + [Amount] decimal NOT NULL, + [Total] decimal NOT NULL, + [Yearly] decimal NOT NULL, + [YTD] decimal NOT NULL, + [MaxValue] decimal NOT NULL, + [MaxValueYTD] decimal NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE CLUSTERED INDEX [IX_FactReportFinancialStatement_Pivoted_Clustered] ON [ob].[FactReportFinancialStatement_Pivoted] ([FiscalYearID]); +CREATE NONCLUSTERED INDEX [IDX_FactReportFinancialStatement_Pivoted_AllKeys] ON [ob].[FactReportFinancialStatement_Pivoted] ([DepartmentalBudgetID], [SnapshotID], [TimeClassID], [FiscalYearID], [FiscalMonthID], [FinancialReportingID], [AccountID]); +GO +ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [FK_FactReportFinancialStatement_Pivoted_SnapshotID] FOREIGN KEY ([SnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO +ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__TimeC__41AC9C5A] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__Fisca__42A0C093] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__Depar__4394E4CC] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO +ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__Finan__44890905] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__Accou__457D2D3E] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__Snaps__46715177] DEFAULT ((0)) FOR [SnapshotID]; GO +ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__Amoun__476575B0] DEFAULT ((0)) FOR [Amount]; GO +ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__Total__485999E9] DEFAULT ((0)) FOR [Total]; GO +ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__Yearl__494DBE22] DEFAULT ((0)) FOR [Yearly]; GO +ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactReportF__YTD__4A41E25B] DEFAULT ((0)) FOR [YTD]; GO +ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__MaxVa__4B360694] DEFAULT ((0)) FOR [MaxValue]; GO +ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__MaxVa__4C2A2ACD] DEFAULT ((0)) FOR [MaxValueYTD]; GO +ALTER TABLE [ob].[FactReportFinancialStatement_Pivoted] ADD CONSTRAINT [DF__FactRepor__Fisca__4D1E4F06] DEFAULT ((0)) FOR [FiscalMonthID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactReportingMonthlySnapshot ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactReportingMonthlySnapshot] ( + [RowID] int NOT NULL, + [OBSnapshotID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [DepartmentalBudgetID] int NOT NULL, + [FinancialReportingID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Month01] decimal NOT NULL, + [Month02] decimal NOT NULL, + [Month03] decimal NOT NULL, + [Month04] decimal NOT NULL, + [Month05] decimal NOT NULL, + [Month06] decimal NOT NULL, + [Month07] decimal NOT NULL, + [Month08] decimal NOT NULL, + [Month09] decimal NOT NULL, + [Month10] decimal NOT NULL, + [Month11] decimal NOT NULL, + [Month12] decimal NOT NULL, + [YTD] decimal NOT NULL, + [Yearly] decimal NOT NULL, + [Total] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [ob].[FactReportingMonthlySnapshot] ([OBSnapshotID], [DepartmentalBudgetID], [FiscalYearID], [TimeClassID], [FinancialReportingID], [IsDeleted]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [ob].[FactReportingMonthlySnapshot] ([OBSnapshotID], [DepartmentalBudgetID], [FiscalYearID], [TimeClassID], [FinancialReportingID], [IsDeleted]); +CREATE NONCLUSTERED INDEX [NCNU_DepartmentalBudget_OBSnapshotID] ON [ob].[FactReportingMonthlySnapshot] ([DepartmentalBudgetID], [OBSnapshotID]); +GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [FK__FactRepor__Depar__3E5965EB] FOREIGN KEY ([DepartmentalBudgetID]) REFERENCES [ob].[DimDepartmentalBudget] ([DepartmentalBudgetID]); GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [FK__FactRepor__Finan__4041AE5D] FOREIGN KEY ([FinancialReportingID]) REFERENCES [ob].[DimFinancialReporting] ([FinancialReportingID]); GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [FK__FactRepor__Fisca__3C711D79] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [FK__FactRepor__OBSna__3A88D507] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [FK__FactRepor__TimeC__4229F6CF] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__OBSna__3994B0CE] DEFAULT ((0)) FOR [OBSnapshotID]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Fisca__3B7CF940] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Depar__3D6541B2] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Finan__3F4D8A24] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__TimeC__4135D296] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__431E1B08] DEFAULT ((0)) FOR [Month01]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__44123F41] DEFAULT ((0)) FOR [Month02]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__4506637A] DEFAULT ((0)) FOR [Month03]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__45FA87B3] DEFAULT ((0)) FOR [Month04]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__46EEABEC] DEFAULT ((0)) FOR [Month05]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__47E2D025] DEFAULT ((0)) FOR [Month06]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__48D6F45E] DEFAULT ((0)) FOR [Month07]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__49CB1897] DEFAULT ((0)) FOR [Month08]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__4ABF3CD0] DEFAULT ((0)) FOR [Month09]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__4BB36109] DEFAULT ((0)) FOR [Month10]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__4CA78542] DEFAULT ((0)) FOR [Month11]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Month__4D9BA97B] DEFAULT ((0)) FOR [Month12]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactReporti__YTD__4E8FCDB4] DEFAULT ((0)) FOR [YTD]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Yearl__4F83F1ED] DEFAULT ((0)) FOR [Yearly]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Total__50781626] DEFAULT ((0)) FOR [Total]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__IsDel__516C3A5F] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Trans__535482D1] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[FactReportingMonthlySnapshot] ADD CONSTRAINT [DF__FactRepor__Histo__52605E98] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactServiceLineExceptions ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactServiceLineExceptions] ( + [RowID] int NOT NULL, + [OBServiceLinePlanID] int NOT NULL, + [OBExceptionsID] int NOT NULL, + [Acknowledged] bit NOT NULL, + [Detail] nvarchar(2000) NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [ob].[FactServiceLineExceptions] ADD CONSTRAINT [FK__FactServi__OBExc__201737F2] FOREIGN KEY ([OBExceptionsID]) REFERENCES [ob].[DimOBExceptions] ([OBExceptionsID]); GO +ALTER TABLE [ob].[FactServiceLineExceptions] ADD CONSTRAINT [FK__FactServi__OBSer__1E2EEF80] FOREIGN KEY ([OBServiceLinePlanID]) REFERENCES [ob].[DimOBServiceLinePlan] ([OBServiceLinePlanID]); GO +ALTER TABLE [ob].[FactServiceLineExceptions] ADD CONSTRAINT [DF__FactServi__Histo__23E7C8D6] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[FactServiceLineExceptions] ADD CONSTRAINT [DF__FactServi__OBSer__1D3ACB47] DEFAULT ((0)) FOR [OBServiceLinePlanID]; GO +ALTER TABLE [ob].[FactServiceLineExceptions] ADD CONSTRAINT [DF__FactServi__OBExc__1F2313B9] DEFAULT ((0)) FOR [OBExceptionsID]; GO +ALTER TABLE [ob].[FactServiceLineExceptions] ADD CONSTRAINT [DF__FactServi__Ackno__210B5C2B] DEFAULT ((0)) FOR [Acknowledged]; GO +ALTER TABLE [ob].[FactServiceLineExceptions] ADD CONSTRAINT [DF__FactServi__Detai__21FF8064] DEFAULT ('') FOR [Detail]; GO +ALTER TABLE [ob].[FactServiceLineExceptions] ADD CONSTRAINT [DF__FactServi__IsDel__22F3A49D] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[FactServiceLineExceptions] ADD CONSTRAINT [DF__FactServi__Trans__24DBED0F] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactServiceLineSnapshot ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactServiceLineSnapshot] ( + [RowID] int NOT NULL, + [DataTypeID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [ModelingServiceLineID] int NOT NULL, + [OBForecastDetailID] int NOT NULL, + [OBSnapshotID] int NOT NULL, + [OBServiceLinePlanID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [Month01] decimal NOT NULL, + [Month02] decimal NOT NULL, + [Month03] decimal NOT NULL, + [Month04] decimal NOT NULL, + [Month05] decimal NOT NULL, + [Month06] decimal NOT NULL, + [Month07] decimal NOT NULL, + [Month08] decimal NOT NULL, + [Month09] decimal NOT NULL, + [Month10] decimal NOT NULL, + [Month11] decimal NOT NULL, + [Month12] decimal NOT NULL, + [Yearly] decimal NOT NULL, + [YTD] decimal NOT NULL, + [Total] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [ob].[FactServiceLineSnapshot] ([OBSnapshotID], [OBServiceLinePlanID], [FiscalYearID], [TimeClassID], [ModelingServiceLineID], [OBForecastDetailID], [UnitTypeID], [IsDeleted], [DataTypeID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [ob].[FactServiceLineSnapshot] ([OBSnapshotID], [OBServiceLinePlanID], [FiscalYearID], [TimeClassID], [ModelingServiceLineID], [OBForecastDetailID], [UnitTypeID], [IsDeleted], [DataTypeID]); +GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [FK__FactServi__DataT__572513B5] FOREIGN KEY ([DataTypeID]) REFERENCES [fw].[DimDataType] ([DataTypeID]); GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [FK__FactServi__Fisca__590D5C27] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [FK__FactServi__Model__5AF5A499] FOREIGN KEY ([ModelingServiceLineID]) REFERENCES [fw].[DimModelingServiceLine] ([ModelingServiceLineID]); GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [FK__FactServi__OBFor__5CDDED0B] FOREIGN KEY ([OBForecastDetailID]) REFERENCES [ob].[DimOBForecastDetail] ([OBForecastDetailID]); GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [FK__FactServi__OBSer__60AE7DEF] FOREIGN KEY ([OBServiceLinePlanID]) REFERENCES [ob].[DimOBServiceLinePlan] ([OBServiceLinePlanID]); GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [FK__FactServi__OBSna__5EC6357D] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [FK__FactServi__TimeC__6296C661] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [FK__FactServi__UnitT__647F0ED3] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Histo__74B5769C] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__DataT__5630EF7C] DEFAULT ((0)) FOR [DataTypeID]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Fisca__581937EE] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Model__5A018060] DEFAULT ((0)) FOR [ModelingServiceLineID]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__OBFor__5BE9C8D2] DEFAULT ((0)) FOR [OBForecastDetailID]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__OBSna__5DD21144] DEFAULT ((0)) FOR [OBSnapshotID]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__OBSer__5FBA59B6] DEFAULT ((0)) FOR [OBServiceLinePlanID]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__TimeC__61A2A228] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__UnitT__638AEA9A] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__6573330C] DEFAULT ((0)) FOR [Month01]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__66675745] DEFAULT ((0)) FOR [Month02]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__675B7B7E] DEFAULT ((0)) FOR [Month03]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__684F9FB7] DEFAULT ((0)) FOR [Month04]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__6943C3F0] DEFAULT ((0)) FOR [Month05]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__6A37E829] DEFAULT ((0)) FOR [Month06]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__6B2C0C62] DEFAULT ((0)) FOR [Month07]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__6C20309B] DEFAULT ((0)) FOR [Month08]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__6D1454D4] DEFAULT ((0)) FOR [Month09]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__6E08790D] DEFAULT ((0)) FOR [Month10]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__6EFC9D46] DEFAULT ((0)) FOR [Month11]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Month__6FF0C17F] DEFAULT ((0)) FOR [Month12]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Yearl__70E4E5B8] DEFAULT ((0)) FOR [Yearly]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactService__YTD__71D909F1] DEFAULT ((0)) FOR [YTD]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Total__72CD2E2A] DEFAULT ((0)) FOR [Total]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__IsDel__73C15263] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[FactServiceLineSnapshot] ADD CONSTRAINT [DF__FactServi__Trans__75A99AD5] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactStaffingPCSnapshot ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactStaffingPCSnapshot] ( + [RowID] int NOT NULL, + [DataTypeID] tinyint NOT NULL, + [EmployeeID] int NOT NULL, + [FiscalYearID] smallint NOT NULL, + [JobCodeID] int NOT NULL, + [DepartmentalBudgetID] int NOT NULL, + [OBSnapshotID] int NOT NULL, + [PayCodeID] smallint NOT NULL, + [PayCodeGroupID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [Month01] decimal NOT NULL, + [Month02] decimal NOT NULL, + [Month03] decimal NOT NULL, + [Month04] decimal NOT NULL, + [Month05] decimal NOT NULL, + [Month06] decimal NOT NULL, + [Month07] decimal NOT NULL, + [Month08] decimal NOT NULL, + [Month09] decimal NOT NULL, + [Month10] decimal NOT NULL, + [Month11] decimal NOT NULL, + [Month12] decimal NOT NULL, + [MonthsLoaded] int NOT NULL, + [Total] decimal NOT NULL, + [Yearly] decimal NOT NULL, + [YTD] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); + +CREATE UNIQUE CLUSTERED INDEX [CU_Base] ON [ob].[FactStaffingPCSnapshot] ([OBSnapshotID], [DepartmentalBudgetID], [TimeClassID], [FiscalYearID], [JobCodeID], [EmployeeID], [PayCodeGroupID], [PayCodeID], [UnitTypeID], [IsDeleted], [DataTypeID]); +CREATE UNIQUE NONCLUSTERED INDEX [NCU_Score] ON [ob].[FactStaffingPCSnapshot] ([OBSnapshotID], [DepartmentalBudgetID], [TimeClassID], [FiscalYearID], [JobCodeID], [EmployeeID], [PayCodeGroupID], [PayCodeID], [UnitTypeID], [IsDeleted], [DataTypeID]); +GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [FK__FactStaff__DataT__3B1D068D] FOREIGN KEY ([DataTypeID]) REFERENCES [fw].[DimDataType] ([DataTypeID]); GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [FK__FactStaff__Depar__42BE2855] FOREIGN KEY ([DepartmentalBudgetID]) REFERENCES [ob].[DimDepartmentalBudget] ([DepartmentalBudgetID]); GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [FK__FactStaff__Emplo__3D054EFF] FOREIGN KEY ([EmployeeID]) REFERENCES [fw].[DimEmployee] ([EmployeeID]); GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [FK__FactStaff__Fisca__3EED9771] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [FK__FactStaff__JobCo__40D5DFE3] FOREIGN KEY ([JobCodeID]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [FK__FactStaff__OBSna__44A670C7] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [FK__FactStaff__PayCo__468EB939] FOREIGN KEY ([PayCodeGroupID]) REFERENCES [fw].[DimPayCodeGroup] ([PayCodeGroupID]); GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [FK__FactStaff__TimeC__487701AB] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [FK__FactStaff__UnitT__4A5F4A1D] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__DataT__3A28E254] DEFAULT ((0)) FOR [DataTypeID]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Emplo__3C112AC6] DEFAULT ((0)) FOR [EmployeeID]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Fisca__3DF97338] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__JobCo__3FE1BBAA] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Depar__41CA041C] DEFAULT ((0)) FOR [DepartmentalBudgetID]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__OBSna__43B24C8E] DEFAULT ((0)) FOR [OBSnapshotID]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__PayCo__459A9500] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__TimeC__4782DD72] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__UnitT__496B25E4] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__4B536E56] DEFAULT ((0)) FOR [Month01]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__4C47928F] DEFAULT ((0)) FOR [Month02]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__4D3BB6C8] DEFAULT ((0)) FOR [Month03]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__4E2FDB01] DEFAULT ((0)) FOR [Month04]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__4F23FF3A] DEFAULT ((0)) FOR [Month05]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__50182373] DEFAULT ((0)) FOR [Month06]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__510C47AC] DEFAULT ((0)) FOR [Month07]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__52006BE5] DEFAULT ((0)) FOR [Month08]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__52F4901E] DEFAULT ((0)) FOR [Month09]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__53E8B457] DEFAULT ((0)) FOR [Month10]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__54DCD890] DEFAULT ((0)) FOR [Month11]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__55D0FCC9] DEFAULT ((0)) FOR [Month12]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Month__56C52102] DEFAULT ((0)) FOR [MonthsLoaded]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Total__57B9453B] DEFAULT ((0)) FOR [Total]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Yearl__58AD6974] DEFAULT ((0)) FOR [Yearly]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaffin__YTD__59A18DAD] DEFAULT ((0)) FOR [YTD]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__IsDel__5A95B1E6] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Trans__5C7DFA58] DEFAULT ((0)) FOR [TransactionID]; GO +ALTER TABLE [ob].[FactStaffingPCSnapshot] ADD CONSTRAINT [DF__FactStaff__Histo__5B89D61F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactStaffingPCVarSnapshot ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactStaffingPCVarSnapshot] ( + [RowID] bigint NOT NULL, + [AssumptionID] int NOT NULL, + [EmployeeID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [JobCodeID] int NOT NULL, + [DepartmentalBudgetID] int NOT NULL, + [PayCodeGroupID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [OBSnapshotID] int NOT NULL, + [Amount] decimal NOT NULL, + [Amount_Comment] nvarchar(max) NOT NULL, + [Amount_Formula] nvarchar(max) NOT NULL, + [Comment] nvarchar(2000) NOT NULL, + [Comment_Comment] nvarchar(max) NOT NULL, + [Comment_Formula] nvarchar(max) NOT NULL, + [TextValue] nvarchar(2000) NOT NULL, + [TextValue_Comment] nvarchar(max) NOT NULL, + [TextValue_Formula] nvarchar(max) NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [FK_FactStaffingPCVarSnapshot_OBSnapshotID] FOREIGN KEY ([OBSnapshotID]) REFERENCES [ob].[DimOBSnapshot] ([OBSnapshotID]); GO +ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__Histo__79710739] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__Fisca__6D0B3054] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__Fisca__6DFF548D] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__OBSna__6EF378C6] DEFAULT ((0)) FOR [OBSnapshotID]; GO +ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__Amoun__6FE79CFF] DEFAULT ((0)) FOR [Amount]; GO +ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__Amoun__70DBC138] DEFAULT ('') FOR [Amount_Comment]; GO +ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__Amoun__71CFE571] DEFAULT ('d') FOR [Amount_Formula]; GO +ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__Comme__72C409AA] DEFAULT ('') FOR [Comment]; GO +ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__Comme__73B82DE3] DEFAULT ('') FOR [Comment_Comment]; GO +ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__Comme__74AC521C] DEFAULT ('d') FOR [Comment_Formula]; GO +ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__TextV__75A07655] DEFAULT ('') FOR [TextValue]; GO +ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__TextV__76949A8E] DEFAULT ('') FOR [TextValue_Comment]; GO +ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__TextV__7788BEC7] DEFAULT ('d') FOR [TextValue_Formula]; GO +ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__IsDel__787CE300] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[FactStaffingPCVarSnapshot] ADD CONSTRAINT [DF__FactStaff__Trans__7A652B72] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FactStagedDSChargeCodeCost ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FactStagedDSChargeCodeCost] ( + [RowID] int NOT NULL, + [DepartmentID] int NOT NULL, + [FiscalYearID] int NOT NULL, + [FiscalMonthID] int NOT NULL, + [TimeClassID] int NOT NULL, + [FinancialCostComponentID] int NOT NULL, + [ChargeCodeID] int NOT NULL, + [Units] decimal NOT NULL, + [Cost] decimal NOT NULL, + [Charge] decimal NOT NULL, + [IsDeleted] bit NOT NULL, + [HistoryItemGUID] uniqueidentifier NOT NULL, + [Version] timestamp NOT NULL, + [TransactionID] int NULL, + [ServiceLineID] int NOT NULL, + [AgeCohortID] int NOT NULL, + [PatientClassID] int NOT NULL, + [MedicalSurgicalID] int NOT NULL, + PRIMARY KEY ([RowID]) +); +GO +ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Servi__0EDF5CF3] DEFAULT ((0)) FOR [ServiceLineID]; GO +ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__AgeCo__0FD3812C] DEFAULT ((0)) FOR [AgeCohortID]; GO +ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Patie__10C7A565] DEFAULT ((0)) FOR [PatientClassID]; GO +ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Medic__11BBC99E] DEFAULT ((0)) FOR [MedicalSurgicalID]; GO +ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Depar__6276CAD0] DEFAULT ((0)) FOR [DepartmentID]; GO +ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Fisca__645F1342] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Fisca__6553377B] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__TimeC__66475BB4] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Finan__673B7FED] DEFAULT ((0)) FOR [FinancialCostComponentID]; GO +ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Charg__682FA426] DEFAULT ((0)) FOR [ChargeCodeID]; GO +ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Units__6923C85F] DEFAULT ((0)) FOR [Units]; GO +ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStaged__Cost__6A17EC98] DEFAULT ((0)) FOR [Cost]; GO +ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Charg__6B0C10D1] DEFAULT ((0)) FOR [Charge]; GO +ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__IsDel__6C00350A] DEFAULT ((0)) FOR [IsDeleted]; GO +ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Histo__6CF45943] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [HistoryItemGUID]; GO +ALTER TABLE [ob].[FactStagedDSChargeCodeCost] ADD CONSTRAINT [DF__FactStage__Trans__6DE87D7C] DEFAULT ((0)) FOR [TransactionID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FlexDriver ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FlexDriver] ( + [FlexDriverGUID] uniqueidentifier NOT NULL, + [Name] nvarchar(100) NOT NULL, + [ScoreDatatableGUID] uniqueidentifier NOT NULL, + [ParentDriverGUID] uniqueidentifier NOT NULL, + [IsParentDriverFlexed] bit NOT NULL, + [SortOrder] smallint NOT NULL, + [Tier] smallint NOT NULL, + [MeasureType] tinyint NOT NULL, + [IsSameJobCode] bit NOT NULL, + [IsSamePayCodeGroup] bit NOT NULL, + PRIMARY KEY ([FlexDriverGUID]) +); +GO +ALTER TABLE [ob].[FlexDriver] ADD CONSTRAINT [DF__FlexDrive__Paren__34A51328] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ParentDriverGUID]; GO +ALTER TABLE [ob].[FlexDriver] ADD CONSTRAINT [DF__FlexDrive__IsPar__35993761] DEFAULT ((0)) FOR [IsParentDriverFlexed]; GO +ALTER TABLE [ob].[FlexDriver] ADD CONSTRAINT [DF__FlexDrive__SortO__368D5B9A] DEFAULT ((0)) FOR [SortOrder]; GO +ALTER TABLE [ob].[FlexDriver] ADD CONSTRAINT [DF__FlexDriver__Tier__37817FD3] DEFAULT ((0)) FOR [Tier]; GO +ALTER TABLE [ob].[FlexDriver] ADD CONSTRAINT [DF__FlexDrive__IsSam__3FCCAD11] DEFAULT ((0)) FOR [IsSameJobCode]; GO +ALTER TABLE [ob].[FlexDriver] ADD CONSTRAINT [DF__FlexDrive__IsSam__40C0D14A] DEFAULT ((0)) FOR [IsSamePayCodeGroup]; GO +ALTER TABLE [ob].[FlexDriver] ADD CONSTRAINT [DF__FlexDrive__FlexD__598BB3BD] DEFAULT (newid()) FOR [FlexDriverGUID]; GO +ALTER TABLE [ob].[FlexDriver] ADD CONSTRAINT [DF__FlexDriver__Name__5A7FD7F6] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[FlexDriver] ADD CONSTRAINT [DF__FlexDrive__Score__5B73FC2F] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ScoreDatatableGUID]; GO +ALTER TABLE [ob].[FlexDriver] ADD CONSTRAINT [DF__FlexDrive__Measu__632AF7E7] DEFAULT ((0)) FOR [MeasureType]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FlexDriverAccountAssignment ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FlexDriverAccountAssignment] ( + [FlexDriverAccountAssignmentID] int NOT NULL, + [FlexDriverGUID] uniqueidentifier NOT NULL, + [AccountAssignment] nvarchar(400) NOT NULL, + PRIMARY KEY ([FlexDriverAccountAssignmentID]) +); +GO +ALTER TABLE [ob].[FlexDriverAccountAssignment] ADD CONSTRAINT [FK__FlexDrive__FlexD__28B43D8F] FOREIGN KEY ([FlexDriverGUID]) REFERENCES [ob].[FlexDriver] ([FlexDriverGUID]); GO +ALTER TABLE [ob].[FlexDriverAccountAssignment] ADD CONSTRAINT [DF__FlexDrive__FlexD__5E5068DA] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FlexDriverGUID]; GO +ALTER TABLE [ob].[FlexDriverAccountAssignment] ADD CONSTRAINT [DF__FlexDrive__Accou__6038B14C] DEFAULT ('') FOR [AccountAssignment]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FlexDriverPayrollAssignment ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FlexDriverPayrollAssignment] ( + [FlexDriverPayrollAssignmentID] int NOT NULL, + [FlexDriverGUID] uniqueidentifier NOT NULL, + [JobCodeAssignment] nvarchar(400) NOT NULL, + [PayCodeGroupAssignment] nvarchar(400) NOT NULL, + PRIMARY KEY ([FlexDriverPayrollAssignmentID]) +); +GO +ALTER TABLE [ob].[FlexDriverPayrollAssignment] ADD CONSTRAINT [FK__FlexDrive__FlexD__29A861C8] FOREIGN KEY ([FlexDriverGUID]) REFERENCES [ob].[FlexDriver] ([FlexDriverGUID]); GO +ALTER TABLE [ob].[FlexDriverPayrollAssignment] ADD CONSTRAINT [DF__FlexDrive__FlexD__63151DF7] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FlexDriverGUID]; GO +ALTER TABLE [ob].[FlexDriverPayrollAssignment] ADD CONSTRAINT [DF__FlexDrive__JobCo__64FD6669] DEFAULT ('') FOR [JobCodeAssignment]; GO +ALTER TABLE [ob].[FlexDriverPayrollAssignment] ADD CONSTRAINT [DF__FlexDrive__PayCo__65F18AA2] DEFAULT ('') FOR [PayCodeGroupAssignment]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.FlexDriverProviderForecastAssignment ------------------ +--------------------------------------------- +CREATE TABLE [ob].[FlexDriverProviderForecastAssignment] ( + [FlexDriverProviderForecastAssignmentID] int NOT NULL, + [FlexDriverGUID] uniqueidentifier NOT NULL, + [ProviderAssignment] nvarchar(400) NULL, + [ForecastDetailAssignment] nvarchar(400) NULL, + PRIMARY KEY ([FlexDriverProviderForecastAssignmentID]) +); +GO +ALTER TABLE [ob].[FlexDriverProviderForecastAssignment] ADD CONSTRAINT [FK__FlexDrive__FlexD__23B61DD2] FOREIGN KEY ([FlexDriverGUID]) REFERENCES [ob].[FlexDriver] ([FlexDriverGUID]); GO +ALTER TABLE [ob].[FlexDriverProviderForecastAssignment] ADD CONSTRAINT [DF__FlexDrive__FlexD__20D9B127] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FlexDriverGUID]; GO +ALTER TABLE [ob].[FlexDriverProviderForecastAssignment] ADD CONSTRAINT [DF__FlexDrive__Provi__21CDD560] DEFAULT ('') FOR [ProviderAssignment]; GO +ALTER TABLE [ob].[FlexDriverProviderForecastAssignment] ADD CONSTRAINT [DF__FlexDrive__Forec__22C1F999] DEFAULT ('') FOR [ForecastDetailAssignment]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.JobCodeReconciliationTarget ------------------ +--------------------------------------------- +CREATE TABLE [ob].[JobCodeReconciliationTarget] ( + [TargetGuid] uniqueidentifier NOT NULL, + [EntityID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [JobCodeID] int NOT NULL, + [Amount] decimal NOT NULL, + PRIMARY KEY ([TargetGuid]) +); +GO +ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [FK__JobCodeRe__Entit__1D428AE3] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [FK__JobCodeRe__Fisca__1F2AD355] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO +ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [FK__JobCodeRe__Fisca__21131BC7] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [FK__JobCodeRe__JobCo__26CBF51D] FOREIGN KEY ([JobCodeID]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO +ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [FK__JobCodeRe__TimeC__22FB6439] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [FK__JobCodeRe__UnitT__24E3ACAB] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [DF__JobCodeRe__Targe__1B5A4271] DEFAULT (newid()) FOR [TargetGuid]; GO +ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [DF__JobCodeRe__Fisca__1E36AF1C] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [DF__JobCodeRe__Fisca__201EF78E] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [DF__JobCodeRe__TimeC__22074000] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [DF__JobCodeRe__UnitT__23EF8872] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [DF__JobCodeRe__JobCo__25D7D0E4] DEFAULT ((0)) FOR [JobCodeID]; GO +ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [DF__JobCodeRe__Amoun__27C01956] DEFAULT ((0)) FOR [Amount]; GO +ALTER TABLE [ob].[JobCodeReconciliationTarget] ADD CONSTRAINT [DF__JobCodeRe__Entit__1C4E66AA] DEFAULT ((0)) FOR [EntityID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.PayCodeReconciliationTarget ------------------ +--------------------------------------------- +CREATE TABLE [ob].[PayCodeReconciliationTarget] ( + [TargetGuid] uniqueidentifier NOT NULL, + [EntityID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [PayCodeGroupID] int NOT NULL, + [Amount] decimal NOT NULL, + PRIMARY KEY ([TargetGuid]) +); +GO +ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [FK__PayCodeRe__Entit__183DDEA4] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [FK__PayCodeRe__Fisca__1A262716] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO +ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [FK__PayCodeRe__Fisca__1C0E6F88] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [FK__PayCodeRe__PayCo__21C748DE] FOREIGN KEY ([PayCodeGroupID]) REFERENCES [fw].[DimPayCodeGroup] ([PayCodeGroupID]); GO +ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [FK__PayCodeRe__TimeC__1DF6B7FA] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [FK__PayCodeRe__UnitT__1FDF006C] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [DF__PayCodeRe__Targe__16559632] DEFAULT (newid()) FOR [TargetGuid]; GO +ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [DF__PayCodeRe__Fisca__193202DD] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [DF__PayCodeRe__Fisca__1B1A4B4F] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [DF__PayCodeRe__TimeC__1D0293C1] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [DF__PayCodeRe__UnitT__1EEADC33] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [DF__PayCodeRe__PayCo__20D324A5] DEFAULT ((0)) FOR [PayCodeGroupID]; GO +ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [DF__PayCodeRe__Amoun__22BB6D17] DEFAULT ((0)) FOR [Amount]; GO +ALTER TABLE [ob].[PayCodeReconciliationTarget] ADD CONSTRAINT [DF__PayCodeRe__Entit__1749BA6B] DEFAULT ((0)) FOR [EntityID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.PayrollVariabilityOverride ------------------ +--------------------------------------------- +CREATE TABLE [ob].[PayrollVariabilityOverride] ( + [DepartmentAssignment] nvarchar(400) NOT NULL, + [JobCodeAssignment] nvarchar(400) NOT NULL, + [PayCodeGroupAssignment] nvarchar(400) NOT NULL, + [Variability] decimal NOT NULL, + [PrecedentOrder] int NOT NULL, + [PayrollVariabilityOverrideID] int NOT NULL, + PRIMARY KEY ([PayrollVariabilityOverrideID]) +); +GO +ALTER TABLE [ob].[PayrollVariabilityOverride] ADD CONSTRAINT [DF__PayrollVa__Depar__6F7AF4DC] DEFAULT ('') FOR [DepartmentAssignment]; GO +ALTER TABLE [ob].[PayrollVariabilityOverride] ADD CONSTRAINT [DF__PayrollVa__JobCo__706F1915] DEFAULT ('') FOR [JobCodeAssignment]; GO +ALTER TABLE [ob].[PayrollVariabilityOverride] ADD CONSTRAINT [DF__PayrollVa__PayCo__71633D4E] DEFAULT ('') FOR [PayCodeGroupAssignment]; GO +ALTER TABLE [ob].[PayrollVariabilityOverride] ADD CONSTRAINT [DF__PayrollVa__Varia__72576187] DEFAULT ((0)) FOR [Variability]; GO +ALTER TABLE [ob].[PayrollVariabilityOverride] ADD CONSTRAINT [DF__PayrollVa__Prece__734B85C0] DEFAULT ((0)) FOR [PrecedentOrder]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.PayrollVariabilityOverrideCache ------------------ +--------------------------------------------- +CREATE TABLE [ob].[PayrollVariabilityOverrideCache] ( + [DepartmentID] int NOT NULL, + [JobCodeID] int NOT NULL, + [PayCodeGroupID] int NOT NULL, + [Variability] decimal NOT NULL, + [IsForAllPayCodeGroups] bit NOT NULL, + PRIMARY KEY ([DepartmentID], [JobCodeID], [PayCodeGroupID]) +); +GO +ALTER TABLE [ob].[PayrollVariabilityOverrideCache] ADD CONSTRAINT [FK_OB_PayrollVariabilityOverrideCache_DimDepartment] FOREIGN KEY ([DepartmentID]) REFERENCES [fw].[DimDepartment] ([DepartmentID]); GO +ALTER TABLE [ob].[PayrollVariabilityOverrideCache] ADD CONSTRAINT [FK_OB_PayrollVariabilityOverrideCache_DimJobCode] FOREIGN KEY ([JobCodeID]) REFERENCES [fw].[DimJobCode] ([JobCodeID]); GO +ALTER TABLE [ob].[PayrollVariabilityOverrideCache] ADD CONSTRAINT [FK_OB_PayrollVariabilityOverrideCache_DimPayCodeGroup] FOREIGN KEY ([PayCodeGroupID]) REFERENCES [fw].[DimPayCodeGroup] ([PayCodeGroupID]); GO +ALTER TABLE [ob].[PayrollVariabilityOverrideCache] ADD CONSTRAINT [DF__PayrollVa__IsFor__0E911584] DEFAULT ((0)) FOR [IsForAllPayCodeGroups]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.ReconciliationTarget ------------------ +--------------------------------------------- +CREATE TABLE [ob].[ReconciliationTarget] ( + [TargetGuid] uniqueidentifier NOT NULL, + [EntityID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [FinancialReportingID] int NOT NULL, + [TimeClassID] tinyint NOT NULL, + [Amount] decimal NOT NULL, + PRIMARY KEY ([TargetGuid]) +); +GO +ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [FK__Reconcili__Entit__22E3F39B] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [FK__Reconcili__Finan__289CCCF1] FOREIGN KEY ([FinancialReportingID]) REFERENCES [ob].[DimFinancialReporting] ([FinancialReportingID]); GO +ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [FK__Reconcili__Fisca__24CC3C0D] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO +ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [FK__Reconcili__Fisca__26B4847F] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [FK__Reconcili__TimeC__2A851563] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [DF__Reconcili__Targe__20FBAB29] DEFAULT (newid()) FOR [TargetGuid]; GO +ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [DF__Reconcili__Fisca__23D817D4] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [DF__Reconcili__Fisca__25C06046] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [DF__Reconcili__Finan__27A8A8B8] DEFAULT ((0)) FOR [FinancialReportingID]; GO +ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [DF__Reconcili__TimeC__2990F12A] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [DF__Reconcili__Amoun__2B79399C] DEFAULT ((0)) FOR [Amount]; GO +ALTER TABLE [ob].[ReconciliationTarget] ADD CONSTRAINT [DF__Reconcili__Entit__21EFCF62] DEFAULT ((0)) FOR [EntityID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.StatisticsEntityReconciliationTarget ------------------ +--------------------------------------------- +CREATE TABLE [ob].[StatisticsEntityReconciliationTarget] ( + [TargetGuid] uniqueidentifier NOT NULL, + [EntityID] int NOT NULL, + [FiscalMonthID] tinyint NOT NULL, + [FiscalYearID] smallint NOT NULL, + [TimeClassID] tinyint NOT NULL, + [UnitTypeID] tinyint NOT NULL, + [AccountID] int NOT NULL, + [Amount] decimal NOT NULL, + PRIMARY KEY ([TargetGuid]) +); +GO +ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [FK__Statistic__Accou__50C22EE9] FOREIGN KEY ([AccountID]) REFERENCES [fw].[DimAccount] ([AccountID]); GO +ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [FK__Statistic__Entit__4738C4AF] FOREIGN KEY ([EntityID]) REFERENCES [fw].[DimEntity] ([EntityID]); GO +ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [FK__Statistic__Fisca__49210D21] FOREIGN KEY ([FiscalMonthID]) REFERENCES [fw].[DimFiscalMonth] ([FiscalMonthID]); GO +ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [FK__Statistic__Fisca__4B095593] FOREIGN KEY ([FiscalYearID]) REFERENCES [fw].[DimFiscalYear] ([FiscalYearID]); GO +ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [FK__Statistic__TimeC__4CF19E05] FOREIGN KEY ([TimeClassID]) REFERENCES [fw].[DimTimeClass] ([TimeClassID]); GO +ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [FK__Statistic__UnitT__4ED9E677] FOREIGN KEY ([UnitTypeID]) REFERENCES [fw].[DimUnitType] ([UnitTypeID]); GO +ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [DF__Statistic__Targe__45507C3D] DEFAULT (newid()) FOR [TargetGuid]; GO +ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [DF__Statistic__Fisca__482CE8E8] DEFAULT ((0)) FOR [FiscalMonthID]; GO +ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [DF__Statistic__Fisca__4A15315A] DEFAULT ((0)) FOR [FiscalYearID]; GO +ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [DF__Statistic__TimeC__4BFD79CC] DEFAULT ((0)) FOR [TimeClassID]; GO +ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [DF__Statistic__UnitT__4DE5C23E] DEFAULT ((0)) FOR [UnitTypeID]; GO +ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [DF__Statistic__Accou__4FCE0AB0] DEFAULT ((0)) FOR [AccountID]; GO +ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [DF__Statistic__Amoun__51B65322] DEFAULT ((0)) FOR [Amount]; GO +ALTER TABLE [ob].[StatisticsEntityReconciliationTarget] ADD CONSTRAINT [DF__Statistic__Entit__4644A076] DEFAULT ((0)) FOR [EntityID]; GO + +--------------------------------------------- + +--------------------------------------------- +-- ob.SystemSetting ------------------ +--------------------------------------------- +CREATE TABLE [ob].[SystemSetting] ( + [SystemSettingID] int NOT NULL, + [Name] nvarchar(100) NOT NULL, + [Description] nvarchar(400) NOT NULL, + [Value] nvarchar(max) NOT NULL, + [IsEditable] bit NOT NULL, + [ColumnType] int NOT NULL, + [DefaultValue] nvarchar(100) NOT NULL, + [IsEncrypted] bit NOT NULL, + PRIMARY KEY ([SystemSettingID]) +); +GO +ALTER TABLE [ob].[SystemSetting] ADD CONSTRAINT [DF_SYSTEMSETTING_VALUE] DEFAULT ('') FOR [Value]; GO +ALTER TABLE [ob].[SystemSetting] ADD CONSTRAINT [DF__SystemSett__Name__5E065017] DEFAULT ('') FOR [Name]; GO +ALTER TABLE [ob].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__Descr__5EFA7450] DEFAULT ('') FOR [Description]; GO +ALTER TABLE [ob].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__IsEdi__60E2BCC2] DEFAULT ((0)) FOR [IsEditable]; GO +ALTER TABLE [ob].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__Colum__61D6E0FB] DEFAULT ((0)) FOR [ColumnType]; GO +ALTER TABLE [ob].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__Defau__62CB0534] DEFAULT ('') FOR [DefaultValue]; GO +ALTER TABLE [ob].[SystemSetting] ADD CONSTRAINT [DF__SystemSet__IsEnc__6AA45E82] DEFAULT ((0)) FOR [IsEncrypted]; GO + +--------------------------------------------- +--------------------------------------------- +-- VIEWS +--------------------------------------------- + +-- ob.viewAllocationBasis +/************************************************************ +** Author: Joel Gerber +** Create Date: 7/29/2014 +** Description: Displays the basis values for each allocation and department +** Last Modified: 2014-07-29 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2014-09-05 JG Changing the way basis is linked to allocations +** 2 2014-09-11 JG Filter out deleted rows +** 3 2014-09-22 JG Adding Department Mapping Basis Views +** 4 2015-01-28 MS Adding support for YTD-driven basis +** 5 2015-08-06 CB D-02673 Added unittypeid to factaccount joins +*************************************************************/ +CREATE view [ob].[viewAllocationBasis] +AS + +/** Account Basis for Account Mapping***************************************************/ +select + DepartmentLevel.OBAllocationID, + DepartmentLevel.OBAllocationBasisID, + DepartmentLevel.DepartmentalBudgetID, + DepartmentLevel.DepartmentID, + DepartmentLevel.Total as BasisValue, + ROUND(coalesce (DepartmentLevel.Total/NULLIF(AllocationLevel.Total,0),0),4) as BasisPercentage +from + (select al.OBAllocationID, + al.OBAllocationBasisID, + db.DepartmentalBudgetID, + db.DepartmentID, + SUM(Total) as Total + from [clientob].[FactAllocationBasis] ab + inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID + inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationAccountMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID + inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID + inner join [clientob].[FactAccount] fa + on db.DepartmentalBudgetID=fa.DepartmentalBudgetID + and ab.AccountID=fa.AccountID + and ab.UnitTypeID=fa.UnitTypeID + inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID + where + dab.OBForecastDetailID<>100 --YTD + and TimeClassID=2 + and FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year') + and Total<>0 + and ab.IsDeleted=0 + group by + al.OBAllocationID, + db.DepartmentalBudgetID, + al.OBAllocationBasisID, + db.DepartmentID) as DepartmentLevel +inner join + (select al.OBAllocationID, + SUM(Total) as Total + from [clientob].[FactAllocationBasis] ab + inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID + inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationAccountMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID + inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID + inner join [clientob].[FactAccount] fa + on db.DepartmentalBudgetID=fa.DepartmentalBudgetID + and ab.AccountID=fa.AccountID + and ab.UnitTypeID=fa.UnitTypeID + inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID + where + dab.OBForecastDetailID<>100 --YTD + and TimeClassID=2 + and FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year') + and Total<>0 + and ab.IsDeleted=0 + group by + al.OBAllocationID) as AllocationLevel on DepartmentLevel.OBAllocationID=AllocationLevel.OBAllocationID + +UNION ALL + +/** Account Basis for Department Mapping***************************************************/ +select + DepartmentLevel.OBAllocationID, + DepartmentLevel.OBAllocationBasisID, + DepartmentLevel.DepartmentalBudgetID, + DepartmentLevel.DepartmentID, + DepartmentLevel.Total as BasisValue, + ROUND(coalesce (DepartmentLevel.Total/NULLIF(AllocationLevel.Total,0),0),4) as BasisPercentage + +from + (select al.OBAllocationID, + al.OBAllocationBasisID, + db.DepartmentalBudgetID, + db.DepartmentID, + SUM(Total) as Total + from [clientob].[FactAllocationBasis] ab + inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID + inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationDepartmentMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID + inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID + inner join [clientob].[FactAccount] fa + on db.DepartmentalBudgetID=fa.DepartmentalBudgetID + and ab.AccountID=fa.AccountID + and ab.UnitTypeID=fa.UnitTypeID + inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID + where + dab.OBForecastDetailID<>100 --YTD + and TimeClassID=2 + and FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year') + and Total<>0 + and ab.IsDeleted=0 + group by + al.OBAllocationID, + db.DepartmentalBudgetID, + al.OBAllocationBasisID, + db.DepartmentID) as DepartmentLevel +inner join + (select al.OBAllocationID, + SUM(Total) as Total + from [clientob].[FactAllocationBasis] ab + inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID + inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationDepartmentMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID + inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID + inner join [clientob].[FactAccount] fa + on db.DepartmentalBudgetID=fa.DepartmentalBudgetID + and ab.AccountID=fa.AccountID + and ab.UnitTypeID=fa.UnitTypeID + inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID + where + dab.OBForecastDetailID<>100 --YTD + and TimeClassID=2 + and FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year') + and Total<>0 + and ab.IsDeleted=0 + group by + al.OBAllocationID) as AllocationLevel on DepartmentLevel.OBAllocationID=AllocationLevel.OBAllocationID + +UNION ALL + +/** Financial Reporting Basis for Account Mapping***************************************************/ +select + DepartmentLevel.OBAllocationID, + DepartmentLevel.OBAllocationBasisID, + DepartmentLevel.DepartmentalBudgetID, + DepartmentLevel.DepartmentID, + DepartmentLevel.Total as BasisValue, + ROUND(coalesce (DepartmentLevel.Total/NULLIF(AllocationLevel.Total,0),0),4) as BasisPercentage + +from + (select al.OBAllocationID, + al.OBAllocationBasisID, + db.DepartmentalBudgetID, + db.DepartmentID, + SUM(Total) as Total + from [clientob].[FactAllocationFinancialReportingBasis] ab + inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID + inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationAccountMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID + inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID + inner join [clientob].[FactReportingMonthly] fa on db.DepartmentalBudgetID=fa.DepartmentalBudgetID and ab.FinancialReportingID=fa.FinancialReportingID + inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID + where + dab.OBForecastDetailID<>100 --YTD + and TimeClassID=2 + and FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year') + and Total<>0 + and ab.IsDeleted=0 + group by + al.OBAllocationID, + al.OBAllocationBasisID, + db.DepartmentalBudgetID, + db.DepartmentID) as DepartmentLevel +inner join + (select al.OBAllocationID, + SUM(Total) as Total + from [clientob].[FactAllocationFinancialReportingBasis] ab + inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID + inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationAccountMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID + inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID + inner join [clientob].[FactReportingMonthly] fa on db.DepartmentalBudgetID=fa.DepartmentalBudgetID and ab.FinancialReportingID=fa.FinancialReportingID + inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID + where + dab.OBForecastDetailID<>100 --YTD + and TimeClassID=2 + and FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year') + and Total<>0 + and ab.IsDeleted=0 + + group by + al.OBAllocationID) as AllocationLevel on DepartmentLevel.OBAllocationID=AllocationLevel.OBAllocationID + +UNION ALL + +/** Financial Reporting Basis for Department Mapping***************************************************/ +select + DepartmentLevel.OBAllocationID, + DepartmentLevel.OBAllocationBasisID, + DepartmentLevel.DepartmentalBudgetID, + DepartmentLevel.DepartmentID, + DepartmentLevel.Total as BasisValue, + ROUND(coalesce (DepartmentLevel.Total/NULLIF(AllocationLevel.Total,0),0),4) as BasisPercentage + +from + (select al.OBAllocationID, + al.OBAllocationBasisID, + db.DepartmentalBudgetID, + db.DepartmentID, + SUM(Total) as Total + from [clientob].[FactAllocationFinancialReportingBasis] ab + inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID + inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationDepartmentMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID + inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID + inner join [clientob].[FactReportingMonthly] fa on db.DepartmentalBudgetID=fa.DepartmentalBudgetID and ab.FinancialReportingID=fa.FinancialReportingID + inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID + where + dab.OBForecastDetailID<>100 --YTD + and TimeClassID=2 + and FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year') + and Total<>0 + and ab.IsDeleted=0 + + group by + al.OBAllocationID, + al.OBAllocationBasisID, + db.DepartmentalBudgetID, + db.DepartmentID) as DepartmentLevel +inner join + (select al.OBAllocationID, + SUM(Total) as Total + from [clientob].[FactAllocationFinancialReportingBasis] ab + inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID + inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationDepartmentMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID + inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID + inner join [clientob].[FactReportingMonthly] fa on db.DepartmentalBudgetID=fa.DepartmentalBudgetID and ab.FinancialReportingID=fa.FinancialReportingID + inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID + where + dab.OBForecastDetailID<>100 --YTD + and TimeClassID=2 + and FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year') + and Total<>0 + and ab.IsDeleted=0 + + group by + al.OBAllocationID) as AllocationLevel on DepartmentLevel.OBAllocationID=AllocationLevel.OBAllocationID + +UNION ALL + +/** Custom Basis ***************************************************/ +select + DepartmentLevel.OBAllocationID, + DepartmentLevel.OBAllocationBasisID, + DepartmentLevel.DepartmentalBudgetID, + DepartmentLevel.DepartmentID, + DepartmentLevel.Total as BasisValue, + ROUND(coalesce (DepartmentLevel.Total/NULLIF(AllocationLevel.Total,0),0),4) as BasisPercentage +from + (select + al.OBAllocationID, + al.OBAllocationBasisID, + db.DepartmentalBudgetID, + db.DepartmentID, + sum(BasisValue) as Total + from + [clientob].[FactAllocationCustomBasis] cb + inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=cb.OBAllocationBasisID + inner join [ob].[DimDepartmentalBudget] db on cb.DepartmentTargetID=db.DepartmentID + where + cb.isdeleted=0 + group by + al.OBAllocationID, + al.OBAllocationBasisID, + db.DepartmentalBudgetID, + db.DepartmentID) as DepartmentLevel +inner join + (select + al.OBAllocationID, + sum(BasisValue) as Total + from + [clientob].[FactAllocationCustomBasis] cb + inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=cb.OBAllocationBasisID + inner join [ob].[DimDepartmentalBudget] db on cb.DepartmentTargetID=db.DepartmentID + where + BasisValue>0 and cb.isdeleted=0 + group by + al.OBAllocationID) as AllocationLevel on DepartmentLevel.OBAllocationID=AllocationLevel.OBAllocationID + +UNION ALL + +/** YTD Account Basis for Account Mapping***************************************************/ +select + DepartmentLevel.OBAllocationID, + DepartmentLevel.OBAllocationBasisID, + DepartmentLevel.DepartmentalBudgetID, + DepartmentLevel.DepartmentID, + DepartmentLevel.Total as BasisValue, + ROUND(coalesce (DepartmentLevel.Total/NULLIF(AllocationLevel.Total,0),0),4) as BasisPercentage + +from + (select al.OBAllocationID, + al.OBAllocationBasisID, + db.DepartmentalBudgetID, + db.DepartmentID, + SUM(YTD) as Total + from [clientob].[FactAllocationBasis] ab + inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID + inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationAccountMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID + inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID + inner join [clientob].[FactAccount] fa + on db.DepartmentalBudgetID=fa.DepartmentalBudgetID + and ab.AccountID=fa.AccountID + and ab.UnitTypeID=fa.UnitTypeID + inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID + where + dab.OBForecastDetailID=100 --YTD + and TimeClassID=1 + and FiscalYearID=(select Setting from [dbo].[DBSetting] where Name='OB_Current_Year') + and YTD<>0 + and ab.IsDeleted=0 + group by + al.OBAllocationID, + db.DepartmentalBudgetID, + al.OBAllocationBasisID, + db.DepartmentID) as DepartmentLevel +inner join + (select al.OBAllocationID, + SUM(YTD) as Total + from [clientob].[FactAllocationBasis] ab + inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID + inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationAccountMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID + inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID + inner join [clientob].[FactAccount] fa + on db.DepartmentalBudgetID=fa.DepartmentalBudgetID + and ab.AccountID=fa.AccountID + and ab.UnitTypeID=fa.UnitTypeID + inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID + where + dab.OBForecastDetailID=100 --YTD + and TimeClassID=1 + and FiscalYearID=(select Setting from [dbo].[DBSetting] where Name='OB_Current_Year') + and YTD<>0 + and ab.IsDeleted=0 + group by + al.OBAllocationID) as AllocationLevel on DepartmentLevel.OBAllocationID=AllocationLevel.OBAllocationID + +UNION ALL + +/** YTD Account Basis for Department Mapping***************************************************/ +select + DepartmentLevel.OBAllocationID, + DepartmentLevel.OBAllocationBasisID, + DepartmentLevel.DepartmentalBudgetID, + DepartmentLevel.DepartmentID, + DepartmentLevel.Total as BasisValue, + ROUND(coalesce (DepartmentLevel.Total/NULLIF(AllocationLevel.Total,0),0),4) as BasisPercentage + +from + (select al.OBAllocationID, + al.OBAllocationBasisID, + db.DepartmentalBudgetID, + db.DepartmentID, + SUM(YTD) as Total + from [clientob].[FactAllocationBasis] ab + inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID + inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationDepartmentMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID + inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID + inner join [clientob].[FactAccount] fa + on db.DepartmentalBudgetID=fa.DepartmentalBudgetID + and ab.AccountID=fa.AccountID + and ab.UnitTypeID=fa.UnitTypeID + inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID + where + dab.OBForecastDetailID=100 --YTD + and TimeClassID=1 + and FiscalYearID=(select Setting from [dbo].[DBSetting] where Name='OB_Current_Year') + and YTD<>0 + and ab.IsDeleted=0 + group by + al.OBAllocationID, + db.DepartmentalBudgetID, + al.OBAllocationBasisID, + db.DepartmentID) as DepartmentLevel +inner join + (select al.OBAllocationID, + SUM(YTD) as Total + from [clientob].[FactAllocationBasis] ab + inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID + inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationDepartmentMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID + inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID + inner join [clientob].[FactAccount] fa + on db.DepartmentalBudgetID=fa.DepartmentalBudgetID + and ab.AccountID=fa.AccountID + and ab.UnitTypeID=fa.UnitTypeID + inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID + where + dab.OBForecastDetailID=100 --YTD + and TimeClassID=1 + and FiscalYearID=(select Setting from [dbo].[DBSetting] where Name='OB_Current_Year') + and YTD<>0 + and ab.IsDeleted=0 + group by + al.OBAllocationID) as AllocationLevel on DepartmentLevel.OBAllocationID=AllocationLevel.OBAllocationID + +UNION ALL + +/** YTD Financial Reporting Basis for Account Mapping***************************************************/ +select + DepartmentLevel.OBAllocationID, + DepartmentLevel.OBAllocationBasisID, + DepartmentLevel.DepartmentalBudgetID, + DepartmentLevel.DepartmentID, + DepartmentLevel.Total as BasisValue, + ROUND(coalesce (DepartmentLevel.Total/NULLIF(AllocationLevel.Total,0),0),4) as BasisPercentage + +from + (select al.OBAllocationID, + al.OBAllocationBasisID, + db.DepartmentalBudgetID, + db.DepartmentID, + SUM(YTD) as Total + from [clientob].[FactAllocationFinancialReportingBasis] ab + inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID + inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationAccountMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID + inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID + inner join [clientob].[FactReportingMonthly] fa on db.DepartmentalBudgetID=fa.DepartmentalBudgetID and ab.FinancialReportingID=fa.FinancialReportingID + inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID + where + dab.OBForecastDetailID=100 --YTD + and TimeClassID=1 + and FiscalYearID=(select Setting from [dbo].[DBSetting] where Name='OB_Current_Year') + and YTD<>0 + and ab.IsDeleted=0 + group by + al.OBAllocationID, + al.OBAllocationBasisID, + db.DepartmentalBudgetID, + db.DepartmentID) as DepartmentLevel +inner join + (select al.OBAllocationID, + SUM(YTD) as Total + from [clientob].[FactAllocationFinancialReportingBasis] ab + inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID + inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationAccountMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID + inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID + inner join [clientob].[FactReportingMonthly] fa on db.DepartmentalBudgetID=fa.DepartmentalBudgetID and ab.FinancialReportingID=fa.FinancialReportingID + inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID + where + dab.OBForecastDetailID=100 --YTD + and TimeClassID=1 + and FiscalYearID=(select Setting from [dbo].[DBSetting] where Name='OB_Current_Year') + and YTD<>0 + and ab.IsDeleted=0 + + group by + al.OBAllocationID) as AllocationLevel on DepartmentLevel.OBAllocationID=AllocationLevel.OBAllocationID + +UNION ALL + +/** YTD Financial Reporting Basis for Department Mapping***************************************************/ +select + DepartmentLevel.OBAllocationID, + DepartmentLevel.OBAllocationBasisID, + DepartmentLevel.DepartmentalBudgetID, + DepartmentLevel.DepartmentID, + DepartmentLevel.Total as BasisValue, + ROUND(coalesce (DepartmentLevel.Total/NULLIF(AllocationLevel.Total,0),0),4) as BasisPercentage + +from + (select al.OBAllocationID, + al.OBAllocationBasisID, + db.DepartmentalBudgetID, + db.DepartmentID, + SUM(YTD) as Total + from [clientob].[FactAllocationFinancialReportingBasis] ab + inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID + inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationDepartmentMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID + inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID + inner join [clientob].[FactReportingMonthly] fa on db.DepartmentalBudgetID=fa.DepartmentalBudgetID and ab.FinancialReportingID=fa.FinancialReportingID + inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID + where + dab.OBForecastDetailID=100 --YTD + and TimeClassID=1 + and FiscalYearID=(select Setting from [dbo].[DBSetting] where Name='OB_Current_Year') + and YTD<>0 + and ab.IsDeleted=0 + + group by + al.OBAllocationID, + al.OBAllocationBasisID, + db.DepartmentalBudgetID, + db.DepartmentID) as DepartmentLevel +inner join + (select al.OBAllocationID, + SUM(YTD) as Total + from [clientob].[FactAllocationFinancialReportingBasis] ab + inner join [ob].[DimOBAllocation] al on al.OBAllocationBasisID=ab.OBAllocationBasisID + inner join (select distinct DepartmentTargetID, OBAllocationID from [clientob].[FactAllocationDepartmentMapping] where IsDeleted=0) dm on al.OBAllocationID=dm.OBAllocationID + inner join [ob].[DimDepartmentalBudget] db on dm.DepartmentTargetID=db.DepartmentID + inner join [clientob].[FactReportingMonthly] fa on db.DepartmentalBudgetID=fa.DepartmentalBudgetID and ab.FinancialReportingID=fa.FinancialReportingID + inner join [ob].[DimOBAllocationBasis] dab on ab.OBAllocationBasisID=dab.OBAllocationBasisID + where + dab.OBForecastDetailID=100 --YTD + and TimeClassID=1 + and FiscalYearID=(select Setting from [dbo].[DBSetting] where Name='OB_Current_Year') + and YTD<>0 + and ab.IsDeleted=0 + + group by + al.OBAllocationID) as AllocationLevel on DepartmentLevel.OBAllocationID=AllocationLevel.OBAllocationID +GO + + +--------------------------------------------- + +-- ob.viewAllocationValues +create view [ob].[viewAllocationValues] +as +/***************************************************************************************** +** Author: Joel Gerber +** Create Date: 7/29/2014 +** Description: Displays the source and target departments and accounts and their allocation values +** Last Modified: 2014-07-29 +** GM Release: 2014.4 +***************************************************************************************** +** Change History +***************************************************************************************** +** CID Date Author WI Description +** 1 2014-09-04 JG Add the department filter +** 2 2014-09-11 JG Add the reversal +** 3 2014-09-22 JG Add ability to use a default (not specified) account for the department mapping +** 4 2014-09-24 JG Only reverse if reverse is being used +** 5 2014-09-25 JG Changing allocation to pull the allocation percentage +** 6 2014-09-26 JG Adding isReverse flag for reporting purposes +** 7 2014-09-30 JG Allowing non-dollars to be allocated +** 8 2015-02-17 JG Adding an isDeleted Filter to the filter table +** 9 2015-09-02 cbb D-03357 Backing out CID 7 because the model does not support non-dollar unittypes +** 10 2016-02-10 cbb B-11086 Adding execution order +*****************************************************************************************/ +--Account Mapping (Reverse) +select + aa.OBAllocationID, + dm.ExecutionOrder, -- CID 10 + fa.DepartmentalBudgetID as DepartmentalBudgetSourceID, + aa.DepartmentSourceID, + aa.AccountSourceID, + db2.DepartmentalBudgetID as DepartmentalBudgetTargetID, + aa.DepartmentID as DepartmentTargetID, + aa.AccountID as AccountTargetID, + fa.FiscalYearID, + fa.TimeClassId, + fa.UnitTypeID, + fa.DataTypeID, + 1 as isReverse, + -aa.AllocationPercentage as AllocationPercentage, + -fa.Month01*aa.AllocationPercentage as Month01, + -fa.Month02*aa.AllocationPercentage as Month02, + -fa.Month03*aa.AllocationPercentage as Month03, + -fa.Month04*aa.AllocationPercentage as Month04, + -fa.Month05*aa.AllocationPercentage as Month05, + -fa.Month06*aa.AllocationPercentage as Month06, + -fa.Month07*aa.AllocationPercentage as Month07, + -fa.Month08*aa.AllocationPercentage as Month08, + -fa.Month09*aa.AllocationPercentage as Month09, + -fa.Month10*aa.AllocationPercentage as Month10, + -fa.Month11*aa.AllocationPercentage as Month11, + -fa.Month12*aa.AllocationPercentage as Month12, + -fa.Total*aa.AllocationPercentage as Total +from + [clientob].[FactAccount] fa + inner join [ob].[DimDepartmentalBudget] db on fa.DepartmentalBudgetID=db.DepartmentalBudgetID + inner join [clientob].[FactAllocationAccountMapping] aa on db.DepartmentID=aa.DepartmentSourceID and fa.AccountID=aa.AccountSourceID + inner join [ob].[DimOBAllocation] dm on aa.OBAllocationID=dm.OBAllocationID -- CID 10 + inner join [ob].[DimDepartmentalBudget] db2 on db2.DepartmentID=aa.DepartmentID +where + TimeClassID=2 + and FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year') + /*** CID9 Start****************************************************************/ + and fa.UnitTypeID=34 + /*** CID9 END******************************************************************/ + and fa.Total<>0 + and aa.IsDeleted=0 + /*** CI4 Start - If reverse department is not specified, don't do anything ***/ + and aa.DepartmentID<>0 + /*** CI4 END******************************************************************/ + +UNION ALL + +--Account Mapping (Direct) +select + aa.OBAllocationID, + dm.ExecutionOrder, -- CID 10 + fa.DepartmentalBudgetID as DepartmentalBudgetSourceID, + aa.DepartmentSourceID, + aa.AccountSourceID, + db2.DepartmentalBudgetID as DepartmentalBudgetTargetID, + aa.DepartmentTargetID, + aa.AccountTargetID, + fa.FiscalYearID, + fa.TimeClassId, + fa.UnitTypeID, + fa.DataTypeID, + 0 as isReverse, + aa.AllocationPercentage, + fa.Month01*aa.AllocationPercentage as Month01, + fa.Month02*aa.AllocationPercentage as Month02, + fa.Month03*aa.AllocationPercentage as Month03, + fa.Month04*aa.AllocationPercentage as Month04, + fa.Month05*aa.AllocationPercentage as Month05, + fa.Month06*aa.AllocationPercentage as Month06, + fa.Month07*aa.AllocationPercentage as Month07, + fa.Month08*aa.AllocationPercentage as Month08, + fa.Month09*aa.AllocationPercentage as Month09, + fa.Month10*aa.AllocationPercentage as Month10, + fa.Month11*aa.AllocationPercentage as Month11, + fa.Month12*aa.AllocationPercentage as Month12, + fa.Total*aa.AllocationPercentage as Total +from + [clientob].[FactAccount] fa + inner join [ob].[DimDepartmentalBudget] db on fa.DepartmentalBudgetID=db.DepartmentalBudgetID + inner join [clientob].[FactAllocationAccountMapping] aa on db.DepartmentID=aa.DepartmentSourceID and fa.AccountID=aa.AccountSourceID + inner join [ob].[DimOBAllocation] dm on aa.OBAllocationID=dm.OBAllocationID -- CID 10 + inner join [ob].[DimDepartmentalBudget] db2 on db2.DepartmentID=aa.DepartmentTargetID +where + TimeClassID=2 + and FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year') + /*** CID9 Start****************************************************************/ + and fa.UnitTypeID=34 + /*** CID9 END******************************************************************/ + and fa.Total<>0 + and aa.IsDeleted=0 + +UNION ALL + +--Department Mapping (Reverse) +select + da.OBAllocationID, + dm.ExecutionOrder, -- CID 10 + fa.DepartmentalBudgetID as DepartmentalBudgetSourceID, + da.DepartmentSourceID, + fa.AccountID as AccountSourceID, + db2.DepartmentalBudgetID as DepartmentalBudgetTargetID, + da.DepartmentID as DepartmentTargetID, + /*** START CID 3 ***********************************************/ + ra.AccountID as AccountTargetID, + /*** END CID 3 *************************************************/ + fa.FiscalYearID, + fa.TimeClassId, + fa.UnitTypeID, + fa.DataTypeID, + 1 as isReverse, + -da.AllocationPercentage as AllocationPercentage, + -fa.Month01*da.AllocationPercentage as Month01, + -fa.Month02*da.AllocationPercentage as Month02, + -fa.Month03*da.AllocationPercentage as Month03, + -fa.Month04*da.AllocationPercentage as Month04, + -fa.Month05*da.AllocationPercentage as Month05, + -fa.Month06*da.AllocationPercentage as Month06, + -fa.Month07*da.AllocationPercentage as Month07, + -fa.Month08*da.AllocationPercentage as Month08, + -fa.Month09*da.AllocationPercentage as Month09, + -fa.Month10*da.AllocationPercentage as Month10, + -fa.Month11*da.AllocationPercentage as Month11, + -fa.Month12*da.AllocationPercentage as Month12, + -fa.Total*da.AllocationPercentage as Total +from + [clientob].[FactAccount] fa + inner join [ob].[DimDepartmentalBudget] db on fa.DepartmentalBudgetID=db.DepartmentalBudgetID + inner join [clientob].[FactAllocationDepartmentMapping] da on db.DepartmentID=da.DepartmentSourceID + inner join [ob].[DimOBAllocation] dm on da.OBAllocationID=dm.OBAllocationID -- CID 10 + inner join [ob].[DimDepartmentalBudget] db2 on db2.DepartmentID=da.DepartmentID + inner join [fw].[DimAccount] acc on fa.AccountID=acc.AccountID + /*** START CID 3 ***********************************************/ + inner join [fw].[DimAccount] ra on ra.AccountID= case when da.AccountID=0 then fa.AccountID else da.AccountID end + /*** END CID 3 *************************************************/ + inner join [clientob].[FactAllocationDepartmentMappingFilter] daf on daf.OBAllocationID=da.OBAllocationID and daf.FinancialReportingID=acc.OBDollarsFinancialReportingID +where + fa.TimeClassID=2 + and fa.FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year') + and fa.Total<>0 + /*** CID9 Start****************************************************************/ + and fa.UnitTypeID=34 + /*** CID9 END******************************************************************/ + and da.IsDeleted=0 + /*** CI4 Start - If reverse department is not specified, don't do anything ***/ + and da.DepartmentID<>0 + /*** CI4 END******************************************************************/ + /*** CID8 Start****************************************************************/ + and daf.IsDeleted=0 + /*** CID8 END******************************************************************/ + +UNION ALL + +--Department Mapping (Direct) +select + da.OBAllocationID, + dm.ExecutionOrder, + fa.DepartmentalBudgetID as DepartmentalBudgetSourceID, + da.DepartmentSourceID, + fa.AccountID as AccountSourceID, + db2.DepartmentalBudgetID as DepartmentalBudgetTargetID, + da.DepartmentTargetID, + /*** START CID 3 ***********************************************/ + ta.AccountID as AccountTargetID, + /*** END CID 3 *************************************************/ + fa.FiscalYearID, + fa.TimeClassId, + fa.UnitTypeID, + fa.DataTypeID, + 0 as isReverse, + da.AllocationPercentage, + fa.Month01*da.AllocationPercentage as Month01, + fa.Month02*da.AllocationPercentage as Month02, + fa.Month03*da.AllocationPercentage as Month03, + fa.Month04*da.AllocationPercentage as Month04, + fa.Month05*da.AllocationPercentage as Month05, + fa.Month06*da.AllocationPercentage as Month06, + fa.Month07*da.AllocationPercentage as Month07, + fa.Month08*da.AllocationPercentage as Month08, + fa.Month09*da.AllocationPercentage as Month09, + fa.Month10*da.AllocationPercentage as Month10, + fa.Month11*da.AllocationPercentage as Month11, + fa.Month12*da.AllocationPercentage as Month12, + fa.Total*da.AllocationPercentage as Total +from + [clientob].[FactAccount] fa + inner join [ob].[DimDepartmentalBudget] db on fa.DepartmentalBudgetID=db.DepartmentalBudgetID + inner join [clientob].[FactAllocationDepartmentMapping] da on db.DepartmentID=da.DepartmentSourceID + inner join [ob].[DimOBAllocation] dm on da.OBAllocationID=dm.OBAllocationID -- CID 10 + inner join [ob].[DimDepartmentalBudget] db2 on db2.DepartmentID=da.DepartmentTargetID + inner join [fw].[DimAccount] acc on fa.AccountID=acc.AccountID + /*** START CID 3 ***********************************************/ + inner join [fw].[DimAccount] ta on ta.AccountID= case when da.AccountTargetID=0 then fa.AccountID else da.AccountTargetID end + /*** END CID 3 *************************************************/ + inner join [clientob].[FactAllocationDepartmentMappingFilter] daf on daf.OBAllocationID=da.OBAllocationID and daf.FinancialReportingID=acc.OBDollarsFinancialReportingID +where + fa.TimeClassID=2 + and fa.FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year') + and fa.Total<>0 + /*** CID9 Start****************************************************************/ + and fa.UnitTypeID=34 + /*** CID9 END******************************************************************/ + and da.IsDeleted=0 + /*** CID8 Start****************************************************************/ + and daf.IsDeleted=0 + /*** CID8 END******************************************************************/ +GO + + +--------------------------------------------- + +-- ob.viewBudgetPlanStatus +create view ob.viewBudgetPlanStatus +as + select + d.DepartmentID, + d.IsOB as IsDepartmentOB, + d.IsActive as IsDepartmentActive, + d.IsVariable as IsDepartmentVariable, + cast(max(case when b.MemberGUID is null or p.PlanGUID is null then 0 else 1 end) as bit) as IsBudgetCreated, + cast(max(case when isnull(mt.Name, 'n/a') = 'GM Blank' then 0 else 1 end) as bit) as IsBudgetActive + from + fw.DimDepartment d + left join ob.DimDepartmentalBudget b on d.DepartmentID = b.DepartmentID + left join dbo.XPlan p on p.PlanGUID = b.MemberGUID and p.IsDeletedPlan = 0 + left join dbo.EMFModelTemplate mt on mt.ModelTemplateGUID = p.ModelTemplateGUID + group by + d.DepartmentID, + d.IsOB, + d.IsActive, + d.IsVariable +GO + + +--------------------------------------------- + +-- ob.viewDimAccountPH +CREATE VIEW [ob].[viewDimAccountPH] +AS +SELECT + grp5927549978BB41F1B481CF9F6F7BFE67.[AccountPHID] + ,grp5927549978BB41F1B481CF9F6F7BFE67.[Name] + ,grp5927549978BB41F1B481CF9F6F7BFE67.[MemberGUID] +, [grp5927549978BB41F1B481CF9F6F7BFE67].[Version], [grp5927549978BB41F1B481CF9F6F7BFE67].[HistoryItemGUID]FROM [ob].[DimAccountPH] grp5927549978BB41F1B481CF9F6F7BFE67 (readuncommitted) +GO + + +--------------------------------------------- + +-- ob.viewDimAdjustmentCategory +--Last Modified 1/6/2017 4:38 PM +CREATE VIEW [ob].[viewDimAdjustmentCategory] +AS +SELECT + grp0A9648AA978144AAA3E1A68E63558EDE.[AdjustmentCategoryID] + ,grp0A9648AA978144AAA3E1A68E63558EDE.[Name] + ,grp0A9648AA978144AAA3E1A68E63558EDE.[Description] + ,grp0A9648AA978144AAA3E1A68E63558EDE.[AdjustmentCategoryRollup] + ,grp0A9648AA978144AAA3E1A68E63558EDE.[BudgetConfigGUID] + ,grp0A9648AA978144AAA3E1A68E63558EDE.[TransactionID] + ,grp0A9648AA978144AAA3E1A68E63558EDE.[MemberGUID] + ,grp0A9648AA978144AAA3E1A68E63558EDE.[HistoryItemGUID] +FROM [ob].[DimAdjustmentCategory] grp0A9648AA978144AAA3E1A68E63558EDE (readuncommitted) +GO + + +--------------------------------------------- + +-- ob.viewDimDepartmentalBudget +CREATE VIEW [ob].[viewDimDepartmentalBudget] +AS +SELECT + +[FrameworkID], + COALESCE([Name],'') as [Name], +[LootID], +[DepartmentalBudgetID], +[DepartmentID], + COALESCE([DepartmentName],'') as [DepartmentName], +[SystemID], + COALESCE([System],'') as [System], +[SystemSortOrder], +[EntityID], + COALESCE([Entity],'') as [Entity], +[EntitySortOrder], +[DepartmentRollup1ID], + COALESCE([DepartmentRollup1],'') as [DepartmentRollup1], +[DepartmentRollup1SortOrder], +[DepartmentRollup2ID], + COALESCE([DepartmentRollup2],'') as [DepartmentRollup2], +[DepartmentRollup2SortOrder], +[DepartmentRollup3ID], + COALESCE([DepartmentRollup3],'') as [DepartmentRollup3], +[DepartmentRollup3SortOrder], +[DepartmentRollup4ID], +[GMTestFWName], +[GMTestFWDateCreated], + COALESCE([DepartmentRollup4],'') as [DepartmentRollup4], +[DepartmentRollup4SortOrder], +[BaseYear], +[DepartmentRollup5ID], + COALESCE([DepartmentRollup5],'') as [DepartmentRollup5], +[Director], +[DepartmentRollup5SortOrder], +[DepartmentRollup6ID], +[HasAttachments], +[LastModified], + COALESCE([DepartmentRollup6],'') as [DepartmentRollup6], +[DepartmentRollup6SortOrder], +[Manager], +[MonthsLoaded], +[ResearchDepartmentCategoryID], + COALESCE([ResearchDepartmentCategoryName],'') as [ResearchDepartmentCategoryName], +[OBActivePlans], +[OpenDate], +[ResearchDepartmentCategorySortOrder], +[IsVariable], +[MemberGUID], +[VicePresident], +[HistoryItemGUID], +[BaseYear1], +[BudgetStatus], +[WorkedHrsperUOSProjection], +[WorkedHrsperUOSBudget], +[FTEApprovalOverride], +[HourType], +[TargetType], +[Admin], +[Finance], +[ContractLaborSkillMix], +[StartYear], +[NumberofYears], +[VariableProjectionMethod], +[HideNotSpecified], +[HourTypeFixed], +[MRVicePresident], +[MRDirector], +[MRManager], +[ReadOnly], +[WriteDeny], +[EntityDefaultWorkWeekID], +[OBDirector], +[OBManager], +[OBVicePresident], +[SecureGroupID], +[VariablehrsperUOS], +[VariablehrsperUOStarget], +[BudgetedFixedFTEs], +[BudgetedVariableFTEs], +[UOSchangeyy], +[ExcessofRevandExpchangeyy], +[VariablehrsperUOSActualYTD], +[VariablehrsperUOStargetCurrentYr], + COALESCE([DepartmentCode],'') as [DepartmentCode] ,[Version] + +FROM [ob].[DimDepartmentalBudget] (readuncommitted) +GO + + +--------------------------------------------- + +-- ob.viewDimDepartmentalBudgetPH_auto +CREATE VIEW [ob].[viewDimDepartmentalBudgetPH_auto] +AS +SELECT + grpD3537B4CDBAB409B91F013D18B84C17C.[MemberGUID] + ,grpD3537B4CDBAB409B91F013D18B84C17C.[DepartmentalBudgetPHID] + ,grpD3537B4CDBAB409B91F013D18B84C17C.[Name] + ,grpD3537B4CDBAB409B91F013D18B84C17C.[IsConstant] +, [grpD3537B4CDBAB409B91F013D18B84C17C].[Version], [grpD3537B4CDBAB409B91F013D18B84C17C].[HistoryItemGUID]FROM [ob].[DimDepartmentalBudgetPH] grpD3537B4CDBAB409B91F013D18B84C17C (readuncommitted) +GO + + +--------------------------------------------- + +-- ob.viewDimDepartmentalBudget_source +CREATE VIEW [ob].[viewDimDepartmentalBudget_source] +AS +SELECT + grp3321230B396444078881D601D47C5275.[DepartmentalBudgetID] + ,grp3321230B396444078881D601D47C5275.[MemberGUID] + ,grp3321230B396444078881D601D47C5275.[HistoryItemGUID] + ,2 AS [FrameworkID] + ,ISNULL([DEPT].[Name], 'Not Specified') as [Name] + ,ISNULL([DEPT].[Name], 'Not Specified') as [DepartmentName] + ,ISNULL([DEPT].[SystemID], 0) as [SystemID] + ,ISNULL([DEPT].[System], 'Not Specified') as [System] + ,ISNULL([DEPT].[SystemSortOrder], 0) as [SystemSortOrder] + ,ISNULL([DEPT].[EntityID], 0) as [EntityID] + ,ISNULL([DEPT].[Entity], 'Not Specified') as [Entity] + ,ISNULL([DEPT].[EntitySortOrder], 0) as [EntitySortOrder] + ,ISNULL([DEPT].[DepartmentRollup1ID], 0) as [DepartmentRollup1ID] + ,ISNULL([DEPT].[DepartmentRollup1], 'Not Specified') as [DepartmentRollup1] + ,ISNULL([DEPT].[DepartmentRollup1SortOrder], 0) as [DepartmentRollup1SortOrder] + ,ISNULL([DEPT].[DepartmentRollup2ID], 0) as [DepartmentRollup2ID] + ,ISNULL([DEPT].[DepartmentRollup2], 'Not Specified') as [DepartmentRollup2] + ,ISNULL([DEPT].[DepartmentRollup2SortOrder], 0) as [DepartmentRollup2SortOrder] + ,ISNULL([DEPT].[DepartmentRollup3ID], 0) as [DepartmentRollup3ID] + ,ISNULL([DEPT].[DepartmentRollup3], 'Not Specified') as [DepartmentRollup3] + ,ISNULL([DEPT].[DepartmentRollup3SortOrder], 0) as [DepartmentRollup3SortOrder] + ,ISNULL([DEPT].[DepartmentRollup4ID], 0) as [DepartmentRollup4ID] + ,ISNULL([DEPT].[DepartmentRollup4], 'Not Specified') as [DepartmentRollup4] + ,ISNULL([DEPT].[DepartmentRollup4SortOrder], 0) as [DepartmentRollup4SortOrder] + ,ISNULL([DEPT].[DepartmentRollup5ID], 0) as [DepartmentRollup5ID] + ,ISNULL([DEPT].[DepartmentRollup5], 'Not Specified') as [DepartmentRollup5] + ,ISNULL([DEPT].[DepartmentRollup5SortOrder], 0) as [DepartmentRollup5SortOrder] + ,ISNULL([DEPT].[DepartmentRollup6ID], 0) as [DepartmentRollup6ID] + ,ISNULL([DEPT].[DepartmentRollup6], 'Not Specified') as [DepartmentRollup6] + ,ISNULL([DEPT].[DepartmentRollup6SortOrder], 0) as [DepartmentRollup6SortOrder] + ,ISNULL([DEPT].[ResearchDepartmentCategoryID], 0) as [ResearchDepartmentCategoryID] + ,ISNULL([DEPT].[ResearchDepartmentCategoryName], 'Not Specified') as [ResearchDepartmentCategoryName] + ,ISNULL([DEPT].[ResearchDepartmentCategorySortOrder], 0) as [ResearchDepartmentCategorySortOrder] + ,ISNULL([DEPT].[IsVariable], 0) as [IsVariable] + ,ISNULL([DEPT].[WorkWeekID], 0) as [EntityDefaultWorkWeekID] + ,ISNULL([DEPT].[SecureGroupID], 0) as [SecureGroupID] + ,ISNULL([DEPT].[DepartmentCode], 'Not Specified') as [DepartmentCode] + ,ISNULL([DimXP].[PlanID], 0) as [LootID] +, [grp3321230B396444078881D601D47C5275].[Version]FROM [ob].[DimDepartmentalBudget] grp3321230B396444078881D601D47C5275 (readuncommitted) + INNER JOIN [fw].[viewDimDepartment] [DEPT] on [DEPT].[DepartmentID] = [grp3321230B396444078881D601D47C5275].[DepartmentID] + INNER JOIN [fw].[viewDimXPlan_auto] [DimXP] on [DimXP].[MemberGUID] = [grp3321230B396444078881D601D47C5275].[MemberGUID] +GO + + +--------------------------------------------- + +-- ob.viewDimExceptions +CREATE VIEW [ob].[viewDimExceptions] +AS +SELECT + grpE6761F5FBF9A400B9432BFA871B53805.[OBExceptionsID] + ,grpE6761F5FBF9A400B9432BFA871B53805.[Name] + ,grpE6761F5FBF9A400B9432BFA871B53805.[Severity] + ,grpE6761F5FBF9A400B9432BFA871B53805.[Model] + ,grpE6761F5FBF9A400B9432BFA871B53805.[SortOrder] + ,grpE6761F5FBF9A400B9432BFA871B53805.[ViewName] + ,grpE6761F5FBF9A400B9432BFA871B53805.[TransactionID] + ,grpE6761F5FBF9A400B9432BFA871B53805.[MemberGUID] + ,grpE6761F5FBF9A400B9432BFA871B53805.[HistoryItemGUID] + ,grpE6761F5FBF9A400B9432BFA871B53805.[Description] + ,grpE6761F5FBF9A400B9432BFA871B53805.[Resolution] + ,coalesce(grpE6761F5FBF9A400B9432BFA871B53805.[FullName],'') as [FullName] +FROM [ob].[DimOBExceptions] grpE6761F5FBF9A400B9432BFA871B53805 (readuncommitted) +GO + + +--------------------------------------------- + +-- ob.viewDimFinancialReporting +CREATE VIEW [ob].[viewDimFinancialReporting] +AS +SELECT + +[FinancialReportingID], +[Statement], +[Section], +[LineName], + COALESCE([Name],'') as [Name], +[IsMappable], +[SortOrder], +[ConsolidatedFinancialReportingID], +[ConsolidatedIsInverted], + COALESCE([StatementMappabilityFilterParameter],'') as [StatementMappabilityFilterParameter], + COALESCE([ConsolidatedFinancialReporting],'') as [ConsolidatedFinancialReporting], +[ConsolidatedFinancialReportingSortOrder], +[ConsolidatedInversion], +[DisplayFormat], +[IsExpense], +[IsRequired], +[IsVolume], +[IsFTERollup], +[IsEditable], +[MemberGUID], +[HistoryItemGUID], + COALESCE([ProjectionMethod],'') as [ProjectionMethod], + COALESCE([SpreadMethod],'') as [SpreadMethod] +FROM [ob].[DimFinancialReporting] (readuncommitted) +GO + + +--------------------------------------------- + +-- ob.viewDimFinancialReportingPH +CREATE VIEW [ob].[viewDimFinancialReportingPH] +AS +SELECT + grp6BAC2BD76D3C4C249EA077E4A3B60870.[FinancialReportingPHID] + ,grp6BAC2BD76D3C4C249EA077E4A3B60870.[Name] + ,grp6BAC2BD76D3C4C249EA077E4A3B60870.[MemberGUID] + ,grp6BAC2BD76D3C4C249EA077E4A3B60870.[HistoryItemGUID] +FROM [ob].[DimFinancialReportingPH] grp6BAC2BD76D3C4C249EA077E4A3B60870 (readuncommitted) +GO + + +--------------------------------------------- + +-- ob.viewDimFinancialReporting_source +CREATE VIEW [ob].[viewDimFinancialReporting_source] +AS +SELECT + grp54CF5FA828E84C28B9227B92B8090EEE.[FinancialReportingID] + ,grp54CF5FA828E84C28B9227B92B8090EEE.[ConsolidatedInversion] + ,grp54CF5FA828E84C28B9227B92B8090EEE.[MemberGUID] + ,grp54CF5FA828E84C28B9227B92B8090EEE.[HistoryItemGUID] + ,grp54CF5FA828E84C28B9227B92B8090EEE.[ProjectionMethod] + ,grp54CF5FA828E84C28B9227B92B8090EEE.[SpreadMethod] + ,[grp54CF5FA828E84C28B9227B92B8090EEE].[Statement] + ' - ' + [grp54CF5FA828E84C28B9227B92B8090EEE].[Section] + ' - ' + [grp54CF5FA828E84C28B9227B92B8090EEE].[LineName] AS [Name] + ,[grp54CF5FA828E84C28B9227B92B8090EEE].[Statement] + ' - ' + [grp54CF5FA828E84C28B9227B92B8090EEE].[IsMappable] AS [StatementMappabilityFilterParameter] + ,ISNULL([CONSFINREP].[Name], 'Not Specified') as [ConsolidatedFinancialReporting] + ,ISNULL([CONSFINREP].[SortOrder], 0) as [ConsolidatedFinancialReportingSortOrder] +FROM [ob].[DimFinancialReporting] grp54CF5FA828E84C28B9227B92B8090EEE (readuncommitted) + INNER JOIN [fw].[viewDimConsolidatedFinancialReporting] [CONSFINREP] on [CONSFINREP].[ConsolidatedFinancialReportingID] = [grp54CF5FA828E84C28B9227B92B8090EEE].[ConsolidatedFinancialReportingID] +GO + + +--------------------------------------------- + +-- ob.viewDimGlobalStatisticRollup +CREATE VIEW [ob].[viewDimGlobalStatisticRollup] +AS +SELECT + grp720F3737CE7D4C0691B695FFCF7BA929.[StatisticRollupID] + ,grp720F3737CE7D4C0691B695FFCF7BA929.[Name] + ,grp720F3737CE7D4C0691B695FFCF7BA929.[MemberGUID] +FROM [ob].[DimGlobalStatisticRollup] grp720F3737CE7D4C0691B695FFCF7BA929 (readuncommitted) +GO + + +--------------------------------------------- + +-- ob.viewDimGlobalStatisticsPlanPH +CREATE VIEW [ob].[viewDimGlobalStatisticsPlanPH] +AS +SELECT + grpC6B7D58A47914B2BB0BDDE89ABBD2900.[OBGlobalStatsPlanPHID] + ,grpC6B7D58A47914B2BB0BDDE89ABBD2900.[Name] + ,grpC6B7D58A47914B2BB0BDDE89ABBD2900.[MemberGUID] + ,grpC6B7D58A47914B2BB0BDDE89ABBD2900.[HistoryItemGUID] +FROM [ob].[DimGlobalStatisticsPlanPH] grpC6B7D58A47914B2BB0BDDE89ABBD2900 (readuncommitted) +GO + + +--------------------------------------------- + +-- ob.viewDimOBAllocation +--Last Modified 2/26/2016 5:46 PM +CREATE VIEW [ob].[viewDimOBAllocation] +AS +SELECT + grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB.[OBAllocationID] + ,grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB.[Name] + ,grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB.[Type] + ,grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB.[OBAllocationBasisID] + ,grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB.[AlwaysUseBasis] + ,grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB.[TransactionID] + ,grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB.[MemberGUID] + ,grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB.[HistoryItemGUID] + ,grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB.[ExecutionOrder] + ,ISNULL([OBALLOCATIONBASIS].[Name], 'Not Specified') as [AllocationBasisName] +FROM [ob].[DimOBAllocation] grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB (readuncommitted) + INNER JOIN [ob].[viewDimOBAllocationBasis] [OBALLOCATIONBASIS] on [OBALLOCATIONBASIS].[OBAllocationBasisID] = [grpF4D7BA87C3AB4F3DAB5E69F8990EBBFB].[OBAllocationBasisID] +GO + + +--------------------------------------------- + +-- ob.viewDimOBAllocationBasis +CREATE VIEW [ob].[viewDimOBAllocationBasis] +AS +SELECT + grpC089980B2C6046C1842FCC918B7F4A76.[OBAllocationBasisID] + ,grpC089980B2C6046C1842FCC918B7F4A76.[Name] + ,grpC089980B2C6046C1842FCC918B7F4A76.[TransactionID] + ,grpC089980B2C6046C1842FCC918B7F4A76.[OBForecastDetailID] + ,grpC089980B2C6046C1842FCC918B7F4A76.[MemberGUID] + ,grpC089980B2C6046C1842FCC918B7F4A76.[HistoryItemGUID] + ,grpC089980B2C6046C1842FCC918B7F4A76.[Category] +FROM [ob].[DimOBAllocationBasis] grpC089980B2C6046C1842FCC918B7F4A76 (readuncommitted) +GO + + +--------------------------------------------- + +-- ob.viewDimOBForecastDetail +CREATE VIEW [ob].[viewDimOBForecastDetail] +AS +SELECT + +[OBForecastDetailID], +[Category], +[Name], +[SortOrder], +[UnitTypeID], + COALESCE([UnitType],'') as [UnitType], +[DriverID], + COALESCE([Driver],'') as [Driver], +[IsSalaryDriver], +[IsRevenueDriver], +[AccountID], + COALESCE([Account],'') as [Account], +[SecondaryAccountID], + COALESCE([SecondaryAccount],'') as [SecondaryAccount], +[TransactionID], +[MemberGUID], +[HistoryItemGUID], +[Code], +[ForecastDetailRollup], +[VolumeTarget], +[IsMROnly], +[IsVariable] +FROM [ob].[DimOBForecastDetail] (readuncommitted) +GO + + +--------------------------------------------- + +-- ob.viewDimOBForecastDetailDriver +CREATE VIEW [ob].[viewDimOBForecastDetailDriver] as +select + OBForecastDetailID as OBForecastDetailDriverSelectionID, + Name, + MemberGUID, + HistoryItemGUID, + TransactionID +from [ob].[DimOBForecastDetail] +GO + + +--------------------------------------------- + +-- ob.viewDimOBForecastDetailDriver_auto +CREATE VIEW [ob].[viewDimOBForecastDetailDriver_auto] +AS +SELECT + grp95352FFAD8B04CA0A70AE8BBCB6CF67D.[OBForecastDetailDriverSelectionID] + ,grp95352FFAD8B04CA0A70AE8BBCB6CF67D.[Name] + ,grp95352FFAD8B04CA0A70AE8BBCB6CF67D.[HistoryItemGUID] + ,grp95352FFAD8B04CA0A70AE8BBCB6CF67D.[MemberGUID] + ,grp95352FFAD8B04CA0A70AE8BBCB6CF67D.[TransactionID] +FROM [ob].[viewDimOBForecastDetailDriver] grp95352FFAD8B04CA0A70AE8BBCB6CF67D +GO + + +--------------------------------------------- + +-- ob.viewDimOBForecastDetailPH +CREATE VIEW [ob].[viewDimOBForecastDetailPH] +AS +SELECT + grp73D1EC9F68144CC1BCDC23C23514DA13.[OBForecastDetailPHID] + ,grp73D1EC9F68144CC1BCDC23C23514DA13.[Name] + ,grp73D1EC9F68144CC1BCDC23C23514DA13.[MemberGUID] + ,grp73D1EC9F68144CC1BCDC23C23514DA13.[HistoryItemGUID] + ,grp73D1EC9F68144CC1BCDC23C23514DA13.[TransactionID] +FROM [ob].[DimOBForecastDetailPH] grp73D1EC9F68144CC1BCDC23C23514DA13 (readuncommitted) +GO + + +--------------------------------------------- + +-- ob.viewDimOBForecastDetail_source +CREATE VIEW [ob].[viewDimOBForecastDetail_source] +AS +SELECT + grpEEE051AAC24A4A73A3160CBD21350A21.[OBForecastDetailID] + ,grpEEE051AAC24A4A73A3160CBD21350A21.[TransactionID] + ,grpEEE051AAC24A4A73A3160CBD21350A21.[MemberGUID] + ,grpEEE051AAC24A4A73A3160CBD21350A21.[HistoryItemGUID] + ,ISNULL([UNITTYPE].[Name], 'Not Specified') as [UnitType] + ,ISNULL([viewDimOBFor].[Name], 'Not Specified') as [Driver] + ,ISNULL([ACCT].[Name], 'Not Specified') as [Account] + ,ISNULL([ACCT_1].[Name], 'Not Specified') as [SecondaryAccount] +FROM [ob].[DimOBForecastDetail] grpEEE051AAC24A4A73A3160CBD21350A21 (readuncommitted) + INNER JOIN [fw].[viewDimUnitType] [UNITTYPE] on [UNITTYPE].[UnitTypeID] = [grpEEE051AAC24A4A73A3160CBD21350A21].[UnitTypeID] + INNER JOIN [ob].[viewDimOBForecastDetailDriver_auto] [viewDimOBFor] on [viewDimOBFor].[OBForecastDetailDriverSelectionID] = [grpEEE051AAC24A4A73A3160CBD21350A21].[DriverID] + INNER JOIN [fw].[viewDimAccount] [ACCT] on [ACCT].[AccountID] = [grpEEE051AAC24A4A73A3160CBD21350A21].[AccountID] + INNER JOIN [fw].[viewDimAccount] [ACCT_1] on [ACCT_1].[AccountID] = [grpEEE051AAC24A4A73A3160CBD21350A21].[SecondaryAccountID] +GO + + +--------------------------------------------- + +-- ob.viewDimOBGlobalStatistics +CREATE VIEW [ob].[viewDimOBGlobalStatistics] +AS +SELECT + + COALESCE([Name],'') as [Name], +[OBGlobalStatisticID], +[TransactionID], +[MemberGUID], +[HistoryItemGUID], + COALESCE([AccountDescription],'') as [AccountDescription], + COALESCE([AccountCode],'') as [AccountCode], +[AccountID], + COALESCE([DepartmentCode],'') as [DepartmentCode], + COALESCE([Account],'') as [Account], +[DepartmentID], + COALESCE([Department],'') as [Department], +[OBForecastDetailID], + COALESCE([OBForecastDetail],'') as [OBForecastDetail], +[LOSLinkID], + COALESCE([LOSLink],'') as [LOSLink], + COALESCE([PatientClass],'') as [PatientClass], + COALESCE([OBPayor],'') as [OBPayor], + COALESCE([OBPayorGroup],'') as [OBPayorGroup], + COALESCE([OBUnitsFinancialReportingName],'') as [OBUnitsFinancialReportingName], + COALESCE([OBUnitsFinancialReportingLineName],'') as [OBUnitsFinancialReportingLineName], + COALESCE([FillinSection],'') as [FillinSection] +FROM [ob].[DimOBGlobalStatistics] (readuncommitted) +GO + + +--------------------------------------------- + +-- ob.viewDimOBGlobalStatisticsPH +CREATE VIEW [ob].[viewDimOBGlobalStatisticsPH] +AS +SELECT + grp859651793B9E4DC5A841C41AD656A89C.[OBGlobalStatisticsPHID] + ,grp859651793B9E4DC5A841C41AD656A89C.[Name] + ,grp859651793B9E4DC5A841C41AD656A89C.[MemberGUID] + ,grp859651793B9E4DC5A841C41AD656A89C.[HistoryItemGUID] + ,grp859651793B9E4DC5A841C41AD656A89C.[TransactionID] +FROM [ob].[DimOBGlobalStatisticsPH] grp859651793B9E4DC5A841C41AD656A89C (readuncommitted) +GO + + +--------------------------------------------- + +-- ob.viewDimOBGlobalStatisticsPlan +CREATE VIEW [ob].[viewDimOBGlobalStatisticsPlan] +AS +SELECT + +[OBGlobalStatisticsPlanID], +[Name], +[EntityID], + COALESCE([Entity],'') as [Entity], +[LootID], +[IsDeleted], +[HistoryItemGUID], +[MemberGUID], +[TransactionID], +[SecureGroupID], +[BaseYear], +[MonthsLoaded], +[StartYear], +[NumberofYears], +[FrameworkID] +FROM [ob].[DimOBGlobalStatisticsPlan] (readuncommitted) +GO + + +--------------------------------------------- + +-- ob.viewDimOBGlobalStatisticsPlan_source +CREATE VIEW [ob].[viewDimOBGlobalStatisticsPlan_source] +AS +SELECT + grp5CAD0D676A7C4C8D80A34AAB99E6C79D.[OBGlobalStatisticsPlanID] + ,grp5CAD0D676A7C4C8D80A34AAB99E6C79D.[HistoryItemGUID] + ,grp5CAD0D676A7C4C8D80A34AAB99E6C79D.[MemberGUID] + ,grp5CAD0D676A7C4C8D80A34AAB99E6C79D.[TransactionID] + ,grp5CAD0D676A7C4C8D80A34AAB99E6C79D.[SecureGroupID] + ,2 AS [FrameworkID] + ,ISNULL([ENT].[Name], 'Not Specified') as [Entity] + ,ISNULL([DimXP].[PlanID], 0) as [LootID] + ,ISNULL([DimXP].[IsDeleted], 0) as [IsDeleted] +FROM [ob].[DimOBGlobalStatisticsPlan] grp5CAD0D676A7C4C8D80A34AAB99E6C79D (readuncommitted) + INNER JOIN [fw].[viewDimEntity] [ENT] on [ENT].[EntityID] = [grp5CAD0D676A7C4C8D80A34AAB99E6C79D].[EntityID] + INNER JOIN [fw].[viewDimXPlan_auto] [DimXP] on [DimXP].[MemberGUID] = [grp5CAD0D676A7C4C8D80A34AAB99E6C79D].[MemberGUID] +GO + + +--------------------------------------------- + +-- ob.viewDimOBGlobalStatistics_source +CREATE VIEW [ob].[viewDimOBGlobalStatistics_source] +AS +SELECT + grpEDB4F13AA36044A48FFB77C37AFA87F5.[Name] + ,grpEDB4F13AA36044A48FFB77C37AFA87F5.[OBGlobalStatisticID] + ,grpEDB4F13AA36044A48FFB77C37AFA87F5.[TransactionID] + ,grpEDB4F13AA36044A48FFB77C37AFA87F5.[MemberGUID] + ,grpEDB4F13AA36044A48FFB77C37AFA87F5.[HistoryItemGUID] + ,grpEDB4F13AA36044A48FFB77C37AFA87F5.[FillinSection] + ,ISNULL([ACCT].[Description], 'Not Specified') as [AccountDescription] + ,ISNULL([ACCT].[AccountCode], 'Not Specified') as [AccountCode] + ,ISNULL([ACCT].[Name], 'Not Specified') as [Account] + ,ISNULL([ACCT].[PatientClass], 'Not Specified') as [PatientClass] + ,ISNULL([ACCT].[OBPayor], 'Not Specified') as [OBPayor] + ,ISNULL([ACCT].[OBPayorGroup], 'Not Specified') as [OBPayorGroup] + ,ISNULL([ACCT].[OBUnitsFinancialReporting], 'Not Specified') as [OBUnitsFinancialReportingName] + ,ISNULL([ACCT].[OBUnitsFinancialReportingLineName], 'Not Specified') as [OBUnitsFinancialReportingLineName] + ,ISNULL([ACCT_1].[Name], 'Not Specified') as [LOSLink] + ,ISNULL([DEPT].[DepartmentCode], 'Not Specified') as [DepartmentCode] + ,ISNULL([DEPT].[Name], 'Not Specified') as [Department] + ,ISNULL([OBFORECASTDETAIL].[Name], 'Not Specified') as [OBForecastDetail] +FROM [ob].[DimOBGlobalStatistics] grpEDB4F13AA36044A48FFB77C37AFA87F5 (readuncommitted) + INNER JOIN [fw].[viewDimAccount] [ACCT] on [ACCT].[AccountID] = [grpEDB4F13AA36044A48FFB77C37AFA87F5].[AccountID] + INNER JOIN [fw].[viewDimAccount] [ACCT_1] on [ACCT_1].[AccountID] = [grpEDB4F13AA36044A48FFB77C37AFA87F5].[LOSLinkID] + INNER JOIN [fw].[viewDimDepartment] [DEPT] on [DEPT].[DepartmentID] = [grpEDB4F13AA36044A48FFB77C37AFA87F5].[DepartmentID] + INNER JOIN [ob].[viewDimOBForecastDetail] [OBFORECASTDETAIL] on [OBFORECASTDETAIL].[OBForecastDetailID] = [grpEDB4F13AA36044A48FFB77C37AFA87F5].[OBForecastDetailID] +GO + + +--------------------------------------------- + +-- ob.viewDimOBReimbursementPlan +CREATE VIEW [ob].[viewDimOBReimbursementPlan] +AS +SELECT + +[OBReimbursementPlanID], +[Name], +[MemberGUID], +[HistoryItemGUID], +[LootID], +[FrameworkID], +[EntityID], + COALESCE([Entity],'') as [Entity], +[EntitySortOrder], +[NameCalc], +[BaseYear], +[StartYear], +[NumberofYears], +[SecureGroupID], +[MonthsLoaded] +FROM [ob].[DimOBReimbursementPlan] (readuncommitted) +GO + + +--------------------------------------------- + +-- ob.viewDimOBReimbursementPlanPH +CREATE VIEW [ob].[viewDimOBReimbursementPlanPH] +AS +SELECT + grpAC3B5D29356247F5BDDFCFC8D09E9F17.[OBReimbursementPlanPHID] + ,grpAC3B5D29356247F5BDDFCFC8D09E9F17.[Name] + ,grpAC3B5D29356247F5BDDFCFC8D09E9F17.[MemberGUID] + ,grpAC3B5D29356247F5BDDFCFC8D09E9F17.[HistoryItemGUID] +FROM [ob].[DimOBReimbursementPlanPH] grpAC3B5D29356247F5BDDFCFC8D09E9F17 (readuncommitted) +GO + + +--------------------------------------------- + +-- ob.viewDimOBReimbursementPlan_source +CREATE VIEW [ob].[viewDimOBReimbursementPlan_source] +AS +SELECT + grpBCD22BB1EBDC4C07A9DB2AB6AB061F79.[OBReimbursementPlanID] + ,grpBCD22BB1EBDC4C07A9DB2AB6AB061F79.[MemberGUID] + ,grpBCD22BB1EBDC4C07A9DB2AB6AB061F79.[HistoryItemGUID] + ,2 AS [FrameworkID] + ,ISNULL([DimXP].[PlanID], 0) as [LootID] + ,ISNULL([ENT].[Name], 'Not Specified') as [Entity] + ,ISNULL([ENT].[SortOrder], 0) as [EntitySortOrder] + ,ISNULL([ENT].[SecureGroupID], 0) as [SecureGroupID] +FROM [ob].[DimOBReimbursementPlan] grpBCD22BB1EBDC4C07A9DB2AB6AB061F79 (readuncommitted) + INNER JOIN [fw].[viewDimXPlan_auto] [DimXP] on [DimXP].[MemberGUID] = [grpBCD22BB1EBDC4C07A9DB2AB6AB061F79].[MemberGUID] + INNER JOIN [fw].[viewDimEntity] [ENT] on [ENT].[EntityID] = [grpBCD22BB1EBDC4C07A9DB2AB6AB061F79].[EntityID] +GO + + +--------------------------------------------- + +-- ob.viewDimOBServiceLinePlan +CREATE VIEW [ob].[viewDimOBServiceLinePlan] +AS +SELECT + +[OBServiceLinePlanID], +[EntityID], +[Name], +[FrameworkID], +[LootID], +[IsDeleted], + COALESCE([Entity],'') as [Entity], +[EntitySortOrder], +[SecureGroupID], +[TransactionID], +[MemberGUID], +[HistoryItemGUID], +[BaseYear], +[MonthsLoaded], +[StartYear], +[NumberofYears], +[InpatientVolumeBudgetYear], +[ClinicVolumeBudgetYear], +[ClinicVolumeProjectedYear], +[EDVolumeBudgetYear], +[EDVolumeProjectedYear], +[InpatientVolumeProjectedYear], +[ObservationVolumeBudgetYear], +[ObservationVolumeProjectedYear], +[OtherVolumeBudgetYear], +[OtherVolumeProjectedYear], +[OutpatientVolumeBudgetYear], +[OutpatientVolumeProjectedYear] +FROM [ob].[DimOBServiceLinePlan] (readuncommitted) +GO + + +--------------------------------------------- + +-- ob.viewDimOBServiceLinePlanPH +CREATE VIEW [ob].[viewDimOBServiceLinePlanPH] +AS +SELECT + grpCA35C88C6A9A4080B0FF5FBA968C28A7.[OBServiceLinePlanPHID] + ,grpCA35C88C6A9A4080B0FF5FBA968C28A7.[Name] + ,grpCA35C88C6A9A4080B0FF5FBA968C28A7.[MemberGUID] + ,grpCA35C88C6A9A4080B0FF5FBA968C28A7.[HistoryItemGUID] + ,grpCA35C88C6A9A4080B0FF5FBA968C28A7.[TransactionID] +FROM [ob].[DimOBServiceLinePlanPH] grpCA35C88C6A9A4080B0FF5FBA968C28A7 (readuncommitted) +GO + + +--------------------------------------------- + +-- ob.viewDimOBServiceLinePlan_source +CREATE VIEW [ob].[viewDimOBServiceLinePlan_source] +AS +SELECT + grp69AF13389B5C41B5A4367BD2A516074B.[OBServiceLinePlanID] + ,grp69AF13389B5C41B5A4367BD2A516074B.[TransactionID] + ,grp69AF13389B5C41B5A4367BD2A516074B.[MemberGUID] + ,grp69AF13389B5C41B5A4367BD2A516074B.[HistoryItemGUID] + ,2 AS [FrameworkID] + ,ISNULL([ENT].[Name], 'Not Specified') as [Entity] + ,ISNULL([ENT].[SortOrder], 0) as [EntitySortOrder] + ,ISNULL([ENT].[SecureGroupID], 0) as [SecureGroupID] + ,ISNULL([DimXP].[PlanID], 0) as [LootID] + ,ISNULL([DimXP].[IsDeleted], 0) as [IsDeleted] +FROM [ob].[DimOBServiceLinePlan] grp69AF13389B5C41B5A4367BD2A516074B (readuncommitted) + INNER JOIN [fw].[viewDimEntity] [ENT] on [ENT].[EntityID] = [grp69AF13389B5C41B5A4367BD2A516074B].[EntityID] + INNER JOIN [fw].[viewDimXPlan_auto] [DimXP] on [DimXP].[MemberGUID] = [grp69AF13389B5C41B5A4367BD2A516074B].[MemberGUID] +GO + + +--------------------------------------------- + +-- ob.viewDimOBSnapshot +CREATE VIEW [ob].[viewDimOBSnapshot] +AS +SELECT + grp39C103E65DEC41F09D8D6D4E85A82692.[OBSnapshotID] + ,grp39C103E65DEC41F09D8D6D4E85A82692.[Name] + ,grp39C103E65DEC41F09D8D6D4E85A82692.[TransactionID] + ,grp39C103E65DEC41F09D8D6D4E85A82692.[MemberGUID] + ,grp39C103E65DEC41F09D8D6D4E85A82692.[HistoryItemGUID] + ,grp39C103E65DEC41F09D8D6D4E85A82692.[Category] + ,grp39C103E65DEC41F09D8D6D4E85A82692.[Date] +FROM [ob].[DimOBSnapshot] grp39C103E65DEC41F09D8D6D4E85A82692 (readuncommitted) +GO + + +--------------------------------------------- + +-- ob.viewDimSpread +--Last Modified 5/25/2018 10:33 AM +CREATE VIEW [ob].[viewDimSpread] +AS +SELECT + grp70A27E28D45145339A6384110B97E4B3.[SpreadID] + ,grp70A27E28D45145339A6384110B97E4B3.[Name] + ,grp70A27E28D45145339A6384110B97E4B3.[MemberGUID] + ,grp70A27E28D45145339A6384110B97E4B3.[IsBuiltIn] + ,grp70A27E28D45145339A6384110B97E4B3.[SortOrder] + ,coalesce(grp70A27E28D45145339A6384110B97E4B3.[Category],'') as [Category] +FROM [ob].[DimSpread] grp70A27E28D45145339A6384110B97E4B3 (readuncommitted) +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetAccountsNotBudgeted +CREATE VIEW [ob].[viewExceptionsDepartmentBudgetAccountsNotBudgeted] +AS +SELECT + DB.[DepartmentalBudgetID], + DB.[Name] AS Model, + 'Has ' + CAST(CAST(SUM(FA.[Total]) AS DECIMAL(16,2)) AS NVARCHAR(100)) + ' current year ' + UT.[Name] + ' for Account ' + ACC.[Name] + ' but does not have a budget.' AS [Detail] +FROM [clientob].[FactAccount] AS FA + INNER JOIN [fw].[DimUnitType] AS UT + ON FA.[UnitTypeID] = UT.[UnitTypeID] + INNER JOIN [fw].[DimAccount] AS ACC + ON ACC.[AccountID] = FA.[AccountID] + INNER JOIN [ob].[DimDepartmentalBudget] AS DB + ON DB.[DepartmentalBudgetID] = FA.[DepartmentalBudgetID] +WHERE 1=1 + AND FA.[IsDeleted] IN (0, 1) + AND FA.[FiscalYearID] = (SELECT TOP 1 CAST([Setting] AS INT) FROM [dbo].[DBSetting] WHERE [DBSettingGUID] = '9c921c27-f3e4-4616-b3fd-925a75870b62') + AND FA.[TimeClassID] = 1 -- Actual + AND FA.[Total] <> 0 + AND ACC.[AccountID] <> 0 + AND NOT (ACC.[OBIsDefined] = 1 AND ACC.[OBAccountPHID] = 0 AND ACC.[OBStatModelSectionID] = 0) + AND UT.[UnitTypeID] IN (34, 51, 140) -- Dollars, Volume and Hours (contract labor) + AND DB.[OBActivePlans] = '1' + AND NOT EXISTS + ( + SELECT + 1 + FROM [clientob].[FactAccount] AS FA2 + WHERE 1 = 1 + AND FA2.[DepartmentalBudgetID] = FA.[DepartmentalBudgetID] + AND FA2.[AccountID] = FA.[AccountID] + AND FA2.[UnitTypeID] = FA.[UnitTypeID] + AND FA2.[TimeClassID] = 2 -- Budgeted + AND FA2.[FiscalYearID] = FA.[FiscalYearID] + 1 + AND FA2.[IsDeleted] IN (0, 1) + AND FA2.[Total] <> 0 + ) +GROUP BY + DB.[DepartmentalBudgetID], + DB.[Name], + UT.[Name], + ACC.[Name] +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetActiveButNoHistory +/************************************************************ +** Author: akowalski +** Create Date: 2015-01-18 +** Description: Displays all budgets that are set to active but have no current year activity +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ +create view [ob].[viewExceptionsDepartmentBudgetActiveButNoHistory] as +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is set to Active but no current year account activity' as Detail +from [ob].[DimDepartmentalBudget] db with (readuncommitted) +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and db.DepartmentalBudgetID not in ( + select fct1.DepartmentalBudgetID from [clientob].[FactAccount] fct1 with (readuncommitted) + inner join [ob].[DimDepartmentalBudget] db1 with (readuncommitted) on fct1.DepartmentalBudgetID=db1.DepartmentalBudgetID and fct1.FiscalYearID=db1.BaseYear + where fct1.TimeClassID in (1,2) and fct1.Total<>0 and DataTypeID=4 +) +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetContractLaborDollarsWithoutHours +/************************************************************ +** Author: mschmitz +** Create Date: 2015-01-18 +** Description: Checks for departmental budgets that have contract labor dollars without hours in historic time periods +** Last Modified: 2016-11-30 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-11-30 srk D-04692 Updated exception report to look for historic time periods where there are dollars but no hours, +** instead of looking for budgeted dollars without hours. It works similar the job code with dollars +** but no hours exception now. +** +*************************************************************/ +CREATE VIEW [ob].[viewExceptionsDepartmentBudgetContractLaborDollarsWithoutHours] AS + +SELECT DISTINCT + db.DepartmentalBudgetID, + db.Name as Model, + 'Has dollars but no hours for contract labor account ' + DA.Name + ' in ' + tc.name + ' '+ cast(FA.FiscalYearID as char(4)) as 'Detail' +FROM [clientob].[FactAccount] FA with (readuncommitted) + INNER JOIN [ob].[DimDepartmentalBudget] DB with (readuncommitted) on DB.DepartmentalBudgetID=FA.DepartmentalBudgetID + INNER JOIN [fw].[DimAccount] DA with (readuncommitted) on DA.AccountID = FA.AccountID + INNER JOIN [data].[ScoreFillin_Account] SFA on FA.AccountID = SFA.AccountID + INNER JOIN [ob].[DimAccountPH] PH on SFA.PlaceholderSectionMemberGUID = PH.MemberGUID + INNER JOIN [fw].[DimTimeClass] TC on FA.TimeClassID = TC.TimeClassID + and PH.Name = 'Staffing - Contract Labor' +WHERE 1=1 + and FA.UnitTypeID=34 + and FA.Total != 0 + and FA.DataTypeID = 4 -- Input + and FA.TimeClassID = 1 -- Budget + and FA.FiscalYearID <= (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year') + and not exists + ( + SELECT top 1 1 + FROM [clientob].[FactAccount] FA1 with (readuncommitted) + WHERE 1=1 + and FA1.UnitTypeID in + ( + 51 --hours + ,146 --nonproductive + ,147 --differential + ,148 --productive + ) + and FA1.DepartmentalBudgetID=FA.DepartmentalBudgetID + and FA1.AccountID = FA.AccountID + and FA1.FiscalYearID = FA.FiscalYearID + and FA1.DataTypeID = 4 -- Input + and FA1.TimeClassID = 1 -- Actual + and FA1.Total != 0 + ) +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetDataWithoutDimensionMembers +/************************************************************ +** Author: jgerber +** Create Date: 2014-09-17 +** Description: Checks for dept budget data that does not have dimension members +** Last Modified: 2014-09-17 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +*************************************************************/ + +create view [ob].[viewExceptionsDepartmentBudgetDataWithoutDimensionMembers] as + +--***Fact Account********************************************* +-- Department Dimension + select + Distinct + 0 as DepartmentalBudgetID, + 'Not Specified' as Model, + 'Has General Ledger data for a Department that no longer exists' as Detail + from + [clientob].[FactAccount] data with (readuncommitted) + left join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + where + db.MemberGUID is null + +UNION ALL + +-- Account Dimension + select + Distinct + db.DepartmentalBudgetID, + db.Name as Model, + 'Has General Ledger data for an Account that no longer exists' as Detail + from + [clientob].[FactAccount] data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + left join [fw].[DimAccount] dim with (readuncommitted) on dim.AccountID = data.AccountID + where + dim.MemberGUID is null + +UNION ALL + +--***Fact Staffing PC********************************************* +-- Department Dimension + select + Distinct + 0 as DepartmentalBudgetID, + 'Not Specified' as Model, + 'Has Staffing data for a Department that no longer exists' as Detail + from + [clientob].[FactStaffingPC] data with (readuncommitted) + left join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + where + db.MemberGUID is null + +Union ALL + +-- Job Code Dimension + select + Distinct + db.DepartmentalBudgetID, + db.Name as Model, + 'Has Staffing data for a Job Code that no longer exists' as Detail + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + left join [fw].[DimJobCode] dim with (readuncommitted) on dim.JobCodeID = data.JobCodeID + where + dim.MemberGUID is null + +Union ALL + +-- Pay Code Dimension + select + Distinct + db.DepartmentalBudgetID, + db.Name as Model, + 'Has Staffing data for a Pay Code that no longer exists' as Detail + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + left join [fw].[DimPayCode] dim with (readuncommitted) on dim.PayCodeID = data.PayCodeID + where + dim.MemberGUID is null + +Union ALL + +-- Pay Code Group Dimension + select + Distinct + db.DepartmentalBudgetID, + db.Name as Model, + 'Has Staffing data for a Pay Code Group that no longer exists' as Detail + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + left join [fw].[DimPayCodeGroup] dim with (readuncommitted) on dim.PayCodeGroupID = data.PayCodeGroupID + where + dim.MemberGUID is null + +Union ALL + +-- Employee Dimension + select + Distinct + db.DepartmentalBudgetID, + db.Name as Model, + 'Has Staffing data for a Employee that no longer exists' as Detail + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + left join [fw].[DimEmployee] dim with (readuncommitted) on dim.EmployeeID = data.EmployeeID + where + dim.MemberGUID is null + +UNION ALL + +--***Fact Provider********************************************* +-- Department Dimension + select + Distinct + 0 as DepartmentalBudgetID, + 'Not Specified' as Model, + 'Has Provider data for a Department that no longer exists' as Detail + from + [clientob].[FactProvider] data with (readuncommitted) + left join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + where + db.MemberGUID is null + +UNION ALL + +-- Provider Dimension + select + Distinct + db.DepartmentalBudgetID, + db.Name as Model, + 'Has Provider data for a Provider that no longer exists' as Detail + from + [clientob].[FactProvider] data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + left join [fw].[DimProvider] dim with (readuncommitted) on dim.ProviderID = data.ProviderID + where + dim.MemberGUID is null + +UNION ALL + +-- Forecast Detail Dimension + select + Distinct + db.DepartmentalBudgetID, + db.Name as Model, + 'Has Provider data for a Forecast Detail that no longer exists' as Detail + from + [clientob].[FactProvider] data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + left join [ob].[DimOBForecastDetail] dim with (readuncommitted) on dim.OBForecastDetailID = data.OBForecastDetailID + where + dim.MemberGUID is null + +UNION ALL + +--***Fact Charge Code********************************************* +-- Department Dimension + select + Distinct + 0 as DepartmentalBudgetID, + 'Not Specified' as Model, + 'Has Charge Code data for a Department that no longer exists' as Detail + from + [clientob].[FactCDM] data with (readuncommitted) + left join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + where + db.MemberGUID is null + +UNION ALL + +-- Charge Code Dimension + select + Distinct + db.DepartmentalBudgetID, + db.Name as Model, + 'Has Charge Code data for a Charge Code that no longer exists' as Detail + from + [clientob].[FactCDM] data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + left join [fw].[DimChargeCode] dim with (readuncommitted) on dim.ChargeCodeID = data.ChargeCodeID + where + dim.MemberGUID is null + +UNION ALL + +--***Fact Reporting********************************************* +-- Department Dimension + select + Distinct + 0 as DepartmentalBudgetID, + 'Not Specified' as Model, + 'Has Financial Reporting data for a Department that no longer exists' as Detail + from + [clientob].[FactReportingMonthly] data with (readuncommitted) + left join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + where + db.MemberGUID is null + +UNION ALL + +-- Financial Reporting Dimension + select + Distinct + db.DepartmentalBudgetID, + db.Name as Model, + 'Has Financial Reporting data for a Line Item that no longer exists' as Detail + from + [clientob].[FactReportingMonthly] data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + left join [ob].[DimFinancialReporting] dim with (readuncommitted) on dim.FinancialReportingID = data.FinancialReportingID + where + dim.MemberGUID is null +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetDollarsWithoutHours +/************************************************************ +** Author: mschmitz +** Create Date: 2015-01-18 +** Description: Checks for job code/pay code group combos that have dollars but not hours in historic time periods +** Last Modified: 08/01/2017 +** GM Release: 2017.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 08/04/2015 CBB D-03150 Issues with false positives - Rebuilt using structure from BudgetHoursWithoutDollars +** 2 09/19/2016 BL D-04355 Filter out "Dollars Only" Productive Class from exception +** 3 10/26/2016 GF B-13254 Refactored for performance +** 4 2017-02-10 akk D-05381 Adding productive non-fte unit type to hours subquery +** 5 08/01/2017 vyaremko D-06199 Filter out inactive departments +*************************************************************/ +CREATE VIEW [ob].[viewExceptionsDepartmentBudgetDollarsWithoutHours] +AS + SELECT DISTINCT + DB.[DepartmentalBudgetID] AS [DepartmentalBudgetID], + DB.[Name] AS [Model], + 'Has dollars in pay code group ' + + PCG.[Name] + + ' but no hours for job code ' + + JC.[Name] + + ' in ' + + TC.[Name] + + ' ' + + cast(st.FiscalYearID as char(4)) + AS [Detail] + ,TC.[Name] + ,ST.[FiscalYearID] + FROM [clientob].[FactStaffingPC] AS ST WITH (READUNCOMMITTED) + INNER JOIN [ob].[DimDepartmentalBudget] AS DB WITH (READUNCOMMITTED) + ON DB.[DepartmentalBudgetID] = ST.[DepartmentalBudgetID] + INNER JOIN [fw].[DimJobCode] AS JC WITH (READUNCOMMITTED) + ON JC.[JobCodeID] = ST.[JobCodeID] + INNER JOIN [fw].[DimPayCodeGroup] AS PCG WITH (READUNCOMMITTED) + ON PCG.[PayCodeGroupID] = ST.[PayCodeGroupID] + INNER JOIN [fw].[DimTimeClass] AS TC WITH (READUNCOMMITTED) + ON TC.[TimeClassID] = ST.[TimeClassID] + WHERE 1=1 + AND ST.[UnitTypeID] = 34 + AND PCG.[ProductiveClassID] <> 4 + AND ST.[Total] != 0 + AND DB.[OBActivePlans] = '1' + AND NOT EXISTS( + SELECT 1 + FROM [clientob].[FactStaffingPC] AS H WITH (READUNCOMMITTED) + WHERE 1=1 + AND H.[UnitTypeID] IN + ( + 51 --hours + ,146 --nonproductive + ,147 --differential + ,148 --productive + ,52 --productive non-fte + ) + AND H.[DepartmentalBudgetID] = ST.[DepartmentalBudgetID] + AND H.[DataTypeID] = ST.[DataTypeID] + AND H.[FiscalYearID] = ST.[FiscalYearID] + AND H.[JobCodeID] = ST.[JobCodeID] + AND H.[PayCodeGroupID] = ST.[PayCodeGroupID] + AND H.[TimeClassID] = ST.[TimeClassID] + AND H.[Total] != 0 + ); +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetDuplicateFillins +/************************************************************ +** Author: dmoldawer +** Create Date: 2014-03-21 +** Description: Finds all duplicate fillins in the OB Departmental Budget model for the Account, Employee, Job Code, and Pay Code Group dimensions +** Last Modified: 2013-10-07 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2014-10-07 JG Renaming and adding to the exception summary report +** +*************************************************************/ + +create view [ob].[viewExceptionsDepartmentBudgetDuplicateFillins] as + +--ACCOUNTS +--CHECK IF EXCLUSIVE FILLINS EXIST IN OTHER SECTIONS + +select + DB.DepartmentalBudgetID, + DB.Name as Model, + DIM.Name + ' in section ' + PH.Name + ' is also in another section' as Detail + +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join XPlan X with (readuncommitted) on DB.MemberGUID = X.PlanGUID + inner join data.ScoreFillin_Account FI with (readuncommitted) on DB.MemberGUID = FI.ModelGUID + inner join fw.DimAccount DIM with (readuncommitted) on FI.AccountID = DIM.AccountID + inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID + inner join +( +select + distinct DB.DepartmentalBudgetID, FI1.AccountID +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join XPlan X with (readuncommitted) on DB.MemberGUID = X.PlanGUID + inner join MEPHSection ME with (readuncommitted) on X.ModelTemplateGUID = ME.ModelTemplateGUID + inner join data.ScoreFillin_Account FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID + and ME.PHSectionMemberGUID = FI1.PlaceholderSectionMemberGUID +where + exists (select 1 from data.ScoreFillin_Account FI2 with (readuncommitted) + inner join XPlan X with (readuncommitted) on fi2.modelguid = X.PlanGUID + inner join MEPHSection ME2 with (readuncommitted) on X.ModelTemplateGUID = ME2.ModelTemplateGUID and FI2.PlaceholderSectionMemberGUID=ME2.PHSectionMemberGUID + where FI2.ModelGUID = FI1.ModelGUID and FI2.FillinMemberGUID = FI1.FillinMemberGUID and FI2.FillinGUID != FI1.FillinGUID + and ME2.ExclusivityGroup=me.ExclusivityGroup) + and ME.IsExclusive = 1 +) DUPES + on DB.DepartmentalBudgetID = DUPES.DepartmentalBudgetID + and DIM.AccountID = DUPES.AccountID + and PH.AccountPHID<>0 + + +union all + +--EMPLOYEE +-- CHECK IF FILLINS EXISTS IN BOTH VARIABLE AND FIXED +select + DB.DepartmentalBudgetID, + DB.Name as Model, + DIM.Name + ' in section ' + PH1.Name + ' is also in another section' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join data.ScoreFillin_Employee FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID + inner join fw.DimEmployeePH PH1 with (readuncommitted) on FI1.EmployeePHID = PH1.EmployeePHID + inner join fw.DimEmployee DIM with (readuncommitted) on FI1.EmployeeID = DIM.EmployeeID +where + PH1.Name in('Staffing - Employee (Fixed)', 'Staffing - Employee (Variable)') + and exists +(select 1 +from + data.ScoreFillin_Employee FI2 with (readuncommitted) + inner join fw.DimEmployeePH PH2 with (readuncommitted) on FI2.EmployeePHID = PH2.EmployeePHID +where + PH2.Name in('Staffing - Employee (Fixed)', 'Staffing - Employee (Variable)') + and FI1.ModelGUID = FI2.ModelGUID + and FI1.EmployeeID = FI2.EmployeeID + and FI1.EmployeePHID != FI2.EmployeePHID +) + +union all + +--JOB CODE +-- CHECK IF FILLINS EXISTS IN BOTH VARIABLE AND FIXED +select + DB.DepartmentalBudgetID, + DB.Name as Model, + DIM.Name + ' in section ' + PH1.Name + ' is also in another section' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join data.ScoreFillin_JobCode FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID + inner join fw.DimJobCodePH PH1 with (readuncommitted) on FI1.JobCodePHID= PH1.JobCodePHID + inner join fw.DimJobCode DIM with (readuncommitted) on FI1.JobCodeID = DIM.JobCodeID +where + PH1.Name in('Staffing - Job Code (Fixed)', 'Staffing - Job Code (Variable)') + and exists +(select 1 +from + data.ScoreFillin_JobCode FI2 with (readuncommitted) + inner join fw.DimJobCodePH PH2 with (readuncommitted) on FI2.JobCodePHID = PH2.JobCodePHID +where + PH2.Name in('Staffing - Job Code (Fixed)', 'Staffing - Job Code (Variable)') + and FI1.ModelGUID = FI2.ModelGUID + and FI1.JobCodeID = FI2.JobCodeID + and FI1.JobCodePHID != FI2.JobCodePHID +) + +union all + +--OB FINANCIAL REPORTING +-- CHECK IF FINANCIAL REPORTING SHOWS UP IN MORE THAN ONE SECTION +select + DB.DepartmentalBudgetID, + DB.Name as Model, + DIM.Name + ' in section ' + PH.Name + ' is also in another section' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join data.ScoreFillin_OBFinancialReporting FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID + inner join ob.DimFinancialReportingPH PH with (readuncommitted) on FI1.FinancialReportingPHID= PH.FinancialReportingPHID + inner join ob.DimFinancialReporting DIM with (readuncommitted) on FI1.FinancialReportingID = DIM.FinancialReportingID +where exists +(select 1 +from + data.ScoreFillin_FinancialReporting FI2 with (readuncommitted) +where + FI1.ModelGUID = FI2.ModelGUID + and FI1.FinancialReportingID= FI2.FinancialReportingID + and FI1.FinancialReportingPHID!= FI2.FinancialReportingPHID +) +and PH.FinancialReportingPHID<>0 + +union all + +--PAY CODE GROUP +--CHECK IF EXCLUSIVE FILLINS EXIST IN OTHER SECTIONS +select + DB.DepartmentalBudgetID, + DB.Name as Model, + DIM.Name + ' in section ' + PH.Name + ' is also in another section' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join data.ScoreFillin_PayCodeGroup FI with (readuncommitted) on DB.MemberGUID = FI.ModelGUID + inner join fw.DimPayCodeGroupPH PH with (readuncommitted) on FI.PayCodeGroupPHID = PH.PayCodeGroupPHID + inner join fw.DimPayCodeGroup DIM with (readuncommitted) on FI.PayCodeGroupID = DIM.PayCodeGroupID + inner join +( +select + distinct DB.DepartmentalBudgetID, FI1.PayCodeGroupID +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join XPlan X with (readuncommitted) on DB.MemberGUID = X.PlanGUID + inner join MEPHSection ME with (readuncommitted) on X.ModelTemplateGUID = ME.ModelTemplateGUID + inner join data.ScoreFillin_PayCodeGroup FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID + and ME.PHSectionMemberGUID = FI1.PlaceholderSectionMemberGUID +where + exists(select 1 from data.ScoreFillin_Account FI2 with (readuncommitted) where FI2.ModelGUID = FI1.ModelGUID and FI2.FillinMemberGUID = FI1.FillinMemberGUID and FI2.FillinGUID != FI1.FillinGUID) + and ME.IsExclusive = 1 +) DUPES + on DB.DepartmentalBudgetID = DUPES.DepartmentalBudgetID + and DIM.PayCodeGroupID = DUPES.PayCodeGroupID + and PH.PayCodeGroupPHID<>0 + +union all + +--PROVIDER +-- CHECK IF PROVIDER SHOWS UP IN MORE THAN ONE SECTION +select + DB.DepartmentalBudgetID, + DB.Name as Model, + DIM.Name + ' in section ' + PH.Name + ' is also in another section' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join data.ScoreFillin_Provider FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID + inner join fw.DimProviderPH PH with (readuncommitted) on FI1.ProviderPHID= PH.ProviderPHID + inner join fw.DimProvider DIM with (readuncommitted) on FI1.ProviderID = DIM.ProviderID +where exists +(select 1 +from + data.ScoreFillin_Provider FI2 with (readuncommitted) +where + FI1.ModelGUID = FI2.ModelGUID + and FI1.ProviderID = FI2.ProviderID + and FI1.ProviderPHID != FI2.ProviderPHID +) +and PH.ProviderPHID<>0 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetExpenseAdjustmentsNoComments +/************************************************************ +** Author: akowalski +** Create Date: 2015-01-18 +** Description: Displays all non-staffing expense accounts that have manager adjustments but no comments +** Last Modified: 2017-02-27 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-02-27 srk D-05574 Added isdeleted <> 1 flag, and made fiscal year parameter dynamic based on dbsetting. +** +*************************************************************/ +CREATE view [ob].[viewExceptionsDepartmentBudgetExpenseAdjustmentsNoComments] as + +/******* fixed monthly adjustments ******/ +-- Projected +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Non-Staffing Expense Account ' + sf.FillinMemberName + ' has a monthly Projection adjustment but no comments' as Detail +from [clientob].[FactAccountVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID +inner join [clientob].[FactAccountVar] fct2 with (readuncommitted) on fct1.AccountID=fct2.AccountID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.AccountPHID in ('9', --Expenses - Non-Staffing +'10') --Expenses - Zero Based +and fct1.Amount<>0 +and fct1.AssumptionID=38 -- Fixed Adjustment +and fct2.AssumptionID=30 -- Comment +and fct2.Comment='' +and fct1.TimeClassID=12 +and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 + + +union all + +-- Budget +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Non-Staffing Expense Account ' + sf.FillinMemberName + ' has a monthly Budget adjustment but no comments' as Detail +from [clientob].[FactAccountVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID +inner join [clientob].[FactAccountVar] fct2 with (readuncommitted) on fct1.AccountID=fct2.AccountID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.AccountPHID in ('9', --Expenses - Non-Staffing +'10') --Expenses - Zero Based +and fct1.Amount<>0 +and fct1.AssumptionID=38 -- Fixed Adjustment +and fct2.AssumptionID=30 -- Comment +and fct2.Comment='' +and fct1.TimeClassID=2 +and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 + +union all + +-- Baseline Budget +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Non-Staffing Expense Account ' + sf.FillinMemberName + ' has a Baseline Budget adjustment but no comments' as Detail +from [clientob].[FactAccountVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID +inner join [clientob].[FactAccountVar] fct2 with (readuncommitted) on fct1.AccountID=fct2.AccountID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.AccountPHID in ('9', --Expenses - Non-Staffing +'10') --Expenses - Zero Based +and fct1.Amount<>0 +and fct1.AssumptionID=38 -- Fixed Adjustment +and fct2.AssumptionID=30 -- Comment +and fct2.Comment='' +and fct1.TimeClassID=18 +and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 + + +union all + +/******* Fixed Annual Adjustments ******/ +-- Projected +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Non-Staffing Expense Account ' + sf.FillinMemberName + ' has a yearly-level Projection adjustment but no comments' as Detail +from [clientob].[FactAccountVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID +inner join [clientob].[FactAccountVar] fct2 with (readuncommitted) on fct1.AccountID=fct2.AccountID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.AccountPHID in ('9', --Expenses - Non-Staffing +'10') --Expenses - Zero Based +and fct1.Amount<>0 +and fct1.AssumptionID=18 -- Adjustment +and fct2.AssumptionID=30 -- Comment +and fct2.Comment='' +and fct1.TimeClassID=12 +and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 + + +union all + +-- Budget +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Non-Staffing Expense Account ' + sf.FillinMemberName + ' has a yearly-level Budget adjustment but no comments' as Detail +from [clientob].[FactAccountVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID +inner join [clientob].[FactAccountVar] fct2 with (readuncommitted) on fct1.AccountID=fct2.AccountID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.AccountPHID in ('9', --Expenses - Non-Staffing +'10') --Expenses - Zero Based +and fct1.Amount<>0 +and fct1.AssumptionID=18 -- Adjustment +and fct2.AssumptionID=30 -- Comment +and fct2.Comment='' +and fct1.TimeClassID=2 +and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 + + +union all + +/******* Subtable Adjustments ******/ +-- Projected +select +Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Non-Staffing Expense Account ' + sf.FillinMemberName + ' has a subtable Projection adjustment with no comment' as Detail +from [clientob].[FactAccountSubtableVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.AccountPHID in ('9', --Expenses - Non-Staffing +'10') --Expenses - Zero Based +and fct1.Total<>0 +and fct1.AssumptionID=18 +and fct1.Comment='' +and fct1.TimeClassID=12 +and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 + +union all + +-- Budget +select +Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Non-Staffing Expense Account ' + sf.FillinMemberName + ' has a subtable Budget adjustment with no comment' as Detail +from [clientob].[FactAccountSubtableVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.AccountPHID in ('9', --Expenses - Non-Staffing +'10') --Expenses - Zero Based +and fct1.Total<>0 +and fct1.AssumptionID=18 +and fct1.Comment='' +and fct1.TimeClassID=2 +and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetFillinCacheIssues +/************************************************************ +** Author: akowalski +** Create Date: 2014-05-13 +** Description: Checks for fill-ins in Score Fill-ins but not in Cache tables or PH Index doesnt Match +** Last Modified: 2014-08-14 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2014-08-14 akk D-02122 Filtering out not specified department budget +** 2 2016-02-26 mholov D-03407 Filtering out 'GM Blank' model template +** 3 2016-08-10 kf B-12543 FP - System Center Exception Management - Initial Framework +*************************************************************/ + +CREATE view [ob].[viewExceptionsDepartmentBudgetFillinCacheIssues] as +--Fill-ins in Score Fill-ins but not in Cache tables or PH Index doesnt Match + +--Account +select + DB.DepartmentalBudgetID, + DB.Name as Model, + 'The fill-in cache for Account ' + DIM.Name + ' out of sync' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join data.ScoreFillin_Account FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join fw.DimAccount DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null +--==================== BEGIN CID 1 ===================== + and db.departmentalbudgetid<>0 +--===================== END CID 1 ====================== + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45' + +union all + +--Job Code +select + DB.DepartmentalBudgetID, + DB.Name as Model, + 'The fill-in cache for Job Code ' + DIM.Name + ' out of sync' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join data.ScoreFillin_JobCode FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join fw.DimJobCode DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null +--==================== BEGIN CID 1 ===================== + and db.departmentalbudgetid<>0 +--===================== END CID 1 ====================== + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45' +union all + +--Employee +select + DB.DepartmentalBudgetID, + DB.Name as Model, + 'The fill-in cache for Employee ' + DIM.Name + ' out of sync' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join data.ScoreFillin_Employee FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join fw.DimEmployee DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null +--==================== BEGIN CID 1 ===================== + and db.departmentalbudgetid<>0 +--===================== END CID 1 ====================== + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45' + +union all + +--Pay Code Group +select + DB.DepartmentalBudgetID, + DB.Name as Model, + 'The fill-in cache for Pay Code Group ' + DIM.Name + ' out of sync' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join data.ScoreFillin_PayCodeGroup FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join fw.DimPayCodeGroup DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null +--==================== BEGIN CID 1 ===================== + and db.departmentalbudgetid<>0 +--===================== END CID 1 ====================== + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45' + + +union all + +--Provider +select + DB.DepartmentalBudgetID, + DB.Name as Model, + 'The fill-in cache for Provider ' + DIM.Name + ' out of sync' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join data.ScoreFillin_Provider FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join fw.DimProvider DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null +--==================== BEGIN CID 1 ===================== + and db.departmentalbudgetid<>0 +--===================== END CID 1 ====================== + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45' + +union all + +--Charge Code +select + DB.DepartmentalBudgetID, + DB.Name as Model, + 'The fill-in cache for Charge Code ' + DIM.Name + ' out of sync' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join data.ScoreFillin_ChargeCode FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join fw.DimChargeCode DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null +--==================== BEGIN CID 1 ===================== + and db.departmentalbudgetid<>0 +--===================== END CID 1 ====================== + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45' + +union all + +--OB Forecast Detail +select + DB.DepartmentalBudgetID, + DB.Name as Model, + 'The fill-in cache for OB Forecast Detail ' + DIM.Name + ' out of sync' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join data.ScoreFillin_OBForecastDetail FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join ob.DimOBForecastDetail DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null +--==================== BEGIN CID 1 ===================== + and db.departmentalbudgetid<>0 +--===================== END CID 1 ====================== + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45' + +union all + +--OB Departmental Budget +select + DB.DepartmentalBudgetID, + DB.Name as Model, + 'The fill-in cache for OB Departmental Budget ' + DIM.Name + ' out of sync' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join data.ScoreFillin_OBDepartmentalBudget FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join ob.DimDepartmentalBudget DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null +--==================== BEGIN CID 1 ===================== + and db.departmentalbudgetid<>0 +--===================== END CID 1 ====================== + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45' + +union all + +--Fiscal Year +select + DB.DepartmentalBudgetID, + DB.Name as Model, + 'The fill-in cache for Fiscal Year ' + DIM.Name + ' out of sync' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join data.ScoreFillin_FiscalYear FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join fw.DimFiscalYear DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null +--==================== BEGIN CID 1 ===================== + and db.departmentalbudgetid<>0 +--===================== END CID 1 ====================== + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45' + +union all + +--OB Financial Reporting +select + DB.DepartmentalBudgetID, + DB.Name as Model, + 'The fill-in cache for Financial Reporting ' + DIM.Name + ' out of sync' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join data.ScoreFillin_OBFinancialReporting FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join ob.DimFinancialReporting DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null +--==================== BEGIN CID 1 ===================== + and db.departmentalbudgetid<>0 +--===================== END CID 1 ====================== + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45' +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetFillinInSubListButNotInFullList +/************************************************************ +** Author: dmoldawer +** Create Date: 2014-03-21 +** Description: Checks if Employee and Job Code fillins exist in Fixed or Variable sections but not the All section in the OB Departmental Budget model +** Last Modified: 2013-03-21 +** GM Release: 2014.3 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ +CREATE view [ob].[viewExceptionsDepartmentBudgetFillinInSubListButNotInFullList] as +--EMPLOYEE +--CHECK IF FILLINS EXISTS IN 'Staffing - Employee (Fixed)' OR 'Staffing - Employee (Variable)' BUT NOT 'Staffing - Employee (All)' +select + DB.DepartmentalBudgetID, + DB.Name as Model, + DIM.Name + ' is in ' + PH1.Name + ' but not in Employee (All)' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join data.ScoreFillin_Employee FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID + inner join fw.DimEmployeePH PH1 with (readuncommitted) on FI1.EmployeePHID = PH1.EmployeePHID + inner join fw.DimEmployee DIM with (readuncommitted) on FI1.EmployeeID = DIM.EmployeeID +where + PH1.Name in('Staffing - Employee (Fixed)', 'Staffing - Employee (Variable)') + and not exists +(select 1 +from + data.ScoreFillin_Employee FI2 with (readuncommitted) + inner join fw.DimEmployeePH PH2 with (readuncommitted) on FI2.EmployeePHID = PH2.EmployeePHID +where + PH2.Name = 'Staffing - Employee (All)' + and FI1.ModelGUID = FI2.ModelGUID + and FI1.EmployeeID = FI2.EmployeeID +) + +union all +--JOB CODE +-- CHECK IF FILLINS EXISTS IN 'Staffing - Job Code (Fixed)' OR 'Staffing - Job Code (Variable)' BUT NOT 'Staffing - Job Code (All)' +select + DB.DepartmentalBudgetID, + DB.Name as Model, + DIM.Name + ' is in ' + PH1.Name + ' but not in Job Code (All)' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join data.ScoreFillin_JobCode FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID + inner join fw.DimJobCodePH PH1 with (readuncommitted) on FI1.JobCodePHID= PH1.JobCodePHID + inner join fw.DimJobCode DIM with (readuncommitted) on FI1.JobCodeID = DIM.JobCodeID +where + PH1.Name in('Staffing - Job Code (Fixed)', 'Staffing - Job Code (Variable)') + and not exists +(select 1 +from + data.ScoreFillin_JobCode FI2 with (readuncommitted) + inner join fw.DimJobCodePH PH2 with (readuncommitted) on FI2.JobCodePHID = PH2.JobCodePHID +where + PH2.Name = 'Staffing - Job Code (All)' + and FI1.ModelGUID = FI2.ModelGUID + and FI1.JobCodeID = FI2.JobCodeID +) +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetFillinsExceedingMaxCount +/************************************************************ +** Author: dmoldawer +** Create Date: 2014-03-21 +** Description: Checks fillin counts > expansion count in the OB Departmental Budget model +** Last Modified: 2017-12-19 +** GM Release: 2014.3 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-12-27 srk D-04955 Provider Global ID and PH Section join updates +** 2 2017-12-19 vyaremko D-06345 Use counts from main/base template +*************************************************************/ + +CREATE VIEW [ob].[viewExceptionsDepartmentBudgetFillinsExceedingMaxCount] +AS + +-- ACCOUNT +select distinct + DB.DepartmentalBudgetID, + DB.Name as Model, + 'Has ' + cast( + ( + select COUNT(*) + from data.ScoreFillin_Account FI with (readuncommitted) + inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID + inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID + where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID + ) as varchar(10)) + + ' Accounts in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail +from + XPlan X with (readuncommitted) + inner join ob.DimDepartmentalBudget DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID + inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID + left join MEScoreExpansionProfile EPC with (readuncommitted) on EPC.ChildModelTemplateGUID = MT.ModelTemplateGUID + inner join EMFModelTemplateWorksheet WS with (readuncommitted) on WS.ModelTemplateGUID = COALESCE(EPC.ParentModelTemplateGUID, MT.ModelTemplateGUID) + inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID + inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID +where + ( + select COUNT(*) + from data.ScoreFillin_Account FI with (readuncommitted) + inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID + inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID + where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID + ) > SE.[Count] + +union all + +--EMPLOYEE +select distinct + DB.DepartmentalBudgetID, + DB.Name as Model, + 'Has ' + cast( + ( + select COUNT(*) + from data.ScoreFillin_Employee FI with (readuncommitted) + inner join fw.DimEmployeePH PH with (readuncommitted) on FI.EmployeePHID = PH.EmployeePHID + inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID + where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID + ) as varchar(10)) + + ' Employees in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail +from + XPlan X with (readuncommitted) + inner join ob.DimDepartmentalBudget DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID + inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID + left join MEScoreExpansionProfile EPC with (readuncommitted) on EPC.ChildModelTemplateGUID = MT.ModelTemplateGUID + inner join EMFModelTemplateWorksheet WS with (readuncommitted) on WS.ModelTemplateGUID = COALESCE(EPC.ParentModelTemplateGUID, MT.ModelTemplateGUID) + inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID + inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID +where + ( + select COUNT(*) + from data.ScoreFillin_Employee FI with (readuncommitted) + inner join fw.DimEmployeePH PH with (readuncommitted) on FI.EmployeePHID = PH.EmployeePHID + inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID + where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID + ) > SE.[Count] + +union all + +--JOB CODE +select distinct + DB.DepartmentalBudgetID, + DB.Name as Model, + 'Has ' + cast( + ( + select COUNT(*) + from data.ScoreFillin_JobCode FI with (readuncommitted) + inner join fw.DimJobCodePH PH with (readuncommitted) on FI.JobCodePHID = PH.JobCodePHID + inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID + where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID + ) as varchar(10)) + + ' Job Codes in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail +from + XPlan X with (readuncommitted) + inner join ob.DimDepartmentalBudget DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID + inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID + left join MEScoreExpansionProfile EPC with (readuncommitted) on EPC.ChildModelTemplateGUID = MT.ModelTemplateGUID + inner join EMFModelTemplateWorksheet WS with (readuncommitted) on WS.ModelTemplateGUID = COALESCE(EPC.ParentModelTemplateGUID, MT.ModelTemplateGUID) + inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID + inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID +where + ( + select COUNT(*) + from data.ScoreFillin_JobCode FI with (readuncommitted) + inner join fw.DimJobCodePH PH with (readuncommitted) on FI.JobCodePHID = PH.JobCodePHID + inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID + where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID + ) > SE.[Count] + +union all + +--OB FINANCIAL REPORTING +select distinct + DB.DepartmentalBudgetID, + DB.Name as Model, + 'Has ' + cast( + ( + select COUNT(*) + from data.ScoreFillin_OBFinancialReporting FI with (readuncommitted) + inner join ob.DimFinancialReportingPH PH with (readuncommitted) on FI.FinancialReportingPHID = PH.FinancialReportingPHID + inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID + where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID + ) as varchar(10)) + + ' Financial Reporting Lines in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail +from + XPlan X with (readuncommitted) + inner join ob.DimDepartmentalBudget DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID + inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID + left join MEScoreExpansionProfile EPC with (readuncommitted) on EPC.ChildModelTemplateGUID = MT.ModelTemplateGUID + inner join EMFModelTemplateWorksheet WS with (readuncommitted) on WS.ModelTemplateGUID = COALESCE(EPC.ParentModelTemplateGUID, MT.ModelTemplateGUID) + inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID + inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID +where + ( + select COUNT(*) + from data.ScoreFillin_OBFinancialReporting FI with (readuncommitted) + inner join ob.DimFinancialReportingPH PH with (readuncommitted) on FI.FinancialReportingPHID = PH.FinancialReportingPHID + inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID + where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID + ) > SE.[Count] + +union all + +--PAY CODE GROUP +select distinct + DB.DepartmentalBudgetID, + DB.Name as Model, + 'Has ' + cast( + ( + select COUNT(*) + from data.ScoreFillin_PayCodeGroup FI with (readuncommitted) + inner join fw.DimPayCodeGroupPH PH with (readuncommitted) on FI.PayCodeGroupPHID = PH.PayCodeGroupPHID + inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID + where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID + ) as varchar(10)) + + ' Pay Code Groups in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail +from + XPlan X with (readuncommitted) + inner join ob.DimDepartmentalBudget DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID + inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID + left join MEScoreExpansionProfile EPC with (readuncommitted) on EPC.ChildModelTemplateGUID = MT.ModelTemplateGUID + inner join EMFModelTemplateWorksheet WS with (readuncommitted) on WS.ModelTemplateGUID = COALESCE(EPC.ParentModelTemplateGUID, MT.ModelTemplateGUID) + inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID + inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID +where + ( + select COUNT(*) + from data.ScoreFillin_PayCodeGroup FI with (readuncommitted) + inner join fw.DimPayCodeGroupPH PH with (readuncommitted) on FI.PayCodeGroupPHID = PH.PayCodeGroupPHID + inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID + where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID + ) > SE.[Count] + +union all + +--PROVIDER +select distinct + DB.DepartmentalBudgetID, + DB.Name as Model, + 'Has ' + cast( + ( + select COUNT(*) + from data.ScoreFillin_Provider FI with (readuncommitted) + inner join fw.DimProviderPH PH with (readuncommitted) on FI.ProviderPHID = PH.ProviderPHID + inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID + where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID + ) as varchar(10)) + + ' Providers in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10) + ) as Detail +from + XPlan X with (readuncommitted) + inner join ob.DimDepartmentalBudget DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID + inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID + left join MEScoreExpansionProfile EPC with (readuncommitted) on EPC.ChildModelTemplateGUID = MT.ModelTemplateGUID + inner join EMFModelTemplateWorksheet WS with (readuncommitted) on WS.ModelTemplateGUID = COALESCE(EPC.ParentModelTemplateGUID, MT.ModelTemplateGUID) + inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID + inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID +where + ( + select COUNT(*) + from data.ScoreFillin_Provider FI with (readuncommitted) + inner join fw.DimProviderPH PH with (readuncommitted) on FI.ProviderPHID = PH.ProviderPHID + inner join dbo.MEPHSection S with (readuncommitted) on s.PHSectionMemberGUID = ph.MemberGUID + where DB.MemberGUID = FI.ModelGUID and S.FriendlyName = SE.GlobalID and S.ModelTemplateGUID = MT.ModelTemplateGUID + ) > SE.[Count] +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetHoursWithoutDollars +/************************************************************ +** Author: akowalski +** Create Date: 2014-09-19 +** Description: Checks for job code/pay code group combos that have hours but not dollars in all time periods +** Last Modified: 2017-11-15 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 10/26/2016 GF B-13254 Refactored for performance +** 2 06/26/2017 cbb D06077 added filter jobcodeid<>0 +** 3 11/15/2017 apukii D-06542 added filter PayCodeGroupID<>0 +*************************************************************/ +CREATE VIEW [ob].[viewExceptionsDepartmentBudgetHoursWithoutDollars] +AS + SELECT DISTINCT + db.DepartmentalBudgetID, + db.Name as Model, + 'Has hours in pay code group ' + + pcg.name + + ' but no dollars for job code ' + + jc.name + + ' in ' + + tc.name + + ' ' + + cast(st.FiscalYearID as char(4)) + as Detail + ,tc.Name + ,st.FiscalYearID + FROM clientob.FactStaffingPC st with (readuncommitted) + INNER JOIN ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID=st.DepartmentalBudgetID + INNER JOIN [fw].[DimJobCode] jc with (readuncommitted) on jc.JobCodeID=st.JobCodeID + INNER JOIN [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID=st.PayCodeGroupID + INNER JOIN [fw].[DimTimeClass] tc with (readuncommitted) on tc.TimeClassID=st.TimeClassID + WHERE + st.UnitTypeID in + ( + 51 --hours + ,146 --nonproductive + ,147 --differential + ,148 --productive + ) + and pcg.ProductiveClassID<>4 + and st.Total <> 0 + and jc.JobCodeID <> 0 + and pcg.PayCodeGroupID <> 0 + and not exists( + SELECT top 1 1 + FROM clientob.FactStaffingPC d with (readuncommitted) + WHERE 1=1 + and d.UnitTypeID = 34 + and d.DepartmentalBudgetID=st.DepartmentalBudgetID + and d.DataTypeID=st.DataTypeID + and d.FiscalYearID=st.FiscalYearID + and d.JobCodeID=st.JobCodeID + and d.PayCodeGroupID=st.PayCodeGroupID + and d.TimeClassID=st.timeclassID + and d.Total != 0 + ) +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetInactiveButYTDActivity +/************************************************************ +** Author: akowalski +** Create Date: 2015-01-18 +** Description: Displays all department budgets set to inactive but have YTD actuals +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ +create view [ob].[viewExceptionsDepartmentBudgetInactiveButYTDActivity] as +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is set to Inactive but has YTD account activity' as Detail +from [clientob].[FactAccount] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID and fct1.FiscalYearID=db.BaseYear +where +db.DepartmentalBudgetID<>0 and OBActivePlans=0 +and TimeClassID=1 and fct1.Total<>0 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetInvalidBenefitConfigurations +/************************************************************ +** Author: mschmitz +** Create Date: 2015-01-18 +** Description: Checks for budgets that have benefit accounts configured as % of Salaries or $ per FTE but do not have either Salaries or FTEs in the department +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ +CREATE VIEW [ob].[viewExceptionsDepartmentBudgetInvalidBenefitConfigurations] AS + +SELECT DISTINCT + FMETHOD.DepartmentalBudgetID, + B.Name AS 'Model', + 'Has benefits budgeted as a % of Salaries but there are no benefit-driving salaries in this department.' as 'Detail' +FROM [clientob].[FactAccountVar] FMETHOD with (readuncommitted) +INNER JOIN [ob].[DimDepartmentalBudget] B ON FMETHOD.DepartmentalBudgetID=B.DepartmentalBudgetID +WHERE + FMETHOD.AssumptionID = '220' --Forecast Method - Benefits + AND FMETHOD.TextValue = '% of Salaries' + --Filter to include only departments that do not have job codes filled in with benefits-driving pay code groups + AND NOT EXISTS ( + SELECT DISTINCT + B2.DepartmentalBudgetID + FROM [ob].[DimDepartmentalBudget] B2 with (readuncommitted) + INNER JOIN [dbo].[XPlan] X ON B2.MemberGUID = X.PlanGUID + INNER JOIN [data].[ScoreFillin_PayCodeGroup] SFPCG with (readuncommitted) + ON SFPCG.ModelGUID = B2.MemberGUID + INNER JOIN [fw].[DimPayCodeGroup] PCG with (readuncommitted) + ON PCG.MemberGUID = SFPCG.FillinMemberGUID + INNER JOIN [data].[ScoreFillin_JobCode] SFJC with (readuncommitted) + ON SFJC.ModelGUID = B2.MemberGUID + INNER JOIN [fw].[DimJobCode] JC with (readuncommitted) + ON JC.MemberGUID = SFJC.FillinMemberGUID + WHERE + PCG.IsExcludedFromBenefits=0 + AND PCG.PayCodeGroupID<>0 + AND JC.JobCodeID<>0 + AND FMETHOD.DepartmentalBudgetID=B2.DepartmentalBudgetID + ) + +UNION ALL + +SELECT DISTINCT + FMETHOD.DepartmentalBudgetID, + B.Name AS 'Model', + 'Has benefits budgeted as $ per FTE but there are no benefit-driving FTEs in this department.' as 'Detail' +FROM [clientob].[FactAccountVar] FMETHOD with (readuncommitted) +INNER JOIN [ob].[DimDepartmentalBudget] B ON FMETHOD.DepartmentalBudgetID=B.DepartmentalBudgetID +WHERE + FMETHOD.AssumptionID = '220' --Forecast Method - Benefits + AND FMETHOD.TextValue = '$ per FTE' + --Filter to include only departments that do not have job codes filled in with benefits-driving pay code groups + AND NOT EXISTS ( + SELECT DISTINCT + B2.DepartmentalBudgetID + FROM [ob].[DimDepartmentalBudget] B2 with (readuncommitted) + INNER JOIN [dbo].[XPlan] X ON B2.MemberGUID = X.PlanGUID + INNER JOIN [data].[ScoreFillin_PayCodeGroup] SFPCG with (readuncommitted) + ON SFPCG.ModelGUID = B2.MemberGUID + INNER JOIN [fw].[DimPayCodeGroup] PCG with (readuncommitted) + ON PCG.MemberGUID = SFPCG.FillinMemberGUID + INNER JOIN [data].[ScoreFillin_JobCode] SFJC with (readuncommitted) + ON SFJC.ModelGUID = B2.MemberGUID + INNER JOIN [fw].[DimJobCode] JC with (readuncommitted) + ON JC.MemberGUID = SFJC.FillinMemberGUID + WHERE + PCG.IsExcludedFromBenefits=0 + AND PCG.PayCodeGroupID<>0 + AND JC.JobCodeID<>0 + AND FMETHOD.DepartmentalBudgetID=B2.DepartmentalBudgetID + ) +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetInvalidDeductionSetups +/********************************************************************************************************************************* +** Author: mschmitz +** Create Date: 2015-01-19 +** Description: Checks for budgets that have contract labor dollars budgeted without hours +** Last Modified: 2016-11-30 +** GM Release: 2015.2 +********************************************************************************************************************************** +** Change History +********************************************************************************************************************************** +** CID Date Author WI Description +** 1 2016-11-30 srk D-04897 Updated view to include only 'Deductions' placeholder section and +** ignore 'Deductions - Reimbursement' section because this section does not +** require gross charges in the same department. Deductions in the Reimbursement section +** are pushed from the Reimbursement model. +** +*********************************************************************************************************************************/ + +CREATE VIEW [ob].[viewExceptionsDepartmentBudgetInvalidDeductionSetups] AS + +select distinct + dB.DepartmentalBudgetID, + dB.Name as Model, + 'Is set to drive deductions by '+ ac.Textvalue+ ' but has no gross charge accounts in the model' as Detail +from [data].[ScoreFillin_Account] sf1 with (readuncommitted) + inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on sf1.ModelGUID=DB.MemberGUID + inner join [ob].[DimAccountPH] ph1 with (readuncommitted) on sf1.PlaceholderSectionMemberGUID=ph1.MemberGUID + inner join [fw].[DimAccount] a with (readuncommitted) on sf1.AccountID=a.AccountID and a.OBModelSectionName = 'Deductions' + inner join [clientob].[FactAccountVar] ac with (readuncommitted) on sf1.AccountID=ac.AccountID and ac.DepartmentalBudgetID=db.DepartmentalBudgetID +where 1=1 + and ph1.Name = 'Deductions' + and (ac.TextValue like '%charges' or ac.TextValue = 'Default') + and ac.AssumptionID=631 --'Deductions as a percent of' + and ac.TimeClassID=12 + and ac.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year') + and not exists ( + select top 1 1 + from [data].[ScoreFillin_Account] SF with (readuncommitted) + inner join [ob].[DimAccountPH] ph with (readuncommitted) + on ph.MemberGUID=sf.PlaceholderSectionMemberGUID + and ph.Name like 'Gross Charges%' + where + db.MemberGUID=SF.ModelGUID + and SF.AccountID<>0 + ) + and db.DepartmentalBudgetID<>0 + + +Union all + +-- check for accounts using default on Global Methods tab +/********* Assumptions +1. Deductions are only ever filled in to the section that matches the patient class set on account in order to pull the global setting +2. Doesn't check if you have gross charges for the specific patient class selected +3. Doesn't check payor specific +*************/ + +select distinct + dB.DepartmentalBudgetID, + dB.Name as Model, + 'Is globally set to drive deductions by '+ fct2.Textvalue+ ' but has no gross charge accounts in the model' as Detail +from [data].[ScoreFillin_Account] sf1 with (readuncommitted) + inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on sf1.ModelGUID=DB.MemberGUID + inner join [ob].[DimAccountPH] ph1 with (readuncommitted) on sf1.PlaceholderSectionMemberGUID=ph1.MemberGUID + inner join [fw].[DimAccount] a with (readuncommitted) on sf1.AccountID=a.AccountID and a.OBModelSectionName = 'Deductions' + inner join [clientob].[FactAccountVar] fct1 with (readuncommitted) on sf1.AccountID=fct1.AccountID and fct1.DepartmentalBudgetID=db.DepartmentalBudgetID + inner join [clientob].[FactAccountRollupVar] fct2 with (readuncommitted) on a.PatientClassID=fct2.PatientClassID and DB.DepartmentalBudgetID=fct2.DepartmentalBudgetID + and fct1.AssumptionID=fct2.AssumptionID +where 1=1 + and ph1.Name = 'Deductions' + and fct1.AssumptionID=631 --Volume Driver + and fct1.TextValue='Global Default' + and fct1.TimeClassID=12 + and fct1.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year') + and (fct2.TextValue like '%charges' or fct2.TextValue = 'Default') + and not exists ( + select top 1 1 + from [data].[ScoreFillin_Account] SF with (readuncommitted) + inner join [ob].[DimAccountPH] ph with (readuncommitted) + on ph.MemberGUID=sf.PlaceholderSectionMemberGUID + and ph.Name like 'Gross Charges%' + where db.MemberGUID=SF.ModelGUID + and SF.AccountID<>0 + ) + and db.DepartmentalBudgetID<>0 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetInvalidDropdownSelection +/************************************************************ +** Author: akowalski +** Create Date: 2014-05-13 +** Description: Finds any text boxes that saved a value of blank that will cause #n/a errors in the model +** Last Modified: 2016-12-05 +** GM Release: 2014.3 +********************************************************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2015-06-15 BL Filter out Not Specified Members (false positives) +** 2 2016-12-05 SK D-04790 When there are no different pay code groups, + false positives need to be filtered for the differential + hours and wage rates methodologies +*********************************************************************************************************/ + +CREATE view [ob].[viewExceptionsDepartmentBudgetInvalidDropdownSelection] as +--Accounts +select +Distinct +DB.DepartmentalBudgetID, +DB.Name as Model, +'Account ' + Dim.Name + ' has an invalid drop-down box selection' as Detail +from clientob.factaccountvar fct with (readuncommitted) +inner join ob.DimDepartmentalBudget DB with (readuncommitted) on fct.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join fw.DimAccount DIM with (readuncommitted) on fct.AccountID = DIM.AccountID +where fct.UnitTypeID=141 +--CID 1 -- +and DIM.AccountID<>0 +and TextValue_Formula='x' +and TextValue='' + +Union all + +-- Job Codes +select distinct + DB.DepartmentalBudgetID, + DB.Name as Model, + 'Job Code ' + Dim.Name + ' has an invalid drop-down box selection' as Detail +from clientob.FactStaffingPCVar fct with (readuncommitted) + inner join ob.DimDepartmentalBudget DB with (readuncommitted) on fct.DepartmentalBudgetID=db.DepartmentalBudgetID + inner join fw.DimJobCode DIM with (readuncommitted) on fct.JobCodeID = DIM.JobCodeID + inner join [fw].[DimPayCodeGroup] pcg on fct.PayCodeGroupID = pcg.PayCodeGroupID + INNER JOIN [fw].[DimAssumption] DA on fct.AssumptionID = DA.AssumptionID +where fct.UnitTypeID=141 +--CID 1 -- + and DIM.JobCodeID<>0 + and TextValue_Formula='x' + and TextValue='' + and EmployeeID=0 +-- CID 2 -- + and not + ( + (select count(1) from [fw].[DimPayCodeGroup] pcg1 where PCG1.ProductiveClassID = 5) = 0 + and DA.Name in ('Differential Hours Methodology', 'Differential Rate Methodology') + ) +-- CID 2 -- + +Union all + +-- Providers +select +Distinct +DB.DepartmentalBudgetID, +DB.Name as Model, +'Provider ' + Dim.Name + ' has an invalid drop-down box selection' as Detail +from clientob.FactProviderVar fct with (readuncommitted) +inner join ob.DimDepartmentalBudget DB with (readuncommitted) on fct.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join fw.DimProvider DIM with (readuncommitted) on fct.ProviderID = DIM.ProviderID +where fct.UnitTypeID=141 +--CID 1 -- +and DIM.ProviderID<>0 +and TextValue_Formula='x' +and TextValue='' + +union all +-- Employees +select +Distinct +DB.DepartmentalBudgetID, +DB.Name as Model, +'Employee ' + Dim.Name + ' has an invalid drop-down box selection' as Detail +from clientob.FactStaffingPCVar fct with (readuncommitted) +inner join ob.DimDepartmentalBudget DB with (readuncommitted) on fct.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join fw.DimEmployee DIM with (readuncommitted) on fct.EmployeeID = DIM.EmployeeID +where fct.UnitTypeID=141 +--CID 1 -- +and DIM.EmployeeID<>0 +and TextValue_Formula='x' +and TextValue='' +and DIM.EmployeeID<>0 + +union all +-- Global Methods +select +Distinct +DB.DepartmentalBudgetID, +DB.Name as Model, +'Global Method ' + Dim.LineName + ' has an invalid drop-down box selection' as Detail +from clientob.FactAccountRollupVar fct with (readuncommitted) +inner join ob.DimDepartmentalBudget DB with (readuncommitted) on fct.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join ob.DimFinancialReporting DIM with (readuncommitted) on fct.FinancialReportingID=DIM.FinancialReportingID +where fct.UnitTypeID=141 +--CID 1 -- +and DIM.FinancialReportingID<>0 +and TextValue_Formula='x' +and TextValue='' +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetInvalidGrossChargesSetups +CREATE view [ob].[viewExceptionsDepartmentBudgetInvalidGrossChargesSetups] as +/************************************************************ +** Author: akowalski +** Create Date: 2014-05-13 +** Description: Find mismatches between how the gross charge accounts are setup and what information is available in the model +** Last Modified: 2016-11-30 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2015-01-19 akk D-02448 Updating charge code section to look at global methods tab in addition to account level +** 2 2016-11-23 cbb D-03536 Provider - remove false positives when global methods are set to provider allocation +** 3 2016-11-30 srk D-04844 Updated first two unions to flag exceptions that don't have a primary revenue driver in the primary stat config screen +*************************************************************/ + +SELECT DISTINCT + dB.DepartmentalBudgetID, + dB.Name as Model, + 'Is set to drive charges by '+ ac.Textvalue+ ' but has no statistics in the model' as Detail +from clientob.FactAccountVar ac with (readuncommitted) + inner join fw.DimAssumption ASS with (readuncommitted) on ASS.AssumptionID=AC.AssumptionID + inner join ob.DimDepartmentalBudget DB with (readuncommitted) on ac.DepartmentalBudgetID=db.DepartmentalBudgetID +where 1=1 + and ac.TextValue like '%UOS%' + and ass.Name='Volume Driver' + and ac.TimeClassID = 12 + and ac.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year') + and not exists + ( + select top 1 1 from data.ScoreFillin_Account SF with (readuncommitted) + inner join ob.DimAccountPH ph with (readuncommitted) on ph.MemberGUID=sf.PlaceholderSectionMemberGUID + and (ph.Name like 'Statistics%' or ph.Name like 'Global Stat%') + INNER JOIN [ob].[viewFactDepartmentPrimaryStatisticConfiguration] PSC with (readuncommitted) on PSC.DepartmentalBudgetID = DB.DepartmentalBudgetID + AND PSC.AccountID = SF.AccountID + where db.MemberGUID=SF.ModelGUID + and SF.AccountID<>0 + AND PSC.Revenue = 1 + ) + and db.DepartmentalBudgetID<>0 + +Union all + +-- check for accounts using default on Global Methods tab +/********* Assumptions +1. Gross Charges are only ever filled in to the section that matches the patient class set on account in order to pull the global setting +2. Doesn't check if you have stats for the specific patient class selected +3. Doesn't check payor specific +*************/ + +SELECT + DISTINCT + dB.DepartmentalBudgetID, + dB.Name as Model, + 'Is set to drive charges by '+ fct2.Textvalue+ ' but has no statistics in the model' as Detail +from [data].[ScoreFillin_Account] sf1 with (readuncommitted) + inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on sf1.ModelGUID=DB.MemberGUID + inner join [ob].[DimAccountPH] ph1 with (readuncommitted) on sf1.PlaceholderSectionMemberGUID=ph1.MemberGUID + inner join clientob.FactAccountVar fct1 with (readuncommitted) on sf1.AccountID=fct1.AccountID and fct1.DepartmentalBudgetID=db.DepartmentalBudgetID + inner join [fw].[DimAccount] a with (readuncommitted) on sf1.AccountID=a.AccountID + inner join [clientob].[FactAccountRollupVar] fct2 with (readuncommitted) on a.PatientClassID=fct2.PatientClassID and DB.DepartmentalBudgetID=fct2.DepartmentalBudgetID + and fct1.AssumptionID=fct2.AssumptionID + inner join [ob].[DimFinancialReporting] fr with (readuncommitted) on fct2.FinancialReportingID=fr.FinancialReportingID and fr.MemberGUID='e02a8750-bc0f-47ac-922b-60e4ffd3c1e5' +where 1=1 + and ph1.Name like 'Gross Charge%' + and fct1.AssumptionID=184 --Volume Driver + and fct1.TextValue='Global Default' + and fct2.TextValue like '%UOS%' + and fct1.TimeClassID = 12 + and fct1.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year') + and not exists + ( + select top 1 1 from data.ScoreFillin_Account SF with (readuncommitted) + inner join ob.DimAccountPH ph with (readuncommitted) on ph.MemberGUID=sf.PlaceholderSectionMemberGUID + and (ph.Name like 'Statistics%' or ph.Name like 'Global Stat%') + INNER JOIN [ob].[viewFactDepartmentPrimaryStatisticConfiguration] PSC with (readuncommitted) on PSC.DepartmentalBudgetID = DB.DepartmentalBudgetID + AND PSC.AccountID = SF.AccountID + where 1=1 + and db.MemberGUID=SF.ModelGUID + and SF.AccountID<>0 + and PSC.Revenue = 1 + ) + and db.DepartmentalBudgetID<>0 + + + +union all + + +SELECT + DISTINCT + dB.DepartmentalBudgetID, + dB.Name as Model, + 'Is set to drive charges by '+ ac.Textvalue+ ' but has no charge codes in the model' as Detail +from clientob.FactAccountVar ac with (readuncommitted) + inner join fw.DimAssumption ASS with (readuncommitted) on ASS.AssumptionID=AC.AssumptionID + inner join ob.DimDepartmentalBudget DB with (readuncommitted) on ac.DepartmentalBudgetID=db.DepartmentalBudgetID +where 1=1 + and TextValue like '%CDM%' + and ass.Name='Volume Driver' + and ac.TimeClassID = 12 + and ac.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year') + and not exists + ( + select top 1 1 from data.ScoreFillin_ChargeCode SF with (readuncommitted) + inner join fw.DimChargeCodePH PH with (readuncommitted) on ph.MemberGUID=sf.PlaceholderSectionMemberGUID + where 1=1 + and db.MemberGUID=SF.ModelGUID + and sf.ChargeCodeID<>0 + ) + and db.DepartmentalBudgetID<>0 + +Union all + +SELECT + DISTINCT + dB.DepartmentalBudgetID, + dB.Name as Model, + 'Is set to drive charges by '+ ac.Textvalue+ ' but has no providers in the model' as Detail +from clientob.FactAccountVar ac with (readuncommitted) + inner join fw.DimAssumption ASS with (readuncommitted) on ASS.AssumptionID=AC.AssumptionID + inner join ob.DimDepartmentalBudget DB with (readuncommitted) on ac.DepartmentalBudgetID=db.DepartmentalBudgetID +where 1=1 + and TextValue like '%Provider%' + and ass.Name='Volume Driver' + and ac.TimeClassID = 12 + and ac.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year') + and not exists + ( + select top 1 1 from data.ScoreFillin_Provider SF with (readuncommitted) + inner join fw.DimProviderPH PH with (readuncommitted) on ph.MemberGUID=sf.PlaceholderSectionMemberGUID + where 1=1 + and db.MemberGUID=SF.ModelGUID + and sf.ProviderID<>0 + ) + and db.DepartmentalBudgetID<>0 + +union all + +--=============== BEGIN CID 1 ======================== +SELECT + DISTINCT + dB.DepartmentalBudgetID, + dB.Name as Model, + 'Is calculating revenue by charge code in section ' + substring(ph.Name,16,100) + ' but has no gross charge accounts configured to be impacted' as Detail +from data.ScoreFillin_ChargeCode SF with (readuncommitted) + inner join [fw].[DimChargeCodePH] ph with (readuncommitted) on SF.ChargeCodePHID=ph.ChargeCodePHID + inner join ob.DimDepartmentalBudget DB with (readuncommitted) + on SF.ModelGUID=db.MemberGUID + and not exists + ( + select top 1 1 + from clientob.FactAccountVar fct1 with (readuncommitted) + inner join [fw].[DimAccount] a on fct1.AccountID=a.AccountID and a.PatientClass=substring(ph.Name,16,100) + where 1=1 + and db.MemberGUID=SF.ModelGUID + and DB.DepartmentalBudgetID=fct1.DepartmentalBudgetID + and TextValue like '%CDM%' + and fct1.AssumptionID=184 --Volume Driver + and fct1.TimeClassID = 12 + and fct1.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year') + ) + and not exists + ( + select top 1 1 + from clientob.FactAccountRollupVar fct1 with (readuncommitted) + inner join [fw].[DimPatientClass] pc on fct1.patientclassid=pc.PatientClassID and pc.Name=substring(ph.Name,16,100) + inner join [ob].[DimFinancialReporting] fr with (readuncommitted) on fct1.FinancialReportingID=fr.FinancialReportingID and fr.MemberGUID='e02a8750-bc0f-47ac-922b-60e4ffd3c1e5' + inner join [clientob].[FactAccountVar] fct2 with (readuncommitted) on fct2.DepartmentalBudgetID=fct1.DepartmentalBudgetID and fct1.AssumptionID=fct2.AssumptionID + inner join [fw].[DimAccount] a on fct2.AccountID=a.AccountID and pc.PatientClassID=a.PatientClassID + inner join [data].[ScoreFillin_Account] sf on a.AccountID=sf.AccountID and DB.MemberGUID=sf.ModelGUID + where 1=1 + and db.MemberGUID = SF.ModelGUID + and DB.DepartmentalBudgetID = fct1.DepartmentalBudgetID + and fct1.TextValue like '%CDM%' + and fct1.AssumptionID = 184 --Volume Driver + and fct2.TextValue = 'Global Default' + and fct1.TimeClassID = 12 + and fct1.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year') + and sf.AccountPHID in + ( + '468', --'Gross Charges - Clinic', + '467', --'Gross Charges - ED', + '14', --'Gross Charges - Inpatient', + '466', --'Gross Charges - Observation', + '16', --'Gross Charges - Other', + '18'--'Gross Charges - Outpatient' + ) + ) + and sf.ChargeCodeID<>0 + and db.DepartmentalBudgetID<>0 + +--=============== END CID 1 ======================== + +union all + +--=============== BEGIN CID 2 ======================== +SELECT + DISTINCT + DepartmentalBudgetID = dB.DepartmentalBudgetID, + Model = dB.Name, + Detail = 'Is calculating revenue by provider but has no gross charge accounts configured to be impacted' +from data.ScoreFillin_Provider SF with (readuncommitted) + inner join [fw].[DimProviderPH] ph on SF.PlaceholderSectionMemberGUID = ph.MemberGUID + inner join ob.DimDepartmentalBudget DB with (readuncommitted) + on SF.ModelGUID=db.MemberGUID + and not exists + ( + select top 1 1 + from clientob.FactAccountVar AC with (readuncommitted) + inner join fw.DimAssumption ASS with (readuncommitted) on ASS.AssumptionID=AC.AssumptionID + where 1=1 + and DB.DepartmentalBudgetID = AC.DepartmentalBudgetID + and ac.TextValue = 'Provider Charge Allocation' + and ass.Name = 'Volume Driver' + and ac.TimeClassID = 12 + and ac.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year') + ) + and not exists + ( + select top 1 1 + from clientob.FactAccountRollupVar fct1 with (readuncommitted) + inner join [clientob].[FactAccountVar] fct2 with (readuncommitted) on fct2.DepartmentalBudgetID=fct1.DepartmentalBudgetID and fct1.AssumptionID=fct2.AssumptionID + inner join [fw].[DimAccount] a with (readuncommitted) on fct2.AccountID=a.AccountID and fct1.PatientClassID=a.PatientClassID + inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on a.AccountID=sf.AccountID and DB.MemberGUID=sf.ModelGUID + where 1=1 + and db.MemberGUID=SF.ModelGUID + and DB.DepartmentalBudgetID=fct1.DepartmentalBudgetID + and fct1.TextValue = 'Provider Charge Allocation' + and fct1.AssumptionID = 184 --Volume Driver + and fct2.TextValue = 'Global Default' + and fct1.TimeClassID = 12 + and fct1.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year') + and sf.AccountPHID in + ( + '468', --'Gross Charges - Clinic', + '467', --'Gross Charges - ED', + '14', --'Gross Charges - Inpatient', + '466', --'Gross Charges - Observation', + '16', --'Gross Charges - Other', + '18'--'Gross Charges - Outpatient' + ) + ) + and sf.ProviderID<>0 + and db.DepartmentalBudgetID<>0 + +--=============== END CID 2 ======================== +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetInvalidSpreadSelections +/************************************************************ +** Author: akowalski +** Create Date: 2015-01-18 +** Description: Displays any spread methods that will not match anything on the spreads tab +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ +create view [ob].[viewExceptionsDepartmentBudgetInvalidSpreadSelections] as +-- account +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Has an invalid spread setting for account ' + sf.FillinMemberName + 'in section ' + ph.Name as Detail +from [clientob].[FactAccountVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID +inner join [ob].[DimAccountPH] ph with (readuncommitted) on ph.AccountPHID=sf.AccountPHID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.AssumptionID=116 --Spread Method +and fct1.TimeClassID=2 +and fct1.TextValue not in ( + -- hard coded spreads + select val as name from [dbo].[ConvertCSValuesToTable] ('Default,Projected,Current Year Budget,Last Year Actual,Annualized,Actual-Budget,Rolling 12,Seasonalization,Act-Bud Var,Even,Days in Month,Budget UOS,Projected UOS,Budget Inpatient UOS,Budget Outpatient UOS,Budget Other UOS,Budget IP and OP UOS,Last Year Worked Hours,Current Year Worked Hours,Next Year Worked Hours,Hours in Month,Gross Revenue,Hours,Salaries,Quarterly,Volume Driver,Zero Based',',') + + union all + + -- global spreads + select fct1.Name from [clientob].[FactGlobalSpreads] fct1 + inner join [ob].[DimSpread] dim1 on fct1.SpreadID=dim1.SpreadID where dim1.IsBuiltIn=0 + + union all + + -- department specific spreads + select Text from [clientob].[FactSpreadVar] fct2 + where fct2.AssumptionID=117 --Spread Name + and fct2.DepartmentalBudgetID<>0 + and db.DepartmentalBudgetID=fct2.DepartmentalBudgetID +) + +union all + +-- Job Code dollars only +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Has an invalid spread setting for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [fw].[DimPayCodeGroup] ph with (readuncommitted) on fct1.PayCodeGroupid=ph.PayCodeGroupID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.AssumptionID=116 --Spread Method +and fct1.PayCodeGroupID<>0 +and fct1.TimeClassID=2 +and fct1.TextValue not in ( + -- hard coded spreads + select val as name from [dbo].[ConvertCSValuesToTable] ('Default,Projected,Current Year Budget,Last Year Actual,Annualized,Actual-Budget,Rolling 12,Seasonalization,Act-Bud Var,Even,Days in Month,Budget UOS,Projected UOS,Budget Inpatient UOS,Budget Outpatient UOS,Budget Other UOS,Budget IP and OP UOS,Last Year Worked Hours,Current Year Worked Hours,Next Year Worked Hours,Hours in Month,Gross Revenue,Hours,Salaries,Quarterly,Volume Driver,Zero Based',',') + + union all + + -- global spreads + select fct1.Name from [clientob].[FactGlobalSpreads] fct1 + inner join [ob].[DimSpread] dim1 on fct1.SpreadID=dim1.SpreadID where dim1.IsBuiltIn=0 + + union all + + -- department specific spreads + select Text from [clientob].[FactSpreadVar] fct2 + where fct2.AssumptionID=117 --Spread Name + and fct2.DepartmentalBudgetID<>0 + and db.DepartmentalBudgetID=fct2.DepartmentalBudgetID +) + +union all + +-- charge code volume spread +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Has an invalid volume spread setting for Charge Code ' + sf.FillinMemberName + ' in section ' + pc.Name as Detail +from [clientob].[FactCDMVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_ChargeCode] sf with (readuncommitted) on fct1.ChargeCodeID=sf.ChargeCodeID and sf.ModelGUID=db.MemberGUID +inner join [fw].[DimPatientClass] pc with (readuncommitted) on pc.PatientClassID=fct1.PatientClassID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.ChargeCodeID<>0 +and fct1.AssumptionID=116 --Spread Method +and fct1.TimeClassID=2 +and fct1.TextValue not in ( + -- hard coded spreads + select val as name from [dbo].[ConvertCSValuesToTable] ('Default,Projected,Current Year Budget,Last Year Actual,Annualized,Actual-Budget,Rolling 12,Seasonalization,Act-Bud Var,Even,Days in Month,Budget UOS,Projected UOS,Budget Inpatient UOS,Budget Outpatient UOS,Budget Other UOS,Budget IP and OP UOS,Last Year Worked Hours,Current Year Worked Hours,Next Year Worked Hours,Hours in Month,Gross Revenue,Hours,Salaries,Quarterly,Volume Driver,Zero Based',',') + + union all + + -- global spreads + select fct1.Name from [clientob].[FactGlobalSpreads] fct1 + inner join [ob].[DimSpread] dim1 on fct1.SpreadID=dim1.SpreadID where dim1.IsBuiltIn=0 + + union all + + -- department specific spreads + select Text from [clientob].[FactSpreadVar] fct2 + where fct2.AssumptionID=117 --Spread Name + and fct2.DepartmentalBudgetID<>0 + and db.DepartmentalBudgetID=fct2.DepartmentalBudgetID +) + +union all + +/************* Provider overrides ********************/ + +-- Budget vol/rev +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Has an invalid spread setting for Provider ' + sf.FillinMemberName + ' for forecast detail ' + fd.Name as Detail +from [clientob].[FactProviderVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Provider] sf with (readuncommitted) on fct1.ProviderID=sf.ProviderID and sf.ModelGUID=db.MemberGUID +inner join [ob].[DimOBForecastDetail] fd with (readuncommitted) on fct1.OBForecastDetailID=fd.OBForecastDetailID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.ProviderID<>0 +and fct1.AssumptionID=116 --Spread Method +and fct1.TimeClassID=2 +and fct1.TextValue not in ( + -- hard coded spreads + select val as name from [dbo].[ConvertCSValuesToTable] ('Default,Projected,Current Year Budget,Last Year Actual,Annualized,Actual-Budget,Rolling 12,Seasonalization,Act-Bud Var,Even,Days in Month,Budget UOS,Projected UOS,Budget Inpatient UOS,Budget Outpatient UOS,Budget Other UOS,Budget IP and OP UOS,Last Year Worked Hours,Current Year Worked Hours,Next Year Worked Hours,Hours in Month,Gross Revenue,Hours,Salaries,Quarterly,Volume Driver,Zero Based',',') + + union all + + -- global spreads + select fct1.Name from [clientob].[FactGlobalSpreads] fct1 + inner join [ob].[DimSpread] dim1 on fct1.SpreadID=dim1.SpreadID where dim1.IsBuiltIn=0 + + union all + + -- department specific spreads + select Text from [clientob].[FactSpreadVar] fct2 + where fct2.AssumptionID=117 --Spread Name + and fct2.DepartmentalBudgetID<>0 + and db.DepartmentalBudgetID=fct2.DepartmentalBudgetID +) + +union all + +-- Budget comp +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Has an invalid spread setting for Provider ' + sf.FillinMemberName + ' for forecast detail ' + fd.Name as Detail +from [clientob].[FactProviderVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Provider] sf with (readuncommitted) on fct1.ProviderID=sf.ProviderID and sf.ModelGUID=db.MemberGUID +inner join [ob].[DimOBForecastDetail] fd with (readuncommitted) on fct1.OBForecastDetailID=fd.OBForecastDetailID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.ProviderID<>0 +and fct1.AssumptionID=107 --Projection Method +and fct1.TimeClassID=2 +and fct1.TextValue not in ( + -- hard coded spreads + select val as name from [dbo].[ConvertCSValuesToTable] ('Default,Projected,Current Year Budget,Last Year Actual,Annualized,Actual-Budget,Rolling 12,Seasonalization,Act-Bud Var,Even,Days in Month,Budget UOS,Projected UOS,Budget Inpatient UOS,Budget Outpatient UOS,Budget Other UOS,Budget IP and OP UOS,Last Year Worked Hours,Current Year Worked Hours,Next Year Worked Hours,Hours in Month,Gross Revenue,Hours,Salaries,Quarterly,Volume Driver,Zero Based',',') + + union all + + -- global spreads + select fct1.Name from [clientob].[FactGlobalSpreads] fct1 + inner join [ob].[DimSpread] dim1 on fct1.SpreadID=dim1.SpreadID where dim1.IsBuiltIn=0 + + union all + + -- department specific spreads + select Text from [clientob].[FactSpreadVar] fct2 + where fct2.AssumptionID=117 --Spread Name + and fct2.DepartmentalBudgetID<>0 + and db.DepartmentalBudgetID=fct2.DepartmentalBudgetID +) +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetInvalidVariableExpenseConfigurations +/************************************************************ +** Author: akowalski +** Create Date: 2014-08-27 +** Description: Finds departments with variable job codes or accounts with no statistics configured to drive them +** Last Modified: 2017-02-27 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-11-29 srk D-04844 In templates >2016.3, stat driver assumptions are not stored in var tables. +** these need to be pulled directly from the primary statistic table. +** 2 2016-02-27 srk D-05529 Fixed join on department ID. +*************************************************************/ + +CREATE view [ob].[viewExceptionsDepartmentBudgetInvalidVariableExpenseConfigurations] as + +--INVALID STAFFING DRIVER CONFIGURATION + +SELECT +DISTINCT + DB.DepartmentalBudgetID, + DB.Name as Model, + 'Has variable job codes but no statistic accounts configured as staffing drivers' as Detail +FROM [data].[ScoreFillin_JobCode] SF1 with (readuncommitted) + INNER JOIN ob.DimDepartmentalBudget DB with (readuncommitted) on DB.MemberGUID=SF1.ModelGUID + INNER JOIN [fw].[DimDepartment] DD with (readuncommitted) on DB.DepartmentID=DD.DepartmentID +WHERE + 1=1 + AND SF1.PlaceholderSectionMemberGUID='ae9287bc-5f5f-408f-afdf-146cae3272ae' --Staffing - Job Code (Variable) + AND DD.IsVariable=1 + AND NOT EXISTS + ( + SELECT top 1 1 from data.ScoreFillin_Account SF with (readuncommitted) + INNER JOIN ob.DimAccountPH PH with (readuncommitted) on PH.MemberGUID=sf.PlaceholderSectionMemberGUID + AND (ph.Name like 'Statistics%' OR ph.Name like 'Global Stat%') + INNER JOIN [ob].[viewFactDepartmentPrimaryStatisticConfiguration] PSC with (readuncommitted) on PSC.DepartmentalBudgetID = DB.DepartmentalBudgetID + AND PSC.AccountID = SF.AccountID + WHERE DB.MemberGUID=SF.ModelGUID + AND SF.AccountID<>0 + AND PSC.Staffing = 1 --Staffing Driver + ) + +union all + +--INVALID NON-STAFFING EXPENSE DRIVER CONFIGURATION + + +SELECT +DISTINCT + DB.DepartmentalBudgetID, + DB.Name as Model, + 'Has variable expense accounts but no statistic accounts configured as expense account drivers' as Detail +FROM [data].[ScoreFillin_Account] SF1 with (readuncommitted) + INNER JOIN ob.DimDepartmentalBudget DB with (readuncommitted) on DB.MemberGUID=SF1.ModelGUID + INNER JOIN [fw].[DimDepartment] DD with (readuncommitted) on DB.DepartmentID=DD.DepartmentID --CID 2 + INNER JOIN [fw].[DimAccount] DA on SF1.AccountID=DA.AccountID +WHERE + 1=1 + AND SF1.PlaceholderSectionMemberGUID='aa2a181f-d126-4b47-ac88-dba1445508a7' --Expenses - Non-Staffing + AND DD.IsVariable=1 + AND DA.Variability=1 + AND NOT EXISTS + ( + SELECT top 1 1 from data.ScoreFillin_Account SF with (readuncommitted) + INNER JOIN ob.DimAccountPH PH with (readuncommitted) on PH.MemberGUID=SF.PlaceholderSectionMemberGUID + AND (PH.Name like 'Statistics%' or PH.Name like 'Global Stat%') + INNER JOIN [ob].[viewFactDepartmentPrimaryStatisticConfiguration] PSC with (readuncommitted) on PSC.DepartmentalBudgetID = DB.DepartmentalBudgetID + AND PSC.AccountID = SF.AccountID + WHERE db.MemberGUID=SF.ModelGUID + AND SF.AccountID<>0 + AND PSC.NonStaffingExpense = 1 --Non-Staffing Expense Driver + ) +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetMissingGlobalStatisticConfigurations +/************************************************************ +** Author: akowalski +** Create Date: 2014-09-19 +** Description: Checks statistics filled into department budgets where there is a global statistic model associated with the department +** Last Modified: 2014-09-19 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ +create view ob.viewExceptionsDepartmentBudgetMissingGlobalStatisticConfigurations as +select + Distinct + dB.DepartmentalBudgetID, + dB.Name as Model, + a.Name + ' appears as a statistic in the model but has no global statistic configured' as Detail +from data.ScoreFillin_Account SF with (readuncommitted) +inner join ob.DimDepartmentalBudget DB with (readuncommitted) on DB.MemberGUID=SF.ModelGUID +inner join [fw].[DimDepartment] d with (readuncommitted) on DB.DepartmentID=d.DepartmentID +inner join [fw].[DimAccount] a with (readuncommitted) on sf.AccountID=a.AccountID +inner join ob.DimAccountPH ph with (readuncommitted) on ph.MemberGUID=sf.PlaceholderSectionMemberGUID +left outer join [ob].[DimOBGlobalStatistics] gs with (readuncommitted) on gs.AccountID=a.AccountID and gs.DepartmentID=d.DepartmentID +where (ph.Name like 'Statistics%' or ph.Name like 'Global Stat%') +and gs.Name is null +and db.DepartmentalBudgetID<>0 +and d.OBGlobalStatisticsPlanID<>0 +and a.IsGlobal=0 + +union all + +select + Distinct + dB.DepartmentalBudgetID, + dB.Name as Model, + a.Name + ' appears as a statistic in the department model but is not filled into the global statistic model' as Detail +from data.ScoreFillin_Account SF with (readuncommitted) +inner join ob.DimDepartmentalBudget DB with (readuncommitted) on DB.MemberGUID=SF.ModelGUID +inner join [fw].[DimDepartment] d with (readuncommitted) on DB.DepartmentID=d.DepartmentID +inner join [fw].[DimAccount] a with (readuncommitted) on sf.AccountID=a.AccountID +inner join ob.DimAccountPH ph with (readuncommitted) on ph.MemberGUID=sf.PlaceholderSectionMemberGUID +inner join [ob].[DimOBGlobalStatistics] gs with (readuncommitted) on gs.AccountID=a.AccountID and gs.DepartmentID=d.DepartmentID +inner join [ob].[DimOBGlobalStatisticsPlan] gsp with (readuncommitted) on gsp.OBGlobalStatisticsPlanID=d.OBGlobalStatisticsPlanID +left outer join [data].[ScoreFillin_OBGlobalStatistics] sf2 with (readuncommitted) on sf2.ModelGUID=gsp.MemberGUID and sf2.FillinMemberGUID=gs.MemberGUID +where (ph.Name like 'Statistics%' or ph.Name like 'Global Stat%') +and sf2.FillinGUID is null +and db.DepartmentalBudgetID<>0 +and d.OBGlobalStatisticsPlanID<>0 +and a.IsGlobal=0 + + +union all + +select + Distinct + dB.DepartmentalBudgetID, + dB.Name as Model, + a.Name + ' appears as a statistic in the department model but is not configured in the global stats to department mapping table' as Detail +from data.ScoreFillin_Account SF with (readuncommitted) +inner join ob.DimDepartmentalBudget DB with (readuncommitted) on DB.MemberGUID=SF.ModelGUID +inner join [fw].[DimDepartment] d with (readuncommitted) on DB.DepartmentID=d.DepartmentID +inner join [fw].[DimAccount] a with (readuncommitted) on sf.AccountID=a.AccountID +inner join ob.DimAccountPH ph with (readuncommitted) on ph.MemberGUID=sf.PlaceholderSectionMemberGUID +inner join [ob].[DimOBGlobalStatisticsPlan] gsp with (readuncommitted) on gsp.OBGlobalStatisticsPlanID=d.OBGlobalStatisticsPlanID +inner join [ob].[DimOBGlobalStatistics] gs with (readuncommitted) on gs.AccountID=a.AccountID and gs.DepartmentID=0 +left outer join [clientob].[FactGlobalStatisticsDeptMapping] fct with (readuncommitted) on fct.OBGlobalStatisticsPlanID=gsp.OBGlobalStatisticsPlanID and d.DepartmentID=fct.DepartmentID and fct.OBGlobalStatisticID=gs.OBGlobalStatisticID +where (ph.Name like 'Statistics%' or ph.Name like 'Global Stat%') +and fct.RowID is null +and db.DepartmentalBudgetID<>0 +and d.OBGlobalStatisticsPlanID<>0 +and a.IsGlobal=1 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetMissingNotSpecifiedFillins +/************************************************************ +** Author: dmoldawer +** Create Date: 2014-03-21 +** Description: Finds all missing not specified fillins in the OB Departmental Budget model for the Account, Employee, Job Code, OB Financial Reporting, Pay Code Group, and Provider dimensions +** Last Modified: 2013-03-21 +** GM Release: 2014.3 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + +CREATE view [ob].[viewExceptionsDepartmentBudgetMissingNotSpecifiedFillins] as +select + DB.DepartmentalBudgetID, + DB.Name as Model, + 'Is Missing the Not Specified Employee' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) +where + not exists(select 1 from data.ScoreFillin_Employee FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.EmployeeID = 0 and FI.EmployeePHID = 0) + and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1 + +union all + +select + DB.DepartmentalBudgetID, + DB.Name as Model, + 'Is Missing the Not Specified Job Code' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) +where + not exists(select 1 from data.ScoreFillin_JobCode FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.JobCodeID = 0 and FI.JobCodePHID = 0) + and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1 + +union all + +select + DB.DepartmentalBudgetID, + DB.Name as Model, + 'Is Missing the Not Specified Pay Code Group' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) +where + not exists(select 1 from data.ScoreFillin_PayCodeGroup FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.PayCodeGroupID = 0 and FI.PayCodeGroupPHID = 0) + and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetMissingPayrollToAccountCrosswalkConfigurations +/************************************************************ +** Author: mschmitz +** Create Date: 2015-01-18 +** Description: Checks for job code/pay code group combos that have dollars budgeted but no matching GL account in the payroll to account crosswalk +** Last Modified: 2016-11-25 +** GM Release: 2017.1 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-11-25 vyaremko D-04954 +** +*************************************************************/ +CREATE VIEW ob.viewExceptionsDepartmentBudgetMissingPayrollToAccountCrosswalkConfigurations AS +SELECT DISTINCT + F.DepartmentalBudgetID, + B.Name AS 'Model', + CASE F.UnitTypeID + WHEN 34 THEN 'Has ' + PCG.Name +' dollars budgeted to ' + JC.Name + ' but this payroll combination is not mapped to a GL account' + WHEN 51 THEN 'Has ' + PCG.Name +' hours budgeted to ' + JC.Name + ' but this payroll combination is not mapped to a GL account' + END AS 'Detail' +FROM [clientob].[FactStaffingPC] F with (readuncommitted) +INNER JOIN [ob].[DimDepartmentalBudget] B with (readuncommitted) + ON F.DepartmentalBudgetID = B.DepartmentalBudgetID +INNER JOIN [fw].[DimPayCodeGroup] PCG with (readuncommitted) + ON F.PayCodeGroupID = PCG.PayCodeGroupID +INNER JOIN [fw].[DimJobCode] JC with (readuncommitted) + ON F.JobCodeID = JC.JobCodeID +WHERE + F.Total <> 0 + AND F.UnitTypeID in (34, 51) + AND F.DataTypeID = 3 + AND NOT EXISTS ( + SELECT 1 + FROM [clientob].[FactPayrollToAccountCrosswalk] X with (readuncommitted) + WHERE + ( + (X.JobCodeID = F.JobCodeID AND X.PayCodeGroupID = F.PayCodeGroupID) --pay code group and job code specific + OR (X.JobCodeID = F.JobCodeID AND X.PayCodeGroupID = 0) --job code specific + OR (X.JobCodeID = 0 AND X.PayCodeGroupID = F.PayCodeGroupID) --pay code group specific + ) + AND X.UnitTypeID = F.UnitTypeID + AND X.IsDeleted = 0 + ) +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetMissingPrimaryStatisticConfigurations +/************************************************************ +** Author: akowalski +** Create Date: 2014-08-27 +** Description: Find mismatches between what is configured in the department primary statistic table and what is actually filled into the model +** Last Modified: 2014-08-27 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2014-12-1 blewis D-02439 Report should exclude inactive departments and fixed departments without gross charges +** +*************************************************************/ + +CREATE view [ob].[viewExceptionsDepartmentBudgetMissingPrimaryStatisticConfigurations] as + +select + Distinct + dB.DepartmentalBudgetID, + dB.Name as Model, + a.Name + ' appears as a statistic in the model but is not configured in the driver statistic table' as Detail +from data.ScoreFillin_Account SF with (readuncommitted) +inner join ob.DimDepartmentalBudget DB with (readuncommitted) on DB.MemberGUID=SF.ModelGUID +--*********************CID 1 ******************************* +inner join [fw].[DimDepartment] d with (readuncommitted) on DB.DepartmentID=DB.DepartmentID +--*********************CID 1 ******************************* +inner join [fw].[DimAccount] a with (readuncommitted) on sf.AccountID=a.AccountID +inner join ob.DimAccountPH ph with (readuncommitted) on ph.MemberGUID=sf.PlaceholderSectionMemberGUID +left outer join [client].[FactDepartmentPrimaryStatisticConfiguration] ps with (readuncommitted) on DB.DepartmentID=ps.DepartmentID and a.AccountID=ps.AccountID +where (ph.Name like 'Statistics%' or ph.Name like 'Global Stat%') +and ps.RowID is null +and db.DepartmentalBudgetID<>0 +--*********************CID 1 ******************************* +and d.IsVariable=1 +and d.IsActive=1 +--*********************CID 1 ******************************* + +union all + +select + Distinct + dB.DepartmentalBudgetID, + dB.Name as Model, + a.Name + ' appears in the driver statistic table but does not appear in the model' as Detail +from [client].[FactDepartmentPrimaryStatisticConfiguration] ps with (readuncommitted) +inner join ob.DimDepartmentalBudget DB with (readuncommitted) on ps.DepartmentID=db.DepartmentID +--*********************CID 1 ******************************* +inner join [fw].[DimDepartment] d with (readuncommitted) on DB.DepartmentID=DB.DepartmentID +--*********************CID 1 ******************************* +inner join [fw].[DimAccount] a with (readuncommitted) on ps.AccountID=a.AccountID +cross join [ob].[DimAccountPH] ph with (readuncommitted) +left outer join data.ScoreFillin_Account SF with (readuncommitted) on a.AccountID=SF.AccountID and DB.MemberGUID=SF.ModelGUID +where (ph.Name like 'Statistics%' or ph.Name like 'Global Stat%') +and sf.RowID is null +and db.DepartmentalBudgetID<>0 +--*********************CID 1 ******************************* +and d.IsVariable=1 +and d.IsActive=1 +--*********************CID 1 ******************************* + +--Fixed Departments with Charges (Section Unioned for CID 1) + +union all + +select + Distinct + dB.DepartmentalBudgetID, + dB.Name as Model, + a.Name + ' appears as a statistic in the model but is not configured in the driver statistic table' as Detail +from data.ScoreFillin_Account SF with (readuncommitted) +inner join ob.DimDepartmentalBudget DB with (readuncommitted) on DB.MemberGUID=SF.ModelGUID +inner join [fw].[DimDepartment] d with (readuncommitted) on DB.DepartmentID=DB.DepartmentID +inner join [fw].[DimAccount] a with (readuncommitted) on sf.AccountID=a.AccountID +inner join ob.DimAccountPH ph with (readuncommitted) on ph.MemberGUID=sf.PlaceholderSectionMemberGUID +left outer join [client].[FactDepartmentPrimaryStatisticConfiguration] ps with (readuncommitted) on DB.DepartmentID=ps.DepartmentID and a.AccountID=ps.AccountID +where (ph.Name like 'Statistics%' or ph.Name like 'Global Stat%') +and ps.RowID is null +and db.DepartmentalBudgetID<>0 +and d.IsVariable=0 +and d.IsActive=1 +--Only Include Fixed Departments with Charges +and DB.MemberGUID IN(SELECT sfa.[ModelGUID] + FROM [data].[ScoreFillin_Account] sfa + inner join [ob].[DimAccountPH] aph on sfa.AccountPHID=aph.AccountPHID + where aph.Name like 'Gross Charges%') + +union all + +select + Distinct + dB.DepartmentalBudgetID, + dB.Name as Model, + a.Name + ' appears in the driver statistic table but does not appear in the model' as Detail +from [client].[FactDepartmentPrimaryStatisticConfiguration] ps with (readuncommitted) +inner join ob.DimDepartmentalBudget DB with (readuncommitted) on ps.DepartmentID=db.DepartmentID +inner join [fw].[DimDepartment] d with (readuncommitted) on DB.DepartmentID=DB.DepartmentID +inner join [fw].[DimAccount] a with (readuncommitted) on ps.AccountID=a.AccountID +cross join [ob].[DimAccountPH] ph with (readuncommitted) +left outer join data.ScoreFillin_Account SF with (readuncommitted) on a.AccountID=SF.AccountID and DB.MemberGUID=SF.ModelGUID +where (ph.Name like 'Statistics%' or ph.Name like 'Global Stat%') +and sf.RowID is null +and db.DepartmentalBudgetID<>0 +and d.IsVariable=0 +and d.IsActive=1 +--Only Include Fixed Departments with Charges +and DB.MemberGUID IN(SELECT sfa.[ModelGUID] + FROM [data].[ScoreFillin_Account] sfa + inner join [ob].[DimAccountPH] aph on sfa.AccountPHID=aph.AccountPHID + where aph.Name like 'Gross Charges%') +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetMissingProductivityStandards +/************************************************************ +** Author: akowalski +** Create Date: 2014-08-27 +** Description: Finds departments with variable job codes but no productivity standard specified +** Last Modified: 2014-08-27 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-02-01 CBB/BL(assist) D-03585 exclude plans if template setting is projected +** +*************************************************************/ + +create view [ob].[viewExceptionsDepartmentBudgetMissingProductivityStandards] as +select +Distinct + dB.DepartmentalBudgetID, + dB.Name as Model, + 'Has variable job codes but no productivity standard specified for the current year projection' as Detail +from [data].[ScoreFillin_JobCode] sf1 with (readuncommitted) +inner join ob.DimDepartmentalBudget DB with (readuncommitted) on DB.MemberGUID=sf1.ModelGUID +inner join [fw].[DimDepartment] d with (readuncommitted) on DB.DepartmentID=d.DepartmentID +--CID 1 begin +inner join [dbo].[XPlan] x on DB.MemberGUID=x.PlanGUID +inner join [dbo].[TemplateSettings] ts on x.ModelTemplateGUID=ts.TemplateGUID +--CID 1 end +where sf1.PlaceholderSectionMemberGUID='ae9287bc-5f5f-408f-afdf-146cae3272ae' --Staffing - Job Code (Variable) +and d.IsVariable=1 and db.OBActivePlans=1 +and (db.WorkedHrsperUOSProjection=0) +--CID 1 begin +and ts.SettingID='GlobalDefaults_Staffing_HrsperUOS_ProjectedOrSupplied' +and ts.Value='Supplied' +--CID 1 end + +union all + +select +Distinct + dB.DepartmentalBudgetID, + dB.Name as Model, + 'Has variable job codes but no productivity standard specified for next year''s budget' as Detail +from [data].[ScoreFillin_JobCode] sf1 with (readuncommitted) +inner join ob.DimDepartmentalBudget DB with (readuncommitted) on DB.MemberGUID=sf1.ModelGUID +inner join [fw].[DimDepartment] d with (readuncommitted) on DB.DepartmentID=d.DepartmentID +--CID 1 begin +inner join [dbo].[XPlan] x on DB.MemberGUID=x.PlanGUID +inner join [dbo].[TemplateSettings] ts on x.ModelTemplateGUID=ts.TemplateGUID +--CID 1 end +where sf1.PlaceholderSectionMemberGUID='ae9287bc-5f5f-408f-afdf-146cae3272ae' --Staffing - Job Code (Variable) +and d.IsVariable=1 and DB.OBActivePlans=1 +and (db.WorkedHrsperUOSBudget=0) +--CID 1 begin +and ts.SettingID='GlobalDefaults_Staffing_HrsperUOS_ProjectedOrSupplied' +and ts.Value='Supplied' +--CID 1 end +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetMissingProviderBenefitAccounts +CREATE view [ob].[viewExceptionsDepartmentBudgetMissingProviderBenefitAccounts] + as +select + distinct + DB.DepartmentalBudgetID, + DB.Name as Model, + 'Is forecasting provider benefit type ' + fd.Name + ' but has no benefit accounts filled into the model' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join [data].[ScoreFillin_OBForecastDetail] sf on db.memberguid=sf.ModelGUID and OBForecastDetailPHID=18 --Provider - Benefits + inner join [ob].[DimOBForecastDetail] fd on sf.OBForecastDetailID=fd.OBForecastDetailID + inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid and sfp.ProviderID<>0 +where + not exists (select 1 from data.ScoreFillin_Account FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.AccountID<>0 and FI.AccountPHID = 7 /*Benefits*/) + and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetMissingProviderDeductionAccounts +/************************************************************ +** Author: bparrott +** Create Date: 2015-01-18 +** Description: Budgets that are forecasting deductions by provider, but do not have the associated deductions accounts filled-in to the model. +** Last Modified: +** GM Release: 2015.2 +*************************************************************/ +Create view [ob].[viewExceptionsDepartmentBudgetMissingProviderDeductionAccounts] + as +select + distinct + DB.DepartmentalBudgetID, + DB.Name as Model, + 'Is forecasting provider deduction type ' + fd.Name + ' but has no deduction accounts filled into the model' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + inner join [data].[ScoreFillin_OBForecastDetail] sf on db.memberguid=sf.ModelGUID and OBForecastDetailPHID=5 --Provider - Deductions + inner join [ob].[DimOBForecastDetail] fd on sf.OBForecastDetailID=fd.OBForecastDetailID + inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid and sfp.ProviderID<>0 +where + not exists (select 1 from data.ScoreFillin_Account FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.AccountID<>0 and FI.AccountPHID = 4 /*Deductions*/) + and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetMissingSelfFillin +/************************************************************ +** Author: akowalski +** Create Date: 2014-05-13 +** Description: Displays any department budgets that are missing their self fill-in +** Last Modified: 2014-05-13 +** GM Release: 2014.3 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-08-10 kf B-12543 FP - System Center Exception Management - Initial Framework +*************************************************************/ + +CREATE view [ob].[viewExceptionsDepartmentBudgetMissingSelfFillin] as + +select +Distinct +DB.DepartmentalBudgetID, +DB.Name as Model, +'Department Budget ' + db.Name + ' is missing the self-fill-in' as Detail +from ob.DimDepartmentalBudget DB with (readuncommitted) +left outer join data.ScoreFillin_OBDepartmentalBudget sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and PlaceholderSectionMemberGUID='58106837-6396-47A4-9876-05DD97C9224E' +where sf.FillinGUID is null +and db.DepartmentalBudgetID<>0 and db.obactiveplans=1 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetMissingXPlanRecords +/************************************************************ +** Author: akowalski +** Create Date: 2014-09-22 +** Description: Checks for poorly created plans (plans with a dimension record but no xplan record) +** Last Modified: 2014-09-22 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ +create view ob.viewExceptionsDepartmentBudgetMissingXPlanRecords as +select +Distinct +db.DepartmentalBudgetID, +d.Name as Model, +'Department Budget record exists in the ob.dimdepartmentalbudget table but not in xplan' as Detail +from [ob].[DimDepartmentalBudget] db +left outer join [fw].[DimDepartment] d on db.DepartmentID=d.DepartmentID +left outer join [dbo].[XPlan] xp on DB.MemberGUID=xp.PlanGUID +where xp.Name is null +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetModelToReconciliationTargetComparision +CREATE view [ob].[viewExceptionsDepartmentBudgetModelToReconciliationTargetComparision] as +/************************************************************ +** Author: akowalski +** Create Date: 2014-06-12 +** Description: Compares the post-model refresh financial statement results with the target financial statement values specified using the reconciliation tool +** Last Modified: 2014-06-12 +** GM Release: 2014.3 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-12-14 srk D-04952 Case statement for detail description +*************************************************************/ +select + 0 as DepartmentalBudgetID, + 'Not Specified' as Model, + fr.Name + ' has value ' + cast(round(src.Amount,0) as varchar(25)) + ' for Entity: ' + + e.Name + ' but should have ' + cast(round(trgt.Amount,0) as varchar(25)) + + ' in ' + tc.Name + ' ' + cast(src.fiscalyearid as varchar(4)) + + case when src.fiscalmonthid = 0 then '' else ' in Month ' + m.name END as Detail +from [ob].[viewFactReportingMonthlyTargetComparision] src +inner join [ob].[ReconciliationTarget] trgt + on trgt.EntityID=src.EntityID + and trgt.FiscalYearID=src.FiscalYearID + and trgt.TimeClassID=src.TimeClassID + and trgt.FinancialReportingID=src.FinancialReportingID + and trgt.FiscalMonthID=src.FiscalMonthID +inner join [ob].[DimFinancialReporting] fr on src.FinancialReportingID=fr.FinancialReportingID +inner join [fw].[DimEntity] e on src.EntityID=e.EntityID +inner join [fw].[DimTimeClass] tc on src.TimeClassID=tc.TimeClassID +inner join [fw].[DimFiscalMonth] m on src.FiscalMonthID=m.FiscalMonthID +where round(trgt.Amount,-2)<>round(src.Amount,-2) +and round(trgt.Amount,-1)<>round(src.Amount,-1) +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetNoReviewerAssignments +/************************************************************ +** Author: akowalski +** Create Date: 2015-01-18 +** Description: Displays all non-staffing expense accounts that have manager adjustments but no comments +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ +create view [ob].[viewExceptionsDepartmentBudgetNoReviewerAssignments] as +select Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Has no reviewers configured' as Detail from [ob].[DimDepartmentalBudget] db +inner join [dbo].[XPlan] xp on db.MemberGUID=xp.PlanGUID +where xp.PlanTypeGUID='05512126-3eb6-4da4-af6e-bc2bc2724b8b' +and db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and not exists(select 1 from [dbo].[viewS3RoleAssignmentDetail] ra +where lootGroupID like 'DEPT|%' and ra.RoleName like 'OB - %' and xp.CachedLootID=ra.LootID +) +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetOrphanedData +/************************************************************************* +** Author: akowalski +** Create Date: 2014-05-13 +** Description: Checks for nonzero data that will not show up in the model because a fillin is missing +** Last Modified: 2014-05-13 +** GM Release: 2014.3 +*************************************************************************** +** Change History +*************************************************************************** +** CID Date Author WI Description +** 1 2016-12-27 srk D-05208 Filtering out inactive providers +** 2 2016-12-29 srk D-05186 Filtering out prior year budget timeclass +**************************************************************************/ + + +CREATE view [ob].[viewExceptionsDepartmentBudgetOrphanedData] as + +-- Account data + select + Distinct + db.DepartmentalBudgetID, + db.Name as Model, + 'Has data in Account ' + dim.Name+ ' but it is not filled in' as Detail + from + clientob.FactAccount data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + inner join fw.DimAccount dim with (readuncommitted) on dim.AccountID = data.AccountID + left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID + and sf.PlaceholderSectionMemberGUID<>'77A0029B-F072-4ED6-8BFC-89BCFD6ED049' --not specified + where + sf.FillinGUID is null + and data.Total <> 0 + and + --CID 2 + ((( + data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Actual Data + and data.timeclassid = 1 + ) + or + ( + data.FiscalYearID = (select s.setting from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Current Year + and data.timeclassid = 2 + ) + or + ( + data.FiscalYearID = (select s.setting+1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Next Year + and data.timeclassid = 2 + ))) + --CID 2 + and db.DepartmentalBudgetID<>0 + and dim.AccountID<>0 + and not (dim.OBIsDefined=1 and dim.OBAccountPHID=0 and dim.OBStatModelSectionID=0) + and db.obactiveplans=1 + +UNION ALL + +--Job Code Data + select + Distinct + db.DepartmentalBudgetID, + db.Name as Model, + 'Has data in Job Code ' + dim.Name+ ' but it is not filled in' as Detail + + from + clientob.FactStaffingPC data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + inner join fw.DimJobCode dim with (readuncommitted) on dim.JobCodeID = data.JobCodeID + left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID + and sf.PlaceholderSectionMemberGUID<>'26FE98B4-987C-403B-84E3-6630F96001F9' --not specified + where + sf.FillinGUID is null + and data.Total <> 0 + and + --CID 2 + ((( + data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Actual Data + and data.timeclassid = 1 + ) + or + ( + data.FiscalYearID = (select s.setting from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Current Year + and data.timeclassid = 2 + ) + or + ( + data.FiscalYearID = (select s.setting+1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Next Year + and data.timeclassid = 2 + ))) + --CID 2 + and db.DepartmentalBudgetID<>0 + and dim.JobCodeID<>0 + and db.obactiveplans=1 + +UNION ALL + +--Pay Code Group + select + Distinct + db.DepartmentalBudgetID, + db.Name as Model, + 'Has data in Pay Code Group ' + dim.Name+ ' but it is not filled in' as Detail + + from + clientob.FactStaffingPC data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + inner join fw.DimPayCodeGroup dim with (readuncommitted) on dim.PayCodeGroupID = data.PayCodeGroupID + left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID + and sf.PlaceholderSectionMemberGUID<>'119D96CF-81AF-4D69-A671-5E5B23F9F9DD' --not specified + where + sf.FillinGUID is null + and data.Total <> 0 + and + --CID 2 + ((( + data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Actual Data + and data.timeclassid = 1 + ) + or + ( + data.FiscalYearID = (select s.setting from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Current Year + and data.timeclassid = 2 + ) + or + ( + data.FiscalYearID = (select s.setting+1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Next Year + and data.timeclassid = 2 + ))) + --CID 2 + and db.DepartmentalBudgetID<>0 + and dim.PayCodeGroupID<>0 + and db.obactiveplans=1 + +UNION ALL + +--Employee + select + Distinct + db.DepartmentalBudgetID, + db.Name as Model, + 'Has data for Employee ' + dim.Name+ ' but it is not filled in' as Detail + + from + clientob.FactStaffingPC data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + inner join fw.DimEmployee dim with (readuncommitted) on dim.EmployeeID = data.EmployeeID + left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID + and sf.PlaceholderSectionMemberGUID<>'A3882825-3889-4669-BA58-886F984F739F' --not specified + inner join DBSetting s with (readuncommitted) on s.Name='OB_Employee_Detail' and s.Setting='1' + where + sf.FillinGUID is null + and data.Total <> 0 + and + --CID 2 + ((( + data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Actual Data + and data.timeclassid = 1 + ) + or + ( + data.FiscalYearID = (select s.setting from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Current Year + and data.timeclassid = 2 + ) + or + ( + data.FiscalYearID = (select s.setting+1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Next Year + and data.timeclassid = 2 + ))) + --CID 2 + and db.DepartmentalBudgetID<>0 + and dim.EmployeeID<>0 + and db.obactiveplans=1 + + +UNION ALL + +--Provider Data + select + Distinct + db.DepartmentalBudgetID, + db.Name as Model, + 'Has data for Provider ' + dim.Name+ ' but it is not filled in' as Detail + from + clientob.FactProvider data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + inner join fw.DimProvider dim with (readuncommitted) on dim.ProviderID = data.ProviderID + left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID + and sf.PlaceholderSectionMemberGUID<>'93524AAB-C5E0-428F-81DE-6AD7ED5CE0CC' --not specified + where + sf.FillinGUID is null + and data.Total <> 0 + and + --CID 2 + ((( + data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Actual Data + and data.timeclassid = 1 + ) + or + ( + data.FiscalYearID = (select s.setting from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Current Year + and data.timeclassid = 2 + ) + or + ( + data.FiscalYearID = (select s.setting+1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Next Year + and data.timeclassid = 2 + ))) + --CID 2 + and db.DepartmentalBudgetID<>0 + and dim.ProviderID<>0 + -- CID 1 + and dim.OBIsActive = 1 + -- CID 1 + and db.obactiveplans=1 + +UNION ALL + +--Charge Code Data + select + Distinct + db.DepartmentalBudgetID, + db.Name as Model, + 'Has data for Charge Code ' + dim.Name+ ' but it is not filled in' as Detail + + from + clientob.FactCDM data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + inner join fw.DimChargeCode dim with (readuncommitted) on dim.ChargeCodeID = data.ChargeCodeID + left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID + and sf.PlaceholderSectionMemberGUID<>'9482496E-5ABF-452A-884D-BF874AABF0DC' --not specified + where + sf.FillinGUID is null + and data.Total <> 0 + and + --CID 2 + ((( + data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Actual Data + and data.timeclassid = 1 + ) + or + ( + data.FiscalYearID = (select s.setting from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Current Year + and data.timeclassid = 2 + ) + or + ( + data.FiscalYearID = (select s.setting+1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') --Budget Data for Next Year + and data.timeclassid = 2 + ))) + --CID 2 + and db.DepartmentalBudgetID<>0 + and dim.ChargeCodeID<>0 + and db.obactiveplans=1 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetOverriddenCalculations +/************************************************************ +** Author: akowalski +** Create Date: 2015-01-18 +** Description: Displays all instances of the use of the override option +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ +create view [ob].[viewExceptionsDepartmentBudgetOverriddenCalculations] as +/************* Account overrides ********************/ +-- Projected +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is Overriding the Projection calculations for Account ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail +from [clientob].[FactAccountVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID +inner join [ob].[DimAccountPH] ph with (readuncommitted) on ph.AccountPHID=sf.AccountPHID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue='Override' +and fct1.TimeClassID=12 + +union all + +-- Budget +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is Overriding the Budget calculations for Account ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail +from [clientob].[FactAccountVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID +inner join [ob].[DimAccountPH] ph with (readuncommitted) on ph.AccountPHID=sf.AccountPHID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue='Override' +and fct1.TimeClassID=2 + +union all +/************* Job Code overrides ********************/ +-- Projected +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is Overriding the Projection calculations for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [fw].[DimJobCodePH] ph with (readuncommitted) on ph.JobCodePHID=sf.JobCodePHID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue like '%Override%' +and fct1.UnitTypeID=141 +and sf.JobCodePHID in ('2', --Staffing - Job Code (Fixed) +'52') --Staffing - Job Code (Variable) +and fct1.TimeClassID=12 + +union all + +-- Budget +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is Overriding the Budget calculations for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [fw].[DimJobCodePH] ph with (readuncommitted) on ph.JobCodePHID=sf.JobCodePHID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue like '%Override%' +and fct1.UnitTypeID=141 +and sf.JobCodePHID in ('2', --Staffing - Job Code (Fixed) +'52') --Staffing - Job Code (Variable) +and fct1.TimeClassID=2 + +union all + +-- Baseline Budget +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is Overriding the Budget calculations for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [fw].[DimJobCodePH] ph with (readuncommitted) on ph.JobCodePHID=sf.JobCodePHID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue like '%Override%' +and fct1.UnitTypeID=141 +and sf.JobCodePHID in ('2', --Staffing - Job Code (Fixed) +'52') --Staffing - Job Code (Variable) +and fct1.TimeClassID=18 + +union all + +-- Projected +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is Overriding the Projection calculations for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [data].[ScoreFillin_PayCodeGroup] sf2 with (readuncommitted) on fct1.PayCodeGroupID=sf2.PayCodeGroupID and sf2.ModelGUID=db.MemberGUID +inner join [fw].[DimPayCodeGroupPH] ph with (readuncommitted) on sf2.PayCodeGroupPHID=ph.PayCodeGroupPHID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue='Override' +and fct1.UnitTypeID=141 +and sf2.PayCodeGroupID<>0 +and fct1.TimeClassID=12 + +union all + +-- Budget +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is Overriding the Budget calculations for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [data].[ScoreFillin_PayCodeGroup] sf2 with (readuncommitted) on fct1.PayCodeGroupID=sf2.PayCodeGroupID and sf2.ModelGUID=db.MemberGUID +inner join [fw].[DimPayCodeGroupPH] ph with (readuncommitted) on sf2.PayCodeGroupPHID=ph.PayCodeGroupPHID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue='Override' +and fct1.UnitTypeID=141 +and sf2.PayCodeGroupID<>0 +and fct1.TimeClassID=2 + +union all +/************* Employee overrides ********************/ +-- Projected +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is Overriding the Projection calculations for Employee ' + sf.FillinMemberName + ' in section Employee Wage Rate' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Employee] sf with (readuncommitted) on fct1.EmployeeID=sf.EmployeeID and sf.ModelGUID=db.MemberGUID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue='Override' +and fct1.UnitTypeID=141 +and fct1.EmployeeID<>0 +and fct1.TimeClassID=12 + +union all + +-- Budget +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is Overriding the Projection calculations for Employee ' + sf.FillinMemberName + ' in section Employee Wage Rate' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Employee] sf with (readuncommitted) on fct1.EmployeeID=sf.EmployeeID and sf.ModelGUID=db.MemberGUID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue='Override' +and fct1.UnitTypeID=141 +and fct1.EmployeeID<>0 +and fct1.TimeClassID=2 + +union all + +/************* Charge Code overrides ********************/ + +-- Projected +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is Overriding the Projection calculations for Charge Code ' + sf.FillinMemberName + ' in section ' + pc.Name as Detail +from [clientob].[FactCDMVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_ChargeCode] sf with (readuncommitted) on fct1.ChargeCodeID=sf.ChargeCodeID and sf.ModelGUID=db.MemberGUID +inner join [fw].[DimPatientClass] pc with (readuncommitted) on pc.PatientClassID=fct1.PatientClassID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.ChargeCodeID<>0 +and fct1.TextValue='Override' +and fct1.UnitTypeID=141 +and fct1.TimeClassID=12 + +union all + +-- Budget +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is Overriding the Budget calculations for Charge Code ' + sf.FillinMemberName + ' in section ' + pc.Name as Detail +from [clientob].[FactCDMVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_ChargeCode] sf with (readuncommitted) on fct1.ChargeCodeID=sf.ChargeCodeID and sf.ModelGUID=db.MemberGUID +inner join [fw].[DimPatientClass] pc with (readuncommitted) on pc.PatientClassID=fct1.PatientClassID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.ChargeCodeID<>0 +and fct1.TextValue='Override' +and fct1.UnitTypeID=141 +and fct1.TimeClassID=2 + +union all +/************* Provider overrides ********************/ + +-- Projected +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is Overriding the Projection calculations for Provider ' + sf.FillinMemberName + ' for forecast detail ' + fd.Name as Detail +from [clientob].[FactProviderVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Provider] sf with (readuncommitted) on fct1.ProviderID=sf.ProviderID and sf.ModelGUID=db.MemberGUID +inner join [ob].[DimOBForecastDetail] fd with (readuncommitted) on fct1.OBForecastDetailID=fd.OBForecastDetailID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.ProviderID<>0 +and fct1.TextValue='Override' +and fct1.UnitTypeID=141 +and fct1.TimeClassID=12 + +union all + +-- Budget +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is Overriding the Budget calculations for Provider ' + sf.FillinMemberName + ' for forecast detail ' + fd.Name as Detail +from [clientob].[FactProviderVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Provider] sf with (readuncommitted) on fct1.ProviderID=sf.ProviderID and sf.ModelGUID=db.MemberGUID +inner join [ob].[DimOBForecastDetail] fd with (readuncommitted) on fct1.OBForecastDetailID=fd.OBForecastDetailID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.ProviderID<>0 +and fct1.TextValue='Override' +and fct1.UnitTypeID=141 +and fct1.TimeClassID=2 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetOverrideProjectionOrSpread +/************************************************************ +** Author: akowalski +** Create Date: 2015-01-18 +** Description: Displays all instances of overriding the default projection or spread methods +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ +create view [ob].[viewExceptionsDepartmentBudgetOverrideProjectionOrSpread] as +/************* Account overrides ********************/ +-- Projected +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is overriding the default projection method for Account ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail +from [clientob].[FactAccountVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID +inner join [ob].[DimAccountPH] ph with (readuncommitted) on ph.AccountPHID=sf.AccountPHID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue<>'Default' +and fct1.AssumptionID=107 --Projection Method +and fct1.TimeClassID=12 + +union all + +-- Budget +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is overriding the default spread method for Account ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail +from [clientob].[FactAccountVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID +inner join [ob].[DimAccountPH] ph with (readuncommitted) on ph.AccountPHID=sf.AccountPHID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue<>'Default' +and fct1.AssumptionID=116 --Spread Method +and fct1.TimeClassID=2 + +union all +-- Contract Labor Dollars +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is overriding the default projection method for Account ' + sf.FillinMemberName + ' in section Contract Labor Dollars' as Detail +from [clientob].[FactAccountVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on fct1.AccountID=sf.AccountID and sf.ModelGUID=db.MemberGUID +inner join [ob].[DimAccountPH] ph with (readuncommitted) on ph.AccountPHID=sf.AccountPHID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue<>'Default' +and fct1.AssumptionID=625 --Dollars Method +and sf.AccountPHID=6 --Staffing - Contract Labor +and fct1.TimeClassID=12 + + +union all +/************* Job Code overrides ********************/ +-- Fixed projection +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is overriding the default projection method for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [fw].[DimJobCodePH] ph with (readuncommitted) on ph.JobCodePHID=sf.JobCodePHID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue<>'Default' +and fct1.EmployeeID=0 +and fct1.PayCodeGroupID=0 +and fct1.JobCodeID<>0 +and fct1.AssumptionID=116 --Spread Method (template is mapped wrong) +and sf.JobCodePHID in ('2', --Staffing - Job Code (Fixed) +'52') --Staffing - Job Code (Variable) +and fct1.TimeClassID=12 + +union all + +-- variable projection +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is overriding the default projection method for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [fw].[DimJobCodePH] ph with (readuncommitted) on ph.JobCodePHID=sf.JobCodePHID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue<>'Default' +and fct1.EmployeeID=0 +and fct1.PayCodeGroupID=0 +and fct1.JobCodeID<>0 +and fct1.AssumptionID=81 --Non-Productive FTE Adjustment (template is mapped wrong) +and sf.JobCodePHID in ('2', --Staffing - Job Code (Fixed) +'52') --Staffing - Job Code (Variable) +and fct1.TimeClassID=12 + +union all + +-- hr/uos projection +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is overriding the default projection method for Hrs per UOS Target' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [fw].[DimAssumption] ass with (readuncommitted) on ass.AssumptionID=fct1.AssumptionID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue<>'Default' +and fct1.EmployeeID=0 +and fct1.PayCodeGroupID=0 +and ass.Name='Productive Hrs per UOS Projection Method' +and fct1.TimeClassID=12 + +union all + +-- hr/uos spread +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is overriding the default budget method for Hrs per UOS Target' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [fw].[DimAssumption] ass with (readuncommitted) on ass.AssumptionID=fct1.AssumptionID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue<>'Default' +and fct1.EmployeeID=0 +and fct1.PayCodeGroupID=0 +and ass.Name='Productive Hrs per UOS Projection Method' +and fct1.TimeClassID=2 + +union all + +-- skill mix projection +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is overriding the default projection method for Skill Mix' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [fw].[DimAssumption] ass with (readuncommitted) on ass.AssumptionID=fct1.AssumptionID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue<>'Default' +and fct1.EmployeeID=0 +and fct1.PayCodeGroupID=0 +and ass.Name='Skill Mix Projection Method' +and fct1.TimeClassID=12 + +union all + +-- skill mix spread +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is overriding the default budget method for Skill Mix' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [fw].[DimAssumption] ass with (readuncommitted) on ass.AssumptionID=fct1.AssumptionID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue<>'Default' +and fct1.EmployeeID=0 +and fct1.PayCodeGroupID=0 +and ass.Name='Skill Mix Projection Method' +and fct1.TimeClassID=2 + + +union all + +-- Projected hrs distribution +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is overriding the Hours Distribution calculations for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [data].[ScoreFillin_PayCodeGroup] sf2 with (readuncommitted) on fct1.PayCodeGroupID=sf2.PayCodeGroupID and sf2.ModelGUID=db.MemberGUID +inner join [fw].[DimPayCodeGroupPH] ph with (readuncommitted) on sf2.PayCodeGroupPHID=ph.PayCodeGroupPHID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue<>'Default' +and fct1.AssumptionID=627 --Hours Method +and sf2.PayCodeGroupID<>0 +and fct1.TimeClassID=1 + +union all + +-- Projected wage rate +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is overriding the Wage Rate calculations for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [data].[ScoreFillin_PayCodeGroup] sf2 with (readuncommitted) on fct1.PayCodeGroupID=sf2.PayCodeGroupID and sf2.ModelGUID=db.MemberGUID +inner join [fw].[DimPayCodeGroupPH] ph with (readuncommitted) on sf2.PayCodeGroupPHID=ph.PayCodeGroupPHID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue<>'Default' +and fct1.AssumptionID=625 --Dollars Method +and sf2.PayCodeGroupID<>0 +and fct1.TimeClassID=1 + +union all + +-- Projected dollars only +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is overriding the default projection method for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [fw].[DimPayCodeGroup] ph with (readuncommitted) on fct1.PayCodeGroupid=ph.PayCodeGroupID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue<>'Default' +and fct1.AssumptionID=107 --Projection Method +and fct1.PayCodeGroupID<>0 +and fct1.TimeClassID=12 + +union all + +-- Budget dollars only +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is overriding the default spread method for Job Code ' + sf.FillinMemberName + ' in section ' + ph.Name as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [fw].[DimPayCodeGroup] ph with (readuncommitted) on fct1.PayCodeGroupid=ph.PayCodeGroupID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue<>'Default' +and fct1.AssumptionID=116 --Spread Method +and fct1.PayCodeGroupID<>0 +and fct1.TimeClassID=2 + +union all +/************* Employee overrides ********************/ +-- Projected +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is overriding the default projection method for Employee ' + sf.FillinMemberName + ' in section Employee Wage Rate' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Employee] sf with (readuncommitted) on fct1.EmployeeID=sf.EmployeeID and sf.ModelGUID=db.MemberGUID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.TextValue<>'Default' +and fct1.AssumptionID=116 --Spread Method (this is wrong in the template) +and fct1.JobCodeID=0 +and fct1.PayCodeGroupID=0 +and fct1.EmployeeID<>0 +and fct1.TimeClassID=12 + + +union all + +/************* Charge Code overrides ********************/ + +-- Projected volume +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is Overriding the volume projection method for Charge Code ' + sf.FillinMemberName + ' in section ' + pc.Name as Detail +from [clientob].[FactCDMVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_ChargeCode] sf with (readuncommitted) on fct1.ChargeCodeID=sf.ChargeCodeID and sf.ModelGUID=db.MemberGUID +inner join [fw].[DimPatientClass] pc with (readuncommitted) on pc.PatientClassID=fct1.PatientClassID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.ChargeCodeID<>0 +and fct1.TextValue<>'Default' +and fct1.AssumptionID=634 --Rate Projection Method (this is wrong in the template) +and fct1.TimeClassID=12 + +union all + +-- Projected rate +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is Overriding the rate projection method for Charge Code ' + sf.FillinMemberName + ' in section ' + pc.Name as Detail +from [clientob].[FactCDMVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_ChargeCode] sf with (readuncommitted) on fct1.ChargeCodeID=sf.ChargeCodeID and sf.ModelGUID=db.MemberGUID +inner join [fw].[DimPatientClass] pc with (readuncommitted) on pc.PatientClassID=fct1.PatientClassID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.ChargeCodeID<>0 +and fct1.TextValue<>'Default' +and fct1.AssumptionID=632 --Volume Projection Method (this is wrong in the template) +and fct1.TimeClassID=12 + +union all + +-- Budget +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is Overriding the volume spread method for Charge Code ' + sf.FillinMemberName + ' in section ' + pc.Name as Detail +from [clientob].[FactCDMVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_ChargeCode] sf with (readuncommitted) on fct1.ChargeCodeID=sf.ChargeCodeID and sf.ModelGUID=db.MemberGUID +inner join [fw].[DimPatientClass] pc with (readuncommitted) on pc.PatientClassID=fct1.PatientClassID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.ChargeCodeID<>0 +and fct1.TextValue<>'Default' +and fct1.AssumptionID=116 --Spread Method +and fct1.TimeClassID=2 + +union all +/************* Provider overrides ********************/ + +-- Projected +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is Overriding the default projection method for Provider ' + sf.FillinMemberName + ' for forecast detail ' + fd.Name as Detail +from [clientob].[FactProviderVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Provider] sf with (readuncommitted) on fct1.ProviderID=sf.ProviderID and sf.ModelGUID=db.MemberGUID +inner join [ob].[DimOBForecastDetail] fd with (readuncommitted) on fct1.OBForecastDetailID=fd.OBForecastDetailID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.ProviderID<>0 +and fct1.TextValue_Formula='x' +and fct1.AssumptionID=107 --Projection Method +and fct1.TimeClassID=12 + +union all + +-- Budget vol/rev +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is Overriding the default spread method for Provider ' + sf.FillinMemberName + ' for forecast detail ' + fd.Name as Detail +from [clientob].[FactProviderVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Provider] sf with (readuncommitted) on fct1.ProviderID=sf.ProviderID and sf.ModelGUID=db.MemberGUID +inner join [ob].[DimOBForecastDetail] fd with (readuncommitted) on fct1.OBForecastDetailID=fd.OBForecastDetailID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.ProviderID<>0 +and fct1.TextValue_Formula='x' +and fct1.AssumptionID=116 --Spread Method +and fct1.TimeClassID=2 + +union all + +-- Budget comp +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Is Overriding the default spread method for Provider ' + sf.FillinMemberName + ' for forecast detail ' + fd.Name as Detail +from [clientob].[FactProviderVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Provider] sf with (readuncommitted) on fct1.ProviderID=sf.ProviderID and sf.ModelGUID=db.MemberGUID +inner join [ob].[DimOBForecastDetail] fd with (readuncommitted) on fct1.OBForecastDetailID=fd.OBForecastDetailID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and fct1.ProviderID<>0 +and fct1.TextValue_Formula='x' +and fct1.AssumptionID=107 --Projection Method +and fct1.TimeClassID=2 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetPlansNotInWorkflow +/************************************************************ +** Author: jgerber +** Create Date: 2014-10-07 +** Description: Finds all departmental budgets without workflows +** Last Modified: 2014-11-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2014-10-07 JG Renaming and adding to the exception summary report +** 2 2014-11-18 cbecker D-02416 Filtering out not specified departmental budget +** +*************************************************************/ +CREATE view [ob].[viewExceptionsDepartmentBudgetPlansNotInWorkflow] +as + select + ob.DepartmentalBudgetID, + ob.Name as Model, + 'Has a departmental budget but does not have an associated workflow.' as Detail + from + ob.viewDimDepartmentalBudget OB + where + not exists( + select + 1 + from + ob.viewDimDepartmentalBudget P + inner join WFToken T on T.EntityGUID = P.MemberGUID + inner join WFWorkflowMap WF on WF.WorkflowMapGUID = T.WorkflowMapGUID + where + WF.Name like 'OB%' + and P.MemberGUID = OB.MemberGUID + ) + and OB.DepartmentalBudgetID<>0 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetPotentiallyInvalidGrossChargesSetups +/************************************************************ +** Author: akowalski +** Create Date: 2014-08-27 +** Description: Find mismatches between how the gross charge accounts are setup and what information is available in the model but may produce some false positives +** Last Modified: 2016-11-30 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-11-30 srk D-04844 Updated first two unions to flag exceptions that don't have a primary revenue driver in the primary stat config screen +** +*************************************************************/ + +CREATE view [ob].[viewExceptionsDepartmentBudgetPotentiallyInvalidGrossChargesSetups] as + +select + Distinct + dB.DepartmentalBudgetID, + dB.Name as Model, + 'Has ' + a.PatientClass + ' Gross Charges and is set to drive charges by '+ ac.Textvalue+ ' but has no ' + a.PatientClass + ' statistics in the model' as Detail +from [clientob].[FactAccountVar] ac with (readuncommitted) + inner join [fw].[DimAssumption] ASS with (readuncommitted) on ASS.AssumptionID=AC.AssumptionID + inner join [ob].[DimDepartmentalBudget] DB with (readuncommitted) on ac.DepartmentalBudgetID=db.DepartmentalBudgetID + inner join [fw].[DimAccount] a with (readuncommitted) on ac.AccountID=a.AccountID +where 1=1 + and TextValue like '%UOS%' + and ass.Name='Volume Driver' + and ac.TimeClassID = 12 + and ac.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year') + and not exists + ( + select top 1 1 from [data].[ScoreFillin_Account] SF with (readuncommitted) + inner join [ob].[DimAccountPH] ph with (readuncommitted) on ph.MemberGUID=sf.PlaceholderSectionMemberGUID + and (ph.Name like 'Statistics%' or ph.Name like 'Global Stat%') + inner join [fw].[DimAccount] a2 on SF.AccountID=a2.AccountID + INNER JOIN [ob].[viewFactDepartmentPrimaryStatisticConfiguration] PSC with (readuncommitted) on PSC.DepartmentalBudgetID = DB.DepartmentalBudgetID + AND PSC.AccountID = SF.AccountID + where 1=1 + and db.MemberGUID=SF.ModelGUID + and SF.AccountID<>0 + and a.PatientClassID=a2.PatientClassID + and PSC.Revenue = 1 + ) + and db.DepartmentalBudgetID<>0 + +Union all + +select + Distinct + dB.DepartmentalBudgetID, + dB.Name as Model, + 'Has ' + a.PatientClass + ' Gross Charges and is set to drive charges by '+ fct2.Textvalue+ ' but has no ' + a.PatientClass + ' statistics in the model' as Detail +from [data].[ScoreFillin_Account] sf1 with (readuncommitted) + inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on sf1.ModelGUID=DB.MemberGUID + inner join [ob].[DimAccountPH] ph1 with (readuncommitted) on sf1.PlaceholderSectionMemberGUID=ph1.MemberGUID + inner join [clientob].[FactAccountVar] fct1 with (readuncommitted) on sf1.AccountID=fct1.AccountID and fct1.DepartmentalBudgetID=db.DepartmentalBudgetID + inner join [fw].[DimAccount] a with (readuncommitted) on sf1.AccountID=a.AccountID + inner join [clientob].[FactAccountRollupVar] fct2 with (readuncommitted) on a.PatientClassID=fct2.PatientClassID and DB.DepartmentalBudgetID=fct2.DepartmentalBudgetID + and fct1.AssumptionID=fct2.AssumptionID + inner join [ob].[DimFinancialReporting] fr with (readuncommitted) on fct2.FinancialReportingID=fr.FinancialReportingID and fr.MemberGUID='e02a8750-bc0f-47ac-922b-60e4ffd3c1e5' +where 1=1 + and ph1.Name like 'Gross Charge%' + and fct1.AssumptionID=184 --Volume Driver + and fct1.TextValue='Global Default' + and fct2.TextValue like '%UOS%' + and fct1.TimeClassID = 12 + and fct1.FiscalYearID = (SELECT DBS.Setting from [dbo].[DBSetting] DBS where DBS.Name = 'OB_Current_Year') + and not exists + ( + select top 1 1 from [data].[ScoreFillin_Account] SF with (readuncommitted) + inner join [ob].[DimAccountPH] ph with (readuncommitted) on ph.MemberGUID=sf.PlaceholderSectionMemberGUID + and (ph.Name like 'Statistics%' or ph.Name like 'Global Stat%') + inner join [fw].[DimAccount] a2 on SF.AccountID=a2.AccountID + INNER JOIN [ob].[viewFactDepartmentPrimaryStatisticConfiguration] PSC with (readuncommitted) on PSC.DepartmentalBudgetID = DB.DepartmentalBudgetID + where 1=1 + and db.MemberGUID=SF.ModelGUID + and SF.AccountID<>0 + and a.PatientClassID=a2.PatientClassID + and PSC.Revenue = 1 + ) + and db.DepartmentalBudgetID<>0 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetProjectedBudgetVarianceTooHigh +/************************************************************ +** Author: akowalski +** Create Date: 2015-01-18 +** Description: Displays financial statement lines who have a greater than 50% change from projection to budget time +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ +create view [ob].[viewExceptionsDepartmentBudgetProjectedBudgetVarianceTooHigh] as +select + DB.DepartmentalBudgetID, + dB.Name as Model, + 'Has Projected to Budgeted Variance of '+ cast(100*(Sum(Budgeted)- SUM(Projected))/SUM(Projected) as nvarchar)+'% in '+ DIM.Name as Detail + from (select + FR.DepartmentalBudgetID, + FR.FinancialReportingID, + case when TimeClassID=2 and FiscalYearID= (select s.Setting +1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') then Total else 0 END As Budgeted, + case when TimeClassID=12 and FiscalYearID= (select s.Setting from [dbo].[DBSetting] s where Name = 'OB_Current_Year') then Total else 0 END As Projected + from clientob.FactReportingMonthly FR with (readuncommitted) + where TimeClassID in (2,12)) as Agg +inner join ob.DimDepartmentalBudget DB with (readuncommitted) on AGG.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join ob.DimFinancialReporting DIM with (readuncommitted) on DIM.financialreportingID=AGG.FinancialReportingID +where dim.Statement='IS' +group by DB.DepartmentalBudgetID, +dB.Name , +dim.Name +having SUM(projected)<>0 +and case when SUM(projected)<>0 then abs((Sum(Budgeted)- SUM(Projected))/SUM(Projected)) end > 0.5 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetProjectedEqualYTD +/************************************************************ +** Author: akowalski +** Create Date: 2014-05-13 +** Description: Compares Projected total and YTD to determine of the anything is being projected in the non-closed months, indicates potential errors +** Last Modified: 2014-05-13 +** GM Release: 2014.3 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + +CREATE view [ob].[viewExceptionsDepartmentBudgetProjectedEqualYTD] as + + +-- Account Data +select +Distinct +DB.DepartmentalBudgetID, +DB.Name as Model, +'Has projected = YTD for Account: ' + Dim.Name + ' in section ' + PH.Name as Detail +from clientob.FactAccount fct with (readuncommitted) +inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID=fct.DepartmentalBudgetID +inner join fw.DimAccount DIM with (readuncommitted) on fct.AccountID = DIM.AccountID +inner join data.ScoreFillin_Account SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + and dim.MemberGUID=sf.FillinMemberGUID +inner join ob.DimAccountPH PH with (readuncommitted) on SF.PlaceholderSectionMemberGUID= PH.MemberGUID +where fct.datatypeid=3 +and fct.YTD=fct.Total +and fct.TimeClassID=12 +and fct.Total<>0 +and fct.MonthsLoaded<>12 + +union all + + +-- Staffing Data +select +Distinct +DB.DepartmentalBudgetID, +DB.Name as Model, +'Has projected dollars = YTD for Pay Code Group "' + pcg.Name + '" of Job Code ' + dim.Name as Detail +from clientob.FactStaffingPC fct with (readuncommitted) +inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID=fct.DepartmentalBudgetID +inner join fw.DimJobCode DIM with (readuncommitted) on fct.JobCodeID = DIM.JobCodeID +inner join fw.DimPayCodeGroup pcg with (readuncommitted) on fct.PayCodeGroupID=pcg.PayCodeGroupID +where fct.datatypeid=3 +and fct.YTD=fct.Total +and fct.TimeClassID=12 +and fct.Total<>0 +and fct.UnitTypeID=34 +and fct.MonthsLoaded<>12 + +union all + +-- Provider Data +select +Distinct +DB.DepartmentalBudgetID, +DB.Name as Model, +'Has projected = YTD for forecast detail "' + fd.Name + '" of Provider ' + dim.Name as Detail +from clientob.FactProvider fct with (readuncommitted) +inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID=fct.DepartmentalBudgetID +inner join fw.DimProvider DIM with (readuncommitted) on fct.ProviderID = DIM.ProviderID +inner join ob.DimOBForecastDetail fd with (readuncommitted) on fct.OBForecastDetailID=fd.OBForecastDetailID +where fct.datatypeid=3 +and fct.YTD=fct.Total +and fct.TimeClassID=12 +and fct.Total<>0 +and fct.MonthsLoaded<>12 + +union all + + +-- Charge Code Data +select +Distinct +DB.DepartmentalBudgetID, +DB.Name as Model, +'Has projected dollars = YTD for charge code ' + dim.Name as Detail +from clientob.FactCDM fct with (readuncommitted) +inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID=fct.DepartmentalBudgetID +inner join fw.DimChargeCode DIM with (readuncommitted) on fct.ChargeCodeID = DIM.ChargeCodeID +where fct.datatypeid=3 +and fct.YTD=fct.Total +and fct.TimeClassID=12 +and fct.Total<>0 +and fct.UnitTypeID=34 +and fct.MonthsLoaded<>12 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetProviderCompToAccount +/*********************************************************************************************************************************************** +** Author: dmoldawer +** Create Date: 2014-03-21 +** Description: If forecast detail category starts with provider compensation, needs to have account fillin to Staffing GL Accounts section +** Last Modified: 2017-03-22 +** GM Release: 2014.4 +************************************************************************************************************************************************* +** Change History +************************************************************************************************************************************************* +** CID Date Author WI Description +** 1 2014-09-04 akk D-02183 Removing false positives for unmapped items and budgets with no providers +** 2 2017-01-11 srk D-05145 Updated second part of the script (after the first union) to check for mid-levels only + because it is looking for secondary accounts on the forecast dimension. Also included a check + for Staffing - Hours Accounts. +** 3 2017-03-22 srk D-05711 Removed 'Provider - Benefits' from this exception view because it only needs to look for comp exceptions +************************************************************************************************************************************************/ + +CREATE view [ob].[viewExceptionsDepartmentBudgetProviderCompToAccount] as +select + distinct + DB.DepartmentalBudgetID, + DB.Name as Model, + 'Account ' + A.Name + ' is configured to receive Physician data from provider comp type ' + OBFD.Name + ' but is not filled in' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + cross join ob.DimOBForecastDetail OBFD with (readuncommitted) + inner join fw.DimAccount A with (readuncommitted) on OBFD.AccountID = A.AccountID + inner join ob.DimAccountPH PH with (readuncommitted) on PH.Name = 'Staffing - GL Accounts' -- Physician Account + inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid +--CID 2 BEGIN-- + inner join [fw].[DimProvider] dp on sfp.FillinMemberGUID = dp.MemberGUID and dp.Type = 'Physician' +--CID 2 END-- +where 1=1 + and OBFD.Category in ('Provider Compensation - Production Earning Tiers','Provider Compensation - Other Pay','Provider Compensation - Guarantee') -- Only Dollars + and not exists(select 1 from data.ScoreFillin_Account FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.AccountID = A.AccountID and FI.AccountPHID = PH.AccountPHID) + and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1 + and A.AccountID<>0 + +UNION ALL + +select + distinct + DB.DepartmentalBudgetID, + DB.Name as Model, + 'Account ' + A.Name + ' is configured to receive Mid-Level Physician data from provider comp type ' + OBFD.Name + ' but is not filled in' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + cross join ob.DimOBForecastDetail OBFD with (readuncommitted) + inner join fw.DimAccount A with (readuncommitted) on OBFD.SecondaryAccountID = A.AccountID -- Mid-Level Account + inner join ob.DimAccountPH PH with (readuncommitted) on PH.Name = 'Staffing - GL Accounts' + inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid +--CID 2 BEGIN-- + inner join [fw].[DimProvider] dp on sfp.FillinMemberGUID = dp.MemberGUID and dp.Type <> 'Physician' +--CID 2 END-- +where 1=1 + and OBFD.Category in ('Provider Compensation - Production Earning Tiers','Provider Compensation - Other Pay','Provider Compensation - Guarantee') -- Only Dollars + and not exists(select 1 from data.ScoreFillin_Account FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.AccountID = A.AccountID and FI.AccountPHID = PH.AccountPHID) + and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1 + and A.AccountID<>0 + + +--CID 2 BEGIN -- INCLUDING HOURS ACCOUNTS-- +UNION ALL + +select + distinct + DB.DepartmentalBudgetID, + DB.Name as Model, + 'Account ' + A.Name + ' is configured to receive Physician hours data from provider comp type ' + OBFD.Name + ' but is not filled in' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + cross join ob.DimOBForecastDetail OBFD with (readuncommitted) + inner join fw.DimAccount A with (readuncommitted) on OBFD.AccountID = A.AccountID + inner join ob.DimAccountPH PH with (readuncommitted) on PH.Name = 'Staffing - Hours Accounts' -- Physician Account + inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid +--CID 2 BEGIN-- + inner join [fw].[DimProvider] dp on sfp.FillinMemberGUID = dp.MemberGUID and dp.Type = 'Physician' +--CID 2 END-- +where 1=1 + and OBFD.Category in ('Provider Compensation - Hours') -- Only Hours + and not exists(select 1 from data.ScoreFillin_Account FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.AccountID = A.AccountID and FI.AccountPHID = PH.AccountPHID) + and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1 + and A.AccountID<>0 + +UNION ALL + +select + distinct + DB.DepartmentalBudgetID, + DB.Name as Model, + 'Account ' + A.Name + ' is configured to receive Mid-Level Physician hours data from provider comp type ' + OBFD.Name + ' but is not filled in' as Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + cross join ob.DimOBForecastDetail OBFD with (readuncommitted) + inner join fw.DimAccount A with (readuncommitted) on OBFD.SecondaryAccountID = A.AccountID -- Mid-Level Account + inner join ob.DimAccountPH PH with (readuncommitted) on PH.Name = 'Staffing - Hours Accounts' + inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid +--CID 2 BEGIN-- + inner join [fw].[DimProvider] dp on sfp.FillinMemberGUID = dp.MemberGUID and dp.Type <> 'Physician' +--CID 2 END-- +where 1=1 + and OBFD.Category in ('Provider Compensation - Hours') -- Only Hours + and not exists(select 1 from data.ScoreFillin_Account FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.AccountID = A.AccountID and FI.AccountPHID = PH.AccountPHID) + and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1 + and A.AccountID<>0 + +--CID 2 END -- INCLUDING HOURS ACCOUNTS-- +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetProviderDeductionsMissingRevenue +/************************************************************ +** Author: bparrott +** Create Date: 2015-01-18 +** Description: Budgets that have providers with data in a driven volume but no data in the driver volume. This causes the driven volume to not project or budget. +** Last Modified: +** GM Release: 2015.2 +*************************************************************/ +Create view [ob].[viewExceptionsDepartmentBudgetProviderDeductionsMissingRevenue] + as + + select distinct + db.departmentalbudgetid, + db.name As Model, + 'Provider' + prov.Name + ' has deductions but no revenue' As Detail + from [ob].[DimDepartmentalBudget] DB + inner join [data].[ScoreFillin_OBForecastDetail] fd on fd.OBForecastDetailID=fd.OBForecastDetailID and OBForecastDetailID=5 + inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid and sfp.ProviderID<>0 + inner join [fw].[DimProvider] prov on prov.ProviderID = sfp.providerid + inner join [ob].[DimOBForecastDetail] ofd on ofd.OBForecastDetailID=fd.OBForecastDetailID and DriverID in (47,50) + inner join [clientob].[FactProvider] fp on fp.ProviderID=prov.ProviderID + where fp.Total <>0 and fp.TimeClassID in (1,2) and DataTypeID=4 + and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetProviderDrivenVolumesMissingDriver +/************************************************************ +** Author: bparrott +** Create Date: 2015-01-18 +** Description: Budgets that have providers with data in a driven volume but no data in the driver volume. This causes the driven volume to not project or budget. +** Last Modified: +** GM Release: 2015.2 +*************************************************************/ +Create view [ob].[viewExceptionsDepartmentBudgetProviderDrivenVolumesMissingDriver] + as + select distinct + db.departmentalbudgetid, + db.name As Model, + 'Provider' + prov.Name + ' has driven but no volume' As Detail + from [ob].[DimDepartmentalBudget] DB + inner join [data].[ScoreFillin_OBForecastDetail] fd on fd.OBForecastDetailID=fd.OBForecastDetailID and OBForecastDetailID=3 + inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid and sfp.ProviderID<>0 + inner join [fw].[DimProvider] prov on prov.ProviderID = sfp.providerid + inner join [ob].[DimOBForecastDetail] ofd on ofd.OBForecastDetailID=fd.OBForecastDetailID and DriverID <> 0 + inner join [clientob].[FactProvider] fp on fp.ProviderID=prov.ProviderID + where fp.Total <>0 and fp.TimeClassID in (1,2) and DataTypeID=4 + and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetProviderFTEGreaterThan1 +/************************************************************ +** Author: bparrott +** Create Date: 2015-01-18 +** Description: Providers whose total FTE across all departments is greater than 1. This usually indicates an oversubscription of a provider to one or more departments. +** Last Modified: +** GM Release: 2015.2 +************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2018-01-02 sdominsk D-06353 Added additional grouping on year/timeclass and use the working hours table to convert FTEs to hours, total them, then convert total back to FTEs. +*************************************************************/ +CREATE view [ob].[viewExceptionsDepartmentBudgetProviderFTEGreaterThan1] + as +select + Distinct + DB.DepartmentalBudgetID, + DB.Name as Model, + 'Provider ' + prov.Name + ' has ' + Cast(TotalFTE as varchar(100)) + ' which is greater than 1 for all departments' As Detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + cross join ob.DimOBForecastDetail OBFD with (readuncommitted) + inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid + inner join ( select fte.FiscalYearID, + TimeClassID, + ProviderID, + SUM(fte.Month01*WorkH.Month01+fte.Month02*workH.Month02+fte.Month03*workH.Month03+fte.Month04*workH.Month04+fte.Month05*workH.Month05+fte.Month06*workH.Month06+fte.Month07*workH.Month07+fte.Month08*workH.Month08+fte.Month09*workH.Month09+fte.Month10*workH.Month10+fte.Month11*workH.Month11+fte.Month12*workH.Month12) + /SUM(WorkH.Month01+workH.Month02+workH.Month03+workH.Month04+workH.Month05+workH.Month06+workH.Month07+workH.Month08+workH.Month09+workH.Month10+workH.Month11+workH.Month12) + as TotalFTE + from [clientob].[FactProvider] fte + inner join ob.DimDepartmentalBudget as DBi with (readuncommitted) on dbi.DepartmentalBudgetID = fte.DepartmentalBudgetID + inner join fw.DimEntity as DEi with (readuncommitted) on DBi.EntityID = DEi.EntityID + inner join [client].[FactWorkingHoursPerMonth] WorkH on WorkH.FiscalYearID = fte.FiscalYearID and WorkH.WorkWeekID = DEi.WorkWeekID + where + OBForecastDetailID=1001 + group by + Providerid,fte.FiscalYearID,TimeClassID + ) rollup on sfp.ProviderID=rollup.ProviderID + inner join [fw].[DimProvider] prov on prov.ProviderID = sfp.ProviderID +where + DB.DepartmentalBudgetID != 0 and db.obactiveplans=1 + and TotalFTE > 1 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetProviderProductionEarningsMissingDriver +/************************************************************ +** Author: bparrott +** Create Date: 2015-01-18 +** Description: Budgets that have providers with data in a driven volume but no data in the driver volume. This causes the driven volume to not project or budget. +** Last Modified: +** GM Release: 2015.2 +*************************************************************/ +Create view [ob].[viewExceptionsDepartmentBudgetProviderProductionEarningsMissingDriver] + as + select distinct + db.departmentalbudgetid, + db.name As Model, + 'Provider' + prov.Name + ' has productive earnings tiers but no volumes' As Detail + from [ob].[DimDepartmentalBudget] DB + inner join [data].[ScoreFillin_OBForecastDetail] fd on fd.OBForecastDetailID=fd.OBForecastDetailID + inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid and sfp.ProviderID<>0 + inner join [fw].[DimProvider] prov on prov.ProviderID = sfp.providerid + inner join [clientob].[FactProvider] fp on fp.ProviderID=prov.ProviderID and fp.TimeClassID in (2,12) + where prov.OBTier1Threshold <> 0 and fp.Total =0 + and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1 + UNION + select distinct + db.departmentalbudgetid, + db.name As Model, + 'Provider' + prov.Name + ' has productive earnings tiers but no volumes' As Detail + from [ob].[DimDepartmentalBudget] DB + inner join [data].[ScoreFillin_OBForecastDetail] fd on fd.OBForecastDetailID=fd.OBForecastDetailID + inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid and sfp.ProviderID<>0 + inner join ob.DimobForecastDetail ob on ob.OBForecastDetailID=fd.OBForecastDetailID and OB.IsSalaryDriver=1 + inner join [fw].[DimProvider] prov on prov.ProviderID = sfp.providerid + inner join [clientob].[FactProvider] fp on fp.ProviderID=prov.ProviderID and fp.TimeClassID in (2,12) + where prov.OBTier1Threshold <> 0 and fp.Total =0 + and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetProviderRevenueMissingDriverVolume +/************************************************************ +** Author: bparrott +** Create Date: 2015-01-18 +** Description: Budgets that have providers with data in a driven volume but no data in the driver volume. This causes the driven volume to not project or budget. +** Last Modified: +** GM Release: 2015.2 +*************************************************************/ +Create view [ob].[viewExceptionsDepartmentBudgetProviderRevenueMissingDriverVolume] + as + select distinct + db.departmentalbudgetid, + db.name As Model, + 'Provider' + prov.Name + ' has revenue but no volumes' As Detail + from [ob].[DimDepartmentalBudget] DB + inner join [data].[ScoreFillin_OBForecastDetail] fd on fd.OBForecastDetailID=fd.OBForecastDetailID and OBForecastDetailID=4 + inner join [data].[ScoreFillin_Provider] sfp with (readuncommitted) on sfp.ProviderPHID<>0 and db.MemberGUID=sfp.modelguid and sfp.ProviderID<>0 + inner join [fw].[DimProvider] prov on prov.ProviderID = sfp.providerid + inner join [ob].[DimOBForecastDetail] ofd on ofd.OBForecastDetailID=fd.OBForecastDetailID and DriverID in (47,50) + inner join [clientob].[FactProvider] fp on fp.ProviderID=prov.ProviderID + where fp.Total <>0 and fp.TimeClassID in (1,2) and DataTypeID=4 + and DB.DepartmentalBudgetID != 0 and db.obactiveplans=1 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetRegularPCGNoHoursNoDollars +/************************************************************ +** Author: mschmitz +** Create Date: 2015-01-18 +** Description: Checks for budgets that have zero YTD 'Regular' hours/dollars but have non-zero values in other pay code groups which depend on the Regular type having non-zero values +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ +CREATE VIEW [ob].[viewExceptionsDepartmentBudgetRegularPCGNoHoursNoDollars] AS + +SELECT DISTINCT + B.DepartmentalBudgetID, + B.Name as 'Model', + 'Has non-regular YTD hours/dollars for job code '+JC.name+' but no regular YTD hours/dollars for this job code. The model will be unable to project the non-regular dollars.' as 'Detail' +FROM ( --Non-zero OTHER YTD dollars + SELECT top (2147483647) + OTH.DepartmentalBudgetID, + OTH.JobCodeID, + OTH.PayCodeGroupID, + OTH.UnitTypeID + FROM [clientob].[FactStaffingPC] OTH with (readuncommitted) + WHERE + OTH.UnitTypeID in ('34','51','146','147','148') + AND OTH.DataTypeID=4 + AND OTH.TimeClassID=1 + AND OTH.FiscalYearID IN (SELECT Setting from [dbo].[DBSetting] with (readuncommitted) WHERE Name like 'OB_Current_Year') + AND OTH.PayCodeGroupID NOT IN (SELECT PCGD.PayCodeGroupID FROM [fw].[DimPayCodeGroup] PCGD with (readuncommitted) WHERE PCGD.ProductiveClassID = 4) --Exclude Dollars Only + AND OTH.PayCodeGroupID NOT IN (--Exludes the first Productive pay code group member + SELECT DISTINCT SFOTH.PayCodeGroupID FROM [data].[ScoreFillin_PayCodeGroup] SFOTH with (readuncommitted) + WHERE + SFOTH.PlaceholderSectionMemberGUID = 'c0294680-5658-454f-90fd-7bfc686131aa' + AND SFOTH.PlaceholderIndex=0 + ) + AND OTH.YTD<>0 + GROUP BY + OTH.DepartmentalBudgetID, + OTH.JobCodeID, + OTH.PayCodeGroupID, + OTH.UnitTypeID + HAVING SUM(OTH.YTD)<>0 + ) OTHER +INNER JOIN ( --Zero REGULAR YTD dollars + SELECT top (2147483647) + REG.DepartmentalBudgetID, + REG.JobCodeID, + REG.UnitTypeID + FROM [clientob].[FactStaffingPC] REG with (readuncommitted) + WHERE + REG.UnitTypeID in ('34','51','146','147','148') + AND REG.DataTypeID=4 + AND REG.TimeClassID=1 + AND REG.FiscalYearID IN (SELECT Setting from [dbo].[DBSetting] with (readuncommitted) WHERE Name like 'OB_Current_Year') + AND REG.PayCodeGroupID IN (--Includes the first Productive pay code group member + SELECT DISTINCT SFREG.PayCodeGroupID FROM [data].[ScoreFillin_PayCodeGroup] SFREG with (readuncommitted) + WHERE + SFREG.PlaceholderSectionMemberGUID = 'c0294680-5658-454f-90fd-7bfc686131aa' + AND SFREG.PlaceholderIndex=0 + ) + GROUP BY + REG.DepartmentalBudgetID, + REG.JobCodeID, + REG.UnitTypeID + HAVING SUM(REG.YTD)=0 + ) REGULAR + ON OTHER.DepartmentalBudgetID=REGULAR.DepartmentalBudgetID + AND OTHER.JobCodeID=REGULAR.JobCodeID + AND OTHER.UnitTypeID=REGULAR.UnitTypeID +INNER JOIN [ob].[DimDepartmentalBudget] B with (readuncommitted) + ON REGULAR.DepartmentalBudgetID = B.DepartmentalBudgetID +INNER JOIN [fw].[DimJobCode] JC with (readuncommitted) + ON REGULAR.JobCodeID=JC.JobCodeID +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetStaffingAdjustmentsNoComments +/************************************************************ +** Author: akowalski +** Create Date: 2015-01-18 +** Description: Displays all job codes that have manager adjustments but no comments +** Last Modified: 2017-02-27 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-02-27 srk D-05574 Adding isdeleted filter and making fiscal year parameter dynamic +** +*************************************************************/ +CREATE view [ob].[viewExceptionsDepartmentBudgetStaffingAdjustmentsNoComments] as + +/********************************************************************************** +************** Fixed Job Code Adjustments *************************************** +**********************************************************************************/ +/******* Monthly FTE adjustments ******/ +-- Projected +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Fixed Job Code ' + sf.FillinMemberName + ' has a monthly FTE Projection adjustment but no comments' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.JobCodePHID=2 --Staffing - Job Code (Fixed) +and fct1.JobCodeID<>0 +and fct1.PayCodeGroupID=0 +and fct1.EmployeeID=0 +and fct1.Amount<>0 +and fct1.AssumptionID=620 -- Productive Adjustment +and fct2.AssumptionID=30 -- Comment +and fct2.Comment='' +and fct1.TimeClassID=12 +and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 + + +union all + +-- Budget +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Fixed Job Code ' + sf.FillinMemberName + ' has a monthly FTE Budget adjustment but no comments' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.JobCodePHID=2 --Staffing - Job Code (Fixed) +and fct1.JobCodeID<>0 +and fct1.PayCodeGroupID=0 +and fct1.EmployeeID=0 +and fct1.Amount<>0 +and fct1.AssumptionID=620 -- Productive Adjustment +and fct2.AssumptionID=30 -- Comment +and fct2.Comment='' +and fct1.TimeClassID=2 +and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 + + +union all + +/******* Annual FTE Adjustments ******/ +-- Projected +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Fixed Job Code ' + sf.FillinMemberName + ' has a yearly-level FTE Projection adjustment but no comments' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.JobCodePHID=2 --Staffing - Job Code (Fixed) +and fct1.JobCodeID<>0 +and fct1.PayCodeGroupID=0 +and fct1.EmployeeID=0 +and fct1.Amount<>0 +and fct1.AssumptionID=18 -- Adjustment +and fct2.AssumptionID=30 -- Comment +and fct2.Comment='' +and fct1.TimeClassID=12 +and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 + + +union all + +-- Budget +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Fixed Job Code ' + sf.FillinMemberName + ' has a yearly-level FTE Budget adjustment but no comments' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.JobCodePHID=2 --Staffing - Job Code (Fixed) +and fct1.JobCodeID<>0 +and fct1.PayCodeGroupID=0 +and fct1.EmployeeID=0 +and fct1.Amount<>0 +and fct1.AssumptionID=18 -- Adjustment +and fct2.AssumptionID=30 -- Comment +and fct2.Comment='' +and fct1.TimeClassID=2 +and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 + + + +union all + +/******* Non-productive % ******/ +-- Projected +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Fixed Job Code ' + sf.FillinMemberName + ' has a Non-Productive Percent Projection adjustment but no comments' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.JobCodePHID=2 --Staffing - Job Code (Fixed) +and fct1.JobCodeID<>0 +and fct1.PayCodeGroupID=0 +and fct1.EmployeeID=0 +and fct1.Amount<>0 +and fct1.AssumptionID=155 -- Non-Productive Mix +and fct2.AssumptionID=30 -- Comment +and fct2.Comment='' +and fct1.TimeClassID=12 +and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 + + +union all + +-- Projected +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Fixed Job Code ' + sf.FillinMemberName + ' has a Non-Productive Percent Budget adjustment but no comments' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.JobCodePHID=2 --Staffing - Job Code (Fixed) +and fct1.JobCodeID<>0 +and fct1.PayCodeGroupID=0 +and fct1.EmployeeID=0 +and fct1.Amount<>0 +and fct1.AssumptionID=155 -- Non-Productive Mix +and fct2.AssumptionID=30 -- Comment +and fct2.Comment='' +and fct1.TimeClassID=2 +and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 + +union all + +-- Baseline Budget +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Fixed Job Code ' + sf.FillinMemberName + ' has a Non-Productive Percent Baseline Budget adjustment but no comments' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.JobCodePHID=2 --Staffing - Job Code (Fixed) +and fct1.JobCodeID<>0 +and fct1.PayCodeGroupID=0 +and fct1.EmployeeID=0 +and fct1.Amount<>0 +and fct1.AssumptionID=155 -- Non-Productive Mix +and fct2.AssumptionID=30 -- Comment +and fct2.Comment='' +and fct1.TimeClassID=18 +and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 + +union all + +/********************************************************************************** +************** Employee Adjustments *************************************** +**********************************************************************************/ +/******* Monthly FTE adjustments ******/ +-- Projected +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Employee ' + sf.FillinMemberName + ' has a monthly FTE Projection adjustment but no comments' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Employee] sf with (readuncommitted) on fct1.EmployeeID=sf.EmployeeID and sf.ModelGUID=db.MemberGUID +inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.EmployeePHID=202 --Staffing - Employee (Fixed) +and fct1.JobCodeID=0 +and fct1.PayCodeGroupID=0 +and fct1.EmployeeID<>0 +and fct1.Amount<>0 +and fct1.AssumptionID=620 -- Productive Adjustment +and fct2.AssumptionID=30 -- Comment +and fct2.Comment='' +and fct1.TimeClassID=12 +and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 + +union all + +-- Budget +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Employee ' + sf.FillinMemberName + ' has a monthly FTE Budget adjustment but no comments' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Employee] sf with (readuncommitted) on fct1.EmployeeID=sf.EmployeeID and sf.ModelGUID=db.MemberGUID +inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.EmployeePHID=202 --Staffing - Employee (Fixed) +and fct1.JobCodeID=0 +and fct1.PayCodeGroupID=0 +and fct1.EmployeeID<>0 +and fct1.Amount<>0 +and fct1.AssumptionID=620 -- Productive Adjustment +and fct2.AssumptionID=30 -- Comment +and fct2.Comment='' +and fct1.TimeClassID=2 +and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 + + +union all + +/******* Annual FTE Adjustments ******/ +-- Projected +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Employee ' + sf.FillinMemberName + ' has a yearly-level FTE Projection adjustment but no comments' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Employee] sf with (readuncommitted) on fct1.EmployeeID=sf.EmployeeID and sf.ModelGUID=db.MemberGUID +inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.EmployeePHID=202 --Staffing - Employee (Fixed) +and fct1.JobCodeID=0 +and fct1.PayCodeGroupID=0 +and fct1.EmployeeID<>0 +and fct1.Amount<>0 +and fct1.AssumptionID=18 -- Adjustment +and fct2.AssumptionID=30 -- Comment +and fct2.Comment='' +and fct1.TimeClassID=12 +and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 + + +union all + +-- Budget +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Employee ' + sf.FillinMemberName + ' has a yearly-level FTE Budget adjustment but no comments' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_Employee] sf with (readuncommitted) on fct1.EmployeeID=sf.EmployeeID and sf.ModelGUID=db.MemberGUID +inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.EmployeePHID=202 --Staffing - Employee (Fixed) +and fct1.JobCodeID=0 +and fct1.PayCodeGroupID=0 +and fct1.EmployeeID<>0 +and fct1.Amount<>0 +and fct1.AssumptionID=18 -- Adjustment +and fct2.AssumptionID=30 -- Comment +and fct2.Comment='' +and fct1.TimeClassID=2 +and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 + +union all + +/********************************************************************************** +************** Variable Job Code Adjustments *************************************** +**********************************************************************************/ +/******* Monthly FTE adjustments ******/ +-- Projected +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Variable Job Code ' + sf.FillinMemberName + ' has a monthly FTE Projection adjustment but no comments' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.JobCodePHID=52 --Staffing - Job Code (Variable) +and fct1.JobCodeID<>0 +and fct1.PayCodeGroupID=0 +and fct1.EmployeeID=0 +and fct1.Amount<>0 +and fct1.AssumptionID=620 -- Productive Adjustment +and fct2.AssumptionID=30 -- Comment +and fct2.Comment='' +and fct1.TimeClassID=12 +and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 + + +union all + +-- Budget +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Variable Job Code ' + sf.FillinMemberName + ' has a monthly FTE Budget adjustment but no comments' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.JobCodePHID=52 --Staffing - Job Code (Variable) +and fct1.JobCodeID<>0 +and fct1.PayCodeGroupID=0 +and fct1.EmployeeID=0 +and fct1.Amount<>0 +and fct1.AssumptionID=620 -- Productive Adjustment +and fct2.AssumptionID=30 -- Comment +and fct2.Comment='' +and fct1.TimeClassID=2 +and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 + + +union all + +/******* Non-productive % ******/ +-- Projected +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Variable Job Code ' + sf.FillinMemberName + ' has a Non-Productive Percent Projection adjustment but no comments' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.JobCodePHID=52 --Staffing - Job Code (Variable) +and fct1.JobCodeID<>0 +and fct1.PayCodeGroupID=0 +and fct1.EmployeeID=0 +and fct1.Amount<>0 +and fct1.AssumptionID=155 -- Non-Productive Mix +and fct2.AssumptionID=30 -- Comment +and fct2.Comment='' +and fct1.TimeClassID=12 +and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 + + +union all + +-- Projected +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Variable Job Code ' + sf.FillinMemberName + ' has a Non-Productive Percent Budget adjustment but no comments' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.JobCodePHID=52 --Staffing - Job Code (Variable) +and fct1.JobCodeID<>0 +and fct1.PayCodeGroupID=0 +and fct1.EmployeeID=0 +and fct1.Amount<>0 +and fct1.AssumptionID=155 -- Non-Productive Mix +and fct2.AssumptionID=30 -- Comment +and fct2.Comment='' +and fct1.TimeClassID=2 +and fct1.FiscalYearID = (SELECT dbs.Setting from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 + + +union all + +-- Baseline Budget +select + Distinct + db.DepartmentalBudgetID as DepartmentalBudgetID, + db.Name as Model, + 'Variable Job Code ' + sf.FillinMemberName + ' has a Non-Productive Percent Baseline Budget adjustment but no comments' as Detail +from [clientob].[FactStaffingPCVar] fct1 with (readuncommitted) +inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on fct1.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join [data].[ScoreFillin_JobCode] sf with (readuncommitted) on fct1.JobCodeID=sf.JobCodeID and sf.ModelGUID=db.MemberGUID +inner join [clientob].[FactStaffingPCVar] fct2 with (readuncommitted) on fct1.JobCodeID=fct2.JobCodeID and fct1.DepartmentalBudgetID=fct2.DepartmentalBudgetID and fct1.PayCodeGroupID=fct2.PayCodeGroupID and fct1.EmployeeID=fct2.EmployeeID +where +db.DepartmentalBudgetID<>0 and db.OBActivePlans=1 +and sf.JobCodePHID=52 --Staffing - Job Code (Variable) +and fct1.JobCodeID<>0 +and fct1.PayCodeGroupID=0 +and fct1.EmployeeID=0 +and fct1.Amount<>0 +and fct1.AssumptionID=155 -- Non-Productive Mix +and fct2.AssumptionID=30 -- Comment +and fct2.Comment='' +and fct1.TimeClassID=18 +and fct1.FiscalYearID = (SELECT dbs.Setting + 1 from [dbo].[DBSetting] dbs where dbs.Name = 'OB_Current_Year') +and fct1.IsDeleted <> 1 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetUnfilledInPayrollAccounts +/************************************************************ +** Author: dmoldawer +** Create Date: 2014-03-21 +** Description: Checks payroll accounts crosswalk for unfilled-in accounts +** Last Modified: 2017-02-10 +** GM Release: 2017.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2017-02-10 akk D-05027 Adding hours to view and making it work with all crosswalk types +** +*************************************************************/ + +CREATE view [ob].[viewExceptionsDepartmentBudgetUnfilledInPayrollAccounts] as + +---- Exceptions for Dollars Option 3b (and the overrides of 3a) +select + DB.DepartmentalBudgetID, + db.name as Model, + 'Account ' + DA.Name + ' is configured to receive salary data from Pay Code Group ' + DPG.Name + ' and Job Code ' + + DJC.Name + ' but is not filled in to the department' as detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + cross join clientob.FactPayrollToAccountCrosswalk CW with (readuncommitted) + inner join fw.DimAccount DA with (readuncommitted) on CW.AccountID = DA.AccountID + inner join fw.DimJobCode DJC with (readuncommitted) on CW.JobCodeID = DJC.JobCodeID + inner join fw.DimPayCodeGroup DPG with (readuncommitted) on CW.PayCodeGroupID = DPG.PayCodeGroupID + inner join data.ScoreFillin_PayCodeGroup FPG with (readuncommitted) on CW.PayCodeGroupID = FPG.PayCodeGroupID and FPG.ModelGUID = DB.MemberGUID + inner join data.ScoreFillin_JobCode FJC with (readuncommitted) on CW.JobCodeID = FJC.JobCodeID and FJC.ModelGUID = DB.MemberGUID and fjc.JobCodePHID=53 --job code (all) +where db.obactiveplans=1 + and not exists +(select + 1 +from + data.ScoreFillin_Account FI with (readuncommitted) + inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID and cw.AccountID=FI.AccountID +where + FI.ModelGUID = DB.MemberGUID + and PH.Name = 'Staffing - GL Accounts' +) +and CW.PayCodeGroupID<>0 +and CW.JobCodeID<>0 +and CW.UnitTypeID=34 --dollars + +union all + +---- Exceptions for Dollars Option 2 +select + DB.DepartmentalBudgetID, + db.name as Model, + 'Account ' + DA.Name + ' is configured to receive salary data from Job Code ' + + DJC.Name + ' but is not filled in to the department' as detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + cross join clientob.FactPayrollToAccountCrosswalk CW with (readuncommitted) + inner join fw.DimAccount DA with (readuncommitted) on CW.AccountID = DA.AccountID + inner join fw.DimJobCode DJC with (readuncommitted) on CW.JobCodeID = DJC.JobCodeID + inner join fw.DimPayCodeGroup DPG with (readuncommitted) on CW.PayCodeGroupID = DPG.PayCodeGroupID + inner join data.ScoreFillin_JobCode FJC with (readuncommitted) on CW.JobCodeID = FJC.JobCodeID and FJC.ModelGUID = DB.MemberGUID and fjc.JobCodePHID=53 --job code (all) +where db.obactiveplans=1 + and not exists +(select + 1 +from + data.ScoreFillin_Account FI with (readuncommitted) + inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID and cw.AccountID=FI.AccountID +where + FI.ModelGUID = DB.MemberGUID + and PH.Name = 'Staffing - GL Accounts' +) +and CW.PayCodeGroupID=0 +and CW.JobCodeID<>0 +and CW.UnitTypeID=34 --dollars + +union all + +---- Exceptions for Dollars Option 1 and the defaults for 3a +select + DB.DepartmentalBudgetID, + db.name as Model, + 'Account ' + DA.Name + ' is configured to receive salary data from Pay Code Group ' + DPG.Name + ' but is not filled in to the department' as detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + cross join clientob.FactPayrollToAccountCrosswalk CW with (readuncommitted) + inner join fw.DimAccount DA with (readuncommitted) on CW.AccountID = DA.AccountID + inner join fw.DimJobCode DJC with (readuncommitted) on CW.JobCodeID = DJC.JobCodeID + inner join fw.DimPayCodeGroup DPG with (readuncommitted) on CW.PayCodeGroupID = DPG.PayCodeGroupID + inner join data.ScoreFillin_PayCodeGroup FPG with (readuncommitted) on CW.PayCodeGroupID = FPG.PayCodeGroupID and FPG.ModelGUID = DB.MemberGUID +where db.obactiveplans=1 + and not exists +(select + 1 +from + data.ScoreFillin_Account FI with (readuncommitted) + inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID and cw.AccountID=FI.AccountID +where + FI.ModelGUID = DB.MemberGUID + and PH.Name = 'Staffing - GL Accounts' +) +and exists (select 1 from [data].[ScoreFillin_JobCode] FI with (readuncommitted) + where FI.ModelGUID = DB.MemberGUID + and FI.PlaceholderSectionMemberGUID='e9ce521d-6953-4636-94cd-b36798515385' -- Job Code (All) + and FI.JobCodeID<>0 + ) +and CW.PayCodeGroupID<>0 +and CW.JobCodeID=0 +and CW.UnitTypeID=34 --dollars + +union all + +---- Exceptions for Hours Option 3b (and the overrides of 3a) +select + DB.DepartmentalBudgetID, + db.name as Model, + 'Account ' + DA.Name + ' is configured to receive hours data from Pay Code Group ' + DPG.Name + ' and Job Code ' + + DJC.Name + ' but is not filled in to the department' as detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + cross join clientob.FactPayrollToAccountCrosswalk CW with (readuncommitted) + inner join fw.DimAccount DA with (readuncommitted) on CW.AccountID = DA.AccountID + inner join fw.DimJobCode DJC with (readuncommitted) on CW.JobCodeID = DJC.JobCodeID + inner join fw.DimPayCodeGroup DPG with (readuncommitted) on CW.PayCodeGroupID = DPG.PayCodeGroupID + inner join data.ScoreFillin_PayCodeGroup FPG with (readuncommitted) on CW.PayCodeGroupID = FPG.PayCodeGroupID and FPG.ModelGUID = DB.MemberGUID + inner join data.ScoreFillin_JobCode FJC with (readuncommitted) on CW.JobCodeID = FJC.JobCodeID and FJC.ModelGUID = DB.MemberGUID and fjc.JobCodePHID=53 --job code (all) +where db.obactiveplans=1 + and not exists +(select + 1 +from + data.ScoreFillin_Account FI with (readuncommitted) + inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID and cw.AccountID=FI.AccountID +where + FI.ModelGUID = DB.MemberGUID + and PH.Name = 'Staffing - Hours Accounts' +) +and CW.PayCodeGroupID<>0 +and CW.JobCodeID<>0 +and CW.UnitTypeID=51 -- hours + +union all + +---- Exceptions for Hours Option 2 +select + DB.DepartmentalBudgetID, + db.name as Model, + 'Account ' + DA.Name + ' is configured to receive hours data from Job Code ' + + DJC.Name + ' but is not filled in to the department' as detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + cross join clientob.FactPayrollToAccountCrosswalk CW with (readuncommitted) + inner join fw.DimAccount DA with (readuncommitted) on CW.AccountID = DA.AccountID + inner join fw.DimJobCode DJC with (readuncommitted) on CW.JobCodeID = DJC.JobCodeID + inner join fw.DimPayCodeGroup DPG with (readuncommitted) on CW.PayCodeGroupID = DPG.PayCodeGroupID + inner join data.ScoreFillin_JobCode FJC with (readuncommitted) on CW.JobCodeID = FJC.JobCodeID and FJC.ModelGUID = DB.MemberGUID and fjc.JobCodePHID=53 --job code (all) +where db.obactiveplans=1 + and not exists +(select + 1 +from + data.ScoreFillin_Account FI with (readuncommitted) + inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID and cw.AccountID=FI.AccountID +where + FI.ModelGUID = DB.MemberGUID + and PH.Name = 'Staffing - Hours Accounts' +) +and CW.PayCodeGroupID=0 +and CW.JobCodeID<>0 +and CW.UnitTypeID=51 -- hours + +union all + +---- Exceptions for Hours Option 1 and the defaults for 3a +select + DB.DepartmentalBudgetID, + db.name as Model, + 'Account ' + DA.Name + ' is configured to receive hours data from Pay Code Group ' + DPG.Name + ' but is not filled in to the department' as detail +from + ob.DimDepartmentalBudget DB with (readuncommitted) + cross join clientob.FactPayrollToAccountCrosswalk CW with (readuncommitted) + inner join fw.DimAccount DA with (readuncommitted) on CW.AccountID = DA.AccountID + inner join fw.DimJobCode DJC with (readuncommitted) on CW.JobCodeID = DJC.JobCodeID + inner join fw.DimPayCodeGroup DPG with (readuncommitted) on CW.PayCodeGroupID = DPG.PayCodeGroupID + inner join data.ScoreFillin_PayCodeGroup FPG with (readuncommitted) on CW.PayCodeGroupID = FPG.PayCodeGroupID and FPG.ModelGUID = DB.MemberGUID +where db.obactiveplans=1 + and not exists +(select + 1 +from + data.ScoreFillin_Account FI with (readuncommitted) + inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID and cw.AccountID=FI.AccountID +where + FI.ModelGUID = DB.MemberGUID + and PH.Name = 'Staffing - Hours Accounts' +) +and exists (select 1 from [data].[ScoreFillin_JobCode] FI with (readuncommitted) + where FI.ModelGUID = DB.MemberGUID + and FI.PlaceholderSectionMemberGUID='e9ce521d-6953-4636-94cd-b36798515385' -- Job Code (All) + and FI.JobCodeID<>0 + ) +and CW.PayCodeGroupID<>0 +and CW.JobCodeID=0 +and CW.UnitTypeID=51 -- hours +GO + + +--------------------------------------------- + +-- ob.viewExceptionsDepartmentBudgetUnmappedProviderForecastItems +/************************************************************ +** Author: akowalski +** Create Date: 2014-05-13 +** Description: Displays any provider comp forecast details that are not mapped to an account (which will prevent them from impacting the income statement) +** Last Modified: 2014-05-13 +** GM Release: 2014.3 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 7/8/16 vyaremko B-11627 Adding filter for 'Hours' and 'FTEs' +** 2 8/1/16 vyaremko B-11627 Exclude 'FTEs' from exception report +** +*************************************************************/ +CREATE VIEW [ob].[viewExceptionsDepartmentBudgetUnmappedProviderForecastItems] AS + +SELECT + DISTINCT + db.[DepartmentalBudgetID], + db.[Name] AS Model, + 'Forecast detail ' + fd.[Name] + ' does not have an GL account associated with it for Physician Providers' as Detail +FROM [ob].[DimDepartmentalBudget] AS db WITH (READUNCOMMITTED) + INNER JOIN [data].[ScoreFillin_Provider] AS sf WITH (READUNCOMMITTED) ON db.[MemberGUID] = sf.[ModelGUID] AND + sf.[PlaceholderSectionMemberGUID] <> '93524AAB-C5E0-428F-81DE-6AD7ED5CE0CC' --not specified + CROSS JOIN [ob].[DimOBForecastDetail] AS fd WITH (READUNCOMMITTED) +WHERE + (fd.[Category] LIKE 'Provider Comp%') + AND ((fd.[AccountID] = 0) OR (fd.[Account] = '0 - Not Specified')) + AND + ( + ((fd.[Category] <> 'Provider Compensation - FTEs') AND (fd.[Category] <> 'Provider Compensation - Hours')) + OR ((fd.[Category] = 'Provider Compensation - Hours') AND EXISTS(SELECT 1 FROM [dbo].[SystemCenterStep] AS scs WHERE scs.[GlobalID] = 'HourstoAccountMappings' AND (CAST(scs.[PropertyXML].query('//IsHoursChecked/text()') AS NVARCHAR(5)) = 'True'))) + ) + AND (db.[DepartmentalBudgetID] <> 0) + +UNION ALL + +SELECT + DISTINCT + db.[DepartmentalBudgetID], + db.[Name] as Model, + 'Forecast detail ' + fd.[Name] + ' does not have an GL account associated with it for Non-Physician Providers' AS Detail +FROM [ob].[DimDepartmentalBudget] AS db WITH (READUNCOMMITTED) + INNER JOIN [data].[ScoreFillin_Provider] AS sf WITH (READUNCOMMITTED) ON db.[MemberGUID] = sf.[ModelGUID] AND + sf.[PlaceholderSectionMemberGUID] <> '93524AAB-C5E0-428F-81DE-6AD7ED5CE0CC' --not specified + CROSS JOIN [ob].[DimOBForecastDetail] AS fd WITH (READUNCOMMITTED) +WHERE + (fd.[Category] LIKE 'Provider Comp%') + AND ((fd.[SecondaryAccountID] = 0) OR (fd.[SecondaryAccount] = '0 - Not Specified')) + AND + ( + ((fd.[Category] <> 'Provider Compensation - FTEs') AND (fd.[Category] <> 'Provider Compensation - Hours')) + OR ((fd.[Category] = 'Provider Compensation - Hours') AND EXISTS(SELECT 1 FROM [dbo].[SystemCenterStep] AS scs WHERE scs.[GlobalID] = 'HourstoAccountMappings' AND (CAST(scs.[PropertyXML].query('//IsHoursChecked/text()') AS NVARCHAR(5)) = 'True'))) + ) + AND (db.[DepartmentalBudgetID] <> 0) +GO + + +--------------------------------------------- + +-- ob.viewExceptionsGlobalStatsAccountsNotBudgeted +/************************************************************ +** Author: jgerber +** Create Date: 2015-01-18 +** Description: Finds any accounts that have YTD data but don't have a budget +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + +create view [ob].[viewExceptionsGlobalStatsAccountsNotBudgeted] +as + +select + db.OBGlobalStatisticsPlanID, + db.Name as Model, + 'Has '+cast(cast(Sum(Total) as decimal(16,2)) as nvarchar(100))+' current year '+ut.Name+' for Global Statistic '+acc.Name+' but does not have a budget' as Detail + +from [clientob].[FactGlobalStatistics] fa +inner join [fw].[DimUnitType] ut on fa.UnitTypeID=ut.UnitTypeID +inner join [ob].[DimOBGlobalStatistics] acc on acc.OBGlobalStatisticID=fa.OBGlobalStatisticID +inner join [ob].[DimOBGlobalStatisticsPlan] db on db.OBGlobalStatisticsPlanID=fa.OBGlobalStatisticsPlanID +where + FiscalYearID = (select Setting from [dbo].[DBSetting] where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62') + and TimeClassID=1 + and Total<>0 + and acc.OBGlobalStatisticID<>0 + and ut.UnitTypeID in (34,51,140) --Dollars, Volume, and Hours (contract labor) + and not exists + (select + 1 + from + [clientob].[FactGlobalStatistics] fa2 + where + FiscalYearID = (select Setting+1 from [dbo].[DBSetting] where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62') + and TimeClassID=2 + and Total<>0 + and fa2.OBGlobalStatisticsPlanID=fa.OBGlobalStatisticsPlanID + and fa2.OBGlobalStatisticID=fa.OBGlobalStatisticID + and fa2.UnitTypeID=fa.UnitTypeID) +group by + db.OBGlobalStatisticsPlanID, + db.Name, + ut.Name, + acc.Name +GO + + +--------------------------------------------- + +-- ob.viewExceptionsGlobalStatsAllocationsNot100Pct +/************************************************************ +** Author: jgerber +** Create Date: 2015-01-18 +** Description: Checks for any reportable global stat being allocated any differently than 100% +** Last Modified: 08/22/2017 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 08/22/2017 vyaremko 05689 Ignore deleted records +** +*************************************************************/ + +CREATE VIEW [ob].[viewExceptionsGlobalStatsAllocationsNot100Pct] +AS + +SELECT + DISTINCT + GSP.[OBGlobalStatisticsPlanID] AS [OBGlobalStatisticsPlanID], + GSP.[Name] AS [Model], + 'Has an allocation of '+ CAST(CAST([TotalAllocation] * 100 AS DECIMAL(6,2)) AS NVARCHAR(10)) + '% for Global Statistic: ' + GS.[Name] AS [Detail] +FROM [ob].[DimOBGlobalStatisticsPlan] AS GSP + INNER JOIN ( + SELECT + [OBGlobalStatisticsPlanID], + [OBGlobalStatisticID], + SUM([Allocation]) AS [TotalAllocation] + FROM [clientob].[FactGlobalStatisticsDeptMapping] + WHERE [IsReportable] = 1 AND [IsDeleted] = 0 + GROUP BY [OBGlobalStatisticsPlanID], [OBGlobalStatisticID] + ) AS ROLLUP + ON GSP.[OBGlobalStatisticsPlanID] = ROLLUP.[OBGlobalStatisticsPlanID] + INNER JOIN [ob].[DimOBGlobalStatistics] AS GS + ON GS.[OBGlobalStatisticID] = ROLLUP.[OBGlobalStatisticID] +WHERE [TotalAllocation] <> 1; +GO + + +--------------------------------------------- + +-- ob.viewExceptionsGlobalStatsDataWithoutDimensionMembers +/************************************************************ +** Author: jgerber +** Create Date: 2014-09-18 +** Description: Checks for global stat data that does not have dimension members +** Last Modified: 2014-09-18 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +*************************************************************/ + +create view [ob].[viewExceptionsGlobalStatsDataWithoutDimensionMembers] as + +--***Fact Global Statistics********************************************* +-- Department Dimension + select + Distinct + 0 as OBGlobalStatisticsPlanID, + 'Not Specified' as Model, + 'Has Global Statistics data for a Global Statistics Plan that no longer exists' as Detail + from + [clientob].[FactGlobalStatistics] data with (readuncommitted) + left join [ob].[DimOBGlobalStatisticsPlan] db with (readuncommitted) on db.OBGlobalStatisticsPlanID = data.OBGlobalStatisticsPlanID + where + db.MemberGUID is null + +UNION ALL + +-- Global Statistics Dimension + select + Distinct + db.OBGlobalStatisticsPlanID, + db.Name as Model, + 'Has Global Statistics data for a Global Statistic that no longer exists' as Detail + from + [clientob].[FactGlobalStatistics] data with (readuncommitted) + inner join[ob].[DimOBGlobalStatisticsPlan] db with (readuncommitted) on db.OBGlobalStatisticsPlanID = data.OBGlobalStatisticsPlanID + left join [ob].[DimOBGlobalStatistics] dim with (readuncommitted) on dim.OBGlobalStatisticID = data.OBGlobalStatisticID + where + dim.MemberGUID is null +GO + + +--------------------------------------------- + +-- ob.viewExceptionsGlobalStatsDepartmentAllocationOrphanedData +/************************************************************ +** Author: jgerber +** Create Date: 2015-01-18 +** Description: Checks for global stat allocations that don't have dimension members +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + +create view [ob].[viewExceptionsGlobalStatsDepartmentAllocationOrphanedData] +as + + +-- Department Dimension + select + Distinct + 0 as OBGlobalStatisticsPlanID, + 'Not Specified' as Model, + 'Has a Global Statistics Allocation for a Departmental Budget Plan that no longer exists' as Detail + from + [clientob].[viewFactGlobalStatisticMapping] data with (readuncommitted) + left join [ob].[DimDepartmentalBudget] db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + where + db.MemberGUID is null + +UNION ALL + +-- Account Dimension + select + Distinct + dep.OBGlobalStatisticsPlanID, + db.Name as Model, + 'Has a Global Statistics Allocation for an Account that no longer exists' as Detail + from + [clientob].[viewFactGlobalStatisticMapping] data with (readuncommitted) + inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + inner join [fw].[DimDepartment] dep with (readuncommitted) on dep.DepartmentID=db.DepartmentID + left join [fw].[DimAccount] dim with (readuncommitted) on dim.AccountID = data.AccountID + where + dim.MemberGUID is null + +UNION ALL + +-- Global Statistics Dimension + select + Distinct + dep.OBGlobalStatisticsPlanID, + db.Name as Model, + 'Has a Global Statistics Allocation for a Global Statistic that no longer exists' as Detail + from + [clientob].[viewFactGlobalStatisticMapping] data with (readuncommitted) + inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + inner join [fw].[DimDepartment] dep with (readuncommitted) on dep.DepartmentID=db.DepartmentID + left join [ob].[DimOBGlobalStatistics] dim with (readuncommitted) on dim.AccountID = data.AccountID and dim.DepartmentID=data.DepartmentID + where + dim.MemberGUID is null +GO + + +--------------------------------------------- + +-- ob.viewExceptionsGlobalStatsDuplicateFillins +/************************************************************ +** Author: jgerber +** Create Date: 2015-01-18 +** Description: Finds all duplicate fillins in the OB Global Statistics model for the Account and Globals Statistics dimensions +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + +create view [ob].[viewExceptionsGlobalStatsDuplicateFillins] as + +--ACCOUNTS +--CHECK IF EXCLUSIVE FILLINS EXIST IN OTHER SECTIONS + +select + DB.OBGlobalStatisticsPlanID, + DB.Name as Model, + DIM.Name + ' in section ' + PH.Name + ' is also in another section' as Detail + +from + ob.DimOBGlobalStatisticsPlan DB with (readuncommitted) + inner join XPlan X with (readuncommitted) on DB.MemberGUID = X.PlanGUID + inner join data.ScoreFillin_Account FI with (readuncommitted) on DB.MemberGUID = FI.ModelGUID + inner join fw.DimAccount DIM with (readuncommitted) on FI.AccountID = DIM.AccountID + inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID + inner join +( +select + distinct DB.OBGlobalStatisticsPlanID, FI1.AccountID +from + [ob].[DimOBGlobalStatisticsPlan] DB with (readuncommitted) + inner join XPlan X with (readuncommitted) on DB.MemberGUID = X.PlanGUID + inner join MEPHSection ME with (readuncommitted) on X.ModelTemplateGUID = ME.ModelTemplateGUID + inner join data.ScoreFillin_Account FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID + and ME.PHSectionMemberGUID = FI1.PlaceholderSectionMemberGUID +where + exists (select 1 from data.ScoreFillin_Account FI2 with (readuncommitted) + inner join XPlan X with (readuncommitted) on fi2.modelguid = X.PlanGUID + inner join MEPHSection ME2 with (readuncommitted) on X.ModelTemplateGUID = ME2.ModelTemplateGUID and FI2.PlaceholderSectionMemberGUID=ME2.PHSectionMemberGUID + where FI2.ModelGUID = FI1.ModelGUID and FI2.FillinMemberGUID = FI1.FillinMemberGUID and FI2.FillinGUID != FI1.FillinGUID + and ME2.ExclusivityGroup=me.ExclusivityGroup) + and ME.IsExclusive = 1 +) DUPES + on DB.OBGlobalStatisticsPlanID = DUPES.OBGlobalStatisticsPlanID + and DIM.AccountID = DUPES.AccountID + and PH.AccountPHID<>0 + +union all + +--GLOBAL STATISTICS +-- CHECK IF FILLINS EXISTS IN BOTH VARIABLE AND FIXED +select + DB.OBGlobalStatisticsPlanID, + DB.Name as Model, + DIM.Name + ' in section ' + PH.Name + ' is also in another section' as Detail + +from + ob.DimOBGlobalStatisticsPlan DB with (readuncommitted) + inner join XPlan X with (readuncommitted) on DB.MemberGUID = X.PlanGUID + inner join [data].[ScoreFillin_OBGlobalStatistics] FI with (readuncommitted) on DB.MemberGUID = FI.ModelGUID + inner join [ob].[DimOBGlobalStatistics] DIM with (readuncommitted) on FI.OBGlobalStatisticID = DIM.OBGlobalStatisticID + inner join [ob].[DimOBGlobalStatisticsPH] PH with (readuncommitted) on FI.OBGlobalStatisticsPHID = PH.OBGlobalStatisticsPHID + inner join +( +select + distinct DB.OBGlobalStatisticsPlanID, FI1.OBGlobalStatisticID +from + [ob].[DimOBGlobalStatisticsPlan] DB with (readuncommitted) + inner join XPlan X with (readuncommitted) on DB.MemberGUID = X.PlanGUID + inner join MEPHSection ME with (readuncommitted) on X.ModelTemplateGUID = ME.ModelTemplateGUID + inner join data.ScoreFillin_OBGlobalStatistics FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID + and ME.PHSectionMemberGUID = FI1.PlaceholderSectionMemberGUID +where + exists (select 1 from data.ScoreFillin_OBGlobalStatistics FI2 with (readuncommitted) + inner join XPlan X with (readuncommitted) on fi2.modelguid = X.PlanGUID + inner join MEPHSection ME2 with (readuncommitted) on X.ModelTemplateGUID = ME2.ModelTemplateGUID and FI2.PlaceholderSectionMemberGUID=ME2.PHSectionMemberGUID + where FI2.ModelGUID = FI1.ModelGUID and FI2.FillinMemberGUID = FI1.FillinMemberGUID and FI2.FillinGUID != FI1.FillinGUID + and ME2.ExclusivityGroup=me.ExclusivityGroup) + and ME.IsExclusive = 1 +) DUPES + on DB.OBGlobalStatisticsPlanID = DUPES.OBGlobalStatisticsPlanID + and DIM.OBGlobalStatisticID = DUPES.OBGlobalStatisticID + and PH.OBGlobalStatisticsPHID<>0 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsGlobalStatsFillinCacheIssues +/************************************************************ +** Author: jgerber +** Create Date: 2015-01-18 +** Description: Checks for fill-ins in Score Fill-ins but not in Cache tables or PH Index doesnt Match +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-02-26 mholov D-03407 Filtering out 'GM Blank' model template +** 2 2016-08-10 kf B-12543 FP - System Center Exception Management - Initial Framework +*************************************************************/ +CREATE view [ob].[viewExceptionsGlobalStatsFillinCacheIssues] as + +--Account +select + DB.OBGlobalStatisticsPlanID, + DB.Name as Model, + 'The fill-in cache for Account ' + DIM.Name + ' out of sync' as Detail +from + [ob].[DimOBGlobalStatisticsPlan] DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join data.ScoreFillin_Account FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join fw.DimAccount DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null + and db.OBGlobalStatisticsPlanID<>0 + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank + +union all + +select + DB.OBGlobalStatisticsPlanID, + DB.Name as Model, + 'The fill-in cache for Account ' + DIM.Name + ' out of sync' as Detail +from + [ob].[DimOBGlobalStatisticsPlan] DB with (readuncommitted) + inner join data.ScoreFillin_Account FI with (readuncommitted) on DB.MemberGUID = FI.ModelGUID + left join ScoreFillin SF with (readuncommitted) on FI.ModelGUID = SF.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join fw.DimAccount DIM with (readuncommitted) on FI.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where SF.FillinMemberGUID is null + and db.OBGlobalStatisticsPlanID<>0 + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank + +union all + +--Global Statistics +select + DB.OBGlobalStatisticsPlanID, + DB.Name as Model, + 'The fill-in cache for Global Statistic ' + DIM.Name + ' out of sync' as Detail +from + ob.DimOBGlobalStatisticsPlan DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join [data].[ScoreFillin_OBGlobalStatistics] FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join [ob].[DimOBGlobalStatistics] DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null + and db.OBGlobalStatisticsPlanID<>0 + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank + +union all + +select + DB.OBGlobalStatisticsPlanID, + DB.Name as Model, + 'The fill-in cache for Global Statistic ' + DIM.Name + ' out of sync' as Detail +from + ob.DimOBGlobalStatisticsPlan DB with (readuncommitted) + inner join [data].[ScoreFillin_OBGlobalStatistics] FI with (readuncommitted) on DB.MemberGUID = FI.ModelGUID + left join ScoreFillin SF with (readuncommitted) on FI.ModelGUID = SF.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join [ob].[DimOBGlobalStatistics] DIM with (readuncommitted) on FI.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where SF.FillinMemberGUID is null + and db.OBGlobalStatisticsPlanID<>0 + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank + +union all + + +--Global Statistics Plan +select + DB.OBGlobalStatisticsPlanID, + DB.Name as Model, + 'The fill-in cache for Global Statistics Plan ' + DIM.Name + ' out of sync' as Detail +from + ob.DimOBGlobalStatisticsPlan DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join [data].[ScoreFillin_OBGlobalStatisticsPlan] FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join [ob].[DimOBGlobalStatisticsPlan] DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null + and db.OBGlobalStatisticsPlanID<>0 + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank + +union all + +select + DB.OBGlobalStatisticsPlanID, + DB.Name as Model, + 'The fill-in cache for Global Statistics Plan ' + DIM.Name + ' out of sync' as Detail +from + ob.DimOBGlobalStatisticsPlan DB with (readuncommitted) + inner join [data].[ScoreFillin_OBGlobalStatisticsPlan] FI with (readuncommitted) on DB.MemberGUID = FI.ModelGUID + left join ScoreFillin SF with (readuncommitted) on FI.ModelGUID = SF.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join [ob].[DimOBGlobalStatisticsPlan] DIM with (readuncommitted) on FI.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where SF.FillinMemberGUID is null + and db.OBGlobalStatisticsPlanID<>0 + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank + +union all + + +--Fiscal Year +select + DB.OBGlobalStatisticsPlanID, + DB.Name as Model, + 'The fill-in cache for Fiscal Year ' + DIM.Name + ' out of sync' as Detail +from + ob.DimOBGlobalStatisticsPlan DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join data.ScoreFillin_FiscalYear FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join fw.DimFiscalYear DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null + and db.OBGlobalStatisticsPlanID<>0 + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank + +UNION ALL + +select + DB.OBGlobalStatisticsPlanID, + DB.Name as Model, + 'The fill-in cache for Fiscal Year ' + DIM.Name + ' out of sync' as Detail +from + ob.DimOBGlobalStatisticsPlan DB with (readuncommitted) + inner join [data].[ScoreFillin_FiscalYear] FI with (readuncommitted) on DB.MemberGUID = FI.ModelGUID + left join ScoreFillin SF with (readuncommitted) on FI.ModelGUID = SF.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join fw.DimFiscalYear DIM with (readuncommitted) on FI.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where SF.FillinMemberGUID is null + and db.OBGlobalStatisticsPlanID<>0 + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank +GO + + +--------------------------------------------- + +-- ob.viewExceptionsGlobalStatsFillinsExceedingMaxCount +/************************************************************ +** Author: jgerber +** Create Date: 2015-01-18 +** Description: Finds all max fillin exceptions for Global Statistics +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + +create view [ob].[viewExceptionsGlobalStatsFillinsExceedingMaxCount] as +select + DB.OBGlobalStatisticsPlanID, + DB.Name as Model, + 'Has ' + cast((select COUNT(*) from [data].[ScoreFillin_OBGlobalStatistics] FI with (readuncommitted) inner join [ob].[DimOBGlobalStatisticsPH] PH with (readuncommitted) on FI.OBGlobalStatisticsPHID = PH.OBGlobalStatisticsPHID where DB.MemberGUID = FI.ModelGUID and PH.Name = SE.GlobalID) as varchar(10)) + + ' Global Statistics in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail + +from + XPlan X with (readuncommitted) + inner join [ob].[DimOBGlobalStatisticsPlan] DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID + inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID + inner join EMFModelTemplateWorksheet WS with (readuncommitted) on MT.ModelTemplateGUID = WS.ModelTemplateGUID + inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID + inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID +where + (select COUNT(*) from data.ScoreFillin_OBGlobalStatistics FI with (readuncommitted) inner join ob.DimOBGlobalStatisticsPH PH with (readuncommitted) on FI.OBGlobalStatisticsPHID = PH.OBGlobalStatisticsPHID where DB.MemberGUID = FI.ModelGUID and PH.Name = SE.GlobalID) > SE.[Count] +GO + + +--------------------------------------------- + +-- ob.viewExceptionsGlobalStatsInvalidDropdownSelection +/************************************************************ +** Author: jgerber +** Create Date: 2015-01-18 +** Description: Finds any text boxes that saved a value of blank that will cause #n/a errors in the model +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + +create view [ob].[viewExceptionsGlobalStatsInvalidDropdownSelection] as + +select +Distinct +DB.OBGlobalStatisticsPlanID, +DB.Name as Model, +'Global Statistic ' + Dim.Name + ' has an invalid drop-down box selection' as Detail +from [clientob].[FactGlobalStatisticsVar] fct with (readuncommitted) +inner join [ob].[DimOBGlobalStatisticsPlan] DB with (readuncommitted) on fct.OBGlobalStatisticsPlanID=db.OBGlobalStatisticsPlanID +inner join [ob].[DimOBGlobalStatistics] DIM with (readuncommitted) on fct.OBGlobalStatisticID = DIM.OBGlobalStatisticID +where fct.UnitTypeID=141 +and TextValue_Formula='x' +and TextValue='' +GO + + +--------------------------------------------- + +-- ob.viewExceptionsGlobalStatsMissingGlobalStatistics +/**************************************************************************************************************** +** Author: akowalski +** Create Date: 2014-06-29 +** Description: Detects any statistics loaded into the global statistics import table that will go no where in global statistic sampling +** Last Modified: 2014-08-29 +** GM Release: 2014.4 +****************************************************************************************************************** +** Change History +****************************************************************************************************************** +** CID Date Author WI Description +** 1 2017-01-11 srk D-05373 Commented out a section that is a valid use case +** (departments with some stats that are driven off of history +** but some are global stats depending on the Global Statistics +** dimension setup/mapping) +** +*****************************************************************************************************************/ +CREATE view [ob].[viewExceptionsGlobalStatsMissingGlobalStatistics] as + +SELECT + distinct + GSP.OBGlobalStatisticsPlanID, + GSP.Name as Model, + 'Has data for Department ' + d.Name + ' and account ' + a.Name + ' but does not have a department-level global statistic configured' as Detail +FROM + [int].[FactGlobalStatistics] fct with (readuncommitted) + inner join fw.DimDepartment d with (readuncommitted) on fct.DepartmentID=d.DepartmentID + inner join [fw].[DimAccount] a with (readuncommitted) on a.AccountID=fct.AccountID + inner join [ob].[DimOBGlobalStatisticsPlan] gsp with (readuncommitted) on gsp.OBGlobalStatisticsPlanID=d.OBGlobalStatisticsPlanID + left outer join [ob].[DimOBGlobalStatistics] gs with (readuncommitted) on gs.AccountID=fct.AccountID and gs.DepartmentID=fct.DepartmentID + where a.IsGlobal=0 and gs.Name is null + and gsp.OBGlobalStatisticsPlanID<>0 and d.IsOB=1 and d.IsActive=1 + and a.IsStat=1 + + +union all + +SELECT + distinct + GSP.OBGlobalStatisticsPlanID, + GSP.Name as Model, + 'Has data for account ' + a.Name + ' but does not have an entity-level global statistic configured' as Detail +FROM + [int].[FactGlobalStatistics] fct with (readuncommitted) + inner join fw.DimDepartment d with (readuncommitted) on fct.DepartmentID=d.DepartmentID + inner join [fw].[DimAccount] a with (readuncommitted) on a.AccountID=fct.AccountID + inner join [ob].[DimOBGlobalStatisticsPlan] gsp with (readuncommitted) on gsp.OBGlobalStatisticsPlanID=d.OBGlobalStatisticsPlanID + left outer join [ob].[DimOBGlobalStatistics] gs with (readuncommitted) on gs.AccountID=fct.AccountID and gs.DepartmentID=0 + where a.IsGlobal=1 and gs.Name is null + and gsp.OBGlobalStatisticsPlanID<>0 and d.IsOB=1 and d.IsActive=1 + and a.IsStat=1 + +--CID 1 BEGIN-- + +--union all +-- +--SELECT +-- distinct +-- GSP.OBGlobalStatisticsPlanID, +-- GSP.Name as Model, +-- 'Has data for Department ' + d.Name + ' and account ' + a.Name + ' but does not have a department-level global statistics configured' as Detail +--FROM +-- [int].[FactStatistic] fct with (readuncommitted) +-- inner join fw.DimDepartment d with (readuncommitted) on fct.DepartmentID=d.DepartmentID +-- inner join [fw].[DimAccount] a with (readuncommitted) on a.AccountID=fct.AccountID +-- inner join [ob].[DimOBGlobalStatisticsPlan] gsp with (readuncommitted) on gsp.OBGlobalStatisticsPlanID=d.OBGlobalStatisticsPlanID +-- left outer join [ob].[DimOBGlobalStatistics] gs with (readuncommitted) on gs.AccountID=fct.AccountID and gs.DepartmentID=fct.DepartmentID +-- where a.IsGlobal=0 and gs.Name is null +-- and gsp.OBGlobalStatisticsPlanID<>0 and d.IsOB=1 and d.IsActive=1 +-- and a.IsStat=1 + +--CID 1 END-- + +union all + +SELECT + distinct + GSP.OBGlobalStatisticsPlanID, + GSP.Name as Model, + 'Has data for account ' + a.Name + ' but does not have an entity-level global statistic configured' as Detail +FROM + [int].[FactStatistic] fct with (readuncommitted) + inner join fw.DimDepartment d with (readuncommitted) on fct.DepartmentID=d.DepartmentID + inner join [fw].[DimAccount] a with (readuncommitted) on a.AccountID=fct.AccountID + inner join [ob].[DimOBGlobalStatisticsPlan] gsp with (readuncommitted) on gsp.OBGlobalStatisticsPlanID=d.OBGlobalStatisticsPlanID + left outer join [ob].[DimOBGlobalStatistics] gs with (readuncommitted) on gs.AccountID=fct.AccountID and gs.DepartmentID=0 + where a.IsGlobal=1 and gs.Name is null + and gsp.OBGlobalStatisticsPlanID<>0 and d.IsOB=1 and d.IsActive=1 + and a.IsStat=1 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsGlobalStatsMissingSelfFillin +/************************************************************ +** Author: jgerber +** Create Date: 2015-01-18 +** Description: Displays any global statistics that are missing their self fill-in +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-08-10 kf B-12543 FP - System Center Exception Management - Initial Framework +*************************************************************/ + +CREATE view [ob].[viewExceptionsGlobalStatsMissingSelfFillin] as + +select Distinct + DB.OBGlobalStatisticsPlanID, + DB.Name as Model, + 'Global Statistics Plan ' + db.Name + ' is missing the self-fill-in' as Detail +from + [ob].[DimOBGlobalStatisticsPlan] DB with (readuncommitted) + left outer join [data].[ScoreFillin_OBGlobalStatisticsPlan] sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and PlaceholderSectionMemberGUID='4c6057f6-854c-410c-9b51-4feb8e70c98e' +where + sf.FillinGUID is null + and db.OBGlobalStatisticsPlanID<>0 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsGlobalStatsOrphanedData +/************************************************************ +** Author: akowalski +** Create Date: 2014-09-17 +** Description: Checks for nonzero data that will not show up in the model because a fillin is missing +** Last Modified: 2014-09-17 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + +Create view [ob].[viewExceptionsGlobalStatsOrphanedData] as + +-- Stat data + select + Distinct + db.OBGlobalStatisticsPlanID, + db.Name as Model, + 'Has data in Statistic ' + dim.Name+ ' but it is not filled in' as Detail + from + [clientob].[FactGlobalStatistics] data with (readuncommitted) + inner join [ob].[DimOBGlobalStatisticsPlan] db with (readuncommitted) on db.OBGlobalStatisticsPlanID = data.OBGlobalStatisticsPlanID + inner join [ob].[DimOBGlobalStatistics] dim with (readuncommitted) on dim.OBGlobalStatisticID=data.OBGlobalStatisticID + left outer join [data].[ScoreFillin_OBGlobalStatistics] sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID + and sf.PlaceholderSectionMemberGUID<>'b2ac7cce-90f5-47fc-a75e-c695ce64583d' --not specified + where + sf.FillinGUID is null + and data.Total <> 0 and data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') + and db.OBGlobalStatisticsPlanID<>0 + and dim.OBGlobalStatisticID<>0 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsGlobalStatsProjectedEqualYTD +/************************************************************ +** Author: jgerber +** Create Date: 2015-01-18 +** Description:Compares Projected total and YTD to determine if anything is being projected in the non-closed months, indicates potential errors +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + +create view [ob].[viewExceptionsGlobalStatsProjectedEqualYTD] as + + +select +Distinct +DB.OBGlobalStatisticsPlanID, +DB.Name as Model, +'Has projected = YTD for Global Statistics: ' + Dim.Name + ' in section ' + PH.Name as Detail +from [clientob].[FactGlobalStatistics] fct with (readuncommitted) +inner join [ob].[DimOBGlobalStatisticsPlan] db with (readuncommitted) on db.OBGlobalStatisticsPlanID=fct.OBGlobalStatisticsPlanID +inner join [ob].[DimOBGlobalStatistics] DIM with (readuncommitted) on fct.OBGlobalStatisticID = DIM.OBGlobalStatisticID +inner join [data].[ScoreFillin_OBGlobalStatistics] SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + and dim.MemberGUID=sf.FillinMemberGUID +inner join [ob].[DimOBGlobalStatisticsPH] PH with (readuncommitted) on SF.PlaceholderSectionMemberGUID= PH.MemberGUID +where fct.datatypeid=3 +and fct.YTD=fct.Total +and fct.TimeClassID=12 +and fct.Total<>0 +and fct.MonthsLoaded<>12 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsInvalidRosterBudgetData +CREATE VIEW ob.viewExceptionsInvalidRosterBudgetData +AS +/**************************************************************************************************** +** Author: cbecker +** Create Date: 2017-02-09 +** Description: Checks for data imported from roster budgeting with no fixed staffing fill-in +** Last Modified: 2017-02-09 +** GM Release: 2017.1.2 +**************************************************************************************************** +** Change History +**************************************************************************************************** +** CID Date Author WI Description +** +****************************************************************************************************/ + +SELECT distinct + DepartmentCode = ddb.DepartmentCode, + DepartmentalBudgetID = ddb.DepartmentalBudgetID, + DepartmentalBudget = ddb.Name, + JobCodeID = djc.JobCodeID, + JobCode = djc.Name, + FTEs = SUM(FTEs), + Dollars = SUM(Dollars), + Detail = case + when ddb.DepartmentalBudgetID is null + then 'Departmental Budget does not exist' + when ddb.OBActivePlans = 0 + then 'Departmental Budget has not been activated' + when djc.JobCodeID is null + then 'Job code does not exist' + when sf.PlaceholderSectionMemberGUID is null + then 'Job code does not exist in this model' + else 'Job code is in the wrong section' + end +FROM [fp].[RosterBudgetBasisResult] rb + left join [fp].[BudgetConfig] bc + on rb.BudgetConfigGUID = bc.BudgetConfigGUID + left join [ob].[DimDepartmentalBudget] ddb + on rb.DepartmentID = ddb.DepartmentID + left join [fw].[DimJobCode] djc + on rb.JobCodeID = djc.JobCodeID + left join [fw].[DimPayCodeGroup] dpcg + on rb.PayCodeGroupID = dpcg.PayCodeGroupID + left join [data].[ScoreFillin_JobCode] sf + on djc.MemberGUID = sf.FillinMemberGUID + and ddb.MemberGUID = sf.ModelGUID + left join [clientob].[FactStaffingPCNonReporting] fct + on ddb.DepartmentalBudgetID = fct.DepartmentalBudgetID + and djc.JobCodeID = fct.JobCodeID + and dpcg.PayCodeGroupID = fct.PayCodeGroupID + and bc.FiscalYearID = fct.FiscalYearID +where ddb.DepartmentalBudgetID is null or djc.JobCodeID is null or dpcg.PayCodeGroupID is null +and bc.IsActive = 1 +GROUP BY + ddb.DepartmentCode, + ddb.DepartmentalBudgetID, + ddb.Name, + djc.JobCodeID, + djc.Name, + ddb.OBActivePlans, + sf.PlaceholderSectionMemberGUID +GO + + +--------------------------------------------- + +-- ob.viewExceptionsReimbursementAccountsNotBudgeted +/************************************************************ +** Author: blewis +** Create Date: 2015-01-15 +** Description: Finds any text boxes that saved a value of blank that will cause #n/a errors in the model +** Last Modified: 2015-01-15 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 +** +*************************************************************/ + +CREATE view [ob].[viewExceptionsReimbursementAccountsNotBudgeted] AS + + +select + db.OBReimbursementPlanID, + db.Name as Model, + 'Has '+cast(cast(Sum(Total) as decimal(16,2)) as nvarchar(100))+' current year '+ut.Name+' for Account '+acc.Name+' but does not have a budget' as Detail + +from [clientob].[FactReimbursementAccount] fa +inner join [fw].[DimUnitType] ut on fa.UnitTypeID=ut.UnitTypeID +inner join [fw].[DimAccount] acc on acc.AccountID=fa.AccountID +inner join [ob].[DimOBReimbursementPlan] db on db.OBReimbursementPlanID=fa.OBReimbursementPlanID +where + FiscalYearID = (select Setting from [dbo].[DBSetting] where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62') + and TimeClassID=1 + and Total<>0 + and acc.AccountID<>0 + and not (acc.OBIsDefined=1 and acc.OBAccountPHID=0 and acc.OBStatModelSectionID=0) + and db.OBReimbursementPlanID<>0 + and ut.UnitTypeID in (34,51,140) --Dollars, Volume, and Hours (contract labor) + and not exists + (select + 1 + from + [clientob].[FactReimbursementAccount] fa2 + where + FiscalYearID = (select Setting+1 from [dbo].[DBSetting] where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62') + and TimeClassID=2 + and Total<>0 + and fa2.OBReimbursementPlanID=fa.OBReimbursementPlanID + and fa2.AccountID=fa.AccountID + and fa2.UnitTypeID=fa.UnitTypeID) +group by + db.OBReimbursementPlanID, + db.Name, + ut.Name, + acc.Name +GO + + +--------------------------------------------- + +-- ob.viewExceptionsReimbursementAllocationsNot100Pct +/************************************************************ +** Author: blewis +** Create Date: 2015-01-15 +** Description: Checks that Account Allocation is 100% for each account in Allocation table +** Last Modified: 2015-01-15 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 +** +*************************************************************/ + +CREATE view [ob].[viewExceptionsReimbursementAllocationsNot100Pct] as + + +SELECT +DB.OBReimbursementPlanID, +DB.Name as Model, +'Has Budget Allocation Not Equal to 1.0000 for Account: ' + Dim.Name + ' Allocation = ' + Cast(round(SUM(BudgetAllocation),4) as nvarchar(max)) as Detail +from [clientob].[FactReimbursementDeptMapping] fct with (readuncommitted) +inner join [ob].[DimOBReimbursementPlan] DB with (readuncommitted) on fct.OBReimbursementPlanID=DB.OBReimbursementPlanID +inner join [fw].[DimDepartment] md with (readuncommitted) on fct.DepartmentID=md.DepartmentID +inner join [ob].[DimDepartmentalBudget] D with (readuncommitted) on md.DepartmentID=D.DepartmentID +inner join [fw].[DimAccount] Dim with (readuncommitted) on fct.AccountID=Dim.AccountID +Group by fct.AccountID, Dim.Name, DB.OBReimbursementPlanID, DB.Name +Having SUM(BudgetAllocation)<>1 + +Union All + +SELECT +DB.OBReimbursementPlanID, +DB.Name as Model, +'Has Projection Allocation Not Equal to 1.0000 for Account: ' + Dim.Name + ' Allocation = ' + Cast(round(SUM(ProjectionAllocation),4) as nvarchar(max)) as Detail +from [clientob].[FactReimbursementDeptMapping] fct with (readuncommitted) +inner join [ob].[DimOBReimbursementPlan] DB with (readuncommitted) on fct.OBReimbursementPlanID=DB.OBReimbursementPlanID +inner join [fw].[DimDepartment] md with (readuncommitted) on fct.DepartmentID=md.DepartmentID +inner join [ob].[DimDepartmentalBudget] D with (readuncommitted) on md.DepartmentID=D.DepartmentID +inner join [fw].[DimAccount] Dim with (readuncommitted) on fct.AccountID=Dim.AccountID +Group by fct.AccountID, Dim.Name, DB.OBReimbursementPlanID, DB.Name +Having SUM(ProjectionAllocation)<>1 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsReimbursementDataWithoutDimensionMembers +/************************************************************ +** Author: jgerber +** Create Date: 2014-09-18 +** Description: Checks for reimbursement data that does not have dimension members +** Last Modified: 2014-09-18 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +*************************************************************/ + +create view [ob].[viewExceptionsReimbursementDataWithoutDimensionMembers] as + +--***Fact Reimbursement Account********************************************* +-- Reimbursement Plan Dimension + select + Distinct + 0 as OBReimbursementPlanID, + 'Not Specified' as Model, + 'Has Reimbursement Account data for a Reimbursement plan that no longer exists' as Detail + from + [clientob].[FactReimbursementAccount] data with (readuncommitted) + left join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + where + db.MemberGUID is null + +UNION ALL + +-- Account Dimension + select + Distinct + db.OBReimbursementPlanID, + db.Name as Model, + 'Has Reimbursement Account data for an Account that no longer exists' as Detail + from + [clientob].[FactReimbursementAccount] data with (readuncommitted) + inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + left join [fw].[DimAccount] dim with (readuncommitted) on dim.AccountID = data.AccountID + where + dim.MemberGUID is null + +UNION ALL + +-- Patient Reimbursement Group Dimension + select + Distinct + db.OBReimbursementPlanID, + db.Name as Model, + 'Has Reimbursement Account data for a Patient Reimbursement Group that no longer exists' as Detail + from + [clientob].[FactReimbursementAccount] data with (readuncommitted) + inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + left join [fw].[DimPatientReimbursementGroup] dim with (readuncommitted) on dim.PatientReimbursementGroupID = data.PatientReimbursementGroupID + where + dim.MemberGUID is null + +UNION ALL + +--***Fact Reimbursement ********************************************* +-- Reimbursement Plan Dimension + select + Distinct + 0 as OBReimbursementPlanID, + 'Not Specified' as Model, + 'Has Reimbursement data for a Reimbursement plan that no longer exists' as Detail + from + [clientob].[FactReimbursement] data with (readuncommitted) + left join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + where + db.MemberGUID is null + +UNION ALL + +-- Forecast Detail Dimension + select + Distinct + db.OBReimbursementPlanID, + db.Name as Model, + 'Has Reimbursement data for a Forecast Detail that no longer exists' as Detail + from + [clientob].[FactReimbursement] data with (readuncommitted) + inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + left join [ob].[DimOBForecastDetail] dim with (readuncommitted) on dim.OBForecastDetailID = data.OBForecastDetailID + where + dim.MemberGUID is null + +UNION ALL + +-- Patient Reimbursement Group Dimension + select + Distinct + db.OBReimbursementPlanID, + db.Name as Model, + 'Has Reimbursement data for a Patient Reimbursement Group that no longer exists' as Detail + from + [clientob].[FactReimbursement] data with (readuncommitted) + inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + left join [fw].[DimPatientReimbursementGroup] dim with (readuncommitted) on dim.PatientReimbursementGroupID = data.PatientReimbursementGroupID + where + dim.MemberGUID is null + + +UNION ALL + +-- Payor Group Dimension + select + Distinct + db.OBReimbursementPlanID, + db.Name as Model, + 'Has Reimbursement data for a Payor Group that no longer exists' as Detail + from + [clientob].[FactReimbursement] data with (readuncommitted) + inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + left join [fw].[DimPayorGroup] dim with (readuncommitted) on dim.PayorGroupID = data.PayorGroupID + where + dim.MemberGUID is null + +UNION ALL + +-- Payor Dimension + select + Distinct + db.OBReimbursementPlanID, + db.Name as Model, + 'Has Reimbursement data for a Payor that no longer exists' as Detail + from + [clientob].[FactReimbursement] data with (readuncommitted) + inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + left join [fw].[DimPayor] dim with (readuncommitted) on dim.PayorID = data.PayorID + where + dim.MemberGUID is null +GO + + +--------------------------------------------- + +-- ob.viewExceptionsReimbursementDuplicateFillins +/************************************************************ +** Author: blewis +** Create Date: 2015-01-15 +** Description: Finds all duplicate fillins in the Reimbursement model for the Account, Employee, Job Code, and Pay Code Group dimensions +** Last Modified: 2015-01-15 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 +** +*************************************************************/ + + +CREATE view [ob].[viewExceptionsReimbursementDuplicateFillins] as + +--ACCOUNTS +--CHECK IF EXCLUSIVE FILLINS EXIST IN OTHER SECTIONS + +select + DB.OBReimbursementPlanID, + DB.Name as Model, + DIM.Name + ' in section ' + PH.Name + ' is also in another section' as Detail + +from + [ob].[DimOBReimbursementPlan] DB with (readuncommitted) + inner join XPlan X with (readuncommitted) on DB.MemberGUID = X.PlanGUID + inner join data.ScoreFillin_Account FI with (readuncommitted) on DB.MemberGUID = FI.ModelGUID + inner join fw.DimAccount DIM with (readuncommitted) on FI.AccountID = DIM.AccountID + inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID + inner join +( +select + distinct DB.OBReimbursementPlanID, FI1.AccountID +from + [ob].[DimOBReimbursementPlan] DB with (readuncommitted) + inner join XPlan X with (readuncommitted) on DB.MemberGUID = X.PlanGUID + inner join MEPHSection ME with (readuncommitted) on X.ModelTemplateGUID = ME.ModelTemplateGUID + inner join data.ScoreFillin_Account FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID + and ME.PHSectionMemberGUID = FI1.PlaceholderSectionMemberGUID +where + exists (select 1 from data.ScoreFillin_Account FI2 with (readuncommitted) + inner join XPlan X with (readuncommitted) on fi2.modelguid = X.PlanGUID + inner join MEPHSection ME2 with (readuncommitted) on X.ModelTemplateGUID = ME2.ModelTemplateGUID and FI2.PlaceholderSectionMemberGUID=ME2.PHSectionMemberGUID + where FI2.ModelGUID = FI1.ModelGUID and FI2.FillinMemberGUID = FI1.FillinMemberGUID and FI2.FillinGUID != FI1.FillinGUID + and ME2.ExclusivityGroup=me.ExclusivityGroup) + and ME.IsExclusive = 1 +) DUPES + on DB.OBReimbursementPlanID = DUPES.OBReimbursementPlanID + and DIM.AccountID = DUPES.AccountID + and PH.AccountPHID<>0 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsReimbursementEntityAndDepartmentNotEqual +/************************************************************ +** Author: blewis +** Create Date: 2015-01-15 +** Description: Show entities where total reimbursement model deductions dont match the final allocated deductions in Dept +** Last Modified: 2015-01-15 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 +** +*************************************************************/ + +CREATE view [ob].[viewExceptionsReimbursementEntityAndDepartmentNotEqual] as + + +--PROJECTED + +Select + REIMB.OBReimbursementPlanID, + REIMB.Model, + 'Dept Proj. Budget Amt: ' + FORMAT(DEPT.Total, 'C', 'en-us') + + ' Reimb Model Proj. Amt: ' +FORMAT(REIMB.TOTAL, 'C', 'en-us') + + ' Department: ' + REIMB.Dept + ' Account: ' + REIMB.Acct as Detail +FROM + (select + rp.OBReimbursementPlanID, + rp.Name as Model, + db.DepartmentalBudgetID, + ma.AccountID, + SUM(rm.Month01 + rm.Month02 + rm.Month03 + rm.Month04 + rm.Month05 + rm.Month06 + rm.Month07 + rm.Month08 + rm.Month09 + rm.Month10 + rm.Month11 + rm.Month12) as Total, + md.Name as Dept, + ma.Name as Acct + from + [clientob].[viewFactReimbursementMapping] rm + inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on rm.DepartmentalBudgetID=db.DepartmentalBudgetID + inner join [fw].[DimDepartment] md on db.DepartmentID=md.DepartmentID + inner join [fw].[DimAccount] ma with (readuncommitted) on ma.AccountID=rm.AccountID + inner join [ob].[DimOBReimbursementPlan] rp with (readuncommitted) on md.OBReimbursementPlanID=rp.OBReimbursementPlanID + inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on rm.AccountID=sf.AccountID and rp.MemberGUID=sf.ModelGUID + where rm.TimeClassID IN(12) AND rm.FiscalYearID = (select Setting from [dbo].[DBSetting] where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62') + Group by + rp.OBReimbursementPlanID, + db.DepartmentalBudgetID, + ma.AccountID, + rp.Name, + md.Name, + ma.Name) As REIMB +INNER JOIN + (select + rp.OBReimbursementPlanID, + rp.Name as Model, + db.DepartmentalBudgetID, + ma.AccountID, + SUM(rm.Total) as Total, + md.Name as Dept, + ma.Name as Acct + from + [clientob].[FactAccount] rm + inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on rm.DepartmentalBudgetID=db.DepartmentalBudgetID + inner join [fw].[DimDepartment] md on db.DepartmentID=md.DepartmentID + inner join [fw].[DimAccount] ma with (readuncommitted) on ma.AccountID=rm.AccountID + inner join [ob].[DimOBReimbursementPlan] rp with (readuncommitted) on md.OBReimbursementPlanID=rp.OBReimbursementPlanID + inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on rm.AccountID=sf.AccountID and rp.MemberGUID=sf.ModelGUID + where rm.TimeClassID IN(12) AND rm.FiscalYearID = (select Setting from [dbo].[DBSetting] where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62') + Group by + rp.OBReimbursementPlanID, + db.DepartmentalBudgetID, + ma.AccountID, + rp.Name, + md.Name, + ma.Name) AS DEPT +ON REIMB.AccountID=DEPT.AccountID AND REIMB.DepartmentalBudgetID=DEPT.DepartmentalBudgetID +Where ROUND(DEPT.Total,0)<>ROUND(REIMB.Total,0) + +UNION ALL + +--BUDGETED + +Select + REIMB.OBReimbursementPlanID, + REIMB.Model, + 'Dept Budg. Budget Amt: ' + FORMAT(DEPT.Total, 'C', 'en-us') + + ' Reimb Model Budg. Amt: ' +FORMAT(REIMB.TOTAL, 'C', 'en-us') + + ' Department: ' + REIMB.Dept + ' Account: ' + REIMB.Acct as Detail +FROM + (select + rp.OBReimbursementPlanID, + rp.Name as Model, + db.DepartmentalBudgetID, + ma.AccountID, + SUM(rm.Month01 + rm.Month02 + rm.Month03 + rm.Month04 + rm.Month05 + rm.Month06 + rm.Month07 + rm.Month08 + rm.Month09 + rm.Month10 + rm.Month11 + rm.Month12) as Total, + md.Name as Dept, + ma.Name as Acct + from + [clientob].[viewFactReimbursementMapping] rm + inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on rm.DepartmentalBudgetID=db.DepartmentalBudgetID + inner join [fw].[DimDepartment] md on db.DepartmentID=md.DepartmentID + inner join [fw].[DimAccount] ma with (readuncommitted) on ma.AccountID=rm.AccountID + inner join [ob].[DimOBReimbursementPlan] rp with (readuncommitted) on md.OBReimbursementPlanID=rp.OBReimbursementPlanID + inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on rm.AccountID=sf.AccountID and rp.MemberGUID=sf.ModelGUID + where rm.TimeClassID IN(2) AND rm.FiscalYearID = (select Setting + 1 from [dbo].[DBSetting] where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62') + Group by + rp.OBReimbursementPlanID, + db.DepartmentalBudgetID, + ma.AccountID, + rp.Name, + md.Name, + ma.Name) As REIMB +INNER JOIN + (select + rp.OBReimbursementPlanID, + rp.Name as Model, + db.DepartmentalBudgetID, + ma.AccountID, + SUM(rm.Total) as Total, + md.Name as Dept, + ma.Name as Acct + from + [clientob].[FactAccount] rm + inner join [ob].[DimDepartmentalBudget] db with (readuncommitted) on rm.DepartmentalBudgetID=db.DepartmentalBudgetID + inner join [fw].[DimDepartment] md on db.DepartmentID=md.DepartmentID + inner join [fw].[DimAccount] ma with (readuncommitted) on ma.AccountID=rm.AccountID + inner join [ob].[DimOBReimbursementPlan] rp with (readuncommitted) on md.OBReimbursementPlanID=rp.OBReimbursementPlanID + inner join [data].[ScoreFillin_Account] sf with (readuncommitted) on rm.AccountID=sf.AccountID and rp.MemberGUID=sf.ModelGUID + where rm.TimeClassID IN(2) AND rm.FiscalYearID = (select Setting + 1 from [dbo].[DBSetting] where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62') + Group by + rp.OBReimbursementPlanID, + db.DepartmentalBudgetID, + ma.AccountID, + rp.Name, + md.Name, + ma.Name) AS DEPT +ON REIMB.AccountID=DEPT.AccountID AND REIMB.DepartmentalBudgetID=DEPT.DepartmentalBudgetID +Where ROUND(DEPT.Total,0)<>ROUND(REIMB.Total,0) +GO + + +--------------------------------------------- + +-- ob.viewExceptionsReimbursementFillinCacheIssues +/************************************************************ +** Author: blewis +** Create Date: 2015-01-15 +** Description: Checks for fill-ins in Score Fill-ins but not in Cache tables or PH Index doesnt Match +** Last Modified: 2015-01-15 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-02-26 mholov D-03407 Filtering out 'GM Blank' model template +** 2 2016-08-10 kf B-12543 FP - System Center Exception Management - Initial Framework +*************************************************************/ + +CREATE view [ob].[viewExceptionsReimbursementFillinCacheIssues] as +--Fill-ins in Score Fill-ins but not in Cache tables or PH Index doesnt Match + +--Account +select + DB.OBReimbursementPlanID, + DB.Name as Model, + 'The fill-in cache for Account ' + DIM.Name + ' out of sync' as Detail +from + ob.DimOBReimbursementPlan DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join data.ScoreFillin_Account FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join fw.DimAccount DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null +--==================== BEGIN CID 1 ===================== + and db.OBReimbursementPlanID<>0 +--===================== END CID 1 ====================== + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank + + +union all + +--Payor +select + DB.OBReimbursementPlanID, + DB.Name as Model, + 'The fill-in cache for Payor ' + DIM.Name + ' out of sync' as Detail +from + ob.DimOBReimbursementPlan DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join data.ScoreFillin_Payor FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join fw.DimPayor DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null +--==================== BEGIN CID 1 ===================== + and db.OBReimbursementPlanID<>0 +--===================== END CID 1 ====================== + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank + +union all + +--PayorGroup +select + DB.OBReimbursementPlanID, + DB.Name as Model, + 'The fill-in cache for PayorGroup ' + DIM.Name + ' out of sync' as Detail +from + ob.DimOBReimbursementPlan DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join data.ScoreFillin_PayorGroup FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join fw.DimPayorGroup DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null +--==================== BEGIN CID 1 ===================== + and db.OBReimbursementPlanID<>0 +--===================== END CID 1 ====================== + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank + + +union all + +--PatientReimbursementGroup +select + DB.OBReimbursementPlanID, + DB.Name as Model, + 'The fill-in cache for PatientReimbursementGroup ' + DIM.Name + ' out of sync' as Detail +from + ob.DimOBReimbursementPlan DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join data.ScoreFillin_PatientReimbursementGroup FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join fw.DimPatientReimbursementGroup DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null +--==================== BEGIN CID 1 ===================== + and db.OBReimbursementPlanID<>0 +--===================== END CID 1 ====================== + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank + +union all + +--OB Forecast Detail +select + DB.OBReimbursementPlanID, + DB.Name as Model, + 'The fill-in cache for OB Forecast Detail ' + DIM.Name + ' out of sync' as Detail +from + ob.DimOBReimbursementPlan DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join data.ScoreFillin_OBForecastDetail FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join ob.DimOBForecastDetail DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null +--==================== BEGIN CID 1 ===================== + and db.OBReimbursementPlanID<>0 +--===================== END CID 1 ====================== + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank + +union all + +--OB Departmental Budget +select + DB.OBReimbursementPlanID, + DB.Name as Model, + 'The fill-in cache for OB Reimbursement Plan ' + DIM.Name + ' out of sync' as Detail +from + ob.DimOBReimbursementPlan DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join [data].[ScoreFillin_OBReimbursementPlan] FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join ob.DimOBReimbursementPlan DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null +--==================== BEGIN CID 1 ===================== + and db.OBReimbursementPlanID<>0 +--===================== END CID 1 ====================== + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank + +union all + +--Fiscal Year +select + DB.OBReimbursementPlanID, + DB.Name as Model, + 'The fill-in cache for Fiscal Year ' + DIM.Name + ' out of sync' as Detail +from + ob.DimOBReimbursementPlan DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join data.ScoreFillin_FiscalYear FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join fw.DimFiscalYear DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null +--==================== BEGIN CID 1 ===================== + and db.OBReimbursementPlanID<>0 +--===================== END CID 1 ====================== + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank +GO + + +--------------------------------------------- + +-- ob.viewExceptionsReimbursementFillinsExceedingMaxCount +/************************************************************ +** Author: blewis +** Create Date: 2015-01-15 +** Description: Check Max Counts for Reimbursement Model +** Last Modified: 2015-01-15 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 +** +*************************************************************/ + +CREATE view [ob].[viewExceptionsReimbursementFillinsExceedingMaxCount] as + +--ACCOUNT +select + DB.OBReimbursementPlanID, + DB.Name as Model, + 'Has ' + cast((select COUNT(*) from data.ScoreFillin_Account FI with (readuncommitted) inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID where DB.MemberGUID = FI.ModelGUID and PH.Name = SE.GlobalID) as varchar(10)) + + ' Accounts in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail + +from + XPlan X with (readuncommitted) + inner join ob.DimOBReimbursementPlan DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID + inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID + inner join EMFModelTemplateWorksheet WS with (readuncommitted) on MT.ModelTemplateGUID = WS.ModelTemplateGUID + inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID + inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID +where + (select COUNT(*) from data.ScoreFillin_Account FI with (readuncommitted) inner join ob.DimAccountPH PH with (readuncommitted) on FI.AccountPHID = PH.AccountPHID where DB.MemberGUID = FI.ModelGUID and PH.Name = SE.GlobalID) > SE.[Count] + +union all + + +--Payor Group +select + DB.OBReimbursementPlanID, + DB.Name as Model, + 'Has ' + cast((select COUNT(*) from [data].[ScoreFillin_PayorGroup] FI with (readuncommitted) inner join [fw].[DimPayorGroupPH] PH with (readuncommitted) on FI.PayorGroupPHID = PH.PayorGroupPHID where DB.MemberGUID = FI.ModelGUID and PH.Name = SE.GlobalID) as varchar(10)) + + ' Payor Groups in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail +from + XPlan X with (readuncommitted) + inner join ob.DimOBReimbursementPlan DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID + inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID + inner join EMFModelTemplateWorksheet WS with (readuncommitted) on MT.ModelTemplateGUID = WS.ModelTemplateGUID + inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID + inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID +where + (select COUNT(*) from data.ScoreFillin_PayorGroup FI with (readuncommitted) inner join fw.DimPayorGroupPH PH with (readuncommitted) on FI.PayorGroupPHID = PH.PayorGroupPHID where DB.MemberGUID = FI.ModelGUID and PH.Name = SE.GlobalID) > SE.[Count] + +union all + + +--Payor +select + DB.OBReimbursementPlanID, + DB.Name as Model, + 'Has ' + cast((select COUNT(*) from [data].[ScoreFillin_Payor] FI with (readuncommitted) inner join [fw].[DimPayorPH] PH with (readuncommitted) on FI.PayorPHID = PH.PayorPHID where DB.MemberGUID = FI.ModelGUID and PH.Name = SE.GlobalID) as varchar(10)) + + ' Payor in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail +from + XPlan X with (readuncommitted) + inner join ob.DimOBReimbursementPlan DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID + inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID + inner join EMFModelTemplateWorksheet WS with (readuncommitted) on MT.ModelTemplateGUID = WS.ModelTemplateGUID + inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID + inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID +where + (select COUNT(*) from data.ScoreFillin_Payor FI with (readuncommitted) inner join fw.DimPayorPH PH with (readuncommitted) on FI.PayorPHID = PH.PayorPHID where DB.MemberGUID = FI.ModelGUID and PH.Name = SE.GlobalID) > SE.[Count] + + +union all + + +--PatientReimbursementGroup +select + DB.OBReimbursementPlanID, + DB.Name as Model, + 'Has ' + cast((select COUNT(*) from [data].[ScoreFillin_PatientReimbursementGroup] FI with (readuncommitted) inner join [fw].[DimPatientReimbursementGroupPH] PH with (readuncommitted) on FI.PatientReimbursementGroupPHID = PH.PatientReimbursementGroupPHID where DB.MemberGUID = FI.ModelGUID and PH.Name = SE.GlobalID) as varchar(10)) + + ' Patient Reimbursement Group in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail +from + XPlan X with (readuncommitted) + inner join ob.DimOBReimbursementPlan DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID + inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID + inner join EMFModelTemplateWorksheet WS with (readuncommitted) on MT.ModelTemplateGUID = WS.ModelTemplateGUID + inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID + inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID +where + (select COUNT(*) from data.ScoreFillin_PatientReimbursementGroup FI with (readuncommitted) inner join fw.DimPatientReimbursementGroupPH PH with (readuncommitted) on FI.PatientReimbursementGroupPHID = PH.PatientReimbursementGroupPHID where DB.MemberGUID = FI.ModelGUID and PH.Name = SE.GlobalID) > SE.[Count] +GO + + +--------------------------------------------- + +-- ob.viewExceptionsReimbursementInvalidDropdownSelection +/************************************************************ +** Author: blewis +** Create Date: 2015-01-15 +** Description: Finds any text boxes that saved a value of blank that will cause #n/a errors in the model +** Last Modified: 2015-01-15 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 +** +*************************************************************/ + + + +CREATE view [ob].[viewExceptionsReimbursementInvalidDropdownSelection] as +--Accounts +select +Distinct +DB.OBReimbursementPlanID, +DB.Name as Model, +'Account ' + Dim.Name + ' has an invalid drop-down box selection' as Detail +from [clientob].[FactReimbursementAccountVar] fct with (readuncommitted) +inner join ob.DimOBReimbursementPlan DB with (readuncommitted) on fct.OBReimbursementPlanID=db.OBReimbursementPlanID +inner join fw.DimAccount DIM with (readuncommitted) on fct.AccountID = DIM.AccountID +where fct.UnitTypeID=141 +and TextValue_Formula='x' +and TextValue='' + +Union all + + +--Payor +select +Distinct +DB.OBReimbursementPlanID, +DB.Name as Model, +'Account ' + Dim.Name + ' has an invalid drop-down box selection' as Detail +from [clientob].[FactReimbursementVar] fct with (readuncommitted) +inner join ob.DimOBReimbursementPlan DB with (readuncommitted) on fct.OBReimbursementPlanID=db.OBReimbursementPlanID +inner join [fw].[DimPayor] DIM with (readuncommitted) on fct.PayorID = DIM.PayorID +where fct.UnitTypeID=141 +and TextValue_Formula='x' +and TextValue='' + +Union all + +--PayorGroup +select +Distinct +DB.OBReimbursementPlanID, +DB.Name as Model, +'Account ' + Dim.Name + ' has an invalid drop-down box selection' as Detail +from [clientob].[FactReimbursementVar] fct with (readuncommitted) +inner join ob.DimOBReimbursementPlan DB with (readuncommitted) on fct.OBReimbursementPlanID=db.OBReimbursementPlanID +inner join [fw].[DimPayorGroup] DIM with (readuncommitted) on fct.PayorGroupID = DIM.PayorGroupID +where fct.UnitTypeID=141 +and TextValue_Formula='x' +and TextValue='' +GO + + +--------------------------------------------- + +-- ob.viewExceptionsReimbursementMissingDepartmentAllocations +CREATE VIEW [ob].[viewExceptionsReimbursementMissingDepartmentAllocations] AS +/************************************************************ +** Author: blewis +** Create Date: 2015-01-15 +** Description: Checks for departments mapped to a reimbursement model with no rows in the allocation table +** Last Modified: 2017-08-22 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 +** 2 08/22/2017 AI/cbb D5967 added fiscal year and timeclass filters +*************************************************************/ + + SELECT DISTINCT + rp.OBReimbursementPlanID, + rp.NAME AS Model, + 'Department missing From Reimbursement Allocation: ' + db.NAME AS Detail + FROM [clientob].[FactAccount] fa WITH (READUNCOMMITTED) + INNER JOIN [ob].[DimDepartmentalBudget] db WITH (READUNCOMMITTED) ON fa.DepartmentalBudgetID = db.DepartmentalBudgetID + INNER JOIN [fw].[DimDepartment] md WITH (READUNCOMMITTED) ON md.DepartmentID = db.DepartmentID + INNER JOIN [ob].[DimOBReimbursementPlan] rp WITH (READUNCOMMITTED) ON rp.OBReimbursementPlanID = md.OBReimbursementPlanID + INNER JOIN [data].[ScoreFillin_Account] ma WITH (READUNCOMMITTED) ON fa.AccountID = ma.AccountID AND db.MemberGUID = ma.ModelGUID + WHERE 1=1 + and md.OBReimbursementPlanID <> 0 + AND fa.Total <> 0 +-- CID 2 begin + AND fa.FiscalYearID = (Select Setting from [dbo].[DBSetting] where Name = 'OB_Current_Year') + and fa.TimeClassID = 1 +-- CID 2 end + AND ma.AccountPHID IN ( + 4 --Deductions + ,484 --Deductions - Charity and Bad Debt + ,481 --Deductions - Reimbursement + ) + AND NOT EXISTS ( + SELECT 1 + FROM [clientob].[FactReimbursementDeptMapping] FI WITH (READUNCOMMITTED) + WHERE FI.DepartmentID = DB.DepartmentID + AND FI.OBReimbursementPlanID = rp.OBReimbursementPlanID + ) +GO + + +--------------------------------------------- + +-- ob.viewExceptionsReimbursementMissingNotSpecifiedFillins +/************************************************************ +** Author: blewis +** Create Date: 2015-01-15 +** Description: Finds missing not specified fill-ins for the Reimbursement Model +** Last Modified: 2015-01-15 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-08-10 kf B-12543 FP - System Center Exception Management - Initial Framework +*************************************************************/ + +CREATE view [ob].[viewExceptionsReimbursementMissingNotSpecifiedFillins] as +select + DB.OBReimbursementPlanID, + DB.Name as Model, + 'Is Missing the Not Specified Payor Fill-in' as Detail +from + ob.DimOBReimbursementPlan DB with (readuncommitted) +where + not exists(select 1 from [data].[ScoreFillin_Payor] FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.PayorID = 0 and FI.PayorPHID = 0) + and DB.OBReimbursementPlanID != 0 + +union all + +select + DB.OBReimbursementPlanID, + DB.Name as Model, + 'Is Missing the Not Specified Payor Group Fill-in' as Detail +from + ob.DimOBReimbursementPlan DB with (readuncommitted) +where + not exists(select 1 from [data].[ScoreFillin_PayorGroup] FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.PayorGroupID = 0 and FI.PayorGroupPHID = 0) + and DB.OBReimbursementPlanID != 0 + +union all + +select + DB.OBReimbursementPlanID, + DB.Name as Model, + 'Is Missing the Not Specified Patient Reimbursement Group Fill-in' as Detail +from + ob.DimOBReimbursementPlan DB with (readuncommitted) +where + not exists(select 1 from [data].[ScoreFillin_PatientReimbursementGroup] FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.PatientReimbursementGroupID = 0 and FI.PatientReimbursementGroupPHID = 0) + and DB.OBReimbursementPlanID != 0 + +union all + +select + DB.OBReimbursementPlanID, + DB.Name as Model, + 'Is Missing the Not Specified OB Forecast Detail Fill-in' as Detail +from + ob.DimOBReimbursementPlan DB with (readuncommitted) +where + not exists(select 1 from [data].[ScoreFillin_OBForecastDetail] FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.OBForecastDetailID = 0 and FI.OBForecastDetailPHID = 0) + and DB.OBReimbursementPlanID != 0 + +union all + +select + DB.OBReimbursementPlanID, + DB.Name as Model, + 'Is Missing the Not Specified Account Fill-in' as Detail +from + ob.DimOBReimbursementPlan DB with (readuncommitted) +where + not exists(select 1 from [data].[ScoreFillin_Account] FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.AccountID = 0 and FI.AccountPHID = 0) + and DB.OBReimbursementPlanID != 0 + +union all + +select + DB.OBReimbursementPlanID, + DB.Name as Model, + 'Is Missing the Not Specified Fiscal Year Fill-in' as Detail +from + ob.DimOBReimbursementPlan DB with (readuncommitted) +where + not exists(select 1 from [data].[ScoreFillin_FiscalYear] FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.FiscalYearID = 0 and FI.FiscalYearPHID = 0) + and DB.OBReimbursementPlanID != 0 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsReimbursementMissingSelfFillin +/************************************************************ +** Author: blewis +** Create Date: 2015-01-15 +** Description: Displays any Reimbusrement Budgets that are missing their self fill-in +** Last Modified: 2015-01-15 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-08-10 kf B-12543 FP - System Center Exception Management - Initial Framework +*************************************************************/ + +CREATE view [ob].[viewExceptionsReimbursementMissingSelfFillin] as + +select +Distinct +DB.OBReimbursementPlanID, +DB.Name as Model, +'Reimbursement Budget ' + db.Name + ' is missing the self-fill-in' as Detail +from ob.DimOBReimbursementPlan DB with (readuncommitted) +left outer join [data].[ScoreFillin_OBReimbursementPlan] sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and PlaceholderSectionMemberGUID='4f0371d7-3d03-4320-9d83-413eb6105076' +where sf.FillinGUID is null +and db.OBReimbursementPlanID<>0 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsReimbursementOrphanedData +/************************************************************************************************************************************************** +** Author: blewis +** Create Date: 2015-01-15 +** Description: Check For Non Zero Data that will not show in model because a fillin is missing +** Last Modified: 2017-01-12 +** GM Release: 2015.2 +**************************************************************************************************************************************************** +** Change History +**************************************************************************************************************************************************** +** CID Date Author WI Description +** 1 2017-01-12 srk D-05196 Exception will only display missing dollar accounts because not all volume accounts need to be filled in +** +***************************************************************************************************************************************************/ + +CREATE view [ob].[viewExceptionsReimbursementOrphanedData] as + +-- Account data + select + Distinct + db.OBReimbursementPlanID, + db.Name as Model, + 'Has data in Account ' + dim.Name+ ' but it is not filled in' as Detail + from + [clientob].[FactReimbursementAccount] data with (readuncommitted) + inner join ob.DimOBReimbursementPlan db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + inner join fw.DimAccount dim with (readuncommitted) on dim.AccountID = data.AccountID + left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID + and sf.PlaceholderSectionMemberGUID<>'77A0029B-F072-4ED6-8BFC-89BCFD6ED049' --not specified + where + sf.FillinGUID is null + and data.Total <> 0 + and data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') + and db.OBReimbursementPlanID<>0 + and dim.AccountID<>0 + and data.UnitTypeID = 34 -- Only Dollars + +UNION ALL + +-- OB Forecast Detail + select + Distinct + db.OBReimbursementPlanID, + db.Name as Model, + 'Has data in for OB Forecast Detail Member ' + dim.Name+ ' but it is not filled in' as Detail + from + [clientob].[FactReimbursement] data with (readuncommitted) + inner join ob.DimOBReimbursementPlan db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + inner join [ob].[DimOBForecastDetail] dim with (readuncommitted) on dim.OBForecastDetailID = data.OBForecastDetailID + left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID + and sf.PlaceholderSectionMemberGUID<>'45ef7590-f41c-4ea6-911e-03fe33a4e09f' --not specified + where + sf.FillinGUID is null + and data.Total <> 0 and data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') + and data.TimeClassID = 1 + and db.OBReimbursementPlanID<>0 + and dim.OBForecastDetailID<>0 + +UNION ALL + +-- Payor Group + select + Distinct + db.OBReimbursementPlanID, + db.Name as Model, + 'Has data in for Payor Group ' + dim.Name+ ' but it is not filled in' as Detail + from + [clientob].[FactReimbursement] data with (readuncommitted) + inner join ob.DimOBReimbursementPlan db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + inner join [fw].[DimPayorGroup] dim with (readuncommitted) on dim.PayorGroupID = data.PayorGroupID + left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID + and sf.PlaceholderSectionMemberGUID<>'2d36244f-b97e-4787-99bd-2d75a499c4d8' --not specified + where + sf.FillinGUID is null + and data.Total <> 0 + and data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') + and data.TimeClassID = 1 + and db.OBReimbursementPlanID<>0 + and dim.PayorGroupID<>0 + +UNION ALL + +-- Payor + select + Distinct + db.OBReimbursementPlanID, + db.Name as Model, + 'Has data in for Payor ' + dim.Name+ ' but it is not filled in' as Detail + from + [clientob].[FactReimbursement] data with (readuncommitted) + inner join ob.DimOBReimbursementPlan db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + inner join [fw].[DimPayor] dim with (readuncommitted) on dim.PayorID = data.PayorID + left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID + and sf.PlaceholderSectionMemberGUID<>'00000000-0000-0000-0000-000000000000' --not specified + where + sf.FillinGUID is null + and data.Total <> 0 + and data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') + and data.TimeClassID = 1 + and db.OBReimbursementPlanID<>0 + and dim.PayorID<>0 + +UNION ALL + +-- PatientReimbursementGroup + select + Distinct + db.OBReimbursementPlanID, + db.Name as Model, + 'Has data in for Patient Reimbursement Group ' + dim.Name+ ' but it is not filled in' as Detail + from + [clientob].[FactReimbursement] data with (readuncommitted) + inner join ob.DimOBReimbursementPlan db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + inner join [fw].[DimPatientReimbursementGroup] dim with (readuncommitted) on dim.PatientReimbursementGroupID = data.PatientReimbursementGroupID + left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID + and sf.PlaceholderSectionMemberGUID<>'00000000-0000-0000-0000-000000000000' --not specified + where + sf.FillinGUID is null + and data.Total <> 0 + and data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') + and data.TimeClassID = 1 + and db.OBReimbursementPlanID<>0 + and dim.PatientReimbursementGroupID<>0 + +UNION ALL + +-- PatientReimbursementGroup + select + Distinct + db.OBReimbursementPlanID, + db.Name as Model, + 'Has data in for Patient Reimbursement Group ' + dim.Name+ ' but it is not filled in' as Detail + from + [clientob].[FactReimbursementAccount] data with (readuncommitted) + inner join ob.DimOBReimbursementPlan db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + inner join [fw].[DimPatientReimbursementGroup] dim with (readuncommitted) on dim.PatientReimbursementGroupID = data.PatientReimbursementGroupID + left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID + and sf.PlaceholderSectionMemberGUID<>'00000000-0000-0000-0000-000000000000' --not specified + where + sf.FillinGUID is null + and data.Total <> 0 + and data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') + and data.TimeClassID = 1 + and db.OBReimbursementPlanID<>0 + and dim.PatientReimbursementGroupID<>0 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsReimbursementProjectedEqualYTD +/************************************************************ +** Author: blewis +** Create Date: 2015-01-15 +** Description: Compares Projected total and YTD to determine of the anything is being projected in the non-closed months, indicates potential errors +** Last Modified: 2015-01-15 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 +** +*************************************************************/ + +CREATE view [ob].[viewExceptionsReimbursementProjectedEqualYTD] as + + +-- Account Data +select +Distinct +DB.OBReimbursementPlanID, +DB.Name as Model, +'Has projected = YTD for Account: ' + Dim.Name + ' in section ' + PH.Name as Detail +from [clientob].[FactReimbursementAccount] fct with (readuncommitted) +inner join ob.DimOBReimbursementPlan db with (readuncommitted) on db.OBReimbursementPlanID=fct.OBReimbursementPlanID +inner join fw.DimAccount DIM with (readuncommitted) on fct.AccountID = DIM.AccountID +inner join data.ScoreFillin_Account SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + and dim.MemberGUID=sf.FillinMemberGUID +inner join ob.DimAccountPH PH with (readuncommitted) on SF.PlaceholderSectionMemberGUID= PH.MemberGUID +where fct.datatypeid=3 +and fct.YTD=fct.Total +and fct.TimeClassID=12 +and fct.Total<>0 +and fct.MonthsLoaded<>12 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsRosterBudgetDataNotInModel +CREATE VIEW ob.viewExceptionsRosterBudgetDataNotInModel +AS +/**************************************************************************************************** +** Author: cbecker +** Create Date: 2017-01-23 +** Description: Checks for data imported from roster budgeting with no fixed staffing fill-in +** Last Modified: 2017-01-23 +** GM Release: 2017.1.2 +**************************************************************************************************** +** Change History +**************************************************************************************************** +** CID Date Author WI Description +** +****************************************************************************************************/ +select distinct + DepartmentCode = ddb.DepartmentCode, + DepartmentalBudgetID = ddb.DepartmentalBudgetID, + DepartmentalBudget = ddb.Name, + JobCodeID = djc.JobCodeID, + JobCode = djc.Name, + Detail = case + when ddb.DepartmentalBudgetID is null + then 'Departmental Budget does not exist' + when ddb.OBActivePlans = 0 + then 'Departmental Budget has not been activated' + when djc.JobCodeID is null + then 'Job code does not exist' + when sf.PlaceholderSectionMemberGUID is null + then 'Job code does not exist in this model' + else 'Job code is in the wrong section' + end +from [fp].[RosterBudgetBasisResult] rb + inner join [fp].[BudgetConfig] bc + on rb.BudgetConfigGUID = bc.BudgetConfigGUID + left join [ob].[DimDepartmentalBudget] ddb + on rb.DepartmentID = ddb.DepartmentID + left join [fw].[DimJobCode] djc + on rb.JobCodeID = djc.JobCodeID + left join [fw].[DimPayCodeGroup] dpcg + on rb.PayCodeGroupID = dpcg.PayCodeGroupID + left join [data].[ScoreFillin_JobCode] sf + on djc.MemberGUID = sf.FillinMemberGUID + and ddb.MemberGUID = sf.ModelGUID + left join [clientob].[FactStaffingPCNonReporting] fct + on ddb.DepartmentalBudgetID = fct.DepartmentalBudgetID + and djc.JobCodeID = fct.JobCodeID + and dpcg.PayCodeGroupID = fct.PayCodeGroupID + and bc.FiscalYearID = fct.FiscalYearID +where 1=1 + and fct.RowID is null + and bc.IsActive = 1 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsServiceLineDataWithoutDimensionMembers +/************************************************************ +** Author: jgerber +** Create Date: 2014-09-18 +** Description: Checks for SL data that does not have dimension members +** Last Modified: 2014-09-18 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +*************************************************************/ + +create view [ob].[viewExceptionsServiceLineDataWithoutDimensionMembers] as + +--***Fact Service Line********************************************* +-- Service Line Plan Dimension + select + Distinct + 0 as OBServiceLinePlanID, + 'Not Specified' as Model, + 'Has Service Line data for a Service Line plan that no longer exists' as Detail + from + [clientob].[FactServiceLine] data with (readuncommitted) + left join [ob].[DimOBServiceLinePlan] db with (readuncommitted) on db.OBServiceLinePlanID = data.OBServiceLinePlanID + where + db.MemberGUID is null + +UNION ALL + +-- Modeling Service Line Dimension + select + Distinct + db.OBServiceLinePlanID, + db.Name as Model, + 'Has Service Line data for a Modeling Service Line that no longer exists' as Detail + from + [clientob].[FactServiceLine] data with (readuncommitted) + inner join [ob].[DimOBServiceLinePlan] db with (readuncommitted) on db.OBServiceLinePlanID = data.OBServiceLinePlanID + left join [fw].[DimModelingServiceLine] dim with (readuncommitted) on dim.ModelingServiceLineID = data.ModelingServiceLineID + where + dim.MemberGUID is null + +UNION ALL + +-- Forecast Detail Dimension + select + Distinct + db.OBServiceLinePlanID, + db.Name as Model, + 'Has Service Line data for a Forecast Detail that no longer exists' as Detail + from + [clientob].[FactServiceLine] data with (readuncommitted) + inner join [ob].[DimOBServiceLinePlan] db with (readuncommitted) on db.OBServiceLinePlanID = data.OBServiceLinePlanID + left join [ob].[DimOBForecastDetail] dim with (readuncommitted) on dim.OBForecastDetailID = data.OBForecastDetailID + where + dim.MemberGUID is null +GO + + +--------------------------------------------- + +-- ob.viewExceptionsServiceLineDuplicateFillins +/************************************************************ +** Author: cbecker +** Create Date: 2015-01-18 +** Description: Finds all duplicate fillins in the OB Service Line model +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + +CREATE VIEW [ob].[viewExceptionsServiceLineDuplicateFillins] as + +--Modeling Service Line + +select + DB.OBServiceLinePlanID + ,DB.Name as Model + ,DIM.Name + ' in section ' + PH.Name + ' is also in another section' as Detail +from + [ob].[DimOBServiceLinePlan] DB with (readuncommitted) + inner join [data].[ScoreFillin_ModelingServiceLine] FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID + inner join [fw].[DimModelingServiceLinePH] PH with (readuncommitted) on FI1.ModelingServiceLinePHID = PH.ModelingServiceLinePHID + inner join [fw].[DimModelingServiceLine] DIM with (readuncommitted) on FI1.ModelingServiceLineID = DIM.ModelingServiceLineID +where exists +(select 1 +from + [data].[ScoreFillin_ModelingServiceLine] FI2 with (readuncommitted) +where + FI1.ModelGUID = FI2.ModelGUID + and FI1.ModelingServiceLineID = FI2.ModelingServiceLineID + and FI1.ModelingServiceLinePHID != FI2.ModelingServiceLinePHID +) +and PH.ModelingServiceLinePHID<>0 + +union all + +--Service Line Rollup + +select + DB.OBServiceLinePlanID, + DB.Name as Model, + DIM.Name + ' in section ' + PH.Name + ' is also in another section' as Detail +from + [ob].[DimOBServiceLinePlan] DB with (readuncommitted) + inner join [data].[ScoreFillin_ServiceLineRollup] FI1 with (readuncommitted) on DB.MemberGUID = FI1.ModelGUID + inner join [fw].[DimServiceLineRollupPH] PH with (readuncommitted) on FI1.ServiceLineRollupPHID = PH.ServiceLineRollupPHID + inner join [fw].[DimServiceLineRollup] DIM with (readuncommitted) on FI1.ServiceLineRollupID = DIM.ServiceLineRollupID +where exists +(select 1 +from + [data].[ScoreFillin_ServiceLineRollup] FI2 with (readuncommitted) +where + FI1.ModelGUID = FI2.ModelGUID + and FI1.ServiceLineRollupID = FI2.ServiceLineRollupID + and FI1.ServiceLineRollupPHID != FI2.ServiceLineRollupPHID +) +and PH.ServiceLineRollupPHID<>0 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsServiceLineFillinCacheIssues +/************************************************************ +** Author: cbecker +** Create Date: 2015-01-18 +** Description: Checks for fill-ins in Score Fill-ins but not in Cache tables or PH Index doesnt Match +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-02-26 mholov D-03407 Filtering out 'GM Blank' model template +** 2 2016-08-10 kf B-12543 FP - System Center Exception Management - Initial Framework +*************************************************************/ + +CREATE view [ob].[viewExceptionsServiceLineFillinCacheIssues] as +--Fill-ins in Score Fill-ins but not in Cache tables or PH Index doesnt Match + +--Modeling service line +select + DB.OBServiceLinePlanID, + DB.Name as Model, + 'The fill-in cache for Account ' + DIM.Name + ' out of sync' as Detail +from + [ob].[DimOBServiceLinePlan] DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join [data].[ScoreFillin_ModelingServiceLine] FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join [fw].[DimModelingServiceLine] DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null + and db.OBServiceLinePlanID<>0 + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank + +UNION ALL + +--Service line Rollup +select + DB.OBServiceLinePlanID, + DB.Name as Model, + 'The fill-in cache for Service Line Rollup ' + DIM.Name + ' out of sync' as Detail +from + [ob].[DimOBServiceLinePlan] DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join [data].[ScoreFillin_ServiceLineRollup] FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join [fw].[DimServiceLineRollup] DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null + and db.OBServiceLinePlanID<>0 + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank + + +UNION ALL + +--Fiscal Year +select + DB.OBServiceLinePlanID, + DB.Name as Model, + 'The fill-in cache for Fiscal Year ' + DIM.Name + ' out of sync' as Detail +from + [ob].[DimOBServiceLinePlan] DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join data.ScoreFillin_FiscalYear FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join fw.DimFiscalYear DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null + and db.OBServiceLinePlanID<>0 + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank + + UNION ALL + + --OBForecast Detail + +select + DB.OBServiceLinePlanID, + DB.Name as Model, + 'The fill-in cache for Forecast Detail ' --+ DIM.Name + ' out of sync' as Detail +from + [ob].[DimOBServiceLinePlan] DB with (readuncommitted) + inner join ScoreFillin SF with (readuncommitted) on DB.MemberGUID = SF.ModelGUID + left join [data].[ScoreFillin_OBForecastDetail] FI with (readuncommitted) on SF.ModelGUID = FI.ModelGUID + and sf.PlaceholderSectionMemberGUID=fi.PlaceholderSectionMemberGUID + and sf.FillinMemberGUID=FI.FillinMemberGUID + and sf.PlaceholderIndex=FI.PlaceholderIndex + inner join [ob].[DimOBForecastDetail] DIM with (readuncommitted) on SF.FillinMemberGUID = DIM.MemberGUID + inner join XPlan P on DB.MemberGUID = P.PlanGUID + where FI.FillinMemberGUID is null + and db.OBServiceLinePlanID<>0 + and P.ModelTemplateGUID <> '7F792F1F-F32A-4053-9907-534A2D736D45'--GM Blank +GO + + +--------------------------------------------- + +-- ob.viewExceptionsServiceLineFillinsExceedingMaxCount +/************************************************************ +** Author: cbecker +** Create Date: 2015-01-18 +** Description: Checks fillin counts > expansion count in the OB Service Line model +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + +CREATE view [ob].[viewExceptionsServiceLineFillinsExceedingMaxCount] as + +select + DB.OBServiceLinePlanID + ,DB.Name as Model + ,'Has ' + cast((select COUNT(*) from [data].[ScoreFillin_ModelingServiceLine] FI with (readuncommitted) inner join [fw].[DimModelingServiceLinePH] PH with (readuncommitted) on FI.ModelingServiceLinePHID = PH.ModelingServiceLinePHID where DB.MemberGUID = FI.ModelGUID and PH.Name = SE.GlobalID) as varchar(10)) + + ' Service Lines in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail + +from + XPlan X with (readuncommitted) + inner join [ob].[DimOBServiceLinePlan] DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID + inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID + inner join EMFModelTemplateWorksheet WS with (readuncommitted) on MT.ModelTemplateGUID = WS.ModelTemplateGUID + inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID + inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID +where + (select COUNT(*) from [data].[ScoreFillin_ModelingServiceLine] FI with (readuncommitted) inner join [fw].[DimModelingServiceLinePH] PH with (readuncommitted) on FI.ModelingServiceLinePHID = PH.ModelingServiceLinePHID where DB.MemberGUID = FI.ModelGUID and PH.Name = SE.GlobalID) > SE.[Count] + +Union all + +select + DB.OBServiceLinePlanID + ,DB.Name as Model + ,'Has ' + cast((select COUNT(*) from [data].[ScoreFillin_ServiceLineRollup] FI with (readuncommitted) inner join [fw].[DimServiceLineRollupPH] PH with (readuncommitted) on FI.ServiceLineRollupPHID = PH.ServiceLineRollupPHID where DB.MemberGUID = FI.ModelGUID and PH.Name = SE.GlobalID) as varchar(10)) + + ' Service Line Rollups in section ' + SE.GlobalID + ' with maximum ' + cast(SE.[Count] as varchar(10)) as Detail + +from + XPlan X with (readuncommitted) + inner join [ob].[DimOBServiceLinePlan] DB with (readuncommitted) on X.PlanGUID = DB.MemberGUID + inner join EMFModelTemplate MT with (readuncommitted) on X.ModelTemplateGUID = MT.ModelTemplateGUID + inner join EMFModelTemplateWorksheet WS with (readuncommitted) on MT.ModelTemplateGUID = WS.ModelTemplateGUID + inner join MEExcelCell EC with (readuncommitted) on WS.WorksheetGUID = EC.ExcelSheetGUID + inner join MEScoreExpansion SE with (readuncommitted) on EC.ExcelCellGUID = SE.ExcelCellGUID +where + (select COUNT(*) from [data].[ScoreFillin_ServiceLineRollup] FI with (readuncommitted) inner join [fw].[DimServiceLineRollupPH] PH with (readuncommitted) on FI.ServiceLineRollupPHID = PH.ServiceLineRollupPHID where DB.MemberGUID = FI.ModelGUID and PH.Name = SE.GlobalID) > SE.[Count] +GO + + +--------------------------------------------- + +-- ob.viewExceptionsServiceLineInvalidDropdownSelection +/************************************************************ +** Author: cbecker +** Create Date: 2015-01-18 +** Description: Finds any text boxes that saved a value of blank that will cause #n/a errors in the model +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + +Create view [ob].[viewExceptionsServiceLineInvalidDropdownSelection] as +--Service Line +select Distinct + DB.OBServiceLinePlanID + ,DB.Name as Model + ,'Service Line ' + Dim.Name + ' has an invalid drop-down box selection' as Detail +from + [clientob].[FactServiceLineVar] fct with (readuncommitted) + inner join [ob].[DimOBServiceLinePlan] DB with (readuncommitted) on fct.OBServiceLinePlanID=db.OBServiceLinePlanID + inner join [fw].[DimModelingServiceLine] DIM with (readuncommitted) on fct.ModelingServiceLineID = DIM.ModelingServiceLineID +where + fct.UnitTypeID=141 + and TextValue_Formula='x' + and TextValue='' + +Union all + +--Service Line Rollup +select Distinct + DB.OBServiceLinePlanID + ,DB.Name as Model + ,'Service Line Rollup ' + Dim.Name + ' has an invalid drop-down box selection' as Detail +from + [clientob].[FactServiceLineRollupVar] fct with (readuncommitted) + inner join [ob].[DimOBServiceLinePlan] DB with (readuncommitted) on fct.OBServiceLinePlanID=db.OBServiceLinePlanID + inner join [fw].[DimServiceLineRollup] DIM with (readuncommitted) on fct.ServiceLineRollupID = DIM.ServiceLineRollupID +where + fct.UnitTypeID=141 + and TextValue_Formula='x' + and TextValue='' +GO + + +--------------------------------------------- + +-- ob.viewExceptionsServiceLineMissingNotSpecifiedFillins +/************************************************************ +** Author: cbecker +** Create Date: 2015-01-18 +** Description: Finds all missing not specified fillins in the OB Service Line model +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + +CREATE view [ob].[viewExceptionsServiceLineMissingNotSpecifiedFillins] +AS + +--Service Line + +select + DB.OBServiceLinePlanID, + DB.Name as Model, + 'Is Missing the Not Specified Service line' as Detail +from + [ob].[DimOBServiceLinePlan] DB with (readuncommitted) +where + not exists(select 1 from [data].[ScoreFillin_ModelingServiceLine] FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.ModelingServiceLineID = 0 and FI.ModelingServiceLinePHID = 0) + and DB.OBServiceLinePlanID != 0 --and db.obactiveplans=1 + +Union all + +--Service Line Rollup + +select + DB.OBServiceLinePlanID, + DB.Name as Model, + 'Is Missing the Not Specified Service Line Rollup' as Detail +from + [ob].[DimOBServiceLinePlan] DB with (readuncommitted) +where + not exists(select 1 from [data].[ScoreFillin_ServiceLineRollup] FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.ServiceLineRollupID = 0 and FI.ServiceLineRollupPHID = 0) + and DB.OBServiceLinePlanID != 0 --and db.obactiveplans=1 + + +Union all + +--OBForecastDetail + +select + DB.OBServiceLinePlanID, + DB.Name as Model, + 'Is Missing the Not Specified OB Forecast Detail' as Detail +from + [ob].[DimOBServiceLinePlan] DB with (readuncommitted) +where + not exists(select 1 from [data].[ScoreFillin_OBForecastDetail] FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.OBForecastDetailID = 0 and FI.OBForecastDetailPHID = 0) + and DB.OBServiceLinePlanID != 0 --and db.obactiveplans=1 + +Union all + + +--Fiscal Year + +select + DB.OBServiceLinePlanID, + DB.Name as Model, + 'Is Missing the Not Specified Fiscal Year' as Detail +from + [ob].[DimOBServiceLinePlan] DB with (readuncommitted) +where + not exists(select 1 from [data].[ScoreFillin_FiscalYear] FI with (readuncommitted) where FI.ModelGUID = DB.MemberGUID and FI.FiscalYearID = 0 and FI.FiscalYearPHID = 0) + and DB.OBServiceLinePlanID != 0 --and db.obactiveplans=1 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsServiceLineMissingSelfFillin +/************************************************************ +** Author: cbecker +** Create Date: 2015-01-18 +** Description: Displays any service line models that are missing their self fill-in +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-08-10 kf B-12543 FP - System Center Exception Management - Initial Framework +*************************************************************/ + +CREATE view [ob].[viewExceptionsServiceLineMissingSelfFillin] as + +--Modeling service line +select +Distinct + DB.OBServiceLinePlanID + ,DB.Name as Model + ,'Service line plan ' + db.Name + ' is missing the self-fill-in' as Detail +from + [ob].[DimOBServiceLinePlan] DB with (readuncommitted) + left outer join [data].[ScoreFillin_OBServiceLinePlan] sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and PlaceholderSectionMemberGUID='811d09b3-431a-42f3-80d2-f100e27a1fdb' +where + sf.FillinGUID is null + and db.OBServiceLinePlanID<>0 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsServiceLineOrphanedData +/************************************************************ +** Author: cbecker +** Create Date: 2015-01-18 +** Description: Checks for nonzero data that will not show up in the model because a fillin is missing +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + +CREATE view [ob].[viewExceptionsServiceLineOrphanedData] as + +-- Service line +select +Distinct + db.OBServiceLinePlanID + , db.Name as Model + ,'Has data in Service Line ' + dim.Name+ ' but it is not filled in' as Detail +from + [clientob].[FactServiceLine] data with (readuncommitted) + inner join [ob].[DimOBServiceLinePlan] db with (readuncommitted) on db.OBServiceLinePlanID = data.OBServiceLinePlanID + inner join [fw].[DimModelingServiceLine] dim with (readuncommitted) on dim.ModelingServiceLineID = data.ModelingServiceLineID + left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID + and sf.PlaceholderSectionMemberGUID<>'d357335b-692a-4149-9d0b-f4fb231536c8' --not specified +where + sf.FillinGUID is null + and data.Total <> 0 and data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') + and db.OBServiceLinePlanID<>0 + and dim.ModelingServiceLineID<>0 + +UNION ALL + +-- Service line Rollup +select +Distinct + db.OBServiceLinePlanID + , db.Name as Model + ,'Has data in Service Line ' + dim.Name+ ' but it is not filled in' as Detail +from + [clientob].[FactServiceLineRollupVar] data with (readuncommitted) + inner join [ob].[DimOBServiceLinePlan] db with (readuncommitted) on db.OBServiceLinePlanID = data.OBServiceLinePlanID + inner join [fw].[DimServiceLineRollup] dim with (readuncommitted) on dim.ServiceLineRollupID = data.ServiceLineRollupID + left outer join ScoreFillin sf with (readuncommitted) on db.MemberGUID=sf.ModelGUID and dim.MemberGUID=sf.FillinMemberGUID + and sf.PlaceholderSectionMemberGUID<>'10802ab1-b116-48b5-a280-2b42083ab7bb' --not specified +where + sf.FillinGUID is null + and data.FiscalYearID>= (select s.setting-1 from [dbo].[DBSetting] s where Name = 'OB_Current_Year') + and db.OBServiceLinePlanID<>0 + and dim.ServiceLineRollupID<>0 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsServiceLineProjectedEqualYTD +/************************************************************ +** Author: cbecker +** Create Date: 2015-01-18 +** Description: Compares Projected total and YTD to determine if anything is being projected in the non-closed months, indicates potential errors +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + +Create view [ob].[viewExceptionsServiceLineProjectedEqualYTD] as + +select Distinct + DB.OBServiceLinePlanID + ,DB.Name as Model + ,'Has projected = YTD for Service Line: ' + Dim.ServiceLine + ' - ' + dim.MedicalSurgical + ' - ' + dim.AgeCohort + ' in section ' + dim.PatientClass as Detail +from + [clientob].[FactServiceLine] fct with (readuncommitted) + inner join [ob].[DimOBServiceLinePlan] db with (readuncommitted) on db.OBServiceLinePlanID=fct.OBServiceLinePlanID + inner join [fw].[DimModelingServiceLine] DIM with (readuncommitted) on fct.ModelingServiceLineID = DIM.ModelingServiceLineID +where + fct.datatypeid=3 + and fct.YTD=fct.Total + and fct.TimeClassID=12 + and fct.Total<>0 +GO + + +--------------------------------------------- + +-- ob.viewExceptionsServiceLineServiceLinesNotBudgeted +/************************************************************ +** Author: cbecker +** Create Date: 2015-01-18 +** Description: Service Lines without a Budget +** Last Modified: 2015-01-18 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + +Create view ob.viewExceptionsServiceLineServiceLinesNotBudgeted +as + +select + db.OBServiceLinePlanID + ,db.Name as Model + ,'Has '+cast(cast(Sum(Total) as decimal(16,2)) as nvarchar(100))+' current year '+ut.Name+' for Service Line '+acc.Name+' but does not have a budget' as Detail + +from [clientob].[FactServiceLine] fa +inner join [fw].[DimUnitType] ut on fa.UnitTypeID=ut.UnitTypeID +inner join [fw].[DimModelingServiceLine] acc on acc.ModelingServiceLineID=fa.ModelingServiceLineID +inner join [ob].[DimOBServiceLinePlan] db on db.OBServiceLinePlanID=fa.OBServiceLinePlanID +where + FiscalYearID = (select Setting from [dbo].[DBSetting] where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62') + and TimeClassID=1 + and Total<>0 + and acc.ModelingServiceLineID<>0 + and fa.OBServiceLinePlanID<>0 + --and not (acc.OBIsDefined=1 and acc.OBAccountPHID=0 and acc.OBStatModelSectionID=0) + and ut.UnitTypeID in (34,51,140) --Dollars, Volume, and Hours (contract labor) + and not exists + (select + 1 + from + [clientob].[FactServiceLine] fa2 + where + FiscalYearID = (select Setting+1 from [dbo].[DBSetting] where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62') + and TimeClassID=2 + and Total<>0 + and fa2.OBServiceLinePlanID=fa.OBServiceLinePlanID + and fa2.ModelingServiceLineID=fa.ModelingServiceLineID + and fa2.UnitTypeID=fa.UnitTypeID) +group by + db.OBServiceLinePlanID + ,db.Name + ,ut.Name + ,acc.Name +GO + + +--------------------------------------------- + +-- ob.viewFactDepartmentPrimaryStatisticConfiguration +CREATE view ob.viewFactDepartmentPrimaryStatisticConfiguration as +select +f.RowID, +d.DepartmentalBudgetID, +f.AccountID, +convert(tinyint,f.Revenue) as Revenue, +convert(tinyint,f.Staffing) as Staffing, +convert(tinyint,f.NonStaffingExpense) as NonStaffingExpense, +f.IsDeleted, +f.HistoryItemGUID, +f.Version, +f.TransactionID +from [client].[FactDepartmentPrimaryStatisticConfiguration] f +inner join [ob].[DimDepartmentalBudget] d on f.DepartmentID=d.DepartmentID +GO + + +--------------------------------------------- + +-- ob.viewFactReportingMonthlyTargetComparision +CREATE view ob.viewFactReportingMonthlyTargetComparision as +/*************************************************************************************************************************************************************** +** Author: akowalski +** Create Date: NA +** Description: Presents the post-model refresh data in the same format as the reconciliation targets are stored for comparison purposes +** Last Modified: 2014-06-12 +** GM Release: 2014.3 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-12-14 srk D-04952 Removed unnecessary unions with factaccount to simplify the view, updated measure for YTD for current year +****************************************************************************************************************************************************************/ + +select total.EntityID, +total.FiscalMonthID, +total.FiscalYearID, +total.FinancialReportingID, +total.TimeClassID, +SUM(total.Amount) as Amount +from +--------------------FACT REPORTING MONTHLY FOR FULL YEAR------------------------- + ( + select db.EntityID, + 0 as FiscalMonthID, + fct.FiscalYearID, + fct.FinancialReportingID, + fct.TimeClassID, + fct.Total as Amount + from [clientob].[FactReportingMonthly] fct + inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fct.DepartmentalBudgetID + inner join FRLineItem fr on fct.FinancialReportingID=fr.FinancialReportingID and fr.FWDimensionGUID='8F46A3C4-97E7-49B3-82F8-6463B701D77D' + where 1=1 + and fr.Type=0 + and fct.FiscalYearID = (Select DBS.Setting - 1 From [dbo].[DBSetting] DBS where DBS.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') + and fct.TimeClassID = 1 + + union all + + select db.EntityID, + 0 as FiscalMonthID, + fct.FiscalYearID, + fct.FinancialReportingID, + fct.TimeClassID, + fct.YTD as Amount + from [clientob].[FactReportingMonthly] fct + inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fct.DepartmentalBudgetID + inner join FRLineItem fr on fct.FinancialReportingID=fr.FinancialReportingID and fr.FWDimensionGUID='8F46A3C4-97E7-49B3-82F8-6463B701D77D' + where 1=1 + and fr.Type=0 + and fct.FiscalYearID = (Select DBS.Setting From [dbo].[DBSetting] DBS where DBS.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') + and fct.TimeClassID = 1 + + union all + + select db.EntityID, + 0 as FiscalMonthID, + fct.FiscalYearID, + fct.FinancialReportingID, + fct.TimeClassID, + fct.Total as Amount + from [clientob].[FactReportingMonthly] fct + inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fct.DepartmentalBudgetID + inner join FRLineItem fr on fct.FinancialReportingID=fr.FinancialReportingID and fr.FWDimensionGUID='8F46A3C4-97E7-49B3-82F8-6463B701D77D' + where 1=1 + and fr.Type=0 + and fct.FiscalYearID = (Select DBS.Setting From [dbo].[DBSetting] DBS where DBS.DBSettingGUID = '9c921c27-f3e4-4616-b3fd-925a75870b62') + and fct.TimeClassID = 2 + +--------------------FACT REPORTING MONTHLY FOR FULL YEAR------------------------- + + UNION ALL + +--------------------FACT REPORTING MONTHLY BY MONTH FOR ACTUAL YTD--------------- + + SELECT pv.EntityID, + fm.FiscalMonthID, + pv.FiscalYearID, + pv.FinancialReportingID, + pv.TimeClassID, + pv.Amount + FROM ( + select db.EntityID, + fct.FiscalYearID, + fct.FinancialReportingID, + 1 as TimeClassID, -- only current year historicals will be by month + fct.Month01, fct.Month02, fct.Month03, fct.Month04, fct.Month05, fct.Month06, fct.Month07, fct.Month08, fct.Month09, fct.Month10, fct.Month11, fct.Month12 + from [clientob].[FactReportingMonthly] fct + inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fct.DepartmentalBudgetID + inner join FRLineItem fr on fct.FinancialReportingID=fr.FinancialReportingID and fr.FWDimensionGUID='8F46A3C4-97E7-49B3-82F8-6463B701D77D' + where fr.Type=0 + and fct.FiscalYearID=(select setting from [dbo].[DBSetting] where Name='OB_Current_Year') -- only current year historicals will be by month + and fct.TimeClassID=12 -- only current year historicals will be by month (this is because projection data is stored by month for the YTD portion) + ) dta + unpivot (Amount for MonthColumnName in (Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12)) as pv + inner join fw.DimFiscalMonth fm with (readuncommitted) on pv.MonthColumnName = fm.MonthColumnName + where fm.FiscalMonthID <= (Select DBS.Setting From [dbo].[DBSetting] DBS where DBS.DBSettingGUID = '14cbd1a1-15e9-411d-9fea-78cecaadf7e7') + +--------------------FACT REPORTING MONTHLY BY MONTH FOR ACTUAL YTD--------------- + + +) total +group by +total.EntityID, +total.FiscalMonthID, +total.FiscalYearID, +total.FinancialReportingID, +total.TimeClassID +GO + + +--------------------------------------------- + +-- ob.viewFactReportingMonthlyTargetComparisionDetail +CREATE view ob.viewFactReportingMonthlyTargetComparisionDetail as +/************************************************************ +** Author: akowalski +** Create Date: NA +** Description: Presents the post-model refresh data in the same format as the financial statement data source for comparison purposes +** Last Modified: 2014-06-12 +** GM Release: 2014.3 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +*************************************************************/ + + select fct.DepartmentalBudgetID, + db.DepartmentID, + 0 as AccountID, + fct.FinancialReportingID as FinancialReportingID, + FiscalYearID, + TimeClassID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + YTD, + Yearly, + Total + from [clientob].[FactReportingMonthly] fct + inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fct.DepartmentalBudgetID + where not (fct.FiscalYearID=(select setting from [dbo].[DBSetting] where Name='OB_Current_Year') -- only current year historicals will be by month + and fct.TimeClassID=1) + +union all + + select + DepartmentalBudgetID, + DepartmentID, + AccountID, + FinancialReportingID, + FiscalYearID, + TimeClassID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + 0 as YTD, + 0 as Yearly, + (YTD.Month01 + YTD.Month02 + YTD.Month03 + YTD.Month04 + + YTD.Month05 + YTD.Month06 + YTD.Month07 + YTD.Month08 + + YTD.Month09 + YTD.Month10 + YTD.Month11 + YTD.Month12) as Total + from ( + select fct.DepartmentalBudgetID, + db.DepartmentID, + 0 as AccountID, + fct.FinancialReportingID as FinancialReportingID, + FiscalYearID, + 1 as TimeClassID, + case when mnth.Setting>=1 then Month01 else 0 end as Month01, + case when mnth.Setting>=2 then Month02 else 0 end as Month02, + case when mnth.Setting>=3 then Month03 else 0 end as Month03, + case when mnth.Setting>=4 then Month04 else 0 end as Month04, + case when mnth.Setting>=5 then Month05 else 0 end as Month05, + case when mnth.Setting>=6 then Month06 else 0 end as Month06, + case when mnth.Setting>=7 then Month07 else 0 end as Month07, + case when mnth.Setting>=8 then Month08 else 0 end as Month08, + case when mnth.Setting>=9 then Month09 else 0 end as Month09, + case when mnth.Setting>=10 then Month10 else 0 end as Month10, + case when mnth.Setting>=11 then Month11 else 0 end as Month11, + case when mnth.Setting>=12 then Month12 else 0 end as Month12, + YTD, + Yearly, + Total + from [clientob].[FactReportingMonthly] fct + inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fct.DepartmentalBudgetID + inner join [dbo].[DBSetting] mnth on mnth.name='OB_Months_Loaded' + where fct.FiscalYearID=(select setting from [dbo].[DBSetting] where Name='OB_Current_Year') -- only current year historicals will be by month + and fct.TimeClassID=12 + ) YTD + + union all + + select + f.DepartmentalBudgetID, + d.DepartmentID, + a.AccountID, + a.OBDollarsFinancialReportingID as FinancialReportingID, + FiscalYearID, + TimeClassID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + YTD, + Yearly, + Total + from [clientob].[FactAccount] f + inner join [ob].[DimDepartmentalBudget] d on d.DepartmentalBudgetID = f.DepartmentalBudgetID + inner join [fw].[DimDepartment] dep on dep.DepartmentID = d.DepartmentID + inner join [fw].[DimAccount] a on a.AccountID = f.AccountID + where f.UnitTypeID=34 and d.OBActivePlans=0 +GO + + +--------------------------------------------- + +-- ob.viewFactStaffingPCUnpivoted +create View [ob].[viewFactStaffingPCUnpivoted] +as + select + [DepartmentalBudgetID], + [PayCodeGroupID], + [PayCodeID], + [JobCodeID], + [EmployeeID], + [FiscalYearID], + [TimeClassID], + [UnitTypeID], + [DataTypeID], + fm.[FiscalMonthID], + [Value] + from + ( + select * + from [clientob].[FactStaffingPC] source + ) as PIV + UNPIVOT + ( + VALUE for MonthColumnName IN + ( + [Month01] + , [Month02] + , [Month03] + , [Month04] + , [Month05] + , [Month06] + , [Month07] + , [Month08] + , [Month09] + , [Month10] + , [Month11] + , [Month12] + ) + ) as f + inner join fw.DimFiscalMonth fm + on f.MonthColumnName=fm.MonthColumnName +GO + + +--------------------------------------------- + +-- ob.viewFlexDriver +CREATE VIEW ob.viewFlexDriver +AS +/** Change History +************************************************************** +** CID Date Author WI Description +** 1 2014-09-03 GF Initial Implementation +** 2 2022-06-21 KF JAZZ-39078 PR Metrics Definition - Add Flex Driver for Daily calculations +*************************************************************/ + select + fd.FlexDriverGUID, + fd.Name, + fd.ScoreDatatableGUID, + fd.ParentDriverGUID, + fd.IsParentDriverFlexed, + fd.SortOrder, + fd.Tier, + fd.MeasureType, + fd.IsSameJobCode, + fd.IsSamePayCodeGroup, + CAST(s.TimeFrameID as tinyint) TimeFrameID + from + [ob].[FlexDriver] fd + inner join + ( + select + kl.DataTableGUID, + MAX(case + when a.SQLColumnName = 'DateID' then 2 + when a.SQLColumnName = 'PayPeriodID' then 1 + else 0 end) as TimeFrameID + from [dbo].[ScoreDataTableKeyLink] kl + inner join [dbo].[ScoreAttribute] a on a.AttributeGUID = kl.KeyGUID + where + a.SQLColumnName in ('FiscalMonthID', 'PayPeriodID', 'DateID') + GROUP BY kl.DataTableGUID + ) s on s.DataTableGUID = fd.ScoreDatatableGUID +GO + + +--------------------------------------------- + +-- ob.viewPayrollVariabilityOverrideCacheForAllPayCodeGroupsGrouped +/************************************************************* +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2023-11-21 HV JAZZ-40552 Technical - Jazz - Create views for calculating targets with spreads for variable job-codes for Productive Hours-Standard metric for Pay Period/YTD +*************************************************************/ + +CREATE VIEW ob.viewPayrollVariabilityOverrideCacheForAllPayCodeGroupsGrouped +AS + +SELECT + DepartmentID, + JobCodeID, + MAX(CASE WHEN Variability > 0 THEN 1 ELSE 0 END) as Variability +FROM ob.PayrollVariabilityOverrideCache +WHERE IsForAllPayCodeGroups = 1 +GROUP BY DepartmentID, JobCodeID +GO + + +--------------------------------------------- + +-- ob.viewReconciliationDepartmentalBudgetIncomeStatement +CREATE view [ob].[viewReconciliationDepartmentalBudgetIncomeStatement] as +select +d.EntityID as EntityID +, f.DepartmentalBudgetID +, d.Name as DepartmentalBudgetName +, dep.DepartmentID +, f.AccountID +, a.OBDollarsFinancialReportingID as [FinancialReportingID] +, f.TimeClassID +, f.FiscalYearID +, f.DataTypeID +, f.UnitTypeID +, f.[Month01] +, f.[Month02] +, f.[Month03] +, f.[Month04] +, f.[Month05] +, f.[Month06] +, f.[Month07] +, f.[Month08] +, f.[Month09] +, f.[Month10] +, f.[Month11] +, f.[Month12] +, f.[Total] +, f.[Yearly] +, f.[YTD] +from [clientob].[FactAccount] f +inner join [ob].[DimDepartmentalBudget] d on d.DepartmentalBudgetID = f.DepartmentalBudgetID +inner join [fw].[DimDepartment] dep on dep.DepartmentID = d.DepartmentID +inner join [fw].[DimAccount] a on a.AccountID = f.AccountID +where f.UnitTypeID=34 +GO + + +--------------------------------------------- + +-- ob.viewReconciliationDepartmentalBudgetStaffing +/************************************************************ +** Author: akowalski +** Create Date: NA +** Description: The driving view for Staffing Data Reconciliation Screens in +** Last Modified: 2014-10-15 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +*************************************************************/ +CREATE view [ob].[viewReconciliationDepartmentalBudgetStaffing] +AS + +-- Data that will actually show up in the model + +SELECT + dept.EntityID as EntityID, + budget.DepartmentalBudgetID, + budget.Name as DepartmentalBudgetName, + dept.DepartmentID, + d.JobCodeID, + pcg.PayCodeGroupID, + d.PayCodeID, + d.TimeClassID, + d.FiscalYearID, + d.FiscalMonthID, + d.EmployeeID, +-- case +-- when unittypeID='34' then unittypeID +-- when unittypeID<>'34' and pcg.ProductiveClass='Productive' then 148 +-- when unittypeID<>'34' and pcg.ProductiveClass='Non-Productive' then 146 +-- when unittypeID<>'34' and pcg.ProductiveClass='Differential' then 147 +-- else 51 end as UnitTypeID, + d.UnitTypeID, + dt.DataTypeID, + d.Value +FROM + [int].[FactStaffing] AS d + inner join fw.DimDepartment dept on d.[DepartmentID]=dept.DepartmentID + inner join ob.DimDepartmentalBudget budget on budget.DepartmentID=dept.DepartmentID + inner join fw.DimPayCode pc on pc.PayCodeid = d.PayCodeid + inner join fw.DimPayCodeGroup pcg on pcg.PayCodeGroupID = pc.PayCodeGroupID + inner join [fw].[DimEmployee] e on e.EmployeeID=d.EmployeeID + inner join fw.DimDataType dt on dt.Name='Input' + inner join [dbo].[DBSetting] yr on yr.Name='OB_Current_Year' + inner join [fw].[DimJobCode] jc on d.JobCodeID=jc.JobCodeID + inner join [fw].[DimEntity] ent on dept.EntityID=ent.EntityID +where e.IsProvider=0 +and pc.PayCodeGroupID<>0 and ((pc.IsDollarsIgnored=0 and d.UnitTypeid=34) +or (pc.IsHoursIgnored=0 and d.UnitTypeid<>34)) +and d.fiscalyearID > (yr.Setting - 2) +and ((jc.IsProvider=0 and ent.OBIsUsingProviderComp=1) +or ent.OBIsUsingProviderComp=0) + +-- Data that's suppressed because of job code configuration +union all + +SELECT + dept.EntityID as EntityID, + budget.DepartmentalBudgetID, + budget.Name as DepartmentalBudgetName, + dept.DepartmentID, + 0 as JobCodeID, + 0 as PayCodeGroupID, + d.PayCodeID, + d.TimeClassID, + d.FiscalYearID, + d.FiscalMonthID, + d.EmployeeID, + d.UnitTypeID, + dt.DataTypeID, + d.Value +FROM + [int].[FactStaffing] AS d + inner join fw.DimDepartment dept on d.[DepartmentID]=dept.DepartmentID + inner join ob.DimDepartmentalBudget budget on budget.DepartmentID=dept.DepartmentID + inner join fw.DimPayCode pc on pc.PayCodeid = d.PayCodeid + inner join fw.DimPayCodeGroup pcg on pcg.PayCodeGroupID = pc.PayCodeGroupID + inner join [fw].[DimEmployee] e on e.EmployeeID=d.EmployeeID + inner join fw.DimDataType dt on dt.Name='Input' + inner join [dbo].[DBSetting] yr on yr.Name='OB_Current_Year' + inner join [fw].[DimJobCode] jc on d.JobCodeID=jc.JobCodeID + inner join [fw].[DimEntity] ent on dept.EntityID=ent.EntityID +where pc.PayCodeGroupID<>0 and ((pc.IsDollarsIgnored=0 and d.UnitTypeid=34) +or (pc.IsHoursIgnored=0 and d.UnitTypeid<>34)) +and d.fiscalyearID > (yr.Setting - 2) +and (e.IsProvider=1 +or (jc.IsProvider=1 and ent.OBIsUsingProviderComp=1)) + +-- data that's suppressed because of pay code configuration +union all + +SELECT + dept.EntityID as EntityID, + budget.DepartmentalBudgetID, + budget.Name as DepartmentalBudgetName, + dept.DepartmentID, + 0 as JobCodeID, + 0 as PayCodeGroupID, + d.PayCodeID, + d.TimeClassID, + d.FiscalYearID, + d.FiscalMonthID, + d.EmployeeID, + d.UnitTypeID, + dt.DataTypeID, + d.Value +FROM + [int].[FactStaffing] AS d + inner join fw.DimDepartment dept on d.[DepartmentID]=dept.DepartmentID + inner join ob.DimDepartmentalBudget budget on budget.DepartmentID=dept.DepartmentID + inner join fw.DimPayCode pc on pc.PayCodeid = d.PayCodeid + inner join fw.DimPayCodeGroup pcg on pcg.PayCodeGroupID = pc.PayCodeGroupID + inner join [fw].[DimEmployee] e on e.EmployeeID=d.EmployeeID + inner join fw.DimDataType dt on dt.Name='Input' + inner join [dbo].[DBSetting] yr on yr.Name='OB_Current_Year' + inner join [fw].[DimJobCode] jc on d.JobCodeID=jc.JobCodeID + inner join [fw].[DimEntity] ent on dept.EntityID=ent.EntityID +where e.IsProvider=0 +and d.fiscalyearID > (yr.Setting - 2) +and ((jc.IsProvider=0 and ent.OBIsUsingProviderComp=1) +or ent.OBIsUsingProviderComp=0) +and (pc.PayCodeGroupID=0 or (pc.IsDollarsIgnored=1 and d.UnitTypeid=34) +or (pc.IsHoursIgnored=1 and d.UnitTypeid<>34)) +GO + + +--------------------------------------------- + +-- ob.viewReconciliationDepartmentalBudgetStatistics +create view [ob].[viewReconciliationDepartmentalBudgetStatistics] as +select +d.EntityID as EntityID +, f.DepartmentalBudgetID +, d.Name as DepartmentalBudgetName +, dep.DepartmentID +, f.AccountID +, a.PatientClassID +, f.TimeClassID +, f.FiscalYearID +, f.DataTypeID +, f.UnitTypeID +, f.[Month01] +, f.[Month02] +, f.[Month03] +, f.[Month04] +, f.[Month05] +, f.[Month06] +, f.[Month07] +, f.[Month08] +, f.[Month09] +, f.[Month10] +, f.[Month11] +, f.[Month12] +, f.[Total] +, f.[Yearly] +, f.[YTD] +from [clientob].[FactAccount] f +inner join [ob].[DimDepartmentalBudget] d on d.DepartmentalBudgetID = f.DepartmentalBudgetID +inner join [fw].[DimDepartment] dep on dep.DepartmentID = d.DepartmentID +inner join [fw].[DimAccount] a on a.AccountID = f.AccountID +where f.UnitTypeID<>34 and f.UnitTypeID<>0 +GO + + +--------------------------------------------- + +-- ob.viewReconciliationRollingOBDollarsGLOnly +CREATE VIEW [ob].[viewReconciliationRollingOBDollarsGLOnly] as +select + ob.DepartmentalBudgetID as PlanID, + ob.Name as PlanName, + source.AccountID as AccountID, + ma.AccountCode as Account, + source.DepartmentID as DepartmentID, + md.DepartmentCode as Department, + 0 as PatientTypeRollupID, + 'n/a' as PatientTypeRollup, + ma.OBDollarsFinancialReportingID as FinancialReportingID, + ma.OBDollarsFinancialReporting, + + ut.UnitTypeID as UnitTypeID, + ut.Name as UnitType, + source.TimeClassID as TimeClassID, + source.TimeClassCode as TimeClass, + source.FiscalYearID as FiscalYearID, + source.FiscalYearCode as FiscalYear, + source.FiscalMonthID as FiscalMonthID, + source.FiscalMonthCode as FiscalMonthCode, + (source.Value * isnull(ma.Inversion, 1)) as Value +from int.FactGL source (readuncommitted) + Inner Join fw.DimAccount ma (readuncommitted) on ma.AccountID = source.AccountID + Inner Join fw.DimDepartment md (readuncommitted) on md.DepartmentID = source.DepartmentID + inner join ob.viewDimDepartmentalBudget ob on md.DepartmentID = ob.DepartmentID + Inner Join fw.DimUnitType ut (readuncommitted) on ut.Name='Dollars' +where + md.DepartmentID<>0 + + + +Union All + +select + ob.DepartmentalBudgetID as PlanID, + ob.Name as PlanName, + source.AccountID as AccountID, + ma.AccountCode as Account, + source.DepartmentID as DepartmentID, + md.DepartmentCode as Department, + 0 as PatientTypeRollupID, + GLRollup as PatientTypeRollup, + ma.OBDollarsFinancialReportingID as FinancialReportingID, + ma.OBDollarsFinancialReporting , + ut.UnitTypeID, + ut.name as UnitType, + source.TimeClassID as TimeClassID, + source.TimeClassCode as TimeClass, + source.FiscalYearID as FiscalYearID, + source.FiscalYearCode as FiscalYear, + source.FiscalMonthID as FiscalMonthID, + source.FiscalMonthCode as FiscalMonthCode, + source.Value as Value +from int.FactStatistic source (readuncommitted) + Inner Join fw.DimAccount ma (readuncommitted) on ma.AccountID = source.AccountID and ma.IsStat =1 + --inner join fw.DimPatientType PT on PT.PatientTypeID = ma.PatientTypeID + --inner join fw.DimPatientTypeRollup PR on PR.PatientTypeRollupID = PT.PatientTypeRollupID + Inner Join fw.DimDepartment md (readuncommitted) on md.DepartmentID = source.DepartmentID + inner join ob.viewDimDepartmentalBudget ob (readuncommitted) on md.DepartmentID=md.DepartmentID + inner join fw.DimUnitType ut on ut.Name ='Volume' +where + md.DepartmentID<>0 +GO + + +--------------------------------------------- + +-- ob.viewReportAccountSnapshotData +/************************************************************ +** Author: Joel Gerber +** Create Date: 2014-03-10 +** Description: Reporting Data View for All OB Snapshot Reports +** Last Modified: 2014-03-10 +** GM Release: NA (Customization) +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +*************************************************************/ +create view [ob].[viewReportAccountSnapshotData] as + + +select + data.DepartmentalBudgetID, + data.AccountID, + FiscalYearID, + TimeClassID, + UnitTypeID, + DataTypeID, + acc.PatientTypeID, + OBSnapshotID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + data.MonthsLoaded, + YTD, + Yearly, + Total +from + ob.FactAccountSnapshot data + inner join fw.DimAccount acc on acc.AccountID=data.AccountID +where + acc.IsGlobal=0 +GO + + +--------------------------------------------- + +-- ob.viewReportAccountWithStaffingDetail +create view [ob].[viewReportAccountWithStaffingDetail] +as + +-- Staffing Data +------------------------------------------------------------------------------------------- + select + DepartmentalBudgetID = vw.DepartmentalBudgetID, + AccountID = vw.AccountID, + JobCodeID = vw.JobCodeID, + PayCodeGroupID = vw.PayCodeGroupID, + FiscalYearID = vw.FiscalYearID, + TimeClassID = vw.TimeClassID, + UnitTypeID = vw.UnitTypeID, + Month01 = vw.Month01, + Month02 = vw.Month02, + Month03 = vw.Month03, + Month04 = vw.Month04, + Month05 = vw.Month05, + Month06 = vw.Month06, + Month07 = vw.Month07, + Month08 = vw.Month08, + Month09 = vw.Month09, + Month10 = vw.Month10, + Month11 = vw.Month11, + Month12 = vw.Month12, + YTD = cmb.IsCY*vw.YTD, + Total = vw.Total + from [ob].[viewReportStaffingtoGLAccount] vw + inner join [ob].[viewValidDataTypeTimeClassFiscalYearCombos] cmb + on vw.TimeClassID=cmb.TimeClassID + and vw.DataTypeID=cmb.DataTypeID + and vw.FiscalYearID=cmb.FiscalYearID + inner join [clientob].[FactAccount] fct + on vw.DepartmentalBudgetID = fct.DepartmentalBudgetID + and vw.AccountID = fct.AccountID + and vw.FiscalYearID = fct.FiscalYearID + and vw.TimeClassID = fct.TimeClassID + and vw.UnitTypeID = fct.UnitTypeID + and vw.DataTypeID = fct.DataTypeID + +UNION ALL + +-- Non-Staffing Account Data +------------------------------------------------------------------------------------------- + select + DepartmentalBudgetID = fct.DepartmentalBudgetID, + AccountID = fct.AccountID, + JobCodeID = 0, + PayCodeGroupID = 0, + FiscalYearID = fct.FiscalYearID, + TimeClassID = fct.TimeClassID, + UnitTypeID = fct.UnitTypeID, + Month01 = fct.Month01, + Month02 = fct.Month02, + Month03 = fct.Month03, + Month04 = fct.Month04, + Month05 = fct.Month05, + Month06 = fct.Month06, + Month07 = fct.Month07, + Month08 = fct.Month08, + Month09 = fct.Month09, + Month10 = fct.Month10, + Month11 = fct.Month11, + Month12 = fct.Month12, + YTD = cmb.IsCY*fct.YTD, + Total = fct.Total + from [clientob].[FactAccount] fct + inner join [ob].[viewValidDataTypeTimeClassFiscalYearCombos] cmb + on fct.TimeClassID=cmb.TimeClassID + and fct.DataTypeID=cmb.DataTypeID + and fct.FiscalYearID=cmb.FiscalYearID + where not exists + ( + select 1 + from [ob].[viewReportStaffingtoGLAccount] vw + where 1=1 + and fct.DepartmentalBudgetID = vw.DepartmentalBudgetID + and fct.AccountID = vw.AccountID + and fct.FiscalYearID = vw.FiscalYearID + and fct.TimeClassID = vw.TimeClassID + and fct.UnitTypeID = vw.UnitTypeID + and fct.DataTypeID = vw.DataTypeID + ) + +UNION ALL + +-- GL Data Historical Input Data Discrepancy +------------------------------------------------------------------------------------------- + select + DepartmentalBudgetID = fct.DepartmentalBudgetID, + AccountID = fct.AccountID, + JobCodeID = 0, + PayCodeGroupID = 0, + FiscalYearID = fct.FiscalYearID, + TimeClassID = fct.TimeClassID, + UnitTypeID = fct.UnitTypeID, + Month01 = max(fct.Month01) - sum(vw.Month01), + Month02 = max(fct.Month02) - sum(vw.Month02), + Month03 = max(fct.Month03) - sum(vw.Month03), + Month04 = max(fct.Month04) - sum(vw.Month04), + Month05 = max(fct.Month05) - sum(vw.Month05), + Month06 = max(fct.Month06) - sum(vw.Month06), + Month07 = max(fct.Month07) - sum(vw.Month07), + Month08 = max(fct.Month08) - sum(vw.Month08), + Month09 = max(fct.Month09) - sum(vw.Month09), + Month10 = max(fct.Month10) - sum(vw.Month10), + Month11 = max(fct.Month11) - sum(vw.Month11), + Month12 = max(fct.Month12) - sum(vw.Month12), + YTD = max(cmb.IsCY)*(max(fct.YTD ) - sum(vw.YTD)), + Total = max(fct.Total ) - sum(vw.Total) + from [clientob].[FactAccount] fct + inner join [ob].[viewReportStaffingtoGLAccount] vw + on fct.DepartmentalBudgetID = vw.DepartmentalBudgetID + and fct.AccountID = vw.AccountID + and fct.FiscalYearID = vw.FiscalYearID + and fct.TimeClassID = vw.TimeClassID + and fct.UnitTypeID = vw.UnitTypeID + and fct.DataTypeID = vw.DataTypeID + inner join [ob].[viewValidDataTypeTimeClassFiscalYearCombos] cmb + on fct.TimeClassID=cmb.TimeClassID + and fct.DataTypeID=cmb.DataTypeID + and fct.FiscalYearID=cmb.FiscalYearID + where 1=1 + and (fct.DataTypeID = 4 or fct.TimeClassID = 12) + group by + fct.DepartmentalBudgetID, + fct.AccountID, + fct.FiscalYearID, + fct.TimeClassID, + fct.UnitTypeID + having + max(fct.Total) <> SUM(vw.Total) +GO + + +--------------------------------------------- + +-- ob.viewReportAccountWithStaffingDetail_Friendly +CREATE VIEW [ob].[viewReportAccountWithStaffingDetail_Friendly] +As + +SELECT + md.DepartmentCode as [DepartmentCode] + , md.Description as [DepartmentDescription] + , md.Entity + , md.EntityCode + , md.DepartmentRollup1 + , md.DepartmentRollup2 + , md.DepartmentRollup3 + , md.DepartmentRollup4 + , md.DepartmentRollup5 + , md.DepartmentRollup6 + , a.AccountCode as [AccountCode] + , a.Description as [AccountDescription] + , a.GMAccountRollup1 as AccountRollup1 + , a.GMAccountRollup2 as AccountRollup2 + , a.GMAccountRollup3 as AccountRollup3 + , a.GMAccountRollup4 as AccountRollup4 + , a.GMAccountRollup5 as AccountRollup5 + , a.GMAccountRollup6 as AccountRollup6 + , a.[OBDollarsFinancialReportingLineName] as DollarsFinancialReportingLineName + , a.[OBUnitsFinancialReportingLineName] as UnitsFinancialReportingLineName + , jc.Name as [JobCode] + , jcg.Name as [JobCodeGroup] + , pcg.Name as [PayCodeGroup] + , fy.Name as [FiscalYear] + , tc.Name as [TimeClass] + , ut.Name as [UnitType] + , [Month01] + , [Month02] + , [Month03] + , [Month04] + , [Month05] + , [Month06] + , [Month07] + , [Month08] + , [Month09] + , [Month10] + , [Month11] + , [Month12] + , [YTD] + , [Total] +FROM [ob].[FactReportAccountWithStaffingDetail] r +INNER JOIN [fw].[DimAccount] a on r.AccountID=a.AccountID +INNER JOIN [ob].[DimDepartmentalBudget] d on r.DepartmentalBudgetID=d.DepartmentalBudgetID +INNER JOIN [fw].[DimDepartment] md on d.DepartmentID=md.DepartmentID +INNER JOIN [fw].[DimJobCode] jc on r.JobCodeID=jc.JobCodeID +INNER JOIN [fw].[DimJobCodeGroup] jcg on jc.JobCodeGroupID=jcg.JobCodeGroupID +INNER JOIN [fw].[DimPayCodeGroup] pcg on r.PayCodeGroupID=pcg.PayCodeGroupID +INNER JOIN [fw].[DimUnitType] ut on r.UnitTypeID=ut.UnitTypeID +INNER JOIN [fw].[DimTimeClass] tc on r.TimeClassID=tc.TimeClassID +INNER JOIN [fw].[DimFiscalYear] fy on r.FiscalYearID=fy.FiscalYearID +Where Total <> 0 +GO + + +--------------------------------------------- + +-- ob.viewReportCDMRatios +/************************************************************ +** Author: BL +** Create Date: 2014-11-13 +** Description: Service Line to Department CDM Ratios for Reporting +** Last Modified: 2014-11-13 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 +*************************************************************/ +Create view [ob].[viewReportCDMRatios] as +select + CDMRatio.FiscalYearID, + B.DepartmentalBudgetID, + CDMRatio.ModelingServiceLineID, + CDMRatio.ChargeCodeID, + ut.UnitTypeID, + dt.DataTypeID, + MSL.PatientClassID, + CDMRatio.CurrentYear as [ProjectedRatio], + CDMRatio.NextYear as [BudgetRatio], + B.DepartmentalBudgetID as BudgID +from [clientob].[FactServiceLinetoDepartmentCDM] CDMRatio +inner join [ob].[DimDepartmentalBudget] B on B.DepartmentID = CDMRatio.DepartmentID +inner join [fw].[DimDepartment] D on D.DepartmentID = B.DepartmentID +inner join [ob].[DimOBServiceLinePlan] SLP on D.OBServiceLinePlanID=SLP.OBServiceLinePlanID +inner join [dbo].[DBSetting] DBS on DBS.Name = 'OB_Current_Year' and CDMRatio.FiscalYearID=DBS.Setting +inner join [fw].[DimModelingServiceLine] MSL on MSL.ModelingServiceLineID = CDMRatio.ModelingServiceLineID +inner join [fw].[DimUnitType] ut on ut.GlobalID='Units' +inner join fw.dimdatatype dt on dt.globalid='Input' +where CDMRatio.IsDeleted = 0 and NOT (CDMRatio.CurrentYear=0 OR CDMRatio.NextYear=0) +GO + + +--------------------------------------------- + +-- ob.viewReportDepartmentBudgetModelToReconciliationTargetComparisionDetail +create view [ob].[viewReportDepartmentBudgetModelToReconciliationTargetComparisionDetail] as +/************************************************************ +** Author: akowalski +** Create Date: 2014-06-12 +** Description: Displays the department level detail for model to target comparisions +** Last Modified: 2014-06-12 +** GM Release: 2014.3 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +*************************************************************/ +select db.entityid, +f.DepartmentID, +f.FinancialReportingID, +f.TimeClassID, +f.FiscalYearID, +f.Month01, +f.Month02, +f.Month03, +f.Month04, +f.Month05, +f.Month06, +f.Month07, +f.Month08, +f.Month09, +f.Month10, +f.Month11, +f.Month12, +f.Total, +'Live' as [Type] +from [ob].[viewFactReportingMonthlyTargetComparisionDetail] f +inner join [ob].[DimDepartmentalBudget] db on f.DepartmentalBudgetID=db.DepartmentalBudgetID + + +union all + +select db.entityid, +f.DepartmentID, +f.FinancialReportingID, +f.TimeClassID, +f.FiscalYearID, +f.Month01, +f.Month02, +f.Month03, +f.Month04, +f.Month05, +f.Month06, +f.Month07, +f.Month08, +f.Month09, +f.Month10, +f.Month11, +f.Month12, +f.Total, +'Target' as [Type] +from [clientob].[viewReportFinancialStatements] f +inner join [ob].[DimDepartmentalBudget] db on f.DepartmentalBudgetID=db.DepartmentalBudgetID +GO + + +--------------------------------------------- + +-- ob.viewReportDepartmentalBudgetExceptionsSummary +create view ob.viewReportDepartmentalBudgetExceptionsSummary as +/************************************************************ +** Author: akowalski +** Create Date: 2014-04-30 +** Description: Summarized OB department budget exceptions for dashboard +** Last Modified: 2014-04-30 +** GM Release: 2014.3 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2013-02-19 DK 56588 Adding update statistics command +** +*************************************************************/ + +select +e.OBExceptionsID, +sum(case when e.Acknowledged=1 then 0 else 1 end) as [Open], +sum(case when e.Acknowledged=1 then 1 else 0 end) as Acknowledged +from [ob].[FactDepartmentBudgetExceptions] e +group by e.OBExceptionsID +GO + + +--------------------------------------------- + +-- ob.viewReportExceptionsDepartmentBudgetExceededProductivityTargets +/************************************************************ +** Author: jgerber +** Create Date: 2013-11-17 +** Description: Exception report to show which departments are over their productivity target +** Last Modified: 2014-10-07 +** GM Release: 2015.1 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2014-10-07 JG Renaming and adding to the exception summary report +** +*************************************************************/ +create view ob.viewReportExceptionsDepartmentBudgetExceededProductivityTargets + +as + +select + targ.DepartmentalBudgetID, + targ.BudgetName as Model, + 'Has '+cast(tot.Amount as Nvarchar(100))+' Hrs/UOS when the target is '+cast(targ.Amount as Nvarchar(100))+' Hrs/UOS for '+targ.TimeClassName+' '+targ.FiscalYearName as Detail +from + [clientob].[viewFactStaffingPCVar] targ + inner join [clientob].[viewFactStaffingPCVar] tot on targ.DepartmentalBudgetID=tot.DepartmentalBudgetID and targ.TimeClassID=tot.TimeClassID and targ.UnitTypeID=tot.UnitTypeID and targ.FiscalYearID=tot.FiscalYearID +where + targ.AssumptionID=639 --Hours per UOS Target + and tot.AssumptionID=640 --Hours per UOS + and targ.Amount0 + and not exists + ( + select 1 + from [clientob].[FactGlobalStatisticsDeptMapping] dm + inner join [ob].[DimOBGlobalStatistics] gsm + on dm.OBGlobalStatisticID = gsm.OBGlobalStatisticID + where 1=1 + and db.DepartmentID = dm.DepartmentID + and gsm.AccountID = gs.AccountID + and dm.IsDeleted=0 + ) +GO + + +--------------------------------------------- + +-- ob.viewReportGLDetail +CREATE VIEW ob.viewReportGLDetail AS + +SELECT + B.DepartmentalBudgetID, + F.AccountID, + F.ComponentID, + F.ProjectID, + F.FiscalMonthID, + F.FiscalYearID, + F.ClientCapitalID, + F.ClientComponentID, + F.ClientDate, + F.Amount, + F.ItemDescription, + F.JournalNumber, + F.JournalLineNumber, + F.CustomText1, + F.CustomText2, + F.CustomText3, + F.CustomText4, + F.CustomText5, + F.CustomDate1, + F.CustomDate2, + F.CustomNumeric1, + F.CustomNumeric2, + F.AccountID as AcctID, + B.DepartmentalBudgetID as BudgID +FROM [int].[FactGLDetail] F +INNER JOIN [ob].[DimDepartmentalBudget] B ON B.DepartmentID = F.DepartmentID +WHERE IsDeleted=0 +GO + + +--------------------------------------------- + +-- ob.viewReportGlobalStatisticsExceptionsSummary +Create view ob.viewReportGlobalStatisticsExceptionsSummary as +/************************************************************ +** Author: akowalski +** Create Date: 2015-01-09 +** Description: Summarized OB Global Stat exceptions for dashboard +** Last Modified: 2015-01-09 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +*************************************************************/ + +select +e.OBExceptionsID, +sum(case when e.Acknowledged=1 then 0 else 1 end) as [Open], +sum(case when e.Acknowledged=1 then 1 else 0 end) as Acknowledged +from [ob].[FactGlobalStatisticExceptions] e +group by e.OBExceptionsID +GO + + +--------------------------------------------- + +-- ob.viewReportPlanExpansion +CREATE VIEW [ob].[viewReportPlanExpansion] +AS +select + vp.PlanTypeName AS plantypename, + vp.planguid, + fi.*, + sd.MemberName, + sd.DimensionName +from clientob.viewscorefillins AS fi + LEFT OUTER JOIN dbo.viewPlans AS vp ON fi.ModelGUID = vp.planguid + left join [data].[viewScoreDimensionMember] sd on sd.MemberGUID=fi.PlaceholderSectionMemberGUID +where plantypeguid='05512126-3eb6-4da4-af6e-bc2bc2724b8b' +GO + + +--------------------------------------------- + +-- ob.viewReportReimbursementExceptionsSummary +Create view ob.viewReportReimbursementExceptionsSummary as +/************************************************************ +** Author: akowalski +** Create Date: 2015-01-09 +** Description: Summarized OB Reimbursement exceptions for dashboard +** Last Modified: 2015-01-09 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +*************************************************************/ + +select +e.OBExceptionsID, +sum(case when e.Acknowledged=1 then 0 else 1 end) as [Open], +sum(case when e.Acknowledged=1 then 1 else 0 end) as Acknowledged +from [ob].[FactReimbursementExceptions] e +group by e.OBExceptionsID +GO + + +--------------------------------------------- + +-- ob.viewReportSecurityDetail +--insert into DataView values(NEWID(), 'OB Duplicate Fill-Ins', 'dataob.viewReportDupeFillIns', dbo.ZeroGUID(), 0, '', dbo.ZeroGUID(), '') + +CREATE view [ob].[viewReportSecurityDetail] +as + select + S.* + from + fw.viewReportSecurityDetail S + inner join UserRole UR on UR.Name = S.USERROLE + where + UR.Category = 'OB' +GO + + +--------------------------------------------- + +-- ob.viewReportServiceLineExceptionsSummary +Create view ob.viewReportServiceLineExceptionsSummary as +/************************************************************ +** Author: akowalski +** Create Date: 2015-01-09 +** Description: Summarized OB Service Line exceptions for dashboard +** Last Modified: 2015-01-09 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +*************************************************************/ + +select +e.OBExceptionsID, +sum(case when e.Acknowledged=1 then 0 else 1 end) as [Open], +sum(case when e.Acknowledged=1 then 1 else 0 end) as Acknowledged +from [ob].[FactServiceLineExceptions] e +group by e.OBExceptionsID +GO + + +--------------------------------------------- + +-- ob.viewReportStaffingSnapshotData +/************************************************************ +** Author: Joel Gerber +** Create Date: 2014-03-21 +** Description: Reporting Staffing Data View for All OB Snapshot Reports +** Last Modified: 2014-03-21 +** GM Release: NA (Customization) +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +*************************************************************/ + +CREATE view [ob].[viewReportStaffingSnapshotData] as + +select + data.DepartmentalBudgetID, + EmployeeID, + JobCodeID, + PayCodeGroupID, + PayCodeID, + FiscalYearID, + TimeClassID, + UnitTypeID, + DataTypeID, + OBSnapshotID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + data.MonthsLoaded, + YTD, + Yearly, + Total +from + [ob].[FactStaffingPCSnapshot] data +GO + + +--------------------------------------------- + +-- ob.viewReportStaffingtoGLAccount +CREATE view [ob].[viewReportStaffingtoGLAccount] as + select * from ob.viewReportStaffingtoGLAccount_BothUnique +GO + + +--------------------------------------------- + +-- ob.viewReportStaffingtoGLAccount_BothOverride +CREATE view [ob].[viewReportStaffingtoGLAccount_BothOverride] as + select + data.DepartmentalBudgetID, + pax.AccountID, + data.JobCodeID, + data.PayCodeGroupID, + data.FiscalYearID, + data.TimeClassID, + ut3.UnitTypeID, + data.DataTypeID, + data.Month01/whpm.Month01 as Month01, + data.Month02/whpm.Month02 as Month02, + data.Month03/whpm.Month03 as Month03, + data.Month04/whpm.Month04 as Month04, + data.Month05/whpm.Month05 as Month05, + data.Month06/whpm.Month06 as Month06, + data.Month07/whpm.Month07 as Month07, + data.Month08/whpm.Month08 as Month08, + data.Month09/whpm.Month09 as Month09, + data.Month10/whpm.Month10 as Month10, + data.Month11/whpm.Month11 as Month11, + data.Month12/whpm.Month12 as Month12, + data.YTD/(case + when data.MonthsLoaded = 1 then whpm.Month01 + when data.MonthsLoaded = 2 then whpm.Month01 + whpm.Month02 + when data.MonthsLoaded = 3 then whpm.Month01 + whpm.Month02 + whpm.Month03 + when data.MonthsLoaded = 4 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + when data.MonthsLoaded = 5 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + when data.MonthsLoaded = 6 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + when data.MonthsLoaded = 7 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + when data.MonthsLoaded = 8 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + when data.MonthsLoaded = 9 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + when data.MonthsLoaded = 10 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + whpm.Month10 + when data.MonthsLoaded = 11 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + whpm.Month10 + whpm.Month11 + else whpm.MonthYearly end) as YTD, + data.Total/whpm.MonthYearly as Total + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join [fw].[DimUnitType] ut1 with (readuncommitted) on ut1.UnitTypeID = data.UnitTypeID + inner join [fw].[DimUnitType] ut2 with (readuncommitted) on ut2.Name = 'Hours' + inner join [fw].[DimUnitType] ut3 with (readuncommitted) on ut3.Name = 'FTEs' + inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and data.JobCodeID=pax.JobCodeID and ut2.UnitTypeID = pax.UnitTypeID + inner join [client].[FactWorkingHoursPerMonth] whpm with (readuncommitted) on data.FiscalYearID=whpm.FiscalYearID + inner join [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID=data.PayCodeGroupID + where + ut1.Name in('Non-Productive Hours', 'Productive Hours') and pcg.ProductiveClassID in ('2', '3') -- Non-Productive, Productive + union all + select + data.DepartmentalBudgetID, + pax.AccountID, + data.JobCodeID, + data.PayCodeGroupID, + data.FiscalYearID, + data.TimeClassID, + ut3.UnitTypeID, + data.DataTypeID, + data.Month01/whpm.Month01 as Month01, + data.Month02/whpm.Month02 as Month02, + data.Month03/whpm.Month03 as Month03, + data.Month04/whpm.Month04 as Month04, + data.Month05/whpm.Month05 as Month05, + data.Month06/whpm.Month06 as Month06, + data.Month07/whpm.Month07 as Month07, + data.Month08/whpm.Month08 as Month08, + data.Month09/whpm.Month09 as Month09, + data.Month10/whpm.Month10 as Month10, + data.Month11/whpm.Month11 as Month11, + data.Month12/whpm.Month12 as Month12, + data.YTD/(case + when data.MonthsLoaded = 1 then whpm.Month01 + when data.MonthsLoaded = 2 then whpm.Month01 + whpm.Month02 + when data.MonthsLoaded = 3 then whpm.Month01 + whpm.Month02 + whpm.Month03 + when data.MonthsLoaded = 4 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + when data.MonthsLoaded = 5 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + when data.MonthsLoaded = 6 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + when data.MonthsLoaded = 7 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + when data.MonthsLoaded = 8 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + when data.MonthsLoaded = 9 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + when data.MonthsLoaded = 10 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + whpm.Month10 + when data.MonthsLoaded = 11 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + whpm.Month10 + whpm.Month11 + else whpm.MonthYearly end) as YTD, + data.Total/whpm.MonthYearly as Total + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join [fw].[DimUnitType] ut1 with (readuncommitted) on ut1.UnitTypeID = data.UnitTypeID + inner join [fw].[DimUnitType] ut2 with (readuncommitted) on ut2.Name = 'Hours' + inner join [fw].[DimUnitType] ut3 with (readuncommitted) on ut3.Name = 'FTEs' + inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and data.JobCodeID=0 and ut2.UnitTypeID = pax.UnitTypeID + inner join [client].[FactWorkingHoursPerMonth] whpm with (readuncommitted) on data.FiscalYearID=whpm.FiscalYearID + inner join [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID=data.PayCodeGroupID + where + ut1.Name in('Non-Productive Hours', 'Productive Hours') and pcg.ProductiveClassID in ('2', '3') -- Non-Productive, Productive + and not exists (select 1 from [clientob].[FactPayrollToAccountCrosswalk] pax2 with (readuncommitted) where data.PayCodeGroupID=pax2.PayCodeGroupID and data.JobCodeID=pax2.JobCodeID and ut2.UnitTypeID=pax2.UnitTypeID) + union all + select + data.DepartmentalBudgetID, + pax.AccountID, + data.JobCodeID, + data.PayCodeGroupID, + data.FiscalYearID, + data.TimeClassID, + ut2.UnitTypeID, + data.DataTypeID, + data.Month01 as Month01, + data.Month02 as Month02, + data.Month03 as Month03, + data.Month04 as Month04, + data.Month05 as Month05, + data.Month06 as Month06, + data.Month07 as Month07, + data.Month08 as Month08, + data.Month09 as Month09, + data.Month10 as Month10, + data.Month11 as Month11, + data.Month12 as Month12, + data.YTD, + data.Total + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join [fw].[DimUnitType] ut1 with (readuncommitted) on ut1.UnitTypeID = data.UnitTypeID + inner join [fw].[DimUnitType] ut2 with (readuncommitted) on ut2.Name = 'Hours' + inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and data.JobCodeID=pax.JobCodeID and ut2.UnitTypeID = pax.UnitTypeID + inner join [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID=data.PayCodeGroupID + where + ut1.Name in('Non-Productive Hours', 'Productive Hours') and pcg.ProductiveClassID in ('2', '3') -- Non-Productive, Productive + union all + select + data.DepartmentalBudgetID, + pax.AccountID, + data.JobCodeID, + data.PayCodeGroupID, + data.FiscalYearID, + data.TimeClassID, + ut2.UnitTypeID, + data.DataTypeID, + data.Month01 as Month01, + data.Month02 as Month02, + data.Month03 as Month03, + data.Month04 as Month04, + data.Month05 as Month05, + data.Month06 as Month06, + data.Month07 as Month07, + data.Month08 as Month08, + data.Month09 as Month09, + data.Month10 as Month10, + data.Month11 as Month11, + data.Month12 as Month12, + data.YTD, + data.Total + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join [fw].[DimUnitType] ut1 with (readuncommitted) on ut1.UnitTypeID = data.UnitTypeID + inner join [fw].[DimUnitType] ut2 with (readuncommitted) on ut2.Name = 'Hours' + inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and data.JobCodeID=0 and ut2.UnitTypeID = pax.UnitTypeID + inner join [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID=data.PayCodeGroupID + where + ut1.Name in('Non-Productive Hours', 'Productive Hours') and pcg.ProductiveClassID in ('2', '3') -- Non-Productive, Productive + and not exists (select 1 from [clientob].[FactPayrollToAccountCrosswalk] pax2 with (readuncommitted) where data.PayCodeGroupID=pax2.PayCodeGroupID and data.JobCodeID=pax2.JobCodeID and ut2.UnitTypeID=pax2.UnitTypeID) + union all + select + data.DepartmentalBudgetID, + pax.AccountID, + data.JobCodeID, + data.PayCodeGroupID, + data.FiscalYearID, + data.TimeClassID, + data.UnitTypeID, + data.DataTypeID, + data.Month01 as Month01, + data.Month02 as Month02, + data.Month03 as Month03, + data.Month04 as Month04, + data.Month05 as Month05, + data.Month06 as Month06, + data.Month07 as Month07, + data.Month08 as Month08, + data.Month09 as Month09, + data.Month10 as Month10, + data.Month11 as Month11, + data.Month12 as Month12, + data.YTD, + data.Total + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and data.JobCodeID=pax.JobCodeID and data.UnitTypeID = pax.UnitTypeID + inner join [fw].[DimUnitType] ut1 with (readuncommitted) on pax.UnitTypeID = ut1.UnitTypeID + where + ut1.Name = 'Dollars' + union all + select + data.DepartmentalBudgetID, + pax.AccountID, + data.JobCodeID, + data.PayCodeGroupID, + data.FiscalYearID, + data.TimeClassID, + data.UnitTypeID, + data.DataTypeID, + data.Month01 as Month01, + data.Month02 as Month02, + data.Month03 as Month03, + data.Month04 as Month04, + data.Month05 as Month05, + data.Month06 as Month06, + data.Month07 as Month07, + data.Month08 as Month08, + data.Month09 as Month09, + data.Month10 as Month10, + data.Month11 as Month11, + data.Month12 as Month12, + data.YTD, + data.Total + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and data.JobCodeID=0 and data.UnitTypeID = pax.UnitTypeID + inner join [fw].[DimUnitType] ut1 with (readuncommitted) on pax.UnitTypeID = ut1.UnitTypeID + where + ut1.Name = 'Dollars' + and not exists (select 1 from [clientob].[FactPayrollToAccountCrosswalk] pax2 with (readuncommitted) where data.PayCodeGroupID=pax2.PayCodeGroupID and data.JobCodeID=pax2.JobCodeID and data.UnitTypeID=pax2.UnitTypeID) +GO + + +--------------------------------------------- + +-- ob.viewReportStaffingtoGLAccount_BothUnique +CREATE view [ob].[viewReportStaffingtoGLAccount_BothUnique] as + select + data.DepartmentalBudgetID, + pax.AccountID, + data.JobCodeID, + data.PayCodeGroupID, + data.FiscalYearID, + data.TimeClassID, + ut3.UnitTypeID, + data.DataTypeID, + data.Month01/whpm.Month01 as Month01, + data.Month02/whpm.Month02 as Month02, + data.Month03/whpm.Month03 as Month03, + data.Month04/whpm.Month04 as Month04, + data.Month05/whpm.Month05 as Month05, + data.Month06/whpm.Month06 as Month06, + data.Month07/whpm.Month07 as Month07, + data.Month08/whpm.Month08 as Month08, + data.Month09/whpm.Month09 as Month09, + data.Month10/whpm.Month10 as Month10, + data.Month11/whpm.Month11 as Month11, + data.Month12/whpm.Month12 as Month12, + data.YTD/(case + when data.MonthsLoaded = 1 then whpm.Month01 + when data.MonthsLoaded = 2 then whpm.Month01 + whpm.Month02 + when data.MonthsLoaded = 3 then whpm.Month01 + whpm.Month02 + whpm.Month03 + when data.MonthsLoaded = 4 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + when data.MonthsLoaded = 5 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + when data.MonthsLoaded = 6 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + when data.MonthsLoaded = 7 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + when data.MonthsLoaded = 8 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + when data.MonthsLoaded = 9 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + when data.MonthsLoaded = 10 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + whpm.Month10 + when data.MonthsLoaded = 11 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + whpm.Month10 + whpm.Month11 + else whpm.MonthYearly end) as YTD, + data.Total/whpm.MonthYearly as Total + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join [fw].[DimUnitType] ut1 with (readuncommitted) on ut1.UnitTypeID = data.UnitTypeID + inner join [fw].[DimUnitType] ut2 with (readuncommitted) on ut2.Name = 'Hours' + inner join [fw].[DimUnitType] ut3 with (readuncommitted) on ut3.Name = 'FTEs' + inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and data.JobCodeID=pax.JobCodeID and ut2.UnitTypeID = pax.UnitTypeID + inner join [client].[FactWorkingHoursPerMonth] whpm with (readuncommitted) on data.FiscalYearID=whpm.FiscalYearID + inner join [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID=data.PayCodeGroupID + where + ut1.Name in('Non-Productive Hours', 'Productive Hours') and pcg.ProductiveClassID in ('2', '3') -- Non-Productive, Productive + union all + + select + data.DepartmentalBudgetID, + pax.AccountID, + data.JobCodeID, + data.PayCodeGroupID, + data.FiscalYearID, + data.TimeClassID, + ut2.UnitTypeID, + data.DataTypeID, + data.Month01 as Month01, + data.Month02 as Month02, + data.Month03 as Month03, + data.Month04 as Month04, + data.Month05 as Month05, + data.Month06 as Month06, + data.Month07 as Month07, + data.Month08 as Month08, + data.Month09 as Month09, + data.Month10 as Month10, + data.Month11 as Month11, + data.Month12 as Month12, + data.YTD, + data.Total + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join [fw].[DimUnitType] ut1 with (readuncommitted) on ut1.UnitTypeID = data.UnitTypeID + inner join [fw].[DimUnitType] ut2 with (readuncommitted) on ut2.Name = 'Hours' + inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and data.JobCodeID=pax.JobCodeID and ut2.UnitTypeID = pax.UnitTypeID + inner join [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID=data.PayCodeGroupID + where + ut1.Name in('Non-Productive Hours', 'Productive Hours') and pcg.ProductiveClassID in ('2', '3') -- Non-Productive, Productive + union all + + select + data.DepartmentalBudgetID, + pax.AccountID, + data.JobCodeID, + data.PayCodeGroupID, + data.FiscalYearID, + data.TimeClassID, + data.UnitTypeID, + data.DataTypeID, + data.Month01 as Month01, + data.Month02 as Month02, + data.Month03 as Month03, + data.Month04 as Month04, + data.Month05 as Month05, + data.Month06 as Month06, + data.Month07 as Month07, + data.Month08 as Month08, + data.Month09 as Month09, + data.Month10 as Month10, + data.Month11 as Month11, + data.Month12 as Month12, + data.YTD, + data.Total + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and data.JobCodeID=pax.JobCodeID and data.UnitTypeID = pax.UnitTypeID + inner join [fw].[DimUnitType] ut1 with (readuncommitted) on pax.UnitTypeID = ut1.UnitTypeID + where + ut1.Name = 'Dollars' +GO + + +--------------------------------------------- + +-- ob.viewReportStaffingtoGLAccount_EachJobCode +CREATE view [ob].[viewReportStaffingtoGLAccount_EachJobCode] as + select + data.DepartmentalBudgetID, + pax.AccountID, + data.JobCodeID, + data.PayCodeGroupID, + data.FiscalYearID, + data.TimeClassID, + ut3.UnitTypeID, + data.DataTypeID, + data.Month01/whpm.Month01 as Month01, + data.Month02/whpm.Month02 as Month02, + data.Month03/whpm.Month03 as Month03, + data.Month04/whpm.Month04 as Month04, + data.Month05/whpm.Month05 as Month05, + data.Month06/whpm.Month06 as Month06, + data.Month07/whpm.Month07 as Month07, + data.Month08/whpm.Month08 as Month08, + data.Month09/whpm.Month09 as Month09, + data.Month10/whpm.Month10 as Month10, + data.Month11/whpm.Month11 as Month11, + data.Month12/whpm.Month12 as Month12, + data.YTD/(case + when data.MonthsLoaded = 1 then whpm.Month01 + when data.MonthsLoaded = 2 then whpm.Month01 + whpm.Month02 + when data.MonthsLoaded = 3 then whpm.Month01 + whpm.Month02 + whpm.Month03 + when data.MonthsLoaded = 4 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + when data.MonthsLoaded = 5 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + when data.MonthsLoaded = 6 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + when data.MonthsLoaded = 7 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + when data.MonthsLoaded = 8 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + when data.MonthsLoaded = 9 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + when data.MonthsLoaded = 10 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + whpm.Month10 + when data.MonthsLoaded = 11 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + whpm.Month10 + whpm.Month11 + else whpm.MonthYearly end) as YTD, + data.Total/whpm.MonthYearly as Total + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join [fw].[DimUnitType] ut1 with (readuncommitted) on ut1.UnitTypeID = data.UnitTypeID + inner join [fw].[DimUnitType] ut2 with (readuncommitted) on ut2.Name = 'Hours' + inner join [fw].[DimUnitType] ut3 with (readuncommitted) on ut3.Name = 'FTEs' + inner join [fw].[DimJobCode] djc with (readuncommitted) on data.JobCodeID = djc.JobCodeID + inner join [ob].[DimDepartmentalBudget] ddb with (readuncommitted) on data.DepartmentalBudgetID = ddb.DepartmentalBudgetID + inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.JobCodeID=pax.JobCodeID and ut2.UnitTypeID = pax.UnitTypeID + inner join [client].[FactWorkingHoursPerMonth] whpm with (readuncommitted) on data.FiscalYearID = whpm.FiscalYearID + and case + when djc.WorkWeekOverrideID = -1 and ddb.EntityDefaultWorkWeekID = whpm.WorkWeekID then 1 + when djc.WorkWeekOverrideID != -1 and djc.WorkWeekOverrideID = whpm.WorkWeekID then 1 + else 0 + end = 1 + inner join [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID = data.PayCodeGroupID + where + ut1.Name in('Non-Productive Hours', 'Productive Hours') and pcg.ProductiveClassID in ('2', '3') -- Non-Productive, Productive + union all + + select + data.DepartmentalBudgetID, + pax.AccountID, + data.JobCodeID, + data.PayCodeGroupID, + data.FiscalYearID, + data.TimeClassID, + ut2.UnitTypeID, + data.DataTypeID, + data.Month01 as Month01, + data.Month02 as Month02, + data.Month03 as Month03, + data.Month04 as Month04, + data.Month05 as Month05, + data.Month06 as Month06, + data.Month07 as Month07, + data.Month08 as Month08, + data.Month09 as Month09, + data.Month10 as Month10, + data.Month11 as Month11, + data.Month12 as Month12, + data.YTD, + data.Total + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join [fw].[DimUnitType] ut1 with (readuncommitted) on ut1.UnitTypeID = data.UnitTypeID + inner join [fw].[DimUnitType] ut2 with (readuncommitted) on ut2.Name = 'Hours' + inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.JobCodeID=pax.JobCodeID and ut2.UnitTypeID = pax.UnitTypeID + inner join [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID=data.PayCodeGroupID + where + ut1.Name in('Non-Productive Hours', 'Productive Hours') and pcg.ProductiveClassID in ('2', '3') -- Non-Productive, Productive + union all + + select + data.DepartmentalBudgetID, + pax.AccountID, + data.JobCodeID, + data.PayCodeGroupID, + data.FiscalYearID, + data.TimeClassID, + data.UnitTypeID, + data.DataTypeID, + data.Month01 as Month01, + data.Month02 as Month02, + data.Month03 as Month03, + data.Month04 as Month04, + data.Month05 as Month05, + data.Month06 as Month06, + data.Month07 as Month07, + data.Month08 as Month08, + data.Month09 as Month09, + data.Month10 as Month10, + data.Month11 as Month11, + data.Month12 as Month12, + data.YTD, + data.Total + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.JobCodeID=pax.JobCodeID and data.UnitTypeID = pax.UnitTypeID + inner join [fw].[DimUnitType] ut1 with (readuncommitted) on pax.UnitTypeID = ut1.UnitTypeID + where + ut1.Name = 'Dollars' +GO + + +--------------------------------------------- + +-- ob.viewReportStaffingtoGLAccount_EachPayCodeGroup +CREATE view [ob].[viewReportStaffingtoGLAccount_EachPayCodeGroup] as + select + data.DepartmentalBudgetID, + pax.AccountID, + data.JobCodeID, + data.PayCodeGroupID, + data.FiscalYearID, + data.TimeClassID, + ut3.UnitTypeID, + data.DataTypeID, + data.Month01/whpm.Month01 as Month01, + data.Month02/whpm.Month02 as Month02, + data.Month03/whpm.Month03 as Month03, + data.Month04/whpm.Month04 as Month04, + data.Month05/whpm.Month05 as Month05, + data.Month06/whpm.Month06 as Month06, + data.Month07/whpm.Month07 as Month07, + data.Month08/whpm.Month08 as Month08, + data.Month09/whpm.Month09 as Month09, + data.Month10/whpm.Month10 as Month10, + data.Month11/whpm.Month11 as Month11, + data.Month12/whpm.Month12 as Month12, + data.YTD/(case + when data.MonthsLoaded = 1 then whpm.Month01 + when data.MonthsLoaded = 2 then whpm.Month01 + whpm.Month02 + when data.MonthsLoaded = 3 then whpm.Month01 + whpm.Month02 + whpm.Month03 + when data.MonthsLoaded = 4 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + when data.MonthsLoaded = 5 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + when data.MonthsLoaded = 6 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + when data.MonthsLoaded = 7 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + when data.MonthsLoaded = 8 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + when data.MonthsLoaded = 9 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + when data.MonthsLoaded = 10 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + whpm.Month10 + when data.MonthsLoaded = 11 then whpm.Month01 + whpm.Month02 + whpm.Month03 + whpm.Month04 + whpm.Month05 + whpm.Month06 + whpm.Month07 + whpm.Month08 + whpm.Month09 + whpm.Month10 + whpm.Month11 + else whpm.MonthYearly end) as YTD, + data.Total/whpm.MonthYearly as Total + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join [fw].[DimUnitType] ut1 with (readuncommitted) on ut1.UnitTypeID = data.UnitTypeID + inner join [fw].[DimUnitType] ut2 with (readuncommitted) on ut2.Name = 'Hours' + inner join [fw].[DimUnitType] ut3 with (readuncommitted) on ut3.Name = 'FTEs' + inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and ut2.UnitTypeID = pax.UnitTypeID + inner join [client].[FactWorkingHoursPerMonth] whpm with (readuncommitted) on data.FiscalYearID=whpm.FiscalYearID + inner join [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID=data.PayCodeGroupID + where + ut1.Name in('Non-Productive Hours', 'Productive Hours') and pcg.ProductiveClassID in ('2', '3') -- Non-Productive, Productive + union all + + select + data.DepartmentalBudgetID, + pax.AccountID, + data.JobCodeID, + data.PayCodeGroupID, + data.FiscalYearID, + data.TimeClassID, + ut2.UnitTypeID, + data.DataTypeID, + data.Month01 as Month01, + data.Month02 as Month02, + data.Month03 as Month03, + data.Month04 as Month04, + data.Month05 as Month05, + data.Month06 as Month06, + data.Month07 as Month07, + data.Month08 as Month08, + data.Month09 as Month09, + data.Month10 as Month10, + data.Month11 as Month11, + data.Month12 as Month12, + data.YTD, + data.Total + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join [fw].[DimUnitType] ut1 with (readuncommitted) on ut1.UnitTypeID = data.UnitTypeID + inner join [fw].[DimUnitType] ut2 with (readuncommitted) on ut2.Name = 'Hours' + inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and ut2.UnitTypeID = pax.UnitTypeID + inner join [fw].[DimPayCodeGroup] pcg with (readuncommitted) on pcg.PayCodeGroupID=data.PayCodeGroupID + where + ut1.Name in('Non-Productive Hours', 'Productive Hours') and pcg.ProductiveClassID in ('2', '3') -- Non-Productive, Productive + union all + + select + data.DepartmentalBudgetID, + pax.AccountID, + data.JobCodeID, + data.PayCodeGroupID, + data.FiscalYearID, + data.TimeClassID, + data.UnitTypeID, + data.DataTypeID, + data.Month01 as Month01, + data.Month02 as Month02, + data.Month03 as Month03, + data.Month04 as Month04, + data.Month05 as Month05, + data.Month06 as Month06, + data.Month07 as Month07, + data.Month08 as Month08, + data.Month09 as Month09, + data.Month10 as Month10, + data.Month11 as Month11, + data.Month12 as Month12, + data.YTD, + data.Total + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join [clientob].[FactPayrollToAccountCrosswalk] pax with (readuncommitted) on data.PayCodeGroupID=pax.PayCodeGroupID and data.UnitTypeID = pax.UnitTypeID + inner join [fw].[DimUnitType] ut1 with (readuncommitted) on pax.UnitTypeID = ut1.UnitTypeID + where + ut1.Name = 'Dollars' +GO + + +--------------------------------------------- + +-- ob.viewSamplingOBServiceLineRevenueFromFactFinancialServiceLineRevenue +/************************************************************ +** Author: Bart Lewis +** Create Date: 4/22/2015 +** Description: Budget Service Line Revenue Sampling View From Import Tables +** Last Modified: 4/22/2015 +** GM Release: 2015.3 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + +Create View [ob].[viewSamplingOBServiceLineRevenueFromFactFinancialServiceLineRevenue] As + +select + [DataTypeID] + , [FiscalYearID] + , [FiscalMonthID] + , [ModelingServiceLineID] + , [PayorID] + , [PayorGroupID] + , [OBForecastDetailID] + , [OBServiceLinePlanID] + , [TimeClassID] + , [UnitTypeID] + , [HistoryItemGUID] + , [TransactionID] + , ISNULL(Month01, 0) [Month01] + , ISNULL(Month02, 0) [Month02] + , ISNULL(Month03, 0) [Month03] + , ISNULL(Month04, 0) [Month04] + , ISNULL(Month05, 0) [Month05] + , ISNULL(Month06, 0) [Month06] + , ISNULL(Month07, 0) [Month07] + , ISNULL(Month08, 0) [Month08] + , ISNULL(Month09, 0) [Month09] + , ISNULL(Month10, 0) [Month10] + , ISNULL(Month11, 0) [Month11] + , ISNULL(Month12, 0) [Month12] + , ISNULL(Month00, 0) [Yearly] + , (ISNULL(Month01, 0) + +ISNULL(Month02, 0) + +ISNULL(Month03, 0) + +ISNULL(Month04, 0) + +ISNULL(Month05, 0) + +ISNULL(Month06, 0) + +ISNULL(Month07, 0) + +ISNULL(Month08, 0) + +ISNULL(Month09, 0) + +ISNULL(Month10, 0) + +ISNULL(Month11, 0) + +ISNULL(Month12, 0) + +ISNULL(Month00, 0)) as [Total] +from +( + SELECT + 4 [DataTypeID] + , c.[FiscalYearID] + , c.[FiscalMonthID] + , m.[ModelingServiceLineID] + , p.[PayorID] + , pg.[PayorGroupID] + , ob.[OBForecastDetailID] + , slp.[OBServiceLinePlanID] + , c.[TimeClassID] + , ob.[UnitTypeID] + , c.[Value] as [Amount] + , fm.[MonthColumnName] + , c.[HistoryItemGUID] + , c.[TransactionID] + FROM [int].[FactFinancialServiceLineRevenue] c + inner join [fw].[DimModelingServiceLine] m on c.ServiceLineID=m.ServiceLineID and c.AgeCohortID=m.AgeCohortID and c.MedicalSurgicalID=m.MedicalSurgicalID and c.PatientClassID=m.PatientClassID + inner join [fw].[DimForecastDetail] fd on c.ForecastDetailID=fd.ForecastDetailID + inner join [ob].[DimOBForecastDetail] ob on ob.OBForecastDetailID=fd.OBForecastDetailID + inner join [fw].[DimPayor] p on p.PayorID=c.PayorID + inner join [fw].[DimPayorGroup] pg on c.PayorGroupID=pg.PayorGroupID + inner join [fw].[DimEntity] e on c.EntityID=e.EntityID + inner join [ob].[DimOBServiceLinePlan] slp on e.EntityID=slp.EntityID and slp.IsDeleted=0 + inner join [fw].[DimFiscalMonth] fm on c.FiscalMonthID=fm.FiscalMonthID +) as data +PIVOT +( +SUM(Amount) for MonthColumnName in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12],[Month00]) +) as pvt +GO + + +--------------------------------------------- + +-- ob.viewSystemCenterAccess +create view [ob].[viewSystemCenterAccess] +as +select + s.SectionGUID, + s.Name as SectionName, + c.CategoryGUID, + c.Name as CategoryName, + m.ModuleGUID, + m.Name as ModuleName, + ISNULL(p.ReadValue, 0) ReadValue, + ISNULL(p.WriteValue, 0) WriteValue, + ISNULL(p.PermissionGUID, '00000000-0000-0000-0000-000000000000') PermissionGUID + from + SystemCenterSection s + inner join SystemCenterCategory c on s.CategoryGUID = c.CategoryGUID + inner join SystemCenterModule m on c.ModuleGUID = m.ModuleGUID + left join S3SimplePermission p on s.SectionGUID = p.LootID and p.IdentityGUID = (select UserGroupGUID from UserGroup where Name = 'ob - local administrator') + where + m.Name in('General', 'Operating Budgeting') + and s.Name in('Detailed Adjustment Import', 'Budget Import', 'Role Assignments', 'Manage Global Assumptions', 'Budget-Level Assumptions', 'System-Generated Statistics') + and c.IsMaintenanceMode = 1 +GO + + +--------------------------------------------- + +-- ob.viewSystemSetting +create view ob.viewSystemSetting +as + select * from ob.SystemSetting + where + Name not like 'AP%' + and Name not like '%ABB%' + and Name not like '%APE%' + and Description not like '%APE%' +GO + + +--------------------------------------------- + +-- ob.viewValidDataTypeTimeClassFiscalYearCombos +CREATE view [ob].[viewValidDataTypeTimeClassFiscalYearCombos] +as + select + DataTypeID = dt.DataTypeID, + FiscalYearID = fy.FiscalYearID, + TimeClassID = tc.TimeClassID, + IsCY = case fy.FiscalYearID + when dbs.Setting then 1 + else 0 + end + from [dbo].[DBSetting] dbs with (readuncommitted) + cross join [fw].[DimDataType] dt with (readuncommitted) + cross join [fw].[DimFiscalYear] fy with (readuncommitted) + cross join [fw].[DimTimeClass] tc with (readuncommitted) + where 1=1 + and dbs.Name = 'OB_Current_Year' + and + ( + (dt.DataTypeID = 4 and fy.FiscalYearID = dbs.Setting-1 and tc.TimeClassID = 1) --PY Actual + or + (dt.DataTypeID = 4 and fy.FiscalYearID = dbs.Setting and tc.TimeClassID = 1) --CY Actual + or + (dt.DataTypeID = 4 and fy.FiscalYearID = dbs.Setting and tc.TimeClassID = 2) --CY Budget + or + (dt.DataTypeID = 3 and fy.FiscalYearID = dbs.Setting and tc.TimeClassID = 12) --CY Projection + or + (dt.DataTypeID = 3 and fy.FiscalYearID = dbs.Setting+1 and tc.TimeClassID = 18) --BY Baseline + or + (dt.DataTypeID = 3 and fy.FiscalYearID = dbs.Setting+1 and tc.TimeClassID = 2) --BY Budget + ) +GO + + +--------------------------------------------- + +--------------------------------------------- +-- PROCEDURES +--------------------------------------------- + +-- ob.procAllocationSampleAll +create proc [ob].[procAllocationSampleAll] + @isDebugOnly bit = 0 +as +/********************************************************************************** +** Author: Corey Becker (Donatello) +** Create Date: 2016-02-11 +** Description: Loops through allocation sampling by execution order +** Last Modified: 2016-02-11 +** GM Release: 2016.2 +********************************************************************************** +** Change History +********************************************************************************** +** CID Date Author WI Description +** +**********************************************************************************/ + +------------------------------------------------------------------------------------------------ +------------------------------- Variable declarations ------------------------------------------ +------------------------------------------------------------------------------------------------ +declare @sql as nvarchar(max) = '' + +------------------------------------------------------------------------------------------------ +----------------- Delete all existing allocation data for affected departments ----------------- +------------------------------------------------------------------------------------------------ + if @isDebugOnly=1 + begin + set @sql = 'Proc will delete all existing allocation data for affected departments. Preview using this select statement: + +select fct.* +from [clientob].[FactAccount] fct + inner join [data].[ScoreFillin_Account] sf + on fct.AccountID=sf.AccountID + inner join [ob].[DimAccountPH] ph + on sf.AccountPHID=ph.AccountPHID + inner join [ob].[viewAllocationValues] av + on fct.DepartmentalBudgetID=av.DepartmentalBudgetTargetID +where 1=1 + and ph.Name like ''%Allocated'' + and fct.TimeClassID=2 + and fct.FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name=''OB_Current_Year'') + ' + print(@sql) + end + else + begin + delete fct + from [clientob].[FactAccount] fct + inner join [data].[ScoreFillin_Account] sf + on fct.AccountID=sf.AccountID + inner join [ob].[DimAccountPH] ph + on sf.AccountPHID=ph.AccountPHID + inner join [ob].[viewAllocationValues] av + on fct.DepartmentalBudgetID=av.DepartmentalBudgetTargetID + where 1=1 + and ph.Name like '%Allocated' + and fct.TimeClassID=2 + and fct.FiscalYearID=(select Setting+1 from [dbo].[DBSetting] where Name='OB_Current_Year') + end + +------------------------------------------------------------------------------------------------ +------------------- xxx --------------------- +------------------------------------------------------------------------------------------------ +declare @currentExecOrder smallint + +if @isDebugOnly=1 + begin + print ('Procedure will then run the following: ') + + declare allocationCursor CURSOR FAST_FORWARD FOR + select distinct dm.ExecutionOrder + from [ob].[viewDimOBAllocation] dm + where OBAllocationID<>0 + + open allocationCursor; + + FETCH NEXT FROM allocationCursor into @currentExecOrder + WHILE (@@FETCH_STATUS = 0) + BEGIN + set @sql = 'exec [clientob].[procAllocationSample] @execOrder = '+cast(@currentExecOrder as nvarchar(8)) + print(@sql) + FETCH NEXT FROM allocationCursor into @currentExecOrder + END + close allocationCursor; + deallocate allocationCursor; + end +else + begin + declare allocationCursor CURSOR FAST_FORWARD FOR + select distinct dm.ExecutionOrder + from [ob].[viewDimOBAllocation] dm + where OBAllocationID<>0 + + open allocationCursor; + + FETCH NEXT FROM allocationCursor into @currentExecOrder + WHILE (@@FETCH_STATUS = 0) + BEGIN + set @sql = 'exec [clientob].[procAllocationSample] @execOrder = '+cast(@currentExecOrder as nvarchar(8)) + exec(@sql) + FETCH NEXT FROM allocationCursor into @currentExecOrder + END + close allocationCursor; + deallocate allocationCursor; + end + + + + +------------------------------------------------------------------------------------------------ +----------------------------------- Invalidate model cache ------------------------------------- +------------------------------------------------------------------------------------------------ +if @isDebugOnly=1 + begin + print('Then model caches are invalidated, if present') + end +else + begin + if exists + ( + select 1 + from [dbo].[XPlan] + where 1=1 + and PlanTypeGUID='05512126-3EB6-4DA4-AF6E-BC2BC2724B8B' + and ModelTemplateGUID<>'00000000-0000-0000-0000-000000000000' + and IsDeletedPlan=0 + and IsModelWorkbookCached=1 + ) + begin + exec [dbo].[procInvalidateModelWorkbookCacheByPlanType] + @planTypeGUID = '05512126-3EB6-4DA4-AF6E-BC2BC2724B8B', + @source = 'procFactAllocationSample' + end + end + +------------------------------------------------------------------------------------------------ +----------------------------------------- Log Script ------------------------------------------- +------------------------------------------------------------------------------------------------ +if @isDebugOnly=1 + begin + print('Finally, the script is logged') + end +else + begin + declare @higuid2 uniqueidentifier + exec [dbo].[procLogScript] + @desc = 'Allocation Sample All Complete', + @higuid = @higuid2 output + end + +return +GO + + +--------------------------------------------- + +-- ob.procBudgetStampOffInsert +/************************************************************************************************************************ +** Author: Mike Schmitz +** Create Date: 2014-09-15 +** Description: Populates Budget Data into the Budget Stamp-Off tables +** Last Modified: 2014-09-15 +** GM Release: 2014.4 +************************************************************************************************************************** +** Change History +************************************************************************************************************************** +** CID Date Author WI Description +** 1 8-24-2015 bjl comment out incorrect value filters +*************************************************************************************************************************/ +CREATE proc [ob].[procBudgetStampOffInsert] as + +/************** Logging *********************************************************/ +declare @higuid uniqueidentifier +exec procLogScript 'Operating Budget Stamp-Off Insert' , @higuid output +print 'Beginning insert, historyitemguid: ' + cast(@higuid as varchar(36)) + +/************** Insert **********************************************************/ +declare @FiscalYearID int = (select Setting+1 from [dbo].[DBSetting] where Name = 'OB_Current_Year') + +--FactAccount +truncate table [clientob].[FactAccountBudgetStampOff] + +insert into [clientob].[FactAccountBudgetStampOff] (DepartmentalBudgetID, AccountID, FiscalYearID, TimeClassID, UnitTypeID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, Yearly, HistoryItemGUID) + + select + DepartmentalBudgetID, + AccountID, + FiscalYearID, + TimeClassID, + UnitTypeID, + sum(Month01), + sum(Month02), + sum(Month03), + sum(Month04), + sum(Month05), + sum(Month06), + sum(Month07), + sum(Month08), + sum(Month09), + sum(Month10), + sum(Month11), + sum(Month12), + sum(Yearly), + @higuid + from + [clientob].[FactAccount] + where IsDeleted=0 and TimeClassID = '2' and FiscalYearID = @FiscalYearID +--CID 1 Begin +-- and (Month01<>0 or Month02<>0 or Month03<>0 or Month04<>0 or Month05<>0 or Month06<>0 or Month07<>0 or Month08<>0 or Month09<>0 or Month10<>0 or Month11<>0 or Month12<>0 or Yearly<>0) +--CID 1 End + group by + DepartmentalBudgetID, + AccountID, + FiscalYearID, + TimeClassID, + UnitTypeID + +--FactGlobalStatistics +truncate table [clientob].[FactGlobalStatisticsBudgetStampOff] + +insert into [clientob].[FactGlobalStatisticsBudgetStampOff] (TimeClassID,FiscalYearID,UnitTypeID,OBGlobalStatisticID,OBGlobalStatisticsPlanID,Month01,Month02,Month03,Month04,Month05,Month06,Month07,Month08,Month09,Month10,Month11,Month12,Yearly,HistoryItemGUID) + + select + TimeClassID, + FiscalYearID, + UnitTypeID, + OBGlobalStatisticID, + OBGlobalStatisticsPlanID, + sum(Month01), + sum(Month02), + sum(Month03), + sum(Month04), + sum(Month05), + sum(Month06), + sum(Month07), + sum(Month08), + sum(Month09), + sum(Month10), + sum(Month11), + sum(Month12), + sum(Yearly), + @higuid + from + [clientob].[FactGlobalStatistics] + where IsDeleted=0 and TimeClassID = '2' and FiscalYearID = @FiscalYearID +--CID 1 Begin +-- and (Month01<>0 or Month02<>0 or Month03<>0 or Month04<>0 or Month05<>0 or Month06<>0 or Month07<>0 or Month08<>0 or Month09<>0 or Month10<>0 or Month11<>0 or Month12<>0 or Yearly<>0) +--CID 1 End + group by + TimeClassID, + FiscalYearID, + UnitTypeID, + OBGlobalStatisticID, + OBGlobalStatisticsPlanID + +--FactReimbursement +truncate table [clientob].[FactReimbursementBudgetStampOff] + +insert into [clientob].[FactReimbursementBudgetStampOff] (FiscalYearID,OBForecastDetailID,OBReimbursementPlanID,PatientReimbursementGroupID,PayorID,PayorGroupID,TimeClassID,UnitTypeID,Month01,Month02,Month03,Month04,Month05,Month06,Month07,Month08,Month09,Month10,Month11,Month12,Yearly,HistoryItemGUID) + + select + FiscalYearID, + OBForecastDetailID, + OBReimbursementPlanID, + PatientReimbursementGroupID, + PayorID, + PayorGroupID, + TimeClassID, + UnitTypeID, + sum(Month01), + sum(Month02), + sum(Month03), + sum(Month04), + sum(Month05), + sum(Month06), + sum(Month07), + sum(Month08), + sum(Month09), + sum(Month10), + sum(Month11), + sum(Month12), + sum(Yearly), + @higuid + from + [clientob].[FactReimbursement] + where IsDeleted=0 and TimeClassID = '2' and FiscalYearID = @FiscalYearID +--CID 1 Begin +-- and (Month01<>0 or Month02<>0 or Month03<>0 or Month04<>0 or Month05<>0 or Month06<>0 or Month07<>0 or Month08<>0 or Month09<>0 or Month10<>0 or Month11<>0 or Month12<>0 or Yearly<>0) +--CID 1 End + group by + FiscalYearID, + OBForecastDetailID, + OBReimbursementPlanID, + PatientReimbursementGroupID, + PayorID, + PayorGroupID, + TimeClassID, + UnitTypeID + +--FactReimbursementAccount +truncate table [clientob].[FactReimbursementAccountBudgetStampOff] + +insert into [clientob].[FactReimbursementAccountBudgetStampOff] (AccountID,FiscalYearID,OBReimbursementPlanID,PatientReimbursementGroupID,TimeClassID,UnitTypeID,Month01,Month02,Month03,Month04,Month05,Month06,Month07,Month08,Month09,Month10,Month11,Month12,Yearly,HistoryItemGUID) + + select + AccountID, + FiscalYearID, + OBReimbursementPlanID, + PatientReimbursementGroupID, + TimeClassID, + UnitTypeID, + sum(Month01), + sum(Month02), + sum(Month03), + sum(Month04), + sum(Month05), + sum(Month06), + sum(Month07), + sum(Month08), + sum(Month09), + sum(Month10), + sum(Month11), + sum(Month12), + sum(Yearly), + @higuid + from + [clientob].[FactReimbursementAccount] + where IsDeleted=0 and TimeClassID = '2' and FiscalYearID = @FiscalYearID +--CID 1 Begin +-- and (Month01<>0 or Month02<>0 or Month03<>0 or Month04<>0 or Month05<>0 or Month06<>0 or Month07<>0 or Month08<>0 or Month09<>0 or Month10<>0 or Month11<>0 or Month12<>0 or Yearly<>0) +--CID 1 End + group by + AccountID, + FiscalYearID, + OBReimbursementPlanID, + PatientReimbursementGroupID, + TimeClassID, + UnitTypeID + +--FactStaffingPC +truncate table [clientob].[FactStaffingPCBudgetStampOff] + +insert into [clientob].[FactStaffingPCBudgetStampOff] (EmployeeID,FiscalYearID,JobCodeID,DepartmentalBudgetID,TimeClassID,PayCodeGroupID,UnitTypeID,Month01,Month02,Month03,Month04,Month05,Month06,Month07,Month08,Month09,Month10,Month11,Month12,Yearly,HistoryItemGUID) + + select + EmployeeID, + FiscalYearID, + JobCodeID, + DepartmentalBudgetID, + TimeClassID, + PayCodeGroupID, + UnitTypeID, + sum(Month01), + sum(Month02), + sum(Month03), + sum(Month04), + sum(Month05), + sum(Month06), + sum(Month07), + sum(Month08), + sum(Month09), + sum(Month10), + sum(Month11), + sum(Month12), + sum(Yearly), + @higuid + from + [clientob].[FactStaffingPC] + where IsDeleted=0 and TimeClassID = '2' and FiscalYearID = @FiscalYearID +--CID 1 Begin +-- and (Month01<>0 or Month02<>0 or Month03<>0 or Month04<>0 or Month05<>0 or Month06<>0 or Month07<>0 or Month08<>0 or Month09<>0 or Month10<>0 or Month11<>0 or Month12<>0 or Yearly<>0) +--CID 1 End + group by + EmployeeID, + FiscalYearID, + JobCodeID, + DepartmentalBudgetID, + TimeClassID, + PayCodeGroupID, + UnitTypeID + +--FactCDM +truncate table [clientob].[FactCDMBudgetStampOff] + +insert into [clientob].[FactCDMBudgetStampOff] (ChargeCodeID,FiscalYearID,DepartmentalBudgetID,OBForecastDetailID,PatientClassID,TimeClassID,UnitTypeID,Month01,Month02,Month03,Month04,Month05,Month06,Month07,Month08,Month09,Month10,Month11,Month12,Yearly,HistoryItemGUID) + + select + ChargeCodeID, + FiscalYearID, + DepartmentalBudgetID, + OBForecastDetailID, + PatientClassID, + TimeClassID, + UnitTypeID, + sum(Month01), + sum(Month02), + sum(Month03), + sum(Month04), + sum(Month05), + sum(Month06), + sum(Month07), + sum(Month08), + sum(Month09), + sum(Month10), + sum(Month11), + sum(Month12), + sum(Yearly), + @higuid + from + [clientob].[FactCDM] + where IsDeleted=0 and TimeClassID = '2' and FiscalYearID = @FiscalYearID +--CID 1 Begin +-- and (Month01<>0 or Month02<>0 or Month03<>0 or Month04<>0 or Month05<>0 or Month06<>0 or Month07<>0 or Month08<>0 or Month09<>0 or Month10<>0 or Month11<>0 or Month12<>0 or Yearly<>0) +--CID 1 End + group by + ChargeCodeID, + FiscalYearID, + DepartmentalBudgetID, + OBForecastDetailID, + PatientClassID, + TimeClassID, + UnitTypeID + +--FactServiceLine +truncate table [clientob].[FactServiceLineBudgetStampOff] + +insert into [clientob].[FactServiceLineBudgetStampOff] (FiscalYearID,ModelingServiceLineID,TimeClassID,UnitTypeID,OBForecastDetailID,OBServiceLinePlanID,Month01,Month02,Month03,Month04,Month05,Month06,Month07,Month08,Month09,Month10,Month11,Month12,Yearly,HistoryItemGUID) + + select + FiscalYearID, + ModelingServiceLineID, + TimeClassID, + UnitTypeID, + OBForecastDetailID, + OBServiceLinePlanID, + sum(Month01), + sum(Month02), + sum(Month03), + sum(Month04), + sum(Month05), + sum(Month06), + sum(Month07), + sum(Month08), + sum(Month09), + sum(Month10), + sum(Month11), + sum(Month12), + sum(Yearly), + @higuid + from + [clientob].[FactServiceLine] + where IsDeleted=0 and TimeClassID = '2' and FiscalYearID = @FiscalYearID +--CID 1 Begin +-- and (Month01<>0 or Month02<>0 or Month03<>0 or Month04<>0 or Month05<>0 or Month06<>0 or Month07<>0 or Month08<>0 or Month09<>0 or Month10<>0 or Month11<>0 or Month12<>0 or Yearly<>0) +--CID 1 End + group by + FiscalYearID, + ModelingServiceLineID, + TimeClassID, + UnitTypeID, + OBForecastDetailID, + OBServiceLinePlanID + +--FactProvider +truncate table [clientob].[FactProviderBudgetStampOff] + +insert into [clientob].[FactProviderBudgetStampOff] (FiscalYearID,UnitTypeID,DepartmentalBudgetID,TimeClassID,ProviderID,OBForecastDetailID,Month01,Month02,Month03,Month04,Month05,Month06,Month07,Month08,Month09,Month10,Month11,Month12,Yearly,HistoryItemGUID) + + select + FiscalYearID, + UnitTypeID, + DepartmentalBudgetID, + TimeClassID, + ProviderID, + OBForecastDetailID, + sum(Month01), + sum(Month02), + sum(Month03), + sum(Month04), + sum(Month05), + sum(Month06), + sum(Month07), + sum(Month08), + sum(Month09), + sum(Month10), + sum(Month11), + sum(Month12), + sum(Yearly), + @higuid + from + [clientob].[FactProvider] + where IsDeleted=0 and TimeClassID = '2' and FiscalYearID = @FiscalYearID +--CID 1 Begin +-- and (Month01<>0 or Month02<>0 or Month03<>0 or Month04<>0 or Month05<>0 or Month06<>0 or Month07<>0 or Month08<>0 or Month09<>0 or Month10<>0 or Month11<>0 or Month12<>0 or Yearly<>0) +--CID 1 End + group by + FiscalYearID, + UnitTypeID, + DepartmentalBudgetID, + TimeClassID, + ProviderID, + OBForecastDetailID + +RETURN +GO + + +--------------------------------------------- + +-- ob.procBudgetUploadFactAccountSample +CREATE procedure ob.procBudgetUploadFactAccountSample + @historyItemGUID uniqueidentifier +as + delete fa + from + clientob.FactAccount fa + where + fa.DataTypeID = 3 --output + and fa.TimeClassID != 1 --actual + and exists( + select 1 + from + clientob.FactAccountNonReporting nr + where + nr.HistoryItemGUID = @historyItemGUID + and nr.AccountID = fa.AccountID + and nr.FiscalYearID = fa.FiscalYearID + and nr.DepartmentalBudgetID = fa.DepartmentalBudgetID + and nr.TimeClassID = fa.TimeClassID + and nr.UnitTypeID = fa.UnitTypeID + ); + + insert into clientob.FactAccount (AccountID, DataTypeID, FiscalYearID, DepartmentalBudgetID, TimeClassID, UnitTypeID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, Yearly, MonthsLoaded, IsDeleted, TransactionID, HistoryItemGUID) + select fa.AccountID, 3 as DataTypeID, fa.FiscalYearID, fa.DepartmentalBudgetID, fa.TimeClassID, fa.UnitTypeID, fa.Month01, fa.Month02, fa.Month03, fa.Month04, fa.Month05, fa.Month06, fa.Month07, fa.Month08, fa.Month09, fa.Month10, fa.Month11, fa.Month12, fa.Yearly, fa.MonthsLoaded, fa.IsDeleted, fa.TransactionID, fa.HistoryItemGUID + from clientob.FactAccountNonReporting fa + where fa.HistoryItemGUID = @historyItemGUID and fa.DataTypeID = 4 and fa.TimeClassID != 1; +GO + + +--------------------------------------------- + +-- ob.procCAPOperationsToOBSubTable_Transfer +CREATE proc [ob].[procCAPOperationsToOBSubTable_Transfer] +/**************************************************************************************************** +** Author: cbb +** Create Date: 2017.02.14 +** Description: Transfer capital revenue and expenses to department budget +** Last Modified: 2017.02.14 +** GM Release: 2017.2.0 +**************************************************************************************************** +** Change History +**************************************************************************************************** +** CID Date Author WI Description +** +****************************************************************************************************/ +as + begin +-------------------------------------------------------------------------------------------------- +-- Variables +-------------------------------------------------------------------------------------------------- + declare @higuid uniqueidentifier + + declare @currYear int + select @currYear = Setting from [dbo].[DBSetting] where Name = 'OB_Current_Year' + + declare @planRefreshList as nvarchar(max) = '' + +-------------------------------------------------------------------------------------------------- +-- Logging +-------------------------------------------------------------------------------------------------- + exec procLogScript 'Transfer project pro forma financials to OB sub-table composite' , @higuid output + --print 'Beginning update, historyguid: ' + cast(@higuid as varchar(36)) + +-------------------------------------------------------------------------------------------------- +-- Create temp table +-------------------------------------------------------------------------------------------------- + create table #dataagg + ( + [TimeClassID] tinyint, + [FiscalYearID] smallint, + [DepartmentalBudgetID] int, + [AccountID] int, + [UnitTypeID] tinyint, + [AssumptionID] int, + [Month01] decimal(19,4), + [Month02] decimal(19,4), + [Month03] decimal(19,4), + [Month04] decimal(19,4), + [Month05] decimal(19,4), + [Month06] decimal(19,4), + [Month07] decimal(19,4), + [Month08] decimal(19,4), + [Month09] decimal(19,4), + [Month10] decimal(19,4), + [Month11] decimal(19,4), + [Month12] decimal(19,4), + [Yearly] decimal(19,4), + [Total] decimal(31,4), + [Comment] nvarchar(4000), + [IsDeleted] bit, + [HistoryItemGUID] uniqueidentifier, + [TransactionID] int, + [AdjustmentCategoryID] int + ) + +-------------------------------------------------------------------------------------------------- +-- Populate temp table +-------------------------------------------------------------------------------------------------- + insert into #dataagg + ( + [TimeClassID], + [FiscalYearID], + [DepartmentalBudgetID], + [AccountID], + [UnitTypeID], + [AssumptionID], + [Month01], + [Month02], + [Month03], + [Month04], + [Month05], + [Month06], + [Month07], + [Month08], + [Month09], + [Month10], + [Month11], + [Month12], + [Yearly], + [Comment], + [HistoryItemGUID], + [TransactionID], + [AdjustmentCategoryID] + ) + select + [TimeClassID] = case fct.FiscalYearID + when @currYear then 12 + else 2 + end, + [FiscalYearID] = fct.FiscalYearID, + [DepartmentalBudgetID] = ddb.DepartmentalBudgetID, + [AccountID] = fd.AccountID, + [UnitTypeID] = fct.UnitTypeID, + [AssumptionID] = 18, + [Month01] = sum(fct.Month01), + [Month02] = sum(fct.Month02), + [Month03] = sum(fct.Month03), + [Month04] = sum(fct.Month04), + [Month05] = sum(fct.Month05), + [Month06] = sum(fct.Month06), + [Month07] = sum(fct.Month07), + [Month08] = sum(fct.Month08), + [Month09] = sum(fct.Month09), + [Month10] = sum(fct.Month10), + [Month11] = sum(fct.Month11), + [Month12] = sum(fct.Month12), + [Yearly] = sum(fct.Yearly), + [Comment] = 'Transfer from Capital - Model: ' + dp.Name + ' - Forecast Line: ' + fd.Name, + [HistoryItemGUID] = @higuid, + [TransactionID] = -99, + [AdjustmentCategoryID] = 0 + from [clientcap].[FactCAPProjectOperationsMonthly] fct + inner join [cap].[viewDimProject] dp + on fct.ProjectID = dp.ProjectID + inner join [cap].[viewDimForecastDetail] fd + on fct.CAPForecastDetailID=fd.CAPForecastDetailID + inner join [ob].[viewDimDepartmentalBudget] ddb + on dp.DepartmentID = ddb.DepartmentID + where 1=1 + and fct.IsDeleted = 0 + and dp.IncludeinOB = 1 + and fd.AccountID > 0 + and fct.UnitTypeID = 34 + and fct.FiscalYearID in (@currYear, @currYear+1) + group by + fct.FiscalYearID, + ddb.DepartmentalBudgetID, + fd.AccountID, + dp.Name, + fd.Name, + fct.UnitTypeID + +-------------------------------------------------------------------------------------------------- +-- Populate temp table - Yearly capital structure +-------------------------------------------------------------------------------------------------- + insert into #dataagg + ( + [TimeClassID], + [FiscalYearID], + [DepartmentalBudgetID], + [AccountID], + [UnitTypeID], + [AssumptionID], + [Month01], + [Month02], + [Month03], + [Month04], + [Month05], + [Month06], + [Month07], + [Month08], + [Month09], + [Month10], + [Month11], + [Month12], + [Yearly], + [Comment], + [HistoryItemGUID], + [TransactionID], + [AdjustmentCategoryID] + ) + select + [TimeClassID] = case fct.FiscalYearID + when @currYear then 12 + else 2 + end, + [FiscalYearID] = fct.FiscalYearID, + [DepartmentalBudgetID] = ddb.DepartmentalBudgetID, + [AccountID] = fd.AccountID, + [UnitTypeID] = fct.UnitTypeID, + [AssumptionID] = 18, + [Month01] = 0, + [Month02] = 0, + [Month03] = 0, + [Month04] = 0, + [Month05] = 0, + [Month06] = 0, + [Month07] = 0, + [Month08] = 0, + [Month09] = 0, + [Month10] = 0, + [Month11] = 0, + [Month12] = 0, + [Yearly] = sum(fct.Amount), + [Comment] = 'Transfer from Capital - Model: ' + dp.Name + ' - Forecast Line: ' + fd.Name, + [HistoryItemGUID] = @higuid, + [TransactionID] = -99, + [AdjustmentCategoryID] = 0 + from [clientcap].[FactProjectOperations] fct + inner join [cap].[viewDimProject] dp + on fct.ProjectID = dp.ProjectID + inner join [cap].[viewDimForecastDetail] fd + on fct.CAPForecastDetailID=fd.CAPForecastDetailID + inner join [ob].[viewDimDepartmentalBudget] ddb + on dp.DepartmentID = ddb.DepartmentID + where 1=1 + and fct.IsDeleted = 0 + and dp.IncludeinOB = 1 + and fd.AccountID > 0 + and fct.UnitTypeID = 34 + and fct.FiscalYearID in (@currYear, @currYear+1) + group by + fct.FiscalYearID, + ddb.DepartmentalBudgetID, + fd.AccountID, + dp.Name, + fd.Name, + fct.UnitTypeID + +-------------------------------------------------------------------------------------------------- +-- Create dept temp table +-------------------------------------------------------------------------------------------------- + select tmp.[DepartmentalBudgetID], ddb.MemberGUID, 0 as IsRefreshNeeded + into #depts + from #dataagg tmp + inner join [ob].[DimDepartmentalBudget] ddb + on tmp.DepartmentalBudgetID = ddb.DepartmentalBudgetID + +-------------------------------------------------------------------------------------------------- +-- Delete sub-table records no longer present in capital projects +-------------------------------------------------------------------------------------------------- + update dept + set IsRefreshNeeded=1 + from #depts dept + inner join [clientob].[FactAccountSubtableVar] fctv + on fctv.DepartmentalBudgetID = dept.DepartmentalBudgetID + left join #dataagg tmp + on fctv.TimeClassID = tmp.TimeClassID + and fctv.FiscalYearID = tmp.FiscalYearID + and fctv.DepartmentalBudgetID = tmp.DepartmentalBudgetID + and fctv.AccountID = tmp.AccountID + and fctv.UnitTypeID = tmp.UnitTypeID + and fctv.AssumptionID = tmp.AssumptionID + and fctv.Comment = tmp.Comment + and fctv.IsDeleted = tmp.IsDeleted + where 1=1 + and tmp.TimeClassID is null + and + ( + (fctv.FiscalYearID = @currYear and fctv.TimeClassID = 12) + or + (fctv.FiscalYearID = @currYear+1 and fctv.TimeClassID = 2) + ) + and fctv.TransactionID = -99 + and fctv.Comment like 'Transfer from Capital - Model: %' + + delete fctv + from [clientob].[FactAccountSubtableVar] fctv + left join #dataagg tmp + on fctv.TimeClassID = tmp.TimeClassID + and fctv.FiscalYearID = tmp.FiscalYearID + and fctv.DepartmentalBudgetID = tmp.DepartmentalBudgetID + and fctv.AccountID = tmp.AccountID + and fctv.UnitTypeID = tmp.UnitTypeID + and fctv.AssumptionID = tmp.AssumptionID + and fctv.Comment = tmp.Comment + and fctv.IsDeleted = tmp.IsDeleted + where 1=1 + and tmp.TimeClassID is null + and + ( + (fctv.FiscalYearID = @currYear and fctv.TimeClassID = 12) + or + (fctv.FiscalYearID = @currYear+1 and fctv.TimeClassID = 2) + ) + and fctv.TransactionID = -99 + and fctv.Comment like 'Transfer from Capital - Model: %' + +-------------------------------------------------------------------------------------------------- +-- Update existing sub-table records +-------------------------------------------------------------------------------------------------- + update dept + set IsRefreshNeeded=1 + from #depts dept + inner join [clientob].[FactAccountSubtableVar] fctv + on dept.DepartmentalBudgetID=fctv.DepartmentalBudgetID + inner join #dataagg tmp + on fctv.TimeClassID = tmp.TimeClassID + and fctv.FiscalYearID = tmp.FiscalYearID + and fctv.DepartmentalBudgetID = tmp.DepartmentalBudgetID + and fctv.AccountID = tmp.AccountID + and fctv.UnitTypeID = tmp.UnitTypeID + and fctv.AssumptionID = tmp.AssumptionID + and fctv.Comment = tmp.Comment + and fctv.IsDeleted = tmp.IsDeleted + where 1=1 + and + ( + fctv.Month01<>tmp.Month01 + or fctv.Month02<>tmp.Month02 + or fctv.Month03<>tmp.Month03 + or fctv.Month04<>tmp.Month04 + or fctv.Month05<>tmp.Month05 + or fctv.Month06<>tmp.Month06 + or fctv.Month07<>tmp.Month07 + or fctv.Month08<>tmp.Month08 + or fctv.Month09<>tmp.Month09 + or fctv.Month10<>tmp.Month10 + or fctv.Month11<>tmp.Month11 + or fctv.Month12<>tmp.Month12 + or fctv.Yearly<>tmp.Yearly + ) + + update fctv + set + fctv.Month01=tmp.Month01, + fctv.Month02=tmp.Month02, + fctv.Month03=tmp.Month03, + fctv.Month04=tmp.Month04, + fctv.Month05=tmp.Month05, + fctv.Month06=tmp.Month06, + fctv.Month07=tmp.Month07, + fctv.Month08=tmp.Month08, + fctv.Month09=tmp.Month09, + fctv.Month10=tmp.Month10, + fctv.Month11=tmp.Month11, + fctv.Month12=tmp.Month12, + fctv.Yearly=tmp.Yearly, + fctv.HistoryItemGUID = @higuid + from [clientob].[FactAccountSubtableVar] fctv + inner join #dataagg tmp + on fctv.TimeClassID = tmp.TimeClassID + and fctv.FiscalYearID = tmp.FiscalYearID + and fctv.DepartmentalBudgetID = tmp.DepartmentalBudgetID + and fctv.AccountID = tmp.AccountID + and fctv.UnitTypeID = tmp.UnitTypeID + and fctv.AssumptionID = tmp.AssumptionID + and fctv.Comment = tmp.Comment + and fctv.IsDeleted = tmp.IsDeleted + where 1=1 + and + ( + fctv.Month01<>tmp.Month01 + or fctv.Month02<>tmp.Month02 + or fctv.Month03<>tmp.Month03 + or fctv.Month04<>tmp.Month04 + or fctv.Month05<>tmp.Month05 + or fctv.Month06<>tmp.Month06 + or fctv.Month07<>tmp.Month07 + or fctv.Month08<>tmp.Month08 + or fctv.Month09<>tmp.Month09 + or fctv.Month10<>tmp.Month10 + or fctv.Month11<>tmp.Month11 + or fctv.Month12<>tmp.Month12 + or fctv.Yearly<>tmp.Yearly + ) + + +-------------------------------------------------------------------------------------------------- +-- Update existing sub-table records +-------------------------------------------------------------------------------------------------- + update dept + set IsRefreshNeeded=1 + from #depts dept + inner join #dataagg tmp + on dept.DepartmentalBudgetID=tmp.DepartmentalBudgetID + left join [clientob].[FactAccountSubtableVar] fctv + on fctv.TimeClassID = tmp.TimeClassID + and fctv.FiscalYearID = tmp.FiscalYearID + and fctv.DepartmentalBudgetID = tmp.DepartmentalBudgetID + and fctv.AccountID = tmp.AccountID + and fctv.UnitTypeID = tmp.UnitTypeID + and fctv.AssumptionID = tmp.AssumptionID + and fctv.Comment = tmp.Comment + and fctv.IsDeleted = tmp.IsDeleted + where 1=1 + and fctv.TimeClassID is null + + + insert into [clientob].[FactAccountSubtableVar] + ( + [TimeClassID], + [FiscalYearID], + [DepartmentalBudgetID], + [AccountID], + [UnitTypeID], + [AssumptionID], + [Month01], + [Month02], + [Month03], + [Month04], + [Month05], + [Month06], + [Month07], + [Month08], + [Month09], + [Month10], + [Month11], + [Month12], + [Yearly], + [Comment], + [HistoryItemGUID], + [TransactionID], + [AdjustmentCategoryID] + ) + select + tmp.[TimeClassID], + tmp.[FiscalYearID], + tmp.[DepartmentalBudgetID], + tmp.[AccountID], + tmp.[UnitTypeID], + tmp.[AssumptionID], + tmp.[Month01], + tmp.[Month02], + tmp.[Month03], + tmp.[Month04], + tmp.[Month05], + tmp.[Month06], + tmp.[Month07], + tmp.[Month08], + tmp.[Month09], + tmp.[Month10], + tmp.[Month11], + tmp.[Month12], + tmp.[Yearly], + tmp.[Comment], + tmp.[HistoryItemGUID], + tmp.[TransactionID], + tmp.[AdjustmentCategoryID] + from #dataagg tmp + left join [clientob].[FactAccountSubtableVar] fctv + on fctv.TimeClassID = tmp.TimeClassID + and fctv.FiscalYearID = tmp.FiscalYearID + and fctv.DepartmentalBudgetID = tmp.DepartmentalBudgetID + and fctv.AccountID = tmp.AccountID + and fctv.UnitTypeID = tmp.UnitTypeID + and fctv.AssumptionID = tmp.AssumptionID + and fctv.Comment = tmp.Comment + and fctv.IsDeleted = tmp.IsDeleted + where 1=1 + and fctv.TimeClassID is null + +-------------------------------------------------------------------------------------------------- +-- Invalidate department models +-------------------------------------------------------------------------------------------------- + select @planRefreshList = 'PlanGUID in (''' + dbo.straggr(cast(dep.MemberGUID as nvarchar(36)), ''',''', '') + ''')' + from #depts dep + + exec [dbo].[procInvalidateModelWorkbookCacheByWhereClause] @xplanWhereClause = @planRefreshList,@isDebugOnly = 0 + +-------------------------------------------------------------------------------------------------- +-- Clean-up +-------------------------------------------------------------------------------------------------- + drop table #depts + drop table #dataagg + +end +GO + + +--------------------------------------------- + +-- ob.procClearAllAssumptions +CREATE proc [ob].[procClearAllAssumptions] as +/************************************************************************************************************************ +** Author: Bart Lewis +** Create Date: 2015-05-12 +** Description: Resets Budget Drop Down Boxes +** Last Modified: 2017-08-08 +** GM Release: 2015.3 +************************************************************************************************************************** +** Change History +************************************************************************************************************************** +** CID Date Author WI Description +** 1 2017-04-05 vyaremko B-15589 Use OB_Budget_IsOpen from [ob].[SystemSetting] instead [dbo].[DBSetting] +** 2 2017-06-06 cbb B-15886 exclude rvu weights and isstatdriver assumptions +** 3 2017-08-08 vyaremko B-16694 Rename 'Is Budget Open' to 'Budget Status' +*************************************************************************************************************************/ + +declare @FiscalYearID int = (select Setting+1 from [dbo].[DBSetting] where Name = 'OB_Current_Year') + +/************** Logging *********************************************************/ +declare @higuid uniqueidentifier +declare @Desc nvarchar(200) = 'Reset All Budget Assumptions ' + cast(@FiscalYearID+1 as Nvarchar(4)) + ' Rollover' + +declare @RVUid nvarchar(15) +declare @IncExcid nvarchar(15) + +select @RVUid = AssumptionID from [fw].[DimAssumption] where MemberGUID = '46c83c8c-fe45-4911-8338-0a2e87474132' +select @IncExcid = AssumptionID from [fw].[DimAssumption] where MemberGUID = 'c70bc8dd-f89c-4afa-bbbd-a454ebfc1a0c' + +exec procLogScript @Desc , @higuid output + +IF (SELECT TOP 1 [Value] FROM [ob].[SystemSetting] WHERE [Name] = 'Budget Status') = 0 -- Closed +BEGIN + +--Cursor to Delete All Var structures + BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + DECLARE @SCHEMA nvarchar(256) + DECLARE @FactTableName nvarchar(256) + DECLARE @SQL nvarchar(1024) + DECLARE @SQL2 nvarchar(1024) + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) + from sys.tables t + where 1=1 + and t.schema_id in + ( + select schema_id + from sys.schemas + where name in('ob', 'clientob') + ) + and t.name like 'fact%' + and t.name like '%var%' + and t.name not like '%Snapshot' + and t.name not in ('FactGlobalSpreads','FactBudgetYearReportingCrosswalk') + and t.name not like '%map' order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + --set @SQL = 'truncate table ' + @SCHEMA + '.' + @FactTableName + set @SQL = 'Delete from ' + @SCHEMA + '.' + @FactTableName + ' where AssumptionID not in ('+@RVUid +','+@IncExcid +')' + set @SQL2='DBCC CHECKIDENT (''' + + @SCHEMA + '.' + @FactTableName + ''', RESEED, 1)' +-- print @SQL +-- print @SQL2 + EXECUTE sp_executesql @SQL + EXECUTE sp_executesql @SQL2 + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + + --Rebuild Indexes and Update Statistics + exec [ob].[procOptimizationRebuildIndexesData] + exec [ob].[procOptimizationRebuildIndexesMapping] + END +END + +RETURN +GO + + +--------------------------------------------- + +-- ob.procClearAllComments +CREATE proc [ob].[procClearAllComments] + @IsDebugOnly bit=0 +as +/************************************************************************************************************************ +** Author: Corey Becker +** Create Date: 2016-06-03 +** Description: Deletes all comments for selected plans +** Last Modified: 2016-06-03 +** GM Release: 2016.3 +************************************************************************************************************************** +** Change History +************************************************************************************************************************** +** CID Date Author WI Description +*************************************************************************************************************************/ + +declare @BudgetYear int +select @BudgetYear = Setting+1 +from [dbo].[DBSetting] +where Name = 'OB_Current_Year' + +/************** Logging *********************************************************/ +declare @higuid uniqueidentifier +declare @Desc nvarchar(200) = 'Delete comments for ' + cast(@BudgetYear as Nvarchar(4)) + ' Rollover' +exec procLogScript @Desc , @higuid output +/********************************************************************************/ + +--Cursor to Delete All Var structures + SET NOCOUNT ON; + DECLARE @SCHEMA nvarchar(256) + DECLARE @FactTableName nvarchar(256) + DECLARE @SQL nvarchar(1024) + DECLARE FactTableCursor CURSOR FOR + select distinct + t.name, + s.name + from sys.tables t + inner join sys.schemas s + on s.schema_id = t.schema_id + inner join sys.columns c + on c.object_id = t.object_id + where 1=1 + and s.name in ('ob', 'clientob') + and t.name like 'fact%' + and t.name like '%var%' + and t.name not in ('FactGlobalSpreads','FactBudgetYearReportingCrosswalk') + and t.name not like '%map' + and t.name not like '%snapshot' + and c.name in ('TextValue_Formula','TextValue Formula','UnitTypeID') + + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + begin + set @SQL = +' +delete from ' + @SCHEMA + '.' + @FactTableName + ' where AssumptionID = 30 +DBCC CHECKIDENT (''' + @SCHEMA + '.' + @FactTableName + ''', RESEED, 1) +DBCC CHECKIDENT (''' + + @SCHEMA + '.' + @FactTableName + ''', RESEED) +' + if @IsDebugOnly=1 + begin + print @SQL + end + else + begin + exec sp_executesql @SQL + end + fetch next from FactTableCursor into @FactTableName, @SCHEMA + end + + close FactTableCursor + deallocate FactTableCursor + + --Rebuild Indexes and Update Statistics + if @IsDebugOnly=0 + begin + exec [ob].[procOptimizationRebuildIndexesData] + exec [ob].[procOptimizationRebuildIndexesMapping] + end + + exec [dbo].[procInvalidateModelWorkbookCacheByPlanType] + @planTypeGUID = '05512126-3eb6-4da4-af6e-bc2bc2724b8b', + @source = 'Unknown' + + exec [dbo].[procInvalidateModelWorkbookCacheByPlanType] + @planTypeGUID = 'b4d1bae4-194d-4499-b573-be9d56cbd802', + @source = 'Unknown' + + exec [dbo].[procInvalidateModelWorkbookCacheByPlanType] + @planTypeGUID = '957dd809-6299-4ec2-81fc-5452df805e8e', + @source = 'Unknown' + +return +GO + + +--------------------------------------------- + +-- ob.procClearAllNumericAssumptionsRollForwardDropDownBoxes +CREATE proc [ob].[procClearAllNumericAssumptionsRollForwardDropDownBoxes] as +/************************************************************************************************************************ +** Author: Bart Lewis +** Create Date: 2015-05-12 +** Description: Resets All Assumptions except Drop Down Boxes, those are rolled Forward +** Last Modified: 2015-05-12 +** GM Release: 2015.3 +************************************************************************************************************************** +** Change History +************************************************************************************************************************** +** CID Date Author WI Description +** 1 2015-08-18 bjl n/a Correct @ColumnCount critera +** 2 2016-05-20 cbb D-04203 DBCC CHECKIDENT auto reseed instead of at id 1 +** 3 2016-06-06 cbb n/a reseed to 1, then reseed +** 4 2017-04-05 vyaremko B-15589 Use OB_Budget_IsOpen from [ob].[SystemSetting] instead [dbo].[DBSetting] +** 5 2017-06-06 cbb B-15886 add assumption id filters to delete for RVU weight and IsStatDriver and filtered out snapshot var tables +** 6 2017-08-08 vyaremko B-16694 Rename 'Is Budget Open' to 'Budget Status' +*************************************************************************************************************************/ + +declare @FiscalYearID int = (select Setting+1 from [dbo].[DBSetting] where Name = 'OB_Current_Year') + +/************** Logging *********************************************************/ +declare @higuid uniqueidentifier +declare @Desc nvarchar(200) = 'Reset Non Text Budget Assumptions ' + cast(@FiscalYearID+1 as Nvarchar(4)) + ' Rollover' + +-- CID 5 BEGIN +declare @RVUid nvarchar(15) +declare @IncExcid nvarchar(15) + +select @RVUid = AssumptionID from [fw].[DimAssumption] where MemberGUID = '46c83c8c-fe45-4911-8338-0a2e87474132' +select @IncExcid = AssumptionID from [fw].[DimAssumption] where MemberGUID = 'c70bc8dd-f89c-4afa-bbbd-a454ebfc1a0c' +-- CID 5 END + +exec procLogScript @Desc , @higuid output + +IF (SELECT TOP 1 [Value] FROM [ob].[SystemSetting] WHERE [Name] = 'Budget Status') = 0 -- Closed +BEGIN + +--Cursor to Delete All Var structures + BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + DECLARE @SCHEMA nvarchar(256) + DECLARE @FactTableName nvarchar(256) + DECLARE @SQL nvarchar(1024) + DECLARE @SQL1 nvarchar(1024) + DECLARE @SQL2 nvarchar(1024) + DECLARE @ColumnCount int + --Cursor for Clientob Var Fact Tables with 'TextValue_Formula' or'UnitTypeID' + DECLARE FactTableCursor CURSOR FOR + select + t.name, + s.name, + Count(c.name) + from sys.tables t + inner join sys.schemas s on s.schema_id = t.schema_id + inner join sys.columns c on c.object_id = t.object_id + where t.schema_id in(select schema_id from sys.schemas where name in('ob', 'clientob')) + and t.name like 'fact%' + and t.name like '%var%' + and t.name not like '%snapshot' + and t.name not in ('FactGlobalSpreads','FactBudgetYearReportingCrosswalk') + and t.name not like '%map' + and c.name IN('TextValue_Formula','TextValue Formula','UnitTypeID') + Group by + t.name, + s.name + order by t.name + + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA, @ColumnCount + WHILE @@FETCH_STATUS = 0 + BEGIN + --Check if 'TextValue_Formula' or just UnitTypeID Exists on Table + If @ColumnCount = 2 Begin + set @SQL = 'Delete from ' + @SCHEMA + '.' + @FactTableName + ' where AssumptionID not in ('+@RVUid +','+@IncExcid +') and UnitTypeID<>141 and TextValue_Formula<>''x''' + End + + IF @ColumnCount = 1 Begin + set @SQL = 'Delete from ' + @SCHEMA + '.' + @FactTableName + ' where AssumptionID not in ('+@RVUid +','+@IncExcid +') and UnitTypeID<>141' + End + set @SQL1 = 'Update ' + @SCHEMA + '.' + @FactTableName + ' set FiscalYearID=FiscalYearID + 1 where FiscalYearID<>0' + + set @SQL2='DBCC CHECKIDENT (''' + + @SCHEMA + '.' + @FactTableName + ''', RESEED,1) + DBCC CHECKIDENT (''' + + @SCHEMA + '.' + @FactTableName + ''', RESEED)' + + --print @SQL + --print @SQL2 + EXECUTE sp_executesql @SQL + EXECUTE sp_executesql @SQL1 + EXECUTE sp_executesql @SQL2 + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA, @ColumnCount + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + + --Rebuild Indexes and Update Statistics + exec [ob].[procOptimizationRebuildIndexesData] + exec [ob].[procOptimizationRebuildIndexesMapping] + END +END + +RETURN +GO + + +--------------------------------------------- + +-- ob.procClearWorkspace +CREATE proc [ob].[procClearWorkspace] + @planGUIDList nvarchar(max)='' +as + +/************************************************************************************** +** Author: Corey Becker +** Create Date: 2016-06-03 +** Description: Deletes all content in Workspace section of departmental budgets +** Last Modified: 2016-06-03 +** GM Release: 2016.3 +*************************************************************************************** +** Change History +*************************************************************************************** +** CID Date Author WI Description +**************************************************************************************/ + +-- Logging ---------------------------------------------------------------------------- + declare @higuid uniqueidentifier + declare @Desc nvarchar(200) = 'Delete Workspace content in OB Dept Budget models' + exec procLogScript @Desc , @higuid output + +-- Create temp table to hold affected models ------------------------------------------ + create Table #Plans(DepartmentalBudgetID int, ModelGUID uniqueidentifier) + + if (len(@planGUIDList) = 0) + begin + insert into #Plans + (DepartmentalBudgetID, ModelGUID) + select dim.DepartmentalBudgetID, dim.MemberGUID + from ob.DimDepartmentalBudget dim + end + else + begin + insert into #Plans + (DepartmentalBudgetID, ModelGUID) + select dim.DepartmentalBudgetID, dim.MemberGUID + from dbo.ConvertCSGuidsToTable(@planGUIDList, ',') guids + inner join ob.DimDepartmentalBudget dim + on guids.guid = dim.MemberGUID + end + +-- Delete data ------------------------------------------------------------------------ + delete data + from [dbo].[MEImprovData] data + inner join #Plans pl + on data.ModelGUID = pl.ModelGUID + +-- Invalidate model cache ------------------------------------------------------------- + if (len(@planGUIDList) = 0) + begin + exec [dbo].[procInvalidateModelWorkbookCacheByPlanType] + @planTypeGUID = '05512126-3eb6-4da4-af6e-bc2bc2724b8b', + @source = 'Unknown' + end + else + begin + declare @whereClause nvarchar(max) = 'PlanGUID in ('''+@planGUIDList+''')' + exec [dbo].[procInvalidateModelWorkbookCacheByWhereClause] + @xplanWhereClause = @whereClause, + @isDebugOnly = 0, + @source = 'Unknown' + end + +-- Clean-up --------------------------------------------------------------------------- + drop table #Plans + +return +GO + + +--------------------------------------------- + +-- ob.procCreateViewReportStaffingtoGLAccount +CREATE proc ob.procCreateViewReportStaffingtoGLAccount + @mode nvarchar(100) = 'default' +as + if (@mode = 'default') begin + select @mode = cast(PropertyXML.query('//PayRollToGLLinkDollarsConfiguration/text()') as nvarchar(100)) from [dbo].[SystemCenterStep] where Name = 'Payroll to GL Link Selection' + if (@mode is null or @mode = '') return + end + + declare @sql nvarchar(max) + set @sql = 'alter view [ob].[viewReportStaffingtoGLAccount] as + select * from ob.viewReportStaffingtoGLAccount_' + @mode + exec(@sql) +GO + + +--------------------------------------------- + +-- ob.procDataViewRegisterDimensions +CREATE proc [ob].[procDataViewRegisterDimensions] + @dvguid uniqueidentifier, + @isSafeMode bit = 0 --safe mode will skip deletes and only do adds +as + declare @rdguid uniqueidentifier + declare @dvsql nvarchar(200) + select @dvsql = replace(replace(SQLViewName, '[', ''), ']', '') from DataView where DataViewGUID = @dvguid + + --department + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentID')) begin + print @dvsql + ' - Registering DepartmentID' + + declare @departmentDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'Department') + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Department' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Department' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Department' when a.SQLColumnName = 'Description' then 'Department Description' else isnull(da.FriendlyName, a.FriendlyName) end + from viewScoreAttribute a + join ScoreAttributeSetting attrSet on a.DimensionGUID = attrSet.DimensionGUID and a.AttributeGuid = attrSet.AttributeGuid + left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID + where + a.DimensionGUID = @departmentDimGuid + and ( + (a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 2) and a.SQLColumnName not like '%IsDefined') + or a.SQLColumnName in('Name', 'DepartmentCode') + or attrSet.OBIsUsed = 1 + ) + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --departmental budget + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentalBudgetID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentalBudgetID')) + begin + declare @departmentalBudgetDimGuid uniqueidentifier = (select DimensionGUID from ScoreDimension where GlobalID = 'OB Departmental Budget') + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentalBudgetID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'OB Departmental Budget' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'OB Departmental Budget' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Departmental Budget' else isnull(da.FriendlyName, a.FriendlyName) end + from viewScoreAttribute a + left join viewScoreAttribute ia on ia.AttributeGUID = a.InferredAttributeGUID + left join ScoreAttributeSetting attrSet on ia.DimensionGUID = attrSet.DimensionGUID and ia.AttributeGuid = attrSet.AttributeGuid + left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID + where + a.DimensionGUID = @departmentalBudgetDimGuid + and ( + (a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 5) and a.SQLColumnName not like '%IsDefined') + or isnull(attrSet.OBIsUsed, 0) = 1 + or a.SQLColumnName in('Name') + ) + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --account + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'AccountID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'AccountID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering AccountID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'AccountID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Account' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Account' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Account' when a.SQLColumnName = 'Description' then 'Account Description' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Account' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID' and a.SQLColumnName != 'OBDollarsFinancialReportingCategory') or a.SQLColumnName in('Name', 'AccountCode', 'OBModelSectionName', 'OBUnitsFinancialReporting', 'OBUnitsFinancialReportingLineName', 'OBUnitsFinancialReportingSortOrder', 'OBPayor', 'OBPayorGroup', 'OBUnitType', 'PatientClass') or (@dvsql not like '%statistic%' and a.SQLColumnName in('OBDollarsFinancialReporting', 'OBDollarsFinancialReportingLineName', 'OBDollarsFinancialReportingCategory', 'OBDollarsFinancialReportingSortOrder'))) + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --job code + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'JobCodeID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'JobCodeID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering JobCodeID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'JobCodeID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Job Code' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Job Code' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Job Code Name' when a.SQLColumnName = 'Description' then 'Job Code Description' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Job Code' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName in('Name', 'JobCodeGroup')) + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --pay code + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'PayCodeID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'PayCodeID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering PayCodeID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'PayCodeID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Pay Code' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Pay Code' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Pay Code Name' when a.SQLColumnName = 'Description' then 'Pay Code Description' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Pay Code' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName in('Name', 'PayCodeGroup')) + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --pay code group + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'PayCodeGroupID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'PayCodeGroupID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering PayCodeGroupID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'PayCodeGroupID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Pay Code Group' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Pay Code Group' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Pay Code Group' when a.SQLColumnName = 'Description' then 'Pay Code Group Description' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Pay Code Group' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName in('Name', 'PayClass', 'IsPremium', 'IsOvertime', 'IsAgency', 'IsDirect', 'ProductiveClass')) + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --employee + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'EmployeeID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'EmployeeID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering EmployeeID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'EmployeeID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Employee' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Employee' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Employee' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Employee' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(0, 2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName = 'Name') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --time class + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'TimeClassID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'TimeClassID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering TimeClassID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'TimeClassID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Time Class' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Time Class' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Time Class' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Time Class' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName = 'Name') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --fiscal year + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'FiscalYearID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'FiscalYearID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering FiscalYearID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'FiscalYearID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Fiscal Year' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Fiscal Year' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Fiscal Year' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Fiscal Year' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName = 'Name') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --fiscal month + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'FiscalMonthID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'FiscalMonthID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering FiscalMonthID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'FiscalMonthID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Fiscal Month' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Fiscal Month' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Fiscal Month' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Fiscal Month' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName in('Name', 'FiscalMonthCode')) + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --date + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DateID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DateID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering DateID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DateID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Date' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Date' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Date' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Date' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName in('Name', 'CalendarDateTime', 'CalendarMonth', 'CalendarMonthName', 'CalendarYear', 'DayNameOfWeek', 'DayNumberOfMonth', 'FiscalYear', 'IsWeekDay')) + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --unit type + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'UnitTypeID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'UnitTypeID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering UnitTypeID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'UnitTypeID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Unit Type' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Unit Type' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Unit Type' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Unit Type' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName = 'Name') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --provider + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'ProviderID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'ProviderID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering ProviderID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'ProviderID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Provider' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Provider' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Provider' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Provider' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName in('Name', 'NameFirst', 'NameLast', 'ProviderCode', 'Type', 'WorkWeekOverrideID')) + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --physician specialty + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'PhysicianSpecialtyID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'PhysicianSpecialtyID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering PhysicianSpecialtyID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'PhysicianSpecialtyID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Physician Specialty' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Physician Specialty' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Physician Specialty' when a.SQLColumnName = 'Description' then 'Physician Specialty Description' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'Physician Specialty' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID' and a.SQLColumnName not in('RVUTarget', 'SpecialtyGroup')) or a.SQLColumnName in('Name', 'PhysicianSpecialtyCode', 'Description')) + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --OB Forecast Detail + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'OBForecastDetailID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'OBForecastDetailID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering OBForecastDetailID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'OBForecastDetailID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'OB Forecast Detail' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'OB Forecast Detail' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'OB Forecast Detail' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionName = 'OB Forecast Detail' and ((a.IsHidden = 0 and a.IsLocked = 0 and a.FrameworkID in(2) and a.SQLColumnName not like '%IsDefined' and a.SQLColumnName not like '%ID') or a.SQLColumnName ='Name') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --System + declare @systemGUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'System') + + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'SystemID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'SystemID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering SystemID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'SystemID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'System' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DimensionGUID = rd.DimensionGUID where d.GlobalID = 'System' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'System' when a.SQLColumnName = 'Code' then 'System Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @systemGUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --Entity + declare @entityGUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'Entity') + + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'EntityID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'EntityID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering EntityID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'EntityID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Entity' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Entity' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Entity' when a.SQLColumnName = 'Code' then 'Entity Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @entityGUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --Department Rollup 1 + declare @departmentRollup1GUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'Department Rollup 1') + + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentRollup1ID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentRollup1ID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering DepartmentRollup1ID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentRollup1ID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Department Rollup 1' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Department Rollup 1' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Department Rollup 1' when a.SQLColumnName = 'Code' then 'Department Rollup 1 Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @departmentRollup1GUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --Department Rollup 2 + declare @departmentRollup2GUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'Department Rollup 2') + + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentRollup2ID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentRollup2ID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering DepartmentRollup2ID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentRollup2ID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Department Rollup 2' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Department Rollup 2' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Department Rollup 2' when a.SQLColumnName = 'Code' then 'Department Rollup 2 Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @departmentRollup2GUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --Department Rollup 3 + declare @departmentRollup3GUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'Department Rollup 3') + + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentRollup3ID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentRollup3ID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering DepartmentRollup3ID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentRollup3ID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Department Rollup 3' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Department Rollup 3' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Department Rollup 3' when a.SQLColumnName = 'Code' then 'Department Rollup 3 Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @departmentRollup3GUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --Department Rollup 4 + declare @departmentRollup4GUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'Department Rollup 4') + + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentRollup4ID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentRollup4ID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering DepartmentRollup4ID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentRollup4ID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Department Rollup 4' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Department Rollup 4' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Department Rollup 4' when a.SQLColumnName = 'Code' then 'Department Rollup 4 Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @departmentRollup4GUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --Department Rollup 5 + declare @departmentRollup5GUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'Department Rollup 5') + + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentRollup5ID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentRollup5ID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering DepartmentRollup5ID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentRollup5ID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Department Rollup 5' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Department Rollup 5' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Department Rollup 5' when a.SQLColumnName = 'Code' then 'Department Rollup 5 Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @departmentRollup5GUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + --Department Rollup 6 + declare @departmentRollup6GUID uniqueidentifier = (select DimensionGUID from dbo.ScoreDimension where GlobalID = 'Department Rollup 6') + + if (exists (select 1 from sys.columns c inner join sys.views v on v.object_id = c.object_id inner join sys.schemas s on s.schema_id = v.schema_id where s.name + '.' + v.name = @dvsql and c.name = 'DepartmentRollup6ID')) + or (exists (select 1 from sys.columns c inner join sys.tables t on t.object_id = c.object_id inner join sys.schemas s on s.schema_id = t.schema_id where s.name + '.' + t.name = @dvsql and c.name = 'DepartmentRollup6ID')) begin + print @dvsql + ' (' + cast(@dvguid as nvarchar(36)) + ') - Registering DepartmentRollup6ID' + + insert into RESQLReportRegisteredDimension (DataViewGUID, DimensionGUID, HierarchyGUID, SQLColumnNames, KeyColumnName, KeyGUID, IsKeyColumnVisible, KeyJoinType, IsSecured) + select @dvguid, d.DimensionGUID, d.DefaultHierarchyGUID, '', 'DepartmentRollup6ID', d.DefaultKeyGUID, 1, 1, 0 from ScoreDimension d where d.GlobalID = 'Department Rollup 6' + and not exists (select 1 from RESQLReportRegisteredDimension ex where ex.DataViewGUID = @dvguid and ex.DimensionGUID = d.DimensionGUID); + select @rdguid = rd.RegisteredDimensionGUID from RESQLReportRegisteredDimension rd inner join ScoreDimension d on d.DImensionGUID = rd.DimensionGUID where d.GlobalID = 'Department Rollup 6' and rd.DataViewGUID = @dvguid; + + insert into RESQLReportRegisteredAttribute (RegisteredDimensionGUID, AttributeGUID, ColumnAlias) + select distinct @rdguid, isnull(da.AttributeGUID, a.AttributeGUID), case when a.SQLColumnName = 'Name' then 'Department Rollup 6' when a.SQLColumnName = 'Code' then 'Department Rollup 6 Code' else isnull(da.FriendlyName, a.FriendlyName) end from viewScoreAttribute a left join viewScoreAttribute da on da.SQLColumnName + 'ID' = a.SQLColumnName and da.DimensionGUID = a.DimensionGUID where a.DimensionGUID = @departmentRollup6GUID and (a.SQLColumnName = 'Name' or a.SQLColumnName = 'Code') + and not exists(select 1 from RESQLReportRegisteredAttribute ex where ex.RegisteredDimensionGUID = @rdguid and ex.AttributeGUID = isnull(da.AttributeGUID, a.AttributeGUID)) + end + + if (@isSafeMode = 0) begin + --ensure settings exist for inferred attributes + exec dbo.procScoreAttributeSettingAddMissing + + --unregister not used attributes + delete ra + from + RESQLReportRegisteredDimension rd + inner join RESQLReportRegisteredAttribute ra on ra.RegisteredDimensionGUID = rd.RegisteredDimensionGUID + inner join ScoreDimension d on d.DimensionGUID = rd.DimensionGUID + inner join ScoreAttributeSetting sas on sas.AttributeGUID = ra.AttributeGUID + where + d.GlobalID in('Department', 'OB Departmental Bduget') + and rd.DataViewGUID = @dvguid + and sas.OBIsUsed = 0 + and sas.IsCustom = 1 + + --remove duplicates + while (exists(select max(a.registeredattributeguid) from resqlreportregisteredattribute a inner join resqlreportregistereddimension d on d.registereddimensionguid = a.registereddimensionguid where d.DataViewGUID = @dvguid group by d.registereddimensionguid, a.attributeguid having count(*) > 1)) begin + delete from resqlreportregisteredattribute where registeredattributeguid in(select max(a.registeredattributeguid) from resqlreportregisteredattribute a inner join resqlreportregistereddimension d on d.registereddimensionguid = a.registereddimensionguid where d.DataViewGUID = @dvguid group by d.registereddimensionguid, a.attributeguid having count(*) > 1) + end + end +GO + + +--------------------------------------------- + +-- ob.procDataViewRegisterDimensionsAll +CREATE proc ob.procDataViewRegisterDimensionsAll +as + set nocount on + + declare @dvguid uniqueidentifier + declare crsViews cursor fast_forward for + select distinct + dv.DataViewGUID + from + DataView dv + where + dv.Name like 'OB %' + + open crsViews + fetch next from crsViews into @dvguid + + while (@@fetch_status = 0) begin + exec ob.procDataViewRegisterDimensions @dvguid + fetch next from crsViews into @dvguid + end + + close crsViews + deallocate crsViews +GO + + +--------------------------------------------- + +-- ob.procDeleteDimensionData +CREATE PROCEDURE [ob].[procDeleteDimensionData] +AS + +/************************************************************ +** Author: unknown +** Create Date: Unknown +** Description: Deletes all OB dimensions that are specified by the client, used only for GM releases - NEVER RUN ON CLIENT DATABASES +** Last Modified: 2014-10-02 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2013-10-02 akk 64597 Adding new dimensions +** 2 2014-02-18 akk D-01495 Filtering out not specified member +** 3 2014-07-22 akk D-01940 Clearing out accountid +** 4 2014-10-02 JG B-02929 Clearing out Snapshot and Allocation dimensions +** 5 2015-02-11 akk Clearing out testing members from OB Forecast Detail +** 6 2015-11-06 akk Deleting global assumptions +*************************************************************/ + + +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + declare @nextid int + select @nextid = 1 + + --==== BEGIN CID 1 ==== +-- delete from ob.DimDepartmentalBudget +-- DBCC CHECKIDENT ('ob.DimDepartmentalBudget', RESEED, @nextid) + +--==== BEGIN CID 2 ==== + delete from [ob].[DimOBGlobalStatistics] where OBGlobalStatisticID<>0 +--==== END CID 2 ==== + DBCC CHECKIDENT ('ob.DimOBGlobalStatistics', RESEED, @nextid) + +--==== BEGIN CID 4 ==== + delete from [ob].[DimOBSnapshot] where OBSnapshotID<>0 + DBCC CHECKIDENT ('ob.DimOBSnapshot', RESEED, @nextid) + delete from [ob].[DimOBAllocation] where OBAllocationID<>0 + DBCC CHECKIDENT ('ob.DimOBAllocation', RESEED, @nextid) + delete from [ob].[DimOBAllocationBasis] where OBAllocationBasisID<>0 + DBCC CHECKIDENT ('ob.DimOBAllocationBasis', RESEED, @nextid) +--==== END CID 4 ==== + + + --==== END CID 1 ==== + --==== BEGIN CID 3 ==== + update [ob].[DimOBForecastDetail] + set AccountID=0,SecondaryAccountID=0 + exec [dbo].[procScoreDimensionCacheRefresh] '7997659c-8a30-4d1e-86d2-0afb41c9e2fc' + --==== END CID 3 ==== + + --==== BEGIN CID 5 ==== + delete from [ob].[DimOBForecastDetail] + where Name like '%zzTest%' + + --==== END CID 5 ==== + --==== BEGIN CID 6 ==== + delete from [dbo].[GlobalAssumption] + --==== END CID 6 ==== + --Rebuild Indexes and Update Statistics + exec [ob].[procOptimizationRebuildIndexesDimensions] +END + +RETURN +GO + + +--------------------------------------------- + +-- ob.procDeleteExceptionsDataWithoutDimensionMembers +/************************************************************ +** Author: jgerber +** Create Date: 2014-09-18 +** Description: Deletes SL data that does not have dimension members +** Last Modified: 2014-09-18 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +*************************************************************/ + +create proc [ob].[procDeleteExceptionsDataWithoutDimensionMembers] + +as + +--***Fact Account********************************************* +-- Department Dimension + delete + data + from + [clientob].[FactAccount] data with (readuncommitted) + left join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + where + db.MemberGUID is null + + +-- Account Dimension + delete + data + from + [clientob].[FactAccount] data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + left join [fw].[DimAccount] dim with (readuncommitted) on dim.AccountID = data.AccountID + where + dim.MemberGUID is null + + +--***Fact Staffing PC********************************************* +-- Department Dimension + delete + data + from + [clientob].[FactStaffingPC] data with (readuncommitted) + left join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + where + db.MemberGUID is null + + +-- Job Code Dimension + delete + data + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + left join [fw].[DimJobCode] dim with (readuncommitted) on dim.JobCodeID = data.JobCodeID + where + dim.MemberGUID is null + + +-- Pay Code Dimension + delete + data + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + left join [fw].[DimPayCode] dim with (readuncommitted) on dim.PayCodeID = data.PayCodeID + where + dim.MemberGUID is null + + +-- Pay Code Group Dimension + delete + data + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + left join [fw].[DimPayCodeGroup] dim with (readuncommitted) on dim.PayCodeGroupID = data.PayCodeGroupID + where + dim.MemberGUID is null + + +-- Employee Dimension + delete + data + from + [clientob].[FactStaffingPC] data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + left join [fw].[DimEmployee] dim with (readuncommitted) on dim.EmployeeID = data.EmployeeID + where + dim.MemberGUID is null + + +--***Fact Provider********************************************* +-- Department Dimension + delete + data + from + [clientob].[FactProvider] data with (readuncommitted) + left join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + where + db.MemberGUID is null + + +-- Provider Dimension + delete + data + from + [clientob].[FactProvider] data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + left join [fw].[DimProvider] dim with (readuncommitted) on dim.ProviderID = data.ProviderID + where + dim.MemberGUID is null + + +-- Forecast Detail Dimension + delete + data + from + [clientob].[FactProvider] data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + left join [ob].[DimOBForecastDetail] dim with (readuncommitted) on dim.OBForecastDetailID = data.OBForecastDetailID + where + dim.MemberGUID is null + + +--***Fact Charge Code********************************************* +-- Department Dimension + delete + data + from + [clientob].[FactCDM] data with (readuncommitted) + left join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + where + db.MemberGUID is null + + +-- Charge Code Dimension + delete + data + from + [clientob].[FactCDM] data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + left join [fw].[DimChargeCode] dim with (readuncommitted) on dim.ChargeCodeID = data.ChargeCodeID + where + dim.MemberGUID is null + + +--***Fact Reporting********************************************* +-- Department Dimension + delete + data + from + [clientob].[FactReportingMonthly] data with (readuncommitted) + left join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + where + db.MemberGUID is null + + +-- Financial Reporting Dimension + delete + data + from + [clientob].[FactReportingMonthly] data with (readuncommitted) + inner join ob.DimDepartmentalBudget db with (readuncommitted) on db.DepartmentalBudgetID = data.DepartmentalBudgetID + left join [ob].[DimFinancialReporting] dim with (readuncommitted) on dim.FinancialReportingID = data.FinancialReportingID + where + dim.MemberGUID is null + + +--***Fact Global Statistics********************************************* +-- Department Dimension + delete + data + from + [clientob].[FactGlobalStatistics] data with (readuncommitted) + left join [ob].[DimOBGlobalStatisticsPlan] db with (readuncommitted) on db.OBGlobalStatisticsPlanID = data.OBGlobalStatisticsPlanID + where + db.MemberGUID is null + + +-- Global Statistics Dimension + delete + data + from + [clientob].[FactGlobalStatistics] data with (readuncommitted) + inner join[ob].[DimOBGlobalStatisticsPlan] db with (readuncommitted) on db.OBGlobalStatisticsPlanID = data.OBGlobalStatisticsPlanID + left join [ob].[DimOBGlobalStatistics] dim with (readuncommitted) on dim.OBGlobalStatisticID = data.OBGlobalStatisticID + where + dim.MemberGUID is null + + +--***Fact Service Line********************************************* +-- Service Line Plan Dimension + delete + data + from + [clientob].[FactServiceLine] data with (readuncommitted) + left join [ob].[DimOBServiceLinePlan] db with (readuncommitted) on db.OBServiceLinePlanID = data.OBServiceLinePlanID + where + db.MemberGUID is null + + +-- Modeling Service Line Dimension + delete + data + from + [clientob].[FactServiceLine] data with (readuncommitted) + inner join [ob].[DimOBServiceLinePlan] db with (readuncommitted) on db.OBServiceLinePlanID = data.OBServiceLinePlanID + left join [fw].[DimModelingServiceLine] dim with (readuncommitted) on dim.ModelingServiceLineID = data.ModelingServiceLineID + where + dim.MemberGUID is null + + +-- Forecast Detail Dimension + delete + data + from + [clientob].[FactServiceLine] data with (readuncommitted) + inner join [ob].[DimOBServiceLinePlan] db with (readuncommitted) on db.OBServiceLinePlanID = data.OBServiceLinePlanID + left join [ob].[DimOBForecastDetail] dim with (readuncommitted) on dim.OBForecastDetailID = data.OBForecastDetailID + where + dim.MemberGUID is null + + +--***Fact Reimbursement Account********************************************* +-- Reimbursement Plan Dimension + delete + data + from + [clientob].[FactReimbursementAccount] data with (readuncommitted) + left join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + where + db.MemberGUID is null + + +-- Account Dimension + delete + data + from + [clientob].[FactReimbursementAccount] data with (readuncommitted) + inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + left join [fw].[DimAccount] dim with (readuncommitted) on dim.AccountID = data.AccountID + where + dim.MemberGUID is null + + +-- Patient Reimbursement Group Dimension + delete + data + from + [clientob].[FactReimbursementAccount] data with (readuncommitted) + inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + left join [fw].[DimPatientReimbursementGroup] dim with (readuncommitted) on dim.PatientReimbursementGroupID = data.PatientReimbursementGroupID + where + dim.MemberGUID is null + + +--***Fact Reimbursement ********************************************* +-- Reimbursement Plan Dimension + delete + data + from + [clientob].[FactReimbursement] data with (readuncommitted) + left join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + where + db.MemberGUID is null + + +-- Forecast Detail Dimension + delete + data + from + [clientob].[FactReimbursement] data with (readuncommitted) + inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + left join [ob].[DimOBForecastDetail] dim with (readuncommitted) on dim.OBForecastDetailID = data.OBForecastDetailID + where + dim.MemberGUID is null + + +-- Patient Reimbursement Group Dimension + delete + data + from + [clientob].[FactReimbursement] data with (readuncommitted) + inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + left join [fw].[DimPatientReimbursementGroup] dim with (readuncommitted) on dim.PatientReimbursementGroupID = data.PatientReimbursementGroupID + where + dim.MemberGUID is null + + +-- Payor Group Dimension + delete + data + from + [clientob].[FactReimbursement] data with (readuncommitted) + inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + left join [fw].[DimPayorGroup] dim with (readuncommitted) on dim.PayorGroupID = data.PayorGroupID + where + dim.MemberGUID is null + + +-- Payor Dimension + delete + data + from + [clientob].[FactReimbursement] data with (readuncommitted) + inner join [ob].[DimOBReimbursementPlan] db with (readuncommitted) on db.OBReimbursementPlanID = data.OBReimbursementPlanID + left join [fw].[DimPayor] dim with (readuncommitted) on dim.PayorID = data.PayorID + where + dim.MemberGUID is null + +RETURN +GO + + +--------------------------------------------- + +-- ob.procDeleteFactData +CREATE PROCEDURE [ob].[procDeleteFactData] +AS +/************************************************************ +** Author: unknown +** Create Date: Unknown +** Description: Deletes all CAP Fact tables - used only for GM releases - NEVER RUN ON CLIENT DATABASES +** Last Modified: 2013-11-07 +** GM Release: 2013-11-19 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2013-11-07 akk 65765 Filtering out mapping tables from the delete +** +*************************************************************/ + +BEGIN + -- SET NOCOUNT ON added to prevent extra result sets from + -- interfering with SELECT statements. + SET NOCOUNT ON; + + DECLARE @SCHEMA nvarchar(256) + DECLARE @FactTableName nvarchar(256) + DECLARE @SQL nvarchar(1024) + DECLARE @SQL2 nvarchar(1024) + DECLARE FactTableCursor CURSOR FOR +--==== BEGIN CID 1 ==== + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in('ob', 'clientob') ) and t.name like 'fact%' and t.name not in ('FactGlobalSpreads','FactBudgetYearReportingCrosswalk') and t.name not like '%map' order by t.name +--==== END CID 1 ==== + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + set @SQL = 'truncate table ' + @SCHEMA + '.' + @FactTableName + set @SQL2='DBCC CHECKIDENT (''' + + @SCHEMA + '.' + @FactTableName + ''', RESEED, 1)' + --print @SQL + --print @SQL2 + EXECUTE sp_executesql @SQL + EXECUTE sp_executesql @SQL2 + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + + truncate table [ob].[ReconciliationTarget] + truncate table [ob].[JobCodeReconciliationTarget] + truncate table [ob].[PayCodeReconciliationTarget] + truncate table [ob].[StatisticsEntityReconciliationTarget] + + --Rebuild Indexes and Update Statistics + exec [ob].[procOptimizationRebuildIndexesData] + exec [ob].[procOptimizationRebuildIndexesMapping] +END + + +RETURN +GO + + +--------------------------------------------- + +-- ob.procDepartmentalBudgetMaintenance +CREATE proc [ob].[procDepartmentalBudgetMaintenance] + @planGUIDList nvarchar(max), + @isForcingRefresh bit = 0 +as + +--/////////////////// DEPRECATED USE SYSTEM CENTER /////////////////// + + +-- declare @budgetSectionGUID uniqueidentifier +-- select @budgetSectionGUID = MemberGUID from ob.DimDepartmentalBudgetPH (readuncommitted) where Name = 'Current Budget' +-- +----if self placeholder exists, assume this proc is already done and can exit +-- if (@isForcingRefresh = 0) begin +-- if((select count(*) from ScoreFillin FI (readuncommitted) where FI.ModelGUID in(select cs.[guid] from dbo.ConvertCSGuidsToTable(@planGUIDList, ',') cs) and FI.PlaceholderSectionMemberGUID = @budgetSectionGUID) > 0) begin +-- return +-- end +-- end +-- +----set departmental budget self placeholder +-- insert into ScoreFillin(ModelGUID, PlaceholderSectionMemberGUID, PlaceholderIndex, FillinMemberGUID, FillinMemberName) +-- select +-- P.PlanGUID, +-- @budgetSectionGUID, +-- 0, +-- P.PlanGUID, +-- P.Name +-- from +-- XPlan P (readuncommitted) +-- where +-- P.PlanGUID in(select cs.[guid] from dbo.ConvertCSGuidsToTable(@planGUIDList, ',') cs) +-- and not exists(select 1 from ScoreFillin FI (readuncommitted) where FI.ModelGUID = P.PlanGUID and FI.PlaceholderSectionMemberGUID = @budgetSectionGUID) +-- +----get year for year fill-ins +-- declare @yearSectionGUID uniqueidentifier +-- select @yearSectionGUID = MemberGUID from fw.DimFiscalYearPH (readuncommitted) where Name = 'Selected Year' +----set dept budget year fill-ins +-- insert into ScoreFillin(ModelGUID, PlaceholderSectionMemberGUID, PlaceholderIndex, FillinMemberGUID, FillinMemberName) +-- select +-- P.MemberGUID, +-- @yearSectionGUID, +-- (FY.FiscalYearID - P.BaseYear + 1), +-- FY.MemberGUID, +-- FY.Name +-- from +-- ob.DimDepartmentalBudget P (readuncommitted) +-- inner join fw.DimFiscalYear FY (readuncommitted) on FY.FiscalYearID = P.BaseYear - 1 or FY.FiscalYearID = P.BaseYear or FY.FiscalYearID = P.BaseYear + 1 +-- where +-- P.MemberGUID in(select cs.[guid] from dbo.ConvertCSGuidsToTable(@planGUIDList, ',') cs) +-- and not exists(select 1 from ScoreFillin FI (readuncommitted) where FI.ModelGUID = P.MemberGUID and FI.PlaceholderSectionMemberGUID = @yearSectionGUID) +GO + + +--------------------------------------------- + +-- ob.procDepartmentalBudgetMaintenanceAll +CREATE proc [ob].[procDepartmentalBudgetMaintenanceAll] +as + declare @planguids nvarchar(max) + select @planguids = coalesce(@planguids + ',','') + cast(MemberGUID as nvarchar(128)) from ob.DimDepartmentalBudget (readuncommitted) where MemberGUID not in(select p.PlanGUID from XPlan p (readuncommitted) where p.IsDeletedPlan = 1) + + exec ob.procDepartmentalBudgetMaintenance @planguids, 1 +GO + + +--------------------------------------------- + +-- ob.procExceptionsDepartmentalBudgetPopulate +CREATE PROCEDURE [ob].[procExceptionsDepartmentalBudgetPopulate] + @ClearAcknowledged BIT = 0, + @OBExceptionsID INT = NULL +AS +/************************************************************ +** Author: akowalski +** Create Date: 2014-04-30 +** Description: Populates Departmental Budget Exception Table +** Last Modified: 2016-08-02 +** GM Release: 2014.3 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2014-10-09 JG Adjusting the widget height of the report +** 2 2015-01-08 akk Changing proc to not use view for better performance +** 3 2016-08-02 kf Add @OBExceptionsID parameter, remove cursor +** 4 2016-08-03 kf Remove widgets update +** 5 2016-08-11 kf Remove duplications +** 6 2019-02-21 GF Remove backup of exceptions +*************************************************************/ + +DECLARE @dbname NVARCHAR(1000) = (DB_Name()) +--EXEC TempTableBackups.dbo.procBackupTable @dbname, 'FactDepartmentBudgetExceptions', 'ob' + +-- Logging ************************************************************************ +DECLARE @higuid UNIQUEIDENTIFIER +EXEC procLogScript 'Updating Department Budget Exceptions', @higuid OUTPUT + +-- Create new exceptions temp table ******************************************** + +CREATE TABLE #NewExceptionsToInsert( + [OBExceptionsID] [int] NOT NULL DEFAULT ((0)), + [DepartmentalBudgetID] [int] NOT NULL DEFAULT ((0)), + [Detail] [nvarchar](2000) NOT NULL DEFAULT ('') +) + +DECLARE @isExecuting BIT = 1 +DECLARE @Model NVARCHAR(256) = 'Departmental Budget' +DECLARE @ModelIDName NVARCHAR(256) = '[DepartmentalBudgetID]' +DECLARE @sqli VARCHAR(MAX) +DECLARE @OBExceptionsIDStr VARCHAR(MAX) +DECLARE @View NVARCHAR(100) + +DECLARE @exceptions TABLE (OBExceptionsID INT, ViewName NVARCHAR(100)) + +INSERT INTO @exceptions (OBExceptionsID, ViewName) +SELECT OBExceptionsID, ViewName +FROM [ob].[DimOBExceptions] e +WHERE e.Model = @Model AND (@OBExceptionsID IS NULL OR e.OBExceptionsID = @OBExceptionsID) + +DECLARE @Count INT +SELECT @Count = COUNT(1) FROM @exceptions + +WHILE @Count > 0 +BEGIN + SELECT TOP 1 @OBExceptionsIDStr = OBExceptionsID, @View = ViewName + FROM @exceptions + + SET @sqli = + 'INSERT INTO #NewExceptionsToInsert ([OBExceptionsID], ' + @ModelIDName + ', [Detail]) + SELECT DISTINCT + ' + @OBExceptionsIDStr + ' as OBExceptionsID, + e.' + @ModelIDName + ', + e.detail + FROM ' + @View + ' e' + + IF @isExecuting = 1 BEGIN + EXEC(@sqli) + END ELSE BEGIN + PRINT @sqli + END + + DELETE FROM @exceptions + WHERE OBExceptionsID = @OBExceptionsIDStr + + SET @Count -= 1 +END + +DECLARE @seedID INT + +IF(@ClearAcknowledged=1) +BEGIN + DELETE FROM [ob].[FactDepartmentBudgetExceptions] + WHERE (@OBExceptionsID IS NULL OR OBExceptionsID = @OBExceptionsID) + + SET @seedID = (SELECT MAX(rowid) FROM [ob].[FactDepartmentBudgetExceptions])+1 + IF @seedID IS NULL + BEGIN + SET @seedID=1 + END + DBCC CHECKIDENT ("ob.FactDepartmentBudgetExceptions", RESEED, @seedID) + + INSERT INTO [ob].[FactDepartmentBudgetExceptions] + ([OBExceptionsID], [DepartmentalBudgetID], [Detail], [Acknowledged], [HistoryItemGuid]) + SELECT + e.OBExceptionsID, + e.DepartmentalBudgetID, + e.detail, + 0 as Acknowledged, + @higuid as HistoryItemGUID + FROM #NewExceptionsToInsert e +END +ELSE +BEGIN + DELETE FROM [ob].[FactDepartmentBudgetExceptions] + WHERE Acknowledged = 0 AND (@OBExceptionsID IS NULL OR OBExceptionsID = @OBExceptionsID) + + SET @seedID = (SELECT MAX(rowid) FROM [ob].[FactDepartmentBudgetExceptions])+1 + IF @seedID IS NULL + BEGIN + SET @seedID=1 + END + DBCC CHECKIDENT ("ob.FactDepartmentBudgetExceptions", RESEED, @seedID) + + INSERT INTO [ob].[FactDepartmentBudgetExceptions] + ([OBExceptionsID], [DepartmentalBudgetID], [Detail], [Acknowledged], [HistoryItemGuid]) + SELECT + e.OBExceptionsID, + e.DepartmentalBudgetID, + e.detail, + 0 as Acknowledged, + @higuid as HistoryItemGUID + FROM #NewExceptionsToInsert e + WHERE NOT EXISTS + (SELECT 1 FROM [ob].[FactDepartmentBudgetExceptions] target + WHERE e.DepartmentalBudgetID=target.DepartmentalBudgetID + AND e.OBExceptionsID=target.OBExceptionsID + AND e.detail=target.detail + ) +END +GO + + +--------------------------------------------- + +-- ob.procExceptionsGlobalStatsPopulate +CREATE PROCEDURE [ob].[procExceptionsGlobalStatsPopulate] + @ClearAcknowledged BIT = 0, + @OBExceptionsID INT = NULL +AS +/************************************************************ +** Author: akowalski +** Create Date: 2015-01-09 +** Description: Populates Global Stats Exception Table +** Last Modified: 2015-08-02 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-08-02 kf Add @OBExceptionsID parameter, remove cursor +** 2 2016-08-03 kf Remove widgets update +** 3 2016-08-11 kf Remove duplications +** 4 2019-02-21 GF Remove backup of exceptions +*************************************************************/ + +DECLARE @dbname NVARCHAR(1000) = (DB_Name()) +--EXEC TempTableBackups.dbo.procBackupTable @dbname, 'FactGlobalStatisticExceptions', 'ob' + +-- Logging ************************************************************************ +DECLARE @higuid UNIQUEIDENTIFIER +EXEC procLogScript 'Updating Global Stats Exceptions' , @higuid OUTPUT + +-- Create new exceptions temp table ******************************************** + +CREATE TABLE #NewExceptionsToInsert( + [OBExceptionsID] [int] NOT NULL DEFAULT ((0)), + [OBGlobalStatisticsPlanID] [int] NOT NULL DEFAULT ((0)), + [Detail] [nvarchar](2000) NOT NULL DEFAULT ('') +) + +DECLARE @isExecuting BIT = 1 +DECLARE @Model NVARCHAR(256) = 'Global Statistics' +DECLARE @ModelIDName NVARCHAR(256) = '[OBGlobalStatisticsPlanID]' +DECLARE @sqli VARCHAR(MAX) +DECLARE @OBExceptionsIDStr VARCHAR(MAX) +DECLARE @View NVARCHAR(100) + +DECLARE @exceptions TABLE (OBExceptionsID INT, ViewName NVARCHAR(100)) + +INSERT INTO @exceptions (OBExceptionsID, ViewName) +SELECT OBExceptionsID, ViewName +FROM [ob].[DimOBExceptions] e +WHERE e.Model = @Model AND (@OBExceptionsID IS NULL OR e.OBExceptionsID = @OBExceptionsID) + +DECLARE @Count INT +SELECT @Count = COUNT(1) FROM @exceptions + +WHILE @Count > 0 +BEGIN + SELECT TOP 1 @OBExceptionsIDStr = OBExceptionsID, @View = ViewName + FROM @exceptions + + SET @sqli = + 'INSERT INTO #NewExceptionsToInsert ([OBExceptionsID], ' + @ModelIDName + ', [Detail]) + SELECT DISTINCT + ' + @OBExceptionsIDStr + ' as OBExceptionsID, + e.' + @ModelIDName + ', + e.detail + FROM ' + @View + ' e' + + IF @isExecuting = 1 BEGIN + EXEC(@sqli) + END ELSE BEGIN + PRINT @sqli + END + + DELETE FROM @exceptions + WHERE OBExceptionsID = @OBExceptionsIDStr + + SET @Count -= 1 +END + +DECLARE @seedID INT + +IF(@ClearAcknowledged=1) +BEGIN + DELETE FROM [ob].[FactGlobalStatisticExceptions] + WHERE (@OBExceptionsID IS NULL OR OBExceptionsID = @OBExceptionsID) + + SET @seedID = (SELECT MAX(rowid) FROM [ob].[FactGlobalStatisticExceptions])+1 + IF @seedID IS NULL + BEGIN + SET @seedID=1 + END + DBCC CHECKIDENT ("ob.FactGlobalStatisticExceptions", RESEED, @seedID) + + INSERT INTO [ob].[FactGlobalStatisticExceptions] + ([OBExceptionsID], [OBGlobalStatisticsPlanID], [Detail], [Acknowledged], [HistoryItemGuid]) + SELECT + e.OBExceptionsID, + e.OBGlobalStatisticsPlanID, + e.detail, + 0 as Acknowledged, + @higuid as HistoryItemGUID + FROM #NewExceptionsToInsert e +END +ELSE +BEGIN + DELETE FROM [ob].[FactGlobalStatisticExceptions] + WHERE Acknowledged = 0 AND (@OBExceptionsID IS NULL OR OBExceptionsID = @OBExceptionsID) + + SET @seedID = (SELECT MAX(rowid) FROM [ob].[FactGlobalStatisticExceptions])+1 + IF @seedID IS NULL + BEGIN + SET @seedID=1 + END + DBCC CHECKIDENT ("ob.FactGlobalStatisticExceptions", RESEED, @seedID) + + INSERT INTO [ob].[FactGlobalStatisticExceptions] + ([OBExceptionsID], [OBGlobalStatisticsPlanID], [Detail], [Acknowledged], [HistoryItemGuid]) + SELECT + e.OBExceptionsID, + e.OBGlobalStatisticsPlanID, + e.detail, + 0 as Acknowledged, + @higuid as HistoryItemGUID + FROM #NewExceptionsToInsert e + WHERE NOT EXISTS + (SELECT 1 FROM [ob].[FactGlobalStatisticExceptions] target + WHERE e.OBGlobalStatisticsPlanID=target.OBGlobalStatisticsPlanID + AND e.OBExceptionsID=target.OBExceptionsID + AND e.detail=target.detail + ) +END +GO + + +--------------------------------------------- + +-- ob.procExceptionsReimbursementPopulate +CREATE PROCEDURE [ob].[procExceptionsReimbursementPopulate] + @ClearAcknowledged BIT = 0, + @OBExceptionsID INT = NULL +AS +/************************************************************ +** Author: akowalski +** Create Date: 2015-01-09 +** Description: Populates Reimbursement Exception Table +** Last Modified: 2016-08-02 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-08-02 kf Add @OBExceptionsID parameter, remove cursor +** 2 2016-08-03 kf Remove widgets update +** 3 2016-08-11 kf Remove duplications +** 4 2019-02-21 GF Remove backup of exceptions +*************************************************************/ + +DECLARE @dbname NVARCHAR(1000) = (DB_Name()) +--EXEC TempTableBackups.dbo.procBackupTable @dbname, 'FactReimbursementExceptions', 'ob' + +-- Logging ************************************************************************ +DECLARE @higuid UNIQUEIDENTIFIER +EXEC procLogScript 'Updating Reimbursement Exceptions' , @higuid OUTPUT + +-- Create new exceptions temp table ******************************************** + +CREATE TABLE #NewExceptionsToInsert( + [OBExceptionsID] [int] NOT NULL DEFAULT ((0)), + [OBReimbursementPlanID] [int] NOT NULL DEFAULT ((0)), + [Detail] [nvarchar](2000) NOT NULL DEFAULT ('') +) + +DECLARE @isExecuting BIT = 1 +DECLARE @Model NVARCHAR(256) = 'Reimbursement' +DECLARE @ModelIDName NVARCHAR(256) = '[OBReimbursementPlanID]' +DECLARE @sqli VARCHAR(MAX) +DECLARE @OBExceptionsIDStr VARCHAR(MAX) +DECLARE @View NVARCHAR(100) + +DECLARE @exceptions TABLE (OBExceptionsID INT, ViewName NVARCHAR(100)) + +INSERT INTO @exceptions (OBExceptionsID, ViewName) +SELECT OBExceptionsID, ViewName +FROM [ob].[DimOBExceptions] e +WHERE e.Model = @Model AND (@OBExceptionsID IS NULL OR e.OBExceptionsID = @OBExceptionsID) + +DECLARE @Count INT +SELECT @Count = COUNT(1) FROM @exceptions + +WHILE @Count > 0 +BEGIN + SELECT TOP 1 @OBExceptionsIDStr = OBExceptionsID, @View = ViewName + FROM @exceptions + + SET @sqli = + 'INSERT INTO #NewExceptionsToInsert ([OBExceptionsID], ' + @ModelIDName + ', [Detail]) + SELECT DISTINCT + ' + @OBExceptionsIDStr + ' as OBExceptionsID, + e.' + @ModelIDName + ', + e.detail + FROM ' + @View + ' e' + + IF @isExecuting = 1 BEGIN + EXEC(@sqli) + END ELSE BEGIN + PRINT @sqli + END + + DELETE FROM @exceptions + WHERE OBExceptionsID = @OBExceptionsIDStr + + SET @Count -= 1 +END + +DECLARE @seedID INT + +IF(@ClearAcknowledged=1) +BEGIN + DELETE FROM [ob].[FactReimbursementExceptions] + WHERE (@OBExceptionsID IS NULL OR OBExceptionsID = @OBExceptionsID) + + SET @seedID = (SELECT MAX(rowid) FROM [ob].[FactReimbursementExceptions])+1 + IF @seedID IS NULL + BEGIN + SET @seedID=1 + END + DBCC CHECKIDENT ("ob.FactReimbursementExceptions", RESEED, @seedID) + + INSERT INTO [ob].[FactReimbursementExceptions] + ([OBExceptionsID], [OBReimbursementPlanID], [Detail], [Acknowledged], [HistoryItemGuid]) + SELECT + e.OBExceptionsID, + e.OBReimbursementPlanID, + e.detail, + 0 as Acknowledged, + @higuid as HistoryItemGUID + FROM #NewExceptionsToInsert e +END +ELSE +BEGIN + DELETE FROM [ob].[FactReimbursementExceptions] + WHERE Acknowledged=0 AND (@OBExceptionsID IS NULL OR OBExceptionsID = @OBExceptionsID) + + SET @seedID = (SELECT MAX(rowid) FROM [ob].[FactReimbursementExceptions])+1 + IF @seedID IS NULL + BEGIN + SET @seedID=1 + END + DBCC CHECKIDENT ("ob.FactReimbursementExceptions", RESEED, @seedID) + + INSERT INTO [ob].[FactReimbursementExceptions] + ([OBExceptionsID], [OBReimbursementPlanID], [Detail], [Acknowledged], [HistoryItemGuid]) + SELECT + e.OBExceptionsID, + e.OBReimbursementPlanID, + e.detail, + 0 as Acknowledged, + @higuid as HistoryItemGUID + FROM #NewExceptionsToInsert e + WHERE NOT EXISTS + (SELECT 1 FROM [ob].[FactReimbursementExceptions] target + WHERE e.OBReimbursementPlanID=target.OBReimbursementPlanID + AND e.OBExceptionsID=target.OBExceptionsID + AND e.detail=target.detail + ) +END +GO + + +--------------------------------------------- + +-- ob.procExceptionsServiceLinePopulate +CREATE PROCEDURE [ob].[procExceptionsServiceLinePopulate] + @ClearAcknowledged BIT = 0, + @OBExceptionsID INT = NULL +AS +/************************************************************ +** Author: akowalski +** Create Date: 2015-01-09 +** Description: Populates Service Line Exception Table +** Last Modified: 2016-08-02 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2016-08-02 kf Add @OBExceptionsID parameter, remove cursor +** 2 2016-08-03 kf Remove widgets update +** 3 2016-08-11 kf Remove duplications +** 4 2019-02-21 GF Remove backup of exceptions +*************************************************************/ + +DECLARE @dbname NVARCHAR(1000) = (DB_Name()) +--EXEC TempTableBackups.dbo.procBackupTable @dbname, 'FactServiceLineExceptions', 'ob' + +-- Logging ************************************************************************ +DECLARE @higuid UNIQUEIDENTIFIER +EXEC procLogScript 'Updating Service Line Exceptions' , @higuid OUTPUT + +-- Create new exceptions temp table ******************************************** + +CREATE TABLE #NewExceptionsToInsert( + [OBExceptionsID] [int] NOT NULL DEFAULT ((0)), + [OBServiceLinePlanID] [int] NOT NULL DEFAULT ((0)), + [Detail] [nvarchar](2000) NOT NULL DEFAULT ('') +) + +DECLARE @isExecuting BIT = 1 +DECLARE @Model NVARCHAR(256) = 'Service Line' +DECLARE @ModelIDName NVARCHAR(256) = '[OBServiceLinePlanID]' +DECLARE @sqli VARCHAR(MAX) +DECLARE @OBExceptionsIDStr VARCHAR(MAX) +DECLARE @View NVARCHAR(100) + +DECLARE @exceptions TABLE (OBExceptionsID INT, ViewName NVARCHAR(100)) + +INSERT INTO @exceptions (OBExceptionsID, ViewName) +SELECT OBExceptionsID, ViewName +FROM [ob].[DimOBExceptions] e +WHERE e.Model = @Model AND (@OBExceptionsID IS NULL OR e.OBExceptionsID = @OBExceptionsID) + +DECLARE @Count INT +SELECT @Count = COUNT(1) FROM @exceptions + +WHILE @Count > 0 +BEGIN + SELECT TOP 1 @OBExceptionsIDStr = OBExceptionsID, @View = ViewName + FROM @exceptions + + SET @sqli = + 'INSERT INTO #NewExceptionsToInsert ([OBExceptionsID], ' + @ModelIDName + ', [Detail]) + SELECT DISTINCT + ' + @OBExceptionsIDStr + ' as OBExceptionsID, + e.' + @ModelIDName + ', + e.detail + FROM ' + @View + ' e' + + IF @isExecuting = 1 BEGIN + EXEC(@sqli) + END ELSE BEGIN + PRINT @sqli + END + + DELETE FROM @exceptions + WHERE OBExceptionsID = @OBExceptionsIDStr + + SET @Count -= 1 +END + +DECLARE @seedID INT + +IF(@ClearAcknowledged=1) +BEGIN + DELETE FROM [ob].[FactServiceLineExceptions] + WHERE (@OBExceptionsID IS NULL OR OBExceptionsID = @OBExceptionsID) + + SET @seedID = (SELECT MAX(rowid) FROM [ob].[FactServiceLineExceptions])+1 + IF @seedID IS NULL + BEGIN + SET @seedID=1 + END + DBCC CHECKIDENT ("ob.FactServiceLineExceptions", RESEED, @seedID) + + INSERT INTO [ob].[FactServiceLineExceptions] + ([OBExceptionsID], [OBServiceLinePlanID], [Detail], [Acknowledged], [HistoryItemGuid]) + SELECT + e.OBExceptionsID, + e.OBServiceLinePlanID, + e.detail, + 0 as Acknowledged, + @higuid as HistoryItemGUID + FROM #NewExceptionsToInsert e +END +ELSE +BEGIN + DELETE FROM [ob].[FactServiceLineExceptions] + WHERE Acknowledged=0 AND (@OBExceptionsID IS NULL OR OBExceptionsID = @OBExceptionsID) + + SET @seedID = (SELECT MAX(rowid) FROM [ob].[FactServiceLineExceptions])+1 + IF @seedID IS NULL + BEGIN + SET @seedID=1 + END + DBCC CHECKIDENT ("ob.FactServiceLineExceptions", RESEED, @seedID) + + INSERT INTO [ob].[FactServiceLineExceptions] + ([OBExceptionsID], [OBServiceLinePlanID], [Detail], [Acknowledged], [HistoryItemGuid]) + SELECT + e.OBExceptionsID, + e.OBServiceLinePlanID, + e.detail, + 0 as Acknowledged, + @higuid as HistoryItemGUID + FROM #NewExceptionsToInsert e + WHERE NOT EXISTS + (SELECT 1 FROM [ob].[FactServiceLineExceptions] target + WHERE e.OBServiceLinePlanID=target.OBServiceLinePlanID + AND e.OBExceptionsID=target.OBExceptionsID + AND e.detail=target.detail + ) +END +GO + + +--------------------------------------------- + +-- ob.procExceptionsUpdateExplanationDashboardWidget +CREATE proc ob.procExceptionsUpdateExplanationDashboardWidget +as +/************************************************************ +** Author: akowalski +** Create Date: 2015-02-02 +** Description: Updates the exception explanation dashboard widget with the latest information from the dimension +** Last Modified: 2015-02-02 +** GM Release: 2015.2 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +*************************************************************/ + +DECLARE @isExecuting bit = 1 +DECLARE @Model nvarchar(200) +DECLARE @Name nvarchar(400) +DECLARE @Severity nvarchar(200) +DECLARE @Description nvarchar(max) +DECLARE @Resolution nvarchar(max) +DECLARE @sqli nvarchar(max) = '' + +DECLARE Models CURSOR FOR + select distinct model from [ob].[DimOBExceptions] where OBExceptionsID<>0 order by Model + +open Models + +FETCH NEXT FROM Models + INTO @Model +WHILE (@@FETCH_STATUS = 0) + BEGIN + SET @sqli = @sqli + '<p><strong><u><font size="3">' + @Model + '</font></u></strong></p>' + + DECLARE Exceptions CURSOR FOR + select Name,Severity,Description,Resolution from [ob].[DimOBExceptions] where OBExceptionsID<>0 and model=@Model order by severity,SortOrder + + open Exceptions + + FETCH NEXT FROM Exceptions + INTO @Name, @Severity, @Description, @Resolution + WHILE (@@FETCH_STATUS = 0) + BEGIN + SET @sqli = @sqli + '<p><strong><u>' + @Name + '<br></u>Severity:</strong> ' + @Severity + '<br><strong>Description:</strong> ' + @Description + '&nbsp;&nbsp;<br><strong>Resolution:</strong> ' + @Resolution + '</p>' + + FETCH NEXT FROM Exceptions INTO @Name, @Severity, @Description, @Resolution + END + CLOSE Exceptions + DEALLOCATE Exceptions + FETCH NEXT FROM Models INTO @Model + END +CLOSE Models +DEALLOCATE Models + +SET @sqli = @sqli + '' + +if @isExecuting = 1 begin + update [dbo].[DesktopWidget] + set WidgetXML=@sqli + where DesktopWidgetGUID='cd85554c-c566-4e02-8a55-57a6075d047e' +end else begin + print @sqli +end + +RETURN +GO + + +--------------------------------------------- + +-- ob.procFactPayrollToAccountCrosswalkAddMissing +create proc ob.procFactPayrollToAccountCrosswalkAddMissing +as + if (exists(select 1 from ob.SystemSetting where Name = 'Payroll To GL Link Dollars Configuration' and Value = 'BothUnique')) begin + ;with groupedRecords as( + select + jc.JobCodeGroupID, + cw.PayCodeGroupID, + cw.AccountID, + cw.UnitTypeID + from + [clientob].[FactPayrollToAccountCrosswalk] cw + inner join fw.DimJobCode jc on jc.JobCodeID = cw.JobCodeID + where + cw.UnitTypeID = 34 + group by + jc.JobCodeGroupID, + cw.PayCodeGroupID, + cw.AccountID, + cw.UnitTypeID + ) + insert into clientob.FactPayrollToAccountCrosswalk (JobCodeID, PayCodeGroupID, AccountID, UnitTypeID) + select + jc.JobCodeID, + cw.PayCodeGroupID, + cw.AccountID, + cw.UnitTypeID + from + groupedRecords cw + inner join fw.DimJobCode jc on jc.JobCodeGroupID = cw.JobCodeGroupID + where + not exists(select 1 from [clientob].[FactPayrollToAccountCrosswalk] ex where ex.JobCodeID = jc.JobCodeID and ex.PayCodeGroupID = cw.PayCodeGroupID and ex.AccountID = cw.AccountID and ex.UnitTypeID = cw.UnitTypeID) + end + + if (exists(select 1 from ob.SystemSetting where Name = 'Payroll To GL Link Hours Configuration' and Value = 'BothUnique')) begin + ;with groupedRecords as( + select + jc.JobCodeGroupID, + cw.PayCodeGroupID, + cw.AccountID, + cw.UnitTypeID + from + [clientob].[FactPayrollToAccountCrosswalk] cw + inner join fw.DimJobCode jc on jc.JobCodeID = cw.JobCodeID + where + cw.UnitTypeID = 51 + group by + jc.JobCodeGroupID, + cw.PayCodeGroupID, + cw.AccountID, + cw.UnitTypeID + ) + insert into clientob.FactPayrollToAccountCrosswalk (JobCodeID, PayCodeGroupID, AccountID, UnitTypeID) + select + jc.JobCodeID, + cw.PayCodeGroupID, + cw.AccountID, + cw.UnitTypeID + from + groupedRecords cw + inner join fw.DimJobCode jc on jc.JobCodeGroupID = cw.JobCodeGroupID + where + not exists(select 1 from [clientob].[FactPayrollToAccountCrosswalk] ex where ex.JobCodeID = jc.JobCodeID and ex.PayCodeGroupID = cw.PayCodeGroupID and ex.AccountID = cw.AccountID and ex.UnitTypeID = cw.UnitTypeID) + end +GO + + +--------------------------------------------- + +-- ob.procFactReportAccountWithStaffingDetailInsert +CREATE proc ob.procFactReportAccountWithStaffingDetailInsert + @planGUID uniqueidentifier = '00000000-0000-0000-0000-000000000000' +as + if (not exists(select 1 from ob.SystemSetting where Name = 'OB Staffing Detail Report Enabled' and Value = '1')) begin + return + end + + --get budget to refresh + declare @budgetid int + if (@planGUID != '00000000-0000-0000-0000-000000000000') begin + select @budgetid = DepartmentalBudgetID from ob.viewDimDepartmentalBudget where MemberGUID = @planGUID + if (@budgetid is null or @budgetid = 0) begin + return + end + end else begin + set @budgetid = 0 + end + + --remove existing data + if (@budgetid = 0) begin + truncate table [ob].[FactReportAccountWithStaffingDetail] + exec dbo.procTableReseedIdentity 'ob', 'FactReportAccountWithStaffingDetail', 1 + end else begin + delete from [ob].[FactReportAccountWithStaffingDetail] where DepartmentalBudgetID = @budgetid + end + + declare @sql nvarchar(max) + set @sql = ' + declare @validDataTypeTimeClassFiscalYearCombos table ( DataTypeID tinyint, FiscalYearID int, TimeClassID tinyint, IsCY bit ) + insert into @validDataTypeTimeClassFiscalYearCombos select * from [ob].[viewValidDataTypeTimeClassFiscalYearCombos] + ' + + --staffing data + set @sql = @sql + ' + insert into [ob].[FactReportAccountWithStaffingDetail] (DepartmentalBudgetID, AccountID, JobCodeID, PayCodeGroupID, FiscalYearID, TimeClassID, UnitTypeID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, YTD, Total) + select + DepartmentalBudgetID = vw.DepartmentalBudgetID, + AccountID = vw.AccountID, + JobCodeID = vw.JobCodeID, + PayCodeGroupID = vw.PayCodeGroupID, + FiscalYearID = vw.FiscalYearID, + TimeClassID = vw.TimeClassID, + UnitTypeID = vw.UnitTypeID, + Month01 = vw.Month01, + Month02 = vw.Month02, + Month03 = vw.Month03, + Month04 = vw.Month04, + Month05 = vw.Month05, + Month06 = vw.Month06, + Month07 = vw.Month07, + Month08 = vw.Month08, + Month09 = vw.Month09, + Month10 = vw.Month10, + Month11 = vw.Month11, + Month12 = vw.Month12, + YTD = cmb.IsCY*vw.YTD, + Total = vw.Total + from + [ob].[viewReportStaffingtoGLAccount] vw + inner join @validDataTypeTimeClassFiscalYearCombos cmb on vw.TimeClassID=cmb.TimeClassID and vw.DataTypeID=cmb.DataTypeID and vw.FiscalYearID=cmb.FiscalYearID + inner join [clientob].[FactAccount] fct with (readuncommitted) + on vw.DepartmentalBudgetID = fct.DepartmentalBudgetID + and vw.AccountID = fct.AccountID + and vw.FiscalYearID = fct.FiscalYearID + and vw.TimeClassID = fct.TimeClassID + and vw.UnitTypeID = fct.UnitTypeID + and vw.DataTypeID = fct.DataTypeID + ' + if (@budgetid != 0) begin set @sql = @sql + ' where vw.DepartmentalBudgetID = ' + cast(@budgetid as nvarchar(16)) end + set @sql = @sql + ' option (recompile);' + + --non-staffing account data + set @sql = @sql + ' + insert into [ob].[FactReportAccountWithStaffingDetail] (DepartmentalBudgetID, AccountID, JobCodeID, PayCodeGroupID, FiscalYearID, TimeClassID, UnitTypeID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, YTD, Total) + select + DepartmentalBudgetID = fct.DepartmentalBudgetID, + AccountID = fct.AccountID, + JobCodeID = 0, + PayCodeGroupID = 0, + FiscalYearID = fct.FiscalYearID, + TimeClassID = fct.TimeClassID, + UnitTypeID = fct.UnitTypeID, + Month01 = fct.Month01, + Month02 = fct.Month02, + Month03 = fct.Month03, + Month04 = fct.Month04, + Month05 = fct.Month05, + Month06 = fct.Month06, + Month07 = fct.Month07, + Month08 = fct.Month08, + Month09 = fct.Month09, + Month10 = fct.Month10, + Month11 = fct.Month11, + Month12 = fct.Month12, + YTD = cmb.IsCY*fct.YTD, + Total = fct.Total + from + [clientob].[FactAccount] fct with (readuncommitted) + inner join @validDataTypeTimeClassFiscalYearCombos cmb on fct.TimeClassID=cmb.TimeClassID and fct.DataTypeID=cmb.DataTypeID and fct.FiscalYearID=cmb.FiscalYearID + where + not exists + ( + select 1 + from [ob].[FactReportAccountWithStaffingDetail] vw + where 1=1 + and fct.DepartmentalBudgetID = vw.DepartmentalBudgetID + and fct.AccountID = vw.AccountID + and fct.FiscalYearID = vw.FiscalYearID + and fct.TimeClassID = vw.TimeClassID + and fct.UnitTypeID = vw.UnitTypeID + ) + ' + if (@budgetid != 0) begin set @sql = @sql + ' and fct.DepartmentalBudgetID = ' + cast(@budgetid as nvarchar(16)) end + set @sql = @sql + ' option (recompile);' + + --GL data historical input data discrepancy + set @sql = @sql + ' + insert into [ob].[FactReportAccountWithStaffingDetail] (DepartmentalBudgetID, AccountID, JobCodeID, PayCodeGroupID, FiscalYearID, TimeClassID, UnitTypeID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, YTD, Total) + select + DepartmentalBudgetID = fct.DepartmentalBudgetID, + AccountID = fct.AccountID, + JobCodeID = 0, + PayCodeGroupID = 0, + FiscalYearID = fct.FiscalYearID, + TimeClassID = fct.TimeClassID, + UnitTypeID = fct.UnitTypeID, + Month01 = max(fct.Month01) - sum(vw.Month01), + Month02 = max(fct.Month02) - sum(vw.Month02), + Month03 = max(fct.Month03) - sum(vw.Month03), + Month04 = max(fct.Month04) - sum(vw.Month04), + Month05 = max(fct.Month05) - sum(vw.Month05), + Month06 = max(fct.Month06) - sum(vw.Month06), + Month07 = max(fct.Month07) - sum(vw.Month07), + Month08 = max(fct.Month08) - sum(vw.Month08), + Month09 = max(fct.Month09) - sum(vw.Month09), + Month10 = max(fct.Month10) - sum(vw.Month10), + Month11 = max(fct.Month11) - sum(vw.Month11), + Month12 = max(fct.Month12) - sum(vw.Month12), + YTD = max(cast(cmb.IsCY as int))*(max(fct.YTD ) - sum(vw.YTD)), + Total = max(fct.Total ) - sum(vw.Total) + from + [clientob].[FactAccount] fct with (readuncommitted) + inner join @validDataTypeTimeClassFiscalYearCombos cmb on fct.TimeClassID=cmb.TimeClassID and fct.DataTypeID=cmb.DataTypeID and fct.FiscalYearID=cmb.FiscalYearID + inner join [ob].[viewReportStaffingtoGLAccount] vw + on fct.DepartmentalBudgetID = vw.DepartmentalBudgetID + and fct.AccountID = vw.AccountID + and fct.FiscalYearID = vw.FiscalYearID + and fct.TimeClassID = vw.TimeClassID + and fct.UnitTypeID = vw.UnitTypeID + and fct.DataTypeID = vw.DataTypeID + where + fct.DataTypeID in(4, 12)' + if (@budgetid != 0) begin set @sql = @sql + ' and fct.DepartmentalBudgetID = ' + cast(@budgetid as nvarchar(16)) end + set @sql = @sql + ' + group by + fct.DepartmentalBudgetID, + fct.AccountID, + fct.FiscalYearID, + fct.TimeClassID, + fct.UnitTypeID + having + max(fct.Total) <> SUM(vw.Total) + option (recompile) + ' + + exec(@sql) +GO + + +--------------------------------------------- + +-- ob.procFactReportFinancialStatementInsert +CREATE PROC [ob].[procFactReportFinancialStatementInsert] + @planGUID uniqueidentifier +WITH RECOMPILE +AS + set nocount on + + declare @budgetid int + if (@planGUID != '00000000-0000-0000-0000-000000000000') begin + select @budgetid = DepartmentalBudgetID from ob.viewDimDepartmentalBudget where MemberGUID = @planGUID + if (@budgetid is null or @budgetid = 0) begin + return + end + end else begin + exec [ob].[procFactReportFinancialStatementInsertAll] + return + end + + delete from [ob].[FactReportFinancialStatement] where DepartmentalBudgetID = @budgetid + + declare @sql nvarchar(max) + set @sql = ' + -- GL Dollars + insert into [ob].[FactReportFinancialStatement] (DepartmentalBudgetID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, TimeClassID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, YTD, Yearly, Total, SnapshotID) + select + data.DepartmentalBudgetID, + DD.DepartmentID, + data.AccountID, + acc.OBDollarsFinancialReportingID as FinancialReportingID, + FiscalYearID, + TimeClassID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + YTD, + Yearly, + Total, + 0 as SnapshotID -- current snapshot + from + clientob.FactAccount data with (readuncommitted) + inner join fw.DimAccount acc with (readuncommitted) on acc.AccountID=data.AccountID + inner join [ob].[DimDepartmentalBudget] DB with (readuncommitted) on DB.DepartmentalBudgetID = data.DepartmentalBudgetID + inner join [fw].[DimDepartment] DD with (readuncommitted) on DD.DepartmentID = DB.DepartmentID + inner join [fw].[DimUnitType] ut with (readuncommitted) on data.unittypeID=ut.UnitTypeID and ut.GlobalID=''Dollars'' + where + acc.IsGlobal=0 + {0} + option (recompile); + + -- Statistics + insert into [ob].[FactReportFinancialStatement] (DepartmentalBudgetID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, TimeClassID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, YTD, Yearly, Total, SnapshotID) + select + data.DepartmentalBudgetID, + DD.DepartmentID, + data.AccountID, + acc.OBUnitsFinancialReportingID as FinancialReportingID, + FiscalYearID, + TimeClassID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + YTD, + Yearly, + Total, + 0 as SnapshotID -- current snapshot + from + clientob.FactAccount data with (readuncommitted) + inner join fw.DimAccount acc with (readuncommitted) on acc.AccountID=data.AccountID + inner join [ob].[DimDepartmentalBudget] DB with (readuncommitted) on DB.DepartmentalBudgetID = data.DepartmentalBudgetID + inner join [fw].[DimDepartment] DD with (readuncommitted) on DD.DepartmentID = DB.DepartmentID + inner join [fw].[DimUnitType] ut with (readuncommitted) on data.unittypeID=ut.UnitTypeID and ut.GlobalID<>''Dollars'' + where + not exists (select 1 from [clientob].[FactGlobalStatisticsDeptMapping] fct with (readuncommitted) + inner join [ob].[DimOBGlobalStatistics] gs with (readuncommitted) on fct.OBGlobalStatisticID=gs.OBGlobalStatisticID + where fct.IsReportable=0 and gs.AccountID=acc.AccountID and fct.DepartmentID=DD.DepartmentID + ) + {0} + option (recompile); + + -- Hard Referenced Data + insert into [ob].[FactReportFinancialStatement] (DepartmentalBudgetID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, TimeClassID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, YTD, Yearly, Total, SnapshotID) + select + data.DepartmentalBudgetID, + DD.DepartmentID, + 0 as AccountID, + data.FinancialReportingID as FinancialReportingID, + FiscalYearID, + TimeClassID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + YTD, + Yearly, + Total, + 0 as SnapshotID -- current snapshot + from + [clientob].[FactReportingMonthly] data with (readuncommitted) + inner join [ob].[DimDepartmentalBudget] DB with (readuncommitted) on DB.DepartmentalBudgetID = data.DepartmentalBudgetID + inner join [fw].[DimDepartment] DD with (readuncommitted) on DD.DepartmentID = DB.DepartmentID + inner join [ob].[DimFinancialReporting] fr with (readuncommitted) on data.FinancialReportingID=fr.FinancialReportingID + where + fr.Statement=''Stats'' + {0} + option (recompile); + + -- GL Dollars (snapshot data) + insert into [ob].[FactReportFinancialStatement] (DepartmentalBudgetID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, TimeClassID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, YTD, Yearly, Total, SnapshotID) + select + data.DepartmentalBudgetID, + DD.DepartmentID, + data.AccountID, + acc.OBDollarsFinancialReportingID as FinancialReportingID, + FiscalYearID, + TimeClassID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + YTD, + Yearly, + Total, + data.OBSnapshotID as SnapshotID + from + ob.FactAccountSnapshot data with (readuncommitted) + inner join fw.DimAccount acc with (readuncommitted) on acc.AccountID=data.AccountID + inner join [ob].[DimDepartmentalBudget] DB with (readuncommitted) on DB.DepartmentalBudgetID = data.DepartmentalBudgetID + inner join [fw].[DimDepartment] DD with (readuncommitted) on DD.DepartmentID = DB.DepartmentID + inner join [fw].[DimUnitType] ut with (readuncommitted) on data.unittypeID=ut.UnitTypeID and ut.GlobalID=''Dollars'' + where + acc.IsGlobal=0 + {0} + option (recompile); + + -- Statistics (snapshot data) + insert into [ob].[FactReportFinancialStatement] (DepartmentalBudgetID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, TimeClassID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, YTD, Yearly, Total, SnapshotID) + select + data.DepartmentalBudgetID, + DD.DepartmentID, + data.AccountID, + acc.OBUnitsFinancialReportingID as FinancialReportingID, + FiscalYearID, + TimeClassID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + YTD, + Yearly, + Total, + data.OBSnapshotID as SnapshotID + from + ob.FactAccountSnapshot data with (readuncommitted) + inner join fw.DimAccount acc with (readuncommitted) on acc.AccountID=data.AccountID + inner join [ob].[DimDepartmentalBudget] DB with (readuncommitted) on DB.DepartmentalBudgetID = data.DepartmentalBudgetID + inner join [fw].[DimDepartment] DD with (readuncommitted) on DD.DepartmentID = DB.DepartmentID + inner join [fw].[DimUnitType] ut with (readuncommitted) on data.unittypeID=ut.UnitTypeID and ut.GlobalID<>''Dollars'' + where + not exists (select 1 from [clientob].[FactGlobalStatisticsDeptMapping] fct with (readuncommitted) + inner join [ob].[DimOBGlobalStatistics] gs with (readuncommitted) on fct.OBGlobalStatisticID=gs.OBGlobalStatisticID + where fct.IsReportable=0 and gs.AccountID=acc.AccountID and fct.DepartmentID=DD.DepartmentID + ) + {0} + option (recompile); + + -- Hard Referenced Data (snapshot data) + insert into [ob].[FactReportFinancialStatement] (DepartmentalBudgetID, DepartmentID, AccountID, FinancialReportingID, FiscalYearID, TimeClassID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, YTD, Yearly, Total, SnapshotID) + select + data.DepartmentalBudgetID, + DD.DepartmentID, + 0 as AccountID, + data.FinancialReportingID as FinancialReportingID, + FiscalYearID, + TimeClassID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + YTD, + Yearly, + Total, + data.OBSnapshotID as SnapshotID + from + [ob].[FactReportingMonthlySnapshot] data with (readuncommitted) + inner join [ob].[DimDepartmentalBudget] DB with (readuncommitted) on DB.DepartmentalBudgetID = data.DepartmentalBudgetID + inner join [fw].[DimDepartment] DD with (readuncommitted) on DD.DepartmentID = DB.DepartmentID + inner join [ob].[DimFinancialReporting] fr with (readuncommitted) on data.FinancialReportingID=fr.FinancialReportingID + where + fr.Statement=''Stats'' + {0} + option (recompile); + ' + select @sql = replace(@sql, '{0}', 'and DB.DepartmentalBudgetID = ' + cast(@budgetid as nvarchar(16))) + exec(@sql) + + delete from [ob].[FactReportFinancialStatement_Pivoted] where DepartmentalBudgetID = @budgetid + + set @sql = ' + insert into [ob].[FactReportFinancialStatement_Pivoted] (TimeClassID, FiscalYearID, DepartmentalBudgetID, FinancialReportingID, AccountID, SnapshotID, Total, Yearly, YTD, Amount, MaxValue, MaxValueYTD, FiscalMonthID) + SELECT source.TimeClassID, source.FiscalYearID, source.DepartmentalBudgetID, source.FinancialReportingID, source.AccountID, source.SnapshotID, source.Total, 0 as Yearly, 0 as YTD, 0 as Amount, source.Total as MaxValue, 0 as MaxValueYTD, 0 as FiscalMonthID + FROM [ob].[FactReportFinancialStatement] source with (readuncommitted) + WHERE source.Total != 0 {0} + + insert into [ob].[FactReportFinancialStatement_Pivoted] (TimeClassID, FiscalYearID, DepartmentalBudgetID, FinancialReportingID, AccountID, SnapshotID, Total, Yearly, YTD, Amount, MaxValue, MaxValueYTD, FiscalMonthID) + SELECT source.TimeClassID, source.FiscalYearID, source.DepartmentalBudgetID, source.FinancialReportingID, source.AccountID, source.SnapshotID, 0 as Total, source.Yearly, 0 as YTD, 0 as Amount, source.Yearly as MaxValue, 0 as MaxValueYTD, 0 as FiscalMonthID + FROM [ob].[FactReportFinancialStatement] source with (readuncommitted) + WHERE source.Yearly != 0 {0} + + insert into [ob].[FactReportFinancialStatement_Pivoted] (TimeClassID, FiscalYearID, DepartmentalBudgetID, FinancialReportingID, AccountID, SnapshotID, Total, Yearly, YTD, Amount, MaxValue, MaxValueYTD, FiscalMonthID) + SELECT source.TimeClassID, source.FiscalYearID, source.DepartmentalBudgetID, source.FinancialReportingID, source.AccountID, source.SnapshotID, 0 as Total, 0 as Yearly, source.YTD, 0 as Amount, source.YTD as MaxValue, 0 as MaxValueYTD, 0 as FiscalMonthID + FROM [ob].[FactReportFinancialStatement] source with (readuncommitted) + WHERE source.YTD != 0 {0} + + insert into [ob].[FactReportFinancialStatement_Pivoted] (TimeClassID, FiscalYearID, DepartmentalBudgetID, FinancialReportingID, AccountID, SnapshotID, Total, Yearly, YTD, Amount, MaxValue, MaxValueYTD, FiscalMonthID) + SELECT source.TimeClassID, source.FiscalYearID, source.DepartmentalBudgetID, source.FinancialReportingID, source.AccountID, source.SnapshotID, 0 as Total, 0 as Yearly, 0 as YTD, source.Amount, source.Amount as MaxValue, source.YTD as MaxValueYTD, fm.FiscalMonthID + FROM + (select * from [ob].[FactReportFinancialStatement] with (readuncommitted)) p + unpivot (Amount for MonthColumnName in (Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12)) as source + inner join fw.DimFiscalMonth fm with (readuncommitted) on source.MonthColumnName = fm.MonthColumnName + where (source.Amount != 0 or source.YTD != 0) {0} + ' + select @sql = replace(@sql, '{0}', 'and source.DepartmentalBudgetID = ' + cast(@budgetid as nvarchar(16))) + exec(@sql) +GO + + +--------------------------------------------- + +-- ob.procFactReportFinancialStatementInsertAll +CREATE PROC [ob].[procFactReportFinancialStatementInsertAll] + @isContinueFromLastRun bit = 0 +WITH RECOMPILE +AS + set nocount on + + if (@isContinueFromLastRun = 0) begin + truncate table [ob].[FactReportFinancialStatement] + exec dbo.procTableReseedIdentity 'ob', 'FactReportFinancialStatement', 1 + + truncate table [ob].[FactReportFinancialStatement_Pivoted] + exec dbo.procTableReseedIdentity 'ob', 'FactReportFinancialStatement_Pivoted', 1 + end + + declare @memberGUID uniqueidentifier + declare crsBudgets cursor fast_forward for select b.MemberGUID from ob.viewDimDepartmentalBudget b where not exists(select 1 from ob.FactReportFinancialStatement fs where fs.DepartmentalBudgetID = b.DepartmentalBudgetID) + open crsBudgets + fetch next from crsBudgets into @memberGUID + while (@@FETCH_STATUS = 0) begin + exec [ob].[procFactReportFinancialStatementInsert] @memberGUID + fetch next from crsBudgets into @memberGUID + end + close crsBudgets + deallocate crsBudgets +GO + + +--------------------------------------------- + +-- ob.procFinalizeBudget_SampleToInt_ChargeCode +create proc [ob].[procFinalizeBudget_SampleToInt_ChargeCode] + @IsDebugOnly bit = 0 +/* ****************************************************************************************************** +** Author: Corey Becker +** Create Date: 2016-03-22 +** Description: Copies Charge Code Budget Data into 'int' tables +** Last Modified: 2016-03-22 +** GM Release: 2016.3 +********************************************************************************************************* +** Change History +********************************************************************************************************* +** CID Date Author WI Description +** +*********************************************************************************************************/ +as +begin +-------------------------------------------------------------------------------------------------- +-- Logging +-------------------------------------------------------------------------------------------------- + declare @logdesc nvarchar(100) + select @logdesc = + case @IsDebugOnly + when 1 then 'Debug only - Sample Charge Code budget data into int tables' + else 'Sample Charge Code budget data into int tables' + end + + declare @higuid uniqueidentifier + exec procLogScript @logdesc, @higuid output + + print 'Beginning sample, historyguid: '+cast(@higuid as varchar(36)) + +-------------------------------------------------------------------------------------------------- +-- Variable declarations +-------------------------------------------------------------------------------------------------- + declare @year int + select @year = dbs.Setting+1 + from [dbo].[DBSetting] dbs + where dbs.Name = 'OB_Current_Year' + + declare @sql nvarchar(max) = '' + +-------------------------------------------------------------------------------------------------- +-- Charge Code data +-------------------------------------------------------------------------------------------------- + SET @sql = ' +-- Charge Code data +-------------------------------------------------------------------------------------------------- +-- Delete Existing +DELETE +FROM [int].[FactCDM] +WHERE 1=1 + and FiscalYearID = ' ++ cast(@year as nvarchar(4)) ++ ' and TimeClassID = 2 + +-- Insert Budget data +INSERT INTO [int].[FactCDM] ( + DepartmentID, + DepartmentCode, + ChargeCodeID, + ChargeCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + FiscalMonthID, + FiscalMonthCode, + PatientClassID, + PatientClassCode, + ServiceLineID, + ServiceLine, + AgeCohortID, + AgeCohort, + MedicalSurgicalID, + MedSurg, + UnitTypeID, + UnitType, + Value, + IsDeleted, + HistoryItemGUID) +SELECT + DEP.DepartmentID, + DEP.DepartmentCode, + CC.ChargeCodeID, + CC.ChargeCode, + BudgetedData.FiscalYearID, + BudgetedData.FiscalYearID AS FiscalYearCode, + TC.TimeClassID, + TC.TimeClassCode, + FM.FiscalMonthID, + FM.FiscalMonthCode, + PAT.PatientClassID, + PAT.Code as [PatientClassCode], + ''0'' as ServiceLineID, + '''' as ServiceLine, + ''0'' as AgeCohortID, + '''' as AgeCohort, + ''0'' as MedicalSurgicalID, + '''' as MedSurg, + UT.UnitTypeID, + UT.Name as [UnitType], + Value, + ''0'' as IsDeleted, + ''' + + cast(@higuid as varchar(36)) + + ''' as HistoryItemGUID +FROM ( + SELECT * + FROM ( + SELECT * + FROM [clientob].[FactCDM] fac + ) EXPORTDATA + UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT +) BudgetedData +INNER JOIN [fw].[DimChargeCode] CC on CC.ChargeCodeID = BudgetedData.ChargeCodeID +INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = BudgetedData.PatientClassID +INNER JOIN [ob].[DimDepartmentalBudget] Budget on Budget.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID +INNER JOIN [fw].[DimDepartment] dep on dep.DepartmentID = Budget.DepartmentID +INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID +INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode +INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = BudgetedData.UnitTypeID +WHERE 1=1 + and BudgetedData.Value <> 0 + and BudgetedData.TimeClassID = 2 + and BudgetedData.IsDeleted = 0 + and BudgetedData.FiscalYearID = ' + cast(@year as nvarchar(4)) + + if @IsDebugOnly=1 + begin + print(@sql) + end + else + begin + exec(@sql) + end + +end --END OF PROCEDURE +GO + + +--------------------------------------------- + +-- ob.procFinalizeBudget_SampleToInt_GL +CREATE proc [ob].[procFinalizeBudget_SampleToInt_GL] + @IsDebugOnly bit = 0 +/* ****************************************************************************************************** +** Author: Corey Becker +** Create Date: 2016-03-22 +** Description: Copies GL Budget Data into 'int' tables +** Last Modified: 2016-12-12 +** GM Release: 2016.3 +********************************************************************************************************* +** Change History +********************************************************************************************************* +** CID Date Author WI Description +** 1 2016-12-12 srk B-13006 Added section to transfer GL Budget Hours +*********************************************************************************************************/ +as +begin +-------------------------------------------------------------------------------------------------- +-- Logging +-------------------------------------------------------------------------------------------------- + declare @logdesc nvarchar(100) + select @logdesc = + case @IsDebugOnly + when 1 then 'Debug only - Sample GL budget data into int tables' + else 'Sample GL budget data into int tables' + end + + declare @higuid uniqueidentifier + exec procLogScript @logdesc, @higuid output + + print 'Beginning sample, historyguid: '+cast(@higuid as varchar(36)) + +-------------------------------------------------------------------------------------------------- +-- Variable declarations +-------------------------------------------------------------------------------------------------- + declare @year int + select @year = dbs.Setting+1 + from [dbo].[DBSetting] dbs + where dbs.Name = 'OB_Current_Year' + + declare @sql nvarchar(max) = '' + +-------------------------------------------------------------------------------------------------- +-- GL Dollars +-------------------------------------------------------------------------------------------------- + SET @sql = ' +-- GL Dollars +-------------------------------------------------------------------------------------------------- +-- Delete Existing +DELETE +FROM [int].[FactGL] +WHERE 1=1 + and FiscalYearID = ' ++ cast(@year as nvarchar(4)) ++ ' and TimeClassID = 2 + +-- Insert Budget data +INSERT INTO [int].[FactGL] +( + [DepartmentID], + [DepartmentCode], + [AccountID], + [AccountCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + [FiscalMonthID], + [FiscalMonthCode], + [Value], + [IsDeleted], + [HistoryItemGUID] +) +SELECT + dep.DepartmentID, + dep.DepartmentCode, + acc.AccountID, + acc.AccountCode, + BudgetedData.FiscalYearID, + BudgetedData.FiscalYearID as FiscalYearCode, + tc.TimeClassID, + tc.TimeClassCode, + fm.FiscalMonthID, + fm.FiscalMonthCode, + acc.inversion*Value as Value, + ''0'' as IsDeleted, + ''' + + cast(@higuid as varchar(36)) + + ''' as HistoryItemGUID +FROM ( + SELECT * + FROM ( + SELECT * + FROM [clientob].[FactAccount] fac + WHERE fac.UnitTypeID = 34 --Dollars only + ) EXPORTDATA + UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT +) BudgetedData + INNER JOIN fw.DimAccount acc on acc.AccountID = BudgetedData.AccountID + INNER JOIN ob.DimDepartmentalBudget Budget on Budget.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID + INNER JOIN fw.DimDepartment dep on dep.DepartmentID = Budget.DepartmentID + INNER JOIN fw.DimTimeClass tc on tc.TimeClassID = BudgetedData.TimeClassID + INNER JOIN fw.DimFiscalMonth fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode +WHERE 1=1 + and BudgetedData.Value <> 0 + and BudgetedData.TimeClassID = 2 + and BudgetedData.IsDeleted = 0 + and BudgetedData.FiscalYearID = ' + cast(@year as nvarchar(4)) + + if @IsDebugOnly=1 + begin + print(@sql) + end + else + begin + exec(@sql) + end + +-------------------------------------------------------------------------------------------------- +-- Department Stats - Volumes +-------------------------------------------------------------------------------------------------- + SET @sql = ' +-- Department Stats +-------------------------------------------------------------------------------------------------- +-- Delete Existing +DELETE FS +FROM [int].[FactStatistic] FS +INNER JOIN [fw].[DimAccount] DA ON FS.[AccountID] = DA.[AccountID] +WHERE 1=1 + and FS.[FiscalYearID] = ' ++ cast(@year as nvarchar(4)) ++ ' and FS.[TimeClassID] = 2 + and DA.[OBStatUnitTypeID] = 140 -- Volumes Only +-- Insert Budget data +INSERT INTO [int].[FactStatistic] +( + [DepartmentID], + [DepartmentCode], + [AccountID], + [AccountCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + [FiscalMonthID], + [FiscalMonthCode], + [Value], + [IsDeleted], + [HistoryItemGUID] +) +SELECT + dep.DepartmentID, + dep.DepartmentCode, + acc.AccountID, + acc.AccountCode, + BudgetedData.FiscalYearID, + BudgetedData.FiscalYearID as FiscalYearCode, + tc.TimeClassID, + tc.TimeClassCode, + fm.FiscalMonthID, + fm.FiscalMonthCode, + acc.inversion*Value as Value, + ''0'' as IsDeleted, + ''' + + cast(@higuid as varchar(36)) + + ''' as HistoryItemGUID +FROM ( + SELECT * + FROM ( + SELECT * + FROM [clientob].[FactAccount] fac + WHERE fac.UnitTypeID = 140 --Volumes Only + ) EXPORTDATA + UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT +) BudgetedData + INNER JOIN fw.DimAccount acc on acc.AccountID = BudgetedData.AccountID + INNER JOIN ob.DimDepartmentalBudget Budget on Budget.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID + INNER JOIN fw.DimDepartment dep on dep.DepartmentID = Budget.DepartmentID + INNER JOIN fw.DimTimeClass tc on tc.TimeClassID = BudgetedData.TimeClassID + INNER JOIN fw.DimFiscalMonth fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode +WHERE 1=1 + and BudgetedData.Value <> 0 + and BudgetedData.TimeClassID = 2 + and BudgetedData.IsDeleted = 0 + and BudgetedData.FiscalYearID = ' + cast(@year as nvarchar(4)) + + if @IsDebugOnly=1 + begin + print(@sql) + end + else + begin + exec(@sql) + end + +-------------------------------------------------------------------------------------------------- +-- Department Stats - GL Hours +-------------------------------------------------------------------------------------------------- + SET @sql = ' +-- Department Stats +-------------------------------------------------------------------------------------------------- +-- Delete Existing +DELETE FS +FROM [int].[FactStatistic] FS +INNER JOIN [fw].[DimAccount] DA ON FS.[AccountID] = DA.[AccountID] +WHERE 1=1 + and FS.[FiscalYearID] = ' ++ cast(@year as nvarchar(4)) ++ ' and FS.[TimeClassID] = 2 + and DA.[OBStatUnitTypeID] = 51 -- Hours Only + +-- Insert Budget data +INSERT INTO [int].[FactStatistic] +( + [DepartmentID], + [DepartmentCode], + [AccountID], + [AccountCode], + [FiscalYearID], + [FiscalYearCode], + [TimeClassID], + [TimeClassCode], + [FiscalMonthID], + [FiscalMonthCode], + [Value], + [IsDeleted], + [HistoryItemGUID] +) +SELECT + dep.DepartmentID, + dep.DepartmentCode, + acc.AccountID, + acc.AccountCode, + BudgetedData.FiscalYearID, + BudgetedData.FiscalYearID as FiscalYearCode, + tc.TimeClassID, + tc.TimeClassCode, + fm.FiscalMonthID, + fm.FiscalMonthCode, + acc.inversion*Value as Value, + ''0'' as IsDeleted, + ''' + + cast(@higuid as varchar(36)) + + ''' as HistoryItemGUID +FROM ( + SELECT * + FROM ( + SELECT * + FROM [clientob].[FactAccount] fac + WHERE fac.UnitTypeID = 51 --Hours only + ) EXPORTDATA + UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT +) BudgetedData + INNER JOIN fw.DimAccount acc on acc.AccountID = BudgetedData.AccountID + INNER JOIN ob.DimDepartmentalBudget Budget on Budget.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID + INNER JOIN fw.DimDepartment dep on dep.DepartmentID = Budget.DepartmentID + INNER JOIN fw.DimTimeClass tc on tc.TimeClassID = BudgetedData.TimeClassID + INNER JOIN fw.DimFiscalMonth fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode +WHERE 1=1 + and BudgetedData.Value <> 0 + and BudgetedData.TimeClassID = 2 + and BudgetedData.IsDeleted = 0 + and BudgetedData.FiscalYearID = ' + cast(@year as nvarchar(4)) + + if @IsDebugOnly=1 + begin + print(@sql) + end + else + begin + exec(@sql) + end + +-------------------------------------------------------------------------------------------------- +-- Global Stats +-------------------------------------------------------------------------------------------------- + SET @sql = ' +-- Insert Global Stats +-------------------------------------------------------------------------------------------------- +-- Delete Existing +DELETE +FROM [int].[FactGlobalStatistics] +WHERE 1=1 + and FiscalYearID = ' ++ cast(@year as nvarchar(4)) ++ ' and TimeClassID = 2 + +-- Insert Budget data +INSERT INTO [int].[FactGlobalStatistics] +( + EntityID, + EntityCode, + DepartmentID, + DepartmentCode, + AccountID, + AccountCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + FiscalMonthID, + FiscalMonthCode, + Value, + IsDeleted, + HistoryItemGUID +) +SELECT + ent.EntityID, + ent.Code as [EntityCode], + ''0'' as DepartmentID, + ''0'' as DepartmentCode, + acc.AccountID, + acc.AccountCode, + BudgetedData.FiscalYearID, + BudgetedData.FiscalYearID as FiscalYearCode, + tc.TimeClassID, + tc.TimeClassCode, + fm.FiscalMonthID, + fm.FiscalMonthCode, + acc.inversion*Value as Value, + ''0'' as IsDeleted, + ''' + + cast(@higuid as varchar(36)) + + ''' as HistoryItemGUID +FROM ( + SELECT * + FROM ( + SELECT * + FROM [clientob].[FactGlobalStatistics] fac + ) EXPORTDATA + UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT +) BudgetedData + INNER JOIN [ob].[DimOBGlobalStatistics] gs on gs.OBGlobalStatisticID = BudgetedData.OBGlobalStatisticID + INNER JOIN fw.DimAccount acc on acc.AccountID = GS.AccountID + INNER JOIN fw.DimDepartment dep on dep.DepartmentID = GS.DepartmentID + INNER JOIN ob.DimOBGlobalStatisticsPlan GSP on GSP.OBGlobalStatisticsPlanID = BudgetedData.OBGlobalStatisticsPlanID + INNER JOIN fw.DimEntity ent on GSP.EntityID = ent.EntityID + INNER JOIN fw.DimTimeClass tc on tc.TimeClassID = BudgetedData.TimeClassID + INNER JOIN fw.DimFiscalMonth fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode +WHERE 1=1 + and gs.DepartmentID = 0 + and BudgetedData.Value <> 0 + and BudgetedData.TimeClassID = 2 + and BudgetedData.IsDeleted = 0 + and BudgetedData.FiscalYearID = ' + cast(@year as nvarchar(4)) + + if @IsDebugOnly=1 + begin + print(@sql) + end + else + begin + exec(@sql) + end + +end --END OF PROCEDURE +GO + + +--------------------------------------------- + +-- ob.procFinalizeBudget_SampleToInt_Payroll +CREATE proc [ob].[procFinalizeBudget_SampleToInt_Payroll] + @IsDebugOnly bit = 0 +/* ****************************************************************************************************** +** Author: Corey Becker +** Create Date: 2016-03-22 +** Description: Copies Staffing Budget Data into 'int' tables +** Last Modified: 2016-03-22 +** GM Release: 2016.3 +********************************************************************************************************* +** Change History +********************************************************************************************************* +** CID Date Author WI Description +** 1 2/9/2018 sdominsk D-06820 Change filter in where clause for ut.UnitTypeID (added ''147'',''52''). +*********************************************************************************************************/ +as +begin +-------------------------------------------------------------------------------------------------- +-- Logging +-------------------------------------------------------------------------------------------------- + declare @logdesc nvarchar(100) + select @logdesc = + case @IsDebugOnly + when 1 then 'Debug only - Sample Payroll budget data into int tables' + else 'Sample Payroll budget data into int tables' + end + + declare @higuid uniqueidentifier + exec procLogScript @logdesc, @higuid output + + print 'Beginning sample, historyguid: '+cast(@higuid as varchar(36)) + +-------------------------------------------------------------------------------------------------- +-- Variable declarations +-------------------------------------------------------------------------------------------------- + declare @year int + select @year = dbs.Setting+1 + from [dbo].[DBSetting] dbs + where dbs.Name = 'OB_Current_Year' + + declare @sql nvarchar(max) = '' + +-------------------------------------------------------------------------------------------------- +-- Staffing data +-------------------------------------------------------------------------------------------------- + SET @sql = ' +-- Staffing data +-------------------------------------------------------------------------------------------------- +-- Delete Existing +DELETE +FROM [int].[FactStaffing] +WHERE 1=1 + and FiscalYearID = ' ++ cast(@year as nvarchar(4)) ++ ' and TimeClassID = 2 + +-- Insert Budget data +INSERT INTO [int].[FactStaffing] ( + DepartmentID + , DepartmentCode + , JobCodeID + , JobCode + , PayCodeID + , PayCode + , FiscalYearID + , FiscalYearCode + , TimeClassID + , TimeClassCode + , UnitTypeID + , UnitType + , FiscalMonthID + , FiscalMonthCode + , Value + , IsDeleted + , HistoryItemGUID + , EmployeeID + , EmployeeCode) +SELECT + dep.DepartmentID + , dep.DepartmentCode + , jc.JobCodeID + , jc.JobCode + , pc.PayCodeID + , pc.PayCode + , BudgetedData.FiscalYearID + , BudgetedData.FiscalYearID as FiscalYearCode + , tc.TimeClassID + , tc.TimeClassCode + , case + when ut.UnitTypeID = 34 + then 34 + else 51 + end as UnitTypeID + , case + when ut.Name =''Dollars'' + then ''Dollars'' + else ''Hours'' + end as UnitType + , fm.FiscalMonthID + , fm.FiscalMonthCode + , Value as Value + , ''0'' as IsDeleted + , ''' + + cast(@higuid as varchar(36)) + + ''' as HistoryItemGUID + , ''0'' as EmployeeID + , ''0'' as EmployeeCode +FROM ( + SELECT * + FROM ( + SELECT * + FROM [clientob].[FactStaffingPC] fac + ) EXPORTDATA + UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT +) BudgetedData + INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = BudgetedData.JobCodeID + INNER JOIN [ob].[DimDepartmentalBudget] budget on budget.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID + INNER JOIN [fw].[DimDepartment] dep on dep.DepartmentID = budget.DepartmentID + INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode + INNER JOIN [fw].[DimPayCodeGroup] PCG ON PCG.PayCodeGroupID = BudgetedData.PayCodeGroupID + INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = PCG.DefaultPayCodeID + INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = BudgetedData.UnitTypeID +WHERE 1=1 + and ut.UnitTypeID IN (''34'',''146'',''148'',''147'',''52'') + and BudgetedData.Value <> 0 + and PCG.PayCodeGroupID<>0 + and BudgetedData.TimeClassID = 2 + and BudgetedData.IsDeleted = 0 + and BudgetedData.FiscalYearID = ' + cast(@year as nvarchar(4)) + + if @IsDebugOnly=1 + begin + print(@sql) + end + else + begin + exec(@sql) + end + + +end --END OF PROCEDURE +GO + + +--------------------------------------------- + +-- ob.procFinalizeBudget_SampleToInt_Provider +CREATE proc [ob].[procFinalizeBudget_SampleToInt_Provider] + @IsDebugOnly bit = 0 +/* ****************************************************************************************************** +** Author: Corey Becker +** Create Date: 2016-03-22 +** Description: Copies Provider Budget Data into 'int' tables +** Last Modified: 2016-03-22 +** GM Release: 2016.3 +********************************************************************************************************* +** Change History +********************************************************************************************************* +** CID Date Author WI Description +** 1 2017-11-22 srk D-04334 Stamp off Provider Hours instead of FTEs +** 2 2019-01-10 ljc B-15790 reverting CID 1. Provider output Hours now mapped +*********************************************************************************************************/ +as +begin + +-------------------------------------------------------------------------------------------------- +-- Logging +-------------------------------------------------------------------------------------------------- + declare @logdesc nvarchar(100) + select @logdesc = + case @IsDebugOnly + when 1 then 'Debug only - Sample Provider budget data into int tables' + else 'Sample Provider budget data into int tables' + end + + declare @higuid uniqueidentifier + exec procLogScript @logdesc, @higuid output + + print 'Beginning sample, historyguid: '+cast(@higuid as varchar(36)) + +-------------------------------------------------------------------------------------------------- +-- Variable declarations +-------------------------------------------------------------------------------------------------- + declare @year int + select @year = dbs.Setting+1 + from [dbo].[DBSetting] dbs + where dbs.Name = 'OB_Current_Year' + + declare @sql nvarchar(max) = '' + +-------------------------------------------------------------------------------------------------- +-- Provider data +-------------------------------------------------------------------------------------------------- + SET @sql = ' +-- Provider data +-------------------------------------------------------------------------------------------------- +-- Delete Existing +DELETE +FROM [int].[FactImportProvider] +WHERE 1=1 + and FiscalYearID = ' ++ cast(@year as nvarchar(4)) ++ ' and TimeClassID = 2 + +-- Insert Budget data +INSERT INTO [int].[FactImportProvider] ( + DepartmentID + , DepartmentCode + , ProviderID + , ProviderCode + , FiscalYearID + , FiscalYearCode + , TimeClassID + , TimeClassCode + , FiscalMonthID + , FiscalMonthCode + , OBForecastDetailID + , AccountRollup + , Value + , IsDeleted + , HistoryItemGUID + ) +SELECT + D.DepartmentID + , D.DepartmentCode + , PRO.ProviderID + , PRO.ProviderCode + , BudgetedData.FiscalYearID + , BudgetedData.FiscalYearID as [FiscalYearCode] + , TC.TimeClassID + , TC.TimeClassCode + , FM.FiscalMonthID + , FM.FiscalMonthCode + , FD.OBForecastDetailID + , FD.Name as [AccountRollup] + , Value + ,''0'' as IsDeleted + ,''' + + cast(@higuid as varchar(36)) + + ''' as HistoryItemGUID +FROM ( + SELECT * + FROM ( + SELECT * + FROM [clientob].[FactProvider] fac + ) EXPORTDATA + UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT +) BudgetedData +INNER JOIN [fw].[DimProvider] PRO ON PRO.ProviderID = BudgetedData.ProviderID +INNER JOIN [ob].[DimDepartmentalBudget] P ON P.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID +INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = P.DepartmentID +INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID +INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode +INNER JOIN [ob].[DimOBForecastDetail] FD ON FD.OBForecastDetailID = BudgetedData.OBForecastDetailID +WHERE 1=1 + and BudgetedData.Value <> 0 + and BudgetedData.TimeClassID = 2 + and BudgetedData.IsDeleted = 0 + and BudgetedData.FiscalYearID = ' + cast(@year as nvarchar(4)) + + if @IsDebugOnly=1 + begin + print(@sql) + end + else + begin + exec(@sql) + end + +end --END OF PROCEDURE +GO + + +--------------------------------------------- + +-- ob.procFinalizeBudget_SampleToInt_Reimbursement +CREATE proc [ob].[procFinalizeBudget_SampleToInt_Reimbursement] + @IsDebugOnly bit = 0 +/* ****************************************************************************************************** +** Author: Corey Becker +** Create Date: 2016-03-22 +** Description: Copies Reimbursement Budget Data into 'int' tables +** Last Modified: 2016-03-22 +** GM Release: 2016.3 +********************************************************************************************************* +** Change History +********************************************************************************************************* +** CID Date Author WI Description +** 1 2016-11-21 srk D-04390 Comment out Payor transfer to avoid duplicaton +*********************************************************************************************************/ +as +begin +-------------------------------------------------------------------------------------------------- +-- Logging +-------------------------------------------------------------------------------------------------- + declare @logdesc nvarchar(100) + select @logdesc = + case @IsDebugOnly + when 1 then 'Debug only - Sample Reimbursement budget data into int tables' + else 'Sample Reimbursement budget data into int tables' + end + + declare @higuid uniqueidentifier + exec procLogScript @logdesc, @higuid output + + print 'Beginning sample, historyguid: '+cast(@higuid as varchar(36)) + +-------------------------------------------------------------------------------------------------- +-- Variable declarations +-------------------------------------------------------------------------------------------------- + declare @year int + select @year = dbs.Setting+1 + from [dbo].[DBSetting] dbs + where dbs.Name = 'OB_Current_Year' + + declare @sql nvarchar(max) = '' + +-------------------------------------------------------------------------------------------------- +-- Payor data +-------------------------------------------------------------------------------------------------- + SET @sql = ' +-- Payor data +-------------------------------------------------------------------------------------------------- +-- Delete Existing +DELETE +FROM [int].[FactOBPayor] +WHERE 1=1 + and FiscalYearID = ' ++ cast(@year as nvarchar(4)) ++ ' and TimeClassID = 2 + +---- Insert Budget data +--INSERT INTO [int].[FactOBPayor] ( +-- OBReimbursementPlanID, +-- ReimbursementPlan, +-- PatientClassID, +-- PatientClassCode, +-- PayorID, +-- PayorCode, +-- FiscalYearID, +-- FiscalYearCode, +-- TimeClassID, +-- TimeClassCode, +-- FiscalMonthID, +-- FiscalMonthCode, +-- OBForecastDetailID, +-- OBForecastDetailCode, +-- CareSettingID, +-- CareSettingCode, +-- Value, +-- IsDeleted, +-- HistoryItemGUID) +--SELECT +-- P.OBReimbursementPlanID, +-- P.Name as ReimbursementPlan, +-- PAT.PatientClassID, +-- PAT.Code as PatientClassCode, +-- PAY.PayorID, +-- PAY.PayorCode, +-- BudgetedData.FiscalYearID, +-- BudgetedData.FiscalYearID as FiscalYearCode, +-- TC.TimeClassID, +-- TC.TimeClassCode, +-- fm.FiscalMonthID, +-- fm.FiscalMonthCode, +-- FD.OBForecastDetailID, +-- FD.Code as OBForecastDetail, +-- C.CareSettingID, +-- C.Code as CareSettingCode, +-- Value +-- ,''0'' as IsDeleted +-- ,''' +-- + cast(@higuid as varchar(36)) +-- + ''' as HistoryItemGUID +--FROM ( +-- SELECT * +-- FROM ( +-- SELECT * +-- FROM [clientob].[FactReimbursement] fac +-- ) EXPORTDATA +-- UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT +--) BudgetedData +-- INNER JOIN [fw].[DimPatientReimbursementGroup] PRG on PRG.PatientReimbursementGroupID = BudgetedData.PatientReimbursementGroupID +-- INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = PRG.PatientClassID +-- INNER JOIN [fw].[DimCareSetting] C ON C.CareSettingID = PRG.CareSettingID +-- INNER JOIN [fw].[DimPayor] PAY ON PAY.PayorID = BudgetedData.PayorID +-- INNER JOIN [ob].[DimOBReimbursementPlan] P ON P.OBReimbursementPlanID = BudgetedData.OBReimbursementPlanID +-- INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID +-- INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode +-- INNER JOIN [ob].[DimOBForecastDetail] FD ON FD.OBForecastDetailID = BudgetedData.OBForecastDetailID +--WHERE 1=1 +-- and BudgetedData.Value <> 0 +-- and BudgetedData.TimeClassID = 2 +-- and BudgetedData.IsDeleted = 0 +-- and BudgetedData.FiscalYearID = ' + cast(@year as nvarchar(4)) +-- +-- if @IsDebugOnly=1 +-- begin +-- print(@sql) +-- end +-- else +-- begin +-- exec(@sql) +-- end + +-------------------------------------------------------------------------------------------------- +-- Payor group data +-------------------------------------------------------------------------------------------------- + SET @sql = ' +-- Payor group data +-------------------------------------------------------------------------------------------------- +-- Delete Existing +DELETE +FROM [int].[FactOBPayorGroup] +WHERE 1=1 + and FiscalYearID = ' ++ cast(@year as nvarchar(4)) ++ ' and TimeClassID = 2 + +-- Insert Budget data +INSERT INTO [int].[FactOBPayorGroup] ( + OBReimbursementPlanID, + ReimbursementPlan, + PatientClassID, + PatientClassCode, + PayorGroupID, + PayorGroupCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + FiscalMonthID, + FiscalMonthCode, + OBForecastDetailID, + OBForecastDetailCode, + CareSettingID, + CareSettingCode, + Value, + IsDeleted, + HistoryItemGUID) +SELECT + P.OBReimbursementPlanID, + P.Name as ReimbursementPlan, + PAT.PatientClassID, + PAT.Code as PatientClassCode, + PAY.PayorGroupID, + PAY.PayorGroupCode, + BudgetedData.FiscalYearID, + BudgetedData.FiscalYearID as FiscalYearCode, + TC.TimeClassID, + TC.TimeClassCode, + fm.FiscalMonthID, + fm.FiscalMonthCode, + FD.OBForecastDetailID, + FD.Code as OBForecastDetail, + C.CareSettingID, + C.Code as CareSettingCode, + Value + ,''0'' as IsDeleted + ,''' + + cast(@higuid as varchar(36)) + + ''' as HistoryItemGUID +FROM ( + SELECT * + FROM ( + SELECT * + FROM [clientob].[FactReimbursement] fac + ) EXPORTDATA + UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT +) BudgetedData + INNER JOIN [fw].[DimPatientReimbursementGroup] PRG on PRG.PatientReimbursementGroupID = BudgetedData.PatientReimbursementGroupID + INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = PRG.PatientClassID + INNER JOIN [fw].[DimCareSetting] C ON C.CareSettingID = PRG.CareSettingID + INNER JOIN [fw].[DimPayorGroup] PAY ON PAY.PayorGroupID = BudgetedData.PayorGroupID + INNER JOIN [ob].[DimOBReimbursementPlan] P ON P.OBReimbursementPlanID = BudgetedData.OBReimbursementPlanID + INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode + INNER JOIN [ob].[DimOBForecastDetail] FD ON FD.OBForecastDetailID = BudgetedData.OBForecastDetailID +WHERE 1=1 + and BudgetedData.Value <> 0 + and BudgetedData.TimeClassID = 2 + and BudgetedData.IsDeleted = 0 + and BudgetedData.FiscalYearID = ' + cast(@year as nvarchar(4)) + + if @IsDebugOnly=1 + begin + print(@sql) + end + else + begin + exec(@sql) + end + +end --END OF PROCEDURE +GO + + +--------------------------------------------- + +-- ob.procFinalizeBudget_SampleToInt_SL +CREATE proc [ob].[procFinalizeBudget_SampleToInt_SL] + @IsDebugOnly bit = 0 +/* ****************************************************************************************************** +** Author: Corey Becker +** Create Date: 2016-03-22 +** Description: Copies Service Line Budget Data into 'int' tables +** Last Modified: 2016-03-22 +** GM Release: 2016.3 +********************************************************************************************************* +** Change History +********************************************************************************************************* +** CID Date Author WI Description +** 1 2016-11-21 srk D-04550 Add DepartmentCode and DepartmentID to the Service Line transfer +*********************************************************************************************************/ +as +begin +-------------------------------------------------------------------------------------------------- +-- Logging +-------------------------------------------------------------------------------------------------- + declare @logdesc nvarchar(100) + select @logdesc = + case @IsDebugOnly + when 1 then 'Debug only - Sample Service Line budget data into int tables' + else 'Sample Service Line budget data into int tables' + end + + declare @higuid uniqueidentifier + exec procLogScript @logdesc, @higuid output + + print 'Beginning sample, historyguid: '+cast(@higuid as varchar(36)) + +-------------------------------------------------------------------------------------------------- +-- Variable declarations +-------------------------------------------------------------------------------------------------- + declare @year int + select @year = dbs.Setting+1 + from [dbo].[DBSetting] dbs + where dbs.Name = 'OB_Current_Year' + + declare @sql nvarchar(max) = '' + +-------------------------------------------------------------------------------------------------- +-- Service Line data +-------------------------------------------------------------------------------------------------- + SET @sql = ' +-- Service Line data +-------------------------------------------------------------------------------------------------- +-- Delete Existing +DELETE +FROM [int].[FactServiceLine] +WHERE 1=1 + and FiscalYearID = ' ++ cast(@year as nvarchar(4)) ++ ' and TimeClassID = 2 + +-- Insert Budget data +INSERT INTO [int].[FactServiceLine] ( + EntityID, + EntityCode, + DepartmentID, + DepartmentCode, + PatientClassID, + PatientClassCode, + ServiceLineID, + ServiceLine, + AgeCohortID, + AgeCohort, + MedicalSurgicalID, + MedSurg, + PayorID, + PayorGroupID, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + FiscalMonthID, + FiscalMonthCode, + OBForecastDetailID, + ForecastDetail, + Value, + IsDeleted, + HistoryItemGUID) +SELECT + E.EntityID, + E.Code as [EntityCode], + DEPT.DepartmentID, + DEPT.DepartmentCode, + PAT.PatientClassID, + PAT.Code as [PatientClassCode], + SL.ServiceLineID, + SL.Code as [ServiceLineCode], + AGE.AgeCohortID, + AGE.Code as [AgeCohort], + MED.MedicalSurgicalID, + MED.Code as [MedSurg], + PAY.PayorID, + PAYG.PayorGroupID, + BudgetedData.FiscalYearID, + BudgetedData.FiscalYearID AS FiscalYearCode, + TC.TimeClassID, + TC.TimeClassCode, + FM.FiscalMonthID, + FM.FiscalMonthCode, + FD.OBForecastDetailID, + FD.Code as [ForecastDetail], + Value + ,''0'' as IsDeleted + ,''' + + cast(@higuid as varchar(36)) + + ''' as HistoryItemGUID +FROM ( + SELECT * + FROM ( + SELECT * + FROM [clientob].[FactServiceLine] fac + ) EXPORTDATA + UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT +) BudgetedData +INNER JOIN [fw].[DimModelingServiceLine] MSL on MSL.ModelingServiceLineID = BudgetedData.ModelingServiceLineID +INNER JOIN [fw].[DimServiceLine] SL ON MSL.ServiceLineID = SL.ServiceLineID +INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = MSL.PatientClassID +INNER JOIN [fw].[DimAgeCohort] AGE ON AGE.AgeCohortID = MSL.AgeCohortID +INNER JOIN [fw].[DimMedicalSurgical] MED ON MED.MedicalSurgicalID = MSL.MedicalSurgicalID +INNER JOIN [ob].[DimOBServiceLinePlan] P ON P.OBServiceLinePlanID = BudgetedData.OBServiceLinePlanID +INNER JOIN [fw].[DimEntity] E on E.EntityID = P.EntityID + CROSS APPLY + ( + SELECT TOP 1 DD.DepartmentCode, DD.DepartmentID + from [fw].[DimDepartment] DD + where DD.EntityID = E.EntityID + ) DEPT +INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID +INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode +INNER JOIN [ob].[DimOBForecastDetail] FD ON FD.OBForecastDetailID = BudgetedData.OBForecastDetailID +INNER JOIN [fw].[DimPayor] PAY ON PAY.PayorID=0 +INNER JOIN [fw].[DimPayorGroup] PAYG ON PAYG.PayorGroupID=0 +WHERE 1=1 + and BudgetedData.Value <> 0 + and BudgetedData.TimeClassID = 2 + and BudgetedData.IsDeleted = 0 + and BudgetedData.FiscalYearID = ' + cast(@year as nvarchar(4)) + + if @IsDebugOnly=1 + begin + print(@sql) + end + else + begin + exec(@sql) + end + +end --END OF PROCEDURE +GO + + +--------------------------------------------- + +-- ob.procFinancialReportingSyncBalFromSP +CREATE proc [ob].[procFinancialReportingSyncBalFromSP] +AS + --apply renames + update ob set ob.LineName = sp.LineName, ob.Name = sp.Name, ob.DisplayFormat = sp.DisplayFormat, ob.SortOrder = sp.SortOrder, ob.IsExpense = sp.ConsolidatedIsInverted + from ob.DimFinancialReporting ob + inner join sp.DimFinancialReporting sp on sp.FinancialReportingID = ob.ConsolidatedFinancialReportingID + where ob.Statement = 'Bal' + + --add missing + declare @startID int + select @startID = MAX(FinancialReportingID) from ob.DimFinancialReporting + INSERT INTO ob.DimFinancialReporting (Statement, Section, LineName, IsMappable, ConsolidatedFinancialReportingID, ConsolidatedIsInverted, Name, StatementMappabilityFilterParameter, ConsolidatedFinancialReporting, ConsolidatedFinancialReportingSortOrder, IsRequired, IsVolume, IsFTERollup, IsEditable, DisplayFormat, SortOrder, FinancialReportingID, IsExpense) + SELECT spf.Statement, spf.Section, spf.LineName, spf.IsMappable, spf.FinancialReportingID, spf.ConsolidatedIsInverted, spf.Name, spf.StatementMappabilityFilterParameter, spf.ConsolidatedFinancialReporting, spf.ConsolidatedFinancialReportingSortOrder, spf.IsRequired, spf.IsVolume, spf.IsFTERollup, spf.IsEditable, spf.DisplayFormat, spf.SortOrder, @startID + spf.FinancialReportingID, spf.ConsolidatedIsInverted + FROM sp.DimFinancialReporting spf + WHERE spf.Statement = 'Bal' + AND not exists(select 1 from ob.DimFinancialReporting ex where ex.ConsolidatedFinancialReportingID = spf.FinancialReportingID) + + --reassign accounts tied to invalid + update a set a.OBDollarsFinancialReportingID = 0 + FROM ob.DimFinancialReporting obf + inner join fw.DimAccount a on a.OBDollarsFinancialReportingID = obf.FinancialReportingID + WHERE obf.Statement = 'Bal' + AND not exists(select 1 from sp.DimFinancialReporting ex where ex.FinancialReportingID = obf.ConsolidatedFinancialReportingID); + + update a set a.OBUnitsFinancialReportingID = 0 + FROM ob.DimFinancialReporting obf + inner join fw.DimAccount a on a.OBUnitsFinancialReportingID = obf.FinancialReportingID + WHERE obf.Statement = 'Bal' + AND not exists(select 1 from sp.DimFinancialReporting ex where ex.FinancialReportingID = obf.ConsolidatedFinancialReportingID); + + --delete invalid + DELETE obf + FROM ob.DimFinancialReporting obf + WHERE obf.Statement = 'Bal' + AND not exists(select 1 from sp.DimFinancialReporting ex where ex.FinancialReportingID = obf.ConsolidatedFinancialReportingID) +GO + + +--------------------------------------------- + +-- ob.procImplDepartmentBudgetClearAssumptionsAndOutputs +/************************************************************ +** Author: akowalski +** Create Date: 2014-08-27 +** Description: Deletes all assumptions and output data for the department budget template - NEVER RUN ON LIVE DATABASES +** Last Modified: 2014-08-27 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 11-24-2014 BL B-03364 Add Clear Non-Reporting to Proc +** +*************************************************************/ +CREATE proc ob.procImplDepartmentBudgetClearAssumptionsAndOutputs + @isExecuting bit = 0 +as +if (@isExecuting=1) +begin +declare @dbname nvarchar(1000) = (DB_Name()) +/************** Remove var data *******************/ + +--Remove data from Fact Account Var +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactAccountVar', 'clientob' +delete fa +from [clientob].[FactAccountvar] fa +inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fa.DepartmentalBudgetID +inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID + + +--Remove data from Fact Account Rollup Var +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactAccountRollupVar', 'clientob' +delete fa +from [clientob].[FactAccountRollupvar] fa +inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fa.DepartmentalBudgetID +inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID + + +--Remove data from Fact Staffing PC Var +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactStaffingPCVar', 'clientob' +delete fs +from [clientob].[FactStaffingPCVar] fs +inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fs.DepartmentalBudgetID +inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID + + +--Remove data from Fact CDM Var +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactCDMVar', 'clientob' +delete fa +from [clientob].[FactCDMvar] fa +inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fa.DepartmentalBudgetID +inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID + +--Remove data from Fact Provider Var +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactProviderVar', 'clientob' +delete fa +from [clientob].[FactProvidervar] fa +inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fa.DepartmentalBudgetID +inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID + + +/************** Remove output data *******************/ + +--Remove output data from Fact Account +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactAccount', 'clientob' +delete fa +from [clientob].[FactAccount] fa +inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fa.DepartmentalBudgetID +inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID +where DataTypeID=3 + +--Remove output data from Fact Account Non Reporting +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactAccountNonReporting', 'clientob' +delete fa +from [clientob].[FactAccountNonReporting] fa +inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fa.DepartmentalBudgetID +inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID +where DataTypeID=3 + +--Remove output data from Fact Staffing PC +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactStaffingPC', 'clientob' +delete fs +from [clientob].[FactStaffingPC] fs +inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fs.DepartmentalBudgetID +inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID +where DataTypeID=3 + +--Remove output data from Fact CDM +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactCDM', 'clientob' +delete fa +from [clientob].[FactCDM] fa +inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fa.DepartmentalBudgetID +inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID +where DataTypeID=3 + +--Remove output data from Fact Provider +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactProvider', 'clientob' +delete fa +from [clientob].[FactProvider] fa +inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fa.DepartmentalBudgetID +inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID +where DataTypeID=3 + +--Remove output data from Fact Reporting Monthly +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactReportingMonthly', 'clientob' +delete fa +from [clientob].[FactReportingMonthly] fa +inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=fa.DepartmentalBudgetID +inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID +inner join [ob].[DimFinancialReporting] fr on fr.FinancialReportingID=fa.FinancialReportingID +where fr.Statement<>'Standards' + +/************** Repopulate data from entity models *******************/ +exec [clientob].[procSampleCDMBudgetYear] +exec [clientob].[procSampleCDMCurrentYear] +exec [clientob].[procFactGlobalStatisticMappingSample] +exec [clientob].[procFactReimbursementMappingSample] + +end + +RETURN +GO + + +--------------------------------------------- + +-- ob.procImplFixInvalidDropDownSelections +/************************************************************ +** Author: akowalski +** Create Date: 2014-09-23 +** Description: Fixes any text boxes that saved a value of blank that will cause #n/a errors in the model +** Last Modified: 2014-09-23 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + +CREATE proc ob.procImplFixInvalidDropDownSelections as + +--get list of affected plans +select distinct db.MemberGUID as PlanGUID +into #Plans +from [ob].[viewExceptionsDepartmentBudgetInvalidDropdownSelection] e +inner join [ob].[DimDepartmentalBudget] db on db.DepartmentalBudgetID=e.DepartmentalBudgetID + + +declare @dbname nvarchar(1000) = (DB_Name()) + +--Accounts +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactAccountVar', 'clientob' + +update fct +set TextValue_Formula='d' +from clientob.factaccountvar fct with (readuncommitted) +inner join ob.DimDepartmentalBudget DB with (readuncommitted) on fct.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join fw.DimAccount DIM with (readuncommitted) on fct.AccountID = DIM.AccountID +where fct.UnitTypeID=141 +and TextValue_Formula='x' +and TextValue='' + + +-- Job Codes +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactStaffingPCVar', 'clientob' +update fct +set TextValue_Formula='d' +from clientob.FactStaffingPCVar fct with (readuncommitted) +inner join ob.DimDepartmentalBudget DB with (readuncommitted) on fct.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join fw.DimJobCode DIM with (readuncommitted) on fct.JobCodeID = DIM.JobCodeID +where fct.UnitTypeID=141 +and TextValue_Formula='x' +and TextValue='' +and EmployeeID=0 + + + +-- Providers +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactProviderVar', 'clientob' +update fct +set TextValue_Formula='d' +from clientob.FactProviderVar fct with (readuncommitted) +inner join ob.DimDepartmentalBudget DB with (readuncommitted) on fct.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join fw.DimProvider DIM with (readuncommitted) on fct.ProviderID = DIM.ProviderID +where fct.UnitTypeID=141 +and TextValue_Formula='x' +and TextValue='' + + +-- Employees +update fct +set TextValue_Formula='d' +from clientob.FactStaffingPCVar fct with (readuncommitted) +inner join ob.DimDepartmentalBudget DB with (readuncommitted) on fct.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join fw.DimEmployee DIM with (readuncommitted) on fct.EmployeeID = DIM.EmployeeID +where fct.UnitTypeID=141 +and TextValue_Formula='x' +and TextValue='' +and DIM.EmployeeID<>0 + + +-- Global Methods +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactAccountRollupVar', 'clientob' +update fct +set TextValue_Formula='d' +from clientob.FactAccountRollupVar fct with (readuncommitted) +inner join ob.DimDepartmentalBudget DB with (readuncommitted) on fct.DepartmentalBudgetID=db.DepartmentalBudgetID +inner join ob.DimFinancialReporting DIM with (readuncommitted) on fct.FinancialReportingID=DIM.FinancialReportingID +where fct.UnitTypeID=141 +and TextValue_Formula='x' +and TextValue='' + +-- invalidatae workbook caches for affected plans +DECLARE guidlist CURSOR FOR + select planguid from #Plans + +open guidlist + +declare @sqli varchar(max) + DECLARE @planguid nvarchar(256) +FETCH NEXT FROM guidlist + INTO @planguid +WHILE (@@FETCH_STATUS = 0) + BEGIN + SET @sqli = 'exec [dbo].[procInvalidateModelWorkbookCache] @entityguid = ''' + @planguid + ''', @istemplate = 0,@source=''ob.procImplFixInvalidDropDownSelections''' + exec(@sqli) + FETCH NEXT FROM guidlist INTO @planguid + END +CLOSE guidlist +DEALLOCATE guidlist + +RETURN +GO + + +--------------------------------------------- + +-- ob.procImplGlobalStatsClearAssumptionsAndOutputs +/************************************************************ +** Author: akowalski +** Create Date: 2014-08-27 +** Description: Deletes all assumptions and output data for the global stats template - NEVER RUN ON LIVE DATABASES +** Last Modified: 2014-08-27 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ +create proc ob.procImplGlobalStatsClearAssumptionsAndOutputs + @isExecuting bit = 0 +as +if (@isExecuting=1) +begin +declare @dbname nvarchar(1000) = (DB_Name()) +/************** Remove var data *******************/ + +--Remove data from Fact GlobalStatistics Var +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactGlobalStatisticsVar', 'clientob' +delete fa +from [clientob].[FactGlobalStatisticsVar] fa +inner join [ob].[DimOBGlobalStatisticsPlan] db on db.OBGlobalStatisticsPlanID=fa.OBGlobalStatisticsPlanID + +/************** Remove output data *******************/ + +--Remove output data from Fact Account +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactGlobalStatistics', 'clientob' +delete fa +from [clientob].[FactGlobalStatistics] fa +inner join [ob].[DimOBGlobalStatisticsPlan] db on db.OBGlobalStatisticsPlanID=fa.OBGlobalStatisticsPlanID +where DataTypeID=3 + +end + +RETURN +GO + + +--------------------------------------------- + +-- ob.procImplReimbursementClearAssumptionsAndOutputs +/************************************************************ +** Author: akowalski +** Create Date: 2014-08-27 +** Description: Deletes all assumptions and output data for the reimbursement template - NEVER RUN ON LIVE DATABASES +** Last Modified: 2014-08-27 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2014-11-24 bl b-03364 Add Fact ReimbAcct and ReimbAcctNonReporting +** +*************************************************************/ +CREATE proc ob.procImplReimbursementClearAssumptionsAndOutputs + @isExecuting bit = 0 +as +if (@isExecuting=1) +begin +declare @dbname nvarchar(1000) = (DB_Name()) +/************** Remove var data *******************/ + +--Remove data from Fact Reimbursement Account Var +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactReimbursementAccountVar', 'clientob' +delete fa +from [clientob].[FactReimbursementAccountVar] fa +inner join [ob].[DimOBReimbursementPlan] db on db.OBReimbursementPlanID=fa.OBReimbursementPlanID + +--Remove data from Fact Reimbursement Var +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactReimbursementVar', 'clientob' +delete fa +from [clientob].[FactReimbursementVar] fa +inner join [ob].[DimOBReimbursementPlan] db on db.OBReimbursementPlanID=fa.OBReimbursementPlanID + +/************** Remove output data *******************/ + +--Remove output data from Fact Reimbursement +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactReimbursement', 'clientob' +delete fa +from [clientob].[FactReimbursement] fa +inner join [ob].[DimOBReimbursementPlan] db on db.OBReimbursementPlanID=fa.OBReimbursementPlanID +where DataTypeID=3 + +--Remove output data from Fact Reimbursement Account +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactReimbursement', 'clientob' +delete fa +from [clientob].[FactReimbursementAccount] fa +inner join [ob].[DimOBReimbursementPlan] db on db.OBReimbursementPlanID=fa.OBReimbursementPlanID +where DataTypeID=3 + +--Remove output data from Fact Reimbursement Account NonReporting +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactReimbursementAccountNonReporting', 'clientob' +delete fa +from [clientob].[FactReimbursementAccountNonReporting] fa +inner join [ob].[DimOBReimbursementPlan] db on db.OBReimbursementPlanID=fa.OBReimbursementPlanID +where DataTypeID=3 + + +end + +RETURN +GO + + +--------------------------------------------- + +-- ob.procImplServiceLineClearAssumptionsAndOutputs +/************************************************************ +** Author: akowalski +** Create Date: 2014-08-27 +** Description: Deletes all assumptions and output data for the service line template - NEVER RUN ON LIVE DATABASES +** Last Modified: 2014-08-27 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ +create proc ob.procImplServiceLineClearAssumptionsAndOutputs + @isExecuting bit = 0 +as +if (@isExecuting=1) +begin +declare @dbname nvarchar(1000) = (DB_Name()) +/************** Remove var data *******************/ + +--Remove data from Fact Service Line Var +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactServiceLineVar', 'clientob' +delete fa +from [clientob].[FactServiceLineVar] fa +inner join [ob].[DimOBServiceLinePlan] db on db.OBServiceLinePlanID=fa.OBServiceLinePlanID + +--Remove data from Fact Service Line Rollup Var +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactServiceLineRollupVar', 'clientob' +delete fa +from [clientob].[FactServiceLineRollupVar] fa +inner join [ob].[DimOBServiceLinePlan] db on db.OBServiceLinePlanID=fa.OBServiceLinePlanID + +/************** Remove output data *******************/ + +--Remove output data from Fact Service Line +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactServiceLine', 'clientob' +delete fa +from [clientob].[FactServiceLine] fa +inner join [ob].[DimOBServiceLinePlan] db on db.OBServiceLinePlanID=fa.OBServiceLinePlanID +where DataTypeID=3 + +end + +RETURN +GO + + +--------------------------------------------- + +-- ob.procLockBudgetModels +CREATE PROCEDURE [ob].[procLockBudgetModels] + @planGUIDs [dbo].[SqlGuidListTableType] READONLY, + @userGroupGUID UNIQUEIDENTIFIER +AS +BEGIN + DECLARE @writeDenyRoleID INT = (select RoleID from UserRole where GlobalID = 'OB - Write Deny') + + INSERT INTO [dbo].[S3RoleAssignment] (LootGroupID, RoleID, IdentityGUID) + SELECT CachedLootID, @writeDenyRoleID, @userGroupGUID + FROM @planGUIDs + INNER JOIN [dbo].[XPlan] + ON PlanGUID = value + WHERE CachedLootID NOT IN ( + SELECT LootGroupID + FROM [dbo].[S3RoleAssignment] ra + WHERE RoleID = @writeDenyRoleID + AND IdentityGUID = @userGroupGUID + ) +END +GO + + +--------------------------------------------- + +-- ob.procMissingJobCodeWageRates_Update +create proc [ob].[procMissingJobCodeWageRates_Update] + @planGUIDList nvarchar(max)='', + @IsDebugOnly bit = 0 +/************************************************************************************************************************ +** Author: cbecker +** Create Date: 2015-12-02 +** Description: Checks for missing wage rates and sets equal to entity or system average +** Last Modified: 2015-12-02 +** GM Release: 2016.1.1 +************************************************************************************************************************** +** Change History +************************************************************************************************************************** +** CID Date Author WI Description +** 00 0000-00-00 xxx x-00000 xx xx +*************************************************************************************************************************/ +as +begin + set nocount on + +-------------------------------------------------------------------------------------------------- +-- Logging +-------------------------------------------------------------------------------------------------- + declare @higuid uniqueidentifier + exec procLogScript 'Update missing job code wage rates' , @higuid output + print 'Beginning update, historyguid: ' + cast(@higuid as varchar(36)) + +-------------------------------------------------------------------------------------------------- +-- Backup +-------------------------------------------------------------------------------------------------- +--declare @dbname nvarchar(1000) = (DB_Name()) +--exec TempTableBackups.dbo.procBackupTable @dbname, 'FactStaffingPCVar', 'clientob' + +-------------------------------------------------------------------------------------------------- +-- Declare variables +-------------------------------------------------------------------------------------------------- + declare @FiscalYearID int + select @FiscalYearID = cast(Setting as int) + from [dbo].[DBSetting] + where DBSettingGUID='9c921c27-f3e4-4616-b3fd-925a75870b62' + + declare @RegPCG int + select @RegPCG = PayCodeGroupID + from [fw].[DimPayCodeGroup] + where 1=1 + and ProductiveClassID = 3 + and SortOrder=(select min(sortorder) from [fw].[DimPayCodeGroup] where ProductiveClassID=3) + +-------------------------------------------------------------------------------------------------- +-- Populate Pay Code Group temp table +-------------------------------------------------------------------------------------------------- + Create Table #PayCodeGroups(PayCodeGroupID int, ProductiveClassID int, PayCodeGroupID2 int) + + insert into #PayCodeGroups(PayCodeGroupID, ProductiveClassID, PayCodeGroupID2) + select + PayCodeGroupID, + ProductiveClassID, + PayCodeGroupID2 = case pcg.ProductiveClassID + when 3 then @RegPCG + else pcg.PayCodeGroupID + end + from [fw].[DimPayCodeGroup] pcg + where ProductiveClassID in (3, 5) + +-------------------------------------------------------------------------------------------------- +-- Populate plans temp table +-------------------------------------------------------------------------------------------------- + Create Table #Plans(DepartmentalBudgetID int) + + if (len(@planGUIDList) = 0) + begin + -- if no plans provided, we will update job codes for all plans + insert into #Plans(DepartmentalBudgetID) + select DepartmentalBudgetID + from ob.DimDepartmentalBudget + end + else + begin + -- if plans are provided, we will only update job codes in specified plans + insert into #Plans(DepartmentalBudgetID) + select + plandim.DepartmentalBudgetID + from dbo.ConvertCSGuidsToTable(@planGUIDList, ',') planguids + inner join ob.DimDepartmentalBudget plandim + on planguids.guid = plandim.MemberGUID + end + +-------------------------------------------------------------------------------------------------- +-- Populate job codes temp table +-------------------------------------------------------------------------------------------------- + create Table #JobCodes(EntityID int, DepartmentalBudgetID int, PayCodeGroupID int, JobCodeID int, Total money) + + insert into #JobCodes (EntityID, DepartmentalBudgetID, PayCodeGroupID, JobCodeID, Total) + select distinct + db.EntityID, + fct.DepartmentalBudgetID, + PayCodeGroupID2, + fct.JobCodeID, + sum(fct.Total) + from [clientob].[FactStaffingPC] fct with (readuncommitted) + inner join #Plans pl + on fct.DepartmentalBudgetID = pl.DepartmentalBudgetID + inner join [ob].[DimDepartmentalBudget] db + on pl.DepartmentalBudgetID = db.DepartmentalBudgetID + inner join #PayCodeGroups pcg + on fct.PayCodeGroupID = pcg.PayCodeGroupID + where 1=1 + and fct.UnitTypeID = 34 + and fct.TimeClassID = 2 + and fct.DataTypeID = 3 + and fct.FiscalYearID = (@FiscalYearID+1) + and (fct.Total = 0 or pcg.ProductiveClassID = 3) + group by + db.EntityID, + fct.DepartmentalBudgetID, + pcg.PayCodeGroupID2, + fct.JobCodeID + having + sum(fct.Total) = 0 + +-------------------------------------------------------------------------------------------------- +-- Populate entity average wage temp table +-------------------------------------------------------------------------------------------------- + create table #EntityAvg (Row int, EntityID int, JobCodeID int, FiscalYearID int, SortOrder int, PayCodeGroupID int, Dollars money, Hours money, Wage money) + + insert into #EntityAvg (Row, EntityID, JobCodeID, FiscalYearID, SortOrder, PayCodeGroupID, Dollars, Hours, Wage) + select + Row = ROW_NUMBER() + OVER + ( + partition by + jc.EntityID, + pc1.JobCodeID, + pc1.PayCodeGroupID, + pc1.FiscalYearID + order by + jc.EntityID, + pc1.JobCodeID, + pc1.PayCodeGroupID, + pc1.FiscalYearID desc, + fm.SortOrder desc + ), + EntityID = jc.EntityID, + JobCodeID = pc1.JobCodeID, + FiscalYearID = pc1.FiscalYearID, + SortOrder = fm.SortOrder, + PayCodeGroupID = case pc1.PayCodeGroupID + when @RegPCG then 0 + else pc1.PayCodeGroupID + end, + Dollars = sum(pc1.Value), + Hours = nullif(sum(pc2.Value),0), + Wage = coalesce(sum(pc1.Value)/nullif(sum(pc2.Value),0),0) + from [ob].[viewFactStaffingPCUnpivoted] pc1 + inner join #JobCodes jc + on pc1.JobCodeID = jc.JobCodeID + --and pc1.DepartmentalBudgetID= jc.DepartmentalBudgetID + and pc1.PayCodeGroupID = jc.PayCodeGroupID + inner join [ob].[viewFactStaffingPCUnpivoted] pc2 + on pc1.DepartmentalBudgetID = pc2.DepartmentalBudgetID + and pc1.PayCodeGroupID = pc2.PayCodeGroupID + and pc1.JobCodeID = pc2.JobCodeID + and pc1.FiscalYearID = pc2.FiscalYearID + and pc1.TimeClassID = pc2.TimeClassID + and pc1.DataTypeID = pc2.DataTypeID + and pc1.FiscalMonthID = pc2.FiscalMonthID + inner join [fw].[DimFiscalMonth] fm + on pc1.FiscalMonthID = fm.FiscalMonthID + where 1=1 + and pc1.UnitTypeID = 34 + and pc1.Value <> 0 + and pc2.Value <> 0 + and pc1.TimeClassID = 12 + and pc1.DataTypeID = 3 + and pc1.FiscalYearID = @FiscalYearID + and pc2.UnitTypeID in (147, 148) + group by + jc.EntityID, + pc1.JobCodeID, + pc1.FiscalYearID, + fm.SortOrder, + pc1.PayCodeGroupID + +-------------------------------------------------------------------------------------------------- +-- Populate system average wage temp table +-------------------------------------------------------------------------------------------------- + create table #SystemAvg (JobCodeID int, PayCodeGroupID int, Wage money) + + insert into #SystemAvg (JobCodeID, PayCodeGroupID, Wage) + select + JobCodeID = ea.JobCodeID, + PayCodeGroupID = ea.PayCodeGroupID, + Wage = coalesce(sum(ea.Dollars)/nullif(sum(ea.Hours),0),0) + from #EntityAvg ea + where 1=1 + and ea.Row = 1 + group by + JobCodeID, + PayCodeGroupID + +-------------------------------------------------------------------------------------------------- +-- Update wage rate annual adjustment +-------------------------------------------------------------------------------------------------- + if (@IsDebugOnly = 1) + begin + select distinct + Amount = coalesce(ea.Wage, sa.Wage, 0), + Amount_Formula = 'x', + HistoryItemGUID = @higuid, + JobCodeID = fct.JobCodeID, + PayCodeGroupID = fct.PayCodeGroupID, + DepartmentalBudgetID= fct.DepartmentalBudgetID + from [clientob].[FactStaffingPCVar] fct + inner join #JobCodes jc + on fct.DepartmentalBudgetID = jc.DepartmentalBudgetID + inner join #SystemAvg sa + on fct.JobCodeID = sa.JobCodeID + and fct.PayCodeGroupID = sa.PayCodeGroupID + left join #EntityAvg ea + on jc.EntityID = ea.EntityID + and fct.JobCodeID = ea.JobCodeID + and fct.PayCodeGroupID = ea.PayCodeGroupID + where 1=1 + and ea.Row = 1 + and fct.TimeClassID = 2 + and fct.UnitTypeID = 159 + and fct.FiscalMonthID = 0 + and fct.AssumptionID = 18 + and fct.FiscalYearID = (@FiscalYearID+1) + + end + else + begin + update fct + set + Amount = coalesce(ea.Wage, sa.Wage, 0), + Amount_Formula = 'x', + HistoryItemGUID = @higuid + from [clientob].[FactStaffingPCVar] fct + inner join #JobCodes jc + on fct.DepartmentalBudgetID = jc.DepartmentalBudgetID + inner join #SystemAvg sa + on fct.JobCodeID = sa.JobCodeID + and fct.PayCodeGroupID = sa.PayCodeGroupID + left join #EntityAvg ea + on jc.EntityID = ea.EntityID + and fct.JobCodeID = ea.JobCodeID + and fct.PayCodeGroupID = ea.PayCodeGroupID + where 1=1 + and ea.Row = 1 + and fct.TimeClassID = 2 + and fct.UnitTypeID = 159 + and fct.FiscalMonthID = 0 + and fct.AssumptionID = 18 + and fct.FiscalYearID = (@FiscalYearID+1) + end + +-------------------------------------------------------------------------------------------------- +-- Clean-up +-------------------------------------------------------------------------------------------------- + +--disable cache for plans + if (@planGUIDList = '') begin + exec [dbo].[procInvalidateModelWorkbookCacheByPlanType] '05512126-3EB6-4DA4-AF6E-BC2BC2724B8B', 'procMissingJobCodeWageRates_Update' + end else begin + declare @invalidateWhere nvarchar(max) + set @invalidateWhere = 'PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(''' + @planGUIDList + ''','',''))' + exec [dbo].[procInvalidateModelWorkbookCacheByWhereClause] @invalidateWhere, 0, 'procMissingJobCodeWageRates_Update' + end + + drop table #Plans + drop table #JobCodes + drop table #EntityAvg + drop table #SystemAvg + +end +GO + + +--------------------------------------------- + +-- ob.procOBSPSLForecastYr1VoltoOBBaseline +create proc [ob].[procOBSPSLForecastYr1VoltoOBBaseline] + @planGUIDList nvarchar(max)='', + @IsDebugOnly bit = 0 +/************************************************************************************************************************ +** Author: cbecker +** Create Date: 2016-04-05 +** Description: B-11790 transfer service line volumes from strategic planning to the OB Service line model +** Last Modified: 2016-04-05 +** GM Release: 2016.2.1 +************************************************************************************************************************** +** Change History +************************************************************************************************************************** +** CID Date Author WI Description +** +*************************************************************************************************************************/ +as +begin +-------------------------------------------------------------------------------------------------- +-- Logging +-------------------------------------------------------------------------------------------------- + declare @logdesc nvarchar(100) + select @logdesc = case @IsDebugOnly + when 1 then 'Debug only - Transfer SP service line volumes from SP forecast year 1 to OB SL baseline' + else 'Transfer SP service line volumes from SP forecast year 1 to OB SL baseline' + end + + declare @higuid uniqueidentifier + exec procLogScript @logdesc, @higuid output + + print N'select * from [dbo].[HistoryItem] where HISTORYITEMGUID=''' + +cast(@higuid as varchar(36)) + +N'''' + +-------------------------------------------------------------------------------------------------- +-- Declare variables +-------------------------------------------------------------------------------------------------- + declare @budgetyear int + select @budgetyear = dbs.Setting+1 + from [dbo].[DBSetting] dbs + where dbs.Name = 'OB_Current_Year' + + declare @sql nvarchar(max) = '' + +-------------------------------------------------------------------------------------------------- +-- Populate plans temp table +-------------------------------------------------------------------------------------------------- + Create Table #Plans(OBServiceLinePlanID int, SPLongRangeServiceLineID int) + if (len(@planGUIDList) = 0) + begin + -- if no plans provided, we will update job codes for all plans + insert into #Plans(OBServiceLinePlanID, SPLongRangeServiceLineID) + select ob.OBServiceLinePlanID,sp.SPLongRangeServiceLineID + from [ob].[DimOBServiceLinePlan] ob + inner join [fw].[DimDepartment] dpt + on ob.EntityID=dpt.EntityID + inner join [sp].[DimSPLongRangeServiceLine] sp + on dpt.DepartmentID=sp.EntityID + where 1=1 + and dpt.IsDepartmentRollup = 1 + and sp.ScenarioID = 0 + and sp.IsDeleted = 0 + and ob.IsDeleted = 0 + end + else + begin + -- if plans are provided, we will only update job codes in specified plans + insert into #Plans(OBServiceLinePlanID, SPLongRangeServiceLineID) + select ob.OBServiceLinePlanID,sp.SPLongRangeServiceLineID + from [ob].[DimOBServiceLinePlan] ob + inner join dbo.ConvertCSGuidsToTable(@planGUIDList, ',') pg + on pg.guid=ob.MemberGUID + inner join [fw].[DimDepartment] dpt + on ob.EntityID=dpt.EntityID + inner join [sp].[DimSPLongRangeServiceLine] sp + on dpt.DepartmentID=sp.EntityID + where 1=1 + and dpt.IsDepartmentRollup = 1 + and sp.ScenarioID = 0 + and sp.IsDeleted = 0 + and ob.IsDeleted = 0 + end + +-------------------------------------------------------------------------------------------------- +-- Suppress percentage adjustments +-------------------------------------------------------------------------------------------------- +set @sql = @sql ++' +update vr +set vr.Amount = -1, + vr.Amount_Formula=''x'' +--select * +from [clientob].[FactServiceLineRollupVar] vr + inner join #Plans pl on vr.OBServiceLinePlanID=pl.OBServiceLinePlanID +where 1=1 + and vr.TimeClassID = 18 --baseline + and vr.AssumptionID = 18 --adjustment + and vr.FiscalMonthID = 0 --not specified + and vr.UnitTypeID = 142 --percentage + and vr.DataTypeID = 2 --var + and vr.OBForecastDetailID = 36 --volume + and vr.FiscalYearID = ' ++ cast(@budgetyear as nvarchar(4)) ++ ' --current budget year +' + +-------------------------------------------------------------------------------------------------- +-- Delete existing service line volume adjustments +-------------------------------------------------------------------------------------------------- +set @sql = @sql ++' +delete vr +--select * +from [clientob].[FactServiceLineVar] vr + inner join #Plans pl on vr.OBServiceLinePlanID=pl.OBServiceLinePlanID +where 1=1 + and vr.TimeClassID = 18 --baseline + and vr.AssumptionID = 18 --adjustment + and vr.FiscalMonthID = 0 --not specified + and vr.UnitTypeID = 140 --volume + and vr.DataTypeID = 2 --var + and vr.OBForecastDetailID = 36 --volume + and vr.FiscalYearID = ' ++ cast(@budgetyear as nvarchar(4)) ++ ' --current budget year +' + +-------------------------------------------------------------------------------------------------- +-- Insert service line volumes from SP to OB +-------------------------------------------------------------------------------------------------- +set @sql = @sql ++' +insert into [clientob].[FactServiceLineVar] +( + [AssumptionID], + [DataTypeID], + [FiscalMonthID], + [FiscalYearID], + [ModelingServiceLineID], + [OBForecastDetailID], + [OBServiceLinePlanID], + [TimeClassID], + [UnitTypeID], + [Amount], + [IsDeleted], + [HistoryItemGUID] +) +select + AssumptionID = 18, + DataTypeID = 2, + FiscalMonthID = 0, + FiscalYearID = ' ++ cast(@budgetyear as nvarchar(4)) ++ ', + ModelingServiceLineID = fct.ModelingServiceLineID, + OBForecastDetailID = 36, + OBServiceLinePlanID = pg.OBServiceLinePlanID, + TimeClassID = 18, + UnitTypeID = 140, + Amount = sum(fct.Amount), + IsDeleted = 0, + HistoryItemGUID = ''' ++ cast(@higuid as nvarchar(36)) ++ ''' +from [clientsp].[FactServiceLineRevenue] fct + inner join #Plans pg + on fct.SPLongRangeServiceLineID = pg.SPLongRangeServiceLineID +where 1=1 + and fct.TimeClassID = 3 --forecast + and fct.DataTypeID = 3 --output + and fct.UnitTypeID = 140 --volume + and fct.AccountRollupID = 3 --volumes + and fct.FiscalYearID = ' ++ cast(@budgetyear as nvarchar(4)) ++ ' --current budget year +group by + fct.ModelingServiceLineID, + pg.OBServiceLinePlanID +' + +-------------------------------------------------------------------------------------------------- +-- Run/Print SQL +-------------------------------------------------------------------------------------------------- +if @IsDebugOnly=1 + begin + print(@sql) + end +else + begin + exec(@sql) + end + +-------------------------------------------------------------------------------------------------- +-- Invalidate cache +-------------------------------------------------------------------------------------------------- +if @IsDebugOnly=1 + begin + print('Model workbook cache is not invalidated in debug mode.') + end +else + begin + if (@planGUIDList = '') + begin + exec [dbo].[procInvalidateModelWorkbookCacheByPlanType] '957dd809-6299-4ec2-81fc-5452df805e8e', 'procOBSPSLForecastYr1VoltoOBBaseline' + end + else + begin + declare @invalidateWhere nvarchar(max) + set @invalidateWhere = 'PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(''' + @planGUIDList + ''','',''))' + exec [dbo].[procInvalidateModelWorkbookCacheByWhereClause] @invalidateWhere, 0, 'procOBSPSLForecastYr1VoltoOBBaseline' + end + end + +-------------------------------------------------------------------------------------------------- +-- Clean-up +-------------------------------------------------------------------------------------------------- + drop table #Plans + +end +GO + + +--------------------------------------------- + +-- ob.procOBSnapshotInsert +CREATE proc [ob].[procOBSnapshotInsert] + @SnapshotCategory nvarchar(200)='Auto', + @SnapshotName nvarchar(200)='' +/************************************************************************************************************************ +** Author: Joel Gerber +** Create Date: 2014-07 +** Description: Saves all the operating budgeting data in snapshot tables with a snapshot ID +** Last Modified: 2017-12-05 +** GM Release: 2014.4 +************************************************************************************************************************** +** Change History +************************************************************************************************************************** +** CID Date Author WI Description +** 1 2014-09-15 JG Adding Provider, Reimbursement, Service Line, and Financial Planning data sources +** 2 2015-09-25 cbb D-03363 Adding joins to dimensions to exclude orphaned data +** 3 2016-02-03 cbb D-03664 Adding missing fact table and dimension deletes +** 4 2017-05-02 cbb B-15664 Refactoring and adding Budget Close category +** 5 2017-05-11 cbb D-05935 fix join on wrong dimension +** 6 2017-06-06 cbb B-15886 add var table snapshots +** 7 2017-11-09 apukii B-17941 add ability to set snapshots name +** 8 2017-11-14 apukii B-17941 modified category limits +** 9 2017-11-20 apukii B-17941 delete snapshots only in case Budget Close +** 10 2017-11-24 apukii B-17941 replaced [fw].[DimForecastDetail] with [ob].[DimOBForecastDetail] for FactProviderVarSnapshot and FactCDMVarSnapshot +** 11 2017-12-05 apukii B-18163 allowed all new snapshots to include var table data +*************************************************************************************************************************/ +as +begin + +---------------------------------------------------------------------------------------------------- +-- Populate temp table with snapshots to be deleted +---------------------------------------------------------------------------------------------------- + ; -- CTE - previous statement must be terminated with a semicolon + with oldsnapshots + as + ( + select + Category, + OBSnapshotID, + Num = row_number() over (PARTITION BY Category order by Date desc, OBSnapshotID desc) + from [ob].[DimOBSnapshot] + ) + select OBSnapshotID, Num + into #tempOldSnapshotIDs + from oldsnapshots + where 1=1 + and Category = 'Budget Close' and Num > 1 + +---------------------------------------------------------------------------------------------------- +-- Delete old snapshots +---------------------------------------------------------------------------------------------------- + if (select count(OBSnapshotID) from #tempOldSnapshotIDs) > 0 and @SnapshotCategory = 'Budget Close' + begin + delete fct from [ob].[FactAccountSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID + delete fct from [ob].[FactStaffingPCSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID + delete fct from [ob].[FactReportingMonthlySnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID + delete fct from [ob].[FactGlobalStatisticsSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID + delete fct from [ob].[FactServiceLineSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID + delete fct from [ob].[FactCDMSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID + delete fct from [ob].[FactReimbursementPayorSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID + delete fct from [ob].[FactReimbursementAccountSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID + delete fct from [ob].[FactProviderSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID +-- CID 6 BEGIN + delete fct from [ob].[FactAccountSubtableVarSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID + delete fct from [ob].[FactAccountVarSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID + delete fct from [ob].[FactCDMVarSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID + delete fct from [ob].[FactProviderVarSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID + delete fct from [ob].[FactStaffingPCVarSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID +-- CID 6 END + --dimension + delete fct from [ob].[DimOBSnapshot] fct inner join #tempOldSnapshotIDs tmp on fct.OBSnapshotID=tmp.OBSnapshotID + end + +---------------------------------------------------------------------------------------------------- +-- Create new snapshot record +---------------------------------------------------------------------------------------------------- + declare @fiscalYear nvarchar(200) = (select top 1 convert(int, Setting) + 1 from [dbo].[DBSetting] where [Name] = 'OB_Current_Year') + declare @newSnapDate nvarchar(200) = left(convert(nvarchar,getdate(),120), 16) + declare @newSnapName nvarchar(200) + + select @newSnapName = + case @SnapshotName + when '' then @newSnapDate + else @SnapshotName + end + + select @newSnapName = + case @SnapshotCategory + when 'Budget Close' then 'Budget Close - FY' + @fiscalYear + ' - ' + @newSnapDate + else @newSnapName + end + + insert into [ob].[DimOBSnapshot] + (Name, Category, Date) + values + (@newSnapName, @SnapshotCategory, @newSnapDate) + + SELECT CAST(SCOPE_IDENTITY() as int); + + declare @newSnapID varchar(16) + select @newSnapID = OBsnapshotID + from [ob].[DimOBSnapshot] + where 1=1 + and Date = @newSnapDate + and OBSnapshotID <> 0 + +---------------------------------------------------------------------------------------------------- +-- FactAccountSnapshot +---------------------------------------------------------------------------------------------------- + insert into [ob].[FactAccountSnapshot] + ( + DepartmentalBudgetID, + AccountID, + FiscalYearID, + TimeClassID, + UnitTypeID, + DataTypeID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + Yearly, + Total, + MonthsLoaded, + YTD, + IsDeleted, + HistoryItemGUID, + OBSnapshotID + ) + select --select top 100 + fct.DepartmentalBudgetID, + fct.AccountID, + fct.FiscalYearID, + fct.TimeClassID, + fct.UnitTypeID, + fct.DataTypeID, + fct.Month01, + fct.Month02, + fct.Month03, + fct.Month04, + fct.Month05, + fct.Month06, + fct.Month07, + fct.Month08, + fct.Month09, + fct.Month10, + fct.Month11, + fct.Month12, + fct.Yearly, + fct.Total, + fct.MonthsLoaded, + fct.YTD, + fct.IsDeleted, + fct.HistoryItemGUID, + @newSnapID as SnapshotID + from [clientob].[FactAccount] fct + inner join [ob].[DimDepartmentalBudget] dmb + on fct.DepartmentalBudgetID=dmb.DepartmentalBudgetID + inner join [fw].[DimAccount] dma + on fct.AccountID=dma.AccountID + +---------------------------------------------------------------------------------------------------- +-- FactStaffingPCSnapshot +---------------------------------------------------------------------------------------------------- + insert into [ob].[FactStaffingPCSnapshot] + ( + DepartmentalBudgetID, + PayCodeGroupID, + JobCodeID, + FiscalYearID, + TimeClassID, + UnitTypeID, + DataTypeID, + PayCodeID, + EmployeeID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + Yearly, + Total, + MonthsLoaded, + YTD, + IsDeleted, + HistoryItemGUID, + OBSnapshotID + ) + select --select top 100 + fct.DepartmentalBudgetID, + fct.PayCodeGroupID, + fct.JobCodeID, + fct.FiscalYearID, + fct.TimeClassID, + fct.UnitTypeID, + fct.DataTypeID, + fct.PayCodeID, + fct.EmployeeID, + fct.Month01, + fct.Month02, + fct.Month03, + fct.Month04, + fct.Month05, + fct.Month06, + fct.Month07, + fct.Month08, + fct.Month09, + fct.Month10, + fct.Month11, + fct.Month12, + fct.Yearly, + fct.Total, + fct.MonthsLoaded, + fct.YTD, + fct.IsDeleted, + fct.HistoryItemGUID, + @newSnapID as SnapshotID + from + [clientob].[FactStaffingPC] fct + inner join [ob].[DimDepartmentalBudget] dmb + on fct.DepartmentalBudgetID=dmb.DepartmentalBudgetID + inner join [fw].[DimPayCodeGroup] dmg + on fct.PayCodeGroupID=dmg.PayCodeGroupID + inner join [fw].[DimPayCode] dmp + on fct.PayCodeID=dmp.PayCodeID + inner join [fw].[DimJobCode] dmj + on fct.JobCodeID=dmj.JobCodeID + inner join [fw].[DimEmployee] dme + on fct.EmployeeID=dme.EmployeeID + +---------------------------------------------------------------------------------------------------- +-- FactReportingMonthlySnapshot +---------------------------------------------------------------------------------------------------- + insert into [ob].[FactReportingMonthlySnapshot] + ( + DepartmentalBudgetID, + FinancialReportingID, + FiscalYearID, + TimeClassID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + Yearly, + Total, + YTD, + IsDeleted, + HistoryItemGUID, + OBSnapshotID + ) + select --select top 100 + fct.DepartmentalBudgetID, + fct.FinancialReportingID, + fct.FiscalYearID, + fct.TimeClassID, + fct.Month01, + fct.Month02, + fct.Month03, + fct.Month04, + fct.Month05, + fct.Month06, + fct.Month07, + fct.Month08, + fct.Month09, + fct.Month10, + fct.Month11, + fct.Month12, + fct.Yearly, + fct.Total, + fct.YTD, + fct.IsDeleted, + fct.HistoryItemGUID, + @newSnapID as SnapshotID + from + [clientob].[FactReportingMonthly] fct + inner join [ob].[DimDepartmentalBudget] dmb + on fct.DepartmentalBudgetID=dmb.DepartmentalBudgetID + inner join [ob].[DimFinancialReporting] dmf -- CID 5 + on fct.FinancialReportingID=dmf.FinancialReportingID + +---------------------------------------------------------------------------------------------------- +-- FactGlobalStatisticsSnapshot +---------------------------------------------------------------------------------------------------- + insert into [ob].[FactGlobalStatisticsSnapshot] + ( + OBGlobalStatisticsPlanID, + OBGlobalStatisticID, + FiscalYearID, + TimeClassID, + UnitTypeID, + DataTypeID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + Yearly, + Total, + MonthsLoaded, + YTD, + IsDeleted, + HistoryItemGUID, + OBSnapshotID + ) + select --select top 100 + fct.OBGlobalStatisticsPlanID, + fct.OBGlobalStatisticID, + fct.FiscalYearID, + fct.TimeClassID, + fct.UnitTypeID, + fct.DataTypeID, + fct.Month01, + fct.Month02, + fct.Month03, + fct.Month04, + fct.Month05, + fct.Month06, + fct.Month07, + fct.Month08, + fct.Month09, + fct.Month10, + fct.Month11, + fct.Month12, + fct.Yearly, + fct.Total, + fct.MonthsLoaded, + fct.YTD, + fct.IsDeleted, + fct.HistoryItemGUID, + @newSnapID as SnapshotID + from [clientob].[FactGlobalStatistics] fct + inner join [ob].[DimOBGlobalStatisticsPlan] dmp + on fct.OBGlobalStatisticsPlanID=dmp.OBGlobalStatisticsPlanID + inner join [ob].[DimOBGlobalStatistics] dmg + on fct.OBGlobalStatisticID=dmg.OBGlobalStatisticID + +---------------------------------------------------------------------------------------------------- +-- FactServiceLineSnapshot +---------------------------------------------------------------------------------------------------- + insert into [ob].[FactServiceLineSnapshot] + ( + OBServiceLinePlanID, + ModelingServiceLineID, + OBForecastDetailID, + DataTypeID, + UnitTypeID, + FiscalYearID, + TimeClassID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + Yearly, + Total, + YTD, + IsDeleted, + HistoryItemGUID, + OBSnapshotID + ) + select --select top 100 + fct.OBServiceLinePlanID, + fct.ModelingServiceLineID, + fct.OBForecastDetailID, + fct.DataTypeID, + fct.UnitTypeID, + fct.FiscalYearID, + fct.TimeClassID, + fct.Month01, + fct.Month02, + fct.Month03, + fct.Month04, + fct.Month05, + fct.Month06, + fct.Month07, + fct.Month08, + fct.Month09, + fct.Month10, + fct.Month11, + fct.Month12, + fct.Yearly, + fct.Total, + fct.YTD, + fct.IsDeleted, + fct.HistoryItemGUID, + @newSnapID as SnapshotID + from [clientob].[FactServiceLine] fct + inner join [ob].[DimOBServiceLinePlan] dmp + on fct.OBServiceLinePlanID=dmp.OBServiceLinePlanID + inner join [fw].[DimModelingServiceLine] dmm + on fct.ModelingServiceLineID=dmm.ModelingServiceLineID + inner join [ob].[DimOBForecastDetail] dmf + on fct.OBForecastDetailID=dmf.OBForecastDetailID + +---------------------------------------------------------------------------------------------------- +-- FactCDMSnapshot +---------------------------------------------------------------------------------------------------- + insert into [ob].[FactCDMSnapshot] + ( + ChargeCodeID, + DataTypeID, + FiscalYearID, + DepartmentalBudgetID, + OBForecastDetailID, + PatientClassID, + TimeClassID, + UnitTypeID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + Yearly, + Total, + YTD, + IsDeleted, + HistoryItemGUID, + OBSnapshotID + ) + select --select top 100 + fct.ChargeCodeID, + fct.DataTypeID, + fct.FiscalYearID, + fct.DepartmentalBudgetID, + fct.OBForecastDetailID, + fct.PatientClassID, + fct.TimeClassID, + fct.UnitTypeID, + fct.Month01, + fct.Month02, + fct.Month03, + fct.Month04, + fct.Month05, + fct.Month06, + fct.Month07, + fct.Month08, + fct.Month09, + fct.Month10, + fct.Month11, + fct.Month12, + fct.Yearly, + fct.Total, + fct.YTD, + fct.IsDeleted, + fct.HistoryItemGUID, + @newSnapID as SnapshotID + from [clientob].[FactCDM] fct + inner join [fw].[DimChargeCode] dmc + on fct.ChargeCodeID=dmc.ChargeCodeID + inner join [ob].[DimDepartmentalBudget] dmd + on fct.DepartmentalBudgetID=dmd.DepartmentalBudgetID + inner join [ob].[DimOBForecastDetail] dmf + on fct.OBForecastDetailID=dmf.OBForecastDetailID + + +---------------------------------------------------------------------------------------------------- +-- FactReimbursementPayorSnapshot +---------------------------------------------------------------------------------------------------- + insert into [ob].[FactReimbursementPayorSnapshot] + ( + DataTypeID, + FiscalYearID, + OBForecastDetailID, + OBReimbursementPlanID, + PatientReimbursementGroupID, + PayorID, + PayorGroupID, + TimeClassID, + UnitTypeID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + Yearly, + Total, + YTD, + MonthsLoaded, + IsDeleted, + HistoryItemGUID, + OBSnapshotID + ) + select --select top 100 + fct.DataTypeID, + fct.FiscalYearID, + fct.OBForecastDetailID, + fct.OBReimbursementPlanID, + fct.PatientReimbursementGroupID, + fct.PayorID, + fct.PayorGroupID, + fct.TimeClassID, + fct.UnitTypeID, + fct.Month01, + fct.Month02, + fct.Month03, + fct.Month04, + fct.Month05, + fct.Month06, + fct.Month07, + fct.Month08, + fct.Month09, + fct.Month10, + fct.Month11, + fct.Month12, + fct.Yearly, + fct.Total, + fct.YTD, + fct.MonthsLoaded, + fct.IsDeleted, + fct.HistoryItemGUID, + @newSnapID as SnapshotID + from [clientob].[FactReimbursement] fct + inner join [ob].[DimOBForecastDetail] dmf + on fct.OBForecastDetailID=dmf.OBForecastDetailID + inner join [ob].[DimOBReimbursementPlan] dmr + on fct.OBReimbursementPlanID=dmr.OBReimbursementPlanID + inner join [fw].[DimPatientReimbursementGroup] dmp + on fct.PatientReimbursementGroupID=dmp.PatientReimbursementGroupID + inner join [fw].[DimPayor] dmy + on fct.PayorID=dmy.PayorID + inner join [fw].[DimPayorGroup] dmg + on fct.PayorGroupID=dmg.PayorGroupID + +---------------------------------------------------------------------------------------------------- +-- FactReimbursementAccountSnapshot +---------------------------------------------------------------------------------------------------- + insert into [ob].[FactReimbursementAccountSnapshot] + ( + AccountID, + DataTypeID, + FiscalYearID, + OBReimbursementPlanID, + PatientReimbursementGroupID, + TimeClassID, + UnitTypeID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + Yearly, + Total, + YTD, + MonthsLoaded, + IsDeleted, + HistoryItemGUID, + OBSnapshotID + ) + select --select top 100 + fct.AccountID, + fct.DataTypeID, + fct.FiscalYearID, + fct.OBReimbursementPlanID, + fct.PatientReimbursementGroupID, + fct.TimeClassID, + fct.UnitTypeID, + fct.Month01, + fct.Month02, + fct.Month03, + fct.Month04, + fct.Month05, + fct.Month06, + fct.Month07, + fct.Month08, + fct.Month09, + fct.Month10, + fct.Month11, + fct.Month12, + fct.Yearly, + fct.Total, + fct.YTD, + fct.MonthsLoaded, + fct.IsDeleted, + fct.HistoryItemGUID, + @newSnapID as SnapshotID + from [clientob].[FactReimbursementAccount] fct + inner join [fw].[DimAccount] dma + on fct.AccountID=dma.AccountID + inner join [ob].[DimOBReimbursementPlan] dmr + on fct.OBReimbursementPlanID=dmr.OBReimbursementPlanID + inner join [fw].[DimPatientReimbursementGroup] dmp + on fct.PatientReimbursementGroupID=dmp.PatientReimbursementGroupID + +---------------------------------------------------------------------------------------------------- +-- FactProviderSnapshot +---------------------------------------------------------------------------------------------------- + insert into [ob].[FactProviderSnapshot] + ( + DataTypeID, + FiscalYearID, + DepartmentalBudgetID, + TimeClassID, + UnitTypeID, + ProviderID, + OBForecastDetailID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + Yearly, + Total, + YTD, + MonthsLoaded, + IsDeleted, + HistoryItemGUID, + OBSnapshotID + ) + select --select top 100 + fct.DataTypeID, + fct.FiscalYearID, + fct.DepartmentalBudgetID, + fct.TimeClassID, + fct.UnitTypeID, + fct.ProviderID, + fct.OBForecastDetailID, + fct.Month01, + fct.Month02, + fct.Month03, + fct.Month04, + fct.Month05, + fct.Month06, + fct.Month07, + fct.Month08, + fct.Month09, + fct.Month10, + fct.Month11, + fct.Month12, + fct.Yearly, + fct.Total, + fct.YTD, + fct.MonthsLoaded, + fct.IsDeleted, + fct.HistoryItemGUID, + @newSnapID as SnapshotID + from [clientob].[FactProvider] fct + inner join [ob].[DimDepartmentalBudget] dmd + on fct.DepartmentalBudgetID=dmd.DepartmentalBudgetID + inner join [fw].[DimProvider] dmp + on fct.ProviderID=dmp.ProviderID + inner join [ob].[DimOBForecastDetail] dmf + on fct.OBForecastDetailID=dmf.OBForecastDetailID + +---------------------------------------------------------------------------------------------------- +-- FactAccountSubtableVarSnapshot +---------------------------------------------------------------------------------------------------- + insert into [ob].[FactAccountSubtableVarSnapshot] + ( + [AccountID], + [AdjustmentCategoryID], + [AssumptionID], + [FiscalYearID], + [DepartmentalBudgetID], + [TimeClassID], + [UnitTypeID], + [Comment], + [Comment_Comment], + [Comment_Formula], + [Month01], + [Month02], + [Month03], + [Month04], + [Month05], + [Month06], + [Month07], + [Month08], + [Month09], + [Month10], + [Month11], + [Month12], + [Yearly], + [IsDeleted], + [HistoryItemGUID], + [OBSnapshotID] + ) + SELECT + fct.[AccountID], + fct.[AdjustmentCategoryID], + fct.[AssumptionID], + fct.[FiscalYearID], + fct.[DepartmentalBudgetID], + fct.[TimeClassID], + fct.[UnitTypeID], + fct.[Comment], + fct.[Comment_Comment], + fct.[Comment_Formula], + fct.[Month01], + fct.[Month02], + fct.[Month03], + fct.[Month04], + fct.[Month05], + fct.[Month06], + fct.[Month07], + fct.[Month08], + fct.[Month09], + fct.[Month10], + fct.[Month11], + fct.[Month12], + fct.[Yearly], + fct.[IsDeleted], + fct.[HistoryItemGUID], + @newSnapID as OBSnapshotID + FROM [clientob].[FactAccountSubtableVar] fct + join [fw].[DimAccount] da + on fct.AccountID = da.AccountID + join [ob].[DimAdjustmentCategory] dac + on fct.AdjustmentCategoryID = dac.AdjustmentCategoryID + join [fw].[DimAssumption] das + on fct.AssumptionID = das.AssumptionID + join [ob].[DimDepartmentalBudget] ddb + on fct.DepartmentalBudgetID = ddb.DepartmentalBudgetID + +---------------------------------------------------------------------------------------------------- +-- FactAccountVarSnapshot +---------------------------------------------------------------------------------------------------- + INSERT INTO [ob].[FactAccountVarSnapshot] + ( + [AccountID], + [AssumptionID], + [FiscalMonthID], + [FiscalYearID], + [DepartmentalBudgetID], + [RowNumberID], + [TimeClassID], + [UnitTypeID], + [Amount], + [Amount_Comment], + [Amount_Formula], + [Comment], + [Comment_Comment], + [Comment_Formula], + [TextValue], + [TextValue_Comment], + [TextValue_Formula], + [IsDeleted], + [HistoryItemGUID], + [OBSnapshotID] + ) + select + fct.[AccountID], + fct.[AssumptionID], + fct.[FiscalMonthID], + fct.[FiscalYearID], + fct.[DepartmentalBudgetID], + fct.[RowNumberID], + fct.[TimeClassID], + fct.[UnitTypeID], + fct.[Amount], + fct.[Amount_Comment], + fct.[Amount_Formula], + fct.[Comment], + fct.[Comment_Comment], + fct.[Comment_Formula], + fct.[TextValue], + fct.[TextValue_Comment], + fct.[TextValue_Formula], + fct.[IsDeleted], + fct.[HistoryItemGUID], + @newSnapID as [OBSnapshotID] + from [clientob].[FactAccountVar] fct + join [fw].[DimAccount] da + on fct.AccountID = da.AccountID + join [fw].[DimAssumption] das + on fct.AssumptionID = das.AssumptionID + join [ob].[DimDepartmentalBudget] ddb + on fct.DepartmentalBudgetID = ddb.DepartmentalBudgetID + +---------------------------------------------------------------------------------------------------- +-- FactCDMVarSnapshot +---------------------------------------------------------------------------------------------------- + INSERT INTO [ob].[FactCDMVarSnapshot] + ( + [AssumptionID], + [ChargeCodeID], + [DataTypeID], + [FiscalMonthID], + [FiscalYearID], + [DepartmentalBudgetID], + [OBForecastDetailID], + [PatientClassID], + [TimeClassID], + [UnitTypeID], + [Amount], + [Amount_Comment], + [Amount_Formula], + [Comment], + [TextValue], + [TextValue_Comment], + [TextValue_Formula], + [IsDeleted], + [HistoryItemGUID], + [OBSnapshotID] + ) + select + fct.[AssumptionID], + fct.[ChargeCodeID], + fct.[DataTypeID], + fct.[FiscalMonthID], + fct.[FiscalYearID], + fct.[DepartmentalBudgetID], + fct.[OBForecastDetailID], + fct.[PatientClassID], + fct.[TimeClassID], + fct.[UnitTypeID], + fct.[Amount], + fct.[Amount_Comment], + fct.[Amount_Formula], + fct.[Comment], + fct.[TextValue], + fct.[TextValue_Comment], + fct.[TextValue_Formula], + fct.[IsDeleted], + fct.[HistoryItemGUID], + @newSnapID as [OBSnapshotID] + from [clientob].[FactCDMVar] fct + join [fw].[DimChargeCode] dcc + on fct.ChargeCodeID = dcc.ChargeCodeID + join [ob].[DimOBForecastDetail] dfd + on fct.OBForecastDetailID = dfd.OBForecastDetailID + join [fw].[DimAssumption] das + on fct.AssumptionID = das.AssumptionID + join [ob].[DimDepartmentalBudget] ddb + on fct.DepartmentalBudgetID = ddb.DepartmentalBudgetID + join [fw].[DimPatientClass] dpc + on fct.PatientClassID = dpc.PatientClassID + +---------------------------------------------------------------------------------------------------- +-- FactProviderVarSnapshot +---------------------------------------------------------------------------------------------------- + INSERT INTO [ob].[FactProviderVarSnapshot] + ( + [AssumptionID], + [FiscalMonthID], + [FiscalYearID], + [DepartmentalBudgetID], + [OBForecastDetailID], + [ProviderID], + [TimeClassID], + [UnitTypeID], + [Amount], + [Amount_Comment], + [Amount_Formula], + [TextValue], + [TextValue_Comment], + [TextValue_Formula], + [IsDeleted], + [HistoryItemGUID], + [OBSnapshotID] + ) + select + fct.[AssumptionID], + fct.[FiscalMonthID], + fct.[FiscalYearID], + fct.[DepartmentalBudgetID], + fct.[OBForecastDetailID], + fct.[ProviderID], + fct.[TimeClassID], + fct.[UnitTypeID], + fct.[Amount], + fct.[Amount_Comment], + fct.[Amount_Formula], + fct.[TextValue], + fct.[TextValue_Comment], + fct.[TextValue_Formula], + fct.[IsDeleted], + fct.[HistoryItemGUID], + @newSnapID as [OBSnapshotID] + from [clientob].[FactProviderVar] fct + join [fw].[DimProvider] dp + on fct.ProviderID = dp.ProviderID + join [ob].[DimOBForecastDetail] dfd + on fct.OBForecastDetailID = dfd.OBForecastDetailID + join [fw].[DimAssumption] das + on fct.AssumptionID = das.AssumptionID + join [ob].[DimDepartmentalBudget] ddb + on fct.DepartmentalBudgetID = ddb.DepartmentalBudgetID + +---------------------------------------------------------------------------------------------------- +-- FactStaffingPCVarSnapshot +---------------------------------------------------------------------------------------------------- + INSERT INTO [ob].[FactStaffingPCVarSnapshot] + ( + [AssumptionID], + [EmployeeID], + [FiscalMonthID], + [FiscalYearID], + [JobCodeID], + [DepartmentalBudgetID], + [PayCodeGroupID], + [TimeClassID], + [UnitTypeID], + [Amount], + [Amount_Comment], + [Amount_Formula], + [Comment], + [Comment_Comment], + [Comment_Formula], + [TextValue], + [TextValue_Comment], + [TextValue_Formula], + [IsDeleted], + [HistoryItemGUID], + [OBSnapshotID] + ) + select + fct.[AssumptionID], + fct.[EmployeeID], + fct.[FiscalMonthID], + fct.[FiscalYearID], + fct.[JobCodeID], + fct.[DepartmentalBudgetID], + fct.[PayCodeGroupID], + fct.[TimeClassID], + fct.[UnitTypeID], + fct.[Amount], + fct.[Amount_Comment], + fct.[Amount_Formula], + fct.[Comment], + fct.[Comment_Comment], + fct.[Comment_Formula], + fct.[TextValue], + fct.[TextValue_Comment], + fct.[TextValue_Formula], + fct.[IsDeleted], + fct.[HistoryItemGUID], + @newSnapID as [OBSnapshotID] + from [clientob].[FactStaffingPCVar] fct + join [fw].[DimEmployee] de + on fct.EmployeeID = de.EmployeeID + join [fw].[DimJobCode] djc + on fct.JobCodeID = djc.JobCodeID + join [fw].[DimPayCodeGroup] dpc + on fct.PayCodeGroupID = dpc.PayCodeGroupID + join [fw].[DimAssumption] das + on fct.AssumptionID = das.AssumptionID + join [ob].[DimDepartmentalBudget] ddb + on fct.DepartmentalBudgetID = ddb.DepartmentalBudgetID + +---------------------------------------------------------------------------------------------------- +-- End procedure +---------------------------------------------------------------------------------------------------- +end + +RETURN +GO + + +--------------------------------------------- + +-- ob.procOptimizationRebuildIndexesData +CREATE PROC [ob].[procOptimizationRebuildIndexesData] + @forceExecution BIT = 0 +AS + +/************************************************************ +** Author: akowalski +** Create Date: 2013-02-18 +** Description: Finds all data tables in the OB schemas and rebuilds indexes, for use after large inserts/deletes +** Last Modified: 2017-01-12 +** GM Release: 2013-03-12 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2013-02-19 DK 56588 Adding update statistics command +** 1 2016-09-09 GF 12897 Include fillin tables +** 2 2017-01-12 VY 05020 Add @forceExecution optional parameter +** 3 2017-01-17 cbb 05447 add missing "(" +*************************************************************/ + +SET NOCOUNT ON; + + IF @forceExecution = 1 + BEGIN + DECLARE @SCHEMA nvarchar(256) + DECLARE @FactTableName nvarchar(256) + DECLARE @SQL nvarchar(1024) + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where + ( + t.schema_id in(select schema_id from sys.schemas where name in('ob', 'clientob')) and (t.name like 'fact%' and t.name not like '%map') + or + t.schema_id in(select schema_id from sys.schemas where name in('dbo', 'data')) and (t.name like 'scorefillin%') + ) + and t.object_ID not in ( + select distinct t.object_id from sys.tables t + inner join sys.indexes i on t.object_id=i.object_id + inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id + where p.data_compression<>0 + ) order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + --=================== BEGIN CID 1 ===================== + set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD WITH (FILLFACTOR=80) + update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN' + --=================== END CID 1 ======================= + --print @SQL + EXECUTE sp_executesql @SQL + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in('ob', 'clientob')) and (t.name like 'fact%' and t.name not like '%map') + and t.object_ID not in ( + select distinct t.object_id from sys.tables t + inner join sys.indexes i on t.object_id=i.object_id + inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id + where p.data_compression=0 + ) order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + --=================== BEGIN CID 1 ===================== + --begin cid 3 + set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD WITH (FILLFACTOR=80,DATA_COMPRESSION = PAGE) + update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN' + --end cid 3 + --=================== END CID 1 ======================= + --print @SQL + EXECUTE sp_executesql @SQL + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + END + ELSE + BEGIN + --Request 'OB Rebuild Indexes' task to rebuild indexes on the next run + UPDATE [ob].[SystemSetting] SET [Value] = '1' WHERE [Name] = 'OB_Rebuild_Indexes' + END +GO + + +--------------------------------------------- + +-- ob.procOptimizationRebuildIndexesDimensions +CREATE proc [ob].[procOptimizationRebuildIndexesDimensions] as + +/************************************************************ +** Author: akowalski +** Create Date: 2013-02-18 +** Description: Finds all dimension tables in the OB schemas and rebuilds indexes, for after dimension customization. +** Last Modified: 2013-02-18 +** GM Release: 2013-03-12 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2013-02-19 DK 56588 Adding update statistics command +** +*************************************************************/ + + +SET NOCOUNT ON; + + DECLARE @SCHEMA nvarchar(256) + DECLARE @FactTableName nvarchar(256) + DECLARE @SQL nvarchar(1024) + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in('ob', 'clientob')) and t.name like 'dim%' + and t.object_ID not in ( + select distinct t.object_id from sys.tables t + inner join sys.indexes i on t.object_id=i.object_id + inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id + where p.data_compression<>0 + ) order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + --=================== BEGIN CID 1 ===================== + set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD WITH (FILLFACTOR=80) + update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN' + --=================== END CID 1 ======================= + --print @SQL + EXECUTE sp_executesql @SQL + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in('ob', 'clientob')) and t.name like 'dim%' + and t.object_ID not in ( + select distinct t.object_id from sys.tables t + inner join sys.indexes i on t.object_id=i.object_id + inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id + where p.data_compression=0 + ) order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + --=================== BEGIN CID 1 ===================== + set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD WITH (FILLFACTOR=80,DATA_COMPRESSION = PAGE) + update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN' + --=================== END CID 1 ======================= + --print @SQL + EXECUTE sp_executesql @SQL + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + + +RETURN +GO + + +--------------------------------------------- + +-- ob.procOptimizationRebuildIndexesMapping +CREATE proc [ob].[procOptimizationRebuildIndexesMapping] as + +/************************************************************ +** Author: akowalski +** Create Date: 2013-02-18 +** Description: Finds all mapping tables in the OB schemas and rebuilds indexes, for use after publishing. +** Last Modified: 2013-05-03 +** GM Release: 2013-05-14 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2013-02-19 DK 56588 Adding update statistics command +** 2 2013-05-01 AKK 57940 Adding meexcelcell, emfmodeltemplate, scoremeasure, and emfmodeltemplateworksheet +** 3 2013-05-03 AKK 57940 Adding MEScorePlaceholderLabel +** 4 2016-09-09 GJF 12897 Change fill factor to 100 +*************************************************************/ + + +SET NOCOUNT ON; + + DECLARE @SCHEMA nvarchar(256) + DECLARE @FactTableName nvarchar(256) + DECLARE @SQL nvarchar(1024) + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in('ob', 'clientob')) and t.name like 'fact%map' + and t.object_ID not in ( + select distinct t.object_id from sys.tables t + inner join sys.indexes i on t.object_id=i.object_id + inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id + where p.data_compression<>0 + ) order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + --=================== BEGIN CID 1 ===================== + set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD WITH (FILLFACTOR=100) + update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN' + --=================== END CID 1 ======================= + --print @SQL + EXECUTE sp_executesql @SQL + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in('ob', 'clientob')) and t.name like 'fact%map' + and t.object_ID not in ( + select distinct t.object_id from sys.tables t + inner join sys.indexes i on t.object_id=i.object_id + inner join sys.partitions p on t.object_id=p.object_ID and i.index_id=p.index_id + where p.data_compression=0 + ) order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + --=================== BEGIN CID 1 ===================== + set @SQL = 'alter index all on ' + @SCHEMA + '.' + @FactTableName + ' REBUILD WITH (FILLFACTOR=100,DATA_COMPRESSION = PAGE) + update statistics ' + @SCHEMA + '.' + @FactTableName + ' WITH FULLSCAN' + --=================== END CID 1 ======================= + --print @SQL + EXECUTE sp_executesql @SQL + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + + --=================== BEGIN CID 2 ===================== + alter index all on dbo.meexcelcell REBUILD WITH (FILLFACTOR=100) + update statistics dbo.meexcelcell WITH FULLSCAN + + alter index all on dbo.emfmodeltemplate REBUILD WITH (FILLFACTOR=100) + update statistics dbo.emfmodeltemplate WITH FULLSCAN + + alter index all on dbo.scoremeasure REBUILD WITH (FILLFACTOR=100) + update statistics dbo.scoremeasure WITH FULLSCAN + + alter index all on dbo.emfmodeltemplateworksheet REBUILD WITH (FILLFACTOR=100) + update statistics dbo.emfmodeltemplateworksheet WITH FULLSCAN + --=================== END CID 2 ======================= + --=================== BEGIN CID 3 ===================== + alter index all on dbo.mescoreplaceholderlabel REBUILD WITH (FILLFACTOR=100) + update statistics dbo.mescoreplaceholderlabel WITH FULLSCAN + --=================== END CID 3 ======================= +GO + + +--------------------------------------------- + +-- ob.procRosterToDeptBudget +CREATE proc [ob].[procRosterToDeptBudget] +/**************************************************************************************************** +** Author: cbb +** Create Date: 2016.11.15 +** Description: Transfer roster budget to dept budget models +** Last Modified: 2018.01.17 +** GM Release: 2017.1.1 +**************************************************************************************************** +** Change History +**************************************************************************************************** +** CID Date Author WI Description +** 1 2017.02.06 cbb d05501 filter out dollars for fixed staffing insert +** 2 2017.03.06 srk D-05668 Added issytemset = 0 to the insert fillin sections +** 3 2017.03.20 srk TK-39537 Updated the invalidatecache section to use where by clause +** 4 2017.03.20 srk B-14939 Invalidate cache only for models where data does not tie out between roster tool and staffing tables +** 5 2018.01.17 ljc B-18199 Adding PayCodeGroupID in #JobCodeDept for var table merge +****************************************************************************************************/ +as + begin +-------------------------------------------------------------------------------------------------- +-- Variables +-------------------------------------------------------------------------------------------------- + declare @higuid uniqueidentifier + + declare @currYear int + select @currYear = Setting from [dbo].[DBSetting] where Name = 'OB_Current_Year' + + declare @IsProjected bit + select @IsProjected = IsProjectionHidden from [fp].[BudgetConfig] where IsActive = 1 + + declare @assumptionID int + select @assumptionID = dm.AssumptionID from [fw].[DimAssumption] dm where MemberGUID='8111719b-4232-49df-aced-1f5fe16df5b9' + + declare @planRefreshList as nvarchar(max) = '' + +-------------------------------------------------------------------------------------------------- +-- Logging +-------------------------------------------------------------------------------------------------- + exec procLogScript 'Update clientob.FactStaffingPCNonReporting from fp.viewRosterBudgetToStaffingPC' , @higuid output + print 'Beginning update, historyguid: ' + cast(@higuid as varchar(36)) + +-------------------------------------------------------------------------------------------------- +-- AGGREGATE ROSTER DATA FOR MERGE +-------------------------------------------------------------------------------------------------- +--CID 2 +-- SELECT +-- [DepartmentalBudgetID] +-- , [PayCodeGroupID] +-- , [PayCodeID] +-- , [JobCodeID] +-- , [EmployeeID] +-- , [FiscalYearID] +-- , [TimeClassID] +-- , [UnitTypeID] +-- , [DataTypeID] +-- , SUM([Month01]) AS Month01 +-- , SUM([Month02]) AS Month02 +-- , SUM([Month03]) AS Month03 +-- , SUM([Month04]) AS Month04 +-- , SUM([Month05]) AS Month05 +-- , SUM([Month06]) AS Month06 +-- , SUM([Month07]) AS Month07 +-- , SUM([Month08]) AS Month08 +-- , SUM([Month09]) AS Month09 +-- , SUM([Month10]) AS Month10 +-- , SUM([Month11]) AS Month11 +-- , SUM([Month12]) AS Month12 +-- INTO #RosterAggregate +-- FROM [fp].[viewRosterBudgetToStaffingPC] rb +-- GROUP BY +-- [DepartmentalBudgetID] +-- , [PayCodeGroupID] +-- , [PayCodeID] +-- , [JobCodeID] +-- , [EmployeeID] +-- , [FiscalYearID] +-- , [TimeClassID] +-- , [UnitTypeID] +-- , [DataTypeID] +-- HAVING NOT ( +-- SUM([Month01]) = 0 +-- AND SUM([Month02]) = 0 +-- AND SUM([Month03]) = 0 +-- AND SUM([Month04]) = 0 +-- AND SUM([Month05]) = 0 +-- AND SUM([Month06]) = 0 +-- AND SUM([Month07]) = 0 +-- AND SUM([Month08]) = 0 +-- AND SUM([Month09]) = 0 +-- AND SUM([Month10]) = 0 +-- AND SUM([Month11]) = 0 +-- AND SUM([Month12]) = 0 +-- ) + +--CID 2 + +SELECT + rb.[DepartmentalBudgetID] + , rb.[PayCodeGroupID] + , rb.[PayCodeID] + , rb.[JobCodeID] + , rb.[EmployeeID] + , rb.[FiscalYearID] + , rb.[TimeClassID] + , rb.[UnitTypeID] + , rb.[DataTypeID] + , SUM(RB.[Month01]) as [Month01] + , SUM(RB.[Month02]) as [Month02] + , SUM(RB.[Month03]) as [Month03] + , SUM(RB.[Month04]) as [Month04] + , SUM(RB.[Month05]) as [Month05] + , SUM(RB.[Month06]) as [Month06] + , SUM(RB.[Month07]) as [Month07] + , SUM(RB.[Month08]) as [Month08] + , SUM(RB.[Month09]) as [Month09] + , SUM(RB.[Month10]) as [Month10] + , SUM(RB.[Month11]) as [Month11] + , SUM(RB.[Month12]) as [Month12] + , SUM(ROUND(RB.[Month01],4)) + + SUM(ROUND(RB.[Month02],4)) + + SUM(ROUND(RB.[Month03],4)) + + SUM(ROUND(RB.[Month04],4)) + + SUM(ROUND(RB.[Month05],4)) + + SUM(ROUND(RB.[Month06],4)) + + SUM(ROUND(RB.[Month07],4)) + + SUM(ROUND(RB.[Month08],4)) + + SUM(ROUND(RB.[Month09],4)) + + SUM(ROUND(RB.[Month10],4)) + + SUM(ROUND(RB.[Month11],4)) + + SUM(ROUND(RB.[Month12],4)) as Total + INTO #RosterAggregateInitial + FROM [fp].[viewRosterBudgetToStaffingPC] RB + WHERE 1=1 + GROUP BY + rb.[DepartmentalBudgetID] + , rb.[PayCodeGroupID] + , rb.[PayCodeID] + , rb.[JobCodeID] + , rb.[EmployeeID] + , rb.[FiscalYearID] + , rb.[TimeClassID] + , rb.[UnitTypeID] + , rb.[DataTypeID] + +--ROSTER AGGREGATE TO INVALIDATE CACHE + + SELECT + rb.[DepartmentalBudgetID] + , rb.[PayCodeGroupID] + , rb.[PayCodeID] + , rb.[JobCodeID] + , rb.[EmployeeID] + , rb.[FiscalYearID] + , rb.[TimeClassID] + , rb.[UnitTypeID] + , rb.[DataTypeID] + , SUM(RB.[Month01]) as [Month01] + , SUM(RB.[Month02]) as [Month02] + , SUM(RB.[Month03]) as [Month03] + , SUM(RB.[Month04]) as [Month04] + , SUM(RB.[Month05]) as [Month05] + , SUM(RB.[Month06]) as [Month06] + , SUM(RB.[Month07]) as [Month07] + , SUM(RB.[Month08]) as [Month08] + , SUM(RB.[Month09]) as [Month09] + , SUM(RB.[Month10]) as [Month10] + , SUM(RB.[Month11]) as [Month11] + , SUM(RB.[Month12]) as [Month12] + INTO #RosterAggregate + FROM #RosterAggregateInitial RB + LEFT JOIN [clientob].[FactStaffingPC] FS + on RB.DepartmentalBudgetID = FS.DepartmentalBudgetID + and RB.JobCodeID = FS.JobCodeID + and RB.PayCodeGroupID = FS.PayCodeGroupID + and RB.UnitTypeID = FS.UnitTypeID + and RB.TimeClassID = FS.TimeClassID + and RB.FiscalYearID = FS.FiscalYearID + and RB.DataTypeID = FS.DataTypeID + GROUP BY + rb.[DepartmentalBudgetID] + , rb.[PayCodeGroupID] + , rb.[PayCodeID] + , rb.[JobCodeID] + , rb.[EmployeeID] + , rb.[FiscalYearID] + , rb.[TimeClassID] + , rb.[UnitTypeID] + , rb.[DataTypeID] + HAVING + ISNULL(ROUND(sum(RB.Total),0),0) <> ISNULL(ROUND(sum(FS.Total),0),0) + +--CID 2 + + +-------------------------------------------------------------------------------------------------- +-- DISTINCT JOB CODE AND DEPARTMENTS FOR VAR TABLE MERGE +-------------------------------------------------------------------------------------------------- + SELECT distinct + [DepartmentalBudgetID], + [PayCodeGroupID], --CID 5 Include PayCodeGroupID in JobCode & Departments for var table merge + [PayCodeID], + [JobCodeID], + 0 [EmployeeID], + [FiscalYearID], + [TimeClassID], + 160 as [UnitTypeID], + [DataTypeID] + INTO #JobCodeDept + FROM [fp].[viewRosterBudgetToStaffingPC] rb + +-------------------------------------------------------------------------------------------------- +-- AGGREGATE ROSTER DATA FOR MERGE WITH NO PAY CODE GROUP +-------------------------------------------------------------------------------------------------- +--CID 2 + +SELECT + rb.[DepartmentalBudgetID] + , 0 as [PayCodeGroupID] + , rb.[JobCodeID] + , rb.[EmployeeID] + , rb.[FiscalYearID] + , rb.[TimeClassID] + , rb.[UnitTypeID] + , rb.[DataTypeID] + , SUM(RB.[Month01]) as [Month01] + , SUM(RB.[Month02]) as [Month02] + , SUM(RB.[Month03]) as [Month03] + , SUM(RB.[Month04]) as [Month04] + , SUM(RB.[Month05]) as [Month05] + , SUM(RB.[Month06]) as [Month06] + , SUM(RB.[Month07]) as [Month07] + , SUM(RB.[Month08]) as [Month08] + , SUM(RB.[Month09]) as [Month09] + , SUM(RB.[Month10]) as [Month10] + , SUM(RB.[Month11]) as [Month11] + , SUM(RB.[Month12]) as [Month12] + , SUM(ROUND(RB.[Month01],4)) + + SUM(ROUND(RB.[Month02],4)) + + SUM(ROUND(RB.[Month03],4)) + + SUM(ROUND(RB.[Month04],4)) + + SUM(ROUND(RB.[Month05],4)) + + SUM(ROUND(RB.[Month06],4)) + + SUM(ROUND(RB.[Month07],4)) + + SUM(ROUND(RB.[Month08],4)) + + SUM(ROUND(RB.[Month09],4)) + + SUM(ROUND(RB.[Month10],4)) + + SUM(ROUND(RB.[Month11],4)) + + SUM(ROUND(RB.[Month12],4)) as Total + INTO #RosterAggregateNoPCGInitial + FROM [fp].[viewRosterBudgetToStaffingPC] RB + inner join [fw].[DimPayCodeGroup] pcg + on rb.PayCodeGroupID = pcg.PayCodeGroupID + where pcg.ProductiveClassID in (2,3) +-- CID 1 begin + and UnitTypeID <> 34 + GROUP BY + rb.[DepartmentalBudgetID] + , rb.[JobCodeID] + , rb.[EmployeeID] + , rb.[FiscalYearID] + , rb.[TimeClassID] + , rb.[UnitTypeID] + , rb.[DataTypeID] + +-- Roster Aggregate No Pay Code Group TO INVALIDATE CACHE + + SELECT + rb.[DepartmentalBudgetID] + , 0 as [PayCodeGroupID] + , rb.[JobCodeID] + , rb.[EmployeeID] + , rb.[FiscalYearID] + , rb.[TimeClassID] + , rb.[UnitTypeID] + , rb.[DataTypeID] + , SUM(RB.[Month01]) as [Month01] + , SUM(RB.[Month02]) as [Month02] + , SUM(RB.[Month03]) as [Month03] + , SUM(RB.[Month04]) as [Month04] + , SUM(RB.[Month05]) as [Month05] + , SUM(RB.[Month06]) as [Month06] + , SUM(RB.[Month07]) as [Month07] + , SUM(RB.[Month08]) as [Month08] + , SUM(RB.[Month09]) as [Month09] + , SUM(RB.[Month10]) as [Month10] + , SUM(RB.[Month11]) as [Month11] + , SUM(RB.[Month12]) as [Month12] + INTO #RosterAggregateNoPayCodeGroup + FROM #RosterAggregateNoPCGInitial RB + LEFT JOIN [clientob].[FactStaffingPC] FS + on RB.DepartmentalBudgetID = FS.DepartmentalBudgetID + and RB.JobCodeID = FS.JobCodeID + and RB.PayCodeGroupID = FS.PayCodeGroupID + and RB.UnitTypeID = FS.UnitTypeID + and RB.TimeClassID = FS.TimeClassID + and RB.FiscalYearID = FS.FiscalYearID + and RB.DataTypeID = FS.DataTypeID + GROUP BY + rb.[DepartmentalBudgetID] + , rb.[JobCodeID] + , rb.[EmployeeID] + , rb.[FiscalYearID] + , rb.[TimeClassID] + , rb.[UnitTypeID] + , rb.[DataTypeID] + HAVING + ISNULL(ROUND(sum(RB.Total),0),0) <> ISNULL(ROUND(sum(FS.Total),0),0) + +-- SELECT +-- DepartmentalBudgetID = [DepartmentalBudgetID], +-- PayCodeGroupID = 0, +-- JobCodeID = [JobCodeID], +-- EmployeeID = [EmployeeID], +-- FiscalYearID = [FiscalYearID], +-- TimeClassID = [TimeClassID], +-- UnitTypeID = [UnitTypeID], +-- DataTypeID = [DataTypeID], +-- Month01 = SUM([Month01]), +-- Month02 = SUM([Month02]), +-- Month03 = SUM([Month03]), +-- Month04 = SUM([Month04]), +-- Month05 = SUM([Month05]), +-- Month06 = SUM([Month06]), +-- Month07 = SUM([Month07]), +-- Month08 = SUM([Month08]), +-- Month09 = SUM([Month09]), +-- Month10 = SUM([Month10]), +-- Month11 = SUM([Month11]), +-- Month12 = SUM([Month12]) +-- INTO #RosterAggregateNoPayCodeGroup +-- FROM [fp].[viewRosterBudgetToStaffingPC] rb +-- inner join [fw].[DimPayCodeGroup] pcg +-- on rb.PayCodeGroupID = pcg.PayCodeGroupID +-- where pcg.ProductiveClassID in (2,3) +---- CID 1 begin +-- and UnitTypeID <> 34 +---- CID 2 end +-- GROUP BY +-- [DepartmentalBudgetID] +-- , [JobCodeID] +-- , [EmployeeID] +-- , [FiscalYearID] +-- , [TimeClassID] +-- , [UnitTypeID] +-- , [DataTypeID] +-- HAVING NOT ( +-- SUM([Month01]) = 0 +-- AND SUM([Month02]) = 0 +-- AND SUM([Month03]) = 0 +-- AND SUM([Month04]) = 0 +-- AND SUM([Month05]) = 0 +-- AND SUM([Month06]) = 0 +-- AND SUM([Month07]) = 0 +-- AND SUM([Month08]) = 0 +-- AND SUM([Month09]) = 0 +-- AND SUM([Month10]) = 0 +-- AND SUM([Month11]) = 0 +-- AND SUM([Month12]) = 0 +-- ) +-- CID 2 + + + + +-------------------------------------------------------------------------------------------------- +-- Job code temp table +-------------------------------------------------------------------------------------------------- + select distinct + DepartmentalBudgetID = ra.DepartmentalBudgetID, + ModelGUID = db.MemberGUID, + JobCodeID = ra.JobCodeID, + JobCodeGUID = jc.MemberGUID + into #JobCodes + from #RosterAggregateInitial ra + inner join [ob].[DimDepartmentalBudget] db + on ra.DepartmentalBudgetID = db.DepartmentalBudgetID + inner join [fw].[DimJobCode] jc + on ra.JobCodeID = jc.JobCodeID + +CREATE UNIQUE CLUSTERED INDEX BASE ON #JobCodes (ModelGUID, JobCodeID); + +-------------------------------------------------------------------------------------------------- +-- Department temp table +-------------------------------------------------------------------------------------------------- + select distinct + jc.DepartmentalBudgetID, + db.MemberGUID + into #Departments + from #JobCodes jc + inner join [ob].[DimDepartmentalBudget] db on jc.DepartmentalBudgetID = db.DepartmentalBudgetID + +CREATE UNIQUE CLUSTERED INDEX BASE ON #Departments (MemberGUID); + + select distinct + jc.DepartmentalBudgetID, + db.MemberGUID + into #DepartmentsCache + from #RosterAggregate jc + inner join [ob].[DimDepartmentalBudget] db on jc.DepartmentalBudgetID = db.DepartmentalBudgetID + +CREATE UNIQUE CLUSTERED INDEX BASE ON #DepartmentsCache (MemberGUID); +-------------------------------------------------------------------------------------------------- +-- Insert enable fill-in +-------------------------------------------------------------------------------------------------- +; + WITH SF AS + ( + SELECT + [FillinGUID], + [ModelGUID], + [PlaceholderSectionMemberGUID], + [FillinMemberGUID], + [FillinMemberName], + [IsSystemSet] + FROM [dbo].[ScoreFillin] + WHERE PlaceholderSectionMemberGUID = 'da5abe63-1339-467d-ad83-89824174bc31' + ) + MERGE SF AS TARGET + USING #Departments AS SOURCE + ON ( + 1=1 + AND TARGET.ModelGUID = SOURCE.MemberGUID + ) + WHEN NOT MATCHED BY TARGET + THEN + INSERT([FillinGUID], [ModelGUID], [PlaceholderSectionMemberGUID], [FillinMemberGUID], [FillinMemberName], [IsSystemSet]) + VALUES(newid(), MemberGUID, 'da5abe63-1339-467d-ad83-89824174bc31', 'fefe375c-656a-4a68-9c60-c5ce63f9919b', 'Enable', 0) + WHEN + NOT MATCHED BY SOURCE + THEN DELETE + ; -- end merge + +-------------------------------------------------------------------------------------------------- +-- Refresh fill-in cache table for Forecast Detail dimension +-------------------------------------------------------------------------------------------------- + exec [dbo].[procScoreFillinTableRefreshByDimension] + @dimensionGUID = '7997659c-8a30-4d1e-86d2-0afb41c9e2fc', + @isDebug = 0, + @whereClause = '' + +-------------------------------------------------------------------------------------------------- +-- Insert missing job code fill-ins +-------------------------------------------------------------------------------------------------- + INSERT INTO [dbo].[ScoreFillin] + ( + [FillinGUID], + [ModelGUID], + [PlaceholderSectionMemberGUID], + [PlaceholderIndex], + [FillinMemberGUID], + [FillinMemberName], + [HistoryItemGUID], + [IsSystemSet] + ) + SELECT + [FillinGUID] = newid(), + [ModelGUID] = db.MemberGUID, + [PlaceholderSectionMemberGUID] = smg.SectionMemberGUID, + [PlaceholderIndex] = coalesce(fmax.MAXPlaceholderIndex,0)+cast(ROW_NUMBER() over (partition by db.MemberGUID, smg.SectionMemberGUID order by jc.Name) as int), + [FillinMemberGUID] = jc.MemberGUID, + [FillinMemberName] = jc.Name, + [HistoryItemGUID] = @higuid, + case when smg.sectionmemberguid = '871804c8-1114-4cfa-b10d-ac401e2c88cb' then 0 else 1 end as [IsSystemSet] +-- into #scorefillin_new + from #JobCodes jc_temp + inner join [ob].[DimDepartmentalBudget] db on jc_temp.DepartmentalBudgetID = db.DepartmentalBudgetID + inner join [fw].[DimJobCode] jc on jc_temp.JobCodeID = jc.JobCodeID + cross join (select CAST('871804c8-1114-4cfa-b10d-ac401e2c88cb' AS uniqueidentifier) AS SectionMemberGUID UNION ALL select CAST('e9ce521d-6953-4636-94cd-b36798515385' AS uniqueidentifier) AS SectionMemberGUID) smg + left join [dbo].[ScoreFillin] sf1 on + db.MemberGUID = sf1.ModelGUID + and jc.MemberGUID = sf1.FillinMemberGUID + inner join + ( + select + ModelGUID, + PlaceholderSectionMemberGUID, + max(PlaceholderIndex) as MAXPlaceholderIndex + from [dbo].[ScoreFillin] sf + where PlaceholderSectionMemberGUID in ('871804c8-1114-4cfa-b10d-ac401e2c88cb','e9ce521d-6953-4636-94cd-b36798515385') + group by ModelGUID, PlaceholderSectionMemberGUID + ) fmax ON + fmax.ModelGUID=db.MemberGUID + and smg.SectionMemberGUID=fmax.PlaceholderSectionMemberGUID + where 1=1 + and sf1.FillinMemberName is null + +-------------------------------------------------------------------------------------------------- +-- Refresh fill-in cache table for Forecast Detail dimension +-------------------------------------------------------------------------------------------------- + exec [dbo].[procScoreFillinTableRefreshByDimension] @dimensionGUID = '99bd1b87-5803-4847-aa83-80c2613aa41b', @isDebug = 0, @whereClause = '' + +-------------------------------------------------------------------------------------------------- +-- Run expansion profile fit update after fill-ins are added +-------------------------------------------------------------------------------------------------- + exec [dbo].[procMEScoreExpansionProfileFitPlans] + @templateGUID = 'c397fa93-f151-4751-ad36-7a34aa7ee3ef', + @planGUIDList = NULL, + @expansionPadding = 10 + +-------------------------------------------------------------------------------------------------- +-- Update var table settings +-------------------------------------------------------------------------------------------------- +; + WITH fctv AS + ( + select + DepartmentalBudgetID, + PayCodeGroupID, + JobCodeID, + EmployeeID, + FiscalYearID, + FiscalMonthID, + TimeClassID, + UnitTypeID, + AssumptionID, + Amount, + Amount_Formula, + HistoryItemGUID, + TransactionID + from [clientob].[FactStaffingPCVar] + where 1=1 +--CID 5 and PayCodeGroupID = 0 + and UnitTypeID = 160 + and AssumptionID = @assumptionID + and FiscalYearID >= @currYear + and IsDeleted = 0 + ) + MERGE fctv AS TARGET + USING #JobCodeDept AS SOURCE + ON ( + 1=1 + AND TARGET.[DepartmentalBudgetID] = SOURCE.[DepartmentalBudgetID] + AND TARGET.[JobCodeID] = SOURCE.[JobCodeID] + AND TARGET.[EmployeeID] = SOURCE.[EmployeeID] + AND TARGET.[FiscalYearID] = SOURCE.[FiscalYearID] + AND TARGET.[TimeClassID] = SOURCE.[TimeClassID] + and target.PayCodeGroupID = source.PayCodeGroupID + and target.UnitTypeID = source.UnitTypeID + and target.AssumptionID = @assumptionID + and target.FiscalYearID = source.FiscalYearID + ) + WHEN NOT MATCHED BY TARGET + THEN + INSERT(DepartmentalBudgetID, PayCodeGroupID, JobCodeID, EmployeeID, FiscalYearID, FiscalMonthID, TimeClassID, UnitTypeID, AssumptionID, Amount, Amount_Formula, HistoryItemGUID, TransactionID) + VALUES(DepartmentalBudgetID, PayCodeGroupID, JobCodeID, 0, FiscalYearID, 0, TimeClassID, 160, @assumptionID, 1, 'x', @higuid, -100) --CID 5 adding PayCodeGroupID + WHEN MATCHED + AND TARGET.Amount <> 1 + THEN + UPDATE + SET TARGET.Amount = 1, + TARGET.Amount_Formula = 'x', + TARGET.HistoryItemGUID = @higuid, + TARGET.TransactionID = -100 + WHEN NOT MATCHED BY SOURCE + AND TARGET.TransactionID = -100 + THEN DELETE + ; -- end merge + ; -- end with + + +-------------------------------------------------------------------------------------------------- +-- MERGE clientob.FactStaffingPCNonReporting - Fixed staffing +-------------------------------------------------------------------------------------------------- + with fct as + ( + select + DepartmentalBudgetID, + PayCodeGroupID, + JobCodeID, + EmployeeID, + FiscalYearID, + TimeClassID, + UnitTypeID, + DataTypeID, + Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, + HistoryItemGUID, + TransactionID + from [clientob].[FactStaffingPCNonReporting] nonr + where 1=1 +-- and nonr.FiscalYearID >= @currYear + and nonr.DataTypeID = 4 + and nonr.PayCodeGroupID = 0 + ) + MERGE fct AS TARGET + USING #RosterAggregateNoPCGInitial AS SOURCE + ON ( + 1=1 + AND TARGET.[DepartmentalBudgetID] = SOURCE.[DepartmentalBudgetID] + AND TARGET.[PayCodeGroupID] = SOURCE.[PayCodeGroupID] + AND TARGET.[JobCodeID] = SOURCE.[JobCodeID] + AND TARGET.[EmployeeID] = SOURCE.[EmployeeID] + AND TARGET.[FiscalYearID] = SOURCE.[FiscalYearID] + AND TARGET.[TimeClassID] = SOURCE.[TimeClassID] + AND TARGET.[UnitTypeID] = SOURCE.[UnitTypeID] +-- AND TARGET.[DataTypeID] = 4 + ) + WHEN + NOT MATCHED BY TARGET + THEN + INSERT(DepartmentalBudgetID, PayCodeGroupID, JobCodeID, EmployeeID, FiscalYearID, TimeClassID, UnitTypeID, DataTypeID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, HistoryItemGUID, TransactionID) + VALUES(DepartmentalBudgetID, PayCodeGroupID, JobCodeID, EmployeeID, FiscalYearID, TimeClassID, UnitTypeID, 4, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, @higuid, -100) + WHEN + MATCHED + AND + ( + TARGET.Month01<>SOURCE.Month01 + OR TARGET.Month02<>SOURCE.Month02 + OR TARGET.Month03<>SOURCE.Month03 + OR TARGET.Month04<>SOURCE.Month04 + OR TARGET.Month05<>SOURCE.Month05 + OR TARGET.Month06<>SOURCE.Month06 + OR TARGET.Month07<>SOURCE.Month07 + OR TARGET.Month08<>SOURCE.Month08 + OR TARGET.Month09<>SOURCE.Month09 + OR TARGET.Month10<>SOURCE.Month10 + OR TARGET.Month11<>SOURCE.Month11 + OR TARGET.Month12<>SOURCE.Month12 + ) + THEN + UPDATE + SET TARGET.Month01=SOURCE.Month01, + TARGET.Month02=SOURCE.Month02, + TARGET.Month03=SOURCE.Month03, + TARGET.Month04=SOURCE.Month04, + TARGET.Month05=SOURCE.Month05, + TARGET.Month06=SOURCE.Month06, + TARGET.Month07=SOURCE.Month07, + TARGET.Month08=SOURCE.Month08, + TARGET.Month09=SOURCE.Month09, + TARGET.Month10=SOURCE.Month10, + TARGET.Month11=SOURCE.Month11, + TARGET.Month12=SOURCE.Month12, + TARGET.HistoryItemGUID = @higuid + WHEN + NOT MATCHED BY SOURCE + AND TARGET.TransactionID=-100 + THEN DELETE + ; -- end merge + ; -- end with + +-------------------------------------------------------------------------------------------------- +-- MERGE clientob.FactStaffingPCNonReporting - Wages +-------------------------------------------------------------------------------------------------- + with fct as + ( + select + DepartmentalBudgetID, + PayCodeGroupID, + JobCodeID, + EmployeeID, + FiscalYearID, + TimeClassID, + UnitTypeID, + DataTypeID, + Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, + HistoryItemGUID, + TransactionID + from [clientob].[FactStaffingPCNonReporting] nonr + where 1=1 + and nonr.FiscalYearID >= @currYear + and nonr.DataTypeID = 4 + and nonr.PayCodeGroupID <> 0 + ) + MERGE fct AS TARGET + USING #RosterAggregateInitial AS SOURCE + ON ( + 1=1 + AND TARGET.[DepartmentalBudgetID] = SOURCE.[DepartmentalBudgetID] + AND TARGET.[PayCodeGroupID] = SOURCE.[PayCodeGroupID] + AND TARGET.[JobCodeID] = SOURCE.[JobCodeID] + AND TARGET.[EmployeeID] = SOURCE.[EmployeeID] + AND TARGET.[FiscalYearID] = SOURCE.[FiscalYearID] + AND TARGET.[TimeClassID] = SOURCE.[TimeClassID] + AND TARGET.[UnitTypeID] = SOURCE.[UnitTypeID] + -- AND TARGET.[DataTypeID] = 4 + ) + WHEN + NOT MATCHED BY TARGET + THEN + INSERT(DepartmentalBudgetID, PayCodeGroupID, JobCodeID, EmployeeID, FiscalYearID, TimeClassID, UnitTypeID, DataTypeID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, HistoryItemGUID, TransactionID) + VALUES(DepartmentalBudgetID, PayCodeGroupID, JobCodeID, EmployeeID, FiscalYearID, TimeClassID, UnitTypeID, 4, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, @higuid, -100) + WHEN + MATCHED + AND + ( + TARGET.Month01<>SOURCE.Month01 + OR TARGET.Month02<>SOURCE.Month02 + OR TARGET.Month03<>SOURCE.Month03 + OR TARGET.Month04<>SOURCE.Month04 + OR TARGET.Month05<>SOURCE.Month05 + OR TARGET.Month06<>SOURCE.Month06 + OR TARGET.Month07<>SOURCE.Month07 + OR TARGET.Month08<>SOURCE.Month08 + OR TARGET.Month09<>SOURCE.Month09 + OR TARGET.Month10<>SOURCE.Month10 + OR TARGET.Month11<>SOURCE.Month11 + OR TARGET.Month12<>SOURCE.Month12 + ) + THEN + UPDATE + SET TARGET.Month01=SOURCE.Month01, + TARGET.Month02=SOURCE.Month02, + TARGET.Month03=SOURCE.Month03, + TARGET.Month04=SOURCE.Month04, + TARGET.Month05=SOURCE.Month05, + TARGET.Month06=SOURCE.Month06, + TARGET.Month07=SOURCE.Month07, + TARGET.Month08=SOURCE.Month08, + TARGET.Month09=SOURCE.Month09, + TARGET.Month10=SOURCE.Month10, + TARGET.Month11=SOURCE.Month11, + TARGET.Month12=SOURCE.Month12, + TARGET.HistoryItemGUID = @higuid + WHEN + NOT MATCHED BY SOURCE + AND TARGET.TransactionID=-100 + THEN DELETE + ; -- end merge + ; -- end with + +-------------------------------------------------------------------------------------------------- +-- MERGE clientob.FactStaffingPC - Fixed staffing +-------------------------------------------------------------------------------------------------- + with fctw as + ( + select DepartmentalBudgetID, PayCodeGroupID, JobCodeID, EmployeeID, FiscalYearID, TimeClassID, UnitTypeID, DataTypeID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, HistoryItemGUID, TransactionID + from [clientob].[FactStaffingPC] fpc + where DataTypeID = 3 + and PayCodeGroupID = 0 + ) + MERGE fctw AS TARGET + USING #RosterAggregateNoPCGInitial AS SOURCE + ON ( + 1=1 + AND TARGET.[DepartmentalBudgetID] = SOURCE.[DepartmentalBudgetID] + AND TARGET.[PayCodeGroupID] = SOURCE.[PayCodeGroupID] + AND TARGET.[JobCodeID] = SOURCE.[JobCodeID] + AND TARGET.[EmployeeID] = SOURCE.[EmployeeID] + AND TARGET.[FiscalYearID] = SOURCE.[FiscalYearID] + AND TARGET.[TimeClassID] = SOURCE.[TimeClassID] + AND TARGET.[UnitTypeID] = SOURCE.[UnitTypeID] + -- AND TARGET.[DataTypeID] = SOURCE.[DataTypeID] + ) + WHEN + NOT MATCHED BY TARGET + THEN + INSERT(DepartmentalBudgetID, PayCodeGroupID, JobCodeID, EmployeeID, FiscalYearID, TimeClassID, UnitTypeID, DataTypeID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, HistoryItemGUID, TransactionID) + VALUES(DepartmentalBudgetID, PayCodeGroupID, JobCodeID, EmployeeID, FiscalYearID, TimeClassID, UnitTypeID, 3, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, @higuid, -100) + WHEN + MATCHED + AND + ( + TARGET.Month01<>SOURCE.Month01 + OR TARGET.Month02<>SOURCE.Month02 + OR TARGET.Month03<>SOURCE.Month03 + OR TARGET.Month04<>SOURCE.Month04 + OR TARGET.Month05<>SOURCE.Month05 + OR TARGET.Month06<>SOURCE.Month06 + OR TARGET.Month07<>SOURCE.Month07 + OR TARGET.Month08<>SOURCE.Month08 + OR TARGET.Month09<>SOURCE.Month09 + OR TARGET.Month10<>SOURCE.Month10 + OR TARGET.Month11<>SOURCE.Month11 + OR TARGET.Month12<>SOURCE.Month12 + ) + THEN + UPDATE + SET TARGET.Month01=SOURCE.Month01, + TARGET.Month02=SOURCE.Month02, + TARGET.Month03=SOURCE.Month03, + TARGET.Month04=SOURCE.Month04, + TARGET.Month05=SOURCE.Month05, + TARGET.Month06=SOURCE.Month06, + TARGET.Month07=SOURCE.Month07, + TARGET.Month08=SOURCE.Month08, + TARGET.Month09=SOURCE.Month09, + TARGET.Month10=SOURCE.Month10, + TARGET.Month11=SOURCE.Month11, + TARGET.Month12=SOURCE.Month12, + TARGET.HistoryItemGUID = @higuid, + TARGET.TransactionID = -100 + WHEN + NOT MATCHED BY SOURCE + AND TARGET.TransactionID = -100 + THEN DELETE + ; -- end merge + ; -- end with + +-------------------------------------------------------------------------------------------------- +-- MERGE clientob.FactStaffingPC - Wages +-------------------------------------------------------------------------------------------------- + with fctw as + ( + select + DepartmentalBudgetID, + PayCodeGroupID, + JobCodeID, + EmployeeID, + FiscalYearID, + TimeClassID, + UnitTypeID, + DataTypeID, + Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, + HistoryItemGUID, + TransactionID + from [clientob].[FactStaffingPC] fpc + where DataTypeID = 3 + and fpc.PayCodeGroupID<>0 + ) + MERGE fctw AS TARGET + USING #RosterAggregateInitial AS SOURCE + ON ( + 1=1 + AND TARGET.[DepartmentalBudgetID] = SOURCE.[DepartmentalBudgetID] + AND TARGET.[PayCodeGroupID] = SOURCE.[PayCodeGroupID] + AND TARGET.[JobCodeID] = SOURCE.[JobCodeID] + AND TARGET.[EmployeeID] = SOURCE.[EmployeeID] + AND TARGET.[FiscalYearID] = SOURCE.[FiscalYearID] + AND TARGET.[TimeClassID] = SOURCE.[TimeClassID] + AND TARGET.[UnitTypeID] = SOURCE.[UnitTypeID] + -- AND TARGET.[DataTypeID] = SOURCE.[DataTypeID] + ) + WHEN + NOT MATCHED BY TARGET + THEN + INSERT(DepartmentalBudgetID, PayCodeGroupID, JobCodeID, EmployeeID, FiscalYearID, TimeClassID, UnitTypeID, DataTypeID, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, HistoryItemGUID, TransactionID) + VALUES(DepartmentalBudgetID, PayCodeGroupID, JobCodeID, EmployeeID, FiscalYearID, TimeClassID, UnitTypeID, 3, Month01, Month02, Month03, Month04, Month05, Month06, Month07, Month08, Month09, Month10, Month11, Month12, @higuid, -100) + WHEN + MATCHED + AND + ( + TARGET.Month01<>SOURCE.Month01 + OR TARGET.Month02<>SOURCE.Month02 + OR TARGET.Month03<>SOURCE.Month03 + OR TARGET.Month04<>SOURCE.Month04 + OR TARGET.Month05<>SOURCE.Month05 + OR TARGET.Month06<>SOURCE.Month06 + OR TARGET.Month07<>SOURCE.Month07 + OR TARGET.Month08<>SOURCE.Month08 + OR TARGET.Month09<>SOURCE.Month09 + OR TARGET.Month10<>SOURCE.Month10 + OR TARGET.Month11<>SOURCE.Month11 + OR TARGET.Month12<>SOURCE.Month12 + ) + THEN + UPDATE + SET TARGET.Month01=SOURCE.Month01, + TARGET.Month02=SOURCE.Month02, + TARGET.Month03=SOURCE.Month03, + TARGET.Month04=SOURCE.Month04, + TARGET.Month05=SOURCE.Month05, + TARGET.Month06=SOURCE.Month06, + TARGET.Month07=SOURCE.Month07, + TARGET.Month08=SOURCE.Month08, + TARGET.Month09=SOURCE.Month09, + TARGET.Month10=SOURCE.Month10, + TARGET.Month11=SOURCE.Month11, + TARGET.Month12=SOURCE.Month12, + TARGET.HistoryItemGUID = @higuid, + TARGET.TransactionID = -100 + WHEN + NOT MATCHED BY SOURCE + AND TARGET.TransactionID = -100 + THEN DELETE + ; -- end merge + ; -- end with + +-------------------------------------------------------------------------------------------------- +-- Invalidate department models +-------------------------------------------------------------------------------------------------- + +--disable cache for plans + select @planRefreshList = 'PlanGUID in (''' + dbo.straggr(cast(dep.MemberGUID as nvarchar(36)), ''',''', '') + ''')' + from #DepartmentsCache dep + + if (@planRefreshList <> '') + + begin + + exec [dbo].[procInvalidateModelWorkbookCacheByWhereClause] @xplanWhereClause = @planRefreshList,@isDebugOnly = 0, @source = 'Roster Transfer' + + end +-------------------------------------------------------------------------------------------------- +-- Clean-up +-------------------------------------------------------------------------------------------------- + DROP TABLE #RosterAggregateInitial + DROP TABLE #RosterAggregate + DROP TABLE #RosterAggregateNoPCGInitial + DROP TABLE #RosterAggregateNoPayCodeGroup + DROP TABLE #Departments + DROP TABLE #DepartmentsCache + DROP TABLE #JobCodes + DROP TABLE #JobCodeDept + +END +GO + + +--------------------------------------------- + +-- ob.procSLReimbursementRefreshGrossChargesfromDeptBudgets +/************************************************************ +** Author: blewis +** Create Date: 2015-04-23 +** Description: Samples Gross Charges from Depts to Severice Line Reimbursement +** Last Modified: 2015-04-31 +** GM Release: 2015.3 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +*************************************************************/ + +CREATE PROC [ob].[procSLReimbursementRefreshGrossChargesfromDeptBudgets] +as + +DECLARE @HIGuid as Nvarchar(36) = newid() +EXEC [dbo].[procLogHistory] @username ='StrataUser' ,@desc ='procSLReimbursementRefreshGrossChargesfromDeptBudgets' ,@cnt =0 ,@higuid =@HIGuid + +--Refresh Charge Master Table +exec [clientob].[procFactChargeMasterRefresh] + +--Delete Stale Values +DELETE FROM [clientob].[FactServiceLineRevenue] +WHERE RowID IN( + SELECT + RowID + FROM [clientob].[FactServiceLineRevenue] FSLR + WHERE FSLR.PayorID=0 AND FSLR.PayorGroupID=0 AND FSLR.OBForecastDetailID=38 --GROSS CHARGES + AND NOT EXISTS(SELECT 1 FROM [clientob].[viewSLReimbursementGrossChargesByServiceLine] VGCSL WHERE + VGCSL.DataTypeID=FSLR.DataTypeID + AND VGCSL.FiscalYearID=FSLR.FiscalYearID + AND VGCSL.ModelingServiceLineID=FSLR.ModelingServiceLineID + AND VGCSL.PayorID=FSLR.PayorID + AND VGCSL.PayorGroupID=FSLR.PayorGroupID + AND VGCSL.OBForecastDetailID=FSLR.OBForecastDetailID + AND VGCSL.OBServiceLinePlanID=FSLR.OBServiceLinePlanID + AND VGCSL.TimeClassID=FSLR.TimeClassID + AND VGCSL.UnitTypeID=FSLR.UnitTypeID) + ) + +--Update Existing Values +UPDATE FSLR +SET Month01=VGCSL.Month01, + Month02=VGCSL.Month02, + Month03=VGCSL.Month03, + Month04=VGCSL.Month04, + Month05=VGCSL.Month05, + Month06=VGCSL.Month06, + Month07=VGCSL.Month07, + Month08=VGCSL.Month08, + Month09=VGCSL.Month09, + Month10=VGCSL.Month10, + Month11=VGCSL.Month11, + Month12=VGCSL.Month12 +FROM [clientob].[FactServiceLineRevenue] FSLR +INNER join [clientob].[viewSLReimbursementGrossChargesByServiceLine] VGCSL on + VGCSL.DataTypeID=FSLR.DataTypeID + AND VGCSL.FiscalYearID=FSLR.FiscalYearID + AND VGCSL.ModelingServiceLineID=FSLR.ModelingServiceLineID + AND VGCSL.PayorID=FSLR.PayorID + AND VGCSL.PayorGroupID=FSLR.PayorGroupID + AND VGCSL.OBForecastDetailID=FSLR.OBForecastDetailID + AND VGCSL.OBServiceLinePlanID=FSLR.OBServiceLinePlanID + AND VGCSL.TimeClassID=FSLR.TimeClassID + AND VGCSL.UnitTypeID=FSLR.UnitTypeID +WHERE + FSLR.Month01 <> VGCSL.Month01 OR + FSLR.Month02 <> VGCSL.Month02 OR + FSLR.Month03 <> VGCSL.Month03 OR + FSLR.Month04 <> VGCSL.Month04 OR + FSLR.Month05 <> VGCSL.Month05 OR + FSLR.Month06 <> VGCSL.Month06 OR + FSLR.Month07 <> VGCSL.Month07 OR + FSLR.Month08 <> VGCSL.Month08 OR + FSLR.Month09 <> VGCSL.Month09 OR + FSLR.Month10 <> VGCSL.Month10 OR + FSLR.Month11 <> VGCSL.Month11 OR + FSLR.Month12 <> VGCSL.Month12 + +--Insert New Rows +INSERT INTO [clientob].[FactServiceLineRevenue] +([DataTypeID], [FiscalYearID], [ModelingServiceLineID], [PayorID], [PayorGroupID], [OBForecastDetailID], [OBServiceLinePlanID], [TimeClassID], [UnitTypeID], [Month01], [Month02], [Month03], [Month04], [Month05], [Month06], [Month07], [Month08], [Month09], [Month10], [Month11], [Month12], [Yearly], [YTD], [IsDeleted], [HistoryItemGUID], [TransactionID]) + SELECT + [DataTypeID] + , [FiscalYearID] + , [ModelingServiceLineID] + , [PayorID] + , [PayorGroupID] + , [OBForecastDetailID] + , [OBServiceLinePlanID] + , [TimeClassID] + , [UnitTypeID] + , [Month01] + , [Month02] + , [Month03] + , [Month04] + , [Month05] + , [Month06] + , [Month07] + , [Month08] + , [Month09] + , [Month10] + , [Month11] + , [Month12] + , 0 as [Yearly] + , 0 AS [YTD] + , 0 AS [IsDeleted] + , @HIGuid as [HistoryItemGUID] + , 0 as [TransactionID] +FROM [clientob].[viewSLReimbursementGrossChargesByServiceLine] VGCSL + WHERE NOT( + VGCSL.Month01 = 0 AND + VGCSL.Month02 = 0 AND + VGCSL.Month03 = 0 AND + VGCSL.Month04 = 0 AND + VGCSL.Month05 = 0 AND + VGCSL.Month06 = 0 AND + VGCSL.Month07 = 0 AND + VGCSL.Month08 = 0 AND + VGCSL.Month09 = 0 AND + VGCSL.Month10 = 0 AND + VGCSL.Month11 = 0 AND + VGCSL.Month12 = 0) + AND NOT EXISTS(SELECT 1 FROM [clientob].[FactServiceLineRevenue] FSLR WHERE + VGCSL.DataTypeID=FSLR.DataTypeID + AND VGCSL.FiscalYearID=FSLR.FiscalYearID + AND VGCSL.ModelingServiceLineID=FSLR.ModelingServiceLineID + AND VGCSL.PayorID=FSLR.PayorID + AND VGCSL.PayorGroupID=FSLR.PayorGroupID + AND VGCSL.OBForecastDetailID=FSLR.OBForecastDetailID + AND VGCSL.OBServiceLinePlanID=FSLR.OBServiceLinePlanID + AND VGCSL.TimeClassID=FSLR.TimeClassID + AND VGCSL.UnitTypeID=FSLR.UnitTypeID) +GO + + +--------------------------------------------- + +-- ob.procSampleBudgetStampOffToIntTables +create PROC [ob].[procSampleBudgetStampOffToIntTables] AS +/* ************************************************************************************************************************ +** Author: Mike Schmitz +** Create Date: 2014-09-19 +** Description: Populates Budget Stamp-Off Data into the fw.int fact tables +** Last Modified: 2016-02-26 +** GM Release: 2014.4 +************************************************************************************************************************** +** Change History +************************************************************************************************************************** +** CID Date Author WI Description +** 1 2/24/15 MJS Remove PayorCode and PayorGroupCode columns from the int.factserviceline insert +** 2 2016-02-26 cbb update staffing data hours to use productive and non-productive +*************************************************************************************************************************/ + +declare @HistoryItemGUID uniqueidentifier = newid() + +declare @year int = (select Setting+1 from DBSetting where Name = 'OB_Current_Year') + +---------<<<<<<<<<<<<<<<< GL Data >>>>>>>>>>>>>>>>>>>>>>--------- +DELETE FROM int.factGL +WHERE FiscalYearID = @year and TimeClassID = 2 + +INSERT INTO [int].[FactGL] + ([DepartmentID] + ,[DepartmentCode] + ,[AccountID] + ,[AccountCode] + ,[FiscalYearID] + ,[FiscalYearCode] + ,[TimeClassID] + ,[TimeClassCode] + ,[FiscalMonthID] + ,[FiscalMonthCode] + ,[Value] + ,[IsDeleted] + ,[HistoryItemGUID]) + SELECT + dep.DepartmentID + , dep.DepartmentCode + , acc.AccountID + , acc.AccountCode + , BudgetedData.FiscalYearID + , BudgetedData.FiscalYearID as FiscalYearCode + , tc.TimeClassID + , tc.TimeClassCode + , fm.FiscalMonthID + , fm.FiscalMonthCode + , acc.inversion*Value as Value + , '0' as IsDeleted + , @HistoryItemGUID as HistoryItemGUID + FROM ( + SELECT * + FROM ( + SELECT * + FROM [clientob].[FactAccountBudgetStampOff] fac + WHERE fac.UnitTypeID = 34 --Dollars only + ) EXPORTDATA + UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT + ) BudgetedData + INNER JOIN fw.DimAccount acc on acc.AccountID = BudgetedData.AccountID + INNER JOIN ob.DimDepartmentalBudget Budget on Budget.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID + INNER JOIN fw.DimDepartment dep on dep.DepartmentID = Budget.DepartmentID + INNER JOIN fw.DimTimeClass tc on tc.TimeClassID = BudgetedData.TimeClassID + INNER JOIN fw.DimFiscalMonth fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode + WHERE BudgetedData.Value <> 0 + + +---------<<<<<<<<<<<<<<<< Department Stats Data >>>>>>>>>>>>>>>>>>>>>>--------- +DELETE FROM int.factStatistic +WHERE FiscalYearID = @year and TimeClassID = 2 + +INSERT INTO [int].[FactStatistic] + ([DepartmentID] + ,[DepartmentCode] + ,[AccountID] + ,[AccountCode] + ,[FiscalYearID] + ,[FiscalYearCode] + ,[TimeClassID] + ,[TimeClassCode] + ,[FiscalMonthID] + ,[FiscalMonthCode] + ,[Value] + ,[IsDeleted] + ,[HistoryItemGUID]) + SELECT + dep.DepartmentID + , dep.DepartmentCode + , acc.AccountID + , acc.AccountCode + , BudgetedData.FiscalYearID + , BudgetedData.FiscalYearID as FiscalYearCode + , tc.TimeClassID + , tc.TimeClassCode + , fm.FiscalMonthID + , fm.FiscalMonthCode + , acc.inversion*Value as Value + , '0' as IsDeleted + , @HistoryItemGUID as HistoryItemGUID + FROM ( + SELECT * + FROM ( + SELECT * + FROM [clientob].[FactAccountBudgetStampOff] fac + WHERE fac.UnitTypeID = 140 --Volumes only + ) EXPORTDATA + UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT + ) BudgetedData + INNER JOIN fw.DimAccount acc on acc.AccountID = BudgetedData.AccountID + INNER JOIN ob.DimDepartmentalBudget Budget on Budget.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID + INNER JOIN fw.DimDepartment dep on dep.DepartmentID = Budget.DepartmentID + INNER JOIN fw.DimTimeClass tc on tc.TimeClassID = BudgetedData.TimeClassID + INNER JOIN fw.DimFiscalMonth fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode + WHERE BudgetedData.Value <> 0 + + +---------<<<<<<<<<<<<<<<< Global Stats Data >>>>>>>>>>>>>>>>>>>>>>--------- +DELETE FROM int.FactGlobalStatistics +WHERE FiscalYearID = @year and TimeClassID = 2 + +INSERT INTO [int].[FactGlobalStatistics] ( + EntityID + , EntityCode + , DepartmentID + , DepartmentCode + , AccountID + , AccountCode + , FiscalYearID + , FiscalYearCode + , TimeClassID + , TimeClassCode + , FiscalMonthID + , FiscalMonthCode + , Value + , IsDeleted + , HistoryItemGUID + ) + SELECT + ent.EntityID + , ent.Code as 'EntityCode' + , '0' as DepartmentID + , '0' as DepartmentCode + , acc.AccountID + , acc.AccountCode + , BudgetedData.FiscalYearID + , BudgetedData.FiscalYearID as FiscalYearCode + , tc.TimeClassID + , tc.TimeClassCode + , fm.FiscalMonthID + , fm.FiscalMonthCode + , acc.inversion*Value as Value + , '0' as IsDeleted + , @HistoryItemGUID as HistoryItemGUID + FROM ( + SELECT * + FROM ( + SELECT * + FROM [clientob].[FactGlobalStatisticsBudgetStampOff] fac + ) EXPORTDATA + UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT + ) BudgetedData + INNER JOIN [ob].[DimOBGlobalStatistics] gs on gs.OBGlobalStatisticID = BudgetedData.OBGlobalStatisticID + INNER JOIN fw.DimAccount acc on acc.AccountID = GS.AccountID + INNER JOIN fw.DimDepartment dep on dep.DepartmentID = GS.DepartmentID + INNER JOIN ob.DimOBGlobalStatisticsPlan GSP on GSP.OBGlobalStatisticsPlanID = BudgetedData.OBGlobalStatisticsPlanID + INNER JOIN fw.DimEntity ent on GSP.EntityID = ent.EntityID + INNER JOIN fw.DimTimeClass tc on tc.TimeClassID = BudgetedData.TimeClassID + INNER JOIN fw.DimFiscalMonth fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode + WHERE gs.DepartmentID = 0 AND BudgetedData.Value <> 0 + + +---------<<<<<<<<<<<<<<<< Staffing Data >>>>>>>>>>>>>>>>>>>>>>--------- +DELETE FROM int.FactStaffing +WHERE FiscalYearID = @year and TimeClassID = 2 + +INSERT INTO [int].[FactStaffing] ( + DepartmentID + , DepartmentCode + , JobCodeID + , JobCode + , PayCodeID + , PayCode + , FiscalYearID + , FiscalYearCode + , TimeClassID + , TimeClassCode + , UnitTypeID + , UnitType + , FiscalMonthID + , FiscalMonthCode + , Value + , IsDeleted + , HistoryItemGUID + , EmployeeID + , EmployeeCode) + SELECT + dep.DepartmentID + , dep.DepartmentCode + , jc.JobCodeID + , jc.JobCode + , pc.PayCodeID + , pc.PayCode + , BudgetedData.FiscalYearID + , BudgetedData.FiscalYearID as FiscalYearCode + , tc.TimeClassID + , tc.TimeClassCode +-- CID 2 Begin + , case + when ut.UnitTypeID = 34 + then 34 + else 51 + end as UnitTypeID + , case + when ut.Name ='Dollars' + then 'Dollars' + else 'Hours' + end as UnitType +-- CID 2 End + , fm.FiscalMonthID + , fm.FiscalMonthCode + , Value as Value + , '0' as IsDeleted + , @HistoryItemGUID as HistoryItemGUID + , '0' as EmployeeID + , '0' as EmployeeCode + FROM ( + SELECT * + FROM ( + SELECT * + FROM [clientob].[FactStaffingPCBudgetStampOff] fac + ) EXPORTDATA + UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT + ) BudgetedData + INNER JOIN [fw].[DimJobCode] jc on jc.JobCodeID = BudgetedData.JobCodeID + INNER JOIN [ob].[DimDepartmentalBudget] budget on budget.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID + INNER JOIN [fw].[DimDepartment] dep on dep.DepartmentID = budget.DepartmentID + INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode + INNER JOIN [fw].[DimPayCodeGroup] PCG ON PCG.PayCodeGroupID = BudgetedData.PayCodeGroupID + INNER JOIN [fw].[DimPayCode] pc ON pc.PayCodeID = PCG.DefaultPayCodeID + INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = BudgetedData.UnitTypeID + WHERE 1=1 + and ut.UnitTypeID IN ('34','146','148') -- CID 2 + AND BudgetedData.Value <> 0 + and PCG.PayCodeGroupID<>0 -- CID 2 + +---------<<<<<<<<<<<<<<<< CDM Data >>>>>>>>>>>>>>>>>>>>>>--------- +DELETE FROM int.FactCDM +WHERE FiscalYearID = @year and TimeClassID = 2 + +INSERT INTO [int].[FactCDM] ( + DepartmentID, + DepartmentCode, + ChargeCodeID, + ChargeCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + FiscalMonthID, + FiscalMonthCode, + PatientClassID, + PatientClassCode, + ServiceLineID, + ServiceLine, + AgeCohortID, + AgeCohort, + MedicalSurgicalID, + MedSurg, + UnitTypeID, + UnitType, + Value, + IsDeleted, + HistoryItemGUID) + SELECT + DEP.DepartmentID, + DEP.DepartmentCode, + CC.ChargeCodeID, + CC.ChargeCode, + BudgetedData.FiscalYearID, + BudgetedData.FiscalYearID AS FiscalYearCode, + TC.TimeClassID, + TC.TimeClassCode, + FM.FiscalMonthID, + FM.FiscalMonthCode, + PAT.PatientClassID, + PAT.Code as 'PatientClassCode', + '0' as ServiceLineID, + '' as ServiceLine, + '0' as AgeCohortID, + '' as AgeCohort, + '0' as MedicalSurgicalID, + '' as MedSurg, + UT.UnitTypeID, + UT.Name as 'UnitType', + Value + ,'0' as IsDeleted + ,@HistoryItemGUID as HistoryItemGUID + FROM ( + SELECT * + FROM ( + SELECT * + FROM [clientob].[FactCDMBudgetStampOff] fac + ) EXPORTDATA + UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT + ) BudgetedData + INNER JOIN [fw].[DimChargeCode] CC on CC.ChargeCodeID = BudgetedData.ChargeCodeID + INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = BudgetedData.PatientClassID + INNER JOIN [ob].[DimDepartmentalBudget] Budget on Budget.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID + INNER JOIN [fw].[DimDepartment] dep on dep.DepartmentID = Budget.DepartmentID + INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode + INNER JOIN [fw].[DimUnitType] UT ON UT.UnitTypeID = BudgetedData.UnitTypeID + WHERE BudgetedData.Value <> 0 + + +---------<<<<<<<<<<<<<<<< Service Line Data >>>>>>>>>>>>>>>>>>>>>>--------- +DELETE FROM int.FactServiceLine +WHERE FiscalYearID = @year and TimeClassID = 2 + +INSERT INTO [int].[FactServiceLine] ( + EntityID, + EntityCode, + PatientClassID, + PatientClassCode, + ServiceLineID, + ServiceLine, + AgeCohortID, + AgeCohort, + MedicalSurgicalID, + MedSurg, + PayorID, + PayorGroupID, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + FiscalMonthID, + FiscalMonthCode, + OBForecastDetailID, + ForecastDetail, + Value, + IsDeleted, + HistoryItemGUID) + SELECT + E.EntityID, + E.Code as 'EntityCode', + PAT.PatientClassID, + PAT.Code as 'PatientClassCode', + SL.ServiceLineID, + SL.Code as 'ServiceLineCode', + AGE.AgeCohortID, + AGE.Code as 'AgeCohort', + MED.MedicalSurgicalID, + MED.Code as 'MedSurg', + PAY.PayorID, + PAYG.PayorGroupID, + BudgetedData.FiscalYearID, + BudgetedData.FiscalYearID AS FiscalYearCode, + TC.TimeClassID, + TC.TimeClassCode, + FM.FiscalMonthID, + FM.FiscalMonthCode, + FD.OBForecastDetailID, + FD.Code as 'ForecastDetail', + Value + ,'0' as IsDeleted + ,@HistoryItemGUID as HistoryItemGUID + FROM ( + SELECT * + FROM ( + SELECT * + FROM [clientob].[FactServiceLineBudgetStampOff] fac + ) EXPORTDATA + UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT + ) BudgetedData + INNER JOIN [fw].[DimModelingServiceLine] MSL on MSL.ModelingServiceLineID = BudgetedData.ModelingServiceLineID + INNER JOIN [fw].[DimServiceLine] SL ON MSL.ServiceLineID = SL.ServiceLineID + INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = MSL.PatientClassID + INNER JOIN [fw].[DimAgeCohort] AGE ON AGE.AgeCohortID = MSL.AgeCohortID + INNER JOIN [fw].[DimMedicalSurgical] MED ON MED.MedicalSurgicalID = MSL.MedicalSurgicalID + INNER JOIN [ob].[DimOBServiceLinePlan] P ON P.OBServiceLinePlanID = BudgetedData.OBServiceLinePlanID + INNER JOIN [fw].[DimEntity] E on E.EntityID = P.EntityID + INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode + INNER JOIN [ob].[DimOBForecastDetail] FD ON FD.OBForecastDetailID = BudgetedData.OBForecastDetailID + INNER JOIN [fw].[DimPayor] PAY ON PAY.PayorID=0 + INNER JOIN [fw].[DimPayorGroup] PAYG ON PAYG.PayorGroupID=0 + WHERE BudgetedData.Value <> 0 + + +---------<<<<<<<<<<<<<<<< Payor Data >>>>>>>>>>>>>>>>>>>>>>--------- +DELETE FROM int.FactOBPayor +WHERE FiscalYearID = @year and TimeClassID = 2 + +INSERT INTO [int].[FactOBPayor] ( + OBReimbursementPlanID, + ReimbursementPlan, + PatientClassID, + PatientClassCode, + PayorID, + PayorCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + FiscalMonthID, + FiscalMonthCode, + OBForecastDetailID, + OBForecastDetailCode, + CareSettingID, + CareSettingCode, + Value, + IsDeleted, + HistoryItemGUID) + SELECT + P.OBReimbursementPlanID, + P.Name as 'ReimbursementPlan', + PAT.PatientClassID, + PAT.Code as 'PatientClassCode', + PAY.PayorID, + PAY.PayorCode, + BudgetedData.FiscalYearID, + BudgetedData.FiscalYearID as 'FiscalYearCode', + TC.TimeClassID, + TC.TimeClassCode, + fm.FiscalMonthID, + fm.FiscalMonthCode, + FD.OBForecastDetailID, + FD.Code as 'OBForecastDetail', + C.CareSettingID, + C.Code as 'CareSettingCode', + Value + ,'0' as IsDeleted + ,@HistoryItemGUID as 'HistoryItemGUID' + FROM ( + SELECT * + FROM ( + SELECT * + FROM [clientob].[FactReimbursementBudgetStampOff] fac + ) EXPORTDATA + UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT + ) BudgetedData + INNER JOIN [fw].[DimPatientReimbursementGroup] PRG on PRG.PatientReimbursementGroupID = BudgetedData.PatientReimbursementGroupID + INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = PRG.PatientClassID + INNER JOIN [fw].[DimCareSetting] C ON C.CareSettingID = PRG.CareSettingID + INNER JOIN [fw].[DimPayor] PAY ON PAY.PayorID = BudgetedData.PayorID + INNER JOIN [ob].[DimOBReimbursementPlan] P ON P.OBReimbursementPlanID = BudgetedData.OBReimbursementPlanID + INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode + INNER JOIN [ob].[DimOBForecastDetail] FD ON FD.OBForecastDetailID = BudgetedData.OBForecastDetailID + WHERE BudgetedData.Value <> 0 + + +---------<<<<<<<<<<<<<<<< Payor Group Data >>>>>>>>>>>>>>>>>>>>>>--------- +DELETE FROM int.FactOBPayorGroup +WHERE FiscalYearID = @year and TimeClassID = 2 + +INSERT INTO [int].[FactOBPayorGroup] ( + OBReimbursementPlanID, + ReimbursementPlan, + PatientClassID, + PatientClassCode, + PayorGroupID, + PayorGroupCode, + FiscalYearID, + FiscalYearCode, + TimeClassID, + TimeClassCode, + FiscalMonthID, + FiscalMonthCode, + OBForecastDetailID, + OBForecastDetailCode, + CareSettingID, + CareSettingCode, + Value, + IsDeleted, + HistoryItemGUID) + SELECT + P.OBReimbursementPlanID, + P.Name as 'ReimbursementPlan', + PAT.PatientClassID, + PAT.Code as 'PatientClassCode', + PAY.PayorGroupID, + PAY.PayorGroupCode, + BudgetedData.FiscalYearID, + BudgetedData.FiscalYearID as 'FiscalYearCode', + TC.TimeClassID, + TC.TimeClassCode, + fm.FiscalMonthID, + fm.FiscalMonthCode, + FD.OBForecastDetailID, + FD.Code as 'OBForecastDetail', + C.CareSettingID, + C.Code as 'CareSettingCode', + Value + ,'0' as IsDeleted + ,@HistoryItemGUID as 'HistoryItemGUID' + FROM ( + SELECT * + FROM ( + SELECT * + FROM [clientob].[FactReimbursementBudgetStampOff] fac + ) EXPORTDATA + UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT + ) BudgetedData + INNER JOIN [fw].[DimPatientReimbursementGroup] PRG on PRG.PatientReimbursementGroupID = BudgetedData.PatientReimbursementGroupID + INNER JOIN [fw].[DimPatientClass] PAT ON PAT.PatientClassID = PRG.PatientClassID + INNER JOIN [fw].[DimCareSetting] C ON C.CareSettingID = PRG.CareSettingID + INNER JOIN [fw].[DimPayorGroup] PAY ON PAY.PayorGroupID = BudgetedData.PayorGroupID + INNER JOIN [ob].[DimOBReimbursementPlan] P ON P.OBReimbursementPlanID = BudgetedData.OBReimbursementPlanID + INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode + INNER JOIN [ob].[DimOBForecastDetail] FD ON FD.OBForecastDetailID = BudgetedData.OBForecastDetailID + WHERE BudgetedData.Value <> 0 + + +---------<<<<<<<<<<<<<<<< Provider Data >>>>>>>>>>>>>>>>>>>>>>--------- +DELETE FROM int.FactImportProvider +WHERE FiscalYearID = @year and TimeClassID = 2 + +INSERT INTO [int].[FactImportProvider] ( + DepartmentID + , DepartmentCode + , ProviderID + , ProviderCode + , FiscalYearID + , FiscalYearCode + , TimeClassID + , TimeClassCode + , FiscalMonthID + , FiscalMonthCode + , OBForecastDetailID + , AccountRollup + , Value + , IsDeleted + , HistoryItemGUID + ) + SELECT + D.DepartmentID + , D.DepartmentCode + , PRO.ProviderID + , PRO.ProviderCode + , BudgetedData.FiscalYearID + , BudgetedData.FiscalYearID as 'FiscalYearCode' + , TC.TimeClassID + , TC.TimeClassCode + , FM.FiscalMonthID + , FM.FiscalMonthCode + , FD.OBForecastDetailID + , FD.Name as 'AccountRollup' + , Value + ,'0' as IsDeleted + ,@HistoryItemGUID as 'HistoryItemGUID' + FROM ( + SELECT * + FROM ( + SELECT * + FROM [clientob].[FactProviderBudgetStampOff] fac + ) EXPORTDATA + UNPIVOT (Value for FiscalMonthCode in ([Month01],[Month02],[Month03],[Month04],[Month05],[Month06],[Month07],[Month08],[Month09],[Month10],[Month11],[Month12])) AS PVT + ) BudgetedData + INNER JOIN [fw].[DimProvider] PRO ON PRO.ProviderID = BudgetedData.ProviderID + INNER JOIN [ob].[DimDepartmentalBudget] P ON P.DepartmentalBudgetID = BudgetedData.DepartmentalBudgetID + INNER JOIN [fw].[DimDepartment] D ON D.DepartmentID = P.DepartmentID + INNER JOIN [fw].[DimTimeClass] tc on tc.TimeClassID = BudgetedData.TimeClassID + INNER JOIN [fw].[DimFiscalMonth] fm on fm.MonthColumnName = BudgetedData.FiscalMonthCode + INNER JOIN [ob].[DimOBForecastDetail] FD ON FD.OBForecastDetailID = BudgetedData.OBForecastDetailID + WHERE BudgetedData.Value <> 0 + +exec procLogScript 'Sample Budget Stamp-Off to int tables' , @HistoryItemGUID output +GO + + +--------------------------------------------- + +-- ob.procSampleOBSLReimbursementandRunFillins +Create Proc [ob].[procSampleOBSLReimbursementandRunFillins] as +/************************************************************ +** Author: Bart Lewis +** Create Date: 2015-06-17 +** Description: Sample and Run fillins for OB SL Reimbursement Model +** Last Modified: 2015-06-17 +** GM Release: 2015.3 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 +*************************************************************/ + +exec [ob].[procSampleOBServiceLineRevenue] @PlanGUIDlist ='' +exec [ob].[procSampleServiceLineGLDeductionsCharityBadDebt] +exec [dbo].[procTERefreshFillins] @planTypeGUID ='957dd809-6299-4ec2-81fc-5452df805e8e' ,@modelTemplateGUID ='f50d79a2-d0b8-4d31-8bc0-1350ea81c46a' ,@placeholderSectionGUIDList ='' ,@IsDebugOnly = 0; +GO + + +--------------------------------------------- + +-- ob.procSampleOBServiceLineRevenue +/************************************************************ +** Author: Bart Lewis +** Create Date: 11/18/2014 +** Description: Rolling Service Line Revenue Sampling Proc +** Last Modified: 11/18/2014 +** GM Release: 2015.2.1 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** +** +*************************************************************/ + +CREATE proc [ob].[procSampleOBServiceLineRevenue] +@PlanGUIDlist as nvarchar(max) +as + +--declare @PlanGUIDlist as nvarchar(max) +declare @isBackingUp bit +declare @isUpdatingExisting bit +declare @isClearingEntireTarget bit +declare @isInsertingNew bit +declare @isShowingAggResult bit +declare @isShowingSampleData bit +declare @targetTableName varchar(64) +declare @isClearingTempTables bit +declare @isViewingTarget bit +declare @isDisablingTriggers bit +declare @isInvalidatingModelWorkbookCache bit + +--set @PlanGUIDlist ='00000000-0000-0000-0000-000000000000' +set @isViewingTarget =0 +set @isShowingSampleData = 0 +set @isClearingEntireTarget = 1 -- Custom Delete +set @isBackingUp = 1 +set @isShowingAggResult = 0 +set @isInsertingNew = 1 +set @isUpdatingExisting = 1 +set @targetTableName = 'clientob.FactServiceLineRevenue' +set @isClearingTempTables = 1 +set @isDisablingTriggers = 1 -- prevent history item entry creation +set @isInvalidatingModelWorkbookCache = 1 + + +declare @backupTableName varchar(1000) +set @backupTableName = 'temptablebackups.dbo.' + REPLACE(REPLACE(cast(DB_NAME() as varchar(32)),'.','_'),' ','_') + '_' + REPLACE(@targetTableName,'.','_') + cast(year(getdate()) as varchar(4)) + '_' + cast(month(getdate()) as varchar(4)) + '_' + cast(day(getdate()) as varchar(4)) + '_' + datename(hh,getdate()) + '_' + datename(mi,getdate()) + '_' + datename(ss,getdate()) + '_' + datename(ms,getdate()) + '_' + datename(ns,getdate()) + + +--****************************************************************************************** +--****************************************************************************************** +-- Logging +--******************************************************************************************* +--******************************************************************************************* +declare @higuid uniqueidentifier +declare @desc nvarchar(4000) + +set @desc = 'Sampling into ' + @targetTableName +set @desc = @desc + ', Inserting=' + cast(@isInsertingNew as varchar(1)) +set @desc = @desc + ', Clearing=' + cast(@isClearingEntireTarget as varchar(1)) +set @desc = @desc + ', Updating=' + cast(@isUpdatingExisting as varchar(1)) +set @desc = @desc + ', BackingUp=' + cast(@isBackingUp as varchar(1)) +set @desc = @desc + ', BackupTable=' + @backupTableName +print @desc +exec procLogScript @desc , @higuid output +print 'Beginning sample, historyguid: ' + cast(@higuid as varchar(36)) + + IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'Temptable') AND type = (N'U')) + drop table TempTable + + if (@PlanGUIDlist='00000000-0000-0000-0000-000000000000' OR @PlanGUIDlist='') + begin + select + MemberGUID, + OBServiceLinePlanID + into TempTable + from + [ob].[DimOBServiceLinePlan] + end + else + begin + select + MemberGUID, + OBServiceLinePlanID + into TempTable + from + [ob].[DimOBServiceLinePlan] where MemberGUID in (select c.guid from dbo.ConvertCSGuidsToTable(@planGUIDList, ',') c) + end + + +--****************************************************************************************** +--****************************************************************************************** +print 'Sampling to temp table...' +--******************************************************************************************* +--******************************************************************************************* + + SELECT --~FQ_TOP~ + source.DataTypeID + , source.FiscalYearID + , source.ModelingServiceLineID + , source.PayorID + , source.PayorGroupID + , source.OBForecastDetailID + , source.OBServiceLinePlanID + , source.TimeClassID + , source.UnitTypeID + , source.Month01 + , source.Month02 + , source.Month03 + , source.Month04 + , source.Month05 + , source.Month06 + , source.Month07 + , source.Month08 + , source.Month09 + , source.Month10 + , source.Month11 + , source.Month12 + into #SampleData + FROM + [ob].[viewSamplingOBServiceLineRevenueFromFactFinancialServiceLineRevenue] source + WHERE + not( + source.Month01 = 0 and + source.Month02 = 0 and + source.Month03 = 0 and + source.Month04 = 0 and + source.Month05 = 0 and + source.Month06 = 0 and + source.Month07 = 0 and + source.Month08 = 0 and + source.Month09 = 0 and + source.Month10 = 0 and + source.Month11 = 0 and + source.Month12 = 0) + and source.OBServiceLinePlanID <> 0 + and source.OBServiceLinePlanID in (select t.OBServiceLinePlanID from TempTable t) + ----~SourceFilter~ + + + + + + if @isShowingSampleData = 1 begin + --****************************************************************************************** + --****************************************************************************************** + print 'Showing Sample Data...' + --******************************************************************************************* + --******************************************************************************************* + + select top 100 * from #Sampledata + end + + if @isBackingUp = 1 begin + --****************************************************************************************** + --****************************************************************************************** + print 'Backing up target table...' + --******************************************************************************************* + --******************************************************************************************* + + declare @sql varchar(max) + set @sql = 'select * into ' + @backupTableName + ' from ' + @targetTableName + exec (@sql) + end + + + if @isDisablingTriggers = 1 begin + + declare @sql2 varchar(max) + set @sql2 = 'ALTER TABLE '+ @targetTableName + ' DISABLE TRIGGER ALL' + exec (@sql2) + + end + + + begin tran + print 'Transaction Started' + + + if @isClearingEntireTarget = 1 begin + --****************************************************************************************** + --****************************************************************************************** + print 'Clearing entire target...' + --******************************************************************************************* + --******************************************************************************************* + delete + --BEGIN TARGET TABLE NAME + --select * + from [clientob].[FactServiceLineRevenue] + --END TARGET TABLE NAME + where + ROWID in (select la.ROWID from [clientob].[FactServiceLineRevenue] la + inner join [ob].[DimOBServiceLinePlan] lrp on la.OBServiceLinePlanID=lrp.OBServiceLinePlanID --and lrp.IsDeleted=0 + where --la.FiscalYearID = Coalesce(@TargetedYearID, FiscalYearID) And la.TimeClassID= Coalesce(@TargetedTimeclassID, TimeClassID) and + la.OBServiceLinePlanID in (select t.OBServiceLinePlanID from TempTable t) + and la.DataTypeid=4--'Input' + ) + + + + if @@error <> 0 begin + print 'Transaction Rolled Back' + rollback + return + end + end + + + + --****************************************************************************************** + --****************************************************************************************** + print 'Aggregating to mapping key level...' + --******************************************************************************************* + --******************************************************************************************* + + select + + --BEGIN INSERT TARGET KEY COLUMNS HERE + DataTypeID + , FiscalYearID + , ModelingServiceLineID + , PayorID + , PayorGroupID + , OBForecastDetailID + , OBServiceLinePlanID + , TimeClassID + , UnitTypeID + --END INSERT TARGET KEY COLUMNS HERE + + --BEGIN INSERT TARGET VALUE COLUMNS HERE + , SUM(Month01) as Month01 + , SUM(Month02) as Month02 + , SUM(Month03) as Month03 + , SUM(Month04) as Month04 + , SUM(Month05) as Month05 + , SUM(Month06) as Month06 + , SUM(Month07) as Month07 + , SUM(Month08) as Month08 + , SUM(Month09) as Month09 + , SUM(Month10) as Month10 + , SUM(Month11) as Month11 + , SUM(Month12) as Month12 + --END INSERT TARGET VALUE COLUMNS HERE + + , @higuid as HistoryItemGUID + into #AggSampleData + from + #SampleData + group by + --INSERT TARGET COLUMNS HERE + DataTypeID + , FiscalYearID + , ModelingServiceLineID + , PayorID + , PayorGroupID + , OBForecastDetailID + , OBServiceLinePlanID + , TimeClassID + , UnitTypeID + --END INSERT TARGET COLUMNS HERE + + + if @@error <> 0 begin + print 'Transaction Rolled Back' + rollback + return + end + + if @isShowingAggResult = 1 begin + --****************************************************************************************** + --****************************************************************************************** + print 'Showing agg result' + --******************************************************************************************* + --******************************************************************************************* + select top 100 * from #AggSampleData + end + + + if @isUpdatingExisting =1 begin + --****************************************************************************************** + --****************************************************************************************** + print 'Updating existing rows...' + --******************************************************************************************* + --******************************************************************************************* + update + targt + set + --BEGIN UPDATE TARGET VALUE COLUMNS + targt.Month01 = source.Month01, + targt.Month02 = source.Month02, + targt.Month03 = source.Month03, + targt.Month04 = source.Month04, + targt.Month05 = source.Month05, + targt.Month06 = source.Month06, + targt.Month07 = source.Month07, + targt.Month08 = source.Month08, + targt.Month09 = source.Month09, + targt.Month10 = source.Month10, + targt.Month11 = source.Month11, + targt.Month12 = source.Month12, + --END UPDATE TARGET VALUE COLUMNS + + targt.historyitemguid = source.historyitemguid + from + #AggSampleData source + inner join [clientob].[FactServiceLineRevenue] targt on + targt.OBServiceLinePlanID = source.OBServiceLinePlanID + and targt.DataTypeID = source.DataTypeID + and targt.ModelingServiceLineID = source.ModelingServiceLineID + and targt.OBForecastDetailID = source.OBForecastDetailID + and targt.PayorGroupID = source.PayorGroupID + and targt.PayorID = source.PayorID + and targt.UnitTypeID = source.UnitTypeID + and targt.TimeClassID = source.TimeClassID + and targt.FiscalYearID = source.FiscalYearID + where + targt.Month01 <> source.Month01 and + targt.Month02 <> source.Month02 and + targt.Month03 <> source.Month03 and + targt.Month04 <> source.Month04 and + targt.Month05 <> source.Month05 and + targt.Month06 <> source.Month06 and + targt.Month07 <> source.Month07 and + targt.Month08 <> source.Month08 and + targt.Month09 <> source.Month09 and + targt.Month10 <> source.Month10 and + targt.Month11 <> source.Month11 and + targt.Month12 <> source.Month12 + + if @@error <> 0 begin + print 'Transaction Rolled Back' + rollback + return + end + end + + if @isInsertingNew = 1 begin + --****************************************************************************************** + --****************************************************************************************** + print 'Inserting missing rows...' + --******************************************************************************************* + --******************************************************************************************* + + insert into [clientob].[FactServiceLineRevenue] + ( + --BEGIN INSERT TARGET KEY COLUMNS HERE + DataTypeID + , FiscalYearID + , ModelingServiceLineID + , PayorID + , PayorGroupID + , OBForecastDetailID + , OBServiceLinePlanID + , TimeClassID + , UnitTypeID + --END INSERT TARGET KEY COLUMNS HERE + + --BEGIN INSERT TARGET VALUE COLUMNS HERE + , Month01 + , Month02 + , Month03 + , Month04 + , Month05 + , Month06 + , Month07 + , Month08 + , Month09 + , Month10 + , Month11 + , Month12 + --END INSERT TARGET VALUE COLUMNS HERE + + , HistoryItemGUID + ) + select + --BEGIN INSERT TARGET KEY COLUMNS HERE + DataTypeID + , FiscalYearID + , ModelingServiceLineID + , PayorID + , PayorGroupID + , OBForecastDetailID + , OBServiceLinePlanID + , TimeClassID + , UnitTypeID + --END INSERT TARGET KEY COLUMNS HERE + + --BEGIN INSERT TARGET VALUE COLUMNS HERE + , Month01 + , Month02 + , Month03 + , Month04 + , Month05 + , Month06 + , Month07 + , Month08 + , Month09 + , Month10 + , Month11 + , Month12 + --END INSERT TARGET VALUE COLUMNS HERE + + , HistoryItemGUID + from + #AggSampleData source + where not exists ( + select 1 from + [clientob].[FactServiceLineRevenue] targt + where + targt.OBServiceLinePlanID = source.OBServiceLinePlanID + and targt.DataTypeID = source.DataTypeID + and targt.ModelingServiceLineID = source.ModelingServiceLineID + and targt.OBForecastDetailID = source.OBForecastDetailID + and targt.PayorGroupID = source.PayorGroupID + and targt.PayorID = source.PayorID + and targt.UnitTypeID = source.UnitTypeID + and targt.TimeClassID = source.TimeClassID + and targt.FiscalYearID = source.FiscalYearID) + + if @@error <> 0 begin + print 'Transaction Rolled Back' + rollback + return + end + + end + + --Drop temp Table + drop table TempTable + + --Delete bad rows? + if @@error = 0 begin + print 'Transaction Committed' + commit + end + else begin + print 'Transaction Rolled Back' + rollback + end + + + + if @isDisablingTriggers = 1 begin + + set @sql2 = 'ALTER TABLE '+ @targetTableName + ' ENABLE TRIGGER ALL' + exec (@sql2) + + end + + + if @isClearingTempTables = 1 begin + --****************************************************************************************** + --****************************************************************************************** + print 'Clearing temp tables...' + --******************************************************************************************* + --******************************************************************************************* + + drop table #SampleData + drop table #AggSampleData + end + + if @isViewingTarget = 1 begin + select top 100 * from [clientob].[FactServiceLineRevenue] where Month01 <> 0 and Month02 <> 0 and Month03 <> 0 and Month04 <> 0 and + Month05 <> 0 and Month06 <> 0 and Month07 <> 0 and Month08 <> 0 and + Month09 <> 0 and Month10 <> 0 and Month11 <> 0 and Month12 <> 0 and + Yearly<>0 + end + + if @isInvalidatingModelWorkbookCache = 1 + begin + if (@PlanGUIDlist='00000000-0000-0000-0000-000000000000') + begin + exec [dbo].[procInvalidateModelWorkbookCacheByPlanType] '957dd809-6299-4ec2-81fc-5452df805e8e', 'OB procSampleFactServiceLineRevenueMonthly' + end else begin + declare @invalidateWhere nvarchar(max) + set @invalidateWhere = 'PlanGUID in(select guid from dbo.ConvertCSGuidsToTable(''' + @PlanGUIDList + ''','',''))' + exec [dbo].[procInvalidateModelWorkbookCacheByWhereClause] @invalidateWhere, 0, 'OB procSampleFactServiceLineRevenueMonthly' + end + end + +RETURN +GO + + +--------------------------------------------- + +-- ob.procSampleServiceLineGLDeductionsCharityBadDebt +/************************************************************ +** Author: blewis +** Create Date: 2015-05-20 +** Description: Samples Charity and Bad Debt Data for SL Reimbursement +** Last Modified: 2015-05-20 +** GM Release: 2015-05-20 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 +** 2 +*************************************************************/ + +CREATE proc [ob].[procSampleServiceLineGLDeductionsCharityBadDebt] +as + +-- Logging ************************************************************************ +declare @higuid uniqueidentifier +exec procLogScript 'Sampling Charity and Bad Debt into clientob.FactServiceLineAccount' , @higuid output +print 'Beginning sample, historyguid: ' + cast(@higuid as varchar(36)) + +-- Backup ************************************************************************ +declare @dbname nvarchar(1000) = (DB_Name()) +exec TempTableBackups.dbo.procBackupTable @dbname, 'FactServiceLineAccount', 'clientob' + +-- Temp table ************************************************************************ +select d.OBServiceLinePlanID, + 34 as UnitTypeID, + f.TimeClassID, + 4 as DataTypeID, + f.FiscalYearID, + f.AccountID, + SUM(f.ValueMonth01 * a.Inversion) as Month01, + SUM(f.ValueMonth02 * a.Inversion) as Month02, + SUM(f.ValueMonth03 * a.Inversion) as Month03, + SUM(f.ValueMonth04 * a.Inversion) as Month04, + sum(f.ValueMonth05 * a.Inversion) as Month05, + SUM(f.ValueMonth06 * a.Inversion) as Month06, + SUM(f.ValueMonth07 * a.Inversion) as Month07, + SUM(f.ValueMonth08 * a.Inversion) as Month08, + SUM(f.ValueMonth09 * a.Inversion) as Month09, + SUM(f.ValueMonth10 * a.Inversion) as Month10, + sum(f.ValueMonth11 * a.Inversion) as Month11, + sum(f.ValueMonth12 * a.Inversion) as Month12, + SUM(f.ValueYearly * a.Inversion) as Yearly + into #SampleData +from [int].[viewFactGLPivoted] f + inner join [ob].[DimDepartmentalBudget] db on f.DepartmentID=db.DepartmentID + inner join [fw].[DimDepartment] d on d.DepartmentID=db.DepartmentID and OBServiceLinePlanID<>0 + inner join [fw].[DimAccount] a on a.AccountID=f.AccountID +where + f.FiscalYearID>=(select Setting-1 from [dbo].[DBSetting] where Name='OB_Current_Year') and + a.PatientClassID IN(Select distinct PatientClassID from [fw].[DimModelingServiceLine] where PatientClassID<>0) and + a.OBAccountPHID in + ( + 4, --Deductions + 484, --Deductions - Charity and Bad Debt + 481 --Deductions - Reimbursement + ) +group by + d.OBServiceLinePlanID + ,f.TimeClassID + ,f.FiscalYearID + ,f.AccountID + +-- Remove old data ************************************************************************ + + delete fct + from + [clientob].[FactServiceLineAccount] fct + inner join [ob].[DimOBServiceLinePlan] pln on fct.OBServiceLinePlanID=pln.OBServiceLinePlanID + inner join [data].[ScoreFillin_Account] sf on pln.MemberGUID=sf.ModelGUID + where + DataTypeID = (select DataTypeID from fw.DimDataType where globalid='Input') + and + sf.AccountPHID in + ( + 4, --Deductions + 484, --Deductions - Charity and Bad Debt + 481 --Deductions - Reimbursement + ) + + +-- Aggregating ************************************************************************ +declare @monthsLoaded int = clientob.getmonthsloaded() + +select + src.OBServiceLinePlanID, + src.UnitTypeID, + src.TimeClassID, + src.DataTypeID, + src.FiscalYearID, + src.AccountID, + SUM(src.Month01) as Month01, + SUM(src.Month02) as Month02, + SUM(src.Month03) as Month03, + SUM(src.Month04) as Month04, + sum(src.Month05) as Month05, + SUM(src.Month06) as Month06, + SUM(src.Month07) as Month07, + SUM(src.Month08) as Month08, + SUM(src.Month09) as Month09, + SUM(src.Month10) as Month10, + sum(src.Month11) as Month11, + sum(src.Month12) as Month12, + sum(src.Yearly) as Yearly, + @monthsLoaded as MonthsLoaded, + @higuid as HistoryItemGUID + +into #AggSampleData +from + #SampleData src +group by + src.OBServiceLinePlanID + ,src.UnitTypeID + ,src.TimeClassID + ,src.DataTypeID + ,src.FiscalYearID + ,src.AccountID + +-- Update Existing ************************************************************************ + + +update ra +set ra.Month01=cons.Month01, + ra.Month02=cons.Month02, + ra.Month03=cons.Month03, + ra.Month04=cons.Month04, + ra.Month05=cons.Month05, + ra.Month06=cons.Month06, + ra.Month07=cons.Month07, + ra.Month08=cons.Month08, + ra.Month09=cons.Month09, + ra.Month10=cons.Month10, + ra.Month11=cons.Month11, + ra.Month12=cons.Month12, + ra.Yearly=cons.Yearly, + ra.MonthsLoaded=cons.monthsloaded, + ra.historyitemguid=cons.historyitemguid +from + [clientob].[FactServiceLineAccount] ra + inner join #AggSampleData cons + ON cons.OBServiceLinePlanID=ra.OBServiceLinePlanID + and cons.UnitTypeID=ra.UnitTypeID + and cons.TimeClassID=ra.TimeClassID + and cons.DataTypeID=ra.DataTypeID + and cons.FiscalYearID=ra.FiscalYearID + and cons.AccountID=ra.AccountID + + + +-- Insert New ************************************************************************ +insert into clientob.FactServiceLineAccount( +OBServiceLinePlanID, +AccountID, +FiscalYearID, +TimeClassID, +UnitTypeID, +DataTypeID, +Month01, +Month02, +Month03, +Month04, +Month05, +Month06, +Month07, +Month08, +Month09, +Month10, +Month11, +Month12, +Yearly, +MonthsLoaded, +HistoryItemGUID +) +select +OBServiceLinePlanID, +AccountID, +FiscalYearID, +TimeClassID, +UnitTypeID, +DataTypeID, +Month01, +Month02, +Month03, +Month04, +Month05, +Month06, +Month07, +Month08, +Month09, +Month10, +Month11, +Month12, +Yearly, +MonthsLoaded, +HistoryItemGUID +from + #AggSampleData source +where not exists ( + select 1 from + clientob.FactServiceLineAccount targt + where + source.OBServiceLinePlanID=targt.OBServiceLinePlanID + and source.UnitTypeID=targt.UnitTypeID + and source.TimeClassID=targt.TimeClassID + and source.DataTypeID=targt.DataTypeID + and source.FiscalYearID=targt.FiscalYearID + and source.AccountID=targt.AccountID + + ) + + +----------------------------------------------------- +-------------------disable cache--------------------- +----------------------------------------------------- +declare @PlanTypeguid as uniqueidentifier = (select top 1 plantypeguid from PlanType where GlobalID='OB Service Line') + +exec procInvalidateModelWorkbookCacheByPlanType @PlanTypeguid, 'procSampleServiceLineGLDeductionsCharityBadDebt' + +-- Clean up +drop table #SampleData +drop table #AggSampleData +GO + + +--------------------------------------------- + +-- ob.procSendCriticalExceptionNotifications +CREATE PROC [ob].[procSendCriticalExceptionNotifications] +AS + +--@recipients_list should be a list of (;) separated e-mail addresses +Declare @recipients_list varchar(2000) = (Select Setting from [dbo].[DBSetting] where Name='OBCriticalExceptionNotificationList') + +--Only send exception notifications when budget is Open +DECLARE @IsBudgetOpen BIT = CAST(IIF(EXISTS(SELECT TOP 1 1 FROM [ob].[SystemSetting] WHERE [Name] = 'Budget Status' AND [Value] <> '0'), 1, 0) AS BIT); + +--Get DB FriendlyName +DECLARE @Client varchar(200) = (Select Setting from [dbo].[DBSetting] where Name='FORM_CLIENTNAME') + +--Get Log In URL +DECLARE @LoginURL varchar(200) = (Select Setting from [dbo].[DBSetting] where Name='GENERAL_APPURL') + +--Get Client Org Pin +DECLARE @OrgPIN NVARCHAR(4); +DECLARE @DatabaseGUID UNIQUEIDENTIFIER; +EXEC dbo.procSMCGetDatabaseGUID @ReturnVal=@DatabaseGUID OUTPUT; + +DECLARE @SMCServer NVARCHAR(4000) = (SELECT TOP 1 REPLACE(REPLACE(Setting,'[',''),']','') FROM DBSetting WHERE Name='SMC_PRIMARY_SERVER') +DECLARE @SMCDatabase NVARCHAR(4000) = (SELECT TOP 1 REPLACE(REPLACE(Setting,'[',''),']','') FROM DBSetting WHERE Name='SMC_PRIMARY_DATABASE') + +DECLARE @SMCSQL NVARCHAR(4000) = 'SELECT @OrgPIN_OUT=OrgPIN FROM [' + @SMCServer + '].[' + @SMCDatabase + '].[dbo].[viewDatabaseInfo] x WHERE x.DatabaseGUID=''' + CAST(@DatabaseGUID AS NVARCHAR(36)) + '''' +EXEC sp_executesql @SMCSQL,N'@OrgPIN_OUT NVARCHAR(4) OUTPUT',@OrgPIN_OUT=@OrgPIN OUTPUT; + + +if @recipients_list = '' + begin + print 'No recipients provided' + return; + end + +if @IsBudgetOpen = 1 + begin + + declare @bodystr varchar(max)=''; + declare @dbsubject varchar(300); + declare @exception_count int; + DECLARE @xml NVARCHAR(MAX); + + + select @exception_count=count(*) + from [ob].[FactDepartmentBudgetExceptions] e + inner join [ob].[DimOBExceptions] de on e.OBExceptionsID=de.OBExceptionsID + where + de.Severity like 'Critical%' + and Acknowledged=0 + and IsDeleted=0; + + if @exception_count>0 + begin + set @dbsubject='Alert from '+@@SERVERNAME+'.'+DB_NAME(); --set @bodystr=@bodystr+'# of Critical Exceptions = '+convert(varchar,@exception_count) + + SET @xml = CAST(( + Select Model AS 'td','',Severity AS 'td','', CountA AS 'td' + From ( + --SCRIPT for Exceptions Counts + --Dept + select 'Deparment Budget' AS 'Model',de.Severity, count(*) as CountA + from [ob].[FactDepartmentBudgetExceptions] be + inner join [ob].[DimOBExceptions] de on be.OBExceptionsID=de.OBExceptionsID + inner join [ob].[viewDimDepartmentalBudget] db on db.DepartmentalBudgetID=be.DepartmentalBudgetID and db.DepartmentalBudgetID<>0 + where be.Acknowledged=0 and IsDeleted=0 + Group by de.Severity + + UNION ALL + --Reimb + select 'Reimbursement' AS 'Model',de.Severity, count(*) as CountA + from [ob].[FactReimbursementExceptions] be + inner join [ob].[DimOBExceptions] de on be.OBExceptionsID=de.OBExceptionsID + inner join [ob].[viewDimOBReimbursementPlan] db on db.OBReimbursementPlanID=be.OBReimbursementPlanID and db.OBReimbursementPlanID<>0 + where be.Acknowledged=0 and IsDeleted=0 + Group by de.Severity + + UNION ALL + --Global Stats + select 'Global Stats' AS 'Model',de.Severity, count(*) as CountA + from [ob].[FactGlobalStatisticExceptions] be + inner join [ob].[DimOBExceptions] de on be.OBExceptionsID=de.OBExceptionsID + inner join [ob].[viewDimOBGlobalStatisticsPlan] db on db.OBGlobalStatisticsPlanID=be.OBGlobalStatisticsPlanID and db.OBGlobalStatisticsPlanID<>0 + where be.Acknowledged=0 and db.IsDeleted=0 + Group by de.Severity + + UNION ALL + --Service Line + select 'Service Line' AS 'Model',de.Severity, count(*) as CountA + from [ob].[FactServiceLineExceptions] be + inner join [ob].[DimOBExceptions] de on be.OBExceptionsID=de.OBExceptionsID + inner join [ob].[viewDimOBServiceLinePlan] db on db.OBServiceLinePlanID=be.OBServiceLinePlanID and db.OBServiceLinePlanID<>0 + where be.Acknowledged=0 and db.IsDeleted=0 + Group by de.Severity + ) SUB + FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX)) + + --Set Client Name, Org Pin, and URL + SET @bodystr =' +

' + @Client + 'Org Pin:' + @OrgPIN + '

+ Login to Database +

Exception Count by Severity

+ + + ' + + SET @bodystr = @bodystr + @xml +'
PlanType Severity Count
' + + + SET @xml = CAST(( + --SCRIPT for Critical Data Loss + Select Model AS 'td','', FullName AS 'td','', Name AS 'td','', Detail AS 'td' + from ( + --Dept + select 'Deparment Budget' AS Model,de.FullName, db.Name , be.Detail + from [ob].[FactDepartmentBudgetExceptions] be + inner join [ob].[DimOBExceptions] de on be.OBExceptionsID=de.OBExceptionsID + inner join [ob].[viewDimDepartmentalBudget] db on db.DepartmentalBudgetID=be.DepartmentalBudgetID and db.DepartmentalBudgetID<>0 + where de.Severity IN('Critical - Data Loss')and be.Acknowledged=0 and IsDeleted=0 + + UNION ALL + --Reimb + select 'Reimbursement' AS Model,de.FullName, db.Name , be.Detail + from [ob].[FactReimbursementExceptions] be + inner join [ob].[DimOBExceptions] de on be.OBExceptionsID=de.OBExceptionsID + inner join [ob].[viewDimOBReimbursementPlan] db on db.OBReimbursementPlanID=be.OBReimbursementPlanID and db.OBReimbursementPlanID<>0 + where de.Severity IN('Critical - Data Loss')and be.Acknowledged=0 and IsDeleted=0 + + UNION ALL + --Global Stats + select 'Global Stats' AS Model,de.FullName, db.Name , be.Detail + from [ob].[FactGlobalStatisticExceptions] be + inner join [ob].[DimOBExceptions] de on be.OBExceptionsID=de.OBExceptionsID + inner join [ob].[viewDimOBGlobalStatisticsPlan] db on db.OBGlobalStatisticsPlanID=be.OBGlobalStatisticsPlanID and db.OBGlobalStatisticsPlanID<>0 + where de.Severity IN('Critical - Data Loss')and be.Acknowledged=0 and DB.IsDeleted=0 + + UNION ALL + --Service Line + select 'Service Line' AS Model,de.FullName, db.Name , be.Detail + from [ob].[FactServiceLineExceptions] be + inner join [ob].[DimOBExceptions] de on be.OBExceptionsID=de.OBExceptionsID + inner join [ob].[viewDimOBServiceLinePlan] db on db.OBServiceLinePlanID=be.OBServiceLinePlanID and db.OBServiceLinePlanID<>0 + where de.Severity IN('Critical - Data Loss')and be.Acknowledged=0 and DB.IsDeleted=0 + ) SUB + FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX)) + + + SET @bodystr = @bodystr + '

Critical - Data Loss

+ + + ' + + + SET @bodystr = @bodystr + @xml +'
ModelType ExceptionType Department Detail
' + + EXEC msdb.dbo.sp_send_dbmail + @profile_name = 'DatabaseMail', + @recipients = @recipients_list, + @body = @bodystr, + @body_format ='HTML', + @subject = @dbsubject; + end +end +GO + + +--------------------------------------------- + +-- ob.procServiceLineVolumetoReimbursementSample +/************************************************************ +** Author: blewis +** Create Date: 2014-08-11 +** Description: Samples Volume from SL model to Reimbursement Model +** Last Modified: 2017-06-06 +** GM Release: 2014.4 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 9/2/2014 BJL Remove the "Output" Filter on Datatype to allow historical Data from SL +** 2 3/6/2015 GJF Skip invalidate for native modeling support +** 3 9/20/2016 GJF B-12949 Add direct call to CDM sample at end, instead of bundling this proc in the custom script +** 4 6/6/2017 SRK D-05890 Moved the proc that updates departmental budget models outside of the IF statement that is used only for Reimbursement +** 5` 10/12/2017 cbb D-06496 added paramter for cdm sampling +*************************************************************/ +CREATE proc [ob].[procServiceLineVolumetoReimbursementSample] + @planGUIDList nvarchar(max)='', + @IsCDMSampling bit = 1 +as + +-----------------------------CID 4---------------------------------------- + -- Sample CDM, which will trigger a partial refresh + if @IsCDMSampling = 1 + begin + exec [clientob].[procSampleCDMAll] @planGUIDList, 0; + end + +-----------------------------CID 4---------------------------------------- + + IF((select Max(OBServiceLinePrimaryVolumeAccountID) from [fw].[DimPatientClass]) = 0 ) Begin + return + End + + -- Temp plans ******************************************************************** + Create Table #Plans(OBServiceLinePlanID int, OBReimbursementPlanID int) + + if (len(@planGUIDList) = 0) begin + -- if no plans provided, we will sample all plans + insert into #Plans(OBServiceLinePlanID,OBReimbursementPlanID) + select OBServiceLinePlanID, OBReimbursementPlanID + from (SELECT DISTINCT + MD.OBServiceLinePlanID + , MD.OBReimbursementPlanID + , SL.MemberGUID + FROM + [fw].[DimDepartment] MD + Inner join [ob].[DimOBServiceLinePlan] SL on md.OBServiceLinePlanID=SL.OBServiceLinePlanID + WHERE MD.OBReimbursementPlanID<>0 AND MD.OBServiceLinePlanID<>0) P + end + else begin + insert into #Plans(OBServiceLinePlanID, OBReimbursementPlanID) + select + plandim.OBServiceLinePlanID + , plandim.OBReimbursementPlanID + from dbo.ConvertCSGuidsToTable(@planGUIDList, ',') planguids + inner join (SELECT DISTINCT + MD.OBServiceLinePlanID + , MD.OBReimbursementPlanID + , SL.MemberGUID + FROM + [fw].[DimDepartment] MD + Inner join [ob].[DimOBServiceLinePlan] SL on md.OBServiceLinePlanID=SL.OBServiceLinePlanID + WHERE MD.OBReimbursementPlanID<>0 AND MD.OBServiceLinePlanID<>0) plandim on planguids.guid = plandim.MemberGUID + end + + -- Logging ************************************************************************ + declare @higuid uniqueidentifier + exec procLogScript 'Sampling into clientob.FactReimbursementAccount' , @higuid output + print 'Beginning sample, historyguid: ' + cast(@higuid as varchar(36)) + + -- Backup ************************************************************************ + --declare @dbname nvarchar(1000) = (DB_Name()) + --exec TempTableBackups.dbo.procBackupTable @dbname, 'FactReimbursementAccount', 'clientob' + + -- Temp table ************************************************************************ + select + src.OBReimbursementPlanID, + src.PatientReimbursementGroupID, + src.UnitTypeID, + src.TimeClassID, + src.DataTypeID, + src.FiscalYearID, + src.AccountID, + SUM(src.Month01) as Month01, + SUM(src.Month02) as Month02, + SUM(src.Month03) as Month03, + SUM(src.Month04) as Month04, + sum(src.Month05) as Month05, + SUM(src.Month06) as Month06, + SUM(src.Month07) as Month07, + SUM(src.Month08) as Month08, + SUM(src.Month09) as Month09, + SUM(src.Month10) as Month10, + sum(src.Month11) as Month11, + sum(src.Month12) as Month12, + SUM(src.Yearly) as Yearly + into #SampleData + from ( + SELECT + map.[OBReimbursementPlanID] + , prg.PatientReimbursementGroupID + , fs.[UnitTypeID] + , fs.[TimeClassID] + , 4 as [DataTypeID] + , fs.[FiscalYearID] + , pc.[OBServiceLinePrimaryVolumeAccountID] as [AccountID] + , [Month01] + , [Month02] + , [Month03] + , [Month04] + , [Month05] + , [Month06] + , [Month07] + , [Month08] + , [Month09] + , [Month10] + , [Month11] + , [Month12] + , [Yearly] + FROM [clientob].[FactServiceLine] fs + INNER JOIN [fw].[DimModelingServiceLine] ms on fs.ModelingServiceLineID=ms.ModelingServiceLineID + INNER JOIN [ob].[DimOBServiceLinePlan] sl ON fs.OBServiceLinePlanID=sl.OBServiceLinePlanID + INNER JOIN #Plans map ON sl.OBServiceLinePlanID=map.OBServiceLinePlanID + INNER JOIN [ob].[DimOBForecastDetail] fd on fs.OBForecastDetailID=fd.OBForecastDetailID + INNER JOIN [fw].[DimPatientReimbursementGroup] prg on ms.PatientClassID=prg.PatientClassID and CareSettingID=0 + Inner Join [fw].[DimPatientClass] pc on prg.PatientClassID=pc.PatientClassID + Where + --==== BEGIN CID 1 ==== + --DataTypeID=3 and + --==== END CID 1 ==== + + prg.PatientReimbursementGroupID<>0 and pc.OBServiceLinePrimaryVolumeAccountID<>0 and fd.Name='Volume' + ) src + group by src.OBReimbursementPlanID,src.PatientReimbursementGroupID,src.UnitTypeID, + src.TimeClassID,src.DataTypeID,src.FiscalYearID,src.AccountID + + + -- Remove old data ************************************************************************ + delete fct + from + [clientob].[FactReimbursementAccount] fct + where + fct.RowID IN( + Select RowID + from + [clientob].[FactReimbursementAccount] fa + inner join #SampleData sd on fa.AccountID=sd.AccountID and fa.PatientReimbursementGroupID=sd.PatientReimbursementGroupID) + -- Aggregating ************************************************************************ + declare @monthsLoaded int = clientob.getmonthsloaded() + + select + src.OBReimbursementPlanID, + src.PatientReimbursementGroupID, + src.UnitTypeID, + src.TimeClassID, + src.DataTypeID, + src.FiscalYearID, + src.AccountID, + SUM(src.Month01) as Month01, + SUM(src.Month02) as Month02, + SUM(src.Month03) as Month03, + SUM(src.Month04) as Month04, + sum(src.Month05) as Month05, + SUM(src.Month06) as Month06, + SUM(src.Month07) as Month07, + SUM(src.Month08) as Month08, + SUM(src.Month09) as Month09, + SUM(src.Month10) as Month10, + sum(src.Month11) as Month11, + sum(src.Month12) as Month12, + sum(src.Yearly) as Yearly, + @monthsLoaded as MonthsLoaded, + @higuid as HistoryItemGUID + into #AggSampleData + from + #SampleData src + group by src.OBReimbursementPlanID,src.PatientReimbursementGroupID,src.UnitTypeID, + src.TimeClassID,src.DataTypeID,src.FiscalYearID,src.AccountID + + + + + -- Insert New ************************************************************************ + insert into clientob.FactReimbursementAccount( + OBReimbursementPlanID, + AccountID, + FiscalYearID, + PatientReimbursementGroupID, + TimeClassID, + UnitTypeID, + DataTypeID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + Yearly, + MonthsLoaded, + HistoryItemGUID + ) + select + OBReimbursementPlanID, + AccountID, + FiscalYearID, + PatientReimbursementGroupID, + TimeClassID, + UnitTypeID, + DataTypeID, + Month01, + Month02, + Month03, + Month04, + Month05, + Month06, + Month07, + Month08, + Month09, + Month10, + Month11, + Month12, + Yearly, + MonthsLoaded, + HistoryItemGUID + from + #AggSampleData source + where not exists ( + select 1 from + clientob.FactReimbursementAccount targt + where + source.OBReimbursementPlanID=targt.OBReimbursementPlanID + and source.PatientReimbursementGroupID=targt.PatientReimbursementGroupID + and source.UnitTypeID=targt.UnitTypeID + and source.TimeClassID=targt.TimeClassID + and source.DataTypeID=targt.DataTypeID + and source.FiscalYearID=targt.FiscalYearID + and source.AccountID=targt.AccountID + + ) + + -- Clean up + drop table #SampleData + drop table #AggSampleData + Drop table #Plans +GO + + +--------------------------------------------- + +-- ob.procTERefreshFillins_DepartmentalBudgetAll +create proc ob.procTERefreshFillins_DepartmentalBudgetAll + @isDeleting bit = 0 +as + if (@isDeleting = 1) begin + --delete existing fillins + declare @deleteWhere nvarchar(max) + select @deleteWhere = 'ModelGUID in(select x.PlanGUID from dbo.XPlan x where x.PlanTypeGUID = ''' + cast(PlanTypeGUID as nvarchar(36)) + ''' and x.IsDeletedPlan = 0)' from [dbo].[PlanType] where GlobalID = 'OB Departmental Budget' + declare @deleteCount int + select @deleteCount = count(*) from [dbo].[ScoreFillin] where ModelGUID in(select x.PlanGUID from dbo.XPlan x inner join dbo.PlanType pt on pt.PlanTypeGUID = x.PlanTypeGUID where pt.GlobalID = 'OB Departmental Budget' and x.IsDeletedPlan = 0) + print 'Deleting...' + exec [dbo].[procRollingDeleteOnTable] 'dbo', 'ScoreFillin', 'RowID', '[dbo].[ScoreFillin]', @deleteWhere, @deleteCount, 1, 0 + exec [dbo].[procScoreFillinTableRebuildAll] + print 'Delete complete.' + end + + --chunk refresh by plan + declare @planguid uniqueidentifier + select top 1 @planguid = x.PlanGUID from dbo.XPlan x inner join dbo.PlanType pt on pt.PlanTypeGUID = x.PlanTypeGUID where pt.GlobalID = 'OB Departmental Budget' and x.IsDeletedPlan = 0 + insert into [dbo].[FillinRefreshRequest] (PlanGUID) select x.PlanGUID from dbo.XPlan x inner join dbo.PlanType pt on pt.PlanTypeGUID = x.PlanTypeGUID where pt.GlobalID = 'OB Departmental Budget' and x.IsDeletedPlan = 0 and x.PlanGUID != @planguid + exec [dbo].[procTERefreshFillinsByPlan] @planguid, '', 0 + print 'Task created.' +GO + + +--------------------------------------------- + +-- ob.procUpdateMonthsLoaded +CREATE proc ob.procUpdateMonthsLoaded as +/************************************************************ +** Author: akowalski +** Create Date: 2014-04-10 +** Description: Updates months data loaded on all dimensions and composite tables +** Last Modified: 2015-02-05 +** GM Release: 2014.3 +************************************************************** +** Change History +************************************************************** +** CID Date Author WI Description +** 1 2015-02-05 akozlovskyi Excluded updating of deleted table DimOBAllocationsPlan +** +*************************************************************/ + +Declare @monthsloaded varchar(2) = cast(clientob.GetMonthsLoaded() as varchar(2)) + +-- Update plan dimensions +update [ob].[DimDepartmentalBudget] set MonthsLoaded=@monthsloaded +update [ob].[DimOBGlobalStatisticsPlan] set MonthsLoaded=@monthsloaded +update [ob].[DimOBReimbursementPlan] set MonthsLoaded=@monthsloaded +update [ob].[DimOBServiceLinePlan] set MonthsLoaded=@monthsloaded + +-- Update composites +SET NOCOUNT ON; + + DECLARE @SCHEMA nvarchar(256) + DECLARE @FactTableName nvarchar(256) + DECLARE @SQL nvarchar(1024) + DECLARE FactTableCursor CURSOR FOR + select t.name, (select name from sys.schemas where schema_id = t.schema_id) from sys.tables t where t.schema_id in(select schema_id from sys.schemas where name in('ob', 'clientob')) and (t.name like 'fact%' and t.name not like '%map') order by t.name + open FactTableCursor + + FETCH NEXT FROM FactTableCursor + INTO @FactTableName, @SCHEMA + WHILE @@FETCH_STATUS = 0 + BEGIN + + if (dbo.ColumnExists(@SCHEMA,@FactTableName,'MonthsLoaded')=1) + begin + set @SQL = 'update ' + @SCHEMA + '.' + @FactTableName + ' set MonthsLoaded=' + @monthsloaded + + --print @SQL + EXECUTE sp_executesql @SQL + end + FETCH NEXT FROM FactTableCursor INTO @FactTableName, @SCHEMA + END + + CLOSE FactTableCursor + DEALLOCATE FactTableCursor + + + +RETURN +GO + + +--------------------------------------------- + +-- ob.procUpdateOBSectionPermissions +CREATE PROCEDURE [ob].[procUpdateOBSectionPermissions] +AS +BEGIN + DECLARE @isBudgetOpen BIT = CAST(IIF(EXISTS(SELECT TOP 1 1 FROM [ob].[SystemSetting] WHERE [Name] = 'Budget Status' AND [Value] <> '0'), 1, 0) AS BIT); + DECLARE @obModuleGUID UNIQUEIDENTIFIER = '65770F68-4223-43FE-970A-D7F8D8D3931D'; + + DECLARE @rosterBudgetingCategoryGUID UNIQUEIDENTIFIER = 'DD9DE9F8-01AF-41BE-9144-4CAD060B6E64'; + DECLARE @budgetConfigurationCategoryGUID UNIQUEIDENTIFIER = '8EF0D151-FCD6-4D0F-925A-94548AF39102'; + DECLARE @featuresCategoryGUID UNIQUEIDENTIFIER = '4F18E245-FB8A-4390-AC5B-B6829543A66B'; + + DECLARE @obLocalAdminGroupGUID UNIQUEIDENTIFIER = 'F515898A-9D76-4E68-896B-22AF1AA4CB72'; + DECLARE @systemCenterMenuItemGUID UNIQUEIDENTIFIER = 'D8C2EEB8-9039-4EC6-81B9-77ABA1F87E01'; + DECLARE @systemGeneratedStatisticsGuid UNIQUEIDENTIFIER = 'F1161287-169C-41BD-B548-0A7A6414D24D'; + + + -- Hide all ob sections except 'BeginBudgetPreparation', 'CloseBudget' and categories 'Budget Configurations', 'Roster Budgeting', 'Features' + UPDATE permission + SET ReadValue = @isBudgetOpen, WriteValue = @isBudgetOpen + FROM [dbo].[S3SimplePermission] permission + INNER JOIN [dbo].[SystemCenterSection] section ON section.SectionGUID = permission.LootID + INNER JOIN [dbo].[SystemCenterCategory] category ON category.CategoryGUID = section.CategoryGUID + WHERE category.ModuleGUID = @obModuleGUID + AND category.IsMaintenanceMode = 1 + AND section.GlobalID NOT IN ('BeginBudgetPreparation', 'CloseBudget') + AND category.CategoryGUID NOT IN (@rosterBudgetingCategoryGUID, @budgetConfigurationCategoryGUID, @featuresCategoryGUID) + + --verify and update access for menu item system center button for users from OB Local Admin Group + IF EXISTS(SELECT * FROM S3SimplePermission WHERE LootID = @systemCenterMenuItemGUID AND IdentityGUID = @obLocalAdminGroupGUID) + BEGIN + IF EXISTS(SELECT * FROM S3SimplePermission WHERE LootID IN (@systemGeneratedStatisticsGuid) and IdentityGUID = @obLocalAdminGroupGUID) + UPDATE [dbo].[S3SimplePermission] + SET ReadValue = 1, WriteValue = 1 + WHERE LootID = @systemCenterMenuItemGUID AND IdentityGUID = @obLocalAdminGroupGUID + ELSE + -- Hide menu item system center button if OB Local Admin didn't have access for 'Role Assignments' or 'System Generated Statistics' sections + UPDATE [dbo].[S3SimplePermission] + SET ReadValue = @isBudgetOpen, WriteValue = @isBudgetOpen + WHERE LootID = @systemCenterMenuItemGUID AND IdentityGUID = @obLocalAdminGroupGUID + END +END +GO + + +--------------------------------------------- + +--------------------------------------------- +-- FUNCTIONS +--------------------------------------------- + diff --git a/ef-migration/infrastructure/sql-server/schemas/ob_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/schemas/ob_schema_database_statements_small.sql new file mode 100644 index 0000000..edf38ce --- /dev/null +++ b/ef-migration/infrastructure/sql-server/schemas/ob_schema_database_statements_small.sql @@ -0,0 +1,24 @@ +-- SCHEMA: ob + +--------------------------------------------- +-- TABLES +--------------------------------------------- + + +--------------------------------------------- +-- ob.AccountVariabilityOverride ------------------ +--------------------------------------------- +CREATE TABLE [ob].[AccountVariabilityOverride] ( + [AccountVariabilityOverrideID] int NOT NULL, + [DepartmentAssignment] nvarchar(800) NOT NULL, + [AccountAssignment] nvarchar(800) NOT NULL, + [PrecedentOrder] int NOT NULL, + [Variability] decimal NOT NULL, + PRIMARY KEY ([AccountVariabilityOverrideID]) +); +GO +ALTER TABLE [ob].[AccountVariabilityOverride] ADD CONSTRAINT [DF__AccountVa__Depar__0EB4746A] DEFAULT ('') FOR [DepartmentAssignment]; GO +ALTER TABLE [ob].[AccountVariabilityOverride] ADD CONSTRAINT [DF__AccountVa__Accou__0FA898A3] DEFAULT ('') FOR [AccountAssignment]; GO +ALTER TABLE [ob].[AccountVariabilityOverride] ADD CONSTRAINT [DF__AccountVa__Prece__109CBCDC] DEFAULT ((0)) FOR [PrecedentOrder]; GO +ALTER TABLE [ob].[AccountVariabilityOverride] ADD CONSTRAINT [DF__AccountVa__Varia__1190E115] DEFAULT ((0)) FOR [Variability]; GO + diff --git a/ef-migration/infrastructure/sql-server/setup.sh b/ef-migration/infrastructure/sql-server/setup.sh new file mode 100644 index 0000000..e69de29 -- 2.45.2 From cf5233f0be0fb3ab5158d43570d6077461585789 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Mon, 3 Feb 2025 22:12:40 +0000 Subject: [PATCH 15/31] Include Docker Compose --- .../infrastructure/docker-compose-infra.yml | 29 +++++++++++++++++++ .../infrastructure/sql-server/Dockerfile | 26 ++++++++++------- 2 files changed, 44 insertions(+), 11 deletions(-) create mode 100644 ef-migration/infrastructure/docker-compose-infra.yml diff --git a/ef-migration/infrastructure/docker-compose-infra.yml b/ef-migration/infrastructure/docker-compose-infra.yml new file mode 100644 index 0000000..08d4307 --- /dev/null +++ b/ef-migration/infrastructure/docker-compose-infra.yml @@ -0,0 +1,29 @@ +version: '3.8' + +services: + sqlserver: + build: + context: . # Changed from ./sql-server to . to include the whole directory + dockerfile: sql-server/Dockerfile # Updated path to Dockerfile + container_name: sqlserver_lightweight + ports: + - "1433:1433" + environment: + - ACCEPT_EULA=Y + - MSSQL_PID=Express + - SA_PASSWORD=YourStrong@Passw0rd + volumes: + - sqlserver_data:/var/opt/mssql + deploy: + resources: + limits: + memory: 1G + cpus: '1.0' + reservations: + memory: 512M + cpus: '0.5' + restart: unless-stopped + +volumes: + sqlserver_data: + driver: local \ No newline at end of file diff --git a/ef-migration/infrastructure/sql-server/Dockerfile b/ef-migration/infrastructure/sql-server/Dockerfile index f87c7cf..31d84a7 100644 --- a/ef-migration/infrastructure/sql-server/Dockerfile +++ b/ef-migration/infrastructure/sql-server/Dockerfile @@ -9,18 +9,22 @@ ENV SA_PASSWORD=YourStrong@Passw0rd # Create a directory for database scripts WORKDIR /usr/src/app +# Create schemas directory +RUN mkdir -p /usr/src/app/schemas + # Copy the schema files -COPY dbo_schema_database_statements_small.sql ./schemas/ -COPY fp_schema_database_statements_small.sql ./schemas/ -COPY fw_schema_database_statements_small.sql ./schemas/ -COPY int_schema_database_statements_small.sql ./schemas/ -COPY ob_schema_database_statements_small.sql ./schemas/ +COPY sql-server/schemas/dbo_schema_database_statements_small.sql /usr/src/app/schemas/ +COPY sql-server/schemas/fp_schema_database_statements_small.sql /usr/src/app/schemas/ +COPY sql-server/schemas/fw_schema_database_statements_small.sql /usr/src/app/schemas/ +COPY sql-server/schemas/int_schema_database_statements_small.sql /usr/src/app/schemas/ +COPY sql-server/schemas/ob_schema_database_statements_small.sql /usr/src/app/schemas/ -# Create initialization script -COPY init.sql ./ +# Copy initialization script +COPY sql-server/init.sql /usr/src/app/ +COPY sql-server/setup.sh /usr/src/app/ -# Create setup script that will run the schema creation -COPY setup.sh ./ -RUN chmod +x setup.sh +# Fix line endings and make setup script executable +RUN sed -i 's/\r$//' /usr/src/app/setup.sh && \ + chmod +x /usr/src/app/setup.sh -CMD /bin/bash ./setup.sh \ No newline at end of file +CMD /bin/bash /usr/src/app/setup.sh \ No newline at end of file -- 2.45.2 From 866b4b251b3f63051916ae9360b272d513298943 Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Mon, 3 Feb 2025 20:27:28 -0500 Subject: [PATCH 16/31] remove xml max definition --- .../dbo_schema_database_statements.sql | 40 +++++++++---------- .../dbo_schema_database_statements_small.sql | 2 +- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements.sql b/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements.sql index 4734fd5..a1abf15 100644 --- a/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements.sql +++ b/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements.sql @@ -16,7 +16,7 @@ CREATE TABLE [dbo].[AMAssumptionView] ( [AssumptionJoinDataGUID] uniqueidentifier NOT NULL, [FolderGUID] uniqueidentifier NOT NULL, [IsDistributionModeActive] bit NOT NULL, - [DistributionInfo] xml(max) NOT NULL, + [DistributionInfo] xml NOT NULL, [ProviderGUID] uniqueidentifier NOT NULL, [CreatedDate] datetime NOT NULL, [CreatedBy] uniqueidentifier NOT NULL, @@ -72,7 +72,7 @@ CREATE TABLE [dbo].[AMCorrelationGroup] ( [AssumptionGroupGUID] uniqueidentifier NOT NULL, [Name] nvarchar(64) NOT NULL, [IsGlobal] bit NOT NULL, - [MembersXML] xml(max) NOT NULL, + [MembersXML] xml NOT NULL, PRIMARY KEY ([CorrelationGroupGUID]) ); GO @@ -1288,7 +1288,7 @@ ALTER TABLE [dbo].[CustomMenu] ADD CONSTRAINT [DF_CustomMenu_ISGLOBAL] DEFAULT ( CREATE TABLE [dbo].[CustomMenuContent] ( [CustomMenuContentGUID] uniqueidentifier NOT NULL, [CustomMenuGUID] uniqueidentifier NOT NULL, - [ContentXML] xml(max) NOT NULL, + [ContentXML] xml NOT NULL, PRIMARY KEY ([CustomMenuContentGUID]) ); GO @@ -2928,7 +2928,7 @@ CREATE TABLE [dbo].[EMFSubtableDefaultTuple] ( [SUBTABLEDEFAULTTUPLEGUID] uniqueidentifier NOT NULL, [SUBTABLEGUID] uniqueidentifier NOT NULL, [ISONCOLUMN] bit NOT NULL, - [DIMENSIONTUPLEXML] xml(max) NOT NULL, + [DIMENSIONTUPLEXML] xml NOT NULL, PRIMARY KEY ([SUBTABLEDEFAULTTUPLEGUID]) ); GO @@ -3707,7 +3707,7 @@ CREATE TABLE [dbo].[FEFormField] ( [RenderComparisonFieldGUID] uniqueidentifier NOT NULL, [RenderComparisonOperator] int NOT NULL, [RefreshMode] tinyint NOT NULL, - [TypeConfigXML] xml(max) NOT NULL, + [TypeConfigXML] xml NOT NULL, PRIMARY KEY ([FORMFIELDGUID]) ); @@ -3930,7 +3930,7 @@ ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_RuleGroupType CREATE TABLE [dbo].[FEFormSectionRule] ( [FormSectionRuleGUID] uniqueidentifier NOT NULL, [FormSectionGUID] uniqueidentifier NOT NULL, - [RuleXML] xml(max) NOT NULL, + [RuleXML] xml NOT NULL, [Description] nvarchar(max) NOT NULL, [RuleType] int NOT NULL, PRIMARY KEY ([FormSectionRuleGUID]) @@ -4709,7 +4709,7 @@ CREATE TABLE [dbo].[HistoryItem] ( [CATEGORY] nvarchar(64) NOT NULL, [DESCRIPTION] nvarchar(4000) NOT NULL, [USERCOMMENTS] nvarchar(256) NOT NULL, - [METAXML] xml(max) NOT NULL, + [METAXML] xml NOT NULL, [VERSION] timestamp NOT NULL, [MODIFIERUSERNAME] nvarchar(256) NOT NULL, [ITEMCOUNT] int NOT NULL, @@ -4873,7 +4873,7 @@ CREATE TABLE [dbo].[ImportCSVConfig] ( [ImportCSVConfigGUID] uniqueidentifier NOT NULL, [Name] nvarchar(64) NOT NULL, [Description] nvarchar(450) NOT NULL, - [ConfigXML] xml(max) NOT NULL, + [ConfigXML] xml NOT NULL, [TimeoutSeconds] int NOT NULL, PRIMARY KEY ([ImportCSVConfigGUID]) ); @@ -4899,7 +4899,7 @@ CREATE TABLE [dbo].[IntCapERPConnectorConfig] ( [PollFrequency] int NOT NULL, [EnvironmentType] tinyint NOT NULL, [SystemType] smallint NOT NULL, - [AdditionalDataXML] xml(max) NOT NULL, + [AdditionalDataXML] xml NOT NULL, PRIMARY KEY ([ConnectorConfigGUID]) ); GO @@ -6546,7 +6546,7 @@ CREATE TABLE [dbo].[OMZPool] ( [Name] nvarchar(64) NOT NULL, [ProviderSettingsGUID] uniqueidentifier NOT NULL, [PoolDimensionMemberGUID] uniqueidentifier NOT NULL, - [Metadata] xml(max) NOT NULL, + [Metadata] xml NOT NULL, [ApprovedFormFieldGUID] uniqueidentifier NOT NULL, [PlanTypeGUID] uniqueidentifier NOT NULL, [IsUsingFinancialReturn] bit NOT NULL, @@ -6579,7 +6579,7 @@ CREATE TABLE [dbo].[OMZProviderSettings] ( [ProviderSettingsGUID] uniqueidentifier NOT NULL, [Name] nvarchar(64) NOT NULL, [AssemblyQualifiedName] nvarchar(450) NOT NULL, - [Metadata] xml(max) NOT NULL, + [Metadata] xml NOT NULL, [ProviderAssemblyQualifiedName] nvarchar(450) NOT NULL, [PoolDimensionGUID] uniqueidentifier NOT NULL, [DefaultEvaluatorRoleGUID] uniqueidentifier NOT NULL, @@ -6614,7 +6614,7 @@ CREATE TABLE [dbo].[OMZScenario] ( [Name] nvarchar(64) NOT NULL, [Description] nvarchar(4000) NOT NULL, [PoolGUID] uniqueidentifier NOT NULL, - [Metadata] xml(max) NOT NULL, + [Metadata] xml NOT NULL, PRIMARY KEY ([ScenarioGUID]) ); GO @@ -8768,7 +8768,7 @@ CREATE TABLE [dbo].[ReportArchiveEntryDetail] ( [ReportArchiveEntryDetailGUID] uniqueidentifier NOT NULL, [ReportArchiveEntryGUID] uniqueidentifier NOT NULL, [ReportArchiveDetailAQN] nvarchar(400) NOT NULL, - [ReportArchiveDetailXML] xml(max) NOT NULL, + [ReportArchiveDetailXML] xml NOT NULL, PRIMARY KEY ([ReportArchiveEntryDetailGUID]) ); GO @@ -8830,7 +8830,7 @@ CREATE TABLE [dbo].[RuleAction] ( [RuleSetGUID] uniqueidentifier NOT NULL, [ExecutionOrder] int NOT NULL, [RuleActionTypeAQN] nvarchar(450) NOT NULL, - [RuleActionTypeConfigXML] xml(max) NOT NULL, + [RuleActionTypeConfigXML] xml NOT NULL, PRIMARY KEY ([RuleActionGUID]) ); @@ -8873,7 +8873,7 @@ CREATE TABLE [dbo].[RuleItem] ( [RuleGUID] uniqueidentifier NOT NULL, [RuleGroupGUID] uniqueidentifier NOT NULL, [RuleTypeAQN] nvarchar(450) NOT NULL, - [RuleTypeConfigXML] xml(max) NOT NULL, + [RuleTypeConfigXML] xml NOT NULL, [DisplayOrder] int NOT NULL, [Name] nvarchar(100) NOT NULL, PRIMARY KEY ([RuleGUID]) @@ -9217,7 +9217,7 @@ CREATE TABLE [dbo].[SAShockAssumptionType] ( [Name] nvarchar(100) NOT NULL, [BaseTableName] nvarchar(50) NOT NULL, [ShockTableName] nvarchar(50) NOT NULL, - [WhereClauseXML] xml(max) NOT NULL, + [WhereClauseXML] xml NOT NULL, [DisplayFormat] nvarchar(50) NOT NULL, [IsPercentage] bit NOT NULL, [FormulaColumnName] nvarchar(max) NOT NULL, @@ -11171,7 +11171,7 @@ CREATE TABLE [dbo].[ScoreTableEditorColumn] ( [Type] int NOT NULL, [PixelWidth] int NOT NULL, [DisplayOrder] int NOT NULL, - [MetaData] xml(max) NOT NULL, + [MetaData] xml NOT NULL, [DisplayName] nvarchar(450) NOT NULL, [DefaultMemberType] int NOT NULL, [IsTextWrap] bit NOT NULL, @@ -11979,7 +11979,7 @@ CREATE TABLE [dbo].[SystemCenterStep] ( [SortOrder] int NOT NULL, [SectionGUID] uniqueidentifier NOT NULL, [Name] nvarchar(200) NOT NULL, - [PropertyXML] xml(max) NOT NULL, + [PropertyXML] xml NOT NULL, [Url] nvarchar(400) NOT NULL, [GlobalID] nvarchar(100) NOT NULL, [Description] nvarchar(4000) NOT NULL, @@ -12206,7 +12206,7 @@ CREATE TABLE [dbo].[TETaskHistory] ( [TaskGUID] uniqueidentifier NOT NULL, [Name] nvarchar(450) NOT NULL, [Status] int NOT NULL, - [ContextXML] xml(max) NOT NULL, + [ContextXML] xml NOT NULL, [CreationTime] datetime NOT NULL, [StartTime] datetime NOT NULL, [LastRunTime] datetime NOT NULL, @@ -12297,7 +12297,7 @@ ALTER TABLE [dbo].[Tag] ADD CONSTRAINT [DF_Tag_Tag] DEFAULT ('') FOR [Name]; GO CREATE TABLE [dbo].[TaskProgressStatus] ( [RowID] bigint NOT NULL, [TaskGUID] uniqueidentifier NOT NULL, - [DataXML] xml(max) NOT NULL, + [DataXML] xml NOT NULL, [StartTime] datetime NOT NULL, [TaskStatus] nvarchar(100) NOT NULL, [GlobalID] nvarchar(100) NOT NULL, diff --git a/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements_small.sql index 446b5a6..eb359e5 100644 --- a/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements_small.sql +++ b/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements_small.sql @@ -16,7 +16,7 @@ CREATE TABLE [dbo].[AMAssumptionView] ( [AssumptionJoinDataGUID] uniqueidentifier NOT NULL, [FolderGUID] uniqueidentifier NOT NULL, [IsDistributionModeActive] bit NOT NULL, - [DistributionInfo] xml(max) NOT NULL, + [DistributionInfo] xml NOT NULL, [ProviderGUID] uniqueidentifier NOT NULL, [CreatedDate] datetime NOT NULL, [CreatedBy] uniqueidentifier NOT NULL, -- 2.45.2 From eb2de1ff122581b92f47f0d7132e0e65facadd9c Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Mon, 3 Feb 2025 20:38:08 -0500 Subject: [PATCH 17/31] adjust setup and init files --- .../infrastructure/sql-server/init.sql | 36 +++++++++---- .../infrastructure/sql-server/setup.sh | 52 +++++++++++++++++++ 2 files changed, 77 insertions(+), 11 deletions(-) diff --git a/ef-migration/infrastructure/sql-server/init.sql b/ef-migration/infrastructure/sql-server/init.sql index 1c752a2..c433681 100644 --- a/ef-migration/infrastructure/sql-server/init.sql +++ b/ef-migration/infrastructure/sql-server/init.sql @@ -8,23 +8,37 @@ GO USE [st-database] GO --- Create schemas if they don't exist -IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'dbo') - EXEC('CREATE SCHEMA [dbo]') -GO +-- Create schemas (excluding dbo since it already exists) +DECLARE @SQL nvarchar(max) IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'fp') - EXEC('CREATE SCHEMA [fp]') -GO +BEGIN + SET @SQL = 'CREATE SCHEMA fp AUTHORIZATION dbo' + EXEC sp_executesql @SQL + PRINT 'Created schema fp' +END IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'fw') - EXEC('CREATE SCHEMA [fw]') -GO +BEGIN + SET @SQL = 'CREATE SCHEMA fw AUTHORIZATION dbo' + EXEC sp_executesql @SQL + PRINT 'Created schema fw' +END IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'int') - EXEC('CREATE SCHEMA [int]') -GO +BEGIN + SET @SQL = 'CREATE SCHEMA int AUTHORIZATION dbo' + EXEC sp_executesql @SQL + PRINT 'Created schema int' +END IF NOT EXISTS (SELECT * FROM sys.schemas WHERE name = 'ob') - EXEC('CREATE SCHEMA [ob]') +BEGIN + SET @SQL = 'CREATE SCHEMA ob AUTHORIZATION dbo' + EXEC sp_executesql @SQL + PRINT 'Created schema ob' +END + +-- Verify schemas +SELECT name FROM sys.schemas WHERE name IN ('fp', 'fw', 'int', 'ob') GO \ No newline at end of file diff --git a/ef-migration/infrastructure/sql-server/setup.sh b/ef-migration/infrastructure/sql-server/setup.sh index e69de29..e3a732a 100644 --- a/ef-migration/infrastructure/sql-server/setup.sh +++ b/ef-migration/infrastructure/sql-server/setup.sh @@ -0,0 +1,52 @@ +#!/bin/bash + +# Start SQL Server +/opt/mssql/bin/sqlservr & + +# Wait for SQL Server to start +echo "Waiting for SQL Server to start..." +sleep 30s + +# Initialize database +for i in {1..50}; +do + sqlcmd -S localhost -U sa -P $SA_PASSWORD -Q "SELECT 1" &> /dev/null + if [ $? -eq 0 ] + then + echo "SQL Server is ready" + break + else + echo "SQL Server is not ready yet..." + sleep 1 + fi +done + +# Run the initialization script +echo "Running initialization script..." +sqlcmd -S localhost -U sa -P $SA_PASSWORD -i /usr/src/app/init.sql +if [ $? -ne 0 ]; then + echo "Error executing initialization script" + exit 1 +fi + +# Run all schema scripts in the schemas directory +echo "Running schema scripts..." +for f in /usr/src/app/schemas/*.sql +do + echo "Processing $f..." + sqlcmd -S localhost -U sa -P $SA_PASSWORD -i "$f" -b + if [ $? -ne 0 ]; then + echo "Error executing schema script $f" + exit 1 + fi + + # Verify schema creation + sqlcmd -S localhost -U sa -P $SA_PASSWORD -Q "SELECT name FROM sys.schemas WHERE name IN ('fp', 'fw', 'int', 'ob')" -h -1 +done + +echo "All scripts executed. SQL Server is ready." + +# Keep container running +while true; do + sleep 1 +done \ No newline at end of file -- 2.45.2 From 2ba65b87077062d250224d8fcf9f7730c9cbe065 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Tue, 4 Feb 2025 02:12:31 +0000 Subject: [PATCH 18/31] adjust file settings --- .../infrastructure/docker-compose-infra.yml | 22 +++++--- .../infrastructure/sql-server/Dockerfile | 52 +++++++++++-------- .../dbo_schema_database_statements.sql | 40 +++++++------- .../dbo_schema_database_statements_small.sql | 2 +- 4 files changed, 65 insertions(+), 51 deletions(-) diff --git a/ef-migration/infrastructure/docker-compose-infra.yml b/ef-migration/infrastructure/docker-compose-infra.yml index 08d4307..dc86278 100644 --- a/ef-migration/infrastructure/docker-compose-infra.yml +++ b/ef-migration/infrastructure/docker-compose-infra.yml @@ -2,10 +2,10 @@ version: '3.8' services: sqlserver: - build: - context: . # Changed from ./sql-server to . to include the whole directory - dockerfile: sql-server/Dockerfile # Updated path to Dockerfile - container_name: sqlserver_lightweight + build: + context: . + dockerfile: sql-server/Dockerfile + container_name: sql1 ports: - "1433:1433" environment: @@ -17,12 +17,18 @@ services: deploy: resources: limits: - memory: 1G - cpus: '1.0' + memory: 2G # Minimum required for SQL Server + cpus: '1.0' # Limit to 1 CPU core reservations: - memory: 512M - cpus: '0.5' + memory: 2G # Must reserve 2GB minimum for SQL Server to start + cpus: '0.25' # Reserve quarter of a CPU core restart: unless-stopped + healthcheck: + test: /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P "$$SA_PASSWORD" -Q "SELECT 1" || exit 1 + interval: 10s + timeout: 3s + retries: 10 + start_period: 10s volumes: sqlserver_data: diff --git a/ef-migration/infrastructure/sql-server/Dockerfile b/ef-migration/infrastructure/sql-server/Dockerfile index 31d84a7..6118e15 100644 --- a/ef-migration/infrastructure/sql-server/Dockerfile +++ b/ef-migration/infrastructure/sql-server/Dockerfile @@ -1,30 +1,38 @@ -# Use the lightweight SQL Server 2022 image +# Use SQL Server 2022 Express for smaller footprint FROM mcr.microsoft.com/mssql/server:2022-latest -# Set environment variables -ENV ACCEPT_EULA=Y -ENV MSSQL_PID=Express -ENV SA_PASSWORD=YourStrong@Passw0rd +# Set required environment variables +ENV ACCEPT_EULA=Y \ + MSSQL_PID=Express \ + SA_PASSWORD=YourStrong@Passw0rd \ + PATH="/opt/mssql-tools/bin:${PATH}" -# Create a directory for database scripts +# Install sqlcmd utility +USER root +RUN apt-get update && \ + apt-get install -y wget software-properties-common gnupg2 && \ + wget -qO- https://packages.microsoft.com/keys/microsoft.asc | apt-key add - && \ + add-apt-repository "$(wget -qO- https://packages.microsoft.com/config/ubuntu/20.04/mssql-server-2022.list)" && \ + apt-get update && \ + ACCEPT_EULA=Y apt-get install -y mssql-tools unixodbc-dev && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists/* + +# Create app directory and schemas subdirectory in one layer WORKDIR /usr/src/app +RUN mkdir -p schemas -# Create schemas directory -RUN mkdir -p /usr/src/app/schemas - -# Copy the schema files -COPY sql-server/schemas/dbo_schema_database_statements_small.sql /usr/src/app/schemas/ -COPY sql-server/schemas/fp_schema_database_statements_small.sql /usr/src/app/schemas/ -COPY sql-server/schemas/fw_schema_database_statements_small.sql /usr/src/app/schemas/ -COPY sql-server/schemas/int_schema_database_statements_small.sql /usr/src/app/schemas/ -COPY sql-server/schemas/ob_schema_database_statements_small.sql /usr/src/app/schemas/ - -# Copy initialization script -COPY sql-server/init.sql /usr/src/app/ -COPY sql-server/setup.sh /usr/src/app/ +# Copy all SQL files in a single layer to reduce image size +COPY ./sql-server/schemas/*.sql ./schemas/ +COPY ./sql-server/init.sql ./ +COPY ./sql-server/setup.sh ./ # Fix line endings and make setup script executable -RUN sed -i 's/\r$//' /usr/src/app/setup.sh && \ - chmod +x /usr/src/app/setup.sh +RUN sed -i 's/\r$//' setup.sh && \ + chmod +x setup.sh -CMD /bin/bash /usr/src/app/setup.sh \ No newline at end of file +# Switch back to mssql user +USER mssql + +# Start SQL Server with our setup script +CMD /bin/bash ./setup.sh \ No newline at end of file diff --git a/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements.sql b/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements.sql index 4734fd5..a1abf15 100644 --- a/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements.sql +++ b/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements.sql @@ -16,7 +16,7 @@ CREATE TABLE [dbo].[AMAssumptionView] ( [AssumptionJoinDataGUID] uniqueidentifier NOT NULL, [FolderGUID] uniqueidentifier NOT NULL, [IsDistributionModeActive] bit NOT NULL, - [DistributionInfo] xml(max) NOT NULL, + [DistributionInfo] xml NOT NULL, [ProviderGUID] uniqueidentifier NOT NULL, [CreatedDate] datetime NOT NULL, [CreatedBy] uniqueidentifier NOT NULL, @@ -72,7 +72,7 @@ CREATE TABLE [dbo].[AMCorrelationGroup] ( [AssumptionGroupGUID] uniqueidentifier NOT NULL, [Name] nvarchar(64) NOT NULL, [IsGlobal] bit NOT NULL, - [MembersXML] xml(max) NOT NULL, + [MembersXML] xml NOT NULL, PRIMARY KEY ([CorrelationGroupGUID]) ); GO @@ -1288,7 +1288,7 @@ ALTER TABLE [dbo].[CustomMenu] ADD CONSTRAINT [DF_CustomMenu_ISGLOBAL] DEFAULT ( CREATE TABLE [dbo].[CustomMenuContent] ( [CustomMenuContentGUID] uniqueidentifier NOT NULL, [CustomMenuGUID] uniqueidentifier NOT NULL, - [ContentXML] xml(max) NOT NULL, + [ContentXML] xml NOT NULL, PRIMARY KEY ([CustomMenuContentGUID]) ); GO @@ -2928,7 +2928,7 @@ CREATE TABLE [dbo].[EMFSubtableDefaultTuple] ( [SUBTABLEDEFAULTTUPLEGUID] uniqueidentifier NOT NULL, [SUBTABLEGUID] uniqueidentifier NOT NULL, [ISONCOLUMN] bit NOT NULL, - [DIMENSIONTUPLEXML] xml(max) NOT NULL, + [DIMENSIONTUPLEXML] xml NOT NULL, PRIMARY KEY ([SUBTABLEDEFAULTTUPLEGUID]) ); GO @@ -3707,7 +3707,7 @@ CREATE TABLE [dbo].[FEFormField] ( [RenderComparisonFieldGUID] uniqueidentifier NOT NULL, [RenderComparisonOperator] int NOT NULL, [RefreshMode] tinyint NOT NULL, - [TypeConfigXML] xml(max) NOT NULL, + [TypeConfigXML] xml NOT NULL, PRIMARY KEY ([FORMFIELDGUID]) ); @@ -3930,7 +3930,7 @@ ALTER TABLE [dbo].[FEFormSection] ADD CONSTRAINT [DF_FEFormSection_RuleGroupType CREATE TABLE [dbo].[FEFormSectionRule] ( [FormSectionRuleGUID] uniqueidentifier NOT NULL, [FormSectionGUID] uniqueidentifier NOT NULL, - [RuleXML] xml(max) NOT NULL, + [RuleXML] xml NOT NULL, [Description] nvarchar(max) NOT NULL, [RuleType] int NOT NULL, PRIMARY KEY ([FormSectionRuleGUID]) @@ -4709,7 +4709,7 @@ CREATE TABLE [dbo].[HistoryItem] ( [CATEGORY] nvarchar(64) NOT NULL, [DESCRIPTION] nvarchar(4000) NOT NULL, [USERCOMMENTS] nvarchar(256) NOT NULL, - [METAXML] xml(max) NOT NULL, + [METAXML] xml NOT NULL, [VERSION] timestamp NOT NULL, [MODIFIERUSERNAME] nvarchar(256) NOT NULL, [ITEMCOUNT] int NOT NULL, @@ -4873,7 +4873,7 @@ CREATE TABLE [dbo].[ImportCSVConfig] ( [ImportCSVConfigGUID] uniqueidentifier NOT NULL, [Name] nvarchar(64) NOT NULL, [Description] nvarchar(450) NOT NULL, - [ConfigXML] xml(max) NOT NULL, + [ConfigXML] xml NOT NULL, [TimeoutSeconds] int NOT NULL, PRIMARY KEY ([ImportCSVConfigGUID]) ); @@ -4899,7 +4899,7 @@ CREATE TABLE [dbo].[IntCapERPConnectorConfig] ( [PollFrequency] int NOT NULL, [EnvironmentType] tinyint NOT NULL, [SystemType] smallint NOT NULL, - [AdditionalDataXML] xml(max) NOT NULL, + [AdditionalDataXML] xml NOT NULL, PRIMARY KEY ([ConnectorConfigGUID]) ); GO @@ -6546,7 +6546,7 @@ CREATE TABLE [dbo].[OMZPool] ( [Name] nvarchar(64) NOT NULL, [ProviderSettingsGUID] uniqueidentifier NOT NULL, [PoolDimensionMemberGUID] uniqueidentifier NOT NULL, - [Metadata] xml(max) NOT NULL, + [Metadata] xml NOT NULL, [ApprovedFormFieldGUID] uniqueidentifier NOT NULL, [PlanTypeGUID] uniqueidentifier NOT NULL, [IsUsingFinancialReturn] bit NOT NULL, @@ -6579,7 +6579,7 @@ CREATE TABLE [dbo].[OMZProviderSettings] ( [ProviderSettingsGUID] uniqueidentifier NOT NULL, [Name] nvarchar(64) NOT NULL, [AssemblyQualifiedName] nvarchar(450) NOT NULL, - [Metadata] xml(max) NOT NULL, + [Metadata] xml NOT NULL, [ProviderAssemblyQualifiedName] nvarchar(450) NOT NULL, [PoolDimensionGUID] uniqueidentifier NOT NULL, [DefaultEvaluatorRoleGUID] uniqueidentifier NOT NULL, @@ -6614,7 +6614,7 @@ CREATE TABLE [dbo].[OMZScenario] ( [Name] nvarchar(64) NOT NULL, [Description] nvarchar(4000) NOT NULL, [PoolGUID] uniqueidentifier NOT NULL, - [Metadata] xml(max) NOT NULL, + [Metadata] xml NOT NULL, PRIMARY KEY ([ScenarioGUID]) ); GO @@ -8768,7 +8768,7 @@ CREATE TABLE [dbo].[ReportArchiveEntryDetail] ( [ReportArchiveEntryDetailGUID] uniqueidentifier NOT NULL, [ReportArchiveEntryGUID] uniqueidentifier NOT NULL, [ReportArchiveDetailAQN] nvarchar(400) NOT NULL, - [ReportArchiveDetailXML] xml(max) NOT NULL, + [ReportArchiveDetailXML] xml NOT NULL, PRIMARY KEY ([ReportArchiveEntryDetailGUID]) ); GO @@ -8830,7 +8830,7 @@ CREATE TABLE [dbo].[RuleAction] ( [RuleSetGUID] uniqueidentifier NOT NULL, [ExecutionOrder] int NOT NULL, [RuleActionTypeAQN] nvarchar(450) NOT NULL, - [RuleActionTypeConfigXML] xml(max) NOT NULL, + [RuleActionTypeConfigXML] xml NOT NULL, PRIMARY KEY ([RuleActionGUID]) ); @@ -8873,7 +8873,7 @@ CREATE TABLE [dbo].[RuleItem] ( [RuleGUID] uniqueidentifier NOT NULL, [RuleGroupGUID] uniqueidentifier NOT NULL, [RuleTypeAQN] nvarchar(450) NOT NULL, - [RuleTypeConfigXML] xml(max) NOT NULL, + [RuleTypeConfigXML] xml NOT NULL, [DisplayOrder] int NOT NULL, [Name] nvarchar(100) NOT NULL, PRIMARY KEY ([RuleGUID]) @@ -9217,7 +9217,7 @@ CREATE TABLE [dbo].[SAShockAssumptionType] ( [Name] nvarchar(100) NOT NULL, [BaseTableName] nvarchar(50) NOT NULL, [ShockTableName] nvarchar(50) NOT NULL, - [WhereClauseXML] xml(max) NOT NULL, + [WhereClauseXML] xml NOT NULL, [DisplayFormat] nvarchar(50) NOT NULL, [IsPercentage] bit NOT NULL, [FormulaColumnName] nvarchar(max) NOT NULL, @@ -11171,7 +11171,7 @@ CREATE TABLE [dbo].[ScoreTableEditorColumn] ( [Type] int NOT NULL, [PixelWidth] int NOT NULL, [DisplayOrder] int NOT NULL, - [MetaData] xml(max) NOT NULL, + [MetaData] xml NOT NULL, [DisplayName] nvarchar(450) NOT NULL, [DefaultMemberType] int NOT NULL, [IsTextWrap] bit NOT NULL, @@ -11979,7 +11979,7 @@ CREATE TABLE [dbo].[SystemCenterStep] ( [SortOrder] int NOT NULL, [SectionGUID] uniqueidentifier NOT NULL, [Name] nvarchar(200) NOT NULL, - [PropertyXML] xml(max) NOT NULL, + [PropertyXML] xml NOT NULL, [Url] nvarchar(400) NOT NULL, [GlobalID] nvarchar(100) NOT NULL, [Description] nvarchar(4000) NOT NULL, @@ -12206,7 +12206,7 @@ CREATE TABLE [dbo].[TETaskHistory] ( [TaskGUID] uniqueidentifier NOT NULL, [Name] nvarchar(450) NOT NULL, [Status] int NOT NULL, - [ContextXML] xml(max) NOT NULL, + [ContextXML] xml NOT NULL, [CreationTime] datetime NOT NULL, [StartTime] datetime NOT NULL, [LastRunTime] datetime NOT NULL, @@ -12297,7 +12297,7 @@ ALTER TABLE [dbo].[Tag] ADD CONSTRAINT [DF_Tag_Tag] DEFAULT ('') FOR [Name]; GO CREATE TABLE [dbo].[TaskProgressStatus] ( [RowID] bigint NOT NULL, [TaskGUID] uniqueidentifier NOT NULL, - [DataXML] xml(max) NOT NULL, + [DataXML] xml NOT NULL, [StartTime] datetime NOT NULL, [TaskStatus] nvarchar(100) NOT NULL, [GlobalID] nvarchar(100) NOT NULL, diff --git a/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements_small.sql index 446b5a6..eb359e5 100644 --- a/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements_small.sql +++ b/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements_small.sql @@ -16,7 +16,7 @@ CREATE TABLE [dbo].[AMAssumptionView] ( [AssumptionJoinDataGUID] uniqueidentifier NOT NULL, [FolderGUID] uniqueidentifier NOT NULL, [IsDistributionModeActive] bit NOT NULL, - [DistributionInfo] xml(max) NOT NULL, + [DistributionInfo] xml NOT NULL, [ProviderGUID] uniqueidentifier NOT NULL, [CreatedDate] datetime NOT NULL, [CreatedBy] uniqueidentifier NOT NULL, -- 2.45.2 From 50eae904e41c6283d7498255ec2a198f2e892f68 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Tue, 4 Feb 2025 20:42:10 +0000 Subject: [PATCH 19/31] Adjust setup.sh file to work with inline go statements --- .../dbo_schema_database_statements.sql | 4 +-- .../fp_schema_database_statements.sql | 0 .../fw_schema_database_statements.sql | 0 .../int_schema_database_statements.sql | 0 .../ob_schema_database_statements.sql | 0 .../dbo_schema_database_statements_small.sql | 4 +++ .../fp_schema_database_statements_small.sql | 3 ++ .../fw_schema_database_statements_small.sql | 3 ++ .../int_schema_database_statements_small.sql | 3 ++ .../ob_schema_database_statements_small.sql | 3 ++ .../infrastructure/sql-server/setup.sh | 29 +++++++++++++++---- 11 files changed, 40 insertions(+), 9 deletions(-) rename ef-migration/infrastructure/sql-server/{schemas => full_schemas}/dbo_schema_database_statements.sql (99%) rename ef-migration/infrastructure/sql-server/{schemas => full_schemas}/fp_schema_database_statements.sql (100%) rename ef-migration/infrastructure/sql-server/{schemas => full_schemas}/fw_schema_database_statements.sql (100%) rename ef-migration/infrastructure/sql-server/{schemas => full_schemas}/int_schema_database_statements.sql (100%) rename ef-migration/infrastructure/sql-server/{schemas => full_schemas}/ob_schema_database_statements.sql (100%) diff --git a/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements.sql b/ef-migration/infrastructure/sql-server/full_schemas/dbo_schema_database_statements.sql similarity index 99% rename from ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements.sql rename to ef-migration/infrastructure/sql-server/full_schemas/dbo_schema_database_statements.sql index a1abf15..eeba30a 100644 --- a/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements.sql +++ b/ef-migration/infrastructure/sql-server/full_schemas/dbo_schema_database_statements.sql @@ -1047,7 +1047,6 @@ CREATE TABLE [dbo].[ColumnStoreIndex] ( [i] int NOT NULL ); -CREATE NONCLUSTERED COLUMNSTORE INDEX [nccx_ColumnStoreIndex] ON [dbo].[ColumnStoreIndex] () INCLUDE ([i]); GO --------------------------------------------- @@ -12815,7 +12814,6 @@ CREATE TABLE [dbo].[WFHistory] ( PRIMARY KEY ([WorkflowHistoryGUID]) ); -CREATE NONCLUSTERED COLUMNSTORE INDEX [NCCNU_WorkflowHistoryGUID] ON [dbo].[WFHistory] () INCLUDE ([WorkflowHistoryGUID]); GO ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [FK_WFHistory_WFWorkflowMap] FOREIGN KEY ([WorkflowMapGUID]) REFERENCES [dbo].[WFWorkflowMap] ([WorkflowMapGUID]); GO ALTER TABLE [dbo].[WFHistory] ADD CONSTRAINT [FK_WFHistory_WFWorkflowStep] FOREIGN KEY ([WorkflowStepGUID]) REFERENCES [dbo].[WFWorkflowStep] ([WorkflowStepGUID]); GO @@ -13526,7 +13524,7 @@ CREATE TABLE [dbo].[dtproperties] ( [property] varchar(64) NOT NULL, [value] varchar(255) NULL, [uvalue] nvarchar(255) NULL, - [lvalue] image(2147483647) NULL, + [lvalue] image NULL, [version] int NOT NULL, PRIMARY KEY ([id], [property]) ); diff --git a/ef-migration/infrastructure/sql-server/schemas/fp_schema_database_statements.sql b/ef-migration/infrastructure/sql-server/full_schemas/fp_schema_database_statements.sql similarity index 100% rename from ef-migration/infrastructure/sql-server/schemas/fp_schema_database_statements.sql rename to ef-migration/infrastructure/sql-server/full_schemas/fp_schema_database_statements.sql diff --git a/ef-migration/infrastructure/sql-server/schemas/fw_schema_database_statements.sql b/ef-migration/infrastructure/sql-server/full_schemas/fw_schema_database_statements.sql similarity index 100% rename from ef-migration/infrastructure/sql-server/schemas/fw_schema_database_statements.sql rename to ef-migration/infrastructure/sql-server/full_schemas/fw_schema_database_statements.sql diff --git a/ef-migration/infrastructure/sql-server/schemas/int_schema_database_statements.sql b/ef-migration/infrastructure/sql-server/full_schemas/int_schema_database_statements.sql similarity index 100% rename from ef-migration/infrastructure/sql-server/schemas/int_schema_database_statements.sql rename to ef-migration/infrastructure/sql-server/full_schemas/int_schema_database_statements.sql diff --git a/ef-migration/infrastructure/sql-server/schemas/ob_schema_database_statements.sql b/ef-migration/infrastructure/sql-server/full_schemas/ob_schema_database_statements.sql similarity index 100% rename from ef-migration/infrastructure/sql-server/schemas/ob_schema_database_statements.sql rename to ef-migration/infrastructure/sql-server/full_schemas/ob_schema_database_statements.sql diff --git a/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements_small.sql index eb359e5..7b675a2 100644 --- a/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements_small.sql +++ b/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements_small.sql @@ -8,6 +8,9 @@ --------------------------------------------- -- dbo.AMAssumptionView ------------------ --------------------------------------------- +DROP TABLE [dbo].[AMAssumptionView]; +GO + CREATE TABLE [dbo].[AMAssumptionView] ( [AssumptionViewGUID] uniqueidentifier NOT NULL, [AssumptionGroupGUID] uniqueidentifier NOT NULL, @@ -36,3 +39,4 @@ ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_FOLDERG ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_ISDISTRIBUTIONMODEACTIVE] DEFAULT ((0)) FOR [IsDistributionModeActive]; GO ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_DISTRIBUTIONINFOXML] DEFAULT ('') FOR [DistributionInfo]; GO ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_PROVIDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ProviderGUID]; GO + diff --git a/ef-migration/infrastructure/sql-server/schemas/fp_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/schemas/fp_schema_database_statements_small.sql index fc7d130..31b867b 100644 --- a/ef-migration/infrastructure/sql-server/schemas/fp_schema_database_statements_small.sql +++ b/ef-migration/infrastructure/sql-server/schemas/fp_schema_database_statements_small.sql @@ -8,6 +8,9 @@ --------------------------------------------- -- fp.APAdminPerformanceTest ------------------ --------------------------------------------- +DROP TABLE [fp].[APAdminPerformanceTest]; +GO + CREATE TABLE [fp].[APAdminPerformanceTest] ( [TestID] uniqueidentifier NOT NULL, [SortOrder] int NOT NULL, diff --git a/ef-migration/infrastructure/sql-server/schemas/fw_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/schemas/fw_schema_database_statements_small.sql index 89f581c..510088c 100644 --- a/ef-migration/infrastructure/sql-server/schemas/fw_schema_database_statements_small.sql +++ b/ef-migration/infrastructure/sql-server/schemas/fw_schema_database_statements_small.sql @@ -8,6 +8,9 @@ --------------------------------------------- -- fw.ABBBudgetedCostPerRVU ------------------ --------------------------------------------- +DROP TABLE [fw].[ABBBudgetedCostPerRVU]; +GO + CREATE TABLE [fw].[ABBBudgetedCostPerRVU] ( [DepartmentID] int NOT NULL, [AccountID] int NOT NULL, diff --git a/ef-migration/infrastructure/sql-server/schemas/int_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/schemas/int_schema_database_statements_small.sql index 872b1ac..6ce75ad 100644 --- a/ef-migration/infrastructure/sql-server/schemas/int_schema_database_statements_small.sql +++ b/ef-migration/infrastructure/sql-server/schemas/int_schema_database_statements_small.sql @@ -8,6 +8,9 @@ --------------------------------------------- -- int.AggregatePostDIHistory ------------------ --------------------------------------------- +DROP TABLE [int].[AggregatePostDIHistory]; +GO + CREATE TABLE [int].[AggregatePostDIHistory] ( [AggregatePostDIHistoryGuid] uniqueidentifier NOT NULL, [CreatedAtUtc] datetime NOT NULL, diff --git a/ef-migration/infrastructure/sql-server/schemas/ob_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/schemas/ob_schema_database_statements_small.sql index edf38ce..43c249c 100644 --- a/ef-migration/infrastructure/sql-server/schemas/ob_schema_database_statements_small.sql +++ b/ef-migration/infrastructure/sql-server/schemas/ob_schema_database_statements_small.sql @@ -8,6 +8,9 @@ --------------------------------------------- -- ob.AccountVariabilityOverride ------------------ --------------------------------------------- +DROP TABLE [ob].[AccountVariabilityOverride]; +GO + CREATE TABLE [ob].[AccountVariabilityOverride] ( [AccountVariabilityOverrideID] int NOT NULL, [DepartmentAssignment] nvarchar(800) NOT NULL, diff --git a/ef-migration/infrastructure/sql-server/setup.sh b/ef-migration/infrastructure/sql-server/setup.sh index e3a732a..9e5d456 100644 --- a/ef-migration/infrastructure/sql-server/setup.sh +++ b/ef-migration/infrastructure/sql-server/setup.sh @@ -21,9 +21,17 @@ do fi done +# Create st-database if it doesn't exist +echo "Creating st-database if it doesn't exist..." +sqlcmd -S localhost -U sa -P $SA_PASSWORD -Q "IF NOT EXISTS (SELECT * FROM sys.databases WHERE name = 'st-database') CREATE DATABASE [st-database]" +if [ $? -ne 0 ]; then + echo "Error creating database" + exit 1 +fi + # Run the initialization script echo "Running initialization script..." -sqlcmd -S localhost -U sa -P $SA_PASSWORD -i /usr/src/app/init.sql +sqlcmd -S localhost -U sa -P $SA_PASSWORD -d st-database -i /usr/src/app/init.sql if [ $? -ne 0 ]; then echo "Error executing initialization script" exit 1 @@ -34,14 +42,23 @@ echo "Running schema scripts..." for f in /usr/src/app/schemas/*.sql do echo "Processing $f..." - sqlcmd -S localhost -U sa -P $SA_PASSWORD -i "$f" -b + + # Create a temporary file + temp_file=$(mktemp) + + # Process the file: add newlines around GO statements + sed 's/GO/\nGO\n/g' "$f" > "$temp_file" + + # Execute the processed file + sqlcmd -S localhost -U sa -P $SA_PASSWORD -d st-database -i "$temp_file" if [ $? -ne 0 ]; then - echo "Error executing schema script $f" - exit 1 + echo "Warning: Script $f had some errors but continuing..." + rm "$temp_file" # Clean up temp file + continue fi - # Verify schema creation - sqlcmd -S localhost -U sa -P $SA_PASSWORD -Q "SELECT name FROM sys.schemas WHERE name IN ('fp', 'fw', 'int', 'ob')" -h -1 + # Clean up temp file + rm "$temp_file" done echo "All scripts executed. SQL Server is ready." -- 2.45.2 From 89b19e7f6232d9e28e1deb19e25a1c947887ee97 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Tue, 4 Feb 2025 21:17:16 +0000 Subject: [PATCH 20/31] Adjust setup.sh file to work with inline go statements --- .../infrastructure/docker-compose-infra.yml | 1 + .../infrastructure/sql-server/Dockerfile | 1 + .../dbo_schema_database_statements.sql | 0 .../fp_schema_database_statements.sql | 0 .../fw_schema_database_statements.sql | 0 .../int_schema_database_statements.sql | 0 .../ob_schema_database_statements.sql | 0 .../infrastructure/sql-server/setup.sh | 118 ++++++++++++------ .../dbo_schema_database_statements_small.sql | 0 .../fp_schema_database_statements_small.sql | 0 .../fw_schema_database_statements_small.sql | 0 .../int_schema_database_statements_small.sql | 0 .../ob_schema_database_statements_small.sql | 0 13 files changed, 81 insertions(+), 39 deletions(-) rename ef-migration/infrastructure/sql-server/{full_schemas => schemas}/dbo_schema_database_statements.sql (100%) rename ef-migration/infrastructure/sql-server/{full_schemas => schemas}/fp_schema_database_statements.sql (100%) rename ef-migration/infrastructure/sql-server/{full_schemas => schemas}/fw_schema_database_statements.sql (100%) rename ef-migration/infrastructure/sql-server/{full_schemas => schemas}/int_schema_database_statements.sql (100%) rename ef-migration/infrastructure/sql-server/{full_schemas => schemas}/ob_schema_database_statements.sql (100%) rename ef-migration/infrastructure/sql-server/{schemas => small_schemas}/dbo_schema_database_statements_small.sql (100%) rename ef-migration/infrastructure/sql-server/{schemas => small_schemas}/fp_schema_database_statements_small.sql (100%) rename ef-migration/infrastructure/sql-server/{schemas => small_schemas}/fw_schema_database_statements_small.sql (100%) rename ef-migration/infrastructure/sql-server/{schemas => small_schemas}/int_schema_database_statements_small.sql (100%) rename ef-migration/infrastructure/sql-server/{schemas => small_schemas}/ob_schema_database_statements_small.sql (100%) diff --git a/ef-migration/infrastructure/docker-compose-infra.yml b/ef-migration/infrastructure/docker-compose-infra.yml index dc86278..c51a07a 100644 --- a/ef-migration/infrastructure/docker-compose-infra.yml +++ b/ef-migration/infrastructure/docker-compose-infra.yml @@ -12,6 +12,7 @@ services: - ACCEPT_EULA=Y - MSSQL_PID=Express - SA_PASSWORD=YourStrong@Passw0rd + - DROP_DATABASE=${DROP_DATABASE:-false} volumes: - sqlserver_data:/var/opt/mssql deploy: diff --git a/ef-migration/infrastructure/sql-server/Dockerfile b/ef-migration/infrastructure/sql-server/Dockerfile index 6118e15..af53d90 100644 --- a/ef-migration/infrastructure/sql-server/Dockerfile +++ b/ef-migration/infrastructure/sql-server/Dockerfile @@ -5,6 +5,7 @@ FROM mcr.microsoft.com/mssql/server:2022-latest ENV ACCEPT_EULA=Y \ MSSQL_PID=Express \ SA_PASSWORD=YourStrong@Passw0rd \ + DROP_DATABASE=false \ PATH="/opt/mssql-tools/bin:${PATH}" # Install sqlcmd utility diff --git a/ef-migration/infrastructure/sql-server/full_schemas/dbo_schema_database_statements.sql b/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements.sql similarity index 100% rename from ef-migration/infrastructure/sql-server/full_schemas/dbo_schema_database_statements.sql rename to ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements.sql diff --git a/ef-migration/infrastructure/sql-server/full_schemas/fp_schema_database_statements.sql b/ef-migration/infrastructure/sql-server/schemas/fp_schema_database_statements.sql similarity index 100% rename from ef-migration/infrastructure/sql-server/full_schemas/fp_schema_database_statements.sql rename to ef-migration/infrastructure/sql-server/schemas/fp_schema_database_statements.sql diff --git a/ef-migration/infrastructure/sql-server/full_schemas/fw_schema_database_statements.sql b/ef-migration/infrastructure/sql-server/schemas/fw_schema_database_statements.sql similarity index 100% rename from ef-migration/infrastructure/sql-server/full_schemas/fw_schema_database_statements.sql rename to ef-migration/infrastructure/sql-server/schemas/fw_schema_database_statements.sql diff --git a/ef-migration/infrastructure/sql-server/full_schemas/int_schema_database_statements.sql b/ef-migration/infrastructure/sql-server/schemas/int_schema_database_statements.sql similarity index 100% rename from ef-migration/infrastructure/sql-server/full_schemas/int_schema_database_statements.sql rename to ef-migration/infrastructure/sql-server/schemas/int_schema_database_statements.sql diff --git a/ef-migration/infrastructure/sql-server/full_schemas/ob_schema_database_statements.sql b/ef-migration/infrastructure/sql-server/schemas/ob_schema_database_statements.sql similarity index 100% rename from ef-migration/infrastructure/sql-server/full_schemas/ob_schema_database_statements.sql rename to ef-migration/infrastructure/sql-server/schemas/ob_schema_database_statements.sql diff --git a/ef-migration/infrastructure/sql-server/setup.sh b/ef-migration/infrastructure/sql-server/setup.sh index 9e5d456..3730046 100644 --- a/ef-migration/infrastructure/sql-server/setup.sh +++ b/ef-migration/infrastructure/sql-server/setup.sh @@ -21,47 +21,87 @@ do fi done -# Create st-database if it doesn't exist -echo "Creating st-database if it doesn't exist..." -sqlcmd -S localhost -U sa -P $SA_PASSWORD -Q "IF NOT EXISTS (SELECT * FROM sys.databases WHERE name = 'st-database') CREATE DATABASE [st-database]" -if [ $? -ne 0 ]; then - echo "Error creating database" - exit 1 -fi - -# Run the initialization script -echo "Running initialization script..." -sqlcmd -S localhost -U sa -P $SA_PASSWORD -d st-database -i /usr/src/app/init.sql -if [ $? -ne 0 ]; then - echo "Error executing initialization script" - exit 1 -fi - -# Run all schema scripts in the schemas directory -echo "Running schema scripts..." -for f in /usr/src/app/schemas/*.sql -do - echo "Processing $f..." - - # Create a temporary file - temp_file=$(mktemp) - - # Process the file: add newlines around GO statements - sed 's/GO/\nGO\n/g' "$f" > "$temp_file" - - # Execute the processed file - sqlcmd -S localhost -U sa -P $SA_PASSWORD -d st-database -i "$temp_file" - if [ $? -ne 0 ]; then - echo "Warning: Script $f had some errors but continuing..." - rm "$temp_file" # Clean up temp file - continue +# Check if we should drop the database +if [ "${DROP_DATABASE,,}" = "true" ]; then + echo "DROP_DATABASE is true. Attempting to drop database..." + sqlcmd -S localhost -U sa -P $SA_PASSWORD -Q " + IF EXISTS (SELECT 1 FROM sys.databases WHERE name = 'st-database') + BEGIN + ALTER DATABASE [st-database] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; + DROP DATABASE [st-database]; + END" + if [ $? -eq 0 ]; then + echo "Database dropped successfully." + else + echo "Error dropping database" + exit 1 fi - - # Clean up temp file - rm "$temp_file" -done +fi -echo "All scripts executed. SQL Server is ready." +# Check if database already exists and has tables +echo "Checking if database is already initialized..." +DB_INITIALIZED=$(sqlcmd -S localhost -U sa -P $SA_PASSWORD -Q " +IF EXISTS ( + SELECT 1 + FROM sys.databases + WHERE name = 'st-database' + AND EXISTS ( + SELECT 1 + FROM st-database.sys.tables + WHERE name = 'AMAssumptionView' + ) +) +SELECT 1 +ELSE +SELECT 0" -h -1) + +if [ "$DB_INITIALIZED" = "1" ]; then + echo "Database st-database already exists and is initialized. Skipping setup." +else + echo "Database needs initialization. Starting setup..." + + # Create st-database if it doesn't exist + echo "Creating st-database if it doesn't exist..." + sqlcmd -S localhost -U sa -P $SA_PASSWORD -Q "IF NOT EXISTS (SELECT * FROM sys.databases WHERE name = 'st-database') CREATE DATABASE [st-database]" + if [ $? -ne 0 ]; then + echo "Error creating database" + exit 1 + fi + + # Run the initialization script + echo "Running initialization script..." + sqlcmd -S localhost -U sa -P $SA_PASSWORD -d st-database -i /usr/src/app/init.sql + if [ $? -ne 0 ]; then + echo "Error executing initialization script" + exit 1 + fi + + # Run all schema scripts in the schemas directory + echo "Running schema scripts..." + for f in /usr/src/app/schemas/*.sql + do + echo "Processing $f..." + + # Create a temporary file + temp_file=$(mktemp) + + # Process the file: add newlines around GO statements + sed 's/GO/\nGO\n/g' "$f" > "$temp_file" + + # Execute the processed file + sqlcmd -S localhost -U sa -P $SA_PASSWORD -d st-database -i "$temp_file" + if [ $? -ne 0 ]; then + echo "Warning: Script $f had some errors but continuing..." + rm "$temp_file" # Clean up temp file + continue + fi + + # Clean up temp file + rm "$temp_file" + done + + echo "All scripts executed. SQL Server is ready." +fi # Keep container running while true; do diff --git a/ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/small_schemas/dbo_schema_database_statements_small.sql similarity index 100% rename from ef-migration/infrastructure/sql-server/schemas/dbo_schema_database_statements_small.sql rename to ef-migration/infrastructure/sql-server/small_schemas/dbo_schema_database_statements_small.sql diff --git a/ef-migration/infrastructure/sql-server/schemas/fp_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/small_schemas/fp_schema_database_statements_small.sql similarity index 100% rename from ef-migration/infrastructure/sql-server/schemas/fp_schema_database_statements_small.sql rename to ef-migration/infrastructure/sql-server/small_schemas/fp_schema_database_statements_small.sql diff --git a/ef-migration/infrastructure/sql-server/schemas/fw_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/small_schemas/fw_schema_database_statements_small.sql similarity index 100% rename from ef-migration/infrastructure/sql-server/schemas/fw_schema_database_statements_small.sql rename to ef-migration/infrastructure/sql-server/small_schemas/fw_schema_database_statements_small.sql diff --git a/ef-migration/infrastructure/sql-server/schemas/int_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/small_schemas/int_schema_database_statements_small.sql similarity index 100% rename from ef-migration/infrastructure/sql-server/schemas/int_schema_database_statements_small.sql rename to ef-migration/infrastructure/sql-server/small_schemas/int_schema_database_statements_small.sql diff --git a/ef-migration/infrastructure/sql-server/schemas/ob_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/small_schemas/ob_schema_database_statements_small.sql similarity index 100% rename from ef-migration/infrastructure/sql-server/schemas/ob_schema_database_statements_small.sql rename to ef-migration/infrastructure/sql-server/small_schemas/ob_schema_database_statements_small.sql -- 2.45.2 From 9ae8ac1501b7e6ef4d7bf1e60b49aaad229d33b3 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Tue, 4 Feb 2025 22:47:30 +0000 Subject: [PATCH 21/31] include parsing files --- .../infrastructure/docker-compose-infra.yml | 1 + .../full_schemas/extract_constraints.sh | 117 +++++++++++++++++ .../sql-server/full_schemas/extract_tables.sh | 105 +++++++++++++++ .../sql-server/full_schemas/extract_views.sh | 124 ++++++++++++++++++ .../sql-server/full_schemas/parse_sql.sh | 116 ++++++++++++++++ 5 files changed, 463 insertions(+) create mode 100755 ef-migration/infrastructure/sql-server/full_schemas/extract_constraints.sh create mode 100755 ef-migration/infrastructure/sql-server/full_schemas/extract_tables.sh create mode 100755 ef-migration/infrastructure/sql-server/full_schemas/extract_views.sh create mode 100755 ef-migration/infrastructure/sql-server/full_schemas/parse_sql.sh diff --git a/ef-migration/infrastructure/docker-compose-infra.yml b/ef-migration/infrastructure/docker-compose-infra.yml index c51a07a..3f59a15 100644 --- a/ef-migration/infrastructure/docker-compose-infra.yml +++ b/ef-migration/infrastructure/docker-compose-infra.yml @@ -15,6 +15,7 @@ services: - DROP_DATABASE=${DROP_DATABASE:-false} volumes: - sqlserver_data:/var/opt/mssql + - ./logs:/usr/src/app/logs deploy: resources: limits: diff --git a/ef-migration/infrastructure/sql-server/full_schemas/extract_constraints.sh b/ef-migration/infrastructure/sql-server/full_schemas/extract_constraints.sh new file mode 100755 index 0000000..a4ce1d8 --- /dev/null +++ b/ef-migration/infrastructure/sql-server/full_schemas/extract_constraints.sh @@ -0,0 +1,117 @@ +#!/bin/bash + +# Check if input file is provided +if [ $# -ne 1 ]; then + echo "Usage: $0 " + exit 1 +fi + +SQL_FILE="$1" +BASE_DIR="sql_objects" + +# Create directory structure +mkdir -p "$BASE_DIR"/{constraints,foreign_keys} + +# Function to clean filename +clean_filename() { + # Remove brackets, convert dots and spaces to underscores, remove parentheses + echo "$1" | sed 's/\[\|\]//g' | tr '.' '_' | tr ' ' '_' | sed 's/[()]//g' | sed 's/__*/_/g' | sed 's/_$//' +} + +# Function to extract table name from constraint +extract_table_name() { + echo "$1" | sed -nE 's/.*ALTER[[:space:]]+TABLE[[:space:]]+\[?([^]]+)\]?.*/\1/p' +} + +# Function to extract constraint name +extract_constraint_name() { + echo "$1" | sed -nE 's/.*CONSTRAINT[[:space:]]+\[?([^]]+)\]?.*/\1/p' +} + +# Function to process each ALTER TABLE statement +process_statement() { + local line="$1" + local table_name=$(extract_table_name "$line") + local constraint_name=$(extract_constraint_name "$line") + + # Skip if we couldn't extract table or constraint name + if [ -z "$table_name" ] || [ -z "$constraint_name" ]; then + return + fi + + # Determine if it's a foreign key + if echo "$line" | grep -i "FOREIGN[[:space:]]\+KEY" >/dev/null; then + output_dir="$BASE_DIR/foreign_keys" + else + output_dir="$BASE_DIR/constraints" + fi + + # Clean filename and save + clean_name=$(clean_filename "${table_name}_${constraint_name}") + output_file="${output_dir}/${clean_name}.sql" + echo "$line" > "$output_file" + echo "Created: $output_file" +} + +# Main processing function +extract_constraints() { + local current_statement="" + + # Read the file line by line + while IFS= read -r line || [ -n "$line" ]; do + # Skip empty lines + if [ -z "${line// }" ]; then + continue + fi + + # If line starts with ALTER TABLE, it's a new statement + if echo "$line" | grep -i "^[[:space:]]*ALTER[[:space:]]\+TABLE" >/dev/null; then + current_statement="$line" + + # If GO is on the same line + if echo "$line" | grep -i "GO[[:space:]]*$" >/dev/null; then + # Remove GO and process + current_statement=$(echo "$current_statement" | sed 's/[[:space:]]*GO[[:space:]]*$//') + process_statement "$current_statement" + current_statement="" + fi + continue + fi + + # If we find GO, process the current statement + if echo "$line" | grep -i "^[[:space:]]*GO[[:space:]]*$" >/dev/null; then + if [ -n "$current_statement" ]; then + process_statement "$current_statement" + current_statement="" + fi + continue + fi + + # Add line to current statement if we're collecting one + if [ -n "$current_statement" ]; then + current_statement+=" $line" + fi + done +} + +# Remove comment lines starting with -- and process +echo "Extracting constraints and foreign keys..." +sed 's/--.*$//' "$SQL_FILE" | extract_constraints + +echo "Constraints and foreign keys have been saved in $BASE_DIR/constraints and $BASE_DIR/foreign_keys" + +# Count and list files +echo -e "\nFile counts:" +for dir in constraints foreign_keys; do + count=$(ls -1 "$BASE_DIR/$dir"/*.sql 2>/dev/null | wc -l || echo 0) + echo "$dir: $count files" + + echo -e "\nExtracted ${dir}:" + if [ "$count" -gt 0 ]; then + for file in "$BASE_DIR/$dir"/*.sql; do + if [ -f "$file" ]; then + echo "- $(basename "$file")" + fi + done + fi +done \ No newline at end of file diff --git a/ef-migration/infrastructure/sql-server/full_schemas/extract_tables.sh b/ef-migration/infrastructure/sql-server/full_schemas/extract_tables.sh new file mode 100755 index 0000000..d9959d2 --- /dev/null +++ b/ef-migration/infrastructure/sql-server/full_schemas/extract_tables.sh @@ -0,0 +1,105 @@ +#!/bin/bash + +# Check if input file is provided +if [ $# -ne 1 ]; then + echo "Usage: $0 " + exit 1 +fi + +SQL_FILE="$1" +BASE_DIR="sql_objects" + +# Create directory structure +mkdir -p "$BASE_DIR/tables" + +# Function to clean filename +clean_filename() { + # Remove brackets, convert dots and spaces to underscores, remove parentheses + echo "$1" | sed 's/\[\|\]//g' | tr '.' '_' | tr ' ' '_' | sed 's/[()]//g' | sed 's/__*/_/g' | sed 's/_$//' +} + +# Function to check if table is temporary +is_temporary_table() { + local table_name="$1" + if echo "$table_name" | grep -iE "temp|tmp|temporary|import_|viewimport_" >/dev/null; then + return 0 # true in bash + else + return 1 # false in bash + fi +} + +# Function to extract CREATE TABLE statements only +extract_tables() { + local current_object="" + local capture_table=false + local table_name="" + + # Read the file line by line + while IFS= read -r line || [ -n "$line" ]; do + # Check if we've found a CREATE TABLE statement + if echo "$line" | grep -i "CREATE[[:space:]]\+TABLE" >/dev/null; then + # Extract table name and check if it's temporary + table_name=$(echo "$line" | sed -E 's/.*CREATE[[:space:]]+TABLE[[:space:]]+\[?([^\]]+)\]?.*/\1/') + + if is_temporary_table "$table_name"; then + echo "Skipping temporary table: $table_name" + continue + fi + + capture_table=true + current_object="$line"$'\n' + continue + fi + + # If we're capturing a table and find a following CREATE or ALTER statement, stop capturing + if $capture_table; then + if echo "$line" | grep -i "^[[:space:]]*CREATE\|^[[:space:]]*ALTER" >/dev/null; then + # Save the current table before starting a new object + if [ -n "$table_name" ]; then + clean_name=$(clean_filename "$table_name") + output_file="$BASE_DIR/tables/${clean_name}.sql" + echo "$current_object" > "$output_file" + echo "Created: $output_file" + fi + capture_table=false + current_object="" + table_name="" + continue + fi + + # Add line to current object if we're still capturing + current_object+="$line"$'\n' + + # If we find a GO statement, save the table + if echo "$line" | grep -i "^[[:space:]]*GO[[:space:]]*$" >/dev/null; then + if [ -n "$table_name" ]; then + clean_name=$(clean_filename "$table_name") + output_file="$BASE_DIR/tables/${clean_name}.sql" + echo "$current_object" > "$output_file" + echo "Created: $output_file" + fi + capture_table=false + current_object="" + table_name="" + fi + fi + done < "$SQL_FILE" +} + +# Remove comment lines starting with -- +echo "Extracting CREATE TABLE statements..." +sed 's/--.*$//' "$SQL_FILE" | extract_tables + +echo "CREATE TABLE statements have been saved in $BASE_DIR/tables/" + +# Count files +count=$(ls -1 "$BASE_DIR/tables"/*.sql 2>/dev/null | wc -l) +echo -e "\nTotal tables extracted: $count" + +# List extracted tables +echo -e "\nExtracted tables:" +for table in "$BASE_DIR/tables"/*.sql; do + if [ -f "$table" ]; then + echo "- $(basename "$table")" + fi +done \ No newline at end of file diff --git a/ef-migration/infrastructure/sql-server/full_schemas/extract_views.sh b/ef-migration/infrastructure/sql-server/full_schemas/extract_views.sh new file mode 100755 index 0000000..a708894 --- /dev/null +++ b/ef-migration/infrastructure/sql-server/full_schemas/extract_views.sh @@ -0,0 +1,124 @@ +#!/bin/bash + +# Check if input file is provided +if [ $# -ne 1 ]; then + echo "Usage: $0 " + exit 1 +fi + +SQL_FILE="$1" +BASE_DIR="sql_objects" + +# Create directory structure +mkdir -p "$BASE_DIR/views" + +# Function to clean filename +clean_filename() { + # Remove brackets, convert dots and spaces to underscores, remove parentheses + echo "$1" | sed 's/\[\|\]//g' | tr '.' '_' | tr ' ' '_' | sed 's/[()]//g' | sed 's/__*/_/g' | sed 's/_$//' +} + +# Function to extract view name +extract_view_name() { + # More flexible pattern for extracting view name + echo "$1" | sed -n 's/.*[Cc][Rr][Ee][Aa][Tt][Ee][[:space:]]*[Vv][Ii][Ee][Ww][[:space:]]*\[\([^]]*\)\]\.\[\([^]]*\)\].*/\1.\2/p' +} + +# Function to clean the input line +clean_input_line() { + # Remove any leading/trailing whitespace and normalize spaces + echo "$1" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | tr -s ' ' +} + +# Function to process each CREATE VIEW statement +process_view() { + local current_object="$1" + local view_name="$2" + + # Skip if we couldn't extract view name + if [ -z "$view_name" ]; then + echo "Warning: Could not extract view name from statement:" + echo "$current_object" | head -n 1 + # Try to extract with a more lenient pattern + view_name=$(echo "$current_object" | head -n 1 | grep -io '\[int\]\.\[[^]]*\]' | head -n 1 | sed 's/\[\|\]//g') + if [ -z "$view_name" ]; then + return + fi + fi + + # Clean filename and save + clean_name=$(clean_filename "$view_name") + output_file="$BASE_DIR/views/${clean_name}.sql" + echo "$current_object" > "$output_file" + echo "Created: $output_file (from view: $view_name)" +} + +# Main processing function +extract_views() { + local current_object="" + local capture_view=false + local view_name="" + + # Read the file line by line + while IFS= read -r line || [ -n "$line" ]; do + # Clean the line + line=$(clean_input_line "$line") + + # Skip empty lines at the start of an object + if [ -z "$line" ] && [ -z "$current_object" ]; then + continue + fi + + # Check if we've found a CREATE VIEW statement (case insensitive and flexible) + if echo "$line" | grep -iE "[[:space:]]*[Cc][Rr][Ee][Aa][Tt][Ee][[:space:]]+[Vv][Ii][Ee][Ww]" >/dev/null; then + capture_view=true + current_object="$line" + view_name=$(extract_view_name "$line") + if [ -n "$view_name" ]; then + echo "Found view: $view_name" + fi + continue + fi + + # If we're capturing a view + if $capture_view; then + # Check if we've reached the end (GO statement) + if echo "$line" | grep -i "^[[:space:]]*GO[[:space:]]*$" >/dev/null; then + # Add GO to the view definition + current_object+=$'\n'"GO" + process_view "$current_object" "$view_name" + capture_view=false + current_object="" + view_name="" + continue + fi + + # Add line to current object + current_object+=$'\n'"$line" + fi + done + + # Handle case where last view might not have a GO statement + if $capture_view && [ -n "$current_object" ]; then + process_view "$current_object" "$view_name" + fi +} + +# Pre-process the file to normalize line endings and remove comments +echo "Extracting views..." +sed 's/--.*$//; /^[[:space:]]*$/d' "$SQL_FILE" | extract_views + +echo "Views have been saved in $BASE_DIR/views" + +# Count and list files +count=$(ls -1 "$BASE_DIR/views"/*.sql 2>/dev/null | wc -l || echo 0) +echo -e "\nTotal views extracted: $count" + +if [ "$count" -gt 0 ]; then + echo -e "\nExtracted views:" + for file in "$BASE_DIR/views"/*.sql; do + if [ -f "$file" ]; then + echo "- $(basename "$file")" + fi + done +fi \ No newline at end of file diff --git a/ef-migration/infrastructure/sql-server/full_schemas/parse_sql.sh b/ef-migration/infrastructure/sql-server/full_schemas/parse_sql.sh new file mode 100755 index 0000000..afa86a4 --- /dev/null +++ b/ef-migration/infrastructure/sql-server/full_schemas/parse_sql.sh @@ -0,0 +1,116 @@ +#!/bin/bash + +# Check if input file is provided +if [ $# -ne 1 ]; then + echo "Usage: $0 " + exit 1 +fi + +SQL_FILE="$1" +BASE_DIR="sql_objects" + +# Create directory structure +mkdir -p "$BASE_DIR"/{tables,views,procedures,constraints,indexes,alter_tables} + +# Function to clean filename +clean_filename() { + echo "$1" | sed 's/\[\|\]//g' | tr '.' '_' +} + +# Function to extract SQL objects and save to files +extract_objects() { + local current_object="" + local object_type="" + local object_name="" + local table_name="" + + # Read the file line by line + while IFS= read -r line || [ -n "$line" ]; do + # Skip empty lines at the start + if [ -z "$current_object" ] && [ -z "${line// }" ]; then + continue + fi + + # Add line to current object + current_object+="$line"$'\n' + + # Check if we've reached the end of an object (GO statement) + if echo "$line" | grep -i "^[[:space:]]*GO[[:space:]]*$" >/dev/null; then + # Determine object type and name + if echo "$current_object" | grep -i "CREATE[[:space:]]\+TABLE" >/dev/null; then + object_type="tables" + object_name=$(echo "$current_object" | grep -i "CREATE[[:space:]]\+TABLE" | sed -E 's/.*CREATE[[:space:]]+TABLE[[:space:]]+\[?([^\]]+)\]?.*/\1/') + elif echo "$current_object" | grep -i "CREATE[[:space:]]\+VIEW" >/dev/null; then + object_type="views" + object_name=$(echo "$current_object" | grep -i "CREATE[[:space:]]\+VIEW" | sed -E 's/.*CREATE[[:space:]]+VIEW[[:space:]]+\[?([^\]]+)\]?.*/\1/') + elif echo "$current_object" | grep -i "CREATE[[:space:]]\+PROC" >/dev/null; then + object_type="procedures" + object_name=$(echo "$current_object" | grep -i "CREATE[[:space:]]\+PROC[[:space:]EDURE]*" | sed -E 's/.*CREATE[[:space:]]+PROC[[:space:]EDURE]*[[:space:]]+\[?([^\]]+)\]?.*/\1/') + elif echo "$current_object" | grep -i "ALTER[[:space:]]\+TABLE" >/dev/null; then + # Extract table name and constraint name if it exists + table_name=$(echo "$current_object" | grep -i "ALTER[[:space:]]\+TABLE" | sed -E 's/.*ALTER[[:space:]]+TABLE[[:space:]]+\[?([^\]]+)\]?.*/\1/') + + if echo "$current_object" | grep -i "ADD[[:space:]]\+CONSTRAINT" >/dev/null; then + object_type="constraints" + object_name=$(echo "$current_object" | grep -i "CONSTRAINT" | sed -E 's/.*CONSTRAINT[[:space:]]+\[?([^\]]+)\]?.*/\1/') + else + object_type="alter_tables" + object_name="${table_name}_alter_$(date +%s%N | cut -b1-5)" + fi + elif echo "$current_object" | grep -i "CREATE.*INDEX" >/dev/null; then + object_type="indexes" + object_name=$(echo "$current_object" | grep -i "INDEX" | sed -E 's/.*INDEX[[:space:]]+\[?([^\]]+)\]?.*/\1/') + fi + + # If we identified an object type and name, save it + if [ -n "$object_type" ] && [ -n "$object_name" ]; then + # Clean the filename + clean_name=$(clean_filename "$object_name") + output_file="$BASE_DIR/$object_type/$clean_name.sql" + + # For alter_tables, make sure we don't overwrite existing files + if [ "$object_type" = "alter_tables" ]; then + counter=1 + base_file="$BASE_DIR/$object_type/$clean_name" + while [ -f "${base_file}.sql" ]; do + clean_name="${clean_name}_${counter}" + counter=$((counter + 1)) + done + output_file="$base_file.sql" + fi + + # Save the object to file + echo "$current_object" > "$output_file" + echo "Created: $output_file" + fi + + # Reset for next object + current_object="" + object_type="" + object_name="" + table_name="" + fi + done < "$SQL_FILE" +} + +# Remove comment lines starting with -- +echo "Removing comments and processing SQL file..." +sed 's/--.*$//' "$SQL_FILE" | extract_objects + +echo "SQL objects have been organized in the $BASE_DIR directory." +echo " +Directory structure: +$BASE_DIR/ +├── tables/ +├── views/ +├── procedures/ +├── constraints/ +├── indexes/ +└── alter_tables/" + +# Count files in each directory +echo -e "\nFile counts:" +for dir in tables views procedures constraints indexes alter_tables; do + count=$(ls -1 "$BASE_DIR/$dir"/*.sql 2>/dev/null | wc -l) + echo "$dir: $count files" +done \ No newline at end of file -- 2.45.2 From d56312a811be35d169417eb0c095719b2c763d9d Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Tue, 4 Feb 2025 23:19:27 +0000 Subject: [PATCH 22/31] extract indexes and procedures --- .../full_schemas/extract_indexes.sh | 171 ++++++++++++++++++ .../full_schemas/extract_procedures.sh | 164 +++++++++++++++++ 2 files changed, 335 insertions(+) create mode 100755 ef-migration/infrastructure/sql-server/full_schemas/extract_indexes.sh create mode 100755 ef-migration/infrastructure/sql-server/full_schemas/extract_procedures.sh diff --git a/ef-migration/infrastructure/sql-server/full_schemas/extract_indexes.sh b/ef-migration/infrastructure/sql-server/full_schemas/extract_indexes.sh new file mode 100755 index 0000000..89037dc --- /dev/null +++ b/ef-migration/infrastructure/sql-server/full_schemas/extract_indexes.sh @@ -0,0 +1,171 @@ +#!/bin/bash + +# Check if input file is provided +if [ $# -ne 1 ]; then + echo "Usage: $0 " + exit 1 +fi + +SQL_FILE="$1" +BASE_DIR="sql_objects" + +# Create directory structure +mkdir -p "$BASE_DIR/indexes/clustered" +mkdir -p "$BASE_DIR/indexes/nonclustered" +mkdir -p "$BASE_DIR/indexes/unique_clustered" + +# Function to clean filename +clean_filename() { + # Remove brackets, convert dots and spaces to underscores, remove parentheses + echo "$1" | sed 's/\[\|\]//g' | tr '.' '_' | tr ' ' '_' | sed 's/[()]//g' | sed 's/__*/_/g' | sed 's/_$//' +} + +# Function to determine if line is start of an index creation statement +is_index_start() { + # Matches with UNIQUE, CLUSTERED/NONCLUSTERED keywords + echo "$1" | grep -qiE "CREATE[[:space:]]*(UNIQUE[[:space:]]+)?(CLUSTERED|NONCLUSTERED)?[[:space:]]*INDEX[[:space:]]+\[?[^]]+\]?[[:space:]]+ON" +} + +# Function to extract table name +extract_table_name() { + # More aggressive extraction of table name + echo "$1" | sed -nE 's/.*CREATE[[:space:]]*(UNIQUE[[:space:]]+)?(CLUSTERED|NONCLUSTERED)?[[:space:]]*INDEX[[:space:]]+\[?[^]]+\]?[[:space:]]+ON[[:space:]]+(\[[^]]+\](\.[^]]+)?).*/\3/p' | tr -d '[]' +} + +# Function to extract index name +extract_index_name() { + # Extract index name, handling various formats + echo "$1" | sed -nE 's/.*CREATE[[:space:]]*(UNIQUE[[:space:]]+)?(CLUSTERED|NONCLUSTERED)?[[:space:]]*INDEX[[:space:]]+\[?([^]]+)\]?.*/\3/p' | tr -d '[]' +} + +# Function to determine index type +get_index_type() { + local line="$1" + local is_unique=$(echo "$line" | grep -qiE "CREATE[[:space:]]+UNIQUE" && echo true || echo false) + local is_clustered=$(echo "$line" | grep -qiE "CREATE[[:space:]]+CLUSTERED" && echo true || echo false) + local is_nonclustered=$(echo "$line" | grep -qiE "CREATE[[:space:]]+NONCLUSTERED" && echo true || echo false) + + if $is_unique && $is_clustered; then + echo "unique_clustered" + elif $is_clustered; then + echo "clustered" + elif $is_nonclustered; then + echo "nonclustered" + else + echo "clustered" # Default to clustered if no type specified + fi +} + +# Function to process each index statement +process_index() { + local line="$1" + local table_name=$(extract_table_name "$line") + local index_name=$(extract_index_name "$line") + local index_type=$(get_index_type "$line") + + # Skip if we couldn't extract table or index name + if [ -z "$table_name" ] || [ -z "$index_name" ]; then + echo "Warning: Could not extract table or index name from:" + echo "$line" + return + fi + + # Clean filename and save + clean_name=$(clean_filename "${table_name}_${index_name}") + output_dir="$BASE_DIR/indexes/$index_type" + output_file="${output_dir}/${clean_name}.sql" + + # Trim whitespace and ensure semicolon at end + line=$(echo "$line" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//') + if [[ "$line" != *\; ]]; then + line="${line};" + fi + + echo "$line" > "$output_file" + echo "Created: $output_file" +} + +# Main processing function +extract_indexes() { + local current_statement="" + local capturing_index=false + + # Disable case sensitivity + shopt -s nocasematch + + # Read the file line by line + while IFS= read -r line || [ -n "$line" ]; do + # Skip empty lines and pure comment lines + if [ -z "${line// }" ] || [[ "$line" =~ ^[[:space:]]*-- ]]; then + continue + fi + + # Check for index start + if is_index_start "$line"; then + # Process previous statement if any + if [ -n "$current_statement" ] && $capturing_index; then + process_index "$current_statement" + fi + + # Start new index statement + current_statement="$line" + capturing_index=true + + # Check if GO is on the same line + if [[ "$line" =~ GO[[:space:]]*$ ]]; then + # Remove GO and process + current_statement=$(echo "$current_statement" | sed 's/[[:space:]]*GO[[:space:]]*$//') + process_index "$current_statement" + current_statement="" + capturing_index=false + fi + continue + fi + + # If we're capturing an index + if $capturing_index; then + # Add line to current statement + current_statement+=" $line" + + # Check for GO statement + if [[ "$line" =~ ^[[:space:]]*GO[[:space:]]*$ ]]; then + # Remove GO and process + current_statement=$(echo "$current_statement" | sed 's/[[:space:]]*GO[[:space:]]*$//; s/;[[:space:]]*$//') + process_index "$current_statement" + current_statement="" + capturing_index=false + fi + fi + done + + # Process any remaining index statement + if [ -n "$current_statement" ] && $capturing_index; then + process_index "$current_statement" + fi + + # Re-enable case sensitivity + shopt -u nocasematch +} + +# Remove comment lines and process +echo "Extracting indexes..." +sed 's/--.*$//' "$SQL_FILE" | extract_indexes + +echo "Indexes have been saved in $BASE_DIR/indexes" + +# Count and list files +echo -e "\nFile counts:" +for index_type in clustered nonclustered unique_clustered; do + count=$(ls -1 "$BASE_DIR/indexes/$index_type"/*.sql 2>/dev/null | wc -l || echo 0) + echo "$index_type indexes: $count files" + + if [ "$count" -gt 0 ]; then + echo -e "\nExtracted $index_type indexes:" + for file in "$BASE_DIR/indexes/$index_type"/*.sql; do + if [ -f "$file" ]; then + echo "- $(basename "$file")" + fi + done + echo + fi +done \ No newline at end of file diff --git a/ef-migration/infrastructure/sql-server/full_schemas/extract_procedures.sh b/ef-migration/infrastructure/sql-server/full_schemas/extract_procedures.sh new file mode 100755 index 0000000..674bea6 --- /dev/null +++ b/ef-migration/infrastructure/sql-server/full_schemas/extract_procedures.sh @@ -0,0 +1,164 @@ +#!/bin/bash + +# Check if input file is provided +if [ $# -ne 1 ]; then + echo "Usage: $0 " + exit 1 +fi + +SQL_FILE="$1" +BASE_DIR="sql_objects" + +# Create directory structure +mkdir -p "$BASE_DIR/procedures" + +# Function to clean filename +clean_filename() { + # Remove brackets, convert dots and spaces to underscores, remove parentheses + echo "$1" | sed 's/\[\|\]//g' | tr '.' '_' | tr ' ' '_' | sed 's/[()]//g' | sed 's/__*/_/g' | sed 's/_$//' +} + +# Function to extract procedure name +extract_procedure_name() { + # More flexible procedure name extraction + local name=$(echo "$1" | sed -nE 's/.*CREATE[[:space:]]+PROC(EDURE)?[[:space:]]+(\[[^]]+\](\.[^]]+)?|\S+).*/\2/pi' | tr -d '[]') + echo "$name" +} + +# Function to extract schema name (if present) +extract_schema_name() { + # Extract schema name with more flexible matching + local schema=$(echo "$1" | sed -nE 's/.*CREATE[[:space:]]+PROC(EDURE)?[[:space:]]+\[?([^.]+)\.([^]]+)\]?.*/\2/pi') + if [ -z "$schema" ]; then + # Try alternative extraction + schema=$(echo "$1" | sed -nE 's/.*CREATE[[:space:]]+PROC(EDURE)?[[:space:]]+\[?([^]]+)\]?.*/\2/pi' | cut -d. -f1) + fi + + if [ -z "$schema" ]; then + echo "dbo" # Default schema if not specified + else + echo "$schema" | tr -d '[]' + fi +} + +# Function to process each procedure statement +process_procedure() { + local procedure_statement="$1" + local procedure_name=$(extract_procedure_name "$procedure_statement") + local schema_name=$(extract_schema_name "$procedure_statement") + + # Skip if we couldn't extract procedure name + if [ -z "$procedure_name" ]; then + echo "Warning: Could not extract procedure name from:" + echo "$procedure_statement" + return + fi + + # Clean filename and save + clean_name=$(clean_filename "${schema_name}_${procedure_name}") + output_file="$BASE_DIR/procedures/${clean_name}.sql" + + # Trim whitespace and ensure semicolon at end if not already present + procedure_statement=$(echo "$procedure_statement" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//') + if [[ "$procedure_statement" != *\; ]]; then + procedure_statement="${procedure_statement};" + fi + + # Save the procedure + echo "$procedure_statement" > "$output_file" + echo "Created: $output_file" +} + +# Main processing function +extract_procedures() { + local current_statement="" + local capturing_procedure=false + local depth=0 + + # Disable case sensitivity + shopt -s nocasematch + + # Read the file line by line + while IFS= read -r line || [ -n "$line" ]; do + # Skip empty lines and pure comment lines + if [ -z "${line// }" ] || [[ "$line" =~ ^[[:space:]]*-- ]]; then + continue + fi + + # Check for procedure start (more flexible) + if [[ "$line" =~ CREATE[[:space:]]+PROC(EDURE)?[[:space:]]+ ]]; then + # Process previous statement if any + if [ -n "$current_statement" ] && $capturing_procedure; then + process_procedure "$current_statement" + fi + + # Start new procedure statement + current_statement="$line" + capturing_procedure=true + depth=0 + + # Check if GO is on the same line + if [[ "$line" =~ GO[[:space:]]*$ ]]; then + # Remove GO and process + current_statement=$(echo "$current_statement" | sed 's/[[:space:]]*GO[[:space:]]*$//') + process_procedure "$current_statement" + current_statement="" + capturing_procedure=false + fi + continue + fi + + # If we're capturing a procedure + if $capturing_procedure; then + # Track BEGIN/END blocks to ensure we capture the entire procedure + if [[ "$line" =~ BEGIN ]]; then + ((depth++)) + fi + + if [[ "$line" =~ END ]]; then + ((depth--)) + fi + + # Add line to current statement + current_statement+=" $line" + + # Check for GO statement or end of procedure + if [[ "$line" =~ ^[[:space:]]*GO[[:space:]]*$ ]] || + ([[ "$line" =~ END ]] && [[ $depth -le 0 ]]); then + # Remove GO and process + current_statement=$(echo "$current_statement" | sed 's/[[:space:]]*GO[[:space:]]*$//; s/;[[:space:]]*$//') + process_procedure "$current_statement" + current_statement="" + capturing_procedure=false + depth=0 + fi + fi + done + + # Process any remaining procedure statement + if [ -n "$current_statement" ] && $capturing_procedure; then + process_procedure "$current_statement" + fi + + # Re-enable case sensitivity + shopt -u nocasematch +} + +# Remove comment lines and process +echo "Extracting stored procedures..." +sed 's/--.*$//' "$SQL_FILE" | extract_procedures + +echo "Stored procedures have been saved in $BASE_DIR/procedures" + +# Count and list files +count=$(ls -1 "$BASE_DIR/procedures"/*.sql 2>/dev/null | wc -l || echo 0) +echo -e "\nTotal stored procedures extracted: $count" + +if [ "$count" -gt 0 ]; then + echo -e "\nExtracted stored procedures:" + for file in "$BASE_DIR/procedures"/*.sql; do + if [ -f "$file" ]; then + echo "- $(basename "$file")" + fi + done +fi \ No newline at end of file -- 2.45.2 From 9b1609e256cc1dbf3eac5d447039081f2b260d03 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Wed, 5 Feb 2025 01:18:33 +0000 Subject: [PATCH 23/31] organize database scripts --- .../infrastructure/sql-server/Dockerfile | 17 +- .../{full_schemas => }/extract_constraints.sh | 3 + .../{full_schemas => }/extract_indexes.sh | 3 + .../{full_schemas => }/extract_procedures.sh | 3 + .../sql-server/extract_tables.sh | 150 ++++++++++++++++++ .../{full_schemas => }/extract_views.sh | 3 + .../sql-server/full_schemas/extract_tables.sh | 105 ------------ .../sql-server/full_schemas/parse_sql.sh | 116 -------------- .../infrastructure/sql-server/setup.sh | 80 +++++++--- .../dbo_schema_database_statements_small.sql | 42 ----- .../fp_schema_database_statements_small.sql | 43 ----- .../fw_schema_database_statements_small.sql | 25 --- .../int_schema_database_statements_small.sql | 25 --- .../ob_schema_database_statements_small.sql | 27 ---- 14 files changed, 236 insertions(+), 406 deletions(-) rename ef-migration/infrastructure/sql-server/{full_schemas => }/extract_constraints.sh (98%) rename ef-migration/infrastructure/sql-server/{full_schemas => }/extract_indexes.sh (99%) rename ef-migration/infrastructure/sql-server/{full_schemas => }/extract_procedures.sh (99%) create mode 100755 ef-migration/infrastructure/sql-server/extract_tables.sh rename ef-migration/infrastructure/sql-server/{full_schemas => }/extract_views.sh (98%) delete mode 100755 ef-migration/infrastructure/sql-server/full_schemas/extract_tables.sh delete mode 100755 ef-migration/infrastructure/sql-server/full_schemas/parse_sql.sh delete mode 100644 ef-migration/infrastructure/sql-server/small_schemas/dbo_schema_database_statements_small.sql delete mode 100644 ef-migration/infrastructure/sql-server/small_schemas/fp_schema_database_statements_small.sql delete mode 100644 ef-migration/infrastructure/sql-server/small_schemas/fw_schema_database_statements_small.sql delete mode 100644 ef-migration/infrastructure/sql-server/small_schemas/int_schema_database_statements_small.sql delete mode 100644 ef-migration/infrastructure/sql-server/small_schemas/ob_schema_database_statements_small.sql diff --git a/ef-migration/infrastructure/sql-server/Dockerfile b/ef-migration/infrastructure/sql-server/Dockerfile index af53d90..635ecc5 100644 --- a/ef-migration/infrastructure/sql-server/Dockerfile +++ b/ef-migration/infrastructure/sql-server/Dockerfile @@ -8,7 +8,7 @@ ENV ACCEPT_EULA=Y \ DROP_DATABASE=false \ PATH="/opt/mssql-tools/bin:${PATH}" -# Install sqlcmd utility +# Install sqlcmd utility and other required packages USER root RUN apt-get update && \ apt-get install -y wget software-properties-common gnupg2 && \ @@ -21,16 +21,23 @@ RUN apt-get update && \ # Create app directory and schemas subdirectory in one layer WORKDIR /usr/src/app -RUN mkdir -p schemas +RUN mkdir -p schemas && \ + mkdir -p sql_objects/{tables,constraints,foreign_keys,indexes/{clustered,nonclustered,unique_clustered},views,procedures} && \ + chown -R mssql:mssql /usr/src/app && \ + chmod -R 755 /usr/src/app -# Copy all SQL files in a single layer to reduce image size +# Copy all SQL files and scripts in a single layer to reduce image size COPY ./sql-server/schemas/*.sql ./schemas/ COPY ./sql-server/init.sql ./ COPY ./sql-server/setup.sh ./ +COPY ./sql-server/extract_*.sh ./ -# Fix line endings and make setup script executable +# Fix line endings and make all scripts executable RUN sed -i 's/\r$//' setup.sh && \ - chmod +x setup.sh + sed -i 's/\r$//' extract_*.sh && \ + chmod +x setup.sh && \ + chmod +x extract_*.sh && \ + chown -R mssql:mssql /usr/src/app # Switch back to mssql user USER mssql diff --git a/ef-migration/infrastructure/sql-server/full_schemas/extract_constraints.sh b/ef-migration/infrastructure/sql-server/extract_constraints.sh similarity index 98% rename from ef-migration/infrastructure/sql-server/full_schemas/extract_constraints.sh rename to ef-migration/infrastructure/sql-server/extract_constraints.sh index a4ce1d8..cfe2b2a 100755 --- a/ef-migration/infrastructure/sql-server/full_schemas/extract_constraints.sh +++ b/ef-migration/infrastructure/sql-server/extract_constraints.sh @@ -12,6 +12,9 @@ BASE_DIR="sql_objects" # Create directory structure mkdir -p "$BASE_DIR"/{constraints,foreign_keys} +# Ensure proper permissions +chmod -R 755 "$BASE_DIR" + # Function to clean filename clean_filename() { # Remove brackets, convert dots and spaces to underscores, remove parentheses diff --git a/ef-migration/infrastructure/sql-server/full_schemas/extract_indexes.sh b/ef-migration/infrastructure/sql-server/extract_indexes.sh similarity index 99% rename from ef-migration/infrastructure/sql-server/full_schemas/extract_indexes.sh rename to ef-migration/infrastructure/sql-server/extract_indexes.sh index 89037dc..df0aa95 100755 --- a/ef-migration/infrastructure/sql-server/full_schemas/extract_indexes.sh +++ b/ef-migration/infrastructure/sql-server/extract_indexes.sh @@ -14,6 +14,9 @@ mkdir -p "$BASE_DIR/indexes/clustered" mkdir -p "$BASE_DIR/indexes/nonclustered" mkdir -p "$BASE_DIR/indexes/unique_clustered" +# Ensure proper permissions +chmod -R 755 "$BASE_DIR" + # Function to clean filename clean_filename() { # Remove brackets, convert dots and spaces to underscores, remove parentheses diff --git a/ef-migration/infrastructure/sql-server/full_schemas/extract_procedures.sh b/ef-migration/infrastructure/sql-server/extract_procedures.sh similarity index 99% rename from ef-migration/infrastructure/sql-server/full_schemas/extract_procedures.sh rename to ef-migration/infrastructure/sql-server/extract_procedures.sh index 674bea6..62add30 100755 --- a/ef-migration/infrastructure/sql-server/full_schemas/extract_procedures.sh +++ b/ef-migration/infrastructure/sql-server/extract_procedures.sh @@ -12,6 +12,9 @@ BASE_DIR="sql_objects" # Create directory structure mkdir -p "$BASE_DIR/procedures" +# Ensure proper permissions +chmod -R 755 "$BASE_DIR" + # Function to clean filename clean_filename() { # Remove brackets, convert dots and spaces to underscores, remove parentheses diff --git a/ef-migration/infrastructure/sql-server/extract_tables.sh b/ef-migration/infrastructure/sql-server/extract_tables.sh new file mode 100755 index 0000000..5948bd4 --- /dev/null +++ b/ef-migration/infrastructure/sql-server/extract_tables.sh @@ -0,0 +1,150 @@ +#!/bin/bash + +# Check if input file is provided +if [ $# -ne 1 ]; then + echo "Usage: $0 " + exit 1 +fi + +SQL_FILE="$1" +BASE_DIR="/usr/src/app/sql_objects" # Use absolute path + +# Create directory structure with proper permissions +echo "Creating directory structure at $BASE_DIR/tables" +mkdir -p "$BASE_DIR/tables" +chmod -R 777 "$BASE_DIR" # Give full permissions for testing + +# Function to check if table is temporary +is_temporary_table() { + local table_name="$1" + if echo "$table_name" | grep -iE "^(#|tmp_|temp_|temporary_|import_|viewimport_)" >/dev/null; then + return 0 # true in bash + else + return 1 # false in bash + fi +} + +# Function to clean filename +clean_filename() { + # Remove brackets, convert dots and spaces to underscores, remove parentheses + echo "$1" | sed 's/\[\|\]//g' | tr '.' '_' | tr ' ' '_' | sed 's/[()]//g' | sed 's/__*/_/g' | sed 's/_$//' +} + +# Function to extract table name with better schema handling +extract_table_name() { + local create_statement="$1" + # First, try to match schema.table pattern with brackets + local table_name=$(echo "$create_statement" | sed -nE 's/.*CREATE[[:space:]]+TABLE[[:space:]]+\[([^]]+)\]\.\[([^]]+)\].*/\1.\2/p') + + if [ -z "$table_name" ]; then + # Try to match schema.table pattern without brackets + table_name=$(echo "$create_statement" | sed -nE 's/.*CREATE[[:space:]]+TABLE[[:space:]]+([^.[:space:]]+)\.([^.[:space:]]+).*/\1.\2/p') + fi + + if [ -z "$table_name" ]; then + # Try to match just table name with brackets + table_name=$(echo "$create_statement" | sed -nE 's/.*CREATE[[:space:]]+TABLE[[:space:]]+\[([^]]+)\].*/\1/p') + fi + + if [ -z "$table_name" ]; then + # Try to match just table name without brackets + table_name=$(echo "$create_statement" | sed -nE 's/.*CREATE[[:space:]]+TABLE[[:space:]]+([^[:space:]]+).*/\1/p') + fi + + echo "$table_name" +} + +# Function to process each CREATE TABLE statement +process_table() { + local table_statement="$1" + local table_name=$(extract_table_name "$table_statement") + + # Debug output + echo "Extracted table name: $table_name" + + # Skip if we couldn't extract table name + if [ -z "$table_name" ]; then + echo "Warning: Could not extract table name from statement:" + echo "$table_statement" | head -n 1 + return + fi + + # Check if it's a temporary table + if is_temporary_table "$table_name"; then + echo "Skipping temporary table: $table_name" + return + fi + + # Clean filename and create full path + clean_name=$(clean_filename "${table_name}") + output_file="$BASE_DIR/tables/${clean_name}.sql" + + echo "Attempting to write to: $output_file" + # Create the file with proper error handling + if ! echo "$table_statement" > "$output_file" 2>/dev/null; then + echo "Error writing to $output_file" + echo "Current permissions:" + ls -la "$BASE_DIR/tables" + return 1 + fi + + echo "Successfully created: $output_file" +} + +# Main processing function +extract_tables() { + local current_statement="" + local capture_table=false + + # Read the file line by line + while IFS= read -r line || [ -n "$line" ]; do + # Skip empty lines and pure comment lines + if [ -z "${line// }" ] || [[ "$line" =~ ^[[:space:]]*-- ]]; then + continue + fi + + # Check for CREATE TABLE statement + if echo "$line" | grep -i "CREATE[[:space:]]\+TABLE" > /dev/null; then + # Debug output + echo "Found CREATE TABLE statement: $line" + local table_name=$(extract_table_name "$line") + echo "Extracted table name from line: $table_name" + + if ! is_temporary_table "$table_name"; then + capture_table=true + current_statement="$line" + else + echo "Skipping temporary table: $table_name" + fi + continue + fi + + # If we're capturing a table + if $capture_table; then + current_statement+=$'\n'"$line" + + # If we find a GO statement, process the table + if echo "$line" | grep -i "^[[:space:]]*GO[[:space:]]*$" > /dev/null; then + process_table "$current_statement" + capture_table=false + current_statement="" + fi + fi + done < "$SQL_FILE" + + # Process any remaining table statement + if $capture_table && [ -n "$current_statement" ]; then + process_table "$current_statement" + fi +} + +# Remove comment lines and process +echo "Starting table extraction from $SQL_FILE to $BASE_DIR/tables" +echo "Current working directory: $(pwd)" +echo "Directory contents before extraction:" +ls -la "$BASE_DIR/tables" + +sed 's/--.*$//' "$SQL_FILE" | extract_tables + +echo "Extraction completed. Directory contents after extraction:" +ls -la "$BASE_DIR/tables" \ No newline at end of file diff --git a/ef-migration/infrastructure/sql-server/full_schemas/extract_views.sh b/ef-migration/infrastructure/sql-server/extract_views.sh similarity index 98% rename from ef-migration/infrastructure/sql-server/full_schemas/extract_views.sh rename to ef-migration/infrastructure/sql-server/extract_views.sh index a708894..a138fac 100755 --- a/ef-migration/infrastructure/sql-server/full_schemas/extract_views.sh +++ b/ef-migration/infrastructure/sql-server/extract_views.sh @@ -12,6 +12,9 @@ BASE_DIR="sql_objects" # Create directory structure mkdir -p "$BASE_DIR/views" +# Ensure proper permissions +chmod -R 755 "$BASE_DIR" + # Function to clean filename clean_filename() { # Remove brackets, convert dots and spaces to underscores, remove parentheses diff --git a/ef-migration/infrastructure/sql-server/full_schemas/extract_tables.sh b/ef-migration/infrastructure/sql-server/full_schemas/extract_tables.sh deleted file mode 100755 index d9959d2..0000000 --- a/ef-migration/infrastructure/sql-server/full_schemas/extract_tables.sh +++ /dev/null @@ -1,105 +0,0 @@ -#!/bin/bash - -# Check if input file is provided -if [ $# -ne 1 ]; then - echo "Usage: $0 " - exit 1 -fi - -SQL_FILE="$1" -BASE_DIR="sql_objects" - -# Create directory structure -mkdir -p "$BASE_DIR/tables" - -# Function to clean filename -clean_filename() { - # Remove brackets, convert dots and spaces to underscores, remove parentheses - echo "$1" | sed 's/\[\|\]//g' | tr '.' '_' | tr ' ' '_' | sed 's/[()]//g' | sed 's/__*/_/g' | sed 's/_$//' -} - -# Function to check if table is temporary -is_temporary_table() { - local table_name="$1" - if echo "$table_name" | grep -iE "temp|tmp|temporary|import_|viewimport_" >/dev/null; then - return 0 # true in bash - else - return 1 # false in bash - fi -} - -# Function to extract CREATE TABLE statements only -extract_tables() { - local current_object="" - local capture_table=false - local table_name="" - - # Read the file line by line - while IFS= read -r line || [ -n "$line" ]; do - # Check if we've found a CREATE TABLE statement - if echo "$line" | grep -i "CREATE[[:space:]]\+TABLE" >/dev/null; then - # Extract table name and check if it's temporary - table_name=$(echo "$line" | sed -E 's/.*CREATE[[:space:]]+TABLE[[:space:]]+\[?([^\]]+)\]?.*/\1/') - - if is_temporary_table "$table_name"; then - echo "Skipping temporary table: $table_name" - continue - fi - - capture_table=true - current_object="$line"$'\n' - continue - fi - - # If we're capturing a table and find a following CREATE or ALTER statement, stop capturing - if $capture_table; then - if echo "$line" | grep -i "^[[:space:]]*CREATE\|^[[:space:]]*ALTER" >/dev/null; then - # Save the current table before starting a new object - if [ -n "$table_name" ]; then - clean_name=$(clean_filename "$table_name") - output_file="$BASE_DIR/tables/${clean_name}.sql" - echo "$current_object" > "$output_file" - echo "Created: $output_file" - fi - capture_table=false - current_object="" - table_name="" - continue - fi - - # Add line to current object if we're still capturing - current_object+="$line"$'\n' - - # If we find a GO statement, save the table - if echo "$line" | grep -i "^[[:space:]]*GO[[:space:]]*$" >/dev/null; then - if [ -n "$table_name" ]; then - clean_name=$(clean_filename "$table_name") - output_file="$BASE_DIR/tables/${clean_name}.sql" - echo "$current_object" > "$output_file" - echo "Created: $output_file" - fi - capture_table=false - current_object="" - table_name="" - fi - fi - done < "$SQL_FILE" -} - -# Remove comment lines starting with -- -echo "Extracting CREATE TABLE statements..." -sed 's/--.*$//' "$SQL_FILE" | extract_tables - -echo "CREATE TABLE statements have been saved in $BASE_DIR/tables/" - -# Count files -count=$(ls -1 "$BASE_DIR/tables"/*.sql 2>/dev/null | wc -l) -echo -e "\nTotal tables extracted: $count" - -# List extracted tables -echo -e "\nExtracted tables:" -for table in "$BASE_DIR/tables"/*.sql; do - if [ -f "$table" ]; then - echo "- $(basename "$table")" - fi -done \ No newline at end of file diff --git a/ef-migration/infrastructure/sql-server/full_schemas/parse_sql.sh b/ef-migration/infrastructure/sql-server/full_schemas/parse_sql.sh deleted file mode 100755 index afa86a4..0000000 --- a/ef-migration/infrastructure/sql-server/full_schemas/parse_sql.sh +++ /dev/null @@ -1,116 +0,0 @@ -#!/bin/bash - -# Check if input file is provided -if [ $# -ne 1 ]; then - echo "Usage: $0 " - exit 1 -fi - -SQL_FILE="$1" -BASE_DIR="sql_objects" - -# Create directory structure -mkdir -p "$BASE_DIR"/{tables,views,procedures,constraints,indexes,alter_tables} - -# Function to clean filename -clean_filename() { - echo "$1" | sed 's/\[\|\]//g' | tr '.' '_' -} - -# Function to extract SQL objects and save to files -extract_objects() { - local current_object="" - local object_type="" - local object_name="" - local table_name="" - - # Read the file line by line - while IFS= read -r line || [ -n "$line" ]; do - # Skip empty lines at the start - if [ -z "$current_object" ] && [ -z "${line// }" ]; then - continue - fi - - # Add line to current object - current_object+="$line"$'\n' - - # Check if we've reached the end of an object (GO statement) - if echo "$line" | grep -i "^[[:space:]]*GO[[:space:]]*$" >/dev/null; then - # Determine object type and name - if echo "$current_object" | grep -i "CREATE[[:space:]]\+TABLE" >/dev/null; then - object_type="tables" - object_name=$(echo "$current_object" | grep -i "CREATE[[:space:]]\+TABLE" | sed -E 's/.*CREATE[[:space:]]+TABLE[[:space:]]+\[?([^\]]+)\]?.*/\1/') - elif echo "$current_object" | grep -i "CREATE[[:space:]]\+VIEW" >/dev/null; then - object_type="views" - object_name=$(echo "$current_object" | grep -i "CREATE[[:space:]]\+VIEW" | sed -E 's/.*CREATE[[:space:]]+VIEW[[:space:]]+\[?([^\]]+)\]?.*/\1/') - elif echo "$current_object" | grep -i "CREATE[[:space:]]\+PROC" >/dev/null; then - object_type="procedures" - object_name=$(echo "$current_object" | grep -i "CREATE[[:space:]]\+PROC[[:space:]EDURE]*" | sed -E 's/.*CREATE[[:space:]]+PROC[[:space:]EDURE]*[[:space:]]+\[?([^\]]+)\]?.*/\1/') - elif echo "$current_object" | grep -i "ALTER[[:space:]]\+TABLE" >/dev/null; then - # Extract table name and constraint name if it exists - table_name=$(echo "$current_object" | grep -i "ALTER[[:space:]]\+TABLE" | sed -E 's/.*ALTER[[:space:]]+TABLE[[:space:]]+\[?([^\]]+)\]?.*/\1/') - - if echo "$current_object" | grep -i "ADD[[:space:]]\+CONSTRAINT" >/dev/null; then - object_type="constraints" - object_name=$(echo "$current_object" | grep -i "CONSTRAINT" | sed -E 's/.*CONSTRAINT[[:space:]]+\[?([^\]]+)\]?.*/\1/') - else - object_type="alter_tables" - object_name="${table_name}_alter_$(date +%s%N | cut -b1-5)" - fi - elif echo "$current_object" | grep -i "CREATE.*INDEX" >/dev/null; then - object_type="indexes" - object_name=$(echo "$current_object" | grep -i "INDEX" | sed -E 's/.*INDEX[[:space:]]+\[?([^\]]+)\]?.*/\1/') - fi - - # If we identified an object type and name, save it - if [ -n "$object_type" ] && [ -n "$object_name" ]; then - # Clean the filename - clean_name=$(clean_filename "$object_name") - output_file="$BASE_DIR/$object_type/$clean_name.sql" - - # For alter_tables, make sure we don't overwrite existing files - if [ "$object_type" = "alter_tables" ]; then - counter=1 - base_file="$BASE_DIR/$object_type/$clean_name" - while [ -f "${base_file}.sql" ]; do - clean_name="${clean_name}_${counter}" - counter=$((counter + 1)) - done - output_file="$base_file.sql" - fi - - # Save the object to file - echo "$current_object" > "$output_file" - echo "Created: $output_file" - fi - - # Reset for next object - current_object="" - object_type="" - object_name="" - table_name="" - fi - done < "$SQL_FILE" -} - -# Remove comment lines starting with -- -echo "Removing comments and processing SQL file..." -sed 's/--.*$//' "$SQL_FILE" | extract_objects - -echo "SQL objects have been organized in the $BASE_DIR directory." -echo " -Directory structure: -$BASE_DIR/ -├── tables/ -├── views/ -├── procedures/ -├── constraints/ -├── indexes/ -└── alter_tables/" - -# Count files in each directory -echo -e "\nFile counts:" -for dir in tables views procedures constraints indexes alter_tables; do - count=$(ls -1 "$BASE_DIR/$dir"/*.sql 2>/dev/null | wc -l) - echo "$dir: $count files" -done \ No newline at end of file diff --git a/ef-migration/infrastructure/sql-server/setup.sh b/ef-migration/infrastructure/sql-server/setup.sh index 3730046..6e0245c 100644 --- a/ef-migration/infrastructure/sql-server/setup.sh +++ b/ef-migration/infrastructure/sql-server/setup.sh @@ -76,31 +76,75 @@ else exit 1 fi - # Run all schema scripts in the schemas directory - echo "Running schema scripts..." - for f in /usr/src/app/schemas/*.sql + # Clean up existing files in sql_objects directories + echo "Cleaning up existing files..." + rm -f /usr/src/app/sql_objects/*/*.sql + rm -f /usr/src/app/sql_objects/indexes/*/*.sql + + # Process each schema file through the extraction scripts + echo "Processing schema files..." + for schema_file in /usr/src/app/schemas/*.sql do - echo "Processing $f..." + echo "Processing schema file: $schema_file" - # Create a temporary file - temp_file=$(mktemp) - - # Process the file: add newlines around GO statements - sed 's/GO/\nGO\n/g' "$f" > "$temp_file" - - # Execute the processed file - sqlcmd -S localhost -U sa -P $SA_PASSWORD -d st-database -i "$temp_file" + # Extract different types of SQL objects + bash /usr/src/app/extract_tables.sh "$schema_file" if [ $? -ne 0 ]; then - echo "Warning: Script $f had some errors but continuing..." - rm "$temp_file" # Clean up temp file - continue + echo "Warning: Table extraction had some errors but continuing..." fi - # Clean up temp file - rm "$temp_file" + bash /usr/src/app/extract_constraints.sh "$schema_file" + bash /usr/src/app/extract_indexes.sh "$schema_file" + bash /usr/src/app/extract_views.sh "$schema_file" + bash /usr/src/app/extract_procedures.sh "$schema_file" done - echo "All scripts executed. SQL Server is ready." + # Function to execute SQL files from a directory + execute_sql_files() { + local dir=$1 + local type=$2 + + if [ -d "$dir" ] && [ "$(ls -A $dir 2>/dev/null)" ]; then + echo "Executing $type..." + for sql_file in "$dir"/*.sql; do + if [ -f "$sql_file" ]; then + echo "Executing $sql_file..." + sqlcmd -S localhost -U sa -P $SA_PASSWORD -d st-database -i "$sql_file" + if [ $? -ne 0 ]; then + echo "Warning: Error executing $sql_file but continuing..." + fi + fi + done + else + echo "No files found in $dir" + fi + } + + # Execute SQL objects in the correct order + echo "Executing SQL objects in order..." + + # 1. Tables + execute_sql_files "sql_objects/tables" "tables" + + # 2. Constraints + execute_sql_files "sql_objects/constraints" "constraints" + execute_sql_files "sql_objects/foreign_keys" "foreign keys" + + # 3. Indexes + execute_sql_files "sql_objects/indexes/clustered" "clustered indexes" + execute_sql_files "sql_objects/indexes/unique_clustered" "unique clustered indexes" + execute_sql_files "sql_objects/indexes/nonclustered" "nonclustered indexes" + + # 4. Views + execute_sql_files "sql_objects/views" "views" + + # 5. Stored Procedures + execute_sql_files "sql_objects/procedures" "stored procedures" + + # Clean up + echo "Cleaning up..." + rm -rf sql_objects + echo "SQL object execution completed" fi # Keep container running diff --git a/ef-migration/infrastructure/sql-server/small_schemas/dbo_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/small_schemas/dbo_schema_database_statements_small.sql deleted file mode 100644 index 7b675a2..0000000 --- a/ef-migration/infrastructure/sql-server/small_schemas/dbo_schema_database_statements_small.sql +++ /dev/null @@ -1,42 +0,0 @@ --- SCHEMA: dbo - ---------------------------------------------- --- TABLES ---------------------------------------------- - - ---------------------------------------------- --- dbo.AMAssumptionView ------------------ ---------------------------------------------- -DROP TABLE [dbo].[AMAssumptionView]; -GO - -CREATE TABLE [dbo].[AMAssumptionView] ( - [AssumptionViewGUID] uniqueidentifier NOT NULL, - [AssumptionGroupGUID] uniqueidentifier NOT NULL, - [Name] nvarchar(450) NOT NULL, - [ColumnWidths] varchar(8000) NOT NULL, - [AssumptionJoinDataGUID] uniqueidentifier NOT NULL, - [FolderGUID] uniqueidentifier NOT NULL, - [IsDistributionModeActive] bit NOT NULL, - [DistributionInfo] xml NOT NULL, - [ProviderGUID] uniqueidentifier NOT NULL, - [CreatedDate] datetime NOT NULL, - [CreatedBy] uniqueidentifier NOT NULL, - [LastUsedDate] datetime NOT NULL, - PRIMARY KEY ([AssumptionViewGUID]) -); -GO -ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_CreatedBy] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [CreatedBy]; GO -ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_CreatedDate] DEFAULT (getdate()) FOR [CreatedDate]; GO -ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_LastUsedDate] DEFAULT (getdate()) FOR [LastUsedDate]; GO -ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_Table_1_AssumptionViewGUID] DEFAULT (newid()) FOR [AssumptionViewGUID]; GO -ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_ASSUMPTIONGROUPGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssumptionGroupGUID]; GO -ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_NAME] DEFAULT ('') FOR [Name]; GO -ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_COLUMNWIDTHS] DEFAULT ('') FOR [ColumnWidths]; GO -ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_ASSUMPTIONCUBEGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [AssumptionJoinDataGUID]; GO -ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_FOLDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [FolderGUID]; GO -ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_ISDISTRIBUTIONMODEACTIVE] DEFAULT ((0)) FOR [IsDistributionModeActive]; GO -ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_DISTRIBUTIONINFOXML] DEFAULT ('') FOR [DistributionInfo]; GO -ALTER TABLE [dbo].[AMAssumptionView] ADD CONSTRAINT [DF_AMAssumptionView_PROVIDERGUID] DEFAULT ('00000000-0000-0000-0000-000000000000') FOR [ProviderGUID]; GO - diff --git a/ef-migration/infrastructure/sql-server/small_schemas/fp_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/small_schemas/fp_schema_database_statements_small.sql deleted file mode 100644 index 31b867b..0000000 --- a/ef-migration/infrastructure/sql-server/small_schemas/fp_schema_database_statements_small.sql +++ /dev/null @@ -1,43 +0,0 @@ --- SCHEMA: fp - ---------------------------------------------- --- TABLES ---------------------------------------------- - - ---------------------------------------------- --- fp.APAdminPerformanceTest ------------------ ---------------------------------------------- -DROP TABLE [fp].[APAdminPerformanceTest]; -GO - -CREATE TABLE [fp].[APAdminPerformanceTest] ( - [TestID] uniqueidentifier NOT NULL, - [SortOrder] int NOT NULL, - [TestTypeID] tinyint NOT NULL, - [TestName] nvarchar(100) NOT NULL, - [Description] nvarchar(3000) NOT NULL, - [BudgetConfigID] int NOT NULL, - [SourceDimensionalityJSON] nvarchar(max) NOT NULL, - [TestDetailJSON] nvarchar(max) NOT NULL, - [IsActive] bit NOT NULL, - [CreatedBy] nvarchar(1000) NOT NULL, - [Target] int NOT NULL, - [MaximumTheshold] int NOT NULL, - [PickableDepartments] nvarchar(max) NOT NULL, - PRIMARY KEY ([TestID]) -); -GO -ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Targe__5375AD4D] DEFAULT ((0)) FOR [Target]; GO -ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Maxim__5469D186] DEFAULT ((0)) FOR [MaximumTheshold]; GO -ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Picka__565219F8] DEFAULT ('') FOR [PickableDepartments]; GO -ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__TestI__6B4249E6] DEFAULT (newid()) FOR [TestID]; GO -ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__SortO__6C366E1F] DEFAULT ((0)) FOR [SortOrder]; GO -ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__TestT__6D2A9258] DEFAULT ((0)) FOR [TestTypeID]; GO -ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__TestN__6E1EB691] DEFAULT ('') FOR [TestName]; GO -ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Descr__6F12DACA] DEFAULT ('') FOR [Description]; GO -ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Budge__70FB233C] DEFAULT ((0)) FOR [BudgetConfigID]; GO -ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Sourc__71EF4775] DEFAULT ('') FOR [SourceDimensionalityJSON]; GO -ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__TestD__72E36BAE] DEFAULT ('') FOR [TestDetailJSON]; GO -ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__IsAct__73D78FE7] DEFAULT ((0)) FOR [IsActive]; GO -ALTER TABLE [fp].[APAdminPerformanceTest] ADD CONSTRAINT [DF__APAdminPe__Creat__74CBB420] DEFAULT ('') FOR [CreatedBy]; GO diff --git a/ef-migration/infrastructure/sql-server/small_schemas/fw_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/small_schemas/fw_schema_database_statements_small.sql deleted file mode 100644 index 510088c..0000000 --- a/ef-migration/infrastructure/sql-server/small_schemas/fw_schema_database_statements_small.sql +++ /dev/null @@ -1,25 +0,0 @@ --- SCHEMA: fw - ---------------------------------------------- --- TABLES ---------------------------------------------- - - ---------------------------------------------- --- fw.ABBBudgetedCostPerRVU ------------------ ---------------------------------------------- -DROP TABLE [fw].[ABBBudgetedCostPerRVU]; -GO - -CREATE TABLE [fw].[ABBBudgetedCostPerRVU] ( - [DepartmentID] int NOT NULL, - [AccountID] int NOT NULL, - [JobCodeID] int NOT NULL, - [PayCodeID] int NOT NULL, - [CostComponentID] int NOT NULL, - [CostingConfigGuid] uniqueidentifier NOT NULL, - [VariableDirectUnitCostPerRVU] decimal NULL, - [TotalVariableDirectCost] decimal NULL, - [TotalCost] decimal NULL -); -GO diff --git a/ef-migration/infrastructure/sql-server/small_schemas/int_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/small_schemas/int_schema_database_statements_small.sql deleted file mode 100644 index 6ce75ad..0000000 --- a/ef-migration/infrastructure/sql-server/small_schemas/int_schema_database_statements_small.sql +++ /dev/null @@ -1,25 +0,0 @@ --- SCHEMA: int - ---------------------------------------------- --- TABLES ---------------------------------------------- - - ---------------------------------------------- --- int.AggregatePostDIHistory ------------------ ---------------------------------------------- -DROP TABLE [int].[AggregatePostDIHistory]; -GO - -CREATE TABLE [int].[AggregatePostDIHistory] ( - [AggregatePostDIHistoryGuid] uniqueidentifier NOT NULL, - [CreatedAtUtc] datetime NOT NULL, - [LastRanUtc] datetime NOT NULL, - [AggregatePostDIStatus] int NOT NULL, - PRIMARY KEY ([AggregatePostDIHistoryGuid]) -); -GO -ALTER TABLE [int].[AggregatePostDIHistory] ADD CONSTRAINT [DF__Aggregate__Aggre__4EDF0E15] DEFAULT (newid()) FOR [AggregatePostDIHistoryGuid]; GO -ALTER TABLE [int].[AggregatePostDIHistory] ADD CONSTRAINT [DF__Aggregate__Creat__4FD3324E] DEFAULT (getutcdate()) FOR [CreatedAtUtc]; GO -ALTER TABLE [int].[AggregatePostDIHistory] ADD CONSTRAINT [DF__Aggregate__LastR__50C75687] DEFAULT ('1900-01-01 00:00:00.000') FOR [LastRanUtc]; GO -ALTER TABLE [int].[AggregatePostDIHistory] ADD CONSTRAINT [DF__Aggregate__Aggre__51BB7AC0] DEFAULT ((0)) FOR [AggregatePostDIStatus]; GO diff --git a/ef-migration/infrastructure/sql-server/small_schemas/ob_schema_database_statements_small.sql b/ef-migration/infrastructure/sql-server/small_schemas/ob_schema_database_statements_small.sql deleted file mode 100644 index 43c249c..0000000 --- a/ef-migration/infrastructure/sql-server/small_schemas/ob_schema_database_statements_small.sql +++ /dev/null @@ -1,27 +0,0 @@ --- SCHEMA: ob - ---------------------------------------------- --- TABLES ---------------------------------------------- - - ---------------------------------------------- --- ob.AccountVariabilityOverride ------------------ ---------------------------------------------- -DROP TABLE [ob].[AccountVariabilityOverride]; -GO - -CREATE TABLE [ob].[AccountVariabilityOverride] ( - [AccountVariabilityOverrideID] int NOT NULL, - [DepartmentAssignment] nvarchar(800) NOT NULL, - [AccountAssignment] nvarchar(800) NOT NULL, - [PrecedentOrder] int NOT NULL, - [Variability] decimal NOT NULL, - PRIMARY KEY ([AccountVariabilityOverrideID]) -); -GO -ALTER TABLE [ob].[AccountVariabilityOverride] ADD CONSTRAINT [DF__AccountVa__Depar__0EB4746A] DEFAULT ('') FOR [DepartmentAssignment]; GO -ALTER TABLE [ob].[AccountVariabilityOverride] ADD CONSTRAINT [DF__AccountVa__Accou__0FA898A3] DEFAULT ('') FOR [AccountAssignment]; GO -ALTER TABLE [ob].[AccountVariabilityOverride] ADD CONSTRAINT [DF__AccountVa__Prece__109CBCDC] DEFAULT ((0)) FOR [PrecedentOrder]; GO -ALTER TABLE [ob].[AccountVariabilityOverride] ADD CONSTRAINT [DF__AccountVa__Varia__1190E115] DEFAULT ((0)) FOR [Variability]; GO - -- 2.45.2 From b32845f6567b07a4ba132493a3a6fd2f59fa0231 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Wed, 5 Feb 2025 03:40:32 +0000 Subject: [PATCH 24/31] Adjust setup.sh to check existing DB and include ReadMe --- .../infrastructure/Build-Containers.ps1 | 81 --------- .../infrastructure/Manage-Containers.ps1 | 89 --------- ef-migration/infrastructure/ReadMe.md | 171 ++++++++++++++++++ .../infrastructure/sql-server/setup.sh | 29 +-- 4 files changed, 186 insertions(+), 184 deletions(-) delete mode 100644 ef-migration/infrastructure/Build-Containers.ps1 delete mode 100644 ef-migration/infrastructure/Manage-Containers.ps1 create mode 100644 ef-migration/infrastructure/ReadMe.md diff --git a/ef-migration/infrastructure/Build-Containers.ps1 b/ef-migration/infrastructure/Build-Containers.ps1 deleted file mode 100644 index 6799c1c..0000000 --- a/ef-migration/infrastructure/Build-Containers.ps1 +++ /dev/null @@ -1,81 +0,0 @@ -# Build-Containers.ps1 -param ( - [switch]$Force -) - -$ErrorActionPreference = "Stop" - -function Test-WSLRequirements { - Write-Host "Checking WSL requirements..." -ForegroundColor Yellow - - # Check if WSL is installed - $wslInstalled = Get-Command wsl.exe -ErrorAction SilentlyContinue - if (-not $wslInstalled) { - Write-Host "WSL is not installed. Please run the following commands as Administrator:" -ForegroundColor Red - Write-Host "wsl --install" -ForegroundColor Yellow - Write-Host "Then restart your computer and run:" -ForegroundColor Yellow - Write-Host "wsl --install -d Ubuntu" -ForegroundColor Yellow - return $false - } - - # Check if any distribution is installed - $wslDistros = wsl --list - if ($LASTEXITCODE -ne 0 -or $wslDistros -match "no installed distributions") { - Write-Host "No WSL distribution found. Please run the following command as Administrator:" -ForegroundColor Red - Write-Host "wsl --install -d Ubuntu" -ForegroundColor Yellow - return $false - } - - # Check if Docker Desktop is running - $dockerPs = Get-Process "Docker Desktop" -ErrorAction SilentlyContinue - if (-not $dockerPs) { - Write-Host "Docker Desktop is not running. Please start Docker Desktop and try again." -ForegroundColor Red - return $false - } - - Write-Host "WSL requirements checked successfully!" -ForegroundColor Green - return $true -} - -# Check WSL requirements -if (-not (Test-WSLRequirements)) { - exit 1 -} - -Write-Host "Starting Docker build process..." -ForegroundColor Green - -# Define container names -$containerName = "st-db" -$imageName = "st-database" - -# Get the current script directory -$scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path -$sqlServerPath = Join-Path $scriptPath "sql-server" - -# Verify Dockerfile exists -if (-not (Test-Path (Join-Path $sqlServerPath "Dockerfile"))) { - Write-Host "Dockerfile not found in $sqlServerPath" -ForegroundColor Red - exit 1 -} - -try { - # Change to the SQL Server directory - Push-Location $sqlServerPath - - # Build the Docker image - Write-Host "Building Docker image '$imageName'..." -ForegroundColor Yellow - docker build -t $imageName . - - if ($LASTEXITCODE -eq 0) { - Write-Host "Docker image built successfully!" -ForegroundColor Green - } else { - Write-Host "Failed to build Docker image" -ForegroundColor Red - exit 1 - } -} catch { - Write-Host "An error occurred: $_" -ForegroundColor Red - exit 1 -} finally { - # Return to original directory - Pop-Location -} \ No newline at end of file diff --git a/ef-migration/infrastructure/Manage-Containers.ps1 b/ef-migration/infrastructure/Manage-Containers.ps1 deleted file mode 100644 index b5eab07..0000000 --- a/ef-migration/infrastructure/Manage-Containers.ps1 +++ /dev/null @@ -1,89 +0,0 @@ -# Manage-Containers.ps1 -param ( - [Parameter(Mandatory=$true)] - [ValidateSet('run', 'stop', 'remove')] - [string]$Action, - [switch]$Force -) - -$ErrorActionPreference = "Stop" - -# Define container names -$containerName = "st-db" -$imageName = "st-database" - -function Start-Container { - Write-Host "Starting container '$containerName'..." -ForegroundColor Yellow - - # Check if container exists and is stopped - $existingContainer = docker ps -a --filter "name=$containerName" --format "{{.Names}}" - if ($existingContainer) { - Write-Host "Container already exists, starting it..." -ForegroundColor Yellow - docker start $containerName - } else { - # Run new container - Write-Host "Creating and starting new container..." -ForegroundColor Yellow - docker run -d -p 1433:1433 --name $containerName $imageName - } - - if ($LASTEXITCODE -eq 0) { - Write-Host "Container started successfully!" -ForegroundColor Green - } else { - Write-Host "Failed to start container" -ForegroundColor Red - exit 1 - } -} - -function Stop-Container { - Write-Host "Stopping container '$containerName'..." -ForegroundColor Yellow - - # Check if container exists and is running - $runningContainer = docker ps --filter "name=$containerName" --format "{{.Names}}" - if ($runningContainer) { - docker stop $containerName - if ($LASTEXITCODE -eq 0) { - Write-Host "Container stopped successfully!" -ForegroundColor Green - } else { - Write-Host "Failed to stop container" -ForegroundColor Red - exit 1 - } - } else { - Write-Host "Container is not running" -ForegroundColor Yellow - } -} - -function Remove-Container { - Write-Host "Removing container '$containerName'..." -ForegroundColor Yellow - - # Stop container if running - $runningContainer = docker ps --filter "name=$containerName" --format "{{.Names}}" - if ($runningContainer) { - Write-Host "Stopping container first..." -ForegroundColor Yellow - docker stop $containerName - } - - # Remove container - $existingContainer = docker ps -a --filter "name=$containerName" --format "{{.Names}}" - if ($existingContainer) { - docker rm $containerName - if ($LASTEXITCODE -eq 0) { - Write-Host "Container removed successfully!" -ForegroundColor Green - } else { - Write-Host "Failed to remove container" -ForegroundColor Red - exit 1 - } - } else { - Write-Host "Container does not exist" -ForegroundColor Yellow - } -} - -try { - switch ($Action) { - 'run' { Start-Container } - 'stop' { Stop-Container } - 'remove' { Remove-Container } - } -} catch { - Write-Host "An error occurred: $_" -ForegroundColor Red - exit 1 -} \ No newline at end of file diff --git a/ef-migration/infrastructure/ReadMe.md b/ef-migration/infrastructure/ReadMe.md new file mode 100644 index 0000000..37cf0e7 --- /dev/null +++ b/ef-migration/infrastructure/ReadMe.md @@ -0,0 +1,171 @@ +# SQL Server Container Setup + +This repository contains a containerized SQL Server setup with initialization scripts and configuration options. + +## Prerequisites + +- Docker and Docker Compose installed on your system +- At least 2GB of available memory for SQL Server +- Port 1433 available on your host machine + +## Quick Start + +### Starting the Container + +With environment variables: +```bash +docker-compose -f docker-compose-infra.yml up -d +``` + +Without environment variables (uses defaults): +```bash +ACCEPT_EULA=Y MSSQL_PID=Express SA_PASSWORD=YourStrong@Passw0rd docker-compose -f docker-compose-infra.yml up -d +``` + +### Building the Container + +```bash +docker-compose -f docker-compose-infra.yml build +``` + +### Stopping and Removing the Container + +Stop the container: +```bash +docker-compose -f docker-compose-infra.yml down +``` + +Remove container and persistent volume: +```bash +docker-compose -f docker-compose-infra.yml down -v +``` + +## Configuration + +### Environment Variables + +| Variable | Description | Default Value | +|----------|-------------|---------------| +| SA_PASSWORD | SQL Server SA user password | YourStrong@Passw0rd | +| DROP_DATABASE | Flag to drop existing database on startup | false | +| ACCEPT_EULA | Accept SQL Server EULA | Y | +| MSSQL_PID | SQL Server edition | Express | + +### Ports + +- **1433**: SQL Server port (mapped to host machine) + +### Volumes + +- **sqlserver_data**: Persistent storage for SQL Server data +- **./logs**: Container logs directory + +## Setup Process + +The container uses `setup.sh` as its entry point, which handles the complete initialization process: + +### Startup Sequence + +1. Starts SQL Server in the background +2. Waits up to 50 seconds for SQL Server to be ready +3. Performs health checks using sqlcmd +4. Handles database initialization or reset based on environment variables + +### Database Management + +- Checks for existing database (`st-database`) +- Drops database if DROP_DATABASE=true +- Verifies database initialization status by checking for key tables +- Runs initialization scripts only if needed + +### Script Execution Order + +1. Runs `init.sql` to create the database and schemas +2. Executes all SQL scripts in the `schemas` directory +3. Handles GO statements automatically with proper spacing +4. Maintains container operation after setup + +### Error Handling + +- Provides detailed logging for each step +- Continues despite non-critical script errors +- Exits with proper status codes for critical failures + +## Database Initialization + +The container automatically: + +1. Initializes SQL Server +2. Creates the database 'st-database' if it doesn't exist +3. Creates the following schemas: + - fp + - fw + - int + - ob + +### Database Reset + +To reset the database: +```bash +DROP_DATABASE=true docker-compose -f docker-compose-infra.yml up -d +``` + +## Extract Scripts + +The container includes several utility scripts for managing database objects: + +### extract_tables.sh +- Extracts table definitions into separate files +- Usage: `./extract_tables.sh ` +- Output directory: `sql_objects/tables` + +### extract_constraints.sh +- Extracts table constraints and foreign keys +- Usage: `./extract_constraints.sh ` +- Output directories: + - `sql_objects/constraints` + - `sql_objects/foreign_keys` + +### extract_indexes.sh +- Extracts index definitions +- Usage: `./extract_indexes.sh ` +- Output directories: + - `sql_objects/indexes/clustered` + - `sql_objects/indexes/nonclustered` + - `sql_objects/indexes/unique_clustered` + +### extract_views.sh +- Extracts view definitions +- Usage: `./extract_views.sh ` +- Output directory: `sql_objects/views` + +### extract_procedures.sh +- Extracts stored procedure definitions +- Usage: `./extract_procedures.sh ` +- Output directory: `sql_objects/procedures` + +## Resource Limits + +The container is configured with the following resource constraints: + +- Memory: 2GB minimum (required for SQL Server) +- CPU: Limited to 1 core, with 0.25 core reserved + +## Health Checks + +The container includes a health check that: +- Runs every 10 seconds +- Verifies SQL Server connectivity +- Allows 10 retries before marking as unhealthy +- Has a 10-second startup grace period + +## Troubleshooting + +If the container fails to start: +1. Ensure at least 2GB of memory is available +2. Check the logs directory for detailed error messages +3. Verify the port 1433 is not in use by another service +4. Check SQL Server logs: `docker logs sql1` +5. Verify SQL Server is running: `docker exec sql1 /opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P $SA_PASSWORD -Q "SELECT @@VERSION"` + +The container will automatically restart unless explicitly stopped. \ No newline at end of file diff --git a/ef-migration/infrastructure/sql-server/setup.sh b/ef-migration/infrastructure/sql-server/setup.sh index 6e0245c..e194c9d 100644 --- a/ef-migration/infrastructure/sql-server/setup.sh +++ b/ef-migration/infrastructure/sql-server/setup.sh @@ -40,20 +40,21 @@ fi # Check if database already exists and has tables echo "Checking if database is already initialized..." -DB_INITIALIZED=$(sqlcmd -S localhost -U sa -P $SA_PASSWORD -Q " -IF EXISTS ( - SELECT 1 - FROM sys.databases - WHERE name = 'st-database' - AND EXISTS ( - SELECT 1 - FROM st-database.sys.tables - WHERE name = 'AMAssumptionView' - ) -) -SELECT 1 -ELSE -SELECT 0" -h -1) +echo "Checking if database is already initialized..." +DB_INITIALIZED=$(sqlcmd -S localhost -U sa -P $SA_PASSWORD -h -1 -Q " +DECLARE @DBExists BIT = 0; + +IF EXISTS (SELECT 1 FROM sys.databases WHERE name = 'st-database') +BEGIN + -- Set the context to the target database + EXEC('USE [st-database]; + IF EXISTS (SELECT 1 FROM sys.tables WHERE name = ''AMAssumptionView'') + BEGIN + SET @DBExists = 1; + END'); +END; + +SELECT @DBExists;") if [ "$DB_INITIALIZED" = "1" ]; then echo "Database st-database already exists and is initialized. Skipping setup." -- 2.45.2 From b12cc774e2d305ed91df4319eec9daa406a77f1f Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Thu, 6 Feb 2025 00:05:35 +0000 Subject: [PATCH 25/31] Adjust database initialization logic --- .../infrastructure/sql-server/setup.sh | 181 +++++++++--------- 1 file changed, 88 insertions(+), 93 deletions(-) diff --git a/ef-migration/infrastructure/sql-server/setup.sh b/ef-migration/infrastructure/sql-server/setup.sh index e194c9d..4a9b0fb 100644 --- a/ef-migration/infrastructure/sql-server/setup.sh +++ b/ef-migration/infrastructure/sql-server/setup.sh @@ -36,118 +36,113 @@ if [ "${DROP_DATABASE,,}" = "true" ]; then echo "Error dropping database" exit 1 fi -fi -# Check if database already exists and has tables -echo "Checking if database is already initialized..." -echo "Checking if database is already initialized..." -DB_INITIALIZED=$(sqlcmd -S localhost -U sa -P $SA_PASSWORD -h -1 -Q " -DECLARE @DBExists BIT = 0; + # Check if database already exists and has tables + echo "Checking if database is already initialized..." -IF EXISTS (SELECT 1 FROM sys.databases WHERE name = 'st-database') -BEGIN - -- Set the context to the target database - EXEC('USE [st-database]; - IF EXISTS (SELECT 1 FROM sys.tables WHERE name = ''AMAssumptionView'') - BEGIN - SET @DBExists = 1; - END'); -END; + # First check if database exists + DB_EXISTS=$(sqlcmd -S localhost -U sa -P $SA_PASSWORD -h -1 -Q " + IF EXISTS (SELECT 1 FROM sys.databases WHERE name = 'st-database') + SELECT 1 + ELSE + SELECT 0" | tr -d '[:space:]') -SELECT @DBExists;") + echo "Database exists check result: '$DB_EXISTS'" -if [ "$DB_INITIALIZED" = "1" ]; then - echo "Database st-database already exists and is initialized. Skipping setup." -else - echo "Database needs initialization. Starting setup..." - - # Create st-database if it doesn't exist - echo "Creating st-database if it doesn't exist..." - sqlcmd -S localhost -U sa -P $SA_PASSWORD -Q "IF NOT EXISTS (SELECT * FROM sys.databases WHERE name = 'st-database') CREATE DATABASE [st-database]" - if [ $? -ne 0 ]; then - echo "Error creating database" - exit 1 - fi - - # Run the initialization script - echo "Running initialization script..." - sqlcmd -S localhost -U sa -P $SA_PASSWORD -d st-database -i /usr/src/app/init.sql - if [ $? -ne 0 ]; then - echo "Error executing initialization script" - exit 1 - fi - - # Clean up existing files in sql_objects directories - echo "Cleaning up existing files..." - rm -f /usr/src/app/sql_objects/*/*.sql - rm -f /usr/src/app/sql_objects/indexes/*/*.sql - - # Process each schema file through the extraction scripts - echo "Processing schema files..." - for schema_file in /usr/src/app/schemas/*.sql - do - echo "Processing schema file: $schema_file" + if [ "$DB_EXISTS" = "1" ]; then + echo "Database st-database already exists and is initialized. Skipping setup." + else + echo "Database needs initialization. Starting setup..." - # Extract different types of SQL objects - bash /usr/src/app/extract_tables.sh "$schema_file" + # Create st-database if it doesn't exist + echo "Creating st-database if it doesn't exist..." + sqlcmd -S localhost -U sa -P $SA_PASSWORD -Q "IF NOT EXISTS (SELECT * FROM sys.databases WHERE name = 'st-database') CREATE DATABASE [st-database]" if [ $? -ne 0 ]; then - echo "Warning: Table extraction had some errors but continuing..." + echo "Error creating database" + exit 1 fi - - bash /usr/src/app/extract_constraints.sh "$schema_file" - bash /usr/src/app/extract_indexes.sh "$schema_file" - bash /usr/src/app/extract_views.sh "$schema_file" - bash /usr/src/app/extract_procedures.sh "$schema_file" - done - # Function to execute SQL files from a directory - execute_sql_files() { - local dir=$1 - local type=$2 + # Run the initialization script + echo "Running initialization script..." + sqlcmd -S localhost -U sa -P $SA_PASSWORD -d st-database -i /usr/src/app/init.sql + if [ $? -ne 0 ]; then + echo "Error executing initialization script" + exit 1 + fi + + # Clean up existing files in sql_objects directories + echo "Cleaning up existing files..." + rm -f /usr/src/app/sql_objects/*/*.sql + rm -f /usr/src/app/sql_objects/indexes/*/*.sql - if [ -d "$dir" ] && [ "$(ls -A $dir 2>/dev/null)" ]; then - echo "Executing $type..." - for sql_file in "$dir"/*.sql; do - if [ -f "$sql_file" ]; then - echo "Executing $sql_file..." - sqlcmd -S localhost -U sa -P $SA_PASSWORD -d st-database -i "$sql_file" - if [ $? -ne 0 ]; then - echo "Warning: Error executing $sql_file but continuing..." + # Process each schema file through the extraction scripts + echo "Processing schema files..." + for schema_file in /usr/src/app/schemas/*.sql + do + echo "Processing schema file: $schema_file" + + # Extract different types of SQL objects + bash /usr/src/app/extract_tables.sh "$schema_file" + if [ $? -ne 0 ]; then + echo "Warning: Table extraction had some errors but continuing..." + fi + + bash /usr/src/app/extract_constraints.sh "$schema_file" + bash /usr/src/app/extract_indexes.sh "$schema_file" + bash /usr/src/app/extract_views.sh "$schema_file" + bash /usr/src/app/extract_procedures.sh "$schema_file" + done + + # Function to execute SQL files from a directory + execute_sql_files() { + local dir=$1 + local type=$2 + + if [ -d "$dir" ] && [ "$(ls -A $dir 2>/dev/null)" ]; then + echo "Executing $type..." + for sql_file in "$dir"/*.sql; do + if [ -f "$sql_file" ]; then + echo "Executing $sql_file..." + sqlcmd -S localhost -U sa -P $SA_PASSWORD -d st-database -i "$sql_file" + if [ $? -ne 0 ]; then + echo "Warning: Error executing $sql_file but continuing..." + fi fi - fi - done - else - echo "No files found in $dir" - fi - } + done + else + echo "No files found in $dir" + fi + } - # Execute SQL objects in the correct order - echo "Executing SQL objects in order..." + # Execute SQL objects in the correct order + echo "Executing SQL objects in order..." - # 1. Tables - execute_sql_files "sql_objects/tables" "tables" + # 1. Tables + execute_sql_files "sql_objects/tables" "tables" - # 2. Constraints - execute_sql_files "sql_objects/constraints" "constraints" - execute_sql_files "sql_objects/foreign_keys" "foreign keys" + # 2. Constraints + execute_sql_files "sql_objects/constraints" "constraints" + execute_sql_files "sql_objects/foreign_keys" "foreign keys" - # 3. Indexes - execute_sql_files "sql_objects/indexes/clustered" "clustered indexes" - execute_sql_files "sql_objects/indexes/unique_clustered" "unique clustered indexes" - execute_sql_files "sql_objects/indexes/nonclustered" "nonclustered indexes" + # 3. Indexes + execute_sql_files "sql_objects/indexes/clustered" "clustered indexes" + execute_sql_files "sql_objects/indexes/unique_clustered" "unique clustered indexes" + execute_sql_files "sql_objects/indexes/nonclustered" "nonclustered indexes" - # 4. Views - execute_sql_files "sql_objects/views" "views" + # 4. Views + execute_sql_files "sql_objects/views" "views" - # 5. Stored Procedures - execute_sql_files "sql_objects/procedures" "stored procedures" + # 5. Stored Procedures + execute_sql_files "sql_objects/procedures" "stored procedures" - # Clean up - echo "Cleaning up..." - rm -rf sql_objects - echo "SQL object execution completed" + # Clean up + echo "Cleaning up..." + rm -rf sql_objects + echo "SQL object execution completed" + fi fi + # Keep container running while true; do sleep 1 -- 2.45.2 From eb2688e2eb888d598950564d00a83eb91a676b55 Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Wed, 5 Feb 2025 20:32:43 -0500 Subject: [PATCH 26/31] Create dll library --- ef-migration/Docker/install-docker.ps1 | 74 -- ef-migration/Docker/uninstall-docker.ps1 | 126 --- ef-migration/Strata.Code.sln | 22 + ef-migration/readme.md | 283 ++++++ .../src/Strata.Code.DataAccess/Class1.cs | 6 + .../Data/OnePlanDbContext.cs | 794 +++++++++++++++++ .../AddProviderEncountersDataForCharge.cs | 78 ++ .../Models/AddProviderSummary.cs | 57 ++ .../Models/AdjustmentChunkingConfiguration.cs | 26 + .../Models/ApedepartmentWorkflowStatus.cs | 31 + .../Models/Apeworkflow.cs | 33 + .../Models/BenefitsSpread.cs | 75 ++ .../Models/BudgetConfig.cs | 149 ++++ .../Models/BudgetConfigDefaultSetting.cs | 23 + .../Models/BudgetConfigSetting.cs | 23 + .../Models/BudgetRefreshRequest.cs | 78 ++ .../Models/BudgetRefreshRequestHistory.cs | 83 ++ .../ChargeVolumeAddProviderAdjustment.cs | 114 +++ .../Models/ChargeVolumeSpread.cs | 119 +++ .../Models/DataRefreshTargetThreshold.cs | 17 + .../DepartmentChargeVolumeAdjustment.cs | 76 ++ .../Models/DepartmentConfig.cs | 51 ++ .../Models/DimCategory.cs | 19 + .../Models/DimDepartment.cs | 478 +++++++++++ .../Models/EngineLog.cs | 52 ++ .../Models/EntityGroupConfig.cs | 121 +++ .../Models/FixChangeHistoryRequest.cs | 67 ++ .../Models/GeneralLedger.cs | 812 ++++++++++++++++++ .../GeneralLedgerInitialPlanConfigDetail.cs | 54 ++ .../Models/GeneralLedgerSpread.cs | 75 ++ .../Models/InitialPlanRule.cs | 47 + .../src/Strata.Code.DataAccess/Models/Lock.cs | 39 + .../OnePlanPerformanceTestValidationResult.cs | 135 +++ .../Models/PerformanceTestingSetting.cs | 35 + .../Models/ProviderCompensationSpread.cs | 95 ++ .../Models/SamplingLog.cs | 43 + .../Models/ScheduledRefreshRequest.cs | 33 + .../Models/ServiceLineEncounterSpread.cs | 79 ++ .../Models/SettingCategory.cs | 24 + .../Models/SpreadHistory.cs | 46 + .../Models/StaffingInitialPlanConfigDetail.cs | 69 ++ .../Models/StaffingSpread.cs | 83 ++ .../Models/StatisticsSpread.cs | 87 ++ .../Models/SystemSetting.cs | 37 + .../Models/TescheduledTask.cs | 66 ++ .../Models/UserProfile.cs | 91 ++ .../Models/ViewReimbursementAdjustment.cs | 74 ++ .../Models/ViewStaffingAdjustment.cs | 78 ++ .../Models/ViewStatisticsAdjustment.cs | 75 ++ .../Strata.Code.DataAccess.csproj | 21 + ef-migration/tools/scaffold.bat | 64 ++ 51 files changed, 5137 insertions(+), 200 deletions(-) delete mode 100644 ef-migration/Docker/install-docker.ps1 delete mode 100644 ef-migration/Docker/uninstall-docker.ps1 create mode 100644 ef-migration/Strata.Code.sln create mode 100644 ef-migration/readme.md create mode 100644 ef-migration/src/Strata.Code.DataAccess/Class1.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Data/OnePlanDbContext.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/AddProviderEncountersDataForCharge.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/AddProviderSummary.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/AdjustmentChunkingConfiguration.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/ApedepartmentWorkflowStatus.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/Apeworkflow.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/BenefitsSpread.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/BudgetConfig.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/BudgetConfigDefaultSetting.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/BudgetConfigSetting.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/BudgetRefreshRequest.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/BudgetRefreshRequestHistory.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/ChargeVolumeAddProviderAdjustment.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/ChargeVolumeSpread.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/DataRefreshTargetThreshold.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/DepartmentChargeVolumeAdjustment.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/DepartmentConfig.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/DimCategory.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/DimDepartment.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/EngineLog.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/EntityGroupConfig.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/FixChangeHistoryRequest.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/GeneralLedger.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/GeneralLedgerInitialPlanConfigDetail.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/GeneralLedgerSpread.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/InitialPlanRule.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/Lock.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/OnePlanPerformanceTestValidationResult.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/PerformanceTestingSetting.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/ProviderCompensationSpread.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/SamplingLog.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/ScheduledRefreshRequest.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/ServiceLineEncounterSpread.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/SettingCategory.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/SpreadHistory.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/StaffingInitialPlanConfigDetail.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/StaffingSpread.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/StatisticsSpread.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/SystemSetting.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/TescheduledTask.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/UserProfile.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/ViewReimbursementAdjustment.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/ViewStaffingAdjustment.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Models/ViewStatisticsAdjustment.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Strata.Code.DataAccess.csproj create mode 100644 ef-migration/tools/scaffold.bat diff --git a/ef-migration/Docker/install-docker.ps1 b/ef-migration/Docker/install-docker.ps1 deleted file mode 100644 index 8811f8f..0000000 --- a/ef-migration/Docker/install-docker.ps1 +++ /dev/null @@ -1,74 +0,0 @@ -# Requires -RunAsAdministrator - -function Write-Status($Message, $Type = "Info") { - switch ($Type) { - "Info" { $Color = "White" } - "Success" { $Color = "Green" } - "Error" { $Color = "Red" } - "Warning" { $Color = "Yellow" } - } - Write-Host ">>> $Message" -ForegroundColor $Color -} - -# Check if running as Administrator -$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) -if (-not $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { - Write-Status "This script must be run as Administrator" "Error" - Exit 1 -} - -try { - # Install Windows features required for Docker - Write-Status "Installing required Windows features..." "Info" - Enable-WindowsOptionalFeature -Online -FeatureName containers -All -NoRestart - - # Download Docker Engine - Write-Status "Downloading Docker Engine..." "Info" - $dockerUrl = "https://download.docker.com/win/static/stable/x86_64/docker-24.0.7.zip" - $dockerZip = "$env:TEMP\docker.zip" - $dockerPath = "C:\Program Files\Docker" - - Invoke-WebRequest -Uri $dockerUrl -OutFile $dockerZip - - # Extract Docker Engine - Write-Status "Extracting Docker Engine..." "Info" - Expand-Archive -Path $dockerZip -DestinationPath $env:ProgramFiles -Force - Remove-Item $dockerZip -Force - - # Add Docker to PATH - Write-Status "Adding Docker to PATH..." "Info" - $oldPath = [Environment]::GetEnvironmentVariable("Path", [EnvironmentVariableTarget]::Machine) - if (-not $oldPath.Contains($dockerPath)) { - $newPath = "$oldPath;$dockerPath" - [Environment]::SetEnvironmentVariable("Path", $newPath, [EnvironmentVariableTarget]::Machine) - } - - # Create Docker service - Write-Status "Creating Docker service..." "Info" - & "$dockerPath\dockerd.exe" --register-service - - # Start Docker service - Write-Status "Starting Docker service..." "Info" - Start-Service docker - - # Test Docker installation - Write-Status "Testing Docker installation..." "Info" - docker version - if ($LASTEXITCODE -eq 0) { - Write-Status "Docker Engine installed successfully!" "Success" - } else { - Write-Status "Docker installation completed but service test failed" "Warning" - } - - # Pull SQL Server image - Write-Status "Pulling SQL Server image..." "Info" - docker pull mcr.microsoft.com/mssql/server:2022-latest - - Write-Status "`nDocker Engine installation completed!" "Success" - Write-Status "You can now use Docker commands directly." "Info" - Write-Status "Please restart your computer to ensure all changes take effect." "Warning" - -} catch { - Write-Status "An error occurred: $_" "Error" - Exit 1 -} \ No newline at end of file diff --git a/ef-migration/Docker/uninstall-docker.ps1 b/ef-migration/Docker/uninstall-docker.ps1 deleted file mode 100644 index b348c5d..0000000 --- a/ef-migration/Docker/uninstall-docker.ps1 +++ /dev/null @@ -1,126 +0,0 @@ -# Requires -RunAsAdministrator - -function Write-Status($Message, $Type = "Info") { - switch ($Type) { - "Info" { $Color = "White" } - "Success" { $Color = "Green" } - "Error" { $Color = "Red" } - "Warning" { $Color = "Yellow" } - } - Write-Host ">>> $Message" -ForegroundColor $Color -} - -# Check if running as Administrator -$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) -if (-not $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { - Write-Status "This script must be run as Administrator" "Error" - Exit 1 -} - -try { - # Stop Docker containers - Write-Status "Stopping Docker containers..." "Info" - $containers = docker ps -aq - if ($containers) { - docker stop $containers - Write-Status "All containers stopped" "Success" - } else { - Write-Status "No running containers found" "Info" - } - - # Remove Docker containers - Write-Status "Removing Docker containers..." "Info" - $containers = docker ps -aq - if ($containers) { - docker rm $containers - Write-Status "All containers removed" "Success" - } else { - Write-Status "No containers to remove" "Info" - } - - # Remove Docker images - Write-Status "Removing Docker images..." "Info" - $images = docker images -aq - if ($images) { - docker rmi -f $images - Write-Status "All images removed" "Success" - } else { - Write-Status "No images to remove" "Info" - } - - # Stop Docker service - Write-Status "Stopping Docker service..." "Info" - $dockerService = Get-Service -Name "com.docker.service" -ErrorAction SilentlyContinue - if ($dockerService) { - Stop-Service "com.docker.service" -Force - Write-Status "Docker service stopped" "Success" - } else { - Write-Status "Docker service not found" "Info" - } - - # Remove Docker Desktop - Write-Status "Uninstalling Docker Desktop..." "Info" - $dockerDesktop = Get-WmiObject -Class Win32_Product | Where-Object { $_.Name -like "*Docker Desktop*" } - if ($dockerDesktop) { - $dockerDesktop.Uninstall() - Write-Status "Docker Desktop uninstalled" "Success" - } else { - Write-Status "Docker Desktop not found in installed programs" "Info" - } - - # Clean up Docker data directories - $directories = @( - "$env:ProgramData\Docker", - "$env:APPDATA\Docker", - "$env:LOCALAPPDATA\Docker" - ) - - foreach ($dir in $directories) { - if (Test-Path $dir) { - Write-Status "Removing $dir..." "Info" - Remove-Item -Path $dir -Recurse -Force -ErrorAction SilentlyContinue - Write-Status "$dir removed" "Success" - } - } - - # Remove environment variables - Write-Status "Cleaning up environment variables..." "Info" - $dockerEnvVars = @( - 'DOCKER_HOST', - 'DOCKER_TLS_VERIFY', - 'DOCKER_CERT_PATH', - 'DOCKER_CONFIG', - 'DOCKER_CONTEXT' - ) - - foreach ($var in $dockerEnvVars) { - if (Test-Path env:$var) { - Remove-Item env:$var -ErrorAction SilentlyContinue - [System.Environment]::SetEnvironmentVariable($var, $null, 'User') - [System.Environment]::SetEnvironmentVariable($var, $null, 'Machine') - Write-Status "Removed environment variable: $var" "Success" - } - } - - # Clean up registry entries - Write-Status "Cleaning up registry entries..." "Info" - $registryPaths = @( - 'HKCU:\Software\Docker Inc.', - 'HKLM:\Software\Docker Inc.' - ) - - foreach ($path in $registryPaths) { - if (Test-Path $path) { - Remove-Item -Path $path -Recurse -Force -ErrorAction SilentlyContinue - Write-Status "Removed registry path: $path" "Success" - } - } - - Write-Status "Docker uninstallation completed successfully!" "Success" - Write-Status "Please restart your computer to complete the cleanup." "Warning" - -} catch { - Write-Status "An error occurred during uninstallation: $_" "Error" - Write-Status "Please try to finish the cleanup manually" "Warning" - Exit 1 -} \ No newline at end of file diff --git a/ef-migration/Strata.Code.sln b/ef-migration/Strata.Code.sln new file mode 100644 index 0000000..1489653 --- /dev/null +++ b/ef-migration/Strata.Code.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Strata.Code.DataAccess", "src\Strata.Code.DataAccess\Strata.Code.DataAccess.csproj", "{C27AA99E-EEC0-41FE-B949-F4EEED1F3952}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C27AA99E-EEC0-41FE-B949-F4EEED1F3952}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C27AA99E-EEC0-41FE-B949-F4EEED1F3952}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C27AA99E-EEC0-41FE-B949-F4EEED1F3952}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C27AA99E-EEC0-41FE-B949-F4EEED1F3952}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/ef-migration/readme.md b/ef-migration/readme.md new file mode 100644 index 0000000..59d301c --- /dev/null +++ b/ef-migration/readme.md @@ -0,0 +1,283 @@ +# Entity Framework Database-First Setup Guide + +## Project Structure +Your solution should follow this structure for optimal organization: + +``` +YourSolution/ +├── src/ +│ ├── YourProject/ +│ │ ├── Controllers/ +│ │ ├── Models/ <- Scaffolded models will go here +│ │ └── Data/ <- DbContext will go here +├── tests/ +│ └── YourProject.Tests/ +├── tools/ +│ └── scaffold.bat <- Place scaffolding script here +└── YourSolution.sln +``` + +Alternative structure with scripts directory: +``` +YourSolution/ +├── src/ +│ ├── YourProject/ +│ │ ├── Controllers/ +│ │ ├── Models/ +│ │ └── Data/ +├── tests/ +│ └── YourProject.Tests/ +├── scripts/ +│ ├── database/ +│ │ └── scaffold.bat <- Or place it here +│ └── other-scripts/ +└── YourSolution.sln +``` + +To run the scaffold script: + +Method 1 (From project directory): +1. Open command prompt +2. Navigate to project directory: `cd src/YourProject` +3. Run: `../../tools/scaffold.bat` + +Method 2 (From any directory): +Update your scaffold.bat to include the project path: +```bat +@echo off +cd ../src/YourProject +dotnet ef dbcontext scaffold ^ +"Your_Connection_String" ^ +Microsoft.EntityFrameworkCore.SqlServer ^ +--project YourProject.csproj ^ +[rest of your options] +pause +``` + +Note: Make sure your project has all required EF Core packages installed: +```xml + + + + + +``` + +This guide explains how to set up Entity Framework Core using a database-first approach for specific tables in the OnePlan database. + +## Prerequisites + +Before starting, ensure you have: + +1. .NET SDK installed +2. Entity Framework Core tools installed globally: +```bash +dotnet tool install --global dotnet-ef +``` + +3. Required NuGet packages in your project: +```bash +dotnet add package Microsoft.EntityFrameworkCore.Design +dotnet add package Microsoft.EntityFrameworkCore.SqlServer +dotnet add package Microsoft.EntityFrameworkCore.Tools +``` + +## Scaffolding Process + +### Step 1: Create a Scaffold Script + +Create a file named `scaffold.bat` in your `tools` directory with the following content: + +```bat +@echo off +cd ../src/YourProject +dotnet ef dbcontext scaffold ^ +"Server=your_server;Database=your_database;User=your_user;Password=your_password;TrustServerCertificate=True;Encrypt=True;" ^ +Microsoft.EntityFrameworkCore.SqlServer ^ +--project YourProject.csproj ^ +--context-dir Data ^ +--output-dir Models ^ +--context OnePlanDbContext ^ +--force ^ +--data-annotations ^ +--no-onconfiguring ^ +--no-connection-string ^ +-t fp.AddProviderEncountersDataForCharges ^ +-t fp.AddProviderSummary ^ +-t fp.AdjustmentChunkingConfiguration ^ +-t fp.APEDepartmentWorkflowStatus ^ +-t fp.APEWorkflow ^ +-t fp.BenefitsSpreads ^ +-t fp.BudgetConfig ^ +-t fp.BudgetConfigDefaultSetting ^ +-t fp.BudgetConfigSetting ^ +-t fp.BudgetRefreshRequest ^ +-t fp.BudgetRefreshRequestHistory ^ +-t fp.ChargeVolumeAddProviderAdjustment ^ +-t fp.ChargeVolumeSpreads ^ +-t fp.DataRefreshTargetThreshold ^ +-t fp.DepartmentChargeVolumeAdjustment ^ +-t fp.DepartmentConfig ^ +-t fp.DimCategory ^ +-t fw.DimDepartment ^ +-t dss.DimPhysician ^ +-t fp.EngineLog ^ +-t fp.EntityGroupConfig ^ +-t fp.FixChangeHistoryRequest ^ +-t fp.GeneralLedger ^ +-t fp.GeneralLedgerInitialPlanConfigDetail ^ +-t fp.GeneralLedgerSpreads ^ +-t fp.InitialPlanRule ^ +-t dbo.LOCK ^ +-t dbo.log ^ +-t dbo.OnePlanPerformanceTestHistory ^ +-t fp.OnePlanPerformanceTestValidationResult ^ +-t fp.PerformanceTestingSetting ^ +-t fp.ProviderCompensationSpreads ^ +-t fp.SamplingLog ^ +-t fp.ScheduledRefreshRequest ^ +-t fp.ServiceLineEncounterSpreads ^ +-t fp.SettingCategory ^ +-t fp.SpreadHistory ^ +-t fp.StaffingInitialPlanConfigDetail ^ +-t fp.StaffingSpreads ^ +-t fp.StatisticsSpreads ^ +-t fp.SystemSetting ^ +-t dbo.TEScheduledTask ^ +-t dbo.UserProfile ^ +-t fp.viewBenefitsAdjustment ^ +-t fp.viewDepartmentChargeVolumeAdjustment ^ +-t fp.viewGeneralLedgerAdjustment ^ +-t fp.viewReimbursementAdjustment ^ +-t fp.viewReimbursementGeneralLedgerAdjustment ^ +-t fp.viewServiceLineEncounterAdjustment ^ +-t fp.viewStaffingAdjustment ^ +-t fp.viewStatisticsAdjustment +pause +``` + +To run the scaffold script: +1. Open command prompt +2. Navigate to solution root directory +3. Run: `tools/scaffold.bat` + +Note: Make sure your project has all required EF Core packages installed: +```xml + + + + + +``` + +### Step 2: Configure Connection String + +After scaffolding, configure your connection string in `appsettings.json`: + +```json +{ + "ConnectionStrings": { + "DefaultConnection": "Server=your_server;Database=your_database;User=your_user;Password=your_password;TrustServerCertificate=True;Encrypt=True;" + } +} +``` + +### Step 3: Configure DbContext + +In your `Program.cs` or `Startup.cs`: + +```csharp +builder.Services.AddDbContext(options => + options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); +``` + +## Command Line Parameters Explained + +- `--context-dir Data`: Places the DbContext in a Data folder +- `--output-dir Models`: Places entity classes in a Models folder +- `--force`: Overwrites existing files +- `--data-annotations`: Uses attributes instead of fluent API +- `--no-onconfiguring`: Skips generating the OnConfiguring method +- `--no-connection-string`: Prevents connection string from being scaffolded into DbContext + +## Schema Organization + +The tables are organized across multiple schemas: +- `fp`: Financial Planning schema (majority of tables) +- `dbo`: Database Owner schema +- `dss`: Decision Support System schema +- `fw`: Framework schema + +## Best Practices + +1. Always scaffold all related tables together to maintain proper relationships +2. Keep connection strings in configuration, not in code +3. Use dependency injection for DbContext +4. Consider using separate configuration classes for complex entity configurations + +## Troubleshooting + +If you encounter SSL/TLS warnings, ensure your connection string includes: +- `TrustServerCertificate=True` +- `Encrypt=True` + +For Docker connections, use: +- `Server=localhost,1433` (adjust port as needed) +- Ensure the container is running and accessible + +## DbContext Organization + +You have two main approaches for organizing your DbContext: + +1. **Single DbContext (Recommended for this project)** +```csharp +public class OnePlanDbContext : DbContext +{ + // All tables from all schemas + public DbSet BudgetConfigs { get; set; } + public DbSet DimDepartments { get; set; } + // ... etc for all tables +} +``` + +Advantages: +- Simpler to manage +- All relationships maintained automatically +- Better for cross-schema transactions +- Easier to maintain data consistency +- Single dependency to inject + +2. **Multiple DbContexts by Schema** +```csharp +public class FinancialPlanningDbContext : DbContext +{ + // Only fp schema tables + public DbSet BudgetConfigs { get; set; } +} + +public class FrameworkDbContext : DbContext +{ + // Only fw schema tables + public DbSet DimDepartments { get; set; } +} +``` + +Advantages: +- Better separation of concerns +- More focused contexts +- Can be more performant for specific schema operations +- Better for microservices architecture + +For this project, the single DbContext approach is recommended due to: +- Highly interconnected tables +- Cross-schema queries +- Views joining data across schemas +- Coherent domain model around financial planning + +## Notes + +- Views are included in the scaffold and will be read-only +- The scaffold includes all specified tables across multiple schemas +- Relationships between tables will be automatically mapped +- Generated models will be placed in the Models directory +- DbContext will be placed in the Data directory \ No newline at end of file diff --git a/ef-migration/src/Strata.Code.DataAccess/Class1.cs b/ef-migration/src/Strata.Code.DataAccess/Class1.cs new file mode 100644 index 0000000..8687269 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Class1.cs @@ -0,0 +1,6 @@ +namespace Strata.Code.DataAccess; + +public class Class1 +{ + +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Data/OnePlanDbContext.cs b/ef-migration/src/Strata.Code.DataAccess/Data/OnePlanDbContext.cs new file mode 100644 index 0000000..57da9d1 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Data/OnePlanDbContext.cs @@ -0,0 +1,794 @@ +using System; +using System.Collections.Generic; +using Microsoft.EntityFrameworkCore; +using Strata.Code.DataAccess.Models; +using Lock = Strata.Code.DataAccess.Models.Lock; + +namespace Strata.Code.DataAccess.Data; + +public partial class OnePlanDbContext : DbContext +{ + public OnePlanDbContext(DbContextOptions options) + : base(options) + { + } + + public virtual DbSet AddProviderEncountersDataForCharges { get; set; } + + public virtual DbSet AddProviderSummaries { get; set; } + + public virtual DbSet AdjustmentChunkingConfigurations { get; set; } + + public virtual DbSet ApedepartmentWorkflowStatuses { get; set; } + + public virtual DbSet Apeworkflows { get; set; } + + public virtual DbSet BenefitsSpreads { get; set; } + + public virtual DbSet BudgetConfigs { get; set; } + + public virtual DbSet BudgetConfigDefaultSettings { get; set; } + + public virtual DbSet BudgetConfigSettings { get; set; } + + public virtual DbSet BudgetRefreshRequests { get; set; } + + public virtual DbSet BudgetRefreshRequestHistories { get; set; } + + public virtual DbSet ChargeVolumeAddProviderAdjustments { get; set; } + + public virtual DbSet ChargeVolumeSpreads { get; set; } + + public virtual DbSet DataRefreshTargetThresholds { get; set; } + + public virtual DbSet DepartmentChargeVolumeAdjustments { get; set; } + + public virtual DbSet DepartmentConfigs { get; set; } + + public virtual DbSet DimCategories { get; set; } + + public virtual DbSet DimDepartments { get; set; } + + public virtual DbSet EngineLogs { get; set; } + + public virtual DbSet EntityGroupConfigs { get; set; } + + public virtual DbSet FixChangeHistoryRequests { get; set; } + + public virtual DbSet GeneralLedgers { get; set; } + + public virtual DbSet GeneralLedgerInitialPlanConfigDetails { get; set; } + + public virtual DbSet GeneralLedgerSpreads { get; set; } + + public virtual DbSet InitialPlanRules { get; set; } + + public virtual DbSet Locks { get; set; } + + public virtual DbSet OnePlanPerformanceTestValidationResults { get; set; } + + public virtual DbSet PerformanceTestingSettings { get; set; } + + public virtual DbSet ProviderCompensationSpreads { get; set; } + + public virtual DbSet SamplingLogs { get; set; } + + public virtual DbSet ScheduledRefreshRequests { get; set; } + + public virtual DbSet ServiceLineEncounterSpreads { get; set; } + + public virtual DbSet SettingCategories { get; set; } + + public virtual DbSet SpreadHistories { get; set; } + + public virtual DbSet StaffingInitialPlanConfigDetails { get; set; } + + public virtual DbSet StaffingSpreads { get; set; } + + public virtual DbSet StatisticsSpreads { get; set; } + + public virtual DbSet SystemSettings { get; set; } + + public virtual DbSet TescheduledTasks { get; set; } + + public virtual DbSet UserProfiles { get; set; } + + public virtual DbSet ViewReimbursementAdjustments { get; set; } + + public virtual DbSet ViewStaffingAdjustments { get; set; } + + public virtual DbSet ViewStatisticsAdjustments { get; set; } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.AddProviderEncountersDataForChargesId).HasName("PK__AddProvi__E4129B703B27669A"); + + entity.Property(e => e.AddProviderEncountersDataForChargesId).ValueGeneratedNever(); + entity.Property(e => e.AdjustmentGuid).HasDefaultValueSql("(newid())"); + + entity.HasOne(d => d.Adjustment).WithMany(p => p.AddProviderEncountersDataForCharges) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK__AddProvid__Adjus__6B6F9474"); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.SummaryId).HasName("PK__AddProvi__DAB10E0F746AF6DC"); + + entity.Property(e => e.SummaryId).ValueGeneratedNever(); + entity.Property(e => e.BenchmarkProvidersJson).HasDefaultValue(""); + entity.Property(e => e.Comment).HasDefaultValue(""); + entity.Property(e => e.StartDateUtc).HasDefaultValueSql("(getdate())"); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.SectionId).HasName("PK__Adjustme__80EF0892617FCD5C"); + + entity.Property(e => e.Description).HasDefaultValueSql("((0))"); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.DepartmentWorkflowStatusId).HasName("PK__APEDepar__30315255363CAB35"); + + entity.Property(e => e.DepartmentWorkflowStatusId).ValueGeneratedNever(); + entity.Property(e => e.EnteredStepDateTimeUtc).HasDefaultValueSql("(getutcdate())"); + + entity.HasOne(d => d.WorkflowStep).WithMany(p => p.ApedepartmentWorkflowStatuses) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK__APEDepart__Workf__0232CC71"); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.WorkflowStepId).HasName("PK__APEWorkf__361214019DCA4D7C"); + + entity.Property(e => e.WorkflowStepId).ValueGeneratedNever(); + entity.Property(e => e.Name).HasDefaultValue(""); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => new { e.BudgetConfigId, e.DepartmentId, e.AccountId }).HasName("PK__Benefits__F1B9F395006A0F0D"); + + entity.Property(e => e.GlobalSpreadId).HasDefaultValue(1); + entity.Property(e => e.SpreadPercentage01).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage02).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage03).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage04).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage05).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage06).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage07).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage08).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage09).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage10).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage11).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage12).HasDefaultValue(0m); + entity.Property(e => e.TotalImportedValue).HasDefaultValue(0m); + + entity.HasOne(d => d.SpreadHistory).WithMany(p => p.BenefitsSpreads) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK_FpBenefitsSpreads_History"); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.BudgetConfigGuid).HasName("PK__BudgetCo__4ED93B3C311E4EB0"); + + entity.Property(e => e.BudgetConfigGuid).HasDefaultValueSql("(newid())"); + entity.Property(e => e.AllowLocalAdminAddAccountMyBudgets).HasDefaultValue(true); + entity.Property(e => e.AllowLocalAdminAddAccountPlanEditor).HasDefaultValue(true); + entity.Property(e => e.AllowLocalAdminAddEmpAddFteplanEditor).HasDefaultValue(true); + entity.Property(e => e.AllowLocalAdminAddEmpAddJobCodeMyBudgets).HasDefaultValue(true); + entity.Property(e => e.BudgetConfigName).HasDefaultValue("Default Budget"); + entity.Property(e => e.ChargeMasterConfigJson).HasDefaultValue(""); + entity.Property(e => e.Comments).HasDefaultValue(""); + entity.Property(e => e.CurrentBudgetPhaseId).HasDefaultValue((byte)2); + entity.Property(e => e.DateModified).HasDefaultValueSql("(getdate())"); + entity.Property(e => e.DatePublished).HasDefaultValueSql("(getdate())"); + entity.Property(e => e.DefaultReimbursementProjectionMethodId).HasDefaultValue(1); + entity.Property(e => e.IsChargeMasterRefreshedForDollarImpactReport).HasDefaultValue(true); + entity.Property(e => e.IsGlbudgetHistoryAvailable).HasDefaultValue(true); + entity.Property(e => e.IsOverUnderFundedUsed).HasDefaultValue(true); + entity.Property(e => e.IsRestrictDepartmentAccess).HasDefaultValue(true); + entity.Property(e => e.IsStaffingBudgetHistoryAvailable).HasDefaultValue(true); + entity.Property(e => e.IsTargetingEmailEnabled).HasDefaultValue(true); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.SettingId).HasName("PK__BudgetCo__54372AFD9588A33A"); + + entity.Property(e => e.SettingId).ValueGeneratedNever(); + entity.Property(e => e.DateCreated).HasDefaultValueSql("(getdate())"); + entity.Property(e => e.DefaultValue).HasDefaultValue(true); + entity.Property(e => e.Description).HasDefaultValue(""); + entity.Property(e => e.Name).HasDefaultValue(""); + }); + + modelBuilder.Entity(entity => + { + entity.HasOne(d => d.Setting).WithMany() + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK__BudgetCon__Setti__3CD3D5C5"); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.RequestGuid).HasName("PK__BudgetRe__2F8FD1AD6F774206"); + + entity.Property(e => e.RequestGuid).HasDefaultValueSql("(newid())"); + entity.Property(e => e.AffectedDepartments).HasDefaultValue(""); + entity.Property(e => e.CurrentDataRefreshMethod).HasDefaultValue(""); + entity.Property(e => e.DateEnded).HasDefaultValue(new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + entity.Property(e => e.DateEndedUtc).HasDefaultValue(new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + entity.Property(e => e.DateStarted).HasDefaultValue(new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + entity.Property(e => e.DateStartedUtc).HasDefaultValue(new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + entity.Property(e => e.DateTimeStamp).HasDefaultValueSql("(getdate())"); + entity.Property(e => e.DateTimeStampUtc).HasDefaultValueSql("(getutcdate())"); + entity.Property(e => e.EmailAddress).HasDefaultValue(""); + entity.Property(e => e.ErrorMessage).HasDefaultValue(""); + entity.Property(e => e.InitialSamplingJson).HasDefaultValue(""); + entity.Property(e => e.InitialSourceDimensionalityJson).HasDefaultValue(""); + entity.Property(e => e.SamplingJson).HasDefaultValue(""); + entity.Property(e => e.Source).HasDefaultValue(""); + entity.Property(e => e.SourceDimensionalityJson).HasDefaultValue(""); + entity.Property(e => e.StackTrace).HasDefaultValue(""); + entity.Property(e => e.UserName).HasDefaultValue(""); + }); + + modelBuilder.Entity(entity => + { + entity.Property(e => e.AffectedDepartments).HasDefaultValue(""); + entity.Property(e => e.CanceledBy).HasDefaultValue(""); + entity.Property(e => e.DateEndedUtc).HasDefaultValue(new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + entity.Property(e => e.DateStartedUtc).HasDefaultValue(new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + entity.Property(e => e.DateTimeStampUtc).HasDefaultValueSql("(getutcdate())"); + entity.Property(e => e.InitialSamplingJson).HasDefaultValue(""); + entity.Property(e => e.InitialSourceDimensionalityJson).HasDefaultValue(""); + entity.Property(e => e.JazzVersion).HasDefaultValue(""); + entity.Property(e => e.SamplingJson).HasDefaultValue(""); + entity.Property(e => e.Source).HasDefaultValue(""); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.RowId).HasName("PK__ChargeVo__FFEE74512DFAE56C"); + + entity.Property(e => e.RowId).ValueGeneratedNever(); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => new { e.BudgetConfigId, e.DepartmentId, e.ServiceLineId, e.ChargeCodeId, e.PatientClassId, e.AgeCohortId, e.MedicalSurgicalId }).HasName("PK__ChargeVo__C17B5AD86F7201B4"); + + entity.Property(e => e.GlobalSpreadId).HasDefaultValue(1); + entity.Property(e => e.SpreadPercentage01).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage02).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage03).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage04).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage05).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage06).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage07).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage08).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage09).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage10).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage11).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage12).HasDefaultValue(0m); + entity.Property(e => e.TotalImportedValue).HasDefaultValue(0m); + + entity.HasOne(d => d.Department).WithMany(p => p.ChargeVolumeSpreads) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK_FpChargeVolumeSpreads_Department"); + + entity.HasOne(d => d.SpreadHistory).WithMany(p => p.ChargeVolumeSpreads) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK_ChargeVolumeSpreads_History"); + }); + + modelBuilder.Entity(entity => + { + entity.Property(e => e.ClassName).HasDefaultValue(""); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.AdjustmentGuid).HasName("PK__Departme__7EE745958E5F2A5E"); + + entity.Property(e => e.AdjustmentGuid).HasDefaultValueSql("(newid())"); + entity.Property(e => e.AdjustedProperty).HasDefaultValue(""); + entity.Property(e => e.AdjustmentFilterJson).HasDefaultValue(""); + entity.Property(e => e.AuthorFullName).HasDefaultValue(""); + entity.Property(e => e.Comment).HasDefaultValue(""); + entity.Property(e => e.DateCreatedUtc).HasDefaultValueSql("(getutcdate())"); + entity.Property(e => e.DimensionMemberJson).HasDefaultValue(""); + entity.Property(e => e.GroupingHierarchyJson).HasDefaultValue(""); + entity.Property(e => e.LastModifiedDateUtc).HasDefaultValueSql("(getutcdate())"); + + entity.HasOne(d => d.BudgetConfig).WithMany(p => p.DepartmentChargeVolumeAdjustments) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK__Departmen__Budge__49A9B822"); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.DepartmentConfigGuid).HasName("PK__Departme__1D24F47EE8255C75"); + + entity.Property(e => e.DepartmentConfigGuid).HasDefaultValueSql("(newid())"); + entity.Property(e => e.UpdatedDate).HasDefaultValue(new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + + entity.HasOne(d => d.Department).WithMany(p => p.DepartmentConfigs) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK__Departmen__Depar__2393C03C"); + + entity.HasOne(d => d.EntityGroupConfig).WithMany(p => p.DepartmentConfigs) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK__Departmen__Entit__3983015B"); + }); + + modelBuilder.Entity(entity => + { + entity.Property(e => e.Category).HasDefaultValue(""); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.DepartmentId).HasName("PK__DimDepar__B2079BCDE1B9CD6D"); + + entity.Property(e => e.DepartmentId).ValueGeneratedNever(); + entity.Property(e => e.AttributionType).HasDefaultValue(""); + entity.Property(e => e.CareSetting).HasDefaultValue(""); + entity.Property(e => e.CompAnDepartment).HasDefaultValue(""); + entity.Property(e => e.ConsolidatedCode).HasDefaultValue(""); + entity.Property(e => e.DepartmentCode).HasDefaultValue(""); + entity.Property(e => e.DepartmentCodeRaw).HasDefaultValue(""); + entity.Property(e => e.DepartmentRollup1).HasDefaultValue(""); + entity.Property(e => e.DepartmentRollup1Code).HasDefaultValue(""); + entity.Property(e => e.DepartmentRollup2).HasDefaultValue(""); + entity.Property(e => e.DepartmentRollup2Code).HasDefaultValue(""); + entity.Property(e => e.DepartmentRollup3).HasDefaultValue(""); + entity.Property(e => e.DepartmentRollup3Code).HasDefaultValue(""); + entity.Property(e => e.DepartmentRollup4).HasDefaultValue(""); + entity.Property(e => e.DepartmentRollup4Code).HasDefaultValue(""); + entity.Property(e => e.DepartmentRollup5).HasDefaultValue(""); + entity.Property(e => e.DepartmentRollup5Code).HasDefaultValue(""); + entity.Property(e => e.DepartmentRollup6).HasDefaultValue(""); + entity.Property(e => e.DepartmentRollup6Code).HasDefaultValue(""); + entity.Property(e => e.DepartmentType).HasDefaultValue(""); + entity.Property(e => e.DepartmentTypeOld).HasDefaultValue("Not Specified"); + entity.Property(e => e.Description).HasDefaultValue(""); + entity.Property(e => e.DssdepartmentRollup1Name).HasDefaultValue(""); + entity.Property(e => e.DssdepartmentRollup2Name).HasDefaultValue(""); + entity.Property(e => e.DssdepartmentRollup3Name).HasDefaultValue(""); + entity.Property(e => e.DssdepartmentRollup4Name).HasDefaultValue(""); + entity.Property(e => e.DssdepartmentRollup5Name).HasDefaultValue(""); + entity.Property(e => e.DssdepartmentRollup6Name).HasDefaultValue(""); + entity.Property(e => e.DssdepartmentRollup7Name).HasDefaultValue(""); + entity.Property(e => e.DssdeptGrouping).HasDefaultValue(""); + entity.Property(e => e.Entity).HasDefaultValue(""); + entity.Property(e => e.EntityCode).HasDefaultValue(""); + entity.Property(e => e.EntityTypeOverride).HasDefaultValue((short)-1); + entity.Property(e => e.FunctionalArea).HasDefaultValue(""); + entity.Property(e => e.Fund).HasDefaultValue(""); + entity.Property(e => e.HomeDepartment).HasDefaultValue(""); + entity.Property(e => e.IsLrfp).HasDefaultValue(true); + entity.Property(e => e.MemberGuid).HasDefaultValueSql("(newid())"); + entity.Property(e => e.Mrdirector).HasDefaultValue(""); + entity.Property(e => e.Mrmanager).HasDefaultValue(""); + entity.Property(e => e.MrvicePresident).HasDefaultValue(""); + entity.Property(e => e.ObglobalStatisticsPlan).HasDefaultValue(""); + entity.Property(e => e.ObreimbursementPlan).HasDefaultValue(""); + entity.Property(e => e.ObserviceLinePlan).HasDefaultValue(""); + entity.Property(e => e.PatientTypeRollupName).HasDefaultValue(""); + entity.Property(e => e.ProductivityPercentile).HasDefaultValue(""); + entity.Property(e => e.Program).HasDefaultValue(""); + entity.Property(e => e.Project).HasDefaultValue(""); + entity.Property(e => e.ResearchDepartmentCategoryName).HasDefaultValue(""); + entity.Property(e => e.SpaccountRollupName).HasDefaultValue(""); + entity.Property(e => e.SpbalanceSheetPlanName).HasDefaultValue(""); + entity.Property(e => e.SphdepartmentName).HasDefaultValue(""); + entity.Property(e => e.SphdepartmentRollupName).HasDefaultValue(""); + entity.Property(e => e.SphdepartmentType).HasDefaultValue(""); + entity.Property(e => e.SpjobCodeGroupName).HasDefaultValue(""); + entity.Property(e => e.SpoperationsPlanName).HasDefaultValue(""); + entity.Property(e => e.SpphysicianGroupName).HasDefaultValue(""); + entity.Property(e => e.SprollingForecastPlanName).HasDefaultValue(""); + entity.Property(e => e.System).HasDefaultValue(""); + entity.Property(e => e.Version) + .IsRowVersion() + .IsConcurrencyToken(); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => new { e.RequestGuid, e.AttemptId, e.StepId }).HasName("PK__EngineLo__613A431601789AAF"); + + entity.Property(e => e.RequestGuid).HasDefaultValueSql("(newid())"); + entity.Property(e => e.AffectedDepartments).HasDefaultValue(""); + entity.Property(e => e.ClassName).HasDefaultValue(""); + entity.Property(e => e.DateEnded).HasDefaultValue(new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + entity.Property(e => e.DateStarted).HasDefaultValue(new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + entity.Property(e => e.ErrorMessage).HasDefaultValue(""); + entity.Property(e => e.OptionsJson).HasDefaultValue(""); + entity.Property(e => e.SourceDimensionalityJson).HasDefaultValue(""); + entity.Property(e => e.StackTrace).HasDefaultValue(""); + entity.Property(e => e.StepName).HasDefaultValue(""); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.EntityGroupConfigGuid).HasName("PK__EntityGr__1D36B145FC4497F8"); + + entity.Property(e => e.EntityGroupConfigGuid).HasDefaultValueSql("(newid())"); + entity.Property(e => e.AccountLastSampled).HasDefaultValue(new DateTime(2000, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + entity.Property(e => e.BenefitsLastSampled).HasDefaultValue(new DateTime(2000, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + entity.Property(e => e.Comments).HasDefaultValue(""); + entity.Property(e => e.DateModified).HasDefaultValueSql("(getdate())"); + entity.Property(e => e.DatePublished).HasDefaultValueSql("(getdate())"); + entity.Property(e => e.DepartmentChargeVolumeLastSampled).HasDefaultValue(new DateTime(2000, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + entity.Property(e => e.Name).HasDefaultValue(""); + entity.Property(e => e.PayrollLastSampled).HasDefaultValue(new DateTime(2000, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + entity.Property(e => e.RevenueAndDeductionsLastSampled).HasDefaultValue(new DateTime(2000, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + entity.Property(e => e.ServiceLineEncounterLastSampled).HasDefaultValue(new DateTime(2000, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + entity.Property(e => e.StatisticsLastSampled).HasDefaultValue(new DateTime(2000, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.RequestGuid).HasName("PK__FixChang__2F8FD1AD343212A7"); + + entity.Property(e => e.RequestGuid).HasDefaultValueSql("(newid())"); + entity.Property(e => e.DateCreatedUtc).HasDefaultValueSql("(getdate())"); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.GeneralLedgerId).HasName("PK__GeneralL__9520696BDEB4E430"); + + entity.Property(e => e.GeneralLedgerId).ValueGeneratedNever(); + entity.Property(e => e.AddDate).HasDefaultValue(new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + entity.Property(e => e.BudgetPercentAdjustmentFactor01).HasDefaultValue(1m); + entity.Property(e => e.BudgetPercentAdjustmentFactor02).HasDefaultValue(1m); + entity.Property(e => e.BudgetPercentAdjustmentFactor03).HasDefaultValue(1m); + entity.Property(e => e.BudgetPercentAdjustmentFactor04).HasDefaultValue(1m); + entity.Property(e => e.BudgetPercentAdjustmentFactor05).HasDefaultValue(1m); + entity.Property(e => e.BudgetPercentAdjustmentFactor06).HasDefaultValue(1m); + entity.Property(e => e.BudgetPercentAdjustmentFactor07).HasDefaultValue(1m); + entity.Property(e => e.BudgetPercentAdjustmentFactor08).HasDefaultValue(1m); + entity.Property(e => e.BudgetPercentAdjustmentFactor09).HasDefaultValue(1m); + entity.Property(e => e.BudgetPercentAdjustmentFactor10).HasDefaultValue(1m); + entity.Property(e => e.BudgetPercentAdjustmentFactor11).HasDefaultValue(1m); + entity.Property(e => e.BudgetPercentAdjustmentFactor12).HasDefaultValue(1m); + entity.Property(e => e.ProjectionPercentAdjustmentFactor01).HasDefaultValue(1m); + entity.Property(e => e.ProjectionPercentAdjustmentFactor02).HasDefaultValue(1m); + entity.Property(e => e.ProjectionPercentAdjustmentFactor03).HasDefaultValue(1m); + entity.Property(e => e.ProjectionPercentAdjustmentFactor04).HasDefaultValue(1m); + entity.Property(e => e.ProjectionPercentAdjustmentFactor05).HasDefaultValue(1m); + entity.Property(e => e.ProjectionPercentAdjustmentFactor06).HasDefaultValue(1m); + entity.Property(e => e.ProjectionPercentAdjustmentFactor07).HasDefaultValue(1m); + entity.Property(e => e.ProjectionPercentAdjustmentFactor08).HasDefaultValue(1m); + entity.Property(e => e.ProjectionPercentAdjustmentFactor09).HasDefaultValue(1m); + entity.Property(e => e.ProjectionPercentAdjustmentFactor10).HasDefaultValue(1m); + entity.Property(e => e.ProjectionPercentAdjustmentFactor11).HasDefaultValue(1m); + entity.Property(e => e.ProjectionPercentAdjustmentFactor12).HasDefaultValue(1m); + entity.Property(e => e.TargetPercentAdjustmentFactor01).HasDefaultValue(1m); + entity.Property(e => e.TargetPercentAdjustmentFactor02).HasDefaultValue(1m); + entity.Property(e => e.TargetPercentAdjustmentFactor03).HasDefaultValue(1m); + entity.Property(e => e.TargetPercentAdjustmentFactor04).HasDefaultValue(1m); + entity.Property(e => e.TargetPercentAdjustmentFactor05).HasDefaultValue(1m); + entity.Property(e => e.TargetPercentAdjustmentFactor06).HasDefaultValue(1m); + entity.Property(e => e.TargetPercentAdjustmentFactor07).HasDefaultValue(1m); + entity.Property(e => e.TargetPercentAdjustmentFactor08).HasDefaultValue(1m); + entity.Property(e => e.TargetPercentAdjustmentFactor09).HasDefaultValue(1m); + entity.Property(e => e.TargetPercentAdjustmentFactor10).HasDefaultValue(1m); + entity.Property(e => e.TargetPercentAdjustmentFactor11).HasDefaultValue(1m); + entity.Property(e => e.TargetPercentAdjustmentFactor12).HasDefaultValue(1m); + + entity.HasOne(d => d.Department).WithMany(p => p.GeneralLedgers) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK_GeneralLedger_Department"); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.RowId).HasName("PK__GeneralL__FFEE7451BBA831F0"); + + entity.Property(e => e.RowId).ValueGeneratedNever(); + + entity.HasOne(d => d.BudgetConfig).WithMany(p => p.GeneralLedgerInitialPlanConfigDetails) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK__GeneralLe__Budge__34EBC896"); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => new { e.BudgetConfigId, e.DepartmentId, e.AccountId }).HasName("PK__GeneralL__F1B9F3954D99BE3F"); + + entity.Property(e => e.GlobalSpreadId).HasDefaultValue(1); + entity.Property(e => e.SpreadPercentage01).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage02).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage03).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage04).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage05).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage06).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage07).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage08).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage09).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage10).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage11).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage12).HasDefaultValue(0m); + entity.Property(e => e.TotalImportedValue).HasDefaultValue(0m); + + entity.HasOne(d => d.SpreadHistory).WithMany(p => p.GeneralLedgerSpreads) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK_FpGeneralLedgerSpreads_History"); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.RowId).HasName("PK__InitialP__FFEE745128948D89"); + + entity.Property(e => e.RowId).ValueGeneratedNever(); + entity.Property(e => e.DimensionalityJson).HasDefaultValue(""); + entity.Property(e => e.VersionId).HasDefaultValue(0); + + entity.HasOne(d => d.BudgetConfig).WithMany(p => p.InitialPlanRules) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK__InitialPl__Budge__269DA93F"); + }); + + modelBuilder.Entity(entity => + { + entity.Property(e => e.DateLastActive).HasDefaultValueSql("(getdate())"); + entity.Property(e => e.DateLastActiveUtc).HasDefaultValueSql("(getutcdate())"); + entity.Property(e => e.DateLocked).HasDefaultValueSql("(getdate())"); + entity.Property(e => e.DateLockedUtc).HasDefaultValueSql("(getutcdate())"); + entity.Property(e => e.LockGroup).HasDefaultValue(""); + entity.Property(e => e.LockGuid).HasDefaultValueSql("(newid())"); + entity.Property(e => e.UserName).HasDefaultValue(""); + }); + + modelBuilder.Entity(entity => + { + entity.Property(e => e.ColumnName).HasDefaultValue(""); + entity.Property(e => e.TableName).HasDefaultValue(""); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.SystemSettingId).HasName("PK__Performa__0191E99DAC87483C"); + + entity.Property(e => e.SystemSettingId).ValueGeneratedNever(); + entity.Property(e => e.DateCreated).HasDefaultValueSql("(getdate())"); + entity.Property(e => e.DefaultValue).HasDefaultValue(""); + entity.Property(e => e.Description).HasDefaultValue(""); + entity.Property(e => e.Name).HasDefaultValue(""); + entity.Property(e => e.Value).HasDefaultValue(""); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => new { e.BudgetConfigId, e.ProviderId, e.ProviderLineItemId, e.DepartmentId, e.JobCodeId, e.PayCodeGroupId, e.UnitTypeId }).HasName("PK__Provider__7B156FC863658543"); + + entity.Property(e => e.UnitTypeId).HasDefaultValue((byte)34); + entity.Property(e => e.GlobalSpreadId).HasDefaultValue(1); + entity.Property(e => e.SpreadPercentage01).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage02).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage03).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage04).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage05).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage06).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage07).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage08).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage09).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage10).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage11).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage12).HasDefaultValue(0m); + entity.Property(e => e.TotalImportedValue).HasDefaultValue(0m); + + entity.HasOne(d => d.Department).WithMany(p => p.ProviderCompensationSpreads) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK_FpProviderCompensationSpreads_Department"); + + entity.HasOne(d => d.SpreadHistory).WithMany(p => p.ProviderCompensationSpreads) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK_ProviderCompensationSpreads_History"); + }); + + modelBuilder.Entity(entity => + { + entity.Property(e => e.DateEndedUtc).HasDefaultValue(new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + entity.Property(e => e.DateStartedUtc).HasDefaultValue(new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + entity.Property(e => e.JazzVersion).HasDefaultValue(""); + entity.Property(e => e.SourceDimensionalityJson).HasDefaultValue(""); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.RequestGuid).HasName("PK__Schedule__2F8FD1AD3D1EE6FD"); + + entity.Property(e => e.RequestGuid).HasDefaultValueSql("(newid())"); + entity.Property(e => e.SamplingJson).HasDefaultValue(""); + entity.Property(e => e.SourceDimensionalityJson).HasDefaultValue(""); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => new { e.BudgetConfigId, e.EntityId, e.ServiceLineId, e.PatientClassId }).HasName("PK__ServiceL__BC32EA931931BBFB"); + + entity.Property(e => e.GlobalSpreadId).HasDefaultValue(1); + entity.Property(e => e.SpreadPercentage01).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage02).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage03).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage04).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage05).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage06).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage07).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage08).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage09).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage10).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage11).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage12).HasDefaultValue(0m); + entity.Property(e => e.TotalImportedValue).HasDefaultValue(0m); + + entity.HasOne(d => d.SpreadHistory).WithMany(p => p.ServiceLineEncounterSpreads) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK_ServiceLineEncounterSpreads_History"); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.SpreadHistoryGuid).HasName("PK__SpreadHi__3D43A8E02794F612"); + + entity.Property(e => e.AuthorFullName).HasDefaultValue(""); + entity.Property(e => e.Date).HasDefaultValueSql("(getdate())"); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.RowId).HasName("PK__Staffing__FFEE7451B817743E"); + + entity.Property(e => e.RowId).ValueGeneratedNever(); + + entity.HasOne(d => d.BudgetConfig).WithMany(p => p.StaffingInitialPlanConfigDetails) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK__StaffingI__Budge__77ADB02C"); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => new { e.BudgetConfigId, e.DepartmentId, e.JobCodeId, e.PayCodeGroupId }).HasName("PK__Staffing__6D5B21DD532F427F"); + + entity.Property(e => e.GlobalSpreadId).HasDefaultValue(1); + entity.Property(e => e.SpreadPercentage01).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage02).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage03).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage04).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage05).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage06).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage07).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage08).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage09).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage10).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage11).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage12).HasDefaultValue(0m); + entity.Property(e => e.TotalImportedValue).HasDefaultValue(0m); + + entity.HasOne(d => d.Department).WithMany(p => p.StaffingSpreads) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK_FpStaffingSpreads_Department"); + + entity.HasOne(d => d.SpreadHistory).WithMany(p => p.StaffingSpreads) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK_StaffingSpreads_History"); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => new { e.BudgetConfigId, e.DepartmentId, e.AccountId, e.ProviderId, e.ProviderLineItemId }).HasName("PK__Statisti__9854220EA98934E2"); + + entity.Property(e => e.GlobalSpreadId).HasDefaultValue(1); + entity.Property(e => e.SpreadPercentage01).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage02).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage03).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage04).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage05).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage06).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage07).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage08).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage09).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage10).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage11).HasDefaultValue(0m); + entity.Property(e => e.SpreadPercentage12).HasDefaultValue(0m); + entity.Property(e => e.TotalImportedValue).HasDefaultValue(0m); + + entity.HasOne(d => d.Department).WithMany(p => p.StatisticsSpreads) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK_FpStatisticsSpreads_Department"); + + entity.HasOne(d => d.SpreadHistory).WithMany(p => p.StatisticsSpreads) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasConstraintName("FK_StatisticsSpreads_History"); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.SystemSettingId).HasName("PK__SystemSe__0191E99D578204DD"); + + entity.Property(e => e.SystemSettingId).ValueGeneratedNever(); + entity.Property(e => e.DateCreated).HasDefaultValueSql("(getdate())"); + entity.Property(e => e.DefaultValue).HasDefaultValue(""); + entity.Property(e => e.Description).HasDefaultValue(""); + entity.Property(e => e.Name).HasDefaultValue(""); + entity.Property(e => e.Value).HasDefaultValue(""); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.ScheduledTaskGuid).HasName("PK__TESchedu__F13F6EC0946D3031"); + + entity.Property(e => e.ScheduledTaskGuid).HasDefaultValueSql("(newid())"); + entity.Property(e => e.AssemblyQualifiedName).HasDefaultValue(""); + entity.Property(e => e.DateCreatedUtc).HasDefaultValueSql("(getutcdate())"); + entity.Property(e => e.Description).HasDefaultValue(""); + entity.Property(e => e.DisabledExpirationDate).HasDefaultValue(new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + entity.Property(e => e.EndDate).HasDefaultValue(new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + entity.Property(e => e.HasEndDate).HasDefaultValue(true); + entity.Property(e => e.LastRunDateUtc).HasDefaultValueSql("(getutcdate())"); + entity.Property(e => e.LastSubmittedDateUtc).HasDefaultValueSql("(getutcdate())"); + entity.Property(e => e.Name).HasDefaultValue(""); + entity.Property(e => e.SetupXml).HasDefaultValue(""); + entity.Property(e => e.StartDate).HasDefaultValue(new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); + entity.Property(e => e.TimeZoneId).HasDefaultValue("Central Standard Time"); + }); + + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.UserGuid).HasName("PK__UserProf__81B7740C1EECCB67"); + + entity.Property(e => e.UserGuid).HasDefaultValueSql("(newid())"); + entity.Property(e => e.AuthId).HasDefaultValue(""); + entity.Property(e => e.BackupPassword).HasDefaultValue(""); + entity.Property(e => e.BrowserVersion).HasDefaultValue("Unknown"); + entity.Property(e => e.Custom1).HasDefaultValue(""); + entity.Property(e => e.Custom2).HasDefaultValue(""); + entity.Property(e => e.Custom3).HasDefaultValue(""); + entity.Property(e => e.Custom4).HasDefaultValue(""); + entity.Property(e => e.DefaultAppModeLevel).HasDefaultValue((byte)1); + entity.Property(e => e.Domain).HasDefaultValue(""); + entity.Property(e => e.DotNetVersion).HasDefaultValue(""); + entity.Property(e => e.EmailAddress).HasDefaultValue(""); + entity.Property(e => e.HashedPassword).HasDefaultValue(""); + entity.Property(e => e.LastChangedPasswordUtc).HasDefaultValueSql("(getutcdate())"); + entity.Property(e => e.LastLoginDateUtc).HasDefaultValueSql("(getutcdate())"); + entity.Property(e => e.NameFirst).HasDefaultValue(""); + entity.Property(e => e.NameLast).HasDefaultValue(""); + entity.Property(e => e.PhoneNumber).HasDefaultValue(""); + entity.Property(e => e.Salt).HasDefaultValueSql("(newid())"); + entity.Property(e => e.UserAgent).HasDefaultValue("Unknown"); + entity.Property(e => e.UserName).HasDefaultValue(""); + }); + + modelBuilder.Entity(entity => + { + entity.ToView("viewReimbursementAdjustment", "fp"); + }); + + modelBuilder.Entity(entity => + { + entity.ToView("viewStaffingAdjustment", "fp"); + }); + + modelBuilder.Entity(entity => + { + entity.ToView("viewStatisticsAdjustment", "fp"); + }); + + OnModelCreatingPartial(modelBuilder); + } + + partial void OnModelCreatingPartial(ModelBuilder modelBuilder); +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/AddProviderEncountersDataForCharge.cs b/ef-migration/src/Strata.Code.DataAccess/Models/AddProviderEncountersDataForCharge.cs new file mode 100644 index 0000000..03498e4 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/AddProviderEncountersDataForCharge.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("AddProviderEncountersDataForCharges", Schema = "fp")] +public partial class AddProviderEncountersDataForCharge +{ + [Key] + [Column("AddProviderEncountersDataForChargesID")] + public int AddProviderEncountersDataForChargesId { get; set; } + + [Column("AdjustmentGUID")] + public Guid AdjustmentGuid { get; set; } + + [Column("BudgetConfigID")] + public int BudgetConfigId { get; set; } + + [Column("EntityID")] + public int EntityId { get; set; } + + [Column("DepartmentID")] + public int DepartmentId { get; set; } + + [Column("ServiceLineID")] + public int ServiceLineId { get; set; } + + [Column("PatientClassID")] + public int PatientClassId { get; set; } + + [Column("ChargeCodeID")] + public int ChargeCodeId { get; set; } + + [Column("AgeCohortID")] + public int AgeCohortId { get; set; } + + [Column("MedicalSurgicalID")] + public int MedicalSurgicalId { get; set; } + + [Column("UnitTypeID")] + public int UnitTypeId { get; set; } + + [Column("ServiceEntityID")] + public int ServiceEntityId { get; set; } + + [Column("MSDRGID")] + public int Msdrgid { get; set; } + + [Column("UBRevCodeID")] + public int UbrevCodeId { get; set; } + + [Column("PrimaryCPTID")] + public int PrimaryCptid { get; set; } + + [Column("ServiceProviderID")] + public int ServiceProviderId { get; set; } + + [Column("ServiceProviderSpecialtyID")] + public int ServiceProviderSpecialtyId { get; set; } + + [Column("PerformingProviderID")] + public int PerformingProviderId { get; set; } + + [Column("PerformingProviderSpecialtyID")] + public int PerformingProviderSpecialtyId { get; set; } + + [Column("BillingCPTID")] + public int BillingCptid { get; set; } + + public bool IsProcessed { get; set; } + + [ForeignKey("AdjustmentGuid")] + [InverseProperty("AddProviderEncountersDataForCharges")] + public virtual DepartmentChargeVolumeAdjustment Adjustment { get; set; } = null!; +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/AddProviderSummary.cs b/ef-migration/src/Strata.Code.DataAccess/Models/AddProviderSummary.cs new file mode 100644 index 0000000..8cfb585 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/AddProviderSummary.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("AddProviderSummary", Schema = "fp")] +[Index("SlencounterAdjustmentGuid", "DcvolumeAdjustmentGuid", Name = "IX_AddProviderSummary_LinkedAdjustments")] +public partial class AddProviderSummary +{ + [Key] + [Column("SummaryID")] + public int SummaryId { get; set; } + + [Column("SLEncounterAdjustmentGUID")] + public Guid? SlencounterAdjustmentGuid { get; set; } + + [Column("DCVolumeAdjustmentGUID")] + public Guid? DcvolumeAdjustmentGuid { get; set; } + + public int EmployeeType { get; set; } + + [Column("EmployeeID")] + public int? EmployeeId { get; set; } + + [Column("ProviderID")] + public int? ProviderId { get; set; } + + public int ProviderType { get; set; } + + public int Specialty { get; set; } + + [Column("StartDateUTC", TypeName = "datetime")] + public DateTime StartDateUtc { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BenchmarkAverage { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionTotal { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetTotal { get; set; } + + [Column("BenchmarkProvidersJSON")] + public string BenchmarkProvidersJson { get; set; } = null!; + + public string Comment { get; set; } = null!; + + [Column("ClassificationGroupID")] + public int ClassificationGroupId { get; set; } + + [Column("ClassificationCategoryID")] + public int ClassificationCategoryId { get; set; } +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/AdjustmentChunkingConfiguration.cs b/ef-migration/src/Strata.Code.DataAccess/Models/AdjustmentChunkingConfiguration.cs new file mode 100644 index 0000000..99334a8 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/AdjustmentChunkingConfiguration.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("AdjustmentChunkingConfiguration", Schema = "fp")] +public partial class AdjustmentChunkingConfiguration +{ + [Key] + [Column("SectionID")] + public int SectionId { get; set; } + + [StringLength(100)] + public string Description { get; set; } = null!; + + public bool IsChunkingEnabled { get; set; } + + public int MaxAdjustmentsPerChunk { get; set; } + + public int MaxImportAdjustmentsPerChunk { get; set; } + + public int MaxAdjustmentRecordCountForChunking { get; set; } +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/ApedepartmentWorkflowStatus.cs b/ef-migration/src/Strata.Code.DataAccess/Models/ApedepartmentWorkflowStatus.cs new file mode 100644 index 0000000..3040208 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/ApedepartmentWorkflowStatus.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("APEDepartmentWorkflowStatus", Schema = "fp")] +[Index("DepartmentId", "WorkflowStepId", Name = "UC_APEDepartmentWorkflowStatus_DepartmentID_WorkflowStepID", IsUnique = true)] +public partial class ApedepartmentWorkflowStatus +{ + [Key] + [Column("DepartmentWorkflowStatusID")] + public int DepartmentWorkflowStatusId { get; set; } + + [Column("WorkflowStepID")] + public int WorkflowStepId { get; set; } + + [Column("DepartmentID")] + public int DepartmentId { get; set; } + + public byte Status { get; set; } + + [Column(TypeName = "datetime")] + public DateTime EnteredStepDateTimeUtc { get; set; } + + [ForeignKey("WorkflowStepId")] + [InverseProperty("ApedepartmentWorkflowStatuses")] + public virtual Apeworkflow WorkflowStep { get; set; } = null!; +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/Apeworkflow.cs b/ef-migration/src/Strata.Code.DataAccess/Models/Apeworkflow.cs new file mode 100644 index 0000000..e3cf921 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/Apeworkflow.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("APEWorkflow", Schema = "fp")] +public partial class Apeworkflow +{ + [Key] + [Column("WorkflowStepID")] + public int WorkflowStepId { get; set; } + + [StringLength(100)] + public string Name { get; set; } = null!; + + [Column("RoleID")] + public int RoleId { get; set; } + + public int WorkflowStepOrder { get; set; } + + [Column("EntityGroupConfigID")] + public int EntityGroupConfigId { get; set; } + + public bool IsEditable { get; set; } + + public bool IsNotificationEnabled { get; set; } + + [InverseProperty("WorkflowStep")] + public virtual ICollection ApedepartmentWorkflowStatuses { get; set; } = new List(); +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/BenefitsSpread.cs b/ef-migration/src/Strata.Code.DataAccess/Models/BenefitsSpread.cs new file mode 100644 index 0000000..3ca903f --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/BenefitsSpread.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[PrimaryKey("BudgetConfigId", "DepartmentId", "AccountId")] +[Table("BenefitsSpreads", Schema = "fp")] +public partial class BenefitsSpread +{ + [Key] + [Column("BudgetConfigID")] + public int BudgetConfigId { get; set; } + + [Key] + [Column("DepartmentID")] + public int DepartmentId { get; set; } + + [Key] + [Column("AccountID")] + public int AccountId { get; set; } + + public bool IsInactive { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? TotalImportedValue { get; set; } + + [Column("SpreadHistoryGUID")] + public Guid SpreadHistoryGuid { get; set; } + + [Column("GlobalSpreadID")] + public int GlobalSpreadId { get; set; } + + [ForeignKey("SpreadHistoryGuid")] + [InverseProperty("BenefitsSpreads")] + public virtual SpreadHistory SpreadHistory { get; set; } = null!; +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/BudgetConfig.cs b/ef-migration/src/Strata.Code.DataAccess/Models/BudgetConfig.cs new file mode 100644 index 0000000..8c2109a --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/BudgetConfig.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("BudgetConfig", Schema = "fp")] +[Index("BudgetConfigId", Name = "NCNU_BudgetConfig_BudgetConfigID")] +[Index("FiscalYearId", Name = "NCNU_BudgetConfig_FiscalYearID")] +public partial class BudgetConfig +{ + [Key] + [Column("BudgetConfigGUID")] + public Guid BudgetConfigGuid { get; set; } + + [Column("FiscalYearID")] + public short FiscalYearId { get; set; } + + [Column("BudgetConfigID")] + public short BudgetConfigId { get; set; } + + [Unicode(false)] + public string ChargeMasterConfigJson { get; set; } = null!; + + [Column(TypeName = "smalldatetime")] + public DateTime DateModified { get; set; } + + [Column(TypeName = "smalldatetime")] + public DateTime DatePublished { get; set; } + + [StringLength(100)] + public string BudgetConfigName { get; set; } = null!; + + public bool IsActive { get; set; } + + [StringLength(2000)] + public string Comments { get; set; } = null!; + + public bool IsOverUnderFundedUsed { get; set; } + + [Column("IsFTEHidden")] + public bool IsFtehidden { get; set; } + + public bool IsProjectionHidden { get; set; } + + public bool IsArchived { get; set; } + + public bool IsProjectCurrentYear { get; set; } + + [Column("IsMRTracking")] + public bool IsMrtracking { get; set; } + + [Column("ParentBudgetConfigID")] + public short ParentBudgetConfigId { get; set; } + + public byte MonthsLoaded { get; set; } + + [Column("CurrentBudgetPhaseID")] + public byte CurrentBudgetPhaseId { get; set; } + + public byte AdjustmentClassificationSetting { get; set; } + + public bool IsEngineDisabled { get; set; } + + [Column("UseDSForSampling")] + public bool UseDsforSampling { get; set; } + + [Column("IsGLBudgetHistoryAvailable")] + public bool IsGlbudgetHistoryAvailable { get; set; } + + public bool IsStaffingBudgetHistoryAvailable { get; set; } + + public bool IsTempoNonStaffingPageAvailable { get; set; } + + public bool IsAdjustmentClassificationEnabled { get; set; } + + public bool IsRestrictDepartmentAccess { get; set; } + + public bool IsChargeMasterRefreshedForDollarImpactReport { get; set; } + + [Column("DefaultReimbursementProjectionMethodID")] + public int DefaultReimbursementProjectionMethodId { get; set; } + + public bool IsProviderVolumesEnabled { get; set; } + + public bool IsTempoOtherRevenuePageAvailable { get; set; } + + public bool UseEmployeePlanning { get; set; } + + public bool IsUsingSystemGeneratedHistoricalStats { get; set; } + + public bool IsSubAccountCategoriesEnabled { get; set; } + + public bool AreStatisticsAccountsEnabled { get; set; } + + public bool IsProviderCompensationEnabled { get; set; } + + public bool DisplayCategoryInMyBudgets { get; set; } + + public bool IsLocalAdminReadOnly { get; set; } + + public bool IsTargetingEmailEnabled { get; set; } + + [Column("AllowLocalAdminAddEmpAddFTEPlanEditor")] + public bool AllowLocalAdminAddEmpAddFteplanEditor { get; set; } + + public bool AllowLocalAdminAddEmpAddJobCodeMyBudgets { get; set; } + + public bool AllowLocalAdminAddAccountPlanEditor { get; set; } + + public bool AllowLocalAdminAddAccountMyBudgets { get; set; } + + public bool IsBudgetClosed { get; set; } + + public bool IsStatisticsBudgetHistoryAvailable { get; set; } + + public bool IsImpactReportsEnabled { get; set; } + + [Column("DefaultReimbursementNetRevenueModelID")] + public int DefaultReimbursementNetRevenueModelId { get; set; } + + public bool IsProviderPlanningEnabled { get; set; } + + public bool IsUsedForReportComparison { get; set; } + + public bool UseProviderSource { get; set; } + + public bool IsProjectionLockedOnMyBudget { get; set; } + + public bool IsBudgetLockedOnMyBudget { get; set; } + + public bool EnableExceptionActionItems { get; set; } + + public bool IsWorkWeekOverrideCheckIgnored { get; set; } + + [InverseProperty("BudgetConfig")] + public virtual ICollection DepartmentChargeVolumeAdjustments { get; set; } = new List(); + + [InverseProperty("BudgetConfig")] + public virtual ICollection GeneralLedgerInitialPlanConfigDetails { get; set; } = new List(); + + [InverseProperty("BudgetConfig")] + public virtual ICollection InitialPlanRules { get; set; } = new List(); + + [InverseProperty("BudgetConfig")] + public virtual ICollection StaffingInitialPlanConfigDetails { get; set; } = new List(); +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/BudgetConfigDefaultSetting.cs b/ef-migration/src/Strata.Code.DataAccess/Models/BudgetConfigDefaultSetting.cs new file mode 100644 index 0000000..1f439b2 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/BudgetConfigDefaultSetting.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("BudgetConfigDefaultSetting", Schema = "fp")] +public partial class BudgetConfigDefaultSetting +{ + [Key] + [Column("SettingID")] + public int SettingId { get; set; } + + public string Name { get; set; } = null!; + + public string Description { get; set; } = null!; + + public bool DefaultValue { get; set; } + + public DateOnly DateCreated { get; set; } +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/BudgetConfigSetting.cs b/ef-migration/src/Strata.Code.DataAccess/Models/BudgetConfigSetting.cs new file mode 100644 index 0000000..3a8e59d --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/BudgetConfigSetting.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Keyless] +[Table("BudgetConfigSetting", Schema = "fp")] +public partial class BudgetConfigSetting +{ + [Column("BudgetConfigID")] + public int BudgetConfigId { get; set; } + + [Column("SettingID")] + public int SettingId { get; set; } + + public bool Value { get; set; } + + [ForeignKey("SettingId")] + public virtual BudgetConfigDefaultSetting Setting { get; set; } = null!; +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/BudgetRefreshRequest.cs b/ef-migration/src/Strata.Code.DataAccess/Models/BudgetRefreshRequest.cs new file mode 100644 index 0000000..f50e1fc --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/BudgetRefreshRequest.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("BudgetRefreshRequest", Schema = "fp")] +public partial class BudgetRefreshRequest +{ + [Key] + [Column("RequestGUID")] + public Guid RequestGuid { get; set; } + + [Column("BudgetConfigID")] + public short BudgetConfigId { get; set; } + + [Column(TypeName = "datetime")] + public DateTime DateTimeStamp { get; set; } + + [StringLength(64)] + public string UserName { get; set; } = null!; + + [Column("SourceDimensionalityJSON")] + public string SourceDimensionalityJson { get; set; } = null!; + + [Column(TypeName = "datetime")] + public DateTime DateStarted { get; set; } + + [Column(TypeName = "datetime")] + public DateTime DateEnded { get; set; } + + public byte Status { get; set; } + + public string ErrorMessage { get; set; } = null!; + + public string StackTrace { get; set; } = null!; + + public string CurrentDataRefreshMethod { get; set; } = null!; + + [Column("SourceActionID")] + public short SourceActionId { get; set; } + + public string AffectedDepartments { get; set; } = null!; + + public bool IsIgnoreTargetingError { get; set; } + + [StringLength(100)] + public string Source { get; set; } = null!; + + [Column("EntityGroupConfigID")] + public int EntityGroupConfigId { get; set; } + + [Column("SamplingJSON")] + public string SamplingJson { get; set; } = null!; + + [StringLength(2000)] + public string EmailAddress { get; set; } = null!; + + [Column("InitialSamplingJSON")] + public string InitialSamplingJson { get; set; } = null!; + + [Column("InitialSourceDimensionalityJSON")] + public string InitialSourceDimensionalityJson { get; set; } = null!; + + [Column("DateTimeStampUTC", TypeName = "datetime")] + public DateTime DateTimeStampUtc { get; set; } + + [Column("DateStartedUTC", TypeName = "datetime")] + public DateTime DateStartedUtc { get; set; } + + [Column("DateEndedUTC", TypeName = "datetime")] + public DateTime DateEndedUtc { get; set; } + + [Column("PlanSectionID")] + public int PlanSectionId { get; set; } +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/BudgetRefreshRequestHistory.cs b/ef-migration/src/Strata.Code.DataAccess/Models/BudgetRefreshRequestHistory.cs new file mode 100644 index 0000000..cc28f49 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/BudgetRefreshRequestHistory.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Keyless] +[Table("BudgetRefreshRequestHistory", Schema = "fp")] +public partial class BudgetRefreshRequestHistory +{ + [Column("RequestGUID")] + public Guid RequestGuid { get; set; } + + [Column("BudgetConfigID")] + public short BudgetConfigId { get; set; } + + [Column(TypeName = "datetime")] + public DateTime DateTimeStamp { get; set; } + + [StringLength(64)] + public string UserName { get; set; } = null!; + + [Column("SourceDimensionalityJSON")] + public string SourceDimensionalityJson { get; set; } = null!; + + [Column(TypeName = "datetime")] + public DateTime DateStarted { get; set; } + + [Column(TypeName = "datetime")] + public DateTime DateEnded { get; set; } + + public byte Status { get; set; } + + public string? ErrorMessage { get; set; } + + public string? StackTrace { get; set; } + + [Column("SourceActionID")] + public short SourceActionId { get; set; } + + public string AffectedDepartments { get; set; } = null!; + + [Column("CollapsedRequestGUID")] + public Guid CollapsedRequestGuid { get; set; } + + public bool IsIgnoreTargetingError { get; set; } + + [StringLength(100)] + public string Source { get; set; } = null!; + + [StringLength(100)] + public string JazzVersion { get; set; } = null!; + + [Column("EntityGroupConfigID")] + public int EntityGroupConfigId { get; set; } + + [Column("SamplingJSON")] + public string SamplingJson { get; set; } = null!; + + [Column("InitialSamplingJSON")] + public string InitialSamplingJson { get; set; } = null!; + + [Column("InitialSourceDimensionalityJSON")] + public string InitialSourceDimensionalityJson { get; set; } = null!; + + public string CanceledBy { get; set; } = null!; + + [Column("DateTimeStampUTC", TypeName = "datetime")] + public DateTime DateTimeStampUtc { get; set; } + + [Column("DateStartedUTC", TypeName = "datetime")] + public DateTime DateStartedUtc { get; set; } + + [Column("DateEndedUTC", TypeName = "datetime")] + public DateTime DateEndedUtc { get; set; } + + public int AffectedDepartmentCount { get; set; } + + [Column("PlanSectionID")] + public int PlanSectionId { get; set; } +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/ChargeVolumeAddProviderAdjustment.cs b/ef-migration/src/Strata.Code.DataAccess/Models/ChargeVolumeAddProviderAdjustment.cs new file mode 100644 index 0000000..4a2313d --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/ChargeVolumeAddProviderAdjustment.cs @@ -0,0 +1,114 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("ChargeVolumeAddProviderAdjustment", Schema = "fp")] +[Index("BudgetConfigId", "AdjustmentGuid", "EntityId", "DepartmentId", "ServiceLineId", "PatientClassId", "AgeCohortId", "MedicalSurgicalId", "ChargeCodeId", "ServiceEntityId", "Msdrgid", "UbrevCodeId", "PrimaryCptid", "ServiceProviderId", "ServiceProviderSpecialtyId", "PerformingProviderId", "PerformingProviderSpecialtyId", "BillingCptid", "TimeClassId", "BudgetPhaseId", Name = "IX_ClusteredUnique", IsUnique = true)] +public partial class ChargeVolumeAddProviderAdjustment +{ + [Key] + [Column("RowID")] + public int RowId { get; set; } + + [Column("BudgetConfigID")] + public int BudgetConfigId { get; set; } + + [Column("AdjustmentGUID")] + public Guid AdjustmentGuid { get; set; } + + [Column("EntityID")] + public int EntityId { get; set; } + + [Column("DepartmentID")] + public int DepartmentId { get; set; } + + [Column("ServiceLineID")] + public int ServiceLineId { get; set; } + + [Column("PatientClassID")] + public int PatientClassId { get; set; } + + [Column("AgeCohortID")] + public int AgeCohortId { get; set; } + + [Column("MedicalSurgicalID")] + public int MedicalSurgicalId { get; set; } + + [Column("ChargeCodeID")] + public int ChargeCodeId { get; set; } + + [Column("ServiceEntityID")] + public int ServiceEntityId { get; set; } + + [Column("MSDRGID")] + public int Msdrgid { get; set; } + + [Column("UBRevCodeID")] + public int UbrevCodeId { get; set; } + + [Column("PrimaryCPTID")] + public int PrimaryCptid { get; set; } + + [Column("BillingCPTID")] + public int BillingCptid { get; set; } + + [Column("ServiceProviderID")] + public int ServiceProviderId { get; set; } + + [Column("ServiceProviderSpecialtyID")] + public int ServiceProviderSpecialtyId { get; set; } + + [Column("PerformingProviderID")] + public int PerformingProviderId { get; set; } + + [Column("PerformingProviderSpecialtyID")] + public int PerformingProviderSpecialtyId { get; set; } + + [Column("TimeClassID")] + public byte TimeClassId { get; set; } + + [Column("BudgetPhaseID")] + public byte BudgetPhaseId { get; set; } + + public bool IsRecordDeleted { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value12 { get; set; } +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/ChargeVolumeSpread.cs b/ef-migration/src/Strata.Code.DataAccess/Models/ChargeVolumeSpread.cs new file mode 100644 index 0000000..eb64062 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/ChargeVolumeSpread.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[PrimaryKey("BudgetConfigId", "DepartmentId", "ServiceLineId", "ChargeCodeId", "PatientClassId", "AgeCohortId", "MedicalSurgicalId")] +[Table("ChargeVolumeSpreads", Schema = "fp")] +public partial class ChargeVolumeSpread +{ + [Key] + [Column("BudgetConfigID")] + public int BudgetConfigId { get; set; } + + [Key] + [Column("DepartmentID")] + public int DepartmentId { get; set; } + + [Key] + [Column("ServiceLineID")] + public int ServiceLineId { get; set; } + + [Key] + [Column("ChargeCodeID")] + public int ChargeCodeId { get; set; } + + [Key] + [Column("PatientClassID")] + public int PatientClassId { get; set; } + + [Key] + [Column("AgeCohortID")] + public int AgeCohortId { get; set; } + + [Key] + [Column("MedicalSurgicalID")] + public int MedicalSurgicalId { get; set; } + + public bool IsInactive { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? TotalImportedValue { get; set; } + + [Column("SpreadHistoryGUID")] + public Guid SpreadHistoryGuid { get; set; } + + [Column("GlobalSpreadID")] + public int GlobalSpreadId { get; set; } + + [Column("ChargeEntityID")] + public int ChargeEntityId { get; set; } + + [Column("MSDRGID")] + public int Msdrgid { get; set; } + + [Column("UBRevCodeID")] + public int UbrevCodeId { get; set; } + + [Column("CPTID")] + public int Cptid { get; set; } + + [Column("ServiceProviderID")] + public int ServiceProviderId { get; set; } + + [Column("ServiceProviderSpecialtyID")] + public int ServiceProviderSpecialtyId { get; set; } + + [Column("BillingProviderID")] + public int BillingProviderId { get; set; } + + [Column("BillingProviderSpecialtyID")] + public int BillingProviderSpecialtyId { get; set; } + + [ForeignKey("DepartmentId")] + [InverseProperty("ChargeVolumeSpreads")] + public virtual DimDepartment Department { get; set; } = null!; + + [ForeignKey("SpreadHistoryGuid")] + [InverseProperty("ChargeVolumeSpreads")] + public virtual SpreadHistory SpreadHistory { get; set; } = null!; +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/DataRefreshTargetThreshold.cs b/ef-migration/src/Strata.Code.DataAccess/Models/DataRefreshTargetThreshold.cs new file mode 100644 index 0000000..0802e7e --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/DataRefreshTargetThreshold.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Keyless] +[Table("DataRefreshTargetThreshold", Schema = "fp")] +public partial class DataRefreshTargetThreshold +{ + [StringLength(300)] + public string ClassName { get; set; } = null!; + + public int Threshold { get; set; } +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/DepartmentChargeVolumeAdjustment.cs b/ef-migration/src/Strata.Code.DataAccess/Models/DepartmentChargeVolumeAdjustment.cs new file mode 100644 index 0000000..fc009e4 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/DepartmentChargeVolumeAdjustment.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("DepartmentChargeVolumeAdjustment", Schema = "fp")] +public partial class DepartmentChargeVolumeAdjustment +{ + [Key] + [Column("AdjustmentGUID")] + public Guid AdjustmentGuid { get; set; } + + [Column("BudgetConfigGUID")] + public Guid BudgetConfigGuid { get; set; } + + public byte AdjustmentType { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value { get; set; } + + [Column("AdjustmentFilterJSON")] + public string AdjustmentFilterJson { get; set; } = null!; + + [Column("GroupingHierarchyJSON")] + public string GroupingHierarchyJson { get; set; } = null!; + + [StringLength(100)] + public string AdjustedProperty { get; set; } = null!; + + public string Comment { get; set; } = null!; + + [Column("AuthorGUID")] + public Guid AuthorGuid { get; set; } + + [StringLength(260)] + public string AuthorFullName { get; set; } = null!; + + [Column("GroupingGUID")] + public Guid GroupingGuid { get; set; } + + [Column("TimeClassID")] + public byte TimeClassId { get; set; } + + [Column("ClassificationGroupID")] + public int ClassificationGroupId { get; set; } + + [Column("ClassificationCategoryID")] + public int ClassificationCategoryId { get; set; } + + public bool IsRecordDeleted { get; set; } + + [Column(TypeName = "datetime")] + public DateTime DateCreatedUtc { get; set; } + + [Column(TypeName = "datetime")] + public DateTime LastModifiedDateUtc { get; set; } + + public string DimensionMemberJson { get; set; } = null!; + + public int AffectedDataCount { get; set; } + + [Column("AdjustmentID")] + public int AdjustmentId { get; set; } + + public bool IsErrored { get; set; } + + [InverseProperty("Adjustment")] + public virtual ICollection AddProviderEncountersDataForCharges { get; set; } = new List(); + + [ForeignKey("BudgetConfigGuid")] + [InverseProperty("DepartmentChargeVolumeAdjustments")] + public virtual BudgetConfig BudgetConfig { get; set; } = null!; +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/DepartmentConfig.cs b/ef-migration/src/Strata.Code.DataAccess/Models/DepartmentConfig.cs new file mode 100644 index 0000000..1756310 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/DepartmentConfig.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("DepartmentConfig", Schema = "fp")] +[Index("DepartmentId", Name = "NCNU_DepartmentConfig_DepartmentID")] +[Index("EntityGroupConfigGuid", Name = "NCNU_DepartmentConfig_EntityGroupConfigGUID")] +[Index("DepartmentId", "EntityGroupConfigGuid", Name = "UC_FP_DepartmentConfig_DeptID_EGC", IsUnique = true)] +public partial class DepartmentConfig +{ + [Key] + [Column("DepartmentConfigGUID")] + public Guid DepartmentConfigGuid { get; set; } + + [Column("DepartmentID")] + public int DepartmentId { get; set; } + + [Column(TypeName = "datetime")] + public DateTime UpdatedDate { get; set; } + + [Column("EntityGroupConfigGUID")] + public Guid EntityGroupConfigGuid { get; set; } + + public bool HasStatistics { get; set; } + + public bool HasRevenueAndDeductions { get; set; } + + public bool HasOtherRevenue { get; set; } + + public bool HasRoster { get; set; } + + public bool HasStaffing { get; set; } + + public bool HasBenefits { get; set; } + + public bool HasNonStaffingExpenses { get; set; } + + public bool HasZeroBasedExpenses { get; set; } + + [ForeignKey("DepartmentId")] + [InverseProperty("DepartmentConfigs")] + public virtual DimDepartment Department { get; set; } = null!; + + [ForeignKey("EntityGroupConfigGuid")] + [InverseProperty("DepartmentConfigs")] + public virtual EntityGroupConfig EntityGroupConfig { get; set; } = null!; +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/DimCategory.cs b/ef-migration/src/Strata.Code.DataAccess/Models/DimCategory.cs new file mode 100644 index 0000000..a2e9b43 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/DimCategory.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Keyless] +[Table("DimCategory", Schema = "fp")] +public partial class DimCategory +{ + [Column("CategoryID")] + public int CategoryId { get; set; } + + [StringLength(50)] + [Unicode(false)] + public string Category { get; set; } = null!; +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/DimDepartment.cs b/ef-migration/src/Strata.Code.DataAccess/Models/DimDepartment.cs new file mode 100644 index 0000000..6ebed77 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/DimDepartment.cs @@ -0,0 +1,478 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("DimDepartment", Schema = "fw")] +[Index("DepartmentRollup1Id", Name = "IX_DepartmentRollup1ID")] +[Index("DepartmentRollup2Id", Name = "IX_DepartmentRollup2ID")] +[Index("DepartmentRollup3Id", Name = "IX_DepartmentRollup3ID")] +[Index("DepartmentRollup4Id", Name = "IX_DepartmentRollup4ID")] +[Index("DepartmentRollup5Id", Name = "IX_DepartmentRollup5ID")] +[Index("DepartmentRollup6Id", Name = "IX_DepartmentRollup6ID")] +[Index("DepartmentId", "DepartmentRollup1Id", "DepartmentRollup2Id", "DepartmentRollup3Id", "DepartmentRollup4Id", "DepartmentRollup5Id", "DepartmentRollup6Id", Name = "IX_Hierarchy")] +[Index("MemberGuid", Name = "IX_MemberGUID")] +[Index("IsMrorPr", "DepartmentId", Name = "NCNU_DimDepartment_IsMRorPR_DepartmentID")] +[Index("DepartmentId", "EntityId", Name = "NCNU_EntityID")] +[Index("DepartmentCode", Name = "NCU_DepartmentCode", IsUnique = true)] +public partial class DimDepartment +{ + [Key] + [Column("DepartmentID")] + public int DepartmentId { get; set; } + + [Column("MemberGUID")] + public Guid MemberGuid { get; set; } + + [StringLength(100)] + public string DepartmentCode { get; set; } = null!; + + [StringLength(100)] + public string Description { get; set; } = null!; + + [Column("SystemID")] + public short SystemId { get; set; } + + [StringLength(100)] + public string System { get; set; } = null!; + + public int SystemSortOrder { get; set; } + + [Column("EntityID")] + public int EntityId { get; set; } + + [StringLength(303)] + public string? Entity { get; set; } + + public int EntitySortOrder { get; set; } + + public short EntityTypeOverride { get; set; } + + [Column("DepartmentRollup1ID")] + public short DepartmentRollup1Id { get; set; } + + [StringLength(200)] + public string DepartmentRollup1 { get; set; } = null!; + + public int DepartmentRollup1SortOrder { get; set; } + + [Column("DepartmentRollup2ID")] + public short DepartmentRollup2Id { get; set; } + + [StringLength(200)] + public string DepartmentRollup2 { get; set; } = null!; + + public int DepartmentRollup2SortOrder { get; set; } + + [Column("DepartmentRollup3ID")] + public short DepartmentRollup3Id { get; set; } + + [StringLength(200)] + public string DepartmentRollup3 { get; set; } = null!; + + public int DepartmentRollup3SortOrder { get; set; } + + [Column("DepartmentRollup4ID")] + public int DepartmentRollup4Id { get; set; } + + [StringLength(200)] + public string DepartmentRollup4 { get; set; } = null!; + + public int DepartmentRollup4SortOrder { get; set; } + + [Column("DepartmentRollup5ID")] + public short DepartmentRollup5Id { get; set; } + + [StringLength(200)] + public string DepartmentRollup5 { get; set; } = null!; + + public int DepartmentRollup5SortOrder { get; set; } + + [Column("DepartmentRollup6ID")] + public short DepartmentRollup6Id { get; set; } + + [StringLength(200)] + public string DepartmentRollup6 { get; set; } = null!; + + public int DepartmentRollup6SortOrder { get; set; } + + [Column("CareSettingID")] + public int CareSettingId { get; set; } + + [StringLength(100)] + public string CareSetting { get; set; } = null!; + + public int SortOrder { get; set; } + + public bool IsDepartmentRollup { get; set; } + + [Column("FunctionalAreaID")] + public int FunctionalAreaId { get; set; } + + [StringLength(100)] + public string FunctionalArea { get; set; } = null!; + + [Column("ResearchDepartmentCategoryID")] + public int ResearchDepartmentCategoryId { get; set; } + + [StringLength(100)] + public string ResearchDepartmentCategoryName { get; set; } = null!; + + public int ResearchDepartmentCategorySortOrder { get; set; } + + [Column("AttributionTypeID")] + public int AttributionTypeId { get; set; } + + [StringLength(200)] + public string AttributionType { get; set; } = null!; + + [Column("CAPIsDefined")] + public bool CapisDefined { get; set; } + + [Column("IsCAP")] + public bool IsCap { get; set; } + + [Column("DSSIsDefined")] + public bool DssisDefined { get; set; } + + [Column("IsDSS")] + public bool IsDss { get; set; } + + [Column("DepartmentTypeOLD")] + [StringLength(100)] + public string DepartmentTypeOld { get; set; } = null!; + + [Column("DSSDeptGrouping")] + [StringLength(200)] + public string DssdeptGrouping { get; set; } = null!; + + [Column("DSSDepartmentRollup1ID")] + public int DssdepartmentRollup1Id { get; set; } + + [Column("DSSDepartmentRollup1Name")] + [StringLength(100)] + public string DssdepartmentRollup1Name { get; set; } = null!; + + [Column("DSSDepartmentRollup2ID")] + public int DssdepartmentRollup2Id { get; set; } + + [Column("DSSDepartmentRollup2Name")] + [StringLength(100)] + public string DssdepartmentRollup2Name { get; set; } = null!; + + [Column("DSSDepartmentRollup3ID")] + public int DssdepartmentRollup3Id { get; set; } + + [Column("DSSDepartmentRollup3Name")] + [StringLength(100)] + public string DssdepartmentRollup3Name { get; set; } = null!; + + public bool IsOverhead { get; set; } + + [Column("OBIsDefined")] + public bool ObisDefined { get; set; } + + [Column("IsOB")] + public bool IsOb { get; set; } + + [Column("IsMRPlan")] + public bool IsMrplan { get; set; } + + public bool IsActive { get; set; } + + public bool IsVariable { get; set; } + + public bool IsAccountFlexing { get; set; } + + [Column("FlexingBucketGUID")] + public Guid FlexingBucketGuid { get; set; } + + [Column("OBGlobalStatisticsPlanID")] + public int ObglobalStatisticsPlanId { get; set; } + + [Column("OBGlobalStatisticsPlan")] + [StringLength(1000)] + public string ObglobalStatisticsPlan { get; set; } = null!; + + [Column("OBReimbursementPlanID")] + public int ObreimbursementPlanId { get; set; } + + [Column("OBReimbursementPlan")] + [StringLength(458)] + public string ObreimbursementPlan { get; set; } = null!; + + [Column("OBServiceLinePlanID")] + public int ObserviceLinePlanId { get; set; } + + [Column("OBServiceLinePlan")] + [StringLength(458)] + public string ObserviceLinePlan { get; set; } = null!; + + [Column("SPIsDefined")] + public bool SpisDefined { get; set; } + + [Column("IsLRFP")] + public bool IsLrfp { get; set; } + + [Column("RollingPlanID")] + public int RollingPlanId { get; set; } + + [Column("SPRollingForecastPlanName")] + [StringLength(200)] + public string SprollingForecastPlanName { get; set; } = null!; + + [Column("OpsPlanID")] + public int OpsPlanId { get; set; } + + [Column("SPOperationsPlanName")] + [StringLength(200)] + public string SpoperationsPlanName { get; set; } = null!; + + [Column("BalPlanID")] + public int BalPlanId { get; set; } + + [Column("SPBalanceSheetPlanName")] + [StringLength(200)] + public string SpbalanceSheetPlanName { get; set; } = null!; + + public byte PatientTypeRollup { get; set; } + + [StringLength(100)] + public string PatientTypeRollupName { get; set; } = null!; + + [Column("SPJobCodeGroup")] + public int SpjobCodeGroup { get; set; } + + [Column("SPJobCodeGroupName")] + [StringLength(100)] + public string SpjobCodeGroupName { get; set; } = null!; + + [Column("SPPhysicianGroup")] + public int SpphysicianGroup { get; set; } + + [Column("SPPhysicianGroupName")] + [StringLength(100)] + public string SpphysicianGroupName { get; set; } = null!; + + [Column("SPAccountRollup")] + public int SpaccountRollup { get; set; } + + [Column("SPAccountRollupName")] + [StringLength(100)] + public string SpaccountRollupName { get; set; } = null!; + + [Column("SPServiceLineForecastType")] + public short SpserviceLineForecastType { get; set; } + + [StringLength(100)] + public string ConsolidatedCode { get; set; } = null!; + + public bool IsConsolidated { get; set; } + + [Column("TransactionID")] + public int TransactionId { get; set; } + + [Column("HistoryItemGUID")] + public Guid HistoryItemGuid { get; set; } + + public byte[] Version { get; set; } = null!; + + [StringLength(203)] + public string Name { get; set; } = null!; + + [Column("SecureGroupID")] + public int SecureGroupId { get; set; } + + [Column("WorkWeekID")] + public int WorkWeekId { get; set; } + + [Column("CAPDefaultSalesTax")] + public double CapdefaultSalesTax { get; set; } + + [StringLength(100)] + public string EntityCode { get; set; } = null!; + + [Column("FundID")] + public int FundId { get; set; } + + [StringLength(100)] + public string Fund { get; set; } = null!; + + public int FundSortOrder { get; set; } + + [Column("ProjectID")] + public int ProjectId { get; set; } + + [StringLength(100)] + public string Project { get; set; } = null!; + + public int ProjectSortOrder { get; set; } + + [Column("HomeDepartmentID")] + public int HomeDepartmentId { get; set; } + + [StringLength(100)] + public string HomeDepartment { get; set; } = null!; + + public int HomeDepartmentSortOrder { get; set; } + + [Column("ProgramID")] + public int ProgramId { get; set; } + + [StringLength(100)] + public string Program { get; set; } = null!; + + public int ProgramSortOrder { get; set; } + + [Column("PayCycleID")] + public int PayCycleId { get; set; } + + [Column("FWIsDefined")] + public bool FwisDefined { get; set; } + + [Column("DepartmentTypeID")] + public int DepartmentTypeId { get; set; } + + [StringLength(200)] + public string DepartmentType { get; set; } = null!; + + [StringLength(100)] + public string DepartmentCodeRaw { get; set; } = null!; + + [Column("IsPR")] + public bool IsPr { get; set; } + + [Column("MRVicePresident")] + [StringLength(400)] + public string MrvicePresident { get; set; } = null!; + + [Column("MRDirector")] + [StringLength(400)] + public string Mrdirector { get; set; } = null!; + + [Column("MRManager")] + [StringLength(400)] + public string Mrmanager { get; set; } = null!; + + [Column("IsMROrPR")] + public int IsMrorPr { get; set; } + + [Column("IsMRMetricTracking")] + public bool IsMrmetricTracking { get; set; } + + public bool IsHealthPlanAdmin { get; set; } + + [StringLength(200)] + public string DepartmentRollup1Code { get; set; } = null!; + + [StringLength(200)] + public string DepartmentRollup2Code { get; set; } = null!; + + [StringLength(200)] + public string DepartmentRollup3Code { get; set; } = null!; + + [StringLength(200)] + public string DepartmentRollup4Code { get; set; } = null!; + + [StringLength(200)] + public string DepartmentRollup5Code { get; set; } = null!; + + [StringLength(200)] + public string DepartmentRollup6Code { get; set; } = null!; + + [Column("DSSDepartmentRollup4Name")] + [StringLength(100)] + public string DssdepartmentRollup4Name { get; set; } = null!; + + [Column("DSSDepartmentRollup4ID")] + public int DssdepartmentRollup4Id { get; set; } + + [Column("DSSDepartmentRollup5ID")] + public int DssdepartmentRollup5Id { get; set; } + + [Column("DSSDepartmentRollup5Name")] + [StringLength(100)] + public string DssdepartmentRollup5Name { get; set; } = null!; + + [Column("DSSDepartmentRollup6ID")] + public int DssdepartmentRollup6Id { get; set; } + + [Column("DSSDepartmentRollup6Name")] + [StringLength(200)] + public string DssdepartmentRollup6Name { get; set; } = null!; + + [Column("DSSDepartmentRollup7ID")] + public int DssdepartmentRollup7Id { get; set; } + + [Column("DSSDepartmentRollup7Name")] + [StringLength(100)] + public string DssdepartmentRollup7Name { get; set; } = null!; + + [Column("SPHDepartmentRollupID")] + public int SphdepartmentRollupId { get; set; } + + [Column("SPHDepartmentRollupName")] + [StringLength(200)] + public string SphdepartmentRollupName { get; set; } = null!; + + [Column("SPHDepartmentRollupConfidenceScore")] + public double SphdepartmentRollupConfidenceScore { get; set; } + + [Column("SPHDepartmentTypeID")] + public int SphdepartmentTypeId { get; set; } + + [Column("SPHDepartmentType")] + [StringLength(200)] + public string SphdepartmentType { get; set; } = null!; + + public bool IsClaimsCosting { get; set; } + + [Column("SPHDepartmentRollupIsValidated")] + public bool SphdepartmentRollupIsValidated { get; set; } + + [Column("CompAnDepartmentID")] + public int CompAnDepartmentId { get; set; } + + [Column("ProductivityPercentileID")] + public int ProductivityPercentileId { get; set; } + + [StringLength(200)] + public string ProductivityPercentile { get; set; } = null!; + + [StringLength(200)] + public string CompAnDepartment { get; set; } = null!; + + [Column("SPHDepartmentID")] + public int SphdepartmentId { get; set; } + + [Column("SPHDepartmentConfidenceScore")] + public double SphdepartmentConfidenceScore { get; set; } + + [Column("SPHDepartmentIsValidated")] + public bool SphdepartmentIsValidated { get; set; } + + [Column("SPHDepartmentName")] + [StringLength(200)] + public string SphdepartmentName { get; set; } = null!; + + [InverseProperty("Department")] + public virtual ICollection ChargeVolumeSpreads { get; set; } = new List(); + + [InverseProperty("Department")] + public virtual ICollection DepartmentConfigs { get; set; } = new List(); + + [InverseProperty("Department")] + public virtual ICollection GeneralLedgers { get; set; } = new List(); + + [InverseProperty("Department")] + public virtual ICollection ProviderCompensationSpreads { get; set; } = new List(); + + [InverseProperty("Department")] + public virtual ICollection StaffingSpreads { get; set; } = new List(); + + [InverseProperty("Department")] + public virtual ICollection StatisticsSpreads { get; set; } = new List(); +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/EngineLog.cs b/ef-migration/src/Strata.Code.DataAccess/Models/EngineLog.cs new file mode 100644 index 0000000..e5f61b1 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/EngineLog.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[PrimaryKey("RequestGuid", "AttemptId", "StepId")] +[Table("EngineLog", Schema = "fp")] +public partial class EngineLog +{ + [Key] + [Column("RequestGUID")] + public Guid RequestGuid { get; set; } + + [Key] + [Column("StepID")] + public int StepId { get; set; } + + [Key] + [Column("AttemptID")] + public int AttemptId { get; set; } + + [StringLength(300)] + public string StepName { get; set; } = null!; + + [StringLength(300)] + public string ClassName { get; set; } = null!; + + [Column("SourceDimensionalityJSON")] + public string SourceDimensionalityJson { get; set; } = null!; + + [Column("OptionsJSON")] + public string OptionsJson { get; set; } = null!; + + [Column(TypeName = "datetime")] + public DateTime DateStarted { get; set; } + + [Column(TypeName = "datetime")] + public DateTime DateEnded { get; set; } + + public byte Status { get; set; } + + public string ErrorMessage { get; set; } = null!; + + public string StackTrace { get; set; } = null!; + + public string AffectedDepartments { get; set; } = null!; + + public int AffectedDepartmentCount { get; set; } +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/EntityGroupConfig.cs b/ef-migration/src/Strata.Code.DataAccess/Models/EntityGroupConfig.cs new file mode 100644 index 0000000..bc3b1e4 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/EntityGroupConfig.cs @@ -0,0 +1,121 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("EntityGroupConfig", Schema = "fp")] +public partial class EntityGroupConfig +{ + [Key] + [Column("EntityGroupConfigGUID")] + public Guid EntityGroupConfigGuid { get; set; } + + [Column("BudgetConfigGUID")] + public Guid BudgetConfigGuid { get; set; } + + [StringLength(100)] + public string? Name { get; set; } + + [StringLength(1000)] + public string? Comments { get; set; } + + [Column("AccountTimeClassID")] + public byte AccountTimeClassId { get; set; } + + [Column("AccountFiscalYearID")] + public short AccountFiscalYearId { get; set; } + + [Column("PayrollTimeClassID")] + public byte PayrollTimeClassId { get; set; } + + [Column("PayrollFiscalYearID")] + public short PayrollFiscalYearId { get; set; } + + [Column("ServiceLineEncounterTimeClassID")] + public byte ServiceLineEncounterTimeClassId { get; set; } + + [Column("ServiceLineEncounterFiscalYearID")] + public short ServiceLineEncounterFiscalYearId { get; set; } + + [Column("DepartmentChargeVolumeTimeClassID")] + public byte DepartmentChargeVolumeTimeClassId { get; set; } + + [Column("DepartmentChargeVolumeFiscalYearID")] + public short DepartmentChargeVolumeFiscalYearId { get; set; } + + [Column(TypeName = "datetime")] + public DateTime AccountLastSampled { get; set; } + + [Column(TypeName = "datetime")] + public DateTime PayrollLastSampled { get; set; } + + [Column(TypeName = "datetime")] + public DateTime ServiceLineEncounterLastSampled { get; set; } + + [Column(TypeName = "datetime")] + public DateTime DepartmentChargeVolumeLastSampled { get; set; } + + [Column("CostingConfigGUID")] + public Guid CostingConfigGuid { get; set; } + + [Column("CostingConfigTimeClassID")] + public byte CostingConfigTimeClassId { get; set; } + + [Column(TypeName = "smalldatetime")] + public DateTime? DateModified { get; set; } + + [Column(TypeName = "smalldatetime")] + public DateTime? DatePublished { get; set; } + + [Column("BenefitsTimeClassID")] + public byte BenefitsTimeClassId { get; set; } + + [Column("BenefitsFiscalYearID")] + public short BenefitsFiscalYearId { get; set; } + + [Column(TypeName = "datetime")] + public DateTime BenefitsLastSampled { get; set; } + + public bool IsMarkedForDeletion { get; set; } + + [Column("StatisticsTimeClassID")] + public byte StatisticsTimeClassId { get; set; } + + [Column("StatisticsFiscalYearID")] + public short StatisticsFiscalYearId { get; set; } + + [Column(TypeName = "datetime")] + public DateTime StatisticsLastSampled { get; set; } + + [Column("EntityGroupConfigID")] + public int EntityGroupConfigId { get; set; } + + public bool IsBudgetLockDown { get; set; } + + public bool IsRosterUsed { get; set; } + + public short StatisticsModel { get; set; } + + [Column("RevenueAndDeductionsTimeClassID")] + public byte RevenueAndDeductionsTimeClassId { get; set; } + + [Column("RevenueAndDeductionsFiscalYearID")] + public short RevenueAndDeductionsFiscalYearId { get; set; } + + [Column(TypeName = "datetime")] + public DateTime RevenueAndDeductionsLastSampled { get; set; } + + public bool IsPatientActivityFlexingForStaffing { get; set; } + + public bool IsPatientActivityFlexingForNonStaffing { get; set; } + + public Guid ParentEntityGroupConfigGuid { get; set; } + + public bool IsPayorGroupUsedForCrosswalk { get; set; } + + [InverseProperty("EntityGroupConfig")] + public virtual ICollection DepartmentConfigs { get; set; } = new List(); +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/FixChangeHistoryRequest.cs b/ef-migration/src/Strata.Code.DataAccess/Models/FixChangeHistoryRequest.cs new file mode 100644 index 0000000..288186c --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/FixChangeHistoryRequest.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("FixChangeHistoryRequest", Schema = "fp")] +public partial class FixChangeHistoryRequest +{ + [Key] + [Column("RequestGUID")] + public Guid RequestGuid { get; set; } + + public byte ChangeHistoryRecordType { get; set; } + + [Column("DateCreatedUTC", TypeName = "datetime")] + public DateTime DateCreatedUtc { get; set; } + + [Column("BasisID")] + public int BasisId { get; set; } + + [Column("TimeClassID")] + public byte TimeClassId { get; set; } + + [Column("BudgetPhaseID")] + public byte BudgetPhaseId { get; set; } + + public bool IsRecordDeleted { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value12 { get; set; } +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/GeneralLedger.cs b/ef-migration/src/Strata.Code.DataAccess/Models/GeneralLedger.cs new file mode 100644 index 0000000..ae7b890 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/GeneralLedger.cs @@ -0,0 +1,812 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("GeneralLedger", Schema = "fp")] +[Index("AccountId", Name = "IX_GeneralLedger_Account")] +[Index("BudgetConfigId", Name = "IX_GeneralLedger_BudgetDollarsConfig")] +[Index("DepartmentId", Name = "IX_GeneralLedger_Department")] +[Index("EntityId", Name = "IX_GeneralLedger_Entity")] +[Index("EntityGroupConfigId", "FlexingTypeId", Name = "IX_GeneralLedger_EntityGroupConfig")] +public partial class GeneralLedger +{ + [Key] + [Column("GeneralLedgerID")] + public int GeneralLedgerId { get; set; } + + [Column("BudgetConfigID")] + public int BudgetConfigId { get; set; } + + [Column("EntityGroupConfigID")] + public int EntityGroupConfigId { get; set; } + + [Column("EntityID")] + public int EntityId { get; set; } + + [Column("DepartmentID")] + public int DepartmentId { get; set; } + + [Column("AccountID")] + public int AccountId { get; set; } + + [Column("FinancialReportingID")] + public int FinancialReportingId { get; set; } + + [Column("VariabilityID")] + public int VariabilityId { get; set; } + + [Column("APEModelSectionID")] + public byte ApemodelSectionId { get; set; } + + [Column(TypeName = "datetime")] + public DateTime AddDate { get; set; } + + public bool IsNew { get; set; } + + [Column("FlexingTypeID")] + public short FlexingTypeId { get; set; } + + [Column("ChangeHistoryGroupingGUID")] + public Guid ChangeHistoryGroupingGuid { get; set; } + + public byte BudgetLockType { get; set; } + + public byte BudgetLockFlag { get; set; } + + public byte TargetLockType { get; set; } + + public byte TargetLockFlag { get; set; } + + public byte ProjectionLockType { get; set; } + + public byte ProjectionLockFlag { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledBudgetTotal { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledProjectionTotal { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudgetTotal { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjectionTotal { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetAdjustedTotal { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetAdjustedTotal { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionAdjustedTotal { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledBudget01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledBudget02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledBudget03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledBudget04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledBudget05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledBudget06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledBudget07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledBudget08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledBudget09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledBudget10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledBudget11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledBudget12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledProjection01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledProjection02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledProjection03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledProjection04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledProjection05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledProjection06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledProjection07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledProjection08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledProjection09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledProjection10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledProjection11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal SampledProjection12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudget01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudget02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudget03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudget04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudget05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudget06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudget07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudget08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudget09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudget10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudget11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudget12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjection01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjection02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjection03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjection04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjection05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjection06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjection07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjection08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjection09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjection10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjection11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjection12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetAdjusted01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetAdjusted02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetAdjusted03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetAdjusted04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetAdjusted05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetAdjusted06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetAdjusted07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetAdjusted08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetAdjusted09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetAdjusted10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetAdjusted11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetAdjusted12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetAdjusted01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetAdjusted02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetAdjusted03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetAdjusted04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetAdjusted05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetAdjusted06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetAdjusted07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetAdjusted08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetAdjusted09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetAdjusted10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetAdjusted11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetAdjusted12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionAdjusted01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionAdjusted02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionAdjusted03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionAdjusted04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionAdjusted05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionAdjusted06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionAdjusted07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionAdjusted08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionAdjusted09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionAdjusted10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionAdjusted11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionAdjusted12 { get; set; } + + [Column("InitialBudgetDollarsPerUOS01", TypeName = "decimal(18, 0)")] + public decimal InitialBudgetDollarsPerUos01 { get; set; } + + [Column("InitialBudgetDollarsPerUOS02", TypeName = "decimal(18, 0)")] + public decimal InitialBudgetDollarsPerUos02 { get; set; } + + [Column("InitialBudgetDollarsPerUOS03", TypeName = "decimal(18, 0)")] + public decimal InitialBudgetDollarsPerUos03 { get; set; } + + [Column("InitialBudgetDollarsPerUOS04", TypeName = "decimal(18, 0)")] + public decimal InitialBudgetDollarsPerUos04 { get; set; } + + [Column("InitialBudgetDollarsPerUOS05", TypeName = "decimal(18, 0)")] + public decimal InitialBudgetDollarsPerUos05 { get; set; } + + [Column("InitialBudgetDollarsPerUOS06", TypeName = "decimal(18, 0)")] + public decimal InitialBudgetDollarsPerUos06 { get; set; } + + [Column("InitialBudgetDollarsPerUOS07", TypeName = "decimal(18, 0)")] + public decimal InitialBudgetDollarsPerUos07 { get; set; } + + [Column("InitialBudgetDollarsPerUOS08", TypeName = "decimal(18, 0)")] + public decimal InitialBudgetDollarsPerUos08 { get; set; } + + [Column("InitialBudgetDollarsPerUOS09", TypeName = "decimal(18, 0)")] + public decimal InitialBudgetDollarsPerUos09 { get; set; } + + [Column("InitialBudgetDollarsPerUOS10", TypeName = "decimal(18, 0)")] + public decimal InitialBudgetDollarsPerUos10 { get; set; } + + [Column("InitialBudgetDollarsPerUOS11", TypeName = "decimal(18, 0)")] + public decimal InitialBudgetDollarsPerUos11 { get; set; } + + [Column("InitialBudgetDollarsPerUOS12", TypeName = "decimal(18, 0)")] + public decimal InitialBudgetDollarsPerUos12 { get; set; } + + [Column("InitialProjectionDollarsPerUOS01", TypeName = "decimal(18, 0)")] + public decimal InitialProjectionDollarsPerUos01 { get; set; } + + [Column("InitialProjectionDollarsPerUOS02", TypeName = "decimal(18, 0)")] + public decimal InitialProjectionDollarsPerUos02 { get; set; } + + [Column("InitialProjectionDollarsPerUOS03", TypeName = "decimal(18, 0)")] + public decimal InitialProjectionDollarsPerUos03 { get; set; } + + [Column("InitialProjectionDollarsPerUOS04", TypeName = "decimal(18, 0)")] + public decimal InitialProjectionDollarsPerUos04 { get; set; } + + [Column("InitialProjectionDollarsPerUOS05", TypeName = "decimal(18, 0)")] + public decimal InitialProjectionDollarsPerUos05 { get; set; } + + [Column("InitialProjectionDollarsPerUOS06", TypeName = "decimal(18, 0)")] + public decimal InitialProjectionDollarsPerUos06 { get; set; } + + [Column("InitialProjectionDollarsPerUOS07", TypeName = "decimal(18, 0)")] + public decimal InitialProjectionDollarsPerUos07 { get; set; } + + [Column("InitialProjectionDollarsPerUOS08", TypeName = "decimal(18, 0)")] + public decimal InitialProjectionDollarsPerUos08 { get; set; } + + [Column("InitialProjectionDollarsPerUOS09", TypeName = "decimal(18, 0)")] + public decimal InitialProjectionDollarsPerUos09 { get; set; } + + [Column("InitialProjectionDollarsPerUOS10", TypeName = "decimal(18, 0)")] + public decimal InitialProjectionDollarsPerUos10 { get; set; } + + [Column("InitialProjectionDollarsPerUOS11", TypeName = "decimal(18, 0)")] + public decimal InitialProjectionDollarsPerUos11 { get; set; } + + [Column("InitialProjectionDollarsPerUOS12", TypeName = "decimal(18, 0)")] + public decimal InitialProjectionDollarsPerUos12 { get; set; } + + [Column("TargetDollarsPerUOSAdjusted01", TypeName = "decimal(18, 0)")] + public decimal TargetDollarsPerUosadjusted01 { get; set; } + + [Column("TargetDollarsPerUOSAdjusted02", TypeName = "decimal(18, 0)")] + public decimal TargetDollarsPerUosadjusted02 { get; set; } + + [Column("TargetDollarsPerUOSAdjusted03", TypeName = "decimal(18, 0)")] + public decimal TargetDollarsPerUosadjusted03 { get; set; } + + [Column("TargetDollarsPerUOSAdjusted04", TypeName = "decimal(18, 0)")] + public decimal TargetDollarsPerUosadjusted04 { get; set; } + + [Column("TargetDollarsPerUOSAdjusted05", TypeName = "decimal(18, 0)")] + public decimal TargetDollarsPerUosadjusted05 { get; set; } + + [Column("TargetDollarsPerUOSAdjusted06", TypeName = "decimal(18, 0)")] + public decimal TargetDollarsPerUosadjusted06 { get; set; } + + [Column("TargetDollarsPerUOSAdjusted07", TypeName = "decimal(18, 0)")] + public decimal TargetDollarsPerUosadjusted07 { get; set; } + + [Column("TargetDollarsPerUOSAdjusted08", TypeName = "decimal(18, 0)")] + public decimal TargetDollarsPerUosadjusted08 { get; set; } + + [Column("TargetDollarsPerUOSAdjusted09", TypeName = "decimal(18, 0)")] + public decimal TargetDollarsPerUosadjusted09 { get; set; } + + [Column("TargetDollarsPerUOSAdjusted10", TypeName = "decimal(18, 0)")] + public decimal TargetDollarsPerUosadjusted10 { get; set; } + + [Column("TargetDollarsPerUOSAdjusted11", TypeName = "decimal(18, 0)")] + public decimal TargetDollarsPerUosadjusted11 { get; set; } + + [Column("TargetDollarsPerUOSAdjusted12", TypeName = "decimal(18, 0)")] + public decimal TargetDollarsPerUosadjusted12 { get; set; } + + [Column("BudgetDollarsPerUOSAdjusted01", TypeName = "decimal(18, 0)")] + public decimal BudgetDollarsPerUosadjusted01 { get; set; } + + [Column("BudgetDollarsPerUOSAdjusted02", TypeName = "decimal(18, 0)")] + public decimal BudgetDollarsPerUosadjusted02 { get; set; } + + [Column("BudgetDollarsPerUOSAdjusted03", TypeName = "decimal(18, 0)")] + public decimal BudgetDollarsPerUosadjusted03 { get; set; } + + [Column("BudgetDollarsPerUOSAdjusted04", TypeName = "decimal(18, 0)")] + public decimal BudgetDollarsPerUosadjusted04 { get; set; } + + [Column("BudgetDollarsPerUOSAdjusted05", TypeName = "decimal(18, 0)")] + public decimal BudgetDollarsPerUosadjusted05 { get; set; } + + [Column("BudgetDollarsPerUOSAdjusted06", TypeName = "decimal(18, 0)")] + public decimal BudgetDollarsPerUosadjusted06 { get; set; } + + [Column("BudgetDollarsPerUOSAdjusted07", TypeName = "decimal(18, 0)")] + public decimal BudgetDollarsPerUosadjusted07 { get; set; } + + [Column("BudgetDollarsPerUOSAdjusted08", TypeName = "decimal(18, 0)")] + public decimal BudgetDollarsPerUosadjusted08 { get; set; } + + [Column("BudgetDollarsPerUOSAdjusted09", TypeName = "decimal(18, 0)")] + public decimal BudgetDollarsPerUosadjusted09 { get; set; } + + [Column("BudgetDollarsPerUOSAdjusted10", TypeName = "decimal(18, 0)")] + public decimal BudgetDollarsPerUosadjusted10 { get; set; } + + [Column("BudgetDollarsPerUOSAdjusted11", TypeName = "decimal(18, 0)")] + public decimal BudgetDollarsPerUosadjusted11 { get; set; } + + [Column("BudgetDollarsPerUOSAdjusted12", TypeName = "decimal(18, 0)")] + public decimal BudgetDollarsPerUosadjusted12 { get; set; } + + [Column("ProjectionDollarsPerUOSAdjusted01", TypeName = "decimal(18, 0)")] + public decimal ProjectionDollarsPerUosadjusted01 { get; set; } + + [Column("ProjectionDollarsPerUOSAdjusted02", TypeName = "decimal(18, 0)")] + public decimal ProjectionDollarsPerUosadjusted02 { get; set; } + + [Column("ProjectionDollarsPerUOSAdjusted03", TypeName = "decimal(18, 0)")] + public decimal ProjectionDollarsPerUosadjusted03 { get; set; } + + [Column("ProjectionDollarsPerUOSAdjusted04", TypeName = "decimal(18, 0)")] + public decimal ProjectionDollarsPerUosadjusted04 { get; set; } + + [Column("ProjectionDollarsPerUOSAdjusted05", TypeName = "decimal(18, 0)")] + public decimal ProjectionDollarsPerUosadjusted05 { get; set; } + + [Column("ProjectionDollarsPerUOSAdjusted06", TypeName = "decimal(18, 0)")] + public decimal ProjectionDollarsPerUosadjusted06 { get; set; } + + [Column("ProjectionDollarsPerUOSAdjusted07", TypeName = "decimal(18, 0)")] + public decimal ProjectionDollarsPerUosadjusted07 { get; set; } + + [Column("ProjectionDollarsPerUOSAdjusted08", TypeName = "decimal(18, 0)")] + public decimal ProjectionDollarsPerUosadjusted08 { get; set; } + + [Column("ProjectionDollarsPerUOSAdjusted09", TypeName = "decimal(18, 0)")] + public decimal ProjectionDollarsPerUosadjusted09 { get; set; } + + [Column("ProjectionDollarsPerUOSAdjusted10", TypeName = "decimal(18, 0)")] + public decimal ProjectionDollarsPerUosadjusted10 { get; set; } + + [Column("ProjectionDollarsPerUOSAdjusted11", TypeName = "decimal(18, 0)")] + public decimal ProjectionDollarsPerUosadjusted11 { get; set; } + + [Column("ProjectionDollarsPerUOSAdjusted12", TypeName = "decimal(18, 0)")] + public decimal ProjectionDollarsPerUosadjusted12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudgetPercentOfCharge01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudgetPercentOfCharge02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudgetPercentOfCharge03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudgetPercentOfCharge04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudgetPercentOfCharge05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudgetPercentOfCharge06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudgetPercentOfCharge07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudgetPercentOfCharge08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudgetPercentOfCharge09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudgetPercentOfCharge10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudgetPercentOfCharge11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialBudgetPercentOfCharge12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjectionPercentOfCharge01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjectionPercentOfCharge02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjectionPercentOfCharge03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjectionPercentOfCharge04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjectionPercentOfCharge05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjectionPercentOfCharge06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjectionPercentOfCharge07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjectionPercentOfCharge08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjectionPercentOfCharge09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjectionPercentOfCharge10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjectionPercentOfCharge11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal InitialProjectionPercentOfCharge12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentOfChargeAdjusted01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentOfChargeAdjusted02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentOfChargeAdjusted03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentOfChargeAdjusted04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentOfChargeAdjusted05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentOfChargeAdjusted06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentOfChargeAdjusted07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentOfChargeAdjusted08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentOfChargeAdjusted09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentOfChargeAdjusted10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentOfChargeAdjusted11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentOfChargeAdjusted12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentOfChargeAdjusted01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentOfChargeAdjusted02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentOfChargeAdjusted03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentOfChargeAdjusted04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentOfChargeAdjusted05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentOfChargeAdjusted06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentOfChargeAdjusted07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentOfChargeAdjusted08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentOfChargeAdjusted09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentOfChargeAdjusted10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentOfChargeAdjusted11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentOfChargeAdjusted12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentOfChargeAdjusted01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentOfChargeAdjusted02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentOfChargeAdjusted03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentOfChargeAdjusted04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentOfChargeAdjusted05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentOfChargeAdjusted06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentOfChargeAdjusted07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentOfChargeAdjusted08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentOfChargeAdjusted09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentOfChargeAdjusted10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentOfChargeAdjusted11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentOfChargeAdjusted12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentAdjustmentFactor01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentAdjustmentFactor02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentAdjustmentFactor03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentAdjustmentFactor04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentAdjustmentFactor05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentAdjustmentFactor06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentAdjustmentFactor07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentAdjustmentFactor08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentAdjustmentFactor09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentAdjustmentFactor10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentAdjustmentFactor11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal TargetPercentAdjustmentFactor12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentAdjustmentFactor01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentAdjustmentFactor02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentAdjustmentFactor03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentAdjustmentFactor04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentAdjustmentFactor05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentAdjustmentFactor06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentAdjustmentFactor07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentAdjustmentFactor08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentAdjustmentFactor09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentAdjustmentFactor10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentAdjustmentFactor11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BudgetPercentAdjustmentFactor12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentAdjustmentFactor01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentAdjustmentFactor02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentAdjustmentFactor03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentAdjustmentFactor04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentAdjustmentFactor05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentAdjustmentFactor06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentAdjustmentFactor07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentAdjustmentFactor08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentAdjustmentFactor09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentAdjustmentFactor10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentAdjustmentFactor11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal ProjectionPercentAdjustmentFactor12 { get; set; } + + [ForeignKey("DepartmentId")] + [InverseProperty("GeneralLedgers")] + public virtual DimDepartment Department { get; set; } = null!; +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/GeneralLedgerInitialPlanConfigDetail.cs b/ef-migration/src/Strata.Code.DataAccess/Models/GeneralLedgerInitialPlanConfigDetail.cs new file mode 100644 index 0000000..95b5092 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/GeneralLedgerInitialPlanConfigDetail.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("GeneralLedgerInitialPlanConfigDetail", Schema = "fp")] +public partial class GeneralLedgerInitialPlanConfigDetail +{ + [Key] + [Column("RowID")] + public int RowId { get; set; } + + [Column("BudgetConfigGUID")] + public Guid BudgetConfigGuid { get; set; } + + [Column("BudgetConfigID")] + public short BudgetConfigId { get; set; } + + [Column("EntityID")] + public int EntityId { get; set; } + + [Column("DepartmentID")] + public int DepartmentId { get; set; } + + [Column("AccountID")] + public int AccountId { get; set; } + + [Column("FinancialReportingID")] + public int FinancialReportingId { get; set; } + + [Column("VariabilityID")] + public int VariabilityId { get; set; } + + [Column("APEModelSectionID")] + public int ApemodelSectionId { get; set; } + + [Column("TimeClassID")] + public byte TimeClassId { get; set; } + + [Column("ProjectionMethodID")] + public int ProjectionMethodId { get; set; } + + public byte TrailingMonths { get; set; } + + [Column("VersionID")] + public int VersionId { get; set; } + + [ForeignKey("BudgetConfigGuid")] + [InverseProperty("GeneralLedgerInitialPlanConfigDetails")] + public virtual BudgetConfig BudgetConfig { get; set; } = null!; +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/GeneralLedgerSpread.cs b/ef-migration/src/Strata.Code.DataAccess/Models/GeneralLedgerSpread.cs new file mode 100644 index 0000000..a92e0a7 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/GeneralLedgerSpread.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[PrimaryKey("BudgetConfigId", "DepartmentId", "AccountId")] +[Table("GeneralLedgerSpreads", Schema = "fp")] +public partial class GeneralLedgerSpread +{ + [Key] + [Column("BudgetConfigID")] + public int BudgetConfigId { get; set; } + + [Key] + [Column("DepartmentID")] + public int DepartmentId { get; set; } + + [Key] + [Column("AccountID")] + public int AccountId { get; set; } + + public bool IsInactive { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? TotalImportedValue { get; set; } + + [Column("SpreadHistoryGUID")] + public Guid SpreadHistoryGuid { get; set; } + + [Column("GlobalSpreadID")] + public int GlobalSpreadId { get; set; } + + [ForeignKey("SpreadHistoryGuid")] + [InverseProperty("GeneralLedgerSpreads")] + public virtual SpreadHistory SpreadHistory { get; set; } = null!; +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/InitialPlanRule.cs b/ef-migration/src/Strata.Code.DataAccess/Models/InitialPlanRule.cs new file mode 100644 index 0000000..929bf6c --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/InitialPlanRule.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("InitialPlanRule", Schema = "fp")] +public partial class InitialPlanRule +{ + [Key] + [Column("RowID")] + public int RowId { get; set; } + + [Column("BudgetConfigGUID")] + public Guid BudgetConfigGuid { get; set; } + + [Column("BudgetConfigID")] + public short BudgetConfigId { get; set; } + + [Column("PlanSectionID")] + public int PlanSectionId { get; set; } + + [Column("SubSectionID")] + public int SubSectionId { get; set; } + + [Column("TimeClassID")] + public byte TimeClassId { get; set; } + + [Column("DimensionalityJSON")] + public string DimensionalityJson { get; set; } = null!; + + [Column("ProjectionMethodID")] + public int ProjectionMethodId { get; set; } + + public byte TrailingMonths { get; set; } + + public int RulePriority { get; set; } + + [Column("VersionID")] + public int? VersionId { get; set; } + + [ForeignKey("BudgetConfigGuid")] + [InverseProperty("InitialPlanRules")] + public virtual BudgetConfig BudgetConfig { get; set; } = null!; +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/Lock.cs b/ef-migration/src/Strata.Code.DataAccess/Models/Lock.cs new file mode 100644 index 0000000..1febce4 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/Lock.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Keyless] +[Table("Lock")] +public partial class Lock +{ + [Column("LockGUID")] + public Guid LockGuid { get; set; } + + [Column("ItemGUID")] + public Guid ItemGuid { get; set; } + + [Column("UserGUID")] + public Guid UserGuid { get; set; } + + [Column(TypeName = "datetime")] + public DateTime DateLocked { get; set; } + + [StringLength(64)] + public string LockGroup { get; set; } = null!; + + [Column(TypeName = "datetime")] + public DateTime DateLastActive { get; set; } + + [StringLength(256)] + public string UserName { get; set; } = null!; + + [Column(TypeName = "datetime")] + public DateTime DateLockedUtc { get; set; } + + [Column(TypeName = "datetime")] + public DateTime DateLastActiveUtc { get; set; } +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/OnePlanPerformanceTestValidationResult.cs b/ef-migration/src/Strata.Code.DataAccess/Models/OnePlanPerformanceTestValidationResult.cs new file mode 100644 index 0000000..c1f4533 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/OnePlanPerformanceTestValidationResult.cs @@ -0,0 +1,135 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Keyless] +[Table("OnePlanPerformanceTestValidationResult", Schema = "fp")] +public partial class OnePlanPerformanceTestValidationResult +{ + [Column("TestResultID")] + public int TestResultId { get; set; } + + [Column("PlanSectionID")] + public int PlanSectionId { get; set; } + + [Column("BasisID")] + public int BasisId { get; set; } + + [StringLength(100)] + public string TableName { get; set; } = null!; + + [StringLength(100)] + public string ColumnName { get; set; } = null!; + + [Column(TypeName = "decimal(18, 0)")] + public decimal BeforeValue01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BeforeValue02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BeforeValue03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BeforeValue04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BeforeValue05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BeforeValue06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BeforeValue07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BeforeValue08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BeforeValue09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BeforeValue10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BeforeValue11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal BeforeValue12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal AfterValue01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal AfterValue02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal AfterValue03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal AfterValue04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal AfterValue05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal AfterValue06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal AfterValue07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal AfterValue08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal AfterValue09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal AfterValue10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal AfterValue11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal AfterValue12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? Variance01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? Variance02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? Variance03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? Variance04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? Variance05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? Variance06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? Variance07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? Variance08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? Variance09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? Variance10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? Variance11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? Variance12 { get; set; } +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/PerformanceTestingSetting.cs b/ef-migration/src/Strata.Code.DataAccess/Models/PerformanceTestingSetting.cs new file mode 100644 index 0000000..2ed6729 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/PerformanceTestingSetting.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("PerformanceTestingSetting", Schema = "fp")] +[Index("Name", Name = "IX_PerformanceTestingSetting_Unique", IsUnique = true)] +public partial class PerformanceTestingSetting +{ + [Key] + [Column("SystemSettingID")] + public int SystemSettingId { get; set; } + + [StringLength(100)] + public string Name { get; set; } = null!; + + [StringLength(400)] + public string Description { get; set; } = null!; + + public string Value { get; set; } = null!; + + public bool IsEditable { get; set; } + + public int ColumnType { get; set; } + + [StringLength(100)] + public string DefaultValue { get; set; } = null!; + + public bool IsEncrypted { get; set; } + + public DateOnly DateCreated { get; set; } +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/ProviderCompensationSpread.cs b/ef-migration/src/Strata.Code.DataAccess/Models/ProviderCompensationSpread.cs new file mode 100644 index 0000000..705aed0 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/ProviderCompensationSpread.cs @@ -0,0 +1,95 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[PrimaryKey("BudgetConfigId", "ProviderId", "ProviderLineItemId", "DepartmentId", "JobCodeId", "PayCodeGroupId", "UnitTypeId")] +[Table("ProviderCompensationSpreads", Schema = "fp")] +public partial class ProviderCompensationSpread +{ + [Key] + [Column("BudgetConfigID")] + public int BudgetConfigId { get; set; } + + [Key] + [Column("ProviderID")] + public int ProviderId { get; set; } + + [Key] + [Column("ProviderLineItemID")] + public int ProviderLineItemId { get; set; } + + [Key] + [Column("DepartmentID")] + public int DepartmentId { get; set; } + + [Key] + [Column("JobCodeID")] + public int JobCodeId { get; set; } + + [Key] + [Column("PayCodeGroupID")] + public int PayCodeGroupId { get; set; } + + public bool IsInactive { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? TotalImportedValue { get; set; } + + [Column("SpreadHistoryGUID")] + public Guid SpreadHistoryGuid { get; set; } + + [Column("GlobalSpreadID")] + public int GlobalSpreadId { get; set; } + + [Key] + [Column("UnitTypeID")] + public byte UnitTypeId { get; set; } + + [ForeignKey("DepartmentId")] + [InverseProperty("ProviderCompensationSpreads")] + public virtual DimDepartment Department { get; set; } = null!; + + [ForeignKey("SpreadHistoryGuid")] + [InverseProperty("ProviderCompensationSpreads")] + public virtual SpreadHistory SpreadHistory { get; set; } = null!; +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/SamplingLog.cs b/ef-migration/src/Strata.Code.DataAccess/Models/SamplingLog.cs new file mode 100644 index 0000000..262def3 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/SamplingLog.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Keyless] +[Table("SamplingLog", Schema = "fp")] +public partial class SamplingLog +{ + [Column("BudgetConfigID")] + public int BudgetConfigId { get; set; } + + [Column("EntityGroupConfigID")] + public int EntityGroupConfigId { get; set; } + + [Column("PlanSectionID")] + public int PlanSectionId { get; set; } + + [StringLength(300)] + public string PlanSectionDescription { get; set; } = null!; + + [Column("SourceDimensionalityJSON")] + public string SourceDimensionalityJson { get; set; } = null!; + + [Column("DateStartedUTC", TypeName = "datetime")] + public DateTime DateStartedUtc { get; set; } + + [Column("DateEndedUTC", TypeName = "datetime")] + public DateTime DateEndedUtc { get; set; } + + public bool IsInitialPlanMethod { get; set; } + + [Column("IsDSSampling")] + public bool IsDssampling { get; set; } + + public int NumberOfRecordsSampled { get; set; } + + [StringLength(10)] + public string JazzVersion { get; set; } = null!; +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/ScheduledRefreshRequest.cs b/ef-migration/src/Strata.Code.DataAccess/Models/ScheduledRefreshRequest.cs new file mode 100644 index 0000000..6bc6d06 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/ScheduledRefreshRequest.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("ScheduledRefreshRequest", Schema = "fp")] +public partial class ScheduledRefreshRequest +{ + [Key] + [Column("RequestGUID")] + public Guid RequestGuid { get; set; } + + [Column("SourceDimensionalityJSON")] + public string SourceDimensionalityJson { get; set; } = null!; + + [Column("SourceActionID")] + public short SourceActionId { get; set; } + + public bool IsIgnoreTargetingError { get; set; } + + [Column("EntityGroupConfigID")] + public int EntityGroupConfigId { get; set; } + + [Column("SamplingJSON")] + public string SamplingJson { get; set; } = null!; + + public int SortOrder { get; set; } + + public bool IsActive { get; set; } +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/ServiceLineEncounterSpread.cs b/ef-migration/src/Strata.Code.DataAccess/Models/ServiceLineEncounterSpread.cs new file mode 100644 index 0000000..0dd6e64 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/ServiceLineEncounterSpread.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[PrimaryKey("BudgetConfigId", "EntityId", "ServiceLineId", "PatientClassId")] +[Table("ServiceLineEncounterSpreads", Schema = "fp")] +public partial class ServiceLineEncounterSpread +{ + [Key] + [Column("BudgetConfigID")] + public int BudgetConfigId { get; set; } + + [Key] + [Column("EntityID")] + public int EntityId { get; set; } + + [Key] + [Column("ServiceLineID")] + public int ServiceLineId { get; set; } + + [Key] + [Column("PatientClassID")] + public int PatientClassId { get; set; } + + public bool IsInactive { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? TotalImportedValue { get; set; } + + [Column("SpreadHistoryGUID")] + public Guid SpreadHistoryGuid { get; set; } + + [Column("GlobalSpreadID")] + public int GlobalSpreadId { get; set; } + + [ForeignKey("SpreadHistoryGuid")] + [InverseProperty("ServiceLineEncounterSpreads")] + public virtual SpreadHistory SpreadHistory { get; set; } = null!; +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/SettingCategory.cs b/ef-migration/src/Strata.Code.DataAccess/Models/SettingCategory.cs new file mode 100644 index 0000000..ce24a5b --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/SettingCategory.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Keyless] +[Table("SettingCategory", Schema = "fp")] +public partial class SettingCategory +{ + [Column("SettingCategoryID")] + public int SettingCategoryId { get; set; } + + [Column("CategoryID")] + public int CategoryId { get; set; } + + [Column("SystemSettingID")] + public int SystemSettingId { get; set; } + + [Column("BudgetConfigDefaultSettingID")] + public int BudgetConfigDefaultSettingId { get; set; } +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/SpreadHistory.cs b/ef-migration/src/Strata.Code.DataAccess/Models/SpreadHistory.cs new file mode 100644 index 0000000..fbf5127 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/SpreadHistory.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("SpreadHistory", Schema = "fp")] +public partial class SpreadHistory +{ + [Key] + [Column("SpreadHistoryGUID")] + public Guid SpreadHistoryGuid { get; set; } + + [Column(TypeName = "datetime")] + public DateTime Date { get; set; } + + [Column("AuthorGUID")] + public Guid AuthorGuid { get; set; } + + public string AuthorFullName { get; set; } = null!; + + public byte[]? ExcelFile { get; set; } + + [InverseProperty("SpreadHistory")] + public virtual ICollection BenefitsSpreads { get; set; } = new List(); + + [InverseProperty("SpreadHistory")] + public virtual ICollection ChargeVolumeSpreads { get; set; } = new List(); + + [InverseProperty("SpreadHistory")] + public virtual ICollection GeneralLedgerSpreads { get; set; } = new List(); + + [InverseProperty("SpreadHistory")] + public virtual ICollection ProviderCompensationSpreads { get; set; } = new List(); + + [InverseProperty("SpreadHistory")] + public virtual ICollection ServiceLineEncounterSpreads { get; set; } = new List(); + + [InverseProperty("SpreadHistory")] + public virtual ICollection StaffingSpreads { get; set; } = new List(); + + [InverseProperty("SpreadHistory")] + public virtual ICollection StatisticsSpreads { get; set; } = new List(); +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/StaffingInitialPlanConfigDetail.cs b/ef-migration/src/Strata.Code.DataAccess/Models/StaffingInitialPlanConfigDetail.cs new file mode 100644 index 0000000..6457033 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/StaffingInitialPlanConfigDetail.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("StaffingInitialPlanConfigDetail", Schema = "fp")] +public partial class StaffingInitialPlanConfigDetail +{ + [Key] + [Column("RowID")] + public int RowId { get; set; } + + [Column("BudgetConfigGUID")] + public Guid BudgetConfigGuid { get; set; } + + [Column("BudgetConfigID")] + public short BudgetConfigId { get; set; } + + [Column("DepartmentID")] + public int DepartmentId { get; set; } + + [Column("JobCodeID")] + public int JobCodeId { get; set; } + + [Column("ProductiveClassID")] + public int ProductiveClassId { get; set; } + + [Column("PayCodeGroupID")] + public int PayCodeGroupId { get; set; } + + [Column("VariabilityID")] + public int VariabilityId { get; set; } + + [Column("TimeClassID")] + public byte TimeClassId { get; set; } + + [Column("UnitTypeID")] + public byte UnitTypeId { get; set; } + + [Column("EmployeeID")] + public int EmployeeId { get; set; } + + [Column("ProviderID")] + public int ProviderId { get; set; } + + [Column("ProviderLineItemID")] + public int ProviderLineItemId { get; set; } + + [Column("ProviderTypeID")] + public int ProviderTypeId { get; set; } + + [Column("ProviderSpecialtyID")] + public int ProviderSpecialtyId { get; set; } + + [Column("ProjectionMethodID")] + public int ProjectionMethodId { get; set; } + + public byte TrailingMonths { get; set; } + + [Column("VersionID")] + public int VersionId { get; set; } + + [ForeignKey("BudgetConfigGuid")] + [InverseProperty("StaffingInitialPlanConfigDetails")] + public virtual BudgetConfig BudgetConfig { get; set; } = null!; +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/StaffingSpread.cs b/ef-migration/src/Strata.Code.DataAccess/Models/StaffingSpread.cs new file mode 100644 index 0000000..3e44dac --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/StaffingSpread.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[PrimaryKey("BudgetConfigId", "DepartmentId", "JobCodeId", "PayCodeGroupId")] +[Table("StaffingSpreads", Schema = "fp")] +public partial class StaffingSpread +{ + [Key] + [Column("BudgetConfigID")] + public int BudgetConfigId { get; set; } + + [Key] + [Column("DepartmentID")] + public int DepartmentId { get; set; } + + [Key] + [Column("JobCodeID")] + public int JobCodeId { get; set; } + + [Key] + [Column("PayCodeGroupID")] + public int PayCodeGroupId { get; set; } + + public bool IsInactive { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? TotalImportedValue { get; set; } + + [Column("SpreadHistoryGUID")] + public Guid SpreadHistoryGuid { get; set; } + + [Column("GlobalSpreadID")] + public int GlobalSpreadId { get; set; } + + [ForeignKey("DepartmentId")] + [InverseProperty("StaffingSpreads")] + public virtual DimDepartment Department { get; set; } = null!; + + [ForeignKey("SpreadHistoryGuid")] + [InverseProperty("StaffingSpreads")] + public virtual SpreadHistory SpreadHistory { get; set; } = null!; +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/StatisticsSpread.cs b/ef-migration/src/Strata.Code.DataAccess/Models/StatisticsSpread.cs new file mode 100644 index 0000000..5884ef3 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/StatisticsSpread.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[PrimaryKey("BudgetConfigId", "DepartmentId", "AccountId", "ProviderId", "ProviderLineItemId")] +[Table("StatisticsSpreads", Schema = "fp")] +public partial class StatisticsSpread +{ + [Key] + [Column("BudgetConfigID")] + public int BudgetConfigId { get; set; } + + [Key] + [Column("DepartmentID")] + public int DepartmentId { get; set; } + + [Key] + [Column("AccountID")] + public int AccountId { get; set; } + + public bool IsInactive { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage01 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage02 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage03 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage04 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage05 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage06 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage07 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage08 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage09 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage10 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage11 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? SpreadPercentage12 { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal? TotalImportedValue { get; set; } + + [Column("SpreadHistoryGUID")] + public Guid SpreadHistoryGuid { get; set; } + + [Column("GlobalSpreadID")] + public int GlobalSpreadId { get; set; } + + [Key] + [Column("ProviderID")] + public int ProviderId { get; set; } + + [Key] + [Column("ProviderLineItemID")] + public int ProviderLineItemId { get; set; } + + [ForeignKey("DepartmentId")] + [InverseProperty("StatisticsSpreads")] + public virtual DimDepartment Department { get; set; } = null!; + + [ForeignKey("SpreadHistoryGuid")] + [InverseProperty("StatisticsSpreads")] + public virtual SpreadHistory SpreadHistory { get; set; } = null!; +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/SystemSetting.cs b/ef-migration/src/Strata.Code.DataAccess/Models/SystemSetting.cs new file mode 100644 index 0000000..aa57255 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/SystemSetting.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("SystemSetting", Schema = "fp")] +[Index("Name", Name = "IX_SystemSetting_Unique", IsUnique = true)] +public partial class SystemSetting +{ + [Key] + [Column("SystemSettingID")] + public int SystemSettingId { get; set; } + + [StringLength(100)] + public string Name { get; set; } = null!; + + [StringLength(400)] + public string Description { get; set; } = null!; + + public string Value { get; set; } = null!; + + public bool IsEditable { get; set; } + + public int ColumnType { get; set; } + + [StringLength(100)] + public string DefaultValue { get; set; } = null!; + + public bool IsEncrypted { get; set; } + + public bool IsFeatureFlag { get; set; } + + public DateOnly DateCreated { get; set; } +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/TescheduledTask.cs b/ef-migration/src/Strata.Code.DataAccess/Models/TescheduledTask.cs new file mode 100644 index 0000000..5277de6 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/TescheduledTask.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("TEScheduledTask")] +public partial class TescheduledTask +{ + [Key] + [Column("ScheduledTaskGUID")] + public Guid ScheduledTaskGuid { get; set; } + + [StringLength(64)] + public string Name { get; set; } = null!; + + [StringLength(450)] + public string Description { get; set; } = null!; + + public int RepeatType { get; set; } + + public int RepeatFrequency { get; set; } + + public int DayOfWeek { get; set; } + + public int DayOfMonth { get; set; } + + [Column(TypeName = "datetime")] + public DateTime StartDate { get; set; } + + [Column(TypeName = "datetime")] + public DateTime EndDate { get; set; } + + public bool HasEndDate { get; set; } + + [Column("SetupXML")] + public string SetupXml { get; set; } = null!; + + [StringLength(450)] + public string AssemblyQualifiedName { get; set; } = null!; + + public bool HasRun { get; set; } + + public bool IsDisabled { get; set; } + + public bool HasDisabledExpirationDate { get; set; } + + [Column(TypeName = "datetime")] + public DateTime DisabledExpirationDate { get; set; } + + [Column(TypeName = "datetime")] + public DateTime DateCreatedUtc { get; set; } + + [Column(TypeName = "datetime")] + public DateTime LastRunDateUtc { get; set; } + + [Column(TypeName = "datetime")] + public DateTime LastSubmittedDateUtc { get; set; } + + public TimeOnly StartTime { get; set; } + + [StringLength(50)] + public string TimeZoneId { get; set; } = null!; +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/UserProfile.cs b/ef-migration/src/Strata.Code.DataAccess/Models/UserProfile.cs new file mode 100644 index 0000000..25972d3 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/UserProfile.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Table("UserProfile")] +[Index("UserName", Name = "IX_UserProfile", IsUnique = true)] +public partial class UserProfile +{ + [Key] + [Column("UserGUID")] + public Guid UserGuid { get; set; } + + [StringLength(64)] + public string UserName { get; set; } = null!; + + [StringLength(64)] + public string HashedPassword { get; set; } = null!; + + [StringLength(64)] + public string NameFirst { get; set; } = null!; + + [StringLength(64)] + public string NameLast { get; set; } = null!; + + [StringLength(130)] + public string NameFull { get; set; } = null!; + + [StringLength(450)] + public string EmailAddress { get; set; } = null!; + + [StringLength(64)] + public string PhoneNumber { get; set; } = null!; + + [Column("IsSysAdmin_DEPRECATED")] + public bool IsSysAdminDeprecated { get; set; } + + [Column("AuthID")] + [StringLength(128)] + public string AuthId { get; set; } = null!; + + public bool IsDisabled { get; set; } + + [StringLength(64)] + public string BackupPassword { get; set; } = null!; + + public byte DefaultAppModeLevel { get; set; } + + [StringLength(64)] + public string BrowserVersion { get; set; } = null!; + + [StringLength(512)] + public string UserAgent { get; set; } = null!; + + [StringLength(64)] + [Unicode(false)] + public string Domain { get; set; } = null!; + + [Column("HIPAADisclaimerStatus")] + public byte HipaadisclaimerStatus { get; set; } + + [StringLength(450)] + public string Custom1 { get; set; } = null!; + + [StringLength(450)] + public string Custom2 { get; set; } = null!; + + [StringLength(450)] + public string Custom3 { get; set; } = null!; + + [StringLength(450)] + public string Custom4 { get; set; } = null!; + + public bool IsHidden { get; set; } + + [StringLength(250)] + public string DotNetVersion { get; set; } = null!; + + [Column(TypeName = "datetime")] + public DateTime LastChangedPasswordUtc { get; set; } + + [Column(TypeName = "datetime")] + public DateTime LastLoginDateUtc { get; set; } + + public Guid Salt { get; set; } + + public bool NeedsPasswordChange { get; set; } +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/ViewReimbursementAdjustment.cs b/ef-migration/src/Strata.Code.DataAccess/Models/ViewReimbursementAdjustment.cs new file mode 100644 index 0000000..ae24b0c --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/ViewReimbursementAdjustment.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Keyless] +public partial class ViewReimbursementAdjustment +{ + [Column("AdjustmentGUID")] + public Guid AdjustmentGuid { get; set; } + + [Column("BudgetConfigGUID")] + public Guid BudgetConfigGuid { get; set; } + + public byte AdjustmentType { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value { get; set; } + + [Column("AdjustmentFilterJSON")] + public string AdjustmentFilterJson { get; set; } = null!; + + [Column("GroupingHierarchyJSON")] + public string GroupingHierarchyJson { get; set; } = null!; + + [StringLength(100)] + public string AdjustedProperty { get; set; } = null!; + + public string Comment { get; set; } = null!; + + [Column("AuthorGUID")] + public Guid AuthorGuid { get; set; } + + [StringLength(260)] + public string AuthorFullName { get; set; } = null!; + + [Column("GroupingGUID")] + public Guid GroupingGuid { get; set; } + + [Column("TimeClassID")] + public byte TimeClassId { get; set; } + + [Column("ClassificationGroupID")] + public int ClassificationGroupId { get; set; } + + [Column("ClassificationCategoryID")] + public int ClassificationCategoryId { get; set; } + + public bool IsRecordDeleted { get; set; } + + [Column(TypeName = "datetime")] + public DateTime DateCreatedUtc { get; set; } + + [Column(TypeName = "datetime")] + public DateTime LastModifiedDateUtc { get; set; } + + public string DimensionMemberJson { get; set; } = null!; + + public int AffectedDataCount { get; set; } + + [Column("UnitTypeID")] + public byte UnitTypeId { get; set; } + + public bool IsCarryForward { get; set; } + + [Column("AdjustmentID")] + public int AdjustmentId { get; set; } + + [Column("BudgetPhaseID")] + public byte BudgetPhaseId { get; set; } +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/ViewStaffingAdjustment.cs b/ef-migration/src/Strata.Code.DataAccess/Models/ViewStaffingAdjustment.cs new file mode 100644 index 0000000..be617e5 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/ViewStaffingAdjustment.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Keyless] +public partial class ViewStaffingAdjustment +{ + [Column("AdjustmentGUID")] + public Guid AdjustmentGuid { get; set; } + + [Column("BudgetConfigGUID")] + public Guid BudgetConfigGuid { get; set; } + + public byte AdjustmentType { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value { get; set; } + + [Column("AdjustmentFilterJSON")] + public string AdjustmentFilterJson { get; set; } = null!; + + [Column("GroupingHierarchyJSON")] + public string GroupingHierarchyJson { get; set; } = null!; + + [StringLength(100)] + public string AdjustedProperty { get; set; } = null!; + + public string Comment { get; set; } = null!; + + [Column("AuthorGUID")] + public Guid AuthorGuid { get; set; } + + [StringLength(260)] + public string AuthorFullName { get; set; } = null!; + + [Column(TypeName = "datetime")] + public DateTime LastModifiedDateUtc { get; set; } + + [Column(TypeName = "datetime")] + public DateTime DateCreatedUtc { get; set; } + + [Column("UnitTypeID")] + public byte UnitTypeId { get; set; } + + [Column("GroupingGUID")] + public Guid GroupingGuid { get; set; } + + [Column("ParentFilterJSON")] + public string ParentFilterJson { get; set; } = null!; + + [Column("TimeClassID")] + public byte TimeClassId { get; set; } + + [Column("BudgetPhaseID")] + public byte BudgetPhaseId { get; set; } + + [Column("ClassificationGroupID")] + public int ClassificationGroupId { get; set; } + + [Column("ClassificationCategoryID")] + public int ClassificationCategoryId { get; set; } + + public bool IsRecordDeleted { get; set; } + + public string DimensionMemberJson { get; set; } = null!; + + [Column("AdjustmentID")] + public int AdjustmentId { get; set; } + + [Column("SubsectionID")] + public int SubsectionId { get; set; } + + public bool IsErrored { get; set; } +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Models/ViewStatisticsAdjustment.cs b/ef-migration/src/Strata.Code.DataAccess/Models/ViewStatisticsAdjustment.cs new file mode 100644 index 0000000..d63bceb --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Models/ViewStatisticsAdjustment.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using Microsoft.EntityFrameworkCore; + +namespace Strata.Code.DataAccess.Models; + +[Keyless] +public partial class ViewStatisticsAdjustment +{ + [Column("AdjustmentGUID")] + public Guid AdjustmentGuid { get; set; } + + [Column("BudgetConfigGUID")] + public Guid BudgetConfigGuid { get; set; } + + public byte AdjustmentType { get; set; } + + [Column(TypeName = "decimal(18, 0)")] + public decimal Value { get; set; } + + [Column("AdjustmentFilterJSON")] + public string AdjustmentFilterJson { get; set; } = null!; + + [Column("GroupingHierarchyJSON")] + public string GroupingHierarchyJson { get; set; } = null!; + + [StringLength(100)] + public string AdjustedProperty { get; set; } = null!; + + public string Comment { get; set; } = null!; + + [Column("AuthorGUID")] + public Guid AuthorGuid { get; set; } + + [StringLength(260)] + public string AuthorFullName { get; set; } = null!; + + [Column(TypeName = "datetime")] + public DateTime LastModifiedDateUtc { get; set; } + + [Column(TypeName = "datetime")] + public DateTime DateCreatedUtc { get; set; } + + [Column("GroupingGUID")] + public Guid GroupingGuid { get; set; } + + [Column("ParentFilterJSON")] + public string ParentFilterJson { get; set; } = null!; + + [Column("TimeClassID")] + public byte TimeClassId { get; set; } + + [Column("BudgetPhaseID")] + public byte BudgetPhaseId { get; set; } + + [Column("ClassificationGroupID")] + public int ClassificationGroupId { get; set; } + + [Column("ClassificationCategoryID")] + public int ClassificationCategoryId { get; set; } + + public bool IsRecordDeleted { get; set; } + + public string DimensionMemberJson { get; set; } = null!; + + [Column("AdjustmentID")] + public int AdjustmentId { get; set; } + + [Column("SubsectionID")] + public int SubsectionId { get; set; } + + public bool IsErrored { get; set; } +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Strata.Code.DataAccess.csproj b/ef-migration/src/Strata.Code.DataAccess/Strata.Code.DataAccess.csproj new file mode 100644 index 0000000..b3834c8 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Strata.Code.DataAccess.csproj @@ -0,0 +1,21 @@ + + + + net9.0 + enable + enable + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + diff --git a/ef-migration/tools/scaffold.bat b/ef-migration/tools/scaffold.bat new file mode 100644 index 0000000..928ec8d --- /dev/null +++ b/ef-migration/tools/scaffold.bat @@ -0,0 +1,64 @@ +@echo off +cd ..\src\Strata.Code.DataAccess +dotnet ef dbcontext scaffold^ + "Server=54.71.217.228,1433;Database=st-database;User=sa;Password=YourStrong@Passw0rd;TrustServerCertificate=True;"^ + Microsoft.EntityFrameworkCore.SqlServer^ + --project Strata.Code.DataAccess.csproj^ + --context-dir Data^ + --output-dir Models^ + --context OnePlanDbContext^ + --force^ + --data-annotations^ + --no-onconfiguring^ + -t fp.AddProviderEncountersDataForCharges^ + -t fp.AddProviderSummary^ + -t fp.AdjustmentChunkingConfiguration^ + -t fp.APEDepartmentWorkflowStatus^ + -t fp.APEWorkflow^ + -t fp.BenefitsSpreads^ + -t fp.BudgetConfig^ + -t fp.BudgetConfigDefaultSetting^ + -t fp.BudgetConfigSetting^ + -t fp.BudgetRefreshRequest^ + -t fp.BudgetRefreshRequestHistory^ + -t fp.ChargeVolumeAddProviderAdjustment^ + -t fp.ChargeVolumeSpreads^ + -t fp.DataRefreshTargetThreshold^ + -t fp.DepartmentChargeVolumeAdjustment^ + -t fp.DepartmentConfig^ + -t fp.DimCategory^ + -t fw.DimDepartment^ + -t dss.DimPhysician^ + -t fp.EngineLog^ + -t fp.EntityGroupConfig^ + -t fp.FixChangeHistoryRequest^ + -t fp.GeneralLedger^ + -t fp.GeneralLedgerInitialPlanConfigDetail^ + -t fp.GeneralLedgerSpreads^ + -t fp.InitialPlanRule^ + -t dbo.LOCK^ + -t dbo.log^ + -t dbo.OnePlanPerformanceTestHistory^ + -t fp.OnePlanPerformanceTestValidationResult^ + -t fp.PerformanceTestingSetting^ + -t fp.ProviderCompensationSpreads^ + -t fp.SamplingLog^ + -t fp.ScheduledRefreshRequest^ + -t fp.ServiceLineEncounterSpreads^ + -t fp.SettingCategory^ + -t fp.SpreadHistory^ + -t fp.StaffingInitialPlanConfigDetail^ + -t fp.StaffingSpreads^ + -t fp.StatisticsSpreads^ + -t fp.SystemSetting^ + -t dbo.TEScheduledTask^ + -t dbo.UserProfile^ + -t fp.viewBenefitsAdjustment^ + -t fp.viewDepartmentChargeVolumeAdjustment^ + -t fp.viewGeneralLedgerAdjustment^ + -t fp.viewReimbursementAdjustment^ + -t fp.viewReimbursementGeneralLedgerAdjustment^ + -t fp.viewServiceLineEncounterAdjustment^ + -t fp.viewStaffingAdjustment^ + -t fp.viewStatisticsAdjustment +pause \ No newline at end of file -- 2.45.2 From ea93e32194c9e63aa42d7fd9fcc0cbd4c41ca6e2 Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Wed, 5 Feb 2025 21:36:49 -0500 Subject: [PATCH 27/31] Create new web Project for the Database testing --- ef-migration/Strata.Code.sln | 20 +- ef-migration/readme.md | 291 +++++++----------- .../BudgetConfigDefaultSettingService.cs | 71 +++++ .../IBudgetConfigDefaultSettingService.cs | 30 ++ .../Strata.Code.Business.csproj | 13 + .../src/Strata.Code.DataAccess/Class1.cs | 6 - .../BudgetConfigDefaultSettingRepository.cs | 66 ++++ .../IBudgetConfigDefaultSettingRepository.cs | 13 + .../Strata.Code.DataAccess.csproj | 9 +- .../BudgetConfigDefaultSettingController .cs | 77 +++++ ef-migration/src/Strata.Code.Web/Program.cs | 51 +++ .../Properties/launchSettings.json | 41 +++ .../Strata.Code.Web/Strata.Code.Web.csproj | 18 ++ .../appsettings.Development.json | 8 + .../src/Strata.Code.Web/appsettings.json | 12 + 15 files changed, 535 insertions(+), 191 deletions(-) create mode 100644 ef-migration/src/Strata.Code.Business/Services/BudgetConfigDefaultSettingService.cs create mode 100644 ef-migration/src/Strata.Code.Business/Services/Interfaces/IBudgetConfigDefaultSettingService.cs create mode 100644 ef-migration/src/Strata.Code.Business/Strata.Code.Business.csproj delete mode 100644 ef-migration/src/Strata.Code.DataAccess/Class1.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Repositories/BudgetConfigDefaultSettingRepository.cs create mode 100644 ef-migration/src/Strata.Code.DataAccess/Repositories/Interfaces/IBudgetConfigDefaultSettingRepository.cs create mode 100644 ef-migration/src/Strata.Code.Web/Controllers/BudgetConfigDefaultSettingController .cs create mode 100644 ef-migration/src/Strata.Code.Web/Program.cs create mode 100644 ef-migration/src/Strata.Code.Web/Properties/launchSettings.json create mode 100644 ef-migration/src/Strata.Code.Web/Strata.Code.Web.csproj create mode 100644 ef-migration/src/Strata.Code.Web/appsettings.Development.json create mode 100644 ef-migration/src/Strata.Code.Web/appsettings.json diff --git a/ef-migration/Strata.Code.sln b/ef-migration/Strata.Code.sln index 1489653..78f4e81 100644 --- a/ef-migration/Strata.Code.sln +++ b/ef-migration/Strata.Code.sln @@ -5,18 +5,32 @@ VisualStudioVersion = 17.0.31903.59 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Strata.Code.DataAccess", "src\Strata.Code.DataAccess\Strata.Code.DataAccess.csproj", "{C27AA99E-EEC0-41FE-B949-F4EEED1F3952}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Strata.Code.Business", "src\Strata.Code.Business\Strata.Code.Business.csproj", "{478E3F10-2B5C-4D40-BE53-327E5B2AD0AC}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{C4F5F2DA-7191-4ACE-8EC4-5715C1E9388E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Strata.Code.Web", "src\Strata.Code.Web\Strata.Code.Web.csproj", "{120D37EF-20DC-492B-AB2B-8A887627A211}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {C27AA99E-EEC0-41FE-B949-F4EEED1F3952}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C27AA99E-EEC0-41FE-B949-F4EEED1F3952}.Debug|Any CPU.Build.0 = Debug|Any CPU {C27AA99E-EEC0-41FE-B949-F4EEED1F3952}.Release|Any CPU.ActiveCfg = Release|Any CPU {C27AA99E-EEC0-41FE-B949-F4EEED1F3952}.Release|Any CPU.Build.0 = Release|Any CPU + {478E3F10-2B5C-4D40-BE53-327E5B2AD0AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {478E3F10-2B5C-4D40-BE53-327E5B2AD0AC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {478E3F10-2B5C-4D40-BE53-327E5B2AD0AC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {478E3F10-2B5C-4D40-BE53-327E5B2AD0AC}.Release|Any CPU.Build.0 = Release|Any CPU + {120D37EF-20DC-492B-AB2B-8A887627A211}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {120D37EF-20DC-492B-AB2B-8A887627A211}.Debug|Any CPU.Build.0 = Debug|Any CPU + {120D37EF-20DC-492B-AB2B-8A887627A211}.Release|Any CPU.ActiveCfg = Release|Any CPU + {120D37EF-20DC-492B-AB2B-8A887627A211}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE EndGlobalSection EndGlobal diff --git a/ef-migration/readme.md b/ef-migration/readme.md index 59d301c..42ef523 100644 --- a/ef-migration/readme.md +++ b/ef-migration/readme.md @@ -6,65 +6,17 @@ Your solution should follow this structure for optimal organization: ``` YourSolution/ ├── src/ -│ ├── YourProject/ +│ ├── OnePlan/ <- Your project │ │ ├── Controllers/ -│ │ ├── Models/ <- Scaffolded models will go here -│ │ └── Data/ <- DbContext will go here +│ │ ├── Models/ <- Scaffolded models will go here +│ │ └── Data/ <- DbContext will go here ├── tests/ -│ └── YourProject.Tests/ +│ └── OnePlan.Tests/ ├── tools/ -│ └── scaffold.bat <- Place scaffolding script here +│ └── scaffold.bat <- Scaffolding script here └── YourSolution.sln ``` -Alternative structure with scripts directory: -``` -YourSolution/ -├── src/ -│ ├── YourProject/ -│ │ ├── Controllers/ -│ │ ├── Models/ -│ │ └── Data/ -├── tests/ -│ └── YourProject.Tests/ -├── scripts/ -│ ├── database/ -│ │ └── scaffold.bat <- Or place it here -│ └── other-scripts/ -└── YourSolution.sln -``` - -To run the scaffold script: - -Method 1 (From project directory): -1. Open command prompt -2. Navigate to project directory: `cd src/YourProject` -3. Run: `../../tools/scaffold.bat` - -Method 2 (From any directory): -Update your scaffold.bat to include the project path: -```bat -@echo off -cd ../src/YourProject -dotnet ef dbcontext scaffold ^ -"Your_Connection_String" ^ -Microsoft.EntityFrameworkCore.SqlServer ^ ---project YourProject.csproj ^ -[rest of your options] -pause -``` - -Note: Make sure your project has all required EF Core packages installed: -```xml - - - - - -``` - -This guide explains how to set up Entity Framework Core using a database-first approach for specific tables in the OnePlan database. - ## Prerequisites Before starting, ensure you have: @@ -76,92 +28,6 @@ dotnet tool install --global dotnet-ef ``` 3. Required NuGet packages in your project: -```bash -dotnet add package Microsoft.EntityFrameworkCore.Design -dotnet add package Microsoft.EntityFrameworkCore.SqlServer -dotnet add package Microsoft.EntityFrameworkCore.Tools -``` - -## Scaffolding Process - -### Step 1: Create a Scaffold Script - -Create a file named `scaffold.bat` in your `tools` directory with the following content: - -```bat -@echo off -cd ../src/YourProject -dotnet ef dbcontext scaffold ^ -"Server=your_server;Database=your_database;User=your_user;Password=your_password;TrustServerCertificate=True;Encrypt=True;" ^ -Microsoft.EntityFrameworkCore.SqlServer ^ ---project YourProject.csproj ^ ---context-dir Data ^ ---output-dir Models ^ ---context OnePlanDbContext ^ ---force ^ ---data-annotations ^ ---no-onconfiguring ^ ---no-connection-string ^ --t fp.AddProviderEncountersDataForCharges ^ --t fp.AddProviderSummary ^ --t fp.AdjustmentChunkingConfiguration ^ --t fp.APEDepartmentWorkflowStatus ^ --t fp.APEWorkflow ^ --t fp.BenefitsSpreads ^ --t fp.BudgetConfig ^ --t fp.BudgetConfigDefaultSetting ^ --t fp.BudgetConfigSetting ^ --t fp.BudgetRefreshRequest ^ --t fp.BudgetRefreshRequestHistory ^ --t fp.ChargeVolumeAddProviderAdjustment ^ --t fp.ChargeVolumeSpreads ^ --t fp.DataRefreshTargetThreshold ^ --t fp.DepartmentChargeVolumeAdjustment ^ --t fp.DepartmentConfig ^ --t fp.DimCategory ^ --t fw.DimDepartment ^ --t dss.DimPhysician ^ --t fp.EngineLog ^ --t fp.EntityGroupConfig ^ --t fp.FixChangeHistoryRequest ^ --t fp.GeneralLedger ^ --t fp.GeneralLedgerInitialPlanConfigDetail ^ --t fp.GeneralLedgerSpreads ^ --t fp.InitialPlanRule ^ --t dbo.LOCK ^ --t dbo.log ^ --t dbo.OnePlanPerformanceTestHistory ^ --t fp.OnePlanPerformanceTestValidationResult ^ --t fp.PerformanceTestingSetting ^ --t fp.ProviderCompensationSpreads ^ --t fp.SamplingLog ^ --t fp.ScheduledRefreshRequest ^ --t fp.ServiceLineEncounterSpreads ^ --t fp.SettingCategory ^ --t fp.SpreadHistory ^ --t fp.StaffingInitialPlanConfigDetail ^ --t fp.StaffingSpreads ^ --t fp.StatisticsSpreads ^ --t fp.SystemSetting ^ --t dbo.TEScheduledTask ^ --t dbo.UserProfile ^ --t fp.viewBenefitsAdjustment ^ --t fp.viewDepartmentChargeVolumeAdjustment ^ --t fp.viewGeneralLedgerAdjustment ^ --t fp.viewReimbursementAdjustment ^ --t fp.viewReimbursementGeneralLedgerAdjustment ^ --t fp.viewServiceLineEncounterAdjustment ^ --t fp.viewStaffingAdjustment ^ --t fp.viewStatisticsAdjustment -pause -``` - -To run the scaffold script: -1. Open command prompt -2. Navigate to solution root directory -3. Run: `tools/scaffold.bat` - -Note: Make sure your project has all required EF Core packages installed: ```xml @@ -170,9 +36,94 @@ Note: Make sure your project has all required EF Core packages installed: ``` +## Scaffolding Process + +### Step 1: Create Scaffold Script + +Create a file named `scaffold.bat` in your `tools` directory with the following content: + +```bat +@echo off +cd ..\src\OnePlan +dotnet ef dbcontext scaffold^ + "Server=your_server;Database=your_database;User=your_user;Password=your_password;TrustServerCertificate=True;Encrypt=True;"^ + Microsoft.EntityFrameworkCore.SqlServer^ + --project OnePlan.csproj^ + --context-dir Data^ + --output-dir Models^ + --context OnePlanDbContext^ + --force^ + --data-annotations^ + --no-onconfiguring^ + -t fp.AddProviderEncountersDataForCharges^ + -t fp.AddProviderSummary^ + -t fp.AdjustmentChunkingConfiguration^ + -t fp.APEDepartmentWorkflowStatus^ + -t fp.APEWorkflow^ + -t fp.BenefitsSpreads^ + -t fp.BudgetConfig^ + -t fp.BudgetConfigDefaultSetting^ + -t fp.BudgetConfigSetting^ + -t fp.BudgetRefreshRequest^ + -t fp.BudgetRefreshRequestHistory^ + -t fp.ChargeVolumeAddProviderAdjustment^ + -t fp.ChargeVolumeSpreads^ + -t fp.DataRefreshTargetThreshold^ + -t fp.DepartmentChargeVolumeAdjustment^ + -t fp.DepartmentConfig^ + -t fp.DimCategory^ + -t fw.DimDepartment^ + -t dss.DimPhysician^ + -t fp.EngineLog^ + -t fp.EntityGroupConfig^ + -t fp.FixChangeHistoryRequest^ + -t fp.GeneralLedger^ + -t fp.GeneralLedgerInitialPlanConfigDetail^ + -t fp.GeneralLedgerSpreads^ + -t fp.InitialPlanRule^ + -t dbo.LOCK^ + -t dbo.log^ + -t dbo.OnePlanPerformanceTestHistory^ + -t fp.OnePlanPerformanceTestValidationResult^ + -t fp.PerformanceTestingSetting^ + -t fp.ProviderCompensationSpreads^ + -t fp.SamplingLog^ + -t fp.ScheduledRefreshRequest^ + -t fp.ServiceLineEncounterSpreads^ + -t fp.SettingCategory^ + -t fp.SpreadHistory^ + -t fp.StaffingInitialPlanConfigDetail^ + -t fp.StaffingSpreads^ + -t fp.StatisticsSpreads^ + -t fp.SystemSetting^ + -t dbo.TEScheduledTask^ + -t dbo.UserProfile^ + -t fp.viewBenefitsAdjustment^ + -t fp.viewDepartmentChargeVolumeAdjustment^ + -t fp.viewGeneralLedgerAdjustment^ + -t fp.viewReimbursementAdjustment^ + -t fp.viewReimbursementGeneralLedgerAdjustment^ + -t fp.viewServiceLineEncounterAdjustment^ + -t fp.viewStaffingAdjustment^ + -t fp.viewStatisticsAdjustment +pause +``` + +Important Notes for Multi-line Batch Files: +1. The `^` character must be the last character on each line (no spaces after it) +2. Each new line should start with a space before the parameter +3. The connection string must be in quotes +4. The last command line doesn't need a `^` +5. Use `..\` instead of `../` for Windows paths + +To run the scaffold script: +1. Open command prompt +2. Navigate to the tools directory: `cd tools` +3. Run: `scaffold.bat` + ### Step 2: Configure Connection String -After scaffolding, configure your connection string in `appsettings.json`: +Add your connection string to `appsettings.json`: ```json { @@ -182,49 +133,32 @@ After scaffolding, configure your connection string in `appsettings.json`: } ``` -### Step 3: Configure DbContext +### Step 3: Set Up Dependency Injection -In your `Program.cs` or `Startup.cs`: +1. Modify the generated DbContext to use constructor injection: ```csharp +public class OnePlanDbContext : DbContext +{ + public OnePlanDbContext(DbContextOptions options) + : base(options) + { + } + + // Your DbSet properties will be here +} +``` + +2. Register the DbContext in `Program.cs`: + +```csharp +var builder = WebApplication.CreateBuilder(args); + +// Add DbContext builder.Services.AddDbContext(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); ``` -## Command Line Parameters Explained - -- `--context-dir Data`: Places the DbContext in a Data folder -- `--output-dir Models`: Places entity classes in a Models folder -- `--force`: Overwrites existing files -- `--data-annotations`: Uses attributes instead of fluent API -- `--no-onconfiguring`: Skips generating the OnConfiguring method -- `--no-connection-string`: Prevents connection string from being scaffolded into DbContext - -## Schema Organization - -The tables are organized across multiple schemas: -- `fp`: Financial Planning schema (majority of tables) -- `dbo`: Database Owner schema -- `dss`: Decision Support System schema -- `fw`: Framework schema - -## Best Practices - -1. Always scaffold all related tables together to maintain proper relationships -2. Keep connection strings in configuration, not in code -3. Use dependency injection for DbContext -4. Consider using separate configuration classes for complex entity configurations - -## Troubleshooting - -If you encounter SSL/TLS warnings, ensure your connection string includes: -- `TrustServerCertificate=True` -- `Encrypt=True` - -For Docker connections, use: -- `Server=localhost,1433` (adjust port as needed) -- Ensure the container is running and accessible - ## DbContext Organization You have two main approaches for organizing your DbContext: @@ -275,9 +209,10 @@ For this project, the single DbContext approach is recommended due to: - Coherent domain model around financial planning ## Notes - - Views are included in the scaffold and will be read-only - The scaffold includes all specified tables across multiple schemas - Relationships between tables will be automatically mapped - Generated models will be placed in the Models directory -- DbContext will be placed in the Data directory \ No newline at end of file +- DbContext will be placed in the Data directory +- Use data annotations for simple configurations +- Use fluent API in OnModelCreating for complex configurations \ No newline at end of file diff --git a/ef-migration/src/Strata.Code.Business/Services/BudgetConfigDefaultSettingService.cs b/ef-migration/src/Strata.Code.Business/Services/BudgetConfigDefaultSettingService.cs new file mode 100644 index 0000000..04078b3 --- /dev/null +++ b/ef-migration/src/Strata.Code.Business/Services/BudgetConfigDefaultSettingService.cs @@ -0,0 +1,71 @@ +using Strata.Code.Business.Services.Interfaces; +using Strata.Code.DataAccess.Models; +using Strata.Code.DataAccess.Repositories.Interfaces; + +namespace Strata.Code.Business.Services +{ + public class BudgetConfigDefaultSettingService : IBudgetConfigDefaultSettingService + { + private readonly IBudgetConfigDefaultSettingRepository _repository; + + public BudgetConfigDefaultSettingService(IBudgetConfigDefaultSettingRepository repository) + { + _repository = repository; + } + + public async Task> GetAllAsync() + { + var settings = await _repository.GetAllAsync(); + return settings.Select(s => MapToDto(s)); + } + + public async Task GetByIdAsync(int id) + { + var setting = await _repository.GetByIdAsync(id); + return setting != null ? MapToDto(setting) : null; + } + + public async Task CreateAsync(BudgetConfigDefaultSettingDto settingDto) + { + var setting = MapToEntity(settingDto); + var result = await _repository.CreateAsync(setting); + return MapToDto(result); + } + + public async Task UpdateAsync(BudgetConfigDefaultSettingDto settingDto) + { + var setting = MapToEntity(settingDto); + var result = await _repository.UpdateAsync(setting); + return result != null ? MapToDto(result) : null; + } + + public async Task DeleteAsync(int id) + { + return await _repository.DeleteAsync(id); + } + + private BudgetConfigDefaultSettingDto MapToDto(BudgetConfigDefaultSetting entity) + { + return new BudgetConfigDefaultSettingDto + { + SettingId = entity.SettingId, + Name = entity.Name, + DefaultValue = entity.DefaultValue, + Description = entity.Description, + DateCreated = entity.DateCreated + }; + } + + private BudgetConfigDefaultSetting MapToEntity(BudgetConfigDefaultSettingDto dto) + { + return new BudgetConfigDefaultSetting + { + SettingId = dto.SettingId, + Name = dto.Name, + DefaultValue = dto.DefaultValue, + Description = dto.Description, + DateCreated = dto.DateCreated + }; + } + } +} diff --git a/ef-migration/src/Strata.Code.Business/Services/Interfaces/IBudgetConfigDefaultSettingService.cs b/ef-migration/src/Strata.Code.Business/Services/Interfaces/IBudgetConfigDefaultSettingService.cs new file mode 100644 index 0000000..d4fc601 --- /dev/null +++ b/ef-migration/src/Strata.Code.Business/Services/Interfaces/IBudgetConfigDefaultSettingService.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Strata.Code.Business.Services.Interfaces +{ + public class BudgetConfigDefaultSettingDto + { + public int SettingId { get; set; } + + public string Name { get; set; } = null!; + + public string Description { get; set; } = null!; + + public bool DefaultValue { get; set; } + + public DateOnly DateCreated { get; set; } + } + + public interface IBudgetConfigDefaultSettingService + { + Task> GetAllAsync(); + Task GetByIdAsync(int id); + Task CreateAsync(BudgetConfigDefaultSettingDto setting); + Task UpdateAsync(BudgetConfigDefaultSettingDto setting); + Task DeleteAsync(int id); + } +} diff --git a/ef-migration/src/Strata.Code.Business/Strata.Code.Business.csproj b/ef-migration/src/Strata.Code.Business/Strata.Code.Business.csproj new file mode 100644 index 0000000..3c3c410 --- /dev/null +++ b/ef-migration/src/Strata.Code.Business/Strata.Code.Business.csproj @@ -0,0 +1,13 @@ + + + + net8.0 + enable + enable + + + + + + + diff --git a/ef-migration/src/Strata.Code.DataAccess/Class1.cs b/ef-migration/src/Strata.Code.DataAccess/Class1.cs deleted file mode 100644 index 8687269..0000000 --- a/ef-migration/src/Strata.Code.DataAccess/Class1.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace Strata.Code.DataAccess; - -public class Class1 -{ - -} diff --git a/ef-migration/src/Strata.Code.DataAccess/Repositories/BudgetConfigDefaultSettingRepository.cs b/ef-migration/src/Strata.Code.DataAccess/Repositories/BudgetConfigDefaultSettingRepository.cs new file mode 100644 index 0000000..4301fe4 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Repositories/BudgetConfigDefaultSettingRepository.cs @@ -0,0 +1,66 @@ +using Microsoft.EntityFrameworkCore; +using Strata.Code.DataAccess.Data; +using Strata.Code.DataAccess.Models; +using Strata.Code.DataAccess.Repositories.Interfaces; + +namespace Strata.Code.DataAccess.Repositories +{ + public class BudgetConfigDefaultSettingRepository : IBudgetConfigDefaultSettingRepository + { + private readonly OnePlanDbContext _context; + + public BudgetConfigDefaultSettingRepository(OnePlanDbContext context) + { + _context = context ?? throw new ArgumentNullException(nameof(context)); + } + + public async Task> GetAllAsync() + { + return await _context.Set() + .ToListAsync(); + } + + public async Task GetByIdAsync(int id) + { + return await _context.Set() + .FirstOrDefaultAsync(x => x.SettingId == id); + } + + public async Task CreateAsync(BudgetConfigDefaultSetting setting) + { + setting.DateCreated = DateOnly.FromDateTime(DateTime.UtcNow); + await _context.Set().AddAsync(setting); + await _context.SaveChangesAsync(); + + return setting; + } + + public async Task UpdateAsync(BudgetConfigDefaultSetting setting) + { + var existingSetting = await GetByIdAsync(setting.SettingId); + if (existingSetting == null) + return null; + + existingSetting.Name = setting.Name; + existingSetting.DefaultValue = setting.DefaultValue; + existingSetting.Description = setting.Description; + + _context.Set().Update(existingSetting); + await _context.SaveChangesAsync(); + + return existingSetting; + } + + public async Task DeleteAsync(int id) + { + var setting = await GetByIdAsync(id); + if (setting == null) + return false; + + _context.Remove(setting); + await _context.SaveChangesAsync(); + + return true; + } + } +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Repositories/Interfaces/IBudgetConfigDefaultSettingRepository.cs b/ef-migration/src/Strata.Code.DataAccess/Repositories/Interfaces/IBudgetConfigDefaultSettingRepository.cs new file mode 100644 index 0000000..d5b4b00 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/Repositories/Interfaces/IBudgetConfigDefaultSettingRepository.cs @@ -0,0 +1,13 @@ +using Strata.Code.DataAccess.Models; + +namespace Strata.Code.DataAccess.Repositories.Interfaces +{ + public interface IBudgetConfigDefaultSettingRepository + { + Task> GetAllAsync(); + Task GetByIdAsync(int id); + Task CreateAsync(BudgetConfigDefaultSetting setting); + Task UpdateAsync(BudgetConfigDefaultSetting setting); + Task DeleteAsync(int id); + } +} diff --git a/ef-migration/src/Strata.Code.DataAccess/Strata.Code.DataAccess.csproj b/ef-migration/src/Strata.Code.DataAccess/Strata.Code.DataAccess.csproj index b3834c8..d3849e5 100644 --- a/ef-migration/src/Strata.Code.DataAccess/Strata.Code.DataAccess.csproj +++ b/ef-migration/src/Strata.Code.DataAccess/Strata.Code.DataAccess.csproj @@ -1,18 +1,19 @@  - net9.0 + net8.0 enable enable - + runtime; build; native; contentfiles; analyzers; buildtransitive all - - + + + runtime; build; native; contentfiles; analyzers; buildtransitive all diff --git a/ef-migration/src/Strata.Code.Web/Controllers/BudgetConfigDefaultSettingController .cs b/ef-migration/src/Strata.Code.Web/Controllers/BudgetConfigDefaultSettingController .cs new file mode 100644 index 0000000..4b1e891 --- /dev/null +++ b/ef-migration/src/Strata.Code.Web/Controllers/BudgetConfigDefaultSettingController .cs @@ -0,0 +1,77 @@ +using Microsoft.AspNetCore.Mvc; +using Strata.Code.Business.Services.Interfaces; + +namespace Strata.Code.Web.Controllers +{ + [ApiController] + [Route("api/[controller]")] + public class BudgetConfigDefaultSettingController : ControllerBase + { + private readonly IBudgetConfigDefaultSettingService _service; + + public BudgetConfigDefaultSettingController(IBudgetConfigDefaultSettingService service) + { + _service = service; + } + + [HttpGet] + [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] + public async Task GetAll() + { + var settings = await _service.GetAllAsync(); + return Ok(settings); + } + + [HttpGet("{id}")] + [ProducesResponseType(typeof(BudgetConfigDefaultSettingDto), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task GetById(int id) + { + var setting = await _service.GetByIdAsync(id); + if (setting == null) + return NotFound(); + + return Ok(setting); + } + + [HttpPost] + [ProducesResponseType(typeof(BudgetConfigDefaultSettingDto), StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task Create([FromBody] BudgetConfigDefaultSettingDto setting) + { + if (!ModelState.IsValid) + return BadRequest(ModelState); + + var createdSetting = await _service.CreateAsync(setting); + return CreatedAtAction(nameof(GetById), new { id = createdSetting.SettingId }, createdSetting); + } + + [HttpPut("{id}")] + [ProducesResponseType(typeof(BudgetConfigDefaultSettingDto), StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task Update(int id, [FromBody] BudgetConfigDefaultSettingDto setting) + { + if (id != setting.SettingId) + return BadRequest(); + + var updatedSetting = await _service.UpdateAsync(setting); + if (updatedSetting == null) + return NotFound(); + + return Ok(updatedSetting); + } + + [HttpDelete("{id}")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task Delete(int id) + { + var result = await _service.DeleteAsync(id); + if (!result) + return NotFound(); + + return NoContent(); + } + } +} diff --git a/ef-migration/src/Strata.Code.Web/Program.cs b/ef-migration/src/Strata.Code.Web/Program.cs new file mode 100644 index 0000000..f51801c --- /dev/null +++ b/ef-migration/src/Strata.Code.Web/Program.cs @@ -0,0 +1,51 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.OpenApi.Models; +using Strata.Code.DataAccess.Repositories.Interfaces; +using Strata.Code.DataAccess.Repositories; +using System.Reflection; +using Strata.Code.Business.Services; +using Strata.Code.Business.Services.Interfaces; +using Strata.Code.DataAccess.Data; + +var builder = WebApplication.CreateBuilder(args); + +builder.Services.AddControllers(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(c => +{ + c.SwaggerDoc("v1", new OpenApiInfo + { + Title = "Budget Config API", + Version = "v1", + Description = "API for managing budget configuration default settings" + }); + + // Include XML comments in Swagger documentation + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + c.IncludeXmlComments(xmlPath); +}); + +// Add your DbContext configuration here +builder.Services.AddDbContext(options => + options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))); + +builder.Services.AddScoped(); +builder.Services.AddScoped(); + +var app = builder.Build(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(c => + { + c.SwaggerEndpoint("/swagger/v1/swagger.json", "Budget Config API V1"); + }); +} + +app.UseHttpsRedirection(); +app.UseAuthorization(); +app.MapControllers(); + +app.Run(); diff --git a/ef-migration/src/Strata.Code.Web/Properties/launchSettings.json b/ef-migration/src/Strata.Code.Web/Properties/launchSettings.json new file mode 100644 index 0000000..d53f34a --- /dev/null +++ b/ef-migration/src/Strata.Code.Web/Properties/launchSettings.json @@ -0,0 +1,41 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:27409", + "sslPort": 44329 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5247", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7241;http://localhost:5247", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/ef-migration/src/Strata.Code.Web/Strata.Code.Web.csproj b/ef-migration/src/Strata.Code.Web/Strata.Code.Web.csproj new file mode 100644 index 0000000..7b40504 --- /dev/null +++ b/ef-migration/src/Strata.Code.Web/Strata.Code.Web.csproj @@ -0,0 +1,18 @@ + + + + net8.0 + enable + enable + True + + + + + + + + + + + diff --git a/ef-migration/src/Strata.Code.Web/appsettings.Development.json b/ef-migration/src/Strata.Code.Web/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/ef-migration/src/Strata.Code.Web/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/ef-migration/src/Strata.Code.Web/appsettings.json b/ef-migration/src/Strata.Code.Web/appsettings.json new file mode 100644 index 0000000..f37fe5f --- /dev/null +++ b/ef-migration/src/Strata.Code.Web/appsettings.json @@ -0,0 +1,12 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "ConnectionStrings": { + "DefaultConnection": "Server=54.71.217.228,1433;Database=st-database;User=sa;Password=YourStrong@Passw0rd;TrustServerCertificate=True;" + } +} -- 2.45.2 From e880749ca87dab611038503a679a6ac010475c9f Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Wed, 5 Feb 2025 21:54:18 -0500 Subject: [PATCH 28/31] Adjust settings for connecting to multiple databases --- ef-migration/src/Strata.Code.Web/Program.cs | 2 +- .../Properties/launchSettings.json | 84 +++++++++++-------- .../appsettings.Development.json | 13 +-- .../Strata.Code.Web/appsettings.Staging.json | 11 +++ .../src/Strata.Code.Web/appsettings.json | 5 +- 5 files changed, 68 insertions(+), 47 deletions(-) create mode 100644 ef-migration/src/Strata.Code.Web/appsettings.Staging.json diff --git a/ef-migration/src/Strata.Code.Web/Program.cs b/ef-migration/src/Strata.Code.Web/Program.cs index f51801c..e64eb79 100644 --- a/ef-migration/src/Strata.Code.Web/Program.cs +++ b/ef-migration/src/Strata.Code.Web/Program.cs @@ -35,7 +35,7 @@ builder.Services.AddScoped diff --git a/ef-migration/src/Strata.Code.Web/Properties/launchSettings.json b/ef-migration/src/Strata.Code.Web/Properties/launchSettings.json index d53f34a..3539547 100644 --- a/ef-migration/src/Strata.Code.Web/Properties/launchSettings.json +++ b/ef-migration/src/Strata.Code.Web/Properties/launchSettings.json @@ -1,41 +1,51 @@ { - "$schema": "http://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:27409", - "sslPort": 44329 - } - }, - "profiles": { - "http": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": true, - "launchUrl": "swagger", - "applicationUrl": "http://localhost:5247", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:27409", + "sslPort": 44329 + } }, - "https": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": true, - "launchUrl": "swagger", - "applicationUrl": "https://localhost:7241;http://localhost:5247", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "launchUrl": "swagger", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } + "profiles": { + "http_Development": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5247", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "http_Staging": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5247", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Staging" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "https://localhost:7241;http://localhost:5247", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } } - } } diff --git a/ef-migration/src/Strata.Code.Web/appsettings.Development.json b/ef-migration/src/Strata.Code.Web/appsettings.Development.json index 0c208ae..445bd44 100644 --- a/ef-migration/src/Strata.Code.Web/appsettings.Development.json +++ b/ef-migration/src/Strata.Code.Web/appsettings.Development.json @@ -1,8 +1,11 @@ { - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "ConnectionStrings": { + "DefaultConnection": "Server=54.71.217.228,1433;Database=st_dev_database;User=sa;Password=YourStrong@Passw0rd;TrustServerCertificate=True;" } - } } diff --git a/ef-migration/src/Strata.Code.Web/appsettings.Staging.json b/ef-migration/src/Strata.Code.Web/appsettings.Staging.json new file mode 100644 index 0000000..4b2d0ce --- /dev/null +++ b/ef-migration/src/Strata.Code.Web/appsettings.Staging.json @@ -0,0 +1,11 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "ConnectionStrings": { + "DefaultConnection": "Server=54.71.217.228,1433;Database=st-database;User=sa;Password=YourStrong@Passw0rd;TrustServerCertificate=True;" + } +} diff --git a/ef-migration/src/Strata.Code.Web/appsettings.json b/ef-migration/src/Strata.Code.Web/appsettings.json index f37fe5f..23160a4 100644 --- a/ef-migration/src/Strata.Code.Web/appsettings.json +++ b/ef-migration/src/Strata.Code.Web/appsettings.json @@ -5,8 +5,5 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*", - "ConnectionStrings": { - "DefaultConnection": "Server=54.71.217.228,1433;Database=st-database;User=sa;Password=YourStrong@Passw0rd;TrustServerCertificate=True;" - } + "AllowedHosts": "*" } -- 2.45.2 From 2015284949f53dd8d9a1d89b0751b1cbcc55fc28 Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Thu, 6 Feb 2025 14:00:32 -0500 Subject: [PATCH 29/31] Initial migration from Core 20 Core 30 --- .../BudgetConfigDefaultSettingService.cs | 22 +- .../IBudgetConfigDefaultSettingService.cs | 12 + .../src/Strata.Code.DataAccess/ReadMe.MD | 380 ++++++++++++++++++ .../BudgetConfigDefaultSettingRepository.cs | 56 ++- .../IBudgetConfigDefaultSettingRepository.cs | 8 +- .../BudgetConfigDefaultSettingController .cs | 41 +- 6 files changed, 510 insertions(+), 9 deletions(-) create mode 100644 ef-migration/src/Strata.Code.DataAccess/ReadMe.MD diff --git a/ef-migration/src/Strata.Code.Business/Services/BudgetConfigDefaultSettingService.cs b/ef-migration/src/Strata.Code.Business/Services/BudgetConfigDefaultSettingService.cs index 04078b3..40804d0 100644 --- a/ef-migration/src/Strata.Code.Business/Services/BudgetConfigDefaultSettingService.cs +++ b/ef-migration/src/Strata.Code.Business/Services/BudgetConfigDefaultSettingService.cs @@ -1,4 +1,5 @@ -using Strata.Code.Business.Services.Interfaces; +using System.Linq.Expressions; +using Strata.Code.Business.Services.Interfaces; using Strata.Code.DataAccess.Models; using Strata.Code.DataAccess.Repositories.Interfaces; @@ -44,6 +45,25 @@ namespace Strata.Code.Business.Services return await _repository.DeleteAsync(id); } + public async Task> GetByNameAsync(string name) + { + var settings = await _repository.GetByNameAsync(name); + return settings.Select(MapToDto); + } + + public async Task> GetByIdsAsync(IEnumerable ids) + { + var settings = await _repository.GetByIdsAsync(ids); + return settings.Select(MapToDto); + } + + public async Task> FindByAsync( + Expression> predicate) + { + var settings = await _repository.FindByAsync(predicate); + return settings.Select(MapToDto); + } + private BudgetConfigDefaultSettingDto MapToDto(BudgetConfigDefaultSetting entity) { return new BudgetConfigDefaultSettingDto diff --git a/ef-migration/src/Strata.Code.Business/Services/Interfaces/IBudgetConfigDefaultSettingService.cs b/ef-migration/src/Strata.Code.Business/Services/Interfaces/IBudgetConfigDefaultSettingService.cs index d4fc601..330ad06 100644 --- a/ef-migration/src/Strata.Code.Business/Services/Interfaces/IBudgetConfigDefaultSettingService.cs +++ b/ef-migration/src/Strata.Code.Business/Services/Interfaces/IBudgetConfigDefaultSettingService.cs @@ -1,8 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; +using Strata.Code.DataAccess.Models; namespace Strata.Code.Business.Services.Interfaces { @@ -19,12 +21,22 @@ namespace Strata.Code.Business.Services.Interfaces public DateOnly DateCreated { get; set; } } + public class LinkedSettingsRequest + { + public string LinkTable { get; set; } = null!; + public string LinkColumn { get; set; } = null!; + public IEnumerable LinkIds { get; set; } = null!; + } + public interface IBudgetConfigDefaultSettingService { Task> GetAllAsync(); Task GetByIdAsync(int id); + Task> GetByNameAsync(string name); + Task> GetByIdsAsync(IEnumerable ids); Task CreateAsync(BudgetConfigDefaultSettingDto setting); Task UpdateAsync(BudgetConfigDefaultSettingDto setting); Task DeleteAsync(int id); + Task> FindByAsync(Expression> predicate); } } diff --git a/ef-migration/src/Strata.Code.DataAccess/ReadMe.MD b/ef-migration/src/Strata.Code.DataAccess/ReadMe.MD new file mode 100644 index 0000000..0ab8c26 --- /dev/null +++ b/ef-migration/src/Strata.Code.DataAccess/ReadMe.MD @@ -0,0 +1,380 @@ +# Migration Guide: Core20 ORM to EF Core 8.0 +## Overview +This document outlines the process of migrating from the Core20 ORM system to Entity Framework Core 8.0, using the BudgetConfigDefaultSetting implementation as a reference example. + +## Database Connection Management Comparison + +### Core20 Approach +```csharp +// Core20 uses static SQL context and connection strings +static string SQL_QUERY_FROM = @"[fp].[BudgetConfigDefaultSetting] OBJ"; +internal const string UPDATE_TABLE_NAME = "fp.BudgetConfigDefaultSetting"; +``` +- Uses static SQL contexts +- Manages connections through `SqlContext.Current` +- Relies on connection string keys +- Manual SQL query construction +- Schema is defined in SQL queries + +### EF Core Approach +```csharp +public class OnePlanDbContext : DbContext +{ + public DbSet BudgetConfigDefaultSettings { get; set; } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity(entity => + { + entity.ToTable("BudgetConfigDefaultSetting", "fp"); + // ... other configurations + }); + } +} +``` +- Connection management through DbContext +- Dependency injection for context lifecycle +- Fluent API for schema definition +- Type-safe queries +- Connection string in configuration + +## ORM Feature Comparison + +| Feature | Core20 | EF Core | Migration Effort | +|---------|--------|---------|------------------| +| Schema Definition | SQL Strings | Fluent API/Attributes | Medium | +| Query Building | String Concatenation | LINQ | High | +| Change Tracking | Manual (IsDirty) | Automatic | Low | +| Transactions | Manual | Built-in | Medium | +| Relationships | Manual Loading | Navigation Properties | High | +| Validation | Custom Implementation | Data Annotations/Custom | Medium | +| Bulk Operations | Custom SQL | Extensions Available | Medium | +| Security | Manual SQL Filters | Global Query Filters | Medium | + +## Migration Steps + +1. **Entity Class Migration** + ```csharp + // From Core20: + [Serializable] + public partial class BudgetConfigDefaultSetting : ReadWriteBase + + // To EF Core: + public class BudgetConfigDefaultSetting + { + public int SettingId { get; set; } + public string Name { get; set; } + public string Description { get; set; } + public bool DefaultValue { get; set; } + public DateOnly DateCreated { get; set; } + } + ``` + +2. **Configuration Migration** + ```csharp + public class BudgetConfigDefaultSettingConfiguration : IEntityTypeConfiguration + { + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("BudgetConfigDefaultSetting", "fp"); + builder.HasKey(e => e.SettingId); + builder.Property(e => e.Name).IsRequired(); + // ... other configurations + } + } + ``` + +3. **Repository Pattern Implementation** + - Replace static loading methods with repository methods + - Convert SQL queries to LINQ expressions + - Implement unit of work pattern if needed + +## Code Examples Comparison + +### Loading Records +```csharp +// Core20 +var records = BudgetConfigDefaultSetting.LoadByColumn("Name", "SomeName"); + +// EF Core +var records = await _repository.GetByNameAsync("SomeName"); +``` + +### Saving Changes +```csharp +// Core20 +setting.MarkDirty(); +setting.Save(); + +// EF Core +await _repository.UpdateAsync(setting); +``` + +### Relationships +```csharp +// Core20 +var linkedSettings = BudgetConfigDefaultSetting.LoadByLinks("LinkTable", "ColumnName", ids); + +// EF Core +var linkedSettings = await _repository.GetByLinksAsync( + _context.Links.Where(l => ids.Contains(l.Id)), + link => link.SettingId +); +``` + +## Migration Effort Assessment + +### High Effort Areas +1. **Query Conversion** + - Converting raw SQL to LINQ expressions + - Implementing type-safe joins + - Replacing string-based queries + +2. **Relationship Management** + - Defining navigation properties + - Converting manual loading to eager/lazy loading + - Implementing proper relationship configurations + +3. **Transaction Management** + - Replacing manual transaction handling + - Implementing unit of work pattern + - Managing context lifecycle + +### Medium Effort Areas +1. **Schema Configuration** + - Converting SQL schema to Fluent API + - Setting up entity configurations + - Defining indexes and constraints + +2. **Validation Logic** + - Implementing validation attributes + - Converting custom validation rules + - Setting up FluentValidation if needed + +### Low Effort Areas +1. **Basic CRUD Operations** + - Converting simple load/save operations + - Implementing basic repository methods + - Setting up entity properties + +## Best Practices for Migration + +1. **Incremental Migration** + - Migrate one entity at a time + - Keep both systems running during migration + - Implement facade pattern for transition + +2. **Testing Strategy** + - Create integration tests first + - Verify queries produce same results + - Test performance impact + +3. **Performance Considerations** + - Use compiled queries for frequent operations + - Implement proper indexing + - Monitor query performance + +4. **Security Migration** + - Replace manual SQL filters with Global Query Filters + - Implement proper user context + - Audit sensitive operations + +## Tools and Utilities + +1. **Essential Tools** + - EF Core Power Tools + - SQL Server Profiler + - dotnet ef CLI tools + +2. **Recommended Extensions** + - EF Core Bulk Extensions + - AutoMapper + - FluentValidation + +## Timeline Estimation + +| Phase | Duration | Description | +|-------|----------|-------------| +| Planning | 1-2 weeks | Analysis, strategy, tooling setup | +| Basic Migration | 2-4 weeks | Entity and schema migration | +| Query Migration | 4-6 weeks | Converting complex queries | +| Testing | 2-3 weeks | Integration and performance testing | +| Deployment | 1-2 weeks | Staging and production deployment | + +## Consumer Impact Analysis + +### Changes in Consumer Code + +#### Dependency Injection (DI) +```csharp +// Core20 - Static access +var setting = BudgetConfigDefaultSetting.LoadBySettingID(123); + +// EF Core - DI approach +public class ConsumerService +{ + private readonly IBudgetConfigDefaultSettingRepository _repository; + + public ConsumerService(IBudgetConfigDefaultSettingRepository repository) + { + _repository = repository; + } + + public async Task GetSetting(int id) + { + return await _repository.GetByIdAsync(id); + } +} +``` + +#### Async/Await Pattern +```csharp +// Core20 - Synchronous +var settings = BudgetConfigDefaultSetting.LoadAll(); +settings.First().Name = "New Name"; +settings.First().Save(); + +// EF Core - Async +var settings = await _repository.GetAllAsync(); +var setting = settings.First(); +setting.Name = "New Name"; +await _repository.UpdateAsync(setting); +``` + +### Comprehensive Usage Examples + +#### 1. Basic CRUD Operations +```csharp +// Create +var newSetting = new BudgetConfigDefaultSetting +{ + Name = "New Feature Flag", + Description = "Controls new feature availability", + DefaultValue = true +}; +await _repository.CreateAsync(newSetting); + +// Read +var setting = await _repository.GetByIdAsync(newSetting.SettingId); +var allSettings = await _repository.GetAllAsync(); +var featureFlags = await _repository.GetByNameAsync("Feature Flag"); + +// Update +setting.DefaultValue = false; +await _repository.UpdateAsync(setting); + +// Delete +await _repository.DeleteAsync(setting.SettingId); +``` + +#### 2. Complex Queries +```csharp +// Finding settings with complex conditions +var customSettings = await _repository.FindByAsync(s => + s.Name.StartsWith("Custom") && + s.DefaultValue == true && + s.DateCreated >= DateOnly.FromDateTime(DateTime.Today.AddDays(-30)) +); + +// Working with related entities +public class CategoryService +{ + private readonly IBudgetConfigDefaultSettingRepository _repository; + private readonly OnePlanDbContext _context; + + public async Task> GetSettingsForCategory(int categoryId) + { + // Using type-safe LINQ approach + return await _repository.GetByLinksAsync( + _context.CategorySettings.Where(cs => cs.CategoryId == categoryId), + link => link.SettingId + ); + } +} +``` + +#### 3. Batch Operations +```csharp +public class BulkOperationService +{ + private readonly IBudgetConfigDefaultSettingRepository _repository; + + public async Task UpdateFeatureFlags(bool newValue) + { + var featureFlags = await _repository.FindByAsync(s => + s.Name.Contains("FeatureFlag")); + + foreach (var flag in featureFlags) + { + flag.DefaultValue = newValue; + await _repository.UpdateAsync(flag); + } + } +} +``` + +#### 4. Validation and Error Handling +```csharp +public class SettingManagementService +{ + private readonly IBudgetConfigDefaultSettingRepository _repository; + + public async Task<(bool success, string message)> CreateSetting(BudgetConfigDefaultSetting setting) + { + try + { + if (!_repository.ValidateSetting(setting, out var errors)) + { + return (false, $"Validation failed: {string.Join(", ", errors)}"); + } + + var created = await _repository.CreateAsync(setting); + return (true, $"Setting created with ID: {created.SettingId}"); + } + catch (Exception ex) + { + return (false, $"Error creating setting: {ex.Message}"); + } + } +} +``` + +#### 5. Working with Links and Relationships +```csharp +public class SettingRelationshipService +{ + private readonly IBudgetConfigDefaultSettingRepository _repository; + private readonly OnePlanDbContext _context; + + // Using navigation properties + public async Task> GetLinkedSettings( + Expression> linkCondition, + Expression> navigationProperty) + where TEntity : class + { + return await _repository.GetByLinkedEntityAsync( + linkCondition, + navigationProperty + ); + } + + // Example usage + public async Task> GetDepartmentSettings(int departmentId) + { + return await GetLinkedSettings( + ds => ds.DepartmentId == departmentId, + ds => ds.Setting + ); + } +} +``` + +### Key Consumer Benefits +1. **Type Safety**: Better IDE support and compile-time error checking +2. **Performance**: Async operations and efficient query generation +3. **Maintainability**: Cleaner, more testable code through DI +4. **Flexibility**: Enhanced querying capabilities through LINQ +5. **Reliability**: Built-in connection and transaction management + +## Conclusion +The migration from Core20 to EF Core represents a significant modernization effort that will result in more maintainable, type-safe, and performant code. While consumers will need to adapt to the async/await pattern and dependency injection approach, the benefits include better tooling support, improved development experience, and more reliable data access patterns. The provided examples demonstrate how the new repository pattern provides a more robust and flexible way to interact with the data layer. \ No newline at end of file diff --git a/ef-migration/src/Strata.Code.DataAccess/Repositories/BudgetConfigDefaultSettingRepository.cs b/ef-migration/src/Strata.Code.DataAccess/Repositories/BudgetConfigDefaultSettingRepository.cs index 4301fe4..2f252d0 100644 --- a/ef-migration/src/Strata.Code.DataAccess/Repositories/BudgetConfigDefaultSettingRepository.cs +++ b/ef-migration/src/Strata.Code.DataAccess/Repositories/BudgetConfigDefaultSettingRepository.cs @@ -1,4 +1,6 @@ -using Microsoft.EntityFrameworkCore; +using System.Linq.Expressions; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; using Strata.Code.DataAccess.Data; using Strata.Code.DataAccess.Models; using Strata.Code.DataAccess.Repositories.Interfaces; @@ -17,21 +19,43 @@ namespace Strata.Code.DataAccess.Repositories public async Task> GetAllAsync() { return await _context.Set() + .OrderBy(x => x.SettingId) .ToListAsync(); } + public async Task> GetAllWithChildrenAsync() + { + // Since the original Core20 code shows no direct children, + // we keep this method for API consistency but it behaves same as GetAllAsync + return await GetAllAsync(); + } + public async Task GetByIdAsync(int id) { return await _context.Set() .FirstOrDefaultAsync(x => x.SettingId == id); } + public async Task> GetByNameAsync(string name) + { + return await _context.Set() + .Where(x => x.Name == name) + .ToListAsync(); + } + + public async Task> GetByIdsAsync(IEnumerable ids) + { + return await _context.Set() + .Where(x => ids.Contains(x.SettingId)) + .ToListAsync(); + } + public async Task CreateAsync(BudgetConfigDefaultSetting setting) { setting.DateCreated = DateOnly.FromDateTime(DateTime.UtcNow); + await _context.Set().AddAsync(setting); await _context.SaveChangesAsync(); - return setting; } @@ -41,13 +65,13 @@ namespace Strata.Code.DataAccess.Repositories if (existingSetting == null) return null; + // Update properties existingSetting.Name = setting.Name; existingSetting.DefaultValue = setting.DefaultValue; existingSetting.Description = setting.Description; - _context.Set().Update(existingSetting); + // EF Core tracks changes automatically await _context.SaveChangesAsync(); - return existingSetting; } @@ -59,8 +83,30 @@ namespace Strata.Code.DataAccess.Repositories _context.Remove(setting); await _context.SaveChangesAsync(); - return true; } + + public async Task> FindByAsync( + Expression> predicate) + { + return await _context.Set() + .Where(predicate) + .ToListAsync(); + } + + // Added validation method to match Core20's TryValidateSelf + public bool ValidateSetting(BudgetConfigDefaultSetting setting, out IList errors) + { + errors = new List(); + + if (string.IsNullOrWhiteSpace(setting.Name)) + { + errors.Add("Name is required"); + } + + // Add any additional validation rules here + + return !errors.Any(); + } } } diff --git a/ef-migration/src/Strata.Code.DataAccess/Repositories/Interfaces/IBudgetConfigDefaultSettingRepository.cs b/ef-migration/src/Strata.Code.DataAccess/Repositories/Interfaces/IBudgetConfigDefaultSettingRepository.cs index d5b4b00..2d1c5c0 100644 --- a/ef-migration/src/Strata.Code.DataAccess/Repositories/Interfaces/IBudgetConfigDefaultSettingRepository.cs +++ b/ef-migration/src/Strata.Code.DataAccess/Repositories/Interfaces/IBudgetConfigDefaultSettingRepository.cs @@ -1,13 +1,19 @@ -using Strata.Code.DataAccess.Models; +using System.Linq.Expressions; +using Strata.Code.DataAccess.Models; namespace Strata.Code.DataAccess.Repositories.Interfaces { public interface IBudgetConfigDefaultSettingRepository { Task> GetAllAsync(); + Task> GetAllWithChildrenAsync(); Task GetByIdAsync(int id); + Task> GetByNameAsync(string name); + Task> GetByIdsAsync(IEnumerable ids); Task CreateAsync(BudgetConfigDefaultSetting setting); Task UpdateAsync(BudgetConfigDefaultSetting setting); Task DeleteAsync(int id); + Task> FindByAsync(Expression> predicate); + bool ValidateSetting(BudgetConfigDefaultSetting setting, out IList errors); } } diff --git a/ef-migration/src/Strata.Code.Web/Controllers/BudgetConfigDefaultSettingController .cs b/ef-migration/src/Strata.Code.Web/Controllers/BudgetConfigDefaultSettingController .cs index 4b1e891..4f96599 100644 --- a/ef-migration/src/Strata.Code.Web/Controllers/BudgetConfigDefaultSettingController .cs +++ b/ef-migration/src/Strata.Code.Web/Controllers/BudgetConfigDefaultSettingController .cs @@ -1,5 +1,7 @@ -using Microsoft.AspNetCore.Mvc; +using System.Linq.Expressions; +using Microsoft.AspNetCore.Mvc; using Strata.Code.Business.Services.Interfaces; +using Strata.Code.DataAccess.Models; namespace Strata.Code.Web.Controllers { @@ -11,7 +13,7 @@ namespace Strata.Code.Web.Controllers public BudgetConfigDefaultSettingController(IBudgetConfigDefaultSettingService service) { - _service = service; + _service = service ?? throw new ArgumentNullException(nameof(service)); } [HttpGet] @@ -73,5 +75,40 @@ namespace Strata.Code.Web.Controllers return NoContent(); } + + [HttpGet("byname/{name}")] + [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] + public async Task GetByName(string name) + { + var settings = await _service.GetByNameAsync(name); + return Ok(settings); + } + + [HttpPost("byids")] + [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] + public async Task GetByIds([FromBody] IEnumerable ids) + { + var settings = await _service.GetByIdsAsync(ids); + return Ok(settings); + } + + [HttpPost("search")] + [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)] + public async Task FindBy([FromBody] string predicateExpression) + { + // Note: In a real implementation, you'd want to create a more structured search model + // This is just an example of how you might expose the FindBy functionality + var predicate = BuildPredicate(predicateExpression); + var settings = await _service.FindByAsync(predicate); + return Ok(settings); + } + + private Expression> BuildPredicate(string expression) + { + // This is a simplified example - in practice, you'd want to implement + // a more robust expression parser or use a different approach for searching + return setting => setting.Name.Contains(expression) || + setting.Description.Contains(expression); + } } } -- 2.45.2 From 5b6d15248e67708cc739901750d0eba53375b2bb Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Thu, 6 Feb 2025 14:07:06 -0500 Subject: [PATCH 30/31] Include new promtps for migration --- .../src/Strata.Code.DataAccess/ReadMe.MD | 133 +++++++++++++++++- 1 file changed, 132 insertions(+), 1 deletion(-) diff --git a/ef-migration/src/Strata.Code.DataAccess/ReadMe.MD b/ef-migration/src/Strata.Code.DataAccess/ReadMe.MD index 0ab8c26..777720c 100644 --- a/ef-migration/src/Strata.Code.DataAccess/ReadMe.MD +++ b/ef-migration/src/Strata.Code.DataAccess/ReadMe.MD @@ -376,5 +376,136 @@ public class SettingRelationshipService 4. **Flexibility**: Enhanced querying capabilities through LINQ 5. **Reliability**: Built-in connection and transaction management +## AI Assistance for Migration + +### Using Claude for Migration Support + +Claude can significantly accelerate the migration process through intelligent code analysis and transformation. Here are effective prompting strategies: + +#### Example 1: Initial Analysis Prompt +``` +I need to migrate a Core20 ORM implementation to EF Core 8.0. Here are my source files: + +[Paste your Core20 files here] + +Please: +1. Analyze the current implementation +2. Identify key patterns and functionality +3. Propose an EF Core equivalent structure +4. Provide a sample implementation for one entity +5. List potential challenges and their solutions +``` + +#### Example 2: Detailed Implementation Prompt +``` +Please help me implement the EF Core repository for this entity: + +[Paste your entity class] + +Requirements: +1. Maintain existing functionality +2. Use async/await pattern +3. Implement proper dependency injection +4. Include repository interface +5. Show example service layer integration +``` + +### Using GitHub Copilot + +1. **Repository Migration** + ```csharp + // Copilot prompt in comments: + // Convert this Core20 repository to EF Core 8.0: + // [Paste original repository code] + + public class MyEntityRepository + { + // Let Copilot suggest the implementation + } + ``` + +2. **Entity Configuration** + ```csharp + // Copilot prompt in comments: + // Create EF Core fluent configuration for this entity: + // [Paste entity properties] + + public class MyEntityConfiguration : IEntityTypeConfiguration + { + // Let Copilot suggest the configuration + } + ``` + +### Best Practices for AI-Assisted Migration + +1. **Preparation** + - Document all existing functionality + - Identify critical patterns + - Create test cases before migration + +2. **Prompting Strategy** + - Start with high-level architecture + - Break down into specific components + - Include context and constraints + - Request examples for complex patterns + +3. **Validation Process** + - Review AI-generated code thoroughly + - Test against existing functionality + - Verify performance characteristics + - Check security implications + +4. **Iterative Improvement** + ``` + Prompt Template: + "The current implementation of [feature] in EF Core needs improvement. + Current code: + [paste code] + + Required improvements: + 1. [specific improvement] + 2. [specific improvement] + + Please provide an optimized version maintaining these constraints: [list constraints]" + ``` + +### AI Tools Comparison for Migration Tasks + +| Task | Claude | GitHub Copilot | Best Practice | +|------|---------|---------------|---------------| +| Architecture Analysis | Excellent | Limited | Use Claude for initial analysis | +| Code Conversion | Good | Excellent | Use Copilot with Claude's guidance | +| Pattern Recognition | Excellent | Good | Start with Claude, refine with Copilot | +| Documentation | Excellent | Limited | Use Claude for docs generation | +| Edge Cases | Good | Limited | Use Claude to identify, Copilot to implement | + +### Velocity Optimization Tips + +1. **Parallel Processing** + - Use AI to generate multiple implementations + - Human review focuses on architecture and edge cases + - AI handles repetitive conversions + +2. **Template Generation** + ``` + Prompt Template for New Entities: + "Convert this Core20 entity to EF Core: + [entity code] + + Include: + 1. Entity configuration + 2. Repository implementation + 3. Service layer + 4. Required interfaces + 5. Example usage" + ``` + +3. **Quality Assurance** + - Use AI to generate test cases + - Automated validation of patterns + - Performance benchmark comparisons + ## Conclusion -The migration from Core20 to EF Core represents a significant modernization effort that will result in more maintainable, type-safe, and performant code. While consumers will need to adapt to the async/await pattern and dependency injection approach, the benefits include better tooling support, improved development experience, and more reliable data access patterns. The provided examples demonstrate how the new repository pattern provides a more robust and flexible way to interact with the data layer. \ No newline at end of file +The migration from Core20 to EF Core represents a significant modernization effort that will result in more maintainable, type-safe, and performant code. While consumers will need to adapt to the async/await pattern and dependency injection approach, the benefits include better tooling support, improved development experience, and more reliable data access patterns. The provided examples demonstrate how the new repository pattern provides a more robust and flexible way to interact with the data layer. + +By leveraging AI tools effectively, the migration process can be significantly accelerated while maintaining high quality standards. The key is to use each tool's strengths appropriately and maintain a consistent validation process throughout the migration. \ No newline at end of file -- 2.45.2 From a23898a70be27e4c42c75de7a292fe3e99ecad53 Mon Sep 17 00:00:00 2001 From: Jorge Burgos Date: Thu, 6 Feb 2025 14:17:15 -0500 Subject: [PATCH 31/31] Improve documentation --- .../src/Strata.Code.DataAccess/ReadMe.MD | 314 ++++-------------- 1 file changed, 60 insertions(+), 254 deletions(-) diff --git a/ef-migration/src/Strata.Code.DataAccess/ReadMe.MD b/ef-migration/src/Strata.Code.DataAccess/ReadMe.MD index 777720c..10cb665 100644 --- a/ef-migration/src/Strata.Code.DataAccess/ReadMe.MD +++ b/ef-migration/src/Strata.Code.DataAccess/ReadMe.MD @@ -191,202 +191,21 @@ var linkedSettings = await _repository.GetByLinksAsync( - AutoMapper - FluentValidation -## Timeline Estimation - -| Phase | Duration | Description | -|-------|----------|-------------| -| Planning | 1-2 weeks | Analysis, strategy, tooling setup | -| Basic Migration | 2-4 weeks | Entity and schema migration | -| Query Migration | 4-6 weeks | Converting complex queries | -| Testing | 2-3 weeks | Integration and performance testing | -| Deployment | 1-2 weeks | Staging and production deployment | - -## Consumer Impact Analysis - -### Changes in Consumer Code - -#### Dependency Injection (DI) -```csharp -// Core20 - Static access -var setting = BudgetConfigDefaultSetting.LoadBySettingID(123); - -// EF Core - DI approach -public class ConsumerService -{ - private readonly IBudgetConfigDefaultSettingRepository _repository; - - public ConsumerService(IBudgetConfigDefaultSettingRepository repository) - { - _repository = repository; - } - - public async Task GetSetting(int id) - { - return await _repository.GetByIdAsync(id); - } -} -``` - -#### Async/Await Pattern -```csharp -// Core20 - Synchronous -var settings = BudgetConfigDefaultSetting.LoadAll(); -settings.First().Name = "New Name"; -settings.First().Save(); - -// EF Core - Async -var settings = await _repository.GetAllAsync(); -var setting = settings.First(); -setting.Name = "New Name"; -await _repository.UpdateAsync(setting); -``` - -### Comprehensive Usage Examples - -#### 1. Basic CRUD Operations -```csharp -// Create -var newSetting = new BudgetConfigDefaultSetting -{ - Name = "New Feature Flag", - Description = "Controls new feature availability", - DefaultValue = true -}; -await _repository.CreateAsync(newSetting); - -// Read -var setting = await _repository.GetByIdAsync(newSetting.SettingId); -var allSettings = await _repository.GetAllAsync(); -var featureFlags = await _repository.GetByNameAsync("Feature Flag"); - -// Update -setting.DefaultValue = false; -await _repository.UpdateAsync(setting); - -// Delete -await _repository.DeleteAsync(setting.SettingId); -``` - -#### 2. Complex Queries -```csharp -// Finding settings with complex conditions -var customSettings = await _repository.FindByAsync(s => - s.Name.StartsWith("Custom") && - s.DefaultValue == true && - s.DateCreated >= DateOnly.FromDateTime(DateTime.Today.AddDays(-30)) -); - -// Working with related entities -public class CategoryService -{ - private readonly IBudgetConfigDefaultSettingRepository _repository; - private readonly OnePlanDbContext _context; - - public async Task> GetSettingsForCategory(int categoryId) - { - // Using type-safe LINQ approach - return await _repository.GetByLinksAsync( - _context.CategorySettings.Where(cs => cs.CategoryId == categoryId), - link => link.SettingId - ); - } -} -``` - -#### 3. Batch Operations -```csharp -public class BulkOperationService -{ - private readonly IBudgetConfigDefaultSettingRepository _repository; - - public async Task UpdateFeatureFlags(bool newValue) - { - var featureFlags = await _repository.FindByAsync(s => - s.Name.Contains("FeatureFlag")); - - foreach (var flag in featureFlags) - { - flag.DefaultValue = newValue; - await _repository.UpdateAsync(flag); - } - } -} -``` - -#### 4. Validation and Error Handling -```csharp -public class SettingManagementService -{ - private readonly IBudgetConfigDefaultSettingRepository _repository; - - public async Task<(bool success, string message)> CreateSetting(BudgetConfigDefaultSetting setting) - { - try - { - if (!_repository.ValidateSetting(setting, out var errors)) - { - return (false, $"Validation failed: {string.Join(", ", errors)}"); - } - - var created = await _repository.CreateAsync(setting); - return (true, $"Setting created with ID: {created.SettingId}"); - } - catch (Exception ex) - { - return (false, $"Error creating setting: {ex.Message}"); - } - } -} -``` - -#### 5. Working with Links and Relationships -```csharp -public class SettingRelationshipService -{ - private readonly IBudgetConfigDefaultSettingRepository _repository; - private readonly OnePlanDbContext _context; - - // Using navigation properties - public async Task> GetLinkedSettings( - Expression> linkCondition, - Expression> navigationProperty) - where TEntity : class - { - return await _repository.GetByLinkedEntityAsync( - linkCondition, - navigationProperty - ); - } - - // Example usage - public async Task> GetDepartmentSettings(int departmentId) - { - return await GetLinkedSettings( - ds => ds.DepartmentId == departmentId, - ds => ds.Setting - ); - } -} -``` - -### Key Consumer Benefits -1. **Type Safety**: Better IDE support and compile-time error checking -2. **Performance**: Async operations and efficient query generation -3. **Maintainability**: Cleaner, more testable code through DI -4. **Flexibility**: Enhanced querying capabilities through LINQ -5. **Reliability**: Built-in connection and transaction management - ## AI Assistance for Migration -### Using Claude for Migration Support +### Using AI Tools for Migration Support -Claude can significantly accelerate the migration process through intelligent code analysis and transformation. Here are effective prompting strategies: +The migration process can be significantly accelerated using Claude and WindSurf. Here's how to effectively leverage these tools: + +### Using Claude for Architecture and Analysis + +Claude excels at high-level analysis and providing detailed implementation guidance. Here are effective prompting strategies: #### Example 1: Initial Analysis Prompt ``` I need to migrate a Core20 ORM implementation to EF Core 8.0. Here are my source files: -[Paste your Core20 files here] +[Paste your Core20 files] Please: 1. Analyze the current implementation @@ -410,30 +229,22 @@ Requirements: 5. Show example service layer integration ``` -### Using GitHub Copilot +### Using WindSurf for Code Generation + +WindSurf is particularly effective for handling specific code generation tasks. Here's how to use it effectively: 1. **Repository Migration** ```csharp - // Copilot prompt in comments: - // Convert this Core20 repository to EF Core 8.0: - // [Paste original repository code] - - public class MyEntityRepository - { - // Let Copilot suggest the implementation - } + // WindSurf prompt: + // Generate EF Core repository for this Core20 entity: + // [Insert entity details] ``` 2. **Entity Configuration** ```csharp - // Copilot prompt in comments: - // Create EF Core fluent configuration for this entity: - // [Paste entity properties] - - public class MyEntityConfiguration : IEntityTypeConfiguration - { - // Let Copilot suggest the configuration - } + // WindSurf prompt: + // Create EF Core entity configuration class for: + // [Insert schema details] ``` ### Best Practices for AI-Assisted Migration @@ -444,10 +255,16 @@ Requirements: - Create test cases before migration 2. **Prompting Strategy** - - Start with high-level architecture - - Break down into specific components - - Include context and constraints - - Request examples for complex patterns + - Use Claude for: + * Architecture decisions + * Pattern analysis + * Complex transformations + * Documentation generation + - Use WindSurf for: + * Code generation + * Schema translations + * LINQ query conversions + * Repetitive transformations 3. **Validation Process** - Review AI-generated code thoroughly @@ -455,57 +272,46 @@ Requirements: - Verify performance characteristics - Check security implications -4. **Iterative Improvement** - ``` - Prompt Template: - "The current implementation of [feature] in EF Core needs improvement. - Current code: - [paste code] - - Required improvements: - 1. [specific improvement] - 2. [specific improvement] - - Please provide an optimized version maintaining these constraints: [list constraints]" - ``` - ### AI Tools Comparison for Migration Tasks -| Task | Claude | GitHub Copilot | Best Practice | +| Task | Claude | WindSurf | Best Practice | |------|---------|---------------|---------------| -| Architecture Analysis | Excellent | Limited | Use Claude for initial analysis | -| Code Conversion | Good | Excellent | Use Copilot with Claude's guidance | -| Pattern Recognition | Excellent | Good | Start with Claude, refine with Copilot | -| Documentation | Excellent | Limited | Use Claude for docs generation | -| Edge Cases | Good | Limited | Use Claude to identify, Copilot to implement | +| Architecture Analysis | Excellent | Limited | Use Claude | +| Code Generation | Good | Excellent | Use WindSurf with Claude's guidance | +| Pattern Recognition | Excellent | Good | Start with Claude, implement with WindSurf | +| Documentation | Excellent | Limited | Use Claude | +| Edge Cases | Good | Good | Use both tools complementarily | -### Velocity Optimization Tips +### Tool-Specific Best Practices -1. **Parallel Processing** - - Use AI to generate multiple implementations - - Human review focuses on architecture and edge cases - - AI handles repetitive conversions +#### Claude +- Provide complete context +- Ask for step-by-step explanations +- Request multiple approaches +- Use for architectural decisions -2. **Template Generation** - ``` - Prompt Template for New Entities: - "Convert this Core20 entity to EF Core: - [entity code] - - Include: - 1. Entity configuration - 2. Repository implementation - 3. Service layer - 4. Required interfaces - 5. Example usage" - ``` +#### WindSurf +- Focus on specific code generation tasks +- Use for repetitive transformations +- Leverage for LINQ query conversions +- Apply to schema migrations -3. **Quality Assurance** - - Use AI to generate test cases - - Automated validation of patterns - - Performance benchmark comparisons +### Recommended Workflow + +1. **Analysis Phase (Claude)** + - System architecture review + - Pattern identification + - Migration strategy development + +2. **Implementation Phase (WindSurf)** + - Code generation + - Entity configurations + - Repository implementations + +3. **Validation Phase (Both)** + - Code review + - Test case execution + - Performance validation ## Conclusion -The migration from Core20 to EF Core represents a significant modernization effort that will result in more maintainable, type-safe, and performant code. While consumers will need to adapt to the async/await pattern and dependency injection approach, the benefits include better tooling support, improved development experience, and more reliable data access patterns. The provided examples demonstrate how the new repository pattern provides a more robust and flexible way to interact with the data layer. - -By leveraging AI tools effectively, the migration process can be significantly accelerated while maintaining high quality standards. The key is to use each tool's strengths appropriately and maintain a consistent validation process throughout the migration. \ No newline at end of file +The migration from Core20 to EF Core represents a significant modernization effort that will result in more maintainable, type-safe, and performant code. By leveraging Claude for strategic planning and WindSurf for implementation, teams can significantly accelerate the migration process while maintaining high quality standards. The key is to use each tool's strengths appropriately and maintain a consistent validation process throughout the migration. \ No newline at end of file -- 2.45.2